rpc: tighten setmocktime upper bound to UINT32_MAX

The previous bound (~year 2262) was too permissive: paths that add an offset to the mocked time (e.g. the future-time check in ContextualCheckBlockHeader) can overflow int64_t (caught by UBSan), and paths that assign it to a uint32_t field (e.g. pblock->nTime in miner.cpp) silently truncate it (caught by the integer sanitizer). UINT32_MAX is the natural ceiling since block header nTime is uint32_t, and mocking beyond it is meaningless for anything consensus-related.

Add setmocktime bound checks to the existing _test_y2106 case in rpc_blockchain.py, and remove the negative bound check from rpc_uptime.py.
This commit is contained in:
stringintech
2026-06-12 15:13:02 +03:30
parent 142e86a65c
commit 406c2348dd
3 changed files with 6 additions and 6 deletions

View File

@@ -29,6 +29,7 @@
#include <util/time.h>
#include <cstdint>
#include <limits>
#ifdef HAVE_MALLOC_INFO
#include <malloc.h>
#endif
@@ -61,7 +62,9 @@ static RPCMethod setmocktime()
LOCK(cs_main);
const int64_t time{request.params[0].getInt<int64_t>()};
constexpr int64_t max_time{Ticks<std::chrono::seconds>(std::chrono::nanoseconds::max())};
// block timestamps are uint32_t, so mocking time beyond that is meaningless for anything
// consensus-related and can cause integer overflow/truncation issues in time arithmetic.
constexpr int64_t max_time{std::numeric_limits<uint32_t>::max()};
if (time < 0 || time > max_time) {
throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Mocktime must be in the range [0, %s], not %s.", max_time, time));
}

View File

@@ -290,6 +290,8 @@ class BlockchainTest(BitcoinTestFramework):
self.log.info("Check that block timestamps work until year 2106")
self.generate(self.nodes[0], 8)[-1]
time_2106 = 2**32 - 1
assert_raises_rpc_error(-8, f"Mocktime must be in the range [0, {time_2106}], not -1.", self.nodes[0].setmocktime, -1)
assert_raises_rpc_error(-8, f"Mocktime must be in the range [0, {time_2106}], not {time_2106 + 1}.", self.nodes[0].setmocktime, time_2106 + 1)
self.nodes[0].setmocktime(time_2106)
last = self.generate(self.nodes[0], 6)[-1]
assert_equal(self.nodes[0].getblockheader(last)["mediantime"], time_2106)

View File

@@ -10,7 +10,6 @@ Test corresponds to code in rpc/server.cpp.
import time
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import assert_raises_rpc_error
class UptimeTest(BitcoinTestFramework):
@@ -19,12 +18,8 @@ class UptimeTest(BitcoinTestFramework):
self.setup_clean_chain = True
def run_test(self):
self._test_negative_time()
self._test_uptime()
def _test_negative_time(self):
assert_raises_rpc_error(-8, "Mocktime must be in the range [0, 9223372036], not -1.", self.nodes[0].setmocktime, -1)
def _test_uptime(self):
time.sleep(1) # Do some work before checking uptime
uptime_before = self.nodes[0].uptime()