btclib_node.rpc package

Submodules

btclib_node.rpc.allow module

-rpcallowip: which sources the JSON-RPC listener answers.

Core’s InitHTTPAllowList and ClientAllowed (src/httpserver.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag). A value is read by lookup_subnet, the ban list’s LookupSubNet, as setban reads one in Core; loopback is always allowed.

btclib_node.rpc.allow.allowed_subnets(values: tuple[str, ...]) → tuple[Subnet, ...][source]

Core’s InitHTTPAllowList: loopback, then every -rpcallowip value.

Raises ValueError with Core’s message for the first value that names no subnet.

btclib_node.rpc.allow.client_allowed(host: str, subnets: tuple[Subnet, ...]) → bool[source]

Core’s ClientAllowed of the peer at host, as accept names it.

lookup_host reads host as an address, and Subnet.matches refuses one CNetAddr::IsValid refuses.

btclib_node.rpc.auth module

RpcAuth, who may call the JSON-RPC listener, and which methods.

Bitcoin Core’s own scheme, read at bitcoin/bitcoin@9be056a8a7 – v31.1, the release integration-bitcoind.yml pins: InitRPCAuthentication, RPCAuthorized, CheckUserAuthorized and HTTPReq_JSONRPC in src/httprpc.cpp, GetAuthCookieFile, GenerateAuthCookie and DeleteAuthCookie in src/rpc/request.cpp. Every request carries HTTP Basic credentials, checked against a list of RpcAuthEntry, each a user, a salt and the HMAC-SHA256 of the password keyed by that salt. -rpcauth=<user>:<salt>$<hmac> adds one as written; -rpcuser and -rpcpassword add one hashed with a fresh random salt, so the plaintext password is not what is kept. The cookie adds another: generate_cookie writes __cookie__:<64 hex digits> to -rpccookiefile, .cookie in the chain’s data directory by default, and keeps only the salted HMAC of that password. Core writes the cookie unless -rpcpassword is set or -norpccookiefile is given, whether or not -rpcauth is.

The user and the HMAC are both compared with hmac.compare_digest, Core’s own TimingResistantEqual, so the time a refusal takes says nothing about how much of either matched.

-rpcwhitelist=<user>:<method>,… limits a user to the methods it names, and refusal is Core’s per-method check, run on the decoded body once the credential is accepted.

class btclib_node.rpc.auth.Refusal(status: str, body: dict[str, Any] | None = None, warning: tuple[str, ...] = ())[source]

Bases: object

A request -rpcwhitelist refuses: the status line and body Core sends.

body is None for Core’s bare 403, and otherwise the JSON-RPC error object JSONErrorReply writes. warning is the format and arguments of the line Core logs with a 403, () where it logs none.

class btclib_node.rpc.auth.RpcAuth(entries: Sequence[__annotationlib_name_1__] = (), *, password: RpcAuthEntry | None = None, cookie_file: Path | None = None, cookie_tmp: Path | None = None, cookie_perms: int | None = None, cookie_perms_error: str | None = None, rpcauth_invalid: bool = False, whitelist: Mapping[__annotationlib_name_2__, __annotationlib_name_3__] | None = None, whitelist_default: bool = False)[source]

Bases: object

The credentials and whitelists RpcConnection.run checks against.

entries is the -rpcuser/-rpcpassword pair’s entry where -rpcpassword is set, every -rpcauth value after it, and the cookie’s own once generate_cookie has run. RpcManager.run calls start on the manager’s thread after binding its listener and before accepting on it, and every read of entries is a request’s, on that same thread, afterwards; RpcManager.stop calls delete_cookie once that thread is joined.

authenticated_user(authorization: str) → bytes | None[source]

Return the user an Authorization header names, if it is accepted.

Core’s RPCAuthorized: the Basic ` scheme, base64 of `<user>:<password> split at its first :, then CheckUserAuthorized over every entry. A header that is not this shape is a wrong credential, not a malformed request. None is a refusal; b”” is the empty user an -rpcpassword with no -rpcuser is accepted as.

Remove the cookie generate_cookie wrote, if it wrote one.

A cookie already gone is not an error, as fs::remove returns false rather than raising for it; any other failure raises OSError, which Core logs as a warning.

classmethod from_config(config: Config) → RpcAuth[source]

Build the RpcAuth a node’s config asks for.

Write the cookie to path and accept the password it holds.

Written to tmp and renamed over path, as Core does, so a client never reads a half-written file. tmp is .tmp appended to path unless given: Config.rpc_cookie_tmp differs from that where -rpccookiefile normalises to .. Created with mode 0600 on POSIX: Core’s own default is owner-only through the process umask 0077 (-rpccookieperms’ “default: owner”), and this sets the mode on the file rather than the umask of a process this node shares with its caller. perms, where given, then replaces that mode after the rename, as Core’s fs::permissions does. On Windows os.open and os.chmod take only the read-only flag from a mode, and every mode -rpccookieperms names keeps the owner’s write bit, so neither changes anything there: the ACL of the directory the file sits in, which it inherits, decides who reads it. A leftover .tmp is removed first, since O_CREAT’s mode applies only to a file it creates.

Raises OSError with GenerateAuthCookie’s own warning where the file cannot be opened, renamed or given perms, the .tmp left where the rename fails, as Core leaves it. A path holding a NUL byte is refused as one that cannot be opened, the ValueError Python raises for it forcing a divergence: bitcoind v31.1.0 writes to the path cut at that byte instead.

refusal(user: bytes, request: object) → Refusal | None[source]

Return how -rpcwhitelist refuses user’s decoded request, if so.

HTTPReq_JSONRPC’s check, run once the body has parsed as JSON: a user with no whitelist may call every method, unless -rpcwhitelistdefault holds, which refuses it everything with a 403. A whitelisted user’s lone request is parsed first, answered with Core’s own error where that parse refuses it, and otherwise refused with a 403 where its method is not allowed; a batch is checked entry by entry, before any of them runs. Anything else a whitelisted user sends is left to the answer anybody else gets.

start(logger: logging.Logger) → None[source]

Write the cookie where Core would, logging what Core logs.

InitRPCAuthentication: no cookie where -rpcpassword is set, with Core’s warning that the password sits in plain text, and none where -norpccookiefile is given. Raises generate_cookie’s OSError where the cookie cannot be written or its permissions set, and RpcCredentialRefusedError where Core refuses -rpccookieperms, before the cookie, or -rpcauth, after it, each logged at Core’s level.

class btclib_node.rpc.auth.RpcAuthEntry(user: bytes, salt: bytes, hmac: bytes)[source]

Bases: object

One user this listener accepts: a name, a salt and a password’s HMAC.

Held as bytes, which is what hmac.compare_digest compares for any content: it refuses a str holding anything but ASCII, and a user name comes off the wire as whatever octets the client sent.

classmethod from_password(user: str, password: str) → RpcAuthEntry[source]

Hash password with a fresh random salt, as Core stores one.

classmethod parse(value: str) → RpcAuthEntry[source]

Parse one -rpcauth value, <user>:<salt>$<hmac>.

Core’s split: on : into exactly two fields, then the second on $ into exactly two. Anything else is Core’s fatal “Invalid -rpcauth argument.”, so a user name cannot hold a :.

btclib_node.rpc.auth.cookie_perms(value: str) → int[source]

Return the mode -rpccookieperms=<value> sets: InterpretPermString.

owner is 0600, group 0640 and all 0644; anything else raises ValueError with Core’s own message, fatal there too.

btclib_node.rpc.auth.parse_whitelist(values: Sequence[__annotationlib_name_1__]) → dict[bytes, frozenset[str]][source]

Parse every -rpcwhitelist value into each user’s allowed methods.

InitRPCAuthentication’s loop: the user is what precedes the first :, and the methods are what follows it split at every , and every space, empty names kept. A second value for a user intersects with the first. A value with no : gives a user not yet named an empty whitelist, and leaves one already named as it was.

btclib_node.rpc.auth.password_hmac(salt: bytes, password: bytes) → bytes[source]

Return HMAC-SHA256 of password keyed by salt, as lowercase hex.

What an -rpcauth line’s third field holds, and what share/rpcauth/ in Core’s source computes for one.

btclib_node.rpc.auth.to_bytes(value: str) → bytes[source]

Return the bytes value was read from, as Core holds a setting.

UTF-8, a lone surrogate being the byte surrogateescape decoded it from: a bitcoin.conf read by cli._read_conf_file, and an argument on POSIX, where Python decodes argv the same way.

btclib_node.rpc.callbacks module

One handler per JSON-RPC method, and callbacks, the table dispatching them.

Every handler shares the signature (node, conn, params) that rpc.main.handle_rpc calls each one with, whether or not its own body reads every argument – the same shared-signature reasoning p2p.callbacks carries for its own two tables. A request reaches an entry here only once rpc.connection.RpcConnection.run has accepted its credential and -rpcwhitelist its method (rpc.auth): a user no whitelist names may call every entry, stop included, unless -rpcwhitelistdefault holds.

btclib_node.rpc.callbacks.add_connection(node: Node, conn: RpcConnection, params: list[Any]) → dict[str, Any][source]

Answer addconnection: dial one peer of a chosen type, regtest only.

Core’s own (src/rpc/net.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag). The three declared arguments are all required, so the generic checks RPCHelpMan::HandleRequest runs ahead of every method’s own lambda – the missing-argument and wrong-JSON-type refusals, _height_param’s own docstring arguing the shape – come first here too, ahead of the chain gate the real lambda opens on.

A connection_type outside _ADDCONNECTION_TYPES is RPC_INVALID_PARAMETER carrying this method’s own full help text, self.ToString()’s shape (measured against a real bitcoind v31.1.0). v2transport true is refused the same way Core refuses it lacking NODE_P2P_V2 (connman.GetLocalServices() & NODE_P2P_V2), which local_services (p2p/connection.py) sets with -v2transport. v2transport false is refused without -v1transport, this node’s own mirror of that, for refusing v1 (btclib-org/btclib-node#1190).

Both of CConnman::AddConnection’s capacity checks, the per-type cap and the shared semOutbound pool, are P2pManager.reserve_automatic_slot’s, which takes the slot in the same step. Its docstring says why the check and the reservation are one step here, where Core’s dial is synchronous. connect_typed releases the slot once the dial concludes.

automatic=True for a feeler too, as _dial_one_draw sets it for a drawn one: maybe_discourage_and_disconnect reads automatic as “not MANUAL”, and a feeler is not MANUAL in Core either.

The dial itself, P2pManager.connect_typed, runs fire-and-forget, the same as onetry’s (add_node above, connect_host): this answers once the dial is scheduled, not once it connects, which is also why nothing here waits to learn whether it does.

btclib_node.rpc.callbacks.add_node(node: Node, conn: RpcConnection, params: list[Any]) → None[source]

Answer addnode’s three commands for real, each against Core’s own list.

The module-level comment above argues the three commands; this function is Core’s own argument parsing and its two literal error messages (rpc/net.cpp:365-377, at bitcoin/bitcoin@bb529657). The empty-node refusal is master’s own fix (rpc: reject empty node argument in addnode, at bitcoin/bitcoin@90ce21e21d) rather than this tree’s own pinned bitcoind’s: at bitcoin/bitcoin@9be056a8a7 – v31.1, the release integration-bitcoind.yml pins, answers an empty node with a silent, do-nothing success instead, measured directly against a real v31.1.0 (issue #1010). 90ce21e21d post-dates v31.1’s own tag commit and is confirmed on bb529657’s own ancestry via git merge-base –is-ancestor.

Matching master here rather than the release this tree tests against is a decision, not an oversight: CONTRIBUTING.md’s own Following Bitcoin Core names matching Core’s behaviour as the default, and reserves a release-pinned citation for a claim about the behaviour of the bitcoind this tree is tested against rather than for what this node implements. Master’s own code comment names why the fix exists – “Such a node would never resolve, but would be retried indefinitely” – and nothing under tests/integration/ drives addnode “”, so this tree’s own integration suite, run against v31.1, never exercises the one call shape the two disagree on. Matching the release instead would mean knowingly carrying a defect Core itself already fixed, only to undo that the moment the pin advances past it – issue #1010 is closed on this reasoning. v2transport is Core’s own optional third argument, kept with an added peer and passed to a onetry dial.

btclib_node.rpc.callbacks.add_peer_address(node: Node, conn: RpcConnection, params: list[Any]) → dict[str, Any][source]

Answer addpeeraddress: add one address to the table, for testing.

Core’s own, a hidden command (src/rpc/net.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag): the address is added with NODE_NETWORK | NODE_WITNESS, the time now, and itself as its source, which is no penalty, and with tried moved to the answered table as a handshake does. An address the table already holds, or refuses, is failed-adding-to-new, with tried too. The host is read as LookupHost does without DNS, lookup_host; Core flips an IPv6 address in fc00::/8 to CJDNS where -cjdnsreachable is set, which this node has no counterpart to.

btclib_node.rpc.callbacks.clear_banned(node: Node, conn: RpcConnection, _: list[Any]) → None[source]

Answer clearbanned.

btclib_node.rpc.callbacks.decode_raw_transaction(node: Node, conn: RpcConnection, params: list[Any]) → dict[str, Any][source]

Answer decoderawtransaction: decode hexstring, answer its JSON.

No chain or mempool lookup, and no CheckTransaction: Core’s own handler (src/rpc/rawtransaction.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag) calls DecodeHexTx and TxToUniv alone, so a well-formed but structurally invalid transaction is answered here too, the same as it decodes and displays there – btclib-org/btclib-node#1398, and unlike sendrawtransaction and testmempoolaccept above, which run _check_transaction. The answer is _tx_to_univ’s, the one get_raw_transaction’s own verbose answer builds on, minus the hex that call adds and the blockhash it sometimes does: Core’s own TxToUniv call here passes include_hex=false and a null block_hash, neither of which this RPC is given a block or asked to serialize.

iswitness picks the readings _decode_tx tries, as Core’s handler does (src/rpc/rawtransaction.cpp, same tag). btclib-org/btclib-node#1458

btclib_node.rpc.callbacks.disconnect_node(node: Node, conn: RpcConnection, params: list[Any]) → None[source]

Answer disconnectnode: drop one connection, by address or by id.

Core’s own (src/rpc/net.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag): address alone, or an empty or null address with nodeid, and anything else RPC_INVALID_PARAMS. A connection still short of verack is found too, as Core’s m_nodes holds it. The address is matched against getpeerinfo’s own addr, the id against its id, and neither found is RPC_CLIENT_NODE_NOT_CONNECTED. Named arguments reach it mapped onto these two positions by arg_names.

A call carrying more than two positional arguments never reaches this function’s own body at all: rpc.main._execute refuses it generically now, for every method arg_names declares, rather than this function checking its own upper bound the way it used to be the only callback here to (rpc.main._execute’s own docstring argues the generalization, btclib-org/btclib-node#1424).

btclib_node.rpc.callbacks.get_best_block_hash(node: Node, conn: RpcConnection, _: list[Any]) → bytes[source]

Answer getbestblockhash with the active chain’s own tip.

btclib_node.rpc.callbacks.get_block(node: Node, conn: RpcConnection, params: list[Any]) → str | dict[str, Any][source]

Answer getblock: the block’s hex, or Core’s own JSON shape.

Core’s own getblock (rpc/blockchain.cpp:761-841, calling blockToJSON, :200-243, at bitcoin/bitcoin@9be056a8a7) answers verbosity 0 or below with the hex, and verbosity 1 with the header fields blockheaderToJSON answers (get_block_header’s own verbose branch, mirrored by _block_json_header above) plus strippedsize, size, weight, coinbase_tx and tx as an array of txids (TxVerbosity::SHOW_TXID). Verbosity 2 answers tx as an array of decoded transactions instead, getrawtransaction’s own verbose shape (_tx_to_univ, with hex) plus the fee of a transaction whose undo data is held; verbosity 3 and above add each input’s prevout (TxVerbosity::SHOW_DETAILS_AND_PREVOUT). _block_undo is where the undo data is read.

btclib_node.rpc.callbacks.get_block_count(node: Node, conn: RpcConnection, _: list[Any]) → int[source]

Answer getblockcount with the active chain’s own height.

btclib_node.rpc.callbacks.get_block_hash(node: Node, conn: RpcConnection, params: list[Any]) → bytes[source]

Answer getblockhash, Core’s own checks on height in Core’s order.

A missing, wrongly typed, non-integral or out-of-range height is each refused the way RPCMethod::HandleRequest and src/rpc/blockchain.cpp:585-601 refuse it, cited beside each check below; a height in range answers active_chain[height].

btclib_node.rpc.callbacks.get_block_header(node: Node, conn: RpcConnection, params: list[Any]) → dict[str, Any] | str[source]

Answer getblockheader for params[0], verbose by Core’s own default.

Not verbose, answers the same eighty bytes a peer is sent on the wire, hex-encoded; verbose, answers the object blockheaderToJSON does, height and confirmations included for a header off the active chain as much as for one on it – each field’s own Core citation is beside where it is built, below.

nTx is the one member blockheaderToJSON answers that this does not (src/rpc/blockchain.cpp:185, at bitcoin/bitcoin@ca7162cde5): Core reads it off CBlockIndex::nTx, a count kept beside the header once the block is received; BlockInfo (chainstate/block_index.py) carries no such count, only header, index, status and downloaded, so answering it here would mean parsing the whole block body off block_db for every call – a header lookup paying a block’s own cost, and one that still has nothing to answer for a header whose block was never downloaded. Left absent rather than answered at that price.

btclib_node.rpc.callbacks.get_blockchain_info(node: Node, conn: RpcConnection, _: list[Any]) → dict[str, Any][source]

Answer getblockchaininfo with Core’s own members this node can answer.

chain: BitcoinCoreFetcher.assert_network (btclib) and BitcoinCoreRpcClient.assert_chain (bitcoin_core_rpc) call this once before their first fetch, by default, and read chain alone – proven by asking a real client of a real node here for get_best_block_id before this callback existed: the very first call failed -32601 Method not found on getblockchaininfo, not on the method it asked for. That is why chain could not be left out, not a reason the rest stayed absent.

blocks is active_chain’s own last index, matching get_block_count above: Core’s own “the height of the most-work fully-validated chain” (src/rpc/blockchain.cpp:1427, at bitcoin/bitcoin@ca7162cde5). headers is header_index’s own last index the same way – header_index is this node’s own best known header chain, tracked separately from active_chain (BlockIndex’s own class docstring) the way Core’s m_best_header is tracked separately from ActiveChain()’s own tip, and answered the same way Core answers it: chainman.m_best_header->nHeight (src/rpc/ blockchain.cpp:1428, at bitcoin/bitcoin@ca7162cde5). bestblockhash is active_chain’s own tip, matching get_best_block_hash above (src/rpc/blockchain.cpp:1429, at bitcoin/bitcoin@ca7162cde5) – both already the display byte order Core’s own GetHex() answers, BlockHeader.hash (btclib) being the reversed hash rather than the wire’s own, confirmed against a real bitcoind’s identical expression at tests/integration/bitcoind_test.py:66.

bits is the tip header’s own compact target, header.bits, hex (Core’s strprintf(“%08x”, tip.nBits), src/rpc/blockchain.cpp:1430, at bitcoin/bitcoin@ca7162cde5). target is header.target (btclib), 32 bytes already in the same big-endian order Core’s own GetTarget(…).GetHex() answers (src/rpc/blockchain.cpp:1431, same commit) – target_from_bits (btclib.block.proof_of_work) is Core’s SetCompact, and arith_uint256::GetHex writes each 32-bit limb little-endian into a base_blob and then reverses that whole blob (src/arith_uint256.cpp:141, src/uint256.cpp:11, same commit), which is a plain big-endian print of the magnitude and not the reversal a hash’s own GetHex answers. difficulty is header.target’s ratio against the genesis target, header.difficulty (btclib) – the same ratio Core’s own GetDifficulty computes by repeated *=//= 256.0 from the compact exponent (src/rpc/blockchain.cpp:106, same commit), verified bit for bit against that literal loop on regtest’s own genesis bits 0x207fffff in this callback’s own unit test.

time is the tip header’s own timestamp, block_index.block_time (Core’s CBlockHeader::GetBlockTime, src/rpc/blockchain.cpp:1433, same commit). mediantime is btclib’s own median_time_past of the tip, over main.parent_lookup’s own walk – the same call main.verify_mempool_acceptance already makes of the tip, for Core’s own CBlockIndex::GetMedianTimePast (src/rpc/blockchain.cpp :1434, same commit). chainwork is block_index.chainwork’s own entry for the tip, hex and zero-padded to 64 digits the way Core’s nChainWork.GetHex() prints a plain magnitude (src/rpc/ blockchain.cpp:1450, same commit) – get_block_header above answers its own chainwork the same way now, closing what used to be a divergence from Core between the two (btclib-org/btclib-node#658).

initialblockdownload is node.is_initial_block_download, main.update_ibd_status’s own latch, matching Core’s own IsInitialBlockDownload (src/rpc/blockchain.cpp:1436, at bitcoin/bitcoin@ca7162cde5) field for field: chain work against node.config.minimum_chain_work and tip age against node.config.max_tip_age, not merely whether this node has run out of candidates to try. size_on_disk is block_db.BlockDB.current_usage, Core’s own CalculateCurrentUsage (src/rpc/blockchain.cpp:1451, same commit). pruned is Config.pruned (src/rpc/blockchain.cpp:1452, same commit); pruneheight, present only where pruned is true, is the first height block_db.BlockDB.prune_up_to has not deleted – pruned_up_to + 1, Core’s own “the first block unpruned, all previous blocks were pruned” (src/rpc/blockchain.cpp:1455, same commit, prune_height.value() + 1). automatic_pruning, present alongside it, is whether Config.prune_target_mib is set – Core’s own GetPruneTarget() != PRUNE_TARGET_MANUAL (src/rpc/blockchain.cpp:1457, same commit); prune_target_size, present only where that is true, is prune_target_mib in bytes, Core’s own unit for the member of the same name.

warnings is node.warnings.get_messages(), Core’s own node::GetWarningsForRpc(*node.warnings, IsDeprecatedRPCEnabled (“warnings”)) (src/rpc/blockchain.cpp:1443, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag) – always the array form: this node has no -deprecatedrpc of its own, so the single-string form use_deprecated=true answers with is never reachable here. Empty, ordinarily: it takes an invalid chain with more work than this node’s own tip (main.check_fork_warning_conditions, btclib-org/btclib-node#1522) or a version bit no deployment uses reaching its threshold (versionbits.check_unknown_activations, btclib-org/btclib-node#1475) to set anything.

Absent, each for its own reason rather than by oversight: verificationprogress, Core’s own GuessVerificationProgress (src/validation.cpp:5519, at bitcoin/bitcoin@ca7162cde5) extrapolating from ChainTxData, an assumed transaction rate for the chain as a whole, against each block’s own accumulated transaction count (CBlockIndex::m_chain_tx_count) – chains.py carries neither the per-chain assumption nor a per-block count, so answering this member under Core’s own name would answer a number carrying none of Core’s meaning behind it, rather than a truthful one; signet_challenge, SigNet here carrying no configurable challenge (chains.py’s own genesis is the one public signet); backgroundvalidation, present on Core’s own side only behind an assumeutxo snapshot this node has no counterpart to.

btclib_node.rpc.callbacks.get_chain_tips(node: Node, conn: RpcConnection, _: list[Any]) → list[dict[str, Any]][source]

Answer getchaintips: every known tip, Core’s own status vocabulary.

Core’s own getchaintips (rpc/blockchain.cpp:1556-1651, at bitcoin/bitcoin@9be056a8a7) finds a tip by one pass over every header it knows, keeping the ones nothing else names as its own parent, and always adds the active chain’s own tip. block_index.children is this index’s own parent -> children table, already kept for BlockIndex.invalidate’s own walk (that class’s own comment on it), so a tip here is exactly a hash with no entry in it, or an empty one – the active tip included, nothing ever being staged on top of it until a block extends it, so it needs no separate case the way Core’s own setTips.insert(active_chain.Tip()) does past its own orphans-only loop.

branchlen is the fork’s own length (CChain::FindFork’s height difference, :1618) – BlockIndex.get_fork_details already returns that same branch, oldest first, for a header not on active_chain, and its own length is this call’s branchlen; the active tip’s own fork is empty by definition, so it is answered 0 without calling that method at all.

status, in Core’s own priority order (:1622-1639): “active” for the chain’s own tip; “invalid” for a tip BlockStatus.invalid already marks, itself or an ancestor, invalidate above already propagating that mark down every child rather than leaving it for a walk here; “headers-only” where the fork’s own blocks are not every one downloaded (Core’s own HaveNumChainTxs, which needs the whole branch’s data and not merely this tip’s – _branch_is_downloaded’s own reasoning, inlined here rather than called, since its own fork is this call’s own fork already); “valid-fork” for BlockStatus.valid, which _finalize_fork’s own to_remove loop and -reindex-chainstate’s wipe set, for a block that was connected once and is off the active chain (Core’s IsValid(BLOCK_VALID_SCRIPTS)); and “valid-headers” for a fully downloaded BlockStatus.valid_header that never was (Core’s IsValid(BLOCK_VALID_TREE)) – the one status left once the other four are ruled out, since every header this index carries already passed _validate_header_batch’s own contextual checks, which is what Core’s own final “unknown” case answers a status below that nothing indexed here ever reaches.

btclib_node.rpc.callbacks.get_connection_count(node: Node, conn: RpcConnection, _: list[Any]) → int[source]

Answer getconnectioncount, a pending connection counted too.

Core’s own getconnectioncount counts every entry of m_nodes (CConnman::GetNodeCount), which holds a socket from the moment it is accepted or dialled – before its handshake, not only after.

btclib_node.rpc.callbacks.get_mempool_ancestors(node: Node, conn: RpcConnection, params: list[Any]) → dict[str, Any] | list[str][source]

Answer getmempoolancestors, _mempool_relatives’ ancestors.

btclib_node.rpc.callbacks.get_mempool_cluster(node: Node, conn: RpcConnection, params: list[Any]) → dict[str, Any][source]

Answer getmempoolcluster: the cluster of a held transaction, by chunk.

Core’s clusterToJSON (src/rpc/mempool.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag): the sigop-adjusted weight and the count of the whole cluster, and each chunk’s modified fee, weight and txids, in the order a block takes them. A txid this mempool does not hold is “Transaction not in mempool”.

btclib_node.rpc.callbacks.get_mempool_descendants(node: Node, conn: RpcConnection, params: list[Any]) → dict[str, Any] | list[str][source]

Answer getmempooldescendants, _mempool_relatives’ descendants.

btclib_node.rpc.callbacks.get_mempool_entry(node: Node, conn: RpcConnection, params: list[Any]) → dict[str, Any][source]

Answer getmempoolentry: one held transaction’s own accounting.

Core’s own shape (entryToJSON, src/rpc/mempool.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag), with Core 32’s vsize_adjusted and vsize_bip141 (at bitcoin/bitcoin@aef8a04966, btclib-org/btclib-node#1757). A txid this mempool does not hold is Core’s own RPC_INVALID_ADDRESS_OR_KEY, “Transaction not in mempool”. btclib-org/btclib-node#1397

btclib_node.rpc.callbacks.get_mempool_feerate_diagram(node: Node, conn: RpcConnection, _: list[Any]) → list[dict[str, Any]][source]

Answer getmempoolfeeratediagram, Core’s hidden RPC.

GetFeerateDiagram (src/txmempool.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag): from zero, the running sigop-adjusted weight and modified fee after each chunk, in the order a block takes them.

btclib_node.rpc.callbacks.get_mempool_info(node: Node, conn: RpcConnection, _: list[Any]) → dict[str, Any][source]

Answer getmempoolinfo with the fields this tree backs for real.

maxdatacarriersize is 0 where -datacarrier is off, as Core’s value_or(0).

The comment below argues, field by field, why Core’s own several others are left out rather than answered with a placeholder, and why mempoolminfee, minrelaytxfee and incrementalrelayfee are BTC/kvB rather than this tree’s own sat/kvB.

btclib_node.rpc.callbacks.get_network_info(node: Node, conn: RpcConnection, _: list[Any]) → dict[str, Any][source]

Answer getnetworkinfo with the fields argued below.

Core’s own getnetworkinfo (rpc/net.cpp:674-800, at bitcoin/bitcoin@bb529657) answers two dozen fields, most either this node’s own configuration it carries no counterpart to – -onlynet, -proxy, -asmap – or relay-loop state this node does not keep (inv_buckets, tx_send_rate). Serving a placeholder for any of those would be the same decoration get_mempool_info’s own docstring already argues against, so they are left out rather than answered with a made-up number.

subversion is what test_framework.py’s own connect_nodes (:568-594, same sha) reads off each side before wiring them together – get_peer_info above answers the matching subver a peer sees on the wire, both reading constants.USER_AGENT (btclib-org/btclib-node#1009) rather than each computing their own. protocolversion is PROTOCOL_VERSION (btclib.p2p.limits), the same constant every version this node sends and every getheaders it builds already carries.

localservices and localservicesnames are p2p.connection.local_services (rpc/net.cpp:706-708, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag) – the services this node’s own version advertises on every connection, one function answering both rather than each computing its own (btclib-org/btclib-node#1394), service_names above turning the same bits into the strings getpeerinfo’s own servicesnames already uses for a peer’s.

warnings is node.warnings.get_messages(), the same array get_blockchain_info’s own warnings answers – Core’s own getnetworkinfo reads the identical node.warnings rpc/net.cpp does (:740, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag – not bb529657 above, this paragraph’s own citation), so the two RPCs never disagree here either.

networkactive is Core’s CConnman::GetNetworkActive (rpc/net.cpp:716, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag), the flag setnetworkactive sets, and it precedes connections as in Core.

connections, connections_in and connections_out are Core’s CConnman::GetNodeCount for Both, In and Out (rpc/net.cpp:717-719, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag). Each counts a pending connection too, as get_connection_count above does, and a connection is inbound exactly where getpeerinfo answers inbound true: Core’s IsInboundConn, so every other connection type, a feeler included, counts as outbound. Both directions are counted off one table, so connections_in + connections_out == connections always.

localaddresses is what P2pManager.local_snapshot holds, as Core’s mapLocalHost is read under its mutex (rpc/net.cpp:728-738, same sha), in the order of its std::map of CNetAddr: IPv4 before IPv6, then by octets.

btclib_node.rpc.callbacks.get_node_addresses(node: Node, conn: RpcConnection, params: list[Any]) → list[dict[str, Any]][source]

Answer getnodeaddresses: known addresses, after quality and recency.

Core’s own (src/rpc/net.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag): CConnman::GetAddressesUnsafe of count and no percentage, which is PeerDB.get_addr, a discouraged or banned host left out as in a getaddr answer. count 0 answers every address, a negative one is refused, and network is one of Core’s five names in any case.

btclib_node.rpc.callbacks.get_orphan_txs(node: Node, conn: RpcConnection, params: list[Any]) → list[str] | list[dict[str, Any]][source]

Answer getorphantxs: the orphanage, in Core’s three verbosities.

Core’s hidden RPC (src/rpc/mempool.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag): the txids at verbosity 0, an object each with its txid, wtxid, bytes, vsize, weight and the ids of the peers it is from at 1, and the hex too at 2, in the order of the wtxids as Core holds them. Any other number is RPC_INVALID_PARAMETER, and a bool is refused (_parse_verbosity). vsize is GetVirtualTransactionSize without sigops, as getrawmempool’s is not.

btclib_node.rpc.callbacks.get_peer_info(node: Node, conn: RpcConnection, _: list[Any]) → list[dict[str, Any]][source]

Answer getpeerinfo, one entry per connection, in id order.

A connection still short of verack is listed too, as Core lists every node CConnman::GetNodeStats returns. Each field matches one getpeerinfo pushes (src/rpc/net.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag), argued in _peer_entry beside where it is built.

btclib_node.rpc.callbacks.get_prioritised_transactions(node: Node, conn: RpcConnection, _: list[Any]) → dict[str, dict[str, Any]][source]

Answer getprioritisedtransactions: every fee delta, held or not.

Core’s own (src/rpc/mining.cpp, same tag): amounts in satoshi, keyed by txid in the order of the txid’s internal bytes, and a modified_fee only for a transaction in the mempool. btclib-org/btclib-node#1502

btclib_node.rpc.callbacks.get_raw_mempool(node: Node, conn: RpcConnection, params: list[Any]) → dict[str, Any] | list[str][source]

Answer getrawmempool, Core’s own three shapes by params.

verbose alone answers one object per mempool transaction; neither flag answers a plain array of txids; mempool_sequence alone adds node.mempool.sequence beside that array. The two together are refused outright, matching MempoolToJSON’s own combination check.

btclib_node.rpc.callbacks.get_raw_transaction(node: Node, conn: RpcConnection, params: list[Any]) → dict[str, Any] | str[source]

getrawtransaction, for a mempool transaction or a named block’s.

No -txindex equivalent: this node keeps no lookup from every txid it has ever confirmed to the block that holds it, so a transaction is answered for exactly the two cases Core itself falls back to without one – the mempool by itself (src/rpc/rawtransaction.cpp:313-314, !g_txindex), and a block named explicitly, searched rather than indexed. Both are read-only lookups against block_index and block_db, which already hold every validated block for reasons of their own; this adds no store.

btclib’s own BitcoinCoreFetcher.get_tx calls this with a txid alone, verbosity 0 being its _call’s implicit default – the shape it always gets, unconditionally, below.

btclib_node.rpc.callbacks.get_rpc_info(node: Node, conn: RpcConnection, _: list[Any]) → dict[str, Any][source]

Answer getrpcinfo: every RPC call in flight, and where this node logs.

Core’s own RPCServerInfo.active_commands/RPCCommandExecution (src/rpc/server.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag): rpc.main._execute is this node’s own ExecuteCommand, and node.active_rpc_commands is its own active_commands, appended to and removed there rather than guarded by a destructor – this call’s own entry is already in it by the time this callback runs, exactly as Core’s own is by the time its lambda runs. duration is microseconds, Ticks<std::chrono::microseconds> over Core’s own SteadyClock::now() - info.start; time.monotonic() is this node’s own steady clock, elapsed time only and never a wall-clock reading, which is what SteadyClock is too.

logpath is node.log_path, “” where this node logs to a stream rather than a file, as LogInstance().m_file_path.utf8string() answers for an unset path too.

btclib_node.rpc.callbacks.get_tx_out(node: Node, conn: RpcConnection, params: list[Any]) → dict[str, Any] | None[source]

Answer gettxout: one outpoint’s own unspent coin, or null.

Core’s own gettxout (rpc/blockchain.cpp:1182-1261, at bitcoin/bitcoin@9be056a8a7). include_mempool, true by default, overlays this node’s own mempool on the confirmed UTXO set the same two ways Core’s CCoinsViewMemPool does: an outpoint a mempool transaction spends answers null before either view is read (isSpent, _mempool_spends above), and one a mempool transaction creates – not yet in UtxoIndex at all – answers that transaction’s own output, at Core’s own sentinel height MEMPOOL_HEIGHT, ahead of the confirmed set (CCoinsViewMemPool::GetCoin, src/txmempool.cpp:790-811) – Mempool.get_tx by txid is that same lookup, Core’s own mempool.get(outpoint.hash).

confirmations is 0 for a coin at that sentinel height, matching Core’s own coin->nHeight == MEMPOOL_HEIGHT check, and otherwise the active chain’s own height past the coin’s, pindex->nHeight - coin->nHeight + 1 – active_chain’s own length already being the tip’s height plus one, the “+ 1” is folded into the subtraction the same way get_block_header’s own confirmations folds it in above.

btclib_node.rpc.callbacks.get_tx_out_set_info(node: Node, conn: RpcConnection, params: list[Any]) → __annotationlib_name_3__ | Generator[__annotationlib_name_1__, None, __annotationlib_name_2__][source]

Answer gettxoutsetinfo from UtxoIndex’s own running CoinStats.

Core’s own default path recomputes every field from a live scan of the coins database (ComputeUTXOStats, kernel/coinstats.cpp) on every call, unless -coinstatsindex is running, in which case the incrementally-maintained CoinStatsIndex answers instead (index/coinstatsindex.cpp) – chainstate/muhash.py’s own module docstring is where CoinStats is argued as this tree’s equivalent of that second path. height, bestblock, txouts, bogosize, total_amount and muhash come from it, and are Core’s own field names and units, total_amount in BTC through btc_amount the way get_mempool_info’s own mempoolminfee already is; muhash itself is the raw digest bytes reversed before this returns, matching uint256::GetHex()’s own convention rather than this class’s digest (chainstate/muhash.py’s own comment beside is_bip30_unspendable is where that reversal is confirmed against the well-known genesis hash rather than assumed).

hash_type: “hash_serialized_3”, Core’s default, is the legacy double-SHA256 over every coin, which no accumulator keeps: it is a scan of the utxo- records, UtxoIndex.serialized_hash. The chainstate is flushed first, as Core’s ForceFlushStateToDisk does, and the cursor is opened on Node’s thread together with the other fields, so the answer is one set’s. The scan is the generator _serialized_hash_job, on a thread of its own as Core’s is on an HTTP worker, and Node’s loop serves other requests meanwhile. A stored record that does not parse is RPC_INTERNAL_ERROR “Unable to read UTXO set”, as in Core. hash_type: “none” answers every field but a hash, the way Core’s own CoinStatsHashType::NONE does.

hash_or_height is refused the way an ordinary bitcoind, run without -coinstatsindex, already refuses it – !g_coin_stats_index (src/rpc/blockchain.cpp:1091-1092) is Core’s own gate, and this tree has no such index either: CoinStats only ever holds the current best block’s own commitment, nothing keyed by an earlier height. use_index is read and type-checked the way Core’s own RPCArg::Type::BOOL argument is, but changes nothing here: there is no non-indexed path for it to switch this tree onto, CoinStats being the only one there is.

transactions and disk_size are left out of every answer, the way Core’s own indexed answer already leaves them out (src/rpc/blockchain.cpp:1131-1134, if (!stats.index_used) {…}): both are an O(n) count over the whole set, which an incrementally maintained accumulator exists specifically to avoid paying on every call. total_unspendable_amount and block_info, CoinStatsIndex’s own two fields this tree could in principle also answer, are left out for a different reason: they need bookkeeping (the subsidy schedule, the BIP30/genesis/unclaimed-reward split) this branch does not add, and issue #639’s own “Not in scope” does not ask for them.

btclib_node.rpc.callbacks.get_tx_spending_prevout(node: Node, conn: RpcConnection, params: list[Any]) → list[dict[str, Any]][source]

Answer gettxspendingprevout: the mempool transaction spending each.

Core’s RPC (src/rpc/mempool.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag), without its -txospenderindex, which this node does not have: the answer is the mempool’s alone, so blockhash is never in it. Each answer is the outpoint’s own object, as given, with spendingtxid added where a mempool transaction spends it, and spendingtx too under return_spending_tx. Core’s mempool_only defaults to true where there is no index, and false asks for the index: an outpoint the mempool does not spend is then refused, as Core refuses it with the index unavailable. btclib-org/btclib-node#1501

btclib_node.rpc.callbacks.help_rpc(node: Node, conn: RpcConnection, params: list[Any]) → str[source]

Answer help; rpc.help.answer_help is the actual answer, node-free.

Every handler here shares this module’s own (node, conn, params) signature (this module’s own docstring); answer_help needs none of it, reading only params and the two tables rpc.help builds from HELP_TEXT and CATEGORY.

btclib_node.rpc.callbacks.import_mempool(node: Node, conn: RpcConnection, params: list[Any]) → Generator[__annotationlib_name_1__, None, __annotationlib_name_2__][source]

Answer importmempool: load a mempool.dat into the mempool.

Core’s own (src/rpc/mempool.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag), in its order: the argument types, a refusal during initial block download, then the options, each a bool or null for its default, unknown ones ignored. A file that cannot be read whole is refused. The file is read as the load goes, a transaction a step, as the load at start is, so peers and other calls are served between steps. The load ends refused where the node stops meanwhile, as Core’s ends on m_interrupt.

btclib_node.rpc.callbacks.invalidate_block(node: Node, conn: RpcConnection, params: list[Any]) → None[source]

Answer invalidateblock, Core’s own single blockhash argument.

Core’s own invalidateblock (rpc/blockchain.cpp:1716-1738, calling the free InvalidateBlock, :1695-1714, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag): _known_block_hash above is this function’s and reconsider_block’s own shared argument check; main.invalidate_chain’s own docstring is where marking the block, forcing the chain off it and what a storage failure on the way down answers with are each argued – RPC_DATABASE_ERROR, the one answer Core gives a failed ActivateBestChain here, is not reproduced, for the reason that docstring gives.

btclib_node.rpc.callbacks.list_banned(node: Node, conn: RpcConnection, _: list[Any]) → list[dict[str, Any]][source]

Answer listbanned, every unexpired ban in the list’s own order.

btclib_node.rpc.callbacks.ping(node: Node, conn: RpcConnection, _: list[Any]) → None[source]

Answer ping by sending every peer a fresh one, via ping_all.

A peer at BIP0031_VERSION or below is sent a ping with no nonce, as in Core. btclib-org/btclib-node#1204

Called on Node’s own thread, handle_rpc’s the same as every handler here; ping_all is defined on P2pManager but reaches this one call site as a plain method call, not a coroutine scheduled on that manager’s own loop.

btclib_node.rpc.callbacks.precious_block(node: Node, conn: RpcConnection, params: list[Any]) → None[source]

Answer preciousblock, Core’s own single blockhash argument.

Core’s own preciousblock (rpc/blockchain.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag): _known_block_hash checks the argument, and main.precious_chain prefers the block and retries the chain. Core answers RPC_DATABASE_ERROR where ActivateBestChain fails on its own storage; here that failure raises out of update_chain, and rpc.main._execute answers INTERNAL_ERROR, as for invalidate_block.

btclib_node.rpc.callbacks.prioritise_transaction(node: Node, conn: RpcConnection, params: list[Any]) → bool[source]

Answer prioritisetransaction: add a fee delta to a transaction.

Core’s own (src/rpc/mining.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag), in its order: the argument types, txid, dummy as a double (get_real, which refuses 1e400), fee_delta as an int64, then dummy again: refused with RPC_INVALID_PARAMETER unless it is null, omitted or zero. A transaction held with a dust output is refused where the mempool requires standard transactions, since one that pays a fee is not allowed to enter with it. The delta is kept for a transaction not held, and applied once it is (Mempool.prioritise). btclib-org/btclib-node#1502

btclib_node.rpc.callbacks.prune_blockchain(node: Node, conn: RpcConnection, params: list[Any]) → int[source]

Answer pruneblockchain: manually delete up to height, or a timestamp.

Core’s own pruneblockchain (rpc/blockchain.cpp:918-975, at bitcoin/bitcoin@ca7162cde5). Requires Config.pruned, matching IsPruneMode()’s own refusal (rpc/blockchain.cpp:936-938) – manual pruning (Config.prune_target_mib unset) and automatic pruning (set) both answer this RPC the same way, Core drawing no such distinction for it either; main._prune_chain is the one place the two differ.

height above _PRUNE_TIMESTAMP_TO_HEIGHT_THRESHOLD is read as a block time instead, by _height_from_timestamp above.

Refused the way Core refuses it, in Core’s own order and wording: a missing or wrongly typed height (RPCMethod::HandleRequest’s own generic argument check, same as get_block_hash above), a negative one (rpc/blockchain.cpp:945-947), a chain shorter than chain.prune_after_height (rpc/blockchain.cpp:962-963, Core’s own per-chain nPruneAfterHeight – 100000 on mainnet, 1000 elsewhere, chains.py’s own leaves carrying the line each comes from), and a height past the tip (rpc/blockchain.cpp:964-965). A height within MIN_BLOCKS_TO_KEEP of the tip is not refused, only clamped down to it (rpc/blockchain.cpp:966-969), and pruning still runs – that clamp’s own floor is MIN_BLOCKS_TO_KEEP, not prune_after_height, matching Core drawing the two apart too.

Answers block_db.BlockDB.pruned_up_to, Core’s own “height of the last block pruned” (rpc/blockchain.cpp:927-928) – this store already tracks exactly that height, so there is no index scan to answer it with the way Core’s own GetPruneHeight runs one.

btclib_node.rpc.callbacks.reconsider_block(node: Node, conn: RpcConnection, params: list[Any]) → None[source]

Answer reconsiderblock, Core’s own single blockhash argument.

Core’s own reconsiderblock (rpc/blockchain.cpp:1761-1785, calling the free ReconsiderBlock, :1741-1759, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag): _known_block_hash above is this function’s and invalidate_block’s own shared argument check; main.reconsider_chain’s own docstring is where clearing the mark and retrying the chain are argued.

btclib_node.rpc.callbacks.save_mempool(node: Node, conn: RpcConnection, _: list[Any]) → dict[str, str][source]

Answer savemempool: write mempool.dat now, and name it.

Core’s own (src/rpc/mempool.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag): refused until the load at start has ended, and where the file cannot be written. -persistmempoolv1 decides the version, and -persistmempool=0 does not refuse it.

btclib_node.rpc.callbacks.send_raw_transaction(node: Node, conn: RpcConnection, params: list[Any]) → str[source]

Answer sendrawtransaction: verify, add to the mempool, announce.

A transaction that fails to decode, that verify_mempool_acceptance refuses, or that Mempool.add_tx evicts right back out under its own size limit is each refused with the reject reason and code cited beside its own raise, below; one kept is broadcast to peers and its txid answered, and so is one whose txid is already held, without being verified again. One whose own outputs are already in the UTXO set, or whose burned or feerate cost exceeds maxburnamount or maxfeerate, is refused before either of those two, the order Core’s own BroadcastTransaction checks them in – _decode_and_precheck_raw_tx above is that first half.

btclib_node.rpc.callbacks.service_names(services: int) → list[str][source]

Return the service bits the way Core’s getpeerinfo names them.

serviceFlagsToStr, which is a walk over the set bits from the least significant up rather than over the names: a bit a member names contributes that name without the NODE_ prefix Core’s own enum carries, and a bit none names contributes “UNKNOWN[2^n]” rather than nothing. Core reserves a range of bits for temporary experiments and sends everything else through the BIP process, so a bit nobody here has heard of is a service and not an error – and dropping it would report a peer as offering less than it said it does.

btclib_node.rpc.callbacks.set_ban(node: Node, conn: RpcConnection, params: list[Any]) → None[source]

Answer setban, Core’s own checks in Core’s own order.

Core’s setban (src/rpc/net.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag). A subnet holding a slash is a subnet, and is otherwise one address, which has to be a valid one. Adding a ban drops every peer it matches.

btclib_node.rpc.callbacks.set_mock_time(node: Node, conn: RpcConnection, params: list[Any]) → None[source]

Answer setmocktime: hold the node’s clock at timestamp, regtest only.

Core’s own (src/rpc/node.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag), in Core’s order: the generic missing-argument and wrong-type refusals, then the chain gate – RPC_MISC_ERROR, as the plain std::runtime_error Core throws becomes – then the range, a non-integer number being “JSON integer out of range” as getInt answers it. A timestamp outside [0, MAX_MOCK_TIME] is RPC_INVALID_PARAMETER. MAX_MOCK_TIME is the v31.1 tag’s bound, nanoseconds::max() in seconds; master narrows it to uint32_t’s maximum (406c2348dd, “rpc: tighten setmocktime upper bound to UINT32_MAX”, read at bitcoin/bitcoin@badc957481), which v31.1 lacks. Every refusal here matches a regtest bitcoind v31.1.0.

The callback runs on Node’s thread between two steps of the loop, so no validation is in flight, as Core’s LOCK(cs_main) ensures. clock’s module docstring says which reads the mock time moves.

btclib_node.rpc.callbacks.set_network_active(node: Node, conn: RpcConnection, params: list[Any]) → bool[source]

Answer setnetworkactive: disable or enable all p2p activity.

Core’s own (src/rpc/net.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag): one required boolean, state, read by P2pManager.set_network_active – its own docstring argues the effect, Core’s CConnman::SetNetworkActive – and answered straight back, Core’s own connman.GetNetworkActive() read right after the call that set it.

btclib_node.rpc.callbacks.stop(node: Node, conn: RpcConnection, params: list[Any]) → str[source]

Answer stop; rpc.main._step delays this reply by wait, then stops.

A wait in milliseconds holds the reply back that long, Core’s own hidden testing argument (src/rpc/server.cpp:155-166, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag): “‘stop 1000’ makes the call wait 1 second before returning to the client”. Read and validated here, through stop_wait_param, exactly as every other declared argument is validated by the callback that owns it; not slept on here, unlike Core’s own UninterruptibleSleep, which this function has no equivalent of at all.

Core’s sleep runs once stop has already requested shutdown, on the request’s own HTTP worker thread, which that shutdown joins before it goes on (StopHTTPServer, src/httpserver.cpp, same tag). A time.sleep here would run before rpc.main._step requested this node’s shutdown at all, on the one thread that carries RPC, P2P and chain work alike (ARCHITECTURE.md, “The loop”). rpc.main._answer_one reads this same wait again once this call is known to have succeeded; rpc.main._step hands the delayed reply to RpcConnection.send_and_close_after and stops the node at once, and RpcManager.stop finishes that reply the way Core’s shutdown finishes its worker.

btclib_node.rpc.callbacks.stop_wait_param(params: list[Any]) → int | None[source]

Read stop’s own hidden wait, or None where none was given.

RPCArg::Type::NUM, RPCArg::Optional::OMITTED, hidden from help (src/rpc/server.cpp:155, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag): omitted or explicit null reads as isNum() false there, so neither delays the reply. Anything else that is not a JSON number is RPC_TYPE_ERROR, the same check RPCMethod::HandleRequest makes for every declared argument before the handler ever runs (src/rpc/util.cpp:653-661); a JSON float, or an integer outside C int’s range, is refused the way _height_param above already refuses a float, UniValue::getInt<int>’s own “JSON integer out of range” (univalue.h), thrown where std::from_chars cannot consume the number in full or reports it out of range.

Called twice for one request that reaches it: here, to decide whether stop itself succeeds, and again by rpc.main._answer_one once it has, to read the same already-valid wait back out and schedule the delayed reply stop’s own docstring explains (btclib-org/btclib-node#1467) – this function’s own return value is not stop’s, which is the RPC’s result field and cannot also carry it.

btclib_node.rpc.callbacks.submit_block(node: Node, conn: RpcConnection, params: list[Any]) → str | None[source]

Answer submitblock, Core’s own two arguments, the second ignored.

Core’s own submitblock (rpc/mining.cpp:1089-1136, at bitcoin/bitcoin@bb529657) decodes, indexes the header if it is new, and hands the block to ProcessNewBlock: None for one accepted, “duplicate” for one already held, and a reject reason for one refused. Some reasons are Core’s literally: “duplicate-invalid” for one whose header is marked invalid (main.is_cached_invalid), BlockValidationResult::BLOCK_MISSING_PREV’s own “prev-blk-not-found” (validation.cpp:4225, same sha), which this node’s own block_index.add_headers answers the identical way p2p.callbacks.block already reads it (missing rather than invalid), AcceptBlockHeader’s “bad-prevblk” for a parent marked invalid, and ContextualCheckBlockHeader’s bad-diffbits, time-too-old, time-timewarp-attack, time-too-new and “bad-version(0x%08x)”, and CheckBlockHeader’s high-hash, which add_headers raises in Core’s words (src/validation.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag). Any other invalid block is answered with btclib’s own exception message instead of one of Core’s: BlockValidationResult names dozens of distinct single-word reasons across validation.cpp, and this tree does not reproduce that vocabulary.

Stores through the same block_index/block_db calls p2p.callbacks.block makes for a block delivered over the wire, minus that callback’s own Connection-specific bookkeeping (remove_block_request), which does not apply to a block submitted out of band.

Where the stored block extends the active tip, main.update_chain is run right here rather than waited for on Node’s next pass: Core’s own ProcessNewBlock calls AcceptBlock and then ActivateBestChain – contextual and connect validation both – before it ever returns to submitblock (src/validation.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag), so a caller is answered only once that trial has actually run, and never told a block was accepted that its own contextual or script check refuses a moment later (ISS 1335, ISS 1390). _ready_fork is not gated on Node.status for exactly this reason (its own comment, btclib-org/btclib-node#1071): calling it here finds this same submission ready, or finds nothing and costs nothing. A block that does not extend the tip is stored and left for that later pass, as before – Core’s own ActivateBestChain runs unconditionally too, but a competing, lower branch is not what either issue measured, and this tree does not chase it synchronously.

main._validate_block’s own bad-txns-nonfinal and bad-cb-height are Core’s literal reasons already; interpreter.check_scripts wraps a script failure into BlockScriptVerifyError, whose own str() is Core’s block-script-verify-flag-failed (%s) (CheckInputScripts, same file and sha) with ScriptErrorString. A spend of an immature coinbase and one over its inputs are Core’s bad-txns-premature-spend-of-coinbase and bad-txns-in-belowout, the reason alone as GetRejectReason gives it, and so are bad-txns-accumulated-fee-outofrange and bad-blk-sigops. Anything else update_chain’s trial raises for this exact hash is answered with btclib’s own text, the same divergence the paragraph above already argues for every reason this function has no literal word for.

A failure update_chain’s own trial does not swallow into a rejection – this node’s own storage or bookkeeping, not the submission’s content – is not answered at all: it is left to propagate, Node.terminate_flag set first, so a caller reached from here instead of from Node’s own scheduled pass still stops the loop rather than running on past it.

btclib_node.rpc.callbacks.submit_header(node: Node, conn: RpcConnection, params: list[Any]) → None[source]

Answer submitheader: index one header alone, or refuse it.

Core’s own submitheader (rpc/mining.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag). hexdata is decoded as DecodeHexBlockHeader decodes it: is_hex, then the first eighty bytes, any after them ignored as Core’s SpanReader ignores them. A header whose parent this index does not hold is refused before any check. BlockIndex.add_headers then checks and indexes it, as ProcessNewBlockHeaders does, and None answers a header indexed now or already. A refusal answers the reason add_headers raises, Core’s word, such as duplicate-invalid, bad-prevblk, bad-diffbits or high-hash.

btclib_node.rpc.callbacks.test_mempool_accept(node: Node, conn: RpcConnection, params: list[Any]) → list[dict[str, Any]][source]

Answer testmempoolaccept, one verdict per raw tx in params[0].

One transaction is judged alone (_test_accept_alone), and several as one package (package.package_test_accept), as Core’s handler does (src/rpc/mempool.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag). Nothing is added to the mempool. A refusal is reported in the entry of the transaction it names; a fault that is not one propagates and ends the call, as Core’s handler has no catch-all either (btclib-org/btclib-node#668).

btclib_node.rpc.connection module

RpcConnection, one accepted HTTP socket carrying one or more requests.

Parses the header section off the wire, bounded by MAX_HEADER_BYTES and MAX_BODY_BYTES since both are read before any credential is checked, answers a request line, a request-target, a header field or a Content-Length Core’s listener cannot frame, and a chunked body it cannot read, with 400 or 413 (_HeadReader, _ChunkedReader), answers an Expect it does not meet with 417 and 100-continue with an interim 100 Continue, answers manager.interrupted with 503 once RpcManager.interrupt has set it (issue #1515), refuses a method or a path Core’s listener refuses before Core checks a credential (_refusal), answers a request whose Authorization header rpc.auth.RpcAuth does not accept with 401, and decodes the body of one it does accept, which rpc.manager.RpcManager.messages queues for rpc.main.handle_rpc. RawJSON is a JSON number written back out exactly as given, the way Core’s own UniValue writes one built from a string rather than from a float.

Each answer is framed as libevent frames it (_frame), in the version of the request it answers, and the socket is kept open across answers where libevent keeps it, the next request read off the same connection rather than requiring a fresh accept per call (issue #640).

The framing is the libevent bitcoind v31.1.0 links, not Core’s own source: bitcoin/bitcoin@9be056a8a7, the v31.1 tag, hands the socket to evhttp, and depends/packages/libevent.mk there pins 2.1.12-stable, read at libevent/libevent@5df3037 (http.c).

class btclib_node.rpc.connection.JSONEncoder(mark: str = '', **kwargs: Any)[source]

Bases: JSONEncoder

Encode bytes as hex and unwrap a RawJSON under a caller’s mark.

default below is json.dumps’s own hook for a type it has no built-in encoding for; it is what RpcConnection.async_send supplies cls= and mark= to, so that a RawJSON value comes out marked rather than quoted, for async_send to unquote once encoding is done – json itself has no hook for writing a literal unquoted.

default(obj: object) → Any[source]

Implement this method in a subclass such that it returns a serializable object for o, or calls the base implementation (to raise a TypeError).

For example, to support arbitrary iterators, you could implement default like this:

def default(self, o):
    try:
        iterable = iter(o)
    except TypeError:
        pass
    else:
        return list(iterable)
    # Let the base class default method raise the TypeError
    return super().default(o)
class btclib_node.rpc.connection.RawJSON(text: str)[source]

Bases: object

A JSON number written to the wire exactly as given, not from a float.

Core’s own UniValue(UniValue::VNUM, “<string>”) does the same: the value is built from a string and written out verbatim, whatever that string was, rather than round-tripped through a floating-point type on the way out. ValueFromAmount (src/core_io.cpp:283-293, at bitcoin/bitcoin@58a7869f86) is the caller this exists for – rpc.callbacks.get_mempool_info’s own mempoolminfee, an exact eight-decimal BTC amount a Python float cannot always carry: repr fixes no decimal places and emits exponent notation (1e-06) at a magnitude ordinary for a feerate, which Core’s own %d.%08d format never does.

json.JSONEncoder.default cannot return this directly – its return value is re-encoded through the same machinery rather than written as-is, and Python’s json has no hook for a raw literal. JSONEncoder.default below returns a marked placeholder instead, and RpcConnection.async_send substitutes it, quotes and all, for text once encoding has already run.

The mark is not a fixed word: a fixed one is not actually safe – a plain string value that happens to contain it once, unpaired (an error message echoing back a client’s own malformed method name, say), lets a regex substitution’s own non-greedy match run past that string’s closing quote and merge it with an unrelated placeholder later in the same response, corrupting both. RpcConnection.async_send passes a fresh random token instead, one per call, so a legitimate value colliding with it is not a realistic risk the way colliding with a guessable word is.

class btclib_node.rpc.connection.RequestHead(raw: bytes, method: bytes, target: bytes, version: tuple[int, int] | None, proxy: bool, fields: tuple[tuple[bytes, bytes], ...], size: int, chunked: bool, length: int, expects_continue: bool, error: MalformedRequestHeadError | OversizedRequestBodyError | UnmetExpectationError | None)[source]

Bases: object

One request’s own header section, and what its answer is framed by.

raw is the octets read for it, which serialize gives back – the same round-trip tests/fuzz_corpus_test.py already holds p2p.transport.frame_message_bytes to. consumed is its length.

method and target are the request line’s first part and its middle, b”” where the line did not split, and version is None where libevent had not read it. proxy is libevent’s EVHTTP_PROXY_REQUEST (_is_proxy_request). fields is every field _FieldReader read, in order, a chunked body’s trailer appended once read, and size the octets it counted. chunked is evhttp_get_body’s own test, a Transfer-Encoding of chunked, and length the body’s Content-Length where it is not. expects_continue is its Expect: 100-continue, which RpcConnection._read_body answers 100 Continue where nothing of the body has arrived yet.

error is what libevent refuses the request for, answered with its error page, fields then holding what was read before it; method is then what it knows of the request, which decides whether a CONNECT keeps its connection, the next request read from the line after the one refused.

raw and fields hold the Authorization field, so repr leaves them out (section 7 of the btclib-org standard, A refusal carries no secret).

property authorization: str | None

The first Authorization field’s value, a trailer’s included.

property connection: str | None

The first Connection field’s value.

property consumed: int

How many octets the section took off the front of its buffer.

field(name: bytes) → str | None[source]

Return the first name field’s value, None where there is none.

evhttp_find_header, comparing names ASCII case-insensitively, as bytes.lower does. The value is decoded as Latin-1, where str.lower changes no character into an ASCII one.

property proxy_connection: str | None

The first Proxy-Connection field’s value.

serialize() → bytes[source]

Reproduce the exact octets the section was read from.

class btclib_node.rpc.connection.RpcConnection(loop: AbstractEventLoop, client: socket.socket, manager: RpcManager, connection_id: int, request_timeout: float | None = 30.0)[source]

Bases: object

One accepted RPC socket, from the header read through the reply.

RpcManager.server builds one per client _accept_loop queues, on this manager’s own thread; run below is scheduled on the same loop and reads the request off client, queuing it onto manager.messages for rpc.main.handle_rpc on Node’s own thread to answer, through send or send_and_wait.

async async_send(reply: HttpReply, *, close: bool = False) → None[source]

Write reply back as one JSON-RPC HTTP reply.

Wraps any RawJSON value in a fresh per-call mark before encoding, substitutes it back out unquoted once encoding is done, and frames the result as _frame does, which also decides what happens once the reply is on the wire: client closes, or this reads another request off the same socket (issue #640). A reply with no body is rpc.jsonrpc.NO_CONTENT, which bitcoind writes with no Content-Type. close is the Connection: close Core’s HTTPRequest::WriteReply adds once shutdown has begun.

close() → None[source]

Close client.

Cancelling whatever this connection is doing – reading a request, writing a reply – is RpcManager.stop’s own job: its asyncio.all_tasks(self.loop) sweep already reaches whichever task is actually live for this connection, cancelled and driven to completion before this is ever called, so this method does not need a handle of its own to end one – an earlier version kept one anyway (self.task), set once at accept and never again, so past a connection’s first request it named a long-finished Future and cancelled nothing (issue #714). Core’s own per-connection object, HTTPRemoteClient, carries no such handle either: HTTPServer::ClearConnectedClients (src/httpserver.cpp:1160-1167, at bitcoin/bitcoin@ca7162cde5), its own shutdown-time sweep, drops whatever is left in m_connected the same unconditional way, once its own socket-handling thread has already been joined, rather than reaching into a live worker to end it.

async run() → None[source]

Read one request off client and queue it for handle_rpc.

Reads the header section a line at a time, as _HeadReader does, then the body, up to its own Content-Length or as _ChunkedReader reads a chunked one, both bounded against an unterminated or overstated one and, together, against taking longer than self.request_timeout – REQUEST_TIMEOUT’s own docstring is where that bound is argued against Core’s. A body that is not valid JSON is answered PARSE_ERROR directly, on the spot, and a body that is gets appended to manager.messages for rpc.main.handle_rpc to answer instead, through send. Any failure – asyncio.timeout raises the standard library’s own TimeoutError once expired, caught below like any other – closes client rather than raising, since nothing reads the Future this task runs under.

In the order Core answers them, and none of them queued: a header section _HeadReader refuses, an Expect it does not meet, or a chunked body _ChunkedReader refuses, is answered 400, 417 or 413 by _send_framing_error, as soon as it is refused; a method outside _LIBEVENT_METHODS is answered 501; manager.interrupted is answered 503, by _refused_early ahead of everything below it, or by _send_shutdown_refusal where it is set only once _refused_early has let the request through (issue #1515); a method or a target _refusal refuses is answered by _send_refusal, whatever the credential; a request whose Authorization header manager.auth does not accept is answered 401 by _send_unauthorized, its body read off the socket and never decoded; and one whose decoded body manager.auth.refusal refuses is answered by _send_whitelist_refusal.

Called again, by async_send below, for every request after the first one a kept-alive connection carries – what this request takes is taken off the front of self.buffer as it is read, so a second call starts on what is left rather than re-reading bytes this one already consumed.

send(reply: HttpReply) → None[source]

Schedule async_send on loop, from handle_rpc’s own thread.

Once Node.terminate_flag is set, the reply carries the Connection: close Core’s HTTPRequest::WriteReply adds once shutdown has begun (src/httpserver.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag).

send_and_close_after(reply: HttpReply, delay: float) → None[source]

Write reply delay seconds from now, on this connection’s loop.

rpc.main._step is the only caller, for a stop carrying a positive wait (btclib-org/btclib-node#1467), and returns at once to set Node.terminate_flag, as Core’s own stop requests shutdown before it sleeps. The wait runs on loop, and RpcManager.stop finishes it rather than cancelling it, so the reply still reaches the client once that shutdown is under way; close=True for the reason send_and_wait above gives. The moment the wait ends is recorded through RpcManager.extend_reply_deadline, for Node.stop to wait for.

send_and_wait(reply: HttpReply) → None[source]

Like send, but block up to 2 seconds for the write to finish.

rpc.main._step is the only caller, for a stop request: the client has to see its own reply before node.stop() starts tearing loop down under it. Writes Connection: close and closes, whatever the request asked for – RpcManager.stop, called right after this returns, tears the whole loop down, so there is no next request this connection could still answer.

btclib_node.rpc.connection.btc_amount(sats: int) → RawJSON[source]

Format a satoshi amount as Core’s own exact BTC string.

Core’s own ValueFromAmount (src/core_io.cpp:285-296, at bitcoin/bitcoin@9be056a8a7): integer amount / COIN and amount % COIN, formatted %d.%08d – exact at every magnitude, where a Python float division (sats / 1e8) serializes through repr, which fixes no decimal places and emits exponent notation (1e-06) at a magnitude ordinary for a feerate. A negative amount, which a decoded output can carry (CAmount is signed), keeps its sign in front, as Core’s own version places it.

btclib_node.rpc.connection.parse_request_head(data: bytes) → RequestHead[source]

Parse one request’s header section off the front of data.

The framing half of what RpcConnection.run does, pulled out so fuzz/fuzz_rpc_head.py can drive it over raw octets the way Core’s own http_request.cpp fuzz target drives HTTPRequest::LoadControlData/LoadHeaders over a raw http_buffer (at bitcoin/bitcoin@ca7162cde5) – scoped the same way that target is: request-line and header-field framing and the Content-Length drawn from them, never the JSON-RPC body those bytes go on to carry, which is stdlib json’s own business (run below) and not this node’s.

Read as _HeadReader reads a section. Raises IncompleteRequestHeadError where data holds no whole section and libevent would wait for more – run’s own call site never hits this, since it reads more instead, but a fuzzed byte string has no such guarantee. Raises MalformedRequestHeadError, answered 400, for a section libevent refuses, UnmetExpectationError for an Expect it answers 417, and OversizedRequestBodyError for a Content-Length past MAX_BODY_BYTES, which libevent answers 413.

btclib_node.rpc.errors module

How a callback refuses a request rather than failing on it.

exception btclib_node.rpc.errors.RpcError(code: RPCErrorCode, message: str)[source]

Bases: Exception

A request this node refuses, named by the answer it is owed.

rpc.jsonrpc.JsonRpcRequest.reply turns it into the reply’s error object, so raising it is how a callback says which of the two was wrong, the request or the node. Opposite in direction from bitcoin_core_rpc.RpcError, which names an error a node’s answer already carries – this one is raised here, not read off a reply.

btclib_node.rpc.errors.bool_mismatch(params: list[Any], position: int, *, name: str) → tuple[int, str, object, str] | None[source]

Return type_errors’ own mismatch tuple for a wrongly typed bool.

Omitted or explicit null is never a mismatch – bool_param below reads either as the argument’s own declared default, the same reading this function shares with it. Split out of bool_param so a caller checking more than one declared argument’s type can collect every mismatch before raising, as RPCMethod::HandleRequest checks every declared argument’s type before any of them is raised on (type_errors’ own docstring), rather than stopping at the first the way a caller with only one bool to check, below, still does. position is the zero-based index into params; type_errors wants Core’s own one-based count, so the tuple carries position + 1.

btclib_node.rpc.errors.bool_param(params: list[Any], position: int, *, name: str, default: bool) → bool[source]

Read a declared RPCArg::Type::BOOL parameter, Core’s own way.

Omitted or explicit null both stand for the argument’s own declared default. Anything else is read, and refused with RPC_TYPE_ERROR where it is not an actual JSON bool – the same check RPCMethod::HandleRequest makes for every declared argument before the handler body runs at all (src/rpc/util.cpp:653-661), applied here to the one JSON type this helper’s every caller declares. position is the zero-based index into params, the way every caller here already addresses it; bool_mismatch above is this same check, split out for a caller checking more than one declared argument’s type at once.

btclib_node.rpc.errors.is_hex(text: str) → bool[source]

Core’s IsHex: a non-empty, even-length string of hexadecimal digits.

src/util/strencodings.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag. bytes.fromhex skips whitespace between bytes, and so does btclib’s bytes_from_octets; IsHex refuses it, so a string is checked here before either decodes it. btclib-org/btclib-node#1372

btclib_node.rpc.errors.parse_hash_v(name: str, value: str) → bytes[source]

Answer Core’s own ParseHashV: a hash from its own 64-character hex.

ParseHashV (src/rpc/util.cpp:116-124, at bitcoin/bitcoin@9be056a8a7) checks the string’s own length before it ever tries to decode it: uint256::FromHex answers nullopt for anything but exactly 64 characters, so a wrong length is “<name> must be of length 64 (not <n>, for ‘<value>’)” even where every character is a valid hex digit (“aabb”, four of them) – and only a 64-character string that is not all hex digits reaches the second message, “<name> must be hexadecimal string (not ‘<value>’)”: FromHex takes digits only, so whitespace, which bytes.fromhex skips, is refused here. name is each call site’s own choice, matching Core’s: “hash” for getblockheader, “blockhash” for getblock, “txid” for gettxout (src/rpc/blockchain.cpp:678,828,1258, same sha), and “parameter 1”/”parameter 3” for getrawtransaction’s own two hash arguments, Core’s own names for them (src/rpc/rawtransaction.cpp:304,317, same sha).

btclib_node.rpc.errors.type_error(position: int, name: str, value: object, expected: str) → RpcError[source]

Refuse a declared argument’s own JSON type, Core’s own wrapped shape.

RPCMethod::HandleRequest’s own type check (src/rpc/util.cpp :652-661, read at bitcoin/bitcoin@b91d983f66) collects every mismatched argument into one UniValue object, keyed strprintf(“Position %s (%s)”, i + 1, arg.m_names), and wraps it in strprintf(“Wrong type passed:n%s”, arg_mismatch.write(4)) – UniValue::write’s own four-space indent and lack of a trailing newline after the closing brace (src/univalue/lib/univalue_write.cpp), reproduced literally in type_errors rather than through a JSON encoder: every key and value is text this tree writes itself, with nothing to escape. Measured against a real bitcoind (v31.1.0, -regtest) answering a raw testmempoolaccept, getblockheader, getblockhash, getrawtransaction and sendrawtransaction call each with one argument of the wrong JSON type.

position is the argument’s own one-based position among the method’s declared arguments, the way Core counts it (i + 1), and name is Core’s own declared name for it – arg.m_names itself, the raw field the key above is built from, not GetFirstName()’s |-trimmed form (m_names.substr(0, m_names.find(‘|’)), src/rpc/util.cpp:917-920), which only RPCArg::ToString reads, for the usage string, and which HandleRequest’s own type check never calls. The two coincide for every argument checked here except getrawtransaction’s own second one, declared “verbosity|verbose” – get_raw_transaction’s own verbose is neither the raw m_names this key is built from nor GetFirstName()’s trimmed form, for the reason _parse_txid’s own usage-string comment argues.

btclib_node.rpc.errors.type_errors(*mismatches: tuple[int, str, object, str]) → RpcError[source]

Refuse every mismatched argument at once, in one object.

Each mismatch is type_error’s own four arguments, in the order Core checks the arguments, first to last: its object holds one key per argument that failed, as the one type_error builds holds one.

btclib_node.rpc.fees module

estimatesmartfee and estimaterawfee, Core’s src/rpc/fees.cpp.

Read at bitcoin/bitcoin@9be056a8a7, the v31.1 tag: the same arguments, refusals, answers and units, from Node.fee_estimator.

btclib_node.rpc.fees.estimate_raw_fee(node: Node, conn: RpcConnection, params: list[Any]) → dict[str, Any][source]

Answer estimaterawfee: each horizon tracking conf_target.

btclib_node.rpc.fees.estimate_smart_fee(node: Node, conn: RpcConnection, params: list[Any]) → dict[str, Any][source]

Answer estimatesmartfee.

The estimate is raised to the mempool’s minimum feerate and to -minrelaytxfee, as Core raises it. unset is economical.

btclib_node.rpc.help module

Every served RPC’s own Core help text, and help itself.

HELP_TEXT is RPCHelpMan::ToString’s own literal answer for each method this node serves (src/rpc/blockchain.cpp, src/rpc/net.cpp, src/rpc/mempool.cpp, src/rpc/mining.cpp, src/rpc/server.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag) – read back from a regtest bitcoind v31.1.0’s own help <command>, the way disconnectnode’s own help text already was before this module existed (btclib-org/btclib-node#1193). rpc.main._execute raises this same text under RPC_MISC_ERROR for a call outside its method’s declared argument count – RPCMethod::HandleRequest’s own HelpResult, caught by ExecuteCommand (src/rpc/server.cpp:874-887, at bitcoin/bitcoin@b91d983f66) – and every callback in rpc.callbacks raises it in place of its own former one-line usage string for a call short of a required argument or carrying a value self.ToString() refuses in Core, both being the identical std::runtime_error(self.ToString()) shape (measured against addnode and setban’s own invalid-command refusal, byte for byte). help_rpc below answers it for a command named explicitly, and un-truncated, where Core’s own bare listing keeps only each entry’s first line.

The vsize_adjusted, vsize and vsize_bip141 lines of getmempoolentry, getrawmempool and testmempoolaccept are Core 32’s (src/rpc/mempool.cpp, at bitcoin/bitcoin@aef8a04966), laid out as RPCHelpMan::ToString lays them out. No bitcoind carrying them was read back (btclib-org/btclib-node#1757).

CATEGORY is each command’s own heading in Core’s help’s bare listing (CRPCTable::help, src/rpc/server.cpp:69-117, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag), sorted the way that function sorts vCommands: by category, and by name within it. help_rpc groups this node’s own served commands under those same headings and in that same order, the way Core’s own bare listing would if run against a bitcoind serving only this node’s own method table – the entries CATEGORY marks “hidden” being this table’s hidden ones, category == “hidden” is left out of that listing the same way Core’s own bare listing leaves a category == “hidden” entry out of its (answer_help’s own docstring is where that check is argued, _BARE_LISTING’s own comment where it is made real). A hidden command’s own help still answers in full for help <command> named explicitly – HELP_TEXT carries every served method alike, hidden or not, and only the bare listing’s own construction reads CATEGORY.

btclib_node.rpc.help.answer_help(params: list[Any]) → str[source]

Answer help: every served command’s usage, or one command’s own.

With no argument (or an empty string, its own declared default), Core’s own bare listing (CRPCTable::help, src/rpc/server.cpp, same tag), grouped by category and truncated to each entry’s own usage line the way that function’s own strHelp.substr(0, strHelp.find(’n’)) truncates it – restricted to the commands rpc.callbacks.callbacks actually serves, and, among those, to the ones CATEGORY does not mark “hidden”: _BARE_LISTING’s own construction (module level, below CATEGORY) drops that category from the set it sorts headings out of, the same continue CRPCTable::help’s own loop makes on pcmd->category == “hidden” for its strCommand == “” arm (src/rpc/server.cpp:87, same tag). With a command’s name, that command’s own untruncated help – addconnection, invalidateblock and reconsiderblock included, Core’s own loop answering a named hidden command exactly as it answers any other, that same line’s || never reached once strMethod == strCommand – or, for a name nothing here serves, Core’s own literal “help: unknown command: %s” (src/rpc/server.cpp:114) – a successful reply, not a refusal, matching Core answering it as RPCResult::Type::STR rather than raising. rpc.callbacks.help_rpc is the shared-signature wrapper handle_rpc actually dispatches to, this function taking params alone since it reads no node state.

btclib_node.rpc.jsonrpc module

Core’s JSON-RPC envelope: what a request is read as, and how it is answered.

Read at bitcoin/bitcoin@9be056a8a7, the v31.1 tag: JSONRPCRequest and JSONRPCReplyObj in src/rpc/request.h and src/rpc/request.cpp, and JSONErrorReply in src/httprpc.cpp. Core answers a request by the version it names. A request with no jsonrpc, or with “1.0”, gets the legacy answer: an error is an HTTP error status, and the reply carries result and error both. A “2.0” request gets the JSON-RPC 2.0 envelope, and HTTP 200 for any error its method raises; a 2.0 request with no id is a notification, run and answered with no body.

class btclib_node.rpc.jsonrpc.HttpReply(status: str, body: dict[str, Any] | list[Any] | None)[source]

Bases: NamedTuple

The status line and the JSON body RpcConnection.async_send writes.

body is None only for NO_CONTENT, which carries no body.

body: dict[str, Any] | list[Any] | None

Alias for field number 1

status: str

Alias for field number 0

class btclib_node.rpc.jsonrpc.JsonObject(pairs: list[tuple[str, Any]])[source]

Bases: dict[str, Any]

A JSON object as Core’s UniValue reads one, a key named twice included.

UniValue::read keeps every pair in the order the text gives them, and find_value, what JSONRPCRequest::parse reads each field through, answers the first pair holding a key; UniValue::write writes every pair back (src/univalue/lib/, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag). So a lookup here answers a key’s first value, and items, which json.dumps writes an object from, answers every pair.

Every other view – iteration, keys, values, len, repr – is the plain dict’s, one pair per key, and items answers the pairs as decoded whatever is written in since. A decoded object is read, never mutated.

items() → list[tuple[str, Any]][source]

Return a set-like object providing a view on the dict’s items.

class btclib_node.rpc.jsonrpc.JsonRpcRequest[source]

Bases: object

Core’s JSONRPCRequest: the fields parse reads off a request object.

parse fills them in the order Core’s does and raises RpcError where Core throws, so what a refused request is answered with is what parse had read by then. A fresh request has a null id and reads as legacy, which is what a body that is not a request object at all is answered with. Core parses every member of a batch into one JSONRPCRequest, so a member refused before its own id is read is answered with the previous member’s id and version; handle_rpc reuses one of these across a batch for that reason.

property is_notification: bool

Whether Core runs this request and answers nothing for it.

parse(request: object) → None[source]

Read request as JSONRPCRequest::parse does.

reply(result: object = None, error: RpcError | None = None) → dict[str, Any][source]

Build JSONRPCReplyObj’s answer to this request.

2.0 carries “jsonrpc”:”2.0” and only one of result and error; legacy carries both, one of them null. id is written only where the request had one.

btclib_node.rpc.jsonrpc.decode(body: bytes | bytearray) → Any[source]

Decode a request body, each object a JsonObject.

Raises ValueError where json.loads does, where the text holds NaN, Infinity or -Infinity, which json.loads reads and Core’s UniValue::read does not, and where a string or an object key holds a lone surrogate. json.loads reads “ud800” with no low surrogate after it, and a UTF-8 encoding of one, as a one-character string. Core’s JSONUTF8StringFilter refuses both (src/univalue/include/univalue_utffilter.h, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag), and HTTPReq_JSONRPC answers the whole body as a parse error.

btclib_node.rpc.jsonrpc.error_reply(code: RPCErrorCode, message: str) → HttpReply[source]

Answer an error raised before any request object was read.

JSONErrorReply with a fresh JSONRPCRequest: the legacy envelope, “id”:null, and the status error_status maps code to.

btclib_node.rpc.jsonrpc.error_status(code: int) → str[source]

Return the HTTP status JSONErrorReply answers error code with.

btclib_node.rpc.jsonrpc.get_real(value: float) → float[source]

Return a JSON number as UniValue::get_real does.

Raises the RPC_MISC_ERROR Core throws where no double holds it (src/univalue/lib/univalue_get.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag): 1e400, or a whole number as large. ParseDouble reads with istream >> double, which in libstdc++ fails on overflow only, so 1e-400 reads as 0. A macOS build of Core (libc++) refuses that too; this tree follows the Linux release, which links libstdc++ statically (contrib/guix/libexec/build.sh:234). The caller has checked it is a number.

btclib_node.rpc.jsonrpc.transform_named_arguments(params: dict[str, Any], arg_names: tuple[str, ...], named_only: tuple[str, ...] = ()) → list[Any][source]

Map params’ keys onto positions as transformNamedArguments does.

src/rpc/server.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag. arg_names is the method’s own, a|b two names for one position. named_only are the names of an OBJ_NAMED_PARAMS argument’s own options: those given are gathered into one object, which fills that argument’s position, and giving that argument too is refused. A position left out ahead of one given is a JSON null, and one left out after the last given is not there at all. An args array holds the leading positions, the named ones filling in after it, and an args that is not an array is dropped. Every pair params holds is read, so a key named twice is refused, as it is in Core; so is a position given both ways, and a key no position names.

Core names the first unknown key its std::unordered_map iterates over, an order the C++ standard leaves to the library, so no fixed order matches Core’s: bitcoind v31.1.0 on macOS names the last of them in the request’s own order for some sets of keys and not for others. The last is the one named here.

btclib_node.rpc.main module

handle_rpc and resume_rpc, called on each pass of Node’s loop.

handle_rpc pops one decoded request body off RpcManager.messages, reads it the way Core’s HTTPReq_JSONRPC does (src/httprpc.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag), and dispatches each request through rpc.callbacks.callbacks by method name. rpc.jsonrpc is where a request is parsed and where the answer’s envelope and HTTP status come from.

Core runs each request on an HTTP worker thread of its own, so a method that waits for the tip, or searches nonces, holds that thread alone. Here every method runs on Node’s thread, which owns the state it reads (ARCHITECTURE.md). Such a method returns a generator instead of its result: each step yields True where it did work and False where it only checked whether to go on waiting, and the generator returns the result. handle_rpc runs a request’s first step; a request not answered by then waits in Node.pending_rpc, and resume_rpc runs one step of each such request on every pass, so the loop goes on serving peers, other requests and stop between steps. Once Node.terminate_flag is set, each of these methods ends at its next step, as Core’s ends on m_interrupt.

btclib_node.rpc.main.answer_warmup(node: Node, conn: RpcConnection, body: object) → HttpReply[source]

Answer body while the node is in warmup, from the RPC manager’s thread.

Node’s thread is opening the stores then, so RpcConnection.run calls this instead of queuing the request. _execute refuses at its first line, so no step yields and no callback runs here.

btclib_node.rpc.main.get_connection(manager: RpcManager, connection_id: int) → RpcConnection | None[source]

Look up connection_id in manager.connections, or None.

btclib_node.rpc.main.handle_rpc(node: Node) → None[source]

Pop one request body off node.rpc_manager.messages and answer it.

An object is a lone request, an array a batch, and anything else is PARSE_ERROR’s “Top-level object parse error”, as in Core. A stop request’s reply reaches the client before the loop it arrived on is torn down: waited on before node.stop() runs, or, where stop carries a positive wait, handed to RpcConnection.send_and_close_after, whose delayed write RpcManager.stop finishes, with node.stop() run at once – Core’s own stop requests shutdown before it sleeps (btclib-org/btclib-node#1467).

A request still waiting after its first step goes to node.pending_rpc, for resume_rpc.

conn_id is left in manager.connections: RpcConnection.async_send removes it, on the branch that closes conn, once conn is done answering. conn.send below only schedules that reply, so a pop here would race async_send reading the next request off a kept-alive connection and remove the entry that request’s answer needs (issue #688).

btclib_node.rpc.main.resume_rpc(node: Node) → bool[source]

Run each request in node.pending_rpc one step, answering those done.

Answers whether any step did work, an answer included, which keeps Node’s loop from sleeping. Each answer pushes rpc_manager’s reply deadline forward, as Node._drain_message_queues does for a request handle_rpc answers (btclib-org/btclib-node#1651). A step that raises drops its request, which is taken off the queue first.

btclib_node.rpc.manager module

RpcManager, the thread listening for JSON-RPC connections.

Runs its own asyncio loop, with a RpcConnection per socket _accept_loop accepts from an allowed source – one request or several, connection.RpcConnection’s own docstring has the keep-alive that decides which – and queuing what each one parses onto messages for Node’s own thread to read in rpc.main.handle_rpc. listening is what a caller waits on rather than is_alive() alone, that flag being true before anything is bound. auth is who may call it, and which methods. run binds, then writes the cookie where one is written, then sets listening, so a client that waits on listening finds the cookie there; stop deletes it. That is the order of Core’s AppInitServers (src/init.cpp:748-761, at bitcoin/bitcoin@9be056a8a7): InitHTTPServer binds before StartHTTPRPC writes the cookie, so a bind that fails leaves no cookie behind. start_listener is how Node learns that either step failed, which Core turns into an InitError.

At most max_connections clients are held at once, Core’s -rpcmaxconnections (config.DEFAULT_MAX_HTTP_CONNECTIONS has the default and the version that sets it). At the limit the accept loops stop accepting, so a new client waits in the kernel’s queue, holding no descriptor of this process, until a held one leaves, as HTTPServer::GenerateWaitSockets leaves it (src/httpserver.cpp, at bitcoin/bitcoin@649bc0a645). _accept_loop has the one client per listening socket that can be accepted past it.

class btclib_node.rpc.manager.RpcManager(node: Node, port: int | None)[source]

Bases: Thread

The thread listening for JSON-RPC connections.

The module docstring above is where its own loop and the boundary with Node’s thread are argued; connections and messages are this class’s own state for that, and _accept_queue is server’s own, kept here only so a test can reach it directly.

answer_warmup(conn: RpcConnection, body: object) → HttpReply[source]

Answer body, a decoded request, as a node in warmup does.

Called by RpcConnection.run holding queue_lock, in_warmup set.

create_connection(loop: AbstractEventLoop, client: socket) → RpcConnection[source]

Wrap client in a RpcConnection and register it under a new id.

extend_reply_deadline(deadline: float) → None[source]

Push latest_reply_deadline to deadline, never back.

Called on Node’s thread alone: by RpcConnection.send_and_close_after for a stop RPC’s delayed reply (btclib-org/btclib-node#1467), by Node._drain_message_queues and Node._drain_rpc_queue once per request they answer, and by stop for the replies it finishes. Each is progress exactly as the others are, and Node.stop’s wait loop reads latest_reply_deadline without caring which moved it. deadline is the caller’s own time.monotonic() reading, taken on its own thread rather than this method’s, so that a caller answering several requests in a row times each push at the moment that request actually finished.

finish_warmup() → None[source]

Core’s SetRPCWarmupFinished: queue requests for Node again.

forget_connection(connection_id: int) → None[source]

Drop connection_id from connections, freeing its place.

Called on this manager’s loop, as its connection closes.

interrupt() → None[source]

Stop accepting new RPC work, without waiting for this thread.

Core’s InterruptHTTPServer (src/httpserver.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag): swaps in the request callback that answers 503 and calls g_threadpool_http.Interrupt(), both ahead of StopHTTPServer’s own Stop(), so a request already queued keeps draining in the background while a new one is refused at once rather than either queued or left for stop to close unanswered. Node._drain_rpc_queue calls this before it drains, which is what bounds that drain to what was queued before this call (btclib-org/btclib-node#1515).

latest_reply_deadline() → float | None[source]

Answer the latest deadline extend_reply_deadline has recorded.

None where it has recorded none. Never lowered once a reply is sent: Node.stop has why.

reply_ended(reply: object) → None[source]

Forget reply, written, given up on or failed; once or again.

Called as the reply’s write ends and again as its task does: on this manager’s loop, or on Node’s thread where a task it handed over had already ended by the time it asked to be told. Only stop’s own wait awaits _reply_ended, so a set from Node’s thread while this loop runs on its own wakes nothing. reply is what the running task’s get_coro answers, which None or any coroutine not recorded leaves replies as it was.

run() → None[source]

Method representing the thread’s activity.

You may override this method in a subclass. The standard run() method invokes the callable object passed to the object’s constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively.

async server(loop: AbstractEventLoop, server_sockets: Sequence[__annotationlib_name_1__]) → None[source]

Accept connections off server_sockets until cancelled by stop.

Awaits _accept_queue for what _accept_loop fills, a task of its own per listening socket, one RpcConnection and one conn.run task per socket _accept_loop queues – rather than a bare await loop.sock_accept(…) right here, which does not have the property the comment below argues for.

set_warmup_status(status: str) → None[source]

Core’s SetRPCWarmupStatus: the message a warmup answer carries.

start_listener() → bool[source]

Start this thread, and answer whether it came up listening.

Blocks until run has bound and written the cookie, or failed to: what Node.run turns into Core’s InitError, where start alone would leave the node running without its listener.

start_warmup() → None[source]

Core’s SetRPCWarmupStarting: answer requests RPC_IN_WARMUP.

stop() → None[source]

Stop this manager’s loop, join its thread, and close every socket.

Once the thread has ended: cancels server, which stops this manager listening, finishes the replies in replies through _finish_replies while every connection goes on reading, then cancels whatever is left and closes every connection (btclib-org/btclib-node#1539, btclib-org/btclib-node#1545).

Guarded on is_alive for the node that never started this thread at all; the long comments below argue why the handle this schedules is cancelled unconditionally afterward, why the pending-task sweep runs as its own pass rather than folded into one combined loop, and why closing _server_sockets here does not race server’s own ExitStack.

Sets interrupted too, unconditionally: Core’s ThreadPool::Stop sets m_interrupt = true itself rather than relying on a prior Interrupt() call, and a caller here that goes straight to stop – every test that never calls Node, and RpcManager.stop’s own callers before btclib-org/btclib-node#1515 – gets the identical guarantee: nothing reaches messages once this method has begun.

track_reply(reply: Coroutine[__annotationlib_name_1__, __annotationlib_name_2__, None], due: float) → None[source]

Record reply, whose write is due to begin by due.

due is a time.monotonic() value. Called before reply is handed to this manager’s loop, never from inside it: a task recording itself on its own first step is missed by a stop whose loop.stop this loop delivers in the same pass that creates that task, and is then cancelled with the rest.

btclib_node.rpc.mining module

The mining RPCs, and the three that wait on the same tip.

Core’s generatetoaddress, generateblock and getblocktemplate are in src/rpc/mining.cpp, and waitfornewblock, waitforblock and waitforblockheight in src/rpc/blockchain.cpp, where each waits through the mining interface’s waitTipChanged, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag. Each handler has rpc.callbacks’ signature and runs on Node’s thread, so it may build a block and hand it to update_chain without a lock (ARCHITECTURE.md). btclib_node.mining builds and checks the blocks.

The nonce search of generatetoaddress and generateblock, a getblocktemplate long poll and the three waits are generators that rpc.main resumes on each pass of Node’s loop, where Core runs them on an RPC thread of their own.

btclib_node.rpc.mining.generate_block(node: Node, conn: RpcConnection, params: list[Any]) → Generator[bool, None, dict[str, Any]][source]

Answer generateblock: mine one block of exactly the given transactions.

Core’s generateblock (src/rpc/mining.cpp): the block pays the subsidy to output, an address or a descriptor, and holds the transactions in the order given, a txid being looked up in the mempool. The block is checked as TestBlockValidity checks it and refused with RPC_VERIFY_ERROR and the reason, which is Core’s word where btclib_node.mining has one. Core’s debug message after the reason is left off: check_block_validity answers the reason alone, as BIP22 does, where Core’s ToString adds the debug text here. It is submitted unless submit is false, and answered as hex then too. The block is checked here, and the search is the generator returned.

btclib_node.rpc.mining.generate_to_address(node: Node, conn: RpcConnection, params: list[Any]) → Generator[bool, None, list[bytes]][source]

Answer generatetoaddress: mine nblocks blocks paying address.

Core’s generateBlocks (src/rpc/mining.cpp): each block holds what the mempool offers, and mining stops early where maxtries is spent, or the node stops, answering the hashes of the blocks found. A negative maxtries is read as the unsigned number it converts to, as Core’s uint64_t does. Core refuses no chain. The arguments are checked here, and the mining is the generator returned.

btclib_node.rpc.mining.get_block_template(node: Node, conn: RpcConnection, params: list[Any]) → dict[str, Any] | str | Generator[bool, None, dict[str, Any]] | None[source]

Answer getblocktemplate: a template, or a verdict on a block.

Core’s getblocktemplate (src/rpc/mining.cpp, BIPs 22 and 23). With mode “proposal” the block in data is checked on top of the tip and not stored, answered null where valid. Otherwise the answer is a template built from the mempool, which on mainnet needs a peer and a node out of initial block download. With a longpollid, the answer is _long_poll, the generator that waits before building it.

btclib_node.rpc.mining.wait_for_block(node: Node, conn: RpcConnection, params: list[Any]) → Generator[bool, None, dict[str, Any]][source]

Answer waitforblock: the tip, once it is blockhash.

Core’s waitforblock, whose blockhash is read before timeout. timeout is waitforblockheight’s, and the tip is compared once per pass of the loop (_wait_for_tip).

btclib_node.rpc.mining.wait_for_block_height(node: Node, conn: RpcConnection, params: list[Any]) → Generator[bool, None, dict[str, Any]][source]

Answer waitforblockheight: the tip, once it is at height or above.

Core’s waitforblockheight: timeout is in milliseconds, 0 for none, and the tip is answered at the timeout too, and once the node stops. The arguments are checked here, and the wait is the generator returned.

btclib_node.rpc.mining.wait_for_new_block(node: Node, conn: RpcConnection, params: list[Any]) → Generator[bool, None, dict[str, Any]][source]

Answer waitfornewblock: the tip, once it is not current_tip.

Core’s waitfornewblock: current_tip is the tip at the call where it is left out, and a current_tip that is not the tip is answered at once. timeout is waitforblockheight’s, and where the node stops the answer is the tip at the call (_wait_for_tip).

btclib_node.rpc.package module

submitpackage: a child and its parents, or one transaction, to the mempool.

Core’s submitpackage (src/rpc/mempool.cpp) over AcceptPackage (src/validation.cpp), at bitcoin/bitcoin@9be056a8a7, the v31.1 tag. The handler has rpc.callbacks’ signature and runs on Node’s thread, so it checks scripts and changes the mempool without a lock (ARCHITECTURE.md). rpc.callbacks imports this module, so its helpers are imported inside the functions that use them. package_test_accept is testmempoolaccept’s judgement of several transactions, which adds none of them.

A transaction taken alone may replace what it conflicts with, as sendrawtransaction’s does, and so may a parent and its child taken together (Mempool.check_package_replacement). replaced-transactions lists what each transaction still held at the end replaced.

class btclib_node.rpc.package.Outcome(error: Exception | None = None, other_wtxid: bytes | None = None, vsize: int = 0, base_fee: int = 0, effective: tuple[int, int, list[bytes]] | None = None, replaced: tuple[bytes, ...] = ())[source]

Bases: NamedTuple

What submitpackage or testmempoolaccept answers of one transaction.

Either error, or what the mempool holds, or would hold, of it: its vsize and the base_fee it pays, and other_wtxid where it holds another witness of it instead. effective is the modified fee and the vsize its effective feerate is of, with the wtxids they are the sums over, where the transaction was taken, or would be, now and not before. replaced are the txids of what taking it replaced.

base_fee: int

Alias for field number 3

effective: tuple[int, int, list[bytes]] | None

Alias for field number 4

error: Exception | None

Alias for field number 0

other_wtxid: bytes | None

Alias for field number 1

replaced: tuple[bytes, ...]

Alias for field number 5

vsize: int

Alias for field number 2

btclib_node.rpc.package.accepted(node: Node, tx: Tx, fee: int, vsize: int, replaced: tuple[bytes, ...] = ()) → Outcome[source]

Return the outcome of tx passing with fee and vsize.

Its effective feerate is its own modified fee over its own vsize.

btclib_node.rpc.package.package_test_accept(node: Node, txs: list[Tx]) → tuple[str | None, dict[bytes, Outcome]][source]

Judge txs as one package, and take none of them.

Core’s ProcessNewPackage with test_accept, which runs AcceptMultipleTransactions under PackageTestAccept (src/validation.cpp, same tag): package_refusal, then pre_verify_subpackage with test_accept, then the scripts of each in turn. Any topology package_refusal takes is judged, a child with its parents or not.

Returns Core’s message where it refuses the package as a whole, and the outcome of each transaction Core answers: the one refused, and, where its scripts are what is refused, each before it; or every one. The effective feerate of each is its own.

btclib_node.rpc.package.submit_package(node: Node, _conn: RpcConnection, params: list[Any]) → dict[str, Any][source]

Answer submitpackage: take what passes, and say what each came to.

A package refused in whole or in part is a result that says why, not an error: _read has the errors. Each transaction the mempool then holds is announced, one held before the call too, as BroadcastTransaction announces it for submitpackage. None is marked unbroadcast: Core holds each in the mempool already when it calls BroadcastTransaction, which marks only what it adds itself (src/node/transaction.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag).

replaced-transactions are the txids each transaction taken replaced, by their internal bytes, as Core’s std::set<Txid> orders them (src/rpc/mempool.cpp, same tag).

btclib_node.rpc.signing module

The signing RPCs that need no wallet.

signmessagewithprivkey and verifymessage are Core’s src/rpc/signmessage.cpp, over MessageSign and MessageVerify (src/common/signmessage.cpp). signrawtransactionwithkey and combinerawtransaction are Core’s src/rpc/rawtransaction.cpp, with ParsePrevouts and SignTransaction of src/rpc/rawtransaction_util.cpp; btclib_node.signing is the signing itself. All are read at bitcoin/bitcoin@9be056a8a7, the v31.1 tag, except where a docstring says otherwise. Each handler has rpc.callbacks’ signature.

btclib_node.rpc.signing.combine_raw_transaction(node: Node, conn: RpcConnection, params: list[Any]) → str[source]

Answer combinerawtransaction: one transaction holding every signature.

Read at Core’s master, bitcoin/bitcoin@6d86184a8bcc, not at v31.1: at least two transactions are needed, and each must be the first one once its signatures are stripped. The v31.1 tag does neither, and copies an unrelated transaction’s complete inputs onto the first one.

btclib_node.rpc.signing.sign_message_with_privkey(node: Node, conn: RpcConnection, params: list[Any]) → str[source]

Answer signmessagewithprivkey: the base64 signature of a message.

The header byte is 27 plus the recovery id, and 4 more for a compressed key, as CKey::SignCompact writes it. -5 for a key DecodeSecret refuses.

btclib_node.rpc.signing.sign_raw_transaction_with_key(node: Node, conn: RpcConnection, params: list[Any]) → dict[str, Any][source]

Answer signrawtransactionwithkey: sign what the given keys can.

Each input’s output is looked up in the mempool, then the chain, and prevtxs replaces what was found. The answer is the transaction, whether it is complete, and each input still unsigned with its error. Where an input has a witness and its output no amount, the refusal is the call’s (-3), not the input’s.

btclib_node.rpc.signing.verify_message(node: Node, conn: RpcConnection, params: list[Any]) → bool[source]

Answer verifymessage: whether a signature opens to a P2PKH address.

Core’s MessageVerify. -5 for an address that does not decode, -3 for one that is not P2PKH and for a signature that is not base64; false for one that recovers no key or another key’s.

btclib_node.rpc.snapshot module

dumptxoutset: write the UTXO set to a snapshot file.

Core’s dumptxoutset is in src/rpc/blockchain.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag, and the file is btclib_node.snapshot’s. The handler has rpc.callbacks’ signature and runs on Node’s thread (ARCHITECTURE.md): a generator that rpc.main resumes on each pass of Node’s loop, which writes _STEP coins between two yields, so the loop serves other requests meanwhile. Invalidating and reconsidering the block run without yielding, so a deep rollback holds the loop, where Core does it on an HTTP worker thread.

A rollback dump invalidates the block after the target, as Core’s TemporaryRollback does, takes the coins of the chain that is left, and reconsiders the block when the call ends. The network is off meanwhile, unless it was off already.

btclib_node.rpc.snapshot.dump_tx_out_set(node: Node, conn: RpcConnection, params: list[Any]) → Generator[bool, None, dict[str, Any]][source]

Answer dumptxoutset: write the UTXO set of a block to path.

latest is the active tip’s, and a rollback option or type is an earlier block’s, rolled back to for the length of the call. path is relative to the data directory. The file is written to path and .incomplete and renamed once whole, and a path that exists is refused.

nchaintx is a sum of every block’s transaction count up to the base block, read from the stored blocks. A node whose blocks are pruned has not those, and refuses with RPC_MISC_ERROR where Core, which keeps the count with each header, answers.

The block is reconsidered when the call ends, as in Core, and the network re-enabled where this call disabled it.

btclib_node.rpc.solver module

Bitcoin Core’s Solver, as scriptPubKey.type and its address read it.

A stand-in for btclib.script.solver.solver (btclib-org/btclib#2458, merged, not yet released), which this tree cannot import while its btclib floor is a release without it: once the floor moves, delete this module and import solver from there. Its source is the one this is copied from, which reads Solver and GetTxnOutputType (src/script/solver.cpp) at bitcoin/bitcoin@9be056a8a7, and it is kept to what an RPC answer needs: the type name and the solutions, nothing a standardness check adds.

btclib.script.script_pub_key.type_and_payload is not a substitute. It names its types its own way and classifies differently on purpose: it parses the keys of a p2pk and a p2ms as curve points where Solver checks CPubKey::ValidSize only, and it takes a nulldata of one push of at most 80 bytes where Solver takes any push-only data. A type name taken from it is a name Core does not answer for such a script.

btclib_node.rpc.solver.solver(script_pub_key: bytes) → tuple[str, list[bytes]][source]

Classify a script_pub_key as Core’s Solver does.

Returns GetTxnOutputType’s name for the type and the solutions Core fills for it: the script hash for “scripthash”; the key or key hash for “pubkey” and “pubkeyhash”; m, each key and n for “multisig”, m and n as one byte each; the program for the three witness types whose version is implied, and the version byte then the program for “witness_unknown”. “nulldata”, “anchor” and “nonstandard” have none.

The checks run in Core’s order, which decides the answer: a witness program of v0 and a length other than 20 or 32 is “nonstandard” and no later shape is tried on it. Keys are checked for their size and prefix only, never parsed as points, and nulldata has no size cap (that one is relay policy, which IsStandardTx applies).

btclib_node.rpc.utxo_set module

The RPCs that read the UTXO set whole: scantxoutset.

Core’s scantxoutset is in src/rpc/blockchain.cpp, with the descriptor arguments in src/rpc/util.cpp, both at bitcoin/bitcoin@9be056a8a7, the v31.1 tag. Its InferDescriptor is btclib_wallet’s infer_descriptor. Each handler has rpc.callbacks’ signature and runs on Node’s thread (ARCHITECTURE.md).

A scan is a generator that rpc.main resumes on each pass of Node’s loop. It walks the stored coins _STEP at a time and yields between steps, so the loop serves other requests meanwhile, status and abort among them. Core runs the scan on an HTTP worker and the two others on workers of their own, which share atomics; here all three run on Node’s thread, and the scan’s state needs no lock.

btclib_node.rpc.utxo_set.scan_tx_out_set(node: Node, conn: RpcConnection, params: list[Any]) → dict[str, Any] | bool | Generator[bool, None, dict[str, Any]] | None[source]

Answer scantxoutset: report on, stop, or run a scan of the UTXO set.

start searches the stored coins for the scripts of the scan objects’ descriptors, a ranged one expanded over its range and combo over its scripts, and answers each coin found with the descriptor that describes its script. A coin is listed once, as Core’s std::map has it, and is found in the set as it was when the scan began: the chainstate is flushed and a cursor opened, whose view RocksDB fixes (UtxoIndex.cursor). success is false for a scan that was aborted or met a record it cannot read, and the rest of the answer is what was found by then.

A coin’s desc is Core’s InferDescriptor of its script, read with what the scan object’s descriptors tell a provider at each index of its range. Core infers every script before the walk; here only a script a coin has is inferred, which answers the same.

A descriptor parse error has Core’s code and btclib_wallet’s message.

Module contents

The JSON-RPC surface this node serves.

Connections, the RPC manager, the credentials it checks, the errors JSON-RPC 2.0 defines and the method handlers Node’s loop calls. manager.RpcManager is the thread; connection.RpcConnection is one accepted socket, carrying one request or several; auth.RpcAuth is who may call it; callbacks.callbacks is the method-name table main.handle_rpc dispatches through; errors.RpcError is what a handler raises to answer with a JSON-RPC error object instead of a result.