Skip to content

Commit 24572cf

Browse files
committed
Merge bitcoin/bitcoin#29939: test: add MiniWallet tagging support to avoid UTXO mixing, use in fill_mempool
dd8fa86 test: use tagged ephemeral MiniWallet instance in fill_mempool (Sebastian Falbesoner) b2037ad test: add MiniWallet tagging support to avoid UTXO mixing (Sebastian Falbesoner) c8e6d08 test: refactor: eliminate COINBASE_MATURITY magic number in fill_mempool (Sebastian Falbesoner) 4f34714 test: refactor: move fill_mempool to new module mempool_util (Sebastian Falbesoner) Pull request description: Different MiniWallet instances using the same mode (either ADDRESS_OP_TRUE, RAW_OP_TRUE or RAW_P2PK) currently always create and spend UTXOs with identical output scripts, which can cause unintentional tx dependencies (see e.g. the discussion in bitcoin/bitcoin#29827 (comment)). In order to avoid mixing of UTXOs between instances, this PR introduces the possibility to provide a MiniWallet tag name, that is used to derive a different internal key for the taproot construction, leading to a different P2TR output script. Note that since we use script-path spending and only the key-path is changed here, no changes in the MiniWallet spending logic are needed. The new tagging option is then used in the `fill_mempool` helper to create an ephemeral wallet for the filling txs, as suggested in bitcoin/bitcoin#29827 (comment). To avoid circular dependencies, `fill_mempool` is moved to a new module `mempool_util.py` first. I'm still not sure if a generic word like "tag" is the right term for what this tries to achieve, happy to pick up better suggestions. Also, maybe passing a tag name is overkill and a boolean flag like "random_output_script" is sufficient? ACKs for top commit: glozow: ACK dd8fa86 achow101: ACK dd8fa86 rkrux: tACK [dd8fa86](bitcoin/bitcoin@dd8fa86) brunoerg: utACK dd8fa86 Tree-SHA512: 5ef3558c3ef5ac32cfa79c8f751972ca6bceaa332cd7daac7e93412a88e30dec472cb041c0845b04abf8a317036d31ebddfc3234e609ed442417894c2bdeeac9
2 parents 012e540 + dd8fa86 commit 24572cf

File tree

9 files changed

+117
-79
lines changed

9 files changed

+117
-79
lines changed

test/functional/mempool_limit.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,16 @@
66

77
from decimal import Decimal
88

9+
from test_framework.mempool_util import (
10+
fill_mempool,
11+
)
912
from test_framework.p2p import P2PTxInvStore
1013
from test_framework.test_framework import BitcoinTestFramework
1114
from test_framework.util import (
1215
assert_equal,
1316
assert_fee_amount,
1417
assert_greater_than,
1518
assert_raises_rpc_error,
16-
fill_mempool,
1719
)
1820
from test_framework.wallet import (
1921
COIN,
@@ -93,7 +95,7 @@ def test_mid_package_eviction(self):
9395
assert_equal(node.getmempoolinfo()['minrelaytxfee'], Decimal('0.00001000'))
9496
assert_equal(node.getmempoolinfo()['mempoolminfee'], Decimal('0.00001000'))
9597

96-
fill_mempool(self, node, self.wallet)
98+
fill_mempool(self, node)
9799
current_info = node.getmempoolinfo()
98100
mempoolmin_feerate = current_info["mempoolminfee"]
99101

@@ -183,7 +185,7 @@ def test_mid_package_replacement(self):
183185
assert_equal(node.getmempoolinfo()['minrelaytxfee'], Decimal('0.00001000'))
184186
assert_equal(node.getmempoolinfo()['mempoolminfee'], Decimal('0.00001000'))
185187

186-
fill_mempool(self, node, self.wallet)
188+
fill_mempool(self, node)
187189
current_info = node.getmempoolinfo()
188190
mempoolmin_feerate = current_info["mempoolminfee"]
189191

@@ -257,7 +259,7 @@ def run_test(self):
257259
assert_equal(node.getmempoolinfo()['minrelaytxfee'], Decimal('0.00001000'))
258260
assert_equal(node.getmempoolinfo()['mempoolminfee'], Decimal('0.00001000'))
259261

260-
fill_mempool(self, node, self.wallet)
262+
fill_mempool(self, node)
261263

262264
# Deliberately try to create a tx with a fee less than the minimum mempool fee to assert that it does not get added to the mempool
263265
self.log.info('Create a mempool tx that will not pass mempoolminfee')

test/functional/p2p_1p1c_network.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,9 @@
1212
from decimal import Decimal
1313
from math import ceil
1414

15+
from test_framework.mempool_util import (
16+
fill_mempool,
17+
)
1518
from test_framework.messages import (
1619
msg_tx,
1720
)
@@ -22,7 +25,6 @@
2225
from test_framework.util import (
2326
assert_equal,
2427
assert_greater_than,
25-
fill_mempool,
2628
)
2729
from test_framework.wallet import (
2830
MiniWallet,
@@ -45,8 +47,7 @@ def set_test_params(self):
4547
self.supports_cli = False
4648

4749
def raise_network_minfee(self):
48-
filler_wallet = MiniWallet(self.nodes[0])
49-
fill_mempool(self, self.nodes[0], filler_wallet)
50+
fill_mempool(self, self.nodes[0])
5051

5152
self.log.debug("Wait for the network to sync mempools")
5253
self.sync_mempools()

test/functional/p2p_opportunistic_1p1c.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,9 @@
88

99
from decimal import Decimal
1010
import time
11+
from test_framework.mempool_util import (
12+
fill_mempool,
13+
)
1114
from test_framework.messages import (
1215
CInv,
1316
CTxInWitness,
@@ -24,7 +27,6 @@
2427
from test_framework.util import (
2528
assert_equal,
2629
assert_greater_than,
27-
fill_mempool,
2830
)
2931
from test_framework.wallet import (
3032
MiniWallet,
@@ -386,8 +388,7 @@ def run_test(self):
386388
self.generate(self.wallet_nonsegwit, 10)
387389
self.generate(self.wallet, 20)
388390

389-
filler_wallet = MiniWallet(node)
390-
fill_mempool(self, node, filler_wallet)
391+
fill_mempool(self, node)
391392

392393
self.log.info("Check opportunistic 1p1c logic when parent (txid != wtxid) is received before child")
393394
self.test_basic_parent_then_child(self.wallet)

test/functional/p2p_tx_download.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,9 @@
88
from decimal import Decimal
99
import time
1010

11+
from test_framework.mempool_util import (
12+
fill_mempool,
13+
)
1114
from test_framework.messages import (
1215
CInv,
1316
MSG_TX,
@@ -24,7 +27,6 @@
2427
from test_framework.test_framework import BitcoinTestFramework
2528
from test_framework.util import (
2629
assert_equal,
27-
fill_mempool,
2830
)
2931
from test_framework.wallet import MiniWallet
3032

@@ -248,7 +250,7 @@ def test_spurious_notfound(self):
248250
def test_rejects_filter_reset(self):
249251
self.log.info('Check that rejected tx is not requested again')
250252
node = self.nodes[0]
251-
fill_mempool(self, node, self.wallet)
253+
fill_mempool(self, node)
252254
self.wallet.rescan_utxos()
253255
mempoolminfee = node.getmempoolinfo()['mempoolminfee']
254256
peer = node.add_p2p_connection(TestP2PConn())

test/functional/rpc_packages.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,9 @@
88
import random
99

1010
from test_framework.blocktools import COINBASE_MATURITY
11+
from test_framework.mempool_util import (
12+
fill_mempool,
13+
)
1114
from test_framework.messages import (
1215
MAX_BIP125_RBF_SEQUENCE,
1316
tx_from_hex,
@@ -18,7 +21,6 @@
1821
assert_equal,
1922
assert_fee_amount,
2023
assert_raises_rpc_error,
21-
fill_mempool,
2224
)
2325
from test_framework.wallet import (
2426
DEFAULT_FEE,
@@ -398,7 +400,7 @@ def test_maxfeerate_submitpackage(self):
398400
])
399401
self.wallet.rescan_utxos()
400402

401-
fill_mempool(self, node, self.wallet)
403+
fill_mempool(self, node)
402404

403405
minrelay = node.getmempoolinfo()["minrelaytxfee"]
404406
parent = self.wallet.create_self_transfer(

test/functional/test_framework/address.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -47,17 +47,18 @@ class AddressType(enum.Enum):
4747
b58chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
4848

4949

50-
def create_deterministic_address_bcrt1_p2tr_op_true():
50+
def create_deterministic_address_bcrt1_p2tr_op_true(explicit_internal_key=None):
5151
"""
5252
Generates a deterministic bech32m address (segwit v1 output) that
5353
can be spent with a witness stack of OP_TRUE and the control block
5454
with internal public key (script-path spending).
5555
5656
Returns a tuple with the generated address and the internal key.
5757
"""
58-
internal_key = (1).to_bytes(32, 'big')
58+
internal_key = explicit_internal_key or (1).to_bytes(32, 'big')
5959
address = output_key_to_p2tr(taproot_construct(internal_key, [(None, CScript([OP_TRUE]))]).output_pubkey)
60-
assert_equal(address, 'bcrt1p9yfmy5h72durp7zrhlw9lf7jpwjgvwdg0jr0lqmmjtgg83266lqsekaqka')
60+
if explicit_internal_key is None:
61+
assert_equal(address, 'bcrt1p9yfmy5h72durp7zrhlw9lf7jpwjgvwdg0jr0lqmmjtgg83266lqsekaqka')
6162
return (address, internal_key)
6263

6364

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
#!/usr/bin/env python3
2+
# Copyright (c) 2024 The Bitcoin Core developers
3+
# Distributed under the MIT software license, see the accompanying
4+
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
5+
"""Helpful routines for mempool testing."""
6+
from decimal import Decimal
7+
8+
from .blocktools import (
9+
COINBASE_MATURITY,
10+
)
11+
from .util import (
12+
assert_equal,
13+
assert_greater_than,
14+
create_lots_of_big_transactions,
15+
gen_return_txouts,
16+
)
17+
from .wallet import (
18+
MiniWallet,
19+
)
20+
21+
22+
def fill_mempool(test_framework, node):
23+
"""Fill mempool until eviction.
24+
25+
Allows for simpler testing of scenarios with floating mempoolminfee > minrelay
26+
Requires -datacarriersize=100000 and
27+
-maxmempool=5.
28+
It will not ensure mempools become synced as it
29+
is based on a single node and assumes -minrelaytxfee
30+
is 1 sat/vbyte.
31+
To avoid unintentional tx dependencies, the mempool filling txs are created with a
32+
tagged ephemeral miniwallet instance.
33+
"""
34+
test_framework.log.info("Fill the mempool until eviction is triggered and the mempoolminfee rises")
35+
txouts = gen_return_txouts()
36+
relayfee = node.getnetworkinfo()['relayfee']
37+
38+
assert_equal(relayfee, Decimal('0.00001000'))
39+
40+
tx_batch_size = 1
41+
num_of_batches = 75
42+
# Generate UTXOs to flood the mempool
43+
# 1 to create a tx initially that will be evicted from the mempool later
44+
# 75 transactions each with a fee rate higher than the previous one
45+
ephemeral_miniwallet = MiniWallet(node, tag_name="fill_mempool_ephemeral_wallet")
46+
test_framework.generate(ephemeral_miniwallet, 1 + num_of_batches * tx_batch_size)
47+
48+
# Mine enough blocks so that the UTXOs are allowed to be spent
49+
test_framework.generate(node, COINBASE_MATURITY - 1)
50+
51+
# Get all UTXOs up front to ensure none of the transactions spend from each other, as that may
52+
# change their effective feerate and thus the order in which they are selected for eviction.
53+
confirmed_utxos = [ephemeral_miniwallet.get_utxo(confirmed_only=True) for _ in range(num_of_batches * tx_batch_size + 1)]
54+
assert_equal(len(confirmed_utxos), num_of_batches * tx_batch_size + 1)
55+
56+
test_framework.log.debug("Create a mempool tx that will be evicted")
57+
tx_to_be_evicted_id = ephemeral_miniwallet.send_self_transfer(
58+
from_node=node, utxo_to_spend=confirmed_utxos.pop(0), fee_rate=relayfee)["txid"]
59+
60+
# Increase the tx fee rate to give the subsequent transactions a higher priority in the mempool
61+
# The tx has an approx. vsize of 65k, i.e. multiplying the previous fee rate (in sats/kvB)
62+
# by 130 should result in a fee that corresponds to 2x of that fee rate
63+
base_fee = relayfee * 130
64+
65+
test_framework.log.debug("Fill up the mempool with txs with higher fee rate")
66+
with node.assert_debug_log(["rolling minimum fee bumped"]):
67+
for batch_of_txid in range(num_of_batches):
68+
fee = (batch_of_txid + 1) * base_fee
69+
utxos = confirmed_utxos[:tx_batch_size]
70+
create_lots_of_big_transactions(ephemeral_miniwallet, node, fee, tx_batch_size, txouts, utxos)
71+
del confirmed_utxos[:tx_batch_size]
72+
73+
test_framework.log.debug("The tx should be evicted by now")
74+
# The number of transactions created should be greater than the ones present in the mempool
75+
assert_greater_than(tx_batch_size * num_of_batches, len(node.getrawmempool()))
76+
# Initial tx created should not be present in the mempool anymore as it had a lower fee rate
77+
assert tx_to_be_evicted_id not in node.getrawmempool()
78+
79+
test_framework.log.debug("Check that mempoolminfee is larger than minrelaytxfee")
80+
assert_equal(node.getmempoolinfo()['minrelaytxfee'], Decimal('0.00001000'))
81+
assert_greater_than(node.getmempoolinfo()['mempoolminfee'], Decimal('0.00001000'))

test/functional/test_framework/util.py

Lines changed: 0 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -496,65 +496,6 @@ def check_node_connections(*, node, num_in, num_out):
496496
assert_equal(info["connections_in"], num_in)
497497
assert_equal(info["connections_out"], num_out)
498498

499-
def fill_mempool(test_framework, node, miniwallet):
500-
"""Fill mempool until eviction.
501-
502-
Allows for simpler testing of scenarios with floating mempoolminfee > minrelay
503-
Requires -datacarriersize=100000 and
504-
-maxmempool=5.
505-
It will not ensure mempools become synced as it
506-
is based on a single node and assumes -minrelaytxfee
507-
is 1 sat/vbyte.
508-
To avoid unintentional tx dependencies, it is recommended to use separate miniwallets for
509-
mempool filling vs transactions in tests.
510-
"""
511-
test_framework.log.info("Fill the mempool until eviction is triggered and the mempoolminfee rises")
512-
txouts = gen_return_txouts()
513-
relayfee = node.getnetworkinfo()['relayfee']
514-
515-
assert_equal(relayfee, Decimal('0.00001000'))
516-
517-
tx_batch_size = 1
518-
num_of_batches = 75
519-
# Generate UTXOs to flood the mempool
520-
# 1 to create a tx initially that will be evicted from the mempool later
521-
# 75 transactions each with a fee rate higher than the previous one
522-
test_framework.generate(miniwallet, 1 + (num_of_batches * tx_batch_size))
523-
524-
# Mine COINBASE_MATURITY - 1 blocks so that the UTXOs are allowed to be spent
525-
test_framework.generate(node, 100 - 1)
526-
527-
# Get all UTXOs up front to ensure none of the transactions spend from each other, as that may
528-
# change their effective feerate and thus the order in which they are selected for eviction.
529-
confirmed_utxos = [miniwallet.get_utxo(confirmed_only=True) for _ in range(num_of_batches * tx_batch_size + 1)]
530-
assert_equal(len(confirmed_utxos), num_of_batches * tx_batch_size + 1)
531-
532-
test_framework.log.debug("Create a mempool tx that will be evicted")
533-
tx_to_be_evicted_id = miniwallet.send_self_transfer(from_node=node, utxo_to_spend=confirmed_utxos[0], fee_rate=relayfee)["txid"]
534-
del confirmed_utxos[0]
535-
536-
# Increase the tx fee rate to give the subsequent transactions a higher priority in the mempool
537-
# The tx has an approx. vsize of 65k, i.e. multiplying the previous fee rate (in sats/kvB)
538-
# by 130 should result in a fee that corresponds to 2x of that fee rate
539-
base_fee = relayfee * 130
540-
541-
test_framework.log.debug("Fill up the mempool with txs with higher fee rate")
542-
with node.assert_debug_log(["rolling minimum fee bumped"]):
543-
for batch_of_txid in range(num_of_batches):
544-
fee = (batch_of_txid + 1) * base_fee
545-
utxos = confirmed_utxos[:tx_batch_size]
546-
create_lots_of_big_transactions(miniwallet, node, fee, tx_batch_size, txouts, utxos)
547-
del confirmed_utxos[:tx_batch_size]
548-
549-
test_framework.log.debug("The tx should be evicted by now")
550-
# The number of transactions created should be greater than the ones present in the mempool
551-
assert_greater_than(tx_batch_size * num_of_batches, len(node.getrawmempool()))
552-
# Initial tx created should not be present in the mempool anymore as it had a lower fee rate
553-
assert tx_to_be_evicted_id not in node.getrawmempool()
554-
555-
test_framework.log.debug("Check that mempoolminfee is larger than minrelaytxfee")
556-
assert_equal(node.getmempoolinfo()['minrelaytxfee'], Decimal('0.00001000'))
557-
assert_greater_than(node.getmempoolinfo()['mempoolminfee'], Decimal('0.00001000'))
558499

559500
# Transaction/Block functions
560501
#############################

test/functional/test_framework/wallet.py

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232
CTxIn,
3333
CTxInWitness,
3434
CTxOut,
35+
hash256,
3536
)
3637
from test_framework.script import (
3738
CScript,
@@ -65,7 +66,10 @@ class MiniWalletMode(Enum):
6566
However, if the transactions need to be modified by the user (e.g. prepending
6667
scriptSig for testing opcodes that are activated by a soft-fork), or the txs
6768
should contain an actual signature, the raw modes RAW_OP_TRUE and RAW_P2PK
68-
can be useful. Summary of modes:
69+
can be useful. In order to avoid mixing of UTXOs between different MiniWallet
70+
instances, a tag name can be passed to the default mode, to create different
71+
output scripts. Note that the UTXOs from the pre-generated test chain can
72+
only be spent if no tag is passed. Summary of modes:
6973
7074
| output | | tx is | can modify | needs
7175
mode | description | address | standard | scriptSig | signing
@@ -80,22 +84,25 @@ class MiniWalletMode(Enum):
8084

8185

8286
class MiniWallet:
83-
def __init__(self, test_node, *, mode=MiniWalletMode.ADDRESS_OP_TRUE):
87+
def __init__(self, test_node, *, mode=MiniWalletMode.ADDRESS_OP_TRUE, tag_name=None):
8488
self._test_node = test_node
8589
self._utxos = []
8690
self._mode = mode
8791

8892
assert isinstance(mode, MiniWalletMode)
8993
if mode == MiniWalletMode.RAW_OP_TRUE:
94+
assert tag_name is None
9095
self._scriptPubKey = bytes(CScript([OP_TRUE]))
9196
elif mode == MiniWalletMode.RAW_P2PK:
9297
# use simple deterministic private key (k=1)
98+
assert tag_name is None
9399
self._priv_key = ECKey()
94100
self._priv_key.set((1).to_bytes(32, 'big'), True)
95101
pub_key = self._priv_key.get_pubkey()
96102
self._scriptPubKey = key_to_p2pk_script(pub_key.get_bytes())
97103
elif mode == MiniWalletMode.ADDRESS_OP_TRUE:
98-
self._address, self._internal_key = create_deterministic_address_bcrt1_p2tr_op_true()
104+
internal_key = None if tag_name is None else hash256(tag_name.encode())
105+
self._address, self._internal_key = create_deterministic_address_bcrt1_p2tr_op_true(internal_key)
99106
self._scriptPubKey = address_to_scriptpubkey(self._address)
100107

101108
# When the pre-mined test framework chain is used, it contains coinbase

0 commit comments

Comments
 (0)