1 package utxobuild_test
2 3 import (
4 "os"
5 "path/filepath"
6 "testing"
7 8 "git.smesh.lol/nostrino/pkg/crypto/chainhash"
9 10 "git.smesh.lol/btcd-lite/internal/utxo"
11 utxostore "git.smesh.lol/btcd-lite/internal/utxo/store"
12 "git.smesh.lol/btcd-lite/internal/utxobuild"
13 "git.smesh.lol/btcd-lite/internal/wire"
14 )
15 16 // TestCheckpointFileIsTheWalk: after the build's first checkpoint, the file it
17 // wrote holds exactly the set the walk held at that height, entry for entry and
18 // in the same order.
19 func TestCheckpointFileIsTheWalk(t *testing.T) {
20 raw, _ := chainOfBodies(22)
21 src := bodies{}
22 for h := range raw {
23 src[uint32(h)] = raw[h]
24 }
25 dir := t.TempDir()
26 var walkAt10 []utxo.Entry
27 utxobuild.Debug(func(height uint32, entries int, name chainhash.Hash) {
28 if height == 10 {
29 t.Logf("walk at 10: %d entries %s", entries, name)
30 }
31 }, nil)
32 _, err := utxobuild.Build(utxobuild.Config{Dir: dir, Interval: 10, From: 0, To: 21, Blocks: src, Logf: t.Logf})
33 utxobuild.Debug(nil, nil)
34 if err != nil {
35 t.Fatalf("build: %v", err)
36 }
37 // The walk over the same 0..10, in this process.
38 var set []utxo.Entry
39 // The file at 10 is the set after block 10, so the walk covers 0..10.
40 for h := uint32(0); h <= 10; h++ {
41 b, err := wire.ParseBlock(raw[h])
42 if err != nil {
43 t.Fatal(err)
44 }
45 lookup := utxo.Lookup(func(op wire.OutPoint) (utxo.Entry, bool) { return utxo.Find(set, op) })
46 ts, err := utxo.BlockTouches(b, h, lookup)
47 if err != nil {
48 t.Fatal(err)
49 }
50 set, err = utxo.ApplyRange(set, ts)
51 if err != nil {
52 t.Fatal(err)
53 }
54 }
55 walkAt10 = set
56 file, err := os.ReadFile(filepath.Join(dir, utxostore.SetFile(10)))
57 if err != nil {
58 t.Fatal(err)
59 }
60 written := make([]utxo.Entry, 0, len(file)/utxostore.EntrySize)
61 buf := make([]byte, utxostore.EntrySize)
62 for i := 0; i+utxostore.EntrySize <= len(file); i += utxostore.EntrySize {
63 copy(buf, file[i:i+utxostore.EntrySize])
64 written = append(written, utxo.Decode(buf))
65 }
66 t.Logf("walk %d entries, file at 10 holds %d", len(walkAt10), len(written))
67 if len(walkAt10) != len(written) {
68 t.Fatalf("%d vs %d", len(walkAt10), len(written))
69 }
70 for i := range walkAt10 {
71 if walkAt10[i] != written[i] {
72 t.Fatalf("entry %d: walk %s v=%d h=%d, file %s v=%d h=%d",
73 i, walkAt10[i].OutPoint, walkAt10[i].Value, walkAt10[i].Height,
74 written[i].OutPoint, written[i].Value, written[i].Height)
75 }
76 }
77 // And the base a later merge reads must be exactly this file, so the set
78 // of 10..20 is merged against the walk's own set at 10.
79 if n, err := utxostore.SetName(dir, 10); err != nil || n != utxostore.NameOf(walkAt10) {
80 t.Fatalf("the base the next merge reads names %s, the walk at 10 is %s", n, utxostore.NameOf(walkAt10))
81 }
82 t.Logf("the file at 10 is the walk's set at 10: %s", utxostore.NameOf(walkAt10))
83 }
84