diff --git a/src/Makefile.gtest.include b/src/Makefile.gtest.include index 09cd79522..5f0a4284d 100644 --- a/src/Makefile.gtest.include +++ b/src/Makefile.gtest.include @@ -19,6 +19,7 @@ hush_gtest_SOURCES = \ gtest/test_sweep_note_selection.cpp \ gtest/test_asyncrpc_cancel.cpp \ gtest/test_wallet_notedata.cpp \ + gtest/test_wallet_witnesstrim.cpp \ gtest/test_net_closesocket.cpp \ gtest/test_net_addrrelay.cpp \ gtest/test_fd_defense.cpp \ diff --git a/src/gtest/test_wallet_witnesstrim.cpp b/src/gtest/test_wallet_witnesstrim.cpp new file mode 100644 index 000000000..fd70e4719 --- /dev/null +++ b/src/gtest/test_wallet_witnesstrim.cpp @@ -0,0 +1,93 @@ +// Copyright (c) 2024-2026 The DragonX 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 "random.h" +#include "uint256.h" +#include "wallet/wallet.h" +#include "zcash/IncrementalMerkleTree.hpp" + +namespace { + +libzcash::SaplingIncomingViewingKey TestIvk() +{ + return libzcash::SaplingIncomingViewingKey(uint256S("0202020202020202020202020202020202020202020202020202020202020202")); +} + +// A note with a witness for every one of nSnapshots blocks, newest at the front, the way +// BuildWitnessCache leaves it: each snapshot is the previous one plus one more commitment. +SaplingNoteData NoteWithHistory(int nSnapshots, int tipHeight, bool fNullifier = true) +{ + SaplingNoteData nd = fNullifier ? SaplingNoteData(TestIvk(), GetRandHash()) : SaplingNoteData(TestIvk()); + SaplingMerkleTree tree; + tree.append(GetRandHash()); // the note's own commitment + nd.witnesses.push_front(tree.witness()); + for (int i = 1; i < nSnapshots; i++) { + nd.witnesses.push_front(nd.witnesses.front()); + nd.witnesses.front().append(GetRandHash()); + } + nd.witnessHeight = tipHeight; + return nd; +} + +const unsigned int CACHE = 109; // WITNESS_CACHE_SIZE on DragonX: MAX_REORG_LENGTH (99) + 10 + +} // namespace + +// Spent deeper than the cache: only the newest witness survives, unchanged, and the note keeps the +// position and height its nullifier and startup validation depend on. +TEST(WalletWitnessTrim, DeeplySpentNoteKeepsOnlyNewestWitness) +{ + SaplingNoteData nd = NoteWithHistory(CACHE, 5000); + const uint256 rootBefore = nd.witnesses.front().root(); + const uint64_t posBefore = nd.witnesses.front().position(); + const boost::optional nfBefore = nd.nullifier; + + EXPECT_TRUE(TrimDeeplySpentNoteWitnesses(nd, CACHE + 1, CACHE)); + ASSERT_EQ(nd.witnesses.size(), 1u); + EXPECT_EQ(nd.witnesses.front().root(), rootBefore); + EXPECT_EQ(nd.witnesses.front().position(), posBefore); + EXPECT_EQ(nd.witnessHeight, 5000); + EXPECT_TRUE(nd.nullifier == nfBefore); + + // Already trimmed: nothing more to do. + EXPECT_FALSE(TrimDeeplySpentNoteWitnesses(nd, CACHE + 50, CACHE)); + EXPECT_EQ(nd.witnesses.size(), 1u); +} + +// Unspent (depth 0) and spent within reorg reach: a reorg may still need the older snapshots. +TEST(WalletWitnessTrim, UnspentAndShallowSpentNotesAreUntouched) +{ + SaplingNoteData unspent = NoteWithHistory(CACHE, 5000); + EXPECT_FALSE(TrimDeeplySpentNoteWitnesses(unspent, 0, CACHE)); + EXPECT_EQ(unspent.witnesses.size(), CACHE); + + SaplingNoteData shallow = NoteWithHistory(CACHE, 5000); + EXPECT_FALSE(TrimDeeplySpentNoteWitnesses(shallow, CACHE, CACHE)); // depth == cache size: still in reach + EXPECT_EQ(shallow.witnesses.size(), CACHE); +} + +// A note without a nullifier is never trimmed (it is not known to be spent), and an empty list stays +// empty: trimming must never be what leaves a note with no witnesses. +TEST(WalletWitnessTrim, NoNullifierOrNoWitnessesIsLeftAlone) +{ + SaplingNoteData noNf = NoteWithHistory(CACHE, 5000, false); + EXPECT_FALSE(TrimDeeplySpentNoteWitnesses(noNf, CACHE + 1, CACHE)); + EXPECT_EQ(noNf.witnesses.size(), CACHE); + + SaplingNoteData empty(TestIvk(), GetRandHash()); + EXPECT_FALSE(TrimDeeplySpentNoteWitnesses(empty, CACHE + 1, CACHE)); + EXPECT_TRUE(empty.witnesses.empty()); +} + +// The serialized note shrinks with the list: what SetBestChain rewrites for every spent note. +TEST(WalletWitnessTrim, SerializedSizeShrinks) +{ + SaplingNoteData nd = NoteWithHistory(CACHE, 5000); + const size_t before = ::GetSerializeSize(nd, SER_DISK, CLIENT_VERSION); + ASSERT_TRUE(TrimDeeplySpentNoteWitnesses(nd, CACHE + 1, CACHE)); + const size_t after = ::GetSerializeSize(nd, SER_DISK, CLIENT_VERSION); + EXPECT_LT(after * 20, before); +} diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp index d1ca4643c..66d68c272 100644 --- a/src/wallet/wallet.cpp +++ b/src/wallet/wallet.cpp @@ -1454,6 +1454,17 @@ void ClearSingleNoteWitnessCache(NoteData* nd) nd->witnessRootValidated = false; } +bool TrimDeeplySpentNoteWitnesses(SaplingNoteData& nd, unsigned int nSpendDepth, unsigned int nCacheSize) +{ + // Never empty the list: UpdateSaplingNullifierNoteMapWithTx drops the nullifier of a note with no + // witnesses, and a spent note without a nullifier is counted as unspent by GetFilteredNotes. + if (!nd.nullifier || nSpendDepth <= nCacheSize || nd.witnesses.size() <= 1) + return false; + while (nd.witnesses.size() > 1) + nd.witnesses.pop_back(); // oldest snapshots are at the back; front() stays the one at witnessHeight + return true; +} + // A note without a nullifier is never extended by BuildWitnessCache (its pending-note gate requires one), // so it doesn't pull the rebuild's start height down. int CWallet::SaplingWitnessMinimumHeight(const boost::optional& nullifier, int nWitnessHeight, int nMinimumHeight) @@ -1754,6 +1765,7 @@ void CWallet::BuildWitnessCache(const CBlockIndex* pindex, bool witnessOnly) // cost changes from O(blocks * walletSize) to O(blocks + activeNotes). struct PendingNote { int startWitnessHeight; SaplingNoteData* nd; }; std::vector pending; + int nNotesTrimmed = 0; for (std::pair& wtxItem : mapWallet) { if (wtxItem.second.mapSaplingNoteData.empty()) continue; @@ -1765,14 +1777,24 @@ void CWallet::BuildWitnessCache(const CBlockIndex* pindex, bool witnessOnly) continue; if (nd->witnesses.empty()) // cannot extend (front() would be UB); the original gate also never matched these in practice continue; - if (GetSaplingSpendDepth(*nd->nullifier) > WITNESS_CACHE_SIZE) + const unsigned int nSpendDepth = GetSaplingSpendDepth(*nd->nullifier); + if (nSpendDepth > WITNESS_CACHE_SIZE) { + // Spent beyond reorg reach: no longer extended, so its older snapshots are dead weight. + if (TrimDeeplySpentNoteWitnesses(*nd, nSpendDepth, WITNESS_CACHE_SIZE)) + nNotesTrimmed++; continue; + } // Only notes that still lag the build target need extension. The lowest such witnessHeight // is exactly startHeight-1 (startHeight = nMinimumHeight+1 from SaplingWitnessMinimumHeight). if (nd->witnessHeight >= startHeight - 1 && nd->witnessHeight <= pindex->GetHeight() - 1) pending.push_back({ nd->witnessHeight, nd }); } } + if (nNotesTrimmed > 0) { + nWitnessGeneration++; // the next SetBestChain (or the shutdown save) writes the shorter lists + LogPrintf("%s: dropped the older witnesses of %d note(s) spent more than %u blocks ago\n", + __func__, nNotesTrimmed, WITNESS_CACHE_SIZE); + } std::sort(pending.begin(), pending.end(), [](const PendingNote& a, const PendingNote& b) { return a.startWitnessHeight < b.startWitnessHeight; }); diff --git a/src/wallet/wallet.h b/src/wallet/wallet.h index baa9f63c2..2521b9635 100644 --- a/src/wallet/wallet.h +++ b/src/wallet/wallet.h @@ -399,6 +399,13 @@ public: typedef std::map mapSproutNoteData_t; typedef std::map mapSaplingNoteData_t; +//! For a note spent nSpendDepth blocks ago: once that is deeper than nCacheSize (WITNESS_CACHE_SIZE) no reorg +//! can un-spend it and BuildWitnessCache stops extending it, so only the newest witness is kept. That one holds +//! the note's position (its nullifier) and the root VerifyAndSetInitialWitness validates; the older snapshots, +//! up to nCacheSize per note, were otherwise kept in memory and rewritten to wallet.dat for every spent note +//! the wallet ever had. Returns true if anything was dropped; never empties the list. +bool TrimDeeplySpentNoteWitnesses(SaplingNoteData& nd, unsigned int nSpendDepth, unsigned int nCacheSize); + /** Sapling note, its location in a transaction, and number of confirmations. */ struct SaplingNoteEntry {