Skip to content

wallet: Track no-longer-spendable TXOs separately - #27865

Open
achow101 wants to merge 19 commits into
bitcoin:masterfrom
achow101:wallet-unspent-txos
Open

wallet: Track no-longer-spendable TXOs separately#27865
achow101 wants to merge 19 commits into
bitcoin:masterfrom
achow101:wallet-unspent-txos

Conversation

@achow101

@achow101 achow101 commented Jun 12, 2023

Copy link
Copy Markdown
Member

In #27286, the wallet keeps track of all of its transaction outputs, even if they are already spent or are otherwise unspendable. This TXO set is iterated for balance checking and coin selection preparation, which can still be slow for wallets that have had a lot of activity. This PR aims to improve the performance of such wallets by moving UTXOs that are definitely no longer spendable to a different map in the wallet so that far fewer TXOs need to be iterated for the aforementioned functions.

Unspendable TXOs (not to be confused with Unspent TXOs) are those which have a spending transaction that has been confirmed, or are no longer valid due to reorgs. TXOs that are spent in unconfirmed transactions remain in the primary TXO set, and are filtered out of balance and coin selection as before.

@DrahtBot

DrahtBot commented Jun 12, 2023

Copy link
Copy Markdown
Contributor

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

Code Coverage & Benchmarks

For details see: https://corecheck.dev/bitcoin/bitcoin/pulls/27865.

Reviews

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

Type Reviewers
Concept ACK remyers, murchandamus, jonatack, rkrux, jeanpablojp
Stale ACK w0xlt

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:

  • #35998 (wallet: Handle or explicitly ignore WalletBatch write failures by achow101)
  • #35935 (wallet: Avoid unnecessary wtxvariant rewrites by achow101)
  • #35813 (wallet, rpc: Add listrawtransactions RPC by pablomartin4btc)
  • #35786 (wallet: drop spent parents redundant cache invalidation and notification by furszy)
  • #35760 (wallet: make corrupted transaction records fail wallet loading instead of forcing a rescan by achow101)
  • #35716 (wallet: Replace mapWallet and wtxOrdered with a boost::multi_index by achow101)
  • #35569 (Encapsulation for CTransaction by purpleKarrot)
  • #35511 (RFC: consensus: Make CAmount a class by hodlinator)
  • #35294 (wallet: Update tx chain state during loading during AttachChain instead of before by achow101)
  • #35151 (wallet, follow-up: Refactor IsSpent to use HowSpent by musaHaruna)
  • #34909 (wallet, refactor: modularise wallet by extracting out legacy wallet migration by rkrux)
  • #34681 (wallet: move rescan logic into ChainScanner and wallet/scan by Eunovo)
  • #32895 (wallet: Prepare for future upgrades by recording versions of last client to open and decrypt by achow101)
  • #29278 (Wallet: Add maxfeerate wallet startup option by ismaelsadeeq)

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.

This was referenced Jun 12, 2023
@achow101
achow101 force-pushed the wallet-unspent-txos branch from 6925928 to 7a50755 Compare June 28, 2023 17:53
@achow101
achow101 force-pushed the wallet-unspent-txos branch 2 times, most recently from 8c4b04a to 9730ec0 Compare June 28, 2023 22:26
@DrahtBot

DrahtBot commented Aug 6, 2026

Copy link
Copy Markdown
Contributor

🚧 At least one of the CI tasks failed.
Task test ancestor commits: https://github.com/bitcoin/bitcoin/actions/runs/31057160752/job/92477056845
LLM reason (✨ experimental): CI failed due to a C++ build error: wallet.cpp references wtx.tx->version but wallet::CWalletTx has no member tx (clang compile error in bitcoin_wallet).

Hints

Try to run the tests locally, according to the documentation. However, a CI failure may still
happen due to a number of reasons, for example:

  • Possibly due to a silent merge conflict (the changes in this pull request being
    incompatible with the current code in the target branch). If so, make sure to rebase on the latest
    commit of the target branch.

  • A sanitizer issue, which can only be found by compiling with the sanitizer and running the
    affected test.

  • An intermittent issue.

Leave a comment here, if you need help tracking down a confusing failure.

w0xlt and others added 19 commits August 11, 2026 12:41
The send RPC can be used to create a double spend of a confirmed
transaction which is added unconditionally to the wallet as an inactive
transaction. The test ensures that the transaction is in the wallet and
that the balance is still being counted correctly.
m_from_me is used to track whether a transaction is "from me", i.e. has
any inputs which belong to the wallet.
Instead of looking at the cached amounts or searching every input of a
transaction each time we want to determine whether it is "from me", use
m_from_me  which stores this value for us.
The states will be updated whenever CWaleltTx::SetState is called too.
This is achieved by having CWalletTx::SetState take a function that
applies the new state to the specified TXO. This ensures that CWalletTx
states and WalletTXO states are kept in sync.
Perform the transaction reorder upgrade immediately after loading txs
instead of waiting for the end of loading.
Since we need to know whether the transaction that creates a WalletTXO
is "from me", we should store this state in the WalletTXO too, copied
from its parent CWalletTx.
WalletTXOs need to know their parent tx's timestamp for AvailableCoins
to work.
A min_conf parameter is added to IsSpent so that it can set a
confirmation threshold for whether something is considered spent.
When a block is disconnected, we need to process the transactions in
reverse order so that the wallet's TXO set is updated in the correct
order.
CWallet::Create will properly connect the wallet to the chain, so we
should be doing that rather than ad-hoc chain connection.
Definitely unusable TXOs are those that are spent by a confirmed
transaction or were produced by a now conflicted transaction. However,
we still need them for GetDebit, so we store them in a separate
m_unusable_txos container. MarkConflicted, AbandonTransaction, and
loading (via PruneSpentTXOs) will ensure that these unusable TXOs are
properly moved.
@DrahtBot

Copy link
Copy Markdown
Contributor

🚧 At least one of the CI tasks failed.
Task fuzzer,address,undefined,integer: https://github.com/bitcoin/bitcoin/actions/runs/31529803354/job/95329356632
LLM reason (✨ experimental): Fuzz test failure: UndefinedBehaviorSanitizer reported an invalid-enum-load (runtime error) in wallet::CWallet::RefreshTXOsFromTx (wallet.cpp:4698) while running wallet_create_transaction.

Hints

Try to run the tests locally, according to the documentation. However, a CI failure may still
happen due to a number of reasons, for example:

  • Possibly due to a silent merge conflict (the changes in this pull request being
    incompatible with the current code in the target branch). If so, make sure to rebase on the latest
    commit of the target branch.

  • A sanitizer issue, which can only be found by compiling with the sanitizer and running the
    affected test.

  • An intermittent issue.

Leave a comment here, if you need help tracking down a confusing failure.

@DrahtBot

Copy link
Copy Markdown
Contributor

Could turn into draft while CI is red?

@jeanpablojp jeanpablojp 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

After a reorg and abandontransaction, an output that should be spendable again is missing from the balance and from listunspent until the wallet is reloaded. Trusted 150 BTC against 200 on 512dc9af1b. And after removeprunedfunds, a block-conflicted output can take the node down on the next getbalances, tripping Assert(tx_depth >= 0). Both are inline, and neither happens on the base.

test

The reorg has to be deep enough for the coinbase to be immature at the new tip, otherwise the spend goes back to the mempool. Restarting the node rebuilds the containers and hides it.

self.generatetoaddress(node, 1, w.getnewaddress())
c_txid = node.getblock(node.getblockhash(1))["tx"][0]
self.generatetoaddress(node, COINBASE_MATURITY, w.getnewaddress())
o = next(u for u in w.listunspent() if u["txid"] == c_txid)

t1 = w.send(outputs=[{w.getnewaddress(): o["amount"] - Decimal("0.001")}],
            inputs=[{"txid": o["txid"], "vout": o["vout"]}], add_inputs=False)["txid"]
self.generatetoaddress(node, 1, w.getnewaddress())

node.invalidateblock(node.getblockhash(COINBASE_MATURITY))
assert_equal(node.getrawmempool(), [])
assert_equal(w.gettransaction(t1)["confirmations"], 0)
self.generatetoaddress(node, 5, w.getnewaddress())

w.abandontransaction(t1)
assert any(u["txid"] == c_txid for u in w.listunspent(minconf=0))

Built this and the base and ran the wallet tests.

Comment thread src/wallet/wallet.cpp
std::pair<CWallet::TXOMap::iterator, CWallet::TXOMap::iterator> CWallet::MaybeMarkTXOUsable(const COutPoint& outpoint)
{
AssertLockHeld(cs_wallet);
if (IsSpent(outpoint)) {

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.

min_depth left at the default instead of the 1 that matches m_unusable_txos's definition. An output spent by a transaction that confirms and is then unconfirmed by a reorg doesn't come back, and abandontransaction doesn't either, since RecursiveUpdateTxState only walks the transaction's outputs and never its inputs. With 1 the wallet functional tests still pass and the case goes away.

Comment thread src/wallet/wallet.cpp
it->second.SetTxFromMe(*wtx.m_from_me);
} else {
WalletTXO txo{txout, wtx.GetState(), wtx.IsCoinBase(), *wtx.m_from_me, wtx.GetTxTime(), wtx.GetTx()->version};
bool is_unusable = m_last_block_processed_height >= 0 && IsSpent(outpoint, /*min_depth=*/1);

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 is missing the TxStateBlockConflicted check that PruneSpentTXOs does. RemoveTxs exposes it, since it clears the containers before rebuilding. Mirroring PruneSpentTXOs here makes the balance match the base again.

Comment thread src/wallet/walletdb.cpp
result = std::max(result, tx_res.m_result);

// Upgrade each CWalletTx missing m_from_me
if (any_missing_from_me) {

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.

ReorderTransactions used to sit after LoadWallet's if (result != DBErrors::LOAD_OK) return result;, and now both it and the new upgrade loop run before that return. With one corrupt tx record, loadwallet fails and the intact records still get rewritten, 310 to 311 bytes here.

Comment thread src/wallet/wallet.cpp
it->second.SetState(wtx.GetState());
it->second.SetTxFromMe(*wtx.m_from_me);
} else {
WalletTXO txo{txout, wtx.GetState(), wtx.IsCoinBase(), *wtx.m_from_me, wtx.GetTxTime(), wtx.GetTx()->version};

@jeanpablojp jeanpablojp Aug 27, 2026

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.

m_from_me is an optional<bool> and CWalletTx(tx, state) doesn't set it. That's the three red fuzz jobs, all on wallet_create_transaction, with UBSan reporting invalid-enum-load and MSan the libc++ hardening assertion on operator*. The RefreshTXOsFromTx call there came in with #35790. LoadToWallet guards with has_value(), but the precondition isn't documented anywhere and the method is public.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.