From 693f81bbbaea5f3a796d4ea31988db61157957f7 Mon Sep 17 00:00:00 2001 From: DanS Date: Wed, 28 Oct 2026 10:36:23 -0500 Subject: [PATCH 1/9] wallet: save witnesses and the best block at a clean shutdown FlushStateToDisk writes the wallet's SetBestChain at most once an hour, the shutdown flush included, and its timer starts at "now" on the first call. A session shorter than an hour therefore never saves: the next start rescans every block of the session ("Rescanning last N blocks"), re-extends every note witness across it, and then rewrites the whole wallet inside init before RPC answers. Measured on regtest with a throwaway prototype: restarts of 8.3 s -> 2.0 s (150 empty blocks), 29 s -> 2.5 s (150 blocks, 639 commitments), 66 s -> 8.5 s (8,215 notes, 631 MB wallet). The cost moves to the stop, at about 41 MB/s of wallet.dat. Add CWallet::PersistStateAtShutdown(), called from Shutdown() inside the existing cs_main block right after the chainstate flush and before the coins view and the wallet are torn down. It calls SetBestChain(chainActive.GetLocator()), which on this tree stamps pindexWalletTip, the block the wallet's state reflects, in the same atomic transaction as the witnesses. It logs "Saving wallet state ..." first, so a GUI can show that the stop is busy, and then the height, the txs written, the elapsed ms and whether it committed. It skips the write, and logs why, when: - AppInit2 did not run to the end (new fInitCompleted): threads were interrupted but not joined, and with no wallet tip SetBestChain would stamp the chain tip over an interrupted rescan's checkpoint; - the shutdown came from the wallet failing on a block (NotifyWalletsOrShutdown now sets fWalletNotifyFailed), or the BDB environment has panicked or a checkpoint/lsn_reset failed (new CDBEnv::IsHealthy()): a full-wallet write into that database fails or deepens the damage, and the logs are what recovery needs; - nothing changed since the last committed save. SetBestChain now returns SetBestChainINTERNAL's result (the CValidationInterface hook returns bool) and, when it committed, records the block it stamped and a generation counter that BuildWitnessCache (when it extended), DecrementNoteWitnesses, VerifyAndSetInitialWitness reseeds, ClearNoteWitnessCache and AddToWallet (a note-bearing tx inserted or changed) bump. Init records the same when it finds the locator at the tip and does not rescan. This also stops a second full write when the hourly SetBestChain happens to fire in the shutdown flush. FlushStateToDisk and DATABASE_WRITE_INTERVAL are unchanged: dropping the throttle for FLUSH_STATE_ALWAYS would also rewrite the whole wallet on every gettxoutsetinfo and on the init flush after a replay. witnessRootValidated stays in memory only, so every witness is still root-checked against hashFinalSaplingRoot on the next start, and a kill during the write rolls back to the previous save (DB_RECOVER). Co-Authored-By: Claude Opus 5.5 --- src/Makefile.gtest.include | 3 +- src/gtest/test_wallet_dbenv.cpp | 20 ++++++ src/gtest/test_wallet_shutdownsave.cpp | 94 ++++++++++++++++++++++++++ src/init.cpp | 17 ++++- src/validationinterface.cpp | 3 + src/validationinterface.h | 6 +- src/wallet/db.cpp | 11 +++ src/wallet/db.h | 3 + src/wallet/wallet.cpp | 84 ++++++++++++++++++++++- src/wallet/wallet.h | 25 ++++++- 10 files changed, 258 insertions(+), 8 deletions(-) create mode 100644 src/gtest/test_wallet_shutdownsave.cpp diff --git a/src/Makefile.gtest.include b/src/Makefile.gtest.include index eb985f328..a2cfac6d3 100644 --- a/src/Makefile.gtest.include +++ b/src/Makefile.gtest.include @@ -20,7 +20,8 @@ hush_gtest_SOURCES = \ gtest/test_fd_defense.cpp \ gtest/test_wallet_dbenv.cpp \ gtest/test_wallet_notecache.cpp \ - gtest/test_wallet_history.cpp + gtest/test_wallet_history.cpp \ + gtest/test_wallet_shutdownsave.cpp hush_gtest_CPPFLAGS = $(AM_CPPFLAGS) -DMULTICORE -fopenmp -DBINARY_OUTPUT -DCURVE_ALT_BN128 -DSTATIC $(BITCOIN_INCLUDES) hush_gtest_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS) diff --git a/src/gtest/test_wallet_dbenv.cpp b/src/gtest/test_wallet_dbenv.cpp index 9cb0ce327..2d564abc5 100644 --- a/src/gtest/test_wallet_dbenv.cpp +++ b/src/gtest/test_wallet_dbenv.cpp @@ -56,3 +56,23 @@ TEST_F(WalletDbEnv, FailedCheckpointKeepsTheLogs) { env.Flush(true); EXPECT_TRUE(boost::filesystem::exists(Log())); } + +// The shutdown wallet save asks before writing: a failed flush or a panicked environment means the logs are what +// recovery needs, and a large write into it would fail or make things worse. +TEST_F(WalletDbEnv, HealthyUntilAFlushFailsOrTheEnvironmentPanics) { + EXPECT_TRUE(env.IsHealthy()); + env.Flush(false); + EXPECT_TRUE(env.IsHealthy()); + ASSERT_EQ(0, env.dbenv->set_flags(DB_PANIC_ENVIRONMENT, 1)); + EXPECT_FALSE(env.IsHealthy()); +} + +TEST_F(WalletDbEnv, UnhealthyAfterAFailedCheckpoint) { + env.CheckpointLSN("no-such-file.dat"); // lsn_reset fails + EXPECT_FALSE(env.IsHealthy()); +} + +TEST(WalletDbEnvNotOpen, NotOpenIsHealthy) { + CDBEnv env; + EXPECT_TRUE(env.IsHealthy()); +} diff --git a/src/gtest/test_wallet_shutdownsave.cpp b/src/gtest/test_wallet_shutdownsave.cpp new file mode 100644 index 000000000..ae29fc17c --- /dev/null +++ b/src/gtest/test_wallet_shutdownsave.cpp @@ -0,0 +1,94 @@ +// Copyright (c) 2016-2024 The Hush developers +// Distributed under the GPLv3 software license, see the accompanying +// file COPYING or https://www.gnu.org/licenses/gpl-3.0.en.html + +#include + +#include + +#include "chain.h" +#include "validationinterface.h" +#include "wallet/wallet.h" + +namespace { + +std::string Reason(CWallet& wallet, bool fInitCompleted) +{ + const char* reason = wallet.ShutdownSaveSkipReason(fInitCompleted); + return reason ? reason : ""; +} + +// fWalletNotifyFailed is process-wide, and other suites drive NotifyWalletsOrShutdown's failure path. +class WalletShutdownSave : public ::testing::Test { +protected: + void SetUp() override { fWalletNotifyFailed = false; } + void TearDown() override { fWalletNotifyFailed = false; } +}; + +} + +// A startup that failed or was cut short never writes: its threads were not joined, and an unset wallet +// tip would make SetBestChain stamp the chain tip over an interrupted rescan's checkpoint. +TEST_F(WalletShutdownSave, SkipsWhenStartupDidNotComplete) { + CWallet wallet; + CBlockIndex tip; + wallet.SetWalletTip(&tip); + EXPECT_EQ("startup did not complete", Reason(wallet, false)); + EXPECT_EQ("", Reason(wallet, true)); +} + +TEST_F(WalletShutdownSave, SkipsWithoutAWalletTip) { + CWallet wallet; + EXPECT_EQ("the wallet tip is not set", Reason(wallet, true)); +} + +// A shutdown caused by the wallet failing on a block must not write the whole wallet into that database. +TEST_F(WalletShutdownSave, SkipsAfterAWalletFailure) { + CWallet wallet; + CBlockIndex tip; + wallet.SetWalletTip(&tip); + fWalletNotifyFailed = true; + EXPECT_EQ("the wallet failed to process a block", Reason(wallet, true)); + fWalletNotifyFailed = false; + EXPECT_EQ("", Reason(wallet, true)); +} + +// Once a save (or init, finding nothing to rescan) has recorded the wallet's block, a shutdown writes again +// only if the wallet moved to another block or its note state changed. +TEST_F(WalletShutdownSave, SkipsWhenNothingChangedSinceTheLastSave) { + CWallet wallet; + CBlockIndex a, b; + a.SetHeight(10); + b.SetHeight(11); + b.pprev = &a; + + wallet.SetWalletTip(&a); + EXPECT_EQ("", Reason(wallet, true)); + wallet.MarkStatePersisted(&a); + EXPECT_EQ("nothing changed since the last save", Reason(wallet, true)); + + wallet.SetWalletTip(&b); + EXPECT_EQ("", Reason(wallet, true)) << "a new block"; + wallet.MarkStatePersisted(&b); + EXPECT_EQ("nothing changed since the last save", Reason(wallet, true)); + + wallet.ClearNoteWitnessCache(); + EXPECT_EQ("", Reason(wallet, true)) << "witnesses changed at the same block"; + wallet.MarkStatePersisted(&b); + EXPECT_EQ("nothing changed since the last save", Reason(wallet, true)); + + // A save recorded at another block than the one the wallet is at does not count. + wallet.MarkStatePersisted(&a); + EXPECT_EQ("", Reason(wallet, true)); +} + +// The skip paths log and return without opening the wallet database. +TEST_F(WalletShutdownSave, SkippedSaveWritesNothing) { + CWallet wallet; + CBlockIndex tip; + wallet.SetWalletTip(&tip); + wallet.MarkStatePersisted(&tip); + LOCK(cs_main); + ASSERT_NO_THROW(wallet.PersistStateAtShutdown(true)); + ASSERT_NO_THROW(wallet.PersistStateAtShutdown(false)); +} diff --git a/src/init.cpp b/src/init.cpp index 7e296bebd..452e53988 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -99,6 +99,9 @@ extern void hush_init(int32_t height); CWallet* pwalletMain = NULL; #endif bool fFeeEstimatesInitialized = false; +// AppInit2 ran to the end and is returning success, so AppInit joins every thread before Shutdown(). +// On any other path Shutdown() runs with threads only interrupted and must not write wallet state. +static std::atomic fInitCompleted(false); #ifdef WIN32 // Win32 LevelDB doesn't use file descriptors, and the ones used for @@ -257,6 +260,12 @@ void Shutdown() LOCK(cs_main); if (pcoinsTip != NULL) { FlushStateToDisk(); +#ifdef ENABLE_WALLET + // The hourly SetBestChain in FlushStateToDisk rarely fires here, so a session shorter + // than an hour would otherwise never save its witnesses and best block. + if (pwalletMain) + pwalletMain->PersistStateAtShutdown(fInitCompleted); +#endif } if (pcoinsTip != NULL) { delete pcoinsTip; @@ -2662,6 +2671,9 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler) pindexRescan = FindForkInGlobalIndex(chainActive, locator); else pindexRescan = chainActive.Genesis(); + // Nothing to rescan: the wallet as loaded is what the last save wrote at this block. + if (pindexRescan != NULL && pindexRescan == chainActive.Tip()) + pwalletMain->MarkStatePersisted(pindexRescan); } if (chainActive.Tip() && chainActive.Tip() != pindexRescan) { @@ -2922,5 +2934,8 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler) if(fDebug) fprintf(stderr,"%s end fRequestShutdown=%d\n", __FUNCTION__, !!fRequestShutdown); - return !fRequestShutdown; + bool fOk = !fRequestShutdown; + if (fOk) + fInitCompleted = true; + return fOk; } diff --git a/src/validationinterface.cpp b/src/validationinterface.cpp index 4de52d6f2..1c680cdf6 100644 --- a/src/validationinterface.cpp +++ b/src/validationinterface.cpp @@ -20,6 +20,8 @@ static CMainSignals g_signals; +std::atomic fWalletNotifyFailed(false); + CMainSignals& GetMainSignals() { return g_signals; @@ -103,6 +105,7 @@ bool NotifyWalletsOrShutdown(const std::function& notify) PrintExceptionContinue(NULL, "ThreadNotifyWallets()"); } LogPrintf("*** %s\n", "Wallet failed to process a block notification; shutting down"); + fWalletNotifyFailed = true; StartShutdown(); uiInterface.ThreadSafeMessageBox( _("Error: A fatal internal error occurred, see debug.log for details"), diff --git a/src/validationinterface.h b/src/validationinterface.h index 98b17abdf..ad3b1d1a7 100644 --- a/src/validationinterface.h +++ b/src/validationinterface.h @@ -8,6 +8,7 @@ #define HUSH_VALIDATIONINTERFACE_H #include +#include #include #include "zcash/IncrementalMerkleTree.hpp" @@ -31,6 +32,9 @@ void UnregisterAllValidationInterfaces(); void EraseFromWallets(const uint256 &hash); /** Rescan all registered wallets */ void RescanWallets(); +/** Set when a wallet failed to process a block notification and the node is shutting down because of it: + * the shutdown must not then try to write the whole wallet into the database that just failed. */ +extern std::atomic fWalletNotifyFailed; class CValidationInterface { protected: @@ -39,7 +43,7 @@ protected: virtual void EraseFromWallet(const uint256 &hash) {} virtual void RescanWallet() {} virtual void ChainTip(const CBlockIndex *pindex, const CBlock *pblock, boost::optional> added) {} - virtual void SetBestChain(const CBlockLocator &locator) {} + virtual bool SetBestChain(const CBlockLocator &locator) { return true; } virtual void UpdatedTransaction(const uint256 &hash) {} virtual void ResendWalletTransactions(int64_t nBestBlockTime) {} virtual void BlockChecked(const CBlock&, const CValidationState&) {} diff --git a/src/wallet/db.cpp b/src/wallet/db.cpp index 5f2df38a3..44ae47cb2 100644 --- a/src/wallet/db.cpp +++ b/src/wallet/db.cpp @@ -483,6 +483,17 @@ bool CDB::Rewrite(const string& strFile, const char* pszSkip) } +bool CDBEnv::IsHealthy() +{ + if (fKeepLogs) + return false; + if (!fDbEnvInit) + return true; + // get_flags itself fails with DB_RUNRECOVERY once the environment has panicked. + u_int32_t envFlags = 0; + return dbenv->get_flags(&envFlags) == 0 && !(envFlags & DB_PANIC_ENVIRONMENT); +} + void CDBEnv::Flush(bool fShutdown) { int64_t nStart = GetTimeMillis(); diff --git a/src/wallet/db.h b/src/wallet/db.h index 73ea50e43..599e33e0e 100644 --- a/src/wallet/db.h +++ b/src/wallet/db.h @@ -100,6 +100,9 @@ public: bool Open(const boost::filesystem::path& path); void Close(); void Flush(bool fShutdown); + //! False once a checkpoint or lsn_reset has failed or the environment has panicked (BDB0060): a + //! large write into it then fails or deepens the damage, and the logs are what recovery needs. + bool IsHealthy(); void CheckpointLSN(const std::string& strFile); void CloseDb(const std::string& strFile); diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp index f3f098589..08a9d3ffc 100644 --- a/src/wallet/wallet.cpp +++ b/src/wallet/wallet.cpp @@ -818,7 +818,7 @@ bool CWallet::CommitAutomatedTx(const CTransaction& tx) { return CommitTransaction(wtx, reservekey); } -void CWallet::SetBestChain(const CBlockLocator& loc) +bool CWallet::SetBestChain(const CBlockLocator& loc) { // FlushStateToDisk passes the chain tip, but ThreadNotifyWallets delivers blocks to the wallet // asynchronously and can lag it. Stamping a locator ahead of what the wallet has processed makes @@ -827,15 +827,85 @@ void CWallet::SetBestChain(const CBlockLocator& loc) // by init before the notifier starts, then advanced by ChainTip). Init's own calls, made before // it is seeded, pass the right locator themselves. CBlockLocator locator = loc; + const CBlockIndex* pindexStamped = nullptr; + uint64_t nGeneration; { LOCK2(cs_main, cs_wallet); - if (pindexWalletTip != nullptr) + // Read before the write: a change made while it runs bumps the counter past this value, so + // the shutdown save still sees it as unsaved. + nGeneration = nWitnessGeneration; + if (pindexWalletTip != nullptr) { locator = chainActive.GetLocator(pindexWalletTip); + pindexStamped = pindexWalletTip; + } else if (!loc.vHave.empty()) { + BlockMap::const_iterator mi = mapBlockIndex.find(loc.vHave.front()); + if (mi != mapBlockIndex.end()) + pindexStamped = mi->second; + } } // Default ctor => fFlushOnClose=true => ~CDB runs a full BDB txn_checkpoint over the entire // cache. Fine for the hourly/shutdown callers; ruinous inside a scan (see SetBestChainNoFlush). CWalletDB walletdb(strWalletFile); - SetBestChainINTERNAL(walletdb, locator); + bool fWritten = SetBestChainINTERNAL(walletdb, locator); + if (fWritten) + RecordStatePersisted(pindexStamped, nGeneration); + return fWritten; +} + +void CWallet::RecordStatePersisted(const CBlockIndex* pindex, uint64_t nGeneration) +{ + LOCK(cs_wallet); + pindexPersistedTip = pindex; + nPersistedWitnessGeneration = nGeneration; +} + +void CWallet::MarkStatePersisted(const CBlockIndex* pindex) +{ + LOCK(cs_wallet); + RecordStatePersisted(pindex, nWitnessGeneration); +} + +const char* CWallet::ShutdownSaveSkipReason(bool fInitCompleted) +{ + // AppInit2 failed or was cut short: the other threads were interrupted but not joined, and the + // wallet tip may still be unset, in which case SetBestChain would stamp the chain tip over an + // interrupted rescan's checkpoint and the next start would skip the unscanned range. + if (!fInitCompleted) + return "startup did not complete"; + if (fWalletNotifyFailed) + return "the wallet failed to process a block"; + if (!bitdb.IsHealthy()) + return "the wallet database environment reported an error"; + LOCK(cs_wallet); + if (pindexWalletTip == nullptr) + return "the wallet tip is not set"; + if (pindexWalletTip == pindexPersistedTip && nWitnessGeneration == nPersistedWitnessGeneration) + return "nothing changed since the last save"; + return nullptr; +} + +void CWallet::PersistStateAtShutdown(bool fInitCompleted) +{ + LOCK2(cs_main, cs_wallet); + const char* skip = ShutdownSaveSkipReason(fInitCompleted); + if (skip != nullptr) { + LogPrintf("%s: not saving the wallet state: %s\n", __func__, skip); + return; + } + // SetBestChainINTERNAL writes every tx that has Sapling note data, each with its whole witness + // cache, in one transaction: on a large wallet this is the bulk of wallet.dat. A kill while it + // runs rolls back to the previous save at the next start (DB_RECOVER), losing only the saving. + unsigned int nTxs = 0; + for (const std::pair& wtxItem : mapWallet) + if (!wtxItem.second.mapSaplingNoteData.empty()) + nTxs++; + const int nHeight = pindexWalletTip->GetHeight(); + LogPrintf("Saving wallet state (note witnesses and best block %d, %u txs)...\n", nHeight, nTxs); + int64_t nStart = GetTimeMillis(); + bool fWritten = SetBestChain(chainActive.GetLocator()); + LogPrintf("%s: wallet state %s at height %d: %u txs in %dms\n", __func__, + fWritten ? "saved" : "NOT saved (the write failed; the previous save stays on disk)", + nHeight, nTxs, GetTimeMillis() - nStart); } bool CWallet::SetBestChainNoFlush(const CBlockLocator& loc) @@ -1215,6 +1285,7 @@ void CWallet::ClearNoteWitnessCache() notes++; } } + nWitnessGeneration++; LogPrintf("%s: Cleared witness data from %d wallet items and %d SaplingNotes\n", __func__, mapWallet.size(), notes); } @@ -1223,6 +1294,7 @@ void CWallet::DecrementNoteWitnesses(const CBlockIndex* pindex) extern int32_t HUSH_REWIND; LOCK2(cs_main, cs_wallet); + nWitnessGeneration++; for (std::pair& wtxItem : mapWallet) { //Sapling @@ -1355,6 +1427,7 @@ int CWallet::VerifyAndSetInitialWitness(const CBlockIndex* pindex, bool witnessO //Clear witness Cache for all other scenarios pblockindex = chainActive[wtxHeight]; ::ClearSingleNoteWitnessCache(nd); + nWitnessGeneration++; LogPrintf("%s: Setting Initial Sapling Witness for tx %s, %i of %i\n", __func__, wtxHash.ToString(), nWitnessTxIncrement, nWitnessTotalTxCount); @@ -1653,6 +1726,7 @@ void CWallet::BuildWitnessCache(const CBlockIndex* pindex, bool witnessOnly) // (DecrementNoteWitnesses clears it), keeping the heal self-correcting. The unrecoverable count // itself comes from checkRoot() on the workers, and only for a bulk rebuild. if (!work.empty()) { + nWitnessGeneration++; for (SaplingNoteData* nd : work) nd->witnessRootValidated = true; if (bulkRebuild) { @@ -2004,6 +2078,10 @@ bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFromLoadWallet, CWalletD fUpdated = true; } } + // Only a real change: re-adding a tx unchanged (ReacceptWalletTransactions on every start + // for each unconfirmed tx) leaves nothing new for SetBestChain to write. + if ((fInsertedNew || fUpdated) && !wtx.mapSaplingNoteData.empty()) + nWitnessGeneration++; //// debug print LogPrintf("AddToWallet %s at height %d %s%s\n", wtxIn.GetHash().ToString(), hush_blockheight(wtxIn.hashBlock), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : "")); diff --git a/src/wallet/wallet.h b/src/wallet/wallet.h index 96bd4b631..89a3c1089 100644 --- a/src/wallet/wallet.h +++ b/src/wallet/wallet.h @@ -993,6 +993,16 @@ private: // reflects (guarded by cs_wallet). SetBestChain stamps this instead of the chain tip. const CBlockIndex* pindexWalletTip = nullptr; + // Change tracking for the shutdown save (guarded by cs_wallet). nWitnessGeneration is bumped + // whenever the note state SetBestChain writes changes in memory: witnesses extended, popped, + // reseeded or cleared, or a note-bearing tx added or merged. A committed SetBestChain records + // the block it stamped and the counter it saw, so a shutdown can tell that nothing is left to + // write. + uint64_t nWitnessGeneration = 0; + const CBlockIndex* pindexPersistedTip = nullptr; + uint64_t nPersistedWitnessGeneration = 0; + void RecordStatePersisted(const CBlockIndex* pindex, uint64_t nGeneration); + protected: bool UpdatedNoteData(const CWalletTx& wtxIn, CWalletTx& wtx, bool fSameBlock); void MarkAffectedTransactionsDirty(const CTransaction& tx); @@ -1320,8 +1330,19 @@ public: void RunSaplingConsolidation(int blockHeight); void RunAutoShieldCoinbase(int blockHeight); bool CommitAutomatedTx(const CTransaction& tx); - /** Saves witness caches and best block locator to disk. Overrides CValidationInterface. */ - void SetBestChain(const CBlockLocator& loc); + /** Saves witness caches and best block locator to disk in one atomic write, and reports whether + * it committed. Overrides CValidationInterface. */ + bool SetBestChain(const CBlockLocator& loc); + /** Init found the locator on disk at pindex and is not rescanning: the wallet in memory is what + * was last saved, so a shutdown with no changes after this has nothing to write. */ + void MarkStatePersisted(const CBlockIndex* pindex); + /** Why a clean shutdown must not write the wallet state now, or nullptr if it should. */ + const char* ShutdownSaveSkipReason(bool fInitCompleted); + /** Called by Shutdown() under cs_main after the chainstate flush, with every other thread + * stopped: writes the witnesses and the best-block locator (SetBestChain), unless a gate in + * 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); // 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 From bc3867a3125729de857ce72a7d0e55b75b4c707a Mon Sep 17 00:00:00 2001 From: DanS Date: Wed, 28 Oct 2026 10:44:55 -0500 Subject: [PATCH 2/9] wallet: compute the witness roots of the startup check on worker threads After every start the first VerifyAndSetInitialWitness pass checks each note's witness: front().root(), compared with hashFinalSaplingRoot at the witness height. root() walks the whole depth-32 path, about 1.7-2.4 ms per note, serially and with cs_main and cs_wallet held: about 14 s for 8,200 notes on regtest, 28-39 s for a 16k-note wallet. With the witnesses now saved at shutdown this pass no longer hides behind the rescan; it holds the first block after start, and every RPC waiting on those locks, for that long, and a stop sent meanwhile waited for all of it. Compute those roots first, the way BuildWitnessCache's Phase 2 spreads the extension: under the existing locks collect the notes the loop will call root() for (confirmed tx, full viewing key, nullifier, witnesses, witnessHeight > 0, not yet validated, block at witnessHeight on the active chain), compute their roots on -witnessbuildthreads threads (one per core by default; inline below 8 notes, or for any shard whose thread cannot start), then run the existing loop unchanged, taking each root from that table. The loop changes a note's witnesses only at that note's own turn (a sibling's reseed rewrites nullifiers, never witnesses), so every root is the root of the witness being checked and the validated/reseeded decisions, their order and nMinimumHeight are those of the serial code. A note the selection misses, or whose root() threw on a worker, gets its root computed inline as before, so a throw surfaces at the same note. The root-equality check and the reseed on a mismatch are untouched. Between the two phases nothing has been changed yet, so a stop requested while the roots are computed ends the pass there; the next block or the next start redoes it. The thread-count and thread-start-with-fallback code is shared with Phase 2 (WitnessThreadCount, RunWitnessShards), with the same results. On regtest (U.base, 24 threads): 2,063 roots in 920 ms against 3.2-4.2 s for the serial pass. The new gtests run the same synthetic wallet with one thread and with several and compare every note's resulting state, including a root mismatch whose reseed throws mid-pass. Co-Authored-By: Claude Opus 5.5 --- src/Makefile.gtest.include | 3 +- src/gtest/test_wallet_witnessroots.cpp | 354 +++++++++++++++++++++++++ src/wallet/wallet.cpp | 122 +++++++-- 3 files changed, 453 insertions(+), 26 deletions(-) create mode 100644 src/gtest/test_wallet_witnessroots.cpp diff --git a/src/Makefile.gtest.include b/src/Makefile.gtest.include index a2cfac6d3..ac9c9fc02 100644 --- a/src/Makefile.gtest.include +++ b/src/Makefile.gtest.include @@ -21,7 +21,8 @@ hush_gtest_SOURCES = \ gtest/test_wallet_dbenv.cpp \ gtest/test_wallet_notecache.cpp \ gtest/test_wallet_history.cpp \ - gtest/test_wallet_shutdownsave.cpp + gtest/test_wallet_shutdownsave.cpp \ + gtest/test_wallet_witnessroots.cpp hush_gtest_CPPFLAGS = $(AM_CPPFLAGS) -DMULTICORE -fopenmp -DBINARY_OUTPUT -DCURVE_ALT_BN128 -DSTATIC $(BITCOIN_INCLUDES) hush_gtest_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS) diff --git a/src/gtest/test_wallet_witnessroots.cpp b/src/gtest/test_wallet_witnessroots.cpp new file mode 100644 index 000000000..bb641ccf4 --- /dev/null +++ b/src/gtest/test_wallet_witnessroots.cpp @@ -0,0 +1,354 @@ +// Copyright (c) 2016-2024 The Hush developers +// Distributed under the GPLv3 software license, see the accompanying +// file COPYING or https://www.gnu.org/licenses/gpl-3.0.en.html + +#include + +#include +#include +#include + +#include "chain.h" +#include "coins.h" +#include "init.h" +#include "main.h" +#include "primitives/block.h" +#include "primitives/transaction.h" +#include "uint256.h" +#include "util.h" +#include "wallet/wallet.h" +#include "zcash/zip32.h" + +extern std::atomic fRequestShutdown; + +// VerifyAndSetInitialWitness computes the witness roots it checks on worker threads before its serial loop. These +// tests run the same synthetic wallet with one thread and with several and compare every note's resulting state. + +namespace { + +class RootsWallet : public CWallet { +public: + int VerifyAndSetInitialWitness(const CBlockIndex* pindex, bool witnessOnly) { + return CWallet::VerifyAndSetInitialWitness(pindex, witnessOnly); + } +}; + +// An active chain of nBlocks blocks (heights 0..nBlocks-1) whose block 1 holds the given txs, with a chosen +// hashFinalSaplingRoot per height. Undone on destruction: chainActive, mapBlockIndex and pcoinsTip are process-wide. +struct RootsChain { + std::deque blocks; + std::deque index; + CBlockIndex* savedTip; + CCoinsView coinsBase; + CCoinsViewCache coins{&coinsBase}; + CCoinsViewCache* savedCoinsTip; + + RootsChain(int nBlocks, const std::vector& inBlock1, const std::map& roots) { + LOCK(cs_main); + savedTip = chainActive.Tip(); + savedCoinsTip = pcoinsTip; + pcoinsTip = &coins; + for (int h = 0; h < nBlocks; h++) { + blocks.emplace_back(); + CBlock& block = blocks.back(); + block.nTime = 1710000000 + h; + block.nNonce = uint256S(strprintf("%x", 0x900 + h)); + if (h > 0) + block.hashPrevBlock = blocks[h - 1].GetHash(); + if (h == 1) + block.vtx = inBlock1; + block.hashMerkleRoot = block.BuildMerkleTree(); + index.emplace_back(block); + CBlockIndex& bi = index.back(); + bi.SetHeight(h); + bi.pprev = h > 0 ? &index[h - 1] : nullptr; + std::map::const_iterator it = roots.find(h); + if (it != roots.end()) + bi.hashFinalSaplingRoot = it->second; + bi.phashBlock = &mapBlockIndex.insert(std::make_pair(block.GetHash(), &bi)).first->first; + } + chainActive.SetTip(&index.back()); + } + ~RootsChain() { + LOCK(cs_main); + chainActive.SetTip(savedTip); + for (const CBlock& block : blocks) + mapBlockIndex.erase(block.GetHash()); + pcoinsTip = savedCoinsTip; + } +}; + +libzcash::SaplingExtendedSpendingKey TestKey() +{ + std::vector> raw(32, 0x5a); + HDSeed seed(raw); + return libzcash::SaplingExtendedSpendingKey::Master(seed); +} + +std::vector Txs(int n) +{ + std::vector txs; + for (int i = 0; i < n; i++) { + CMutableTransaction mtx; + mtx.nLockTime = 1000 + i; // distinct txids + txs.push_back(CTransaction(mtx)); + } + return txs; +} + +// Witnesses of nNotes positions in one tree: all share the tree's root. Each is a distinct witness object. +std::vector Witnesses(int nNotes, int salt, uint256& rootOut) +{ + SaplingMerkleTree tree; + std::vector ws; + for (int i = 0; i < nNotes; i++) { + uint256 cm = uint256S(strprintf("%x%04x", salt, i + 1)); + tree.append(cm); + for (SaplingWitness& w : ws) + w.append(cm); + ws.push_back(tree.witness()); + } + rootOut = tree.root(); + return ws; +} + +enum Kind { VALID_BELOW_TIP, VALID_AT_TIP, AHEAD_OF_CHAIN, ALREADY_VALIDATED, WRONG_ROOT, NOT_IN_CHAIN }; + +struct Fixture { + std::vector txs; + std::map roots; + std::vector wBelow, wAt; + int nTxs; +}; + +// Fills the wallet: tx i gets notes of the kinds kinds(i) returns, in output order. +template +void Fill(RootsWallet& wallet, const Fixture& fx, const RootsChain& chain, KindsOf kinds) +{ + auto sk = TestKey(); + auto ivk = sk.expsk.full_viewing_key().in_viewing_key(); + LOCK2(cs_main, wallet.cs_wallet); + ASSERT_TRUE(wallet.AddSaplingZKey(sk, sk.DefaultAddress())); + ASSERT_TRUE(wallet.HaveSaplingFullViewingKey(ivk)); + size_t nBelow = 0, nAt = 0; + for (int i = 0; i < fx.nTxs; i++) { + const CTransaction& tx = fx.txs[i]; + CWalletTx wtx(&wallet, tx); + std::vector ks = kinds(i); + mapSaplingNoteData_t notes; + for (size_t n = 0; n < ks.size(); n++) { + SaplingNoteData nd(ivk, uint256S(strprintf("f%03x%03x", i, (int)n))); + switch (ks[n]) { + case VALID_BELOW_TIP: + nd.witnesses.push_front(fx.wBelow[nBelow++ % fx.wBelow.size()]); + nd.witnessHeight = 2; + break; + case VALID_AT_TIP: + nd.witnesses.push_front(fx.wAt[nAt++ % fx.wAt.size()]); + nd.witnessHeight = 3; + break; + case AHEAD_OF_CHAIN: + nd.witnesses.push_front(fx.wAt[0]); + nd.witnessHeight = 9; + break; + case ALREADY_VALIDATED: + nd.witnesses.push_front(fx.wBelow[0]); + nd.witnessHeight = 2; + nd.witnessRootValidated = true; + break; + case WRONG_ROOT: + nd.witnesses.push_front(fx.wAt[0]); // the tip's tree, checked against block 2's root + nd.witnessHeight = 2; + break; + case NOT_IN_CHAIN: + nd.witnesses.push_front(fx.wBelow[0]); + nd.witnessHeight = 2; + break; + } + notes[SaplingOutPoint(tx.GetHash(), n)] = nd; + } + wtx.mapSaplingNoteData = notes; // the txs carry no outputs; nothing here decrypts + ASSERT_TRUE(wallet.AddToWallet(wtx, true, nullptr)); + if (ks.empty() || ks[0] != NOT_IN_CHAIN) { + wallet.mapWallet.at(tx.GetHash()).SetMerkleBranch(chain.blocks[1]); + ASSERT_GT(wallet.mapWallet.at(tx.GetHash()).GetDepthInMainChain(), 0); + } + } +} + +struct NoteState { + bool validated; + int witnessHeight; + size_t nWitnesses; + bool hasNullifier; + bool operator==(const NoteState& o) const { + return validated == o.validated && witnessHeight == o.witnessHeight && nWitnesses == o.nWitnesses && + hasNullifier == o.hasNullifier; + } +}; + +std::map States(RootsWallet& wallet) +{ + LOCK(wallet.cs_wallet); + std::map out; + for (const auto& wtxItem : wallet.mapWallet) + for (const auto& item : wtxItem.second.mapSaplingNoteData) + out[item.first] = {item.second.witnessRootValidated, item.second.witnessHeight, + item.second.witnesses.size(), static_cast(item.second.nullifier)}; + return out; +} + +Fixture MakeFixture(int nTxs) +{ + Fixture fx; + fx.nTxs = nTxs; + fx.txs = Txs(nTxs); + uint256 rootBelow, rootAt; + fx.wBelow = Witnesses(24, 0xb, rootBelow); + fx.wAt = Witnesses(24, 0xa, rootAt); + fx.roots[2] = rootBelow; + fx.roots[3] = rootAt; + return fx; +} + +class WalletWitnessRoots : public ::testing::Test { +protected: + std::string savedThreads; + void SetUp() override { + fRequestShutdown = false; + savedThreads = mapArgs.count("-witnessbuildthreads") ? mapArgs["-witnessbuildthreads"] : ""; + } + void TearDown() override { + fRequestShutdown = false; + if (savedThreads.empty()) + mapArgs.erase("-witnessbuildthreads"); + else + mapArgs["-witnessbuildthreads"] = savedThreads; + } +}; + +std::vector MixedKinds(int i) +{ + static const Kind cycle[] = {VALID_BELOW_TIP, VALID_AT_TIP, VALID_BELOW_TIP, AHEAD_OF_CHAIN, ALREADY_VALIDATED, + VALID_AT_TIP}; + std::vector ks; + for (int n = 0; n < 1 + i % 3; n++) + ks.push_back(cycle[(i + n) % 6]); + return ks; +} + +} + +// Every note is validated, skipped or deferred exactly as the serial pass does it, and the minimum height +// matches, whether the roots come from one thread or eight. +TEST_F(WalletWitnessRoots, ParallelMatchesSerial) { + Fixture fx = MakeFixture(60); + RootsChain chain(4, fx.txs, fx.roots); + + std::map results[2]; + int minHeight[2]; + const char* threads[2] = {"1", "8"}; + for (int r = 0; r < 2; r++) { + mapArgs["-witnessbuildthreads"] = threads[r]; + RootsWallet wallet; + Fill(wallet, fx, chain, MixedKinds); + minHeight[r] = wallet.VerifyAndSetInitialWitness(chainActive.Tip(), false); + results[r] = States(wallet); + } + EXPECT_EQ(minHeight[0], minHeight[1]); + EXPECT_EQ(2, minHeight[0]) << "the lowest witness height among the checked notes"; + ASSERT_EQ(results[0].size(), results[1].size()); + EXPECT_TRUE(results[0] == results[1]); + + // And the outcome is the one the serial rules give for each kind. + std::map kindOf; + for (int i = 0; i < fx.nTxs; i++) { + std::vector ks = MixedKinds(i); + for (size_t n = 0; n < ks.size(); n++) + kindOf[SaplingOutPoint(fx.txs[i].GetHash(), n)] = ks[n]; + } + int nValidated = 0; + for (const auto& r : results[1]) { + Kind k = kindOf.at(r.first); + bool expectValidated = k != AHEAD_OF_CHAIN; + EXPECT_EQ(expectValidated, r.second.validated) << "kind " << k; + EXPECT_EQ(1u, r.second.nWitnesses); + EXPECT_TRUE(r.second.hasNullifier); + nValidated += r.second.validated && k != ALREADY_VALIDATED; + } + EXPECT_GT(nValidated, 40) << "enough roots to spread over the threads"; +} + +// With witnessOnly the already-validated notes are skipped outright; the rest is the same. +TEST_F(WalletWitnessRoots, ParallelMatchesSerialWitnessOnly) { + Fixture fx = MakeFixture(40); + RootsChain chain(4, fx.txs, fx.roots); + std::map results[2]; + int minHeight[2]; + const char* threads[2] = {"1", "6"}; + for (int r = 0; r < 2; r++) { + mapArgs["-witnessbuildthreads"] = threads[r]; + RootsWallet wallet; + Fill(wallet, fx, chain, MixedKinds); + minHeight[r] = wallet.VerifyAndSetInitialWitness(chainActive.Tip(), true); + results[r] = States(wallet); + } + EXPECT_EQ(minHeight[0], minHeight[1]); + EXPECT_TRUE(results[0] == results[1]); +} + +// A wrong root sends the note to the reseed, which reads its block from disk; there are no block files here, so +// it throws. Every note before it in wallet order has been decided, every note after it not, identically. +TEST_F(WalletWitnessRoots, MismatchIsHandledInSerialOrder) { + Fixture fx = MakeFixture(30); + RootsChain chain(4, fx.txs, fx.roots); + auto kinds = [](int i) { + std::vector ks = MixedKinds(i); + if (i == 17) + ks.push_back(WRONG_ROOT); + return ks; + }; + std::map results[2]; + const char* threads[2] = {"1", "8"}; + for (int r = 0; r < 2; r++) { + mapArgs["-witnessbuildthreads"] = threads[r]; + RootsWallet wallet; + Fill(wallet, fx, chain, kinds); + EXPECT_THROW(wallet.VerifyAndSetInitialWitness(chainActive.Tip(), false), std::runtime_error); + results[r] = States(wallet); + } + EXPECT_TRUE(results[0] == results[1]); + int nDecided = 0, nUndecided = 0; + for (const auto& r : results[1]) + (r.second.validated ? nDecided : nUndecided)++; + EXPECT_GT(nDecided, 0); + EXPECT_GT(nUndecided, 0); +} + +// A stop requested while the roots are computed ends the pass before it changes anything. +TEST_F(WalletWitnessRoots, ShutdownSkipsThePassUnchanged) { + Fixture fx = MakeFixture(20); + RootsChain chain(4, fx.txs, fx.roots); + mapArgs["-witnessbuildthreads"] = "4"; + RootsWallet wallet; + Fill(wallet, fx, chain, MixedKinds); + std::map before = States(wallet); + fRequestShutdown = true; + EXPECT_EQ(chainActive.Height(), wallet.VerifyAndSetInitialWitness(chainActive.Tip(), false)); + EXPECT_TRUE(before == States(wallet)); +} + +// Notes of a tx that is not in the active chain are never checked. +TEST_F(WalletWitnessRoots, UnconfirmedTxIsNotChecked) { + Fixture fx = MakeFixture(12); + RootsChain chain(4, fx.txs, fx.roots); + mapArgs["-witnessbuildthreads"] = "4"; + RootsWallet wallet; + Fill(wallet, fx, chain, [](int i) { + return i % 2 ? std::vector{NOT_IN_CHAIN, NOT_IN_CHAIN} : std::vector{VALID_BELOW_TIP, VALID_AT_TIP}; + }); + wallet.VerifyAndSetInitialWitness(chainActive.Tip(), false); + for (int i = 0; i < fx.nTxs; i++) + for (int n = 0; n < 2; n++) + EXPECT_EQ(i % 2 == 0, States(wallet).at(SaplingOutPoint(fx.txs[i].GetHash(), n)).validated); +} diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp index 08a9d3ffc..1f2c55930 100644 --- a/src/wallet/wallet.cpp +++ b/src/wallet/wallet.cpp @@ -48,6 +48,8 @@ #include #include #include +#include +#include #include "zcash/zip32.h" #include "cc/CCinclude.h" #include @@ -1345,6 +1347,39 @@ int CWallet::SaplingWitnessMinimumHeight(const boost::optional& nullifi return nMinimumHeight; } +// Threads for witness work spread over notes: -witnessbuildthreads, else one per core, and never +// more than there are notes. +static int WitnessThreadCount(size_t nJobs) +{ + int nPar = (int)GetArg("-witnessbuildthreads", 0); + if (nPar <= 0) nPar = (int)std::thread::hardware_concurrency(); + if (nPar <= 0) nPar = 1; + if (nPar > (int)nJobs) nPar = (int)nJobs; + if (nPar < 1) nPar = 1; + return nPar; +} + +// Runs shard(0) .. shard(nPar-1), each exactly once, on up to nPar threads; shard must not throw. +// If the OS refuses a thread (task limit, memory), the remaining shards run here instead of letting +// the exception unwind past joinable threads (std::terminate). The result is unchanged either way. +static void RunWitnessShards(int nPar, const std::function& shard, const char* caller) +{ + if (nPar <= 1) { + shard(0); + return; + } + std::vector threads; + threads.reserve(nPar); + int t = 0; + try { + for (; t < nPar; t++) threads.emplace_back(shard, t); + } catch (const std::system_error& e) { + LogPrintf("%s: could only start %d of %d witness threads (%s); running the rest inline\n", caller, t, nPar, e.what()); + } + for (int u = t; u < nPar; u++) shard(u); + for (std::thread& th : threads) th.join(); +} + int CWallet::VerifyAndSetInitialWitness(const CBlockIndex* pindex, bool witnessOnly) { LOCK2(cs_main, cs_wallet); @@ -1353,6 +1388,64 @@ int CWallet::VerifyAndSetInitialWitness(const CBlockIndex* pindex, bool witnessO int nWitnessTotalTxCount = mapWallet.size(); int nMinimumHeight = pindex->GetHeight(); + // root() walks a witness's whole depth-32 path, ~1.7-2.4ms, and after a restart every note needs + // one: ~30s for a 16k-note wallet, with cs_main and cs_wallet held. So compute those roots first, + // spread over threads the way BuildWitnessCache's Phase 2 spreads the extension, and then run the + // loop below unchanged, taking each root from here instead of computing it. That loop changes a + // note's witnesses only at that note's own turn (a sibling's reseed rewrites nullifiers, never + // witnesses), so each root is the root of the witness the loop checks, and the validated/reseeded + // decisions, their order and nMinimumHeight are exactly the serial ones. The selection mirrors the + // loop's conditions for reaching root(); a note it misses (one that only gains a nullifier from a + // sibling's reseed) has its root computed inline, as does one whose root() threw here, so a throw + // surfaces exactly where it used to. + std::vector rootNotes; + for (const std::pair& wtxItem : mapWallet) { + if (wtxItem.second.mapSaplingNoteData.empty() || wtxItem.second.GetDepthInMainChain() <= 0) + continue; + for (const mapSaplingNoteData_t::value_type& item : wtxItem.second.mapSaplingNoteData) { + const SaplingNoteData* nd = &(item.second); + if (nd->nullifier && !nd->witnesses.empty() && nd->witnessHeight > 0 && !nd->witnessRootValidated && + chainActive[nd->witnessHeight] != NULL && HaveSaplingFullViewingKey(nd->ivk)) + rootNotes.push_back(nd); + } + } + std::vector roots(rootNotes.size()); + std::unordered_map rootIndex; + if (!rootNotes.empty()) { + std::vector haveRoot(rootNotes.size(), 0); + // Starting the threads costs about as much as a root, so a handful stay on this thread. + const int nPar = rootNotes.size() >= 8 ? WitnessThreadCount(rootNotes.size()) : 1; + int64_t r0 = GetTimeMicros(); + RunWitnessShards(nPar, [&](int tid) { + // Workers read only their own notes' witnesses; this thread holds the locks and waits. + for (size_t k = (size_t)tid; k < rootNotes.size(); k += (size_t)nPar) { + if (ShutdownRequested()) + return; + try { + roots[k] = rootNotes[k]->witnesses.front().root(); + haveRoot[k] = 1; + } catch (...) { + } + } + }, __func__); + // Nothing has been changed yet, so stopping here is as if this pass never ran: the next block or + // the next start redoes it. Without this a stop waited for the whole pass. + if (ShutdownRequested()) { + LogPrintf("%s: shutdown requested, skipping the witness check at height %d\n", __func__, pindex->GetHeight()); + return pindex->GetHeight(); + } + for (size_t k = 0; k < rootNotes.size(); k++) + if (haveRoot[k]) + rootIndex[rootNotes[k]] = k; + if (fZdebug) + LogPrintf("%s: %u witness root(s) computed in %ldms using %d thread(s)\n", __func__, + (unsigned)rootNotes.size(), (long)((GetTimeMicros() - r0) / 1000), nPar); + } + auto cachedRoot = [&](const SaplingNoteData* nd) { + std::unordered_map::const_iterator it = rootIndex.find(nd); + return it != rootIndex.end() ? roots[it->second] : nd->witnesses.front().root(); + }; + for (std::pair& wtxItem : mapWallet) { nWitnessTxIncrement += 1; @@ -1405,7 +1498,7 @@ int CWallet::VerifyAndSetInitialWitness(const CBlockIndex* pindex, bool witnessO nMinimumHeight = SaplingWitnessMinimumHeight(item.second.nullifier, nd->witnessHeight, nMinimumHeight); continue; } - if (nd->witnesses.front().root() == whIndex->hashFinalSaplingRoot) { + if (cachedRoot(nd) == whIndex->hashFinalSaplingRoot) { nd->witnessRootValidated = true; nMinimumHeight = SaplingWitnessMinimumHeight(item.second.nullifier, nd->witnessHeight, nMinimumHeight); continue; @@ -1414,7 +1507,7 @@ int CWallet::VerifyAndSetInitialWitness(const CBlockIndex* pindex, bool witnessO } //Validate the witness at the witness height - witnessRoot = nd->witnesses.front().root(); + witnessRoot = cachedRoot(nd); pblockindex = chainActive[nd->witnessHeight]; blockRoot = pblockindex->hashFinalSaplingRoot; if (witnessRoot == blockRoot) { @@ -1604,12 +1697,7 @@ void CWallet::BuildWitnessCache(const CBlockIndex* pindex, bool witnessOnly) nCms += cms.size(); const bool fParallel = bulkRebuild || (uint64_t)work.size() * nCms >= 2000; - int nPar = (int)GetArg("-witnessbuildthreads", 0); - if (nPar <= 0) nPar = (int)std::thread::hardware_concurrency(); - if (nPar <= 0) nPar = 1; - if (nPar > (int)work.size()) nPar = (int)work.size(); - if (nPar < 1) nPar = 1; - if (!fParallel) nPar = 1; + const int nPar = fParallel ? WitnessThreadCount(work.size()) : 1; std::atomic failed(false); std::mutex failMtx; @@ -1694,23 +1782,7 @@ void CWallet::BuildWitnessCache(const CBlockIndex* pindex, bool witnessOnly) }; int64_t e0 = GetTimeMicros(); - if (nPar <= 1) { - worker(0); - } else { - // If the OS refuses a thread (task limit, memory), run the remaining shards here instead of - // letting the exception unwind past joinable threads (std::terminate). Each shard still runs - // exactly once, so the result is unchanged. - std::vector threads; - threads.reserve(nPar); - int t = 0; - try { - for (; t < nPar; t++) threads.emplace_back(worker, t); - } catch (const std::system_error& e) { - LogPrintf("%s: could only start %d of %d witness threads (%s); running the rest inline\n", __func__, t, nPar, e.what()); - } - for (int u = t; u < nPar; u++) worker(u); - for (std::thread& th : threads) th.join(); - } + RunWitnessShards(nPar, worker, __func__); int64_t tExtend = GetTimeMicros() - e0; if (failed) From b4513498e5403bd4a4b47a0b734dcad9fc3d537a Mon Sep 17 00:00:00 2001 From: DanS Date: Wed, 28 Oct 2026 10:48:35 -0500 Subject: [PATCH 3/9] wallet: say what the startup witness check did VerifyAndSetInitialWitness logs one line per reseeded note and nothing else, so the pass that root-checks every note after a start (seconds on a large wallet) is invisible, and the reseed line's " of " reads like progress although is the tx's place in mapWallet and is mapWallet.size(): transactions, not notes. Append "[reseed ]", the running count of reseeded notes, to the reseed line. Its prefix, the comma after the hash and " of " stay exactly as they were: ObsidianDragon parses them (the hash between "for tx " and the comma, the number after " of ") to track progress. Add one summary line at the end of a pass that validated or reseeded anything: the notes validated, reseeded, already valid and ahead of the chain, the lowest witness height and the elapsed ms. A routine block with nothing to check prints nothing new. Logging only; the counters feed no decision. Co-Authored-By: Claude Opus 5.5 --- src/wallet/wallet.cpp | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp index 1f2c55930..8994e217f 100644 --- a/src/wallet/wallet.cpp +++ b/src/wallet/wallet.cpp @@ -1387,6 +1387,9 @@ int CWallet::VerifyAndSetInitialWitness(const CBlockIndex* pindex, bool witnessO int nWitnessTxIncrement = 0; int nWitnessTotalTxCount = mapWallet.size(); int nMinimumHeight = pindex->GetHeight(); + // For the end-of-pass summary only; no decision reads them. + const int64_t nPassStart = GetTimeMicros(); + int nNotesValidated = 0, nNotesReseeded = 0, nNotesKnownGood = 0, nNotesAhead = 0; // root() walks a witness's whole depth-32 path, ~1.7-2.4ms, and after a restart every note needs // one: ~30s for a 16k-note wallet, with cs_main and cs_wallet held. So compute those roots first, @@ -1478,11 +1481,14 @@ int CWallet::VerifyAndSetInitialWitness(const CBlockIndex* pindex, bool witnessO if (!nd->witnesses.empty() && nd->witnessHeight > 0) { //Skip all functions for validated witness while witness only = true - if (nd->witnessRootValidated && witnessOnly) + if (nd->witnessRootValidated && witnessOnly) { + nNotesKnownGood++; continue; + } //Skip Validation when witness root has been validated if (nd->witnessRootValidated) { + nNotesKnownGood++; nMinimumHeight = SaplingWitnessMinimumHeight(item.second.nullifier, nd->witnessHeight, nMinimumHeight); continue; } @@ -1495,11 +1501,13 @@ int CWallet::VerifyAndSetInitialWitness(const CBlockIndex* pindex, bool witnessO CBlockIndex* whIndex = chainActive[nd->witnessHeight]; if (whIndex == NULL) { //witnessHeight strictly above the active chain (transient catch-up): cannot validate yet + nNotesAhead++; nMinimumHeight = SaplingWitnessMinimumHeight(item.second.nullifier, nd->witnessHeight, nMinimumHeight); continue; } if (cachedRoot(nd) == whIndex->hashFinalSaplingRoot) { nd->witnessRootValidated = true; + nNotesValidated++; nMinimumHeight = SaplingWitnessMinimumHeight(item.second.nullifier, nd->witnessHeight, nMinimumHeight); continue; } @@ -1512,6 +1520,7 @@ int CWallet::VerifyAndSetInitialWitness(const CBlockIndex* pindex, bool witnessO blockRoot = pblockindex->hashFinalSaplingRoot; if (witnessRoot == blockRoot) { nd->witnessRootValidated = true; + nNotesValidated++; nMinimumHeight = SaplingWitnessMinimumHeight(item.second.nullifier, nd->witnessHeight, nMinimumHeight); continue; } @@ -1521,8 +1530,11 @@ int CWallet::VerifyAndSetInitialWitness(const CBlockIndex* pindex, bool witnessO pblockindex = chainActive[wtxHeight]; ::ClearSingleNoteWitnessCache(nd); nWitnessGeneration++; + nNotesReseeded++; - LogPrintf("%s: Setting Initial Sapling Witness for tx %s, %i of %i\n", __func__, wtxHash.ToString(), nWitnessTxIncrement, nWitnessTotalTxCount); + //The GUI parses this line (the hash between "for tx " and the comma, and the count after " of "): + //keep that part as it is and only append. of is the tx's place in mapWallet, not a note count. + LogPrintf("%s: Setting Initial Sapling Witness for tx %s, %i of %i [reseed %d]\n", __func__, wtxHash.ToString(), nWitnessTxIncrement, nWitnessTotalTxCount, nNotesReseeded); SaplingMerkleTree saplingTree; blockRoot = pblockindex->pprev->hashFinalSaplingRoot; @@ -1570,6 +1582,10 @@ int CWallet::VerifyAndSetInitialWitness(const CBlockIndex* pindex, bool witnessO } } + if (nNotesValidated > 0 || nNotesReseeded > 0) + LogPrintf("%s: block %d: %d note witness(es) validated, %d reseeded, %d already valid, %d ahead of the chain; " + "lowest witness height %d; %ldms\n", __func__, pindex->GetHeight(), nNotesValidated, nNotesReseeded, + nNotesKnownGood, nNotesAhead, nMinimumHeight, (long)((GetTimeMicros() - nPassStart) / 1000)); if(fZdebug) LogPrintf("%s: nMinimumHeight=%d\n",__func__, nMinimumHeight); return nMinimumHeight; From ed13277dcb8f95f76ffc86ab51c182006997abd9 Mon Sep 17 00:00:00 2001 From: DanS Date: Wed, 28 Oct 2026 12:27:43 -0500 Subject: [PATCH 4/9] 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 From 0b822cc6b258d37ec6011e1b6d10bb2542271628 Mon Sep 17 00:00:00 2001 From: DanS Date: Wed, 28 Oct 2026 12:32:54 -0500 Subject: [PATCH 5/9] wallet: keep a failed open of the wallet database inside the shutdown save SetBestChain opens the wallet database (CWalletDB) outside the try block of SetBestChainINTERNAL, and CDB's constructor throws when the environment or the file cannot be opened. Shutdown() calls the save with no handler around it, so such a failure ended in std::terminate: the coins views and the block tree were not deleted, the wallet was not flushed and the pidfile stayed. The hourly SetBestChain runs inside FlushStateToDisk's try block and never had this problem. PersistStateAtShutdown now catches the exception, logs the save as NOT saved with the reason, records nothing, and lets the teardown go on. Co-Authored-By: Claude Opus 5.5 --- src/gtest/test_wallet_shutdownsave.cpp | 39 ++++++++++++++++++++++++++ src/wallet/wallet.cpp | 13 +++++++-- 2 files changed, 50 insertions(+), 2 deletions(-) diff --git a/src/gtest/test_wallet_shutdownsave.cpp b/src/gtest/test_wallet_shutdownsave.cpp index f5798011e..c5b55a916 100644 --- a/src/gtest/test_wallet_shutdownsave.cpp +++ b/src/gtest/test_wallet_shutdownsave.cpp @@ -6,8 +6,13 @@ #include +#include + #include "chain.h" +#include "chainparams.h" +#include "util.h" #include "validationinterface.h" +#include "wallet/db.h" #include "wallet/wallet.h" namespace { @@ -145,3 +150,37 @@ TEST_F(WalletShutdownSave, SkippedSaveWritesNothing) { ASSERT_NO_THROW(wallet.PersistStateAtShutdown(true)); ASSERT_NO_THROW(wallet.PersistStateAtShutdown(false)); } + +// Opening the wallet database can throw (an environment or file that cannot be opened). Shutdown() has no handler, +// so the save must catch it, record nothing, and return. +TEST_F(WalletShutdownSave, AFailedOpenDoesNotEscape) { + SelectParams(CBaseChainParams::MAIN); + const boost::filesystem::path dir = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path("shutdownsave-%%%%%%%%"); + const bool hadDatadir = mapArgs.count("-datadir") > 0; + const std::string oldDatadir = hadDatadir ? mapArgs["-datadir"] : ""; + boost::filesystem::create_directories(dir); + mapArgs["-datadir"] = dir.string(); + ClearDatadirCache(); + // The environment's log directory is a regular file, so opening the environment throws. + { + FILE* f = fopen((GetDataDir() / "database").string().c_str(), "wb"); + ASSERT_TRUE(f != nullptr); + fclose(f); + } + + CWallet wallet("wallet.dat"); + uint256 hash = uint256S("0123"); + CBlockIndex tip; + tip.phashBlock = &hash; + wallet.SetWalletTip(&tip); + ASSERT_EQ("", Reason(wallet, true)); + { + LOCK(cs_main); + EXPECT_NO_THROW(wallet.PersistStateAtShutdown(true)); + } + EXPECT_EQ("", Reason(wallet, true)) << "a failed save must not be recorded as one"; + + if (hadDatadir) mapArgs["-datadir"] = oldDatadir; else mapArgs.erase("-datadir"); + ClearDatadirCache(); + boost::filesystem::remove_all(dir); +} diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp index 499dc5ed2..fc2aff3e7 100644 --- a/src/wallet/wallet.cpp +++ b/src/wallet/wallet.cpp @@ -909,9 +909,18 @@ void CWallet::PersistStateAtShutdown(bool fInitCompleted) const int nHeight = pindexWalletTip->GetHeight(); LogPrintf("Saving wallet state (note witnesses and best block %d, %u txs)...\n", nHeight, nTxs); int64_t nStart = GetTimeMillis(); - bool fWritten = SetBestChain(chainActive.GetLocator()); + bool fWritten = false; + std::string strFailure = "the write failed"; + // Opening the wallet database throws when the environment or the file cannot be opened. Shutdown() + // has no handler, so this must not escape: the rest of the teardown (the coins views, the wallet + // flush, the pidfile) still has to run. + try { + fWritten = SetBestChain(chainActive.GetLocator()); + } catch (const std::exception& e) { + strFailure = e.what(); + } LogPrintf("%s: wallet state %s at height %d: %u txs in %dms\n", __func__, - fWritten ? "saved" : "NOT saved (the write failed; the previous save stays on disk)", + fWritten ? "saved" : strprintf("NOT saved (%s; the previous save stays on disk)", strFailure), nHeight, nTxs, GetTimeMillis() - nStart); } From 6413b8da4e2d03ef8b5b8e7532420a5664b3de47 Mon Sep 17 00:00:00 2001 From: DanS Date: Wed, 28 Oct 2026 12:37:36 -0500 Subject: [PATCH 6/9] wallet: skip the shutdown save when the chainstate flush failed The shutdown save runs right after FlushStateToDisk(), whose void wrapper dropped the result. If that flush failed (out of disk space, a coins database or block index write error), the save still stamped the wallet tip, a block the chainstate and block index on disk might not have, and started a write the size of the wallet on what is typically a full disk. FlushStateToDisk() now returns the result of the flush it runs (true for an nSPV light client, which flushes nothing). Its behaviour is unchanged, and the other callers ignore the result as before. Shutdown() passes it to PersistStateAtShutdown, which skips the save with "the chainstate flush failed". Co-Authored-By: Claude Opus 5.5 --- src/gtest/test_wallet_shutdownsave.cpp | 20 +++++++++++++++----- src/init.cpp | 6 ++++-- src/main.cpp | 5 +++-- src/main.h | 5 +++-- src/wallet/wallet.cpp | 10 +++++++--- src/wallet/wallet.h | 4 ++-- 6 files changed, 34 insertions(+), 16 deletions(-) diff --git a/src/gtest/test_wallet_shutdownsave.cpp b/src/gtest/test_wallet_shutdownsave.cpp index c5b55a916..78dda74ba 100644 --- a/src/gtest/test_wallet_shutdownsave.cpp +++ b/src/gtest/test_wallet_shutdownsave.cpp @@ -17,9 +17,9 @@ namespace { -std::string Reason(CWallet& wallet, bool fInitCompleted) +std::string Reason(CWallet& wallet, bool fInitCompleted, bool fChainstateFlushed = true) { - const char* reason = wallet.ShutdownSaveSkipReason(fInitCompleted); + const char* reason = wallet.ShutdownSaveSkipReason(fInitCompleted, fChainstateFlushed); return reason ? reason : ""; } @@ -58,6 +58,16 @@ TEST_F(WalletShutdownSave, SkipsAfterAWalletFailure) { EXPECT_EQ("", Reason(wallet, true)); } +// A failed chainstate flush (typically a full disk) leaves the block the locator would name possibly missing from the +// chainstate on disk. +TEST_F(WalletShutdownSave, SkipsWhenTheChainstateFlushFailed) { + CWallet wallet; + CBlockIndex tip; + wallet.SetWalletTip(&tip); + EXPECT_EQ("the chainstate flush failed", Reason(wallet, true, false)); + EXPECT_EQ("", Reason(wallet, true, true)); +} + // Once a save (or init, finding nothing to rescan) has recorded the wallet's block, a shutdown writes again // only if the wallet moved to another block or its note state changed. TEST_F(WalletShutdownSave, SkipsWhenNothingChangedSinceTheLastSave) { @@ -147,8 +157,8 @@ TEST_F(WalletShutdownSave, SkippedSaveWritesNothing) { wallet.SetWalletTip(&tip); wallet.MarkStatePersisted(&tip); LOCK(cs_main); - ASSERT_NO_THROW(wallet.PersistStateAtShutdown(true)); - ASSERT_NO_THROW(wallet.PersistStateAtShutdown(false)); + ASSERT_NO_THROW(wallet.PersistStateAtShutdown(true, true)); + ASSERT_NO_THROW(wallet.PersistStateAtShutdown(false, true)); } // Opening the wallet database can throw (an environment or file that cannot be opened). Shutdown() has no handler, @@ -176,7 +186,7 @@ TEST_F(WalletShutdownSave, AFailedOpenDoesNotEscape) { ASSERT_EQ("", Reason(wallet, true)); { LOCK(cs_main); - EXPECT_NO_THROW(wallet.PersistStateAtShutdown(true)); + EXPECT_NO_THROW(wallet.PersistStateAtShutdown(true, true)); } EXPECT_EQ("", Reason(wallet, true)) << "a failed save must not be recorded as one"; diff --git a/src/init.cpp b/src/init.cpp index 452e53988..2f2a682dc 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -259,12 +259,14 @@ void Shutdown() { LOCK(cs_main); if (pcoinsTip != NULL) { - FlushStateToDisk(); + bool fChainstateFlushed = FlushStateToDisk(); #ifdef ENABLE_WALLET // The hourly SetBestChain in FlushStateToDisk rarely fires here, so a session shorter // than an hour would otherwise never save its witnesses and best block. if (pwalletMain) - pwalletMain->PersistStateAtShutdown(fInitCompleted); + pwalletMain->PersistStateAtShutdown(fInitCompleted, fChainstateFlushed); +#else + (void)fChainstateFlushed; #endif } if (pcoinsTip != NULL) { diff --git a/src/main.cpp b/src/main.cpp index db0af063b..7593a43b5 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3846,10 +3846,11 @@ bool static FlushStateToDisk(CValidationState &state, FlushStateMode mode) { return true; } -void FlushStateToDisk() { +bool FlushStateToDisk() { CValidationState state; if ( HUSH_NSPV_FULLNODE ) - FlushStateToDisk(state, FLUSH_STATE_ALWAYS); + return FlushStateToDisk(state, FLUSH_STATE_ALWAYS); + return true; } void PruneAndFlush() { diff --git a/src/main.h b/src/main.h index 89e962497..861ff7d13 100644 --- a/src/main.h +++ b/src/main.h @@ -323,8 +323,9 @@ CBlockIndex * InsertBlockIndex(uint256 hash); bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats); /** Increase a node's misbehavior score. */ void Misbehaving(NodeId nodeid, int howmuch); -/** Flush all state, indexes and buffers to disk. */ -void FlushStateToDisk(); +/** Flush all state, indexes and buffers to disk. False if the flush failed (out of disk space, a write + * error); true also for an nSPV light client, which has no chainstate to flush. */ +bool FlushStateToDisk(); /** Prune block files and flush state to disk. */ void PruneAndFlush(); diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp index fc2aff3e7..430a5c729 100644 --- a/src/wallet/wallet.cpp +++ b/src/wallet/wallet.cpp @@ -867,7 +867,7 @@ void CWallet::MarkStatePersisted(const CBlockIndex* pindex) RecordStatePersisted(pindex, nWitnessGeneration); } -const char* CWallet::ShutdownSaveSkipReason(bool fInitCompleted) +const char* CWallet::ShutdownSaveSkipReason(bool fInitCompleted, bool fChainstateFlushed) { // AppInit2 failed or was cut short: the other threads were interrupted but not joined, and the // wallet tip may still be unset, in which case SetBestChain would stamp the chain tip over an @@ -876,6 +876,10 @@ const char* CWallet::ShutdownSaveSkipReason(bool fInitCompleted) return "startup did not complete"; if (fWalletNotifyFailed) return "the wallet failed to process a block"; + // The locator would then name a block the chainstate and block index on disk may not have, and + // this is typically a full disk, where a write the size of the wallet is the worst thing to start. + if (!fChainstateFlushed) + return "the chainstate flush failed"; if (!bitdb.IsHealthy()) return "the wallet database environment reported an error"; LOCK(cs_wallet); @@ -891,10 +895,10 @@ const char* CWallet::ShutdownSaveSkipReason(bool fInitCompleted) return nullptr; } -void CWallet::PersistStateAtShutdown(bool fInitCompleted) +void CWallet::PersistStateAtShutdown(bool fInitCompleted, bool fChainstateFlushed) { LOCK2(cs_main, cs_wallet); - const char* skip = ShutdownSaveSkipReason(fInitCompleted); + const char* skip = ShutdownSaveSkipReason(fInitCompleted, fChainstateFlushed); if (skip != nullptr) { LogPrintf("%s: not saving the wallet state: %s\n", __func__, skip); return; diff --git a/src/wallet/wallet.h b/src/wallet/wallet.h index 5b4f8e4db..ac614351b 100644 --- a/src/wallet/wallet.h +++ b/src/wallet/wallet.h @@ -1341,12 +1341,12 @@ public: * was last saved, so a shutdown with no changes after this has nothing to write. */ void MarkStatePersisted(const CBlockIndex* pindex); /** Why a clean shutdown must not write the wallet state now, or nullptr if it should. */ - const char* ShutdownSaveSkipReason(bool fInitCompleted); + const char* ShutdownSaveSkipReason(bool fInitCompleted, bool fChainstateFlushed); /** Called by Shutdown() under cs_main after the chainstate flush, with every other thread * stopped: writes the witnesses and the best-block locator (SetBestChain), unless a gate in * 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); + void PersistStateAtShutdown(bool fInitCompleted, bool fChainstateFlushed); /** 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 From 9bd2fd2b92f5d7a3d706c8c5ccbff22f84606eb7 Mon Sep 17 00:00:00 2001 From: DanS Date: Wed, 28 Oct 2026 12:39:25 -0500 Subject: [PATCH 7/9] wallet: add -walletsaveatshutdown to turn the shutdown save off The shutdown save writes every note-bearing tx with its witness cache, which takes tens of seconds on a large wallet: about 15 s unloaded and 30-40 s under load for a 631 MB regtest wallet, and more for a mainnet wallet of 1-2 GB. A deployment that kills the daemon sooner (an old GUI with a 20 s kill, a short service stop timeout) gains nothing from it: the kill rolls the save back, and the next start spends extra time on BDB recovery. -walletsaveatshutdown=0 skips the save and logs why. The default stays on. The shipped init scripts run with -disablewallet, so their stop timeouts are left as they are. Co-Authored-By: Claude Opus 5.5 --- src/gtest/test_wallet_shutdownsave.cpp | 12 ++++++++++++ src/init.cpp | 2 ++ src/wallet/wallet.cpp | 4 ++++ 3 files changed, 18 insertions(+) diff --git a/src/gtest/test_wallet_shutdownsave.cpp b/src/gtest/test_wallet_shutdownsave.cpp index 78dda74ba..7a7f34356 100644 --- a/src/gtest/test_wallet_shutdownsave.cpp +++ b/src/gtest/test_wallet_shutdownsave.cpp @@ -58,6 +58,18 @@ TEST_F(WalletShutdownSave, SkipsAfterAWalletFailure) { EXPECT_EQ("", Reason(wallet, true)); } +TEST_F(WalletShutdownSave, CanBeTurnedOff) { + CWallet wallet; + CBlockIndex tip; + wallet.SetWalletTip(&tip); + mapArgs["-walletsaveatshutdown"] = "0"; + EXPECT_EQ("disabled by -walletsaveatshutdown=0", Reason(wallet, true)); + mapArgs["-walletsaveatshutdown"] = "1"; + EXPECT_EQ("", Reason(wallet, true)); + mapArgs.erase("-walletsaveatshutdown"); + EXPECT_EQ("", Reason(wallet, true)) << "on by default"; +} + // A failed chainstate flush (typically a full disk) leaves the block the locator would name possibly missing from the // chainstate on disk. TEST_F(WalletShutdownSave, SkipsWhenTheChainstateFlushFailed) { diff --git a/src/init.cpp b/src/init.cpp index 2f2a682dc..5248a6231 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -529,6 +529,8 @@ std::string HelpMessage(HelpMessageMode mode) if (showDebug) strUsage += HelpMessageOpt("-checknotecache", "On every balance or note-listing call, decrypt each cached note it considers again and log and repair any difference from the cache (slow; default: 0)"); strUsage += HelpMessageOpt("-rescan", _("Rescan the block chain for missing wallet transactions") + " " + _("on startup")); + strUsage += HelpMessageOpt("-walletsaveatshutdown", "Save the note witnesses and best block at a clean shutdown, so the next start does not rescan the session's blocks. " + "On a large wallet this can add a minute or more to the stop (default: 1)"); strUsage += HelpMessageOpt("-rescanheight", _("Rescan from specified height when rescan=1 on startup")); strUsage += HelpMessageOpt("-salvagewallet", _("Attempt to recover private keys from a corrupt wallet.dat") + " " + _("on startup")); strUsage += HelpMessageOpt("-sendfreetransactions", strprintf(_("Send transactions as zero-fee transactions if possible (default: %u)"), 0)); diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp index 430a5c729..51f8d3691 100644 --- a/src/wallet/wallet.cpp +++ b/src/wallet/wallet.cpp @@ -874,6 +874,10 @@ const char* CWallet::ShutdownSaveSkipReason(bool fInitCompleted, bool fChainstat // interrupted rescan's checkpoint and the next start would skip the unscanned range. if (!fInitCompleted) return "startup did not complete"; + // For deployments whose stop timeout is shorter than the save takes on their wallet: a kill + // during the save rolls it back and only lengthens the next start. + if (!GetBoolArg("-walletsaveatshutdown", true)) + return "disabled by -walletsaveatshutdown=0"; if (fWalletNotifyFailed) return "the wallet failed to process a block"; // The locator would then name a block the chainstate and block index on disk may not have, and From fef79e7b12576fc07ea721ce7ea335c6fd95fa5a Mon Sep 17 00:00:00 2001 From: DanS Date: Wed, 28 Oct 2026 12:40:42 -0500 Subject: [PATCH 8/9] wallet: skip fully validated txs before the depth lookup in the root selection The root selection of VerifyAndSetInitialWitness looked up the depth of every note-bearing tx on every block, although in the steady state between restarts every note is already validated and nothing is selected. A tx whose notes are all validated is now skipped before GetDepthInMainChain. The selection is the same: it never took a validated note. Co-Authored-By: Claude Opus 5.5 --- src/wallet/wallet.cpp | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp index 51f8d3691..a94c9a1c8 100644 --- a/src/wallet/wallet.cpp +++ b/src/wallet/wallet.cpp @@ -1450,7 +1450,15 @@ int CWallet::VerifyAndSetInitialWitness(const CBlockIndex* pindex, bool witnessO // surfaces exactly where it used to. std::vector rootNotes; for (const std::pair& wtxItem : mapWallet) { - if (wtxItem.second.mapSaplingNoteData.empty() || wtxItem.second.GetDepthInMainChain() <= 0) + // Once every note is validated (the steady state between restarts) nothing here selects one, so + // skip the depth lookup for such a tx. + bool fAnyUnvalidated = false; + for (const mapSaplingNoteData_t::value_type& item : wtxItem.second.mapSaplingNoteData) + if (!item.second.witnessRootValidated) { + fAnyUnvalidated = true; + break; + } + if (!fAnyUnvalidated || wtxItem.second.GetDepthInMainChain() <= 0) continue; for (const mapSaplingNoteData_t::value_type& item : wtxItem.second.mapSaplingNoteData) { const SaplingNoteData* nd = &(item.second); From c0b99a0e1f67ec4f814edc7522820110d5860587 Mon Sep 17 00:00:00 2001 From: DanS Date: Wed, 28 Oct 2026 13:10:41 -0500 Subject: [PATCH 9/9] wallet: test what the shutdown save records and a reseed that succeeds The tests of the shutdown save covered the skip reasons and ClearNoteWitnessCache only, and the witness-root tests compared the new code with itself at 1 and at N threads, with every reseed throwing for want of block files. A stale root table, or a lost change bump, would have passed all of them. SetBestChain's work on an open database moves into a template, SetBestChainWith, so a fake database can fail each step of the transaction; SetBestChain itself only opens the database and calls it. The new tests check: - a write that fails at any step (begin, a tx, the cache size, the best block, the commit) records nothing; a committed one records the wallet tip, which is what is stamped, not the chain tip passed in; without a wallet tip, the block the locator names; - DecrementNoteWitnesses, and adding or changing a note-bearing tx, make the next shutdown save again; re-adding a tx unchanged or adding one without notes does not (AddToWallet on an in-memory BDB environment); - the save writes the best block through the real wallet database, and each skip path writes nothing to it; - a reseed that reads its block from disk and succeeds: the loop goes on, a sibling note in the same tx that had no nullifier gets one from that reseed and is checked with an inline root, every note ends as the serial rules say at 1 and at 8 threads, and the reseed counts as a change to save. Each assertion was checked by breaking the code it covers (the inline root fallback, each bump site, recording on failure, the rescan gate): every such change fails at least one test. Co-Authored-By: Claude Opus 5.5 --- src/gtest/test_wallet_shutdownsave.cpp | 189 ++++++++++++++++++++++++- src/gtest/test_wallet_witnessroots.cpp | 123 +++++++++++++++- src/wallet/wallet.cpp | 28 +--- src/wallet/wallet.h | 32 +++++ 4 files changed, 337 insertions(+), 35 deletions(-) diff --git a/src/gtest/test_wallet_shutdownsave.cpp b/src/gtest/test_wallet_shutdownsave.cpp index 7a7f34356..a823539d4 100644 --- a/src/gtest/test_wallet_shutdownsave.cpp +++ b/src/gtest/test_wallet_shutdownsave.cpp @@ -12,8 +12,10 @@ #include "chainparams.h" #include "util.h" #include "validationinterface.h" +#include "main.h" #include "wallet/db.h" #include "wallet/wallet.h" +#include "wallet/walletdb.h" namespace { @@ -30,6 +32,39 @@ protected: void TearDown() override { fWalletNotifyFailed = false; } }; +class SaveWallet : public CWallet { +public: + explicit SaveWallet(const std::string& strFile = "") : CWallet(strFile) {} + template + bool SetBestChainWith(WalletDB& walletdb, const CBlockLocator& loc) { return CWallet::SetBestChainWith(walletdb, loc); } + void DecrementNoteWitnesses(const CBlockIndex* pindex) { CWallet::DecrementNoteWitnesses(pindex); } +}; + +// Each step of SetBestChainINTERNAL's transaction can be made to fail. +struct FakeWalletDB { + bool fBegin = true, fWriteTx = true, fCacheSize = true, fBestBlock = true, fCommit = true; + int nAborts = 0; + CBlockLocator written; + bool TxnBegin() { return fBegin; } + bool TxnCommit() { return fCommit; } + bool TxnAbort() { nAborts++; return true; } + bool WriteTx(uint256, const CWalletTx&) { return fWriteTx; } + bool WriteWitnessCacheSize(int64_t) { return fCacheSize; } + bool WriteBestBlock(const CBlockLocator& loc) { written = loc; return fBestBlock; } +}; + +// A wallet with one note, so the transaction writes a tx. +void AddNote(CWallet& wallet) +{ + CMutableTransaction mtx; + mtx.nLockTime = 4242; + CWalletTx wtx(&wallet, CTransaction(mtx)); + SaplingNoteData nd(uint256S("01"), uint256S("02")); + wtx.mapSaplingNoteData[SaplingOutPoint(wtx.GetHash(), 0)] = nd; + LOCK(wallet.cs_wallet); + ASSERT_TRUE(wallet.AddToWallet(wtx, true, nullptr)); +} + } // A startup that failed or was cut short never writes: its threads were not joined, and an unset wallet @@ -162,15 +197,61 @@ TEST_F(WalletShutdownSave, SkipsAfterAnIncompleteRescan) { EXPECT_EQ("", Reason(wallet, true)); } -// The skip paths log and return without opening the wallet database. -TEST_F(WalletShutdownSave, SkippedSaveWritesNothing) { - CWallet wallet; +// The save writes through the real wallet database (an in-memory BDB environment here), and a skip writes nothing. +class WalletShutdownSaveDb : public WalletShutdownSave { +protected: + void SetUp() override { + WalletShutdownSave::SetUp(); + bitdb.MakeMock(); + CWalletDB create(strFile, "cr+"); + } + void TearDown() override { + bitdb.Flush(true); + bitdb.Reset(); + WalletShutdownSave::TearDown(); + } + const std::string strFile = "shutdownsave.dat"; + bool ReadBestBlock(CBlockLocator& loc) { + CWalletDB walletdb(strFile, "r"); + return walletdb.ReadBestBlock(loc); + } +}; + +TEST_F(WalletShutdownSaveDb, SavesTheWalletTipAndRecordsIt) { + CWallet wallet(strFile); + AddNote(wallet); + uint256 hash = uint256S("0abc"); CBlockIndex tip; + tip.phashBlock = &hash; wallet.SetWalletTip(&tip); - wallet.MarkStatePersisted(&tip); - LOCK(cs_main); - ASSERT_NO_THROW(wallet.PersistStateAtShutdown(true, true)); - ASSERT_NO_THROW(wallet.PersistStateAtShutdown(false, true)); + { + LOCK(cs_main); + wallet.PersistStateAtShutdown(true, true); + } + CBlockLocator loc; + ASSERT_TRUE(ReadBestBlock(loc)); + ASSERT_FALSE(loc.vHave.empty()); + EXPECT_EQ(hash, loc.vHave.front()); + EXPECT_EQ("nothing changed since the last save", Reason(wallet, true)); +} + +TEST_F(WalletShutdownSaveDb, SkippedSaveWritesNothing) { + CWallet wallet(strFile); + AddNote(wallet); + uint256 hash = uint256S("0abc"); + CBlockIndex tip; + tip.phashBlock = &hash; + wallet.SetWalletTip(&tip); + { + LOCK(cs_main); + wallet.PersistStateAtShutdown(false, true); + wallet.PersistStateAtShutdown(true, false); + wallet.NoteRescanStarted(0); + wallet.PersistStateAtShutdown(true, true); + } + CBlockLocator loc; + EXPECT_FALSE(ReadBestBlock(loc)); + EXPECT_EQ("a rescan did not complete; the next start resumes it from the locator it left", Reason(wallet, true)); } // Opening the wallet database can throw (an environment or file that cannot be opened). Shutdown() has no handler, @@ -206,3 +287,97 @@ TEST_F(WalletShutdownSave, AFailedOpenDoesNotEscape) { ClearDatadirCache(); boost::filesystem::remove_all(dir); } + +// The shutdown save may skip only what a committed write saved: a write that failed at any step records nothing. +TEST_F(WalletShutdownSave, RecordsOnlyACommittedWrite) { + SaveWallet wallet; + AddNote(wallet); + uint256 hash = uint256S("0abc"); + CBlockIndex tip; + tip.phashBlock = &hash; + wallet.SetWalletTip(&tip); + CBlockLocator chainTip(std::vector{uint256S("0def")}); + + for (int step = 0; step < 5; step++) { + FakeWalletDB db; + bool* steps[5] = {&db.fBegin, &db.fWriteTx, &db.fCacheSize, &db.fBestBlock, &db.fCommit}; + *steps[step] = false; + EXPECT_FALSE(wallet.SetBestChainWith(db, chainTip)) << "step " << step; + EXPECT_EQ("", Reason(wallet, true)) << "step " << step; + EXPECT_EQ(step >= 1 && step <= 3 ? 1 : 0, db.nAborts) << "step " << step; + } + + FakeWalletDB db; + EXPECT_TRUE(wallet.SetBestChainWith(db, chainTip)); + EXPECT_EQ("nothing changed since the last save", Reason(wallet, true)); + ASSERT_FALSE(db.written.vHave.empty()); + EXPECT_EQ(hash, db.written.vHave.front()) << "the wallet tip is stamped, not the chain tip passed in"; +} + +// Before init seeds the wallet tip, the block recorded is the one the locator passed in names. +TEST_F(WalletShutdownSave, RecordsTheLocatorsBlockWithoutAWalletTip) { + SaveWallet wallet; + CBlock block; + block.nTime = 1720000000; + CBlockIndex index(block); + { + LOCK(cs_main); + index.phashBlock = &mapBlockIndex.insert(std::make_pair(block.GetHash(), &index)).first->first; + } + FakeWalletDB db; + EXPECT_TRUE(wallet.SetBestChainWith(db, CBlockLocator(std::vector{block.GetHash()}))); + EXPECT_EQ(block.GetHash(), db.written.vHave.front()); + wallet.SetWalletTip(&index); + EXPECT_EQ("nothing changed since the last save", Reason(wallet, true)); + LOCK(cs_main); + mapBlockIndex.erase(block.GetHash()); +} + +// Every change to what SetBestChain writes makes the next shutdown write again. +TEST_F(WalletShutdownSave, NoteChangesNeedASave) { + SaveWallet wallet; + CBlockIndex tip; + tip.SetHeight(5); + wallet.SetWalletTip(&tip); + wallet.MarkStatePersisted(&tip); + ASSERT_EQ("nothing changed since the last save", Reason(wallet, true)); + + // As set from the chain parameters at startup; DecrementNoteWitnesses asserts it was. + extern unsigned int WITNESS_CACHE_SIZE; + const unsigned int nSavedCacheSize = WITNESS_CACHE_SIZE; + WITNESS_CACHE_SIZE = MAX_REORG_LENGTH + 10; + wallet.DecrementNoteWitnesses(&tip); + WITNESS_CACHE_SIZE = nSavedCacheSize; + EXPECT_EQ("", Reason(wallet, true)) << "a disconnected block"; + wallet.MarkStatePersisted(&tip); + + wallet.ClearNoteWitnessCache(); + EXPECT_EQ("", Reason(wallet, true)) << "witnesses cleared"; +} + +// Adding a note-bearing tx, or changing one, is a change to save; re-adding one unchanged (as +// ReacceptWalletTransactions does for every unconfirmed tx at each start) is not, nor is a tx without notes. +TEST_F(WalletShutdownSaveDb, AddingANoteNeedsASave) { + CWallet wallet(strFile); + CBlockIndex tip; + wallet.SetWalletTip(&tip); + wallet.MarkStatePersisted(&tip); + CWalletDB walletdb(strFile, "r+"); + LOCK(wallet.cs_wallet); + + CMutableTransaction mtx; + mtx.nLockTime = 777; + CWalletTx plain(&wallet, CTransaction(mtx)); + ASSERT_TRUE(wallet.AddToWallet(plain, false, &walletdb)); + EXPECT_EQ("nothing changed since the last save", Reason(wallet, true)) << "no notes"; + + mtx.nLockTime = 778; + CWalletTx wtx(&wallet, CTransaction(mtx)); + wtx.mapSaplingNoteData[SaplingOutPoint(wtx.GetHash(), 0)] = SaplingNoteData(uint256S("01"), uint256S("02")); + ASSERT_TRUE(wallet.AddToWallet(wtx, false, &walletdb)); + EXPECT_EQ("", Reason(wallet, true)) << "a new note"; + wallet.MarkStatePersisted(&tip); + + ASSERT_TRUE(wallet.AddToWallet(wtx, false, &walletdb)); + EXPECT_EQ("nothing changed since the last save", Reason(wallet, true)) << "the same tx again"; +} diff --git a/src/gtest/test_wallet_witnessroots.cpp b/src/gtest/test_wallet_witnessroots.cpp index bb641ccf4..3d8a0d72e 100644 --- a/src/gtest/test_wallet_witnessroots.cpp +++ b/src/gtest/test_wallet_witnessroots.cpp @@ -8,7 +8,10 @@ #include #include +#include + #include "chain.h" +#include "chainparams.h" #include "coins.h" #include "init.h" #include "main.h" @@ -16,6 +19,7 @@ #include "primitives/transaction.h" #include "uint256.h" #include "util.h" +#include "validationinterface.h" #include "wallet/wallet.h" #include "zcash/zip32.h" @@ -112,7 +116,9 @@ std::vector Witnesses(int nNotes, int salt, uint256& rootOut) return ws; } -enum Kind { VALID_BELOW_TIP, VALID_AT_TIP, AHEAD_OF_CHAIN, ALREADY_VALIDATED, WRONG_ROOT, NOT_IN_CHAIN }; +// NO_NULLIFIER_VALID: a valid witness at height 2 but no nullifier yet, which only a sibling's reseed gives it. +enum Kind { VALID_BELOW_TIP, VALID_AT_TIP, AHEAD_OF_CHAIN, ALREADY_VALIDATED, WRONG_ROOT, NOT_IN_CHAIN, + NO_NULLIFIER_VALID }; struct Fixture { std::vector txs; @@ -164,6 +170,11 @@ void Fill(RootsWallet& wallet, const Fixture& fx, const RootsChain& chain, Kinds nd.witnesses.push_front(fx.wBelow[0]); nd.witnessHeight = 2; break; + case NO_NULLIFIER_VALID: + nd.witnesses.push_front(fx.wBelow[1]); + nd.witnessHeight = 2; + nd.nullifier = boost::none; + break; } notes[SaplingOutPoint(tx.GetHash(), n)] = nd; } @@ -176,6 +187,60 @@ void Fill(RootsWallet& wallet, const Fixture& fx, const RootsChain& chain, Kinds } } +// A tx with real Sapling outputs to the test key, which the reseed decrypts to derive nullifiers (it never checks +// the proofs or the value commitments). +CTransaction TxWithOutputs(int nOutputs) +{ + auto pa = TestKey().DefaultAddress(); + CMutableTransaction mtx; + mtx.fOverwintered = true; // or the outputs are not serialized into the block file + mtx.nVersion = SAPLING_TX_VERSION; + mtx.nVersionGroupId = SAPLING_VERSION_GROUP_ID; + mtx.nLockTime = 5000; + for (int i = 0; i < nOutputs; i++) { + libzcash::SaplingNote note(pa, 1000 + i); + std::array memo; + memo.fill(0); + auto enc = libzcash::SaplingNotePlaintext(note, memo).encrypt(note.pk_d); + assert(static_cast(enc)); + OutputDescription od; + od.cv = GetRandHash(); + od.cm = note.cm().get(); + od.ephemeralKey = enc->second.get_epk(); + od.encCiphertext = enc->first; + mtx.vShieldedOutput.push_back(od); + } + return CTransaction(mtx); +} + +// Block files for the reseed to read, in a temporary datadir. Undone on destruction. +struct BlockFiles { + boost::filesystem::path dir; + bool hadDatadir; + std::string oldDatadir; + BlockFiles() { + SelectParams(CBaseChainParams::MAIN); + dir = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path("witnessroots-%%%%%%%%"); + boost::filesystem::create_directories(dir); + hadDatadir = mapArgs.count("-datadir") > 0; + oldDatadir = hadDatadir ? mapArgs["-datadir"] : ""; + mapArgs["-datadir"] = dir.string(); + ClearDatadirCache(); + } + void Write(const CBlock& block, CBlockIndex& index) { + CDiskBlockPos pos(0, index.GetHeight() == 0 ? 0 : (unsigned int)boost::filesystem::file_size(GetBlockPosFilename(CDiskBlockPos(0, 0), "blk"))); + ASSERT_TRUE(WriteBlockToDisk(block, pos, Params().MessageStart())); + index.nFile = pos.nFile; + index.nDataPos = pos.nPos; + index.nStatus |= BLOCK_HAVE_DATA; + } + ~BlockFiles() { + if (hadDatadir) mapArgs["-datadir"] = oldDatadir; else mapArgs.erase("-datadir"); + ClearDatadirCache(); + boost::filesystem::remove_all(dir); + } +}; + struct NoteState { bool validated; int witnessHeight; @@ -216,10 +281,12 @@ protected: std::string savedThreads; void SetUp() override { fRequestShutdown = false; + fWalletNotifyFailed = false; // process-wide; the shutdown-save check below reads it savedThreads = mapArgs.count("-witnessbuildthreads") ? mapArgs["-witnessbuildthreads"] : ""; } void TearDown() override { fRequestShutdown = false; + fWalletNotifyFailed = false; if (savedThreads.empty()) mapArgs.erase("-witnessbuildthreads"); else @@ -352,3 +419,57 @@ TEST_F(WalletWitnessRoots, UnconfirmedTxIsNotChecked) { for (int n = 0; n < 2; n++) EXPECT_EQ(i % 2 == 0, States(wallet).at(SaplingOutPoint(fx.txs[i].GetHash(), n)).validated); } + +// A reseed that succeeds: the loop goes on past it, and a sibling that had no nullifier, and so no precomputed root, +// gets one from that reseed and is then checked with its root computed inline. Each note ends as the serial rules +// say, whether the other roots come from one thread or eight, and the reseed counts as a change to save. +TEST_F(WalletWitnessRoots, SuccessfulReseedAndItsSibling) { + Fixture fx = MakeFixture(30); + const int iSeeded = 11; + fx.txs[iSeeded] = TxWithOutputs(2); + BlockFiles files; + RootsChain chain(4, fx.txs, fx.roots); + for (int h = 0; h < 4; h++) + files.Write(chain.blocks[h], chain.index[h]); + auto kinds = [&](int i) { + return i == iSeeded ? std::vector{WRONG_ROOT, NO_NULLIFIER_VALID} : MixedKinds(i); + }; + const SaplingOutPoint seeded(fx.txs[iSeeded].GetHash(), 0), sibling(fx.txs[iSeeded].GetHash(), 1); + + std::map results[2]; + int minHeight[2]; + const char* threads[2] = {"1", "8"}; + for (int r = 0; r < 2; r++) { + mapArgs["-witnessbuildthreads"] = threads[r]; + RootsWallet wallet; + Fill(wallet, fx, chain, kinds); + wallet.SetWalletTip(chainActive.Tip()); + wallet.MarkStatePersisted(chainActive.Tip()); + minHeight[r] = wallet.VerifyAndSetInitialWitness(chainActive.Tip(), false); + results[r] = States(wallet); + const char* reason = wallet.ShutdownSaveSkipReason(true, true); + EXPECT_TRUE(reason == nullptr) << "the reseed changed a witness: " << (reason ? reason : ""); + } + EXPECT_EQ(minHeight[0], minHeight[1]); + EXPECT_EQ(1, minHeight[0]) << "the reseeded note's witness is at its own block"; + EXPECT_TRUE(results[0] == results[1]); + + for (int r = 0; r < 2; r++) { + const NoteState& s = results[r].at(seeded); + EXPECT_FALSE(s.validated); + EXPECT_EQ(1, s.witnessHeight); + EXPECT_EQ(1u, s.nWitnesses); + EXPECT_TRUE(s.hasNullifier); + const NoteState& t = results[r].at(sibling); + EXPECT_TRUE(t.validated) << "the sibling's own witness is valid; threads " << threads[r]; + EXPECT_EQ(2, t.witnessHeight); + EXPECT_TRUE(t.hasNullifier); + } + for (int i = 0; i < fx.nTxs; i++) { + if (i == iSeeded) + continue; + std::vector ks = MixedKinds(i); + for (size_t n = 0; n < ks.size(); n++) + EXPECT_EQ(ks[n] != AHEAD_OF_CHAIN, results[1].at(SaplingOutPoint(fx.txs[i].GetHash(), n)).validated); + } +} diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp index a94c9a1c8..64a9445bf 100644 --- a/src/wallet/wallet.cpp +++ b/src/wallet/wallet.cpp @@ -822,36 +822,10 @@ bool CWallet::CommitAutomatedTx(const CTransaction& tx) { bool CWallet::SetBestChain(const CBlockLocator& loc) { - // FlushStateToDisk passes the chain tip, but ThreadNotifyWallets delivers blocks to the wallet - // asynchronously and can lag it. Stamping a locator ahead of what the wallet has processed makes - // the next start skip those blocks for good (no rescan, no notification): notes received in them - // go missing and spends in them go unseen. So stamp the block the wallet's state reflects (seeded - // by init before the notifier starts, then advanced by ChainTip). Init's own calls, made before - // it is seeded, pass the right locator themselves. - CBlockLocator locator = loc; - const CBlockIndex* pindexStamped = nullptr; - uint64_t nGeneration; - { - LOCK2(cs_main, cs_wallet); - // Read before the write: a change made while it runs bumps the counter past this value, so - // the shutdown save still sees it as unsaved. - nGeneration = nWitnessGeneration; - if (pindexWalletTip != nullptr) { - locator = chainActive.GetLocator(pindexWalletTip); - pindexStamped = pindexWalletTip; - } else if (!loc.vHave.empty()) { - BlockMap::const_iterator mi = mapBlockIndex.find(loc.vHave.front()); - if (mi != mapBlockIndex.end()) - pindexStamped = mi->second; - } - } // Default ctor => fFlushOnClose=true => ~CDB runs a full BDB txn_checkpoint over the entire // cache. Fine for the hourly/shutdown callers; ruinous inside a scan (see SetBestChainNoFlush). CWalletDB walletdb(strWalletFile); - bool fWritten = SetBestChainINTERNAL(walletdb, locator); - if (fWritten) - RecordStatePersisted(pindexStamped, nGeneration); - return fWritten; + return SetBestChainWith(walletdb, loc); } void CWallet::RecordStatePersisted(const CBlockIndex* pindex, uint64_t nGeneration) diff --git a/src/wallet/wallet.h b/src/wallet/wallet.h index ac614351b..5d33601d4 100644 --- a/src/wallet/wallet.h +++ b/src/wallet/wallet.h @@ -985,6 +985,38 @@ protected: return true; } + //! SetBestChain on an open wallet database (a template so tests can pass a fake one). + template + bool SetBestChainWith(WalletDB& walletdb, const CBlockLocator& loc) { + // FlushStateToDisk passes the chain tip, but ThreadNotifyWallets delivers blocks to the wallet + // asynchronously and can lag it. Stamping a locator ahead of what the wallet has processed makes + // the next start skip those blocks for good (no rescan, no notification): notes received in them + // go missing and spends in them go unseen. So stamp the block the wallet's state reflects (seeded + // by init before the notifier starts, then advanced by ChainTip). Init's own calls, made before + // it is seeded, pass the right locator themselves. + CBlockLocator locator = loc; + const CBlockIndex* pindexStamped = nullptr; + uint64_t nGeneration; + { + LOCK2(cs_main, cs_wallet); + // Read before the write: a change made while it runs bumps the counter past this value, so + // the shutdown save still sees it as unsaved. + nGeneration = nWitnessGeneration; + if (pindexWalletTip != nullptr) { + locator = chainActive.GetLocator(pindexWalletTip); + pindexStamped = pindexWalletTip; + } else if (!loc.vHave.empty()) { + BlockMap::const_iterator mi = mapBlockIndex.find(loc.vHave.front()); + if (mi != mapBlockIndex.end()) + pindexStamped = mi->second; + } + } + bool fWritten = SetBestChainINTERNAL(walletdb, locator); + if (fWritten) + RecordStatePersisted(pindexStamped, nGeneration); + return fWritten; + } + private: template void SyncMetaData(std::pair::iterator, typename TxSpendMap::iterator>);