6 suggestions
Earlier concerns neither republished nor resolved: 1 suggestion. See the Run archive for their assessments.
Optional improvements
[suggestion] · Kernel Items() traversal becomes quadratic
The wrapper's Items() now locates witness elements quadratically, without a linear witness-item traversal API; no in-tree non-test consumer was found and external production impact is unconfirmed.
Location: src/kernel/bitcoinkernel.cpp:875 (head).
Details and suggested fix
btck_witness_stack_get_item_at() now reaches CScriptWitness::operator[], which restarts at begin() and skips index element prefixes. The wrapper iterator retains only an index, not a parsing cursor. Enumerating n items therefore performs about n(n - 1) / 2 prefix skips, where the base used direct vector indexing. A consensus-valid unknown-version witness spend can contain almost four million empty elements within block weight, making complete enumeration require trillions of skips rather than being bounded by ordinary execution-stack limits.
Expose a linear cursor or per-item callback and use it for Items(). If that is deferred, at minimum document O(index) lookup and O(n²) complete traversal in bitcoinkernel.h and the wrapper. Whole-transaction serialization provides a workaround only if callers parse the transaction themselves.
[suggestion] · VerifyWitnessProgram() expands witnesses before spend-type dispatch
VerifyWitnessProgram() now copies nonempty witnesses before dispatch, adding allocations on Taproot key-path and early-return paths that previously borrowed them; the runtime impact has not been measured.
Location: src/script/interpreter.cpp:1929 (head).
Details and suggested fix
ToVectors() reserves an outer vector and copies every element before checking the witness version or spending form. A single-signature Taproot key-path spend therefore allocates and copies its signature unnecessarily. Unknown witness versions and other early-return paths also expand the whole witness, potentially including millions of elements. The base borrowed a span and copied only the remaining execution arguments inside ExecuteWitnessScript(). Use borrowed element spans for dispatch and structural checks, and defer ToVectors() until the three branches that execute scripts. VerifyTaprootCommitment() can accept a control-block span, as ComputeTaprootMerkleRoot() already does. Preserve structural-element removal, length-prefixed annex hashing, full-witness signature budgeting, and the existing OP_SUCCESSx ordering.
[suggestion] · Vector-built witnesses can violate the noexcept parser invariant
CScriptWitness can accept vectors above MAX_SIZE and then terminate in a noexcept accessor, although no current caller producing such counts or element lengths was found.
Location: src/script/script.cpp:312 (head).
Details and suggested fix
A single MAX_SIZE + 1-byte element fits the constructor's 32-bit aggregate limit, and WriteCompactSize() accepts its length. Calling front() then re-parses that length with range-checked ReadCompactSize(). Its exception escapes Iterator::operator*() noexcept, causing std::terminate. size() still returns one in this example; an excessive outer count would instead fail in size() and begin(). Use ReadCompactSize(reader, /*range_check=*/false) when parsing the class's private, self-generated serialization. Keep the range-checked vector decoder in Unserialize() unchanged so wire-input acceptance does not change.
[suggestion] · The new witness tests lack a memory-accounting ceiling
The new witness tests check semantic equivalence and a memory lower bound, but would not detect a return to correctly accounted per-element storage.
Location: src/test/fuzz/script_witness.cpp:91 (head).
Details and suggested fix
The fuzz assertion checks only DynamicMemoryUsage() >= serialized_size, while script_witness_representation never checks memory usage. An outer vector plus per-element allocations also satisfies that lower bound, so these assertions do not protect the compact accounting that RecursiveDynamicUsage(const CTxIn&) now uses. Add a representation-specific unit case with many empty or one-byte elements, such as 65,536, and an upper bound based on memusage::MallocUsage(4 + serialized_size). Also check zero usage for empty and moved-from witnesses. Keep this fixture out of the all-indices loop, which would be quadratic. These checks protect the accounting estimate, not physical allocator behavior or peak deserialization memory.
[suggestion] · IsWitnessStandard() allocates an unnecessary Taproot span vector
For each nonempty native Taproot input, IsWitnessStandard() now builds a temporary span vector, including key-path spends that need no per-element policy checks.
Location: src/policy/policy.cpp:328 (head).
Details and suggested fix
ToSpans() reserves and fills one span per element before the annex and control-block checks. The base's borrowed std::span required no allocation. Use the witness's size() and a cached back() result for those checks, then forward iteration over the first size() - 2 elements for a script-path spend with a TAPROOT_LEAF_TAPSCRIPT leaf. Preserve the size() >= 2 annex guard and exclude both the script and control block from the item-size loop. This avoids the temporary allocation without changing policy.
[suggestion] · The mempool capacity improvement is missing from the release notes
Lower retained transaction memory can reduce getmempoolinfo's usage and increase capacity under the same -maxmempool, depending on the transaction mix, but the PR adds no release note explaining this.
Location: src/core_memusage.h:22 (head).
Details and suggested fix
RecursiveDynamicUsage(const CTxIn&) now charges one compact witness allocation instead of an outer vector and each element allocation. CTxMemPoolEntry includes that estimate in nUsageSize, which feeds the RPC's usage and the total compared with the configured limit in TrimToSize(). Add a short doc/release-notes-<PR>.md entry describing this operator-visible memory and capacity improvement. This reflects real savings in retained memory rather than under-accounting.
Earlier concerns
Earlier reports raised these, with the titles and severities shown there. This review neither republished nor resolved them.
- [suggestion]: Witness count tests miss the five-byte
CompactSizeboundary (earlier report)
Background
Ralph's summary of historical context for the behaviour affected by this change. The historical record reviewed here is incomplete.
Documented decisions
SegWit deliberately separates the witness's wire representation from Script encoding and from the transaction identifier used to identify spends. Each input's witness is a count followed by length-prefixed elements; an empty witness is encoded as 0x00. The witness-bearing serialization determines wtxid.
The base transaction reader decodes the witness as a vector of byte vectors; the head delegates to CScriptWitness. This is a storage change behind an existing wire format, not an opportunity to alter element boundaries, empty-stack meaning, or serialized bytes. The new private length header is not part of transaction serialization. An empty stack and a stack containing one empty element remain distinct.
PSBT was designed for interoperability between different wallet implementations and offline signers. Its format requires value data to occupy exactly its declared length, minimally encoded CompactSize key types, and an unsigned transaction in the old serialization format with empty scriptSigs and witnesses.
In the pinned base, final_script_witness uses the same vector witness decoder inside UnserializeFromVector; the head substitutes CScriptWitness without removing that wrapper. Thus witness decoding and PSBT value-length validation are separate compatibility layers. The wrapper's declared-size mismatch failure and the unsigned-transaction restrictions remain relevant independently of the witness's in-memory representation.
Malformed-input rejection has explicitly been treated as an implementation-compatibility concern. Historical tests were added after discrepancies were found in another implementation: every strict prefix of a witness transaction must fail, incomplete CompactSize encodings must fail, and an unsupported transaction flag must not be silently accepted.
These are existing reader behaviors that reach the changed witness deserializer. The base also rejects superfluous witness records when every stack is empty. Preserving the reader contract therefore means more than producing equal stacks on valid input: truncation and optional-data rejection must remain distinct from successful decoding.
Tapscript's validation order deliberately gives OP_SUCCESSx precedence over execution-stack resource limits. BIP 342 explains that unconditional success avoids difficult edge cases, including an initial stack exceeding 1,000 elements, and provides a soft-fork upgrade mechanism.
ExecuteWitnessScript in the pinned base scans for OP_SUCCESSx before checking the initial stack count or element sizes. Extracting the execution stack or changing its ownership must not turn those execution limits into unconditional witness-decoding limits. The raw witness includes structural elements, and even the remaining initial stack cannot always be rejected solely by its size before the Tapscript success scan.
Serialized weight is not generally an upper bound on the memory occupied by an expanded witness. An earlier orphanage proposal documented a standard-weight transaction with 199,000 one-byte witness elements using approximately 11.1 MB: about 28 times its weight-based accounting. It also explained that witness standardness cannot be checked while the spent inputs are missing.
This supplies the adversarial motivation for reducing per-element vector and allocator overhead in CScriptWitness. It also explains why ordinary execution or policy stack limits do not eliminate the storage problem at admission boundaries. The earlier proposal explicitly sought to preserve admission and orphan-resolution behavior, including transactions with many small witness elements, rather than equating memory protection with stricter witness acceptance.
The kernel witness-access API was introduced to support silent-payment scanning without forcing callers to deserialize raw transactions themselves, described as difficult and error-prone. Its design exposes a borrowed witness view, indexed item delivery through a byte-writing callback, and explicit owned-copy lifecycle operations.
The affected kernel accessor is an application-facing extraction boundary, not just an interpreter helper. The pinned header ties the borrowed witness to the transaction input's lifetime and requires a valid index. The storage change preserves those ownership concepts while changing the cost of locating an indexed item; the retrieved historical proposal does not promise constant-time access.
Ralph's inferences
Canonicality and the existing vector decoder together define a compatibility boundary: one logical stack has one accepted serialization, and malformed or excessive length declarations are rejected rather than normalized into a new accepted representation.
Pinned ReadCompactSize rejects overlong encodings at the 253, 65,536 and 2^32 boundaries and, with its default range check, rejects values above MAX_SIZE = 0x02000000. Applied to a vector of byte vectors, that bounds the outer element count and each element's declared byte length separately; it is not an aggregate witness-size limit. The head still decodes through that vector path. This also supplies the premise for comparing canonical stored serializations as stack equality. Historical testing confirms that malformed encodings matter even when transport limits make some oversized cases unreachable over ordinary P2P messages.
Source 1 · Source 2 · Source 3 · Source 4
Execution-stack extraction separates immutable transaction evidence from the mutable working state of Script execution. Structural witness elements are not ordinary execution arguments, and resource accounting can still refer to the complete original witness after those elements are removed from the working stack.
The base borrows a span, removes the witness script or Taproot annex/control/script elements from that view, then copies the remaining arguments into an owned vector for execution. The head instead expands once with ToVectors(), removes structural elements, and moves the remainder into ExecuteWitnessScript. In both pinned versions, the Tapscript budget is 50 plus the serialized size of the full original witness—including its count and element-length prefixes—not the reduced execution stack, allocated memory, or the new private storage header. This distinction follows from the code; the retrieved BIP passage documents the separation and validation ordering, but not the numerical budget rationale.
The resource tradeoff is between long-lived compact storage and temporary expansion or repeated parsing. Compact storage reduces retained per-element overhead, but does not by itself bound peak decoding or validation memory, nor make repeated indexed access cheap.
At the head, deserialization temporarily constructs the original vector of vectors, and validation expands the witness before branching on its spending form. Those temporary costs remain even when retained transactions are compact. ToVectors supplies owned, mutable execution data; ToSpans supplies an indexable collection of borrowed views without copying payloads. Direct indexing and back() instead scan preceding element encodings. Consequently, one forward traversal is linear in the number of elements, while fetching every item through the kernel's indexed accessor can require quadratic traversal work. Borrowed spans avoid payload copies only while their owning witness remains alive and unchanged. These are consequences of the pinned representation and ownership interfaces, not historical evidence that a particular CPU cost was accepted.