github.com/palcoin-project/palcd@v1.0.0/rpcclient/examples/btcwalletwebsockets/main.go (about)

     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  
     5  package main
     6  
     7  import (
     8  	"io/ioutil"
     9  	"log"
    10  	"path/filepath"
    11  	"time"
    12  
    13  	"github.com/davecgh/go-spew/spew"
    14  	"github.com/palcoin-project/palcd/rpcclient"
    15  	"github.com/palcoin-project/palcutil"
    16  )
    17  
    18  func main() {
    19  	// Only override the handlers for notifications you care about.
    20  	// Also note most of the 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  		OnAccountBalance: func(account string, balance palcutil.Amount, confirmed bool) {
    25  			log.Printf("New balance for account %s: %v", account,
    26  				balance)
    27  		},
    28  	}
    29  
    30  	// Connect to local btcwallet RPC server using websockets.
    31  	certHomeDir := palcutil.AppDataDir("palcwallet", false)
    32  	certs, err := ioutil.ReadFile(filepath.Join(certHomeDir, "rpc.cert"))
    33  	if err != nil {
    34  		log.Fatal(err)
    35  	}
    36  	connCfg := &rpcclient.ConnConfig{
    37  		Host:         "localhost:11987",
    38  		Endpoint:     "ws",
    39  		User:         "yourrpcuser",
    40  		Pass:         "yourrpcpass",
    41  		Certificates: certs,
    42  	}
    43  	client, err := rpcclient.New(connCfg, &ntfnHandlers)
    44  	if err != nil {
    45  		log.Fatal(err)
    46  	}
    47  
    48  	// Get the list of unspent transaction outputs (utxos) that the
    49  	// connected wallet has at least one private key for.
    50  	unspent, err := client.ListUnspent()
    51  	if err != nil {
    52  		log.Fatal(err)
    53  	}
    54  	log.Printf("Num unspent outputs (utxos): %d", len(unspent))
    55  	if len(unspent) > 0 {
    56  		log.Printf("First utxo:\n%v", spew.Sdump(unspent[0]))
    57  	}
    58  
    59  	// For this example gracefully shutdown the client after 10 seconds.
    60  	// Ordinarily when to shutdown the client is highly application
    61  	// specific.
    62  	log.Println("Client shutdown in 10 seconds...")
    63  	time.AfterFunc(time.Second*10, func() {
    64  		log.Println("Client shutting down...")
    65  		client.Shutdown()
    66  		log.Println("Client shutdown complete.")
    67  	})
    68  
    69  	// Wait until the client either shuts down gracefully (or the user
    70  	// terminates the process with Ctrl+C).
    71  	client.WaitForShutdown()
    72  }