BuildWitnessCache stops extending a note once its spend is deeper than
WITNESS_CACHE_SIZE (MAX_REORG_LENGTH + 10 = 109): no reorg can un-spend it any
more. But the up-to-109 witness snapshots the note had by then were never
released. Every spent note the wallet ever had kept them, in memory and in
wallet.dat, and SetBestChain rewrote them all on every save. On a wallet that
receives a steady stream of deposits and sweeps them, memory and wallet.dat grow
with the number of notes ever received.
Measured in the 2026-11-29/30 stress soak (exchange-style wallet, ~360 deposit
notes an hour swept to a withdraw address): RSS rose ~120-170 MB an hour to
2.9 GB over 18 h, wallet.dat reached 855 MB for ~6,500 transactions, and the
per-block log reported ~6,200 witnessed notes. With deposits stopped, RSS stopped
climbing, so this is history growth, not a leak.
Now such a note keeps only its newest witness (front()). That one is at
witnessHeight, gives the position its nullifier is derived from, and is the root
VerifyAndSetInitialWitness validates at startup, so a trimmed note loads and
validates exactly as before. The list is never emptied: a note with no witnesses
loses its nullifier in UpdateSaplingNullifierNoteMapWithTx and would then count
as unspent. A deeper-than-cache reorg (only possible after raising -maxreorg)
already pops or clears such notes' single remaining witness and reseeds them.
The trim runs in the per-block BuildWitnessCache pass, which already evaluates
each note's spend depth, so it costs no extra wallet walk. It bumps
nWitnessGeneration so the next SetBestChain or the shutdown save writes the
shorter lists, and logs how many notes it trimmed.
New gtest WalletWitnessTrim covers: deeply spent notes keep exactly their newest
witness (root, position, height, nullifier unchanged); unspent and in-reach notes,
notes without a nullifier, and empty lists are untouched; the serialized note
shrinks by more than 20x.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Two bugs from the general audit (origin/audit-fixes-20260901), both still on dev:
- SendMessages pushed the whole of vAddrToSend once for every address the peer did not know yet, so
one getaddr reply of N addresses went out as N messages of N addresses each, all serialized and
checksummed while cs_main is held. The locally built vAddr was never sent. Restore the upstream
idiom: collect the unknown addresses, send them in MAX_ADDR_TO_SEND batches, then the rest once.
The ADDR/ADDRV2 choice and the wire format are unchanged.
- CNode::PushAddress tested IsAddressKnown(addr) -- the CNode member holding this peer's own address
-- instead of _addr, the address being queued. Once the peer's own address was in its addrKnown
(routine: it advertises itself, or it comes back in a getaddr reply), every address queued for that
peer was dropped until the daily addrKnown.reset(). Fixed together with the first bug, since it
re-enables relay paths that would otherwise be amplified.
Regtest, two nodes over TLS, node A holding ~1000 addresses and B connecting and sending getaddr:
the old binary answered with 18 identical 235-byte addrv2 messages (5017 bytes to the peer); this
sends the same 235-byte message once (614 bytes). On mainnet a reply carries far more addresses,
and the waste grows with the square of that count. New gtest NetAddrRelay.PushAddressFiltersOnQueuedAddress
fails with the old filter.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
The base class said "Override this method if you can interrupt execution of main()", but cancel()
was not virtual. Every caller holds a std::shared_ptr<AsyncRPCOperation> -- the queue's map, the
wallet schedulers, z_consolidate -- so the overrides in the sweep, consolidation and autoshield ops,
written to move an EXECUTING operation to CANCELLED, never ran: the base version only cancels an
operation that has not started. In practice that meant a stop could not interrupt a running
automatic round; the node waited for it to finish every remaining transaction. Consolidation had
grown its own ShutdownRequested() checks as a workaround.
- cancel() is virtual, and the three overrides are marked override, so this cannot silently
regress: with the base non-virtual again they fail to compile.
- Only the queue closing at shutdown can cancel a running round. The schedulers return early
while a round is in flight (the sweep since its in-flight guard, consolidation and autoshield on
their running flags) and z_consolidate refuses while a consolidation runs, so they only ever
cancel an operation that has finished, which the overrides leave alone.
- A round cancelled part-way stays CANCELLED instead of being relabelled SUCCESS or FAILED by how
much of it got done, and logs "(status=cancelled)".
- The sweep checks isCancelled() || ShutdownRequested() before starting each address as well as
after each build, so a stop does not wait for another multi-second build to be discarded.
- Comments that described the old behaviour are corrected.
New gtest AsyncRPCCancel: each override is reached through a shared_ptr<AsyncRPCOperation> and
stops an EXECUTING op, leaves SUCCESS/FAILED alone and still cancels a READY one; an op without an
override still only cancels before it starts (z_sendmany and friends are unaffected). With the old
declarations, the three override tests fail. Regtest, same fixture, the node stopped while a sweep
round was building its first of four transactions: dev took 56.2 s to exit, building all four first;
this exits in 9-12 s ("Canceled. Stopping.", status=cancelled), and the wallet is intact on restart.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
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>
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>
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>
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>
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>
FlushStateToDisk writes the wallet's SetBestChain at most once an hour,
the shutdown flush included, and its timer starts at "now" on the first
call. A session shorter than an hour therefore never saves: the next
start rescans every block of the session ("Rescanning last N blocks"),
re-extends every note witness across it, and then rewrites the whole
wallet inside init before RPC answers. Measured on regtest with a
throwaway prototype: restarts of 8.3 s -> 2.0 s (150 empty blocks),
29 s -> 2.5 s (150 blocks, 639 commitments), 66 s -> 8.5 s (8,215 notes,
631 MB wallet). The cost moves to the stop, at about 41 MB/s of
wallet.dat.
Add CWallet::PersistStateAtShutdown(), called from Shutdown() inside
the existing cs_main block right after the chainstate flush and before
the coins view and the wallet are torn down. It calls
SetBestChain(chainActive.GetLocator()), which on this tree stamps
pindexWalletTip, the block the wallet's state reflects, in the same
atomic transaction as the witnesses. It logs "Saving wallet state ..."
first, so a GUI can show that the stop is busy, and then the height,
the txs written, the elapsed ms and whether it committed. It skips the
write, and logs why, when:
- AppInit2 did not run to the end (new fInitCompleted): threads were
interrupted but not joined, and with no wallet tip SetBestChain would
stamp the chain tip over an interrupted rescan's checkpoint;
- the shutdown came from the wallet failing on a block
(NotifyWalletsOrShutdown now sets fWalletNotifyFailed), or the BDB
environment has panicked or a checkpoint/lsn_reset failed (new
CDBEnv::IsHealthy()): a full-wallet write into that database fails
or deepens the damage, and the logs are what recovery needs;
- nothing changed since the last committed save. SetBestChain now
returns SetBestChainINTERNAL's result (the CValidationInterface hook
returns bool) and, when it committed, records the block it stamped
and a generation counter that BuildWitnessCache (when it extended),
DecrementNoteWitnesses, VerifyAndSetInitialWitness reseeds,
ClearNoteWitnessCache and AddToWallet (a note-bearing tx inserted or
changed) bump. Init records the same when it finds the locator at
the tip and does not rescan. This also stops a second full write
when the hourly SetBestChain happens to fire in the shutdown flush.
FlushStateToDisk and DATABASE_WRITE_INTERVAL are unchanged: dropping
the throttle for FLUSH_STATE_ALWAYS would also rewrite the whole wallet
on every gettxoutsetinfo and on the init flush after a replay.
witnessRootValidated stays in memory only, so every witness is still
root-checked against hashFinalSaplingRoot on the next start, and a kill
during the write rolls back to the previous save (DB_RECOVER).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sapling consolidation picks notes in wallet order, a random 1..8 of them
per address with rand(), and merges every address with three or more
notes, every round. A miner whose wallet autoshield fills with one note
per round wants the opposite: leave tidy addresses alone, merge the
small notes of the crowded ones in bounded batches, and never re-merge
the big note an earlier round produced.
Add that policy as a pure function the op can use and the tests can
drive: PlanSaplingConsolidation() takes each address's eligible note
values and returns the round's batches. Only an address with MORE than
the threshold of notes (default 25) is consolidated; its notes are taken
smallest first, up to maxtxs transactions (default 3) of a per-tx input
count drawn from [max(2, ceil(2*batch/3)), batch] (default batch 15,
clamped to 2..50 and to what fits in MAX_TX_SIZE_AFTER_SAPLING next to
the 1 + 7 Sietch outputs). A transaction never takes an address's last
note, so the address stays spendable while the round confirms, and
batches never mix addresses. The randomness is the caller's (the op
will pass GetRand).
The option defaults live with the other auto-op defaults in wallet.h.
Nothing calls the planner yet.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
zsWalletTxJSON (z_listsentbyaddress, z_listreceivedaddress, getalldata)
runs once per wallet tx under LOCK2(cs_main, cs_wallet). For every
shielded output it copied the wallet's address set, and for each address
fetched the spending key, re-derived its full viewing key (an
elliptic-curve operation), and trial-decrypted the output; the sends side
did the same with the ovk. Every received or sent note in a tx with
spends walked the whole wallet in GetNullifiersForAddresses for the
change check. The spends side decrypted every spent note again and
deep-copied its SaplingNoteData (witnesses included). The GUI runs
z_listsentbyaddress over the whole wallet on every launch.
SaplingHistoryKeys, built once per RPC call, holds each address with a
usable spending key (in GetSaplingPaymentAddresses order, with its ivk
and ovk as the spending key gives them, and its ivk as
GetSaplingIncomingViewingKey gives it). It also gives the change check
as a lookup into the wallet's (ivk, nullifier) pairs, collected on first
use. The helpers keep their exact structure and quirks. Each output's
JSON object and change flag still accumulate across the addresses that
decrypt it. Diversified addresses sharing a key still produce one entry
each. An unknown address still checks change under a zero ivk. A locked
wallet still reports no shielded received or sent entries. Only the
repeated work is gone:
- each output is decrypted at most once per distinct key. Once it is
known which ivk decrypts an output, no other ivk is tried: the cached
plaintext, or a decryption under the ivk the wallet's note data
records. Two canonical ivks can't both pass the note commitment check,
which pins pk_d = [ivk]g_d;
- outCiphertexts are decrypted once per distinct ovk; the t->z shielding
ovk is derived from the seed once per tx;
- spends use the cached plaintext of the spent note.
Two deliberate behaviour changes. The spends helper looked notes up with
operator[]: it inserted a null-outpoint entry into
mapSaplingNullifiersToNotes for every other wallet's nullifier it met.
After getalldata or z_listsentbyaddress had run, z_viewtransaction of
any tx spending someone else's note (every incoming z->z payment) failed
with map::at. And with an inconsistent nullifier map, it inserted an
empty note into a wallet tx. The helpers now only read the wallet. Also,
if the walletpassphrase timer relocks the wallet during the call, the
whole call reports the keys as of its start; the old per-output lookups
switched over partway.
test_wallet_history.cpp holds 69bb035e7's helpers verbatim (renamed)
and a wallet exercising every branch:
- default and diversified addresses, a viewing-key-only address, and a
key imported after its note arrived;
- z->z sends with change, and with text, empty and binary memos;
- a send nobody's ovk reads, and a t->z shielding send;
- our spends, someone else's, and a mixed tx.
Every tx x every return type x nine address filters gives byte-identical
JSON: with the plaintext cache warm, cold, and on an encrypted wallet
both locked and unlocked. Mutation-checked: dropping the ivk check from
the uniqueness shortcut fails the test. DoesNotModifyTheWallet pins the
read-only change (and shows that the old helpers did insert the foreign
nullifier).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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 69bb035e7 loop verbatim, with tx_height()
passed in so the minDepth > 1 branch can be modelled on a -txindex node.
FilteredNotesMatchLegacy compares the real walk against it entry by entry
and in order (z_sendmany sorts the result with an unstable sort) over
minDepth {0,1} x maxDepth x ignoreSpent x requireSpendingKey x
ignoreLocked x address filters. FixtureExercisesEveryFilter checks that
each filter really removes something, so the comparison can't pass
vacuously.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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>
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>
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 9ff756590, 2020), so every
DragonX release is affected.
So CNode::hSocket kept its number after the socket was closed. Every
P2P disconnect closed that same number again, 2 to 4 times:
- CloseSocketDisconnect (net.cpp:572) runs once per disconnect trigger
(ThreadSocketHandler, SocketSendData, the TLS socket handler,
ThreadMessageHandler), and each run still saw a valid-looking hSocket;
- ~CNode (net.cpp:2819) then closed it once more.
Meanwhile the socket handler kept FD_SETting, send()ing and recv()ing on
the stale number. In between, other threads get that number from the
kernel's lowest-free-fd rule:
- BDB reopening wallet.dat or database/log.* (ThreadFlushWalletDB, ~11/s);
- fopen("rb+") of a block file for getdata/getblock;
- an HTTP RPC accept.
The stray close then closes it. BDB keeps doing I/O on the dead number:
'wallet.dat: write failed for page N' / 'Illegal seek' / 'BDB0060
PANIC', or silent wallet-page writes into a blocks/blk*.dat that got
the number next. Its failing reads later threw out of ThreadNotifyWallets
(std::terminate). A closed HTTP connection fd makes libevent re-arm
and later close whatever owns that number next ('Epoll ADD ... failed').
Reproduced on isolated regtest with an LD_PRELOAD close() guard:
- one disconnectnode gives exactly one EBADF double close (49
disconnects, 50 EBADF; with strace and no shim, 29 disconnects gave
30 'close(N) = -1 EBADF');
- P2P churn alone gives non-owner closes of block files and wallet.dat;
- RPC-only and Tor-only loads give none.
Disassembly of CloseSocketDisconnect and ~CNode shows 'call close@plt'
before this change and 'call CloseSocket(unsigned int&)' after.
Undefine the macro right after the wolfSSL include in net.h; wolfio.h
is include-guarded, so it can't come back. net.cpp gets an #error
tripwire in case it ever does. NetCloseSocket.ClosedNodeNeverClosesAReusedFdNumber
fails on the old code (a closed CNode closes the fd number's new owner)
and passes now.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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>
Covers b3e81f1ed: a 63-character mining.submit job_id containing any
non-hex byte must never complete to a 32-byte vector, so the EWBF
completion loop skips it instead of constructing uint256() (which
asserts vch.size()==32 and would abort the daemon from an
unauthenticated client).
Five cases pin the invariant using the real ParseHex/uint256 primitives:
all-spaces, a non-hex byte mid-string, and a non-hex byte at the end
never yield 32 bytes; a genuine 63-hex job_id completes to exactly 32
bytes for all 16 digits; plus ParseHex odd/even-length anchors. Wired
gtest/test_stratum_jobid.cpp into Makefile.gtest.include (5 tests, all
pass; full hush-gtest suite now 18/18).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PGhWvdBSgt6UxxHANr7gfN
Derive transparent (t-addr) keys from the HD seed and add BIP39 mnemonic seed
phrases that are byte-for-byte compatible with SilentDragonXLite, so the same
24 words recover the same shielded and transparent addresses in either wallet.
HD transparent keys:
- Derive t-keys from the seed at m/44'/coin'/0'/0/i (were random CKeys).
- CHDChain gains a version-gated transparent counter; existing wallets load
unchanged. GenerateNewKey routes through DeriveNewChildKey when enabled
(-hdtransparent, default on).
- Restore from a seed hex via -hdseed with gap-limit pre-derivation; birthday
pinned to genesis so the rescan is not clipped.
BIP39 seed phrases:
- Wire the vendored trezor BIP39 lib (src/crypto/bip39) into the build, fix its
BIP39_WORDS guard, and disable the insecure mnemonic cache.
- Match SDXLite exactly: English wordlist, empty passphrase, PBKDF2 64-byte
seed, coin type 141, ZIP-32 m/32'/141'/i' and BIP44 m/44'/141'/0'/0/i. Store
the 32-byte entropy and expand to the 64-byte seed on demand.
- Restore via -mnemonic, create via -usemnemonic, reveal via z_exportmnemonic.
Verified by gtests including a known-answer BIP39 seed vector and z/t address
derivation checks (src/gtest/test_hdtransparent.cpp, test_mnemonic_compat.cpp).
Docs in doc/hd-transparent-keys.md and doc/seed-phrase.md.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Removes the dumptxoutset RPC, -loadutxosnapshot / -loadutxosnapshotunsafe,
the CCoinsViewDB Dump/LoadSnapshot machinery + CUTXOSnapshotHeader, the
AssumeutxoData chainparams anchor, the LoadSnapshotChainstate activation +
reorg-below-H guard, the persisted assumeutxo-height flag, and the gtest.
Rationale: it duplicated the existing bootstrap (same skip-the-genesis-grind
fast-sync, no speed advantage), its only real edge was a trust model we don't
need for this chain, and it was inert anyway (no published snapshot hash in
chainparams). The -loadutxosnapshot load path adopted an external UTXO set and
bypassed genesis validation, so removing it also drops that attack surface.
Builds clean (no dangling references); the kept IBD speedups (RandomX
pre-verify, adaptive dbcache, tlsmanager) are untouched.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
LIBBITCOIN_SERVER was fed into both EXTRA_LIBRARIES (a list of buildable
library files) and several _LDADD link lines. Embedding the -lcurl linker
flag inside it made automake reject it in the EXTRA_LIBRARIES context
("'-lcurl' is not a standard library name"). Make LIBBITCOIN_SERVER a pure
file and route -lcurl through its own LIBCURL variable, added to the
dragonxd, hush-gtest, and test_bitcoin link lines after libbitcoin_server.a
(whose objects reference curl symbols) so static link order stays correct.
Verified with a clean Windows cross-build (-DCURL_STATICLIB) and a native
Linux build: both link cleanly and the automake lint is gone.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
- Parallel RandomX PoW pre-verification pool (CCheckQueue) run ahead of the serial
connect; consensus-neutral (inline CheckRandomXSolution fallback still verifies
anything not pre-verified). New -randomxverifythreads (default = -par).
- Adaptive dbcache: default sizes the UTXO/coins cache to most of RAM and shrinks
under memory pressure, always leaving a reserve free; -dbcache pins a fixed value.
- P2P block download: bounded socket recv-drain loop (tlsmanager); frontier-block
reassignment to break head-of-line stalls (-blockreassigntimeout); ProcessGetData
serves a bounded batch of blocks per pass instead of one (fixes the serve-side
one-block-per-tick throttle that caps download network-wide).
- assumeutxo: dumptxoutset RPC + LoadSnapshot machinery + AssumeutxoData chainparams.
- Signed bootstrap verification (util/bootstrap-dragonx.sh, util/sign-bootstrap.md).
- gtest: RandomX pre-verify consensus-equivalence test + UTXO-snapshot round-trip;
revived the gtest harness (Makefile.am include fix, Makefile.gtest.include).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>