mirror of
https://github.com/bitcoin/bitcoin
synced 2026-12-04 10:47:36 +00:00
WIP: p2p: Prefill compact blocks #35558
No reviewers
Labels
No labels
Android
Backport
Block storage
Brainstorming
Bug
Build system
CI failed
Consensus
Data corruption
Descriptors
Docs
DrahtBot Guix build requested
Feature
Fuzzing
GUI
Good First Review
IPC
Insufficient Review
Kernel
Linux/Unix
Mempool
Mining
Needs Backport (31.x)
Needs Backport (32.x)
Needs Benchmark
Needs Conceptual Review
Needs backport (30.x)
Needs rebase
Needs release note
Net
P2P
PSBT
Privacy
Private Broadcast
Questions and Help
RPC/REST/ZMQ
Refactoring
Resource usage
Review club
Scripts and tools
Settings
TX fees and policy
Tests
Tracking Issue
UTXO Db and Indexes
Up for grabs
Upstream
Utils/log/libs
Validation
Waiting for author
Wallet
Windows
good first issue
interfaces
macOS
No milestone
No project
No assignees
2 participants
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
bitcoin/bitcoin!35558
Loading…
Reference in a new issue
No description provided.
Delete branch "2025-11-13-0xB10C-prefill-rebase-binary-limit"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
This is an implementation based on 0xB10C's proposal and implementation of prefilling CMPCTBLOCK messages with what we1 needed during CMPCTBLOCK reconstruction in the hopes of providing everything our peers will need to reconstruct without having to ask us for transactions.
Although full support for receiving prefills is implemented in Bitcoin Core, the only prefills sent presently are coinbases. The goal of prefilling is to improve compact block reconstruction rates, which reduces the number of roundtrips needed to propagate blocks per-hop, which reduces the amount of time needed for blocks to propagate on the network, which mitigates selfish mining attacks by lowering the stale rate and the ratio
γof honest miners a selfish miner is able to recruit in a block race.2 The tradeoff of prefilling is that it uses a small amount of extra bandwidth and makes propagation slightly worse when the predictions are bad.My primary contribution is limiting the prefill based on the connection's TCP window. Exceeding the boundary of the current TCP window will result in a ~roundtrip at the network layer,3 and any time a roundtrip is going to be incurred anyways, it would be better to let our peer tell us exactly what they are missing in a roundtrip instead of hazarding a guess, which risks sending redundant information.4
Prefill do
In measurements I took from 2026-02-15 to 2026-03-16, a node receiving prefilled
CMPCTBLOCKs limited to the TCP window size was able to reconstruct 89.7% of compact blocks received without a GETBLOCKTXN roundtrip, and a node receiving typicalCMPCTBLOCKs with only coinbases prefilled was able to reconstruct 56.9% of blocks received without a GETBLOCKTXN roundtrip.5The mean prefill sent was 1,694.64 bytes and the median was 897 bytes. If all the bytes of every prefill were redundant 6, the cost of prefilling 1,694.64 bytes would be 1.39 MiB per node in wasted bandwidth per day (counting both the sending and the receiving bandwidth for all 3 HB peers).
Prefill why
There are changes that are likely more effective at improving propagation times than prefilling, for example:
The advantage of this approach is that it requires no protocol changes and is entirely backwards compatible with existing node software that has implemented the
CMPCTBLOCKprotocol. Concretely: An old version of Bitcoin Core that knows nothing about this PR can enjoy faster block reconstructions if it connects to a peer that prefills blocks. I think these benefits are worth the tradeoff of violating the layer cake and taking transport matters into our own hands.Prefill what
GETBLOCKTXN->BLOCKTXNround trip with our peer.The reasons to like this heuristic are that it's simple, per-block rather than per-peer, makes sense on paper, and seems to be effective in practice.
Prefill when
To avoid having to generate unique CMPCTBLOCK messages for each of our peers, which might be costly8, we (lazily9) build and cache 2 CMPCTBLOCK messages: one prefilled and one not prefilled.
At sending time we check the available bytes in our peer's TCP window, and if the total number of TCP windows occupied by the prefilled block is equal to the total number of windows occupied by the nonprefilled block, then we send the prefilled block.
TCP Windows
Discussed in greater detail elsewhere, I'll try to summarize here:
In RFC 793, TCP was specified with receiver advertised window sizes because receivers allocate some buffer size to a given TCP connection, and this receiver advertised window represents the most unacknowledged data a receiver will process before dropping bytes on the ground or something awful like that. So the sender of a message over a TCP connection will only send up to the last acknowledged byte + the receiver's advertised window size in order to avoid filling up their peer's receive buffer.
It was later discovered that TCP was susceptible to "congestion collapse", which can probably describe any congestion feedback loop but in TCP is where packets being dropped due to congestion results in retransmissions that cause even more congestion. TCP implementers addressed this with "congestion control" algorithms which decide on the sending side to limit the number of bytes to send dynamically, based on how frequently packets are dropped on a TCP connection. For a more concrete account of various congestion control algorithms see RFC 5681. A user's TCP implementation (typically in their OS kernel) will compute a window size dynamically for each TCP connection usually increasing as packets sent are ACKnowledged and decreasing when packets sent are dropped.
Computed congestion control window sizes vary:
There is not likely to be any way to guess or predict what the TCP window will be very effectively, and we must query the TCP implementation in order to learn what our connection window sizes are.
The usable window size is the smaller of the receiver advertised window and the sender computed congestion control window, but in practice the congestion control window is far smaller. In my observation node, the mean Bitcoin P2P congestion window observed was 17,360.52 bytes and the median was 14,480 bytes.
'We' refers to the Royal Node. ↩︎
(2013) Eyal and Sirer Majority is not Enough (pg. 8) https://arxiv.org/pdf/1311.0243 The claim that lowering block propagation times lowers γ probably needs serious analysis, but my hand-waving argument is that the faster public network-wide block propagation is, the more expensive any proportional propagation time advantage over the public network becomes, and γ is a function of propagation time advantage. ↩︎
A network layer roundtrip will be faster than an application layer roundtrip, although probably not by much for most connections. Since at the application layer there will be some time your message spends waiting to be processed by your peer, at least for peers that use single-threaded message processing like Bitcoin Core does presently. ↩︎
In practice exceeding the TCP window is ~not quite as bad as I've implied here and in the delving post: because the window is sliding, once the first 1.5 round-trips are completed there is a continuous stream as ACKnowledgements for the oldest segments arrive and the newest segments are fired out. The effect of this more precisely is that if a message exceeds a window boundary, the minimum travel time of the message becomes 1.5 round-trip-time (RTT) instead of 0.5 RTT and the throughput limit of the connection becomes
\text{window size} / \text{RTT}. I am working on a more complete write-up that takes this more precise cost into consideration, but I think approximating it as a ~round trip is reasonable. ↩︎In reality, not all of the prefill is redundant otherwise prefilling would not be very useful. In my observation node that received prefilled compact blocks, the mean redundant prefill bytes was 865.62 bytes/block. 2 HB announcements will always be redundant so: 1.17 MiB per node in wasted bandwidth per day if one CMPCTBLOCK announcement only has 865.62 redundant bytes. ↩︎
I will share a write-up describing my full experimental setup and data soon. It was mostly identical to the set up described here: https://delvingbitcoin.org/t/stats-on-compact-block-reconstructions/1052/34 I had one node running a prefilling branch, and another node set up to only receive CMPCTBLOCK messages from the prefilling node. My infrastructure as code observation set up: https://github.com/davidgumberg/prefill-research and the script I used to analyze the results: https://radicle.network/nodes/iris.radicle.network/rad:z37pH1UAxFvazXnfAMS5qbcUjQaP6/tree/leave/scripts/prefill.py ↩︎
The reason to pluck from the extrapool is because it is very likely to differ between nodes. ↩︎
But maybe there is some cost here that is worth trading off, it's not something I've explored. ↩︎
This is based on andrewtoth's #26755. ↩︎
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.
If your review is incorrectly listed, please copy-paste
<!--meta-tag:bot-skip-->into the comment that the bot should ignore.Conflicts
Reviewers, this pull request conflicts with the following ones:
If you consider this pull request important, please also help to review the conflicting pull requests. Ideally, start with the one that should be merged first.
LLM Linter (✨ experimental)
Possible typos and grammar issues:
src/blockencodings.h:annoucements→announcements[misspelling]src/net_processing.cpp:annoucements→announcements[misspelling]src/net_processing.cpp:recontruct→reconstruct[misspelling]src/util/sock.h:on /Linux|e.BSD/→on Linux/BSD[malformed wording]2026-11-06 01:47:23
Concept ACK
Concept ACK.
Curious to see also Prefill Who section.
These transactions in the extrapool were sent to us by some peers, no? We can reduce a bit of redundancy by not sending them again to the peers that announced them to us.
Concept ACK
Based on prior discussions we've had about this, very excited to see it come to life. I have not looked at the code yet, but after reading the PR description (very well done, btw), I strongly agree that the simplicity and backwards compatibility of the approach make this a very strong proposal.
Concept ACK
Concept ACK
Very excited to see this PR.
Concept ACK.
Again, thanks for picking this idea up and moving it closer to the finish line.
An idea mentioned in the delving post was to log information about wasted prefill bandwidth on the receiving side. How many transactions were received that we didn't use? How many extra bytes did we receive? This doesn't have to happen in this PR, but would probably good to have before this is reaches broader deployment on mainnet.
Once merged: I've been thinking about how I could test the effect on mainnet once this is deployed. One idea would be to run a node that's patched to specifically NOT use anything prefilled besides the coinbase and compare it's reconstruction performance to the other mainnet nodes. Additionally, keeping track of what share of blocks come with more than a coinbase prefilled and measuring their reconstruction performance would be interesting.
I'm not too sure about logging this for all required transactions in a non-test setting (which might be a few thousands). Could this cause log rate-limiting? Maybe a good use for the
tracelog level?Running this PR and observing this in the logs should give us information about how often we can prefill.
This is probably a good idea even before merging this, maybe there is some fine tuning we can find.
cc @m4ycon
f610cdd2a6d3aa6de8de8cc20af3664277bba07d utACK
will test it locally and gather debug logs.
nit: this assert is not needed here and elsewhere in this file (feel free to ignore)
github.com/bitcoin/bitcoin@e1290ce7f7/doc/developer-notes.md (L976-L979)Since we are just reading the
send_statewhy not prefer WITH_LOCK?I think we can hoist
cb_futandprefilled_cb_futout and copy the shared futures whilem_most_recent_block_mutexis held, then release the lock for the rest of this method.The only other thing we need is
m_most_recent_pow_block.hashbelow, but we can get that viapindex->GetBlockHash()instead.Ah! Great idea! Pushing an update that does this...
Yeah I kind of agree, to me it just didn't make sense to log only if there are 5 or fewer, it seems either all of them should be logged or none.
Trace and Debug level logs are not rate limited:
github.com/bitcoin/bitcoin@dc282ff31d/src/util/log.h (L132-L140)I didn't know that! thanks, taken.
Good catch, fixed, thank you.
Nice! Much better to not hold a lock that prevents block updates while doing syscalls!!
Thanks to reviewers for feedback, I've pushed to address.
Even if a peer has sent us a transaction that ends up in our extrapool, they may not have it in their mempool now since:
The other problem with this that I see would be the cost in implementation complexity and in node resources of tracking per-peer, and potentially creating new CMPCTBLOCK's per-peer. The current branch is very conservative in only generating two candidate CMPCTBLOCK messages, one prefilled, and one not prefilled, as the working assumption is that it would be bad for performance to have to generate unique CMPCTBLOCK messages for each peer, and because of the way CMPCTBLOCK serialization works, adding a single prefilled transaction unfortunately means having to reserialize the whole thing, since the short-txid has to be removed, and the differential index for the next prefill would have to be changed.
The assumption that per-peer prefills would be too expensive might be wrong, but needs to be investigated. Empirically in my observations, I should point out that of the redundant prefill data received by the prefill-receiving node, 85% was stuff that was already in the prefill-receiving node's extra-pool.
That's a great point, I had logic for this in my observation nodes, but I've incorporated the changes into this PR.
I don't think we should seed with the coinbase here. In that case, the check in net_processing for
prefill_candidates.size() > 0is always true, so we will always go through the prefill path and do all the syscalls even for the current behavior of always prefilling only the coinbase. We should only bother with that logic if we have at least one non-coinbase prefill tx.We log
window_sizeandbytes_availablehere, but we also log them on the call side. Can we remove one of the logs?When will the block hash in
prefill_candidatesdiffer fromhashabove? Can these be merged?I don't think we should be switching the serialization from
std::launch::deferredtostd::launch::async. The latter spawns a new thread and serializes message eagerly, while the former just defers the serialization lazily until something callsget()on the future.Spawning threads is harder to reason about here as well. There can be lifetime issues introduced.
Edit: Hmm I see from the commit message this is intentional. I suppose it doesn't introduce any lifetime issues since we're just copying shared_ptrs. But, I think the main benefit was that we serialize the message once for all our peers, instead of having to reserialize for each. With prefilling it might make sense to also do that eagerly in a background thread.
style nit: no hungarian notation. Also, please be consistent in declaration and implementation of parameters. Some places are putting the ref or pointer marker next to the variable name, but they should all be next to the type (
CNode& nodeinstead ofCNode &node).Also need
prefilled_size += tx_size;We don't increment/decrement
extra_sizeeither. Seems like an oversight?This is a use-after-free. We need to get the size before we reset it 3 lines above.
Here and in
GetMessageSizeabove, we should takem_send_mutexlock and return the value ifsend_state != SendState::v1, and then return the fallback after releasing the lock. That way we don't take and release the lock multiple times.Thanks for catching, sorry the quality of this logging commit was low when I pushed it.
Thanks for catching, sorry this went out broken.
Also this probably should've been caught by a sanitizer during testing, I'll investigate.
Fixed, thank you.
🐙 This pull request conflicts with the target branch and needs rebase.
Hmm, looking back at this I can't think of a good way to test collisions in unit tests, but I think this would have been caught by fuzzing.
Yeah, sorry if it's weird to combine both changes in one commit, I can split up if you think that makes sense. OK to mark this resolved or is there still a concern?
Taken thanks, this also made me realize
GetMessageHeaderSizeshouldn't be virtual, public, or take a lock, so fixed that as well.Great catch, thank you, I took this by changing the check to be
prefill_candidates.size() > 1Ok, I removed it on the caller side.
I have to think about this a little more, but right now the issue is that we'll update the prefill candidates on reconstruction, but the block might still fail somewhere in
ProcessBlock():github.com/bitcoin/bitcoin@9f36a29393/src/net_processing.cpp (L3659-L3667)tACK 9c3a0a5
For the past week I’ve been running this PR and collecting some data. I created a repository to show some statistics about how effective this change is, by trying to show some numbers that could answer my research questions (RQs).
For those who don't want to get too deep into this, I recommend just taking a look at RQ1.5 and RQ2.2 -- readme points where they are.
Repository: https://github.com/m4ycon/prefill-compact-blocks-review
I still plan to run for about a week or two, to see if anything changes (I suppose not). And to implement a good suggestion by @johnnyasantoss, to run a "Node-C" from a second machine to see if it makes some difference on RQs -- current setup is running two nodes on the same machine.
Maybe I'm missing something here. Just a minor issue affecting logs, but why inside this condition
!pool->exists(tx_wtxid)which means "not in mempool", there's a mempool variableredundant_prefilled_mp_...handling? Wouldn't this else hold cases like "not in mempool and not in extrapool"?🐙 This pull request conflicts with the target branch and needs rebase.
tACK 9f36a29393663bb2a70d0f0690ec30f2176f6ef6
Built and ran on Linux x86_64 (gcc 13.3, RelWithDebInfo,
-DBUILD_GUI=OFF -DENABLE_IPC=OFF):blockencodings_tests, 8 cases)p2p_compactblocks.py,p2p_compactblocks_blocksonly.py,p2p_compactblocks_hb.py(v1 + v2 transport): all passI also rebased this onto current master (
70d9ec7f3d), resolving the conflicts with #35727'sTxSourcerefactor: https://github.com/s00ly/bitcoin/tree/35558-rebase-2026-07-22 (headfc4355a0cf7e). The same test battery passes on the rebased branch. Feel free to cherry-pick it or treat it as reference only.Rebase notes (worth author/maintainer eyes):
TxSourceenum. Collision decrements are now attributed by source:EXTRAdecrementsextra_count, otherwisemempool_count.extra_sizeunconditionally on collision; the rebased version subtracts from the pool the slot actually came from. Log numbers only; flagging in case the unconditional version was deliberate.ReceiveWithExtraTransactions(GetMempoolCount()1U -> 0U after the MEMPOOL-slot collision) to match this PR's intended disjoint semantics; folded into commit 2.TxSource::EXTRAandprefill_candidates.insertin the extrapool-hit path.(Also noting the LLM-linter typos are still present:
annoucementsx4,recontructx1.)range-diff vs 9f36a2939
I was about to update datasets on my analysis repo (see this for more context), but I realized that drawing conclusions from logs is unreliable if they are not 100% accurate -- some questions could still be answered, but not all. I'll take a break from those tests until they are fixed.
I assume that the first version of the analysis is still accurate, although I'm not 100% sure because I couldn't check the code state of that commit.
If it helps, I have uploaded the last logs here on this branch.
It seems that there's some problem with
prefilled_sizein this log. Using my recent logs (run against the most recent version of this PR, 9f36a29), the value is always zero. Which could not be true in any scenario as coinbase is always prefilled. I couldn't find any assignment to it, probably it's a simple fix.See also https://github.com/bitcoin/bitcoin/pull/35724 for the logging changes which will be merged first.
Hmm totally forgot about this one. I'll let both my comments open, although I see they are fixed in #35724. Feel free to resolve those comments when this PR is rebased with them (author).
Good catch, this got messed up while rebasing, pushed a fix.
Rebased on top of #35724, where I've pulled out the logging changes, review there would be appreciated.
Thanks, I've rebased this on #35724, so marking as resolved.
11 additional verified findings in the full report.
Earlier concerns remain unresolved; see the full report for their current assessments.
🟠 Minor · Optimistic reconstruction drops prefill candidates
When optimistic reconstruction wins without candidates already cached for that block, its non-mempool transactions are omitted from outgoing prefills.
Location:
src/net_processing.cpp:3870(head).🟠 Minor · Separate queue samples can miss bytes sent between them
A socket-thread send between the kernel and application queue reads can omit bytes from both samples and overstate the remaining window budget.
Location:
src/net.cpp:4289(head).🟠 Minor · Cached getdata replies can overwrite current-branch header state
After a reorg, serving a stale cached compact block can overwrite pindexBestHeaderSent and make that peer's next announcement fall back to INV.
Location:
src/net_processing.cpp:2380(head).🟠 Minor · tcp_info test ignores the Linux congestion-only fallback
On Linux without tcpi_snd_wnd, the test compares a congestion-window estimate with requested receive-buffer sizes, so valid fallback behavior can fail the test.
Location:
src/test/sock_tests.cpp:221(head).🟠 Minor · Diagnostic counts depend on the log level at initialization
blockencodings.cpp:205 still collects mempool and extra-pool counts only if debug logging was on during InitData, and FillBlock (286) checks again, so enabling logging in between reports zeros. This exists in the base; the head narrowed it by always collecting prefill counters.
Location:
src/blockencodings.cpp:205(head).🟠 Minor · Keep platform-specific TCP queries out of the widely included socket header
TCPInfo and its platform-specific queries are still defined inline in the widely included sock.h, and compat.h now pulls linux/tcp.h, linux/version.h and mstcpip.h into every file that includes it.
Location:
src/util/sock.h:341(head).Review coverage was incomplete.
Reviewed:
aee9cc32881c· Full review report · Previous reportspermalink
Rebased on the latest #35724, marking this as draft until that is merged.
🐙 This pull request conflicts with the target branch and needs rebase.
🐙 This pull request conflicts with the target branch and needs rebase.
I just had some time to come back at this, and as a follow-up from this earlier comment about an analysis, I ran this PR with the Node C idea that I commented and got some more realistic numbers -- which are worse from the initial scenario but still great. It ran on top of
864895088bfor about a month, which is not the latest version but as I suppose the main idea didn't change, so it's still valid.Repository: https://github.com/m4ycon/prefill-compact-blocks-review
I aim to review it (code, not the test above) when it's marked as ready to review again.
Rebased on #36787, I've extracted some of the refactors and performance improvements here into that PR for separate review, and that PR should be reviewed before this one.
A note on the metric. The metric mentioned in the description -- the ratio of blocks reconstructed without any extra GETBLOCKTXN -- is a good target, but I think it's not the best one. More precise would be to look at the time between receiving a compact block announcement till the full block is being relayed (after it is assembled and validated). The block propagation in the network is the sum of these delays. I can imagine approaches -- such as an overly aggressive prefill strategy -- that would improve the "clean block ratio", but worsen the delay time.
I think the delay metric is more accurate and useful than the "clean block ratio", and it may justify some infrastructure effort to support the metric.
I would define the target metric as the interval between when the incoming compact block message is received (start) and the time when the node sends out compact block message for the same block (also start).