Keep witness stacks in serialized form in CScriptWitness

bitcoin/bitcoin: PR #36895

3 suggestions

Optional improvements

Link

[suggestion] · Items() traversal is quadratic without a public complexity warning

In the shipped libbitcoinkernel C++ wrapper, traversing Items() now performs quadratic element scanning, but neither the public accessor nor the wrapper documents this cost.

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

Details and suggested fix

btck_witness_stack_get_item_at() now calls CScriptWitness::operator[], which starts from begin() for every index; base used constant-time vector indexing. WitnessStackApi::Items() dereferences through GetItem(index), so visiting all n items requires n(n-1)/2 element skips even with a range-for. The witness-level C API offers no forward-traversal alternative. This matters for consumers walking block witnesses because a consensus-valid unknown-version spend can contain millions of empty elements. At minimum, document the O(index) lookup in bitcoinkernel.h and the resulting O(n²) traversal on GetItem() and Items(). That exposes the storage tradeoff at the API boundary without changing compact storage or element contents.


Link

[suggestion] · VerifyWitnessProgram() materializes witnesses on paths that ignore them

Unknown witness versions, pay-to-anchor, and Taproot with SCRIPT_VERIFY_TAPROOT unset now rebuild unused nested vectors during verification, adding per-element work without changing validation results.

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

Details and suggested fix

ToVectors() reserves one vector object per witness element before dispatch. An unknown-version spend in a mined block can contain millions of empty elements, and block flags omit SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM, so verification reconstructs the whole stack before returning success without examining it. The same unnecessary conversion precedes the pay-to-anchor return and the Taproot return when SCRIPT_VERIFY_TAPROOT is unset. Base only took a span on these paths and copied execution arguments inside ExecuteWitnessScript(). The deserialization peak already includes a temporary nested vector; the avoidable cost here is rebuilding it during verification.

Dispatch these content-independent branches before ToVectors(), preserving their existing flag checks, and leave the owning-vector execution path unchanged. The Tapscript budget can continue using GetSerializeSize(witness).


Link

[suggestion] · DynamicMemoryUsage() tests do not cap witness accounting

The new witness tests would accept an excessive per-element DynamicMemoryUsage() charge, potentially causing earlier mempool trimming, although the current accounting is correct.

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

Details and suggested fix

For non-empty stacks, the fuzz target only asserts DynamicMemoryUsage() >= ser_stack.size(). A charge that includes vector-sized overhead per element would still satisfy that assertion, and the new unit cases do not check memory usage. RecursiveDynamicUsage(CTxIn) feeds this value into the cached mempool charge used for trimming. Add an upper-bound assertion such as witness.DynamicMemoryUsage() <= memusage::MallocUsage(4 + GetSerializeSize(witness)) to script_witness_large_count. Its existing 65,535- and 65,536-element witnesses make a per-element accounting regression distinguishable from the intended serialized-size charge, while MallocUsage() accounts for allocator rounding.


Coverage details

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 parsing was introduced to eliminate deserialize–reserialize byte mismatches that could conceal exploitable inconsistencies. The original compatibility argument was that older reference nodes already reconstructed transactions and blocks and serialized them canonically before hashing or relaying; rejecting alternative encodings therefore did not change the canonical transaction contents or block-header hash.

Replacing a reconstructed stack with stored serialized bytes makes uniqueness of serialization especially important. The pinned parser still rejects nonminimal CompactSize encodings, independently of its optional size-range check. This is the historical basis for treating serialized-byte equality as stack equality, rather than accepting several byte encodings for the same stack.

Source 1

SegWit defined witnesses as counted stacks of byte arrays, not scripts or undifferentiated byte strings. BIP141 assigns each input a witness field and commits witness-bearing serialization through wtxids. BIP144 requires the old transaction format when the witness is empty, with empty-witness transactions retaining wtxid equal to txid. Its marker and flag were designed to distinguish formats without breaking older parsers or test uses of empty transactions.

An empty stack and a stack containing an empty byte array cannot be collapsed merely because both contain zero payload bytes. Stack cardinality determines witness presence and affects transaction serialization, hashing, and interpretation. Both pinned base and head reject an extended transaction encoding whose input witness stacks are all empty.

Source 1 · Source 2

Tapscript replaced a separate block-wide signature-operation constraint with an input-local budget of 50 plus the complete serialized witness size, including its CompactSize prefix. Each executed signature opcode with a nonempty signature consumes 50. The stated goals were to bound pathological verification work while avoiding a second independent constraint in miners' transaction-selection problem. Ordinary signatures already contribute sufficient witness weight; repeated-signature constructions must buy additional weight. The factor 50 follows the historical ratio of four million weight units to 80,000 sigops, and the free operation accounts for non-witness input weight.

The budget is defined by wire serialization, not allocation size, element count alone, or the execution stack remaining after removing script, control block, and annex. Base computes it from the original nested-vector witness; head computes it from CScriptWitness. The private four-byte storage header is not part of this consensus quantity.

Source 1

Tapscript's resource model assumes that other interpreter structures are independently bounded and that relevant operations have controlled cost. Its rationale cites bounded stack/altstack sizes, the 520-byte element limit, and constant-time conditional-execution bookkeeping when explaining removal of script-size and opcode-count limits. Separately, OP_SUCCESS deliberately precedes execution-stack restrictions to preserve broad soft-fork upgrade possibilities.

Execution limits are not interchangeable with limits on every stored or deserialized witness. The pinned interpreter also accepts unknown witness-version combinations for future soft-fork compatibility. These constraints explain why storage must tolerate witnesses that are not ordinary bounded initial stacks for an executed current-version script.

Source 1 · Source 2

Mempool memory accounting was introduced as an explicit measure of resource consumption, initially exposed through getmempoolinfo and intended to support resource limits. Its original discussion distinguishes indirect allocations from the enclosing entry: the entry's own storage is accounted through its container so alignment and malloc overhead can be included.

The witness representation changes the owned allocations being measured, not merely its network size. Base recursively counts the outer witness vector and each element allocation; head delegates that accounting to the witness's single allocation. The pinned mempool trims against DynamicMemoryUsage, while eviction ranking remains fee/virtual-size based.

Source 1 · Source 2

The parent proposal identifies per-element vector objects and allocations as the source of witness memory amplification. Its stated objective was a sufficient practical reduction, rather than proving an optimal data layout. It also explicitly distinguishes memory retained in a deserialized transaction from temporary peak memory during processing.

This supplies the historical motivation for separating compact, immutable stored witnesses from their working representation. It does not establish that every phase has the same memory bound: head still constructs vectors during deserialization and script verification, even though the stored witness uses one allocation.

Source 1 · Source 2

Ralph's inferences

Retaining nested-vector deserialization appears to isolate the storage change from parser-acceptance changes: incoming witnesses still pass through the existing vector parser before being serialized into compact storage. Retaining vector-based execution similarly preserves an owning, mutable stack for the existing interpreter; head moves the remaining elements into execution rather than requiring execution to mutate serialized storage. This trades temporary allocations and conversion work for a narrower representation transition.

The head interface explicitly promises vector-equivalent deserialization semantics and failures. Base already copied execution arguments into a mutable vector; head constructs that working representation through ToVectors and moves it onward. These are code-supported explanations of the tradeoff, not independently documented author intent for this split.

Linear stored-witness indexing is the space-for-access-time consequence of keeping serialized element lengths without a separate offset index. Forward traversal can skip each element once, whereas accessing position i starts at the beginning and skips i elements; repeated indexed traversal can therefore become quadratic. A vector working stack avoids imposing that access pattern on execution.

Head's operator[] implements exactly this scan, and back() delegates to the final index. The representation removes persistent per-element metadata while preserving forward iteration and conversion to vectors. The inspected history does not establish a constant-time-access compatibility requirement or fully document the decision to omit cached offsets.

The mempool limit is an estimate of owned retained memory, not an exact process-RSS ceiling or a consensus-weight limit. The accounting model includes vector capacity and estimated allocation overhead, caches inner usage for efficiency, and separately estimates container overhead. Its malloc formula is based on measurements of a particular Linux allocator.

Head charges the witness's serialized bytes plus its private header through MallocUsage, while enclosing transaction storage remains accounted elsewhere. Lower representation overhead can therefore increase the number of retained transactions under an unchanged memory limit, without changing their consensus weight. Temporary deserialization or interpreter allocations are outside that retained-witness measurement.

Under the specified counted-stack format, zero elements serialize as 00, while one empty element serializes as 01 00. Consequently, payload emptiness cannot substitute for stack emptiness, even where the single-empty witness would later fail script validation.

Base defines witness nullness through the outer vector's emptiness. Head instead uses absence of its allocation, with a static 00 serialization for that state. Preserving this distinction keeps witness presence, round-tripping, and transaction-format selection independent of whether individual elements contain bytes.

Source 1

Unresolved disagreements

The parent discussion contains competing priorities for temporary vector expansion during verification. One participant argued for avoiding expansion on paths that never execute a script. A response prioritized deserialization defenses, arguing that arbitrary peers can trigger parsing cheaply, whereas block script validation follows proof-of-work checks and is rate-limited in that threat model. The inspected discussion does not resolve where conversion should occur.

Head materializes vectors before witness-version dispatch. The historical exchange distinguishes persistent memory reduction, temporary verification cost, and pre-validation peer-triggerable work; it is not evidence that these resource costs are equivalent, nor a judgment of the current change.

Source 1 · Source 2