-
Notifications
You must be signed in to change notification settings - Fork 0
Websocket JSON RPC API
-
Overview
-
Extension Requests
2.1. Extension Request Overview
2.2. Extension Request Details
-
Notifications
3.1. Notification Overview
3.2. Notification Details
-
Example Go Applications
4.1. Rescan and blockconnected
btcd websocket RPC, like legacy RPC, is performed using requests and responses following the JSON-RPC specification. All implemented legacy RPC requests are also available for use by websocket connections, with the only difference being that all requests and responses are sent asynchronously. Please reference the [JSON-RPC API](JSON RPC API) for documentation on btcd legacy command support.
In addition to the legacy 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 legacy API during the development of btcwallet.
The extension API should be considered a work in progress, incomplete, and susceptible to changes (both additions and removals).
### 2. Extension Requests **2.1 Extension Request Overview**The following is an overview of the RPC extension requests available to websocket connections. Click the method name for further details such as parameter and return information.
| # | Method | Description |
|---|---|---|
| 1 | getbestblock | Get block height and hash of best block in the main chain. |
| 2 | getcurrentnet | Get bitcoin network btcd is running on. |
| 3 | notifynewtxs | Send notifications when a txout spends to an address. |
| 4 | notifyspent | Send notification when a txout is spent. |
| 5 | rescan | Rescan blockchain for transactions to addresses. |
| Method | getbestblock |
| Parameters | None |
| Description | Get block height and hash of best block in the main chain. |
| Returns |
{ (json object)"hash": "data", (string) the hex-encoded bytes of the best block hash"height": n (numeric) the block height of the best block}
|
|
Return to Request Overview |
| Method | getcurrentnet |
| Parameters | None |
| Description | Get bitcoin network btcd is running on. |
| Returns | numeric |
| Example Return |
3652501241 (mainnet)118034699 (testnet3) |
|
Return to Request Overview |
| Method | notifynewtxs |
| Parameters | 1. Addresses (JSON array, required)[ (json array of strings)"bitcoinaddress", (string) the bitcoin address...]
|
| Description | Send a processedtx notification when a mempool or attached block transaction's txout spends to any number of addresses. |
| Returns | Nothing |
|
Return to Request Overview |
| Method | notifyspent |
| Parameters | 1. Txid (string, required) the hex-encoded bytes of the outpoint transaction hash 2. Index (numeric, required) the txout index of the outpoint |
| Description | Send a txspent notification when a block is attached with a transaction that spends a given outpoint. |
| Returns | Nothing |
|
Return to Request Overview |
| Method | rescan |
| Parameters | 1. BeginBlock (numeric, required) block height to begin rescanning from 2. Addresses (JSON object, required) { (JSON object)"bitcoinaddress": null,...}3. EndBlock (numeric, option) height of final block to rescan |
| Description | Rescan blockchain for transactions to addresses, starting at block height BeginBlock and ending at height EndBlock. If EndBlock is omitted, the rescan continues through the best block in the main chain. Rescan results are sent as processedtx notifications. This call returns once the rescan completes. |
| Returns | Nothing |
|
Return to Request Overview |
btcd uses standard JSON-RPC notifications to notify clients of changes, rather than requiring clients to poll btcd 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.
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 |
|---|---|---|
| 1 | blockconnected | Block connected to the main chain. |
| 2 | blockdisconnected | Block disconnected from the main chain. |
| 3 | processedtx | Processed a transaction output spending to a wallet address. |
| 4 | txmined | Processed a block containing a transaction sent from a wallet. |
| 5 | txspent | Processed a block containing a transaction that spends a requested outpoint. |
| Method | blockconnected |
| Parameters | 1. BlockHash (string) hex-encoded bytes of the attached block hash 2. BlockHeight (numeric) height 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],"id": null}
|
|
Return to Notification Overview |
| Method | blockdisconnected |
| Parameters | 1. BlockHash (string) hex-encoded bytes of the disconnected block hash 2. BlockHeight (numeric) height 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],"id": null}
|
|
Return to Notification Overview |
| Method | processedtx |
| Parameters | 1. Receiver (string) address the txout spends to 2. Amount (numeric) amount spent by the txout, calculated in satoshis 3. TxID (string) hex-encoded bytes of the transaction hash 4. TxOutIndex (numeric) index of the transaction output 5. PkScript (string) hex-encoded bytes of the txout's pubkey script 6. BlockHash (string) hex-encoded bytes of the block hash this transaction output appears in 7. BlockHeight (numeric) block height of block this transaction output appears in 8. BlockIndex (numeric) transaction index for block this transaction output appears in 9. BlockTime (numeric) unix time of block this transaction output appears in 10. Spent (boolean) whether this transaction output is currently spent by another validated transaction |
| Description | Notifies a client when a transaction is processed that outputs to a requested address. One processedtx notification is sent per transaction output. If a transaction is processed without belonging in a block (for example, accepting a transaction to the btcd mempool) all Block* parameters will be set to their zero values, except for BlockHeight which is set to -1. |
| Example | Example processedtx notification for mainnet transaction 61d3696de4c888730cbe06b0ad8ecb6d72d6108e893895aa9bc067bd7eba3fad when processed by mempool (newlines added for readability):{"jsonrpc": "1.0","method": "processedtx","params":["17XhEvq9Nahdj7Xe1nv6oRe1tEmaHUuynH",10000000,"61d3696de4c888730cbe06b0ad8ecb6d72d6108e893895aa9bc067bd7eba3fad",0,"76a914479ed307831d0ac19ebc5f63de7d5f1a430ddb9d88ac","",-1,0,0,false],"id": null}The processedtx notification for the same txout, after the transaction was mined into block 276425: {"jsonrpc": "1.0","method": "processedtx","params":["17XhEvq9Nahdj7Xe1nv6oRe1tEmaHUuynH",10000000,"61d3696de4c888730cbe06b0ad8ecb6d72d6108e893895aa9bc067bd7eba3fad",0,"76a914479ed307831d0ac19ebc5f63de7d5f1a430ddb9d88ac","000000000000000325474bb799b9e591f965ca4461b72cb7012b808db92bb2fc",276425,684,1387737310,false],"id": null}
|
|
Return to Notification Overview |
| Method | txmined |
| Parameters | 1. TxID (string) hex-encoded bytes of the transaction hash 2. BlockHash (string) hex-encoded bytes of the block hash this transaction appears in 3. BlockHeight (numeric) block height of block this transaction appears in 4. BlockTime (numeric) unix time of block this transaction appears in 5. Index (numeric) transaction index for block this transaction appears in |
| Description | Notifies a client after a transaction sent with the sendrawtransaction standard RPC request is mined into a block and attached to the main chain. |
| Example | Example txmined notification for mainnet transaction 61d3696de4c888730cbe06b0ad8ecb6d72d6108e893895aa9bc067bd7eba3fad after being mined into block 276425 (newlines added for readability):{"jsonrpc": "1.0","method": "txmined","params":["61d3696de4c888730cbe06b0ad8ecb6d72d6108e893895aa9bc067bd7eba3fad","000000000000000325474bb799b9e591f965ca4461b72cb7012b808db92bb2fc",276425,1387737310,684],"id": null}
|
|
Return to Notification Overview |
| Method | txspent |
| Parameters | 1. TxID (string) hex-encoded bytes of the transaction hash of the spent outpoint 2. TxOutIndex (numeric) transaction output index of the spent outpoint. 3. SpendingTx (string) hex-encoded bytes of the txid of the transaction spending this outpoint |
| Description | Notifies a client when an outpoint requested with a notifyspent request is spent by a transaction appearing in a block connected to the main chain. |
| Example | Example txspent notification for mainnet outpoint 61d3696de4c888730cbe06b0ad8ecb6d72d6108e893895aa9bc067bd7eba3fad:0 after being spent by transaction 4ad0c16ac973ff675dec1f3e5f1273f1c45be2a63554343f21b70240a1e43ece (newlines added for readability):{"jsonrpc": "1.0","method": "txspent","params":["61d3696de4c888730cbe06b0ad8ecb6d72d6108e893895aa9bc067bd7eba3fad",0,"4ad0c16ac973ff675dec1f3e5f1273f1c45be2a63554343f21b70240a1e43ece"],"id": null}
|
|
Return to Notification Overview |
The following Go application shows how to open a btcd websocket connection and send/receive messages to/from btcd. A rescan request is created for a single address, and notification handlers are set up for the processedtx (sent as a rescan result) and blockconnected notification.
package main
import (
"code.google.com/p/go.net/websocket"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"fmt"
"github.com/conformal/btcjson"
"github.com/conformal/btcws"
"io/ioutil"
"log"
)
func main() {
// Read certificates for TLS connection.
certs, err := ioutil.ReadFile("/path/to/btcd/appdata/rpc.cert")
if err != nil {
log.Fatal(err)
}
// Open websocket connection to mainnet btcd.
ws, err := BtcdWS("localhost:8334", certs, "user", "pass")
if err != nil {
log.Fatal(err)
}
// Receive replies/notifications from btcd and send across
// a channel to handle from another goroutine.
marshaledReplies := make(chan []byte)
go func() {
var b []byte
err := websocket.Message.Receive(ws, &b)
if err != nil {
log.Fatalf("cannot receive btcd message: %v", err)
}
marshaledReplies <- b
}()
// Send commands received from a channel to btcd.
sendCmd := make(chan btcjson.Cmd)
go func() {
for cmd := range sendCmd {
mcmd, err := cmd.MarshalJSON()
if err != nil {
log.Printf("cannot marshal request: %v", err)
continue
}
err = websocket.Message.Send(ws, mcmd)
if err != nil {
log.Printf("cannot send request: %v", err)
continue
}
log.Printf("sent %v request with id %v\n", cmd.Method(), cmd.Id())
}
}()
// Marshal and send a rescan request (starting at block height 276000)
// for a single address.
addrs := map[string]struct{}{
"17XhEvq9Nahdj7Xe1nv6oRe1tEmaHUuynH": struct{}{},
}
rescanCmd, err := btcws.NewRescanCmd(0, 276000, addrs)
if err == nil {
sendCmd <- rescanCmd
}
// Wait for and handle btcd notifications.
for {
reply := <-marshaledReplies
// Try unmarshaling as a notification. btcjson.Cmds
// with no IDs are notifications.
if n, err := btcjson.ParseMarshaledCmd(reply); err == nil {
if n.Id() != nil {
log.Printf("received a request")
continue
}
switch cn := n.(type) {
case *btcws.BlockConnectedNtfn:
log.Printf("block %v connected at height %v", cn.Hash, cn.Height)
case *btcws.ProcessedTxNtfn: // from a rescan request
log.Printf("rescanned block %v includes outpoint %v:%v to %v",
cn.BlockHash, cn.TxID, cn.TxOutIndex, cn.Receiver)
}
}
// Should be a response. Real code would unmashal as one,
// check the id, and pass to a handler specific for the
// expected result.
}
}
// BtcdWS opens a websocket connection to a btcd instance.
func BtcdWS(connect string, certificates []byte, user, pass string) (*websocket.Conn, error) {
url := fmt.Sprintf("wss://%s/wallet", connect)
config, err := websocket.NewConfig(url, "https://localhost/")
if err != nil {
return nil, err
}
// btcd uses a self-signed TLS certifiate which is used as the CA.
pool := x509.NewCertPool()
pool.AppendCertsFromPEM(certificates)
config.TlsConfig = &tls.Config{
RootCAs: pool,
MinVersion: tls.VersionTLS12,
}
// btcd requires basic authorization, so set the Authorization header.
login := user + ":" + pass
auth := "Basic " + base64.StdEncoding.EncodeToString([]byte(login))
config.Header.Add("Authorization", auth)
// Dial connection.
return websocket.DialConfig(config)
}Example output:
2014/01/13 17:02:16 sent rescan request with id 0
2014/01/13 17:02:17 rescanned block 0000000000000002ef165b60dc2b602e173d53a185660eeee28ef09c227e97c1 includes outpoint 61d3696de4c888730cbe06b0ad8ecb6d72d6108e893895aa9bc067bd7eba3fad:0 to 17XhEvq9Nahdj7Xe1nv6oRe1tEmaHUuynH
2014/01/13 17:03:00 block 0000000000000000b876330236b9f27ad6676f93756ddb59a028e2b84ae2991a connected at height 280358