Skip to content

Commit bd75014

Browse files
kwvgUdjinM6
andcommitted
merge bitcoin#21762: Speed up mempool_spend_coinbase.py
Co-authored-by: UdjinM6 <[email protected]>
1 parent 72eeb9a commit bd75014

File tree

3 files changed

+42
-26
lines changed

3 files changed

+42
-26
lines changed

test/functional/mempool_spend_coinbase.py

Lines changed: 18 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -20,40 +20,41 @@
2020
class MempoolSpendCoinbaseTest(BitcoinTestFramework):
2121
def set_test_params(self):
2222
self.num_nodes = 1
23-
self.setup_clean_chain = True
2423

2524
def run_test(self):
2625
wallet = MiniWallet(self.nodes[0])
2726

28-
wallet.generate(200)
29-
chain_height = self.nodes[0].getblockcount()
30-
assert_equal(chain_height, 200)
27+
# Invalidate two blocks, so that miniwallet has access to a coin that will mature in the next block
28+
chain_height = 198
29+
self.nodes[0].invalidateblock(self.nodes[0].getblockhash(chain_height + 1))
30+
assert_equal(chain_height, self.nodes[0].getblockcount())
3131

3232
# Coinbase at height chain_height-100+1 ok in mempool, should
3333
# get mined. Coinbase at height chain_height-100+2 is
3434
# too immature to spend.
35-
b = [self.nodes[0].getblockhash(n) for n in range(101, 103)]
36-
coinbase_txids = [self.nodes[0].getblock(h)['tx'][0] for h in b]
37-
utxo_101 = wallet.get_utxo(txid=coinbase_txids[0])
38-
utxo_102 = wallet.get_utxo(txid=coinbase_txids[1])
35+
wallet.scan_blocks(start=chain_height - 100 + 1, num=1)
36+
utxo_mature = wallet.get_utxo()
37+
wallet.scan_blocks(start=chain_height - 100 + 2, num=1)
38+
utxo_immature = wallet.get_utxo()
3939

40-
spend_101_id = wallet.send_self_transfer(from_node=self.nodes[0], utxo_to_spend=utxo_101)["txid"]
40+
spend_mature_id = wallet.send_self_transfer(from_node=self.nodes[0], utxo_to_spend=utxo_mature)["txid"]
4141

42-
# coinbase at height 102 should be too immature to spend
42+
# other coinbase should be too immature to spend
43+
immature_tx = wallet.create_self_transfer(from_node=self.nodes[0], utxo_to_spend=utxo_immature, mempool_valid=False)
4344
assert_raises_rpc_error(-26,
4445
"bad-txns-premature-spend-of-coinbase",
45-
lambda: wallet.send_self_transfer(from_node=self.nodes[0], utxo_to_spend=utxo_102))
46+
lambda: self.nodes[0].sendrawtransaction(immature_tx['hex']))
4647

47-
# mempool should have just spend_101:
48-
assert_equal(self.nodes[0].getrawmempool(), [spend_101_id])
48+
# mempool should have just the mature one
49+
assert_equal(self.nodes[0].getrawmempool(), [spend_mature_id])
4950

50-
# mine a block, spend_101 should get confirmed
51+
# mine a block, mature one should get confirmed
5152
self.nodes[0].generate(1)
5253
assert_equal(set(self.nodes[0].getrawmempool()), set())
5354

54-
# ... and now height 102 can be spent:
55-
spend_102_id = wallet.send_self_transfer(from_node=self.nodes[0], utxo_to_spend=utxo_102)["txid"]
56-
assert_equal(self.nodes[0].getrawmempool(), [spend_102_id])
55+
# ... and now previously immature can be spent:
56+
spend_new_id = self.nodes[0].sendrawtransaction(immature_tx['hex'])
57+
assert_equal(self.nodes[0].getrawmempool(), [spend_new_id])
5758

5859

5960
if __name__ == '__main__':

test/functional/test_framework/test_framework.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -913,12 +913,13 @@ def _initialize_chain(self):
913913
# This is needed so that we are out of IBD when the test starts,
914914
# see the tip age check in IsInitialBlockDownload().
915915
self.set_genesis_mocktime()
916-
gen_addresses = [k.address for k in TestNode.PRIV_KEYS] + [ADDRESS_BCRT1_P2SH_OP_TRUE]
916+
gen_addresses = [k.address for k in TestNode.PRIV_KEYS][:3] + [ADDRESS_BCRT1_P2SH_OP_TRUE]
917+
assert_equal(len(gen_addresses), 4)
917918
for i in range(8):
918919
self.bump_mocktime((25 if i != 7 else 24) * 156)
919920
cache_node.generatetoaddress(
920921
nblocks=25 if i != 7 else 24,
921-
address=gen_addresses[i % 4],
922+
address=gen_addresses[i % len(gen_addresses)],
922923
)
923924

924925
assert_equal(cache_node.getblockchaininfo()["blocks"], 199)

test/functional/test_framework/wallet.py

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -37,9 +37,13 @@ def scan_blocks(self, *, start=1, num):
3737
for i in range(start, start + num):
3838
block = self._test_node.getblock(blockhash=self._test_node.getblockhash(i), verbosity=2)
3939
for tx in block['tx']:
40-
for out in tx['vout']:
41-
if out['scriptPubKey']['hex'] == self._scriptPubKey.hex():
42-
self._utxos.append({'txid': tx['txid'], 'vout': out['n'], 'value': out['value']})
40+
self.scan_tx(tx)
41+
42+
def scan_tx(self, tx):
43+
"""Scan the tx for self._scriptPubKey outputs and add them to self._utxos"""
44+
for out in tx['vout']:
45+
if out['scriptPubKey']['hex'] == self._scriptPubKey.hex():
46+
self._utxos.append({'txid': tx['txid'], 'vout': out['n'], 'value': out['value']})
4347

4448
def generate(self, num_blocks):
4549
"""Generate blocks with coinbase outputs to the internal address, and append the outputs to the internal list"""
@@ -69,6 +73,12 @@ def get_utxo(self, *, txid: Optional[str]=''):
6973

7074
def send_self_transfer(self, *, fee_rate=Decimal("0.003"), from_node, utxo_to_spend=None):
7175
"""Create and send a tx with the specified fee_rate. Fee may be exact or at most one satoshi higher than needed."""
76+
tx = self.create_self_transfer(fee_rate=fee_rate, from_node=from_node, utxo_to_spend=utxo_to_spend)
77+
self.sendrawtransaction(from_node=from_node, tx_hex=tx['hex'])
78+
return tx
79+
80+
def create_self_transfer(self, *, fee_rate=Decimal("0.003"), from_node, utxo_to_spend=None, mempool_valid=True):
81+
"""Create and return a tx with the specified fee_rate. Fee may be exact or at most one satoshi higher than needed."""
7282
self._utxos = sorted(self._utxos, key=lambda k: k['value'])
7383
utxo_to_spend = utxo_to_spend or self._utxos.pop() # Pick the largest utxo (if none provided) and hope it covers the fee
7484
vsize = Decimal(85)
@@ -83,8 +93,12 @@ def send_self_transfer(self, *, fee_rate=Decimal("0.003"), from_node, utxo_to_sp
8393
tx_hex = tx.serialize().hex()
8494

8595
tx_info = from_node.testmempoolaccept([tx_hex])[0]
86-
self._utxos.append({'txid': tx_info['txid'], 'vout': 0, 'value': send_value})
87-
from_node.sendrawtransaction(tx_hex)
88-
assert_equal(len(tx_hex) // 2, vsize)
89-
assert_equal(tx_info['fees']['base'], fee)
96+
assert_equal(mempool_valid, tx_info['allowed'])
97+
if mempool_valid:
98+
assert_equal(len(tx_hex) // 2, vsize)
99+
assert_equal(tx_info['fees']['base'], fee)
90100
return {'txid': tx_info['txid'], 'hex': tx_hex}
101+
102+
def sendrawtransaction(self, *, from_node, tx_hex):
103+
from_node.sendrawtransaction(tx_hex)
104+
self.scan_tx(from_node.decoderawtransaction(tx_hex))

0 commit comments

Comments
 (0)