Assurance case¶
SECURITY states what a user can and cannot expect of btclib-node in terms of security. This page argues why those expectations hold: the threat model, the trust boundaries, how secure design principles are applied, and how common implementation weaknesses are countered. Each argument below names the file, the test or the workflow that supports it; where SECURITY.md already states a fact, this page points at it instead of repeating it. The components named here are the ones ARCHITECTURE describes.
What is claimed¶
A block, a transaction, a script and an address this node accepts or builds agree with Bitcoin Core.
.github/workflows/integration-bitcoind.ymlruns a disposable regtestbitcoindagainst a fresh node over p2p, andtests/integration/bitcoind_test.pychecks the tip after a sync of blocks Core mined.tests/integration/reorg_test.pychecks that a chain split follows Core off an abandoned branch,tests/integration/compact_blocks_test.pythat Core takes acmpctblockthis node built, andtests/integration/backpressure_test.pythat the receive bound below engages against a real daemon serving blocks faster than this node validates them. No integration test offers Core a block, a transaction or an address it rejects, so what this node refuses rests on the tests and the vendored vectors undertests/,tests/_data/README.mdnaming where each came from, and not on a run against Core.Octets from a peer or a caller either parse into what they claim to be or are refused, and nothing else.
tests/property_test.py’s own property — “over unconstrained octets, a declared entry point either returns or raisesBTClibException, and nothing else” — is checked by Hypothesis over the domain it describes, forframe_message_bytesandparse_request_head, and extended by the atheris harnesses underfuzz/..github/workflows/fuzz.ymlruns them weekly as ordinary scripts, not under ClusterFuzzLite, from the committed seeds and with no corpus kept between runs.fuzz_process_message.pyreaches the handlers ofp2p/callbacks.pythrough aNode, which the property test leaves out. Nothing here fuzzes thejson.loadsof an RPC body.What one connection may cost this node, and how many inbound connections it holds, are bounded. A peer whose send buffer passes
-maxsendbufferhas nothing more read from it until the buffer drains, as in Core, and one that stops reading is dropped by the ping timeout; the comment besideConnection.send_buffer_max_size(src/btclib_node/p2p/connection.py) argues what the two leave it able to cost, closed as btclib-org/btclib-node#1805. PastConfig.max_connections’s inbound share,P2pManager.serverevicts an inbound peer by Core’s own rules and closes the new one, before building anything for it, only where every peer held is protected. A peer from a host this node has discouraged is closed where it would take the last inbound slot or none is left, unless-whitelistgrants itnoban, and is otherwise preferred for eviction, as in Core (src/btclib_node/p2p/manager.py,src/btclib_node/p2p/eviction.py), closed as btclib-org/btclib-node#1054, btclib-org/btclib-node#1064 and btclib-org/btclib-node#1078.Inbound connections do not stop this node dialling. The outbound dial target counts only the connections
P2pManagerdialled off its own draw, not inbound or-connect/-addnodeones (src/btclib_node/p2p/manager.py), closed as btclib-org/btclib-node#1065.A published distribution is what this tree built. SECURITY.md’s Supported versions states how that is verified.
What is not claimed.
Development Status :: 3 - Alpha(pyproject.toml) is the claim this node makes about itself: it has downloaded and validated a chain, which SECURITY.md’s own closing line says is not the same as having been run against somebody trying to make it do otherwise. Production consensus-safety is not asserted anywhere in this tree.
Threat model¶
btclib-node is an application, not a library: it opens sockets of its
own, on both surfaces ARCHITECTURE.md’s The protocol and the RPC
surface describes, and it writes to a datadir on disk. The command
below lists the top-level name of every module src/ imports, at any
depth and in any spelling of the statement — bitcoin_core_rpc,
btclib_wallet and rocksdict beside btclib itself, and otherwise the
standard library.
python3 - <<'EOF'
import ast, pathlib
names = set()
for p in pathlib.Path("src").rglob("*.py"):
for n in ast.walk(ast.parse(p.read_text(encoding="utf-8"))):
if isinstance(n, ast.Import):
names.update(a.name.split(".")[0] for a in n.names)
elif isinstance(n, ast.ImportFrom) and n.level == 0:
names.add(n.module.split(".")[0])
print(sorted(names))
EOF
bitcoin_core_rpc is a required dependency, and src/ imports only
RPCErrorCode and chain_from_network from it — its error-code and
chain vocabulary, eagerly loaded by the package’s own __init__ — never
BitcoinCoreRpcClient or a transport, which the package loads lazily
and only tests/ (never shipped) asks for. asyncio and socket are
what P2pManager and RpcManager open their listeners and connections
through; rocksdict is the store; multiprocessing is Node.worker_pool
under a GIL interpreter.
btclib_wallet is a required dependency: rpc/callbacks.py and
rpc/utxo_set.py take infer_descriptor from its descriptors to write
a script’s descriptor, and rpc/utxo_set.py parses with its parse the
descriptors a scantxoutset caller sends, so what it returns reaches a
caller’s answer.
ctypes is imported by p2p/netif.py alone, which loads the C library
with CDLL(None), calls getifaddrs and reads the ifaddrs memory it
returns, the standard library having no binding of it. On Windows it loads
iphlpapi, calls GetAdaptersAddresses and reads the memory it fills. That
is a trust item: the C library, iphlpapi and the layouts _IfAddrs,
_Adapter and _UnicastAddress declare are trusted without a check, and
what is read is this machine’s own interface table, never a peer’s.
subprocess runs an operator’s -*notify command through the shell
(notify.py).
What is defended.
The correctness of every verdict this node reaches over a peer’s or a caller’s input: a block or a transaction accepted that Core would reject, a valid one refused, or an answer that disagrees with what the chain state on disk actually holds.
This process, against octets built to make a parser raise an exception this tree does not document, or allocate without bound.
The chain state on disk, against a bit flipped by the medium under it, and against being read from a second process while a
Nodealready has it open.The user’s control over what serves the RPC port and to whom:
-rpcbinddecides who can reach it,-rpcallowipwhich sources it answers, the credentials it accepts who it answers, and-rpcwhitelistwhich methods each of them may call.The content of peer-to-peer traffic, against an observer on the path, under BIP324’s v2 transport, which this node requires except where SECURITY.md’s Where this node departs from Bitcoin Core says otherwise.
The adversaries.
A remote peer, over p2p: a handshake, a block, a transaction, an address, a filter request, or any other message this node’s protocol handlers read.
Whoever can reach the RPC port: a request’s credential is checked before its body is decoded, and a caller without an accepted one gets a closed connection for a request the listener does not read whole; for one it does, a 501, a 405 or a 404 for a method or a path it refuses, as from
bitcoind, and otherwise a 401.A party on the path of a p2p connection, reading or rewriting its traffic.
A party tampering with the medium the datadir sits on, or opening the same datadir from a second process.
A party tampering with a distribution between this tree and the user.
What is not defended, each stated in SECURITY.md’s Limitations, not vulnerabilities:
the JSON-RPC listener, against a caller holding an accepted credential, who may call every method
-rpcwhitelistleaves it, and against whoever can read the plain HTTP it is sent overa p2p peer’s identity, against a party in the middle of a v2 handshake: BIP324 does not authenticate it
the timing and sizes of p2p packets, against an observer on the path
anything SECURITY.md attributes to btclib rather than to this tree — the constant-time properties of the arithmetic btclib’s own assurance case states, since btclib-node holds no long-lived private key, and calls btclib for verification and, for a v2 connection’s ephemeral key, the key exchange and key derivation, never for signing
Nor is the interpreter, the operating system, or the RocksDB build this node runs on: an application shares its process with all three and has no defence against them.
Trust boundaries¶
The caller and the RPC surface. src/btclib_node/rpc/ is where a
local caller’s request crosses in. RpcConnection bounds what it will
read before decoding anything — MAX_HEADER_BYTES and MAX_BODY_BYTES
in rpc/connection.py — and a body json.loads cannot parse answers
bitcoind’s own PARSE_ERROR rather than closing the socket with
nothing said. Before that decoding, RpcConnection.run checks the
request’s credential against rpc/auth.py’s RpcAuth and answers one
it does not accept with a 401, so no handler sees a request from a
caller without an accepted credential; once the body is decoded,
RpcAuth.refusal answers a method -rpcwhitelist does not allow that
caller with a 403. rpc/callbacks.py’s own module docstring states the
rest of the boundary: a caller no whitelist names may call every
handler, unless -rpcwhitelistdefault holds, which it does by default
once any -rpcwhitelist is set.
btclib-node and btclib. Every object on the wire and every
consensus rule crosses this boundary rather than being reimplemented:
src/btclib_node/interpreter.py calls btclib.script.engine.verify_transaction
and verify_input, dispatched across Node.worker_pool, and trusts
btclib’s own verdict the way ARCHITECTURE.md’s Validation describes.
A flaw in the arithmetic or the parsing on the far side of this boundary
is btclib’s to fix, and SECURITY.md’s What belongs here, and what
belongs upstream says where each kind of defect is reported.
Octets from the network. src/btclib_node/p2p/transport.py and
src/btclib_node/p2p/connection.py are where a peer’s own bytes cross
in, ahead of btclib’s wire codec: V1Transport reads a header’s own
length field before taking anything from it, bounds it by
MAX_PROTOCOL_MESSAGE_LENGTH and checks the magic against the chain this
node runs. V2Transport (p2p/v2transport.py) refuses a handshake whose
garbage is longer than MAX_GARBAGE_LEN, 4095 bytes, before its
terminator, a packet whose length field exceeds a message’s largest
contents before it decrypts the contents, and a packet that does not
authenticate. The connection bounds what it will buffer in either
direction — recv_flood_size (-maxreceivebuffer) on what may sit
unprocessed, send_buffer_max_size (-maxsendbuffer) on what this node
may owe a peer before it reads nothing more from it — with getdata and
getcfilters answers checked against that last bound before every item,
the comment beside it arguing what bounds the rest. What crosses this
boundary already framed is handed to btclib’s own Message.parse for the
codec itself.
The store. src/btclib_node/db.py is what every index opens its
datadir through, and it is the one place a bit flipped on disk is
caught: every record carries its own checksum, verified on every read,
which is RocksDB’s own design and not a scheme built by hand
(db.py’s own docstring argues it against Bitcoin Core’s LevelDB in
full). A corrupted key or value is a StoreCorruptionError, never a
silently wrong answer, and a second process opening the same datadir is
refused by RocksDB’s own directory LOCK rather than let in the way a
WAL-backed store would let a second reader in.
The environment and the files. -datadir, -conf and every other
CLI flag cli.py reads, and bitcoin.conf inside the datadir it names,
are the operator’s own input, not a remote party’s — cli.py’s own
module docstring is where each flag is named against Bitcoin Core’s
equivalent. The datadir holds the stores, banlist.json, anchors.dat,
fee_estimates.dat, the log file and the RPC cookie .cookie;
-blocksdir moves the block files, -rpccookiefile the cookie, and
-conf and -includeconf name the files read for options. Beside these,
dirlock.py creates a .lock
file in the datadir and in the blocks directory, rpc/auth.py writes the
cookie through a .tmp file beside it, and p2p/anchors.py writes
anchors.dat through a temporary file beside it. Nothing under src/
opens a file outside those.
PYTEST_XDIST_WORKER_COUNT is read in any process, not only under
pytest: _default_worker_count in src/btclib_node/__init__.py sizes
Node.worker_pool from it, and takes eight where it is not a positive
integer.
Bitcoin Core, as an oracle rather than a dependency.
.github/workflows/integration-bitcoind.yml is the one place this
node’s own answers are checked against a bitcoind it does not talk to
in any other job. Blocks are checked over p2p, matching what a real peer
would see, and rpc_framing_test.py, banlist_test.py,
getpeerinfo_test.py and rawtx_test.py compare RPC answers.
Secure design principles¶
Saltzer and Schroeder’s principles, over the layering ARCHITECTURE.md describes.
Economy of mechanism. One class is where every index’s storage is decided (
db.py), one dispatch is where a fork of validation work is fanned out (Node.worker_pool, chosen by one predicate,_pool_factory), and one exception hierarchy groups a failure by what actually went wrong rather than by which module raises it (exceptions.py’s own docstring argues the grouping).Fail-safe defaults. The RPC listener binds loopback by default, and
-rpcbinddoes not widen it without-rpcallowip, as in Core (btclib-org/btclib-node#1268). A second process cannot silently share a datadir already open: RocksDB’s ownLOCKrefuses it rather than allowing concurrent, uncoordinated writers._step_chainstops: an exception fromdownload_manager.step()orupdate_chainis logged,runleaves its loop, and the node closes its stores and ends, as Core’sFatalErrorends its own (src/btclib_node/main.py’s comment above_CONTENT_FAILUREargues the split). A block’s own content failing is not one: the fork is rejected and the node goes on. An exception peer data could provoke there would therefore stop the node.Complete mediation. A p2p message is bounded and its magic checked before it is parsed at all, never after; an RPC body is bounded before
json.loadsever sees it._drain_message_queues(src/btclib_node/__init__.py) wraps a pass over the handlers in onetry/except Exception, so a handler that raises on input none expected is logged and the next pass runs.Open design. The code, the fuzz corpus and harnesses, and the limitations are published; SECURITY.md states what is known rather than leaving it to be found again.
Least privilege.
src/loads no RPC client of its own and no transport, the census under Threat model shows. The only sockets this process opens are the p2p and RPC listeners and the outbound peer connectionsP2pManager.connectmakes. Names are resolved bygetaddrinfo, for the DNS seeds (p2p/address.py), for-connectand-addnodehosts (p2p/manager.py) and for-rpcbindhosts (rpc/manager.py). The only files it opens are the ones The environment and the files names.Psychological acceptability. A malformed RPC request answers the HTTP status and the error
bitcoindanswers it with rather than closing the socket with nothing said, so a caller can tell its own mistake from this node refusing the call outright.Layering. ARCHITECTURE.md’s own sections are this: the loop does not parse wire objects itself, the protocol and RPC surfaces do not validate consensus rules themselves, and validation does not open a socket or a file itself.
Which thread reaches a piece of state decides whether it needs a
lock, not which callback names it. ARCHITECTURE.md’s The protocol and
the RPC surface is the argument in full: Mempool is reached from one
thread only and carries no lock, and PeerDB is reached from two and
carries two, taken separately and never nested, and a third, taken first,
that a move between its tables holds throughout. A change that moves a
callback across that boundary without re-reading this argument is what
REVIEWING.md asks a reviewer to check for.
Common implementation weaknesses¶
Weaknesses from MITRE’s CWE list that a node of this kind is exposed to, and what counters each.
Improper input validation (CWE-20). The trust boundaries above, and the harnesses under
fuzz/:fuzz_framing.pyfor this tree’s own framing arithmetic ahead of btclib’s wire codec,fuzz_rpc_head.pyfor the HTTP header arithmetic ahead ofjson.loads, andfuzz_process_message.pyforp2p/callbacks.py’s own handlers.Race conditions on shared state (CWE-362). Countered by construction rather than by a runtime check in most of this tree: ARCHITECTURE.md’s The protocol and the RPC surface is the argument for which state needs a lock, and
PeerDB’s own locks, two taken separately and a third, taken first, held across a move, are the argued example. Other state carries a lock of its own, whichgrep -rn 'threading\.R\?Lock()' srclists.Uncaught exceptions on hostile input (CWE-248, CWE-755).
tests/property_test.py’s property, over the harnesses’ own declared entry points: unconstrained octets either parse into what they claim to be or raiseBTClibException, and nothing else.tests/fuzz_corpus_test.pychecks that every corpus seed still parses. InsideNode’s own loop,_drain_message_queuescatches what a handler raises and logs it, and the loop goes on;_step_chaincatches and logs it too, and then stops the node (Fail-safe defaults above).Uncontrolled resource consumption (CWE-400, CWE-770).
MAX_HEADER_BYTES/MAX_BODY_BYTESon the RPC surface,MAX_PROTOCOL_MESSAGE_LENGTH,-maxreceivebufferand-maxsendbufferand the pacing beside them on the p2p surface. SECURITY.md’s Limitations states what is bounded and what is not yet.Weak randomness (CWE-330, CWE-338).
ruff’s flake8-bandit family, selected whole inpyproject.toml, flags a call to arandomfunction undersrc/(S311), not the import.download.py’s own trickle-relay schedule draws fromrandom.SystemRandom, andp2p/callbacks.py’s address-sampling jitter fromsecrets.SystemRandom, rather than the default generator precisely because each is a choice a peer is meant not to be able to predict.p2p/connection.py’s handshake and keep-alive nonces draw fromsecretsdirectly.Improper verification of a signature or a chain (CWE-347). Checked against Bitcoin Core, not merely against this tree’s own suite, within the limits What is claimed above gives the regtest oracle, and by the vendored vectors
.github/workflows/vendored-vectors.ymlcompares with upstream on a schedule.Deserialization of untrusted data (CWE-502).
json.loadson an RPC body is the only deserializer of untrusted datasrc/calls directly, and it is the standard library’s own, bounded ahead of the call byMAX_BODY_BYTES; a p2p message is parsed by btclib rather than unpickled or unmarshalled.rocksdictpickles a value by default, whichdb.pyavoids withraw_mode=Trueon everyOptionsandWriteBatch, so no stored value is unpickled. The census under Threat model lists neitherpicklenormarshalnorshelve..github/workflows/codeql.ymlanalyses the code and the workflows.Exposure of sensitive information (CWE-209). The rule is section 7’s A refusal carries no secret in btclib-org/.github’s README.md.
tests/secret_free/__init__.py’sassert_secret_freeis the helper the rule’s tests call. A configuration line that fails to parse, a refused command-line argument, an unknown configuration key, and a section name in its warning and in the configuration log are quoted up to the first sensitive option’s name and the first=, and only where that is at most 16 characters, a longer one being given by its length (cli.py’s_quoted_line). A malformed RPC header field is named by its index and its length (rpc/connection.py’s_FieldReader), and the reprs ofRequestHeadand_Settingsleave out the fields that hold a credential.tests/unit/cli_test.py’stest_parse_parameters_leaves_a_value_out_of_a_refusal,test_parse_conf_text_leaves_a_value_out_of_a_refusal,test_an_unrecognized_section_is_warned_about_by_its_name_aloneandtest_log_args_quotes_a_section_by_its_name_alone, andtests/unit/rpc/connection_test.py’stest_a_malformed_header_is_named_by_index_not_by_its_text, call it on those refusals, warnings and log lines. This tree does not keep the rule yet:_log_argswrites eachsettings.jsonvalue as read, a sensitive option’s included, and btclib-org/btclib-node#1967 owes the fix with its test._log_argsand_init_settings_file’s warning write eachsettings.jsonname whole, and btclib-org/btclib-node#1986 owes the fix with its test.Type confusion (CWE-843). mypy runs with
strict = true(pyproject.toml) over this tree and its suite, as a hook of the lint gate in.pre-commit-config.yaml.Code that is wrong and still passes. Line and branch coverage is held at 100% by
fail_underinpyproject.toml, and.github/mutation/interpreter.toml, run by.github/workflows/mutation.yml, asks whether the suite notices a wrong line insidesrc/btclib_node/interpreter.py, the consensus entry point ARCHITECTURE.md’s Validation names. Each weekly run executes every mutant of that file, and ofp2p/headers_sync.pythroughheaders_sync.toml; a survivor is a test to write or an equivalent mutantinterpreter.tomlexplains.Supply chain. SECURITY.md’s Supported versions describes the attestations.
uv.lockpins every dependency of an install from the checkout, and the suite and the lint gate install with--locked(CONTRIBUTING.md’s own commands). The smoke test intest.yml’sdistjob installs the wheel unpinned, deliberately; on a release that job runs after the build job, on the files that job signed, and publishes nothing. A release ships floors, not pins, sopip install btclib-nodegets the newest version each floor admits.deps-latest.ymlanddeps-oldest.ymlresolve fresh, deliberately, so a break in what the lock hides is caught on a schedule rather than never. Every third-party action is pinned to a commit sha;actionlint,zizmoranddetect-secretsrun as hooks in.pre-commit-config.yaml.