wallet: drop the witness history of notes spent beyond reorg reach

BuildWitnessCache stops extending a note once its spend is deeper than
WITNESS_CACHE_SIZE (MAX_REORG_LENGTH + 10 = 109): no reorg can un-spend it any
more. But the up-to-109 witness snapshots the note had by then were never
released. Every spent note the wallet ever had kept them, in memory and in
wallet.dat, and SetBestChain rewrote them all on every save. On a wallet that
receives a steady stream of deposits and sweeps them, memory and wallet.dat grow
with the number of notes ever received.

Measured in the 2026-11-29/30 stress soak (exchange-style wallet, ~360 deposit
notes an hour swept to a withdraw address): RSS rose ~120-170 MB an hour to
2.9 GB over 18 h, wallet.dat reached 855 MB for ~6,500 transactions, and the
per-block log reported ~6,200 witnessed notes. With deposits stopped, RSS stopped
climbing, so this is history growth, not a leak.

Now such a note keeps only its newest witness (front()). That one is at
witnessHeight, gives the position its nullifier is derived from, and is the root
VerifyAndSetInitialWitness validates at startup, so a trimmed note loads and
validates exactly as before. The list is never emptied: a note with no witnesses
loses its nullifier in UpdateSaplingNullifierNoteMapWithTx and would then count
as unspent. A deeper-than-cache reorg (only possible after raising -maxreorg)
already pops or clears such notes' single remaining witness and reseeds them.

The trim runs in the per-block BuildWitnessCache pass, which already evaluates
each note's spend depth, so it costs no extra wallet walk. It bumps
nWitnessGeneration so the next SetBestChain or the shutdown save writes the
shorter lists, and logs how many notes it trimmed.

New gtest WalletWitnessTrim covers: deeply spent notes keep exactly their newest
witness (root, position, height, nullifier unchanged); unspent and in-reach notes,
notes without a nullifier, and empty lists are untouched; the serialized note
shrinks by more than 20x.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-11-29 22:23:02 -06:00
co-authored by Claude Opus 5.5
parent 9c7c5835bd
commit 19f20736df
4 changed files with 124 additions and 1 deletions
+23 -1
View File
@@ -1452,6 +1452,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<uint256>& nullifier, int nWitnessHeight, int nMinimumHeight)
@@ -1752,6 +1763,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<PendingNote> pending;
int nNotesTrimmed = 0;
for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
if (wtxItem.second.mapSaplingNoteData.empty())
continue;
@@ -1763,14 +1775,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; });