JSON-RPC
API12.4.15+

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.

12.4.16+

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:

NetworkPort
Mainnet10604
Testnet11604
Regtest12604
Shell
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/

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.

OptionMeaning
-testnet, -regtestTalk 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
-stdinrpcpassRead the password from standard input
-rpcwallet=<walletname>Send the command to that wallet (endpoint /wallet/<walletname>)
-namedPass named instead of positional arguments
-rpcwaitWait for the RPC server to start
-getinfoA summary gathered from several commands
Shell
lotus-cli -named getblock blockhash=<hash> verbosity=1
lotus-cli -rpcwallet=mywallet getbalance

Authentication #

Three modes, described in Security:

  • the cookie file .cookie, written in the data directory at each start (default);
  • rpcauth= (hashed password) or rpcuser= and rpcpassword= in lotus.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:

Shell
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:

Shell
lotus-cli help
lotus-cli help getblock

help 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 #

CommandDescription
downloadutxosnapshotDownload the periodic UTXO snapshot of height from another node's REST API, by chunks checked against its manifest.
dumptxoutsetWrite the UTXO set at the tip, or at an earlier height, to a snapshot file that loadtxoutset can load.
getbestblockhashReturns the hash of the best (tip) block in the most-work fully-validated chain.
getblockReturns the block with the given hash: serialized hex with verbosity 0, an object with verbosity 1, with transaction data with verbosity 2.
getblockchaininfoReturns an object containing various state info regarding blockchain processing.
getblockcountReturns the height of the most-work fully-validated chain.
getblockfilterRetrieve a BIP 157 content filter for a particular block.
getblockhashReturns hash of block in best-block-chain at height provided.
getblockheaderReturns the block header with the given hash, as an object or as serialized hex.
getblockstatsCompute per block statistics for a given window.
getchaintipsReturn information about all known tips in the block tree, including the main chain as well as orphaned branches.
getchaintxstatsCompute statistics about the total number and rate of transactions in the chain.
getdifficultyReturns the proof-of-work difficulty as a multiple of the minimum difficulty.
getepochrootsEpoch roots of the complete epochs of the active chain (header checkpoint for thin nodes).
getmempoolancestorsIf txid is in the mempool, returns all in-mempool ancestors.
getmempooldescendantsIf txid is in the mempool, returns all in-mempool descendants.
getmempoolentryReturns mempool data for given transaction.
getmempoolinfoReturns details on the active state of the TX memory pool.
getrawmempoolReturns all transaction ids in memory pool as a json array of string transaction ids.
getthininfoThin 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.
gettxoutReturns details about an unspent transaction output.
gettxoutproofReturns a hex-encoded proof that "txid" was included in a block.
gettxoutsetinfoReturns statistics about the unspent transaction output set.
getutxocommitmentThe 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.
getutxohashThe incremental UTXO set hash (MuHash3072) at the tip or at a height of the active chain (-utxohash).
getutxosnapshotinfoState of the UTXO snapshot this node runs on and of its background validation.
listutxosnapshotsThe periodic UTXO snapshots kept by this node (newest first).
loadtxoutsetLoad a UTXO snapshot whose base block this release vouches for, make it the chain state and continue the chain from its base at once.
preciousblockTreats a block as if it were received before others with the same work.
pruneblockchainPrune the block files up to the given block height.
readutxosnapshotRead a UTXO snapshot file's metadata (base hash, height, coins, transaction count, MuHash).
savemempoolDumps the mempool to disk.
scantxoutsetEXPERIMENTAL. Scans the unspent transaction output set for entries that match certain output descriptors.
verifychainVerifies blockchain database.
verifytxoutproofVerifies that a proof points to a transaction in a block, returning the transaction it commits to.
verifyutxocommitmentVerify a UTXO set hash for the set after block height against the coinbase commitment of the block that commits to it.
writeutxosnapshotWrite a periodic UTXO snapshot of height now.

Control #

CommandDescription
getmemoryinfoReturns an object containing information about memory usage.
getrpcinfoReturns details of the RPC server.
helpList all commands, or get help for a specified command.
loggingGets and sets the logging configuration.
stopRequest a graceful shutdown of the node.
uptimeReturns the total uptime of the server.

Generating #

CommandDescription
generateblockMine a block with a set of ordered transactions immediately to a specified address or descriptor.
generatetoaddressMine blocks immediately to a specified address.
generatetodescriptorMine blocks immediately to a specified descriptor.

Mining #

CommandDescription
createauxblockCreate an auxiliary block for merged mining.
decodepoolrecordDecode the POOL on-chain mining record (eMPP, LOKAD "POOL") of a block's coinbase.
disconnectminingworkerCloses the Stratum session(s) of a miner on the SHA-256 and Scrypt listeners.
getauxblockMerged mining: without arguments, a template paying -auxpowaddress; with a hash and an AuxPoW, submit a solved template.
getblocktemplateReturns data needed to construct a block to work on.
getmergemineinfoReturns the parent work sources of the ASIC algorithms (pools, parent nodes, embedded nodes, the synthetic parent) with their hosts and sanitised errors. Operator information.
getmininginfoReturns a json object containing mining-related information.
getnetworkhashpsReturns the estimated network hashes per second based on the last n blocks.
getpoolinfoPool payouts state: configuration, ledger digest, float, share and job counts, fleet peers, counters and the last payout plan.
getpoolpayoutsPool blocks indexed by the POOL module with their payout outputs (from pool.sqlite).
getpoolsharesMost recent shares in memory (local and from fleet peers).
getrawunsolvedblockGet a serialized block candidate with coinbase sending to the specified address.
getstratuminfoReturns the state of this node's Stratum mining server: listeners, per-algorithm totals and recent problems. Operator information.
listminingworkersLists the miners connected now with their real names and addresses, and the anonymous label each one has on the public dashboard.
poolrecoverproofsOne-off repair (12.4.13): rebuild the lost block share (the ownership proof) of this node's own blocks classified spoof.
prioritisetransactionAccepts the transaction into mined blocks at a higher (or lower) priority.
submitauxblockSubmit a solved auxiliary block with its AuxPoW proof.
submitblockAttempts to submit new block to network.
submitheaderDecode the given hexdata as a header and submit it as a candidate chain tip if valid.

Network #

CommandDescription
addnodeAttempts to add or remove a node from the addnode list.
clearbannedClear all banned IPs.
clearnngpublicbansLift every ban of the public NNG listener and reset violation scores, rate buckets and payout-script windows.
disconnectnodeImmediately disconnects from the specified peer node.
getaddednodeinfoReturns information about the given added node, or all added nodes.
getblockholdinfoBlocks from peers outside -trustedblocksource waiting -untrustedblockdelay before validation.
getconnectioncountReturns the number of connections to other nodes.
getdiscoveryinfoActive peer discovery (-peerdiscovery): what the node does to find new peers and how it is going.
getexcessiveblockReturn the excessive block size.
getintroducerinfoReturns the local node's NAT-traversal capability snapshot plus running counters for the hole-punch introducer overlay (NODE_INTRODUCER).
getnettotalsReturns information about network traffic, including bytes in, bytes out, and current time.
getnetworkinfoReturns an object containing various state info regarding P2P networking.
getnngpublicinfoStatus of the public NNG listener (-nngpublic, -nngpublicpub): endpoints, limits, connections, counters, bans, template cache.
getnodeaddressesReturn known addresses which can potentially be used to find new nodes in the network.
getpeerinfoReturns data about each connected network node as a json array of objects.
listbannedList all manually banned IPs/Subnets.
pingRequests that a ping be sent to all other nodes, to measure ping time.
requestintroducerpunchManually fire a GETINTRO message to one of our connected peers that advertises NODE_INTRODUCER.
setbanAttempts to add or remove an IP/Subnet from the banned list.
setnetworkactiveDisable/enable all p2p network activity.

Raw transactions #

CommandDescription
analyzepsbtAnalyzes and provides information about the current status of a PSBT and its inputs.
combinepsbtCombine multiple PSBTs into one transaction.
combinerawtransactionCombine multiple partially signed transactions into one transaction.
converttopsbtConverts a network serialized transaction to a PSBT.
createpsbtCreates a transaction in the Partially Signed Transaction format.
createrawtransactionCreate a transaction spending the given inputs and creating new outputs.
decodepsbtReturn a JSON object representing the serialized, base64-encoded PSBT.
decoderawtransactionReturn a JSON object representing the serialized, hex-encoded transaction.
decodescriptDecode a hex-encoded script.
finalizepsbtFinalize the inputs of a PSBT.
fundrawtransactionIf the transaction has no inputs, they will be automatically selected to meet its out value.
getrawtransactionReturn the raw transaction data. By default this only works for mempool transactions; confirmed ones need -txindex or the block hash.
joinpsbtsJoins multiple distinct PSBTs with different inputs and outputs into one PSBT with inputs and outputs from all of the PSBTs.
sendrawtransactionSubmits raw transaction (serialized, hex-encoded) to local node and network.
signrawtransactionwithkeySign inputs for raw transaction (serialized, hex-encoded).
testmempoolacceptReturns result of mempool acceptance tests indicating if raw transaction (serialized, hex-encoded) would be accepted by mempool.
utxoupdatepsbtUpdates all inputs and outputs in a PSBT with data from output descriptors, the UTXO set or the mempool.

Util #

CommandDescription
createmultisigCreates a multi-signature address with n signature of m keys required.
deriveaddressesDerives one or more addresses corresponding to an output descriptor.
estimatefeeEstimates the approximate fee per kilobyte needed for a transaction.
getcurrencyinfoReturns an object containing information about the currency.
getdescriptorinfoAnalyses a descriptor.
getindexinfoReturns the status of one or all available indices currently running in the node.
signmessagewithprivkeySign a message with the private key of an address.
validateaddressReturn information about the given address.
verifymessageVerify a signed message.

Wallet #

CommandDescription
abandontransactionMark in-wallet transaction <txid> as abandoned.
abortrescanStops current wallet rescan triggered by an RPC call, e.g. by an importprivkey call.
addmultisigaddressAdd an nrequired-to-sign multisignature address to the wallet.
backupwalletSafely copies current wallet file to destination, which can be a directory or a path with filename.
createwalletCreates and loads a new wallet.
dumpcoinsDump all the UTXO tracked by the wallet.
dumpprivkeyReveals the private key corresponding to 'address'.
dumpwalletDumps all wallet keys in a human-readable format to a server-side file.
encryptwalletEncrypts the wallet with 'passphrase'.
getaddressesbylabelReturns the list of addresses assigned the specified label.
getaddressinfoReturn information about the given address.
getbalanceReturns the total available balance.
getbalancesReturns an object with all balances.
getnewaddressReturns a new address for receiving payments.
getrawchangeaddressReturns a new address, for receiving change.
getreceivedbyaddressReturns the total amount received by the given address in transactions with at least minconf confirmations.
getreceivedbylabelReturns the total amount received by addresses with <label> in transactions with at least [minconf] confirmations.
gettransactionGet detailed information about in-wallet transaction <txid>.
getunconfirmedbalanceDEPRECATED. Identical to getbalances().mine.untrusted_pending.
getwalletinfoReturns an object containing various wallet state info.
importaddressAdds an address or script (in hex) that can be watched as if it were in your wallet but cannot be used to spend.
importdescriptorsImport descriptors. This will trigger a rescan of the blockchain based on the earliest timestamp of all descriptors being imported.
importmultiImport addresses/scripts (with private or public keys, redeem script (P2SH)), optionally rescanning the blockchain.
importprivkeyAdds a private key (as returned by dumpprivkey) to your wallet.
importprunedfundsImports funds without rescan. Corresponding address or script must previously be included in wallet.
importpubkeyAdds a public key (in hex) that can be watched as if it were in your wallet but cannot be used to spend.
importwalletImports keys from a wallet dump file (see dumpwallet).
keypoolrefillFills the keypool.
listaddressgroupingsLists groups of addresses which have had their common ownership made public by common use as inputs or as the resulting change in past transactions.
listlabelsReturns the list of all labels, or labels that are assigned to addresses with a specific purpose.
listlockunspentReturns list of temporarily unspendable outputs.
listreceivedbyaddressList balances by receiving address.
listreceivedbylabelList received transactions by label.
listsinceblockGet all transactions in blocks since block [blockhash], or all transactions if omitted.
listtransactionsIf a label name is provided, this will return only incoming transactions paying to addresses with the specified label.
listunspentReturns array of unspent transaction outputs.
listwalletdirReturns a list of wallets in the wallet directory.
listwalletsReturns a list of currently loaded wallets.
loadwalletLoads a wallet from a wallet file or directory.
lockunspentUpdates list of temporarily unspendable outputs.
removeprunedfundsDeletes the specified transaction from the wallet.
rescanblockchainRescan the local blockchain for wallet related transactions.
sendEXPERIMENTAL. Send a transaction.
sendmanySend multiple times. Amounts are double-precision floating point numbers.
sendtoaddressSend an amount to a given address.
sethdseedSet or generate a new HD wallet seed.
setlabelSets the label associated with the given address.
settxfeeSet the transaction fee per kB for this wallet.
setwalletflagChange the state of the given wallet flag for a wallet.
signmessageSign a message with the private key of an address.
signrawtransactionwithwalletSign inputs for raw transaction (serialized, hex-encoded).
unloadwalletUnloads the wallet referenced by the request endpoint otherwise unloads the wallet specified in the argument.
upgradewalletUpgrade the wallet. Upgrades to the latest version if no version number is specified.
walletcreatefundedpsbtCreates and funds a transaction in the Partially Signed Transaction format.
walletdumpmigrateMigrate an unloaded Berkeley DB wallet directory to the SQLite wallet backend.
walletlockRemoves the wallet encryption key from memory, locking the wallet.
walletpassphraseStores the wallet decryption key in memory for 'timeout' seconds.
walletpassphrasechangeChanges the wallet passphrase from 'oldpassphrase' to 'newpassphrase'.
walletprocesspsbtUpdate a PSBT with input information from our wallet and then sign inputs that we can sign for.

Contracts #

CommandDescription
contractstateReturn the commitment, state and value of an unspent Taproot output (mempool included by default), or null if it is spent or unknown.
createcontractBuild a Taproot script tree from leaf scripts and return the commitment, scriptPubKey (with optional 32-byte state), address and each leaf's control block.
decodecontractDecode a Lotus Taproot scriptPubKey (commitment, state, address) and, given the spending scriptSig, the script-path spend.
spendcontractSet the scriptSig of one input to <args...> <leaf> <control block> for a tree built from leaves (as createcontract). Does not sign.
tracescriptEvaluate one input of a transaction and return every step: phase, opcode, stack after it, operation cost.

Modules #

CommandDescription
cancelmodulerescanAsk the running chain module rescan to stop after the block (or chunk) it is writing.
getmodulerescanstatusStatus of the current or last chain module rescan (see rescanmodule).
rescanmoduleStart a background rescan of a height range of the active chain for one chain module (rank, pokr, blob, slp, alp).

Avalanche #

CommandDescription
addavalanchenodeAdd a node in the set of peers to poll for avalanche.
buildavalancheproofBuild a proof for avalanche's sybil resistance.
decodeavalancheproofConvert a serialized, hex-encoded proof, into JSON object.
delegateavalancheproofDelegate the avalanche proof to another public key.
getavalanchekeyReturns the key used to sign avalanche messages.
getavalanchepeerinfoReturns data about each connected avalanche peer as a json array of objects.
getrawavalancheproofLookup for a known avalanche proof by id.
sendavalancheproofBroadcast an avalanche proof.
verifyavalancheproofVerify an avalanche proof is valid and return the error otherwise.

ZMQ #

CommandDescription
getzmqnotificationsReturns 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:

JSON
{"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.

CodeNameMeaning
-32700RPC_PARSE_ERRORThe request is not valid JSON
-32600RPC_INVALID_REQUESTNot a valid request object
-32601RPC_METHOD_NOT_FOUNDUnknown command
-32602RPC_INVALID_PARAMSInvalid parameters
-32603RPC_INTERNAL_ERRORGenuine error in the node (for example data directory corruption)
-1RPC_MISC_ERRORException thrown in command handling
-3RPC_TYPE_ERRORUnexpected type was passed as parameter
-5RPC_INVALID_ADDRESS_OR_KEYInvalid address or key
-7RPC_OUT_OF_MEMORYRan out of memory during operation
-8RPC_INVALID_PARAMETERInvalid, missing or duplicate parameter
-20RPC_DATABASE_ERRORDatabase error
-22RPC_DESERIALIZATION_ERRORError parsing or validating structure in raw format
-25RPC_VERIFY_ERRORGeneral error during transaction or block submission
-26RPC_VERIFY_REJECTEDTransaction or block was rejected by network rules
-27RPC_VERIFY_ALREADY_IN_CHAINTransaction already in chain
-28RPC_IN_WARMUPThe node is still warming up
-32RPC_METHOD_DEPRECATEDRPC method is deprecated
-9RPC_CLIENT_NOT_CONNECTEDThe node is not connected
-10RPC_CLIENT_IN_INITIAL_DOWNLOADStill downloading initial blocks
-23RPC_CLIENT_NODE_ALREADY_ADDEDNode is already added
-24RPC_CLIENT_NODE_NOT_ADDEDNode has not been added before
-29RPC_CLIENT_NODE_NOT_CONNECTEDNode to disconnect not found in connected nodes
-30RPC_CLIENT_INVALID_IP_OR_SUBNETInvalid IP/Subnet
-31RPC_CLIENT_P2P_DISABLEDNo valid connection manager instance found
-33RPC_CLIENT_MEMPOOL_DISABLEDNo mempool instance found
-34RPC_CLIENT_NODE_CAPACITY_REACHEDMax number of outbound or block-relay connections already open
-4RPC_WALLET_ERRORUnspecified problem with wallet (key not found etc.)
-6RPC_WALLET_INSUFFICIENT_FUNDSNot enough funds in wallet
-11RPC_WALLET_INVALID_LABEL_NAMEInvalid label name
-12RPC_WALLET_KEYPOOL_RAN_OUTKeypool ran out, call keypoolrefill first
-13RPC_WALLET_UNLOCK_NEEDEDEnter the wallet passphrase with walletpassphrase first
-14RPC_WALLET_PASSPHRASE_INCORRECTThe wallet passphrase entered was incorrect
-15RPC_WALLET_WRONG_ENC_STATECommand given in wrong wallet encryption state
-16RPC_WALLET_ENCRYPTION_FAILEDFailed to encrypt the wallet
-17RPC_WALLET_ALREADY_UNLOCKEDWallet is already unlocked
-18RPC_WALLET_NOT_FOUNDInvalid wallet specified
-19RPC_WALLET_NOT_SPECIFIEDNo 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.

Source share/www/docs/rpc.md in the lotusd repository
Checked against doc/JSON-RPC-interface.md src/rpc/blockchain.cpp src/rpc/mining.cpp src/rpc/net.cpp src/rpc/rawtransaction.cpp src/rpc/misc.cpp src/rpc/server.cpp src/rpc/contracts.cpp src/rpc/modules.cpp src/rpc/avalanche.cpp src/rpc/nngpublic.cpp src/pool/rpc.cpp src/zmq/zmqrpc.cpp src/wallet/rpcwallet.cpp src/wallet/rpcdump.cpp src/rpc/protocol.h src/httprpc.cpp src/bitcoin-cli.cpp src/chainparamsbase.cpp