Skip to content

Witness stacks in serialized form (optimization follow-ups) - #36918

Open
sipa wants to merge 5 commits into
bitcoin:masterfrom
sipa:202610_witpack
Open

sipa wants to merge 5 commits into
bitcoin:masterfrom
sipa:202610_witpack

Conversation

@sipa

@sipa sipa commented Nov 19, 2026 •

Copy link
Copy Markdown
Member

This is a PR with follow-up optimizations to #36895.

Benchmarks for the various commits, in milliseconds, on recent Zen5 machine, gcc 15.3 -O2, median of 11 runs. All measure time from receipt to accept/reject (covering everything from deserialization to validation, if relevant):

block master 64061b6 99841eb 945c9e5 5401e67
Before the proof-of-work check
❌ bad commitment, 4.0M × 0 B 275 21 21 21 21
❌ bad commitment, 2.0M × 1 B 134 15 15 15 15
❌ 399,700 txs without inputs or outputs 109 110 109 109 109
Valid blocks
✅ unknown version, 4.0M × 0 B 316 57 57 57 21
✅ unknown leaf version, 4.0M × 0 B 312 59 58 56 55
✅ unknown version, 2.66M × 0–1 B (random) 238 83 79 80 23
✅ unknown leaf version, 2.0M × 1 B 161 67 65 65 65
✅ 14,690 signed P2WPKH 118 117 117 117 118
Invalid blocks with valid proof of work
❌ P2WSH stack too large, 4.0M × 0 B 324 69 65 60 61
❌ P2WSH mismatch, 4.0M × 0 B 315 64 62 56 56
❌ P2WPKH item count, 4.0M × 0 B 314 59 56 56 21
❌ P2WSH stack too large, 2.0M × 1 B 191 97 95 93 93
❌ tapscript stack too large, 2.0M × 1 B 184 93 92 78 76
❌ P2TR bad control block, 2.0M × 1 B 160 66 65 65 66
❌ P2WSH mismatch, 2.0M × 1 B 165 69 67 66 65

@DrahtBot

DrahtBot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

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
Concept ACK optout21
Approach ACK ajtowns

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:

  • #36853 (test: Add test for CompactSize larger than MAX_SIZE value by maflcko)
  • #36122 (BIP460: CISA for Taproot key path spends by fjahr)

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.

Comment thread src/script/script.cpp Resolved
@DrahtBot

Copy link
Copy Markdown
Contributor

🚧 At least one of the CI tasks failed.
Task iwyu: https://github.com/bitcoin/bitcoin/actions/runs/44588028340/job/135786171179
LLM reason (✨ experimental): CI failed because IWYU added a missing <span> include to src/bench/block_deserialize.cpp, leaving an uncommitted diff that the check rejects.

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.

@sipa
sipa force-pushed the 202610_witpack branch 2 times, most recently from 06a20ee to d2483cf Compare November 24, 2026 18:59
fanquake added a commit that referenced this pull request Nov 26, 2026
56fa33e doc: add release note for the reduced memory usage of witnesses (Pieter Wuille)
150002b script: store witness stacks as their serialization (Pieter Wuille)
3fca959 span: add SameSpan (Pieter Wuille)
519aa85 script: remove CScriptWitness's old interface (Pieter Wuille)
77f8bac test, bench, fuzz: build witness stacks before constructing a CScriptWitness (Pieter Wuille)
5fc4db0 refactor: use CScriptWitness's interface where that needs more than a rename (Pieter Wuille)
68b0ae9 policy: iterate over witness stacks directly in IsWitnessStandard (Pieter Wuille)
0f1253e script: build the witness execution stack with ToVectors() (Pieter Wuille)
0e317e2 script: let ExecuteWitnessScript take its initial stack by value (Pieter Wuille)
e294e28 scripted-diff: replace witnesses as a whole instead of their stack (Pieter Wuille)
ce3c41b scripted-diff: serialize CScriptWitness rather than its stack (Pieter Wuille)
afc3248 scripted-diff: read and compare CScriptWitness through its interface (Pieter Wuille)
a2230b1 scripted-diff: use CScriptWitness's size(), empty() and back() (Pieter Wuille)
4be6595 test: check CScriptWitness against the vector of vectors it represents (Pieter Wuille)
fa34694 script: give CScriptWitness an interface that hides its representation (Pieter Wuille)

Pull request description:

  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.

ACKs for top commit:
  instagibbs:
    reACK 56fa33e
  l0rinc:
    reACK 56fa33e
  brunoerg:
    reACK 56fa33e
  ajtowns:
    ACK 56fa33e
  w0xlt:
    ACK 56fa33e

Tree-SHA512: b9786d96fe14641a8029d3cd5fcf440c6b60ee613d6cb0a19c9b9b765b43cdef8497cbd6a9a4dd8c757a621e1605b9966617649d147ad5cc67af9d2a448d44c7
@sipa
sipa marked this pull request as ready for review November 26, 2026 18:58
@sipa

sipa commented Nov 27, 2026

Copy link
Copy Markdown
Member Author

Ready for review.

@ajtowns ajtowns left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approach ACK 5401e67

Comment thread src/serialize.h Resolved
Comment thread src/script/script.h Resolved
Comment thread src/script/interpreter.cpp Resolved
Comment thread src/script/script.h Resolved
sipa added 5 commits November 27, 2026 15:51
Add benchmarks deserializing blocks filled up to the weight limit with
synthetic transactions of a few shapes that stress different parts of
deserialization:
* spends of P2WPKH outputs to P2WPKH outputs (a typical segwit block)
* the smallest segwit transactions
* one transaction with as many inputs as fit,
* one transaction with as many outputs as fit,
* one transaction whose witness has as many 1-byte elements as fit.
Instead of deserializing a witness stack as a vector of vectors and then
serializing that again, build the serialization directly while reading,
with the same checks. This makes deserializing a block whose witness
consists of millions of 1-byte elements about 10x faster.

To support this, add AppendCompactSize to serialize.h, which cheaply
appends a CompactSize to a byte vector.
Add DecodeCompactSizeUnchecked to serialize.h, which decodes a
CompactSize from a span without any checks, making it small enough to be
inlined.

Use it to find the elements in a CScriptWitness's serialization, which
is known to be valid as CScriptWitness constructed it. This makes
iterating over witness stacks 5-7x faster, both for real blocks and for
blocks whose witnesses consist of millions of 1-byte elements. As a
bonus, script.h no longer needs streams.h.
Add the offset of the last element to the header of CScriptWitness's
allocation, making back() and accessing the last element by index O(1).
The last element is used in P2WSH sigop counting, policy checks, and
BIP352 public key extraction.

This adds 4 bytes to the allocation of every non-empty witness stack,
but does not change the minimum allocation size of a single-element
stack, nor the worst-case ratio of memory usage to weight or size.
VerifyWitnessProgram converted the whole witness to a vector of vectors
before looking at the witness program. That is wasted work when the
rules for the program do not use the witness: unknown witness versions,
v0 programs of an unknown length, pay-to-anchor, and taproot when
SCRIPT_VERIFY_TAPROOT is not set. Such a witness is only limited by the
block weight, so it can consist of millions of elements.

Instead, convert inside the P2WSH and taproot branches, and for P2WPKH
only after checking that the witness has exactly 2 elements.
@fanquake fanquake added this to the 33.0 milestone Nov 30, 2026

@optout21 optout21 left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Concept ACK (32a2937)

Worthwhile optimizations, a followup of #36895.
Code review and tests are OK.
Left some minor remarks, and some general ones here:

1, The last-element optimization's commit message states: "but does not change the minimum allocation size of a single-element stack". I believe this is true on 64-bit systems, so it should be qualified "(on 64-bit systems)".

2, I have some doubts about the last-element optimization: it produces a speed-up, but the effect of the extra memory used is not trivial.
Using the mempool accounting rule (memusage::MallocUsage, 64-bit, rounds as ((alloc + 31) >> 4) << 4), P2WPKH, the most common input type, uses 144 instead of 128 bytes total, a 12.5% extra. With real glibc rounding ((n + 8 + 15) & ~15, minimum 32), it's still 128.

Some options that may be considered:

  • Always store the last element index (current state of 6134604)
  • Never last element index
  • Store the extra last-index only for witness stacks with elements above a threshold (e.g. >= 4), as iterating over only a few elements is not that slow. But the element count may be not always readily available, so it could use the total data size (stored in the first 4 bytes), e.g. skip the last element index if data size < 128. With small data it is likely that the number of elements is small (this is an approximation), for large data the relative extra memory (the 4 extra bytes) is small. Overall this would reduce the extra memory usage. Drawbacks: the code becomes even more complex (header is 4 or 8 bytes), the optimal threshold limit is hard to estimate.
  • Use compact encoding to store the data size and the element index, may use less extra memory.

Comment thread src/serialize.h
std::vector<std::byte>& data;
void write(std::span<const std::byte> src)
{
for (const auto b : src) data.push_back(b);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

2d5b121 script: deserialize witness stacks directly into their serialization:

Nit: Alternative for the for loop:
data.insert(data.end(), src.begin(), src.end())
Simpler, depending on taste, and about as fast, depending on compiler optimizations.

Comment thread src/serialize.h
std::span<const std::byte>& data;
void read(std::span<std::byte> dst) noexcept
{
std::memcpy(dst.data(), data.data(), dst.size());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

a9e2ed1 script: decode the CompactSizes in witness stacks inline:

Nit: I suggest an Assume on the size before memcpy:
Assume(dst.size() <= data.size());
The old SpanReader threw before reading, this assume would restore the check in debug and fuzz builds and at no cost in release builds.
With hardened std::span (_GLIBCXX_ASSERTIONS or libc++ hardening), an overrun is caught only after it has already happened.

Comment on lines 1948 to 1950
if (memcmp(hash_exec_script.begin(), program.data(), 32)) {
return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

32a2937 script: only convert the witness to vectors when it is used:

Small optimization for error case: This check (for P2WSH with a wrong script hash) could be moved before witness.ToVectors(), using back().

if (program.size() == WITNESS_V0_SCRIPTHASH_SIZE) {
// BIP141 P2WSH: 32-byte witness v0 program (which encodes SHA256(script))
auto stack = witness.ToVectors();
if (stack.size() == 0) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

32a2937 script: only convert the witness to vectors when it is used:

Nit: This check could come before the ToString(), if (witness.empty()).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants