Skip to content

Commit 7d33ae7

Browse files
committed
Merge bitcoin/bitcoin#27145: wallet: when a block is disconnected, update transactions that are no longer conflicted
89df798 Add wallets_conflicts (Antoine Riard) dced203 wallet, tests: mark unconflicted txs as inactive (ishaanam) 096487c wallet: introduce generic recursive tx state updating function (ishaanam) Pull request description: This implements a fix for #7315. Previously when a block was disconnected any transactions that were conflicting with transactions mined in that block were not updated to be marked as inactive. The fix implemented here is described on the [Bitcoin DevWiki](https://github.com/bitcoin-core/bitcoin-devwiki/wiki/Wallet-Transaction-Conflict-Tracking#idea-refresh-conflicted). A test which tested the previous behavior has also been updated. Second attempt at #17543 ACKs for top commit: achow101: ACK 89df798 rajarshimaitra: tACK 89df798. glozow: ACK 89df798 furszy: Tested ACK 89df798 Tree-SHA512: 3133b151477e8818302fac29e96de30cd64c09a8fe3a7612074a34ba1a332e69148162e6cb3f1074d9d9c9bab5ef9996967d325d8c4c99ba42b5fe3b66a60546
2 parents 927b001 + 89df798 commit 7d33ae7

File tree

5 files changed

+212
-57
lines changed

5 files changed

+212
-57
lines changed

src/wallet/wallet.cpp

Lines changed: 72 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -1266,11 +1266,6 @@ bool CWallet::AbandonTransaction(const uint256& hashTx)
12661266
{
12671267
LOCK(cs_wallet);
12681268

1269-
WalletBatch batch(GetDatabase());
1270-
1271-
std::set<uint256> todo;
1272-
std::set<uint256> done;
1273-
12741269
// Can't mark abandoned if confirmed or in mempool
12751270
auto it = mapWallet.find(hashTx);
12761271
assert(it != mapWallet.end());
@@ -1279,44 +1274,25 @@ bool CWallet::AbandonTransaction(const uint256& hashTx)
12791274
return false;
12801275
}
12811276

1282-
todo.insert(hashTx);
1283-
1284-
while (!todo.empty()) {
1285-
uint256 now = *todo.begin();
1286-
todo.erase(now);
1287-
done.insert(now);
1288-
auto it = mapWallet.find(now);
1289-
assert(it != mapWallet.end());
1290-
CWalletTx& wtx = it->second;
1291-
int currentconfirm = GetTxDepthInMainChain(wtx);
1292-
// If the orig tx was not in block, none of its spends can be
1293-
assert(currentconfirm <= 0);
1294-
// if (currentconfirm < 0) {Tx and spends are already conflicted, no need to abandon}
1295-
if (currentconfirm == 0 && !wtx.isAbandoned()) {
1296-
// If the orig tx was not in block/mempool, none of its spends can be in mempool
1297-
assert(!wtx.InMempool());
1277+
auto try_updating_state = [](CWalletTx& wtx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet) {
1278+
// If the orig tx was not in block/mempool, none of its spends can be.
1279+
assert(!wtx.isConfirmed());
1280+
assert(!wtx.InMempool());
1281+
// If already conflicted or abandoned, no need to set abandoned
1282+
if (!wtx.isConflicted() && !wtx.isAbandoned()) {
12981283
wtx.m_state = TxStateInactive{/*abandoned=*/true};
1299-
wtx.MarkDirty();
1300-
batch.WriteTx(wtx);
1301-
NotifyTransactionChanged(wtx.GetHash(), CT_UPDATED);
1302-
// Iterate over all its outputs, and mark transactions in the wallet that spend them abandoned too.
1303-
// States are not permanent, so these transactions can become unabandoned if they are re-added to the
1304-
// mempool, or confirmed in a block, or conflicted.
1305-
// Note: If the reorged coinbase is re-added to the main chain, the descendants that have not had their
1306-
// states change will remain abandoned and will require manual broadcast if the user wants them.
1307-
for (unsigned int i = 0; i < wtx.tx->vout.size(); ++i) {
1308-
std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range = mapTxSpends.equal_range(COutPoint(now, i));
1309-
for (TxSpends::const_iterator iter = range.first; iter != range.second; ++iter) {
1310-
if (!done.count(iter->second)) {
1311-
todo.insert(iter->second);
1312-
}
1313-
}
1314-
}
1315-
// If a transaction changes 'conflicted' state, that changes the balance
1316-
// available of the outputs it spends. So force those to be recomputed
1317-
MarkInputsDirty(wtx.tx);
1284+
return TxUpdate::NOTIFY_CHANGED;
13181285
}
1319-
}
1286+
return TxUpdate::UNCHANGED;
1287+
};
1288+
1289+
// Iterate over all its outputs, and mark transactions in the wallet that spend them abandoned too.
1290+
// States are not permanent, so these transactions can become unabandoned if they are re-added to the
1291+
// mempool, or confirmed in a block, or conflicted.
1292+
// Note: If the reorged coinbase is re-added to the main chain, the descendants that have not had their
1293+
// states change will remain abandoned and will require manual broadcast if the user wants them.
1294+
1295+
RecursiveUpdateTxState(hashTx, try_updating_state);
13201296

13211297
return true;
13221298
}
@@ -1333,13 +1309,29 @@ void CWallet::MarkConflicted(const uint256& hashBlock, int conflicting_height, c
13331309
if (conflictconfirms >= 0)
13341310
return;
13351311

1312+
auto try_updating_state = [&](CWalletTx& wtx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet) {
1313+
if (conflictconfirms < GetTxDepthInMainChain(wtx)) {
1314+
// Block is 'more conflicted' than current confirm; update.
1315+
// Mark transaction as conflicted with this block.
1316+
wtx.m_state = TxStateConflicted{hashBlock, conflicting_height};
1317+
return TxUpdate::CHANGED;
1318+
}
1319+
return TxUpdate::UNCHANGED;
1320+
};
1321+
1322+
// Iterate over all its outputs, and mark transactions in the wallet that spend them conflicted too.
1323+
RecursiveUpdateTxState(hashTx, try_updating_state);
1324+
1325+
}
1326+
1327+
void CWallet::RecursiveUpdateTxState(const uint256& tx_hash, const TryUpdatingStateFn& try_updating_state) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet) {
13361328
// Do not flush the wallet here for performance reasons
13371329
WalletBatch batch(GetDatabase(), false);
13381330

13391331
std::set<uint256> todo;
13401332
std::set<uint256> done;
13411333

1342-
todo.insert(hashTx);
1334+
todo.insert(tx_hash);
13431335

13441336
while (!todo.empty()) {
13451337
uint256 now = *todo.begin();
@@ -1348,14 +1340,12 @@ void CWallet::MarkConflicted(const uint256& hashBlock, int conflicting_height, c
13481340
auto it = mapWallet.find(now);
13491341
assert(it != mapWallet.end());
13501342
CWalletTx& wtx = it->second;
1351-
int currentconfirm = GetTxDepthInMainChain(wtx);
1352-
if (conflictconfirms < currentconfirm) {
1353-
// Block is 'more conflicted' than current confirm; update.
1354-
// Mark transaction as conflicted with this block.
1355-
wtx.m_state = TxStateConflicted{hashBlock, conflicting_height};
1343+
1344+
TxUpdate update_state = try_updating_state(wtx);
1345+
if (update_state != TxUpdate::UNCHANGED) {
13561346
wtx.MarkDirty();
13571347
batch.WriteTx(wtx);
1358-
// Iterate over all its outputs, and mark transactions in the wallet that spend them conflicted too
1348+
// Iterate over all its outputs, and update those tx states as well (if applicable)
13591349
for (unsigned int i = 0; i < wtx.tx->vout.size(); ++i) {
13601350
std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range = mapTxSpends.equal_range(COutPoint(now, i));
13611351
for (TxSpends::const_iterator iter = range.first; iter != range.second; ++iter) {
@@ -1364,7 +1354,12 @@ void CWallet::MarkConflicted(const uint256& hashBlock, int conflicting_height, c
13641354
}
13651355
}
13661356
}
1367-
// If a transaction changes 'conflicted' state, that changes the balance
1357+
1358+
if (update_state == TxUpdate::NOTIFY_CHANGED) {
1359+
NotifyTransactionChanged(wtx.GetHash(), CT_UPDATED);
1360+
}
1361+
1362+
// If a transaction changes its tx state, that usually changes the balance
13681363
// available of the outputs it spends. So force those to be recomputed
13691364
MarkInputsDirty(wtx.tx);
13701365
}
@@ -1459,8 +1454,36 @@ void CWallet::blockDisconnected(const interfaces::BlockInfo& block)
14591454
// future with a stickier abandoned state or even removing abandontransaction call.
14601455
m_last_block_processed_height = block.height - 1;
14611456
m_last_block_processed = *Assert(block.prev_hash);
1457+
1458+
int disconnect_height = block.height;
1459+
14621460
for (const CTransactionRef& ptx : Assert(block.data)->vtx) {
14631461
SyncTransaction(ptx, TxStateInactive{});
1462+
1463+
for (const CTxIn& tx_in : ptx->vin) {
1464+
// No other wallet transactions conflicted with this transaction
1465+
if (mapTxSpends.count(tx_in.prevout) < 1) continue;
1466+
1467+
std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range = mapTxSpends.equal_range(tx_in.prevout);
1468+
1469+
// For all of the spends that conflict with this transaction
1470+
for (TxSpends::const_iterator _it = range.first; _it != range.second; ++_it) {
1471+
CWalletTx& wtx = mapWallet.find(_it->second)->second;
1472+
1473+
if (!wtx.isConflicted()) continue;
1474+
1475+
auto try_updating_state = [&](CWalletTx& tx) {
1476+
if (!tx.isConflicted()) return TxUpdate::UNCHANGED;
1477+
if (tx.state<TxStateConflicted>()->conflicting_block_height >= disconnect_height) {
1478+
tx.m_state = TxStateInactive{};
1479+
return TxUpdate::CHANGED;
1480+
}
1481+
return TxUpdate::UNCHANGED;
1482+
};
1483+
1484+
RecursiveUpdateTxState(wtx.tx->GetHash(), try_updating_state);
1485+
}
1486+
}
14641487
}
14651488
}
14661489

src/wallet/wallet.h

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -334,6 +334,13 @@ class CWallet final : public WalletStorage, public interfaces::Chain::Notificati
334334
/** Mark a transaction (and its in-wallet descendants) as conflicting with a particular block. */
335335
void MarkConflicted(const uint256& hashBlock, int conflicting_height, const uint256& hashTx);
336336

337+
enum class TxUpdate { UNCHANGED, CHANGED, NOTIFY_CHANGED };
338+
339+
using TryUpdatingStateFn = std::function<TxUpdate(CWalletTx& wtx)>;
340+
341+
/** Mark a transaction (and its in-wallet descendants) as a particular tx state. */
342+
void RecursiveUpdateTxState(const uint256& tx_hash, const TryUpdatingStateFn& try_updating_state) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
343+
337344
/** Mark a transaction's inputs dirty, thus forcing the outputs to be recomputed */
338345
void MarkInputsDirty(const CTransactionRef& tx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
339346

test/functional/test_runner.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,8 @@
196196
'wallet_watchonly.py --legacy-wallet',
197197
'wallet_watchonly.py --usecli --legacy-wallet',
198198
'wallet_reorgsrestore.py',
199+
'wallet_conflicts.py --legacy-wallet',
200+
'wallet_conflicts.py --descriptors',
199201
'interface_http.py',
200202
'interface_rpc.py',
201203
'interface_usdt_coinselection.py',

test/functional/wallet_abandonconflict.py

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -226,20 +226,16 @@ def run_test(self):
226226
assert_equal(double_spend["walletconflicts"], [txAB1])
227227

228228
# Verify that B and C's 10 BTC outputs are available for spending again because AB1 is now conflicted
229+
assert_equal(alice.gettransaction(txAB1)["confirmations"], -1)
229230
newbalance = alice.getbalance()
230231
assert_equal(newbalance, balance + Decimal("20"))
231232
balance = newbalance
232233

233-
# There is currently a minor bug around this and so this test doesn't work. See Issue #7315
234-
# Invalidate the block with the double spend and B's 10 BTC output should no longer be available
235-
# Don't think C's should either
234+
# Invalidate the block with the double spend. B & C's 10 BTC outputs should no longer be available
236235
self.nodes[0].invalidateblock(self.nodes[0].getbestblockhash())
236+
assert_equal(alice.gettransaction(txAB1)["confirmations"], 0)
237237
newbalance = alice.getbalance()
238-
#assert_equal(newbalance, balance - Decimal("10"))
239-
self.log.info("If balance has not declined after invalidateblock then out of mempool wallet tx which is no longer")
240-
self.log.info("conflicted has not resumed causing its inputs to be seen as spent. See Issue #7315")
241-
assert_equal(balance, newbalance)
242-
238+
assert_equal(newbalance, balance - Decimal("20"))
243239

244240
if __name__ == '__main__':
245241
AbandonConflictTest().main()

test/functional/wallet_conflicts.py

Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
#!/usr/bin/env python3
2+
# Copyright (c) 2023 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+
6+
"""
7+
Test that wallet correctly tracks transactions that have been conflicted by blocks, particularly during reorgs.
8+
"""
9+
10+
from decimal import Decimal
11+
12+
from test_framework.test_framework import BitcoinTestFramework
13+
from test_framework.util import (
14+
assert_equal,
15+
)
16+
17+
class TxConflicts(BitcoinTestFramework):
18+
def add_options(self, parser):
19+
self.add_wallet_options(parser)
20+
21+
def set_test_params(self):
22+
self.num_nodes = 3
23+
24+
def skip_test_if_missing_module(self):
25+
self.skip_if_no_wallet()
26+
27+
def get_utxo_of_value(self, from_tx_id, search_value):
28+
return next(tx_out["vout"] for tx_out in self.nodes[0].gettransaction(from_tx_id)["details"] if tx_out["amount"] == Decimal(f"{search_value}"))
29+
30+
def run_test(self):
31+
self.log.info("Send tx from which to conflict outputs later")
32+
txid_conflict_from_1 = self.nodes[0].sendtoaddress(self.nodes[0].getnewaddress(), Decimal("10"))
33+
txid_conflict_from_2 = self.nodes[0].sendtoaddress(self.nodes[0].getnewaddress(), Decimal("10"))
34+
self.generate(self.nodes[0], 1)
35+
self.sync_blocks()
36+
37+
self.log.info("Disconnect nodes to broadcast conflicts on their respective chains")
38+
self.disconnect_nodes(0, 1)
39+
self.disconnect_nodes(2, 1)
40+
41+
self.log.info("Create transactions that conflict with each other")
42+
output_A = self.get_utxo_of_value(from_tx_id=txid_conflict_from_1, search_value=10)
43+
output_B = self.get_utxo_of_value(from_tx_id=txid_conflict_from_2, search_value=10)
44+
45+
# First create a transaction that consumes both A and B outputs.
46+
#
47+
# | tx1 | -----> | | | |
48+
# | AB_parent_tx | ----> | Child_Tx |
49+
# | tx2 | -----> | | | |
50+
#
51+
inputs_tx_AB_parent = [{"txid": txid_conflict_from_1, "vout": output_A}, {"txid": txid_conflict_from_2, "vout": output_B}]
52+
tx_AB_parent = self.nodes[0].signrawtransactionwithwallet(self.nodes[0].createrawtransaction(inputs_tx_AB_parent, {self.nodes[0].getnewaddress(): Decimal("19.99998")}))
53+
54+
# Secondly, create two transactions: One consuming output_A, and another one consuming output_B
55+
#
56+
# | tx1 | -----> | Tx_A_1 |
57+
# ----------------
58+
# | tx2 | -----> | Tx_B_1 |
59+
#
60+
inputs_tx_A_1 = [{"txid": txid_conflict_from_1, "vout": output_A}]
61+
inputs_tx_B_1 = [{"txid": txid_conflict_from_2, "vout": output_B}]
62+
tx_A_1 = self.nodes[0].signrawtransactionwithwallet(self.nodes[0].createrawtransaction(inputs_tx_A_1, {self.nodes[0].getnewaddress(): Decimal("9.99998")}))
63+
tx_B_1 = self.nodes[0].signrawtransactionwithwallet(self.nodes[0].createrawtransaction(inputs_tx_B_1, {self.nodes[0].getnewaddress(): Decimal("9.99998")}))
64+
65+
self.log.info("Broadcast conflicted transaction")
66+
txid_AB_parent = self.nodes[0].sendrawtransaction(tx_AB_parent["hex"])
67+
self.generate(self.nodes[0], 1, sync_fun=self.no_op)
68+
69+
# Now that 'AB_parent_tx' was broadcast, build 'Child_Tx'
70+
output_c = self.get_utxo_of_value(from_tx_id=txid_AB_parent, search_value=19.99998)
71+
inputs_tx_C_child = [({"txid": txid_AB_parent, "vout": output_c})]
72+
73+
tx_C_child = self.nodes[0].signrawtransactionwithwallet(self.nodes[0].createrawtransaction(inputs_tx_C_child, {self.nodes[0].getnewaddress() : Decimal("19.99996")}))
74+
tx_C_child_txid = self.nodes[0].sendrawtransaction(tx_C_child["hex"])
75+
self.generate(self.nodes[0], 1, sync_fun=self.no_op)
76+
77+
self.log.info("Broadcast conflicting tx to node 1 and generate a longer chain")
78+
conflicting_txid_A = self.nodes[1].sendrawtransaction(tx_A_1["hex"])
79+
self.generate(self.nodes[1], 4, sync_fun=self.no_op)
80+
conflicting_txid_B = self.nodes[1].sendrawtransaction(tx_B_1["hex"])
81+
self.generate(self.nodes[1], 4, sync_fun=self.no_op)
82+
83+
self.log.info("Connect nodes 0 and 1, trigger reorg and ensure that the tx is effectively conflicted")
84+
self.connect_nodes(0, 1)
85+
self.sync_blocks([self.nodes[0], self.nodes[1]])
86+
conflicted_AB_tx = self.nodes[0].gettransaction(txid_AB_parent)
87+
tx_C_child = self.nodes[0].gettransaction(tx_C_child_txid)
88+
conflicted_A_tx = self.nodes[0].gettransaction(conflicting_txid_A)
89+
90+
self.log.info("Verify, after the reorg, that Tx_A was accepted, and tx_AB and its Child_Tx are conflicting now")
91+
# Tx A was accepted, Tx AB was not.
92+
assert conflicted_AB_tx["confirmations"] < 0
93+
assert conflicted_A_tx["confirmations"] > 0
94+
95+
# Conflicted tx should have confirmations set to the confirmations of the most conflicting tx
96+
assert_equal(-conflicted_AB_tx["confirmations"], conflicted_A_tx["confirmations"])
97+
# Child should inherit conflicted state from parent
98+
assert_equal(-tx_C_child["confirmations"], conflicted_A_tx["confirmations"])
99+
# Check the confirmations of the conflicting transactions
100+
assert_equal(conflicted_A_tx["confirmations"], 8)
101+
assert_equal(self.nodes[0].gettransaction(conflicting_txid_B)["confirmations"], 4)
102+
103+
self.log.info("Now generate a longer chain that does not contain any tx")
104+
# Node2 chain without conflicts
105+
self.generate(self.nodes[2], 15, sync_fun=self.no_op)
106+
107+
# Connect node0 and node2 and wait reorg
108+
self.connect_nodes(0, 2)
109+
self.sync_blocks()
110+
conflicted = self.nodes[0].gettransaction(txid_AB_parent)
111+
tx_C_child = self.nodes[0].gettransaction(tx_C_child_txid)
112+
113+
self.log.info("Test that formerly conflicted transaction are inactive after reorg")
114+
# Former conflicted tx should be unconfirmed as it hasn't been yet rebroadcast
115+
assert_equal(conflicted["confirmations"], 0)
116+
# Former conflicted child tx should be unconfirmed as it hasn't been rebroadcast
117+
assert_equal(tx_C_child["confirmations"], 0)
118+
# Rebroadcast former conflicted tx and check it confirms smoothly
119+
self.nodes[2].sendrawtransaction(conflicted["hex"])
120+
self.generate(self.nodes[2], 1)
121+
self.sync_blocks()
122+
former_conflicted = self.nodes[0].gettransaction(txid_AB_parent)
123+
assert_equal(former_conflicted["confirmations"], 1)
124+
assert_equal(former_conflicted["blockheight"], 217)
125+
126+
if __name__ == '__main__':
127+
TxConflicts().main()

0 commit comments

Comments
 (0)