dcrd/docs/json_rpc_api.md
2018-10-09 18:28:17 -05:00

92 KiB

Table of Contents

  1. Overview
  2. HTTP POST Versus Websockets
  3. Authentication
    3.1. Overview
    3.2. HTTP Basic Access Authentication
    3.3. JSON-RPC Authenticate Command (Websocket-specific)
  4. Command-line Utility
  5. Standard Methods
    5.1. Method Overview
    5.2. Method Details
  6. Websocket Methods (Websocket Specific)
    6.1. Method Overview
    6.2. Method Details
  7. Notifications (Websocket-specific)
    7.1. Notification Overview
    7.2. Notification Details
  8. Example Code
    8.1. Go
    8.2. node.js

1. Overview

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.

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).

The original bitcoind/bitcoin-qt JSON-RPC API documentation is available at https://en.bitcoin.it/wiki/Original_Bitcoin_client/API_Calls_list

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.

3.2 HTTP Basic Access Authentication

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.

3.3 JSON-RPC Authenticate Command (Websocket-specific)

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 comes with a separate utility named 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.

# Method Safe for limited user? Description
1 addnode N Attempts to add or remove a persistent peer.
2 createrawtransaction Y Returns a new transaction spending the provided inputs and sending to the provided addresses.
3 decoderawtransaction Y Returns a JSON object representing the provided serialized, hex-encoded transaction.
4 decodescript Y Returns a JSON object with information about the provided hex-encoded script.
5 getaddednodeinfo N Returns information about manually added (persistent) peers.
6 getbestblockhash Y Returns the hash of the of the best (most recent) block in the longest block chain.
7 getblock Y Returns information about a block given its hash.
8 getblockchaininfo Y Returns information about the current state of the block chain.
9 getblockcount Y Returns the number of blocks in the longest block chain.
10 getblockhash Y Returns hash of the block in best block chain at the given height.
11 getblockheader Y Returns the block header of the block.
12 getchaintips Y Returns information about all known chain tips the in the block tree.
13 getconnectioncount N Returns the number of active connections to other peers.
14 getdifficulty Y Returns the proof-of-work difficulty as a multiple of the minimum difficulty.
15 getgenerate N Return if the server is set to generate coins (mine) or not.
16 gethashespersec N Returns a recent hashes per second performance measurement while generating coins (mining).
17 getinfo Y Returns a JSON object containing various state info.
18 getmempoolinfo N Returns a JSON object containing mempool-related information.
19 getmininginfo N Returns a JSON object containing mining-related information.
20 getnettotals Y Returns a JSON object containing network traffic statistics.
21 getnetworkhashps Y Returns the estimated network hashes per second for the block heights provided by the parameters.
22 getpeerinfo N Returns information about each connected network peer as an array of json objects.
23 getrawmempool Y Returns an array of hashes for all of the transactions currently in the memory pool.
24 getrawtransaction Y Returns information about a transaction given its hash.
25 getwork N 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.
26 help Y Returns a list of all commands or help for a specified command.
27 ping N Queues a ping to be sent to each connected peer.
28 sendrawtransaction Y Submits the serialized, hex-encoded transaction to the local peer and relays it to the network.

NOTE: dcrd does not yet implement the allowhighfees parameter, so it has no effect
29 setgenerate N 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.
30 stop N Shutdown dcrd.
31 submitblock Y Attempts to submit a new serialized, hex-encoded block to the network.
32 validateaddress Y Verifies the given address is valid. NOTE: Since dcrd does not have a wallet integrated, dcrd will only return whether the address is valid or not.
33 verifychain N Verifies the block chain database.
34 debuglevel N Dynamically changes the debug logging level.
35 getbestblock Y Get block height and hash of best block in the main chain.
36 getcurrentnet Y Get Decred network dcrd is running on.
37 searchrawtransactions Y Query for transactions related to a particular address.
38 node N Attempts to add or remove a peer.
39 generate N When in simnet or regtest mode, generate a set number of blocks.
40 getstakeversions Y Get stake versions per block.

5.2 Method Details

Method addnode
Parameters 1. peer: (string, required) ip address and port of the peer to operate on.
2. command: (string, required) - add to add a persistent peer, remove to remove a persistent peer, or onetry to try a single connection to a peer.
Description Attempts to add or remove a persistent peer.
Returns Nothing
Return to Overview

Method createrawtransaction
Parameters 1. transaction inputs: (JSON array, required) json array of json objects.
amount: (numeric) the previous output amount.
hash: (string, required) the hash of the input.
vout: (numeric, required) the specific output of the input transaction to redeem transaction.

[{"amount": n.nnn, "txid": "hash", "vout": n}, ...]

2. addresses and amounts: (JSON object, required) - json object with addresses as keys and output amounts as values.
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
Example Parameters 1. transaction inputs [{"amount":0.49213337, "txid":"e6da89de7a6b8508ce8f371a3d0535b04b5e108cb1a6e9284602d3bfd357c018", "vout":1}]

2. addresses and amounts {"13cgrTP7wgbZYWrY9BZ22BV6p82QXQT3nY": 0.49213337}
Example Return Newlines added for display purposes. The actual return does not contain newlines.
010000000118c057d3bfd3024628e9a6b18c105e4bb035053d1a378fce08856b7ade89dae6010000
0000ffffffff0199efee02000000001976a9141cb013db35ecccc156fdfd81d03a11c51998f99388
ac00000000
Return to Overview

Method decoderawtransaction
Parameters 1. data: (string, required) serialized, hex-encoded transaction.
Description 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.
locktime: (numeric) the transaction lock time.
version: (numeric) the block version.
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", "locktime": n, "version":n, "expiry": n, "vin": [...], "vout": [...]}

vin (for coinbase transactions)
(json object)
coinbase: (string) the hex-encoded bytes of the signature script.
sequence: (numeric) the script sequence number.

{"coinbase": "data", "sequence": n, ...}

vin (for stakebase transactions)
(json object)
stakebase: (string) the hash of the stake transaction.
sequence: (numeric) the script sequence number.

{"stakebase": "hash", "sequence": n, ...}

vin (for non-coinbase / non-stakebase transactions)
(json object)
txid: (string) the hash of the origin transaction.
vout: (numeric) the index of the output being redeemed from the origin transaction.
scriptSig: (json object) the signature script used to redeem the origin transaction.
asm:(string) disassembly of the script.
data: (string) hex-encoded bytes of the script.
sequence: (numeric) the script sequence number.

{"txid": "hash", "vout": n,"scriptSig": {"asm": "asm", "hex": "data"}, "sequence": n, ...}

vout
(json object)
value: (numeric) the value in DCR.
n: (numeric) the index of this transaction output.
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.

{ "value": n, "n": n, "scriptPubKey": {"asm": "asm", "hex": "data","reqSigs": n, "type": "scripttype","addresses": [...]}}
Example Return For coinbase transactions
{"txid": "4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b", "version": 1, "locktime": 0, "vin": [{"coinbase": "04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6...","sequence": 4294967295}, ...],"vout": [{"value": 50, "n": 0, "scriptPubKey": {"asm": "04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4ce...","hex": "4104678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4...", "reqSigs": 1,"type": "pubkey","addresses": ["1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa", ...]}}]}

For stakebase transactions
{"txid": "4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b", "version": 1, "locktime": 0, "vin": [{"stakebase": "60ac4b057247b3d0b9a8173de56b5e1be8c1d1da970511c626ef53706c66be04","sequence": 4294967295}, ...],"vout": [{"value": 50, "n": 0, "scriptPubKey": {"asm": "04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4ce...","hex": "4104678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4...", "reqSigs": 1,"type": "pubkey","addresses": ["1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa", ...]}}]}

For non-coinbase / non-stakebase transactions
{"txid": "4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b", "version": 1, "locktime": 0, "vin": [{"txid": "60ac4b057247b3d0b9a8173de56b5e1be8c1d1da970511c626ef53706c66be04", "vout": 0, "scriptSig": {"asm": "3046022100cb42f8df44eca83dd0a727988dcde9384953e830b1f8004d57485e2ede1b9c8f0...", "hex": "493046022100cb42f8df44eca83dd0a727988dcde9384953e830b1f8004d57485e2ede1b9c8...",},"sequence": 4294967295}, ...],"vout": [{"value": 50, "n": 0, "scriptPubKey": {"asm": "04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4ce...","hex": "4104678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4...", "reqSigs": 1,"type": "pubkey","addresses": ["1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa", ...]}}]}
Return to Overview

Method decodescript
Parameters 1. script: (string, required) hex-encoded script.
Description Returns a JSON object with information about the provided hex-encoded script.
Returns (json object)
asm: (string) disassembly of the script (absent for nonstandard scripts).
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 script.
p2sh: (string) the script hash for use in pay-to-script-hash transactions.

{ "asm": "asm", "reqSigs": n, "type": "scripttype", "addresses": [...], "p2sh": "scripthash"}
Example Return {"asm": "OP_DUP OP_HASH160 b0a4d8a91981106e4ed85165a66748b19f7b7ad4 OP_EQUALVERIFY OP_CHECKSIG", "reqSigs": 1, "type": "pubkeyhash", "addresses": ["1H71QVBpzuLTNUh5pewaH3UTLTo2vWgcRJ"], "p2sh": "359b84ff799f48231990ff0298206f54117b08b6"}
Return to Overview

Method getaddednodeinfo
Parameters 1. dns: (boolean, required) specifies whether the returned data is a JSON object including DNS and connection information, or just a list of added peers.
2. 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).

[{"addednode": "ip_or_domain","connected": true or false,"addresses": [{address: "ip"}, ...], "connected": "inbound/outbound/false"}, ...]
Example Return (dns=false) ["192.168.0.10:9108", "mydomain.org:9108"]
Example Return (dns=true) [{"addednode": "mydomain.org:9108", "connected": true, "addresses": [{"address": "1.2.3.4", "connected": "outbound"}, {"address": "5.6.7.8", "connected": "false"}]}]
Return to Overview

Method getbestblockhash
Parameters None
Description Returns the hash of the of the best (most recent) block in the longest block chain.
Returns string
Example Return 0000000000000001f356adc6b29ab42b59f913a396e170f80190dba615bd1e60
Return to Overview

Method getblock
Parameters 1. block hash: (string, required) the hash of the block.
2. verbose: (boolean, optional, default=true) specifies the block is returned as a JSON object instead of hex-encoded string.
3. 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).
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.
transactionhash: (string) hash of the parent transaction.
time: (numeric) the block time in seconds since 1 Jan 1970 GMT.
nonce: (numeric) the block nonce.
bits: (numeric) the bits which represent the block difficulty.
sbits: (numeric) the bits which represent the stake difficulty
revocations: (numeric) the number of nullified tickets.
difficulty: (numeric) the proof-of-work difficulty as a multiple of the minimum difficulty.
previousblockhash: (string) the hash of the previous block.
nextblockhash: (string) the hash of the next block.

{"hash": "blockhash","confirmations": n, "size": n, "height": n,"version": n, "merkleroot": "hash","tx": ["transactionhash", ...],"stx": ["transactionhash", ...],"time": n, "revocations": n, "nonce": n, "bits": n, "difficulty": n.nn, "previousblockhash": "hash", "nextblockhash": "hash", ...}
Returns (verbose=true, verbosetx=true) (json object)
hash: (string) the hash of the block (same as provided)
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.
rawtx: (array of json objects) the transactions as json objects.
tx: (json array of string) the transaction hashes.
stx: (json array of string) the stake transaction hashes.
transactionhash: (string) hash of the parent transaction.
time: (numeric) the block time in seconds since 1 Jan 1970 GMT.
nonce: (numeric) the block nonce.
bits: (numeric) the bits which represent the block difficulty.
revocations: (numeric) the number of nullified tickets.
difficulty: (numeric) the proof-of-work difficulty as a multiple of the minimum difficulty.
previousblockhash: (string) the hash of the previous block.
nextblockhash: (string) the hash of the next block.

{"hash": "blockhash","confirmations": n, "size": n, "height": n,"version": n, "merkleroot": "hash", "rawtx":[...], "tx": ["transactionhash", ...], "tx": ["transactionhash", ...],"time": n, "revocations": n, "nonce": n, "bits": n, "difficulty": n.nn, "previousblockhash": "hash", "nextblockhash": "hash", ...}
Example Return (verbose=false) Newlines added for display purposes. The actual return does not contain newlines.
"010000000000000000000000000000000000000000000000000000000000000000000000
3ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a29ab5f49
ffff001d1dac2b7c01010000000100000000000000000000000000000000000000000000
00000000000000000000ffffffff4d04ffff001d0104455468652054696d65732030332f
4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f
6e64206261696c6f757420666f722062616e6b73ffffffff0100f2052a01000000434104
678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f
4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5fac00000000"
Example Return (verbose=true, verbosetx=false) "hash": "000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f", "confirmations": 277113,"size": 285, "height": 0, "version": 1, "merkleroot": "4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b", "tx": ["4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b", ...], "stx": ["4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f", ...], "time": 1231006505, "nonce": 2083236893, "bits": "1d00ffff", "difficulty": 1, "previousblockhash": "0000000000000000000000000000000000000000000000000000000000000000", "nextblockhash": "00000000839a8e6886ab5951d76f411475428afc90947ee320161bbf18eb6048", ...}
Return to Overview

Method getblockcount
Parameters None
Description Returns the number of blocks in the longest block chain.
Returns numeric
Example Return 276820
Return to Overview

Method getblockhash
Parameters 1. block height (numeric, required)
Description Returns hash of the block in best block chain at the given height.
Returns string
Example Return 000000000000000096579458d1c0f1531fcfc58d57b4fce51eb177d8d10e784d
Return to Overview

Method getblockheader
Parameters 1. block hash: (string, required) the hash of the block.
2. 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).
confirmations: (numeric) the number of confirmations.
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.
time: (numeric) the block time in seconds since 1 Jan 1970 GMT
nonce: (numeric) the block nonce.
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.
previousblockhash: (string) the hash of the previous block.
nextblockhash: (string) the hash of the next block (only if there is one).

{"hash": "blockhash", "confirmations": n, "height": n, "version": n, "merkleroot": "hash", "stakeroot": "hash", "time": n, "nonce": n, "bits": n, "sbits": n, "difficulty": n.nn, "previousblockhash": "hash", "nextblockhash": "hash"}
Example Return (verbose=false) Newlines added for display purposes. The actual return does not contain newlines.
"0200000035ab154183570282ce9afc0b494c9fc6a3cfea05aa8c1add2ecc564900000000
38ba3d78e4500a5a7570dbe61960398add4410d278b21cd9708e6d9743f374d544fc0552
27f1001c29c1ea3b"
Example Return (verbose=true) {"hash": "00000000009e2958c15ff9290d571bf9459e93b19765c6801ddeccadbb160a1e", "confirmations": 392076, "height": 100000, "version": 2, "merkleroot": "d574f343976d8e70d91cb278d21044dd8a396019e6db70755a0a50e4783dba38", "stakeroot":"b4765ae7d5bf4768ff7c4372d55abb7894b2bd9d3f48f7437115502b0bcc47e7", "time": 1376123972, "nonce": 1005240617, "bits": "1c00f127", "sbits": 68, "difficulty": 271.75767393, "previousblockhash": "000000004956cc2edd1a8caa05eacfa3c69f4c490bfc9ace820257834115ab35", "nextblockhash": "0000000000629d100db387f37d0f37c51118f250fb0946310a8c37316cbc4028", ...}
Return to Overview

Method getchaintips
Parameters None
Description 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"}, ...]
Example Return [{"height": 217033, "hash": "00000000000000161bd5b120ef945faad60fc6e4c32b5caf1d4cabeae9a75346", "branchlen": 0, "status": "active"}, {"height": 213522, "hash": "0000000000000015e27658ce02ba8fa05d8d7ad9c587a5a472e3307773a9b36e", "branchlen": 1, "status": "valid-fork"}]"
Return to Overview

Method getblockchaininfo
Parameters None
Description 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) The current network 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, "verificationprogress": n, "chainwork": "n", "initialblockdownload": bool, "maxblocksize": n, "deployments": {"agenda": { "status": "status", "since": n, "starttime": n, "expiretime": n}, ...}}
Example Return {"chain": "simnet", "blocks": 463, "headers": 463, "syncheight": 0, "bestblockhash": "000043c89f6e227c9d90a5460aff98b662e503b9a394818942bdd60709cbb8aa", "difficulty": 520127421, "verificationprogress": 0, "chainwork": "0x23c0e40", "initialblockdownload": false, "maxblocksize": 1000000, "deployments": {"lnfeatures": {"status": "started", "since": 463, "starttime": 0, "expiretime": 9223372036854775807}, "maxblocksize": {"status": "started", "since": 463, "starttime": 0, "expiretime": 9223372036854775807}, "sdiffalgorithm": {"status": "started", "since": 463, "starttime": 0, "expiretime": 9223372036854775807}}}
Return to Overview

Method getconnectioncount
Parameters None
Description Returns the number of active connections to other peers.
Returns numeric
Example Return 8
Return to Overview

Method getdifficulty
Parameters None
Description Returns the proof-of-work difficulty as a multiple of the minimum difficulty.
Returns numeric
Example Return 1180923195.260000
Return to Overview

Method getgenerate
Parameters None
Description Return if the server is set to generate coins (mine) or not.
Returns false (boolean)
Return to Overview

Method gethashespersec
Parameters None
Description Returns a recent hashes per second performance measurement while generating coins (mining).
Returns 0 (numeric)
Return to Overview

Method getinfo
Parameters None
Description 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.

{"version": n,"protocolversion": n, "blocks": n, "timeoffset": n, "connections": n, "proxy": "host:port", "difficulty": n.nn, "testnet": true or false, "relayfee": n.nn}
Example Return {"version": 70000, "protocolversion": 70001, "blocks": 298963, "timeoffset": 0, "connections": 17, "proxy": "", "difficulty": 8000872135.97, "testnet": false,"relayfee": 0.00001}
Return to Overview

Method getmempoolinfo
Parameters None
Description 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}
Return to Overview

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 }
Example Return {"blocks": 236526, "currentblocksize": 185, "currentblocktx": 1, "difficulty": 256, "errors": "", "generate": false, "genproclimit": -1, "hashespersec": 0, "networkhashps": 33081554756, "pooledtx": 8, "testnet": true }
Return to Overview

Method getnettotals
Parameters None
Description Returns a JSON object containing network traffic statistics.
Returns (json object)
totalbytesrecv: (numeric) total bytes received.
totalbytessent: (numeric) total bytes sent.
timemillis: (numeric) number of milliseconds since 1 Jan 1970 GMT.

{"totalbytesrecv": n, "totalbytessent": n, "timemillis": n }
Example Return {"totalbytesrecv": 1150990, "totalbytessent": 206739, "timemillis": 1391626433845 }
Return to Overview

Method getnetworkhashps
Parameters 1. blocks: (numeric, optional, default=120) The number of blocks, or -1 for blocks since last difficulty change.
2. 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
Return to Overview

Method getpeerinfo
Parameters None
Description Returns data about each connected network peer as an array of json objects.
Returns (json array)
addr: (string) the ip address and port of the peer.
services: (string) the services supported by the peer.
lastrecv: (numeric) time the last message was received in seconds since 1 Jan 1970 GMT.
lastsend: (numeric) time the last message was sent 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.
syncnode: (boolean) whether or not the peer is the sync peer.

[{"addr": "host:port", "services": "00000001", "lastrecv": n, "lastsend": n, "bytessent": n, "bytesrecv": n, "conntime": n, "pingtime": n, "pingwait": n, "version": n, "subver": "useragent", "inbound": true_or_false, "startingheight": n, "currentheight": n, "syncnode": true_or_false }, ...]
Example Return [{"addr": "178.172.xxx.xxx:9108", "services": "00000001", "lastrecv": 1388183523, "lastsend": 1388185470, "bytessent": 287592965, "bytesrecv": 780340, "conntime": 1388182973, "pingtime": 405551, "pingwait": 183023, "version": 70001, "subver": "/dcrd:0.4.0/", "inbound": false, "startingheight": 276921, "currentheight": 276955, "syncnode": true }, ...]
Return to Overview

Method getrawtransaction
Parameters 1. transaction hash: (string, required) the hash of the transaction.
2. 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.
coinbase: (string) the hex-encoded bytes of the signature script.
stakebase: (string) the hash of the stake transaction.
sequence: (numeric) the script sequence number.
txid: (string) the hash of the origin transaction.
vout: (numeric) the index of the output being redeemed from the origin transaction.
scriptSig: (json object) the signature script used to redeem the origin transaction.
asm: (string) disassembly of the script.
sequence: (numeric) the script sequence number.
vout: (array of json objects) the transaction outputs as json objects.
value: (numeric) the value in DCR.
n: (numeric) the index of this transaction output.
scriptPubKey: (json object) the public key script used to pay coins.
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.
decredaddress: (string) the Decred address
blockhash: (string) the hash of the block that contains the transaction.
blockheight: (numeric) the height of the block that contains the transaction.
blockindex: (numeric) the index within the array of transactions contained by the block.
confirmations: (numeric) number of confirmations.
time: (numeric) transaction time in seconds since the epoch.
blocktime: (numeric) block time in seconds since the epoch.

For coinbase transactions
{"hex": "data", "txid": "hash", "version": n, "locktime": n, "expiry": n, vin": [{ "coinbase": "data", "sequence": n}, ...], "vout": [{"value": n, "n": n,"scriptPubKey": { "asm": "asm","hex": "data", "reqSigs": n,"type": "scripttype", "addresses": [ "decredaddress", ...]}}, ...], "blockhash": "hash", "blockheight": n, "confirmations": n, "blocktime": n}

For stakebase transactions
{"hex": "data", "txid": "hash", "version": n, "locktime": n, "expiry": n, "vin": [{ "stakebase": "hash", "sequence": n}, ...], "vout": [{"value": n, "n": n,"scriptPubKey": { "asm": "asm","hex": "data", "reqSigs": n,"type": "scripttype", "addresses": [ "decredaddress", ...]}}, ...], "blockhash": "hash", "blockheight": n, "blockindex": n, "confirmations": n, "time": n, blocktime": n}

For non-coinbase / non-stakebase transactions
{"hex": "data", "txid": "hash", "version": n, "locktime": n, "expiry": n, "vin": [{"txid": "hash","vout": n, "scriptSig": {"asm": "asm", "hex": "data"}, "sequence": n}, ...], "vout": [{"value": n, "n": n,"scriptPubKey": { "asm": "asm","hex": "data", "reqSigs": n,"type": "scripttype", "addresses": [ "decredaddress", ...]}}, ...], "blockhash": "hash", "blockheight": n, "blockindex": n, "confirmations": n, "time": n, "blocktime": n}
Example Return (verbose=0) Newlines added for display purposes. The actual return does not contain newlines.
"010000000104be666c7053ef26c6110597dad1c1e81b5e6be53d17a8b9d0b34772054bac60000000
008c493046022100cb42f8df44eca83dd0a727988dcde9384953e830b1f8004d57485e2ede1b9c8f
022100fbce8d84fcf2839127605818ac6c3e7a1531ebc69277c504599289fb1e9058df0141045a33
76eeb85e494330b03c1791619d53327441002832f4bd618fd9efa9e644d242d5e1145cb9c2f71965
656e276633d4ff1a6db5e7153a0a9042745178ebe0f5ffffffff0280841e00000000001976a91406
f1b6703d3f56427bfcfd372f952d50d04b64bd88ac4dd52700000000001976a9146b63f291c295ee
abd9aee6be193ab2d019e7ea7088ac00000000
Example Return (verbose=1) For coinbase transactions
{"hex": "01000000010000000000000000000000000000000000000000000000000000000000000000f...","txid": "90743aad855880e517270550d2a881627d84db5265142fd1e7fb7add38b08be9","version": 1,"locktime": 0,"vin": [{"coinbase": "03708203062f503253482f04066d605108f800080100000ea2122f6f7a636f696e4065757374726174756d2f","sequence": 0},...], "vout": [{"value": 25.1394,"n": 0, "scriptPubKey": {"asm": "OP_DUP OP_HASH160 ea132286328cfc819457b9dec386c4b5c84faa5c OP_EQUALVERIFY OP_CHECKSIG", "hex": "76a914ea132286328cfc819457b9dec386c4b5c84faa5c88ac", "reqSigs": 1, "type": "pubkeyhash", "addresses": ["1NLg3QJMsMQGM5KEUaEu5ADDmKQSLHwmyh", ...]}}, ...]}

For stakebase transactions
{"hex": "01000000010000000000000000000000000000000000000000000000000000000000000000f...","txid": "90743aad855880e517270550d2a881627d84db5265142fd1e7fb7add38b08be9","version": 1,"locktime": 0,"vin": [{"stakebase": "90743aad855880e517270550d2a881627d84db5265142fd1e7fb7add38b08be9","sequence": 0},...], "vout": [{"value": 25.1394,"n": 0, "scriptPubKey": {"asm": "OP_DUP OP_HASH160 ea132286328cfc819457b9dec386c4b5c84faa5c OP_EQUALVERIFY OP_CHECKSIG", "hex": "76a914ea132286328cfc819457b9dec386c4b5c84faa5c88ac", "reqSigs": 1, "type": "pubkeyhash", "addresses": ["1NLg3QJMsMQGM5KEUaEu5ADDmKQSLHwmyh", ...]}}, ...]}

For non-coinbase / non-stakebase transactions
{"hex": "01000000010000000000000000000000000000000000000000000000000000000000000000f...","txid": "90743aad855880e517270550d2a881627d84db5265142fd1e7fb7add38b08be9","version": 1,"locktime": 0,"vin": [{"txid": "60ac4b057247b3d0b9a8173de56b5e1be8c1d1da970511c626ef53706c66be04","scriptSig": {"asm": "3046022100cb42f8df44eca83dd0a727988dcde9384953e830b1f8004d57485e2ede1b9c8f0...","hex": "493046022100cb42f8df44eca83dd0a727988dcde9384953e830b1f8004d57485e2ede1b9c8..."}, "sequence": 4294967295}, ...], "vout": [{"value": 25.1394,"n": 0, "scriptPubKey": {"asm": "OP_DUP OP_HASH160 ea132286328cfc819457b9dec386c4b5c84faa5c OP_EQUALVERIFY OP_CHECKSIG", "hex": "76a914ea132286328cfc819457b9dec386c4b5c84faa5c88ac", "reqSigs": 1, "type": "pubkeyhash", "addresses": ["1NLg3QJMsMQGM5KEUaEu5ADDmKQSLHwmyh", ...]}}, ...]}
Return to Overview

Method getwork
Parameters 1. data: (string, optional) The hex
Description Returns information about a transaction given its hash.
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
hash1: (string) (DEPRECATED) hex-encoded formatted hash buffer
midstate: (string) (DEPRECATED) hex-encoded precomputed hash state after hashing first half of the data
target: (string) the hex-encoded little-endian hash target

{"data": "hex", "hash1": "hex", "midstate": "hex", "target": "hex"}
Returns (data specified) true or false (boolean)
Example Return (data not specified) {"data": "00000002c39b5d2b7a1e8f7356a1efce26b24bd15d7d906e85341ef9cec99b6a000000006474f...", "hash1": "00000000000000000000000000000000000000000000000000000000000000000000008000000...", "midstate": "ae4a80fc51476e452de855b4e20d5f33418c50fc7cae3b1ecd5badb819b8a584", "target": "0000000000000000000000000000000000000000000000008c96010000000000"}
Example Return (data specified) true
Return to Overview

Method help
Parameters 1. command: (string, optional) the command to get help for
Description Returns a list of all commands or help for a specified command.
When no command parameter is specified, a list of available commands is returned
When command is a valid method, the help text for that method is returned.
Returns string
Example Return getblockcount
Returns a numeric for the number of blocks in the longest block chain.
Return to Overview

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
Return to Overview

Method getrawmempool
Parameters 1. verbose (boolean, optional, default=false)
Description Returns an array of hashes for all of the transactions currently in the memory pool.
The verbose flag specifies that each transaction is returned as a JSON object.
Notes Since dcrd does not perform any mining, the priority related fields startingpriority and currentpriority that are available when the verbose flag is set are always 0.
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) priority when transaction entered the pool.
currentpriority: (numeric) current priority.
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", ...]}, ...}
Example Return (verbose=false) ["3480058a397b6ffcc60f7e3345a61370fded1ca6bef4b58156ed17987f20d4e7","cbfe7c056a358c3a1dbced5a22b06d74b8650055d5195c1c2469e6b63a41514a"]
Example Return (verbose=true) {"1697a19cede08694278f19584e8dcc87945f40c6b59a942dd8906f133ad3f9cc": {"size": 226, "fee" : 0.0001, "time": 1387992789, "height": 276836, "startingpriority": 0, "currentpriority": 0, "depends": ["aa96f672fcc5a1ec6a08a94aa46d6b789799c87bd6542967da25a96b2dee0afb", ...]}
Return to Overview

Method setgenerate
Parameters 1. generate: (boolean, required) set to true to enable generation, false to disable it.
2. 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
Return to Overview

Method sendrawtransaction
Parameters 1. signedhex: (string, required) serialized, hex-encoded signed transaction.
2. 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.
Notes dcrd does not yet implement the allowhighfees parameter, so it has no effect.
Returns "hash" (string) the hash of the transaction
Example Return "1697a19cede08694278f19584e8dcc87945f40c6b59a942dd8906f133ad3f9cc"
Return to Overview

Method submitblock
Parameters 1. data: (string, required) serialized, hex-encoded block.
2. params: (json object, optional, default=nil) this parameter is currently ignored.
Description Attempts to submit a new serialized, hex-encoded block to the network.
Returns Success: Nothing.
Failure: (string) "rejected: reason"
Return to Overview

Method stop
Parameters None
Description Shutdown dcrd.
Returns "dcrd stopping." (string)
Return to Overview

Method validateaddress
Parameters 1. address: (string, required) Decred address.
Description Verify an address is valid.
Returns (json object)
isvalid: (bool) whether or not the address is valid.
address: (string) the Decred address validated.

{"isvalid": true or false,"address": "decredaddress"}
Return to Overview

Method verifychain
Parameters 1. 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).
2. 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
Return to Overview

Method debuglevel
Parameters 1. levelspec: (string) the debug level specification.
Description Dynamically changes the debug logging level.
The levelspec can either a debug level or of the form <subsystem>=<level>,<subsystem2>=<level2>,...
The valid debug levels are trace, debug, info, warn, error, and critical.
The valid subsystems are AMGR, ADXR, BCDB, BMGR, DCRD, CHAN, DISC, PEER, RPCS, SCRP, SRVR, and TXMP.
Additionally, the special keyword show can be used to get a list of the available subsystems.
Returns string
Example Return Done.
Example show Return Supported subsystems [AMGR ADXR BCDB BMGR DCRD CHAN DISC PEER RPCS SCRP SRVR TXMP]
Return to Overview

Method getbestblock
Parameters None
Description Get block height and hash of best block in the main chain.
Returns (json object)
hash: (string) the hex-encoded bytes of the best block hash.
height: (numeric) the block height of the best block.

{"hash": "data", "height": n}
Return to Overview

Method getcurrentnet
Parameters None
Description Get Decred network dcrd is running on.
Returns numeric
Example Return (mainnet) 3652501241
(testnet) 118034699
(testnet2) 1223139429
Return to Overview

Method searchrawtransactions
Parameters 1. address: (string, required) Decred address.
2. verbose: (int, optional, default=true) specifies the transaction is returned as a JSON object instead of hex-encoded string.
3. skip: (int, optional, default=0) the number of leading transactions to leave out of the final response.
4. count: (int, optional, default=100) the maximum number of transactions to return.
5. vinextra: (int, optional, default=0) specify that extra data from previous output will be returned in vin.
Description Returns raw data for transactions involving the passed address. Returned transactions are pulled from both the database, and transactions currently in the mempool. Transactions pulled from the mempool will have the "confirmations" field set to 0. Usage of this RPC requires the optional --addrindex flag to be activated, otherwise all responses will simply return with an error stating the address index has not yet been built up. Similarly, until the address index has caught up with the current best height, all requests will return an error response in order to avoid serving stale data.
Returns (verbose=0) (json array of strings)
serializedtx: (string) hex-encoded bytes of the serialized transaction.
["serializedtx", ... ]
Returns (verbose=1) (array of json objects)
hex: (string) hex-encoded transaction.
txid: (string) the hash of the transaction.
version: (numeric) the transaction version.
locktime: (numeric) the transaction lock time.
expiry: (numeric) the transaction expiry.
vin: (json array) the transaction inputs as json objects.
coinbase: (string) the hex-encoded bytes of the signature script.
stakebase: (string) the hash of the stake transaction.
sequence: (numeric) the script sequence number.
txid: (string) the hash of the origin transaction.
vout: (numeric) the index of the output being redeemed from 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.
prevOut: Data from the origin transaction output with index vout.
addresses: (array of string) previous output addresses.
value: (numeric) previous output value.
sequence: (numeric) the script sequence number.
vout: (array of json objects) the transaction outputs as json objects.
value: (numeric) the value in DCR.
n: (numeric) the index of this transaction output.
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.
address: (string) the Decred address.
blockhash: (string) the hash of the block that contains the transaction.
blockheight: (numeric) the height of the block that contains the transaction.
blockindex: (numeric) the index within the array of transactions contained by the block.
confirmations: (numeric) number of confirmations.
time: (numeric) transaction time in seconds since the epoch.
blocktime: (numeric) block time in seconds since the epoch.

For coinbase transactions
[{"hex": "data", "txid": "hash", "version": n, "locktime": n,"vin": [{"coinbase": "data", "sequence": n},{"txid": "hash", "vout": n, "scriptSig": {"asm": "asm", "hex": "data"}, "prevOut": {"addresses": ["value", ...], "value": n.nnn}, "sequence": n}, ...],"vout": [{ "value": n, "n": n, "scriptPubKey": {"asm": "asm", "hex": "data", "reqSigs": n, "type": "scripttype", "addresses": ["address", ...]}}, ...], "blockhash": "hash", "blockheight": n, confirmations": n, "time": n, "blocktime": n},...]

For stakebase transactions
[{"hex": "data", "txid": "hash", "version": n, "locktime": n,"vin": [{"stakebase": "hash", "sequence": n},{"txid": "hash", "vout": n, "scriptSig": {"asm": "asm", "hex": "data"}, "prevOut": {"addresses": ["value", ...], "value": n.nnn}, "sequence": n}, ...],"vout": [{ "value": n,"n": n, "scriptPubKey": {"asm": "asm", "hex": "data", "reqSigs": n, "type": "scripttype", "addresses": ["address", ...]}}, ...], "blockhash": "hash", "blockheight": n, "blockindex": n, confirmations": n, "time": n, "blocktime": n},...]

For non-coinbase / non-stakebase transactions
[{"hex": "data", "txid": "hash", "version": n, "locktime": n,"vin": [{"txid": "hash", "vout": n, "scriptSig": {"asm": "asm", "hex": "data"}, "prevOut": {"addresses": ["value",...], "value": n.nnn}, "sequence": n}, ...],"vout": [{ "value": n,"n": n, "scriptPubKey": {"asm": "asm", "hex": "data", "reqSigs": n, "type": "scripttype", "addresses": ["address", ...]}}, ...], "blockhash":"hash", "blockheight": n, "blockindex": n, confirmations": n, "time": n, "blocktime": n},...]
Return to Overview

Method node
Parameters 1. command: (string, required) connect to add a peer (defaults to temporary), remove to remove a persistent peer, or disconnect to remove all matching non-persistent peers.
2. peer: (string, required) ip address and port, or ID of the peer to operate on.
3. connection type: (string, optional) perm indicates the peer should be added as a permanent peer, temp indicates a connection should only be attempted once.
Description Attempts to add or remove a peer.
Returns Nothing
Return to Overview

Method generate
Parameters 1. 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", ...]
Return to Overview
Method getstakeversions
Parameters 1. hash: (string, required) The start block hash.
2. 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 },...]},...]}
Return to Overview

6. Websocket Methods (Websocket-specific)

6.1 Method Overview

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.

# Method Description Notifications
1 authenticate 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.
None
2 notifyblocks Send notifications when a block is connected or disconnected from the best chain. blockconnected and blockdisconnected
3 stopnotifyblocks Cancel registered notifications for whenever a block is connected or disconnected from the main (best) chain. None
4 notifyreceived Send notifications when a txout spends to an address. recvtx and redeemingtx
5 stopnotifyreceived Cancel registered notifications for when a txout spends to any of the passed addresses. None
6 notifyspent Send notification when a txout is spent. redeemingtx
7 stopnotifyspent Cancel registered spending notifications for each passed outpoint. None
8 loadtxfilter Load, add to, or reload a websocket client's transaction filter for mempool transactions, new blocks and rescanblocks. relevanttxaccepted
9 rescan Rescan block chain for transactions to addresses and spent transaction outpoints. recvtx, redeemingtx, rescanprogress, and rescanfinished
10 notifynewtransactions Send notifications for all new transactions as they are accepted into the mempool. txaccepted or txacceptedverbose
11 stopnotifynewtransactions Stop sending either a txaccepted or a txacceptedverbose notification when a new transaction is accepted into the mempool. None
12 session Return details regarding a websocket client's current connection. None

6.2 Method Details

Method authenticate
Parameters 1. username: (string, required)
2. 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.
Returns Success: Nothing
Failure: Nothing (websocket disconnected)
Return to Overview

Method notifyblocks
Notifications blockconnected and blockdisconnected
Parameters None
Description Request notifications for whenever a block is connected or disconnected from the main (best) chain.
NOTE: If a client subscribes to both block and transaction (recvtx and redeemingtx) notifications, the blockconnected notification will be sent after all transaction notifications have been sent. This allows clients to know when all relevant transactions for a block have been received.
Returns Nothing
Return to Overview

Method stopnotifyblocks
Notifications None
Parameters None
Description Cancel sending notifications for whenever a block is connected or disconnected from the main (best) chain.
Returns Nothing
Return to Overview

Method notifyreceived
Notifications recvtx and redeemingtx
Parameters 1. Addresses: (JSON array, required)
decredaddress: (string) the Decred address.

["decredaddress", ...]
Description Send a recvtx notification when a transaction added to mempool or appears in a newly-attached block contains a txout pkScript sending to any of the passed addresses. Matching outpoints are automatically registered for redeemingtx notifications.
Returns Nothing
Return to Overview

Method stopnotifyreceived
Notifications None
Parameters 1. Addresses: (JSON array, required)
decredaddress: (string) the Decred address.

["decredaddress", ...]
Description Cancel registered receive notifications for each passed address.
Returns Nothing
Return to Overview

Method notifyspent
Notifications redeemingtx
Parameters 1. Outpoints: (json array, required)
hash: (string) the hex-encoded bytes of the outpoint hash.
index: (numeric) the txout index of the outpoint.

[{"hash":"data", "index":n }, ...]
Description Send a redeemingtx notification when a transaction spending an outpoint appears in mempool (if relayed to this dcrd instance) and when such a transaction first appears in a newly-attached block.
Returns Nothing
Return to Overview

Method stopnotifyspent
Notifications None
Parameters 1. Outpoints: (json array, required)
hash: (string) the hex-encoded bytes of the outpoint hash.
index: (numeric) the txout index of the outpoint.

[{"hash":"data", "index":n }, ...]
Description Cancel registered spending notifications for each passed outpoint.
Returns Nothing
Return to Overview

Method loadtxfilter
Notifications relevanttxaccepted
Parameters 1. Reload: (boolean, required) load a new filter instead of adding data to an existing one.
2. Addresses: (json array, required) array of addresses to add to the transaction filter
3. Outpoints: (JSON array, required) array of outpoints to add to the transaction filter.
Description Load, add to, or reload a websocket client's transaction filter for mempool transactions, new blocks and rescanblocks.
Returns Nothing
Return to Overview

Method rescan
Notifications None
Parameters 1.Blockhashes: (JSON array, required) list of hashes to rescan. Each next block must be a child of the previous.
Description Rescan blocks for transactions matching the loaded transaction filter.
Returns (json array)
hash: (string) hash of the matching block.
transactions: (json array) list of matching transactions, serialized and hex-encoded.
serializedtx: (string) serialized and hex-encoded transaction.

[{"hash": "data", "transactions": [serializedtx,...]}, ...]
Example Return [{"hash": "0000002099417930b2ae09feda10e38b58c0f6bb44b4d60fa33f0e000000000000000000d53...", "transactions": ["493046022100cb42f8df44eca83dd0a727988dcde9384953e830b1f8004d57485e2ede1b9c8...", ...]}, ...]
Return to Overview

Method notifynewtransactions
Notifications txaccepted or txacceptedverbose
Parameters 1. 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
Return to Overview

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.
Returns Nothing
Return to Overview

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}
Return to Overview

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.

# Method Description Request
1 blockconnected Block connected to the main chain. notifyblocks
2 blockdisconnected Block disconnected from the main chain. notifyblocks
3 recvtx Processed a transaction output spending to a wallet address. notifyreceived and rescan
4 redeemingtx Processed a transaction that spends a registered outpoint. notifyspent and rescan
5 txaccepted Received a new transaction after requesting simple notifications of all new transactions accepted into the mempool. notifynewtransactions
6 txacceptedverbose Received a new transaction after requesting verbose notifications of all new transactions accepted into the mempool. notifynewtransactions
7 rescanprogress A rescan operation that is underway has made progress. rescan
8 rescanfinished A rescan operation has completed. rescan

7.2 Notification Details

Method blockconnected
Request notifyblocks
Parameters 1. BlockHash: (string) hex-encoded bytes of the attached block hash.
2. BlockHeight: (numeric) height of the attached block.
3. BlockTime: (numeric) unix time of the attached block.
Description Notifies when a block has been added to the main chain. Notification is sent to all connected clients.
Example Example blockconnected notification for mainnet block 280330 (newlines added for readability):

{"jsonrpc": "1.0", "method": "blockconnected", "params": ["000000000000000004cbdfe387f4df44b914e464ca79838a8ab777b3214dbffd", 280330, 1389636265],"id": null}
Return to Overview

Method blockdisconnected
Request notifyblocks
Parameters 1. BlockHash: (string) hex-encoded bytes of the disconnected block hash.
2. BlockHeight: (numeric) height of the disconnected block.
3. BlockTime: (numeric) unix time of the disconnected block.
Description Notifies when a block has been removed from the main chain. Notification is sent to all connected clients.
Example Example blockdisconnected notification for mainnet block 280330 (newlines added for readability):

{"jsonrpc": "1.0","method": "blockdisconnected", "params":["000000000000000004cbdfe387f4df44b914e464ca79838a8ab777b3214dbffd", 280330,1389636265],"id": null}
Return to Overview

Method recvtx
Request rescan or notifyreceived
Parameters 1. Transaction: (string) full transaction encoded as a hex string.
2. Block details: (object, optional) details about a block and the index of the transaction within a block, if the transaction is mined.
Description Notifies a client when a transaction is processed that contains at least a single output with a pkScript sending to a requested address. If multiple outputs send to requested addresses, a single notification is sent. If a mempool (unmined) transaction is processed, the block details object (second parameter) is excluded.
Example Example recvtx notification for mainnet transaction 61d3696de4c888730cbe06b0ad8ecb6d72d6108e893895aa9bc067bd7eba3fad when processed by mempool (newlines added for readability):

{"jsonrpc": "1.0", "method": "recvtx", "params": ["010000000114d9ff358894c486b4ae11c2a8cf7851b1df64c53d2e511278eff17c22fb737300000000...], "id": null }

The recvtx notification for the same txout, after the transaction was mined into block 276425:

{"jsonrpc": "1.0","method": "recvtx", "params": ["010000000114d9ff358894c486b4ae11c2a8cf7851b1df64c53d2e511278eff17c22fb737300000000...", {"height": 276425, "hash": "000000000000000325474bb799b9e591f965ca4461b72cb7012b808db92bb2fc", "index": 684, "time": 1387737310 }], "id": null }
Return to Overview

Method redeemingtx
Requests notifyspent and rescan
Parameters 1. Transaction: (string) full transaction encoded as a hex string.
2. Block details: (object, optional) details about a block and the index of the transaction within a block, if the transaction is mined.
Description Notifies a client when an registered outpoint is spent by a transaction accepted to mempool and/or mined into a block.
Example Example redeemingtx notification for mainnet outpoint 61d3696de4c888730cbe06b0ad8ecb6d72d6108e893895aa9bc067bd7eba3fad:0 after being spent by transaction 4ad0c16ac973ff675dec1f3e5f1273f1c45be2a63554343f21b70240a1e43ece (newlines added for readability):

{"jsonrpc": "1.0", "method": "redeemingtx", "params": ["0100000003ad3fba7ebd67c09baa9538898e10d6726dcb8eadb006be0c7388c8e46d69d3610000000..."],"id": null}

The redeemingtx notification for the same txout, after the spending transaction was mined into block 279143:

{"jsonrpc": "1.0", "method": "recvtx", "params": ["0100000003ad3fba7ebd67c09baa9538898e10d6726dcb8eadb006be0c7388c8e46d69d3610000000...", {"height": 279143, "hash": "00000000000000017188b968a371bab95aa43522665353b646e41865abae02a4", "index": 6, "time": 1389115004 }], "id": null }
Return to Overview

Method txaccepted
Request notifynewtransactions
Parameters 1. TxId: (string) hex-encoded bytes of the transaction hash.
2. Amount: (numeric) sum of the value of all the transaction outpoints.
Description Notifies when a new transaction has been accepted and the client has requested standard transaction details.
Example Example txaccepted notification for mainnet transaction id 16c54c9d02fe570b9d41b518c0daefae81cc05c69bbe842058e84c6ed5826261 (newlines added for readability):

{"jsonrpc": "1.0", "method": "txaccepted", "params": ["16c54c9d02fe570b9d41b518c0daefae81cc05c69bbe842058e84c6ed5826261", 55838384], "id": null}
Return to Overview

Method txacceptedverbose
Request notifynewtransactions
Parameters 1. RawTx: (json object) the transaction as a json object (see getrawtransaction json object details).
Description Notifies when a new transaction has been accepted and the client has requested verbose transaction details.
Example Example txacceptedverbose notification (newlines added for readability):

For coinbase transactions
{"jsonrpc": "1.0", "method": "txacceptedverbose", "params": [{"hex": "01000000010000000000000000000000000000000000000000000000000000000000000000f...", "txid": "90743aad855880e517270550d2a881627d84db5265142fd1e7fb7add38b08be9", "version": 1, "locktime": 0, "vin": [{"coinbase": "03708203062f503253482f04066d605108f800080100000ea2122f6f7a636f696e4065757374726174756d2f", "sequence": 0}, ...], "vout": [{"value": 25.1394, "n": 0,"scriptPubKey": {"asm": "OP_DUP OP_HASH160 ea132286328cfc819457b9dec386c4b5c84faa5c OP_EQUALVERIFY OP_CHECKSIG", "hex": "76a914ea132286328cfc819457b9dec386c4b5c84faa5c88ac", "reqSigs": 1,"type": "pubkeyhash", "addresses": ["1NLg3QJMsMQGM5KEUaEu5ADDmKQSLHwmyh", ...]}]}], "id": null}

For non-coinbase transactions
{"jsonrpc": "1.0", "method": "txacceptedverbose", "params": [{"hex": "01000000010000000000000000000000000000000000000000000000000000000000000000f...", "txid": "90743aad855880e517270550d2a881627d84db5265142fd1e7fb7add38b08be9", "version": 1, "locktime": 0, "vin": [{"txid": "60ac4b057247b3d0b9a8173de56b5e1be8c1d1da970511c626ef53706c66be04","vout": 0, "scriptSig": {"asm": "3046022100cb42f8df44eca83dd0a727988dcde9384953e830b1f8004d57485e2ede1b9c8f0...", "hex": "493046022100cb42f8df44eca83dd0a727988dcde9384953e830b1f8004d57485e2ede1b9c8..."}, "sequence": 4294967295}, ...], "vout": [{"value": 25.1394, "n": 0,"scriptPubKey": {"asm": "OP_DUP OP_HASH160 ea132286328cfc819457b9dec386c4b5c84faa5c OP_EQUALVERIFY OP_CHECKSIG", "hex": "76a914ea132286328cfc819457b9dec386c4b5c84faa5c88ac", "reqSigs": 1,"type": "pubkeyhash", "addresses": ["1NLg3QJMsMQGM5KEUaEu5ADDmKQSLHwmyh", ...]}]}], "id": null}
Return to Overview

Method rescanprogress
Request rescan
Parameters 1. Hash: (string) hash of the last processed block.
2. Height: (numeric) height of the last processed block.
3. Time: (numeric) UNIX time of the last processed block.
Description Notifies a client with the current progress at periodic intervals when a long-running rescan is underway.
Example {"jsonrpc": "1.0", "method": "rescanprogress", "params": ["0000000000000ea86b49e11843b2ad937ac89ae74a963c7edd36e0147079b89d", 127213, 1306533807], "id": null }
Return to Overview

Method rescanfinished
Request rescan
Parameters 1. Hash: (string) hash of the last rescanned block.
2. Height: (numeric) height of the last rescanned block.
3. Time: (numeric) UNIX time of the last rescanned block.
Description Notifies a client that the rescan has completed and no further notifications will be sent.
Example {"jsonrpc": "1.0", "method": "rescanfinished", "params": ["0000000000000ea86b49e11843b2ad937ac89ae74a963c7edd36e0147079b89d", 127213, 1306533807], "id": null }
Return to Overview

8. Example Code

This section provides example code for interacting with the JSON-RPC API in various languages.

8.1 Go

This section provides examples of using the RPC interface using Go and the rpcclient package.

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 (
	"io/ioutil"
	"log"
	"path/filepath"

	"github.com/decred/dcrd/dcrutil"
	"github.com/decred/dcrd/rpcclient"
)

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 := ioutil.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.
	blockCount, err := client.GetBlockCount()
	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 (
	"io/ioutil"
	"log"
	"path/filepath"
	"time"

	"github.com/decred/dcrd/chaincfg/chainhash"
	"github.com/decred/dcrd/dcrutil"
	"github.com/decred/dcrd/rpcclient"
)

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 := ioutil.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.
	genesisHashStr := "298e5cc3d985bfe7f81dc135f360abe089edd4396b86d2de66b0cef42b21d980"
	blockHash, err := chainhash.NewHashFromStr(genesisHashStr)
	if err != nil {
		log.Fatal(err)
	}
	block, err := client.GetBlockVerbose(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 (
	"io/ioutil"
	"log"
	"path/filepath"
	"time"

	"github.com/decred/dcrd/dcrutil"
	"github.com/decred/dcrd/rpcclient"
)

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 := ioutil.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.
	if err := client.NotifyBlocks(); 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()
}

Example output:

Client shutdown in 10 seconds...
Block connected: 050000008478546af6812f4b3cb2148b5967b2dab78c3438d31821760f000000000000002c5f513f6ed478b90a7fc3525bbd64d16ab9b577c6b01861a1e9438f42e22ad95369522fdb6d393edf7eff3f0b33e93b60361fef1ec678843faae2caec0b782701003406e68c8961050013004aa00000e21668193dcd2d0302000000a21d03002bed00003b125d5a005fd38e00000000f1ea07e25fff20eb000000000000000000000000000000000000000005000000 (0 txs)
Client shutting down...
Client shutdown complete.

8.2. Example node.js Code

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');
})