arena_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  	"fmt"
  10  	"math/rand"
  11  	"sync"
  12  	"testing"
  13  
  14  	"github.com/stretchr/testify/require"
  15  )
  16  
  17  // TestScriptArenaAlloc ensures basic allocation invariants: exact lengths,
  18  // capacity clamped to length, and no overlap between consecutive
  19  // allocations.
  20  func TestScriptArenaAlloc(t *testing.T) {
  21  	ar := borrowScriptArena()
  22  	defer ar.release()
  23  
  24  	sizes := []int{0, 1, 25, 512, 1000, 33}
  25  	allocs := make([][]byte, 0, len(sizes))
  26  	for _, size := range sizes {
  27  		s, err := ar.alloc(size)
  28  		require.NoError(t, err)
  29  		require.Len(t, s, size)
  30  		require.Equal(t, size, cap(s))
  31  
  32  		// Fill the allocation with a marker so overlap with any
  33  		// other allocation is detectable below.
  34  		for i := range s {
  35  			s[i] = byte(len(allocs))
  36  		}
  37  		allocs = append(allocs, s)
  38  	}
  39  
  40  	// Every allocation must still hold its own marker; a bump allocator
  41  	// bug that handed out overlapping memory would have clobbered one of
  42  	// the earlier allocations.
  43  	for marker, s := range allocs {
  44  		require.Equal(
  45  			t, len(s), bytes.Count(s, []byte{byte(marker)}),
  46  		)
  47  	}
  48  }
  49  
  50  // TestScriptArenaGrowth ensures the arena walks up the chunk size class
  51  // ladder as demand grows and that a single allocation larger than the next
  52  // class skips ahead to a class that fits it.
  53  func TestScriptArenaGrowth(t *testing.T) {
  54  	ar := borrowScriptArena()
  55  	defer ar.release()
  56  
  57  	// The first allocation draws the starting class.
  58  	_, err := ar.alloc(100)
  59  	require.NoError(t, err)
  60  	require.Len(t, ar.chunks, 1)
  61  	require.Equal(t, scriptChunkClasses[0], len(*ar.chunks[0]))
  62  
  63  	// Exhausting the first chunk must borrow the next class up.
  64  	_, err = ar.alloc(scriptChunkClasses[0])
  65  	require.NoError(t, err)
  66  	require.Len(t, ar.chunks, 2)
  67  	require.Equal(t, scriptChunkClasses[1], len(*ar.chunks[1]))
  68  
  69  	// An allocation bigger than the next class in the ladder must skip
  70  	// ahead to one that fits it in a single chunk.
  71  	_, err = ar.alloc(scriptChunkClasses[2] + 1)
  72  	require.NoError(t, err)
  73  	require.Len(t, ar.chunks, 3)
  74  	require.Equal(
  75  		t, scriptChunkClasses[len(scriptChunkClasses)-1],
  76  		len(*ar.chunks[2]),
  77  	)
  78  }
  79  
  80  // TestScriptArenaAllocNegativeSize ensures a negative allocation size is
  81  // rejected with errScriptArenaFull.  The decode path never passes one, but
  82  // a caller that did would otherwise panic on slice bounds since the
  83  // capacity check only compares against the remaining budget.
  84  func TestScriptArenaAllocNegativeSize(t *testing.T) {
  85  	ar := borrowScriptArena()
  86  	defer ar.release()
  87  
  88  	for _, size := range []int{-1, -58, -(8 << 20)} {
  89  		_, err := ar.alloc(size)
  90  		require.ErrorIs(t, err, errScriptArenaFull, "size %d", size)
  91  	}
  92  
  93  	// Rejected allocations must not consume any of the budget.
  94  	require.Equal(t, scriptArenaMaxAlloc, ar.remaining())
  95  }
  96  
  97  // TestScriptArenaCapacity ensures the arena enforces the per-transaction
  98  // staging limit that the fixed slab previously provided.
  99  func TestScriptArenaCapacity(t *testing.T) {
 100  	ar := borrowScriptArena()
 101  	defer ar.release()
 102  
 103  	// Fill the arena right up to its capacity.
 104  	_, err := ar.alloc(scriptArenaMaxAlloc - 1)
 105  	require.NoError(t, err)
 106  	require.Equal(t, 1, ar.remaining())
 107  
 108  	_, err = ar.alloc(1)
 109  	require.NoError(t, err)
 110  	require.Equal(t, 0, ar.remaining())
 111  
 112  	// The next allocation must fail, and a rewind must restore the full
 113  	// capacity.
 114  	_, err = ar.alloc(1)
 115  	require.ErrorIs(t, err, errScriptArenaFull)
 116  
 117  	ar.rewind()
 118  	require.Equal(t, scriptArenaMaxAlloc, ar.remaining())
 119  
 120  	_, err = ar.alloc(1)
 121  	require.NoError(t, err)
 122  }
 123  
 124  // TestScriptArenaRewind ensures rewinding recycles the memory of the largest
 125  // chunk in place and returns the smaller warm-up chunks to their pools.
 126  func TestScriptArenaRewind(t *testing.T) {
 127  	ar := borrowScriptArena()
 128  	defer ar.release()
 129  
 130  	// Grow through two classes.
 131  	_, err := ar.alloc(scriptChunkClasses[0])
 132  	require.NoError(t, err)
 133  	_, err = ar.alloc(scriptChunkClasses[0])
 134  	require.NoError(t, err)
 135  	require.Len(t, ar.chunks, 2)
 136  	largest := *ar.chunks[1]
 137  
 138  	ar.rewind()
 139  
 140  	// Only the largest chunk survives the rewind and subsequent
 141  	// allocations are served from its start.
 142  	require.Len(t, ar.chunks, 1)
 143  	s, err := ar.alloc(8)
 144  	require.NoError(t, err)
 145  
 146  	// The allocation must be served from the retained chunk itself, not
 147  	// from a copy that merely holds equal bytes.
 148  	require.Same(t, &largest[0], &s[0])
 149  }
 150  
 151  // TestBlockArenaTransactionReuse ensures block staging depends on the largest
 152  // transaction rather than the aggregate scripts across the block.
 153  func TestBlockArenaTransactionReuse(t *testing.T) {
 154  	for _, locations := range []bool{false, true} {
 155  		name := "deserialize"
 156  		if locations {
 157  			name = "transaction_locations"
 158  		}
 159  
 160  		t.Run(name, func(t *testing.T) {
 161  			original := scriptChunkPools
 162  			t.Cleanup(func() {
 163  				scriptChunkPools = original
 164  			})
 165  
 166  			var allocated [len(scriptChunkClasses)]int
 167  			for i, size := range scriptChunkClasses {
 168  				scriptChunkPools[i] = &chunkClassPool{
 169  					fixed: make(
 170  						chan *[]byte, scriptChunkFixedCaps[i],
 171  					),
 172  					pool: sync.Pool{New: func() interface{} {
 173  						allocated[i]++
 174  						chunk := make([]byte, size)
 175  						return &chunk
 176  					}},
 177  				}
 178  			}
 179  
 180  			block := MsgBlock{Header: blockOne.Header}
 181  			for i := 0; i < 1000; i++ {
 182  				block.AddTransaction(blockOne.Transactions[0])
 183  			}
 184  
 185  			var encoded bytes.Buffer
 186  			require.NoError(t, block.Serialize(&encoded))
 187  
 188  			var decoded MsgBlock
 189  			if locations {
 190  				locs, err := decoded.DeserializeTxLoc(
 191  					bytes.NewBuffer(encoded.Bytes()),
 192  				)
 193  				require.NoError(t, err)
 194  				require.Len(t, locs, len(block.Transactions))
 195  			} else {
 196  				require.NoError(t, decoded.Deserialize(
 197  					bytes.NewReader(encoded.Bytes()),
 198  				))
 199  			}
 200  
 201  			var roundTrip bytes.Buffer
 202  			require.NoError(t, decoded.Serialize(&roundTrip))
 203  			require.Equal(t, encoded.Bytes(), roundTrip.Bytes())
 204  
 205  			// The whole block must be staged by a single smallest-class
 206  			// chunk: one borrow serves every transaction.
 207  			for i, count := range allocated {
 208  				want := 0
 209  				if i == 0 {
 210  					want = 1
 211  				}
 212  				require.Equal(t, want, count, "class %d", i)
 213  			}
 214  		})
 215  	}
 216  }
 217  
 218  // TestScriptArenaDecodeGrowth decodes a transaction whose script data
 219  // overflows the starting chunk class for standalone transactions, ensuring
 220  // the decode path grows the arena transparently.
 221  func TestScriptArenaDecodeGrowth(t *testing.T) {
 222  	// Build a transaction with a signature script comfortably larger
 223  	// than the 16 KiB starting chunk.
 224  	bigScript := make([]byte, 3*scriptChunkClasses[0])
 225  	rng := rand.New(rand.NewSource(1337))
 226  	rng.Read(bigScript)
 227  
 228  	tx := NewMsgTx(1)
 229  	tx.AddTxIn(&TxIn{
 230  		PreviousOutPoint: OutPoint{Index: 0xffffffff},
 231  		SignatureScript:  bigScript,
 232  		Sequence:         0xffffffff,
 233  	})
 234  	tx.AddTxOut(NewTxOut(0, []byte{0x51}))
 235  
 236  	var buf bytes.Buffer
 237  	require.NoError(t, tx.Serialize(&buf))
 238  
 239  	var decoded MsgTx
 240  	require.NoError(t, decoded.Deserialize(bytes.NewReader(buf.Bytes())))
 241  	require.Equal(t, bigScript, decoded.TxIn[0].SignatureScript)
 242  }
 243  
 244  // TestScriptArenaConcurrentDecode exercises the chunk pools from many
 245  // goroutines at once to give the race detector a chance to catch unsound
 246  // sharing between arenas.
 247  func TestScriptArenaConcurrentDecode(t *testing.T) {
 248  	// Serialize one small and one multi-input transaction as shared
 249  	// decode inputs.
 250  	var smallTxBuf, multiTxBuf bytes.Buffer
 251  	require.NoError(t, blockOne.Transactions[0].Serialize(&smallTxBuf))
 252  	require.NoError(t, multiTx.Serialize(&multiTxBuf))
 253  
 254  	const numWorkers = 16
 255  	const decodesPerWorker = 200
 256  
 257  	var wg sync.WaitGroup
 258  	errs := make(chan error, numWorkers)
 259  	for w := 0; w < numWorkers; w++ {
 260  		wg.Add(1)
 261  		go func() {
 262  			defer wg.Done()
 263  			for i := 0; i < decodesPerWorker; i++ {
 264  				var tx1, tx2 MsgTx
 265  				err := tx1.Deserialize(
 266  					bytes.NewReader(smallTxBuf.Bytes()),
 267  				)
 268  				if err != nil {
 269  					errs <- err
 270  					return
 271  				}
 272  				err = tx2.Deserialize(
 273  					bytes.NewReader(multiTxBuf.Bytes()),
 274  				)
 275  				if err != nil {
 276  					errs <- err
 277  					return
 278  				}
 279  
 280  				// Verify the decoded scripts match the
 281  				// originals so cross-arena aliasing would
 282  				// surface as corruption.
 283  				if !bytes.Equal(
 284  					tx2.TxIn[0].SignatureScript,
 285  					multiTx.TxIn[0].SignatureScript,
 286  				) {
 287  					errs <- fmt.Errorf("cross-arena " +
 288  						"aliasing: decoded script " +
 289  						"mismatch")
 290  					return
 291  				}
 292  			}
 293  		}()
 294  	}
 295  	wg.Wait()
 296  	close(errs)
 297  	for err := range errs {
 298  		require.NoError(t, err)
 299  	}
 300  }
 301  
 302  // TestScriptArenaRandomizedAllocations drives the arena with a deterministic
 303  // random allocation/rewind pattern and checks that live allocations never
 304  // alias each other.
 305  func TestScriptArenaRandomizedAllocations(t *testing.T) {
 306  	rng := rand.New(rand.NewSource(42))
 307  
 308  	for round := 0; round < 50; round++ {
 309  		ar := borrowScriptArena()
 310  
 311  		for rewinds := 0; rewinds < 4; rewinds++ {
 312  			var live [][]byte
 313  			for ar.remaining() > 0 && rng.Float64() > 0.05 {
 314  				n := rng.Intn(64 << 10)
 315  				if n > ar.remaining() {
 316  					n = ar.remaining()
 317  				}
 318  
 319  				s, err := ar.alloc(n)
 320  				require.NoError(t, err)
 321  				require.Len(t, s, n)
 322  
 323  				marker := byte(len(live))
 324  				for i := range s {
 325  					s[i] = marker
 326  				}
 327  				live = append(live, s)
 328  			}
 329  
 330  			// All live allocations must retain their markers.
 331  			for marker, s := range live {
 332  				require.Equal(
 333  					t, len(s),
 334  					bytes.Count(s, []byte{byte(marker)}),
 335  				)
 336  			}
 337  
 338  			ar.rewind()
 339  			require.LessOrEqual(t, len(ar.chunks), 1)
 340  		}
 341  
 342  		ar.release()
 343  	}
 344  }
 345