net: preserve anchors when network is disabled #34213

Manually merged
brunoerg merged 6 commits from 2026-01-net-anchors-networkactive into master 2026-10-02 22:23:14 +00:00 AGit
brunoerg commented 2026-01-06 21:26:09 +00:00 (Migrated from github.com)

Problem

When a node is shut down while network activity is disabled (e.g. via -networkactive=0 or setnetworkactive false), anchors.dat is overwritten with an empty list. This happens because StopNodes() collects anchors via GetCurrentBlockRelayOnlyConns(), 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

  • Guard m_anchors with a mutex, since it is now accessed outside the connection-opening thread.
  • In SetNetworkActive(false), save the current block-relay-only connections into m_anchors before the connections are closed, so the anchor list is preserved after the network is deactivated. Stored anchors are kept if there are no such
    connections.
  • In ThreadOpenConnections(), only consume anchors while the network is active; otherwise they would be popped and dropped by the connection attempt.
  • In StopNodes(), if the network is inactive and m_anchors is non-empty, use those stored anchors as the source for anchors.dat instead of the (empty) live connection list.

Also, log that "X anchors will be tried for connections" only if the network is active.

### Problem When a node is shut down while network activity is disabled (e.g. via -networkactive=0 or `setnetworkactive` false), `anchors.dat` is overwritten with an empty list. This happens because `StopNodes()` collects anchors via `GetCurrentBlockRelayOnlyConns()`, 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 - Guard `m_anchors` with a mutex, since it is now accessed outside the connection-opening thread. - In `SetNetworkActive(false)`, save the current block-relay-only connections into `m_anchors` before the connections are closed, so the anchor list is preserved after the network is deactivated. Stored anchors are kept if there are no such connections. - In `ThreadOpenConnections()`, only consume anchors while the network is active; otherwise they would be popped and dropped by the connection attempt. - In `StopNodes()`, if the network is inactive and `m_anchors` is non-empty, use those stored anchors as the source for `anchors.dat` instead of the (empty) live connection list. Also, log that "X anchors will be tried for connections" only if the network is active.
DrahtBot commented 2026-01-06 21:26:16 +00:00 (Migrated from github.com)

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
ACK willcl-ark, naiyoma, w0xlt, achow101
Concept ACK waketraindev, danielabrozzoni
Stale ACK bensig, Bortlesboat

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:

  • #36397 (scripted-diff: Remove trailing newlines from one-line log messages by maflcko)
  • #36268 (refactor: prune unused semi-colons by fanquake)
  • #34486 (net: Reduce local network activity when networkactive=0 by willcl-ark)

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.

<!--e57a25ab6845829454e8d69fc972939a--> The following sections might be updated with supplementary metadata relevant to reviewers and maintainers. <!--006a51241073e994b41acfe9ec718e94--> ### External sites * Code coverage & benchmarks: https://corecheck.dev/bitcoin/bitcoin/pulls/34213 * Ralph review <img src=https://review.fish.foo/assets/bitcoin/bitcoin/34213.png alt="Ralph review status"> https://git.fish.foo/bitcoin/bitcoin/pulls/34213#author-ralph <!--021abf342d371248e50ceaed478a90ca--> ### Reviews See [the guideline](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#code-review) and [AI policy](https://github.com/bitcoin/bitcoin/blob/master/doc/AI_POLICY.md) for information on the review process. | Type | Reviewers | | ---- | --------- | | ACK | [willcl-ark](https://github.com/bitcoin/bitcoin/pull/34213#pullrequestreview-5208506563), [naiyoma](https://github.com/bitcoin/bitcoin/pull/34213#pullrequestreview-5383273295), [w0xlt](https://github.com/bitcoin/bitcoin/pull/34213#pullrequestreview-5383840629), [achow101](https://github.com/bitcoin/bitcoin/pull/34213#issuecomment-5962212695) | | Concept ACK | [waketraindev](https://github.com/bitcoin/bitcoin/pull/34213#issuecomment-3716823758), [danielabrozzoni](https://github.com/bitcoin/bitcoin/pull/34213#pullrequestreview-3656784193) | | Stale ACK | [bensig](https://github.com/bitcoin/bitcoin/pull/34213#issuecomment-3720228097), [Bortlesboat](https://github.com/bitcoin/bitcoin/pull/34213#issuecomment-4083239706) | If your review is incorrectly listed, please copy-paste <code>&lt;!--meta-tag:bot-skip--&gt;</code> into the comment that the bot should ignore. <!--174a7506f384e20aa4161008e828411d--> ### Conflicts Reviewers, this pull request conflicts with the following ones: * [#36397](https://github.com/bitcoin/bitcoin/pull/36397) (scripted-diff: Remove trailing newlines from one-line log messages by maflcko) * [#36268](https://github.com/bitcoin/bitcoin/pull/36268) (refactor: prune unused semi-colons by fanquake) * [#34486](https://github.com/bitcoin/bitcoin/pull/34486) (net: Reduce local network activity when networkactive=0 by willcl-ark) If you consider this pull request important, please also help to review the conflicting pull requests. Ideally, start with the one that should be merged first. <!--5faf32d7da4f0f540f40219e4f7537a3-->
DrahtBot commented 2026-01-06 21:31:54 +00:00 (Migrated from github.com)

🚧 At least one of the CI tasks failed.
Task lint: https://github.com/bitcoin/bitcoin/actions/runs/20762589891/job/59621113321
LLM 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.

<!--85328a0da195eb286784d51f73fa0af9--> 🚧 At least one of the CI tasks failed. <sub>Task `lint`: https://github.com/bitcoin/bitcoin/actions/runs/20762589891/job/59621113321</sub> <sub>LLM reason (✨ experimental): Linting failed: ruff detected errors (trailing whitespace) in Python code, causing the CI to fail.</sub> <details><summary>Hints</summary> Try to run the tests locally, according to the documentation. However, a CI failure may still happen due to a number of reasons, for example: * Possibly due to a silent merge conflict (the changes in this pull request being incompatible with the current code in the target branch). If so, make sure to rebase on the latest commit of the target branch. * A sanitizer issue, which can only be found by compiling with the sanitizer and running the affected test. * An intermittent issue. Leave a comment here, if you need help tracking down a confusing failure. </details>
waketraindev (Migrated from github.com) reviewed 2026-01-07 00:21:54 +00:00
waketraindev (Migrated from github.com) commented 2026-01-07 00:21:54 +00:00

I start some nodes with network inactive.

micro nit (in both cases):

    if (fNetworkActive && m_use_addrman_outgoing) {
I start some nodes with network inactive. micro nit (in both cases): ```suggestion if (fNetworkActive && m_use_addrman_outgoing) { ```
waketraindev commented 2026-01-07 00:22:37 +00:00 (Migrated from github.com)

Concept ACK

Concept ACK
waketraindev commented 2026-01-07 01:50:48 +00:00 (Migrated from github.com)

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.

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.
brunoerg (Migrated from github.com) reviewed 2026-01-07 18:25:14 +00:00
brunoerg (Migrated from github.com) commented 2026-01-07 18:25:14 +00:00

I'll leave as-is for now.

I'll leave as-is for now.
brunoerg commented 2026-01-07 18:26:58 +00:00 (Migrated from github.com)

Have you considered also adding a DumpAnchors() if anchors_to_dump.size() > 1 when setting network active from true to false?

Yes, but would leave it for a follow-up, it will require more changes than the simple ones to cover the -networkactive behavior.

> Have you considered also adding a DumpAnchors() if anchors_to_dump.size() > 1 when setting network active from true to false? Yes, but would leave it for a follow-up, it will require more changes than the simple ones to cover the `-networkactive` behavior.
bensig commented 2026-01-07 18:40:02 +00:00 (Migrated from github.com)

ACK 903a37c1e142b4ee6b83fee99735ab69716084ee

Tested, feature_anchors.py passes

ACK 903a37c1e142b4ee6b83fee99735ab69716084ee Tested, `feature_anchors.py` passes
w0xlt (Migrated from github.com) reviewed 2026-01-07 20:59:40 +00:00
w0xlt (Migrated from github.com) left a comment

This seems like a reasonable change, but it may be better to document that setting fNetworkActive to false via the setnetworkactive RPC can prevent anchors from being preserved.

This seems like a reasonable change, but it may be better to document that setting `fNetworkActive` to false via the `setnetworkactive` RPC can prevent anchors from being preserved.
brunoerg commented 2026-01-08 19:48:06 +00:00 (Migrated from github.com)

This seems like a reasonable change, but it may be better to document that setting fNetworkActive to false via the setnetworkactive RPC can prevent anchors from being preserved.

Sounds good, I will add this information in the setnetworkactive RPC.

> This seems like a reasonable change, but it may be better to document that setting `fNetworkActive` to false via the `setnetworkactive` RPC can prevent anchors from being preserved. Sounds good, I will add this information in the `setnetworkactive` RPC.
brunoerg commented 2026-01-09 13:07:59 +00:00 (Migrated from github.com)
Force-pushed addressing https://github.com/bitcoin/bitcoin/pull/34213#pullrequestreview-3636779749
danielabrozzoni (Migrated from github.com) reviewed 2026-01-13 16:39:07 +00:00
danielabrozzoni (Migrated from github.com) left a comment

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:

  • Anchors are used to protect from eclipse attacks. When our node cleanly shutdown, it saves our outbound block relay only connections to the anchors.dat file. The attack this is preventing is: if an attacker can manipulate our addrman to make sure that, on restart, we will only connect to the attacker nodes, and we happen to restart our node, the attacker can eclipse us. Anchors protect us because on restart we would connect to some of our previous block relay only peer, and one honest peer is sufficient for us not to become eclipsed.
  • We do not persist anchors if we uncleanly shutdown (power outage, software crash, etc.), because if one of our anchor is malicious and figures out a way to crash our node, and on restart we will reconnect to it, the attacker can keep crashing our node. See: https://github.com/bitcoin/bitcoin/pull/17428#issuecomment-579580035

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 networkactive is 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:

  • Start the node, keep it running until there’s block only connections, shut it down and check that the anchors.dat file is present
  • Disconnect internet
  • Restart the 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.

2026-01-13T11:48:49Z Loaded 2 addresses from "anchors.dat"
2026-01-13T11:48:49Z 2 block-relay-only anchors will be tried for connections.
2026-01-13T11:53:26Z DumpAnchors: Flush 0 outbound block-relay-only peer addresses to anchors.dat started
2026-01-13T11:53:26Z DumpAnchors: Flush 0 outbound block-relay-only peer addresses to anchors.dat completed (0.00s)

The same happens if we start the node, disconnect the wifi, wait for long enough that all the peers are disconnected.

This happens because fNetworkActive only refers to whether -networkactive is 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.

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: - Anchors are used to protect from eclipse attacks. When our node cleanly shutdown, it saves our outbound block relay only connections to the anchors.dat file. The attack this is preventing is: if an attacker can manipulate our addrman to make sure that, on restart, we will only connect to the attacker nodes, and we happen to restart our node, the attacker can eclipse us. Anchors protect us because on restart we would connect to some of our previous block relay only peer, and one honest peer is sufficient for us not to become eclipsed. - We do not persist anchors if we uncleanly shutdown (power outage, software crash, etc.), because if one of our anchor is malicious and figures out a way to crash our node, and on restart we will reconnect to it, the attacker can keep crashing our node. See: https://github.com/bitcoin/bitcoin/pull/17428#issuecomment-579580035 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 `networkactive` is 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: - Start the node, keep it running until there’s block only connections, shut it down and check that the anchors.dat file is present - Disconnect internet - Restart the 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. ``` 2026-01-13T11:48:49Z Loaded 2 addresses from "anchors.dat" 2026-01-13T11:48:49Z 2 block-relay-only anchors will be tried for connections. 2026-01-13T11:53:26Z DumpAnchors: Flush 0 outbound block-relay-only peer addresses to anchors.dat started 2026-01-13T11:53:26Z DumpAnchors: Flush 0 outbound block-relay-only peer addresses to anchors.dat completed (0.00s) ``` The same happens if we start the node, disconnect the wifi, wait for long enough that all the peers are disconnected. This happens because `fNetworkActive` only refers to [whether `-networkactive` is set or not](https://github.com/bitcoin/bitcoin/blob/3c8d389a84d29c7e5532548320228f3e8107969d/src/init.cpp#L1607). 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.
brunoerg commented 2026-01-14 12:27:17 +00:00 (Migrated from github.com)

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.

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.

> 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. 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.
waketraindev (Migrated from github.com) reviewed 2026-01-14 18:32:34 +00:00
waketraindev (Migrated from github.com) left a comment

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

    if (m_use_addrman_outgoing && fNetworkActive) {
        // Load addresses from anchors.dat
        m_anchors = ReadAnchors(gArgs.GetDataDirNet() / ANCHORS_DATABASE_FILENAME);
        if (m_anchors.size() > MAX_BLOCK_RELAY_ONLY_ANCHORS) {
            m_anchors.resize(MAX_BLOCK_RELAY_ONLY_ANCHORS);
        }
        LogInfo("%i block-relay-only anchors will be tried for connections.\n", m_anchors.size());
    }

How I see it:

  • Anchors should be loaded on startup regardless if network activity is disabled (it might be turned on after)
  • Anchors should not be popped back, attempted connection, if network activity is disabled
  • Anchors should be saved on exit from GetCurrentBlockRelayOnlyConns() if populated or m_anchors if empty
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 ```cpp if (m_use_addrman_outgoing && fNetworkActive) { // Load addresses from anchors.dat m_anchors = ReadAnchors(gArgs.GetDataDirNet() / ANCHORS_DATABASE_FILENAME); if (m_anchors.size() > MAX_BLOCK_RELAY_ONLY_ANCHORS) { m_anchors.resize(MAX_BLOCK_RELAY_ONLY_ANCHORS); } LogInfo("%i block-relay-only anchors will be tried for connections.\n", m_anchors.size()); } ``` How I see it: * Anchors should be loaded on startup regardless if network activity is disabled (it might be turned on after) * Anchors should not be popped back, attempted connection, if network activity is disabled * Anchors should be saved on exit from `GetCurrentBlockRelayOnlyConns()` if populated or `m_anchors` if empty
luke-jr (Migrated from github.com) reviewed 2026-01-22 20:26:21 +00:00
luke-jr (Migrated from github.com) commented 2026-01-22 20:26:20 +00:00

This 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?

This 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?
luke-jr (Migrated from github.com) reviewed 2026-01-22 20:27:41 +00:00
luke-jr (Migrated from github.com) commented 2026-01-22 20:27:41 +00:00

If the user subsequently uses setnetworkactive to enable network, should we restore the anchors then?

If the user subsequently uses `setnetworkactive` to enable network, should we restore the anchors then?
brunoerg (Migrated from github.com) reviewed 2026-01-27 12:36:07 +00:00
brunoerg (Migrated from github.com) commented 2026-01-27 12:36:07 +00:00

Maybe we should re-save the original anchors if there's no new ones at a clean shutdown?

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.

> Maybe we should re-save the original anchors if there's no new ones at a clean shutdown? 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.
brunoerg (Migrated from github.com) reviewed 2026-01-27 12:36:21 +00:00
brunoerg (Migrated from github.com) commented 2026-01-27 12:36:21 +00:00

Yes, I think so. I will implement it in a follow-up.

Yes, I think so. I will implement it in a follow-up.
Bortlesboat commented 2026-03-18 15:01:24 +00:00 (Migrated from github.com)

ACK a52689837bfa210e4426092e34a5d2c6ea24f351

Ran feature_anchors.py locally — passes on both transports.

ACK a52689837bfa210e4426092e34a5d2c6ea24f351 Ran `feature_anchors.py` locally — passes on both transports.
Bortlesboat commented 2026-03-18 15:04:10 +00:00 (Migrated from github.com)

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 calls setnetworkactive 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.

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 calls `setnetworkactive 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.
l0rinc commented 2026-03-18 15:07:53 +00:00 (Migrated from github.com)

@Bortlesboat, please point your bot to a different repo, this isn't useful...

@Bortlesboat, please point your bot to a different repo, this isn't useful...
fanquake commented 2026-03-18 15:08:03 +00:00 (Migrated from github.com)

cc @willcl-ark given #34486.

cc @willcl-ark given #34486.
ajtowns (Migrated from github.com) reviewed 2026-03-20 09:52:46 +00:00
ajtowns (Migrated from github.com) commented 2026-03-20 09:52:46 +00:00

I think maintaining m_anchors as something like:

    auto cutoff = now() - 1m;
    vector<CAddress> anchors;
    set<CAddress> old{m_anchors};
    for (const CNode* pnode : m_nodes) {
        if (!pnode->IsBlockOnlyConn()) continue;
        if (!pnode->fSuccessfullyConnected) continue;
        if (pnode->m_connected > cutoff) continue;
        anchors.push_back(pnode->addr);
        old.erase(pnode->addr);
    }
    for (auto& o : old) {
        if (m_nodes.size() >= 2) break;
        anchors.push_back(o);
    }
    m_anchors.swap(anchors);

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.

I think maintaining `m_anchors` as something like: ```c++ auto cutoff = now() - 1m; vector<CAddress> anchors; set<CAddress> old{m_anchors}; for (const CNode* pnode : m_nodes) { if (!pnode->IsBlockOnlyConn()) continue; if (!pnode->fSuccessfullyConnected) continue; if (pnode->m_connected > cutoff) continue; anchors.push_back(pnode->addr); old.erase(pnode->addr); } for (auto& o : old) { if (m_nodes.size() >= 2) break; anchors.push_back(o); } m_anchors.swap(anchors); ``` 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.
brunoerg (Migrated from github.com) reviewed 2026-03-20 18:14:38 +00:00
brunoerg (Migrated from github.com) commented 2026-03-20 18:14:38 +00:00

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_anchors and use it in StopNodes if GetCurrentBlockRelayOnlyConns doesn't return any peer.

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_anchors` and use it in `StopNodes` if `GetCurrentBlockRelayOnlyConns` doesn't return any peer.
brunoerg commented 2026-03-27 14:52:08 +00:00 (Migrated from github.com)

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

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
danielabrozzoni (Migrated from github.com) reviewed 2026-04-10 15:30:27 +00:00
danielabrozzoni (Migrated from github.com) left a comment

Review up to 3aa8484020

Thanks for updating! This is shaping up nicely, I left a couple of comments

Review up to 3aa8484020 Thanks for updating! This is shaping up nicely, I left a couple of comments
danielabrozzoni (Migrated from github.com) commented 2026-04-06 16:12:17 +00:00

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.

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.
danielabrozzoni (Migrated from github.com) commented 2026-04-10 15:29:21 +00:00

Same as other comments, you should add a AssertLockNotHeld at the start of ThreadOpenConnections

Same as other comments, you should add a AssertLockNotHeld at the start of ThreadOpenConnections
danielabrozzoni (Migrated from github.com) commented 2026-04-10 14:06:41 +00:00

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:

if (!active) {
    auto anchors = GetCurrentBlockRelayOnlyConns();
    LOCK(m_anchors_mutex);
    m_anchors = std::move(anchors);
}
fNetworkActive = active;  // flip AFTER capturing

The reason is: right now you set fNetworkActive to false, then call GetCurrentBlockRelayOnlyConns(). Between these two steps there is a small window where ThreadSocketHandler might call DisconnectNodes, which will lock m_nodes_mutex and disconnect all nodes if the network is not active, and clear m_nodes:

github.com/bitcoin/bitcoin@58dccd27e1/src/net.cpp (L1923-L1944)

GetCurrentBlockRelayOnlyConns needs a lock on m_nodes_mutex, so if DisconnectNodes runs first, it will have already marked all nodes as fDisconnect = true and removed them from m_nodes. By the time GetCurrentBlockRelayOnlyConns acquires the lock, m_nodes is empty and it returns nothing.

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: ```cpp if (!active) { auto anchors = GetCurrentBlockRelayOnlyConns(); LOCK(m_anchors_mutex); m_anchors = std::move(anchors); } fNetworkActive = active; // flip AFTER capturing ``` The reason is: right now you set `fNetworkActive` to false, then call `GetCurrentBlockRelayOnlyConns()`. Between these two steps there is a small window where `ThreadSocketHandler` might call `DisconnectNodes`, which will lock `m_nodes_mutex` and disconnect all nodes if the network is not active, and clear `m_nodes`: https://github.com/bitcoin/bitcoin/blob/58dccd27e11de68f810145fc30631a2c446f3bf5/src/net.cpp#L1923-L1944 `GetCurrentBlockRelayOnlyConns` needs a lock on `m_nodes_mutex`, so if `DisconnectNodes` runs first, it will have already marked all nodes as `fDisconnect = true` and removed them from `m_nodes`. By the time `GetCurrentBlockRelayOnlyConns` acquires the lock, `m_nodes` is empty and it returns nothing.
danielabrozzoni (Migrated from github.com) commented 2026-04-10 11:15:39 +00:00

Right now m_anchors is used for:

  1. keeping track of the anchors that were in the file upon startup and we haven't connected to yet
    or
  2. keeping track of the anchors we were connected to when we disable the network

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_anchors so it's not bigger than MAX_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:

  • we start our node, it reads 2 anchors from the file, anchor1 and anchor2, puts them in m_anchors
  • the node starts our first block only connection, pops anchor1 from m_anchors
  • we set network active to 0: this saves anchor1 to m_anchors, anchor2 is forgotten.
Right now m_anchors is used for: 1. keeping track of the anchors that were in the file upon startup and we haven't connected to yet or 2. keeping track of the anchors we were connected to when we disable the network 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_anchors` so it's not bigger than `MAX_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: - we start our node, it reads 2 anchors from the file, `anchor1` and `anchor2`, puts them in m_anchors - the node starts our first block only connection, pops `anchor1` from `m_anchors` - we set network active to 0: this saves `anchor1` to `m_anchors`, `anchor2` is forgotten.
danielabrozzoni (Migrated from github.com) commented 2026-04-10 13:51:47 +00:00

nit: can be if(!anchors_to_dump.empty()): even if the network is active, but anchors_to_dump is empty, you can skip the dump

nit: can be `if(!anchors_to_dump.empty())`: even if the network is active, but `anchors_to_dump` is empty, you can skip the dump
danielabrozzoni (Migrated from github.com) commented 2026-04-10 15:27:37 +00:00

You should add a AssertLockNotHeld at the start of the function, similarly to AssertLockNotHeld(m_reconnections_mutex);

You should add a `AssertLockNotHeld` at the start of the function, similarly to `AssertLockNotHeld(m_reconnections_mutex);`
danielabrozzoni (Migrated from github.com) commented 2026-04-06 16:09:07 +00:00

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=0 passed in as a bitcoind argument, and the other one calling self.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.

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=0` passed in as a bitcoind argument, and the other one calling `self.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.
brunoerg (Migrated from github.com) reviewed 2026-04-13 16:42:36 +00:00
brunoerg (Migrated from github.com) commented 2026-04-13 16:42:36 +00:00

Done. I think it makes sense to have both tests together.

Done. I think it makes sense to have both tests together.
brunoerg (Migrated from github.com) reviewed 2026-04-13 16:45:27 +00:00
brunoerg (Migrated from github.com) commented 2026-04-13 16:45:27 +00:00

I've changed the documentation of m_anchors according to the new behavior - it is now contains addresses saved from previous clean shutdown or when the network was deactivated.

Also, it would make sense here to append to m_anchors, instead of substituting (and then resizing m_anchors so it's not bigger than MAX_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.

Left this as is for now, tried to not change too much. But happy to change it whether I have to touch it again.

I've changed the documentation of `m_anchors` according to the new behavior - it is now contains addresses saved from previous clean shutdown or when the network was deactivated. > Also, it would make sense here to append to m_anchors, instead of substituting (and then resizing m_anchors so it's not bigger than MAX_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. Left this as is for now, tried to not change too much. But happy to change it whether I have to touch it again.
brunoerg (Migrated from github.com) reviewed 2026-04-13 16:45:52 +00:00
brunoerg (Migrated from github.com) commented 2026-04-13 16:45:52 +00:00

Nice find, going to address it.

Nice find, going to address it.
brunoerg commented 2026-04-13 16:54:46 +00:00 (Migrated from github.com)

Thanks, @danielabrozzoni for reviewing. Force-pushed - major changes:

  • Updated m_anchors documentation to reflect the new behavior;
  • Added missing AssertLockNotHeld for m_anchors;
  • Fixed data race when disabling the network and saving the anchors.
Thanks, @danielabrozzoni for reviewing. Force-pushed - major changes: - Updated m_anchors documentation to reflect the new behavior; - Added missing `AssertLockNotHeld` for `m_anchors`; - Fixed data race when disabling the network and saving the anchors.
brunoerg commented 2026-05-05 12:19:08 +00:00 (Migrated from github.com)

Rebased

Rebased
sedited commented 2026-09-09 09:52:38 +00:00 (Migrated from github.com)

@davidgumberg @stratospher @theuni @vasild you previously expressed interest in looking at this pull request. Are you still interested in the changes?

@davidgumberg @stratospher @theuni @vasild you previously expressed interest in looking at this pull request. Are you still interested in the changes?
willcl-ark (Migrated from github.com) reviewed 2026-09-10 10:16:54 +00:00
willcl-ark (Migrated from github.com) commented 2026-09-10 10:16:31 +00:00

In f5ddca1e02

Hmmm, ThreadOpenConnections() still consumes m_anchors while networking is disabled. It pops an address before calling OpenNetworkConnection(), which then returns because fNetworkActive is 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:

import time
time.sleep(2)

makes this test fail here on L61 and on L144

In f5ddca1e0292845c76614b5ce1a3a482bef07c7d Hmmm, `ThreadOpenConnections()` still consumes `m_anchors` while networking is disabled. It pops an address before calling `OpenNetworkConnection()`, which then returns because `fNetworkActive` is 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: ```python import time time.sleep(2) ``` makes this test fail here on L61 and on L144
brunoerg (Migrated from github.com) reviewed 2026-09-11 01:26:27 +00:00
brunoerg (Migrated from github.com) commented 2026-09-11 01:26:27 +00:00

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 before OpenNetworkConnection() gets a chance to reject the attempt.

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 before `OpenNetworkConnection()` gets a chance to reject the attempt.
brunoerg (Migrated from github.com) reviewed 2026-09-11 01:29:04 +00:00
brunoerg (Migrated from github.com) commented 2026-09-11 01:29:04 +00:00

With this, I dropped the !anchors_to_dump.empty() guard in StopNodes() since it isn't needed.

With this, I dropped the !anchors_to_dump.empty() guard in StopNodes() since it isn't needed.
brunoerg commented 2026-09-11 01:29:41 +00:00 (Migrated from github.com)
Force-pushed addressing https://github.com/bitcoin/bitcoin/pull/34213#discussion_r3978006683
w0xlt (Migrated from github.com) reviewed 2026-09-11 02:45:57 +00:00
w0xlt (Migrated from github.com) commented 2026-09-11 02:45:57 +00:00

GetCurrentBlockRelayOnlyConns() returns peers in connection order, while ThreadOpenConnections() consumes anchors from the back.

anchor_addr = m_anchors.back();
m_anchors.pop_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.

diff --git a/src/net.cpp b/src/net.cpp
index f1cc544f4b..039a6df131 100644
--- a/src/net.cpp
+++ b/src/net.cpp
@@ -3418,6 +3418,10 @@ void CConnman::SetNetworkActive(bool active)
         // once the network is re-enabled, or dumped at shutdown. Keep any
         // not-yet-tried anchors if there are no such peers.
         auto anchors = GetCurrentBlockRelayOnlyConns();
+        if (anchors.size() > MAX_BLOCK_RELAY_ONLY_ANCHORS) {
+            // Keep the oldest peers, as when saving anchors at shutdown.
+            anchors.resize(MAX_BLOCK_RELAY_ONLY_ANCHORS);
+        }
         if (!anchors.empty()) {
             LOCK(m_anchors_mutex);
             m_anchors = std::move(anchors);
`GetCurrentBlockRelayOnlyConns()` returns peers in connection order, while `ThreadOpenConnections()` consumes anchors from the back. ```c++ anchor_addr = m_anchors.back(); m_anchors.pop_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. ```diff diff --git a/src/net.cpp b/src/net.cpp index f1cc544f4b..039a6df131 100644 --- a/src/net.cpp +++ b/src/net.cpp @@ -3418,6 +3418,10 @@ void CConnman::SetNetworkActive(bool active) // once the network is re-enabled, or dumped at shutdown. Keep any // not-yet-tried anchors if there are no such peers. auto anchors = GetCurrentBlockRelayOnlyConns(); + if (anchors.size() > MAX_BLOCK_RELAY_ONLY_ANCHORS) { + // Keep the oldest peers, as when saving anchors at shutdown. + anchors.resize(MAX_BLOCK_RELAY_ONLY_ANCHORS); + } if (!anchors.empty()) { LOCK(m_anchors_mutex); m_anchors = std::move(anchors); ```
brunoerg (Migrated from github.com) reviewed 2026-09-11 13:33:19 +00:00
brunoerg (Migrated from github.com) commented 2026-09-11 13:33:19 +00:00

Thanks, addressed it in a74484c to ddf0330.

Thanks, addressed it in a74484c to ddf0330.
brunoerg commented 2026-09-11 13:35:36 +00:00 (Migrated from github.com)

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.

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.
willcl-ark (Migrated from github.com) reviewed 2026-09-14 12:20:06 +00:00
willcl-ark (Migrated from github.com) commented 2026-09-14 12:20:06 +00:00

In 41771236b4

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

In 41771236b4d9903eb9bfb92c7d5073f0e031f177 I 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...
willcl-ark (Migrated from github.com) reviewed 2026-09-14 12:22:21 +00:00
willcl-ark (Migrated from github.com) left a comment

Looks pretty nice to me now, thanks for addressing my comments.

I think the PR description could be updated as it still has:

Also skip DumpAnchors entirely when the network is inactive and there is nothing to write.

Looks pretty nice to me now, thanks for addressing my comments. I think the PR description could be updated as it still has: > Also skip DumpAnchors entirely when the network is inactive and there is nothing to write.
brunoerg commented 2026-09-14 14:19:44 +00:00 (Migrated from github.com)

Looks pretty nice to me now, thanks for addressing my comments.

I think the PR description could be updated as it still has:

Also skip DumpAnchors entirely when the network is inactive and there is nothing to write.

Done, just updated it.

> Looks pretty nice to me now, thanks for addressing my comments. > > I think the PR description could be updated as it still has: > > > Also skip DumpAnchors entirely when the network is inactive and there is nothing to write. Done, just updated it.
willcl-ark (Migrated from github.com) approved these changes 2026-09-15 10:09:36 +00:00
willcl-ark (Migrated from github.com) left a comment

ACK ddf033054f

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

ACK ddf033054ff66129e9307c7c4661ad20e08727fe Disabling 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.
naiyoma (Migrated from github.com) reviewed 2026-10-01 17:51:42 +00:00
naiyoma (Migrated from github.com) left a comment

tACK ddf033054f

Tested changes with 3 scenarios before and after changes.

on master 37c57bc5c2

Scenario 0 - Clean stop, with default config networkactive=1

logs ``` 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 false and stop.

An empty anchor list was dumped

logs
2026-10-01T10:52:38Z Loaded 2 addresses from "anchors.dat"

Made a connection to both.

bitcoin-cli getpeerinfo | jq '[.[] | select(.connection_type=="block-relay-only")] | length'
2

Changed the state to false.

2026-10-01T10:55:00Z SetNetworkActive: false
2026-10-01T10:55:00Z [net] Network not active, disconnecting peer=0, peeraddr=213.152.187.253:22268
2026-10-01T10:55:00Z [net] Network not active, disconnecting peer=1, peeraddr=137.226.34.45:8333

No block relay peers.

bitcoin-cli getpeerinfo | jq '[.[] | select(.connection_type=="block-relay-only")] | length'
0

bitcoin-cli stop

2026-10-01T10:57:39Z DumpAnchors: Flush 0 outbound block-relay-only peer addresses to anchors.dat started
2026-10-01T10:57:39Z DumpAnchors: Flush 0 outbound block-relay-only peer addresses to anchors.dat completed (0.00s)

scenario 2 - Normal start no anchors dumped nothing to read from previous state

logs
2026-10-01T11:02:55Z anchors 0 block-relay-only anchors will be tried for connections.

No anchors to load from.

We make new block-relay-only connections.

on ddf033054f

scenario 0 - clean stop with default config networkactive=1

logs
2026-10-01T12:22:26Z DumpAnchors: Flush 2 outbound block-relay-only peer addresses to anchors.dat started
2026-10-01T12:22:26Z DumpAnchors: Flush 2 outbound block-relay-only peer addresses to anchors.dat completed (0.00s)

scenario 1 - normal start set bitcoin-cli setnetworkactive false and stop.

2 Anchors dumped to list

logs
2026-10-01T12:25:42Z Loaded 2 addresses from "anchors.dat"

Made a connection to both.

bitcoin-cli getpeerinfo | jq '[.[] | select(.connection_type=="block-relay-only")] | length'
2

Changed the state to false.

2026-10-01T12:27:31Z SetNetworkActive: false
2026-10-01T12:27:31Z [net] Network not active, disconnecting peer=0, peeraddr=186.235.86.249:8333
2026-10-01T12:27:31Z [net] Network not active, disconnecting peer=1, peeraddr=76.223.46.29:8333

No block relay peers.

bitcoin-cli getpeerinfo | jq '[.[] | select(.connection_type=="block-relay-only")] | length'
0

./build/bin/bitcoin-cli stop

2026-10-01T12:28:56Z DumpAnchors: Flush 2 outbound block-relay-only peer addresses to anchors.dat started
2026-10-01T12:28:56Z DumpAnchors: Flush 2 outbound block-relay-only peer addresses to anchors.dat completed (0.00s)

scenario 2 - Normal start load anchors from previous state

logs
2026-10-01T12:31:55Z Loaded 2 addresses from "anchors.dat"
2026-10-01T12:31:56Z [net] Trying to make an anchor connection to 76.xx.xx.xx
2026-10-01T12:31:56Z [net] Trying to make an anchor connection to 186.x.x.x

2026-10-01T12:33:49Z DumpAnchors: Flush 2 outbound block-relay-only peer addresses to anchors.dat started
2026-10-01T12:33:49Z DumpAnchors: Flush 2 outbound block-relay-only peer addresses to anchors.dat completed (0.00s)

Restarting with networkactive=0.

2026-10-01T12:42:50Z Loaded 2 addresses from "anchors.dat"
2026-10-01T12:43:20Z DumpAnchors: Flush 2 outbound block-relay-only peer addresses to anchors.dat started
2026-10-01T12:43:20Z DumpAnchors: Flush 2 outbound block-relay-only peer addresses to anchors.dat completed (0.00s)

non-related observation
When network is inactive, ThreadOpenConnections keeps 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.

tACK ddf033054ff66129e9307c7c4661ad20e08727fe Tested changes with 3 scenarios before and after changes. on master 37c57bc5c2979fd3222b14f42ac3341821f5f198 Scenario 0 - Clean stop, with default config `networkactive=1` <details> <summary>logs</summary> ``` 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) ``` </details> scenario 1 - normal start set `./build/bin/bitcoin-cli setnetworkactive false ` and stop. An empty anchor list was dumped <details> <summary>logs</summary> ```text 2026-10-01T10:52:38Z Loaded 2 addresses from "anchors.dat" Made a connection to both. bitcoin-cli getpeerinfo | jq '[.[] | select(.connection_type=="block-relay-only")] | length' 2 Changed the state to false. 2026-10-01T10:55:00Z SetNetworkActive: false 2026-10-01T10:55:00Z [net] Network not active, disconnecting peer=0, peeraddr=213.152.187.253:22268 2026-10-01T10:55:00Z [net] Network not active, disconnecting peer=1, peeraddr=137.226.34.45:8333 No block relay peers. bitcoin-cli getpeerinfo | jq '[.[] | select(.connection_type=="block-relay-only")] | length' 0 bitcoin-cli stop 2026-10-01T10:57:39Z DumpAnchors: Flush 0 outbound block-relay-only peer addresses to anchors.dat started 2026-10-01T10:57:39Z DumpAnchors: Flush 0 outbound block-relay-only peer addresses to anchors.dat completed (0.00s) ``` </details> scenario 2 - Normal start no anchors dumped nothing to read from previous state <details> <summary>logs</summary> ```text 2026-10-01T11:02:55Z anchors 0 block-relay-only anchors will be tried for connections. No anchors to load from. We make new block-relay-only connections. ``` </details> on ddf033054ff66129e9307c7c4661ad20e08727fe scenario 0 - clean stop with default config `networkactive=1` <details> <summary>logs</summary> ```text 2026-10-01T12:22:26Z DumpAnchors: Flush 2 outbound block-relay-only peer addresses to anchors.dat started 2026-10-01T12:22:26Z DumpAnchors: Flush 2 outbound block-relay-only peer addresses to anchors.dat completed (0.00s) ``` </details> scenario 1 - normal start set `bitcoin-cli setnetworkactive false` and stop. 2 Anchors dumped to list <details> <summary>logs</summary> ```text 2026-10-01T12:25:42Z Loaded 2 addresses from "anchors.dat" Made a connection to both. bitcoin-cli getpeerinfo | jq '[.[] | select(.connection_type=="block-relay-only")] | length' 2 Changed the state to false. 2026-10-01T12:27:31Z SetNetworkActive: false 2026-10-01T12:27:31Z [net] Network not active, disconnecting peer=0, peeraddr=186.235.86.249:8333 2026-10-01T12:27:31Z [net] Network not active, disconnecting peer=1, peeraddr=76.223.46.29:8333 No block relay peers. bitcoin-cli getpeerinfo | jq '[.[] | select(.connection_type=="block-relay-only")] | length' 0 ./build/bin/bitcoin-cli stop 2026-10-01T12:28:56Z DumpAnchors: Flush 2 outbound block-relay-only peer addresses to anchors.dat started 2026-10-01T12:28:56Z DumpAnchors: Flush 2 outbound block-relay-only peer addresses to anchors.dat completed (0.00s) ``` </details> scenario 2 - Normal start load anchors from previous state <details> <summary>logs</summary> ```text 2026-10-01T12:31:55Z Loaded 2 addresses from "anchors.dat" 2026-10-01T12:31:56Z [net] Trying to make an anchor connection to 76.xx.xx.xx 2026-10-01T12:31:56Z [net] Trying to make an anchor connection to 186.x.x.x 2026-10-01T12:33:49Z DumpAnchors: Flush 2 outbound block-relay-only peer addresses to anchors.dat started 2026-10-01T12:33:49Z DumpAnchors: Flush 2 outbound block-relay-only peer addresses to anchors.dat completed (0.00s) Restarting with networkactive=0. 2026-10-01T12:42:50Z Loaded 2 addresses from "anchors.dat" 2026-10-01T12:43:20Z DumpAnchors: Flush 2 outbound block-relay-only peer addresses to anchors.dat started 2026-10-01T12:43:20Z DumpAnchors: Flush 2 outbound block-relay-only peer addresses to anchors.dat completed (0.00s) ``` </details> non-related observation When network is inactive, `ThreadOpenConnections` keeps 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.
First-time contributor

Base: 7988380da987c0b860885853ace8149b84ac2ee8
Head: ddf033054ff66129e9307c7c4661ad20e08727fe

🟡 Minor

An anchor can be lost when deactivation races its dequeue (src/net.cpp:2859, head)

The anchor eligibility check reads fNetworkActive separately from the dequeue, which holds only m_anchors_mutex. If setnetworkactive(false) completes after the eligibility check but before the pop, the thread can remove an anchor, then have OpenNetworkConnection reject 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

<!-- forgejo-review-bot:bitcoin/bitcoin --> Base: `7988380da987c0b860885853ace8149b84ac2ee8` Head: `ddf033054ff66129e9307c7c4661ad20e08727fe` ##### 🟡 Minor **An anchor can be lost when deactivation races its dequeue** (src/net.cpp:2859, head) The anchor eligibility check reads `fNetworkActive` separately from the dequeue, which holds only `m_anchors_mutex`. If `setnetworkactive(false)` completes after the eligibility check but before the pop, the thread can remove an anchor, then have `OpenNetworkConnection` reject 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](<https://review.fish.foo/traces/34213-ddf033054ff66129e9307c7c4661ad20e08727fe-200-1.html>)
w0xlt (Migrated from github.com) reviewed 2026-10-01 18:37:30 +00:00
w0xlt (Migrated from github.com) left a comment
ACK ddf033054ff66129e9307c7c4661ad20e08727fe
achow101 commented 2026-10-02 22:05:25 +00:00 (Migrated from github.com)
ACK ddf033054ff66129e9307c7c4661ad20e08727fe
Sign in to join this conversation.
No reviewers
No milestone
No project
No assignees
2 participants
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
bitcoin/bitcoin!34213
No description provided.