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

Open
furszy wants to merge 3 commits from 2026_wallet_drop_redundant_dirty_cache into master AGit
furszy commented 2026-07-23 19:28:28 +00:00 (Migrated from github.com)

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.

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 commented 2026-07-23 19:28:36 +00:00 (Migrated from github.com)

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.

<!--e57a25ab6845829454e8d69fc972939a--> The following sections might be updated with supplementary metadata relevant to reviewers and maintainers. <!--006a51241073e994b41acfe9ec718e94--> ### External sites * Code coverage & benchmarks: https://corecheck.dev/bitcoin/bitcoin/pulls/35786 * Ralph review <img src=https://review.fish.foo/assets/bitcoin/bitcoin/35786.png alt="Ralph review status"> https://git.fish.foo/bitcoin/bitcoin/pulls/35786#author-ralph <!--021abf342d371248e50ceaed478a90ca--> ### Reviews See [the guideline](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#code-review) and [AI policy](https://github.com/bitcoin/bitcoin/blob/master/doc/AI_POLICY.md) for information on the review process. | Type | Reviewers | | ---- | --------- | | Concept ACK | [w0xlt](https://github.com/bitcoin/bitcoin/pull/35786#issuecomment-5169321351), [rkrux](https://github.com/bitcoin/bitcoin/pull/35786#issuecomment-5424644841), [vicjuma](https://github.com/bitcoin/bitcoin/pull/35786#pullrequestreview-5395131494) | | Stale ACK | [Bicaru20](https://github.com/bitcoin/bitcoin/pull/35786#issuecomment-5122543745), [pablomartin4btc](https://github.com/bitcoin/bitcoin/pull/35786#pullrequestreview-5055081708) | If your review is incorrectly listed, please copy-paste <code>&lt;!--meta-tag:bot-skip--&gt;</code> into the comment that the bot should ignore. <!--174a7506f384e20aa4161008e828411d--> ### Conflicts Reviewers, this pull request conflicts with the following ones: * [#36897](https://github.com/bitcoin/bitcoin/pull/36897) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36897.svg"></sub> (wallet, migration: Contain all legacy wallet and migration related things in its own subdirectory, namespace, and classes by achow101) * [#36823](https://github.com/bitcoin/bitcoin/pull/36823) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36823.svg"></sub> (wallet, migration: Skip legacy wallet records rather than erasing them, and drop unused record erase functions by achow101) * [#36380](https://github.com/bitcoin/bitcoin/pull/36380) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36380.svg"></sub> (wallet: extend -walletbroadcast to allow initial send only by vasild) * [#35998](https://github.com/bitcoin/bitcoin/pull/35998) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/35998.svg"></sub> (wallet: Handle or explicitly ignore `WalletBatch` write failures by achow101) * [#34872](https://github.com/bitcoin/bitcoin/pull/34872) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/34872.svg"></sub> (wallet: fix mixed-input transaction accounting in history RPCs by w0xlt) * [#27865](https://github.com/bitcoin/bitcoin/pull/27865) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/27865.svg"></sub> (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. <!--5faf32d7da4f0f540f40219e4f7537a3-->
pablomartin4btc (Migrated from github.com) reviewed 2026-07-24 19:36:09 +00:00
pablomartin4btc (Migrated from github.com) left a comment

Concept ACK

Checked https://github.com/bitcoin/bitcoin/pull/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).

Concept ACK Checked https://github.com/bitcoin/bitcoin/pull/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).
pablomartin4btc (Migrated from github.com) commented 2026-07-24 18:13:05 +00:00

minor nit: bool is_from_me; (I understand that perhaps it could be mirroring CachedTxIsFromMe in spend.cpp - bool tx_from_me)

minor nit: `bool is_from_me;` (I understand that perhaps it could be mirroring `CachedTxIsFromMe` in [`spend.cpp`](https://github.com/bitcoin/bitcoin/blob/3a2c52f9d70db6076ce64b8f7ef0eb301d7935a5/src/wallet/spend.cpp#L444) - `bool tx_from_me`)
pablomartin4btc (Migrated from github.com) commented 2026-07-24 18:11:46 +00:00

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

minor nit: perhaps `CheckValuesUnchanged` or `AssertValuesUnchanged` make the intent immediately clear at the call site...
pablomartin4btc (Migrated from github.com) commented 2026-07-24 17:27:45 +00:00

typo nit (the body in 59da62d2e28d5986d9445e583663e63c9eed4911 is correct):

    // Now check that abandoning the spending tx does not change the parent cached values either.
typo nit (the body in 59da62d2e28d5986d9445e583663e63c9eed4911 is correct): ```suggestion // Now check that abandoning the spending tx does not change the parent cached values either. ```
Lines 229-234
pablomartin4btc (Migrated from github.com) commented 2026-07-24 17:39:46 +00:00

nit: in fb9c53c515cabbb89ff2429a2c7cd3f9f7da2823, the comment "Only importing a descriptor could make values change" applies to m_cached_from_me too? If so, perhaps could extend it to cover both.

Option A — extend the block comment to cover both fields, drop the separate one:

// Memory only
//
// Represents the incoming/outgoing amounts of this specific tx and whether it
// spends any wallet inputs. Not the final wallet balance.
// Only importing a descriptor could make these values change.
enum AmountType { DEBIT, CREDIT, AMOUNTTYPE_ENUM_ELEMENTS };
mutable CachableAmount m_amounts[AMOUNTTYPE_ENUM_ELEMENTS];
mutable std::optional<bool> m_cached_from_me{std::nullopt};

Option B — keep the separate comment but cross-reference:

  // Cached value for whether the transaction spends any inputs known to the wallet.
  // Same caching semantics as m_amounts: frozen except on descriptor import.
  mutable std::optional<bool> m_cached_from_me{std::nullopt};

Option A seems cleaner.

nit: in fb9c53c515cabbb89ff2429a2c7cd3f9f7da2823, the comment "Only importing a descriptor could make values change" applies to `m_cached_from_me` too? If so, perhaps could extend it to cover both. **Option A** — extend the block comment to cover both fields, drop the separate one: ``` // Memory only // // Represents the incoming/outgoing amounts of this specific tx and whether it // spends any wallet inputs. Not the final wallet balance. // Only importing a descriptor could make these values change. enum AmountType { DEBIT, CREDIT, AMOUNTTYPE_ENUM_ELEMENTS }; mutable CachableAmount m_amounts[AMOUNTTYPE_ENUM_ELEMENTS]; mutable std::optional<bool> m_cached_from_me{std::nullopt}; ``` **Option B** — keep the separate comment but cross-reference: ``` // Cached value for whether the transaction spends any inputs known to the wallet. // Same caching semantics as m_amounts: frozen except on descriptor import. mutable std::optional<bool> m_cached_from_me{std::nullopt}; ``` Option A seems cleaner.
pablomartin4btc (Migrated from github.com) commented 2026-07-24 18:21:52 +00:00

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.

`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.
pablomartin4btc (Migrated from github.com) commented 2026-07-24 18:00:57 +00:00

any parent tx that is wallet-relevant would be its own desc_tx and get MarkDirty() in its own iteration, is that the reasoning? (apart from AddWalletDescriptor calls CWallet::MarkDirty() at the end regardless)?

any parent tx that is wallet-relevant would be its own `desc_tx` and get `MarkDirty()` in its own iteration, is that the reasoning? (apart from `AddWalletDescriptor` [calls](https://github.com/bitcoin/bitcoin/blob/3a2c52f9d70db6076ce64b8f7ef0eb301d7935a5/src/wallet/wallet.cpp#L3855) `CWallet::MarkDirty()` at the end regardless)?
furszy (Migrated from github.com) reviewed 2026-07-27 14:53:26 +00:00
Lines 229-234
furszy (Migrated from github.com) commented 2026-07-27 14:53:26 +00:00

The change values also have the same behaviour. We could probably move the "Only importing a descriptor could make values change" at the top, just below "Memory only" or.. encapsulate all values in a struct. But still, seems a tiny nit we could leave it as is too.

The change values also have the same behaviour. We could probably move the "Only importing a descriptor could make values change" at the top, just below "Memory only" or.. encapsulate all values in a struct. But still, seems a tiny nit we could leave it as is too.
furszy (Migrated from github.com) reviewed 2026-07-27 14:57:48 +00:00
furszy (Migrated from github.com) commented 2026-07-27 14:57:48 +00:00

Not sure I understand the comment. Resetting a transaction's cache when no new descriptor has been imported results on the exact same values being re-computed again.

Not sure I understand the comment. Resetting a transaction's cache when no new descriptor has been imported results on the exact same values being re-computed again.
furszy (Migrated from github.com) reviewed 2026-07-27 15:22:06 +00:00
furszy (Migrated from github.com) commented 2026-07-27 15:22:06 +00:00

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.

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.
furszy (Migrated from github.com) reviewed 2026-07-27 15:23:49 +00:00
furszy (Migrated from github.com) commented 2026-07-27 15:23:49 +00:00

Not sure. Everything is tx based, it is inside the TxValues struct.

Not sure. Everything is tx based, it is inside the TxValues struct.
furszy (Migrated from github.com) reviewed 2026-07-27 15:24:50 +00:00
furszy (Migrated from github.com) commented 2026-07-27 15:24:50 +00:00

done, pushed

done, pushed
Bicaru20 commented 2026-07-29 19:27:35 +00:00 (Migrated from github.com)

ACK 0ec1a08131.

I agree MarkInputsDirty is no longer needed. As explained in the description, since https://github.com/bitcoin/bitcoin/pull/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 bdf7c84eda, 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.

ACK 0ec1a08131. I agree `MarkInputsDirty` is no longer needed. As explained in the description, since https://github.com/bitcoin/bitcoin/pull/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 bdf7c84eda, 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.
w0xlt commented 2026-08-03 16:56:38 +00:00 (Migrated from github.com)

Concept ACK

Concept ACK
DrahtBot commented 2026-08-04 22:54:34 +00:00 (Migrated from github.com)

🐙 This pull request conflicts with the target branch and needs rebase.

<!--cf906140f33d8803c4a75a2196329ecb--> 🐙 This pull request conflicts with the target branch and [needs rebase](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#rebasing-changes).
rkrux commented 2026-08-26 11:30:56 +00:00 (Migrated from github.com)

Concept ACK 9a075fca12

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

Concept ACK 9a075fca1253249a5972f04e8167fb7b2f20a25b I never preferred reading those mark dirty calls, used to break my flow. Good that they can be removed now.
pablomartin4btc (Migrated from github.com) reviewed 2026-08-28 21:06:20 +00:00
pablomartin4btc (Migrated from github.com) left a comment

ACK 9a075fca12

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

ACK 9a075fca1253249a5972f04e8167fb7b2f20a25b Confirmed only the typo [fix](https://github.com/bitcoin/bitcoin/pull/35786#discussion_r3658548501) and a [rebase](https://github.com/bitcoin/bitcoin/compare/0ec1a08131d175f6e2a8cca2bac02beb0e106c34..9a075fca1253249a5972f04e8167fb7b2f20a25b) since my last review — nothing else changed.
DrahtBot commented 2026-09-12 12:02:09 +00:00 (Migrated from github.com)

🐙 This pull request conflicts with the target branch and needs rebase.

<!--cf906140f33d8803c4a75a2196329ecb--> 🐙 This pull request conflicts with the target branch and [needs rebase](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#rebasing-changes).
w0xlt commented 2026-09-15 00:04:45 +00:00 (Migrated from github.com)

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 (51ddab532c) and fails on 4591142a8f: 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()
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 (51ddab532c) and fails on 4591142a8f: 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. <details> <summary>diff</summary> ```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() ``` </details>
vicjuma (Migrated from github.com) reviewed 2026-10-02 21:45:57 +00:00
vicjuma (Migrated from github.com) left a comment

Concept ACK

Concept ACK
vicjuma (Migrated from github.com) commented 2026-10-02 18:07:10 +00:00

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

The test proves that they are not required post-#27286 <img width="3836" height="1474" alt="Image" src="https://git.fish.foo/attachments/fa8bb535-4a9a-4612-8cc5-912016ff27a2" /> The same output is persisted across memory and wallet reload, even with these excluded
vicjuma (Migrated from github.com) commented 2026-10-02 21:45:14 +00:00

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

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
First-time contributor

1 minor finding

🟠 Minor

Keypool top-up can leave a parent’s cached credit stale

Location: src/wallet/wallet.cpp:1418 (base).

gettransaction can omit an output the wallet has since recognized as its own; balances and coin selection are unaffected, and the production impact is unconfirmed.

Details and suggested fix

A keypool top-up can add scripts to the wallet’s cached set, changing whether an output belongs to the wallet. TopUpCallback updates the script cache but does not invalidate cached transaction amounts. If a parent’s credit was cached before a spend triggers a top-up, that credit can remain stale until the parent is re-added or the wallet reloads. gettransaction can then report an amount that omits the output while its details list it. Balances and coin selection are unaffected because they read m_txos, which this path does not refresh. In avoid-reuse wallets, MarkDestinationsDirty may still clear the parent’s cache. Mark wallet transactions with outputs to newly added scripts dirty in TopUpCallback; the comment should also say cached values can change when the wallet’s script set changes, not only on descriptor import. No current production flow that pays a not-yet-derived wallet script was identified, so the frequency of this behavior in production is unconfirmed.

Previous reports

Previous reports of the same concern:

  • src/wallet/wallet.cpp:1418. First reported at 4591142a8fc876d280e0a0a6a61ee3c497010a65. Last checked at 4591142a8fc876d280e0a0a6a61ee3c497010a65.
  • src/wallet/wallet.cpp:1418. First reported at 4591142a8fc876d280e0a0a6a61ee3c497010a65. Last checked at 4591142a8fc876d280e0a0a6a61ee3c497010a65.

Review coverage was incomplete.


Reviewed: 4591142a8fc8 · Full review report · Previous reports

<!-- forgejo-review-bot:bitcoin/bitcoin --> <!-- ralph-engine:current:87bdde6e11c8200ebab55606962dbcbbed1f25d8bebf674c6c6e659db1fe52cc:8f5adaa231eb1aff4d179f52d5ea908b8cc3066455d0b32a1baa87e2b34c9f86 --> <!-- ralph-base:9bf4815b94b9eaf8807f4e569091778da6c338d5 --> <!-- ralph-head:4591142a8fc876d280e0a0a6a61ee3c497010a65 --> <!-- ralph-case:9bfaeb47e246b465afbd96db577d91bb389473d0ac8d0802b22b5afd45942e0a --> 1 minor finding **🟠 Minor** **Keypool top-up can leave a parent’s cached credit stale** Location: [`src/wallet/wallet.cpp:1418`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/cff00c547e7460fa1ec4aa1e38217793593d4263/src/wallet/wallet.cpp#L1418>) (base). `gettransaction` can omit an output the wallet has since recognized as its own; balances and coin selection are unaffected, and the production impact is unconfirmed. <details> <summary>Details and suggested fix</summary> A keypool top-up can add scripts to the wallet’s cached set, changing whether an output belongs to the wallet. `TopUpCallback` updates the script cache but does not invalidate cached transaction amounts. If a parent’s credit was cached before a spend triggers a top-up, that credit can remain stale until the parent is re-added or the wallet reloads. `gettransaction` can then report an `amount` that omits the output while its `details` list it. Balances and coin selection are unaffected because they read `m_txos`, which this path does not refresh. In avoid-reuse wallets, `MarkDestinationsDirty` may still clear the parent’s cache. Mark wallet transactions with outputs to newly added scripts dirty in `TopUpCallback`; the comment should also say cached values can change when the wallet’s script set changes, not only on descriptor import. No current production flow that pays a not-yet-derived wallet script was identified, so the frequency of this behavior in production is unconfirmed. </details> <details> <summary>Previous reports</summary> Previous reports of the same concern: - src/wallet/wallet.cpp:1418. First reported at `4591142a8fc876d280e0a0a6a61ee3c497010a65`. Last checked at `4591142a8fc876d280e0a0a6a61ee3c497010a65`. - src/wallet/wallet.cpp:1418. First reported at `4591142a8fc876d280e0a0a6a61ee3c497010a65`. Last checked at `4591142a8fc876d280e0a0a6a61ee3c497010a65`. </details> Review coverage was incomplete. <!-- Review tier: sensitive --> --- Reviewed: [`4591142a8fc8`](<https://git.fish.foo/bitcoin/bitcoin/commit/4591142a8fc876d280e0a0a6a61ee3c497010a65>) · [Full review report](<https://review.fish.foo/traces/35786-4591142a8fc876d280e0a0a6a61ee3c497010a65-1667-3.html>) · [Previous reports](<https://review.fish.foo/traces/35786/>)
Sign in to join this conversation.
No reviewers
No milestone
No project
No assignees
2 participants
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
bitcoin/bitcoin!35786
No description provided.