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.
4
5package main
6
7import (
8	"io/ioutil"
9	"log"
10	"path/filepath"
11	"time"
12
13	"github.com/btcsuite/btcd/rpcclient"
14	"github.com/btcsuite/btcd/wire"
15	"github.com/btcsuite/btcutil"
16)
17
18func main() {
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)
27		},
28		OnFilteredBlockDisconnected: func(height int32, header *wire.BlockHeader) {
29			log.Printf("Block disconnected: %v (%d) %v",
30				header.BlockHash(), height, header.Timestamp)
31		},
32	}
33
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"))
37	if err != nil {
38		log.Fatal(err)
39	}
40	connCfg := &rpcclient.ConnConfig{
41		Host:         "localhost:8334",
42		Endpoint:     "ws",
43		User:         "yourrpcuser",
44		Pass:         "yourrpcpass",
45		Certificates: certs,
46	}
47	client, err := rpcclient.New(connCfg, &ntfnHandlers)
48	if err != nil {
49		log.Fatal(err)
50	}
51
52	// Register for block connect and disconnect notifications.
53	if err := client.NotifyBlocks(); err != nil {
54		log.Fatal(err)
55	}
56	log.Println("NotifyBlocks: Registration Complete")
57
58	// Get the current block count.
59	blockCount, err := client.GetBlockCount()
60	if err != nil {
61		log.Fatal(err)
62	}
63	log.Printf("Block count: %d", blockCount)
64
65	// For this example gracefully shutdown the client after 10 seconds.
66	// Ordinarily when to shutdown the client is highly application
67	// specific.
68	log.Println("Client shutdown in 10 seconds...")
69	time.AfterFunc(time.Second*10, func() {
70		log.Println("Client shutting down...")
71		client.Shutdown()
72		log.Println("Client shutdown complete.")
73	})
74
75	// Wait until the client either shuts down gracefully (or the user
76	// terminates the process with Ctrl+C).
77	client.WaitForShutdown()
78}
79