package utxo_test import ( "bytes" "encoding/binary" "math/rand" "testing" "git.smesh.lol/btcd-lite/internal/utxo" "git.smesh.lol/btcd-lite/internal/wire" ) // op makes an outpoint whose hash comes from i. Hash i at the end of a 32-byte // value is the sorted order of the id, which keeps the set walk easy to check // while the low bytes keep the hash from looking like a chain hash. A single // hash byte as the index would be wrong: it folds every 256th id onto another. func op(i uint32) wire.OutPoint { var h [32]byte binary.LittleEndian.PutUint32(h[:4], i^0xDEADBEEF) binary.BigEndian.PutUint32(h[28:], i) return wire.OutPoint{Hash: h, Index: 0} } func entry(i uint32, height uint32) utxo.Entry { return utxo.Entry{OutPoint: op(i), Value: int64(1000 + i), Height: height} } // chain produces n heights. Height h creates d outputs (the ids h*d..h*d+d-1) // and spends touchCount outputs that are at least two heights old. // // A simulated block has to stay inside the set the earlier ones built: every // spend names an output some earlier height created and no later height spent. // Writing that down as "draw from what is held" is not enough, because it lets // one simulated block spend more than the height before it left, which is a // chain no set walk can follow. The age check is what fixes the boundary. func chain(n int, d int, seed int64) [][]utxo.Touch { rng := rand.New(rand.NewSource(seed)) spendable := map[uint32]int{} var order []uint32 out := make([][]utxo.Touch, n) for h := 0; h < n; h++ { var ts []utxo.Touch for k := 0; k < d; k++ { id := uint32(h*d + k) spendable[id] = h order = append(order, id) ts = append(ts, utxo.Touch{OutPoint: op(id), Height: uint32(h), New: entry(id, uint32(h))}) } spent := 0 for tries := 0; spent < d*7/10 && tries < d*100 && len(order) > 0; tries++ { idx := rng.Intn(len(order)) id := order[idx] at, ok := spendable[id] if !ok || h-at < 2 { continue } order = append(order[:idx], order[idx+1:]...) delete(spendable, id) ts = append(ts, utxo.Touch{OutPoint: op(id), Height: uint32(h), Spent: true}) spent++ } out[h] = ts } return out } // TestDiffsComposeAndSplit checks the property the checkpoint model rests on: // the set a range produces from the checkpoint at a equals the set the same // blocks produce per block, and advancing from either to the tip gives the same // chain. The number of heights is small enough that the whole walk is done once // per case. func TestDiffsComposeAndSplit(t *testing.T) { heights := chain(400, 40, 1) set := []utxo.Entry{} for h := range heights { var err error set, err = utxo.ApplyRange(set, heights[h]) if err != nil { for _, tt := range heights[h] { if tt.Spent { if _, ok := utxo.Find(set, tt.OutPoint); !ok { t.Fatalf("height %d: set lacks the spent outpoint %s", h, tt.OutPoint) } } } t.Fatalf("height %d: %v", h, err) } if err := utxo.Validate(set); err != nil { t.Fatalf("height %d: %v", h, err) } } for _, a := range []int{0, 3, 12, 25} { for _, b := range []int{a + 1, a + 4, 40} { if b > len(heights) { continue } // The set at a, built by replay from zero, is what a checkpoint // holds. startSet[h] is therefore the set at height h for the rest // of this case. startSet := make([][]utxo.Entry, len(heights)+1) startSet[0] = []utxo.Entry{} for h := 0; h < len(heights); h++ { var err error startSet[h+1], err = utxo.ApplyRange(startSet[h], heights[h]) if err != nil { t.Fatalf("replay to %d: %v", h, err) } } // The range is its own copy: the earlier walk appended a height's // touches without a copy of the touches, and a slice of the same // backing array is not a range, it is a view of one. diff := make([]utxo.Touch, 0, b-a) for h := a; h < b; h++ { diff = append(diff, heights[h]...) } mid, err := utxo.ApplyRange(startSet[a], diff) if err != nil { t.Fatalf("[%d,%d): %v", a, b, err) } // The tail is applied a block at a time from the range's result, the // way a chain advances on a checkpoint it was handed, so the range // path and the block path have to agree all the way to the tip. end := mid for h := b; h < len(heights); h++ { if len(startSet[h]) != len(end) && h == b { // The range's result must already equal the checkpoint at b. t.Fatalf("a=%d b=%d: range holds %d entries, checkpoint at %d holds %d", a, b, len(end), b, len(startSet[b])) } end, err = utxo.ApplyRange(end, heights[h]) if err != nil { t.Fatalf("a=%d b=%d height %d: %v", a, b, h, err) } } if len(end) != len(set) { t.Fatalf("a=%d b=%d: split set has %d entries, whole has %d", a, b, len(end), len(set)) } if !equalSets(end, set) { t.Fatalf("a=%d b=%d: split composition differs from the whole", a, b) } } } } func equalSets(a, b []utxo.Entry) bool { if len(a) != len(b) { return false } for i := range a { if a[i] != b[i] { return false } } return true } // TestDiffRoundTrip requires a diff to encode and decode to itself and to apply // to the same set. func TestDiffRoundTrip(t *testing.T) { heights := chain(50, 20, 2) var all []utxo.Touch var start, end []utxo.Entry for h := range heights { all = append(all, heights[h]...) } mid := all[:len(all)/2] var err error start, err = utxo.ApplyRange(nil, mid) if err != nil { t.Fatal(err) } end, err = utxo.ApplyRange(start, all[len(all)/2:]) if err != nil { t.Fatal(err) } d := utxo.Diff{From: 25, To: 50, Touches: all[len(all)/2:]} raw := d.Encode() back, err := utxo.DecodeDiff(raw) if err != nil { t.Fatalf("decode: %v", err) } if !bytes.Equal(raw, back.Encode()) { t.Fatal("diff does not round trip") } got, err := back.ApplyTo(start) if err != nil { t.Fatal(err) } if !equalSets(got, end) { t.Fatal("decoded diff applies to a different set") } // A truncated diff is refused, not guessed at. if _, err := utxo.DecodeDiff(raw[:len(raw)-5]); err == nil { t.Fatal("a truncated diff decoded") } if _, err := utxo.DecodeDiff(append(raw, 0)); err == nil { t.Fatal("a diff with trailing bytes decoded") } } // TestSpendOfAbsentIsRefused requires a set walk to refuse a spend of something // that is not there, which is the only way a chain replay goes wrong silently. func TestSpendOfAbsentIsRefused(t *testing.T) { set := []utxo.Entry{entry(1, 0), entry(2, 0)} _, err := utxo.ApplyRange(set, []utxo.Touch{{OutPoint: op(99), Height: 1, Spent: true}}) if err == nil { t.Fatal("a spend of an absent outpoint was applied") } // A creation at a height the set does not have for the outpoint is a second // history for one outpoint, and is refused. _, err = utxo.ApplyRange(set, []utxo.Touch{{OutPoint: op(1), Height: 1, New: entry(1, 1)}}) if err == nil { t.Fatal("a creation of an outpoint the set holds at another height was applied") } // The same output at the same height is the same output: a replay of an // already-applied range is a no-op, not an error. same, err := utxo.ApplyRange(set, []utxo.Touch{{OutPoint: op(1), Height: 0, New: set[0]}}) if err != nil || !equalSets(same, set) { t.Fatalf("idempotent replay: %v", err) } _, err = utxo.ApplyRange(set, []utxo.Touch{ {OutPoint: op(1), Height: 1, Spent: true}, {OutPoint: op(1), Height: 1, Spent: true}, }) if err == nil { t.Fatal("a double spend in one range was applied") } // A creation and a spend of the same outpoint in one range net to nothing. got, err := utxo.ApplyRange([]utxo.Entry{}, []utxo.Touch{ {OutPoint: op(5), Height: 1, New: entry(5, 1)}, {OutPoint: op(5), Height: 9, Spent: true}, }) if err != nil || len(got) != 0 { t.Fatalf("create and spend in one range: %v %d", err, len(got)) } }