test: Allow to set height in create_block

Previously, it was only possible to set the height indirectly by calling
create_coinbase outside the create_block function. This is fine, but
verbose and not needed.

Just like hashprev can be set directly (instead of using the value from
tmpl), allow height to be set directly.

Also, use it in one place. The other places are done in a scripted-diff.

Also, add a unit test for the new feature.
This commit is contained in:
MarcoFalke
2026-04-15 17:11:24 +02:00
parent 44ac0c32b9
commit fa5eb74b96
2 changed files with 11 additions and 4 deletions

View File

@@ -15,7 +15,6 @@ from test_framework.address import (
from test_framework.blocktools import (
add_witness_commitment,
create_block,
create_coinbase,
)
from test_framework.test_framework import BitcoinTestFramework
from test_framework.messages import (
@@ -419,7 +418,7 @@ class ZMQTest (BitcoinTestFramework):
bump_txid = self.nodes[0].sendrawtransaction(orig_tx['tx'].serialize().hex())
# Mine the pre-bump tx
txs_to_add = [orig_tx['hex']] + [tx['hex'] for tx in more_tx]
block = create_block(int(self.nodes[0].getbestblockhash(), 16), create_coinbase(self.nodes[0].getblockcount()+1), txlist=txs_to_add)
block = create_block(int(self.nodes[0].getbestblockhash(), 16), height=self.nodes[0].getblockcount() + 1, txlist=txs_to_add)
add_witness_commitment(block)
block.solve()
assert_equal(self.nodes[0].submitblock(block.serialize().hex()), None)

View File

@@ -95,7 +95,7 @@ def nbits_str(nbits):
def target_str(target):
return f"{target:064x}"
def create_block(hashprev=None, coinbase=None, ntime=None, *, version=None, tmpl=None, txlist=None):
def create_block(hashprev=None, coinbase=None, ntime=None, *, height=None, version=None, tmpl=None, txlist=None):
"""Create a block (with regtest difficulty)."""
block = CBlock()
if tmpl is None:
@@ -108,7 +108,7 @@ def create_block(hashprev=None, coinbase=None, ntime=None, *, version=None, tmpl
else:
block.nBits = REGTEST_N_BITS
if coinbase is None:
coinbase = create_coinbase(height=tmpl['height'])
coinbase = create_coinbase(height=height or tmpl["height"])
block.vtx.append(coinbase)
if txlist:
for tx in txlist:
@@ -278,6 +278,14 @@ def send_to_witness(use_p2wsh, node, utxo, pubkey, encode_p2sh, amount, sign=Tru
return node.sendrawtransaction(tx_to_witness)
class TestFrameworkBlockTools(unittest.TestCase):
def test_create_block_prefers_explicit_height(self):
block = create_block(
hashprev=1,
tmpl={"height": 100},
height=200,
)
assert_equal(CScriptNum.decode(block.vtx[0].vin[0].scriptSig), 200)
def test_create_coinbase(self):
height = 20
coinbase_tx = create_coinbase(height=height)