p2pnode.go raw

   1  package main
   2  
   3  import (
   4  	"context"
   5  	"errors"
   6  	"fmt"
   7  	"sync"
   8  
   9  	"git.smesh.lol/nostrino/pkg/btcwire"
  10  	"git.smesh.lol/nostrino/pkg/chain"
  11  	"git.smesh.lol/nostrino/pkg/crypto/chainhash"
  12  	"git.smesh.lol/nostrino/pkg/neutrino"
  13  )
  14  
  15  // p2pNode is the publisher's source when there is no node to ask over JSON-RPC.
  16  //
  17  // It follows the same peer the gateway proxies, through the same light client a wallet uses, and
  18  // answers the publisher's six questions from that client's verified store. That is what makes a
  19  // sidecar deployable beside a gateway instead of beside a full node: the chain data comes from the
  20  // peer the deployment already trusts for it, and nothing here needs an RPC endpoint, credentials or
  21  // a node's disk.
  22  //
  23  // The store is on disk, so a restart resumes the header and filter chain instead of downloading it
  24  // again.
  25  type p2pNode struct {
  26  	client *neutrino.Client
  27  	store  neutrino.Store
  28  
  29  	mu sync.Mutex
  30  	// heights remembers where a block hash was seen, because the block service is asked by hash
  31  	// and the store is indexed by height. A service asked for recent blocks only ever fills a
  32  	// small part of it.
  33  	heights map[chainhash.Hash]uint32
  34  	logf    func(string, ...any)
  35  }
  36  
  37  // openP2PNode prepares the client, seeds the store's anchor and connects.
  38  func openP2PNode(
  39  	ctx context.Context, profile *chain.Profile, storeDir, address string,
  40  	logf func(string, ...any),
  41  ) (*p2pNode, error) {
  42  	store, err := neutrino.OpenFileStore(storeDir)
  43  	if err != nil {
  44  		return nil, err
  45  	}
  46  
  47  	if _, ok := store.Anchor(); !ok {
  48  		anchor := neutrino.Anchor{Height: 0, BlockHash: profile.GenesisHash, FilterHeight: -1}
  49  
  50  		if profile.Checkpoint != nil {
  51  			anchor = neutrino.Anchor{
  52  				Height:       profile.Checkpoint.Height,
  53  				BlockHash:    profile.Checkpoint.BlockHash,
  54  				FilterHeight: int32(profile.Checkpoint.Height),
  55  				FilterHeader: profile.Checkpoint.FilterHeader,
  56  			}
  57  		}
  58  
  59  		if err := store.SetAnchor(anchor); err != nil {
  60  			return nil, err
  61  		}
  62  	}
  63  
  64  	client, err := neutrino.New(neutrino.Config{
  65  		Profile: profile,
  66  		Store:   store,
  67  		Address: address,
  68  		Logf:    logf,
  69  	})
  70  
  71  	if err != nil {
  72  		return nil, err
  73  	}
  74  
  75  	if err := client.Connect(ctx); err != nil {
  76  		return nil, fmt.Errorf("peer %s: %w", address, err)
  77  	}
  78  
  79  	return &p2pNode{
  80  		client: client, store: store,
  81  		heights: make(map[chainhash.Hash]uint32), logf: logf,
  82  	}, nil
  83  }
  84  
  85  // tip brings the header chain up to the peer and reports where it ends.
  86  func (n *p2pNode) tip(ctx context.Context) (uint32, error) {
  87  	if _, err := n.client.SyncHeaders(ctx); err != nil {
  88  		return 0, err
  89  	}
  90  
  91  	tip, _, ok := n.store.HeaderTip()
  92  
  93  	if !ok {
  94  		return 0, errors.New("p2p: no header tip")
  95  	}
  96  
  97  	return tip, nil
  98  }
  99  
 100  // header returns one verified header from the store.
 101  func (n *p2pNode) header(_ context.Context, height uint32) (btcwire.BlockHeader, error) {
 102  	header, ok := n.store.Header(height)
 103  
 104  	if !ok {
 105  		return btcwire.BlockHeader{}, fmt.Errorf("p2p: no header at %d", height)
 106  	}
 107  
 108  	return header, nil
 109  }
 110  
 111  // blockTime returns the header's own time, which is what the filter batch dates itself by.
 112  func (n *p2pNode) blockTime(ctx context.Context, height uint32) (int64, error) {
 113  	header, err := n.header(ctx, height)
 114  
 115  	if err != nil {
 116  		return 0, err
 117  	}
 118  
 119  	return int64(header.Timestamp), nil
 120  }
 121  
 122  // filter returns one compact filter, fetching it from the peer when the store does not have it.
 123  func (n *p2pNode) filter(ctx context.Context, height uint32) ([]byte, chainhash.Hash, error) {
 124  	if filter, ok := n.store.Filter(height); ok {
 125  		if hash, ok := n.store.FilterHash(height); ok {
 126  			return filter, hash, nil
 127  		}
 128  	}
 129  
 130  	if _, _, err := n.client.SyncFilters(ctx, height, 1); err != nil {
 131  		return nil, chainhash.Hash{}, fmt.Errorf("filter %d: %w", height, err)
 132  	}
 133  
 134  	filter, ok := n.store.Filter(height)
 135  
 136  	if !ok {
 137  		return nil, chainhash.Hash{}, fmt.Errorf("p2p: no filter at %d after the fetch", height)
 138  	}
 139  
 140  	hash, ok := n.store.FilterHash(height)
 141  
 142  	if !ok {
 143  		return nil, chainhash.Hash{}, fmt.Errorf("p2p: no filter hash at %d after the fetch", height)
 144  	}
 145  
 146  	return filter, hash, nil
 147  }
 148  
 149  // block returns one raw block through the client, which verifies its header before the caller
 150  // sees it.
 151  func (n *p2pNode) block(ctx context.Context, height uint32) ([]byte, error) {
 152  	return n.client.Block(ctx, height)
 153  }
 154  
 155  // blockByHash resolves a hash to a height and reads the block there.
 156  //
 157  // The lookup walks down from the tip, which is where a block service's requests are: a client
 158  // asks for the block whose filter matched, and those are recent. The answer is remembered, so a
 159  // second request for the same block does not walk again.
 160  func (n *p2pNode) blockByHash(ctx context.Context, hash chainhash.Hash) ([]byte, error) {
 161  	n.mu.Lock()
 162  	height, known := n.heights[hash]
 163  	n.mu.Unlock()
 164  
 165  	if !known {
 166  		tip, _, ok := n.store.HeaderTip()
 167  
 168  		if !ok {
 169  			return nil, errors.New("p2p: no header tip")
 170  		}
 171  
 172  		for h := tip; ; h-- {
 173  			header, ok := n.store.Header(h)
 174  
 175  			if ok && header.BlockHash() == hash {
 176  				height, known = h, true
 177  
 178  				break
 179  			}
 180  
 181  			if h == 0 {
 182  				break
 183  			}
 184  		}
 185  
 186  		if !known {
 187  			return nil, fmt.Errorf("p2p: block %s is not in the header chain", hash.String())
 188  		}
 189  
 190  		n.mu.Lock()
 191  		n.heights[hash] = height
 192  		n.mu.Unlock()
 193  	}
 194  
 195  	return n.block(ctx, height)
 196  }
 197  
 198  // close ends the peer connection.
 199  func (n *p2pNode) close() {
 200  	_ = n.client.Close()
 201  }
 202