Example #1
0
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 btcrpcclient
	// NotificationHandlers type for more details about each handler.
	ntfnHandlers := btcrpcclient.NotificationHandlers{
		OnBlockConnected: func(hash *btcwire.ShaHash, height int32) {
			log.Printf("Block connected: %v (%d)", hash, height)
		},
		OnBlockDisconnected: func(hash *btcwire.ShaHash, height int32) {
			log.Printf("Block disconnected: %v (%d)", hash, height)
		},
	}

	// Connect to local btcd RPC server using websockets.
	btcdHomeDir := btcutil.AppDataDir("btcd", false)
	certs, err := ioutil.ReadFile(filepath.Join(btcdHomeDir, "rpc.cert"))
	if err != nil {
		log.Fatal(err)
	}
	connCfg := &btcrpcclient.ConnConfig{
		Host:         "localhost:8334",
		Endpoint:     "ws",
		User:         "******",
		Pass:         "******",
		Certificates: certs,
	}
	client, err := btcrpcclient.New(connCfg, &ntfnHandlers)
	if err != nil {
		log.Fatal(err)
	}

	// Register for block connect and disconnect notifications.
	if err := client.NotifyBlocks(); err != nil {
		log.Fatal(err)
	}
	log.Println("NotifyBlocks: Registration Complete")

	// Get the current block count.
	blockCount, err := client.GetBlockCount()
	if err != nil {
		log.Fatal(err)
	}
	log.Printf("Block count: %d", blockCount)

	// For this example gracefully shutdown the client after 10 seconds.
	// Ordinarily when to shutdown the client is highly application
	// specific.
	log.Println("Client shutdown in 10 seconds...")
	time.AfterFunc(time.Second*10, func() {
		log.Println("Client shutting down...")
		client.Shutdown()
		log.Println("Client shutdown complete.")
	})

	// Wait until the client either shuts down gracefully (or the user
	// terminates the process with Ctrl+C).
	client.WaitForShutdown()
}
Example #2
0
func main() {
	// Only override the handlers for notifications you care about.
	// Also note most of the handlers will only be called if you register
	// for notifications.  See the documentation of the btcrpcclient
	// NotificationHandlers type for more details about each handler.
	ntfnHandlers := btcrpcclient.NotificationHandlers{
		OnAccountBalance: func(account string, balance btcutil.Amount, confirmed bool) {
			log.Printf("New balance for account %s: %v", account,
				balance)
		},
	}

	// Connect to local btcwallet RPC server using websockets.
	certHomeDir := btcutil.AppDataDir("btcwallet", false)
	certs, err := ioutil.ReadFile(filepath.Join(certHomeDir, "rpc.cert"))
	if err != nil {
		log.Fatal(err)
	}
	connCfg := &btcrpcclient.ConnConfig{
		Host:         "localhost:18332",
		Endpoint:     "ws",
		User:         "******",
		Pass:         "******",
		Certificates: certs,
	}
	client, err := btcrpcclient.New(connCfg, &ntfnHandlers)
	if err != nil {
		log.Fatal(err)
	}

	// Get the list of unspent transaction outputs (utxos) that the
	// connected wallet has at least one private key for.
	unspent, err := client.ListUnspent()
	if err != nil {
		log.Fatal(err)
	}
	log.Printf("Num unspent outputs (utxos): %d", len(unspent))
	if len(unspent) > 0 {
		log.Printf("First utxo:\n%v", spew.Sdump(unspent[0]))
	}

	// For this example gracefully shutdown the client after 10 seconds.
	// Ordinarily when to shutdown the client is highly application
	// specific.
	log.Println("Client shutdown in 10 seconds...")
	time.AfterFunc(time.Second*10, func() {
		log.Println("Client shutting down...")
		client.Shutdown()
		log.Println("Client shutdown complete.")
	})

	// Wait until the client either shuts down gracefully (or the user
	// terminates the process with Ctrl+C).
	client.WaitForShutdown()
}
Example #3
0
func main() {
	var err error

	cfg, _, err = loadConfig()
	if err != nil {
		fmt.Fprintf(os.Stderr, "loadConfig failed: %v\n", err)
		os.Exit(-1)
	}

	listeners := make([]net.Listener, 0, len(cfg.Listeners))
	for _, addr := range cfg.Listeners {
		listener, err := net.Listen("tcp", addr)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Listen failed: %v\n", err)
			os.Exit(-1)
		}
		listeners = append(listeners, listener)
	}

	cert, err := ioutil.ReadFile(cfg.RPCCert)
	if err != nil {
		fmt.Fprintf(os.Stderr, "failed to load certificate: %v\n", err)
		os.Exit(-1)
	}
	rpccfg := btcrpcclient.ConnConfig{
		Host:         cfg.RPCServer,
		Endpoint:     "ws",
		User:         cfg.RPCUser,
		Pass:         cfg.RPCPassword,
		Certificates: cert,
	}
	client, err = btcrpcclient.New(&rpccfg, nil)
	if err != nil {
		fmt.Fprintf(os.Stderr, "New RPC Client failed: %v\n", err)
		os.Exit(-1)
	}

	http.HandleFunc("/", handleRequest)

	httpServeMux := http.NewServeMux()
	httpServer := &http.Server{Handler: httpServeMux}
	httpServeMux.HandleFunc("/", handleRequest)

	var wg sync.WaitGroup
	for _, listener := range listeners {
		wg.Add(1)
		go func(listener net.Listener) {
			fmt.Fprintf(os.Stderr, "HTTP server listening on %s\n", listener.Addr())
			httpServer.Serve(listener)
			wg.Done()
		}(listener)
	}
	wg.Wait()
}
Example #4
0
func makeRpcClient(connCfg *btcrpcclient.ConnConfig) (*btcrpcclient.Client, error) {
	client, err := btcrpcclient.New(connCfg, nil)
	if err != nil {
		return nil, err
	}
	err = checkconnection(client)
	if err != nil {
		return nil, err
	}
	return client, nil
}
Example #5
0
func btcRpcClient() (*btcrpcclient.Client, error) {
	cfg := &btcrpcclient.ConnConfig{
		Host:         BtcRpcHost,
		User:         "******",
		Pass:         "******",
		DisableTLS:   true,
		HttpPostMode: true,
	}
	client, err := btcrpcclient.New(cfg, nil)
	if err != nil {
		log.Println(err)
	}
	return client, err
}
Example #6
0
func main() {
	flag.Parse()

	ntfnHandlers := btcrpcclient.NotificationHandlers{
		OnTxAccepted: func(hash *btcwire.ShaHash, amount btcutil.Amount) {
			h.broadcast <- []byte(strconv.FormatFloat(amount.ToUnit(0), 'f', -1, 64))
			log.Printf("Tx Accepted: %v (%s)", hash, amount.String())
		},
	}

	var certFile string
	if *rpcCert != "" {
		certFile = *rpcCert
	} else {
		btcdHomeDir := btcutil.AppDataDir("btcd", false)
		filepath.Join(btcdHomeDir, "rpc.cert")
		certFile = filepath.Join(btcdHomeDir, "rpc.cert")
	}

	certs, _ := ioutil.ReadFile(certFile)

	connCfg := &btcrpcclient.ConnConfig{
		Host:         *rpcHost,
		Endpoint:     "ws",
		User:         *rpcUser,
		Pass:         *rpcPass,
		Certificates: certs,
	}

	// Connect to btcd server
	client, err := btcrpcclient.New(connCfg, &ntfnHandlers)
	if err != nil {
		log.Fatal(err)
	}

	client.NotifyNewTransactions(false)

	// Start Websocket server
	go h.run()
	http.HandleFunc("/", serveWs)
	err = http.ListenAndServe(*address, nil)
	if err != nil {
		log.Fatal("Error starting http listener: ", err)
	}
}
Example #7
0
func newRPCClient(certs []byte) (*rpcClient, error) {
	client := rpcClient{
		enqueueNotification: make(chan notification),
		dequeueNotification: make(chan notification),
		quit:                make(chan struct{}),
	}
	initializedClient := make(chan struct{})
	ntfnCallbacks := btcrpcclient.NotificationHandlers{
		OnClientConnected: func() {
			log.Info("Established connection to btcd")
			<-initializedClient

			// nil client to broadcast to all connected clients
			server.NotifyConnectionStatus(nil)

			err := client.Handshake()
			if err != nil {
				log.Errorf("Cannot complete handshake: %v", err)
				client.Stop()
			}
		},
		OnBlockConnected:    client.onBlockConnected,
		OnBlockDisconnected: client.onBlockDisconnected,
		OnRecvTx:            client.onRecvTx,
		OnRedeemingTx:       client.onRedeemingTx,
		OnRescanFinished:    client.onRescanFinished,
		OnRescanProgress:    client.onRescanProgress,
	}
	conf := btcrpcclient.ConnConfig{
		Host:         cfg.RPCConnect,
		Endpoint:     "ws",
		User:         cfg.BtcdUsername,
		Pass:         cfg.BtcdPassword,
		Certificates: certs,
	}
	c, err := btcrpcclient.New(&conf, &ntfnCallbacks)
	if err != nil {
		return nil, err
	}
	client.Client = c
	close(initializedClient)
	return &client, nil
}
Example #8
0
func main() {
	// Connect to local bitcoin core RPC server using HTTP POST mode.
	connCfg := &btcrpcclient.ConnConfig{
		Host:         "localhost:8332",
		User:         "******",
		Pass:         "******",
		HttpPostMode: true, // Bitcoin core only supports HTTP POST mode
		DisableTLS:   true, // Bitcoin core does not provide TLS by default
	}
	// Notice the notification parameter is nil since notifications are
	// not supported in HTTP POST mode.
	client, err := btcrpcclient.New(connCfg, nil)
	if err != nil {
		log.Fatal(err)
	}
	defer client.Shutdown()

	// Get the current block count.
	blockCount, err := client.GetBlockCount()
	if err != nil {
		log.Fatal(err)
	}
	log.Printf("Block count: %d", blockCount)
}