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.yml runs a disposable regtest bitcoind against a fresh node over p2p, and tests/integration/bitcoind_test.py checks the tip after a sync of blocks Core mined. tests/integration/reorg_test.py checks that a chain split follows Core off an abandoned branch, tests/integration/compact_blocks_test.py that Core takes a cmpctblock this node built, and tests/integration/backpressure_test.py that 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 under tests/, tests/_data/README.md naming 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 raises BTClibException, and nothing else” — is checked by Hypothesis over the domain it describes, for frame_message_bytes and parse_request_head, and extended by the atheris harnesses under fuzz/. .github/workflows/fuzz.yml runs them weekly as ordinary scripts, not under ClusterFuzzLite, from the committed seeds and with no corpus kept between runs. fuzz_process_message.py reaches the handlers of p2p/callbacks.py through a Node, which the property test leaves out. Nothing here fuzzes the json.loads of 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 -maxsendbuffer has 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 beside Connection.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. Past Config.max_connections’s inbound share, P2pManager.server evicts 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 -whitelist grants it noban, 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 P2pManager dialled off its own draw, not inbound or -connect/-addnode ones (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 Node already has it open.

  • The user’s control over what serves the RPC port and to whom: -rpcbind decides who can reach it, -rpcallowip which sources it answers, the credentials it accepts who it answers, and -rpcwhitelist which 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 -rpcwhitelist leaves it, and against whoever can read the plain HTTP it is sent over

  • a 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 -rpcbind does 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 own LOCK refuses it rather than allowing concurrent, uncoordinated writers. _step_chain stops: an exception from download_manager.step() or update_chain is logged, run leaves its loop, and the node closes its stores and ends, as Core’s FatalError ends its own (src/btclib_node/main.py’s comment above _CONTENT_FAILURE argues 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.loads ever sees it. _drain_message_queues (src/btclib_node/__init__.py) wraps a pass over the handlers in one try/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 connections P2pManager.connect makes. Names are resolved by getaddrinfo, for the DNS seeds (p2p/address.py), for -connect and -addnode hosts (p2p/manager.py) and for -rpcbind hosts (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 bitcoind answers 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.py for this tree’s own framing arithmetic ahead of btclib’s wire codec, fuzz_rpc_head.py for the HTTP header arithmetic ahead of json.loads, and fuzz_process_message.py for p2p/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, which grep -rn 'threading\.R\?Lock()' src lists.

  • 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 raise BTClibException, and nothing else. tests/fuzz_corpus_test.py checks that every corpus seed still parses. Inside Node’s own loop, _drain_message_queues catches what a handler raises and logs it, and the loop goes on; _step_chain catches 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_BYTES on the RPC surface, MAX_PROTOCOL_MESSAGE_LENGTH, -maxreceivebuffer and -maxsendbuffer and 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 in pyproject.toml, flags a call to a random function under src/ (S311), not the import. download.py’s own trickle-relay schedule draws from random.SystemRandom, and p2p/callbacks.py’s address-sampling jitter from secrets.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 from secrets directly.

  • 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.yml compares with upstream on a schedule.

  • Deserialization of untrusted data (CWE-502). json.loads on an RPC body is the only deserializer of untrusted data src/ calls directly, and it is the standard library’s own, bounded ahead of the call by MAX_BODY_BYTES; a p2p message is parsed by btclib rather than unpickled or unmarshalled. rocksdict pickles a value by default, which db.py avoids with raw_mode=True on every Options and WriteBatch, so no stored value is unpickled. The census under Threat model lists neither pickle nor marshal nor shelve. .github/workflows/codeql.yml analyses 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’s assert_secret_free is 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 of RequestHead and _Settings leave out the fields that hold a credential. tests/unit/cli_test.py’s test_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_alone and test_log_args_quotes_a_section_by_its_name_alone, and tests/unit/rpc/connection_test.py’s test_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_args writes each settings.json value as read, a sensitive option’s included, and btclib-org/btclib-node#1967 owes the fix with its test. _log_args and _init_settings_file’s warning write each settings.json name 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_under in pyproject.toml, and .github/mutation/interpreter.toml, run by .github/workflows/mutation.yml, asks whether the suite notices a wrong line inside src/btclib_node/interpreter.py, the consensus entry point ARCHITECTURE.md’s Validation names. Each weekly run executes every mutant of that file, and of p2p/headers_sync.py through headers_sync.toml; a survivor is a test to write or an equivalent mutant interpreter.toml explains.

  • Supply chain. SECURITY.md’s Supported versions describes the attestations. uv.lock pins 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 in test.yml’s dist job 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, so pip install btclib-node gets the newest version each floor admits. deps-latest.yml and deps-oldest.yml resolve 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, zizmor and detect-secrets run as hooks in .pre-commit-config.yaml.