Skip to content

wallet: drop spent parents redundant cache invalidation and notification - #35786

Open
furszy wants to merge 3 commits into
bitcoin:masterfrom
furszy:2026_wallet_drop_redundant_dirty_cache
Open

furszy wants to merge 3 commits into
bitcoin:masterfrom
furszy:2026_wallet_drop_redundant_dirty_cache

Conversation

@furszy

@furszy furszy commented Jul 23, 2026 •

Copy link
Copy Markdown
Member

When a transaction spends outputs owned by the wallet, the wallet invalidates
the cached amounts of the transactions those outputs came from, and
CommitTransaction also notifies them. Neither is needed.

Both date back to pre-#27286, when a CWalletTx also cached the available
amount. Now the balance is read live from m_txos and mapTxSpends, and
CWalletTx cache 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.

@DrahtBot

DrahtBot commented Jul 23, 2026 •

Copy link
Copy Markdown
Contributor

The following sections might be updated with supplementary metadata relevant to reviewers and maintainers.

External sites

Reviews

See the guideline and AI policy for information on the review process.

Type Reviewers
Concept ACK w0xlt, rkrux, vicjuma
Stale ACK Bicaru20, pablomartin4btc

If your review is incorrectly listed, please copy-paste <!--meta-tag:bot-skip--> into the comment that the bot should ignore.

Conflicts

Reviewers, this pull request conflicts with the following ones:

  • #36897 (wallet, migration: Contain all legacy wallet and migration related things in its own subdirectory, namespace, and classes by achow101)
  • #36823 (wallet, migration: Skip legacy wallet records rather than erasing them, and drop unused record erase functions by achow101)
  • #36380 (wallet: extend -walletbroadcast to allow initial send only by vasild)
  • #35998 (wallet: Handle or explicitly ignore WalletBatch write failures by achow101)
  • #34872 (wallet: fix mixed-input transaction accounting in history RPCs by w0xlt)
  • #27865 (wallet: Track no-longer-spendable TXOs separately by achow101)

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 pablomartin4btc left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

Comment thread src/wallet/test/wallet_tests.cpp Resolved
Comment thread src/wallet/transaction.h Resolved
Comment thread src/wallet/wallet.cpp Resolved
CachedTxIsFromMe(wallet, wtx)};
}

static void CheckValues(const CWallet& wallet, const Txid& txid, const TxValues& before) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

minor nit: perhaps CheckValuesUnchanged or AssertValuesUnchanged make the intent immediately clear at the call site...

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread src/wallet/test/wallet_tests.cpp Resolved
Comment thread src/wallet/wallet.cpp
}
}

void CWallet::MarkInputsDirty(const CTransactionRef& tx)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@Bicaru20

Copy link
Copy Markdown
Contributor

ACK 0ec1a08.

I agree MarkInputsDirty is no longer needed. As explained in the description, since #27286 CWalletTx no longer saves on cache the amount aviable to spend since this was moved to m_txos and mapTxSpends. Now, the CWalletTx it only save the m_amounts which saves the fixed incoming and outgoing amounts, and the m_cached_from_me which saves whether the tx originated from the wallet.

In bdf7c84, the tests checks, through various paths, that the cached values are not changed. The first test checks the CommitTransaction and AddToWallet path by commiting a transaction that spends from a coin owned by the wallet, and the RecursiveUpdateTxState path by using AbandonTransaction on a spending transaction. The other test, chechs the SyncTransaction path by using transactionAddedToMempool with a spending transaction.

@DrahtBot
DrahtBot requested a review from pablomartin4btc July 29, 2026 19:27
@w0xlt

w0xlt commented Aug 3, 2026

Copy link
Copy Markdown
Contributor

Concept ACK

@rkrux

rkrux commented Aug 26, 2026

Copy link
Copy Markdown
Contributor

Concept ACK 9a075fc

I never preferred reading those mark dirty calls, used to break my flow.
Good that they can be removed now.

@pablomartin4btc pablomartin4btc left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ACK 9a075fc

Confirmed only the typo fix and a rebase since my last review — nothing else changed.

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).
@furszy
furszy force-pushed the 2026_wallet_drop_redundant_dirty_cache branch from 9a075fc to 4591142 Compare September 14, 2026 18:37
@w0xlt

w0xlt commented Sep 15, 2026

Copy link
Copy Markdown
Contributor

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, gettransaction still reports 1 BTC, even though details shows both payments.

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.

diff
diff --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()

@vicjuma vicjuma left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Concept ACK

Comment thread src/wallet/wallet.cpp
}

// Notify that old coins are spent
for (const CTxIn& txin : tx->vin) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The test proves that they are not required post-#27286

Image

The same output is persisted across memory and wallet reload, even with these excluded

Comment thread src/wallet/wallet.cpp
// 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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants