Repository navigation
Conversation
|
The following sections might be updated with supplementary metadata relevant to reviewers and maintainers. External sites
ReviewsSee the guideline and AI policy for information on the review process.
If your review is incorrectly listed, please copy-paste ConflictsReviewers, this pull request conflicts with the following ones:
If you consider this pull request important, please also help to review the conflicting pull requests. Ideally, start with the one that should be merged first. |
pablomartin4btc
left a comment
There was a problem hiding this comment.
Concept ACK
Checked #27286.
After the above PR, the per-transaction caches (m_amounts, m_cached_from_me) reflect the transaction's own incoming/outgoing amounts — none of these change when a child tx spends one of the parent's outputs. So MarkInputsDirty is forcing a recompute that produces the same result, and the CommitTransaction notification loop is asking the GUI to repaint a row that looks identical. Both are dead work; removing them is correct.
Left some comments and nits (none blocking).
| CachedTxIsFromMe(wallet, wtx)}; | ||
| } | ||
|
|
||
| static void CheckValues(const CWallet& wallet, const Txid& txid, const TxValues& before) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet) |
There was a problem hiding this comment.
minor nit: perhaps CheckValuesUnchanged or AssertValuesUnchanged make the intent immediately clear at the call site...
There was a problem hiding this comment.
I don't think this add much value, the intent should be clear enough as is now. But could change it if you are strong on it.
| } | ||
| } | ||
|
|
||
| void CWallet::MarkInputsDirty(const CTransactionRef& tx) |
There was a problem hiding this comment.
MarkInputsDirty was actually a slightly misleading name (it marks the parent transactions dirty, not the inputs themselves), so removing it entirely is the best outcome.
6b6236c to
0ec1a08
Compare
|
ACK 0ec1a08. I agree In bdf7c84, the tests checks, through various paths, that the cached values are not changed. The first test checks the |
|
Concept ACK |
0ec1a08 to
9a075fc
Compare
|
Concept ACK 9a075fc I never preferred reading those mark dirty calls, used to break my flow. |
CWalletTx caches its own incoming and outgoing amounts, not the wallet available balance. Which means spending one of its outputs do not change the cache in any way, in the same way, abandoning the spend does not change it either. The cache can become stalled only when a descriptor is imported.
Since bitcoin#27286 the CWalletTx amounts cache does not contain the available amount anymore, only the per-tx incoming and outgoing amounts, these are frozen except when new descriptor is imported. This means we no longer need to mark the parent txs of a spend as dirty and recompute their values. We can drop the MarkDirty loop in CommitTransaction along with the MarkInputsDirty calls in AddToWallet, SyncTransaction and RecursiveUpdateTxState, which do the same on the block, mempool, abandon and conflict paths. The single mentioned import case exception is already covered by AddWalletDescriptor, which calls MarkDirty itself. So we can safely delete MarkInputsDirty.
When the wallet creates a spend, CommitTransaction notifies the new tx and every wallet tx it spends from. But no other spending path does this: SyncTransaction, for a spend arriving from the mempool or a block, notifies only the tx it was given, and RecursiveUpdateTxState, for abandoning one, notifies only the txs whose own state changed. The ones whose outputs become spendable again did not change state, so they are not notified either. On top of that, the GUI is the only consumer, and neither of its two subscribers needs it. The transaction table takes the CT_UPDATED and marks the notified tx row for a status refresh, but that status comes from the tx's own depth, maturity and abandoned flag, and from whether it is trusted. A spend changes none of that, and the amounts are not part of the refresh (which are actually not changed during a spend).
9a075fc to
4591142
Compare
|
This invalidation is still needed in a narrow case. A transaction pays 1 BTC to each of two wallet addresses, but the wallet hasn’t derived one address yet, so it recognizes and caches only 1 BTC. A later spend can expand the keypool and make the wallet recognize the second payment. Without this invalidation, The test below passes on master (51ddab5) and fails on 4591142: the parent’s amount remains 1 BTC when 2 BTC is expected. It’s a very narrow edge case, but it may still be worth addressing. diffdiff --git a/test/functional/wallet_keypool_topup.py b/test/functional/wallet_keypool_topup.py
index aae6985f5b..a8277bb231 100755
--- a/test/functional/wallet_keypool_topup.py
+++ b/test/functional/wallet_keypool_topup.py
@@ -11,8 +11,11 @@ Two nodes. Node1 is under test. Node0 is providing transactions and generating b
- Stop node1, clear the datadir, move wallet file back into the datadir and restart node1.
- connect node1 to node0. Verify that they sync and node1 receives its funds."""
import shutil
+from decimal import Decimal
from test_framework.blocktools import COINBASE_MATURITY
+from test_framework.descriptors import descsum_create
+from test_framework.extendedkey import ExtendedPrivateKey
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import (
assert_equal,
@@ -88,6 +91,64 @@ class KeypoolRestoreTest(BitcoinTestFramework):
elif output_type == 'bech32m':
assert_equal(self.nodes[idx].getaddressinfo(self.nodes[idx].getnewaddress(address_type=output_type))['hdkeypath'], "m/86h/1h/0h/0/110")
+ self.test_cached_parent_credit()
+
+ def test_cached_parent_credit(self):
+ self.log.info("Test parent credit is refreshed when a spend expands the keypool")
+ self.restart_node(1, extra_args=['-keypool=1'])
+ self.connect_nodes(0, 1)
+ self.sync_all()
+
+ for delivery in ("mempool", "block"):
+ self.log.info(f"Test keypool expansion via a {delivery} notification")
+ wallet_name = f"cached_credit_{delivery}"
+ self.nodes[1].createwallet(wallet_name, blank=True)
+ wallet = self.nodes[1].get_wallet_rpc(wallet_name)
+ desc = descsum_create(f"wpkh({ExtendedPrivateKey.generate().to_string()}/*)")
+ assert_equal(wallet.importdescriptors([{
+ "desc": desc,
+ "timestamp": "now",
+ "range": [0, 0],
+ "active": True,
+ }]), [{"success": True}])
+ addresses = self.nodes[0].deriveaddresses(desc, [0, 2])
+
+ # Index 2 is outside the keypool even after receiving at index 0
+ # extends it to index 1. Keep these outputs in this order.
+ raw_parent = self.nodes[0].createrawtransaction([], [{addresses[2]: 1}, {addresses[0]: 1}])
+ funded_parent = self.nodes[0].fundrawtransaction(raw_parent, {"changePosition": 2})
+ signed_parent = self.nodes[0].signrawtransactionwithwallet(funded_parent["hex"])
+ parent_txid = self.nodes[0].sendrawtransaction(signed_parent["hex"])
+ self.generate(self.nodes[0], 1)
+
+ # Populate the parent's credit cache before index 2 becomes owned.
+ parent = wallet.gettransaction(parent_txid)
+ assert_equal(parent["amount"], 1)
+ assert_equal(len(parent["details"]), 1)
+ assert_equal(wallet.getaddressinfo(addresses[2])["ismine"], False)
+
+ raw_spend = self.nodes[0].createrawtransaction(
+ [{"txid": parent_txid, "vout": 1}], [{addresses[1]: Decimal("0.9999")}])
+ signed_spend = wallet.signrawtransactionwithwallet(raw_spend)
+ assert_equal(signed_spend["complete"], True)
+ if delivery == "block":
+ self.disconnect_nodes(0, 1)
+ assert_equal(self.nodes[1].getconnectioncount(), 0)
+ self.nodes[0].sendrawtransaction(signed_spend["hex"])
+ if delivery == "block":
+ self.generate(self.nodes[0], 1, sync_fun=self.no_op)
+ self.connect_nodes(0, 1)
+ self.sync_all()
+ else:
+ self.sync_mempools()
+
+ # Processing the spend at index 1 extends the keypool to index 2,
+ # making the parent's other output ours without a descriptor import.
+ assert_equal(wallet.getaddressinfo(addresses[2])["ismine"], True)
+ parent = wallet.gettransaction(parent_txid)
+ assert_equal(len(parent["details"]), 2)
+ assert_equal(parent["amount"], 2)
+
if __name__ == '__main__':
KeypoolRestoreTest(__file__).main() |
| } | ||
|
|
||
| // Notify that old coins are spent | ||
| for (const CTxIn& txin : tx->vin) { |
There was a problem hiding this comment.
The test proves that they are not required post-#27286
The same output is persisted across memory and wallet reload, even with these excluded
| // If a transaction changes 'conflicted' state, that changes the balance | ||
| // available of the outputs it spends. So force those to be | ||
| // recomputed, also: | ||
| MarkInputsDirty(ptx); |
There was a problem hiding this comment.
This appears to be outside the confines of the PR description as pointed out by @w0xlt because of the keypool logic. Commenting it out in my master branch removes the invalidation logic, which leads to the unexpected behavior. Probably it should be retained for recomputations

When a transaction spends outputs owned by the wallet, the wallet invalidates
the cached amounts of the transactions those outputs came from, and
CommitTransactionalso notifies them. Neither is needed.Both date back to pre-#27286, when a
CWalletTxalso cached the availableamount. Now the balance is read live from
m_txosandmapTxSpends, andCWalletTxcache only its own, tx specific, incoming and outgoing amounts,and whether the tx is from the wallet. None of this changes after one of its
outputs is spent. So the cache invalidation recomputes the same values, and
the notification makes the GUI refresh a status that has not changed.