WIP: kernel: add btck_witness_stack_iterate_items

bitcoin/bitcoin: PR #36909

2 minor findings · 6 suggestions

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

Findings

Link

[minor] · VerifyWitnessProgram expands witnesses before checks that need no execution stack

VerifyWitnessProgram now expands witnesses before count and version checks, adding avoidable per-element allocations on early-return paths; validation results are unchanged and the extra runtime is unmeasured.

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

Details and suggested fix

A P2WPKH spend can carry 100,000 one-byte witness elements, about 200,000 WU of witness data, while remaining below MAX_STANDARD_TX_WEIGHT. If funding, fees and the other admission checks pass, neither input nor witness standardness rejects that item count. PolicyScriptChecks then reaches this conversion with cs_main and m_pool.cs held, allocates each element, and only afterward returns SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH. Base checked the count through a borrowed span without copying. Since deserialization still builds and frees a vector of vectors, this adds another per-element allocation cycle. Other early returns, including disabled Taproot, unknown versions, P2A and failed control-block or commitment checks, also expand first whenever this function is reached.

Inspect counts and role elements through the read-only witness interface, then build owning vectors only for the execution prefix at the ExecuteWitnessScript call sites. Preserve the annex's CompactSize-prefixed hashing and the OP_SUCCESSx-before-stack-limits ordering. Base already copied the execution stack before that tapscript scan.


Link

[minor] · Existing witness traversal is now quadratic without a complexity warning

Items() and repeated btck_witness_stack_get_item_at calls now traverse quadratically without warnings, despite the linear bulk alternative; the only in-tree caller is a four-item test, and use by external consumers is unconfirmed.

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

Details and suggested fix

Items() still uses the indexed range whose dereference calls GetItem(index). That reaches CScriptWitness::operator[], which walks from begin() to the requested index, so a full traversal performs quadratic work instead of base's linear traversal. The range still advertises random-access iteration. Consensus-valid blocks can contain witnesses with millions of elements through upgradeable witness versions or OP_SUCCESSx tapscripts, although this cost was not timed. At minimum, document the O(index) lookup and quadratic full-traversal cost in the C and C++ accessors, and direct full traversals to btck_witness_stack_get_items or GetItems(), noting that the latter returns borrowed spans rather than owned item bytes.


Optional improvements

Link

[suggestion] · GetItems() permits borrowed results from a temporary owning handle

Calling GetItems() on a temporary owning WitnessStack leaves its nonempty spans dangling after the statement; no current caller misusing this lifetime was found.

Location: src/kernel/bitcoinkernel_wrapper.h:679 (head).

Details and suggested fix

auto items = WitnessStack{view}.GetItems(); returns spans into the temporary's copied CScriptWitness allocation. Destruction of the owning handle frees that allocation at the semicolon, unlike GetItem(), which returns copied bytes. Follow the existing Items() convention by declaring GetItems() const & and deleting GetItems() const &&, and document that the result borrows its bytes. As with Items(), this also rejects prvalue views; callers must still keep the underlying owner alive.


Link

[suggestion] · Vector construction can violate the noexcept accessor invariant

Constructing an element above MAX_SIZE makes later noexcept access terminate; wire reads reject it, and no current production caller producing such an oversized vector was identified.

Location: src/script/script.cpp:312 (head).

Details and suggested fix

A vector containing one MAX_SIZE + 1-byte element passes the constructor: serialization writes that length, and the total remains well below Allocate()'s uint32_t limit. A subsequent front() dereferences the iterator, whose default range-checked ReadCompactSize throws inside noexcept, causing std::terminate. The class currently assumes this cannot happen only “in practice” for vector-built stacks. Reject element counts and lengths above MAX_SIZE with a recoverable exception in the constructor, and add a direct-construction boundary test. The existing unit sizes stop at 65,536 bytes, while the deserialize-based fuzz target cannot construct this state.


Link

[suggestion] · IsWitnessStandard materializes spans for checks that need only a scan

For Taproot policy checks, ToSpans() adds a whole-witness temporary array before rejection; a weight-bounded stack of tiny items can require several megabytes without changing policy results.

Location: src/policy/policy.cpp:328 (head).

Details and suggested fix

The Taproot branch fills ToSpans() before checking for an annex or an empty control block. There is no item-count bound here, so 200,000 empty elements can require roughly 3.2 MB of span metadata on a typical 64-bit build before the empty-control-block rejection. Base inspected a borrowed span without allocating. Use the witness's read-only accessors to inspect trailing roles and forward iteration to check the execution prefix, avoiding the full array while preserving policy decisions. This may take another linear pass. In the P2WSH branch, check the count before the newly linear back() lookup; its later ToSpans() allocation is already bounded to a small array. These temporaries are smaller than the vector-of-vectors allocation still used during deserialization.


Link

[suggestion] · The PR text describes callbacks instead of the implemented bulk arrays

The PR title and description promise btck_witness_stack_iterate_items and IterateItems, but the API commit adds array-based btck_witness_stack_get_items and GetItems().

Location: src/kernel/bitcoinkernel.cpp:879 at 9d0f1d05bd30 (commit) (commit).

Details and suggested fix

Commit 9d0f1d05bd30e49628239542c697ef44d1fcbe92, the kernel-API addition following the representation prerequisites, fills caller-provided pointer and size arrays and adds a wrapper returning borrowed spans. It does not add btck_WitnessItemCallback. The actual contract requires the exact item count, ties byte-pointer validity to the witness owner, and permits null pointers for empty items. Retitle the PR to kernel: add btck_witness_stack_get_items and describe that array contract so reviewers assess the implemented interface rather than a callback interface. No commit rearrangement is needed.


Link

[suggestion] · The span-lifetime comment omits whole-witness replacement

The ToSpans() lifetime promise overlooks assignment and Unserialize, which replace the allocation before the object dies; no current caller retaining views across replacement was found.

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

Details and suggested fix

ToSpans() says its spans remain valid “as long as this witness is”, and the class description calls the witness unmodifiable. However, copy assignment replaces or resets m_data, move assignment replaces the destination's allocation, and successful Unserialize assigns new contents. Previously obtained spans and iterators can therefore dangle while the object remains alive. State that individual elements cannot be edited in place, but replacing the contents invalidates views into the previous allocation. Moving the source instead transfers that allocation, whose views depend on the new owner keeping it alive.


Link

[suggestion] · GetItems() needs two full-size scratch buffers

For nonempty stacks, GetItems() allocates two full-size scratch arrays and copies their metadata into a third vector, although a visitor could fill the result directly.

Location: src/kernel/bitcoinkernel_wrapper.h:682 (head).

Details and suggested fix

items(count) and sizes(count) coexist with the reserved views result, using about 32 bytes of metadata per item on typical 64-bit builds, half of it temporary. The element bytes are not copied, so this remains a constant-factor cost in a linear accessor. Consider a per-item visitor in the C interface so the wrapper can reserve views and append each span directly during the traversal. That removes the two scratch buffers and the metadata-conversion pass while retaining borrowed bytes and arbitrary-order access through the returned vector. The runtime tradeoff between callbacks and arrays has not been measured.


Coverage details

Earlier concerns

Earlier reports raised these, with the titles and severities shown there. This review neither republished nor resolved them.