mirror of
https://github.com/bitcoin/bitcoin
synced 2026-12-04 12:20:38 +00:00
net: preserve anchors when network is disabled #34213
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!34213
Loading…
Reference in a new issue
No description provided.
Delete branch "2026-01-net-anchors-networkactive"
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?
Problem
When a node is shut down while network activity is disabled (e.g. via -networkactive=0 or
setnetworkactivefalse),anchors.datis overwritten with an empty list. This happens becauseStopNodes()collects anchors viaGetCurrentBlockRelayOnlyConns(), which returns nothing when there are no active connections. The node then loses its anchors and cannot reconnect to them on the next startup.Fix
m_anchorswith a mutex, since it is now accessed outside the connection-opening thread.SetNetworkActive(false), save the current block-relay-only connections intom_anchorsbefore the connections are closed, so the anchor list is preserved after the network is deactivated. Stored anchors are kept if there are no suchconnections.
ThreadOpenConnections(), only consume anchors while the network is active; otherwise they would be popped and dropped by the connection attempt.StopNodes(), if the network is inactive andm_anchorsis non-empty, use those stored anchors as the source foranchors.datinstead of the (empty) live connection list.Also, log that "X anchors will be tried for connections" only if the network is active.
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.
🚧 At least one of the CI tasks failed.
Task
lint: https://github.com/bitcoin/bitcoin/actions/runs/20762589891/job/59621113321LLM reason (✨ experimental): Linting failed: ruff detected errors (trailing whitespace) in Python code, causing the CI to fail.
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.
I start some nodes with network inactive.
micro nit (in both cases):
Concept ACK
Have you considered also adding a DumpAnchors() if anchors_to_dump.size() > 1 when setting network active from true to false?
That would persist the anchors for nodes that do a setnetworkactive false and after shut down and skip dumping them again at shutdown.
I'll leave as-is for now.
Yes, but would leave it for a follow-up, it will require more changes than the simple ones to cover the
-networkactivebehavior.ACK 903a37c1e142b4ee6b83fee99735ab69716084ee
Tested,
feature_anchors.pypassesThis seems like a reasonable change, but it may be better to document that setting
fNetworkActiveto false via thesetnetworkactiveRPC can prevent anchors from being preserved.Sounds good, I will add this information in the
setnetworkactiveRPC.Force-pushed addressing https://github.com/bitcoin/bitcoin/pull/34213#pullrequestreview-3636779749
Concept ACK. I think this is a good improvement, makes sense to have, and I can’t find any additional surface of attack introduced here.
To recap, this is how we use anchors at the moment:
I started thinking along the lines of the last bullet point, to see whether the code introduced in this PR could be dangerous in any way, but I couldn’t think of anything. While I couldn’t find a way to exploit the bug this PR is fixing (if an attacker can figure out how to manipulate our bitcoind setting to set
networkactive=0, we likely have bigger problems!), I still think it makes sense to fix this, as it’s low risk, and would avoid unnecessarily losing anchors.However, while reviewing it I started thinking about the anchor logic, and I wonder if we should harden it a bit to make sure that we don’t delete anchors if
networkactiveis not set, but the user is not connected to the internet. I would appreciate feedback from someone who has thought about this area more deeply than me :)At the moment, the PR works as intended if we set
-networkactive=0, but if we simply disconnect the wifi between restarts, Bitcoin Core is still deleting anchors, similarly to master.For example, I tried on my own node:
From the logs, we can see that the node reads the anchors, can’t connect to them, and at the time of flushing to disk, it writes 0 addresses.
The same happens if we start the node, disconnect the wifi, wait for long enough that all the peers are disconnected.
This happens because
fNetworkActiveonly refers to whether-networkactiveis set or not.I think it would be beneficial to fix this edge case, because if an attacker can figure out how to disconnect us from the internet, then we would lose the anchors and be vulnerable to an eclipse attack. Of course, finding a way to disconnect a node from the internet is not an easy task! I suppose an attacker could try with a BGP attack, but I’m not entirely sure.
I haven’t looked into how we would implement this, and I’m not sure it’s entirely doable.
To clarify, I don't think this is exploitable, it is mostly about the own user restarting the node (which happened to me) disabling the network and ending up losing the anchors. Also, since the network is disabled it makes sense to not perform any network activity like this.
still wish anchors would have been persisted if available when network activity is turned off instead just on exit.
edit: shouldn't anchors be loaded at startup even if networkactive is false and maybe just skip saving them if network is inactive?
With this case both loading and saving will be skipped if node is started with network active false
How I see it:
GetCurrentBlockRelayOnlyConns()if populated orm_anchorsif emptyThis seems like a bug... Maybe we should re-save the original anchors if there's no new ones at a clean shutdown? Perhaps update the "original anchors" list just before disabling network activity?
If the user subsequently uses
setnetworkactiveto enable network, should we restore the anchors then?I don't think so. What if these anchors are not available anymore? I mean, we tried to connect to them but they are not available anymore.
Yes, I think so. I will implement it in a follow-up.
ACK a52689837bfa210e4426092e34a5d2c6ea24f351
Ran
feature_anchors.pylocally — passes on both transports.Re the open question about whether anchors should be loaded at startup even with
-networkactive=0: I think skipping the load is correct. Anchors protect against eclipse attacks on restart — if the node starts with the network off, there is no connection activity to eclipse. If the user later callssetnetworkactive true, the node has its addrman for peer diversity. The anchors.dat file stays on disk, so the next clean restart with network active loads them normally.@Bortlesboat, please point your bot to a different repo, this isn't useful...
cc @willcl-ark given #34486.
I think maintaining
m_anchorsas something like:could work? ie update it with the address of current blocks-only connections that have been working, but if there aren't any (or enough) such connections, keep the old addresses.
Would it prevent us to not save addresses that we tried to connect to and didn't work?
Perhaps when disabling the network, we could save the anchors (we're connected to) to
m_anchorsand use it inStopNodesifGetCurrentBlockRelayOnlyConnsdoesn't return any peer.I just changed the approach of this PR and changed PR title and description. It addresses concerns like https://github.com/bitcoin/bitcoin/pull/34213#discussion_r2718514479. Now this PR addresses cases involving disabling network via RPC and starting the node with the network disabled via flag.
cc @danielabrozzoni @luke-jr @ajtowns
Review up to 3aa8484020
Thanks for updating! This is shaping up nicely, I left a couple of comments
In dce37280c3a2cdebf4a97c99b67fba110b2b84f2: I think this commit should be the first one, so in the git history we never access m_anchors from multiple threads without having a mutex.
Same as other comments, you should add a AssertLockNotHeld at the start of ThreadOpenConnections
claude code caught this, but I verified manually and I think it's correct: currently there is a data race, you should first save the anchors, and only then set
fNetworkActive = active, like this:The reason is: right now you set
fNetworkActiveto false, then callGetCurrentBlockRelayOnlyConns(). Between these two steps there is a small window whereThreadSocketHandlermight callDisconnectNodes, which will lockm_nodes_mutexand disconnect all nodes if the network is not active, and clearm_nodes:github.com/bitcoin/bitcoin@58dccd27e1/src/net.cpp (L1923-L1944)GetCurrentBlockRelayOnlyConnsneeds a lock onm_nodes_mutex, so ifDisconnectNodesruns first, it will have already marked all nodes asfDisconnect = trueand removed them fromm_nodes. By the timeGetCurrentBlockRelayOnlyConnsacquires the lock,m_nodesis empty and it returns nothing.Right now m_anchors is used for:
or
The docs of m_anchors should be updated to reflect this.
Also, it would make sense here to append to m_anchors, instead of substituting (and then resizing
m_anchorsso it's not bigger thanMAX_BLOCK_RELAY_ONLY_CONNECTIONS). I think it's a bit cleaner, because we wouldn't lose any information about anchors that were in the file, and we hadn't connected to yet.In this way, point 2 would become:
"keeping track of the anchors we were connected to and were about to connect to when we disable the network"
Right now, this could happen:
anchor1andanchor2, puts them in m_anchorsanchor1fromm_anchorsanchor1tom_anchors,anchor2is forgotten.nit: can be
if(!anchors_to_dump.empty()): even if the network is active, butanchors_to_dumpis empty, you can skip the dumpYou should add a
AssertLockNotHeldat the start of the function, similarly toAssertLockNotHeld(m_reconnections_mutex);In 71d3aa1957d42d79e075c3380b73f3c7bae37f2e: I think this test should be moved in the next commit (a6d411664e967b4fa06c4a6249e492b9185766b9, "test: disabling network activity should not affect anchors").
Both test additions are testing
networkactive=0, this one having-networkactive=0passed in as a bitcoind argument, and the other one callingself.nodes[0].setnetworkactive(False). Can we move these two closer to each other? This way it's clear that we're testing both ways of setting the network to inactive.Done. I think it makes sense to have both tests together.
I've changed the documentation of
m_anchorsaccording to the new behavior - it is now contains addresses saved from previous clean shutdown or when the network was deactivated.Left this as is for now, tried to not change too much. But happy to change it whether I have to touch it again.
Nice find, going to address it.
Thanks, @danielabrozzoni for reviewing. Force-pushed - major changes:
AssertLockNotHeldform_anchors;Rebased
@davidgumberg @stratospher @theuni @vasild you previously expressed interest in looking at this pull request. Are you still interested in the changes?
In
f5ddca1e02Hmmm,
ThreadOpenConnections()still consumesm_anchorswhile networking is disabled. It pops an address before callingOpenNetworkConnection(), which then returns becausefNetworkActiveis false. By shutdown, both the live connections and saved anchors can be empty. The new tests stop the node immediately after disabling networking so it's not visible here.Adding:
makes this test fail here on L61 and on L144
Good catch! You're right, I just pushed a fix for this.
ThreadOpenConnections()now skips the anchor branch entirely while the network is inactive, so anchors are no longer popped and discarded beforeOpenNetworkConnection()gets a chance to reject the attempt.With this, I dropped the !anchors_to_dump.empty() guard in StopNodes() since it isn't needed.
Force-pushed addressing https://github.com/bitcoin/bitcoin/pull/34213#discussion_r3978006683
GetCurrentBlockRelayOnlyConns()returns peers in connection order, whileThreadOpenConnections()consumes anchors from the back.Including a temporary third peer therefore lets it take the oldest anchor’s place after a network toggle. The patch below keeps only the two oldest peers, matching the existing startup and shutdown limit.
Thanks, addressed it in
a74484ctoddf0330.Force-pushed addressing https://github.com/bitcoin/bitcoin/pull/34213#discussion_r3985494910. Also, mutation testing + @willcl-ark's comment made me think in a way of strengthen the anchors' functional test by using mocktime to deterministically exercise
ThreadOpenConnections- I just added a new commit with it.In
41771236b4I guess another execution path here is that we might save only a single anchor and skip any "pending" one. But that seems fine to me as there doesn't seem much value is saving one we didnt' yet make a connection to...
Looks pretty nice to me now, thanks for addressing my comments.
I think the PR description could be updated as it still has:
Done, just updated it.
ACK
ddf033054fDisabling networking should not cause the node to lose its anchors. Preserving them across a clean shutdown lets the node reconnect when networking resumes, increasing eclipse attack resilience on restarts.
tACK
ddf033054fTested changes with 3 scenarios before and after changes.
on master
37c57bc5c2Scenario 0 - Clean stop, with default config
networkactive=1logs
``` 2026-10-01T10:47:13Z DumpAnchors: Flush 2 outbound block-relay-only peer addresses to anchors.dat started 2026-10-01T10:47:13Z DumpAnchors: Flush 2 outbound block-relay-only peer addresses to anchors.dat completed (0.00s) ```scenario 1 - normal start set
./build/bin/bitcoin-cli setnetworkactive falseand stop.An empty anchor list was dumped
logs
scenario 2 - Normal start no anchors dumped nothing to read from previous state
logs
on
ddf033054fscenario 0 - clean stop with default config
networkactive=1logs
scenario 1 - normal start set
bitcoin-cli setnetworkactive falseand stop.2 Anchors dumped to list
logs
scenario 2 - Normal start load anchors from previous state
logs
non-related observation
When network is inactive,
ThreadOpenConnectionskeeps running; in my test, it made 9,000 addrman Select() calls in 68mins, with 0 possible connections. Maybe ThreadOpenConnections should skip its loop body entirely while the network is inactive.Base:
7988380da987c0b860885853ace8149b84ac2ee8Head:
ddf033054ff66129e9307c7c4661ad20e08727fe🟡 Minor
An anchor can be lost when deactivation races its dequeue (src/net.cpp:2859, head)
The anchor eligibility check reads
fNetworkActiveseparately from the dequeue, which holds onlym_anchors_mutex. Ifsetnetworkactive(false)completes after the eligibility check but before the pop, the thread can remove an anchor, then haveOpenNetworkConnectionreject it because networking is inactive. If this was the sole anchor, the inactive shutdown fallback has no address to preserve. When deactivation saves live peers, it publishes the snapshot before setting the inactive flag, so an already-eligible connection pass can also consume and filter those saved addresses. Coordinate anchor removal and the connection attempt with deactivation, or retain an anchor when the attempt is rejected due to inactivity. Another unsynchronized active-state check would leave a similar race.Review coverage was incomplete. The adversarial review had incomplete evidence. The adversarial_glm review had incomplete evidence.
Full review report
ACK
ddf033054fACK
ddf033054f