package main import ( "encoding/json" "fmt" "net/http" "os" "path/filepath" "time" "git.smesh.lol/btcd-lite/internal/chains" "git.smesh.lol/btcd-lite/internal/filterbuild" "git.smesh.lol/btcd-lite/internal/filterstore" "git.smesh.lol/btcd-lite/internal/logging" "git.smesh.lol/btcd-lite/internal/store" utxoserve "git.smesh.lol/btcd-lite/internal/utxo/serve" "git.smesh.lol/btcd-lite/internal/utxobuild" ) // utxoDirs is where one chain's dataset lives: the shared prefix's snapshots // and diffs first, the chain's own second. func utxoDirs(data, chainName string) (sets, diffs []string) { utxo := filepath.Join(data, "utxo") return []string{filepath.Join(utxo, "canonical"), filepath.Join(utxo, "chain-"+chainName)}, []string{filepath.Join(utxo, "diff", "shared"), filepath.Join(utxo, "diff", chainName)} } // utxoHandler answers one chain's UTXO dataset on the service's mux. func mountUTXO(mux *http.ServeMux, c utxoserve.Chain) { utxoserve.Routes(mux, c) } // builtFile records how far each chain's dataset covers, so a restart does not // rebuild one that is already complete. func builtFile(data string) string { return filepath.Join(data, "utxo", "built.json") } type builtState struct { Tips map[string]uint32 `json:"tips"` } func readBuilt(data string) builtState { s := builtState{Tips: map[string]uint32{}} raw, err := os.ReadFile(builtFile(data)) if err != nil { return s } _ = json.Unmarshal(raw, &s) if s.Tips == nil { s.Tips = map[string]uint32{} } return s } func writeBuilt(data string, s builtState) error { raw, err := json.MarshalIndent(s, "", " ") if err != nil { return err } if err := os.MkdirAll(filepath.Dir(builtFile(data)), 0o755); err != nil { return err } return os.WriteFile(builtFile(data), raw, 0o644) } // ensureUTXO builds the dataset for every chain that has headers, or leaves the // one that is already there, and returns the routes to mount. // // The shared prefix is walked once and each chain continues from where it // ended, which is what utxobuild.BuildChains does: one diff per block, one // snapshot per retarget height, one filter per block, and the filters' fold // written into every chain's header store. func ensureUTXO(data string, names []string, headers map[string]*store.HeaderStore, bodies *store.BlockStore, filters *filterstore.Store, interval uint32, rebuild, filtersOnly, verify bool, to uint32, lg *logging.Logger) []utxoserve.Chain { built := readBuilt(data) tips := map[string]uint32{} var ready []string for _, name := range names { tip, _, ok := headers[name].HeaderTip() if !ok || tip == 0 { lg.Warnf("utxo: %s has no headers yet; not building a dataset for it", name) continue } ready = append(ready, name) tips[name] = tip } if len(ready) == 0 { return nil } complete := !rebuild for _, name := range ready { if built.Tips[name] < tips[name] { complete = false } } if filtersOnly { // Filters and the UTXO set are separate datasets now, and the filters // need no set: a host that cannot hold one can still build them. if err := buildFilters(data, ready, headers, bodies, filters, interval, tips, verify, to, lg); err != nil { lg.Errorf("filters: %v", err) return nil } complete = true } if !complete { if err := buildDataset(data, ready, headers, bodies, filters, interval, tips, lg); err != nil { lg.Errorf("utxo: building the dataset: %v", err) return nil } if err := writeBuilt(data, builtState{Tips: tips}); err != nil { lg.Warnf("utxo: recording coverage: %v", err) } } else { lg.Infof("utxo: serving the dataset already in %s, up to %v", filepath.Join(data, "utxo"), tips) } out := make([]utxoserve.Chain, 0, len(ready)) for _, name := range ready { sets, diffs := utxoDirs(data, name) out = append(out, utxoserve.Chain{Name: name, Sets: sets, Diffs: diffs, Interval: interval}) } return out } // buildFilters builds every chain's filters from bodies and stops. func buildFilters(data string, names []string, headers map[string]*store.HeaderStore, bodies *store.BlockStore, filters *filterstore.Store, interval uint32, tips map[string]uint32, verify bool, to uint32, lg *logging.Logger) error { for _, name := range names { if to > 0 && to < tips[name] { tips[name] = to } } return buildFiltersFor(data, names, headers, bodies, filters, interval, tips, verify, lg) } // buildFiltersFor is the one filter pass: internal/filterbuild per chain. func buildFiltersFor(data string, names []string, headers map[string]*store.HeaderStore, bodies *store.BlockStore, filters *filterstore.Store, interval uint32, tips map[string]uint32, verify bool, lg *logging.Logger) error { for _, name := range names { start := time.Now() res, err := filterbuild.Build(filterbuild.Config{ Dir: filepath.Join(data, "build", "scripts", name), From: 0, To: tips[name] + 1, Interval: interval, Blocks: utxobuild.StoreSource{S: bodies, Headers: headers[name]}, Filters: filters, Folds: []*store.HeaderStore{headers[name]}, Verify: verify, Logf: lg.Logf, }) if err != nil { return fmt.Errorf("%s filters: %w", name, err) } if verify { lg.Infof("filters: %s verified %d of %d heights, %d differed, in %s", name, res.Checked-res.Differed, res.Checked, res.Differed, time.Since(start).Round(time.Second)) if res.Differed > 0 { lg.Errorf("filters: %s first difference at height %d", name, res.FirstDifference) } continue } lg.Infof("filters: %s built %d from bodies in %d epochs in %s", name, res.Filters, res.Tables, time.Since(start).Round(time.Second)) } return nil } // buildDataset builds the filters and then the sets. // // Filters come from internal/filterbuild, which keeps the script of every // unspent output in a sorted file and streams it, so the build needs one epoch // in memory and not the whole set. The sets come from utxobuild, which no longer // touches filters at all: an entry carries a script hash, not a script, and // asking it to build filters is what used to hold tens of gigabytes. func buildDataset(data string, names []string, headers map[string]*store.HeaderStore, bodies *store.BlockStore, filters *filterstore.Store, interval uint32, tips map[string]uint32, lg *logging.Logger) error { // A fold this instance synced from a peer already covers the chain, and the // filter bodies are stored under their block hashes. Building them again // would fight for the same records: the fold is dense from height 0 and // append-only, so a second writer cannot add to it. buildFilters := false for _, name := range names { if tip, _, ok := headers[name].FilterHeaderTip(); !ok || tip < tips[name] { buildFilters = true } } if buildFilters { if err := buildFiltersFor(data, names, headers, bodies, filters, interval, tips, false, lg); err != nil { return err } } else { lg.Infof("utxo: filters are already synced to the tip; building the sets only") } inputs := make([]utxobuild.ChainInput, 0, len(names)) for _, name := range names { inputs = append(inputs, utxobuild.ChainInput{ Name: name, Tip: tips[name], Blocks: utxobuild.StoreSource{S: bodies, Headers: headers[name]}, }) } res, err := utxobuild.BuildChains(utxobuild.ChainsConfig{ Dir: filepath.Join(data, "utxo"), Interval: interval, SharedLast: chains.SharedLastHeight, Chains: inputs, Logf: lg.Logf, }) if err != nil { return err } for _, c := range inputs { lg.Infof("utxo: %s dataset ends at %d, %d entries", c.Name, res[c.Name].Height, len(res[c.Name].Set)) } return nil }