package utxostore import ( "encoding/binary" "fmt" "os" "path/filepath" "testing" "git.smesh.lol/nostrino/pkg/crypto/chainhash" "git.smesh.lol/btcd-lite/internal/utxo" "git.smesh.lol/btcd-lite/internal/wire" ) func twop(i uint32) wire.OutPoint { var h [32]byte binary.LittleEndian.PutUint32(h[:4], i) binary.BigEndian.PutUint32(h[28:], i) return wire.OutPoint{Hash: h} } // TestSynthSevenBaseEightCreations is the node-body second range in its // skeleton: seven base entries, eight creations, no spends. If this passes, the // difference in the node case is in the values or the ordering, not the shape. func TestSynthSevenBaseEightCreations(t *testing.T) { var base []utxo.Entry for i := uint32(0); i < 7; i++ { base = append(base, utxo.Entry{OutPoint: twop(i * 10), Value: int64(i), Height: 0}) } var ts []utxo.Touch for i := uint32(0); i < 8; i++ { // Creations that sort between and after the base entries: 5, 15, 25, ... id := 5 + i*10 ts = append(ts, utxo.Touch{OutPoint: twop(id), Height: 1, New: utxo.Entry{OutPoint: twop(id), Value: int64(id), Height: 1}}) } want, err := utxo.ApplyRange(base, ts) if err != nil { t.Fatal(err) } dir := t.TempDir() if _, err := WriteSet(dir, 0, base); err != nil { t.Fatal(err) } if _, err := Promote(dir, 0); err != nil { t.Fatal(err) } if _, err := CutRange(dir, 0, 1, ts); err != nil { t.Fatal(err) } d, _ := LoadDiff(dir, 0, 1) got, err := MergeRange(dir, 0, 1, d, NameOf(want)) if err != nil { t.Fatalf("merge: %v", err) } if got != NameOf(want) { raw, rerr := os.ReadFile(filepath.Join(dir, SetFile(1))) if rerr != nil { t.Fatal(rerr) } buf := make([]byte, EntrySize) var vals []int64 for i := 0; i+EntrySize <= len(raw); i += EntrySize { copy(buf, raw[i:i+EntrySize]) vals = append(vals, utxo.Decode(buf).Value) } var wantVals []int64 for _, e := range want { wantVals = append(wantVals, e.Value) } t.Fatalf("merge wrote %v, walk has %v", vals, wantVals) } _ = chainhash.Hash{} } // TestSynthFromNodeBase takes the actual seven entries at checkpoint 4 from the // node bodies and applies the actual eight creations of the second range to // them, so any difference in values or ordering is the node's and not mine. func TestSynthFromNodeBase(t *testing.T) { base := nodeEntriesAt4(t) t.Logf("base: %d entries", len(base)) for _, e := range base { t.Logf(" base v=%d h=%d", e.Value, e.Height) } ts, set := nodeSecondRange(t, base) t.Logf("creations: %d, walk: %d", len(ts), len(set)) dir := t.TempDir() if _, err := WriteSet(dir, 0, base); err != nil { t.Fatal(err) } if _, err := Promote(dir, 0); err != nil { t.Fatal(err) } if _, err := CutRange(dir, 0, 1, ts); err != nil { t.Fatal(err) } d, _ := LoadDiff(dir, 0, 1) got, err := MergeRange(dir, 0, 1, d, NameOf(set)) if err != nil { t.Fatalf("merge: %v", err) } t.Logf("merge from the node's own base agrees: %s", got) } // TestSynthEqualValues is the node base's shape with hand-made entries: seven // base entries whose values repeat, eight creations whose values repeat, and a // coinbase flag that alternates. If this fails, the difference is in what the // merge does with entries it cannot tell apart by value. func TestSynthEqualValues(t *testing.T) { var base []utxo.Entry for i := uint32(0); i < 7; i++ { e := utxo.Entry{OutPoint: twop(i * 10), Value: 5_000_000_000, Height: i % 4} if i%2 == 1 { e.Value = 0 } e.Coinbase = true base = append(base, e) } var ts []utxo.Touch for i := uint32(0); i < 8; i++ { id := 5 + i*10 e := utxo.Entry{OutPoint: twop(id), Value: 5_000_000_000, Height: 4 + i%4, Coinbase: true} if i%2 == 1 { e.Value = 0 } ts = append(ts, utxo.Touch{OutPoint: twop(id), Height: 4, New: e}) } want, err := utxo.ApplyRange(base, ts) if err != nil { t.Fatal(err) } dir := t.TempDir() if _, err := WriteSet(dir, 0, base); err != nil { t.Fatal(err) } if _, err := Promote(dir, 0); err != nil { t.Fatal(err) } if _, err := CutRange(dir, 0, 1, ts); err != nil { t.Fatal(err) } d, _ := LoadDiff(dir, 0, 1) got, err := MergeRange(dir, 0, 1, d, NameOf(want)) if err != nil { t.Fatalf("merge: %v", err) } if got != NameOf(want) { raw, rerr := os.ReadFile(filepath.Join(dir, SetFile(1))) if rerr != nil { t.Fatalf("merge %s, walk %s, and the output is gone: %v", got, NameOf(want), rerr) } buf := make([]byte, EntrySize) var vals []int64 for i := 0; i+EntrySize <= len(raw); i += EntrySize { copy(buf, raw[i:i+EntrySize]) vals = append(vals, utxo.Decode(buf).Value) } t.Fatalf("merge wrote %d entries %v, walk %d", len(vals), vals, len(want)) } } // TestSynthEqualValuesDump prints the two sets for the equal-value case entry by // entry, so the difference is in the output and not in a name. func TestSynthEqualValuesDump(t *testing.T) { var base []utxo.Entry for i := uint32(0); i < 7; i++ { e := utxo.Entry{OutPoint: twop(i * 10), Value: 5_000_000_000, Height: i % 4, Coinbase: true} if i%2 == 1 { e.Value = 0 } base = append(base, e) } var ts []utxo.Touch for i := uint32(0); i < 8; i++ { id := 5 + i*10 e := utxo.Entry{OutPoint: twop(id), Value: 5_000_000_000, Height: 4 + i%4, Coinbase: true} if i%2 == 1 { e.Value = 0 } ts = append(ts, utxo.Touch{OutPoint: twop(id), Height: 4, New: e}) } want, _ := utxo.ApplyRange(base, ts) dir := t.TempDir() _, _ = WriteSet(dir, 0, base) _, _ = Promote(dir, 0) _, _ = CutRange(dir, 0, 1, ts) d, _ := LoadDiff(dir, 0, 1) _, err := MergeRange(dir, 0, 1, d, NameOf(want)) raw, _ := os.ReadFile(filepath.Join(dir, SetFile(1))) buf := make([]byte, EntrySize) var got []utxo.Entry for i := 0; i+EntrySize <= len(raw); i += EntrySize { copy(buf, raw[i:i+EntrySize]) got = append(got, utxo.Decode(buf)) } t.Logf("err=%v walk %d entries, merge %d", err, len(want), len(got)) for i := 0; i < len(want) || i < len(got); i++ { var w, g string if i < len(want) { w = fmt.Sprintf("idx=%d v=%d h=%d", want[i].OutPoint.Index, want[i].Value, want[i].Height) } if i < len(got) { g = fmt.Sprintf("idx=%d v=%d h=%d", got[i].OutPoint.Index, got[i].Value, got[i].Height) } t.Logf(" %d walk [%s] merge [%s]", i, w, g) } } // TestSynthFromNodeBaseDump prints the two sets for the node-base case with the // diff's heights fixed, so what remains is visible entry by entry. func TestSynthFromNodeBaseDump(t *testing.T) { base := nodeEntriesAt4(t) ts, set := nodeSecondRange(t, base) dir := t.TempDir() _, _ = WriteSet(dir, 0, base) _, _ = Promote(dir, 0) _, _ = CutRange(dir, 0, 1, ts) d, _ := LoadDiff(dir, 0, 1) t.Logf("touches %d; first creation height in the diff %d, in the walk %d", len(ts), d.Touches[0].New.Height, ts[0].New.Height) _, err := MergeRange(dir, 0, 1, d, NameOf(set)) same := 0 for i := range ts { if d.Touches[i].New.Height == ts[i].New.Height { same++ } } t.Logf("heights surviving the round trip: %d of %d; merge err %v", same, len(ts), err) raw, _ := os.ReadFile(filepath.Join(dir, SetFile(1))) buf := make([]byte, EntrySize) var got []utxo.Entry for i := 0; i+EntrySize <= len(raw); i += EntrySize { copy(buf, raw[i:i+EntrySize]) got = append(got, utxo.Decode(buf)) } t.Logf("walk %d, merge %d", len(set), len(got)) for i := 0; i < len(set) && i < len(got); i++ { if set[i] != got[i] { t.Logf(" first difference %d: walk v=%d h=%d cb=%v | merge v=%d h=%d cb=%v", i, set[i].Value, set[i].Height, set[i].Coinbase, got[i].Value, got[i].Height, got[i].Coinbase) break } } } // TestSynthFromNodeBaseScripts prints every entry's script hash on both sides. func TestSynthFromNodeBaseScripts(t *testing.T) { base := nodeScriptsAt4(t) ts, set := nodeSecondRange(t, base) dir := t.TempDir() _, _ = WriteSet(dir, 0, base) _, _ = Promote(dir, 0) _, _ = CutRange(dir, 0, 1, ts) d, _ := LoadDiff(dir, 0, 1) // No target: the merge keeps its file when nothing asks it to match. _, _ = MergeRange(dir, 0, 1, d, chainhash.Hash{}) raw, rerr := os.ReadFile(filepath.Join(dir, SetFile(1))) if rerr != nil { t.Fatalf("the file is gone: %v", rerr) } buf := make([]byte, EntrySize) var got []utxo.Entry for i := 0; i+EntrySize <= len(raw); i += EntrySize { copy(buf, raw[i:i+EntrySize]) got = append(got, utxo.Decode(buf)) } t.Logf("walk %d, merge %d", len(set), len(got)) for i := 0; i < len(set) && i < len(got); i++ { if set[i] != got[i] { t.Logf(" first difference %d: walk v=%d h=%d cb=%v s=%x | merge v=%d h=%d cb=%v s=%x", i, set[i].Value, set[i].Height, set[i].Coinbase, set[i].ScriptHash[:4], got[i].Value, got[i].Height, got[i].Coinbase, got[i].ScriptHash[:4]) break } } } // TestNodeBaseCollision: does any creation of the second range name an outpoint // the base at height 4 already holds? func TestNodeBaseCollision(t *testing.T) { base := nodeEntriesAt4(t) ts, _ := nodeSecondRange(t, base) for _, e := range base { for _, tc := range ts { if e.OutPoint == tc.OutPoint { t.Logf("COLLISION %s: base v=%d h=%d cb=%v | creation v=%d h=%d cb=%v", e.OutPoint, e.Value, e.Height, e.Coinbase, tc.New.Value, tc.New.Height, tc.New.Coinbase) } } } // And the reverse: a creation the base holds under another height. seen := map[wire.OutPoint]int{} for _, e := range base { seen[e.OutPoint]++ } dups := 0 for op, n := range seen { if n > 1 { dups++ t.Logf("BASE DUPLICATE %s x%d", op, n) } } t.Logf("base %d entries, %d creations, %d base duplicates", len(base), len(ts), dups) } // TestNodeBaseOrder prints the base's outpoint order and the creation order, // with the comparison the merge uses, so an order the merge cannot walk is // visible. func TestNodeBaseOrder(t *testing.T) { base := nodeEntriesAt4(t) ts, _ := nodeSecondRange(t, base) for i, e := range base { t.Logf("base %d: outpoint %x idx=%d", i, e.OutPoint.Hash[:4], e.OutPoint.Index) } for i, tc := range ts { t.Logf("created %d: outpoint %x idx=%d", i, tc.OutPoint.Hash[:4], tc.OutPoint.Index) } // Interleave by the set's comparison. all := append([]wire.OutPoint{}, nil...) _ = all type item struct { op wire.OutPoint src string } var items []item for _, e := range base { items = append(items, item{e.OutPoint, "base"}) } for _, tc := range ts { items = append(items, item{tc.OutPoint, "made"}) } sortBySetOps(items, func(a, b item) bool { return utxo.LessEntry(utxo.Entry{OutPoint: a.op}, utxo.Entry{OutPoint: b.op}) }) for i, it := range items { t.Logf(" %d %s %x idx=%d", i, it.src, it.op.Hash[:4], it.op.Index) } } // TestWalkVersusInterlock builds the expected union by interleaving base and // creations with the set's comparison, and compares it with the walk's set and // with the merge's. func TestWalkVersusInterlock(t *testing.T) { base := nodeEntriesAt4(t) ts, walk := nodeSecondRange(t, base) var expect []utxo.Entry expect = append(expect, base...) for _, tc := range ts { expect = append(expect, tc.New) } sortEntries(expect) if NameOf(expect) == NameOf(walk) { t.Logf("the walk is the interlock") } else { t.Logf("the walk is NOT the interlock") } for i := 0; i < len(expect) && i < len(walk); i++ { if expect[i] != walk[i] { t.Logf(" first difference at %d: interlock h=%d v=%d | walk h=%d v=%d", i, expect[i].Height, expect[i].Value, walk[i].Height, walk[i].Value) break } } } func sortEntries(s []utxo.Entry) { for i := 1; i < len(s); i++ { for j := i; j > 0 && utxo.LessEntry(s[j], s[j-1]); j-- { s[j], s[j-1] = s[j-1], s[j] } } } func sortBySetOps[T any](s []T, less func(a, b T) bool) { for i := 1; i < len(s); i++ { for j := i; j > 0 && less(s[j], s[j-1]); j-- { s[j], s[j-1] = s[j-1], s[j] } } } // TestSynthFromNodeBaseDump2 prints every entry of both sets after the height // fix, so the difference is a list and not a name. func TestSynthFromNodeBaseDump2(t *testing.T) { base := nodeEntriesAt4(t) ts, walk := nodeSecondRange(t, base) dir := t.TempDir() _, _ = WriteSet(dir, 0, base) _, _ = Promote(dir, 0) _, _ = CutRange(dir, 0, 1, ts) d, _ := LoadDiff(dir, 0, 1) _, _ = MergeRange(dir, 0, 1, d, chainhash.Hash{}) raw, _ := os.ReadFile(filepath.Join(dir, SetFile(1))) buf := make([]byte, EntrySize) var got []utxo.Entry for i := 0; i+EntrySize <= len(raw); i += EntrySize { copy(buf, raw[i:i+EntrySize]) got = append(got, utxo.Decode(buf)) } t.Logf("walk %d, merge %d", len(walk), len(got)) for i := 0; i < len(walk) || i < len(got); i++ { var w, g string if i < len(walk) { w = fmt.Sprintf("%x:%d v=%d h=%d", walk[i].OutPoint.Hash[:2], walk[i].OutPoint.Index, walk[i].Value, walk[i].Height) } if i < len(got) { g = fmt.Sprintf("%x:%d v=%d h=%d", got[i].OutPoint.Hash[:2], got[i].OutPoint.Index, got[i].Value, got[i].Height) } mark := "" if w != g { mark = " <<<" } t.Logf(" %2d walk [%s] merge [%s]%s", i, w, g, mark) } }