-
Notifications
You must be signed in to change notification settings - Fork 0
JSON RPC API
-
Overview
-
Authentication
-
Command-line Utility
-
Methods
4.1. Method Overview
4.2. Method Details
-
Extension Methods
5.1. Method Overview
5.2. Method Details
-
Example Go Applications
6.1 Using getblockcount to Retrieve the Current Block Height
6.2 Using getblock to Retrieve the Genesis Block
The original bitcoind JSON-RPC API documentation is available at https://en.bitcoin.it/wiki/Original_Bitcoin_client/API_Calls_list
### 2. AuthenticationThe following authentication details are needed before establishing a connection to a btcd RPC server:
- rpcuser is the username that the btcd RPC server is configured with
- rpcpass is the password that the btcd RPC server is configured with
-
rpccert is the the PEM-encoded X.509 certificate (public key) that the btcd server is configured with. It is automatically generated by btcd and placed in the btcd home directory (which is typically
%LOCALAPPDATA%\Btcd
on Windows and~/.btcd
on POSIX-like OSes)
NOTE: As mentioned above, btcd is secure by default which means the RPC server is not running unless configured with a rpcuser and rpcpass and uses TLS authentication for all connections. TODO: Insert link to documentation for configuring the RPC server here.
### 3. Command-line Utilitybtcd comes with a separate utility named btcctl
which can be used to issue these RPC commands to btcd 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 bitcoind/bitcoin-qt client.
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 | Description |
---|---|---|
1 | addnode | Attempts to add or remove a peer. |
2 | createrawtransaction | Returns a new transaction spending the provided inputs and sending to the provided addresses. |
3 | decoderawtransaction | Returns a JSON object representing the provided serialized, hex-encoded transaction. |
4 | decodescript | Returns a JSON object with information about the provided hex-encoded script. |
5 | getaddednodeinfo | Not Yet Implemented |
6 | getbestblockhash | Returns the hash of the of the best (most recent) block in the longest block chain. |
7 | getblock | Returns information about a block given its hash. |
8 | getblockcount | Returns the number of blocks in the longest block chain. |
9 | getblockhash | Returns hash of the block in best block chain at the given height. |
10 | getblocktemplate | Not Yet Implemented |
11 | getconnectioncount | Returns the number of active connections to other peers. |
12 | getdifficulty | Returns the proof-of-work difficulty as a multiple of the minimum difficulty. |
13 | getgenerate | Return if the server is set to generate coins (mine) or not. NOTE: btcd does NOT mine, so this will always return false. It is only provided for compatibility. |
14 | gethashespersec | Returns a recent hashes per second performance measurement while generating coins (mining). NOTE: btcd does NOT mine, so this will always return 0. It is only provided for compatibility. |
15 | getpeerinfo | Returns information about each connected network peer as an array of json objects. NOTE: btcd does NOT yet implement all fields. |
16 | getrawmempool | Returns an array of hashes for all of the transactions currently in the memory pool. |
17 | getrawtransaction | Returns information about a transaction given its hash. |
18 | getwork | Not Yet Implemented |
19 | help | Not Yet Implemented |
20 | ping | Not Yet Implemented |
21 | sendrawtransaction | Submits the serialized, hex-encoded transaction to the local peer and relays it to the network. btcd does not yet implement the allowhighfees parameter, so it has no effect
|
22 | setgenerate | Set the server to generate coins (mine) or not. NOTE: btcd does NOT mine, so this call has no effect. It is only provided for compatibility. |
23 | stop | Shutdown btcd. |
24 | submitblock | Not Yet Implemented |
25 | verifychain | Verifies the block chain database. |
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 peer, or onetry to try a single connection to a peer |
Description | Attempts to add or remove a peer. |
Returns | Nothing |
Return to Method Overview |
Method | createrawtransaction |
Parameters | 1. transaction inputs (string, required) - json array of json objects[ { "txid": "hash", (string, required) the hash of the input transaction "vout": n (numeric, required) the specific output of the input transaction to redeem }, ... ] 2. addresses and amounts (string, required) - json object with addresses as keys and amounts as values { "address": n.nnn (numeric, required) the address to send to as the key and the amount in BTC as the value , ... }
|
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 [{"txid":"e6da89de7a6b8508ce8f371a3d0535b04b5e108cb1a6e9284602d3bfd357c018","vout":1}] 2. addresses and amounts {"13cgrTP7wgbZYWrY9BZ22BV6p82QXQT3nY": 0.49213337}
|
Example Return |
010000000118c057d3bfd3024628e9a6b18c105e4bb035053d1a378fce08856b7ade89dae6010000 0000ffffffff0199efee02000000001976a9141cb013db35ecccc156fdfd81d03a11c51998f99388 ac00000000 Newlines added for display purposes. The actual return does not contain newlines. |
Return to Method 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": "hash", (string) the hash of the transaction "version": n, (numeric) the transaction version "locktime": n, (numeric) the transaction lock time "vin": [ (array of json objects) the transaction inputs as json objects For coinbase transactions: { (json object) "coinbase": "data", (string) the hex-dencoded bytes of the signature script "sequence": n, (numeric) the script sequence number } For non-coinbase transactions: { (json object) "txid": "hash", (string) the hash of the origin transaction "vout": n, (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": "asm", (string) disassembly of the script "hex": "data", (string) hex-encoded bytes of the script } "sequence": n, (numeric) the script sequence number }, ... ] "vout": [ (array of json objects) the transaction outputs as json objects { (json object) "value": n, (numeric) the value in BTC "n": n, (numeric) the index of this transaction output "scriptPubKey": { (json object) the public key script used to pay coins "asm": "asm", (string) disassembly of the script "hex": "data", (string) hex-encoded bytes of the script "reqSigs": n, (numeric) the number of required signatures "type": "scripttype" (string) the type of the script (e.g. 'pubkeyhash') "addresses": [ (json array of string) the bitcoin addresses associated with this output "bitcoinaddress", (string) the bitcoin address ... ] } }, ... ] }
|
Example Return |
{ "txid": "4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b", "version": 1, "locktime": 0, "vin": [ For coinbase transactions: { (json object) "coinbase": "04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6...", "sequence": 4294967295, } For non-coinbase transactions: { "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 Method 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": "asm", (string) disassembly of the script "reqSigs": n, (numeric) the number of required signatures "type": "scripttype", (string) the type of the script (e.g. 'pubkeyhash') "addresses": [ (json array of string) the bitcoin addresses associated with this script "bitcoinaddress", (string) the bitcoin address ... ] "p2sh": "scripthash", (string) the script hash for use in pay-to-script-hash transactions }
|
Example Return |
{ "asm": "OP_DUP OP_HASH160 b0a4d8a91981106e4ed85165a66748b19f7b7ad4 OP_EQUALVERIFY OP_CHECKSIG", "reqSigs": 1, "type": "pubkeyhash", "addresses": [ "1H71QVBpzuLTNUh5pewaH3UTLTo2vWgcRJ" ] "p2sh": "359b84ff799f48231990ff0298206f54117b08b6" }
|
Return to Method 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 Method 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.This parameter is a btcd extension
|
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": "blockhash", (string) the hash of the block (same as provided) "confirmations": n, (numeric) the number of confirmations "size": n, (numeric) the size of the block "height": n, (numeric) the height of the block in the block chain "version": n, (numeric) the block version "merkleroot": "hash", (string) root hash of the merkle tree "tx": [ (json array of string) the transaction hashes "transactionhash", (string) hash of the parent transaction ... ] "time": n, (numeric) the block time in seconds since 1 Jan 1970 GMT "nonce": n, (numeric) the block nonce "bits", n, (numeric) the bits which represent the block difficulty difficulty: n.nn, (numeric) the proof-of-work difficulty as a multiple of the minimum difficulty "previousblockhash": "hash", (string) the hash of the previous block "nextblockhash": "hash", (string) the hash of the next block }
|
Returns (verbose=true, verbosetx=true) |
{ (json object) "hash": "blockhash", (string) the hash of the block (same as provided) "confirmations": n, (numeric) the number of confirmations "size": n, (numeric) the size of the block "height": n, (numeric) the height of the block in the block chain "version": n, (numeric) the block version "merkleroot": "hash", (string) root hash of the merkle tree "rawtx": [ (array of json objects) the transactions as json objects (see getrawtransaction json object details) ] "time": n, (numeric) the block time in seconds since 1 Jan 1970 GMT "nonce": n, (numeric) the block nonce "bits", n, (numeric) the bits which represent the block difficulty difficulty: n.nn, (numeric) the proof-of-work difficulty as a multiple of the minimum difficulty "previousblockhash": "hash", (string) the hash of the previous block "nextblockhash": "hash", (string) the hash of the next block }
|
Example Return (verbose=false) |
"010000000000000000000000000000000000000000000000000000000000000000000000 3ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a29ab5f49 ffff001d1dac2b7c01010000000100000000000000000000000000000000000000000000 00000000000000000000ffffffff4d04ffff001d0104455468652054696d65732030332f 4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f 6e64206261696c6f757420666f722062616e6b73ffffffff0100f2052a01000000434104 678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f 4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5fac00000000" Newlines added for display purposes. The actual return does not contain newlines. |
Example Return (verbose=true, verbosetx=false) |
{ "hash": "000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f", "confirmations": 277113, "size": 285, "height": 0, "version": 1, "merkleroot": "4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b", "tx": [ "4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b" ], "time": 1231006505, "nonce": 2083236893, "bits": "1d00ffff", "difficulty": 1, "previousblockhash": "0000000000000000000000000000000000000000000000000000000000000000", "nextblockhash": "00000000839a8e6886ab5951d76f411475428afc90947ee320161bbf18eb6048" }
|
Return to Method Overview |
Method | getblockcount |
Parameters | None |
Description | Returns the number of blocks in the longest block chain. |
Returns | numeric |
Example Return | 276820 |
Return to Method 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 Method Overview |
Method | getconnectioncount |
Parameters | None |
Description | Returns the number of active connections to other peers |
Returns | numeric |
Example Return | 8 |
Return to Method 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 Method Overview |
Method | getgenerate |
Parameters | None |
Description | Return if the server is set to generate coins (mine) or not. |
Notes | NOTE: btcd does NOT mine, so this will always return false. It is only provided for compatibility. |
Returns |
false (boolean) |
Return to Method Overview |
Method | gethashespersec |
Parameters | None |
Description | Returns a recent hashes per second performance measurement while generating coins (mining). |
Notes | NOTE: btcd does NOT mine, so this will always return 0. It is only provided for compatibility. |
Returns |
0 (numeric) |
Return to Method Overview |
Method | getpeerinfo |
Parameters | None |
Description | Returns data about each connected network peer as an array of json objects. |
Notes | NOTE: btcd does NOT yet implement all fields. The fields marked with NYI are not yet implemented. |
Returns |
[ { "addr": "host:port", (string) the ip address and port of the peer "services": "00000001", (string) the services supported by the peer "lastrecv": n, (numeric) time the last message was received in seconds since 1 Jan 1970 GMT "lastsend": n, (numeric) time the last message was sent in seconds since 1 Jan 1970 GMT "bytessent": n, (numeric) total bytes sent NYI"bytesrecv": n, (numeric) total bytes received NYI"conntime": n, (numeric) time the connection was made in seconds since 1 Jan 1970 GMT "version": n, (numeric) the protocol version of the peer "subver": "useragent", (string) the user agent of the peer "inbound": true_or_false, (boolean) whether or not the peer is an inbound connection "startingheight": n, (numeric) the latest block height the peer knew about when the connection was established "syncnode": true_or_false, (boolean) whether or not the peer is the sync peer NYI}, ... ]
|
Example Return |
[ { "addr": "178.172.xxx.xxx:8333", "services": "00000001", "lastrecv": 1388183523, "lastsend": 1388185470, "bytessent": 287592965, "bytesrecv": 780340, "conntime": 1388182973, "version": 70001, "subver": "/btcd:0.4.0/", "inbound": false, "startingheight": 276921, "syncnode": false, } ]
|
Return to Method Overview |
Method | getrawtransaction |
Parameters | 1. transaction hash (string, required) - the hash of the transaciton 2. verbose (boolean, optional, default=false) - 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=false) | "data" (string) hex-encoded bytes of the serialized block |
Returns (verbose=true) |
{ (json object) "hex": "data", (string) hex-encoded transaction "txid": "hash", (string) the hash of the transaction "version": n, (numeric) the transaction version "locktime": n, (numeric) the transaction lock time "vin": [ (array of json objects) the transaction inputs as json objects For coinbase transactions: { (json object) "coinbase": "data", (string) the hex-dencoded bytes of the signature script "sequence": n, (numeric) the script sequence number } For non-coinbase transactions: { (json object) "txid": "hash", (string) the hash of the origin transaction "vout": n, (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": "asm", (string) disassembly of the script "hex": "data", (string) hex-encoded bytes of the script } "sequence": n, (numeric) the script sequence number }, ... ] "vout": [ (array of json objects) the transaction outputs as json objects { (json object) "value": n, (numeric) the value in BTC "n": n, (numeric) the index of this transaction output "scriptPubKey": { (json object) the public key script used to pay coins "asm": "asm", (string) disassembly of the script "hex": "data", (string) hex-encoded bytes of the script "reqSigs": n, (numeric) the number of required signatures "type": "scripttype" (string) the type of the script (e.g. 'pubkeyhash') "addresses": [ (json array of string) the bitcoin addresses associated with this output "bitcoinaddress", (string) the bitcoin address ... ] } }, ... ] }
|
Example Return (verbose=false) |
"010000000104be666c7053ef26c6110597dad1c1e81b5e6be53d17a8b9d0b34772054bac60000000 008c493046022100cb42f8df44eca83dd0a727988dcde9384953e830b1f8004d57485e2ede1b9c8f 022100fbce8d84fcf2839127605818ac6c3e7a1531ebc69277c504599289fb1e9058df0141045a33 76eeb85e494330b03c1791619d53327441002832f4bd618fd9efa9e644d242d5e1145cb9c2f71965 656e276633d4ff1a6db5e7153a0a9042745178ebe0f5ffffffff0280841e00000000001976a91406 f1b6703d3f56427bfcfd372f952d50d04b64bd88ac4dd52700000000001976a9146b63f291c295ee abd9aee6be193ab2d019e7ea7088ac00000000 Newlines added for display purposes. The actual return does not contain newlines. |
Example Return (verbose=true) |
{ "hex": "01000000010000000000000000000000000000000000000000000000000000000000000000f...", "txid": "90743aad855880e517270550d2a881627d84db5265142fd1e7fb7add38b08be9", "version": 1, "locktime": 0, "vin": [ For coinbase transactions: { (json object) "coinbase": "03708203062f503253482f04066d605108f800080100000ea2122f6f7a636f696e4065757374726174756d2f", "sequence": 0, } For non-coinbase transactions: { "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", ] } } ] }
|
Return to Method 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 btcd 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 ... ]
|
Returns (verbose=true) |
{ (json object) "transactionhash": { (json object) "size": n, (numeric) transaction size in bytes "fee" : n, (numeric) transaction fee in bitcoins "time": n, (numeric) local time transaction entered pool in seconds since 1 Jan 1970 GMT "height": n, (numeric) block height when transaction entered the pool "startingpriority": n, (numeric) priority when transaction entered the pool "currentpriority": n, (numeric) current priority "depends": [ (json array) unconfirmed transactions used as inputs for this transaction "transactionhash", (string) hash of the parent transaction ... ] }, ... }
|
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 Method Overview |
Method | setgenerate |
Parameters | 1. generate (boolean, required) - true to enable generation, false to disable it2. genproclimit (numeric, optional) - the number of processors (cores) to limit generation to or -1 for unlimited |
Description | Set the server to generate coins (mine) or not. |
Notes | NOTE: btcd does NOT mine, so this call has no effect. It is only provided for compatibility. |
Returns | Nothing |
Return to Method 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 | btcd 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 Method Overview |
Method | stop |
Parameters | None |
Description | Shutdown btcd. |
Returns |
"btcd stopping." (string) |
Return to Method 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 btcd 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 | Btcd 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 btcd. |
Returns |
true or false (boolean) |
Example Return | true |
Return to Method Overview |
The following is an overview of the RPC methods which are implemented by btcd, but not the original bitcoind client. Click the method name for further details such as parameter and return information.
# | Method | Description |
---|---|---|
1 | debuglevel | Dynamically changes the debug logging level. |
Method | debuglevel |
Parameters | 1. levelspec (string) |
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 , BCDB , BMGR , BTCD , 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 BCDB BMGR BTCD CHAN DISC PEER RPCS SCRP SRVR TXMP] |
Return to Method Overview |
The following section provides examples of using the RPC interface using Go and btcjson.
### 6.1 Using getblockcount to Retrieve the Current Block HeightThe following is an example Go application which uses btcjson to connect with a btcd instance, issues getblockcount to retrieve the current block height, and displays it.
package main
import (
"github.com/conformal/btcjson"
"io/ioutil"
"log"
"fmt"
)
func main() {
// Load the certificate for the TLS connection which is automatically
// generated by btcd when it starts the RPC server and doesn't already
// have one.
certFile, err := ioutil.ReadFile("/path/to/btcd/appdata/rpc.cert")
if err != nil {
log.Fatal(err)
}
// Create a new "getblockcount" command and marshal it into a JSON
// byte slice so it can be sent to the RPC server.
getBlockCountCmd, err := btcjson.NewGetBlockCountCmd(1)
if err != nil {
log.Fatal(err)
}
msg, err := getBlockCountCmd.MarshalJSON()
if err != nil {
log.Fatal(err)
}
// NOTE: Any error here is related to sending the command. The
// reply.Error below is a potential error response from the server such
// as "Block number out of range".
user := "yourusername"
password := "yourpassword"
server := "127.0.0.1:8334"
reply, err := btcjson.TlsRpcCommand(user, password, server, msg, certFile, false)
if err != nil {
log.Fatal(err)
}
if reply.Error != nil {
log.Fatal(reply.Error)
}
fmt.Println(reply.Result)
}
Which results in:
276978
The following is an example Go application which uses btcjson to connect with a btcd instance, issues getblock to retrieve information about the Genesis block, and display a few details about it.
package main
import (
"fmt"
"github.com/conformal/btcjson"
"io/ioutil"
"log"
"time"
)
func main() {
// Load the certificate for the TLS connection which is automatically
// generated by btcd when it starts the RPC server and doesn't already
// have one.
certFile, err := ioutil.ReadFile("/path/to/btcd/appdata/rpc.cert")
if err != nil {
log.Fatal(err)
}
// Create a new "getblock" command for the genesis block and marshal it
// into JSON so it can be sent to the RPC server.
blockHash := "000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f"
getBlockCmd, err := btcjson.NewGetBlockCmd(1, blockHash, true)
if err != nil {
log.Fatal(err)
}
msg, err := getBlockCmd.MarshalJSON()
if err != nil {
log.Fatal(err)
}
// NOTE: Any error here is related to sending the command. The
// reply.Error below is a potential error response from the server such
// as "Block not found".
user := "yourusername"
password := "yourpassword"
server := "127.0.0.1:8334"
reply, err := btcjson.TlsRpcCommand(user, password, server, msg, certFile, false)
if err != nil {
log.Fatal(err)
}
if reply.Error != nil {
log.Fatal(reply.Error)
}
// Since the original command above set verbose to true, a JSON object
// representing the block was returned. btcjson already unmarshalled
// the JSON object into a btcjson.BlockResult for us, so we can simply
// type assert it and have access to a full fledged type with properly
// typed fields.
//
// When verbose is set to false in the getblock command, a hex-encoded
// string of the serialized block is returned instead. This code simply
// uses a type switch to select the appropriate result type and acts
// accordingly. To see the string case in action, change the "true"
// to "false" in the btcjson.NewGetBlockCmd call above.
switch result := reply.Result.(type) {
case btcjson.BlockResult:
fmt.Printf("Hash: %v\n", result.Hash)
fmt.Printf("Previous Block: %v\n", result.PreviousHash)
fmt.Printf("Next Block: %v\n", result.NextHash)
fmt.Printf("Merkle root: %v\n", result.MerkleRoot)
fmt.Printf("Timestamp: %v\n", time.Unix(result.Time, 0).UTC())
fmt.Printf("Confirmations: %v\n", result.Confirmations)
fmt.Printf("Difficulty: %f\n", result.Difficulty)
fmt.Printf("Size (in bytes): %v\n", result.Size)
fmt.Printf("Num transactions: %v\n", len(result.Tx))
case string:
fmt.Println(result)
default:
log.Fatalf("Unexpected type returned - %T", result)
}
}
Which results in:
Hash: 000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f
Previous Block: 0000000000000000000000000000000000000000000000000000000000000000
Next Block: 00000000839a8e6886ab5951d76f411475428afc90947ee320161bbf18eb6048
Merkle root: 4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b
Timestamp: 2009-01-03 18:15:05 +0000 UTC
Confirmations: 277290
Difficulty: 1.000000
Size (in bytes): 285
Num transactions: 1