// Package utxobuild makes a chain's canonical UTXO set out of block bodies, // one snapshot per retarget and one diff per block, and builds the chain's // compact filters on the same walk. // // It is not a validator. It reads the outputs each block funds and the outpoints // it spends, and it trusts the bodies it is given: the caller is the processing // pass, which checked every body against the header it was asked for. // // The snapshot cadence is the chain's retarget interval, not a flag. A snapshot // lands at every height that is a multiple of it, so the boundaries are the ones // the chain already has, and between two of them there is one diff per block: // the touches of exactly one height, which is the degenerate range a merge // already handles. package utxobuild import ( "errors" "fmt" "git.smesh.lol/nostrino/pkg/crypto/chainhash" "git.smesh.lol/btcd-lite/internal/store" "git.smesh.lol/btcd-lite/internal/utxo" utxostore "git.smesh.lol/btcd-lite/internal/utxo/store" "git.smesh.lol/btcd-lite/internal/wire" ) // BlockSource is where the bodies come from: one block at a height. type BlockSource interface { Block(height uint32) ([]byte, error) } // Config is what a build needs. type Config struct { // Dir is where the snapshots are written. Dir string // DiffDir is where the per-block diffs are written. It is a separate // directory because a diff belongs to a block and a snapshot belongs to a // chain at a height: the shared prefix's diffs are written once. DiffDir string // Chain names the walk in the log lines. It selects nothing. Chain string // Interval is how many blocks between snapshots: the chain's retarget // interval, from chains.ExportedChain.Retarget. Interval uint32 // From and To are the heights to cover, half-open. From, To uint32 // Start is the set the replay begins from. A streamed walk ignores it: it // reads the snapshot on disk at From, which is why it can start above height // 0 without rebuilding the chain to learn what the set holds. Start []utxo.Entry // BaseDir is where the snapshot the walk starts from is read, when it is not // Dir. A chain continuing a shared prefix reads the prefix's snapshot where // the prefix wrote it. BaseDir string // DiffFrom is the first height whose diff this walk writes. It is zero for a // chain's own dataset and the fork point for a chain that continues from a // shared prefix: the prefix's diffs are written once, by the prefix's walk, // and a second copy in a chain's directory would be the same bytes under a // second name. DiffFrom uint32 // Blocks supplies the bodies. Blocks BlockSource // Logf receives progress; nil discards it. Logf func(string, ...any) } // Result is what a walk leaves: the set it ended with, the height it ended at, // and the name of the last snapshot it wrote. // // The set is here because the next walk of the same chain starts from it. A // shared prefix is walked once and both chains continue from the set it ends // with, so no second walk reloads a snapshot and replays an epoch to learn what // it already had in memory. type Result struct { Set []utxo.Entry Height uint32 Name chainhash.Hash } // Build walks blocks From..To of one chain, writing one diff per block, a // snapshot at every retarget height, and a filter per block when the config asks // for them. The heights are the blocks themselves: a snapshot at H is the set // after block H, and the diff of block H takes the set at H-1 to the set at H. // // The set is carried in memory between snapshots and laid down as a file at // each one, so a client reaches a snapshot without replay and reaches anything // between two of them by applying the per-block diffs that follow. // // The filter build needs the scriptPubKey of every output a block spends, and a // block does not carry them, so the walk keeps them: the scripts of unspent // outputs live in memory alongside the set and are dropped when they are spent. // That is the price of building filters at all, and it is why the filter build // is here and not in the processing pass, which sees one block at a time and // could not answer for an output spent by a later block. func Build(cfg Config) (Result, error) { if cfg.Interval == 0 { return Result{}, errors.New("utxobuild: the interval is required") } if cfg.To <= cfg.From { return Result{}, fmt.Errorf("utxobuild: range %d..%d is empty", cfg.From, cfg.To) } if cfg.From > 0 && cfg.Start == nil { return Result{}, fmt.Errorf("utxobuild: a walk from %d needs the set it starts from", cfg.From) } if err := utxo.Validate(cfg.Start); err != nil { return Result{}, fmt.Errorf("utxobuild: start set: %w", err) } if cfg.Logf == nil { cfg.Logf = func(string, ...any) {} } if cfg.DiffDir == "" { // A caller with one directory keeps both artifacts in it; a caller // that splits them says where the diffs go. cfg.DiffDir = cfg.Dir } set := cfg.Start last := chainhash.Hash{} for h := cfg.From; h < cfg.To; h++ { raw, err := cfg.Blocks.Block(h) if err != nil { return Result{}, fmt.Errorf("utxobuild: block %d: %w", h, err) } b, err := wire.ParseBlock(raw) if err != nil { return Result{}, fmt.Errorf("utxobuild: block %d: %w", h, err) } // The lookup is the set being built: an input the set does not hold is // not a spend of anything, and BlockTouches records it as a spend the // set will refuse, which is how a body that spends outside its own // chain shows up instead of being swallowed. ts, err := utxo.BlockTouches(b, h, utxo.Lookup(func(op wire.OutPoint) (utxo.Entry, bool) { return utxo.Find(set, op) })) if err != nil { return Result{}, fmt.Errorf("utxobuild: block %d: %w", h, err) } set, err = utxo.ApplyRange(set, ts) if err != nil { return Result{}, fmt.Errorf("utxobuild: block %d: %w", h, err) } // The diff of block h takes the set at h-1 to the set at h, so it is // named for that step. Block 0 has no predecessor: its effects are in // the snapshot at 0, which is where every client starts. if h > 0 { if _, err := utxostore.CutRange(cfg.DiffDir, h-1, h, ts); err != nil { return Result{}, fmt.Errorf("utxobuild: diff %d: %w", h, err) } } debugSet(h, len(set), utxostore.NameOf(set)) if h%cfg.Interval != 0 { continue } name, err := utxostore.WriteSetFile(cfg.Dir, h, set) if err != nil { return Result{}, err } last = name cfg.Logf("utxobuild %s: snapshot at %d, %d entries, %s", cfg.Chain, h, len(set), name) debugCheckpoint(h, name, name) } return Result{Set: set, Height: cfg.To, Name: last}, nil } // debugSet and debugCheckpoint are switches a test flips to see the walk's name // at every block and the name of each snapshot. var debugSet = func(height uint32, entries int, name chainhash.Hash) {} var debugCheckpoint = func(to uint32, merged, walked chainhash.Hash) {} // Debug installs those switches from outside the package. Passing nil disables // one of them. func Debug(set func(uint32, int, chainhash.Hash), checkpoint func(uint32, chainhash.Hash, chainhash.Hash)) { debugSet = func(uint32, int, chainhash.Hash) {} debugCheckpoint = func(uint32, chainhash.Hash, chainhash.Hash) {} if set != nil { debugSet = set } if checkpoint != nil { debugCheckpoint = checkpoint } } // StoreSource adapts a body store to a BlockSource through a chain's header // store, which is where a height resolves to a hash. The body store is keyed by // hash alone, so it cannot answer a height on its own. type StoreSource struct { S *store.BlockStore Headers *store.HeaderStore } // Block returns one body. func (s StoreSource) Block(height uint32) ([]byte, error) { hdr, ok := s.Headers.Header(height) if !ok { return nil, fmt.Errorf("utxobuild: no header at %d", height) } return s.S.GetBlock(hdr.BlockHash()) }