Commit Graph

32128 Commits

Author SHA1 Message Date
ac95106abe build(win): make the mingw cross-compile link and find librustzcash
Three things broke the x86_64-w64-mingw32 build; two are real and fixed
here (the third was a stale-object contamination from building Linux and
Windows in the same tree, resolved by a clean rebuild — not a code fix).

1. Single-pass mingw ld could not resolve the cross-references DragonX
   added between the internal static archives (libbitcoin_util/common
   objects pulling in UniValue; util<->common mutual deps). GNU ld on
   Linux re-scans archives so it never surfaced; ld64 on macOS rejects
   the grouping flag outright. Bracket each binary's _LDADD in
   -Wl,--start-group/--end-group, delivered via AC_SUBST(LINK_GROUP_*)
   so automake does not reject the linker flag inside _LDADD, and left
   empty on every non-Windows target.

2. The Rust build emits the mingw archive as rustzcash.lib, but the
   link line asks for -lrustzcash, i.e. librustzcash.a. Normalize the
   staged filename to librustzcash.a for every host (a no-op on
   Linux/macOS, where the basename was already librustzcash.a).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-27 03:56:23 -05:00
02b4d03fc6 wallet: low-severity polish from the dev/v1.2.0 review
Follow-up nits surfaced by the multi-agent review of the dragonx..dev delta;
none are correctness/consensus bugs, all are defensive/consistency tidy-ups.
Builds clean; the diff was reviewed across concurrency, scheduler, and
tx-building lenses.

- wallet: default CWallet::fAutoShieldEnabled to false. init.cpp always
  recomputes it (ON only for CREATED/RESTORED seed provenance) before any
  ChainTip round, so this is behaviour-neutral in the normal path and stops a
  CWallet that skips that init from auto-enabling for provenance the gate would
  reject.

- wallet: clamp a loaded hdSeedOrigin to UNKNOWN when out of enum range, so a
  corrupt/hand-edited wallet.dat cannot claim a known-recoverable seed and flip
  autoshield ON.

- wallet: key the sweep and consolidation ops' NU-straddle guard, transaction
  builder height, and expiry off execution-time tipHeight instead of the stale
  enqueue-time targetHeight_ -- matching the autoshield op (65130c312) so the
  builder's consensus-branch selection agrees with the height the tx is signed
  for. (Sweep previously built at targetHeight_ but expired at the live tip.)

- wallet: on the sweep NU-straddle skip, set sweepComplete_ so the round backs
  nextSweep off one interval instead of re-dispatching a fresh sweep op every
  block through the activation window.

- init: clamp -autoshieldinterval below 5 up to the documented minimum of 5,
  rather than silently resetting it to the default 25.

- chainparams: make the ClearSeeds guard an exact "DRAGONX" match instead of a
  7-char prefix, so DRAGONX-prefixed assetchains (e.g. DRAGONX2) no longer
  inherit DragonX's seeds.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UtvyqQQSqR64DNEjUEuTmb
2026-08-26 22:10:35 -05:00
fad05d3ab4 doc: regenerate manpages for v1.2.0
They still described v1.0.3-4caf2fc68, so none of the options added
since -- -autoshield and its four companions, -mnemonic,
-mnemonicsaplinggap -- appeared anywhere in them.

Generated from a binary built at a clean tree on an annotated v1.2.0
tag, which is what makes util/genbuild.sh emit BUILD_DESC "v1.2.0"
rather than a version with a commit suffix. Note that genbuild.sh uses
`git describe --abbrev=0`, which ignores lightweight tags; v1.0.0
through v1.0.3 were lightweight, which is why those releases all
reported themselves as v1.0.x-<sha>. Tag releases annotated.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FU87LdsJZiZkfq1eXubpeo
v1.2.0
2026-08-25 18:42:18 -05:00
5d3f7e520c packaging: correct the debian changelog and the manpage file list
- dragonx.manpages listed DEBIAN/manpages/*.1, a path nothing creates,
  so dh_installman would fail on it. Point it at doc/man/*.1, which is
  where util/gen-manpages.sh writes and what doc/man/Makefile.am ships.
- Restore the 1.0.1 and 1.0.2 stanzas, reconstructed from the commits
  each tag actually contains. The file jumped 1.0.3 -> 1.0.0.
- The 1.1.0 and 1.0.0 trailers named weekdays that do not match their
  dates ("Thu, 21 Aug 2026" is a Friday; "Mon, 03 Mar 2026" is a
  Tuesday). Replace both with the real v1.1.0 and v1.0.0 tag dates,
  which fixes the weekday and the disagreement with the tag at once.
- Record the 1.2.0 peer-discovery work in its stanza.
- Drop doc/man/hushd.html and doc/man/hush-cli.html: stale Hush-branded
  pages for binaries this tree no longer builds, referenced by nothing.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FU87LdsJZiZkfq1eXubpeo
2026-08-25 18:36:03 -05:00
092a608fd9 chainparams: do not let other smart chains inherit DragonX's seeds
A smart chain builds its params by copying a base network and
overriding pieces, but nothing ever touched vSeeds/vFixedSeeds. That is
how DRAGONX ran on Hush's seeds -- seed1.hush.is and friends, long
since gone from DNS -- for as long as it did, and it means any other
assetchain started from this binary now inherits DragonX's.

Seeds are per-chain by nature: an address serving one chain is useless
to another, and dialling it is at best wasted effort and at worst a
peer speaking a different protocol. DRAGONX keeps the seeds configured
in CMainParams, which are its own; every other chain starts empty and
relies on -addnode/-connect, which an assetchain operator has to
configure regardless.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FU87LdsJZiZkfq1eXubpeo
2026-08-25 18:36:03 -05:00
3dd667b127 net: add two seed nodes and reserve names for three more
node6.dragonx.is (13.140.58.251) and node7.dragonx.is (5.104.83.100)
are new full nodes in regions the existing five did not cover. Both go
into the compiled-in fixed-seed list and into the DRAGONX -addnode set.

node8 through node10 are reserved names with no DNS records yet. A
hostname that does not resolve is harmless on this path --
ThreadOpenAddedConnections simply fails to open the connection and
retries on its normal cycle -- and reserving the names in the binary
means a future seed can be brought into the default addnode set by
creating a single DNS record, with no release and no waiting for users
to upgrade. seed.dragonx.is already gives the DNS-seed path that
property; this extends it to the addnode path.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FU87LdsJZiZkfq1eXubpeo
2026-08-25 18:36:03 -05:00
dde6cd810f net: seed from a round-robin DNS record instead of hardcoded hosts
seed.dragonx.is is now an A-record set over the five seed nodes (DNS-only, TTL 300,
created in Cloudflare alongside this change). One lookup returns all of them, and
the set can change -- a node added, a node retired -- with a DNS edit rather than a
release.

That is the actual point. Before this the network's entry points were hardcoded
into the binary twice over: here in vSeeds, and again in the -addnode injection in
hush_utils.h. Adding a sixth node meant shipping a new version and waiting for
users to upgrade.

node1 and node5 stay as static fallbacks against the round-robin record being
mistyped or deleted. They resolve to the same hosts, so that is insurance against a
DNS mistake rather than real redundancy.

Verified end to end on a fresh datadir (empty addrman, real node untouched, and
crucially with NO custom -port -- see below):

  before:  0 addresses found from DNS seeds, 0 handshakes, 1 block (genesis)
  after:   7 addresses found, connection attempts to all five seeds on :21768,
           3 version handshakes, 3296 blocks connected and syncing

The earlier run of this test appeared to fail with 0 handshakes. That was the
harness, not the code: -port overrides ASSETCHAINS_P2PPORT, and net.cpp builds
DNS-seeded addresses as CAddress(CService(ip, ASSETCHAINS_P2PPORT)), so a test node
with a custom port dials every seeded peer on its own port and reaches nothing.
That is the mechanism behind the long-standing "never use a custom -port on a test
node" rule; use -listen=0 instead.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-26 00:22:56 +02:00
499f02a905 net: repair DragonX peer discovery, broken three separate ways
A DRAGONX node had no working peer discovery. Both mechanisms were broken, and a
third bug hid the fact.

1. DNS seeds were Hush's, and all three are dead. chainparams_commandline() sets an
   assetchain's port, magic, blocktime, upgrade heights and checkpoints but never
   touches vSeeds or vFixedSeeds, so DRAGONX silently inherited CMainParams':
   seed1.hush.is, seed2.hush.is and dns.leto.net. None of the three has an A record
   any more -- verified against 1.1.1.1 and 8.8.8.8, with google.com and
   node1..node5.dragonx.is resolving fine from the same host as a control. Replaced
   with the five DragonX node hostnames, which do resolve and do listen.

2. Every fixed seed carried port 0. contrib/seeds/generate-seeds.py documents its
   input as <ip>:<port>, but contrib/seeds/nodes_main.txt held bare IPs, so
   parse_spec() took the port as empty and emitted 0x00,0x00 for all five entries.
   The fixed-seed fallback -- which exists precisely for when DNS seeding yields
   nothing -- was therefore handing out unconnectable addresses. Added the port to
   nodes_main.txt and regenerated; entries now end 0x55,0x08 (21768).

3. ThreadDNSAddressSeed never incremented `found`, so "%d addresses found from DNS
   seeds" printed 0 unconditionally, whether seeding worked or not. That is almost
   certainly why nobody noticed the seeds had gone dead: the one diagnostic that
   would have shown it was hardcoded to say zero.

Verified on a fresh datadir (empty addrman, separate ports, real node untouched):
DNS seeding now reports "5 addresses found from DNS seeds" where it previously
reported 0, and the fixed-seed path adds 5 entries carrying the correct port.

Note on scope: the five hostnames are single-A-record hosts, so each contributes one
address rather than the spread a real seeder returns. A dedicated DNS seeder, or
simply a round-robin A record over the seed set, would be the proper fix and needs
only a DNS change rather than a release. This restores a working discovery path;
it does not make it a good one.

Also corrected the generated header's #endif comment, which said
HUSH_CHAINPARAMSSEEDS_H while the guard is DRAGONX_CHAINPARAMSSEEDS_H.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-26 00:11:55 +02:00
4dc57e80b1 build: bump version to 1.2.0
dev and the v1.1.0 tag were version-indistinguishable: both reported
CLIENT_VERSION 1010050, subversion "/DragonX:1.1.0/" and IS_RELEASE=true, because
660678f9b was the last commit to touch a version file and it predates the tag. The
twenty commits since were therefore invisible to every channel a client can query,
and the in-app updater compares exactly those. Only git-describe distinguished
them, and that degrades to "-unk" on a tarball build.

A minor bump rather than a patch: since v1.1.0 the tree gained auto-shield-coinbase
(a new feature, on by default where the seed is known-recoverable), BIP39 seed
phrases as the default for new wallets, the z_autoshieldstatus RPC, and three new
wallet.dat record types. Understating that as 1.1.1 would hide an on-disk format
change from the one place users look.

The published v1.1.0 tag is left where it is. Re-pointing a tag that is already on
the remote breaks anyone who fetched it.

The wallet feature version deliberately stays at FEATURE_LATEST = 60000. The new
records are additive and older binaries skip unknown types harmlessly, while
bumping it would make them refuse the wallet outright with DB_TOO_NEW. The one real
incompatibility, a truncated hdchain record, is self-healing as of a0ccb4be1, so
refusing to load would be strictly worse for the user than what happens today.

Verified: configure.ac and clientversion.h agree; CLIENT_VERSION 1010050 -> 1020050;
build.sh derives 1.2.0; bitcoin-config.h carries CLIENT_VERSION_MINOR 2 after a
reconfigure run with the depends CONFIG_SITE; a full rebuild of src succeeds with 0
errors and both binaries report v1.2.0.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-25 21:52:51 +02:00
04ac7c1186 doc: how to build release binaries in containers, for several glibc floors
Binaries built on Ubuntu 22.04 require GLIBC_2.34 and GLIBCXX_3.4.30 and will not
start on Ubuntu 20.04 -- which is four of our five seeds, and an unknown share of
users. The binary the fleet actually runs today needs only GLIBC_2.29, so it was
built somewhere older; seed 176 has since been upgraded to 22.04 and now produces
binaries it is the only seed able to run.

--linux-compat and Dockerfile.compat already solved this (6d56ad854) but were
undocumented outside the build script and pinned to one base image. Parameterise
the base via ARG BASE_IMAGE (default unchanged, so --linux-compat behaves exactly
as before) and document the whole path.

doc/build-containers.md is written to be executed by a person or an agent starting
from a machine with nothing installed: why the glibc direction matters, with the
measured numbers; what already exists in the repo so nobody writes a second build
system; prerequisites and honest cost (~15GB, 4GB RAM, 1-2h per base because
depends/ builds boost, BDB, wolfssl and rust from source); one-target and
multi-target recipes; which base to pick and why 20.04 is the recommended floor
while 18.04 needs verifying (GCC 7 against -std=c++17); a mandatory verification
step with the exact objdump/readelf commands and the expected ceilings; and the
traps.

The traps are the part worth having written down: ETXTBSY when installing over a
running daemon (cp fails even after the process exits -- stage and rename, then
sha256-verify before starting); never touching configure.ac in a configured tree,
because the mtime alone triggers a reconfigure that dies on libdb_cxx; never
blind-touching a path that may not exist, which silently creates stray empty files;
RandomX needing ARCH=default or it emits AVX-512 that SIGILLs the fleet; build-win.sh
silently discarding every argument; and macOS being uncontainerisable because
depends/ has no darwin cross path at all.

Also records that full static linking is NOT the answer here: the daemon resolves
node1..node5.dragonx.is via getaddrinfo, and static glibc pushes that through NSS,
which dlopens libnss_dns at runtime and reintroduces the dependency it was meant to
remove.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-25 21:28:12 +02:00
65130c3120 async/wallet: close the loose ends around automated operations
Six small defects, all found by an audit of the automated-operation path and all
verified present before changing anything.

AsyncRPCQueue::addOperation returned void and silently dropped the operation when
the queue was closed or finishing. Every caller assumed success: the three
schedulers left their running flag set with nothing in flight (which then blocks
every later round), and z_sendmany / z_shieldcoinbase / z_mergetoaddress returned
an opid for work that would never run -- z_shieldcoinbase and z_mergetoaddress
having already locked their selected coins in the constructor. It now returns
bool; the schedulers release the flag and log, and the three RPCs raise an error
instead of handing back an opid. Coin locks are memory-only, so a refusal at
shutdown reclaims them with the process; the lie about success was the defect.

Nothing ever removed finished automated operations from the queue's map.
popOperationForId is reached only from z_getoperationresult, so on a node running
autoshield every 25 blocks the map grew by one entry per round forever. The
schedulers now pop the operation they just cancelled. The worker already handles
a missing id ("cannot find operation in map, may have been removed",
asyncrpcqueue.cpp), and it releases lock_ before calling main(), so popping under
cs_wallet introduces no lock cycle.

The autoshield operation built its transaction against targetHeight_, the
enqueue-time height, while SetExpiryHeight and the network-upgrade straddle guard
both used tipHeight. Since the builder's height selects the consensus branch id,
the guard was checking a height the transaction was not signed against -- it could
not prevent the failure it exists to prevent. Now tipHeight throughout.

cancel() in the sweep, consolidation and autoshield operations set CANCELLED
unconditionally, dropping the base class's guard entirely. The schedulers cancel
the previous operation when they enqueue the next, so a round that had already
SUCCEEDED got its result relabelled as cancelled. Restored a narrower guard: still
cancellable while READY or EXECUTING (the base class refuses the latter, which
would defeat cancellation here), but a terminal state is left alone.

CommitAutomatedTx dumped the whole transaction to stderr on every commit,
duplicating the LogPrintf that CommitTransaction does one call later. ToString()
emits a line per input, so with the 400-input autoshield cap that was tens of KB
of stderr per round. Removed.

Also corrected a comment that credited the immature-coinbase exclusion to
fOnlySpendable (the argument is fOnlyConfirmed; the exclusion is unconditional in
AvailableCoins), and noted that AUTOSHIELD_CTXIN_P2SH_SIZE is a byte size that
merely happens to share the value 400 with the input cap.

Verified on an isolated regtest chain, 8/8: nine consecutive autoshield rounds
succeed after the builder-height change; the operation map stays at 1 entry across
all nine (it grew one per round before); stderr totals 1608 bytes for the whole
run with zero CommitAutomatedTx dumps, while debug.log still records all nine
commits via CommitTransaction; no round is relabelled cancelled; funds shield
correctly and no coin locks leak.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-25 19:18:30 +02:00
698bcf9574 build: derive the release version from configure.ac
build.sh hardcoded VERSION="1.0.3" while configure.ac had been at 1.1.0 since
660678f9b. package_release() uses it to name the output directory, so
`./build.sh --all-release` from dev would have emitted
release/dragonx-1.0.3-<platform>/ containing binaries that report 1.1.0 --
mislabelled artifacts, from the one place where the label is what users see.

Read the four _CLIENT_VERSION_* defines out of configure.ac instead, applying the
same suffix rule its _CLIENT_VERSION_SUFFIX m4 uses (build < 25 -> beta, < 50 ->
rc, == 50 -> plain, > 50 -> point release), and abort if any of them cannot be
parsed rather than naming a release directory after an empty string.

SCRIPT_DIR moves above the version block because the lookup needs it.

Verified: derives 1.1.0 from the current tree, and a deliberately unparseable
configure.ac makes it exit 1 with a message instead of guessing.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-25 18:56:18 +02:00
a0ccb4be1d wallet: repair a truncated hdchain record instead of refusing the wallet
A build predating VERSION_HD_TRANSPARENT rewrites the hdchain record with only
its four base fields while leaving nVersion at whatever it read. Our version-gated
reads then run off the end of the stream, ReadKeyValue turns the throw into
fHDChainRead=false, and LoadWallet escalates that to DB_CORRUPT. Verified against
the real v1.0.2-2b011d6ee release binary: a dev wallet, opened once by v1.0.2 and
given a single new sapling address, came back to

  Error reading wallet database: hdchain record is corrupt
  Error loading wallet.dat: HD seed present but the hdchain record is missing or corrupt
  Error loading wallet.dat: Wallet corrupted

Nothing is actually lost there -- the same test showed the seed phrase restoring
the full balance, the autoshield destination, and even the address v1.0.2 had
generated -- but the user is shown "Wallet corrupted" with no hint of that.

Recover instead, for a v1 or v2 record. Everything derivation depends on is either
in the four-field prefix or in the separate hdseed record, and the trailing
counters are self-healing: DeriveNewChildKey and GenerateNewSaplingZKey both skip
indices whose key the wallet already holds, so restarting a counter at 0 re-walks
past existing keys rather than reissuing them. Read the prefix from an untouched
copy of the stream, default the missing tail, log it, and rewrite the record in
full form so the next load is clean.

A record claiming nVersion >= VERSION_HD_MNEMONIC still fails loud: that flag
selects the derivation input, so guessing it wrong yields a different key tree in
silence. No wallet this code has written can be in that state -- every
InstallHDSeed call site passes fMnemonic=false -- so the branch is defensive only.

Also say what to do about it. Both the log line and the init error now name the
remedy (move wallet.dat aside, restart with -mnemonic and -rescan) rather than
stopping at "Wallet corrupted".

Verified on regtest against the real v1.0.2 binary, 14/14: the round-trip that
previously ended in "Wallet corrupted" now loads, logs the repair and the rewrite,
keeps the balance, the autoshield destination and v1.0.2's own address, still
issues distinct fresh t-addresses after the counter reset, needs no repair on the
second load, and remains fully recoverable from the seed phrase.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-25 18:18:38 +02:00
358011bd54 wallet: resolve the autoshield destination at startup
pwalletMain->autoShieldAddress was only ever written by a round running in the
current process, so on any node without an explicit -autoshieldaddress,
z_autoshieldstatus reported an empty destination from startup until the first
round fired. disabled_reason was empty on that path too (rpcwallet.cpp), so the
RPC showed autoshield true, running false, no address and no explanation -- the
exact silent state z_autoshieldstatus was added to eliminate. On a restored
wallet, which pre-derives the whole -mnemonicsaplinggap window and therefore
always has an in-gap account to pick, the answer was known at startup and simply
not computed.

Split the read-only half of resolveDestination into a free function shared with
init: the configured override if set, else the lowest in-gap account
m/32'/coin'/i' the wallet already holds. init calls it once when autoshield is
enabled and no explicit address was given.

It deliberately does not generate a key. Deriving a fresh sapling account as a
side effect of populating a status field would mutate the wallet to make an RPC
prettier, so step 3 of resolveDestination -- the generation path, which must stay
inside the operation where an unlocked wallet is already established -- is left
where it was. A brand-new wallet holds nothing in-gap, so the field stays empty
there and disabled_reason now says why instead of being blank.

Behaviour is otherwise unchanged: same derivation, same lowest-index-wins rule,
same refusal to trust CKeyMetadata, same caching for the life of the process.

Verified on an isolated regtest chain, 12/12:
  fresh wallet      -> address "", reason "no destination resolved yet; one will
                       be derived from the HD seed on the first round"
  after one round   -> address set, reason empty
  after RESTART     -> address visible with NO block mined since (height 12 both
                       sides), and z_listaddresses still holds exactly 1 address,
                       so init derived nothing
  -autoshieldaddress-> still overrides the derived destination, and the round
                       shields into it

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-25 17:41:32 +02:00
7a62fc4877 wallet: break the sweep/consolidation/autoshield deadlock
A successful-but-incomplete sweep round deliberately returns with fSweepRunning
still set and nextSweep unadvanced, as a "keep draining next block" baton. Every
early return in RunSaplingSweep, though, leaves that baton set without
re-dispatching -- and RunSaplingConsolidation, which is gated on fSweepRunning,
then returns without advancing nextConsolidation. So the "consolidation is
within 5 blocks" blackout at the top of RunSaplingSweep never lifts: sweep waits
on consolidation, consolidation waits on sweep, and neither runs again.

That much is pre-existing. What is new is that autoshield now shares the gate --
RunAutoShieldCoinbase returns early on fSweepRunning || fConsolidationRunning --
so a wedged sweep silently disables coinbase shielding too, with
z_autoshieldstatus reporting autoshield true, running false, and no reason.

Only honour the baton while a sweep operation is genuinely in flight: if the
operation for saplingSweepOperationId is absent or has reached a terminal state,
drop the stale flag and let the checks below decide afresh. The drain model is
unchanged -- nextSweep is still unadvanced, so the next block re-dispatches.

Also report the deferral in z_autoshieldstatus, so mutual exclusion with sweep
or consolidation reads as a deferral rather than an unexplained idle.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-25 07:59:13 +02:00
9a8f17b2c8 wallet: bound autoshield rounds and lock their inputs
Two defects in a single autoshield round, both of the quiet kind.

The size estimate reserved a flat 2000 bytes for "header + sietch outputs", but
every autoshield tx carries three Sapling OutputDescriptions -- the change note
plus the two Sietch dummies -- and the real fixed cost is ~2937 bytes. Measured
across seven live mainnet coinbase shields: 113.5 bytes per input and 2936.6
+/- 0.8 bytes fixed, of which 3 * 948 = 2844 is the output descriptions. The
estimate was therefore short by ~937 bytes before a single input was counted.

Inputs are charged AUTOSHIELD_CTXIN_DUST_SIZE = 148, which is conservative for
the default P2PK coinbase but exact for P2PKH, so with a P2PKH coinbase a
backlog of 1332..1337 utxos passed the estimate and built a tx over
MAX_TX_SIZE_AFTER_SAPLING. CommitTransaction calls AddToWallet before
AcceptToMemoryPool, so a rejected oversize tx leaves its inputs reading as spent.

z_shieldcoinbase caps a manual shield at SHIELD_COINBASE_DEFAULT_LIMIT = 50
utxos; autoshield dropped that cap and relied on the byte estimate alone.
Restore one -- AUTOSHIELD_MAX_INPUTS = 400 -- so the byte arithmetic is no longer
the only thing between a large backlog and an oversize transaction. The
remainder is shielded on the next round.

Second, the proof build deliberately runs without cs_wallet so wallet RPCs are
not stalled, which leaves a multi-second window in which a concurrent
z_shieldcoinbase or z_sendmany can re-select the same coinbase outputs.
AvailableCoins already honours IsLockedCoin and z_shieldcoinbase already
brackets its selection with LockCoin/UnlockCoin; autoshield made zero LockCoin
calls. Take the locks under cs_wallet at selection time and release them via
RAII, since several early returns sit between selection and commit and a leaked
lock would exclude those coins from every future round.

Verified on an isolated regtest chain with a 540-utxo backlog:
  round 1 logged "reached per-round input cap (400)" and committed exactly 400
    inputs in a 48351-byte tx (estimate 62300, limit 200000)
  round 2 took the remaining 151; backlog drained 540 -> 0
  listlockunspent showed 400 coins locked mid-round and 0 afterwards
  48351 bytes for 400 inputs implies 2937 bytes of fixed overhead, agreeing
    with the mainnet measurement to 14 bytes

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-25 07:59:13 +02:00
1ec6590fb7 wallet: add z_autoshieldstatus
Auto-shielding could silently decline to run with no way to ask why. The
destination it resolves was equally invisible: the only evidence was a LogPrintf
emitted once per round, so an operator wanting to know where their mined coinbase
was going had to grep debug.log.

z_autoshieldstatus reports the enable state, whether a round is in flight, the
next height, interval, fee, minimum utxos, and the resolved destination -- plus
the HD seed provenance in both numeric and readable form, whether the seed is
phrase-recoverable, and a disabled_reason explaining why it is off when it is.

That last field is the point. "autoshield": false on its own does not distinguish
an operator who passed -autoshield=0 from a wallet whose seed provenance is not
known-recoverable, and those need different responses.

Mirrors z_sweepstatus in shape and registration.

Verified on all three branches:
  fresh wallet    -> autoshield true, origin 1 "created on an empty wallet",
                     seed_recoverable true, disabled_reason ""
  -autoshield=0   -> disabled_reason "disabled by -autoshield=0"
  upgraded wallet -> autoshield false, origin 4 "predates provenance recording",
                     seed_recoverable false, disabled_reason "HD seed origin is
                     not known-recoverable; back the seed up and pass -autoshield=1"

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-25 06:04:43 +02:00
92e6c7008d wallet: define CHDChain's static constants out of line
hush-gtest failed to link with "undefined reference to
CHDChain::VERSION_HD_MNEMONIC". The version constants are static const int with
in-class initialisers and no definition anywhere, so any ODR use needs one --
and gtest's EXPECT_*/ASSERT_* macros take their arguments by const reference,
which is exactly that. test_mnemonic_compat.cpp:161 passes VERSION_HD_MNEMONIC
to EXPECT_LT.

dragonxd links either way, because nothing in the daemon binds these to a
reference; only the test target exposed it, and the test target was never built
on the branch that introduced the test.

Define all four rather than only the one that failed: VERSION_HD_BASE,
VERSION_HD_TRANSPARENT and CURRENT_VERSION carry the identical latent fault, and
the next EXPECT_EQ against any of them would hit the same wall. Fixing the test
instead would have hidden the problem rather than removed it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-23 18:58:24 +02:00
733df964ec Merge autoshield-safety into dev: auto-shield coinbase + BIP39 by default
Brings the auto-shield-coinbase feature and the wallet seed work onto the release
line so both are exercised from dev rather than a side branch.

From upstream: auto-shield of matured coinbase into a wallet z-address, plus
fixes to two pre-existing scheduler wedges (consolidation dispatching every block
instead of once per interval, and a failing sweep stranding its running flag).

On top of that:
  * the auto-shield destination is chosen by re-deriving m/32'/coin'/i' from the
    seed and taking the lowest in-gap account the wallet holds a key for, rather
    than the first entry in std::set order. Key metadata is NOT evidence of
    provenance -- z_importwallet copies hdKeypath and seedFp verbatim from the
    import file -- so a crafted import could otherwise claim account 0 and
    capture every shielded reward;
  * HD seed/chain persistence is hardened: the chain record is written before the
    seed, a corrupt hdchain is loud rather than silently reverting derivation to
    the raw entropy, hdchain survives -salvagewallet, and the silent BIP39 ->
    random seed fallback is gone;
  * seed provenance is recorded, and -autoshield defaults ON only where that
    provenance says the seed is recoverable;
  * mnemonic wallets now store the EXPANDED 64-byte BIP39 seed with the 32-byte
    entropy in a separate display-only record. Derivation reads stored bytes
    directly on every binary, so key trees are identical and no CHDChain version
    bump or minversion fence is needed -- the format stays readable by earlier
    releases;
  * new wallets are created from a BIP39 phrase by default;
  * the plaintext hdseed record is erased when a wallet is encrypted. It was
    previously left behind, and CDB::Rewrite copies surviving records verbatim,
    so the unencrypted seed persisted on disk forever.

TWO DEFAULTS CHANGE for new wallets: auto-shielding (where the seed provenance is
known) and BIP39 seed generation. Existing wallets are untouched -- seed
generation is reachable only when a wallet has none, and all three key stores
refuse to replace an existing seed.

Testing state, stated plainly: every commit built clean and the branch was
verified on an isolated chain -- destination selection provably ignores an
imported foreign key, both provenance branches behave, a new-format wallet
reopened by a pre-change binary lists identical addresses, and restoring only the
24 words recovers the wallet. NOT yet tested: any of this against a funded wallet
on mainnet, or a soak of these defaults on a real node.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-23 11:53:32 -05:00
d12e7dc99d Merge origin/master into dev: restore the mingw -Wa,-mbig-obj flag
dev branched from the release line before 1c3523aac and so lost -Wa,-mbig-obj
from util/build-win.sh. Without it the Windows cross-compile fails at link: large
template/boost-heavy translation units exceed the PE/COFF ~32k-section limit, and
GNU ld emits "dangerous relocation" on .pdata and crashes. v1.1.0 therefore could
not produce a win64 binary at all.

The merge brings only that one file back. util/build-win.sh is the only file both
sides touched, and the two edits are ~20 lines apart, so it auto-merges keeping
both fixes: -Wa,-mbig-obj on the configure line and -DARCH=default on the cmake
line. Verified after merging that dev's own work is intact -- the extended
checkpoint table, the guarded RandomX dedup, the 1.1.0 version bump, and
ARCH=default in the other two build scripts.

No C++ changed; the only delta from the pre-merge dev is the shell script.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
v1.1.0
2026-08-23 10:42:29 -05:00
9734402d7b wallet: create new wallets from a BIP39 seed phrase by default
New wallets now get an exportable 24-word phrase instead of a random seed that
no phrase can ever reproduce. Only wallets with no seed yet are affected;
GenerateNewSeed is reachable from one place, under !HaveHDSeed(), and all three
key stores refuse to replace an existing seed.

This is safe to default on now that the storage form is backwards compatible: the
expanded 64-byte BIP39 seed is what gets stored, so a binary predating any of
this reads it and derives the same keys.

Verified on an isolated chain before flipping:
  - a new-format wallet reopened with the tagged v1.1.0 binary, which has no
    knowledge of the entropy record, listed identical addresses;
  - restoring only the 24 words into a fresh datadir recovered every address.

Note this changes what a new wallet is, not what an existing one is: the same
entropy yields a different key tree depending on which side of this commit
created the wallet. Nothing migrates, and nothing needs to.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-23 07:01:22 +02:00
20b2cbe830 wallet: store the expanded BIP39 seed for mnemonic wallets
Mnemonic wallets stored the 32-byte BIP39 entropy as the HD seed and relied on
CHDChain.fMnemonicSeed to tell the deriver to expand it first. That flag is
version-gated in the CHDChain serialisation, so a binary that predates it reads
the record, never consumes the trailing byte, and derives from the raw entropy --
a different key tree, silently, with no error.

Store the expanded 64-byte BIP39 seed instead, with fMnemonic = false, and keep
the entropy in its own display-only record. Derivation then reads the stored
bytes directly on every binary, old or new, so key trees are identical and no
CHDChain version bump or minversion fence is needed. The wallet format stays
readable by earlier releases rather than becoming one-way.

Addresses are unchanged: the previous format expanded the entropy on every read
and fed the same 64 bytes to Master(). This is also the form the tree already
round-trips through -- z_exportwallet dumps the expanded seed, and restoring that
hex via -hdseed installs it with fMnemonic = false.

Write order is load-bearing: seed first, entropy second. A crash between them
leaves a wallet with a seed and no phrase, which is merely inconvenient. The
reverse would leave an entropy record with no seed, and the next start would mint
a different seed while the wallet still held a phrase for the old one.

-usemnemonic still defaults to false; only explicit opt-in and -mnemonic restores
take this path.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-23 06:39:38 +02:00
2d7dd90c55 wallet: plumb the mnemonic entropy through CWallet
Wires the key store secret to the database records: load and store paths on
CWallet, the two ReadKeyValue arms, and the export path.

GetMnemonicPhrase now prefers the entropy record and verifies it before printing:
a phrase is only returned if expanding it reproduces the seed derivation actually
uses. It falls back to the existing fMnemonicSeed path, so wallets that store the
entropy AS the seed keep working unchanged.

IsMnemonicSeed() now means "a phrase is available" rather than "the seed is the
entropy", which is what every caller actually wants.

Still a no-op on every existing wallet: nothing creates an entropy record yet, so
GetMnemonicEntropy returns false and the old code path is taken.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-23 06:37:43 +02:00
3caec548ae wallet: persist the mnemonic entropy in wallet.dat
Adds the record pair for the entropy, mirroring "hdseed"/"chdseed": a plaintext
form, an encrypted form that erases its plaintext counterpart the way
WriteCryptedKey does, and an erase.

Both new types are registered in IsKeyType so -salvagewallet preserves them.
Without that, salvage would silently drop the phrase while keeping the wallet
otherwise intact.

The records are defined but nothing writes them yet.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-23 06:30:18 +02:00
2a7fdcc1db wallet: add an optional mnemonic-entropy secret to the key stores
Additive plumbing for storing a BIP39 entropy alongside the HD seed, mirroring
how the seed itself is handled through both key store layers: a plaintext member
on CBasicKeyStore, an encrypted pair on CCryptoKeyStore, encryption during the
unencrypted-to-encrypted conversion in EncryptKeys with the plaintext cleared,
and decryption on unlock.

RawHDSeed and CKeyingMaterial are the same secure_allocator vector type, so the
entropy passes through EncryptSecret/DecryptSecret with no adaptation.

Nothing calls this yet; there is no behaviour change.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-23 06:23:09 +02:00
143c33de48 wallet: erase the plaintext HD seed record when the wallet is encrypted
CWalletDB::WriteCryptedHDSeed wrote the "chdseed" record and left "hdseed" in
place, unlike WriteCryptedKey which erases "key"/"wkey" after writing "ckey".
No erase of "hdseed" existed anywhere in src/wallet/.

CDB::Rewrite does not save us: EncryptWallet calls it with pszSkip defaulted, so
it copies every surviving record verbatim into the new file. The result is that a
wallet created unencrypted and later encrypted keeps its raw HD seed in cleartext
on disk permanently, and reloads it into memory on every start.

Add CWalletDB::EraseHDSeed and call it from CWallet::SetCryptedHDSeed after the
encrypted record is written, through the same CWalletDB so it shares
EncryptWallet's transaction. Erase returns true on DB_NOTFOUND, so a wallet that
was never written in plaintext is unaffected.

The erase is deliberately best-effort and only logs on failure. A hard failure
here propagates into CCryptoKeyStore::EncryptKeys, which EncryptWallet turns into
assert(false) with half the keys encrypted in memory; a warning is strictly
better than that.

Note this path is only reachable with -developerencryptwallet, which is
experimental and off by default on this chain, so this is a latent fix rather
than a live one.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-23 06:14:31 +02:00
e2f88175ab wallet: default -autoshield ON only when the HD seed is known-recoverable
Autoshield moves mined coinbase into a z-address that only this wallet's HD seed
can re-derive. Defaulting that ON is only defensible where the user can actually
restore that seed.

Two cases fail that test. A seedless legacy wallet has a seed minted onto it
silently at first start, so no backup the user already holds contains it. And a
wallet seeded by an earlier build predates provenance recording, so we cannot
tell which case it was. Both are now classified as not-known-recoverable and
autoshield stays off there until the operator backs the seed up and passes
-autoshield=1. An explicit -autoshield=0/1 still wins in either direction.

Wallets this software created on an empty datadir, or restored from a
user-supplied -mnemonic/-hdseed, keep the ON default: in both cases the user
either has the phrase or supplied the seed themselves.

Verified on real wallets: a wallet carrying no origin record is classified
unknown and logs "autoshield left OFF by default: HD seed origin 4"; a wallet
created by the previous commit logs "autoshield enabled" with no
re-classification, confirming the record persists rather than being recomputed.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-23 03:22:55 +02:00
a494eabdce wallet: harden HD seed/chain persistence and record seed provenance
Autoshield sends mined coinbase to a seed-derived z-address, so the records that
decide how the seed derives keys become fund-safety critical. Three of them were
not treated that way.

InstallHDSeed wrote the seed record before the chain record, non-transactionally.
A crash between the two left a wallet holding a seed with no hdchain: on the next
load hdChain silently reverts to defaults, clearing fMnemonicSeed -- which
switches the derivation input from the expanded BIP39 seed to the raw entropy --
and resetting saplingAccountCounter. Write the chain first; the opposite torn
state is harmless and self-heals, because HaveHDSeed() is then false and init
installs again.

The hdchain record was read as a bare deserialise inside a catch-all with strErr
never set, and it is not a key type, so a corrupt record was downgraded to a
non-critical error and the node booted into the wrong key tree. Report it, track
whether it was read, and refuse to load a wallet that holds a seed but no
readable hdchain. Also preserve hdchain through a keys-only salvage, which would
otherwise drop it and produce exactly the state we now refuse.

GenerateNewSeed silently fell back to a random seed when BIP39 generation failed,
producing a wallet that looks mnemonic-capable but whose words can never be
exported and which no seed phrase can restore. A user who asked for -usemnemonic
now gets that or a hard failure.

Finally, record how the seed came to exist -- created on an empty wallet,
restored from -mnemonic/-hdseed, retrofitted onto a pre-existing seedless wallet,
or predating this record. A retrofitted seed is in no backup the user already
holds, so a feature that moves funds into addresses only that seed can re-derive
must not enable itself there by default. Nothing consumes this yet.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-23 03:18:35 +02:00
dad162a89a wallet: pick the autoshield destination by seed re-derivation, in-gap only
resolveDestination() took the first spendable address in std::set order, which
orders on the raw Sapling diversifier (zcash/Address.hpp:95-98) -- uncorrelated
with anything the operator can see, and unstable across restarts as addresses
are added.

Worse, GetSaplingPaymentAddresses() also returns z_importkey/z_importwallet
addresses, and CKeyMetadata is NOT evidence of provenance: both hdKeypath and
seedFp are copied verbatim out of the import source (rpcdump.cpp:511-516 ->
wallet.cpp:5440-5441) with no verification. A crafted import can therefore claim
this wallet's seedFp and keypath m/32'/coin'/0' and capture every shielded
mining reward into a key no seed restore can reproduce. Filtering on metadata
would not have caught that.

Derive instead. A bare -mnemonic/-hdseed restore pre-derives exactly
-mnemonicsaplinggap sapling accounts from index 0 with saplingAccountCounter
reset (init.cpp:2349-2355), so the only self-recoverable destinations are the
default addresses of m/32'/<coin>'/i' for i below the gap. Walk that window from
the seed and take the lowest index the wallet holds a spending key for. Deriving
is the only authoritative test and cannot be spoofed.

When nothing in the window is held yet, derive the next account -- but only if it
will land inside the window. GenerateNewSaplingZKey does not derive at
saplingAccountCounter: its do/while skips indices already held
(wallet.cpp:150-157), so a bare counter-below-gap test is unsound. Predict the
lowest free index at or above the counter and post-verify the returned address.
If no free account remains below the gap, refuse the round and leave the coinbase
transparent -- transparent funds are still recoverable through the 1000-key
transparent gap, an unfindable note is not.

Refusing is safe: main_impl turns a false return into a clean skip, and main()
always advances nextAutoShield and clears fAutoShieldRunning, so a refused round
cannot latch the feature off.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-23 02:52:34 +02:00
bb292a89cc test: merge feature/autoshield-coinbase into v1.1.0 for isolated testing
Not for release. Built solely to exercise auto-shield-coinbase on an isolated
mining chain, since the feature is a no-op on a non-mining node (the canary
seed has no balance, no z-address, no coinbase, and does not mine).

Merge is clean: util/build-win.sh auto-merged, keeping both our ARCH=default
and their -Wa,-mbig-obj. Checkpoints, verify-once guard and the version bump
all survive.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-21 19:24:20 -05:00
660678f9bb build: bump version to 1.1.0
CLIENT_VERSION 1000350 -> 1010050. Goes to 1.1.0 rather than 1.0.4 because
1.0.3 is already burned and ambiguous: origin/dragonx's debian changelog
already claims 1.0.3 and the daemon bundled in the ObsidianDragon 2.0.1
installer is labelled v1.0.3-dc45e7d90, so a 1.0.4 would sort above builds
that contain less.

Bumped in configure.ac (authoritative) and in the src/clientversion.h fallback
used when HAVE_CONFIG_H is unset, which the header itself asks to be kept in
sync.

DELIBERATELY NOT BUMPED: SPROUT_VALUE_VERSION, SAPLING_VALUE_VERSION and
SAPLING_VALUE_OPTIONAL_VERSION in chain.h. Those are thresholds marking the
CLIENT_VERSION that INTRODUCED each block-index format, not "the current
version". Raising SAPLING_VALUE_OPTIONAL_VERSION to 1010050 would push every
record written by a v1.0.3 node (nVersion 1000350) into the legacy
raw-CAmount branch of the deserializer and misparse it. The stale comment
naming 1000350 as the current CLIENT_VERSION is updated; the constants stand.

1010050 >= 1000350, so this build still writes and reads the optional format.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-21 19:15:56 -05:00
fbcf160478 fix(pow): only dedup RandomX when CheckBlockHeader verified it; drop fake git id
Brings onto dev the two fixes that until now existed only on release/1.0.4, so
nothing is stranded on a branch we are not shipping from.

1. GUARDED VERIFY-ONCE (main.cpp)

4e67e687d arms the RandomX dedup unconditionally whenever fCheckPOW is set. But
CheckBlockHeader returns early -- BEFORE reaching its RandomX check -- for a
block whose timestamp is >60s in the future (*futureblockp==1), and CheckBlock
deliberately continues on that path. There, hush_checkPOW is the ONLY RandomX
verification the block gets, so suppressing it leaves the block unverified.

Not a chain-acceptance hole: ConnectBlock rejects futureblock != 0, so such a
block never joins the chain. But it silently weakens DoS banning -- an invalid
future block gets rejected for its timestamp instead of for bad PoW, which is a
regression against the un-deduped behaviour it replaced.

ScopedRandomXSkip now takes an `arm` flag and CheckBlock passes fHeaderChecked,
so the dedup applies only where the header check actually completed and did the
verification. Strictly a tightening: it can only cause MORE verification than
before, never less.

2. NO FAKE GIT IDENTITY (clientversion.cpp)

A hardcoded `#define GIT_ARCHIVE 1` with GIT_COMMIT_ID "a86845f3dc", dated Feb
2018, is reached whenever build.h supplies no BUILD_DESC -- i.e. any build
without git metadata, which is exactly the tarball/CI release case. Such
binaries reported themselves as that Komodo commit regardless of content; a
build here did precisely that before this was found. The archive substitution
placeholders are kept, so a real git-archive export still works; a git-less
build now reports "-unk", which is honest and greppable.

Both syntax-clean. Rebuild and re-validation on EPYC follows; the earlier
validated binary (md5 fe83d70fec5b50c38bf65ea6c733ffa9) predates these.

release/1.0.4 is parked, not deleted -- its commit records why the v1.0.2
lineage cannot ship (block-index format incompatibility with dev-written
chainstate).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-21 19:15:56 -05:00
7dc904c96f perf(sync): extend DRAGONX checkpoints to 3,226,000; build portable RandomX
The RandomX skip in RandomXValidationRequired() has never fired in production.
It skips verification below the last in-index checkpoint, but the DRAGONX
checkpoint table ended at 2,838,000 while ASSETCHAINS_RANDOMX_VALIDATION is
2,838,976 -- the window was empty by 976 blocks. Every block since the RandomX
activation has been fully verified, at ~65ms per hash on the fastest x86 core
available and ~180ms on a typical user machine.

Extends the table by 388 entries at stride 1000, from 2,839,000 to 3,226,000
(tip - ~5,600, far beyond any reorg this chain has produced; max observed depth
is 3-4). Blocks requiring a RandomX verify drop from 391,447 to ~5,500. The
same extension carries the existing script/zk-proof skip (fScriptChecks,
fExpensiveChecks) over the same range.

Checkpoint data verification, before it went anywhere near source:
  - generated on a continuously-synced node
  - all 388 hashes identical on 4 other full nodes (388/388 on each)
  - reverse-verified hash -> height, all on the active chain
  - re-extracted from the patched file and diffed against the verified set
  - 2,838 pre-existing entries unchanged; all 3,226 ascending and unique
Trailer fields computed from RPC, not util/checkpoints.pl, which greps a
rotating debug.log and assumes 1440 blk/day (DragonX is 2400).

Also switches all three build scripts from -DARCH=native to -DARCH=default.
RandomX's CMakeLists maps ARCH=native to -march=native, tuning the binary to
the build host: a Zen4 build emitted 746 AVX-512 instructions into
librandomx.a, and every seed reports avx512f=no, so that binary would SIGILL
inside RandomX fleet-wide -- and on any user CPU older than the build machine.
build-win.sh had the same flag, so shipped Windows binaries inherited it.
ARCH=default keeps -maes and per-file -mssse3/-mavx2, so the portable baseline
costs essentially nothing. Note build.sh skips cmake entirely when
src/RandomX/build/ exists, so a stale dir silently preserves the old ARCH.

Validated on an isolated datadir on an EPYC seed, bootstrap -> tip:
  - below 3,226,000 (RandomX skipped):  91.3 blk/s (22,823 blocks / 250s)
  - at/above 3,226,000 (verified):       4.7 blk/s
  ~19x at the boundary. The 4.7 blk/s baseline matches a same-day restore on
  the old binary, corroborating it independently.
  - gettxoutsetinfo at height 3,231,951 BYTE-IDENTICAL to a live node
    (hash_serialized 4885c2374ef8b84c648b97d560a57cfcc99bb979142dc89c2a5ccbc90a1f1692,
     222,635 txs/txouts, 15,826,352 bytes, total 667909.93689180)
  - synced through all 388 new checkpoints with zero rejections
  - verifychain 4 (500) and 3 (2000) both true
Binary: v1.0.3-bf3c33c53-dirty, stripped md5 fe83d70fec5b50c38bf65ea6c733ffa9

Checkpoints decay at 2,400 blocks/day; regenerating them belongs on the
release checklist.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-21 19:15:56 -05:00
4d72e5fc30 wallet: fix sweep-scheduler wedge and unsynchronized driver mutation
The zaddr-sweep op cleared fSweepRunning/nextSweep only on the sweepComplete
success path (inside main_impl), so a cancelled or throwing sweep left
fSweepRunning stuck true. Since fSweepRunning now also gates consolidation and
the default-on autoshield, a persistently failing sweep (e.g. a corrupt-witness
note) would wedge all three background ops for the session.

Move the scheduler bookkeeping into main() so it runs on every terminal state
(success/failure/exception/cancel), guarded by op id. Preserve the intended
"keep draining every block until swept" model: on a successful-but-incomplete
round the flag stays set and nextSweep is not advanced; on completion OR on
failure/exception the flag is released and nextSweep backs off one interval, so
a failing sweep no longer retries every block or wedges the other ops.

Also fix RunSaplingSweep to take cs_wallet itself (was AssertLockHeld, a no-op
in release builds) since ChainTip does not hold it there and the driver mutates
scheduler state + enqueues -- matching RunSaplingConsolidation and
RunAutoShieldCoinbase.

sweepComplete is recorded via a new member; saplingSweepOperationId made public.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-21 18:55:16 -05:00
ca730a5d98 wallet: fix consolidation-scheduler wedge (ran every block; dead mutual-exclusion)
The Sapling auto-consolidation scheduler never advanced nextConsolidation after
init and never set fConsolidationRunning, so once the tip passed the init
threshold `-consolidation` dispatched a consolidation op every block instead of
once per -consolidationinterval, and every guard that reads fConsolidationRunning
(in RunSaplingSweep, and in the new autoshield driver) was dead.

Mirror the intended scheduler model:
- RunSaplingConsolidation sets fConsolidationRunning=true before dispatch and
  self-guards with `if (fConsolidationRunning) return;`.
- The consolidation op advances nextConsolidation = consolidationInterval +
  tipHeight and clears fConsolidationRunning on every terminal state
  (success/failure/exception/cancel), guarded by op id so only the current op
  mutates scheduler state.
- saplingConsolidationOperationId moved to public so the op can read it.

Restores the documented once-per-interval cadence and makes the
sweep/consolidation/autoshield mutual-exclusion guards effective.

Note: the sweep op has the same latent wedge (fSweepRunning/nextSweep are
cleared only on the sweepComplete success path, so a cancelled or throwing
sweep leaves fSweepRunning stuck true) - left for a follow-up; this commit is
the template to port.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-21 18:28:17 -05:00
2ebbbc777c wallet: add default-on auto-shield-coinbase; drain miner coinbase into a z-addr
On this ac_private=1 chain miners accumulate one transparent coinbase UTXO per
block (the only transparent output the chain permits). It had to be shielded
manually via z_shieldcoinbase, and left unshielded it is the sole persistent
metadata leak on the chain and the source of miner UTXO-fragmentation send
failures.

Add AsyncRPCOperation_autoshieldcoinbase: a periodic, default-on wallet op
driven from CWallet::ChainTip alongside sweep/consolidation, draining matured
coinbase into a wallet-owned Sapling z-address in size-bounded batches.

- Enqueue-only driver (RunAutoShieldCoinbase): takes only cs_wallet in the
  notify context; all gathering runs on the async worker under LOCK2(cs_main,
  cs_wallet).
- Dedicated op (not a reuse of z_shieldcoinbase) so it never toggles mining.
- Default-ON but conditional: silent no-op on -disablewallet, external
  -mineraddress, non-mining, or locked wallets (explicit IsLocked() guard).
- Destination is reuse-then-create; -autoshieldaddress override is
  spend-key-validated at init so funds cannot be stranded.
- Sweep-model bookkeeping: advances nextAutoShield and clears the running flag
  on every terminal state; an op-id guard stops a stale op clobbering scheduler
  state; a self-guard stops cancel/re-enqueue churn.
- Sietch-padded output shape matches manual z_shieldcoinbase txns.

Config: -autoshield (default true), -autoshieldinterval, -autoshieldaddress,
-autoshieldfee (range-validated), -autoshieldminutxos.

Incorporates fixes from an 8-angle code review: CAmount fee type with init-time
range validation, op-id-guarded flag bookkeeping, driver self-guard, and a
tipHeight-consistent NU-activation guard.

Note: the fConsolidationRunning / nextConsolidation consolidation-scheduler
wedge is a pre-existing bug, left for a separate change.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-21 02:06:09 -05:00
1c3523aac1 build(win): add -Wa,-mbig-obj to the mingw cross-compile flags
Large template/boost-heavy TUs (e.g. asyncrpcoperation.cpp) exceed the standard
PE/COFF ~32k-section limit under mingw-w64, which makes GNU ld emit
"dangerous relocation" on .pdata and crash (SIGSEGV) at link. The bigobj COFF
variant lifts that limit; this is the same flag Bitcoin Core sets for its mingw
host. Fixes the Windows daemon cross-compile.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
v1.0.3
2026-07-23 16:56:13 -05:00
d0657d38b4 Merge dev into dragonx: DragonX rebrand + security/consensus hardening + IBD speedups
# Conflicts:
#	contrib/init/dragonxd.conf
#	contrib/init/dragonxd.init
#	contrib/init/dragonxd.openrc
#	contrib/init/dragonxd.openrcconf
#	contrib/init/dragonxd.service
2026-07-21 18:58:33 -05:00
8976e020e9 packaging: don't fail the .deb build when optional lintian is absent
build-debian-package.sh warns at startup that lintian is optional, but then
called `lintian -i ...` unconditionally at the end. Under `set -e` that aborted
with exit 127 on hosts without lintian — after the .deb had already been built.
Guard the call with `command -v lintian` so the build exits 0.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-21 16:04:08 -05:00
9c715f68eb depends: fix libsodium build breaking on git.savannah.gnu.org 502
libsodium's autogen.sh fetches config.sub/config.guess from git.savannah.gnu.org
gitweb, which is frequently down (currently returns 502). curl saved the HTML
error page over config.sub, so libsodium's configure died with
"cannot run /bin/bash ./build-aux/config.sub" and the whole build failed.

autoreconf -ivf (run earlier in autogen.sh) already installs valid config.sub/
config.guess from the build host, so set DO_NOT_UPDATE_CONFIG_SCRIPTS=1 (the
script's own opt-out) to skip the fragile download. Validated: the full build
now completes and produces working dragonxd/dragonx-cli/dragonx-tx.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-21 16:02:04 -05:00
e3247d946e cleanup: rebrand residual user-facing "HUSH" strings to DragonX
Sweeps the leftover coin-name strings in RPC help text, RPC output, and log
messages that the currency-unit change didn't cover:

- RPC help: "mining reward amount in HUSH" -> DRAGONX (mining.cpp x2);
  "at least minbal HUSH" -> DRAGONX (rpcwallet.cpp); "the HUSH address" /
  "(string) HUSH address" -> DragonX (rawtransaction.cpp)
- RPC output: the SMART_CHAIN_SYMBOL[0]==0 ? "HUSH" : SYMBOL coin-name fallback
  (crosschain/misc/mining/blockchain) -> "DRAGONX"; the notarizations JSON key
  make_pair("HUSH", ...) -> "DRAGONX"
- Logs: "HUSH blocktime changing", "stopping HUSH HTTP/REST/RPC",
  "HUSH raw magic=" -> DragonX

Left untouched (verified): the 82 "HUSH3"/ishush3 chain-symbol consensus checks;
hush_globals.h CURRENCIES[] price-oracle basket (internal lookup, dead feature
on DragonX); hush.h notarization debug printf; a commented-out cout in main.cpp.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-21 15:37:57 -05:00
ffb753057a cleanup: rebrand currency unit, depends mirrors, seeds; drop Hush-history files
Follow-up to the doc rebrand, addressing the previously out-of-scope legacy:

- Currency unit: strCurrencyUnits (chainparams.cpp) and CURRENCY_UNIT
  (amount.cpp) "HUSH" -> "DRAGONX". Both are display-only (RPC help + metrics);
  no logic comparisons, verified.
- depends mirrors: libsodium/boost/utfcpp fetched from git.hush.is/attachments;
  repointed to canonical upstream (GitHub release / archives.boost.io / GitHub
  tag) with the existing sha256 hashes verified to match those sources.
- Seeds: nodes_main.txt now lists the five node[1-5].dragonx.is IPs (DNS-resolved)
  instead of Hush nodes; regenerated src/chainparamsseeds.h (was compiling Hush
  seed IPs as the fixed fallback); generate-seeds.py header now says DragonX;
  hush_seed_nodes.txt updated to DragonX seeds.
- Deleted Hush-history / wrong-for-DragonX files: contrib/snapshot/ (block-500000
  Hush airdrop, ~10MB), notary_seeds.txt (Hush notaries; DragonX isn't notarized),
  and the Hush emission scripts hush_supply, hush_supply_old, hush_halvings,
  hush_block_subsidy_per_halving (hardcode Hush's 340000/12.5 economics).

Kept: hush_scanner (engine invoked by dragonx_scanner) and the "The Hush
developers" copyright headers (lineage credit).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-21 14:13:31 -05:00
46693a355a docs: rebrand documentation, packaging, and helper scripts to DragonX
The docs/packaging were largely un-rebranded Hush3 content, with several
docs stating facts that are wrong for DragonX. This rewrites them against
the verified DragonX source state.

Corrections (not just branding):
- PoW: RandomX (CPU), not Equihash/ASIC — README, overview.md, randomx.md
- Privacy: private from genesis (ac_private=1, Sapling@height1), not "as of
  block 340000" — overview.md, payment-api.md
- Removed the false "coinbase must be shielded" consensus claim
  (shield-coinbase.md, payment-api.md); coinbase is directly spendable
- Fixed default fee 0.0001 (was 0.0010000, 10x); stratum port 22769 (was 19031)
- datadir ~/.hush/DRAGONX, DRAGONX.conf, dragonxd/dragonx-cli/dragonx-tx,
  git.dragonx.is throughout; branch model dev->dragonx
- Softened the inherited dPoW reorg claim (no live DragonX notary infra)

Packaging: fix build-debian-package.sh + gen-manpages.sh to use the dragonx
binaries/manpages; rename bash-completions to dragonx*; drop hush-arrakis-chain
from the package. Keep /usr/share/hush (hardcoded in the binary for params).

Also: README links/logo, ObsidianDragon + SilentDragonXAndroid wallets,
networking/init/dev-process/contrib/util rebrand, and leftover helper scripts.
Delete legacy duplicates (hushd.* init/service, HUSH3.conf examples,
OLD_WALLETS.md, hsc.md) and rename hush-uri.bat -> dragonx-uri.bat.

Out of scope (noted, not changed): historical changelog/copyright, the Hush
mainnet airdrop snapshot, seed data files, depends/ source mirrors, and the
in-code strCurrencyUnits="HUSH".

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-21 13:59:06 -05:00
bf3c33c53a revert(net): remove header-accept RandomX check; keep nMinimumChainWork + #8
An adversarial re-review found the header-accept RandomX check (b9fdc7981 +
7e9b2c661 header-PoW + d2124a303 defer) to be a persistent source of
consensus-liveness bugs: it derives the RandomX key from the ACTIVE chain
(hush_chainactive), the wrong branch for reorg/side-branch/catch-up headers, so
it repeatedly false-rejected validly-mined headers and DoS(100)-hard-banned
honest peers (IBD-tail catch-up and deep-reorg cases); the defer fix and an
extend-tip fix each addressed one case while leaving/creating others (an
extend-tip variant re-opened an unbounded post-IBD side-branch flood). It only
mitigated a low-harm resource DoS -- forged headers bloat mapBlockIndex memory/
disk but are never SELECTED (nMinimumChainWork) and the full RandomX + target
check still runs at block-connect. Revert to fCheckPOW=0 at header-accept
(original behavior). A comment in AcceptBlockHeader records that any re-attempt
must derive the key from the header's OWN ancestry (pindexPrev->GetAncestor),
never the active chain.

Also hardens two issues the same review found:
- #8 IBD header cap now bounds against the VALIDATED chainActive.Height()
  (attacker-hard) instead of pindexBestHeader, which a forward-extending flood
  advanced in lockstep, defeating the cap.
- opreturn_burn only emits a change output above the dust threshold; a sub-dust
  change made the returned tx non-standard/unrelayable.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-14 20:24:45 -05:00
5951ee118a fix(net): cap per-peer headers during IBD (header-flood DoS)
Audit #8. The HEADERS handler accepted unbounded headers per peer with no
cumulative cap; during IBD (fCheckPOW=0) a peer could flood cost-free PoW-less
headers into mapBlockIndex/leveldb (never selected -- nMinimumChainWork gates
that -- but still memory/disk growth). Add a per-peer nHeadersProcessed counter
in CNodeState; while IsInitialBlockDownload(), if one peer exceeds
2*max(pindexBestHeader height, checkpoint height) + 200000 headers,
Misbehaving(100) and drop it. The cap is ~2x the chain length, so honest sync
never approaches it; inert post-IBD (the RandomX header check handles forged
headers there).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-14 18:54:35 -05:00
d2124a3038 fix(pow): defer RandomX header check when key block not yet connected
Follow-on to the post-IBD header-PoW verification (b9fdc7981 + 7e9b2c661).
CheckRandomXSolution derives the RandomX key from the block at
keyHeight = ((height-lag)/interval)*interval, looked up on the ACTIVE chain
(hush_chainactive), so that block must be CONNECTED. When a post-IBD node's
block tip lags the header tip by more than ~one RandomX interval -- the normal
IBD tail, or any node catching up -- the key block is not connected yet, so
GetRandomXKey returns empty. The old code returned an error, making
CheckBlockHeader DoS(100)-ban the honest peer that sent a perfectly valid tip
header we simply could not verify yet.

Observed live: a node finishing a mainnet reindex banned the pool box + seeds
and stalled ~2000 blocks short of the tip. Fix: on an empty key, DEFER (return
true) instead of error -- the header is fully RandomX-verified at block-connect,
where the key block is always connected (blocks connect in order,
keyHeight <= height-lag < the connected tip). Flood protection is preserved for
synced nodes (key present -> real check) and bounded during catch-up by the
per-peer IBD header cap + nMinimumChainWork.

Validated on the live 3.14M-block chain: the affected node caught up the full
~2135-block gap to the tip with zero peer bans (was stalled + banned before).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-14 18:54:35 -05:00
b5050d06c0 fix(wallet): opreturn_burn return change + widen txfee to CAmount
#10 (HIGH) opreturn_burn selected UTXOs for nAmount+txfee but pushed only the
burn vout and returned - so the entire selected-input surplus was silently paid
as miner fee (e.g. a 500-coin UTXO burning 10 lost ~490). Push a change output
for (inputs - nAmount - txfee). Also widen the int32_t txfee (which truncated
large CAmount fees) to CAmount and MoneyRange-validate.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-14 11:21:28 -05:00
a520441e3a fix(rpc): guard z_validateaddress against null pwalletMain under -disablewallet
#11 (HIGH) z_validateaddress locked LOCK2(cs_main, pwalletMain->cs_wallet) with
no availability guard; under -disablewallet pwalletMain is NULL, so the member
deref SIGSEGVs the daemon (execute() only catches std::exception). Use the
null-safe LOCK2 idiom already used by sibling RPCs so validation still works
without a wallet.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-14 11:21:28 -05:00
11704e6023 fix(nspv): add missing length lower-bounds before request/vopret reads
nSPV handlers (gated behind non-default -nspv_msg) read request[1]/vopret[1]
before confirming the peer sent >=2 bytes:

#6 (MEDIUM) NSPV_UTXOS/NSPV_TXIDS evaluated request[1] whenever len<69 (incl
len==1); the 4351d5b73 value-clamp left this lower bound open. The TXIDS/MEMPOOL
else-branch debug prints also read request[1] unconditionally. Add len>=2 guards
/ drop request[1] from the prints.

#7 (LOW) NSPV_MEMPOOL_CCEVALCODE read vopret[1] on a possibly-1-byte vector.
Guard with vopret.size()>=2.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-14 11:21:28 -05:00
7e9b2c6615 fix(net): verify RandomX at correct height in AcceptBlockHeader + cap locator
header-pow: AcceptBlockHeader passed the caller's reused *ppindex (and a height
derived from it, ==0 for a new header) to CheckBlockHeader instead of the
header's own local pindex + real height. Post-IBD this made
RandomXValidationRequired(0) false, so CheckRandomXSolution returned true WITHOUT
verifying (and the fRandomXVerified short-circuit could fire on an unverified
header) - silently defeating the header-flood PoW gate from b9fdc7981. Resolve
pindexPrev up-front, pass real height (parent+1) and the local (NULL) pindex so
the post-IBD RandomX check actually runs; IBD stays fast (fCheckPOW=0).
Stability-tested: 303 valid headers accepted across a 4-node RandomX net,
0 false rejects / bans.

#9 (MEDIUM) GETBLOCKS/GETHEADERS deserialized an unbounded CBlockLocator.vHave
(~130k hashes) and scanned it linearly under cs_main with no ban - a
message-thread liveness DoS. Add MAX_LOCATOR_SZ=101 + Misbehaving, matching the
adjacent vInv/headers caps.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-14 11:21:28 -05:00