net: serve `MSG_BLOCK` by stripping witnesses in place #36548

pull l0rinc wants to merge 4 commits into bitcoin:master from l0rinc:l0rinc/msg-block-serving changing 11 files +401 −7
  1. l0rinc commented at 1:08 AM on October 16, 2026: contributor

    Problem: To send a MSG_BLOCK reply from disk, a node currently decodes the block and serializes it again without witnesses. For MSG_WITNESS_BLOCK, it already sends the stored bytes directly. Serving MSG_BLOCK efficiently also matters for the proposed witnessless initial block download. #36476

    Fix: For MSG_BLOCK replies from disk on non-Signet chains, read the block into an owned byte buffer and check the header’s proof of work and expected hash. Walk the serialized transactions directly and strip their witnesses in place. Signet still uses ReadBlock to verify the Signet solution. Header checks now run before transaction parsing, so if both the header and transaction data are corrupt, the node may log a different error.

    Performance:

    Block Before After Speedup
    block413567 3.204 ms 0.369 ms 8.7×
    Same block with synthetic witnesses 8.944 ms 1.026 ms 8.7×

    The synthetic fixture adds a 512-byte witness item and an empty item to every input.

    Related work: This extends the path that sends witness blocks directly from disk. #13151 Earlier work identified unnecessary transaction hashing when serving historical blocks. #13011 discussion · #13098 The implementation also builds on bulk block reads. #31551

  2. DrahtBot added the label P2P on Oct 16, 2026
  3. DrahtBot commented at 1:08 AM on October 16, 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 optout21
    Stale ACK fametrano

    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:

    • #36946 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36946.svg"></sub> (scripted-diff: [test] Add util/check.h includes for assertions by maflcko)
    • #36621 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36621.svg"></sub> (node: batch block file pruning in a single pass over block index by mutatrum)
    • #36000 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36000.svg"></sub> (validation: prefetch blocks while connecting by l0rinc)
    • #35731 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/35731.svg"></sub> (Indexes: Harden the flush-error notification invariant by arejula27)
    • #35003 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/35003.svg"></sub> (validation: improve block data I/O error handling in P2P paths by furszy)
    • #32554 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/32554.svg"></sub> (bench: replace embedded raw block with configurable block generator by l0rinc)

    If you consider this pull request important, please also help to review the conflicting pull requests. Ideally, start with the one that should be merged first.

    <!--5faf32d7da4f0f540f40219e4f7537a3-->

  4. DrahtBot added the label CI failed on Oct 16, 2026
  5. DrahtBot commented at 2:21 AM on October 16, 2026: contributor

    <!--85328a0da195eb286784d51f73fa0af9-->

    🚧 At least one of the CI tasks failed. <sub>Task iwyu: https://github.com/bitcoin/bitcoin/actions/runs/38833479928/job/116757258223</sub> <sub>LLM reason (✨ experimental): CI failed because IWYU modified includes in src/bench/readwriteblock.cpp, and the formatting check detected uncommitted changes.</sub>

    <details><summary>Hints</summary>

    Try to run the tests locally, according to the documentation. However, a CI failure may still happen due to a number of reasons, for example:

    • Possibly due to a silent merge conflict (the changes in this pull request being incompatible with the current code in the target branch). If so, make sure to rebase on the latest commit of the target branch.

    • A sanitizer issue, which can only be found by compiling with the sanitizer and running the affected test.

    • An intermittent issue.

    Leave a comment here, if you need help tracking down a confusing failure.

    </details>

  6. l0rinc force-pushed on Oct 16, 2026
  7. l0rinc closed this on Oct 18, 2026

  8. l0rinc reopened this on Oct 18, 2026

  9. DrahtBot removed the label CI failed on Oct 18, 2026
  10. pmazzocchi referenced this in commit ca94fe44d6 on Oct 18, 2026
  11. fametrano commented at 11:41 AM on October 25, 2026: none

    tACK 0b01ce05e162ee61fb0e3c0d8413e0e1af4c1976

    I checked that the new MSG_BLOCK reply is byte for byte the old one. On 214 blocks, the head's ReadBlockWithoutWitness matches its ReadBlock plus TX_NO_WITNESS, that old path matches the base's, and btclib, a library I maintain, agrees. The blocks are mainnet 481824, 709632, 774628, 920000 and the bench's 413567, plus 209 regtest blocks with segwit v0 and v1 spends, 1,000 witness items, empty stacks and items, a 3,990,000-byte annex, 300 inputs, 316 outputs, 260 transactions, or no witness. Over P2P, a head node and a base node give the same MSG_BLOCK and MSG_WITNESS_BLOCK payloads for all 209: 208 from disk, and the two successive tips from the recent-block cache.

    Each of seven mutants of StripBlockWitness and ReadBlockWithoutWitness fails blockmanager_tests. They range from keeping the marker or the witnesses to skipping the proof-of-work or hash check. The new p2p_getdata case also passes against a base node, so it guards the payload format rather than the new path.

    Building the reply got 7.2x to 9.0x faster than on the base for those five mainnet blocks and the two largest regtest blocks (median of three runs, Release, Apple M5). Peak heap fell from 2.9 to 2.0 MB for 481824 and from 7.9 to 4.0 MB for 774628. I measured with a Boost test that writes each block with WriteBlock and reads it back both ways, and a functional test running a head and a base node; I can share both as a gist.

  12. DrahtBot added the label Needs rebase on Oct 28, 2026
  13. l0rinc force-pushed on Oct 31, 2026
  14. l0rinc force-pushed on Oct 31, 2026
  15. DrahtBot added the label CI failed on Oct 31, 2026
  16. DrahtBot commented at 3:25 PM on October 31, 2026: contributor

    <!--85328a0da195eb286784d51f73fa0af9-->

    🚧 At least one of the CI tasks failed. <sub>Task iwyu: https://github.com/bitcoin/bitcoin/actions/runs/41212933561/job/124571513411</sub> <sub>LLM reason (✨ experimental): CI failed because IWYU modified src/bench/readwriteblock.cpp to add missing includes, and the subsequent diff check detected uncommitted changes.</sub>

    <details><summary>Hints</summary>

    Try to run the tests locally, according to the documentation. However, a CI failure may still happen due to a number of reasons, for example:

    • Possibly due to a silent merge conflict (the changes in this pull request being incompatible with the current code in the target branch). If so, make sure to rebase on the latest commit of the target branch.

    • A sanitizer issue, which can only be found by compiling with the sanitizer and running the affected test.

    • An intermittent issue.

    Leave a comment here, if you need help tracking down a confusing failure.

    </details>

  17. DrahtBot removed the label CI failed on Oct 31, 2026
  18. DrahtBot removed the label Needs rebase on Oct 31, 2026
  19. fametrano commented at 6:25 PM on November 1, 2026: none

    tACK d36943b49ce321cd622a8ae5a885227c7b3189cf

    The PR's own changes are the ones I tested on 0b01ce05: the range-diff only moves three bench includes into the earlier bench commits and places the new tests before master's new blockmanager_tests case, and the net diff is unchanged line for line. The new base widens block file positions to 64 bits, which the new read path goes through, so I re-ran the byte-for-byte check rather than carry the old result over.

    On this head, ReadBlockWithoutWitness matches ReadBlock plus TX_NO_WITNESS for the same five mainnet blocks and for 263 new regtest blocks, and btclib agrees. The regtest blocks include taproot annexes of up to 3,990,001 bytes, witness stacks of 1,001 items, 260 transactions, 300 inputs and 316 outputs, and three blocks with no witness. Over P2P, MSG_BLOCK equals the test framework's non-witness serialization for all 263 blocks read from disk and for 22 of them while they were the tip. MSG_WITNESS_BLOCK equals getblock. blockmanager_tests, p2p_getdata, p2p_segwit and p2p_compactblocks pass. I did not re-run the mutants or the timings. Scripts and output: https://gist.github.com/fametrano/740bc1f88f3d5967023c920824bafd70/29865a5e048c740b1ac50fbc311e2f1607bfaa3d

  20. l0rinc force-pushed on Nov 9, 2026
  21. l0rinc commented at 9:47 PM on November 9, 2026: contributor

    Rebased + applied some minor Fable 5.2 simplification suggestions.

  22. DrahtBot added the label Needs rebase on Nov 10, 2026
  23. fametrano commented at 9:41 PM on November 10, 2026: none

    reACK 52081127364481ed14249e38bd460e725e4b0a40

    Since d36943b4, the rebase and the simplifications l0rinc applied leave the non-test changes identical line for line; only the unit tests, the functional test and the bench changed. The new base widens the block file sizes and constants to 64 bits, with the same values.

    I re-ran the earlier checks on this head with the same scripts (https://gist.github.com/fametrano/740bc1f88f3d5967023c920824bafd70/29865a5e048c740b1ac50fbc311e2f1607bfaa3d). ReadBlockWithoutWitness still matches ReadBlock plus TX_NO_WITNESS for the five mainnet and 263 regtest blocks, MSG_BLOCK still matches the non-witness serialization for all 263 regtest blocks, and blockmanager_tests, p2p_getdata, p2p_segwit and p2p_compactblocks pass.

  24. l0rinc force-pushed on Nov 11, 2026
  25. DrahtBot removed the label Needs rebase on Nov 11, 2026
  26. DrahtBot added the label Needs rebase on Nov 26, 2026
  27. l0rinc force-pushed on Nov 27, 2026
  28. DrahtBot removed the label Needs rebase on Nov 27, 2026
  29. in test/functional/p2p_getdata.py:70 in be13ee8903
      65 | +        node = self.nodes[0]
      66 | +        blockhash = self.generate(node, 1)[0]  # Generated blocks have a coinbase witness
      67 | +        full = bytes.fromhex(node.getblock(blockhash, 0))
      68 | +        stripped = from_binary(CBlock, full).serialize(with_witness=False)
      69 | +        assert_greater_than(len(full), len(stripped))
      70 | +        MESSAGEMAP[b"block"] = RawBlockMessage
    


    optout21 commented at 8:04 AM on November 30, 2026:

    be13ee8 test: cover block serving serialization:

    This overwrite is not restored. Can later tests be distracted by this?

  30. in src/net_processing.cpp:2648 in 28a0c6a4ec
    2647 | -        // Fast-path: in this case it is possible to serve the block directly from disk,
    2648 | -        // as the network format matches the format on disk
    2649 | -        if (const auto block_data{m_chainman.m_blockman.ReadRawBlock(block_pos)}) {
    2650 | +    } else if (const bool strip_witness{inv.IsMsgBlk() && !m_chainparams.GetConsensus().signet_blocks};
    2651 | +               inv.IsMsgWitnessBlk() || strip_witness) {
    2652 | +        // Serve MSG_WITNESS_BLOCK directly from on-disk serialization.
    


    optout21 commented at 8:08 AM on November 30, 2026:

    28a0c6a net: serve MSG_BLOCK from serialized data:

    Nit: This also handles MSG_BLOCK

  31. in src/net_processing.cpp:2650 in 28a0c6a4ec outdated
    2649 | -        if (const auto block_data{m_chainman.m_blockman.ReadRawBlock(block_pos)}) {
    2650 | +    } else if (const bool strip_witness{inv.IsMsgBlk() && !m_chainparams.GetConsensus().signet_blocks};
    2651 | +               inv.IsMsgWitnessBlk() || strip_witness) {
    2652 | +        // Serve MSG_WITNESS_BLOCK directly from on-disk serialization.
    2653 | +        // Use ReadBlock below for MSG_BLOCK on Signet to check the block solution.
    2654 | +        const auto& blockman{m_chainman.m_blockman};
    


    optout21 commented at 8:10 AM on November 30, 2026:

    28a0c6a net: serve MSG_BLOCK from serialized data:

    Nit: as this alias is introduced, it could also be used 4 lines below, within the same code block. (return m_chainman.m_blockman.IsBlockPruned(*pindex))

  32. optout21 commented at 8:32 AM on November 30, 2026: contributor

    Concept ACK (28a0c6a4ec09a1c56cb1c9685360bbb7ab37c58a)

    Reviewed by reimplementing and comparing solutions.

    Comments:

    • StripBlockWitness is pure serialization logic with no storage dependency, but it sits in node:: inside blockstorage. Putting it next to the block and transaction serialization code would make it reusable (for example by REST or a future compact-block path), and its tests wouldn't need node code.

    • The reason to exclude Signet could be explained in more detail.

    • Signet isn't covered. No test exercises the MSG_BLOCK-on-Signet branch, which still uses ReadBlock. It's cheap to leave untested since it's the old code path, but if the special case stays, a test would stop it from being lost in a later cleanup.

    • Is ReadBlockWithoutWitness more similar to ReadBlock or ReadRawBlock? It's a combinations; this could be explained.

    • Possible follow-up: CSerializedNetMsg::data is a std::vector<unsigned char>, so NetMsg::Make copies the 1–4 MB payload once more. If the message could take ownership of the buffer, that copy would go away for both the witness and non-witness paths.

  33. l0rinc force-pushed on Dec 1, 2026
  34. l0rinc force-pushed on Dec 1, 2026
  35. l0rinc commented at 8:18 PM on December 1, 2026: contributor

    Thanks for the review, @optout21! I rebased and moved the witness-stripping code and tests next to block serialization and made the P2P test restore MESSAGEMAP. I also added a test that checks that we serve a valid Signet block from disk and refuse it if its solution is damaged.

  36. in src/node/blockstorage.cpp:1099 in 1f1d86c9f2
    1093 | @@ -1094,6 +1094,30 @@ bool BlockManager::ReadBlock(CBlock& block, const CBlockIndex& index) const
    1094 |      return ReadBlock(block, block_pos, index.GetBlockHash());
    1095 |  }
    1096 |  
    1097 | +BlockManager::ReadRawBlockResult BlockManager::ReadBlockWithoutWitness(const FlatFilePos& pos, const uint256& expected_hash) const
    1098 | +{
    1099 | +    Assume(!GetConsensus().signet_blocks);
    


    optout21 commented at 8:52 AM on December 2, 2026:

    1f1d86c node: read non-witness block payloads:

    Nit: This can happen on incorrect usage, so maybe a proper error in this case would be more appropriate. Assume does nothing in release mode.

  37. in src/node/blockstorage.cpp:1113 in 1f1d86c9f2 outdated
    1108 | +            return util::Unexpected{ReadRawError::IO};
    1109 | +        }
    1110 | +        if (hash != expected_hash) {
    1111 | +            LogError("GetHash() doesn't match index at %s while reading block (%s != %s)", pos.ToString(), hash.ToString(), expected_hash.ToString());
    1112 | +            return util::Unexpected{ReadRawError::IO};
    1113 | +        }
    


    optout21 commented at 9:09 AM on December 2, 2026:

    1f1d86c node: read non-witness block payloads:

    Nit: These checks are verbatim in ReadBlock as well, a common helper could reduce code duplication (it's fine to have CheckSignetBlockSolution in as well, as that's if'ed).


    l0rinc commented at 2:01 PM on December 2, 2026:

    Sharing that sequence would require passing the decoded block into the helper, I tried it, didn't like the results - you can suggest a version you like if you think we should do it here.

  38. in src/node/blockstorage.cpp:1108 in 1f1d86c9f2 outdated
    1103 | +        CBlockHeader header;
    1104 | +        SpanReader{*data} >> header;
    1105 | +        const auto hash{header.GetHash()};
    1106 | +        if (!CheckProofOfWork(hash, header.nBits, GetConsensus())) {
    1107 | +            LogError("Errors in block header at %s while reading block", pos.ToString());
    1108 | +            return util::Unexpected{ReadRawError::IO};
    


    optout21 commented at 9:11 AM on December 2, 2026:

    1f1d86c node: read non-witness block payloads:

    Nit: Invalid data read from disk is arguably not an IO error, but data inconsistency. Could use a specialized error here.


    l0rinc commented at 2:02 PM on December 2, 2026:

    InvalidData may be more precise, but the logs already distinguish the failures and the P2P caller handles them the same way - the diff seems simpler as-is.

  39. optout21 commented at 9:12 AM on December 2, 2026: contributor

    ACK 8a827efb361aaef267f0ec3e31f7b17d2b88c251

    Thanks for addressing my review comments. Reviewed again, only non-blocking nits found.

  40. DrahtBot requested review from fametrano on Dec 2, 2026
  41. l0rinc referenced this in commit 64378eb189 on Dec 2, 2026
  42. l0rinc force-pushed on Dec 2, 2026
  43. l0rinc commented at 2:02 PM on December 2, 2026: contributor

    Rebased and made ReadBlockWithoutWitness return an error on Signet in all builds, thanks @optout21

  44. optout21 commented at 11:07 AM on December 4, 2026: contributor

    It looks like the fixup is missing for the last fixup commit. I've reviewed it, LGTM, thanks for reacting. Happy to re-ack after fixup.

  45. test: cover block serving serialization
    Check exact `MSG_BLOCK` and `MSG_WITNESS_BLOCK` payloads before and after recent-block cache eviction.
    Request an older Signet block from disk and check that serving it rejects corruption of its stored solution.
    0a720ef990
  46. bench: measure non-witness block serving
    Measure disk reads followed by `TX_NO_WITNESS` message serialization before replacing the full block reader.
    
    Measurements from the original branch at `369db2528b` before #36895.
    
    Witness-free: 1.31 ms/block
    Witness-bearing: 3.47 ms/block
    41846674a2
  47. node: read non-witness block payloads
    Check proof of work and the expected block hash before walking the serialized transactions.
    Compact the retained bytes in the owned buffer so serving can skip witnesses without constructing transactions or computing their cached hashes.
    Switch the non-witness serving benchmark to the new reader.
    
    Compare the result with ordinary decoding followed by non-witness serialization in unit and fuzz tests.
    
    Return an error on Signet, where `ReadBlock` must verify the block solution.
    6d6d10bb1d
  48. net: serve `MSG_BLOCK` from serialized data
    Use `ReadBlockWithoutWitness` for disk-backed `MSG_BLOCK` requests.
    Keep Signet, cached, witness, compact, and filtered block requests on their existing paths.
    5163788036
  49. l0rinc force-pushed on Dec 4, 2026
  50. l0rinc commented at 11:11 AM on December 4, 2026: contributor

    It looks like the fixup is missing for the last fixup commit.

    That's how I usually review locally, forgot to fold back the fixup, thanks, rebased and folded it back, no other change was done in latest push.

  51. optout21 commented at 11:17 AM on December 4, 2026: contributor

    reACK 516378803669d42e0dda9e1a29ef8cbc229dcdb0 (git range-diff 8a827ef...5163788)


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-12-05 04:51 UTC

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