1 minor finding · 4 suggestions
Findings
[minor] · Kernel witness enumeration becomes quadratic
Enumerating WitnessStackApi::Items() now performs quadratic lookup work; no current in-tree caller enumerating large witnesses was found, and downstream impact is unconfirmed.
Location: src/kernel/bitcoinkernel.cpp:875 (head).
Details and suggested fix
btck_witness_stack_get_item_at now calls CScriptWitness::operator[], which starts at begin() and skips every preceding element. The unchanged Items() iterator retains only a numeric index, so reading all elements performs roughly n(n-1)/2 prefix skips instead of the base implementation's linear number of vector lookups. btck_transaction_create only deserializes, so execution-stack limits do not prevent inspection of 100,000 empty elements, about 100 KB serialized, requiring roughly five billion skips. Provide a one-pass visitor or cursor through the C API and use it for wrapper enumeration, rather than forcing traversal through repeated indexed lookups.
Optional improvements
[suggestion] · VerifyWitnessProgram expands witnesses before selecting a spend path
Unconditional ToVectors() adds transient reconstruction on key-path and early-return validation paths that previously used a view; the runtime cost has not been measured.
Location: src/script/interpreter.cpp:1929 (head).
Details and suggested fix
An annex-free Taproot key-path spend now allocates an outer vector and a signature buffer even though verification only reads the signature. Wrong-count P2WPKH witnesses and other early-return paths also reconstruct every element before their checks. Base copied arguments only when entering ExecuteWitnessScript; moving the reconstructed stack into that function does not eliminate the new work elsewhere.
Inspect structural elements through spans and build owned argument vectors only immediately before ExecuteWitnessScript. Preserve the existing commitment checks, annex hashing with its CompactSize length prefix, the budget based on GetSerializeSize(witness), and OP_SUCCESSx processing before execution-stack limits.
[suggestion] · Witness memory tests do not enforce compact storage
The only witness-memory assertion is a lower bound, so a correctly accounted return to per-element vectors would pass despite undoing the PR's retained-memory improvement.
Location: src/test/fuzz/script_witness.cpp:91 (head).
Details and suggested fix
The current single-allocation accounting is correct, but neither new test constrains its upper bound. Add a deterministic witness with, for example, 10,000 empty or one-byte elements and assert a conservative upper bound relative to serialized size using memusage::MallocUsage conventions. Also check zero usage for empty and reset witnesses, and that RecursiveDynamicUsage of a transaction input includes the witness contribution. Keep traversal linear rather than using the existing all-indices loop. These assertions would protect reported accounting, not independently measure allocator residency.
[suggestion] · IsWitnessStandard allocates a span vector it only scans
The Taproot policy branch builds a span vector before rejecting an annex or empty control block; forward traversal can preserve policy without that temporary allocation.
Location: src/policy/policy.cpp:328 (head).
Details and suggested fix
ToSpans() allocates one span slot per witness element, whereas base used a non-owning view. Read the top structural elements a fixed number of times and scan the argument prefix with the witness iterator instead. Even though top-element lookups are linear, a fixed number of them plus one prefix scan remains linear and needs no auxiliary vector. Preserve the >= 2 annex guard, exclude the script and control block from argument checks, and apply the 80-byte limit only to 0xc0 leaves. The P2WSH branch can use the same approach, though its benefit is smaller because it checks MAX_STANDARD_P2WSH_STACK_ITEMS before allocating.
[suggestion] · Witness count tests miss the five-byte CompactSize boundary
The representation test never constructs a witness with a five-byte outer CompactSize count, leaving witness-specific count parsing and element positioning untested at that boundary.
Location: src/test/script_tests.cpp:1741 (head).
Details and suggested fix
COUNTS stops at 254; the 65535 and 65536 entries in SIZES only vary element lengths. Although the shared ReadCompactSize helper already has boundary coverage, size() and begin() consume the outer prefix separately. Add witnesses with 65,535 and 65,536 empty or one-byte elements, checking count, forward-iteration distance, conversions, front/back, and serialization round-trips. Keep these separate from the all-indices witness[i] loop, which would make the large cases quadratic.
Background
Ralph's summary of historical context for the behaviour affected by this change. The historical record reviewed here is incomplete.
Documented decisions
CompactSize canonicalization was introduced to eliminate discrepancies between received bytes and deserialize–reserialize results. The 2013 proposal explicitly treated such mismatches as a potential exploit surface and specified rejecting noncanonical encodings with an exception, rather than silently accepting and normalizing them.
At the pinned base, witness element counts and element lengths inherit this rule from nested-vector deserialization. The head still decodes through those vectors before constructing the compact representation. Thus retaining serialized witnesses does not imply retaining arbitrary received encodings: shortest-form CompactSize decoding remains the compatibility boundary. This also supplies the historical premise behind comparing canonical serialized witnesses for equality.
BIP342 deliberately places OP_SUCCESSx recognition ahead of script execution rules, including initial-stack limits. Its stated purpose is clean soft-fork extensibility without entanglement in existing failure cases, such as oversized initial stacks, excessive signature operations, or incomplete conditionals. The script commitment prevents a third party from injecting this unconditional-success mechanism into someone else's spend.
Both pinned versions scan a committed Tapscript for OP_SUCCESSx before checking the 1,000-element initial-stack limit and the 520-byte execution-stack element limit. Reconstructing vectors or changing witness accessors must not be interpreted as permission to apply those execution limits earlier during witness deserialization or preprocessing. Policy discouragement of OP_SUCCESSx is separate from its consensus behavior.
Tapscript's signature-operation accounting was designed as a simpler limit that fixes complicated interactions with transaction weight, rather than merely retaining the older signature-opcode accounting unchanged.
The pinned implementation initializes the Tapscript budget from the complete serialized input witness plus 50, not from the execution stack remaining after preprocessing. Consequently, the witness serialization used for this calculation includes its count prefix, element-length prefixes, script, control block, and any annex. The representation change affects the mechanism for obtaining that size, not which data funds the budget.
Prior orphanage work identified a distinction between transaction weight and retained deserialized memory: many tiny witness elements can incur an outer-vector slot and a separate allocation for very little weight. That proposal chose serialized retention and reconstruction on retrieval to make existing weight-based accounting bound stored transaction bytes, while preserving admission and orphan-resolution behavior.
The historical proposal illustrated approximately 11.1 MB of retained memory for a roughly 398,247-WU transaction containing 199,000 one-byte witness elements. It also explained that witness standardness cannot be checked while inputs are missing. This is directly relevant to compact CScriptWitness storage: limiting retained representation overhead addresses a different resource exposure from imposing new witness-validity or admission restrictions.
Ralph's inferences
The compatibility requirement has separate transport-decoding, consensus, and policy layers. A witness decoder cannot substitute current execution-stack limits for the existing nested-vector decoding contract.
In the pinned decoder, the outer element count and each element length independently use canonical ReadCompactSize with MAX_SIZE = 0x02000000; this is not an aggregate 32 MiB witness limit. Nonminimal encodings and excessive declared sizes throw std::ios_base::failure, and truncated prefixes or payloads fail through the stream. A witness decoder consumes its own elements rather than requiring the enclosing stream to end. Separately, the head's four-byte internal allocation header limits representable serialized size to uint32_t; that is not the same rule as MAX_SIZE, block weight, or the 520-byte script-element limit. The historical rationale supports preserving the decoding boundary, but does not establish that exact exception wording or the state of a partially modified destination was a protocol requirement.
Taproot preprocessing must identify structural witness elements before applying the rules of the selected script language. Applying Tapscript rules to all serialized witness elements would erase distinctions needed for upgradeability.
The pinned ordering recognizes an annex only when at least two elements exist and the nonempty final element starts with 0x50; it removes and hashes the annex before distinguishing key-path from script-path spending. Script-path processing then removes the control block and script, checks control-block structure, and verifies the Taproot commitment before dispatching on leaf version. Unknown leaf versions succeed under consensus after those commitment checks, unless a discouragement policy flag is requested; they do not pass through current Tapscript stack checks. For version 0xc0, only the remaining argument elements become the execution stack. BIP342's explicitly scoped applicability and upgrade mechanism support this separation, although the complete BIP341 explanation was not retrieved.
Compact retained storage and expanded mutable validation state serve different purposes. Historical serialized-retention work supports exchanging reconstruction work for lower long-lived memory exposure, but does not imply that validation has no transient allocation cost.
The base already copies witness arguments into owned vectors for script execution. At the head, VerifyWitnessProgram reconstructs vectors with ToVectors(), removes elements with structural roles, and moves the remainder into ExecuteWitnessScript. Deserialization also still passes through a temporary nested vector before compact storage is built. Thus the retained transaction representation becomes compact while vector allocations remain transient during decoding and validation. The prior orphanage proposal provides a closely related resource-accounting precedent, not evidence for a particular peak-memory or performance result in this implementation.