Skip to content

net: Reduce local network activity when networkactive=0 - #34486

Draft
willcl-ark wants to merge 6 commits into
bitcoin:masterfrom
willcl-ark:respect-networkactive
Draft

willcl-ark wants to merge 6 commits into
bitcoin:masterfrom
willcl-ark:respect-networkactive

Conversation

@willcl-ark

@willcl-ark willcl-ark commented Feb 2, 2026 •

Copy link
Copy Markdown
Member

Fixes #34190

When networkactive=0 is set, NAT-PMP port mapping and Tor control connections still run in the background, mapping ports and logging retry attempts despite the node being "inactive."

This wires both subsystems to CConnman::SetNetworkActive so they start and stop with the network state:

  • mapport: EnableMapPort is injected as a callback via CConnman::Options. SetNetworkActive and SetMapPortEnabled both gate on network state.

  • torcontrol: TorController is injected similarly through a CConnman::Options callback. The controller thread stays alive while networkactive=0, but idles without connecting or reconnecting to the Tor control port. Re-enabling the network wakes the controller promptly and resets reconnect backoff.

@DrahtBot DrahtBot added the P2P label Feb 2, 2026
@willcl-ark

willcl-ark commented Feb 2, 2026 •

Copy link
Copy Markdown
Member Author

This is an alternative to #34467. The key difference is that #34467 gates mapport and tor control at init time with if (networkactive) guards, which means those subsystems are permanently disabled for the lifetime of the process. setnetworkactive true via RPC won't start them. Boot-time and runtime behavior would now differ.

This PR instead wires both subsystems into CConnman::SetNetworkActive so they follow the network state through the full lifecycle: starting with -networkactive=0 and later calling setnetworkactive true works as expected.

I'm unsure how this will conflict with the work currently being done to remove libevent.

@DrahtBot

DrahtBot commented Feb 2, 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/34486.

Reviews

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

Type Reviewers
Concept ACK sedited, fanquake, Jhackman2019, fjahr
Approach ACK winterrdog
Stale ACK brunoerg

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:

  • #36374 (torcontrol: escape backslashes in -torpassword by 0xShadowX)
  • #36268 (refactor: prune unused semi-colons by fanquake)
  • #36170 (net: require a dedicated bind for automatic Tor by l0rinc)
  • #36142 (net: validate Tor onion service replies and cached keys by l0rinc)
  • #35888 (net: reject oversized outbound messages by l0rinc)
  • #35292 (test: Add coverage for Tor control HASHEDPASSWORD authentication by winterrdog)
  • #34534 (rpc: Manual prune lock management (Take 2) by fjahr)
  • #34213 (net: preserve anchors when network is disabled by brunoerg)
  • #31260 (scripted-diff: Type-safe settings retrieval by ryanofsky)
  • #30951 (net: option to disallow v1 connection on ipv4 and ipv6 peers by stratospher)

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.

@sedited

sedited commented Feb 2, 2026

Copy link
Copy Markdown
Contributor

Concept ACK

@bradleystachurski bradleystachurski left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Reviewed 35da4e03b18b7ef5eb23e1b038f5755fe37825a1

Tested on Linux: started with -networkactive=0 -natpmp=1 -debug=net -debug=tor, confirmed no portmap/tor activity at startup, toggled via setnetworkactive, confirmed mapport thread start/stop and tor connection attempts follow network state.

Verified feature_mapport.py fails when the m_mapport callback is removed from SetNetworkActive.

nit: TorController::SetNetworkActive doesn't reset reconnect_timeout, so re-enabling network after backoff has grown continues from the stale value. Verified this fixes it:

diff --git a/src/torcontrol.cpp b/src/torcontrol.cpp
index d5aeb55a72..934499d72b 100644
--- a/src/torcontrol.cpp
+++ b/src/torcontrol.cpp
@@ -677,6 +677,8 @@ void TorController::SetNetworkActive(bool set_active)
         // Disconnect if currently connected
         conn.Disconnect();
     }
+    // Reset backoff when re-enabling network
+    reconnect_timeout = RECONNECT_TIMEOUT_START;
     // Connect handles both cases: connects if active, reschedules if inactive
     Connect();
 }

@willcl-ark
willcl-ark force-pushed the respect-networkactive branch from 35da4e0 to 745aed3 Compare February 3, 2026 09:26
@willcl-ark

Copy link
Copy Markdown
Member Author

Thanks @bradleystachurski that's a nice suggestion which I've taken in 745aed37224102888332823aadc6d766e701aa0b

I also reworked the if logic slightly to make the flow of this function clearer (and not always call Connect()).

@fanquake

fanquake commented Feb 3, 2026

Copy link
Copy Markdown
Member

Concept ACK

@willcl-ark

Copy link
Copy Markdown
Member Author

I will address the LLM linter suggestion if I push again.

@Jhackman2019

Jhackman2019 commented Feb 7, 2026 •

Copy link
Copy Markdown

Tested this on my Pi 5 (ARM64, Debian Bookworm). Builds clean, all the networking-related tests pass:

feature_mapport.py                  PASSED
feature_proxy.py                    PASSED
p2p_addr_relay.py                   PASSED
p2p_disconnect_ban.py --v1transport PASSED
p2p_disconnect_ban.py --v2transport PASSED
p2p_dns_seeds.py                    PASSED

Had to clear my test/cache first since I had a stale cache from an autotools build — after that everything was smooth.

Concept ACK

@brunoerg

Copy link
Copy Markdown
Contributor

Concept ACK

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

tested up to 396b56af0ac261863b076ab8d2d02a99f6e03f3a: I checked that portmap activity follows network activity.

Comment thread src/torcontrol.cpp Resolved
@willcl-ark

Copy link
Copy Markdown
Member Author

Drafting this to rework/rebase on #34158, and not undo libevent removal.

@fanquake fanquake closed this Aug 17, 2026
@fanquake fanquake reopened this Aug 17, 2026

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

approach ACK 48f1321

Comment thread src/torcontrol.cpp Outdated
Comment on lines +452 to +454
if (!m_network_active) {
continue;
}

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.

premise: backoff keeps growing after a quick off/on during sleep

there is a subtle gap in how ThreadControl handles backoff timeouts during rapid state toggles i.e. something that could happen when automated scripts or tests issue setnetworkactive false followed immediately by setnetworkactive true

if the node is currently in a backoff sleep (say, waiting 30 seconds after several failed Tor connection attempts) and a script toggles the network off and back on within that single sleep window, SleepWithNetworkPolling wakes up early due to the change count. however, because the script already flipped network activity back to true, the live if (!m_network_active) check evaluates to false. execution then falls through directly into growing the backoff delay (m_reconnect_timeout *= RECONNECT_TIMEOUT_EXP), punishing the node with a longer reconnect delay instead of resetting it back to 1.0s despite a fresh reactivation occurring

the test below reproduces this by doing the off/on calls back-to-back while the node is inside a reconnect sleep. the next retry incorrectly gets the grown delay (1.5s) instead of starting again at 1.0s:

diff
diff --git a/test/functional/feature_torcontrol.py b/test/functional/feature_torcontrol.py
index 7a6fc4e6c0..053fc65b3f 100755
--- a/test/functional/feature_torcontrol.py
+++ b/test/functional/feature_torcontrol.py
@@ -313,6 +313,40 @@ class TorControlTest(BitcoinTestFramework):
         ], timeout=2):
             node.setnetworkactive(state=True)
 
+    def test_networkactive_race_during_backoff(self):
+        self.log.info("Test that a rapid off->on cycle during a reconnect backoff sleep still resets the backoff")
+
+        node = self.nodes[0]
+
+        # nothing listens on 127.0.0.1:1, so every connection attempt fails
+        # immediately thus the retry/backoff cycle is predictable: the first
+        # retry is always logged at RECONNECT_TIMEOUT_START (1.0s)
+        with node.assert_debug_log(expected_msgs=["Retrying in 1.0 seconds"], timeout=10):
+            self.restart_node(0, extra_args=[
+                "-torcontrol=127.0.0.1:1",
+                "-listenonion=1",
+                "-debug=tor",
+            ])
+
+        # we are now inside that first ~1.0s backoff sleep. toggle the network
+        # off then immediately back on, as quick as possible, so the whole
+        # round trip lands inside this single sleep window rather than
+        # spanning two separate ThreadControl loop iterations
+        node.setnetworkactive(state=False)
+        node.setnetworkactive(state=True)
+
+        # a reactivation should always reset the backoff to
+        # RECONNECT_TIMEOUT_START, regardless of whether the deactivate/
+        # reactivate pair happened between loop iterations or inside one
+        # backoff sleep. so the *next* retry should again log 1.0s, not a
+        # grown value (i.e. 1.5s) carried over from before the toggle
+        with node.assert_debug_log(
+            expected_msgs=["Retrying in 1.0 seconds"],
+            unexpected_msgs=["Retrying in 1.5 seconds"],
+            timeout=3,
+        ):
+            pass
+
     def run_test(self):
         self.test_basic()
         self.test_partial_data()
@@ -321,6 +355,7 @@ class TorControlTest(BitcoinTestFramework):
         self.test_overmany_lines()
         self.test_networkactive()
         self.test_networkactive_reactivation_resets_backoff()
+        self.test_networkactive_race_during_backoff()
 
 
 if __name__ == '__main__':

potential fix

the fix is to check whether the network-active change count changed during the sleep itself. if it did and the network is active again, treat that as a fresh reactivation & reset the backoff:

diff
diff --git a/src/torcontrol.cpp b/src/torcontrol.cpp
index dfded42746..5cfaaad515 100644
--- a/src/torcontrol.cpp
+++ b/src/torcontrol.cpp
@@ -447,11 +447,14 @@ void TorController::ThreadControl()
                 LogDebug(BCLog::TOR, "Retrying in %.1f seconds", m_reconnect_timeout.count());
                 const auto change_count{m_network_active_change_count.load()};
                 if (!SleepWithNetworkPolling(std::chrono::duration_cast<std::chrono::milliseconds>(m_reconnect_timeout), change_count) && m_interrupt) {
                     break;
                 }
-                if (!m_network_active) {
+                if (change_count != m_network_active_change_count.load()) {
+                    if (m_network_active) {
+                        m_reconnect_timeout = RECONNECT_TIMEOUT_START;
+                    }
                     continue;
                 }
                 m_reconnect_timeout = std::min(m_reconnect_timeout * RECONNECT_TIMEOUT_EXP, RECONNECT_TIMEOUT_MAX);
                 continue;
             }

Note

this gap will not crash the node. it quietly increases the delay before Tor Control reconnects, which can be annoying and surprising, but it is not dangerous. if it happens repeatedly, the delay can compound noticeably, but the node will eventually reconnect once the delay elapses

thoughts ?

willcl-ark and others added 5 commits September 21, 2026 10:29
When -networkactive=0 is set, NAT-PMP port mapping was still running and
attempting gateway queries. Move mapport lifecycle management into
CConnman, which already owns SetNetworkActive, so it can control mapport
based on both the -natpmp setting and network state.

EnableMapPort is injected as a callback via CConnman::Options to avoid a
circular dependency between net and mapport.
Add functional test to verify that PCP/NAT-PMP port mapping respects the
networkactive state:

- Does not run when started with -networkactive=0
- Starts when network is activated via setnetworkactive RPC
- Stops when network is deactivated
- Resumes when network is reactivated
Have CConnman propagate networkactive changes to the node-owned
TorController so it can idle without connecting or reconnecting while
networking is disabled.

Track activity changes during reconnect sleeps so even a rapid off/on
cycle resets an already-grown backoff when the controller resumes.
Exercise disabled startup, activation, and control-connection shutdown so
networkactive cannot silently regress to affecting P2P connections alone.
Check that reactivation also resets an already-grown reconnect backoff.

Clear the mock server's connection handle on close so the disconnect
assertion observes the completed connection teardown.
Verify that the tor controller attempts reconnection to the control port
by asserting the retry log message when started with an unreachable
`-torcontrol` address.

Co-authored-by: brunoerg <[email protected]>
@willcl-ark
willcl-ark force-pushed the respect-networkactive branch from 48f1321 to 249da15 Compare September 21, 2026 10:02
RPC callers can toggle networking concurrently with each other and with
GUI port-mapping preferences. Keep each state change and its subsystem
callbacks together so the final Tor and mapport states cannot disagree
with CConnman.

Protect the global mapport thread separately because shutdown accesses it
directly. Interrupt before joining on every stop, including when a runtime
restart occurs between shutdown's interrupt and stop calls.

Exercise concurrent network and preference updates, checking that the
callbacks do not overlap and that disabled mapping remains disabled.
@DrahtBot

Copy link
Copy Markdown
Contributor

🚧 At least one of the CI tasks failed.
Task macOS-cross to arm64: https://github.com/bitcoin/bitcoin/actions/runs/35586599554/job/106291273996
LLM reason (✨ experimental): CI failed due to a Clang -Wthread-safety-analysis error treated as -Werror in src/mapport.cpp (misused mutex g_mapport_mutex).

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.

@willcl-ark

Copy link
Copy Markdown
Member Author

Force-pushed after rebasing and outstanding feedback addressed:

  • Tor reconnects now use the updated backoff path while continuing to respect networkactive.
  • Replaced the post-sleep networkactive check with the network-change counter, so rapid off/on toggles reset an already-grown reconnect delay. The regression test now starts from a 3.38-second delay.
  • Updated the private-broadcast test for the new Tor retry log message from the rebase.

During self-review, I found that multiple concurrent network toggles could race mapport start/stop operations and apply the Tor/mapport callbacks out of order. I added a final commit to serialize those, and protect the mapport thread separately, since shutdown accesses it directly.

Without that commit, concurrent updates could leave the state inconsistent with CConnman, for example with networkactive=false while the Tor control or mapport callback from a competing update had taken effect.

@fjahr fjahr 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 (somehow this wasn't on my radar until now)

Comment thread src/mapport.cpp
}

void StartMapPort(bool enable)
void EnableMapPort(bool enable)

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: Is this rename really needed? I don't find the new name clearer and given the bool parameter I would have chosen something like SetMapPortActive(bool) or maybe SwitchMapPort(bool) but it could also stay as it was.

@@ -0,0 +1,52 @@
#!/usr/bin/env python3
# Copyright (c) 2026-present The Bitcoin Core developers

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: Copyright (c) The Bitcoin Core developers

assert_equal(node.getnetworkinfo()["networkactive"], False)
time.sleep(2)

self.log.info("Test that mapport starts when network is activated")

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.

Hm, this sends the real requests to the local router, right? This was kind of unexpected for me. I am not sure if we should add this or maybe rather avoid it and rely on unit tests for anything other than the negative test above.

):
self.restart_node(0, extra_args=["-natpmp=1", "-networkactive=0", "-debug=net"])
assert_equal(node.getnetworkinfo()["networkactive"], False)
time.sleep(2)

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.

I would rather like to avoid the sleeps here and below. I think a good way to handle this better is to give the assert_debug_log an expected_msgs that we know will have to come after the unexpected_msgs have appeared. This pattern is also used here for example:

# The expected_msg must be something we are confident will be logged after the unexpected_msg

Should also make the test finish quicker hopefully.

# sleep, after the backoff has already grown.
with node.assert_debug_log(
expected_msgs=["retrying in 1.00 s"],
unexpected_msgs=["retrying in 3.38 s"],

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 should check for the next backoff steps rather than 3.38s since that must have already passed due to the assert above.

with node.assert_debug_log(expected_msgs=["SetNetworkActive: false\n"]):
node.setnetworkactive(state=False)

ensure_for(duration=2, f=lambda: not node.getnetworkinfo()["networkactive"])

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.

I don't understand the purpose of this ensure_for, why would the status change if nothing otherwise happens? This would be a pretty wild regression at a level that we usually don't test for and if we did I think this would at least need a comment.

mock_tor = MockTorControlServer(tor_port)
mock_tor.start()

self.restart_node(0, extra_args=[

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 use restart_with_mock here if you extend it to allow for adding extra_args


ensure_for(duration=2, f=lambda: len(mock_tor.received_commands) == 0)

with self.nodes[0].assert_debug_log(expected_msgs=["SetNetworkActive: true\n"]):

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.

These assert_debug_log on setnetworkactive are not helpful since the log is printed unconditionally even if the status change fails:

LogInfo("%s: %s\n", __func__, active);

"-networkactive=0",
"-debug=tor",
])
with tx_originator.assert_debug_log(expected_msgs=[

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.

I'm not loving that this adds this unrelated check to the private broadcast test. Even if this means adding more code I think this should go in the torcontrol test. And it seems to me like test_reconnect_backoff already covers this there?

Comment thread src/mapport.cpp

void EnableMapPort(bool enable)
{
LOCK(g_mapport_mutex);

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.

I think the implementation changes in 799116c should have been in the related earlier commits. I think the commits don't grow too large because of this and introducing problematic code in one commit and then fixing it in a later one isn't great for review. No problem with keeping the unit test in a separate commit though!

@willcl-ark

Copy link
Copy Markdown
Member Author

Concept ACK (somehow this wasn't on my radar until now)

Thanks for the review. Most of these suggestions look pretty sensible to me on first glance, but will take me a little time to go through them all thoroughly and update here :)

@DrahtBot

DrahtBot commented Oct 2, 2026

Copy link
Copy Markdown
Contributor

🐙 This pull request conflicts with the target branch and needs rebase.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

bitcoind shouldn't perform network activity if the option networkactive=0, e.g. [addrman] Selected IP:PORT from tried

9 participants