Please check the build logs for more information.
See Builds for ideas on how to fix a failed build, or Metadata for how to configure docs.rs builds.
If you believe this is docs.rs' fault, open an issue.
bitcoin-remote
Low-level, zero-magic utilities for speaking Bitcoin Core's JSON‑RPC over HTTP, faithfully ported from upstream C++ with strongly typed Rust interfaces.
This crate does not try to be a full Bitcoin wallet or a high-level client library. Instead, it focuses on being a precise, observable, and testable substrate for:
- constructing and serializing JSON‑RPC requests and replies,
- handling Bitcoin Core's RPC error model (codes and HTTP mappings),
- managing
rpcauth/cookie-based authentication, - resolving Bitcoin-style configuration paths,
- and handling parameter-conversion metadata reproduced from Bitcoin Core's own RPC tables.
If you want exact behavioral parity with bitcoind's RPC interface—down to error codes, HTTP status behavior, and batch semantics—this crate is intended for you.
Features at a Glance
-
HTTP / JSON‑RPC fidelity
HTTPStatusCodeenum for mapping internal failures to HTTP status codes.- JSON‑RPC 1.0 compatible wire format with selective adoption of 1.1/2.0 semantics for error structure.
- Batch‑reply processing that mirrors upstream C++ behavior, including panic conditions on malformed replies.
-
Bitcoin Core RPC error codes
RPCErrorCodeis abitflags!set of all Bitcoin Core RPC error codes, including wallet, P2P, chain, and general application errors.- Aliases for backward compatibility (e.g.
RPC_TRANSACTION_ERROR) closely track upstream.
-
RPC parameter conversion metadata
RPCConvertParamandRPCConvertTableencode which RPC parameters must be treated as JSON even when passed as textual CLI arguments.- Lookup by
(method, index)or(method, name)gives you a boolean indicating whether a parameter must be JSON‑parsed before being passed to Core.
-
Authentication cookie helpers
generate_auth_cookie,get_auth_cookie, anddelete_auth_cookieimplement the same cookie‑file strategy as Bitcoin Core:- random password generation
- temporary file + atomic rename
- respect for
-rpccookiefilefrom global args
-
JSON‑RPC request and response composition
JSONRPCRequestencapsulates method, params, id, and metadata likeuri,auth_user, andpeer_addr.jsonrpc_request_obj,jsonrpc_reply_obj,jsonrpc_reply, andjsonrpc_errorare low-level helpers overUniValue.
-
Instrumentation
- Strategic, structured logging via the
tracingcrate at trace/debug/info levels, intended for production observability without polluting the hot path.
- Strategic, structured logging via the
The crate assumes you are comfortable working close to the protocol: you will handle HTTP transport concerns, lifetimes, and concurrency at your own abstraction layer.
Design Philosophy
The design mirrors Bitcoin Core's internals:
- Minimal abstraction leak: the Rust types are thin wrappers around the behavior of upstream C++ constructs, including panic conditions and error code usage.
- Deterministic edge behavior: malformed batch responses, invalid request objects, and type errors produce panics consistent with the original exception‑throwing C++ implementation.
- Explicit data flow: all JSON objects are composed using
UniValue(fromuni_value), notserde_json, to follow Core's semantics exactly.
The goal is to allow you to reconstruct, inspect, and control your interaction with a Bitcoin node with maximal transparency.
Core Types and Modules
HTTPStatusCode
HTTPStatusCode encodes the subset of HTTP codes relevant to JSON‑RPC error mapping. Upstream Core maps certain RPC errors to specific HTTP codes (e.g. RPC_INVALID_REQUEST → HTTP_BAD_REQUEST). Use this when designing your HTTP layer.
JSONRPCRequestMode
JSONRPCRequestMode allows you to model whether an incoming request is meant to be executed or used for help/argument introspection. This is primarily useful for CLI frontends or meta‑RPC layers.
RPCErrorCode (bitflags)
RPCErrorCode is defined using bitflags! over i32. It enumerates the entire Bitcoin Core RPC error space:
- Standard JSON‑RPC 2.0 errors:
RPC_INVALID_REQUEST,RPC_METHOD_NOT_FOUND,RPC_INVALID_PARAMS,RPC_INTERNAL_ERROR,RPC_PARSE_ERROR. - General application errors:
RPC_MISC_ERROR,RPC_TYPE_ERROR,RPC_INVALID_PARAMETER, etc. - P2P client errors:
RPC_CLIENT_NOT_CONNECTED,RPC_CLIENT_IN_INITIAL_DOWNLOAD,RPC_CLIENT_NODE_CAPACITY_REACHED, etc. - Chain and mempool errors.
- Wallet errors:
RPC_WALLET_ERROR,RPC_WALLET_INSUFFICIENT_FUNDS,RPC_WALLET_UNLOCK_NEEDED,RPC_WALLET_ALREADY_LOADED, etc. - Legacy aliases and reserved codes, retained for backwards compatibility.
Each error is a bitflag with a specific negative code matching Bitcoin Core's public RPC interface. Example:
use RPCErrorCode;
Using a bitflag type instead of raw i32 clarifies intent and allows consistent code completion.
RPCConvertParam & RPCConvertTable
Bitcoin Core distinguishes between positional and named RPC parameters that must be treated as JSON instead of simple strings. For example, sendrawtransaction expects a hex string, whereas createrawtransaction may expect complex JSON objects.
This crate mirrors Core's table‑driven approach using:
and the global instance:
lazy_static!
RPCConvertTable::new() populates members and members_by_name from a static vRPCConvertParams list emitted from upstream definitions. You can query it as follows:
use RPC_CVT_TABLE;
These APIs are intentionally simple: they answer "must this parameter be JSON‑parsed?" without hiding the table's structure.
JSONRPCRequest
The parse method implements JSON‑RPC request parsing consistent with Bitcoin Core:
- Validates that the top-level value is an object.
- Extracts
idearly so subsequent error reports can include it. - Checks
methodis present and a string. - Accepts
paramsas either an array or object;nullbecomes an empty array; all other types panic as invalid.
Example:
use ;
use ;
Because the implementation intentionally panics on structural violations (mirroring C++ exceptions), you should either sanitize input at your HTTP boundary or wrap parsing in higher‑level error handling if you need a non‑panic path.
JSON‑RPC Utilities
Building requests
Creates a minimal JSON‑RPC request object:
Example:
use jsonrpc_request_obj;
use ;
let mut params = new;
params.push_back;
let id = from;
let req = jsonrpc_request_obj;
let wire = req.write;
Building replies and errors
Semantics:
- If
erroris notnull, the reply's"result"field is forced tonull. jsonrpc_replyserializes the reply to a compact string and appends a newline (matching Core'swrite() + "\n").
Example:
use ;
use UniValue;
// success reply
let result = from;
let error = null;
let id = from;
let success_wire = jsonrpc_reply;
// error reply
let err_obj = jsonrpc_error;
let error_wire = jsonrpc_reply;
Batch reply processing
Parses a batch reply into a Vec<UniValue> indexed by numeric "id":
in_must be an array; otherwise the function panics with "Batch must be an array".- Each member must be an object; non‑objects panic with "Batch member must be an object".
- Each member must have an integer
"id"between0andbatch_size - 1; otherwise, a panic with "Batch member id is larger than batch size" occurs.
This deterministic behavior makes it straightforward to implement batch clients that rely strictly on index‑based mapping.
Example:
use jsonrpc_process_batch_reply;
use ;
Authentication Cookie Helpers
Bitcoin Core supports a cookie‑file based authentication mechanism. This crate provides low-level helpers that implement the same behavior, including path resolution and atomic writes.
get_auth_cookie_file
- Resolves the absolute path for the RPC auth cookie.
- If
temp == Some(true), appends.tmpand returns the path for the temporary file location. - Uses
-rpccookiefile=<path>from global args if present; otherwise it falls back to the default (typically something like$DATADIR/.cookie).
generate_auth_cookie
Steps:
- Generate 32 random bytes and hex‑encode them as the password portion.
- Construct
"<COOKIEAUTH_USER>:<hex_password>". - Write to the temporary cookie file (
.tmp), creating parent directories as needed. - Atomically rename the temporary file to the final auth cookie path.
On success, cookie_out is populated and true is returned. Errors are logged via tracing::error! and false is returned; best‑effort clean‑up is attempted.
Example:
use generate_auth_cookie;
let mut cookie = Stringnew;
if generate_auth_cookie
get_auth_cookie
- Reads the cookie from disk into
cookie_out. - Trims trailing
\nand optional\rto match C++getlinebehavior. - Returns
falseif the file cannot be opened or read, logging atdebugorwarnlevels.
delete_auth_cookie
Attempts to delete the cookie file. Any I/O error other than file not found is logged but otherwise ignored.
Example integration pattern:
use ;
Error Semantics and Stability
- Panics vs. errors: many functions (
JSONRPCRequest::parse,jsonrpc_process_batch_reply) intentionally usepanic!on structural violations, to mimic Bitcoin Core's use of exceptions for programmer / protocol errors rather than expected runtime failures. - Logging:
trace!,debug!,info!,warn!, anderror!invocations align with logical phases—construction, parsing, and I/O. In production, you can adjust yourtracingsubscriber level to tune verbosity. - Error codes:
RPCErrorCodevalues are kept numerically identical to upstream. Where upstream deprecates or repurposes codes, the crate favors backward compatibility.
If you are building public APIs or user‑facing tooling on top of this crate, you may want to wrap these primitives into a non‑panicking facade that translates panics into structured error values.
Example: End‑to‑End Single Call
Below is a sketch of how you might integrate bitcoin-remote into a higher-level HTTP client. This example omits error‑handling and TLS for brevity.
use ;
use ;
Crate Metadata
- Crate name:
bitcoin-remote - Version:
0.1.22 - Edition: Rust 2021
- License: MIT
- Repository: https://github.com/klebs6/bitcoin-rs
- Primary author:
klebs <none>
Caveats
- This README was produced by an AI model and may diverge slightly from the exact current API surface, especially around auxiliary functions and constants not shown in the provided interface.
- Always rely on the actual Rustdoc and source code in the repository for authoritative reference.