Commit Graph
32236 Commits
Author SHA1 Message Date
DanSandClaude Opus 5.5 2ff5c5d541 asyncrpc: make AsyncRPCOperation::cancel() virtual, so a running auto-op can be stopped
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>
2026-11-20 19:05:53 -06:00
DanSandClaude Opus 5.5 b0e0d211d2 build: list libbitcoin_server again after libbitcoin_wallet when linking
libbitcoin_server and libbitcoin_wallet use each other: the server's init and RPC code calls into
the wallet, and the wallet's async operations derive from the server's AsyncRPCOperation. GNU ld
(Linux and mingw) scans each static archive once, in order, so dragonxd and hush-gtest only linked
because some server object happened to reference asyncrpcoperation.o directly and pull it in on the
first pass: AsyncRPCQueue called the non-virtual AsyncRPCOperation::cancel(). Making cancel()
virtual, as the next commit does, removes that reference, and dragonxd fails to link with undefined
AsyncRPCOperation members from libbitcoin_wallet.a.

List libbitcoin_server again after the wallet, spelled ./libbitcoin_server.a: libtool drops a
repeated archive and keeps only its last copy, which would put the server after the wallet and break
the other direction, and it compares the literal strings. LINK_GROUP_START/END cannot do it either:
libtool moves both flags ahead of all the archives, so the group is empty (that is true of the
existing mingw link group too). macOS's ld64 does not depend on archive order; a repeated archive is
at most a warning there.

test_bitcoin already lists the server twice but is not built (its include is commented out in
Makefile.am); if it is revived it needs the same spelling.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-20 19:04:51 -06:00
DanS 227cc7730b Merge branch 'fix/sweep-autoops-hardening' into dev 2026-11-20 16:45:35 -06:00
DanS 695050afe1 Merge branch 'fix/reject-unpayable-sapling-addr' into dev 2026-11-20 16:45:35 -06:00
DanSandClaude Opus 5.5 b61611d5c2 wallet: one unspendable note no longer stops the whole zsweep round
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>
2026-11-20 16:07:39 -06:00
DanSandClaude Opus 5.5 ca07b8299f wallet: keep an interrupted -zapwallettxes / -rescan from hiding the unscanned range
-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>
2026-11-18 11:08:57 -06:00
DanSandClaude Opus 5.5 eec0d86dbf wallet: make z_sweepstatus report what the sweep actually does
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>
2026-11-18 11:08:57 -06:00
DanSandClaude Opus 5.5 70dd6c6f8b wallet: stop zsweep reporting success on a locked wallet
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>
2026-11-18 11:08:57 -06:00
DanSandClaude Opus 5.5 2e78769817 wallet: let an in-flight zsweep round finish, and build each tx at the current tip
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>
2026-11-18 11:08:57 -06:00
DanSandClaude Opus 5.5 c59b445ac1 zaddr: reject Sapling addresses that cannot receive funds
DecodePaymentAddress accepted any 43 bytes with a valid bech32 checksum.
An address whose diversifier has no valid g_d, or whose pk_d is not a
point in Jubjub's prime-order subgroup, can never receive a note, yet
z_validateaddress reported it as valid and z_sendmany queued the send.
The async operation then failed in TransactionBuilder::Build
("Invalid sapling note commitment!", surfaced as "Failed to build
transaction.") and took every other recipient in the batch with it.
A mining pool's payouts stalled for 10.5 hours on one such miner
address.

Add SaplingPaymentAddress::is_valid(), which runs
librustzcash_sapling_compute_cm: the same check the builder runs on
every output. DecodePaymentAddress now returns InvalidEncoding when it
fails. As a result:
- z_validateaddress returns isvalid:false for these addresses.
- z_sendmany fails up front with -8 "unknown address format: <addr>".
- Every other RPC and startup option that takes a zaddr rejects them
  through its existing invalid-address path.

The check is the builder's own, so it cannot reject an address the
builder would accept. Wallet-derived addresses are always valid, and
wallet.dat stores addresses in binary rather than decoding these
strings, so existing wallets are unaffected.

Tests: new gtest SaplingAddressValidity covers three real-world
unpayable addresses, constructed small-order, non-canonical, off-curve
and bad-diversifier cases, derived and hardcoded good addresses, and
is_valid() agreeing with SaplingNote::cm(). With the decoder check
reverted, 2 of the 4 tests fail. The full gtest suite passes (100/100),
and the change was verified end to end on regtest.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 10:33:00 -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
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