From ed13277dcb8f95f76ffc86ab51c182006997abd9 Mon Sep 17 00:00:00 2001 From: DanS Date: Wed, 28 Oct 2026 12:27:43 -0500 Subject: [PATCH] wallet: do not save over the locator of a rescan that did not complete A rescan started by RPC (rescan, z_importkey, z_importviewingkey, importprivkey) that is cut short by abortrescan or by a stop writes its progress as the best-block locator, or leaves the older locator when it may not advance it. The next start resumes the scan from there. The shutdown save then stamped the wallet tip over that locator, so the next start found nothing to rescan: for a newly imported key, its notes in the unscanned blocks stayed out of the wallet, with no warning, until a manual rescan. On dev a session shorter than an hour never wrote at shutdown, so this is a regression of the shutdown save. ScanForWalletTransactions now records, for the session, where it left the locator on disk: the persisted height when it starts (so a scan that throws counts as incomplete too), the checkpoint or the old locator when it is cut short. A scan that reaches the tip clears this, unless an earlier scan was interrupted and this one starts above where that one left the locator. While it is set, the shutdown save is skipped, as dev would, and logs why. The hourly SetBestChain after abortrescan is unchanged: it stamps the wallet tip as it does on dev. Co-Authored-By: Claude Opus 5.5 --- src/gtest/test_wallet_shutdownsave.cpp | 53 ++++++++++++++++++++++++++ src/wallet/wallet.cpp | 47 +++++++++++++++++++++-- src/wallet/wallet.h | 11 ++++++ 3 files changed, 108 insertions(+), 3 deletions(-) diff --git a/src/gtest/test_wallet_shutdownsave.cpp b/src/gtest/test_wallet_shutdownsave.cpp index ae29fc17c..f5798011e 100644 --- a/src/gtest/test_wallet_shutdownsave.cpp +++ b/src/gtest/test_wallet_shutdownsave.cpp @@ -82,6 +82,59 @@ TEST_F(WalletShutdownSave, SkipsWhenNothingChangedSinceTheLastSave) { EXPECT_EQ("", Reason(wallet, true)); } +// A rescan that did not complete (abortrescan, a stop, a throw) left the locator on disk below the wallet tip: the +// next start resumes from there only if the shutdown does not stamp the tip over it. A later scan clears that once it +// covers the range from where the locator stands. +TEST_F(WalletShutdownSave, SkipsAfterAnIncompleteRescan) { + const std::string incomplete = "a rescan did not complete; the next start resumes it from the locator it left"; + CWallet wallet; + CBlockIndex tip; + tip.SetHeight(841); + wallet.SetWalletTip(&tip); + + // Interrupted after a checkpoint at 833. + EXPECT_EQ(-1, wallet.NoteRescanStarted(821)); + EXPECT_EQ(incomplete, Reason(wallet, true)) << "while it runs"; + wallet.NoteRescanInterrupted(833); + EXPECT_EQ(incomplete, Reason(wallet, true)); + + // A complete scan from above the checkpoint leaves 834.. unscanned from where the disk stands. + int before = wallet.NoteRescanStarted(833); + EXPECT_EQ(833, before); + wallet.NoteRescanCompleted(835, before); + EXPECT_EQ(incomplete, Reason(wallet, true)); + + // One from the block after it covers everything. + before = wallet.NoteRescanStarted(833); + wallet.NoteRescanCompleted(834, before); + EXPECT_EQ("", Reason(wallet, true)); + + // A scan that throws never reports an end. + wallet.NoteRescanStarted(841); + EXPECT_EQ(incomplete, Reason(wallet, true)); + before = wallet.NoteRescanStarted(841); + wallet.NoteRescanCompleted(100, before); + EXPECT_EQ("", Reason(wallet, true)); + + // With nothing interrupted before it, a complete scan is what was asked for, wherever it starts + // (z_importkey with a start height above the locator). + before = wallet.NoteRescanStarted(821); + EXPECT_EQ(-1, before); + wallet.NoteRescanCompleted(840, before); + EXPECT_EQ("", Reason(wallet, true)); + + // No locator on disk: resume from genesis. + wallet.NoteRescanStarted(-1); + wallet.NoteRescanInterrupted(-1); + EXPECT_EQ(incomplete, Reason(wallet, true)); + before = wallet.NoteRescanStarted(-1); + EXPECT_EQ(0, before); + wallet.NoteRescanCompleted(2, before); + EXPECT_EQ(incomplete, Reason(wallet, true)); + wallet.NoteRescanCompleted(1, before); + EXPECT_EQ("", Reason(wallet, true)); +} + // The skip paths log and return without opening the wallet database. TEST_F(WalletShutdownSave, SkippedSaveWritesNothing) { CWallet wallet; diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp index 8994e217f..499dc5ed2 100644 --- a/src/wallet/wallet.cpp +++ b/src/wallet/wallet.cpp @@ -881,6 +881,11 @@ const char* CWallet::ShutdownSaveSkipReason(bool fInitCompleted) LOCK(cs_wallet); if (pindexWalletTip == nullptr) return "the wallet tip is not set"; + // A rescan (rescan, z_importkey, ...) that was cut short wrote its own locator, or could not and + // left the older one. Stamping the wallet tip over that would mark the unscanned range as scanned, + // and a key imported with that scan would never see its notes there. + if (nInterruptedRescanHeight >= 0) + return "a rescan did not complete; the next start resumes it from the locator it left"; if (pindexWalletTip == pindexPersistedTip && nWitnessGeneration == nPersistedWitnessGeneration) return "nothing changed since the last save"; return nullptr; @@ -910,6 +915,31 @@ void CWallet::PersistStateAtShutdown(bool fInitCompleted) nHeight, nTxs, GetTimeMillis() - nStart); } +int CWallet::NoteRescanStarted(int nPersistedHeight) +{ + LOCK(cs_wallet); + // Until the scan completes, assume it ends early, even by throwing: the next start then resumes + // from the locator on disk, as it would without a shutdown save. + int nBefore = nInterruptedRescanHeight; + nInterruptedRescanHeight = std::max(nPersistedHeight, 0); + return nBefore; +} + +void CWallet::NoteRescanInterrupted(int nResumeHeight) +{ + LOCK(cs_wallet); + nInterruptedRescanHeight = std::max(nResumeHeight, 0); +} + +void CWallet::NoteRescanCompleted(int nStartHeight, int nInterruptedBefore) +{ + LOCK(cs_wallet); + // A scan that starts above the locator on disk covers what the caller asked for. It is still + // incomplete if an earlier scan was interrupted and this one starts above where that left off. + if (nInterruptedBefore < 0 || nStartHeight <= nInterruptedBefore + 1) + nInterruptedRescanHeight = -1; +} + bool CWallet::SetBestChainNoFlush(const CBlockLocator& loc) { CWalletDB walletdb(strWalletFile, "r+", false); @@ -3796,20 +3826,30 @@ int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate) // already present. No witness work is needed: witnesses are re-derived from each note's own // witnessHeight, and witnessRootValidated is in-memory-only so every note is revalidated // against hashFinalSaplingRoot on the next start. - auto checkpointProgress = [&](const CBlockIndex* pindexStopped) { + const int nInterruptedBefore = NoteRescanStarted(pindexPersisted ? pindexPersisted->GetHeight() : 0); + + // Returns the height the locator on disk is left at, which the next start resumes from. + auto writeCheckpoint = [&](const CBlockIndex* pindexStopped) { + const int nPersisted = pindexPersisted ? pindexPersisted->GetHeight() : 0; if (!fMayCheckpoint || !pindexStopped || !pindexStopped->pprev) - return; + return nPersisted; const CBlockIndex* pindexDone = pindexStopped->pprev; if (pindexDone->GetHeight() <= pindexPersisted->GetHeight()) - return; // never move the locator backwards + return nPersisted; // never move the locator backwards if (SetBestChainNoFlush(chainActive.GetLocator(pindexDone))) { LogPrintf("%s: checkpointed scan progress at height %d\n", __func__, pindexDone->GetHeight()); + return pindexDone->GetHeight(); } else { LogPrintf("%s: FAILED to checkpoint scan progress at height %d; the scan will replay " "from height %d on the next start\n", __func__, pindexDone->GetHeight(), pindexPersisted->GetHeight()); + return nPersisted; } }; + // Also keeps the shutdown save from stamping the wallet tip over what was written here. + auto checkpointProgress = [&](const CBlockIndex* pindexStopped) { + NoteRescanInterrupted(writeCheckpoint(pindexStopped)); + }; ShowProgress(_("Rescanning..."), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup double dProgressStart = Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), pindex, false); @@ -3887,6 +3927,7 @@ int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate) //Update all witness caches BuildWitnessCache(chainActive.Tip(), false); + NoteRescanCompleted(pindexStart->GetHeight(), nInterruptedBefore); ShowProgress(_("Rescanning..."), 100); // hide progress dialog in GUI } diff --git a/src/wallet/wallet.h b/src/wallet/wallet.h index 89a3c1089..5b4f8e4db 100644 --- a/src/wallet/wallet.h +++ b/src/wallet/wallet.h @@ -1001,6 +1001,10 @@ private: uint64_t nWitnessGeneration = 0; const CBlockIndex* pindexPersistedTip = nullptr; uint64_t nPersistedWitnessGeneration = 0; + // Where a rescan of this session that did not complete left the locator on disk (its checkpoint, + // or the older locator it could not advance), or -1 (guarded by cs_wallet). The next start resumes + // the scan from there, so a shutdown must not stamp the wallet tip over it. + int nInterruptedRescanHeight = -1; void RecordStatePersisted(const CBlockIndex* pindex, uint64_t nGeneration); protected: @@ -1343,6 +1347,13 @@ public: * ShutdownSaveSkipReason says not to. Without it a session shorter than the hourly write never * saves, and the next start rescans and re-extends every witness across the whole session. */ void PersistStateAtShutdown(bool fInitCompleted); + /** Rescan bookkeeping for the shutdown save. A scan reports its start with the height of the + * locator on disk (getting back the height an earlier interrupted scan left, or -1), where it + * stopped if cut short (the height it left the locator at), and its start once it reached the + * tip. Until a scan has covered everything above the locator on disk, a shutdown does not save. */ + int NoteRescanStarted(int nPersistedHeight); + void NoteRescanInterrupted(int nResumeHeight); + void NoteRescanCompleted(int nStartHeight, int nInterruptedBefore); // Seed the block the wallet's state reflects, before ThreadNotifyWallets starts delivering. void SetWalletTip(const CBlockIndex* pindex); /** As SetBestChain, but for use INSIDE a long scan: opens the wallet DB with fFlushOnClose=false