From c0b99a0e1f67ec4f814edc7522820110d5860587 Mon Sep 17 00:00:00 2001 From: DanS Date: Wed, 28 Oct 2026 13:10:41 -0500 Subject: [PATCH] wallet: test what the shutdown save records and a reseed that succeeds The tests of the shutdown save covered the skip reasons and ClearNoteWitnessCache only, and the witness-root tests compared the new code with itself at 1 and at N threads, with every reseed throwing for want of block files. A stale root table, or a lost change bump, would have passed all of them. SetBestChain's work on an open database moves into a template, SetBestChainWith, so a fake database can fail each step of the transaction; SetBestChain itself only opens the database and calls it. The new tests check: - a write that fails at any step (begin, a tx, the cache size, the best block, the commit) records nothing; a committed one records the wallet tip, which is what is stamped, not the chain tip passed in; without a wallet tip, the block the locator names; - DecrementNoteWitnesses, and adding or changing a note-bearing tx, make the next shutdown save again; re-adding a tx unchanged or adding one without notes does not (AddToWallet on an in-memory BDB environment); - the save writes the best block through the real wallet database, and each skip path writes nothing to it; - a reseed that reads its block from disk and succeeds: the loop goes on, a sibling note in the same tx that had no nullifier gets one from that reseed and is checked with an inline root, every note ends as the serial rules say at 1 and at 8 threads, and the reseed counts as a change to save. Each assertion was checked by breaking the code it covers (the inline root fallback, each bump site, recording on failure, the rescan gate): every such change fails at least one test. Co-Authored-By: Claude Opus 5.5 --- src/gtest/test_wallet_shutdownsave.cpp | 189 ++++++++++++++++++++++++- src/gtest/test_wallet_witnessroots.cpp | 123 +++++++++++++++- src/wallet/wallet.cpp | 28 +--- src/wallet/wallet.h | 32 +++++ 4 files changed, 337 insertions(+), 35 deletions(-) diff --git a/src/gtest/test_wallet_shutdownsave.cpp b/src/gtest/test_wallet_shutdownsave.cpp index 7a7f34356..a823539d4 100644 --- a/src/gtest/test_wallet_shutdownsave.cpp +++ b/src/gtest/test_wallet_shutdownsave.cpp @@ -12,8 +12,10 @@ #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 { @@ -30,6 +32,39 @@ protected: 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 @@ -162,15 +197,61 @@ TEST_F(WalletShutdownSave, SkipsAfterAnIncompleteRescan) { EXPECT_EQ("", Reason(wallet, true)); } -// The skip paths log and return without opening the wallet database. -TEST_F(WalletShutdownSave, SkippedSaveWritesNothing) { - CWallet wallet; +// 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); - wallet.MarkStatePersisted(&tip); - LOCK(cs_main); - ASSERT_NO_THROW(wallet.PersistStateAtShutdown(true, true)); - ASSERT_NO_THROW(wallet.PersistStateAtShutdown(false, true)); + { + 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, @@ -206,3 +287,97 @@ TEST_F(WalletShutdownSave, AFailedOpenDoesNotEscape) { 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 index bb641ccf4..3d8a0d72e 100644 --- a/src/gtest/test_wallet_witnessroots.cpp +++ b/src/gtest/test_wallet_witnessroots.cpp @@ -8,7 +8,10 @@ #include #include +#include + #include "chain.h" +#include "chainparams.h" #include "coins.h" #include "init.h" #include "main.h" @@ -16,6 +19,7 @@ #include "primitives/transaction.h" #include "uint256.h" #include "util.h" +#include "validationinterface.h" #include "wallet/wallet.h" #include "zcash/zip32.h" @@ -112,7 +116,9 @@ std::vector Witnesses(int nNotes, int salt, uint256& rootOut) return ws; } -enum Kind { VALID_BELOW_TIP, VALID_AT_TIP, AHEAD_OF_CHAIN, ALREADY_VALIDATED, WRONG_ROOT, NOT_IN_CHAIN }; +// 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; @@ -164,6 +170,11 @@ void Fill(RootsWallet& wallet, const Fixture& fx, const RootsChain& chain, Kinds 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; } @@ -176,6 +187,60 @@ void Fill(RootsWallet& wallet, const Fixture& fx, const RootsChain& chain, Kinds } } +// 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; @@ -216,10 +281,12 @@ 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 @@ -352,3 +419,57 @@ TEST_F(WalletWitnessRoots, UnconfirmedTxIsNotChecked) { 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/wallet/wallet.cpp b/src/wallet/wallet.cpp index a94c9a1c8..64a9445bf 100644 --- a/src/wallet/wallet.cpp +++ b/src/wallet/wallet.cpp @@ -822,36 +822,10 @@ bool CWallet::CommitAutomatedTx(const CTransaction& tx) { 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; - 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; - } - } // 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); - bool fWritten = SetBestChainINTERNAL(walletdb, locator); - if (fWritten) - RecordStatePersisted(pindexStamped, nGeneration); - return fWritten; + return SetBestChainWith(walletdb, loc); } void CWallet::RecordStatePersisted(const CBlockIndex* pindex, uint64_t nGeneration) diff --git a/src/wallet/wallet.h b/src/wallet/wallet.h index ac614351b..5d33601d4 100644 --- a/src/wallet/wallet.h +++ b/src/wallet/wallet.h @@ -985,6 +985,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>);