arena_rapid_test.go raw
1 // Copyright (c) 2026 The btcsuite developers
2 // Use of this source code is governed by an ISC
3 // license that can be found in the LICENSE file.
4
5 package wire
6
7 import (
8 "bytes"
9 "sync"
10 "testing"
11
12 "github.com/stretchr/testify/require"
13 "pgregory.net/rapid"
14 )
15
16 // poisonScriptArena scribbles over the exact chunks used by a decode. A
17 // decoded transaction that still aliases its staging arena will be corrupted.
18 func poisonScriptArena(ar *scriptArena) {
19 for _, chunk := range ar.chunks {
20 for i := range *chunk {
21 (*chunk)[i] = 0xaa
22 }
23 }
24 }
25
26 // genScript returns a rapid generator for a non-nil script of up to maxLen
27 // bytes. Zero-length scripts are always non-nil so that decoded messages,
28 // which never produce nil scripts, compare equal structurally.
29 func genScript(rt *rapid.T, label string, maxLen int) []byte {
30 n := rapid.IntRange(0, maxLen).Draw(rt, label+"Len")
31 s := make([]byte, n)
32 for i := 0; i < n; i++ {
33 s[i] = byte(rapid.IntRange(0, 255).Draw(rt, label+"Byte"))
34 }
35 return s
36 }
37
38 // genMsgTx generates a structurally valid random transaction. Script and
39 // witness sizes are biased small like real traffic but occasionally exceed
40 // the 16 KiB starting chunk class so the arena growth path is exercised.
41 func genMsgTx(rt *rapid.T) *MsgTx {
42 tx := NewMsgTx(int32(rapid.IntRange(0, 2).Draw(rt, "version")))
43
44 // Most generated scripts are small, but roughly one in ten draws
45 // from a range that overflows the first chunk class.
46 scriptMax := 512
47 if rapid.IntRange(0, 9).Draw(rt, "bigScripts") == 0 {
48 scriptMax = 3 * scriptChunkClasses[0]
49 }
50
51 numIn := rapid.IntRange(1, 6).Draw(rt, "numIn")
52 hasWitness := rapid.Bool().Draw(rt, "hasWitness")
53 for i := 0; i < numIn; i++ {
54 ti := &TxIn{
55 PreviousOutPoint: OutPoint{
56 Index: uint32(rapid.IntRange(0, 1<<30).Draw(
57 rt, "prevIndex",
58 )),
59 },
60 SignatureScript: genScript(rt, "sigScript", scriptMax),
61 Sequence: uint32(
62 rapid.IntRange(0, 1<<30).Draw(rt, "sequence"),
63 ),
64 }
65 for j := range ti.PreviousOutPoint.Hash {
66 ti.PreviousOutPoint.Hash[j] = byte(
67 rapid.IntRange(0, 255).Draw(rt, "prevHash"),
68 )
69 }
70
71 // When the transaction is witnessy every input carries a
72 // (possibly empty) non-nil witness stack, matching what the
73 // decoder produces.
74 if hasWitness {
75 numItems := rapid.IntRange(0, 3).Draw(rt, "numWitness")
76 ti.Witness = make(TxWitness, numItems)
77 for j := 0; j < numItems; j++ {
78 ti.Witness[j] = genScript(
79 rt, "witnessItem", scriptMax,
80 )
81 }
82 }
83
84 tx.AddTxIn(ti)
85 }
86
87 // A witness marker with zero total witness items is rejected by the
88 // decoder (and never produced by the encoder), so force at least one
89 // item when the transaction claims to be witnessy.
90 if hasWitness && !tx.HasWitness() {
91 tx.TxIn[0].Witness = TxWitness{
92 genScript(rt, "forcedWitness", scriptMax),
93 }
94 }
95
96 numOut := rapid.IntRange(0, 6).Draw(rt, "numOut")
97 for i := 0; i < numOut; i++ {
98 tx.AddTxOut(&TxOut{
99 Value: rapid.Int64Range(0, 1<<40).Draw(rt, "value"),
100 PkScript: genScript(rt, "pkScript", scriptMax),
101 })
102 }
103
104 tx.LockTime = uint32(rapid.IntRange(0, 1<<30).Draw(rt, "lockTime"))
105
106 return tx
107 }
108
109 // TestScriptArenaPropertyTxRoundTrip checks two properties over random
110 // transactions: serialize/deserialize is the identity, and the decoded
111 // transaction owns all of its memory after its exact staging chunks are
112 // overwritten.
113 func TestScriptArenaPropertyTxRoundTrip(t *testing.T) {
114 rapid.Check(t, func(rt *rapid.T) {
115 tx := genMsgTx(rt)
116
117 var wireBuf bytes.Buffer
118 require.NoError(rt, tx.Serialize(&wireBuf))
119
120 ar := borrowScriptArena()
121 defer ar.release()
122
123 buf := binarySerializer.Borrow()
124 defer binarySerializer.Return(buf)
125
126 var decoded MsgTx
127 err := decoded.btcDecode(
128 bytes.NewReader(wireBuf.Bytes()), 0, WitnessEncoding, buf, ar,
129 )
130 require.NoError(rt, err)
131
132 var reserialized bytes.Buffer
133 require.NoError(rt, decoded.Serialize(&reserialized))
134 require.Equal(rt, wireBuf.Bytes(), reserialized.Bytes())
135
136 // Overwrite the exact chunks used by this decode rather than
137 // relying on a later pool lookup to return the same chunks.
138 poisonScriptArena(ar)
139
140 var afterPoison bytes.Buffer
141 require.NoError(rt, decoded.Serialize(&afterPoison))
142 require.Equal(rt, wireBuf.Bytes(), afterPoison.Bytes())
143 })
144 }
145
146 // TestScriptArenaPropertyBlockRoundTrip checks round-trip stability for full
147 // blocks, including the rewinds performed while transactions share an arena.
148 func TestScriptArenaPropertyBlockRoundTrip(t *testing.T) {
149 rapid.Check(t, func(rt *rapid.T) {
150 block := &MsgBlock{Header: blockOne.Header}
151 numTxs := rapid.IntRange(1, 8).Draw(rt, "numTxs")
152 for i := 0; i < numTxs; i++ {
153 block.AddTransaction(genMsgTx(rt))
154 }
155
156 var wireBuf bytes.Buffer
157 require.NoError(rt, block.Serialize(&wireBuf))
158
159 var decoded MsgBlock
160 err := decoded.Deserialize(bytes.NewReader(wireBuf.Bytes()))
161 require.NoError(rt, err)
162
163 var reserialized bytes.Buffer
164 require.NoError(rt, decoded.Serialize(&reserialized))
165 require.Equal(rt, wireBuf.Bytes(), reserialized.Bytes())
166
167 // Decode the serialized block again to exercise arena reuse, then
168 // verify the first decoded block remains stable.
169 var again MsgBlock
170 err = again.Deserialize(bytes.NewReader(reserialized.Bytes()))
171 require.NoError(rt, err)
172
173 var afterReuse bytes.Buffer
174 require.NoError(rt, decoded.Serialize(&afterReuse))
175 require.Equal(rt, wireBuf.Bytes(), afterReuse.Bytes())
176 })
177 }
178
179 // TestScriptArenaPropertyAllocator drives the raw allocator with random
180 // alloc/rewind sequences against a simple model, checking capacity
181 // accounting and that live allocations never alias one another.
182 func TestScriptArenaPropertyAllocator(t *testing.T) {
183 rapid.Check(t, func(rt *rapid.T) {
184 ar := borrowScriptArena()
185 defer ar.release()
186
187 type allocation struct {
188 s []byte
189 marker byte
190 }
191 var live []allocation
192 modelUsed := 0
193
194 verifyLive := func() {
195 for _, a := range live {
196 count := bytes.Count(a.s, []byte{a.marker})
197 require.Equal(rt, len(a.s), count)
198 }
199 }
200
201 steps := rapid.IntRange(1, 60).Draw(rt, "steps")
202 for i := 0; i < steps; i++ {
203 if rapid.IntRange(0, 9).Draw(rt, "op") == 0 {
204 verifyLive()
205 ar.rewind()
206 live = live[:0]
207 modelUsed = 0
208 require.LessOrEqual(rt, len(ar.chunks), 1)
209 continue
210 }
211
212 n := rapid.IntRange(0, 300_000).Draw(rt, "n")
213 s, err := ar.alloc(n)
214
215 // The model predicts exactly when allocation fails.
216 if n > scriptArenaMaxAlloc-modelUsed {
217 require.ErrorIs(
218 rt, err, errScriptArenaFull,
219 )
220 continue
221 }
222 require.NoError(rt, err)
223 require.Len(rt, s, n)
224 require.Equal(rt, n, cap(s))
225 modelUsed += n
226 require.Equal(
227 rt, scriptArenaMaxAlloc-modelUsed,
228 ar.remaining(),
229 )
230
231 marker := byte(len(live) % 251)
232 for j := range s {
233 s[j] = marker
234 }
235 live = append(live, allocation{s: s, marker: marker})
236 }
237 verifyLive()
238 })
239 }
240
241 // TestReadTxOutOwnedScript ensures the script returned by the exported
242 // ReadTxOut has an exact-sized backing allocation owned by the output.
243 func TestReadTxOutOwnedScript(t *testing.T) {
244 const sizeClass = 0
245 size := scriptChunkClasses[sizeClass]
246 testPool := &chunkClassPool{
247 fixed: make(chan *[]byte, 1),
248 pool: sync.Pool{
249 New: func() interface{} {
250 chunk := make([]byte, size)
251 return &chunk
252 },
253 },
254 }
255
256 origPool := scriptChunkPools[sizeClass]
257 scriptChunkPools[sizeClass] = testPool
258 t.Cleanup(func() {
259 scriptChunkPools[sizeClass] = origPool
260 })
261
262 orig := blockOne.Transactions[0].TxOut[0]
263 var buf bytes.Buffer
264 require.NoError(t, WriteTxOut(&buf, 0, 0, orig))
265
266 var txOut TxOut
267 require.NoError(t, ReadTxOut(bytes.NewReader(buf.Bytes()), 0, 0, &txOut))
268 require.Equal(t, orig.PkScript, txOut.PkScript)
269 require.Equal(t, len(txOut.PkScript), cap(txOut.PkScript))
270
271 // ReadTxOut releases its staging arena before returning. Pull the exact
272 // chunk back out of the isolated pool and overwrite it to ensure the
273 // returned script does not alias staging memory.
274 chunk := testPool.get()
275 for i := range *chunk {
276 (*chunk)[i] = 0xaa
277 }
278 require.Equal(t, orig.PkScript, txOut.PkScript)
279 }
280
281 // TestScriptArenaReleaseSafety exercises the misuse guards within a single
282 // ownership interval: double release is a no-op, and a released arena refuses
283 // to allocate even after a rewind.
284 func TestScriptArenaReleaseSafety(t *testing.T) {
285 ar := borrowScriptArena()
286 _, err := ar.alloc(128)
287 require.NoError(t, err)
288
289 ar.release()
290
291 // Allocating through a stale reference must fail loudly.
292 _, err = ar.alloc(1)
293 require.ErrorIs(t, err, errScriptArenaFull)
294
295 // A rewind must not resurrect a released arena.
296 ar.rewind()
297 _, err = ar.alloc(1)
298 require.ErrorIs(t, err, errScriptArenaFull)
299
300 // Double release must be a no-op rather than double-inserting the
301 // arena into the pool.
302 ar.release()
303
304 // A fresh borrow resets the poisoned state.
305 fresh := borrowScriptArena()
306 defer fresh.release()
307 s, err := fresh.alloc(32)
308 require.NoError(t, err)
309 require.Len(t, s, 32)
310 }
311