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
+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" : ""));