client.go raw

   1  // Package rpc is the bitcoin-cli vocabulary the gate tests use.
   2  //
   3  // It is a test oracle, not the product: the service pulls from peers and never
   4  // talks to a node. The tests compare what the service computes against what a
   5  // node with a block filter index says, which is the only independent
   6  // implementation of the filter, the filter header chain and the merkle root
   7  // this machine has.
   8  package rpc
   9  
  10  import (
  11  	"bytes"
  12  	"encoding/base64"
  13  	"encoding/hex"
  14  	"encoding/json"
  15  	"fmt"
  16  	"io"
  17  	"net/http"
  18  	"os"
  19  	"strings"
  20  	"time"
  21  )
  22  
  23  // Client is one node reached over its JSON-RPC port.
  24  type Client struct {
  25  	url  string
  26  	auth string
  27  	http *http.Client
  28  }
  29  
  30  // DialCookie opens a session with credentials from a node's .cookie file.
  31  func DialCookie(port int, cookiePath string) (*Client, error) {
  32  	raw, err := os.ReadFile(cookiePath)
  33  	if err != nil {
  34  		return nil, fmt.Errorf("rpc: read cookie: %w", err)
  35  	}
  36  	return Dial(port, strings.TrimSpace(string(raw)))
  37  }
  38  
  39  // Dial opens a session with user:pass credentials.
  40  func Dial(port int, userPass string) (*Client, error) {
  41  	if !strings.Contains(userPass, ":") {
  42  		return nil, fmt.Errorf("rpc: credentials are not user:pass")
  43  	}
  44  	return &Client{
  45  		url:  fmt.Sprintf("http://127.0.0.1:%d", port),
  46  		auth: base64.StdEncoding.EncodeToString([]byte(userPass)),
  47  		http: &http.Client{Timeout: 60 * time.Second},
  48  	}, nil
  49  }
  50  
  51  // Call runs one method and unmarshals its result into out.
  52  func (c *Client) Call(method string, params []any, out any) error {
  53  	if params == nil {
  54  		params = []any{}
  55  	}
  56  	body, err := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": 1, "method": method, "params": params})
  57  	if err != nil {
  58  		return err
  59  	}
  60  	req, err := http.NewRequest(http.MethodPost, c.url, bytes.NewReader(body))
  61  	if err != nil {
  62  		return err
  63  	}
  64  	req.Header.Set("Content-Type", "application/json")
  65  	req.Header.Set("Authorization", "Basic "+c.auth)
  66  	resp, err := c.http.Do(req)
  67  	if err != nil {
  68  		return fmt.Errorf("rpc %s: %w", method, err)
  69  	}
  70  	defer resp.Body.Close()
  71  	raw, err := io.ReadAll(resp.Body)
  72  	if err != nil {
  73  		return fmt.Errorf("rpc %s: %w", method, err)
  74  	}
  75  	var envelope struct {
  76  		Result json.RawMessage `json:"result"`
  77  		Error  *struct {
  78  			Code    int    `json:"code"`
  79  			Message string `json:"message"`
  80  		} `json:"error"`
  81  	}
  82  	if err := json.Unmarshal(raw, &envelope); err != nil {
  83  		return fmt.Errorf("rpc %s: %d bytes that are not JSON: %w", method, len(raw), err)
  84  	}
  85  	if envelope.Error != nil {
  86  		return fmt.Errorf("rpc %s: %d %s", method, envelope.Error.Code, envelope.Error.Message)
  87  	}
  88  	if out == nil {
  89  		return nil
  90  	}
  91  	if err := json.Unmarshal(envelope.Result, out); err != nil {
  92  		return fmt.Errorf("rpc %s: result: %w", method, err)
  93  	}
  94  	return nil
  95  }
  96  
  97  // BlockCount is the node's chain height.
  98  func (c *Client) BlockCount() (uint32, error) {
  99  	var n uint32
 100  	err := c.Call("getblockcount", nil, &n)
 101  	return n, err
 102  }
 103  
 104  // BlockHash is the hash at a height.
 105  func (c *Client) BlockHash(height uint32) (string, error) {
 106  	var h string
 107  	err := c.Call("getblockhash", []any{height}, &h)
 108  	return strings.ToLower(h), err
 109  }
 110  
 111  // BlockRaw is the block at a hash in wire form.
 112  func (c *Client) BlockRaw(hash string) ([]byte, error) {
 113  	var raw string
 114  	if err := c.Call("getblock", []any{hash, 0}, &raw); err != nil {
 115  		return nil, err
 116  	}
 117  	return hex.DecodeString(raw)
 118  }
 119  
 120  // Filter is the BIP157 basic filter at a block and the header it folds to.
 121  func (c *Client) Filter(hash string) (filter, header []byte, err error) {
 122  	var out struct {
 123  		Filter string `json:"filter"`
 124  		Header string `json:"header"`
 125  	}
 126  	if err := c.Call("getblockfilter", []any{hash}, &out); err != nil {
 127  		return nil, nil, err
 128  	}
 129  	filter, err = hex.DecodeString(out.Filter)
 130  	if err != nil {
 131  		return nil, nil, err
 132  	}
 133  	header, err = hex.DecodeString(out.Header)
 134  	return filter, header, err
 135  }
 136  
 137  // RawTx is the raw hex of a wallet transaction.
 138  func (c *Client) RawTx(txid string) ([]byte, error) {
 139  	var raw string
 140  	if err := c.Call("getrawtransaction", []any{txid, false}, &raw); err != nil {
 141  		return nil, err
 142  	}
 143  	return hex.DecodeString(raw)
 144  }
 145  
 146  // Stop asks the node to shut down.
 147  func (c *Client) Stop() error {
 148  	return c.Call("stop", nil, nil)
 149  }
 150