Skip to content

Instantly share code, notes, and snippets.

@davecgh
Created February 20, 2016 06:19
Show Gist options
  • Save davecgh/1443ceb6f42531b32027 to your computer and use it in GitHub Desktop.
Save davecgh/1443ceb6f42531b32027 to your computer and use it in GitHub Desktop.
Naive bridge to listen for blockconnected notifications and invoke an executable.
// Copyright (c) 2016 The btcsuite developers
// Copyright (c) 2015-2016 The Decred developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package main
import (
"io/ioutil"
"log"
"os/exec"
"path/filepath"
"time"
"github.com/decred/dcrd/chaincfg/chainhash"
"github.com/decred/dcrrpcclient"
"github.com/decred/dcrutil"
)
const (
processName = "blocknotify"
)
func main() {
// Only override the handlers for notifications you care about.
// Also note most of these handlers will only be called if you register
// for notifications. See the documentation of the dcrrpcclient
// NotificationHandlers type for more details about each handler.
ntfnHandlers := dcrrpcclient.NotificationHandlers{
OnBlockConnected: func(hash *chainhash.Hash, height int32, time time.Time, vb uint16) {
// Find the process path.
cmd := exec.Command(processName, "1574", hash.String())
if err := cmd.Run(); err != nil {
log.Fatalln(err)
}
log.Printf("Block connected: %v (%d)", hash, height)
},
}
// Connect to local dcrd RPC server using websockets.
dcrdHomeDir := dcrutil.AppDataDir("dcrd", false)
certs, err := ioutil.ReadFile(filepath.Join(dcrdHomeDir, "rpc.cert"))
if err != nil {
log.Fatal(err)
}
connCfg := &dcrrpcclient.ConnConfig{
Host: "localhost:9109",
Endpoint: "ws",
User: "test",
Pass: "tabc",
Certificates: certs,
}
client, err := dcrrpcclient.New(connCfg, &ntfnHandlers)
if err != nil {
log.Fatalln(err)
}
// Register for block connect and disconnect notifications.
if err := client.NotifyBlocks(); err != nil {
log.Fatalln(err)
}
log.Println("NotifyBlocks: Registration Complete")
// Wait until the client either shuts down gracefully (or the user
// terminates the process with Ctrl+C).
client.WaitForShutdown()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment