realtrace_test.go raw
1 package utxostore
2
3 import (
4 "fmt"
5 "os"
6 "path/filepath"
7 "strings"
8 "testing"
9
10 "git.smesh.lol/nostrino/pkg/crypto/chainhash"
11
12 "git.smesh.lol/btcd-lite/internal/utxo"
13 "git.smesh.lol/btcd-lite/internal/wire"
14 )
15
16 // TestRealBlocksTrace drives the merge over the captured blocks with the step
17 // trace on, so the cursor action that loses an entry is visible rather than
18 // inferred from the output.
19 func TestRealBlocksTrace(t *testing.T) {
20 dir := t.TempDir()
21 funder, _ := chainhash.NewHashFromStr("36e95a2200bb470593863bf444790eaa31323f2728a0b9d8688a6294776c6710")
22 base := []utxo.Entry{{OutPoint: wire.OutPoint{Hash: *funder}, Value: 50_0000_0000, Height: 1, Coinbase: true}}
23 if _, err := WriteSet(dir, 0, base); err != nil {
24 t.Fatal(err)
25 }
26 if _, err := Promote(dir, 0); err != nil {
27 t.Fatal(err)
28 }
29 var touches []utxo.Touch
30 set := append([]utxo.Entry(nil), base...)
31 for h := uint32(80); h <= 105; h++ {
32 raw, err := os.ReadFile(filepath.Join("..", "testdata", fmt.Sprintf("regtest-block-%d.hex", h)))
33 if err != nil {
34 t.Skip("no blocks")
35 }
36 b, err := wire.ParseBlock([]byte(mustDecode(t, strings.TrimSpace(string(raw)))))
37 if err != nil {
38 t.Fatal(err)
39 }
40 lookup := utxo.Lookup(func(op wire.OutPoint) (utxo.Entry, bool) { return utxo.Find(set, op) })
41 ts, err := utxo.BlockTouches(b, h, lookup)
42 if err != nil {
43 t.Fatalf("%d: %v", h, err)
44 }
45 touches = append(touches, ts...)
46 set, err = utxo.ApplyRange(set, ts)
47 if err != nil {
48 t.Fatalf("%d: %v", h, err)
49 }
50 }
51 if _, err := WriteSet(dir, 106, set); err != nil {
52 t.Fatal(err)
53 }
54 if _, err := CutRange(dir, 0, 106, touches); err != nil {
55 t.Fatal(err)
56 }
57 d, err := LoadDiff(dir, 0, 106)
58 if err != nil {
59 t.Fatal(err)
60 }
61 steps := 0
62 debugStep = func(b wire.OutPoint, ci int, c wire.OutPoint, ch bool, s wire.OutPoint, sh bool) {
63 if steps < 6 {
64 t.Logf("base %s | created[%d] %s have=%v | spent %s have=%v", short(b), ci, short(c), ch, short(s), sh)
65 }
66 steps++
67 }
68 defer func() { debugStep = func(wire.OutPoint, int, wire.OutPoint, bool, wire.OutPoint, bool) {} }()
69 got, err := MergeRange(dir, 0, 106, d, chainhash.Hash{})
70 raw, _ := os.ReadFile(filepath.Join(dir, SetFile(106)))
71 written := make([]utxo.Entry, 0, len(raw)/EntrySize)
72 buf := make([]byte, EntrySize)
73 for i := 0; i+EntrySize <= len(raw); i += EntrySize {
74 copy(buf, raw[i:i+EntrySize])
75 written = append(written, utxo.Decode(buf))
76 }
77 t.Logf("merge %s err %v walk %s, %d entries written %d", got, err, NameOf(set), len(set), len(written))
78 for i := 0; i < len(set) && i < len(written); i++ {
79 if set[i] != written[i] {
80 t.Logf("first difference at %d: walk %s v=%d h=%d, written %s v=%d h=%d",
81 i, short(set[i].OutPoint), set[i].Value, set[i].Height,
82 short(written[i].OutPoint), written[i].Value, written[i].Height)
83 break
84 }
85 }
86 }
87