JSON-RPC
How to call the node's JSON-RPC interface with lotus-cli or curl, every command by category, and the error codes.
JSON-RPC is the node's control interface: everything lotus-cli does goes through it. It is authenticated and, by default, reachable from the node's own machine only. For public, read-only access to chain data use the REST API instead.
New commands: sendrawtransactions (up to 1,000 transactions or 8 MB in one call, best effort or atomic), getblocktemplatelight and submitblocklight (a template without its transactions, identified by a job_id), and getindexerinfo (how far the asynchronous explorer indexer is behind the tip).
Call it #
The port depends on the network:
| Network | Port |
|---|---|
| Mainnet | 10604 |
| Testnet | 11604 |
| Regtest | 12604 |
curl --user myuser:mypassword \
--data-binary '{"jsonrpc":"1.0","id":"curltest","method":"getblockcount","params":[]}' \
-H 'content-type: text/plain;' http://127.0.0.1:10604/lotus-cli getblockcountconst r = await fetch('http://127.0.0.1:10604/', {
method: 'POST',
headers: {
'content-type': 'application/json',
authorization: 'Basic ' + btoa('myuser:mypassword'),
},
body: JSON.stringify({jsonrpc: '1.0', id: 1, method: 'getblockcount', params: []}),
});
const {result, error} = await r.json();The reply is {"result": ..., "error": null, "id": "curltest"}. Requests are POST only. Send a content-type header as shown (text/plain or application/json): curl's default form content type is answered 404. A JSON array of requests is executed as a batch.
With lotus-cli #
lotus-cli reads the same lotus.conf and data directory as the node, so on the node's machine it needs no option: it finds the authentication cookie by itself.
| Option | Meaning |
|---|---|
-testnet, -regtest | Talk to a node on that network |
-datadir=<dir>, -conf=<file> | Where to find the configuration and the cookie |
-rpcconnect=<ip>, -rpcport=<port> | A node on another host or port |
-rpcuser=<user>, -rpcpassword=<pw> | Credentials, when not using the cookie |
-stdinrpcpass | Read the password from standard input |
-rpcwallet=<walletname> | Send the command to that wallet (endpoint /wallet/<walletname>) |
-named | Pass named instead of positional arguments |
-rpcwait | Wait for the RPC server to start |
-getinfo | A summary gathered from several commands |
lotus-cli -named getblock blockhash=<hash> verbosity=1
lotus-cli -rpcwallet=mywallet getbalanceAuthentication #
Three modes, described in Security:
- the cookie file
.cookie, written in the data directory at each start (default); rpcauth=(hashed password) orrpcuser=andrpcpassword=inlotus.conf;- none, with
-rpcnoauth=1, when access is controlled outside the node.
With curl and the cookie, pass the content of the file as the credentials:
curl --user "$(cat ~/.lotus/.cookie)" \
--data-binary '{"jsonrpc":"1.0","id":1,"method":"uptime","params":[]}' \
-H 'content-type: text/plain;' http://127.0.0.1:10604/A request that arrives through a reverse proxy is refused with 403 unless the node runs with -rpcallowforwarded=1.
The help command #
The node documents every command itself, with arguments, result and examples:
lotus-cli help
lotus-cli help getblockhelp lists the commands by category. The tables below give the same names with the first line of each help text. Use help <command> for the arguments: it is always in step with the version you run.
Commands #
Blockchain #
| Command | Description |
|---|---|
downloadutxosnapshot | Download the periodic UTXO snapshot of height from another node's REST API, by chunks checked against its manifest. |
dumptxoutset | Write the UTXO set at the tip, or at an earlier height, to a snapshot file that loadtxoutset can load. |
getbestblockhash | Returns the hash of the best (tip) block in the most-work fully-validated chain. |
getblock | Returns the block with the given hash: serialized hex with verbosity 0, an object with verbosity 1, with transaction data with verbosity 2. |
getblockchaininfo | Returns an object containing various state info regarding blockchain processing. |
getblockcount | Returns the height of the most-work fully-validated chain. |
getblockfilter | Retrieve a BIP 157 content filter for a particular block. |
getblockhash | Returns hash of block in best-block-chain at height provided. |
getblockheader | Returns the block header with the given hash, as an object or as serialized hex. |
getblockstats | Compute per block statistics for a given window. |
getchaintips | Return information about all known tips in the block tree, including the main chain as well as orphaned branches. |
getchaintxstats | Compute statistics about the total number and rate of transactions in the chain. |
getdifficulty | Returns the proof-of-work difficulty as a multiple of the minimum difficulty. |
getepochroots | Epoch roots of the complete epochs of the active chain (header checkpoint for thin nodes). |
getmempoolancestors | If txid is in the mempool, returns all in-mempool ancestors. |
getmempooldescendants | If txid is in the mempool, returns all in-mempool descendants. |
getmempoolentry | Returns mempool data for given transaction. |
getmempoolinfo | Returns details on the active state of the TX memory pool. |
getrawmempool | Returns all transaction ids in memory pool as a json array of string transaction ids. |
getthininfo | Thin mode health: the proof client's answers per proof peer, the blocks waiting for the proofs of their inputs and, with -proofserver=1, the server's counters. |
gettxout | Returns details about an unspent transaction output. |
gettxoutproof | Returns a hex-encoded proof that "txid" was included in a block. |
gettxoutsetinfo | Returns statistics about the unspent transaction output set. |
getutxocommitment | The coinbase UTXO set commitment of the block at height of the active chain, and this node's own UTXO set hash for the committed height. |
getutxohash | The incremental UTXO set hash (MuHash3072) at the tip or at a height of the active chain (-utxohash). |
getutxosnapshotinfo | State of the UTXO snapshot this node runs on and of its background validation. |
listutxosnapshots | The periodic UTXO snapshots kept by this node (newest first). |
loadtxoutset | Load a UTXO snapshot whose base block this release vouches for, make it the chain state and continue the chain from its base at once. |
preciousblock | Treats a block as if it were received before others with the same work. |
pruneblockchain | Prune the block files up to the given block height. |
readutxosnapshot | Read a UTXO snapshot file's metadata (base hash, height, coins, transaction count, MuHash). |
savemempool | Dumps the mempool to disk. |
scantxoutset | EXPERIMENTAL. Scans the unspent transaction output set for entries that match certain output descriptors. |
verifychain | Verifies blockchain database. |
verifytxoutproof | Verifies that a proof points to a transaction in a block, returning the transaction it commits to. |
verifyutxocommitment | Verify a UTXO set hash for the set after block height against the coinbase commitment of the block that commits to it. |
writeutxosnapshot | Write a periodic UTXO snapshot of height now. |
Control #
| Command | Description |
|---|---|
getmemoryinfo | Returns an object containing information about memory usage. |
getrpcinfo | Returns details of the RPC server. |
help | List all commands, or get help for a specified command. |
logging | Gets and sets the logging configuration. |
stop | Request a graceful shutdown of the node. |
uptime | Returns the total uptime of the server. |
Generating #
| Command | Description |
|---|---|
generateblock | Mine a block with a set of ordered transactions immediately to a specified address or descriptor. |
generatetoaddress | Mine blocks immediately to a specified address. |
generatetodescriptor | Mine blocks immediately to a specified descriptor. |
Mining #
| Command | Description |
|---|---|
createauxblock | Create an auxiliary block for merged mining. |
decodepoolrecord | Decode the POOL on-chain mining record (eMPP, LOKAD "POOL") of a block's coinbase. |
disconnectminingworker | Closes the Stratum session(s) of a miner on the SHA-256 and Scrypt listeners. |
getauxblock | Merged mining: without arguments, a template paying -auxpowaddress; with a hash and an AuxPoW, submit a solved template. |
getblocktemplate | Returns data needed to construct a block to work on. |
getmergemineinfo | Returns the parent work sources of the ASIC algorithms (pools, parent nodes, embedded nodes, the synthetic parent) with their hosts and sanitised errors. Operator information. |
getmininginfo | Returns a json object containing mining-related information. |
getnetworkhashps | Returns the estimated network hashes per second based on the last n blocks. |
getpoolinfo | Pool payouts state: configuration, ledger digest, float, share and job counts, fleet peers, counters and the last payout plan. |
getpoolpayouts | Pool blocks indexed by the POOL module with their payout outputs (from pool.sqlite). |
getpoolshares | Most recent shares in memory (local and from fleet peers). |
getrawunsolvedblock | Get a serialized block candidate with coinbase sending to the specified address. |
getstratuminfo | Returns the state of this node's Stratum mining server: listeners, per-algorithm totals and recent problems. Operator information. |
listminingworkers | Lists the miners connected now with their real names and addresses, and the anonymous label each one has on the public dashboard. |
poolrecoverproofs | One-off repair (12.4.13): rebuild the lost block share (the ownership proof) of this node's own blocks classified spoof. |
prioritisetransaction | Accepts the transaction into mined blocks at a higher (or lower) priority. |
submitauxblock | Submit a solved auxiliary block with its AuxPoW proof. |
submitblock | Attempts to submit new block to network. |
submitheader | Decode the given hexdata as a header and submit it as a candidate chain tip if valid. |
Network #
| Command | Description |
|---|---|
addnode | Attempts to add or remove a node from the addnode list. |
clearbanned | Clear all banned IPs. |
clearnngpublicbans | Lift every ban of the public NNG listener and reset violation scores, rate buckets and payout-script windows. |
disconnectnode | Immediately disconnects from the specified peer node. |
getaddednodeinfo | Returns information about the given added node, or all added nodes. |
getblockholdinfo | Blocks from peers outside -trustedblocksource waiting -untrustedblockdelay before validation. |
getconnectioncount | Returns the number of connections to other nodes. |
getdiscoveryinfo | Active peer discovery (-peerdiscovery): what the node does to find new peers and how it is going. |
getexcessiveblock | Return the excessive block size. |
getintroducerinfo | Returns the local node's NAT-traversal capability snapshot plus running counters for the hole-punch introducer overlay (NODE_INTRODUCER). |
getnettotals | Returns information about network traffic, including bytes in, bytes out, and current time. |
getnetworkinfo | Returns an object containing various state info regarding P2P networking. |
getnngpublicinfo | Status of the public NNG listener (-nngpublic, -nngpublicpub): endpoints, limits, connections, counters, bans, template cache. |
getnodeaddresses | Return known addresses which can potentially be used to find new nodes in the network. |
getpeerinfo | Returns data about each connected network node as a json array of objects. |
listbanned | List all manually banned IPs/Subnets. |
ping | Requests that a ping be sent to all other nodes, to measure ping time. |
requestintroducerpunch | Manually fire a GETINTRO message to one of our connected peers that advertises NODE_INTRODUCER. |
setban | Attempts to add or remove an IP/Subnet from the banned list. |
setnetworkactive | Disable/enable all p2p network activity. |
Raw transactions #
| Command | Description |
|---|---|
analyzepsbt | Analyzes and provides information about the current status of a PSBT and its inputs. |
combinepsbt | Combine multiple PSBTs into one transaction. |
combinerawtransaction | Combine multiple partially signed transactions into one transaction. |
converttopsbt | Converts a network serialized transaction to a PSBT. |
createpsbt | Creates a transaction in the Partially Signed Transaction format. |
createrawtransaction | Create a transaction spending the given inputs and creating new outputs. |
decodepsbt | Return a JSON object representing the serialized, base64-encoded PSBT. |
decoderawtransaction | Return a JSON object representing the serialized, hex-encoded transaction. |
decodescript | Decode a hex-encoded script. |
finalizepsbt | Finalize the inputs of a PSBT. |
fundrawtransaction | If the transaction has no inputs, they will be automatically selected to meet its out value. |
getrawtransaction | Return the raw transaction data. By default this only works for mempool transactions; confirmed ones need -txindex or the block hash. |
joinpsbts | Joins multiple distinct PSBTs with different inputs and outputs into one PSBT with inputs and outputs from all of the PSBTs. |
sendrawtransaction | Submits raw transaction (serialized, hex-encoded) to local node and network. |
signrawtransactionwithkey | Sign inputs for raw transaction (serialized, hex-encoded). |
testmempoolaccept | Returns result of mempool acceptance tests indicating if raw transaction (serialized, hex-encoded) would be accepted by mempool. |
utxoupdatepsbt | Updates all inputs and outputs in a PSBT with data from output descriptors, the UTXO set or the mempool. |
Util #
| Command | Description |
|---|---|
createmultisig | Creates a multi-signature address with n signature of m keys required. |
deriveaddresses | Derives one or more addresses corresponding to an output descriptor. |
estimatefee | Estimates the approximate fee per kilobyte needed for a transaction. |
getcurrencyinfo | Returns an object containing information about the currency. |
getdescriptorinfo | Analyses a descriptor. |
getindexinfo | Returns the status of one or all available indices currently running in the node. |
signmessagewithprivkey | Sign a message with the private key of an address. |
validateaddress | Return information about the given address. |
verifymessage | Verify a signed message. |
Wallet #
| Command | Description |
|---|---|
abandontransaction | Mark in-wallet transaction <txid> as abandoned. |
abortrescan | Stops current wallet rescan triggered by an RPC call, e.g. by an importprivkey call. |
addmultisigaddress | Add an nrequired-to-sign multisignature address to the wallet. |
backupwallet | Safely copies current wallet file to destination, which can be a directory or a path with filename. |
createwallet | Creates and loads a new wallet. |
dumpcoins | Dump all the UTXO tracked by the wallet. |
dumpprivkey | Reveals the private key corresponding to 'address'. |
dumpwallet | Dumps all wallet keys in a human-readable format to a server-side file. |
encryptwallet | Encrypts the wallet with 'passphrase'. |
getaddressesbylabel | Returns the list of addresses assigned the specified label. |
getaddressinfo | Return information about the given address. |
getbalance | Returns the total available balance. |
getbalances | Returns an object with all balances. |
getnewaddress | Returns a new address for receiving payments. |
getrawchangeaddress | Returns a new address, for receiving change. |
getreceivedbyaddress | Returns the total amount received by the given address in transactions with at least minconf confirmations. |
getreceivedbylabel | Returns the total amount received by addresses with <label> in transactions with at least [minconf] confirmations. |
gettransaction | Get detailed information about in-wallet transaction <txid>. |
getunconfirmedbalance | DEPRECATED. Identical to getbalances().mine.untrusted_pending. |
getwalletinfo | Returns an object containing various wallet state info. |
importaddress | Adds an address or script (in hex) that can be watched as if it were in your wallet but cannot be used to spend. |
importdescriptors | Import descriptors. This will trigger a rescan of the blockchain based on the earliest timestamp of all descriptors being imported. |
importmulti | Import addresses/scripts (with private or public keys, redeem script (P2SH)), optionally rescanning the blockchain. |
importprivkey | Adds a private key (as returned by dumpprivkey) to your wallet. |
importprunedfunds | Imports funds without rescan. Corresponding address or script must previously be included in wallet. |
importpubkey | Adds a public key (in hex) that can be watched as if it were in your wallet but cannot be used to spend. |
importwallet | Imports keys from a wallet dump file (see dumpwallet). |
keypoolrefill | Fills the keypool. |
listaddressgroupings | Lists groups of addresses which have had their common ownership made public by common use as inputs or as the resulting change in past transactions. |
listlabels | Returns the list of all labels, or labels that are assigned to addresses with a specific purpose. |
listlockunspent | Returns list of temporarily unspendable outputs. |
listreceivedbyaddress | List balances by receiving address. |
listreceivedbylabel | List received transactions by label. |
listsinceblock | Get all transactions in blocks since block [blockhash], or all transactions if omitted. |
listtransactions | If a label name is provided, this will return only incoming transactions paying to addresses with the specified label. |
listunspent | Returns array of unspent transaction outputs. |
listwalletdir | Returns a list of wallets in the wallet directory. |
listwallets | Returns a list of currently loaded wallets. |
loadwallet | Loads a wallet from a wallet file or directory. |
lockunspent | Updates list of temporarily unspendable outputs. |
removeprunedfunds | Deletes the specified transaction from the wallet. |
rescanblockchain | Rescan the local blockchain for wallet related transactions. |
send | EXPERIMENTAL. Send a transaction. |
sendmany | Send multiple times. Amounts are double-precision floating point numbers. |
sendtoaddress | Send an amount to a given address. |
sethdseed | Set or generate a new HD wallet seed. |
setlabel | Sets the label associated with the given address. |
settxfee | Set the transaction fee per kB for this wallet. |
setwalletflag | Change the state of the given wallet flag for a wallet. |
signmessage | Sign a message with the private key of an address. |
signrawtransactionwithwallet | Sign inputs for raw transaction (serialized, hex-encoded). |
unloadwallet | Unloads the wallet referenced by the request endpoint otherwise unloads the wallet specified in the argument. |
upgradewallet | Upgrade the wallet. Upgrades to the latest version if no version number is specified. |
walletcreatefundedpsbt | Creates and funds a transaction in the Partially Signed Transaction format. |
walletdumpmigrate | Migrate an unloaded Berkeley DB wallet directory to the SQLite wallet backend. |
walletlock | Removes the wallet encryption key from memory, locking the wallet. |
walletpassphrase | Stores the wallet decryption key in memory for 'timeout' seconds. |
walletpassphrasechange | Changes the wallet passphrase from 'oldpassphrase' to 'newpassphrase'. |
walletprocesspsbt | Update a PSBT with input information from our wallet and then sign inputs that we can sign for. |
Contracts #
| Command | Description |
|---|---|
contractstate | Return the commitment, state and value of an unspent Taproot output (mempool included by default), or null if it is spent or unknown. |
createcontract | Build a Taproot script tree from leaf scripts and return the commitment, scriptPubKey (with optional 32-byte state), address and each leaf's control block. |
decodecontract | Decode a Lotus Taproot scriptPubKey (commitment, state, address) and, given the spending scriptSig, the script-path spend. |
spendcontract | Set the scriptSig of one input to <args...> <leaf> <control block> for a tree built from leaves (as createcontract). Does not sign. |
tracescript | Evaluate one input of a transaction and return every step: phase, opcode, stack after it, operation cost. |
Modules #
| Command | Description |
|---|---|
cancelmodulerescan | Ask the running chain module rescan to stop after the block (or chunk) it is writing. |
getmodulerescanstatus | Status of the current or last chain module rescan (see rescanmodule). |
rescanmodule | Start a background rescan of a height range of the active chain for one chain module (rank, pokr, blob, slp, alp). |
Avalanche #
| Command | Description |
|---|---|
addavalanchenode | Add a node in the set of peers to poll for avalanche. |
buildavalancheproof | Build a proof for avalanche's sybil resistance. |
decodeavalancheproof | Convert a serialized, hex-encoded proof, into JSON object. |
delegateavalancheproof | Delegate the avalanche proof to another public key. |
getavalanchekey | Returns the key used to sign avalanche messages. |
getavalanchepeerinfo | Returns data about each connected avalanche peer as a json array of objects. |
getrawavalancheproof | Lookup for a known avalanche proof by id. |
sendavalancheproof | Broadcast an avalanche proof. |
verifyavalancheproof | Verify an avalanche proof is valid and return the error otherwise. |
ZMQ #
| Command | Description |
|---|---|
getzmqnotifications | Returns information about the active ZeroMQ notifications. |
A few more commands are hidden from help because they are meant for testing or repair (for example invalidateblock, reconsiderblock, parkblock, setmocktime). help <command> still documents them.
Errors #
On failure, result is null and error is an object:
{"result":null,"error":{"code":-32601,"message":"Method not found"},"id":"curltest"}The HTTP status is 404 for an unknown method, 400 for an invalid request and 500 for other command errors. 401 means missing or wrong credentials; 403 means the source address, the proxy rule or -rpcwhitelist refused the request. A full work queue answers 503.
| Code | Name | Meaning |
|---|---|---|
| -32700 | RPC_PARSE_ERROR | The request is not valid JSON |
| -32600 | RPC_INVALID_REQUEST | Not a valid request object |
| -32601 | RPC_METHOD_NOT_FOUND | Unknown command |
| -32602 | RPC_INVALID_PARAMS | Invalid parameters |
| -32603 | RPC_INTERNAL_ERROR | Genuine error in the node (for example data directory corruption) |
| -1 | RPC_MISC_ERROR | Exception thrown in command handling |
| -3 | RPC_TYPE_ERROR | Unexpected type was passed as parameter |
| -5 | RPC_INVALID_ADDRESS_OR_KEY | Invalid address or key |
| -7 | RPC_OUT_OF_MEMORY | Ran out of memory during operation |
| -8 | RPC_INVALID_PARAMETER | Invalid, missing or duplicate parameter |
| -20 | RPC_DATABASE_ERROR | Database error |
| -22 | RPC_DESERIALIZATION_ERROR | Error parsing or validating structure in raw format |
| -25 | RPC_VERIFY_ERROR | General error during transaction or block submission |
| -26 | RPC_VERIFY_REJECTED | Transaction or block was rejected by network rules |
| -27 | RPC_VERIFY_ALREADY_IN_CHAIN | Transaction already in chain |
| -28 | RPC_IN_WARMUP | The node is still warming up |
| -32 | RPC_METHOD_DEPRECATED | RPC method is deprecated |
| -9 | RPC_CLIENT_NOT_CONNECTED | The node is not connected |
| -10 | RPC_CLIENT_IN_INITIAL_DOWNLOAD | Still downloading initial blocks |
| -23 | RPC_CLIENT_NODE_ALREADY_ADDED | Node is already added |
| -24 | RPC_CLIENT_NODE_NOT_ADDED | Node has not been added before |
| -29 | RPC_CLIENT_NODE_NOT_CONNECTED | Node to disconnect not found in connected nodes |
| -30 | RPC_CLIENT_INVALID_IP_OR_SUBNET | Invalid IP/Subnet |
| -31 | RPC_CLIENT_P2P_DISABLED | No valid connection manager instance found |
| -33 | RPC_CLIENT_MEMPOOL_DISABLED | No mempool instance found |
| -34 | RPC_CLIENT_NODE_CAPACITY_REACHED | Max number of outbound or block-relay connections already open |
| -4 | RPC_WALLET_ERROR | Unspecified problem with wallet (key not found etc.) |
| -6 | RPC_WALLET_INSUFFICIENT_FUNDS | Not enough funds in wallet |
| -11 | RPC_WALLET_INVALID_LABEL_NAME | Invalid label name |
| -12 | RPC_WALLET_KEYPOOL_RAN_OUT | Keypool ran out, call keypoolrefill first |
| -13 | RPC_WALLET_UNLOCK_NEEDED | Enter the wallet passphrase with walletpassphrase first |
| -14 | RPC_WALLET_PASSPHRASE_INCORRECT | The wallet passphrase entered was incorrect |
| -15 | RPC_WALLET_WRONG_ENC_STATE | Command given in wrong wallet encryption state |
| -16 | RPC_WALLET_ENCRYPTION_FAILED | Failed to encrypt the wallet |
| -17 | RPC_WALLET_ALREADY_UNLOCKED | Wallet is already unlocked |
| -18 | RPC_WALLET_NOT_FOUND | Invalid wallet specified |
| -19 | RPC_WALLET_NOT_SPECIFIED | No wallet specified (several wallets are loaded) |
While the node starts, every command answers -28 with a message saying what it is loading. Retry.
A confirmed transaction asked from getrawtransaction on a node without -txindex answers -5 ("No such mempool transaction. Use -txindex or provide a block hash..."). The REST route GET /api/v1/txs/<txid> does not need the index.
Consistency #
State returned by a command is at least as recent as the chain state just before the call. The mempool returned is consistent with itself and with the chain state at the time of the call. Wallet state reflects every block up to that point; it may lag behind the current mempool.
