fix: uptime RPC returns 0 on first call
What changed, and why it matters
This commit fixes a minor bug in the `uptime` RPC command. Previously, the very first call to `uptime` would always report 0 seconds because the program's start time was accidentally recorded at the moment of that first call, not at actual startup. The fix moves the startup timestamp to a global variable that is set when the program begins. This is a correctness fix with no security impact.
No security action required. This is a routine bug fix; apply as part of normal maintenance if desired.
Security signals we found
No strong security signals were identified.
Evidence from the diff
The patch moves g_startup_time from a function-local static inside GetUptime() to an anonymous namespace scope in src/common/system.cpp. A function-local static is initialized on first execution of the function, so the first uptime() RPC call captured the current time and returned a duration of zero. By placing the variable at namespace scope, it is initialized during static initialization before main(), so GetUptime() returns the true elapsed time from process start on every call. The functional test was updated to sleep briefly and assert the first uptime value is greater than zero.
Changed components
src/common/system.cpptest/functional/rpc_uptime.pyInspect captured patch +9 / −6
diff --git a/src/common/system.cpp b/src/common/system.cpp
index 98bc0147..08c0c692 100644
--- a/src/common/system.cpp
+++ b/src/common/system.cpp
@@ -127,8 +127,8 @@ std::optional<size_t> GetTotalRAM()
return std::nullopt;
}
-SteadyClock::duration GetUptime()
-{
- static const auto g_startup_time{SteadyClock::now()};
- return SteadyClock::now() - g_startup_time;
-}
+namespace {
+ const auto g_startup_time{SteadyClock::now()};
+} // namespace
+
+SteadyClock::duration GetUptime() { return SteadyClock::now() - g_startup_time; }
diff --git a/test/functional/rpc_uptime.py b/test/functional/rpc_uptime.py
index 817ba2b4..48256e2f 100755
--- a/test/functional/rpc_uptime.py
+++ b/test/functional/rpc_uptime.py
@@ -26,8 +26,11 @@ class UptimeTest(BitcoinTestFramework):
assert_raises_rpc_error(-8, "Mocktime must be in the range [0, 9223372036], not -1.", self.nodes[0].setmocktime, -1)
def _test_uptime(self):
- wait_time = 20_000
+ time.sleep(1) # Do some work before checking uptime
uptime_before = self.nodes[0].uptime()
+ assert uptime_before > 0, "uptime should begin at app start"
+
+ wait_time = 20_000
self.nodes[0].setmocktime(int(time.time()) + wait_time)
uptime_after = self.nodes[0].uptime()
self.nodes[0].setmocktime(0)
Why this scored 18/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.