utxo_dataset_test.go raw
1 package gate
2
3 import (
4 "encoding/hex"
5 "errors"
6 "io"
7 "net/http"
8 "net/http/httptest"
9 "path/filepath"
10 "testing"
11
12 "git.smesh.lol/nostrino/pkg/crypto/chainhash"
13 "git.smesh.lol/nostrino/pkg/neutrino"
14
15 "git.smesh.lol/btcd-lite/internal/chains"
16 "git.smesh.lol/btcd-lite/internal/fetch"
17 "git.smesh.lol/btcd-lite/internal/store"
18 "git.smesh.lol/btcd-lite/internal/utxo"
19 utxoserve "git.smesh.lol/btcd-lite/internal/utxo/serve"
20 utxostore "git.smesh.lol/btcd-lite/internal/utxo/store"
21 "git.smesh.lol/btcd-lite/internal/utxobuild"
22 )
23
24 // mapSource is a block source over bodies already in memory, with a count of
25 // what the walk asked it for.
26 type mapSource struct {
27 bodies map[uint32][]byte
28 reads int
29 }
30
31 func (m *mapSource) Block(height uint32) ([]byte, error) {
32 raw, ok := m.bodies[height]
33 if !ok {
34 return nil, errNoBody
35 }
36 m.reads++
37 return raw, nil
38 }
39
40 var errNoBody = errors.New("gate: no body at that height")
41
42 // rpcBodies reads every raw block from the node over RPC, which is the fixture
43 // for a builder test: the transport is gated elsewhere and this keeps a
44 // three-hundred-block chain from taking minutes.
45 func rpcBodies(t *testing.T, r *rig, tip int) map[uint32][]byte {
46 t.Helper()
47 out := make(map[uint32][]byte, tip+1)
48 for h := 0; h <= tip; h++ {
49 hash := r.must(t, "getblockhash", itoa(h))
50 raw, err := hex.DecodeString(r.must(t, "getblock", hash, "0"))
51 if err != nil {
52 t.Fatalf("height %d: %v", h, err)
53 }
54 out[uint32(h)] = raw
55 }
56 return out
57 }
58
59 // anchoredHeaderStore is a header store with an anchor and no headers: it is
60 // what a filter fold needs, and nothing else here does.
61 func anchoredHeaderStore(t *testing.T, dir string, genesis chainhash.Hash) *store.HeaderStore {
62 t.Helper()
63 hs, err := store.NewHeaderStore(dir)
64 if err != nil {
65 t.Fatal(err)
66 }
67 t.Cleanup(func() { hs.Close() })
68 if err := hs.SetAnchor(neutrino.Anchor{Height: 0, BlockHash: genesis, FilterHeight: -1}); err != nil {
69 t.Fatal(err)
70 }
71 return hs
72 }
73
74 // TestSnapshotFiltersAndFold: the builder snapshots on the retarget heights and
75 // nowhere else, builds a filter per block that is the node's filter, and folds
76 // the filter headers into the chain's header store.
77 func TestSnapshotFiltersAndFold(t *testing.T) {
78 r := nodeOn(t)
79 r.createWallet(t)
80 r.mine(t, 300)
81 tip := r.height(t)
82 bodies := rpcBodies(t, r, tip)
83 src := &mapSource{bodies: bodies}
84 dir := t.TempDir()
85
86 interval := chains.Regtest().Exported.Retarget
87 if interval != 144 {
88 t.Fatalf("the regtest retarget is %d", interval)
89 }
90 if _, err := utxobuild.BuildChains(utxobuild.ChainsConfig{
91 Dir: filepath.Join(dir, "utxo"),
92 Interval: interval,
93 SharedLast: chains.SharedLastHeight,
94 Chains: []utxobuild.ChainInput{
95 {Name: "btc", Tip: uint32(tip), Blocks: src},
96 },
97 Logf: t.Logf,
98 }); err != nil {
99 t.Fatalf("build: %v", err)
100 }
101
102 // Snapshots at the retarget heights and nowhere else.
103 sets := filepath.Join(dir, "utxo", "canonical")
104 idx, err := utxoserve.Open(utxoserve.Chain{
105 Name: "btc", Sets: []string{sets},
106 Diffs: []string{filepath.Join(dir, "utxo", "diff", "shared")}, Interval: interval,
107 })
108 if err != nil {
109 t.Fatal(err)
110 }
111 var got []uint32
112 for h := uint32(0); h <= uint32(tip); h++ {
113 if _, ok := idx.Name(h); ok {
114 got = append(got, h)
115 }
116 }
117 want := []uint32{0, 144, 288}
118 if len(got) != len(want) {
119 t.Fatalf("snapshots at %v, want %v", got, want)
120 }
121 for i := range want {
122 if got[i] != want[i] {
123 t.Fatalf("snapshots at %v, want %v", got, want)
124 }
125 }
126
127 // Filters are no longer built here: internal/filterbuild owns them, and
128 // TestFiltersComputedFromBodies checks them byte for byte.
129 t.Logf("snapshots at %v", want)
130 }
131
132 // TestClientReachesAnyHeight: a client starts at a snapshot, applies per-block
133 // diffs, and arrives at the name the builder's walk gave every height.
134 func TestClientReachesAnyHeight(t *testing.T) {
135 r := nodeOn(t)
136 r.createWallet(t)
137 r.mine(t, 300)
138 tip := r.height(t)
139 bodies := rpcBodies(t, r, tip)
140 src := &mapSource{bodies: bodies}
141 dir := t.TempDir()
142 interval := chains.Regtest().Exported.Retarget
143
144 // The replay is the reference for the name at every height, including the
145 // heights between snapshots: it holds the set, so it can name one. The
146 // streamed walk cannot, and does not have to: the client's job is to arrive
147 // at the same set the replay would.
148 walk := map[uint32]chainhash.Hash{}
149 utxobuild.Debug(func(h uint32, entries int, name chainhash.Hash) {
150 walk[h] = name
151 }, nil)
152 defer utxobuild.Debug(nil, nil)
153 ref := t.TempDir()
154 if _, err := utxobuild.Build(utxobuild.Config{
155 Dir: filepath.Join(ref, "utxo"), DiffDir: filepath.Join(ref, "diff"),
156 Chain: "btc", Interval: interval, From: 0, To: uint32(tip) + 1,
157 Blocks: src, Logf: t.Logf,
158 }); err != nil {
159 t.Fatalf("replay: %v", err)
160 }
161 utxobuild.Debug(nil, nil)
162 if _, err := utxobuild.BuildChains(utxobuild.ChainsConfig{
163 Dir: filepath.Join(dir, "utxo"),
164 Interval: interval,
165 SharedLast: chains.SharedLastHeight,
166 Chains: []utxobuild.ChainInput{{Name: "btc", Tip: uint32(tip), Blocks: src}},
167 Logf: t.Logf,
168 }); err != nil {
169 t.Fatalf("build: %v", err)
170 }
171 sets, diffs := filepath.Join(dir, "utxo", "canonical"), filepath.Join(dir, "utxo", "diff", "shared")
172 mux := http.NewServeMux()
173 utxoserve.Routes(mux, utxoserve.Chain{Name: "btc", Sets: []string{sets}, Diffs: []string{diffs}, Interval: interval})
174 srv := httptest.NewServer(mux)
175 defer srv.Close()
176
177 cl := &fetch.Client{Base: srv.URL}
178 dst := t.TempDir()
179 n, err := cl.UTXO(t.Context(), "btc", dst)
180 if err != nil {
181 t.Fatalf("fetch: %v", err)
182 }
183 if want := 3; n != want {
184 t.Fatalf("the client reached %d snapshots, want %d", n, want)
185 }
186 for _, h := range []uint32{0, 144, 288} {
187 got, err := utxostore.SetName(dst, h)
188 if err != nil {
189 t.Fatalf("height %d: %v", h, err)
190 }
191 if got != walk[h] {
192 t.Fatalf("height %d: the client has %s, the walk had %s", h, got, walk[h])
193 }
194 }
195 // Between two snapshots: the run from 144 to 200 applied in order gives the
196 // walk's name at 200.
197 set, err := utxostore.LoadSet(dst, 144)
198 if err != nil {
199 t.Fatal(err)
200 }
201 run := getBytes(t, srv.URL+"/v1/utxo/btc/diffs/145-201")
202 set, err = applyRun(t, set, run)
203 if err != nil {
204 t.Fatal(err)
205 }
206 if got := utxostore.NameOf(set); got != walk[200] {
207 t.Fatalf("the client's set at 200 is %s, the walk's is %s", got, walk[200])
208 }
209 t.Logf("reached %d snapshots and the walk's name at 200", n)
210 }
211
212 // applyRun applies a stream of length-prefixed diffs.
213 func applyRun(t *testing.T, set []utxo.Entry, run []byte) ([]utxo.Entry, error) {
214 t.Helper()
215 at := 0
216 for at < len(run) {
217 n := int(binaryLE(run[at:]))
218 d, err := utxo.DecodeDiff(run[at+4 : at+4+n])
219 if err != nil {
220 return nil, err
221 }
222 at += 4 + n
223 if set, err = d.ApplyTo(set); err != nil {
224 return nil, err
225 }
226 }
227 return set, nil
228 }
229
230 // TestSharedPrefixIsWalkedOnce: two chains of the same length share one walk of
231 // the prefix. The count is the whole claim: 101 prefix reads, then each chain's
232 // own two hundred, not two copies of three hundred.
233 func TestSharedPrefixIsWalkedOnce(t *testing.T) {
234 r := nodeOn(t)
235 r.createWallet(t)
236 r.mine(t, 400)
237 tip := r.height(t)
238 bodies := rpcBodies(t, r, tip)
239 btc := &mapSource{bodies: bodies}
240 xbt := &mapSource{bodies: bodies}
241 dir := t.TempDir()
242 // Above one interval, so the fork sits past the first snapshot boundary: a
243 // prefix shorter than an interval leaves the chain nothing to continue from
244 // and it starts at height 0, writing a base of its own.
245 const sharedLast = 250
246 if _, err := utxobuild.BuildChains(utxobuild.ChainsConfig{
247 Dir: filepath.Join(dir, "utxo"),
248 Interval: chains.Regtest().Exported.Retarget,
249 SharedLast: sharedLast,
250 Chains: []utxobuild.ChainInput{
251 {Name: "btc", Tip: uint32(tip), Blocks: btc},
252 {Name: "xbt", Tip: uint32(tip), Blocks: xbt},
253 },
254 Logf: t.Logf,
255 }); err != nil {
256 t.Fatalf("build: %v", err)
257 }
258 prefix := sharedLast + 1
259 post := tip + 1 - prefix
260 // A streamed walk reads an epoch's blocks twice, once to learn what they
261 // spend and once to apply them, because it cannot hold 2016 bodies. What it
262 // must not do is re-walk a prefix beyond the snapshot boundary below the
263 // fork: that remainder is at most one interval, and the shared walk owns
264 // everything below it.
265 interval := int(chains.Regtest().Exported.Retarget)
266 remainder := prefix % interval
267 if remainder == 0 {
268 remainder = interval
269 }
270 // The first chain's count covers the shared walk and its own walk.
271 if want := 2*prefix + 2*(remainder+post); btc.reads > want {
272 t.Fatalf("the first chain read %d bodies, want at most %d (two reads of %d prefix + %d own)", btc.reads, want, prefix, post)
273 }
274 if want := 2 * (remainder + post); xbt.reads > want {
275 t.Fatalf("the second chain read %d bodies, want at most %d (%d remaining prefix + %d own): it re-walked the prefix", xbt.reads, want, remainder, post)
276 }
277 // The prefix's snapshots and diffs are in one place, and only there.
278 if _, err := utxostore.SetName(filepath.Join(dir, "utxo", "canonical"), 0); err != nil {
279 t.Fatalf("no shared snapshot at 0: %v", err)
280 }
281 if _, err := utxostore.SetName(filepath.Join(dir, "utxo", "chain-xbt"), 0); err == nil {
282 t.Fatal("the second chain wrote its own copy of the prefix's base")
283 }
284 t.Logf("prefix walked once: %d reads + %d + %d for two chains of %d", btc.reads, xbt.reads, 0, tip+1)
285 }
286
287 // TestSnapshotHeightIsNotAServedRange: a diff run that crosses a snapshot is
288 // refused, and one that ends on it is served.
289 func TestSnapshotHeightIsNotAServedRange(t *testing.T) {
290 r := nodeOn(t)
291 r.createWallet(t)
292 r.mine(t, 150)
293 tip := r.height(t)
294 bodies := rpcBodies(t, r, tip)
295 dir := t.TempDir()
296 interval := chains.Regtest().Exported.Retarget
297 if _, err := utxobuild.BuildChains(utxobuild.ChainsConfig{
298 Dir: filepath.Join(dir, "utxo"),
299 Interval: interval,
300 SharedLast: chains.SharedLastHeight,
301 Chains: []utxobuild.ChainInput{{Name: "btc", Tip: uint32(tip), Blocks: &mapSource{bodies: bodies}}},
302 Logf: t.Logf,
303 }); err != nil {
304 t.Fatalf("build: %v", err)
305 }
306 sets, diffs := filepath.Join(dir, "utxo", "canonical"), filepath.Join(dir, "utxo", "diff", "shared")
307 mux := http.NewServeMux()
308 utxoserve.Routes(mux, utxoserve.Chain{Name: "btc", Sets: []string{sets}, Diffs: []string{diffs}, Interval: interval})
309 srv := httptest.NewServer(mux)
310 defer srv.Close()
311 if resp := getStatus(t, srv.URL+"/v1/utxo/btc/diffs/1-145"); resp != 200 {
312 t.Fatalf("a run ending on the snapshot answered %d", resp)
313 }
314 if resp := getStatus(t, srv.URL+"/v1/utxo/btc/diffs/1-146"); resp != 400 {
315 t.Fatalf("a run across the snapshot answered %d, want 400", resp)
316 }
317 }
318
319 // getBytes fetches a response body that is not JSON.
320 func getBytes(t *testing.T, u string) []byte {
321 t.Helper()
322 resp, err := http.Get(u)
323 if err != nil {
324 t.Fatal(err)
325 }
326 defer resp.Body.Close()
327 body, err := io.ReadAll(resp.Body)
328 if err != nil {
329 t.Fatal(err)
330 }
331 if resp.StatusCode != http.StatusOK {
332 t.Fatalf("%s: %d %s", u, resp.StatusCode, body)
333 }
334 return body
335 }
336
337 func getStatus(t *testing.T, u string) int {
338 t.Helper()
339 resp, err := http.Get(u)
340 if err != nil {
341 t.Fatal(err)
342 }
343 resp.Body.Close()
344 return resp.StatusCode
345 }
346
347 // binaryLE reads the first four bytes of b little-endian, which is how a diff
348 // run frames each record.
349 func binaryLE(b []byte) uint32 {
350 return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24
351 }
352