Merge bitcoin/bitcoin#36192: test: cover unsatisfiable mining timestamp
What changed, and why it matters
This commit only adds and reorganizes Bitcoin Core's own functional tests. It renames some test constants, moves a shared constant into the test framework, and adds a new test that checks how the mining code behaves when an attacker manipulates block timestamps to make template creation temporarily fail. The commit does not change any production consensus, networking, or wallet code, and the pull request description explicitly calls the scenario an 'impractical' test-case. There is no security patch or vulnerability fix here.
No action required. This is a test-only change. Reviewers may optionally run the updated functional tests (interface_ipc_mining.py and mining_basic.py) to confirm the new coverage passes.
Security signals we found
No strong security signals were identified.
Evidence from the diff
The merge commit b4f341a93f1cc9e9229f5aa1ccfbb033da074f22 is a pure test/refactor change. It renames REGTEST_N_BITS/TARGET to N_BITS/TARGET, REGTEST_RETARGET_PERIOD to HALVING_INTERVAL, and moves DIFFICULTY_ADJUSTMENT_INTERVAL into test_framework/blocktools.py. The only new behavior is in interface_ipc_mining.py: run_unsatisfiable_timestamp_test(), which simulates six attacker blocks timestamped at the victim’s MAX_FUTURE_BLOCK_TIME limit, asserts that getblocktemplate/createNewBlock fail with ‘time-too-new’, then advances mocktime by one second and verifies both RPC and IPC mining recover. No C++ node logic is modified.
Changed components
test/functional/interface_ipc_mining.pytest/functional/mining_basic.pytest/functional/rpc_blockchain.pytest/functional/feature_block.pytest/functional/feature_assumeutxo.pytest/functional/test_framework/blocktools.pyInspect captured patch +93 / −28
### test/functional/feature_assumeutxo.py
@@ -46,8 +46,8 @@
MiniWallet,
)
from test_framework.blocktools import (
- REGTEST_N_BITS,
- REGTEST_TARGET,
+ N_BITS,
+ TARGET,
nbits_str,
target_str,
)
@@ -251,9 +251,9 @@ def test_snapshot_in_a_divergent_chain(self, dump_output_path):
assert_equal(snapshot['blocks'], SNAPSHOT_BASE_HEIGHT)
# Both states should have the same nBits and target
- assert_equal(normal['bits'], nbits_str(REGTEST_N_BITS))
+ assert_equal(normal['bits'], nbits_str(N_BITS))
assert_equal(normal['bits'], snapshot['bits'])
- assert_equal(normal['target'], target_str(REGTEST_TARGET))
+ assert_equal(normal['target'], target_str(TARGET))
assert_equal(normal['target'], snapshot['target'])
# Now lets sync the nodes and wait for the background validation to finish
### test/functional/feature_block.py
@@ -13,7 +13,7 @@
create_tx_with_script,
get_legacy_sigopcount_block,
MAX_BLOCK_SIGOPS,
- REGTEST_N_BITS,
+ N_BITS,
)
from test_framework.messages import (
CBlock,
@@ -619,7 +619,7 @@ def run_test(self):
b44 = CBlock()
b44.nTime = self.tip.nTime + 1
b44.hashPrevBlock = self.tip.hash_int
- b44.nBits = REGTEST_N_BITS
+ b44.nBits = N_BITS
b44.vtx.append(coinbase)
tx = self.create_and_sign_transaction(out[14], 1)
b44.vtx.append(tx)
@@ -635,7 +635,7 @@ def run_test(self):
b45 = CBlock()
b45.nTime = self.tip.nTime + 1
b45.hashPrevBlock = self.tip.hash_int
- b45.nBits = REGTEST_N_BITS
+ b45.nBits = N_BITS
b45.vtx.append(non_coinbase)
b45.hashMerkleRoot = b45.calc_merkle_root()
b45.solve()
@@ -649,7 +649,7 @@ def run_test(self):
b46 = CBlock()
b46.nTime = b44.nTime + 1
b46.hashPrevBlock = b44.hash_int
- b46.nBits = REGTEST_N_BITS
+ b46.nBits = N_BITS
b46.vtx = []
b46.hashMerkleRoot = 0
b46.solve()
### test/functional/interface_ipc_mining.py
@@ -10,6 +10,8 @@
from decimal import Decimal
from io import BytesIO
from test_framework.blocktools import (
+ MAX_FUTURE_BLOCK_TIME,
+ NORMAL_GBT_REQUEST_PARAMS,
NULL_OUTPOINT,
script_BIP34_coinbase_height,
WITNESS_COMMITMENT_HEADER,
@@ -34,6 +36,7 @@
assert_equal,
assert_greater_than_or_equal,
assert_not_equal,
+ assert_raises_rpc_error,
)
from test_framework.wallet import MiniWallet
from test_framework.p2p import P2PInterface
@@ -770,6 +773,64 @@ async def async_routine():
asyncio.run(capnp.run(async_routine()))
+ def run_unsatisfiable_timestamp_test(self):
+ """Test template creation when timestamp constraints conflict.
+
+ Simulate an attacker releasing six blocks with timestamps exactly at
+ the victim's two-hour future-time limit. Test both the getblocktemplate
+ RPC and the IPC mining interface. This attack is impractical, and
+ mining works again one second later.
+ """
+ self.log.info("Test unsatisfiable block timestamp constraints")
+ victim = self.nodes[0]
+ attacker = self.nodes[1]
+
+ # Six of the last eleven blocks determine the median time past.
+ NUM_ATTACK_BLOCKS = 6
+ # Time as seen by the victim and other non-attacker nodes.
+ actual_time = int(time.time())
+
+ # The six attack blocks use the highest timestamp the victim accepts,
+ # putting MTP at its future-time limit. The next block needs MTP + 1,
+ # so template creation fails instead of returning an unmineable template.
+ error = "TestBlockValidity failed: time-too-new, block timestamp too far in the future"
+
+ for node in self.nodes:
+ node.setmocktime(actual_time)
+
+ attacker_time = actual_time + MAX_FUTURE_BLOCK_TIME
+ attacker.setmocktime(attacker_time)
+ self.generate(attacker, NUM_ATTACK_BLOCKS)
+
+ assert_equal(victim.getblockchaininfo()["mediantime"], attacker_time)
+
+ # Check template creation failure over RPC, followed by IPC.
+ assert_raises_rpc_error(-1, error, victim.getblocktemplate, NORMAL_GBT_REQUEST_PARAMS)
+
+ async def assert_ipc_failure_and_recovery():
+ ctx, mining = await make_mining_ctx(self)
+ opts = self.capnp_modules["mining"].BlockCreateOptions()
+ await assert_create_new_block_fails(ctx, mining, opts, error)
+
+ # One second later, MTP + 1 is exactly at the future-time limit.
+ # Reuse the IPC connection to verify the remote exception did not
+ # tear it down.
+ victim.setmocktime(actual_time + 1)
+ async with destroying((await mining.createNewBlock(ctx, opts)).result, ctx) as template:
+ block = await mining_get_block(template, ctx)
+ assert_equal(block.nTime, attacker_time + 1)
+
+ asyncio.run(capnp.run(assert_ipc_failure_and_recovery()))
+
+ # The async block bumped the victim's time by one second, so
+ # creation via RPC succeeds again.
+ rpc_template = victim.getblocktemplate(NORMAL_GBT_REQUEST_PARAMS)
+ assert_equal(rpc_template["mintime"], attacker_time + 1)
+ assert_equal(rpc_template["curtime"], attacker_time + 1)
+
+ for node in self.nodes:
+ node.setmocktime(0)
+
def run_low_height_test(self):
"""Test that IPC createNewBlock() works at low block heights on a
clean chain, in particular with regard to bad-cb-length.
@@ -832,6 +893,7 @@ def run_test(self):
self.run_block_max_weight_test()
self.run_ipc_option_override_test()
self.run_transaction_lookup_test()
+ self.run_unsatisfiable_timestamp_test()
# Needs to run last because it resets the chain.
self.run_low_height_test()
### test/functional/mining_basic.py
@@ -14,14 +14,15 @@
from decimal import Decimal
from test_framework.blocktools import (
+ DIFFICULTY_ADJUSTMENT_INTERVAL,
create_block,
create_coinbase,
get_witness_script,
MAX_FUTURE_BLOCK_TIME,
NORMAL_GBT_REQUEST_PARAMS,
TIME_GENESIS_BLOCK,
- REGTEST_N_BITS,
- REGTEST_TARGET,
+ N_BITS,
+ TARGET,
nbits_str,
target_str,
)
@@ -52,7 +53,6 @@
)
-DIFFICULTY_ADJUSTMENT_INTERVAL = 144
MAX_TIMEWARP = 600
VERSIONBITS_TOP_BITS = 0x20000000
VERSIONBITS_DEPLOYMENT_TESTDUMMY_BIT = 28
@@ -267,6 +267,7 @@ def test_murch_zawy_mintime(self):
self.generate(self.wallet, 1, sync_fun=self.no_op)
node.setmocktime(t + MAX_FUTURE_BLOCK_TIME)
self.generate(self.wallet, 1, sync_fun=self.no_op)
+ assert_equal(node.getblockchaininfo()['blocks'] % DIFFICULTY_ADJUSTMENT_INTERVAL, 0)
first_block_time = node.getblock(node.getbestblockhash())['time']
assert_equal(first_block_time, t + MAX_FUTURE_BLOCK_TIME)
@@ -277,6 +278,7 @@ def test_murch_zawy_mintime(self):
self.log.info("The template for the last block of the period is adjusted to its first block's time")
tmpl = node.getblocktemplate(NORMAL_GBT_REQUEST_PARAMS)
+ assert_equal(tmpl['height'] % DIFFICULTY_ADJUSTMENT_INTERVAL, DIFFICULTY_ADJUSTMENT_INTERVAL - 1)
assert_equal(tmpl['mintime'], first_block_time)
assert_equal(tmpl['curtime'], first_block_time)
@@ -436,13 +438,13 @@ def run_test(self):
assert_equal(mining_info['chain'], self.chain)
assert 'currentblocktx' not in mining_info
assert 'currentblockweight' not in mining_info
- assert_equal(mining_info['bits'], nbits_str(REGTEST_N_BITS))
- assert_equal(mining_info['target'], target_str(REGTEST_TARGET))
+ assert_equal(mining_info['bits'], nbits_str(N_BITS))
+ assert_equal(mining_info['target'], target_str(TARGET))
# We don't care about precision, round to avoid mismatch under Valgrind:
assert_equal(round(mining_info['difficulty'], 10), Decimal('0.0000000005'))
assert_equal(mining_info['next']['height'], 201)
- assert_equal(mining_info['next']['target'], target_str(REGTEST_TARGET))
- assert_equal(mining_info['next']['bits'], nbits_str(REGTEST_N_BITS))
+ assert_equal(mining_info['next']['target'], target_str(TARGET))
+ assert_equal(mining_info['next']['bits'], nbits_str(N_BITS))
assert_equal(round(mining_info['next']['difficulty'], 10), Decimal('0.0000000005'))
assert_equal(round(mining_info['networkhashps'], 5), Decimal('0.00333'))
assert_equal(mining_info['pooledtx'], 0)
### test/functional/rpc_blockchain.py
@@ -29,10 +29,11 @@
import textwrap
from test_framework.blocktools import (
+ DIFFICULTY_ADJUSTMENT_INTERVAL,
MAX_FUTURE_BLOCK_TIME,
TIME_GENESIS_BLOCK,
- REGTEST_N_BITS,
- REGTEST_TARGET,
+ N_BITS,
+ TARGET,
create_block,
create_coinbase,
create_tx_with_script,
@@ -66,7 +67,6 @@
TIME_RANGE_MTP = TIME_GENESIS_BLOCK + (HEIGHT - 6) * TIME_RANGE_STEP
TIME_RANGE_TIP = TIME_GENESIS_BLOCK + (HEIGHT - 1) * TIME_RANGE_STEP
TIME_RANGE_END = TIME_GENESIS_BLOCK + HEIGHT * TIME_RANGE_STEP
-DIFFICULTY_ADJUSTMENT_INTERVAL = 144
class BlockchainTest(BitcoinTestFramework):
@@ -207,8 +207,8 @@ def _test_getblockchaininfo(self):
assert_equal(res['prune_target_size'], 576716800)
assert_greater_than(res['size_on_disk'], 0)
- assert_equal(res['bits'], nbits_str(REGTEST_N_BITS))
- assert_equal(res['target'], target_str(REGTEST_TARGET))
+ assert_equal(res['bits'], nbits_str(N_BITS))
+ assert_equal(res['target'], target_str(TARGET))
def check_signalling_deploymentinfo_result(self, gdi_result, height, blockhash, status_next):
assert height >= 144 and height <= 287
@@ -459,8 +459,8 @@ def _test_getblockheader(self):
assert_is_hash_string(header['hash'])
assert_is_hash_string(header['previousblockhash'])
assert_is_hash_string(header['merkleroot'])
- assert_equal(header['bits'], nbits_str(REGTEST_N_BITS))
- assert_equal(header['target'], target_str(REGTEST_TARGET))
+ assert_equal(header['bits'], nbits_str(N_BITS))
+ assert_equal(header['target'], target_str(TARGET))
assert isinstance(header['time'], int)
assert_equal(header['mediantime'], TIME_RANGE_MTP)
assert isinstance(header['nonce'], int)
### test/functional/test_framework/blocktools.py
@@ -69,11 +69,12 @@
VERSIONBITS_LAST_OLD_BLOCK_VERSION = 4
MIN_BLOCKS_TO_KEEP = 288
-REGTEST_RETARGET_PERIOD = 150
+HALVING_INTERVAL = 150 # regtest nSubsidyHalvingInterval
-REGTEST_N_BITS = 0x207fffff # difficulty retargeting is disabled in REGTEST chainparams"
-REGTEST_TARGET = 0x7fffff0000000000000000000000000000000000000000000000000000000000
-assert_equal(uint256_from_compact(REGTEST_N_BITS), REGTEST_TARGET)
+DIFFICULTY_ADJUSTMENT_INTERVAL = 144 # regtest nPowTargetTimespan / nPowTargetSpacing
+N_BITS = 0x207fffff # difficulty retargeting is disabled in REGTEST chainparams"
+TARGET = 0x7fffff0000000000000000000000000000000000000000000000000000000000
+assert_equal(uint256_from_compact(N_BITS), TARGET)
DIFF_1_N_BITS = 0x1d00ffff
DIFF_1_TARGET = 0x00000000ffff0000000000000000000000000000000000000000000000000000
@@ -106,7 +107,7 @@ def create_block(hashprev=None, coinbase=None, *, ntime=None, height=None, versi
if tmpl and tmpl.get('bits') is not None:
block.nBits = struct.unpack('>I', bytes.fromhex(tmpl['bits']))[0]
else:
- block.nBits = REGTEST_N_BITS
+ block.nBits = N_BITS
if coinbase is None:
coinbase = create_coinbase(height=height or tmpl["height"])
block.vtx.append(coinbase)
@@ -171,7 +172,7 @@ def script_BIP34_coinbase_height(height, *, padding=True):
return CScript([CScriptNum(height)])
-def create_coinbase(height, pubkey=None, *, script_pubkey=None, extra_output_script=None, fees=0, nValue=50, halving_period=REGTEST_RETARGET_PERIOD):
+def create_coinbase(height, pubkey=None, *, script_pubkey=None, extra_output_script=None, fees=0, nValue=50, halving_period=HALVING_INTERVAL):
"""Create a coinbase transaction.
If pubkey is passed in, the coinbase output will be a P2PK output;Why this scored 15/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.