main.go raw

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