3 suggestions
Optional improvements
[suggestion] · Non-executing witness paths recreate per-element vector overhead
Eager ToVectors() adds an avoidable, weight-bounded transient allocation on block-validation paths that do not need an execution stack.
Location: src/script/interpreter.cpp:1929 (head).
Details and suggested fix
ToVectors() reserves one vector object per element before dispatch, although unknown-version, P2A and disabled-Taproot paths never inspect the result. A consensus-valid block spending an unknown-version output with about 3.9 million empty elements therefore recreates roughly 90 MiB of vector headers before discarding them, assuming 24-byte vectors. This is a static estimate, not a measurement. Base used only a span on these paths. Move these dispatch decisions, including their existing flag checks, ahead of materialization. This leaves Taproot commitment checks and tapscript OP_SUCCESSx ordering untouched. The buffer is freed on return; base retained expanded witnesses, and head still temporarily constructs them during deserialization, so this is not evidence of a worse overall memory bound.
[suggestion] · Kernel witness traversal hides quadratic element scans
Full traversal of WitnessStackApi::Items() now performs quadratic element scans without an API warning; no external caller traversing large witnesses was identified.
Location: src/kernel/bitcoinkernel.cpp:875 (head).
Details and suggested fix
btck_witness_stack_get_item_at now locates each item by scanning from CScriptWitness::begin(). The wrapper's iterator calls GetItem(index) on every dereference, so visiting n items scans roughly n(n-1)/2 preceding elements, in addition to copying the returned bytes. With millions of tiny elements, this becomes trillions of CompactSize reads. Neither bitcoinkernel.h nor WitnessStackApi::Items() documents the cost. Add linear-in-index lookup and quadratic full-traversal warnings to those public interfaces. The in-tree traversal only covers a four-item witness.
[suggestion] · Witness memory tests miss overcharging and input integration
The new fuzz assertions accept per-element overcharging and do not exercise RecursiveDynamicUsage(CTxIn), leaving the compact mempool-accounting change without a focused regression check.
Location: src/test/fuzz/script_witness.cpp:98 (head).
Details and suggested fix
DynamicMemoryUsage() >= ser_stack.size() still passes if the compact witness is charged for a vector header per element. Removing the witness contribution from RecursiveDynamicUsage(CTxIn) also leaves this target untouched, although that contribution feeds CTxMemPoolEntry::nUsageSize and the mempool limit. Add a deterministic case with many empty and one-byte elements that checks the charge equals memusage::MallocUsage(4 + GetSerializeSize(witness)). Then check that setting and clearing only the input's witness adds and removes exactly that charge. MallocUsage is a deterministic estimator, so the assertion need not depend on the host allocator.
Background
Ralph's summary of historical context for the behaviour affected by this change. The historical record reviewed here is incomplete.
Documented decisions
SegWit's serialization was designed to preserve interoperability with legacy nodes and existing transaction interfaces. Witnesses are counted stacks of length-prefixed byte arrays, not Script, and transactions with entirely empty witnesses must use legacy serialization.
The representation change sits behind an established wire format. Empty-stack detection controls whether marker/flag and witness records are serialized and consequently whether wtxid equals txid. A stack containing one empty byte array is not the zero-element stack. BIP144 also explains that reusing transaction messages avoided duplicating messages and RPC interfaces or relying on ambiguous format guessing.
Tapscript's OP_SUCCESS precedence deliberately preserves a broad soft-fork upgrade surface rather than merely providing an early-exit optimization.
BIP342 requires BIP141/BIP341 validity first, then opcode decoding and OP_SUCCESS recognition before initial-stack resource checks or execution. Its rationale explicitly includes oversized initial stacks, excessive signature operations, and malformed conditionals as cases that must not obstruct this upgrade mechanism. It also explains why unconditional success is safe from third-party injection: the script is committed to by the output. Thus the check ordering in ExecuteWitnessScript has compatibility meaning independent of witness storage layout.
The predecessor proposal treated deserialization and script validation as different resource-abuse surfaces: deserialization is cheaply triggerable by peers, whereas block script validation follows proof-of-work checks.
In the predecessor discussion, the defense of prioritizing deserialization costs explicitly invoked attacker cost and frequency after proof-of-work validation. Its description separately measured retained object memory and peak deserialization memory. This explains why persistent storage reduction, parsing allocations, and execution-stack allocation were discussed separately; it is not a claim that proof-of-work protects every validation entry point or eliminates CPU and memory concerns.
Mempool memory limiting was justified as a way for node operators to fit resource consumption to their hardware, while compact transaction storage was expected to increase effective capacity within that memory bound.
The historical mempool-limiting discussion explicitly connects configurable memory consumption with the ability to run a full node. The predecessor witness proposal separately identifies increased capacity of memory-bounded structures as a benefit of smaller transaction objects. The pinned mempool accounting sums allocation estimates and cached transaction usage, so retained allocation size—not only serialized weight—is relevant to the capacity effect.
The predecessor discussion explicitly balanced compact storage against witness-access overhead by favoring direct iteration where indexed traversal or temporary view containers would add avoidable work.
A predecessor comment distinguished three costs: allocating a container of views, repeatedly indexing serialized elements, and reading only the metadata needed for policy checks. The author reported addressing that concern. At the pinned head, CScriptWitness documents forward iteration and O(index) lookup, so access patterns are part of the resource tradeoff rather than interchangeable container syntax. The predecessor's O(1) back() observation concerned its own representation and does not apply to this head's documented O(n) back().
Ralph's inferences
Deserialization limits, execution limits, and relay limits protect different boundaries and cannot be treated as one witness-size rule.
The base vector reader uses range-checked CompactSize decoding and staged allocation rather than trusting a declared count. Its comment explicitly identifies allocation-based DoS prevention. The head retains vector-based deserialization semantics, while execution separately applies stack and element limits and policy defines tighter standardness constants. This supports interpreting the parsing contract as inherited compatibility behavior, not as permission to apply execution or relay limits to every serialized witness.
Canonical CompactSize encoding makes the serialized witness a unique representation of its stack, while zero-element semantics determine transaction-level witness presence.
The base reader rejects nonminimal CompactSize encodings and the writer emits the minimal form. The head relies on this property for bytewise witness equality. Separately, transaction decoding rejects an extended witness record when every input stack is empty. These premises explain why exact round-tripping, equality, and the distinction between no elements and an empty element matter beyond memory layout.
The base implementation separates immutable witness evidence from mutable execution state; the exact materialization point is an implementation choice constrained by consensus interpretation and ordering.
At the base, a span excludes the P2WSH script or Taproot annex, control block, and leaf script without modifying the witness; ExecuteWitnessScript then copies the execution arguments. Taproot annex removal precedes key/script-path selection, and commitment verification precedes tapscript execution. At the head, ToVectors materializes the whole witness before those branches and the remaining vectors are moved into execution. This changes allocation lifetime without changing why those elements have distinct roles. The tapscript budget continues to use the original witness's serialized size, not its retained heap footprint.
Unresolved disagreements
The inspected predecessor discussion did not resolve how strongly transient validation allocations should constrain the compact-storage change.
One participant argued that materializing witnesses on paths that never execute a script forfeited validation-time memory savings and supplied measurements. Another response prioritized peer-triggerable deserialization costs, invoking proof-of-work gating and lower combined processing cost. These are competing priorities about allocation lifetime and attacker leverage, not evidence of a defect or a verdict on the current PR. The response was truncated, and the complete subsequent resolution was not retrieved.