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