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 <noreply@anthropic.com>
This commit is contained in:
2026-10-28 10:36:23 -05:00
co-authored by Claude Opus 5.5
parent fe988d6fbe
commit 693f81bbba
10 changed files with 258 additions and 8 deletions
+2 -1
View File
@@ -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)
+20
View File
@@ -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());
}
+94
View File
@@ -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 <gtest/gtest.h>
#include <string>
#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));
}
+16 -1
View File
@@ -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<bool> 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;
}
+3
View File
@@ -20,6 +20,8 @@
static CMainSignals g_signals;
std::atomic<bool> fWalletNotifyFailed(false);
CMainSignals& GetMainSignals()
{
return g_signals;
@@ -103,6 +105,7 @@ bool NotifyWalletsOrShutdown(const std::function<void()>& 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"),
+5 -1
View File
@@ -8,6 +8,7 @@
#define HUSH_VALIDATIONINTERFACE_H
#include <boost/signals2/signal.hpp>
#include <atomic>
#include <functional>
#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<bool> 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<std::pair<SproutMerkleTree, SaplingMerkleTree>> 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&) {}
+11
View File
@@ -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();
+3
View File
@@ -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);
+81 -3
View File
@@ -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<const uint256, CWalletTx>& 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<const uint256, CWalletTx>& 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" : ""));
+23 -2
View File
@@ -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