Repository navigation
net: Reduce local network activity when networkactive=0 - #34486
willcl-ark wants to merge 6 commits into
Conversation
|
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. 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. |
|
The following sections might be updated with supplementary metadata relevant to reviewers and maintainers. Code Coverage & BenchmarksFor details see: https://corecheck.dev/bitcoin/bitcoin/pulls/34486. ReviewsSee the guideline and AI policy for information on the review process.
If your review is incorrectly listed, please copy-paste ConflictsReviewers, 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. |
|
Concept ACK |
bradleystachurski
left a comment
There was a problem hiding this comment.
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();
}35da4e0 to
745aed3
Compare
|
Thanks @bradleystachurski that's a nice suggestion which I've taken in 745aed37224102888332823aadc6d766e701aa0b I also reworked the |
|
Concept ACK |
|
I will address the LLM linter suggestion if I push again. |
|
Tested this on my Pi 5 (ARM64, Debian Bookworm). Builds clean, all the networking-related tests pass: Had to clear my Concept ACK |
|
Concept ACK |
brunoerg
left a comment
There was a problem hiding this comment.
tested up to 396b56af0ac261863b076ab8d2d02a99f6e03f3a: I checked that portmap activity follows network activity.
|
Drafting this to rework/rebase on #34158, and not undo libevent removal. |
a749a98 to
804cb1a
Compare
804cb1a to
98ddbb6
Compare
| if (!m_network_active) { | ||
| continue; | ||
| } |
There was a problem hiding this comment.
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 ?
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]>
48f1321 to
249da15
Compare
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.
249da15 to
799116c
Compare
|
🚧 At least one of the CI tasks failed. HintsTry to run the tests locally, according to the documentation. However, a CI failure may still
Leave a comment here, if you need help tracking down a confusing failure. |
|
Force-pushed after rebasing and outstanding feedback addressed:
During self-review, I found that multiple concurrent network toggles could race Without that commit, concurrent updates could leave the state inconsistent with |
fjahr
left a comment
There was a problem hiding this comment.
Concept ACK (somehow this wasn't on my radar until now)
| } | ||
|
|
||
| void StartMapPort(bool enable) | ||
| void EnableMapPort(bool enable) |
There was a problem hiding this comment.
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 | |||
There was a problem hiding this comment.
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") |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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:
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"], |
There was a problem hiding this comment.
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"]) |
There was a problem hiding this comment.
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=[ |
There was a problem hiding this comment.
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"]): |
There was a problem hiding this comment.
These assert_debug_log on setnetworkactive are not helpful since the log is printed unconditionally even if the status change fails:
Line 3457 in ed7dd7c
| "-networkactive=0", | ||
| "-debug=tor", | ||
| ]) | ||
| with tx_originator.assert_debug_log(expected_msgs=[ |
There was a problem hiding this comment.
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?
|
|
||
| void EnableMapPort(bool enable) | ||
| { | ||
| LOCK(g_mapport_mutex); |
There was a problem hiding this comment.
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!
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 :) |
|
🐙 This pull request conflicts with the target branch and needs rebase. |
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:
EnableMapPortis injected as a callback via CConnman::Options. SetNetworkActive and SetMapPortEnabled both gate on network state.torcontrol:
TorControlleris 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.