1 // Copyright (c) 2014-2017 The btcsuite developers
2 // Use of this source code is governed by an ISC
3 // license that can be found in the LICENSE file.
13 "github.com/btcsuite/btcd/rpcclient"
14 "github.com/btcsuite/btcd/wire"
15 "github.com/btcsuite/btcutil"
19 // Only override the handlers for notifications you care about.
20 // Also note most of these handlers will only be called if you register
21 // for notifications. See the documentation of the rpcclient
22 // NotificationHandlers type for more details about each handler.
23 ntfnHandlers := rpcclient.NotificationHandlers{
24 OnFilteredBlockConnected: func(height int32, header *wire.BlockHeader, txns []*btcutil.Tx) {
25 log.Printf("Block connected: %v (%d) %v",
26 header.BlockHash(), height, header.Timestamp)
28 OnFilteredBlockDisconnected: func(height int32, header *wire.BlockHeader) {
29 log.Printf("Block disconnected: %v (%d) %v",
30 header.BlockHash(), height, header.Timestamp)
34 // Connect to local btcd RPC server using websockets.
35 btcdHomeDir := btcutil.AppDataDir("btcd", false)
36 certs, err := ioutil.ReadFile(filepath.Join(btcdHomeDir, "rpc.cert"))
40 connCfg := &rpcclient.ConnConfig{
41 Host: "localhost:8334",
47 client, err := rpcclient.New(connCfg, &ntfnHandlers)
52 // Register for block connect and disconnect notifications.
53 if err := client.NotifyBlocks(); err != nil {
56 log.Println("NotifyBlocks: Registration Complete")
58 // Get the current block count.
59 blockCount, err := client.GetBlockCount()
63 log.Printf("Block count: %d", blockCount)
65 // For this example gracefully shutdown the client after 10 seconds.
66 // Ordinarily when to shutdown the client is highly application
68 log.Println("Client shutdown in 10 seconds...")
69 time.AfterFunc(time.Second*10, func() {
70 log.Println("Client shutting down...")
72 log.Println("Client shutdown complete.")
75 // Wait until the client either shuts down gracefully (or the user
76 // terminates the process with Ctrl+C).
77 client.WaitForShutdown()