diff --git a/src/Makefile.gtest.include b/src/Makefile.gtest.include index b119785ce..7fb806c61 100644 --- a/src/Makefile.gtest.include +++ b/src/Makefile.gtest.include @@ -22,7 +22,9 @@ hush_gtest_SOURCES = \ gtest/test_wallet_dbenv.cpp \ gtest/test_wallet_notecache.cpp \ gtest/test_wallet_history.cpp \ - gtest/test_wallet_consolidation.cpp + gtest/test_wallet_consolidation.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_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..a823539d4 --- /dev/null +++ b/src/gtest/test_wallet_shutdownsave.cpp @@ -0,0 +1,383 @@ +// 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 "chain.h" +#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 { + +std::string Reason(CWallet& wallet, bool fInitCompleted, bool fChainstateFlushed = true) +{ + const char* reason = wallet.ShutdownSaveSkipReason(fInitCompleted, fChainstateFlushed); + 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; } +}; + +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 +// 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)); +} + +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) { + 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) { + 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)); +} + +// 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 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); + { + 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, +// 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, 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); +} + +// 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 new file mode 100644 index 000000000..3d8a0d72e --- /dev/null +++ b/src/gtest/test_wallet_witnessroots.cpp @@ -0,0 +1,475 @@ +// 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 + +#include "chain.h" +#include "chainparams.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 "validationinterface.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; +} + +// 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; + 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; + 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; + } + 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); + } + } +} + +// 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; + 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; + 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 + 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); +} + +// 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/init.cpp b/src/init.cpp index 0971625e4..1c571bef9 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -100,6 +100,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 @@ -403,7 +406,15 @@ 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, fChainstateFlushed); +#else + (void)fChainstateFlushed; +#endif } if (pcoinsTip != NULL) { delete pcoinsTip; @@ -675,6 +686,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)); @@ -2863,6 +2876,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) { @@ -3127,5 +3143,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/main.cpp b/src/main.cpp index 199b0504f..648eb791a 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3862,10 +3862,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/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 c737a584c..c83396fda 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 @@ -873,24 +875,115 @@ 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 - // 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; - { - LOCK2(cs_main, cs_wallet); - if (pindexWalletTip != nullptr) - locator = chainActive.GetLocator(pindexWalletTip); - } // 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); + return SetBestChainWith(walletdb, loc); +} + +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, 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 + // 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 + // 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); + 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; +} + +void CWallet::PersistStateAtShutdown(bool fInitCompleted, bool fChainstateFlushed) +{ + LOCK2(cs_main, cs_wallet); + const char* skip = ShutdownSaveSkipReason(fInitCompleted, fChainstateFlushed); + 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 = 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" : strprintf("NOT saved (%s; the previous save stays on disk)", strFailure), + 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) @@ -1270,6 +1363,7 @@ void CWallet::ClearNoteWitnessCache() notes++; } } + nWitnessGeneration++; LogPrintf("%s: Cleared witness data from %d wallet items and %d SaplingNotes\n", __func__, mapWallet.size(), notes); } @@ -1278,6 +1372,7 @@ void CWallet::DecrementNoteWitnesses(const CBlockIndex* pindex) extern int32_t HUSH_REWIND; LOCK2(cs_main, cs_wallet); + nWitnessGeneration++; for (std::pair& wtxItem : mapWallet) { //Sapling @@ -1328,6 +1423,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); @@ -1335,6 +1463,75 @@ 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, + // 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) { + // 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); + 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; @@ -1368,11 +1565,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; } @@ -1385,11 +1585,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 (nd->witnesses.front().root() == whIndex->hashFinalSaplingRoot) { + if (cachedRoot(nd) == whIndex->hashFinalSaplingRoot) { nd->witnessRootValidated = true; + nNotesValidated++; nMinimumHeight = SaplingWitnessMinimumHeight(item.second.nullifier, nd->witnessHeight, nMinimumHeight); continue; } @@ -1397,11 +1599,12 @@ 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) { nd->witnessRootValidated = true; + nNotesValidated++; nMinimumHeight = SaplingWitnessMinimumHeight(item.second.nullifier, nd->witnessHeight, nMinimumHeight); continue; } @@ -1410,8 +1613,12 @@ int CWallet::VerifyAndSetInitialWitness(const CBlockIndex* pindex, bool witnessO //Clear witness Cache for all other scenarios 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; @@ -1459,6 +1666,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; @@ -1586,12 +1797,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; @@ -1676,23 +1882,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) @@ -1708,6 +1898,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) { @@ -2059,6 +2250,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" : "")); @@ -3692,20 +3887,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); @@ -3783,6 +3988,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 0eb3d5b19..6e14a5f39 100644 --- a/src/wallet/wallet.h +++ b/src/wallet/wallet.h @@ -1049,6 +1049,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>); @@ -1057,6 +1089,20 @@ 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; + // 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: bool UpdatedNoteData(const CWalletTx& wtxIn, CWalletTx& wtx, bool fSameBlock); void MarkAffectedTransactionsDirty(const CTransaction& tx); @@ -1394,8 +1440,26 @@ public: void SetConsolidationSuggestion(int overThreshold); 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, 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, 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 + * 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