19f20736df1df4a34c8be4b4e5dabb2b15bc285d
32256
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
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> |
||
|
|
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> |
||
|
|
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> |
||
|
|
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>
|
||
|
|
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> |
||
|
|
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> |
||
|
|
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> |
||
|
|
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> |
||
|
|
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> |
||
|
|
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> |
||
|
|
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> |
||
|
|
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> |
||
|
|
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> |
||
|
|
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>
|
||
|
|
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>
|
||
|
|
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>
|
||
|
|
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> |
||
|
|
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> |
||
|
|
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
|
||
|
|
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> |
||
|
|
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> |
||
|
|
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
|
||
|
|
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> |
||
|
|
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> |
||
|
|
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> |
||
|
|
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
|
||
|
|
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> |
||
|
|
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> |
||
|
|
21586b353a |
wallet/rpc: monotonic timers and a quieter default slow-walk line
Review follow-ups to the GetFilteredNotes / RPC timing logs: - Time with std::chrono::steady_clock instead of GetTimeMicros(), which is the system clock. A wall-clock step otherwise writes false ">= 500ms" lines unconditionally; on a WSL2 host the clock was seen stepping +3.6s every ~32s. - A long-poll getblocktemplate deliberately blocks (with cs_main released) until a new block arrives, so it is logged only under -debug=bench. - Log the method as "RPC method=<name> took <n>ms". A bare " rescan " token followed by "<n>ms" matches ObsidianDragon's rescan-finished log heuristic. - The always-on slow-walk line keeps just the filters and the walk time; the wallet-size counts (txs, notes, spent, entries) are logged only with -debug=bench, so a shared debug.log doesn't carry them. - The -txindex=0 startup line names the version. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
34b94e761a |
wallet: don't copy every encrypted Sapling key on each lookup
CCryptoKeyStore::HaveSaplingSpendingKey and GetSaplingSpendingKey scan mapCryptedSaplingSpendingKeys with `for (auto entry : ...)`. That copies each entry (an extended full viewing key plus its encrypted-secret vector) for every key visited, on every call. GetFilteredNotes' requireSpendingKey check makes one such call per note, and the history RPCs make one per output per address: ~22ns per key per call, measured (11us per note on a 1024-key wallet). Iterate by const reference. The equivalence test gains a locked, encrypted-keystore variant, LockedWalletMatchesLegacy, so spendability coming from the encrypted map is covered too. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
94967efa7b |
wallet: take note heights from the wallet's depth, not tx_height()
For minDepth > 1, GetFilteredNotes located each wallet tx's block with tx_height(), which calls GetTransaction and re-reads the tx from disk through the txindex. It did this once per wallet tx, transparent ones included, while holding LOCK2. z_listunspent and z_listreceivedbyaddress did it once more per returned note. Without -txindex, GetTransaction can only find a tx that still has unspent transparent outputs. tx_height() then returned 0 for every fully shielded tx, and the tx was skipped. So on a -txindex=0 node, sweep and consolidation (minDepth 11) and any minconf >= 2 call never saw those notes. The wallet already has the depth, and for an active-chain tx GetDepthInMainChain is chainActive.Height() - height + 1. The new HeightFromDepth() inverts that (0 when unconfirmed or off the active chain) and replaces tx_height() at all three sites. The height only feeds the == 0 skip and hush_dpowconfs. Both sides hold cs_main for the whole call, so the tip can't move between the walk and the RPC tail. On a -txindex node the results are identical: the txindex block and wtx.hashBlock are the same block. The extended equivalence test now also covers minDepth 2/11/12/22. On -txindex=0 nodes, fully shielded notes now show up for minDepth > 1. With -zsweep or -consolidation enabled, those notes will now be swept and consolidated, so init logs that once. MinDepthAboveOneUsesWalletHeight pins the new behaviour and shows that the old path returned nothing without a txindex. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
bfc1334565 |
wallet: walk GetFilteredNotes by reference, cheap filters first
GetFilteredNotes copied every CWalletTx by value before any filter ran, then copied each SaplingNoteData by value again. Both copies deep-copy the note's witness list (up to WITNESS_CACHE_SIZE witnesses, ~100KB per note on a mainnet wallet): ~40us per note per pass, measured. Spent and locked notes were also fully decrypted (~0.6ms of Jubjub arithmetic per note) before the spent and locked checks threw them away. -deletetx is off by default, so spent notes accumulate. - iterate mapWallet and mapSaplingNoteData by const reference; - skip txs with no notes of ours before CheckFinalTx; - read GetDepthInMainChain once per tx instead of 2+N times (cs_main is held, so it can't change during the walk); - run the spent and locked checks before the decryption; - z_listreceivedbyaddress no longer copies the whole CWalletTx per entry to read its time, and z_sendmany's sort comparator takes its entries by reference. The filters have no side effects, so the result set and its order are unchanged; the A0 equivalence test passes unchanged. One deliberate difference: a spent or locked note whose ciphertext no longer decrypts under its ivk is now skipped instead of tripping the decrypt assert. The new SpentAndLockedNotesAreNotDecrypted test pins this (it aborts on the old ordering). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
b9cdce8e96 |
wallet/rpc: time GetFilteredNotes walks and slow RPCs
GetFilteredNotes logged "GetFilteredNotes ignoreLocked=N" on every call. The balance RPCs run it on every GUI poll, so that line was log spam on a fast wallet, and on a slow one the gaps between its timestamps were the only timing there was. Those gaps also count lock waits and the previous RPC's own post-processing. It now logs one summary per walk: the filters, txs that passed the tx-level checks out of the wallet total, notes examined, notes skipped as spent, entries returned, and the walk time. The summary is always written when the walk takes >= 500ms (that long under cs_main stalls block connection) and otherwise only with -debug=bench. The line has no lock-wait figure: every caller already holds LOCK2(cs_main, cs_wallet) and CCriticalSection is recursive, so the inner LOCK2 never waits. Lock waits are measured where they happen instead. CRPCTable::execute logs "RPC <method> took <n>ms" under the same >= 500ms / -debug=bench rule. The per-locked-note line moves to -debug=zrpcunsafe, since it logs txid prefixes. No behaviour change otherwise. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
dc8ca4996a |
gtest: pin GetFilteredNotes behaviour before optimizing it
Adds test_wallet_notecache.cpp: a wallet with Sapling notes at several
depths (spent by a mined tx, spent by an unmined tx, locked, viewing-key
only, never mined, plus txs carrying no wallet notes), mined into a fake
active chain. The fixture undoes everything it puts into the process-wide
chain state (chainActive, mapBlockIndex, pcoinsTip) in TearDown, since all
gtest suites share one process.
LegacyFilteredNotes is the
|
||
|
|
b911189ac6 |
wallet: don't witness viewing-key-only notes (fixes an abort on the next block)
A note found through an incoming viewing key only (z_importviewingkey)
has no full viewing key behind it. UpdateSaplingNullifierNoteMapWithTx
skips such notes, so they never get a nullifier. VerifyAndSetInitialWitness
treated "no nullifier" as "witness needs reseeding" on every call: it
cleared the note's witness, re-read the block from disk, reseeded it,
and then dereferenced the nullifier that never came. dragonxd aborted
in the txnotify thread (boost::optional "is_initialized" assert) on the
first block confirming a note to such an address, and again after every
restart, before the block index was flushed.
Such a note can't be spent, so it needs no witness. Skip it there; if
its spending key is imported later, it has a full viewing key and the
existing no-nullifier rule seeds it then. SaplingWitnessMinimumHeight
now takes the optional nullifier. A note without one is never extended
by BuildWitnessCache (its pending-note gate requires one), so it must
not lower the rebuild's start height. Every call site that worked before
passes a set nullifier and behaves as before.
The deref came in with the 2020 witness rework (
|
||
|
|
7131b3673f |
qa: add fd-guard, the close() guard and regtest harness that found the double close
shim/ is an LD_PRELOAD guard around close/fclose/dup2/dup3: - before each close it resolves /proc/self/fd/N; - it reports, with a backtrace, a non-owner close of wallet.dat, database/log.* or blocks/*.dat, and every close that fails with EBADF (the second half of a double close); - FDGUARD_ABORT=1 aborts on the first hit; - run_tests.sh self-tests it (51 checks). repro/ runs a shimmed dragonxd on isolated regtest. Each run gets its own unprivileged network namespace (loopback only). The loads are: - rpc: a hammer with impatient/RST/half-open clients, work-queue bursts and long-polls; - p2p: TLS peers churned by disconnectnode, ban and kill, plus a raw TCP/TLS misbehaver; - tor: a fake control port; - mine: mining with blocknotify and autoshield. tools/tally.py groups the reports by closer. tools/scan_bdb.py finds BDB pages written into block files. With the wolfSSL CloseSocket macro in effect: - p2pmin (300 s) gives one EBADF double close per disconnect; - the full load (1200 s) gives 930 EBADF closes, 186 non-owner closes (37 of wallet/log/blk files) and a 632 KB db.log with BDB0060 PANIC; - RPC-only and Tor-only loads give none. After the fix, every count is 0 and db.log stays empty. The README has the commands and the numbers. Paths come from the environment (GOLDEN, BIN, RUNS, SHIM, ASMAP and the Sapling params). Run output goes to $RUNS, outside the tree. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
70b35ac11a |
wallet/db: keep the BDB logs when the shutdown flush fails
CDBEnv::Flush(true) removed database/ (log_archive DB_ARCH_REMOVE, then remove_all) once mapFileUseCount was empty. It did that even when the checkpoint or lsn_reset before it had failed, or the environment had panicked (BDB0060). In those states wallet.dat can be missing committed changes that only the logs hold: - a page write failed (EBADF/ESPIPE through an fd closed behind BDB's back, the wolfSSL CloseSocket bug), so the page stayed dirty in the mpool cache and the checkpoint never completed; - pages written after the last lsn_reset carry real LSNs that point into those logs. Deleting the logs turned a wallet that the next start's DB_RECOVER would repair into one that silently lost those changes. A std::terminate kept the logs; the clean shutdown that ThreadNotifyWallets now does on a wallet DB error deleted them. Remember a failed txn_checkpoint or lsn_reset (in Flush and in CheckpointLSN, which the periodic flush and backupwallet use). Before removing anything, also check the environment for a panic. get_flags reports it, and itself fails with DB_RUNRECOVERY once the environment has panicked. In any of those cases keep database/ and log why. If the kept logs are unusable, the next start already moves database/ aside and retries (CWallet::Verify). WalletDbEnv tests: - a clean shutdown still removes the logs; - a panicked environment (DB_PANIC_ENVIRONMENT) keeps them; - a failed lsn_reset keeps them. With the old db.cpp only the first passes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
5b36d7ad24 |
validationinterface: shut down cleanly when a wallet block notification throws
ThreadNotifyWallets' block disconnect and connect loops had no try/catch (only its mempool loop does). A wallet database failure inside SyncWithWallets or ChainTip escaped the thread, and TraceThread logs and rethrows, so the node died in std::terminate with nothing flushed. One example: CWalletDB::ListAccountCreditDebit's "error scanning DB" after BDB lost its file to the wolfSSL CloseSocket bug. That is how the pool's node died on 2026-10-12 and 2026-10-16. Run each block's wallet notifications through NotifyWalletsOrShutdown. On an exception it logs the error, requests a shutdown, shows the usual fatal-error message and stops the notifier, leaving pindexLastTip at the last block the wallet fully processed. Carrying on instead would leave the wallet behind the chain, missing the block it failed on. Thread interruption still propagates. The shutdown is requested before the fatal-error message is shown. FdDefense.WalletNotifyFailureShutsDownCleanly: - a throwing notification requests a shutdown, a clean one doesn't; - a non-std exception is handled the same way; - boost::thread_interrupted still propagates. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
9cb31326e3 |
main: open block and undo files read-only when they're opened for reading
OpenDiskFile opened every block or undo file "rb+", even for its fReadOnly callers, so every reader held a writable fd. That's what let the wolfSSL CloseSocket bug corrupt blocks/*.dat. A P2P double close took the wallet's BDB fd away; the number was then handed to a block file opened for a getblock/getdata read; BDB's next wallet page write landed in it, at offset pgno*4096. On production that destroyed blocks 2,728,132-2,728,161 in blk00011.dat and block 3,356,880 in blk00020.dat. Every fReadOnly caller only reads through the handle: - ReadBlockFromDisk, UndoReadFromDisk, both GetTransaction paths and hush_blockload read via CAutoFile >>; - the reindex loop hands it to LoadExternalBlockFile, which reads via CBufferedFile; - the existence check at startup only opens it; - hush_prefetch only freads. Open those "rb". A stray write through a reused fd number then fails (EBADF) instead of silently corrupting a block file. Missing files still fail to open as before; writers keep "rb+"/"wb+". FdDefense.ReadOnlyBlockFileIsNotWritable: pwrite through a read-only block file's fd fails with EBADF, while the writable open still writes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
d91e069da3 |
net: stop wolfSSL's CloseSocket macro from turning P2P closes into double closes
wolfssl/wolfio.h (included by <wolfssl/ssl.h> in net.h) does
`#ifndef CloseSocket / #define CloseSocket(s) close(s)`. Every TU that
includes net.h after that point compiles CloseSocket(x) to a bare
close(x). That includes all 15 calls in net.cpp, among them the ones
in CloseSocketDisconnect and ~CNode. util/sock.cpp's
CloseSocket(SOCKET&), the only thing that sets the handle to
INVALID_SOCKET, was never called from net.cpp. This has been the case
since OpenSSL was replaced by wolfSSL (Hush
|
||
|
|
69bb035e7e |
wallet/main: break the replay -> witness-rebuild -> kill loop on large wallets
A v1.3.0 node with a ~13.6k-note wallet (-dbcache=4084) looked hung for hours:
every start replayed ~62k blocks from a chainstate 26 days stale, then ran a
47-60 min all-core witness rebuild holding LOCK2(cs_main, cs_wallet) (RPC answered
HTTP 500 "Work queue depth exceeded", peers timed out), the GUI killed it before
anything was flushed, and the next start did it all again. Even after escaping,
each new block cost ~30s under LOCK2, so the node fell behind a 36s chain.
D1 BuildWitnessCache: the post-rebuild latch computed witnesses.front().root()
(~2.4ms) for every pending note on every block, only to feed a log line that
is printed for bulk rebuilds alone. The anchor check now runs on the Phase-2
workers and only for a bulk rebuild; the per-block path just sets the latch.
Phase 2 also runs in parallel whenever the job is big (notes x commitments
>= 2000), not only for a bulk range, so busy blocks no longer extend every
note serially. If the OS refuses a worker thread, the remaining shards run
inline instead of unwinding past joinable threads (std::terminate).
D2 FlushStateToDisk: the coins cache was only flushed on shutdown, gettxoutsetinfo
or after 24h; on this chain it stays a few MiB, so the size triggers never
fire and a node that never reached 24h uptime or a clean stop kept its
chainstate (and block index) weeks behind. Flush at least hourly and every
DATABASE_FLUSH_BLOCKS (5000) connected blocks -- the latter also inside one
long ActivateBestChain -- and right after the startup ActivateBestChain when
it moved the tip.
D3 UpdatedNoteData: a replayed or rescanned tx arrives with FindMySaplingNotes
data (no nullifier). Witnesses and witnessHeight were carried over but the
nullifier was dropped, so VerifyAndSetInitialWitness cleared and reseeded the
witnesses on the next block -- the replay above rewrote 3,750 txs and forced
the full rebuild. Carry the nullifier with the witnesses, unless the tx was
re-mined in a different block (its notes moved; reseed as before). When the
merged data is identical, don't rewrite the tx; just clear the in-memory
witnessRootValidated so the next block re-checks the kept roots once (a
rescan still finds and reseeds a witness that went bad, without rebuilding
the healthy ones). The carry loop no longer deep-copies every note.
SetBestChain: with hourly coin flushes the wallet locator must not run ahead
of the async notifier, or a crash permanently skips the blocks it had not yet
delivered. Stamp the block the wallet's state reflects (pindexWalletTip,
seeded in init before ThreadNotifyWallets starts -- at the startup rescan's
checkpoint if that rescan was interrupted -- and advanced contiguously by
ChainTip), like zcashd's ChainTipAdded. ThreadNotifyWallets no longer hands
the wallet an empty block after a fatal block-read failure.
Tests: new gtest test_wallet_notedata.cpp (5 tests); 23/23 gtests pass, and the
two core D3 tests fail with D3 reverted. Regtest A/B against master with a
1,008-note wallet: notify-thread CPU per block 1,780ms -> 3ms; worst LOCK2 RPC
stall 1.6-2.9s -> 10-15ms on ordinary blocks and 4.6-7.1s -> ~1.6s on a block
carrying a 40-output self-send; a z_importkey rescan went from 35 reseeds plus a
bulk rebuild (10.6s) to 0 reseeds, same balance; after kill -9 at 150 blocks a
build with a 100-block flush threshold restarted at 100, master at 0. Two
adversarial review rounds; every confirmed finding is addressed here.
Not covered: the hourly SetBestChain/flush paths were reviewed, not exercised
(GetTimeMicros ignores mocktime); no run yet against a copy of a real large wallet.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
||
|
|
da191e447d |
Merge branch 'dev' for the v1.3.0 release
72 commits sincev1.3.0 |
||
|
|
fc26e2e0a0 |
doc: stamp the man pages with the release version, not a build sha
The man pages were regenerated at |
||
|
|
1d2d5f32d0 |
version: bump PROTOCOL_VERSION for the v1.3.0 consensus changes
doc/release-process.md requires PROTOCOL_VERSION to increase by 1 for any release carrying a consensus change. This one does: |
||
|
|
c1040028e4 |
wallet: checkpoint rescan progress when the scan is interrupted
An aborted or shutdown-interrupted rescan discarded all of its progress: nothing
advanced the on-disk best-block locator, so the next run started over. On a large
shielded wallet that is a multi-minute witness rebuild repeated from scratch.
Writes the locator ONCE, at the interrupt, rather than periodically through the
scan. That delivers the whole stated benefit -- "resume where it stopped" -- at
the cost of exactly one SetBestChain per interrupted scan. A periodic checkpoint
would additionally survive SIGKILL and power loss, a much weaker requirement, and
it is the part that carries all the cost: SetBestChainINTERNAL is O(whole wallet)
regardless of progress, so on the reported 5.3k-tx / 7.5k-note wallet a checkpoint
every 2500 blocks would plausibly cost more than the rebuild it was meant to save.
If someone later demonstrates a need for crash resilience mid-scan, add it then,
with a measured interval and fFlush=false -- not before.
Two guards, both necessary:
- CONTIGUITY. The RPC entry points (rescan / importprivkey / z_importkey /
z_importviewingkey) take a caller-supplied start height validated only against
chainActive.Height(), never against the wallet's own persisted locator. A scan
beginning above that locator must not checkpoint at all, or it would record
the skipped range as scanned and hide any funds in it. Logged once when it
applies, so an operator can see why an interrupt did not persist.
- MONOTONICITY. A checkpoint may only advance the locator, never move it back.
The locator points at the last FULLY PROCESSED block -- the parent of the block we
were about to scan -- so resume restarts one block early. CChain::GetLocator pushes
its argument first and FindForkInGlobalIndex returns that same block, so resume
begins AT it; the one-block overlap is deliberate and idempotent, since AddToWallet
only takes its merge path when the transaction is already present.
No witness work is done at the interrupt, which answers the two "//TODO: should we
update witness caches?" comments this replaces: witnesses are re-derived from each
note's own witnessHeight independently of the locator, and witnessRootValidated is
never serialized, so every note is revalidated against hashFinalSaplingRoot on the
next start. A mid-scan checkpoint does capture notes at mixed witnessHeights -- the
in-loop BuildWitnessCache(pindex, true) returns before the extension phase and only
seeds new notes at their own transaction's height -- but that state is recoverable:
the post-loop BuildWitnessCache(tip, false) levels every note, and it now occurs at
most once per scan instead of hundreds of times.
Uses SetBestChainNoFlush so the checkpoint does not trigger a full BDB
txn_checkpoint over the whole cache, and reports failure rather than silently
leaving the operator to discover the replay.
Depends on the fLastRescanCompleted gate in the previous commit: without it
init.cpp would overwrite this checkpoint with a tip locator immediately after the
scan returns.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FU87LdsJZiZkfq1eXubpeo
|
||
|
|
a6b6f80db0 |
wallet: stop an interrupted rescan from hiding funds, and un-latch fAbortRescan
Two independent fund-visibility bugs on the rescan path, both pre-existing.
1. AN INTERRUPTED RESCAN RECORDED ITSELF AS COMPLETE.
ScanForWalletTransactions returns a bare `int ret` (a found-tx count) on both its
abort and shutdown bail-outs, so the caller could not tell "finished" from
"stopped at block H". init.cpp then ran, unconditionally:
pwalletMain->ScanForWalletTransactions(pindexRescan, true);
pwalletMain->SetBestChain(chainActive.GetLocator()); // TIP locator
An interrupted scan therefore stamped the wallet as scanned all the way to the
chain tip. On the next start, the `chainActive.Tip() != pindexRescan` guard just
above sees no work to do and skips the rescan entirely, so every transaction in
the never-scanned range stays out of mapWallet -- permanently invisible to
getbalance and unspendable. That is exactly the case `-rescan` exists for: a key
import, right after ClearNoteWitnessCache has run.
Adds CWallet::fLastRescanCompleted, set false at scan entry and true only on the
normal exit, and gates the init.cpp locator write on it. Deliberately NOT
overloading the int return, which callers already use as a tx count.
2. fAbortRescan WAS NEVER RESET.
wallet.h declares it, AbortRescan() sets it true, and nothing in src/ ever sets
it false. The abortrescan RPC is live. After one call, for the remaining lifetime
of the process:
- every ScanForWalletTransactions returns immediately, so re-running an import
silently no-ops while the RPC still reports success;
- BuildWitnessCache bails on the same flag on EVERY call, including the routine
per-block extension from ChainTip.
Witness heights then diverge across notes while the chain advances, and
GetSaplingNoteWitnesses elects the majority root as the anchor and returns
boost::none for every note that disagrees. Those notes still show in the balance
but cannot be spent. Cleared at scan entry and consumed in the abort branch.
Also in BuildWitnessCache's abort branch: stop clearing fRescanning. A witness
rebuild is not a rescan and must not touch a flag ScanForWalletTransactions owns.
3. Both bail-out log lines had two format specifiers and one argument:
LogPrintf("%s: Rescan aborted at block %d\n", pwalletMain->rescanHeight);
tinyformat's "too many conversion specifiers" guard is disabled in this tree
(tinyformat.h: `if(*fmt != '\0' && 0 ) // disabled due to complaints`), so this
does not throw -- verified by compiling the exact call against this tree's
tinyformat.h. It emits "3841207: Rescan aborted at block " with the height in the
__func__ slot, the real height dropped, and the trailing newline swallowed so the
next log line concatenates onto it. On the one path an operator has to diagnose
an interrupted rescan, the only record was corrupt. Fixed at both sites, and the
state updates moved above the log call.
4. Makes SetBestChainINTERNAL report whether the atomic write committed, so a
checkpointing caller can tell (six failure paths returned void). Adds
SetBestChainNoFlush, which opens the wallet DB with fFlushOnClose=false: the
default ctor makes ~CDB run a full BDB txn_checkpoint over the whole cache, which
is fine hourly but not from inside a scan -- the same flush wallet.cpp already
documents avoiding elsewhere "for performance reasons". Nothing calls it yet.
5. SetBestChainINTERNAL took each CWalletTx by value, deep-copying every note's
witness deque (WITNESS_CACHE_SIZE entries) per transaction per call, purely to
serialize it. Now by const reference.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FU87LdsJZiZkfq1eXubpeo
|
||
|
|
3aac75e94f |
cli: report the port actually dialled, not a stale global
dragonx-cli resolves -rpcport correctly -- CallRPC does
int port = GetArg("-rpcport", BaseParams().RPCPort());
and dials that port. But both connection-failure messages printed
ASSETCHAINS_RPCPORT instead, a separate global defined at the top of
bitcoin-cli.cpp, initialised to the mainnet default 21769, and never assigned
anywhere in the CLI.
So every failure claimed port 21769 regardless of what was asked for:
$ dragonx-cli -rpcport=21799 getblockcount
error: couldn't connect to server at port 21769
That reads as "your -rpcport was ignored", which is a much more alarming and
much more misleading diagnosis than "nothing is listening yet". It cost an hour
of debugging on a node that was simply still loading a 15 GB txindex, and led to
the wrong conclusion that the CLI could be talking to the production daemon when
it was not.
Both sites now print the local `port`. Verified against the previous binary:
new: -rpcport=21799 -> "couldn't connect to server at port 21799"
-rpcport=59999 -> "couldn't connect to server at port 59999"
old: both -> "couldn't connect to server at port 21769"
and the CLI still reaches a live daemon on a non-default port.
ASSETCHAINS_RPCPORT is left defined; it is referenced by other translation units.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FU87LdsJZiZkfq1eXubpeo
|
||
|
|
5634aed750 |
wallet: open salvaged wallets in a degraded mode, and detect a mismatched hdchain
A wallet.dat repaired by v1.0.3-or-earlier -salvagewallet could not be opened by
this build at all. Those builds' IsKeyType has no "hdchain" case, so salvage
dropped the record; LoadWallet then returned DB_CORRUPT and told the user to
restore from a seed phrase. There is no such recovery path: the node aborts
before the RPC server exists, -usemnemonic defaulted to 0 in v1.0.3 so many of
these wallets never had a phrase, and SetHDSeedFromMnemonic refuses a non-empty
wallet, so "move wallet.dat aside" discards every non-HD key salvage preserved.
The guard itself was right to refuse to DERIVE -- a missing hdchain falls back to
SetNull defaults, clearing fMnemonicSeed and switching derivation from the
64-byte BIP39 seed to the raw 32-byte entropy, an entirely different key tree.
It was wrong to refuse to OPEN. Split the two:
- "hdchain" record ABSENT (the salvage signature, tracked by a new
wss.fHDChainSeen set before any parse attempt) -> open DEGRADED.
- "hdchain" record PRESENT but unreadable -> still DB_CORRUPT; that signals
wider file damage.
Degraded means the wallet spends, receives and rescans normally but refuses to
derive any new HD key. Gated at the single choke point GetHDSeedForDerivation
rather than at the two generators, so z_getnewaddress/sendmany/shieldcoinbase
raise a clean error and autoshield skips. hdChain.seedFp is deliberately left
null, which keeps IsHDTransparentEnabled false so getnewaddress falls back to the
legacy random-key path -- gating it instead would break TopUpKeyPool, change
addresses and block templates. -rescan is soft-set because an old salvage also
dropped defaultkey and bestblock, which would otherwise look like a first run and
skip the rescan, leaving a permanently zero balance.
NEW DETECTOR, covering strictly more damage than the guard beside it. A wallet
salvaged by v1.0.3 and then USED on v1.0.3 persists a SetNull-derived hdchain
carrying seedFp=null. On this build fHDChainRead is then true, the guard never
fires, the node starts perfectly clean -- and derives into the wrong key tree
forever, silently. That state is unforgeable by any legitimate writer, since
InstallHDSeed always stores seedFp = seed.Fingerprint(), so compare the loaded
chain's seedFp against the fingerprint taken from the hdseed/chdseed record KEY
(which works while an encrypted wallet is locked) and degrade on mismatch.
Also:
- init.cpp: abort in the DB_CORRUPT branch itself, as DB_NEED_REWRITE already
does. Falling through ran several hundred more lines against a wallet just
declared corrupt, including SetHDSeedOrigin(), which WRITES to it. Error text
no longer advises -mnemonic (wrong twice over, see above).
- rpcdump.cpp: z_exportwallet discarded GetHDSeedForDerivation's return and
emitted the line regardless, so a failure wrote a blank seed next to a
legitimate-looking BLAKE2b-of-empty fingerprint -- a backup that looks valid
and restores nothing.
- Corrected the guard's comment: the saplingAccountCounter half was overstated.
Both generators loop while(Have...Key(...)), so a low counter walks forward
past existing accounts rather than colliding with them.
qa/r4-salvaged-wallet-harness.sh builds the victim wallets with the on-disk
v1.0.1 release binary and asserts the behaviour end to end. It REFUSES to run
outside a network namespace and re-checks getconnectioncount==0, because those
old binaries predate the regtest seed-injection fix and would otherwise dial the
live network. 11/11 pass:
C healthy wallet opens and is NOT flagged (no false positives)
A salvaged wallet opens, flagged, persists no hdchain, z_getnewaddress refused,
getnewaddress still works, z_exportwallet emits no bogus HDSeed line
B poisoned wallet opens and the seedFp detector fires
Note the harness asserts "no hdchain synthesised", NOT "wallet.dat unchanged":
a control run showed normal startup rewrites wallet.dat for healthy wallets too.
This is the access/detection half. Proving fMnemonicSeed by re-deriving against
held keys, and repairing the record, is deliberately left out: it requires a
write, and the affected population is unmeasured. dev's own salvage already
preserves hdchain, so the class is closed going forward.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FU87LdsJZiZkfq1eXubpeo
|
||
|
|
db42091ce3 |
rpc/net: gate and harden stratummine, keep regtest off the live network, init nSPV filter
stratummine (rpc/mining.cpp), a test-only reference miner, was registered
unconditionally behind a bare #ifndef WIN32 with okSafeMode=true, so it shipped
as a live RPC on every non-Windows release build. Four fixes:
- Gated behind an explicit, default-off -stratummine, with regtest exempt so
qa/rpc-tests can still drive it. Deliberately NOT gated on fExperimentalMode:
that defaults to TRUE (init.cpp:1195), so such a gate is a no-op -- an error
made and caught while testing this change.
- mining.notify's three hash fields went straight into uint256(ParseHex(...)).
uint256's vector ctor asserts on a wrong size (uint256.cpp:30) and NDEBUG is
defined nowhere in this build, so that assert is live in release; ParseHex
also truncates silently at the first non-hex character. A short or garbled
field therefore ABORTED THE DAEMON. Added StratumHex256(), which requires 64
hex chars and a 32-byte result, and all three fields are validated before any
is committed so a bad job is rejected rather than half-applied.
- processLine ran inside the window where the RandomX cache, the VM and the
socket are live, all released on the normal path only, and every get_str()
throws on a type mismatch -- so a malformed message leaked 256 MB and the fd.
Body wrapped in try/catch: ignore the line, keep mining.
- Caller-supplied timeout clamped to [1, 3600]; it was unbounded, pinning an
RPC worker and the cache indefinitely. okSafeMode -> false.
Verified against a hostile stratum server on regtest:
- 4 malformed mining.notify payloads (short hex, non-hex, wrong JSON type,
31 bytes) -> all rejected, daemon alive, 0 assertions. The 31-byte case is
the one that previously hit the uint256 assert.
- valid job first (so RandomX actually allocates) then garbage mid-mine ->
RSS delta +2.2 MB, i.e. cache and VM released, not the ~256 MB a leak leaves.
- regtest exemption confirmed: stratummine runs past the gate there.
The non-regtest refusal path is by code reading only -- a testnet node on this
host collides with the production daemon's RPC port, so it was not exercised.
hush_utils.h: stop injecting the mainnet node1-node10.dragonx.is addnode seeds
when -regtest or -testnet is set. regtest reuses mainnet's network magic, so a
supposedly isolated node was handshaking production peers and pulling their
headers into its own index. Gated at the injection site only -- isdragonx itself
must stay true, because it also selects ac_private, ac_algo, blocktime and the
reward/halving schedule (an earlier version of this patch gated isdragonx itself
and silently turned ac_private off on regtest). hush_args() runs between
ParseParameters() and ReadConfigFile() (bitcoind.cpp:115/144/158), so this sees a
command-line -regtest, as qa/rpc-tests uses, but not a config-file regtest=1.
hush_nSPV_fullnode.h: initialize `filter` at both sites. It was assigned only on
the len-11 request form; the other two passed uninitialized stack memory to
NSPV_getaddressutxos/NSPV_getaddresstxids, remotely reachable since
HUSH_NSPV_FULLNODE is on by default.
getblocktemplate_proposals.py still passes.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FU87LdsJZiZkfq1eXubpeo
|
||
|
|
6d282db216 |
consensus: stop BLOCK_VALID_CONTEXT overwriting the block validity level
BLOCK_VALID_CONTEXT was 6. The validity levels above it are sequential VALUES
packed into a 3-bit field, not independent bits, so BLOCK_VALID_MASK is
1|2|3|4|5 == 7 and the value 6 sat entirely inside it. `pindex->nStatus |=
BLOCK_VALID_CONTEXT` (main.cpp:5616, and :3285) therefore did not set a flag --
it overwrote the validity level.
Consequences, all long-standing:
- A header-only block raised to BLOCK_VALID_TREE(2) became 2|6 == 6, which
reads as >= BLOCK_VALID_CHAIN(4) and >= BLOCK_VALID_SCRIPTS(5). A block
merely written to disk reported full script validity.
- Every later RaiseValidity() silently no-opped, because 6 >= every level.
ConnectBlock's RaiseValidity(BLOCK_VALID_SCRIPTS) was a permanent no-op.
- CheckBlockIndex's "CHAIN valid implies all parents are CHAIN valid" invariant
was violated whenever a stored block sat above a still-header-only ancestor,
i.e. ordinary out-of-order parallel block download. fDefaultConsistencyChecks
is true only for regtest, so the abort was regtest-only -- but the garbled
index is written identically on mainnet, where only the detection is off.
Not a v1.3.0 regression: introduced upstream in Komodo
|