32261 Commits
Author SHA1 Message Date
DanS aea4bb7fa3 Merge branch 'fix/expired-log-and-sweep-error' into dev 2026-12-01 15:17:18 -06:00
DanSandClaude Opus 5.5 a7b15e40a0 wallet: say why a zsweep or autoshield round failed when its tx is rejected
When CommitAutomatedTx refused a transaction (AcceptToMemoryPool rejected it),
the sweep and autoshield ops returned false without setting an error, so the
operation finished as "failed" with an empty message:

  Sweep operation finished. (status=failed, error=)

Seen twice in 175 sweep rounds in the 2026-12-01 soak; one was a note already
spent by another transaction ("sapling nullifier ... exists"). Both ops now set
RPC_WALLET_ERROR and a message naming the rejected txid, pointing at debug.log
for the mempool's reason (CommitTransaction does not return it), and saying the
next round retries. Consolidation already records a per-address reason.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-12-01 15:11:48 -06:00
DanSandClaude Opus 5.5 2a2eaa2078 wallet: stop logging every mined transaction as "expired" on each rebroadcast
ResendWalletTransactionsBefore applied its "expired, don't relay" test to every
wallet transaction, mined ones included. A confirmed transaction is past its
expiry height a few hundred blocks after it was mined, so every pass (every
0-30 minutes) logged one "ignoring expired tx" line per transaction the wallet
had ever made, and the count only grew.

Measured in the 2026-12-01 soak (exchange-style wallet, ~15k transactions):
14,735 distinct "expired" txs x 89 passes = 1.1 million lines; debug.log grew
by 354 MB in 24 h.

Mined transactions are now skipped before the expiry test (they have nothing to
rebroadcast; RelayWalletTransaction already refused them). Genuinely expired
unconfirmed transactions are counted and reported in one summary line, with the
per-transaction detail under -debug=wallet. The function now takes cs_main
itself as well; both callers already hold it, and GetDepthInMainChain needs it.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-12-01 15:07:24 -06:00
DanS c4b0a23911 Merge branch 'fix/trim-spent-witnesses' into dev 2026-11-30 12:44:29 -06:00
DanSandClaude Opus 5.5 7c0702affa wallet: make zsweep and consolidation take strict turns
The previous fix (3e75769a4) let a due sweep give way once to a consolidation
round that was running or "due within 5 blocks", and then hold every new
consolidation round off until the sweep had run. On a wallet that always has
something to sweep this starved consolidation instead: the 5-block "give way"
itself set the waiting flag, the next consolidation was refused because a sweep
was waiting, the sweep ran, and so on.

Measured on the 2026-11-30 soak of 9c7c5835b (exchange-style wallet, zsweep
every 5 blocks, consolidation at the default 25): in 15.5 h, 2,375 sweep txs and
0 consolidation txs (273 deferrals); the withdraw address piled up to 5,898
unspent notes and RSS reached 4.7 GB.

Now the two ops take strict turns:
- a due sweep that finds a consolidation round running sets fSweepWaiting, and
  no new consolidation round starts until the sweep is dispatched;
- a due consolidation round that finds a sweep running sets
  fConsolidationWaiting, and no new sweep round starts until it is dispatched;
- the 5-block blackout is gone (with consolidationinterval=5 it was always true);
- whichever op yields clears its own flag, so they can never both be waiting;
- each flag is cleared on dispatch, when its op is off, or when it is skipped for
  a locked wallet.

z_consolidationstatus gains waiting_for_sweep, next to z_sweepstatus's
waiting_for_consolidation. doc/zsweep-consolidation.md updated.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-30 12:44:29 -06:00
DanSandClaude Opus 5.5 19f20736df wallet: drop the witness history of notes spent beyond reorg reach
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>
2026-11-29 22:23:02 -06:00
DanS 9c7c5835bd Merge branch 'fix/sweep-consolidation-fairness' into dev 2026-11-29 19:41:43 -06:00
DanS 722c3a7d7a Merge branch 'fix/autoop-expiry' into dev 2026-11-29 19:41:43 -06:00
DanS 8dc2e3c93c Merge branch 'fix/stratum-default-address' into dev 2026-11-29 19:41:43 -06:00
DanSandClaude Opus 5.5 3e75769a48 wallet: stop consolidation from starving zsweep
RunSaplingSweep returned early, and retried the next block, whenever a
consolidation round was running or due within 5 blocks, but kept no memory of
having given way. With consolidationinterval=5 the "due within 5 blocks" test is
always true, and with longer intervals a long consolidation round could fill the
remaining blocks, so on a busy wallet the sweep could go a whole run without
dispatching while deposits piled up.

Measured on the 2026-11-29 stress fleet (exchange-style wallet, zsweepinterval=5,
consolidationinterval=5, 150 deposit notes): in 20 minutes consolidation ran
4 rounds / 11 txs and the sweep 0, with 45 "not sweeping since consolidation"
lines; the deposit notes never moved.

A due sweep now gives way once and records it in fSweepWaiting. While that is
set, RunSaplingConsolidation starts no new round (nextConsolidation is left
alone, so that round runs right after the sweep), and the sweep skips the
5-block blackout. The flag is cleared when the sweep is dispatched, disabled, or
skipped for a locked wallet, so it cannot hold consolidation off once there is
no sweep to wait for. z_sweepstatus reports it as waiting_for_consolidation.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-29 10:48:26 -06:00
DanSandClaude Opus 5.5 66b74aa6aa wallet: give zsweep, consolidation and autoshield txs the normal expiry
The automated ops set nExpiryHeight to buildHeight + 15. The wallet only
rebroadcasts its unconfirmed transactions every 0-30 minutes (randomised, for
privacy), and only those a few minutes older than the last block, while each
transaction is relayed to a random half of the node's peers. A tx that missed
the miners on its first relay was therefore almost never retried before block
+15 (~9 minutes on mainnet), and expired. The op had already logged "Committed"
and, for zsweep, added it to amount_swept; the notes reappeared as unspent and
were swept again a round later. Nothing was lost, but z_sweepstatus overstated
progress, and manual z_sendmany calls from the deposit addresses kept colliding
with the re-sweeps ("bad-txns-shielded-requirements-not-met").

Measured on the 2026-11-29 stress fleet (exchange-style node with ~5 peer
connections): 38 of 184 sweep txs (21%) never confirmed; the log shows 1810
"ignoring expired tx" lines from the rebroadcast pass.

The three ops now use -txexpirydelta (default 200), the same window every other
wallet transaction gets, through AutoOpExpiryDelta(). Their NU-straddle guards
use the same window, so near a network upgrade they pause for the full expiry
window instead of 15 blocks. This applies to v1.2.0 too (its per-op
*_EXPIRY_DELTA constants were also 15); it is not a v1.3.0 regression.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-29 10:46:59 -06:00
DanSandClaude Opus 5.5 23159fcb25 stratum: honour the "x" worker name again
mining.authorize maps the worker name "x" to -stratumaddress, but it tested
CBitcoinAddress("x").ToString() == "x". "x" is not a valid address, so the
CBitcoinAddress holds no data and never prints as "x": the default address was
never used, and every "x" miner was refused with "Invalid DragonX address: x".
stratummine's default worker is "x", so the reference miner failed with "did not
receive complete RandomX work" unless it was given an explicit address.

Compare the worker name as sent (after stripping a ".rig" suffix) instead.

Found in the 2026-11-29 stress run: on a local RandomX chain with -stratumaddress
set, authorize "x" got the error above, while the same session authorized with the
address itself received set_randomx_key/set_target/notify and mined accepted shares.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-29 10:46:15 -06:00
DanSandClaude Opus 5.5 4538a8cd76 rpc: build getblocktemplate's block into a local before touching the cached template
getblocktemplate releases cs_main while CreateNewBlockWithKey runs, but it wrote the result
straight into the function-static pblocktemplate from inside that unlocked scope. A second
getblocktemplate call holding cs_main could then delete and NULL it (the "create new block"
branch frees the old template first) just before the first call took cs_main back, so the
first call threw "CreateNewBlock(): create block failed" for a block that had been built
fine, and templates overwritten this way were leaked.

The new block now goes into a local, and the cached template is freed and replaced only
after cs_main is held again. The old template also stays valid while the new one is built.

Seen once on the 3-VPS stress fleet (4 concurrent RPC hammer workers, one of them calling
getblocktemplate). Not reproduced locally: 720 calls (24 concurrent callers per forced
rebuild, 13 wide shielded txs in the mempool, background cs_main load) passed on both the
old and the new binary, so the fix rests on the code path above. The new binary showed no
regressions in that run.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-28 21:51:22 -06:00
DanS 0ac7812b11 Merge branch 'chore/remove-arrakis-wording' into dev 2026-11-28 17:23:59 -06:00
DanSandClaude Opus 5.5 5770f73b3d wallet/rpc: remove the unused Lock2NSPV/Unlock2NSPV
Neither has a caller anywhere in the tree. Both took cs_main and cs_wallet by hand, so any future
caller that threw between them would have leaked both locks. Remove them rather than keep a trap.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-26 22:26:29 -06:00
DanSandClaude Opus 5.5 8e34bcbba7 net: reset a peer's addrKnown under cs_addrKnown in the daily rebroadcast
SendMessages' 24-hour address rebroadcast cleared each peer's addrKnown under cs_vNodes only, while
the message handler inserts into and tests the same filter under cs_addrKnown
(AddAddressIfNotAlreadyKnown, IsAddressKnown): a data race on the bloom filter. Take
cs_addrKnown for the reset, as CloseSocketDisconnect already does. The order is unchanged:
cs_main (try-locked) -> cs_vNodes -> cs_addrKnown, as on the relay path.

Exercised on regtest with two nodes on a mock clock moved 25 hours at a time: the reset ran 4 times
(seen with a gdb breakpoint) with no fault.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-26 22:26:29 -06:00
DanSandClaude Opus 5.5 7d5893cd2a rpc: hold cs_main across gettxoutsetinfo's flush and scan
gettxoutsetinfo flushed the chainstate and then scanned it with no lock. GetStats reads the best
block and iterates a snapshot of the coins database separately, so a flush landing in between
reported the UTXO totals of a different block than the "height" and "bestblock" it returned. Hold
cs_main across both. The transparent UTXO set of a fully shielded chain is small, so the scan is
short (12 outputs on a 113-block regtest chain).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-26 22:26:29 -06:00
DanSandClaude Opus 5.5 bc36fa5a74 miner: take CreateNewBlock's locks with LOCK2 instead of by hand
CreateNewBlock entered cs_main and mempool.cs with ENTER_CRITICAL_SECTION and released them by
hand before each of its four returns. Anything that threw in between -- TestBlockValidity, the
notary payment, the coinbase setup, an allocation -- left both locks held by that thread for good:
for the RPC thread in getblocktemplate that wedges every later cs_main user, and for a miner thread
the same. The releases were also in the wrong order (cs_main before mempool.cs), which pops the
wrong DEBUG_LOCKORDER lock-stack entry.

Take them with LOCK2 for the block's scope, so every return and any exception releases both, in
reverse order, and drop the four hand-written release pairs.

The boost::this_thread::disable_interruption() before them constructed a temporary that was
destroyed on the same line, so it never disabled anything. It is removed rather than "fixed": with
scoped locks an interruption unwinds cleanly, and disabling it would only delay stopping a miner
thread.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-26 22:26:29 -06:00
DanSandClaude Opus 5.5 b9c5498bd2 docs: DragonX P2P port is 21768; fix sdl_checkpoints example
developer-notes.md and tor.md still gave 18030 (the HUSH3 port) as the
DragonX P2P port, contradicting the README. DragonX derives 21768 from
its chain parameters (hush_utils.h), as contrib/seeds shows. The tor.md
torrc example now maps 21768 to 127.0.0.1:21768, matching what
torcontrol.cpp's ADD_ONION uses (GetListenPort() for both).

sdl_checkpoints.pl: the "another chain" example now passes -ac_name,
since ./src/dragonx-cli is already the default.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 22:14:37 -06:00
DanSandClaude Opus 5.5 a2348515a2 Remove Hush Arrakis Chain (HAC) wording; delete dead launcher scripts
User-visible text:
- validateaddress help: "the given DragonX address" / "The DragonX
  address validated".
- getblockmerkletree help and error: "a given block height" / "Invalid
  block height parameter".
- ContextualCheckBlockHeader debug log: "HAC nbits" -> "nbits".

Comments and docs: HAC / Arrakis chain -> "smart chain" or "chain"
(src, contrib, util, doc/DEVELOPING.md, doc/randomx.md); the HAC and
Arrakis lines in doc/relnotes/README.md and contrib/debian/changelog
say "smart chain". Older "Hush Smart Chain" history is left as is.

Dead scripts removed: src/hush-arrakis-chain(.bat), src/smartchains and
src/sc/{koolaid,kush,zex}. They all start ./hushd, which the build no
longer produces, and none is in the release archive or the deb package.
The Dockerfile symlink to the launcher is dropped, and the rpc-test
framework defaults to src/dragonxd like util.py already does.

README: P2P port is 21768 (what the network and contrib/seeds use),
not 18030.

No identifiers, options (-ac_*), consensus code or licence headers are
changed. The miner.cpp change is a comment only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 22:14:37 -06:00
DanSandClaude Opus 5.5 433892e40b wallet/rpc: fix listtransactions with a large count, and read wallet data by reference in more RPCs
The parts of origin/perf/wallet-scan-rpc-costs that dev's note cache did not already cover:

- listtransactions computed count+from in an int, so a large count (e.g. INT_MAX, a common "all"
  idiom) wrapped and returned nothing. It is now clamped. Regtest: `listtransactions "*" 2147483647 1`
  returned 0 entries on the old binary and 150 of 151 here; a normal page is byte-identical.
- Fewer per-entry copies of wallet transactions in listtransactions and gettransaction, and reads by
  reference in other wallet RPCs.
- z_viewtransaction skips a spend whose parent transaction is no longer in the wallet (e.g. after
  -deletetx) instead of failing with map::at; that spend, and outputs only its key could recover,
  are then left out of the reply.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-20 20:10:01 -06:00
DanSandClaude Opus 5.5 93f8b3768b rpc: read the peer list under cs_vNodes in getinfo/getnetworkinfo; z_getoperationstatus without cs_main
From origin/perf/wallet-scan-rpc-costs, both still on dev:

- getinfo and getnetworkinfo read vNodes.size() and iterated vNodes without cs_vNodes, racing the
  network threads that add and remove peers (a reallocation mid-iteration is undefined behaviour).
  Both now count through one helper that takes the lock.
- z_getoperationstatus and z_listoperationids took cs_main and cs_wallet, though they only read the
  async queue (which has its own mutex) and each operation's status. GUIs poll them, so every poll
  contended with block validation. Regtest: z_getoperationstatus reports a running sweep normally.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-20 20:10:01 -06:00
DanSandClaude Opus 5.5 3537531901 rpc: cap HTTP request headers at 8 KiB, and keep getblocktemplate from aborting on an error
From the general audit, both still on dev:

- libevent's max_headers_size defaults to unlimited, and the request line and headers are buffered
  before the -rpcallowip check or authentication runs, so one connection could grow the node's memory
  with every byte it sent. Capped at 8 KiB. Regtest: a 9 KiB header and a 10 KiB request line now get
  400 (the old binary accepted the first and processed the second); normal calls are unaffected.
  qa/rpc-tests/httpbasics.py gains a request-line case.
- getblocktemplate left cs_main with LEAVE_CRITICAL_SECTION around CreateNewBlockWithKey. If that
  threw (a wallet or BDB fault), the enclosing scoped lock's destructor unlocked an already unlocked
  mutex while unwinding, which aborts the node with nothing logged. It now re-enters cs_main first,
  so the error reaches the caller. Regtest: getblocktemplate returns templates as before.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-20 20:10:01 -06:00
DanSandClaude Opus 5.5 179429ef7e rpc: honour importprivkey's height with a secret_key, and lock in three block RPCs
From the general audit, all still on dev:

- importprivkey used its height argument only when exactly 4 arguments were given, so supplying the
  optional 5th (secret_key) silently rescanned from genesis. Regtest under gdb: with
  `true 120 <prefix>` the old binary started ScanForWalletTransactions at height 0, this one at 120.
- getblockhashes: `if (fActiveOnly) LOCK(cs_main);` was unbraced, so the lock was released on the
  same line and, with noOrphans, GetTimestampIndex checked rows against chainActive unlocked. The
  lock now spans that call when noOrphans is set; without it the call only walks the LevelDB index
  and takes no lock, as before.
- getblockdeltas and getblockmerkletree read mapBlockIndex, chainActive and (getblockmerkletree)
  pcoinsTip's anchor cache, which inserts on a miss, with no lock; every sibling RPC locks.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-20 20:10:01 -06:00
DanSandClaude Opus 5.5 dbe154c2dc net: stop sending every ADDR message once per address, and filter PushAddress on the right address
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>
2026-11-20 19:51:15 -06:00
DanSandClaude Opus 5.5 2ff5c5d541 asyncrpc: make AsyncRPCOperation::cancel() virtual, so a running auto-op can be stopped
The base class said "Override this method if you can interrupt execution of main()", but cancel()
was not virtual. Every caller holds a std::shared_ptr<AsyncRPCOperation> -- the queue's map, the
wallet schedulers, z_consolidate -- so the overrides in the sweep, consolidation and autoshield ops,
written to move an EXECUTING operation to CANCELLED, never ran: the base version only cancels an
operation that has not started. In practice that meant a stop could not interrupt a running
automatic round; the node waited for it to finish every remaining transaction. Consolidation had
grown its own ShutdownRequested() checks as a workaround.

- cancel() is virtual, and the three overrides are marked override, so this cannot silently
  regress: with the base non-virtual again they fail to compile.
- Only the queue closing at shutdown can cancel a running round. The schedulers return early
  while a round is in flight (the sweep since its in-flight guard, consolidation and autoshield on
  their running flags) and z_consolidate refuses while a consolidation runs, so they only ever
  cancel an operation that has finished, which the overrides leave alone.
- A round cancelled part-way stays CANCELLED instead of being relabelled SUCCESS or FAILED by how
  much of it got done, and logs "(status=cancelled)".
- The sweep checks isCancelled() || ShutdownRequested() before starting each address as well as
  after each build, so a stop does not wait for another multi-second build to be discarded.
- Comments that described the old behaviour are corrected.

New gtest AsyncRPCCancel: each override is reached through a shared_ptr<AsyncRPCOperation> and
stops an EXECUTING op, leaves SUCCESS/FAILED alone and still cancels a READY one; an op without an
override still only cancels before it starts (z_sendmany and friends are unaffected). With the old
declarations, the three override tests fail. Regtest, same fixture, the node stopped while a sweep
round was building its first of four transactions: dev took 56.2 s to exit, building all four first;
this exits in 9-12 s ("Canceled. Stopping.", status=cancelled), and the wallet is intact on restart.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-20 19:05:53 -06:00
DanSandClaude Opus 5.5 b0e0d211d2 build: list libbitcoin_server again after libbitcoin_wallet when linking
libbitcoin_server and libbitcoin_wallet use each other: the server's init and RPC code calls into
the wallet, and the wallet's async operations derive from the server's AsyncRPCOperation. GNU ld
(Linux and mingw) scans each static archive once, in order, so dragonxd and hush-gtest only linked
because some server object happened to reference asyncrpcoperation.o directly and pull it in on the
first pass: AsyncRPCQueue called the non-virtual AsyncRPCOperation::cancel(). Making cancel()
virtual, as the next commit does, removes that reference, and dragonxd fails to link with undefined
AsyncRPCOperation members from libbitcoin_wallet.a.

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

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

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-20 19:04:51 -06:00
DanS 227cc7730b Merge branch 'fix/sweep-autoops-hardening' into dev 2026-11-20 16:45:35 -06:00
DanS 695050afe1 Merge branch 'fix/reject-unpayable-sapling-addr' into dev 2026-11-20 16:45:35 -06:00
DanSandClaude Opus 5.5 b61611d5c2 wallet: one unspendable note no longer stops the whole zsweep round
The sweep took the first maxInputs notes of an address and asked GetSaplingNoteWitnesses for their
witnesses. If one had none -- a missing witness, or a desynced one that does not match the anchor
the others agree on -- it logged "Missing Witnesses! Stopping.", built anyway with that note's value
still counted, failed the build, and broke out of the address loop. The round failed, every address
after that one went unswept, and the same thing happened again every interval. And because that
anchor is a majority vote, a desynced group that outnumbers the good notes at an address (as one did
on a real wallet) makes the "agreed" root one the chain never had.

SelectSweepableNotes now picks each transaction's notes. It copies each note's latest cached witness
under cs_wallet (GetSaplingNoteLatestWitness, which does no hashing), computes each root once with
no lock held, groups the notes by root, and takes the largest group whose root is an anchor the
chainstate knows -- the same lookup consensus applies to shielded spends. It reads the notes in
windows of 2 * maxInputs and stops as soon as a known group can fill the transaction, so a healthy
address costs about what the old first-maxInputs selection did (a Merkle root is ~1-2 ms, and an
earlier all-notes pass held cs_main for ~30 s on a 13k-note wallet), while a run of bad notes at the
front cannot hide good ones behind it. Notes left out are logged once per address with a count and
the first outpoint, and looked at again next round. In the round itself:

- an address with no spendable notes is skipped rather than failing the round;
- a failed build moves on to the next address (nothing was recorded); a failed commit still stops
  the round, because CommitTransaction has already written the tx to the wallet;
- a round counts as incomplete only once it has committed something, so an address whose notes are
  all unspendable no longer has the scheduler re-dispatch on every block -- it is retried an
  interval later.

New gtest SweepNoteSelection, 9 cases, including a desynced majority, a desynced run ahead of good
notes, a lone good note behind five desynced groups, two real anchors, and a healthy address being
read one window at a time. Accepting every root as an anchor fails 4 of them, and reading every note
fails the window test (200 notes took 244 ms against one window's worth). End to end on regtest,
with gdb making the wallet's first witness lookup find nothing: the other 4 notes at that address
and every other address were swept in the same round, the round succeeded, the next round swept
the skipped note, and the wallet drained fully, with no per-note desync lines in the log.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-20 16:07:39 -06:00
DanSandClaude Opus 5.5 ca07b8299f wallet: keep an interrupted -zapwallettxes / -rescan from hiding the unscanned range
-zapwallettxes erases every wallet transaction but leaves the best-block locator at the old tip.
The forced rescan that follows starts at genesis, and ScanForWalletTransactions only ever moves the
locator forward, so when that rescan was cut short -- killed, or a clean shutdown -- the next normal
start read the old locator, skipped the rescan, and the wallet came up without the erased
transactions: zero balance and no notes until someone ran -rescan. Plain -rescan had the same gap.

- Before a forced rescan that starts below the locator on disk, move the locator back to where the
  scan starts (RewindWalletLocatorForRescan). An interrupted scan then checkpoints forward from
  there, and a killed one restarts from there. With -zapwallettxes this is done right after the
  zap, so a startup that fails in between (a config error, say) cannot reopen the gap.
- SetBestChainWith no longer stamps the chain tip while the startup rescan is running or was cut
  short and init has not seeded the wallet tip yet. That stamp comes from FlushStateToDisk (its
  hourly write, or the one in Shutdown) and would overwrite the scan's own locator the same way.

Regtest, dev vs this branch on the same fixture (141 blocks, 26 notes, 146 txs, 430.0496418 DRGX),
stopping the node under gdb as the zap rescan begins and then starting it normally: dev comes up
empty (0 balance, 0 notes, 0 txs) after both SIGKILL and SIGTERM; this branch resumes the rescan
from block 0 and restores exactly the baseline. New gtest
WalletShutdownSave.DoesNotStampTheChainTipOverAnIncompleteStartupRescan.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-18 11:08:57 -06:00
DanSandClaude Opus 5.5 eec0d86dbf wallet: make z_sweepstatus report what the sweep actually does
Three z_sweepstatus fields read members nothing kept up to date:

- zsweepmaxinputs showed a member never set from -zsweepmaxinputs, so it always said 200 while
  the op used GetArg("-zsweepmaxinputs", 8). Parse and range-check the option once at startup into
  that member (5 to 100, default 8; same fallback as before) and have the op read it.
- zsweepfee showed a member never set from -zsweepfee. Report fSweepTxFee, which the op uses, and
  drop the dead member.
- amount_swept showed a counter nothing incremented (an int of puposhis, which would also have
  overflowed past ~21 DRGX). Count committed sweep transactions in a CAmount and report DRGX.

Add wallet_locked, so it is visible at a glance why nothing is being swept, and give the RPC a real
help text (it had a stray "}" and no Result section). Add the include guard that
asyncrpcoperation_sweep.h lacked, now that rpcwallet.cpp includes it too.

Release-notes item: amount_swept is now a decimal DRGX amount (it was an integer that was always 0).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-18 11:08:57 -06:00
DanSandClaude Opus 5.5 70dd6c6f8b wallet: stop zsweep reporting success on a locked wallet
On an encrypted wallet that is locked, the sweep op could get no spending key, skipped every
address without a word, and finished "Created 0 transactions ... status=1": a successful round that
swept nothing, every interval, with no hint anywhere. Every restart locks an encrypted wallet, so an
exchange that restarted its node to upgrade saw its deposit -> withdraw sweep simply stop.

- RunSaplingSweep skips the round while the wallet is locked, logs why, and looks again an interval
  later, as consolidation and autoshield already do.
- The op fails with RPC_WALLET_UNLOCK_NEEDED if the wallet is locked when it starts, and fails the
  round with that error if the wallet is locked part-way through (a walletpassphrase timeout).
- An address the wallet has only a viewing key for is now logged (zrpcunsafe) rather than skipped
  silently.

Regtest, dev vs this branch on the same encrypted fixture: dev logs "Created 0 transactions ...
status=success" while locked; this logs "wallet locked; not sweeping ... Unlock it with
walletpassphrase", and locking mid-round ends it "status=failed, error=Wallet was locked during
the sweep ...". After unlocking, both sweep everything.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-18 11:08:57 -06:00
DanSandClaude Opus 5.5 2e78769817 wallet: let an in-flight zsweep round finish, and build each tx at the current tip
RunSaplingSweep re-dispatched a sweep on every block while a round was still running. That never
stopped the running op -- AsyncRPCOperation::cancel() is not virtual, so through the queue's base
pointer it only cancels an op that has not started, and the sweep's own cancel() override is never
reached -- it just queued a fresh round behind it, which then repeated note selection over the
whole wallet and was itself superseded a block later. Leave an in-flight op alone, as
RunSaplingConsolidation already does, and log that it is still running and since which height.

A round can outlive the block it started at (a busy deposit wallet takes seconds per sweep
transaction), but since v1.3.0 every transaction in a round was built and expired against the tip
read once when the round began, so late transactions in a long round could be expiring, or already
expired, by the time they were committed. Read the tip for each transaction, and re-check the
NU-straddle guard there.

Regtest, same fixture as dev (3 deposit addresses x 7 notes, -zsweepmaxinputs=5, a block every
~3 s while each build takes ~7 s): the same 7 sweep transactions and amount as dev, with "still
running; not re-dispatching" where dev queued a redundant round on every block.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-18 11:08:57 -06:00
DanSandClaude Opus 5.5 c59b445ac1 zaddr: reject Sapling addresses that cannot receive funds
DecodePaymentAddress accepted any 43 bytes with a valid bech32 checksum.
An address whose diversifier has no valid g_d, or whose pk_d is not a
point in Jubjub's prime-order subgroup, can never receive a note, yet
z_validateaddress reported it as valid and z_sendmany queued the send.
The async operation then failed in TransactionBuilder::Build
("Invalid sapling note commitment!", surfaced as "Failed to build
transaction.") and took every other recipient in the batch with it.
A mining pool's payouts stalled for 10.5 hours on one such miner
address.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-28 17:05:03 -05:00
DanSandClaude Opus 5.5 c0b99a0e1f wallet: test what the shutdown save records and a reseed that succeeds
The tests of the shutdown save covered the skip reasons and
ClearNoteWitnessCache only, and the witness-root tests compared the new
code with itself at 1 and at N threads, with every reseed throwing for
want of block files. A stale root table, or a lost change bump, would
have passed all of them.

SetBestChain's work on an open database moves into a template,
SetBestChainWith, so a fake database can fail each step of the
transaction; SetBestChain itself only opens the database and calls it.
The new tests check:
- a write that fails at any step (begin, a tx, the cache size, the best
  block, the commit) records nothing; a committed one records the wallet
  tip, which is what is stamped, not the chain tip passed in; without a
  wallet tip, the block the locator names;
- DecrementNoteWitnesses, and adding or changing a note-bearing tx, make
  the next shutdown save again; re-adding a tx unchanged or adding one
  without notes does not (AddToWallet on an in-memory BDB environment);
- the save writes the best block through the real wallet database, and
  each skip path writes nothing to it;
- a reseed that reads its block from disk and succeeds: the loop goes
  on, a sibling note in the same tx that had no nullifier gets one from
  that reseed and is checked with an inline root, every note ends as the
  serial rules say at 1 and at 8 threads, and the reseed counts as a
  change to save.

Each assertion was checked by breaking the code it covers (the inline
root fallback, each bump site, recording on failure, the rescan gate):
every such change fails at least one test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 13:10:41 -05:00
DanSandClaude Opus 5.5 5d5b47d05a wallet/rpc: z_consolidate is not safe-mode; say which units it uses
z_consolidate creates and broadcasts transactions, so like z_sendmany
and z_shieldcoinbase it must not run in safe mode. Its fee argument is
in DRGX, like z_sendmany's, while -consolidationtxfee and every amount
in z_consolidationstatus are in puposhis; the help and the doc now say
so.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 12:59:46 -05:00
DanSandClaude Opus 5.5 25c79b7512 wallet: keep consolidation to the sweep address, warn on bad config off
With -zsweep=1 and -consolidation=0, z_consolidate consolidated every
address: the sweep-address substitution sat under
fSaplingConsolidationEnabled, and an explicit address list skipped the
sweep-address rule. Sweep and consolidation then fight over the same
notes and pay fees for nothing. Apply the rule whatever -consolidation
is, and have z_consolidate refuse any address but the sweep address
while zsweep is on.

The branch also started checking -consolidatesaplingaddress with
-consolidation=0, so an old config with a stale, watch-only or mistyped
address, which used to be ignored, stopped startup. Keep the InitError
with -consolidation=1; with it off, warn and drop the address (with
zsweep on, use the sweep address instead).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 12:57:58 -05:00
DanSandClaude Opus 5.5 27a2f04189 wallet: spend consolidation notes only at a chain anchor
The round took its anchor from GetSaplingNoteWitnesses, a majority vote
over the planned notes alone that never looks at the chain. A real
wallet has had 108 notes desynced onto one root the chain never had, at
the same address as 104 healthy ones. Smallest-first planning can pick
a batch that is mostly desynced notes. The vote then made the healthy
notes the "unusable" ones, and the tx was proved at a non-anchor: Build
succeeds, since witnesses and anchor agree, but CommitTransaction adds
it to the wallet before the mempool refuses it. Its notes then look
spent, and since the plan is nearly deterministic this recurs every
round. One failed tx also ended the round for every other address.

PlanSaplingConsolidationSpends now plans over the notes that can be
spent together. A planned note is used only if its newest witness root
is a Sapling anchor the chain holds (GetSaplingAnchorAt on pcoinsTip,
the check consensus makes) and is its address's anchor: the tip's root
if any planned note is there, else the chain anchor most share. Other
planned notes are left out and the round is re-planned until none are.
The planner is pure apart from its callbacks and is tested, including
a desynced majority. GetSaplingNoteLatestWitness is pass 1 of
GetSaplingNoteWitnesses, split out; that function is unchanged.

A tx that fails to build or commit now only skips the rest of its own
address's txs; the first failure is the round's error.

Skipped notes are logged once per round with a count and the first
five outpoints, instead of once per process: a note that is unusable
only during a witness rebuild was otherwise never reported again.

The fee rule moves into SaplingConsolidationTxFee, with a test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 12:54:55 -05:00