Skip to content

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

Open
l0rinc wants to merge 5 commits into
bitcoin:masterfrom
l0rinc:l0rinc/msg-block-serving
Open

l0rinc wants to merge 5 commits into
bitcoin:masterfrom
l0rinc:l0rinc/msg-block-serving

Conversation

@l0rinc

@l0rinc l0rinc commented Oct 16, 2026 •

Copy link
Copy Markdown
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

@DrahtBot DrahtBot added the P2P label Oct 16, 2026
@DrahtBot

DrahtBot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

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

External sites

Reviews

See the guideline and AI policy for information on the review process.

Type Reviewers
Stale ACK fametrano, optout21

If your review is incorrectly listed, please copy-paste <!--meta-tag:bot-skip--> into the comment that the bot should ignore.

Conflicts

Reviewers, this pull request conflicts with the following ones:

  • #36946 (scripted-diff: [test] Add util/check.h includes for assertions by maflcko)
  • #36621 (node: batch block file pruning in a single pass over block index by mutatrum)
  • #36000 (validation: prefetch blocks while connecting by l0rinc)
  • #35731 (Indexes: Harden the flush-error notification invariant by arejula27)
  • #35003 (validation: improve block data I/O error handling in P2P paths by furszy)
  • #32554 (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.

@DrahtBot

Copy link
Copy Markdown
Contributor

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

Hints

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

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

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

  • An intermittent issue.

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

@l0rinc
l0rinc force-pushed the l0rinc/msg-block-serving branch from 7b0104b to 0b01ce0 Compare October 16, 2026 13:37
@l0rinc l0rinc closed this Oct 18, 2026
@l0rinc l0rinc reopened this Oct 18, 2026
pmazzocchi pushed a commit to btclib-org/btclib-node that referenced this pull request Oct 18, 2026
A getdata for MSG_BLOCK or MSG_CMPCT_BLOCK sent the stored record
without checking that it was the block asked for. A record holding
another well-formed block went out under the requested hash.

Core v31.1 reads these items with ReadBlock(..., inv.hash). It refuses a
header that misses its proof of work, on signet a block whose solution
does not verify, and a header that hashes to another hash. This node
asks the same, in that order. Off signet, only the 80 header octets are
parsed.

A MSG_WITNESS_BLOCK is not checked: Core reads it with ReadRawBlock,
which checks no hash. bitcoin/bitcoin#36548, at its head 0b01ce05e1,
checks the header's work and hash before it strips a MSG_BLOCK, reads a
signet MSG_BLOCK with ReadBlock, and serves a MSG_WITNESS_BLOCK as read.

A refused read logs "Cannot load block from disk" as an error and drops
the peer, as Core does. A record that does not parse gets the same
answer; it raised and kept the peer.

Tests pin the order: a forged signet record under another hash is refused
for its solution, and a forged signet record missing its work for its
work.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: Ferdinando Ametrano <[email protected]>
Signed-off-by: pmazzocchi <[email protected]>
@fametrano

Copy link
Copy Markdown

tACK 0b01ce0

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.

@l0rinc
l0rinc force-pushed the l0rinc/msg-block-serving branch 2 times, most recently from 4ddf35f to d36943b Compare October 31, 2026 15:24
@DrahtBot

Copy link
Copy Markdown
Contributor

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

Hints

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

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

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

  • An intermittent issue.

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

@fametrano fametrano left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

tACK d36943b

The PR's own changes are the ones I tested on 0b01ce0: 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

@l0rinc

l0rinc commented Nov 9, 2026

Copy link
Copy Markdown
Contributor Author

Rebased + applied some minor Fable 5.2 simplification suggestions.

@optout21 optout21 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Concept ACK (28a0c6a)

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.

Comment thread test/functional/p2p_getdata.py Outdated
full = bytes.fromhex(node.getblock(blockhash, 0))
stripped = from_binary(CBlock, full).serialize(with_witness=False)
assert_greater_than(len(full), len(stripped))
MESSAGEMAP[b"block"] = RawBlockMessage

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

be13ee8 test: cover block serving serialization:

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

Comment thread src/net_processing.cpp Outdated
if (const auto block_data{m_chainman.m_blockman.ReadRawBlock(block_pos)}) {
} else if (const bool strip_witness{inv.IsMsgBlk() && !m_chainparams.GetConsensus().signet_blocks};
inv.IsMsgWitnessBlk() || strip_witness) {
// Serve MSG_WITNESS_BLOCK directly from on-disk serialization.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

28a0c6a net: serve MSG_BLOCK from serialized data:

Nit: This also handles MSG_BLOCK

Comment thread src/net_processing.cpp
inv.IsMsgWitnessBlk() || strip_witness) {
// Serve MSG_WITNESS_BLOCK directly from on-disk serialization.
// Use ReadBlock below for MSG_BLOCK on Signet to check the block solution.
const auto& blockman{m_chainman.m_blockman};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

@l0rinc
l0rinc force-pushed the l0rinc/msg-block-serving branch 2 times, most recently from df99e2d to 8a827ef Compare December 1, 2026 20:17
@l0rinc

l0rinc commented Dec 1, 2026

Copy link
Copy Markdown
Contributor Author

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.

@optout21 optout21 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ACK 8a827ef

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

Comment thread src/node/blockstorage.cpp Resolved
Comment thread src/node/blockstorage.cpp
Comment on lines +1106 to +1113
if (!CheckProofOfWork(hash, header.nBits, GetConsensus())) {
LogError("Errors in block header at %s while reading block", pos.ToString());
return util::Unexpected{ReadRawError::IO};
}
if (hash != expected_hash) {
LogError("GetHash() doesn't match index at %s while reading block (%s != %s)", pos.ToString(), hash.ToString(), expected_hash.ToString());
return util::Unexpected{ReadRawError::IO};
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

Comment thread src/node/blockstorage.cpp
const auto hash{header.GetHash()};
if (!CheckProofOfWork(hash, header.nBits, GetConsensus())) {
LogError("Errors in block header at %s while reading block", pos.ToString());
return util::Unexpected{ReadRawError::IO};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

@DrahtBot
DrahtBot requested a review from fametrano December 2, 2026 09:12
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.
Measure disk reads followed by `TX_NO_WITNESS` message serialization before replacing the full block reader.

Measurements from the original branch at `369db2528b` before bitcoin#36895.

Witness-free: 1.31 ms/block
Witness-bearing: 3.47 ms/block
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.
Use `ReadBlockWithoutWitness` for disk-backed `MSG_BLOCK` requests.
Keep Signet, cached, witness, compact, and filtered block requests on their existing paths.
Reject Signet in ReadBlockWithoutWitness so callers get an error in release builds. They need ReadBlock to verify the block solution.

optout21 pointed out that “Assume does nothing in release mode.”
bitcoin#36548 (comment)
@l0rinc
l0rinc force-pushed the l0rinc/msg-block-serving branch from 8a827ef to 64378eb Compare December 2, 2026 13:58
@l0rinc

l0rinc commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants