WIP: kernel: add btck_witness_stack_get_items

bitcoin/bitcoin: PR #36909

2 minor findings · 1 suggestion

Earlier concerns neither republished nor resolved: 2 suggestions. See the Run archive for their assessments.

Findings

Link

[minor] · VerifyWitnessProgram expands witnesses on non-executing paths

ToVectors() now copies witnesses even on non-executing paths, adding verification work for Taproot key-path spends and unknown versions; no real-chain occurrence of the large unknown-version case is known.

Location: src/script/interpreter.cpp:1929 (head).

Details and suggested fix

ToVectors() reserves one vector per element before checking the witness version or spending path. Unknown versions, P2A, Taproot key-path spends, unknown leaf versions, the Taproot-disabled return, and early size or commitment failures therefore materialize an execution stack they never execute. Base used a span on these paths. A miner-included v2 spend with about 3.99 million empty witness elements can fit within the 4M-WU block limit and pass block script checks, yet this conversion reserves roughly 91 MiB with 24-byte vectors. That is a static estimate, not a measurement. The regression is extra verification-time work and lost packed-storage savings: base already retained expanded witnesses, and head still expands them temporarily during deserialization, so this does not establish a higher overall memory peak or a consensus change.

Use the immutable witness interface for dispatch and annex, control-block, and script inspection. Call ToVectors() only on paths reaching ExecuteWitnessScript, remove the role elements, and move the remaining stack into execution. Preserve annex hashing, unknown-version and unknown-leaf acceptance, and the existing OP_SUCCESS-before-stack-limit ordering.


Link

[minor] · Kernel Items() still performs quadratic witness traversal

The existing Items() range now traverses witnesses quadratically despite the linear GetItems() alternative; no in-tree production caller was found, so downstream impact is unconfirmed.

Location: src/kernel/bitcoinkernel.cpp:875 (head).

Details and suggested fix

Items() still uses GetItem(i) for every dereference, and btck_witness_stack_get_item_at now calls CScriptWitness::operator[], which walks past all preceding elements. A full traversal therefore performs about n²/2 element-decoding steps instead of base's linear traversal. If a kernel application uses this range on a miner-included unknown-version spend containing millions of empty items, it can spend an impractical amount of time traversing the witness. The new bulk accessor avoids this only when callers explicitly switch to it, and the public getter documentation does not explain that distinction. Back Items(), or a replacement range, with one bulk fetch. At minimum, document the O(index) cost of btck_witness_stack_get_item_at and GetItem, the quadratic cost of traversing Items(), and the linear bulk alternatives.


Optional improvements

Link

[suggestion] · btck_witness_stack_get_items lifetime contract lacks direct coverage

The new tests copy the C accessor's results immediately, leaving its borrowed-pointer lifetime and explicit nullptr output-array contract unchecked.

Location: src/test/kernel/test_kernel.cpp:587 (head).

Details and suggested fix

GetItems() immediately converts the returned pointers into owned vectors, so these assertions do not check the new C API's lifetime guarantee. Reuse the four-item fixture to obtain raw pointer and size arrays from an owned WitnessStack copy. Destroy the originating transaction and input, then compare the bytes through those pointers while keeping the copied witness alive. Include the zero-length first item without requiring its pointer to be non-null. Also call btck_witness_stack_get_items explicitly with nullptr, nullptr, 0 on the empty witness. These small cases directly cover the documented contract that the copying wrapper cannot fully exercise.


Coverage details

Earlier concerns

Earlier reports raised these, with the titles and severities shown there. This review neither republished nor resolved them.

Background

Ralph's summary of historical context for the behaviour affected by this change. The historical record reviewed here is incomplete.

Documented decisions

Witness serialization was designed to preserve compatibility with older transaction parsers while giving witness-aware parsers an unambiguous extended format. BIP144 specifies one stack per input, in input order, encoded as an item count followed by length-prefixed byte strings; an empty stack is one zero byte.

Replacing the vector representation does not change the externally meaningful sequence of items or its encoding. The packed representation's private four-byte allocation header is not part of transaction serialization. Kernel iteration likewise exposes the same bottom-to-top item sequence, rather than script push-opcode encodings.

Source 1

An entirely witness-empty transaction must use the old serialization, and its witness hash equals its ordinary transaction hash. This is a protocol rule, not merely a storage optimization: historical decoding discussion explicitly identifies extended serialization without any witnesses as invalid under BIP144.

Empty-stack semantics control HasWitness(), marker/flag emission and rejection of a superfluous witness record. A stack with zero elements must remain distinct from a stack containing one empty byte string: their encodings are respectively 00 and 01 00, and only the latter supplies witness data.

Source 1 · Source 2

PSBT's format exists to let different wallets and offline signers exchange and combine the same transaction safely. Its records are explicitly length-delimited, with value data required to occupy exactly the declared number of bytes; the unsigned transaction uses old serialization and empty scriptSigs and witnesses.

Routing final-witness serialization through CScriptWitness must retain the existing nested encoding and exact PSBT value boundaries. In pinned code, UnserializeFromVector checks actual consumption against the declared value length, so successful witness decoding alone is not sufficient for a valid PSBT value.

Source 1

Tapscript validation order deliberately protects future soft-fork extensibility. BIP342 requires prior BIP141/BIP341 validity, then opcode decoding with OP_SUCCESS recognition before subsequent execution rules. Its rationale explicitly includes permitting success despite an initial stack exceeding 1,000 elements, excessive signature operations or otherwise problematic script structure.

Execution-stack conversion and resource checks sit inside an order-sensitive consensus procedure. The base interpreter recognizes OP_SUCCESS before checking the Tapscript initial stack count and stack-item sizes. Treating those execution limits as universal witness-decoding limits would erase the documented distinction between transport data and scripts whose semantics are actually executed.

Source 1

The memory threat is amplification from many tiny witness elements, not just large serialized transactions. The earlier witness proposal identifies a 24-byte vector object and per-element allocation overhead. The orphanage proposal quantifies a roughly 398,247-WU transaction using 11.1 MB of deserialized memory, and notes that witness standardness cannot be checked while its inputs are missing.

Wire weight, retained heap usage and temporary execution memory are different resources. Packed witnesses target per-element amplification without making witness acceptance depend on a new policy restriction. The earlier proposal also explicitly connects reduced transaction memory to increased effective capacity of memory-bounded structures such as the mempool; the head's DynamicMemoryUsage accounts for the packed allocation, including its header and allocator accounting.

Source 1 · Source 2

Moving rejection earlier is observably different from merely changing storage. The earlier proposal explicitly warns that P2P deserialization failures drop or ignore messages rather than reaching validation and net-processing behavior, which may include disconnection or reject-filter insertion. It also distinguishes P2P-only restrictions from RPC compatibility requirements.

Canonical decoding, transaction validity and policy rejection are separate boundaries. Preserving failure behavior requires attention to where an input fails, not merely whether it is eventually rejected. The head witness decoder states its intention to retain vector-of-vectors decoding semantics and translates representation length errors into an I/O-style deserialization failure.

Source 1

Earlier discussion identified both iteration cost and execution-stack materialization as independent resource concerns. A policy comment sought to avoid temporary span-vector allocations and quadratic indexed iteration, and the author said it was addressed. Separately, a reported unknown-v2 witness with 3,990,000 empty elements caused a roughly 91-MiB ToVectors copy during verification even though no script executed.

These observations explain why linear traversal, cheap policy checks and the point at which a mutable execution stack is materialized matter alongside compact retained storage. They also supply historical context for the bulk kernel accessor: the earlier proposal explicitly recognized that random access would become O(n). These are historical motivations and measurements, not a finding about this PR.

Source 1 · Source 2 · Source 3 · Source 4

Ralph's inferences

The existing generic decoding contract is canonical CompactSize at both nesting levels: the stack count and every element length. Nonminimal encodings fail, and default range checking rejects values above MAX_SIZE = 0x02000000. This is a count-or-length bound, not an aggregate 32-MiB witness limit and not the block-weight limit. Vector decoding also grows allocations incrementally rather than trusting an advertised count immediately.

The head still decodes through vector<vector<unsigned char>>, preserving those boundaries before packing. Its accessors disable only the MAX_SIZE range check on internally generated serialization; canonical decoding is still performed. Construction from vectors can exceed the wire decoder's per-count or per-element bound, subject to the new allocation representation fitting within uint32_t maximum minus four header bytes.

Consensus execution limits cannot be applied indiscriminately to every decoded witness. The base accepts otherwise-unknown witness version/program combinations for future soft-fork compatibility unless a discouragement flag applies; unknown Taproot leaf versions likewise have a separate success path. For executed Tapscript, the validation budget is derived from the serialized witness size plus an offset.

Huge stacks can therefore be meaningful transport objects without being execution stacks subject to current script limits. Conversion to mutable vectors serves execution ownership rather than defining validity by itself. Serialization sizes remain relevant to both consensus resource accounting and hashes even when the in-memory representation changes.

Policy ordering reflects both scope and cost: empty witnesses are skipped because they cannot be bloated, while missing-witness invalidity is left to validation. At the head, P2WSH item count is checked before looking up the last element, and the remaining items are traversed directly. Taproot policy distinguishes annex, control block, script and argument items rather than imposing one uniform item rule.

With O(n) back() and indexed access, checking a cheap count before scanning an oversized stack avoids work unrelated to deciding standardness. Direct traversal also preserves linear behavior. This explains the ordering change without treating policy limits as universal serialization or consensus constraints.

Kernel borrowed pointers follow an ownership chain, not the lifetime of an output array or a local view handle. The API says const pointers are non-owning views, copying acquires ownership, and views must not outlive the original object. A witness obtained from an input depends on that input's lifetime; a separately copied witness has its own destroy operation.

The new item-pointer arrays describe bytes owned by the underlying witness, not newly allocated item objects. Retaining those pointers requires retaining the actual owner behind a borrowed witness; retaining the pointer arrays alone does not extend that lifetime. The head CScriptWitness exposes immutable spans into its allocation, while copying creates separate storage. Empty items remain items with zero length, rather than evidence of an absent witness.