stream.go raw

   1  package utxobuild
   2  
   3  import (
   4  	"bufio"
   5  	"fmt"
   6  	"io"
   7  	"os"
   8  	"path/filepath"
   9  
  10  	"git.smesh.lol/nostrino/pkg/crypto/chainhash"
  11  
  12  	"git.smesh.lol/btcd-lite/internal/utxo"
  13  	"git.smesh.lol/btcd-lite/internal/utxo/store"
  14  	"git.smesh.lol/btcd-lite/internal/wire"
  15  )
  16  
  17  // BuildStream walks the same blocks as Build and writes the same diffs and
  18  // snapshots, but it never holds the set: it works one epoch at a time, with the
  19  // entries that epoch touches in memory and everything else on disk.
  20  //
  21  // The pieces are one pass over the epoch's blocks to learn what it spends and
  22  // creates, a streamed join of those spends against the snapshot the epoch starts
  23  // from, and a second pass that applies the blocks in order against that overlay,
  24  // writing each block's diff and the diff of the whole epoch. The snapshot at the
  25  // epoch's end comes from utxostore.MergeRange, which streams the base alongside
  26  // the epoch's diff.
  27  //
  28  // The cost is the epoch: at 2016 blocks on mainnet, about five million touches,
  29  // which is a few hundred megabytes. Build holds the chain, which is four
  30  // gigabytes on a good day and the whole point of this path.
  31  func BuildStream(cfg Config) (Result, error) {
  32  	if cfg.Interval == 0 {
  33  		return Result{}, fmt.Errorf("utxobuild: the interval is required")
  34  	}
  35  	if cfg.To <= cfg.From {
  36  		return Result{}, fmt.Errorf("utxobuild: nothing to walk, %d to %d", cfg.From, cfg.To)
  37  	}
  38  	if cfg.From%cfg.Interval != 0 {
  39  		return Result{}, fmt.Errorf("utxobuild: a streamed walk starts on a snapshot, and %d is not one", cfg.From)
  40  	}
  41  	if cfg.Logf == nil {
  42  		cfg.Logf = func(string, ...any) {}
  43  	}
  44  	// MergeRange writes its key files beside the snapshot it reads, so the
  45  	// snapshot directory has to exist before the first epoch, not after.
  46  	for _, dir := range []string{cfg.Dir, cfg.DiffDir} {
  47  		if err := os.MkdirAll(dir, 0o755); err != nil {
  48  			return Result{}, fmt.Errorf("utxobuild: %w", err)
  49  		}
  50  	}
  51  	var res Result
  52  	res.Height = cfg.To
  53  	// A snapshot at H is the set after block H, so an epoch that starts at a
  54  	// snapshot covers the blocks above it: base+1 through base+Interval. Height 0
  55  	// has no predecessor to merge from, so its snapshot comes from block 0 alone,
  56  	// which is one block of touches.
  57  	base := cfg.From
  58  	if base == 0 {
  59  		name, err := seedZero(cfg)
  60  		if err != nil {
  61  			return res, err
  62  		}
  63  		res.Name = name
  64  		cfg.Logf("utxobuild %s: snapshot at 0, %s", cfg.Chain, name)
  65  	}
  66  	for base+cfg.Interval <= cfg.To {
  67  		to := base + cfg.Interval
  68  		from := base + 1
  69  		if base == 0 {
  70  			from = 1
  71  		}
  72  		// The snapshot at to is after block to, so the epoch's blocks are
  73  		// base+1 through to inclusive: the bound handed to the walk is exclusive.
  74  		touches, err := walk(cfg, base, from, to+1)
  75  		if err != nil {
  76  			return res, err
  77  		}
  78  		name, err := utxostore.MergeRangeFrom(cfg.baseDir(), cfg.Dir, base, to,
  79  			utxo.Diff{From: base, To: to, Touches: touches}, chainhash.Hash{})
  80  		if err != nil {
  81  			return res, fmt.Errorf("utxobuild: snapshot %d: %w", to, err)
  82  		}
  83  		res.Name = name
  84  		cfg.Logf("utxobuild %s: snapshot at %d, epoch %d..%d with %d touches, %s",
  85  			cfg.Chain, to, from, to, len(touches), name)
  86  		base = to
  87  	}
  88  	// The tail after the last snapshot boundary still has a diff per block: a
  89  	// client reaches those heights by applying them to the last snapshot.
  90  	if base+1 < cfg.To {
  91  		if _, err := walk(cfg, base, base+1, cfg.To); err != nil {
  92  			return res, err
  93  		}
  94  	}
  95  	return res, nil
  96  }
  97  
  98  // baseDir is where the snapshot the walk starts from is read.
  99  func (cfg Config) baseDir() string {
 100  	if cfg.BaseDir != "" {
 101  		return cfg.BaseDir
 102  	}
 103  	return cfg.Dir
 104  }
 105  
 106  // seedZero writes the snapshot at height 0: the set after block 0, which is the
 107  // genesis block's outputs and nothing else.
 108  func seedZero(cfg Config) (chainhash.Hash, error) {
 109  	b, err := readBlock(cfg, 0)
 110  	if err != nil {
 111  		return chainhash.Hash{}, err
 112  	}
 113  	ts, err := utxo.BlockTouches(b, 0, nil)
 114  	if err != nil {
 115  		return chainhash.Hash{}, fmt.Errorf("utxobuild: block 0: %w", err)
 116  	}
 117  	set, err := utxo.ApplyRange(nil, ts)
 118  	if err != nil {
 119  		return chainhash.Hash{}, fmt.Errorf("utxobuild: block 0: %w", err)
 120  	}
 121  	return utxostore.WriteSetFile(cfg.Dir, 0, set)
 122  }
 123  
 124  // walk applies blocks from..to to the overlay the snapshot at base resolves, and
 125  // returns the range's touches. It writes each block's diff, and nothing else:
 126  // whether a snapshot follows is the caller's business.
 127  //
 128  // The epoch is resolved in three steps: a pass over the blocks with no lookup to
 129  // learn what they spend and create, a streamed join that pulls the entry of every
 130  // spent outpoint out of the snapshot, and then the application itself, which
 131  // keeps the overlay current so a block may spend what a previous block made.
 132  func walk(cfg Config, base, from, to uint32) ([]utxo.Touch, error) {
 133  	spends := make(map[wire.OutPoint]bool, 4096)
 134  	for h := from; h < to; h++ {
 135  		b, err := readBlock(cfg, h)
 136  		if err != nil {
 137  			return nil, err
 138  		}
 139  		ts, err := utxo.BlockTouches(b, h, nil)
 140  		if err != nil {
 141  			return nil, fmt.Errorf("utxobuild: block %d: %w", h, err)
 142  		}
 143  		for i := range ts {
 144  			if ts[i].Spent {
 145  				spends[ts[i].OutPoint] = true
 146  			}
 147  		}
 148  	}
 149  	overlay, err := loadTouched(cfg, base, spends)
 150  	if err != nil {
 151  		return nil, err
 152  	}
 153  	touches := make([]utxo.Touch, 0, len(spends)*2)
 154  	for h := from; h < to; h++ {
 155  		b, err := readBlock(cfg, h)
 156  		if err != nil {
 157  			return nil, err
 158  		}
 159  		ts, err := utxo.BlockTouches(b, h, func(op wire.OutPoint) (utxo.Entry, bool) {
 160  			e, ok := overlay[op]
 161  			return e, ok
 162  		})
 163  		if err != nil {
 164  			return nil, fmt.Errorf("utxobuild: block %d: %w", h, err)
 165  		}
 166  		for j := range ts {
 167  			if ts[j].Spent {
 168  				delete(overlay, ts[j].OutPoint)
 169  				continue
 170  			}
 171  			overlay[ts[j].OutPoint] = ts[j].New
 172  		}
 173  		touches = append(touches, ts...)
 174  		if h > 0 && h >= cfg.DiffFrom {
 175  			if _, err := utxostore.CutRange(cfg.DiffDir, h-1, h, ts); err != nil {
 176  				return nil, fmt.Errorf("utxobuild: diff %d: %w", h, err)
 177  			}
 178  		}
 179  	}
 180  	return touches, nil
 181  }
 182  
 183  // loadTouched streams the snapshot the epoch starts from and returns the entry
 184  // of every outpoint the epoch spends. A spend of an outpoint the snapshot does
 185  // not hold is either a spend of an output the epoch itself creates, which the
 186  // overlay answers, or a body that spends nothing, which BlockTouches refuses.
 187  func loadTouched(cfg Config, from uint32, spends map[wire.OutPoint]bool) (map[wire.OutPoint]utxo.Entry, error) {
 188  	out := make(map[wire.OutPoint]utxo.Entry, len(spends))
 189  	if from == 0 || len(spends) == 0 {
 190  		return out, nil
 191  	}
 192  	f, err := os.Open(filepath.Join(cfg.baseDir(), utxostore.SetFile(from)))
 193  	if err != nil {
 194  		return nil, fmt.Errorf("utxobuild: snapshot %d: %w", from, err)
 195  	}
 196  	defer f.Close()
 197  	r := bufio.NewReaderSize(f, 1<<20)
 198  	buf := make([]byte, utxo.EntryEncodeSize)
 199  	for {
 200  		if _, err := io.ReadFull(r, buf); err != nil {
 201  			if err == io.EOF {
 202  				break
 203  			}
 204  			return nil, fmt.Errorf("utxobuild: snapshot %d: %w", from, err)
 205  		}
 206  		e := utxo.Decode(buf)
 207  		if spends[e.OutPoint] {
 208  			out[e.OutPoint] = e
 209  		}
 210  	}
 211  	return out, nil
 212  }
 213  
 214  // readBlock reads one body and parses it.
 215  func readBlock(cfg Config, h uint32) (*wire.Block, error) {
 216  	raw, err := cfg.Blocks.Block(h)
 217  	if err != nil {
 218  		return nil, fmt.Errorf("utxobuild: block %d: %w", h, err)
 219  	}
 220  	b, err := wire.ParseBlock(raw)
 221  	if err != nil {
 222  		return nil, fmt.Errorf("utxobuild: block %d: %w", h, err)
 223  	}
 224  	return b, nil
 225  }
 226