mirror of
https://github.com/bitcoin/bitcoin
synced 2026-12-04 12:41:38 +00:00
Witness stacks in serialized form (optimization follow-ups) #36918
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!36918
Loading…
Reference in a new issue
No description provided.
Delete branch "202610_witpack"
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 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):
64061b6a4a99841eb0f9945c9e55fe5401e67366The 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:
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.
Earlier concerns neither republished nor resolved: 1 major finding · 2 suggestions. See the Run archive linked from the Review report for their assessments.
🔵 Suggestion · P2WSH hash mismatches still materialize the entire witness
The pre-existing P2WSH conversion still materializes every element before rejecting a script-hash mismatch, although the new constant-time
back()makes that work avoidable.Location:
src/script/interpreter.cpp:1940(head).🔵 Suggestion · Witness rejection tests miss canonicality, count-limit and truncation checks
The new
CScriptWitness::Unserialize()loop has only an oversized-element rejection unit test; its canonical-prefix, count-limit and short-payload checks lack deterministic witness coverage, despite differential fuzz coverage.Location:
src/script/script.h:724(head).🔵 Suggestion · Witness payload chunk boundaries lack deterministic coverage
CScriptWitnessunit tests never successfully deserialize an element larger thanMAX_VECTOR_ALLOCATE, leaving continuation offsets and stream consumption in the new chunk loop without deterministic checks.Location:
src/script/script.h:743(head).🔵 Suggestion · P2WPKH benchmark gives the public-key item 72 bytes
DeserializeBlockP2WPKHgives the compressed-public-key item 72 bytes instead of 33, so its synthetic block underrepresents transaction and witness counts at the same weight.Location:
src/bench/block_deserialize.cpp:117(head).Review coverage was incomplete.
Reviewed:
32a29373e0c8· Review report · Previous reportspermalink
I'm not sure I understand the split: this was just added in the unmerged previous PR (one of my pending suggestions is exactly that we don't actually need a separate
ToSpans), and now we remove it here again, so code we reviewed in the previous PR won't even end up being used... Is this meant to simplify cherry-picking to older versions?Yes. #36895 is just the minimal part to get the memory usage savings in, which hopefully doesn't need that much discussion. This PR (and the side track #36906) likely need some debate about which changes exactly are worth it.
🚧 At least one of the CI tasks failed.
Task
iwyu: https://github.com/bitcoin/bitcoin/actions/runs/44588028340/job/135786171179LLM reason (✨ experimental): CI failed because IWYU added a missing
<span>include tosrc/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.
🐙 This pull request conflicts with the target branch and needs rebase.
Ready for review.
Approach ACK
5401e67366What do you think of making this
auto stack = witness.ToVectors()and changing it toconst auto pop{[&](std::vector<valtype>& stack) {andpop(stack)so that thestackvariables are scoped to where they're used?The back() commit feels hardest to justify. Arguably:
Perhaps a
ToLastSpans(n)that returns a vector of the last (up to) n stack elements would eventually be more useful?Worth an
Assume(m_data);? Would previously have been caught viaoperator[]doingAssume(last_offset < size())withlast_offsethaving wrapped around to max I think.What do you think of renaming this to
DecodeCompactSizeUnchecked(like txmempoolremoveUnchecked)? The difference between "Read" and "Decode" is not very obvious ("ReadCompactSize" is also described in its comments as "Decode a CompactSize-encoded variable-length integer.").Done.
If annexes were to become standard, it would be possible to instead store the offset to the penultimate element, and making
back()do one forward iteration step.At that point, there probably should just be a "get iterator to element at position X" or so?
Done.
Done.
Ah, keeping a pointer to 2nd or 3rd last element works, yeah. Maybe
stack.back(0)andstack.back(1)or something would be better thanstack[stack.size()-1]in that case (with an error if you trystack.back(2)and that can't be efficient. Sounds solvable either way though.Concept ACK (
32a29373e0)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:
6134604)Nit: This check could come before the
ToString(),if (witness.empty()).Small optimization for error case: This check (for P2WSH with a wrong script hash) could be moved before
witness.ToVectors(), usingback().Nit: Alternative for the
forloop:data.insert(data.end(), src.begin(), src.end())Simpler, depending on taste, and about as fast, depending on compiler optimizations.
Nit: I suggest an
Assumeon the size beforememcpy: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_ASSERTIONSor libc++ hardening), an overrun is caught only after it has already happened.