1 package utxo_test
2 3 import (
4 "bytes"
5 "encoding/binary"
6 "math/rand"
7 "testing"
8 9 "git.smesh.lol/btcd-lite/internal/utxo"
10 "git.smesh.lol/btcd-lite/internal/wire"
11 )
12 13 // op makes an outpoint whose hash comes from i. Hash i at the end of a 32-byte
14 // value is the sorted order of the id, which keeps the set walk easy to check
15 // while the low bytes keep the hash from looking like a chain hash. A single
16 // hash byte as the index would be wrong: it folds every 256th id onto another.
17 func op(i uint32) wire.OutPoint {
18 var h [32]byte
19 binary.LittleEndian.PutUint32(h[:4], i^0xDEADBEEF)
20 binary.BigEndian.PutUint32(h[28:], i)
21 return wire.OutPoint{Hash: h, Index: 0}
22 }
23 24 func entry(i uint32, height uint32) utxo.Entry {
25 return utxo.Entry{OutPoint: op(i), Value: int64(1000 + i), Height: height}
26 }
27 28 // chain produces n heights. Height h creates d outputs (the ids h*d..h*d+d-1)
29 // and spends touchCount outputs that are at least two heights old.
30 //
31 // A simulated block has to stay inside the set the earlier ones built: every
32 // spend names an output some earlier height created and no later height spent.
33 // Writing that down as "draw from what is held" is not enough, because it lets
34 // one simulated block spend more than the height before it left, which is a
35 // chain no set walk can follow. The age check is what fixes the boundary.
36 func chain(n int, d int, seed int64) [][]utxo.Touch {
37 rng := rand.New(rand.NewSource(seed))
38 spendable := map[uint32]int{}
39 var order []uint32
40 out := make([][]utxo.Touch, n)
41 for h := 0; h < n; h++ {
42 var ts []utxo.Touch
43 for k := 0; k < d; k++ {
44 id := uint32(h*d + k)
45 spendable[id] = h
46 order = append(order, id)
47 ts = append(ts, utxo.Touch{OutPoint: op(id), Height: uint32(h), New: entry(id, uint32(h))})
48 }
49 spent := 0
50 for tries := 0; spent < d*7/10 && tries < d*100 && len(order) > 0; tries++ {
51 idx := rng.Intn(len(order))
52 id := order[idx]
53 at, ok := spendable[id]
54 if !ok || h-at < 2 {
55 continue
56 }
57 order = append(order[:idx], order[idx+1:]...)
58 delete(spendable, id)
59 ts = append(ts, utxo.Touch{OutPoint: op(id), Height: uint32(h), Spent: true})
60 spent++
61 }
62 out[h] = ts
63 }
64 return out
65 }
66 67 // TestDiffsComposeAndSplit checks the property the checkpoint model rests on:
68 // the set a range produces from the checkpoint at a equals the set the same
69 // blocks produce per block, and advancing from either to the tip gives the same
70 // chain. The number of heights is small enough that the whole walk is done once
71 // per case.
72 func TestDiffsComposeAndSplit(t *testing.T) {
73 heights := chain(400, 40, 1)
74 set := []utxo.Entry{}
75 for h := range heights {
76 var err error
77 set, err = utxo.ApplyRange(set, heights[h])
78 if err != nil {
79 for _, tt := range heights[h] {
80 if tt.Spent {
81 if _, ok := utxo.Find(set, tt.OutPoint); !ok {
82 t.Fatalf("height %d: set lacks the spent outpoint %s", h, tt.OutPoint)
83 }
84 }
85 }
86 t.Fatalf("height %d: %v", h, err)
87 }
88 if err := utxo.Validate(set); err != nil {
89 t.Fatalf("height %d: %v", h, err)
90 }
91 }
92 for _, a := range []int{0, 3, 12, 25} {
93 for _, b := range []int{a + 1, a + 4, 40} {
94 if b > len(heights) {
95 continue
96 }
97 // The set at a, built by replay from zero, is what a checkpoint
98 // holds. startSet[h] is therefore the set at height h for the rest
99 // of this case.
100 startSet := make([][]utxo.Entry, len(heights)+1)
101 startSet[0] = []utxo.Entry{}
102 for h := 0; h < len(heights); h++ {
103 var err error
104 startSet[h+1], err = utxo.ApplyRange(startSet[h], heights[h])
105 if err != nil {
106 t.Fatalf("replay to %d: %v", h, err)
107 }
108 }
109 // The range is its own copy: the earlier walk appended a height's
110 // touches without a copy of the touches, and a slice of the same
111 // backing array is not a range, it is a view of one.
112 diff := make([]utxo.Touch, 0, b-a)
113 for h := a; h < b; h++ {
114 diff = append(diff, heights[h]...)
115 }
116 mid, err := utxo.ApplyRange(startSet[a], diff)
117 if err != nil {
118 t.Fatalf("[%d,%d): %v", a, b, err)
119 }
120 // The tail is applied a block at a time from the range's result, the
121 // way a chain advances on a checkpoint it was handed, so the range
122 // path and the block path have to agree all the way to the tip.
123 end := mid
124 for h := b; h < len(heights); h++ {
125 if len(startSet[h]) != len(end) && h == b {
126 // The range's result must already equal the checkpoint at b.
127 t.Fatalf("a=%d b=%d: range holds %d entries, checkpoint at %d holds %d", a, b, len(end), b, len(startSet[b]))
128 }
129 end, err = utxo.ApplyRange(end, heights[h])
130 if err != nil {
131 t.Fatalf("a=%d b=%d height %d: %v", a, b, h, err)
132 }
133 }
134 if len(end) != len(set) {
135 t.Fatalf("a=%d b=%d: split set has %d entries, whole has %d", a, b, len(end), len(set))
136 }
137 if !equalSets(end, set) {
138 t.Fatalf("a=%d b=%d: split composition differs from the whole", a, b)
139 }
140 }
141 }
142 }
143 144 func equalSets(a, b []utxo.Entry) bool {
145 if len(a) != len(b) {
146 return false
147 }
148 for i := range a {
149 if a[i] != b[i] {
150 return false
151 }
152 }
153 return true
154 }
155 156 // TestDiffRoundTrip requires a diff to encode and decode to itself and to apply
157 // to the same set.
158 func TestDiffRoundTrip(t *testing.T) {
159 heights := chain(50, 20, 2)
160 var all []utxo.Touch
161 var start, end []utxo.Entry
162 for h := range heights {
163 all = append(all, heights[h]...)
164 }
165 mid := all[:len(all)/2]
166 var err error
167 start, err = utxo.ApplyRange(nil, mid)
168 if err != nil {
169 t.Fatal(err)
170 }
171 end, err = utxo.ApplyRange(start, all[len(all)/2:])
172 if err != nil {
173 t.Fatal(err)
174 }
175 d := utxo.Diff{From: 25, To: 50, Touches: all[len(all)/2:]}
176 raw := d.Encode()
177 back, err := utxo.DecodeDiff(raw)
178 if err != nil {
179 t.Fatalf("decode: %v", err)
180 }
181 if !bytes.Equal(raw, back.Encode()) {
182 t.Fatal("diff does not round trip")
183 }
184 got, err := back.ApplyTo(start)
185 if err != nil {
186 t.Fatal(err)
187 }
188 if !equalSets(got, end) {
189 t.Fatal("decoded diff applies to a different set")
190 }
191 // A truncated diff is refused, not guessed at.
192 if _, err := utxo.DecodeDiff(raw[:len(raw)-5]); err == nil {
193 t.Fatal("a truncated diff decoded")
194 }
195 if _, err := utxo.DecodeDiff(append(raw, 0)); err == nil {
196 t.Fatal("a diff with trailing bytes decoded")
197 }
198 }
199 200 // TestSpendOfAbsentIsRefused requires a set walk to refuse a spend of something
201 // that is not there, which is the only way a chain replay goes wrong silently.
202 func TestSpendOfAbsentIsRefused(t *testing.T) {
203 set := []utxo.Entry{entry(1, 0), entry(2, 0)}
204 _, err := utxo.ApplyRange(set, []utxo.Touch{{OutPoint: op(99), Height: 1, Spent: true}})
205 if err == nil {
206 t.Fatal("a spend of an absent outpoint was applied")
207 }
208 // A creation at a height the set does not have for the outpoint is a second
209 // history for one outpoint, and is refused.
210 _, err = utxo.ApplyRange(set, []utxo.Touch{{OutPoint: op(1), Height: 1, New: entry(1, 1)}})
211 if err == nil {
212 t.Fatal("a creation of an outpoint the set holds at another height was applied")
213 }
214 // The same output at the same height is the same output: a replay of an
215 // already-applied range is a no-op, not an error.
216 same, err := utxo.ApplyRange(set, []utxo.Touch{{OutPoint: op(1), Height: 0, New: set[0]}})
217 if err != nil || !equalSets(same, set) {
218 t.Fatalf("idempotent replay: %v", err)
219 }
220 _, err = utxo.ApplyRange(set, []utxo.Touch{
221 {OutPoint: op(1), Height: 1, Spent: true},
222 {OutPoint: op(1), Height: 1, Spent: true},
223 })
224 if err == nil {
225 t.Fatal("a double spend in one range was applied")
226 }
227 // A creation and a spend of the same outpoint in one range net to nothing.
228 got, err := utxo.ApplyRange([]utxo.Entry{}, []utxo.Touch{
229 {OutPoint: op(5), Height: 1, New: entry(5, 1)},
230 {OutPoint: op(5), Height: 9, Spent: true},
231 })
232 if err != nil || len(got) != 0 {
233 t.Fatalf("create and spend in one range: %v %d", err, len(got))
234 }
235 }
236