Keep witness stacks in serialized form in CScriptWitness #36521

pull sipa wants to merge 17 commits into bitcoin:master from sipa:202610_witpack changing 76 files +1255 −280
  1. sipa commented at 6:23 AM on October 14, 2026: 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 #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).
  2. DrahtBot commented at 6:23 AM on October 14, 2026: contributor

    <!--e57a25ab6845829454e8d69fc972939a-->

    The following sections might be updated with supplementary metadata relevant to reviewers and maintainers.

    <!--006a51241073e994b41acfe9ec718e94-->

    External sites

    <!--021abf342d371248e50ceaed478a90ca-->

    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 <code>&lt;!--meta-tag:bot-skip--&gt;</code> into the comment that the bot should ignore.

    <!--174a7506f384e20aa4161008e828411d-->

    Conflicts

    Reviewers, this pull request conflicts with the following ones:

    • #36853 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36853.svg"></sub> (test: Add test for CompactSize larger than MAX_SIZE value by maflcko)
    • #36787 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36787.svg"></sub> (cmpctblock: Cache serialized cmpctblock msg for relay [part of prefill series] by davidgumberg)
    • #36776 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36776.svg"></sub> (bip352: match P2SH-P2WPKH instead of evaluating it by Eunovo)
    • #36721 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36721.svg"></sub> (script: store interpreter stack elements as reference-counted objects by conduition)
    • #36548 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36548.svg"></sub> (net: serve MSG_BLOCK by stripping witnesses in place by l0rinc)
    • #36466 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36466.svg"></sub> (policy: make unstructured Taproot annexes standard by RobinLinus)
    • #36122 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36122.svg"></sub> (BIP460: CISA for Taproot key path spends by fjahr)
    • #36109 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36109.svg"></sub> (test: fix coinbases built on arbitrary parents by l0rinc)
    • #35788 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/35788.svg"></sub> (bitcoin-util: Add evalscript subcommand by ajtowns)
    • #35716 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/35716.svg"></sub> (wallet: Replace mapWallet and wtxOrdered with a boost::multi_index by achow101)
    • #35671 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/35671.svg"></sub> (mining: add TxCollection to bandwidth-efficiently validate external block templates by Sjors)
    • #35662 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/35662.svg"></sub> (script: prevent partial reinitialization of sighash data by l0rinc)
    • #35558 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/35558.svg"></sub> (p2p: Prefill compact blocks by davidgumberg)
    • #35522 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/35522.svg"></sub> (refactor: Extract per-message helpers from SendMessages() (move-only) by pablomartin4btc)
    • #35502 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/35502.svg"></sub> (refactor: extract per-message helpers from ProcessMessage (move-only) by w0xlt)
    • #31252 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/31252.svg"></sub> (rpc: print P2WSH and P2SH redem Script in getrawtransaction and getblock by polespinasa)
    • #29247 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/29247.svg"></sub> (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.

    <!--5faf32d7da4f0f540f40219e4f7537a3-->

  3. sipa force-pushed on Oct 14, 2026
  4. DrahtBot added the label CI failed on Oct 14, 2026
  5. furszy commented at 6:35 AM on October 14, 2026: member

    Obvious concept ACK

  6. 0xB10C commented at 6:35 AM on October 14, 2026: contributor

    Concept ACK

  7. sipa force-pushed on Oct 14, 2026
  8. sipa force-pushed on Oct 14, 2026
  9. DrahtBot removed the label CI failed on Oct 14, 2026
  10. instagibbs commented at 12:13 AM on October 15, 2026: member

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

  11. w0xlt commented at 6:10 AM on October 15, 2026: contributor

    Concept ACK

  12. rkrux commented at 1:06 PM on October 15, 2026: contributor

    Concept ACK

  13. Yudis-bit commented at 1:22 PM on October 17, 2026: none

    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.

  14. sipa force-pushed on Oct 19, 2026
  15. sipa commented at 1:01 AM on October 20, 2026: member

    @Yudis-bit Thanks, addressed in a separate commit at the end.

  16. Yudis-bit commented at 3:08 AM on October 20, 2026: none

    Tested ACK d3fb8e8 on Windows.

  17. DrahtBot requested review from furszy on Oct 20, 2026
  18. DrahtBot requested review from rkrux on Oct 20, 2026
  19. DrahtBot requested review from instagibbs on Oct 20, 2026
  20. DrahtBot requested review from 0xB10C on Oct 20, 2026
  21. DrahtBot added the label Needs rebase on Oct 22, 2026
  22. sipa force-pushed on Oct 22, 2026
  23. sipa commented at 6:52 PM on October 22, 2026: member

    I have added changes that also reject transactions/blocks early during deserialization which exceed the 4M WU limit. This reduces the worst-case memory and deserialization time for invalid transactions/blocks further.

  24. DrahtBot removed the label Needs rebase on Oct 22, 2026
  25. fametrano commented at 7:45 AM on October 25, 2026: none

    VerifyWitnessProgram calls witness.ToVectors() before it looks at the witness version, so the valid "1 tx, max empty wit elems" block from the description still allocates about 91 MiB, now during script verification.

    Such a witness is only valid when no script runs on it, as when it spends an unknown witness version, so the copy is never used. As in 8072be3acb, calling ToVectors() only in the branches that reach ExecuteWitnessScript would keep the saving through validation.

    I counted heap in a program that replaces operator new, linked against each build, and took times from regtest nodes running each build. With 3,990,000 empty elements spending a v2 output, deserialization peaks at 7.8 MiB on bd51226995 against 182.7 MiB on its base. VerifyScript then makes a 91.3 MiB copy that the base does not make. The Verify 1 txins bench line goes from 0.02-0.03 ms to 18-24 ms. The block is still accepted faster than on the base (0.04-0.05 s against 0.14-0.20 s).

    I also compared the two builds over RPC and P2P in one functional test (edge cases, test vectors, blocks at the weight limit, PSBTs), and on 400,000 mutated transactions fed to each deserializer. I checked decoding, wtxids, sighashes, weight and sigops against btclib, a parser I maintain. Apart from error messages, the only differences were those the description lists. I can share the code, corpus generator included, as a gist.

  26. purpleKarrot commented at 5:13 PM on October 29, 2026: contributor

    May I dare to NACK this? I understand that keeping the witness data in serialized format considerably improves performance, but as I wrote in #35569 (comment), there sure are hundreds of possibilities for data layouts that may be even more optimized for fast data access.

    Instead pushing 17 commits touching over 1000 lines in 76 files, just to establish an implementation that is proven better but not proven best, should we maybe concentrate on the task that would allow us to make such a change localized in a single place? This would give us the possibility to easily experiment with different data layouts and lead to an even faster implementation?

  27. DrahtBot added the label Needs rebase on Oct 30, 2026
  28. alexanderwiederin commented at 11:24 AM on November 2, 2026: contributor

    Would it make sense to split this into (1) the CScriptWitness interface and caller conversion (e41dd47 through 9e22357), (2) the serialised representation, and (3) the deserialisation checks?

    Part 1 is a pure refactor that localises the representation and makes parts 2 and 3 smaller to review. The P2P behaviour changes in part 3 might also benefit from separate discussion.

  29. bench: add block deserialization benchmarks for synthetic blocks
    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.
    ceb38d05cc
  30. script: give CScriptWitness an interface that hides its representation
    Add element access through spans (forward iteration, front(), back(), and
    indexing), conversion to and construction from a vector of elements,
    serialization, and memory usage accounting, so that users no longer need to
    access the stack vector directly. This prepares for a future commit which
    will replace the representation with a more compact & efficient one.
    
    The stack vector itself stays public until the next commits have converted
    its users.
    0354397577
  31. test: check CScriptWitness against the vector of vectors it represents
    Add a unit test and a fuzz test that compare CScriptWitness's interface
    (accessors, construction, and serialization) with the
    std::vector<std::vector<unsigned char>> it represents. The unit test
    focuses on element counts and sizes around CompactSize encoding
    boundaries.
    95c73e5d25
  32. scripted-diff: use CScriptWitness's interface instead of its stack
    Convert the uses of CScriptWitness::stack for which the new interface
    is a simple substitution. The remaining ones are converted manually in
    the next commits.
    
    -BEGIN VERIFY SCRIPT-
    FILES=$(git grep -l -E '\.stack\b|(scriptWitness|final_script_witness)\.SetNull\(\)' -- src ':!src/script/miniscript.*' ':!src/script/script.h')
    
    # Element count, emptiness, and last element: the witness has size(), empty() and back() itself. Lines that need the
    # stack itself (to compute the size of its serialization without the element count, to pass the last element where a
    # vector is expected, or to index all elements in a loop) are left for the manual changes.
    sed -i -E -e '/GetSizeOfCompactSize|TAPROOT_LEAF_TAPSCRIPT|i < txin\.scriptWitness/b' \
        -e 's/\.stack\.(size|empty|back)\(\)/.\1()/g' $FILES
    
    # Reading an element by index: the witness has operator[] itself. Writes to elements, and loops indexing all elements
    # (which can be quadratic with indexing that is not constant-time), are left for the manual changes.
    sed -i -E -e '/MAX_STANDARD_P2WSH_STACK_ITEM_SIZE|HexStr\(txin\.scriptWitness|\.stack\[[^]]*\]( =|\.resize)|^\s*\+\+/b' \
        -e 's/\.stack\[/[/g' $FILES
    
    # Const references to the stack: refer to the witness itself, which provides the same read-only accessors.
    sed -i -E 's/^(\s*const auto& \w+( = |\{).*)\.stack(\}?;)$/\1\3/' $FILES
    
    # Comparisons of two stacks: compare the witnesses, which are equal exactly when their stacks are.
    sed -i -E '/\.stack [!=]= /s/\.stack\b//g' $FILES
    
    # Serialization of the stack, and its size: serialize the witness itself, which has the same serialization.
    sed -i -E -e 's/ (>>|<<) ([][A-Za-z0-9_.]+)\.stack( <<|;)/ \1 \2\3/' \
        -e 's/(SerializeToVector|UnserializeFromVector)\(s, (\w+)\.stack\)/\1(s, \2)/' \
        -e 's/::GetSerializeSize\(([][A-Za-z0-9_.]+)\.stack\)/::GetSerializeSize(\1)/' $FILES
    
    # Range-for loops over the stack: iterate over the witness. Its elements are spans, returned by value, so they are not
    # bound by reference.
    sed -i -E 's/for \(const auto& (\w+) : ([][A-Za-z0-9_.]+)\.stack\)/for (const auto \1 : \2)/' $FILES
    
    # Clearing the stack (SetNull(), clear() or resize(0)): assign an empty witness. A clear() followed by pushing elements
    # in a loop is left for the manual changes.
    sed -i -E -e '/txin\.scriptWitness\.stack\.clear/b' \
        -e 's/(scriptWitness|final_script_witness)\.SetNull\(\)/\1 = {}/' \
        -e 's/(scriptWitness)\.stack\.(clear\(\)|resize\(0\));$/\1 = {};/' $FILES
    
    # Assigning a vector of elements to the stack: assign a witness constructed from it (moving from the vector is
    # pointless, as the witness is constructed from a const reference).
    sed -i -E 's/(\w+)\.stack = (std::move\((\w+)\)|(.*));$/\1 = CScriptWitness{\3\4};/' $FILES
    
    # Pushing a single element onto an empty witness (in these benchmarks and tests): assign a witness constructed from
    # that element. The one place that pushes onto a non-empty witness (to make a different witness) is left for the
    # manual changes, as are pushes in loops.
    sed -i -E '/ tx\.vin\[0\]\.scriptWitness\.stack\.push_back\(\{5\}\)|Consume/!s/(\w+)\.stack\.push_back\((.*)\);$/\1 = CScriptWitness{{\2}};/' \
        src/bench/block_assemble.cpp src/bench/blockencodings.cpp src/bench/mempool_eviction.cpp src/bench/mempool_stress.cpp src/bench/rpc_mempool.cpp \
        src/test/fuzz/connect_block.cpp src/test/fuzz/txdownloadman.cpp src/test/orphanage_tests.cpp src/test/txdownload_tests.cpp src/test/validation_block_tests.cpp
    
    # IsNull(): use empty(), which the witness provides along with size() and its other container-like accessors.
    sed -i -E -e 's/(scriptWitness|final_script_witness)\.IsNull\(\)/\1.empty()/g' -e 's/witness->IsNull\(\)/witness->empty()/g' \
        $(git grep -l -E '(scriptWitness|final_script_witness)\.IsNull\(\)|witness->IsNull\(\)' -- src)
    -END VERIFY SCRIPT-
    e78a86fa58
  33. script: let ExecuteWitnessScript take its initial stack by value
    This lets callers move the stack into it, rather than having it be
    copied from a span. This will be used in a future commit.
    b0c0cbd0f4
  34. refactor: use CScriptWitness's interface where that needs more than a rename
    Convert the remaining non-test uses of CScriptWitness::stack, which need
    more than a substitution. The script interpreter now converts the
    witness stack to a vector of vectors once, and moves the remaining
    elements into the execution stack, rather than copying them.
    11b5566f68
  35. test, bench, fuzz: build witness stacks before constructing a CScriptWitness
    Convert the remaining uses of CScriptWitness::stack in tests, benchmarks,
    and fuzz tests, by constructing witnesses from a separately-built vector
    of elements, rather than modifying the stack in place.
    b791e22fa4
  36. streams: add SpanReader::Remaining()
    This returns the data that has not been read yet, as a span referring
    to the underlying data. It will be used in the next commit to find the
    elements of a witness stack within its serialization.
    c4fb996171
  37. script: store witness stacks as their serialization
    Replace CScriptWitness's vector of vectors with a single allocation,
    containing the size of the stack's serialization (4 bytes, little
    endian), followed by that serialization. An empty stack uses no
    allocation at all.
    
    This means a witness stack no longer needs one allocation per non-empty
    element plus one for the outer vector, and no longer has a 24-byte
    overhead per element. A block whose witnesses consist of millions of
    tiny elements thus no longer costs tens of bytes of memory and an
    allocation per byte. It also shrinks CScriptWitness from 24 to 8 bytes,
    and thus CTxIn from 112 to 96 bytes. The downside is that indexing
    becomes O(n) in the distance from the bottom of the stack.
    
    This is the simplest implementation of this representation:
    deserialization still goes through a vector of vectors, and elements
    are found by parsing the serialization with SpanReader and
    ReadCompactSize. Future commits will make both faster.
    a1cea0d7e0
  38. script: deserialize witness stacks directly into their serialization
    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.
    5c175e82b3
  39. script: decode the CompactSizes in witness stacks inline
    Add DecodeCompactSize 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.
    b28174d41c
  40. script: store the offset of a witness stack's last element
    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.
    c190556259
  41. primitives: reject txs with more inputs or outputs than fit in a block
    When deserializing a transaction, read the input and output counts
    first, and fail before reading the inputs or outputs if more of them
    are claimed than can fit in a block, given their minimum size (41 bytes
    for an input, 9 for an output). Such a transaction can never be valid.
    
    This allows us to allocate the vin and vout vectors immediately, rather
    than sequentially in batches of 5 MB as the std::vector deserializer
    does, because that memory becomes bounded: to 2.3 MB for 24390 inputs,
    and 5.3 MB for 111111 outputs. It is a preparation for further changes
    that rely on this structuring of conditionals.
    
    This affects all places where transactions are deserialized. Through
    RPC, such transactions can no longer be decoded. From P2P, a transaction
    or block containing one is ignored like other malformed messages, rather
    than rejected by validation.
    2d869d8186
  42. sipa force-pushed on Nov 5, 2026
  43. DrahtBot removed the label Needs rebase on Nov 5, 2026
  44. p2p: reject transactions without inputs or outputs when deserializing
    Add a reject_empty flag to TransactionSerParams, which makes
    deserialization fail as soon as a transaction is found to have no
    inputs or no outputs. Such transactions are never valid, but are
    currently fully deserialized (along with the rest of the message) before
    validation rejects them.
    
    This reduces the memory a peer can make us allocate by sending a block.
    A block full of 10-byte empty transactions was the previous worst case;
    with this change, the worst case becomes 1-input 1-output transactions
    with a significantly lower per-WU memory usage.
    
    The flag is enabled (as TX_WITH_WITNESS_P2P) only where transactions are
    received from P2P peers: tx and block messages, and the transactions in
    cmpctblock and blocktxn messages. Like other malformed messages, these
    are now ignored, rather than, for a block, causing the peer to be
    disconnected, or, for a transaction, being added to the reject filters.
    The functional tests are updated accordingly.
    b2ee9d29f2
  45. policy: iterate over witness stacks directly in IsWitnessStandard
    Instead of converting a witness stack to a vector of spans for the P2WSH
    and Taproot checks, use its size() and back() (which are constant-time)
    and iterate over its elements directly. This avoids an allocation for
    every witness spend that is checked.
    60b2da3cc8
  46. refactor: use the stream's parameters for compact block transactions
    BlockTransactions and PrefilledTransaction (de)serialized their
    transactions with TX_WITH_WITNESS_P2P, overriding any parameters of the
    stream. Use the stream's parameters instead, like CBlock does, and pass
    TX_WITH_WITNESS where they are serialized and TX_WITH_WITNESS_P2P where
    they are deserialized. This does not change behavior (serialization only
    depends on allow_witness), but makes it possible to deserialize them
    with other parameters.
    5ed576d99a
  47. p2p: limit the weight of transactions and blocks while deserializing
    Add an optional weight budget to TransactionSerParams. When it is set,
    the budget is decremented while transactions are being deserialized
    (charging the minimum weight of inputs and outputs before allocating
    memory for them), causing failure as soon as the budget is exceeded.
    
    Use this for tx, block, cmpctblock and blocktxn messages, with a budget
    of MAX_BLOCK_WEIGHT minus the header: the transactions in a block,
    cmpctblock or blocktxn message are part of one block (for blocktxn, this
    does not account for those of the block that are already known), and a
    transaction that does not fit in a block cannot be valid.
    
    The P2P message size limit allows blocks of up to 4 MB, which is up to
    16M weight, all of which is currently deserialized before validation
    rejects it (unless a transaction has more inputs or outputs than fit in
    a block). With this change, the weight deserialized from a message is
    at most MAX_BLOCK_WEIGHT minus the header.
    
    Messages exceeding the budget are ignored, like other malformed
    messages, rather than causing the peer to be disconnected for sending an
    invalid block.
    c655a696d8
  48. sipa force-pushed on Nov 5, 2026
  49. DrahtBot added the label CI failed on Nov 5, 2026
  50. sipa commented at 10:44 AM on November 5, 2026: member

    @purpleKarrot

    May I dare to NACK this? I understand that keeping the witness data in serialized format considerably improves performance, but as I wrote in #35569 (comment), there sure are hundreds of possibilities for data layouts that may be even more optimized for fast data access.

    I consider this PR a bugfix for a significant problem. It doesn't rise to the level of vulnerability that needs immediate fixing and emergency releases, but I do think it's an issue that should be fixed and ideally soon. My goal is not at all to find the optimal solution; the goal is simply to get a sufficient and acceptable solution in, and I think this is one. Providing the ability to experiment with even better representations is what I'd consider a secondary goal here.

    That said, I don't think it's far off from what an optimal solution can achieve. In terms of memory usage, it drops from ~28 bytes/WU to 1.6 bytes/WU. Clearly nothing can go below 1 byte/WU. In terms of deserialization performance it's harder to give a lower bound, but I think this brings values to an acceptable level regardless.

    Instead pushing 17 commits touching over 1000 lines in 76 files, just to establish an implementation that is proven better but not proven best, should we maybe concentrate on the task that would allow us to make such a change localized in a single place? This would give us the possibility to easily experiment with different data layouts and lead to an even faster implementation?

    I think that is exactly what (the first half of) this PR is: the introduction of an abstraction layer for CScriptWitness, sufficient to hide the representation aspects. The later commits then introduce one particular representation that is decent, plus some optimizations to it, and to the P2P deserialization code to improve further upon what become the new worst-case scenarios. Nothing prevents experimenting with better layouts as follow-ups, and the changes here make that easy; this is demonstrated by how narrow the changes in a1cea0d7e024e838be8ea295688693116ec357a1 are.

    While I'm sure there are code-level conflicts with with #35569, I don't think those are of a conceptual nature. This PR is about an abstraction at the CScriptWitness level, while yours is about abstraction at the CTransaction level as I understand it. We can do either, or both, and I'm happy to rebase on yours if that were the consensus for going forward (though I personally think the changes here are more urgent). If we do both, in whatever order, it opens up the ability for a CTransaction-wide shared allocation approach (packing everything in 1 or a small number of per-transaction allocations + index structures). I've experimented with those too, getting down to around 1.1 bytes/WU memory usage, but I don't think those benefits are worth gating behind the more involved refactorings needed as we can get 90% of the benefit with a more localized change.


    @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.

  51. ismaelsadeeq commented at 11:03 AM on November 5, 2026: member

    Concept ACK

  52. DrahtBot removed the label CI failed on Nov 5, 2026
  53. Yudis-bit commented at 12:44 PM on November 5, 2026: none

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

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

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

  54. DrahtBot requested review from ismaelsadeeq on Nov 5, 2026
  55. purpleKarrot commented at 7:57 AM on November 6, 2026: 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.

  56. sedited referenced this in commit e71cebc016 on Nov 6, 2026
  57. fametrano commented at 6:14 PM on November 7, 2026: none

    On c655a696d8, 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, c655a696d8 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 0e38ad26af. witness_diff.py, run with the fix against c655a696d8, 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?

  58. sipa commented at 4:27 PM on November 9, 2026: member

    @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.

  59. in src/script/script.cpp:321 in a1cea0d7e0
     322 | +{
     323 | +    if (data.empty()) {
     324 | +        m_data.reset();
     325 | +        return;
     326 | +    }
     327 | +    std::ranges::copy(data, Allocate(data.size()).begin());
    


    instagibbs commented at 7:22 PM on November 9, 2026:

    a1cea0d7e024e838be8ea295688693116ec357a1

    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/bug-116754-4@http.gcc.gnu.org%2Fbugzilla%2F/T/#u


    sipa commented at 8:51 PM on November 9, 2026:

    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.

  60. DrahtBot requested review from instagibbs on Nov 9, 2026
  61. purpleKarrot commented at 7:43 AM on November 10, 2026: 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.

  62. in src/test/private_broadcast_tests.cpp:34 in b791e22fa4 outdated
      30 | @@ -31,7 +31,7 @@ static CTransactionRef MakeDummyTx(uint32_t id, size_t num_witness)
      31 |      mtx.vin[0].nSequence = id;
      32 |      if (num_witness > 0) {
      33 |          mtx.vin[0].scriptWitness = CScriptWitness{};
      34 | -        mtx.vin[0].scriptWitness.stack.resize(num_witness);
      35 | +        mtx.vin[0].scriptWitness = CScriptWitness{std::vector<std::vector<unsigned char>>(num_witness)};
    


    ajtowns commented at 5:01 PM on November 10, 2026:

    nit: redundant double assignment

  63. in src/streams.h:104 in c4fb996171 outdated
      99 | @@ -100,6 +100,8 @@ class SpanReader
     100 |  
     101 |      size_t size() const { return m_data.size(); }
     102 |      bool empty() const { return m_data.empty(); }
     103 | +    //! The data that remains to be read (referring to the underlying data, not a copy of it).
     104 | +    std::span<const std::byte> Remaining() const { return m_data; }
    


    ajtowns commented at 5:07 PM on November 10, 2026:

    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?


    l0rinc commented at 10:01 AM on November 12, 2026:

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

  64. in src/script/script.h:588 in a1cea0d7e0 outdated
     586 | + *  The stack is stored as its serialization (the CompactSize-encoded number of elements, followed
     587 | + *  by each element as a CompactSize-prefixed byte string), in a single allocation. Access by index
     588 | + *  is O(n) in the position from the bottom of the stack.
     589 |   */
     590 | -struct CScriptWitness
     591 | +class CScriptWitness
    


    ajtowns commented at 5:34 PM on November 10, 2026:

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

  65. in src/script/script.h:661 in a1cea0d7e0 outdated
     659 | +        }
     660 |          Iterator operator++(int) noexcept { auto ret{*this}; ++*this; return ret; }
     661 | -        friend bool operator==(const Iterator&, const Iterator&) noexcept = default;
     662 | +        /** Iterators over the same stack are equal if the same number of bytes of its serialization
     663 | +         *  remain. */
     664 | +        friend bool operator==(const Iterator& a, const Iterator& b) noexcept { return a.m_reader.size() == b.m_reader.size(); }
    


    ajtowns commented at 6:23 PM on November 10, 2026:

    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.

  66. fanquake added this to the milestone 33.0 on Nov 10, 2026
  67. fanquake commented at 8:59 PM on November 10, 2026: 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.

  68. darosior commented at 9:01 PM on November 10, 2026: 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.

  69. in src/net_processing.cpp:4812 in c655a696d8
    4805 | @@ -4800,7 +4806,10 @@ void PeerManagerImpl::ProcessMessage(Peer& peer, CNode& pfrom, const std::string
    4806 |          }
    4807 |  
    4808 |          CBlockHeaderAndShortTxIDs cmpctblock;
    4809 | -        vRecv >> TX_WITH_WITNESS_P2P(cmpctblock);
    4810 | +        // The prefilled transactions are part of the block, so stop deserializing as soon as they exceed the weight
    4811 | +        // that the transactions of a valid block can have.
    4812 | +        uint64_t weight_left{MAX_BLOCK_TXS_WEIGHT};
    4813 | +        vRecv >> TxWithWitnessP2P(weight_left)(cmpctblock);
    


    ajtowns commented at 11:35 PM on November 10, 2026:

    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.


    ajtowns commented at 5:10 PM on November 11, 2026:

    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);
    
  70. ajtowns commented at 11:45 PM on November 10, 2026: contributor

    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.

  71. in src/script/script.h:715 in c655a696d8
     717 | +    /** The elements, bottom to top, as vectors. For code that needs to modify or take ownership of them (e.g. to
     718 | +     *  execute a script with them as its initial stack). */
     719 | +    std::vector<std::vector<unsigned char>> ToVectors() const;
     720 | +    /** Spans of the elements, bottom to top, which are valid as long as this witness is. For code that accesses many
     721 | +     *  elements by index, as indexing a witness need not be constant-time. */
     722 | +    std::vector<std::span<const unsigned char>> ToSpans() const LIFETIMEBOUND;
    


    l0rinc commented at 9:16 AM on November 12, 2026:

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

    After this change, we could clean up the leftovers.

  72. in src/bench/block_deserialize.cpp:100 in c655a696d8
      95 | +        VectorWriter s{data, 0};
      96 | +        // Header.
      97 | +        s << CBlockHeader{};
      98 | +        // Transactions.
      99 | +        WriteCompactSize(s, shape.num_txn);
     100 | +        for (size_t i = 0; i < shape.num_txn; ++i) s.write(MakeByteSpan(tx));
    


    l0rinc commented at 9:16 AM on November 12, 2026:

    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.

    <details> <summary>Reuse benchmark serializers</summary>

    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.
         {
    

    </details>

  73. in src/test/transaction_tests.cpp:1516 in c655a696d8
    1512 | +    BOOST_CHECK_EXCEPTION(SpanReader{block_ser} >> TX_WITH_WITNESS_P2P(block_deser), std::ios_base::failure, HasReason("Transaction without inputs"));
    1513 | +}
    1514 | +
    1515 | +BOOST_AUTO_TEST_CASE(weight_limited_deserialization)
    1516 | +{
    1517 | +    const auto ser{[](const auto& obj) {
    


    l0rinc commented at 9:16 AM on November 12, 2026:

    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.

    <details> <summary>Reuse DataStream in serialization tests</summary>

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

    </details>

  74. in src/test/fuzz/util.cpp:61 in c655a696d8
      57 | @@ -58,7 +58,7 @@ CMutableTransaction ConsumeTransaction(FuzzedDataProvider& fuzzed_data_provider,
      58 |          const auto script_sig = p2wsh_op_true ? CScript{} : ConsumeScript(fuzzed_data_provider);
      59 |          CScriptWitness script_wit;
      60 |          if (p2wsh_op_true) {
      61 | -            script_wit.stack = std::vector<std::vector<uint8_t>>{WITNESS_STACK_ELEM_OP_TRUE};
      62 | +            script_wit = CScriptWitness{std::vector<std::vector<uint8_t>>{WITNESS_STACK_ELEM_OP_TRUE}};
    


    l0rinc commented at 9:16 AM on November 12, 2026:

    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.

    <details> <summary>Trim witness migration residue</summary>

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

    </details>

  75. in src/test/serialize_tests.cpp:194 in c655a696d8
     189 | +}
     190 | +
     191 | +BOOST_AUTO_TEST_CASE(decode_compactsize)
     192 | +{
     193 | +    // DecodeCompactSize decodes what WriteCompactSize encodes, advancing past each value.
     194 | +    static constexpr uint64_t VALUES[]{0, 252, 253, 0xffff, 0x10000, 0xffffffff, 0x100000000, std::numeric_limits<uint64_t>::max()};
    


    l0rinc commented at 9:17 AM on November 12, 2026:

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

    The two tests can share COMPACT_SIZE_BOUNDARIES.

    <details> <summary>Share CompactSize boundary cases</summary>

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

    </details>

  76. in src/test/transaction_tests.cpp:1447 in c655a696d8
    1443 | +        if (outputs) s << std::vector<CTxIn>(1);
    1444 | +        WriteCompactSize(s, count);
    1445 | +        CMutableTransaction tx;
    1446 | +        BOOST_CHECK_EXCEPTION(s >> TX_WITH_WITNESS(tx), std::ios_base::failure, HasReason(reason));
    1447 | +    }};
    1448 | +    for (const bool extended : {false, true}) {
    


    l0rinc commented at 9:17 AM on November 12, 2026:

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

    I'd check the minimum input/output weights against their serialized sizes here, so we catch the bounds drifting if the encoding changes.

    <details> <summary>Check minimum input and output weights</summary>

    diff --git a/src/test/transaction_tests.cpp b/src/test/transaction_tests.cpp
    index d9fbf8d7ad..3141f23914 100644
    --- a/src/test/transaction_tests.cpp
    +++ b/src/test/transaction_tests.cpp
    @@ -1444,6 +1444,9 @@ BOOST_AUTO_TEST_CASE(too_many_inputs_or_outputs)
             CMutableTransaction tx;
             BOOST_CHECK_EXCEPTION(s >> TX_WITH_WITNESS(tx), std::ios_base::failure, HasReason(reason));
         }};
    +    // The limits are based on the weight of an input and an output that are as small as possible.
    +    BOOST_CHECK_EQUAL(MIN_WEIGHT_PER_TXIN, WITNESS_SCALE_FACTOR * ::GetSerializeSize(CTxIn{}));
    +    BOOST_CHECK_EQUAL(MIN_WEIGHT_PER_TXOUT, WITNESS_SCALE_FACTOR * ::GetSerializeSize(CTxOut{}));
         for (const bool extended : {false, true}) {
             check(extended, /*outputs=*/false, MAX_BLOCK_WEIGHT / MIN_WEIGHT_PER_TXIN, "end of data");
             check(extended, /*outputs=*/false, MAX_BLOCK_WEIGHT / MIN_WEIGHT_PER_TXIN + 1, "Too many transaction inputs");
    

    </details>

  77. in src/test/script_tests.cpp:1784 in c655a696d8
    1779 | +            // Moving leaves the source empty.
    1780 | +            CScriptWitness moved{std::move(deser)};
    1781 | +            BOOST_CHECK(moved == witness);
    1782 | +            BOOST_CHECK(deser.empty() && deser.size() == 0 && deser.begin() == deser.end()); // NOLINT(bugprone-use-after-move)
    1783 | +
    1784 | +            CScriptWitness copy{witness};
    


    l0rinc commented at 9:17 AM on November 12, 2026:

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

    For consistency, we could cover copy and move assignment as well.

    <details> <summary>Cover copy and move assignment</summary>

    diff --git a/src/test/script_tests.cpp b/src/test/script_tests.cpp
    index 10a6ce0ed2..3a1ed2df53 100644
    --- a/src/test/script_tests.cpp
    +++ b/src/test/script_tests.cpp
    @@ -1778,9 +1778,18 @@ BOOST_AUTO_TEST_CASE(script_witness_representation)
                 BOOST_CHECK(deser.empty() && deser.size() == 0 && deser.begin() == deser.end()); // NOLINT(bugprone-use-after-move)
     
                 CScriptWitness copy{witness};
    +            CScriptWitness assigned{{{0xff}}};
    +            assigned = copy;
                 copy = {};
                 BOOST_CHECK(copy.empty());
                 BOOST_CHECK(copy.begin() == copy.end());
    +            BOOST_CHECK(assigned == witness);
    +
    +            CScriptWitness move_assigned{{{0xff}}};
    +            move_assigned = std::move(assigned);
    +            BOOST_CHECK(move_assigned == witness);
    +            BOOST_CHECK(assigned.empty() && assigned.begin() == assigned.end()); // NOLINT(bugprone-use-after-move)
    +            if (!witness.empty()) BOOST_CHECK(std::ranges::equal(move_assigned.back(), witness.back()));
             }
         }
     }
    

    </details>

  78. in src/test/blockencodings_tests.cpp:494 in c655a696d8
     489 | +                BOOST_CHECK_EXCEPTION(stream >> TxWithWitnessP2P(weight_left)(deser), std::ios_base::failure, HasReason{"Weight limit exceeded"});
     490 | +            }
     491 | +        }
     492 | +    }};
     493 | +    check(short_ids, CBlockHeaderAndShortTxIDs{});
     494 | +    check(block_txn, BlockTransactions{});
    


    l0rinc commented at 9:17 AM on November 12, 2026:

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

    Worth covering empty inputs and outputs through compact blocks and blocktxn responses too, since these decoders now inherit the stream parameters. The ordinary-parameter round trip can check that compatibility is preserved.

    <details> <summary>Extend the coverage</summary>

    diff --git a/src/test/blockencodings_tests.cpp b/src/test/blockencodings_tests.cpp
    index a951d2eba1..e07805e255 100644
    --- a/src/test/blockencodings_tests.cpp
    +++ b/src/test/blockencodings_tests.cpp
    @@ -494,4 +494,30 @@ BOOST_AUTO_TEST_CASE(WeightLimitedDeserializationTest)
         check(block_txn, BlockTransactions{});
     }
     
    +BOOST_AUTO_TEST_CASE(EmptyTransactionDeserializationTest)
    +{
    +    auto rand_ctx(FastRandomContext(uint256{42}));
    +    CBlock block{BuildBlockTestCase(rand_ctx)};
    +    for (const bool with_input : {false, true}) {
    +        CMutableTransaction empty_tx;
    +        if (with_input) empty_tx.vin.resize(1);
    +        // A compact block prefills the first transaction of its block.
    +        block.vtx[0] = MakeTransactionRef(empty_tx);
    +        const CBlockHeaderAndShortTxIDs short_ids{block, rand_ctx.rand64()};
    +        BlockTransactions block_txn;
    +        block_txn.blockhash = block.GetHash();
    +        block_txn.txn = block.vtx;
    +
    +        const auto check{[&](const auto& obj, auto deser) {
    +            const auto data{DataStream{} << TX_WITH_WITNESS(obj)};
    +            DataStream{data} >> TX_WITH_WITNESS(deser);
    +            BOOST_CHECK_EQUAL((DataStream{} << TX_WITH_WITNESS(deser)).str(), data.str());
    +            const auto reason = with_input ? "Transaction without outputs" : "Transaction without inputs";
    +            BOOST_CHECK_EXCEPTION(DataStream{data} >> TX_WITH_WITNESS_P2P(deser), std::ios_base::failure, HasReason{reason});
    +        }};
    +        check(short_ids, CBlockHeaderAndShortTxIDs{});
    +        check(block_txn, BlockTransactions{});
    +    }
    +}
    +
     BOOST_AUTO_TEST_SUITE_END()
    

    </details>

  79. in src/script/script.h:743 in c655a696d8
     745 | +            return;
     746 | +        }
     747 | +        // Build the serialization directly. Like deserializing a vector of vectors, this rejects
     748 | +        // non-canonical CompactSizes and sizes above MAX_SIZE (through ReadCompactSize), and reads
     749 | +        // large elements in chunks (so that a bogus size does not cause a large allocation).
     750 | +        std::vector<std::byte> data;
    


    l0rinc commented at 9:17 AM on November 12, 2026:

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

    A small reserve(256) here would avoid repeated buffer growth for common witness stacks. In local Clang Release runs, DeserializeBlockP2WPKH went from 3.462 to 3.072 ms and DeserializeBlockManyInputs from 2.743 to 2.426 ms (minima from eight rotating rounds). Those runs used the original 72/72-byte P2WPKH fixture.

  80. in src/script/script.cpp:318 in c655a696d8
     318 | +    // The last element (with its size prefix) ends the serialization.
     319 | +    const auto& last = stack.back();
     320 | +    SpanWriter{Allocate(size, size - GetSizeOfCompactSize(last.size()) - last.size()), stack};
     321 | +}
     322 | +
     323 | +void CScriptWitness::Assign(std::span<const std::byte> data, size_t last_offset)
    


    l0rinc commented at 9:17 AM on November 12, 2026:

    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.

  81. in src/bench/block_deserialize.cpp:124 in c655a696d8
     119 | +static void DeserializeBlockP2WPKH(benchmark::Bench& bench)
     120 | +{
     121 | +    DeserializeBlock(bench, {.num_txn = 4385,
     122 | +                             .num_txin = 2,
     123 | +                             .num_txout = 2, .size_spk = 22,
     124 | +                             .num_wit_items = 2, .size_wit_item = 72});
    


    l0rinc commented at 9:18 AM on November 12, 2026:

    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.

    <details> <summary>Use P2WPKH witness item sizes</summary>

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

    </details>

  82. in src/bench/block_deserialize.cpp:71 in c655a696d8
      66 | +        s << std::vector<unsigned char>(shape.size_spk, 0x52);
      67 | +    }
      68 | +    // Witnesses.
      69 | +    if (have_witness) {
      70 | +        for (size_t i = 0; i < shape.num_txin; ++i) {
      71 | +            // Number of witness items.
    


    l0rinc commented at 9:18 AM on November 12, 2026:

    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.

    <details> <summary>Trim redundant benchmark comments</summary>

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

    </details>

  83. in src/script/script.cpp:353 in c655a696d8
     353 | +}
     354 | +
     355 | +std::span<const unsigned char> CScriptWitness::operator[](size_t index) const noexcept
     356 | +{
     357 | +    const auto count = size();
     358 | +    Assume(index < count);
    


    l0rinc commented at 9:18 AM on November 12, 2026:

    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.

  84. l0rinc changes_requested
  85. l0rinc commented at 12:27 PM on November 12, 2026: contributor

    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.
  86. sipa commented at 7:03 PM on November 16, 2026: member

    Going to split this up.

  87. sipa closed this on Nov 16, 2026

  88. fanquake removed this from the milestone 33.0 on Nov 16, 2026

github-metadata-mirror

This is a metadata mirror of the GitHub repository bitcoin/bitcoin. This site is not affiliated with GitHub. Content is generated from a GitHub metadata backup.
generated: 2026-11-27 03:51 UTC

This site is hosted by @0xB10C
More mirrored repositories can be found on mirror.b10c.me