synth2_test.go raw
1 package utxostore
2
3 import (
4 "encoding/binary"
5 "fmt"
6 "os"
7 "path/filepath"
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 func twop(i uint32) wire.OutPoint {
17 var h [32]byte
18 binary.LittleEndian.PutUint32(h[:4], i)
19 binary.BigEndian.PutUint32(h[28:], i)
20 return wire.OutPoint{Hash: h}
21 }
22
23 // TestSynthSevenBaseEightCreations is the node-body second range in its
24 // skeleton: seven base entries, eight creations, no spends. If this passes, the
25 // difference in the node case is in the values or the ordering, not the shape.
26 func TestSynthSevenBaseEightCreations(t *testing.T) {
27 var base []utxo.Entry
28 for i := uint32(0); i < 7; i++ {
29 base = append(base, utxo.Entry{OutPoint: twop(i * 10), Value: int64(i), Height: 0})
30 }
31 var ts []utxo.Touch
32 for i := uint32(0); i < 8; i++ {
33 // Creations that sort between and after the base entries: 5, 15, 25, ...
34 id := 5 + i*10
35 ts = append(ts, utxo.Touch{OutPoint: twop(id), Height: 1, New: utxo.Entry{OutPoint: twop(id), Value: int64(id), Height: 1}})
36 }
37 want, err := utxo.ApplyRange(base, ts)
38 if err != nil {
39 t.Fatal(err)
40 }
41 dir := t.TempDir()
42 if _, err := WriteSet(dir, 0, base); err != nil {
43 t.Fatal(err)
44 }
45 if _, err := Promote(dir, 0); err != nil {
46 t.Fatal(err)
47 }
48 if _, err := CutRange(dir, 0, 1, ts); err != nil {
49 t.Fatal(err)
50 }
51 d, _ := LoadDiff(dir, 0, 1)
52 got, err := MergeRange(dir, 0, 1, d, NameOf(want))
53 if err != nil {
54 t.Fatalf("merge: %v", err)
55 }
56 if got != NameOf(want) {
57 raw, rerr := os.ReadFile(filepath.Join(dir, SetFile(1)))
58 if rerr != nil {
59 t.Fatal(rerr)
60 }
61 buf := make([]byte, EntrySize)
62 var vals []int64
63 for i := 0; i+EntrySize <= len(raw); i += EntrySize {
64 copy(buf, raw[i:i+EntrySize])
65 vals = append(vals, utxo.Decode(buf).Value)
66 }
67 var wantVals []int64
68 for _, e := range want {
69 wantVals = append(wantVals, e.Value)
70 }
71 t.Fatalf("merge wrote %v, walk has %v", vals, wantVals)
72 }
73 _ = chainhash.Hash{}
74 }
75
76 // TestSynthFromNodeBase takes the actual seven entries at checkpoint 4 from the
77 // node bodies and applies the actual eight creations of the second range to
78 // them, so any difference in values or ordering is the node's and not mine.
79 func TestSynthFromNodeBase(t *testing.T) {
80 base := nodeEntriesAt4(t)
81 t.Logf("base: %d entries", len(base))
82 for _, e := range base {
83 t.Logf(" base v=%d h=%d", e.Value, e.Height)
84 }
85 ts, set := nodeSecondRange(t, base)
86 t.Logf("creations: %d, walk: %d", len(ts), len(set))
87 dir := t.TempDir()
88 if _, err := WriteSet(dir, 0, base); err != nil {
89 t.Fatal(err)
90 }
91 if _, err := Promote(dir, 0); err != nil {
92 t.Fatal(err)
93 }
94 if _, err := CutRange(dir, 0, 1, ts); err != nil {
95 t.Fatal(err)
96 }
97 d, _ := LoadDiff(dir, 0, 1)
98 got, err := MergeRange(dir, 0, 1, d, NameOf(set))
99 if err != nil {
100 t.Fatalf("merge: %v", err)
101 }
102 t.Logf("merge from the node's own base agrees: %s", got)
103 }
104
105 // TestSynthEqualValues is the node base's shape with hand-made entries: seven
106 // base entries whose values repeat, eight creations whose values repeat, and a
107 // coinbase flag that alternates. If this fails, the difference is in what the
108 // merge does with entries it cannot tell apart by value.
109 func TestSynthEqualValues(t *testing.T) {
110 var base []utxo.Entry
111 for i := uint32(0); i < 7; i++ {
112 e := utxo.Entry{OutPoint: twop(i * 10), Value: 5_000_000_000, Height: i % 4}
113 if i%2 == 1 {
114 e.Value = 0
115 }
116 e.Coinbase = true
117 base = append(base, e)
118 }
119 var ts []utxo.Touch
120 for i := uint32(0); i < 8; i++ {
121 id := 5 + i*10
122 e := utxo.Entry{OutPoint: twop(id), Value: 5_000_000_000, Height: 4 + i%4, Coinbase: true}
123 if i%2 == 1 {
124 e.Value = 0
125 }
126 ts = append(ts, utxo.Touch{OutPoint: twop(id), Height: 4, New: e})
127 }
128 want, err := utxo.ApplyRange(base, ts)
129 if err != nil {
130 t.Fatal(err)
131 }
132 dir := t.TempDir()
133 if _, err := WriteSet(dir, 0, base); err != nil {
134 t.Fatal(err)
135 }
136 if _, err := Promote(dir, 0); err != nil {
137 t.Fatal(err)
138 }
139 if _, err := CutRange(dir, 0, 1, ts); err != nil {
140 t.Fatal(err)
141 }
142 d, _ := LoadDiff(dir, 0, 1)
143 got, err := MergeRange(dir, 0, 1, d, NameOf(want))
144 if err != nil {
145 t.Fatalf("merge: %v", err)
146 }
147 if got != NameOf(want) {
148 raw, rerr := os.ReadFile(filepath.Join(dir, SetFile(1)))
149 if rerr != nil {
150 t.Fatalf("merge %s, walk %s, and the output is gone: %v", got, NameOf(want), rerr)
151 }
152 buf := make([]byte, EntrySize)
153 var vals []int64
154 for i := 0; i+EntrySize <= len(raw); i += EntrySize {
155 copy(buf, raw[i:i+EntrySize])
156 vals = append(vals, utxo.Decode(buf).Value)
157 }
158 t.Fatalf("merge wrote %d entries %v, walk %d", len(vals), vals, len(want))
159 }
160 }
161
162 // TestSynthEqualValuesDump prints the two sets for the equal-value case entry by
163 // entry, so the difference is in the output and not in a name.
164 func TestSynthEqualValuesDump(t *testing.T) {
165 var base []utxo.Entry
166 for i := uint32(0); i < 7; i++ {
167 e := utxo.Entry{OutPoint: twop(i * 10), Value: 5_000_000_000, Height: i % 4, Coinbase: true}
168 if i%2 == 1 {
169 e.Value = 0
170 }
171 base = append(base, e)
172 }
173 var ts []utxo.Touch
174 for i := uint32(0); i < 8; i++ {
175 id := 5 + i*10
176 e := utxo.Entry{OutPoint: twop(id), Value: 5_000_000_000, Height: 4 + i%4, Coinbase: true}
177 if i%2 == 1 {
178 e.Value = 0
179 }
180 ts = append(ts, utxo.Touch{OutPoint: twop(id), Height: 4, New: e})
181 }
182 want, _ := utxo.ApplyRange(base, ts)
183 dir := t.TempDir()
184 _, _ = WriteSet(dir, 0, base)
185 _, _ = Promote(dir, 0)
186 _, _ = CutRange(dir, 0, 1, ts)
187 d, _ := LoadDiff(dir, 0, 1)
188 _, err := MergeRange(dir, 0, 1, d, NameOf(want))
189 raw, _ := os.ReadFile(filepath.Join(dir, SetFile(1)))
190 buf := make([]byte, EntrySize)
191 var got []utxo.Entry
192 for i := 0; i+EntrySize <= len(raw); i += EntrySize {
193 copy(buf, raw[i:i+EntrySize])
194 got = append(got, utxo.Decode(buf))
195 }
196 t.Logf("err=%v walk %d entries, merge %d", err, len(want), len(got))
197 for i := 0; i < len(want) || i < len(got); i++ {
198 var w, g string
199 if i < len(want) {
200 w = fmt.Sprintf("idx=%d v=%d h=%d", want[i].OutPoint.Index, want[i].Value, want[i].Height)
201 }
202 if i < len(got) {
203 g = fmt.Sprintf("idx=%d v=%d h=%d", got[i].OutPoint.Index, got[i].Value, got[i].Height)
204 }
205 t.Logf(" %d walk [%s] merge [%s]", i, w, g)
206 }
207 }
208
209 // TestSynthFromNodeBaseDump prints the two sets for the node-base case with the
210 // diff's heights fixed, so what remains is visible entry by entry.
211 func TestSynthFromNodeBaseDump(t *testing.T) {
212 base := nodeEntriesAt4(t)
213 ts, set := nodeSecondRange(t, base)
214 dir := t.TempDir()
215 _, _ = WriteSet(dir, 0, base)
216 _, _ = Promote(dir, 0)
217 _, _ = CutRange(dir, 0, 1, ts)
218 d, _ := LoadDiff(dir, 0, 1)
219 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)
220 _, err := MergeRange(dir, 0, 1, d, NameOf(set))
221 same := 0
222 for i := range ts {
223 if d.Touches[i].New.Height == ts[i].New.Height {
224 same++
225 }
226 }
227 t.Logf("heights surviving the round trip: %d of %d; merge err %v", same, len(ts), err)
228 raw, _ := os.ReadFile(filepath.Join(dir, SetFile(1)))
229 buf := make([]byte, EntrySize)
230 var got []utxo.Entry
231 for i := 0; i+EntrySize <= len(raw); i += EntrySize {
232 copy(buf, raw[i:i+EntrySize])
233 got = append(got, utxo.Decode(buf))
234 }
235 t.Logf("walk %d, merge %d", len(set), len(got))
236 for i := 0; i < len(set) && i < len(got); i++ {
237 if set[i] != got[i] {
238 t.Logf(" first difference %d: walk v=%d h=%d cb=%v | merge v=%d h=%d cb=%v",
239 i, set[i].Value, set[i].Height, set[i].Coinbase, got[i].Value, got[i].Height, got[i].Coinbase)
240 break
241 }
242 }
243 }
244
245 // TestSynthFromNodeBaseScripts prints every entry's script hash on both sides.
246 func TestSynthFromNodeBaseScripts(t *testing.T) {
247 base := nodeScriptsAt4(t)
248 ts, set := nodeSecondRange(t, base)
249 dir := t.TempDir()
250 _, _ = WriteSet(dir, 0, base)
251 _, _ = Promote(dir, 0)
252 _, _ = CutRange(dir, 0, 1, ts)
253 d, _ := LoadDiff(dir, 0, 1)
254 // No target: the merge keeps its file when nothing asks it to match.
255 _, _ = MergeRange(dir, 0, 1, d, chainhash.Hash{})
256 raw, rerr := os.ReadFile(filepath.Join(dir, SetFile(1)))
257 if rerr != nil {
258 t.Fatalf("the file is gone: %v", rerr)
259 }
260 buf := make([]byte, EntrySize)
261 var got []utxo.Entry
262 for i := 0; i+EntrySize <= len(raw); i += EntrySize {
263 copy(buf, raw[i:i+EntrySize])
264 got = append(got, utxo.Decode(buf))
265 }
266 t.Logf("walk %d, merge %d", len(set), len(got))
267 for i := 0; i < len(set) && i < len(got); i++ {
268 if set[i] != got[i] {
269 t.Logf(" first difference %d: walk v=%d h=%d cb=%v s=%x | merge v=%d h=%d cb=%v s=%x",
270 i, set[i].Value, set[i].Height, set[i].Coinbase, set[i].ScriptHash[:4],
271 got[i].Value, got[i].Height, got[i].Coinbase, got[i].ScriptHash[:4])
272 break
273 }
274 }
275 }
276
277 // TestNodeBaseCollision: does any creation of the second range name an outpoint
278 // the base at height 4 already holds?
279 func TestNodeBaseCollision(t *testing.T) {
280 base := nodeEntriesAt4(t)
281 ts, _ := nodeSecondRange(t, base)
282 for _, e := range base {
283 for _, tc := range ts {
284 if e.OutPoint == tc.OutPoint {
285 t.Logf("COLLISION %s: base v=%d h=%d cb=%v | creation v=%d h=%d cb=%v",
286 e.OutPoint, e.Value, e.Height, e.Coinbase, tc.New.Value, tc.New.Height, tc.New.Coinbase)
287 }
288 }
289 }
290 // And the reverse: a creation the base holds under another height.
291 seen := map[wire.OutPoint]int{}
292 for _, e := range base {
293 seen[e.OutPoint]++
294 }
295 dups := 0
296 for op, n := range seen {
297 if n > 1 {
298 dups++
299 t.Logf("BASE DUPLICATE %s x%d", op, n)
300 }
301 }
302 t.Logf("base %d entries, %d creations, %d base duplicates", len(base), len(ts), dups)
303 }
304
305 // TestNodeBaseOrder prints the base's outpoint order and the creation order,
306 // with the comparison the merge uses, so an order the merge cannot walk is
307 // visible.
308 func TestNodeBaseOrder(t *testing.T) {
309 base := nodeEntriesAt4(t)
310 ts, _ := nodeSecondRange(t, base)
311 for i, e := range base {
312 t.Logf("base %d: outpoint %x idx=%d", i, e.OutPoint.Hash[:4], e.OutPoint.Index)
313 }
314 for i, tc := range ts {
315 t.Logf("created %d: outpoint %x idx=%d", i, tc.OutPoint.Hash[:4], tc.OutPoint.Index)
316 }
317 // Interleave by the set's comparison.
318 all := append([]wire.OutPoint{}, nil...)
319 _ = all
320 type item struct {
321 op wire.OutPoint
322 src string
323 }
324 var items []item
325 for _, e := range base {
326 items = append(items, item{e.OutPoint, "base"})
327 }
328 for _, tc := range ts {
329 items = append(items, item{tc.OutPoint, "made"})
330 }
331 sortBySetOps(items, func(a, b item) bool {
332 return utxo.LessEntry(utxo.Entry{OutPoint: a.op}, utxo.Entry{OutPoint: b.op})
333 })
334 for i, it := range items {
335 t.Logf(" %d %s %x idx=%d", i, it.src, it.op.Hash[:4], it.op.Index)
336 }
337 }
338
339 // TestWalkVersusInterlock builds the expected union by interleaving base and
340 // creations with the set's comparison, and compares it with the walk's set and
341 // with the merge's.
342 func TestWalkVersusInterlock(t *testing.T) {
343 base := nodeEntriesAt4(t)
344 ts, walk := nodeSecondRange(t, base)
345 var expect []utxo.Entry
346 expect = append(expect, base...)
347 for _, tc := range ts {
348 expect = append(expect, tc.New)
349 }
350 sortEntries(expect)
351 if NameOf(expect) == NameOf(walk) {
352 t.Logf("the walk is the interlock")
353 } else {
354 t.Logf("the walk is NOT the interlock")
355 }
356 for i := 0; i < len(expect) && i < len(walk); i++ {
357 if expect[i] != walk[i] {
358 t.Logf(" first difference at %d: interlock h=%d v=%d | walk h=%d v=%d",
359 i, expect[i].Height, expect[i].Value, walk[i].Height, walk[i].Value)
360 break
361 }
362 }
363 }
364
365 func sortEntries(s []utxo.Entry) {
366 for i := 1; i < len(s); i++ {
367 for j := i; j > 0 && utxo.LessEntry(s[j], s[j-1]); j-- {
368 s[j], s[j-1] = s[j-1], s[j]
369 }
370 }
371 }
372
373 func sortBySetOps[T any](s []T, less func(a, b T) bool) {
374 for i := 1; i < len(s); i++ {
375 for j := i; j > 0 && less(s[j], s[j-1]); j-- {
376 s[j], s[j-1] = s[j-1], s[j]
377 }
378 }
379 }
380
381 // TestSynthFromNodeBaseDump2 prints every entry of both sets after the height
382 // fix, so the difference is a list and not a name.
383 func TestSynthFromNodeBaseDump2(t *testing.T) {
384 base := nodeEntriesAt4(t)
385 ts, walk := nodeSecondRange(t, base)
386 dir := t.TempDir()
387 _, _ = WriteSet(dir, 0, base)
388 _, _ = Promote(dir, 0)
389 _, _ = CutRange(dir, 0, 1, ts)
390 d, _ := LoadDiff(dir, 0, 1)
391 _, _ = MergeRange(dir, 0, 1, d, chainhash.Hash{})
392 raw, _ := os.ReadFile(filepath.Join(dir, SetFile(1)))
393 buf := make([]byte, EntrySize)
394 var got []utxo.Entry
395 for i := 0; i+EntrySize <= len(raw); i += EntrySize {
396 copy(buf, raw[i:i+EntrySize])
397 got = append(got, utxo.Decode(buf))
398 }
399 t.Logf("walk %d, merge %d", len(walk), len(got))
400 for i := 0; i < len(walk) || i < len(got); i++ {
401 var w, g string
402 if i < len(walk) {
403 w = fmt.Sprintf("%x:%d v=%d h=%d", walk[i].OutPoint.Hash[:2], walk[i].OutPoint.Index, walk[i].Value, walk[i].Height)
404 }
405 if i < len(got) {
406 g = fmt.Sprintf("%x:%d v=%d h=%d", got[i].OutPoint.Hash[:2], got[i].OutPoint.Index, got[i].Value, got[i].Height)
407 }
408 mark := ""
409 if w != g {
410 mark = " <<<"
411 }
412 t.Logf(" %2d walk [%s] merge [%s]%s", i, w, g, mark)
413 }
414 }
415