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 "errors"
9 "sync"
10 )
11 12 // This file implements a small bump allocator ("script arena") used to stage
13 // variable-length scripts and witness items while a transaction is being
14 // decoded from the wire. Once a transaction is fully decoded, all of its
15 // scripts are copied into a single exactly-sized allocation before the arena
16 // is reused. A successful decode therefore leaves no arena-backed scripts
17 // in the transaction. A failed public transaction decode clears its inputs
18 // and outputs before releasing the arena, while block decoding discards the
19 // failed transaction. This ownership contract makes arena reuse safe without
20 // reference counting.
21 //
22 // The arena replaces the previous fixed 4 MiB script slab. The slab approach
23 // suffered from memory amplification: decoding even a tiny transaction pinned
24 // a full 4 MiB buffer for the duration of the decode, a pool miss allocated
25 // and zeroed 4 MiB, and the channel-based free list could retain hundreds of
26 // megabytes indefinitely since channels are invisible to the garbage
27 // collector's pressure heuristics.
28 //
29 // The arena instead draws fixed-size chunks from a ladder of size classes
30 // backed by sync.Pool and bump-allocates scripts out of them. A decode only
31 // touches memory proportional to the scripts it actually contains: typical
32 // transactions are served entirely by a single 16 KiB chunk while full blocks
33 // walk up to the larger classes. Because the chunk pools are sync.Pools,
34 // idle chunks are released back to the runtime across garbage collection
35 // cycles instead of being pinned forever.
36 37 const (
38 // scriptArenaMaxAlloc is the maximum total number of bytes that may be
39 // bump-allocated from a script arena between rewinds. Since the arena
40 // is rewound for each transaction, this bounds the staged script data
41 // of a single transaction. It intentionally matches the size of the
42 // script slab it replaced in order to preserve the existing decode
43 // limits: no valid transaction can contain more script data than the
44 // maximum block payload, so anything beyond this is malformed.
45 scriptArenaMaxAlloc = 1 << 22
46 47 // maxScriptChunkSize is the size of the largest chunk class. It
48 // must be at least scriptArenaMaxAlloc so that any single allocation
49 // passing the arena capacity check can be satisfied by one chunk;
50 // the compile-time assertion below enforces the coupling.
51 maxScriptChunkSize = 1 << 22
52 )
53 54 // scriptChunkClasses defines the ladder of chunk sizes that back script
55 // arenas. The classes were chosen so that the overwhelmingly common cases
56 // are served by the first chunk borrowed:
57 //
58 // - 16 KiB covers virtually all standalone transactions seen on the
59 // network, which typically carry well under 1 KiB of script data.
60 // - 128 KiB covers large non-standard transactions (the standardness
61 // limit for a transaction is 100 KB).
62 // - 1 MiB covers transactions with unusually large aggregate script data.
63 // - 4 MiB covers the worst case: total script data in a message is
64 // bounded by scriptArenaMaxAlloc, and a single witness item is bounded
65 // by maxWitnessItemSize, so the largest class can always satisfy any
66 // single allocation.
67 var scriptChunkClasses = [...]int{
68 16 << 10,
69 128 << 10,
70 1 << 20,
71 maxScriptChunkSize,
72 }
73 74 // Compile-time assertion that the largest chunk class can satisfy any single
75 // allocation that passes the arena capacity check. grow relies on this: if
76 // scriptArenaMaxAlloc were raised past maxScriptChunkSize, allocSlow could
77 // select a chunk smaller than the requested allocation and panic slicing it.
78 var _ [maxScriptChunkSize - scriptArenaMaxAlloc]byte
79 80 // scriptChunkFixedCaps is the number of chunks per size class that are
81 // retained in a small bounded free list rather than being subject to GC
82 // reclamation. The large classes are the expensive ones to re-create (a
83 // pool miss zeroes the whole chunk), and only a handful are ever live at
84 // once since block decode concurrency is bounded, so pinning a few of them
85 // buys stable block decode performance for at most 16*1 MiB + 8*4 MiB =
86 // 48 MiB, and only once block traffic has actually warmed them. The 1 MiB
87 // class gets the deepest list to absorb concurrent decodes of transactions
88 // with large aggregate script data, while the 4 MiB class only serves the
89 // rare transaction that stages more than 1 MiB. The small classes cost well
90 // under a microsecond to re-create, so they are left entirely to the
91 // GC-cooperating sync.Pool.
92 var scriptChunkFixedCaps = [len(scriptChunkClasses)]int{0, 0, 16, 8}
93 94 // chunkClassPool hands out chunks of a single size class. It layers a
95 // small bounded free list (fixed) in front of a sync.Pool: the fixed list
96 // gives deterministic reuse for the handful of chunks that stay hot, while
97 // the sync.Pool absorbs bursts beyond it and lets the garbage collector
98 // reclaim that overflow when it goes idle. The previous design was a single
99 // channel free list holding up to 125 four-MiB slabs (~524 MB) that the GC
100 // could never reclaim.
101 type chunkClassPool struct {
102 fixed chan *[]byte
103 pool sync.Pool
104 }
105 106 // get returns a chunk for this class, preferring the bounded free list.
107 func (p *chunkClassPool) get() *[]byte {
108 select {
109 case chunk := <-p.fixed:
110 return chunk
111 default:
112 }
113 return p.pool.Get().(*[]byte)
114 }
115 116 // put returns a chunk to this class, refilling the bounded free list first
117 // and spilling the rest into the sync.Pool.
118 func (p *chunkClassPool) put(chunk *[]byte) {
119 select {
120 case p.fixed <- chunk:
121 default:
122 p.pool.Put(chunk)
123 }
124 }
125 126 // scriptChunkPools holds one pool per chunk size class.
127 var scriptChunkPools = func() [len(scriptChunkClasses)]*chunkClassPool {
128 var pools [len(scriptChunkClasses)]*chunkClassPool
129 for i := range scriptChunkClasses {
130 size := scriptChunkClasses[i]
131 pools[i] = &chunkClassPool{
132 fixed: make(chan *[]byte, scriptChunkFixedCaps[i]),
133 pool: sync.Pool{
134 New: func() interface{} {
135 b := make([]byte, size)
136 return &b
137 },
138 },
139 }
140 }
141 return pools
142 }()
143 144 // putScriptChunk returns a chunk to the pool for its size class. Chunks
145 // are only ever created by the class pools, so their lengths always match a
146 // class size exactly. A chunk whose size matches no class can only mean
147 // internal corruption, and reusing it would hand some future allocation a
148 // buffer too small for the capacity it was granted, so a slice bounds check
149 // would panic deep inside a decode. Failing loudly here instead pinpoints
150 // the corruption at the source.
151 func putScriptChunk(chunk *[]byte) {
152 for i, size := range scriptChunkClasses {
153 if len(*chunk) == size {
154 scriptChunkPools[i].put(chunk)
155 return
156 }
157 }
158 159 panic("putScriptChunk: chunk size matches no class")
160 }
161 162 // errScriptArenaFull is returned by alloc when satisfying the request would
163 // push the total bytes allocated since the last rewind beyond
164 // scriptArenaMaxAlloc.
165 var errScriptArenaFull = errors.New("script arena capacity exceeded")
166 167 // scriptArena is a bump allocator for transient script buffers used during
168 // transaction decoding. Allocations are carved out of fixed-size chunks
169 // drawn from the tiered chunk pools, and the entire arena is freed at once
170 // via release (or recycled via rewind), so individual allocations carry no
171 // bookkeeping at all.
172 //
173 // The zero value is not usable; arenas must be obtained via
174 // borrowScriptArena and returned via release. Arenas are not safe for
175 // concurrent use, mirroring the decode paths they serve.
176 type scriptArena struct {
177 // chunks holds every chunk currently borrowed from the class pools,
178 // in the order they were acquired. The last entry backs cur.
179 chunks []*[]byte
180 181 // cur is the chunk allocations are currently served from and off is
182 // the bump offset within it.
183 cur []byte
184 off int
185 186 // used tracks the total bytes handed out since the last rewind. It
187 // is capped at scriptArenaMaxAlloc to preserve the per-transaction
188 // decode limit previously enforced by the fixed slab size.
189 used int
190 191 // dead marks an arena that has been released. A dead arena rejects all
192 // allocations and ignores rewinds until the arena is borrowed again.
193 // Arenas have a single lexical owner and references must not be retained
194 // after release.
195 dead bool
196 }
197 198 // scriptArenaPool recycles the arena structs themselves so that decoding a
199 // message does not allocate any bookkeeping state in the steady state.
200 var scriptArenaPool = sync.Pool{
201 New: func() interface{} {
202 return new(scriptArena)
203 },
204 }
205 206 // borrowScriptArena returns an arena ready to stage script data. Chunks
207 // are borrowed lazily, so an arena that never allocates never touches the
208 // chunk pools. The returned arena must be handed back via release.
209 //
210 // Forgetting to call release is safe in the memory sense: the chunks are
211 // ordinary garbage collected slices, so an abandoned arena is simply
212 // reclaimed by the GC and only the pooling benefit is lost.
213 func borrowScriptArena() *scriptArena {
214 a := scriptArenaPool.Get().(*scriptArena)
215 a.used = 0
216 a.dead = false
217 return a
218 }
219 220 // remaining returns the number of bytes that may still be allocated before
221 // the arena reaches its total capacity.
222 func (a *scriptArena) remaining() int {
223 return scriptArenaMaxAlloc - a.used
224 }
225 226 // alloc returns a slice of exactly n bytes carved from the arena. The
227 // returned slice has its capacity clamped to its length so that appends by
228 // callers can never bleed into neighboring allocations. The contents are
229 // not zeroed; callers are expected to fully overwrite the buffer (the decode
230 // path fills every allocation with io.ReadFull).
231 //
232 // alloc fails with errScriptArenaFull once the total bytes handed out since
233 // the last rewind would exceed scriptArenaMaxAlloc, and for any negative
234 // size. The decode path never passes a negative size, but rejecting one
235 // here keeps alloc total on any input rather than panicking on the slice
236 // bounds below, which the remaining-budget check alone does not catch.
237 func (a *scriptArena) alloc(n int) ([]byte, error) {
238 if n < 0 || n > a.remaining() {
239 return nil, errScriptArenaFull
240 }
241 if n > len(a.cur)-a.off {
242 return a.allocSlow(n)
243 }
244 245 end := a.off + n
246 s := a.cur[a.off:end:end]
247 a.off = end
248 a.used += n
249 250 return s, nil
251 }
252 253 // allocSlow services an allocation that does not fit in the current chunk
254 // by growing first. It is kept separate so the common in-chunk alloc path
255 // stays small; alloc itself still lands just past the compiler's inlining
256 // budget due to the call here, which is left as a future optimization.
257 func (a *scriptArena) allocSlow(n int) ([]byte, error) {
258 a.grow(n)
259 260 s := a.cur[:n:n]
261 a.off = n
262 a.used += n
263 264 return s, nil
265 }
266 267 // grow borrows a new chunk large enough to hold n bytes and makes it the
268 // current chunk. The chunk comes from the smallest size class that
269 // holds both n and one more byte than the current chunk, so consecutive
270 // growths walk up the ladder and converge to the largest class in a
271 // constant number of steps without any per-arena class bookkeeping. Any
272 // request is satisfiable because callers bound n by the arena capacity,
273 // which equals the largest class size.
274 func (a *scriptArena) grow(n int) {
275 sizeClass := 0
276 for scriptChunkClasses[sizeClass] < max(n, len(a.cur)+1) {
277 sizeClass++
278 }
279 280 chunk := scriptChunkPools[sizeClass].get()
281 a.chunks = append(a.chunks, chunk)
282 a.cur = *chunk
283 a.off = 0
284 }
285 286 // rewind resets the arena so previously allocated memory is reused from the
287 // start, invalidating every slice handed out since the last rewind. It is
288 // called between transactions while decoding a block: each transaction copies
289 // its scripts into a single exactly-sized allocation before decoding of the
290 // next one begins, so the staged data is already dead by the time rewind
291 // runs.
292 //
293 // To keep the reused footprint minimal, only the largest chunk is retained;
294 // smaller chunks acquired while the arena was warming up are returned to
295 // their pools.
296 func (a *scriptArena) rewind() {
297 // A released arena stays dead: rewinding must not resurrect its
298 // capacity, otherwise a stale reference could allocate out of chunks
299 // that have already been handed to another decode.
300 if a.dead {
301 return
302 }
303 304 a.used = 0
305 a.off = 0
306 307 // The common case by far is a single chunk (a transaction that fit
308 // its starting class), where cur already points at it and resetting
309 // the offsets above is all that's needed.
310 if len(a.chunks) <= 1 {
311 return
312 }
313 314 a.rewindSlow()
315 }
316 317 // rewindSlow handles the multi-chunk case of rewind, kept out of line so
318 // the hot single-chunk rewind path stays small enough to inline.
319 func (a *scriptArena) rewindSlow() {
320 // Find the largest chunk, return the rest, and continue serving
321 // allocations from it.
322 largest := 0
323 for i := 1; i < len(a.chunks); i++ {
324 if len(*a.chunks[i]) > len(*a.chunks[largest]) {
325 largest = i
326 }
327 }
328 keep := a.chunks[largest]
329 for i, chunk := range a.chunks {
330 if i != largest {
331 putScriptChunk(chunk)
332 }
333 a.chunks[i] = nil
334 }
335 336 a.chunks = append(a.chunks[:0], keep)
337 a.cur = *keep
338 // Nothing else to do: grow derives the next class from the retained
339 // chunk's size, so there is no class cursor to reposition.
340 }
341 342 // release returns every chunk to its class pool and recycles the arena
343 // struct itself. All slices previously returned by alloc are invalidated.
344 //
345 // release is idempotent until the arena is borrowed again: a second call on
346 // an already released arena is a no-op rather than double-inserting it into
347 // the pool. A released arena also rejects further allocations until it is
348 // borrowed again. Callers must not retain an arena reference after release.
349 func (a *scriptArena) release() {
350 if a.dead {
351 return
352 }
353 354 for i, chunk := range a.chunks {
355 putScriptChunk(chunk)
356 a.chunks[i] = nil
357 }
358 a.chunks = a.chunks[:0]
359 a.cur = nil
360 a.off = 0
361 362 // Poison the capacity so any alloc through a stale reference fails
363 // with errScriptArenaFull rather than succeeding against recycled
364 // memory. One past the limit makes remaining negative, so even a
365 // zero-length alloc is rejected.
366 a.used = scriptArenaMaxAlloc + 1
367 a.dead = true
368 369 scriptArenaPool.Put(a)
370 }
371