writes_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 // TestWrittenEntries lists what the merge wrote, in order, next to what the
17 // walk holds, so the entry that never got written is named rather than
18 // inferred from a count.
19 func TestWrittenEntries(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(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.Fatal(err)
44 }
45 touches = append(touches, ts...)
46 set, err = utxo.ApplyRange(set, ts)
47 if err != nil {
48 t.Fatal(err)
49 }
50 }
51 d := utxo.Diff{From: 0, To: 106, Touches: touches}
52 _, err := MergeRange(dir, 0, 106, d, chainhash.Hash{})
53 if err != nil {
54 t.Fatalf("merge: %v", err)
55 }
56 raw, _ := os.ReadFile(filepath.Join(dir, SetFile(106)))
57 written := make([]utxo.Entry, 0, len(raw)/EntrySize)
58 buf := make([]byte, EntrySize)
59 for i := 0; i+EntrySize <= len(raw); i += EntrySize {
60 copy(buf, raw[i:i+EntrySize])
61 written = append(written, utxo.Decode(buf))
62 }
63 have := map[wire.OutPoint]bool{}
64 for _, e := range written {
65 have[e.OutPoint] = true
66 }
67 t.Logf("%d written, %d in the walk", len(written), len(set))
68 shown := 0
69 for _, e := range set {
70 if have[e.OutPoint] {
71 continue
72 }
73 if shown < 8 {
74 t.Logf(" not written: %s v=%d h=%d", short(e.OutPoint), e.Value, e.Height)
75 }
76 shown++
77 }
78 if shown > 0 {
79 t.Fatalf("%d entries the walk holds and the merge never wrote", shown)
80 }
81 }
82