Repository navigation
Conversation
|
The following sections might be updated with supplementary metadata relevant to reviewers and maintainers. External sites
ReviewsSee the guideline and AI policy for information on the review process.
If your review is incorrectly listed, please copy-paste ConflictsReviewers, this pull request conflicts with the following ones:
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. |
|
🚧 At least one of the CI tasks failed. HintsTry to run the tests locally, according to the documentation. However, a CI failure may still
Leave a comment here, if you need help tracking down a confusing failure. |
06a20ee to
d2483cf
Compare
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
|
Ready for review. |
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.
There was a problem hiding this comment.
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.
| std::vector<std::byte>& data; | ||
| void write(std::span<const std::byte> src) | ||
| { | ||
| for (const auto b : src) data.push_back(b); |
There was a problem hiding this comment.
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.
| std::span<const std::byte>& data; | ||
| void read(std::span<std::byte> dst) noexcept | ||
| { | ||
| std::memcpy(dst.data(), data.data(), dst.size()); |
There was a problem hiding this comment.
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.
| if (memcmp(hash_exec_script.begin(), program.data(), 32)) { | ||
| return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH); | ||
| } |
There was a problem hiding this comment.
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) { |
There was a problem hiding this comment.
32a2937 script: only convert the witness to vectors when it is used:
Nit: This check could come before the ToString(), if (witness.empty()).

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):