Skip to content

Keep witness stacks in serialized form in CScriptWitness - #36521

Closed
sipa wants to merge 17 commits into
bitcoin:masterfrom
sipa:202610_witpack
Closed

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

Conversation

@sipa

@sipa sipa commented Oct 14, 2026 •

Copy link
Copy Markdown
Member

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 element. This makes it possible to construct transactions that take a large amount of memory after deserialization, while becoming very slow to deserialize.

This PR stores the stack as its serialization in a single allocation (or none if the stack is empty), with a small header holding its size and the offset of the last element. Witnesses can no longer be modified in place, only allowing replacing them entirely. 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.

Later commits also introduce stricter checking during deserialization, rejecting the following before fully deserializing:

  • Transactions with more inputs/outputs than are possible in a valid transaction.
  • Transactions with 0 inputs or 0 outputs (applied in P2P, but not RPC etc. for backward compatibility).
  • Transactions/blocks that exceed the 4M weight limit (also only applied in P2P).

The result is a significant reduction in the worst-case time and memory allocations needed for deserialization, both in valid and invalid transactions. With it, the worst-case memory of a valid deserialized block drops from 106.8 MiB to 6.0 MiB. Memory usage during deserialization can temporarily be higher: up to 7.8 MiB for valid blocks, and up to 13.4 MiB for invalid blocks, which can combine a few temporary vector allocations of up to 5 MB each.

Deserialization time and memory of the deserialized block, master → PR. Runtimes are medians in milliseconds. Memory usage is in MiB, and ✕ means rejected at deserialization time. Peak memory refers to the memory during deserialization itself, not persisted in the deserialized CBlock object. Numbers over 50 ms, 20 MiB usage, or 100 MiB peak are in bold.

block gcc clang mem peak mem
Valid blocks
1 tx, max 1-byte wit elems 99.1 → 16.0 111.4 → 21.9 106.8 → 3.8 145.9 → 7.8
1 tx, max empty wit elems 279.2 → 18.7 293.7 → 25.1 91.5 → 3.8 182.2 → 7.8
max txs, 1 txin, 1 txout, 1-item wit 12.33 → 13.39 15.00 → 15.43 6.7 → 6.0 6.7 → 6.0
max txs, 1 txin and 1 txout 6.43 → 7.04 7.87 → 8.30 5.8 → 5.6 5.8 → 5.6
1 tx, max txins, 1-elem wit 4.53 → 4.68 5.04 → 5.37 4.0 → 2.9 4.0 → 2.9
mainnet block 969729 5.30 → 5.47 5.97 → 6.20 3.5 → 2.9 3.5 → 2.9
Invalid blocks
400k txs, many wit elems, truncated 84.8 → 16.1 95.6 → 21.8 ✕ → ✕ 150.7 → 12.6
400k txs, big wit+scriptsig, truncated 84.0 → 16.1 96.0 → 21.7 ✕ → ✕ 150.7 → 13.4
1 tx, 2M 1-byte wit elems 98.0 → 10.6 109.9 → 16.2 106.8 → ✕ 145.9 → 7.8
1 tx, 4M empty wit elems 271.0 → 13.4 288.9 → 19.6 91.6 → ✕ 182.2 → 7.8
max empty txs 101.0 → 0.006 139.0 → 0.008 67.1 → ✕ 67.1 → 4.8
max txs, 1 txin, 1 txout 27.6 → 7.3 34.5 → 8.5 23.4 → ✕ 23.4 → 6.4

So in addition to improving worst cases very significantly, it also provides modest memory usage improvements to the common case. This translates to mildly increasing the effective capacity of memory-bounded data structures that store transactions, like the mempool.

Some notable changes:

  • By implementing some checks (for inherently consensus-invalid things) in the deserialization logic, behavior may change. In particular, deserialization errors in P2P cause messages to be dropped/ignored, rather than triggering validation or net processing logic (which may include disconnections and/or inserting into reject filters).
  • The rejection of transactions with too many inputs or outputs applies everywhere, including in RPC. That's hopefully a desirable change, but a change in behavior still.
  • Random access to the witness stack elements becomes $\mathcal{O}(n)$. This is not a problem for any validation logic, but may be relevant for the libbitcoinkernel API which exposes an individual element accessor.

Issue reported by furszy and 0xB10C.

There are a few possible follow-ups:

  • Enforce the 400k WU policy limit during transaction deserialization when active (instead of the 4M WU consensus limit).
  • Extend this approach to entire CTransaction, allowing all transaction data to be stored packed together in a few allocations (rather than one per input, one per output, one per witness) plus some index structure to access it efficiently. That's a much bigger change, needing abstractions like Encapsulation for CTransaction #35569, but would reduce the maximum memory usage per WU for valid blocks from around 1.5 bytes/WU to 1.1 bytes/WU (compared to ~28 bytes/WU in master).

@DrahtBot

DrahtBot commented Oct 14, 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
ACK Yudis-bit
Concept NACK purpleKarrot
Concept ACK furszy, 0xB10C, instagibbs, w0xlt, rkrux, ismaelsadeeq, fanquake, l0rinc
Approach ACK darosior, 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)
  • #36787 (cmpctblock: Cache serialized cmpctblock msg for relay [part of prefill series] by davidgumberg)
  • #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)
  • #35558 (p2p: Prefill compact blocks by davidgumberg)
  • #35522 (refactor: Extract per-message helpers from SendMessages() (move-only) by pablomartin4btc)
  • #35502 (refactor: extract per-message helpers from ProcessMessage (move-only) by w0xlt)
  • #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.

@furszy

furszy commented Oct 14, 2026

Copy link
Copy Markdown
Member

Obvious concept ACK

@0xB10C

0xB10C commented Oct 14, 2026

Copy link
Copy Markdown
Contributor

Concept ACK

@sipa
sipa force-pushed the 202610_witpack branch 2 times, most recently from 091f56b to e1cbb97 Compare October 14, 2026 07:25
@instagibbs

Copy link
Copy Markdown
Member

definite concept ACK, this issue with exceptional tx types shows up in a lot of places, like #36015

@w0xlt

w0xlt commented Oct 15, 2026

Copy link
Copy Markdown
Contributor

Concept ACK

1 similar comment
@rkrux

rkrux commented Oct 15, 2026

Copy link
Copy Markdown
Contributor

Concept ACK

@Yudis-bit

Copy link
Copy Markdown

In IsWitnessStandard (src/policy/policy.cpp), tx.vin[i].scriptWitness.ToSpans() allocates on the heap for every Taproot input, even though for standard keypath spends (size() == 1) no policy rules apply. Since back() is O(1), checking witness.size() >= 2 and witness.back() upfront before calling ToSpans() avoids that allocation.

Similarly in the P2WSH check, ToSpans() is used for indexed access up to sizeWitnessStack. Iterating directly over scriptWitness with a counter avoids allocating the vector of spans without doing O(n^2) indexing.

@Yudis-bit

Copy link
Copy Markdown

+1 on splitting. The interface abstraction is uncontroversial and can go in first.

The views::take change in 60b2da3 looks clean, drops the allocations without touching behavior.

re-ACK c655a69, tests pass locally (unit, feature_block, p2p_invalid_tx).

@purpleKarrot

Copy link
Copy Markdown
Contributor

(the first half of) this PR is: the introduction of an abstraction layer for CScriptWitness, sufficient to hide the representation aspects

Thanks for the explanation @sipa. I think that resolves my concerns. I would still prefer another approach:

  1. Let's agree that encapsulation on Core's vocabulary types provides us a benefit by itself, and that we want to utilize it here.
  2. Let's discuss how the API of Core's vocabulary types should look like.
  3. Let's agree on an how we want to transform the current code base to our desired state (eg use a custom clang-tidy check).
  4. Let's make the transition in a concentrated effort. This step is expected to be invasive.
  5. Show in this PR that changing the data layout is actually not invasive.

Step 1 is the most important one, and I think it does not receive sufficient attention in the current approach. This is where we should discuss how CTxIn exposes CScriptWitness. If we provide a GetScriptWitness() observer that returns CScriptWitness by const reference, we are leaking the implementation details that CTxIn definitely contains a CScriptWitness object. But if that observer returns CScriptWitness by value, we can keep its details internal. This would allow storing a vector<vector<byte>> inside CTxIn and define CScriptWitness as a view (inheriting from ranges::view_interface) of span<const byte> initially, and later change the implementation without affecting the API.

sedited added a commit that referenced this pull request Nov 6, 2026
…ively

b7abd88 test: construct mempool_tests inputs/outputs declaratively (Alexander Wiederin)

Pull request description:

  Part of #36692. This replaces the field-by-field construction of transaction inputs and outputs in `mempool_tests` with `COutPoint`, `CTxIn` and `CTxOut` constructor calls.

  It keeps `CMutableTransaction` as the builder, since a `CTransaction` constructor taking inputs and outputs directly is still under discussion (#36696). If one is added, the `vin`/`vout` lists here can be passed to it directly. Either way, the declarative form makes the constructed transactions easier to read.

  This change is test-only and does not change the constructed transactions.

  The `mempool_eviction` bench and `rbf_tests` changes from the earlier version of this PR have been dropped, as they conflict with #36521. They can follow once that is resolved.

ACKs for top commit:
  sedited:
    ACK b7abd88
  yuvicc:
    lgtm ACK b7abd88
  janb84:
    tACK b7abd88

Tree-SHA512: 5d1ebdad6d5029a310434415cb0bcbe0bdaddfcee0fd3381eb03b9189a851187e302e794e74b81b7bb193ab14425a40dd531f0eea14baf774171fc168748eec5
@fametrano

fametrano commented Nov 7, 2026 •

Copy link
Copy Markdown

On c655a69, VerifyWitnessProgram still copies the whole witness before the version check (interpreter.cpp:1933; my earlier comment). fametrano:36521-defer-witness-copy, one commit on top, reads the witness script, annex, control block and leaf script through views, as master does, and copies the rest only on the paths that call ExecuteWitnessScript.

On the "1 tx, max empty wit elems" block, the Verify 1 txins bench line drops from 15.4 ms (median) to 0.02 ms. In peak heap during VerifyScript, above what was held before it, c655a69 holds 91.3 MiB more than the fix, and for a 3.9 MB tapscript leaf about 3.7 MiB more than the fix or the merge base 0e38ad2. witness_diff.py, run with the fix against c655a69, matched on the 37 signed spends that reach script verification. Core's script, transaction and segwit/taproot tests pass. The scripts and logs are in this gist.

I think the fix is needed here, since without it this PR makes witness verification costlier than on master. @sipa, I know how much the PR already carries, but would you take the commit, adapted however you prefer?

@sipa

sipa commented Nov 9, 2026

Copy link
Copy Markdown
Member Author

@fametrano

I don't think your patch is important here. Script validation happens after PoW is checked on a block, so attackers are rate limited by it (one per ~10 minutes). The point of the PR is reducing deserialization costs, as they happen before we have a chance to reject anything quickly. This means that they can be triggered by any peer, at any time, at basically zero cost. Resources spent after PoW checks can only be exploited by miners, infrequently, and if it comes at the cost of making the block invalid also at huge expense. The change here certainly enables future improvements in other parts of the code like validation, but at this point I don't want to burden the PR further.

I think the fix is needed here, since without it this PR makes witness verification costlier than on master.

I believe this fails to see the big picture. Yes, it makes validation seen in isolation in some cases more expensive, but simultaneously makes deserialization even more cheaper, so in aggregate the time to receive and process a block still goes down, and part of the more expensive logic was moved after PoW and other checks. Even if that were not the case, I don't think 15 ms for block validation is concerning to begin with, and the gains of your patch don't apply to the worst case, as there are other script types that still need to perform the full copy.


@purpleKarrot

This PR is a bug fix, and I don't think we should gate those behind getting agreement on refactoring concerns, especially as we may want it backported. Of course, if it were to actively interfere with your goals/PRs, especially in a way that's easy to address, I'd love to hear it. However, I don't think that's the case: if/when we decide to encapsulate CTransaction, and perhaps make a GetScriptWitness() that returns a "view" object for the witness by value rather than a reference to its actual storage, nothing will have been lost or made more complicated by this PR having changed the interface of CScriptWitness.

Comment thread src/script/script.cpp Outdated
m_data.reset();
return;
}
std::ranges::copy(data, Allocate(data.size()).begin());

@instagibbs instagibbs Nov 9, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

a1cea0d

on my gcc13.3, this is compiling to a byte loop, vs memcpy, which is causing a bit of a slowdown. It's fixed in later releases, and works fine in guix builds. No fix for 12.X.

https://inbox.sourceware.org/gcc-bugs/[email protected]%2Fbugzilla%2F/T/#u

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

If guix is not affected, my preference is to ignore the issue. It doesn't affect production binaries, and is a transient problem for from-source builds.

@purpleKarrot

Copy link
Copy Markdown
Contributor

This PR is a bug fix, and I don't think we should gate those behind getting agreement on refactoring concerns

I don't think we should treat bug fixes and refactoring as competing priorities. Quite the opposite: the more important a bug fix is, the more deliberate we should be about how we approach it.

I'm not asking to postpone the fix until we find an optimal data representation, nor am I suggesting that it must wait for #35569.

What I am proposing is a different process:

  1. Agree on a plan for addressing the problem.
  2. Make the necessary preparatory refactoring in separate, behavior-preserving PRs.
  3. Apply the actual bug fix in a small, focused PR.

This separates architectural changes from behavioral changes, makes each step easier to review, and reduces the potential for merge conflicts. I would expect this to increase the chances of getting the fix merged sooner, not later.

You already describe the first part of this PR as introducing an abstraction layer. Why not extract that into a separate PR, merge it first, and then apply the optimized representation on top?

To me, the urgency of a bug fix is an argument for a disciplined process, not against it.

@fanquake fanquake added this to the 33.0 milestone Nov 10, 2026
@fanquake

Copy link
Copy Markdown
Member

Concept ACK - Given what is being fixed here, I think it's important that any changes remain (as easily as possible) backportable. I've also put this onto the v33 milestone, to indicate that I think we want to ship some improvements to this issue (and possibly into release branches), by then.

@darosior

Copy link
Copy Markdown
Member

Concept ACK, approach ACK.

@alexanderwiederin That sounds pretty reasonable; the PR has grown a bit beyond its original intentions and it may be worth splitting up. I'll wait for a few more review comments to see what others think.

I'm skeptical splitting up refactorings first is useful. Splitting the later deserialization checks from the earlier memory optimisation could make sense, but i don't feel strongly.

@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

I'm just -0 on the last commit (plus nits) at the moment, so would be a proper ack on the rest of the PR if that commit was deferred (if you want to rush), otherwise will finish poking at alternative approaches and update.

if (num_witness > 0) {
mtx.vin[0].scriptWitness = CScriptWitness{};
mtx.vin[0].scriptWitness.stack.resize(num_witness);
mtx.vin[0].scriptWitness = CScriptWitness{std::vector<std::vector<unsigned char>>(num_witness)};

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.

nit: redundant double assignment

Comment thread src/streams.h
size_t size() const { return m_data.size(); }
bool empty() const { return m_data.empty(); }
//! The data that remains to be read (referring to the underlying data, not a copy of it).
std::span<const std::byte> Remaining() const { return m_data; }

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.

nit: Remaining() sounds like it should return a count (and does for LineReader::Remaining()). Maybe RemainingData() or RemainingSpan() or Unread() would be better? OTOH, I don't think this function is actually used outside of tests by the end of this patchset, so could also be dropped entirely?

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.

+1 for dropping it. It's only used by its own test now, like the ToSpans() leftover.

Comment thread src/script/script.h
* is O(n) in the position from the bottom of the stack.
*/
struct CScriptWitness
class CScriptWitness

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.

nit: Mild preference for removing the old interface and switching from struct to class as a separate commit to introducing the new representation.

Comment thread src/script/script.h Outdated
friend bool operator==(const Iterator&, const Iterator&) noexcept = default;
/** Iterators over the same stack are equal if the same number of bytes of its serialization
* remain. */
friend bool operator==(const Iterator& a, const Iterator& b) noexcept { return a.m_reader.size() == b.m_reader.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.

Might be worth having a SameSpan(a, b) { return a.data() == b.data() && a.size() == b.size(); } and using SameSpan(a.m_reader.Remaining(), b.m_reader.Remaining()) ? Similarly for after the reader becomes a span and this switches from a size comparison to a data comparison.

Comment thread src/net_processing.cpp
// The prefilled transactions are part of the block, so stop deserializing as soon as they exceed the weight
// that the transactions of a valid block can have.
uint64_t weight_left{MAX_BLOCK_TXS_WEIGHT};
vRecv >> TxWithWitnessP2P(weight_left)(cmpctblock);

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.

I don't like the approach of having to declare a storage location in the caller here, or passing a "const pointer to non-const" in the params, but I don't yet have a better alternative to suggest.

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.

Here's an alternative that I like better: https://github.com/ajtowns/bitcoin/commits/202611-pr36521-ser/

It modifes ParamsStream to also support mutable state if the params have a State class and an InitState method, and provides a GetState function to access/modify that state. At the caller side, you just have:

static constexpr TransactionSerParams TX_WITH_WITNESS_BLOCK_LIMIT{
    .allow_witness = true, .reject_empty = true, .max_weight = MAX_BLOCK_TXS_WEIGHT
};

vRecv >> TX_WITH_WITNESS_BLOCK_LIMIT(*pblock);

@l0rinc l0rinc 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: I'd like to see this in v33 (and parts of it backported).
I also found and reported several witness amplification problems, and this fixes many of them: excessive memory retained by witness-heavy orphans and blocks held during reorgs, and decoding spikes in transactions, compact-block prefills and blocktxn responses. Thanks for tackling this.

I've only done a first pass so far and left some nits and simplifications inline. I'd like to go deeper once the changes are split up.

I agree with others about splitting out the interface addition, the serialized representation, and the early deserialization checks. Keeping rejection of invalid and empty transactions separate from changes to valid witness storage would make the RPC/P2P behavior changes easier to review. Some older branches may only want the checks rejecting invalid and empty transactions. #35936 does something similar for locators, rejecting oversized counts before allocating.

#36548 also extracts UnserializeTransactionBody so decoding and witness stripping share the same rules. If it helps, I'm happy to prepare that extraction separately around the count-first parsing here. Otherwise I'll rebase #36548 on top and adapt it to the new count checks and weight budget.

The synthetic block builder in the new benchmark overlaps with the configurable block generator in #32554, which also replaces the hardcoded raw block fixture. I'm happy to unify them either before or after this change, whichever is easier.


Edit: To simplify my review, I amended your changes locally, splitting the large scripted diff (e78a86fa) and the manual caller-conversion commit (11b5566f) into smaller commits, please consider if you think this would also help others:

  • Scripted accessor substitutions: size(), empty() and back() can be migrated independently with simple scripted diffs.
  • Scripted reads and comparisons: indexed access, const witness references, and equality/emptiness checks.
  • Scripted serialization: stream reads/writes and serialized-size calculations through the witness interface.
  • Scripted replacement: clearing a witness or assigning a newly constructed one.
  • Manual loop conversions, moved out of the scripted diff: for example, for (const auto& item : witness.stack) becomes for (const auto item : witness). The old element is a referenced byte vector. The new element is a span copied by value, borrowing bytes from the witness. I wouldn't expect these changes in scripted diffs. Its type and lifetime deserve explicit review.
  • Manual interpreter changes, split from the caller-conversion commit: creating the mutable stack with ToVectors() and moving it into execution after extracting the script, annex or control data.

Comment thread src/script/script.h
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;

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.

c655a69 p2p: limit the weight of transactions and blocks while deserializing:

After this change, we could clean up the leftovers.

s << CBlockHeader{};
// Transactions.
WriteCompactSize(s, shape.num_txn);
for (size_t i = 0; i < shape.num_txn; ++i) s.write(MakeByteSpan(tx));

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.

c655a69 p2p: limit the weight of transactions and blocks while deserializing:

We can reuse the CTxIn and CTxOut serializers here and write transactions directly into the block buffer.

As a follow-up (or prerequisite), we should extract and generalize the block creator in this benchmark along the lines of #32554, so a shared generator can replace the hardcoded raw block fixture.

Reuse benchmark serializers
diff --git a/src/bench/block_deserialize.cpp b/src/bench/block_deserialize.cpp
index cd45c56a34..1051e37c8d 100644
--- a/src/bench/block_deserialize.cpp
+++ b/src/bench/block_deserialize.cpp
@@ -8,15 +8,14 @@
 #include <consensus/validation.h>
 #include <primitives/block.h>
 #include <primitives/transaction.h>
+#include <script/script.h>
 #include <serialize.h>
-#include <span.h>
 #include <streams.h>
 #include <uint256.h>
 
 #include <cassert>
 #include <cstddef>
 #include <cstdint>
-#include <span>
 #include <vector>
 
 namespace {
@@ -49,22 +48,17 @@ void WriteTx(VectorWriter& s, const BlockShape& shape)
     if (have_witness) s << uint8_t{0} << uint8_t{1};
     // Inputs.
     WriteCompactSize(s, shape.num_txin);
+    CScript script_sig;
+    script_sig.assign(shape.size_scriptsig, 0x51);
     for (size_t i = 0; i < shape.num_txin; ++i) {
-        // Prevout.
-        s << uint256::ONE << uint32_t(i);
-        // scriptSig (all OP_1).
-        s << std::vector<unsigned char>(shape.size_scriptsig, 0x51);
-        // nSequence.
-        s << CTxIn::SEQUENCE_FINAL;
+        s << CTxIn{Txid::FromUint256(uint256::ONE), uint32_t(i), script_sig};
     }
     // Outputs.
     WriteCompactSize(s, shape.num_txout);
-    for (size_t i = 0; i < shape.num_txout; ++i) {
-        // nValue (1 BTC).
-        s << COIN;
-        // scriptPubKey (all OP_2).
-        s << std::vector<unsigned char>(shape.size_spk, 0x52);
-    }
+    CScript script_pub_key;
+    script_pub_key.assign(shape.size_spk, 0x52);
+    const CTxOut output{COIN, script_pub_key};
+    for (size_t i = 0; i < shape.num_txout; ++i) s << output;
     // Witnesses.
     if (have_witness) {
         for (size_t i = 0; i < shape.num_txin; ++i) {
@@ -83,12 +77,6 @@ void WriteTx(VectorWriter& s, const BlockShape& shape)
 /** Benchmark deserializing a block of the specified shape. */
 void DeserializeBlock(benchmark::Bench& bench, const BlockShape& shape)
 {
-    // Construct one serialized transaction.
-    std::vector<unsigned char> tx;
-    {
-        VectorWriter s{tx, 0};
-        WriteTx(s, shape);
-    }
     // Construct serialized block.
     std::vector<unsigned char> data;
     {
@@ -97,7 +85,7 @@ void DeserializeBlock(benchmark::Bench& bench, const BlockShape& shape)
         s << CBlockHeader{};
         // Transactions.
         WriteCompactSize(s, shape.num_txn);
-        for (size_t i = 0; i < shape.num_txn; ++i) s.write(MakeByteSpan(tx));
+        for (size_t i = 0; i < shape.num_txn; ++i) WriteTx(s, shape);
     }
     // Verify block deserialization succeeds and has valid weight.
     {


BOOST_AUTO_TEST_CASE(weight_limited_deserialization)
{
const auto ser{[](const auto& obj) {

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.

c655a69 p2p: limit the weight of transactions and blocks while deserializing:

These tests can use DataStream directly instead of repeating the ser lambdas and block setup.

Reuse DataStream in serialization tests
diff --git a/src/test/transaction_tests.cpp b/src/test/transaction_tests.cpp
index 708c16b9ea..d9fbf8d7ad 100644
--- a/src/test/transaction_tests.cpp
+++ b/src/test/transaction_tests.cpp
@@ -1454,16 +1454,11 @@ BOOST_AUTO_TEST_CASE(too_many_inputs_or_outputs)
 
 BOOST_AUTO_TEST_CASE(reject_empty)
 {
-    const auto deser_tx{[](std::span<const unsigned char> data, const TransactionSerParams& params) {
+    const auto deser_tx{[](const auto& data, const TransactionSerParams& params) {
         CMutableTransaction tx;
         SpanReader{data} >> params(tx);
         return tx;
     }};
-    const auto ser{[](const CMutableTransaction& tx, const TransactionSerParams& params) {
-        std::vector<unsigned char> ret;
-        VectorWriter{ret, 0, params(tx)};
-        return ret;
-    }};
 
     CMutableTransaction valid;
     valid.vin.resize(1);
@@ -1473,17 +1468,17 @@ BOOST_AUTO_TEST_CASE(reject_empty)
     const CMutableTransaction empty;
 
     // A transaction with inputs and outputs is accepted either way.
-    BOOST_CHECK(CTransaction{deser_tx(ser(valid, TX_WITH_WITNESS), TX_WITH_WITNESS_P2P)}.GetWitnessHash() == CTransaction{valid}.GetWitnessHash());
+    BOOST_CHECK(CTransaction{deser_tx(DataStream{} << TX_WITH_WITNESS(valid), TX_WITH_WITNESS_P2P)}.GetWitnessHash() == CTransaction{valid}.GetWitnessHash());
 
     // A transaction without inputs or outputs (version, 0x00, 0x00, locktime) deserializes normally, but not with
     // TX_WITH_WITNESS_P2P.
-    const auto empty_ser{ser(empty, TX_WITH_WITNESS)};
+    const auto empty_ser{DataStream{} << TX_WITH_WITNESS(empty)};
     BOOST_CHECK_EQUAL(empty_ser.size(), 10U);
     BOOST_CHECK(deser_tx(empty_ser, TX_WITH_WITNESS).vin.empty());
     BOOST_CHECK_EXCEPTION(deser_tx(empty_ser, TX_WITH_WITNESS_P2P), std::ios_base::failure, HasReason("Transaction without inputs"));
 
     // A transaction without outputs.
-    const auto no_outputs_ser{ser(no_outputs, TX_WITH_WITNESS)};
+    const auto no_outputs_ser{DataStream{} << TX_WITH_WITNESS(no_outputs)};
     BOOST_CHECK(deser_tx(no_outputs_ser, TX_WITH_WITNESS).vout.empty());
     BOOST_CHECK_EXCEPTION(deser_tx(no_outputs_ser, TX_WITH_WITNESS_P2P), std::ios_base::failure, HasReason("Transaction without outputs"));
 
@@ -1503,8 +1498,7 @@ BOOST_AUTO_TEST_CASE(reject_empty)
     CBlock block;
     block.vtx.push_back(MakeTransactionRef(valid));
     block.vtx.push_back(MakeTransactionRef(empty));
-    std::vector<unsigned char> block_ser;
-    VectorWriter{block_ser, 0, TX_WITH_WITNESS(block)};
+    const auto block_ser{DataStream{} << TX_WITH_WITNESS(block)};
     CBlock block_deser;
     SpanReader{block_ser} >> TX_WITH_WITNESS(block_deser);
     BOOST_CHECK_EQUAL(block_deser.vtx.size(), 2U);
@@ -1513,11 +1507,6 @@ BOOST_AUTO_TEST_CASE(reject_empty)
 
 BOOST_AUTO_TEST_CASE(weight_limited_deserialization)
 {
-    const auto ser{[](const auto& obj) {
-        std::vector<unsigned char> ret;
-        VectorWriter{ret, 0, TX_WITH_WITNESS(obj)};
-        return ret;
-    }};
     const auto random_bytes{[&](size_t max_size) {
         // Sometimes cross a CompactSize encoding boundary.
         return m_rng.randbytes(m_rng.randbool() ? m_rng.randrange(max_size) : 250 + m_rng.randrange(10));
@@ -1554,7 +1543,7 @@ BOOST_AUTO_TEST_CASE(weight_limited_deserialization)
     // Deserializing a transaction with a weight limit succeeds if and only if the limit is at least its weight, and
     // then consumes exactly its weight.
     for (const auto& tx : txs) {
-        const auto data = ser(tx);
+        const auto data = DataStream{} << TX_WITH_WITNESS(tx);
         const auto weight = GetTransactionWeight(CTransaction{tx});
         for (const uint64_t limit : {uint64_t(weight), uint64_t(weight) + 1, uint64_t(weight) - 1}) {
             uint64_t weight_left{limit};
@@ -1578,7 +1567,7 @@ BOOST_AUTO_TEST_CASE(weight_limited_deserialization)
         block.vtx.push_back(MakeTransactionRef(tx));
         txs_weight += GetTransactionWeight(*block.vtx.back());
     }
-    const auto data = ser(block);
+    const auto data = DataStream{} << TX_WITH_WITNESS(block);
     BOOST_CHECK_EQUAL(GetBlockWeight(block), txs_weight + WITNESS_SCALE_FACTOR * int64_t(80 + 1));
     for (const auto limit : {txs_weight, txs_weight - 1}) {
         uint64_t weight_left(limit);

Comment thread src/test/fuzz/util.cpp
CScriptWitness script_wit;
if (p2wsh_op_true) {
script_wit.stack = std::vector<std::vector<uint8_t>>{WITNESS_STACK_ELEM_OP_TRUE};
script_wit = CScriptWitness{std::vector<std::vector<uint8_t>>{WITNESS_STACK_ELEM_OP_TRUE}};

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.

c655a69 p2p: limit the weight of transactions and blocks while deserializing:

Batched a few nits found during review (to minimize separate comments): a few witness conversions can drop a redundant assignment, an explicit element type, and an extra copy in the RBF fixture, and use ToByteVector() for the public keys.
The test JSON writer can iterate directly rather than indexing the packed witness, and policy.cpp no longer needs <span.h>.
The block weight budget can sit with the other block limits, and the JSON error loop can drop its iteration comment.

Trim witness migration residue
diff --git a/src/bench/block_assemble.cpp b/src/bench/block_assemble.cpp
index 53dbe75d18..c2735912b3 100644
--- a/src/bench/block_assemble.cpp
+++ b/src/bench/block_assemble.cpp
@@ -26,8 +26,7 @@ static void AssembleBlock(benchmark::Bench& bench)
 {
     const auto test_setup = MakeNoLogFileContext<const TestingSetup>();
 
-    CScriptWitness witness;
-    witness = CScriptWitness{{WITNESS_STACK_ELEM_OP_TRUE}};
+    const CScriptWitness witness{{WITNESS_STACK_ELEM_OP_TRUE}};
     BlockCreateOptions options{
         .coinbase_output_script = P2WSH_OP_TRUE,
     };
diff --git a/src/net_processing.cpp b/src/net_processing.cpp
index a6a8666690..8c5bb3f0fe 100644
--- a/src/net_processing.cpp
+++ b/src/net_processing.cpp
@@ -111,9 +111,6 @@ static constexpr int32_t MAX_OUTBOUND_PEERS_TO_PROTECT_FROM_DISCONNECT = 4;
 static constexpr auto CHAIN_SYNC_TIMEOUT{20min};
 /** How frequently to check for stale tips */
 static constexpr auto STALE_CHECK_INTERVAL{10min};
-/** The total weight that the transactions of a valid block can have: MAX_BLOCK_WEIGHT minus that of
- *  the block's header (80 bytes) and (at least a 1-byte) transaction count. */
-static constexpr uint64_t MAX_BLOCK_TXS_WEIGHT{MAX_BLOCK_WEIGHT - WITNESS_SCALE_FACTOR * (80 + 1)};
 /** How frequently to check for extra outbound peers and disconnect */
 static constexpr auto EXTRA_PEER_CHECK_INTERVAL{45s};
 /** Minimum time an outbound-peer-eviction candidate must be connected for, in order to evict */
@@ -151,6 +148,9 @@ static const int MAX_CMPCTBLOCK_DEPTH = 5;
 /** Maximum depth of blocks we're willing to respond to GETBLOCKTXN requests for. */
 static const int MAX_BLOCKTXN_DEPTH = 10;
 static_assert(MAX_BLOCKTXN_DEPTH <= MIN_BLOCKS_TO_KEEP, "MAX_BLOCKTXN_DEPTH too high");
+/** The total weight that the transactions of a valid block can have: MAX_BLOCK_WEIGHT minus that of
+ *  the block's header (80 bytes) and (at least a 1-byte) transaction count. */
+static constexpr uint64_t MAX_BLOCK_TXS_WEIGHT{MAX_BLOCK_WEIGHT - WITNESS_SCALE_FACTOR * (80 + 1)};
 /** Size of the "block download window": how far ahead of our current height do we fetch?
  *  Larger windows tolerate larger download speed differences between peer, but increase the potential
  *  degree of disordering of blocks on disk (which make reindexing and pruning harder). We'll probably
diff --git a/src/policy/policy.cpp b/src/policy/policy.cpp
index 5add4a6a00..dc5b2c787a 100644
--- a/src/policy/policy.cpp
+++ b/src/policy/policy.cpp
@@ -17,7 +17,6 @@
 #include <script/script.h>
 #include <script/solver.h>
 #include <serialize.h>
-#include <span.h>
 #include <tinyformat.h>
 
 #include <algorithm>
diff --git a/src/rpc/rawtransaction_util.cpp b/src/rpc/rawtransaction_util.cpp
index 46436c9dad..c15a88fffa 100644
--- a/src/rpc/rawtransaction_util.cpp
+++ b/src/rpc/rawtransaction_util.cpp
@@ -192,7 +192,6 @@ static void TxInErrorToJSON(const CTxIn& txin, UniValue& vErrorsRet, const std::
     entry.pushKV("txid", txin.prevout.hash.ToString());
     entry.pushKV("vout", txin.prevout.n);
     UniValue witness(UniValue::VARR);
-    // Iterate over the elements, rather than indexing them, as indexing need not be constant-time.
     for (const auto element : txin.scriptWitness) {
         witness.push_back(HexStr(element));
     }
diff --git a/src/test/bip352_tests.cpp b/src/test/bip352_tests.cpp
index b5bfdad77c..ec7fb7b322 100644
--- a/src/test/bip352_tests.cpp
+++ b/src/test/bip352_tests.cpp
@@ -233,7 +233,7 @@ BOOST_AUTO_TEST_CASE(bip352_skips_transactions_spending_unknown_segwit_versions)
     COutPoint unknown_segwit_outpoint{Txid::FromHex("0000000000000000000000000000000000000000000000000000000000000002").value(), 0};
 
     CTxIn eligible_input{eligible_outpoint};
-    eligible_input.scriptWitness = CScriptWitness{{std::vector<unsigned char>(64, 0), {pubkey.begin(), pubkey.end()}}};
+    eligible_input.scriptWitness = CScriptWitness{{std::vector<unsigned char>(64, 0), ToByteVector(pubkey)}};
 
     std::map<COutPoint, Coin> coins;
     coins[eligible_outpoint] = Coin{CTxOut{{}, GetScriptForDestination(WitnessV0KeyHash{pubkey})}, 0, false};
@@ -258,7 +258,7 @@ BOOST_AUTO_TEST_CASE(bip352_scan_skips_invalid_taproot_outputs)
 
     CTxIn txin{outpoint};
     const CPubKey sender_pubkey{sender_key.GetPubKey()};
-    txin.scriptWitness = CScriptWitness{{{}, {sender_pubkey.begin(), sender_pubkey.end()}}};
+    txin.scriptWitness = CScriptWitness{{{}, ToByteVector(sender_pubkey)}};
 
     std::map<COutPoint, Coin> coins;
     coins[outpoint] = Coin{CTxOut{{}, GetScriptForDestination(WitnessV0KeyHash{sender_pubkey})}, 0, false};
diff --git a/src/test/fuzz/util.cpp b/src/test/fuzz/util.cpp
index 082e0d3b7d..9946559f8c 100644
--- a/src/test/fuzz/util.cpp
+++ b/src/test/fuzz/util.cpp
@@ -58,7 +58,7 @@ CMutableTransaction ConsumeTransaction(FuzzedDataProvider& fuzzed_data_provider,
         const auto script_sig = p2wsh_op_true ? CScript{} : ConsumeScript(fuzzed_data_provider);
         CScriptWitness script_wit;
         if (p2wsh_op_true) {
-            script_wit = CScriptWitness{std::vector<std::vector<uint8_t>>{WITNESS_STACK_ELEM_OP_TRUE}};
+            script_wit = CScriptWitness{{WITNESS_STACK_ELEM_OP_TRUE}};
         } else {
             script_wit = ConsumeScriptWitness(fuzzed_data_provider);
         }
diff --git a/src/test/rbf_tests.cpp b/src/test/rbf_tests.cpp
index 960f664a8c..97f235f21f 100644
--- a/src/test/rbf_tests.cpp
+++ b/src/test/rbf_tests.cpp
@@ -27,8 +27,7 @@ static inline CTransactionRef make_tx(const std::vector<CTransactionRef>& inputs
         tx.vin[i].prevout.hash = inputs[i]->GetHash();
         tx.vin[i].prevout.n = 0;
         // Add a witness so wtxid != txid
-        CScriptWitness witness{{std::vector<unsigned char>(i + 10)}};
-        tx.vin[i].scriptWitness = witness;
+        tx.vin[i].scriptWitness = CScriptWitness{{std::vector<unsigned char>(i + 10)}};
     }
     for (size_t i = 0; i < output_values.size(); ++i) {
         tx.vout[i].scriptPubKey = CScript() << OP_11 << OP_EQUAL;
diff --git a/src/test/script_tests.cpp b/src/test/script_tests.cpp
index dd5d85e47a..10a6ce0ed2 100644
--- a/src/test/script_tests.cpp
+++ b/src/test/script_tests.cpp
@@ -396,9 +396,8 @@ public:
         UniValue array(UniValue::VARR);
         if (!scriptWitness.empty()) {
             UniValue wit(UniValue::VARR);
-            // Indexing a CScriptWitness is O(n), so this loop is quadratic, which is fine for the small witnesses here.
-            for (unsigned i = 0; i < scriptWitness.size(); i++) {
-                wit.push_back(HexStr(scriptWitness[i]));
+            for (const auto element : scriptWitness) {
+                wit.push_back(HexStr(element));
             }
             wit.push_back(ValueFromAmount(nValue));
             array.push_back(std::move(wit));

BOOST_AUTO_TEST_CASE(decode_compactsize)
{
// DecodeCompactSize decodes what WriteCompactSize encodes, advancing past each value.
static constexpr uint64_t VALUES[]{0, 252, 253, 0xffff, 0x10000, 0xffffffff, 0x100000000, std::numeric_limits<uint64_t>::max()};

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.

c655a69 p2p: limit the weight of transactions and blocks while deserializing:

The two tests can share COMPACT_SIZE_BOUNDARIES.

Share CompactSize boundary cases
diff --git a/src/test/serialize_tests.cpp b/src/test/serialize_tests.cpp
index 29a955098d..6e1a03a327 100644
--- a/src/test/serialize_tests.cpp
+++ b/src/test/serialize_tests.cpp
@@ -205,13 +205,15 @@ BOOST_AUTO_TEST_CASE(compactsize)
     }
 }
 
+/** Values around the CompactSize encoding boundaries. */
+static constexpr uint64_t COMPACT_SIZE_BOUNDARIES[]{0, 252, 253, 0xffff, 0x10000, 0xffffffff, 0x100000000, std::numeric_limits<uint64_t>::max()};
+
 BOOST_AUTO_TEST_CASE(append_compactsize)
 {
-    // AppendCompactSize produces the same encoding as WriteCompactSize, for values around the encoding boundaries.
+    // AppendCompactSize produces the same encoding as WriteCompactSize.
     std::vector<std::byte> appended;
     DataStream written{};
-    for (const uint64_t n : {uint64_t{0}, uint64_t{252}, uint64_t{253}, uint64_t{0xffff}, uint64_t{0x10000},
-                             uint64_t{0xffffffff}, uint64_t{0x100000000}, std::numeric_limits<uint64_t>::max()}) {
+    for (const uint64_t n : COMPACT_SIZE_BOUNDARIES) {
         AppendCompactSize(appended, n);
         WriteCompactSize(written, n);
     }
@@ -221,11 +223,10 @@ BOOST_AUTO_TEST_CASE(append_compactsize)
 BOOST_AUTO_TEST_CASE(decode_compactsize)
 {
     // DecodeCompactSize decodes what WriteCompactSize encodes, advancing past each value.
-    static constexpr uint64_t VALUES[]{0, 252, 253, 0xffff, 0x10000, 0xffffffff, 0x100000000, std::numeric_limits<uint64_t>::max()};
     DataStream data{};
-    for (const uint64_t n : VALUES) WriteCompactSize(data, n);
+    for (const uint64_t n : COMPACT_SIZE_BOUNDARIES) WriteCompactSize(data, n);
     std::span<const std::byte> rest{data};
-    for (const uint64_t n : VALUES) {
+    for (const uint64_t n : COMPACT_SIZE_BOUNDARIES) {
         const auto size_before = rest.size();
         BOOST_CHECK_EQUAL(DecodeCompactSize(rest), n);
         BOOST_CHECK_EQUAL(size_before - rest.size(), GetSizeOfCompactSize(n));

Comment thread src/script/script.cpp
SpanWriter{Allocate(size, size - GetSizeOfCompactSize(last.size()) - last.size()), stack};
}

void CScriptWitness::Assign(std::span<const std::byte> data, size_t last_offset)

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.

c655a69 p2p: limit the weight of transactions and blocks while deserializing:

Assign() has just one caller, which already returns for a zero element count. We can inline it into Unserialize() and drop the unreachable empty-data branch.

DeserializeBlock(bench, {.num_txn = 4385,
.num_txin = 2,
.num_txout = 2, .size_spk = 22,
.num_wit_items = 2, .size_wit_item = 72});

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.

c655a69 p2p: limit the weight of transactions and blocks while deserializing:

What if we used a 33-byte compressed public key alongside the 72-byte signature in the P2WPKH benchmark instead?
For two inputs and two outputs, that changes each transaction from 912 to 834 WU, so 4,795 fit instead of 4,385.

Use P2WPKH witness item sizes
diff --git a/src/bench/block_deserialize.cpp b/src/bench/block_deserialize.cpp
index 1051e37c8d..533ffbfc9f 100644
--- a/src/bench/block_deserialize.cpp
+++ b/src/bench/block_deserialize.cpp
@@ -20,7 +20,7 @@
 
 namespace {
 
-/** The shape of a synthetic block. */
+/** The shape of a synthetic block for deserialization, without consensus-valid transactions. */
 struct BlockShape {
     /** The number of transactions in the block (all identical). */
     size_t num_txn = 1;
@@ -34,13 +34,14 @@ struct BlockShape {
     size_t size_spk = 0;
     /** The number of items in each input's witness stack. */
     size_t num_wit_items = 0;
-    /** The size of each witness stack item. */
-    size_t size_wit_item = 0;
+    /** Witness item sizes, repeated to fill each stack. */
+    std::vector<size_t> sizes_wit_items{0};
 };
 
 /** Write the serialization of a transaction specified by shape. */
 void WriteTx(VectorWriter& s, const BlockShape& shape)
 {
+    assert(shape.sizes_wit_items.size());
     const bool have_witness = (shape.num_wit_items > 0);
     // Version.
     s << CTransaction::CURRENT_VERSION;
@@ -66,7 +67,7 @@ void WriteTx(VectorWriter& s, const BlockShape& shape)
             WriteCompactSize(s, shape.num_wit_items);
             for (size_t j = 0; j < shape.num_wit_items; ++j) {
                 // Witness items (all 0x03 bytes).
-                s << std::vector<unsigned char>(shape.size_wit_item, 0x03);
+                s << std::vector<unsigned char>(shape.sizes_wit_items[j % shape.sizes_wit_items.size()], 0x03);
             }
         }
     }
@@ -93,7 +94,7 @@ void DeserializeBlock(benchmark::Bench& bench, const BlockShape& shape)
         SpanReader{data} >> TX_WITH_WITNESS(block);
         assert(GetBlockWeight(block) <= MAX_BLOCK_WEIGHT);
     }
-    // Run benchmark.
+    // Includes transaction hashing and destruction. Fixture construction is outside the timed loop.
     bench.unit("block").run([&] {
         CBlock block;
         SpanReader{data} >> TX_WITH_WITNESS(block);
@@ -103,13 +104,13 @@ void DeserializeBlock(benchmark::Bench& bench, const BlockShape& shape)
 
 } // namespace
 
-/** Spends of P2WPKH outputs to P2WPKH outputs: a typical segwit block. */
+/** Transactions with the serialized sizes of two-input, two-output P2WPKH spends. */
 static void DeserializeBlockP2WPKH(benchmark::Bench& bench)
 {
-    DeserializeBlock(bench, {.num_txn = 4385,
+    DeserializeBlock(bench, {.num_txn = 4795,
                              .num_txin = 2,
                              .num_txout = 2, .size_spk = 22,
-                             .num_wit_items = 2, .size_wit_item = 72});
+                             .num_wit_items = 2, .sizes_wit_items = {72, 33}});
 }
 
 /** The smallest segwit transactions: the most transactions a block can have. */
@@ -133,7 +134,7 @@ static void DeserializeBlockManyOutputs(benchmark::Bench& bench)
 /** One transaction whose witness has as many 1-byte elements as fit. */
 static void DeserializeBlockManyWitnessElements(benchmark::Bench& bench)
 {
-    DeserializeBlock(bench, {.num_wit_items = 1999714, .size_wit_item = 1});
+    DeserializeBlock(bench, {.num_wit_items = 1999714, .sizes_wit_items = {1}});
 }
 
 BENCHMARK(DeserializeBlockP2WPKH);

// Witnesses.
if (have_witness) {
for (size_t i = 0; i < shape.num_txin; ++i) {
// Number of witness items.

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.

c655a69 p2p: limit the weight of transactions and blocks while deserializing:

I don't find most of these comments useful, they just repeat the code.

Trim redundant benchmark comments
diff --git a/src/bench/block_deserialize.cpp b/src/bench/block_deserialize.cpp
index 533ffbfc9f..3bcca13802 100644
--- a/src/bench/block_deserialize.cpp
+++ b/src/bench/block_deserialize.cpp
@@ -38,35 +38,28 @@ struct BlockShape {
     std::vector<size_t> sizes_wit_items{0};
 };
 
-/** Write the serialization of a transaction specified by shape. */
 void WriteTx(VectorWriter& s, const BlockShape& shape)
 {
     assert(shape.sizes_wit_items.size());
     const bool have_witness = (shape.num_wit_items > 0);
-    // Version.
     s << CTransaction::CURRENT_VERSION;
     // Extended serialization flag and marker, if needed.
     if (have_witness) s << uint8_t{0} << uint8_t{1};
-    // Inputs.
     WriteCompactSize(s, shape.num_txin);
     CScript script_sig;
     script_sig.assign(shape.size_scriptsig, 0x51);
     for (size_t i = 0; i < shape.num_txin; ++i) {
         s << CTxIn{Txid::FromUint256(uint256::ONE), uint32_t(i), script_sig};
     }
-    // Outputs.
     WriteCompactSize(s, shape.num_txout);
     CScript script_pub_key;
     script_pub_key.assign(shape.size_spk, 0x52);
     const CTxOut output{COIN, script_pub_key};
     for (size_t i = 0; i < shape.num_txout; ++i) s << output;
-    // Witnesses.
     if (have_witness) {
         for (size_t i = 0; i < shape.num_txin; ++i) {
-            // Number of witness items.
             WriteCompactSize(s, shape.num_wit_items);
             for (size_t j = 0; j < shape.num_wit_items; ++j) {
-                // Witness items (all 0x03 bytes).
                 s << std::vector<unsigned char>(shape.sizes_wit_items[j % shape.sizes_wit_items.size()], 0x03);
             }
         }
@@ -75,20 +68,15 @@ void WriteTx(VectorWriter& s, const BlockShape& shape)
     s << uint32_t{0};
 }
 
-/** Benchmark deserializing a block of the specified shape. */
 void DeserializeBlock(benchmark::Bench& bench, const BlockShape& shape)
 {
-    // Construct serialized block.
     std::vector<unsigned char> data;
     {
         VectorWriter s{data, 0};
-        // Header.
         s << CBlockHeader{};
-        // Transactions.
         WriteCompactSize(s, shape.num_txn);
         for (size_t i = 0; i < shape.num_txn; ++i) WriteTx(s, shape);
     }
-    // Verify block deserialization succeeds and has valid weight.
     {
         CBlock block;
         SpanReader{data} >> TX_WITH_WITNESS(block);

Comment thread src/script/script.cpp
std::span<const unsigned char> CScriptWitness::operator[](size_t index) const noexcept
{
const auto count = size();
Assume(index < count);

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.

c655a69 p2p: limit the weight of transactions and blocks while deserializing:

An Assert seems more appropriate here since we cannot continue if this doesn't hold.

Comment thread src/streams.h
size_t size() const { return m_data.size(); }
bool empty() const { return m_data.empty(); }
//! The data that remains to be read (referring to the underlying data, not a copy of it).
std::span<const std::byte> Remaining() const { return m_data; }

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.

+1 for dropping it. It's only used by its own test now, like the ToSpans() leftover.

@sipa

sipa commented Nov 16, 2026

Copy link
Copy Markdown
Member Author

Going to split this up.

@sipa sipa closed this Nov 16, 2026
@fanquake fanquake removed this from the 33.0 milestone Nov 16, 2026
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
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.