When CommitAutomatedTx refused a transaction (AcceptToMemoryPool rejected it),
the sweep and autoshield ops returned false without setting an error, so the
operation finished as "failed" with an empty message:
Sweep operation finished. (status=failed, error=)
Seen twice in 175 sweep rounds in the 2026-12-01 soak; one was a note already
spent by another transaction ("sapling nullifier ... exists"). Both ops now set
RPC_WALLET_ERROR and a message naming the rejected txid, pointing at debug.log
for the mempool's reason (CommitTransaction does not return it), and saying the
next round retries. Consolidation already records a per-address reason.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
ResendWalletTransactionsBefore applied its "expired, don't relay" test to every
wallet transaction, mined ones included. A confirmed transaction is past its
expiry height a few hundred blocks after it was mined, so every pass (every
0-30 minutes) logged one "ignoring expired tx" line per transaction the wallet
had ever made, and the count only grew.
Measured in the 2026-12-01 soak (exchange-style wallet, ~15k transactions):
14,735 distinct "expired" txs x 89 passes = 1.1 million lines; debug.log grew
by 354 MB in 24 h.
Mined transactions are now skipped before the expiry test (they have nothing to
rebroadcast; RelayWalletTransaction already refused them). Genuinely expired
unconfirmed transactions are counted and reported in one summary line, with the
per-transaction detail under -debug=wallet. The function now takes cs_main
itself as well; both callers already hold it, and GetDepthInMainChain needs it.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
The previous fix (3e75769a4) let a due sweep give way once to a consolidation
round that was running or "due within 5 blocks", and then hold every new
consolidation round off until the sweep had run. On a wallet that always has
something to sweep this starved consolidation instead: the 5-block "give way"
itself set the waiting flag, the next consolidation was refused because a sweep
was waiting, the sweep ran, and so on.
Measured on the 2026-11-30 soak of 9c7c5835b (exchange-style wallet, zsweep
every 5 blocks, consolidation at the default 25): in 15.5 h, 2,375 sweep txs and
0 consolidation txs (273 deferrals); the withdraw address piled up to 5,898
unspent notes and RSS reached 4.7 GB.
Now the two ops take strict turns:
- a due sweep that finds a consolidation round running sets fSweepWaiting, and
no new consolidation round starts until the sweep is dispatched;
- a due consolidation round that finds a sweep running sets
fConsolidationWaiting, and no new sweep round starts until it is dispatched;
- the 5-block blackout is gone (with consolidationinterval=5 it was always true);
- whichever op yields clears its own flag, so they can never both be waiting;
- each flag is cleared on dispatch, when its op is off, or when it is skipped for
a locked wallet.
z_consolidationstatus gains waiting_for_sweep, next to z_sweepstatus's
waiting_for_consolidation. doc/zsweep-consolidation.md updated.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
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>
RunSaplingSweep returned early, and retried the next block, whenever a
consolidation round was running or due within 5 blocks, but kept no memory of
having given way. With consolidationinterval=5 the "due within 5 blocks" test is
always true, and with longer intervals a long consolidation round could fill the
remaining blocks, so on a busy wallet the sweep could go a whole run without
dispatching while deposits piled up.
Measured on the 2026-11-29 stress fleet (exchange-style wallet, zsweepinterval=5,
consolidationinterval=5, 150 deposit notes): in 20 minutes consolidation ran
4 rounds / 11 txs and the sweep 0, with 45 "not sweeping since consolidation"
lines; the deposit notes never moved.
A due sweep now gives way once and records it in fSweepWaiting. While that is
set, RunSaplingConsolidation starts no new round (nextConsolidation is left
alone, so that round runs right after the sweep), and the sweep skips the
5-block blackout. The flag is cleared when the sweep is dispatched, disabled, or
skipped for a locked wallet, so it cannot hold consolidation off once there is
no sweep to wait for. z_sweepstatus reports it as waiting_for_consolidation.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
The automated ops set nExpiryHeight to buildHeight + 15. The wallet only
rebroadcasts its unconfirmed transactions every 0-30 minutes (randomised, for
privacy), and only those a few minutes older than the last block, while each
transaction is relayed to a random half of the node's peers. A tx that missed
the miners on its first relay was therefore almost never retried before block
+15 (~9 minutes on mainnet), and expired. The op had already logged "Committed"
and, for zsweep, added it to amount_swept; the notes reappeared as unspent and
were swept again a round later. Nothing was lost, but z_sweepstatus overstated
progress, and manual z_sendmany calls from the deposit addresses kept colliding
with the re-sweeps ("bad-txns-shielded-requirements-not-met").
Measured on the 2026-11-29 stress fleet (exchange-style node with ~5 peer
connections): 38 of 184 sweep txs (21%) never confirmed; the log shows 1810
"ignoring expired tx" lines from the rebroadcast pass.
The three ops now use -txexpirydelta (default 200), the same window every other
wallet transaction gets, through AutoOpExpiryDelta(). Their NU-straddle guards
use the same window, so near a network upgrade they pause for the full expiry
window instead of 15 blocks. This applies to v1.2.0 too (its per-op
*_EXPIRY_DELTA constants were also 15); it is not a v1.3.0 regression.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Neither has a caller anywhere in the tree. Both took cs_main and cs_wallet by hand, so any future
caller that threw between them would have leaked both locks. Remove them rather than keep a trap.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
User-visible text:
- validateaddress help: "the given DragonX address" / "The DragonX
address validated".
- getblockmerkletree help and error: "a given block height" / "Invalid
block height parameter".
- ContextualCheckBlockHeader debug log: "HAC nbits" -> "nbits".
Comments and docs: HAC / Arrakis chain -> "smart chain" or "chain"
(src, contrib, util, doc/DEVELOPING.md, doc/randomx.md); the HAC and
Arrakis lines in doc/relnotes/README.md and contrib/debian/changelog
say "smart chain". Older "Hush Smart Chain" history is left as is.
Dead scripts removed: src/hush-arrakis-chain(.bat), src/smartchains and
src/sc/{koolaid,kush,zex}. They all start ./hushd, which the build no
longer produces, and none is in the release archive or the deb package.
The Dockerfile symlink to the launcher is dropped, and the rpc-test
framework defaults to src/dragonxd like util.py already does.
README: P2P port is 21768 (what the network and contrib/seeds use),
not 18030.
No identifiers, options (-ac_*), consensus code or licence headers are
changed. The miner.cpp change is a comment only.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The parts of origin/perf/wallet-scan-rpc-costs that dev's note cache did not already cover:
- listtransactions computed count+from in an int, so a large count (e.g. INT_MAX, a common "all"
idiom) wrapped and returned nothing. It is now clamped. Regtest: `listtransactions "*" 2147483647 1`
returned 0 entries on the old binary and 150 of 151 here; a normal page is byte-identical.
- Fewer per-entry copies of wallet transactions in listtransactions and gettransaction, and reads by
reference in other wallet RPCs.
- z_viewtransaction skips a spend whose parent transaction is no longer in the wallet (e.g. after
-deletetx) instead of failing with map::at; that spend, and outputs only its key could recover,
are then left out of the reply.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
From origin/perf/wallet-scan-rpc-costs, both still on dev:
- getinfo and getnetworkinfo read vNodes.size() and iterated vNodes without cs_vNodes, racing the
network threads that add and remove peers (a reallocation mid-iteration is undefined behaviour).
Both now count through one helper that takes the lock.
- z_getoperationstatus and z_listoperationids took cs_main and cs_wallet, though they only read the
async queue (which has its own mutex) and each operation's status. GUIs poll them, so every poll
contended with block validation. Regtest: z_getoperationstatus reports a running sweep normally.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
From the general audit, all still on dev:
- importprivkey used its height argument only when exactly 4 arguments were given, so supplying the
optional 5th (secret_key) silently rescanned from genesis. Regtest under gdb: with
`true 120 <prefix>` the old binary started ScanForWalletTransactions at height 0, this one at 120.
- getblockhashes: `if (fActiveOnly) LOCK(cs_main);` was unbraced, so the lock was released on the
same line and, with noOrphans, GetTimestampIndex checked rows against chainActive unlocked. The
lock now spans that call when noOrphans is set; without it the call only walks the LevelDB index
and takes no lock, as before.
- getblockdeltas and getblockmerkletree read mapBlockIndex, chainActive and (getblockmerkletree)
pcoinsTip's anchor cache, which inserts on a miss, with no lock; every sibling RPC locks.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
The base class said "Override this method if you can interrupt execution of main()", but cancel()
was not virtual. Every caller holds a std::shared_ptr<AsyncRPCOperation> -- the queue's map, the
wallet schedulers, z_consolidate -- so the overrides in the sweep, consolidation and autoshield ops,
written to move an EXECUTING operation to CANCELLED, never ran: the base version only cancels an
operation that has not started. In practice that meant a stop could not interrupt a running
automatic round; the node waited for it to finish every remaining transaction. Consolidation had
grown its own ShutdownRequested() checks as a workaround.
- cancel() is virtual, and the three overrides are marked override, so this cannot silently
regress: with the base non-virtual again they fail to compile.
- Only the queue closing at shutdown can cancel a running round. The schedulers return early
while a round is in flight (the sweep since its in-flight guard, consolidation and autoshield on
their running flags) and z_consolidate refuses while a consolidation runs, so they only ever
cancel an operation that has finished, which the overrides leave alone.
- A round cancelled part-way stays CANCELLED instead of being relabelled SUCCESS or FAILED by how
much of it got done, and logs "(status=cancelled)".
- The sweep checks isCancelled() || ShutdownRequested() before starting each address as well as
after each build, so a stop does not wait for another multi-second build to be discarded.
- Comments that described the old behaviour are corrected.
New gtest AsyncRPCCancel: each override is reached through a shared_ptr<AsyncRPCOperation> and
stops an EXECUTING op, leaves SUCCESS/FAILED alone and still cancels a READY one; an op without an
override still only cancels before it starts (z_sendmany and friends are unaffected). With the old
declarations, the three override tests fail. Regtest, same fixture, the node stopped while a sweep
round was building its first of four transactions: dev took 56.2 s to exit, building all four first;
this exits in 9-12 s ("Canceled. Stopping.", status=cancelled), and the wallet is intact on restart.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
The sweep took the first maxInputs notes of an address and asked GetSaplingNoteWitnesses for their
witnesses. If one had none -- a missing witness, or a desynced one that does not match the anchor
the others agree on -- it logged "Missing Witnesses! Stopping.", built anyway with that note's value
still counted, failed the build, and broke out of the address loop. The round failed, every address
after that one went unswept, and the same thing happened again every interval. And because that
anchor is a majority vote, a desynced group that outnumbers the good notes at an address (as one did
on a real wallet) makes the "agreed" root one the chain never had.
SelectSweepableNotes now picks each transaction's notes. It copies each note's latest cached witness
under cs_wallet (GetSaplingNoteLatestWitness, which does no hashing), computes each root once with
no lock held, groups the notes by root, and takes the largest group whose root is an anchor the
chainstate knows -- the same lookup consensus applies to shielded spends. It reads the notes in
windows of 2 * maxInputs and stops as soon as a known group can fill the transaction, so a healthy
address costs about what the old first-maxInputs selection did (a Merkle root is ~1-2 ms, and an
earlier all-notes pass held cs_main for ~30 s on a 13k-note wallet), while a run of bad notes at the
front cannot hide good ones behind it. Notes left out are logged once per address with a count and
the first outpoint, and looked at again next round. In the round itself:
- an address with no spendable notes is skipped rather than failing the round;
- a failed build moves on to the next address (nothing was recorded); a failed commit still stops
the round, because CommitTransaction has already written the tx to the wallet;
- a round counts as incomplete only once it has committed something, so an address whose notes are
all unspendable no longer has the scheduler re-dispatch on every block -- it is retried an
interval later.
New gtest SweepNoteSelection, 9 cases, including a desynced majority, a desynced run ahead of good
notes, a lone good note behind five desynced groups, two real anchors, and a healthy address being
read one window at a time. Accepting every root as an anchor fails 4 of them, and reading every note
fails the window test (200 notes took 244 ms against one window's worth). End to end on regtest,
with gdb making the wallet's first witness lookup find nothing: the other 4 notes at that address
and every other address were swept in the same round, the round succeeded, the next round swept
the skipped note, and the wallet drained fully, with no per-note desync lines in the log.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
-zapwallettxes erases every wallet transaction but leaves the best-block locator at the old tip.
The forced rescan that follows starts at genesis, and ScanForWalletTransactions only ever moves the
locator forward, so when that rescan was cut short -- killed, or a clean shutdown -- the next normal
start read the old locator, skipped the rescan, and the wallet came up without the erased
transactions: zero balance and no notes until someone ran -rescan. Plain -rescan had the same gap.
- Before a forced rescan that starts below the locator on disk, move the locator back to where the
scan starts (RewindWalletLocatorForRescan). An interrupted scan then checkpoints forward from
there, and a killed one restarts from there. With -zapwallettxes this is done right after the
zap, so a startup that fails in between (a config error, say) cannot reopen the gap.
- SetBestChainWith no longer stamps the chain tip while the startup rescan is running or was cut
short and init has not seeded the wallet tip yet. That stamp comes from FlushStateToDisk (its
hourly write, or the one in Shutdown) and would overwrite the scan's own locator the same way.
Regtest, dev vs this branch on the same fixture (141 blocks, 26 notes, 146 txs, 430.0496418 DRGX),
stopping the node under gdb as the zap rescan begins and then starting it normally: dev comes up
empty (0 balance, 0 notes, 0 txs) after both SIGKILL and SIGTERM; this branch resumes the rescan
from block 0 and restores exactly the baseline. New gtest
WalletShutdownSave.DoesNotStampTheChainTipOverAnIncompleteStartupRescan.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Three z_sweepstatus fields read members nothing kept up to date:
- zsweepmaxinputs showed a member never set from -zsweepmaxinputs, so it always said 200 while
the op used GetArg("-zsweepmaxinputs", 8). Parse and range-check the option once at startup into
that member (5 to 100, default 8; same fallback as before) and have the op read it.
- zsweepfee showed a member never set from -zsweepfee. Report fSweepTxFee, which the op uses, and
drop the dead member.
- amount_swept showed a counter nothing incremented (an int of puposhis, which would also have
overflowed past ~21 DRGX). Count committed sweep transactions in a CAmount and report DRGX.
Add wallet_locked, so it is visible at a glance why nothing is being swept, and give the RPC a real
help text (it had a stray "}" and no Result section). Add the include guard that
asyncrpcoperation_sweep.h lacked, now that rpcwallet.cpp includes it too.
Release-notes item: amount_swept is now a decimal DRGX amount (it was an integer that was always 0).
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
On an encrypted wallet that is locked, the sweep op could get no spending key, skipped every
address without a word, and finished "Created 0 transactions ... status=1": a successful round that
swept nothing, every interval, with no hint anywhere. Every restart locks an encrypted wallet, so an
exchange that restarted its node to upgrade saw its deposit -> withdraw sweep simply stop.
- RunSaplingSweep skips the round while the wallet is locked, logs why, and looks again an interval
later, as consolidation and autoshield already do.
- The op fails with RPC_WALLET_UNLOCK_NEEDED if the wallet is locked when it starts, and fails the
round with that error if the wallet is locked part-way through (a walletpassphrase timeout).
- An address the wallet has only a viewing key for is now logged (zrpcunsafe) rather than skipped
silently.
Regtest, dev vs this branch on the same encrypted fixture: dev logs "Created 0 transactions ...
status=success" while locked; this logs "wallet locked; not sweeping ... Unlock it with
walletpassphrase", and locking mid-round ends it "status=failed, error=Wallet was locked during
the sweep ...". After unlocking, both sweep everything.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
RunSaplingSweep re-dispatched a sweep on every block while a round was still running. That never
stopped the running op -- AsyncRPCOperation::cancel() is not virtual, so through the queue's base
pointer it only cancels an op that has not started, and the sweep's own cancel() override is never
reached -- it just queued a fresh round behind it, which then repeated note selection over the
whole wallet and was itself superseded a block later. Leave an in-flight op alone, as
RunSaplingConsolidation already does, and log that it is still running and since which height.
A round can outlive the block it started at (a busy deposit wallet takes seconds per sweep
transaction), but since v1.3.0 every transaction in a round was built and expired against the tip
read once when the round began, so late transactions in a long round could be expiring, or already
expired, by the time they were committed. Read the tip for each transaction, and re-check the
NU-straddle guard there.
Regtest, same fixture as dev (3 deposit addresses x 7 notes, -zsweepmaxinputs=5, a block every
~3 s while each build takes ~7 s): the same 7 sweep transactions and amount as dev, with "still
running; not re-dispatching" where dev queued a redundant round on every block.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
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 <noreply@anthropic.com>
z_consolidate creates and broadcasts transactions, so like z_sendmany
and z_shieldcoinbase it must not run in safe mode. Its fee argument is
in DRGX, like z_sendmany's, while -consolidationtxfee and every amount
in z_consolidationstatus are in puposhis; the help and the doc now say
so.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
With -zsweep=1 and -consolidation=0, z_consolidate consolidated every
address: the sweep-address substitution sat under
fSaplingConsolidationEnabled, and an explicit address list skipped the
sweep-address rule. Sweep and consolidation then fight over the same
notes and pay fees for nothing. Apply the rule whatever -consolidation
is, and have z_consolidate refuse any address but the sweep address
while zsweep is on.
The branch also started checking -consolidatesaplingaddress with
-consolidation=0, so an old config with a stale, watch-only or mistyped
address, which used to be ignored, stopped startup. Keep the InitError
with -consolidation=1; with it off, warn and drop the address (with
zsweep on, use the sweep address instead).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The round took its anchor from GetSaplingNoteWitnesses, a majority vote
over the planned notes alone that never looks at the chain. A real
wallet has had 108 notes desynced onto one root the chain never had, at
the same address as 104 healthy ones. Smallest-first planning can pick
a batch that is mostly desynced notes. The vote then made the healthy
notes the "unusable" ones, and the tx was proved at a non-anchor: Build
succeeds, since witnesses and anchor agree, but CommitTransaction adds
it to the wallet before the mempool refuses it. Its notes then look
spent, and since the plan is nearly deterministic this recurs every
round. One failed tx also ended the round for every other address.
PlanSaplingConsolidationSpends now plans over the notes that can be
spent together. A planned note is used only if its newest witness root
is a Sapling anchor the chain holds (GetSaplingAnchorAt on pcoinsTip,
the check consensus makes) and is its address's anchor: the tip's root
if any planned note is there, else the chain anchor most share. Other
planned notes are left out and the round is re-planned until none are.
The planner is pure apart from its callbacks and is tested, including
a desynced majority. GetSaplingNoteLatestWitness is pass 1 of
GetSaplingNoteWitnesses, split out; that function is unchanged.
A tx that fails to build or commit now only skips the rest of its own
address's txs; the first failure is the round's error.
Skipped notes are logged once per round with a count and the first
five outpoints, instead of once per process: a note that is unusable
only during a witness rebuild was otherwise never reported again.
The fee rule moves into SaplingConsolidationTxFee, with a test.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A stop issued during a consolidation round waited for the whole round
to be built and committed: 634 s in review, ~8 min for the default 18
txs on a crowded wallet. StopRPC cancels every queued operation, but
AsyncRPCOperation::cancel() is not virtual, so the op's own cancel(),
which moves an EXECUTING op to CANCELLED, is never called and its
isCancelled() checks between transactions never fire. A GUI that kills
dragonxd 20 s into shutdown then kills it mid-round, which costs a
chainstate replay and a witness rebuild on the next start.
Check ShutdownRequested() next to isCancelled() before building each
transaction and before committing it, so a stop waits for one tx at
most. Making cancel() virtual would also do it, but would change what
the sweep and autoshield schedulers' cancel of their previous op does.
dragonxd also has a single async worker, so a z_sendmany made during a
round waited for all of it. After each committed tx the round now ends
when another operation is queued. Its unspent planned notes are
unlocked as before and the next round takes them up. last_round and the
op result report it as yielded.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The root selection of VerifyAndSetInitialWitness looked up the depth of
every note-bearing tx on every block, although in the steady state
between restarts every note is already validated and nothing is
selected. A tx whose notes are all validated is now skipped before
GetDepthInMainChain. The selection is the same: it never took a
validated note.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The shutdown save writes every note-bearing tx with its witness cache,
which takes tens of seconds on a large wallet: about 15 s unloaded and
30-40 s under load for a 631 MB regtest wallet, and more for a mainnet
wallet of 1-2 GB. A deployment that kills the daemon sooner (an old GUI
with a 20 s kill, a short service stop timeout) gains nothing from it:
the kill rolls the save back, and the next start spends extra time on
BDB recovery.
-walletsaveatshutdown=0 skips the save and logs why. The default stays
on. The shipped init scripts run with -disablewallet, so their stop
timeouts are left as they are.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The shutdown save runs right after FlushStateToDisk(), whose void
wrapper dropped the result. If that flush failed (out of disk space, a
coins database or block index write error), the save still stamped the
wallet tip, a block the chainstate and block index on disk might not
have, and started a write the size of the wallet on what is typically a
full disk.
FlushStateToDisk() now returns the result of the flush it runs (true for
an nSPV light client, which flushes nothing). Its behaviour is
unchanged, and the other callers ignore the result as before. Shutdown()
passes it to PersistStateAtShutdown, which skips the save with "the
chainstate flush failed".
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
SetBestChain opens the wallet database (CWalletDB) outside the try block
of SetBestChainINTERNAL, and CDB's constructor throws when the
environment or the file cannot be opened. Shutdown() calls the save with
no handler around it, so such a failure ended in std::terminate: the
coins views and the block tree were not deleted, the wallet was not
flushed and the pidfile stayed. The hourly SetBestChain runs inside
FlushStateToDisk's try block and never had this problem.
PersistStateAtShutdown now catches the exception, logs the save as NOT
saved with the reason, records nothing, and lets the teardown go on.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A rescan started by RPC (rescan, z_importkey, z_importviewingkey,
importprivkey) that is cut short by abortrescan or by a stop writes its
progress as the best-block locator, or leaves the older locator when it
may not advance it. The next start resumes the scan from there. The
shutdown save then stamped the wallet tip over that locator, so the next
start found nothing to rescan: for a newly imported key, its notes in the
unscanned blocks stayed out of the wallet, with no warning, until a
manual rescan. On dev a session shorter than an hour never wrote at
shutdown, so this is a regression of the shutdown save.
ScanForWalletTransactions now records, for the session, where it left
the locator on disk: the persisted height when it starts (so a scan that
throws counts as incomplete too), the checkpoint or the old locator when
it is cut short. A scan that reaches the tip clears this, unless an
earlier scan was interrupted and this one starts above where that one
left the locator. While it is set, the shutdown save is skipped, as dev
would, and logs why.
The hourly SetBestChain after abortrescan is unchanged: it stamps the
wallet tip as it does on dev.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The op tallied the round in a local and handed it over only through
setConsolidationResult, which an exception thrown mid-round skips, so
last_round and the cumulative totals lost transactions it had already
committed. Tally into the member main() records from instead.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Consolidation stays off by default, but a miner whose autoshield adds
one note per round should hear that it would help before the wallet
slows down.
With -consolidation off, count the addresses holding more than
-consolidationthreshold eligible notes right after the startup note
cache warm-up (the plaintexts are in memory then, so the walk is
cheap) and log once:
N addresses have more than 25 spendable notes; consider
-consolidation=1 or z_consolidate
z_autoshieldstatus reports it as consolidation_suggested (refreshing
the count at most once per consolidation interval, since autoshield is
what keeps adding the notes), and z_consolidationstatus verbose as
consolidation_suggested and consolidation_suggested_count from its own
walk. A later count that first finds an address over the threshold
logs the line then, still only once per run.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A CLI miner who keeps -consolidation off (the default) has no way to
shed the notes autoshield piles up short of scripting z_mergetoaddress,
which pauses the miner and rebuilds its RandomX dataset on every call.
z_consolidate ( fee batchsize maxtxs ["zaddr",...] ) runs one round of
the built-in consolidation now, with the -consolidation policy, also
when -consolidation is off. Any argument may be null to keep its
setting; out-of-range values and addresses that are not the wallet's
own Sapling addresses are refused rather than clamped. It returns the
operation id; z_getoperationstatus/-result give the round's result,
and z_consolidationstatus records it as a last_round with manual=true.
It refuses while the node is syncing (the test ChainTip applies to the
periodic ops), while the wallet is locked, and while a consolidation,
zsweep or autoshield round is in flight. It takes the scheduler's slot
like RunSaplingConsolidation does (fConsolidationRunning plus the op
id), so sweep and autoshield defer to it and its completion releases
the slot. The scheduler no longer pops a z_consolidate op from the
queue when it starts the next round, so the user's result stays until
z_getoperationresult collects it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
z_consolidationstatus reported amount_consolidated from an int that
nothing ever added to (so always 0, and it would have overflowed past
21 DRGX), no policy, nothing about the rounds, and no hint of why a
round would not run.
Each consolidation op now records its round in CWallet's
consolidationStats when it finishes (the op-id-guarded block in
main(), so on success, failure and exception alike): tip height,
time, txids, notes merged, amount merged and created, fees, notes
skipped for a bad witness, and the error that stopped it, if any.
The cumulative totals come from the same records.
z_consolidationstatus keeps its fields (amount_consolidated now
accumulates, in puposhis like consolidationtxfee) and adds the policy
settings, rounds, txs_created, notes_consolidated, last_round and a
disabled_reason like z_autoshieldstatus has: off, wallet locked,
syncing (the same test ChainTip applies), or deferred while zsweep or
autoshield runs. With the new optional verbose argument it also counts
every address's eligible notes and says which are over the threshold;
that walks the wallet under cs_main + cs_wallet, so only on request.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
VerifyAndSetInitialWitness logs one line per reseeded note and nothing
else, so the pass that root-checks every note after a start (seconds on
a large wallet) is invisible, and the reseed line's "<i> of <N>" reads
like progress although <i> is the tx's place in mapWallet and <N> is
mapWallet.size(): transactions, not notes.
Append "[reseed <k>]", the running count of reseeded notes, to the
reseed line. Its prefix, the comma after the hash and " of <N>" stay
exactly as they were: ObsidianDragon parses them (the hash between
"for tx " and the comma, the number after " of ") to track progress.
Add one summary line at the end of a pass that validated or reseeded
anything: the notes validated, reseeded, already valid and ahead of the
chain, the lowest witness height and the elapsed ms. A routine block
with nothing to check prints nothing new.
Logging only; the counters feed no decision.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
After every start the first VerifyAndSetInitialWitness pass checks each
note's witness: front().root(), compared with hashFinalSaplingRoot at
the witness height. root() walks the whole depth-32 path, about
1.7-2.4 ms per note, serially and with cs_main and cs_wallet held:
about 14 s for 8,200 notes on regtest, 28-39 s for a 16k-note wallet.
With the witnesses now saved at shutdown this pass no longer hides
behind the rescan; it holds the first block after start, and every RPC
waiting on those locks, for that long, and a stop sent meanwhile waited
for all of it.
Compute those roots first, the way BuildWitnessCache's Phase 2 spreads
the extension: under the existing locks collect the notes the loop will
call root() for (confirmed tx, full viewing key, nullifier, witnesses,
witnessHeight > 0, not yet validated, block at witnessHeight on the
active chain), compute their roots on -witnessbuildthreads threads (one
per core by default; inline below 8 notes, or for any shard whose
thread cannot start), then run the existing loop unchanged, taking each
root from that table. The loop changes a note's witnesses only at that
note's own turn (a sibling's reseed rewrites nullifiers, never
witnesses), so every root is the root of the witness being checked and
the validated/reseeded decisions, their order and nMinimumHeight are
those of the serial code. A note the selection misses, or whose root()
threw on a worker, gets its root computed inline as before, so a throw
surfaces at the same note. The root-equality check and the reseed on a
mismatch are untouched.
Between the two phases nothing has been changed yet, so a stop
requested while the roots are computed ends the pass there; the next
block or the next start redoes it.
The thread-count and thread-start-with-fallback code is shared with
Phase 2 (WitnessThreadCount, RunWitnessShards), with the same results.
On regtest (U.base, 24 threads): 2,063 roots in 920 ms against 3.2-4.2 s
for the serial pass. The new gtests run the same synthetic wallet with
one thread and with several and compare every note's resulting state,
including a root mismatch whose reseed throws mid-pass.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The consolidation op now plans its round with PlanSaplingConsolidation:
only addresses holding more than -consolidationthreshold eligible notes
(GetFilteredNotes at depth 11, as before), up to -consolidationmaxtxs
transactions per address, each spending up to -consolidationbatchsize
of the address's smallest notes back to it, with GetRand rather than
rand() varying the input count. Each transaction is shaped as before:
N spends, one real output to the same address, 7 Sietch dummy outputs,
expiry at tip + AUTO_OP_EXPIRY_DELTA, and the fee unless the notes are
worth no more than it (then none, as sweep does).
Two fixes ride on the rewrite:
- The op locked every eligible note in the wallet, and only after
proving, so a send made during a round saw no funds at all, while
one made during the proving could pick the very notes being spent.
It now locks exactly the notes it plans to spend, at planning time
under the wallet lock, and unlocks them on every exit (main()).
- One note with a missing or desynced witness ("Missing Witnesses!
Stopping.") failed the whole round, every round. It is now dropped,
logged once with its txid:index, and the round re-planned without it.
Per address, the witnesses come from one GetSaplingNoteWitnesses
call, so all of an address's spends share its majority anchor.
The scheduler snapshots the policy into the op when it enqueues it,
and skips a round (one interval) while the wallet is locked, as
autoshield does, instead of enqueueing one that can sign nothing.
Options: -consolidationthreshold (25), -consolidationbatchsize (15,
clamped to 2..50 and the tx size) and -consolidationmaxtxs (3, 1..100)
are new. -consolidationinterval below 5 is now clamped to 5 with a
warning instead of silently reset to 25; -consolidationtxfee is range
checked like -autoshieldfee ([1000, 10000000], else the default). The
policy is parsed even with -consolidation off, for z_consolidate.
-consolidatesaplingaddress must now be a Sapling address the wallet
holds the spending key of (startup error otherwise), except the zsweep
address -zsweep substitutes, which may be external as before. It is
resolved once at startup instead of on every round.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
FlushStateToDisk writes the wallet's SetBestChain at most once an hour,
the shutdown flush included, and its timer starts at "now" on the first
call. A session shorter than an hour therefore never saves: the next
start rescans every block of the session ("Rescanning last N blocks"),
re-extends every note witness across it, and then rewrites the whole
wallet inside init before RPC answers. Measured on regtest with a
throwaway prototype: restarts of 8.3 s -> 2.0 s (150 empty blocks),
29 s -> 2.5 s (150 blocks, 639 commitments), 66 s -> 8.5 s (8,215 notes,
631 MB wallet). The cost moves to the stop, at about 41 MB/s of
wallet.dat.
Add CWallet::PersistStateAtShutdown(), called from Shutdown() inside
the existing cs_main block right after the chainstate flush and before
the coins view and the wallet are torn down. It calls
SetBestChain(chainActive.GetLocator()), which on this tree stamps
pindexWalletTip, the block the wallet's state reflects, in the same
atomic transaction as the witnesses. It logs "Saving wallet state ..."
first, so a GUI can show that the stop is busy, and then the height,
the txs written, the elapsed ms and whether it committed. It skips the
write, and logs why, when:
- AppInit2 did not run to the end (new fInitCompleted): threads were
interrupted but not joined, and with no wallet tip SetBestChain would
stamp the chain tip over an interrupted rescan's checkpoint;
- the shutdown came from the wallet failing on a block
(NotifyWalletsOrShutdown now sets fWalletNotifyFailed), or the BDB
environment has panicked or a checkpoint/lsn_reset failed (new
CDBEnv::IsHealthy()): a full-wallet write into that database fails
or deepens the damage, and the logs are what recovery needs;
- nothing changed since the last committed save. SetBestChain now
returns SetBestChainINTERNAL's result (the CValidationInterface hook
returns bool) and, when it committed, records the block it stamped
and a generation counter that BuildWitnessCache (when it extended),
DecrementNoteWitnesses, VerifyAndSetInitialWitness reseeds,
ClearNoteWitnessCache and AddToWallet (a note-bearing tx inserted or
changed) bump. Init records the same when it finds the locator at
the tip and does not rescan. This also stops a second full write
when the hourly SetBestChain happens to fire in the shutdown flush.
FlushStateToDisk and DATABASE_WRITE_INTERVAL are unchanged: dropping
the throttle for FLUSH_STATE_ALWAYS would also rewrite the whole wallet
on every gettxoutsetinfo and on the init flush after a replay.
witnessRootValidated stays in memory only, so every witness is still
root-checked against hashFinalSaplingRoot on the next start, and a kill
during the write rolls back to the previous save (DB_RECOVER).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sapling consolidation picks notes in wallet order, a random 1..8 of them
per address with rand(), and merges every address with three or more
notes, every round. A miner whose wallet autoshield fills with one note
per round wants the opposite: leave tidy addresses alone, merge the
small notes of the crowded ones in bounded batches, and never re-merge
the big note an earlier round produced.
Add that policy as a pure function the op can use and the tests can
drive: PlanSaplingConsolidation() takes each address's eligible note
values and returns the round's batches. Only an address with MORE than
the threshold of notes (default 25) is consolidated; its notes are taken
smallest first, up to maxtxs transactions (default 3) of a per-tx input
count drawn from [max(2, ceil(2*batch/3)), batch] (default batch 15,
clamped to 2..50 and to what fits in MAX_TX_SIZE_AFTER_SAPLING next to
the 1 + 7 Sietch outputs). A transaction never takes an address's last
note, so the address stays spendable while the round confirms, and
batches never mix addresses. The randomness is the caller's (the op
will pass GetRand).
The option defaults live with the other auto-op defaults in wallet.h.
Nothing calls the planner yet.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
zsWalletTxJSON (z_listsentbyaddress, z_listreceivedaddress, getalldata)
runs once per wallet tx under LOCK2(cs_main, cs_wallet). For every
shielded output it copied the wallet's address set, and for each address
fetched the spending key, re-derived its full viewing key (an
elliptic-curve operation), and trial-decrypted the output; the sends side
did the same with the ovk. Every received or sent note in a tx with
spends walked the whole wallet in GetNullifiersForAddresses for the
change check. The spends side decrypted every spent note again and
deep-copied its SaplingNoteData (witnesses included). The GUI runs
z_listsentbyaddress over the whole wallet on every launch.
SaplingHistoryKeys, built once per RPC call, holds each address with a
usable spending key (in GetSaplingPaymentAddresses order, with its ivk
and ovk as the spending key gives them, and its ivk as
GetSaplingIncomingViewingKey gives it). It also gives the change check
as a lookup into the wallet's (ivk, nullifier) pairs, collected on first
use. The helpers keep their exact structure and quirks. Each output's
JSON object and change flag still accumulate across the addresses that
decrypt it. Diversified addresses sharing a key still produce one entry
each. An unknown address still checks change under a zero ivk. A locked
wallet still reports no shielded received or sent entries. Only the
repeated work is gone:
- each output is decrypted at most once per distinct key. Once it is
known which ivk decrypts an output, no other ivk is tried: the cached
plaintext, or a decryption under the ivk the wallet's note data
records. Two canonical ivks can't both pass the note commitment check,
which pins pk_d = [ivk]g_d;
- outCiphertexts are decrypted once per distinct ovk; the t->z shielding
ovk is derived from the seed once per tx;
- spends use the cached plaintext of the spent note.
Two deliberate behaviour changes. The spends helper looked notes up with
operator[]: it inserted a null-outpoint entry into
mapSaplingNullifiersToNotes for every other wallet's nullifier it met.
After getalldata or z_listsentbyaddress had run, z_viewtransaction of
any tx spending someone else's note (every incoming z->z payment) failed
with map::at. And with an inconsistent nullifier map, it inserted an
empty note into a wallet tx. The helpers now only read the wallet. Also,
if the walletpassphrase timer relocks the wallet during the call, the
whole call reports the keys as of its start; the old per-output lookups
switched over partway.
test_wallet_history.cpp holds 69bb035e7's helpers verbatim (renamed)
and a wallet exercising every branch:
- default and diversified addresses, a viewing-key-only address, and a
key imported after its note arrived;
- z->z sends with change, and with text, empty and binary memos;
- a send nobody's ovk reads, and a t->z shielding send;
- our spends, someone else's, and a mixed tx.
Every tx x every return type x nine address filters gives byte-identical
JSON: with the plaintext cache warm, cold, and on an encrypted wallet
both locked and unlocked. Mutation-checked: dropping the ivk check from
the uniqueness shortcut fails the test. DoesNotModifyTheWallet pins the
read-only change (and shows that the old helpers did insert the foreign
nullifier).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
getalldata, z_listreceivedaddress and z_listsentbyaddress build a
map<int64_t, CWalletTx> of the whole wallet, keyed by nOrderPos, before
any filter runs. Every insert deep-copies the CWalletTx, including each
note's witness list (~100KB per note on a mainnet wallet). That is
gigabytes of allocation per call on a large wallet, under
LOCK2(cs_main, cs_wallet). The GUI's history scan runs
z_listsentbyaddress on every launch and about once per new tip.
The map now holds const CWalletTx* into mapWallet. It is still a
std::map, so the first tx inserted for an nOrderPos wins, exactly as
before. mapWallet can't change while the RPC holds cs_wallet, so the
pointers stay valid. Output is unchanged for a consistent wallet. One
corner case differs: with a nullifier map entry pointing at a note
its tx lacks, the spends helper's operator[] inserts an empty note into
that tx, and a later iteration now sees it where the old copies didn't.
The next commit removes that insertion.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- UpdatedNoteData now keeps the incoming plaintext when it keeps the
wallet's own entries. When it returns "unchanged" (equal note data,
or SaplingNoteDataIdentical), any entry lacking a plaintext takes the
incoming one, for the same outpoint and ivk only. The startup rescan
replays loaded txs with FindMySaplingNotes' freshly decrypted data;
that plaintext was thrown away, so the warm-up decrypted those notes a
second time. The cache is outside every comparison, so the function
still returns false and nothing is rewritten.
- -checknotecache is read once at init into fCheckNoteCache, instead of
a mapArgs lookup on every GetFilteredNotes call. Its help text and
comment now say what it checks: every note the walk considers, before
the address filter, so a corrupt cached address can't drop a note
unchecked.
- GetFilteredNotes pre-sizes its result only when there's no address
filter, so a one-address call no longer reserves room for the whole
wallet.
- WarmSaplingNoteCache returns its counts (notes, filled, no such
output, undecryptable), and FillSaplingNoteCache records the threads
it used, so tests can tell the cases apart.
- WarmSaplingNoteCache's comment no longer claims nothing can wait on
cs_wallet while it runs: the RPCs allowed during warmup can.
Tests:
- ReplayWithPlaintextIsNoUpdate pins the rule that the plaintext cache
stays out of the "did this tx change?" decision. A rescan replays a
witnessed note loaded without plaintext, using FindMySaplingNotes'
data that carries one. That must be no update: no rewrite, and the
witness and nullifier are kept. The stored entry then gains the
plaintext. Checked by mutation: with cache presence added to
SaplingNoteDataIdentical, this test fails and every other test still
passes.
- ParallelFillMatchesSerial uses 460 notes and asserts the thread count.
So the 7-thread case really runs 7 threads, with uneven shards
(460 % 7 != 0). Before, it was capped at 4 and repeated the 4-thread
case.
- ColdParallelFillMatchesLegacy: a cold GetFilteredNotes over ~270
candidates fills on 4 threads and matches the 69bb035e7 loop entry
for entry.
- WarmUpSkipsBadNotes asserts the warm-up's separate counts (1 no such
output, 2 undecryptable), so removing the out-of-range guard is now
caught.
- CachedPlaintextMatchesFreshDecrypt checks exact counts.
CheckNoteCacheRepairsADifference also tampers with a memo, and looks
entries up by outpoint. The meaningless GetHash check is dropped.
- A ScopedArg / ScopedCheckNoteCache RAII helper restores -args and
fCheckNoteCache even when an assertion returns early.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
With -checknotecache=1 (debug help), GetFilteredNotes decrypts every
note it returns again. If the cached plaintext differs from the fresh
decryption, it logs the note and replaces the cache entry with the
fresh value. It costs the full decryption the cache exists to avoid, so
it is off by default; it is there for validating the cache on a real
wallet, or for diagnosing a suspected cache problem in the field.
CheckNoteCacheRepairsADifference: by default a tampered cache entry is
returned as is (the cache is trusted); with the option it is repaired
and the fresh value is returned.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The startup warm-up, or a lazy fill after -notecachewarmup=0, decrypts
the whole wallet: ~0.5ms per note, ~6s serial for 12k notes. Each
decryption is independent: it reads its own output and writes only its
own note's cachedPlaintext. So FillSaplingNoteCache now splits batches
of 128 or more notes round-robin across -witnessbuildthreads (default:
hardware_concurrency) workers, at least 64 notes per thread. It follows
BuildWitnessCache's Phase 2 pattern:
- the caller keeps cs_wallet held throughout;
- workers take no lock and assert none; under DEBUG_LOCKORDER a fresh
thread has no lock stack;
- per-shard fill counters are summed after join;
- nothing escapes a worker: a throwing decryption leaves that note
unfilled, like one that doesn't decrypt;
- if the OS refuses a thread, the remaining shards run inline.
librustzcash is already called concurrently by BuildWitnessCache's
workers, and libsodium is thread-safe after sodium_init.
ParallelFillMatchesSerial: 300 notes across two keys and diversified
addresses decrypt to exactly the same cache with 1, 4 and 7 threads.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The plaintext cache is in memory only, so a restart empties it. Without
a warm-up, the first balance call after a restart decrypts the whole
wallet under LOCK2(cs_main, cs_wallet): ~6s for a 12k-note wallet. That
is the observed failure: restart, the GUI connects, and the node looks
stuck.
CWallet::WarmSaplingNoteCache decrypts every note whose plaintext isn't
cached, spent ones included, because z_listreceivedbyaddress
(ignoreSpent=false) is called once per address by the GUI's history
scan.
init runs it at the end of the wallet block, just before
SetBroadcastTransactions. At that point RPC is still in warmup (it
shows "Decrypting wallet notes...") and the wallet notification
thread, whose startup witness rebuild can hold cs_wallet for a long
time, has not started yet. It takes cs_wallet only. -notecachewarmup=0
(debug help) skips it, which leaves the lazy fill in GetFilteredNotes
to do the work.
Unlike GetFilteredNotes, the warm-up never asserts. A note that doesn't
decrypt under its ivk, or names an output its tx lacks, is counted in
the summary line and listed under -debug=zrpcunsafe. A corrupt note
therefore can't stop the node from starting, or from serving the
key-export RPCs allowed during warmup; GetFilteredNotes still asserts
on it, as before.
Tests:
- WarmUpFillsEveryNote: spent, locked, unconfirmed and stale-block
notes included; walks afterwards decrypt nothing.
- WarmUpSkipsBadNotes: undecryptable and out-of-range notes are skipped
without aborting.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
GetFilteredNotes, the walk behind every balance and note-listing RPC,
sweep, consolidation, z_sendmany and z_mergetoaddress, decrypted every
note it looked at on every call: ~0.5ms of Jubjub arithmetic per note,
under LOCK2(cs_main, cs_wallet). A note's plaintext is fixed by its
output (the txid commits to the ciphertext) and the ivk that decrypts
it, so it never needs to be decrypted twice.
SaplingNoteData gains an in-memory-only
boost::optional<SaplingNoteCache> {note, memo}; the address is the
note's (d, pk_d). It follows the witnessRootValidated precedent:
- never serialized, and left out of operator== and
SaplingNoteDataIdentical, so filling it never makes a tx look changed
and get rewritten (the replay rewrite storm 69bb035e7 removed);
- FindMySaplingNotes fills it from the decryption that found the note
(both the spending-key and the viewing-key-only loop);
- UpdatedNoteData's replace branch keeps a plaintext the wallet already
had, for the same outpoint and ivk only;
- GetFilteredNotes now runs in two passes: pass 1 applies the tx,
spent and locked filters and collects the notes that pass; whatever
lacks a plaintext (everything after a restart, until the startup
warm-up in a later commit) is decrypted once via the new
FillSaplingNoteCache; pass 2 applies the address and spending-key
filters and emits entries in the same order as before.
Spentness, spendability, lock state and depth are still decided on every
call; only the plaintext is cached.
The A0 equivalence test passes unchanged (warm). New tests:
- ColdCacheMatchesLegacy: the same grid with the cache dropped before
every call;
- CachedPlaintextMatchesFreshDecrypt: eager and lazy fills;
- WarmPassDoesNotDecrypt: a fill counter shows a warm walk decrypts
nothing, and spent or locked notes only when the caller asks for
them;
- CacheNeverSerialized: byte-identical SER_DISK/NETWORK/GETHASH output,
empty after a load;
- UpdatedNoteDataAndTheCache: no rewrite on a cache-only difference,
carried on replace, never across another ivk;
- SpendabilityNotCached;
- FindMySaplingNotesFillsCache.
Memory: ~616 bytes per note (the memo is 512), ~8MB for a 13k-note
wallet, next to ~100KB per note of cached witnesses.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
SaplingNotePlaintext::decrypt(ciphertext, ivk, epk, cmu) derives
pk_d = [ivk]g_d to check the note commitment, then throws it away. The
wallet then calls ivk.address(d), which derives pk_d again, and
plaintext.note(ivk), which derives it a third time. Each derivation is a
Jubjub scalar multiplication, ~115us, measured. Including the key
agreement and the commitment check, the whole sequence is ~775us per
note.
decrypt_with_note() runs the same decryption and checks and returns the
note built from that pk_d. ivk_to_pkd succeeding already implies a
valid diversifier, which is all ivk.address() checks on top. It gets its
own name rather than a decrypt() overload: an overload taking a fifth
argument by non-const reference would capture calls meant for the
(epk, esk, pk_d, cmu) variant. The cmu check stays.
GetFilteredNotes and FindMySaplingNotes' spending-key loop use it. That
saves two of the three derivations per note in every balance walk, and
one per found note during scans and rescans (trial decryption of
outputs that aren't ours still fails at the AEAD, as before).
FindMySaplingNotes also no longer copies each OutputDescription.
New tests: MatchesDecryptThenNote checks decrypt_with_note field for
field against decrypt() + note(ivk), over default and diversified
addresses, a wrong ivk and a wrong cmu. FindMySaplingNotes pins what
discovery returns: notes per key, diversified addresses to register,
foreign outputs ignored. Both pass before and after the switch.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review follow-ups to the GetFilteredNotes / RPC timing logs:
- Time with std::chrono::steady_clock instead of GetTimeMicros(), which
is the system clock. A wall-clock step otherwise writes false
">= 500ms" lines unconditionally; on a WSL2 host the clock was seen
stepping +3.6s every ~32s.
- A long-poll getblocktemplate deliberately blocks (with cs_main
released) until a new block arrives, so it is logged only under
-debug=bench.
- Log the method as "RPC method=<name> took <n>ms". A bare " rescan "
token followed by "<n>ms" matches ObsidianDragon's rescan-finished
log heuristic.
- The always-on slow-walk line keeps just the filters and the walk
time; the wallet-size counts (txs, notes, spent, entries) are logged
only with -debug=bench, so a shared debug.log doesn't carry them.
- The -txindex=0 startup line names the version.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
CCryptoKeyStore::HaveSaplingSpendingKey and GetSaplingSpendingKey scan
mapCryptedSaplingSpendingKeys with `for (auto entry : ...)`. That copies
each entry (an extended full viewing key plus its encrypted-secret
vector) for every key visited, on every call. GetFilteredNotes'
requireSpendingKey check makes one such call per note, and the history
RPCs make one per output per address: ~22ns per key per call, measured
(11us per note on a 1024-key wallet). Iterate by const reference.
The equivalence test gains a locked, encrypted-keystore variant,
LockedWalletMatchesLegacy, so spendability coming from the encrypted
map is covered too.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>