build.go raw

   1  // Package utxobuild makes a chain's canonical UTXO set out of block bodies,
   2  // one snapshot per retarget and one diff per block, and builds the chain's
   3  // compact filters on the same walk.
   4  //
   5  // It is not a validator. It reads the outputs each block funds and the outpoints
   6  // it spends, and it trusts the bodies it is given: the caller is the processing
   7  // pass, which checked every body against the header it was asked for.
   8  //
   9  // The snapshot cadence is the chain's retarget interval, not a flag. A snapshot
  10  // lands at every height that is a multiple of it, so the boundaries are the ones
  11  // the chain already has, and between two of them there is one diff per block:
  12  // the touches of exactly one height, which is the degenerate range a merge
  13  // already handles.
  14  package utxobuild
  15  
  16  import (
  17  	"errors"
  18  	"fmt"
  19  
  20  	"git.smesh.lol/nostrino/pkg/crypto/chainhash"
  21  
  22  	"git.smesh.lol/btcd-lite/internal/store"
  23  	"git.smesh.lol/btcd-lite/internal/utxo"
  24  	utxostore "git.smesh.lol/btcd-lite/internal/utxo/store"
  25  	"git.smesh.lol/btcd-lite/internal/wire"
  26  )
  27  
  28  // BlockSource is where the bodies come from: one block at a height.
  29  type BlockSource interface {
  30  	Block(height uint32) ([]byte, error)
  31  }
  32  
  33  // Config is what a build needs.
  34  type Config struct {
  35  	// Dir is where the snapshots are written.
  36  	Dir string
  37  	// DiffDir is where the per-block diffs are written. It is a separate
  38  	// directory because a diff belongs to a block and a snapshot belongs to a
  39  	// chain at a height: the shared prefix's diffs are written once.
  40  	DiffDir string
  41  	// Chain names the walk in the log lines. It selects nothing.
  42  	Chain string
  43  	// Interval is how many blocks between snapshots: the chain's retarget
  44  	// interval, from chains.ExportedChain.Retarget.
  45  	Interval uint32
  46  	// From and To are the heights to cover, half-open.
  47  	From, To uint32
  48  	// Start is the set the replay begins from. A streamed walk ignores it: it
  49  	// reads the snapshot on disk at From, which is why it can start above height
  50  	// 0 without rebuilding the chain to learn what the set holds.
  51  	Start []utxo.Entry
  52  	// BaseDir is where the snapshot the walk starts from is read, when it is not
  53  	// Dir. A chain continuing a shared prefix reads the prefix's snapshot where
  54  	// the prefix wrote it.
  55  	BaseDir string
  56  	// DiffFrom is the first height whose diff this walk writes. It is zero for a
  57  	// chain's own dataset and the fork point for a chain that continues from a
  58  	// shared prefix: the prefix's diffs are written once, by the prefix's walk,
  59  	// and a second copy in a chain's directory would be the same bytes under a
  60  	// second name.
  61  	DiffFrom uint32
  62  	// Blocks supplies the bodies.
  63  	Blocks BlockSource
  64  	// Logf receives progress; nil discards it.
  65  	Logf func(string, ...any)
  66  }
  67  
  68  // Result is what a walk leaves: the set it ended with, the height it ended at,
  69  // and the name of the last snapshot it wrote.
  70  //
  71  // The set is here because the next walk of the same chain starts from it. A
  72  // shared prefix is walked once and both chains continue from the set it ends
  73  // with, so no second walk reloads a snapshot and replays an epoch to learn what
  74  // it already had in memory.
  75  type Result struct {
  76  	Set    []utxo.Entry
  77  	Height uint32
  78  	Name   chainhash.Hash
  79  }
  80  
  81  // Build walks blocks From..To of one chain, writing one diff per block, a
  82  // snapshot at every retarget height, and a filter per block when the config asks
  83  // for them. The heights are the blocks themselves: a snapshot at H is the set
  84  // after block H, and the diff of block H takes the set at H-1 to the set at H.
  85  //
  86  // The set is carried in memory between snapshots and laid down as a file at
  87  // each one, so a client reaches a snapshot without replay and reaches anything
  88  // between two of them by applying the per-block diffs that follow.
  89  //
  90  // The filter build needs the scriptPubKey of every output a block spends, and a
  91  // block does not carry them, so the walk keeps them: the scripts of unspent
  92  // outputs live in memory alongside the set and are dropped when they are spent.
  93  // That is the price of building filters at all, and it is why the filter build
  94  // is here and not in the processing pass, which sees one block at a time and
  95  // could not answer for an output spent by a later block.
  96  func Build(cfg Config) (Result, error) {
  97  	if cfg.Interval == 0 {
  98  		return Result{}, errors.New("utxobuild: the interval is required")
  99  	}
 100  	if cfg.To <= cfg.From {
 101  		return Result{}, fmt.Errorf("utxobuild: range %d..%d is empty", cfg.From, cfg.To)
 102  	}
 103  	if cfg.From > 0 && cfg.Start == nil {
 104  		return Result{}, fmt.Errorf("utxobuild: a walk from %d needs the set it starts from", cfg.From)
 105  	}
 106  	if err := utxo.Validate(cfg.Start); err != nil {
 107  		return Result{}, fmt.Errorf("utxobuild: start set: %w", err)
 108  	}
 109  	if cfg.Logf == nil {
 110  		cfg.Logf = func(string, ...any) {}
 111  	}
 112  	if cfg.DiffDir == "" {
 113  		// A caller with one directory keeps both artifacts in it; a caller
 114  		// that splits them says where the diffs go.
 115  		cfg.DiffDir = cfg.Dir
 116  	}
 117  	set := cfg.Start
 118  	last := chainhash.Hash{}
 119  	for h := cfg.From; h < cfg.To; h++ {
 120  		raw, err := cfg.Blocks.Block(h)
 121  		if err != nil {
 122  			return Result{}, fmt.Errorf("utxobuild: block %d: %w", h, err)
 123  		}
 124  		b, err := wire.ParseBlock(raw)
 125  		if err != nil {
 126  			return Result{}, fmt.Errorf("utxobuild: block %d: %w", h, err)
 127  		}
 128  		// The lookup is the set being built: an input the set does not hold is
 129  		// not a spend of anything, and BlockTouches records it as a spend the
 130  		// set will refuse, which is how a body that spends outside its own
 131  		// chain shows up instead of being swallowed.
 132  		ts, err := utxo.BlockTouches(b, h, utxo.Lookup(func(op wire.OutPoint) (utxo.Entry, bool) {
 133  			return utxo.Find(set, op)
 134  		}))
 135  		if err != nil {
 136  			return Result{}, fmt.Errorf("utxobuild: block %d: %w", h, err)
 137  		}
 138  		set, err = utxo.ApplyRange(set, ts)
 139  		if err != nil {
 140  			return Result{}, fmt.Errorf("utxobuild: block %d: %w", h, err)
 141  		}
 142  		// The diff of block h takes the set at h-1 to the set at h, so it is
 143  		// named for that step. Block 0 has no predecessor: its effects are in
 144  		// the snapshot at 0, which is where every client starts.
 145  		if h > 0 {
 146  			if _, err := utxostore.CutRange(cfg.DiffDir, h-1, h, ts); err != nil {
 147  				return Result{}, fmt.Errorf("utxobuild: diff %d: %w", h, err)
 148  			}
 149  		}
 150  		debugSet(h, len(set), utxostore.NameOf(set))
 151  		if h%cfg.Interval != 0 {
 152  			continue
 153  		}
 154  		name, err := utxostore.WriteSetFile(cfg.Dir, h, set)
 155  		if err != nil {
 156  			return Result{}, err
 157  		}
 158  		last = name
 159  		cfg.Logf("utxobuild %s: snapshot at %d, %d entries, %s", cfg.Chain, h, len(set), name)
 160  		debugCheckpoint(h, name, name)
 161  	}
 162  	return Result{Set: set, Height: cfg.To, Name: last}, nil
 163  }
 164  
 165  // debugSet and debugCheckpoint are switches a test flips to see the walk's name
 166  // at every block and the name of each snapshot.
 167  var debugSet = func(height uint32, entries int, name chainhash.Hash) {}
 168  var debugCheckpoint = func(to uint32, merged, walked chainhash.Hash) {}
 169  
 170  // Debug installs those switches from outside the package. Passing nil disables
 171  // one of them.
 172  func Debug(set func(uint32, int, chainhash.Hash), checkpoint func(uint32, chainhash.Hash, chainhash.Hash)) {
 173  	debugSet = func(uint32, int, chainhash.Hash) {}
 174  	debugCheckpoint = func(uint32, chainhash.Hash, chainhash.Hash) {}
 175  	if set != nil {
 176  		debugSet = set
 177  	}
 178  	if checkpoint != nil {
 179  		debugCheckpoint = checkpoint
 180  	}
 181  }
 182  
 183  // StoreSource adapts a body store to a BlockSource through a chain's header
 184  // store, which is where a height resolves to a hash. The body store is keyed by
 185  // hash alone, so it cannot answer a height on its own.
 186  type StoreSource struct {
 187  	S       *store.BlockStore
 188  	Headers *store.HeaderStore
 189  }
 190  
 191  // Block returns one body.
 192  func (s StoreSource) Block(height uint32) ([]byte, error) {
 193  	hdr, ok := s.Headers.Header(height)
 194  	if !ok {
 195  		return nil, fmt.Errorf("utxobuild: no header at %d", height)
 196  	}
 197  	return s.S.GetBlock(hdr.BlockHash())
 198  }
 199