Provider refusals
write_verifier: Provider declined the request because of a cybersecurity restriction. Experiments remain incomplete; static verification can continue.
1 major finding · 5 suggestions
Findings
[major] · Kernel witness enumeration becomes quadratic
Enumerating a large witness through Items() or the kernel C getter now takes quadratic work; no in-tree production caller was found, so production 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 scans from begin() for every index except the last. The unchanged wrapper implements both iterator dereference and Items()[i] through that getter, so even a range-based loop repeatedly scans the prefix. Base indexed a std::vector, making the same traversal linear. The witness API exposes no sequential alternative.
btck_transaction_create parses caller-supplied bytes without consensus validation. Unknown witness programs also permit millions of tiny elements in a consensus-valid block. Enumerating two million elements therefore requires roughly two trillion prefix decodes; the cached last-element offset saves only the final scan. Expose a sequential callback backed by CScriptWitness::Iterator and use it for Items() so full traversal remains linear. This affects consumers of the experimental, opt-in kernel library, not bitcoind's validation.
Optional improvements
[suggestion] · P2WSH hash mismatches still materialize the entire witness
This is an optimization opportunity, not a regression: checking witness.empty() and hashing witness.back() before ToVectors() would avoid per-element allocations when the P2WSH script hash mismatches.
Location: src/script/interpreter.cpp:1942 (head).
Details and suggested fix
The P2WSH branch calls witness.ToVectors() before checking for an empty witness or hashing the script. A witness containing millions of small elements therefore recreates all their vectors even when the final script does not match the program. Check witness.empty() first, then hash the span returned by the constant-time witness.back(). Return the existing errors on failure and convert only after the hash matches, dropping the final element before execution. This preserves the error order. On the network block-validation path, reaching this expensive rejection already requires valid proof of work.
[suggestion] · ToVectors() is made eager and then lazy in separate commits
Folding the later lazy-conversion change into the initial ToVectors() refactor would avoid an intermediate whole-witness copy and let reviewers assess the rewrite once; the final tree already behaves correctly.
Location: src/script/interpreter.cpp:1929 at 8ddce725a631 (commit) (commit).
Details and suggested fix
In 8ddce725a6317e108fe25154c9c15183e1792774 (script: build the witness execution stack with ToVectors()), VerifyWitnessProgram replaces a zero-copy span with an unconditional ToVectors() before dispatch. At that point, ToVectors() returns the stored vector by value. Programs that ignore the witness therefore gain a deep copy that the earlier code avoided.
Fold 06a20ee01126a0631b35dc2a2df08fef82a20785 (script: only convert the witness to vectors when it is used) into that refactor. Its branch-local conversions need no later representation changes: size() and ToVectors() already exist, and 9e0e0bee78edce8f17ad25b600b768f4879741ca has already made ExecuteWitnessScript take its stack by value. This leaves the final tree unchanged while removing the intermediate copy and the second review of the same rewrite. The separate lazy-conversion benchmark comparison can remain in the combined commit message.
[suggestion] · Assume does not enforce fatal witness preconditions
Although indexing was already unchecked at base, the new Assume checks do not enforce preconditions needed for safe witness decoding in production; no violating caller was found.
Location: src/script/script.cpp:335 (head).
Details and suggested fix
The index check guards iterator advancement followed by DecodeCompactSize. The offset check guards the stored position later consumed by back(). An invalid index or an offset at or beyond the serialization end makes those reads unsafe, but Assume does not stop execution in ordinary production builds. doc/developer-notes.md reserves Assume for violations that are safe to continue from. Use Assert(index < count) and Assert(last_offset < size) to make these existing checks fail fast in production while preserving valid-call behavior.
[suggestion] · Witness unit tests miss multi-chunk element deserialization
The new deterministic witness tests never deserialize an element large enough to exercise the second iteration of CScriptWitness::Unserialize's chunk loop.
Location: src/test/script_tests.cpp:1921 (head).
Details and suggested fix
script_witness_representation limits element sizes to 65,536 bytes. script_witness_large_element constructs its large witness from vectors and tests deserialization only with a length prefix rejected before reading the body. The differential fuzz target needs an input larger than 5 MB to exercise multiple chunks. Add a deterministic case with a MAX_VECTOR_ALLOCATE + 1-byte element whose data differs across the boundary, followed by a small second element and unread trailing bytes. Compare the decoded bytes, back(), and remaining input against vector-of-vectors deserialization. A truncated second chunk would also cover the failure path.
[suggestion] · The P2WPKH benchmark oversizes the public-key item
Using two 72-byte items instead of a signature and 33-byte compressed public key makes the typical P2WPKH benchmark fit about 9% fewer transactions and witness elements per block.
Location: src/bench/block_deserialize.cpp:117 (head).
Details and suggested fix
The single size_wit_item makes WriteTx emit both witness items at 72 bytes. For the intended two-input, two-output shape, this gives 912 WU per transaction rather than 834 WU with item sizes {72, 33}. Correcting the sizes allows 4,795 transactions instead of 4,385 within the existing weight limit, changing the transaction, input, and witness-allocation counts measured per block. Allow per-item sizes, use {72, 33}, and recompute num_txn. The synthetic contents need not be valid; only their lengths need to match the workload.
Background
Ralph's summary of historical context for the behaviour affected by this change. The historical record reviewed here is incomplete.
Documented decisions
Permissive handling of unknown witness programs is an intentional soft-fork extension mechanism. BIP141 reserved versions 1–16 without further interpretation or witness-stack size restrictions; subsequent upgrades can constrain subsets of those spends.
This explains why a witness container cannot impose ordinary execution-stack limits on every parsed witness. The pinned interpreter still accepts unassigned version/size/P2SH combinations for future-soft-fork compatibility and bypasses Taproot interpretation when its verification flag is absent. Conversely, version-0 programs of the wrong length fail rather than acquiring unknown-version semantics. Lazy conversion changes when vectors are materialized, not these distinct acceptance rules.
Witness serialization is not itself Script. BIP141 explicitly separates a witness field's item count and length-prefixed byte strings from script semantics, partly so future upgrades can reevaluate constraints such as the 520-byte push limit.
The compact representation stores those serialized byte strings, while execution limits belong to the applicable witness-program rules. This distinction is important for large ignored witnesses and for elements serving as scripts or proofs rather than ordinary execution-stack arguments. It does not eliminate framing and deserialization checks.
BIP342 deliberately orders validation so that BIP141/341 failures come first, followed by script decoding and OP_SUCCESSx recognition, before ordinary execution rules. OP_SUCCESSx precedes stack limits and execution checks to provide a clean soft-fork upgrade mechanism without ambiguous edge cases.
An oversized initial stack cannot simply be rejected during generic witness decoding: a committed tapscript containing OP_SUCCESSx may succeed despite it. But OP_SUCCESSx cannot bypass the enclosing Taproot validity checks. BIP342 explains the adversarial distinction: unlike early OP_RETURN behavior, a third party cannot inject OP_SUCCESSx because it is part of the output-committed script. The base interpreter reflects this by checking the Taproot commitment before entering execution, then scanning for OP_SUCCESSx before checking initial-stack limits.
Rejecting non-canonical CompactSize encodings was introduced to avoid subtle deserialize/reserialize byte mismatches that could become exploit opportunities. The proposal intentionally made malformed encodings throw instead of silently normalizing them.
Preserving the witness's wire representation makes this historical boundary especially relevant. The head still uses ReadCompactSize for externally supplied counts and element lengths, retaining non-canonical and MAX_SIZE failures. The unchecked decoder is a separate internal accessor, not a replacement for network-facing validation. Canonical encoding also supports comparing serialized witnesses as a representation of stack equality.
Earlier witness-memory work explicitly identified many tiny elements as an adversarial amplification case: serialized weight can substantially understate a vector-of-vectors transaction's heap usage. The orphan-storage proposal chose serialized storage to bound memory without excluding previously admitted transaction shapes.
That proposal reports a standard-weight transaction with 199,000 one-byte witness elements using about 11.1 MB, because each element carries vector and allocation overhead. It also notes that witness standardness cannot be checked while inputs are missing. This history explains the incentive to reduce representation overhead rather than rely on relay policy as a universal memory bound. Its weight-based orphan accounting is distinct from the mempool's recursive heap accounting.
Ralph's inferences
Witness-element roles must be resolved before applying execution-stack rules: the P2WSH script, Taproot annex, control block, and leaf script are not ordinary initial-stack arguments.
Both pinned versions remove the P2WSH script and check its hash before execution. Taproot recognizes an annex only with at least two elements and a final nonempty element starting with ANNEX_TAG, removes it and records its hash, then distinguishes key-path from script-path spending. Script-path validation removes control and script elements, checks control size and the output commitment, and only then selects leaf-version execution. The storage redesign therefore needs to preserve element order and these roles, not merely the collection of bytes.
Staged allocation and CompactSize range checks address different resource risks from script limits or compact retained storage.
The base vector deserializer explicitly avoids allocating everything a stream claims to contain, advancing in roughly 5 MB batches for DoS prevention. The head's witness reader retains checked counts and lengths and reads element bodies in MAX_VECTOR_ALLOCATE chunks. Thus an attacker must supply data as parsing progresses; the batch size is not a maximum valid witness size or a complete bound on aggregate retained memory. The exact original numerical choice was not established.
Unchecked decoding relies on an internal construction invariant, not on trusting an unvalidated peer.
At the head, witness storage is private and constructed as a whole. Vector construction writes serialization through the normal writer; deserialization checks CompactSizes and reads the declared bodies before installing the allocation. Accessors then use DecodeCompactSize, whose contract explicitly omits canonicality, range, and bounds checks. The historical parser boundary remains separate from repeated traversal of an already constructed witness. This describes the intended trust boundary, not a proof of every caller's correctness.
Execution-resource accounting depends on serialized witness size, whereas mempool memory accounting depends on the in-memory representation; those quantities must remain conceptually separate.
Base and head initialize the tapscript validation budget from the complete serialized witness plus VALIDATION_WEIGHT_OFFSET, not from the remaining execution vectors after removing annex, script, and control elements. Separately, mempool entries cache RecursiveDynamicUsage: the base counts outer and inner witness vectors, while the head delegates to an allocator-aware charge for the compact allocation and header. Reduced retained heap usage can therefore increase mempool capacity under the same memory setting without changing transaction weight or tapscript's serialized-size-based budget.
Compact retained storage and lazy execution-stack materialization address different stages of the same amplification problem.
A compact witness avoids per-element retained allocations, but ToVectors recreates them when mutable execution data is needed. The head defers that conversion until program-specific rules use the witness, and checks P2WPKH's exact two-element requirement first. Ignored programs can consequently remain serialized. This follows from the historical permissive-program semantics and the documented tiny-element memory amplification; it does not imply that witnesses used by P2WSH or Taproot never require expanded transient storage.