You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
dcrd provides a JSON-RPC API that is
fully compatible with the original bitcoind/bitcoin-qt. There are a few key
differences between dcrd and bitcoind as far as how RPCs are serviced:
Unlike bitcoind that has the wallet and chain intermingled in the same process which leads to several issues, dcrd intentionally splits the wallet and chain services into independent processes. See the blog post here for further details on why they were separated. This means that if you are talking directly to dcrd, only chain-related RPCs are available. However both chain-related and wallet-related RPCs are available via dcrwallet.
dcrd is secure by default which means that the RPC connection is TLS-enabled by default
dcrd provides access to the API through both HTTP POST requests and Websockets
Websockets are the preferred transport for dcrd RPC and are used by applications
such as dcrwallet for inter-process
communication with dcrd. The websocket connection endpoint for dcrd is
wss://your_ip_or_domain:9109/ws.
All requests are limited to a maximum size of 8 MiB when accessed via HTTP POST
and 16 MiB when accessed via Websockets.
In addition to the standard API, an extension API
has been developed that is exclusive to clients using Websockets. In its current
state, this API attempts to cover features found missing in the standard API
during the development of dcrwallet.
While the standard API is stable, the
Websocket extension API should be considered a work in
progress, incomplete, and susceptible to changes (both additions and removals).
2. HTTP POST Versus Websockets
The dcrd RPC server supports both HTTP POST
requests and the preferred Websockets.
All of the standard and extension methods described in
this documentation can be accessed through both. As the name
indicates, the Websocket-specific extension methods can only be
accessed when connected via Websockets.
As mentioned in the overview, the websocket connection endpoint for
dcrd is wss://your_ip_or_domain:9109/ws.
The most important differences between the two transports as it pertains to the
JSON-RPC API are:
HTTP POST Requests
Websockets
Allows multiple requests across a single connection
Yes
Yes
Supports asynchronous notifications
No
Yes
Scales well with large numbers of requests
No
Yes
3. Authentication
3.1 Authentication Overview
The following authentication details are needed before establishing a connection
to a dcrd RPC server:
rpcuser is the full-access username configured for the dcrd RPC server
rpcpass is the full-access password configured for the dcrd RPC server
rpclimituser is the limited username configured for the dcrd RPC server
rpclimitpass is the limited password configured for the dcrd RPC server
rpccert is the PEM-encoded X.509 certificate (public key) that the dcrd server is configured with. It is automatically generated by dcrd and placed in the dcrd home directory (which is typically %LOCALAPPDATA%\Dcrd on Windows and ~/.dcrd on POSIX-like OSes)
NOTE: As mentioned above, dcrd is secure by default which means the RPC
server is not running unless configured with a rpcuser and rpcpass
and/or a rpclimituser and rpclimitpass, and uses TLS authentication for
all connections.
Depending on which connection type you are using, you can choose one of
two, mutually exclusive, methods.
The dcrd RPC server uses HTTP basic access authentication with the rpcuser
and rpcpass detailed above. If the supplied credentials are invalid, you
will be disconnected immediately upon making the connection.
While the HTTP basic access authentication method is the preferred method, the
ability to set HTTP headers from websockets is not always available. In that
case, you will need to use the authenticate JSON-RPC method.
The authenticate command must be the first command sent after
connecting to the websocket. Sending any other commands before authenticating,
supplying invalid credentials, or attempting to authenticate again when already
authenticated will cause the websocket to be closed immediately.
4. Command-line Utility
dcrd is built to work with dcrctl
which can be used to issue these RPC commands via HTTP POST requests to dcrd
after configuring it with the information in the Authentication
section above. It can also be used to communicate with any server/daemon/service
which provides a JSON-RPC API compatible with the original dcrd client.
5. Standard Methods
5.1 Method Overview
The following is an overview of the RPC methods and their current status. Click
the method name for further details such as parameter and return information.
Returns the current set of mixing pair request messages from the mixpool. WARNING: This is experimental and will very likely be removed in the next version. Do not use!
Returns formatted hash data to work on or checks and submits solved data. NOTE: Since dcrd does not have the wallet integrated to provide payment addresses, dcrd must be configured via the --miningaddr option to provide which payment addresses to pay created blocks to for this RPC to function.
Reconsiders a block for validation and best chain selection by removing any invalid status from it and its ancestors. Any descendants that are neither themselves marked as having failed validation, nor descendants of another such block, are also made eligibile for best chain selection.
Set the server to generate coins (mine) or not. NOTE: Since dcrd does not have the wallet integrated to provide payment addresses, dcrd must be configured via the --miningaddr option to provide which payment addresses to pay created blocks to for this RPC to function.
addresses and amounts: (JSON object, required) - json object with addresses as keys and output amounts as values in coins.
address: (string, required) the address to send the specified output amount to.
{"address": n.nnn, ...}
Description
Returns a new transaction spending the provided inputs and sending to the provided addresses. The transaction inputs are not signed in the created transaction.
The signrawtransaction RPC command provided by wallet must be used to sign the resulting transaction.
Returns
transaction: (string) - hex-encoded bytes of the serialized transaction.
Returns a JSON object representing the provided serialized, hex-encoded transaction.
Returns
(json object)
txid: (string) the transaction id.
hash: (string) the hash of the transaction.
version: (numeric) the block version.
locktime: (numeric) the transaction lock time.
expiry: (numeric) the transaction expiry.
vin: (array of json objects) the transaction inputs as json objects.
vout: (array of json objects) the transaction outputs as json objects.
{"txid": "hash", "version": n, "locktime": n, "expiry": n, "vin": [...], "vout": [...]}
vin (for coinbase transactions)
(json object)
coinbase: (string) the hex-encoded bytes of the signature script.
amountin: (numeric) the input amount.
blockheight: (numeric) the block height of the origin transaction.
blockindex: (numeric) the block index of the origin transaction.
sequence: (numeric) the script sequence number.
{"coinbase": "data", "amountin": n.nnn, "blockheight": n, "blockindex": n, "sequence": n, ...}
vin (for vote transactions)
(json object)
stakebase: (string) the hex-encoded bytes of the signature script.
amountin: (numeric) the input amount.
blockheight: (numeric) the block height of the origin transaction.
blockindex: (numeric) the block index of the origin transaction.
sequence: (numeric) the script sequence number.
{"stakebase": "data", "amountin": n.nnn, "blockheight": n, "blockindex": n, "sequence": n, ...}
vin (for treasurybase transactions)
(json object)
treasurybase: (boolean) Whether or not the input is a treasury base.
amountin: (numeric) the input amount.
blockheight: (numeric) the block height of the origin transaction.
blockindex: (numeric) the block index of the origin transaction.
sequence: (numeric) the script sequence number.
{"treasurybase": bool, "amountin": n.nnn, "blockheight": n, "blockindex": n, "sequence": n, ...}
vin (for treasury spend transactions)
(json object)
treasuryspend: (string) the hex-encoded bytes of the signature script.
amountin: (numeric) the input amount.
blockheight: (numeric) the block height of the origin transaction.
blockindex: (numeric) the block index of the origin transaction.
sequence: (numeric) the script sequence number.
{"treasuryspend": "data", "amountin": n.nnn, "blockheight": n, "blockindex": n, "sequence": n, ...}
vin (for other transactions)
(json object)
txid: (string) the hash of the origin transaction.
vout: (numeric) the index of the output being redeemed from the origin transaction.
tree: (numeric) the tree of the transaction.
sequence: (numeric) the script sequence number.
amountin: (numeric) the input amount.
blockheight: (numeric) the block height of the origin transaction.
blockindex: (numeric) the block index of the origin transaction.
scriptSig: (json object) the signature script used to redeem the origin transaction.
asm:(string) disassembly of the script.
hex: (string) hex-encoded bytes of the script.
{"txid": "hash", "vout": n, "tree": n, "sequence": n, "amountin": n.nnn, "blockheight": n, "blockindex": n, "scriptSig": {"asm": "asm", "hex": "data"}, ...}
vout
(json object)
value: (numeric) the value in DCR.
n: (numeric) the index of this transaction output.
version: (numeric) the version of public key script.
scriptPubKey:(json object) the public key script used to pay coins.
asm: (string) disassembly of the script.
hex: (string) hex-encoded bytes of the script.
reqSigs: (numeric) the number of required signatures.
type: (string) the type of the script (e.g. 'pubkeyhash').
addresses: (json array of string) the Decred addresses associated with this output.
commitamt: (numeric) the ticket commitment value if the script is for a staking commitment (ticket txns only)
version: (numeric) the script version.
{"value": n, "n": n, "scriptPubKey": {"asm": "asm", "hex": "data","reqSigs": n, "type": "scripttype", "addresses": [...], "commitamt": n.nnn, "version": n}}
addresses: (json array, required) The addresses to check.
Description
Returns the existence of the provided address.
Returns
bitset Bitset of bools showing if addresses exist or not.
Example Return
07
existsliveticket
Method
existsliveticket
Parameters
txhash: (string, required) The ticket hash to check.
Description
Returns the existence of the provided ticket.
Returns
boolean
Example Return
true
existslivetickets
Method
existslivetickets
Parameters
txhashes: (json array, required) The array of tx hashes to check.
Description
Returns the existence of the provided tickets in the live ticket map.
Returns
bitset Bitset of bools showing if tx hashes exist or not as live tickets.
Example Return
00
existsmempooltxs
Method
existsmempooltxs
Parameters
txhashes: (json array, required) The array of tx hashes to check.
Description
Returns the existence of the provided txs in the mempool.
Returns
bitset Bitset of bools showing if tx hashes exist or not in the mempool.
Example Return
00
generate
Method
generate
Parameters
numblocks: (int, required) The number of blocks to generate.
Description
When in simnet or regtest mode, generates numblocks blocks. If blocks arrive from elsewhere, they are built upon but don't count toward the number of blocks to generate. Only generated blocks are returned. This RPC call will exit with an error if the server is already CPU mining, and will prevent the server from CPU mining for another command while it runs.
Returns
(json array of strings)
blockhash: hash of the generated block.
["blockhash", ...]
getaddednodeinfo
Method
getaddednodeinfo
Parameters
dns: (boolean, required) specifies whether the returned data is a JSON object including DNS and connection information, or just a list of added peers.
node: (string, optional) only return information about this specific peer instead of all added peers.
Description
Returns information about manually added (persistent) peers.
Returns (dns=false)
["ip:port", ...]
Returns (dns=true)
(json array of objects)
addednode: (string) the ip address or domain of the added peer.
connected: (boolean) whether or not the peer is currently connected.
addresses: (json array or objects) DNS lookup and connection information about the peer.
address: (string) the ip address for this DNS entry.
connected: (string) the connection 'direction' (if connected).
block hash: (string, required) the hash of the block.
verbose: (boolean, optional, default=true) specifies the block is returned as a JSON object instead of hex-encoded string.
verbosetx: (boolean, optional, default=false) specifies that each transaction is returned as a JSON object and only applies if the verbose flag is true.
Description
Returns information about a block given its hash.
Returns (verbose=false)
"data" (string) hex-encoded bytes of the serialized block
Returns (verbose=true, verbosetx=false)
(json object)
hash: (string) the hash of the block (same as provided).
powhash: (string) the Proof-of-Work hash of the block (same as hash prior to DCP0011 activation).
confirmations: (numeric) the number of confirmations.
size: (numeric) the size of the block.
height: (numeric) the height of the block in the block chain.
version: (numeric) the block version.
merkleroot: (string) root hash of the merkle tree.
stakeroot: (string) root hash of the stake tree.
tx: (json array of string) the transaction hashes.
stx: (json array of string) the stake transaction hashes.
time: (numeric) the block time in seconds since 1 Jan 1970 GMT.
mediantime: (numeric) the median block time over the last 11 blocks.
nonce: (numeric) the block nonce.
votebits: (numeric) the block voting results.
finalstate: (string) the final lottery state.
voters: (numeric) the number of votes.
freshstake: (numeric) the number of ticket purchases.
revocations: (numeric) the number of ticket revocations.
poolsize: (numeric) the total number of valid spendble tickets as of the block.
bits: (numeric) the bits which represent the block difficulty.
sbits: (numeric) the bits which represent the stake difficulty.
difficulty: (numeric) the proof-of-work difficulty as a multiple of the minimum difficulty.
chainwork: (string) the total number of hashes expected to produce the chain up to the block in hex.
extradata: (string) extra data for the block including the extra nonce used by proof-of-work miners.
stakeversion: (string) block stake version.
previousblockhash: (string) the hash of the previous block.
nextblockhash: (string) the hash of the next block (only if there is one).
{"hash": "blockhash", "powhash": "hash", "confirmations": n, "size": n, "height": n, "version": n, "merkleroot": "hash", "stakeroot": "hash", "tx": ["transactionhash", ...], "stx": ["transactionhash", ...], "time": n, "nonce": n, "votebits": n, "finalstate": "state", "voters": n, "freshstake": n, "revocations": n, "poolsize": n, "bits": n, "sbits": n.nn, "difficulty": n.nn, "chainwork": "workhex", "extradata": "data", "stakeversion": n, previousblockhash": "hash", "nextblockhash": "hash"}
Example Return (verbose=false)
Newlines added for display purposes. The actual return does not contain newlines.
Returns information about the current state of the block chain.
Returns
(json object)
chain: (string) The current network name.
blocks: (numeric) The number of blocks in the current best chain.
headers: (numeric) The number of validated block headers that comprise the target best chain.
syncheight: (numeric) The latest known block height being synced to.
bestblockhash: (string) The block hash of the current best chain tip.
difficulty: (numeric) (DEPRECATED) The current network difficulty.
difficultyratio: (numeric) The current proof-of-work difficulty as a multiple of the minimum difficulty.
verificationprogress: (numeric) The chain verification progress estimate.
chainwork: (string) Hex encoded total work done for the chain.
initialblockdownload: (boolean) Best guess of whether this node is in the initial block download mode used to catch up the chain when it is far behind.
maxblocksize: (numeric) The maximum allowed block size.
deployments: (json array of objects) Network consensus deployments.
status: (string) The deployment agenda's current status.
since: (numeric) The blockheight of the first block to which the status applies.
starttime: (numeric) The start time of the voting period for the agenda.
expiretime: (numeric) The expiry time of the voting period for the agenda.
{ "chain": "name", "blocks": n, "headers": n, "syncheight": n, "bestblockhash": "hash", "difficulty": n, "difficultyratio": n, "verificationprogress": n, "chainwork": "n", "initialblockdownload": bool, "maxblocksize": n, "deployments": {"agenda": { "status": "status", "since": n, "starttime": n, "expiretime": n}, ...}}
block hash: (string, required) the hash of the block.
verbose: (boolean, optional, default=true) specifies the block header is returned as a JSON object instead of a hex-encoded string.
Description
Returns hex-encoded bytes of the serialized block header.
Returns (verbose=false)
"data" (string) hex-encoded bytes of the serialized block
Returns (verbose=true)
(json object)
hash: (string) the hash of the block (same as provided).
powhash: (string) the Proof-of-Work hash of the block (same as hash prior to DCP0011 activation).
confirmations: (numeric) the number of confirmations.
version: (numeric) the block version.
merkleroot: (string) root hash of the merkle tree.
stakeroot: (string) root hash of the stake tree.
votebits: (numeric) the block voting results.
finalstate: (string) the final lottery state.
voters: (numeric) the number of votes.
freshstake: (numeric) the number of ticket purchases.
revocations: (numeric) the number of ticket revocations.
poolsize: (numeric) the total number of valid spendble tickets as of the block.
bits: (numeric) the bits which represent the block difficulty.
sbits: (numeric) the bits which represent the stake difficulty.
height: (numeric) the height of the block in the block chain.
size: (numeric) the size of the block.
time: (numeric) the block time in seconds since 1 Jan 1970 GMT.
mediantime: (numeric) the median block time over the last 11 blocks.
nonce: (numeric) the block nonce.
extradata: (string) extra data for the block including the extra nonce used by proof-of-work miners.
stakeversion: (string) block stake version.
difficulty: (numeric) the proof-of-work difficulty as a multiple of the minimum difficulty.
chainwork: (string) the total number of hashes expected to produce the chain up to the block in hex.
previousblockhash: (string) the hash of the previous block.
nextblockhash: (string) the hash of the next block (only if there is one).
{"hash": "blockhash", "powhash": "hash", "confirmations": n, "version": n, "merkleroot": "hash", "stakeroot": "hash", "votebits": n, "finalstate": "state", "voters": n, "freshstake": n, "revocations": n, "poolsize": n, "bits": n, "sbits": n.nn, "height": n, "size": n, "time": n, "nonce": n, "extradata": "data", "stakeversion": n, "difficulty": n.nn, "chainwork": "workhex", "previousblockhash": "hash", "nextblockhash": "hash"}
Example Return (verbose=false)
Newlines added for display purposes. The actual return does not contain newlines.
Returns about all known chain tips the in the block tree.
The statuses in the result have the following meanings:
active: The current best chain tip.
invalid: The block or one of its ancestors is invalid.
headers-only: The block or one of its ancestors does not have the full block data available which also means the block can't be validated or connected.
valid-fork: The block is fully validated which implies it was probably part of the main chain at one point and was reorganized.
valid-headers: The full block data is available and the header is valid, but the block was never validated which implies it was probably never part of the main chain.
Returns
(json array of objects)
height: (numeric) The height of the chain tip.
hash: (string) The block hash of the chain tip.
branchlen: (numeric) The length of the branch that connects the tip to the main chain (0 for the main chain tip).
status: (string) status of the chain (active, invalid, headers-only, valid-fork, valid-headers).
[{"height": n, "hash": "hash", "branchlen": n, "status": "status"}, ...]
Returns the number of active connections to other peers.
Returns
numeric
Example Return
8
getcurrentnet
Method
getcurrentnet
Parameters
None
Description
Get Decred network dcrd is running on.
Returns
numeric
Example Return
(mainnet)3652501241
(testnet3)2979310197
getdifficulty
Method
getdifficulty
Parameters
None
Description
Returns the proof-of-work difficulty as a multiple of the minimum difficulty.
Returns
numeric
Example Return
1180923195.260000
getgenerate
Method
getgenerate
Parameters
None
Description
Return if the server is set to generate coins (mine) or not.
Returns
false (boolean)
gethashespersec
Method
gethashespersec
Parameters
None
Description
Returns a recent hashes per second performance measurement while generating coins (mining).
Returns
0 (numeric)
getheaders
Method
getheaders
Parameters
blocklocators: (json array, required) Array of block locator hashes.
hashstop: (string, required) Block hash to stop including block headers for, set to zero to get as many blocks as possible.
Description
Returns block headers starting with the first known block hash from the request.
Returns
(json object)
headers: (json array) Serialized block headers of all located blocks, limited to some arbitrary maximum number of hashes (currently 2000, which matches the wire protocol headers message, but this is not guaranteed).
Returns a JSON object containing various state info.
Notes
NOTE: Since dcrd does NOT contain wallet functionality, wallet-related fields are not returned. See getinfo in dcrwallet for a version which includes that information.
Returns
(json object)
version: (numeric) the version of the server.
protocolversion: (numeric) the latest supported protocol version.
blocks: (numeric) the number of blocks processed.
timeoffset: (numeric) the time offset.
connections: (numeric) the number of connected peers.
proxy: (string) the proxy used by the server
difficulty: (numeric) the current target difficulty.
testnet: (boolean) whether or not server is using testnet.
relayfee: (numeric) the minimum relay fee for non-free transactions in DCR/KB.
txindex: (boolean) whether or not server has transaction index enabled.
{"version": n,"protocolversion": n, "blocks": n, "timeoffset": n, "connections": n, "proxy": "host:port", "difficulty": n.nn, "testnet": true or false, "relayfee": n.nn, "txindex": true or false}
Returns a JSON object containing mempool-related information.
Returns
(json object)
bytes: (numeric) size in bytes of the mempool
size: (numeric) number of transactions in the mempool
{"bytes": n, "size": n}
Example Return
{"bytes": 310768, "size": 157}
getmininginfo
Method
getmininginfo
Parameters
None
Description
Returns a JSON object containing mining-related information.
Returns
(json object)
blocks: (numeric) latest best block.
currentblocksize: (numeric) size of the latest best block.
currentblocktx: (numeric) number of transactions in the latest best block.
difficulty: (numeric) current target difficulty.
stakedifficulty: (numeric) Stake difficulty required for the next block.
errors: (string) any current errors.
generate: (boolean) whether or not server is set to generate coins.
genproclimit: (numeric) number of processors to use for coin generation (-1 when disabled).
hashespersec: (numeric) recent hashes per second performance measurement while generating coins.
networkhashps: (numeric) estimated network hashes per second for the most recent blocks.
pooledtx: (numeric) number of transactions in the memory pool.
testnet: (boolean) whether or not server is using testnet.
{"blocks": n, "currentblocksize": n, "currentblocktx": n, "difficulty": n.nn, "stakedifficulty": n, "errors": "errors", "generate": true or false, "genproclimit": n, "hashespersec": n, "networkhashps": n, "pooledtx": n, "testnet": true or false }
blocks: (numeric, optional, default=120) The number of blocks, or -1 for blocks since last difficulty change.
height: (numeric, optional, default=-1) Perform estimate ending with this height or -1 for current best chain block height.
Description
Returns the estimated network hashes per second for the block heights provided by the parameters.
Returns
numeric
Example Return
6573971939
getnetworkinfo
Method
getnetworkinfo
Parameters
None
Description
Returns a JSON object containing network-related information.
Returns
(json object)
address: (string) The local address being listened on.
port: (numeric) The port being listened on for the associated local address.
score: (numeric) Reserved.
name: (string) The name of the network interface.
limited: (boolean) True if only connections to the network are allowed.
proxy: (string) The proxy set for the network.
proxyrandomizecredentials: (boolean) True if randomized credentials are set for the proxy.
reachable: (boolean) True if connections can be made to or from the network.
version: (numeric) The version of the node as a numeric.
subversion: (string) The subversion of the node, as advertised to peers.
protocolversion: (numeric) The protocol version of the node.
timeoffset: (numeric) The node clock offset in seconds.
connections: (numeric) The total number of open connections for the node.
networks: (json array) An array of objects describing IPV4, IPV6 and Onion network interface states.
relayfee: (numeric) The minimum required transaction fee for the node.
localaddresses: (json array) An array of objects describing local addresses being listened on by the node.
localservices: (string) The services supported by the node, as advertised in its version message.
{"version": n, "subversion": "major.minor.patch", "protocolversion": n, "timeoffset": n, "connections": n, "networks": [{"name": "network", "limited": true or false, "reachable": true or false, "proxy": "host:port","proxyrandomizecredentials": true or false }, ...], "relayfee": n.nn., "localaddresses": [{ "address": "ip", "port": n, "score": n }, ...], "localservices": "services"}
Returns data about each connected network peer as an array of json objects.
Returns
(json array)
id: (numeric) a unique node ID.
addr: (string) the ip address and port of the peer.
addrlocal: (string) local address.
services: (string) the services supported by the peer.
relaytxes: (boolean) peer has requested transactions be relayed to it.
lastsend: (numeric) time the last message was sent in seconds since 1 Jan 1970 GMT.
lastrecv: (numeric) time the last message was received in seconds since 1 Jan 1970 GMT.
bytessent: (numeric) total bytes sent.
bytesrecv: (numeric) total bytes received.
conntime: (numeric) time the connection was made in seconds since 1 Jan 1970 GMT.
pingtime: (numeric) number of microseconds the last ping took.
pingwait: (numeric) number of microseconds a queued ping has been waiting for a response.
version: (numeric) the protocol version of the peer.
subver: (string) the user agent of the peer.
inbound: (boolean) whether or not the peer is an inbound connection.
startingheight: (numeric) the latest block height the peer knew about when the connection was established.
currentheight: (numeric) the latest block height the peer is known to have relayed since connected.
banscore: (numeric) the ban score.
syncnode: (boolean) whether or not the peer is the sync peer.
[{"id": n, "addr": "host:port", "addrlocal": "host:port", "services": "00000001", "relaytxes": true_or_false, "lastsend": n, "lastrecv": n, "bytessent": n, "bytesrecv": n, "conntime": n, "pingtime": n.nnn, "pingwait": n.nnn, "version": n, "subver": "useragent", "inbound": true_or_false, "startingheight": n, "currentheight": n, "banscore": n, "syncnode": true_or_false }, ...]
verbose(boolean, optional, default=false) Returns JSON object when true or an array of transaction hashes when false.
txtype(string, optional) Type of transaction to return.
Description
Returns information about all of the transactions currently in the memory pool.
The verbose flag specifies that each transaction is returned as a JSON object.
The valid transaction types are regular, tickets, votes, revocations, tspend, tadd, and all.
Returns (verbose=false)
(json array of string)
transactionhash: (string) hash of the transaction.
["transactionhash", ...]
Returns (verbose=true)
(json object)
size: (numeric) transaction size in bytes.
fee : (numeric) transaction fee in DCR.
time: (numeric) local time transaction entered pool in seconds since 1 Jan 1970 GMT.
height: (numeric) block height when transaction entered the pool.
startingpriority: (numeric) (DEPRECATED) this field is always 0 and will be removed in a future version of the software.
currentpriority: (numeric) (DEPRECATED) this field is always 0 and will be removed in a future version of the software.
depends: (json array) unconfirmed transactions used as inputs for this transaction.
transactionhash: (string) hash of the parent transaction.
{"transactionhash": {"size": n,"fee" : n, "time": n,"height": n, "startingpriority": n, "currentpriority": n, "depends": ["transactionhash", ...]}, ...}
transaction hash: (string, required) the hash of the transaction.
verbose: (int, optional, default=0) specifies the transaction is returned as a JSON object instead of hex-encoded string.
Description
Returns information about a transaction given its hash.
Returns (verbose=0)
"data" (string) hex-encoded bytes of the serialized transaction
Returns (verbose=1)
(json object)
hex: (string) hex-encoded transaction / hex-encoded bytes of the script.
txid: (string) the hash of the transaction.
version: (numeric) the transaction version.
locktime: (numeric) the transaction lock time.
expiry: (numeric) the transaction expiry.
vin: (array of json objects) the transaction inputs as json objects.
vout: (array of json objects) the transaction outputs as json objects.
{"hex": "data", "txid": "hash", "version": n, "locktime": n, "expiry": n, "vin": [...], "vout": [...]}
vin (for coinbase transactions)
(json object)
coinbase: (string) the hex-encoded bytes of the signature script.
amountin: (numeric) the input amount.
blockheight: (numeric) the block height of the origin transaction.
blockindex: (numeric) the block index of the origin transaction.
sequence: (numeric) the script sequence number.
{"coinbase": "data", "amountin": n.nnn, "blockheight": n, "blockindex": n, "sequence": n, ...}
vin (for vote transactions)
(json object)
stakebase: (string) the hex-encoded bytes of the signature script.
amountin: (numeric) the input amount.
blockheight: (numeric) the block height of the origin transaction.
blockindex: (numeric) the block index of the origin transaction.
sequence: (numeric) the script sequence number.
{"stakebase": "data", "amountin": n.nnn, "blockheight": n, "blockindex": n, "sequence": n, ...}
vin (for treasurybase transactions)
(json object)
treasurybase: (boolean) Whether or not the input is a treasury base.
amountin: (numeric) the input amount.
blockheight: (numeric) the block height of the origin transaction.
blockindex: (numeric) the block index of the origin transaction.
sequence: (numeric) the script sequence number.
{"treasurybase": bool, "amountin": n.nnn, "blockheight": n, "blockindex": n, "sequence": n, ...}
vin (for treasury spend transactions)
(json object)
treasuryspend: (string) the hex-encoded bytes of the signature script.
amountin: (numeric) the input amount.
blockheight: (numeric) the block height of the origin transaction.
blockindex: (numeric) the block index of the origin transaction.
sequence: (numeric) the script sequence number.
{"treasuryspend": "data", "amountin": n.nnn, "blockheight": n, "blockindex": n, "sequence": n, ...}
vin (for other transactions)
(json object)
txid: (string) the hash of the origin transaction.
vout: (numeric) the index of the output being redeemed from the origin transaction.
tree: (numeric) the tree of the transaction.
sequence: (numeric) the script sequence number.
amountin: (numeric) the input amount.
blockheight: (numeric) the block height of the origin transaction.
blockindex: (numeric) the block index of the origin transaction.
scriptSig: (json object) the signature script used to redeem the origin transaction.
asm:(string) disassembly of the script.
hex: (string) hex-encoded bytes of the script.
{"txid": "hash", "vout": n, "tree": n, "sequence": n, "amountin": n.nnn, "blockheight": n, "blockindex": n, "scriptSig": {"asm": "asm", "hex": "data"}, ...}
vout
(json object)
value: (numeric) the value in DCR.
n: (numeric) the index of this transaction output.
version: (numeric) the version of public key script.
scriptPubKey:(json object) the public key script used to pay coins.
asm: (string) disassembly of the script.
hex: (string) hex-encoded bytes of the script.
reqSigs: (numeric) the number of required signatures.
type: (string) the type of the script (e.g. 'pubkeyhash').
addresses: (json array of string) the Decred addresses associated with this output.
commitamt: (numeric) the ticket commitment value if the script is for a staking commitment (ticket txns only)
version: (numeric) the script version.
{"value": n, "n": n, "scriptPubKey": {"asm": "asm", "hex": "data","reqSigs": n, "type": "scripttype", "addresses": [...], "commitamt": n.nnn, "version": n}}
Example Return (verbose=0)
Newlines added for display purposes. The actual return does not contain newlines.
count: (numeric, required) The number of blocks that will be returned.
Description
Returns the stake versions statistics.
Returns
stakeversions: (array of object) Array of stake versions per block.
hash: (string) hash of the block.
height: (numeric) Height of the block.
blockversion: (numeric) the block version.
stakeversion: (numeric) the stake version of the block.
votes: (array of object) the version and bits of each vote in the block.
version: (numeric) the version of the vote.
bits: (numeric) the bits assigned by the vote.
{"stakeversions": [{ "hash": "value", "height": n, "blockversion": n, "stakeversion": n,"votes": [{ "version": n, "bits": n },...]},...]}
getticketpoolvalue
Method
getticketpoolvalue
Parameters
None
Description
Returns the current value of all locked funds in the ticket pool.
Returns
numeric
Example Return
5214124.18608402
gettreasurybalance
Method
gettreasurybalance
Parameters
hash: (string, optional) Return the treasury balance at the specified block. If unspecified, return the balance for the current tip block.
verbose: (bool, optional) Whether to fill the updates field of the response. Defaults to false.
Description
Returns the matured balance of the network's treasury account. It optionally also returns the individual balance-changing amounts (treasury base, add and spend transactions) for the block.
Returns
(json object)
hash: (string) Block hash for which the balance was fetched.
height: (numeric) Block height for which the balance was fetched.
balance: (numeric) Balance (in atoms) of mature funds of the treasury account.
updates: (json array of numeric): Individual amounts that affect the treasury balance in the given block. Amounts corresponding to treasury spend transactions will be negative. Only filled if verbose is specified.
blockhash: (string, optional) Count treasury spend votes up to this block. If unspecified, the current chain tip is used.
tspends: (json array of strings, optional) A list of treasury spend transaction hashes for which to tally votes. All specified hashes must correspond to either mined or mempool residing tspends. If unspecified, defaults to tallying votes for all tspends currently in the mempool.
Description
Returns a tally of on-chain votes for treasury spend transactions.
Returns
(json object)
hash: (string) The block hash of the block up to which the votes were tallied.
height: (numeric) The block height of the block up to which the votes were tallied.
votes: (json array of objects) Per-tspend vote counts.
hash: (string) Hash of the treasury spend transaction.
expiry: (numeric) Expiry value for the tspend tx.
votestart: (numeric) Block height at which voting for the tspend starts.
voteend: (numeric) Block height at which voting for the tspend ends.
yesvotes: (numeric) Number of yes votes the tspend received (up to the height returned in the main response object).
novotes: (numeric) Number of no votes the tspend received (up to the height returned in the main response object).
startheight: (numeric) The start height of the voting window.
endheight: (numeric) The end height of the voting window.
hash: (string) The hash of the current height block.
voteversion: (numeric) The selected vote version.
quorum: (numeric) The minimum amount of votes required.
totalvotes: (numeric) Total votes.
agendas: (json array) All agendas for this stake version.
id: (string) Unique identifier of the agenda.
description: (string) Description of this agenda.
mask: (numeric) Agenda mask.
starttime: (numeric) Time agenda becomes valid.
expiretime: (numeric) Time agenda becomes invalid.
status: (string) Agenda status.
quorumprogress: (numeric) Progress of quorum reached.
choices: (json array) All choices in the agenda.
id: (string) Unique identifier of the choice.
description: (string) Unique identifier of the choice.
bits: (numeric) Bits that identify the choice.
isabstain: (boolean) This choice is to abstain from change.
isno: (boolean) Hard no choice (1 and only 1 per agenda).
count: (numeric) How many votes received.
progress: (numeric) Progress of the overall count.
Example Return
{"currentheight": 374709,"startheight": 366976,"endheight": 375039,"hash": "00000000000000001ff9abe7300929d1a0ce8cca0d3a57e201336af82be3330e","voteversion": 5,"quorum": 4032,"totalvotes": 1835,"agendas": [{"id": "lnfeatures","description": "Enable features defined in DCP0002 and DCP0003 necessary to support Lightning Network (LN)","mask": 6,"starttime": 1505260800,"expiretime": 1536796800,"status": "active","quorumprogress": 0,"choices": [{"id": "abstain","description": "abstain voting for change","bits": 0,"isabstain": true,"isno": false,"count": 0,"progress": 0},{"id": "no","description": "keep the existing consensus rules","bits": 2,"isabstain": false,"isno": true,"count": 0,"progress": 0},{"id": "yes","description": "change to the new consensus rules","bits": 4,"isabstain": false,"isno": false,"count": 0,"progress": 0}]}]}
getwork
Method
getwork
Parameters
data: (string, optional) The hex
Description
Returns formatted hash data to work on or checks and submits solved data.
Notes
Since dcrd does not have the wallet integrated to provide payment addresses, dcrd must be configured via the --miningaddr option to provide which payment addresses to pay created blocks to for this RPC to function.
Returns (data not specified)
(json object)
data: (string) hex-encoded block data
target: (string) the hex-encoded little-endian hash target
subcmd: (string, required)disconnect to remove all matching non-persistent peers, remove to remove a persistent peer, or connect to connect to a peer.
target: (string, required) Either the IP address and port of the peer to operate on, or a valid peer ID.
connectsubcmd: (string)perm to make the connected peer a permanent one, temp to try a single connect to a peer.
Description
Attempts to add or remove a peer.
Returns
Nothing
ping
Method
ping
Parameters
None
Description
Queues a ping to be sent to each connected peer.
Ping times are provided by getpeerinfo via the pingtime and pingwait fields.
Returns
Nothing
reconsiderblock
Method
reconsiderblock
Parameters
block hash: (string, required) the hash of the block to reconsider
Description
Reconsiders a block for validation and best chain selection by removing any invalid status from it and its ancestors.
Any descendants that are neither themselves marked as having failed validation, nor descendants of another such block, are also made eligibile for best chain selection.
Returns
Nothing
regentemplate
Method
regentemplate
Parameters
None
Description
Asks the daemon to regenerate the block mining template. Note that template generation is an asynchronous process and some situations (such as the node performing a reorg or waiting for remaining votes after a new block was connected to the main chain) might delay template regeneration.
Returns
Nothing
sendrawmixmessage
Method
sendrawmixmessage
Parameters
command: (string, required) the wire command name of the message type.
message: (string, required) mixing message serialized and encoded as hex.
Description
Submits a serialized, hex-encoded mixing message to the mixpool and broadcasts it to the network.
The valid wire command names are mixpairreq, mixkeyxchg, mixcphrtxt, mixslotres, mixdcnet, mixconfirm, mixfactpoly, and mixsecrets.
Returns
Nothing
sendrawtransaction
Method
sendrawtransaction
Parameters
signedhex: (string, required) serialized, hex-encoded signed transaction.
allowhighfees: (boolean, optional, default=false) whether or not to allow insanely high fees.
Description
Submits the serialized, hex-encoded transaction to the local peer and relays it to the network.
generate: (boolean, required) set to true to enable generation, false to disable it.
genproclimit: (numeric, optional) the number of processors (cores) to limit generation to or -1 for default.
Description
Set the server to generate coins (mine) or not.
Notes
NOTE: Since dcrd does not have the wallet integrated to provide payment addresses, dcrd must be configured via the --miningaddr option to provide which payment addresses to pay created blocks to for this RPC to function.
Returns
Nothing
startprofiler
Method
startprofiler
Parameters
address: (string, required) the interface/port to listen for profile server connections (e.g. 127.0.0.1:6060)
allownonloopback: (boolean, optional, default=false) whether or not to allow listening on non loopback addresses
Description
Starts the HTTP profile server listening on a given address.
The provided address may either be a lone port or of the form host:port. When a lone port is provided, the address will be normalized to a loopback address by prepending 127.0.0.1:
Note that all non loopback addresses are rejected by default unless the allownonloopback parameter is set to true. This protection mechanism is in place to help prevent accidentally exposing the profile server publicly.
If access to profiling data from outside of the local machine is required, users are highly encouraged to use a mechanism such as ssh local port forwarding with its -L flag instead.
When the allownonloopback parameter is true, the host portion of the address may be an interface name to listen on all IP addresses associated with the interface.
Returns
(json object)
listeners: (json array) List of normalized listening addresses the profile server is listening on
isvalid: (bool) whether or not the address is valid.
address: (string) the Decred address validated.
{"isvalid": true or false,"address": "decredaddress"}
verifychain
Method
verifychain
Parameters
checklevel: (numeric, optional, default=3) how in-depth the verification is (0=least amount of checks, higher levels are clamped to the highest supported level).
numblocks: (numeric, optional, default=288) the number of blocks starting from the end of the chain to verify.
Description
Verifies the block chain database. The actual checks performed by the checklevel parameter is implementation specific.
For dcrd this is:
checklevel=0 - Look up each block and ensure it can be loaded from the database.
checklevel=1 - Perform basic context-free sanity checks on each block.
Notes
dcrd currently only supports checklevel 0 and 1, but the default is still 3 for compatibility. Per the information in the Parameters section above, higher levels are automatically clamped to the highest supported level, so this means the default is effectively 1 for dcrd.
Returns
(boolean)true or false
Example Return
true
verifymessage
Method
verifymessage
Parameters
address: (string, required) The Decred address to use for the signature.
signature: (string, required) The base-64 encoded signature provided by the signer.
message: (string, required) The signed message.
Description
Verify an address is valid.
Returns
(boolean) Whether or not the signature verified.
Example Return
true
version
Method
version
Parameters
None
Description
Returns the JSON-RPC API version (semver)
Returns
(json object) Object containing the semantic versions of programs and API versions.
The following is an overview of the RPC method requests available exclusively to Websocket clients. All of these RPC methods are available to the limited
user. Click the method name for further details such as parameter and return information.
Authenticate the connection against the username and passphrase configured for the RPC server. NOTE: This is only required if an HTTP Authorization header is not being used.
Return details regarding a websocket client's current connection.
None
6.2 Method Details
authenticate
Method
authenticate
Parameters
username: (string, required)
passphrase: (string, required)
Description
Authenticate the connection against the username and password configured for the RPC server. Invoking any other method before authenticating with this command will close the connection.
NOTE: This is only required if an HTTP Authorization header is not being used.
verbose: (boolean, optional, default=false) specifies which type of notification to receive. If verbose is true, then the caller receives txacceptedverbose, otherwise the caller receives txaccepted
Description
Send either a txaccepted or a txacceptedverbose notification when a new transaction is accepted into the mempool.
Returns
Nothing
stopnotifynewtransactions
Method
stopnotifynewtransactions
Notifications
None
Parameters
None
Description
Stop sending either a txaccepted or a txacceptedverbose notification when a new transaction is accepted into the mempool.
Send a newtickets notification when new tickets have matured.
Returns
Nothing
session
Method
session
Notifications
None
Parameters
None
Description
Return a JSON object with details regarding a websocket client's current connection to the RPC server. This currently only includes the session ID, a random unsigned 64-bit integer that is created for each newly connected client. Session IDs may be used to verify that the current connection was not lost and subsequently reestablished.
Returns
(json object)
sessionid: (numeric) the session ID.
{"sessionid": n}
Example Return
{"sessionid": 67089679842}
7. Notifications (Websocket-specific)
dcrd uses standard JSON-RPC notifications to notify clients of changes, rather than requiring clients to poll dcrd for updates. JSON-RPC notifications are a subset of requests, but do not contain an ID. The notification type is categorized by the method field and additional details are sent as a JSON array in the params field.
7.1 Notification Overview
The following is an overview of the JSON-RPC notifications used for Websocket connections. Click the method name for further details of the context(s) in which they are sent and their parameters.
8.1.1 Using getblockcount to Retrieve the Current Block Height
The following is an example Go application which uses the
rpcclient package to connect with
a dcrd instance via Websockets, issues getblockcount to
retrieve the current block height, and displays it.
package main
import (
"context"
"log"
"os"
"path/filepath"
"github.com/decred/dcrd/dcrutil/v4"
"github.com/decred/dcrd/rpcclient/v8"
)
func main() {
// Load the certificate for the TLS connection which is automatically
// generated by dcrd when it starts the RPC server and doesn't already
// have one.
dcrdHomeDir := dcrutil.AppDataDir("dcrd", false)
certs, err := os.ReadFile(filepath.Join(dcrdHomeDir, "rpc.cert"))
if err != nil {
log.Fatal(err)
}
// Create a new RPC client using websockets. Since this example is
// not long-lived, the connection will be closed as soon as the program
// exits.
connCfg := &rpcclient.ConnConfig{
Host: "localhost:9109",
Endpoint: "ws",
User: "yourrpcuser",
Pass: "yourrpcpass",
Certificates: certs,
}
client, err := rpcclient.New(connCfg, nil)
if err != nil {
log.Fatal(err)
}
defer client.Shutdown()
// Query the RPC server for the current block count and display it.
ctx := context.Background()
blockCount, err := client.GetBlockCount(ctx)
if err != nil {
log.Fatal(err)
}
log.Printf("Block count: %d", blockCount)
}
Which results in:
Block count: 203528
8.1.2 Using getblock to Retrieve the Genesis Block
The following is an example Go application which uses the
rpcclient package to connect with
a dcrd instance via Websockets, issues getblock to retrieve
information about the Genesis block, and display a few details about it.
package main
import (
"context"
"log"
"os"
"path/filepath"
"time"
"github.com/decred/dcrd/chaincfg/chainhash"
"github.com/decred/dcrd/dcrutil/v4"
"github.com/decred/dcrd/rpcclient/v8"
)
func main() {
// Load the certificate for the TLS connection which is automatically
// generated by dcrd when it starts the RPC server and doesn't already
// have one.
dcrdHomeDir := dcrutil.AppDataDir("dcrd", false)
certs, err := os.ReadFile(filepath.Join(dcrdHomeDir, "rpc.cert"))
if err != nil {
log.Fatal(err)
}
// Create a new RPC client using websockets. Since this example is
// not long-lived, the connection will be closed as soon as the program
// exits.
connCfg := &rpcclient.ConnConfig{
Host: "localhost:9109",
Endpoint: "ws",
User: "yourrpcuser",
Pass: "yourrpcpass",
Certificates: certs,
}
client, err := rpcclient.New(connCfg, nil)
if err != nil {
log.Fatal(err)
}
defer client.Shutdown()
// Query the RPC server for the genesis block using the "getblock"
// command with the verbose flag set to true and the verboseTx flag
// set to false.
ctx := context.Background()
genesisHashStr := "298e5cc3d985bfe7f81dc135f360abe089edd4396b86d2de66b0cef42b21d980"
blockHash, err := chainhash.NewHashFromStr(genesisHashStr)
if err != nil {
log.Fatal(err)
}
block, err := client.GetBlockVerbose(ctx, blockHash, false)
if err != nil {
log.Fatal(err)
}
// Display some details about the returned block.
log.Printf("Hash: %v\n", block.Hash)
log.Printf("Previous Block: %v\n", block.PreviousHash)
log.Printf("Next Block: %v\n", block.NextHash)
log.Printf("Merkle root: %v\n", block.MerkleRoot)
log.Printf("Timestamp: %v\n", time.Unix(block.Time, 0).UTC())
log.Printf("Confirmations: %v\n", block.Confirmations)
log.Printf("Difficulty: %f\n", block.Difficulty)
log.Printf("Size (in bytes): %v\n", block.Size)
log.Printf("Num transactions: %v\n", len(block.Tx))
}
Which results in:
Hash: 298e5cc3d985bfe7f81dc135f360abe089edd4396b86d2de66b0cef42b21d980
Previous Block: 0000000000000000000000000000000000000000000000000000000000000000
Next Block: 000000000000437482b6d47f82f374cde539440ddb108b0a76886f0d87d126b9
Merkle root: 66aa7491b9adce110585ccab7e3fb5fe280de174530cca10eba2c6c3df01c10d
Timestamp: 2016-02-08 18:00:00 +0000 UTC
Confirmations: 203529
Difficulty: 32767.749998
Size (in bytes): 0
Num transactions: 1
8.1.3 Using notifyblocks to Receive blockconnected and blockdisconnected Notifications (Websocket-specific)
The following is an example Go application which uses the
rpcclient package to connect with
a dcrd instance via Websockets and registers for
blockconnected and blockdisconnected
notifications with notifyblocks. It also sets up handlers for
the notifications.
package main
import (
"context"
"log"
"os"
"path/filepath"
"time"
"github.com/decred/dcrd/dcrutil/v4"
"github.com/decred/dcrd/rpcclient/v8"
)
func main() {
// Setup handlers for blockconnected and blockdisconnected
// notifications.
ntfnHandlers := rpcclient.NotificationHandlers{
OnBlockConnected: func(blockHeader []byte, transactions [][]byte) {
log.Printf("Block connected: %x (%d txs)", blockHeader, len(transactions))
},
OnBlockDisconnected: func(blockHeader []byte) {
log.Printf("Block disconnected: %x", blockHeader)
},
}
// Load the certificate for the TLS connection which is automatically
// generated by dcrd when it starts the RPC server and doesn't already
// have one.
dcrdHomeDir := dcrutil.AppDataDir("dcrd", false)
certs, err := os.ReadFile(filepath.Join(dcrdHomeDir, "rpc.cert"))
if err != nil {
log.Fatal(err)
}
// Create a new RPC client using websockets.
connCfg := &rpcclient.ConnConfig{
Host: "localhost:9109",
Endpoint: "ws",
User: "yourrpcuser",
Pass: "yourrpcpass",
Certificates: certs,
}
client, err := rpcclient.New(connCfg, &ntfnHandlers)
if err != nil {
log.Fatal(err)
}
// Register for blockconnected and blockdisconneted notifications.
ctx := context.Background()
if err := client.NotifyBlocks(ctx); err != nil {
client.Shutdown()
log.Fatal(err)
}
// For this example, gracefully shutdown the client after 10 seconds.
// Ordinarily when to shutdown the client is highly application
// specific.
log.Println("Client shutdown in 10 seconds...")
time.AfterFunc(time.Second*10, func() {
log.Println("Client shutting down...")
client.Shutdown()
log.Println("Client shutdown complete.")
})
// Wait until the client either shuts down gracefully (or the user
// terminates the process with Ctrl+C).
client.WaitForShutdown()
}
8.2.1 Using notifyblocks to be Notified of Block Connects and Disconnects
The following is example node.js code which uses ws
(can be installed with npm install ws) to connect with a dcrd instance,
issues notifyblocks to register for
blockconnected and blockdisconnected
notifications, and displays all incoming messages.
This code has only been confirmed to work as of node.js 8.11.1 LTS. It might
not work with earlier versions.
var fs = require('fs');
var WebSocket = require('ws');
// Load the certificate for the TLS connection which is automatically
// generated by dcrd when it starts the RPC server and doesn't already
// have one.
var cert = fs.readFileSync('/path/to/dcrd/appdata/rpc.cert');
var user = "yourusername";
var password = "yourpassword";
// Initiate the websocket connection. The dcrd generated certificate acts as
// its own certificate authority, so it needs to be specified in the 'ca' array
// for the certificate to properly validate.
var ws = new WebSocket('wss://127.0.0.1:9109/ws', {
headers: {
'Authorization': 'Basic '+Buffer.from(user+':'+password).toString('base64')
},
cert: cert,
ecdhCurve: 'secp521r1', // Required for node.js v8.11.1 LTS, not for v10.1.0.
ca: [cert]
});
ws.on('open', function() {
console.log('CONNECTED');
// Send a JSON-RPC command to be notified when blocks are connected and
// disconnected from the chain.
ws.send('{"jsonrpc":"1.0","id":"0","method":"notifyblocks","params":[]}');
});
ws.on('message', function(data, flags) {
console.log(data);
});
ws.on('error', function(derp) {
console.log('ERROR:' + derp);
})
ws.on('close', function(data) {
console.log('DISCONNECTED');
})