Skip to content

p2p: prevent IBD stall after empty headers - #35839

Closed
l0rinc wants to merge 5 commits into
bitcoin:masterfrom
l0rinc:l0rinc/p2p-empty-headers-sync
Closed

l0rinc wants to merge 5 commits into
bitcoin:masterfrom
l0rinc:l0rinc/p2p-empty-headers-sync

Conversation

@l0rinc

@l0rinc l0rinc commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

Draft: seeking design input: This PR changes when a peer gives up the sole initial headers-sync slot. Before merging, I’d like to confirm whether retaining that slot after a valid empty headers response is intentional, or whether another eligible peer should be tried. The existing timeout does not hand off the slot when no other preferred download peer is available; an additional sync attempt also depends on receiving a qualifying new-block announcement.

Problem: While the best header is at least a day old, a node normally selects one peer for initial headers sync. An inbound or manual peer can answer with valid empty headers and remain selected, so another eligible peer is not asked. The peer may simply be caught up with the node or stuck at the same height. Bitcoin Core itself can also return empty headers while its active chain is below minimumchainwork, so an empty response is not misbehavior. This can prevent IBD from progressing when no other preferred download peer is available.

Fix: After such a response from an inbound or manual peer, release its initial-sync slot and cancel its download deadline. Start a new response window so another eligible peer can take the slot before the same peer is selected again. Automatic full-relay and block-relay peers retain their existing timeout and old-chain eviction behavior.

Remaining cases: This does not prevent deliberate stalling. A block announcement can bypass the retry delay, and an already-known connecting header can clear it. Short non-empty responses can also end headers download without releasing the slot. Those cases, timeout handoff without a preferred peer, and early release for automatic outbound peers need separate design discussion.

Manual reproducer

Run these commands before and after the fix. The Python script connects two inbound P2P peers.

{ cmake -B build && cmake --build build -j10 --target bitcoind; } >/dev/null 2>&1
build/bin/bitcoind -regtest -daemonwait -datadir="$(mktemp -d)" -connect=0 -listen=1 -port=18455
time python3 <(curl -fsSL https://gist.github.com/l0rinc/39e471dd6835fe332205d3812ebb9e92/raw)
killall bitcoind

The fixed node returns as soon as the replacement peer receives getheaders.
On the old node, that wait times out after 10 seconds because the initial peer is still treated as active.

Fixes #34096

@DrahtBot DrahtBot added the P2P label Jul 29, 2026
@DrahtBot

DrahtBot commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

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

Code Coverage & Benchmarks

For details see: https://corecheck.dev/bitcoin/bitcoin/pulls/35839.

Reviews

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

Type Reviewers
Concept ACK jeanpablojp, hodlinator

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:

  • #35502 (refactor: extract per-message helpers from ProcessMessage (move-only) by w0xlt)

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.

@l0rinc
l0rinc marked this pull request as draft July 29, 2026 20:58
@l0rinc
l0rinc marked this pull request as ready for review July 29, 2026 21:15
@l0rinc
l0rinc force-pushed the l0rinc/p2p-empty-headers-sync branch from b2c6de0 to ea55ab8 Compare July 29, 2026 21:15
@l0rinc l0rinc closed this Jul 30, 2026
@l0rinc l0rinc reopened this Jul 30, 2026
@maflcko

maflcko commented Jul 30, 2026

Copy link
Copy Markdown
Member

Looks like CI fails on f169af4:

test  2026-07-30T05:28:45.141085Z TestFramework (ERROR): Unexpected exception: 
                                   Traceback (most recent call last):
                                     File "/home/runner/work/bitcoin/bitcoin/test/functional/test_framework/test_framework.py", line 145, in main
                                       self.run_test()
                                     File "/home/runner/work/bitcoin/bitcoin/ci_build/test/functional/p2p_segwit.py", line 261, in run_test
                                       self.test_non_witness_transaction()
                                     File "/home/runner/work/bitcoin/bitcoin/ci_build/test/functional/p2p_segwit.py", line 112, in func_wrapper
                                       func(self, *args, **kwargs)
                                     File "/home/runner/work/bitcoin/bitcoin/ci_build/test/functional/p2p_segwit.py", line 308, in test_non_witness_transaction
                                       self.generate(self.wallet, 99)  # let the block mature
                                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                                     File "/home/runner/work/bitcoin/bitcoin/test/functional/test_framework/test_framework.py", line 662, in generate
                                       sync_fun() if sync_fun else self.sync_all()
                                                                   ^^^^^^^^^^^^^^^
                                     File "/home/runner/work/bitcoin/bitcoin/test/functional/test_framework/test_framework.py", line 743, in sync_all
                                       self.sync_blocks(nodes)
                                     File "/home/runner/work/bitcoin/bitcoin/test/functional/test_framework/test_framework.py", line 714, in sync_blocks
                                       raise AssertionError("Block sync timed out after {}s:{}".format(
                                   AssertionError: Block sync timed out after 60s:
                                     '44c1a1dd2c9cd9b6e27c3236cb82a66ac501e990bc4d84642fa9706b89169839'
                                     '0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206'

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

Could you explain the motivation a bit more - is this a countermeasure against deliberate stalling by malicious peers, or something that is sometimes observed with legit peers or maybe broken peers on mainnet? Or just something that could happen in theory?

@l0rinc
l0rinc force-pushed the l0rinc/p2p-empty-headers-sync branch from ea55ab8 to 6d10e8e Compare July 30, 2026 21:26
@l0rinc

l0rinc commented Jul 30, 2026

Copy link
Copy Markdown
Contributor Author

Looks like CI fails

It seems I split the change into too many parts, and there apparently isn't a simple enough seam here: releasing the peer while leaving the block-announcement retry for later creates a broken intermediate state. I squashed the two commits.

Could you explain the motivation a bit more

I found this while investigating crashes in code paths I’m more familiar with, rather than from a mainnet observation.
My understanding is that an empty headers response is protocol-valid: the peer may be up to date with us or stuck at the same height, so it is not necessarily misbehaving. The second commit adjusted the test explicitly relying on this.
I reproduced the stall locally with the reproducer included in this PR. I assume that translates to mainnet behavior. Updated PR description slightly, let me know if it makes sense.

@davidgumberg

Copy link
Copy Markdown
Contributor

I found this while investigating crashes in code paths I’m more familiar with, rather than from a mainnet observation.

This fixes #34096, isn't that the motivation? (l0rinc#69)

#34096 happens on mainnet and requires the use of addnode, but I don't see why it couldn't work to stall a random new node, but I haven't reproduced this.

@l0rinc

l0rinc commented Aug 4, 2026

Copy link
Copy Markdown
Contributor Author

This fixes #34096, isn't that the motivation

Absolutely, it was in the queue for so long that I forgot about it, thanks for noticing, added it to the PR description.
Can you check if it fixes the problem for you

@danielabrozzoni danielabrozzoni left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Partial review, up to 79aca0b

I am still wrapping my head around the code, I'm not very familiar with it :)

I left a few nits that, imho, make the comments easier to follow, plus one issue that GPT-5.6-sol found. I reviewed it manually and think it’s correct, but I’m not sure whether it’s worth fixing or whether a comment pointing it out would be enough.

self.log.info("Test empty headers response during initial sync")
peer1 = self.nodes[0].add_p2p_connection(P2PInterface())
best_block_hash = int(self.nodes[0].getbestblockhash(), 16)
peer1.wait_for_getheaders(block_hash=best_block_hash)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This wasn’t obvious to me on first read: wait_for_getheaders() removes the matching getheaders entry from last_message. Without knowing this, the assertion below at L96 looked useless, because I assumed it would have been true even if we didn't send any getheaders after receiving the unconnecting header.

Maybe it's worth it to add as a comment:

# wait_for_getheaders() consumes the matching entry from last_message,
# so a later "getheaders" entry represents a newly received request.
peer1.wait_for_getheaders(block_hash=best_block_hash)

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.

Thanks, that sequence is gone now. The rewritten characterization checks peer4.last_message directly, so it no longer depends on wait_for_getheaders() consuming an earlier message.

Comment on lines +97 to +100
peer1.send_and_ping(msg_headers())
unconnecting_header.hashPrevBlock = 2
unconnecting_header.solve()
peer1.send_and_ping(msg_headers([unconnecting_header]))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

nit: it can be made slightly clearer with a comment:

Answer the previous getheaders with an empty response,
then send a different unconnecting header to trigger a new
request

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.

That repeated-empty and unconnecting-header sequence is gone in the rewritten test, so this no longer applies.

Comment thread src/net_processing.cpp Outdated
Comment on lines +3241 to +3242
// A peer that released its slot keeps its request timestamp as a backoff
// instead, so the scheduler does not hand the slot straight back to it.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

nit: This should be in the other if branch

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.

That branch and m_initial_headers_sync_released are gone now. The remaining comment is next to the conditional timestamp clear.

Comment thread src/net_processing.cpp Outdated
// headers cannot be a response to a getheaders request. A connecting response also
// ends any released-slot backoff.
peer.m_last_getheaders_timestamp = {};
peer.m_initial_headers_sync_released = false;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

(Found with gpt 5.6-sol): this means that a peer can send an already-known connecting header and bypass the backoff. Consider this:

  1. Peer P receives the initial getheaders
  2. P sends empty headers and is released with backoff
  3. P sends one already-known header (such as our current best header)
  4. The header connects, so we clear the backoff and the released flag
  5. if no repleacement peer has taken the slot yet, SendMessages() can immediately select P again

If P wants to stall us for as long as possible, and there are other eligible peers, it could:

  1. Receive getheaders
  2. Hold the slot without replying until shortly before m_headers_sync_timeout (~15 minutes)
  3. Send an empty headers, releasing the slot
  4. Send an already known connecting header
  5. If no other peer acquired the slot, acquire the slot, refreshing m_headers_sync_timeout
  6. Repeat

(If there are no other eligble peers, P can stall us indefinitely because we won't disconnect, this is true for master too)

Now, I'm not sure if this is worth fixing or not, because I don't know if there are many ways to stall a peer during header sync, but if we decide not to fix, it should be at least pointed out in a comment

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.

a peer can send an already-known connecting header and bypass the backoff

Good catch, this still applies because connecting headers clear m_last_getheaders_timestamp.
I started implementing this first but it got more complicated than I was comfortable with - we should fix it after this is merged.
Instead I narrowed this PR to #34096's valid empty-response stall because I do not see a small fix for deliberate reacquisition that would not complicate low-work and continuation handling.

Comment thread src/net_processing.cpp Outdated
Comment on lines +3293 to +3308
// headers cannot be a response to a getheaders request.
// headers cannot be a response to a getheaders request. A connecting response also
// ends any released-slot backoff.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

nit: I would change the order of the sentences, so we explain the case where headers connect first, and then when they don't:

// If headers connect, assume that this is in response to any outstanding getheaders
// request we may have sent, and clear out the time of our last request. This will also
// ends any released-slot backoff. Non-connecting
// headers cannot be a response to a getheaders request.

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.

That comment and the released-slot flag are gone in the rewrite, so this no longer applies.

@bitcoin bitcoin deleted a comment from dangervslash Aug 28, 2026
@l0rinc
l0rinc force-pushed the l0rinc/p2p-empty-headers-sync branch from 6d10e8e to f374ee9 Compare August 29, 2026 21:56
@l0rinc l0rinc changed the title p2p: select another peer after empty headers p2p: prevent IBD stall after empty headers Aug 29, 2026

@l0rinc l0rinc left a comment

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.

Thanks for the review, rebased and simplified this a lot in the latest push: we don't have to fix every headers sync problem here, it was getting uncomfortably bloated...

The previous version released every initial headers-sync peer after an empty response. That also stopped automatic outbound old-chain eviction, so it needed a new release flag, helper refactors, broader tests, and 2 follow-up commits to keep eviction active. I reverted that machinery and the outbound-specific tests because they expanded the change beyond #34096. Automatic full-relay and block-relay peers now keep their existing bounded timeout and eviction behavior.

The current change focuses on the indefinite inbound/manual stall. During stale-header IBD, an inbound or manual peer can return valid empty headers while retaining the only sync slot.
The node releases peer1’s initial-sync slot and cancels the download deadline attached to it, allowing another eligible peer to take over. It retains peer1’s recent getheaders timestamp only to prevent the scheduler from immediately assigning the free slot back to the same peer. Another eligible peer can take over, while a later block announcement can still trigger the existing one-shot request.

The first commit removes the block-announcement test’s dependency on empty-header behavior, the second characterizes the stalled replacement peer, and the third changes production behavior and flips that single expectation. Deliberate reacquisition with an already-known header remains separate follow-up work because I did not find a small fix that stayed independent of low-work headers sync.

self.log.info("Test empty headers response during initial sync")
peer1 = self.nodes[0].add_p2p_connection(P2PInterface())
best_block_hash = int(self.nodes[0].getbestblockhash(), 16)
peer1.wait_for_getheaders(block_hash=best_block_hash)

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.

Thanks, that sequence is gone now. The rewritten characterization checks peer4.last_message directly, so it no longer depends on wait_for_getheaders() consuming an earlier message.

Comment on lines +97 to +100
peer1.send_and_ping(msg_headers())
unconnecting_header.hashPrevBlock = 2
unconnecting_header.solve()
peer1.send_and_ping(msg_headers([unconnecting_header]))

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.

That repeated-empty and unconnecting-header sequence is gone in the rewritten test, so this no longer applies.

Comment thread src/net_processing.cpp Outdated
Comment on lines +3241 to +3242
// A peer that released its slot keeps its request timestamp as a backoff
// instead, so the scheduler does not hand the slot straight back to it.

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.

That branch and m_initial_headers_sync_released are gone now. The remaining comment is next to the conditional timestamp clear.

Comment thread src/net_processing.cpp Outdated
// headers cannot be a response to a getheaders request. A connecting response also
// ends any released-slot backoff.
peer.m_last_getheaders_timestamp = {};
peer.m_initial_headers_sync_released = false;

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.

a peer can send an already-known connecting header and bypass the backoff

Good catch, this still applies because connecting headers clear m_last_getheaders_timestamp.
I started implementing this first but it got more complicated than I was comfortable with - we should fix it after this is merged.
Instead I narrowed this PR to #34096's valid empty-response stall because I do not see a small fix for deliberate reacquisition that would not complicate low-work and continuation handling.

Comment thread src/net_processing.cpp Outdated
Comment on lines +3293 to +3308
// headers cannot be a response to a getheaders request.
// headers cannot be a response to a getheaders request. A connecting response also
// ends any released-slot backoff.

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.

That comment and the released-slot flag are gone in the rewrite, so this no longer applies.

@l0rinc l0rinc closed this Aug 29, 2026
@l0rinc l0rinc reopened this Aug 29, 2026

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

If the empty response arrives more than two minutes after the request, the peer is released and takes the slot back in the same SendMessages, with a fresh m_headers_sync_timeout. Answering that way every time keeps every other peer out of the sync and the deadline never fires. The retained timestamp is the request's, not the release's, so the backoff has already expired when the response arrives.

With mocktime advanced 121s before each empty response and another peer available, the merge base disconnects the peer at the deadline and this branch keeps it, eighteen initial getheaders in the log and none to the other peer. Same for manual connections. Is this intentional?

Comment thread src/net_processing.cpp Outdated
if (peer.m_last_getheaders_timestamp != NodeClock::time_point{} && (pfrom.IsInboundConn() || pfrom.IsManualConn())) {
LOCK(cs_main);
if (m_chainman.m_best_header->Time() <= NodeClock::now() - 24h) {
keep_request_timestamp = true;

@jeanpablojp jeanpablojp Aug 31, 2026 •

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.

This is outside the fSyncStarted check, so a peer that isn't holding the slot gets the backoff too, and the reason in the commit message doesn't cover that case. Moving it inside keeps the tests green here. Worth it?

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.

Good catch, even better, we don't need two separate conditions and we can modify m_last_getheaders_timestamp directly (we just have to bump peer.m_last_getheaders_timestamp = {} to the top)

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.

Looks like I forgot to push yesterday, see the latest push

peer3.peer_disconnect()
self.nodes[0].wait_until(lambda: self.nodes[0].num_test_p2p_connections() == 1)

peer1.send_and_ping(msg_headers())

@jeanpablojp jeanpablojp Aug 31, 2026 •

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.

IsManualConn() is the only arm of the guard with no coverage, and removing it breaks no test. addconnection has no manual type, but you can build one with addnode onetry on top of peer_accept_connection.

@l0rinc l0rinc Aug 31, 2026 •

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.

Another good catch, thanks. I added a manual-peer test using addnode onetry on top of peer_accept_connection(), and split the inbound and manual cases into separate characterization/fix pairs. Removing either guard arm now breaks its corresponding test. Added you as coauthor, thanks.

@l0rinc l0rinc left a comment

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.

Rebased after the related lagging-clock headers-sync fix.

Thanks @jeanpablojp, took all your suggestions.
This update starts the retry delay when a peer releases the slot, splits inbound and manual handling into separate characterization/fix pairs, flattens the nested release conditions, and adds delayed manual-peer coverage.

Comment thread src/net_processing.cpp Outdated
if (peer.m_last_getheaders_timestamp != NodeClock::time_point{} && (pfrom.IsInboundConn() || pfrom.IsManualConn())) {
LOCK(cs_main);
if (m_chainman.m_best_header->Time() <= NodeClock::now() - 24h) {
keep_request_timestamp = true;

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.

Good catch, even better, we don't need two separate conditions and we can modify m_last_getheaders_timestamp directly (we just have to bump peer.m_last_getheaders_timestamp = {} to the top)

peer3.peer_disconnect()
self.nodes[0].wait_until(lambda: self.nodes[0].num_test_p2p_connections() == 1)

peer1.send_and_ping(msg_headers())

@l0rinc l0rinc Aug 31, 2026 •

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.

Another good catch, thanks. I added a manual-peer test using addnode onetry on top of peer_accept_connection(), and split the inbound and manual cases into separate characterization/fix pairs. Removing either guard arm now breaks its corresponding test. Added you as coauthor, thanks.

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

Will take some time to fully wrap my brain around this, thanks for at least decreasing the scope already.

assert "getheaders" not in peer2.last_message
assert "getheaders" not in peer3.last_message

self.nodes[0].bumpmocktime(HEADERS_RESPONSE_TIME_SEC + 1)

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.

Could you please add a comment here in the code describing why we bump the mocktime before announcing the block?

Same for the later bump.

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.

I was travelling yesterday, looks like my force push timed out and you were reviewing the previous version - my mistake, added the code comments and the previous restructure

Comment thread src/net_processing.cpp Outdated
// A headers message with no headers cannot be an announcement, so assume
// it is a response to our last getheaders request, if there is one.
peer.m_last_getheaders_timestamp = {};
// Empty headers cannot be an announcement, so clear the request timestamp unless it is retained as a retry delay

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.

nanonit: 80 columns?

Suggested change
// Empty headers cannot be an announcement, so clear the request timestamp unless it is retained as a retry delay
// Empty headers cannot be an announcement, so clear the request
// timestamp unless it is retained as a retry delay.

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.

I prefer the code and especially comments to occupy the space proportional to their usefulness and how often we need them, so I usually try to compress all info on a single line for new comments - if they're really needed.

Comment thread src/net_processing.cpp Outdated
bool keep_request_timestamp{false};
if (peer.m_last_getheaders_timestamp != NodeClock::time_point{} && (pfrom.IsInboundConn() || pfrom.IsManualConn())) {
LOCK(cs_main);
if (m_chainman.m_best_header->Time() <= NodeClock::now() - 24h) {

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.

Could you please add a comment explaining why we check this condition?

"Only keep the header request timestamp for this peer if our local best header is more than 1 day old since [reason not immediately obvious]"

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.

Added, let me know if it helps

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.

thread #35839 (comment):

            // Match the scheduler's one-day threshold and retain the timestamp so this peer cannot immediately retake the sync slot

Still not sure which scheduler this refers to. My best guess is that this is referring to the two 24h thresholds in PeerManagerImpl::SendMessages()?

Long lines in tests as in #35839 (comment) seem more okay. But here we go far beyond the method's established convention of ~80 chars (past 120 too).

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.

Thanks, I’ve replaced the vague and long comment, let me know if it helps

@l0rinc
l0rinc force-pushed the l0rinc/p2p-empty-headers-sync branch 2 times, most recently from ec9fd7e to be1f152 Compare September 1, 2026 17:27

@hodlinator hodlinator 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 be1f152


def test_initial_headers_sync(self):
self.log.info("Test initial headers sync")
self.nodes[0].setmocktime(int(time.time()))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

nit: Could explain why:

Suggested change
self.nodes[0].setmocktime(int(time.time()))
# Take control over time so we can trigger timeouts precisely.
self.nodes[0].setmocktime(int(time.time()))

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.

Added something similar

Comment on lines -78 to -82
# An empty reply will clear the outstanding getheaders request,
# allowing additional getheaders requests to be sent to this peer in
# the future.
peer1.send_without_ping(msg_headers())

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

nit: Could replace this with:

-         # An empty reply will clear the outstanding getheaders request,
-         # allowing additional getheaders requests to be sent to this peer in
-         # the future.
-         peer1.send_without_ping(msg_headers())
- 
+        # Don't answer the getheaders request since we want to time out later.
+

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.

Added something similar, thanks

Comment thread src/net_processing.cpp
peer.m_last_getheaders_timestamp = {};

// Automatic outbound peers already time out or get evicted
if (is_response && (pfrom.IsInboundConn() || pfrom.IsManualConn())) {

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.

remark: In my mind manually added nodes are even more trusted than outbound nodes, which are more trusted than inbound nodes. I guess there could still be some kind of hiccup causing manual nodes to not have all the headers though.

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.

Agreed, but keeping a manual peer selected after an otherwise perfectly valid empty headers response can prevent IBD from progressing. This releases the sync slot without disconnecting or penalizing the peer.

Comment thread src/net_processing.cpp Outdated
bool keep_request_timestamp{false};
if (peer.m_last_getheaders_timestamp != NodeClock::time_point{} && (pfrom.IsInboundConn() || pfrom.IsManualConn())) {
LOCK(cs_main);
if (m_chainman.m_best_header->Time() <= NodeClock::now() - 24h) {

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.

thread #35839 (comment):

            // Match the scheduler's one-day threshold and retain the timestamp so this peer cannot immediately retake the sync slot

Still not sure which scheduler this refers to. My best guess is that this is referring to the two 24h thresholds in PeerManagerImpl::SendMessages()?

Long lines in tests as in #35839 (comment) seem more okay. But here we go far beyond the method's established convention of ~80 chars (past 120 too).

Comment thread src/net_processing.cpp Outdated
const bool is_response{peer.m_last_getheaders_timestamp != NodeClock::time_point{}};
peer.m_last_getheaders_timestamp = {};

// Automatic outbound peers already time out or get evicted

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.

Could you please include a reference to PeerManagerImpl::ConsiderEviction(), where outbound or block relay peers are evicted, either in the comment or the commit message?

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.

Added ConsiderEviction() to the code comment next to the connection-type check. Thanks.

Comment thread src/net_processing.cpp

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.

PR desc:

A new block announcement can still trigger the existing one-shot request.

This sounds like it re-enables the attack somewhat? Could add a note admitting so and that it should be fixed in a later PR.

Could also add a sentence about deferring fixing #35839 (comment) to the PR desc.

Not sure the reproducer script linked in the PR desc adds that much beyond the functional tests. I guess it's nice to have a minimal example. But it feels insecure to encourage download and execution of script source code obscured behind a URL.

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.

Good points. I’ve documented both bypasses as remaining cases for separate discussion. I kept the manual reproducer because it isolates the stall, but I agree the command should let readers inspect the script before running it.

manual_peer.wait_for_getheaders(block_hash=best_block_hash)
assert_equal(node.getpeerinfo()[0]["connection_type"], "manual")

node.bumpmocktime(HEADERS_RESPONSE_TIME_SEC + 1)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I'm confused, is the bumpmocktime really necessary? I think the point is that regardless of timeout, if an inbound/manual sends empty headers, we release the slot. The test seems to pass even if I comment this out

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.

This is meant to catch a possible race where a delayed empty response frees the slot, but the original retry window has expired and the same peer retakes it before the replacement connects. The bump makes that case reproducible. I’ve added a comment to clarify that.

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

Some observations:

  • this is not an attack. Any peer could just send nothing instead of sending an empty header and stall until the timeout hits. So this is more about interactions between honest nodes.
  • Empty header messages are sent by Bitcoin Core itself not only when we have no more headers, but also when the node is below minchainwork. I think this is important information that belongs into the OP.
  • ConsiderEviction is just one of two timeout mechanisms. m_headers_sync_timeout applies to all peers.
  • #34096 is not a permanent stall to my understanding due to m_headers_sync_timeout, see #34096 (comment)
  • Even if the stall was permanent, we'd just sync from another peer as soon as a new block is found, see

    bitcoin/src/net_processing.cpp

    Lines 4413 to 4422 in 0e9018e

    // If we haven't started initial headers-sync with this peer, then
    // consider sending a getheaders now. On initial startup, there's a
    // reliability vs bandwidth tradeoff, where we are only trying to do
    // initial headers sync with one peer at a time, with a long
    // timeout (at which point, if the sync hasn't completed, we will
    // disconnect the peer and then choose another). In the meantime,
    // as new blocks are found, we are willing to add one new peer per
    // block to sync with as well, to sync quicker in the case where
    // our initial peer is unresponsive (but less bandwidth than we'd
    // use if we turned on sync with all peers).
    .

I would say that there are two separate possible problems, none of which are critical:
1.) headerssync can finish early before we get to the today -1 threshold because our peer's chain is not far enough. This could happen due to an empty message or a non-full message, it could happen after or before MinChainWork is reached (so we may have a HeadersSync object or not). In this case, it is strictly unnecessary to wait for the timeout. Instead, we could have a shortcut, in which we release the current sync peer immediately, give it a refractory period, so that we can sync from another peer. But nothing here is specific to inbound/manual peers, plus we might as well not do it and wait ~10 minutes for the next block instead.

2.) When m_headers_sync_timeout hits and we do not have a preferred peer (which means we are in a very bad situation anyway), we do nothing. Instead, we could reset nSyncStarted, and possibly add a refractory period (this is optional in my opinion) so we could try sync from another non-preferred peer (e.g. an inbound).

I'm not sure about the current approach because it

  • unnecessarily adds a restriction to inbound/manual peers to the empty-headers case, when full outbounds would benefit from it just as well. I don't think resettting ConsiderEviction is so important here, we just need headers from someone to start IBD!
  • only addresses one of multiple possible paths in which we can return early from headers sync.

@l0rinc
l0rinc marked this pull request as draft September 22, 2026 22:33
l0rinc and others added 5 commits September 22, 2026 15:48
The block-announcement checks send empty headers only to let the same peer receive another request.
The later fix changes how empty responses affect request timing.

Advance mock time past the normal two-minute response window so the test remains focused on selecting one additional peer per announcement.
During IBD, a delayed empty `headers` response leaves an inbound peer selected for initial headers sync, so an eligible replacement receives no `getheaders` request.

Extend the existing test with this stalled replacement before changing inbound peer handling.
During IBD, an inbound peer can answer the initial `getheaders` request with empty `headers` and retain the only sync slot.
With no preferred download peer available, the headers timeout will not release it.

Release the slot after an empty response while the best header is at least a day old.
Restart the normal response window so an eligible replacement is preferred before the same peer can be selected again.
A new block announcement can still trigger the existing one-shot request.

Automatic outbound peers keep their existing headers timeout and old-chain eviction behavior.

Already-known connecting headers can still end the retry delay, and preventing deliberate slot reacquisition is deferred.
A manual peer can also retain the initial headers-sync slot after a delayed empty `headers` response, so an eligible replacement receives no `getheaders` request.

Add the corresponding stalled-replacement case before extending empty-response handling to manual connections.

Co-authored-by: JP <[email protected]>
After an empty `headers` response, a manual peer can also retain the initial headers-sync slot.
With no other preferred download peer, the timeout does not release it, and automatic outbound eviction does not apply.

Apply the same slot release and retry delay used for inbound peers, allowing another eligible peer to take over.
@l0rinc
l0rinc force-pushed the l0rinc/p2p-empty-headers-sync branch from be1f152 to 45d2f0a Compare September 22, 2026 23:00

@l0rinc l0rinc left a comment

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.

Thanks for the detailed reviews.
I rebased the branch and clarified that empty headers can be a normal response, while #34096 may recover through the timeout or a new-block announcement.
This PR addressed only one case, and since the broader headers-sync behavior change is more complicated than anticipated, I’m closing the PR so someone more familiar with this area can take it forward. @mzumsande / @hodlinator, would any of you be interested?


def test_initial_headers_sync(self):
self.log.info("Test initial headers sync")
self.nodes[0].setmocktime(int(time.time()))

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.

Added something similar

Comment on lines -78 to -82
# An empty reply will clear the outstanding getheaders request,
# allowing additional getheaders requests to be sent to this peer in
# the future.
peer1.send_without_ping(msg_headers())

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.

Added something similar, thanks

Comment thread src/net_processing.cpp Outdated
bool keep_request_timestamp{false};
if (peer.m_last_getheaders_timestamp != NodeClock::time_point{} && (pfrom.IsInboundConn() || pfrom.IsManualConn())) {
LOCK(cs_main);
if (m_chainman.m_best_header->Time() <= NodeClock::now() - 24h) {

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.

Thanks, I’ve replaced the vague and long comment, let me know if it helps

Comment thread src/net_processing.cpp
peer.m_last_getheaders_timestamp = {};

// Automatic outbound peers already time out or get evicted
if (is_response && (pfrom.IsInboundConn() || pfrom.IsManualConn())) {

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.

Agreed, but keeping a manual peer selected after an otherwise perfectly valid empty headers response can prevent IBD from progressing. This releases the sync slot without disconnecting or penalizing the peer.

Comment thread src/net_processing.cpp Outdated
const bool is_response{peer.m_last_getheaders_timestamp != NodeClock::time_point{}};
peer.m_last_getheaders_timestamp = {};

// Automatic outbound peers already time out or get evicted

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.

Added ConsiderEviction() to the code comment next to the connection-type check. Thanks.

Comment thread src/net_processing.cpp

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.

Good points. I’ve documented both bypasses as remaining cases for separate discussion. I kept the manual reproducer because it isolates the stall, but I agree the command should let readers inspect the script before running it.

manual_peer.wait_for_getheaders(block_hash=best_block_hash)
assert_equal(node.getpeerinfo()[0]["connection_type"], "manual")

node.bumpmocktime(HEADERS_RESPONSE_TIME_SEC + 1)

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.

This is meant to catch a possible race where a delayed empty response frees the slot, but the original retry window has expired and the same peer retakes it before the replacement connects. The bump makes that case reproducible. I’ve added a comment to clarify that.

@l0rinc l0rinc closed this Sep 22, 2026
@mzumsande

Copy link
Copy Markdown
Contributor

@mzumsande / @hodlinator, would any of you be interested?

It's not a priority for me right now.

in my opinion, some more analysis with #34096 scenarios would be helpful to decide if the status quo is sufficient or not, i.e. is this a real problem in some practical scenarios, or is the current design with the timeout + extra peer after ~10 minutes on average sufficient?
We could still do a comprehensive fix to reduce the waiting time, but if users don't run into this in practice I'm not sure how important this is, since in any adversarial stalling scenario they the peer will just send nothing instead of empty headers anyway.

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.

IBD stalls if addnode peer is in IBD

8 participants