Skip to content

Commit 27d935f

Browse files
committed
Merge bitcoin/bitcoin#29179: test: wallet rescan with reorged parent + IsFromMe child in mempool
df30247 [test] import descriptor wallet with reorged parent + IsFromMe child in mempool (glozow) c3d02be [test] rescan legacy wallet with reorged parent + IsFromMe child in mempool (Gloria Zhao) Pull request description: Originally motivated by #29019, which reverts back to having `requestMempoolTransactions` emit `transactionAddedToMempool` in `mapTx` default order instead of `GetSortedDepthAndScore` order. It's important that these notifications happen in topological order, otherwise the wallet rescan may miss transactions that belong to it. Notably, checking whether a transaction `IsFromMe` requires knowing its inputs, which may be from a mempool parent. When using `mapTx` order, a parent may come later than its child if it was added from a block disconnected in a reorg. This PR adds a test for this case. ACKs for top commit: achow101: ACK df30247 furszy: Code review ACK df30247, nits can be disregarded. Tree-SHA512: 2f1d9ef92313228adbbef94e634e5f7a9ec6e6a2c88e16aa343bdc95ffc9b9f9c82a569b412c9a3841db9d789e52f9283e8b9385731668d59355903e26e58a5d
2 parents f1fcc96 + df30247 commit 27d935f

File tree

3 files changed

+131
-9
lines changed

3 files changed

+131
-9
lines changed

test/functional/test_runner.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -336,6 +336,7 @@
336336
'wallet_create_tx.py --descriptors',
337337
'wallet_inactive_hdchains.py --legacy-wallet',
338338
'wallet_spend_unconfirmed.py',
339+
'wallet_rescan_unconfirmed.py --descriptors',
339340
'p2p_fingerprint.py',
340341
'feature_uacomment.py',
341342
'feature_init.py',

test/functional/wallet_import_rescan.py

Lines changed: 47 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,10 @@
2020
"""
2121

2222
from test_framework.test_framework import BitcoinTestFramework
23-
from test_framework.address import AddressType
23+
from test_framework.address import (
24+
AddressType,
25+
ADDRESS_BCRT1_UNSPENDABLE,
26+
)
2427
from test_framework.util import (
2528
assert_equal,
2629
set_node_times,
@@ -109,7 +112,7 @@ def check(self, txid=None, amount=None, confirmation_height=None):
109112

110113
address, = [ad for ad in addresses if txid in ad["txids"]]
111114
assert_equal(address["address"], self.address["address"])
112-
assert_equal(address["amount"], self.expected_balance)
115+
assert_equal(address["amount"], self.amount_received)
113116
assert_equal(address["confirmations"], confirmations)
114117
# Verify the transaction is correctly marked watchonly depending on
115118
# whether the transaction pays to an imported public key or
@@ -223,11 +226,11 @@ def run_test(self):
223226
variant.node = self.nodes[2 + IMPORT_NODES.index(ImportNode(variant.prune, expect_rescan))]
224227
variant.do_import(variant.timestamp)
225228
if expect_rescan:
226-
variant.expected_balance = variant.initial_amount
229+
variant.amount_received = variant.initial_amount
227230
variant.expected_txs = 1
228231
variant.check(variant.initial_txid, variant.initial_amount, variant.confirmation_height)
229232
else:
230-
variant.expected_balance = 0
233+
variant.amount_received = 0
231234
variant.expected_txs = 0
232235
variant.check()
233236

@@ -247,7 +250,7 @@ def run_test(self):
247250
# Check the latest results from getbalance and listtransactions.
248251
for variant in IMPORT_VARIANTS:
249252
self.log.info('Run check for variant {}'.format(variant))
250-
variant.expected_balance += variant.sent_amount
253+
variant.amount_received += variant.sent_amount
251254
variant.expected_txs += 1
252255
variant.check(variant.sent_txid, variant.sent_amount, variant.confirmation_height)
253256

@@ -267,14 +270,45 @@ def run_test(self):
267270
address_type=variant.address_type.value,
268271
))
269272
variant.key = self.nodes[1].dumpprivkey(variant.address["address"])
270-
variant.initial_amount = get_rand_amount()
273+
variant.initial_amount = get_rand_amount() * 2
271274
variant.initial_txid = self.nodes[0].sendtoaddress(variant.address["address"], variant.initial_amount)
272275
variant.confirmation_height = 0
273276
variant.timestamp = timestamp
274277

278+
# Mine a block so these parents are confirmed
279+
assert_equal(len(self.nodes[0].getrawmempool()), len(mempool_variants))
280+
self.sync_mempools()
281+
block_to_disconnect = self.generate(self.nodes[0], 1)[0]
282+
assert_equal(len(self.nodes[0].getrawmempool()), 0)
283+
284+
# For each variant, create an unconfirmed child transaction from initial_txid, sending all
285+
# the funds to an unspendable address. Importantly, no change output is created so the
286+
# transaction can't be recognized using its outputs. The wallet rescan needs to know the
287+
# inputs of the transaction to detect it, so the parent must be processed before the child.
288+
# An equivalent test for descriptors exists in wallet_rescan_unconfirmed.py.
289+
unspent_txid_map = {txin["txid"] : txin for txin in self.nodes[1].listunspent()}
290+
for variant in mempool_variants:
291+
# Send full amount, subtracting fee from outputs, to ensure no change is created.
292+
child = self.nodes[1].send(
293+
add_to_wallet=False,
294+
inputs=[unspent_txid_map[variant.initial_txid]],
295+
outputs=[{ADDRESS_BCRT1_UNSPENDABLE : variant.initial_amount}],
296+
subtract_fee_from_outputs=[0]
297+
)
298+
variant.child_txid = child["txid"]
299+
variant.amount_received = 0
300+
self.nodes[0].sendrawtransaction(child["hex"])
301+
302+
# Mempools should contain the child transactions for each variant.
275303
assert_equal(len(self.nodes[0].getrawmempool()), len(mempool_variants))
276304
self.sync_mempools()
277305

306+
# Mock a reorg so the parent transactions are added back to the mempool
307+
for node in self.nodes:
308+
node.invalidateblock(block_to_disconnect)
309+
# Mempools should now contain the parent and child for each variant.
310+
assert_equal(len(node.getrawmempool()), 2 * len(mempool_variants))
311+
278312
# For each variation of wallet key import, invoke the import RPC and
279313
# check the results from getbalance and listtransactions.
280314
for variant in mempool_variants:
@@ -283,11 +317,15 @@ def run_test(self):
283317
variant.node = self.nodes[2 + IMPORT_NODES.index(ImportNode(variant.prune, expect_rescan))]
284318
variant.do_import(variant.timestamp)
285319
if expect_rescan:
286-
variant.expected_balance = variant.initial_amount
320+
# Ensure both transactions were rescanned. This would raise a JSONRPCError if the
321+
# transactions were not identified as belonging to the wallet.
322+
assert_equal(variant.node.gettransaction(variant.initial_txid)['confirmations'], 0)
323+
assert_equal(variant.node.gettransaction(variant.child_txid)['confirmations'], 0)
324+
variant.amount_received = variant.initial_amount
287325
variant.expected_txs = 1
288-
variant.check(variant.initial_txid, variant.initial_amount)
326+
variant.check(variant.initial_txid, variant.initial_amount, 0)
289327
else:
290-
variant.expected_balance = 0
328+
variant.amount_received = 0
291329
variant.expected_txs = 0
292330
variant.check()
293331

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
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+
"""Test that descriptor wallets rescan mempool transactions properly when importing."""
6+
7+
from test_framework.address import (
8+
address_to_scriptpubkey,
9+
ADDRESS_BCRT1_UNSPENDABLE,
10+
)
11+
from test_framework.messages import COIN
12+
from test_framework.test_framework import BitcoinTestFramework
13+
from test_framework.util import assert_equal
14+
from test_framework.wallet import MiniWallet
15+
from test_framework.wallet_util import test_address
16+
17+
18+
class WalletRescanUnconfirmed(BitcoinTestFramework):
19+
def add_options(self, parser):
20+
self.add_wallet_options(parser, legacy=False)
21+
22+
def set_test_params(self):
23+
self.num_nodes = 1
24+
25+
def skip_test_if_missing_module(self):
26+
self.skip_if_no_wallet()
27+
self.skip_if_no_sqlite()
28+
29+
def run_test(self):
30+
self.log.info("Create wallets and mine initial chain")
31+
node = self.nodes[0]
32+
tester_wallet = MiniWallet(node)
33+
34+
node.createwallet(wallet_name='w0', disable_private_keys=False)
35+
w0 = node.get_wallet_rpc('w0')
36+
37+
self.log.info("Create a parent tx and mine it in a block that will later be disconnected")
38+
parent_address = w0.getnewaddress()
39+
tx_parent_to_reorg = tester_wallet.send_to(
40+
from_node=node,
41+
scriptPubKey=address_to_scriptpubkey(parent_address),
42+
amount=COIN,
43+
)
44+
assert tx_parent_to_reorg["txid"] in node.getrawmempool()
45+
block_to_reorg = self.generate(tester_wallet, 1)[0]
46+
assert_equal(len(node.getrawmempool()), 0)
47+
node.syncwithvalidationinterfacequeue()
48+
assert_equal(w0.gettransaction(tx_parent_to_reorg["txid"])["confirmations"], 1)
49+
50+
# Create an unconfirmed child transaction from the parent tx, sending all
51+
# the funds to an unspendable address. Importantly, no change output is created so the
52+
# transaction can't be recognized using its outputs. The wallet rescan needs to know the
53+
# inputs of the transaction to detect it, so the parent must be processed before the child.
54+
w0_utxos = w0.listunspent()
55+
56+
self.log.info("Create a child tx and wait for it to propagate to all mempools")
57+
# The only UTXO available to spend is tx_parent_to_reorg.
58+
assert_equal(len(w0_utxos), 1)
59+
assert_equal(w0_utxos[0]["txid"], tx_parent_to_reorg["txid"])
60+
tx_child_unconfirmed_sweep = w0.sendall([ADDRESS_BCRT1_UNSPENDABLE])
61+
assert tx_child_unconfirmed_sweep["txid"] in node.getrawmempool()
62+
node.syncwithvalidationinterfacequeue()
63+
64+
self.log.info("Mock a reorg, causing parent to re-enter mempools after its child")
65+
node.invalidateblock(block_to_reorg)
66+
assert tx_parent_to_reorg["txid"] in node.getrawmempool()
67+
68+
self.log.info("Import descriptor wallet on another node")
69+
descriptors_to_import = [{"desc": w0.getaddressinfo(parent_address)['parent_desc'], "timestamp": 0, "label": "w0 import"}]
70+
71+
node.createwallet(wallet_name="w1", disable_private_keys=True)
72+
w1 = node.get_wallet_rpc("w1")
73+
w1.importdescriptors(descriptors_to_import)
74+
75+
self.log.info("Check that the importing node has properly rescanned mempool transactions")
76+
# Check that parent address is correctly determined as ismine
77+
test_address(w1, parent_address, solvable=True, ismine=True)
78+
# This would raise a JSONRPCError if the transactions were not identified as belonging to the wallet.
79+
assert_equal(w1.gettransaction(tx_parent_to_reorg["txid"])["confirmations"], 0)
80+
assert_equal(w1.gettransaction(tx_child_unconfirmed_sweep["txid"])["confirmations"], 0)
81+
82+
if __name__ == '__main__':
83+
WalletRescanUnconfirmed().main()

0 commit comments

Comments
 (0)