package utxobuild import ( "bufio" "fmt" "io" "os" "path/filepath" "git.smesh.lol/nostrino/pkg/crypto/chainhash" "git.smesh.lol/btcd-lite/internal/utxo" "git.smesh.lol/btcd-lite/internal/utxo/store" "git.smesh.lol/btcd-lite/internal/wire" ) // BuildStream walks the same blocks as Build and writes the same diffs and // snapshots, but it never holds the set: it works one epoch at a time, with the // entries that epoch touches in memory and everything else on disk. // // The pieces are one pass over the epoch's blocks to learn what it spends and // creates, a streamed join of those spends against the snapshot the epoch starts // from, and a second pass that applies the blocks in order against that overlay, // writing each block's diff and the diff of the whole epoch. The snapshot at the // epoch's end comes from utxostore.MergeRange, which streams the base alongside // the epoch's diff. // // The cost is the epoch: at 2016 blocks on mainnet, about five million touches, // which is a few hundred megabytes. Build holds the chain, which is four // gigabytes on a good day and the whole point of this path. func BuildStream(cfg Config) (Result, error) { if cfg.Interval == 0 { return Result{}, fmt.Errorf("utxobuild: the interval is required") } if cfg.To <= cfg.From { return Result{}, fmt.Errorf("utxobuild: nothing to walk, %d to %d", cfg.From, cfg.To) } if cfg.From%cfg.Interval != 0 { return Result{}, fmt.Errorf("utxobuild: a streamed walk starts on a snapshot, and %d is not one", cfg.From) } if cfg.Logf == nil { cfg.Logf = func(string, ...any) {} } // MergeRange writes its key files beside the snapshot it reads, so the // snapshot directory has to exist before the first epoch, not after. for _, dir := range []string{cfg.Dir, cfg.DiffDir} { if err := os.MkdirAll(dir, 0o755); err != nil { return Result{}, fmt.Errorf("utxobuild: %w", err) } } var res Result res.Height = cfg.To // A snapshot at H is the set after block H, so an epoch that starts at a // snapshot covers the blocks above it: base+1 through base+Interval. Height 0 // has no predecessor to merge from, so its snapshot comes from block 0 alone, // which is one block of touches. base := cfg.From if base == 0 { name, err := seedZero(cfg) if err != nil { return res, err } res.Name = name cfg.Logf("utxobuild %s: snapshot at 0, %s", cfg.Chain, name) } for base+cfg.Interval <= cfg.To { to := base + cfg.Interval from := base + 1 if base == 0 { from = 1 } // The snapshot at to is after block to, so the epoch's blocks are // base+1 through to inclusive: the bound handed to the walk is exclusive. touches, err := walk(cfg, base, from, to+1) if err != nil { return res, err } name, err := utxostore.MergeRangeFrom(cfg.baseDir(), cfg.Dir, base, to, utxo.Diff{From: base, To: to, Touches: touches}, chainhash.Hash{}) if err != nil { return res, fmt.Errorf("utxobuild: snapshot %d: %w", to, err) } res.Name = name cfg.Logf("utxobuild %s: snapshot at %d, epoch %d..%d with %d touches, %s", cfg.Chain, to, from, to, len(touches), name) base = to } // The tail after the last snapshot boundary still has a diff per block: a // client reaches those heights by applying them to the last snapshot. if base+1 < cfg.To { if _, err := walk(cfg, base, base+1, cfg.To); err != nil { return res, err } } return res, nil } // baseDir is where the snapshot the walk starts from is read. func (cfg Config) baseDir() string { if cfg.BaseDir != "" { return cfg.BaseDir } return cfg.Dir } // seedZero writes the snapshot at height 0: the set after block 0, which is the // genesis block's outputs and nothing else. func seedZero(cfg Config) (chainhash.Hash, error) { b, err := readBlock(cfg, 0) if err != nil { return chainhash.Hash{}, err } ts, err := utxo.BlockTouches(b, 0, nil) if err != nil { return chainhash.Hash{}, fmt.Errorf("utxobuild: block 0: %w", err) } set, err := utxo.ApplyRange(nil, ts) if err != nil { return chainhash.Hash{}, fmt.Errorf("utxobuild: block 0: %w", err) } return utxostore.WriteSetFile(cfg.Dir, 0, set) } // walk applies blocks from..to to the overlay the snapshot at base resolves, and // returns the range's touches. It writes each block's diff, and nothing else: // whether a snapshot follows is the caller's business. // // The epoch is resolved in three steps: a pass over the blocks with no lookup to // learn what they spend and create, a streamed join that pulls the entry of every // spent outpoint out of the snapshot, and then the application itself, which // keeps the overlay current so a block may spend what a previous block made. func walk(cfg Config, base, from, to uint32) ([]utxo.Touch, error) { spends := make(map[wire.OutPoint]bool, 4096) for h := from; h < to; h++ { b, err := readBlock(cfg, h) if err != nil { return nil, err } ts, err := utxo.BlockTouches(b, h, nil) if err != nil { return nil, fmt.Errorf("utxobuild: block %d: %w", h, err) } for i := range ts { if ts[i].Spent { spends[ts[i].OutPoint] = true } } } overlay, err := loadTouched(cfg, base, spends) if err != nil { return nil, err } touches := make([]utxo.Touch, 0, len(spends)*2) for h := from; h < to; h++ { b, err := readBlock(cfg, h) if err != nil { return nil, err } ts, err := utxo.BlockTouches(b, h, func(op wire.OutPoint) (utxo.Entry, bool) { e, ok := overlay[op] return e, ok }) if err != nil { return nil, fmt.Errorf("utxobuild: block %d: %w", h, err) } for j := range ts { if ts[j].Spent { delete(overlay, ts[j].OutPoint) continue } overlay[ts[j].OutPoint] = ts[j].New } touches = append(touches, ts...) if h > 0 && h >= cfg.DiffFrom { if _, err := utxostore.CutRange(cfg.DiffDir, h-1, h, ts); err != nil { return nil, fmt.Errorf("utxobuild: diff %d: %w", h, err) } } } return touches, nil } // loadTouched streams the snapshot the epoch starts from and returns the entry // of every outpoint the epoch spends. A spend of an outpoint the snapshot does // not hold is either a spend of an output the epoch itself creates, which the // overlay answers, or a body that spends nothing, which BlockTouches refuses. func loadTouched(cfg Config, from uint32, spends map[wire.OutPoint]bool) (map[wire.OutPoint]utxo.Entry, error) { out := make(map[wire.OutPoint]utxo.Entry, len(spends)) if from == 0 || len(spends) == 0 { return out, nil } f, err := os.Open(filepath.Join(cfg.baseDir(), utxostore.SetFile(from))) if err != nil { return nil, fmt.Errorf("utxobuild: snapshot %d: %w", from, err) } defer f.Close() r := bufio.NewReaderSize(f, 1<<20) buf := make([]byte, utxo.EntryEncodeSize) for { if _, err := io.ReadFull(r, buf); err != nil { if err == io.EOF { break } return nil, fmt.Errorf("utxobuild: snapshot %d: %w", from, err) } e := utxo.Decode(buf) if spends[e.OutPoint] { out[e.OutPoint] = e } } return out, nil } // readBlock reads one body and parses it. func readBlock(cfg Config, h uint32) (*wire.Block, error) { raw, err := cfg.Blocks.Block(h) if err != nil { return nil, fmt.Errorf("utxobuild: block %d: %w", h, err) } b, err := wire.ParseBlock(raw) if err != nil { return nil, fmt.Errorf("utxobuild: block %d: %w", h, err) } return b, nil }