build.go raw

   1  // Package filterbuild computes BIP158 filters from block bodies, with the
   2  // scriptPubKey of every unspent output kept in a sorted file on disk instead of
   3  // in memory.
   4  //
   5  // A filter needs the script of every output a block spends, and a block carries
   6  // only the outpoints it spends. The walk therefore needs the scripts of outputs
   7  // created earlier, which is what the canonical set does not hold: its entries
   8  // keep an eight-byte script hash and nothing else.
   9  //
  10  // Two properties make this fit in a small host. The table is sorted by outpoint
  11  // and only ever streamed, because the epoch's spends are sorted and joined
  12  // against it in one pass, so no lookup is random. And only one epoch's touches
  13  // are held at a time: about five million outpoints at 2016 blocks, which is a
  14  // few hundred megabytes, not the tens of gigabytes a map of every unspent script
  15  // costs.
  16  package filterbuild
  17  
  18  import (
  19  	"bufio"
  20  	"encoding/binary"
  21  	"errors"
  22  	"fmt"
  23  	"io"
  24  	"os"
  25  	"path/filepath"
  26  	"sort"
  27  
  28  	"git.smesh.lol/nostrino/pkg/crypto/chainhash"
  29  
  30  	"git.smesh.lol/btcd-lite/internal/filter"
  31  	"git.smesh.lol/btcd-lite/internal/filterstore"
  32  	"git.smesh.lol/btcd-lite/internal/store"
  33  	"git.smesh.lol/btcd-lite/internal/utxo"
  34  	"git.smesh.lol/btcd-lite/internal/wire"
  35  )
  36  
  37  // Entry is one unspent output's script.
  38  type Entry struct {
  39  	OutPoint wire.OutPoint
  40  	Script   []byte
  41  }
  42  
  43  // RecordSize is the fixed part of a record: outpoint (36) and script length (2).
  44  const RecordSize = 38
  45  
  46  // sorted reports whether a is before b, by the one outpoint order the whole
  47  // project uses.
  48  func sorted(a, b Entry) bool { return utxo.CompareOutPoints(a.OutPoint, b.OutPoint) < 0 }
  49  
  50  // Writer appends sorted entries to a table file.
  51  type Writer struct {
  52  	f *os.File
  53  	w *bufio.Writer
  54  	// last is the entry written last, so the writer refuses an unsorted
  55  	// sequence rather than producing a file no merge can read.
  56  	last Entry
  57  	set  bool
  58  }
  59  
  60  // Create starts a new table at path.
  61  func Create(path string) (*Writer, error) {
  62  	if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
  63  		return nil, fmt.Errorf("filterbuild: %w", err)
  64  	}
  65  	f, err := os.Create(path)
  66  	if err != nil {
  67  		return nil, fmt.Errorf("filterbuild: %w", err)
  68  	}
  69  	return &Writer{f: f, w: bufio.NewWriterSize(f, 1<<20)}, nil
  70  }
  71  
  72  // Write appends one entry. Entries must arrive in outpoint order.
  73  func (w *Writer) Write(e Entry) error {
  74  	if len(e.Script) == 0 || len(e.Script) > 0xffff {
  75  		return fmt.Errorf("filterbuild: script of %d bytes", len(e.Script))
  76  	}
  77  	if w.set && !sorted(w.last, e) {
  78  		return fmt.Errorf("filterbuild: %s arrives after %s", e.OutPoint, w.last.OutPoint)
  79  	}
  80  	var rec [RecordSize]byte
  81  	copy(rec[0:32], e.OutPoint.Hash[:])
  82  	binary.LittleEndian.PutUint32(rec[32:36], e.OutPoint.Index)
  83  	binary.LittleEndian.PutUint16(rec[36:38], uint16(len(e.Script)))
  84  	if _, err := w.w.Write(rec[:]); err != nil {
  85  		return fmt.Errorf("filterbuild: %w", err)
  86  	}
  87  	if _, err := w.w.Write(e.Script); err != nil {
  88  		return fmt.Errorf("filterbuild: %w", err)
  89  	}
  90  	w.last, w.set = e, true
  91  	return nil
  92  }
  93  
  94  // Close flushes and closes the table.
  95  func (w *Writer) Close() error {
  96  	if err := w.w.Flush(); err != nil {
  97  		w.f.Close()
  98  		return fmt.Errorf("filterbuild: %w", err)
  99  	}
 100  	if err := w.f.Sync(); err != nil {
 101  		w.f.Close()
 102  		return fmt.Errorf("filterbuild: %w", err)
 103  	}
 104  	return w.f.Close()
 105  }
 106  
 107  // Reader streams a table.
 108  type Reader struct {
 109  	f *os.File
 110  	r *bufio.Reader
 111  }
 112  
 113  // Open streams the table at path.
 114  func Open(path string) (*Reader, error) {
 115  	f, err := os.Open(path)
 116  	if err != nil {
 117  		return nil, fmt.Errorf("filterbuild: %w", err)
 118  	}
 119  	return &Reader{f: f, r: bufio.NewReaderSize(f, 1<<20)}, nil
 120  }
 121  
 122  // Next returns the next entry, or false at the end.
 123  func (r *Reader) Next() (Entry, bool, error) {
 124  	var rec [RecordSize]byte
 125  	if _, err := io.ReadFull(r.r, rec[:]); err != nil {
 126  		if errors.Is(err, io.EOF) {
 127  			return Entry{}, false, nil
 128  		}
 129  		return Entry{}, false, fmt.Errorf("filterbuild: %w", err)
 130  	}
 131  	var e Entry
 132  	copy(e.OutPoint.Hash[:], rec[0:32])
 133  	e.OutPoint.Index = binary.LittleEndian.Uint32(rec[32:36])
 134  	n := binary.LittleEndian.Uint16(rec[36:38])
 135  	e.Script = make([]byte, n)
 136  	if _, err := io.ReadFull(r.r, e.Script); err != nil {
 137  		return Entry{}, false, fmt.Errorf("filterbuild: short script: %w", err)
 138  	}
 139  	return e, true, nil
 140  }
 141  
 142  // Close closes the table.
 143  func (r *Reader) Close() error { return r.f.Close() }
 144  
 145  // writeUnique writes entries that are sorted, collapsing runs of the same
 146  // outpoint to the first.
 147  //
 148  // Two blocks can create one outpoint. Bitcoin has one such pair: the duplicate
 149  // coinbase transaction of blocks 91722 and 91880, which carry the same txid, so
 150  // both create the same output. A table is a set, so the second record is the
 151  // first record and writing it twice would make the file unmergeable.
 152  func writeUnique(w *Writer, entries []Entry) error {
 153  	for i := range entries {
 154  		if i > 0 && !sorted(entries[i-1], entries[i]) {
 155  			if compare(entries[i-1].OutPoint, entries[i].OutPoint) == 0 {
 156  				continue
 157  			}
 158  		}
 159  		if w.set && compare(w.last.OutPoint, entries[i].OutPoint) == 0 {
 160  			continue
 161  		}
 162  		if err := w.Write(entries[i]); err != nil {
 163  			return err
 164  		}
 165  	}
 166  	return nil
 167  }
 168  
 169  // compare orders two outpoints the way the table does.
 170  func compare(a, b wire.OutPoint) int { return utxo.CompareOutPoints(a, b) }
 171  
 172  // Merge writes old, minus the spent outpoints, plus the created entries, into
 173  // path. Both inputs must be in outpoint order.
 174  func Merge(oldPath, path string, spent map[wire.OutPoint]bool, created []Entry) error {
 175  	sort.Slice(created, func(i, j int) bool { return sorted(created[i], created[j]) })
 176  	w, err := Create(path)
 177  	if err != nil {
 178  		return err
 179  	}
 180  	defer w.Close()
 181  	if _, err := os.Stat(oldPath); os.IsNotExist(err) {
 182  		if err := writeUnique(w, created); err != nil {
 183  			return err
 184  		}
 185  		return w.Close()
 186  	}
 187  	r, err := Open(oldPath)
 188  	if err != nil {
 189  		return err
 190  	}
 191  	defer r.Close()
 192  	old, ok, err := r.Next()
 193  	if err != nil {
 194  		return err
 195  	}
 196  	ci := 0
 197  	for {
 198  		// Take whichever is next in outpoint order.
 199  		takeOld := ok
 200  		if ok && ci < len(created) && !sorted(old, created[ci]) {
 201  			takeOld = false
 202  		}
 203  		if !ok && ci >= len(created) {
 204  			break
 205  		}
 206  		if takeOld {
 207  			if !spent[old.OutPoint] {
 208  				if err := w.Write(old); err != nil {
 209  					return err
 210  				}
 211  			}
 212  			old, ok, err = r.Next()
 213  			if err != nil {
 214  				return err
 215  			}
 216  			continue
 217  		}
 218  		if err := writeUnique(w, created[ci:ci+1]); err != nil {
 219  			return err
 220  		}
 221  		ci++
 222  	}
 223  	return w.Close()
 224  }
 225  
 226  // Config is one build over a range of a chain.
 227  type Config struct {
 228  	// Dir holds the table files: <Dir>/scripts-<height>.tab.
 229  	Dir string
 230  	// From and To are the heights to cover, half-open.
 231  	From, To uint32
 232  	// Interval is the epoch length: the chain's retarget interval, which is
 233  	// also the snapshot cadence. The table is rewritten at each boundary.
 234  	Interval uint32
 235  	// Blocks supplies the bodies.
 236  	Blocks interface {
 237  		Block(height uint32) ([]byte, error)
 238  	}
 239  	// Filters receives one filter per block, keyed by the block's hash.
 240  	Filters *filterstore.Store
 241  	// Folds are the header stores that receive the filter hash and the folded
 242  	// filter header at each height.
 243  	Folds []*store.HeaderStore
 244  	// Verify compares what is stored with what the bodies produce instead of
 245  	// writing, which is how a chain of filters that came from a peer is checked
 246  	// against the blocks this instance holds.
 247  	Verify bool
 248  	// Logf receives progress; nil discards it.
 249  	Logf func(string, ...any)
 250  }
 251  
 252  // TablePath is where a table for a boundary height lives.
 253  func TablePath(dir string, height uint32) string {
 254  	return filepath.Join(dir, fmt.Sprintf("scripts-%09d.tab", height))
 255  }
 256  
 257  // Result is what a build wrote.
 258  type Result struct {
 259  	Filters int
 260  	// Tables is how many table rewrites were done.
 261  	Tables int
 262  	// Checked and Differed are the verification's counts: how many heights were
 263  	// compared and how many disagreed with what the bodies produce.
 264  	Checked  int
 265  	Differed int
 266  	// FirstDifference is the lowest height that disagreed.
 267  	FirstDifference uint32
 268  	// MaxCreated and MaxSpent are the largest single epoch's touch lists, which
 269  	// is the memory the design costs: they must not grow with the chain, only
 270  	// with the epochs, and a build that held the chain would grow them every
 271  	// epoch.
 272  	MaxCreated int
 273  	MaxSpent   int
 274  }
 275  
 276  // Build computes one filter per block over From..To, rewriting the script table
 277  // at every Interval.
 278  //
 279  // Each epoch is two reads of its blocks and one pass over the table: first to
 280  // collect the epoch's spends and creations, then a join that puts the script of
 281  // every spent outpoint in a map for that epoch, then a second read to build each
 282  // block's filter as the block ends. Only the epoch is in memory.
 283  func Build(cfg Config) (Result, error) {
 284  	if cfg.Interval == 0 {
 285  		return Result{}, errors.New("filterbuild: the interval is required")
 286  	}
 287  	if len(cfg.Folds) == 0 || cfg.Filters == nil {
 288  		return Result{}, errors.New("filterbuild: filters and a fold store are required")
 289  	}
 290  	if cfg.Logf == nil {
 291  		cfg.Logf = func(string, ...any) {}
 292  	}
 293  	var res Result
 294  	table := ""
 295  	if cfg.From > 0 {
 296  		table = TablePath(cfg.Dir, cfg.From-cfg.From%cfg.Interval)
 297  	}
 298  	for epochStart := cfg.From; epochStart < cfg.To; epochStart += cfg.Interval {
 299  		epochEnd := min(epochStart+cfg.Interval, cfg.To)
 300  		nextTable := TablePath(cfg.Dir, epochEnd)
 301  		spent, created, err := collect(cfg, epochStart, epochEnd)
 302  		if err != nil {
 303  			return res, err
 304  		}
 305  		scripts, err := join(cfg, table, spent)
 306  		if err != nil {
 307  			return res, err
 308  		}
 309  		if err := emit(cfg, epochStart, epochEnd, scripts, &res); err != nil {
 310  			return res, err
 311  		}
 312  		// The table is written even when verifying: it is the state the walk
 313  		// carries from one epoch to the next, not an output. Only the filters and
 314  		// the fold are skipped.
 315  		if err := Merge(table, nextTable, spent, created); err != nil {
 316  			return res, err
 317  		}
 318  		res.Tables++
 319  		res.MaxCreated = max(res.MaxCreated, len(created))
 320  		res.MaxSpent = max(res.MaxSpent, len(spent))
 321  		cfg.Logf("filterbuild: epoch %d..%d, %d spends, %d creations, table %s",
 322  			epochStart, epochEnd-1, len(spent), len(created), nextTable)
 323  		table = nextTable
 324  	}
 325  	return res, nil
 326  }
 327  
 328  // collect reads the epoch once and returns what it spent, what it created, and
 329  // per block the scripts it needs from elsewhere.
 330  func collect(cfg Config, from, to uint32) (spent map[wire.OutPoint]bool, created []Entry, err error) {
 331  	spent = make(map[wire.OutPoint]bool, 4096)
 332  	for h := from; h < to; h++ {
 333  		raw, err := cfg.Blocks.Block(h)
 334  		if err != nil {
 335  			return nil, nil, fmt.Errorf("filterbuild: block %d: %w", h, err)
 336  		}
 337  		b, err := wire.ParseBlock(raw)
 338  		if err != nil {
 339  			return nil, nil, fmt.Errorf("filterbuild: block %d: %w", h, err)
 340  		}
 341  		for i := range b.Txs {
 342  			tx := &b.Txs[i]
 343  			txid := tx.TxID()
 344  			for j := range tx.TxOut {
 345  				script := tx.TxOut[j].PkScript
 346  				// An unspendable output never needs its script again: no
 347  				// consensus rule forbids spending one, but the filter element
 348  				// set already excludes it, so the table would carry dead bytes.
 349  				if filter.IsUnspendable(script) {
 350  					continue
 351  				}
 352  				created = append(created, Entry{OutPoint: wire.OutPoint{Hash: txid, Index: uint32(j)}, Script: script})
 353  			}
 354  		}
 355  		for i := range b.Txs {
 356  			tx := &b.Txs[i]
 357  			if i == 0 && tx.IsCoinBase() {
 358  				continue
 359  			}
 360  			for j := range tx.TxIn {
 361  				// A spend of an output the same block creates is answered by
 362  				// filter.Elements from the block itself, so it does not need
 363  				// the table; marking it spent would only drop a creation.
 364  				spent[tx.TxIn[j].PreviousOutPoint] = true
 365  			}
 366  		}
 367  	}
 368  	return spent, created, nil
 369  }
 370  
 371  // join streams the table and returns the script of every outpoint the epoch
 372  // spent.
 373  func join(cfg Config, table string, spent map[wire.OutPoint]bool) (map[wire.OutPoint][]byte, error) {
 374  	out := make(map[wire.OutPoint][]byte, len(spent))
 375  	if table == "" || len(spent) == 0 {
 376  		return out, nil
 377  	}
 378  	if _, err := os.Stat(table); os.IsNotExist(err) {
 379  		// No table means nothing was unspent when this epoch started, which is
 380  		// only true at height 0.
 381  		return out, nil
 382  	}
 383  	r, err := Open(table)
 384  	if err != nil {
 385  		return nil, err
 386  	}
 387  	defer r.Close()
 388  	for {
 389  		e, ok, err := r.Next()
 390  		if err != nil {
 391  			return nil, err
 392  		}
 393  		if !ok {
 394  			break
 395  		}
 396  		if spent[e.OutPoint] {
 397  			out[e.OutPoint] = e.Script
 398  		}
 399  	}
 400  	return out, nil
 401  }
 402  
 403  // emit walks the epoch again and writes each block's filter and fold record.
 404  func emit(cfg Config, from, to uint32, scripts map[wire.OutPoint][]byte, res *Result) error {
 405  	// made is what this epoch has created so far. A block may spend an output
 406  	// an earlier block of the same epoch made, and the table only holds what
 407  	// existed before the epoch: the first transaction ever to spend a coinbase
 408  	// is block 170 spending block 9's, both inside the first epoch.
 409  	made := make(map[wire.OutPoint][]byte, 4096)
 410  	for h := from; h < to; h++ {
 411  		raw, err := cfg.Blocks.Block(h)
 412  		if err != nil {
 413  			return fmt.Errorf("filterbuild: block %d: %w", h, err)
 414  		}
 415  		b, err := wire.ParseBlock(raw)
 416  		if err != nil {
 417  			return fmt.Errorf("filterbuild: block %d: %w", h, err)
 418  		}
 419  		lookup := func(op wire.OutPoint) ([]byte, bool) {
 420  			if s, ok := made[op]; ok {
 421  				return s, true
 422  			}
 423  			s, ok := scripts[op]
 424  			return s, ok
 425  		}
 426  		f, err := filter.Build(b, lookup)
 427  		if err != nil {
 428  			return fmt.Errorf("filterbuild: filter %d: %w", h, err)
 429  		}
 430  		// This block's outputs are spendable by the blocks after it, not by
 431  		// itself: filter.Elements answers a same-block spend from the block.
 432  		for i := range b.Txs {
 433  			tx := &b.Txs[i]
 434  			txid := tx.TxID()
 435  			for j := range tx.TxOut {
 436  				if filter.IsUnspendable(tx.TxOut[j].PkScript) {
 437  					continue
 438  				}
 439  				made[wire.OutPoint{Hash: txid, Index: uint32(j)}] = tx.TxOut[j].PkScript
 440  			}
 441  		}
 442  		fh := filter.Hash(f)
 443  		var prev chainhash.Hash
 444  		if h > 0 {
 445  			p, ok := cfg.Folds[0].FilterHeader(h - 1)
 446  			if !ok {
 447  				return fmt.Errorf("filterbuild: no filter header at %d to fold from", h-1)
 448  			}
 449  			prev = p
 450  		}
 451  		next := filter.Fold(fh, prev)
 452  		if cfg.Verify {
 453  			res.Checked++
 454  			stored, err := cfg.Filters.Get(b.BlockHash())
 455  			if err != nil {
 456  				return fmt.Errorf("filterbuild: no stored filter at %d: %w", h, err)
 457  			}
 458  			recorded, ok := cfg.Folds[0].FilterHeader(h)
 459  			if !ok {
 460  				return fmt.Errorf("filterbuild: no stored filter header at %d", h)
 461  			}
 462  			if string(stored) != string(f) || recorded != next {
 463  				res.Differed++
 464  				if res.FirstDifference == 0 {
 465  					res.FirstDifference = h
 466  				}
 467  				cfg.Logf("filterbuild: height %d differs from the bodies", h)
 468  			}
 469  			continue
 470  		}
 471  		for _, fold := range cfg.Folds {
 472  			if err := fold.PutFilterHeaderRecord(h, fh, next); err != nil {
 473  				return fmt.Errorf("filterbuild: filter header %d: %w", h, err)
 474  			}
 475  		}
 476  		if err := cfg.Filters.Put(b.BlockHash(), f); err != nil {
 477  			return fmt.Errorf("filterbuild: store filter %d: %w", h, err)
 478  		}
 479  		res.Filters++
 480  	}
 481  	return nil
 482  }
 483