utxo.go raw
1 package main
2
3 import (
4 "encoding/json"
5 "fmt"
6 "net/http"
7 "os"
8 "path/filepath"
9 "time"
10
11 "git.smesh.lol/btcd-lite/internal/chains"
12 "git.smesh.lol/btcd-lite/internal/filterbuild"
13 "git.smesh.lol/btcd-lite/internal/filterstore"
14 "git.smesh.lol/btcd-lite/internal/logging"
15 "git.smesh.lol/btcd-lite/internal/store"
16 utxoserve "git.smesh.lol/btcd-lite/internal/utxo/serve"
17 "git.smesh.lol/btcd-lite/internal/utxobuild"
18 )
19
20 // utxoDirs is where one chain's dataset lives: the shared prefix's snapshots
21 // and diffs first, the chain's own second.
22 func utxoDirs(data, chainName string) (sets, diffs []string) {
23 utxo := filepath.Join(data, "utxo")
24 return []string{filepath.Join(utxo, "canonical"), filepath.Join(utxo, "chain-"+chainName)},
25 []string{filepath.Join(utxo, "diff", "shared"), filepath.Join(utxo, "diff", chainName)}
26 }
27
28 // utxoHandler answers one chain's UTXO dataset on the service's mux.
29 func mountUTXO(mux *http.ServeMux, c utxoserve.Chain) {
30 utxoserve.Routes(mux, c)
31 }
32
33 // builtFile records how far each chain's dataset covers, so a restart does not
34 // rebuild one that is already complete.
35 func builtFile(data string) string { return filepath.Join(data, "utxo", "built.json") }
36
37 type builtState struct {
38 Tips map[string]uint32 `json:"tips"`
39 }
40
41 func readBuilt(data string) builtState {
42 s := builtState{Tips: map[string]uint32{}}
43 raw, err := os.ReadFile(builtFile(data))
44 if err != nil {
45 return s
46 }
47 _ = json.Unmarshal(raw, &s)
48 if s.Tips == nil {
49 s.Tips = map[string]uint32{}
50 }
51 return s
52 }
53
54 func writeBuilt(data string, s builtState) error {
55 raw, err := json.MarshalIndent(s, "", " ")
56 if err != nil {
57 return err
58 }
59 if err := os.MkdirAll(filepath.Dir(builtFile(data)), 0o755); err != nil {
60 return err
61 }
62 return os.WriteFile(builtFile(data), raw, 0o644)
63 }
64
65 // ensureUTXO builds the dataset for every chain that has headers, or leaves the
66 // one that is already there, and returns the routes to mount.
67 //
68 // The shared prefix is walked once and each chain continues from where it
69 // ended, which is what utxobuild.BuildChains does: one diff per block, one
70 // snapshot per retarget height, one filter per block, and the filters' fold
71 // written into every chain's header store.
72 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 {
73 built := readBuilt(data)
74 tips := map[string]uint32{}
75 var ready []string
76 for _, name := range names {
77 tip, _, ok := headers[name].HeaderTip()
78 if !ok || tip == 0 {
79 lg.Warnf("utxo: %s has no headers yet; not building a dataset for it", name)
80 continue
81 }
82 ready = append(ready, name)
83 tips[name] = tip
84 }
85 if len(ready) == 0 {
86 return nil
87 }
88 complete := !rebuild
89 for _, name := range ready {
90 if built.Tips[name] < tips[name] {
91 complete = false
92 }
93 }
94 if filtersOnly {
95 // Filters and the UTXO set are separate datasets now, and the filters
96 // need no set: a host that cannot hold one can still build them.
97 if err := buildFilters(data, ready, headers, bodies, filters, interval, tips, verify, to, lg); err != nil {
98 lg.Errorf("filters: %v", err)
99 return nil
100 }
101 complete = true
102 }
103 if !complete {
104 if err := buildDataset(data, ready, headers, bodies, filters, interval, tips, lg); err != nil {
105 lg.Errorf("utxo: building the dataset: %v", err)
106 return nil
107 }
108 if err := writeBuilt(data, builtState{Tips: tips}); err != nil {
109 lg.Warnf("utxo: recording coverage: %v", err)
110 }
111 } else {
112 lg.Infof("utxo: serving the dataset already in %s, up to %v", filepath.Join(data, "utxo"), tips)
113 }
114 out := make([]utxoserve.Chain, 0, len(ready))
115 for _, name := range ready {
116 sets, diffs := utxoDirs(data, name)
117 out = append(out, utxoserve.Chain{Name: name, Sets: sets, Diffs: diffs, Interval: interval})
118 }
119 return out
120 }
121
122 // buildFilters builds every chain's filters from bodies and stops.
123 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 {
124 for _, name := range names {
125 if to > 0 && to < tips[name] {
126 tips[name] = to
127 }
128 }
129 return buildFiltersFor(data, names, headers, bodies, filters, interval, tips, verify, lg)
130 }
131
132 // buildFiltersFor is the one filter pass: internal/filterbuild per chain.
133 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 {
134 for _, name := range names {
135 start := time.Now()
136 res, err := filterbuild.Build(filterbuild.Config{
137 Dir: filepath.Join(data, "build", "scripts", name),
138 From: 0,
139 To: tips[name] + 1,
140 Interval: interval,
141 Blocks: utxobuild.StoreSource{S: bodies, Headers: headers[name]},
142 Filters: filters,
143 Folds: []*store.HeaderStore{headers[name]},
144 Verify: verify,
145 Logf: lg.Logf,
146 })
147 if err != nil {
148 return fmt.Errorf("%s filters: %w", name, err)
149 }
150 if verify {
151 lg.Infof("filters: %s verified %d of %d heights, %d differed, in %s",
152 name, res.Checked-res.Differed, res.Checked, res.Differed, time.Since(start).Round(time.Second))
153 if res.Differed > 0 {
154 lg.Errorf("filters: %s first difference at height %d", name, res.FirstDifference)
155 }
156 continue
157 }
158 lg.Infof("filters: %s built %d from bodies in %d epochs in %s",
159 name, res.Filters, res.Tables, time.Since(start).Round(time.Second))
160 }
161 return nil
162 }
163
164 // buildDataset builds the filters and then the sets.
165 //
166 // Filters come from internal/filterbuild, which keeps the script of every
167 // unspent output in a sorted file and streams it, so the build needs one epoch
168 // in memory and not the whole set. The sets come from utxobuild, which no longer
169 // touches filters at all: an entry carries a script hash, not a script, and
170 // asking it to build filters is what used to hold tens of gigabytes.
171 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 {
172 // A fold this instance synced from a peer already covers the chain, and the
173 // filter bodies are stored under their block hashes. Building them again
174 // would fight for the same records: the fold is dense from height 0 and
175 // append-only, so a second writer cannot add to it.
176 buildFilters := false
177 for _, name := range names {
178 if tip, _, ok := headers[name].FilterHeaderTip(); !ok || tip < tips[name] {
179 buildFilters = true
180 }
181 }
182 if buildFilters {
183 if err := buildFiltersFor(data, names, headers, bodies, filters, interval, tips, false, lg); err != nil {
184 return err
185 }
186 } else {
187 lg.Infof("utxo: filters are already synced to the tip; building the sets only")
188 }
189 inputs := make([]utxobuild.ChainInput, 0, len(names))
190 for _, name := range names {
191 inputs = append(inputs, utxobuild.ChainInput{
192 Name: name,
193 Tip: tips[name],
194 Blocks: utxobuild.StoreSource{S: bodies, Headers: headers[name]},
195 })
196 }
197 res, err := utxobuild.BuildChains(utxobuild.ChainsConfig{
198 Dir: filepath.Join(data, "utxo"),
199 Interval: interval,
200 SharedLast: chains.SharedLastHeight,
201 Chains: inputs,
202 Logf: lg.Logf,
203 })
204 if err != nil {
205 return err
206 }
207 for _, c := range inputs {
208 lg.Infof("utxo: %s dataset ends at %d, %d entries", c.Name, res[c.Name].Height, len(res[c.Name].Set))
209 }
210 return nil
211 }
212