Skip to content

wallet: make corrupted transaction records fail wallet loading instead of forcing a rescan - #35760

Open
achow101 wants to merge 5 commits into
bitcoin:masterfrom
achow101:wallet-rm-needs-rescan
Open

achow101 wants to merge 5 commits into
bitcoin:masterfrom
achow101:wallet-rm-needs-rescan

Conversation

@achow101

Copy link
Copy Markdown
Member

In wallet loading, the NEED_RESCAN enum was only ever returned if the stored hash of a transaction did not match the calculated hash of the transaction. This would then trigger a rescan from genesis during loading, and then allow the wallet to be operational as if it were normal.

However, it seems incorrect to be treating such corruption as acceptable. That transaction would be inserted to mapWallet, but not be added to mapTxSpends or any of the conflict tracking or to TXO caching. Furthermore, the rescan doesn't actually fix the problem, the incorrect record would persist, which means that the wallet would be rescanning the entire chain every time it is loaded. The only situation this could occur is if the wallet actually experienced corruption, so it's reasonable to return CORRUPT instead and force the user to load a backup or otherwise un-corrupt the wallet before it can be used.

Implements the idea from #35501 (comment)

@DrahtBot

DrahtBot commented Jul 20, 2026 •

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/35760.

Reviews

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

Type Reviewers
Concept ACK polespinasa, jonatack, rkrux
Approach ACK pablomartin4btc, jeanpablojp

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:

  • #36167 (build: Enable -Wunused by fanquake)
  • #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.

Approach ACK at fdd1a43

When a tx record's stored hash doesn't match the hash of its deserialized content, returning NEED_RESCAN was the wrong response: the rescan is not a reliable repair — it only overwrites the corrupted DB record as a side effect if the tx happens to be on-chain and wallet-relevant; if it isn't, the corrupted record stays in the DB permanently and the wallet rescans from genesis on every subsequent load. I think failing hard with CORRUPT makes no unverifiable assumptions about what the DB was supposed to contain, and signals unambiguous failure rather than attempting an unreliable recovery.

Having said that, the error message "Error loading %s: Wallet corrupted" gives the user no indication of what to do next.

Since this is a user-visible behaviour change — wallet now fails to load instead of triggering a rescan — some release note seems required.

As a side effect, bitcoin-wallet info on a wallet with this corruption previously printed a misleading "Rescanning wallet" warning to stdout and silently exited with an error code — the tool never calls AttachChain so no rescan would ever run. It now correctly prints "Wallet corrupted" to stderr (but still no indication to the user of what to do next).

One suggestion: a unit test that writes a tx record with a mismatched key to the DB and asserts loading fails with CORRUPT would pin this behaviour and prevent regressions. I have one ready at 5e32122 on top of this PR if useful.

@pablomartin4btc

Copy link
Copy Markdown
Member

The PR correctly surfaces the corruption at load time rather than silently rescanning forever. The missing piece for users is what to do when they see that error — opened #35944 which adds a "Recovering from a Corrupted Wallet" section to doc/managing-wallets.md to address that gap.

Also worth noting: walletdb.cpp:1050 has an error message that still says "This can be fixed by removing transactions from wallet and rescanning." — that message covers a different corruption path but contradicts the same user-facing guidance. Could be addressed here since this PR is already touching the corruption detection code.

@polespinasa

Copy link
Copy Markdown
Member

opened #35944 which adds a "Recovering from a Corrupted Wallet" section to doc/managing-wallets.md to address that gap

That's a small doc change probably worth adding here as an extra commit, as both PRs are small and related. I don't think there's the need for be looking for reviewers and going through the ACK process twice :)

@polespinasa polespinasa 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.

Aproach ACK

How can I test this?

@achow101

Copy link
Copy Markdown
Member Author

How can I test this?

Open a wallet file with sqlite, find a tx record and change the hash.

@jonatack

Copy link
Copy Markdown
Member

Concept ACK. Worth a release note?

@pablomartin4btc

Copy link
Copy Markdown
Member

How can I test this?

Open a wallet file with sqlite, find a tx record and change the hash.

I've suggested a unit test earlier that writes a tx record with a mismatched key to the DB and asserts loading fails with CORRUPT -> 5e32122.

Comment thread src/wallet/walletdb.cpp Resolved
@achow101
achow101 force-pushed the wallet-rm-needs-rescan branch from 304ec37 to 98045fe Compare August 19, 2026 20:36
@achow101

Copy link
Copy Markdown
Member Author

I've suggested a unit test earlier that writes a tx record with a mismatched key to the DB and asserts loading fails with CORRUPT -> 5e32122.

Pulled the test

Worth a release note?

Added a release note

@polespinasa

Copy link
Copy Markdown
Member

I just came with a concern regarding this change.

Before this PR a corrupted wallet would be anyway loaded after a rescan and would still show be able to spend funds, maybe not all due to corruption, but the valid and non-corrupted tx entries.

If we disable allowing this corrupted wallets, users that unconsciously did not create a backup will be unable to access any of their funds at all without switching to an old Core version.

Comment thread src/wallet/walletdb.cpp Resolved
Comment thread src/wallet/test/walletload_tests.cpp Resolved
Comment thread src/wallet/test/walletload_tests.cpp Resolved
achow101 and others added 5 commits August 21, 2026 13:27
If the wallet fails to load a transaction from the database, the wallet
is corrupted.
DBErrors::NEED_RESCAN is no longer returned by any part of wallet
loading, so it can be deleted. AttachChain's rescan_required parameter
was only ever set to true when NEED_RESCAN was returned, so this can be
removed as well.
Verifies that a tx record whose DB key does not match the hash of its
serialised transaction causes `PopulateWalletFromDB` to return
`DBErrors::CORRUPT`, pinning the behaviour introduced in this PR and
preventing regressions.
Adds section 1.7 "Recovering from a Corrupted Wallet" to
doc/managing-wallets.md. The section documents that restoring from a
known-good backup is the only supported recovery path for corrupted
wallet databases, and that there is no safe in-place repair mechanism.

Motivated by achow101's conclusion in bitcoin#35605: "we should make the only
supported corruption recovery mechanism be to restore a backup and not
do any of this stuff with maybe being able to recover."
@achow101
achow101 force-pushed the wallet-rm-needs-rescan branch from 98045fe to 1e45c91 Compare August 21, 2026 20:29
@achow101

Copy link
Copy Markdown
Member Author

If we disable allowing this corrupted wallets, users that unconsciously did not create a backup will be unable to access any of their funds at all without switching to an old Core version.

The user experience of such wallets is already pretty awful and I would expect there to be issues opened if anyone is actually running into this today.

@bitcoin bitcoin deleted a comment from Amarrufo-1 Aug 21, 2026
@polespinasa

Copy link
Copy Markdown
Member

The user experience of such wallets is already pretty awful and I would expect there to be issues opened if anyone is actually running into this today.

Yes I don't disagree with this, I am only pointing out that even if the experience is awful, might be the only way to recover funds o part of the funds.

Maybe we could think in some way we can help the user instead of prohibiting access to the funds. If the transactions are the only thing corrupted we could give the user the option to list the descriptors so he can create a blank wallet and import them to recover funds. Or something like that, it's just an idea.

@rkrux

rkrux commented Aug 26, 2026

Copy link
Copy Markdown
Contributor

Concept ACK 1e45c91

I do prefer the wallet to stop and fail fast instead of trying to fix rare corrupted scenarios automatically everytime on load, which makes the wallet do too much and bloats the codebase as well. Ideally the corrupted scenarios of write time should fail-fast while writing itself (which I see might not be possible in every such case) instead of the read flow taking on the onus of fixing - unfortunate that the wallet has been doing this already and setting such a precedent.

There indeed is a slight concern regarding the user not being able to access the funds if the backup is not there, which is also not ideal though in the first place. But I don't think the wallet should preemptively try to fix automatically at load time as such corrupted scenarios should be very unlikely.

force the user to load a backup or otherwise un-corrupt the wallet before it can be used.

Is there even a way for the user to un-corrupt the wallet?

@achow101

Copy link
Copy Markdown
Member Author

Is there even a way for the user to un-corrupt the wallet?

Depends on their knowledge of the wallet. You can always use sqlite to manually modify records directly, outside of the wallet.

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

Approach ACK

Built it, ran the unit tests and the wallet functional tests, and reproduced the corruption on regtest.

The description says the tx is inserted into mapWallet but not added to mapTxSpends. That stopped being true in #35501, where LoadToWallet started getting called on the mismatch path too. With the old code put back here, IsSpent on the prevout returns true. The rest of the argument, the record that stays behind and the rescan on every load, still holds.

Comment thread src/wallet/walletdb.cpp
CWalletTx wtx{deserialize, value, ReadWtxVariants(batch, hash)};
if (wtx.GetHash() != hash) {
result = std::max(result, DBErrors::NEED_RESCAN);
err = strprintf("Error: Corrupt transaction. Stored hash of %s but an actual hash of %s", wtx.GetHash().ToString(), hash.ToString());

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 two are swapped. In the description you call the DB key the stored hash and wtx.GetHash() the calculated one, and here the strprintf passes them the other way round. The new test writes under a zeroed key, so this is what it prints.

Stored hash of 7c2ae489...40fe but an actual hash of 0000...0000

Anyone looking for that record in sqlite by the message searches for a key that isn't there.

@polespinasa

polespinasa commented Aug 31, 2026 •

Copy link
Copy Markdown
Member

Depends on their knowledge of the wallet. You can always use sqlite to manually modify records directly, outside of the wallet.

I don't think that is an option lol.

But I don't think the wallet should preemptively try to fix automatically at load time as such corrupted scenarios should be very unlikely.

I was not referring to fix corrupted scenarios on load, but to just let them load, with a big warning, if I am not wrong a corrupted wallet can still work, just the corrupted entries will not. That is a partial access to the funds which is, imho, better than 0 access. As I mentioned in #35760 (comment), imagine if the wallet is corrupted, instead of throwing, just return a message saying the wallet is corrupted, here are your private descriptors (if wallet is unlocked) so the user can import them to some other place. I don't think that is too much complexity and it's not trying to fix the corrupt state. The user will fix it by importing descriptors to a new wallet.

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

I'm in between a N-A-C-K for locking out the user and A-C-K for nonconsequential recans. IMO the rescans are friendlier than loss of funds:-)

Comment thread src/wallet/walletdb.cpp
@@ -1031,15 +1039,16 @@ static DBErrors LoadTxRecords(CWallet* pwallet, DatabaseBatch& batch, bool& any_
try {
CWalletTx wtx{deserialize, value, ReadWtxVariants(batch, hash)};
if (wtx.GetHash() != hash) {
result = std::max(result, DBErrors::NEED_RESCAN);
err = strprintf("Error: Corrupt transaction. Stored hash of %s but an actual hash of %s", wtx.GetHash().ToString(), hash.ToString());
return DBErrors::CORRUPT;

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.

I’m literally of two minds about this PR. This early return means locking the user out of their wallet and their funds, wallet-load rescan on the other hand somehow sucks. Reproduced the rescan via a mutation test

 CWalletTx wtx{deserialize, value, ReadWtxVariants(batch, hash)};
  if (true) {
      result = std::max(result, DBErrors::NEED_RESCAN);
  }
  1. Create wallet: ./bitcoin-cli createwallet pr35760
  2. Generate the address: ./bitcoin-cli -named getnewaddress address_type=bech32m [bcrt1ps7q4t7jflcwmsk4gg4dxx47gfagzd8jwsjtafsaw6yh48e7fhvss3gtw4e]
  3. Generate 100000 blocks: ./bitcoin-cli generatetoaddress 100000 bcrt1ps7q4t7jflcwmsk4gg4dxx47gfagzd8jwsjtafsaw6yh48e7fhvss3gtw4e
  4. ./bitcoin-cli loadwallet pr35760

Just these blocks took quite some time, but was eventually successful, allowing further actions

Image

This return means that the user is denied all these. The initial error might be enough to notify the user of the need to export the necessary wallet info into a cleaner wallet (if the damage isn't that big) instead of locking them out completely, unless there is another way of doing this other than

force the user to load a backup or otherwise un-corrupt the wallet before it can be used

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.

CORRUPT enum variant could still be used though instead of NEED_RESCAN. The return on mismatch is the issue here. Maybe I am missing something here

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.

8 participants