bitcoin_core_rpc module¶
One page for the package. The facade carries the design of the client
and the reasoning behind each refusal, and no member list of its own:
automodule without :members: renders that docstring alone,
because a constant this facade only forwards through __getattr__
has its attribute docstring in the module that defines it and nowhere
else, and autodoc reads a module’s data members from that module’s
own source. Every name in __all__ is therefore documented once,
under whichever of the four defines it.
A standalone JSON-RPC client against Bitcoin Core.
Nothing but the standard library behind it. BitcoinCoreRpcClient invokes any one rpc method a node has, with positional or named parameters: one HTTP POST per call, basic authentication, the result or an exception. Any method, because a caller with a node has every reason to ask it anything, and a client that knew a list of methods would only mean they write this class again.
BitcoinCoreRestClient is Core’s other interface, -rest: read-only, off by default, and authenticating nobody who reaches it. get_bin and get_json GET one path and answer with the bytes or the parsed json, sharing the transport and the chain vocabulary with the JSON-RPC client above and nothing else – no credentials, -rest taking none, and no method per resource, a path being the caller’s own to build.
Not python-bitcoinrpc’s `AuthServiceProxy`, and not a port of it. That class, and the copy of it Core’s test framework maintains, carry the LGPL-2.1 of their python-jsonrpc ancestry, where this is MIT: this is an implementation of the protocol rather than a translation of theirs, and shares no line with either. It is not API-compatible with them either, and does not try to be – call(“getblockcount”) against an attribute lookup that builds a method name is a different interface, and the explicit one is what makes an unknown method a value rather than a typo that becomes a request.
Migrating from `AuthServiceProxy`. Four things change, and each of them is the difference deliberately.
# a method is an argument, not an attribute: an unknown one is a
# value that arrives at the node, not an AttributeError here
rpc.getblock(block_id, 2)
client.call("getblock", [block_id, 2])
# and the named form is the other structure Core takes
client.call("getblock", {"blockhash": block_id, "verbosity": 2})
# credentials leave the url, which is what gets written into a
# config file and printed in a traceback
AuthServiceProxy(f"http://{user}:{password}@127.0.0.1:8332")
BitcoinCoreRpcClient("http://127.0.0.1:8332", user=user, password=password)
BitcoinCoreRpcClient.from_chain("main") # or the node's cookie file
# one wallet of a multi-wallet node, percent-encoded
client.for_wallet("hot").call("getbalance")
JSONRPCException becomes three exceptions, because it covered three things a caller acts on differently: RpcError when the node computed an error, with its code; HttpError when the exchange failed, with its status; FetchError when there was no answer to read at all. All three are FetchError, so one except FetchError is the equivalent of the one except JSONRPCException; what catching them apart buys is the status a retry policy reads.
batch_ is what a consumer loses under that name – Core’s maintained
fork spells it batch – and call_batch is what replaces it. Several
(method, params) pairs travel in one HTTP POST, each built the way
call builds its own single request, and the answer is a list aligned
with the input: position i holds member i’s result, or its RpcError
as a value, matched to its request by id rather than by array
position. Only a failure of the whole exchange – a non-2xx status, a
reply that is not an array, a reply no member’s id claims – raises,
exactly as call raises. COMPARISON.md’s Batching has the case for
reaching for it over a loop of call, and where a loop remains the
better choice.
Notifications – a request sent with no id, which a node does not answer – are a non-goal too, and no AuthServiceProxy consumer is giving one up: both implementations count an id into every request they build, so sending one at all means building the request body instead of calling call.
One call, one HTTP request, and no retry. A 503 from bitcoind means its rpc work queue is full and the same request works once the queue drains, so a retry is the obvious convenience – and it is the caller’s to write, for two reasons. call carries any method, so this class cannot know whether re-sending one is safe. And the timeout bounds this client’s wait rather than the node’s work: a node that stopped answering may still be executing the call, so a client re-sending a wallet command of its own accord can execute it twice. HttpError.status is what makes that policy three lines rather than a match on the text of a message; it is no ruling on which failures are transient, a refused connection and an expired timeout arriving as a plain FetchError and both able to clear on their own.
JSON-RPC 2.0, and 1.1 read back. Core answers 1.1 by default and 2.0 to a request carrying the “jsonrpc”: “2.0” marker, and the difference is which layer reports a bitcoin error: under 1.1 an unknown transaction comes back as HTTP 500 with the error object in the body, so a genuine server fault and a routine “no such transaction” are the same status. Under 2.0 an rpc error is HTTP 200 with an error member, and a non-2xx means the HTTP exchange itself failed. Both are read here – a node older than v28 does not know the marker and replies 1.1 to it – but only one of them can be told apart from a proxy in the way.
No credentials in the url. A url with the userinfo part filled in – the <user>:<password>@ before the host – puts a password in a string that ends up in configuration files, tracebacks and logs. Such a url is refused here; the password arrives as an argument, or, better, is never seen at all – .cookie is what bitcoind writes for exactly this, rotated at every restart, readable by the user running the node and by nobody else.
The client and the transport are published without being imported. chains.py is the chain and network vocabulary and opens no socket, and errors.py is the exception hierarchy every module raises out of; both import only the standard library beneath them, and neither pulls in urllib.request. client.py and transport.py do – ssl and socket under it – so a caller reaching for magic_from_chain or cookie_auth alone pays for none of that. The names those two modules hold are answered by __getattr__ below, imported the first time one of them is asked for; the TYPE_CHECKING import beside it is what keeps a checker reading BitcoinCoreRpcClient as that class and not as the Any an unresolved __getattr__ answers with, since it never runs and costs nothing at import time.
The exception hierarchy this package raises.
BtcRpcValueError to CookieNotFoundError: every other module raises out of this one, so it is the layer beneath all of them and the one place a caller wanting the whole hierarchy imports from.
- exception bitcoin_core_rpc.errors.BtcRpcRuntimeError[source]¶
Bases:
RuntimeErrorA check that failed on valid inputs, e.g. a failed verification.
- exception bitcoin_core_rpc.errors.BtcRpcTypeError[source]¶
Bases:
TypeErrorAn input of a type no conversion accepts: a caller error.
- exception bitcoin_core_rpc.errors.BtcRpcValueError[source]¶
Bases:
ValueErrorA value no valid input could carry; the library’s usual refusal.
- exception bitcoin_core_rpc.errors.CookieNotFoundError[source]¶
Bases:
FetchErrorThere is no cookie file where one was looked for.
A FetchError like the others, and for the same reason: nothing the caller passed is wrong, and the node starting is what fixes it. A class of its own because it is the one cookie failure that is ordinarily no fault at all – bitcoind writes the file while it runs and removes it when it stops, so an absent one is a node that is not running, or one whose rpc server is off, which is bitcoin-qt without server=1. Every other cookie failure is a file to go and look at.
A caller that reports the two the same way tells an operator to inspect a file that was never written; one holding them apart says “start the node” for this and names the file for the rest.
- exception bitcoin_core_rpc.errors.FetchError[source]¶
Bases:
BtcRpcRuntimeErrorA backend did not answer, or did not answer this.
A RuntimeError and not a ValueError: nothing the caller passed is wrong. The node is down, the credentials are stale, the explorer sent html, the transaction is not in the index – retrying later can work, and correcting the argument cannot.
It covers the conversion of an answer too: a backend replying with something that is not a transaction has failed, and reporting that as the BtcRpcValueError the parser raised would name the parser rather than the host that has to be fixed.
HttpError, RpcError and CookieNotFoundError derive from it, so one except FetchError catches every failure of an exchange.
- exception bitcoin_core_rpc.errors.HttpError(message: str, status: int)[source]¶
Bases:
FetchErrorA backend failed at the HTTP layer, and status is what it said.
A field rather than something to be parsed back out of a message: the retry policy that reads it is the caller’s, for the reasons this module’s docstring gives.
Not every FetchError carries one. A refused connection and an expired timeout never produced a status; neither did a body that is no answer – not json, not utf-8, not a reply object – arriving with an HTTP 200, where the shape of the body is the whole diagnosis. The same body under a non-200 is this exception instead: it cannot be an answer the backend computed, so the status is what is left to report. The message states it too – an exception is a diagnostic before it is a value.
- class bitcoin_core_rpc.errors.RPCErrorCode(*values)[source]¶
Bases:
IntEnumCore’s own RPCErrorCode, src/rpc/protocol.h, transcribed whole.
Every member of Core’s enum at bitcoin/bitcoin@9be056a8a7, RPC_ dropped from each name, values included – a code Core reserved or deprecated stays a member here rather than being trimmed, because RpcError.code can still carry it. FORBIDDEN_BY_SAFE_MODE (-2) is that case: Core’s own comment marks the block it is in “unused reserved codes, kept around for backwards compatibility. Do not reuse,” and it is transcribed rather than dropped for the same reason the rest are. -21 names no member because Core’s own enum does not either – the gap is Core’s, not a value cut here. TRANSACTION_ERROR, TRANSACTION_REJECTED and WALLET_INVALID_ACCOUNT_NAME alias another member rather than naming a new value, through enum’s own mechanism for it – a repeated value binds to the member that already claims it – which reproduces Core’s own RPC_X = RPC_Y aliases rather than approximating them.
This is a lookup, not a constraint: RpcError.code stays a plain int, because a code absent here is an answer a node gave and not a defect of this type – a future Core release, or a JSON-RPC server that is not Core, is free to send a code this class does not name. RPCErrorCode(exc.code) is the caller’s own one line when it wants the name, and it raises ValueError – Core’s own answer, not a silent guess – only for a code truly absent from Core’s table.
- exception bitcoin_core_rpc.errors.RpcError(message: str, code: int, data: Any = None)[source]¶
Bases:
FetchErrorbitcoind answered with a JSON-RPC error object, and this is it.
code is the node’s, from src/rpc/protocol.h: -5 is RPC_INVALID_ADDRESS_OR_KEY, which is what getrawtransaction returns for a transaction it cannot find – including every non-wallet transaction on a node running without -txindex. A caller telling “no such transaction” from “the node is unreachable” needs the number, and it stays a plain int here rather than RPCErrorCode – a code Core’s own header does not (yet) name is still a code Core sent, and typing this field to the enumeration would make that answer a ValueError instead. RPCErrorCode(exc.code) is the caller’s own line when it wants the name.
data is JSON-RPC’s optional third member of an error object, kept as it arrived. Core leaves it out today, so it is None for every error a node sends; a method that starts sending one, or a proxy adding its own, would otherwise have it dropped here, which is the one place it cannot be recovered from.
args[0] is the text as it arrived, the node’s message included. str() writes each non-printable character of it as an escape, so a message carrying a newline or an ESC cannot forge a log line or drive a terminal.
Core’s chains: the port and datadir tables, the magic bytes, the cookie.
The chain and network vocabularies and their translations, the rpc port and datadir subdirectory of each chain, the magic bytes and the signet derivation, and the cookie path and cookie_auth that reads it. Nothing here opens a socket: client.py is where a chain’s own defaults become a connection.
- bitcoin_core_rpc.chains.COOKIE_USER = '__cookie__'¶
The username bitcoind writes into its cookie file.
COOKIEAUTH_USER in Core’s src/rpc/request.cpp. The node ignores it – cookie authentication compares the whole user:password line – so it is documentation, and a cookie file whose first field is something else is still a valid one.
- bitcoin_core_rpc.chains.Chain¶
Core’s chain names, which -chain= takes and getblockchaininfo reports, and which from_chain and the two lookups are spelled in.
What chain_from_network returns, and not what network_from_chain is annotated as taking.
alias of
Literal[‘main’, ‘test’, ‘testnet4’, ‘signet’, ‘regtest’]
- bitcoin_core_rpc.chains.DEFAULT_DATADIR: Path | None = PosixPath('/home/docs/.bitcoin')¶
Core’s datadir for this platform as it stood at import, or None.
default_datadir computes it, and says which directory each platform gets. from_chain calls that rather than reading this, so that a HOME set after this module was imported is the one that counts.
- bitcoin_core_rpc.chains.DEFAULT_SIGNET_CHALLENGE = '512103ad5e0edad18cb1f0fc0d28a3d4f1f3e445640337489abb10404f2d1e086be430210359ef5021964fe22d6f8e05b2463c9540ce96883fe3b278760f048f5189f2e6c452ae'¶
The block challenge of the signet everyone means by “signet”.
SigNetParams in Core’s src/kernel/chainparams.cpp, the bin a node started without -signetchallenge uses. What makes it worth publishing is that it is the one signet a caller can name rather than describe: magic_from_signet_challenge(DEFAULT_SIGNET_CHALLENGE) is magic_from_chain(“signet”), and any other challenge is a chain this table has no entry for.
- bitcoin_core_rpc.chains.Network¶
The five BIP network names, which BIP32 and BIP173 spell.
mainnet and testnet are where this vocabulary differs from Chain; the rest agree. chain_from_network translates.
alias of
Literal[‘mainnet’, ‘testnet’, ‘testnet4’, ‘signet’, ‘regtest’]
- bitcoin_core_rpc.chains.chain_from_network(network: str) Literal['main', 'test', 'testnet4', 'signet', 'regtest'][source]¶
Return Core’s chain name for one of the BIP network names.
Raises rather than passing an unrecognized name through, in both directions: a chain Core adds later is then a failure here, naming what it knows, instead of a string that reaches a node as a port lookup or a directory name.
- bitcoin_core_rpc.chains.cookie_auth(cookie_path: Path) str[source]¶
Return the user:password bitcoind wrote in its cookie file.
One line, __cookie__: and 32 random bytes in hex, rewritten at every start of the node. Read at each call rather than once at construction: a client built when the node was up and used an hour later would otherwise answer 401 for the rest of the process, the node having been restarted in between, and the cost is one small local read against an HTTP round trip.
A regular file only: a FIFO or a device at the path can block the read, with no deadline to end it.
Ascii, one line and a bounded read, because a path that is not a cookie file is the ordinary mistake here and a credential is the one value that must not appear in the error reporting it: what the three checks buy is that a binary file, a log or something enormous arrives as a FetchError naming the file, rather than as a UnicodeDecodeError or as memory nobody agreed to.
A file that is not there is CookieNotFoundError, which is a FetchError too: it says the node wrote no cookie, where the rest say something is at the path and it is not a cookie.
- bitcoin_core_rpc.chains.cookie_path_from_chain(chain: str, datadir: str | PathLike[str] | None = None) Path[source]¶
Return the path of the cookie file bitcoind writes for one chain.
Under datadir, the directory the node was started with, defaulting to default_datadir – asked at this call, so that the environment of the call is what counts, and where it has no base to answer with this refuses with BtcRpcValueError naming datadir rather than deriving a path against the working directory. Then the subdirectory datadir_subdir_from_chain names, and .cookie, which is COOKIEAUTH_FILE in Core’s src/rpc/request.cpp.
What from_chain builds its cookie_path out of, and what the caller it cannot serve otherwise assembles by hand: a node started with -datadir= somewhere else, or one reached at a url of the caller’s, which is the constructor and derives nothing. Two of the three facts were published as tables and the name of the file was not, so assembling it meant writing that name out.
A node started with -rpccookiefile writes the file somewhere else again: that is a path the caller already holds, and nothing derives it.
A path and no read, cookie_auth being what reads one – and a client re-reads it at every call, the node rotating the credential at every restart.
- bitcoin_core_rpc.chains.datadir_subdir_from_chain(chain: str) str[source]¶
Return the datadir subdirectory of one of Core’s chains.
Empty for main, which keeps its cookie in the datadir itself, and testnet3 for test: the two the chain name does not give away. cookie_path_from_chain composes it with a datadir and the name of the cookie file; what is left for this is a caller naming something else under the same directory – a wallet, a debug.log.
- bitcoin_core_rpc.chains.default_datadir() Path | None[source]¶
Return Core’s datadir for this platform, or None where it has no base.
What Core’s own GetDefaultDataDir answers:
%APPDATA%\Bitcoinon Windows,~/Library/Application Support/Bitcoinon macOS,~/.bitcoinon everything else. The three are a table here, so the branch a checker or a coverage run on one platform does not take is still a line both of them read; sys.platform and the environment are read at the call, which is what a test drives to reach the other two.Three ways there is no base to hang that off, and none may raise, since DEFAULT_DATADIR below calls this at import: Path.home() raises RuntimeError when nothing resolves ~ – no HOME in the environment and no passwd entry for the uid, which is a container run under an arbitrary one – and it answers with whatever HOME holds, so a relative HOME gives a relative home and raises nothing. On Windows APPDATA is the base, and it can be unset or relative in the same way.
None for all of them, rather than a path that is no datadir. A relative one would be resolved against the working directory at the moment of the read, so ~/.bitcoin/.cookie would make a file a caller’s cwd happens to contain the credential this client presents. from_chain refuses instead, naming cookie_path as what to pass.
A default and not a discovery: a node started with -datadir= is somewhere this cannot know, and cookie_path is the answer for one.
from_chain calls this at every call rather than reading DEFAULT_DATADIR, so that the HOME of the call is the one that counts and not the one that stood when something first imported this module. Public for the same reason: a caller building its own datadir-derived path – a wallet directory, or the cookie cookie_path_from_chain derives – needs that live answer too, and had no way to ask for it short of copying this function.
- bitcoin_core_rpc.chains.magic_from_chain(chain: str) bytes[source]¶
Return the p2p message start of one of Core’s chains.
Signet’s is the default signet’s – magic_from_signet_challenge is what answers for any other, the challenge being what a signet is identified by.
- bitcoin_core_rpc.chains.magic_from_signet_challenge(challenge: str | bytes | bytearray) bytes[source]¶
Return the p2p message start a signet’s block challenge determines.
Core: “message start is defined as the first 4 bytes of the sha256d of the block script”, the script serialized with its CompactSize length, and the four bytes in the order the digest produces them. BIP325 is the challenge itself; this is what SigNetParams does with it.
Hex or the bytes it spells, because a challenge is written in a config file and reported by getblockchaininfo as hex, and held as bytes by anything that has parsed it. Nothing else, bytes(7) being seven zero bytes rather than an error: a challenge that arrived as a number would otherwise be hashed as a script of that length.
The empty challenge is a signet too: Core reads -signetchallenge= and a bare -signetchallenge as the empty script, and such a node uses the magic this returns for “”.
- bitcoin_core_rpc.chains.network_from_chain(chain: str) Literal['mainnet', 'testnet', 'testnet4', 'signet', 'regtest'][source]¶
Return the BIP network name for one of Core’s chain names.
The inverse of chain_from_network, and raising for the same reason.
- bitcoin_core_rpc.chains.rpc_port_from_chain(chain: str) int[source]¶
Return the default rpc port of one of Core’s chains.
What from_chain builds its loopback url out of, and what reaching the same node any other way – through a tunnel, an https proxy, or from another host – otherwise means copying this table to know.
The HTTP layer: HttpTransport, http_request, and the bounded read.
Everything below an HTTP status is mapped onto FetchError here, and nothing above it is: what a status means is client.py’s question, not this module’s. urlopen_transport and SessionTransport are the two things here that open a socket, both through _connect; nothing else in this module does.
- bitcoin_core_rpc.transport.DEFAULT_MAX_BODY_SIZE = 8001024¶
How much of a reply this module will hold in memory, by default.
Twice Core’s buffer bound on a serialized block, so a block as hex fits. A default and not a ceiling on what a node can answer: getblock at verbosity 2 renders every transaction as json and is larger, and so is listunspent or listtransactions on a large wallet, which no block size bounds at all. Those are ordinary calls, so the refusal names max_body_size – the one thing the caller has to change.
- bitcoin_core_rpc.transport.DEFAULT_TIMEOUT = 30.0¶
The seconds a call may take, unless timeout or request_timeout says.
For both transports of this module it bounds the whole exchange rather than each socket operation – name resolution, connect, send, status line, headers and body – so a peer that keeps sending cannot outlast it. A reply large enough to take longer than this to arrive is one of the cases for request_timeout, along with the methods that legitimately run long.
- bitcoin_core_rpc.transport.HttpTransport¶
What this module does its I/O with, and what transport= takes.
A callable given the built Request – url, method, body and headers all set – and a timeout in seconds, answering with the HTTP status and the response body. A status rather than an exception, because a JSON-RPC error can arrive with a 500 and its body is the error object.
Two arguments and no more, so a transport of a caller’s own owes four things this module cannot check for it. urlopen_transport is the default and does all four:
its own bound on what it holds in memory while reading. There is nowhere in two arguments to pass max_body_size, and the limit applied to the bytes it hands back is a refusal after the allocation rather than instead of it;
a bound on how long it holds the call. timeout is one number, and most client libraries spend it per socket operation, which a peer dripping a body resets forever; urlopen_transport reads it as a deadline for the whole exchange;
no redirect followed. The request already carries the Authorization for the host it names, and a client library that follows a 30x sends that credential to whatever the Location says;
its own thread-safety. BitcoinCoreRpcClient promises that concurrent calls are safe while its configuration is not mutated, and the transport is part of that configuration: a session object that is not thread-safe makes the client not thread-safe, and only its author knows which it is.
- bitcoin_core_rpc.transport.MAX_ERROR_BODY_SIZE = 65536¶
How much of the body of a failure is kept, max_body_size not applying.
Enough to carry whatever the backend said with its status, and not the megabytes an error page from something in the way can be. Truncated rather than refused: an error page one octet over a caller’s limit for a tip height is still the diagnosis of why there is no height.
- class bitcoin_core_rpc.transport.SessionTransport(*, connection_factory: ~collections.abc.Callable[[str, str, int, float], ~bitcoin_core_rpc.transport._Connection] = <function _new_connection>)[source]¶
Bases:
objectAn HttpTransport that keeps one connection per (scheme, host, port).
urlopen_transport opens a socket, sends Connection: close – not its own choice but urllib’s AbstractHTTPHandler.do_open, which sets the header unconditionally – and lets the node close it. This one does not: it keeps the connection http.client gives it and hands the same one to the next call addressed to the same scheme, host and port, so a caller making many calls against one node pays the connect cost, and on https the TLS handshake, once rather than every time.
max_body_size and the timeout mean what they mean for urlopen_transport: max_body_size bounds what one answer holds in memory, and timeout is a deadline over the whole exchange – connect or reuse, send, and read – taken as one monotonic() reading before any of the three. The connection is given it as its deadline, which every lookup, connect, send and recv over the connection _new_connection builds is held to, and it is what _read_bounded reads the response against, the same bounded, chunked read urlopen_transport uses. No redirect is followed: http.client does not follow one on its own, so a 30x already arrives as the status and body of any other response, with nothing here needing to refuse it.
Thread safety. One instance is safe to share between threads, and the contract is one lock guarding the whole exchange rather than one per connection: a socket can carry one request at a time, so two threads sharing a connection have to be serialized somewhere, and guarding only the dict of connections would still let both drive the same socket’s request() and getresponse() at once, which is corruption on the wire rather than a data race Python’s own GIL prevents. Serializing the whole call is what rules that out, at the cost of one instance never running two calls concurrently even across different hosts; a caller wanting that keeps one instance per host, the same shape BitcoinCoreRpcClient already asks a caller’s own transport for.
A kept connection is probed before it is reused. A connection this transport kept open is one the node may since have closed on its own – an idle timeout on the other end, unrelated to anything this transport does – and whether a send() into that socket fails outright, succeeds and only the read afterwards fails, or fails as a plain ConnectionResetError at either step, is a detail of what the peer did (a graceful close() versus a shutdown()) and of timing that this transport does not control and cannot tell apart from a healthy connection’s own silence by guessing. Before every reuse, a zero-timeout probe asks the kept socket whether it is already readable with no request in flight – _is_reused_connection_dead above – which is unambiguous under HTTP/1.1’s one-request-at-a-time shape: a live connection with nothing asked of it reports not-readable. A readable probe evicts the kept connection and opens a fresh one before anything at all is sent, which is not the reconnect below – nothing has been written yet, so there is nothing to have sent twice – and the fresh connection’s own first failure, if the node itself is also unreachable, is the ordinary fresh-connection case: a node not answering, which no reconnect fixes either.
The one reconnect is on the write. What the probe above does not catch is a drop landing after it: between the probe and the write, or after the write. Where the write is what notices – one of _STALE_CONNECTION_ERRORS out of request() – the request never reached the wire in full, so no node can have executed it, and it is sent once more on a fresh connection. Where the read is what notices, nothing is sent again, whatever it raises: request() has returned, so the whole request was written, and http.client.RemoteDisconnected – the end of the stream where a status line belongs – is what a node that executed the call and closed before answering produces. That failure propagates, http_request reports it as a FetchError, and whether to send the request again is the caller’s decision, for the reason the package docstring’s One call, one HTTP request, and no retry gives: the node may have executed it. The reconnect is offered only where the connection was already open before this call, and once: a fresh connection failing the same way is a node not answering, which no reconnect fixes, and a failure of the reconnect’s own attempt is not caught again. The end of the write is the line the reconnect must not cross, and a status line that did arrive is further past it still: a response that began and then broke – a truncated body, a malformed header – is not re-sent.
Nothing failed is left pooled. Any exception request() or getresponse() raises that the paragraph above does not resolve into a successful reconnect closes the connection and drops it from the pool before propagating, whether the connection was fresh or reused: a (scheme, host, port) a first attempt could not reach stays usable for the next attempt once the node answers, rather than failing forever on a dead connection object no later call has any way to replace. Only a connection an exchange actually completed over is kept.
Not a pool of several connections per key, and not eviction under memory pressure: one caller talks to one node, sometimes a second for a second wallet, which is one or two keys for the life of the process – the pool a caller polling many nodes would want is closer to what requests or httpx already build.
No connection is opened by the constructor: one is asked for on the first call addressed to a given (scheme, host, port). connection_factory is the seam a test replaces it with, taking the scheme, the host, the port and the timeout and answering something with _Connection’s interface – a fake never opening a real socket, _new_connection above doing exactly that for everything else.
- bitcoin_core_rpc.transport.http_request(url: str, *, data: bytes | None = None, headers: ~collections.abc.Mapping[str, str] | None = None, timeout: float = 30.0, max_body_size: int = 8001024, transport: ~collections.abc.Callable[[~urllib.request.Request, float], tuple[int, bytes]] = <function urlopen_transport>) tuple[int, bytes][source]¶
Return the status and body of a GET, or of a POST when data is given.
Everything below the HTTP status is a FetchError: a refused connection, an unresolvable host and an expired timeout are one answer to the caller – the backend did not answer – and none of them is a bitcoin error worth a type of its own.
A non-2xx status is not a failure here. It comes back like any other, because the body of a 500 is where bitcoind’s legacy JSON-RPC 1.1 reply puts its error object, and the body of a 404 is where an explorer says what it could not find. Deciding what a status means is the backend’s job, that being the layer that knows. A 30x is one of those statuses now rather than a second request: urlopen_transport follows no redirect, and _OPENER says why.
max_body_size is what an answer may weigh, and the caller sets it from what it asked for: a tip height is a few octets and a raw transaction is megabytes, so one number for both would be the larger. The body of a failure is bounded by MAX_ERROR_BODY_SIZE instead, and in time by timeout, the same deadline the answer is read against: a drip is a drip whichever status precedes it.
A header name that is not an RFC 9110 token, and a value holding a CR, an LF, a NUL or a character latin-1 cannot encode, are refused as BtcRpcValueError before the request is built, and a name or a value that is not a string as BtcRpcTypeError.
A url that is not http(s), has no host, a port that is no number, or a login is refused as BtcRpcValueError without repeating it: no message of this module carries a url beyond scheme://host[:port].
timeout is checked here and not only where BitcoinCoreRpcClient already does, because this function is public on its own: a caller reaching it directly with a transport of their own would otherwise forward a zero, a negative number, True or a NaN straight to that transport unexamined.
- bitcoin_core_rpc.transport.urlopen_transport(request: Request, timeout: float, *, max_body_size: int = 8001024) tuple[int, bytes][source]¶
Perform the request with urllib, reading a bounded response.
The default HttpTransport, and one of the two things here that open a socket. It maps nothing and interprets nothing: the status and the bytes go back as they arrived, and http_request is where the failures become the exceptions above.
Bounded while reading, the limit being a keyword with a default, so this function still is an HttpTransport – SessionTransport takes it the same way. A transport of someone else’s returns bytes it has already read, so all http_request can do for those is refuse to pass an oversized body on.
No redirect is followed: _OPENER above says why, and what a 30x arrives as is the HTTPError any other non-2xx status does.
timeout bounds the exchange and not each socket operation: the connection urllib builds for the request takes its deadline from it before it connects, and gives every step of the exchange what is left of that – so a peer that drips headers or a body one octet at a time cannot hold this call open past it.
The scheme, the timeout and the limit are checked here and not only where http_request already checks them, for the reason that function gives for its own copy: this one is public too, and it takes a Request a caller built. urlopen speaks file: and data: as well, so a request whose url came from configuration would otherwise make this transport read the local disk and report the bytes as a node’s answer – and an invalid control would be refused after the resource was opened rather than instead of opening it.
BitcoinCoreRpcClient, BitcoinCoreRestClient and RpcChannel.
The layer that decides what a status and a body mean: _reply_object, _legacy_result and _v2_result are the JSON-RPC 1.1 and 2.0 reply shapes, _discriminate is what picks between the latter two, and BitcoinCoreRpcClient.call is what builds the request they answer. call_batch sends several such requests in one HTTP exchange and reads each member’s reply with the same _discriminate, by way of _batch_reply_array’s array-shaped counterpart to _reply_object; call_raw builds one request the same way call does and hands back whatever _parsed_json_body parses, unread and unshaped past that.
BitcoinCoreRestClient is the other client this module builds, over Core’s -rest interface rather than its JSON-RPC one: no envelope to read at all, so get_bin and get_json alike check the status before trusting the body – get_json then reads it through call_raw’s own _parsed_json_body, unshaped, over a GET rather than a POST, and get_bin returns it with nothing parsed out of it at all. _checked_url, http_request and the chain and network tables are the whole of what the two clients share – one speaks JSON-RPC with the credentials Core requires for it, the other a plain GET Core requires none for, so nothing here folds the two into one class.
- class bitcoin_core_rpc.client.BitcoinCoreRestClient(url: str, *, timeout: float = 30.0, transport: ~collections.abc.Callable[[~urllib.request.Request, float], tuple[int, bytes]] = <function urlopen_transport>)[source]¶
Bases:
objectCore’s -rest interface: one node, no credentials, no envelope.
-rest is off by default (-rest=1) and, unlike the JSON-RPC server beside it, authenticates nobody who reaches it – an operator who turns it on knows that, so this class is what a caller who did speaks with, and not this package recommending it. It answers on the same port BitcoinCoreRpcClient reaches, which is what rpc_port_from_chain and from_chain below are for.
Two methods, because Core’s -rest answers two shapes and this client reads exactly them: get_bin for a .bin path, returning the body unread, and get_json for a .json one, returning what it parses to – the same Decimal-preserving parser call_raw reads its own envelope with, refusing NaN and the two infinities exactly as it does. .hex is the same octets as .bin, one more decode away from a caller who wants them that way, so it is not offered a method of its own.
A path is a path, and this client passes any. There is no get_tx, no get_block, no get_utxos: path is built by the caller from Core’s own documentation of -rest and appended after /rest unread. /getutxos is the reason a per-resource method is refused rather than merely undone here – it reads the UTXO set, so an output that has been spent and one that was never created answer the same way: neither is in the set, and -rest itself cannot tell the two apart. A wrapper turning that answer into None would read as telling a caller more than /getutxos does, when it tells them exactly as little. A caller who wants the output either way fetches the whole transaction through get_json and reads its own outputs, which is the one place the two cases are still told apart.
No credentials, because `-rest` takes none. The constructor takes no user, no password, no cookie_path: passing one would claim an authentication this interface does not perform, and a node behind a proxy that does add one is reached through transport=, the same seam BitcoinCoreRpcClient offers for the case it cannot cover either.
One request, no retry, for the reason BitcoinCoreRpcClient’s module docstring gives its own call: a caller who knows a GET is safe to repeat is free to loop, and this client does not decide that for it.
A non-200 status is HttpError, -rest having no error object of its own to read the way a JSON-RPC reply’s error member is read – a 404 for a transaction or a block Core does not have is the ordinary case, and its body is prose rather than anything to parse. Everything below the status is FetchError, exactly as http_request promises.
- classmethod from_chain(chain: str = 'main', *, timeout: float = 30.0, transport: ~collections.abc.Callable[[~urllib.request.Request, float], tuple[int, bytes]] = <function urlopen_transport>) BitcoinCoreRestClient[source]¶
Return a -rest client for the local node of one of Core’s chains.
The loopback url and the port, rpc_port_from_chain’s – -rest answers on the same port the JSON-RPC server does, there being no separate one to derive. It asks the node nothing, so it is no claim that one is listening on that port, still less that it was started with -rest: the first get_bin or get_json is what finds out, exactly as BitcoinCoreRpcClient.from_chain promises for its own first call.
- get_bin(path: str, *, request_timeout: float | None = None, max_body_size: int = 8001024) bytes[source]¶
Return the raw body of a GET to <url>/rest<path>.
path is appended after /rest unread – /tx/<txid>.bin, /block/<hash>.bin, /headers/<count>/<hash>.bin are Core’s own shapes for it. max_body_size is what DEFAULT_MAX_BODY_SIZE documents for call’s own reply: twice Core’s buffer bound on a serialized block, so a block as raw octets fits by default, and wider still for /headers, which answers several of them at once.
HttpError for a status that is not 200, -rest reporting a transaction or a block Core does not have with a 404 rather than with a reply this client could read a diagnosis out of.
- get_json(path: str, *, request_timeout: float | None = None, max_body_size: int = 8001024) Any[source]¶
Return the parsed json body of a GET to <url>/rest<path>.
path is appended after /rest unread – /chaininfo.json, /tx/<txid>.json, /getutxos/<outpoint>.json are Core’s own shapes for it. The body is read exactly as call_raw reads its own envelope, through the same _parsed_json_body: a Decimal for every floating-point number, an int for every integer, the three constants json has no number for refused, and nothing about the parsed value’s own shape asked – an object, an array, or a bare scalar all come back as parsed.
HttpError for a status that is not 200, checked before the body is parsed rather than left to _parsed_json_body’s own parse failure: a non-200 reply is not trusted as the node’s answer merely because its body happens to parse as json, -rest’s ordinary failure body being prose rather than an error object, but a proxy in front of the node under no such constraint.
- class bitcoin_core_rpc.client.BitcoinCoreRpcClient(url: str, *, user: str | None = None, password: str | None = None, cookie_path: str | ~os.PathLike[str] | None = None, timeout: float = 30.0, transport: ~collections.abc.Callable[[~urllib.request.Request, float], tuple[int, bytes]] = <function urlopen_transport>)[source]¶
Bases:
objectOne Bitcoin Core JSON-RPC endpoint, and the credentials to reach it.
Not a dataclass, and that is about the password: a generated __repr__ prints every field, so the credential would appear in any traceback or log line that renders the client.
Credentials or a cookie path, and not both: each of the two says who is calling, so a client given both would have to rank them, and a caller who passed both has a mistaken idea of which one is in use. from_chain is the constructor that fills in a cookie path, along with the port, from Core’s own defaults.
Concurrent calls are supported while the configuration is not mutated. call writes nothing on the client, opens its own connection and takes its request id from no shared counter, so one client serves any number of threads. What is not promised is a client whose url, credentials or transport are reassigned while a call is in flight, or a caller’s transport that is not itself thread-safe – that one is the transport’s own contract.
Basic authentication is cleartext over plain HTTP, as SECURITY.md says under Limitations, not vulnerabilities, which also says what keeps a credential off the wire.
One connection per call by default, urllib holding none open: every call sends Connection: close and opens a socket of its own. Beside the node that is a loopback connect, which costs nothing for one call and is socket churn for a great many – RFC 9112 section 9.6 has the server initiating the close on that option, so it is the node that holds the sockets in TIME_WAIT – and to a node reached over https it is a TLS handshake each time. SessionTransport is this module’s own alternative, one connection kept per (scheme, host, port) and reused across calls; passing it as transport= is what a caller polling one node in a loop wants, ahead of a requests session or an httpx client.
No call asks the node which chain it is on: the url and the cookie path say where to ask, and what the answers mean is the caller’s to hold. getblockchaininfo is the question, its chain member the answer, and network_from_chain the vocabulary to read it in – worth the one round trip, because a client built for a testnet node under code that believes it is on mainnet fails silently. from_chain’s verify_chain makes exactly that call once, at construction.
- assert_chain(chain: str = 'main', *, signet_challenge: str | bytes | bytearray | None = None) None[source]¶
Raise unless the node serves this chain, and this signet of it.
One round trip, getblockchaininfo, and the answer cannot change under a client that goes on pointing at the same node – so this is a question asked at a moment of the caller’s choosing: at startup, after a client was repointed, or by from_chain(verify_chain=True), which is this method.
Worth asking, because the failure it catches is silent. Nothing in an rpc exchange says which chain is behind it: a cookie authenticates the node that wrote it and not what that node is running, so a url, a datadir or an environment variable carried over from another host answers every call and answers about the wrong chain.
Signet is the case a name cannot settle. Core reports signet for the default signet and for every custom one alike, so two nodes sharing nothing but the shape of a challenge answer the same string; the challenge is what tells them apart, and the p2p magic it derives is what this compares – magic_from_signet_challenge of what the node reports, against the caller’s signet_challenge or, with none, magic_from_chain(“signet”). Comparing the derived magic rather than the challenge text is what makes a challenge written in upper case the same challenge.
A challenge off signet is refused before the reply is read: a caller passing one has a signet in mind and this client is on no signet at all, which is the caller’s configuration either way.
BtcRpcValueError for a disagreement, the node being the authority on what it serves and the client’s label therefore the thing to fix. FetchError for a reply with nothing to compare – a result that is not a mapping, a chain that is not a string, a signet answering without a signet_challenge member – this being an interpretation of an untrusted reply like any other.
- auth_header() str[source]¶
Return the Basic credential, from the arguments or the cookie.
RFC 7617 leaves the charset of the credential unspecified and Core compares the decoded bytes, so utf-8 is a choice that only matters for a password with a non-ascii character in it – where it is the choice that matches what a shell and a config file would have written.
- call(method: str, params: Sequence[Any] | Mapping[str, Any] | None = None, *, request_timeout: float | None = None, max_body_size: int = 8001024) Any[source]¶
Invoke one rpc method, returning its result.
params is one value, shaped as json-rpc shapes it: a sequence for the positional form, a mapping for the named one. The client’s own controls are keyword-only for that reason – timeout is a parameter of several Core methods, and a signature mixing the two would have to decide which of them owns the name.
Amounts need not travel as binary floating point in either direction: a floating-point number in the reply decodes as a Decimal, an integer as an int, and a Decimal parameter is written as the json number it is, digit for digit, which Core parses as an amount exactly. A float is written as its shortest repr, and the Decimal is what makes the digits the caller’s. NaN and Infinity are refused both ways, json having no numbers for them.
request_timeout is this call’s, defaulting to the client’s, and for the default transport it bounds the whole exchange – the node’s thinking and the reply’s arrival together. What it is for is the methods that legitimately run long – rescanblockchain, scantxoutset, dumptxoutset – and the replies large enough to take a while on the wire; the alternative is a second client whose wider timeout applies to everything.
max_body_size is what the reply may weigh: widen it for the answers larger than the default, which DEFAULT_MAX_BODY_SIZE names, and tighten it where the reply is a number, this being the caller’s node and the caller’s memory.
There is no retry: one call is one HTTP request, whatever comes back. HttpError.status is what a caller’s own policy reads, and this module’s docstring says why the policy is theirs.
- call_batch(calls: Iterable[tuple[str, Sequence[Any] | Mapping[str, Any] | None]], *, request_timeout: float | None = None, max_body_size: int = 8001024) list[Any][source]¶
Invoke several rpc methods in one HTTP request.
calls is an iterable of (method, params) pairs, one per member, read once, so a generator serves as well as a list; params is shaped exactly as call’s own – a sequence for the positional form, a mapping for the named one, None for no parameters at all. Each member is built the way call builds its one request: the 2.0 marker, an id of its own from the same source call draws from, and the same params validation – a member that fails it is refused before anything is sent, naming its position in calls rather than a position in a request Core never sees. A member that is not a sequence of two is refused the same way, with BtcRpcTypeError, and so is a calls that is a str or is not iterable at all.
The answer is a list aligned with calls rather than with whatever order the array came back in: position i holds member i’s result, or its RpcError as a value – a batch partly failing is the ordinary case, and raising the first error would discard every answer beside it. JSON-RPC 2.0 section 6 lets the replies arrive in any order, matched by id, and that is how this aligns them: never by position in the reply array.
Only a failure of the whole exchange raises, exactly as call raises – HttpError or FetchError for the lot: a non-2xx status, a reply that is not an array, a reply that cannot be attributed to any member, or a member with no reply among them. Each member’s own reply, once correlated by id, is read by the same _reply_object-then-version discrimination call reads its own with; there is no second parsing branch for a batch’s shape.
request_timeout and max_body_size are call’s own controls, and what each bounds changes shape here: this is one HTTP exchange that is now N node operations, so request_timeout bounds all of them together rather than one, and max_body_size bounds the sum of every member’s reply rather than any one of them – widen either the way a single large call would ask you to, and for the same reason.
A calls yielding no pair is refused with BtcRpcValueError, where an empty str is one of the BtcRpcTypeError refusals above: JSON-RPC 2.0 section 6 has no shape for a batch of zero requests, its own rule being that the server’s answer to an invalid batch is a single reply object rather than the array this method promises.
- call_raw(method: str, params: Sequence[Any] | Mapping[str, Any] | None = None, *, jsonrpc: str | None = '2.0', request_timeout: float | None = None, max_body_size: int = 8001024) tuple[int, Any][source]¶
Send one rpc request and hand back the envelope, unread.
The same authenticated POST call builds – this url, the Authorization header, USER_AGENT, a fresh id, the same params validation – with the protocol marker itself an argument rather than the “2.0” call always sends: a string is sent verbatim as jsonrpc, None sends no jsonrpc member at all, and the default is “2.0”, call’s own.
The answer is the pair as it arrived: the HTTP status, and whatever _parsed_json_body safely parses the body into – Decimal numbers, the three non-number constants refused – but not interpreted: no id check, no version discrimination, no RpcError raised, no result extracted, and no shape assumed either. A conformant node answers with a json object, but this is the seam a caller tests a server’s own conformance through, so an array, a bare string or number, or null comes back exactly as parsed rather than being refused the way call’s own reply has to be – _reply_object’s object-shape gate is a rule about a correlated answer, which is one interpretation this method does not make. What the envelope holds is the caller’s own question, so the envelope is the answer, read exactly as far as call reads before it starts asking what the reply means.
Below the status everything stays a FetchError, exactly as http_request promises: a refused connection, an expired timeout, a body that is not json at all – a non-200 status with an unparsable body is HttpError, precisely as it is for call. This is a raw reply, not raw bytes – a caller wanting the bytes has http_request and auth_header() already, both public.
Deliberately out of scope: a request this client refuses to build – a missing method, a non-string one, params that are neither a sequence nor a mapping. A client constructing an invalid request on purpose is a conformance harness’s job, and http_request is the public seam such a harness builds on.
- for_wallet(wallet_name: str) BitcoinCoreRpcClient[source]¶
Return a client for this node’s /wallet/<name> endpoint.
Which is how a node with several wallets loaded is told which one a wallet command is about. The name is percent-encoded, a wallet being a directory and free to be called anything a filesystem accepts: a space, a # or a / written into the path unencoded addresses a different endpoint, or none.
The credentials, the timeout and the transport are this client’s, the endpoint being the only difference – so a caller working on several wallets builds one client and derives the rest, each from that one client and not from another wallet’s: a client that is already a wallet endpoint is one this refuses to extend, naming the client to call it on.
type(self) and not this class by name, as from_chain builds with cls: a subclass that derives a wallet client keeps whatever it added.
- classmethod from_chain(chain: str = 'main', *, user: str | None = None, password: str | None = None, cookie_path: str | ~os.PathLike[str] | None = None, timeout: float = 30.0, transport: ~collections.abc.Callable[[~urllib.request.Request, float], tuple[int, bytes]] = <function urlopen_transport>, verify_chain: bool = False, signet_challenge: str | bytes | bytearray | None = None) BitcoinCoreRpcClient[source]¶
Return a client for the local node of one of Core’s chains.
The convenience of not writing out a loopback url, a port and a datadir: all three come from Core’s own tables, and everything else is the constructor’s. chain is spelled as Core spells it, so main where BIP32 and BIP173 say mainnet; chain_from_network translates for a caller holding a BIP name, and a chain Core has no default port for is an explicit url with a cookie_path, which is the constructor.
It asks the node nothing, so it is no claim that one is listening on that port, nor that it serves this chain if it is. The first call is what finds out – unless verify_chain says to ask now, which is assert_chain and its docstring for what that settles.
Off by default, because a cookie authenticates only that the node is the one this call was told about – a file only that node could have written – and says nothing about which chain it is running: -chain=test and a main cookie both exist. A caller for whom that gap matters – a cookie path or a datadir carried over from a differently-configured host, an environment variable naming the wrong chain – opts in and gets BtcRpcValueError naming both chains instead of a wrong-network call succeeding silently, at the cost of one round trip here rather than trust in every call after.
signet_challenge is the signet the caller means, and is what assert_chain compares by: without it, signet means the default signet and a node on any other is refused. It is the one argument here that does nothing to the client built – every signet answers on 38332 and keeps its cookie in the same subdirectory – so it is refused rather than ignored when verify_chain is off, that being a caller expecting a check that would not be made.
The datadir comes from default_datadir at this call, which is Core’s own for the platform underneath; where there is no absolute directory to hang it off, deriving a cookie path is what this refuses – naming cookie_path as the answer.
Nothing is derived when the caller said who is calling: a user or a password, either of them, is an answer to that question, and the constructor is where the two are held to going together. A cookie derived before that check would report a missing home directory to a caller who passed a password and forgot the user.
- class bitcoin_core_rpc.client.RpcChannel(client: BitcoinCoreRpcClient)[source]¶
Bases:
objectAttribute-style convenience over a client’s call.
channel.getblockcount() is client.call(“getblockcount”). channel.getblock(block_hash, 2) passes the positional form, channel.getblock(blockhash=block_hash, verbosity=2) the named one – whichever the caller wrote, since json-rpc has one params shape per call and not both at once.
request_timeout and max_body_size, call’s own keyword-only controls, are caught by the wrapper and passed to call rather than travelling to the node as named rpc parameters. That reservation is why this class lives here rather than in a caller’s own script: it has to know which names are call’s own, that list is this module’s to grow, and a copy written against one release is silently wrong against a later one that adds a third control – neither mypy nor a test catches a keyword that now reaches Core instead of this class.
A hand-written guard sits in front of every name starting with _, dunders included. Without it, copy.deepcopy, a pickling path this object does not otherwise reach, and an interactive shell probing for _repr_html_ or _ipython_canary_method_should_not_exist_ would each turn into a bound method for an rpc call of that name – and calling one is not the same failure as an AttributeError a caller can catch by name.
client, the one public attribute, is reserved for the same reason: it is how a caller reaches the BitcoinCoreRpcClient this channel wraps, and an rpc method named client – Core has none – would otherwise shadow it.
Not BitcoinCoreRpcClient.__getattr__: that class stays the explicit surface call(method, params) is, where an unknown attribute is an AttributeError and for_walet(“hot”) a typo caught at the call rather than one more method name sent to the node. This is the opt-in beside it, for a caller who has weighed that trade the other way for a given script.
- bitcoin_core_rpc.client.USER_AGENT = 'bitcoin-core-rpc'¶
What call sends as User-Agent, and a transport of a caller’s own can.
urllib’s default names the interpreter – Python-urllib/3.14 – which identifies neither this client nor the program running it, where a node’s access log and any proxy in front of it record this. No version in it: the release tag is the version, and a constant inside the package is a second one that drifts against it.