// Package filterbuild computes BIP158 filters from block bodies, with the // scriptPubKey of every unspent output kept in a sorted file on disk instead of // in memory. // // A filter needs the script of every output a block spends, and a block carries // only the outpoints it spends. The walk therefore needs the scripts of outputs // created earlier, which is what the canonical set does not hold: its entries // keep an eight-byte script hash and nothing else. // // Two properties make this fit in a small host. The table is sorted by outpoint // and only ever streamed, because the epoch's spends are sorted and joined // against it in one pass, so no lookup is random. And only one epoch's touches // are held at a time: about five million outpoints at 2016 blocks, which is a // few hundred megabytes, not the tens of gigabytes a map of every unspent script // costs. package filterbuild import ( "bufio" "encoding/binary" "errors" "fmt" "io" "os" "path/filepath" "sort" "git.smesh.lol/nostrino/pkg/crypto/chainhash" "git.smesh.lol/btcd-lite/internal/filter" "git.smesh.lol/btcd-lite/internal/filterstore" "git.smesh.lol/btcd-lite/internal/store" "git.smesh.lol/btcd-lite/internal/utxo" "git.smesh.lol/btcd-lite/internal/wire" ) // Entry is one unspent output's script. type Entry struct { OutPoint wire.OutPoint Script []byte } // RecordSize is the fixed part of a record: outpoint (36) and script length (2). const RecordSize = 38 // sorted reports whether a is before b, by the one outpoint order the whole // project uses. func sorted(a, b Entry) bool { return utxo.CompareOutPoints(a.OutPoint, b.OutPoint) < 0 } // Writer appends sorted entries to a table file. type Writer struct { f *os.File w *bufio.Writer // last is the entry written last, so the writer refuses an unsorted // sequence rather than producing a file no merge can read. last Entry set bool } // Create starts a new table at path. func Create(path string) (*Writer, error) { if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { return nil, fmt.Errorf("filterbuild: %w", err) } f, err := os.Create(path) if err != nil { return nil, fmt.Errorf("filterbuild: %w", err) } return &Writer{f: f, w: bufio.NewWriterSize(f, 1<<20)}, nil } // Write appends one entry. Entries must arrive in outpoint order. func (w *Writer) Write(e Entry) error { if len(e.Script) == 0 || len(e.Script) > 0xffff { return fmt.Errorf("filterbuild: script of %d bytes", len(e.Script)) } if w.set && !sorted(w.last, e) { return fmt.Errorf("filterbuild: %s arrives after %s", e.OutPoint, w.last.OutPoint) } var rec [RecordSize]byte copy(rec[0:32], e.OutPoint.Hash[:]) binary.LittleEndian.PutUint32(rec[32:36], e.OutPoint.Index) binary.LittleEndian.PutUint16(rec[36:38], uint16(len(e.Script))) if _, err := w.w.Write(rec[:]); err != nil { return fmt.Errorf("filterbuild: %w", err) } if _, err := w.w.Write(e.Script); err != nil { return fmt.Errorf("filterbuild: %w", err) } w.last, w.set = e, true return nil } // Close flushes and closes the table. func (w *Writer) Close() error { if err := w.w.Flush(); err != nil { w.f.Close() return fmt.Errorf("filterbuild: %w", err) } if err := w.f.Sync(); err != nil { w.f.Close() return fmt.Errorf("filterbuild: %w", err) } return w.f.Close() } // Reader streams a table. type Reader struct { f *os.File r *bufio.Reader } // Open streams the table at path. func Open(path string) (*Reader, error) { f, err := os.Open(path) if err != nil { return nil, fmt.Errorf("filterbuild: %w", err) } return &Reader{f: f, r: bufio.NewReaderSize(f, 1<<20)}, nil } // Next returns the next entry, or false at the end. func (r *Reader) Next() (Entry, bool, error) { var rec [RecordSize]byte if _, err := io.ReadFull(r.r, rec[:]); err != nil { if errors.Is(err, io.EOF) { return Entry{}, false, nil } return Entry{}, false, fmt.Errorf("filterbuild: %w", err) } var e Entry copy(e.OutPoint.Hash[:], rec[0:32]) e.OutPoint.Index = binary.LittleEndian.Uint32(rec[32:36]) n := binary.LittleEndian.Uint16(rec[36:38]) e.Script = make([]byte, n) if _, err := io.ReadFull(r.r, e.Script); err != nil { return Entry{}, false, fmt.Errorf("filterbuild: short script: %w", err) } return e, true, nil } // Close closes the table. func (r *Reader) Close() error { return r.f.Close() } // writeUnique writes entries that are sorted, collapsing runs of the same // outpoint to the first. // // Two blocks can create one outpoint. Bitcoin has one such pair: the duplicate // coinbase transaction of blocks 91722 and 91880, which carry the same txid, so // both create the same output. A table is a set, so the second record is the // first record and writing it twice would make the file unmergeable. func writeUnique(w *Writer, entries []Entry) error { for i := range entries { if i > 0 && !sorted(entries[i-1], entries[i]) { if compare(entries[i-1].OutPoint, entries[i].OutPoint) == 0 { continue } } if w.set && compare(w.last.OutPoint, entries[i].OutPoint) == 0 { continue } if err := w.Write(entries[i]); err != nil { return err } } return nil } // compare orders two outpoints the way the table does. func compare(a, b wire.OutPoint) int { return utxo.CompareOutPoints(a, b) } // Merge writes old, minus the spent outpoints, plus the created entries, into // path. Both inputs must be in outpoint order. func Merge(oldPath, path string, spent map[wire.OutPoint]bool, created []Entry) error { sort.Slice(created, func(i, j int) bool { return sorted(created[i], created[j]) }) w, err := Create(path) if err != nil { return err } defer w.Close() if _, err := os.Stat(oldPath); os.IsNotExist(err) { if err := writeUnique(w, created); err != nil { return err } return w.Close() } r, err := Open(oldPath) if err != nil { return err } defer r.Close() old, ok, err := r.Next() if err != nil { return err } ci := 0 for { // Take whichever is next in outpoint order. takeOld := ok if ok && ci < len(created) && !sorted(old, created[ci]) { takeOld = false } if !ok && ci >= len(created) { break } if takeOld { if !spent[old.OutPoint] { if err := w.Write(old); err != nil { return err } } old, ok, err = r.Next() if err != nil { return err } continue } if err := writeUnique(w, created[ci:ci+1]); err != nil { return err } ci++ } return w.Close() } // Config is one build over a range of a chain. type Config struct { // Dir holds the table files: /scripts-.tab. Dir string // From and To are the heights to cover, half-open. From, To uint32 // Interval is the epoch length: the chain's retarget interval, which is // also the snapshot cadence. The table is rewritten at each boundary. Interval uint32 // Blocks supplies the bodies. Blocks interface { Block(height uint32) ([]byte, error) } // Filters receives one filter per block, keyed by the block's hash. Filters *filterstore.Store // Folds are the header stores that receive the filter hash and the folded // filter header at each height. Folds []*store.HeaderStore // Verify compares what is stored with what the bodies produce instead of // writing, which is how a chain of filters that came from a peer is checked // against the blocks this instance holds. Verify bool // Logf receives progress; nil discards it. Logf func(string, ...any) } // TablePath is where a table for a boundary height lives. func TablePath(dir string, height uint32) string { return filepath.Join(dir, fmt.Sprintf("scripts-%09d.tab", height)) } // Result is what a build wrote. type Result struct { Filters int // Tables is how many table rewrites were done. Tables int // Checked and Differed are the verification's counts: how many heights were // compared and how many disagreed with what the bodies produce. Checked int Differed int // FirstDifference is the lowest height that disagreed. FirstDifference uint32 // MaxCreated and MaxSpent are the largest single epoch's touch lists, which // is the memory the design costs: they must not grow with the chain, only // with the epochs, and a build that held the chain would grow them every // epoch. MaxCreated int MaxSpent int } // Build computes one filter per block over From..To, rewriting the script table // at every Interval. // // Each epoch is two reads of its blocks and one pass over the table: first to // collect the epoch's spends and creations, then a join that puts the script of // every spent outpoint in a map for that epoch, then a second read to build each // block's filter as the block ends. Only the epoch is in memory. func Build(cfg Config) (Result, error) { if cfg.Interval == 0 { return Result{}, errors.New("filterbuild: the interval is required") } if len(cfg.Folds) == 0 || cfg.Filters == nil { return Result{}, errors.New("filterbuild: filters and a fold store are required") } if cfg.Logf == nil { cfg.Logf = func(string, ...any) {} } var res Result table := "" if cfg.From > 0 { table = TablePath(cfg.Dir, cfg.From-cfg.From%cfg.Interval) } for epochStart := cfg.From; epochStart < cfg.To; epochStart += cfg.Interval { epochEnd := min(epochStart+cfg.Interval, cfg.To) nextTable := TablePath(cfg.Dir, epochEnd) spent, created, err := collect(cfg, epochStart, epochEnd) if err != nil { return res, err } scripts, err := join(cfg, table, spent) if err != nil { return res, err } if err := emit(cfg, epochStart, epochEnd, scripts, &res); err != nil { return res, err } // The table is written even when verifying: it is the state the walk // carries from one epoch to the next, not an output. Only the filters and // the fold are skipped. if err := Merge(table, nextTable, spent, created); err != nil { return res, err } res.Tables++ res.MaxCreated = max(res.MaxCreated, len(created)) res.MaxSpent = max(res.MaxSpent, len(spent)) cfg.Logf("filterbuild: epoch %d..%d, %d spends, %d creations, table %s", epochStart, epochEnd-1, len(spent), len(created), nextTable) table = nextTable } return res, nil } // collect reads the epoch once and returns what it spent, what it created, and // per block the scripts it needs from elsewhere. func collect(cfg Config, from, to uint32) (spent map[wire.OutPoint]bool, created []Entry, err error) { spent = make(map[wire.OutPoint]bool, 4096) for h := from; h < to; h++ { raw, err := cfg.Blocks.Block(h) if err != nil { return nil, nil, fmt.Errorf("filterbuild: block %d: %w", h, err) } b, err := wire.ParseBlock(raw) if err != nil { return nil, nil, fmt.Errorf("filterbuild: block %d: %w", h, err) } for i := range b.Txs { tx := &b.Txs[i] txid := tx.TxID() for j := range tx.TxOut { script := tx.TxOut[j].PkScript // An unspendable output never needs its script again: no // consensus rule forbids spending one, but the filter element // set already excludes it, so the table would carry dead bytes. if filter.IsUnspendable(script) { continue } created = append(created, Entry{OutPoint: wire.OutPoint{Hash: txid, Index: uint32(j)}, Script: script}) } } for i := range b.Txs { tx := &b.Txs[i] if i == 0 && tx.IsCoinBase() { continue } for j := range tx.TxIn { // A spend of an output the same block creates is answered by // filter.Elements from the block itself, so it does not need // the table; marking it spent would only drop a creation. spent[tx.TxIn[j].PreviousOutPoint] = true } } } return spent, created, nil } // join streams the table and returns the script of every outpoint the epoch // spent. func join(cfg Config, table string, spent map[wire.OutPoint]bool) (map[wire.OutPoint][]byte, error) { out := make(map[wire.OutPoint][]byte, len(spent)) if table == "" || len(spent) == 0 { return out, nil } if _, err := os.Stat(table); os.IsNotExist(err) { // No table means nothing was unspent when this epoch started, which is // only true at height 0. return out, nil } r, err := Open(table) if err != nil { return nil, err } defer r.Close() for { e, ok, err := r.Next() if err != nil { return nil, err } if !ok { break } if spent[e.OutPoint] { out[e.OutPoint] = e.Script } } return out, nil } // emit walks the epoch again and writes each block's filter and fold record. func emit(cfg Config, from, to uint32, scripts map[wire.OutPoint][]byte, res *Result) error { // made is what this epoch has created so far. A block may spend an output // an earlier block of the same epoch made, and the table only holds what // existed before the epoch: the first transaction ever to spend a coinbase // is block 170 spending block 9's, both inside the first epoch. made := make(map[wire.OutPoint][]byte, 4096) for h := from; h < to; h++ { raw, err := cfg.Blocks.Block(h) if err != nil { return fmt.Errorf("filterbuild: block %d: %w", h, err) } b, err := wire.ParseBlock(raw) if err != nil { return fmt.Errorf("filterbuild: block %d: %w", h, err) } lookup := func(op wire.OutPoint) ([]byte, bool) { if s, ok := made[op]; ok { return s, true } s, ok := scripts[op] return s, ok } f, err := filter.Build(b, lookup) if err != nil { return fmt.Errorf("filterbuild: filter %d: %w", h, err) } // This block's outputs are spendable by the blocks after it, not by // itself: filter.Elements answers a same-block spend from the block. for i := range b.Txs { tx := &b.Txs[i] txid := tx.TxID() for j := range tx.TxOut { if filter.IsUnspendable(tx.TxOut[j].PkScript) { continue } made[wire.OutPoint{Hash: txid, Index: uint32(j)}] = tx.TxOut[j].PkScript } } fh := filter.Hash(f) var prev chainhash.Hash if h > 0 { p, ok := cfg.Folds[0].FilterHeader(h - 1) if !ok { return fmt.Errorf("filterbuild: no filter header at %d to fold from", h-1) } prev = p } next := filter.Fold(fh, prev) if cfg.Verify { res.Checked++ stored, err := cfg.Filters.Get(b.BlockHash()) if err != nil { return fmt.Errorf("filterbuild: no stored filter at %d: %w", h, err) } recorded, ok := cfg.Folds[0].FilterHeader(h) if !ok { return fmt.Errorf("filterbuild: no stored filter header at %d", h) } if string(stored) != string(f) || recorded != next { res.Differed++ if res.FirstDifference == 0 { res.FirstDifference = h } cfg.Logf("filterbuild: height %d differs from the bodies", h) } continue } for _, fold := range cfg.Folds { if err := fold.PutFilterHeaderRecord(h, fh, next); err != nil { return fmt.Errorf("filterbuild: filter header %d: %w", h, err) } } if err := cfg.Filters.Put(b.BlockHash(), f); err != nil { return fmt.Errorf("filterbuild: store filter %d: %w", h, err) } res.Filters++ } return nil }