Keep witness stacks in serialized form in CScriptWitness

bitcoin/bitcoin: PR #36895

3 suggestions

Optional improvements

Link

[suggestion] · Quadratic Items() traversal is undocumented in the kernel API

The bundled WitnessStackApi::Items() range now traverses witnesses in O(n²) without a public complexity warning; no current production caller exercising large-witness traversal was found.

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

Details and suggested fix

Items() calls GetItem(index) on every dereference. That reaches btck_witness_stack_get_item_at, whose stack[index] now starts at begin() and advances index times instead of indexing a vector. Both index loops and range-for traversal therefore perform O(n²) element-length decodes, even for empty elements. The public header documents the index precondition but neither promises a complexity bound nor warns about this cost, and the witness API supplies no bulk or serialized-stack accessor. At minimum, document O(index) lookup for the C accessor and GetItem(), and O(n²) traversal for Items(). A single-pass accessor would let the wrapper avoid the regression while retaining packed storage.


Link

[suggestion] · VerifyWitnessProgram materializes unused witness stacks

VerifyWitnessProgram now rebuilds per-element vectors even when no script runs, adding avoidable validation memory and work; this bounded temporary cost does not demonstrate a higher overall peak than base.

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

Details and suggested fix

ToVectors() reserves one vector object per witness element before witness-version dispatch. An otherwise valid unknown-version spend can put nearly four million empty elements in a block. When its script checks run, this code constructs and destroys all those objects before returning success without calling ExecuteWitnessScript. With 24-byte vector objects, the temporary array alone approaches 96 MB, inferred from the code rather than measured on this head. Base used a non-owning span on this path and copied only execution arguments inside ExecuteWitnessScript. The large block case remains bounded by block weight and requires proof of work. Inspect script, annex and control data through spans, and materialize only the leading arguments on branches that call ExecuteWitnessScript, preserving annex length-prefix hashing, error order and OP_SUCCESSx precedence.


Link

[suggestion] · Witness memory tests miss header and over-accounting regressions

Current witness accounting is correct, but its new tests would still pass if it omitted the header or overestimated usage, and they do not verify the CTxIn accounting integration.

Location: src/test/fuzz/script_witness.cpp:98 (head).

Details and suggested fix

For non-empty stacks, DynamicMemoryUsage() >= ser_stack.size() remains true if accounting drops the four-byte header, because MallocUsage() already rounds above the serialized size. It also accepts per-element overhead or inflated accounting. Keep this representation-independent fuzz check, but add unit assertions for zero usage on an empty stack and exactly memusage::MallocUsage(4 + GetSerializeSize(stack)) otherwise. Cover many empty elements and a serialized size that crosses a rounding boundary when the header is added. Also check that assigning the witness to an otherwise unchanged CTxIn increases RecursiveDynamicUsage() by that amount, covering the contribution cached by mempool entries.


Coverage details

Background

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

Documented decisions

Canonical CompactSize decoding was introduced to eliminate discrepancies between received bytes and reserialized objects that could create subtle exploit opportunities. The 2013 proposal argued that rejection was compatible because older nodes already erased noncanonical encodings when parsing and reserializing transactions for hashing and relay.

Keeping witness bytes as their representation makes this historical normalization boundary important: accepted stored bytes must remain the canonical serialization of the logical stack. The pinned implementation retains generic vector decoding before storing canonical bytes; serialized-byte equality therefore depends on an existing encoding invariant, rather than introducing a new notion of witness equality.

Source 1

Empty witness data must use legacy transaction serialization. A historical clarification explicitly identifies this as a BIP144 serialization rule, distinct from BIP141.

The base transaction parser rejects a witness-marked transaction when every input stack is empty, and its serializer selects the extended format only when HasWitness() is true. Replacing IsNull() with empty(), and representing an empty stack by a null allocation, must preserve that logical distinction because it controls transaction serialization and witness hashing.

Source 1

The packed-storage proposal targeted worst-case allocation amplification, not an optimal general transaction layout. Its author described reducing approximately 28 bytes/WU to 1.6 bytes/WU as a sufficient solution, while treating broader representation experimentation as secondary.

Tiny or empty witness elements incur vector-object overhead disproportionate to their serialized weight. The predecessor reported a valid-block case retaining 106.8 MiB and another case peaking at 182.2 MiB during deserialization. These explain the incentive to remove per-element retained allocations, but its optimized parsing results must not be transferred to this head, which still deserializes through vectors.

Source 1 · Source 2

The predecessor distinguished cheaply attacker-triggered deserialization from block script validation after proof-of-work checks. A response defended deferring validation-copy improvements because peers can trigger parsing before useful rejection checks, whereas exploiting block validation requires a miner-produced block and may sacrifice its reward.

This explains why reducing retained witness memory and optimizing whole-witness materialization were treated as separable work. It is a prioritization argument about attack cost, not a claim that validation allocations disappear, and it specifically concerns the block-validation path rather than every possible script-verification caller.

Source 1 · Source 2

Linear random access was an acknowledged compactness tradeoff. The predecessor explicitly said random access would become O(n), considered that acceptable for validation logic, and separately flagged the public libbitcoinkernel element accessor as potentially affected.

The pinned representation contains serialized elements without an offset index; indexed access advances an iterator from the beginning. Forward traversal retains linear total work without per-element indexing metadata. The inspected history supports accepting this tradeoff for a bounded memory fix, not a conclusion that indexed access was proven optimal.

Source 1 · Source 2

Mempool memory accounting was introduced to measure actual resource requirements separately from transaction size. The packed-witness predecessor explicitly connected smaller retained transactions to greater effective capacity in memory-bounded structures such as the mempool.

The head routes witness allocation usage through RecursiveDynamicUsage, while mempool entries cache memory usage separately from transaction weight. Thus the intended benefit is more transactions within a memory budget, not a change to their consensus weight or fee-sizing rules.

Source 1 · Source 2

Ralph's inferences

Preserving vector deserialization means preserving both length acceptance and resistance to allocations based only on claimed lengths. MAX_SIZE is 0x02000000 for CompactSize lengths/counts, while vector allocation proceeds in bounded batches rather than reserving the entire advertised count immediately.

These are distinct constraints, not an aggregate witness-size limit or the script execution stack limit. The head retains them by decoding a vector of vectors first. Its trusted internal accessors disable only the CompactSize range check, allowing construction from larger in-memory vectors; they do not make external decoding permissive. The separate 32-bit storage header also imposes a representation-size bound.

Empty-witness semantics concern element count, not whether all element payloads are empty: an empty stack serializes as 00, whereas one empty element serializes as 01 00 and is a present witness.

The base IsNull() tests outer-vector emptiness. The head's allocation-free empty representation must preserve that behavior across construction, copying, moving, clearing, and decoding. Collapsing empty elements into an empty stack would change HasWitness() and transaction encoding.

Materialization supplies the interpreter with mutable, owned stack elements while leaving transaction witnesses immutable. Materializing the entire witness before dispatch is an implementation simplification, not a protocol requirement.

Previously ExecuteWitnessScript copied the remaining span into a mutable vector. The head instead calls ToVectors() once, removes script/annex/control elements, and moves the remainder into execution. This avoids another argument-stack copy but recreates per-element allocations temporarily. Dispatch order also matters: unknown witness versions can succeed without executing the stack, and OP_SUCCESS processing precedes tapscript stack-limit enforcement, so parsing limits cannot simply be replaced by execution limits.

Kernel compatibility here separates observable API behavior from computational complexity: the indexed callback interface can keep returning the same item bytes while repeated indexed traversal becomes quadratic.

The public header specifies the index precondition and callback return behavior but contains no complexity promise. With the head's O(index) lookup, reading all n items by successive indexed calls costs O(n²), even though internal forward iteration costs O(n). The inspected evidence does not establish whether downstream callers rely on the former constant-time behavior.

Source 1

Unresolved disagreements

The predecessor contained competing positions on eager whole-witness materialization. One participant advocated copying only execution arguments on paths that actually execute a script, reporting that roughly four million empty elements otherwise recreated about 91 MiB during verification. The response prioritized cheaper pre-rejection parsing attacks and deferred that optimization.

The pinned head retains eager ToVectors() before witness-version dispatch. The historical record explains that scope choice and its temporary-memory cost, but does not establish that eager copying is intrinsically preferable or settle the acceptable validation-time versus implementation-scope tradeoff. The reported measurements concern predecessor revisions, not this head.

Source 1 · Source 2