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

bitcoin/bitcoin: PR #36918

1 major finding · 6 suggestions

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

Findings

Link

[major] · Kernel witness enumeration becomes quadratic

Walking a large witness through btck_witness_stack_get_item_at or Items() now takes O(n²), rather than O(n); no current in-tree production caller doing this was found.

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

Details and suggested fix

The getter now calls CScriptWitness::operator[], which starts at begin() and advances index times, except for the final element's fast path. The wrapper's Items() iterator stores only an index, so each dereference repeats that scan. Base indexed a std::vector in constant time. The C witness API offers no forward cursor or bulk visitor, so consumers cannot enumerate its items linearly through that interface.

btck_transaction_create only deserializes the supplied transaction, without imposing execution-stack limits. In the supplied test-only Release experiment, enumerating 80,000 empty elements through either interface took about 6.4 seconds at head, versus less than 0.5 milliseconds at base. Add a forward cursor backed by CScriptWitness::Iterator at the C boundary and implement Items() using it. Include a large tiny-element enumeration benchmark to protect the linear traversal.


Optional improvements

Link

[suggestion] · Commitment failures still materialize the full witness

P2WSH and Taproot copy every witness element before checking commitments, leaving avoidable allocations on rejection paths even though the reported head timings already improve on master.

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

Details and suggested fix

In the P2WSH branch, ToVectors() reserves an outer vector and copies every element before the script's SHA256 commitment is checked. Check witness.empty() first, then hash witness.back(), whose stored offset makes access O(1). Only materialize the stack and remove its script after the commitment matches. This preserves the existing empty-witness and mismatch error order and leaves execution limits unchanged.

Taproot similarly converts before checking the control-block size and commitment. Read the last two or three elements through spans from one forward pass, let the commitment helper accept a span, and defer argument copying until execution is needed. Preserve the length-prefixed annex hash and the validation budget based on the original witness.


Link

[suggestion] · The ownership conversion adds copies that a later commit removes

The head avoids these copies, but folding 9d160722 into 0f1253eb would keep conversion and its guards together and prevent temporary overhead for uninterpreted witnesses in #36895.

Location: src/script/interpreter.cpp:1929 at 0f1253eb5a64 (commit) (commit).

Details and suggested fix

Commit 0f1253eb5a64874fadc73ec6fdcf57247fc9ab8f replaces the witness span with an unconditional ToVectors() call before dispatching on the witness program. This copies every element for unknown versions, wrong-length v0 programs, pay-to-anchor, Taproot without SCRIPT_VERIFY_TAPROOT, and wrong-count P2WPKH witnesses, although those paths previously needed no copy.

Fold 9d160722716131b35d03a3ab0f7e4b3a154509ce, which moves conversion behind those checks, into that ownership-conversion commit. Its required size() and ToVectors() methods already exist in fa34694a431597258039ca5e16e7f23a85e5c576, so this adds no dependency and leaves the final tree unchanged. Keeping the placement decision in the same commit makes the copy boundary easier to review and avoids retaining this overhead if #36895 merges without the follow-up.


Link

[suggestion] · Witness deserialization tests miss multi-chunk elements

The current loop appears correct, but the new unit tests never deserialize an element larger than MAX_VECTOR_ALLOCATE and therefore miss multi-chunk append and consumption errors.

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

Details and suggested fix

script_witness_representation deserializes elements of at most 65,536 bytes, while script_witness_large_count uses tiny elements. script_witness_large_element only deserializes a MAX_SIZE + 1 length prefix, which fails before reading element bytes. Add a case with MAX_VECTOR_ALLOCATE + 1 bytes whose contents differ across the chunk boundary, followed by a small element and trailing bytes. Compare the elements, back(), and unread-byte count against vector-of-vectors deserialization. A variant truncated inside the second chunk should throw. This would distinguish a regression that stops after the first chunk or appends subsequent chunks at the wrong offset.


Link

[suggestion] · The memory-usage assertion accepts serialized-size-only accounting

The fuzz assertion would accept omitting the witness allocation's header and malloc overhead, even though current accounting includes both and feeds mempool usage.

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

Details and suggested fix

For a non-empty witness, returning Data().size() would satisfy DynamicMemoryUsage() >= ser_stack.size() while omitting the allocation's eight-byte header and malloc overhead. Require at least ser_stack.size() + 8 instead. That rejects serialized-size-only accounting without reproducing the allocator-rounding formula. The reported value flows through RecursiveDynamicUsage(CTxIn) into cached mempool-entry usage, so this checks a meaningful retained-memory invariant.


Link

[suggestion] · The synthetic deserialization benchmark arrives after the baseline change

The benchmark can already build at base; placing it before the serialized-storage commit would allow direct per-commit comparisons without transplanting benchmark code and would leave the final tree unchanged.

Location: src/bench/block_deserialize.cpp:1 at 4a206ee6df89 (commit) (commit).

Details and suggested fix

Commit 4a206ee6df8954f0333ff2a7c6c09ae3b6924c42 adds the synthetic deserialization workloads after 150002be68e0ca307b71fc968589c45d7b44687e changes witness storage. The benchmark uses existing transaction and block serialization, VectorWriter, SpanReader, and GetBlockWeight, not the new witness accessors. Move the benchmark commit, including its CMake entry, before the representation change. Although the current placement follows the #36895/follow-up split, introducing the workloads first would let reviewers compare the vector baseline, minimal serialized representation and later optimizations with the same in-tree benchmark.


Link

[suggestion] · The P2WPKH benchmark overstates public-key size

The synthetic P2WPKH case uses two 72-byte witness items per input, so it models about 9% fewer transactions and allocations than the same full-block shape with a 33-byte compressed key.

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

Details and suggested fix

WriteTx gives every witness item size_wit_item bytes, and DeserializeBlockP2WPKH sets that to 72 for both items. For its two-input/two-output shape, this produces 912 WU per transaction instead of 834 WU for a 72-byte signature and 33-byte compressed public key. Roughly 4,795 such transactions fit in the synthetic block instead of 4,385, so the current fixture understates transaction, input and witness-allocation counts. Allow per-item sizes such as {72, 33} and recompute num_txn so the case represents the P2WPKH workload it names.


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

CompactSize canonicality was introduced to eliminate deserialize/reserialize byte mismatches that could become exploit opportunities. The original proposal justified compatibility by explaining that older nodes already normalized encodings before relay and transaction hashing, while block headers contained no CompactSize fields.

The affected representation stores and compares serialized witnesses directly. Canonicality therefore matters both to the existing external decoding contract and to the assumption that a stack has one serialization. The base reader rejects overlong encodings at each CompactSize boundary; the head witness deserializer continues using that checked reader for element counts and lengths.

Source 1

BIP141 separates transaction effects from validation data to address transaction malleability while remaining soft-fork compatible. Its wire format defines witnesses as item counts followed by length-prefixed byte strings—not Script—and commits the witness-bearing serialization through wtxids and the coinbase witness commitment.

Changing the in-memory container does not change those serialized commitments. Empty witnesses, item order, length prefixes, and the distinction between no elements and an empty element affect witness serialization and transaction witness presence. The coinbase witness remains a single 32-byte reserved value when the commitment is present.

Source 1

Malformed-input rejection is an explicit interoperability boundary. Historical tests were added after finding gaps in another implementation: every strict prefix of a witness transaction must fail, incomplete CompactSize encodings must fail, and transaction flag 0x02 must be rejected as unknown optional data. Separate oversized-CompactSize tests recognize that transport payload limits can otherwise mask the decoder's own size check.

The custom witness deserializer replaces generic vector deserialization, so compatibility includes rejection and byte-consumption behavior, not just successful round trips. Transaction optional-data flags are also distinct from script-validation flags: unknown transaction serialization flags fail rather than receive upgrade-compatible script treatment.

Source 1 · Source 2

BIP342 deliberately gives OP_SUCCESSx precedence over ordinary execution and initial-stack limits. Its stated purpose is clean soft-fork extensibility: later rules can restrict these already-valid scripts without having to preserve complicated existing execution edge cases. The script is committed to by the output, preventing third parties from injecting this unconditional-success mechanism.

Witness extraction and execution-stack construction must preserve the distinction between structural Taproot validation and subsequent Tapscript execution. In the base implementation, OP_SUCCESSx scanning occurs before the initial 1000-element and 520-byte element checks; moving ownership of execution arguments does not redefine that ordering.

Source 1

Tapscript's signature budget ties verification work to paid witness weight instead of adding another block-selection constraint. The historical specification gives each input a budget of its full serialized witness size plus 50, charges 50 for each executed signature opcode with a nonempty signature, and counts unknown public-key types too. Ordinary signatures fund their own checks; duplicated-signature constructions require additional weight. The factor 50 reflects the previous 4-million-weight/80,000-sigops ratio, while the free operation accounts for non-witness input weight.

GetSerializeSize(witness) supplies a consensus resource budget, not an estimate of heap consumption. It refers to the original serialized witness, including its count prefix and elements later removed for other roles, rather than only the remaining execution arguments. The same historical design retains 1000-element stack/altstack and 520-byte element limits while removing the old script-size and opcode-count limits under stated computational assumptions.

Source 1

Mempool memory accounting was introduced as a measurement of actual resource use, with resource limiting an explicit intended application. The subsequent limiting proposal coupled a bounded mempool with eviction of cheaper transactions and a corresponding minimum relay fee.

This is a different accounting domain from consensus weight and fee-rate size. A representation change can reduce retained memory without changing transaction serialization or weight, allowing a different number of transactions within the same memory budget. The pinned entry separately caches transaction weight and recursively calculated memory usage.

Source 1 · Source 2

Ralph's inferences

Decoder size limits and incremental allocation defend against different attacks. MAX_SIZE bounds a declared element count or byte-string length at 0x02000000; it is not a total-witness execution limit. Incremental allocation avoids trusting a large declared length before the sender supplies its contents. The base reader explicitly describes this DoS model, and the head reads element contents in chunks capped by MAX_VECTOR_ALLOCATE, currently 5,000,000 bytes.

A later block-weight or script failure does not remove the resource cost of parsing an adversarial message first. Conversely, these generic parsing safeguards do not justify applying execution-stack limits indiscriminately to every serialized witness.

The pinned base and head preserve role-sensitive witness extraction. P2WPKH requires exactly two items; P2WSH removes the final item as the script, verifies its SHA256 commitment, and executes with the preceding items. Taproot first recognizes an annex only when at least two items exist and the final nonempty item starts with ANNEX_TAG, hashes the serialized annex, then distinguishes a one-item key path from a script path whose final items are control block and script.

Those roles determine which bytes are hashed, which items become executable arguments, and which structural failures occur. In particular, hashing the serialized annex rather than only its raw contents preserves the existing length-prefixed hash input, while removing it from execution does not remove it from original-witness size accounting.

Source 1

Upgrade behavior is intentionally not equivalent to validating every witness as an ordinary execution stack. The pinned code rejects unsupported version-0 program lengths, but other version/size/P2SH combinations succeed unless the applicable discouragement flag rejects them. Native Taproot succeeds without interpreting its witness when SCRIPT_VERIFY_TAPROOT is absent; unknown Taproot leaf versions succeed after commitment checks unless discouraged. Native pay-to-anchor has its own success branch.

These distinctions explain why some witnesses can contain enormous numbers of small elements without ordinary execution-stack checks applying. Delaying conversion to vectors affects materialization work, while the existing version, wrapping, activation, and discouragement decisions define whether the witness is interpreted at all.

Source 1

Serialized witness size is not interchangeable with retained heap usage or execution-stack allocation cost. Tiny or empty elements have cheap wire encodings, while materializing them as vectors creates per-element objects. The head keeps serialized storage until execution needs vectors and routes the witness's memory report through RecursiveDynamicUsage into cached transaction-entry usage; total mempool usage also includes indexes, graph storage, and other overhead.

The optimization interacts with three separate budgets: parsing-time allocations, consensus validation work, and retained mempool memory. Reducing the last does not alter the first two rules, and a -maxmempool charge is not simply witness bytes or discounted transaction weight.