WIP: Witness stacks in serialized form (optimization follow-ups)

bitcoin/bitcoin: PR #36918

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

Earlier concerns neither republished nor resolved: 1 suggestion. See the Run archive for their assessments.

Findings

Link

[major] · Kernel Items() traversal becomes quadratic

Enumerating a large untrusted witness through kernel Items() now takes quadratic work instead of linear work; no external consumer performing this traversal was identified.

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

Details and suggested fix

btck_witness_stack_get_item_at now delegates to CScriptWitness::operator[], which restarts at begin() and advances index times except for the final item. WitnessStackApi::Items() still uses the index-based Range, so every dereference repeats that scan. With roughly two million one-byte items, this implies about two trillion CompactSize decodes. Such witnesses fit in consensus-valid unknown-version spends, and btck_transaction_create also accepts their raw serialization without script validation, so that route requires no mined block. The base getter indexed a vector directly. This can monopolize a kernel consumer's traversal, rather than bitcoind's validation path.

Add a cursor-based linear traversal at the C boundary and use it for Items(), with a many-item traversal benchmark. The witness API currently offers no alternative per-item traversal; re-parsing btck_transaction_to_bytes output is a consumer workaround.


Optional improvements

Link

[suggestion] · P2WSH and Taproot exits still expand unused witness elements

Although base already allocated these elements during deserialization, the serialized representation can avoid rebuilding whole witnesses before P2WSH hash failures or Taproot control, commitment and unknown-leaf exits.

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

Details and suggested fix

ToVectors() reserves one entry per item and copies every element before the P2WSH emptiness/hash checks and the Taproot annex, control-size, commitment and leaf-version checks. Unknown Taproot leaves then return success or SCRIPT_ERR_DISCOURAGE_UPGRADABLE_TAPROOT_VERSION without using an execution stack. Large P2WSH witnesses are policy-limited in the mempool, so their main optimization opportunity is block processing.

Check P2WSH emptiness and the hash of witness.back() before conversion. For Taproot, inspect the annex, control block and script as spans and defer full-stack expansion until the 0xc0 execution branch, changing VerifyTaprootCommitment to accept a control-block span. Preserve CompactSize-prefixed annex hashing and the existing emptiness, control-size, commitment and leaf-version order. Leave OP_SUCCESSx and execution-limit processing in ExecuteWitnessScript unchanged.


Link

[suggestion] · The series introduces a witness copy that it later removes

Commit 74ed0e6 adds unconditional witness expansion that d2483cf later makes lazy, requiring review of an avoidable intermediate performance regression rather than a head defect.

Location: src/script/interpreter.cpp:1929 at 74ed0e6b5324 (commit) (commit).

Details and suggested fix

74ed0e6b532425a323b3ddb582ea0e7bca2ba77a replaces the span with an unconditional ToVectors() call while the witness still stores vectors. Unknown witness versions, wrong-length v0 programs, pay-to-anchor and Taproot with SCRIPT_VERIFY_TAPROOT unset therefore incur a new deep copy. Fold the branch-local placement and P2WPKH count guard from d2483cfce4d764cca9b3251ce36336e23d966ed4 into that conversion commit, then drop or shrink the later commit. size() already exists there, so this does not depend on the serialized representation. Although the current boundary separates #36895 from the separately benchmarked follow-ups, the fold lets the conversion be reviewed without introducing work that a later patch removes, and avoids retaining that cost if #36895 lands alone. The final tree remains unchanged.


Link

[suggestion] · Witness tests omit successful multi-chunk element reads

None of the added unit tests successfully deserialize an element larger than MAX_VECTOR_ALLOCATE, leaving the new loop's second iteration and following-element boundary unchecked.

Location: src/script/script.h:742 (head).

Details and suggested fix

The representation cases stop at 65,536 bytes, while MAX_VECTOR_ALLOCATE is 5,000,000 and ReadCompactSize accepts element lengths up to MAX_SIZE (32 MiB). script_witness_large_element constructs from vectors and only tests rejection of a MAX_SIZE + 1 prefix, so it does not read a payload. Add a deterministic round trip containing a non-uniform MAX_VECTOR_ALLOCATE + 1-byte element followed by another item and trailing sentinel bytes. Compare with vector-of-vectors deserialization, including back() and remaining bytes, and require truncation before completing the second chunk to throw. This exercises append offsets and len -= chunk without depending on large fuzz inputs.


Link

[suggestion] · Witness memory-usage assertion misses header undercounting

The fuzz target's non-empty witness check still passes if the header charge is omitted or reduced to four bytes, although the current production formula correctly includes eight bytes.

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

Details and suggested fix

MallocUsage(serialized_size) already rounds up above serialized_size, so the existing lower bound does not check the header term used by RecursiveDynamicUsage(CTxIn). Assert exact equality with memusage::MallocUsage(8 + serialized_size) for non-empty witnesses. Include a single seven-byte element, whose serialization is nine bytes: on 64-bit builds the correct charge is 48 bytes, versus 32 for a four-byte or missing header. Exercise construction, deserialization and copying, plus zero accounting for reset and moved-from witnesses.


Link

[suggestion] · P2WPKH benchmark overstates the public-key item size

The purported typical P2WPKH block benchmark fits about 9% fewer transactions and witnesses because both witness items are 72 bytes instead of using a 33-byte compressed-public-key item.

Location: src/bench/block_deserialize.cpp:117 (head).

Details and suggested fix

WriteTx writes every witness item with shape.size_wit_item bytes, and DeserializeBlockP2WPKH selects two 72-byte items per input. For its two-input, two-output transactions, that gives 912 WU rather than 834 WU with a 72-byte signature item and a 33-byte public-key item. Approximately 4,795 transactions would then fit instead of 4,385. Since this PR changes per-input and per-witness allocation and copying costs, the current fixture understates those costs relative to the workload it describes. Allow per-item witness sizes such as {72, 33} and recompute num_txn against the weight limit.


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

Canonical CompactSize rejection was introduced to eliminate deserialize/re-serialize byte mismatches that could become exploit opportunities, with explicit attention to compatibility with older nodes.

The 2013 proposal explained that older implementations normalized encodings before hashing or relaying transactions and blocks. It also distinguished rejecting malformed messages from penalizing peers, because stronger penalties could partition older nodes. This history matters when witness bytes become their persistent representation: accepting a previously rejected encoding is not merely a storage optimization, and byte equality relies on a unique serialization.

Source 1 · Source 2 · Source 3

Witness versions reserved for future extensions deliberately leave the witness stack uninterpreted and impose no version-specific stack-size restriction; invalid version-0 program lengths instead fail.

The historical BIP141 clarification explains why ordinary execution-stack limits cannot be applied indiscriminately before dispatching on witness version. At the pinned head, unknown combinations can succeed or receive the discourage-upgrade policy error without expansion, whereas a version-0 program of an unsupported length returns the wrong-length error. Skipping expansion does not eliminate serialization checks or block-level resource limits.

Source 1 · Source 2 · Source 3

BIP342 makes validation ordering part of the upgrade mechanism: BIP141/BIP341 failures precede tapscript processing, but an encountered OP_SUCCESSx precedes execution and initial-stack limits.

The specification expressly includes stacks exceeding 1,000 elements among the cases OP_SUCCESSx must permit. Its rationale is to allow future soft forks to define powerful new behavior without inheriting today's execution restrictions. This is safe from third-party opcode injection because the script is committed by the output. Consequently, avoiding witness expansion cannot be justified by applying current stack limits before the commitment and OP_SUCCESSx stages.

Source 1

Mempool memory accounting was introduced to measure actual data-structure resource usage, with resource limiting identified as an intended use rather than treating serialized transaction size as sufficient.

The original accounting proposal explicitly anticipated resource limits. The pinned accounting includes outer witness-vector storage and each element's allocation, while the allocator estimator charges capacity and allocation overhead. This supports understanding -maxmempool as a retained-memory budget, distinct from transaction weight or virtual size.

Source 1

The earlier serialized-witness proposal explicitly targeted peer-controlled deserialization amplification, while also seeking greater useful capacity in memory-bounded transaction stores.

Proposal #36521 identified the per-element vector object and allocation as the reason tiny witness elements could produce large memory use and slow deserialization. It separately discussed peak deserialization memory and retained block memory, and stated that common-case savings increase effective mempool capacity. This establishes both objectives: reduce adversarial expansion and let genuine allocation savings improve retention, rather than maintaining an artificial charge for the old representation.

Source 1

Ralph's inferences

MAX_SIZE and canonicality are separate deserialization invariants: the former bounds each size or element-count declaration, while the latter requires its shortest encoding.

The base reader rejects nonminimal encodings independently of its default 0x02000000 range bound. The head witness reader uses that checked reader for both the element count and every element length. This is not an aggregate witness-memory budget, and it is distinct from execution limits. The exact historical reason for choosing 32 MiB was not established.

Chunked vector allocation prevents a length declaration alone from immediately forcing its full claimed allocation; it does not bound total nested-container amplification.

The base formatter explicitly describes its batches as DoS prevention and scales the outer batch by element-object size. Reading must progress before subsequent batches are requested. Nevertheless, many empty or tiny elements can still carry substantial outer-vector and allocator overhead. The head's direct serialized construction retains checked lengths and chunked element reads while addressing that separate representation cost.

Skipping expansion is constrained both by consensus acceptance boundaries and by the existing implementation's diagnostic ordering; these are not identical requirements.

The pinned paths check P2WPKH's two-item requirement before execution; P2WSH emptiness and script-hash mismatch before execution-stack checks; and Taproot control-block shape and commitment before leaf-version handling. Taproot verification disabled by flags, pay-to-anchor, and unknown witness combinations do not require an execution stack. BIP342 explicitly mandates ordering that can change success versus failure, whereas the inspected code—not a retrieved historical specification—establishes the precise ScriptError precedence for other multiply-invalid inputs.

Source 1

Consensus validation cost and local memory retention intentionally use different metrics, so cheaper witness storage can increase retention without changing the tapscript validation budget.

Both base and head derive the tapscript validation budget from serialized witness size plus VALIDATION_WEIGHT_OFFSET. Mempool trimming instead compares DynamicMemoryUsage with its memory limit and removes low-feerate chunks, raising the admission floor to resist immediate refill. The allocation estimator is a platform-based approximation, not an exact RSS measurement. Thus retained allocation savings, transient expansion costs, and witness-weight-based validation costs are separate quantities.

Source 1