RPC Service Reference Documentation
Index
- Overview
- Types
- RPCServer
- Functions
- NewServer
- Methods
- Start
- Stop
- Init
- Health
- checkAuth
- jsonRPCRead
- RPC Handlers
- Configuration
- Authentication
- General Format
- Supported RPC Commands
- createrawtransaction - Creates a raw transaction without signing it
- generate - Mine blocks (for regression testing)
- generatetoaddress - Mine blocks to a specified address
- getbestblockhash - Returns the hash of the best (most recent) block in the longest blockchain
- getblock - Returns information about a block
- getblockbyheight - Returns information about a block at the specified height
- getblockhash - Returns the hash of a block at the specified height
- getblockheader - Returns information about a block header
- getblockchaininfo - Returns blockchain state information
- getdifficulty - Returns the proof-of-work difficulty
- getinfo - Returns general information about the node
- getmininginfo - Returns mining-related information
- getpeerinfo - Returns data about each connected network node
- getrawtransaction - Returns raw transaction data
- getminingcandidate - Returns mining candidate information for generating a new block
- help - Lists all available commands or gets help on a specific command
- invalidateblock - Permanently marks a block as invalid
- isbanned - Checks if an IP/subnet is banned
- listbanned - Lists all banned IPs/subnets
- clearbanned - Clears all banned IPs
- reconsiderblock - Removes invalidity status from a block
- sendrawtransaction - Submits a raw transaction to the network
- setban - Attempts to add or remove an IP/subnet from the banned list
- stop - Stops the server
- submitminingsolution - Submits a mining solution to the network
- version - Returns the server version information
- freeze - Freezes specified UTXOs or OUTPUTs
- unfreeze - Unfreezes specified UTXOs or OUTPUTs
- reassign - Reassigns specified frozen UTXOs to a new address
- Unimplemented RPC Commands
- Error Handling
- Rate Limiting
- Version Compatibility
- Concurrency
- Extensibility
- Limitations
- Security
Overview
The RPC Service provides a JSON-RPC interface for interacting with the Bitcoin SV node. It handles various Bitcoin-related commands and manages client connections. The service implements a standard Bitcoin protocol interface while integrating with Teranode's modular architecture to provide high-performance access to blockchain data and network operations.
Types
RPCServer
type RPCServer struct {
settings *settings.Settings
started int32
shutdown int32
authsha [sha256.Size]byte
limitauthsha [sha256.Size]byte
numClients int32
statusLines map[int]string
statusLock sync.RWMutex
wg sync.WaitGroup
requestProcessShutdown chan struct{}
quit chan int
logger ulogger.Logger
rpcMaxClients int
rpcQuirks bool
listeners []net.Listener
blockchainClient blockchain.ClientI
blockAssemblyClient *blockassembly.Client
peerClient peer.ClientI
p2pClient p2p.ClientI
assetHTTPURL *url.URL
helpCacher *helpCacher
utxoStore utxo.Store
}
The RPCServer provides a concurrent-safe JSON-RPC server implementation for the Bitcoin protocol. It handles client authentication, request processing, response generation, and maintains connections to other Teranode services to fulfill RPC requests.
The server implements a two-tier authentication system that separates administrative capabilities from limited-user operations, providing security through proper authorization. It supports standard Bitcoin Core RPC methods and Bitcoin SV extensions for compatibility with existing tools while enhancing functionality.
The RPCServer is designed for concurrent operation, employing synchronization mechanisms to handle multiple simultaneous client connections without race conditions or resource conflicts. It implements proper connection management, graceful shutdown, and health monitoring.
Functions
NewServer
func NewServer(logger ulogger.Logger, tSettings *settings.Settings, blockchainClient blockchain.ClientI, utxoStore utxo.Store) (*RPCServer, error)
Creates a new instance of the RPC Service with the necessary dependencies including logger, settings, blockchain client, and UTXO store.
This factory function creates a fully configured RPCServer instance, setting up:
- Authentication credentials from settings
- Connection limits and parameters
- Command handlers and help text
- Client connections to required services
The RPC server requires connections to several other Teranode services to function properly, as it primarily serves as an API gateway to underlying node functionality. These dependencies are injected through this constructor to maintain proper service separation and testability.
Methods
Start
func (s *RPCServer) Start(ctx context.Context, readyCh chan<- struct{}) error
Initialization Tasks
Starts the RPC server, begins listening for client connections, and signals readiness by closing the readyCh channel once initialization is complete.
This method performs several critical initialization tasks:
- Validates the server has not already been started (using atomic operations)
- Initializes network listeners on all configured interfaces and ports
- Launches goroutines to accept and process incoming connections
- Sets up proper handling for clean shutdown
- Signals readiness through the provided channel
The server supports binding to multiple addresses simultaneously, allowing both IPv4 and IPv6 connections, as well as restricting access to localhost-only if configured for development or testing environments.
Stop
func (s *RPCServer) Stop(ctx context.Context) error
Gracefully shuts down the RPC server and its associated resources. It ensures that any in-progress requests are allowed to complete before terminating, and that all network connections are properly closed.
This method implements a thread-safe shutdown mechanism using atomic operations to prevent multiple concurrent shutdown attempts. When called, it closes the quit channel to signal all goroutines to terminate, then waits for them to exit using the wait group before returning.
Init
func (s *RPCServer) Init(ctx context.Context) (err error)
Performs second-stage initialization of the RPC server by establishing connections to dependent services that weren't available during initial construction.
Initialization Steps
This method completes the RPC server initialization by:
- Connecting to the Block Assembly service for mining-related operations
- Connecting to the P2P service for network peer management
- Connecting to the Legacy service for compatibility with older protocols
- Refreshing the help cache with complete command information
The initialization is designed to be idempotent and can be safely called multiple times, though typically it's only called once after NewServer and before Start.
Health
func (s *RPCServer) Health(ctx context.Context, checkLiveness bool) (int, string, error)
Reports the operational status of the RPC service for monitoring and health checking.
This method implements the standard Teranode health checking interface used across all services for consistent monitoring, alerting, and orchestration.
Health Check Types
It provides both readiness and liveness checking capabilities to support different operational scenarios:
- Readiness: Indicates whether the service is ready to accept requests (listeners are bound and core dependencies are available)
- Liveness: Indicates whether the service is functioning correctly (listeners are still working and not in a hung state)
Health Check Components:
- Verifying network listeners are active
- Checking connections to dependent services
- Validating internal state consistency
checkAuth
func (s *RPCServer) checkAuth(r *http.Request, require bool) (bool, bool, error)
Implements the two-tier HTTP Basic authentication system for RPC clients. It validates credentials supplied in the HTTP request against configured admin and limited-access username/password combinations.
Authentication Flow
The method implements a secure authentication flow that:
- Extracts the Authorization header from the HTTP request
- Validates the credentials against both admin and limited-user authentication strings
- Uses time-constant comparison operations to prevent timing attacks
- Distinguishes between admin users (who can perform state-changing operations) and limited users (who can only perform read-only operations)
Security Considerations
- Uses SHA256 for credential hashing
- Implements constant-time comparison to prevent timing attacks
- Properly handles missing or malformed authentication headers
- Can be configured to require or not require authentication based on settings
Returns:
bool
: Authentication success (true if successful)bool
: Authorization level (true for admin access, false for limited access). The value specifies whether the user can change the state of the node.error
: Authentication error if any occurred, nil on success
jsonRPCRead
func (s *RPCServer) jsonRPCRead(w http.ResponseWriter, r *http.Request, isAdmin bool)
Handles reading and responding to RPC messages. This method is the core request processing function.
Request Processing Steps
- Parses incoming JSON-RPC requests from HTTP request bodies
- Validates request format and structure
- Routes requests to appropriate command handlers
- Formats and sends responses back to clients
- Implements proper error handling and serialization
- Ensures thread-safety for concurrent request handling
The method supports batch requests, proper HTTP status codes, and includes safeguards against oversized or malformed requests. It also handles authorization checking to ensure admin-only commands cannot be executed by limited-access users.
RPC Handlers
The RPC Service implements various handlers for Bitcoin-related commands. All handlers follow a consistent function signature:
func handleCommand(ctx context.Context, s *RPCServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error)
Each handler receives a context for cancellation and tracing, the RPC server instance, parsed command parameters, and a close notification channel. They return a properly formatted response object or an error.
Some key handlers include:
handleGetBlock
: Retrieves block information at different verbosity levelshandleGetBlockHash
: Gets the hash of a block at a specific heighthandleGetBestBlockHash
: Retrieves the hash of the best (most recent) blockhandleCreateRawTransaction
: Creates a raw transactionhandleSendRawTransaction
: Broadcasts a raw transaction to the networkhandleGetMiningCandidate
: Retrieves a candidate block for mininghandleSubmitMiningSolution
: Submits a solved block to the networkhandleFreeze
: Freezes specified UTXOs to prevent spendinghandleUnfreeze
: Unfreezes previously frozen UTXOshandleReassign
: Reassigns specified frozen UTXOs to a new addresshandleSetBan
: Adds or removes IP addresses/subnets from the node's ban listhandleClearBanned
: Removes all bans from the nodehandleListBanned
: Lists all currently banned IP addresses and subnets
Configuration
RPC Configuration Settings
The RPC Service uses various configuration values:
Authentication Settings:
rpc_user
andrpc_pass
: Credentials for RPC authentication with full admin privileges-
rpc_limit_user
andrpc_limit_pass
: Credentials for limited RPC access (read-only operations)Connection Settings: -
rpc_max_clients
: Maximum number of concurrent RPC clients (default: 1000) -rpc_listener_url
: URL for the RPC listener (default: "http://localhost:8332") -rpc_listeners
: List of URLs for multiple RPC listeners (overrides rpc_listener_url if set)Security Settings: -
rpc_tls_enabled
: Enables TLS for secure RPC connections (default: false) -rpc_tls_cert_file
: Path to TLS certificate file -rpc_tls_key_file
: Path to TLS private key file -rpc_auth_timeouts_seconds
: Timeout for authentication in seconds (default: 10)Compatibility Settings: -
rpc_quirks
: Enables compatibility quirks for legacy clients (default: false)Production Warnings
rpc_disable_auth
: Disables authentication (NOT recommended for production)rpc_cross_origin
: Allows cross-origin requests (NOT recommended for production)
Configuration values can be provided through the configuration file, environment variables, or command-line flags, with precedence in that order.
Authentication
Authentication Levels
The server supports two levels of authentication:
- Admin-level access with full permissions
- Limited access with restricted permissions
Authentication is performed using HTTP Basic Auth.
Credential Provision Methods:
- Username and password in the HTTP header
- Cookie-based authentication
- Configuration file settings
General Format
Request Requirements
All requests should be POST requests with Content-Type: application/json.
Request format:
{
"jsonrpc": "1.0",
"id": "id",
"method": "method_name",
"params": []
}
Supported RPC Commands
The following RPC commands are fully implemented and supported in the current version of the node.
createrawtransaction
Creates a raw Bitcoin transaction without signing it.
Parameters:
1. inputs
(array, required):
[
{
"txid": "hex_string", // The transaction id
"vout": n // The output number
}
]
outputs
(object, required):
{
"address": x.xxx, // Bitcoin address:amount pairs
"data": "hex" // Optional data output
}
Returns:
string
- hex-encoded raw transaction
Example Request:
{
"jsonrpc": "1.0",
"id": "curltest",
"method": "createrawtransaction",
"params": [
[{"txid":"1234abcd...", "vout":0}],
{"1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa": 0.01}
]
}
Example Response:
{
"result": "0200000001abcd1234...00000000",
"error": null,
"id": "curltest"
}
generate
Mines blocks immediately (for testing only).
Parameters:
nblocks
(numeric, required) - Number of blocks to generatemaxtries
(numeric, optional) - Maximum number of iterations to try
Returns:
array
- hashes of blocks generated
Example Request:
{
"jsonrpc": "1.0",
"id": "curltest",
"method": "generate",
"params": [1, 1000000]
}
Example Response:
{
"result": [
"36252b5852a5921bdfca8701f936b39edeb1f8c39fffe73b0d8437921401f9af"
],
"error": null,
"id": "curltest"
}
getbestblockhash
Returns the hash of the best (tip) block in the longest blockchain.
Parameters: none
Returns:
string
- The block hash
Example Request:
{
"jsonrpc": "1.0",
"id": "curltest",
"method": "getbestblockhash",
"params": []
}
Example Response:
{
"result": "000000000000000004a1b6d6fdfa0d0a0e52a7a2c8a35ee5b5a7518a846387bc",
"error": null,
"id": "curltest"
}
getblock
Returns information about a block.
Parameters:
blockhash
(string, required) - The block hashverbosity
(numeric, optional, default=1) - 0 for hex-encoded data, 1 for a json object, 2 for json object with transaction data
Returns:
- If verbosity is 0:
string
- hex-encoded block data - If verbosity is 1 or 2:
object
- JSON object with block information
Example Request:
{
"jsonrpc": "1.0",
"id": "curltest",
"method": "getblock",
"params": [
"000000000000000004a1b6d6fdfa0d0a0e52a7a2c8a35ee5b5a7518a846387bc",
1
]
}
Example Response:
{
"result": {
"hash": "000000000000000004a1b6d6fdfa0d0a0e52a7a2c8a35ee5b5a7518a846387bc",
"confirmations": 1,
"size": 1000,
"height": 1000,
"version": 1,
"versionHex": "00000001",
"merkleroot": "4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b",
"tx": ["4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"],
"time": 1231006505,
"mediantime": 1231006505,
"nonce": 2083236893,
"bits": "1d00ffff",
"difficulty": 1,
"chainwork": "0000000000000000000000000000000000000000000000000000000100010001",
"previousblockhash": "00000000839a8e6886ab5951d76f411475428afc90947ee320161bbf18eb6048"
},
"error": null,
"id": "curltest"
}
getblockbyheight
Returns information about a block at the specified height in the blockchain. This is similar to getblock
but uses a height parameter instead of a hash.
Parameters:
height
(numeric, required) - The height of the blockverbosity
(numeric, optional, default=1) - 0 for hex-encoded data, 1 for a json object, 2 for json object with transaction data
Returns:
- If verbosity is 0:
string
- hex-encoded block data - If verbosity is 1 or 2:
object
- JSON object with block information
Example Request:
{
"jsonrpc": "1.0",
"id": "curltest",
"method": "getblockbyheight",
"params": [2]
}
Example Response:
{
"result":
{
"hash": "000000000000000004a1b6d6fdfa0d0a0e52a7a2c8a35ee5b5a7518a846387bc",
"height": 2,
"version": 1,
"versionHex": "00000001",
"merkleroot": "4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b",
"time": 1231006505,
"nonce": 2083236893,
"bits": "1d00ffff",
"difficulty": 1,
"previousblockhash": "00000000839a8e6886ab5951d76f411475428afc90947ee320161bbf18eb6048",
"tx": ["4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"],
"size": 285,
"confirmations": 750000
},
"error": null,
"id": "curltest"
}
getblockhash
Returns the hash of block at the specified height in the blockchain.
Parameters:
height
(numeric, required) - The height of the block
Returns:
string
- The block hash
Example Request:
{
"jsonrpc": "1.0",
"id": "curltest",
"method": "getblockhash",
"params": [2]
}
Example Response:
{
"result": "000000000000000004a1b6d6fdfa0d0a0e52a7a2c8a35ee5b5a7518a846387bc",
"error": null,
"id": "curltest"
}
getblockheader
Returns information about a block header.
Parameters:
hash
(string, required) - The block hashverbose
(boolean, optional, default=true) - true for a json object, false for the hex-encoded data
Returns:
- If verbose=false:
string
- hex-encoded block header - If verbose=true:
object
- JSON object with header information
Example Request:
{
"jsonrpc": "1.0",
"id": "curltest",
"method": "getblockheader",
"params": [
"000000000000000004a1b6d6fdfa0d0a0e52a7a2c8a35ee5b5a7518a846387bc",
true
]
}
Example Response:
{
"result": {
"hash": "000000000000000004a1b6d6fdfa0d0a0e52a7a2c8a35ee5b5a7518a846387bc",
"version": 1,
"versionHex": "00000001",
"previoushash": "00000000839a8e6886ab5951d76f411475428afc90947ee320161bbf18eb6048",
"merkleroot": "4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b",
"time": 1231006505,
"nonce": 2083236893,
"bits": "1d00ffff",
"difficulty": 1,
"height": 1000
},
"error": null,
"id": "curltest"
}
getdifficulty
Returns the proof-of-work difficulty as a multiple of the minimum difficulty.
Parameters: none
Returns:
number
- The current difficulty
Example Request:
{
"jsonrpc": "1.0",
"id": "curltest",
"method": "getdifficulty",
"params": []
}
Example Response:
{
"result": 21448277761059.71,
"error": null,
"id": "curltest"
}
getmininginfo
Returns a json object containing mining-related information.
Parameters: none
Returns:
{
"blocks": number, // The current block count
"currentblocksize": number, // The last block size
"currentblocktx": number, // The last block transaction count
"difficulty": number, // The current difficulty
"errors": "string", // Current errors
"networkhashps": number, // The estimated network hashes per second
"chain": "string" // Current network name (main, test, regtest)
}
Example Request:
{
"jsonrpc": "1.0",
"id": "curltest",
"method": "getmininginfo",
"params": []
}
Example Response:
{
"result": {
"blocks": 750000,
"currentblocksize": 1000000,
"currentblocktx": 2000,
"difficulty": 21448277761059.71,
"errors": "",
"networkhashps": 7.088e+17,
"chain": "main"
},
"error": null,
"id": "curltest"
}
sendrawtransaction
Submits a raw transaction to the network.
Parameters:
hexstring
(string, required) - The hex string of the raw transactionallowhighfees
(boolean, optional, default=false) - Allow high fees
Returns:
string
- The transaction hash in hex
Example Request:
{
"jsonrpc": "1.0",
"id": "curltest",
"method": "sendrawtransaction",
"params": ["0200000001abcd1234...00000000"]
}
Example Response:
{
"result": "a1b2c3d4e5f6...",
"error": null,
"id": "curltest"
}
getminingcandidate
Returns information for creating a new block.
Parameters:
-
parameters
(object, optional): -
coinbaseValue
(numeric, optional): Custom coinbase value in satoshis
Returns:
{
"id": "string", // Mining candidate ID
"prevhash": "string", // Previous block hash
"coinbase": "string", // Coinbase transaction
"coinbaseValue": number, // Coinbase value in satoshis
"version": number, // Block version
"nBits": "string", // Compressed difficulty target
"time": number, // Current timestamp
"height": number, // Block height
"num_tx": number, // Number of transactions
"merkleProof": ["string"], // Merkle proof
"merkleRoot": "string" // Merkle root
}
Example Request (standard):
{
"jsonrpc": "1.0",
"id": "curltest",
"method": "getminingcandidate",
"params": []
}
Example Request (with custom coinbase value):
{
"jsonrpc": "1.0",
"id": "curltest",
"method": "getminingcandidate",
"params": [{"coinbaseValue": 5000000000}]
}
submitminingsolution
Submits a solved block to the network.
Parameters:
solution
(object, required):{ "id": "string", // Mining candidate ID "nonce": number, // Block nonce "coinbase": "string", // Coinbase transaction "time": number, // Block time "version": number // Block version }
Returns:
- boolean
- True if accepted, false if rejected
Example Request:
{
"jsonrpc": "1.0",
"id": "curltest",
"method": "submitminingsolution",
"params": [{
"id": "100000",
"nonce": 1234567890,
"coinbase": "01000000...",
"time": 1631234567,
"version": 1
}]
}
getblockchaininfo
Returns state information about blockchain processing.
Parameters: none
Returns:
{
"chain": "string", // Current network name (main, test, regtest)
"blocks": number, // Current number of blocks processed
"headers": number, // Current number of headers processed
"bestblockhash": "string", // Hash of the currently best block
"difficulty": number, // Current difficulty
"mediantime": number, // Median time for the current best block
"verificationprogress": number, // Estimate of verification progress [0..1]
"chainwork": "string", // Total amount of work in active chain, in hexadecimal
"pruned": boolean, // If the blocks are subject to pruning
"softforks": [ // Status of softforks
{
"id": "string", // Name of the softfork
"version": number, // Block version that signals this softfork
"enforce": { // Progress toward enforcing the softfork rules
"status": boolean, // True if threshold reached
"found": number, // Number of blocks with the new version found
"required": number,// Number of blocks required
"window": number // Maximum size of examined window of recent blocks
},
"reject": { // Progress toward rejecting pre-softfork blocks
"status": boolean, // True if threshold reached
"found": number, // Number of blocks with the new version found
"required": number,// Number of blocks required
"window": number // Maximum size of examined window of recent blocks
}
}
]
}
Example Request:
{
"jsonrpc": "1.0",
"id": "curltest",
"method": "getblockchaininfo",
"params": []
}
Example Response:
{
"result": {
"chain": "main",
"blocks": 750000,
"headers": 750000,
"bestblockhash": "000000000000000004a1b6d6fdfa0d0a0e52a7a2c8a35ee5b5a7518a846387bc",
"difficulty": 21448277761059.71,
"mediantime": 1657123456,
"verificationprogress": 0.9999987,
"chainwork": "000000000000000000000000000000000000000000a0ff23f0182b0000000000",
"pruned": false,
"softforks": []
},
"error": null,
"id": "curltest"
}
getinfo
Returns general information about the node and blockchain.
Parameters: none
Returns:
{
"version": number, // Server version
"protocolversion": number, // Protocol version
"blocks": number, // Current number of blocks
"timeoffset": number, // Time offset in seconds
"connections": number, // Number of connections
"proxy": "string", // Proxy used
"difficulty": number, // Current difficulty
"testnet": boolean, // If using testnet
"relayfee": number, // Minimum relay fee
"errors": "string" // Current errors
}
Example Request:
{
"jsonrpc": "1.0",
"id": "curltest",
"method": "getinfo",
"params": []
}
Example Response:
{
"result": {
"version": 1000000,
"protocolversion": 70015,
"blocks": 750000,
"timeoffset": 0,
"connections": 8,
"proxy": "",
"difficulty": 21448277761059.71,
"testnet": false,
"relayfee": 0.00001000,
"errors": ""
},
"error": null,
"id": "curltest"
}
getpeerinfo
Returns data about each connected network node.
Parameters: none
Returns:
- Array of Objects, one per peer:
[
{
"id": number, // Peer index
"addr": "string", // IP address and port
"addrlocal": "string", // Local address
"services": "string", // Services offered (hex)
"lastsend": number, // Time in seconds since last send
"lastrecv": number, // Time in seconds since last receive
"bytessent": number, // Total bytes sent
"bytesrecv": number, // Total bytes received
"conntime": number, // Connection time in seconds
"pingtime": number, // Ping time in seconds
"version": number, // Peer version
"subver": "string", // Peer subversion string
"inbound": boolean, // Inbound (true) or Outbound (false)
"startingheight": number, // Starting height when peer connected
"banscore": number, // Ban score
"synced_headers": number, // Last header we have in common with this peer
"synced_blocks": number // Last block we have in common with this peer
}
]
Example Request:
{
"jsonrpc": "1.0",
"id": "curltest",
"method": "getpeerinfo",
"params": []
}
Example Response:
{
"result": [
{
"id": 1,
"addr": "192.168.1.123:8333",
"addrlocal": "192.168.1.100:8333",
"services": "000000000000040d",
"lastsend": 1657123456,
"lastrecv": 1657123455,
"bytessent": 123456,
"bytesrecv": 234567,
"conntime": 1657120000,
"pingtime": 0.001,
"version": 70015,
"subver": "/Bitcoin SV:1.0.0/",
"inbound": false,
"startingheight": 750000,
"banscore": 0,
"synced_headers": 750000,
"synced_blocks": 750000
}
],
"error": null,
"id": "curltest"
}
invalidateblock
Permanently marks a block as invalid, as if it violated a consensus rule.
Parameters:
blockhash
(string, required) - The hash of the block to mark as invalid
Returns:
null
on success
Example Request:
{
"jsonrpc": "1.0",
"id": "curltest",
"method": "invalidateblock",
"params": ["000000000000000004a1b6d6fdfa0d0a0e52a7a2c8a35ee5b5a7518a846387bc"]
}
Example Response:
{
"result": null,
"error": null,
"id": "curltest"
}
reconsiderblock
Removes invalidity status of a block and its descendants, reconsidering them for activation.
Parameters:
blockhash
(string, required) - The hash of the block to reconsider
Returns:
null
on success
Example Request:
{
"jsonrpc": "1.0",
"id": "curltest",
"method": "reconsiderblock",
"params": ["000000000000000004a1b6d6fdfa0d0a0e52a7a2c8a35ee5b5a7518a846387bc"]
}
Example Response:
{
"result": null,
"error": null,
"id": "curltest"
}
setban
Attempts to add or remove an IP/Subnet from the banned list.
Parameters:
subnet
(string, required) - The IP/Subnet with an optional netmask (default is /32 = single IP)command
(string, required) - 'add' to add a ban, 'remove' to remove a banbantime
(numeric, optional) - Time in seconds how long the ban is in effect, 0 or empty means using the default time of 24habsolute
(boolean, optional) - If set, the bantime must be an absolute timestamp in seconds since epoch
Returns:
- null
on success
Example Request:
{
"jsonrpc": "1.0",
"id": "curltest",
"method": "setban",
"params": ["192.168.0.6", "add", 86400]
}
Example Response:
{
"result": null,
"error": null,
"id": "curltest"
}
listbanned
Returns list of all banned IP addresses/subnets.
Parameters: none
Returns: - Array of objects with banned addresses and details
Example Request:
{
"jsonrpc": "1.0",
"id": "curltest",
"method": "listbanned",
"params": []
}
Example Response:
{
"result": [
{
"address": "192.168.0.6/32",
"ban_created": 1621500000,
"ban_reason": "manually added",
"banned_until": 1621586400
}
],
"error": null,
"id": "curltest"
}
clearbanned
Removes all IP address bans.
Parameters: none
Returns:
- null
on success
Example Request:
{
"jsonrpc": "1.0",
"id": "curltest",
"method": "clearbanned",
"params": []
}
Example Response:
{
"result": null,
"error": null,
"id": "curltest"
}
stop
Safely shuts down the node.
Parameters: none
Returns:
string
- A message indicating the node is stopping
Example Request:
{
"jsonrpc": "1.0",
"id": "curltest",
"method": "stop",
"params": []
}
Example Response:
{
"result": "Bitcoin server stopping",
"error": null,
"id": "curltest"
}
version
Returns the server version information.
Parameters: none
Returns:
{
"version": "string", // Server version string
"subversion": "string", // User agent string
"protocolversion": number // Protocol version number
}
Example Request:
{
"jsonrpc": "1.0",
"id": "curltest",
"method": "version",
"params": []
}
Example Response:
{
"result": {
"version": "1.0.0",
"subversion": "/Bitcoin SV:1.0.0/",
"protocolversion": 70015
},
"error": null,
"id": "curltest"
}
isbanned
Checks if a network address is currently banned.
Parameters:
address
(string, required) - The network address to check, e.g. "192.168.0.1/24"
Returns:
boolean
- True if the address is banned, false otherwise
Example Request:
{
"jsonrpc": "1.0",
"id": "curltest",
"method": "isbanned",
"params": ["192.168.0.6"]
}
Example Response:
{
"result": false,
"error": null,
"id": "curltest"
}
freeze
Freezes a specific UTXO, preventing it from being spent.
Parameters:
txid
(string, required) - Transaction ID of the output to freezevout
(numeric, required) - Output index to freeze
Returns:
boolean
- True if the UTXO was successfully frozen
Example Request:
{
"jsonrpc": "1.0",
"id": "curltest",
"method": "freeze",
"params": [
"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0",
1
]
}
Example Response:
{
"result": true,
"error": null,
"id": "curltest"
}
unfreeze
Unfreezes a previously frozen UTXO, allowing it to be spent.
Parameters:
txid
(string, required) - Transaction ID of the frozen outputvout
(numeric, required) - Output index to unfreeze
Returns:
boolean
- True if the UTXO was successfully unfrozen
Example Request:
{
"jsonrpc": "1.0",
"id": "curltest",
"method": "unfreeze",
"params": [
"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0",
1
]
}
Example Response:
{
"result": true,
"error": null,
"id": "curltest"
}
reassign
Reassigns ownership of a specific UTXO to a new Bitcoin address.
Parameters:
txid
(string, required) - Transaction ID of the output to reassignvout
(numeric, required) - Output index to reassigndestination
(string, required) - Bitcoin address to reassign the UTXO to
Returns:
boolean
- True if the UTXO was successfully reassigned
Example Request:
{
"jsonrpc": "1.0",
"id": "curltest",
"method": "reassign",
"params": [
"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0",
1,
"1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa"
]
}
Example Response:
{
"result": true,
"error": null,
"id": "curltest"
}
generatetoaddress
Mines blocks immediately to a specified address (for testing only).
Parameters:
nblocks
(numeric, required) - Number of blocks to generateaddress
(string, required) - The address to send the newly generated bitcoin tomaxtries
(numeric, optional) - Maximum number of iterations to try
Returns:
array
- hashes of blocks generated
Example Request:
{
"jsonrpc": "1.0",
"id": "curltest",
"method": "generatetoaddress",
"params": [1, "1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa", 1000000]
}
Example Response:
{
"result": [
"36252b5852a5921bdfca8701f936b39edeb1f8c39fffe73b0d8437921401f9af"
],
"error": null,
"id": "curltest"
}
getrawtransaction
Returns raw transaction data for a specific transaction.
Parameters:
1. txid
(string, required) - The transaction id
2. verbose
(boolean, optional, default=false) - If false, returns a string that is serialized, hex-encoded data for the transaction. If true, returns a JSON object with transaction information.
Returns:
- If verbose=false: string
- Serialized, hex-encoded data for the transaction
- If verbose=true: object
- A JSON object with transaction information
Example Request:
{
"jsonrpc": "1.0",
"id": "curltest",
"method": "getrawtransaction",
"params": [
"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0",
true
]
}
Example Response:
{
"result": {
"hex": "0200000001abcd1234...00000000",
"txid": "a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0",
"hash": "a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0",
"size": 225,
"version": 2,
"locktime": 0,
"vin": [
{
"txid": "efgh5678...",
"vout": 0,
"scriptSig": {
"asm": "...",
"hex": "..."
},
"sequence": 4294967295
}
],
"vout": [
{
"value": 0.01000000,
"n": 0,
"scriptPubKey": {
"asm": "OP_DUP OP_HASH160 hash OP_EQUALVERIFY OP_CHECKSIG",
"hex": "76a914hash88ac",
"reqSigs": 1,
"type": "pubkeyhash",
"addresses": [
"1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa"
]
}
}
],
"blockhash": "0000000000000000000b9d2ec5a352ecba0592946514a92f14319dc2cf8127f0",
"confirmations": 1024,
"time": 1570747519,
"blocktime": 1570747519
},
"error": null,
"id": "curltest"
}
Unimplemented RPC Commands
The following commands are recognized by the RPC server but are not currently implemented (they would return an ErrRPCUnimplemented error):
addnode
- Adds a node to the peer listdebuglevel
- Changes the debug level on the flydecoderawtransaction
- Decodes a raw transaction hexadecimal stringdecodescript
- Decodes a hex-encoded scriptestimatefee
- Estimates the fee per kilobytegetaddednodeinfo
- Returns information about added nodesgetbestblock
- Returns information about best blockgetblockcount
- Returns the current block countgetblocktemplate
- Returns template for block generationgetcfilter
- Returns the committed filter for a blockgetcfilterheader
- Returns the filter header for a filtergetconnectioncount
- Returns connection countgetcurrentnet
- Returns the current network IDgetgenerate
- Returns if the server is generating coinsgethashespersec
- Returns hashes per secondgetheaders
- Returns header informationgetmempoolinfo
- Returns mempool information (Not in scope for Teranode)getnettotals
- Returns network statisticsgetnetworkhashps
- Returns estimated network hashes per secondgetrawmempool
- Returns raw mempool contents (Not in scope for Teranode)gettxout
- Returns unspent transaction outputgettxoutproof
- Returns proof that transaction was included in a blocknode
- Attempts to add or remove a node-
ping
- Pings the server -
addmultisigaddress
- Add a multisignature address to the wallet backupwallet
- Safely copies wallet.dat to the specified filecreateencryptedwallet
- Creates a new encrypted walletcreatemultisig
- Creates a multi-signature addressdumpprivkey
- Reveals the private key for an addressdumpwallet
- Dumps wallet keys to a fileencryptwallet
- Encrypts the walletgetaccount
- Returns the account associated with an addressgetaccountaddress
- Returns the address for an accountgetaddressesbyaccount
- Returns addresses for an accountgetbalance
- Returns the wallet balancegetnewaddress
- Returns a new Bitcoin address for receiving paymentsgetrawchangeaddress
- Returns a new Bitcoin address for receiving changegetreceivedbyaccount
- Returns amount received by accountgetreceivedbyaddress
- Returns amount received by addressgettransaction
- Returns wallet transaction detailsgetunconfirmedbalance
- Returns unconfirmed balancegetwalletinfo
- Returns wallet state informationimportaddress
- Adds an address to the walletimportprivkey
- Adds a private key to the walletimportwallet
- Imports keys from a wallet dump filekeypoolrefill
- Refills the key poollistaccounts
- Lists account balanceslistaddressgroupings
- Lists address groupingslistlockunspent
- Lists temporarily unspendable outputslistreceivedbyaccount
- Lists balances by accountlistreceivedbyaddress
- Lists balances by addresslistsinceblock
- Lists transactions since a blocklisttransactions
- Lists wallet transactionslistunspent
- Lists unspent transaction outputslockunspent
- Locks/unlocks unspent outputsmove
- Moves funds between accountssendfrom
- Sends from an accountsendmany
- Sends to multiple recipientssendtoaddress
- Sends to an addresssetaccount
- Sets the account for an addresssettxfee
- Sets the transaction feesignmessage
- Signs a message with address keysignrawtransaction
- Signs a raw transactionwalletlock
- Locks the walletwalletpassphrase
- Unlocks wallet for sendingwalletpassphrasechange
- Changes wallet passphrase
Additionally, the following node-related commands are recognized but return ErrRPCUnimplemented:
addnode
- Add/remove a node from the address managerdebuglevel
- Changes debug logging leveldecoderawtransaction
- Decodes a raw transactiondecodescript
- Decodes a scriptestimatefee
- Estimates transaction feegetaddednodeinfo
- Returns information about added nodesgetbestblock
- Returns best block hash and heightgetblockcount
- Returns the blockchain heightgetblocktemplate
- Returns data for block template creationgetcfilter
- Returns a compact filter for a blockgetcfilterheader
- Returns a filter header for a blockgetconnectioncount
- Returns connection countgetcurrentnet
- Returns the network (mainnet/testnet)getgenerate
- Returns if the node is generating blocksgethashespersec
- Returns mining hashrategetheaders
- Returns block headersgetmempoolinfo
- Returns mempool informationgetnettotals
- Returns network traffic statisticsgetnetworkhashps
- Returns estimated network hashrategetrawmempool
- Returns mempool transaction datagettxout
- Returns transaction output informationgettxoutproof
- Returns proof that transaction was included in a blocknode
- Attempts to add or remove a peer nodeping
- Requests the node pingsearchrawtransactions
- Searches for raw transactionssetgenerate
- Sets if the node generates blockssubmitblock
- Submits a block to the networkuptime
- Returns node uptimevalidateaddress
- Validates a Bitcoin addressverifychain
- Verifies blockchain databaseverifymessage
- Verifies a signed messageverifytxoutproof
- Verifies proof that transaction was included in a block
Error Handling
The RPC service uses a standardized error handling system based on the Bitcoin Core JSON-RPC error codes. All errors returned to clients follow the JSON-RPC 2.0 specification format:
{
"jsonrpc": "2.0",
"id": "request-id",
"error": {
"code": -32000,
"message": "Error message"
}
}
Standard error codes include:
- -1: General error during command handling
- -3: Wallet error (wallet functionality not implemented)
- -5: Invalid address or key
- -8: Out of memory or other resource exhaustion
- -20: Database inconsistency or corruption
- -22: Error parsing or validating a block or transaction
- -25: Transaction or block validation error
- -26: Transaction rejected by policy rules
- -27: Transaction already in chain
- -32600: Invalid JSON-RPC request
- -32601: Method not found
- -32602: Invalid parameters
- -32603: Internal JSON-RPC error
- -32700: Parse error (invalid JSON)
Each handler implements specific error checks relevant to its operation and returns appropriately formatted error responses.
Errors are wrapped in bsvjson.RPCError
structures, providing standardized error codes and messages as per the Bitcoin Core RPC specification.
RPC calls return errors in the following format:
{
"result": null,
"error": {
"code": -32601,
"message": "Method not found"
},
"id": "id"
}
Common error codes that may be returned:
Code | Message | Meaning |
---|---|---|
-1 | RPC_MISC_ERROR | Standard "catch-all" error |
-3 | RPC_TYPE_ERROR | Unexpected type was passed as parameter |
-5 | RPC_INVALID_ADDRESS | Invalid address or key |
-8 | RPC_INVALID_PARAMETER | Invalid, missing or duplicate parameter |
-32600 | RPC_INVALID_REQUEST | JSON request format error |
-32601 | RPC_METHOD_NOT_FOUND | Method not found |
-32602 | RPC_INVALID_PARAMS | Invalid method parameters |
-32603 | RPC_INTERNAL_ERROR | Internal RPC error |
-32700 | RPC_PARSE_ERROR | Error parsing JSON request |
Rate Limiting
The RPC interface implements rate limiting to prevent abuse. Default limits:
- Maximum concurrent connections: 16
- Maximum requests per minute: 60
Version Compatibility
These RPC commands are compatible with Bitcoin SV Teranode version 1.0.0 and later.
Concurrency
The RPC Service is designed for high-concurrency operation with multiple simultaneous client connections. Key concurrency features include:
- Thread-safe request processing with proper synchronization
- Atomic operations for tracking client connections
- Connection limits to prevent resource exhaustion
- Wait groups for coordinated shutdown with in-progress requests
- Context-based cancellation for long-running operations
- Non-blocking request handler dispatch
- Proper mutex usage for shared data structures
- Per-request goroutines for parallel processing
- Response caching to reduce contention on frequently accessed data
These mechanisms ensure the RPC service can safely handle many concurrent connections without race conditions or deadlocks, even under high load scenarios.
The server uses goroutines to handle multiple client connections concurrently. It also employs various synchronization primitives (mutexes, atomic operations) to ensure thread-safety.
Extensibility
The command handling system is designed to be extensible. New RPC commands can be added by implementing new handler functions and registering them in the rpcHandlers
map.
Limitations
- The server does not implement wallet functionality. Wallet-related commands are delegated to a separate wallet service.
- Several commands are marked as unimplemented and will return an error if called.
- The UTXO management commands (freeze, unfreeze, reassign) require the node to be properly configured with the necessary capabilities.
- Memory and connection limits are enforced to prevent resource exhaustion.
Security
The RPC Service implements several security features:
- HTTP Basic authentication with SHA256 credential validation
- Two-tier authentication system separating admin from limited-access operations
- Connection limiting to prevent denial-of-service attacks
- Configurable binding to specific network interfaces
- Proper HTTP request/response handling with appropriate headers
- Input validation on all parameters
- Authorization checking for privileged operations
- Ban management capabilities for malicious IP addresses
- Context timeouts to prevent resource exhaustion
- Secure credential handling to prevent information leakage
- TLS support for encrypted communications (when configured)