mirror of
https://github.com/bitcoin/bitcoin
synced 2026-12-04 10:44:38 +00:00
Keep witness stacks in serialized form in CScriptWitness #36895
No reviewers
Labels
No labels
Android
Backport
Block storage
Brainstorming
Bug
Build system
CI failed
Consensus
Data corruption
Descriptors
Docs
DrahtBot Guix build requested
Feature
Fuzzing
GUI
Good First Review
IPC
Insufficient Review
Kernel
Linux/Unix
Mempool
Mining
Needs Backport (31.x)
Needs Backport (32.x)
Needs Benchmark
Needs Conceptual Review
Needs backport (30.x)
Needs rebase
Needs release note
Net
P2P
PSBT
Privacy
Private Broadcast
Questions and Help
RPC/REST/ZMQ
Refactoring
Resource usage
Review club
Scripts and tools
Settings
TX fees and policy
Tests
Tracking Issue
UTXO Db and Indexes
Up for grabs
Upstream
Utils/log/libs
Validation
Waiting for author
Wallet
Windows
good first issue
interfaces
macOS
No milestone
No project
No assignees
2 participants
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
bitcoin/bitcoin!36895
Loading…
Reference in a new issue
No description provided.
Delete branch "202611_witpack_minimal"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
This is split off from #36521. This PR focuses on reducing memory usage of transactions in memory, leaving performance improvements for other PRs.
CScriptWitnessstores a witness stack as astd::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 singlestd::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.CScriptWitnessshrinks from 24 to 8 bytes, andCTxInfrom 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:
\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.
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.
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:
MSG_BLOCKby stripping witnesses in place by l0rinc)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.
Concept ACK
🔵 Suggestion ·
Items()traversal is quadratic without a public complexity warningIn 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 themUnknown witness versions, pay-to-anchor, and Taproot with
SCRIPT_VERIFY_TAPROOTunset 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 accountingThe 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 reportspermalink
Concept ACK
Concept ACK
Concept ACK
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
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
@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,
CheckBlockandConnectBlock, in ms. These are medians of 11 interleaved rounds on the now-idle machine, gcc Release.crACK
a6a4df2770This 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;
CTxInsize from 96 to 104).A note on the range of counts and lengths:
uint64_t ReadCompactSize()is implicitly converted tosize_tin a few places. This is fine:ReadCompactSizerejects values aboveMAX_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 thanMAX_SIZE. In this casestd::terminatewould be hit on first access, since the accessors are noexcept. That's not reachable from the network, but checkingMAX_SIZEin 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.Minor: Here
back()is called, thenToSpans(). If theMAX_STANDARD_P2WSH_SCRIPT_SIZEcheck was moved afterToSpans(), theback()call could be avoided (backis potentially expensive).Nit: Could be simplified to: (requires
#include <util/string.h>)I like this, a natural consequence of this is that it would speed up the kernel.
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
49c0f21971A 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.
Done.
@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.
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.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).
If there is a second use case for it, that seems reasonable, but I'm not sure where that'd be.
I believe the old PR already had that; it's in the follow-up PR now.
#36918 instead has a lazy creation of the stack (and no more
ToSpans), which avoids this issue entirely I think.reACK
0c981e75a9Diff review, one minor change applied (ToString();
a6a4df2->0c981e7)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.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-timeback()), 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
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.Given @instagibbs’s mempool measurements, this seems worth a release note. The same
-maxmempoolbudget can now hold more transactions.Mention the mempool memory saving
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
WitnessSigOps()and the BIP352 annex check both callback()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, whereback()would become constant time, or my suggestion, wherebackwould already have constant time access.Bind back() once in WitnessSigOps and GetPubKeyFromInput
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.
RecursiveDynamicUsage(const CTxIn&)to theCScriptWitness::DynamicMemoryUsage()helper already added there.front()as*begin()andback()as(*this)[size() - 1]. The same iterators already work forToVectors(), the newToString()and, if we keep it,ToSpans().ToString()formats empty elements in the commit that adds the witness tests.Changes to fold in by the end of the interface commit
Formatting cases for the witness tests
I’d still prefer to drop 32-bit support, but with a 32-bit
size_t,::GetSerializeSize()returnsuint64_tand the header leaves room for at mostUINT32_MAX - 4payload bytes.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
Prefix
++could useLIFETIMEBOUND- and the three private span/iterator helpers could carry it too to guard internal callers.Annotate prefix ++ and internal span helpers
Returning a shared zero byte from
Data()for an empty witness simplifiesSerialize()andend().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
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
The vector constructor accepts elements above
MAX_SIZE, but reading their lengths throws inside thenoexceptaccessors 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
Data().last(0)givesend()the one-past-the-end position directly.Take the empty suffix for end()
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 thatToVectors()returns copies.Document borrowed span lifetimes and ToVectors() copies
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
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
It seems to me that using
std::byteprevents 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
Alongside the empty-stack case, we could cover witnesses of equal length with different contents.
Witness equality returning false
nit: For a follow-up, AJ’s
SameSpanhelper would letNetGroupManagercheck 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
The
catchcovers decoding failure, so I’d include theSpanReaderconstruction in thetryas well - that also lets us drop the extra scope.Move SpanReader inside the try blocks
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
What if both serializers write the same wrong byte? We still have
bufferhere, 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
The empty case is a no-op here since an unsigned size is always
>= 0.Assert DynamicMemoryUsage() == 0 for empty witnesses
AsWit()currently unpacks and rebuilds the witness for every item. We could pack it once inTest()and copy justscriptSigto include any pending push.Accumulate a vector in TestBuilder and pack in Test()
Alongside your cases for the item count, I’d put each boundary length at both ends of a witness. That exercises
front()andback()on every run and keeps the random coverage.Check both ends at every boundary length
For consistency, cover postfix increment as well, including the returned iterator.
Cover Iterator::operator++(int)
When both the input and
deserare empty, the test would pass even if the read did nothing. Startingdeserwith 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
We can construct the witnesses directly in
package_submission_testsandblock_malleation, avoiding the temporarybad_witnessand the extra conversion to vectors.Construct the test witnesses directly
A
CTxIn::HasWitness()predicate would avoid the repeated negations and let us pass&CTxIn::HasWitnessdirectly toany_ofandall_of.It's possible some parent methods could also become inlinable in that case...
Share the input witness predicate
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 existingvector<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.
🚧 At least one of the CI tasks failed.
Task
tidy: https://github.com/bitcoin/bitcoin/actions/runs/45439914413/job/138607832119LLM reason (✨ experimental): CI failed because clang-tidy treats an unnecessary copy in
test/script_tests.cpp:1874as 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.
reACK
94bf86a320Reviewed the range-diff since
0c981e75a9tested ACK
94bf86a320Thanks 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=0mainnet 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.
Nit: we can pass
std::ranges::equaldirectly here.Use the existing comparison directly
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
reACK
94bf86a320Re-reviewed with focus on the diff, LGTM. Nice to see a reduction in
back()calls!🐙 This pull request conflicts with the target branch and needs rebase.
Wouldn't calling
witness.ToVectors()unconditionally here materializes the fullvector<vector<unsigned char>>even for branches that never inspect the witness stack or can reject it?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.
code review ACK
94bf86a320totally nit: in the case of no annex,
stack[effective_size - 1]fetches the element that was alreadylast?edit: #36918 seems to be handling this
Yeah, becomes (mostly) moot in #36918.
Rebased on master.
reACK
56fa33eac6Rebase only since
94bf86a320reACK
56fa33eac6reACK
56fa33eac6GitHub won't allow me to edit, so adding a new comment instead:
ralph referenced this pull request2026-11-25 19:39:46 +00:00
ACK
56fa33eac6Benchmarks 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.
ACK
56fa33eac6