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
+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());
}