32228 Commits
Author SHA1 Message Date
DanS 25b29d293e Merge branch 'dev' v1.3.1 2026-11-08 11:22:26 -06:00
DanS df17fd4b1a Merge branch 'fix/witness-shutdown-save' into dev
# Conflicts:
#	src/Makefile.gtest.include
2026-10-31 11:59:04 -05:00
DanS a1f09558e5 Merge branch 'feat/consolidation-policy' into dev 2026-10-31 11:58:36 -05:00
DanS 16db6cc7a0 Merge branch 'fix/notarizations-lock' into dev 2026-10-31 11:58:36 -05:00
DanS 78f19c1617 Merge branch 'fix/daemon-report2' into dev 2026-10-31 11:58:36 -05:00
DanS 92a18df998 Merge branch 'fix/reorg-shutdown-dos' into dev 2026-10-31 11:58:35 -05:00
DanSandClaude Opus 4.8 10217af8e4 consensus: height/time-gated removal of the CRYPTO555/notary t-vout exemption (F16)
On the fully-private chain (ac_private=1) all transparent outputs are banned except coinbase,
but hush_isnotaryvout() exempts CRYPTO555 and dPoW notary addresses -- so a public transparent
UTXO to those addresses is accepted on a chain users treat as fully shielded. Drop that
exemption so such vouts are rejected like any other taddr.

Dropping a previously-accepted output is a consensus change that could fork the live chain, so
it is activated by block time (DRAGONX_NOTARYVOUT_BAN_TIME, same mechanism as
HUSH_SAPING_ACTIVATION). It ships DEFAULT-OFF via the 0xFFFFFFFF sentinel (year 2106), so
merging is a verified no-op; the operator sets a real future timestamp once (a) the upgrade
window has passed and (b) they have confirmed no active dPoW notarization posts transparent
notary vouts on-chain -- otherwise activation would reject notarization txs and halt/fork.

Adversarially reviewed as SOUND (default-off, safe to merge): tiptime is deterministic at the
authoritative connect paths (prev->nTime), the sentinel is byte-identical to prior behavior,
and coinbase + ac_burn paths are preserved. Reviewer note: a height-based gate would be
marginally cleaner than time if ever made live.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-30 22:28:32 -05:00
DanSandClaude Opus 4.8 1c29fe86ff net: cap per-peer header flooding in and after IBD, by side-branch growth (F14)
AcceptBlockHeader runs CheckBlockHeader with fCheckPOW=0 (no RandomX/PoW check), so a peer can
cheaply mint valid-looking sibling headers of the tip, each stored as a permanent mapBlockIndex
entry. The existing per-peer cap ran only during IBD, leaving post-IBD growth unbounded -> a
memory-exhaustion DoS from one connected peer.

Two complementary per-peer caps, applied in and after IBD:
 (1) a TIGHT cap (2000) on newly-stored SIDE-BRANCH headers -- headers added to mapBlockIndex that
     did not become the best-known header. That is the actual growth vector; honest headers-first
     sync and new-block announcements are best-extending and never increment it, and duplicates
     (which do not grow mapBlockIndex) are excluded, so the cap can be small with no honest-peer
     risk. A sibling flood trips it after ~2000 entries instead of millions.
 (2) the prior loose cumulative cap (2*validated-height + 200000) as a backstop against a long
     FORWARD chain of correct-nBits headers (which do extend the best chain, so (1) never sees them).

Adversarial review drove the tightening: the earlier IBD-gate-removal-only version bounded memory
only at ~6.8M entries/peer. Counting just newly-stored non-best headers bounds it to a few thousand.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-30 22:28:06 -05:00
DanSandClaude Opus 4.8 661678dd84 miner: hold cs_main across TestBlockValidity in the RandomX solver (F15)
The RandomX miner's solution check called TestBlockValidity(..., chainActive.LastTip(), ...)
with cs_main NOT held (the LOCK was commented out). TestBlockValidity asserts
pindexPrev == chainActive.Tip(), so a tip change (a peer block or a reorg) between the
LastTip() read and the assert aborts the node. The lock had been removed only to avoid a
~256MB RandomX re-validation allocation; SetSkipRandomXValidation(true) already skips that
re-validation here, so re-acquiring cs_main across the (now cheap) call is safe and closes
the race. Adversarially reviewed: no lock-order cycle (datasetMtx(shared)->cs_main only),
ProcessBlockFound stays outside the scope with its own staleness recheck.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-30 22:27:41 -05:00
DanSandClaude Opus 4.8 ae7e085144 gtest: regression guard for the hush_checkPOW height-0 RandomX re-check
A forged-RandomX block reaches hush_checkPOW(0,pblock,0) over the P2P accept
path; the first CheckRandomXSolution runs at height 0 (skipped), the height is
recovered from hashPrevBlock, and fix (a) re-runs CheckRandomXSolution at the
real height. The test drives the same forged block through hush_checkPOW twice:
with the parent unknown the height stays 0 and the block is not rejected here
(the pre-fix outcome), and with the parent known at height 9 the recovered
height makes the fix reject it. The A/B contrast fails if the re-check is
reverted. Also asserts CheckRandomXSolution is skipped at height 0 and rejects
the forgery at the real height.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-29 01:25:37 -05:00
DanSandClaude Opus 4.8 da7acda6d8 main: refuse an oversized reorg instead of shutting the node down
ActivateBestChainStep's MAX_REORG_LENGTH guard called StartShutdown() when a
peer-delivered fork would roll back more than -maxreorg (default 99) blocks.
That is a per-reachability remote DoS: the victim re-pulls the attacker's fork
from addrman after every restart and re-kills itself as long as the attacker
is reachable (reproduced on an isolated regtest net; the node exited 2-4s
after pulling a 135-block fork, and again on restart while the attacker was up).

Refuse the fork and keep running instead, mirroring the past-notarized-height
branch just above (InvalidateBlock + DoS(100)). Invalidate the base of the
attacker branch (the block at forkHeight+1), not just its tip, so
FindMostWorkChain's fFailedChain sweep removes the whole branch from the
candidate set in one pass and AcceptBlockHeader rejects any future extension
(pprev becomes BLOCK_FAILED_CHILD) -- the fork is never re-selected or
re-pulled. The base is strictly on the fork side, so no honest block is
disconnected. DoS(100) penalizes the peer; under the default banscore (101) the
ban lands on the second such trip, but the durable protection is the chainstate
poisoning, not the ban. cs_main is already held.

Because the refusal is persisted (BLOCK_FAILED on the base), raising -maxreorg
alone does not make the node follow this fork after a trip: recovery for a
genuine deep reorg is an explicit `reconsiderblock <base>` (the log prints the
hash), optionally with a raised -maxreorg so it is not re-refused. The refusal
is also published via strMiscWarning so it shows in getinfo/getnetworkinfo
rather than leaving a refused node silently stranded. Reorgs within the limit
and the notarized-height branch are unchanged; the startup-only RewindBlockIndex
guard is left as-is.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-28 17:32:08 -05:00
DanSandClaude Opus 4.8 6b67fc0e8e hush_checkPOW: verify RandomX at the recovered height on the peer-accept path
A block arriving over P2P reaches ProcessNewBlock(0,0,...) (the net BLOCK
handler), and both CheckBlock() calls on that accept path -- in
ProcessNewBlock and in AcceptBlock -- pass fCheckPOW=0, so CheckBlockHeader's
RandomX check never runs there. The only real-height PoW gate before the
block becomes a setBlockIndexCandidate is hush_checkPOW(0,pblock,height), and
for a peer block height is 0: CheckRandomXSolution ran at height 0 (where
RandomXValidationRequired is false, so it is skipped), the real height was
then recovered from hashPrevBlock, but RandomX was never re-checked.

So a block with a forged RandomX solution (only a grindable SHA256 target)
could become a candidate with its RandomX never verified at its real height,
and trip the MAX_REORG_LENGTH reorg guard before the connect-time check would
reject it -- the cheap half of the reorg-shutdown DoS.

Re-run CheckRandomXSolution at the recovered height before returning. It is a
no-op wherever the first call was (algo gate, activation height -- regtest is
far below it -- HUSH_LOADINGBLOCKS during IBD/reindex, the last in-index
checkpoint, and the thread-local miner self-check skip), so it only adds one
light-mode verification on the height==0 peer-accept path, which previously
did no real-height RandomX work at all.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-28 17:05:03 -05:00
DanSandClaude Opus 5.5 c0b99a0e1f 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 <noreply@anthropic.com>
2026-10-28 13:10:41 -05:00
DanSandClaude Opus 5.5 5d5b47d05a wallet/rpc: z_consolidate is not safe-mode; say which units it uses
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>
2026-10-28 12:59:46 -05:00
DanSandClaude Opus 5.5 25c79b7512 wallet: keep consolidation to the sweep address, warn on bad config off
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>
2026-10-28 12:57:58 -05:00
DanSandClaude Opus 5.5 27a2f04189 wallet: spend consolidation notes only at a chain anchor
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>
2026-10-28 12:54:55 -05:00
DanSandClaude Opus 5.5 6d7ffeb2b9 wallet: end a consolidation round early on shutdown or a queued op
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>
2026-10-28 12:48:44 -05:00
DanSandClaude Opus 5.5 fef79e7b12 wallet: skip fully validated txs before the depth lookup in the root selection
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>
2026-10-28 12:40:42 -05:00
DanSandClaude Opus 5.5 9bd2fd2b92 wallet: add -walletsaveatshutdown to turn the shutdown save off
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>
2026-10-28 12:39:25 -05:00
DanSandClaude Opus 5.5 6413b8da4e wallet: skip the shutdown save when the chainstate flush failed
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>
2026-10-28 12:37:36 -05:00
DanSandClaude Opus 5.5 0b822cc6b2 wallet: keep a failed open of the wallet database inside the shutdown save
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>
2026-10-28 12:32:54 -05:00
DanSandClaude Opus 5.5 ced37555c4 init: recreate a data-less notarizations DB in place, not aside
Every unreadable notarizations DB was moved aside under a new
timestamped notarizations.corrupt-* name. For a failure that persists
across starts rather than real corruption (disk full: DB::Open creates
the directory and LOCK, then fails), each start moved another empty
directory aside, and the copies piled up without limit.

When the directory holds no data, i.e. no non-empty .ldb/.sst table or
.log write-ahead log, there is nothing to keep: recreate the DB in place
instead (falling back to an in-memory DB as before if that fails). A
directory that cannot be listed counts as holding data, and any DB with
records is still moved aside, never deleted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 12:32:01 -05:00
DanSandClaude Opus 5.5 ed13277dcb wallet: do not save over the locator of a rescan that did not complete
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>
2026-10-28 12:27:43 -05:00
DanSandClaude Opus 5.5 2bc4a70eb8 init: bound the notarizations LOCK wait by wall-clock time
The wait for another process to release notarizations/LOCK counted 1 s
sleeps, so the time spent probing and a loaded machine stretched the
"up to 30 s" to 33-34 s. Wait against a GetTimeMillis() deadline instead,
and report the measured elapsed time in the "released after" and "still
could not be taken after" lines.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 12:21:55 -05:00
DanSandClaude Opus 5.5 8f70f494b3 init: do not call the notarizations DB corrupt on one post-failure probe
OpenNotarizationDB() decided between "LOCK held" and "corrupt" with a
lock probe taken after DB::Open had already failed. If the holder (an
older dragonxd finishing its exit, the very upgrade-restart case the
lock-aware fallback exists for) released notarizations/LOCK between the
failed open and the probe, the probe found the lock free and a healthy
DB was moved aside and replaced by an empty one. CDBWrapper throws a
generic "Database I/O error", so the error text cannot tell the two
cases apart either.

Only treat the DB as unreadable when an open fails although the probe
just before that open found the lock free: on a free probe, open once
more, and move aside only if that attempt fails too. A held probe still
gets the single bounded wait and then the in-memory fallback.

The probe now returns the leveldb::Status of its LockFile call, and the
log reports it ("Resource temporarily unavailable" versus, say,
"Permission denied") instead of the generic open error alone, worded as
"could not be taken" since a non-ok probe is not always another holder.
Any non-ok probe still counts as held, so it never moves or wipes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 12:10:21 -05:00
DanSandClaude Opus 5.5 63e7d6ef2d wallet: keep a throwing consolidation round's committed txs in its record
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>
2026-10-28 11:36:59 -05:00
DanSandClaude Opus 5.5 7983a3dc68 doc: describe consolidation as it now works; fix zsweep doc errors
Rewrite the consolidation part of doc/zsweep-consolidation.md to match
the code: off by default (also for GUI wallets, which the doc claimed
were on), what an eligible note is, the threshold/batch/maxtxs policy
and its defaults including -consolidationinterval, smallest-first and
the randomised input count, the 8-output shape, locking only the
round's notes, skipped bad-witness notes, the fee range (fee 0 is no
longer accepted), the spending-key requirement, z_consolidationstatus
(the doc named z_sweepstatus) and its verbose mode, z_consolidate, and
the off-but-suggested hint.

Also fix -zsweepinterval: it defaults to 10 (values below 5 fall back to
10), not the 5 the doc and -help claimed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 11:22:58 -05:00
DanSandClaude Opus 5.5 ead3394188 wallet: suggest consolidation when it is off and notes pile up
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>
2026-10-28 11:21:06 -05:00
DanSandClaude Opus 5.5 52b747f6d3 wallet/rpc: add z_consolidate, one consolidation round on demand
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>
2026-10-28 11:09:20 -05:00
DanSandClaude Opus 5.5 e5791fea71 wallet/rpc: make z_consolidationstatus report what consolidation does
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>
2026-10-28 10:49:38 -05:00
DanSandClaude Opus 5.5 b4513498e5 wallet: say what the startup witness check did
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>
2026-10-28 10:48:35 -05:00
DanSandClaude Opus 5.5 bc3867a312 wallet: compute the witness roots of the startup check on worker threads
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>
2026-10-28 10:44:55 -05:00
DanSandClaude Opus 5.5 4d7de7a0eb init: do not leave chain DB pointers dangling in the block-index load loop
The load loop deleted pcoinsTip, pcoinsdbview, pcoinscatcher and
pblocktree before reopening them without resetting the pointers. If a
reopen throws (e.g. a corrupt or unopenable blocks/index), the outer
handler reports "Error opening block database", AppInit2() returns false
and Shutdown() then calls FlushStateToDisk() on, and deletes, the
already freed objects: a use-after-free and double delete on the exit
path. Null each pointer right after its delete, as the previous commit
already did for pnotarizations.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 10:44:43 -05:00
DanSandClaude Opus 5.5 a7adcbc954 init: make the notarizations DB open fallback lock-aware
Any failure to open the notarizations DB used to be treated as
corruption: the previous notarizations.corrupt was remove_all()ed, the
live directory renamed over it and a fresh DB created. The common
failure is not corruption at all but "IO error: lock .../LOCK: Resource
temporarily unavailable" from a previous dragonxd that has not finished
exiting, and the fallback then destroyed both the live DB and the last
saved copy. A filesystem exception from remove_all()/rename() also
escaped into the outer handler and failed startup with a spurious
"Error opening block database".

Move the logic into OpenNotarizationDB():

 - if notarizations/LOCK is held (probed with leveldb's own
   Env::LockFile, i.e. the lock DB::Open takes), log once that we are
   waiting for a previous dragonxd, wait up to 30 s in 1 s steps
   (abandoned on a shutdown request) and retry; if it is still held,
   run this session on an in-memory notarizations DB and leave the
   on-disk one untouched;
 - only a DB that fails to open with the lock free is moved aside, now
   to a timestamped notarizations.corrupt-YYYYmmdd-HHMMSS name, so an
   earlier copy is never deleted;
 - a failed move-aside or recreate falls back to an in-memory DB
   instead of throwing: the DB is non-essential and regenerable and
   must never fail startup.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 10:42:30 -05:00
DanSandClaude Opus 5.5 a800a266e5 wallet: consolidate with the threshold/batch policy, lock only its notes
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>
2026-10-28 10:37:33 -05:00
DanSandClaude Opus 5.5 693f81bbba wallet: save witnesses and the best block at a clean shutdown
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>
2026-10-28 10:36:23 -05:00
DanSandClaude Opus 5.5 cbd5f8dce4 init: do not rename the main thread in Shutdown()
Shutdown() called RenameThread("hush-shutoff") on the main thread. On
Linux that sets /proc/<pid>/comm, i.e. the process name, so for the
whole shutdown (wallet flush, chainstate flush, LevelDB closes) the node
no longer matched 'pgrep -x dragonxd' / pidof while it still held the
datadir and LevelDB locks. pgrep-based restart scripts took that as
"exited" and relaunched it early; on regtest pgrep stopped matching
about 1 s after 'stop' in 10/10 runs while the old process was alive.

Keep the process name until exit. Worker threads keep their own names.
Nothing depends on "hush-shutoff": no hit in src/, qa/, contrib/ or
util/, and the ObsidianDragon GUI only works around the rename by also
checking the exe link.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 10:26:20 -05:00
DanSandClaude Opus 5.5 3859a8ce22 wallet: plan consolidation rounds with a threshold/batch policy
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>
2026-10-28 10:25:59 -05:00
DanSandClaude Opus 5.5 f09f5a7b95 init: close the notarizations DB in Shutdown()
Shutdown() deleted pcoinsTip, pcoinsdbview and pblocktree but never
pnotarizations, so notarizations/LOCK was the one LevelDB lock still held
after "Shutdown: done". It was only released when the process was torn
down, after the static datadir .lock had already been released. A
successor started in that window took .lock, blocks/index and chainstate
and then failed to open notarizations/LOCK (EAGAIN), which the open
fallback "fixed" by moving the live notarizations DB aside and wiping it.

Delete it under cs_main next to pblocktree, and null the pointer after
the delete in the block-index load loop so a throwing reopen can never
leave it dangling for Shutdown() to delete twice.

Every user of pnotarizations now treats NULL as an empty DB
(GetBlockNotarizations, GetBackNotarization, ScanNotarizationsDB,
ConnectNotarizations, DisconnectNotarizations; crosschain.cpp,
rpc/crosschain.cpp, hush_nSPV_fullnode.h and hush_dailysnapshot only
reach it through those), so a straggler after Shutdown() cannot
dereference it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 10:23:20 -05:00
DanS 09fa5c7b5f Merge branch 'dev' for the v1.3.1 release 2026-10-27 15:27:37 -05:00
DanSandClaude Opus 5.5 fe988d6fbe release: bump to v1.3.1
dev is 22 commits past the v1.3.0 tag and still stamped 1.3.0, so a
release built from it would be indistinguishable from v1.3.0 on the wire,
in getnetworkinfo and to the wallet's updater.

Bump REVISION, not MINOR: the delta is bug fixes and wallet performance.
It adds no subsystem, and the new RPC-visible options (-notecachewarmup,
-checknotecache) are debug-help only.

  configure.ac, src/clientversion.h  1.3.0 -> 1.3.1 (CLIENT_VERSION 1030150)
  doc/man/*.1                        version strings restamped
  contrib/debian/changelog           1.3.1 entry
  src/chain.h                        the CLIENT_VERSION comment

The man page content needs no regeneration: every option in
`dragonxd --help` at 3032eb786 is already in dragonxd.1, and the two new
options appear only in -help-debug.

No consensus change since v1.3.0, so PROTOCOL_VERSION and
MIN_PEER_PROTO_VERSION are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 15:27:25 -05:00
DanSandClaude Opus 5.5 3032eb7868 wallet/rpc: gather Sapling keys once per history RPC, not per output per address
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>
2026-10-17 08:16:09 -05:00
DanSandClaude Opus 5.5 7c3563cd5a wallet/rpc: order history RPC txs by pointer, not by deep copy
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>
2026-10-17 08:16:09 -05:00
DanSandClaude Opus 5.5 190023f85f wallet: note-cache review follow-ups
- 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>
2026-10-17 08:16:09 -05:00
DanSandClaude Opus 5.5 23877e1038 wallet: -checknotecache, a diagnostic for the note plaintext cache
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>
2026-10-17 08:16:09 -05:00
DanSandClaude Opus 5.5 43635b7fd7 wallet: decrypt big note-cache batches on worker threads
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>
2026-10-17 08:16:09 -05:00
DanSandClaude Opus 5.5 83a14a7bfb wallet/init: decrypt every wallet note into the plaintext cache at startup
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>
2026-10-17 08:16:09 -05:00
DanSandClaude Opus 5.5 b1e3c5230a wallet: cache each Sapling note's decrypted plaintext in memory
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>
2026-10-17 08:16:09 -05:00
DanSandClaude Opus 5.5 7ddd03d86d zcash/wallet: decrypt a Sapling note's plaintext and note in one pass
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>
2026-10-17 08:16:09 -05:00
DanSandClaude Opus 5.5 bfec5c74ae gtest: notecache review fixes
- Take LOCK2(cs_main, cs_wallet) before adding keys in SetUp: both
  AddSaplingZKey and AddSaplingIncomingViewingKey assert cs_wallet is
  held, which aborts a DEBUG_LOCKORDER build.
- TIP_HEIGHT becomes a namespace-scope constexpr. As a static class
  member it was ODR-used by EXPECT_EQ without a definition, which fails
  to link as C++11 at -O0.
- TearDown restores the previous chainActive tip and erases only the
  mapBlockIndex entries the fixture inserted.
- Add a tx mined only in a stale side block. The legacy tx_height model
  returns that block's height, as a txindex can, and the tx must still
  be excluded at every minDepth.
- The encrypted variant asserts HaveSaplingSpendingKey directly, and a
  new test unlocks the keystore and checks GetSaplingSpendingKey (the
  other loop the crypter change touched).
- The legacy-loop comment now says its two LogPrintf lines are dropped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 08:16:09 -05:00