Keep witness stacks in serialized form in CScriptWitness #36895

Manually merged
sipa merged 15 commits from 202611_witpack_minimal into master 2026-11-26 17:07:37 +00:00 AGit
sipa commented 2026-11-16 19:11:40 +00:00 (Migrated from github.com)

This is split off from #36521. This PR focuses on reducing memory usage of transactions in memory, leaving performance improvements for other PRs.

CScriptWitness stores a witness stack as a std::vector<std::vector<unsigned char>>, which costs a 24-byte vector object and an allocation for every non-empty element. This makes it possible to construct transactions that take a large amount of memory after deserialization.

This PR first introduces encapsulation for CScriptWitness, hiding its representation. The last commit then changes the representation to be single std::unique_ptr<byte[]> which for non-empty witness stacks stores their serialization prefixed by a small length header. Witnesses can no longer be modified in place; they can only be replaced in their entirety. Access to the individual witness stack elements is done by on-the-fly deserialization instead.

CScriptWitness shrinks from 24 to 8 bytes, and CTxIn from 112 to 96 bytes. Worst-case allocated size for transactions kept in memory drops from roughly 28 bytes/WU to 1.6 bytes/WU.

This worsens deserialization and validation time, adding some 50-70 ms per block to the worst case for me. A follow-up #36918 with optimizations improves the worst case deserialization time significantly instead. Other minor degradations:

  • libbitcoinkernel's witness stack element accessor becomes \mathcal{O}(n) in the index of the witness element; using it to iterate a whole witness may therefore become \mathcal{O}(n^2).
  • CScriptWitness::back() is \mathcal{O}(n) in the length of the witness stack.

Issue reported by furszy and 0xB10C.

This is split off from #36521. This PR focuses on reducing memory usage of transactions in memory, leaving performance improvements for other PRs. `CScriptWitness` stores a witness stack as a `std::vector<std::vector<unsigned char>>`, which costs a 24-byte vector object and an allocation for every non-empty element. This makes it possible to construct transactions that take a large amount of memory after deserialization. This PR first introduces encapsulation for `CScriptWitness`, hiding its representation. The last commit then changes the representation to be single `std::unique_ptr<byte[]>` which for non-empty witness stacks stores their serialization prefixed by a small length header. Witnesses can no longer be modified in place; they can only be replaced in their entirety. Access to the individual witness stack elements is done by on-the-fly deserialization instead. `CScriptWitness` shrinks from 24 to 8 bytes, and `CTxIn` from 112 to 96 bytes. Worst-case allocated size for transactions kept in memory drops from roughly 28 bytes/WU to 1.6 bytes/WU. This worsens deserialization and validation time, adding some 50-70 ms per block to the worst case for me. A follow-up #36918 with optimizations improves the worst case deserialization time significantly instead. Other minor degradations: * libbitcoinkernel's witness stack element accessor becomes $\mathcal{O}(n)$ in the index of the witness element; using it to iterate a whole witness may therefore become $\mathcal{O}(n^2)$. * `CScriptWitness::back()` is $\mathcal{O}(n)$ in the length of the witness stack. Issue reported by furszy and 0xB10C.
DrahtBot commented 2026-11-16 19:11:51 +00:00 (Migrated from github.com)

The following sections might be updated with supplementary metadata relevant to reviewers and maintainers.

External sites

Reviews

See the guideline and AI policy for information on the review process.

Type Reviewers
ACK instagibbs, l0rinc, brunoerg, w0xlt, ajtowns
Concept ACK darosior, xyzconstant
Stale ACK optout21

If your review is incorrectly listed, please copy-paste <!--meta-tag:bot-skip--> into the comment that the bot should ignore.

Conflicts

Reviewers, this pull request conflicts with the following ones:

  • #36909 (kernel: add btck_witness_stack_get_items by pzafonte)
  • #36776 (bip352: match P2SH-P2WPKH instead of evaluating it by Eunovo)
  • #36721 (script: store interpreter stack elements as reference-counted objects by conduition)
  • #36548 (net: serve MSG_BLOCK by stripping witnesses in place by l0rinc)
  • #36466 (policy: make unstructured Taproot annexes standard by RobinLinus)
  • #36122 (BIP460: CISA for Taproot key path spends by fjahr)
  • #36109 (test: fix coinbases built on arbitrary parents by l0rinc)
  • #35788 (bitcoin-util: Add evalscript subcommand by ajtowns)
  • #35716 (wallet: Replace mapWallet and wtxOrdered with a boost::multi_index by achow101)
  • #35671 (mining: add TxCollection to bandwidth-efficiently validate external block templates by Sjors)
  • #35662 (script: prevent partial reinitialization of sighash data by l0rinc)
  • #31252 (rpc: print P2WSH and P2SH redem Script in getrawtransaction and getblock by polespinasa)
  • #29247 (CAT in Tapscript (BIP-347) by arminsabouri)

If you consider this pull request important, please also help to review the conflicting pull requests. Ideally, start with the one that should be merged first.

<!--e57a25ab6845829454e8d69fc972939a--> The following sections might be updated with supplementary metadata relevant to reviewers and maintainers. <!--006a51241073e994b41acfe9ec718e94--> ### External sites * Code coverage & benchmarks: https://corecheck.dev/bitcoin/bitcoin/pulls/36895 * Ralph review <img src=https://review.fish.foo/assets/bitcoin/bitcoin/36895.png alt="Ralph review status"> https://git.fish.foo/bitcoin/bitcoin/pulls/36895#author-ralph <!--021abf342d371248e50ceaed478a90ca--> ### Reviews See [the guideline](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#code-review) and [AI policy](https://github.com/bitcoin/bitcoin/blob/master/doc/AI_POLICY.md) for information on the review process. | Type | Reviewers | | ---- | --------- | | ACK | [instagibbs](https://github.com/bitcoin/bitcoin/pull/36895#issuecomment-7166030598), [l0rinc](https://github.com/bitcoin/bitcoin/pull/36895#issuecomment-7166539130), [brunoerg](https://github.com/bitcoin/bitcoin/pull/36895#issuecomment-7166733160), [w0xlt](https://github.com/bitcoin/bitcoin/pull/36895#pullrequestreview-6066032059), [ajtowns](https://github.com/bitcoin/bitcoin/pull/36895#issuecomment-7197997430) | | Concept ACK | [darosior](https://github.com/bitcoin/bitcoin/pull/36895#pullrequestreview-5926443294), [xyzconstant](https://github.com/bitcoin/bitcoin/pull/36895#issuecomment-6932126293) | | Stale ACK | [optout21](https://github.com/bitcoin/bitcoin/pull/36895#issuecomment-7146400976) | If your review is incorrectly listed, please copy-paste <code>&lt;!--meta-tag:bot-skip--&gt;</code> into the comment that the bot should ignore. <!--174a7506f384e20aa4161008e828411d--> ### Conflicts Reviewers, this pull request conflicts with the following ones: * [#36909](https://github.com/bitcoin/bitcoin/pull/36909) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36909.svg"></sub> (kernel: add btck_witness_stack_get_items by pzafonte) * [#36776](https://github.com/bitcoin/bitcoin/pull/36776) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36776.svg"></sub> (bip352: match P2SH-P2WPKH instead of evaluating it by Eunovo) * [#36721](https://github.com/bitcoin/bitcoin/pull/36721) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36721.svg"></sub> (script: store interpreter stack elements as reference-counted objects by conduition) * [#36548](https://github.com/bitcoin/bitcoin/pull/36548) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36548.svg"></sub> (net: serve `MSG_BLOCK` by stripping witnesses in place by l0rinc) * [#36466](https://github.com/bitcoin/bitcoin/pull/36466) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36466.svg"></sub> (policy: make unstructured Taproot annexes standard by RobinLinus) * [#36122](https://github.com/bitcoin/bitcoin/pull/36122) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36122.svg"></sub> (BIP460: CISA for Taproot key path spends by fjahr) * [#36109](https://github.com/bitcoin/bitcoin/pull/36109) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36109.svg"></sub> (test: fix coinbases built on arbitrary parents by l0rinc) * [#35788](https://github.com/bitcoin/bitcoin/pull/35788) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/35788.svg"></sub> (bitcoin-util: Add evalscript subcommand by ajtowns) * [#35716](https://github.com/bitcoin/bitcoin/pull/35716) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/35716.svg"></sub> (wallet: Replace mapWallet and wtxOrdered with a boost::multi_index by achow101) * [#35671](https://github.com/bitcoin/bitcoin/pull/35671) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/35671.svg"></sub> (mining: add TxCollection to bandwidth-efficiently validate external block templates by Sjors) * [#35662](https://github.com/bitcoin/bitcoin/pull/35662) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/35662.svg"></sub> (script: prevent partial reinitialization of sighash data by l0rinc) * [#31252](https://github.com/bitcoin/bitcoin/pull/31252) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/31252.svg"></sub> (rpc: print P2WSH and P2SH redem Script in getrawtransaction and getblock by polespinasa) * [#29247](https://github.com/bitcoin/bitcoin/pull/29247) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/29247.svg"></sub> (CAT in Tapscript (BIP-347) by arminsabouri) If you consider this pull request important, please also help to review the conflicting pull requests. Ideally, start with the one that should be merged first. <!--5faf32d7da4f0f540f40219e4f7537a3-->
darosior (Migrated from github.com) reviewed 2026-11-16 19:48:44 +00:00
darosior (Migrated from github.com) left a comment

Concept ACK

Concept ACK
First-time contributor

🔵 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).

🔵 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).

🔵 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).

Review coverage was incomplete.


Reviewed: 56fa33eac63c · Review report · Previous reports

permalink

<!-- forgejo-review-bot:bitcoin/bitcoin --> <!-- ralph-engine:current:806938d40e279b6d701b2e78128bb1a09b55193a0b697245a1dce6241d3081c1:3607c760b63c01fb7f1f349adfc3fd0614b148a7df02e42f2f0edc2d448925a1 --> <!-- ralph-base:5ba05739881855cba25c3c05d6f82a61b8a0665f --> <!-- ralph-head:56fa33eac63c37513305841ff1bd73f56ad92322 --> <!-- ralph-case:9475172aa0c4157ccde47c88ef4073442f8caeff2bb19bc7d5c6fc5764753b6e --> **🔵 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`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/56fa33eac63c37513305841ff1bd73f56ad92322/src/kernel/bitcoinkernel.cpp#L875>) (head). **🔵 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`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/56fa33eac63c37513305841ff1bd73f56ad92322/src/script/interpreter.cpp#L1929>) (head). **🔵 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`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/56fa33eac63c37513305841ff1bd73f56ad92322/src/test/fuzz/script_witness.cpp#L98>) (head). Review coverage was incomplete. <!-- Review tier: sensitive --> --- Reviewed: [`56fa33eac63c`](<https://git.fish.foo/bitcoin/bitcoin/commit/56fa33eac63c37513305841ff1bd73f56ad92322>) · [Review report](<https://review.fish.foo/report/36895-56fa33eac63c37513305841ff1bd73f56ad92322-3120-6.html>) · [Previous reports](<https://review.fish.foo/traces/36895/>) [permalink](<https://review.fish.foo/report/36895-56fa33eac63c37513305841ff1bd73f56ad92322-3120-6.html>)
w0xlt commented 2026-11-16 20:26:30 +00:00 (Migrated from github.com)

Concept ACK

Concept ACK
xyzconstant commented 2026-11-16 23:08:27 +00:00 (Migrated from github.com)

Concept ACK

Concept ACK
brunoerg commented 2026-11-17 13:22:15 +00:00 (Migrated from github.com)

Concept ACK

Concept ACK
pzafonte commented 2026-11-18 08:36:49 +00:00 (Migrated from github.com)
  • libbitcoinkernel's witness stack element accessor becomes O(n) in the index of the witness element; using it to iterate a whole witness may therefore become O(n^2)

This should be able to be addressed by an API function that walks the stack once and hands each item's bytes to the caller. Testing it out.

Edit: See: #36909

> * libbitcoinkernel's witness stack element accessor becomes O(n) in the index of the witness element; using it to iterate a whole witness may therefore become O(n^2) > This should be able to be addressed by an API function that walks the stack once and hands each item's bytes to the caller. Testing it out. Edit: See: #36909
instagibbs commented 2026-11-18 18:34:31 +00:00 (Migrated from github.com)

Did another clanker deep dive to see its performance effects on memory and verification speed. On the historical blockchain it seems like noise. Under adversarial conditions slightly slower verification speeds when dealing with related issues, but nothing remotely close to close to worst case blocks, even post-bip54.

Worst case regression I'm getting is +149ms for a block that is just 4M of witness data elements, which is a bit north of "50-70 ms per block" but might be due to measurement differences, and is largely irrelevant anyways.

Can share longer form slop on request, but nothing concerning.

concept ACK on focusing on the persistent memory usage first

Did another clanker deep dive to see its performance effects on memory and verification speed. On the historical blockchain it seems like noise. Under adversarial conditions slightly slower verification speeds when dealing with related issues, but nothing remotely close to close to worst case blocks, even post-bip54. Worst case regression I'm getting is +149ms for a block that is just 4M of witness data elements, which is a bit north of "50-70 ms per block" but might be due to measurement differences, and is largely irrelevant anyways. Can share longer form slop on request, but nothing concerning. concept ACK on focusing on the persistent memory usage first
sipa commented 2026-11-18 22:06:05 +00:00 (Migrated from github.com)

@instagibbs FWIW, these are the benchmarks I based this on. "minimal" is this PR. The "lazy conversion" and "direction deserialization" are follow-up optimizations not included in this PR. Hardware is a high-end Zen5 machine.


Each row is one 4M WU block, timed over deserialize, CheckBlock and ConnectBlock, in ms. These are medians of 11 interleaved rounds on the now-idle machine, gcc Release.

block master minimal + lazy conversion + direct deserialization
valid: unknown witness version, 2M one-byte items 99 169 (+70) 108 76
invalid: P2WPKH with 2M one-byte items 99 169 (+70) 108 77
valid: unknown tapleaf version, 2M one-byte items 99 151 (+52) 151 70
invalid: P2WSH script mismatch, 2M one-byte items 99 147 (+48) 147 66
invalid: P2WSH script mismatch, 4M empty items 249 293 (+44) 294 59
invalid: P2WSH with 4M empty items (master's slowest) 307 296 (−11) 294 61
valid: 5,169 P2WSH spends of 403 items 22.2 23.3 (+1.1) 23.4 21.8
@instagibbs FWIW, these are the benchmarks I based this on. "minimal" is this PR. The "lazy conversion" and "direction deserialization" are follow-up optimizations not included in this PR. Hardware is a high-end Zen5 machine. --- Each row is one 4M WU block, timed over deserialize, `CheckBlock` and `ConnectBlock`, in ms. These are medians of 11 interleaved rounds on the now-idle machine, gcc Release. | block | master | minimal | + lazy conversion | + direct deserialization | |---|--:|--:|--:|--:| | valid: unknown witness version, 2M one-byte items | 99 | 169 (+70) | 108 | 76 | | invalid: P2WPKH with 2M one-byte items | 99 | 169 (+70) | 108 | 77 | | valid: unknown tapleaf version, 2M one-byte items | 99 | 151 (+52) | 151 | 70 | | invalid: P2WSH script mismatch, 2M one-byte items | 99 | 147 (+48) | 147 | 66 | | invalid: P2WSH script mismatch, 4M empty items | 249 | 293 (+44) | 294 | 59 | | invalid: P2WSH with 4M empty items (master's slowest) | 307 | 296 (−11) | 294 | 61 | | valid: 5,169 P2WSH spends of 403 items | 22.2 | 23.3 (+1.1) | 23.4 | 21.8 |
optout21 (Migrated from github.com) reviewed 2026-11-19 12:14:15 +00:00
optout21 (Migrated from github.com) left a comment

crACK a6a4df2770

This change reduces the memory usage of CScriptWitness. Instead of the parsed representation it stores the serialized version. Memory footprint is reduced especially for empty witnesses, or for empty or small witness elements. Considering that the parsing is relatively low complexity, and the usage pattern, the tradeoff seems to be worth it.

Instead of storing a byte vector (with a footprint of 3 values, 24 bytes on 64-bit systems) it pushes the optimization further: it stores a byte pointer, no allocated size / capacity, and the length in 4 bytes inside the data buffer. The memory needed for the fields is thus 8 bytes inline plus 4 extra bytes on the heap, but only for non-empty witnesses.

The commits are granular and well structured (nice usage of scripted diffs for usage switch).

Two minor issues left as comments. No other issues found.

An alternative considered: Store the length as a separate field, not part of the buffer. The advantages would be: simpler access to the serialized form, and no header read on each access. However, the memory usage improvement -- the biggest win of this PR -- would take a hit (8 extra bytes for every witness, including empty ones; CTxIn size from 96 to 104).

A note on the range of counts and lengths: uint64_t ReadCompactSize() is implicitly converted to size_t in a few places. This is fine: ReadCompactSize rejects values above MAX_SIZE (2^25), so anything it returns fits in 26 bits. For deserialized witnesses this always holds; for witnesses built from vectors it holds in practice. It's worth mentioning that it's possible to construct an artificially large witness with an element larger than MAX_SIZE. In this case std::terminate would be hit on first access, since the accessors are noexcept. That's not reachable from the network, but checking MAX_SIZE in the constructor would make the invariant hold by construction.

Further (followup) ideas:

  • I wonder if this "light read-only byte vector" construct would be worthwhile to be separated on its own into utils.

  • A potential optimization: Since the class wrote the serialization itself, lengths can be decoded without ReadCompactSize's internal checks, with a fast path for one-byte lengths. This also removes the terminate case above, as decoding can no longer throw. In addition, operator[] can read the header and the element count only once instead of twice. In a quick micro-benchmark this made iteration, back() and [] on a typical 3-element witness about 5× faster, and 1.4–2× faster for 10k one-byte elements; see branch pr36895-oo-optim1.

crACK a6a4df2770eb5f79f4e2dc58dee12889ca0be700 This change reduces the memory usage of `CScriptWitness`. Instead of the parsed representation it stores the serialized version. Memory footprint is reduced especially for empty witnesses, or for empty or small witness elements. Considering that the parsing is relatively low complexity, and the usage pattern, the tradeoff seems to be worth it. Instead of storing a byte vector (with a footprint of 3 values, 24 bytes on 64-bit systems) it pushes the optimization further: it stores a byte pointer, no allocated size / capacity, and the length in 4 bytes inside the data buffer. The memory needed for the fields is thus 8 bytes inline plus 4 extra bytes on the heap, but only for non-empty witnesses. The commits are granular and well structured (nice usage of scripted diffs for usage switch). Two minor issues left as comments. No other issues found. An alternative considered: Store the length as a separate field, not part of the buffer. The advantages would be: simpler access to the serialized form, and no header read on each access. However, the memory usage improvement -- the biggest win of this PR -- would take a hit (8 extra bytes for every witness, including empty ones; `CTxIn` size from 96 to 104). A note on the range of counts and lengths: `uint64_t ReadCompactSize()` is implicitly converted to `size_t` in a few places. This is fine: `ReadCompactSize` rejects values above `MAX_SIZE` (2^25), so anything it returns fits in 26 bits. For deserialized witnesses this always holds; for witnesses built from vectors it holds in practice. It's worth mentioning that it's possible to construct an artificially large witness with an element larger than `MAX_SIZE`. In this case `std::terminate` would be hit on first access, since the accessors are noexcept. That's not reachable from the network, but checking `MAX_SIZE` in the constructor would make the invariant hold by construction. Further (followup) ideas: - I wonder if this "light read-only byte vector" construct would be worthwhile to be separated on its own into utils. - A potential optimization: Since the class wrote the serialization itself, lengths can be decoded without `ReadCompactSize`'s internal checks, with a fast path for one-byte lengths. This also removes the terminate case above, as decoding can no longer throw. In addition, `operator[]` can read the header and the element count only once instead of twice. In a quick micro-benchmark this made iteration, `back()` and `[]` on a typical 3-element witness about 5× faster, and 1.4–2× faster for 10k one-byte elements; see [branch pr36895-oo-optim1](https://github.com/optout21/bitcoin/tree/pr36895-oo-optim1).
Lines 316-323
optout21 (Migrated from github.com) commented 2026-11-19 12:01:52 +00:00

0a82e05 refactor: use CScriptWitness's interface where that needs more than a rename:

Minor: Here back() is called, then ToSpans(). If the MAX_STANDARD_P2WSH_SCRIPT_SIZE check was moved after ToSpans(), the back() call could be avoided (back is potentially expensive).

> [0a82e05](https://github.com/bitcoin/bitcoin/pull/36895/changes/0a82e05e34b920c7400f945a830b120f99a7e9d8) _refactor: use CScriptWitness's interface where that needs more than a rename_: Minor: Here `back()` is called, then `ToSpans()`. If the `MAX_STANDARD_P2WSH_SCRIPT_SIZE` check was moved after `ToSpans()`, the `back()` call could be avoided (`back` is potentially expensive).
Lines 306-313
optout21 (Migrated from github.com) commented 2026-11-19 10:32:29 +00:00

a6a4df2 script: store witness stacks as their serialization:

Nit: Could be simplified to: (requires #include <util/string.h>)

    return "CScriptWitness(" + util::Join(*this, ", ", [](auto element) { return HexStr(element); }) + ")";
> [a6a4df2](https://github.com/bitcoin/bitcoin/pull/36895/changes/a6a4df2770eb5f79f4e2dc58dee12889ca0be700) _script: store witness stacks as their serialization_: Nit: Could be simplified to: (requires `#include <util/string.h>`) ``` return "CScriptWitness(" + util::Join(*this, ", ", [](auto element) { return HexStr(element); }) + ")"; ```
pzafonte commented 2026-11-19 16:42:08 +00:00 (Migrated from github.com)
  • A potential optimization: Since the class wrote the serialization itself, lengths can be decoded without ReadCompactSize's internal checks, with a fast path for one-byte lengths.

I like this, a natural consequence of this is that it would speed up the kernel.

> * A potential optimization: Since the class wrote the serialization itself, lengths can be decoded without `ReadCompactSize`'s internal checks, with a fast path for one-byte lengths. I like this, a natural consequence of this is that it would speed up the kernel.
instagibbs (Migrated from github.com) approved these changes 2026-11-19 17:02:48 +00:00
instagibbs (Migrated from github.com) left a comment

ACK https://github.com/bitcoin/bitcoin/pull/36895/commits/0c981e75a9e7e352d1c0f08118596ea91a9fa102

Ran quite a few validation passes over worst-case at-rest memory usage for various places like orphanage and other vectors. Does what it says on the tin with no slowdown on average case transaction/block patterns, the biggest exception being single transaction NFT blocks which are a few hundred mics slower due to double copying of the exec_script.

Also, looks like mempool will fit ~13-15% more transactions in it, based on my historical simulations.

This change also doesn't seem make future updates to interface any more difficult, so we're not being boxed in with this bugfix change.

CI failures seem unrelated

ACK https://github.com/bitcoin/bitcoin/pull/36895/commits/0c981e75a9e7e352d1c0f08118596ea91a9fa102 Ran quite a few validation passes over worst-case at-rest memory usage for various places like orphanage and other vectors. Does what it says on the tin with no slowdown on average case transaction/block patterns, the biggest exception being single transaction NFT blocks which are a few hundred mics slower due to double copying of the exec_script. Also, looks like mempool will fit ~13-15% more transactions in it, based on my historical simulations. This change also doesn't seem make future updates to interface any more difficult, so we're not being boxed in with this bugfix change. CI failures seem unrelated
instagibbs (Migrated from github.com) commented 2026-11-19 14:39:03 +00:00

49c0f21971

A couple suggestions for tests here. 3 to 5 compactsize boundary which IIUC is consensus legal in a block, and every way of making an empty witness giving the same object, since HasWitness() and so the witness flag and wtxid depend on it.

diff --git a/src/test/script_tests.cpp b/src/test/script_tests.cpp
index cc6fa3843a..3b46f468d4 100644
--- a/src/test/script_tests.cpp
+++ b/src/test/script_tests.cpp
@@ -1774,26 +1774,110 @@ BOOST_AUTO_TEST_CASE(script_witness_representation)
             if (!stack.empty()) BOOST_CHECK(std::ranges::equal(deser.back(), stack.back()));
 
             // Moving leaves the source empty.
             CScriptWitness moved{std::move(deser)};
             BOOST_CHECK(moved == witness);
             BOOST_CHECK(deser.empty() && deser.size() == 0 && deser.begin() == deser.end()); // NOLINT(bugprone-use-after-move)
 
             // Copy and move assignment replace the stack that was there.
             CScriptWitness copy{witness};
             CScriptWitness assigned{{{0xff}}};
             assigned = copy;
             copy = {};
             BOOST_CHECK(copy.empty());
             BOOST_CHECK(copy.begin() == copy.end());
             BOOST_CHECK(assigned == witness);
 
             CScriptWitness move_assigned{{{0xff}}};
             move_assigned = std::move(assigned);
             BOOST_CHECK(move_assigned == witness);
             BOOST_CHECK(assigned.empty() && assigned.begin() == assigned.end()); // NOLINT(bugprone-use-after-move)
             if (!stack.empty()) BOOST_CHECK(std::ranges::equal(move_assigned.back(), stack.back()));
         }
     }
 }
 
+BOOST_AUTO_TEST_CASE(script_witness_large_count)
+{
+    // Element counts on both sides of the boundary between the 3-byte and 5-byte CompactSize encodings. Elements are
+    // small, and only a few are accessed by index, as indexing may take time linear in the index.
+    for (const size_t count : {size_t{0xffff}, size_t{0x10000}}) {
+        std::vector<std::vector<unsigned char>> stack(count);
+        for (auto& element : stack) element = m_rng.randbytes(m_rng.randrange(3));
+        const CScriptWitness witness{stack};
+
+        BOOST_CHECK_EQUAL(witness.size(), count);
+        BOOST_CHECK_EQUAL(std::distance(witness.begin(), witness.end()), (std::ptrdiff_t)count);
+        BOOST_CHECK(witness.ToVectors() == stack);
+        BOOST_CHECK(std::ranges::equal(witness.front(), stack.front()));
+        BOOST_CHECK(std::ranges::equal(witness.back(), stack.back()));
+        for (const size_t i : {size_t{1}, count / 2, count - 2}) BOOST_CHECK(std::ranges::equal(witness[i], stack[i]));
+
+        std::vector<unsigned char> ser_vec, ser_wit;
+        VectorWriter{ser_vec, 0, stack};
+        VectorWriter{ser_wit, 0, witness};
+        BOOST_CHECK(ser_vec == ser_wit);
+        // The count is encoded as 0xfd followed by 2 bytes, or 0xfe followed by 4.
+        BOOST_CHECK_EQUAL(int{ser_wit.at(0)}, count <= 0xffff ? 0xfd : 0xfe);
+        CScriptWitness deser;
+        SpanReader{ser_vec} >> deser;
+        BOOST_CHECK(deser == witness);
+        BOOST_CHECK_EQUAL(deser.size(), count);
+        BOOST_CHECK(std::ranges::equal(deser.back(), stack.back()));
+    }
+}
+
+BOOST_AUTO_TEST_CASE(script_witness_empty)
+{
+    // Every way of producing a witness without elements gives the same witness. A transaction is serialized with
+    // witness data exactly when one of its inputs has a non-empty witness, so this determines its wtxid and whether its
+    // serialization round-trips.
+    using Stack = std::vector<std::vector<unsigned char>>;
+    const std::vector<unsigned char> ser_empty{0x00};
+    const CScriptWitness from_default;
+    const CScriptWitness from_vector{Stack{}};
+    CScriptWitness from_deser{{{0x01}}};
+    SpanReader{ser_empty} >> from_deser;
+    CScriptWitness moved_from{{{0x01}}};
+    const CScriptWitness moved_to{std::move(moved_from)};
+    BOOST_CHECK_EQUAL(moved_to.size(), 1U);
+    CScriptWitness reset{{{0x01}}};
+    reset = {};
+    const CScriptWitness copied{from_default};
+    CScriptWitness copy_assigned{{{0x01}}};
+    copy_assigned = from_default;
+
+    const std::vector<const CScriptWitness*> empties{&from_default, &from_vector, &from_deser, &moved_from, &reset, &copied, &copy_assigned}; // NOLINT(bugprone-use-after-move)
+    for (const CScriptWitness* witness : empties) {
+        BOOST_CHECK(witness->empty());
+        BOOST_CHECK_EQUAL(witness->size(), 0U);
+        BOOST_CHECK(witness->begin() == witness->end());
+        BOOST_CHECK(witness->ToVectors().empty());
+        BOOST_CHECK(*witness == from_default);
+        std::vector<unsigned char> ser;
+        VectorWriter{ser, 0, *witness};
+        BOOST_CHECK(ser == ser_empty);
+        CMutableTransaction tx;
+        tx.vin.resize(1);
+        tx.vin[0].scriptWitness = *witness;
+        BOOST_CHECK(!tx.HasWitness());
+    }
+
+    // A single empty element is a different stack.
+    const CScriptWitness one_empty{Stack(1)};
+    BOOST_CHECK(!one_empty.empty());
+    BOOST_CHECK_EQUAL(one_empty.size(), 1U);
+    BOOST_CHECK(one_empty.back().empty());
+    BOOST_CHECK(one_empty != from_default);
+    std::vector<unsigned char> ser;
+    VectorWriter{ser, 0, one_empty};
+    BOOST_CHECK(ser == (std::vector<unsigned char>{0x01, 0x00}));
+    CScriptWitness deser;
+    SpanReader{ser} >> deser;
+    BOOST_CHECK(deser == one_empty);
+    CMutableTransaction tx;
+    tx.vin.resize(1);
+    tx.vin[0].scriptWitness = one_empty;
+    BOOST_CHECK(tx.HasWitness());
+}
+
 BOOST_AUTO_TEST_SUITE_END()
49c0f21971050b24cecde56bdb42653af3910fc6 A couple suggestions for tests here. 3 to 5 compactsize boundary which IIUC is consensus legal in a block, and every way of making an empty witness giving the same object, since HasWitness() and so the witness flag and wtxid depend on it. ``` diff --git a/src/test/script_tests.cpp b/src/test/script_tests.cpp index cc6fa3843a..3b46f468d4 100644 --- a/src/test/script_tests.cpp +++ b/src/test/script_tests.cpp @@ -1774,26 +1774,110 @@ BOOST_AUTO_TEST_CASE(script_witness_representation) if (!stack.empty()) BOOST_CHECK(std::ranges::equal(deser.back(), stack.back())); // Moving leaves the source empty. CScriptWitness moved{std::move(deser)}; BOOST_CHECK(moved == witness); BOOST_CHECK(deser.empty() && deser.size() == 0 && deser.begin() == deser.end()); // NOLINT(bugprone-use-after-move) // Copy and move assignment replace the stack that was there. CScriptWitness copy{witness}; CScriptWitness assigned{{{0xff}}}; assigned = copy; copy = {}; BOOST_CHECK(copy.empty()); BOOST_CHECK(copy.begin() == copy.end()); BOOST_CHECK(assigned == witness); CScriptWitness move_assigned{{{0xff}}}; move_assigned = std::move(assigned); BOOST_CHECK(move_assigned == witness); BOOST_CHECK(assigned.empty() && assigned.begin() == assigned.end()); // NOLINT(bugprone-use-after-move) if (!stack.empty()) BOOST_CHECK(std::ranges::equal(move_assigned.back(), stack.back())); } } } +BOOST_AUTO_TEST_CASE(script_witness_large_count) +{ + // Element counts on both sides of the boundary between the 3-byte and 5-byte CompactSize encodings. Elements are + // small, and only a few are accessed by index, as indexing may take time linear in the index. + for (const size_t count : {size_t{0xffff}, size_t{0x10000}}) { + std::vector<std::vector<unsigned char>> stack(count); + for (auto& element : stack) element = m_rng.randbytes(m_rng.randrange(3)); + const CScriptWitness witness{stack}; + + BOOST_CHECK_EQUAL(witness.size(), count); + BOOST_CHECK_EQUAL(std::distance(witness.begin(), witness.end()), (std::ptrdiff_t)count); + BOOST_CHECK(witness.ToVectors() == stack); + BOOST_CHECK(std::ranges::equal(witness.front(), stack.front())); + BOOST_CHECK(std::ranges::equal(witness.back(), stack.back())); + for (const size_t i : {size_t{1}, count / 2, count - 2}) BOOST_CHECK(std::ranges::equal(witness[i], stack[i])); + + std::vector<unsigned char> ser_vec, ser_wit; + VectorWriter{ser_vec, 0, stack}; + VectorWriter{ser_wit, 0, witness}; + BOOST_CHECK(ser_vec == ser_wit); + // The count is encoded as 0xfd followed by 2 bytes, or 0xfe followed by 4. + BOOST_CHECK_EQUAL(int{ser_wit.at(0)}, count <= 0xffff ? 0xfd : 0xfe); + CScriptWitness deser; + SpanReader{ser_vec} >> deser; + BOOST_CHECK(deser == witness); + BOOST_CHECK_EQUAL(deser.size(), count); + BOOST_CHECK(std::ranges::equal(deser.back(), stack.back())); + } +} + +BOOST_AUTO_TEST_CASE(script_witness_empty) +{ + // Every way of producing a witness without elements gives the same witness. A transaction is serialized with + // witness data exactly when one of its inputs has a non-empty witness, so this determines its wtxid and whether its + // serialization round-trips. + using Stack = std::vector<std::vector<unsigned char>>; + const std::vector<unsigned char> ser_empty{0x00}; + const CScriptWitness from_default; + const CScriptWitness from_vector{Stack{}}; + CScriptWitness from_deser{{{0x01}}}; + SpanReader{ser_empty} >> from_deser; + CScriptWitness moved_from{{{0x01}}}; + const CScriptWitness moved_to{std::move(moved_from)}; + BOOST_CHECK_EQUAL(moved_to.size(), 1U); + CScriptWitness reset{{{0x01}}}; + reset = {}; + const CScriptWitness copied{from_default}; + CScriptWitness copy_assigned{{{0x01}}}; + copy_assigned = from_default; + + const std::vector<const CScriptWitness*> empties{&from_default, &from_vector, &from_deser, &moved_from, &reset, &copied, &copy_assigned}; // NOLINT(bugprone-use-after-move) + for (const CScriptWitness* witness : empties) { + BOOST_CHECK(witness->empty()); + BOOST_CHECK_EQUAL(witness->size(), 0U); + BOOST_CHECK(witness->begin() == witness->end()); + BOOST_CHECK(witness->ToVectors().empty()); + BOOST_CHECK(*witness == from_default); + std::vector<unsigned char> ser; + VectorWriter{ser, 0, *witness}; + BOOST_CHECK(ser == ser_empty); + CMutableTransaction tx; + tx.vin.resize(1); + tx.vin[0].scriptWitness = *witness; + BOOST_CHECK(!tx.HasWitness()); + } + + // A single empty element is a different stack. + const CScriptWitness one_empty{Stack(1)}; + BOOST_CHECK(!one_empty.empty()); + BOOST_CHECK_EQUAL(one_empty.size(), 1U); + BOOST_CHECK(one_empty.back().empty()); + BOOST_CHECK(one_empty != from_default); + std::vector<unsigned char> ser; + VectorWriter{ser, 0, one_empty}; + BOOST_CHECK(ser == (std::vector<unsigned char>{0x01, 0x00})); + CScriptWitness deser; + SpanReader{ser} >> deser; + BOOST_CHECK(deser == one_empty); + CMutableTransaction tx; + tx.vin.resize(1); + tx.vin[0].scriptWitness = one_empty; + BOOST_CHECK(tx.HasWitness()); +} + BOOST_AUTO_TEST_SUITE_END() ```
sipa (Migrated from github.com) reviewed 2026-11-19 18:29:11 +00:00
Lines 306-313
sipa (Migrated from github.com) commented 2026-11-19 18:29:11 +00:00

Done.

Done.
sipa commented 2026-11-19 18:31:00 +00:00 (Migrated from github.com)

@optout21 I had a series of several optimizations in my old PR #36521, some of which do similar things to what you suggest. I've opened a draft PR #36918 with those optimization to avoid duplicate work.

This PR is deliberately avoiding performance optimizations, to focus review on the more important issue of memory usage.


An alternative considered: Store the length as a separate field, not part of the buffer. The advantages would be: simpler access to the serialized form, and no header read on each access. However, the memory usage improvement -- the biggest win of this PR -- would take a hit (8 extra bytes for every witness, including empty ones; CTxIn size from 96 to 104).

I'd rather not do that. Memory usage is the priority here I think. In the follow-up PR the header is also expanded with the position of the last element, so that CScriptWitness::back() runs is \mathcal{O}(1) time.

In this case std::terminate would be hit on first access, since the accessors are noexcept. That's not reachable from the network, but checking MAX_SIZE in the constructor would make the invariant hold by construction.

The follow-up uses an optimized decoder that never throws (but relies on the fact that the bytes are self-encoded and thus guaranteed to be correct).

I wonder if this "light read-only byte vector" construct would be worthwhile to be separated on its own into utils.

If there is a second use case for it, that seems reasonable, but I'm not sure where that'd be.

Since the class wrote the serialization itself, lengths can be decoded without ReadCompactSize's internal checks, with a fast path for one-byte lengths.

I believe the old PR already had that; it's in the follow-up PR now.

@optout21 I had a series of several optimizations in my old PR #36521, some of which do similar things to what you suggest. I've opened a draft PR #36918 with those optimization to avoid duplicate work. This PR is deliberately avoiding performance optimizations, to focus review on the more important issue of memory usage. --- > An alternative considered: Store the length as a separate field, not part of the buffer. The advantages would be: simpler access to the serialized form, and no header read on each access. However, the memory usage improvement -- the biggest win of this PR -- would take a hit (8 extra bytes for every witness, including empty ones; CTxIn size from 96 to 104). I'd rather not do that. Memory usage is the priority here I think. In the follow-up PR the header is also expanded with the position of the last element, so that `CScriptWitness::back()` runs is $\mathcal{O}(1)$ time. > In this case std::terminate would be hit on first access, since the accessors are noexcept. That's not reachable from the network, but checking MAX_SIZE in the constructor would make the invariant hold by construction. The follow-up uses an optimized decoder that never throws (but relies on the fact that the bytes are self-encoded and thus guaranteed to be correct). > I wonder if this "light read-only byte vector" construct would be worthwhile to be separated on its own into utils. If there is a second use case for it, that seems reasonable, but I'm not sure where that'd be. > Since the class wrote the serialization itself, lengths can be decoded without ReadCompactSize's internal checks, with a fast path for one-byte lengths. I believe the old PR already had that; it's in the follow-up PR now.
sipa (Migrated from github.com) reviewed 2026-11-19 18:37:00 +00:00
Lines 316-323
sipa (Migrated from github.com) commented 2026-11-19 18:37:00 +00:00

#36918 instead has a lazy creation of the stack (and no more ToSpans), which avoids this issue entirely I think.

#36918 instead has a lazy creation of the stack (and no more `ToSpans`), which avoids this issue entirely I think.
optout21 commented 2026-11-19 20:32:26 +00:00 (Migrated from github.com)

reACK 0c981e75a9
Diff review, one minor change applied (ToString(); a6a4df2 -> 0c981e7)

reACK 0c981e75a9e7e352d1c0f08118596ea91a9fa102 Diff review, one minor change applied (ToString(); a6a4df2 -> 0c981e7)
optout21 (Migrated from github.com) reviewed 2026-11-19 20:36:28 +00:00
Lines 316-323
optout21 (Migrated from github.com) commented 2026-11-19 20:36:28 +00:00

OK, I see that it belongs to #36918, thanks. It seems the back() call is still present, but I'm not sure if it's avoidable; I will check there when it's due.

OK, I see that it belongs to #36918, thanks. It seems the `back()` call is still present, but I'm not sure if it's avoidable; I will check there when it's due.
l0rinc (Migrated from github.com) requested changes 2026-11-22 22:40:07 +00:00
l0rinc (Migrated from github.com) left a comment

Concept reACK. Eagerly expanding witnesses into vectors can have considerable memory and CPU costs, leaving them raw is the logical step.

I've left some suggestions inline that I'd still include here, e.g. comparing witnesses as unsigned bytes, inlining a few helpers for simplicity, and extra fuzz and unit coverage. The constructor/accessor mismatch is worth fixing here, since a vector-constructed witness can currently terminate the process when an accessor reads an element above MAX_SIZE.

I’d prefer moving some of the changes into earlier commits and bringing over the relevant simplifications from your optimization followup, so we avoid changing the same lines twice. Personally, I’d rather review those parts once than review two successive implementations.

I also benchmarked a few scenarios, e.g. the usual chainstate reindex, which was about 3% faster on an earlier revision (one run per revision with -assumevalid). Script verification and the later expansion into mutable execution stacks are skipped for eligible blocks, but we still build temporary vectors during deserialization, so we'd need to remeasure this after the optimizations - or bring the deferred vector conversion here. That part doesn't really complicate this change in my opinion.

I was also wondering about splitting the sizes from the contents, while keeping both as byte arrays in the same allocation. The encoded sizes could then be scanned contiguously, without touching the contents until we actually need an item's bytes. Storing the sizes naively would bring some of the memory overhead back. If we used a format whose boundaries can be found from either end (e.g. VARINT), letting us walk backwards through the items (and constant-time back()), e.g. to reach the control block below a Taproot annex. Arbitrary indexing would still be linear, but my benchmarks indicate lookup would be roughly twice as fast. The item count, payload boundary and total length could stay in the allocation header, keeping the witness itself to one pointer.

Storage layout and forward/backward traversal
// One allocation behind the witness's owning pointer:
// [header: item count, payload boundary, total length]
// [item_0 bytes ... item_n bytes][VARINT(size_0) ... VARINT(size_n)]
// These spans are local views of the two sections.
using Item = std::span<const unsigned char>;

Item PopBack(Item& lengths, Item& payload)
{
    // The last byte terminates the VARINT. Preceding continuation bytes belong to it.
    size_t start = lengths.size() - 1;
    while (start && (lengths[start - 1] & 0x80)) --start;
    SpanReader reader{lengths.subspan(start)};
    const auto size = ReadVarInt<SpanReader, VarIntMode::DEFAULT, size_t>(reader);
    const Item item = payload.last(size);
    lengths = lengths.first(start);
    payload = payload.first(payload.size() - size);
    return item;
}

void ForEach(Item lengths, Item payload, auto visit)
{
    SpanReader reader{lengths};
    while (reader.size() > 0) {
        const auto size = ReadVarInt<SpanReader, VarIntMode::DEFAULT, size_t>(reader);
        visit(payload.first(size));
        payload = payload.subspan(size);
    }
}

void ForEachReverse(Item lengths, Item payload, auto visit)
{
    while (lengths.size() > 0) visit(PopBack(lengths, payload));
}

This did make writing the witness back to the wire slower, though, and the cached offset in your optimization followup would still be slightly faster for back() alone.

Concept reACK. Eagerly expanding witnesses into vectors can have considerable memory and CPU costs, leaving them raw is the logical step. I've left some suggestions inline that I'd still include here, e.g. comparing witnesses as unsigned bytes, inlining a few helpers for simplicity, and extra fuzz and unit coverage. The constructor/accessor mismatch is worth fixing here, since a vector-constructed witness can currently terminate the process when an accessor reads an element above `MAX_SIZE`. I’d prefer moving some of the changes into earlier commits and bringing over the relevant simplifications from [your optimization followup](https://github.com/bitcoin/bitcoin/pull/36918), so we avoid changing the same lines twice. Personally, I’d rather review those parts once than review two successive implementations. I also benchmarked a few scenarios, e.g. the usual chainstate reindex, which was about 3% faster on an earlier revision (one run per revision with `-assumevalid`). Script verification and the later expansion into mutable execution stacks are skipped for eligible blocks, but we still build temporary vectors during deserialization, so we'd need to remeasure this after the optimizations - or bring the deferred vector conversion here. That part doesn't really complicate this change in my opinion. I was also wondering about splitting the sizes from the contents, while keeping both as byte arrays in the same allocation. The encoded sizes could then be scanned contiguously, without touching the contents until we actually need an item's bytes. Storing the sizes naively would bring some of the memory overhead back. If we used a format whose boundaries can be found from either end (e.g. `VARINT`), letting us walk backwards through the items (and constant-time `back()`), e.g. to reach the control block below a Taproot annex. Arbitrary indexing would still be linear, but my benchmarks indicate lookup would be roughly twice as fast. The item count, payload boundary and total length could stay in the allocation header, keeping the witness itself to one pointer. <details> <summary>Storage layout and forward/backward traversal</summary> ```cpp // One allocation behind the witness's owning pointer: // [header: item count, payload boundary, total length] // [item_0 bytes ... item_n bytes][VARINT(size_0) ... VARINT(size_n)] // These spans are local views of the two sections. using Item = std::span<const unsigned char>; Item PopBack(Item& lengths, Item& payload) { // The last byte terminates the VARINT. Preceding continuation bytes belong to it. size_t start = lengths.size() - 1; while (start && (lengths[start - 1] & 0x80)) --start; SpanReader reader{lengths.subspan(start)}; const auto size = ReadVarInt<SpanReader, VarIntMode::DEFAULT, size_t>(reader); const Item item = payload.last(size); lengths = lengths.first(start); payload = payload.first(payload.size() - size); return item; } void ForEach(Item lengths, Item payload, auto visit) { SpanReader reader{lengths}; while (reader.size() > 0) { const auto size = ReadVarInt<SpanReader, VarIntMode::DEFAULT, size_t>(reader); visit(payload.first(size)); payload = payload.subspan(size); } } void ForEachReverse(Item lengths, Item payload, auto visit) { while (lengths.size() > 0) visit(PopBack(lengths, payload)); } ``` </details> This did make writing the witness back to the wire slower, though, and the cached offset [in your optimization followup](https://github.com/bitcoin/bitcoin/pull/36918) would still be slightly faster for `back()` alone.
l0rinc (Migrated from github.com) commented 2026-11-22 20:37:45 +00:00

0a82e05 refactor: use CScriptWitness's interface where that needs more than a rename:

Given @instagibbs’s mempool measurements, this seems worth a release note. The same -maxmempool budget can now hold more transactions.

Mention the mempool memory saving
diff --git a/doc/release-notes-36895.md b/doc/release-notes-36895.md
new file mode 100644
index 0000000000..a2d54546cc
--- /dev/null
+++ b/doc/release-notes-36895.md
@@ -0,0 +1,4 @@
+Mempool
+-------
+
+Transactions retained in the mempool use less memory, especially when their witnesses contain many elements. The mempool can therefore retain more transactions within the same `-maxmempool` memory limit. (#36895)
> [0a82e05](https://github.com/bitcoin/bitcoin/pull/36895/changes/0a82e05e34b920c7400f945a830b120f99a7e9d8) _refactor: use CScriptWitness's interface where that needs more than a rename_: Given [@instagibbs’s mempool measurements](https://github.com/bitcoin/bitcoin/pull/36895#pullrequestreview-5977061786), this seems worth a release note. The same `-maxmempool` budget can now hold more transactions. <details> <summary>Mention the mempool memory saving</summary> ```diff diff --git a/doc/release-notes-36895.md b/doc/release-notes-36895.md new file mode 100644 index 0000000000..a2d54546cc --- /dev/null +++ b/doc/release-notes-36895.md @@ -0,0 +1,4 @@ +Mempool +------- + +Transactions retained in the mempool use less memory, especially when their witnesses contain many elements. The mempool can therefore retain more transactions within the same `-maxmempool` memory limit. (#36895) ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-22 21:24:11 +00:00

0c981e7 script: store witness stacks as their serialization:

Swapping the P2WSH item count check ahead of back() avoids the extra walk @optout21 noticed for witnesses that already exceed the item limit.

Check the count before reading the last item
diff --git a/src/policy/policy.cpp b/src/policy/policy.cpp
index 10e765cb8e..2d552b598f 100644
--- a/src/policy/policy.cpp
+++ b/src/policy/policy.cpp
@@ -306,11 +306,11 @@ bool IsWitnessStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs)
 
         // Check P2WSH standard limits
         if (witnessversion == 0 && witnessprogram.size() == WITNESS_V0_SCRIPTHASH_SIZE) {
-            if (tx.vin[i].scriptWitness.back().size() > MAX_STANDARD_P2WSH_SCRIPT_SIZE)
-                return false;
             size_t sizeWitnessStack = tx.vin[i].scriptWitness.size() - 1;
             if (sizeWitnessStack > MAX_STANDARD_P2WSH_STACK_ITEMS)
                 return false;
+            if (tx.vin[i].scriptWitness.back().size() > MAX_STANDARD_P2WSH_SCRIPT_SIZE)
+                return false;
             // The elements as a vector of spans, for indexed access in the loop below.
             const auto witness_stack = tx.vin[i].scriptWitness.ToSpans();
             for (unsigned int j = 0; j < sizeWitnessStack; j++) {
> [0c981e7](https://github.com/bitcoin/bitcoin/pull/36895/changes/0c981e75a9e7e352d1c0f08118596ea91a9fa102) _script: store witness stacks as their serialization_: Swapping the P2WSH item count check ahead of `back()` avoids [the extra walk @optout21 noticed](https://github.com/bitcoin/bitcoin/pull/36895#discussion_r4628395285) for witnesses that already exceed the item limit. <details> <summary>Check the count before reading the last item</summary> ```diff diff --git a/src/policy/policy.cpp b/src/policy/policy.cpp index 10e765cb8e..2d552b598f 100644 --- a/src/policy/policy.cpp +++ b/src/policy/policy.cpp @@ -306,11 +306,11 @@ bool IsWitnessStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs) // Check P2WSH standard limits if (witnessversion == 0 && witnessprogram.size() == WITNESS_V0_SCRIPTHASH_SIZE) { - if (tx.vin[i].scriptWitness.back().size() > MAX_STANDARD_P2WSH_SCRIPT_SIZE) - return false; size_t sizeWitnessStack = tx.vin[i].scriptWitness.size() - 1; if (sizeWitnessStack > MAX_STANDARD_P2WSH_STACK_ITEMS) return false; + if (tx.vin[i].scriptWitness.back().size() > MAX_STANDARD_P2WSH_SCRIPT_SIZE) + return false; // The elements as a vector of spans, for indexed access in the loop below. const auto witness_stack = tx.vin[i].scriptWitness.ToSpans(); for (unsigned int j = 0; j < sizeWitnessStack; j++) { ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-22 22:32:35 +00:00

0c981e7 script: store witness stacks as their serialization:

WitnessSigOps() and the BIP352 annex check both call back() twice (which seems related to @optout21’s observation), so keeping that span would avoid doing the same lookup again. The benefit would be smaller with your optimization followup, where back() would become constant time, or my suggestion, where back would already have constant time access.

Bind back() once in WitnessSigOps and GetPubKeyFromInput
diff --git a/src/common/bip352.cpp b/src/common/bip352.cpp
index c119613fc6..667110faa6 100644
--- a/src/common/bip352.cpp
+++ b/src/common/bip352.cpp
@@ -149,7 +149,8 @@ std::optional<PubKey> GetPubKeyFromInput(const CTxIn& txin, const CScript& spk)
     if (type == TxoutType::WITNESS_V1_TAPROOT) {
         const auto& stack = txin.scriptWitness;
         if (stack.empty()) return std::nullopt;
-        const bool has_annex = !stack.back().empty() && stack.back()[0] == ANNEX_TAG;
+        const auto last = stack.back();
+        const bool has_annex = last.size() > 0 && last[0] == ANNEX_TAG;
         const size_t effective_size = stack.size() - (has_annex ? 1 : 0);
 
         if (effective_size > 1) {
diff --git a/src/script/interpreter.cpp b/src/script/interpreter.cpp
index 591f06b5f6..6cc4e2c7c9 100644
--- a/src/script/interpreter.cpp
+++ b/src/script/interpreter.cpp
@@ -2142,7 +2142,8 @@ size_t static WitnessSigOps(int witversion, const std::vector<unsigned char>& wi
             return 1;
 
         if (witprogram.size() == WITNESS_V0_SCRIPTHASH_SIZE && witness.size() > 0) {
-            CScript subscript(witness.back().begin(), witness.back().end());
+            const auto script = witness.back();
+            CScript subscript(script.begin(), script.end());
             return subscript.GetSigOpCount(true);
         }
     }
> [0c981e7](https://github.com/bitcoin/bitcoin/pull/36895/changes/0c981e75a9e7e352d1c0f08118596ea91a9fa102) _script: store witness stacks as their serialization_: `WitnessSigOps()` and the BIP352 annex check both call `back()` twice (which seems related to [@optout21’s observation](https://github.com/bitcoin/bitcoin/pull/36895#discussion_r4628395285)), so keeping that span would avoid doing the same lookup again. The benefit would be smaller with [your optimization followup](https://github.com/bitcoin/bitcoin/pull/36918), where `back()` would become constant time, or my suggestion, where `back` would already have constant time access. <details> <summary>Bind back() once in WitnessSigOps and GetPubKeyFromInput</summary> ```diff diff --git a/src/common/bip352.cpp b/src/common/bip352.cpp index c119613fc6..667110faa6 100644 --- a/src/common/bip352.cpp +++ b/src/common/bip352.cpp @@ -149,7 +149,8 @@ std::optional<PubKey> GetPubKeyFromInput(const CTxIn& txin, const CScript& spk) if (type == TxoutType::WITNESS_V1_TAPROOT) { const auto& stack = txin.scriptWitness; if (stack.empty()) return std::nullopt; - const bool has_annex = !stack.back().empty() && stack.back()[0] == ANNEX_TAG; + const auto last = stack.back(); + const bool has_annex = last.size() > 0 && last[0] == ANNEX_TAG; const size_t effective_size = stack.size() - (has_annex ? 1 : 0); if (effective_size > 1) { diff --git a/src/script/interpreter.cpp b/src/script/interpreter.cpp index 591f06b5f6..6cc4e2c7c9 100644 --- a/src/script/interpreter.cpp +++ b/src/script/interpreter.cpp @@ -2142,7 +2142,8 @@ size_t static WitnessSigOps(int witversion, const std::vector<unsigned char>& wi return 1; if (witprogram.size() == WITNESS_V0_SCRIPTHASH_SIZE && witness.size() > 0) { - CScript subscript(witness.back().begin(), witness.back().end()); + const auto script = witness.back(); + CScript subscript(script.begin(), script.end()); return subscript.GetSigOpCount(true); } } ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-22 20:37:31 +00:00

0c981e7 script: store witness stacks as their serialization:

Splitting out the interface and caller changes makes the review much easier to follow. A few more pieces could move earlier to avoid changing them twice.

  • In the interface commit, switch RecursiveDynamicUsage(const CTxIn&) to the CScriptWitness::DynamicMemoryUsage() helper already added there.
  • In the interface commit, define front() as *begin() and back() as (*this)[size() - 1]. The same iterators already work for ToVectors(), the new ToString() and, if we keep it, ToSpans().
  • Test how ToString() formats empty elements in the commit that adds the witness tests.
Changes to fold in by the end of the interface commit
diff --git a/src/core_memusage.h b/src/core_memusage.h
index e96cd734ea..f199a033fb 100644
--- a/src/core_memusage.h
+++ b/src/core_memusage.h
@@ -19,9 +19,6 @@ static inline size_t RecursiveDynamicUsage(const COutPoint& out) {
 
 static inline size_t RecursiveDynamicUsage(const CTxIn& in) {
-    size_t mem = RecursiveDynamicUsage(in.scriptSig) + RecursiveDynamicUsage(in.prevout) + memusage::DynamicUsage(in.scriptWitness.stack);
-    for (std::vector<std::vector<unsigned char> >::const_iterator it = in.scriptWitness.stack.begin(); it != in.scriptWitness.stack.end(); it++) {
-         mem += memusage::DynamicUsage(*it);
-    }
-    return mem;
+    // The witness accounts for the memory of all its elements.
+    return RecursiveDynamicUsage(in.scriptSig) + RecursiveDynamicUsage(in.prevout) + in.scriptWitness.DynamicMemoryUsage();
 }
 
diff --git a/src/script/script.cpp b/src/script/script.cpp
index 447d1d4b18..2b18bbf2ac 100644
--- a/src/script/script.cpp
+++ b/src/script/script.cpp
@@ -12,4 +12,5 @@
 #include <uint256.h>
 #include <util/hash_type.h>
+#include <util/string.h>
 
 #include <compare>
@@ -289,12 +290,21 @@ bool CScript::IsPushOnly() const
 std::string CScriptWitness::ToString() const
 {
-    std::string ret = "CScriptWitness(";
-    for (unsigned int i = 0; i < stack.size(); i++) {
-        if (i) {
-            ret += ", ";
-        }
-        ret += HexStr(stack[i]);
-    }
-    return ret + ")";
+    return "CScriptWitness(" + util::Join(*this, ", ", [](auto element) { return HexStr(element); }) + ")";
+}
+
+std::vector<std::vector<unsigned char>> CScriptWitness::ToVectors() const
+{
+    std::vector<std::vector<unsigned char>> ret;
+    ret.reserve(size());
+    for (const auto element : *this) ret.emplace_back(element.begin(), element.end());
+    return ret;
+}
+
+std::vector<std::span<const unsigned char>> CScriptWitness::ToSpans() const
+{
+    std::vector<std::span<const unsigned char>> ret;
+    ret.reserve(size());
+    for (const auto element : *this) ret.push_back(element);
+    return ret;
 }
 
diff --git a/src/script/script.h b/src/script/script.h
index 19c95824b6..a7c862fcb3 100644
--- a/src/script/script.h
+++ b/src/script/script.h
@@ -628,7 +628,7 @@ struct CScriptWitness
     Iterator end() const noexcept LIFETIMEBOUND { return Iterator{stack.end()}; }
     /** The first (bottom) element. The stack must not be empty. */
-    std::span<const unsigned char> front() const noexcept LIFETIMEBOUND { return stack.front(); }
+    std::span<const unsigned char> front() const noexcept LIFETIMEBOUND { return *begin(); }
     /** The last (top) element. The stack must not be empty. */
-    std::span<const unsigned char> back() const noexcept LIFETIMEBOUND { return stack.back(); }
+    std::span<const unsigned char> back() const noexcept LIFETIMEBOUND { return (*this)[size() - 1]; }
     /** The element at a given index (from the bottom), which must exist. */
     std::span<const unsigned char> operator[](size_t index) const noexcept LIFETIMEBOUND
@@ -640,8 +640,8 @@ struct CScriptWitness
     /** The elements, bottom to top, as vectors. For code that needs to modify or take ownership of them (e.g. to
      *  execute a script with them as its initial stack). */
-    std::vector<std::vector<unsigned char>> ToVectors() const { return stack; }
+    std::vector<std::vector<unsigned char>> ToVectors() const;
     /** Spans of the elements, bottom to top, which are valid as long as this witness is. For code that accesses many
      *  elements by index, as indexing a witness need not be constant-time. */
-    std::vector<std::span<const unsigned char>> ToSpans() const LIFETIMEBOUND { return {begin(), end()}; }
+    std::vector<std::span<const unsigned char>> ToSpans() const LIFETIMEBOUND;
 
     /** The dynamic memory usage of the stack, including that of its elements. */
Formatting cases for the witness tests
diff --git a/src/test/script_tests.cpp b/src/test/script_tests.cpp
index 9afeed3759..ac3c5e15d0 100644
--- a/src/test/script_tests.cpp
+++ b/src/test/script_tests.cpp
@@ -1739,2 +1739,7 @@ BOOST_AUTO_TEST_CASE(script_witness_representation)
 {
+    BOOST_CHECK_EQUAL(CScriptWitness{}.ToString(), "CScriptWitness()");
+    BOOST_CHECK_EQUAL(CScriptWitness{{{0xaa}}}.ToString(), "CScriptWitness(aa)");
+    const CScriptWitness with_empty{{{}, {0xbb, 0xcc}, {}}};
+    BOOST_CHECK_EQUAL(with_empty.ToString(), "CScriptWitness(, bbcc, )");
+
     // Element counts and sizes around CompactSize encoding boundaries.
> [0c981e7](https://github.com/bitcoin/bitcoin/pull/36895/changes/0c981e75a9e7e352d1c0f08118596ea91a9fa102) _script: store witness stacks as their serialization_: Splitting out [the interface and caller changes](https://github.com/bitcoin/bitcoin/pull/36521#pullrequestreview-5871920324) makes the review much easier to follow. A few more pieces could move earlier to avoid changing them twice. - In the interface commit, switch `RecursiveDynamicUsage(const CTxIn&)` to the `CScriptWitness::DynamicMemoryUsage()` helper already added there. - In the interface commit, define `front()` as `*begin()` and `back()` as `(*this)[size() - 1]`. The same iterators already work for `ToVectors()`, [the new `ToString()`](https://github.com/bitcoin/bitcoin/pull/36895#discussion_r4633256652) and, if we keep it, `ToSpans()`. - Test how `ToString()` formats empty elements in the commit that adds the witness tests. <details> <summary>Changes to fold in by the end of the interface commit</summary> ```diff diff --git a/src/core_memusage.h b/src/core_memusage.h index e96cd734ea..f199a033fb 100644 --- a/src/core_memusage.h +++ b/src/core_memusage.h @@ -19,9 +19,6 @@ static inline size_t RecursiveDynamicUsage(const COutPoint& out) { static inline size_t RecursiveDynamicUsage(const CTxIn& in) { - size_t mem = RecursiveDynamicUsage(in.scriptSig) + RecursiveDynamicUsage(in.prevout) + memusage::DynamicUsage(in.scriptWitness.stack); - for (std::vector<std::vector<unsigned char> >::const_iterator it = in.scriptWitness.stack.begin(); it != in.scriptWitness.stack.end(); it++) { - mem += memusage::DynamicUsage(*it); - } - return mem; + // The witness accounts for the memory of all its elements. + return RecursiveDynamicUsage(in.scriptSig) + RecursiveDynamicUsage(in.prevout) + in.scriptWitness.DynamicMemoryUsage(); } diff --git a/src/script/script.cpp b/src/script/script.cpp index 447d1d4b18..2b18bbf2ac 100644 --- a/src/script/script.cpp +++ b/src/script/script.cpp @@ -12,4 +12,5 @@ #include <uint256.h> #include <util/hash_type.h> +#include <util/string.h> #include <compare> @@ -289,12 +290,21 @@ bool CScript::IsPushOnly() const std::string CScriptWitness::ToString() const { - std::string ret = "CScriptWitness("; - for (unsigned int i = 0; i < stack.size(); i++) { - if (i) { - ret += ", "; - } - ret += HexStr(stack[i]); - } - return ret + ")"; + return "CScriptWitness(" + util::Join(*this, ", ", [](auto element) { return HexStr(element); }) + ")"; +} + +std::vector<std::vector<unsigned char>> CScriptWitness::ToVectors() const +{ + std::vector<std::vector<unsigned char>> ret; + ret.reserve(size()); + for (const auto element : *this) ret.emplace_back(element.begin(), element.end()); + return ret; +} + +std::vector<std::span<const unsigned char>> CScriptWitness::ToSpans() const +{ + std::vector<std::span<const unsigned char>> ret; + ret.reserve(size()); + for (const auto element : *this) ret.push_back(element); + return ret; } diff --git a/src/script/script.h b/src/script/script.h index 19c95824b6..a7c862fcb3 100644 --- a/src/script/script.h +++ b/src/script/script.h @@ -628,7 +628,7 @@ struct CScriptWitness Iterator end() const noexcept LIFETIMEBOUND { return Iterator{stack.end()}; } /** The first (bottom) element. The stack must not be empty. */ - std::span<const unsigned char> front() const noexcept LIFETIMEBOUND { return stack.front(); } + std::span<const unsigned char> front() const noexcept LIFETIMEBOUND { return *begin(); } /** The last (top) element. The stack must not be empty. */ - std::span<const unsigned char> back() const noexcept LIFETIMEBOUND { return stack.back(); } + std::span<const unsigned char> back() const noexcept LIFETIMEBOUND { return (*this)[size() - 1]; } /** The element at a given index (from the bottom), which must exist. */ std::span<const unsigned char> operator[](size_t index) const noexcept LIFETIMEBOUND @@ -640,8 +640,8 @@ struct CScriptWitness /** The elements, bottom to top, as vectors. For code that needs to modify or take ownership of them (e.g. to * execute a script with them as its initial stack). */ - std::vector<std::vector<unsigned char>> ToVectors() const { return stack; } + std::vector<std::vector<unsigned char>> ToVectors() const; /** Spans of the elements, bottom to top, which are valid as long as this witness is. For code that accesses many * elements by index, as indexing a witness need not be constant-time. */ - std::vector<std::span<const unsigned char>> ToSpans() const LIFETIMEBOUND { return {begin(), end()}; } + std::vector<std::span<const unsigned char>> ToSpans() const LIFETIMEBOUND; /** The dynamic memory usage of the stack, including that of its elements. */ ``` </details> <details> <summary>Formatting cases for the witness tests</summary> ```diff diff --git a/src/test/script_tests.cpp b/src/test/script_tests.cpp index 9afeed3759..ac3c5e15d0 100644 --- a/src/test/script_tests.cpp +++ b/src/test/script_tests.cpp @@ -1739,2 +1739,7 @@ BOOST_AUTO_TEST_CASE(script_witness_representation) { + BOOST_CHECK_EQUAL(CScriptWitness{}.ToString(), "CScriptWitness()"); + BOOST_CHECK_EQUAL(CScriptWitness{{{0xaa}}}.ToString(), "CScriptWitness(aa)"); + const CScriptWitness with_empty{{{}, {0xbb, 0xcc}, {}}}; + BOOST_CHECK_EQUAL(with_empty.ToString(), "CScriptWitness(, bbcc, )"); + // Element counts and sizes around CompactSize encoding boundaries. ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-22 20:18:10 +00:00

0c981e7 script: store witness stacks as their serialization:

I’d still prefer to drop 32-bit support, but with a 32-bit size_t, ::GetSerializeSize() returns uint64_t and the header leaves room for at most UINT32_MAX - 4 payload bytes.

> [0c981e7](https://github.com/bitcoin/bitcoin/pull/36895/changes/0c981e75a9e7e352d1c0f08118596ea91a9fa102) _script: store witness stacks as their serialization_: I’d still prefer to [drop 32-bit support](https://github.com/bitcoin/bitcoin/issues/32375), but with a 32-bit `size_t`, `::GetSerializeSize()` returns `uint64_t` and the header leaves room for at most `UINT32_MAX - 4` payload bytes.
l0rinc (Migrated from github.com) commented 2026-11-22 20:03:13 +00:00

0c981e7 script: store witness stacks as their serialization:

We could drop CopyFrom() and reuse the copy constructor for assignment. Copying the header and payload together would also preserve the cached offset in your optimization followup. For consistency, we should cover self-assignment alongside the existing assignment tests.

Copy the header and payload together
diff --git a/src/script/script.cpp b/src/script/script.cpp
index 4f2ffbd64c..872a6c3b30 100644
--- a/src/script/script.cpp
+++ b/src/script/script.cpp
@@ -15,6 +15,7 @@
 #include <util/hash_type.h>
 #include <util/string.h>
 
+#include <algorithm>
 #include <cassert>
 #include <compare>
 #include <limits>
@@ -315,16 +316,12 @@ std::span<std::byte> CScriptWitness::Allocate(size_t size)
     return {m_data.get() + HEADER_SIZE, size};
 }
 
-void CScriptWitness::CopyFrom(const CScriptWitness& other)
+CScriptWitness::CScriptWitness(const CScriptWitness& other)
 {
-    if (!other.m_data) {
-        m_data.reset();
-        return;
-    }
+    if (other.empty()) return;
     const auto total = HEADER_SIZE + other.Data().size();
-    auto new_data = std::make_unique_for_overwrite<std::byte[]>(total);
-    std::copy(other.m_data.get(), other.m_data.get() + total, new_data.get());
-    m_data = std::move(new_data);
+    m_data = std::make_unique_for_overwrite<std::byte[]>(total);
+    std::copy_n(other.m_data.get(), total, m_data.get());
 }
 
 std::span<const unsigned char> CScriptWitness::operator[](size_t index) const noexcept
diff --git a/src/script/script.h b/src/script/script.h
index 19cba94eec..8cba924f3a 100644
--- a/src/script/script.h
+++ b/src/script/script.h
@@ -619,8 +619,6 @@ class CScriptWitness
     /** Allocate m_data for a non-empty stack whose serialization has the given size, and write the
      *  header. Returns where the serialization goes, which the caller must fill. */
     std::span<std::byte> Allocate(size_t size);
-    /** Make this a copy of other. */
-    void CopyFrom(const CScriptWitness& other);
 
 public:
     /** Forward iterator over the elements of the stack, exposing them as spans. */
@@ -664,10 +662,10 @@ public:
 
     CScriptWitness() = default;
     explicit CScriptWitness(const std::vector<std::vector<unsigned char>>& stack);
-    CScriptWitness(const CScriptWitness& other) { CopyFrom(other); }
+    CScriptWitness(const CScriptWitness& other);
     CScriptWitness& operator=(const CScriptWitness& other)
     {
-        if (this != &other) CopyFrom(other);
+        if (this != &other) *this = CScriptWitness{other};
         return *this;
     }
     /** Moving leaves the source empty. */
diff --git a/src/test/script_tests.cpp b/src/test/script_tests.cpp
index 9afeed3759..51af49c5e7 100644
--- a/src/test/script_tests.cpp
+++ b/src/test/script_tests.cpp
@@ -1782,6 +1782,9 @@ BOOST_AUTO_TEST_CASE(script_witness_representation)
 
             // Copy and move assignment replace the stack that was there.
             CScriptWitness copy{witness};
+            const auto& alias = copy;
+            copy = alias;
+            BOOST_CHECK(copy == witness);
             CScriptWitness assigned{{{0xff}}};
             assigned = copy;
             copy = {};
> [0c981e7](https://github.com/bitcoin/bitcoin/pull/36895/changes/0c981e75a9e7e352d1c0f08118596ea91a9fa102) _script: store witness stacks as their serialization_: We could drop `CopyFrom()` and reuse the copy constructor for assignment. Copying the header and payload together would also preserve the cached offset [in your optimization followup](https://github.com/bitcoin/bitcoin/pull/36918). For consistency, we should cover self-assignment alongside [the existing assignment tests](https://github.com/bitcoin/bitcoin/pull/36521#discussion_r4548487630). <details> <summary>Copy the header and payload together</summary> ```diff diff --git a/src/script/script.cpp b/src/script/script.cpp index 4f2ffbd64c..872a6c3b30 100644 --- a/src/script/script.cpp +++ b/src/script/script.cpp @@ -15,6 +15,7 @@ #include <util/hash_type.h> #include <util/string.h> +#include <algorithm> #include <cassert> #include <compare> #include <limits> @@ -315,16 +316,12 @@ std::span<std::byte> CScriptWitness::Allocate(size_t size) return {m_data.get() + HEADER_SIZE, size}; } -void CScriptWitness::CopyFrom(const CScriptWitness& other) +CScriptWitness::CScriptWitness(const CScriptWitness& other) { - if (!other.m_data) { - m_data.reset(); - return; - } + if (other.empty()) return; const auto total = HEADER_SIZE + other.Data().size(); - auto new_data = std::make_unique_for_overwrite<std::byte[]>(total); - std::copy(other.m_data.get(), other.m_data.get() + total, new_data.get()); - m_data = std::move(new_data); + m_data = std::make_unique_for_overwrite<std::byte[]>(total); + std::copy_n(other.m_data.get(), total, m_data.get()); } std::span<const unsigned char> CScriptWitness::operator[](size_t index) const noexcept diff --git a/src/script/script.h b/src/script/script.h index 19cba94eec..8cba924f3a 100644 --- a/src/script/script.h +++ b/src/script/script.h @@ -619,8 +619,6 @@ class CScriptWitness /** Allocate m_data for a non-empty stack whose serialization has the given size, and write the * header. Returns where the serialization goes, which the caller must fill. */ std::span<std::byte> Allocate(size_t size); - /** Make this a copy of other. */ - void CopyFrom(const CScriptWitness& other); public: /** Forward iterator over the elements of the stack, exposing them as spans. */ @@ -664,10 +662,10 @@ public: CScriptWitness() = default; explicit CScriptWitness(const std::vector<std::vector<unsigned char>>& stack); - CScriptWitness(const CScriptWitness& other) { CopyFrom(other); } + CScriptWitness(const CScriptWitness& other); CScriptWitness& operator=(const CScriptWitness& other) { - if (this != &other) CopyFrom(other); + if (this != &other) *this = CScriptWitness{other}; return *this; } /** Moving leaves the source empty. */ diff --git a/src/test/script_tests.cpp b/src/test/script_tests.cpp index 9afeed3759..51af49c5e7 100644 --- a/src/test/script_tests.cpp +++ b/src/test/script_tests.cpp @@ -1782,6 +1782,9 @@ BOOST_AUTO_TEST_CASE(script_witness_representation) // Copy and move assignment replace the stack that was there. CScriptWitness copy{witness}; + const auto& alias = copy; + copy = alias; + BOOST_CHECK(copy == witness); CScriptWitness assigned{{{0xff}}}; assigned = copy; copy = {}; ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-22 20:37:18 +00:00

0c981e7 script: store witness stacks as their serialization:

Prefix ++ could use LIFETIMEBOUND - and the three private span/iterator helpers could carry it too to guard internal callers.

Annotate prefix ++ and internal span helpers
diff --git a/src/script/script.h b/src/script/script.h
index 19cba94eec..0d024681ab 100644
--- a/src/script/script.h
+++ b/src/script/script.h
@@ -613,3 +613,3 @@ class CScriptWitness
      */
-    std::span<const std::byte> Data() const noexcept
+    std::span<const std::byte> Data() const noexcept LIFETIMEBOUND
     {
@@ -620,3 +620,3 @@ class CScriptWitness
      *  header. Returns where the serialization goes, which the caller must fill. */
-    std::span<std::byte> Allocate(size_t size);
+    std::span<std::byte> Allocate(size_t size) LIFETIMEBOUND;
     /** Make this a copy of other. */
@@ -631,3 +631,3 @@ public:
         friend CScriptWitness;
-        explicit Iterator(std::span<const std::byte> rest) noexcept : m_rest{rest} {}
+        explicit Iterator(std::span<const std::byte> rest LIFETIMEBOUND) noexcept : m_rest{rest} {}
 
@@ -649,3 +649,3 @@ public:
         }
-        Iterator& operator++() noexcept
+        Iterator& operator++() noexcept LIFETIMEBOUND
         {
> [0c981e7](https://github.com/bitcoin/bitcoin/pull/36895/changes/0c981e75a9e7e352d1c0f08118596ea91a9fa102) _script: store witness stacks as their serialization_: Prefix `++` could use `LIFETIMEBOUND` - and the three private span/iterator helpers could carry it too to guard internal callers. <details> <summary>Annotate prefix ++ and internal span helpers</summary> ```diff diff --git a/src/script/script.h b/src/script/script.h index 19cba94eec..0d024681ab 100644 --- a/src/script/script.h +++ b/src/script/script.h @@ -613,3 +613,3 @@ class CScriptWitness */ - std::span<const std::byte> Data() const noexcept + std::span<const std::byte> Data() const noexcept LIFETIMEBOUND { @@ -620,3 +620,3 @@ class CScriptWitness * header. Returns where the serialization goes, which the caller must fill. */ - std::span<std::byte> Allocate(size_t size); + std::span<std::byte> Allocate(size_t size) LIFETIMEBOUND; /** Make this a copy of other. */ @@ -631,3 +631,3 @@ public: friend CScriptWitness; - explicit Iterator(std::span<const std::byte> rest) noexcept : m_rest{rest} {} + explicit Iterator(std::span<const std::byte> rest LIFETIMEBOUND) noexcept : m_rest{rest} {} @@ -649,3 +649,3 @@ public: } - Iterator& operator++() noexcept + Iterator& operator++() noexcept LIFETIMEBOUND { ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-22 20:18:43 +00:00

0c981e7 script: store witness stacks as their serialization:

Returning a shared zero byte from Data() for an empty witness simplifies Serialize() and end().
With the iterator equality AJ suggested, iterators from different empty witnesses would point past the same static byte and differ from Iterator{}.

Return the serialized zero byte for an empty witness
diff --git a/src/script/script.h b/src/script/script.h
index 19cba94eec..e7704b1685 100644
--- a/src/script/script.h
+++ b/src/script/script.h
@@ -606,14 +606,15 @@ class CScriptWitness
     std::unique_ptr<std::byte[]> m_data;
     static constexpr size_t HEADER_SIZE{4};
 
-    /** The serialization of the stack (empty for an empty stack). As it was produced by this class,
+    /** The serialization of the stack. As it was produced by this class,
      *  ReadCompactSize cannot fail on it, so the accessors below are noexcept. This relies on the
      *  number of elements and their sizes not exceeding MAX_SIZE, which holds for deserialized
      *  stacks, and in practice for stacks constructed from vectors.
      */
     std::span<const std::byte> Data() const noexcept
     {
-        if (!m_data) return {};
+        static constexpr std::byte EMPTY_SERIALIZATION[1]{};
+        if (!m_data) return EMPTY_SERIALIZATION;
         return {m_data.get() + HEADER_SIZE, ReadLE32(m_data.get())};
     }
     /** Allocate m_data for a non-empty stack whose serialization has the given size, and write the
@@ -685,7 +686,7 @@ public:
     }
     Iterator begin() const noexcept LIFETIMEBOUND
     {
-        if (!m_data) return Iterator{};
+        if (!m_data) return end();
         const auto data = Data();
         SpanReader reader{data};
         ReadCompactSize(reader);
@@ -694,7 +695,6 @@ public:
     }
     Iterator end() const noexcept LIFETIMEBOUND
     {
-        if (!m_data) return Iterator{};
         const auto data = Data();
         return Iterator{data.subspan(data.size())};
     }
@@ -719,11 +719,7 @@ public:
     template <typename Stream>
     void Serialize(Stream& s) const
     {
-        if (!m_data) {
-            s << uint8_t{0};
-        } else {
-            s.write(Data());
-        }
+        s.write(Data());
     }
 
     /** Deserialize a witness stack, with the same semantics (and failures) as deserializing a
> [0c981e7](https://github.com/bitcoin/bitcoin/pull/36895/changes/0c981e75a9e7e352d1c0f08118596ea91a9fa102) _script: store witness stacks as their serialization_: Returning a shared zero byte from `Data()` for an empty witness simplifies `Serialize()` and `end()`. With [the iterator equality AJ suggested](https://github.com/bitcoin/bitcoin/pull/36521#discussion_r4528821567), iterators from different empty witnesses would point past the same static byte and differ from `Iterator{}`. <details> <summary>Return the serialized zero byte for an empty witness</summary> ```diff diff --git a/src/script/script.h b/src/script/script.h index 19cba94eec..e7704b1685 100644 --- a/src/script/script.h +++ b/src/script/script.h @@ -606,14 +606,15 @@ class CScriptWitness std::unique_ptr<std::byte[]> m_data; static constexpr size_t HEADER_SIZE{4}; - /** The serialization of the stack (empty for an empty stack). As it was produced by this class, + /** The serialization of the stack. As it was produced by this class, * ReadCompactSize cannot fail on it, so the accessors below are noexcept. This relies on the * number of elements and their sizes not exceeding MAX_SIZE, which holds for deserialized * stacks, and in practice for stacks constructed from vectors. */ std::span<const std::byte> Data() const noexcept { - if (!m_data) return {}; + static constexpr std::byte EMPTY_SERIALIZATION[1]{}; + if (!m_data) return EMPTY_SERIALIZATION; return {m_data.get() + HEADER_SIZE, ReadLE32(m_data.get())}; } /** Allocate m_data for a non-empty stack whose serialization has the given size, and write the @@ -685,7 +686,7 @@ public: } Iterator begin() const noexcept LIFETIMEBOUND { - if (!m_data) return Iterator{}; + if (!m_data) return end(); const auto data = Data(); SpanReader reader{data}; ReadCompactSize(reader); @@ -694,7 +695,6 @@ public: } Iterator end() const noexcept LIFETIMEBOUND { - if (!m_data) return Iterator{}; const auto data = Data(); return Iterator{data.subspan(data.size())}; } @@ -719,11 +719,7 @@ public: template <typename Stream> void Serialize(Stream& s) const { - if (!m_data) { - s << uint8_t{0}; - } else { - s.write(Data()); - } + s.write(Data()); } /** Deserialize a witness stack, with the same semantics (and failures) as deserializing a ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-22 20:13:46 +00:00

18403ab script: give CScriptWitness an interface that hides its representation:

nit: for consistency with the standard library, we could separate the iterator concept and the legacy category here too. C++ draft · libc++

Separate the iterator concept from the legacy category
diff --git a/src/script/script.h b/src/script/script.h
index 19c95824b6..054f3ed7f5 100644
--- a/src/script/script.h
+++ b/src/script/script.h
@@ -606,7 +606,8 @@ struct CScriptWitness
         explicit Iterator(std::vector<std::vector<unsigned char>>::const_iterator it) noexcept : m_it{it} {}
 
     public:
-        using iterator_category = std::forward_iterator_tag;
+        using iterator_concept = std::forward_iterator_tag;
+        using iterator_category = std::input_iterator_tag;
         using value_type = std::span<const unsigned char>;
         using difference_type = std::ptrdiff_t;
         using pointer = void;
diff --git a/src/test/script_tests.cpp b/src/test/script_tests.cpp
index a0ff214f92..68f31c9ab0 100644
--- a/src/test/script_tests.cpp
+++ b/src/test/script_tests.cpp
@@ -32,7 +32,10 @@
 #include <boost/test/unit_test.hpp>
 
 #include <cstdint>
+#include <iterator>
+#include <ranges>
 #include <string>
+#include <type_traits>
 #include <vector>
 
 // Uncomment if you want to output updated JSON tests.
@@ -427,6 +430,9 @@ std::string JSONPrettyPrint(const UniValue& univalue)
 }
 } // namespace
 
+static_assert(std::ranges::forward_range<const CScriptWitness>);
+static_assert(std::is_same_v<std::iterator_traits<CScriptWitness::Iterator>::iterator_category, std::input_iterator_tag>);
+
 BOOST_FIXTURE_TEST_SUITE(script_tests, ScriptTest)
 
 BOOST_AUTO_TEST_CASE(script_build)
> [18403ab](https://github.com/bitcoin/bitcoin/pull/36895/changes/18403ab7545664d2369b1f8ea40b893123779fb9) _script: give CScriptWitness an interface that hides its representation_: nit: for consistency with the standard library, we could separate the iterator concept and the legacy category here too. [C++ draft](https://eel.is/c++draft/range.transform.iterator#2.2) · [libc++](https://github.com/llvm/llvm-project/blob/llvmorg-21.1.0/libcxx/include/__ranges/transform_view.h#L159-L195) <details> <summary>Separate the iterator concept from the legacy category</summary> ```diff diff --git a/src/script/script.h b/src/script/script.h index 19c95824b6..054f3ed7f5 100644 --- a/src/script/script.h +++ b/src/script/script.h @@ -606,7 +606,8 @@ struct CScriptWitness explicit Iterator(std::vector<std::vector<unsigned char>>::const_iterator it) noexcept : m_it{it} {} public: - using iterator_category = std::forward_iterator_tag; + using iterator_concept = std::forward_iterator_tag; + using iterator_category = std::input_iterator_tag; using value_type = std::span<const unsigned char>; using difference_type = std::ptrdiff_t; using pointer = void; diff --git a/src/test/script_tests.cpp b/src/test/script_tests.cpp index a0ff214f92..68f31c9ab0 100644 --- a/src/test/script_tests.cpp +++ b/src/test/script_tests.cpp @@ -32,7 +32,10 @@ #include <boost/test/unit_test.hpp> #include <cstdint> +#include <iterator> +#include <ranges> #include <string> +#include <type_traits> #include <vector> // Uncomment if you want to output updated JSON tests. @@ -427,6 +430,9 @@ std::string JSONPrettyPrint(const UniValue& univalue) } } // namespace +static_assert(std::ranges::forward_range<const CScriptWitness>); +static_assert(std::is_same_v<std::iterator_traits<CScriptWitness::Iterator>::iterator_category, std::input_iterator_tag>); + BOOST_FIXTURE_TEST_SUITE(script_tests, ScriptTest) BOOST_AUTO_TEST_CASE(script_build) ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-22 20:01:34 +00:00

0c981e7 script: store witness stacks as their serialization:

The vector constructor accepts elements above MAX_SIZE, but reading their lengths throws inside the noexcept accessors and terminates the process. We could disable the range check on these internal reads, as your followup decoder does, and cover optout21’s constructor case.

Internal CompactSize reads and regression test
diff --git a/src/script/script.h b/src/script/script.h
index 19cba94eec..167c3ae049 100644
--- a/src/script/script.h
+++ b/src/script/script.h
@@ -606,10 +606,9 @@ class CScriptWitness
     std::unique_ptr<std::byte[]> m_data;
     static constexpr size_t HEADER_SIZE{4};
 
-    /** The serialization of the stack (empty for an empty stack). As it was produced by this class,
-     *  ReadCompactSize cannot fail on it, so the accessors below are noexcept. This relies on the
-     *  number of elements and their sizes not exceeding MAX_SIZE, which holds for deserialized
-     *  stacks, and in practice for stacks constructed from vectors.
+    /** The serialization of the stack (empty for an empty stack).
+     *  It is canonical, but vector construction permits counts and element sizes above MAX_SIZE.
+     *  ReadCompactSize with range_check=false cannot fail on it, so the accessors are noexcept.
      */
     std::span<const std::byte> Data() const noexcept
     {
@@ -642,7 +641,7 @@ public:
         value_type operator*() const noexcept
         {
             SpanReader reader{m_rest};
-            const auto len = ReadCompactSize(reader);
+            const auto len = ReadCompactSize(reader, /*range_check=*/false);
             // What the reader has left starts with the element. The serialization is std::byte, but elements are
             // returned as unsigned char, like other script data.
             return UCharSpanCast(m_rest.last(reader.size()).first(len));
@@ -650,7 +649,7 @@ public:
         Iterator& operator++() noexcept
         {
             SpanReader reader{m_rest};
-            const auto len = ReadCompactSize(reader);
+            const auto len = ReadCompactSize(reader, /*range_check=*/false);
             // Skip the element, which is at the start of what the reader has left.
             m_rest = m_rest.last(reader.size() - len);
             return *this;
@@ -681,14 +680,14 @@ public:
     {
         if (!m_data) return 0;
         SpanReader reader{Data()};
-        return ReadCompactSize(reader);
+        return ReadCompactSize(reader, /*range_check=*/false);
     }
     Iterator begin() const noexcept LIFETIMEBOUND
     {
         if (!m_data) return Iterator{};
         const auto data = Data();
         SpanReader reader{data};
-        ReadCompactSize(reader);
+        ReadCompactSize(reader, /*range_check=*/false);
         // The elements are what follows the number of elements.
         return Iterator{data.last(reader.size())};
     }
diff --git a/src/test/script_tests.cpp b/src/test/script_tests.cpp
index df8dbee555..4d0a708126 100644
--- a/src/test/script_tests.cpp
+++ b/src/test/script_tests.cpp
@@ -15,6 +15,7 @@
 #include <script/signingprovider.h>
 #include <script/solver.h>
 #include <secp256k1.h>
+#include <serialize.h>
 #include <streams.h>
 #include <test/data/bip341_wallet_vectors.json.h>
 #include <test/data/script_tests.json.h>
@@ -31,7 +32,11 @@
 
 #include <boost/test/unit_test.hpp>
 
+#include <algorithm>
+#include <cstddef>
 #include <cstdint>
+#include <ios>
+#include <iterator>
 #include <string>
 #include <vector>
 
@@ -1799,6 +1804,20 @@ BOOST_AUTO_TEST_CASE(script_witness_representation)
             if (!stack.empty()) BOOST_CHECK(std::ranges::equal(move_assigned.back(), stack.back()));
         }
     }
+
+    // Vector construction permits larger elements than stream deserialization.
+    std::vector<std::vector<unsigned char>> large_stack(1);
+    large_stack.front().resize(MAX_SIZE + 1);
+    const CScriptWitness large{large_stack};
+    BOOST_CHECK(std::ranges::equal(large.front(), large_stack[0]));
+    BOOST_CHECK_EQUAL(large.back().size(), MAX_SIZE + 1);
+    BOOST_CHECK_EQUAL(std::distance(large.begin(), large.end()), (std::ptrdiff_t)large_stack.size());
+
+    DataStream stream;
+    WriteCompactSize(stream, large_stack.size());
+    WriteCompactSize(stream, large_stack[0].size());
+    CScriptWitness decoded;
+    BOOST_CHECK_EXCEPTION(stream >> decoded, std::ios_base::failure, HasReason{"ReadCompactSize(): size too large"});
 }
 
 BOOST_AUTO_TEST_SUITE_END()
> [0c981e7](https://github.com/bitcoin/bitcoin/pull/36895/changes/0c981e75a9e7e352d1c0f08118596ea91a9fa102) _script: store witness stacks as their serialization_: The vector constructor accepts elements above `MAX_SIZE`, but reading their lengths throws inside the `noexcept` accessors and terminates the process. We could disable the range check on these internal reads, as [your followup decoder](https://github.com/bitcoin/bitcoin/pull/36918) does, and cover [optout21’s constructor case](https://github.com/bitcoin/bitcoin/pull/36895#pullrequestreview-5973320107). <details> <summary>Internal CompactSize reads and regression test</summary> ```diff diff --git a/src/script/script.h b/src/script/script.h index 19cba94eec..167c3ae049 100644 --- a/src/script/script.h +++ b/src/script/script.h @@ -606,10 +606,9 @@ class CScriptWitness std::unique_ptr<std::byte[]> m_data; static constexpr size_t HEADER_SIZE{4}; - /** The serialization of the stack (empty for an empty stack). As it was produced by this class, - * ReadCompactSize cannot fail on it, so the accessors below are noexcept. This relies on the - * number of elements and their sizes not exceeding MAX_SIZE, which holds for deserialized - * stacks, and in practice for stacks constructed from vectors. + /** The serialization of the stack (empty for an empty stack). + * It is canonical, but vector construction permits counts and element sizes above MAX_SIZE. + * ReadCompactSize with range_check=false cannot fail on it, so the accessors are noexcept. */ std::span<const std::byte> Data() const noexcept { @@ -642,7 +641,7 @@ public: value_type operator*() const noexcept { SpanReader reader{m_rest}; - const auto len = ReadCompactSize(reader); + const auto len = ReadCompactSize(reader, /*range_check=*/false); // What the reader has left starts with the element. The serialization is std::byte, but elements are // returned as unsigned char, like other script data. return UCharSpanCast(m_rest.last(reader.size()).first(len)); @@ -650,7 +649,7 @@ public: Iterator& operator++() noexcept { SpanReader reader{m_rest}; - const auto len = ReadCompactSize(reader); + const auto len = ReadCompactSize(reader, /*range_check=*/false); // Skip the element, which is at the start of what the reader has left. m_rest = m_rest.last(reader.size() - len); return *this; @@ -681,14 +680,14 @@ public: { if (!m_data) return 0; SpanReader reader{Data()}; - return ReadCompactSize(reader); + return ReadCompactSize(reader, /*range_check=*/false); } Iterator begin() const noexcept LIFETIMEBOUND { if (!m_data) return Iterator{}; const auto data = Data(); SpanReader reader{data}; - ReadCompactSize(reader); + ReadCompactSize(reader, /*range_check=*/false); // The elements are what follows the number of elements. return Iterator{data.last(reader.size())}; } diff --git a/src/test/script_tests.cpp b/src/test/script_tests.cpp index df8dbee555..4d0a708126 100644 --- a/src/test/script_tests.cpp +++ b/src/test/script_tests.cpp @@ -15,6 +15,7 @@ #include <script/signingprovider.h> #include <script/solver.h> #include <secp256k1.h> +#include <serialize.h> #include <streams.h> #include <test/data/bip341_wallet_vectors.json.h> #include <test/data/script_tests.json.h> @@ -31,7 +32,11 @@ #include <boost/test/unit_test.hpp> +#include <algorithm> +#include <cstddef> #include <cstdint> +#include <ios> +#include <iterator> #include <string> #include <vector> @@ -1799,6 +1804,20 @@ BOOST_AUTO_TEST_CASE(script_witness_representation) if (!stack.empty()) BOOST_CHECK(std::ranges::equal(move_assigned.back(), stack.back())); } } + + // Vector construction permits larger elements than stream deserialization. + std::vector<std::vector<unsigned char>> large_stack(1); + large_stack.front().resize(MAX_SIZE + 1); + const CScriptWitness large{large_stack}; + BOOST_CHECK(std::ranges::equal(large.front(), large_stack[0])); + BOOST_CHECK_EQUAL(large.back().size(), MAX_SIZE + 1); + BOOST_CHECK_EQUAL(std::distance(large.begin(), large.end()), (std::ptrdiff_t)large_stack.size()); + + DataStream stream; + WriteCompactSize(stream, large_stack.size()); + WriteCompactSize(stream, large_stack[0].size()); + CScriptWitness decoded; + BOOST_CHECK_EXCEPTION(stream >> decoded, std::ios_base::failure, HasReason{"ReadCompactSize(): size too large"}); } BOOST_AUTO_TEST_SUITE_END() ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-22 20:18:49 +00:00

0c981e7 script: store witness stacks as their serialization:

Data().last(0) gives end() the one-past-the-end position directly.

Take the empty suffix for end()
diff --git a/src/script/script.h b/src/script/script.h
index 19cba94eec..b75a1fa841 100644
--- a/src/script/script.h
+++ b/src/script/script.h
@@ -695,8 +695,7 @@ public:
     Iterator end() const noexcept LIFETIMEBOUND
     {
         if (!m_data) return Iterator{};
-        const auto data = Data();
-        return Iterator{data.subspan(data.size())};
+        return Iterator{Data().last(0)};
     }
     /** The first (bottom) element. The stack must not be empty. */
     std::span<const unsigned char> front() const noexcept LIFETIMEBOUND { return *begin(); }
> [0c981e7](https://github.com/bitcoin/bitcoin/pull/36895/changes/0c981e75a9e7e352d1c0f08118596ea91a9fa102) _script: store witness stacks as their serialization_: `Data().last(0)` gives `end()` the one-past-the-end position directly. <details> <summary>Take the empty suffix for end()</summary> ```diff diff --git a/src/script/script.h b/src/script/script.h index 19cba94eec..b75a1fa841 100644 --- a/src/script/script.h +++ b/src/script/script.h @@ -695,8 +695,7 @@ public: Iterator end() const noexcept LIFETIMEBOUND { if (!m_data) return Iterator{}; - const auto data = Data(); - return Iterator{data.subspan(data.size())}; + return Iterator{Data().last(0)}; } /** The first (bottom) element. The stack must not be empty. */ std::span<const unsigned char> front() const noexcept LIFETIMEBOUND { return *begin(); } ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-22 20:37:54 +00:00

0c981e7 script: store witness stacks as their serialization:

Do we want to mention that spans and iterators follow the storage when a witness is moved? I’d put that on the class since your optimization followup drops ToSpans() (though I'd prefer that here instead), and say explicitly that ToVectors() returns copies.

Document borrowed span lifetimes and ToVectors() copies
diff --git a/src/script/script.h b/src/script/script.h
index 19cba94eec..2993e85e75 100644
--- a/src/script/script.h
+++ b/src/script/script.h
@@ -582,2 +582,3 @@ public:
  *  can only be constructed as a whole (from a vector of its elements), not modified.
+ *  Returned spans and iterators remain valid while the storage they refer to exists, including after ownership is moved.
  *
@@ -708,6 +709,6 @@ public:
 
-    /** The elements, bottom to top, as vectors. For code that needs to modify or take ownership of them (e.g. to
+    /** Copies of the elements, bottom to top. For code that needs to modify or take ownership of them (e.g. to
      *  execute a script with them as its initial stack). */
     std::vector<std::vector<unsigned char>> ToVectors() const;
-    /** Spans of the elements, bottom to top, which are valid as long as this witness is. For code that accesses many
+    /** Spans of the elements, bottom to top. For code that accesses many
      *  elements by index, as indexing a witness need not be constant-time. */
> [0c981e7](https://github.com/bitcoin/bitcoin/pull/36895/changes/0c981e75a9e7e352d1c0f08118596ea91a9fa102) _script: store witness stacks as their serialization_: Do we want to mention that spans and iterators follow the storage when a witness is moved? I’d put that on the class since [your optimization followup](https://github.com/bitcoin/bitcoin/pull/36918) drops `ToSpans()` (though I'd prefer that here instead), and say explicitly that `ToVectors()` returns copies. <details> <summary>Document borrowed span lifetimes and ToVectors() copies</summary> ```diff diff --git a/src/script/script.h b/src/script/script.h index 19cba94eec..2993e85e75 100644 --- a/src/script/script.h +++ b/src/script/script.h @@ -582,2 +582,3 @@ public: * can only be constructed as a whole (from a vector of its elements), not modified. + * Returned spans and iterators remain valid while the storage they refer to exists, including after ownership is moved. * @@ -708,6 +709,6 @@ public: - /** The elements, bottom to top, as vectors. For code that needs to modify or take ownership of them (e.g. to + /** Copies of the elements, bottom to top. For code that needs to modify or take ownership of them (e.g. to * execute a script with them as its initial stack). */ std::vector<std::vector<unsigned char>> ToVectors() const; - /** Spans of the elements, bottom to top, which are valid as long as this witness is. For code that accesses many + /** Spans of the elements, bottom to top. For code that accesses many * elements by index, as indexing a witness need not be constant-time. */ ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-22 20:18:23 +00:00

0c981e7 script: store witness stacks as their serialization:

We could report a size limit reached while reading or packing the witness as std::ios_base::failure, as your optimization followup does for packing.

Report the failure as a deserialization error
diff --git a/src/script/script.h b/src/script/script.h
index 19cba94eec..dd10e3470f 100644
--- a/src/script/script.h
+++ b/src/script/script.h
@@ -19,6 +19,7 @@
 #include <cassert>
 #include <cstddef>
 #include <cstdint>
+#include <ios>
 #include <iterator>
 #include <limits>
 #include <memory>
@@ -726,14 +727,17 @@ public:
         }
     }
 
-    /** Deserialize a witness stack, with the same semantics (and failures) as deserializing a
-     *  std::vector<std::vector<unsigned char>>. */
+    /** Deserialize a witness stack using the wire format of std::vector<std::vector<unsigned char>>. */
     template <typename Stream>
     void Unserialize(Stream& s)
     {
-        std::vector<std::vector<unsigned char>> stack;
-        s >> stack;
-        *this = CScriptWitness{stack};
+        try {
+            std::vector<std::vector<unsigned char>> stack;
+            s >> stack;
+            *this = CScriptWitness{stack};
+        } catch (const std::length_error&) {
+            throw std::ios_base::failure("Witness stack too large");
+        }
     }
 
     std::string ToString() const;
diff --git a/src/test/fuzz/script_witness.cpp b/src/test/fuzz/script_witness.cpp
index 5a03b561f0..91d43f9f9d 100644
--- a/src/test/fuzz/script_witness.cpp
+++ b/src/test/fuzz/script_witness.cpp
@@ -13,9 +13,7 @@
 #include <optional>
 #include <vector>
 
-/** Deserialization of a CScriptWitness behaves exactly like that of a
- *  std::vector<std::vector<unsigned char>>, and its accessors and serialization agree with that
- *  vector. */
+/** Compare wire decoding against a vector of vectors, then check the accessors and serialization on success. */
 FUZZ_TARGET(script_witness_deserialize)
 {
     // Deserialize the input as a vector of vector of unsigned chars.
> [0c981e7](https://github.com/bitcoin/bitcoin/pull/36895/changes/0c981e75a9e7e352d1c0f08118596ea91a9fa102) _script: store witness stacks as their serialization_: We could report a size limit reached while reading or packing the witness as `std::ios_base::failure`, as [your optimization followup](https://github.com/bitcoin/bitcoin/pull/36918) does for packing. <details> <summary>Report the failure as a deserialization error</summary> ```diff diff --git a/src/script/script.h b/src/script/script.h index 19cba94eec..dd10e3470f 100644 --- a/src/script/script.h +++ b/src/script/script.h @@ -19,6 +19,7 @@ #include <cassert> #include <cstddef> #include <cstdint> +#include <ios> #include <iterator> #include <limits> #include <memory> @@ -726,14 +727,17 @@ public: } } - /** Deserialize a witness stack, with the same semantics (and failures) as deserializing a - * std::vector<std::vector<unsigned char>>. */ + /** Deserialize a witness stack using the wire format of std::vector<std::vector<unsigned char>>. */ template <typename Stream> void Unserialize(Stream& s) { - std::vector<std::vector<unsigned char>> stack; - s >> stack; - *this = CScriptWitness{stack}; + try { + std::vector<std::vector<unsigned char>> stack; + s >> stack; + *this = CScriptWitness{stack}; + } catch (const std::length_error&) { + throw std::ios_base::failure("Witness stack too large"); + } } std::string ToString() const; diff --git a/src/test/fuzz/script_witness.cpp b/src/test/fuzz/script_witness.cpp index 5a03b561f0..91d43f9f9d 100644 --- a/src/test/fuzz/script_witness.cpp +++ b/src/test/fuzz/script_witness.cpp @@ -13,9 +13,7 @@ #include <optional> #include <vector> -/** Deserialization of a CScriptWitness behaves exactly like that of a - * std::vector<std::vector<unsigned char>>, and its accessors and serialization agree with that - * vector. */ +/** Compare wire decoding against a vector of vectors, then check the accessors and serialization on success. */ FUZZ_TARGET(script_witness_deserialize) { // Deserialize the input as a vector of vector of unsigned chars. ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-22 20:18:17 +00:00

0c981e7 script: store witness stacks as their serialization:

Would it be useful to test a truncated read into a populated witness as well? The packed reader already preserves the original value.

Check that a failed read leaves a populated witness unchanged
diff --git a/src/test/script_tests.cpp b/src/test/script_tests.cpp
index 9afeed3759..222f0ec8cc 100644
--- a/src/test/script_tests.cpp
+++ b/src/test/script_tests.cpp
@@ -32,6 +32,7 @@
 #include <boost/test/unit_test.hpp>
 
 #include <cstdint>
+#include <ios>
 #include <string>
 #include <vector>
 
@@ -1796,6 +1797,12 @@ BOOST_AUTO_TEST_CASE(script_witness_representation)
             if (!stack.empty()) BOOST_CHECK(std::ranges::equal(move_assigned.back(), stack.back()));
         }
     }
+
+    const CScriptWitness original{{{0xaa}}};
+    CScriptWitness destination{original};
+    static constexpr auto truncated{"0201bb01"_hex};
+    BOOST_CHECK_EXCEPTION(SpanReader{truncated} >> destination, std::ios_base::failure, HasReason{"end of data"});
+    BOOST_CHECK(destination == original);
 }
 
 BOOST_AUTO_TEST_SUITE_END()
> [0c981e7](https://github.com/bitcoin/bitcoin/pull/36895/changes/0c981e75a9e7e352d1c0f08118596ea91a9fa102) _script: store witness stacks as their serialization_: Would it be useful to test a truncated read into a populated witness as well? The packed reader already preserves the original value. <details> <summary>Check that a failed read leaves a populated witness unchanged</summary> ```diff diff --git a/src/test/script_tests.cpp b/src/test/script_tests.cpp index 9afeed3759..222f0ec8cc 100644 --- a/src/test/script_tests.cpp +++ b/src/test/script_tests.cpp @@ -32,6 +32,7 @@ #include <boost/test/unit_test.hpp> #include <cstdint> +#include <ios> #include <string> #include <vector> @@ -1796,6 +1797,12 @@ BOOST_AUTO_TEST_CASE(script_witness_representation) if (!stack.empty()) BOOST_CHECK(std::ranges::equal(move_assigned.back(), stack.back())); } } + + const CScriptWitness original{{{0xaa}}}; + CScriptWitness destination{original}; + static constexpr auto truncated{"0201bb01"_hex}; + BOOST_CHECK_EXCEPTION(SpanReader{truncated} >> destination, std::ios_base::failure, HasReason{"end of data"}); + BOOST_CHECK(destination == original); } BOOST_AUTO_TEST_SUITE_END() ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-22 20:05:53 +00:00

0c981e7 script: store witness stacks as their serialization:

It seems to me that using std::byte prevents an optimized comparison here. Guix’s Clang build is probably affected too, but the fix looks like a simple cast so we could include it here.

Compare the spans as unsigned char
diff --git a/src/script/script.h b/src/script/script.h
index 19cba94eec..5d75d8a5e3 100644
--- a/src/script/script.h
+++ b/src/script/script.h
@@ -739,7 +739,7 @@ public:
     std::string ToString() const;
 
     /** Witnesses are equal exactly when their stacks are, as a stack has only one serialization. */
-    friend bool operator==(const CScriptWitness& a, const CScriptWitness& b) noexcept { return std::ranges::equal(a.Data(), b.Data()); }
+    friend bool operator==(const CScriptWitness& a, const CScriptWitness& b) noexcept { return std::ranges::equal(UCharSpanCast(a.Data()), UCharSpanCast(b.Data())); }
 };
 
 /** A reference to a CScript: the Hash160 of its serialization */
> [0c981e7](https://github.com/bitcoin/bitcoin/pull/36895/changes/0c981e75a9e7e352d1c0f08118596ea91a9fa102) _script: store witness stacks as their serialization_: It seems to me that using `std::byte` prevents an optimized comparison here. Guix’s Clang build is probably affected too, but the fix looks like a [simple cast](https://godbolt.org/z/78EvWKbhG) so we could include it here. <details> <summary>Compare the spans as unsigned char</summary> ```diff diff --git a/src/script/script.h b/src/script/script.h index 19cba94eec..5d75d8a5e3 100644 --- a/src/script/script.h +++ b/src/script/script.h @@ -739,7 +739,7 @@ public: std::string ToString() const; /** Witnesses are equal exactly when their stacks are, as a stack has only one serialization. */ - friend bool operator==(const CScriptWitness& a, const CScriptWitness& b) noexcept { return std::ranges::equal(a.Data(), b.Data()); } + friend bool operator==(const CScriptWitness& a, const CScriptWitness& b) noexcept { return std::ranges::equal(UCharSpanCast(a.Data()), UCharSpanCast(b.Data())); } }; /** A reference to a CScript: the Hash160 of its serialization */ ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-22 21:06:56 +00:00

0c981e7 script: store witness stacks as their serialization:

Alongside the empty-stack case, we could cover witnesses of equal length with different contents.

Witness equality returning false
diff --git a/src/test/script_tests.cpp b/src/test/script_tests.cpp
index 9afeed3759..df8dbee555 100644
--- a/src/test/script_tests.cpp
+++ b/src/test/script_tests.cpp
@@ -1737,6 +1737,9 @@ BOOST_AUTO_TEST_CASE(formatscriptflags)
 
 BOOST_AUTO_TEST_CASE(script_witness_representation)
 {
+    BOOST_CHECK(CScriptWitness{{{0x01}}} != CScriptWitness{{{0x02}}});
+    BOOST_CHECK(CScriptWitness{} != CScriptWitness{{{}}});
+
     // Element counts and sizes around CompactSize encoding boundaries.
     static constexpr size_t COUNTS[]{0, 1, 2, 3, 252, 253, 254};
     static constexpr size_t SIZES[]{0, 1, 32, 252, 253, 65535, 65536};
> [0c981e7](https://github.com/bitcoin/bitcoin/pull/36895/changes/0c981e75a9e7e352d1c0f08118596ea91a9fa102) _script: store witness stacks as their serialization_: Alongside [the empty-stack case](https://github.com/bitcoin/bitcoin/pull/36895#discussion_r4630270818), we could cover witnesses of equal length with different contents. <details> <summary>Witness equality returning false</summary> ```diff diff --git a/src/test/script_tests.cpp b/src/test/script_tests.cpp index 9afeed3759..df8dbee555 100644 --- a/src/test/script_tests.cpp +++ b/src/test/script_tests.cpp @@ -1737,6 +1737,9 @@ BOOST_AUTO_TEST_CASE(formatscriptflags) BOOST_AUTO_TEST_CASE(script_witness_representation) { + BOOST_CHECK(CScriptWitness{{{0x01}}} != CScriptWitness{{{0x02}}}); + BOOST_CHECK(CScriptWitness{} != CScriptWitness{{{}}}); + // Element counts and sizes around CompactSize encoding boundaries. static constexpr size_t COUNTS[]{0, 1, 2, 3, 252, 253, 254}; static constexpr size_t SIZES[]{0, 1, 32, 252, 253, 65535, 65536}; ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-22 20:38:00 +00:00

2366d35 span: add SameSpan:

nit: For a follow-up, AJ’s SameSpan helper would let NetGroupManager check that it kept the full ASMap after the move. The current assertion checks only its starting address.
Maybe we could add this as a separate preceding PR to simplify this one...

Check the entire ASMap view
diff --git a/src/netgroup.cpp b/src/netgroup.cpp
index dd9c3f300c..e489729e55 100644
--- a/src/netgroup.cpp
+++ b/src/netgroup.cpp
@@ -5,6 +5,7 @@
 #include <netgroup.h>
 
 #include <hash.h>
+#include <span.h>
 #include <uint256.h>
 #include <util/asmap.h>
 #include <util/log.h>
@@ -18,7 +19,7 @@ NetGroupManager::NetGroupManager(std::span<const std::byte> embedded_asmap, std:
       m_loaded_asmap{std::move(loaded_asmap)},
       m_asmap_version{AsmapVersion(m_asmap)}
 {
-    assert(m_loaded_asmap.empty() || m_asmap.data() == m_loaded_asmap.data());
+    assert(m_loaded_asmap.empty() || SameSpan(m_asmap, std::span<const std::byte>{m_loaded_asmap}));
 }
 
 uint256 NetGroupManager::GetAsmapVersion() const
> [2366d35](https://github.com/bitcoin/bitcoin/pull/36895/changes/2366d35e07710eb236a1f2ce3937cf2e40ac8de5) _span: add SameSpan_: nit: For a follow-up, [AJ’s `SameSpan` helper](https://github.com/bitcoin/bitcoin/pull/36521#discussion_r4528821567) would let `NetGroupManager` check that it kept the full ASMap after the move. The current assertion checks only its starting address. Maybe we could add this as a separate preceding PR to simplify this one... <details> <summary>Check the entire ASMap view</summary> ```diff diff --git a/src/netgroup.cpp b/src/netgroup.cpp index dd9c3f300c..e489729e55 100644 --- a/src/netgroup.cpp +++ b/src/netgroup.cpp @@ -5,6 +5,7 @@ #include <netgroup.h> #include <hash.h> +#include <span.h> #include <uint256.h> #include <util/asmap.h> #include <util/log.h> @@ -18,7 +19,7 @@ NetGroupManager::NetGroupManager(std::span<const std::byte> embedded_asmap, std: m_loaded_asmap{std::move(loaded_asmap)}, m_asmap_version{AsmapVersion(m_asmap)} { - assert(m_loaded_asmap.empty() || m_asmap.data() == m_loaded_asmap.data()); + assert(m_loaded_asmap.empty() || SameSpan(m_asmap, std::span<const std::byte>{m_loaded_asmap})); } uint256 NetGroupManager::GetAsmapVersion() const ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-22 20:01:41 +00:00

0c981e7 script: store witness stacks as their serialization:

The catch covers decoding failure, so I’d include the SpanReader construction in the try as well - that also lets us drop the extra scope.

Move SpanReader inside the try blocks
diff --git a/src/test/fuzz/script_witness.cpp b/src/test/fuzz/script_witness.cpp
index 5a03b561f0..ec7045f65d 100644
--- a/src/test/fuzz/script_witness.cpp
+++ b/src/test/fuzz/script_witness.cpp
@@ -21,29 +21,25 @@ FUZZ_TARGET(script_witness_deserialize)
     // Deserialize the input as a vector of vector of unsigned chars.
     size_t stack_left{0};
     std::optional<std::vector<std::vector<unsigned char>>> stack;
-    {
+    try {
         SpanReader reader{buffer};
-        try {
-            std::vector<std::vector<unsigned char>> tmp;
-            reader >> tmp;
-            stack = std::move(tmp);
-            stack_left = reader.size();
-        } catch (const std::ios_base::failure&) {
-        }
+        std::vector<std::vector<unsigned char>> tmp;
+        reader >> tmp;
+        stack = std::move(tmp);
+        stack_left = reader.size();
+    } catch (const std::ios_base::failure&) {
     }
 
     // Start over, and deserialize as a CScriptWitness.
     std::optional<CScriptWitness> witness;
     size_t witness_left{0};
-    {
+    try {
         SpanReader reader{buffer};
-        try {
-            CScriptWitness tmp;
-            reader >> tmp;
-            witness = std::move(tmp);
-            witness_left = reader.size();
-        } catch (const std::ios_base::failure&) {
-        }
+        CScriptWitness tmp;
+        reader >> tmp;
+        witness = std::move(tmp);
+        witness_left = reader.size();
+    } catch (const std::ios_base::failure&) {
     }
 
     // Check whether deserialization success matches between them.
> [0c981e7](https://github.com/bitcoin/bitcoin/pull/36895/changes/0c981e75a9e7e352d1c0f08118596ea91a9fa102) _script: store witness stacks as their serialization_: The `catch` covers decoding failure, so I’d include the `SpanReader` construction in the `try` as well - that also lets us drop the extra scope. <details> <summary>Move SpanReader inside the try blocks</summary> ```diff diff --git a/src/test/fuzz/script_witness.cpp b/src/test/fuzz/script_witness.cpp index 5a03b561f0..ec7045f65d 100644 --- a/src/test/fuzz/script_witness.cpp +++ b/src/test/fuzz/script_witness.cpp @@ -21,29 +21,25 @@ FUZZ_TARGET(script_witness_deserialize) // Deserialize the input as a vector of vector of unsigned chars. size_t stack_left{0}; std::optional<std::vector<std::vector<unsigned char>>> stack; - { + try { SpanReader reader{buffer}; - try { - std::vector<std::vector<unsigned char>> tmp; - reader >> tmp; - stack = std::move(tmp); - stack_left = reader.size(); - } catch (const std::ios_base::failure&) { - } + std::vector<std::vector<unsigned char>> tmp; + reader >> tmp; + stack = std::move(tmp); + stack_left = reader.size(); + } catch (const std::ios_base::failure&) { } // Start over, and deserialize as a CScriptWitness. std::optional<CScriptWitness> witness; size_t witness_left{0}; - { + try { SpanReader reader{buffer}; - try { - CScriptWitness tmp; - reader >> tmp; - witness = std::move(tmp); - witness_left = reader.size(); - } catch (const std::ios_base::failure&) { - } + CScriptWitness tmp; + reader >> tmp; + witness = std::move(tmp); + witness_left = reader.size(); + } catch (const std::ios_base::failure&) { } // Check whether deserialization success matches between them. ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-22 20:13:19 +00:00

49c0f21 test: check CScriptWitness against the vector of vectors it represents:

There are two limits of 64 here. Are they meant to coincide? My understanding is that they bound the repeated linear work from indexed reads. If so, consider extracting a shared constant.

Extract a shared MAX_INDEXED_READS constant
diff --git a/src/test/fuzz/script_witness.cpp b/src/test/fuzz/script_witness.cpp
index 5a03b561f0..3ea44643eb 100644
--- a/src/test/fuzz/script_witness.cpp
+++ b/src/test/fuzz/script_witness.cpp
@@ -68,13 +68,14 @@ FUZZ_TARGET(script_witness_deserialize)
         assert(std::ranges::equal(CScriptWitness{*witness}.back(), stack->back()));
         // Compare elements accessed by index: all of them if there are few (as indexing may take time linear in the
         // index), and otherwise those at positions read from the rest of the input, after the serialized witness.
-        if (stack->size() <= 64) {
+        constexpr size_t MAX_INDEXED_READS{64}; // Arbitrary cap because checking every index would take quadratic time.
+        if (stack->size() <= MAX_INDEXED_READS) {
             for (size_t i = 0; i < stack->size(); ++i) {
                 assert(std::ranges::equal((*witness)[i], (*stack)[i]));
             }
         } else {
             FuzzedDataProvider provider{buffer.data() + buffer.size() - witness_left, witness_left};
-            LIMITED_WHILE(provider.remaining_bytes() > 0, 64) {
+            LIMITED_WHILE(provider.remaining_bytes() > 0, MAX_INDEXED_READS) {
                 const auto i = provider.ConsumeIntegralInRange<size_t>(0, stack->size() - 1);
                 assert(std::ranges::equal((*witness)[i], (*stack)[i]));
             }
> [49c0f21](https://github.com/bitcoin/bitcoin/pull/36895/changes/49c0f21971050b24cecde56bdb42653af3910fc6) _test: check CScriptWitness against the vector of vectors it represents_: There are two limits of 64 here. Are they meant to coincide? My understanding is that they bound the repeated linear work from indexed reads. If so, consider extracting a shared constant. <details> <summary>Extract a shared MAX_INDEXED_READS constant</summary> ```diff diff --git a/src/test/fuzz/script_witness.cpp b/src/test/fuzz/script_witness.cpp index 5a03b561f0..3ea44643eb 100644 --- a/src/test/fuzz/script_witness.cpp +++ b/src/test/fuzz/script_witness.cpp @@ -68,13 +68,14 @@ FUZZ_TARGET(script_witness_deserialize) assert(std::ranges::equal(CScriptWitness{*witness}.back(), stack->back())); // Compare elements accessed by index: all of them if there are few (as indexing may take time linear in the // index), and otherwise those at positions read from the rest of the input, after the serialized witness. - if (stack->size() <= 64) { + constexpr size_t MAX_INDEXED_READS{64}; // Arbitrary cap because checking every index would take quadratic time. + if (stack->size() <= MAX_INDEXED_READS) { for (size_t i = 0; i < stack->size(); ++i) { assert(std::ranges::equal((*witness)[i], (*stack)[i])); } } else { FuzzedDataProvider provider{buffer.data() + buffer.size() - witness_left, witness_left}; - LIMITED_WHILE(provider.remaining_bytes() > 0, 64) { + LIMITED_WHILE(provider.remaining_bytes() > 0, MAX_INDEXED_READS) { const auto i = provider.ConsumeIntegralInRange<size_t>(0, stack->size() - 1); assert(std::ranges::equal((*witness)[i], (*stack)[i])); } ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-22 19:51:22 +00:00

49c0f21 test: check CScriptWitness against the vector of vectors it represents:

What if both serializers write the same wrong byte? We still have buffer here, so I’d also compare the result with the part of the input we actually read.

Use the consumed prefix and the remaining index bytes
diff --git a/src/test/fuzz/script_witness.cpp b/src/test/fuzz/script_witness.cpp
index 5a03b561f0..9e83f760ca 100644
--- a/src/test/fuzz/script_witness.cpp
+++ b/src/test/fuzz/script_witness.cpp
@@ -75,3 +75,3 @@ FUZZ_TARGET(script_witness_deserialize)
         } else {
-            FuzzedDataProvider provider{buffer.data() + buffer.size() - witness_left, witness_left};
+            FuzzedDataProvider provider{buffer.last(witness_left).data(), witness_left};
             LIMITED_WHILE(provider.remaining_bytes() > 0, 64) {
@@ -88,2 +88,3 @@ FUZZ_TARGET(script_witness_deserialize)
     assert(ser_stack == ser_witness);
+    assert(std::ranges::equal(ser_witness, buffer.first(buffer.size() - witness_left)));
     assert(::GetSerializeSize(*witness) == ser_stack.size());
> [49c0f21](https://github.com/bitcoin/bitcoin/pull/36895/changes/49c0f21971050b24cecde56bdb42653af3910fc6) _test: check CScriptWitness against the vector of vectors it represents_: What if both serializers write the same wrong byte? We still have `buffer` here, so I’d also compare the result with the part of the input we actually read. <details> <summary>Use the consumed prefix and the remaining index bytes</summary> ```diff diff --git a/src/test/fuzz/script_witness.cpp b/src/test/fuzz/script_witness.cpp index 5a03b561f0..9e83f760ca 100644 --- a/src/test/fuzz/script_witness.cpp +++ b/src/test/fuzz/script_witness.cpp @@ -75,3 +75,3 @@ FUZZ_TARGET(script_witness_deserialize) } else { - FuzzedDataProvider provider{buffer.data() + buffer.size() - witness_left, witness_left}; + FuzzedDataProvider provider{buffer.last(witness_left).data(), witness_left}; LIMITED_WHILE(provider.remaining_bytes() > 0, 64) { @@ -88,2 +88,3 @@ FUZZ_TARGET(script_witness_deserialize) assert(ser_stack == ser_witness); + assert(std::ranges::equal(ser_witness, buffer.first(buffer.size() - witness_left))); assert(::GetSerializeSize(*witness) == ser_stack.size()); ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-22 19:50:48 +00:00

0c981e7 script: store witness stacks as their serialization:

The empty case is a no-op here since an unsigned size is always >= 0.

Assert DynamicMemoryUsage() == 0 for empty witnesses
diff --git a/src/test/fuzz/script_witness.cpp b/src/test/fuzz/script_witness.cpp
index 5a03b561f0..ca5051852f 100644
--- a/src/test/fuzz/script_witness.cpp
+++ b/src/test/fuzz/script_witness.cpp
@@ -3,14 +3,18 @@
 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
 
 #include <script/script.h>
+#include <serialize.h>
 #include <streams.h>
 #include <test/fuzz/FuzzedDataProvider.h>
 #include <test/fuzz/fuzz.h>
 
 #include <algorithm>
 #include <cassert>
+#include <cstddef>
 #include <ios>
 #include <optional>
+#include <span>
+#include <utility>
 #include <vector>
 
 /** Deserialization of a CScriptWitness behaves exactly like that of a
@@ -88,5 +92,9 @@ FUZZ_TARGET(script_witness_deserialize)
     assert(ser_stack == ser_witness);
     assert(::GetSerializeSize(*witness) == ser_stack.size());
     // Sanity check memory usage.
-    assert(witness->DynamicMemoryUsage() >= (stack->empty() ? 0 : ser_stack.size()));
+    if (stack->empty()) {
+        assert(witness->DynamicMemoryUsage() == 0);
+    } else {
+        assert(witness->DynamicMemoryUsage() >= ser_stack.size());
+    }
 }
> [0c981e7](https://github.com/bitcoin/bitcoin/pull/36895/changes/0c981e75a9e7e352d1c0f08118596ea91a9fa102) _script: store witness stacks as their serialization_: The empty case is a no-op here since an unsigned size is always `>= 0`. <details> <summary>Assert DynamicMemoryUsage() == 0 for empty witnesses</summary> ```diff diff --git a/src/test/fuzz/script_witness.cpp b/src/test/fuzz/script_witness.cpp index 5a03b561f0..ca5051852f 100644 --- a/src/test/fuzz/script_witness.cpp +++ b/src/test/fuzz/script_witness.cpp @@ -3,14 +3,18 @@ // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <script/script.h> +#include <serialize.h> #include <streams.h> #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <algorithm> #include <cassert> +#include <cstddef> #include <ios> #include <optional> +#include <span> +#include <utility> #include <vector> /** Deserialization of a CScriptWitness behaves exactly like that of a @@ -88,5 +92,9 @@ FUZZ_TARGET(script_witness_deserialize) assert(ser_stack == ser_witness); assert(::GetSerializeSize(*witness) == ser_stack.size()); // Sanity check memory usage. - assert(witness->DynamicMemoryUsage() >= (stack->empty() ? 0 : ser_stack.size())); + if (stack->empty()) { + assert(witness->DynamicMemoryUsage() == 0); + } else { + assert(witness->DynamicMemoryUsage() >= ser_stack.size()); + } } ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-22 21:08:01 +00:00

0c981e7 script: store witness stacks as their serialization:

AsWit() currently unpacks and rebuilds the witness for every item. We could pack it once in Test() and copy just scriptSig to include any pending push.

Accumulate a vector in TestBuilder and pack in Test()
diff --git a/src/test/script_tests.cpp b/src/test/script_tests.cpp
index 9afeed3759..68a851bb44 100644
--- a/src/test/script_tests.cpp
+++ b/src/test/script_tests.cpp
@@ -33,6 +33,7 @@
 
 #include <cstdint>
 #include <string>
+#include <utility>
 #include <vector>
 
 // Uncomment if you want to output updated JSON tests.
@@ -228,7 +229,7 @@ private:
     CScript redeemscript;
     //! The Witness embedded script
     CScript witscript;
-    CScriptWitness scriptWitness;
+    std::vector<std::vector<unsigned char>> witness_stack;
     CTransactionRef creditTx;
     CMutableTransaction spendTx;
     bool havePush{false};
@@ -373,19 +374,16 @@ public:
 
     TestBuilder& Test(ScriptTest& test)
     {
-        TestBuilder copy = *this; // Make a copy so we can rollback the push.
-        DoPush();
-        test.DoTest(creditTx->vout[0].scriptPubKey, spendTx.vin[0].scriptSig, scriptWitness, flags, comment, scriptError, nValue);
-        *this = copy;
+        CScript script_sig{spendTx.vin[0].scriptSig};
+        if (havePush) script_sig << push;
+        test.DoTest(creditTx->vout[0].scriptPubKey, script_sig, CScriptWitness{witness_stack}, flags, comment, scriptError, nValue);
         return *this;
     }
 
     TestBuilder& AsWit()
     {
         assert(havePush);
-        auto stack = scriptWitness.ToVectors();
-        stack.push_back(push);
-        scriptWitness = CScriptWitness{stack};
+        witness_stack.push_back(std::move(push));
         havePush = false;
         return *this;
     }
@@ -394,9 +392,9 @@ public:
     {
         DoPush();
         UniValue array(UniValue::VARR);
-        if (!scriptWitness.empty()) {
+        if (witness_stack.size() > 0) {
             UniValue wit(UniValue::VARR);
-            for (const auto element : scriptWitness) {
+            for (const auto& element : witness_stack) {
                 wit.push_back(HexStr(element));
             }
             wit.push_back(ValueFromAmount(nValue));
> [0c981e7](https://github.com/bitcoin/bitcoin/pull/36895/changes/0c981e75a9e7e352d1c0f08118596ea91a9fa102) _script: store witness stacks as their serialization_: `AsWit()` currently unpacks and rebuilds the witness for every item. We could pack it once in `Test()` and copy just `scriptSig` to include any pending push. <details> <summary>Accumulate a vector in TestBuilder and pack in Test()</summary> ```diff diff --git a/src/test/script_tests.cpp b/src/test/script_tests.cpp index 9afeed3759..68a851bb44 100644 --- a/src/test/script_tests.cpp +++ b/src/test/script_tests.cpp @@ -33,6 +33,7 @@ #include <cstdint> #include <string> +#include <utility> #include <vector> // Uncomment if you want to output updated JSON tests. @@ -228,7 +229,7 @@ private: CScript redeemscript; //! The Witness embedded script CScript witscript; - CScriptWitness scriptWitness; + std::vector<std::vector<unsigned char>> witness_stack; CTransactionRef creditTx; CMutableTransaction spendTx; bool havePush{false}; @@ -373,19 +374,16 @@ public: TestBuilder& Test(ScriptTest& test) { - TestBuilder copy = *this; // Make a copy so we can rollback the push. - DoPush(); - test.DoTest(creditTx->vout[0].scriptPubKey, spendTx.vin[0].scriptSig, scriptWitness, flags, comment, scriptError, nValue); - *this = copy; + CScript script_sig{spendTx.vin[0].scriptSig}; + if (havePush) script_sig << push; + test.DoTest(creditTx->vout[0].scriptPubKey, script_sig, CScriptWitness{witness_stack}, flags, comment, scriptError, nValue); return *this; } TestBuilder& AsWit() { assert(havePush); - auto stack = scriptWitness.ToVectors(); - stack.push_back(push); - scriptWitness = CScriptWitness{stack}; + witness_stack.push_back(std::move(push)); havePush = false; return *this; } @@ -394,9 +392,9 @@ public: { DoPush(); UniValue array(UniValue::VARR); - if (!scriptWitness.empty()) { + if (witness_stack.size() > 0) { UniValue wit(UniValue::VARR); - for (const auto element : scriptWitness) { + for (const auto& element : witness_stack) { wit.push_back(HexStr(element)); } wit.push_back(ValueFromAmount(nValue)); ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-22 20:13:26 +00:00

Alongside your cases for the item count, I’d put each boundary length at both ends of a witness. That exercises front() and back() on every run and keeps the random coverage.

Check both ends at every boundary length
diff --git a/src/test/script_tests.cpp b/src/test/script_tests.cpp
index 9afeed3759..62cbec1f1e 100644
--- a/src/test/script_tests.cpp
+++ b/src/test/script_tests.cpp
@@ -1740,6 +1740,13 @@ BOOST_AUTO_TEST_CASE(script_witness_representation)
     // Element counts and sizes around CompactSize encoding boundaries.
     static constexpr size_t COUNTS[]{0, 1, 2, 3, 252, 253, 254};
     static constexpr size_t SIZES[]{0, 1, 32, 252, 253, 65535, 65536};
+    for (const size_t size : SIZES) {
+        const std::vector<unsigned char> first(size, 0x01);
+        const std::vector<unsigned char> last(size, 0x02);
+        const CScriptWitness witness{{first, {0xff}, last}};
+        BOOST_CHECK(std::ranges::equal(witness.front(), first));
+        BOOST_CHECK(std::ranges::equal(witness.back(), last));
+    }
     for (const size_t count : COUNTS) {
         for (int iter = 0; iter < 3; ++iter) {
             std::vector<std::vector<unsigned char>> stack(count);
Alongside [your cases for the item count](https://github.com/bitcoin/bitcoin/pull/36895#discussion_r4630270818), I’d put each boundary length at both ends of a witness. That exercises `front()` and `back()` on every run and keeps the random coverage. <details> <summary>Check both ends at every boundary length</summary> ```diff diff --git a/src/test/script_tests.cpp b/src/test/script_tests.cpp index 9afeed3759..62cbec1f1e 100644 --- a/src/test/script_tests.cpp +++ b/src/test/script_tests.cpp @@ -1740,6 +1740,13 @@ BOOST_AUTO_TEST_CASE(script_witness_representation) // Element counts and sizes around CompactSize encoding boundaries. static constexpr size_t COUNTS[]{0, 1, 2, 3, 252, 253, 254}; static constexpr size_t SIZES[]{0, 1, 32, 252, 253, 65535, 65536}; + for (const size_t size : SIZES) { + const std::vector<unsigned char> first(size, 0x01); + const std::vector<unsigned char> last(size, 0x02); + const CScriptWitness witness{{first, {0xff}, last}}; + BOOST_CHECK(std::ranges::equal(witness.front(), first)); + BOOST_CHECK(std::ranges::equal(witness.back(), last)); + } for (const size_t count : COUNTS) { for (int iter = 0; iter < 3; ++iter) { std::vector<std::vector<unsigned char>> stack(count); ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-22 20:13:13 +00:00

49c0f21 test: check CScriptWitness against the vector of vectors it represents:

For consistency, cover postfix increment as well, including the returned iterator.

Cover Iterator::operator++(int)
diff --git a/src/test/script_tests.cpp b/src/test/script_tests.cpp
index cc6fa3843a..60855247f6 100644
--- a/src/test/script_tests.cpp
+++ b/src/test/script_tests.cpp
@@ -1756,6 +1756,9 @@ BOOST_AUTO_TEST_CASE(script_witness_representation)
             if (!stack.empty()) {
                 BOOST_CHECK(std::ranges::equal(witness.front(), stack.front()));
                 BOOST_CHECK(std::ranges::equal(witness.back(), stack.back()));
+                auto it{witness.begin()};
+                BOOST_CHECK(std::ranges::equal(*it++, stack.front()));
+                BOOST_CHECK_EQUAL(std::distance(it, witness.end()), (std::ptrdiff_t)stack.size() - 1);
                 for (size_t i = 0; i < stack.size(); ++i) BOOST_CHECK(std::ranges::equal(witness[i], stack[i]));
             }
             const auto spans = witness.ToSpans();
> [49c0f21](https://github.com/bitcoin/bitcoin/pull/36895/changes/49c0f21971050b24cecde56bdb42653af3910fc6) _test: check CScriptWitness against the vector of vectors it represents_: For consistency, cover postfix increment as well, including the returned iterator. <details> <summary>Cover Iterator::operator++(int)</summary> ```diff diff --git a/src/test/script_tests.cpp b/src/test/script_tests.cpp index cc6fa3843a..60855247f6 100644 --- a/src/test/script_tests.cpp +++ b/src/test/script_tests.cpp @@ -1756,6 +1756,9 @@ BOOST_AUTO_TEST_CASE(script_witness_representation) if (!stack.empty()) { BOOST_CHECK(std::ranges::equal(witness.front(), stack.front())); BOOST_CHECK(std::ranges::equal(witness.back(), stack.back())); + auto it{witness.begin()}; + BOOST_CHECK(std::ranges::equal(*it++, stack.front())); + BOOST_CHECK_EQUAL(std::distance(it, witness.end()), (std::ptrdiff_t)stack.size() - 1); for (size_t i = 0; i < stack.size(); ++i) BOOST_CHECK(std::ranges::equal(witness[i], stack[i])); } const auto spans = witness.ToSpans(); ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-22 20:13:07 +00:00

49c0f21 test: check CScriptWitness against the vector of vectors it represents:

When both the input and deser are empty, the test would pass even if the read did nothing. Starting deser with one item covers the case where the read clears it and checks replacement with a nonempty stack in the same loop.

Start deserialization from a populated witness
diff --git a/src/test/script_tests.cpp b/src/test/script_tests.cpp
index cc6fa3843a..2817794afa 100644
--- a/src/test/script_tests.cpp
+++ b/src/test/script_tests.cpp
@@ -1768,7 +1768,7 @@ BOOST_AUTO_TEST_CASE(script_witness_representation)
             VectorWriter{ser_wit, 0, witness};
             BOOST_CHECK(ser_vec == ser_wit);
             BOOST_CHECK_EQUAL(::GetSerializeSize(witness), ser_vec.size());
-            CScriptWitness deser;
+            CScriptWitness deser{{{0xff}}};
             SpanReader{ser_vec} >> deser;
             BOOST_CHECK(deser == witness);
             if (!stack.empty()) BOOST_CHECK(std::ranges::equal(deser.back(), stack.back()));
> [49c0f21](https://github.com/bitcoin/bitcoin/pull/36895/changes/49c0f21971050b24cecde56bdb42653af3910fc6) _test: check CScriptWitness against the vector of vectors it represents_: When both the input and `deser` are empty, the test would pass even if the read did nothing. Starting `deser` with one item covers [the case where the read clears it](https://github.com/bitcoin/bitcoin/pull/36895#discussion_r4630270818) and checks replacement with a nonempty stack in the same loop. <details> <summary>Start deserialization from a populated witness</summary> ```diff diff --git a/src/test/script_tests.cpp b/src/test/script_tests.cpp index cc6fa3843a..2817794afa 100644 --- a/src/test/script_tests.cpp +++ b/src/test/script_tests.cpp @@ -1768,7 +1768,7 @@ BOOST_AUTO_TEST_CASE(script_witness_representation) VectorWriter{ser_wit, 0, witness}; BOOST_CHECK(ser_vec == ser_wit); BOOST_CHECK_EQUAL(::GetSerializeSize(witness), ser_vec.size()); - CScriptWitness deser; + CScriptWitness deser{{{0xff}}}; SpanReader{ser_vec} >> deser; BOOST_CHECK(deser == witness); if (!stack.empty()) BOOST_CHECK(std::ranges::equal(deser.back(), stack.back())); ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-22 20:30:34 +00:00

0c981e7 script: store witness stacks as their serialization:

We can construct the witnesses directly in package_submission_tests and block_malleation, avoiding the temporary bad_witness and the extra conversion to vectors.

Construct the test witnesses directly
diff --git a/src/test/txpackage_tests.cpp b/src/test/txpackage_tests.cpp
index d1bf3cb04b..327e413be3 100644
--- a/src/test/txpackage_tests.cpp
+++ b/src/test/txpackage_tests.cpp
@@ -419,9 +419,8 @@ BOOST_AUTO_TEST_CASE(package_submission_tests)
     // Parent and child package where transactions are invalid for reasons other than fee and
     // missing inputs, so the package validation isn't expected to happen.
     {
-        CScriptWitness bad_witness{{std::vector<unsigned char>(1)}};
         CMutableTransaction mtx_parent_invalid{mtx_parent};
-        mtx_parent_invalid.vin[0].scriptWitness = bad_witness;
+        mtx_parent_invalid.vin[0].scriptWitness = CScriptWitness{{{0}}};
         CTransactionRef tx_parent_invalid = MakeTransactionRef(mtx_parent_invalid);
         Package package_invalid_parent{tx_parent_invalid, tx_child};
         auto result_quit_early = ProcessNewPackage(m_node.chainman->ActiveChainstate(), *m_node.mempool,
diff --git a/src/test/validation_tests.cpp b/src/test/validation_tests.cpp
index ca58340b36..e4727914c6 100644
--- a/src/test/validation_tests.cpp
+++ b/src/test/validation_tests.cpp
@@ -332,10 +332,7 @@ BOOST_AUTO_TEST_CASE(block_malleation)
         // Malleating witnesses should be caught by `IsBlockMutated`.
         {
             CMutableTransaction mtx{*block.vtx[1]};
-            assert(!mtx.vin[0].scriptWitness[0].empty());
-            auto stack = mtx.vin[0].scriptWitness.ToVectors();
-            ++stack[0][0];
-            mtx.vin[0].scriptWitness = CScriptWitness{stack};
+            mtx.vin[0].scriptWitness = CScriptWitness{{{1}}};
             block.vtx[1] = MakeTransactionRef(mtx);
         }
         // Without also updating the witness commitment, the merkle root should
> [0c981e7](https://github.com/bitcoin/bitcoin/pull/36895/changes/0c981e75a9e7e352d1c0f08118596ea91a9fa102) _script: store witness stacks as their serialization_: We can construct the witnesses directly in `package_submission_tests` and `block_malleation`, avoiding the temporary `bad_witness` and the extra conversion to vectors. <details> <summary>Construct the test witnesses directly</summary> ```diff diff --git a/src/test/txpackage_tests.cpp b/src/test/txpackage_tests.cpp index d1bf3cb04b..327e413be3 100644 --- a/src/test/txpackage_tests.cpp +++ b/src/test/txpackage_tests.cpp @@ -419,9 +419,8 @@ BOOST_AUTO_TEST_CASE(package_submission_tests) // Parent and child package where transactions are invalid for reasons other than fee and // missing inputs, so the package validation isn't expected to happen. { - CScriptWitness bad_witness{{std::vector<unsigned char>(1)}}; CMutableTransaction mtx_parent_invalid{mtx_parent}; - mtx_parent_invalid.vin[0].scriptWitness = bad_witness; + mtx_parent_invalid.vin[0].scriptWitness = CScriptWitness{{{0}}}; CTransactionRef tx_parent_invalid = MakeTransactionRef(mtx_parent_invalid); Package package_invalid_parent{tx_parent_invalid, tx_child}; auto result_quit_early = ProcessNewPackage(m_node.chainman->ActiveChainstate(), *m_node.mempool, diff --git a/src/test/validation_tests.cpp b/src/test/validation_tests.cpp index ca58340b36..e4727914c6 100644 --- a/src/test/validation_tests.cpp +++ b/src/test/validation_tests.cpp @@ -332,10 +332,7 @@ BOOST_AUTO_TEST_CASE(block_malleation) // Malleating witnesses should be caught by `IsBlockMutated`. { CMutableTransaction mtx{*block.vtx[1]}; - assert(!mtx.vin[0].scriptWitness[0].empty()); - auto stack = mtx.vin[0].scriptWitness.ToVectors(); - ++stack[0][0]; - mtx.vin[0].scriptWitness = CScriptWitness{stack}; + mtx.vin[0].scriptWitness = CScriptWitness{{{1}}}; block.vtx[1] = MakeTransactionRef(mtx); } // Without also updating the witness commitment, the merkle root should ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-22 20:36:43 +00:00

0c981e7 script: store witness stacks as their serialization:

A CTxIn::HasWitness() predicate would avoid the repeated negations and let us pass &CTxIn::HasWitness directly to any_of and all_of.
It's possible some parent methods could also become inlinable in that case...

Share the input witness predicate
diff --git a/src/core_io.cpp b/src/core_io.cpp
index 88f2b1f870..d230b3cb54 100644
--- a/src/core_io.cpp
+++ b/src/core_io.cpp
@@ -463,7 +463,7 @@ void TxToUniv(const CTransaction& tx, const uint256& block_hash, UniValue& entry
             o.pushKV("hex", HexStr(txin.scriptSig));
             in.pushKV("scriptSig", std::move(o));
         }
-        if (!tx.vin[i].scriptWitness.empty()) {
+        if (tx.vin[i].HasWitness()) {
             UniValue txinwitness(UniValue::VARR);
             txinwitness.reserve(tx.vin[i].scriptWitness.size());
             for (const auto item : tx.vin[i].scriptWitness) {
diff --git a/src/primitives/transaction.cpp b/src/primitives/transaction.cpp
index 942f708426..517c550a48 100644
--- a/src/primitives/transaction.cpp
+++ b/src/primitives/transaction.cpp
@@ -73,9 +73,7 @@ Txid CMutableTransaction::GetHash() const
 
 bool CTransaction::ComputeHasWitness() const
 {
-    return std::any_of(vin.begin(), vin.end(), [](const auto& input) {
-        return !input.scriptWitness.empty();
-    });
+    return std::ranges::any_of(vin, &CTxIn::HasWitness);
 }
 
 Txid CTransaction::ComputeHash() const
diff --git a/src/primitives/transaction.h b/src/primitives/transaction.h
index dc173134fe..371bdc6d37 100644
--- a/src/primitives/transaction.h
+++ b/src/primitives/transaction.h
@@ -122,6 +122,8 @@ public:
     explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), uint32_t nSequenceIn=SEQUENCE_FINAL);
     CTxIn(Txid hashPrevTx, uint32_t nOut, CScript scriptSigIn=CScript(), uint32_t nSequenceIn=SEQUENCE_FINAL);
 
+    bool HasWitness() const noexcept { return !scriptWitness.empty(); }
+
     SERIALIZE_METHODS(CTxIn, obj) { READWRITE(obj.prevout, obj.scriptSig, obj.nSequence); }
 
     friend bool operator==(const CTxIn& a, const CTxIn& b)
@@ -405,12 +407,7 @@ struct CMutableTransaction
 
     bool HasWitness() const
     {
-        for (size_t i = 0; i < vin.size(); i++) {
-            if (!vin[i].scriptWitness.empty()) {
-                return true;
-            }
-        }
-        return false;
+        return std::ranges::any_of(vin, &CTxIn::HasWitness);
     }
 };
 
diff --git a/src/psbt.h b/src/psbt.h
index 86bcf29540..b0147ab64d 100644
--- a/src/psbt.h
+++ b/src/psbt.h
@@ -1399,7 +1399,7 @@ public:
                     UnserializeFromVector(s, TX_NO_WITNESS(*tx));
                     // Make sure that all scriptSigs and scriptWitnesses are empty
                     for (const CTxIn& txin : tx->vin) {
-                        if (!txin.scriptSig.empty() || !txin.scriptWitness.empty()) {
+                        if (!txin.scriptSig.empty() || txin.HasWitness()) {
                             throw std::ios_base::failure("Unsigned tx does not have empty scriptSigs and scriptWitnesses.");
                         }
                     }
diff --git a/src/rpc/rawtransaction.cpp b/src/rpc/rawtransaction.cpp
index a3307bfc82..288742a3fe 100644
--- a/src/rpc/rawtransaction.cpp
+++ b/src/rpc/rawtransaction.cpp
@@ -1805,7 +1805,7 @@ static RPCMethod converttopsbt()
 
     // Remove all scriptSigs and scriptWitnesses from inputs
     for (CTxIn& input : tx.vin) {
-        if ((!input.scriptSig.empty() || !input.scriptWitness.empty()) && !permitsigdata) {
+        if ((!input.scriptSig.empty() || input.HasWitness()) && !permitsigdata) {
             throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Inputs must not have scriptSigs and scriptWitnesses");
         }
         input.scriptSig.clear();
diff --git a/src/script/interpreter.cpp b/src/script/interpreter.cpp
index 591f06b5f6..ccfd17d596 100644
--- a/src/script/interpreter.cpp
+++ b/src/script/interpreter.cpp
@@ -1420,7 +1420,7 @@ void PrecomputedTransactionData::Init(const T& txTo, std::vector<CTxOut>&& spent
     bool uses_bip143_segwit = force;
     bool uses_bip341_taproot = force;
     for (size_t inpos = 0; inpos < txTo.vin.size() && !(uses_bip143_segwit && uses_bip341_taproot); ++inpos) {
-        if (!txTo.vin[inpos].scriptWitness.empty()) {
+        if (txTo.vin[inpos].HasWitness()) {
             if (m_spent_outputs_ready && m_spent_outputs[inpos].scriptPubKey.size() == 2 + WITNESS_V1_TAPROOT_SIZE &&
                 m_spent_outputs[inpos].scriptPubKey[0] == OP_1) {
                 // Treat every witness-bearing spend with 34-byte scriptPubKey that starts with OP_1 as a Taproot
diff --git a/src/script/sign.cpp b/src/script/sign.cpp
index 6751e171b4..9d5eecb7a8 100644
--- a/src/script/sign.cpp
+++ b/src/script/sign.cpp
@@ -1066,7 +1066,7 @@ bool SignTransaction(CMutableTransaction& mtx, const SigningProvider* keystore,
         UpdateInput(txin, sigdata);
 
         // amount must be specified for valid segwit signature
-        if (amount == MAX_MONEY && !txin.scriptWitness.empty()) {
+        if (amount == MAX_MONEY && txin.HasWitness()) {
             input_errors[i] = _("Missing amount");
             continue;
         }
diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp
index de7da017e0..dea6aa4a9e 100644
--- a/src/wallet/wallet.cpp
+++ b/src/wallet/wallet.cpp
@@ -737,7 +737,7 @@ std::set<CWalletTx*, WalletTxOrderComparator> CWallet::GetMalleatedVariants(cons
     if (wtx.IsCoinBase()) return txs;
 
     // Only transactions that have non-witness inputs can be malleated
-    if (std::ranges::none_of(wtx.GetTx()->vin, [](const CTxIn& in) { return in.scriptWitness.empty(); })) {
+    if (std::ranges::all_of(wtx.GetTx()->vin, &CTxIn::HasWitness)) {
         return txs;
     }
 
> [0c981e7](https://github.com/bitcoin/bitcoin/pull/36895/changes/0c981e75a9e7e352d1c0f08118596ea91a9fa102) _script: store witness stacks as their serialization_: A `CTxIn::HasWitness()` predicate would avoid the repeated negations and let us pass `&CTxIn::HasWitness` directly to `any_of` and `all_of`. It's possible some parent methods could also become inlinable in that case... <details> <summary>Share the input witness predicate</summary> ```diff diff --git a/src/core_io.cpp b/src/core_io.cpp index 88f2b1f870..d230b3cb54 100644 --- a/src/core_io.cpp +++ b/src/core_io.cpp @@ -463,7 +463,7 @@ void TxToUniv(const CTransaction& tx, const uint256& block_hash, UniValue& entry o.pushKV("hex", HexStr(txin.scriptSig)); in.pushKV("scriptSig", std::move(o)); } - if (!tx.vin[i].scriptWitness.empty()) { + if (tx.vin[i].HasWitness()) { UniValue txinwitness(UniValue::VARR); txinwitness.reserve(tx.vin[i].scriptWitness.size()); for (const auto item : tx.vin[i].scriptWitness) { diff --git a/src/primitives/transaction.cpp b/src/primitives/transaction.cpp index 942f708426..517c550a48 100644 --- a/src/primitives/transaction.cpp +++ b/src/primitives/transaction.cpp @@ -73,9 +73,7 @@ Txid CMutableTransaction::GetHash() const bool CTransaction::ComputeHasWitness() const { - return std::any_of(vin.begin(), vin.end(), [](const auto& input) { - return !input.scriptWitness.empty(); - }); + return std::ranges::any_of(vin, &CTxIn::HasWitness); } Txid CTransaction::ComputeHash() const diff --git a/src/primitives/transaction.h b/src/primitives/transaction.h index dc173134fe..371bdc6d37 100644 --- a/src/primitives/transaction.h +++ b/src/primitives/transaction.h @@ -122,6 +122,8 @@ public: explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), uint32_t nSequenceIn=SEQUENCE_FINAL); CTxIn(Txid hashPrevTx, uint32_t nOut, CScript scriptSigIn=CScript(), uint32_t nSequenceIn=SEQUENCE_FINAL); + bool HasWitness() const noexcept { return !scriptWitness.empty(); } + SERIALIZE_METHODS(CTxIn, obj) { READWRITE(obj.prevout, obj.scriptSig, obj.nSequence); } friend bool operator==(const CTxIn& a, const CTxIn& b) @@ -405,12 +407,7 @@ struct CMutableTransaction bool HasWitness() const { - for (size_t i = 0; i < vin.size(); i++) { - if (!vin[i].scriptWitness.empty()) { - return true; - } - } - return false; + return std::ranges::any_of(vin, &CTxIn::HasWitness); } }; diff --git a/src/psbt.h b/src/psbt.h index 86bcf29540..b0147ab64d 100644 --- a/src/psbt.h +++ b/src/psbt.h @@ -1399,7 +1399,7 @@ public: UnserializeFromVector(s, TX_NO_WITNESS(*tx)); // Make sure that all scriptSigs and scriptWitnesses are empty for (const CTxIn& txin : tx->vin) { - if (!txin.scriptSig.empty() || !txin.scriptWitness.empty()) { + if (!txin.scriptSig.empty() || txin.HasWitness()) { throw std::ios_base::failure("Unsigned tx does not have empty scriptSigs and scriptWitnesses."); } } diff --git a/src/rpc/rawtransaction.cpp b/src/rpc/rawtransaction.cpp index a3307bfc82..288742a3fe 100644 --- a/src/rpc/rawtransaction.cpp +++ b/src/rpc/rawtransaction.cpp @@ -1805,7 +1805,7 @@ static RPCMethod converttopsbt() // Remove all scriptSigs and scriptWitnesses from inputs for (CTxIn& input : tx.vin) { - if ((!input.scriptSig.empty() || !input.scriptWitness.empty()) && !permitsigdata) { + if ((!input.scriptSig.empty() || input.HasWitness()) && !permitsigdata) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Inputs must not have scriptSigs and scriptWitnesses"); } input.scriptSig.clear(); diff --git a/src/script/interpreter.cpp b/src/script/interpreter.cpp index 591f06b5f6..ccfd17d596 100644 --- a/src/script/interpreter.cpp +++ b/src/script/interpreter.cpp @@ -1420,7 +1420,7 @@ void PrecomputedTransactionData::Init(const T& txTo, std::vector<CTxOut>&& spent bool uses_bip143_segwit = force; bool uses_bip341_taproot = force; for (size_t inpos = 0; inpos < txTo.vin.size() && !(uses_bip143_segwit && uses_bip341_taproot); ++inpos) { - if (!txTo.vin[inpos].scriptWitness.empty()) { + if (txTo.vin[inpos].HasWitness()) { if (m_spent_outputs_ready && m_spent_outputs[inpos].scriptPubKey.size() == 2 + WITNESS_V1_TAPROOT_SIZE && m_spent_outputs[inpos].scriptPubKey[0] == OP_1) { // Treat every witness-bearing spend with 34-byte scriptPubKey that starts with OP_1 as a Taproot diff --git a/src/script/sign.cpp b/src/script/sign.cpp index 6751e171b4..9d5eecb7a8 100644 --- a/src/script/sign.cpp +++ b/src/script/sign.cpp @@ -1066,7 +1066,7 @@ bool SignTransaction(CMutableTransaction& mtx, const SigningProvider* keystore, UpdateInput(txin, sigdata); // amount must be specified for valid segwit signature - if (amount == MAX_MONEY && !txin.scriptWitness.empty()) { + if (amount == MAX_MONEY && txin.HasWitness()) { input_errors[i] = _("Missing amount"); continue; } diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp index de7da017e0..dea6aa4a9e 100644 --- a/src/wallet/wallet.cpp +++ b/src/wallet/wallet.cpp @@ -737,7 +737,7 @@ std::set<CWalletTx*, WalletTxOrderComparator> CWallet::GetMalleatedVariants(cons if (wtx.IsCoinBase()) return txs; // Only transactions that have non-witness inputs can be malleated - if (std::ranges::none_of(wtx.GetTx()->vin, [](const CTxIn& in) { return in.scriptWitness.empty(); })) { + if (std::ranges::all_of(wtx.GetTx()->vin, &CTxIn::HasWitness)) { return txs; } ``` </details>
sipa commented 2026-11-24 17:00:33 +00:00 (Migrated from github.com)

Thank you for the many comments and suggestions, @l0rinc, I have included a substantial portion of them, including dropping ToSpans() in this PR already. I won't respond to all of them individually, but the ones I didn't take are because they deviate more from existing vector<vector<uchar>> behavior CScriptWitness has today, because they're bigger diffs for little gain, because they're testing properties that hold now but we may not want to promise, or because they're more appropriate for a follow-up.

Regarding bringing the deferred vector conversion here: my priority is reducing memory usage, and not significantly worsening performance at the deserialization stage. Everything that happens afterwards I consider lower priority, because it comes after PoW or standardness checks. I'll run more detailed benchmarks in the next days.

Regarding splitting the sizes and data of witnesses, I think that's something that can be explored as a follow-up, but I think it's optimizing for the wrong thing. Iterating the witness stack should only happen a small constant number of times at most.

Thank you for the many comments and suggestions, @l0rinc, I have included a substantial portion of them, including dropping `ToSpans()` in this PR already. I won't respond to all of them individually, but the ones I didn't take are because they deviate more from existing `vector<vector<uchar>>` behavior CScriptWitness has today, because they're bigger diffs for little gain, because they're testing properties that hold now but we may not want to promise, or because they're more appropriate for a follow-up. Regarding bringing the deferred vector conversion here: my priority is reducing memory usage, and not significantly worsening performance at the deserialization stage. Everything that happens afterwards I consider lower priority, because it comes after PoW or standardness checks. I'll run more detailed benchmarks in the next days. Regarding splitting the sizes and data of witnesses, I think that's something that can be explored as a follow-up, but I think it's optimizing for the wrong thing. Iterating the witness stack should only happen a small constant number of times at most.
DrahtBot commented 2026-11-24 17:44:22 +00:00 (Migrated from github.com)

🚧 At least one of the CI tasks failed.
Task tidy: https://github.com/bitcoin/bitcoin/actions/runs/45439914413/job/138607832119
LLM reason (✨ experimental): CI failed because clang-tidy treats an unnecessary copy in test/script_tests.cpp:1874 as an error; use a reference instead.

Hints

Try to run the tests locally, according to the documentation. However, a CI failure may still
happen due to a number of reasons, for example:

  • Possibly due to a silent merge conflict (the changes in this pull request being
    incompatible with the current code in the target branch). If so, make sure to rebase on the latest
    commit of the target branch.

  • A sanitizer issue, which can only be found by compiling with the sanitizer and running the
    affected test.

  • An intermittent issue.

Leave a comment here, if you need help tracking down a confusing failure.

<!--85328a0da195eb286784d51f73fa0af9--> 🚧 At least one of the CI tasks failed. <sub>Task `tidy`: https://github.com/bitcoin/bitcoin/actions/runs/45439914413/job/138607832119</sub> <sub>LLM reason (✨ experimental): CI failed because clang-tidy treats an unnecessary copy in `test/script_tests.cpp:1874` as an error; use a reference instead.</sub> <details><summary>Hints</summary> Try to run the tests locally, according to the documentation. However, a CI failure may still happen due to a number of reasons, for example: * Possibly due to a silent merge conflict (the changes in this pull request being incompatible with the current code in the target branch). If so, make sure to rebase on the latest commit of the target branch. * A sanitizer issue, which can only be found by compiling with the sanitizer and running the affected test. * An intermittent issue. Leave a comment here, if you need help tracking down a confusing failure. </details>
instagibbs commented 2026-11-24 20:02:48 +00:00 (Migrated from github.com)

reACK 94bf86a320

Reviewed the range-diff since 0c981e75a9

reACK 94bf86a32071770f54ebac504b3cff82a2f2b192 Reviewed the range-diff since 0c981e75a9
l0rinc commented 2026-11-24 21:48:22 +00:00 (Migrated from github.com)

tested ACK 94bf86a320

Thanks for considering & incorporating many of my suggestions.

I re-reviewed all commits, manually reconstructed and replayed all scripted diffs. I also checked serialization roundtrips, span lifetimes and the optimized witness comparisons in GCC/Clang disassemblies with AI assistance. I'm running an -assumevalid=0 mainnet chainstate reindex as a sanity check - but don't expect any problems.

I hope we can get this merged before the end of the month.

tested ACK 94bf86a32071770f54ebac504b3cff82a2f2b192 Thanks for considering & incorporating many of my suggestions. I re-reviewed all commits, manually reconstructed and replayed all scripted diffs. I also checked serialization roundtrips, span lifetimes and the optimized witness comparisons in GCC/Clang disassemblies with AI assistance. I'm running an `-assumevalid=0` mainnet chainstate reindex as a sanity check - but don't expect any problems. I hope we can get this merged before the end of the month.
l0rinc (Migrated from github.com) reviewed 2026-11-24 21:48:35 +00:00
l0rinc (Migrated from github.com) commented 2026-11-24 21:32:42 +00:00

6ba3634 test: check CScriptWitness against the vector of vectors it represents:

Nit: we can pass std::ranges::equal directly here.

Use the existing comparison directly
diff --git a/src/test/script_tests.cpp b/src/test/script_tests.cpp
index c5e716eabb..d7aa9dfc70 100644
--- a/src/test/script_tests.cpp
+++ b/src/test/script_tests.cpp
@@ -1782,7 +1782,7 @@ BOOST_AUTO_TEST_CASE(script_witness_representation)
                 for (size_t i = 0; i < stack.size(); ++i) BOOST_CHECK(std::ranges::equal(witness[i], stack[i]));
             }
             // Iterating over the witness yields its elements, in order.
-            BOOST_CHECK(std::ranges::equal(witness, stack, [](auto a, const auto& b) { return std::ranges::equal(a, b); }));
+            BOOST_CHECK(std::ranges::equal(witness, stack, std::ranges::equal));
 
             // Serialization matches that of the vector of vectors, in both directions.
             std::vector<unsigned char> ser_vec, ser_wit;
> [6ba3634](https://github.com/bitcoin/bitcoin/pull/36895/changes/6ba363488f477271f23bb51cbae5ba0e53714c28) _test: check CScriptWitness against the vector of vectors it represents_: Nit: we can pass `std::ranges::equal` directly here. <details> <summary>Use the existing comparison directly</summary> ```diff diff --git a/src/test/script_tests.cpp b/src/test/script_tests.cpp index c5e716eabb..d7aa9dfc70 100644 --- a/src/test/script_tests.cpp +++ b/src/test/script_tests.cpp @@ -1782,7 +1782,7 @@ BOOST_AUTO_TEST_CASE(script_witness_representation) for (size_t i = 0; i < stack.size(); ++i) BOOST_CHECK(std::ranges::equal(witness[i], stack[i])); } // Iterating over the witness yields its elements, in order. - BOOST_CHECK(std::ranges::equal(witness, stack, [](auto a, const auto& b) { return std::ranges::equal(a, b); })); + BOOST_CHECK(std::ranges::equal(witness, stack, std::ranges::equal)); // Serialization matches that of the vector of vectors, in both directions. std::vector<unsigned char> ser_vec, ser_wit; ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-24 21:32:35 +00:00

b7ec0d2 refactor: use CScriptWitness's interface where that needs more than a rename:

Nit: the reserved value is the same for every coinbase, so we could pack it once when a coinbase first needs a witness.

Pack the static coinbase witness nonce once
diff --git a/src/validation.cpp b/src/validation.cpp
index 17fe37d2e7..89e14c8566 100644
--- a/src/validation.cpp
+++ b/src/validation.cpp
@@ -4073,11 +4073,11 @@ bool CheckBlock(const CBlock& block, BlockValidationState& state, const Consensu
 void ChainstateManager::UpdateUncommittedBlockStructures(CBlock& block, const CBlockIndex* pindexPrev) const
 {
     int commitpos = GetWitnessCommitmentIndex(block);
-    static const std::vector<unsigned char> nonce(32, 0x00);
     if (commitpos != NO_WITNESS_COMMITMENT && DeploymentActiveAfter(pindexPrev, *this, Consensus::DEPLOYMENT_SEGWIT) && !block.vtx[0]->HasWitness()) {
         CMutableTransaction tx(*block.vtx[0]);
         // The coinbase witness consists of just the witness reserved value.
-        tx.vin[0].scriptWitness = CScriptWitness{{nonce}};
+        static const CScriptWitness nonce_witness{{std::vector<unsigned char>(32, 0x00)}};
+        tx.vin[0].scriptWitness = nonce_witness;
         block.vtx[0] = MakeTransactionRef(std::move(tx));
     }
 }
> [b7ec0d2](https://github.com/bitcoin/bitcoin/pull/36895/changes/b7ec0d2817dd55cf8170306a813ec30035abf2ef) _refactor: use CScriptWitness's interface where that needs more than a rename_: Nit: the reserved value is the same for every coinbase, so we could pack it once when a coinbase first needs a witness. <details> <summary>Pack the static coinbase witness nonce once</summary> ```diff diff --git a/src/validation.cpp b/src/validation.cpp index 17fe37d2e7..89e14c8566 100644 --- a/src/validation.cpp +++ b/src/validation.cpp @@ -4073,11 +4073,11 @@ bool CheckBlock(const CBlock& block, BlockValidationState& state, const Consensu void ChainstateManager::UpdateUncommittedBlockStructures(CBlock& block, const CBlockIndex* pindexPrev) const { int commitpos = GetWitnessCommitmentIndex(block); - static const std::vector<unsigned char> nonce(32, 0x00); if (commitpos != NO_WITNESS_COMMITMENT && DeploymentActiveAfter(pindexPrev, *this, Consensus::DEPLOYMENT_SEGWIT) && !block.vtx[0]->HasWitness()) { CMutableTransaction tx(*block.vtx[0]); // The coinbase witness consists of just the witness reserved value. - tx.vin[0].scriptWitness = CScriptWitness{{nonce}}; + static const CScriptWitness nonce_witness{{std::vector<unsigned char>(32, 0x00)}}; + tx.vin[0].scriptWitness = nonce_witness; block.vtx[0] = MakeTransactionRef(std::move(tx)); } } ``` </details>
optout21 commented 2026-11-24 22:34:52 +00:00 (Migrated from github.com)

reACK 94bf86a320
Re-reviewed with focus on the diff, LGTM. Nice to see a reduction in back() calls!

reACK 94bf86a32071770f54ebac504b3cff82a2f2b192 Re-reviewed with focus on the diff, LGTM. Nice to see a reduction in `back()` calls!
DrahtBot commented 2026-11-25 00:53:27 +00:00 (Migrated from github.com)

🐙 This pull request conflicts with the target branch and needs rebase.

<!--cf906140f33d8803c4a75a2196329ecb--> 🐙 This pull request conflicts with the target branch and [needs rebase](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#rebasing-changes).
brunoerg (Migrated from github.com) reviewed 2026-11-25 12:09:49 +00:00
brunoerg (Migrated from github.com) commented 2026-11-25 12:09:49 +00:00

Wouldn't calling witness.ToVectors() unconditionally here materializes the full vector<vector<unsigned char>> even for branches that never inspect the witness stack or can reject it?

Wouldn't calling `witness.ToVectors()` unconditionally here materializes the full `vector<vector<unsigned char>> ` even for branches that never inspect the witness stack or can reject it?
sipa (Migrated from github.com) reviewed 2026-11-25 12:17:13 +00:00
sipa (Migrated from github.com) commented 2026-11-25 12:17:13 +00:00

Indeed. There is a commit in the follow-up PR that only materializes the vector when it's actually needed.

The fact that this branch always materializes is technically a regression in some circumstances, but it doesn't change worse case behavior (which uses scripts where the materialization always needs to happen), and also only after IsStandard() or proof-of-work checks.

Indeed. There is a commit in the follow-up PR that only materializes the vector when it's actually needed. The fact that this branch always materializes is technically a regression in some circumstances, but it doesn't change worse case behavior (which uses scripts where the materialization always needs to happen), and also only after IsStandard() or proof-of-work checks.
brunoerg (Migrated from github.com) approved these changes 2026-11-25 12:28:26 +00:00
brunoerg (Migrated from github.com) left a comment

code review ACK 94bf86a320

code review ACK 94bf86a32071770f54ebac504b3cff82a2f2b192
otaliptus (Migrated from github.com) reviewed 2026-11-25 12:52:29 +00:00
otaliptus (Migrated from github.com) commented 2026-11-25 12:52:29 +00:00

totally nit: in the case of no annex, stack[effective_size - 1] fetches the element that was already last?

const auto& control = has_annex ? stack[effective_size - 1] : last;

edit: #36918 seems to be handling this

totally nit: in the case of no annex, `stack[effective_size - 1]` fetches the element that was already `last`? ```cpp const auto& control = has_annex ? stack[effective_size - 1] : last; ``` edit: #36918 seems to be handling this
sipa (Migrated from github.com) reviewed 2026-11-25 14:04:01 +00:00
sipa (Migrated from github.com) commented 2026-11-25 14:04:01 +00:00

Yeah, becomes (mostly) moot in #36918.

Yeah, becomes (mostly) moot in #36918.
sipa commented 2026-11-25 14:04:13 +00:00 (Migrated from github.com)

Rebased on master.

Rebased on master.
instagibbs commented 2026-11-25 14:55:34 +00:00 (Migrated from github.com)

reACK 56fa33eac6

Rebase only since 94bf86a320

reACK 56fa33eac63c37513305841ff1bd73f56ad92322 Rebase only since 94bf86a320
l0rinc commented 2026-11-25 15:14:57 +00:00 (Migrated from github.com)

reACK 56fa33eac6

reACK 56fa33eac63c37513305841ff1bd73f56ad92322
brunoerg commented 2026-11-25 15:22:08 +00:00 (Migrated from github.com)

reACK 56fa33eac6

reACK 56fa33eac63c37513305841ff1bd73f56ad92322
l0rinc commented 2026-11-25 16:18:39 +00:00 (Migrated from github.com)

GitHub won't allow me to edit, so adding a new comment instead:

Finished a fully validating chainstate reindex in 29'403 s (8.16 hours) and one with normal assumevalid in 10'948 s (3.04 hours), roughly 1% faster than master at 11'084 s (3.08 hours).
For reference, #36918 (d2483cfce4) finished in 10'797 s (2.99 hours).

GitHub won't allow me to edit, so adding a new comment instead: > Finished a fully validating chainstate reindex in 29'403 s (8.16 hours) and one with normal `assumevalid` in 10'948 s (3.04 hours), roughly 1% faster than master at 11'084 s (3.08 hours). For reference, #36918 (d2483cfce4) finished in 10'797 s (2.99 hours).
w0xlt (Migrated from github.com) reviewed 2026-11-25 22:47:00 +00:00
w0xlt (Migrated from github.com) left a comment
ACK 56fa33eac63c37513305841ff1bd73f56ad92322
sipa commented 2026-11-26 04:39:46 +00:00 (Migrated from github.com)

Benchmarks for this PR and #36918. All are the median of 9 runs on a Zen5 machine, in milliseconds, compiled with GCC 15.3.0, for going from received serialized block to accept/reject (so including deserialization + validation). The last 4 columns refer to the individual optimization commits in #36918. This is without #36906, which speeds certain invalid blocks/transaction up further.

block master this PR + deser + inline + offset + lazy
✅ unknown version, 4.0M × 0 B 282 308 58 57 56 21
✅ unknown version, 2.0M × 1 B 130 189 94 93 93 15
✅ unknown version, 2.66M × 0–1 B (random) 176 240 84 83 83 23
❌ P2WPKH item count, 4.0M × 0 B 286 315 59 57 57 21
❌ P2WPKH item count, 2.0M × 1 B 131 189 95 93 93 15
❌ P2WSH stack too large, 4.0M × 0 B 359 319 68 65 61 60
❌ P2WSH stack too large, 2.0M × 1 B 219 189 97 95 93 94
❌ P2WSH mismatch, 2.0M × 1 B 131 162 69 67 66 66
❌ tapscript stack too large, 2.0M × 1 B 207 184 93 92 79 78
❌ P2TR bad control block, 2.0M × 1 B 130 160 66 65 65 65
❌ bad commitment, 2.0M × 1 B 102 135 15 15 15 15
✅ 12,294 unknown version × 80 × 1 B 50 40 23 23 23 15
✅ 5,169 P2WSH × 403 items 31 27 25 24 21 21
✅ 2,343 tapscript × 1,000 items 44 36 33 33 33 33
✅ 14,690 signed P2WPKH 118 118 118 118 119 118
✅ unknown version, 1 × 4.0 MB 1.6 3.4 3.4 3.4 3.4 2.8
❌ P2TR bad signature, 4.0 MB annex 3.2 5.0 5.0 5.0 5.0 5.0
❌ 399,700 txs without inputs or outputs 110 109 110 110 110 110
Benchmarks for this PR and #36918. All are the median of 9 runs on a Zen5 machine, in milliseconds, compiled with GCC 15.3.0, for going from received serialized block to accept/reject (so including deserialization + validation). The last 4 columns refer to the individual optimization commits in #36918. This is without #36906, which speeds certain invalid blocks/transaction up further. | block | master | this PR | + deser | + inline | + offset | + lazy | |---|--:|--:|--:|--:|--:|--:| | ✅ unknown version, 4.0M × 0 B | 282 | 308 | 58 | 57 | 56 | 21 | | ✅ unknown version, 2.0M × 1 B | 130 | 189 | 94 | 93 | 93 | 15 | | ✅ unknown version, 2.66M × 0–1 B (random) | 176 | 240 | 84 | 83 | 83 | 23 | | ❌ P2WPKH item count, 4.0M × 0 B | 286 | 315 | 59 | 57 | 57 | 21 | | ❌ P2WPKH item count, 2.0M × 1 B | 131 | 189 | 95 | 93 | 93 | 15 | | ❌ P2WSH stack too large, 4.0M × 0 B | 359 | 319 | 68 | 65 | 61 | 60 | | ❌ P2WSH stack too large, 2.0M × 1 B | 219 | 189 | 97 | 95 | 93 | 94 | | ❌ P2WSH mismatch, 2.0M × 1 B | 131 | 162 | 69 | 67 | 66 | 66 | | ❌ tapscript stack too large, 2.0M × 1 B | 207 | 184 | 93 | 92 | 79 | 78 | | ❌ P2TR bad control block, 2.0M × 1 B | 130 | 160 | 66 | 65 | 65 | 65 | | ❌ bad commitment, 2.0M × 1 B | 102 | 135 | 15 | 15 | 15 | 15 | | ✅ 12,294 unknown version × 80 × 1 B | 50 | 40 | 23 | 23 | 23 | 15 | | ✅ 5,169 P2WSH × 403 items | 31 | 27 | 25 | 24 | 21 | 21 | | ✅ 2,343 tapscript × 1,000 items | 44 | 36 | 33 | 33 | 33 | 33 | | ✅ 14,690 signed P2WPKH | 118 | 118 | 118 | 118 | 119 | 118 | | ✅ unknown version, 1 × 4.0 MB | 1.6 | 3.4 | 3.4 | 3.4 | 3.4 | 2.8 | | ❌ P2TR bad signature, 4.0 MB annex | 3.2 | 5.0 | 5.0 | 5.0 | 5.0 | 5.0 | | ❌ 399,700 txs without inputs or outputs | 110 | 109 | 110 | 110 | 110 | 110 |
ajtowns commented 2026-11-26 16:42:40 +00:00 (Migrated from github.com)
ACK 56fa33eac63c37513305841ff1bd73f56ad92322
Sign in to join this conversation.
No milestone
No project
No assignees
2 participants
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
bitcoin/bitcoin!36895
No description provided.