1 package main
2 3 import (
4 "fmt"
5 "io/ioutil"
6 "log"
7 "path/filepath"
8 "time"
9 10 "github.com/p9c/p9/pkg/qu"
11 12 "github.com/p9c/p9/pkg/appdata"
13 "github.com/p9c/p9/pkg/rpcclient"
14 "github.com/p9c/p9/pkg/util"
15 "github.com/p9c/p9/pkg/wire"
16 )
17 18 func main() {
19 // Only override the handlers for notifications you care about. Also note most of these handlers will only be called
20 // if you register for notifications. See the documentation of the rpcclient NotificationHandlers type for more
21 // details about each handler.
22 ntfnHandlers := rpcclient.NotificationHandlers{
23 OnFilteredBlockConnected: func(height int32, header *wire.BlockHeader, txns []*util.Tx) {
24 log.Printf(
25 "Block connected: %v (%d) %v",
26 header.BlockHash(), height, header.Timestamp,
27 )
28 },
29 OnFilteredBlockDisconnected: func(height int32, header *wire.BlockHeader) {
30 log.Printf(
31 "Block disconnected: %v (%d) %v",
32 header.BlockHash(), height, header.Timestamp,
33 )
34 },
35 }
36 // Connect to local pod RPC server using websockets.
37 podHomeDir := appdata.Dir("pod", false)
38 var certs []byte
39 var e error
40 certs, e = ioutil.ReadFile(filepath.Join(podHomeDir, "rpc.cert"))
41 if e != nil {
42 F.Ln(e)
43 }
44 connCfg := &rpcclient.ConnConfig{
45 Host: "localhost:11048",
46 Endpoint: "ws",
47 User: "yourrpcuser",
48 Pass: "yourrpcpass",
49 Certificates: certs,
50 }
51 var client *rpcclient.Client
52 client, e = rpcclient.New(connCfg, &ntfnHandlers, qu.T())
53 if e != nil {
54 F.Ln(e)
55 }
56 // Register for block connect and disconnect notifications.
57 if e = client.NotifyBlocks(); E.Chk(e) {
58 F.Ln(e)
59 }
60 fmt.Println("NotifyBlocks: Registration Complete")
61 // Get the current block count.
62 blockCount, e := client.GetBlockCount()
63 if e != nil {
64 F.Ln(e)
65 }
66 log.Printf("Block count: %d", blockCount)
67 // For this example gracefully shutdown the client after 10 seconds. Ordinarily when to shutdown the client is
68 // highly application specific.
69 fmt.Println("Client shutdown in 10 seconds...")
70 time.AfterFunc(
71 time.Second*10, func() {
72 fmt.Println("Client shutting down...")
73 client.Shutdown()
74 fmt.Println("Client shutdown complete.")
75 },
76 )
77 // Wait until the client either shuts down gracefully (or the user terminates the process with Ctrl+C).
78 client.WaitForShutdown()
79 }
80