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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

The fee rule moves into SaplingConsolidationTxFee, with a test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 12:54:55 -05:00
DanSandClaude Opus 5.5 6d7ffeb2b9 wallet: end a consolidation round early on shutdown or a queued op
A stop issued during a consolidation round waited for the whole round
to be built and committed: 634 s in review, ~8 min for the default 18
txs on a crowded wallet. StopRPC cancels every queued operation, but
AsyncRPCOperation::cancel() is not virtual, so the op's own cancel(),
which moves an EXECUTING op to CANCELLED, is never called and its
isCancelled() checks between transactions never fire. A GUI that kills
dragonxd 20 s into shutdown then kills it mid-round, which costs a
chainstate replay and a witness rebuild on the next start.

Check ShutdownRequested() next to isCancelled() before building each
transaction and before committing it, so a stop waits for one tx at
most. Making cancel() virtual would also do it, but would change what
the sweep and autoshield schedulers' cancel of their previous op does.

dragonxd also has a single async worker, so a z_sendmany made during a
round waited for all of it. After each committed tx the round now ends
when another operation is queued. Its unspent planned notes are
unlocked as before and the next round takes them up. last_round and the
op result report it as yielded.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 12:48:44 -05:00
DanSandClaude Opus 5.5 fef79e7b12 wallet: skip fully validated txs before the depth lookup in the root selection
The root selection of VerifyAndSetInitialWitness looked up the depth of
every note-bearing tx on every block, although in the steady state
between restarts every note is already validated and nothing is
selected. A tx whose notes are all validated is now skipped before
GetDepthInMainChain. The selection is the same: it never took a
validated note.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 12:40:42 -05:00
DanSandClaude Opus 5.5 9bd2fd2b92 wallet: add -walletsaveatshutdown to turn the shutdown save off
The shutdown save writes every note-bearing tx with its witness cache,
which takes tens of seconds on a large wallet: about 15 s unloaded and
30-40 s under load for a 631 MB regtest wallet, and more for a mainnet
wallet of 1-2 GB. A deployment that kills the daemon sooner (an old GUI
with a 20 s kill, a short service stop timeout) gains nothing from it:
the kill rolls the save back, and the next start spends extra time on
BDB recovery.

-walletsaveatshutdown=0 skips the save and logs why. The default stays
on. The shipped init scripts run with -disablewallet, so their stop
timeouts are left as they are.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 12:39:25 -05:00
DanSandClaude Opus 5.5 6413b8da4e wallet: skip the shutdown save when the chainstate flush failed
The shutdown save runs right after FlushStateToDisk(), whose void
wrapper dropped the result. If that flush failed (out of disk space, a
coins database or block index write error), the save still stamped the
wallet tip, a block the chainstate and block index on disk might not
have, and started a write the size of the wallet on what is typically a
full disk.

FlushStateToDisk() now returns the result of the flush it runs (true for
an nSPV light client, which flushes nothing). Its behaviour is
unchanged, and the other callers ignore the result as before. Shutdown()
passes it to PersistStateAtShutdown, which skips the save with "the
chainstate flush failed".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 12:37:36 -05:00
DanSandClaude Opus 5.5 0b822cc6b2 wallet: keep a failed open of the wallet database inside the shutdown save
SetBestChain opens the wallet database (CWalletDB) outside the try block
of SetBestChainINTERNAL, and CDB's constructor throws when the
environment or the file cannot be opened. Shutdown() calls the save with
no handler around it, so such a failure ended in std::terminate: the
coins views and the block tree were not deleted, the wallet was not
flushed and the pidfile stayed. The hourly SetBestChain runs inside
FlushStateToDisk's try block and never had this problem.

PersistStateAtShutdown now catches the exception, logs the save as NOT
saved with the reason, records nothing, and lets the teardown go on.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 12:32:54 -05:00
DanSandClaude Opus 5.5 ced37555c4 init: recreate a data-less notarizations DB in place, not aside
Every unreadable notarizations DB was moved aside under a new
timestamped notarizations.corrupt-* name. For a failure that persists
across starts rather than real corruption (disk full: DB::Open creates
the directory and LOCK, then fails), each start moved another empty
directory aside, and the copies piled up without limit.

When the directory holds no data, i.e. no non-empty .ldb/.sst table or
.log write-ahead log, there is nothing to keep: recreate the DB in place
instead (falling back to an in-memory DB as before if that fails). A
directory that cannot be listed counts as holding data, and any DB with
records is still moved aside, never deleted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 12:32:01 -05:00
DanSandClaude Opus 5.5 ed13277dcb wallet: do not save over the locator of a rescan that did not complete
A rescan started by RPC (rescan, z_importkey, z_importviewingkey,
importprivkey) that is cut short by abortrescan or by a stop writes its
progress as the best-block locator, or leaves the older locator when it
may not advance it. The next start resumes the scan from there. The
shutdown save then stamped the wallet tip over that locator, so the next
start found nothing to rescan: for a newly imported key, its notes in the
unscanned blocks stayed out of the wallet, with no warning, until a
manual rescan. On dev a session shorter than an hour never wrote at
shutdown, so this is a regression of the shutdown save.

ScanForWalletTransactions now records, for the session, where it left
the locator on disk: the persisted height when it starts (so a scan that
throws counts as incomplete too), the checkpoint or the old locator when
it is cut short. A scan that reaches the tip clears this, unless an
earlier scan was interrupted and this one starts above where that one
left the locator. While it is set, the shutdown save is skipped, as dev
would, and logs why.

The hourly SetBestChain after abortrescan is unchanged: it stamps the
wallet tip as it does on dev.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 12:27:43 -05:00
DanSandClaude Opus 5.5 2bc4a70eb8 init: bound the notarizations LOCK wait by wall-clock time
The wait for another process to release notarizations/LOCK counted 1 s
sleeps, so the time spent probing and a loaded machine stretched the
"up to 30 s" to 33-34 s. Wait against a GetTimeMillis() deadline instead,
and report the measured elapsed time in the "released after" and "still
could not be taken after" lines.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 12:21:55 -05:00
DanSandClaude Opus 5.5 8f70f494b3 init: do not call the notarizations DB corrupt on one post-failure probe
OpenNotarizationDB() decided between "LOCK held" and "corrupt" with a
lock probe taken after DB::Open had already failed. If the holder (an
older dragonxd finishing its exit, the very upgrade-restart case the
lock-aware fallback exists for) released notarizations/LOCK between the
failed open and the probe, the probe found the lock free and a healthy
DB was moved aside and replaced by an empty one. CDBWrapper throws a
generic "Database I/O error", so the error text cannot tell the two
cases apart either.

Only treat the DB as unreadable when an open fails although the probe
just before that open found the lock free: on a free probe, open once
more, and move aside only if that attempt fails too. A held probe still
gets the single bounded wait and then the in-memory fallback.

The probe now returns the leveldb::Status of its LockFile call, and the
log reports it ("Resource temporarily unavailable" versus, say,
"Permission denied") instead of the generic open error alone, worded as
"could not be taken" since a non-ok probe is not always another holder.
Any non-ok probe still counts as held, so it never moves or wipes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 12:10:21 -05:00
DanSandClaude Opus 5.5 63e7d6ef2d wallet: keep a throwing consolidation round's committed txs in its record
The op tallied the round in a local and handed it over only through
setConsolidationResult, which an exception thrown mid-round skips, so
last_round and the cumulative totals lost transactions it had already
committed. Tally into the member main() records from instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 11:36:59 -05:00
DanSandClaude Opus 5.5 7983a3dc68 doc: describe consolidation as it now works; fix zsweep doc errors
Rewrite the consolidation part of doc/zsweep-consolidation.md to match
the code: off by default (also for GUI wallets, which the doc claimed
were on), what an eligible note is, the threshold/batch/maxtxs policy
and its defaults including -consolidationinterval, smallest-first and
the randomised input count, the 8-output shape, locking only the
round's notes, skipped bad-witness notes, the fee range (fee 0 is no
longer accepted), the spending-key requirement, z_consolidationstatus
(the doc named z_sweepstatus) and its verbose mode, z_consolidate, and
the off-but-suggested hint.

Also fix -zsweepinterval: it defaults to 10 (values below 5 fall back to
10), not the 5 the doc and -help claimed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 11:22:58 -05:00
DanSandClaude Opus 5.5 ead3394188 wallet: suggest consolidation when it is off and notes pile up
Consolidation stays off by default, but a miner whose autoshield adds
one note per round should hear that it would help before the wallet
slows down.

With -consolidation off, count the addresses holding more than
-consolidationthreshold eligible notes right after the startup note
cache warm-up (the plaintexts are in memory then, so the walk is
cheap) and log once:

  N addresses have more than 25 spendable notes; consider
  -consolidation=1 or z_consolidate

z_autoshieldstatus reports it as consolidation_suggested (refreshing
the count at most once per consolidation interval, since autoshield is
what keeps adding the notes), and z_consolidationstatus verbose as
consolidation_suggested and consolidation_suggested_count from its own
walk. A later count that first finds an address over the threshold
logs the line then, still only once per run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 11:21:06 -05:00
DanSandClaude Opus 5.5 52b747f6d3 wallet/rpc: add z_consolidate, one consolidation round on demand
A CLI miner who keeps -consolidation off (the default) has no way to
shed the notes autoshield piles up short of scripting z_mergetoaddress,
which pauses the miner and rebuilds its RandomX dataset on every call.

z_consolidate ( fee batchsize maxtxs ["zaddr",...] ) runs one round of
the built-in consolidation now, with the -consolidation policy, also
when -consolidation is off. Any argument may be null to keep its
setting; out-of-range values and addresses that are not the wallet's
own Sapling addresses are refused rather than clamped. It returns the
operation id; z_getoperationstatus/-result give the round's result,
and z_consolidationstatus records it as a last_round with manual=true.

It refuses while the node is syncing (the test ChainTip applies to the
periodic ops), while the wallet is locked, and while a consolidation,
zsweep or autoshield round is in flight. It takes the scheduler's slot
like RunSaplingConsolidation does (fConsolidationRunning plus the op
id), so sweep and autoshield defer to it and its completion releases
the slot. The scheduler no longer pops a z_consolidate op from the
queue when it starts the next round, so the user's result stays until
z_getoperationresult collects it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 11:09:20 -05:00
DanSandClaude Opus 5.5 e5791fea71 wallet/rpc: make z_consolidationstatus report what consolidation does
z_consolidationstatus reported amount_consolidated from an int that
nothing ever added to (so always 0, and it would have overflowed past
21 DRGX), no policy, nothing about the rounds, and no hint of why a
round would not run.

Each consolidation op now records its round in CWallet's
consolidationStats when it finishes (the op-id-guarded block in
main(), so on success, failure and exception alike): tip height,
time, txids, notes merged, amount merged and created, fees, notes
skipped for a bad witness, and the error that stopped it, if any.
The cumulative totals come from the same records.

z_consolidationstatus keeps its fields (amount_consolidated now
accumulates, in puposhis like consolidationtxfee) and adds the policy
settings, rounds, txs_created, notes_consolidated, last_round and a
disabled_reason like z_autoshieldstatus has: off, wallet locked,
syncing (the same test ChainTip applies), or deferred while zsweep or
autoshield runs. With the new optional verbose argument it also counts
every address's eligible notes and says which are over the threshold;
that walks the wallet under cs_main + cs_wallet, so only on request.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 10:49:38 -05:00
DanSandClaude Opus 5.5 b4513498e5 wallet: say what the startup witness check did
VerifyAndSetInitialWitness logs one line per reseeded note and nothing
else, so the pass that root-checks every note after a start (seconds on
a large wallet) is invisible, and the reseed line's "<i> of <N>" reads
like progress although <i> is the tx's place in mapWallet and <N> is
mapWallet.size(): transactions, not notes.

Append "[reseed <k>]", the running count of reseeded notes, to the
reseed line. Its prefix, the comma after the hash and " of <N>" stay
exactly as they were: ObsidianDragon parses them (the hash between
"for tx " and the comma, the number after " of ") to track progress.

Add one summary line at the end of a pass that validated or reseeded
anything: the notes validated, reseeded, already valid and ahead of the
chain, the lowest witness height and the elapsed ms. A routine block
with nothing to check prints nothing new.

Logging only; the counters feed no decision.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 10:48:35 -05:00
DanSandClaude Opus 5.5 bc3867a312 wallet: compute the witness roots of the startup check on worker threads
After every start the first VerifyAndSetInitialWitness pass checks each
note's witness: front().root(), compared with hashFinalSaplingRoot at
the witness height. root() walks the whole depth-32 path, about
1.7-2.4 ms per note, serially and with cs_main and cs_wallet held:
about 14 s for 8,200 notes on regtest, 28-39 s for a 16k-note wallet.
With the witnesses now saved at shutdown this pass no longer hides
behind the rescan; it holds the first block after start, and every RPC
waiting on those locks, for that long, and a stop sent meanwhile waited
for all of it.

Compute those roots first, the way BuildWitnessCache's Phase 2 spreads
the extension: under the existing locks collect the notes the loop will
call root() for (confirmed tx, full viewing key, nullifier, witnesses,
witnessHeight > 0, not yet validated, block at witnessHeight on the
active chain), compute their roots on -witnessbuildthreads threads (one
per core by default; inline below 8 notes, or for any shard whose
thread cannot start), then run the existing loop unchanged, taking each
root from that table. The loop changes a note's witnesses only at that
note's own turn (a sibling's reseed rewrites nullifiers, never
witnesses), so every root is the root of the witness being checked and
the validated/reseeded decisions, their order and nMinimumHeight are
those of the serial code. A note the selection misses, or whose root()
threw on a worker, gets its root computed inline as before, so a throw
surfaces at the same note. The root-equality check and the reseed on a
mismatch are untouched.

Between the two phases nothing has been changed yet, so a stop
requested while the roots are computed ends the pass there; the next
block or the next start redoes it.

The thread-count and thread-start-with-fallback code is shared with
Phase 2 (WitnessThreadCount, RunWitnessShards), with the same results.

On regtest (U.base, 24 threads): 2,063 roots in 920 ms against 3.2-4.2 s
for the serial pass. The new gtests run the same synthetic wallet with
one thread and with several and compare every note's resulting state,
including a root mismatch whose reseed throws mid-pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 10:44:55 -05:00
DanSandClaude Opus 5.5 4d7de7a0eb init: do not leave chain DB pointers dangling in the block-index load loop
The load loop deleted pcoinsTip, pcoinsdbview, pcoinscatcher and
pblocktree before reopening them without resetting the pointers. If a
reopen throws (e.g. a corrupt or unopenable blocks/index), the outer
handler reports "Error opening block database", AppInit2() returns false
and Shutdown() then calls FlushStateToDisk() on, and deletes, the
already freed objects: a use-after-free and double delete on the exit
path. Null each pointer right after its delete, as the previous commit
already did for pnotarizations.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 10:44:43 -05:00
DanSandClaude Opus 5.5 a7adcbc954 init: make the notarizations DB open fallback lock-aware
Any failure to open the notarizations DB used to be treated as
corruption: the previous notarizations.corrupt was remove_all()ed, the
live directory renamed over it and a fresh DB created. The common
failure is not corruption at all but "IO error: lock .../LOCK: Resource
temporarily unavailable" from a previous dragonxd that has not finished
exiting, and the fallback then destroyed both the live DB and the last
saved copy. A filesystem exception from remove_all()/rename() also
escaped into the outer handler and failed startup with a spurious
"Error opening block database".

Move the logic into OpenNotarizationDB():

 - if notarizations/LOCK is held (probed with leveldb's own
   Env::LockFile, i.e. the lock DB::Open takes), log once that we are
   waiting for a previous dragonxd, wait up to 30 s in 1 s steps
   (abandoned on a shutdown request) and retry; if it is still held,
   run this session on an in-memory notarizations DB and leave the
   on-disk one untouched;
 - only a DB that fails to open with the lock free is moved aside, now
   to a timestamped notarizations.corrupt-YYYYmmdd-HHMMSS name, so an
   earlier copy is never deleted;
 - a failed move-aside or recreate falls back to an in-memory DB
   instead of throwing: the DB is non-essential and regenerable and
   must never fail startup.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 10:42:30 -05:00
DanSandClaude Opus 5.5 a800a266e5 wallet: consolidate with the threshold/batch policy, lock only its notes
The consolidation op now plans its round with PlanSaplingConsolidation:
only addresses holding more than -consolidationthreshold eligible notes
(GetFilteredNotes at depth 11, as before), up to -consolidationmaxtxs
transactions per address, each spending up to -consolidationbatchsize
of the address's smallest notes back to it, with GetRand rather than
rand() varying the input count. Each transaction is shaped as before:
N spends, one real output to the same address, 7 Sietch dummy outputs,
expiry at tip + AUTO_OP_EXPIRY_DELTA, and the fee unless the notes are
worth no more than it (then none, as sweep does).

Two fixes ride on the rewrite:

- The op locked every eligible note in the wallet, and only after
  proving, so a send made during a round saw no funds at all, while
  one made during the proving could pick the very notes being spent.
  It now locks exactly the notes it plans to spend, at planning time
  under the wallet lock, and unlocks them on every exit (main()).

- One note with a missing or desynced witness ("Missing Witnesses!
  Stopping.") failed the whole round, every round. It is now dropped,
  logged once with its txid:index, and the round re-planned without it.
  Per address, the witnesses come from one GetSaplingNoteWitnesses
  call, so all of an address's spends share its majority anchor.

The scheduler snapshots the policy into the op when it enqueues it,
and skips a round (one interval) while the wallet is locked, as
autoshield does, instead of enqueueing one that can sign nothing.

Options: -consolidationthreshold (25), -consolidationbatchsize (15,
clamped to 2..50 and the tx size) and -consolidationmaxtxs (3, 1..100)
are new. -consolidationinterval below 5 is now clamped to 5 with a
warning instead of silently reset to 25; -consolidationtxfee is range
checked like -autoshieldfee ([1000, 10000000], else the default). The
policy is parsed even with -consolidation off, for z_consolidate.
-consolidatesaplingaddress must now be a Sapling address the wallet
holds the spending key of (startup error otherwise), except the zsweep
address -zsweep substitutes, which may be external as before. It is
resolved once at startup instead of on every round.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 10:37:33 -05:00
DanSandClaude Opus 5.5 693f81bbba wallet: save witnesses and the best block at a clean shutdown
FlushStateToDisk writes the wallet's SetBestChain at most once an hour,
the shutdown flush included, and its timer starts at "now" on the first
call. A session shorter than an hour therefore never saves: the next
start rescans every block of the session ("Rescanning last N blocks"),
re-extends every note witness across it, and then rewrites the whole
wallet inside init before RPC answers. Measured on regtest with a
throwaway prototype: restarts of 8.3 s -> 2.0 s (150 empty blocks),
29 s -> 2.5 s (150 blocks, 639 commitments), 66 s -> 8.5 s (8,215 notes,
631 MB wallet). The cost moves to the stop, at about 41 MB/s of
wallet.dat.

Add CWallet::PersistStateAtShutdown(), called from Shutdown() inside
the existing cs_main block right after the chainstate flush and before
the coins view and the wallet are torn down. It calls
SetBestChain(chainActive.GetLocator()), which on this tree stamps
pindexWalletTip, the block the wallet's state reflects, in the same
atomic transaction as the witnesses. It logs "Saving wallet state ..."
first, so a GUI can show that the stop is busy, and then the height,
the txs written, the elapsed ms and whether it committed. It skips the
write, and logs why, when:

- AppInit2 did not run to the end (new fInitCompleted): threads were
  interrupted but not joined, and with no wallet tip SetBestChain would
  stamp the chain tip over an interrupted rescan's checkpoint;
- the shutdown came from the wallet failing on a block
  (NotifyWalletsOrShutdown now sets fWalletNotifyFailed), or the BDB
  environment has panicked or a checkpoint/lsn_reset failed (new
  CDBEnv::IsHealthy()): a full-wallet write into that database fails
  or deepens the damage, and the logs are what recovery needs;
- nothing changed since the last committed save. SetBestChain now
  returns SetBestChainINTERNAL's result (the CValidationInterface hook
  returns bool) and, when it committed, records the block it stamped
  and a generation counter that BuildWitnessCache (when it extended),
  DecrementNoteWitnesses, VerifyAndSetInitialWitness reseeds,
  ClearNoteWitnessCache and AddToWallet (a note-bearing tx inserted or
  changed) bump. Init records the same when it finds the locator at
  the tip and does not rescan. This also stops a second full write
  when the hourly SetBestChain happens to fire in the shutdown flush.

FlushStateToDisk and DATABASE_WRITE_INTERVAL are unchanged: dropping
the throttle for FLUSH_STATE_ALWAYS would also rewrite the whole wallet
on every gettxoutsetinfo and on the init flush after a replay.
witnessRootValidated stays in memory only, so every witness is still
root-checked against hashFinalSaplingRoot on the next start, and a kill
during the write rolls back to the previous save (DB_RECOVER).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 10:36:23 -05:00
DanSandClaude Opus 5.5 cbd5f8dce4 init: do not rename the main thread in Shutdown()
Shutdown() called RenameThread("hush-shutoff") on the main thread. On
Linux that sets /proc/<pid>/comm, i.e. the process name, so for the
whole shutdown (wallet flush, chainstate flush, LevelDB closes) the node
no longer matched 'pgrep -x dragonxd' / pidof while it still held the
datadir and LevelDB locks. pgrep-based restart scripts took that as
"exited" and relaunched it early; on regtest pgrep stopped matching
about 1 s after 'stop' in 10/10 runs while the old process was alive.

Keep the process name until exit. Worker threads keep their own names.
Nothing depends on "hush-shutoff": no hit in src/, qa/, contrib/ or
util/, and the ObsidianDragon GUI only works around the rename by also
checking the exe link.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 10:26:20 -05:00
DanSandClaude Opus 5.5 3859a8ce22 wallet: plan consolidation rounds with a threshold/batch policy
Sapling consolidation picks notes in wallet order, a random 1..8 of them
per address with rand(), and merges every address with three or more
notes, every round. A miner whose wallet autoshield fills with one note
per round wants the opposite: leave tidy addresses alone, merge the
small notes of the crowded ones in bounded batches, and never re-merge
the big note an earlier round produced.

Add that policy as a pure function the op can use and the tests can
drive: PlanSaplingConsolidation() takes each address's eligible note
values and returns the round's batches. Only an address with MORE than
the threshold of notes (default 25) is consolidated; its notes are taken
smallest first, up to maxtxs transactions (default 3) of a per-tx input
count drawn from [max(2, ceil(2*batch/3)), batch] (default batch 15,
clamped to 2..50 and to what fits in MAX_TX_SIZE_AFTER_SAPLING next to
the 1 + 7 Sietch outputs). A transaction never takes an address's last
note, so the address stays spendable while the round confirms, and
batches never mix addresses. The randomness is the caller's (the op
will pass GetRand).

The option defaults live with the other auto-op defaults in wallet.h.
Nothing calls the planner yet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 10:25:59 -05:00
DanSandClaude Opus 5.5 f09f5a7b95 init: close the notarizations DB in Shutdown()
Shutdown() deleted pcoinsTip, pcoinsdbview and pblocktree but never
pnotarizations, so notarizations/LOCK was the one LevelDB lock still held
after "Shutdown: done". It was only released when the process was torn
down, after the static datadir .lock had already been released. A
successor started in that window took .lock, blocks/index and chainstate
and then failed to open notarizations/LOCK (EAGAIN), which the open
fallback "fixed" by moving the live notarizations DB aside and wiping it.

Delete it under cs_main next to pblocktree, and null the pointer after
the delete in the block-index load loop so a throwing reopen can never
leave it dangling for Shutdown() to delete twice.

Every user of pnotarizations now treats NULL as an empty DB
(GetBlockNotarizations, GetBackNotarization, ScanNotarizationsDB,
ConnectNotarizations, DisconnectNotarizations; crosschain.cpp,
rpc/crosschain.cpp, hush_nSPV_fullnode.h and hush_dailysnapshot only
reach it through those), so a straggler after Shutdown() cannot
dereference it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 10:23:20 -05:00
DanS 09fa5c7b5f Merge branch 'dev' for the v1.3.1 release 2026-10-27 15:27:37 -05:00
DanSandClaude Opus 5.5 fe988d6fbe release: bump to v1.3.1
dev is 22 commits past the v1.3.0 tag and still stamped 1.3.0, so a
release built from it would be indistinguishable from v1.3.0 on the wire,
in getnetworkinfo and to the wallet's updater.

Bump REVISION, not MINOR: the delta is bug fixes and wallet performance.
It adds no subsystem, and the new RPC-visible options (-notecachewarmup,
-checknotecache) are debug-help only.

  configure.ac, src/clientversion.h  1.3.0 -> 1.3.1 (CLIENT_VERSION 1030150)
  doc/man/*.1                        version strings restamped
  contrib/debian/changelog           1.3.1 entry
  src/chain.h                        the CLIENT_VERSION comment

The man page content needs no regeneration: every option in
`dragonxd --help` at 3032eb786 is already in dragonxd.1, and the two new
options appear only in -help-debug.

No consensus change since v1.3.0, so PROTOCOL_VERSION and
MIN_PEER_PROTO_VERSION are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 15:27:25 -05:00
DanSandClaude Opus 5.5 3032eb7868 wallet/rpc: gather Sapling keys once per history RPC, not per output per address
zsWalletTxJSON (z_listsentbyaddress, z_listreceivedaddress, getalldata)
runs once per wallet tx under LOCK2(cs_main, cs_wallet). For every
shielded output it copied the wallet's address set, and for each address
fetched the spending key, re-derived its full viewing key (an
elliptic-curve operation), and trial-decrypted the output; the sends side
did the same with the ovk. Every received or sent note in a tx with
spends walked the whole wallet in GetNullifiersForAddresses for the
change check. The spends side decrypted every spent note again and
deep-copied its SaplingNoteData (witnesses included). The GUI runs
z_listsentbyaddress over the whole wallet on every launch.

SaplingHistoryKeys, built once per RPC call, holds each address with a
usable spending key (in GetSaplingPaymentAddresses order, with its ivk
and ovk as the spending key gives them, and its ivk as
GetSaplingIncomingViewingKey gives it). It also gives the change check
as a lookup into the wallet's (ivk, nullifier) pairs, collected on first
use. The helpers keep their exact structure and quirks. Each output's
JSON object and change flag still accumulate across the addresses that
decrypt it. Diversified addresses sharing a key still produce one entry
each. An unknown address still checks change under a zero ivk. A locked
wallet still reports no shielded received or sent entries. Only the
repeated work is gone:

- each output is decrypted at most once per distinct key. Once it is
  known which ivk decrypts an output, no other ivk is tried: the cached
  plaintext, or a decryption under the ivk the wallet's note data
  records. Two canonical ivks can't both pass the note commitment check,
  which pins pk_d = [ivk]g_d;
- outCiphertexts are decrypted once per distinct ovk; the t->z shielding
  ovk is derived from the seed once per tx;
- spends use the cached plaintext of the spent note.

Two deliberate behaviour changes. The spends helper looked notes up with
operator[]: it inserted a null-outpoint entry into
mapSaplingNullifiersToNotes for every other wallet's nullifier it met.
After getalldata or z_listsentbyaddress had run, z_viewtransaction of
any tx spending someone else's note (every incoming z->z payment) failed
with map::at. And with an inconsistent nullifier map, it inserted an
empty note into a wallet tx. The helpers now only read the wallet. Also,
if the walletpassphrase timer relocks the wallet during the call, the
whole call reports the keys as of its start; the old per-output lookups
switched over partway.

test_wallet_history.cpp holds 69bb035e7's helpers verbatim (renamed)
and a wallet exercising every branch:
- default and diversified addresses, a viewing-key-only address, and a
  key imported after its note arrived;
- z->z sends with change, and with text, empty and binary memos;
- a send nobody's ovk reads, and a t->z shielding send;
- our spends, someone else's, and a mixed tx.
Every tx x every return type x nine address filters gives byte-identical
JSON: with the plaintext cache warm, cold, and on an encrypted wallet
both locked and unlocked. Mutation-checked: dropping the ivk check from
the uniqueness shortcut fails the test. DoesNotModifyTheWallet pins the
read-only change (and shows that the old helpers did insert the foreign
nullifier).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 08:16:09 -05:00
DanSandClaude Opus 5.5 7c3563cd5a wallet/rpc: order history RPC txs by pointer, not by deep copy
getalldata, z_listreceivedaddress and z_listsentbyaddress build a
map<int64_t, CWalletTx> of the whole wallet, keyed by nOrderPos, before
any filter runs. Every insert deep-copies the CWalletTx, including each
note's witness list (~100KB per note on a mainnet wallet). That is
gigabytes of allocation per call on a large wallet, under
LOCK2(cs_main, cs_wallet). The GUI's history scan runs
z_listsentbyaddress on every launch and about once per new tip.

The map now holds const CWalletTx* into mapWallet. It is still a
std::map, so the first tx inserted for an nOrderPos wins, exactly as
before. mapWallet can't change while the RPC holds cs_wallet, so the
pointers stay valid. Output is unchanged for a consistent wallet. One
corner case differs: with a nullifier map entry pointing at a note
its tx lacks, the spends helper's operator[] inserts an empty note into
that tx, and a later iteration now sees it where the old copies didn't.
The next commit removes that insertion.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 08:16:09 -05:00
DanSandClaude Opus 5.5 190023f85f wallet: note-cache review follow-ups
- UpdatedNoteData now keeps the incoming plaintext when it keeps the
  wallet's own entries. When it returns "unchanged" (equal note data,
  or SaplingNoteDataIdentical), any entry lacking a plaintext takes the
  incoming one, for the same outpoint and ivk only. The startup rescan
  replays loaded txs with FindMySaplingNotes' freshly decrypted data;
  that plaintext was thrown away, so the warm-up decrypted those notes a
  second time. The cache is outside every comparison, so the function
  still returns false and nothing is rewritten.
- -checknotecache is read once at init into fCheckNoteCache, instead of
  a mapArgs lookup on every GetFilteredNotes call. Its help text and
  comment now say what it checks: every note the walk considers, before
  the address filter, so a corrupt cached address can't drop a note
  unchecked.
- GetFilteredNotes pre-sizes its result only when there's no address
  filter, so a one-address call no longer reserves room for the whole
  wallet.
- WarmSaplingNoteCache returns its counts (notes, filled, no such
  output, undecryptable), and FillSaplingNoteCache records the threads
  it used, so tests can tell the cases apart.
- WarmSaplingNoteCache's comment no longer claims nothing can wait on
  cs_wallet while it runs: the RPCs allowed during warmup can.

Tests:
- ReplayWithPlaintextIsNoUpdate pins the rule that the plaintext cache
  stays out of the "did this tx change?" decision. A rescan replays a
  witnessed note loaded without plaintext, using FindMySaplingNotes'
  data that carries one. That must be no update: no rewrite, and the
  witness and nullifier are kept. The stored entry then gains the
  plaintext. Checked by mutation: with cache presence added to
  SaplingNoteDataIdentical, this test fails and every other test still
  passes.
- ParallelFillMatchesSerial uses 460 notes and asserts the thread count.
  So the 7-thread case really runs 7 threads, with uneven shards
  (460 % 7 != 0). Before, it was capped at 4 and repeated the 4-thread
  case.
- ColdParallelFillMatchesLegacy: a cold GetFilteredNotes over ~270
  candidates fills on 4 threads and matches the 69bb035e7 loop entry
  for entry.
- WarmUpSkipsBadNotes asserts the warm-up's separate counts (1 no such
  output, 2 undecryptable), so removing the out-of-range guard is now
  caught.
- CachedPlaintextMatchesFreshDecrypt checks exact counts.
  CheckNoteCacheRepairsADifference also tampers with a memo, and looks
  entries up by outpoint. The meaningless GetHash check is dropped.
- A ScopedArg / ScopedCheckNoteCache RAII helper restores -args and
  fCheckNoteCache even when an assertion returns early.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 08:16:09 -05:00
DanSandClaude Opus 5.5 23877e1038 wallet: -checknotecache, a diagnostic for the note plaintext cache
With -checknotecache=1 (debug help), GetFilteredNotes decrypts every
note it returns again. If the cached plaintext differs from the fresh
decryption, it logs the note and replaces the cache entry with the
fresh value. It costs the full decryption the cache exists to avoid, so
it is off by default; it is there for validating the cache on a real
wallet, or for diagnosing a suspected cache problem in the field.

CheckNoteCacheRepairsADifference: by default a tampered cache entry is
returned as is (the cache is trusted); with the option it is repaired
and the fresh value is returned.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 08:16:09 -05:00
DanSandClaude Opus 5.5 43635b7fd7 wallet: decrypt big note-cache batches on worker threads
The startup warm-up, or a lazy fill after -notecachewarmup=0, decrypts
the whole wallet: ~0.5ms per note, ~6s serial for 12k notes. Each
decryption is independent: it reads its own output and writes only its
own note's cachedPlaintext. So FillSaplingNoteCache now splits batches
of 128 or more notes round-robin across -witnessbuildthreads (default:
hardware_concurrency) workers, at least 64 notes per thread. It follows
BuildWitnessCache's Phase 2 pattern:

- the caller keeps cs_wallet held throughout;
- workers take no lock and assert none; under DEBUG_LOCKORDER a fresh
  thread has no lock stack;
- per-shard fill counters are summed after join;
- nothing escapes a worker: a throwing decryption leaves that note
  unfilled, like one that doesn't decrypt;
- if the OS refuses a thread, the remaining shards run inline.

librustzcash is already called concurrently by BuildWitnessCache's
workers, and libsodium is thread-safe after sodium_init.

ParallelFillMatchesSerial: 300 notes across two keys and diversified
addresses decrypt to exactly the same cache with 1, 4 and 7 threads.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 08:16:09 -05:00
DanSandClaude Opus 5.5 83a14a7bfb wallet/init: decrypt every wallet note into the plaintext cache at startup
The plaintext cache is in memory only, so a restart empties it. Without
a warm-up, the first balance call after a restart decrypts the whole
wallet under LOCK2(cs_main, cs_wallet): ~6s for a 12k-note wallet. That
is the observed failure: restart, the GUI connects, and the node looks
stuck.

CWallet::WarmSaplingNoteCache decrypts every note whose plaintext isn't
cached, spent ones included, because z_listreceivedbyaddress
(ignoreSpent=false) is called once per address by the GUI's history
scan.

init runs it at the end of the wallet block, just before
SetBroadcastTransactions. At that point RPC is still in warmup (it
shows "Decrypting wallet notes...") and the wallet notification
thread, whose startup witness rebuild can hold cs_wallet for a long
time, has not started yet. It takes cs_wallet only. -notecachewarmup=0
(debug help) skips it, which leaves the lazy fill in GetFilteredNotes
to do the work.

Unlike GetFilteredNotes, the warm-up never asserts. A note that doesn't
decrypt under its ivk, or names an output its tx lacks, is counted in
the summary line and listed under -debug=zrpcunsafe. A corrupt note
therefore can't stop the node from starting, or from serving the
key-export RPCs allowed during warmup; GetFilteredNotes still asserts
on it, as before.

Tests:
- WarmUpFillsEveryNote: spent, locked, unconfirmed and stale-block
  notes included; walks afterwards decrypt nothing.
- WarmUpSkipsBadNotes: undecryptable and out-of-range notes are skipped
  without aborting.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 08:16:09 -05:00
DanSandClaude Opus 5.5 b1e3c5230a wallet: cache each Sapling note's decrypted plaintext in memory
GetFilteredNotes, the walk behind every balance and note-listing RPC,
sweep, consolidation, z_sendmany and z_mergetoaddress, decrypted every
note it looked at on every call: ~0.5ms of Jubjub arithmetic per note,
under LOCK2(cs_main, cs_wallet). A note's plaintext is fixed by its
output (the txid commits to the ciphertext) and the ivk that decrypts
it, so it never needs to be decrypted twice.

SaplingNoteData gains an in-memory-only
boost::optional<SaplingNoteCache> {note, memo}; the address is the
note's (d, pk_d). It follows the witnessRootValidated precedent:
- never serialized, and left out of operator== and
  SaplingNoteDataIdentical, so filling it never makes a tx look changed
  and get rewritten (the replay rewrite storm 69bb035e7 removed);
- FindMySaplingNotes fills it from the decryption that found the note
  (both the spending-key and the viewing-key-only loop);
- UpdatedNoteData's replace branch keeps a plaintext the wallet already
  had, for the same outpoint and ivk only;
- GetFilteredNotes now runs in two passes: pass 1 applies the tx,
  spent and locked filters and collects the notes that pass; whatever
  lacks a plaintext (everything after a restart, until the startup
  warm-up in a later commit) is decrypted once via the new
  FillSaplingNoteCache; pass 2 applies the address and spending-key
  filters and emits entries in the same order as before.
Spentness, spendability, lock state and depth are still decided on every
call; only the plaintext is cached.

The A0 equivalence test passes unchanged (warm). New tests:
- ColdCacheMatchesLegacy: the same grid with the cache dropped before
  every call;
- CachedPlaintextMatchesFreshDecrypt: eager and lazy fills;
- WarmPassDoesNotDecrypt: a fill counter shows a warm walk decrypts
  nothing, and spent or locked notes only when the caller asks for
  them;
- CacheNeverSerialized: byte-identical SER_DISK/NETWORK/GETHASH output,
  empty after a load;
- UpdatedNoteDataAndTheCache: no rewrite on a cache-only difference,
  carried on replace, never across another ivk;
- SpendabilityNotCached;
- FindMySaplingNotesFillsCache.

Memory: ~616 bytes per note (the memo is 512), ~8MB for a 13k-note
wallet, next to ~100KB per note of cached witnesses.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 08:16:09 -05:00
DanSandClaude Opus 5.5 7ddd03d86d zcash/wallet: decrypt a Sapling note's plaintext and note in one pass
SaplingNotePlaintext::decrypt(ciphertext, ivk, epk, cmu) derives
pk_d = [ivk]g_d to check the note commitment, then throws it away. The
wallet then calls ivk.address(d), which derives pk_d again, and
plaintext.note(ivk), which derives it a third time. Each derivation is a
Jubjub scalar multiplication, ~115us, measured. Including the key
agreement and the commitment check, the whole sequence is ~775us per
note.

decrypt_with_note() runs the same decryption and checks and returns the
note built from that pk_d. ivk_to_pkd succeeding already implies a
valid diversifier, which is all ivk.address() checks on top. It gets its
own name rather than a decrypt() overload: an overload taking a fifth
argument by non-const reference would capture calls meant for the
(epk, esk, pk_d, cmu) variant. The cmu check stays.

GetFilteredNotes and FindMySaplingNotes' spending-key loop use it. That
saves two of the three derivations per note in every balance walk, and
one per found note during scans and rescans (trial decryption of
outputs that aren't ours still fails at the AEAD, as before).
FindMySaplingNotes also no longer copies each OutputDescription.

New tests: MatchesDecryptThenNote checks decrypt_with_note field for
field against decrypt() + note(ivk), over default and diversified
addresses, a wrong ivk and a wrong cmu. FindMySaplingNotes pins what
discovery returns: notes per key, diversified addresses to register,
foreign outputs ignored. Both pass before and after the switch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 08:16:09 -05:00
DanSandClaude Opus 5.5 bfec5c74ae gtest: notecache review fixes
- Take LOCK2(cs_main, cs_wallet) before adding keys in SetUp: both
  AddSaplingZKey and AddSaplingIncomingViewingKey assert cs_wallet is
  held, which aborts a DEBUG_LOCKORDER build.
- TIP_HEIGHT becomes a namespace-scope constexpr. As a static class
  member it was ODR-used by EXPECT_EQ without a definition, which fails
  to link as C++11 at -O0.
- TearDown restores the previous chainActive tip and erases only the
  mapBlockIndex entries the fixture inserted.
- Add a tx mined only in a stale side block. The legacy tx_height model
  returns that block's height, as a txindex can, and the tx must still
  be excluded at every minDepth.
- The encrypted variant asserts HaveSaplingSpendingKey directly, and a
  new test unlocks the keystore and checks GetSaplingSpendingKey (the
  other loop the crypter change touched).
- The legacy-loop comment now says its two LogPrintf lines are dropped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 08:16:09 -05:00
DanSandClaude Opus 5.5 21586b353a wallet/rpc: monotonic timers and a quieter default slow-walk line
Review follow-ups to the GetFilteredNotes / RPC timing logs:

- Time with std::chrono::steady_clock instead of GetTimeMicros(), which
  is the system clock. A wall-clock step otherwise writes false
  ">= 500ms" lines unconditionally; on a WSL2 host the clock was seen
  stepping +3.6s every ~32s.
- A long-poll getblocktemplate deliberately blocks (with cs_main
  released) until a new block arrives, so it is logged only under
  -debug=bench.
- Log the method as "RPC method=<name> took <n>ms". A bare " rescan "
  token followed by "<n>ms" matches ObsidianDragon's rescan-finished
  log heuristic.
- The always-on slow-walk line keeps just the filters and the walk
  time; the wallet-size counts (txs, notes, spent, entries) are logged
  only with -debug=bench, so a shared debug.log doesn't carry them.
- The -txindex=0 startup line names the version.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 08:16:09 -05:00
DanSandClaude Opus 5.5 34b94e761a wallet: don't copy every encrypted Sapling key on each lookup
CCryptoKeyStore::HaveSaplingSpendingKey and GetSaplingSpendingKey scan
mapCryptedSaplingSpendingKeys with `for (auto entry : ...)`. That copies
each entry (an extended full viewing key plus its encrypted-secret
vector) for every key visited, on every call. GetFilteredNotes'
requireSpendingKey check makes one such call per note, and the history
RPCs make one per output per address: ~22ns per key per call, measured
(11us per note on a 1024-key wallet). Iterate by const reference.

The equivalence test gains a locked, encrypted-keystore variant,
LockedWalletMatchesLegacy, so spendability coming from the encrypted
map is covered too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 08:16:09 -05:00
DanSandClaude Opus 5.5 94967efa7b wallet: take note heights from the wallet's depth, not tx_height()
For minDepth > 1, GetFilteredNotes located each wallet tx's block with
tx_height(), which calls GetTransaction and re-reads the tx from disk
through the txindex. It did this once per wallet tx, transparent ones
included, while holding LOCK2. z_listunspent and z_listreceivedbyaddress
did it once more per returned note. Without -txindex, GetTransaction can
only find a tx that still has unspent transparent outputs. tx_height()
then returned 0 for every fully shielded tx, and the tx was skipped. So
on a -txindex=0 node, sweep and consolidation (minDepth 11) and any
minconf >= 2 call never saw those notes.

The wallet already has the depth, and for an active-chain tx
GetDepthInMainChain is chainActive.Height() - height + 1. The new
HeightFromDepth() inverts that (0 when unconfirmed or off the active
chain) and replaces tx_height() at all three sites. The height only
feeds the == 0 skip and hush_dpowconfs. Both sides hold cs_main for the
whole call, so the tip can't move between the walk and the RPC tail.

On a -txindex node the results are identical: the txindex block and
wtx.hashBlock are the same block. The extended equivalence test now
also covers minDepth 2/11/12/22. On -txindex=0 nodes, fully shielded
notes now show up for minDepth > 1. With -zsweep or -consolidation
enabled, those notes will now be swept and consolidated, so init logs
that once. MinDepthAboveOneUsesWalletHeight pins the new behaviour and
shows that the old path returned nothing without a txindex.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 08:16:09 -05:00
DanSandClaude Opus 5.5 bfc1334565 wallet: walk GetFilteredNotes by reference, cheap filters first
GetFilteredNotes copied every CWalletTx by value before any filter ran,
then copied each SaplingNoteData by value again. Both copies deep-copy
the note's witness list (up to WITNESS_CACHE_SIZE witnesses, ~100KB per
note on a mainnet wallet): ~40us per note per pass, measured. Spent and
locked notes were also fully decrypted (~0.6ms of Jubjub arithmetic per
note) before the spent and locked checks threw them away. -deletetx is
off by default, so spent notes accumulate.

- iterate mapWallet and mapSaplingNoteData by const reference;
- skip txs with no notes of ours before CheckFinalTx;
- read GetDepthInMainChain once per tx instead of 2+N times (cs_main is
  held, so it can't change during the walk);
- run the spent and locked checks before the decryption;
- z_listreceivedbyaddress no longer copies the whole CWalletTx per
  entry to read its time, and z_sendmany's sort comparator takes its
  entries by reference.

The filters have no side effects, so the result set and its order are
unchanged; the A0 equivalence test passes unchanged. One deliberate
difference: a spent or locked note whose ciphertext no longer decrypts
under its ivk is now skipped instead of tripping the decrypt assert. The
new SpentAndLockedNotesAreNotDecrypted test pins this (it aborts on the
old ordering).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 08:16:09 -05:00
DanSandClaude Opus 5.5 b9cdce8e96 wallet/rpc: time GetFilteredNotes walks and slow RPCs
GetFilteredNotes logged "GetFilteredNotes ignoreLocked=N" on every call.
The balance RPCs run it on every GUI poll, so that line was log spam on
a fast wallet, and on a slow one the gaps between its timestamps were
the only timing there was. Those gaps also count lock waits and the
previous RPC's own post-processing.

It now logs one summary per walk: the filters, txs that passed the
tx-level checks out of the wallet total, notes examined, notes skipped
as spent, entries returned, and the walk time. The summary is always
written when the walk takes >= 500ms (that long under cs_main stalls
block connection) and otherwise only with -debug=bench. The line has no
lock-wait figure: every caller already holds LOCK2(cs_main, cs_wallet)
and CCriticalSection is recursive, so the inner LOCK2 never waits.

Lock waits are measured where they happen instead. CRPCTable::execute
logs "RPC <method> took <n>ms" under the same >= 500ms / -debug=bench
rule. The per-locked-note line moves to -debug=zrpcunsafe, since it
logs txid prefixes.

No behaviour change otherwise.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 08:16:09 -05:00
DanSandClaude Opus 5.5 dc8ca4996a gtest: pin GetFilteredNotes behaviour before optimizing it
Adds test_wallet_notecache.cpp: a wallet with Sapling notes at several
depths (spent by a mined tx, spent by an unmined tx, locked, viewing-key
only, never mined, plus txs carrying no wallet notes), mined into a fake
active chain. The fixture undoes everything it puts into the process-wide
chain state (chainActive, mapBlockIndex, pcoinsTip) in TearDown, since all
gtest suites share one process.

LegacyFilteredNotes is the 69bb035e7 loop verbatim, with tx_height()
passed in so the minDepth > 1 branch can be modelled on a -txindex node.
FilteredNotesMatchLegacy compares the real walk against it entry by entry
and in order (z_sendmany sorts the result with an unstable sort) over
minDepth {0,1} x maxDepth x ignoreSpent x requireSpendingKey x
ignoreLocked x address filters. FixtureExercisesEveryFilter checks that
each filter really removes something, so the comparison can't pass
vacuously.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 08:16:09 -05:00
DanSandClaude Opus 5.5 b911189ac6 wallet: don't witness viewing-key-only notes (fixes an abort on the next block)
A note found through an incoming viewing key only (z_importviewingkey)
has no full viewing key behind it. UpdateSaplingNullifierNoteMapWithTx
skips such notes, so they never get a nullifier. VerifyAndSetInitialWitness
treated "no nullifier" as "witness needs reseeding" on every call: it
cleared the note's witness, re-read the block from disk, reseeded it,
and then dereferenced the nullifier that never came. dragonxd aborted
in the txnotify thread (boost::optional "is_initialized" assert) on the
first block confirming a note to such an address, and again after every
restart, before the block index was flushed.

Such a note can't be spent, so it needs no witness. Skip it there; if
its spending key is imported later, it has a full viewing key and the
existing no-nullifier rule seeds it then. SaplingWitnessMinimumHeight
now takes the optional nullifier. A note without one is never extended
by BuildWitnessCache (its pending-note gate requires one), so it must
not lower the rebuild's start height. Every call site that worked before
passes a set nullifier and behaves as before.

The deref came in with the 2020 witness rework (6c48397cf). The new
gtest ViewingKeyOnlyNoteIsNotWitnessed fails on the old code (the note
reaches the reseed path).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 08:16:09 -05:00
DanSandClaude Opus 5.5 7131b3673f qa: add fd-guard, the close() guard and regtest harness that found the double close
shim/ is an LD_PRELOAD guard around close/fclose/dup2/dup3:
- before each close it resolves /proc/self/fd/N;
- it reports, with a backtrace, a non-owner close of wallet.dat,
  database/log.* or blocks/*.dat, and every close that fails with EBADF
  (the second half of a double close);
- FDGUARD_ABORT=1 aborts on the first hit;
- run_tests.sh self-tests it (51 checks).

repro/ runs a shimmed dragonxd on isolated regtest. Each run gets its
own unprivileged network namespace (loopback only). The loads are:
- rpc: a hammer with impatient/RST/half-open clients, work-queue
  bursts and long-polls;
- p2p: TLS peers churned by disconnectnode, ban and kill, plus a raw
  TCP/TLS misbehaver;
- tor: a fake control port;
- mine: mining with blocknotify and autoshield.
tools/tally.py groups the reports by closer. tools/scan_bdb.py finds BDB
pages written into block files.

With the wolfSSL CloseSocket macro in effect:
- p2pmin (300 s) gives one EBADF double close per disconnect;
- the full load (1200 s) gives 930 EBADF closes, 186 non-owner closes
  (37 of wallet/log/blk files) and a 632 KB db.log with BDB0060 PANIC;
- RPC-only and Tor-only loads give none.
After the fix, every count is 0 and db.log stays empty. The README has
the commands and the numbers.

Paths come from the environment (GOLDEN, BIN, RUNS, SHIM, ASMAP and the
Sapling params). Run output goes to $RUNS, outside the tree.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 21:23:01 -05:00
DanSandClaude Opus 5.5 70b35ac11a wallet/db: keep the BDB logs when the shutdown flush fails
CDBEnv::Flush(true) removed database/ (log_archive DB_ARCH_REMOVE, then
remove_all) once mapFileUseCount was empty. It did that even when the
checkpoint or lsn_reset before it had failed, or the environment had
panicked (BDB0060). In those states wallet.dat can be missing committed
changes that only the logs hold:
- a page write failed (EBADF/ESPIPE through an fd closed behind BDB's
  back, the wolfSSL CloseSocket bug), so the page stayed dirty in the
  mpool cache and the checkpoint never completed;
- pages written after the last lsn_reset carry real LSNs that point
  into those logs.
Deleting the logs turned a wallet that the next start's DB_RECOVER would
repair into one that silently lost those changes. A std::terminate kept
the logs; the clean shutdown that ThreadNotifyWallets now does on a
wallet DB error deleted them.

Remember a failed txn_checkpoint or lsn_reset (in Flush and in
CheckpointLSN, which the periodic flush and backupwallet use). Before
removing anything, also check the environment for a panic. get_flags
reports it, and itself fails with DB_RUNRECOVERY once the environment
has panicked. In any of those cases keep database/ and log why. If the
kept logs are unusable, the next start already moves database/ aside
and retries (CWallet::Verify).

WalletDbEnv tests:
- a clean shutdown still removes the logs;
- a panicked environment (DB_PANIC_ENVIRONMENT) keeps them;
- a failed lsn_reset keeps them.
With the old db.cpp only the first passes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 21:23:01 -05:00
DanSandClaude Opus 5.5 5b36d7ad24 validationinterface: shut down cleanly when a wallet block notification throws
ThreadNotifyWallets' block disconnect and connect loops had no
try/catch (only its mempool loop does). A wallet database failure
inside SyncWithWallets or ChainTip escaped the thread, and TraceThread
logs and rethrows, so the node died in std::terminate with nothing
flushed. One example: CWalletDB::ListAccountCreditDebit's "error
scanning DB" after BDB lost its file to the wolfSSL CloseSocket bug.
That is how the pool's node died on 2026-10-12 and 2026-10-16.

Run each block's wallet notifications through NotifyWalletsOrShutdown.
On an exception it logs the error, requests a shutdown, shows the usual
fatal-error message and stops the notifier, leaving pindexLastTip at
the last block the wallet fully processed. Carrying on instead would
leave the wallet behind the chain, missing the block it failed on.
Thread interruption still propagates. The shutdown is requested before
the fatal-error message is shown.

FdDefense.WalletNotifyFailureShutsDownCleanly:
- a throwing notification requests a shutdown, a clean one doesn't;
- a non-std exception is handled the same way;
- boost::thread_interrupted still propagates.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 21:23:01 -05:00
DanSandClaude Opus 5.5 9cb31326e3 main: open block and undo files read-only when they're opened for reading
OpenDiskFile opened every block or undo file "rb+", even for its
fReadOnly callers, so every reader held a writable fd. That's what let
the wolfSSL CloseSocket bug corrupt blocks/*.dat. A P2P double close
took the wallet's BDB fd away; the number was then handed to a block
file opened for a getblock/getdata read; BDB's next wallet page write
landed in it, at offset pgno*4096. On production that destroyed blocks
2,728,132-2,728,161 in blk00011.dat and block 3,356,880 in blk00020.dat.

Every fReadOnly caller only reads through the handle:
- ReadBlockFromDisk, UndoReadFromDisk, both GetTransaction paths and
  hush_blockload read via CAutoFile >>;
- the reindex loop hands it to LoadExternalBlockFile, which reads via
  CBufferedFile;
- the existence check at startup only opens it;
- hush_prefetch only freads.
Open those "rb". A stray write through a reused fd number then fails
(EBADF) instead of silently corrupting a block file. Missing files
still fail to open as before; writers keep "rb+"/"wb+".

FdDefense.ReadOnlyBlockFileIsNotWritable: pwrite through a read-only
block file's fd fails with EBADF, while the writable open still writes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 21:23:01 -05:00
DanSandClaude Opus 5.5 d91e069da3 net: stop wolfSSL's CloseSocket macro from turning P2P closes into double closes
wolfssl/wolfio.h (included by <wolfssl/ssl.h> in net.h) does
`#ifndef CloseSocket / #define CloseSocket(s) close(s)`. Every TU that
includes net.h after that point compiles CloseSocket(x) to a bare
close(x). That includes all 15 calls in net.cpp, among them the ones
in CloseSocketDisconnect and ~CNode. util/sock.cpp's
CloseSocket(SOCKET&), the only thing that sets the handle to
INVALID_SOCKET, was never called from net.cpp. This has been the case
since OpenSSL was replaced by wolfSSL (Hush 9ff756590, 2020), so every
DragonX release is affected.

So CNode::hSocket kept its number after the socket was closed. Every
P2P disconnect closed that same number again, 2 to 4 times:
- CloseSocketDisconnect (net.cpp:572) runs once per disconnect trigger
  (ThreadSocketHandler, SocketSendData, the TLS socket handler,
  ThreadMessageHandler), and each run still saw a valid-looking hSocket;
- ~CNode (net.cpp:2819) then closed it once more.
Meanwhile the socket handler kept FD_SETting, send()ing and recv()ing on
the stale number. In between, other threads get that number from the
kernel's lowest-free-fd rule:
- BDB reopening wallet.dat or database/log.* (ThreadFlushWalletDB, ~11/s);
- fopen("rb+") of a block file for getdata/getblock;
- an HTTP RPC accept.
The stray close then closes it. BDB keeps doing I/O on the dead number:
'wallet.dat: write failed for page N' / 'Illegal seek' / 'BDB0060
PANIC', or silent wallet-page writes into a blocks/blk*.dat that got
the number next. Its failing reads later threw out of ThreadNotifyWallets
(std::terminate). A closed HTTP connection fd makes libevent re-arm
and later close whatever owns that number next ('Epoll ADD ... failed').

Reproduced on isolated regtest with an LD_PRELOAD close() guard:
- one disconnectnode gives exactly one EBADF double close (49
  disconnects, 50 EBADF; with strace and no shim, 29 disconnects gave
  30 'close(N) = -1 EBADF');
- P2P churn alone gives non-owner closes of block files and wallet.dat;
- RPC-only and Tor-only loads give none.
Disassembly of CloseSocketDisconnect and ~CNode shows 'call close@plt'
before this change and 'call CloseSocket(unsigned int&)' after.

Undefine the macro right after the wolfSSL include in net.h; wolfio.h
is include-guarded, so it can't come back. net.cpp gets an #error
tripwire in case it ever does. NetCloseSocket.ClosedNodeNeverClosesAReusedFdNumber
fails on the old code (a closed CNode closes the fd number's new owner)
and passes now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 21:23:00 -05:00
DanSandClaude Opus 5.5 69bb035e7e wallet/main: break the replay -> witness-rebuild -> kill loop on large wallets
A v1.3.0 node with a ~13.6k-note wallet (-dbcache=4084) looked hung for hours:
every start replayed ~62k blocks from a chainstate 26 days stale, then ran a
47-60 min all-core witness rebuild holding LOCK2(cs_main, cs_wallet) (RPC answered
HTTP 500 "Work queue depth exceeded", peers timed out), the GUI killed it before
anything was flushed, and the next start did it all again. Even after escaping,
each new block cost ~30s under LOCK2, so the node fell behind a 36s chain.

D1  BuildWitnessCache: the post-rebuild latch computed witnesses.front().root()
    (~2.4ms) for every pending note on every block, only to feed a log line that
    is printed for bulk rebuilds alone. The anchor check now runs on the Phase-2
    workers and only for a bulk rebuild; the per-block path just sets the latch.
    Phase 2 also runs in parallel whenever the job is big (notes x commitments
    >= 2000), not only for a bulk range, so busy blocks no longer extend every
    note serially. If the OS refuses a worker thread, the remaining shards run
    inline instead of unwinding past joinable threads (std::terminate).

D2  FlushStateToDisk: the coins cache was only flushed on shutdown, gettxoutsetinfo
    or after 24h; on this chain it stays a few MiB, so the size triggers never
    fire and a node that never reached 24h uptime or a clean stop kept its
    chainstate (and block index) weeks behind. Flush at least hourly and every
    DATABASE_FLUSH_BLOCKS (5000) connected blocks -- the latter also inside one
    long ActivateBestChain -- and right after the startup ActivateBestChain when
    it moved the tip.

D3  UpdatedNoteData: a replayed or rescanned tx arrives with FindMySaplingNotes
    data (no nullifier). Witnesses and witnessHeight were carried over but the
    nullifier was dropped, so VerifyAndSetInitialWitness cleared and reseeded the
    witnesses on the next block -- the replay above rewrote 3,750 txs and forced
    the full rebuild. Carry the nullifier with the witnesses, unless the tx was
    re-mined in a different block (its notes moved; reseed as before). When the
    merged data is identical, don't rewrite the tx; just clear the in-memory
    witnessRootValidated so the next block re-checks the kept roots once (a
    rescan still finds and reseeds a witness that went bad, without rebuilding
    the healthy ones). The carry loop no longer deep-copies every note.

    SetBestChain: with hourly coin flushes the wallet locator must not run ahead
    of the async notifier, or a crash permanently skips the blocks it had not yet
    delivered. Stamp the block the wallet's state reflects (pindexWalletTip,
    seeded in init before ThreadNotifyWallets starts -- at the startup rescan's
    checkpoint if that rescan was interrupted -- and advanced contiguously by
    ChainTip), like zcashd's ChainTipAdded. ThreadNotifyWallets no longer hands
    the wallet an empty block after a fatal block-read failure.

Tests: new gtest test_wallet_notedata.cpp (5 tests); 23/23 gtests pass, and the
two core D3 tests fail with D3 reverted. Regtest A/B against master with a
1,008-note wallet: notify-thread CPU per block 1,780ms -> 3ms; worst LOCK2 RPC
stall 1.6-2.9s -> 10-15ms on ordinary blocks and 4.6-7.1s -> ~1.6s on a block
carrying a 40-output self-send; a z_importkey rescan went from 35 reseeds plus a
bulk rebuild (10.6s) to 0 reseeds, same balance; after kill -9 at 150 blocks a
build with a 100-block flush threshold restarted at 100, master at 0. Two
adversarial review rounds; every confirmed finding is addressed here.

Not covered: the hourly SetBestChain/flush paths were reviewed, not exercised
(GetTimeMicros ignores mocktime); no run yet against a copy of a real large wallet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 19:05:45 -05:00
DanSandClaude Opus 5 da191e447d Merge branch 'dev' for the v1.3.0 release
72 commits since 1c3523aac (2026-07-23). Highlights:

  consensus  BLOCK_VALID_CONTEXT no longer overwrites the block validity level
             (6d282db21); dead CBOPRET coinbase price check removed (267e6f7ad);
             PROTOCOL_VERSION 2000000 -> 2000001, MIN_PEER_PROTO_VERSION held.
  sync       DRAGONX checkpoints extended to 3,226,000 -- past the RandomX
             activation at 2,838,976, so the skip-below-checkpoint path finally
             fires (7dc904c96).
  wallet     interrupted rescans no longer hide funds and no longer latch
             fAbortRescan (a6b6f80db); rescan progress is checkpointed when a scan
             is interrupted (c1040028e); salvaged wallets open in a degraded mode
             with hdchain-mismatch detection (5634aed75).
  stratum    stratummine gated behind an explicit flag and hardened (db42091ce);
             low-difficulty shares rejected before spending a RandomX hash
             (fa16e740b).
  release    version bumped to v1.3.0 (af7d9e230) and doc/release-process.md
             corrected -- it previously omitted signing entirely, which is why
             v1.1.0 and v1.2.0 were tagged but never became installable releases.

Soak before merge: ~86 node-hours on c1040028e across all seven seeds, plus the
primary -- the pool's block-template source -- running it in production with the
pool accepting shares. Fleet consensus verified at a common height throughout.

Not included, deliberately: branch audit-fixes-20260901 (two commits, both marked
UNTESTED) stays parked. The ported rpc-tests have never been run green and are not
a gate for this release.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FU87LdsJZiZkfq1eXubpeo
2026-09-01 19:09:04 -05:00
DanSandClaude Opus 5 fc26e2e0a0 doc: stamp the man pages with the release version, not a build sha
The man pages were regenerated at e2e10f6ef from a binary built at af7d9e230 and
carry "v1.3.0-af7d9e230". The release will be tagged v1.3.0, so the shipped man
pages would contradict the tag they ship under -- the same provenance gap af7d9e230
itself was written to close.

A faithful regeneration cannot fix this before the tag exists: gen-manpages.sh reads
--version from the binary, genbuild.sh derives that from `git describe`, and that
only prints exactly "v1.3.0" once the annotated tag is in place. Regenerating after
tagging would mean committing on top of the tag and moving it. doc/release-process.md
anticipates this and documents hardcoding the version instead.

Content is untouched and needs no regeneration: all 150 daemon options in the man
page match `dragonxd --help` exactly, including the five -autoshield* flags.

Not changed: dragonx-tx.1 still describes itself as "hush-tx utility". That string
comes from the binary's own --help, so editing the man page would make it diverge
from what the tool actually prints. It is a binary-level branding fix, not a doc one.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FU87LdsJZiZkfq1eXubpeo
2026-09-01 19:06:54 -05:00
DanSandClaude Opus 5 1d2d5f32d0 version: bump PROTOCOL_VERSION for the v1.3.0 consensus changes
doc/release-process.md requires PROTOCOL_VERSION to increase by 1 for any release
carrying a consensus change. This one does: 6d282db21 stops BLOCK_VALID_CONTEXT
overwriting the block validity level, 267e6f7ad drops the dead CBOPRET price
validation from the coinbase check, and pow.cpp is 157 lines lighter. The value
has not moved since 85c8d7f7d in March.

MIN_PEER_PROTO_VERSION stays at 2000000. It currently equals PROTOCOL_VERSION, so
raising it in step would disconnect every peer still announcing 2000000 -- which is
every user, because no DragonX release has ever been installable: the wallet's
updater pins an ed25519 key and sets kDaemonRequireSignature = true, and no release
has ever shipped a .sig. Bumping only the advertised version lets 1.3.0 nodes be
identified on the wire without partitioning the network on release day.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FU87LdsJZiZkfq1eXubpeo
2026-09-01 19:06:54 -05:00
DanSandClaude Opus 5 c1040028e4 wallet: checkpoint rescan progress when the scan is interrupted
An aborted or shutdown-interrupted rescan discarded all of its progress: nothing
advanced the on-disk best-block locator, so the next run started over. On a large
shielded wallet that is a multi-minute witness rebuild repeated from scratch.

Writes the locator ONCE, at the interrupt, rather than periodically through the
scan. That delivers the whole stated benefit -- "resume where it stopped" -- at
the cost of exactly one SetBestChain per interrupted scan. A periodic checkpoint
would additionally survive SIGKILL and power loss, a much weaker requirement, and
it is the part that carries all the cost: SetBestChainINTERNAL is O(whole wallet)
regardless of progress, so on the reported 5.3k-tx / 7.5k-note wallet a checkpoint
every 2500 blocks would plausibly cost more than the rebuild it was meant to save.
If someone later demonstrates a need for crash resilience mid-scan, add it then,
with a measured interval and fFlush=false -- not before.

Two guards, both necessary:

  - CONTIGUITY. The RPC entry points (rescan / importprivkey / z_importkey /
    z_importviewingkey) take a caller-supplied start height validated only against
    chainActive.Height(), never against the wallet's own persisted locator. A scan
    beginning above that locator must not checkpoint at all, or it would record
    the skipped range as scanned and hide any funds in it. Logged once when it
    applies, so an operator can see why an interrupt did not persist.

  - MONOTONICITY. A checkpoint may only advance the locator, never move it back.

The locator points at the last FULLY PROCESSED block -- the parent of the block we
were about to scan -- so resume restarts one block early. CChain::GetLocator pushes
its argument first and FindForkInGlobalIndex returns that same block, so resume
begins AT it; the one-block overlap is deliberate and idempotent, since AddToWallet
only takes its merge path when the transaction is already present.

No witness work is done at the interrupt, which answers the two "//TODO: should we
update witness caches?" comments this replaces: witnesses are re-derived from each
note's own witnessHeight independently of the locator, and witnessRootValidated is
never serialized, so every note is revalidated against hashFinalSaplingRoot on the
next start. A mid-scan checkpoint does capture notes at mixed witnessHeights -- the
in-loop BuildWitnessCache(pindex, true) returns before the extension phase and only
seeds new notes at their own transaction's height -- but that state is recoverable:
the post-loop BuildWitnessCache(tip, false) levels every note, and it now occurs at
most once per scan instead of hundreds of times.

Uses SetBestChainNoFlush so the checkpoint does not trigger a full BDB
txn_checkpoint over the whole cache, and reports failure rather than silently
leaving the operator to discover the replay.

Depends on the fLastRescanCompleted gate in the previous commit: without it
init.cpp would overwrite this checkpoint with a tip locator immediately after the
scan returns.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FU87LdsJZiZkfq1eXubpeo
2026-08-31 20:54:37 -05:00
DanSandClaude Opus 5 a6b6f80db0 wallet: stop an interrupted rescan from hiding funds, and un-latch fAbortRescan
Two independent fund-visibility bugs on the rescan path, both pre-existing.

1. AN INTERRUPTED RESCAN RECORDED ITSELF AS COMPLETE.

ScanForWalletTransactions returns a bare `int ret` (a found-tx count) on both its
abort and shutdown bail-outs, so the caller could not tell "finished" from
"stopped at block H". init.cpp then ran, unconditionally:

    pwalletMain->ScanForWalletTransactions(pindexRescan, true);
    pwalletMain->SetBestChain(chainActive.GetLocator());   // TIP locator

An interrupted scan therefore stamped the wallet as scanned all the way to the
chain tip. On the next start, the `chainActive.Tip() != pindexRescan` guard just
above sees no work to do and skips the rescan entirely, so every transaction in
the never-scanned range stays out of mapWallet -- permanently invisible to
getbalance and unspendable. That is exactly the case `-rescan` exists for: a key
import, right after ClearNoteWitnessCache has run.

Adds CWallet::fLastRescanCompleted, set false at scan entry and true only on the
normal exit, and gates the init.cpp locator write on it. Deliberately NOT
overloading the int return, which callers already use as a tx count.

2. fAbortRescan WAS NEVER RESET.

wallet.h declares it, AbortRescan() sets it true, and nothing in src/ ever sets
it false. The abortrescan RPC is live. After one call, for the remaining lifetime
of the process:
  - every ScanForWalletTransactions returns immediately, so re-running an import
    silently no-ops while the RPC still reports success;
  - BuildWitnessCache bails on the same flag on EVERY call, including the routine
    per-block extension from ChainTip.
Witness heights then diverge across notes while the chain advances, and
GetSaplingNoteWitnesses elects the majority root as the anchor and returns
boost::none for every note that disagrees. Those notes still show in the balance
but cannot be spent. Cleared at scan entry and consumed in the abort branch.

Also in BuildWitnessCache's abort branch: stop clearing fRescanning. A witness
rebuild is not a rescan and must not touch a flag ScanForWalletTransactions owns.

3. Both bail-out log lines had two format specifiers and one argument:

    LogPrintf("%s: Rescan aborted at block %d\n", pwalletMain->rescanHeight);

tinyformat's "too many conversion specifiers" guard is disabled in this tree
(tinyformat.h: `if(*fmt != '\0' && 0 ) // disabled due to complaints`), so this
does not throw -- verified by compiling the exact call against this tree's
tinyformat.h. It emits "3841207: Rescan aborted at block " with the height in the
__func__ slot, the real height dropped, and the trailing newline swallowed so the
next log line concatenates onto it. On the one path an operator has to diagnose
an interrupted rescan, the only record was corrupt. Fixed at both sites, and the
state updates moved above the log call.

4. Makes SetBestChainINTERNAL report whether the atomic write committed, so a
checkpointing caller can tell (six failure paths returned void). Adds
SetBestChainNoFlush, which opens the wallet DB with fFlushOnClose=false: the
default ctor makes ~CDB run a full BDB txn_checkpoint over the whole cache, which
is fine hourly but not from inside a scan -- the same flush wallet.cpp already
documents avoiding elsewhere "for performance reasons". Nothing calls it yet.

5. SetBestChainINTERNAL took each CWalletTx by value, deep-copying every note's
witness deque (WITNESS_CACHE_SIZE entries) per transaction per call, purely to
serialize it. Now by const reference.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FU87LdsJZiZkfq1eXubpeo
2026-08-31 20:52:40 -05:00
DanSandClaude Opus 5 3aac75e94f cli: report the port actually dialled, not a stale global
dragonx-cli resolves -rpcport correctly -- CallRPC does
  int port = GetArg("-rpcport", BaseParams().RPCPort());
and dials that port. But both connection-failure messages printed
ASSETCHAINS_RPCPORT instead, a separate global defined at the top of
bitcoin-cli.cpp, initialised to the mainnet default 21769, and never assigned
anywhere in the CLI.

So every failure claimed port 21769 regardless of what was asked for:

  $ dragonx-cli -rpcport=21799 getblockcount
  error: couldn't connect to server at port 21769

That reads as "your -rpcport was ignored", which is a much more alarming and
much more misleading diagnosis than "nothing is listening yet". It cost an hour
of debugging on a node that was simply still loading a 15 GB txindex, and led to
the wrong conclusion that the CLI could be talking to the production daemon when
it was not.

Both sites now print the local `port`. Verified against the previous binary:

  new:  -rpcport=21799 -> "couldn't connect to server at port 21799"
        -rpcport=59999 -> "couldn't connect to server at port 59999"
  old:  both            -> "couldn't connect to server at port 21769"

and the CLI still reaches a live daemon on a non-default port.

ASSETCHAINS_RPCPORT is left defined; it is referenced by other translation units.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FU87LdsJZiZkfq1eXubpeo
2026-08-31 17:35:52 -05:00
DanSandClaude Opus 5 5634aed750 wallet: open salvaged wallets in a degraded mode, and detect a mismatched hdchain
A wallet.dat repaired by v1.0.3-or-earlier -salvagewallet could not be opened by
this build at all. Those builds' IsKeyType has no "hdchain" case, so salvage
dropped the record; LoadWallet then returned DB_CORRUPT and told the user to
restore from a seed phrase. There is no such recovery path: the node aborts
before the RPC server exists, -usemnemonic defaulted to 0 in v1.0.3 so many of
these wallets never had a phrase, and SetHDSeedFromMnemonic refuses a non-empty
wallet, so "move wallet.dat aside" discards every non-HD key salvage preserved.

The guard itself was right to refuse to DERIVE -- a missing hdchain falls back to
SetNull defaults, clearing fMnemonicSeed and switching derivation from the
64-byte BIP39 seed to the raw 32-byte entropy, an entirely different key tree.
It was wrong to refuse to OPEN. Split the two:

  - "hdchain" record ABSENT (the salvage signature, tracked by a new
    wss.fHDChainSeen set before any parse attempt) -> open DEGRADED.
  - "hdchain" record PRESENT but unreadable -> still DB_CORRUPT; that signals
    wider file damage.

Degraded means the wallet spends, receives and rescans normally but refuses to
derive any new HD key. Gated at the single choke point GetHDSeedForDerivation
rather than at the two generators, so z_getnewaddress/sendmany/shieldcoinbase
raise a clean error and autoshield skips. hdChain.seedFp is deliberately left
null, which keeps IsHDTransparentEnabled false so getnewaddress falls back to the
legacy random-key path -- gating it instead would break TopUpKeyPool, change
addresses and block templates. -rescan is soft-set because an old salvage also
dropped defaultkey and bestblock, which would otherwise look like a first run and
skip the rescan, leaving a permanently zero balance.

NEW DETECTOR, covering strictly more damage than the guard beside it. A wallet
salvaged by v1.0.3 and then USED on v1.0.3 persists a SetNull-derived hdchain
carrying seedFp=null. On this build fHDChainRead is then true, the guard never
fires, the node starts perfectly clean -- and derives into the wrong key tree
forever, silently. That state is unforgeable by any legitimate writer, since
InstallHDSeed always stores seedFp = seed.Fingerprint(), so compare the loaded
chain's seedFp against the fingerprint taken from the hdseed/chdseed record KEY
(which works while an encrypted wallet is locked) and degrade on mismatch.

Also:
  - init.cpp: abort in the DB_CORRUPT branch itself, as DB_NEED_REWRITE already
    does. Falling through ran several hundred more lines against a wallet just
    declared corrupt, including SetHDSeedOrigin(), which WRITES to it. Error text
    no longer advises -mnemonic (wrong twice over, see above).
  - rpcdump.cpp: z_exportwallet discarded GetHDSeedForDerivation's return and
    emitted the line regardless, so a failure wrote a blank seed next to a
    legitimate-looking BLAKE2b-of-empty fingerprint -- a backup that looks valid
    and restores nothing.
  - Corrected the guard's comment: the saplingAccountCounter half was overstated.
    Both generators loop while(Have...Key(...)), so a low counter walks forward
    past existing accounts rather than colliding with them.

qa/r4-salvaged-wallet-harness.sh builds the victim wallets with the on-disk
v1.0.1 release binary and asserts the behaviour end to end. It REFUSES to run
outside a network namespace and re-checks getconnectioncount==0, because those
old binaries predate the regtest seed-injection fix and would otherwise dial the
live network. 11/11 pass:

  C healthy wallet opens and is NOT flagged   (no false positives)
  A salvaged wallet opens, flagged, persists no hdchain, z_getnewaddress refused,
    getnewaddress still works, z_exportwallet emits no bogus HDSeed line
  B poisoned wallet opens and the seedFp detector fires

Note the harness asserts "no hdchain synthesised", NOT "wallet.dat unchanged":
a control run showed normal startup rewrites wallet.dat for healthy wallets too.

This is the access/detection half. Proving fMnemonicSeed by re-deriving against
held keys, and repairing the record, is deliberately left out: it requires a
write, and the affected population is unmeasured. dev's own salvage already
preserves hdchain, so the class is closed going forward.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FU87LdsJZiZkfq1eXubpeo
2026-08-31 13:29:43 -05:00
DanSandClaude Opus 5 db42091ce3 rpc/net: gate and harden stratummine, keep regtest off the live network, init nSPV filter
stratummine (rpc/mining.cpp), a test-only reference miner, was registered
unconditionally behind a bare #ifndef WIN32 with okSafeMode=true, so it shipped
as a live RPC on every non-Windows release build. Four fixes:

  - Gated behind an explicit, default-off -stratummine, with regtest exempt so
    qa/rpc-tests can still drive it. Deliberately NOT gated on fExperimentalMode:
    that defaults to TRUE (init.cpp:1195), so such a gate is a no-op -- an error
    made and caught while testing this change.
  - mining.notify's three hash fields went straight into uint256(ParseHex(...)).
    uint256's vector ctor asserts on a wrong size (uint256.cpp:30) and NDEBUG is
    defined nowhere in this build, so that assert is live in release; ParseHex
    also truncates silently at the first non-hex character. A short or garbled
    field therefore ABORTED THE DAEMON. Added StratumHex256(), which requires 64
    hex chars and a 32-byte result, and all three fields are validated before any
    is committed so a bad job is rejected rather than half-applied.
  - processLine ran inside the window where the RandomX cache, the VM and the
    socket are live, all released on the normal path only, and every get_str()
    throws on a type mismatch -- so a malformed message leaked 256 MB and the fd.
    Body wrapped in try/catch: ignore the line, keep mining.
  - Caller-supplied timeout clamped to [1, 3600]; it was unbounded, pinning an
    RPC worker and the cache indefinitely. okSafeMode -> false.

Verified against a hostile stratum server on regtest:
  - 4 malformed mining.notify payloads (short hex, non-hex, wrong JSON type,
    31 bytes) -> all rejected, daemon alive, 0 assertions. The 31-byte case is
    the one that previously hit the uint256 assert.
  - valid job first (so RandomX actually allocates) then garbage mid-mine ->
    RSS delta +2.2 MB, i.e. cache and VM released, not the ~256 MB a leak leaves.
  - regtest exemption confirmed: stratummine runs past the gate there.
  The non-regtest refusal path is by code reading only -- a testnet node on this
  host collides with the production daemon's RPC port, so it was not exercised.

hush_utils.h: stop injecting the mainnet node1-node10.dragonx.is addnode seeds
when -regtest or -testnet is set. regtest reuses mainnet's network magic, so a
supposedly isolated node was handshaking production peers and pulling their
headers into its own index. Gated at the injection site only -- isdragonx itself
must stay true, because it also selects ac_private, ac_algo, blocktime and the
reward/halving schedule (an earlier version of this patch gated isdragonx itself
and silently turned ac_private off on regtest). hush_args() runs between
ParseParameters() and ReadConfigFile() (bitcoind.cpp:115/144/158), so this sees a
command-line -regtest, as qa/rpc-tests uses, but not a config-file regtest=1.

hush_nSPV_fullnode.h: initialize `filter` at both sites. It was assigned only on
the len-11 request form; the other two passed uninitialized stack memory to
NSPV_getaddressutxos/NSPV_getaddresstxids, remotely reachable since
HUSH_NSPV_FULLNODE is on by default.

getblocktemplate_proposals.py still passes.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FU87LdsJZiZkfq1eXubpeo
2026-08-31 02:38:38 -05:00
DanSandClaude Opus 5 6d282db216 consensus: stop BLOCK_VALID_CONTEXT overwriting the block validity level
BLOCK_VALID_CONTEXT was 6. The validity levels above it are sequential VALUES
packed into a 3-bit field, not independent bits, so BLOCK_VALID_MASK is
1|2|3|4|5 == 7 and the value 6 sat entirely inside it. `pindex->nStatus |=
BLOCK_VALID_CONTEXT` (main.cpp:5616, and :3285) therefore did not set a flag --
it overwrote the validity level.

Consequences, all long-standing:
  - A header-only block raised to BLOCK_VALID_TREE(2) became 2|6 == 6, which
    reads as >= BLOCK_VALID_CHAIN(4) and >= BLOCK_VALID_SCRIPTS(5). A block
    merely written to disk reported full script validity.
  - Every later RaiseValidity() silently no-opped, because 6 >= every level.
    ConnectBlock's RaiseValidity(BLOCK_VALID_SCRIPTS) was a permanent no-op.
  - CheckBlockIndex's "CHAIN valid implies all parents are CHAIN valid" invariant
    was violated whenever a stored block sat above a still-header-only ancestor,
    i.e. ordinary out-of-order parallel block download. fDefaultConsistencyChecks
    is true only for regtest, so the abort was regtest-only -- but the garbled
    index is written identically on mainnet, where only the detection is off.

Not a v1.3.0 regression: introduced upstream in Komodo fa309e5b0 (2019-04-02),
inherited via Hush, and byte-identical in v1.0.3, which the production network
runs today. Validity was only ever INFLATED, never deflated, so no valid block
was rejected and no invalid block skipped validation -- ConnectBlock's CheckBlock
and full script/proof verification always ran. The user-visible effects were
misreports: getchaintips labelling never-connected forks "valid-fork",
submitblock answering "duplicate" for unvalidated blocks, and ProcessGetData
serving them. The material cost was to QA: multi-node regtest tests aborted the
syncing node at random, making the rpc-test suite unusable.

Moves the flag to 512, the next free bit above BLOCK_IN_TMPFILE(256), and adds
static_asserts that every nStatus flag is disjoint from BLOCK_VALID_MASK so this
cannot be reintroduced silently. nStatus is serialized as VARINT, so the wider
value needs no format change.

Verified under gdb on regtest. A connected block's nStatus:
  before   0x1e  validity field 6            (measured on the previous binary)
  after   0x21d  validity field 5 = SCRIPTS, context bit set
wallet_sapling.py, which aborted the syncing node deterministically, now runs to
completion with no assert.

No migration: the original level is unrecoverable from a polluted entry (1|6,
3|6 and 5|6 all give 7; 2|6 and 4|6 both give 6), and the only safe guess is
downward, which would risk revalidation work on a 3.25M-block index for a
cosmetic gain. Legacy entries simply have the flag bit clear, so they re-run the
contextual check they previously skipped -- more checking, not less -- and
resolve on any reindex.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FU87LdsJZiZkfq1eXubpeo
2026-08-31 02:12:17 -05:00
DanSandClaude Opus 5 c5fde12485 qa: port 12 wallet/mining tests to python3 and fix three framework blockers
Ports qa/rpc-tests from 6 python3 files to 18. Ran every ported test against
the freshly built v1.3.0 dragonxd. Results, honestly:

  PASS (1)            getblocktemplate_proposals.py
  NOT APPLICABLE (7)  wallet.py, walletbackup.py, wallet_protectcoinbase.py,
                      wallet_listnotes.py, wallet_mergetoaddress.py,
                      getblocktemplate.py, wallet_shieldcoinbase.py
  BLOCKED (4)         wallet_sapling, wallet_nullifiers, wallet_persistence,
                      wallet_treestate

The "not applicable" seven are inherited Zcash/Hush-era tests that exercise
features DragonX deliberately removed. They assume transparent t->t value
transfer, but ASSETCHAINS_PRIVATE=1 (hush_utils.h:1826) makes sendtoaddress
and sendmany consensus-refuse; they assume Sprout joinsplits, which are gone
from the RPC layer entirely; and they hardcode Bitcoin economics (10 coin/block,
100-block maturity) against DragonX's 3 DRGX and COINBASE_MATURITY=1. They are
ported and left in place rather than deleted, but they cannot pass on this chain
without being rewritten around z_shieldcoinbase/autoshield.

Three framework fixes in test_framework/util.py, each of which broke every
multi-node test:
  - initialize_chain() passed -connect=0, and init.cpp soft-sets -listen=0 when
    -connect is present, so cache node0 never opened its p2p port and nodes 1-3
    could never sync to it -- initialize_chain() hung forever in sync_blocks().
    Now passes -listen=1 -bind=127.0.0.1 -dnsseed=0 explicitly (an explicit arg
    beats SoftSetBoolArg) while keeping the cache nodes off the public network.
  - cache cleanup removed files from <datadir> when dragonxd writes them one
    level deeper into the net-specific <datadir>/regtest.
  - set_node_times() did print("..." + t) with t an int -> TypeError.
  - default binary paths corrected to src/dragonxd and src/dragonx-cli.

The four BLOCKED tests are blocked by a daemon assert, not by the port; see the
follow-up commit/report on BLOCK_VALID_CONTEXT.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FU87LdsJZiZkfq1eXubpeo
2026-08-31 01:53:43 -05:00
DanSandClaude Opus 5 e2e10f6ef8 doc: regenerate man pages from the v1.3.0 binaries
Previously the version strings were restamped by hand in af7d9e230 because
help2man and a built binary were both unavailable. Regenerated properly via
util/gen-manpages.sh against freshly built v1.3.0 binaries, which also picks
up two options that were never documented:

  -sietch-min-zouts=<n>   decoy Sapling outputs added to each z_sendmany
  -stratumtarget=<hex>    pool share target, for solo/low-difficulty mining

NOTE: the version lines read "v1.3.0-af7d9e230" because `git describe` has
no annotated tag to find yet. Once v1.3.0 is tagged annotated, these must be
regenerated once more so they read a clean "v1.3.0" -- that step stays open
on the release checklist.

Generated on seed 176 (glibc 2.35 runs the binaries; help2man is installed
there and not on the primary), with an isolated HOME so nothing touched the
node's datadir. The reindex running on that box was not disturbed.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FU87LdsJZiZkfq1eXubpeo
2026-08-31 00:23:56 -05:00
DanSandClaude Opus 5 af7d9e2300 release: bump to v1.3.0 and document the signing step that was never performed
The tree stamped 1.2.0 in both configure.ac and src/clientversion.h, but
v1.2.0 is an annotated tag already pushed at fad05d3ab and dev is 27
commits past it. Both trees therefore produced CLIENT_VERSION 1020050 and
announced an identical /DragonX:1.2.0/ subversion, so a released binary
would have been indistinguishable from the tag on the wire, in
getnetworkinfo, and to the wallet's in-app updater -- destroying the only
provenance check users have: build the tag, compare the binary.

Bump MINOR rather than REVISION: the delta since v1.2.0 adds a subsystem
(RandomX stratum) and a new RPC (stratummine).

  configure.ac, src/clientversion.h  1.2.0 -> 1.3.0 (CLIENT_VERSION 1030050)
  doc/man/*.1                        version strings restamped
  contrib/debian/changelog           1.3.0 entry for the 27 commits
  src/chain.h                        stale "CLIENT_VERSION is 1010050" comment

Man page *content* still needs a real regeneration: util/gen-manpages.sh
requires help2man and built 1.3.0 binaries, so it belongs in the release
build, where it will also pick up the new stratum options.

doc/release-process.md is why v1.1.0 and v1.2.0 were tagged but never
became releases. Followed verbatim it produced a release the wallet
refuses to install:

  - it directed releases to a branch named `dragonx`, which does not
    exist; releases are cut on `master`
  - it never once mentioned signing, yet the updater pins an ed25519 key
    and sets kDaemonRequireSignature = true, so an unsigned release is
    refused outright and every user silently stays on their old daemon
  - it did not require the release tag to be annotated, and genbuild.sh
    calls `git describe` without --tags, so a lightweight tag stamps the
    build `v<older-tag>-<sha>` instead of the release version -- which is
    exactly what happened to v1.0.0 through v1.0.3
  - it referenced util/build-debian-package-ARM.sh, which is not in tree

Adds the signing and checksum-table steps, the annotated-tag requirement
with a `git describe` verification, and the rule that a new version must
exceed every existing tag including unpublished ones.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FU87LdsJZiZkfq1eXubpeo
2026-08-30 22:48:52 -05:00
DanS 4cc7e0491a qa: finish the python3 port far enough to build the shared test chain
Follow-up to 5e0a70683, which got start_node() working. Three more
defects sat behind it:

- initialize_chain() builds the 4-node cache with its own daemon
  invocation, which 5e0a70683 did not touch. It therefore still omitted
  -regtest (so those cache nodes ran on MAINNET) and -asmap (so they
  refused to start at all). Every test that uses the cache -- which is
  most of the wallet suite -- died there.

- reindex.py and getblocktemplate_longpoll.py each carried a single
  python2 print statement, which is the whole reason they would not even
  parse under python3. Shebangs updated to match.

The suite still does not pass: initialize_chain hits a remaining py2
str+int concatenation, and getblocktemplate.py reaches a real test
assertion. Both are beyond this commit, but the harness now gets far
enough to start nodes, answer RPC and begin building the shared chain,
which it could not do before.
2026-08-30 21:29:08 -05:00
DanS 5e0a706839 qa: repair the rpc-test harness so it can start a DragonX node at all
The integration suite has never run against DragonX. Six independent
defects stacked up, each only visible once the previous was fixed:

1. test_framework used python2 implicit relative imports
   ("from authproxy import ..."), removed in python3, so every test died
   at import. Made explicit relative imports.

2. It wrote ZZZ.conf -- a Komodo assetchain convention -- while DragonX
   reads DRAGONX.conf. The daemon therefore never saw the generated
   config, fell back to mainnet defaults and tried to bind RPC 21769,
   which on a seed node is already held by the real node.

3. start_node() was hard-wired for the -ac_name=ZZZ assetchain tests: it
   took the RPC port from extra_args[3], passed extra_args[0] as argv[0]
   of the CLI, and only wrote a config when extra_args[0] matched. Any
   test that passes no extra args crashed on len(None). The generic path
   now takes the port from rpc_port(i) -- the same helper
   initialize_datadir() already used -- and drives the CLI with -datadir.

4. dragonxd refuses to start without an asmap file, which no test datadir
   had. initialize_datadir() now provisions one.

5. -asmap relative paths resolve against the NET-SPECIFIC datadir, so a
   copy in <datadir> is never found. Pass an absolute path.

6. Worst: -regtest was only ever set as "regtest=1" in the conf file,
   which DragonX ignores. Every "regtest" node therefore ran on MAINNET:
   real genesis, real seeds, real peers. An observed run synced 196,180
   live blocks and 679MB into /tmp before the test timed out. -regtest is
   now passed as a command-line flag, with -connect=0 so an isolated
   regtest node stays off the public network.

With these, nodes start, RPC answers, and tests run to a real result.
They do not all pass yet -- getblocktemplate.py reaches an assertion --
but that is now a test outcome rather than a harness failure.
2026-08-30 19:44:27 -05:00
DanSandClaude Opus 4.8 60d66022f6 regtest: default -checkpoints off so an isolated node leaves IBD
chainparams_commandline() applies the DRAGONX mainnet checkpoint set to
every SMART_CHAIN_SYMBOL=="DRAGONX" network, -regtest included, so an
isolated regtest node (height ~hundreds) sits far below the top checkpoint
(~3.2M). IsInitialBlockDownload() latches true whenever fCheckpointsEnabled
&& height < GetTotalBlocksEstimate(), so regtest was permanently in IBD --
disabling every ChainTip auto-op that gates on !IBD (autoshield, z_sweep,
consolidation) and the below-checkpoint script-check skip, and forcing
every regtest test to pass -checkpoints=0 by hand.

Default -checkpoints to false on regtest (still overridable with
-checkpoints=1). Verified: a fresh regtest node logs "Leaving
InitialBlockDownload" after a few blocks with no flag, and -checkpoints=1
keeps it in IBD as before.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PGhWvdBSgt6UxxHANr7gfN
2026-08-30 17:26:21 -05:00
DanSandClaude Opus 4.8 3b2aa866aa rpc: honor a command-line rpcpassword across restarts; fix dead -rpcusername key
hush_configfile(), on any restart where the auto-generated DRAGONX.conf
already exists, hard-assigned mapArgs["-rpcpassword"] from the conf and
wrote the username to mapArgs["-rpcusername"] -- a key nothing reads
(InitRPCAuthentication in httprpc.cpp and bitcoin-cli.cpp both read
"-rpcuser"). The hard assignment silently overwrote a -rpcpassword passed
on the command line, so after the first run the effective RPC credentials
became {cmdline-user}:{conf-password}, matching neither the command-line
pair the operator passed nor the full conf pair. Automation or external
clients that connect with the known command-line password broke on every
restart.

Use SoftSetArg for both, so a command-line (or explicitly configured)
value wins and the conf-derived credential is only a fallback. Verified on
regtest: after a restart an external client with the command-line password
gets HTTP 200 and the conf's random password gets 401; the conf-only
operator path (no command-line creds) still authenticates.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PGhWvdBSgt6UxxHANr7gfN
2026-08-30 16:32:20 -05:00
DanSandClaude Opus 4.8 2d6359ea74 gtest: add job_id parser regression test for the 63-char abort fix
Covers b3e81f1ed: a 63-character mining.submit job_id containing any
non-hex byte must never complete to a 32-byte vector, so the EWBF
completion loop skips it instead of constructing uint256() (which
asserts vch.size()==32 and would abort the daemon from an
unauthenticated client).

Five cases pin the invariant using the real ParseHex/uint256 primitives:
all-spaces, a non-hex byte mid-string, and a non-hex byte at the end
never yield 32 bytes; a genuine 63-hex job_id completes to exactly 32
bytes for all 16 digits; plus ParseHex odd/even-length anchors. Wired
gtest/test_stratum_jobid.cpp into Makefile.gtest.include (5 tests, all
pass; full hush-gtest suite now 18/18).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PGhWvdBSgt6UxxHANr7gfN
2026-08-30 16:24:55 -05:00
91 changed files with 11185 additions and 786 deletions
+2 -2
View File
@@ -2,8 +2,8 @@ dnl require autoconf 2.60 (AS_ECHO/AS_ECHO_N)
AC_PREREQ([2.60]) AC_PREREQ([2.60])
define(_CLIENT_VERSION_MAJOR, 1) define(_CLIENT_VERSION_MAJOR, 1)
dnl Must be kept in sync with src/clientversion.h , ugh! dnl Must be kept in sync with src/clientversion.h , ugh!
define(_CLIENT_VERSION_MINOR, 2) define(_CLIENT_VERSION_MINOR, 3)
define(_CLIENT_VERSION_REVISION, 0) define(_CLIENT_VERSION_REVISION, 1)
define(_CLIENT_VERSION_BUILD, 50) define(_CLIENT_VERSION_BUILD, 50)
define(_ZC_BUILD_VAL, m4_if(m4_eval(_CLIENT_VERSION_BUILD < 25), 1, m4_incr(_CLIENT_VERSION_BUILD), m4_eval(_CLIENT_VERSION_BUILD < 50), 1, m4_eval(_CLIENT_VERSION_BUILD - 24), m4_eval(_CLIENT_VERSION_BUILD == 50), 1, , m4_eval(_CLIENT_VERSION_BUILD - 50))) define(_ZC_BUILD_VAL, m4_if(m4_eval(_CLIENT_VERSION_BUILD < 25), 1, m4_incr(_CLIENT_VERSION_BUILD), m4_eval(_CLIENT_VERSION_BUILD < 50), 1, m4_eval(_CLIENT_VERSION_BUILD - 24), m4_eval(_CLIENT_VERSION_BUILD == 50), 1, , m4_eval(_CLIENT_VERSION_BUILD - 50)))
define(_CLIENT_VERSION_SUFFIX, m4_if(m4_eval(_CLIENT_VERSION_BUILD < 25), 1, _CLIENT_VERSION_REVISION-beta$1, m4_eval(_CLIENT_VERSION_BUILD < 50), 1, _CLIENT_VERSION_REVISION-rc$1, m4_eval(_CLIENT_VERSION_BUILD == 50), 1, _CLIENT_VERSION_REVISION, _CLIENT_VERSION_REVISION-$1))) define(_CLIENT_VERSION_SUFFIX, m4_if(m4_eval(_CLIENT_VERSION_BUILD < 25), 1, _CLIENT_VERSION_REVISION-beta$1, m4_eval(_CLIENT_VERSION_BUILD < 50), 1, _CLIENT_VERSION_REVISION-rc$1, m4_eval(_CLIENT_VERSION_BUILD == 50), 1, _CLIENT_VERSION_REVISION, _CLIENT_VERSION_REVISION-$1)))
+57
View File
@@ -1,3 +1,60 @@
dragonx (1.3.1) stable; urgency=high
* Fix a file-descriptor double close that could corrupt wallets and block
files and crash the node. wolfSSL's CloseSocket macro turned every P2P
disconnect into a bare close() that left the socket handle set, so the
same fd number was closed again after another thread had reused it,
often for wallet.dat, a BDB log or a block file. Present in every
release since the 2020 move to wolfSSL.
* Defense in depth: block and undo files opened for reading are now
read-only; a wallet error while processing a block now shuts the node
down cleanly instead of crashing it; the BDB logs are kept when the
shutdown flush fails, so the next start can recover the wallet.
* Fix an abort on the next block after a note arrives at an address
imported with z_importviewingkey.
* Large wallets: break the replay -> witness rebuild -> kill loop. Witness
extension is much cheaper and parallel, the chainstate is flushed at
least hourly, replayed transactions keep their nullifiers (no mass
reseed), and the wallet locator never runs ahead of what the wallet has
processed.
* Much faster balance and note RPCs on wallets with thousands of Sapling
notes, through an in-memory cache of decrypted notes (warmed at startup,
-notecachewarmup) and by avoiding deep copies; history RPCs gather
Sapling keys once per call.
* -txindex=0 nodes now include fully shielded notes in queries with
minconf >= 2, so -zsweep and -consolidation now move them.
* No consensus change; PROTOCOL_VERSION is unchanged.
-- DragonX Developers <dev@dragonx.is> Tue, 27 Oct 2026 12:00:00 +0000
dragonx (1.3.0) stable; urgency=medium
* RandomX stratum mining support: the daemon can serve stratum clients
directly, with a reference miner behind the stratummine RPC for testing.
* Stratum fixes found by audit: a malformed 63-character job_id no longer
aborts the daemon; each block is paid to the miner that actually found it
rather than to whichever client asked for work first; and a low-difficulty
share is now rejected before it costs a RandomX hash.
* Fix -connect never dialing its targets, so a node pinned to specific peers
reaches them instead of silently falling through to peer discovery.
* Remove roughly 7,100 lines of dead code, including the CBOPRET price
validation in the coinbase check, whose guard could not be true on any
chain, and adaptive-PoW difficulty logic that DragonX does not enable.
* Honor a command-line -rpcpassword across restarts, and fix a misspelled
-rpcusername key that silently discarded the configured RPC user.
* Default -checkpoints off on regtest so an isolated node leaves initial
block download, instead of staying in IBD forever and disabling every
operation gated on it.
* Release cs_main and the mempool lock on the miner's isStake error paths;
the leak presented as a permanent stall rather than a slow response.
* Windows cross-build: the mingw target links and finds librustzcash, and a
fs::path::c_str() regression in init no longer breaks the build.
* Stamp container builds with the real version instead of "-unk".
* Repair the qa/rpc-tests harness far enough to start a DragonX node and
build the shared test chain; it previously started mainnet nodes.
-- DragonX Developers <dev@dragonx.is> Mon, 31 Aug 2026 03:46:19 +0000
dragonx (1.2.0) stable; urgency=medium dragonx (1.2.0) stable; urgency=medium
* Auto-shield matured coinbase into a wallet-owned Sapling address on a block * Auto-shield matured coinbase into a wallet-owned Sapling address on a block
+3 -3
View File
@@ -1,9 +1,9 @@
.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.49.1. .\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.49.1.
.TH DRAGONX-CLI "1" "August 2026" "dragonx-cli v1.2.0" "User Commands" .TH DRAGONX-CLI "1" "October 2026" "dragonx-cli v1.3.1" "User Commands"
.SH NAME .SH NAME
dragonx-cli \- manual page for dragonx-cli v1.2.0 dragonx-cli \- manual page for dragonx-cli v1.3.1
.SH DESCRIPTION .SH DESCRIPTION
DragonX RPC client version v1.2.0 DragonX RPC client version v1.3.1
.PP .PP
In order to ensure you are adequately protecting your privacy when using In order to ensure you are adequately protecting your privacy when using
DragonX, please see <https://dragonx.is/security/>. DragonX, please see <https://dragonx.is/security/>.
+3 -3
View File
@@ -1,9 +1,9 @@
.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.49.1. .\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.49.1.
.TH DRAGONX-TX "1" "August 2026" "dragonx-tx v1.2.0" "User Commands" .TH DRAGONX-TX "1" "October 2026" "dragonx-tx v1.3.1" "User Commands"
.SH NAME .SH NAME
dragonx-tx \- manual page for dragonx-tx v1.2.0 dragonx-tx \- manual page for dragonx-tx v1.3.1
.SH DESCRIPTION .SH DESCRIPTION
hush\-tx utility version v1.2.0 hush\-tx utility version v1.3.1
.SS "Usage:" .SS "Usage:"
.TP .TP
hush\-tx [options] <hex\-tx> [commands] hush\-tx [options] <hex\-tx> [commands]
+15 -3
View File
@@ -1,9 +1,9 @@
.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.49.1. .\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.49.1.
.TH DRAGONXD "1" "August 2026" "dragonxd v1.2.0" "User Commands" .TH DRAGONXD "1" "October 2026" "dragonxd v1.3.1" "User Commands"
.SH NAME .SH NAME
dragonxd \- manual page for dragonxd v1.2.0 dragonxd \- manual page for dragonxd v1.3.1
.SH DESCRIPTION .SH DESCRIPTION
DragonX Daemon version v1.2.0 DragonX Daemon version v1.3.1
.PP .PP
In order to ensure you are adequately protecting your privacy when using In order to ensure you are adequately protecting your privacy when using
DragonX, please see <https://dragonx.is/security/>. DragonX, please see <https://dragonx.is/security/>.
@@ -452,6 +452,13 @@ or create a wallet z\-address). Must be spendable by this wallet.
Fee in puposhis for automatic coinbase\-shielding transactions (default: Fee in puposhis for automatic coinbase\-shielding transactions (default:
10000) 10000)
.HP .HP
\fB\-sietch\-min\-zouts=\fR<n>
.IP
Minimum number of shielded (Sapling) outputs Sietch adds to each
z_sendmany transaction as decoys, strengthening
amount/linkability privacy. Higher values add privacy at the cost
of larger transactions (default: 7, clamped to the range 3\-50)
.HP
\fB\-autoshieldminutxos\fR \fB\-autoshieldminutxos\fR
.IP .IP
Only auto\-shield once at least this many matured coinbase UTXOs exist Only auto\-shield once at least this many matured coinbase UTXOs exist
@@ -710,6 +717,11 @@ Stratum server options:
.IP .IP
Enable stratum server (default: off) Enable stratum server (default: off)
.HP .HP
\fB\-stratumtarget=\fR<hex>
.IP
Pool share target (64\-hex, big\-endian; larger = easier). Default is the
diff\-1 target. Useful for solo/low\-difficulty mining.
.HP
\fB\-stratumaddress=\fR<address> \fB\-stratumaddress=\fR<address>
.IP .IP
Mining address to use when special address of 'x' is sent by miner Mining address to use when special address of 'x' is sent by miner
+27 -16
View File
@@ -8,32 +8,32 @@ It is best to keep doc/relnotes/README.md up to date as changes and bug fixes ar
## Branch model ## Branch model
Development happens on the `dev` branch. Releases are cut on the default branch, `dragonx`. There is no `master` branch. Code changes should land on `dev` first and undergo testing before being merged into `dragonx`. Development happens on the `dev` branch. Releases are cut on the default branch, `master`. Code changes should land on `dev` first and undergo testing before being merged into `master`.
## Check for changes on dragonx that should be on dev ## Check for changes on master that should be on dev
Occasionally trivial changes are made directly on the `dragonx` branch, such as documentation changes. In theory, no code changes should happen on `dragonx` without being on `dev` first, but it's better to be safe than sorry. We want the `dev` branch which undergoes testing to be as close as possible to what the `dragonx` branch will become, so we don't want to merge `dev` into `dragonx` and just assume everything works. So it's best to merge the `dragonx` branch into `dev` just before merging the `dev` branch into `dragonx`. Occasionally trivial changes are made directly on the `master` branch, such as documentation changes. In theory, no code changes should happen on `master` without being on `dev` first, but it's better to be safe than sorry. We want the `dev` branch which undergoes testing to be as close as possible to what the `master` branch will become, so we don't want to merge `dev` into `master` and just assume everything works. So it's best to merge the `master` branch into `dev` just before merging the `dev` branch into `master`.
To check if the `dragonx` branch has any changes that the `dev` branch does not: To check if the `master` branch has any changes that the `dev` branch does not:
``` ```
# this assumes you are working with https://git.dragonx.is/DragonX/dragonx as your remote # this assumes you are working with https://git.dragonx.is/DragonX/dragonx as your remote
git checkout dev git checkout dev
git pull # make sure dev is up to date git pull # make sure dev is up to date
git checkout dragonx git checkout master
git pull # make sure dragonx is up to date git pull # make sure master is up to date
git diff dev...dragonx # look at the set of changes which exist in dragonx but not dev git diff dev...master # look at the set of changes which exist in master but not dev
``` ```
If the last command has no output, congrats, there is nothing to do. If the last command has output, then you should merge `dragonx` into `dev`: If the last command has no output, congrats, there is nothing to do. If the last command has output, then you should merge `master` into `dev`:
``` ```
git checkout dev git checkout dev
git merge dragonx git merge master
git push origin dev git push origin dev
``` ```
Use the `--no-ff` flag when merging `dev` into `dragonx` for a release (see below). The `--no-ff` flag makes sure to make a merge commit, no matter what, even if a "fast forward" could be done. For those in the future looking back, it's much better to see evidence of when branches were merged. Use the `--no-ff` flag when merging `dev` into `master` for a release (see below). The `--no-ff` flag makes sure to make a merge commit, no matter what, even if a "fast forward" could be done. For those in the future looking back, it's much better to see evidence of when branches were merged.
### Git Issues ### Git Issues
@@ -66,6 +66,7 @@ Install deps on Linux:
- Run "make seeds" - Run "make seeds"
- Commit the result - Commit the result
- Update version in configure.ac and src/clientversion.h to update the dragonxd version - Update version in configure.ac and src/clientversion.h to update the dragonxd version
- **The new version MUST be higher than every version already tagged**, including tags that were never built or published. Check with `git tag -l --sort=-v:refname | head`. Two trees stamped with the same `CLIENT_VERSION` are indistinguishable on the wire, in `getnetworkinfo`, and to the wallet's in-app updater — and a published archive that does not match its tag destroys the only provenance check users have.
- In src/clientversion.h you update `CLIENT_VERSION_*` variables. Usually you will just update `CLIENT_VERSION_REVISION` - In src/clientversion.h you update `CLIENT_VERSION_*` variables. Usually you will just update `CLIENT_VERSION_REVISION`
- If there is a consensus change, it may be a good idea to update `CLIENT_VERSION_MINOR` or `CLIENT_VERSION_MAJOR` - If there is a consensus change, it may be a good idea to update `CLIENT_VERSION_MINOR` or `CLIENT_VERSION_MAJOR`
- To make a pre-release "beta" you can modify `CLIENT_VERSION_BUILD` but that is rarely done. - To make a pre-release "beta" you can modify `CLIENT_VERSION_BUILD` but that is rarely done.
@@ -97,17 +98,27 @@ Install deps on Linux:
- Try to generate checkpoints as close to the release as possible, so you can have a recent block height be protected. - Try to generate checkpoints as close to the release as possible, so you can have a recent block height be protected.
- For instance, don't update checkpoints and then do a release a month later. You can always update checkpoint data again or multiple times - For instance, don't update checkpoints and then do a release a month later. You can always update checkpoint data again or multiple times
- Update doc/relnotes/README.md - Update doc/relnotes/README.md
- To get the stats of file changes: `git diff --stat dragonx...dev` - To get the stats of file changes: `git diff --stat master...dev`
- Do a fresh clone and fresh sync with new checkpoints - Do a fresh clone and fresh sync with new checkpoints
- Stop node, wait 20 minutes, and then do a partial sync with new checkpoints - Stop node, wait 20 minutes, and then do a partial sync with new checkpoints
- Merge dev into dragonx: `git checkout dev && git pull && git checkout dragonx && git pull && git merge --no-ff dev && git push` - Merge dev into master: `git checkout dev && git pull && git checkout master && git pull && git merge --no-ff dev && git push`
- The above command makes sure that your local dev branch is up to date before doing anything - The above command makes sure that your local dev branch is up to date before doing anything
- The above command will not merge if "git pull" creates a merge conflict - The above command will not merge if "git pull" creates a merge conflict
- The above command will not push if there is a problem with merging dev - The above command will not push if there is a problem with merging dev
- Make Gitea release with git tag from the dragonx branch (make sure to merge dev in first) - Make Gitea release with git tag from the master branch (make sure to merge dev in first)
- Make sure git tag starts with a `v` such as `v1.0.3` - Make sure git tag starts with a `v` such as `v1.0.3`
- Use util/gen-linux-binary-release.sh to make a Linux release binary - **The tag MUST be annotated** (`git tag -a v1.3.0 -m 'DragonX v1.3.0'`), not lightweight. `util/genbuild.sh` calls `git describe` *without* `--tags`, which only ever sees annotated tags — a lightweight tag makes the build stamp itself `v<older-tag>-<sha>` instead of the release version. v1.0.0 through v1.0.3 are lightweight, which is why their builds are labelled that way.
- Upload Linux binary to Gitea release and add SHA256 sum - Verify before building: `git describe` must print exactly the tag, with no `-<n>-g<sha>` suffix.
- Use `./build.sh` (container-based, see doc/build-containers.md) or util/gen-linux-binary-release.sh to make a Linux release binary
- **Sign every archive and publish the signatures.** This step is mandatory and was missing from this document until v1.3.0 — its absence is why v1.1.0 and v1.2.0 were tagged but never became installable releases.
- The wallet's in-app daemon updater pins an ed25519 public key in `ObsidianDragon/src/util/daemon_updater.h` and sets `kDaemonRequireSignature = true`. **An update is refused outright unless a valid `<archive>.sig` is published beside the archive.** No signature means every existing user silently stays on their old daemon.
- Sign with `ObsidianDragon/scripts/sign-daemon-release.sh`:
- `scripts/sign-daemon-release.sh sign <secret.key> <archive>...` produces `<archive>.sig` (base64 of a detached 64-byte ed25519 signature over the exact archive bytes)
- or `scripts/sign-daemon-release.sh release <secret.key> <version>` to zip, sign, and print the checksum table in one step
- Keep the secret key offline, mode 600. The matching base64 public key must already be pinned in `kDaemonSignaturePublicKeyBase64`.
- Upload each Linux binary archive **and its `.sig`** to the Gitea release
- **Paste the SHA-256 checksum table into the release body** as markdown rows of the form `| <archive>.zip | `<sha256hex>` |`. The updater parses this table and will not install an archive that is absent from it.
- Confirm the release is actually consumable before announcing it: the updater looks for an asset whose name contains `"-" + platformToken + ".zip"` (`linux-amd64`, `macos`, `win64`). An archive named for a distro variant instead of the platform token is invisible to it.
- Create an x86 Debian package for the release: - Create an x86 Debian package for the release:
- Edit contrib/debian/changelog to add information about the new release - Edit contrib/debian/changelog to add information about the new release
- Use `util/build-debian-package.sh` to make an x86 Debian package for the release - Use `util/build-debian-package.sh` to make an x86 Debian package for the release
@@ -115,7 +126,7 @@ Install deps on Linux:
- `lintian` is an optional dependency, it's not needed to build the .deb - `lintian` is an optional dependency, it's not needed to build the .deb
- Upload .deb to Gitea release - Upload .deb to Gitea release
- Add SHA256 checksum of .deb to release - Add SHA256 checksum of .deb to release
- Use util/build-debian-package-ARM.sh (does this still work?) to make an ARM Debian package for the release - ARM Debian package: `util/build-debian-package-ARM.sh` is referenced here historically but **is not present in the tree**. Skip, or restore the script first.
- Upload the debian packages to the Gitea release page, with SHA256 sums - Upload the debian packages to the Gitea release page, with SHA256 sums
## Platform-specific notes ## Platform-specific notes
+71 -7
View File
@@ -13,7 +13,7 @@ This is to document zsweep and consolidation for advanced DragonX users.
A user can use these options at the command line, but it is **recommended to configure these options within the DRAGONX.conf file**. A user can use these options at the command line, but it is **recommended to configure these options within the DRAGONX.conf file**.
Consolidation takes many unspent shielded UTXOs (zutxos) into one zutxo, which makes spending them in the future faster and potentially cost less in fees. It also helps prevent certain kinds of metadata leakages and spam attacks. It is not recommended for very large wallets (wallet.dat files with thousands of transactions) for performance reasons. This is why it defaults to OFF for CLI full nodes but ON for GUI wallets that use an embedded dragonxd. Consolidation merges many unspent shielded notes (zutxos) of one z-address into a few notes of that same address, which makes spending them later faster and cheaper, keeps the wallet smaller and shortens witness rebuilds and rescans. It never moves funds between addresses. Both zsweep and consolidation are **off by default** in dragonxd, for CLI nodes and for GUI wallets that run an embedded dragonxd alike (the ObsidianDragon GUI does its own, separate auto-consolidation through `z_mergetoaddress`).
Zsweep is when you sweep numerous zutxos into one z-address that you configure. This z-address can be local to that system or it can be configured to sweep to a remote wallet on a different system with the zsweepexternal=1 option, which is explained below in the Zsweep section. Zsweep is when you sweep numerous zutxos into one z-address that you configure. This z-address can be local to that system or it can be configured to sweep to a remote wallet on a different system with the zsweepexternal=1 option, which is explained below in the Zsweep section.
@@ -32,7 +32,7 @@ Zsweep is when you sweep numerous zutxos into one z-address that you configure.
| Zsweep Option Name| Details of what it does | | Zsweep Option Name| Details of what it does |
|-------------------|-------------------------| |-------------------|-------------------------|
| zsweepexternal=1 | Will enable the option to zsweep to an "external" z-address which exists in a wallet on a different system. | | zsweepexternal=1 | Will enable the option to zsweep to an "external" z-address which exists in a wallet on a different system. |
| zsweepinterval=5 | By default zsweep runs every 5 blocks, so set and modify this value to change that. | | zsweepinterval=10 | By default zsweep runs every 10 blocks (values below 5 fall back to 10), so set and modify this value to change that. |
| zsweepmaxinputs=8 | By default zsweep makes sure to not reduce the anonset in any tx by having a maximum number of inputs of 8. This should be fine for new wallets, but if you have an existing wallet with many zutxos it can be changed with this option. Keep in mind that large values will make sweeping faster at the expense of reducing the AnonSet. | | zsweepmaxinputs=8 | By default zsweep makes sure to not reduce the anonset in any tx by having a maximum number of inputs of 8. This should be fine for new wallets, but if you have an existing wallet with many zutxos it can be changed with this option. Keep in mind that large values will make sweeping faster at the expense of reducing the AnonSet. |
| zsweepfee=0 | The default zsweep fee is 10000 puposhis or 0.0001 DRAGONX, the default for all transactions. To use fee=0 for zsweep transactions, set this option. | | zsweepfee=0 | The default zsweep fee is 10000 puposhis or 0.0001 DRAGONX, the default for all transactions. To use fee=0 for zsweep transactions, set this option. |
| zsweepexclude=zs1... | Exclude a certain address from being swept. Can be used multiple times to exclude multiple addressses | | zsweepexclude=zs1... | Exclude a certain address from being swept. Can be used multiple times to exclude multiple addressses |
@@ -41,7 +41,42 @@ Zsweep is when you sweep numerous zutxos into one z-address that you configure.
## Consolidation ## Consolidation
1. We add the following to our conf file as per the Pre-Step. Mining with auto-shielding on (the default for wallets created or restored by dragonxd) adds one shielded note to the
wallet per auto-shield round. Over weeks that is thousands of small notes, which slow down sends, balance calls and
witness rebuilds. Consolidation keeps that in check.
### What a round does
* An address is consolidated only when it holds **more than** `consolidationthreshold` (default 25) *eligible*
notes: unspent (also not spent by a transaction still in the mempool), not locked by another operation, spendable
by this wallet, and at least 11 confirmations deep. Addresses at or below the threshold are left alone.
* For each such address a round sends up to `consolidationmaxtxs` (default 3) transactions. Each spends up to
`consolidationbatchsize` (default 15) of the address's **smallest** notes and pays their value, minus the fee, back
to **the same address**. The big note an earlier round produced is therefore not merged again every round.
* The number of inputs per transaction is drawn at random between two thirds of the batch size and the batch size
(10 to 15 by default), so rounds don't all look alike. A transaction never takes an address's last remaining note,
so every address keeps at least one spendable note while the round confirms.
* Each transaction has exactly 8 shielded outputs: the real one plus 7 zero-value dummy ("Sietch") outputs to random
addresses, so it does not shrink the anonymity set. It pays `consolidationtxfee`, or no fee when its notes are worth
no more than the fee, and expires 15 blocks after it is made.
* Only the notes a round actually spends are locked while it proves, so sends made meanwhile still see the rest of
the wallet.
* All spends of one transaction must use one anchor (Sapling tree root). An address's spends use the tip's root,
where the wallet keeps its witnesses, or else the chain anchor most of its planned notes are at. A note without a
witness, or whose witness root the chain never had (a desynced witness), is skipped and the round goes on without
it; so is, until a later round, a note whose witness is at another real anchor. Each round logs how many it
skipped (`last_round.skipped_notes`).
* If one transaction fails to build or is not accepted, the rest of that address's transactions are skipped for
the round, but the other addresses still get theirs; `last_round.error` gives the first failure.
* With the defaults, an address over the threshold loses 27 to 42 notes per round, and a round runs every 25 blocks.
* dragonxd runs one async operation at a time. So that a `z_sendmany` (or any other async RPC) made during a round
does not wait for all of it, the round ends after its current transaction when another operation is queued
(`last_round.yielded`); the notes it did not get to are unlocked and taken up by the next round. A node that is
asked to stop also ends the round after the current transaction.
### Turning it on
1. Add the following to the conf file as per the Pre-Step.
``` ```
consolidation=1 consolidation=1
``` ```
@@ -50,10 +85,35 @@ Zsweep is when you sweep numerous zutxos into one z-address that you configure.
| Consolidation Option Name| Details of what it does | | Consolidation Option Name| Details of what it does |
|--------------------------|-------------------------| |--------------------------|-------------------------|
| consolidationtxfee=0 | The default consolidation fee is 10000 puposhis or 0.0001 DRAGONX, the default for all transactions. To use fee=0 for consolidation transactions, set this option. | | consolidationinterval=25 | Blocks between rounds (default 25, minimum 5; smaller values are raised to 5). |
| consolidatesaplingaddress=zs1... | Default of consolidation is set to all, but you can set this option if you have one specific z-address (zs1... is a placeholder for this documentation) that you want to only consolidate to. | | consolidationthreshold=25 | Only addresses with more than this many eligible notes are consolidated (default 25, minimum 1). |
| consolidationbatchsize=15 | Most notes one consolidation transaction spends (default 15, clamped to 2..50). |
| consolidationmaxtxs=3 | Most consolidation transactions per address per round (default 3, clamped to 1..100). |
| consolidationtxfee=10000 | Fee in puposhis per consolidation transaction (default 10000 = 0.0001 DRAGONX; allowed range 1000..10000000, anything else falls back to the default). |
| consolidatesaplingaddress=zs1... | Only consolidate this address (may be given several times). The default is every address the wallet can spend. With `consolidation=1` the wallet must hold the address's spending key, or dragonxd refuses to start; with it off, such an address is ignored with a warning (and `z_consolidate` works on all addresses unless given its own). |
1. The following DragonX RPC will let you view your consolidation configuration options and run-time stats at the command line: `dragonx-cli z_sweepstatus` 1. `dragonx-cli z_consolidationstatus` shows the settings, whether a round is running, when the next one is due,
cumulative totals (`notes_consolidated`, `amount_consolidated` in puposhis), the last round (`last_round`: height,
time, txids, notes merged, amount merged, notes skipped, error) and, when rounds can't run, why
(`disabled_reason`). `dragonx-cli z_consolidationstatus true` also counts the eligible notes of every address and
lists which are over the threshold (this walks the whole wallet, so it is only done on request).
### Consolidating on demand
`dragonx-cli z_consolidate` runs one round now with the current settings, also when `consolidation` is off, so a CLI
miner can clean up whenever it suits them. It takes optional overrides, in order: fee (in DRAGONX), batch size,
maximum transactions per address, and a JSON array of addresses; pass `null` to keep a setting, e.g.
`dragonx-cli z_consolidate null 50 20 '["zs1..."]'`. Its fee is in DRAGONX like `z_sendmany`'s, while `consolidationtxfee` and the amounts in
`z_consolidationstatus` are in puposhis. It returns an operation id; `z_getoperationstatus` /
`z_getoperationresult` give the result. It refuses while the node is syncing, while the wallet is locked, and while a
consolidation, zsweep or auto-shield round is in flight.
### Off, but suggested
When consolidation is off and some address has more notes than the threshold, dragonxd logs once after loading the
wallet: `N addresses have more than 25 spendable notes; consider -consolidation=1 or z_consolidate`.
`z_autoshieldstatus` then reports `consolidation_suggested: true`, and `z_consolidationstatus true` reports
`consolidation_suggested` and `consolidation_suggested_count`.
## Zsweep & Consolidation Together ## Zsweep & Consolidation Together
@@ -66,6 +126,11 @@ Zsweep is when you sweep numerous zutxos into one z-address that you configure.
1. Then follow along with the zsweep section above if you want to set specific options for the zsweep behavior. 1. Then follow along with the zsweep section above if you want to set specific options for the zsweep behavior.
1. With zsweep on, consolidation only works on the sweep address: a `consolidatesaplingaddress` other than the
sweep address is refused at startup (with `consolidation=0` it is replaced by the sweep address, with a warning),
and `z_consolidate` refuses any other address too. Sweep and consolidation never run at the same time, and a
sweep is not started when a consolidation round is due within 5 blocks.
### Copyright ### Copyright
The DragonX Developers, jahway603, and The Hush Developers The DragonX Developers, jahway603, and The Hush Developers
@@ -73,4 +138,3 @@ The DragonX Developers, jahway603, and The Hush Developers
### License ### License
GPLv3 GPLv3
+4
View File
@@ -0,0 +1,4 @@
shim/libfdguard.so
shim/fdguard_test
*.o
shim/t/
+55
View File
@@ -0,0 +1,55 @@
# fd-guard: catch stray close() of files a thread doesn't own
This is the harness that found the wolfSSL `CloseSocket` macro bug. With that bug, P2P disconnects closed their fd number a second time, after another thread had reused it, and BDB then wrote wallet pages into `blocks/*.dat`.
It has two parts:
- `shim/`: an `LD_PRELOAD` guard around `close`, `fclose`, `dup2` and `dup3`.
- Before each close it resolves `/proc/self/fd/N`.
- It logs a backtrace when a non-owner closes `wallet.dat`, `database/log.*` or `blocks/*.dat`, and for every close that fails with `EBADF` (the second half of a double close).
- `FDGUARD_ABORT=1` makes the first hit abort.
- `repro/`: isolated regtest runs that put a shimmed `dragonxd` under load:
- **rpc:** impatient and RST clients, half-open connections, work-queue bursts and long-polls;
- **p2p:** TLS peers churned by `disconnectnode`/ban/kill, plus misbehaving raw TCP/TLS clients;
- **tor:** a fake control port;
- **mining:** with `blocknotify` and autoshield.
Each run executes in its own unprivileged network namespace: loopback only, no route.
## Requirements
- Linux.
- `unshare -rn` (unprivileged user namespaces), `nsenter`, `ip`, python3, gcc, and `addr2line` for symbolizing.
- A `dragonxd`/`dragonx-cli` built with `-g`. Adding `-rdynamic` makes backtraces readable without `addr2line`.
- A regtest datadir with a grown wallet to copy from (`GOLDEN`). It is never modified.
## Running
```sh
qa/fd-guard/shim/build.sh # builds libfdguard.so
qa/fd-guard/shim/run_tests.sh # self-test: double close, foreign close of a guarded file
cd qa/fd-guard/repro
export GOLDEN=/path/to/regtest/datadir BIN=/path/to/build/src # RUNS defaults to ~/fd-guard-runs
LOADS=p2pmin,mine DISC_INT=5 GUARD=all ./go.sh p2pmin 300 # 1 peer, disconnectnode every 5 s
LOADS=rpc,p2p,tor,mine WQ=64 RT=8 GUARD=all ./go.sh full 1200 # everything, production-like work queue
python3 tools/tally.py "$RUNS/<name>/fdguard.log" # who closed what
python3 ../shim/symbolize.py --summary "$RUNS/<name>/fdguard.log"
python3 tools/scan_bdb.py "$RUNS/<name>"/target/regtest/blocks/*.dat # BDB pages inside block files
```
Each run writes `run.txt` (full log plus summary), `fdguard.log` and the target's `debug.log` and `db.log` under `$RUNS/<name>/`.
## What to expect
Measured on a 2041-note regtest wallet, before and after the fix (`net: stop wolfSSL's CloseSocket macro ...`), under the same loads:
| Run | Binary | EBADF closes | Non-owner closes (wallet/log/blk) | libevent `Epoll` failures | `db.log` |
|---|---|---|---|---|---|
| `p2pmin`, 300 s | before | 51 (≈ 1 per disconnect) | 1 | 0 | empty |
| | after | 0 | 0 | 0 | empty |
| `full`, 1200 s, `WQ=64 RT=8` | before | 930 | 186 (37) | 111 | 632 KB: 7500 × `BDB0060 PANIC`, `write failed for page N` |
| | after | 0 | 0 | 0 | empty |
- RPC-only and Tor-only loads give 0 reports, even before the fix: P2P disconnects are the only origin.
- `scan_bdb.py` found no BDB pages in block files in any run. The landing of a page in a block file needs the reused number to be a writable block file at the moment BDB writes. Production did hit that (blk00011/blk00020), but it is rare.
- `SSL_write ... closing connection` lines are expected under `tcpchurn`. They are how the load triggers disconnects, not a symptom.
+72
View File
@@ -0,0 +1,72 @@
# shellcheck shell=bash
# Shared config + helpers for the fd-double-close REPRODUCTION harness.
# Regtest only. Meant to run INSIDE an unprivileged network namespace (see ns.sh),
# so every port is private to the namespace and nothing can reach a real network.
set +e
REPRO=${REPRO:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)}
SRCROOT=$(cd "$REPRO/../../.." && pwd)
BIN=${BIN:-$SRCROOT/src} # dir with dragonxd + dragonx-cli (build with -g -rdynamic for backtraces)
DRAGONXD=$BIN/dragonxd
CLI=$BIN/dragonx-cli
RUNS=${RUNS:-$HOME/fd-guard-runs} # run output (block files, logs): keep it out of the repo
GOLDEN=${GOLDEN:?set GOLDEN to a regtest datadir with a grown wallet (it is only ever copied)}
ASMAP=${ASMAP:-$SRCROOT/asmap.dat}
SP=${SP:-$HOME/.zcash-params/sapling-spend.params}
OP=${OP:-$HOME/.zcash-params/sapling-output.params}
SHIM=${SHIM:-$REPRO/../shim/libfdguard.so}
RPCUSER=ab
RPCPASS=abpass
RPC_T=18901 ; P2P_T=18911
RPC_H1=18902; P2P_H1=18912
RPC_H2=18903; P2P_H2=18913
TORPORT=18950
clin() { local dd=$1 rp=$2; shift 2; "$CLI" -regtest -datadir="$dd" -rpcuser=$RPCUSER -rpcpassword=$RPCPASS -rpcport=$rp "$@"; }
write_conf() { printf 'rpcuser=%s\nrpcpassword=%s\nrpcport=%s\n' "$RPCUSER" "$RPCPASS" "$2" > "$1/DRAGONX.conf"; }
# prep_golden <dd> : copy of the golden wallet datadir (2041 notes, txindex=1, height 286)
prep_golden() {
local dd=$1
rm -rf "$dd"; cp -a "$GOLDEN" "$dd"
cp -f "$ASMAP" "$dd/asmap.dat"; cp -f "$SP" "$dd/sapling-spend.params"; cp -f "$OP" "$dd/sapling-output.params"
write_conf "$dd" "$RPC_T"
: > "$dd/regtest/debug.log"; rm -f "$dd/regtest/db.log"
}
# prep_fresh <dd> <rpcport> : empty regtest datadir (helpers)
prep_fresh() {
local dd=$1 rp=$2
rm -rf "$dd"; mkdir -p "$dd"
cp -f "$ASMAP" "$dd/asmap.dat"; cp -f "$SP" "$dd/sapling-spend.params"; cp -f "$OP" "$dd/sapling-output.params"
write_conf "$dd" "$rp"
}
start_helper() { # <dd> <p2p> <rpc> <logfile>
local dd=$1 p2p=$2 rp=$3 lg=$4
( cd "$dd" && exec nice -n 10 "$DRAGONXD" -regtest -datadir="$dd" -testnode=1 -checkpoints=0 \
-listen=1 -bind=127.0.0.1 -port=$p2p -connect=127.0.0.1:1 -addnode=127.0.0.1:$P2P_T \
-dnsseed=0 -dns=0 -asmap="$dd/asmap.dat" -autoshield=0 \
-rpcuser=$RPCUSER -rpcpassword=$RPCPASS -rpcport=$rp -listenonion=0 -maxinboundfromip=100 \
-debug=net -debug=tls -daemon ) >> "$lg" 2>&1
}
waitrpc() { # <dd> <rpc> [secs]
local dd=$1 rp=$2 n=${3:-300} i
for i in $(seq 1 "$n"); do clin "$dd" "$rp" getblockcount >/dev/null 2>&1 && return 0; sleep 1; done
return 1
}
stop_daemon() { # <dd> <rpc> (helpers, started with -daemon)
local dd=$1 rp=$2 pid i
pid=$(cat "$dd/regtest/hushd.pid" 2>/dev/null)
clin "$dd" "$rp" stop >/dev/null 2>&1
for i in $(seq 1 90); do { [ -z "$pid" ] || ! kill -0 "$pid" 2>/dev/null; } && return 0; sleep 1; done
[ -n "$pid" ] && kill -9 "$pid" 2>/dev/null
}
MARKERS=('libevent: Epoll' 'Socket close failed' 'Bad file descriptor' 'Operation not permitted' 'Illegal seek'
'SSL_write' 'Unable to seek' 'socket select error' 'write failed for page' 'PANIC' 'error scanning DB'
'terminate' 'Assertion' 'EXCEPTION')
+14
View File
@@ -0,0 +1,14 @@
#!/usr/bin/env bash
# go.sh <name> <seconds> -- create a private network namespace (loopback only, no route),
# run run.sh inside it, then tear the namespace down. Env knobs pass through to run.sh.
export REPRO=${REPRO:-$(cd "$(dirname "$0")" && pwd)}
export RUNS=${RUNS:-$HOME/fd-guard-runs}
OUT=$RUNS/$1; mkdir -p "$OUT"
setsid unshare -rn sh -c "ip link set lo up && echo \$\$ > $OUT/ns.pid && exec sleep infinity" </dev/null >/dev/null 2>&1 &
for _ in 1 2 3 4 5 6 7 8 9 10; do [ -s "$OUT/ns.pid" ] && break; sleep 0.3; done
NSP=$(cat "$OUT/ns.pid")
cp "$REPRO/run.sh" "$OUT/run.sh.snapshot" # run a frozen copy: editing run.sh cannot disturb a live run
nsenter -t "$NSP" -U -n --preserve-credentials bash "$OUT/run.sh.snapshot" "$@" > "$OUT/go.txt" 2>&1
rc=$?
kill "$NSP" 2>/dev/null
echo "go.sh: run.sh rc=$rc, namespace holder $NSP killed" >> "$OUT/go.txt"
+156
View File
@@ -0,0 +1,156 @@
#!/usr/bin/env bash
# run.sh <name> <seconds> -- run INSIDE the network namespace (go.sh does that).
# Env knobs:
# LOADS=rpc,p2p,tor,mine which load generators run (default all four); p2pmin = 1 helper + disconnectnode every DISC_INT s
# WQ=4 RT=2 -rpcworkqueue / -rpcthreads of the target
# GUARD=all FDGUARD_GUARD (db,blk | all)
# SHIMON=1 run the target under LD_PRELOAD=libfdguard.so
# STRACE=0 1 = also wrap the target in strace (failed fd syscalls only)
# TRACE=0 1 = FDGUARD_TRACE_ALL (one line per open/close; big)
# MINE_INT=3 seconds between generate 1
# HAMMER_ARGS=... override the hammer thread mix
# STOP_ON_HIT=0 1 = end the run 60 s after the first NON-OWNER db/blk close
# EXTRA=... extra target args
source "$REPRO/common.sh"
NAME=$1; DUR=${2:-600}
OUT=$RUNS/$NAME
LOADS=${LOADS:-rpc,p2p,tor,mine}; WQ=${WQ:-4}; RT=${RT:-2}; GUARD=${GUARD:-all}
SHIMON=${SHIMON:-1}; STRACE=${STRACE:-0}; TRACE=${TRACE:-0}; MINE_INT=${MINE_INT:-3}
STOP_ON_HIT=${STOP_ON_HIT:-0}
HAMMER_ARGS=${HAMMER_ARGS:---normal 8 --impatient 8 --slowfire 2 --halfopen 3 --pipeline 3 --garbage 2 --slowread 2 --longpoll 4 --burst-size 16 --burst-every 2}
has() { case ",$LOADS," in *",$1,"*) return 0;; esac; return 1; }
mkdir -p "$OUT/logs"; rm -f "$OUT/STOP"
DD_T=$OUT/target; DD_H1=$OUT/helper1; DD_H2=$OUT/helper2
exec > >(tee -a "$OUT/run.txt") 2>&1
echo "=== repro run $NAME $(date -u +%FT%TZ) dur=${DUR}s loads=$LOADS wq=$WQ rt=$RT guard=$GUARD shim=$SHIMON strace=$STRACE"
echo "netns check (must be ENETUNREACH=101): $(python3 -c 'import socket;print(socket.socket().connect_ex(("1.1.1.1",80)))')"
echo "binary: $DRAGONXD build-id: $(readelf -n "$DRAGONXD" | awk '/Build ID/{print $3}')"
echo "dragonxd already running in this namespace? $(pgrep -a -x dragonxd | wc -l) (other agents' nodes live in other namespaces)"
PIDS=()
cleanup() {
echo "--- cleanup $(date -u +%T)"
touch "$OUT/STOP"
for p in "${PIDS[@]}"; do kill "$p" 2>/dev/null; done
stop_daemon "$DD_H2" "$RPC_H2"; stop_daemon "$DD_H1" "$RPC_H1"
if [ -n "$TPID" ] && kill -0 "$TPID" 2>/dev/null; then
timeout 20 "$CLI" -regtest -datadir="$DD_T" -rpcuser=$RPCUSER -rpcpassword=$RPCPASS -rpcport=$RPC_T stop >/dev/null 2>&1
for _ in $(seq 1 60); do kill -0 "$TPID" 2>/dev/null || break; sleep 1; done
# abandoned longpoll getblocktemplate calls can hold every -rpcthreads worker, so RPC stop may never run:
# fall back to SIGTERM (same clean StartShutdown path), SIGKILL only as a last resort
kill -0 "$TPID" 2>/dev/null && { echo "RPC stop did not finish in 60 s -> SIGTERM"; kill -TERM "$TPID"; }
for _ in $(seq 1 180); do kill -0 "$TPID" 2>/dev/null || break; sleep 1; done
kill -0 "$TPID" 2>/dev/null && { echo "target did not stop -> SIGKILL"; kill -9 "$TPID"; }
fi
[ -n "$WPID" ] && wait "$WPID" 2>/dev/null; echo "target exit status: $?"
for p in "${PIDS[@]}"; do kill -9 "$p" 2>/dev/null; done
summarize
}
summarize() {
local DL=$DD_T/regtest/debug.log
echo "=== markers in target debug.log"
for m in "${MARKERS[@]}"; do printf ' [%6d] %s\n' "$(grep -c -- "$m" "$DL" 2>/dev/null)" "$m"; done
echo " db.log bytes: $(stat -c %s "$DD_T/regtest/db.log" 2>/dev/null || echo absent)"
grep -q 'Shutdown: done' "$DL" && echo " clean shutdown: yes" || echo " clean shutdown: NO"
if [ "$SHIMON" = 1 ]; then
echo "=== fdguard reports"; grep -o '=== FDGUARD #[0-9]* [A-Z-]*' "$OUT/fdguard.log" | awk '{print $4}' | sort | uniq -c
grep '^S ' "$OUT/fdguard.log" | tail -1
python3 "$REPRO/../shim/symbolize.py" --summary "$OUT/fdguard.log" > "$OUT/fdguard.summary.txt" 2>&1
head -60 "$OUT/fdguard.summary.txt"
fi
echo "=== BDB-page-in-blockfile detector"
python3 "$REPRO/tools/scan_bdb.py" "$DD_T"/regtest/blocks/blk*.dat "$DD_T"/regtest/blocks/rev*.dat 2>&1 | tail -15
echo "=== end $(date -u +%FT%TZ)"
}
trap cleanup EXIT
trap 'exit 130' INT TERM
echo "--- prep datadirs"
prep_golden "$DD_T"
prep_fresh "$DD_H1" "$RPC_H1"; prep_fresh "$DD_H2" "$RPC_H2"
cat > "$OUT/blocknotify.sh" <<EOF
#!/bin/sh
# pool-like blocknotify: a couple of dragonx-cli calls per block
$CLI -regtest -datadir=$DD_T -rpcuser=$RPCUSER -rpcpassword=$RPCPASS -rpcport=$RPC_T getblock "\$1" >/dev/null 2>&1
$CLI -regtest -datadir=$DD_T -rpcuser=$RPCUSER -rpcpassword=$RPCPASS -rpcport=$RPC_T getblocktemplate >/dev/null 2>&1
echo "\$(date +%s) \$1" >> $OUT/logs/blocknotify.log
EOF
chmod +x "$OUT/blocknotify.sh"
if has tor; then
nice -n 10 python3 "$REPRO/tools/faketor.py" --port $TORPORT > "$OUT/logs/faketor.txt" 2>&1 & PIDS+=($!)
TORARGS="-listenonion=1 -torcontrol=127.0.0.1:$TORPORT -debug=tor"
else
TORARGS="-listenonion=0"
fi
if has p2p || has p2pmin; then P2PARGS="-listen=1 -bind=127.0.0.1 -port=$P2P_T -allowlist=127.0.0.0/8 -maxinboundfromip=100"
else P2PARGS="-listen=0 -port=$P2P_T"; fi
TARGS=(-regtest -datadir="$DD_T" -testnode=1 -checkpoints=0 $P2PARGS -connect=127.0.0.1:1 -dnsseed=0 -dns=0
-asmap="$DD_T/asmap.dat" -rpcuser=$RPCUSER -rpcpassword=$RPCPASS -rpcport=$RPC_T
-txindex=1 -autoshield=1 -rpcworkqueue=$WQ -rpcthreads=$RT
"-blocknotify=$OUT/blocknotify.sh %s" $TORARGS -debug=net -debug=tls -printtoconsole=0 -daemon=0 $EXTRA)
echo "target args: ${TARGS[*]}" | sed "s/$RPCPASS/***/g"
ENVV=()
if [ "$SHIMON" = 1 ]; then
ENVV=(FDGUARD_LOG="$OUT/fdguard.log" FDGUARD_GUARD="$GUARD" FDGUARD_ABORT=0 FDGUARD_STATS_SEC=60 FDGUARD_MAXREPORTS=2000 LD_PRELOAD="$SHIM")
[ "$TRACE" = 1 ] && ENVV+=(FDGUARD_TRACE_ALL=1)
fi
WRAP=()
[ "$STRACE" = 1 ] && WRAP=(strace -f -tt -qq -e trace=close,openat,accept4,socket,dup2,dup3 -e status=failed -o "$OUT/strace.txt")
( cd "$DD_T" && exec env "${ENVV[@]}" nice -n 10 "${WRAP[@]}" "$DRAGONXD" "${TARGS[@]}" ) > "$OUT/logs/target_stdout.txt" 2>&1 &
WPID=$!
echo "--- target launched (wrapper pid $WPID); waiting for RPC"
waitrpc "$DD_T" "$RPC_T" 600 || { echo "target never answered RPC"; exit 1; }
TPID=$(cat "$DD_T/regtest/hushd.pid" 2>/dev/null); [ -z "$TPID" ] && TPID=$WPID
echo "target up pid=$TPID height=$(clin "$DD_T" "$RPC_T" getblockcount) $(date -u +%T)"
T0=$(date +%s)
if has p2p; then
start_helper "$DD_H1" "$P2P_H1" "$RPC_H1" "$OUT/logs/helper1.txt"
start_helper "$DD_H2" "$P2P_H2" "$RPC_H2" "$OUT/logs/helper2.txt"
waitrpc "$DD_H1" "$RPC_H1" 120; waitrpc "$DD_H2" "$RPC_H2" 120
nice -n 10 python3 "$REPRO/tools/tcpchurn.py" --port $P2P_T --duration "$DUR" --concurrency 8 > "$OUT/logs/tcpchurn.txt" 2>&1 & PIDS+=($!)
nice -n 10 bash "$REPRO/tools/rpcchurn.sh" "$OUT" "$DUR" > "$OUT/logs/rpcchurn.txt" 2>&1 & PIDS+=($!)
fi
if has p2pmin; then
# minimal P2P: ONE well-behaved helper peer, and an ordinary "disconnectnode" every DISC_INT s
# (the helper's -addnode re-dials the target). No raw TCP/TLS churn, no bans, no kills.
start_helper "$DD_H1" "$P2P_H1" "$RPC_H1" "$OUT/logs/helper1.txt"; waitrpc "$DD_H1" "$RPC_H1" 120
( k=0; while [ ! -e "$OUT/STOP" ]; do sleep "${DISC_INT:-5}"; for a in $(clin "$DD_T" "$RPC_T" getpeerinfo 2>/dev/null | python3 -c 'import json,sys; [print(p["addr"]) for p in json.load(sys.stdin)]' 2>/dev/null); do
clin "$DD_T" "$RPC_T" disconnectnode "$a" >/dev/null 2>&1 && { k=$((k+1)); echo "$(date -u +%T.%N) disconnectnode $a" >> "$OUT/logs/disconnects.log"; }; done
sleep 1; clin "$DD_H1" "$RPC_H1" addnode "127.0.0.1:$P2P_T" onetry >/dev/null 2>&1 # helper re-dials now (its -addnode retry is ~2 min)
echo "$k" > "$OUT/logs/disconnects.txt"; done ) & PIDS+=($!)
fi
if has rpc; then
MINEARG=""; has mine && MINEARG="--mine --mine-interval $MINE_INT"
nice -n 10 python3 "$REPRO/tools/hammer.py" --port $RPC_T --user $RPCUSER --password $RPCPASS --duration "$DUR" \
$HAMMER_ARGS $MINEARG --pid "$TPID" --logfile "$OUT/logs/hammer.log" > "$OUT/logs/hammer_stdout.txt" 2>&1 & PIDS+=($!)
elif has mine; then
( while [ ! -e "$OUT/STOP" ]; do clin "$DD_T" "$RPC_T" generate 1 >/dev/null 2>&1; sleep "$MINE_INT"; done ) & PIDS+=($!)
fi
# ---- poll
end=$(( T0 + DUR )); n=0; hit_at=0
while [ "$(date +%s)" -lt "$end" ] && [ ! -e "$OUT/STOP" ]; do
sleep 30; n=$((n+1))
alive=no; kill -0 "$TPID" 2>/dev/null && alive=yes
DL=$DD_T/regtest/debug.log
h=$(clin "$DD_T" "$RPC_T" getblockcount 2>/dev/null); c=$(clin "$DD_T" "$RPC_T" getconnectioncount 2>/dev/null)
rep=$(grep -c '^=== FDGUARD' "$OUT/fdguard.log" 2>/dev/null); noc=$(grep -c 'NON-OWNER-CLOSE' "$OUT/fdguard.log" 2>/dev/null)
ebf=$(grep -c 'EBADF-CLOSE' "$OUT/fdguard.log" 2>/dev/null); epl=$(grep -c '=== FDGUARD #[0-9]* EPOLL' "$OUT/fdguard.log" 2>/dev/null)
dbnoc=$(grep -A3 'NON-OWNER-CLOSE' "$OUT/fdguard.log" 2>/dev/null | grep -c 'class=\(db\|blk\)')
printf '[poll %3d %s +%4ds] alive=%s h=%s conns=%s | fdguard reports=%s nonowner=%s(db/blk %s) ebadf=%s epoll=%s | Epoll=%s SockCloseFail=%s EBADF=%s EPERM=%s SSL_write=%s seek=%s sel=%s | db.log=%s\n' \
$n "$(date -u +%T)" $(( $(date +%s) - T0 )) $alive "$h" "$c" "$rep" "$noc" "$dbnoc" "$ebf" "$epl" \
"$(grep -c 'libevent: Epoll' "$DL")" "$(grep -c 'Socket close failed' "$DL")" "$(grep -c 'Bad file descriptor' "$DL")" \
"$(grep -c 'Operation not permitted' "$DL")" "$(grep -c 'SSL_write' "$DL")" "$(grep -c 'Unable to seek' "$DL")" \
"$(grep -c 'socket select error' "$DL")" "$(stat -c %s "$DD_T/regtest/db.log" 2>/dev/null)" | tee -a "$OUT/poll.txt"
[ "$alive" = no ] && { echo "!!! target died"; break; }
if [ "$STOP_ON_HIT" = 1 ] && [ "${dbnoc:-0}" -gt 0 ]; then
[ "$hit_at" = 0 ] && hit_at=$(date +%s)
[ $(( $(date +%s) - hit_at )) -ge 60 ] && { echo "--- stop-on-hit"; break; }
fi
done
cat "$OUT/logs/tcpchurn.txt" "$OUT/logs/rpcchurn.txt" 2>/dev/null
grep -E 'TOTAL|totals' -A12 "$OUT/logs/hammer.log" 2>/dev/null | tail -14
+98
View File
@@ -0,0 +1,98 @@
#!/usr/bin/env python3
"""
Fake Tor control port for the fd-bug harness.
dragonxd's torcontrol.cpp opens a libevent bufferevent to -torcontrol=<host:port>,
speaks the control protocol (PROTOCOLINFO / AUTHCHALLENGE / AUTHENTICATE / ADD_ONION),
and on EOF/ERROR reconnects with exponential backoff. We give it a server on a
loopback port that behaves badly in several ways so the reconnect/teardown loop
(bufferevent_free with BEV_OPT_CLOSE_ON_FREE, the event_base, the reconnect timer)
runs constantly. Each accepted connection picks a behaviour at random:
close : accept, then immediately close (EOF right away)
rst : accept, set SO_LINGER 0, close -> sends RST
stall : accept, read nothing, hold the socket open then drop it
garbage : send non-control-protocol bytes then close
halfok : answer PROTOCOLINFO plausibly, then drop before AUTHENTICATE completes
Loopback only. Run with --port. Ctrl-C / SIGTERM stops it.
"""
import argparse, random, socket, struct, threading, time, sys, signal
STOP = threading.Event()
def handle(conn, mode):
try:
conn.settimeout(5.0)
if mode == "close":
conn.close(); return
if mode == "rst":
conn.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER,
struct.pack("ii", 1, 0))
conn.close(); return
if mode == "stall":
# read whatever the controller sends but never reply; hold 2-4s
try:
conn.recv(4096)
except Exception:
pass
time.sleep(random.uniform(2.0, 4.0))
conn.close(); return
if mode == "garbage":
try:
conn.recv(4096)
except Exception:
pass
conn.sendall(b"\x00\xff\x01garbage not a tor reply\r\n" * 4)
conn.close(); return
if mode == "halfok":
# read the PROTOCOLINFO line, give a plausible 250 reply advertising
# NULL auth, then drop the connection before AUTHENTICATE finishes.
try:
conn.recv(4096)
except Exception:
pass
conn.sendall(b"250-PROTOCOLINFO 1\r\n"
b"250-AUTH METHODS=NULL\r\n"
b'250-VERSION Tor="0.4.7.13"\r\n'
b"250 OK\r\n")
time.sleep(random.uniform(0.2, 1.0))
conn.close(); return
except Exception:
try: conn.close()
except Exception: pass
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--port", type=int, required=True)
ap.add_argument("--host", default="127.0.0.1")
args = ap.parse_args()
modes = ["close", "rst", "stall", "garbage", "halfok"]
srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
srv.bind((args.host, args.port))
srv.listen(16)
srv.settimeout(1.0)
print(f"faketor: listening on {args.host}:{args.port}", flush=True)
def onsig(*_): STOP.set()
signal.signal(signal.SIGTERM, onsig)
signal.signal(signal.SIGINT, onsig)
n = 0
while not STOP.is_set():
try:
conn, _ = srv.accept()
except socket.timeout:
continue
except Exception:
break
mode = modes[n % len(modes)]
n += 1
threading.Thread(target=handle, args=(conn, mode), daemon=True).start()
srv.close()
print(f"faketor: stopped after {n} connections", flush=True)
if __name__ == "__main__":
main()
+796
View File
@@ -0,0 +1,796 @@
#!/usr/bin/env python3
# hammer.py -- JSON-RPC robustness/load harness for a LOCAL regtest dragonxd.
#
# Scope: connects only to the --host/--port you pass (meant to be 127.0.0.1 and a
# regtest RPC port). Its job is to reproduce a known file-descriptor bug in the
# libevent-2.1.8 HTTP RPC server (src/httpserver.cpp) by exercising the same
# request patterns the production pool box sees: many concurrent clients, clients
# that disconnect mid-request/mid-response (the explorer indexer's 120 s client
# timeout), work-queue overflow, keep-alive pipelining, and malformed input.
# stdlib only.
#
# Correctness oracle: every request carries a unique JSON-RPC id; if a reply comes
# back with a different id on the same socket, that is cross-talk (the server wrote
# one client's reply onto another client's fd) and is logged + counted.
#
# See README.txt for the exact invocation.
import argparse
import base64
import collections
import json
import os
import random
import socket
import struct
import threading
import time
# ------------------------------------------------------------------ config/state
class C:
host = "127.0.0.1"
port = 19461
auth = ""
ctimeout = 15.0
CFG = C()
STOP = threading.Event()
SHARED = {"hashes": [], "lpid": None, "zaddrs": [], "rawblock": None}
SHARED_LOCK = threading.Lock()
_ID = [random.SystemRandom().randrange(1 << 40)]
_ID_LOCK = threading.Lock()
LOGLOCK = threading.Lock()
LOGF = [None]
def next_id():
with _ID_LOCK:
_ID[0] += 1
return _ID[0]
def log(msg):
line = "%s %s" % (time.strftime("%H:%M:%S"), msg)
with LOGLOCK:
print(line, flush=True)
if LOGF[0]:
LOGF[0].write(line + "\n"); LOGF[0].flush()
# ------------------------------------------------------------------ stats
KEYS = ["sent", "ok", "rpcerr", "wq500", "http401", "http4xx", "httpother",
"early_rst", "early_fin", "srvreset", "srveof", "ctimeout", "connfail",
"idmismatch", "malformed", "mined", "half_open", "half_srvclose"]
class Stats:
def __init__(self):
self.lk = threading.Lock()
self.total = collections.Counter()
self.win = collections.Counter()
self.anom = []
def inc(self, k, n=1):
with self.lk:
self.total[k] += n; self.win[k] += n
def anomaly(self, kind, detail):
with self.lk:
if len(self.anom) < 300:
self.anom.append((time.time(), kind, detail))
log("ANOMALY %s %s" % (kind, detail))
def swap(self):
with self.lk:
w = self.win; self.win = collections.Counter(); return w
ST = Stats()
# ------------------------------------------------------------------ socket helpers
def auth_header(u, p):
return "Basic " + base64.b64encode(("%s:%s" % (u, p)).encode()).decode()
def mkconn(timeout=None, rcvbuf=None):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if rcvbuf:
s.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, rcvbuf)
s.settimeout(timeout if timeout is not None else CFG.ctimeout)
s.connect((CFG.host, CFG.port))
return s
def end_rst(s):
# linger 0 -> TCP RST on close (models a client that dies / resets abruptly)
try:
s.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack("ii", 1, 0))
except OSError:
pass
try:
s.close()
except OSError:
pass
def end_fin(s):
try:
s.shutdown(socket.SHUT_RDWR)
except OSError:
pass
try:
s.close()
except OSError:
pass
def end_early(s, how=None):
how = how or random.choice(("rst", "fin"))
if how == "rst":
end_rst(s); ST.inc("early_rst")
else:
end_fin(s); ST.inc("early_fin")
def req_bytes(method, params, rid, keepalive=True, auth=None, uri="/",
httpmethod="POST", body=None, clen=None):
if body is None:
body = json.dumps({"jsonrpc": "1.0", "id": rid,
"method": method, "params": params}).encode()
head = [
"%s %s HTTP/1.1" % (httpmethod, uri),
"Host: %s:%d" % (CFG.host, CFG.port),
"Authorization: %s" % (auth if auth is not None else CFG.auth),
"Content-Type: application/json",
"Content-Length: %d" % (clen if clen is not None else len(body)),
"Connection: %s" % ("keep-alive" if keepalive else "close"),
"", "",
]
return "\r\n".join(head).encode() + body
class Reader:
"""Incremental HTTP/1.1 reply reader over one socket."""
def __init__(self, s):
self.s = s; self.buf = b""
def _fill(self):
d = self.s.recv(65536)
if not d:
raise EOFError()
self.buf += d
def read(self):
while b"\r\n\r\n" not in self.buf:
self._fill()
if len(self.buf) > (1 << 20):
raise ValueError("oversize header")
head, self.buf = self.buf.split(b"\r\n\r\n", 1)
lines = head.split(b"\r\n")
p = lines[0].split(b" ", 2)
if len(p) < 2 or not p[0].startswith(b"HTTP/1."):
raise ValueError("bad status line %r" % lines[0][:80])
status = int(p[1])
hdr = {}
for ln in lines[1:]:
if b":" in ln:
k, v = ln.split(b":", 1)
hdr[k.strip().lower()] = v.strip()
if hdr.get(b"transfer-encoding", b"").lower() == b"chunked":
body = b""
while True:
while b"\r\n" not in self.buf:
self._fill()
ln, self.buf = self.buf.split(b"\r\n", 1)
n = int(ln.split(b";")[0], 16)
while len(self.buf) < n + 2:
self._fill()
body += self.buf[:n]; self.buf = self.buf[n + 2:]
if n == 0:
break
elif b"content-length" in hdr:
n = int(hdr[b"content-length"])
while len(self.buf) < n:
self._fill()
body, self.buf = self.buf[:n], self.buf[n:]
else:
try:
while True:
self._fill()
except EOFError:
pass
body, self.buf = self.buf, b""
return status, hdr, body
def account(status, body, rid, method, expect401=False):
if status == 401:
ST.inc("http401")
if not expect401:
ST.anomaly("unexpected401", (method,))
return None
if status == 500 and b"Work queue depth exceeded" in body:
ST.inc("wq500"); return None
j = None
if body[:1] in (b"{", b"["):
try:
j = json.loads(body)
except ValueError:
j = None
if j is None:
if 400 <= status < 500:
ST.inc("http4xx")
else:
ST.inc("httpother")
if status == 200:
ST.anomaly("non-json-200", (method, body[:120].decode("latin1")))
return None
if isinstance(j, dict) and rid is not None and j.get("id") != rid:
ST.inc("idmismatch")
ST.anomaly("idmismatch", {"method": method, "sent": rid, "got": j.get("id"),
"body": body[:200].decode("latin1")})
if isinstance(j, dict) and j.get("error"):
ST.inc("rpcerr")
else:
ST.inc("ok")
return j
def call(s, rd, method, params, keepalive=True, expect401=False, auth=None):
rid = next_id()
try:
s.sendall(req_bytes(method, params, rid, keepalive=keepalive, auth=auth))
ST.inc("sent")
status, hdr, body = rd.read()
except socket.timeout:
ST.inc("ctimeout"); return None, False
except (ConnectionResetError, BrokenPipeError):
ST.inc("srvreset"); return None, False
except EOFError:
ST.inc("srveof"); return None, False
except ValueError as e:
ST.inc("malformed"); ST.anomaly("malformed", (method, str(e))); return None, False
except OSError:
ST.inc("srvreset"); return None, False
j = account(status, body, rid, method, expect401)
alive = keepalive and hdr.get(b"connection", b"").lower() != b"close"
return j, alive
# ------------------------------------------------------------------ menus
def a_hash():
with SHARED_LOCK:
return random.choice(SHARED["hashes"]) if SHARED["hashes"] else None
def a_zaddr():
with SHARED_LOCK:
return random.choice(SHARED["zaddrs"]) if SHARED["zaddrs"] else None
def normal_menu():
# Mostly fast calls (sub-ms) so a well-behaved client interleaves with mining.
# Heavy wallet calls (z_gettotalbalance ~2.3s on the golden wallet) appear but
# are rare, so they don't permanently peg the small worker pool on their own.
fast = [("getinfo", []), ("getblockcount", []), ("getbestblockhash", []),
("getrawmempool", []), ("getmininginfo", []), ("getdifficulty", []),
("getblockchaininfo", []), ("getpeerinfo", []),
("getblocktemplate", []), ("getnetworkinfo", [])]
h = a_hash()
if h:
fast.append(("getblock", [h, 2]))
fast.append(("getblockheader", [h]))
# "slow" here is only mildly-larger fast calls; the genuinely heavy wallet calls
# live in the paced slow-fire class so a normal dashboard poller never pegs the
# worker pool.
slow = [("coinsupply", []), ("listtransactions", ["*", 10]),
("listunspent", [0]), ("getblock", [a_hash() or "", 2])]
return random.choice(slow) if random.random() < 0.1 else random.choice(fast)
def medium_menu():
# Fast to compute (~4 ms on this node) but a non-trivial reply to write, so they
# are good targets for a mid-response disconnect. The fd-reuse race fires on the
# disconnect, not on call duration, so firing these at a HIGH rate drives the
# race hard while the worker frees in milliseconds (mining keeps its slots).
m = [("listtransactions", ["*", 10000]), ("getrawmempool", []),
("getrawmempool", [True]), ("getblockchaininfo", []),
("getblocktemplate", []), ("getchaintips", []), ("getinfo", []),
("coinsupply", []), ("listunspent", [0])]
h = a_hash()
if h:
m.append(("getblock", [h, 2]))
m.append(("getblock", [h, 1]))
return random.choice(m)
def heavy_menu():
# Genuinely slow calls (z_gettotalbalance ~1.7 s, z_listunspent ~5.7 s on the
# golden wallet). Fired only by the small, PACED slow-fire class so a worker
# keeps running a multi-second call long after the client disconnected (the
# production indexer/coinsupply scenario that widens the fd-reuse window),
# without the fire-and-disconnect backlog pinning the whole pool.
m = [("z_gettotalbalance", [0]), ("z_listunspent", [0])]
z = a_zaddr()
if z:
m.append(("z_listreceivedbyaddress", [z, 0]))
return random.choice(m)
# ------------------------------------------------------------------ clients
def client_normal(cid):
while not STOP.is_set():
keepalive = random.random() < 0.7
try:
s = mkconn()
except OSError:
ST.inc("connfail"); time.sleep(0.05); continue
rd = Reader(s)
n = random.randint(1, 8) if keepalive else 1
try:
for _ in range(n):
if STOP.is_set():
break
method, params = normal_menu()
j, alive = call(s, rd, method, params, keepalive=keepalive)
if not alive:
break
finally:
(end_fin if random.random() < 0.8 else end_rst)(s)
time.sleep(random.uniform(0.01, 0.15))
def client_impatient(cid):
# High-rate fast-disconnect churn: send a (medium) request, then disconnect
# after 1-500 ms at a random phase. This is the main driver of the fd-reuse
# race -- a disconnect concurrent with the server writing the reply / re-arming
# the socket -- and the worker frees in ms so mining is unaffected.
while not STOP.is_set():
method, params = medium_menu()
rid = next_id()
body = json.dumps({"jsonrpc": "1.0", "id": rid, "method": method,
"params": params}).encode()
phase = random.choice(("mid_request", "after_send", "mid_response"))
try:
s = mkconn(timeout=2.0)
except OSError:
ST.inc("connfail"); continue
try:
if phase == "mid_request":
full = req_bytes(method, params, rid, keepalive=False, body=body)
cut = random.randint(len(full) - len(body), len(full) - 1)
s.sendall(full[:cut])
time.sleep(random.uniform(0.001, 0.5))
end_early(s); continue
s.sendall(req_bytes(method, params, rid, keepalive=False, body=body))
ST.inc("sent")
time.sleep(random.uniform(0.001, 0.5))
if phase == "mid_response":
try:
s.recv(random.randint(0, 64)) # read a few bytes, then bail
except OSError:
pass
end_early(s)
except (OSError, socket.timeout):
ST.inc("srvreset")
end_rst(s)
time.sleep(random.uniform(0.05, 0.4))
def client_slowfire(cid, pace):
# Paced indexer/coinsupply client: fire ONE genuinely-slow request, disconnect
# after 1-500 ms (so the worker runs the multi-second call with no client left
# == the production fd-reuse window), then wait `pace` s before the next so a
# fire-and-disconnect backlog cannot pin the whole worker pool. Phase: cut the
# request mid-body, or send it whole and abort while the worker is busy, or read
# a few bytes of the reply then abort.
while not STOP.is_set():
method, params = heavy_menu()
rid = next_id()
body = json.dumps({"jsonrpc": "1.0", "id": rid, "method": method,
"params": params}).encode()
phase = random.choice(("mid_request", "after_send", "mid_response"))
try:
s = mkconn(timeout=2.0)
except OSError:
ST.inc("connfail"); time.sleep(pace); continue
try:
if phase == "mid_request":
full = req_bytes(method, params, rid, keepalive=False, body=body)
cut = random.randint(len(full) - len(body), len(full) - 1)
s.sendall(full[:cut])
time.sleep(random.uniform(0.001, 0.5)); end_early(s)
else:
s.sendall(req_bytes(method, params, rid, keepalive=False, body=body))
ST.inc("sent")
time.sleep(random.uniform(0.001, 0.5))
if phase == "mid_response":
try:
s.recv(random.randint(0, 64))
except OSError:
pass
end_early(s)
except (OSError, socket.timeout):
ST.inc("srvreset"); end_rst(s)
time.sleep(random.uniform(pace * 0.5, pace * 1.5))
def client_half_open(cid):
# connect, send nothing / partial headers, trickle, then vanish
while not STOP.is_set():
try:
s = mkconn(timeout=1.0)
except OSError:
ST.inc("connfail"); time.sleep(0.1); continue
ST.inc("half_open")
style = random.choice(("silent", "partial_headers", "full_headers_no_body"))
try:
if style == "partial_headers":
s.sendall(b"POST / HTTP/1.1\r\nHost: x\r\n")
elif style == "full_headers_no_body":
s.sendall(b"POST / HTTP/1.1\r\nHost: x\r\nAuthorization: " +
CFG.auth.encode() + b"\r\nContent-Length: 1000\r\n\r\n")
deadline = time.monotonic() + random.uniform(0.1, 20.0)
while time.monotonic() < deadline and not STOP.is_set():
time.sleep(random.uniform(0.2, 1.5))
try:
s.sendall(b" ") # one byte, keep it half-alive
except OSError:
ST.inc("half_srvclose"); break
try:
s.settimeout(0.01)
if s.recv(1) == b"":
ST.inc("half_srvclose"); break
except socket.timeout:
pass
except OSError:
ST.inc("half_srvclose"); break
finally:
end_early(s)
def client_burst(cid, size, every):
while not STOP.is_set():
batch = []
for _ in range(size):
try:
s = mkconn(timeout=3.0)
except OSError:
ST.inc("connfail"); continue
batch.append(s)
for s in batch:
try:
method, params = medium_menu()
s.sendall(req_bytes(method, params, next_id(), keepalive=False))
ST.inc("sent")
except OSError:
pass
# most close immediately (before the 500/reply is written); a few read it
keep = random.sample(batch, max(0, len(batch) // 4)) if batch else []
for s in batch:
if s in keep:
continue
end_early(s)
for s in keep:
try:
rd = Reader(s); st, hd, bd = rd.read(); account(st, bd, None, "burst")
except Exception:
ST.inc("srvreset")
finally:
end_fin(s)
for _ in range(int(every * 10)):
if STOP.is_set():
break
time.sleep(0.1)
def client_pipeline(cid):
while not STOP.is_set():
try:
s = mkconn()
except OSError:
ST.inc("connfail"); time.sleep(0.05); continue
n = random.randint(2, 8)
ids = []
blob = b""
for _ in range(n):
rid = next_id(); ids.append(rid)
method, params = normal_menu()
blob += req_bytes(method, params, rid, keepalive=True)
try:
s.sendall(blob); ST.inc("sent", n)
rd = Reader(s)
toread = random.randint(0, n) # sometimes leave replies unread, then close
for k in range(toread):
st, hd, bd = rd.read()
account(st, bd, ids[k], "pipeline")
except (OSError, EOFError, ValueError):
ST.inc("srvreset")
finally:
end_early(s)
time.sleep(random.uniform(0, 0.03))
def client_garbage(cid):
probes = [
("submitblock", lambda: ["ab" * random.randint(1, 4000)]),
("submitblock", lambda: [os.urandom(random.randint(1, 200)).hex()]),
("submitblock", lambda: ["zzzz"]),
("submitblock", lambda: [""]),
]
while not STOP.is_set():
pick = random.random()
try:
s = mkconn(timeout=5.0)
except OSError:
ST.inc("connfail"); continue
try:
if pick < 0.5:
method, mk = random.choice(probes)
j, _ = call(s, Reader(s), method, mk(), keepalive=False)
elif pick < 0.65:
# malformed JSON body
s.sendall(req_bytes("x", [], next_id(), keepalive=False,
body=b'{"jsonrpc":"1.0","method":'))
ST.inc("sent")
try:
account(*((lambda r: (r[0], r[2]))(Reader(s).read())), rid=None, method="badjson")
except Exception:
ST.inc("srvreset")
elif pick < 0.8:
# unknown method / wrong URI
s.sendall(req_bytes("getinfo", [], next_id(), keepalive=False, uri="/nope"))
ST.inc("sent")
try:
st, hd, bd = Reader(s).read(); account(st, bd, None, "wronguri")
except Exception:
ST.inc("srvreset")
else:
# Content-Length larger than the body we send, then bail
body = b'{"id":1}'
s.sendall(req_bytes("getinfo", [], 1, keepalive=False, body=body, clen=len(body) + 5000))
ST.inc("sent")
time.sleep(random.uniform(0.001, 0.3))
end_early(s)
continue
except (OSError, socket.timeout):
ST.inc("srvreset")
finally:
end_early(s)
time.sleep(random.uniform(0.02, 0.2))
def client_slowread(cid):
# ask for a big reply with a tiny recv buffer and do not read it, stalling the
# server write side, then close abruptly
while not STOP.is_set():
try:
s = mkconn(timeout=3.0, rcvbuf=512)
except OSError:
ST.inc("connfail"); continue
try:
s.sendall(req_bytes("listtransactions", ["*", 10000], next_id(), keepalive=False))
ST.inc("sent")
time.sleep(random.uniform(0.05, 1.0))
except OSError:
ST.inc("srvreset")
finally:
end_early(s)
time.sleep(random.uniform(0, 0.05))
def _stale_lpid():
# A longpollid whose hash != the current tip makes getblocktemplate return at
# once (the server's wait loop condition is immediately false), so it exercises
# the long-poll request path (lpval parsing, cs_main leave/enter) and the
# mid-response disconnect WITHOUT parking a worker. On a tiny -rpcthreads pool a
# genuinely parking long-poll + RPC-driven mining self-deadlocks (both workers
# wait for a block that only a third worker could mine); that is a pool-size
# artifact, not the fd bug, so the harness avoids it by default.
with SHARED_LOCK:
lpid = SHARED["lpid"]
if lpid and len(lpid) > 64:
h = lpid[:64]
flip = "0" if h[0] != "0" else "1"
return flip + h[1:] + lpid[64:]
return ("0" * 64) + "0"
def client_longpoll(cid):
while not STOP.is_set():
try:
s = mkconn(timeout=10.0)
except OSError:
ST.inc("connfail"); time.sleep(0.2); continue
rd = Reader(s)
params = [{"longpollid": _stale_lpid()}]
rid = next_id()
try:
s.sendall(req_bytes("getblocktemplate", params, rid, keepalive=False))
ST.inc("sent")
if random.random() < 0.5:
# impatient pool worker: abandon the request after 1-500 ms
time.sleep(random.uniform(0.001, 0.5))
end_early(s); continue
st, hd, bd = rd.read()
j = account(st, bd, rid, "getblocktemplate(lp)")
if j and isinstance(j, dict) and j.get("result"):
with SHARED_LOCK:
SHARED["lpid"] = j["result"].get("longpollid")
except (OSError, socket.timeout, EOFError, ValueError):
ST.inc("srvreset")
finally:
end_fin(s)
time.sleep(random.uniform(0.02, 0.2))
def miner(interval):
# Mine a block every `interval` seconds. Retry through work-queue rejections so
# blocks still land under heavy load (the production box mines steadily too).
while not STOP.is_set():
got = False
deadline = time.monotonic() + interval + 30
while not got and not STOP.is_set() and time.monotonic() < deadline:
try:
s = mkconn(timeout=60.0)
j, _ = call(s, Reader(s), "generate", [1], keepalive=False)
end_fin(s)
if j and not j.get("error") and j.get("result"):
ST.inc("mined"); got = True
h = j["result"][0] if isinstance(j["result"], list) else None
if h:
with SHARED_LOCK:
SHARED["hashes"].append(h)
SHARED["hashes"] = SHARED["hashes"][-200:]
else:
time.sleep(0.2) # likely work-queue 500; back off and retry
except Exception:
time.sleep(0.2)
for _ in range(int(interval * 10)):
if STOP.is_set():
break
time.sleep(0.1)
# ------------------------------------------------------------------ bootstrap shared state
def bootstrap():
try:
s = mkconn(timeout=30.0); rd = Reader(s)
j, _ = call(s, rd, "getbestblockhash", [], keepalive=True)
if j and j.get("result"):
with SHARED_LOCK:
SHARED["hashes"].append(j["result"])
j, _ = call(s, rd, "getblockcount", [], keepalive=True)
cnt = j.get("result") if j else None
if isinstance(cnt, int):
for hh in range(max(0, cnt - 30), cnt + 1):
jj, _ = call(s, rd, "getblockhash", [hh], keepalive=True)
if jj and jj.get("result"):
with SHARED_LOCK:
SHARED["hashes"].append(jj["result"])
j, _ = call(s, rd, "listaddresses", [], keepalive=True)
j, _ = call(s, rd, "z_listaddresses", [], keepalive=True)
if j and isinstance(j.get("result"), list):
with SHARED_LOCK:
SHARED["zaddrs"] = j["result"][:16]
j, _ = call(s, rd, "getblocktemplate", [{}], keepalive=True)
if j and isinstance(j.get("result"), dict):
with SHARED_LOCK:
SHARED["lpid"] = j["result"].get("longpollid")
end_fin(s)
log("bootstrap: %d hashes, %d zaddrs, lpid=%s" %
(len(SHARED["hashes"]), len(SHARED["zaddrs"]), bool(SHARED["lpid"])))
except Exception as e:
log("bootstrap failed: %s" % e)
# ------------------------------------------------------------------ fd accounting
def count_fds(pid):
if not pid:
return (None, None, None)
base = "/proc/%d/fd" % pid
try:
fds = os.listdir(base)
except OSError:
return (None, None, None)
sock = files = 0
for fd in fds:
try:
tgt = os.readlink(os.path.join(base, fd))
except OSError:
continue
if tgt.startswith("socket:"):
sock += 1
elif tgt.startswith("/"):
files += 1
return (len(fds), sock, files)
def pid_alive(pid):
if not pid:
return True
try:
os.kill(pid, 0); return True
except OSError:
return False
# ------------------------------------------------------------------ main
def reporter(pid):
t0 = time.monotonic()
while not STOP.is_set():
for _ in range(10):
if STOP.is_set():
break
time.sleep(0.1)
w = ST.swap()
tot, sk, fl = count_fds(pid)
fdstr = ""
if tot is not None:
fdstr = " | fds=%d sock=%d file=%d" % (tot, sk, fl)
log("t=%4ds ok=%d rpcerr=%d wq500=%d 4xx=%d other=%d | "
"earlyRST=%d earlyFIN=%d srvRST=%d srvEOF=%d ctmo=%d connfail=%d | "
"idmis=%d malf=%d | mined=%d halfopen=%d%s" % (
int(time.monotonic() - t0),
w["ok"], w["rpcerr"], w["wq500"], w["http4xx"], w["httpother"],
w["early_rst"], w["early_fin"], w["srvreset"], w["srveof"],
w["ctimeout"], w["connfail"], w["idmismatch"], w["malformed"],
w["mined"], w["half_open"], fdstr))
if pid and not pid_alive(pid):
log("!!! NODE PROCESS %d IS GONE -- stopping harness" % pid)
STOP.set()
break
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--host", default="127.0.0.1")
ap.add_argument("--port", type=int, default=19461)
ap.add_argument("--user", default="ab")
ap.add_argument("--password", default="abpass")
ap.add_argument("--duration", type=int, default=300)
ap.add_argument("--ctimeout", type=float, default=15.0)
ap.add_argument("--normal", type=int, default=24)
ap.add_argument("--impatient", type=int, default=10)
ap.add_argument("--slowfire", type=int, default=3,
help="paced clients that fire a genuinely-slow call then disconnect")
ap.add_argument("--slowfire-pace", type=float, default=2.0)
ap.add_argument("--halfopen", type=int, default=6)
ap.add_argument("--pipeline", type=int, default=6)
ap.add_argument("--garbage", type=int, default=4)
ap.add_argument("--slowread", type=int, default=2)
ap.add_argument("--longpoll", type=int, default=6)
# burst-size must exceed (rpcthreads + rpcworkqueue) to overflow the queue even
# when calls are fast; with -rpcthreads=8 -rpcworkqueue=4 that threshold is 12.
ap.add_argument("--burst-threads", type=int, default=1)
ap.add_argument("--burst-size", type=int, default=24)
ap.add_argument("--burst-every", type=float, default=1.5)
ap.add_argument("--mine", action="store_true", help="run a miner thread")
ap.add_argument("--mine-interval", type=float, default=4.0)
ap.add_argument("--pid", type=int, default=0, help="node pid, for /proc fd + liveness")
ap.add_argument("--logfile", default="")
args = ap.parse_args()
CFG.host = args.host; CFG.port = args.port
CFG.auth = auth_header(args.user, args.password); CFG.ctimeout = args.ctimeout
if args.logfile:
LOGF[0] = open(args.logfile, "a")
log("hammer start host=%s port=%d duration=%ds pid=%s" %
(CFG.host, CFG.port, args.duration, args.pid or "-"))
bootstrap()
threads = []
def spawn(fn, n, *a):
for i in range(n):
t = threading.Thread(target=fn, args=(i,) + a, daemon=True)
t.start(); threads.append(t)
spawn(client_normal, args.normal)
spawn(client_impatient, args.impatient)
spawn(client_slowfire, args.slowfire, args.slowfire_pace)
spawn(client_half_open, args.halfopen)
spawn(client_pipeline, args.pipeline)
spawn(client_garbage, args.garbage)
spawn(client_slowread, args.slowread)
spawn(client_longpoll, args.longpoll)
for i in range(args.burst_threads):
t = threading.Thread(target=client_burst, args=(i, args.burst_size, args.burst_every), daemon=True)
t.start(); threads.append(t)
if args.mine:
t = threading.Thread(target=miner, args=(args.mine_interval,), daemon=True)
t.start(); threads.append(t)
rt = threading.Thread(target=reporter, args=(args.pid,), daemon=True)
rt.start()
end = time.monotonic() + args.duration
try:
while time.monotonic() < end and not STOP.is_set():
time.sleep(0.2)
except KeyboardInterrupt:
pass
STOP.set()
time.sleep(1.0)
log("=== TOTALS ===")
for k in KEYS:
if ST.total[k]:
log(" %-14s %d" % (k, ST.total[k]))
log("anomalies: %d" % len(ST.anom))
for t, kind, detail in ST.anom[:40]:
log(" %s %s %s" % (time.strftime("%H:%M:%S", time.localtime(t)), kind, detail))
if args.pid:
log("node alive at end: %s" % pid_alive(args.pid))
if __name__ == "__main__":
main()
+29
View File
@@ -0,0 +1,29 @@
#!/usr/bin/env bash
# RPC-driven P2P peer churn on the target (same mix as fdbug/p2p/rpcchurn.sh):
# disconnectnode / addnode onetry / setban+clearbanned / kill -9 + restart of helper2.
# usage: rpcchurn.sh <run dir> <seconds>
source "$REPRO/common.sh"
OUT=$1; DUR=${2:-300}
DD_T=$OUT/target; DD_H1=$OUT/helper1; DD_H2=$OUT/helper2
end=$(( $(date +%s) + DUR )); i=0; restarts=0
while [ "$(date +%s)" -lt "$end" ] && [ ! -e "$OUT/STOP" ]; do
i=$((i+1))
case $(( i % 5 )) in
0) clin "$DD_T" "$RPC_T" disconnectnode "127.0.0.1:$P2P_H1" >/dev/null 2>&1 ;;
1) clin "$DD_T" "$RPC_T" addnode "127.0.0.1:$P2P_H1" onetry >/dev/null 2>&1 ;;
2) clin "$DD_T" "$RPC_T" setban "127.0.0.1" add 1 >/dev/null 2>&1; sleep 0.3
clin "$DD_T" "$RPC_T" clearbanned >/dev/null 2>&1
clin "$DD_H2" "$RPC_H2" addnode "127.0.0.1:$P2P_T" onetry >/dev/null 2>&1 ;;
3) pid=$(cat "$DD_H2/regtest/hushd.pid" 2>/dev/null)
if [ -n "$pid" ] && kill -0 "$pid" 2>/dev/null; then
kill -9 "$pid" 2>/dev/null
for _ in $(seq 1 20); do kill -0 "$pid" 2>/dev/null || break; sleep 0.5; done
start_helper "$DD_H2" "$P2P_H2" "$RPC_H2" "$OUT/logs/helper2.txt"
waitrpc "$DD_H2" "$RPC_H2" 120 >/dev/null 2>&1
restarts=$((restarts+1))
fi ;;
4) clin "$DD_T" "$RPC_T" addnode "127.0.0.1:$P2P_H2" onetry >/dev/null 2>&1 ;;
esac
sleep 0.7
done
echo "rpcchurn: $i cycles, $restarts helper2 restarts"
+113
View File
@@ -0,0 +1,113 @@
#!/usr/bin/env python3
"""
scan_bdb.py -- find Berkeley DB pages written into files that must not contain them
(blocks/blk*.dat, blocks/rev*.dat). Stand-in for the production incident tool.
BDB writes page P of a database at file offset P*pagesize through pwrite(fd, ...). If
fd has been closed and its number reused by a block file, the page lands in the block
file at exactly P*pagesize. So at every pagesize-aligned offset we decode the PAGE
header (db_page.h, all little-endian on x86):
0 u32 lsn.file 4 u32 lsn.offset 8 u32 pgno 12 u32 prev_pgno
16 u32 next_pgno 20 u16 entries 22 u16 hf_offset
24 u8 level 25 u8 type
and a metadata page (pgno 0 / any meta type) also carries magic at 12 and pagesize at 20.
A hit needs ALL of:
* pgno == offset // pagesize (the self-locating property)
* type is a real BDB page type (1..16 except 0)
* level consistent with type (overflow/meta/hash: 0; btree leaf: 1; internal: 2..32)
* hf_offset <= pagesize; entries <= pagesize/2
* for overflow (7): entries (refcount) >= 1 and 0 < hf_offset (data length) <= pagesize-26
Strength: "STRONG" if lsn == (0,1) (pages rewritten by lsn_reset -- the production
signature) or a meta page with a valid magic, else "weak".
Also reports any aligned BDB meta magic (btree 0x053162, hash 0x061561, queue 0x042253,
heap 0x074582) even when pgno does not match.
usage: scan_bdb.py [--pagesize 4096] [--all-offsets] files...
exit 0 = clean, 2 = hits.
"""
import argparse, struct, sys
TYPES = {1: "duplicate", 2: "hash_unsorted", 3: "ibtree", 4: "irecno", 5: "lbtree", 6: "lrecno",
7: "overflow", 8: "hashmeta", 9: "btreemeta", 10: "qammeta", 11: "qamdata", 12: "ldup",
13: "hash", 14: "heapmeta", 15: "heap", 16: "iheap"}
MAGIC = {0x053162: "btree", 0x061561: "hash", 0x042253: "queue", 0x074582: "heap"}
META = {8, 9, 10, 14}
def level_ok(t, lvl):
if t in (5, 6, 12): # leaf pages
return lvl == 1
if t in (3, 4): # internal pages
return 2 <= lvl <= 32
return lvl == 0 # overflow / meta / hash / queue / heap
def check(buf, off, ps):
if len(buf) < 26:
return None
lf, lo, pgno, prv, nxt, ent, hfo, lvl, typ = struct.unpack_from("<IIIIIHHBB", buf, 0)
if typ not in TYPES or pgno != off // ps or not level_ok(typ, lvl):
return None
if typ in META:
magic, ver, psz = struct.unpack_from("<III", buf, 12)
if magic not in MAGIC:
return None
return ("STRONG", f"{TYPES[typ]} magic={MAGIC[magic]} ver={ver} pagesize={psz} lsn=({lf},{lo})")
if hfo > ps or ent > ps // 2:
return None
if typ == 7 and not (ent >= 1 and 0 < hfo <= ps - 26):
return None
strength = "STRONG" if (lf, lo) == (0, 1) else "weak"
return (strength, f"{TYPES[typ]} lsn=({lf},{lo}) prev={prv} next={nxt} entries={ent} hf_offset={hfo} level={lvl}")
def scan(path, ps):
hits, magic_only = [], []
with open(path, "rb") as f:
off = 0
while True:
buf = f.read(ps)
if not buf:
break
r = check(buf, off, ps)
if r:
hits.append((off, off // ps) + r)
elif len(buf) >= 16:
m = struct.unpack_from("<I", buf, 12)[0]
if m in MAGIC and buf[25] in META:
magic_only.append((off, MAGIC[m]))
off += len(buf)
return hits, magic_only, off
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--pagesize", type=int, default=4096)
ap.add_argument("--quiet", action="store_true")
ap.add_argument("files", nargs="+")
a = ap.parse_args()
total = strong = 0
for p in a.files:
try:
hits, mo, size = scan(p, a.pagesize)
except OSError as e:
print(f"{p}: ERROR {e}")
continue
s = sum(1 for h in hits if h[2] == "STRONG")
total += len(hits); strong += s
if hits or mo:
print(f"{p}: {len(hits)} BDB page(s) ({s} strong), {len(mo)} stray meta magic, size={size}")
if not a.quiet:
for h in hits[:20]:
print(f" off={h[0]} pgno={h[1]} {h[2]} {h[3]}")
for m in mo[:5]:
print(f" meta-magic off={m[0]} {m[1]}")
else:
print(f"{p}: clean ({size} bytes)")
print(f"TOTAL BDB pages found: {total} ({strong} strong)")
return 2 if total else 0
if __name__ == "__main__":
sys.exit(main())
+80
View File
@@ -0,0 +1,80 @@
#!/usr/bin/env python3
"""tally.py <fdguard.log> -- attribute every fdguard report to (type, closer function, target class)
and, for EBADF/NON-OWNER reports, to the code that made the previous close of that fd number.
The point: show that the stray closes ORIGINATE in CNode code (net.cpp CloseSocketDisconnect /
~CNode closing a number they already closed) and that libevent / BDB / CreateNodeFromAcceptedSocket /
GetTransaction only appear as victims-turned-amplifiers downstream of that.
"""
import collections, re, sys
ORIGIN = ("_ZN5CNode21CloseSocketDisconnectEv", "_ZN5CNodeD1Ev", "_ZN5CNodeD2Ev", "_ZN11CNetCleanupD2Ev")
NAMES = {"_ZN5CNode21CloseSocketDisconnectEv": "CNode::CloseSocketDisconnect (net.cpp:572)",
"_ZN5CNodeD1Ev": "CNode::~CNode (net.cpp:2819)",
"_ZN11CNetCleanupD2Ev": "CNetCleanup::~CNetCleanup (net.cpp:2465, shutdown)",
"evhttp_connection_free": "libevent evhttp_connection_free (http.c:1244)",
"__os_closehandle": "BDB __os_closehandle",
"_Z28CreateNodeFromAcceptedSocketjbRK8CAddressS1_": "CreateNodeFromAcceptedSocket (net.cpp:1336)",
"_Z14GetTransactionRK7uint256R12CTransactionRS_b": "GetTransaction fclose (main.cpp)",
"epoll_nochangelist_add": "libevent epoll ADD", "epoll_nochangelist_del": "libevent epoll DEL/MOD"}
def fn(frame_line):
m = re.search(r"\+0x[0-9a-f]+ (\S+?)\+0x", frame_line)
return m.group(1) if m else "?"
def main(path):
reps, cur = [], None
for line in open(path, errors="replace"):
if line.startswith("=== FDGUARD #"):
cur = {"hdr": line.strip(), "lines": []}
reps.append(cur)
elif cur is not None:
if line.startswith("=== END"):
cur = None
else:
cur["lines"].append(line.rstrip("\n"))
tally = collections.Counter()
prev_tally = collections.Counter()
db_blk = []
for r in reps:
typ = r["hdr"].split()[3]
L = r["lines"]
cls = next((re.search(r"class=(\S+)", l).group(1) for l in L if " target=" in l and "class=" in l), "?")
try:
i = next(k for k, l in enumerate(L) if l.strip() == "closer stack:")
closer = fn(L[i + 1])
except StopIteration:
closer = "?"
prev = "-"
for k, l in enumerate(L):
if "previous successful close of this fd number" in l:
# first frame line after the target= line
for l2 in L[k + 1:k + 4]:
if l2.strip().startswith("#0"):
prev = fn(l2)
break
break
tally[(typ, NAMES.get(closer, closer), cls)] += 1
if typ in ("EBADF-CLOSE", "NON-OWNER-CLOSE"):
prev_tally[NAMES.get(prev, prev)] += 1
if typ == "NON-OWNER-CLOSE" and cls in ("db", "blk"):
tgt = next((l.split("target=")[1].split()[0] for l in L if " target=" in l), "?")
db_blk.append((r["hdr"].split()[2], r["hdr"].split()[4], NAMES.get(closer, closer), tgt.rsplit("/", 2)[-2:]))
print(f"{len(reps)} reports in {path}")
print("\n count type class closer")
for (typ, closer, cls), n in tally.most_common():
print(f"{n:6d} {typ:17s} {cls:6s} {closer}")
print("\nEBADF + NON-OWNER reports by the code that made the PREVIOUS close of the same number:")
for k, n in prev_tally.most_common():
print(f"{n:6d} {k}")
o = sum(n for (typ, c, cls), n in tally.items() if typ == "NON-OWNER-CLOSE" and cls in ("db", "blk") and c.startswith(("CNode", "CNetCleanup")))
a = sum(n for (typ, c, cls), n in tally.items() if typ == "NON-OWNER-CLOSE" and cls in ("db", "blk")) - o
print(f"\nNON-OWNER closes of wallet/BDB-log/block files: {o + a} (by CNode code directly: {o}; by an amplifier: {a})")
for d in db_blk[:40]:
print(" ", d[0], d[1], "closer=" + d[2], "target=" + "/".join(d[3]))
if __name__ == "__main__":
main(sys.argv[1])
+147
View File
@@ -0,0 +1,147 @@
#!/usr/bin/env python3
"""
Raw TCP / TLS client churn against the target node's P2P port.
dragonxd P2P is TLS 1.3 only (wolfSSL), self-signed, no cert verification. The
accept path is net.cpp CreateNodeFromAcceptedSocket -> tlsmanager.accept()
(wolfSSL_accept), and teardown is CloseSocketDisconnect / ~CNode
(wolfSSL_shutdown + wolfSSL_free + CloseSocket). This driver pokes the accept and
TLS-teardown/error paths (SSL_read/SSL_write at net.cpp ~1005 and tlsmanager.cpp
~660-680) by opening many short-lived connections that each misbehave:
rst : connect, then abort with RST (SO_LINGER 0) before any TLS bytes
fin : connect, then close cleanly (FIN) before any TLS bytes
garbage : connect, send non-ClientHello bytes, then drop
stall : connect, send a few bytes, hold mid-handshake, drop
tlsjunk : complete a real TLS 1.3 handshake (verify off), send junk, drop
tlshalf : start TLS, send a partial ClientHello record, drop
Loopback only, against a port this harness started. --duration seconds.
"""
import argparse, random, socket, ssl, struct, sys, time, os
def mk():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(3.0)
return s
def rst_close(s):
try:
s.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack("ii", 1, 0))
except Exception:
pass
try: s.close()
except Exception: pass
def do_rst(host, port):
s = mk()
try:
s.connect((host, port)); rst_close(s)
except Exception:
rst_close(s)
def do_fin(host, port):
s = mk()
try:
s.connect((host, port)); s.close()
except Exception:
try: s.close()
except Exception: pass
def do_garbage(host, port):
s = mk()
try:
s.connect((host, port))
s.sendall(os.urandom(random.randint(16, 400)))
time.sleep(random.uniform(0.0, 0.3))
except Exception:
pass
rst_close(s)
def do_stall(host, port):
s = mk()
try:
s.connect((host, port))
# a couple of bytes that look like the start of a TLS record, then wait
s.sendall(b"\x16\x03\x01")
time.sleep(random.uniform(0.5, 2.0))
except Exception:
pass
rst_close(s)
def _ctx():
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
try:
ctx.minimum_version = ssl.TLSVersion.TLSv1_3
except Exception:
pass
return ctx
def do_tlsjunk(host, port):
raw = mk()
try:
raw.connect((host, port))
tls = _ctx().wrap_socket(raw, server_hostname=None)
# handshake completed; the node now expects a P2P version message.
# send junk inside the TLS channel, then tear down.
try:
tls.sendall(os.urandom(random.randint(8, 128)))
except Exception:
pass
time.sleep(random.uniform(0.0, 0.4))
try:
tls.close()
except Exception:
rst_close(raw)
except Exception:
rst_close(raw)
def do_tlshalf(host, port):
s = mk()
try:
s.connect((host, port))
# a well-formed TLS record header claiming a long handshake, but we send
# only part of it, then drop -> server sits in wolfSSL_accept WANT_READ.
body = os.urandom(40)
rec = b"\x16\x03\x03" + struct.pack(">H", 512) + body
s.sendall(rec)
time.sleep(random.uniform(0.3, 1.5))
except Exception:
pass
rst_close(s)
HANDLERS = [do_rst, do_fin, do_garbage, do_stall, do_tlsjunk, do_tlshalf]
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--host", default="127.0.0.1")
ap.add_argument("--port", type=int, required=True)
ap.add_argument("--duration", type=float, default=300.0)
ap.add_argument("--concurrency", type=int, default=6)
ap.add_argument("--rate", type=float, default=0.03, help="sleep between bursts")
args = ap.parse_args()
end = time.time() + args.duration
counts = {h.__name__: 0 for h in HANDLERS}
import threading
lock = threading.Lock()
def worker():
while time.time() < end:
h = random.choice(HANDLERS)
h(args.host, args.port)
with lock:
counts[h.__name__] += 1
time.sleep(random.uniform(0.0, args.rate))
ts = [threading.Thread(target=worker, daemon=True) for _ in range(args.concurrency)]
for t in ts: t.start()
for t in ts: t.join()
total = sum(counts.values())
print(f"tcpchurn: {total} connections in {args.duration:.0f}s -> {counts}", flush=True)
if __name__ == "__main__":
main()
+15
View File
@@ -0,0 +1,15 @@
#!/bin/sh
# Build the fdguard LD_PRELOAD shim and its self-test program.
# ./build.sh -> libfdguard.so, fdguard_test
set -e
cd "$(dirname "$0")"
CC=${CC:-gcc}
$CC -O2 -g -fPIC -shared -Wall -Wextra -Wno-unused-parameter -fvisibility=default \
-o libfdguard.so.tmp fdguard.c -ldl -lpthread
# rename, never overwrite in place: a running process may have the old one mapped
mv -f libfdguard.so.tmp libfdguard.so
# the test program keeps its symbols (no -rdynamic on purpose: like dragonxd,
# owner detection must work from .symtab alone) and frame pointers for clarity
$CC -O1 -g -fno-omit-frame-pointer -fno-inline -Wall -o fdguard_test.tmp fdguard_test.c -lpthread
mv -f fdguard_test.tmp fdguard_test
echo "built: $(pwd)/libfdguard.so $(pwd)/fdguard_test"
File diff suppressed because it is too large Load Diff
+206
View File
@@ -0,0 +1,206 @@
/*
* fdguard_test.c -- exercises libfdguard.so.
*
* The function names imitate the real owners inside dragonxd so the shim's
* built-in domain patterns apply unchanged:
* __os_openhandle / __os_closehandle Berkeley DB os layer (domain bdb)
* OpenDiskFile / FlushBlockFile block-file code (domain blk)
* ConnectSocketDirectly / CloseSocket P2P sockets (domain p2p)
* foreign_stale_close / foreign_* somebody who holds a stale number
*
* usage: fdguard_test <dir> <case> (see main() for the list)
*/
#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/epoll.h>
#include <sys/socket.h>
#include <sys/syscall.h>
#include <time.h>
#include <unistd.h>
#define NI __attribute__((noinline))
static char D[512];
static char *P(const char *rel) { static char b[4][700]; static int i; i = (i + 1) & 3; snprintf(b[i], sizeof b[i], "%s/%s", D, rel); return b[i]; }
static void say(const char *m) { fprintf(stderr, "[test] %s\n", m); }
/* --- "Berkeley DB" --- */
NI int __os_openhandle(const char *path) { return open(path, O_RDWR | O_CREAT, 0600); }
NI int __os_closehandle(int fd) { return close(fd); }
/* --- "block files" --- */
NI FILE *OpenDiskFile(const char *path) { FILE *f = fopen(path, "rb+"); if (!f) f = fopen(path, "wb+"); return f; }
NI int FlushBlockFile(FILE *f) { fflush(f); return fclose(f); }
/* --- "P2P" --- */
NI int ConnectSocketDirectly(void) { return socket(AF_INET, SOCK_STREAM, 0); }
NI int CloseSocket(int *s) { int r = close(*s); if (r) fprintf(stderr, "[test] Socket close failed: %d. Error: %s\n", *s, strerror(errno)); return r; }
/* --- foreigners --- */
NI int foreign_stale_close(int fd) { return close(fd); }
NI int foreign_stale_fclose(FILE *f) { return fclose(f); }
NI int foreign_dup2(int fd) { int dn = open("/dev/null", O_RDWR); int r = dup2(dn, fd); close(dn); return r; }
NI int foreign_close_range(int fd) { return close_range((unsigned)fd, (unsigned)fd, 0); }
NI void foreign_closefrom(int fd) { closefrom(fd); }
/* --- plain code that opens and closes in the same function --- */
NI int copy_like(const char *src) { int fd = open(src, O_RDONLY); char b[16]; if (fd >= 0) { (void)!read(fd, b, sizeof b); close(fd); } return fd; }
NI int plain_open(const char *p) { return open(p, O_RDWR | O_CREAT, 0600); }
NI int plain_close(int fd) { return close(fd); }
static int fd_valid(int fd) { return fcntl(fd, F_GETFD) != -1; }
static int c_double(void)
{
int fd = plain_open(P("plain.txt"));
plain_close(fd);
int r = plain_close(fd); /* EBADF */
return r == -1 && errno == EBADF ? 0 : 1;
}
static int c_dbowner(void) { int fd = __os_openhandle(P("regtest/wallet.dat")); int r = __os_closehandle(fd); return r; }
static int c_dbforeign(void)
{
int fd = __os_openhandle(P("regtest/wallet.dat"));
foreign_stale_close(fd); /* HIT */
int r = __os_closehandle(fd); /* BDB's own close then fails: EBADF (unless deny) */
(void)r;
return 0;
}
static int c_deny(void)
{
int fd = __os_openhandle(P("regtest/wallet.dat"));
foreign_stale_close(fd); /* HIT + DENIED */
if (!fd_valid(fd)) { say("deny FAILED: fd closed"); return 1; }
if (write(fd, "x", 1) != 1) { say("deny FAILED: write"); return 1; }
return __os_closehandle(fd);
}
static int c_blkowner(void) { FILE *f = OpenDiskFile(P("regtest/blocks/blk00000.dat")); fputs("blk", f); return FlushBlockFile(f); }
static int c_blkraw(void)
{
FILE *f = OpenDiskFile(P("regtest/blocks/blk00001.dat"));
foreign_stale_close(fileno(f)); /* HIT: raw close under a live FILE */
FlushBlockFile(f); /* EBADF from fclose */
return 0;
}
static int c_stalefile(void)
{
FILE *f = OpenDiskFile(P("regtest/blocks/blk00002.dat"));
int n = fileno(f);
foreign_stale_close(n); /* HIT #1 */
int w = __os_openhandle(P("regtest/wallet.dat"));
if (w != n) fprintf(stderr, "[test] note: wallet got fd %d, FILE had %d\n", w, n);
FlushBlockFile(f); /* HIT #2: fclose of a stale FILE whose number is now wallet.dat */
if (w == n) __os_closehandle(w); /* EBADF: BDB lost its fd */
return 0;
}
static int c_reuse(void)
{
int s = ConnectSocketDirectly();
int keep = s;
CloseSocket(&s); /* legit */
int w = __os_openhandle(P("regtest/wallet.dat")); /* reuses the number */
if (w != keep) fprintf(stderr, "[test] note: wallet got fd %d, socket was %d\n", w, keep);
s = keep;
CloseSocket(&s); /* HIT: stale socket number now = wallet.dat */
__os_closehandle(w); /* EBADF */
return 0;
}
static int c_dup2(void) { int w = __os_openhandle(P("regtest/wallet.dat")); foreign_dup2(w); __os_closehandle(w); return 0; }
static int c_range(void)
{
int w = __os_openhandle(P("regtest/wallet.dat"));
foreign_close_range(w); /* HIT */
w = __os_openhandle(P("regtest/database/log.0000000001"));
int hi = fcntl(w, F_DUPFD, 600); /* move it high so closefrom only hits it */
close(w);
foreign_closefrom(hi); /* HIT (domain mismatch: opened by test main via fcntl dup? -> fallback db) */
return 0;
}
static int c_owner_misc(void)
{
/* nothing here may be flagged */
copy_like(P("regtest/wallet.dat")); /* common-caller */
int fd = __os_openhandle(P("regtest/blocks/blk00003.dat"));
FILE *f = fdopen(fd, "rb+"); /* ownership moves to FILE */
FlushBlockFile(f);
int s = ConnectSocketDirectly(); CloseSocket(&s);
fd = (int)syscall(SYS_openat, AT_FDCWD, P("regtest/wallet.dat"), O_RDWR); /* untracked open */
__os_closehandle(fd); /* fallback:bdb */
return 0;
}
static int c_fallback_hit(void)
{
int fd = (int)syscall(SYS_openat, AT_FDCWD, P("regtest/wallet.dat"), O_RDWR); /* untracked open */
foreign_stale_close(fd); /* HIT via fallback rule */
return 0;
}
static int c_epoll(void)
{
int ep = epoll_create1(0);
int fd = plain_open(P("plain2.txt"));
struct epoll_event ev = { .events = EPOLLIN };
int r = epoll_ctl(ep, EPOLL_CTL_ADD, fd, &ev); /* EPERM: regular file */
close(fd);
r = epoll_ctl(ep, EPOLL_CTL_ADD, fd, &ev); /* EBADF */
close(ep);
return r == -1 ? 0 : 1;
}
static int c_selfclose(void)
{
/* close every fd from 3 to 1100 by number, like a buggy daemonizer */
for (int i = 3; i < 1100; i++) close(i);
return 0;
}
/* concurrency + micro-benchmark: open/close churn in many threads */
static int nthr = 8, iters = 20000;
static void *worker(void *arg)
{
long id = (long)arg;
char p[700]; snprintf(p, sizeof p, "%s/thr%ld.txt", D, id);
for (int i = 0; i < iters; i++) {
int s = ConnectSocketDirectly(); CloseSocket(&s);
int fd = plain_open(p); plain_close(fd);
FILE *f = fopen(p, "r"); if (f) fclose(f);
if ((i & 255) == 0) { int w = __os_openhandle(P("regtest/wallet.dat")); __os_closehandle(w); }
}
return NULL;
}
static int c_threads(void)
{
const char *e = getenv("T_ITERS"); if (e) iters = atoi(e);
pthread_t t[64];
struct timespec a, b; clock_gettime(CLOCK_MONOTONIC, &a);
for (long i = 0; i < nthr; i++) pthread_create(&t[i], NULL, worker, (void *)i);
for (int i = 0; i < nthr; i++) pthread_join(t[i], NULL);
clock_gettime(CLOCK_MONOTONIC, &b);
double ns = (b.tv_sec - a.tv_sec) * 1e9 + (b.tv_nsec - a.tv_nsec);
long ops = (long)nthr * iters * 3;
printf("threads=%d iters=%d ops=%ld (socket/open/fopen + close each) wall=%.3fs %.0f ns/op-pair/thread\n",
nthr, iters, ops, ns / 1e9, ns * nthr / ops);
return 0;
}
int main(int argc, char **argv)
{
if (argc < 3) { fprintf(stderr, "usage: %s <dir> <case>\n", argv[0]); return 2; }
snprintf(D, sizeof D, "%s", argv[1]);
const char *c = argv[2];
if (!strcmp(c, "double")) return c_double();
if (!strcmp(c, "dbowner")) return c_dbowner();
if (!strcmp(c, "dbforeign")) return c_dbforeign();
if (!strcmp(c, "deny")) return c_deny();
if (!strcmp(c, "blkowner")) return c_blkowner();
if (!strcmp(c, "blkraw")) return c_blkraw();
if (!strcmp(c, "stalefile")) return c_stalefile();
if (!strcmp(c, "reuse")) return c_reuse();
if (!strcmp(c, "dup2")) return c_dup2();
if (!strcmp(c, "range")) return c_range();
if (!strcmp(c, "ownermisc")) return c_owner_misc();
if (!strcmp(c, "fallback")) return c_fallback_hit();
if (!strcmp(c, "epoll")) return c_epoll();
if (!strcmp(c, "selfclose")) return c_selfclose();
if (!strcmp(c, "threads")) return c_threads();
fprintf(stderr, "unknown case %s\n", c);
return 2;
}
+97
View File
@@ -0,0 +1,97 @@
#!/bin/bash
# Self-test for libfdguard.so. Every case lists the report types it must
# produce (exactly, in order) -- an empty list means "no report at all".
# ./run_tests.sh (builds first)
set -u
cd "$(dirname "$0")"
./build.sh >/dev/null || { echo "build failed"; exit 1; }
SO=$PWD/libfdguard.so
T=$PWD/t
rm -rf "$T"; mkdir -p "$T/regtest/blocks" "$T/regtest/database"
pass=0; fail=0
run() { # run <case> [ENV=VAL ...] -> sets RC, LOG
local c=$1; shift
LOG=$T/$c${SUFFIX:-}.log; rm -f "$LOG"
env FDGUARD_EXE=fdguard_test FDGUARD_LOG="$LOG" "$@" LD_PRELOAD="$SO" ./fdguard_test "$T" "$c" >"$T/$c${SUFFIX:-}.out" 2>&1
RC=$?
}
types() { grep '^=== FDGUARD' "$LOG" 2>/dev/null | awk '{print $4}' | tr '\n' ' ' | sed 's/ $//'; }
reasons() { grep -o 'reason=[^ ]*' "$LOG" 2>/dev/null | sed 's/reason=//' | tr '\n' ' ' | sed 's/ $//'; }
check() { # check <name> <cond-description> <actual> <expected>
if [ "$3" == "$4" ]; then pass=$((pass+1)); printf 'PASS %-12s %s\n' "$1" "$2";
else fail=$((fail+1)); printf 'FAIL %-12s %s\n got: [%s]\n want: [%s]\n' "$1" "$2" "$3" "$4"; fi
}
# case | expected report types | expected reasons
while IFS='|' read -r c want wantr; do
[ -z "$c" ] && continue
run "$c"
check "$c" "reports" "$(types)" "$want"
check "$c" "reasons" "$(reasons)" "$wantr"
check "$c" "exit 0" "$RC" "0"
done <<'EOF'
double|EBADF-CLOSE|
dbowner||
dbforeign|NON-OWNER-CLOSE EBADF-CLOSE|DOMAIN-MISMATCH
blkowner||
blkraw|NON-OWNER-CLOSE EBADF-CLOSE|stdio:RAW-CLOSE-UNDER-LIVE-FILE
stalefile|NON-OWNER-CLOSE NON-OWNER-CLOSE EBADF-CLOSE|stdio:RAW-CLOSE-UNDER-LIVE-FILE stdio:STALE-FILE
reuse|NON-OWNER-CLOSE EBADF-CLOSE|DOMAIN-MISMATCH
dup2|NON-OWNER-CLOSE|DOMAIN-MISMATCH
range|NON-OWNER-CLOSE NON-OWNER-CLOSE NON-OWNER-CLOSE|DOMAIN-MISMATCH DOMAIN-MISMATCH fallback:DB-FILE-CLOSED-OUTSIDE-BDB
ownermisc||
fallback|NON-OWNER-CLOSE|fallback:DB-FILE-CLOSED-OUTSIDE-BDB
epoll|EPOLL-CTL-EPERM EPOLL-CTL-EBADF|epoll_ctl(ADD)-failed epoll_ctl(ADD)-failed
EOF
# the previous close of the reused number must be the first CloseSocket (proves the double close)
run reuse
check reuse "history shows 1st CloseSocket on a socket" \
"$(grep -A2 'previous successful close' "$LOG" | head -3 | grep -c -e 'class=sock dom=p2p' -e 'CloseSocket+')" "2"
# the stale FILE report must name wallet.dat as the victim and OpenDiskFile as the FILE's opener
run stalefile
check stalefile "victim=wallet.dat, FILE opened in OpenDiskFile" \
"$(sed -n '/#2 NON-OWNER/,/=== END #2/p' "$LOG" | grep -m1 -c 'target=.*wallet.dat class=db') $(sed -n '/#2 NON-OWNER/,/=== END #2/p' "$LOG" | grep -A3 'which had been opened by: fopen' | grep -c 'OpenDiskFile+')" "1 1"
# the log fd survives a close-everything loop and the attempt is reported
run selfclose
check selfclose "log-fd close refused + reported" "$(grep -c 'CLOSE-OF-FDGUARD-LOG-FD' "$LOG")" "1"
check selfclose "log still writable afterwards (final stats)" "$(grep -c '^S .* final' "$LOG")" "1"
# abort mode: first non-owner close -> SIGABRT (rc 134), report already written
SUFFIX=_abort run dbforeign FDGUARD_ABORT=1
check abort "rc=134 (SIGABRT)" "$RC" "134"
check abort "report written before abort" "$(types)" "NON-OWNER-CLOSE"
# abort=2 also aborts on EBADF
SUFFIX=_abort2 run double FDGUARD_ABORT=2
check abort2 "rc=134 on EBADF" "$RC" "134"
# deny mode: wallet fd survives the foreign close; no EBADF afterwards
SUFFIX=_deny run deny FDGUARD_DENY=1
check deny "exit 0 (fd still valid + writable)" "$RC" "0"
check deny "reported as DENIED, no EBADF" "$(types) $(grep -c 'ACTION=DENIED' "$LOG")" "NON-OWNER-CLOSE 1"
# extra classes: guard=all with the owner cases must still be silent
SUFFIX=_all run ownermisc FDGUARD_GUARD=all
check guard-all "ownermisc silent with FDGUARD_GUARD=all" "$(types)" ""
# trace-all writes one T line per open/close
SUFFIX=_trace run dbowner FDGUARD_TRACE_ALL=1
check trace "T lines for open+close" "$(grep -c '^T ' "$LOG")" "2"
# passive in non-matching processes
LOG=$T/passive.log; env FDGUARD_EXE=dragonxd FDGUARD_LOG="$LOG" LD_PRELOAD="$SO" ./fdguard_test "$T" dbforeign >/dev/null 2>&1
check passive "no log when exe does not match" "$( [ -e "$LOG" ] && echo exists || echo none)" "none"
# concurrency: 8 threads x 5000 x (socket, open, fopen) churn, guard=all -> no reports
SUFFIX=_thr run threads T_ITERS=5000 FDGUARD_GUARD=all
check threads "no reports under 8-thread churn (guard=all)" "$(types)" ""
check threads "stats: HITS=0 EBADF=0" "$(grep '^S .*final' "$LOG" | grep -o 'HITS=[0-9]* EBADF=[0-9]*')" "HITS=0 EBADF=0"
# symbolizer resolves file:line for the test binary
check symbolize "addr2line resolved CloseSocket to fdguard_test.c" \
"$(./symbolize.py "$T/reuse.log" | grep -m1 -o 'in CloseSocket at .*fdguard_test.c:[0-9]*' | sed 's/.*fdguard_test.c:[0-9]*/ok/')" "ok"
echo "== $pass passed, $fail failed"
[ $fail -eq 0 ]
+212
View File
@@ -0,0 +1,212 @@
#!/usr/bin/env python3
"""
symbolize.py -- turn fdguard log frames into function + file:line.
Every stack frame in an fdguard report looks like
#3 0x5b96b433c991 /path/to/module+0x1991 c_dbforeign+0x2d [bdb]
where "+0x1991" is the ELF virtual address inside that module (runtime address
minus the module's load bias, so PIE executables and shared libraries need no
further adjustment; for a non-PIE executable it equals the absolute address).
Frames are return addresses, so we ask addr2line about vaddr-1 (the call
instruction), with -f -C -i (function, demangle, inline chain).
backtrace_symbols_fd lines "module(+0x1991)[0x...]" are symbolized too.
usage:
symbolize.py [options] LOG [LOG...] annotated log on stdout
symbolize.py --summary LOG one line per distinct report
options:
--map OLD=NEW read module OLD from path NEW instead (repeatable),
e.g. --map /path/to/deployed/dragonxd=./dragonxd.unstripped
--addr2line PATH addr2line binary (default: addr2line)
--only-reports drop T/S lines (trace + stats) from the output
"""
import os
import re
import subprocess
import sys
from collections import defaultdict, OrderedDict
FRAME_RE = re.compile(r'^(\s*#\d+ 0x[0-9a-f]+ )(\S+)\+0x([0-9a-f]+)(.*)$')
BSFD_RE = re.compile(r'^(\S+)\(\+0x([0-9a-f]+)\)\[0x[0-9a-f]+\]\s*$')
HDR_RE = re.compile(r'^=== FDGUARD #(\d+) (\S+)')
def parse_args(argv):
opts = {'map': {}, 'addr2line': 'addr2line', 'summary': False, 'only': False, 'logs': []}
it = iter(argv)
for a in it:
if a == '--map':
old, new = next(it).split('=', 1)
opts['map'][old] = new
elif a.startswith('--map='):
old, new = a[6:].split('=', 1)
opts['map'][old] = new
elif a == '--addr2line':
opts['addr2line'] = next(it)
elif a == '--summary':
opts['summary'] = True
elif a == '--only-reports':
opts['only'] = True
elif a in ('-h', '--help'):
print(__doc__)
sys.exit(0)
else:
opts['logs'].append(a)
if not opts['logs']:
opts['logs'] = ['-']
return opts
def read_lines(paths):
out = []
for p in paths:
f = sys.stdin if p == '-' else open(p, errors='replace')
out.extend(f.read().splitlines())
if f is not sys.stdin:
f.close()
return out
def resolve_module(mod, opts, known):
if mod in opts['map']:
return opts['map'][mod]
if os.path.exists(mod):
return mod
base = os.path.basename(mod)
for k in known:
if os.path.basename(k) == base and os.path.exists(opts['map'].get(k, k)):
return opts['map'].get(k, k)
return None
def run_addr2line(binary, addrs, a2l):
"""addrs: list of int vaddrs (already -1'd). returns {addr: [(func, loc), ...]}"""
res = {}
if not addrs:
return res
uniq = sorted(set(addrs))
try:
p = subprocess.run([a2l, '-a', '-f', '-C', '-i', '-e', binary] + ['0x%x' % a for a in uniq],
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, check=False)
except FileNotFoundError:
return res
cur = None
lines = p.stdout.splitlines()
i = 0
while i < len(lines):
ln = lines[i]
if re.match(r'^0x[0-9a-f]+$', ln):
cur = int(ln, 16)
res[cur] = []
i += 1
continue
func = ln
loc = lines[i + 1] if i + 1 < len(lines) else '??:0'
if cur is not None:
res[cur].append((func, loc))
i += 2
return res
def main():
opts = parse_args(sys.argv[1:])
lines = read_lines(opts['logs'])
if opts['summary']:
summary(lines)
return
# pass 1: collect modules + addresses
want = defaultdict(set)
known = OrderedDict()
for ln in lines:
m = FRAME_RE.match(ln)
if m:
known[m.group(2)] = 1
want[m.group(2)].add(max(int(m.group(3), 16) - 1, 0))
for ln in lines:
m = BSFD_RE.match(ln)
if m:
want[m.group(1)].add(max(int(m.group(2), 16) - 1, 0))
table = {}
for mod, addrs in want.items():
path = resolve_module(mod, opts, known)
if not path:
continue
table[mod] = run_addr2line(path, list(addrs), opts['addr2line'])
def fmt(mod, vaddr):
r = table.get(mod, {}).get(vaddr)
if not r:
return []
out = []
for j, (func, loc) in enumerate(r):
if func == '??' and loc.startswith('??'):
continue
# addr2line -i lists the innermost (inlined) frame first
tag = 'inlined:' if j < len(r) - 1 else 'in'
out.append('%s %s at %s' % (tag, func, loc))
return out
w = sys.stdout.write
for ln in lines:
if opts['only'] and (ln.startswith('T ') or ln.startswith('S ')):
continue
w(ln + '\n')
m = FRAME_RE.match(ln)
if m:
v = max(int(m.group(3), 16) - 1, 0)
for s in fmt(m.group(2), v):
w(' -> ' + s + '\n')
continue
m = BSFD_RE.match(ln)
if m:
v = max(int(m.group(2), 16) - 1, 0)
for s in fmt(m.group(1), v):
w(' -> ' + s + '\n')
def summary(lines):
"""one line per (type, reason, class, first exe closer frame)"""
groups = OrderedDict()
cur = None
in_closer = False
for ln in lines:
h = HDR_RE.match(ln)
if h:
cur = {'type': h.group(2), 'reason': '', 'cls': '', 'top': '', 'call': ''}
in_closer = False
continue
if cur is None:
continue
s = ln.strip()
if s.startswith('call:'):
cur['call'] = s.split('(')[0][6:]
elif s.startswith('target=') and ' class=' in s and not cur['cls']:
cur['cls'] = s.rsplit('class=', 1)[-1]
elif s.startswith('verdict='):
cur['reason'] = s.split('reason=', 1)[-1].split(' ')[0]
elif s == 'closer stack:':
in_closer = True
elif in_closer and FRAME_RE.match(ln):
parts = s.split(' ')
if len(parts) >= 4 and not cur['top'] and '/libc.so' not in parts[2] and '/libstdc++' not in parts[2]:
cur['top'] = parts[3]
elif in_closer and not s.startswith('#'):
in_closer = False
if s.startswith('=== END'):
k = (cur['type'], cur['call'], cur['reason'], cur['cls'], cur['top'])
groups[k] = groups.get(k, 0) + 1
cur = None
print('%6s %-22s %-12s %-6s %-40s %s' % ('count', 'type', 'call', 'class', 'reason', 'first closer frame'))
for (t, c, r, cl, top), n in groups.items():
print('%6d %-22s %-12s %-6s %-40s %s' % (n, t[:22], c, cl, r[:40], top))
stats = [ln for ln in lines if ln.startswith('S ')]
if stats:
print('\nlast stats line:\n ' + stats[-1])
if __name__ == '__main__':
main()
+87
View File
@@ -0,0 +1,87 @@
#!/usr/bin/env bash
# r4 now-tier acceptance harness. MUST run inside a network namespace: the v1.0.x binaries
# predate the regtest seed-injection fix and would otherwise dial the live DragonX network.
set -u
OLD=/home/dev/dragonx/release/dragonx-1.0.1-linux-amd64
NEW=/home/dev/dragonx-dev/src
ROOT=/tmp/claude-1000/-home-dev/45a644d6-ea0b-4b7c-8ec7-6ccb1a64afa7/scratchpad/r4lab
PASS=0; FAIL=0
ok(){ echo " PASS $1"; PASS=$((PASS+1)); }
no(){ echo " FAIL $1"; FAIL=$((FAIL+1)); }
# --- hard guardrail: refuse to run unisolated ---
if [ "$(ip route show 2>/dev/null | wc -l)" != "0" ]; then
echo "REFUSING: not in an isolated netns (routes present). Run under: unshare -rn"; exit 90
fi
ip link set lo up 2>/dev/null
echo "isolation: $(ip route show | wc -l) routes, $(ip -o link | wc -l) interface(s)"
conf(){ printf 'regtest=1\nrpcuser=t\nrpcpassword=t\nlisten=0\ndnsseed=0\n' > "$1/DRAGONX.conf"; }
start(){ # $1=bindir $2=datadir $3=extra
"$1/dragonxd" -regtest -datadir="$2" -connect=0 -listen=0 -dnsseed=0 $3 -daemon >/dev/null 2>&1
for i in $(seq 40); do "$1/dragonx-cli" -regtest -datadir="$2" -rpcuser=t -rpcpassword=t getblockcount >/dev/null 2>&1 && return 0; sleep 2; done
return 1; }
cli(){ "$1/dragonx-cli" -regtest -datadir="$2" -rpcuser=t -rpcpassword=t "${@:3}" 2>&1; }
stopn(){ cli "$1" "$2" stop >/dev/null 2>&1; sleep 6; }
rm -rf "$ROOT"; mkdir -p "$ROOT"
echo; echo "### build victim wallets with the OLD binary (v1.0.1) ###"
mkdir -p "$ROOT/base/regtest"; conf "$ROOT/base/regtest"
start "$OLD" "$ROOT/base/regtest" "" || { echo "old node failed to start"; exit 91; }
[ "$(cli "$OLD" "$ROOT/base/regtest" getconnectioncount)" = "0" ] && ok "victim-maker has 0 peers (isolated)" || no "victim-maker NOT isolated -- ABORT"
cli "$OLD" "$ROOT/base/regtest" getnewaddress >/dev/null
cli "$OLD" "$ROOT/base/regtest" z_getnewaddress >/dev/null
ZBEFORE=$(cli "$OLD" "$ROOT/base/regtest" z_listaddresses | tr -d ' \n')
stopn "$OLD" "$ROOT/base/regtest"
for v in C A B; do cp -a "$ROOT/base" "$ROOT/$v"; done
# A = salvaged by v1.0.1 (drops hdchain). B = A then USED on v1.0.1 (persists a bogus chain).
start "$OLD" "$ROOT/A/regtest" "-salvagewallet" && stopn "$OLD" "$ROOT/A/regtest"
start "$OLD" "$ROOT/B/regtest" "-salvagewallet" && stopn "$OLD" "$ROOT/B/regtest"
start "$OLD" "$ROOT/B/regtest" "" && { cli "$OLD" "$ROOT/B/regtest" z_getnewaddress >/dev/null; stopn "$OLD" "$ROOT/B/regtest"; }
echo " A hdchain records: $(strings "$ROOT/A/regtest/regtest/wallet.dat" | grep -c hdchain) (expect 0)"
echo " B hdchain records: $(strings "$ROOT/B/regtest/regtest/wallet.dat" | grep -c hdchain) (expect >=1)"
echo; echo "### open each on the NEW binary ###"
for v in C A B; do
D="$ROOT/$v/regtest"; L="$D/regtest/debug.log"
WDAT="$D/regtest/wallet.dat"
[ -f "$WDAT" ] || { echo " FAIL $v: wallet.dat not found at $WDAT"; exit 92; }
# NOT a byte-identical check: normal startup (keypool top-up, bestblock) rewrites wallet.dat for
# ANY wallet, healthy ones included -- verified with a control. The precise claim is that the
# degraded path never SYNTHESISES an hdchain record, so count that instead.
HD1=$(strings "$WDAT" | grep -c hdchain)
: > "$L" 2>/dev/null
if start "$NEW" "$D" "-exportdir=$D/exp"; then
STARTED=yes; DEG=$(grep -c "DEGRADED" "$L" 2>/dev/null)
MISS=$(grep -c "hdchain record is missing" "$L" 2>/dev/null)
MISM=$(grep -c "does not belong to this wallet" "$L" 2>/dev/null)
if [ "$v" = "A" ]; then
mkdir -p "$D/exp"; EXP=$(cli "$NEW" "$D" z_exportwallet r4dump 2>&1 | head -1)
DUMP=$(find "$D" -name 'r4dump' 2>/dev/null | head -1)
ZNEW=$(cli "$NEW" "$D" z_getnewaddress); TNEW=$(cli "$NEW" "$D" getnewaddress)
fi
stopn "$NEW" "$D"
else STARTED=no; DEG=0; MISS=0; MISM=0; fi
HD2=$(strings "$WDAT" | grep -c hdchain)
case $v in
C) [ "$STARTED" = yes ] && ok "C healthy wallet opens" || no "C healthy wallet failed to open"
[ "$DEG" = "0" ] && ok "C no false positive (not flagged degraded)" || no "C FALSE POSITIVE: healthy wallet flagged" ;;
A) [ "$STARTED" = yes ] && ok "A salvaged wallet opens (was DB_CORRUPT before)" || no "A salvaged wallet still refuses to open"
[ "$MISS" -ge 1 ] && ok "A flagged: hdchain missing" || no "A not flagged as missing-hdchain"
[ "$HD1" = "0" ] && [ "$HD2" = "0" ] && ok "A no hdchain synthesised (degraded path persists nothing)" || no "A hdchain record appeared ($HD1 -> $HD2)"
echo "$ZNEW" | grep -qi 'error' && ok "A z_getnewaddress refused cleanly (derivation gated)" || no "A z_getnewaddress derived anyway: $ZNEW"
echo "$TNEW" | grep -qiE '^R[a-zA-Z0-9]+$' && ok "A getnewaddress still works (legacy random t-key)" || no "A getnewaddress broke: $TNEW"
if [ -n "${DUMP:-}" ] && [ -f "$DUMP" ]; then
grep -qE '^# HDSeed=[0-9a-f]' "$DUMP" && no "E z_exportwallet emitted an HDSeed line on a degraded wallet" || ok "E z_exportwallet emitted no bogus HDSeed line"
else echo " SKIP E (no dump produced: $EXP)"; fi ;;
B) [ "$STARTED" = yes ] && ok "B poisoned wallet opens" || no "B poisoned wallet failed to open"
[ "$MISM" -ge 1 ] && ok "B CASE-3 DETECTOR FIRED (seedFp mismatch)" || no "B case-3 detector did NOT fire" ;;
esac
done
echo; echo "### $PASS passed, $FAIL failed ###"
exit $FAIL
+1 -1
View File
@@ -1,4 +1,4 @@
#!/usr/bin/env python2 #!/usr/bin/env python3
# Copyright (c) 2016-2024 The Hush developers # Copyright (c) 2016-2024 The Hush developers
# Copyright (c) 2016 The Zcash developers # Copyright (c) 2016 The Zcash developers
# Distributed under the GPLv3 software license, see the accompanying # Distributed under the GPLv3 software license, see the accompanying
+2 -2
View File
@@ -1,4 +1,4 @@
#!/usr/bin/env python2 #!/usr/bin/env python3
# Copyright (c) 2016-2024 The Hush developers # Copyright (c) 2016-2024 The Hush developers
# Copyright (c) 2014 The Bitcoin Core developers # Copyright (c) 2014 The Bitcoin Core developers
# Distributed under the GPLv3 software license, see the accompanying # Distributed under the GPLv3 software license, see the accompanying
@@ -52,7 +52,7 @@ class GetBlockTemplateLPTest(BitcoinTestFramework):
''' '''
def run_test(self): def run_test(self):
print "Warning: this test will take about 70 seconds in the best case. Be patient." print("Warning: this test will take about 70 seconds in the best case. Be patient.")
self.nodes[0].generate(10) self.nodes[0].generate(10)
templat = self.nodes[0].getblocktemplate() templat = self.nodes[0].getblocktemplate()
longpollid = templat['longpollid'] longpollid = templat['longpollid']
+74 -9
View File
@@ -1,4 +1,4 @@
#!/usr/bin/env python2 #!/usr/bin/env python3
# Copyright (c) 2016-2024 The Hush developers # Copyright (c) 2016-2024 The Hush developers
# Copyright (c) 2014 The Bitcoin Core developers # Copyright (c) 2014 The Bitcoin Core developers
# Distributed under the GPLv3 software license, see the accompanying # Distributed under the GPLv3 software license, see the accompanying
@@ -6,6 +6,7 @@
from test_framework.test_framework import BitcoinTestFramework from test_framework.test_framework import BitcoinTestFramework
from test_framework.authproxy import JSONRPCException from test_framework.authproxy import JSONRPCException
from test_framework.util import initialize_chain_clean, start_node
from binascii import a2b_hex, b2a_hex from binascii import a2b_hex, b2a_hex
from hashlib import sha256 from hashlib import sha256
@@ -69,14 +70,43 @@ def genmrklroot(leaflist):
cur = n cur = n
return cur[0] return cur[0]
# ---------------------------------------------------------------------------
# Sapling v4 transaction layout.
#
# This test was written against the pre-Overwinter serialization, where a tx
# began with a 4-byte nVersion immediately followed by the vin count, so the
# first input's prevout hash lived at offset 4+1. DragonX transactions are
# Sapling v4: 4-byte header (nVersion | fOverwintered) + 4-byte nVersionGroupId
# + vin count, so the prevout hash starts 4 bytes further in. Poking the old
# offset corrupts nVersionGroupId and every proposal below just comes back
# "Block decode failed" instead of exercising any consensus rule.
CB_PREVOUT_OFF = 4+4+1
# Likewise the tx no longer ends at nLockTime: nExpiryHeight (4), valueBalance
# (8) and the empty vShieldedSpend/vShieldedOutput/vJoinSplit counts (1 each)
# trail it, so nLockTime is the 4 bytes at [-19:-15].
TX_TAIL_AFTER_LOCKTIME = 4+8+1+1+1
def tx_seq_off(tx):
"""Offset of the first input's nSequence in a Sapling v4 tx."""
scriptlen_off = CB_PREVOUT_OFF + 32 + 4 # after prevout hash + prevout.n
return scriptlen_off + 1 + tx[scriptlen_off]
def tx_vout0_value_off(tx):
"""Offset of the first output's 8-byte value in a Sapling v4 tx."""
return tx_seq_off(tx) + 4 + 1 # after nSequence + vout count
def template_to_bytes(tmpl, txlist): def template_to_bytes(tmpl, txlist):
blkver = pack('<L', tmpl['version']) blkver = pack('<L', tmpl['version'])
mrklroot = genmrklroot(list(dblsha(a) for a in txlist)) mrklroot = genmrklroot(list(dblsha(a) for a in txlist))
reserved = b'\0'*32 # hashFinalSaplingRoot. The all-zeroes placeholder this test used predates
# Sapling; a header carrying the wrong root is rejected with
# 'bad-sapling-root-in-block', which would sink even Test 11 (valid block).
reserved = a2b_hex(tmpl['finalsaplingroothash'])[::-1]
timestamp = pack('<L', tmpl['curtime']) timestamp = pack('<L', tmpl['curtime'])
nonce = b'\0'*32 nonce = b'\0'*32
soln = b'\0' soln = b'\0'
blk = blkver + a2b_hex(tmpl['previousblockhash'])[::-1] + mrklroot + reserved + timestamp + a2b_hex(tmpl['bits'])[::-1] + nonce + soln # bytearray, not bytes: Test 9 mutates one byte of the result in place.
blk = bytearray(blkver + a2b_hex(tmpl['previousblockhash'])[::-1] + mrklroot + reserved + timestamp + a2b_hex(tmpl['bits'])[::-1] + nonce + soln)
blk += varlenEncode(len(txlist)) blk += varlenEncode(len(txlist))
for tx in txlist: for tx in txlist:
blk += tx blk += tx
@@ -95,6 +125,20 @@ class GetBlockTemplateProposalTest(BitcoinTestFramework):
Test block proposals with getblocktemplate. Test block proposals with getblocktemplate.
''' '''
def setup_chain(self):
print("Initializing test directory "+self.options.tmpdir)
initialize_chain_clean(self.options.tmpdir, 1)
def setup_network(self, split=False):
# -daaforkheight=0: ContextualCheckBlockHeader only enforces nBits for a
# smart chain above daaForkHeight, which defaults to
# ASSETCHAINS_RANDOMX_VALIDATION+62000 (millions of blocks) so that a
# fresh sync accepts DragonX's historical bad-nBits window. Without this
# flag Test 8 (bad bits) is unreachable at regtest heights and the
# daemon happily accepts a block with arbitrary nBits.
self.nodes = [ start_node(0, self.options.tmpdir, ['-daaforkheight=0']) ]
self.is_network_split = False
def run_test(self): def run_test(self):
node = self.nodes[0] node = self.nodes[0]
node.generate(1) # Mine a block to leave initial block download node.generate(1) # Mine a block to leave initial block download
@@ -117,9 +161,9 @@ class GetBlockTemplateProposalTest(BitcoinTestFramework):
#txlist[0][4+1+36+1+1] -= 1 #txlist[0][4+1+36+1+1] -= 1
# Test 2: Bad input hash for gen tx # Test 2: Bad input hash for gen tx
txlist[0][4+1] += 1 txlist[0][CB_PREVOUT_OFF] += 1
assert_template(node, tmpl, txlist, 'bad-cb-missing') assert_template(node, tmpl, txlist, 'bad-cb-missing')
txlist[0][4+1] -= 1 txlist[0][CB_PREVOUT_OFF] -= 1
# Test 3: Truncated final tx # Test 3: Truncated final tx
lastbyte = txlist[-1].pop() lastbyte = txlist[-1].pop()
@@ -136,14 +180,33 @@ class GetBlockTemplateProposalTest(BitcoinTestFramework):
# Test 5: Add an invalid tx to the end (non-duplicate) # Test 5: Add an invalid tx to the end (non-duplicate)
txlist.append(bytearray(txlist[0])) txlist.append(bytearray(txlist[0]))
txlist[-1][4+1] = b'\xff' txlist[-1][CB_PREVOUT_OFF] = 0xff
# DragonX is a fully private chain (ASSETCHAINS_PRIVATE): a non-coinbase
# tx paying a positive amount to a t-addr is killed in CheckTransaction
# with 'bad-txns-acprivacy-chain' before ConnectBlock ever looks up its
# inputs. Zero the output value -- CheckTransaction exempts zero-value
# vouts -- so the tx survives to the missing-input check this case is
# actually about.
_val_off = tx_vout0_value_off(txlist[-1])
txlist[-1][_val_off:_val_off+8] = b'\0'*8
assert_template(node, tmpl, txlist, 'bad-txns-inputs-missingorspent') assert_template(node, tmpl, txlist, 'bad-txns-inputs-missingorspent')
txlist.pop() txlist.pop()
# Test 6: Future tx lock time # Test 6: Future tx lock time
txlist[0][-4:] = b'\xff\xff\xff\xff' # The server-supplied coinbase carries nSequence=0xffffffff, and
# IsFinalTx() short-circuits on all-final inputs, so a future nLockTime
# alone leaves the tx final and the block valid. (DragonX's IsFinalTx
# also whitelists 0xfffffffe below the Hush hardfork height, which
# regtest is.) Make the input genuinely non-final so the future
# nLockTime is the thing under test.
seq_off = tx_seq_off(txlist[0])
realseq = txlist[0][seq_off:seq_off+4]
txlist[0][seq_off:seq_off+4] = b'\0\0\0\0'
reallocktime = txlist[0][-TX_TAIL_AFTER_LOCKTIME-4:-TX_TAIL_AFTER_LOCKTIME]
txlist[0][-TX_TAIL_AFTER_LOCKTIME-4:-TX_TAIL_AFTER_LOCKTIME] = b'\xff\xff\xff\xff'
assert_template(node, tmpl, txlist, 'bad-txns-nonfinal') assert_template(node, tmpl, txlist, 'bad-txns-nonfinal')
txlist[0][-4:] = b'\0\0\0\0' txlist[0][-TX_TAIL_AFTER_LOCKTIME-4:-TX_TAIL_AFTER_LOCKTIME] = reallocktime
txlist[0][seq_off:seq_off+4] = realseq
# Test 7: Bad tx count # Test 7: Bad tx count
txlist.append(b'') txlist.append(b'')
@@ -171,7 +234,9 @@ class GetBlockTemplateProposalTest(BitcoinTestFramework):
tmpl['curtime'] = 0x7fffffff tmpl['curtime'] = 0x7fffffff
assert_template(node, tmpl, txlist, 'time-too-new') assert_template(node, tmpl, txlist, 'time-too-new')
tmpl['curtime'] = 0 tmpl['curtime'] = 0
assert_template(node, tmpl, txlist, 'time-too-old') # DragonX split Bitcoin's 'time-too-old' into 'time-too-old-median'
# (block time <= prev MedianTimePast) and 'time-too-old-prevblock'.
assert_template(node, tmpl, txlist, 'time-too-old-median')
tmpl['curtime'] = realtime tmpl['curtime'] = realtime
# Test 11: Valid block # Test 11: Valid block
+2 -2
View File
@@ -1,4 +1,4 @@
#!/usr/bin/env python2 #!/usr/bin/env python3
# Copyright (c) 2014 The Bitcoin Core developers # Copyright (c) 2014 The Bitcoin Core developers
# Copyright (c) 2016-2024 The Hush developers # Copyright (c) 2016-2024 The Hush developers
# Released under the GPLv3 # Released under the GPLv3
@@ -28,7 +28,7 @@ class ReindexTest(BitcoinTestFramework):
wait_bitcoinds() wait_bitcoinds()
self.nodes[0]=start_node(0, self.options.tmpdir, ["-debug", "-reindex", "-checkblockindex=1"]) self.nodes[0]=start_node(0, self.options.tmpdir, ["-debug", "-reindex", "-checkblockindex=1"])
assert_equal(self.nodes[0].getblockcount(), 3) assert_equal(self.nodes[0].getblockcount(), 3)
print "Success" print("Success")
if __name__ == '__main__': if __name__ == '__main__':
ReindexTest().main() ReindexTest().main()
+1 -1
View File
@@ -7,7 +7,7 @@
# and for constructing a getheaders message # and for constructing a getheaders message
# #
from mininode import CBlock, CBlockHeader, CBlockLocator, CTransaction, msg_block, msg_headers, msg_tx from .mininode import CBlock, CBlockHeader, CBlockLocator, CTransaction, msg_block, msg_headers, msg_tx
import sys import sys
import cStringIO import cStringIO
+2 -2
View File
@@ -3,8 +3,8 @@
# Distributed under the GPLv3 software license, see the accompanying # Distributed under the GPLv3 software license, see the accompanying
# file COPYING or https://www.gnu.org/licenses/gpl-3.0.en.html # file COPYING or https://www.gnu.org/licenses/gpl-3.0.en.html
# blocktools.py - utilities for manipulating blocks and transactions # blocktools.py - utilities for manipulating blocks and transactions
from mininode import CBlock, CTransaction, CTxIn, CTxOut, COutPoint from .mininode import CBlock, CTransaction, CTxIn, CTxOut, COutPoint
from script import CScript, OP_0, OP_EQUAL, OP_HASH160 from .script import CScript, OP_0, OP_EQUAL, OP_HASH160
# Create a block (with regtest difficulty) # Create a block (with regtest difficulty)
def create_block(hashprev, coinbase, nTime=None, nBits=None): def create_block(hashprev, coinbase, nTime=None, nBits=None):
+3 -3
View File
@@ -3,10 +3,10 @@
# Distributed under the GPLv3 software license, see the accompanying # Distributed under the GPLv3 software license, see the accompanying
# file COPYING or https://www.gnu.org/licenses/gpl-3.0.en.html # file COPYING or https://www.gnu.org/licenses/gpl-3.0.en.html
from mininode import CBlock, CTransaction, CInv, NodeConn, NodeConnCB, \ from .mininode import CBlock, CTransaction, CInv, NodeConn, NodeConnCB, \
msg_inv, msg_getheaders, msg_ping, msg_mempool, mininode_lock, MAX_INV_SZ msg_inv, msg_getheaders, msg_ping, msg_mempool, mininode_lock, MAX_INV_SZ
from blockstore import BlockStore, TxStore from .blockstore import BlockStore, TxStore
from util import p2p_port from .util import p2p_port
import time import time
@@ -11,8 +11,8 @@ import shutil
import tempfile import tempfile
import traceback import traceback
from authproxy import JSONRPCException from .authproxy import JSONRPCException
from util import assert_equal, check_json_precision, \ from .util import assert_equal, check_json_precision, \
initialize_chain, initialize_chain_clean, \ initialize_chain, initialize_chain_clean, \
start_nodes, connect_nodes_bi, stop_nodes, \ start_nodes, connect_nodes_bi, stop_nodes, \
sync_blocks, sync_mempools, wait_bitcoinds sync_blocks, sync_mempools, wait_bitcoinds
@@ -91,7 +91,7 @@ class BitcoinTestFramework(object):
parser.add_option("--noshutdown", dest="noshutdown", default=False, action="store_true", parser.add_option("--noshutdown", dest="noshutdown", default=False, action="store_true",
help="Don't stop nodes after the test execution") help="Don't stop nodes after the test execution")
parser.add_option("--srcdir", dest="srcdir", default="../../src", parser.add_option("--srcdir", dest="srcdir", default="../../src",
help="Source directory containing hushd/hush-cli (default: %default)") help="Source directory containing dragonxd/dragonx-cli (default: %default)")
parser.add_option("--tmpdir", dest="tmpdir", default=tempfile.mkdtemp(prefix="test"), parser.add_option("--tmpdir", dest="tmpdir", default=tempfile.mkdtemp(prefix="test"),
help="Root directory for datadirs") help="Root directory for datadirs")
parser.add_option("--tracerpc", dest="trace_rpc", default=False, action="store_true", parser.add_option("--tracerpc", dest="trace_rpc", default=False, action="store_true",
+70 -20
View File
@@ -18,7 +18,7 @@ import subprocess
import time import time
import re import re
from authproxy import AuthServiceProxy from .authproxy import AuthServiceProxy
def p2p_port(n): def p2p_port(n):
return 11000 + n + os.getpid()%999 return 11000 + n + os.getpid()%999
@@ -97,8 +97,8 @@ def initialize_datadir(dirname, n):
print("Creating dirs %s" % datadir) print("Creating dirs %s" % datadir)
os.makedirs(datadir) os.makedirs(datadir)
print("Writing to " + os.path.join(datadir,"ZZZ.conf")) print("Writing to " + os.path.join(datadir,"DRAGONX.conf"))
with open(os.path.join(datadir, "ZZZ.conf"), 'w') as f: with open(os.path.join(datadir, "DRAGONX.conf"), 'w') as f:
f.write("regtest=1\n"); f.write("regtest=1\n");
f.write("txindex=1\n"); f.write("txindex=1\n");
#f.write("testnode=1\n"); #f.write("testnode=1\n");
@@ -116,7 +116,19 @@ def initialize_datadir(dirname, n):
f.write("spentindex=1\n"); f.write("spentindex=1\n");
f.write("timestampindex=1\n"); f.write("timestampindex=1\n");
#f.write("zindex=1\n"); #f.write("zindex=1\n");
print("Done writing to %s" % os.path.join(datadir,"ZZZ.conf") ) print("Done writing to %s" % os.path.join(datadir,"DRAGONX.conf") )
# dragonxd refuses to start without an asmap file ("Could not find any asmap file!"),
# so every regtest datadir needs one. Link the tree's copy rather than duplicating it.
for src in ("../../../asmap.dat", "../../../src/asmap.dat",
os.path.expanduser("~/.hush/DRAGONX/asmap.dat")):
cand = src if os.path.isabs(src) else os.path.join(os.path.dirname(os.path.abspath(__file__)), src)
if os.path.exists(cand):
dst = os.path.join(datadir, "asmap.dat")
if not os.path.exists(dst):
try: os.symlink(os.path.realpath(cand), dst)
except OSError: shutil.copyfile(cand, dst)
break
return datadir return datadir
@@ -133,11 +145,23 @@ def initialize_chain(test_dir):
# Create cache directories, run hushds: # Create cache directories, run hushds:
for i in range(4): for i in range(4):
datadir=initialize_datadir("cache", i) datadir=initialize_datadir("cache", i)
args = [ os.getenv("BITCOIND", "hushd"), "-keypool=1", "-datadir="+datadir, "-discover=0" ] # Same two requirements as start_node(): -regtest must be a command-line flag (the
# conf key is ignored, and without it this cache node runs on MAINNET), and -asmap
# must be absolute or dragonxd refuses to start.
# -connect=<anything> makes init.cpp soft-set -listen=0 ("parameter interaction: -connect
# set -> setting -listen=0"), so cache node0 never opened its p2p port and nodes 1-3 could
# never sync to it -- initialize_chain() then hung forever in sync_blocks(). Pass -listen
# and -bind explicitly (an explicit arg beats SoftSetBoolArg) and keep the loopback bind so
# the cache nodes stay off the public network.
args = [ os.getenv("BITCOIND", "src/dragonxd"), "-regtest", "-connect=0", "-keypool=1", "-datadir="+datadir, "-discover=0",
"-listen=1", "-bind=127.0.0.1", "-dnsseed=0" ]
_am = os.path.join(os.path.dirname(os.path.abspath(__file__)), "../../../asmap.dat")
if os.path.exists(_am):
args.append("-asmap=" + os.path.realpath(_am))
if i > 0: if i > 0:
args.append("-connect=127.0.0.1:"+str(p2p_port(0))) args.append("-connect=127.0.0.1:"+str(p2p_port(0)))
bitcoind_processes[i] = subprocess.Popen(args) bitcoind_processes[i] = subprocess.Popen(args)
cmd = os.getenv("BITCOINCLI", "hush-cli") cmd = os.getenv("BITCOINCLI", "src/dragonx-cli")
cmd_args = cmd + " -datadir="+datadir + " -rpcwait getblockcount" cmd_args = cmd + " -datadir="+datadir + " -rpcwait getblockcount"
if os.getenv("PYTHON_DEBUG", ""): if os.getenv("PYTHON_DEBUG", ""):
print("initialize_chain: hushd started, calling: " + cmd_args) print("initialize_chain: hushd started, calling: " + cmd_args)
@@ -180,10 +204,17 @@ def initialize_chain(test_dir):
wait_bitcoinds() wait_bitcoinds()
for i in range(4): for i in range(4):
print("Cleaning up cache dir files") print("Cleaning up cache dir files")
os.remove(log_filename("cache", i, "debug.log")) # log_filename() points at <cache>/node<i>/regtest, but that IS the -datadir we passed;
os.remove(log_filename("cache", i, "db.log")) # dragonxd writes its logs/peers.dat one level deeper, into the net-specific
os.remove(log_filename("cache", i, "peers.dat")) # <datadir>/regtest subdir (same datadir-vs-netdir split that forced -asmap to be
os.remove(log_filename("cache", i, "fee_estimates.dat")) # absolute in start_node). Try both, and tolerate files a node never created.
for name in ("debug.log", "db.log", "peers.dat", "fee_estimates.dat"):
for cand in (log_filename("cache", i, os.path.join("regtest", name)),
log_filename("cache", i, name)):
try:
os.remove(cand)
except OSError:
pass
for i in range(4): for i in range(4):
from_dir = os.path.join("cache", "node"+str(i)) from_dir = os.path.join("cache", "node"+str(i))
@@ -227,9 +258,10 @@ def start_node(i, dirname, extra_args=None, rpchost=None, timewait=None, binary=
""" """
print("Starting node " + str(i) + " in dir " + dirname) print("Starting node " + str(i) + " in dir " + dirname)
datadir = os.path.join(dirname, "node"+str(i), "regtest") datadir = os.path.join(dirname, "node"+str(i), "regtest")
if extra_args is None: extra_args = []
# creating special config # creating special config
if len(extra_args) > 0 and extra_args[0] == '-ac_name=ZZZ': if len(extra_args) > 0 and extra_args[0] == '-ac_name=ZZZ':
configpath = datadir + "/ZZZ.conf" configpath = datadir + "/DRAGONX.conf"
with open(configpath, "w+") as config: with open(configpath, "w+") as config:
config.write("rpcuser=hush\n") config.write("rpcuser=hush\n")
config.write("rpcpassword=puppy\n") config.write("rpcpassword=puppy\n")
@@ -247,16 +279,30 @@ def start_node(i, dirname, extra_args=None, rpchost=None, timewait=None, binary=
print("Done writing to %s" % configpath) print("Done writing to %s" % configpath)
if binary is None: if binary is None:
binary = os.getenv("BITCOIND", "src/hushd") binary = os.getenv("BITCOIND", "src/dragonxd")
args = [ binary, "-datadir="+datadir, "-keypool=1", "-discover=0", "-rest" ] # -regtest MUST be a command-line flag. DragonX ignores "regtest=1" in the conf file, so
# without this the node silently runs on MAINNET: it loads the real genesis, dials the real
# seeds and starts syncing the live chain into the test datadir (observed: 196k blocks and
# 679MB before a test timed out). -connect=0 keeps the regtest node off the public network.
args = [ binary, "-regtest", "-connect=0", "-datadir="+datadir, "-keypool=1", "-discover=0", "-rest" ]
# -asmap relative paths are resolved against the NET-SPECIFIC datadir (init.cpp), which for
# regtest is <datadir>/regtest -- so a copy sitting in <datadir> is never found. Pass an
# absolute path; without it dragonxd exits with "Could not find any asmap file!".
_asmap = os.path.join(os.path.dirname(os.path.abspath(__file__)), "../../../asmap.dat")
if os.path.exists(_asmap):
args.append("-asmap=" + os.path.realpath(_asmap))
if extra_args is not None: args.extend(extra_args) if extra_args is not None: args.extend(extra_args)
print("args=" + ' '.join(args)) print("args=" + ' '.join(args))
bitcoind_processes[i] = subprocess.Popen(args) bitcoind_processes[i] = subprocess.Popen(args)
devnull = open("/dev/null", "w+") devnull = open("/dev/null", "w+")
cmd = os.getenv("BITCOINCLI", "src/hush-cli") cmd = os.getenv("BITCOINCLI", "src/dragonx-cli")
print("cmd=" + cmd) print("cmd=" + cmd)
args = [ extra_args[0], "-datadir="+datadir, "-keypool=1", "-discover=0", "-rest" ] # The CLI only needs the datadir: initialize_datadir() already wrote DRAGONX.conf there
# with the right rpcport/user/password. The old form passed extra_args[0] as argv[0] and
# replayed daemon-only flags at the CLI, which only worked for the -ac_name=ZZZ assetchain
# tests and broke every test that passes no extra_args.
args = [ "-regtest", "-datadir="+datadir ]
cmd_args = ' '.join(args) + " -rpcwait getblockcount " cmd_args = ' '.join(args) + " -rpcwait getblockcount "
if os.getenv("PYTHON_DEBUG", ""): if os.getenv("PYTHON_DEBUG", ""):
print("start_node: hushd started, calling : " + cmd + " " + cmd_args) print("start_node: hushd started, calling : " + cmd + " " + cmd_args)
@@ -266,18 +312,22 @@ def start_node(i, dirname, extra_args=None, rpchost=None, timewait=None, binary=
import time import time
time.sleep(2) time.sleep(2)
subprocess.check_call(strcmd, shell=True); subprocess.check_call(strcmd, shell=True);
#subprocess.check_call([ os.getenv("BITCOINCLI", "hush-cli"), "-datadir="+datadir] + #subprocess.check_call([ os.getenv("BITCOINCLI", "dragonx-cli"), "-datadir="+datadir] +
# _rpchost_to_args(rpchost) + # _rpchost_to_args(rpchost) +
# ["-rpcwait", "-rpcport=6438", "getblockcount"], stdout=devnull) # ["-rpcwait", "-rpcport=6438", "getblockcount"], stdout=devnull)
if os.getenv("PYTHON_DEBUG", ""): if os.getenv("PYTHON_DEBUG", ""):
print("start_node: calling hush-cli -rpcwait getblockcount returned") print("start_node: calling hush-cli -rpcwait getblockcount returned")
devnull.close() devnull.close()
port = extra_args[3] # Port comes from the same helper initialize_datadir() used, except for the assetchain
#port = rpc_port(i) # tests which pass it positionally as extra_args[3] == "-rpcport=NNNN".
if len(extra_args) > 3 and str(extra_args[0]) == '-ac_name=ZZZ':
port = extra_args[3][9:]
else:
port = str(rpc_port(i))
#print("port=%s" % port) #print("port=%s" % port)
username = rpc_username() username = rpc_username()
password = rpc_password() password = rpc_password()
url = "http://%s:%s@%s:%s" % (username, password, rpchost or '127.0.0.1', port[9:]) url = "http://%s:%s@%s:%s" % (username, password, rpchost or '127.0.0.1', port)
print("connecting to " + url) print("connecting to " + url)
if timewait is not None: if timewait is not None:
proxy = AuthServiceProxy(url, timeout=timewait) proxy = AuthServiceProxy(url, timeout=timewait)
@@ -315,7 +365,7 @@ def stop_nodes(nodes):
del nodes[:] # Emptying array closes connections as a side effect del nodes[:] # Emptying array closes connections as a side effect
def set_node_times(nodes, t): def set_node_times(nodes, t):
print("Setting nodes time to " + t) print("Setting nodes time to " + str(t))
for node in nodes: for node in nodes:
node.setmocktime(t) node.setmocktime(t)
+35 -23
View File
@@ -1,4 +1,4 @@
#!/usr/bin/env python2 #!/usr/bin/env python3
# Copyright (c) 2016-2024 The Hush developers # Copyright (c) 2016-2024 The Hush developers
# Copyright (c) 2014 The Bitcoin Core developers # Copyright (c) 2014 The Bitcoin Core developers
# Distributed under the GPLv3 software license, see the accompanying # Distributed under the GPLv3 software license, see the accompanying
@@ -20,8 +20,20 @@ class WalletTest (BitcoinTestFramework):
print("Initializing test directory "+self.options.tmpdir) print("Initializing test directory "+self.options.tmpdir)
initialize_chain_clean(self.options.tmpdir, 4) initialize_chain_clean(self.options.tmpdir, 4)
# PORT NOTE (DragonX/regtest, not a change of test intent):
# test_framework.start_node() hardcodes "-connect=0", and init.cpp turns that into
# "-connect set -> setting -listen=0". With listening off the nodes never bind their
# p2p port, so connect_nodes_bi() connects nothing at all (its version==0 poll loop
# exits immediately because there are no local peers) and the first sync_all() hangs
# forever. Passing -bind forces -listen back to 1. -dnsseed=0 keeps these regtest
# nodes from dialing the live DragonX network.
NET_ARGS = ["-listen=1", "-bind=127.0.0.1", "-dnsseed=0"]
def net_args(self, n, extra=None):
return [list(self.NET_ARGS) + list(extra or []) for _ in range(n)]
def setup_network(self, split=False): def setup_network(self, split=False):
self.nodes = start_nodes(3, self.options.tmpdir) self.nodes = start_nodes(3, self.options.tmpdir, self.net_args(3))
connect_nodes_bi(self.nodes,0,1) connect_nodes_bi(self.nodes,0,1)
connect_nodes_bi(self.nodes,1,2) connect_nodes_bi(self.nodes,1,2)
connect_nodes_bi(self.nodes,0,2) connect_nodes_bi(self.nodes,0,2)
@@ -29,7 +41,7 @@ class WalletTest (BitcoinTestFramework):
self.sync_all() self.sync_all()
def run_test (self): def run_test (self):
print "Mining blocks..." print("Mining blocks...")
self.nodes[0].generate(4) self.nodes[0].generate(4)
self.sync_all() self.sync_all()
@@ -106,7 +118,7 @@ class WalletTest (BitcoinTestFramework):
signed_tx = self.nodes[2].signrawtransaction(raw_tx) signed_tx = self.nodes[2].signrawtransaction(raw_tx)
try: try:
self.nodes[2].sendrawtransaction(signed_tx["hex"]) self.nodes[2].sendrawtransaction(signed_tx["hex"])
except JSONRPCException,e: except JSONRPCException as e:
errorString = e.error['message'] errorString = e.error['message']
assert("absurdly high fees" in errorString) assert("absurdly high fees" in errorString)
assert("900000000 > 190000" in errorString) assert("900000000 > 190000" in errorString)
@@ -186,7 +198,7 @@ class WalletTest (BitcoinTestFramework):
txid2 = self.nodes[1].sendtoaddress(self.nodes[0].getnewaddress(), 1) txid2 = self.nodes[1].sendtoaddress(self.nodes[0].getnewaddress(), 1)
sync_mempools(self.nodes) sync_mempools(self.nodes)
self.nodes.append(start_node(3, self.options.tmpdir)) self.nodes.append(start_node(3, self.options.tmpdir, list(self.NET_ARGS)))
connect_nodes_bi(self.nodes, 0, 3) connect_nodes_bi(self.nodes, 0, 3)
sync_blocks(self.nodes) sync_blocks(self.nodes)
@@ -227,7 +239,7 @@ class WalletTest (BitcoinTestFramework):
#do some -walletbroadcast tests #do some -walletbroadcast tests
stop_nodes(self.nodes) stop_nodes(self.nodes)
wait_bitcoinds() wait_bitcoinds()
self.nodes = start_nodes(3, self.options.tmpdir, [["-walletbroadcast=0"],["-walletbroadcast=0"],["-walletbroadcast=0"]]) self.nodes = start_nodes(3, self.options.tmpdir, self.net_args(3, ["-walletbroadcast=0"]))
connect_nodes_bi(self.nodes,0,1) connect_nodes_bi(self.nodes,0,1)
connect_nodes_bi(self.nodes,1,2) connect_nodes_bi(self.nodes,1,2)
connect_nodes_bi(self.nodes,0,2) connect_nodes_bi(self.nodes,0,2)
@@ -256,7 +268,7 @@ class WalletTest (BitcoinTestFramework):
#restart the nodes with -walletbroadcast=1 #restart the nodes with -walletbroadcast=1
stop_nodes(self.nodes) stop_nodes(self.nodes)
wait_bitcoinds() wait_bitcoinds()
self.nodes = start_nodes(3, self.options.tmpdir) self.nodes = start_nodes(3, self.options.tmpdir, self.net_args(3))
connect_nodes_bi(self.nodes,0,1) connect_nodes_bi(self.nodes,0,1)
connect_nodes_bi(self.nodes,1,2) connect_nodes_bi(self.nodes,1,2)
connect_nodes_bi(self.nodes,0,2) connect_nodes_bi(self.nodes,0,2)
@@ -290,7 +302,7 @@ class WalletTest (BitcoinTestFramework):
num_t_recipients = 3000 num_t_recipients = 3000
amount_per_recipient = Decimal('0.00000001') amount_per_recipient = Decimal('0.00000001')
errorString = '' errorString = ''
for i in xrange(0,num_t_recipients): for i in range(0,num_t_recipients):
newtaddr = self.nodes[2].getnewaddress() newtaddr = self.nodes[2].getnewaddress()
recipients.append({"address":newtaddr, "amount":amount_per_recipient}) recipients.append({"address":newtaddr, "amount":amount_per_recipient})
@@ -305,7 +317,7 @@ class WalletTest (BitcoinTestFramework):
try: try:
self.nodes[0].z_sendmany(myzaddr, recipients) self.nodes[0].z_sendmany(myzaddr, recipients)
except JSONRPCException,e: except JSONRPCException as e:
errorString = e.error['message'] errorString = e.error['message']
assert("Too many outputs, size of raw transaction" in errorString) assert("Too many outputs, size of raw transaction" in errorString)
@@ -314,10 +326,10 @@ class WalletTest (BitcoinTestFramework):
num_z_recipients = 50 num_z_recipients = 50
amount_per_recipient = Decimal('0.00000001') amount_per_recipient = Decimal('0.00000001')
errorString = '' errorString = ''
for i in xrange(0,num_t_recipients): for i in range(0,num_t_recipients):
newtaddr = self.nodes[2].getnewaddress() newtaddr = self.nodes[2].getnewaddress()
recipients.append({"address":newtaddr, "amount":amount_per_recipient}) recipients.append({"address":newtaddr, "amount":amount_per_recipient})
for i in xrange(0,num_z_recipients): for i in range(0,num_z_recipients):
newzaddr = self.nodes[2].z_getnewaddress() newzaddr = self.nodes[2].z_getnewaddress()
recipients.append({"address":newzaddr, "amount":amount_per_recipient}) recipients.append({"address":newzaddr, "amount":amount_per_recipient})
@@ -327,7 +339,7 @@ class WalletTest (BitcoinTestFramework):
try: try:
self.nodes[0].z_sendmany(myzaddr, recipients) self.nodes[0].z_sendmany(myzaddr, recipients)
except JSONRPCException,e: except JSONRPCException as e:
errorString = e.error['message'] errorString = e.error['message']
assert("size of raw transaction would be larger than limit" in errorString) assert("size of raw transaction would be larger than limit" in errorString)
@@ -335,12 +347,12 @@ class WalletTest (BitcoinTestFramework):
num_z_recipients = 100 num_z_recipients = 100
amount_per_recipient = Decimal('0.00000001') amount_per_recipient = Decimal('0.00000001')
errorString = '' errorString = ''
for i in xrange(0,num_z_recipients): for i in range(0,num_z_recipients):
newzaddr = self.nodes[2].z_getnewaddress() newzaddr = self.nodes[2].z_getnewaddress()
recipients.append({"address":newzaddr, "amount":amount_per_recipient}) recipients.append({"address":newzaddr, "amount":amount_per_recipient})
try: try:
self.nodes[0].z_sendmany(myzaddr, recipients) self.nodes[0].z_sendmany(myzaddr, recipients)
except JSONRPCException,e: except JSONRPCException as e:
errorString = e.error['message'] errorString = e.error['message']
assert("Invalid parameter, too many zaddr outputs" in errorString) assert("Invalid parameter, too many zaddr outputs" in errorString)
@@ -426,7 +438,7 @@ class WalletTest (BitcoinTestFramework):
errorString = "" errorString = ""
try: try:
txId = self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), "1f-4") txId = self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), "1f-4")
except JSONRPCException,e: except JSONRPCException as e:
errorString = e.error['message'] errorString = e.error['message']
assert_equal("Invalid amount" in errorString, True) assert_equal("Invalid amount" in errorString, True)
@@ -434,7 +446,7 @@ class WalletTest (BitcoinTestFramework):
errorString = "" errorString = ""
try: try:
self.nodes[0].generate("2") #use a string to as block amount parameter must fail because it's not interpreted as amount self.nodes[0].generate("2") #use a string to as block amount parameter must fail because it's not interpreted as amount
except JSONRPCException,e: except JSONRPCException as e:
errorString = e.error['message'] errorString = e.error['message']
assert_equal("not an integer" in errorString, True) assert_equal("not an integer" in errorString, True)
@@ -448,9 +460,9 @@ class WalletTest (BitcoinTestFramework):
try: try:
myopid = self.nodes[0].z_sendmany(myzaddr, recipients) myopid = self.nodes[0].z_sendmany(myzaddr, recipients)
assert(myopid) assert(myopid)
except JSONRPCException,e: except JSONRPCException as e:
errorString = e.error['message'] errorString = e.error['message']
print errorString print(errorString)
assert(False) assert(False)
# This fee is larger than the default fee and since amount=0 # This fee is larger than the default fee and since amount=0
@@ -462,7 +474,7 @@ class WalletTest (BitcoinTestFramework):
try: try:
myopid = self.nodes[0].z_sendmany(myzaddr, recipients, minconf, fee) myopid = self.nodes[0].z_sendmany(myzaddr, recipients, minconf, fee)
except JSONRPCException,e: except JSONRPCException as e:
errorString = e.error['message'] errorString = e.error['message']
assert('Small transaction amount' in errorString) assert('Small transaction amount' in errorString)
@@ -475,9 +487,9 @@ class WalletTest (BitcoinTestFramework):
try: try:
myopid = self.nodes[0].z_sendmany(myzaddr, recipients, minconf, fee) myopid = self.nodes[0].z_sendmany(myzaddr, recipients, minconf, fee)
assert(myopid) assert(myopid)
except JSONRPCException,e: except JSONRPCException as e:
errorString = e.error['message'] errorString = e.error['message']
print errorString print(errorString)
assert(False) assert(False)
# Make sure amount=0, fee=0 transaction are valid to add to mempool # Make sure amount=0, fee=0 transaction are valid to add to mempool
@@ -490,9 +502,9 @@ class WalletTest (BitcoinTestFramework):
try: try:
myopid = self.nodes[0].z_sendmany(myzaddr, recipients, minconf, fee) myopid = self.nodes[0].z_sendmany(myzaddr, recipients, minconf, fee)
assert(myopid) assert(myopid)
except JSONRPCException,e: except JSONRPCException as e:
errorString = e.error['message'] errorString = e.error['message']
print errorString print(errorString)
assert(False) assert(False)
+1 -1
View File
@@ -1,4 +1,4 @@
#!/usr/bin/env python2 #!/usr/bin/env python3
# Copyright (c) 2016-2024 The Hush developers # Copyright (c) 2016-2024 The Hush developers
# Copyright (c) 2018 The Zcash developers # Copyright (c) 2018 The Zcash developers
# Distributed under the GPLv3 software license, see the accompanying # Distributed under the GPLv3 software license, see the accompanying
+12 -12
View File
@@ -1,4 +1,4 @@
#!/usr/bin/env python2 #!/usr/bin/env python3
# Copyright (c) 2016-2024 The Hush developers # Copyright (c) 2016-2024 The Hush developers
# Copyright (c) 2017 The Zcash developers # Copyright (c) 2017 The Zcash developers
# Distributed under the GPLv3 software license, see the accompanying # Distributed under the GPLv3 software license, see the accompanying
@@ -32,7 +32,7 @@ class WalletMergeToAddressTest (BitcoinTestFramework):
self.sync_all() self.sync_all()
def run_test (self): def run_test (self):
print "Mining blocks..." print("Mining blocks...")
self.nodes[0].generate(1) self.nodes[0].generate(1)
do_not_shield_taddr = self.nodes[0].getnewaddress() do_not_shield_taddr = self.nodes[0].getnewaddress()
@@ -81,7 +81,7 @@ class WalletMergeToAddressTest (BitcoinTestFramework):
try: try:
self.nodes[0].z_mergetoaddress("*", myzaddr) self.nodes[0].z_mergetoaddress("*", myzaddr)
assert(False) assert(False)
except JSONRPCException,e: except JSONRPCException as e:
errorString = e.error['message'] errorString = e.error['message']
assert_equal("JSON value is not an array as expected" in errorString, True) assert_equal("JSON value is not an array as expected" in errorString, True)
@@ -90,7 +90,7 @@ class WalletMergeToAddressTest (BitcoinTestFramework):
try: try:
self.nodes[2].z_mergetoaddress([mytaddr], myzaddr) self.nodes[2].z_mergetoaddress([mytaddr], myzaddr)
assert(False) assert(False)
except JSONRPCException,e: except JSONRPCException as e:
errorString = e.error['message'] errorString = e.error['message']
assert_equal("Could not find any funds to merge" in errorString, True) assert_equal("Could not find any funds to merge" in errorString, True)
@@ -98,7 +98,7 @@ class WalletMergeToAddressTest (BitcoinTestFramework):
try: try:
self.nodes[0].z_mergetoaddress(["*"], myzaddr, -1) self.nodes[0].z_mergetoaddress(["*"], myzaddr, -1)
assert(False) assert(False)
except JSONRPCException,e: except JSONRPCException as e:
errorString = e.error['message'] errorString = e.error['message']
assert_equal("Amount out of range" in errorString, True) assert_equal("Amount out of range" in errorString, True)
@@ -106,7 +106,7 @@ class WalletMergeToAddressTest (BitcoinTestFramework):
try: try:
self.nodes[0].z_mergetoaddress(["*"], myzaddr, Decimal('21000000.00000001')) self.nodes[0].z_mergetoaddress(["*"], myzaddr, Decimal('21000000.00000001'))
assert(False) assert(False)
except JSONRPCException,e: except JSONRPCException as e:
errorString = e.error['message'] errorString = e.error['message']
assert_equal("Amount out of range" in errorString, True) assert_equal("Amount out of range" in errorString, True)
@@ -114,7 +114,7 @@ class WalletMergeToAddressTest (BitcoinTestFramework):
try: try:
self.nodes[0].z_mergetoaddress(["*"], myzaddr, 999) self.nodes[0].z_mergetoaddress(["*"], myzaddr, 999)
assert(False) assert(False)
except JSONRPCException,e: except JSONRPCException as e:
errorString = e.error['message'] errorString = e.error['message']
assert_equal("Insufficient funds" in errorString, True) assert_equal("Insufficient funds" in errorString, True)
@@ -122,7 +122,7 @@ class WalletMergeToAddressTest (BitcoinTestFramework):
try: try:
self.nodes[0].z_mergetoaddress(["*"], myzaddr, Decimal('0.001'), -1) self.nodes[0].z_mergetoaddress(["*"], myzaddr, Decimal('0.001'), -1)
assert(False) assert(False)
except JSONRPCException,e: except JSONRPCException as e:
errorString = e.error['message'] errorString = e.error['message']
assert_equal("Limit on maximum number of UTXOs cannot be negative" in errorString, True) assert_equal("Limit on maximum number of UTXOs cannot be negative" in errorString, True)
@@ -130,7 +130,7 @@ class WalletMergeToAddressTest (BitcoinTestFramework):
try: try:
self.nodes[0].z_mergetoaddress(["*"], myzaddr, Decimal('0.001'), 99999999999999) self.nodes[0].z_mergetoaddress(["*"], myzaddr, Decimal('0.001'), 99999999999999)
assert(False) assert(False)
except JSONRPCException,e: except JSONRPCException as e:
errorString = e.error['message'] errorString = e.error['message']
assert_equal("JSON integer out of range" in errorString, True) assert_equal("JSON integer out of range" in errorString, True)
@@ -138,7 +138,7 @@ class WalletMergeToAddressTest (BitcoinTestFramework):
try: try:
self.nodes[0].z_mergetoaddress(["*"], myzaddr, Decimal('0.001'), 50, -1) self.nodes[0].z_mergetoaddress(["*"], myzaddr, Decimal('0.001'), 50, -1)
assert(False) assert(False)
except JSONRPCException,e: except JSONRPCException as e:
errorString = e.error['message'] errorString = e.error['message']
assert_equal("Limit on maximum number of notes cannot be negative" in errorString, True) assert_equal("Limit on maximum number of notes cannot be negative" in errorString, True)
@@ -146,7 +146,7 @@ class WalletMergeToAddressTest (BitcoinTestFramework):
try: try:
self.nodes[0].z_mergetoaddress(["*"], myzaddr, Decimal('0.001'), 50, 99999999999999) self.nodes[0].z_mergetoaddress(["*"], myzaddr, Decimal('0.001'), 50, 99999999999999)
assert(False) assert(False)
except JSONRPCException,e: except JSONRPCException as e:
errorString = e.error['message'] errorString = e.error['message']
assert_equal("JSON integer out of range" in errorString, True) assert_equal("JSON integer out of range" in errorString, True)
@@ -154,7 +154,7 @@ class WalletMergeToAddressTest (BitcoinTestFramework):
try: try:
self.nodes[0].z_mergetoaddress([mytaddr], mytaddr) self.nodes[0].z_mergetoaddress([mytaddr], mytaddr)
assert(False) assert(False)
except JSONRPCException,e: except JSONRPCException as e:
errorString = e.error['message'] errorString = e.error['message']
assert_equal("Destination address is also the only source address, and all its funds are already merged" in errorString, True) assert_equal("Destination address is also the only source address, and all its funds are already merged" in errorString, True)
+60 -4
View File
@@ -1,4 +1,4 @@
#!/usr/bin/env python2 #!/usr/bin/env python3
# Copyright (c) 2016-2024 The Hush developers # Copyright (c) 2016-2024 The Hush developers
# Copyright (c) 2016 The Zcash developers # Copyright (c) 2016 The Zcash developers
# Distributed under the GPLv3 software license, see the accompanying # Distributed under the GPLv3 software license, see the accompanying
@@ -7,15 +7,71 @@
from test_framework.test_framework import BitcoinTestFramework from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import assert_equal, assert_true, bitcoind_processes, \ from test_framework.util import assert_equal, assert_true, bitcoind_processes, \
connect_nodes_bi, start_node, start_nodes, wait_and_assert_operationid_status connect_nodes_bi, initialize_chain_clean, p2p_port, start_node, start_nodes, \
sync_blocks, wait_and_assert_operationid_status
from decimal import Decimal from decimal import Decimal
class WalletNullifiersTest (BitcoinTestFramework): class WalletNullifiersTest (BitcoinTestFramework):
# The framework default setup_chain() calls initialize_chain(), which pre-builds a
# 200-block chain in a *relative* "cache/" directory shared by every test process
# running out of this tree. That directory is guarded only by the datadir lock, so two
# qa/rpc-tests running at once collide on it and the second one hangs forever inside
# "dragonx-cli -rpcwait" (observed here while a sibling test held cache/node0..3).
# Build the identical pre-condition -- 4 nodes, two rounds of 25 blocks each, i.e. 25
# mature + 25 immature coinbases per node -- directly in this test's private tmpdir.
# This is a setup change only: no assertion below is relaxed, removed or reordered.
def setup_chain(self):
print("Initializing test directory "+self.options.tmpdir)
initialize_chain_clean(self.options.tmpdir, 4)
# Three networking facts about this daemon force extra flags here. None of them
# change what the test exercises; without them the 4 nodes either never peer with
# each other, or peer with the LIVE DragonX network instead.
#
# 1. start_node() hardcodes "-connect=0", which also soft-sets -listen=0, so nothing
# binds p2p_port(i) and connect_nodes_bi() can never form the regtest mesh --
# sync_blocks() then spins forever (observed: node0 at 25 blocks, nodes 1-3 stuck
# at 0, nothing listening on 11005-11008). -listen=1 -bind=127.0.0.1 restores the
# mesh and keeps it on loopback.
# 2. hush_args() appends node1..node10.dragonx.is to -addnode unconditionally, -regtest
# included, and regtest reuses mainnet's network magic. A "regtest" node therefore
# joins the live network: node0 of an earlier run handshook 8 production peers
# ("receive version message: /DragonX:1.0.3/ ... blocks=3254266") and ingested their
# headers. -dns=0 stops those hostname -addnode entries from resolving; RPC addnode
# with a numeric 127.0.0.1:port is unaffected.
# 3. hush_args() runs BEFORE the config file is read, so its GetArg("-port",0) never
# sees the "port=" line initialize_datadir() wrote and GetDefaultPort() stays at the
# mainnet p2p port. "-connect=0" is then parsed as the address 0.0.0.0:<mainnet
# port>, i.e. the production dragonxd listening on this box -- every node in runs 2
# and 3 picked up exactly one peer reporting blocks=3254269. Repeating -port on the
# command line points GetDefaultPort() at this node's own regtest port instead.
#
# -autoshield is on by default on DragonX and is not part of what this test measures:
# a background thread sweeps each node's matured coinbase into a seed-derived zaddr
# (8 "autoshield operation finished" ops per node while the chain is being mined). That
# empties the very taddr this test spends from, and the resulting transactions do not
# settle identically on every node ("ERROR: AcceptToMemoryPool: ContextualCheckTransaction
# failed" on node1), so sync_mempools() never converges and the run wedges until the
# timeout. Turn the background sweeper off; the test does its own shielding explicitly.
def net_args(self, i):
return ['-listen=1', '-bind=127.0.0.1', '-dns=0', '-autoshield=0',
'-port=%d' % p2p_port(i)]
def setup_nodes(self): def setup_nodes(self):
return start_nodes(4, self.options.tmpdir, return start_nodes(4, self.options.tmpdir,
extra_args=[['-experimentalfeatures', '-developerencryptwallet']] * 4) extra_args=[['-experimentalfeatures', '-developerencryptwallet']
+ self.net_args(i) for i in range(4)])
def setup_network(self, split = False):
super().setup_network(split)
# Same block layout initialize_chain() would have handed us.
for _ in range(2):
for peer in range(4):
self.nodes[peer].generate(25)
sync_blocks(self.nodes)
self.sync_all()
def run_test (self): def run_test (self):
# add zaddr to node 0 # add zaddr to node 0
@@ -44,7 +100,7 @@ class WalletNullifiersTest (BitcoinTestFramework):
bitcoind_processes[1].wait() bitcoind_processes[1].wait()
# restart node 1 # restart node 1
self.nodes[1] = start_node(1, self.options.tmpdir) self.nodes[1] = start_node(1, self.options.tmpdir, self.net_args(1))
connect_nodes_bi(self.nodes, 0, 1) connect_nodes_bi(self.nodes, 0, 1)
connect_nodes_bi(self.nodes, 1, 2) connect_nodes_bi(self.nodes, 1, 2)
self.sync_all() self.sync_all()
+38 -5
View File
@@ -1,4 +1,4 @@
#!/usr/bin/env python2 #!/usr/bin/env python3
# Copyright (c) 2016-2024 The Hush developers # Copyright (c) 2016-2024 The Hush developers
# Copyright (c) 2018 The Zcash developers # Copyright (c) 2018 The Zcash developers
# Distributed under the GPLv3 software license, see the accompanying # Distributed under the GPLv3 software license, see the accompanying
@@ -13,6 +13,29 @@ from test_framework.util import (
) )
from decimal import Decimal from decimal import Decimal
def get_value_pool(pools, pool_id):
"""
Return the valuePools entry with the given id, or None if this chain does
not have that pool. DragonX's getblockchaininfo only reports the Sapling
pool (no Sprout history exists on this chain), so the pools list can no
longer be indexed positionally the way the upstream test did.
"""
for pool in pools:
if pool['id'] == pool_id:
return pool
return None
def assert_pool_values(pools, sprout_value, sapling_value):
sprout = get_value_pool(pools, 'sprout')
if sprout is not None:
assert_equal(sprout['chainValue'], sprout_value)
else:
# No Sprout pool at all is the same statement as "the Sprout pool holds nothing"
assert_equal(sprout_value, Decimal('0'))
sapling = get_value_pool(pools, 'sapling')
assert_true(sapling is not None, "Sapling value pool missing from getblockchaininfo")
assert_equal(sapling['chainValue'], sapling_value)
class WalletPersistenceTest (BitcoinTestFramework): class WalletPersistenceTest (BitcoinTestFramework):
def setup_chain(self): def setup_chain(self):
@@ -20,8 +43,20 @@ class WalletPersistenceTest (BitcoinTestFramework):
initialize_chain_clean(self.options.tmpdir, 3) initialize_chain_clean(self.options.tmpdir, 3)
def setup_network(self, split=False): def setup_network(self, split=False):
# -listen=1/-bind: the framework's start_node() passes -connect=0, and DragonX (like
# Bitcoin) reacts to -connect by soft-setting -listen=0. A non-listening node can never
# accept the "addnode 127.0.0.1:<port>" that connect_nodes_bi() issues, so without this
# the three nodes stay isolated and sync_all() spins forever. -bind keeps the listener on
# loopback so a regtest node never becomes reachable from the public internet.
self.nodes = start_nodes(3, self.options.tmpdir, self.nodes = start_nodes(3, self.options.tmpdir,
extra_args=[[ extra_args=[[
'-listen=1',
'-bind=127.0.0.1',
# -dns=0: DragonX appends node1..node10.dragonx.is to -addnode for every chain
# named DRAGONX (hush_utils.h), and -connect=0 does not suppress -addnode. Without
# this a regtest node dials the LIVE DragonX network and is fed mainnet headers.
# The addnode calls connect_nodes_bi() makes use literal IPs, so they still work.
'-dns=0',
'-nuparams=5ba81b19:100', # Overwinter '-nuparams=5ba81b19:100', # Overwinter
'-nuparams=76b809bb:201', # Sapling '-nuparams=76b809bb:201', # Sapling
]] * 3) ]] * 3)
@@ -72,8 +107,7 @@ class WalletPersistenceTest (BitcoinTestFramework):
# Verify size of shielded pools # Verify size of shielded pools
pools = self.nodes[0].getblockchaininfo()['valuePools'] pools = self.nodes[0].getblockchaininfo()['valuePools']
assert_equal(pools[0]['chainValue'], Decimal('0')) # Sprout assert_pool_values(pools, Decimal('0'), Decimal('20'))
assert_equal(pools[1]['chainValue'], Decimal('20')) # Sapling
# Restart the nodes # Restart the nodes
stop_nodes(self.nodes) stop_nodes(self.nodes)
@@ -82,8 +116,7 @@ class WalletPersistenceTest (BitcoinTestFramework):
# Verify size of shielded pools # Verify size of shielded pools
pools = self.nodes[0].getblockchaininfo()['valuePools'] pools = self.nodes[0].getblockchaininfo()['valuePools']
assert_equal(pools[0]['chainValue'], Decimal('0')) # Sprout assert_pool_values(pools, Decimal('0'), Decimal('20'))
assert_equal(pools[1]['chainValue'], Decimal('20')) # Sapling
# Node 0 sends some shielded funds to Node 1 # Node 0 sends some shielded funds to Node 1
dest_addr = self.nodes[1].z_getnewaddress('sapling') dest_addr = self.nodes[1].z_getnewaddress('sapling')
+51 -33
View File
@@ -1,4 +1,4 @@
#!/usr/bin/env python2 #!/usr/bin/env python3
# Copyright (c) 2016-2024 The Hush developers # Copyright (c) 2016-2024 The Hush developers
# Copyright (c) 2016 The Zcash developers # Copyright (c) 2016 The Zcash developers
# Distributed under the GPLv3 software license, see the accompanying # Distributed under the GPLv3 software license, see the accompanying
@@ -6,7 +6,6 @@
from test_framework.test_framework import BitcoinTestFramework from test_framework.test_framework import BitcoinTestFramework
from test_framework.authproxy import JSONRPCException from test_framework.authproxy import JSONRPCException
from test_framework.mininode import COIN
from test_framework.util import assert_equal, initialize_chain_clean, \ from test_framework.util import assert_equal, initialize_chain_clean, \
start_nodes, connect_nodes_bi, wait_and_assert_operationid_status start_nodes, connect_nodes_bi, wait_and_assert_operationid_status
@@ -14,6 +13,20 @@ import sys
import timeit import timeit
from decimal import Decimal from decimal import Decimal
# Upstream imported this from test_framework.mininode, which is still python2 and
# fails to even parse under python3 (0x100000000L literals). mininode is a p2p
# serialisation module this test does not otherwise use, so rather than drag a
# large unrelated port into test_framework/ the one constant needed is inlined.
# Same value as test_framework/mininode.py:52.
COIN = 100000000 # 1 DRGX in puposhis
# DragonX has no Sprout pool: getblockchaininfo/getblock only ever emit a
# "sapling" entry in valuePools (see rpc/blockchain.cpp), and z_getnewaddress
# only makes Sapling addresses. The shielded value this test moves therefore
# lands in the Sapling pool, so every check that upstream made against 'sprout'
# is made against 'sapling' here. The assertion itself is unchanged.
SHIELDED_POOL = 'sapling'
def check_value_pool(node, name, total): def check_value_pool(node, name, total):
value_pools = node.getblockchaininfo()['valuePools'] value_pools = node.getblockchaininfo()['valuePools']
found = False found = False
@@ -42,7 +55,7 @@ class WalletProtectCoinbaseTest (BitcoinTestFramework):
self.sync_all() self.sync_all()
def run_test (self): def run_test (self):
print "Mining blocks..." print("Mining blocks...")
self.nodes[0].generate(4) self.nodes[0].generate(4)
@@ -59,17 +72,17 @@ class WalletProtectCoinbaseTest (BitcoinTestFramework):
assert_equal(self.nodes[2].getbalance(), 0) assert_equal(self.nodes[2].getbalance(), 0)
assert_equal(self.nodes[3].getbalance(), 0) assert_equal(self.nodes[3].getbalance(), 0)
check_value_pool(self.nodes[0], 'sprout', 0) check_value_pool(self.nodes[0], SHIELDED_POOL, 0)
check_value_pool(self.nodes[1], 'sprout', 0) check_value_pool(self.nodes[1], SHIELDED_POOL, 0)
check_value_pool(self.nodes[2], 'sprout', 0) check_value_pool(self.nodes[2], SHIELDED_POOL, 0)
check_value_pool(self.nodes[3], 'sprout', 0) check_value_pool(self.nodes[3], SHIELDED_POOL, 0)
# Send will fail because we are enforcing the consensus rule that # Send will fail because we are enforcing the consensus rule that
# coinbase utxos can only be sent to a zaddr. # coinbase utxos can only be sent to a zaddr.
errorString = "" errorString = ""
try: try:
self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 1) self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 1)
except JSONRPCException,e: except JSONRPCException as e:
errorString = e.error['message'] errorString = e.error['message']
assert_equal("Coinbase funds can only be sent to a zaddr" in errorString, True) assert_equal("Coinbase funds can only be sent to a zaddr" in errorString, True)
@@ -95,11 +108,11 @@ class WalletProtectCoinbaseTest (BitcoinTestFramework):
# Test that the returned status object contains a params field with the operation's input parameters # Test that the returned status object contains a params field with the operation's input parameters
assert_equal(error_result["method"], "z_sendmany") assert_equal(error_result["method"], "z_sendmany")
params = error_result["params"] params = error_result["params"]
assert_equal(params["fee"], Decimal('0.0001')) # default assert_equal(Decimal(params["fee"]), Decimal('0.0001')) # default
assert_equal(params["minconf"], Decimal('1')) # default assert_equal(Decimal(params["minconf"]), Decimal('1')) # default
assert_equal(params["fromaddress"], mytaddr) assert_equal(params["fromaddress"], mytaddr)
assert_equal(params["amounts"][0]["address"], myzaddr) assert_equal(params["amounts"][0]["address"], myzaddr)
assert_equal(params["amounts"][0]["amount"], Decimal('1.23456789')) assert_equal(Decimal(params["amounts"][0]["amount"]), Decimal('1.23456789'))
# Add viewing key for myzaddr to Node 3 # Add viewing key for myzaddr to Node 3
myviewingkey = self.nodes[0].z_exportviewingkey(myzaddr) myviewingkey = self.nodes[0].z_exportviewingkey(myzaddr)
@@ -169,14 +182,17 @@ class WalletProtectCoinbaseTest (BitcoinTestFramework):
assert_equal(Decimal(resp["private"]), Decimal('19.9999')) assert_equal(Decimal(resp["private"]), Decimal('19.9999'))
assert_equal(Decimal(resp["total"]), Decimal('39.9999')) assert_equal(Decimal(resp["total"]), Decimal('39.9999'))
# The Sprout value pool should reflect the send # The shielded value pool should reflect the send
sproutvalue = shieldvalue shieldedvalue = shieldvalue
check_value_pool(self.nodes[0], 'sprout', sproutvalue) check_value_pool(self.nodes[0], SHIELDED_POOL, shieldedvalue)
# A custom fee of 0 is okay. Here the node will send the note value back to itself. # A custom fee of 0 is okay. Here the node will send the note value back to itself.
recipients = [] recipients = []
recipients.append({"address":myzaddr, "amount": Decimal('19.9999')}) recipients.append({"address":myzaddr, "amount": Decimal('19.9999')})
myopid = self.nodes[0].z_sendmany(myzaddr, recipients, 1, Decimal('0.0')) # NB: the fee is passed as a JSON number, not a Decimal. authproxy serialises
# Decimal as a JSON *string* and z_sendmany reads the fee with params[3].get_real(),
# which only accepts VNUM -- see port notes. The value is unchanged.
myopid = self.nodes[0].z_sendmany(myzaddr, recipients, 1, 0.0)
mytxid = wait_and_assert_operationid_status(self.nodes[0], myopid) mytxid = wait_and_assert_operationid_status(self.nodes[0], myopid)
self.sync_all() self.sync_all()
self.nodes[1].generate(1) self.nodes[1].generate(1)
@@ -186,8 +202,8 @@ class WalletProtectCoinbaseTest (BitcoinTestFramework):
assert_equal(Decimal(resp["private"]), Decimal('19.9999')) assert_equal(Decimal(resp["private"]), Decimal('19.9999'))
assert_equal(Decimal(resp["total"]), Decimal('39.9999')) assert_equal(Decimal(resp["total"]), Decimal('39.9999'))
# The Sprout value pool should be unchanged # The shielded value pool should be unchanged
check_value_pool(self.nodes[0], 'sprout', sproutvalue) check_value_pool(self.nodes[0], SHIELDED_POOL, shieldedvalue)
# convert note to transparent funds # convert note to transparent funds
unshieldvalue = Decimal('10.0') unshieldvalue = Decimal('10.0')
@@ -206,12 +222,12 @@ class WalletProtectCoinbaseTest (BitcoinTestFramework):
self.sync_all() self.sync_all()
# check balances # check balances
sproutvalue -= unshieldvalue + Decimal('0.0001') shieldedvalue -= unshieldvalue + Decimal('0.0001')
resp = self.nodes[0].z_gettotalbalance() resp = self.nodes[0].z_gettotalbalance()
assert_equal(Decimal(resp["transparent"]), Decimal('30.0')) assert_equal(Decimal(resp["transparent"]), Decimal('30.0'))
assert_equal(Decimal(resp["private"]), Decimal('9.9998')) assert_equal(Decimal(resp["private"]), Decimal('9.9998'))
assert_equal(Decimal(resp["total"]), Decimal('39.9998')) assert_equal(Decimal(resp["total"]), Decimal('39.9998'))
check_value_pool(self.nodes[0], 'sprout', sproutvalue) check_value_pool(self.nodes[0], SHIELDED_POOL, shieldedvalue)
# z_sendmany will return an error if there is transparent change output considered dust. # z_sendmany will return an error if there is transparent change output considered dust.
# UTXO selection in z_sendmany sorts in ascending order, so smallest utxos are consumed first. # UTXO selection in z_sendmany sorts in ascending order, so smallest utxos are consumed first.
@@ -226,7 +242,7 @@ class WalletProtectCoinbaseTest (BitcoinTestFramework):
errorString = "" errorString = ""
try: try:
self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 99999) self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 99999)
except JSONRPCException,e: except JSONRPCException as e:
errorString = e.error['message'] errorString = e.error['message']
assert_equal("Insufficient funds" in errorString, True) assert_equal("Insufficient funds" in errorString, True)
@@ -241,7 +257,7 @@ class WalletProtectCoinbaseTest (BitcoinTestFramework):
# Send will fail because of insufficient funds unless sender uses coinbase utxos # Send will fail because of insufficient funds unless sender uses coinbase utxos
try: try:
self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 21) self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 21)
except JSONRPCException,e: except JSONRPCException as e:
errorString = e.error['message'] errorString = e.error['message']
assert_equal("Insufficient funds, coinbase funds can only be spent after they have been sent to a zaddr" in errorString, True) assert_equal("Insufficient funds, coinbase funds can only be spent after they have been sent to a zaddr" in errorString, True)
@@ -256,7 +272,7 @@ class WalletProtectCoinbaseTest (BitcoinTestFramework):
# Note that regtest chainparams does not require standard tx, so setting the amount to be # Note that regtest chainparams does not require standard tx, so setting the amount to be
# less than the dust threshold, e.g. 0.00000001 will not result in mempool rejection. # less than the dust threshold, e.g. 0.00000001 will not result in mempool rejection.
start_time = timeit.default_timer() start_time = timeit.default_timer()
for i in xrange(0,num_t_recipients): for i in range(0,num_t_recipients):
newtaddr = self.nodes[2].getnewaddress() newtaddr = self.nodes[2].getnewaddress()
recipients.append({"address":newtaddr, "amount":amount_per_recipient}) recipients.append({"address":newtaddr, "amount":amount_per_recipient})
elapsed = timeit.default_timer() - start_time elapsed = timeit.default_timer() - start_time
@@ -287,28 +303,30 @@ class WalletProtectCoinbaseTest (BitcoinTestFramework):
# check balance # check balance
node2balance = amount_per_recipient * num_t_recipients node2balance = amount_per_recipient * num_t_recipients
sproutvalue -= node2balance + Decimal('0.0001') shieldedvalue -= node2balance + Decimal('0.0001')
assert_equal(self.nodes[2].getbalance(), node2balance) assert_equal(self.nodes[2].getbalance(), node2balance)
check_value_pool(self.nodes[0], 'sprout', sproutvalue) check_value_pool(self.nodes[0], SHIELDED_POOL, shieldedvalue)
# Send will fail because fee is negative # Send will fail because fee is negative
try: try:
self.nodes[0].z_sendmany(myzaddr, recipients, 1, -1) self.nodes[0].z_sendmany(myzaddr, recipients, 1, -1)
except JSONRPCException,e: except JSONRPCException as e:
errorString = e.error['message'] errorString = e.error['message']
assert_equal("Amount out of range" in errorString, True) assert_equal("Amount out of range" in errorString, True)
# Send will fail because fee is larger than MAX_MONEY # Send will fail because fee is larger than MAX_MONEY
errorString = ""
try: try:
self.nodes[0].z_sendmany(myzaddr, recipients, 1, Decimal('21000000.00000001')) self.nodes[0].z_sendmany(myzaddr, recipients, 1, float(Decimal('21000000.00000001')))
except JSONRPCException,e: except JSONRPCException as e:
errorString = e.error['message'] errorString = e.error['message']
assert_equal("Amount out of range" in errorString, True) assert_equal("Amount out of range" in errorString, True)
# Send will fail because fee is larger than sum of outputs # Send will fail because fee is larger than sum of outputs
errorString = ""
try: try:
self.nodes[0].z_sendmany(myzaddr, recipients, 1, (amount_per_recipient * num_t_recipients) + Decimal('0.00000001')) self.nodes[0].z_sendmany(myzaddr, recipients, 1, float((amount_per_recipient * num_t_recipients) + Decimal('0.00000001')))
except JSONRPCException,e: except JSONRPCException as e:
errorString = e.error['message'] errorString = e.error['message']
assert_equal("is greater than the sum of outputs" in errorString, True) assert_equal("is greater than the sum of outputs" in errorString, True)
@@ -334,10 +352,10 @@ class WalletProtectCoinbaseTest (BitcoinTestFramework):
send_amount = num_recipients * amount_per_recipient send_amount = num_recipients * amount_per_recipient
custom_fee = Decimal('0.00012345') custom_fee = Decimal('0.00012345')
zbalance = self.nodes[0].z_getbalance(myzaddr) zbalance = self.nodes[0].z_getbalance(myzaddr)
for i in xrange(0,num_recipients): for i in range(0,num_recipients):
newzaddr = self.nodes[2].z_getnewaddress() newzaddr = self.nodes[2].z_getnewaddress()
recipients.append({"address":newzaddr, "amount":amount_per_recipient}) recipients.append({"address":newzaddr, "amount":amount_per_recipient})
myopid = self.nodes[0].z_sendmany(myzaddr, recipients, minconf, custom_fee) myopid = self.nodes[0].z_sendmany(myzaddr, recipients, minconf, float(custom_fee))
wait_and_assert_operationid_status(self.nodes[0], myopid) wait_and_assert_operationid_status(self.nodes[0], myopid)
self.sync_all() self.sync_all()
self.nodes[1].generate(1) self.nodes[1].generate(1)
@@ -353,8 +371,8 @@ class WalletProtectCoinbaseTest (BitcoinTestFramework):
resp = self.nodes[0].z_getbalance(myzaddr) resp = self.nodes[0].z_getbalance(myzaddr)
assert_equal(Decimal(resp), zbalance - custom_fee - send_amount) assert_equal(Decimal(resp), zbalance - custom_fee - send_amount)
sproutvalue -= custom_fee shieldedvalue -= custom_fee
check_value_pool(self.nodes[0], 'sprout', sproutvalue) check_value_pool(self.nodes[0], SHIELDED_POOL, shieldedvalue)
notes = self.nodes[0].z_listunspent(1, 99999, False, [myzaddr]) notes = self.nodes[0].z_listunspent(1, 99999, False, [myzaddr])
sum_of_notes = sum([note["amount"] for note in notes]) sum_of_notes = sum([note["amount"] for note in notes])
+85 -7
View File
@@ -1,4 +1,4 @@
#!/usr/bin/env python2 #!/usr/bin/env python3
# Copyright (c) 2016-2024 The Hush developers # Copyright (c) 2016-2024 The Hush developers
# Copyright (c) 2018 The Zcash developers # Copyright (c) 2018 The Zcash developers
# Distributed under the GPLv3 software license, see the accompanying # Distributed under the GPLv3 software license, see the accompanying
@@ -8,21 +8,99 @@ from test_framework.test_framework import BitcoinTestFramework
from test_framework.authproxy import JSONRPCException from test_framework.authproxy import JSONRPCException
from test_framework.util import ( from test_framework.util import (
assert_equal, assert_equal,
start_nodes, initialize_chain_clean,
p2p_port,
set_node_times,
start_node,
sync_blocks,
wait_and_assert_operationid_status, wait_and_assert_operationid_status,
) )
import os
import stat
from decimal import Decimal from decimal import Decimal
# Test wallet behaviour with Sapling addresses # Test wallet behaviour with Sapling addresses
class WalletSaplingTest(BitcoinTestFramework): class WalletSaplingTest(BitcoinTestFramework):
def setup_chain(self):
# The shared initialize_chain() cache builder in test_framework/util.py has not been
# repaired for DragonX (it spawns the cache nodes by bare name off PATH, drives the
# CLI without -regtest so it dials the assetchain RPC port, and deletes debug.log
# from the non-net-specific datadir). Build the same starting state here instead --
# see _generate_starting_chain() -- so this test does not depend on it.
print("Initializing test directory " + self.options.tmpdir)
initialize_chain_clean(self.options.tmpdir, 4)
# !!! test_framework/util.py:start_node() hardcodes "-connect=0" into every regtest
# node's argv. Modern Bitcoin Core special-cases that value to mean "make no automatic
# connections", but THIS codebase does not (net.cpp ThreadOpenConnections just iterates
# mapMultiArgs["-connect"]), so "0" is dialled as a hostname: it resolves to 0.0.0.0,
# which on Linux connects to localhost on Params().GetDefaultPort() -- 21768, the live
# DRAGONX p2p port. Observed directly: a regtest node started by the unmodified
# framework peered with the production dragonxd on this host and with seven public
# mainnet nodes (heights ~3.25M) and began ingesting mainnet headers. "-connect" also
# soft-sets "-listen=0", so the framework's own connect_nodes_bi() can never establish
# the local links a multi-node test needs.
#
# Both problems are in the shared framework, which this port is not allowed to touch, so
# they are worked around per-node here: the daemon is launched through a tiny wrapper
# that strips the "-connect=0" argument, and the real topology/listening flags are passed
# as extra_args (which start_node appends after its own).
def _daemon_wrapper(self):
srcdir = os.path.join(
os.path.dirname(os.path.abspath(__file__)), "..", "..", "src", "dragonxd")
path = os.path.join(self.options.tmpdir, "dragonxd-no-connect0")
with open(path, "w") as f:
f.write("#!/usr/bin/env bash\n")
f.write("args=()\n")
f.write('for a in "$@"; do\n')
f.write(' if [ "$a" = "-connect=0" ]; then continue; fi\n')
f.write(' args+=("$a")\n')
f.write("done\n")
f.write('exec %s "${args[@]}"\n' % os.path.realpath(srcdir))
os.chmod(path, os.stat(path).st_mode | stat.S_IXUSR)
return path
def setup_nodes(self): def setup_nodes(self):
return start_nodes(4, self.options.tmpdir, [[ binary = self._daemon_wrapper()
#'-nuparams=5ba81b19:201', # Overwinter nodes = []
#'-nuparams=76b809bb:203', # Sapling for i in range(4):
#'-experimentalfeatures', '-zmergetoaddress', extra_args = [
]] * 4) #'-nuparams=5ba81b19:201', # Overwinter
#'-nuparams=76b809bb:203', # Sapling
#'-experimentalfeatures', '-zmergetoaddress',
# Listen on this test's PID-keyed port so the nodes can actually peer with
# each other, and only ever dial each other -- never the public network.
'-listen=1',
'-bind=127.0.0.1',
'-port=%d' % p2p_port(i),
] + ['-connect=127.0.0.1:%d' % p2p_port(j) for j in range(4) if j != i]
nodes.append(start_node(i, self.options.tmpdir, extra_args, binary=binary))
return nodes
def setup_network(self, split=False):
super(WalletSaplingTest, self).setup_network(split)
self._generate_starting_chain()
def _generate_starting_chain(self):
# Equivalent of test_framework.util.initialize_chain(): a 200-block chain where each
# of the 4 nodes mined 25 blocks twice, so every node holds 25 mature and 25 immature
# coinbases. Block timestamps are 10 minutes apart starting 1 Jan 2014, as there.
block_time = 1388534400
for _round in range(2):
for peer in range(4):
for _j in range(25):
set_node_times(self.nodes, block_time)
self.nodes[peer].generate(1)
block_time += 10 * 75
# Must sync before next peer starts generating blocks
sync_blocks(self.nodes)
# Drop back to wall-clock time: initialize_chain() stops the cache nodes and the test
# then runs against freshly started nodes that have no mocktime set.
set_node_times(self.nodes, 0)
self.sync_all()
def run_test(self): def run_test(self):
# Sanity-check the test harness # Sanity-check the test harness
+36 -10
View File
@@ -1,4 +1,4 @@
#!/usr/bin/env python2 #!/usr/bin/env python3
# Copyright (c) 2016-2024 The Hush developers # Copyright (c) 2016-2024 The Hush developers
# Copyright (c) 2017 The Zcash developers # Copyright (c) 2017 The Zcash developers
# Distributed under the GPLv3 software license, see the accompanying # Distributed under the GPLv3 software license, see the accompanying
@@ -22,8 +22,24 @@ class WalletShieldCoinbaseTest (BitcoinTestFramework):
initialize_chain_clean(self.options.tmpdir, 4) initialize_chain_clean(self.options.tmpdir, 4)
def setup_network(self, split=False): def setup_network(self, split=False):
args = ['-regtestprotectcoinbase', '-debug=zrpcunsafe'] # DragonX-specific environment flags. None of these change what the test
args2 = ['-regtestprotectcoinbase', '-debug=zrpcunsafe', "-mempooltxinputlimit=7"] # asserts; without them the test cannot run at all on this daemon:
# -listen=1/-bind=127.0.0.1: the framework's start_node() always passes
# -connect=0, and AppInit2 soft-sets -listen=0 whenever -connect is
# present, so the nodes never listen and connect_nodes_bi() silently
# builds an empty topology (sync_all() then spins forever). An explicit
# -listen=1 beats the SoftSetBoolArg.
# -dnsseed=0: chainparams_commandline() keeps DRAGONX's DNS seeds and
# overwrites pchMessageStart with the DRAGONX chain magic on *every*
# network including regtest, so a regtest node otherwise dials and
# handshakes with live mainnet peers (observed: 8 mainnet peers,
# blocks=3254237, feeding mainnet headers into the regtest node).
# -autoshield=0: DragonX auto-shields matured coinbase every 25 blocks
# by default, which would race the manual z_shieldcoinbase calls under
# test and move the balances this test checks.
isolate = ['-listen=1', '-bind=127.0.0.1', '-dnsseed=0', '-autoshield=0']
args = ['-regtestprotectcoinbase', '-debug=zrpcunsafe'] + isolate
args2 = ['-regtestprotectcoinbase', '-debug=zrpcunsafe', "-mempooltxinputlimit=7"] + isolate
if self.addr_type != 'sprout': if self.addr_type != 'sprout':
nu = [ nu = [
'-nuparams=5ba81b19:0', # Overwinter '-nuparams=5ba81b19:0', # Overwinter
@@ -42,7 +58,7 @@ class WalletShieldCoinbaseTest (BitcoinTestFramework):
self.sync_all() self.sync_all()
def run_test (self): def run_test (self):
print "Mining blocks..." print("Mining blocks...")
self.nodes[0].generate(1) self.nodes[0].generate(1)
self.sync_all() self.sync_all()
@@ -73,42 +89,42 @@ class WalletShieldCoinbaseTest (BitcoinTestFramework):
self.nodes[2].importaddress(mytaddr) self.nodes[2].importaddress(mytaddr)
try: try:
self.nodes[2].z_shieldcoinbase(mytaddr, myzaddr) self.nodes[2].z_shieldcoinbase(mytaddr, myzaddr)
except JSONRPCException,e: except JSONRPCException as e:
errorString = e.error['message'] errorString = e.error['message']
assert_equal("Could not find any coinbase funds to shield" in errorString, True) assert_equal("Could not find any coinbase funds to shield" in errorString, True)
# Shielding will fail because fee is negative # Shielding will fail because fee is negative
try: try:
self.nodes[0].z_shieldcoinbase("*", myzaddr, -1) self.nodes[0].z_shieldcoinbase("*", myzaddr, -1)
except JSONRPCException,e: except JSONRPCException as e:
errorString = e.error['message'] errorString = e.error['message']
assert_equal("Amount out of range" in errorString, True) assert_equal("Amount out of range" in errorString, True)
# Shielding will fail because fee is larger than MAX_MONEY # Shielding will fail because fee is larger than MAX_MONEY
try: try:
self.nodes[0].z_shieldcoinbase("*", myzaddr, Decimal('21000000.00000001')) self.nodes[0].z_shieldcoinbase("*", myzaddr, Decimal('21000000.00000001'))
except JSONRPCException,e: except JSONRPCException as e:
errorString = e.error['message'] errorString = e.error['message']
assert_equal("Amount out of range" in errorString, True) assert_equal("Amount out of range" in errorString, True)
# Shielding will fail because fee is larger than sum of utxos # Shielding will fail because fee is larger than sum of utxos
try: try:
self.nodes[0].z_shieldcoinbase("*", myzaddr, 999) self.nodes[0].z_shieldcoinbase("*", myzaddr, 999)
except JSONRPCException,e: except JSONRPCException as e:
errorString = e.error['message'] errorString = e.error['message']
assert_equal("Insufficient coinbase funds" in errorString, True) assert_equal("Insufficient coinbase funds" in errorString, True)
# Shielding will fail because limit parameter must be at least 0 # Shielding will fail because limit parameter must be at least 0
try: try:
self.nodes[0].z_shieldcoinbase("*", myzaddr, Decimal('0.001'), -1) self.nodes[0].z_shieldcoinbase("*", myzaddr, Decimal('0.001'), -1)
except JSONRPCException,e: except JSONRPCException as e:
errorString = e.error['message'] errorString = e.error['message']
assert_equal("Limit on maximum number of utxos cannot be negative" in errorString, True) assert_equal("Limit on maximum number of utxos cannot be negative" in errorString, True)
# Shielding will fail because limit parameter is absurdly large # Shielding will fail because limit parameter is absurdly large
try: try:
self.nodes[0].z_shieldcoinbase("*", myzaddr, Decimal('0.001'), 99999999999999) self.nodes[0].z_shieldcoinbase("*", myzaddr, Decimal('0.001'), 99999999999999)
except JSONRPCException,e: except JSONRPCException as e:
errorString = e.error['message'] errorString = e.error['message']
assert_equal("JSON integer out of range" in errorString, True) assert_equal("JSON integer out of range" in errorString, True)
@@ -214,3 +230,13 @@ class WalletShieldCoinbaseTest (BitcoinTestFramework):
sync_mempools(self.nodes[:2]) sync_mempools(self.nodes[:2])
self.nodes[1].generate(1) self.nodes[1].generate(1)
self.sync_all() self.sync_all()
if __name__ == '__main__':
# Upstream (Zcash/Hush) ran this test twice: once with Sprout zaddrs and once
# with Sapling. DragonX has no Sprout support at all -- z_getnewaddress only
# accepts "sapling" or "amnesia" (src/wallet/rpcwallet.cpp z_getnewaddress),
# so WalletShieldCoinbaseTest('sprout') cannot even allocate its target
# address. The sprout-only branches inside run_test() are kept intact for
# reference but only the sapling variant is executed.
print("Running for sapling...")
WalletShieldCoinbaseTest('sapling').main()
+13 -4
View File
@@ -1,4 +1,4 @@
#!/usr/bin/env python2 #!/usr/bin/env python3
# Copyright (c) 2016-2024 The Hush developers # Copyright (c) 2016-2024 The Hush developers
# Copyright (c) 2016 The Zcash developers # Copyright (c) 2016 The Zcash developers
# Distributed under the GPLv3 software license, see the accompanying # Distributed under the GPLv3 software license, see the accompanying
@@ -20,7 +20,16 @@ class WalletTreeStateTest (BitcoinTestFramework):
# Start nodes with -regtestprotectcoinbase to set fCoinbaseMustBeProtected to true. # Start nodes with -regtestprotectcoinbase to set fCoinbaseMustBeProtected to true.
def setup_network(self, split=False): def setup_network(self, split=False):
self.nodes = start_nodes(3, self.options.tmpdir, extra_args=[['-regtestprotectcoinbase','-debug=zrpc']] * 3 ) # -listen=1 and -dns=0 are DragonX-specific harness requirements, not part of the
# original test: start_node() passes -connect=0, which trips the "-connect set ->
# setting -listen=0" parameter interaction, so without -listen=1 the three nodes
# cannot open the p2p links connect_nodes_bi() asks for (node1/node2 stay at height
# 0 forever and sync_all() can never converge). -dns=0 blocks the unconditional
# node1..node10.dragonx.is -addnode injection in hush_args(), which otherwise dials
# the real DragonX seed nodes from regtest and floods these nodes with mainnet headers.
self.nodes = start_nodes(3, self.options.tmpdir,
extra_args=[['-regtestprotectcoinbase','-debug=zrpc',
'-listen=1','-dns=0']] * 3 )
connect_nodes_bi(self.nodes,0,1) connect_nodes_bi(self.nodes,0,1)
connect_nodes_bi(self.nodes,1,2) connect_nodes_bi(self.nodes,1,2)
connect_nodes_bi(self.nodes,0,2) connect_nodes_bi(self.nodes,0,2)
@@ -28,7 +37,7 @@ class WalletTreeStateTest (BitcoinTestFramework):
self.sync_all() self.sync_all()
def run_test (self): def run_test (self):
print "Mining blocks..." print("Mining blocks...")
self.nodes[0].generate(100) self.nodes[0].generate(100)
self.sync_all() self.sync_all()
@@ -79,7 +88,7 @@ class WalletTreeStateTest (BitcoinTestFramework):
myopid = self.nodes[0].z_sendmany(myzaddr, recipients) myopid = self.nodes[0].z_sendmany(myzaddr, recipients)
# Wait for Tx 2 to begin executing... # Wait for Tx 2 to begin executing...
for x in xrange(1, 60): for x in range(1, 60):
results = self.nodes[0].z_getoperationstatus([myopid]) results = self.nodes[0].z_getoperationstatus([myopid])
status = results[0]["status"] status = results[0]["status"]
if status == "executing": if status == "executing":
+53 -10
View File
@@ -1,4 +1,4 @@
#!/usr/bin/env python2 #!/usr/bin/env python3
# Copyright (c) 2016-2024 The Hush developers # Copyright (c) 2016-2024 The Hush developers
# Copyright (c) 2014 The Bitcoin Core developers # Copyright (c) 2014 The Bitcoin Core developers
# Distributed under the GPLv3 software license, see the accompanying # Distributed under the GPLv3 software license, see the accompanying
@@ -37,8 +37,8 @@ and confirm again balances are correct.
from test_framework.test_framework import BitcoinTestFramework from test_framework.test_framework import BitcoinTestFramework
from test_framework.authproxy import JSONRPCException from test_framework.authproxy import JSONRPCException
from test_framework.util import assert_equal, initialize_chain_clean, \ from test_framework.util import assert_equal, initialize_chain_clean, \
start_nodes, start_node, connect_nodes, stop_node, \ start_nodes, start_node, connect_nodes, \
sync_blocks, sync_mempools sync_blocks, sync_mempools, bitcoind_processes
import os import os
import shutil import shutil
@@ -48,6 +48,46 @@ import logging
logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.INFO) logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.INFO)
# Three node flags this test has to supply for itself, because test_framework.util.start_node()
# cannot give it a usable isolated regtest network on DragonX:
#
# -listen=1: start_node() passes "-connect=0" to every node. In DragonX (as in Bitcoin) the
# presence of a -connect argument SoftSetBoolArg()s -listen to false, so no test node ever
# binds its p2p port and connect_nodes() cannot build the loopback topology this test needs.
# Verified on a live run: only the RPC ports were listening and getpeerinfo showed zero
# 127.0.0.1 peers on all four nodes. SoftSetBoolArg does not override an explicit value.
#
# -dns=0: hush_args() unconditionally appends node1..node10.dragonx.is to -addnode whenever the
# chain name is DRAGONX, regardless of network, and -connect=0 does not suppress it. On a live
# run every "regtest" node ended up with 7-8 established connections to production mainnet
# nodes on port 21768, was flooded with mainnet headers ("AcceptBlockHeader: hashPrevBlock ...
# not found"), and one of them aborted on CheckBlockIndex(). -dns=0 stops the hostnames from
# resolving while leaving the literal 127.0.0.1:PORT addnodes connect_nodes() uses intact.
#
# -allowlist=127.0.0.1: "-connect=0" does not mean "no connections". The daemon resolves the
# literal "0" to 0.0.0.0 and dials it on the chain's default p2p port, i.e. 127.0.0.1:21768 --
# which on a machine that also runs a real node is the PRODUCTION daemon (observed:
# ESTAB 127.0.0.1:41282 -> 127.0.0.1:21768 from every test node, peer subver /DragonX:1.0.3/,
# startingheight 3254254). That peer is outbound, so it is the node's only preferred-download
# peer; main.cpp:8398 then computes fFetch=false for every inbound peer, and node3 -- which in
# this test's topology is dialed by everyone and dials no one -- never downloads an announced
# block, so sync_blocks() hangs forever. Allowlisting loopback makes inbound test peers
# preferred-download too (main.cpp:381), which restores block propagation.
LISTEN = "-listen=1"
NODNS = "-dns=0"
ALLOWLIST = "-allowlist=127.0.0.1"
def stop_node_and_reap(node, i):
# Equivalent to test_framework.util.stop_node(), which cannot be called: it does
# print("Stopping node " + i) with the int index that every caller passes, which raises
# TypeError. Reimplemented here rather than editing shared framework code other tests use.
print("Stopping node %d" % i)
node.stop()
bitcoind_processes[i].wait()
del bitcoind_processes[i]
class WalletBackupTest(BitcoinTestFramework): class WalletBackupTest(BitcoinTestFramework):
def setup_chain(self): def setup_chain(self):
@@ -62,7 +102,10 @@ class WalletBackupTest(BitcoinTestFramework):
ed2 = "-exportdir=" + self.options.tmpdir + "/node2" ed2 = "-exportdir=" + self.options.tmpdir + "/node2"
# nodes 1, 2,3 are spenders, let's give them a keypool=100 # nodes 1, 2,3 are spenders, let's give them a keypool=100
extra_args = [["-keypool=100", ed0], ["-keypool=100", ed1], ["-keypool=100", ed2], []] extra_args = [["-keypool=100", ed0, LISTEN, NODNS, ALLOWLIST],
["-keypool=100", ed1, LISTEN, NODNS, ALLOWLIST],
["-keypool=100", ed2, LISTEN, NODNS, ALLOWLIST],
[LISTEN, NODNS, ALLOWLIST]]
self.nodes = start_nodes(4, self.options.tmpdir, extra_args) self.nodes = start_nodes(4, self.options.tmpdir, extra_args)
connect_nodes(self.nodes[0], 3) connect_nodes(self.nodes[0], 3)
connect_nodes(self.nodes[1], 3) connect_nodes(self.nodes[1], 3)
@@ -95,18 +138,18 @@ class WalletBackupTest(BitcoinTestFramework):
# As above, this mirrors the original bash test. # As above, this mirrors the original bash test.
def start_three(self): def start_three(self):
self.nodes[0] = start_node(0, self.options.tmpdir) self.nodes[0] = start_node(0, self.options.tmpdir, [LISTEN, NODNS, ALLOWLIST])
self.nodes[1] = start_node(1, self.options.tmpdir) self.nodes[1] = start_node(1, self.options.tmpdir, [LISTEN, NODNS, ALLOWLIST])
self.nodes[2] = start_node(2, self.options.tmpdir) self.nodes[2] = start_node(2, self.options.tmpdir, [LISTEN, NODNS, ALLOWLIST])
connect_nodes(self.nodes[0], 3) connect_nodes(self.nodes[0], 3)
connect_nodes(self.nodes[1], 3) connect_nodes(self.nodes[1], 3)
connect_nodes(self.nodes[2], 3) connect_nodes(self.nodes[2], 3)
connect_nodes(self.nodes[2], 0) connect_nodes(self.nodes[2], 0)
def stop_three(self): def stop_three(self):
stop_node(self.nodes[0], 0) stop_node_and_reap(self.nodes[0], 0)
stop_node(self.nodes[1], 1) stop_node_and_reap(self.nodes[1], 1)
stop_node(self.nodes[2], 2) stop_node_and_reap(self.nodes[2], 2)
def erase_three(self): def erase_three(self):
os.remove(self.options.tmpdir + "/node0/regtest/wallet.dat") os.remove(self.options.tmpdir + "/node0/regtest/wallet.dat")
+12 -1
View File
@@ -12,8 +12,19 @@ hush_gtest_SOURCES = \
gtest/main.cpp \ gtest/main.cpp \
gtest/utils.cpp \ gtest/utils.cpp \
gtest/test_randomx_preverify.cpp \ gtest/test_randomx_preverify.cpp \
gtest/test_randomx_heightrecover.cpp \
gtest/test_hdtransparent.cpp \ gtest/test_hdtransparent.cpp \
gtest/test_mnemonic_compat.cpp gtest/test_mnemonic_compat.cpp \
gtest/test_stratum_jobid.cpp \
gtest/test_wallet_notedata.cpp \
gtest/test_net_closesocket.cpp \
gtest/test_fd_defense.cpp \
gtest/test_wallet_dbenv.cpp \
gtest/test_wallet_notecache.cpp \
gtest/test_wallet_history.cpp \
gtest/test_wallet_consolidation.cpp \
gtest/test_wallet_shutdownsave.cpp \
gtest/test_wallet_witnessroots.cpp
hush_gtest_CPPFLAGS = $(AM_CPPFLAGS) -DMULTICORE -fopenmp -DBINARY_OUTPUT -DCURVE_ALT_BN128 -DSTATIC $(BITCOIN_INCLUDES) hush_gtest_CPPFLAGS = $(AM_CPPFLAGS) -DMULTICORE -fopenmp -DBINARY_OUTPUT -DCURVE_ALT_BN128 -DSTATIC $(BITCOIN_INCLUDES)
hush_gtest_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS) hush_gtest_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS)
+6 -2
View File
@@ -257,14 +257,18 @@ UniValue CallRPC(const std::string& strMethod, const UniValue& params)
event_base_dispatch(base.get()); event_base_dispatch(base.get());
if (response.status == 0) { if (response.status == 0) {
// Report the port we ACTUALLY dialled. ASSETCHAINS_RPCPORT is a separate global that is
// initialised to the mainnet default at the top of this file and never assigned here, so
// using it made every failure claim port 21769 no matter what -rpcport was given -- which
// reads as "your -rpcport was ignored" and sends you chasing a config bug that isn't there.
throw CConnectionFailed(strprintf("couldn't connect to server at port %d : %s (code %d)\n(make sure server is running and you are connecting to the correct RPC port)", throw CConnectionFailed(strprintf("couldn't connect to server at port %d : %s (code %d)\n(make sure server is running and you are connecting to the correct RPC port)",
ASSETCHAINS_RPCPORT, http_errorstring(response.error), response.error)); port, http_errorstring(response.error), response.error));
} else if (response.status == HTTP_UNAUTHORIZED) { } else if (response.status == HTTP_UNAUTHORIZED) {
throw std::runtime_error("incorrect rpcuser or rpcpassword (authorization failed)"); throw std::runtime_error("incorrect rpcuser or rpcpassword (authorization failed)");
} else if (response.status >= 400 && response.status != HTTP_BAD_REQUEST && response.status != HTTP_NOT_FOUND && response.status != HTTP_INTERNAL_SERVER_ERROR) { } else if (response.status >= 400 && response.status != HTTP_BAD_REQUEST && response.status != HTTP_NOT_FOUND && response.status != HTTP_INTERNAL_SERVER_ERROR) {
throw std::runtime_error(strprintf("server returned HTTP error %d", response.status)); throw std::runtime_error(strprintf("server returned HTTP error %d", response.status));
} else if (response.body.empty()) { } else if (response.body.empty()) {
throw std::runtime_error(strprintf("no response from server at port %d", ASSETCHAINS_RPCPORT )); throw std::runtime_error(strprintf("no response from server at port %d", port));
} }
// Parse reply // Parse reply
+24 -5
View File
@@ -35,7 +35,7 @@ extern bool fZindex;
// These version thresholds control whether nSproutValue/nSaplingValue are // These version thresholds control whether nSproutValue/nSaplingValue are
// serialized in the block index. They must be <= CLIENT_VERSION or the // serialized in the block index. They must be <= CLIENT_VERSION or the
// values will never be persisted, causing nChainSaplingValue to reset // values will never be persisted, causing nChainSaplingValue to reset
// to 0 after node restart. DragonX CLIENT_VERSION is 1010050 (v1.1.0.50). // to 0 after node restart. DragonX CLIENT_VERSION is 1030150 (v1.3.1.50).
static const int SPROUT_VALUE_VERSION = 1000000; static const int SPROUT_VALUE_VERSION = 1000000;
static const int SAPLING_VALUE_VERSION = 1000000; static const int SAPLING_VALUE_VERSION = 1000000;
// Block-index records written at >= this version store nSaplingValue as a boost::optional // Block-index records written at >= this version store nSaplingValue as a boost::optional
@@ -113,10 +113,9 @@ enum BlockStatus: uint32_t {
//! Scripts & signatures ok. Implies all parents are also at least SCRIPTS. //! Scripts & signatures ok. Implies all parents are also at least SCRIPTS.
BLOCK_VALID_SCRIPTS = 5, BLOCK_VALID_SCRIPTS = 5,
// flag to check if contextual check block has passed in Accept block, if it has not check at connect block.
BLOCK_VALID_CONTEXT = 6,
//! All validity bits. //! All validity bits.
//! NOTE: the levels above are sequential VALUES occupying this 3-bit field, not independent
//! bits, so any flag stored in nStatus must live entirely outside this mask.
BLOCK_VALID_MASK = BLOCK_VALID_HEADER | BLOCK_VALID_TREE | BLOCK_VALID_TRANSACTIONS | BLOCK_VALID_MASK = BLOCK_VALID_HEADER | BLOCK_VALID_TREE | BLOCK_VALID_TRANSACTIONS |
BLOCK_VALID_CHAIN | BLOCK_VALID_SCRIPTS, BLOCK_VALID_CHAIN | BLOCK_VALID_SCRIPTS,
@@ -129,9 +128,29 @@ enum BlockStatus: uint32_t {
BLOCK_FAILED_MASK = BLOCK_FAILED_VALID | BLOCK_FAILED_CHILD, BLOCK_FAILED_MASK = BLOCK_FAILED_VALID | BLOCK_FAILED_CHILD,
BLOCK_ACTIVATES_UPGRADE = 128, //! block activates a network upgrade BLOCK_ACTIVATES_UPGRADE = 128, //! block activates a network upgrade
BLOCK_IN_TMPFILE = 256 BLOCK_IN_TMPFILE = 256,
//! ContextualCheckBlock already passed in AcceptBlock, so ConnectBlock may skip re-running it.
//! Was 6 until v1.3.0, which put it INSIDE BLOCK_VALID_MASK (1|2|3|4|5 == 7): `nStatus |=
//! BLOCK_VALID_CONTEXT` then overwrote the validity level rather than setting a flag, so a
//! block that was only written to disk read back as BLOCK_VALID_SCRIPTS and every later
//! RaiseValidity() silently no-opped. Detected by CheckBlockIndex's "CHAIN valid implies all
//! parents are CHAIN valid" assert, which aborts any node doing out-of-order block download
//! (regtest only, where fDefaultConsistencyChecks is true). Validity was only ever inflated,
//! never deflated, so ConnectBlock's full validation was never skipped -- see git history.
//! Legacy block indexes still carry the polluted low bits; they resolve on reindex, and until
//! then simply re-run the contextual check they used to skip.
BLOCK_VALID_CONTEXT = 512
}; };
//! The validity level is a small integer packed into BLOCK_VALID_MASK, so every other nStatus flag
//! must be disjoint from it. Enforced here so this class of bug cannot be reintroduced silently.
static_assert((BLOCK_VALID_CONTEXT & BLOCK_VALID_MASK) == 0, "BLOCK_VALID_CONTEXT overlaps the validity-level field");
static_assert((BLOCK_HAVE_MASK & BLOCK_VALID_MASK) == 0, "BLOCK_HAVE_MASK overlaps the validity-level field");
static_assert((BLOCK_FAILED_MASK & BLOCK_VALID_MASK) == 0, "BLOCK_FAILED_MASK overlaps the validity-level field");
static_assert((BLOCK_ACTIVATES_UPGRADE & BLOCK_VALID_MASK) == 0, "BLOCK_ACTIVATES_UPGRADE overlaps the validity-level field");
static_assert((BLOCK_IN_TMPFILE & BLOCK_VALID_MASK) == 0, "BLOCK_IN_TMPFILE overlaps the validity-level field");
//! Short-hand for the highest consensus validity we implement. //! Short-hand for the highest consensus validity we implement.
//! Blocks with this validity are assumed to satisfy all consensus rules. //! Blocks with this validity are assumed to satisfy all consensus rules.
static const BlockStatus BLOCK_VALID_CONSENSUS = BLOCK_VALID_SCRIPTS; static const BlockStatus BLOCK_VALID_CONSENSUS = BLOCK_VALID_SCRIPTS;
+2 -2
View File
@@ -29,8 +29,8 @@
//! These need to be macros, as clientversion.cpp's and bitcoin*-res.rc's voodoo requires it //! These need to be macros, as clientversion.cpp's and bitcoin*-res.rc's voodoo requires it
// Must be kept in sync with configure.ac , ugh! // Must be kept in sync with configure.ac , ugh!
#define CLIENT_VERSION_MAJOR 1 #define CLIENT_VERSION_MAJOR 1
#define CLIENT_VERSION_MINOR 2 #define CLIENT_VERSION_MINOR 3
#define CLIENT_VERSION_REVISION 0 #define CLIENT_VERSION_REVISION 1
#define CLIENT_VERSION_BUILD 50 #define CLIENT_VERSION_BUILD 50
//! Set to true for release, false for prerelease or test build //! Set to true for release, false for prerelease or test build
+83
View File
@@ -0,0 +1,83 @@
// Copyright (c) 2016-2024 The Hush developers
// Distributed under the GPLv3 software license, see the accompanying
// file COPYING or https://www.gnu.org/licenses/gpl-3.0.en.html
#include <gtest/gtest.h>
#include <atomic>
#include <errno.h>
#include <stdexcept>
#include <stdio.h>
#include <unistd.h>
#include <boost/filesystem.hpp>
#include <boost/thread.hpp>
#include "chainparams.h"
#include "init.h"
#include "main.h"
#include "noui.h"
#include "util.h"
#include "validationinterface.h"
extern std::atomic<bool> fRequestShutdown;
// A block file opened for reading must not be writable through its fd: a stray write through a reused fd number
// (the wolfSSL CloseSocket macro let the wallet's BDB fd be closed behind its back) used to land in it.
TEST(FdDefense, ReadOnlyBlockFileIsNotWritable) {
SelectParams(CBaseChainParams::MAIN);
const boost::filesystem::path dir = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path("fddefense-%%%%%%%%");
const bool hadDatadir = mapArgs.count("-datadir") > 0;
const std::string oldDatadir = hadDatadir ? mapArgs["-datadir"] : "";
boost::filesystem::create_directories(dir);
mapArgs["-datadir"] = dir.string();
ClearDatadirCache();
const CDiskBlockPos pos(0, 0);
const boost::filesystem::path blk = GetBlockPosFilename(pos, "blk");
boost::filesystem::create_directories(blk.parent_path());
{
FILE* f = fopen(blk.string().c_str(), "wb");
ASSERT_TRUE(f != nullptr);
fputs("block bytes", f);
fclose(f);
}
FILE* ro = OpenBlockFile(pos, true);
ASSERT_TRUE(ro != nullptr);
char c = 0;
EXPECT_EQ(1u, fread(&c, 1, 1, ro)) << "still readable";
errno = 0;
EXPECT_EQ(-1, pwrite(fileno(ro), "X", 1, 0)) << "a write through a read-only block file's fd must fail";
EXPECT_EQ(EBADF, errno);
fclose(ro);
FILE* rw = OpenBlockFile(pos, false);
ASSERT_TRUE(rw != nullptr);
EXPECT_EQ(1, pwrite(fileno(rw), "b", 1, 0)) << "the writable open still writes";
fclose(rw);
if (hadDatadir) mapArgs["-datadir"] = oldDatadir; else mapArgs.erase("-datadir");
ClearDatadirCache();
boost::filesystem::remove_all(dir);
}
// A wallet notification that throws (a wallet DB failure) requests a clean shutdown instead of escaping the
// notifier thread into std::terminate; a successful one doesn't; thread interruption still propagates.
TEST(FdDefense, WalletNotifyFailureShutsDownCleanly) {
noui_connect(); // the daemon connects these UI signals at startup; the error path shows a message box
fRequestShutdown = false;
EXPECT_TRUE(NotifyWalletsOrShutdown([] {}));
EXPECT_FALSE(ShutdownRequested());
EXPECT_FALSE(NotifyWalletsOrShutdown([] { throw std::runtime_error("CWalletDB::ListAccountCreditDebit(): error scanning DB"); }));
EXPECT_TRUE(ShutdownRequested());
fRequestShutdown = false;
EXPECT_FALSE(NotifyWalletsOrShutdown([] { throw 42; }));
EXPECT_TRUE(ShutdownRequested());
fRequestShutdown = false;
EXPECT_THROW(NotifyWalletsOrShutdown([] { throw boost::thread_interrupted(); }), boost::thread_interrupted);
EXPECT_FALSE(ShutdownRequested());
}
+50
View File
@@ -0,0 +1,50 @@
// Copyright (c) 2016-2024 The Hush developers
// Distributed under the GPLv3 software license, see the accompanying
// file COPYING or https://www.gnu.org/licenses/gpl-3.0.en.html
#include <gtest/gtest.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <unistd.h>
#include "net.h"
#include "util/sock.h"
// Regression test for the wolfSSL CloseSocket macro (see net.h): closing a CNode's socket must invalidate
// hSocket, so neither a repeated CloseSocketDisconnect nor ~CNode can close that fd number again once another
// owner (the wallet's BDB files, a block file, an RPC socket) has been handed it.
TEST(NetCloseSocket, ClosedNodeNeverClosesAReusedFdNumber) {
int pair[2];
ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, pair));
const int number = pair[0];
CNode* node = new CNode(number, CAddress(), "", true); // inbound: sends no version message
node->CloseSocketDisconnect();
EXPECT_EQ(INVALID_SOCKET, node->hSocket) << "CloseSocketDisconnect left the closed fd number in hSocket";
EXPECT_EQ(-1, fcntl(number, F_GETFD)) << "the node's socket wasn't closed";
// Another owner gets the freed number, as the kernel's lowest-free-fd rule does in a busy node.
const int other = open("/dev/null", O_RDONLY);
ASSERT_GE(other, 0);
ASSERT_EQ(number, dup2(other, number));
node->CloseSocketDisconnect(); // e.g. a send error after the disconnect was already handled
delete node; // ~CNode
EXPECT_NE(-1, fcntl(number, F_GETFD)) << "a closed CNode closed the fd number's new owner";
close(number);
close(other);
close(pair[1]);
}
// util/sock.cpp's CloseSocket is the one that must be called: it closes once and invalidates.
TEST(NetCloseSocket, CloseSocketInvalidates) {
int pair[2];
ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, pair));
SOCKET s = pair[0];
EXPECT_TRUE(CloseSocket(s));
EXPECT_EQ(INVALID_SOCKET, s);
EXPECT_FALSE(CloseSocket(s)) << "a second close of an invalidated handle must be a no-op";
close(pair[1]);
}
+116
View File
@@ -0,0 +1,116 @@
// Copyright (c) 2024-2026 The DragonX developers
// Distributed under the GPLv3 software license, see the accompanying
// file COPYING or https://www.gnu.org/licenses/gpl-3.0.en.html
//
// Regression guard for the hush_checkPOW height-0 RandomX fix. A block arriving over P2P reaches
// hush_checkPOW with height==0; the first CheckRandomXSolution runs at height 0 (where
// RandomXValidationRequired is false, so it is skipped), the real height is then recovered from
// hashPrevBlock, and the fix re-runs CheckRandomXSolution at that height. Without the fix a block
// with a forged RandomX solution would be accepted on that path. We prove: (1) CheckRandomXSolution
// is skipped at height 0 but rejects the forged solution at the real height; (2) hush_checkPOW lets
// the forged block through only while the parent is unknown (height cannot be recovered), and
// rejects it once the parent is known and the height recovers -- which is exactly what the fix does.
#include <gtest/gtest.h>
#include <cstring>
#include <string>
#include "arith_uint256.h"
#include "chain.h"
#include "chainparams.h"
#include "chainparamsbase.h"
#include "pow.h"
#include "primitives/block.h"
#include "primitives/transaction.h"
#include "RandomX/src/randomx.h"
#include "hush_defs.h"
#include "main.h"
#include "sync.h"
#include "uint256.h"
extern int32_t HUSH_LOADINGBLOCKS;
extern bool fCheckpointsEnabled;
int32_t hush_checkPOW(int32_t slowflag, CBlock *pblock, int32_t height);
TEST(RandomXHeightRecover, ForgedSolutionRejectedOnceHeightIsRecovered)
{
// hush_checkPOW calls Params(); give it a selected chain. Done before the ASSETCHAINS_* globals
// below so params init cannot clobber them. RandomX is enforced via ASSETCHAINS_RANDOMX_VALIDATION,
// not the chain's activation height, so MAIN's high activation height is irrelevant here.
SelectParams(CBaseChainParams::MAIN);
// Save the globals this test flips.
uint32_t sAlgo = ASSETCHAINS_ALGO, sRx = ASSETCHAINS_RANDOMX;
int32_t sVal = ASSETCHAINS_RANDOMX_VALIDATION, sLoad = HUSH_LOADINGBLOCKS;
bool sCkpt = fCheckpointsEnabled;
char sSym[sizeof(SMART_CHAIN_SYMBOL)];
std::memcpy(sSym, SMART_CHAIN_SYMBOL, sizeof sSym);
ASSETCHAINS_RANDOMX = 2; // a distinct nonzero algo id
ASSETCHAINS_ALGO = ASSETCHAINS_RANDOMX;
ASSETCHAINS_RANDOMX_VALIDATION = 1; // enforce from height 1
HUSH_LOADINGBLOCKS = 0; // not initial-load (else RandomX skipped)
fCheckpointsEnabled = false; // avoid the below-checkpoint skip
std::strcpy(SMART_CHAIN_SYMBOL, "DRGXTEST"); // non-empty: not the default regtest chain
// A block with a FORGED RandomX solution (all zero bytes -- overwhelmingly not the real hash).
CBlock block;
block.nVersion = 4;
block.hashPrevBlock = uint256S("0x0000000000000000000000000000000000000000000000000000000000000011");
block.hashMerkleRoot = uint256S("0x0000000000000000000000000000000000000000000000000000000000000022");
block.hashFinalSaplingRoot = uint256S("0x0000000000000000000000000000000000000000000000000000000000000033");
block.nTime = 1700000000;
block.nBits = 0x200f0f0f;
block.nNonce = uint256S("0x0000000000000000000000000000000000000000000000000000000000000001");
block.nSolution.assign(RANDOMX_HASH_SIZE, 0);
// hush_block2pubkey33 reads vtx[0]; give the block a minimal coinbase so it is never a null deref.
CMutableTransaction cb;
cb.vin.resize(1);
cb.vin[0].prevout.SetNull();
cb.vout.resize(1);
block.vtx.push_back(CTransaction(cb));
// Grind the nonce so the block's SHA target check passes. Then the ONLY thing that can reject it
// in hush_checkPOW at the recovered height is the RandomX re-check, so the test isolates the fix
// (without the fix the block would fall through the target check and be accepted).
arith_uint256 bnTarget;
bool neg, over;
bnTarget.SetCompact(block.nBits, &neg, &over);
for (uint32_t n = 1; n < 100000; n++) {
block.nNonce = ArithToUint256(arith_uint256(n));
if (UintToArith256(block.GetHash()) <= bnTarget) break;
}
ASSERT_LE(UintToArith256(block.GetHash()), bnTarget) << "could not grind a passing SHA target";
// (1) The primitive the fix relies on: skipped at height 0, rejects the forgery at the real height.
EXPECT_TRUE(CheckRandomXSolution(&block, 0)) << "RandomX must be skipped at height 0";
EXPECT_FALSE(CheckRandomXSolution(&block, 10)) << "a forged solution must be rejected at its real height";
// (2a) Parent unknown: hush_checkPOW cannot recover the height, so it stays 0 and the block is NOT
// rejected here -- the pre-fix behavior for an unrecoverable height.
EXPECT_GE(hush_checkPOW(0, &block, 0), 0)
<< "with no recoverable height the forged block is not rejected on this path";
// (2b) Parent known at height 9: the height recovers to 10 and the fix re-checks RandomX -> rejected.
CBlockIndex prev;
prev.SetHeight(9);
uint256 prevHash = block.hashPrevBlock;
prev.phashBlock = &prevHash;
{
LOCK(cs_main);
mapBlockIndex[prevHash] = &prev;
}
EXPECT_LT(hush_checkPOW(0, &block, 0), 0)
<< "once the height recovers, the fix must reject the forged RandomX solution";
{
LOCK(cs_main);
mapBlockIndex.erase(prevHash);
}
// Restore.
ASSETCHAINS_ALGO = sAlgo; ASSETCHAINS_RANDOMX = sRx;
ASSETCHAINS_RANDOMX_VALIDATION = sVal; HUSH_LOADINGBLOCKS = sLoad;
fCheckpointsEnabled = sCkpt;
std::memcpy(SMART_CHAIN_SYMBOL, sSym, sizeof sSym);
}
+98
View File
@@ -0,0 +1,98 @@
// Copyright (c) 2016-2026 The Hush developers
// Distributed under the GPLv3 software license, see the accompanying
// file COPYING or https://www.gnu.org/licenses/gpl-3.0.en.html
//
// Regression coverage for the b3e81f1ed fix:
// "stratum: do not abort the daemon on a malformed 63-character job_id"
//
// The EWBF "31 bytes job_id" path in stratum_mining_submit() completes a
// 63-character job_id with each hex digit in turn and feeds the result to
// uint256(). ParseHex() stops at the first non-hex character and returns a
// SHORT vector without signalling an error, and base_blob's vector ctor
// asserts vch.size() == 32. asserts are live in release builds here, and the
// job_id arrives from an unauthenticated client -- so a single mining.submit
// whose 63-character job_id contains any non-hex byte (63 spaces will do)
// used to abort the node.
//
// The fix size-checks each candidate before constructing uint256. These tests
// pin the exact invariant that guard relies on, using the real ParseHex and
// uint256 primitives, without ever constructing a uint256 from a short vector
// (which would still abort under the guard we are protecting).
#include <gtest/gtest.h>
#include <string>
#include <vector>
#include "uint256.h"
#include "utilstrencodings.h"
namespace {
const std::string HEXDIGITS = "0123456789abcdef";
// Mirrors the guarded completion loop in stratum_mining_submit(): try every
// single-hex-digit completion and report whether ANY of them parses to a
// whole 32-byte value. Only then is uint256() construction reached.
bool AnyCompletionParsesTo32(const std::string& jobid) {
for (char d : HEXDIGITS) {
std::vector<unsigned char> vch = ParseHex(jobid + d);
if (vch.size() == 32) return true;
}
return false;
}
} // namespace
// The exact example from the fix commit: a 63-character job_id of spaces.
// No completion may reach a 32-byte vector, so the daemon never constructs
// uint256() and never aborts.
TEST(StratumJobId, AllSpacesNeverYields32Bytes) {
std::string spaces(63, ' ');
ASSERT_EQ(spaces.size(), 63u);
for (char d : HEXDIGITS) {
EXPECT_NE(ParseHex(spaces + d).size(), 32u)
<< "completion '" << d << "' unexpectedly produced 32 bytes";
}
EXPECT_FALSE(AnyCompletionParsesTo32(spaces));
}
// A single non-hex byte embedded in an otherwise-hex 63-char job_id is enough:
// ParseHex stops at it, so every completion is short.
TEST(StratumJobId, SingleNonHexByteInMiddleIsRejected) {
std::string jobid(63, 'a');
jobid[30] = 'g'; // 'g' is not a hex digit
ASSERT_EQ(jobid.size(), 63u);
EXPECT_FALSE(AnyCompletionParsesTo32(jobid));
}
// A non-hex byte at the very end (position 62) is likewise rejected: the last
// hex pair can never complete to a whole byte.
TEST(StratumJobId, NonHexByteAtEndIsRejected) {
std::string jobid(62, 'a');
jobid.push_back('z'); // length 63, last char non-hex
ASSERT_EQ(jobid.size(), 63u);
EXPECT_FALSE(AnyCompletionParsesTo32(jobid));
}
// A genuine truncated EWBF job_id -- 63 real hex characters -- must complete
// to exactly 32 bytes for every digit, so uint256() construction is safe.
TEST(StratumJobId, ValidSixtyThreeHexCompletesToExactly32Bytes) {
std::string jobid(63, 'a');
ASSERT_EQ(jobid.size(), 63u);
for (char d : HEXDIGITS) {
std::vector<unsigned char> vch = ParseHex(jobid + d);
ASSERT_EQ(vch.size(), 32u) << "completion '" << d << "'";
// 32-byte vector: construction must not trip the size assertion.
uint256 h(vch);
EXPECT_EQ(h.size(), 32u);
}
EXPECT_TRUE(AnyCompletionParsesTo32(jobid));
}
// Sanity anchors for ParseHex's odd/even handling that the loop depends on:
// an odd hex length drops the trailing nibble (63 hex -> 31 bytes), and one
// more hex char fills the 32nd byte (64 hex -> 32 bytes).
TEST(StratumJobId, ParseHexOddLengthDropsTrailingNibble) {
EXPECT_EQ(ParseHex(std::string(63, 'a')).size(), 31u);
EXPECT_EQ(ParseHex(std::string(64, 'a')).size(), 32u);
}
+395
View File
@@ -0,0 +1,395 @@
// Copyright (c) 2016-2026 The Hush developers
// Distributed under the GPLv3 software license, see the accompanying
// file COPYING or https://www.gnu.org/licenses/gpl-3.0.en.html
#include <gtest/gtest.h>
#include <algorithm>
#include <map>
#include <set>
#include "arith_uint256.h"
#include "primitives/transaction.h"
#include "random.h"
#include "wallet/asyncrpcoperation_saplingconsolidation.h"
#include "wallet/wallet.h"
namespace {
// Always the low end, always the high end, or a fixed sequence.
uint64_t RngLow(uint64_t) { return 0; }
uint64_t RngHigh(uint64_t n) { return n == 0 ? 0 : n - 1; }
std::vector<CAmount> Values(size_t n, CAmount start = 1000, CAmount step = 1000) {
std::vector<CAmount> v;
for (size_t i = 0; i < n; i++)
v.push_back(start + step * (CAmount)i);
return v;
}
size_t PlannedNotes(const std::vector<SaplingConsolidationBatch>& plan, size_t group) {
size_t n = 0;
for (const SaplingConsolidationBatch& b : plan)
if (b.group == group)
n += b.notes.size();
return n;
}
} // namespace
TEST(SaplingConsolidationPlan, ThresholdIsStrict) {
SaplingConsolidationPolicy policy; // threshold 25, batch 15, 3 txs
std::vector<std::vector<CAmount>> groups = { Values(25), Values(26) };
auto plan = PlanSaplingConsolidation(groups, policy, RngHigh);
EXPECT_EQ(PlannedNotes(plan, 0), 0u) << "an address AT the threshold is left alone";
EXPECT_GT(PlannedNotes(plan, 1), 0u) << "an address one note over it is consolidated";
}
TEST(SaplingConsolidationPlan, DefaultsMergeUpToThreeBatches) {
SaplingConsolidationPolicy policy;
std::vector<std::vector<CAmount>> groups = { Values(200) };
auto high = PlanSaplingConsolidation(groups, policy, RngHigh);
ASSERT_EQ(high.size(), 3u);
for (const auto& b : high)
EXPECT_EQ(b.notes.size(), 15u);
// ceil(2*15/3) = 10 at the low end.
auto low = PlanSaplingConsolidation(groups, policy, RngLow);
ASSERT_EQ(low.size(), 3u);
for (const auto& b : low)
EXPECT_EQ(b.notes.size(), 10u);
}
TEST(SaplingConsolidationPlan, SmallestNotesFirstAndDisjoint) {
SaplingConsolidationPolicy policy;
// Shuffled values; the planner must take them in ascending order.
std::vector<CAmount> v = Values(100);
std::vector<CAmount> shuffled = v;
std::reverse(shuffled.begin(), shuffled.end());
std::rotate(shuffled.begin(), shuffled.begin() + 37, shuffled.end());
std::vector<std::vector<CAmount>> groups = { shuffled };
auto plan = PlanSaplingConsolidation(groups, policy, RngHigh);
ASSERT_EQ(plan.size(), 3u);
std::set<size_t> seen;
std::vector<CAmount> taken;
for (const auto& b : plan) {
for (size_t idx : b.notes) {
ASSERT_LT(idx, shuffled.size());
EXPECT_TRUE(seen.insert(idx).second) << "a note is planned twice";
taken.push_back(shuffled[idx]);
}
}
// The 45 notes taken are exactly the 45 smallest, in ascending order across batches.
ASSERT_EQ(taken.size(), 45u);
for (size_t i = 0; i < taken.size(); i++)
EXPECT_EQ(taken[i], v[i]);
}
TEST(SaplingConsolidationPlan, NeverCrossesAddresses) {
SaplingConsolidationPolicy policy;
std::vector<std::vector<CAmount>> groups = { Values(40, 5), Values(3), Values(80, 7), Values(26, 1) };
auto plan = PlanSaplingConsolidation(groups, policy, [](uint64_t n) { return GetRand(n); });
std::map<size_t, int> txs;
std::map<size_t, std::set<size_t>> used;
for (const auto& b : plan) {
ASSERT_LT(b.group, groups.size());
txs[b.group]++;
for (size_t idx : b.notes) {
ASSERT_LT(idx, groups[b.group].size());
EXPECT_TRUE(used[b.group].insert(idx).second);
}
}
EXPECT_EQ(txs.count(1), 0u) << "3 notes is under the threshold";
for (const auto& t : txs)
EXPECT_LE(t.second, policy.maxTxs);
// Each consolidated address keeps at least one note outside the round.
for (const auto& u : used)
EXPECT_LT(u.second.size(), groups[u.first].size());
}
TEST(SaplingConsolidationPlan, LeavesOneNoteAndStopsBelowTwoInputs) {
SaplingConsolidationPolicy policy;
policy.threshold = 2;
// 30 notes, batch 15: 15, then at most 14 (one must stay out), then nothing.
auto plan = PlanSaplingConsolidation({ Values(30) }, policy, RngHigh);
ASSERT_EQ(plan.size(), 2u);
EXPECT_EQ(plan[0].notes.size(), 15u);
EXPECT_EQ(plan[1].notes.size(), 14u);
// 3 notes over a threshold of 2: one tx of 2, the third note stays.
plan = PlanSaplingConsolidation({ Values(3) }, policy, RngHigh);
ASSERT_EQ(plan.size(), 1u);
EXPECT_EQ(plan[0].notes.size(), 2u);
// 2 notes over a threshold of 1: merging both would leave none outside the round.
policy.threshold = 1;
plan = PlanSaplingConsolidation({ Values(2) }, policy, RngHigh);
EXPECT_TRUE(plan.empty());
}
TEST(SaplingConsolidationPlan, MaxTxsAndBatchSize) {
SaplingConsolidationPolicy policy;
policy.maxTxs = 0;
EXPECT_TRUE(PlanSaplingConsolidation({ Values(500) }, policy, RngHigh).empty());
policy.maxTxs = 7;
policy.batchSize = 2;
auto plan = PlanSaplingConsolidation({ Values(500) }, policy, RngLow);
ASSERT_EQ(plan.size(), 7u);
for (const auto& b : plan)
EXPECT_EQ(b.notes.size(), 2u);
// Out-of-range batch sizes are clamped, not trusted.
policy.batchSize = 1;
plan = PlanSaplingConsolidation({ Values(500) }, policy, RngHigh);
for (const auto& b : plan)
EXPECT_EQ(b.notes.size(), 2u);
policy.batchSize = 1000;
plan = PlanSaplingConsolidation({ Values(500) }, policy, RngHigh);
for (const auto& b : plan)
EXPECT_EQ(b.notes.size(), (size_t)MAX_CONSOLIDATION_BATCHSIZE);
}
TEST(SaplingConsolidationPlan, RespectsTxSizeCap) {
// The real cap fits the largest allowed batch with room to spare.
EXPECT_GE(SaplingConsolidationMaxInputs(MAX_TX_SIZE_AFTER_SAPLING), MAX_CONSOLIDATION_BATCHSIZE);
EXPECT_EQ(ClampSaplingConsolidationBatchSize(15), 15);
EXPECT_EQ(ClampSaplingConsolidationBatchSize(0), MIN_CONSOLIDATION_BATCHSIZE);
EXPECT_EQ(ClampSaplingConsolidationBatchSize(51), MAX_CONSOLIDATION_BATCHSIZE);
// A tx size that only fits 5 spends next to the 8 outputs caps every batch at 5.
const size_t outputs = 8 * OUTPUTDESCRIPTION_SIZE;
const size_t small = 1000 + outputs + 5 * SPENDDESCRIPTION_SIZE + SPENDDESCRIPTION_SIZE / 2;
EXPECT_EQ(SaplingConsolidationMaxInputs(small), 5);
EXPECT_EQ(ClampSaplingConsolidationBatchSize(15, small), 5);
SaplingConsolidationPolicy policy;
policy.maxTxSize = small;
auto plan = PlanSaplingConsolidation({ Values(100) }, policy, RngHigh);
ASSERT_EQ(plan.size(), 3u);
for (const auto& b : plan)
EXPECT_EQ(b.notes.size(), 5u);
// Too small for even two spends: nothing is planned.
policy.maxTxSize = 1000 + outputs + SPENDDESCRIPTION_SIZE;
EXPECT_TRUE(PlanSaplingConsolidation({ Values(100) }, policy, RngHigh).empty());
}
TEST(SaplingConsolidationPlan, RandomCountsStayInRange) {
SaplingConsolidationPolicy policy;
std::set<size_t> sizes;
for (int run = 0; run < 200; run++) {
auto plan = PlanSaplingConsolidation({ Values(300) }, policy, [](uint64_t n) { return GetRand(n); });
ASSERT_EQ(plan.size(), 3u);
for (const auto& b : plan) {
EXPECT_GE(b.notes.size(), 10u);
EXPECT_LE(b.notes.size(), 15u);
sizes.insert(b.notes.size());
}
}
EXPECT_GT(sizes.size(), 1u) << "the per-tx input count should vary";
}
TEST(SaplingConsolidationStats, RecordAccumulates) {
SaplingConsolidationStats stats;
EXPECT_FALSE(stats.hasLastRound);
EXPECT_EQ(stats.amountConsolidated, 0);
SaplingConsolidationRound first;
first.height = 100;
first.txids = { "aa", "bb", "cc" };
first.notesMerged = 40;
first.amountMerged = 4000000;
first.fees = 30000;
first.amountConsolidated = 4000000 - 30000;
stats.Record(first);
// A round that found nothing to do still counts as a round and becomes the last one.
SaplingConsolidationRound idle;
idle.height = 125;
stats.Record(idle);
SaplingConsolidationRound failed;
failed.height = 150;
failed.txids = { "dd" };
failed.notesMerged = 12;
failed.amountMerged = 1200000;
failed.fees = 10000;
failed.amountConsolidated = 1190000;
failed.skippedNotes = 2;
failed.error = "transaction was not accepted (CommitTransaction failed)";
stats.Record(failed);
EXPECT_EQ(stats.rounds, 3);
EXPECT_EQ(stats.txsCreated, 4);
EXPECT_EQ(stats.notesConsolidated, 52);
EXPECT_EQ(stats.amountConsolidated, 3970000 + 1190000);
ASSERT_TRUE(stats.hasLastRound);
EXPECT_EQ(stats.lastRound.height, 150);
EXPECT_EQ(stats.lastRound.txids.size(), 1u);
EXPECT_EQ(stats.lastRound.skippedNotes, 2);
EXPECT_EQ(stats.lastRound.error, failed.error);
}
namespace {
uint256 Root(int n) { return ArithToUint256(arith_uint256(n)); }
// Witness roots per note, for PlanSaplingConsolidationSpends; also counts its lookups.
struct Witnesses {
std::vector<std::vector<boost::optional<uint256>>> roots;
std::set<uint256> chainAnchors;
std::map<std::pair<size_t, size_t>, int> rootCalls;
std::map<uint256, int> anchorCalls;
SaplingConsolidationSpendPlan Plan(const std::vector<std::vector<CAmount>>& groups,
const SaplingConsolidationPolicy& policy, const uint256& tip) {
return PlanSaplingConsolidationSpends(groups, policy, RngHigh,
[this](size_t g, size_t i) { rootCalls[std::make_pair(g, i)]++; return roots[g][i]; },
[this](const uint256& r) { anchorCalls[r]++; return chainAnchors.count(r) > 0; },
tip);
}
};
void ExpectAllAt(const SaplingConsolidationSpendPlan& plan, const Witnesses& w) {
for (const auto& b : plan.batches) {
ASSERT_TRUE(plan.anchors.count(b.group));
for (size_t i : b.notes) {
ASSERT_TRUE(w.roots[b.group][i]);
EXPECT_EQ(*w.roots[b.group][i], plan.anchors.at(b.group)) << "note " << i << " of address " << b.group;
}
}
}
} // namespace
TEST(SaplingConsolidationSpends, HealthyWalletPlansAsBefore) {
SaplingConsolidationPolicy policy;
std::vector<std::vector<CAmount>> groups = { Values(60), Values(10), Values(40) };
Witnesses w;
w.chainAnchors = { Root(7) };
for (const auto& g : groups)
w.roots.push_back(std::vector<boost::optional<uint256>>(g.size(), Root(7)));
auto spends = w.Plan(groups, policy, Root(7));
auto plain = PlanSaplingConsolidation(groups, policy, RngHigh);
ASSERT_EQ(spends.batches.size(), plain.size());
for (size_t k = 0; k < plain.size(); k++) {
EXPECT_EQ(spends.batches[k].group, plain[k].group);
EXPECT_EQ(spends.batches[k].notes, plain[k].notes);
}
EXPECT_TRUE(spends.unusable.empty());
EXPECT_TRUE(spends.deferred.empty());
EXPECT_EQ(spends.anchors.size(), 2u) << "the address under the threshold gets no anchor";
EXPECT_EQ(spends.anchors.at(0), Root(7));
// Only planned notes are looked at, each once, and the one root once.
for (const auto& c : w.rootCalls)
EXPECT_EQ(c.second, 1);
EXPECT_EQ(w.rootCalls.size(), PlannedNotes(plain, 0) + PlannedNotes(plain, 2));
EXPECT_EQ(w.anchorCalls.size(), 1u);
EXPECT_EQ(w.anchorCalls[Root(7)], 1);
}
// The case seen on a real wallet: many notes of one address share a root the chain never had, and smallest-first
// planning picks mostly (here: only) those. They must not decide the anchor and take the healthy notes down.
TEST(SaplingConsolidationSpends, DesyncedMajorityDoesNotWin) {
SaplingConsolidationPolicy policy; // 25 / 15 / 3
std::vector<std::vector<CAmount>> groups = { Values(100) };
Witnesses w;
w.chainAnchors = { Root(7) };
w.roots.resize(1);
for (size_t i = 0; i < 100; i++)
w.roots[0].push_back(i < 50 ? Root(666) : Root(7)); // the 50 smallest are desynced
auto plan = w.Plan(groups, policy, Root(7));
ASSERT_EQ(plan.batches.size(), 3u);
EXPECT_EQ(plan.anchors.at(0), Root(7));
ExpectAllAt(plan, w);
for (const auto& b : plan.batches)
for (size_t i : b.notes)
EXPECT_GE(i, 50u);
EXPECT_EQ(plan.unusable.size(), 50u);
EXPECT_TRUE(plan.deferred.empty());
EXPECT_EQ(w.anchorCalls[Root(666)], 1) << "a root is checked against the chain once";
for (const auto& c : w.rootCalls)
EXPECT_EQ(c.second, 1);
// The same when the tip's root is not among them: the chain anchor wins, not the majority.
Witnesses old = w;
old.chainAnchors = { Root(5) };
for (size_t i = 50; i < 100; i++)
old.roots[0][i] = Root(5);
old.rootCalls.clear();
old.anchorCalls.clear();
auto plan2 = old.Plan(groups, policy, Root(7));
ASSERT_EQ(plan2.batches.size(), 3u);
EXPECT_EQ(plan2.anchors.at(0), Root(5));
ExpectAllAt(plan2, old);
}
TEST(SaplingConsolidationSpends, MissingWitnessesAreSkipped) {
SaplingConsolidationPolicy policy;
policy.maxTxs = 1;
std::vector<std::vector<CAmount>> groups = { Values(40) };
Witnesses w;
w.chainAnchors = { Root(7) };
w.roots.assign(1, std::vector<boost::optional<uint256>>(40, Root(7)));
w.roots[0][0] = boost::none;
w.roots[0][3] = boost::none;
auto plan = w.Plan(groups, policy, Root(7));
ASSERT_EQ(plan.batches.size(), 1u);
EXPECT_EQ(plan.batches[0].notes.size(), 15u) << "the dropped notes are replaced by the next smallest";
ExpectAllAt(plan, w);
std::set<std::pair<size_t, size_t>> unusable(plan.unusable.begin(), plan.unusable.end());
EXPECT_EQ(unusable, (std::set<std::pair<size_t, size_t>>{ {0, 0}, {0, 3} }));
}
// Witnesses at a different, real anchor (a rebuild still under way) are deferred, not called unusable.
TEST(SaplingConsolidationSpends, OtherChainAnchorIsDeferred) {
SaplingConsolidationPolicy policy;
policy.maxTxs = 1;
std::vector<std::vector<CAmount>> groups = { Values(40) };
Witnesses w;
w.chainAnchors = { Root(7), Root(6) };
w.roots.assign(1, std::vector<boost::optional<uint256>>(40, Root(7)));
w.roots[0][1] = Root(6);
w.roots[0][2] = Root(6);
auto plan = w.Plan(groups, policy, Root(7));
ASSERT_EQ(plan.batches.size(), 1u);
EXPECT_EQ(plan.anchors.at(0), Root(7));
ExpectAllAt(plan, w);
EXPECT_TRUE(plan.unusable.empty());
EXPECT_EQ(plan.deferred.size(), 2u);
}
// Leaving notes out can bring an address down to the threshold; then it is not consolidated, and needs no anchor.
TEST(SaplingConsolidationSpends, ThresholdCountsUsableNotes) {
SaplingConsolidationPolicy policy;
std::vector<std::vector<CAmount>> groups = { Values(26) };
Witnesses w;
w.chainAnchors = { Root(7) };
w.roots.assign(1, std::vector<boost::optional<uint256>>(26, Root(7)));
w.roots[0][0] = boost::none;
auto plan = w.Plan(groups, policy, Root(7));
EXPECT_TRUE(plan.batches.empty());
EXPECT_TRUE(plan.anchors.empty());
EXPECT_EQ(plan.unusable.size(), 1u);
// Nothing at a chain anchor at all: nothing planned, every looked-at note reported.
Witnesses bad;
bad.roots.assign(1, std::vector<boost::optional<uint256>>(26, Root(666)));
auto none = bad.Plan(groups, policy, Root(7));
EXPECT_TRUE(none.batches.empty());
EXPECT_EQ(none.unusable.size(), 25u) << "the first plan took 25 of the 26, then 1 was too few to plan";
}
TEST(SaplingConsolidationFee, NotesWorthTheFeeGoFeeFree) {
EXPECT_EQ(SaplingConsolidationTxFee(10000, 10000), 0);
EXPECT_EQ(SaplingConsolidationTxFee(9999, 10000), 0);
EXPECT_EQ(SaplingConsolidationTxFee(10001, 10000), 10000);
EXPECT_EQ(SaplingConsolidationTxFee(5000000, 10000), 10000);
}
+78
View File
@@ -0,0 +1,78 @@
// Copyright (c) 2016-2024 The Hush developers
// Distributed under the GPLv3 software license, see the accompanying
// file COPYING or https://www.gnu.org/licenses/gpl-3.0.en.html
#include <gtest/gtest.h>
#include <boost/filesystem.hpp>
#include "wallet/db.h"
namespace {
// A fresh environment in a temp dir with one committed record in "wallet.dat", so database/ holds a log file.
class WalletDbEnv : public ::testing::Test {
protected:
boost::filesystem::path dir;
CDBEnv env;
void SetUp() override {
dir = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path("dbenv-%%%%%%%%");
boost::filesystem::create_directories(dir);
ASSERT_TRUE(env.Open(dir));
Db db(env.dbenv, DB_CXX_NO_EXCEPTIONS);
ASSERT_EQ(0, db.open(NULL, "wallet.dat", "main", DB_BTREE, DB_CREATE | DB_AUTO_COMMIT, 0));
char k[] = "key", v[] = "value";
Dbt key(k, sizeof k), value(v, sizeof v);
ASSERT_EQ(0, db.put(NULL, &key, &value, 0));
ASSERT_EQ(0, db.close(0));
ASSERT_TRUE(boost::filesystem::exists(Log()));
}
void TearDown() override {
env.Close();
boost::system::error_code ec;
boost::filesystem::remove_all(dir, ec);
}
boost::filesystem::path Log() const { return dir / "database" / "log.0000000001"; }
};
} // namespace
TEST_F(WalletDbEnv, CleanShutdownRemovesTheLogs) {
env.Flush(true);
EXPECT_FALSE(boost::filesystem::exists(dir / "database"));
}
// BDB0060 PANIC (a page write failed, e.g. through an fd closed behind BDB's back): the logs may hold committed
// changes wallet.dat never got, and the next start's DB_RECOVER needs them.
TEST_F(WalletDbEnv, PanickedEnvironmentKeepsTheLogs) {
ASSERT_EQ(0, env.dbenv->set_flags(DB_PANIC_ENVIRONMENT, 1));
env.Flush(true);
EXPECT_TRUE(boost::filesystem::exists(Log()));
}
TEST_F(WalletDbEnv, FailedCheckpointKeepsTheLogs) {
env.CheckpointLSN("no-such-file.dat"); // lsn_reset fails
env.Flush(true);
EXPECT_TRUE(boost::filesystem::exists(Log()));
}
// The shutdown wallet save asks before writing: a failed flush or a panicked environment means the logs are what
// recovery needs, and a large write into it would fail or make things worse.
TEST_F(WalletDbEnv, HealthyUntilAFlushFailsOrTheEnvironmentPanics) {
EXPECT_TRUE(env.IsHealthy());
env.Flush(false);
EXPECT_TRUE(env.IsHealthy());
ASSERT_EQ(0, env.dbenv->set_flags(DB_PANIC_ENVIRONMENT, 1));
EXPECT_FALSE(env.IsHealthy());
}
TEST_F(WalletDbEnv, UnhealthyAfterAFailedCheckpoint) {
env.CheckpointLSN("no-such-file.dat"); // lsn_reset fails
EXPECT_FALSE(env.IsHealthy());
}
TEST(WalletDbEnvNotOpen, NotOpenIsHealthy) {
CDBEnv env;
EXPECT_TRUE(env.IsHealthy());
}
+816
View File
@@ -0,0 +1,816 @@
// Copyright (c) 2016-2024 The Hush developers
// Distributed under the GPLv3 software license, see the accompanying
// file COPYING or https://www.gnu.org/licenses/gpl-3.0.en.html
#include <gtest/gtest.h>
#include <deque>
#include <utf8.h>
#include "chain.h"
#include "chainparams.h"
#include "coins.h"
#include "init.h"
#include "key_io.h"
#include "main.h"
#include "primitives/block.h"
#include "primitives/transaction.h"
#include "random.h"
#include "rpc/server.h"
#include "script/standard.h"
#include "utilmoneystr.h"
#include "wallet/wallet.h"
#include "wallet/rpchushwallet.h"
#include "zcash/Address.hpp"
#include "zcash/Note.hpp"
#include "zcash/NoteEncryption.hpp"
#include "zcash/zip32.h"
using namespace std;
using namespace libzcash;
// The history-RPC helpers (src/wallet/rpchushwallet.cpp) as of 69bb035e7, verbatim apart from the Legacy_
// prefix and static linkage: the reference the optimized helpers must reproduce byte for byte.
static void Legacy_zsTxSpendsToJSON(const CWalletTx& wtx, UniValue& spends, CAmount& totalSpends, CAmount& filteredSpends, const std::string& strAddress, bool filterByAddress) {
LOCK2(cs_main, pwalletMain->cs_wallet);
//Used to identify incomplete key sets
int vinCount = 0;
int vinSpendCount = 0;
int shieldedSpendCount = 0;
int shieldedSpendsSpentCount = 0;
//Check address
bool isTAddress = false;
bool isZsAddress = false;
CTxDestination tAddress = DecodeDestination(strAddress);
auto zAddress = DecodePaymentAddress(strAddress);
SaplingPaymentAddress zsAddress;
if (filterByAddress) {
if (IsValidDestination(tAddress))
isTAddress = true;
if (IsValidPaymentAddress(zAddress)) {
if (boost::get<libzcash::SaplingPaymentAddress>(&zAddress) != nullptr) {
zsAddress = boost::get<libzcash::SaplingPaymentAddress>(zAddress);
isZsAddress = true;
}
}
}
// Transparent Inputs belonging to the wallet
UniValue tSpends(UniValue::VARR);
if (isTAddress || !filterByAddress) {
for (int i = 0; i < wtx.vin.size(); i++) {
vinCount++;
const CTxIn& txin = wtx.vin[i];
UniValue obj(UniValue::VOBJ);
CTxDestination address;
const CWalletTx* parent = pwalletMain->GetWalletTx(txin.prevout.hash);
if (parent != NULL) {
const CTxOut& parentOut = parent->vout[txin.prevout.n];
ExtractDestination(parentOut.scriptPubKey, address);
if(IsMine(*pwalletMain, address)){
vinSpendCount++;
totalSpends += CAmount(-parentOut.nValue);
obj.push_back(Pair("address",EncodeDestination(address)));
obj.push_back(Pair("scriptPubKey",HexStr(parentOut.scriptPubKey.begin(), parentOut.scriptPubKey.end())));
obj.push_back(Pair("amount",ValueFromAmount(-parentOut.nValue)));
obj.push_back(Pair("spendTxid",parent->GetHash().ToString()));
obj.push_back(Pair("spendVout",(int)txin.prevout.n));
CTxDestination filterAddress = DecodeDestination(strAddress);
if (address == tAddress || !filterByAddress) {
filteredSpends += CAmount(-parentOut.nValue);
tSpends.push_back(obj);
}
}
}
}
}
spends.push_back(Pair("transparentSpends",tSpends));
// Sapling Inputs belonging to the wallet
UniValue zsSpends(UniValue::VARR);
if (isZsAddress || !filterByAddress) {
for (int i = 0; i < wtx.vShieldedSpend.size(); i++) {
shieldedSpendCount++;
const SpendDescription& spendDesc = wtx.vShieldedSpend[i];
UniValue obj(UniValue::VOBJ);
SaplingOutPoint op = pwalletMain->mapSaplingNullifiersToNotes[spendDesc.nullifier];
if (pwalletMain->IsSaplingNullifierFromMe(spendDesc.nullifier)) {
const CWalletTx* parent = pwalletMain->GetWalletTx(pwalletMain->mapSaplingNullifiersToNotes[spendDesc.nullifier].hash);
const OutputDescription& output = parent->vShieldedOutput[op.n];
auto nd = pwalletMain->mapWallet[pwalletMain->mapSaplingNullifiersToNotes[spendDesc.nullifier].hash].mapSaplingNoteData[op];
auto pt = libzcash::SaplingNotePlaintext::decrypt(output.encCiphertext,nd.ivk,output.ephemeralKey,output.cm);
if (pt) {
auto note = pt.get();
auto pa = nd.ivk.address(note.d);
auto address = pa.get();
shieldedSpendsSpentCount++;
totalSpends += CAmount(-note.value());
obj.push_back(Pair("address",EncodePaymentAddress(address)));
obj.push_back(Pair("amount", ValueFromAmount(CAmount(-note.value()))));
obj.push_back(Pair("spendTxid",parent->GetHash().ToString()));
obj.push_back(Pair("spendshieldedOutputIndex",(int)op.n));
if (address == zsAddress || !filterByAddress) {
filteredSpends += CAmount(-note.value());
zsSpends.push_back(obj);
}
}
}
}
}
spends.push_back(Pair("saplingSpends",zsSpends));
spends.push_back(Pair("totalSpends",ValueFromAmount(filteredSpends)));
if (!filterByAddress) {
if (filteredSpends != 0 && (vinCount != vinSpendCount || shieldedSpendCount != shieldedSpendsSpentCount)) {
spends.push_back(Pair("missingSpendingKeys", true));
spends.push_back(Pair("vinCount", vinCount));
spends.push_back(Pair("vinSpendCount", vinSpendCount));
spends.push_back(Pair("shieldedSpendCount", shieldedSpendCount));
spends.push_back(Pair("shieldedSpendsSpentCount", shieldedSpendsSpentCount));
} else {
spends.push_back(Pair("missingSpendingKeys", false));
}
}
}
static void Legacy_zsTxReceivedToJSON(const CWalletTx& wtx, UniValue& received, CAmount& totalReceived, const std::string& strAddress, bool filterByAddress) {
if(fZdebug)
fprintf(stderr,"%s: txid=%s\n", __func__, wtx.GetHash().ToString().c_str() );
LOCK2(cs_main, pwalletMain->cs_wallet);
//Check address
bool isTAddress = false;
bool isZsAddress = false;
CTxDestination tAddress = DecodeDestination(strAddress);
auto zAddress = DecodePaymentAddress(strAddress);
SaplingPaymentAddress zsAddress;
if (filterByAddress) {
if (IsValidDestination(tAddress))
isTAddress = true;
if (IsValidPaymentAddress(zAddress)) {
if (boost::get<libzcash::SaplingPaymentAddress>(&zAddress) != nullptr) {
zsAddress = boost::get<libzcash::SaplingPaymentAddress>(zAddress);
isZsAddress = true;
}
}
}
//Transparent Received txos belonging to the wallet
UniValue tReceived(UniValue::VARR);
if (isTAddress || !filterByAddress) {
for (int i = 0; i < wtx.vout.size(); i++) {
const CTxOut& txout = wtx.vout[i];
UniValue obj(UniValue::VOBJ);
CTxDestination address;
ExtractDestination(txout.scriptPubKey, address);
if(IsMine(*pwalletMain, address)){
obj.push_back(Pair("address",EncodeDestination(address)));
obj.push_back(Pair("scriptPubKey",HexStr(txout.scriptPubKey.begin(), txout.scriptPubKey.end())));
obj.push_back(Pair("amount",ValueFromAmount(txout.nValue)));
obj.push_back(Pair("vout", i));
if (address == tAddress || !filterByAddress) {
totalReceived += CAmount(txout.nValue);
tReceived.push_back(obj);
}
}
}
}
received.push_back(Pair("transparentReceived",tReceived));
//Sapling Sends belonging to the wallet
UniValue zsReceived(UniValue::VARR);
if (isZsAddress || !filterByAddress) {
for (int i = 0; i < wtx.vShieldedOutput.size(); i++) {
const OutputDescription& outputDesc = wtx.vShieldedOutput[i];
UniValue obj(UniValue::VOBJ);
bool changeTx = false;
//Decrypt sapling incoming commitments using IVK
std::set<libzcash::SaplingPaymentAddress> addresses;
pwalletMain->GetSaplingPaymentAddresses(addresses);
for (auto addr : addresses) {
libzcash::SaplingExtendedSpendingKey extsk;
if (pwalletMain->GetSaplingExtendedSpendingKey(addr, extsk)) {
auto pt = libzcash::SaplingNotePlaintext::decrypt(
outputDesc.encCiphertext, extsk.expsk.full_viewing_key().in_viewing_key(), outputDesc.ephemeralKey, outputDesc.cm);
if (pt) {
auto note = pt.get();
auto pt_unwrapped = pt.get();
auto memo = pt_unwrapped.memo();
obj.push_back(Pair("address",EncodePaymentAddress(addr)));
obj.push_back(Pair("amount", ValueFromAmount(CAmount(note.value()))));
obj.push_back(Pair("memo", HexStr(memo)));
if (memo[0] <= 0xf4) {
auto end = std::find_if(memo.rbegin(), memo.rend(), [](unsigned char v) { return v != 0; });
std::string memoStr(memo.begin(), end.base());
if (utf8::is_valid(memoStr)) {
obj.push_back(Pair("memoStr", memoStr));
}
}
obj.push_back(Pair("shieldedOutputIndex",i));
//Check Change Status
if (wtx.vShieldedSpend.size()!=0) {
std::set<std::pair<PaymentAddress, uint256>> nullifierSet;
nullifierSet = pwalletMain->GetNullifiersForAddresses({addr});
BOOST_FOREACH(const SpendDescription& spendDesc, wtx.vShieldedSpend) {
if (nullifierSet.count(std::make_pair(addr, spendDesc.nullifier))) {
changeTx = true;
}
}
}
obj.push_back(Pair("change",changeTx));
if (addr == zsAddress || !filterByAddress) {
totalReceived += CAmount(note.value());
zsReceived.push_back(obj);
}
}
}
}
}
}
received.push_back(Pair("saplingReceived",zsReceived));
received.push_back(Pair("totalReceived",ValueFromAmount(totalReceived)));
}
static void Legacy_zsTxSendsToJSON(const CWalletTx& wtx, UniValue& sends, CAmount& totalSends, const std::string& strAddress, bool filterByAddress) {
LOCK2(cs_main, pwalletMain->cs_wallet);
//Used to identify incomplete key sets
int shieldedOutputCount = 0;
int shieldedOutputDecryptedCount = 0;
//Check address
bool isTAddress = false;
bool isZsAddress = false;
CTxDestination tAddress = DecodeDestination(strAddress);
auto zAddress = DecodePaymentAddress(strAddress);
SaplingPaymentAddress zsAddress;
if (filterByAddress) {
if (IsValidDestination(tAddress))
isTAddress = true;
if (IsValidPaymentAddress(zAddress)) {
if (boost::get<libzcash::SaplingPaymentAddress>(&zAddress) != nullptr) {
zsAddress = boost::get<libzcash::SaplingPaymentAddress>(zAddress);
isZsAddress = true;
}
}
}
//All Transparent Sends in the transaction
UniValue tSends(UniValue::VARR);
if (isTAddress || !filterByAddress) {
for (int i = 0; i < wtx.vout.size(); i++) {
const CTxOut& txout = wtx.vout[i];
UniValue obj(UniValue::VOBJ);
CTxDestination address;
ExtractDestination(txout.scriptPubKey, address);
obj.push_back(Pair("address",EncodeDestination(address)));
obj.push_back(Pair("scriptPubKey",HexStr(txout.scriptPubKey.begin(), txout.scriptPubKey.end())));
obj.push_back(Pair("amount",ValueFromAmount(-txout.nValue)));
obj.push_back(Pair("vout", i));
if (address == tAddress || !filterByAddress) {
totalSends += CAmount(-txout.nValue);
tSends.push_back(obj);
}
}
}
sends.push_back(Pair("transparentSends",tSends));
//All Shielded Sends in the transaction
UniValue zsSends(UniValue::VARR);
if (isZsAddress || !filterByAddress) {
for (int i = 0; i < wtx.vShieldedOutput.size(); i++) {
const OutputDescription& outputDesc = wtx.vShieldedOutput[i];
shieldedOutputCount++;
UniValue obj(UniValue::VOBJ);
bool changeTx = false;
//Decrypt sapling outgoing t to z transaction using HDseed
if (wtx.vShieldedSpend.size()==0) {
HDSeed seed;
if (pwalletMain->GetHDSeedForDerivation(seed)) {
auto opt = libzcash::SaplingOutgoingPlaintext::decrypt(
outputDesc.outCiphertext,ovkForShieldingFromTaddr(seed),outputDesc.cv,outputDesc.cm,outputDesc.ephemeralKey);
if (opt) {
auto opt_unwrapped = opt.get();
auto pt = libzcash::SaplingNotePlaintext::decrypt(
outputDesc.encCiphertext,outputDesc.ephemeralKey,opt_unwrapped.esk,opt_unwrapped.pk_d,outputDesc.cm);
if (pt) {
shieldedOutputDecryptedCount++;
auto pt_unwrapped = pt.get();
libzcash::SaplingPaymentAddress sentAddr(pt_unwrapped.d, opt_unwrapped.pk_d);
obj.push_back(Pair("address",EncodePaymentAddress(sentAddr)));
obj.push_back(Pair("amount", ValueFromAmount(CAmount(pt_unwrapped.value()))));
obj.push_back(Pair("shieldedOutputIndex",i));
obj.push_back(Pair("change",false));
if (sentAddr == zsAddress || !filterByAddress) {
totalSends += CAmount(-pt_unwrapped.value());
zsSends.push_back(obj);
}
}
}
}
//attempt Decryption of Outgoing Sapling using wallet extended spending keys
} else {
std::set<libzcash::SaplingPaymentAddress> addresses;
pwalletMain->GetSaplingPaymentAddresses(addresses);
for (auto addr : addresses) {
libzcash::SaplingExtendedSpendingKey extsk;
if (pwalletMain->GetSaplingExtendedSpendingKey(addr, extsk)) {
auto opt = libzcash::SaplingOutgoingPlaintext::decrypt(
outputDesc.outCiphertext,extsk.expsk.full_viewing_key().ovk,outputDesc.cv,outputDesc.cm,outputDesc.ephemeralKey);
if (opt) {
auto opt_unwrapped = opt.get();
auto pt = libzcash::SaplingNotePlaintext::decrypt(
outputDesc.encCiphertext,outputDesc.ephemeralKey,opt_unwrapped.esk,opt_unwrapped.pk_d,outputDesc.cm);
if (pt) {
auto pt_unwrapped = pt.get();
auto memo = pt_unwrapped.memo();
shieldedOutputDecryptedCount++;
libzcash::SaplingPaymentAddress sentAddr(pt_unwrapped.d, opt_unwrapped.pk_d);
obj.push_back(Pair("address",EncodePaymentAddress(sentAddr)));
obj.push_back(Pair("amount", ValueFromAmount(CAmount(-pt_unwrapped.value()))));
obj.push_back(Pair("memo", HexStr(memo)));
if (memo[0] <= 0xf4) {
auto end = std::find_if(memo.rbegin(), memo.rend(), [](unsigned char v) { return v != 0; });
std::string memoStr(memo.begin(), end.base());
if (utf8::is_valid(memoStr)) {
obj.push_back(Pair("memoStr", memoStr));
}
}
obj.push_back(Pair("shieldedOutputIndex",i));
//Check Change Status
if (wtx.vShieldedSpend.size()!=0) {
std::set<std::pair<PaymentAddress, uint256>> nullifierSet;
nullifierSet = pwalletMain->GetNullifiersForAddresses({sentAddr});
BOOST_FOREACH(const SpendDescription& spendDesc, wtx.vShieldedSpend) {
if (nullifierSet.count(std::make_pair(sentAddr, spendDesc.nullifier))) {
changeTx = true;
}
}
}
obj.push_back(Pair("change",changeTx));
if (sentAddr == zsAddress || !filterByAddress) {
totalSends += CAmount(-pt_unwrapped.value());
zsSends.push_back(obj);
}
}
}
}
}
}
}
}
sends.push_back(Pair("saplingSends",zsSends));
if (shieldedOutputCount != shieldedOutputDecryptedCount) {
sends.push_back(Pair("missingSaplingOVK", true));
} else {
sends.push_back(Pair("missingSaplingOVK", false));
}
sends.push_back(Pair("totalSends",ValueFromAmount(totalSends)));
}
static void Legacy_zsWalletTxJSON(const CWalletTx& wtx, UniValue& ret, const std::string strAddress, bool fBool, const int returnType) {
LOCK2(cs_main, pwalletMain->cs_wallet);
//Track total wallet spend and received
CAmount totalSpends = 0;
CAmount filteredSpends = 0;
CAmount totalReceived = 0;
CAmount totalSends = 0;
//Various Univalue to be added to the final transaction
UniValue spends(UniValue::VOBJ);
UniValue received(UniValue::VOBJ);
UniValue sends(UniValue::VOBJ);
UniValue tx(UniValue::VOBJ);
//Begin Compiling the Decrypted Transaction
tx.push_back(Pair("txid", wtx.GetHash().ToString()));
if(fZdebug)
fprintf(stderr,"%s: txid=%s\n", __func__, wtx.GetHash().ToString().c_str() );
if (wtx.IsCoinBase())
{
tx.push_back(Pair("coinbase", true));
if (wtx.GetDepthInMainChain() < 1)
tx.push_back(Pair("category", "orphan"));
else if (wtx.GetBlocksToMaturity() > 0)
tx.push_back(Pair("category", "immature"));
else
tx.push_back(Pair("category", "generate"));
} else {
tx.push_back(Pair("coinbase", false));
tx.push_back(Pair("category", "standard"));
}
tx.push_back(Pair("blockhash", wtx.hashBlock.GetHex()));
tx.push_back(Pair("blockindex", wtx.nIndex));
int confirms = wtx.GetDepthInMainChain();
if(confirms > 0)
{
tx.push_back(Pair("blocktime", mapBlockIndex[wtx.hashBlock]->GetBlockTime()));
} else {
tx.push_back(Pair("blocktime", 0));
}
tx.push_back(Pair("expiryheight", (int64_t)wtx.nExpiryHeight));
tx.push_back(Pair("confirmations", confirms));
tx.push_back(Pair("time", wtx.GetTxTime()));
tx.push_back(Pair("size", static_cast<uint64_t>(GetSerializeSize(static_cast<CTransaction>(wtx), SER_NETWORK, PROTOCOL_VERSION))));
//Wallet Conflicts
UniValue conflicts(UniValue::VARR);
BOOST_FOREACH(const uint256& conflict, wtx.GetConflicts())
conflicts.push_back(conflict.GetHex());
tx.push_back(Pair("walletconflicts", conflicts));
// Return Type used to determine what is included in the transaction
// 0 Spends, Received and spends
// 1 Sends
// 2 Received
// 3 Spends
// TODO - Setup Enum, maybe...
// Add Spends retrieved earlier
if (returnType != 2) {
Legacy_zsTxSpendsToJSON(wtx, spends, totalSpends, filteredSpends, strAddress, fBool);
if ((!fBool || filteredSpends != 0) && (returnType == 0 || returnType == 1)) {
tx.push_back(Pair("spends",spends));
}
}
// Get Received
if (returnType == 0 || returnType == 2) {
Legacy_zsTxReceivedToJSON(wtx, received, totalReceived, strAddress, fBool);
if (!fBool || totalReceived != 0) {
tx.push_back(Pair("received",received));
}
}
// Get Sends
if (returnType == 0 || returnType == 3) {
//Only include sends if there are spends that belong to the wallet.
if (totalSpends != 0 || fBool) {
Legacy_zsTxSendsToJSON(wtx, sends, totalSends, strAddress, fBool);
}
if (!fBool || totalSends != 0) {
tx.push_back(Pair("sends",sends));
}
}
if ((returnType == 0 && (!fBool || filteredSpends != 0 || totalReceived != 0 || totalSends != 0))
|| (returnType == 1 && (!fBool || filteredSpends != 0))
|| (returnType == 2 && (!fBool || totalReceived != 0))
|| (returnType == 3 && (!fBool || totalSends != 0))) {
ret.push_back(tx);
}
}
namespace {
std::array<unsigned char, HUSH_MEMO_SIZE> Memo(const std::string& text)
{
std::array<unsigned char, HUSH_MEMO_SIZE> memo;
memo.fill(0);
if (text == "empty") // the "no memo" encoding: 0xF6 then zeros
memo[0] = 0xF6;
else if (text == "binary") // starts below 0xF5 but isn't UTF-8
memo[0] = 0xC3, memo[1] = 0x28;
else
memcpy(memo.data(), text.data(), text.size());
return memo;
}
// A real encrypted Sapling output, and when ovk is given, an outCiphertext the sender can decrypt with it
// (the wallet never checks proofs or value commitments).
OutputDescription Output(const SaplingPaymentAddress& to, uint64_t value, const std::string& memo,
const boost::optional<uint256>& ovk = boost::none)
{
SaplingNote note(to, value);
auto enc = SaplingNotePlaintext(note, Memo(memo)).encrypt(note.pk_d);
assert(static_cast<bool>(enc));
OutputDescription od;
od.cv = GetRandHash();
od.cm = note.cm().get();
od.ephemeralKey = enc->second.get_epk();
od.encCiphertext = enc->first;
if (ovk) {
SaplingOutgoingPlaintext out(note.pk_d, enc->second.get_esk());
od.outCiphertext = out.encrypt(*ovk, od.cv, od.cm, enc->second);
} else {
GetRandBytes(od.outCiphertext.begin(), od.outCiphertext.size());
}
return od;
}
CTransaction SaplingTx(const std::vector<OutputDescription>& outputs, const std::vector<uint256>& spentNullifiers,
const std::vector<COutPoint>& vin = {})
{
CMutableTransaction mtx;
mtx.fOverwintered = true;
mtx.nVersion = SAPLING_TX_VERSION;
mtx.nVersionGroupId = SAPLING_VERSION_GROUP_ID;
mtx.vShieldedOutput = outputs;
for (const uint256& nf : spentNullifiers) {
SpendDescription sd;
sd.nullifier = nf;
mtx.vShieldedSpend.push_back(sd);
}
for (const COutPoint& prev : vin)
mtx.vin.push_back(CTxIn(prev));
return CTransaction(mtx);
}
SaplingExtendedSpendingKey Key(uint32_t account)
{
std::vector<unsigned char, secure_allocator<unsigned char>> raw(32, 0x6b);
HDSeed seed(raw);
return SaplingExtendedSpendingKey::Master(seed).Derive(account | ZIP32_HARDENED_KEY_LIMIT);
}
}
// A wallet whose txs exercise every branch of the history helpers: notes received on default and diversified
// addresses, by a viewing-key-only address and by a key imported afterwards; z->z sends with change and memos;
// a t->z shielding send; spends of our notes and of someone else's. pwalletMain points at it during the test.
class HistoryWallet : public CWallet {
public:
bool EncryptKeys(CKeyingMaterial& vMasterKeyIn) { return CCryptoKeyStore::EncryptKeys(vMasterKeyIn); }
bool Unlock(const CKeyingMaterial& vMasterKeyIn) { return CCryptoKeyStore::Unlock(vMasterKeyIn); }
};
class WalletHistory : public ::testing::Test {
protected:
HistoryWallet wallet;
CWallet* savedWallet = nullptr;
SaplingPaymentAddress paA, paA2, paB, paC, paD, paF;
CTxDestination taddr;
std::map<uint256, int> depthOf;
std::vector<uint256> txids;
CCoinsView coinsBase;
CCoinsViewCache coins{&coinsBase};
CCoinsViewCache* savedCoinsTip = nullptr;
CBlockIndex* savedTip = nullptr;
std::deque<CBlock> blocks;
std::deque<CBlockIndex> index;
std::vector<uint256> insertedBlocks;
void SetUp() override {
SelectParams(CBaseChainParams::MAIN);
savedWallet = pwalletMain;
pwalletMain = &wallet;
savedCoinsTip = pcoinsTip;
pcoinsTip = &coins;
LOCK2(cs_main, wallet.cs_wallet);
savedTip = chainActive.Tip();
std::vector<unsigned char, secure_allocator<unsigned char>> raw(32, 0x2d);
ASSERT_TRUE(wallet.SetHDSeed(HDSeed(raw)));
HDSeed seed;
ASSERT_TRUE(wallet.GetHDSeedForDerivation(seed));
const uint256 seedOvk = ovkForShieldingFromTaddr(seed);
auto skA = Key(0), skB = Key(1), skC = Key(2), skD = Key(3), skF = Key(9);
paA = skA.DefaultAddress();
diversifier_index_t j;
j.begin()[0] = 50;
paA2 = skA.ToXFVK().Address(j)->second;
paB = skB.DefaultAddress();
paC = skC.DefaultAddress();
paD = skD.DefaultAddress();
paF = skF.DefaultAddress();
const uint256 ovkA = skA.expsk.full_viewing_key().ovk, ovkC = skC.expsk.full_viewing_key().ovk;
ASSERT_TRUE(wallet.AddSaplingZKey(skA, paA));
ASSERT_TRUE(wallet.AddSaplingIncomingViewingKey(skA.expsk.full_viewing_key().in_viewing_key(), paA2));
ASSERT_TRUE(wallet.AddSaplingIncomingViewingKey(skB.expsk.full_viewing_key().in_viewing_key(), paB));
ASSERT_TRUE(wallet.AddSaplingZKey(skC, paC));
CKey tkey;
tkey.MakeNewKey(true);
ASSERT_TRUE(wallet.AddKeyPubKey(tkey, tkey.GetPubKey()));
taddr = tkey.GetPubKey().GetID();
const uint256 nfA = uint256S("a1"), nfA2 = uint256S("a2"), nfC = uint256S("c1"), nfForeign = uint256S("ff");
// T0: transparent funds to our taddr.
CMutableTransaction t0;
t0.vin.push_back(CTxIn(COutPoint(GetRandHash(), 0)));
t0.vout.push_back(CTxOut(10 * COIN, GetScriptForDestination(taddr)));
AddTx(CTransaction(t0), 30);
// T1: received by A, A2, B (viewing key only), C and someone else; no spends.
uint256 t1 = AddTx(SaplingTx({Output(paA, 1000, "for A"), Output(paA2, 2000, "empty"), Output(paB, 3000, "for B"),
Output(paC, 4000, "binary"), Output(paF, 5000, "not ours")}, {}),
25, {{0, nfA}, {1, nfA2}, {3, nfC}});
(void)t1;
// T2: A sends to F with change back to A, spending A's note: outCiphertexts under A's ovk.
AddTx(SaplingTx({Output(paF, 600, "payment", ovkA), Output(paA, 399, "change", ovkA)}, {nfA}), 20);
// T3: t->z shielding of T0's output to A, outCiphertext under the seed's shielding ovk.
AddTx(SaplingTx({Output(paA, 9 * COIN, "empty", seedOvk)}, {}, {COutPoint(txids[0], 0)}), 15);
// T4: C spends its note: to A2 (another of our keys) and change to C.
AddTx(SaplingTx({Output(paA2, 1500, "to a diversified A", ovkC), Output(paC, 2499, "binary", ovkC)}, {nfC}), 10);
// T5: someone else's spend paying A.
AddTx(SaplingTx({Output(paA, 777, "from a stranger")}, {nfForeign}), 8);
// T6: received by D before D's key is in the wallet (an import without rescan), then mined.
AddTx(SaplingTx({Output(paD, 4242, "for D, found later")}, {}), 5);
// T8: spends one of our notes and one of someone else's (a coinjoin-like tx): missingSpendingKeys.
AddTx(SaplingTx({Output(paF, 100, "mixed", ovkA)}, {nfA, uint256S("fe")}), 3);
// T9: spends A2's note, but its one output's outCiphertext is under nobody's ovk we know: missingSaplingOVK.
AddTx(SaplingTx({Output(paF, 50, "unreadable send")}, {nfA2}), 2);
// T7: spends A2's note (A and A2 share A's key); never mined and not in the mempool (depth -1).
AddTx(SaplingTx({Output(paF, 2900, "", ovkA)}, {nfA2}), 0);
ASSERT_TRUE(wallet.AddSaplingZKey(skD, paD));
Mine();
}
void TearDown() override {
LOCK(cs_main);
chainActive.SetTip(savedTip);
for (const uint256& h : insertedBlocks)
mapBlockIndex.erase(h);
pcoinsTip = savedCoinsTip;
pwalletMain = savedWallet;
}
uint256 AddTx(const CTransaction& tx, int depth, const std::map<uint32_t, uint256>& nullifiers = {}) {
CWalletTx wtx(&wallet, tx);
mapSaplingNoteData_t found = wallet.FindMySaplingNotes(tx).first;
for (const auto& nf : nullifiers)
found.at(SaplingOutPoint(tx.GetHash(), nf.first)).nullifier = nf.second;
wtx.SetSaplingNoteData(found);
EXPECT_TRUE(wallet.AddToWallet(wtx, true, nullptr));
if (depth > 0)
depthOf[tx.GetHash()] = depth;
txids.push_back(tx.GetHash());
return tx.GetHash();
}
void Mine() {
const int tip = 40;
for (int h = 0; h <= tip; h++) {
blocks.emplace_back();
CBlock& block = blocks.back();
block.nTime = 1700000000 + 36 * h;
block.nNonce = uint256S(strprintf("%x", 0x900 + h));
if (h > 0)
block.hashPrevBlock = blocks[h - 1].GetHash();
for (const auto& d : depthOf)
if (tip - d.second + 1 == h)
block.vtx.push_back(wallet.mapWallet.at(d.first));
block.hashMerkleRoot = block.BuildMerkleTree();
index.emplace_back(block);
CBlockIndex& bi = index.back();
bi.SetHeight(h);
bi.pprev = h > 0 ? &index[h - 1] : nullptr;
auto inserted = mapBlockIndex.insert(std::make_pair(block.GetHash(), &bi));
ASSERT_TRUE(inserted.second);
insertedBlocks.push_back(block.GetHash());
bi.phashBlock = &inserted.first->first;
}
chainActive.SetTip(&index[tip]);
for (const auto& d : depthOf)
wallet.mapWallet.at(d.first).SetMerkleBranch(blocks[tip - d.second + 1]);
}
std::string NewJSON(const CWalletTx& wtx, const std::string& addr, bool fBool, int returnType) {
UniValue ret(UniValue::VARR);
zsWalletTxJSON(wtx, ret, addr, fBool, returnType, GetSaplingHistoryKeys());
return ret.write();
}
std::string LegacyJSON(const CWalletTx& wtx, const std::string& addr, bool fBool, int returnType) {
UniValue ret(UniValue::VARR);
Legacy_zsWalletTxJSON(wtx, ret, addr, fBool, returnType);
return ret.write();
}
void ExpectMatchesLegacy(bool checkCoverage = true);
};
// Every tx, every return type, unfiltered and filtered by each kind of address: byte-identical JSON. Run with
// the wallet's plaintext cache warm (as after the startup warm-up) and cold (every output trial-decrypted).
class WalletHistoryCold : public WalletHistory {};
TEST_F(WalletHistoryCold, MatchesLegacy) {
LOCK2(cs_main, wallet.cs_wallet);
for (auto& p : wallet.mapWallet)
for (auto& item : p.second.mapSaplingNoteData)
item.second.cachedPlaintext = boost::none;
ExpectMatchesLegacy();
}
TEST_F(WalletHistory, MatchesLegacy) {
LOCK2(cs_main, wallet.cs_wallet);
ExpectMatchesLegacy();
}
void WalletHistory::ExpectMatchesLegacy(bool checkCoverage) {
const std::vector<std::pair<std::string, bool>> filters = {
{"*", false}, {"*", true}, {EncodePaymentAddress(paA), true}, {EncodePaymentAddress(paA2), true},
{EncodePaymentAddress(paB), true}, {EncodePaymentAddress(paC), true}, {EncodePaymentAddress(paD), true},
{EncodePaymentAddress(paF), true}, {EncodeDestination(taddr), true},
};
std::string all;
for (const uint256& txid : txids) {
const CWalletTx& wtx = wallet.mapWallet.at(txid);
for (int returnType = 0; returnType <= 3; returnType++) {
for (const auto& f : filters) {
// New first: the legacy spends helper default-inserts into wallet maps.
std::string got = NewJSON(wtx, f.first, f.second, returnType);
std::string want = LegacyJSON(wtx, f.first, f.second, returnType);
EXPECT_EQ(want, got) << "tx " << txid.ToString() << " returnType " << returnType << " filter " << f.first << "/" << f.second;
all += got;
}
}
}
// The fixture really reaches the interesting branches.
if (!checkCoverage)
return;
for (const char* needle : {"\"change\":true", "\"memoStr\"", "\"saplingSpends\":[{", "\"transparentSpends\":[{",
"\"saplingSends\":[{", "\"saplingReceived\":[{", "\"missingSaplingOVK\":true",
"\"missingSpendingKeys\":true", "for D, found later"}) {
EXPECT_NE(std::string::npos, all.find(needle)) << needle;
}
}
// The same comparison on an encrypted wallet, locked (no spending keys or HD seed available: no shielded
// received or sent entries, as before) and then unlocked.
class WalletHistoryEncrypted : public WalletHistory {};
TEST_F(WalletHistoryEncrypted, MatchesLegacyLockedAndUnlocked) {
LOCK2(cs_main, wallet.cs_wallet);
CKeyingMaterial masterKey(32, 0x5e);
ASSERT_TRUE(wallet.EncryptKeys(masterKey));
ASSERT_TRUE(wallet.IsLocked());
ASSERT_TRUE(GetSaplingHistoryKeys().spendable.empty());
ExpectMatchesLegacy(false);
ASSERT_TRUE(wallet.Unlock(masterKey));
ASSERT_FALSE(GetSaplingHistoryKeys().spendable.empty());
ExpectMatchesLegacy();
}
// The history helpers only read the wallet. The old spends helper's operator[] lookups inserted an entry into
// mapSaplingNullifiersToNotes for every other wallet's nullifier they met, which made a later
// z_viewtransaction of that tx fail (map::at on a null outpoint).
TEST_F(WalletHistory, DoesNotModifyTheWallet) {
LOCK2(cs_main, wallet.cs_wallet);
const size_t nullifierEntries = wallet.mapSaplingNullifiersToNotes.size();
std::map<uint256, size_t> noteEntries;
for (const auto& p : wallet.mapWallet)
noteEntries[p.first] = p.second.mapSaplingNoteData.size();
for (const uint256& txid : txids)
for (int returnType = 0; returnType <= 3; returnType++)
NewJSON(wallet.mapWallet.at(txid), "*", false, returnType);
EXPECT_EQ(nullifierEntries, wallet.mapSaplingNullifiersToNotes.size());
EXPECT_EQ(0u, wallet.mapSaplingNullifiersToNotes.count(uint256S("ff"))) << "someone else's spend";
for (const auto& p : wallet.mapWallet)
EXPECT_EQ(noteEntries.at(p.first), p.second.mapSaplingNoteData.size());
// What the old helpers did, for the record.
for (const uint256& txid : txids)
LegacyJSON(wallet.mapWallet.at(txid), "*", false, 0);
EXPECT_EQ(1u, wallet.mapSaplingNullifiersToNotes.count(uint256S("ff")));
}
File diff suppressed because it is too large Load Diff
+272
View File
@@ -0,0 +1,272 @@
// Copyright (c) 2016-2024 The Hush developers
// Distributed under the GPLv3 software license, see the accompanying
// file COPYING or https://www.gnu.org/licenses/gpl-3.0.en.html
#include <gtest/gtest.h>
#include <deque>
#include "chain.h"
#include "coins.h"
#include "main.h"
#include "primitives/block.h"
#include "primitives/transaction.h"
#include "random.h"
#include "uint256.h"
#include "wallet/wallet.h"
#include "zcash/Note.hpp"
#include "zcash/zip32.h"
namespace {
class NoteDataWallet : public CWallet {
public:
bool UpdatedNoteData(const CWalletTx& wtxIn, CWalletTx& wtx, bool fSameBlock = true) {
return CWallet::UpdatedNoteData(wtxIn, wtx, fSameBlock);
}
int VerifyAndSetInitialWitness(const CBlockIndex* pindex, bool witnessOnly) {
return CWallet::VerifyAndSetInitialWitness(pindex, witnessOnly);
}
};
libzcash::SaplingIncomingViewingKey TestIvk()
{
return libzcash::SaplingIncomingViewingKey(uint256S("0101010101010101010101010101010101010101010101010101010101010101"));
}
// A note as the wallet holds it once witnessed: nullifier set, witnesses cached at a height.
SaplingNoteData WitnessedNote(const SaplingMerkleTree& tree, int height, const uint256& nullifier)
{
SaplingNoteData nd(TestIvk(), nullifier);
nd.witnesses.push_front(tree.witness());
nd.witnessHeight = height;
return nd;
}
// A note as FindMySaplingNotes returns it during a replay or rescan: no nullifier, no witnesses.
SaplingNoteData FreshNote()
{
return SaplingNoteData(TestIvk());
}
}
// A replayed or rescanned tx must keep the witnesses AND the nullifier it already had, and must not
// report an update: dropping the nullifier made the next block clear and reseed every carried witness.
TEST(WalletNoteData, ReplayKeepsNullifierAndWitnesses) {
NoteDataWallet wallet;
CWalletTx wtx(&wallet, CTransaction());
uint256 txid = uint256S("aa");
SaplingOutPoint op0(txid, 0);
SaplingMerkleTree tree;
tree.append(uint256S("01"));
const uint256 nf = uint256S("f00d");
wtx.mapSaplingNoteData[op0] = WitnessedNote(tree, 100, nf);
wtx.mapSaplingNoteData[op0].witnessRootValidated = true;
auto before = wtx.mapSaplingNoteData;
CWalletTx replay(&wallet, CTransaction());
replay.mapSaplingNoteData[op0] = FreshNote();
EXPECT_FALSE(wallet.UpdatedNoteData(replay, wtx));
ASSERT_EQ(1u, wtx.mapSaplingNoteData.size());
const SaplingNoteData& nd = wtx.mapSaplingNoteData.at(op0);
ASSERT_TRUE(static_cast<bool>(nd.nullifier));
EXPECT_EQ(nf, *nd.nullifier);
EXPECT_EQ(100, nd.witnessHeight);
EXPECT_TRUE(nd.witnesses == before.at(op0).witnesses);
// ...but the kept witness is re-checked against the active chain once (in-memory flag only).
EXPECT_FALSE(nd.witnessRootValidated);
}
// A tx re-mined in a different block (reorg) has its notes at new tree positions: the old nullifier
// must not be carried, so VerifyAndSetInitialWitness reseeds the note at its new position.
TEST(WalletNoteData, MovedTxDropsNullifier) {
NoteDataWallet wallet;
CWalletTx wtx(&wallet, CTransaction());
SaplingOutPoint op0(uint256S("ee"), 0);
SaplingMerkleTree tree;
tree.append(uint256S("04"));
wtx.mapSaplingNoteData[op0] = WitnessedNote(tree, 500, uint256S("cafe"));
CWalletTx moved(&wallet, CTransaction());
moved.mapSaplingNoteData[op0] = FreshNote();
EXPECT_TRUE(wallet.UpdatedNoteData(moved, wtx, false));
const SaplingNoteData& nd = wtx.mapSaplingNoteData.at(op0);
EXPECT_FALSE(static_cast<bool>(nd.nullifier));
}
// When the incoming data really adds something (a note for a newly added key), the tx is updated,
// and the notes it already had keep their witnesses, witness height and nullifier together.
TEST(WalletNoteData, NewNoteUpdatesAndKeepsExistingNoteState) {
NoteDataWallet wallet;
CWalletTx wtx(&wallet, CTransaction());
uint256 txid = uint256S("bb");
SaplingOutPoint op0(txid, 0);
SaplingOutPoint op1(txid, 1);
SaplingMerkleTree tree;
tree.append(uint256S("02"));
const uint256 nf = uint256S("beef");
wtx.mapSaplingNoteData[op0] = WitnessedNote(tree, 200, nf);
CWalletTx incoming(&wallet, CTransaction());
incoming.mapSaplingNoteData[op0] = FreshNote();
incoming.mapSaplingNoteData[op1] = FreshNote();
EXPECT_TRUE(wallet.UpdatedNoteData(incoming, wtx));
ASSERT_EQ(2u, wtx.mapSaplingNoteData.size());
const SaplingNoteData& nd0 = wtx.mapSaplingNoteData.at(op0);
ASSERT_TRUE(static_cast<bool>(nd0.nullifier));
EXPECT_EQ(nf, *nd0.nullifier);
EXPECT_EQ(200, nd0.witnessHeight);
EXPECT_EQ(1u, nd0.witnesses.size());
const SaplingNoteData& nd1 = wtx.mapSaplingNoteData.at(op1);
EXPECT_FALSE(static_cast<bool>(nd1.nullifier));
EXPECT_TRUE(nd1.witnesses.empty());
EXPECT_EQ(-1, nd1.witnessHeight);
}
// Nothing is carried for a note that has no witnesses (PART B2): its height and nullifier describe
// no witness, so they must not survive onto the incoming data.
TEST(WalletNoteData, UnwitnessedNoteCarriesNothing) {
NoteDataWallet wallet;
CWalletTx wtx(&wallet, CTransaction());
SaplingOutPoint op0(uint256S("cc"), 0);
SaplingNoteData stale(TestIvk(), uint256S("dead"));
stale.witnessHeight = 300;
wtx.mapSaplingNoteData[op0] = stale;
CWalletTx incoming(&wallet, CTransaction());
incoming.mapSaplingNoteData[op0] = FreshNote();
EXPECT_TRUE(wallet.UpdatedNoteData(incoming, wtx));
const SaplingNoteData& nd = wtx.mapSaplingNoteData.at(op0);
EXPECT_FALSE(static_cast<bool>(nd.nullifier));
EXPECT_EQ(-1, nd.witnessHeight);
EXPECT_TRUE(nd.witnesses.empty());
}
// Incoming data with no Sapling notes never touches the wallet's note data.
TEST(WalletNoteData, EmptyIncomingIsNoUpdate) {
NoteDataWallet wallet;
CWalletTx wtx(&wallet, CTransaction());
SaplingOutPoint op0(uint256S("dd"), 0);
SaplingMerkleTree tree;
tree.append(uint256S("03"));
wtx.mapSaplingNoteData[op0] = WitnessedNote(tree, 400, uint256S("abcd"));
CWalletTx incoming(&wallet, CTransaction());
EXPECT_FALSE(wallet.UpdatedNoteData(incoming, wtx));
EXPECT_EQ(1u, wtx.mapSaplingNoteData.size());
EXPECT_EQ(400, wtx.mapSaplingNoteData.at(op0).witnessHeight);
}
namespace {
// A real encrypted Sapling output to pa (the wallet never checks its proof or value commitment).
OutputDescription EncryptedOutput(const libzcash::SaplingPaymentAddress& pa, uint64_t value)
{
libzcash::SaplingNote note(pa, value);
std::array<unsigned char, HUSH_MEMO_SIZE> memo;
memo.fill(0);
auto enc = libzcash::SaplingNotePlaintext(note, memo).encrypt(note.pk_d);
assert(static_cast<bool>(enc));
OutputDescription od;
od.cv = GetRandHash();
od.cm = note.cm().get();
od.ephemeralKey = enc->second.get_epk();
od.encCiphertext = enc->first;
return od;
}
// A three-block active chain (heights 0-2) whose block 1 holds the given txs, undone on destruction:
// chainActive, mapBlockIndex and pcoinsTip are process-wide and every gtest suite shares the process.
struct FakeActiveChain {
std::deque<CBlock> blocks;
std::deque<CBlockIndex> index;
CBlockIndex* savedTip;
CCoinsView coinsBase;
CCoinsViewCache coins{&coinsBase};
CCoinsViewCache* savedCoinsTip;
explicit FakeActiveChain(const std::vector<CTransaction>& inBlock1) {
LOCK(cs_main);
savedTip = chainActive.Tip();
savedCoinsTip = pcoinsTip;
pcoinsTip = &coins;
for (int h = 0; h <= 2; h++) {
blocks.emplace_back();
CBlock& block = blocks.back();
block.nTime = 1700000000 + h;
block.nNonce = uint256S(strprintf("%x", 0x700 + h));
if (h > 0)
block.hashPrevBlock = blocks[h - 1].GetHash();
if (h == 1)
block.vtx = inBlock1;
block.hashMerkleRoot = block.BuildMerkleTree();
index.emplace_back(block);
CBlockIndex& bi = index.back();
bi.SetHeight(h);
bi.pprev = h > 0 ? &index[h - 1] : nullptr;
bi.phashBlock = &mapBlockIndex.insert(std::make_pair(block.GetHash(), &bi)).first->first;
}
chainActive.SetTip(&index.back());
}
~FakeActiveChain() {
LOCK(cs_main);
chainActive.SetTip(savedTip);
for (const CBlock& block : blocks)
mapBlockIndex.erase(block.GetHash());
pcoinsTip = savedCoinsTip;
}
};
}
// A note found with an incoming viewing key only (z_importviewingkey) can't be spent and never gets
// a nullifier, because deriving one takes the full viewing key. VerifyAndSetInitialWitness must leave
// it alone. It used to clear it and reseed its witness from the block on disk on every call, then
// abort on the missing nullifier the first time the note was confirmed. Here there are no block
// files, so the old reseed path throws.
TEST(WalletNoteData, ViewingKeyOnlyNoteIsNotWitnessed) {
NoteDataWallet wallet;
std::vector<unsigned char, secure_allocator<unsigned char>> raw(32, 0x3c);
HDSeed seed(raw);
auto sk = libzcash::SaplingExtendedSpendingKey::Master(seed);
auto pa = sk.DefaultAddress();
LOCK2(cs_main, wallet.cs_wallet);
ASSERT_TRUE(wallet.AddSaplingIncomingViewingKey(sk.expsk.full_viewing_key().in_viewing_key(), pa));
ASSERT_FALSE(wallet.HaveSaplingFullViewingKey(sk.expsk.full_viewing_key().in_viewing_key()));
CMutableTransaction mtx;
mtx.fOverwintered = true;
mtx.nVersion = SAPLING_TX_VERSION;
mtx.nVersionGroupId = SAPLING_VERSION_GROUP_ID;
mtx.vShieldedOutput.push_back(EncryptedOutput(pa, 5000));
CTransaction tx(mtx);
CWalletTx wtx(&wallet, tx);
mapSaplingNoteData_t found = wallet.FindMySaplingNotes(tx).first;
ASSERT_EQ(1u, found.size()) << "the viewing key finds the note";
wtx.SetSaplingNoteData(found);
ASSERT_TRUE(wallet.AddToWallet(wtx, true, nullptr));
FakeActiveChain chain({tx});
CWalletTx& stored = wallet.mapWallet.at(tx.GetHash());
stored.SetMerkleBranch(chain.blocks[1]);
ASSERT_EQ(2, stored.GetDepthInMainChain());
int minHeight = -1;
ASSERT_NO_THROW(minHeight = wallet.VerifyAndSetInitialWitness(chainActive.Tip(), false));
EXPECT_EQ(chainActive.Height(), minHeight) << "it must not pull the witness rebuild down to its height";
const SaplingNoteData& nd = stored.mapSaplingNoteData.at(SaplingOutPoint(tx.GetHash(), 0));
EXPECT_TRUE(nd.witnesses.empty());
EXPECT_FALSE(static_cast<bool>(nd.nullifier));
EXPECT_EQ(-1, nd.witnessHeight);
}
+383
View File
@@ -0,0 +1,383 @@
// Copyright (c) 2016-2024 The Hush developers
// Distributed under the GPLv3 software license, see the accompanying
// file COPYING or https://www.gnu.org/licenses/gpl-3.0.en.html
#include <gtest/gtest.h>
#include <string>
#include <boost/filesystem.hpp>
#include "chain.h"
#include "chainparams.h"
#include "util.h"
#include "validationinterface.h"
#include "main.h"
#include "wallet/db.h"
#include "wallet/wallet.h"
#include "wallet/walletdb.h"
namespace {
std::string Reason(CWallet& wallet, bool fInitCompleted, bool fChainstateFlushed = true)
{
const char* reason = wallet.ShutdownSaveSkipReason(fInitCompleted, fChainstateFlushed);
return reason ? reason : "";
}
// fWalletNotifyFailed is process-wide, and other suites drive NotifyWalletsOrShutdown's failure path.
class WalletShutdownSave : public ::testing::Test {
protected:
void SetUp() override { fWalletNotifyFailed = false; }
void TearDown() override { fWalletNotifyFailed = false; }
};
class SaveWallet : public CWallet {
public:
explicit SaveWallet(const std::string& strFile = "") : CWallet(strFile) {}
template <typename WalletDB>
bool SetBestChainWith(WalletDB& walletdb, const CBlockLocator& loc) { return CWallet::SetBestChainWith(walletdb, loc); }
void DecrementNoteWitnesses(const CBlockIndex* pindex) { CWallet::DecrementNoteWitnesses(pindex); }
};
// Each step of SetBestChainINTERNAL's transaction can be made to fail.
struct FakeWalletDB {
bool fBegin = true, fWriteTx = true, fCacheSize = true, fBestBlock = true, fCommit = true;
int nAborts = 0;
CBlockLocator written;
bool TxnBegin() { return fBegin; }
bool TxnCommit() { return fCommit; }
bool TxnAbort() { nAborts++; return true; }
bool WriteTx(uint256, const CWalletTx&) { return fWriteTx; }
bool WriteWitnessCacheSize(int64_t) { return fCacheSize; }
bool WriteBestBlock(const CBlockLocator& loc) { written = loc; return fBestBlock; }
};
// A wallet with one note, so the transaction writes a tx.
void AddNote(CWallet& wallet)
{
CMutableTransaction mtx;
mtx.nLockTime = 4242;
CWalletTx wtx(&wallet, CTransaction(mtx));
SaplingNoteData nd(uint256S("01"), uint256S("02"));
wtx.mapSaplingNoteData[SaplingOutPoint(wtx.GetHash(), 0)] = nd;
LOCK(wallet.cs_wallet);
ASSERT_TRUE(wallet.AddToWallet(wtx, true, nullptr));
}
}
// A startup that failed or was cut short never writes: its threads were not joined, and an unset wallet
// tip would make SetBestChain stamp the chain tip over an interrupted rescan's checkpoint.
TEST_F(WalletShutdownSave, SkipsWhenStartupDidNotComplete) {
CWallet wallet;
CBlockIndex tip;
wallet.SetWalletTip(&tip);
EXPECT_EQ("startup did not complete", Reason(wallet, false));
EXPECT_EQ("", Reason(wallet, true));
}
TEST_F(WalletShutdownSave, SkipsWithoutAWalletTip) {
CWallet wallet;
EXPECT_EQ("the wallet tip is not set", Reason(wallet, true));
}
// A shutdown caused by the wallet failing on a block must not write the whole wallet into that database.
TEST_F(WalletShutdownSave, SkipsAfterAWalletFailure) {
CWallet wallet;
CBlockIndex tip;
wallet.SetWalletTip(&tip);
fWalletNotifyFailed = true;
EXPECT_EQ("the wallet failed to process a block", Reason(wallet, true));
fWalletNotifyFailed = false;
EXPECT_EQ("", Reason(wallet, true));
}
TEST_F(WalletShutdownSave, CanBeTurnedOff) {
CWallet wallet;
CBlockIndex tip;
wallet.SetWalletTip(&tip);
mapArgs["-walletsaveatshutdown"] = "0";
EXPECT_EQ("disabled by -walletsaveatshutdown=0", Reason(wallet, true));
mapArgs["-walletsaveatshutdown"] = "1";
EXPECT_EQ("", Reason(wallet, true));
mapArgs.erase("-walletsaveatshutdown");
EXPECT_EQ("", Reason(wallet, true)) << "on by default";
}
// A failed chainstate flush (typically a full disk) leaves the block the locator would name possibly missing from the
// chainstate on disk.
TEST_F(WalletShutdownSave, SkipsWhenTheChainstateFlushFailed) {
CWallet wallet;
CBlockIndex tip;
wallet.SetWalletTip(&tip);
EXPECT_EQ("the chainstate flush failed", Reason(wallet, true, false));
EXPECT_EQ("", Reason(wallet, true, true));
}
// Once a save (or init, finding nothing to rescan) has recorded the wallet's block, a shutdown writes again
// only if the wallet moved to another block or its note state changed.
TEST_F(WalletShutdownSave, SkipsWhenNothingChangedSinceTheLastSave) {
CWallet wallet;
CBlockIndex a, b;
a.SetHeight(10);
b.SetHeight(11);
b.pprev = &a;
wallet.SetWalletTip(&a);
EXPECT_EQ("", Reason(wallet, true));
wallet.MarkStatePersisted(&a);
EXPECT_EQ("nothing changed since the last save", Reason(wallet, true));
wallet.SetWalletTip(&b);
EXPECT_EQ("", Reason(wallet, true)) << "a new block";
wallet.MarkStatePersisted(&b);
EXPECT_EQ("nothing changed since the last save", Reason(wallet, true));
wallet.ClearNoteWitnessCache();
EXPECT_EQ("", Reason(wallet, true)) << "witnesses changed at the same block";
wallet.MarkStatePersisted(&b);
EXPECT_EQ("nothing changed since the last save", Reason(wallet, true));
// A save recorded at another block than the one the wallet is at does not count.
wallet.MarkStatePersisted(&a);
EXPECT_EQ("", Reason(wallet, true));
}
// A rescan that did not complete (abortrescan, a stop, a throw) left the locator on disk below the wallet tip: the
// next start resumes from there only if the shutdown does not stamp the tip over it. A later scan clears that once it
// covers the range from where the locator stands.
TEST_F(WalletShutdownSave, SkipsAfterAnIncompleteRescan) {
const std::string incomplete = "a rescan did not complete; the next start resumes it from the locator it left";
CWallet wallet;
CBlockIndex tip;
tip.SetHeight(841);
wallet.SetWalletTip(&tip);
// Interrupted after a checkpoint at 833.
EXPECT_EQ(-1, wallet.NoteRescanStarted(821));
EXPECT_EQ(incomplete, Reason(wallet, true)) << "while it runs";
wallet.NoteRescanInterrupted(833);
EXPECT_EQ(incomplete, Reason(wallet, true));
// A complete scan from above the checkpoint leaves 834.. unscanned from where the disk stands.
int before = wallet.NoteRescanStarted(833);
EXPECT_EQ(833, before);
wallet.NoteRescanCompleted(835, before);
EXPECT_EQ(incomplete, Reason(wallet, true));
// One from the block after it covers everything.
before = wallet.NoteRescanStarted(833);
wallet.NoteRescanCompleted(834, before);
EXPECT_EQ("", Reason(wallet, true));
// A scan that throws never reports an end.
wallet.NoteRescanStarted(841);
EXPECT_EQ(incomplete, Reason(wallet, true));
before = wallet.NoteRescanStarted(841);
wallet.NoteRescanCompleted(100, before);
EXPECT_EQ("", Reason(wallet, true));
// With nothing interrupted before it, a complete scan is what was asked for, wherever it starts
// (z_importkey with a start height above the locator).
before = wallet.NoteRescanStarted(821);
EXPECT_EQ(-1, before);
wallet.NoteRescanCompleted(840, before);
EXPECT_EQ("", Reason(wallet, true));
// No locator on disk: resume from genesis.
wallet.NoteRescanStarted(-1);
wallet.NoteRescanInterrupted(-1);
EXPECT_EQ(incomplete, Reason(wallet, true));
before = wallet.NoteRescanStarted(-1);
EXPECT_EQ(0, before);
wallet.NoteRescanCompleted(2, before);
EXPECT_EQ(incomplete, Reason(wallet, true));
wallet.NoteRescanCompleted(1, before);
EXPECT_EQ("", Reason(wallet, true));
}
// The save writes through the real wallet database (an in-memory BDB environment here), and a skip writes nothing.
class WalletShutdownSaveDb : public WalletShutdownSave {
protected:
void SetUp() override {
WalletShutdownSave::SetUp();
bitdb.MakeMock();
CWalletDB create(strFile, "cr+");
}
void TearDown() override {
bitdb.Flush(true);
bitdb.Reset();
WalletShutdownSave::TearDown();
}
const std::string strFile = "shutdownsave.dat";
bool ReadBestBlock(CBlockLocator& loc) {
CWalletDB walletdb(strFile, "r");
return walletdb.ReadBestBlock(loc);
}
};
TEST_F(WalletShutdownSaveDb, SavesTheWalletTipAndRecordsIt) {
CWallet wallet(strFile);
AddNote(wallet);
uint256 hash = uint256S("0abc");
CBlockIndex tip;
tip.phashBlock = &hash;
wallet.SetWalletTip(&tip);
{
LOCK(cs_main);
wallet.PersistStateAtShutdown(true, true);
}
CBlockLocator loc;
ASSERT_TRUE(ReadBestBlock(loc));
ASSERT_FALSE(loc.vHave.empty());
EXPECT_EQ(hash, loc.vHave.front());
EXPECT_EQ("nothing changed since the last save", Reason(wallet, true));
}
TEST_F(WalletShutdownSaveDb, SkippedSaveWritesNothing) {
CWallet wallet(strFile);
AddNote(wallet);
uint256 hash = uint256S("0abc");
CBlockIndex tip;
tip.phashBlock = &hash;
wallet.SetWalletTip(&tip);
{
LOCK(cs_main);
wallet.PersistStateAtShutdown(false, true);
wallet.PersistStateAtShutdown(true, false);
wallet.NoteRescanStarted(0);
wallet.PersistStateAtShutdown(true, true);
}
CBlockLocator loc;
EXPECT_FALSE(ReadBestBlock(loc));
EXPECT_EQ("a rescan did not complete; the next start resumes it from the locator it left", Reason(wallet, true));
}
// Opening the wallet database can throw (an environment or file that cannot be opened). Shutdown() has no handler,
// so the save must catch it, record nothing, and return.
TEST_F(WalletShutdownSave, AFailedOpenDoesNotEscape) {
SelectParams(CBaseChainParams::MAIN);
const boost::filesystem::path dir = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path("shutdownsave-%%%%%%%%");
const bool hadDatadir = mapArgs.count("-datadir") > 0;
const std::string oldDatadir = hadDatadir ? mapArgs["-datadir"] : "";
boost::filesystem::create_directories(dir);
mapArgs["-datadir"] = dir.string();
ClearDatadirCache();
// The environment's log directory is a regular file, so opening the environment throws.
{
FILE* f = fopen((GetDataDir() / "database").string().c_str(), "wb");
ASSERT_TRUE(f != nullptr);
fclose(f);
}
CWallet wallet("wallet.dat");
uint256 hash = uint256S("0123");
CBlockIndex tip;
tip.phashBlock = &hash;
wallet.SetWalletTip(&tip);
ASSERT_EQ("", Reason(wallet, true));
{
LOCK(cs_main);
EXPECT_NO_THROW(wallet.PersistStateAtShutdown(true, true));
}
EXPECT_EQ("", Reason(wallet, true)) << "a failed save must not be recorded as one";
if (hadDatadir) mapArgs["-datadir"] = oldDatadir; else mapArgs.erase("-datadir");
ClearDatadirCache();
boost::filesystem::remove_all(dir);
}
// The shutdown save may skip only what a committed write saved: a write that failed at any step records nothing.
TEST_F(WalletShutdownSave, RecordsOnlyACommittedWrite) {
SaveWallet wallet;
AddNote(wallet);
uint256 hash = uint256S("0abc");
CBlockIndex tip;
tip.phashBlock = &hash;
wallet.SetWalletTip(&tip);
CBlockLocator chainTip(std::vector<uint256>{uint256S("0def")});
for (int step = 0; step < 5; step++) {
FakeWalletDB db;
bool* steps[5] = {&db.fBegin, &db.fWriteTx, &db.fCacheSize, &db.fBestBlock, &db.fCommit};
*steps[step] = false;
EXPECT_FALSE(wallet.SetBestChainWith(db, chainTip)) << "step " << step;
EXPECT_EQ("", Reason(wallet, true)) << "step " << step;
EXPECT_EQ(step >= 1 && step <= 3 ? 1 : 0, db.nAborts) << "step " << step;
}
FakeWalletDB db;
EXPECT_TRUE(wallet.SetBestChainWith(db, chainTip));
EXPECT_EQ("nothing changed since the last save", Reason(wallet, true));
ASSERT_FALSE(db.written.vHave.empty());
EXPECT_EQ(hash, db.written.vHave.front()) << "the wallet tip is stamped, not the chain tip passed in";
}
// Before init seeds the wallet tip, the block recorded is the one the locator passed in names.
TEST_F(WalletShutdownSave, RecordsTheLocatorsBlockWithoutAWalletTip) {
SaveWallet wallet;
CBlock block;
block.nTime = 1720000000;
CBlockIndex index(block);
{
LOCK(cs_main);
index.phashBlock = &mapBlockIndex.insert(std::make_pair(block.GetHash(), &index)).first->first;
}
FakeWalletDB db;
EXPECT_TRUE(wallet.SetBestChainWith(db, CBlockLocator(std::vector<uint256>{block.GetHash()})));
EXPECT_EQ(block.GetHash(), db.written.vHave.front());
wallet.SetWalletTip(&index);
EXPECT_EQ("nothing changed since the last save", Reason(wallet, true));
LOCK(cs_main);
mapBlockIndex.erase(block.GetHash());
}
// Every change to what SetBestChain writes makes the next shutdown write again.
TEST_F(WalletShutdownSave, NoteChangesNeedASave) {
SaveWallet wallet;
CBlockIndex tip;
tip.SetHeight(5);
wallet.SetWalletTip(&tip);
wallet.MarkStatePersisted(&tip);
ASSERT_EQ("nothing changed since the last save", Reason(wallet, true));
// As set from the chain parameters at startup; DecrementNoteWitnesses asserts it was.
extern unsigned int WITNESS_CACHE_SIZE;
const unsigned int nSavedCacheSize = WITNESS_CACHE_SIZE;
WITNESS_CACHE_SIZE = MAX_REORG_LENGTH + 10;
wallet.DecrementNoteWitnesses(&tip);
WITNESS_CACHE_SIZE = nSavedCacheSize;
EXPECT_EQ("", Reason(wallet, true)) << "a disconnected block";
wallet.MarkStatePersisted(&tip);
wallet.ClearNoteWitnessCache();
EXPECT_EQ("", Reason(wallet, true)) << "witnesses cleared";
}
// Adding a note-bearing tx, or changing one, is a change to save; re-adding one unchanged (as
// ReacceptWalletTransactions does for every unconfirmed tx at each start) is not, nor is a tx without notes.
TEST_F(WalletShutdownSaveDb, AddingANoteNeedsASave) {
CWallet wallet(strFile);
CBlockIndex tip;
wallet.SetWalletTip(&tip);
wallet.MarkStatePersisted(&tip);
CWalletDB walletdb(strFile, "r+");
LOCK(wallet.cs_wallet);
CMutableTransaction mtx;
mtx.nLockTime = 777;
CWalletTx plain(&wallet, CTransaction(mtx));
ASSERT_TRUE(wallet.AddToWallet(plain, false, &walletdb));
EXPECT_EQ("nothing changed since the last save", Reason(wallet, true)) << "no notes";
mtx.nLockTime = 778;
CWalletTx wtx(&wallet, CTransaction(mtx));
wtx.mapSaplingNoteData[SaplingOutPoint(wtx.GetHash(), 0)] = SaplingNoteData(uint256S("01"), uint256S("02"));
ASSERT_TRUE(wallet.AddToWallet(wtx, false, &walletdb));
EXPECT_EQ("", Reason(wallet, true)) << "a new note";
wallet.MarkStatePersisted(&tip);
ASSERT_TRUE(wallet.AddToWallet(wtx, false, &walletdb));
EXPECT_EQ("nothing changed since the last save", Reason(wallet, true)) << "the same tx again";
}
+475
View File
@@ -0,0 +1,475 @@
// Copyright (c) 2016-2024 The Hush developers
// Distributed under the GPLv3 software license, see the accompanying
// file COPYING or https://www.gnu.org/licenses/gpl-3.0.en.html
#include <gtest/gtest.h>
#include <deque>
#include <map>
#include <stdexcept>
#include <boost/filesystem.hpp>
#include "chain.h"
#include "chainparams.h"
#include "coins.h"
#include "init.h"
#include "main.h"
#include "primitives/block.h"
#include "primitives/transaction.h"
#include "uint256.h"
#include "util.h"
#include "validationinterface.h"
#include "wallet/wallet.h"
#include "zcash/zip32.h"
extern std::atomic<bool> fRequestShutdown;
// VerifyAndSetInitialWitness computes the witness roots it checks on worker threads before its serial loop. These
// tests run the same synthetic wallet with one thread and with several and compare every note's resulting state.
namespace {
class RootsWallet : public CWallet {
public:
int VerifyAndSetInitialWitness(const CBlockIndex* pindex, bool witnessOnly) {
return CWallet::VerifyAndSetInitialWitness(pindex, witnessOnly);
}
};
// An active chain of nBlocks blocks (heights 0..nBlocks-1) whose block 1 holds the given txs, with a chosen
// hashFinalSaplingRoot per height. Undone on destruction: chainActive, mapBlockIndex and pcoinsTip are process-wide.
struct RootsChain {
std::deque<CBlock> blocks;
std::deque<CBlockIndex> index;
CBlockIndex* savedTip;
CCoinsView coinsBase;
CCoinsViewCache coins{&coinsBase};
CCoinsViewCache* savedCoinsTip;
RootsChain(int nBlocks, const std::vector<CTransaction>& inBlock1, const std::map<int, uint256>& roots) {
LOCK(cs_main);
savedTip = chainActive.Tip();
savedCoinsTip = pcoinsTip;
pcoinsTip = &coins;
for (int h = 0; h < nBlocks; h++) {
blocks.emplace_back();
CBlock& block = blocks.back();
block.nTime = 1710000000 + h;
block.nNonce = uint256S(strprintf("%x", 0x900 + h));
if (h > 0)
block.hashPrevBlock = blocks[h - 1].GetHash();
if (h == 1)
block.vtx = inBlock1;
block.hashMerkleRoot = block.BuildMerkleTree();
index.emplace_back(block);
CBlockIndex& bi = index.back();
bi.SetHeight(h);
bi.pprev = h > 0 ? &index[h - 1] : nullptr;
std::map<int, uint256>::const_iterator it = roots.find(h);
if (it != roots.end())
bi.hashFinalSaplingRoot = it->second;
bi.phashBlock = &mapBlockIndex.insert(std::make_pair(block.GetHash(), &bi)).first->first;
}
chainActive.SetTip(&index.back());
}
~RootsChain() {
LOCK(cs_main);
chainActive.SetTip(savedTip);
for (const CBlock& block : blocks)
mapBlockIndex.erase(block.GetHash());
pcoinsTip = savedCoinsTip;
}
};
libzcash::SaplingExtendedSpendingKey TestKey()
{
std::vector<unsigned char, secure_allocator<unsigned char>> raw(32, 0x5a);
HDSeed seed(raw);
return libzcash::SaplingExtendedSpendingKey::Master(seed);
}
std::vector<CTransaction> Txs(int n)
{
std::vector<CTransaction> txs;
for (int i = 0; i < n; i++) {
CMutableTransaction mtx;
mtx.nLockTime = 1000 + i; // distinct txids
txs.push_back(CTransaction(mtx));
}
return txs;
}
// Witnesses of nNotes positions in one tree: all share the tree's root. Each is a distinct witness object.
std::vector<SaplingWitness> Witnesses(int nNotes, int salt, uint256& rootOut)
{
SaplingMerkleTree tree;
std::vector<SaplingWitness> ws;
for (int i = 0; i < nNotes; i++) {
uint256 cm = uint256S(strprintf("%x%04x", salt, i + 1));
tree.append(cm);
for (SaplingWitness& w : ws)
w.append(cm);
ws.push_back(tree.witness());
}
rootOut = tree.root();
return ws;
}
// NO_NULLIFIER_VALID: a valid witness at height 2 but no nullifier yet, which only a sibling's reseed gives it.
enum Kind { VALID_BELOW_TIP, VALID_AT_TIP, AHEAD_OF_CHAIN, ALREADY_VALIDATED, WRONG_ROOT, NOT_IN_CHAIN,
NO_NULLIFIER_VALID };
struct Fixture {
std::vector<CTransaction> txs;
std::map<int, uint256> roots;
std::vector<SaplingWitness> wBelow, wAt;
int nTxs;
};
// Fills the wallet: tx i gets notes of the kinds kinds(i) returns, in output order.
template <typename KindsOf>
void Fill(RootsWallet& wallet, const Fixture& fx, const RootsChain& chain, KindsOf kinds)
{
auto sk = TestKey();
auto ivk = sk.expsk.full_viewing_key().in_viewing_key();
LOCK2(cs_main, wallet.cs_wallet);
ASSERT_TRUE(wallet.AddSaplingZKey(sk, sk.DefaultAddress()));
ASSERT_TRUE(wallet.HaveSaplingFullViewingKey(ivk));
size_t nBelow = 0, nAt = 0;
for (int i = 0; i < fx.nTxs; i++) {
const CTransaction& tx = fx.txs[i];
CWalletTx wtx(&wallet, tx);
std::vector<Kind> ks = kinds(i);
mapSaplingNoteData_t notes;
for (size_t n = 0; n < ks.size(); n++) {
SaplingNoteData nd(ivk, uint256S(strprintf("f%03x%03x", i, (int)n)));
switch (ks[n]) {
case VALID_BELOW_TIP:
nd.witnesses.push_front(fx.wBelow[nBelow++ % fx.wBelow.size()]);
nd.witnessHeight = 2;
break;
case VALID_AT_TIP:
nd.witnesses.push_front(fx.wAt[nAt++ % fx.wAt.size()]);
nd.witnessHeight = 3;
break;
case AHEAD_OF_CHAIN:
nd.witnesses.push_front(fx.wAt[0]);
nd.witnessHeight = 9;
break;
case ALREADY_VALIDATED:
nd.witnesses.push_front(fx.wBelow[0]);
nd.witnessHeight = 2;
nd.witnessRootValidated = true;
break;
case WRONG_ROOT:
nd.witnesses.push_front(fx.wAt[0]); // the tip's tree, checked against block 2's root
nd.witnessHeight = 2;
break;
case NOT_IN_CHAIN:
nd.witnesses.push_front(fx.wBelow[0]);
nd.witnessHeight = 2;
break;
case NO_NULLIFIER_VALID:
nd.witnesses.push_front(fx.wBelow[1]);
nd.witnessHeight = 2;
nd.nullifier = boost::none;
break;
}
notes[SaplingOutPoint(tx.GetHash(), n)] = nd;
}
wtx.mapSaplingNoteData = notes; // the txs carry no outputs; nothing here decrypts
ASSERT_TRUE(wallet.AddToWallet(wtx, true, nullptr));
if (ks.empty() || ks[0] != NOT_IN_CHAIN) {
wallet.mapWallet.at(tx.GetHash()).SetMerkleBranch(chain.blocks[1]);
ASSERT_GT(wallet.mapWallet.at(tx.GetHash()).GetDepthInMainChain(), 0);
}
}
}
// A tx with real Sapling outputs to the test key, which the reseed decrypts to derive nullifiers (it never checks
// the proofs or the value commitments).
CTransaction TxWithOutputs(int nOutputs)
{
auto pa = TestKey().DefaultAddress();
CMutableTransaction mtx;
mtx.fOverwintered = true; // or the outputs are not serialized into the block file
mtx.nVersion = SAPLING_TX_VERSION;
mtx.nVersionGroupId = SAPLING_VERSION_GROUP_ID;
mtx.nLockTime = 5000;
for (int i = 0; i < nOutputs; i++) {
libzcash::SaplingNote note(pa, 1000 + i);
std::array<unsigned char, HUSH_MEMO_SIZE> memo;
memo.fill(0);
auto enc = libzcash::SaplingNotePlaintext(note, memo).encrypt(note.pk_d);
assert(static_cast<bool>(enc));
OutputDescription od;
od.cv = GetRandHash();
od.cm = note.cm().get();
od.ephemeralKey = enc->second.get_epk();
od.encCiphertext = enc->first;
mtx.vShieldedOutput.push_back(od);
}
return CTransaction(mtx);
}
// Block files for the reseed to read, in a temporary datadir. Undone on destruction.
struct BlockFiles {
boost::filesystem::path dir;
bool hadDatadir;
std::string oldDatadir;
BlockFiles() {
SelectParams(CBaseChainParams::MAIN);
dir = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path("witnessroots-%%%%%%%%");
boost::filesystem::create_directories(dir);
hadDatadir = mapArgs.count("-datadir") > 0;
oldDatadir = hadDatadir ? mapArgs["-datadir"] : "";
mapArgs["-datadir"] = dir.string();
ClearDatadirCache();
}
void Write(const CBlock& block, CBlockIndex& index) {
CDiskBlockPos pos(0, index.GetHeight() == 0 ? 0 : (unsigned int)boost::filesystem::file_size(GetBlockPosFilename(CDiskBlockPos(0, 0), "blk")));
ASSERT_TRUE(WriteBlockToDisk(block, pos, Params().MessageStart()));
index.nFile = pos.nFile;
index.nDataPos = pos.nPos;
index.nStatus |= BLOCK_HAVE_DATA;
}
~BlockFiles() {
if (hadDatadir) mapArgs["-datadir"] = oldDatadir; else mapArgs.erase("-datadir");
ClearDatadirCache();
boost::filesystem::remove_all(dir);
}
};
struct NoteState {
bool validated;
int witnessHeight;
size_t nWitnesses;
bool hasNullifier;
bool operator==(const NoteState& o) const {
return validated == o.validated && witnessHeight == o.witnessHeight && nWitnesses == o.nWitnesses &&
hasNullifier == o.hasNullifier;
}
};
std::map<SaplingOutPoint, NoteState> States(RootsWallet& wallet)
{
LOCK(wallet.cs_wallet);
std::map<SaplingOutPoint, NoteState> out;
for (const auto& wtxItem : wallet.mapWallet)
for (const auto& item : wtxItem.second.mapSaplingNoteData)
out[item.first] = {item.second.witnessRootValidated, item.second.witnessHeight,
item.second.witnesses.size(), static_cast<bool>(item.second.nullifier)};
return out;
}
Fixture MakeFixture(int nTxs)
{
Fixture fx;
fx.nTxs = nTxs;
fx.txs = Txs(nTxs);
uint256 rootBelow, rootAt;
fx.wBelow = Witnesses(24, 0xb, rootBelow);
fx.wAt = Witnesses(24, 0xa, rootAt);
fx.roots[2] = rootBelow;
fx.roots[3] = rootAt;
return fx;
}
class WalletWitnessRoots : public ::testing::Test {
protected:
std::string savedThreads;
void SetUp() override {
fRequestShutdown = false;
fWalletNotifyFailed = false; // process-wide; the shutdown-save check below reads it
savedThreads = mapArgs.count("-witnessbuildthreads") ? mapArgs["-witnessbuildthreads"] : "";
}
void TearDown() override {
fRequestShutdown = false;
fWalletNotifyFailed = false;
if (savedThreads.empty())
mapArgs.erase("-witnessbuildthreads");
else
mapArgs["-witnessbuildthreads"] = savedThreads;
}
};
std::vector<Kind> MixedKinds(int i)
{
static const Kind cycle[] = {VALID_BELOW_TIP, VALID_AT_TIP, VALID_BELOW_TIP, AHEAD_OF_CHAIN, ALREADY_VALIDATED,
VALID_AT_TIP};
std::vector<Kind> ks;
for (int n = 0; n < 1 + i % 3; n++)
ks.push_back(cycle[(i + n) % 6]);
return ks;
}
}
// Every note is validated, skipped or deferred exactly as the serial pass does it, and the minimum height
// matches, whether the roots come from one thread or eight.
TEST_F(WalletWitnessRoots, ParallelMatchesSerial) {
Fixture fx = MakeFixture(60);
RootsChain chain(4, fx.txs, fx.roots);
std::map<SaplingOutPoint, NoteState> results[2];
int minHeight[2];
const char* threads[2] = {"1", "8"};
for (int r = 0; r < 2; r++) {
mapArgs["-witnessbuildthreads"] = threads[r];
RootsWallet wallet;
Fill(wallet, fx, chain, MixedKinds);
minHeight[r] = wallet.VerifyAndSetInitialWitness(chainActive.Tip(), false);
results[r] = States(wallet);
}
EXPECT_EQ(minHeight[0], minHeight[1]);
EXPECT_EQ(2, minHeight[0]) << "the lowest witness height among the checked notes";
ASSERT_EQ(results[0].size(), results[1].size());
EXPECT_TRUE(results[0] == results[1]);
// And the outcome is the one the serial rules give for each kind.
std::map<SaplingOutPoint, Kind> kindOf;
for (int i = 0; i < fx.nTxs; i++) {
std::vector<Kind> ks = MixedKinds(i);
for (size_t n = 0; n < ks.size(); n++)
kindOf[SaplingOutPoint(fx.txs[i].GetHash(), n)] = ks[n];
}
int nValidated = 0;
for (const auto& r : results[1]) {
Kind k = kindOf.at(r.first);
bool expectValidated = k != AHEAD_OF_CHAIN;
EXPECT_EQ(expectValidated, r.second.validated) << "kind " << k;
EXPECT_EQ(1u, r.second.nWitnesses);
EXPECT_TRUE(r.second.hasNullifier);
nValidated += r.second.validated && k != ALREADY_VALIDATED;
}
EXPECT_GT(nValidated, 40) << "enough roots to spread over the threads";
}
// With witnessOnly the already-validated notes are skipped outright; the rest is the same.
TEST_F(WalletWitnessRoots, ParallelMatchesSerialWitnessOnly) {
Fixture fx = MakeFixture(40);
RootsChain chain(4, fx.txs, fx.roots);
std::map<SaplingOutPoint, NoteState> results[2];
int minHeight[2];
const char* threads[2] = {"1", "6"};
for (int r = 0; r < 2; r++) {
mapArgs["-witnessbuildthreads"] = threads[r];
RootsWallet wallet;
Fill(wallet, fx, chain, MixedKinds);
minHeight[r] = wallet.VerifyAndSetInitialWitness(chainActive.Tip(), true);
results[r] = States(wallet);
}
EXPECT_EQ(minHeight[0], minHeight[1]);
EXPECT_TRUE(results[0] == results[1]);
}
// A wrong root sends the note to the reseed, which reads its block from disk; there are no block files here, so
// it throws. Every note before it in wallet order has been decided, every note after it not, identically.
TEST_F(WalletWitnessRoots, MismatchIsHandledInSerialOrder) {
Fixture fx = MakeFixture(30);
RootsChain chain(4, fx.txs, fx.roots);
auto kinds = [](int i) {
std::vector<Kind> ks = MixedKinds(i);
if (i == 17)
ks.push_back(WRONG_ROOT);
return ks;
};
std::map<SaplingOutPoint, NoteState> results[2];
const char* threads[2] = {"1", "8"};
for (int r = 0; r < 2; r++) {
mapArgs["-witnessbuildthreads"] = threads[r];
RootsWallet wallet;
Fill(wallet, fx, chain, kinds);
EXPECT_THROW(wallet.VerifyAndSetInitialWitness(chainActive.Tip(), false), std::runtime_error);
results[r] = States(wallet);
}
EXPECT_TRUE(results[0] == results[1]);
int nDecided = 0, nUndecided = 0;
for (const auto& r : results[1])
(r.second.validated ? nDecided : nUndecided)++;
EXPECT_GT(nDecided, 0);
EXPECT_GT(nUndecided, 0);
}
// A stop requested while the roots are computed ends the pass before it changes anything.
TEST_F(WalletWitnessRoots, ShutdownSkipsThePassUnchanged) {
Fixture fx = MakeFixture(20);
RootsChain chain(4, fx.txs, fx.roots);
mapArgs["-witnessbuildthreads"] = "4";
RootsWallet wallet;
Fill(wallet, fx, chain, MixedKinds);
std::map<SaplingOutPoint, NoteState> before = States(wallet);
fRequestShutdown = true;
EXPECT_EQ(chainActive.Height(), wallet.VerifyAndSetInitialWitness(chainActive.Tip(), false));
EXPECT_TRUE(before == States(wallet));
}
// Notes of a tx that is not in the active chain are never checked.
TEST_F(WalletWitnessRoots, UnconfirmedTxIsNotChecked) {
Fixture fx = MakeFixture(12);
RootsChain chain(4, fx.txs, fx.roots);
mapArgs["-witnessbuildthreads"] = "4";
RootsWallet wallet;
Fill(wallet, fx, chain, [](int i) {
return i % 2 ? std::vector<Kind>{NOT_IN_CHAIN, NOT_IN_CHAIN} : std::vector<Kind>{VALID_BELOW_TIP, VALID_AT_TIP};
});
wallet.VerifyAndSetInitialWitness(chainActive.Tip(), false);
for (int i = 0; i < fx.nTxs; i++)
for (int n = 0; n < 2; n++)
EXPECT_EQ(i % 2 == 0, States(wallet).at(SaplingOutPoint(fx.txs[i].GetHash(), n)).validated);
}
// A reseed that succeeds: the loop goes on past it, and a sibling that had no nullifier, and so no precomputed root,
// gets one from that reseed and is then checked with its root computed inline. Each note ends as the serial rules
// say, whether the other roots come from one thread or eight, and the reseed counts as a change to save.
TEST_F(WalletWitnessRoots, SuccessfulReseedAndItsSibling) {
Fixture fx = MakeFixture(30);
const int iSeeded = 11;
fx.txs[iSeeded] = TxWithOutputs(2);
BlockFiles files;
RootsChain chain(4, fx.txs, fx.roots);
for (int h = 0; h < 4; h++)
files.Write(chain.blocks[h], chain.index[h]);
auto kinds = [&](int i) {
return i == iSeeded ? std::vector<Kind>{WRONG_ROOT, NO_NULLIFIER_VALID} : MixedKinds(i);
};
const SaplingOutPoint seeded(fx.txs[iSeeded].GetHash(), 0), sibling(fx.txs[iSeeded].GetHash(), 1);
std::map<SaplingOutPoint, NoteState> results[2];
int minHeight[2];
const char* threads[2] = {"1", "8"};
for (int r = 0; r < 2; r++) {
mapArgs["-witnessbuildthreads"] = threads[r];
RootsWallet wallet;
Fill(wallet, fx, chain, kinds);
wallet.SetWalletTip(chainActive.Tip());
wallet.MarkStatePersisted(chainActive.Tip());
minHeight[r] = wallet.VerifyAndSetInitialWitness(chainActive.Tip(), false);
results[r] = States(wallet);
const char* reason = wallet.ShutdownSaveSkipReason(true, true);
EXPECT_TRUE(reason == nullptr) << "the reseed changed a witness: " << (reason ? reason : "");
}
EXPECT_EQ(minHeight[0], minHeight[1]);
EXPECT_EQ(1, minHeight[0]) << "the reseeded note's witness is at its own block";
EXPECT_TRUE(results[0] == results[1]);
for (int r = 0; r < 2; r++) {
const NoteState& s = results[r].at(seeded);
EXPECT_FALSE(s.validated);
EXPECT_EQ(1, s.witnessHeight);
EXPECT_EQ(1u, s.nWitnesses);
EXPECT_TRUE(s.hasNullifier);
const NoteState& t = results[r].at(sibling);
EXPECT_TRUE(t.validated) << "the sibling's own witness is valid; threads " << threads[r];
EXPECT_EQ(2, t.witnessHeight);
EXPECT_TRUE(t.hasNullifier);
}
for (int i = 0; i < fx.nTxs; i++) {
if (i == iSeeded)
continue;
std::vector<Kind> ks = MixedKinds(i);
for (size_t n = 0; n < ks.size(); n++)
EXPECT_EQ(ks[n] != AHEAD_OF_CHAIN, results[1].at(SaplingOutPoint(fx.txs[i].GetHash(), n)).validated);
}
}
+16
View File
@@ -1713,6 +1713,22 @@ int32_t hush_checkPOW(int32_t slowflag,CBlock *pblock,int32_t height)
height = pprev->GetHeight() + 1; height = pprev->GetHeight() + 1;
if ( height == 0 ) if ( height == 0 )
return(0); return(0);
// The CheckRandomXSolution() above ran with height==0, where RandomXValidationRequired(0)
// is false, so RandomX was NOT verified. Re-verify now that the real height is recovered
// from hashPrevBlock. Without this, a peer block entering via ProcessNewBlock(0,0,...) (the
// net BLOCK handler, main.cpp) becomes a setBlockIndexCandidate with its PoW never checked
// at its real height: both CheckBlock() calls on that accept path pass fCheckPOW=0, so
// CheckBlockHeader's RandomX check never runs there -- this hush_checkPOW(0,...) is the ONLY
// real-height PoW gate before candidacy. A forged-RandomX fork could then trip the reorg
// guard before the connect-time check rejects it. This is a no-op wherever the first call
// was already a no-op: RandomXValidationRequired() gates on algo, the activation height
// (regtest heights are far below it), HUSH_LOADINGBLOCKS (IBD/reindex), and the last
// in-index checkpoint, and the thread-local fSkipRandomXValidation still skips the miner self-check.
if ( !CheckRandomXSolution(pblock, height) )
{
fprintf(stderr,"hush_checkPOW slowflag.%d ht.%d CheckRandomXSolution failed (post height-recovery)\n",slowflag,height);
return(-1);
}
} }
if ( (SMART_CHAIN_SYMBOL[0] != 0) && bhash > bnTarget ) { if ( (SMART_CHAIN_SYMBOL[0] != 0) && bhash > bnTarget ) {
+9
View File
@@ -32,6 +32,15 @@
#define CRYPTO555_PUBSECPSTR "038a1bd41a08f38edda51042988022933c5775dfce81f7bae0b32a9179650352ac" #define CRYPTO555_PUBSECPSTR "038a1bd41a08f38edda51042988022933c5775dfce81f7bae0b32a9179650352ac"
#define CRYPTO555_HUSHADDR "RFetqf8WUfWnwNeXdknkm8ojk7EXnYFzrv" #define CRYPTO555_HUSHADDR "RFetqf8WUfWnwNeXdknkm8ojk7EXnYFzrv"
#define CRYPTO555_RMD160STR "deadbeefbadcaca748c4986b240ff7d7bc3fffb0" #define CRYPTO555_RMD160STR "deadbeefbadcaca748c4986b240ff7d7bc3fffb0"
// DragonX: block time at/after which the inherited CRYPTO555/notary transparent-vout exemption on
// the fully-private chain is removed, so those vouts become invalid like any other taddr. Dropping
// a previously-accepted output is a consensus change, so it is activated by block time (same
// mechanism as HUSH_SAPING_ACTIVATION) to let the whole network upgrade before it bites.
// 0xFFFFFFFF is a SENTINEL meaning "never active": the operator sets a real future timestamp once
// the upgrade window has passed AND they have confirmed no active dPoW notarization posts
// transparent notary vouts on-chain (which this ban would otherwise reject). Until then this commit
// is a no-op and changes no validation behavior.
#define DRAGONX_NOTARYVOUT_BAN_TIME 0xFFFFFFFF
#define HUSH_FIRSTFUNGIBLEID 100 #define HUSH_FIRSTFUNGIBLEID 100
#define HUSH_SAPING_ACTIVATION 1544832000 // Dec 15th, 2018 #define HUSH_SAPING_ACTIVATION 1544832000 // Dec 15th, 2018
#define HUSH_SAPING_DEADLINE 1550188800 // Feb 15th, 2019 #define HUSH_SAPING_DEADLINE 1550188800 // Feb 15th, 2019
+2 -2
View File
@@ -660,7 +660,7 @@ void hush_nSPVreq(CNode *pfrom,std::vector<uint8_t> request) // received a reque
struct NSPV_utxosresp U; struct NSPV_utxosresp U;
if ( len >= 2 && len < 64+5 && request[1] < 64 && (request[1] == len-3 || request[1] == len-7 || request[1] == len-11) ) if ( len >= 2 && len < 64+5 && request[1] < 64 && (request[1] == len-3 || request[1] == len-7 || request[1] == len-11) )
{ {
int32_t skipcount = 0; char coinaddr[64]; uint32_t filter; uint8_t isCC = 0; int32_t skipcount = 0; char coinaddr[64]; uint32_t filter = 0; uint8_t isCC = 0; // only assigned on the len-11 form; the other two passed it on uninitialized
memcpy(coinaddr,&request[2],request[1]); // request[1] < 64 bounds the copy + the terminator write memcpy(coinaddr,&request[2],request[1]); // request[1] < 64 bounds the copy + the terminator write
coinaddr[request[1]] = 0; coinaddr[request[1]] = 0;
if ( request[1] == len-3 ) if ( request[1] == len-3 )
@@ -698,7 +698,7 @@ void hush_nSPVreq(CNode *pfrom,std::vector<uint8_t> request) // received a reque
struct NSPV_txidsresp T; struct NSPV_txidsresp T;
if ( len >= 2 && len < 64+5 && request[1] < 64 && (request[1] == len-3 || request[1] == len-7 || request[1] == len-11) ) if ( len >= 2 && len < 64+5 && request[1] < 64 && (request[1] == len-3 || request[1] == len-7 || request[1] == len-11) )
{ {
int32_t skipcount = 0; char coinaddr[64]; uint32_t filter; uint8_t isCC = 0; int32_t skipcount = 0; char coinaddr[64]; uint32_t filter = 0; uint8_t isCC = 0; // only assigned on the len-11 form; the other two passed it on uninitialized
memcpy(coinaddr,&request[2],request[1]); // request[1] < 64 bounds the copy + the terminator write memcpy(coinaddr,&request[2],request[1]); // request[1] < 64 bounds the copy + the terminator write
coinaddr[request[1]] = 0; coinaddr[request[1]] = 0;
if ( request[1] == len-3 ) if ( request[1] == len-3 )
+21 -5
View File
@@ -1383,8 +1383,14 @@ void hush_configfile(char *symbol,uint16_t rpcport)
#endif #endif
} else { } else {
_hush_userpass(myusername,mypassword,fp); _hush_userpass(myusername,mypassword,fp);
mapArgs["-rpcpassword"] = mypassword; // Feed the credentials read by InitRPCAuthentication (httprpc.cpp) and the
mapArgs["-rpcusername"] = myusername; // CLI (bitcoin-cli.cpp) -- both read "-rpcuser"/"-rpcpassword". Use SoftSetArg
// so a value passed on the command line (or an explicit -rpcuser/-rpcpassword)
// still wins: the old direct assignment silently overwrote a command-line
// -rpcpassword on every restart once this conf existed, and the username was
// written to a misspelled "-rpcusername" key that nothing ever reads.
SoftSetArg("-rpcpassword", mypassword);
SoftSetArg("-rpcuser", myusername);
fclose(fp); fclose(fp);
} }
} }
@@ -1777,11 +1783,21 @@ void hush_args(char *argv0)
fprintf(stderr,".oO Starting %s Full Node (Extreme Privacy!) with genproc=%d notary=%d\n",name.c_str(),HUSH_MININGTHREADS, IS_HUSH_NOTARY); fprintf(stderr,".oO Starting %s Full Node (Extreme Privacy!) with genproc=%d notary=%d\n",name.c_str(),HUSH_MININGTHREADS, IS_HUSH_NOTARY);
vector<string> DRAGONX_nodes = {}; vector<string> DRAGONX_nodes = {};
// Only DRAGONX connects to these by default, other chains must opt-in via -connect/-addnode // Only DRAGONX connects to these by default, other chains must opt-in via -connect/-addnode.
// Never on regtest or testnet: regtest reuses mainnet's network magic, so injecting the mainnet
// seeds here makes a supposedly isolated node handshake production peers and pull their headers
// into its own index -- which is exactly what it did, and why multi-node rpc-tests were talking
// to the live chain. NOTE: hush_args() runs between ParseParameters() and ReadConfigFile()
// (bitcoind.cpp:115/144/158), so this sees a command-line -regtest (how qa/rpc-tests starts
// nodes) but NOT a bare "regtest=1" in the config file.
const bool isdragonx = strncmp(name.c_str(), "DRAGONX",7) == 0 ? true : false; const bool isdragonx = strncmp(name.c_str(), "DRAGONX",7) == 0 ? true : false;
LogPrint("net", "%s: isdragonx=%d\n", __func__, isdragonx); // Seed injection only -- isdragonx itself must stay true here, because it also selects
if (isdragonx) { // ac_private, ac_algo, blocktime and the reward/halving schedule below.
const bool isnotmainnet = GetBoolArg("-regtest", false) || GetBoolArg("-testnet", false);
LogPrint("net", "%s: isdragonx=%d isnotmainnet=%d\n", __func__, isdragonx, isnotmainnet);
if (isdragonx && !isnotmainnet) {
// node8-node10 are PLACEHOLDERS with no DNS records yet. A hostname that // node8-node10 are PLACEHOLDERS with no DNS records yet. A hostname that
// does not resolve is harmless here: ThreadOpenAddedConnections just fails // does not resolve is harmless here: ThreadOpenAddedConnections just fails
// to open the connection and retries on its 2-minute cycle. Reserving the // to open the connection and retries on its 2-minute cycle. Reserving the
+386 -76
View File
@@ -79,6 +79,7 @@
#include <boost/function.hpp> #include <boost/function.hpp>
#include <boost/interprocess/sync/file_lock.hpp> #include <boost/interprocess/sync/file_lock.hpp>
#include <boost/thread.hpp> #include <boost/thread.hpp>
#include <leveldb/env.h>
#include <chrono> #include <chrono>
#include <wolfssl/options.h> #include <wolfssl/options.h>
#include <wolfssl/ssl.h> #include <wolfssl/ssl.h>
@@ -99,6 +100,9 @@ extern void hush_init(int32_t height);
CWallet* pwalletMain = NULL; CWallet* pwalletMain = NULL;
#endif #endif
bool fFeeEstimatesInitialized = false; bool fFeeEstimatesInitialized = false;
// AppInit2 ran to the end and is returning success, so AppInit joins every thread before Shutdown().
// On any other path Shutdown() runs with threads only interrupted and must not write wallet state.
static std::atomic<bool> fInitCompleted(false);
#ifdef WIN32 #ifdef WIN32
// Win32 LevelDB doesn't use file descriptors, and the ones used for // Win32 LevelDB doesn't use file descriptors, and the ones used for
@@ -125,6 +129,152 @@ static const char* DEFAULT_ASMAP_FILENAME="asmap.dat";
// in-memory cache the DB is opened with; the value here does not affect validation. // in-memory cache the DB is opened with; the value here does not affect validation.
static const size_t NOTARIZATION_DB_CACHE_BYTES = 100 * 1024 * 1024; // 100 MiB static const size_t NOTARIZATION_DB_CACHE_BYTES = 100 * 1024 * 1024; // 100 MiB
// How long AppInit2() waits for another process to release notarizations/LOCK before it gives up and
// runs on an in-memory notarizations DB.
static const int NOTARIZATION_LOCK_WAIT_SECONDS = 30;
/**
* Try to take <dbdir>/LOCK with LevelDB's own Env::LockFile, i.e. the same lock DB::Open takes, and
* release it at once. ok() means the lock is free (a missing LOCK file cannot be held). Anything else
* means it could not be taken: usually another process holds it ("Resource temporarily unavailable"),
* but it may also be e.g. a permission error. The caller treats every non-ok status as held, and so
* never moves or wipes the directory on its strength.
*/
static leveldb::Status ProbeLevelDBLock(const boost::filesystem::path& dbdir)
{
const boost::filesystem::path lockpath = dbdir / "LOCK";
boost::system::error_code ec;
if (!boost::filesystem::exists(lockpath, ec))
return leveldb::Status::OK();
leveldb::Env* env = leveldb::Env::Default();
leveldb::FileLock* lock = NULL;
leveldb::Status status = env->LockFile(lockpath.string(), &lock);
if (status.ok())
env->UnlockFile(lock);
return status;
}
/**
* Does <dbdir> hold any LevelDB data, i.e. a non-empty table (.ldb/.sst) or write-ahead log (.log)?
* CURRENT, MANIFEST-*, LOCK and the LOG/LOG.old info logs carry no records. When in doubt (the
* directory cannot be listed) say yes, so the caller keeps a copy.
*/
static bool LevelDBDirHasData(const boost::filesystem::path& dbdir)
{
boost::system::error_code ec;
if (!boost::filesystem::exists(dbdir, ec))
return ec ? true : false;
boost::filesystem::directory_iterator it(dbdir, ec), end;
if (ec)
return true;
for (; it != end; it.increment(ec)) {
if (ec)
return true;
const std::string ext = it->path().extension().string();
if (ext != ".ldb" && ext != ".sst" && ext != ".log")
continue;
boost::system::error_code sizeEc;
const uintmax_t size = boost::filesystem::file_size(it->path(), sizeEc);
if (sizeEc || size > 0)
return true;
}
return false;
}
/**
* Open the notarizations (dPoW) DB. It is non-essential and node-regenerable, so nothing here may fail
* startup (previously any open failure surfaced as a spurious "Error opening block database"):
* - LOCK cannot be taken (typically a previous dragonxd that is still exiting): wait up to
* NOTARIZATION_LOCK_WAIT_SECONDS for it and retry; if it is still held, run this session on an
* in-memory DB and leave the on-disk one alone.
* - otherwise the DB is unreadable (seen: a torn snapshot, 0-byte log -> leveldb "Database I/O error"):
* move it aside under a timestamped notarizations.corrupt-* name, never deleting an earlier copy, and
* create a fresh one. A directory holding no data is recreated in place instead, so a persistent
* failure (e.g. disk full) does not add another empty copy on every start. If even that fails, fall
* back to an in-memory DB.
* The lock is probed only after an open fails, so a holder that exits between the failed open and the
* probe makes the probe report "free" for a DB that is fine. The DB is therefore treated as corrupt only
* when an open fails although the probe just before that open found the lock free.
*/
static NotarizationDB* OpenNotarizationDB(bool fWipe)
{
const boost::filesystem::path ndir = GetDataDir() / "notarizations";
std::string strError;
bool fWaited = false; // the bounded wait for the lock has been used up
bool fProbedFree = false; // the probe right before the last open attempt found the lock free
int64_t nWaitStart = 0;
while (true) {
try {
NotarizationDB* pdb = new NotarizationDB(NOTARIZATION_DB_CACHE_BYTES, false, fWipe);
if (fWaited)
LogPrintf("%s: notarizations/LOCK released after %d s; notarizations DB opened\n", __func__, (GetTimeMillis() - nWaitStart) / 1000);
else if (fProbedFree)
LogPrintf("%s: notarizations DB opened on retry (notarizations/LOCK was released after the first attempt)\n", __func__);
return pdb;
} catch (const std::exception& e) {
strError = e.what();
}
if (fProbedFree)
break; // failed with the lock free beforehand: genuinely unreadable
leveldb::Status lockStatus = ProbeLevelDBLock(ndir);
if (!lockStatus.ok()) {
if (!fWaited) {
LogPrintf("%s: notarizations DB failed to open (%s): notarizations/LOCK could not be taken (%s); waiting for a previous dragonxd to release notarizations/LOCK (up to %d s)\n",
__func__, strError, lockStatus.ToString(), NOTARIZATION_LOCK_WAIT_SECONDS);
fWaited = true;
nWaitStart = GetTimeMillis();
const int64_t nDeadline = nWaitStart + NOTARIZATION_LOCK_WAIT_SECONDS * 1000LL;
while (GetTimeMillis() < nDeadline && !ShutdownRequested()) {
MilliSleep(std::min<int64_t>(1000, std::max<int64_t>(1, nDeadline - GetTimeMillis())));
lockStatus = ProbeLevelDBLock(ndir);
if (lockStatus.ok())
break;
}
}
if (!lockStatus.ok()) {
LogPrintf("%s: notarizations/LOCK still could not be taken after %d s (%s); using an in-memory notarizations DB for this run (on-disk notarizations DB left untouched)\n",
__func__, (GetTimeMillis() - nWaitStart) / 1000, lockStatus.ToString());
return new NotarizationDB(NOTARIZATION_DB_CACHE_BYTES, true, false);
}
}
// The lock is free now: open once more before calling the DB corrupt.
fProbedFree = true;
}
if (!LevelDBDirHasData(ndir)) {
LogPrintf("%s: notarizations DB failed to open (%s) and holds no data; recreating it in place (non-fatal)\n", __func__, strError);
try {
return new NotarizationDB(NOTARIZATION_DB_CACHE_BYTES, false, true);
} catch (const std::exception& e) {
LogPrintf("%s: could not recreate the notarizations DB (%s); using an in-memory notarizations DB for this run\n", __func__, e.what());
return new NotarizationDB(NOTARIZATION_DB_CACHE_BYTES, true, false);
}
}
LogPrintf("%s: notarizations DB failed to open (%s); moving aside and regenerating (non-fatal)\n", __func__, strError);
// Move (do NOT delete) the old DB aside, so a transient open failure (fd exhaustion, disk full,
// permissions) cannot permanently destroy notarization history. Earlier copies are kept too.
try {
const std::string base = ndir.string() + ".corrupt-" + DateTimeStrFormat("%Y%m%d-%H%M%S", GetTime());
boost::filesystem::path aside(base);
for (int i = 1; boost::filesystem::exists(aside); i++)
aside = base + strprintf(".%d", i);
boost::filesystem::rename(ndir, aside);
LogPrintf("%s: moved the old notarizations DB to %s\n", __func__, aside.string());
} catch (const std::exception& e) {
LogPrintf("%s: could not move the notarizations DB aside (%s); using an in-memory notarizations DB for this run (on-disk notarizations DB left untouched)\n",
__func__, e.what());
return new NotarizationDB(NOTARIZATION_DB_CACHE_BYTES, true, false);
}
try {
return new NotarizationDB(NOTARIZATION_DB_CACHE_BYTES, false, true);
} catch (const std::exception& e) {
LogPrintf("%s: could not recreate the notarizations DB (%s); using an in-memory notarizations DB for this run\n", __func__, e.what());
return new NotarizationDB(NOTARIZATION_DB_CACHE_BYTES, true, false);
}
}
CClientUIInterface uiInterface; // global UI callback dispatcher (declared extern in ui_interface.h) CClientUIInterface uiInterface; // global UI callback dispatcher (declared extern in ui_interface.h)
// Shutdown // Shutdown
@@ -211,9 +361,9 @@ void Shutdown()
/// for example if the data directory was found to be locked. /// for example if the data directory was found to be locked.
/// Be sure that anything that writes files or flushes caches only does this if the respective /// Be sure that anything that writes files or flushes caches only does this if the respective
/// module was initialized. /// module was initialized.
static char shutoffstr[128]; // Do not RenameThread() here: Shutdown() runs on the main thread, whose name is the process name
sprintf(shutoffstr,"%s-shutoff","hush"); // (/proc/<pid>/comm). Renaming it made 'pgrep -x dragonxd' stop matching a node that was still
RenameThread(shutoffstr); // shutting down and holding its locks, so pgrep-based restart scripts relaunched it too early.
mempool.AddTransactionsUpdated(1); mempool.AddTransactionsUpdated(1);
if(fDebug) { if(fDebug) {
@@ -256,7 +406,15 @@ void Shutdown()
{ {
LOCK(cs_main); LOCK(cs_main);
if (pcoinsTip != NULL) { if (pcoinsTip != NULL) {
FlushStateToDisk(); bool fChainstateFlushed = FlushStateToDisk();
#ifdef ENABLE_WALLET
// The hourly SetBestChain in FlushStateToDisk rarely fires here, so a session shorter
// than an hour would otherwise never save its witnesses and best block.
if (pwalletMain)
pwalletMain->PersistStateAtShutdown(fInitCompleted, fChainstateFlushed);
#else
(void)fChainstateFlushed;
#endif
} }
if (pcoinsTip != NULL) { if (pcoinsTip != NULL) {
delete pcoinsTip; delete pcoinsTip;
@@ -274,6 +432,13 @@ void Shutdown()
delete pblocktree; delete pblocktree;
pblocktree = NULL; pblocktree = NULL;
} }
// Close the notarizations DB with the other LevelDBs. It used to be left open until process
// teardown, which made notarizations/LOCK the one LevelDB lock still held after "Shutdown: done"
// (and after the datadir .lock was released), so a quickly restarted successor failed to open it.
if (pnotarizations != NULL) {
delete pnotarizations;
pnotarizations = NULL;
}
} }
#ifdef ENABLE_WALLET #ifdef ENABLE_WALLET
if (pwalletMain) if (pwalletMain)
@@ -479,15 +644,18 @@ std::string HelpMessage(HelpMessageMode mode)
strUsage += HelpMessageOpt("-usemnemonic", strprintf(_("Create new wallets from a fresh BIP39 seed phrase so the 24 words can be exported (z_exportmnemonic) and used in SilentDragonXLite. Set to 0 for a raw random seed with no recovery phrase; existing wallets are never changed (default: %u)"), 1)); strUsage += HelpMessageOpt("-usemnemonic", strprintf(_("Create new wallets from a fresh BIP39 seed phrase so the 24 words can be exported (z_exportmnemonic) and used in SilentDragonXLite. Set to 0 for a raw random seed with no recovery phrase; existing wallets are never changed (default: %u)"), 1));
strUsage += HelpMessageOpt("-hdtransparentgaplimit=<n>", strprintf(_("On -mnemonic/-hdseed restore, pre-derive this many HD transparent keys so a rescan can find coinbase paid to them (default: %u)"), 1000)); strUsage += HelpMessageOpt("-hdtransparentgaplimit=<n>", strprintf(_("On -mnemonic/-hdseed restore, pre-derive this many HD transparent keys so a rescan can find coinbase paid to them (default: %u)"), 1000));
strUsage += HelpMessageOpt("-mnemonicsaplinggap=<n>", strprintf(_("On -mnemonic/-hdseed restore, pre-derive this many shielded (Sapling) addresses so a rescan can find notes sent to them (default: %u)"), 100)); strUsage += HelpMessageOpt("-mnemonicsaplinggap=<n>", strprintf(_("On -mnemonic/-hdseed restore, pre-derive this many shielded (Sapling) addresses so a rescan can find notes sent to them (default: %u)"), 100));
strUsage += HelpMessageOpt("-consolidation", _("Enable auto Sapling note consolidation (default: false)")); strUsage += HelpMessageOpt("-consolidation", _("Periodically merge the notes of every address holding more than -consolidationthreshold spendable notes back into that address (default: false; z_consolidate runs a round on demand)"));
strUsage += HelpMessageOpt("-consolidationinterval", _("Block interval between consolidations (default: 25)")); strUsage += HelpMessageOpt("-consolidationinterval", strprintf(_("Block interval between consolidation rounds (default: %i, min %i)"), DEFAULT_CONSOLIDATION_INTERVAL, MIN_CONSOLIDATION_INTERVAL));
strUsage += HelpMessageOpt("-consolidatesaplingaddress=<zaddr>", _("Specify Sapling Address to Consolidate. (default: all)")); strUsage += HelpMessageOpt("-consolidationthreshold", strprintf(_("Only consolidate addresses with more than this many spendable notes (default: %i)"), DEFAULT_CONSOLIDATION_THRESHOLD));
strUsage += HelpMessageOpt("-consolidationtxfee", strprintf(_("Fee amount in Puposhis used send consolidation transactions. (default %i)"), DEFAULT_CONSOLIDATION_FEE)); strUsage += HelpMessageOpt("-consolidationbatchsize", strprintf(_("Most notes one consolidation transaction spends, smallest first (default: %i, %i to %i)"), DEFAULT_CONSOLIDATION_BATCHSIZE, MIN_CONSOLIDATION_BATCHSIZE, MAX_CONSOLIDATION_BATCHSIZE));
strUsage += HelpMessageOpt("-consolidationmaxtxs", strprintf(_("Most consolidation transactions per address per round (default: %i, max %i)"), DEFAULT_CONSOLIDATION_MAXTXS, MAX_CONSOLIDATION_MAXTXS));
strUsage += HelpMessageOpt("-consolidatesaplingaddress=<zaddr>", _("Only consolidate this Sapling address; may be repeated. The wallet must hold its spending key (default: all)"));
strUsage += HelpMessageOpt("-consolidationtxfee", strprintf(_("Fee in puposhis per consolidation transaction (default: %i, range %i to %i)"), DEFAULT_CONSOLIDATION_FEE, CONSOLIDATION_MIN_FEE, CONSOLIDATION_MAX_FEE));
strUsage += HelpMessageOpt("-zsweep", _("Enable zaddr sweeping, automatically move all shielded funds to a one address once per X blocks")); strUsage += HelpMessageOpt("-zsweep", _("Enable zaddr sweeping, automatically move all shielded funds to a one address once per X blocks"));
strUsage += HelpMessageOpt("-zsweepaddress=<zaddr>", _("Specify the shielded address where swept funds will be sent)")); strUsage += HelpMessageOpt("-zsweepaddress=<zaddr>", _("Specify the shielded address where swept funds will be sent)"));
strUsage += HelpMessageOpt("-zsweepfee", strprintf(_("Fee amount in puposhis used send sweep transactions. (default %i)"), DEFAULT_SWEEP_FEE)); strUsage += HelpMessageOpt("-zsweepfee", strprintf(_("Fee amount in puposhis used send sweep transactions. (default %i)"), DEFAULT_SWEEP_FEE));
strUsage += HelpMessageOpt("-zsweepinterval", strprintf(_("Sweep shielded funds every X blocks (default %i)"), 5)); strUsage += HelpMessageOpt("-zsweepinterval", strprintf(_("Sweep shielded funds every X blocks (default %i)"), 10));
strUsage += HelpMessageOpt("-zsweepmaxinputs", strprintf(_("Maximum number of shielded inputs to sweep per transaction (default %i)"), 8)); strUsage += HelpMessageOpt("-zsweepmaxinputs", strprintf(_("Maximum number of shielded inputs to sweep per transaction (default %i)"), 8));
// By default we only allow sweeping to the current wallet which must have the spending key of the sweep zaddr // By default we only allow sweeping to the current wallet which must have the spending key of the sweep zaddr
// This hopefully will make it harder for people to accidentally sweep funds to a wrong zaddr and lose funds // This hopefully will make it harder for people to accidentally sweep funds to a wrong zaddr and lose funds
@@ -513,7 +681,13 @@ std::string HelpMessage(HelpMessageMode mode)
// If this is used incorrectly (-rescanheight too large), then the local wallet may attempt to spend funds which it does not have witness data about // If this is used incorrectly (-rescanheight too large), then the local wallet may attempt to spend funds which it does not have witness data about
// which will cause a "missing inputs" error when added to the mempool. Rescanning from correct height will fix this. // which will cause a "missing inputs" error when added to the mempool. Rescanning from correct height will fix this.
strUsage += HelpMessageOpt("-keepnotewitnesscache", _("Keep partial Sapling Note Witness cache. Must be used with -rescanheight to find missing cache items.")); strUsage += HelpMessageOpt("-keepnotewitnesscache", _("Keep partial Sapling Note Witness cache. Must be used with -rescanheight to find missing cache items."));
if (showDebug)
strUsage += HelpMessageOpt("-notecachewarmup", "Decrypt all wallet notes into memory at startup, so the first balance call after a restart doesn't (default: 1)");
if (showDebug)
strUsage += HelpMessageOpt("-checknotecache", "On every balance or note-listing call, decrypt each cached note it considers again and log and repair any difference from the cache (slow; default: 0)");
strUsage += HelpMessageOpt("-rescan", _("Rescan the block chain for missing wallet transactions") + " " + _("on startup")); strUsage += HelpMessageOpt("-rescan", _("Rescan the block chain for missing wallet transactions") + " " + _("on startup"));
strUsage += HelpMessageOpt("-walletsaveatshutdown", "Save the note witnesses and best block at a clean shutdown, so the next start does not rescan the session's blocks. "
"On a large wallet this can add a minute or more to the stop (default: 1)");
strUsage += HelpMessageOpt("-rescanheight", _("Rescan from specified height when rescan=1 on startup")); strUsage += HelpMessageOpt("-rescanheight", _("Rescan from specified height when rescan=1 on startup"));
strUsage += HelpMessageOpt("-salvagewallet", _("Attempt to recover private keys from a corrupt wallet.dat") + " " + _("on startup")); strUsage += HelpMessageOpt("-salvagewallet", _("Attempt to recover private keys from a corrupt wallet.dat") + " " + _("on startup"));
strUsage += HelpMessageOpt("-sendfreetransactions", strprintf(_("Send transactions as zero-fee transactions if possible (default: %u)"), 0)); strUsage += HelpMessageOpt("-sendfreetransactions", strprintf(_("Send transactions as zero-fee transactions if possible (default: %u)"), 0));
@@ -1016,7 +1190,8 @@ extern int32_t HUSH_REWIND;
// --- Adaptive coins-cache sizing ------------------------------------------------------------- // --- Adaptive coins-cache sizing -------------------------------------------------------------
// The in-memory UTXO/coins cache (nCoinCacheUsage) is the biggest lever on IBD speed: a bigger // The in-memory UTXO/coins cache (nCoinCacheUsage) is the biggest lever on IBD speed: a bigger
// cache means far fewer chainstate flushes to disk. We size it to use most of RAM, but a scheduled // cache means fewer size-triggered chainstate flushes to disk (the chainstate is also flushed at
// least every DATABASE_FLUSH_INTERVAL / DATABASE_FLUSH_BLOCKS, see main.h). We size it to use most of RAM, but a scheduled
// background task (AdjustCoinCacheForMemoryPressure, registered in AppInit2) shrinks the target when // background task (AdjustCoinCacheForMemoryPressure, registered in AppInit2) shrinks the target when
// free system memory runs low — e.g. the user opens other apps — and grows it back when memory frees // free system memory runs low — e.g. the user opens other apps — and grows it back when memory frees
// up, always leaving a reserve free for the rest of the system. The existing per-block flush // up, always leaving a reserve free for the rest of the system. The existing per-block flush
@@ -1432,7 +1607,13 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler)
mempool.setSanityCheck(1.0 / ratio); mempool.setSanityCheck(1.0 / ratio);
} }
fCheckBlockIndex = GetBoolArg("-checkblockindex", chainparams.DefaultConsistencyChecks()); fCheckBlockIndex = GetBoolArg("-checkblockindex", chainparams.DefaultConsistencyChecks());
fCheckpointsEnabled = GetBoolArg("-checkpoints", true); // Regtest inherits the DRAGONX *mainnet* checkpoint set (chainparams_commandline applies it
// for every SMART_CHAIN_SYMBOL=="DRAGONX" network, regardless of -regtest), whose top height
// ~3.2M would otherwise pin an isolated regtest chain in IsInitialBlockDownload() forever --
// disabling the ChainTip auto-ops (autoshield/sweep/consolidation) and the below-checkpoint
// script-check skip. Default checkpoints OFF on regtest so a fresh regtest node leaves IBD
// normally; still overridable with -checkpoints=1.
fCheckpointsEnabled = GetBoolArg("-checkpoints", chainparams.NetworkIDString() != "regtest");
// -par=0 means autodetect, but nScriptCheckThreads==0 means no concurrency // -par=0 means autodetect, but nScriptCheckThreads==0 means no concurrency
nScriptCheckThreads = GetArg("-par", DEFAULT_SCRIPTCHECK_THREADS); nScriptCheckThreads = GetArg("-par", DEFAULT_SCRIPTCHECK_THREADS);
@@ -2064,35 +2245,19 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler)
do { do {
try { try {
UnloadBlockIndex(); UnloadBlockIndex();
delete pcoinsTip; // Shutdown() deletes (and pcoinsTip: flushes) whatever is non-NULL here, so never leave
delete pcoinsdbview; // a pointer dangling if one of the reopens below throws.
delete pcoinscatcher; delete pcoinsTip; pcoinsTip = NULL;
delete pblocktree; delete pcoinsdbview; pcoinsdbview = NULL;
delete pnotarizations; delete pcoinscatcher; pcoinscatcher = NULL;
delete pblocktree; pblocktree = NULL;
delete pnotarizations; pnotarizations = NULL;
pblocktree = new CBlockTreeDB(nBlockTreeDBCache, false, fReindex, dbCompression, dbMaxOpenFiles); pblocktree = new CBlockTreeDB(nBlockTreeDBCache, false, fReindex, dbCompression, dbMaxOpenFiles);
pcoinsdbview = new CCoinsViewDB(nCoinDBCache, false, fReindex); pcoinsdbview = new CCoinsViewDB(nCoinDBCache, false, fReindex);
pcoinscatcher = new CCoinsViewErrorCatcher(pcoinsdbview); pcoinscatcher = new CCoinsViewErrorCatcher(pcoinsdbview);
pcoinsTip = new CCoinsViewCache(pcoinscatcher); pcoinsTip = new CCoinsViewCache(pcoinscatcher);
try { pnotarizations = OpenNotarizationDB(fReindex);
pnotarizations = new NotarizationDB(NOTARIZATION_DB_CACHE_BYTES, false, fReindex);
} catch (const std::exception& e) {
// The notarizations (dPoW) DB is non-essential and node-regenerable. It has been seen to
// snapshot/flush torn (0-byte log -> leveldb "Database I/O error" on reopen), which
// previously aborted startup with a spurious "Error opening block database" and forced a
// full resync. Wipe and recreate it instead of failing hard.
LogPrintf("%s: notarizations DB failed to open (%s); moving aside and regenerating (non-fatal)\n", __FUNCTION__, e.what());
// Move (do NOT delete) the old DB aside, so a transient open failure (fd
// exhaustion, disk full, permissions) cannot permanently destroy notarization
// history. If the recreate below also fails it propagates as fatal and the old
// data survives in notarizations.corrupt for recovery.
{
boost::filesystem::path ndir = GetDataDir() / "notarizations";
boost::filesystem::remove_all(ndir.string() + ".corrupt");
boost::filesystem::rename(ndir, ndir.string() + ".corrupt");
}
pnotarizations = new NotarizationDB(NOTARIZATION_DB_CACHE_BYTES, false, true);
}
if (fReindex) { if (fReindex) {
@@ -2223,6 +2388,9 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler)
// ********************************************************* Step 8: load wallet // ********************************************************* Step 8: load wallet
#ifdef ENABLE_WALLET #ifdef ENABLE_WALLET
// Set when the startup rescan below is interrupted: the wallet's state then ends at the scan's
// own checkpoint, not at the tip the notifier starts from.
bool fWalletScanIncomplete = false;
if (fDisableWallet) { if (fDisableWallet) {
pwalletMain = NULL; pwalletMain = NULL;
LogPrintf("Wallet disabled!\n"); LogPrintf("Wallet disabled!\n");
@@ -2254,10 +2422,22 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler)
if (nLoadWalletRet != DB_LOAD_OK) if (nLoadWalletRet != DB_LOAD_OK)
{ {
if (nLoadWalletRet == DB_CORRUPT) if (nLoadWalletRet == DB_CORRUPT)
strErrors << _("Error loading wallet.dat: Wallet corrupted. If this wallet was last opened " {
"by an older version, move wallet.dat aside and restore from your seed " // Abort HERE, as the DB_NEED_REWRITE branch below already does. Falling through
"phrase with -mnemonic=\"<your seed phrase>\" -rescan (see debug.log for " // runs several hundred more lines of initialisation against a wallet we have just
"the specific record at fault).") << "\n"; // declared corrupt -- including SetHDSeedOrigin(), which WRITES to it, and the
// rescan and SetBestChain that follow.
//
// The old text advised restoring with -mnemonic. That is wrong twice over:
// -usemnemonic defaulted to 0 in v1.0.3 so many such wallets never had a phrase,
// and SetHDSeedFromMnemonic refuses a non-empty wallet, so "move wallet.dat aside"
// would discard every non-HD key the salvage preserved.
strErrors << _("Error loading wallet.dat: the wallet database is corrupt. Your keys may "
"still be intact -- do NOT delete or replace wallet.dat. Back it up now, "
"and see debug.log for the specific record at fault.") << "\n";
LogPrintf("%s", strErrors.str());
return InitError(strErrors.str());
}
else if (nLoadWalletRet == DB_NONCRITICAL_ERROR) else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
{ {
string msg(_("Warning: error reading wallet.dat! All keys read correctly, but transaction data" string msg(_("Warning: error reading wallet.dat! All keys read correctly, but transaction data"
@@ -2383,32 +2563,58 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler)
LogPrintf("%s: HD seed predates seed-provenance recording; recorded origin as unknown\n", __func__); LogPrintf("%s: HD seed predates seed-provenance recording; recorded origin as unknown\n", __func__);
} }
//Set Sapling Consolidation //Set Sapling Consolidation. The policy is read even with -consolidation off: z_consolidate
//runs rounds on demand with it.
pwalletMain->fSaplingConsolidationEnabled = GetBoolArg("-consolidation", false); pwalletMain->fSaplingConsolidationEnabled = GetBoolArg("-consolidation", false);
if(pwalletMain->fSaplingConsolidationEnabled) { {
fConsolidationTxFee = GetArg("-consolidationtxfee", DEFAULT_CONSOLIDATION_FEE); CAmount consolidationFee = GetArg("-consolidationtxfee", DEFAULT_CONSOLIDATION_FEE);
fConsolidationMapUsed = !mapMultiArgs["-consolidatesaplingaddress"].empty(); if (consolidationFee < CONSOLIDATION_MIN_FEE || consolidationFee > CONSOLIDATION_MAX_FEE) {
InitWarning(strprintf(_("-consolidationtxfee=%lld out of range [%lld,%lld], using default %lld"),
(long long)consolidationFee, (long long)CONSOLIDATION_MIN_FEE, (long long)CONSOLIDATION_MAX_FEE, (long long)DEFAULT_CONSOLIDATION_FEE));
consolidationFee = DEFAULT_CONSOLIDATION_FEE;
}
fConsolidationTxFee = consolidationFee;
int consolidationInterval = GetArg("-consolidationinterval", 25); int consolidationInterval = GetArg("-consolidationinterval", DEFAULT_CONSOLIDATION_INTERVAL);
if (consolidationInterval < 5) { if (consolidationInterval < MIN_CONSOLIDATION_INTERVAL) {
LogPrintf("%s: Invalid consolidation interval of %d < 5, setting to default of 25\n", __func__, consolidationInterval); InitWarning(strprintf(_("consolidation interval %d below the minimum, clamping to %d"),
consolidationInterval = 25; consolidationInterval, MIN_CONSOLIDATION_INTERVAL));
consolidationInterval = MIN_CONSOLIDATION_INTERVAL;
}
int consolidationThreshold = GetArg("-consolidationthreshold", DEFAULT_CONSOLIDATION_THRESHOLD);
if (consolidationThreshold < MIN_CONSOLIDATION_THRESHOLD) {
InitWarning(strprintf(_("-consolidationthreshold=%d below the minimum, clamping to %d"),
consolidationThreshold, MIN_CONSOLIDATION_THRESHOLD));
consolidationThreshold = MIN_CONSOLIDATION_THRESHOLD;
}
int consolidationBatchSize = GetArg("-consolidationbatchsize", DEFAULT_CONSOLIDATION_BATCHSIZE);
if (ClampSaplingConsolidationBatchSize(consolidationBatchSize) != consolidationBatchSize) {
InitWarning(strprintf(_("-consolidationbatchsize=%d out of range [%d,%d], clamping to %d"),
consolidationBatchSize, MIN_CONSOLIDATION_BATCHSIZE, MAX_CONSOLIDATION_BATCHSIZE,
ClampSaplingConsolidationBatchSize(consolidationBatchSize)));
consolidationBatchSize = ClampSaplingConsolidationBatchSize(consolidationBatchSize);
}
int consolidationMaxTxs = GetArg("-consolidationmaxtxs", DEFAULT_CONSOLIDATION_MAXTXS);
if (consolidationMaxTxs < 1 || consolidationMaxTxs > MAX_CONSOLIDATION_MAXTXS) {
int clamped = std::max(1, std::min(consolidationMaxTxs, MAX_CONSOLIDATION_MAXTXS));
InitWarning(strprintf(_("-consolidationmaxtxs=%d out of range [1,%d], clamping to %d"),
consolidationMaxTxs, MAX_CONSOLIDATION_MAXTXS, clamped));
consolidationMaxTxs = clamped;
} }
pwalletMain->consolidationInterval = consolidationInterval; pwalletMain->consolidationInterval = consolidationInterval;
pwalletMain->nextConsolidation = pwalletMain->consolidationInterval + chainActive.Height(); pwalletMain->consolidationThreshold = consolidationThreshold;
LogPrintf("%s: set nextConsolidation=%d\n", __func__, pwalletMain->nextConsolidation ); pwalletMain->consolidationBatchSize = consolidationBatchSize;
pwalletMain->consolidationMaxTxs = consolidationMaxTxs;
//Validate Sapling Addresses if (pwalletMain->fSaplingConsolidationEnabled) {
vector<string>& vaddresses = mapMultiArgs["-consolidatesaplingaddress"]; pwalletMain->nextConsolidation = pwalletMain->consolidationInterval + chainActive.Height();
for (int i = 0; i < vaddresses.size(); i++) { LogPrintf("%s: consolidation enabled, nextConsolidation=%d interval=%d threshold=%d batchsize=%d maxtxs=%d fee=%d\n",
LogPrintf("Consolidating Sapling Address: %s\n", vaddresses[i]); __func__, pwalletMain->nextConsolidation, consolidationInterval, consolidationThreshold,
auto zAddress = DecodePaymentAddress(vaddresses[i]); consolidationBatchSize, consolidationMaxTxs, (int)fConsolidationTxFee);
if (!IsValidPaymentAddress(zAddress)) {
return InitError("Invalid consolidation address");
}
} }
} }
// Set when -zsweep makes consolidation work on the sweep address (see below).
bool fConsolidateSweepAddress = false;
//Set Sweep //Set Sweep
pwalletMain->fSweepEnabled = GetBoolArg("-zsweep", false); pwalletMain->fSweepEnabled = GetBoolArg("-zsweep", false);
@@ -2465,21 +2671,63 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler)
pwalletMain->sweepExcludeAddresses.push_back( vSweepExclude[i] ); pwalletMain->sweepExcludeAddresses.push_back( vSweepExclude[i] );
} }
if (pwalletMain->fSaplingConsolidationEnabled) { // With sweep on, consolidation works on the sweep address only, also for z_consolidate with
//Validate 1 Consolidation address only that matches the sweep address // -consolidation off: the two would otherwise fight over the same notes and pay fees for nothing.
vector<string>& vaddresses = mapMultiArgs["-consolidatesaplingaddress"]; vector<string>& vaddresses = mapMultiArgs["-consolidatesaplingaddress"];
if (vaddresses.size() == 0) { bool fOtherAddress = false;
fConsolidationMapUsed = true; for (size_t i = 0; i < vaddresses.size(); i++)
mapMultiArgs["-consolidatesaplingaddress"] = vSweep; fOtherAddress |= vSweep[0] != vaddresses[i];
} else { if (fOtherAddress) {
pwalletMain->consolidationAddress = vaddresses[0]; if (pwalletMain->fSaplingConsolidationEnabled)
for (int i = 0; i < vaddresses.size(); i++) { return InitError("Consolidation can only be used on the sweep address when sweep is enabled.");
if (vSweep[0] != vaddresses[i]) { InitWarning(_("-consolidatesaplingaddress is not the sweep address; with -zsweep, consolidation only works on the sweep address"));
return InitError("Consolidation can only be used on the sweep address when sweep is enabled.");
}
}
}
} }
if (vaddresses.empty() || fOtherAddress) {
fConsolidateSweepAddress = true;
vaddresses = vSweep;
}
}
// The addresses consolidation works on: -consolidatesaplingaddress, or with -zsweep the sweep address.
// A user-given address must be one this wallet can spend, else every round would silently skip it.
// With -consolidation off, where older versions ignored the option, a bad one is only warned about
// and dropped; z_consolidate then works on all addresses unless given its own.
{
const vector<string>& vaddresses = mapMultiArgs["-consolidatesaplingaddress"];
pwalletMain->consolidationAddresses.clear();
pwalletMain->consolidationAddress.clear();
for (size_t i = 0; i < vaddresses.size(); i++) {
LogPrintf("Consolidating Sapling Address: %s\n", vaddresses[i]);
std::string strProblem;
auto zAddress = DecodePaymentAddress(vaddresses[i]);
if (!IsValidPaymentAddress(zAddress) ||
boost::get<libzcash::SaplingPaymentAddress>(&zAddress) == nullptr) {
strProblem = "Invalid consolidation address: -consolidatesaplingaddress must be a Sapling z-address";
} else if (!boost::apply_visitor(HaveSpendingKeyForPaymentAddress(pwalletMain), zAddress)) {
if (!fConsolidateSweepAddress)
strProblem = strprintf("Wallet must hold the spending key of -consolidatesaplingaddress %s", vaddresses[i]);
else
LogPrintf("%s: the zsweep address is external to this wallet, so consolidation has nothing to do\n", __func__);
}
if (!strProblem.empty()) {
if (pwalletMain->fSaplingConsolidationEnabled)
return InitError(strProblem);
InitWarning(strProblem + "; ignoring it while -consolidation is off");
continue;
}
pwalletMain->consolidationAddresses.push_back(boost::get<libzcash::SaplingPaymentAddress>(zAddress));
if (pwalletMain->consolidationAddress.empty())
pwalletMain->consolidationAddress = vaddresses[i];
}
fConsolidationMapUsed = !pwalletMain->consolidationAddresses.empty();
}
// Sweep and consolidation pick notes with GetFilteredNotes at minDepth > 1. Older versions
// located each note's block by re-reading its tx through the txindex, so on a -txindex=0 node
// every fully shielded tx was skipped and these never moved those notes. Now they will.
if (!fTxIndex && (pwalletMain->fSweepEnabled || pwalletMain->fSaplingConsolidationEnabled)) {
LogPrintf("%s: -txindex=0 with -zsweep/-consolidation: fully shielded notes, which versions before "
"v1.3.1 never saw on such nodes, are now included in sweeps and consolidations\n", __func__);
} }
//Set Automatic Coinbase Shielding (default ON, conditional: self-guards //Set Automatic Coinbase Shielding (default ON, conditional: self-guards
@@ -2628,6 +2876,9 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler)
pindexRescan = FindForkInGlobalIndex(chainActive, locator); pindexRescan = FindForkInGlobalIndex(chainActive, locator);
else else
pindexRescan = chainActive.Genesis(); pindexRescan = chainActive.Genesis();
// Nothing to rescan: the wallet as loaded is what the last save wrote at this block.
if (pindexRescan != NULL && pindexRescan == chainActive.Tip())
pwalletMain->MarkStatePersisted(pindexRescan);
} }
if (chainActive.Tip() && chainActive.Tip() != pindexRescan) if (chainActive.Tip() && chainActive.Tip() != pindexRescan)
{ {
@@ -2636,8 +2887,20 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler)
nStart = GetTimeMillis(); nStart = GetTimeMillis();
pwalletMain->ScanForWalletTransactions(pindexRescan, true); pwalletMain->ScanForWalletTransactions(pindexRescan, true);
LogPrintf(" rescan %15dms\n", GetTimeMillis() - nStart); LogPrintf(" rescan %15dms\n", GetTimeMillis() - nStart);
pwalletMain->SetBestChain(chainActive.GetLocator()); // ONLY record "scanned to the tip" if the scan actually reached it. An aborted or
nWalletDBUpdated++; // shutdown-interrupted scan that stamps a tip locator tells the next startup there is
// nothing left to scan (the chainActive.Tip() != pindexRescan guard above then skips
// the rescan entirely), so every transaction in the unscanned range stays out of
// mapWallet permanently: invisible to getbalance and unspendable. The scan writes its
// own locator at the interrupt point instead.
if (pwalletMain->fLastRescanCompleted) {
pwalletMain->SetBestChain(chainActive.GetLocator());
nWalletDBUpdated++;
} else {
LogPrintf("Rescan did not complete; leaving the best-block locator at the scan's own "
"checkpoint so the remaining range is rescanned on the next start\n");
fWalletScanIncomplete = true;
}
// Restore wallet transaction metadata after -zapwallettxes=1 // Restore wallet transaction metadata after -zapwallettxes=1
if (GetBoolArg("-zapwallettxes", false) && GetArg("-zapwallettxes", "1") != "2") if (GetBoolArg("-zapwallettxes", false) && GetArg("-zapwallettxes", "1") != "2")
@@ -2664,6 +2927,19 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler)
} }
} }
} }
// Decrypt the wallet's notes into the in-memory plaintext cache now, while RPC is still in warmup
// and before the wallet notification thread (started below) can want cs_wallet. Otherwise the
// first balance call after a restart decrypts them all under cs_main.
fCheckNoteCache = GetBoolArg("-checknotecache", false);
if (GetBoolArg("-notecachewarmup", true) && !ShutdownRequested()) {
uiInterface.InitMessage(_("Decrypting wallet notes..."));
pwalletMain->WarmSaplingNoteCache();
// With the notes decrypted, counting them per address is cheap: suggest consolidation to a
// wallet that has piled up notes (typically a miner's, one note per autoshield round).
if (!pwalletMain->fSaplingConsolidationEnabled && !ShutdownRequested())
pwalletMain->RefreshConsolidationSuggestion();
}
pwalletMain->SetBroadcastTransactions(GetBoolArg("-walletbroadcast", true)); pwalletMain->SetBroadcastTransactions(GetBoolArg("-walletbroadcast", true));
} // (!fDisableWallet) } // (!fDisableWallet)
#else // ENABLE_WALLET #else // ENABLE_WALLET
@@ -2707,6 +2983,21 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler)
{ {
LOCK(cs_main); LOCK(cs_main);
pindexLastTip = chainActive.Tip(); pindexLastTip = chainActive.Tip();
#ifdef ENABLE_WALLET
// The wallet's state reflects the block the notifier starts from, unless the startup
// rescan was interrupted: then it ends at the scan's checkpoint, and the hourly
// SetBestChain must keep stamping that so the next start rescans the rest.
if (pwalletMain) {
const CBlockIndex* pindexWallet = pindexLastTip;
if (fWalletScanIncomplete) {
CWalletDB walletdb(pwalletMain->strWalletFile);
CBlockLocator locator;
if (walletdb.ReadBestBlock(locator))
pindexWallet = FindForkInGlobalIndex(chainActive, locator);
}
pwalletMain->SetWalletTip(pindexWallet);
}
#endif
} }
boost::function<void()> threadnotifywallets = boost::bind(&ThreadNotifyWallets, pindexLastTip); boost::function<void()> threadnotifywallets = boost::bind(&ThreadNotifyWallets, pindexLastTip);
threadGroup.create_thread( threadGroup.create_thread(
@@ -2748,8 +3039,24 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler)
uiInterface.InitMessage(_("Activating best chain...")); uiInterface.InitMessage(_("Activating best chain..."));
// scan for better chains in the block chain database, that are not yet connected in the active best chain // scan for better chains in the block chain database, that are not yet connected in the active best chain
CValidationState state; CValidationState state;
const CBlockIndex* pindexBeforeActivate = NULL;
{
LOCK(cs_main);
pindexBeforeActivate = chainActive.Tip();
}
if ( !ActivateBestChain(true,state)) if ( !ActivateBestChain(true,state))
strErrors << "Failed to connect best block"; strErrors << "Failed to connect best block";
else {
// Persist a startup replay now: the wallet's witness rebuild runs next and can hold
// cs_main for a long time, and a node killed before any later flush would replay it all again.
bool fTipMoved;
{
LOCK(cs_main);
fTipMoved = chainActive.Tip() != pindexBeforeActivate;
}
if (fTipMoved)
FlushStateToDisk();
}
} else { } else {
LogPrintf("HUSH_REWIND < 0\n"); LogPrintf("HUSH_REWIND < 0\n");
} }
@@ -2836,5 +3143,8 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler)
if(fDebug) if(fDebug)
fprintf(stderr,"%s end fRequestShutdown=%d\n", __FUNCTION__, !!fRequestShutdown); fprintf(stderr,"%s end fRequestShutdown=%d\n", __FUNCTION__, !!fRequestShutdown);
return !fRequestShutdown; bool fOk = !fRequestShutdown;
if (fOk)
fInitCompleted = true;
return fOk;
} }
+110 -34
View File
@@ -328,8 +328,12 @@ namespace {
bool fBulkHeaderSeen; bool fBulkHeaderSeen;
//! (server side) time (us) we last served a bulk stream to this peer, for flood throttling. //! (server side) time (us) we last served a bulk stream to this peer, for flood throttling.
int64_t nLastBulkServeTime; int64_t nLastBulkServeTime;
//! (#8 IBD header-flood cap) cumulative headers this peer made us process while in IBD. //! (#8 header-flood cap) cumulative headers this peer made us process.
int64_t nHeadersProcessed; int64_t nHeadersProcessed;
//! (#8 header-flood cap) newly-stored headers from this peer that did NOT extend the best
//! header chain (side-branch/sibling): the real mapBlockIndex-growth vector. Honest sync and
//! new-block announcements are best-extending and never increment this.
int64_t nSideBranchHeaders;
CNodeState() { CNodeState() {
fCurrentlyConnected = false; fCurrentlyConnected = false;
@@ -351,6 +355,7 @@ namespace {
fBulkHeaderSeen = false; fBulkHeaderSeen = false;
nLastBulkServeTime = 0; nLastBulkServeTime = 0;
nHeadersProcessed = 0; nHeadersProcessed = 0;
nSideBranchHeaders = 0;
} }
}; };
@@ -1593,7 +1598,14 @@ bool CheckTransactionWithoutProofVerification(uint32_t tiptime,const CTransactio
char destaddr[65]; char destaddr[65];
Getscriptaddress(destaddr,txout.scriptPubKey); Getscriptaddress(destaddr,txout.scriptPubKey);
if ( hush_isnotaryvout(destaddr,tiptime) == 0 ) // The CRYPTO555/notary allowlist exempts those transparent vouts from the private-chain
// ban, leaving a public UTXO on a chain users treat as fully shielded. At/after the
// activation time that exemption is dropped and such vouts are rejected like any other
// taddr (time-gated + default-off via the sentinel so the whole network upgrades first).
// The gate is checked first so the allowlist lookup is skipped entirely once active.
int32_t isNotaryVout = ( tiptime >= DRAGONX_NOTARYVOUT_BAN_TIME )
? 0 : hush_isnotaryvout(destaddr,tiptime);
if ( isNotaryVout == 0 )
{ {
const bool isburn = (strcmp(destaddr,BURN_ADDRESS) == 0); const bool isburn = (strcmp(destaddr,BURN_ADDRESS) == 0);
if ((ASSETCHAINS_BURN == 1) && isburn && tx.vin.empty()) { if ((ASSETCHAINS_BURN == 1) && isburn && tx.vin.empty()) {
@@ -2980,6 +2992,8 @@ static bool ApplyTxInUndo(const CTxInUndo& undo, CCoinsViewCache& view, const CO
void ConnectNotarizations(const CBlock &block, int height) void ConnectNotarizations(const CBlock &block, int height)
{ {
if (pnotarizations == NULL) // closed by Shutdown()
return;
NotarizationsInBlock notarizations = ScanBlockNotarizations(block, height); NotarizationsInBlock notarizations = ScanBlockNotarizations(block, height);
if (notarizations.size() > 0) { if (notarizations.size() > 0) {
CDBBatch batch = CDBBatch(*pnotarizations); CDBBatch batch = CDBBatch(*pnotarizations);
@@ -2992,6 +3006,8 @@ void ConnectNotarizations(const CBlock &block, int height)
void DisconnectNotarizations(const CBlock &block) void DisconnectNotarizations(const CBlock &block)
{ {
if (pnotarizations == NULL) // closed by Shutdown()
return;
NotarizationsInBlock nibs; NotarizationsInBlock nibs;
if (GetBlockNotarizations(block.GetHash(), nibs)) { if (GetBlockNotarizations(block.GetHash(), nibs)) {
CDBBatch batch = CDBBatch(*pnotarizations); CDBBatch batch = CDBBatch(*pnotarizations);
@@ -3738,6 +3754,7 @@ bool static FlushStateToDisk(CValidationState &state, FlushStateMode mode) {
static int64_t nLastWrite = 0; static int64_t nLastWrite = 0;
static int64_t nLastFlush = 0; static int64_t nLastFlush = 0;
static int64_t nLastSetChain = 0; static int64_t nLastSetChain = 0;
static int nLastFlushHeight = -1;
std::set<int> setFilesToPrune; std::set<int> setFilesToPrune;
bool fFlushForPrune = false; bool fFlushForPrune = false;
try { try {
@@ -3763,6 +3780,9 @@ bool static FlushStateToDisk(CValidationState &state, FlushStateMode mode) {
if (nLastSetChain == 0) { if (nLastSetChain == 0) {
nLastSetChain = nNow; nLastSetChain = nNow;
} }
if (nLastFlushHeight < 0) {
nLastFlushHeight = chainActive.Height();
}
size_t cacheSize = pcoinsTip->DynamicMemoryUsage(); size_t cacheSize = pcoinsTip->DynamicMemoryUsage();
// The cache is large and close to the limit, but we have time now (not in the middle of a block processing). // The cache is large and close to the limit, but we have time now (not in the middle of a block processing).
bool fCacheLarge = mode == FLUSH_STATE_PERIODIC && cacheSize * (10.0/9) > nCoinCacheUsage; bool fCacheLarge = mode == FLUSH_STATE_PERIODIC && cacheSize * (10.0/9) > nCoinCacheUsage;
@@ -3772,8 +3792,10 @@ bool static FlushStateToDisk(CValidationState &state, FlushStateMode mode) {
bool fPeriodicWrite = mode == FLUSH_STATE_PERIODIC && nNow > nLastWrite + (int64_t)DATABASE_WRITE_INTERVAL * 1000000; bool fPeriodicWrite = mode == FLUSH_STATE_PERIODIC && nNow > nLastWrite + (int64_t)DATABASE_WRITE_INTERVAL * 1000000;
// It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage. // It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage.
bool fPeriodicFlush = mode == FLUSH_STATE_PERIODIC && nNow > nLastFlush + (int64_t)DATABASE_FLUSH_INTERVAL * 1000000; bool fPeriodicFlush = mode == FLUSH_STATE_PERIODIC && nNow > nLastFlush + (int64_t)DATABASE_FLUSH_INTERVAL * 1000000;
// Many blocks connected since the last flush, e.g. a long replay inside one ActivateBestChain call.
bool fBlockCountFlush = (mode == FLUSH_STATE_IF_NEEDED || mode == FLUSH_STATE_PERIODIC) && chainActive.Height() - nLastFlushHeight >= DATABASE_FLUSH_BLOCKS;
// Combine all conditions that result in a full cache flush. // Combine all conditions that result in a full cache flush.
bool fDoFullFlush = (mode == FLUSH_STATE_ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush || fFlushForPrune; bool fDoFullFlush = (mode == FLUSH_STATE_ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush || fFlushForPrune || fBlockCountFlush;
// Write blocks and block index to disk. // Write blocks and block index to disk.
if (fDoFullFlush || fPeriodicWrite) { if (fDoFullFlush || fPeriodicWrite) {
// Depend on nMinDiskSpace to ensure we can write block index // Depend on nMinDiskSpace to ensure we can write block index
@@ -3827,6 +3849,7 @@ bool static FlushStateToDisk(CValidationState &state, FlushStateMode mode) {
if (!pcoinsTip->Flush()) if (!pcoinsTip->Flush())
return AbortNode(state, "Failed to write to coin database"); return AbortNode(state, "Failed to write to coin database");
nLastFlush = nNow; nLastFlush = nNow;
nLastFlushHeight = chainActive.Height();
} }
if ((mode == FLUSH_STATE_ALWAYS || mode == FLUSH_STATE_PERIODIC) && nNow > nLastSetChain + (int64_t)DATABASE_WRITE_INTERVAL * 1000000) { if ((mode == FLUSH_STATE_ALWAYS || mode == FLUSH_STATE_PERIODIC) && nNow > nLastSetChain + (int64_t)DATABASE_WRITE_INTERVAL * 1000000) {
// Update best block in wallet (so we can detect restored wallets). // Update best block in wallet (so we can detect restored wallets).
@@ -3839,10 +3862,11 @@ bool static FlushStateToDisk(CValidationState &state, FlushStateMode mode) {
return true; return true;
} }
void FlushStateToDisk() { bool FlushStateToDisk() {
CValidationState state; CValidationState state;
if ( HUSH_NSPV_FULLNODE ) if ( HUSH_NSPV_FULLNODE )
FlushStateToDisk(state, FLUSH_STATE_ALWAYS); return FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
return true;
} }
void PruneAndFlush() { void PruneAndFlush() {
@@ -4308,23 +4332,52 @@ static bool ActivateBestChainStep(bool fSkipdpow, CValidationState &state, CBloc
assert(MAX_REORG_LENGTH > 0);//, "We must be able to reorg some distance"); assert(MAX_REORG_LENGTH > 0);//, "We must be able to reorg some distance");
if ( reorgLength > MAX_REORG_LENGTH) if ( reorgLength > MAX_REORG_LENGTH)
{ {
// A peer-delivered fork that would roll back more than MAX_REORG_LENGTH
// (-maxreorg, default 99) blocks. This used to StartShutdown() the whole
// process, which is a per-reachability remote DoS: the attacker's fork is
// re-pulled from addrman after every restart and re-kills the node. Instead
// refuse the fork, poison the attacker branch so it leaves
// setBlockIndexCandidates and is never re-selected or re-pulled, stay up on
// the current chain, and penalize the delivering peer (DoS(100); the default
// banscore 101 bans on the second such trip). This mirrors the
// past-notarized-height branch above, which already refuses a fork with
// InvalidateBlock + DoS(100) and keeps running.
//
// Invalidate the BASE of the attacker branch (the first block above the fork
// point), not just its tip: FindMostWorkChain's fFailedChain sweep then
// erases the whole branch from the candidate set in one pass, and
// AcceptBlockHeader rejects any future extension (pprev is BLOCK_FAILED_CHILD).
// The base is strictly on the fork side (height forkHeight+1), so it is never
// in chainActive and no honest block is disconnected or poisoned.
CBlockIndex *pindexBadBase = (pindexFork != 0) ? pindexMostWork->GetAncestor(pindexFork->GetHeight() + 1) : pindexMostWork;
if (pindexBadBase == 0)
pindexBadBase = pindexMostWork;
// 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>`
// (optionally with a raised -maxreorg so it isn't re-refused). Say so, and
// surface it in getinfo "errors" so a refused node is never silently stranded.
auto msg = strprintf(_( auto msg = strprintf(_(
"A block chain reorganization has been detected that would roll back %d blocks!!! " "A block chain reorganization that would roll back %d blocks (more than the maximum of %d) "
"This is larger than the maximum of %d blocks, and so the node is shutting down for your safety." "was refused; staying on the current chain."
), reorgLength, MAX_REORG_LENGTH) + "\n\n" + ), reorgLength, MAX_REORG_LENGTH) + "\n" +
_("Reorganization details") + ":\n" + _("Reorganization details") + ":\n" +
"- " + strprintf(_("Current tip: %s, height %d, work %s\n"), "- " + strprintf(_("Current tip: %s, height %d, work %s"),
pindexOldTip->phashBlock->GetHex(), pindexOldTip->GetHeight(), pindexOldTip->chainPower.chainWork.GetHex()) + "\n" + pindexOldTip->phashBlock->GetHex(), pindexOldTip->GetHeight(), pindexOldTip->chainPower.chainWork.GetHex()) + "\n" +
"- " + strprintf(_("New tip: %s, height %d, work %s\n"), "- " + strprintf(_("Rejected tip: %s, height %d, work %s"),
pindexMostWork->phashBlock->GetHex(), pindexMostWork->GetHeight(), pindexMostWork->chainPower.chainWork.GetHex()) + "\n" + pindexMostWork->phashBlock->GetHex(), pindexMostWork->GetHeight(), pindexMostWork->chainPower.chainWork.GetHex()) + "\n" +
"- " + strprintf(_("Fork point: %s %s, height %d"), "- " + strprintf(_("Fork point: %s %s, height %d"),
SMART_CHAIN_SYMBOL,pindexFork->phashBlock->GetHex(), pindexFork->GetHeight()) + "\n\n" + SMART_CHAIN_SYMBOL, pindexFork ? pindexFork->phashBlock->GetHex() : "(none)", pindexFork ? pindexFork->GetHeight() : -1) + "\n" +
_("Please help me, wise human!"); strprintf(_("If this is a legitimate deep reorg, recover with: reconsiderblock %s (raise -maxreorg first if needed)"),
LogPrintf("*** %s\nif you launch with -maxreorg=%d it might be able to resolve this automatically", msg,reorgLength+10); pindexBadBase->phashBlock->GetHex());
fprintf(stderr,"*** %s\nif you launch with -maxreorg=%d it might be able to resolve this automatically", msg.c_str(),reorgLength+10); LogPrintf("*** %s\n", msg);
uiInterface.ThreadSafeMessageBox(msg, "", CClientUIInterface::MSG_ERROR); fprintf(stderr,"*** %s\n", msg.c_str());
StartShutdown(); strMiscWarning = msg; // surfaces in getinfo/getnetworkinfo (GetWarnings), not fatal
return false;
CValidationState tmpstate;
InvalidateBlock(tmpstate, pindexBadBase);
return state.DoS(100, error("ActivateBestChainStep(): reorg of %d blocks exceeds maximum of %d; refusing fork and staying on current chain",
reorgLength, MAX_REORG_LENGTH), REJECT_INVALID, "oversized-reorg");
} }
// Disconnect active blocks which are no longer in the best chain. // Disconnect active blocks which are no longer in the best chain.
@@ -5915,7 +5968,10 @@ FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
return NULL; return NULL;
boost::filesystem::path path = GetBlockPosFilename(pos, prefix); boost::filesystem::path path = GetBlockPosFilename(pos, prefix);
boost::filesystem::create_directories(path.parent_path()); boost::filesystem::create_directories(path.parent_path());
FILE* file = fopen(path.string().c_str(), "rb+"); // Read-only opens get a read-only FILE (every fReadOnly caller only reads). With "rb+", a write through a
// reused fd number landed here: when the wolfSSL CloseSocket macro (see net.h) closed the wallet's BDB fd
// behind its back, BDB's next page write went to whatever reopened that number -- a block file opened here.
FILE* file = fopen(path.string().c_str(), fReadOnly ? "rb" : "rb+");
if (!file && !fReadOnly) if (!file && !fReadOnly)
file = fopen(path.string().c_str(), "wb+"); file = fopen(path.string().c_str(), "wb+");
if (!file) { if (!file) {
@@ -7865,6 +7921,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv,
} }
CBlockIndex *pindexLast = NULL; CBlockIndex *pindexLast = NULL;
int64_t nSideBranchThisMsg = 0; // newly-stored headers that did NOT extend the best header chain
BOOST_FOREACH(const CBlockHeader& header, headers) { BOOST_FOREACH(const CBlockHeader& header, headers) {
if(fDebug) { if(fDebug) {
printf("%s: size.%i, solution size.%i\n", __func__, (int)sizeof(header), (int)header.nSolution.size()); printf("%s: size.%i, solution size.%i\n", __func__, (int)sizeof(header), (int)header.nSolution.size());
@@ -7877,6 +7934,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv,
return error("non-continuous headers sequence"); return error("non-continuous headers sequence");
} }
int32_t futureblock; int32_t futureblock;
const bool fWasNew = (mapBlockIndex.count(header.GetHash()) == 0); // not already stored (duplicates don't grow mapBlockIndex)
if (!AcceptBlockHeader(&futureblock,header, state, &pindexLast)) { if (!AcceptBlockHeader(&futureblock,header, state, &pindexLast)) {
int nDoS; int nDoS;
if (state.IsInvalid(nDoS) && futureblock == 0) if (state.IsInvalid(nDoS) && futureblock == 0)
@@ -7886,29 +7944,47 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv,
return error("invalid header received"); return error("invalid header received");
} }
} }
else if (fWasNew && pindexLast != NULL && pindexLast != pindexBestHeader) {
// Newly added to mapBlockIndex but NOT the best-known header: a side-branch/sibling,
// which is exactly the flood vector. Honest headers-first sync and new-block
// announcements extend the best chain, so they are never counted here.
nSideBranchThisMsg++;
}
} }
// SECURITY (#8: IBD header-flood cap): bound how many headers a single peer can make us // SECURITY (#8: header-flood cap): bound how many headers a single peer can make us store, in and
// store while in IBD. Honest headers-first sync needs at most ~chain-length headers from a // after IBD. Header-accept does no PoW check (removed as bug-prone), so without a cap a connected
// peer; one that floods far past 2x the known chain length is only trying to bloat // peer could flood sibling headers of the tip and grow mapBlockIndex linearly (a memory-exhaustion
// mapBlockIndex/leveldb (such headers are never selected -- nMinimumChainWork gates that -- // DoS). Two complementary per-peer caps, both dropping the peer when exceeded:
// but they still cost memory/disk). Cap per-peer and drop the peer. IBD-only: post-IBD there is {
// no header-accept PoW check (removed as bug-prone), so a post-IBD flood is bounded only by
// nMinimumChainWork gating selection -- memory/disk growth there is accepted as low-severity.
if (IsInitialBlockDownload()) {
CNodeState *hstate = State(pfrom->GetId()); CNodeState *hstate = State(pfrom->GetId());
if (hstate != NULL) { if (hstate != NULL) {
hstate->nHeadersProcessed += (int64_t)nCount; hstate->nHeadersProcessed += (int64_t)nCount;
// Cap RELATIVE TO THE VALIDATED ACTIVE-CHAIN HEIGHT (attacker-hard -- advancing it requires hstate->nSideBranchHeaders += nSideBranchThisMsg;
// connecting real PoW blocks), NOT pindexBestHeader: a forward-extending header flood advances
// pindexBestHeader in lockstep with the attacker, so a pindexBestHeader-relative cap never fires. // (1) Tight cap on newly-stored SIDE-BRANCH headers -- the actual mapBlockIndex-growth
// The checkpoint height is a fixed floor so honest IBD (blocks still lagging headers) is never capped. // vector. A legitimate competing fork is bounded by the reorg window (MAX_REORG_LENGTH);
// this allows many times that for slack while bounding a flood to a few thousand entries
// per peer. Honest best-extending sync never increments the counter, so it is safe to
// keep small.
const int64_t kSideBranchCap = 2000;
if (hstate->nSideBranchHeaders > kSideBranchCap) {
Misbehaving(pfrom->GetId(), 100);
return error("%s: peer=%d flooded %lld side-branch headers (cap %lld)", __func__,
pfrom->id, (long long)hstate->nSideBranchHeaders, (long long)kSideBranchCap);
}
// (2) Loose cumulative backstop against an attacker who grinds a long FORWARD chain of
// correct-nBits headers (those do extend the best chain, so (1) never sees them). Cap
// RELATIVE TO THE VALIDATED ACTIVE-CHAIN HEIGHT (attacker-hard -- advancing it needs real
// PoW), NOT pindexBestHeader (a forward flood advances that in lockstep). The checkpoint
// height is a fixed floor so honest IBD (blocks lagging headers) is never capped.
int knownH = std::max((int)chainActive.Height(), int knownH = std::max((int)chainActive.Height(),
Checkpoints::GetTotalBlocksEstimate(chainparams.Checkpoints())); Checkpoints::GetTotalBlocksEstimate(chainparams.Checkpoints()));
int64_t headerCap = 2 * (int64_t)knownH + 200000; int64_t headerCap = 2 * (int64_t)knownH + 200000;
if (hstate->nHeadersProcessed > headerCap) { if (hstate->nHeadersProcessed > headerCap) {
Misbehaving(pfrom->GetId(), 100); Misbehaving(pfrom->GetId(), 100);
return error("%s: peer=%d flooded %lld headers during IBD (cap %lld)", __func__, return error("%s: peer=%d flooded %lld headers (cap %lld)", __func__,
pfrom->id, (long long)hstate->nHeadersProcessed, (long long)headerCap); pfrom->id, (long long)hstate->nHeadersProcessed, (long long)headerCap);
} }
} }
+12 -4
View File
@@ -143,8 +143,15 @@ static const unsigned int MAX_LOCATOR_SZ = 101;
static unsigned int BLOCK_DOWNLOAD_WINDOW = 1024; static unsigned int BLOCK_DOWNLOAD_WINDOW = 1024;
/** Time to wait (in seconds) between writing blocks/block index to disk. */ /** Time to wait (in seconds) between writing blocks/block index to disk. */
static const unsigned int DATABASE_WRITE_INTERVAL = 60 * 60; static const unsigned int DATABASE_WRITE_INTERVAL = 60 * 60;
/** Time to wait (in seconds) between flushing chainstate to disk. */ /** Time to wait (in seconds) between flushing chainstate to disk. Upstream uses 24h to keep a large
static const unsigned int DATABASE_FLUSH_INTERVAL = 24 * 60 * 60; * coins cache warm, but DragonX's cache stays a few MiB (private chain, few transparent outputs), so
* the size triggers never fire and this timer is all that persists the chainstate while a node runs:
* a node that never reached 24h uptime or a clean shutdown replayed weeks of blocks on every start. */
static const unsigned int DATABASE_FLUSH_INTERVAL = 60 * 60;
/** Also flush chainstate once this many blocks were connected since the last flush. A long
* ActivateBestChain (startup replay, catching up after downtime) only flushes IF_NEEDED until it
* returns, so without this a node killed part-way through loses the whole replay. */
static const int DATABASE_FLUSH_BLOCKS = 5000;
/** Maximum length of reject messages. */ /** Maximum length of reject messages. */
static const unsigned int MAX_REJECT_MESSAGE_LENGTH = 111; static const unsigned int MAX_REJECT_MESSAGE_LENGTH = 111;
static const int64_t DEFAULT_MAX_TIP_AGE = 24 * 60 * 60; static const int64_t DEFAULT_MAX_TIP_AGE = 24 * 60 * 60;
@@ -316,8 +323,9 @@ CBlockIndex * InsertBlockIndex(uint256 hash);
bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats); bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats);
/** Increase a node's misbehavior score. */ /** Increase a node's misbehavior score. */
void Misbehaving(NodeId nodeid, int howmuch); void Misbehaving(NodeId nodeid, int howmuch);
/** Flush all state, indexes and buffers to disk. */ /** Flush all state, indexes and buffers to disk. False if the flush failed (out of disk space, a write
void FlushStateToDisk(); * error); true also for an nSPV light client, which has no chainstate to flush. */
bool FlushStateToDisk();
/** Prune block files and flush state to disk. */ /** Prune block files and flush state to disk. */
void PruneAndFlush(); void PruneAndFlush();
+13 -8
View File
@@ -1436,13 +1436,19 @@ void static RandomXMiner()
} }
CValidationState state; CValidationState state;
//{ LOCK(cs_main); bool fValid;
// Skip RandomX re-validation during TestBlockValidity — we already {
// computed the correct hash, and re-verifying allocates ~256MB which // Hold cs_main across the LastTip() read and TestBlockValidity: the latter
// can trigger the OOM killer on memory-constrained systems. // asserts pindexPrev == chainActive.Tip(), so without the lock a tip change
SetSkipRandomXValidation(true); // (a block arriving from a peer, or a reorg) between the read and the assert
bool fValid = TestBlockValidity(state,B, chainActive.LastTip(), true, false); // aborts the node. The lock was previously removed only to avoid a ~256MB
SetSkipRandomXValidation(false); // RandomX re-validation alloc; SetSkipRandomXValidation() already skips that
// re-validation here, so holding the lock is cheap and safe.
LOCK(cs_main);
SetSkipRandomXValidation(true);
fValid = TestBlockValidity(state, B, chainActive.LastTip(), true, false);
SetSkipRandomXValidation(false);
}
if ( !fValid ) if ( !fValid )
{ {
LogPrintf("RandomXMiner: TestBlockValidity FAILED at ht.%d, gotinvalid=1, state=%s\n", LogPrintf("RandomXMiner: TestBlockValidity FAILED at ht.%d, gotinvalid=1, state=%s\n",
@@ -1450,7 +1456,6 @@ void static RandomXMiner()
gotinvalid = 1; gotinvalid = 1;
return(false); return(false);
} }
//}
SetThreadPriority(THREAD_PRIORITY_NORMAL); SetThreadPriority(THREAD_PRIORITY_NORMAL);
LogPrintf("HushRandomXMiner:\n"); LogPrintf("HushRandomXMiner:\n");
LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", B.GetHash().GetHex(), HASHTarget.GetHex()); LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", B.GetHash().GetHex(), HASHTarget.GetHex());
+7
View File
@@ -45,6 +45,13 @@
#include <wolfssl/options.h> #include <wolfssl/options.h>
#include <wolfssl/ssl.h> #include <wolfssl/ssl.h>
#include <hush/tlsmanager.cpp> #include <hush/tlsmanager.cpp>
// CloseSocket must be util/sock.cpp's CloseSocket(SOCKET&), which invalidates the handle it closes. If
// wolfSSL's `#define CloseSocket(s) close(s)` survived into this file (see net.h), each close here would leave
// its stale fd number behind to be closed again after another thread reused it.
#ifdef CloseSocket
#error "CloseSocket is a macro here (wolfssl/wolfio.h): it would bypass CloseSocket(SOCKET&) in util/sock.cpp"
#endif
using namespace hush; using namespace hush;
extern int32_t HUSH_TESTNODE; extern int32_t HUSH_TESTNODE;
extern uint8_t ASSETCHAINS_CLEARNET; extern uint8_t ASSETCHAINS_CLEARNET;
+8
View File
@@ -57,6 +57,14 @@
#define byte unsigned char #define byte unsigned char
#include <wolfssl/ssl.h> #include <wolfssl/ssl.h>
#undef byte #undef byte
// wolfssl/wolfio.h (pulled in by ssl.h) does `#ifndef CloseSocket / #define CloseSocket(s) close(s)`. Left
// defined, it turns every CloseSocket(hSocket) after this point -- all 15 calls in net.cpp, including the ones in
// CloseSocketDisconnect and ~CNode -- into a bare close() that never sets hSocket = INVALID_SOCKET, so util/sock.cpp's
// CloseSocket(SOCKET&) is never called. Every P2P disconnect then closed its fd number again later (a repeated
// CloseSocketDisconnect, then ~CNode), by which time another thread often owned that number: wallet.dat or a
// database/log.* fd (BDB then wrote wallet pages into whatever got the number next, e.g. a blocks/*.dat file
// opened "rb+"), a block file, or an HTTP RPC socket. wolfio.h is include-guarded, so it can't come back.
#undef CloseSocket
class CAddrMan; class CAddrMan;
class CBlockIndex; class CBlockIndex;
+10 -1
View File
@@ -9,7 +9,10 @@
#include "main.h" #include "main.h"
#include <boost/foreach.hpp> #include <boost/foreach.hpp>
NotarizationDB *pnotarizations; // Owned by init: opened in AppInit2() and closed (set back to NULL) in Shutdown(), so that
// notarizations/LOCK is released together with the other LevelDB locks. Every accessor treats NULL
// as an empty DB, so a straggler after Shutdown() cannot dereference it.
NotarizationDB *pnotarizations = NULL;
NotarizationDB::NotarizationDB(size_t nCacheSize, bool fMemory, bool fWipe) : CDBWrapper(GetDataDir() / "notarizations", nCacheSize, fMemory, fWipe, false, 64) { } NotarizationDB::NotarizationDB(size_t nCacheSize, bool fMemory, bool fWipe) : CDBWrapper(GetDataDir() / "notarizations", nCacheSize, fMemory, fWipe, false, 64) { }
NotarizationsInBlock ScanBlockNotarizations(const CBlock &block, int nHeight) { NotarizationsInBlock ScanBlockNotarizations(const CBlock &block, int nHeight) {
@@ -55,11 +58,15 @@ NotarizationsInBlock ScanBlockNotarizations(const CBlock &block, int nHeight) {
} }
bool GetBlockNotarizations(uint256 blockHash, NotarizationsInBlock &nibs) { bool GetBlockNotarizations(uint256 blockHash, NotarizationsInBlock &nibs) {
if (pnotarizations == NULL)
return false;
return pnotarizations->Read(blockHash, nibs); return pnotarizations->Read(blockHash, nibs);
} }
bool GetBackNotarization(uint256 notarizationHash, Notarization &n) { bool GetBackNotarization(uint256 notarizationHash, Notarization &n) {
if (pnotarizations == NULL)
return false;
return pnotarizations->Read(notarizationHash, n); return pnotarizations->Read(notarizationHash, n);
} }
@@ -86,6 +93,8 @@ void EraseBackNotarizations(const NotarizationsInBlock notarizations, CDBBatch &
// Scan notarizationsdb backwards for blocks containing a notarization // Scan notarizationsdb backwards for blocks containing a notarization
// for given symbol. Return height of matched notarization or 0. // for given symbol. Return height of matched notarization or 0.
int ScanNotarizationsDB(int height, std::string symbol, int scanLimitBlocks, Notarization& out) { int ScanNotarizationsDB(int height, std::string symbol, int scanLimitBlocks, Notarization& out) {
if (pnotarizations == NULL)
return 0;
if (height < 0 || height > chainActive.Height()) if (height < 0 || height > chainActive.Height())
return false; return false;
+5
View File
@@ -151,6 +151,11 @@ static const CRPCConvertParam vRPCConvertParams[] =
{ "z_shieldcoinbase", 2}, { "z_shieldcoinbase", 2},
{ "z_shieldcoinbase", 3}, { "z_shieldcoinbase", 3},
{ "z_getoperationstatus", 0}, { "z_getoperationstatus", 0},
{ "z_consolidationstatus", 0},
{ "z_consolidate", 0},
{ "z_consolidate", 1},
{ "z_consolidate", 2},
{ "z_consolidate", 3},
{ "z_getoperationresult", 0}, { "z_getoperationresult", 0},
{ "notaries", 2 }, { "notaries", 2 },
{ "minerids", 1 }, { "minerids", 1 },
+55 -5
View File
@@ -1112,6 +1112,27 @@ static bool StratumMinerRecvLines(int fd, std::string& buf, int timeout_ms, std:
// authorize, receive work + the per-height RandomX key, then vary the block nNonce, hash with // authorize, receive work + the per-height RandomX key, then vary the block nNonce, hash with
// RandomX (byte-identical to CheckRandomXSolution via GetRandomXInput), and submit a 32-byte // RandomX (byte-identical to CheckRandomXSolution via GetRandomXInput), and submit a 32-byte
// solution when the block hash meets target. Exists to validate the -stratum RandomX pool path. // solution when the block hash meets target. Exists to validate the -stratum RandomX pool path.
//! Upper bound on how long stratummine will hold an RPC worker thread (and a 256 MB RandomX
//! cache). An unbounded caller-supplied deadline pins both indefinitely.
static const int64_t MAX_STRATUMMINE_TIMEOUT = 3600;
//! Parse a 64-char hex field from mining.notify into a uint256.
//! These fields come from whatever host the operator pointed us at, and both primitives below are
//! unforgiving: uint256's vector constructor asserts on a wrong-size input (uint256.cpp:30, and
//! NDEBUG is never defined for this build so the assert is live in release), while ParseHex
//! silently truncates at the first non-hex character. A short or garbled field would therefore
//! abort the daemon rather than be rejected. Returns false instead.
static bool StratumHex256(const std::string& hex, uint256& out)
{
if (hex.size() != 64 || !IsHex(hex))
return false;
std::vector<unsigned char> v = ParseHex(hex);
if (v.size() != 32)
return false;
out = uint256(v);
return true;
}
UniValue stratummine(const UniValue& params, bool fHelp, const CPubKey& mypk) UniValue stratummine(const UniValue& params, bool fHelp, const CPubKey& mypk)
{ {
if (fHelp || params.size() < 2 || params.size() > 4) if (fHelp || params.size() < 2 || params.size() > 4)
@@ -1129,10 +1150,24 @@ UniValue stratummine(const UniValue& params, bool fHelp, const CPubKey& mypk)
if (ASSETCHAINS_ALGO != ASSETCHAINS_RANDOMX) if (ASSETCHAINS_ALGO != ASSETCHAINS_RANDOMX)
throw JSONRPCError(RPC_MISC_ERROR, "stratummine only supports RandomX chains"); throw JSONRPCError(RPC_MISC_ERROR, "stratummine only supports RandomX chains");
// This is a reference miner for exercising -stratum, not a production facility: it dials an
// operator-supplied host, blocks an RPC worker for the whole run, and parses whatever that host
// chooses to send back. Require an explicit opt-in, and exempt regtest so the test suite can
// still drive it. NOTE: do NOT gate this on fExperimentalMode -- that defaults to TRUE
// (init.cpp:1195), so it would leave the RPC exposed on every node and the gate would be a no-op.
if (!GetBoolArg("-stratummine", false) && Params().NetworkIDString() != "regtest")
throw JSONRPCError(RPC_MISC_ERROR,
"stratummine is a test-only reference miner and is disabled by default; "
"restart with -stratummine to enable it");
const std::string host = params[0].get_str(); const std::string host = params[0].get_str();
const int port = params[1].get_int(); const int port = params[1].get_int();
const std::string addr = params.size() > 2 ? params[2].get_str() : "x"; const std::string addr = params.size() > 2 ? params[2].get_str() : "x";
const int64_t timeout = params.size() > 3 ? params[3].get_int64() : 120; int64_t timeout = params.size() > 3 ? params[3].get_int64() : 120;
if (timeout < 1)
timeout = 1;
if (timeout > MAX_STRATUMMINE_TIMEOUT)
timeout = MAX_STRATUMMINE_TIMEOUT;
const int64_t deadline = GetTime() + timeout; const int64_t deadline = GetTime() + timeout;
// connect (blocking TCP) // connect (blocking TCP)
@@ -1166,6 +1201,11 @@ UniValue stratummine(const UniValue& params, bool fHelp, const CPubKey& mypk)
uint256 hashPrevBlock, hashMerkleRoot, hashReserved; uint256 hashPrevBlock, hashMerkleRoot, hashReserved;
auto processLine = [&](const std::string& line) { auto processLine = [&](const std::string& line) {
// Every get_str()/get_int() below throws on a type mismatch, and this lambda runs inside the
// window where the RandomX cache and VM are allocated and the socket is open -- all of which
// are released only on the normal path. A malformed server message must therefore never
// escape from here, or it leaks 256 MB and the fd on its way out.
try {
UniValue v; UniValue v;
if (!v.read(line)) return; if (!v.read(line)) return;
const UniValue& id = find_value(v, "id"); const UniValue& id = find_value(v, "id");
@@ -1185,16 +1225,26 @@ UniValue stratummine(const UniValue& params, bool fHelp, const CPubKey& mypk)
poolTarget = UintToArith256(uint256S(p[0].get_str())); poolTarget = UintToArith256(uint256S(p[0].get_str()));
haveTarget = true; haveTarget = true;
} else if (m == "mining.notify" && p.size() >= 7) { } else if (m == "mining.notify" && p.size() >= 7) {
// Validate every fixed-width field before committing any of it, so a malformed job is
// ignored outright rather than half-applied over the previous one.
uint256 prev, merkle, reserved;
if (!StratumHex256(p[2].get_str(), prev) ||
!StratumHex256(p[3].get_str(), merkle) ||
!StratumHex256(p[4].get_str(), reserved))
return;
jobId = p[0].get_str(); jobId = p[0].get_str();
nVersion = bswap_32((uint32_t)strtoul(p[1].get_str().c_str(), NULL, 16)); nVersion = bswap_32((uint32_t)strtoul(p[1].get_str().c_str(), NULL, 16));
hashPrevBlock = uint256(ParseHex(p[2].get_str())); hashPrevBlock = prev;
hashMerkleRoot = uint256(ParseHex(p[3].get_str())); hashMerkleRoot = merkle;
hashReserved = uint256(ParseHex(p[4].get_str())); hashReserved = reserved;
timeHex = p[5].get_str(); timeHex = p[5].get_str();
nTime = bswap_32((uint32_t)strtoul(timeHex.c_str(), NULL, 16)); nTime = bswap_32((uint32_t)strtoul(timeHex.c_str(), NULL, 16));
nBits = bswap_32((uint32_t)strtoul(p[6].get_str().c_str(), NULL, 16)); nBits = bswap_32((uint32_t)strtoul(p[6].get_str().c_str(), NULL, 16));
haveJob = true; haveJob = true;
} }
} catch (const std::exception&) {
// Malformed message from the server: ignore the line and keep mining.
}
}; };
std::string buf; std::string buf;
@@ -1302,7 +1352,7 @@ static const CRPCCommand commands[] =
{ // category name actor (function) okSafeMode { // category name actor (function) okSafeMode
// --------------------- ------------------------ ----------------------- ---------- // --------------------- ------------------------ ----------------------- ----------
#ifndef WIN32 #ifndef WIN32
{ "mining", "stratummine", &stratummine, true }, { "mining", "stratummine", &stratummine, false },
#endif #endif
{ "mining", "getlocalsolps", &getlocalsolps, true }, { "mining", "getlocalsolps", &getlocalsolps, true },
{ "mining", "getnetworksolps", &getnetworksolps, true }, { "mining", "getnetworksolps", &getnetworksolps, true },
+26
View File
@@ -26,6 +26,7 @@
#include "util.h" #include "util.h"
#include "util/strencodings.h" #include "util/strencodings.h"
#include "asyncrpcqueue.h" #include "asyncrpcqueue.h"
#include <chrono>
#include <memory> #include <memory>
#include <univalue.h> #include <univalue.h>
#include <boost/bind.hpp> #include <boost/bind.hpp>
@@ -640,6 +641,30 @@ std::string JSONRPCExecBatch(const UniValue& vReq)
return ret.write() + "\n"; return ret.write() + "\n";
} }
namespace {
// Logs an RPC whose wall time reached 500ms, or every RPC under -debug=bench. That time includes
// waiting for cs_main / cs_wallet behind block connection or another RPC, which the callee's own
// timers can't see because they start once the locks are held. A long-poll getblocktemplate waits
// for a new block with cs_main released, so it is only logged under -debug=bench. The method is
// logged as method=<name>: a bare " <name> " token would match the GUI's " rescan " log heuristic.
class RPCCallTimer {
const std::string& strMethod;
const bool fLongPoll;
const std::chrono::steady_clock::time_point start;
public:
RPCCallTimer(const std::string& method, const UniValue& params)
: strMethod(method),
fLongPoll(method == "getblocktemplate" && params.size() > 0 && params[0].isObject() &&
!find_value(params[0], "longpollid").isNull()),
start(std::chrono::steady_clock::now()) {}
~RPCCallTimer() {
const int64_t nMs = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start).count();
if ((nMs >= 500 && !fLongPoll) || LogAcceptCategory("bench"))
LogPrintf("RPC method=%s took %dms\n", strMethod, nMs);
}
};
}
UniValue CRPCTable::execute(const std::string &strMethod, const UniValue &params) const UniValue CRPCTable::execute(const std::string &strMethod, const UniValue &params) const
{ {
// Find method // Find method
@@ -674,6 +699,7 @@ UniValue CRPCTable::execute(const std::string &strMethod, const UniValue &params
try try
{ {
// Execute // Execute
RPCCallTimer timer(strMethod, params);
return pcmd->actor(params, false, CPubKey()); return pcmd->actor(params, false, CPubKey());
} }
catch (const std::exception& e) catch (const std::exception& e)
+1
View File
@@ -368,6 +368,7 @@ extern UniValue z_sendmany(const UniValue& params, bool fHelp, const CPubKey& my
extern UniValue z_sweepstatus(const UniValue& params, bool fHelp, const CPubKey& mypk); // in rpcwallet.cpp extern UniValue z_sweepstatus(const UniValue& params, bool fHelp, const CPubKey& mypk); // in rpcwallet.cpp
extern UniValue z_autoshieldstatus(const UniValue& params, bool fHelp, const CPubKey& mypk); // in rpcwallet.cpp extern UniValue z_autoshieldstatus(const UniValue& params, bool fHelp, const CPubKey& mypk); // in rpcwallet.cpp
extern UniValue z_consolidationstatus(const UniValue& params, bool fHelp, const CPubKey& mypk); // in rpcwallet.cpp extern UniValue z_consolidationstatus(const UniValue& params, bool fHelp, const CPubKey& mypk); // in rpcwallet.cpp
extern UniValue z_consolidate(const UniValue& params, bool fHelp, const CPubKey& mypk); // in rpcwallet.cpp
extern UniValue z_shieldcoinbase(const UniValue& params, bool fHelp, const CPubKey& mypk); // in rpcwallet.cpp extern UniValue z_shieldcoinbase(const UniValue& params, bool fHelp, const CPubKey& mypk); // in rpcwallet.cpp
extern UniValue z_getoperationstatus(const UniValue& params, bool fHelp, const CPubKey& mypk); // in rpcwallet.cpp extern UniValue z_getoperationstatus(const UniValue& params, bool fHelp, const CPubKey& mypk); // in rpcwallet.cpp
extern UniValue z_getoperationresult(const UniValue& params, bool fHelp, const CPubKey& mypk); // in rpcwallet.cpp extern UniValue z_getoperationresult(const UniValue& params, bool fHelp, const CPubKey& mypk); // in rpcwallet.cpp
+56 -18
View File
@@ -20,6 +20,8 @@
static CMainSignals g_signals; static CMainSignals g_signals;
std::atomic<bool> fWalletNotifyFailed(false);
CMainSignals& GetMainSignals() CMainSignals& GetMainSignals()
{ {
return g_signals; return g_signals;
@@ -86,6 +88,31 @@ struct CachedBlockData {
pindex(pindex), oldTrees(oldTrees), txConflicted(txConflicted) {} pindex(pindex), oldTrees(oldTrees), txConflicted(txConflicted) {}
}; };
bool NotifyWalletsOrShutdown(const std::function<void()>& notify)
{
// The wallet can throw here on a database failure, e.g. CWalletDB::ListAccountCreditDebit's "error scanning
// DB" after BDB lost its file. Escaping this thread, that std::terminate()d the node (TraceThread logs and
// rethrows) with nothing flushed. Stop cleanly instead: going on would leave the wallet behind the chain,
// missing the block it failed on.
try {
notify();
return true;
} catch (const boost::thread_interrupted&) {
throw;
} catch (const std::exception& e) {
PrintExceptionContinue(&e, "ThreadNotifyWallets()");
} catch (...) {
PrintExceptionContinue(NULL, "ThreadNotifyWallets()");
}
LogPrintf("*** %s\n", "Wallet failed to process a block notification; shutting down");
fWalletNotifyFailed = true;
StartShutdown();
uiInterface.ThreadSafeMessageBox(
_("Error: A fatal internal error occurred, see debug.log for details"),
"", CClientUIInterface::MSG_ERROR);
return false;
}
void ThreadNotifyWallets(CBlockIndex *pindexLastTip) void ThreadNotifyWallets(CBlockIndex *pindexLastTip)
{ {
// If pindexLastTip == nullptr, the wallet is at genesis. // If pindexLastTip == nullptr, the wallet is at genesis.
@@ -203,15 +230,21 @@ void ThreadNotifyWallets(CBlockIndex *pindexLastTip)
_("Error: A fatal internal error occurred, see debug.log for details"), _("Error: A fatal internal error occurred, see debug.log for details"),
"", CClientUIInterface::MSG_ERROR); "", CClientUIInterface::MSG_ERROR);
StartShutdown(); StartShutdown();
// Don't hand the wallet an empty block as if it had been processed.
fDisconnectIncomplete = true;
break;
} }
// Let wallets know transactions went from 1-confirmed to if (!NotifyWalletsOrShutdown([&] {
// 0-confirmed or conflicted: // Let wallets know transactions went from 1-confirmed to
for (const CTransaction &tx : block.vtx) { // 0-confirmed or conflicted:
SyncWithWallets(tx, NULL); for (const CTransaction &tx : block.vtx) {
} SyncWithWallets(tx, NULL);
// Update cached incremental witnesses }
GetMainSignals().ChainTip(pindexLastTip, &block, boost::none); // Update cached incremental witnesses
GetMainSignals().ChainTip(pindexLastTip, &block, boost::none);
}))
return;
// On to the next block! // On to the next block!
pindexLastTip = pindexLastTip->pprev; pindexLastTip = pindexLastTip->pprev;
@@ -239,19 +272,24 @@ void ThreadNotifyWallets(CBlockIndex *pindexLastTip)
_("Error: A fatal internal error occurred, see debug.log for details"), _("Error: A fatal internal error occurred, see debug.log for details"),
"", CClientUIInterface::MSG_ERROR); "", CClientUIInterface::MSG_ERROR);
StartShutdown(); StartShutdown();
// Don't hand the wallet an empty block as if it had been processed.
break;
} }
// Tell wallet about transactions that went from mempool if (!NotifyWalletsOrShutdown([&] {
// to conflicted: // Tell wallet about transactions that went from mempool
for (const CTransaction &tx : blockData.txConflicted) { // to conflicted:
SyncWithWallets(tx, NULL); for (const CTransaction &tx : blockData.txConflicted) {
} SyncWithWallets(tx, NULL);
// ... and about transactions that got confirmed: }
for (const CTransaction &tx : block.vtx) { // ... and about transactions that got confirmed:
SyncWithWallets(tx, &block); for (const CTransaction &tx : block.vtx) {
} SyncWithWallets(tx, &block);
// Update cached incremental witnesses }
GetMainSignals().ChainTip(blockData.pindex, &block, blockData.oldTrees); // Update cached incremental witnesses
GetMainSignals().ChainTip(blockData.pindex, &block, blockData.oldTrees);
}))
return;
// This block is done! // This block is done!
pindexLastTip = blockData.pindex; pindexLastTip = blockData.pindex;
+10 -1
View File
@@ -8,6 +8,8 @@
#define HUSH_VALIDATIONINTERFACE_H #define HUSH_VALIDATIONINTERFACE_H
#include <boost/signals2/signal.hpp> #include <boost/signals2/signal.hpp>
#include <atomic>
#include <functional>
#include "zcash/IncrementalMerkleTree.hpp" #include "zcash/IncrementalMerkleTree.hpp"
class CBlock; class CBlock;
@@ -30,6 +32,9 @@ void UnregisterAllValidationInterfaces();
void EraseFromWallets(const uint256 &hash); void EraseFromWallets(const uint256 &hash);
/** Rescan all registered wallets */ /** Rescan all registered wallets */
void RescanWallets(); void RescanWallets();
/** Set when a wallet failed to process a block notification and the node is shutting down because of it:
* the shutdown must not then try to write the whole wallet into the database that just failed. */
extern std::atomic<bool> fWalletNotifyFailed;
class CValidationInterface { class CValidationInterface {
protected: protected:
@@ -38,7 +43,7 @@ protected:
virtual void EraseFromWallet(const uint256 &hash) {} virtual void EraseFromWallet(const uint256 &hash) {}
virtual void RescanWallet() {} virtual void RescanWallet() {}
virtual void ChainTip(const CBlockIndex *pindex, const CBlock *pblock, boost::optional<std::pair<SproutMerkleTree, SaplingMerkleTree>> added) {} virtual void ChainTip(const CBlockIndex *pindex, const CBlock *pblock, boost::optional<std::pair<SproutMerkleTree, SaplingMerkleTree>> added) {}
virtual void SetBestChain(const CBlockLocator &locator) {} virtual bool SetBestChain(const CBlockLocator &locator) { return true; }
virtual void UpdatedTransaction(const uint256 &hash) {} virtual void UpdatedTransaction(const uint256 &hash) {}
virtual void ResendWalletTransactions(int64_t nBestBlockTime) {} virtual void ResendWalletTransactions(int64_t nBestBlockTime) {}
virtual void BlockChecked(const CBlock&, const CValidationState&) {} virtual void BlockChecked(const CBlock&, const CValidationState&) {}
@@ -76,4 +81,8 @@ CMainSignals& GetMainSignals();
void ThreadNotifyWallets(CBlockIndex *pindexLastTip); void ThreadNotifyWallets(CBlockIndex *pindexLastTip);
/** Runs one block's wallet notifications for ThreadNotifyWallets. Returns false, after logging the error and
* requesting a shutdown, if they threw (e.g. a wallet database failure); thread interruption propagates. */
bool NotifyWalletsOrShutdown(const std::function<void()>& notify);
#endif // HUSH_VALIDATIONINTERFACE_H #endif // HUSH_VALIDATIONINTERFACE_H
+7 -1
View File
@@ -22,7 +22,13 @@
// network protocol versioning // network protocol versioning
// DragonX 1.0.0 - bumped to separate from old HUSH/DragonX nodes with RandomX bug // DragonX 1.0.0 - bumped to separate from old HUSH/DragonX nodes with RandomX bug
static const int PROTOCOL_VERSION = 2000000; // DragonX 1.3.0 - bumped for the consensus changes in this release (BLOCK_VALID_CONTEXT
// no longer overwrites the validity level, the dead CBOPRET coinbase
// price check is gone, and pow.cpp lost 157 lines). MIN_PEER_PROTO_VERSION
// is deliberately NOT raised: it currently equals this value, and raising
// it would disconnect every node still on v1.0.3 -- which is all users,
// since no release has ever been installable (unsigned archives).
static const int PROTOCOL_VERSION = 2000001;
//! initial proto version, to be increased after version/verack negotiation //! initial proto version, to be increased after version/verack negotiation
static const int INIT_PROTO_VERSION = 209; static const int INIT_PROTO_VERSION = 209;
//! In this version, 'getheaders' was introduced. //! In this version, 'getheaders' was introduced.
@@ -8,7 +8,9 @@
#include "asyncrpcoperation_saplingconsolidation.h" #include "asyncrpcoperation_saplingconsolidation.h"
#include "init.h" #include "init.h"
#include "key_io.h" #include "key_io.h"
#include "asyncrpcqueue.h"
#include "rpc/protocol.h" #include "rpc/protocol.h"
#include "rpc/server.h"
#include "random.h" #include "random.h"
#include "sync.h" #include "sync.h"
#include "tinyformat.h" #include "tinyformat.h"
@@ -17,6 +19,10 @@
#include "utilmoneystr.h" #include "utilmoneystr.h"
#include "wallet.h" #include "wallet.h"
#include <algorithm>
#include <climits>
#include <set>
CAmount fConsolidationTxFee = DEFAULT_CONSOLIDATION_FEE; CAmount fConsolidationTxFee = DEFAULT_CONSOLIDATION_FEE;
bool fConsolidationMapUsed = false; bool fConsolidationMapUsed = false;
@@ -28,7 +34,188 @@ static const int MIN_ZOUTS = 7;
extern string randomSietchZaddr(); extern string randomSietchZaddr();
AsyncRPCOperation_saplingconsolidation::AsyncRPCOperation_saplingconsolidation(int targetHeight) : targetHeight_(targetHeight) {} // Whether another operation waits in the async queue. dragonxd has a single async worker, so an
// operation queued during a round (a z_sendmany, say) runs only once the round is over.
static bool OtherAsyncOperationWaiting(const AsyncRPCOperationId& self) {
std::shared_ptr<AsyncRPCQueue> q = getAsyncRPCQueue();
for (const AsyncRPCOperationId& id : q->getAllOperationIds()) {
if (id == self)
continue;
std::shared_ptr<AsyncRPCOperation> op = q->getOperationForId(id);
if (op && op->isReady())
return true;
}
return false;
}
int SaplingConsolidationMaxInputs(size_t maxTxSize) {
// Everything but the descriptions (header, value balance, binding signature, counts) is a few
// hundred bytes; 1000 leaves room to spare.
const size_t overhead = 1000;
const size_t outputs = (1 + MIN_ZOUTS) * OUTPUTDESCRIPTION_SIZE;
if (maxTxSize <= overhead + outputs)
return 0;
return (int)std::min<size_t>((maxTxSize - overhead - outputs) / SPENDDESCRIPTION_SIZE, INT_MAX);
}
int ClampSaplingConsolidationBatchSize(int requested, size_t maxTxSize) {
int batch = std::max(MIN_CONSOLIDATION_BATCHSIZE, std::min(requested, MAX_CONSOLIDATION_BATCHSIZE));
return std::min(batch, SaplingConsolidationMaxInputs(maxTxSize));
}
std::vector<SaplingConsolidationBatch> PlanSaplingConsolidation(
const std::vector<std::vector<CAmount>>& groups,
const SaplingConsolidationPolicy& policy,
const std::function<uint64_t(uint64_t)>& rng)
{
std::vector<SaplingConsolidationBatch> plan;
const int batch = ClampSaplingConsolidationBatchSize(policy.batchSize, policy.maxTxSize);
if (batch < 2)
return plan;
// ceil(2*batch/3), at least 2: the low end of the per-tx input count.
const int low = std::max(2, (2 * batch + 2) / 3);
for (size_t g = 0; g < groups.size(); g++) {
const std::vector<CAmount>& values = groups[g];
if (policy.threshold < 0 || values.size() <= (size_t)policy.threshold)
continue;
// Smallest first; ties keep wallet order so the plan is deterministic for a given rng.
std::vector<size_t> order(values.size());
for (size_t i = 0; i < order.size(); i++)
order[i] = i;
std::stable_sort(order.begin(), order.end(),
[&values](size_t a, size_t b) { return values[a] < values[b]; });
size_t next = 0;
for (int t = 0; t < policy.maxTxs; t++) {
const size_t left = order.size() - next;
size_t take = low + (size_t)rng((uint64_t)(batch - low + 1));
take = std::min<size_t>(take, batch);
// Leave at least one note out of the round so the address stays spendable meanwhile.
if (left == 0 || take > left - 1)
take = (left == 0) ? 0 : left - 1;
if (take < 2)
break;
SaplingConsolidationBatch b;
b.group = g;
b.notes.assign(order.begin() + next, order.begin() + next + take);
next += take;
plan.push_back(std::move(b));
}
}
return plan;
}
SaplingConsolidationSpendPlan PlanSaplingConsolidationSpends(
const std::vector<std::vector<CAmount>>& groups,
const SaplingConsolidationPolicy& policy,
const std::function<uint64_t(uint64_t)>& rng,
const std::function<boost::optional<uint256>(size_t, size_t)>& rootOf,
const std::function<bool(const uint256&)>& isChainAnchor,
const uint256& preferredAnchor)
{
SaplingConsolidationSpendPlan result;
std::map<std::pair<size_t, size_t>, boost::optional<uint256>> roots;
std::map<uint256, bool> chainAnchor;
// A planned note's root if it is a chain anchor, else none.
auto usableRoot = [&](size_t g, size_t i) -> boost::optional<uint256> {
const std::pair<size_t, size_t> key(g, i);
auto ri = roots.find(key);
if (ri == roots.end())
ri = roots.insert(std::make_pair(key, rootOf(g, i))).first;
if (!ri->second)
return boost::none;
auto ai = chainAnchor.find(*ri->second);
if (ai == chainAnchor.end())
ai = chainAnchor.insert(std::make_pair(*ri->second, isChainAnchor(*ri->second))).first;
return ai->second ? ri->second : boost::none;
};
// Each pass leaves out at least one more note or is the last, so this ends.
std::vector<std::set<size_t>> excluded(groups.size());
for (;;) {
std::vector<std::vector<size_t>> live(groups.size());
std::vector<std::vector<CAmount>> values(groups.size());
for (size_t g = 0; g < groups.size(); g++) {
for (size_t i = 0; i < groups[g].size(); i++) {
if (excluded[g].count(i))
continue;
live[g].push_back(i);
values[g].push_back(groups[g][i]);
}
}
std::vector<SaplingConsolidationBatch> plan = PlanSaplingConsolidation(values, policy, rng);
for (SaplingConsolidationBatch& b : plan)
for (size_t& idx : b.notes)
idx = live[b.group][idx];
// An address planned for the first time gets its anchor from its planned notes; it then keeps it.
std::map<size_t, std::map<uint256, int>> votes;
for (const SaplingConsolidationBatch& b : plan) {
if (result.anchors.count(b.group))
continue;
for (size_t i : b.notes) {
boost::optional<uint256> root = usableRoot(b.group, i);
if (root)
votes[b.group][*root]++;
}
}
for (const auto& v : votes) {
if (v.second.count(preferredAnchor)) {
result.anchors[v.first] = preferredAnchor;
continue;
}
int best = 0;
for (const auto& rv : v.second) {
if (rv.second > best) {
best = rv.second;
result.anchors[v.first] = rv.first;
}
}
}
bool dropped = false;
for (const SaplingConsolidationBatch& b : plan) {
auto anchor = result.anchors.find(b.group);
for (size_t i : b.notes) {
boost::optional<uint256> root = usableRoot(b.group, i);
if (root && anchor != result.anchors.end() && *root == anchor->second)
continue;
if (root)
result.deferred.push_back(std::make_pair(b.group, i));
else
result.unusable.push_back(std::make_pair(b.group, i));
excluded[b.group].insert(i);
dropped = true;
}
}
if (!dropped) {
result.batches = std::move(plan);
break;
}
}
// An address whose notes were all left out ends up without batches; it needs no anchor.
std::set<size_t> planned;
for (const SaplingConsolidationBatch& b : result.batches)
planned.insert(b.group);
for (auto it = result.anchors.begin(); it != result.anchors.end(); ) {
if (planned.count(it->first))
++it;
else
it = result.anchors.erase(it);
}
return result;
}
CAmount SaplingConsolidationTxFee(CAmount amount, CAmount fee) {
// Notes worth no more than the fee go fee-free rather than being burnt into it.
return amount <= fee ? 0 : fee;
}
AsyncRPCOperation_saplingconsolidation::AsyncRPCOperation_saplingconsolidation(int targetHeight, const SaplingConsolidationRequest& request)
: targetHeight_(targetHeight), request_(request) {}
AsyncRPCOperation_saplingconsolidation::~AsyncRPCOperation_saplingconsolidation() {} AsyncRPCOperation_saplingconsolidation::~AsyncRPCOperation_saplingconsolidation() {}
@@ -87,6 +274,22 @@ void AsyncRPCOperation_saplingconsolidation::main() {
int tipHeight = (chainActive.Tip() != NULL) ? chainActive.Tip()->GetHeight() : targetHeight_; int tipHeight = (chainActive.Tip() != NULL) ? chainActive.Tip()->GetHeight() : targetHeight_;
pwalletMain->nextConsolidation = pwalletMain->consolidationInterval + tipHeight; pwalletMain->nextConsolidation = pwalletMain->consolidationInterval + tipHeight;
pwalletMain->fConsolidationRunning = false; pwalletMain->fConsolidationRunning = false;
SaplingConsolidationRound round;
round.height = tipHeight;
round.manual = request_.manual;
round.time = GetTime();
round.txids = tally_.txids;
round.notesMerged = tally_.notesMerged;
round.amountMerged = tally_.amountMerged;
round.amountConsolidated = tally_.amountConsolidated;
round.fees = tally_.fees;
round.skippedNotes = tally_.skippedNotes;
round.yielded = tally_.yielded;
round.error = tally_.error;
if (!success && round.error.empty())
round.error = getErrorMessage();
pwalletMain->consolidationStats.Record(round);
} }
} }
} }
@@ -94,7 +297,9 @@ void AsyncRPCOperation_saplingconsolidation::main() {
bool AsyncRPCOperation_saplingconsolidation::main_impl() { bool AsyncRPCOperation_saplingconsolidation::main_impl() {
bool status=true; bool status=true;
auto opid=getId(); auto opid=getId();
LogPrintf("%s: Beginning AsyncRPCOperation_saplingconsolidation\n", opid); LogPrintf("%s: Beginning AsyncRPCOperation_saplingconsolidation%s (threshold=%d batchsize=%d maxtxs=%d fee=%d)\n",
opid, request_.manual ? " (z_consolidate)" : "", request_.policy.threshold,
request_.policy.batchSize, request_.policy.maxTxs, (int)request_.fee);
auto consensusParams = Params().GetConsensus(); auto consensusParams = Params().GetConsensus();
int tipHeight; int tipHeight;
{ {
@@ -109,197 +314,269 @@ bool AsyncRPCOperation_saplingconsolidation::main_impl() {
auto nextActivationHeight = NextActivationHeight(tipHeight, consensusParams); auto nextActivationHeight = NextActivationHeight(tipHeight, consensusParams);
if (nextActivationHeight && tipHeight + AUTO_OP_EXPIRY_DELTA >= nextActivationHeight.get()) { if (nextActivationHeight && tipHeight + AUTO_OP_EXPIRY_DELTA >= nextActivationHeight.get()) {
LogPrintf("%s: Consolidation txs would be created before a NU activation but may expire after. Skipping this round.\n",opid); LogPrintf("%s: Consolidation txs would be created before a NU activation but may expire after. Skipping this round.\n",opid);
setConsolidationResult(0, 0, std::vector<std::string>()); setConsolidationResult(ConsolidationTally());
return status; return status;
} }
std::vector<SaplingNoteEntry> saplingEntries; // One address's eligible notes and the key that spends them.
std::set<libzcash::SaplingPaymentAddress> addresses; struct AddressNotes {
libzcash::SaplingPaymentAddress addr;
libzcash::SaplingExtendedSpendingKey extsk;
std::vector<SaplingNoteEntry> notes;
};
// One transaction to build: notes of one address, with witnesses that share one anchor.
struct PlannedTx {
size_t group;
std::vector<SaplingNoteEntry> notes;
std::vector<SaplingWitness> witnesses;
uint256 anchor;
};
std::vector<AddressNotes> groups;
std::vector<PlannedTx> txs;
// The member, not a local: if anything below throws, main() still records what was committed.
ConsolidationTally& tally = tally_;
{ {
LOCK2(cs_main, pwalletMain->cs_wallet); LOCK2(cs_main, pwalletMain->cs_wallet);
// We set minDepth to 11 to avoid unconfirmed notes and in anticipation of specifying // We set minDepth to 11 to avoid unconfirmed notes and in anticipation of specifying
// an anchor at height N-10 for each SpendDescription // an anchor at height N-10 for each SpendDescription. Spent (also by a mempool tx) and
// Consider, should notes be sorted? // locked notes are left out, as are notes this wallet can't spend.
pwalletMain->GetFilteredNotes(saplingEntries, "", 11); std::vector<SaplingNoteEntry> saplingEntries;
pwalletMain->GetFilteredNotes(saplingEntries, "", CONSOLIDATION_MIN_DEPTH);
if(saplingEntries.size() == 0) { std::set<libzcash::SaplingPaymentAddress> wanted(request_.addresses.begin(), request_.addresses.end());
LogPrintf("%s: Nothing to consolidate, done.\n",opid); std::map<libzcash::SaplingPaymentAddress, size_t> groupOf;
return true; std::set<libzcash::SaplingPaymentAddress> noKey;
} for (const SaplingNoteEntry& entry : saplingEntries) {
if (!wanted.empty() && wanted.count(entry.address) == 0)
// store sapling inputs so we can correctly lock and unlock them continue;
for (auto entry : saplingEntries) { auto it = groupOf.find(entry.address);
z_sapling_inputs_.push_back(entry); if (it == groupOf.end()) {
} if (noKey.count(entry.address))
continue;
if (fConsolidationMapUsed) { AddressNotes g;
const vector<string>& v = mapMultiArgs["-consolidatesaplingaddress"]; g.addr = entry.address;
for(int i = 0; i < v.size(); i++) { if (!pwalletMain->GetSaplingExtendedSpendingKey(entry.address, g.extsk)) {
auto zAddress = DecodePaymentAddress(v[i]); noKey.insert(entry.address);
if (boost::get<libzcash::SaplingPaymentAddress>(&zAddress) != nullptr) { continue;
libzcash::SaplingPaymentAddress saplingAddress = boost::get<libzcash::SaplingPaymentAddress>(zAddress);
addresses.insert(saplingAddress);
} else {
LogPrintf("%s: Invalid zaddr, exiting\n", opid);
return false;
} }
it = groupOf.insert(std::make_pair(entry.address, groups.size())).first;
groups.push_back(std::move(g));
}
groups[it->second].notes.push_back(entry);
}
// Plan the round over the notes that can be spent: a planned note whose witness is missing, or whose
// root the chain never had as an anchor (a desynced witness), is left out and the round re-planned
// without it. Checking the root against the chain, not just against the other notes, keeps a tx from
// being proved at an anchor no node accepts when the desynced notes are the majority of a batch.
const uint256 tipRoot = (chainActive.Tip() != NULL) ? chainActive.Tip()->hashFinalSaplingRoot : uint256();
std::vector<std::vector<CAmount>> values(groups.size());
for (size_t g = 0; g < groups.size(); g++)
for (const SaplingNoteEntry& entry : groups[g].notes)
values[g].push_back(CAmount(entry.note.value()));
std::map<std::pair<size_t, size_t>, SaplingWitness> witnessOf;
SaplingConsolidationSpendPlan spendPlan = PlanSaplingConsolidationSpends(
values, request_.policy, [](uint64_t n) { return GetRand(n); },
[&](size_t g, size_t i) -> boost::optional<uint256> {
boost::optional<SaplingWitness> w = pwalletMain->GetSaplingNoteLatestWitness(groups[g].notes[i].op);
if (!w)
return boost::none;
witnessOf.insert(std::make_pair(std::make_pair(g, i), *w));
return w->root();
},
[](const uint256& root) {
SaplingMerkleTree tree;
return pcoinsTip->GetSaplingAnchorAt(root, tree);
},
tipRoot);
for (const SaplingConsolidationBatch& b : spendPlan.batches) {
PlannedTx tx;
tx.group = b.group;
tx.anchor = spendPlan.anchors.at(b.group);
for (size_t i : b.notes) {
tx.notes.push_back(groups[b.group].notes[i]);
tx.witnesses.push_back(witnessOf.at(std::make_pair(b.group, i)));
}
txs.push_back(std::move(tx));
}
// One line per round, not one per note: a note can be unusable for a while (a witness rebuild in
// progress) and fine later, so the next round reports it again rather than never.
tally.skippedNotes = spendPlan.unusable.size() + spendPlan.deferred.size();
if (!spendPlan.unusable.empty()) {
std::string some;
for (size_t k = 0; k < spendPlan.unusable.size() && k < 5; k++) {
const SaplingOutPoint& op = groups[spendPlan.unusable[k].first].notes[spendPlan.unusable[k].second].op;
some += strprintf("%s%s:%u", k ? ", " : "", op.hash.ToString(), op.n);
}
LogPrintf("%s: skipping %d notes without a usable witness (none, or not at a chain anchor): %s%s\n",
opid, spendPlan.unusable.size(), some, spendPlan.unusable.size() > 5 ? ", ..." : "");
}
if (!spendPlan.deferred.empty())
LogPrintf("%s: deferring %d notes whose witness is at another anchor than the rest of their address\n",
opid, spendPlan.deferred.size());
// Lock just the notes this round spends, before the locks are released for proving, so a send
// made meanwhile neither picks them nor goes without the rest of the wallet's notes.
for (const PlannedTx& tx : txs) {
for (const SaplingNoteEntry& entry : tx.notes) {
pwalletMain->LockNote(entry.op);
z_sapling_inputs_.push_back(entry);
} }
} else {
pwalletMain->GetSaplingPaymentAddresses(addresses);
} }
} }
int numTxCreated = 0; if (txs.empty()) {
std::vector<std::string> consolidationTxIds; LogPrintf("%s: Nothing to consolidate (no address over %d eligible notes), done.\n", opid, request_.policy.threshold);
CAmount amountConsolidated = 0; setConsolidationResult(tally);
CCoinsViewCache coinsView(pcoinsTip); return true;
}
LogPrint("zrpc", "%s: %d consolidation input notes locked for %d transactions\n", opid, z_sapling_inputs_.size(), txs.size());
for (auto addr : addresses) { // A tx that fails ends its own address's part of the round, not the other addresses'. The round's error
libzcash::SaplingExtendedSpendingKey extsk; // is the first such failure.
if (pwalletMain->GetSaplingExtendedSpendingKey(addr, extsk)) { std::set<size_t> failedGroups;
auto failAddress = [&](size_t g, const std::string& why) {
LogPrintf("%s: %s; skipping the rest of this round for address %s\n",
opid, why, groups[g].addr.GetHash().ToString());
failedGroups.insert(g);
if (tally.error.empty())
tally.error = why;
status = false;
};
std::vector<SaplingNoteEntry> fromNotes; for (const PlannedTx& planned : txs) {
CAmount amountToSend = 0; // The queue's cancel at shutdown never reaches an executing op (AsyncRPCOperation::cancel() is
// max of 8 zins means the tx cannot reduce the anonset, // not virtual), so look for the shutdown here, or a stop would wait for the whole round.
// since there will be 8 zins and 8 zouts at worst case if (isCancelled() || ShutdownRequested()) {
// This also helps reduce ztx creation time LogPrintf("%s: %s. Stopping.\n", opid, isCancelled() ? "Canceled" : "Shutting down");
int maxQuantity = rand() % 8 + 1; tally.error = isCancelled() ? "cancelled" : "shutting down";
for (const SaplingNoteEntry& saplingEntry : saplingEntries) { status=false;
break;
}
// Once a tx is made, give the worker to anything queued meanwhile: the notes not spent yet are
// unlocked and the next round takes them up.
if (!tally.txids.empty() && OtherAsyncOperationWaiting(opid)) {
LogPrintf("%s: an async operation is waiting; ending the round after %d transactions\n",
opid, tally.txids.size());
tally.yielded = true;
break;
}
if (failedGroups.count(planned.group))
continue;
const AddressNotes& group = groups[planned.group];
libzcash::SaplingIncomingViewingKey ivk; auto builder = TransactionBuilder(consensusParams, tipHeight, pwalletMain);
pwalletMain->GetSaplingIncomingViewingKey(boost::get<libzcash::SaplingPaymentAddress>(saplingEntry.address), ivk); builder.SetExpiryHeight(tipHeight + AUTO_OP_EXPIRY_DELTA);
//Select Notes from that same address we will be sending to. CAmount amountToSend = 0;
if (ivk == extsk.expsk.full_viewing_key().in_viewing_key()) { for (const SaplingNoteEntry& entry : planned.notes)
amountToSend += CAmount(saplingEntry.note.value()); amountToSend += CAmount(entry.note.value());
fromNotes.push_back(saplingEntry); CAmount thisTxFee = SaplingConsolidationTxFee(amountToSend, request_.fee);
} CAmount actualAmountToSend = amountToSend - thisTxFee;
LogPrintf("%s: %s Beginning to create transaction with %d Sapling inputs, output amount=%s\n",
__func__, opid, planned.notes.size(), FormatMoney(actualAmountToSend));
//Only use a randomly determined number of notes // Add Sapling spends
if (fromNotes.size() >= maxQuantity) bool spendsOk = true;
break; for (size_t i = 0; i < planned.notes.size(); i++) {
if (!builder.AddSaplingSpend(group.extsk.expsk, planned.notes[i].note, planned.anchor, planned.witnesses[i])) {
} spendsOk = false;
// minimum required
// We use 3 so that addresses can spent one zutxo and still have another zutxo to use while that
// tx is confirming
int minQuantity = 3;
if (fromNotes.size() < minQuantity)
continue;
auto builder = TransactionBuilder(consensusParams, tipHeight, pwalletMain);
builder.SetExpiryHeight(tipHeight + AUTO_OP_EXPIRY_DELTA);
auto actualAmountToSend = amountToSend < fConsolidationTxFee ? 0 : amountToSend - fConsolidationTxFee;
LogPrintf("%s: %s Beginning to create transaction with Sapling output amount=%s\n", __func__, opid, FormatMoney(actualAmountToSend));
// Select Sapling notes
std::vector<SaplingOutPoint> ops;
std::vector<libzcash::SaplingNote> notes;
for (auto fromNote : fromNotes) {
ops.push_back(fromNote.op);
notes.push_back(fromNote.note);
}
// Fetch Sapling anchor and witnesses
uint256 anchor;
std::vector<boost::optional<SaplingWitness>> witnesses;
{
LOCK2(cs_main, pwalletMain->cs_wallet);
// LogPrint("zrpcunsafe", "%s: Fetching note witnesses\n", opid);
pwalletMain->GetSaplingNoteWitnesses(ops, witnesses, anchor);
}
// Add Sapling spends
for (size_t i = 0; i < notes.size(); i++) {
if (!witnesses[i]) {
LogPrintf("%s: Missing Witnesses! Stopping.\n", opid);
status=false;
break;
}
builder.AddSaplingSpend(extsk.expsk, notes[i], anchor, witnesses[i].get());
LogPrint("zrpcunsafe", "%s: Added consolidation input %d\n", opid, i);
}
CAmount thisTxFee = amountToSend < fConsolidationTxFee ? 0 : fConsolidationTxFee;
LogPrint("zrpcunsafe", "%s: Using fee=%d\n", opid, thisTxFee);
builder.SetFee(thisTxFee);
// Add the actual consolidation tx
builder.AddSaplingOutput(extsk.expsk.ovk, addr, actualAmountToSend);
LogPrint("zrpcunsafe", "%s: Added consolidation output %s with amount=%li\n", opid, addr.GetHash().ToString().c_str(), actualAmountToSend);
// Add sietch zouts: MIN_ZOUTS dummy zero-value shielded outputs to
// randomly-generated z-addresses, so the consolidation tx does not
// shrink the anonymity set.
for(size_t i = 0; i < MIN_ZOUTS; i++) {
string zdust = randomSietchZaddr();
auto zaddr = DecodePaymentAddress(zdust);
if (IsValidPaymentAddress(zaddr)) {
CAmount amount=0;
auto sietchZoutput = boost::get<libzcash::SaplingPaymentAddress>(zaddr);
LogPrint("zrpcunsafe", "%s: Adding Sietch zdust output %d %s amount=%li\n", opid, i, zdust, amount);
// actually add our sietch zoutput, the new way
builder.AddSaplingOutput(extsk.expsk.ovk, sietchZoutput, amount);
} else {
LogPrintf("%s: Invalid payment address %s! Stopping.\n", opid, zdust);
status = false;
break;
}
}
LogPrint("zrpcunsafe", "%s: Done adding %d sietch zouts\n", opid, MIN_ZOUTS);
auto maybe_tx = builder.Build();
if (!maybe_tx) {
LogPrintf("%s: Failed to build transaction.\n",opid);
status=false;
break; break;
} }
CTransaction tx = maybe_tx.get(); LogPrint("zrpcunsafe", "%s: Added consolidation input %d\n", opid, i);
}
if (!spendsOk) {
failAddress(planned.group, "inputs do not share one anchor");
continue;
}
if (isCancelled()) { LogPrint("zrpcunsafe", "%s: Using fee=%d\n", opid, thisTxFee);
LogPrintf("%s: Canceled. Stopping.\n", opid); builder.SetFee(thisTxFee);
status=false;
break;
}
// Lock shielded input notes // Add the actual consolidation tx
lock_notes(); builder.AddSaplingOutput(group.extsk.expsk.ovk, group.addr, actualAmountToSend);
LogPrint("zrpc", "%s: consolidation input notes locked\n", getId()); LogPrint("zrpcunsafe", "%s: Added consolidation output %s with amount=%li\n", opid, group.addr.GetHash().ToString().c_str(), actualAmountToSend);
if(pwalletMain->CommitAutomatedTx(tx)) { // Add sietch zouts: MIN_ZOUTS dummy zero-value shielded outputs to
LogPrintf("%s: Committed consolidation transaction with txid=%s\n",opid, tx.GetHash().ToString()); // randomly-generated z-addresses, so the consolidation tx does not
amountConsolidated += actualAmountToSend; // shrink the anonymity set.
consolidationTxIds.push_back(tx.GetHash().ToString()); bool zoutsOk = true;
numTxCreated++; for(size_t i = 0; i < MIN_ZOUTS; i++) {
string zdust = randomSietchZaddr();
auto zaddr = DecodePaymentAddress(zdust);
if (IsValidPaymentAddress(zaddr)) {
CAmount amount=0;
auto sietchZoutput = boost::get<libzcash::SaplingPaymentAddress>(zaddr);
LogPrint("zrpcunsafe", "%s: Adding Sietch zdust output %d %s amount=%li\n", opid, i, zdust, amount);
// actually add our sietch zoutput, the new way
builder.AddSaplingOutput(group.extsk.expsk.ovk, sietchZoutput, amount);
} else { } else {
LogPrintf("%s: Consolidation transaction FAILED in CommitTransaction, txid=%s\n",opid , tx.GetHash().ToString()); LogPrintf("%s: Invalid payment address %s!\n", opid, zdust);
zoutsOk = false;
unlock_notes();
LogPrint("zrpc", "%s: consolidatoin input notes unlocked\n", getId());
setConsolidationResult(numTxCreated, amountConsolidated, consolidationTxIds);
status = false;
break; break;
} }
}
if (!zoutsOk) {
failAddress(planned.group, "invalid sietch address");
continue;
}
LogPrint("zrpcunsafe", "%s: Done adding %d sietch zouts\n", opid, MIN_ZOUTS);
auto maybe_tx = builder.Build();
if (!maybe_tx) {
failAddress(planned.group, "failed to build transaction");
continue;
}
CTransaction tx = maybe_tx.get();
if (isCancelled() || ShutdownRequested()) {
LogPrintf("%s: %s. Stopping.\n", opid, isCancelled() ? "Canceled" : "Shutting down");
tally.error = isCancelled() ? "cancelled" : "shutting down";
status=false;
break;
}
if(pwalletMain->CommitAutomatedTx(tx)) {
LogPrintf("%s: Committed consolidation transaction with txid=%s\n",opid, tx.GetHash().ToString());
tally.txids.push_back(tx.GetHash().ToString());
tally.notesMerged += planned.notes.size();
tally.amountMerged += amountToSend;
tally.amountConsolidated += actualAmountToSend;
tally.fees += thisTxFee;
} else {
LogPrintf("%s: Consolidation transaction FAILED in CommitTransaction, txid=%s\n",opid , tx.GetHash().ToString());
failAddress(planned.group, "transaction was not accepted (CommitTransaction failed)");
continue;
} }
} }
LogPrintf("%s: Created %d transactions with total Sapling output amount=%s,status=%d\n",opid , numTxCreated, FormatMoney(amountConsolidated), (int)status); LogPrintf("%s: Created %d transactions merging %d notes with total Sapling output amount=%s, skipped %d notes, yielded=%d, status=%d\n",
setConsolidationResult(numTxCreated, amountConsolidated, consolidationTxIds); opid, tally.txids.size(), tally.notesMerged, FormatMoney(tally.amountConsolidated), tally.skippedNotes,
(int)tally.yielded, (int)status);
setConsolidationResult(tally);
return status; return status;
} }
void AsyncRPCOperation_saplingconsolidation::setConsolidationResult(int numTxCreated, const CAmount& amountConsolidated, const std::vector<std::string>& consolidationTxIds) { void AsyncRPCOperation_saplingconsolidation::setConsolidationResult(const ConsolidationTally& tally) {
if (&tally != &tally_)
tally_ = tally;
UniValue res(UniValue::VOBJ); UniValue res(UniValue::VOBJ);
res.push_back(Pair("num_tx_created", numTxCreated)); res.push_back(Pair("num_tx_created", (int)tally.txids.size()));
res.push_back(Pair("amount_consolidated", FormatMoney(amountConsolidated))); res.push_back(Pair("amount_consolidated", FormatMoney(tally.amountConsolidated)));
UniValue txIds(UniValue::VARR); UniValue txIds(UniValue::VARR);
for (const std::string& txId : consolidationTxIds) { for (const std::string& txId : tally.txids) {
txIds.push_back(txId); txIds.push_back(txId);
} }
res.push_back(Pair("consolidation_txids", txIds)); res.push_back(Pair("consolidation_txids", txIds));
res.push_back(Pair("notes_merged", tally.notesMerged));
res.push_back(Pair("amount_merged", FormatMoney(tally.amountMerged)));
res.push_back(Pair("fees", FormatMoney(tally.fees)));
res.push_back(Pair("skipped_notes", tally.skippedNotes));
res.push_back(Pair("yielded", tally.yielded));
if (!tally.error.empty())
res.push_back(Pair("error", tally.error));
set_result(res); set_result(res);
} }
@@ -319,17 +596,10 @@ UniValue AsyncRPCOperation_saplingconsolidation::getStatus() const {
UniValue obj = v.get_obj(); UniValue obj = v.get_obj();
obj.push_back(Pair("method", "saplingconsolidation")); obj.push_back(Pair("method", "saplingconsolidation"));
obj.push_back(Pair("target_height", targetHeight_)); obj.push_back(Pair("target_height", targetHeight_));
obj.push_back(Pair("manual", request_.manual));
return obj; return obj;
} }
// Lock input notes
void AsyncRPCOperation_saplingconsolidation::lock_notes() {
LOCK2(cs_main, pwalletMain->cs_wallet);
for (auto note : z_sapling_inputs_) {
pwalletMain->LockNote(note.op);
}
}
// Unlock input notes // Unlock input notes
void AsyncRPCOperation_saplingconsolidation::unlock_notes() { void AsyncRPCOperation_saplingconsolidation::unlock_notes() {
LOCK2(cs_main, pwalletMain->cs_wallet); LOCK2(cs_main, pwalletMain->cs_wallet);
@@ -3,6 +3,9 @@
// Distributed under the GPLv3 software license, see the accompanying // Distributed under the GPLv3 software license, see the accompanying
// file COPYING or https://www.gnu.org/licenses/gpl-3.0.en.html // file COPYING or https://www.gnu.org/licenses/gpl-3.0.en.html
#ifndef HUSH_WALLET_ASYNCRPCOPERATION_SAPLINGCONSOLIDATION_H
#define HUSH_WALLET_ASYNCRPCOPERATION_SAPLINGCONSOLIDATION_H
#include "amount.h" #include "amount.h"
#include "asyncrpcoperation.h" #include "asyncrpcoperation.h"
#include "univalue.h" #include "univalue.h"
@@ -10,15 +13,104 @@
#include "zcash/zip32.h" #include "zcash/zip32.h"
#include "wallet.h" // for SaplingNoteEntry #include "wallet.h" // for SaplingNoteEntry
#include <functional>
#include <map>
#include <utility>
#include <vector>
#include <boost/optional.hpp>
//Default fee used for consolidation transactions, in puposhis //Default fee used for consolidation transactions, in puposhis
static const CAmount DEFAULT_CONSOLIDATION_FEE = 10000; static const CAmount DEFAULT_CONSOLIDATION_FEE = 10000;
extern CAmount fConsolidationTxFee; extern CAmount fConsolidationTxFee;
extern bool fConsolidationMapUsed; extern bool fConsolidationMapUsed;
// What one consolidation round may do (see PlanSaplingConsolidation).
struct SaplingConsolidationPolicy {
int threshold = DEFAULT_CONSOLIDATION_THRESHOLD; // only addresses with MORE eligible notes than this
int batchSize = DEFAULT_CONSOLIDATION_BATCHSIZE; // most notes one transaction spends
int maxTxs = DEFAULT_CONSOLIDATION_MAXTXS; // most transactions per address per round
size_t maxTxSize = MAX_TX_SIZE_AFTER_SAPLING; // the batch is also capped to what fits in this
};
// One planned consolidation transaction: notes of a single address merged back into it.
struct SaplingConsolidationBatch {
size_t group; // index of the address in the groups handed to the planner
std::vector<size_t> notes; // indices into that address's note values
};
// Most spends a consolidation tx can carry next to its 1 + MIN_ZOUTS outputs within maxTxSize.
int SaplingConsolidationMaxInputs(size_t maxTxSize);
// The batch size actually used: clamped to [MIN_CONSOLIDATION_BATCHSIZE, MAX_CONSOLIDATION_BATCHSIZE]
// and to SaplingConsolidationMaxInputs(maxTxSize).
int ClampSaplingConsolidationBatchSize(int requested, size_t maxTxSize = MAX_TX_SIZE_AFTER_SAPLING);
// Plans one round. groups[i] holds the values of address i's eligible notes. Only an address with more
// than policy.threshold notes is consolidated. Its notes are taken smallest first (so the note an earlier
// round produced is not merged again and again), up to policy.maxTxs transactions, each spending a count
// drawn uniformly from [max(2, ceil(2*batch/3)), batch] so rounds don't all look alike. A transaction never
// takes the address's last remaining note (one stays spendable while the round confirms), and the address
// is done once fewer than two notes could be taken. Batches never mix addresses. rng(n) returns a uniform
// value in [0, n); pure apart from it.
std::vector<SaplingConsolidationBatch> PlanSaplingConsolidation(
const std::vector<std::vector<CAmount>>& groups,
const SaplingConsolidationPolicy& policy,
const std::function<uint64_t(uint64_t)>& rng);
// A round planned over the notes it can spend (see PlanSaplingConsolidationSpends). Note indices are the
// caller's: into the address's values as given.
struct SaplingConsolidationSpendPlan {
std::vector<SaplingConsolidationBatch> batches;
std::map<size_t, uint256> anchors; // per address with batches: the anchor of all its spends
std::vector<std::pair<size_t, size_t>> unusable; // (address, note): no witness, or one at no chain anchor
std::vector<std::pair<size_t, size_t>> deferred; // (address, note): witness at another chain anchor
};
// Plans a round as PlanSaplingConsolidation does, but only over notes that can be spent together. rootOf(g, i)
// is the root of note i of address g's witness (none: there is none), isChainAnchor(root) whether the chain
// holds that root as a Sapling anchor, which is what consensus checks a spend's anchor against. An address's
// spends all use one anchor: preferredAnchor (the tip's root, where the wallet keeps its witnesses) when one
// of its planned notes is there, else the chain anchor most of them share. A planned note whose witness is
// missing or at no chain anchor is left out as unusable; one at another chain anchor is deferred to a later
// round. The round is then planned again without them, until no planned note is left out. Planned notes on a
// root the chain never had therefore can't outvote the address's good ones, however many they are. rootOf is
// called at most once per note and isChainAnchor at most once per root.
SaplingConsolidationSpendPlan PlanSaplingConsolidationSpends(
const std::vector<std::vector<CAmount>>& groups,
const SaplingConsolidationPolicy& policy,
const std::function<uint64_t(uint64_t)>& rng,
const std::function<boost::optional<uint256>(size_t, size_t)>& rootOf,
const std::function<bool(const uint256&)>& isChainAnchor,
const uint256& preferredAnchor);
// The fee of a consolidation tx spending amount: the fee, or none when the notes are worth no more than it.
CAmount SaplingConsolidationTxFee(CAmount amount, CAmount fee);
// What a consolidation operation is asked to do, fixed when it is enqueued.
struct SaplingConsolidationRequest {
bool manual = false; // z_consolidate rather than the -consolidation scheduler
CAmount fee = DEFAULT_CONSOLIDATION_FEE;
SaplingConsolidationPolicy policy;
std::vector<libzcash::SaplingPaymentAddress> addresses; // empty: every address the wallet can spend
};
// What a round did.
struct ConsolidationTally {
std::vector<std::string> txids;
int notesMerged = 0;
CAmount amountMerged = 0; // value of the notes spent
CAmount amountConsolidated = 0; // value of the notes created (amountMerged minus fees)
CAmount fees = 0;
int skippedNotes = 0; // left out for a missing or unusable witness
bool yielded = false; // stopped after a tx to let a queued async operation run
std::string error;
};
class AsyncRPCOperation_saplingconsolidation : public AsyncRPCOperation class AsyncRPCOperation_saplingconsolidation : public AsyncRPCOperation
{ {
public: public:
AsyncRPCOperation_saplingconsolidation(int targetHeight); AsyncRPCOperation_saplingconsolidation(int targetHeight, const SaplingConsolidationRequest& request);
virtual ~AsyncRPCOperation_saplingconsolidation(); virtual ~AsyncRPCOperation_saplingconsolidation();
// We don't want to be copied or moved around // We don't want to be copied or moved around
@@ -33,15 +125,18 @@ public:
virtual UniValue getStatus() const; virtual UniValue getStatus() const;
void lock_notes();
void unlock_notes(); void unlock_notes();
private: private:
int targetHeight_; int targetHeight_;
SaplingConsolidationRequest request_;
bool main_impl(); bool main_impl();
std::vector<SaplingNoteEntry> z_sapling_inputs_; std::vector<SaplingNoteEntry> z_sapling_inputs_; // the notes this round locked
ConsolidationTally tally_; // what the round did, for z_consolidationstatus
void setConsolidationResult(int numTxCreated, const CAmount& amountConsolidated, const std::vector<std::string>& consolidationTxIds); void setConsolidationResult(const ConsolidationTally& tally);
}; };
#endif // HUSH_WALLET_ASYNCRPCOPERATION_SAPLINGCONSOLIDATION_H
+1 -1
View File
@@ -591,7 +591,7 @@ bool CCryptoKeyStore::GetSaplingSpendingKey(const libzcash::SaplingFullViewingKe
if (!IsCrypted()) if (!IsCrypted())
return CBasicKeyStore::GetSaplingSpendingKey(fvk, skOut); return CBasicKeyStore::GetSaplingSpendingKey(fvk, skOut);
for (auto entry : mapCryptedSaplingSpendingKeys) { for (const auto& entry : mapCryptedSaplingSpendingKeys) {
if (entry.first.fvk == fvk) { if (entry.first.fvk == fvk) {
const std::vector<unsigned char> &vchCryptedSecret = entry.second; const std::vector<unsigned char> &vchCryptedSecret = entry.second;
return DecryptSaplingSpendingKey(vMasterKey, vchCryptedSecret, entry.first, skOut); return DecryptSaplingSpendingKey(vMasterKey, vchCryptedSecret, entry.first, skOut);
+1 -1
View File
@@ -265,7 +265,7 @@ public:
LOCK(cs_SpendingKeyStore); LOCK(cs_SpendingKeyStore);
if (!IsCrypted()) if (!IsCrypted())
return CBasicKeyStore::HaveSaplingSpendingKey(fvk); return CBasicKeyStore::HaveSaplingSpendingKey(fvk);
for (auto entry : mapCryptedSaplingSpendingKeys) { for (const auto& entry : mapCryptedSaplingSpendingKeys) {
if (entry.first.fvk == fvk) { if (entry.first.fvk == fvk) {
return true; return true;
} }
+43 -9
View File
@@ -61,6 +61,7 @@ void CDBEnv::Reset()
dbenv = new DbEnv(DB_CXX_NO_EXCEPTIONS); dbenv = new DbEnv(DB_CXX_NO_EXCEPTIONS);
fDbEnvInit = false; fDbEnvInit = false;
fMockDb = false; fMockDb = false;
fKeepLogs = false;
} }
CDBEnv::CDBEnv() : dbenv(NULL) CDBEnv::CDBEnv() : dbenv(NULL)
@@ -276,10 +277,12 @@ bool CDBEnv::Salvage(const std::string& strFile, bool fAggressive, std::vector<C
void CDBEnv::CheckpointLSN(const std::string& strFile) void CDBEnv::CheckpointLSN(const std::string& strFile)
{ {
dbenv->txn_checkpoint(0, 0, 0); if (dbenv->txn_checkpoint(0, 0, 0) != 0)
fKeepLogs = true;
if (fMockDb) if (fMockDb)
return; return;
dbenv->lsn_reset(strFile.c_str(), 0); if (dbenv->lsn_reset(strFile.c_str(), 0) != 0)
fKeepLogs = true;
} }
@@ -480,6 +483,17 @@ bool CDB::Rewrite(const string& strFile, const char* pszSkip)
} }
bool CDBEnv::IsHealthy()
{
if (fKeepLogs)
return false;
if (!fDbEnvInit)
return true;
// get_flags itself fails with DB_RUNRECOVERY once the environment has panicked.
u_int32_t envFlags = 0;
return dbenv->get_flags(&envFlags) == 0 && !(envFlags & DB_PANIC_ENVIRONMENT);
}
void CDBEnv::Flush(bool fShutdown) void CDBEnv::Flush(bool fShutdown)
{ {
int64_t nStart = GetTimeMillis(); int64_t nStart = GetTimeMillis();
@@ -498,10 +512,16 @@ void CDBEnv::Flush(bool fShutdown)
// Move log data to the dat file // Move log data to the dat file
CloseDb(strFile); CloseDb(strFile);
LogPrint("db", "CDBEnv::Flush: %s checkpoint\n", strFile); LogPrint("db", "CDBEnv::Flush: %s checkpoint\n", strFile);
dbenv->txn_checkpoint(0, 0, 0); int ret = dbenv->txn_checkpoint(0, 0, 0);
if (ret != 0) {
LogPrintf("CDBEnv::Flush: %s checkpoint failed: %s\n", strFile, DbEnv::strerror(ret));
fKeepLogs = true;
}
LogPrint("db", "CDBEnv::Flush: %s detach\n", strFile); LogPrint("db", "CDBEnv::Flush: %s detach\n", strFile);
if (!fMockDb) if (!fMockDb && (ret = dbenv->lsn_reset(strFile.c_str(), 0)) != 0) {
dbenv->lsn_reset(strFile.c_str(), 0); LogPrintf("CDBEnv::Flush: %s lsn_reset failed: %s\n", strFile, DbEnv::strerror(ret));
fKeepLogs = true;
}
LogPrint("db", "CDBEnv::Flush: %s closed\n", strFile); LogPrint("db", "CDBEnv::Flush: %s closed\n", strFile);
mapFileUseCount.erase(mi++); mapFileUseCount.erase(mi++);
} else } else
@@ -511,10 +531,24 @@ void CDBEnv::Flush(bool fShutdown)
if (fShutdown) { if (fShutdown) {
char** listp; char** listp;
if (mapFileUseCount.empty()) { if (mapFileUseCount.empty()) {
dbenv->log_archive(&listp, DB_ARCH_REMOVE); // After a failed flush, or once the environment has panicked (BDB0060, e.g. after a page
Close(); // write failed), wallet.dat can be missing committed changes that only the logs hold.
if (!fMockDb) // Removing them would turn a wallet the next start recovers (DB_RECOVER) into one that
boost::filesystem::remove_all(boost::filesystem::path(strPath) / "database"); // silently lost them. If the logs are unusable, the next start moves database/ aside.
// (get_flags itself fails with DB_RUNRECOVERY once the environment has panicked.)
u_int32_t envFlags = 0;
if (dbenv->get_flags(&envFlags) != 0 || (envFlags & DB_PANIC_ENVIRONMENT))
fKeepLogs = true;
if (fKeepLogs && !fMockDb) {
LogPrintf("CDBEnv::Flush: the wallet database was not flushed cleanly; keeping %s for recovery at the next start\n",
(boost::filesystem::path(strPath) / "database").string());
Close();
} else {
dbenv->log_archive(&listp, DB_ARCH_REMOVE);
Close();
if (!fMockDb)
boost::filesystem::remove_all(boost::filesystem::path(strPath) / "database");
}
} }
} }
} }
+7
View File
@@ -28,6 +28,7 @@
#include "sync.h" #include "sync.h"
#include "version.h" #include "version.h"
#include <atomic>
#include <map> #include <map>
#include <string> #include <string>
#include <vector> #include <vector>
@@ -53,6 +54,9 @@ class CDBEnv
private: private:
bool fDbEnvInit; bool fDbEnvInit;
bool fMockDb; bool fMockDb;
// A checkpoint or lsn_reset failed: the logs in database/ may hold the only copy of committed
// wallet changes, so the shutdown flush must leave them for DB_RECOVER at the next start.
std::atomic<bool> fKeepLogs;
// Don't change into boost::filesystem::path, as that can result in // Don't change into boost::filesystem::path, as that can result in
// shutdown problems/crashes caused by a static initialized internal pointer. // shutdown problems/crashes caused by a static initialized internal pointer.
std::string strPath; std::string strPath;
@@ -96,6 +100,9 @@ public:
bool Open(const boost::filesystem::path& path); bool Open(const boost::filesystem::path& path);
void Close(); void Close();
void Flush(bool fShutdown); void Flush(bool fShutdown);
//! False once a checkpoint or lsn_reset has failed or the environment has panicked (BDB0060): a
//! large write into it then fails or deepens the damage, and the logs are what recovery needs.
bool IsHealthy();
void CheckpointLSN(const std::string& strFile); void CheckpointLSN(const std::string& strFile);
void CloseDb(const std::string& strFile); void CloseDb(const std::string& strFile);
+11 -4
View File
@@ -746,10 +746,17 @@ UniValue dumpwallet_impl(const UniValue& params, bool fHelp, bool fDumpZKeys)
HDSeed hdSeed; HDSeed hdSeed;
// Dump the 64-byte derivation seed (for mnemonic wallets this is the // Dump the 64-byte derivation seed (for mnemonic wallets this is the
// expanded BIP39 seed), so re-importing the hex reproduces the same keys. // expanded BIP39 seed), so re-importing the hex reproduces the same keys.
pwalletMain->GetHDSeedForDerivation(hdSeed); // The return MUST be checked: on failure hdSeed is default-constructed, and emitting it
auto rawSeed = hdSeed.RawSeed(); // anyway writes a blank seed next to a legitimate-looking BLAKE2b-of-empty fingerprint --
file << strprintf("# HDSeed=%s fingerprint=%s", HexStr(rawSeed.begin(), rawSeed.end()), hdSeed.Fingerprint().GetHex()); // a backup that looks valid and restores nothing. The per-key dump below is still a
file << "\n"; // complete backup without this line.
if (pwalletMain->GetHDSeedForDerivation(hdSeed)) {
auto rawSeed = hdSeed.RawSeed();
file << strprintf("# HDSeed=%s fingerprint=%s", HexStr(rawSeed.begin(), rawSeed.end()), hdSeed.Fingerprint().GetHex());
file << "\n";
} else {
file << "# HDSeed unavailable (wallet locked, no HD seed, or hdchain unproven)\n";
}
} }
file << "\n"; file << "\n";
for (std::vector<std::pair<int64_t, CKeyID> >::const_iterator it = vKeyBirth.begin(); it != vKeyBirth.end(); it++) { for (std::vector<std::pair<int64_t, CKeyID> >::const_iterator it = vKeyBirth.begin(); it != vKeyBirth.end(); it++) {
+165 -60
View File
@@ -16,6 +16,109 @@ using namespace libzcash;
bool EnsureWalletIsAvailable(bool avoidException); bool EnsureWalletIsAvailable(bool avoidException);
SaplingHistoryKeys GetSaplingHistoryKeys()
{
AssertLockHeld(pwalletMain->cs_wallet);
SaplingHistoryKeys keys;
std::set<libzcash::SaplingPaymentAddress> addresses;
pwalletMain->GetSaplingPaymentAddresses(addresses);
for (const auto& addr : addresses) {
libzcash::SaplingExtendedSpendingKey extsk;
if (pwalletMain->GetSaplingExtendedSpendingKey(addr, extsk)) {
const libzcash::SaplingFullViewingKey fvk = extsk.expsk.full_viewing_key();
SaplingHistoryKeys::SpendableAddress a;
a.addr = addr;
a.ivk = fvk.in_viewing_key();
a.ovk = fvk.ovk;
// Left zero when the wallet doesn't know addr, exactly as GetNullifiersForAddresses does.
pwalletMain->GetSaplingIncomingViewingKey(addr, a.walletIvk);
keys.spendable.push_back(a);
}
}
return keys;
}
bool SaplingHistoryKeys::IsNullifierOfAddress(const libzcash::SaplingIncomingViewingKey& addrIvk, const uint256& nullifier) const
{
AssertLockHeld(pwalletMain->cs_wallet);
if (!noteNullifiers) {
noteNullifiers = std::set<std::pair<libzcash::SaplingIncomingViewingKey, uint256>>();
for (const auto& p : pwalletMain->mapWallet) {
for (const auto& item : p.second.mapSaplingNoteData) {
if (item.second.nullifier)
noteNullifiers->insert(std::make_pair(item.second.ivk, *item.second.nullifier));
}
}
}
return noteNullifiers->count(std::make_pair(addrIvk, nullifier)) > 0;
}
namespace {
// One output's decryptions under incoming viewing keys, each key tried at most once. Two distinct ivks can't
// both decrypt an output: the cm check recomputes pk_d = [ivk]g_d, and ivks are canonical scalars below the
// order of g_d (ka_agree and ivk_to_pkd reject the rest), so a second one would need a NoteCommit collision.
// So once it is known which ivk decrypts the output (the wallet's note data records the one FindMySaplingNotes
// found, with its plaintext normally cached), no other ivk is tried.
class OutputDecryptions {
const OutputDescription& output;
const SaplingNoteData* nd;
std::map<libzcash::SaplingIncomingViewingKey, boost::optional<SaplingNoteCache>> tried;
boost::optional<SaplingNoteCache> Decrypt(const libzcash::SaplingIncomingViewingKey& ivk) const {
auto both = libzcash::SaplingNotePlaintext::decrypt_with_note(output.encCiphertext, ivk, output.ephemeralKey, output.cm);
if (!both)
return boost::none;
return SaplingNoteCache{ both->second, both->first.memo() };
}
// The plaintext under the ivk the wallet recorded for this output, decrypting it if it isn't cached.
const boost::optional<SaplingNoteCache>& Recorded() {
auto it = tried.find(nd->ivk);
if (it == tried.end())
it = tried.insert(std::make_pair(nd->ivk, nd->cachedPlaintext ? nd->cachedPlaintext : Decrypt(nd->ivk))).first;
return it->second;
}
public:
OutputDecryptions(const CWalletTx& wtx, uint32_t n) : output(wtx.vShieldedOutput[n]), nd(nullptr) {
auto it = wtx.mapSaplingNoteData.find(SaplingOutPoint(wtx.GetHash(), n));
if (it != wtx.mapSaplingNoteData.end())
nd = &it->second;
}
const SaplingNoteCache* Get(const libzcash::SaplingIncomingViewingKey& ivk) {
auto it = tried.find(ivk);
if (it == tried.end()) {
boost::optional<SaplingNoteCache> result;
if (nd && nd->ivk == ivk) {
result = Recorded();
} else if (!(nd && Recorded())) {
// Not a wallet note, or one whose recorded ivk doesn't decrypt it: try this key.
result = Decrypt(ivk);
}
it = tried.insert(std::make_pair(ivk, result)).first;
}
return it->second ? &*it->second : nullptr;
}
};
// What an outCiphertext tells the sender holding ovk: the note's plaintext and the address it was sent to.
boost::optional<std::pair<libzcash::SaplingNotePlaintext, libzcash::SaplingPaymentAddress>> DecryptSent(
const OutputDescription& outputDesc, const uint256& ovk)
{
auto opt = libzcash::SaplingOutgoingPlaintext::decrypt(
outputDesc.outCiphertext,ovk,outputDesc.cv,outputDesc.cm,outputDesc.ephemeralKey);
if (!opt)
return boost::none;
auto opt_unwrapped = opt.get();
auto pt = libzcash::SaplingNotePlaintext::decrypt(
outputDesc.encCiphertext,outputDesc.ephemeralKey,opt_unwrapped.esk,opt_unwrapped.pk_d,outputDesc.cm);
if (!pt)
return boost::none;
auto pt_unwrapped = pt.get();
return std::make_pair(pt_unwrapped, libzcash::SaplingPaymentAddress(pt_unwrapped.d, opt_unwrapped.pk_d));
}
}
void zsTxSpendsToJSON(const CWalletTx& wtx, UniValue& spends, CAmount& totalSpends, CAmount& filteredSpends, const std::string& strAddress, bool filterByAddress) { void zsTxSpendsToJSON(const CWalletTx& wtx, UniValue& spends, CAmount& totalSpends, CAmount& filteredSpends, const std::string& strAddress, bool filterByAddress) {
LOCK2(cs_main, pwalletMain->cs_wallet); LOCK2(cs_main, pwalletMain->cs_wallet);
@@ -87,18 +190,29 @@ void zsTxSpendsToJSON(const CWalletTx& wtx, UniValue& spends, CAmount& totalSpen
const SpendDescription& spendDesc = wtx.vShieldedSpend[i]; const SpendDescription& spendDesc = wtx.vShieldedSpend[i];
UniValue obj(UniValue::VOBJ); UniValue obj(UniValue::VOBJ);
SaplingOutPoint op = pwalletMain->mapSaplingNullifiersToNotes[spendDesc.nullifier]; // Lookups by find(), not operator[]: that inserted an entry for every other wallet's nullifier it met
// (and could insert an empty note into a wallet tx).
if (pwalletMain->IsSaplingNullifierFromMe(spendDesc.nullifier)) { if (pwalletMain->IsSaplingNullifierFromMe(spendDesc.nullifier)) {
const CWalletTx* parent = pwalletMain->GetWalletTx(pwalletMain->mapSaplingNullifiersToNotes[spendDesc.nullifier].hash); const SaplingOutPoint op = pwalletMain->mapSaplingNullifiersToNotes.at(spendDesc.nullifier);
const OutputDescription& output = parent->vShieldedOutput[op.n]; const CWalletTx* parent = pwalletMain->GetWalletTx(op.hash);
auto nd = pwalletMain->mapWallet[pwalletMain->mapSaplingNullifiersToNotes[spendDesc.nullifier].hash].mapSaplingNoteData[op]; auto ndIt = parent->mapSaplingNoteData.find(op);
auto pt = libzcash::SaplingNotePlaintext::decrypt(output.encCiphertext,nd.ivk,output.ephemeralKey,output.cm); // The spent note's plaintext, from the wallet's cache when it has it.
boost::optional<SaplingNoteCache> pt;
if (ndIt != parent->mapSaplingNoteData.end() && op.n < parent->vShieldedOutput.size()) {
const SaplingNoteData& nd = ndIt->second;
if (nd.cachedPlaintext) {
pt = nd.cachedPlaintext;
} else {
const OutputDescription& output = parent->vShieldedOutput[op.n];
auto both = libzcash::SaplingNotePlaintext::decrypt_with_note(output.encCiphertext,nd.ivk,output.ephemeralKey,output.cm);
if (both)
pt = SaplingNoteCache{ both->second, both->first.memo() };
}
}
if (pt) { if (pt) {
auto note = pt.get(); const libzcash::SaplingNote& note = pt->note;
auto pa = nd.ivk.address(note.d); const libzcash::SaplingPaymentAddress address(note.d, note.pk_d);
auto address = pa.get();
shieldedSpendsSpentCount++; shieldedSpendsSpentCount++;
totalSpends += CAmount(-note.value()); totalSpends += CAmount(-note.value());
obj.push_back(Pair("address",EncodePaymentAddress(address))); obj.push_back(Pair("address",EncodePaymentAddress(address)));
@@ -132,7 +246,7 @@ void zsTxSpendsToJSON(const CWalletTx& wtx, UniValue& spends, CAmount& totalSpen
} }
void zsTxReceivedToJSON(const CWalletTx& wtx, UniValue& received, CAmount& totalReceived, const std::string& strAddress, bool filterByAddress) { void zsTxReceivedToJSON(const CWalletTx& wtx, UniValue& received, CAmount& totalReceived, const std::string& strAddress, bool filterByAddress, const SaplingHistoryKeys& keys) {
if(fZdebug) if(fZdebug)
fprintf(stderr,"%s: txid=%s\n", __func__, wtx.GetHash().ToString().c_str() ); fprintf(stderr,"%s: txid=%s\n", __func__, wtx.GetHash().ToString().c_str() );
@@ -188,22 +302,18 @@ void zsTxReceivedToJSON(const CWalletTx& wtx, UniValue& received, CAmount& total
UniValue zsReceived(UniValue::VARR); UniValue zsReceived(UniValue::VARR);
if (isZsAddress || !filterByAddress) { if (isZsAddress || !filterByAddress) {
for (int i = 0; i < wtx.vShieldedOutput.size(); i++) { for (int i = 0; i < wtx.vShieldedOutput.size(); i++) {
const OutputDescription& outputDesc = wtx.vShieldedOutput[i];
UniValue obj(UniValue::VOBJ); UniValue obj(UniValue::VOBJ);
bool changeTx = false; bool changeTx = false;
//Decrypt sapling incoming commitments using IVK //Decrypt sapling incoming commitments using IVK: once per key, not once per address
std::set<libzcash::SaplingPaymentAddress> addresses; OutputDecryptions decryptions(wtx, i);
pwalletMain->GetSaplingPaymentAddresses(addresses); for (const SaplingHistoryKeys::SpendableAddress& a : keys.spendable) {
for (auto addr : addresses) { const libzcash::SaplingPaymentAddress& addr = a.addr;
libzcash::SaplingExtendedSpendingKey extsk; {
if (pwalletMain->GetSaplingExtendedSpendingKey(addr, extsk)) { const SaplingNoteCache* pt = decryptions.Get(a.ivk);
auto pt = libzcash::SaplingNotePlaintext::decrypt(
outputDesc.encCiphertext, extsk.expsk.full_viewing_key().in_viewing_key(), outputDesc.ephemeralKey, outputDesc.cm);
if (pt) { if (pt) {
auto note = pt.get(); const libzcash::SaplingNote& note = pt->note;
auto pt_unwrapped = pt.get(); auto memo = pt->memo;
auto memo = pt_unwrapped.memo();
obj.push_back(Pair("address",EncodePaymentAddress(addr))); obj.push_back(Pair("address",EncodePaymentAddress(addr)));
obj.push_back(Pair("amount", ValueFromAmount(CAmount(note.value())))); obj.push_back(Pair("amount", ValueFromAmount(CAmount(note.value()))));
obj.push_back(Pair("memo", HexStr(memo))); obj.push_back(Pair("memo", HexStr(memo)));
@@ -219,10 +329,8 @@ void zsTxReceivedToJSON(const CWalletTx& wtx, UniValue& received, CAmount& total
//Check Change Status //Check Change Status
if (wtx.vShieldedSpend.size()!=0) { if (wtx.vShieldedSpend.size()!=0) {
std::set<std::pair<PaymentAddress, uint256>> nullifierSet;
nullifierSet = pwalletMain->GetNullifiersForAddresses({addr});
BOOST_FOREACH(const SpendDescription& spendDesc, wtx.vShieldedSpend) { BOOST_FOREACH(const SpendDescription& spendDesc, wtx.vShieldedSpend) {
if (nullifierSet.count(std::make_pair(addr, spendDesc.nullifier))) { if (keys.IsNullifierOfAddress(a.walletIvk, spendDesc.nullifier)) {
changeTx = true; changeTx = true;
} }
} }
@@ -243,7 +351,7 @@ void zsTxReceivedToJSON(const CWalletTx& wtx, UniValue& received, CAmount& total
} }
void zsTxSendsToJSON(const CWalletTx& wtx, UniValue& sends, CAmount& totalSends, const std::string& strAddress, bool filterByAddress) { void zsTxSendsToJSON(const CWalletTx& wtx, UniValue& sends, CAmount& totalSends, const std::string& strAddress, bool filterByAddress, const SaplingHistoryKeys& keys) {
LOCK2(cs_main, pwalletMain->cs_wallet); LOCK2(cs_main, pwalletMain->cs_wallet);
@@ -296,6 +404,13 @@ void zsTxSendsToJSON(const CWalletTx& wtx, UniValue& sends, CAmount& totalSends,
//All Shielded Sends in the transaction //All Shielded Sends in the transaction
UniValue zsSends(UniValue::VARR); UniValue zsSends(UniValue::VARR);
if (isZsAddress || !filterByAddress) { if (isZsAddress || !filterByAddress) {
//The t to z shielding ovk comes from the HD seed: derive it once per tx, not once per output
boost::optional<uint256> seedOvk;
if (wtx.vShieldedSpend.size()==0 && wtx.vShieldedOutput.size()!=0) {
HDSeed seed;
if (pwalletMain->GetHDSeedForDerivation(seed))
seedOvk = ovkForShieldingFromTaddr(seed);
}
for (int i = 0; i < wtx.vShieldedOutput.size(); i++) { for (int i = 0; i < wtx.vShieldedOutput.size(); i++) {
const OutputDescription& outputDesc = wtx.vShieldedOutput[i]; const OutputDescription& outputDesc = wtx.vShieldedOutput[i];
shieldedOutputCount++; shieldedOutputCount++;
@@ -304,20 +419,14 @@ void zsTxSendsToJSON(const CWalletTx& wtx, UniValue& sends, CAmount& totalSends,
//Decrypt sapling outgoing t to z transaction using HDseed //Decrypt sapling outgoing t to z transaction using HDseed
if (wtx.vShieldedSpend.size()==0) { if (wtx.vShieldedSpend.size()==0) {
HDSeed seed; if (seedOvk) {
if (pwalletMain->GetHDSeedForDerivation(seed)) { {
auto opt = libzcash::SaplingOutgoingPlaintext::decrypt( auto sent = DecryptSent(outputDesc, *seedOvk);
outputDesc.outCiphertext,ovkForShieldingFromTaddr(seed),outputDesc.cv,outputDesc.cm,outputDesc.ephemeralKey);
if (opt) { if (sent) {
auto opt_unwrapped = opt.get();
auto pt = libzcash::SaplingNotePlaintext::decrypt(
outputDesc.encCiphertext,outputDesc.ephemeralKey,opt_unwrapped.esk,opt_unwrapped.pk_d,outputDesc.cm);
if (pt) {
shieldedOutputDecryptedCount++; shieldedOutputDecryptedCount++;
auto pt_unwrapped = pt.get(); const libzcash::SaplingNotePlaintext& pt_unwrapped = sent->first;
libzcash::SaplingPaymentAddress sentAddr(pt_unwrapped.d, opt_unwrapped.pk_d); const libzcash::SaplingPaymentAddress& sentAddr = sent->second;
obj.push_back(Pair("address",EncodePaymentAddress(sentAddr))); obj.push_back(Pair("address",EncodePaymentAddress(sentAddr)));
obj.push_back(Pair("amount", ValueFromAmount(CAmount(pt_unwrapped.value())))); obj.push_back(Pair("amount", ValueFromAmount(CAmount(pt_unwrapped.value()))));
obj.push_back(Pair("shieldedOutputIndex",i)); obj.push_back(Pair("shieldedOutputIndex",i));
@@ -330,26 +439,22 @@ void zsTxSendsToJSON(const CWalletTx& wtx, UniValue& sends, CAmount& totalSends,
} }
} }
//attempt Decryption of Outgoing Sapling using wallet extended spending keys //attempt Decryption of Outgoing Sapling using wallet extended spending keys: once per ovk, not once per address
} else { } else {
std::set<libzcash::SaplingPaymentAddress> addresses; std::map<uint256, boost::optional<std::pair<libzcash::SaplingNotePlaintext, libzcash::SaplingPaymentAddress>>> sentByOvk;
pwalletMain->GetSaplingPaymentAddresses(addresses); for (const SaplingHistoryKeys::SpendableAddress& a : keys.spendable) {
for (auto addr : addresses) { {
libzcash::SaplingExtendedSpendingKey extsk; auto tried = sentByOvk.find(a.ovk);
if (pwalletMain->GetSaplingExtendedSpendingKey(addr, extsk)) { if (tried == sentByOvk.end())
auto opt = libzcash::SaplingOutgoingPlaintext::decrypt( tried = sentByOvk.insert(std::make_pair(a.ovk, DecryptSent(outputDesc, a.ovk))).first;
outputDesc.outCiphertext,extsk.expsk.full_viewing_key().ovk,outputDesc.cv,outputDesc.cm,outputDesc.ephemeralKey); const auto& sent = tried->second;
if (opt) { {
auto opt_unwrapped = opt.get(); if (sent) {
auto pt = libzcash::SaplingNotePlaintext::decrypt( const libzcash::SaplingNotePlaintext& pt_unwrapped = sent->first;
outputDesc.encCiphertext,outputDesc.ephemeralKey,opt_unwrapped.esk,opt_unwrapped.pk_d,outputDesc.cm);
if (pt) {
auto pt_unwrapped = pt.get();
auto memo = pt_unwrapped.memo(); auto memo = pt_unwrapped.memo();
shieldedOutputDecryptedCount++; shieldedOutputDecryptedCount++;
libzcash::SaplingPaymentAddress sentAddr(pt_unwrapped.d, opt_unwrapped.pk_d); const libzcash::SaplingPaymentAddress& sentAddr = sent->second;
obj.push_back(Pair("address",EncodePaymentAddress(sentAddr))); obj.push_back(Pair("address",EncodePaymentAddress(sentAddr)));
obj.push_back(Pair("amount", ValueFromAmount(CAmount(-pt_unwrapped.value())))); obj.push_back(Pair("amount", ValueFromAmount(CAmount(-pt_unwrapped.value()))));
obj.push_back(Pair("memo", HexStr(memo))); obj.push_back(Pair("memo", HexStr(memo)));
@@ -365,10 +470,10 @@ void zsTxSendsToJSON(const CWalletTx& wtx, UniValue& sends, CAmount& totalSends,
//Check Change Status //Check Change Status
if (wtx.vShieldedSpend.size()!=0) { if (wtx.vShieldedSpend.size()!=0) {
std::set<std::pair<PaymentAddress, uint256>> nullifierSet; libzcash::SaplingIncomingViewingKey sentIvk;
nullifierSet = pwalletMain->GetNullifiersForAddresses({sentAddr}); pwalletMain->GetSaplingIncomingViewingKey(sentAddr, sentIvk);
BOOST_FOREACH(const SpendDescription& spendDesc, wtx.vShieldedSpend) { BOOST_FOREACH(const SpendDescription& spendDesc, wtx.vShieldedSpend) {
if (nullifierSet.count(std::make_pair(sentAddr, spendDesc.nullifier))) { if (keys.IsNullifierOfAddress(sentIvk, spendDesc.nullifier)) {
changeTx = true; changeTx = true;
} }
} }
@@ -397,7 +502,7 @@ void zsTxSendsToJSON(const CWalletTx& wtx, UniValue& sends, CAmount& totalSends,
} }
void zsWalletTxJSON(const CWalletTx& wtx, UniValue& ret, const std::string strAddress, bool fBool, const int returnType) { void zsWalletTxJSON(const CWalletTx& wtx, UniValue& ret, const std::string strAddress, bool fBool, const int returnType, const SaplingHistoryKeys& keys) {
LOCK2(cs_main, pwalletMain->cs_wallet); LOCK2(cs_main, pwalletMain->cs_wallet);
@@ -469,7 +574,7 @@ void zsWalletTxJSON(const CWalletTx& wtx, UniValue& ret, const std::string strAd
} }
// Get Received // Get Received
if (returnType == 0 || returnType == 2) { if (returnType == 0 || returnType == 2) {
zsTxReceivedToJSON(wtx, received, totalReceived, strAddress, fBool); zsTxReceivedToJSON(wtx, received, totalReceived, strAddress, fBool, keys);
if (!fBool || totalReceived != 0) { if (!fBool || totalReceived != 0) {
tx.push_back(Pair("received",received)); tx.push_back(Pair("received",received));
} }
@@ -479,7 +584,7 @@ void zsWalletTxJSON(const CWalletTx& wtx, UniValue& ret, const std::string strAd
if (returnType == 0 || returnType == 3) { if (returnType == 0 || returnType == 3) {
//Only include sends if there are spends that belong to the wallet. //Only include sends if there are spends that belong to the wallet.
if (totalSpends != 0 || fBool) { if (totalSpends != 0 || fBool) {
zsTxSendsToJSON(wtx, sends, totalSends, strAddress, fBool); zsTxSendsToJSON(wtx, sends, totalSends, strAddress, fBool, keys);
} }
if (!fBool || totalSends != 0) { if (!fBool || totalSends != 0) {
tx.push_back(Pair("sends",sends)); tx.push_back(Pair("sends",sends));
+28 -3
View File
@@ -13,10 +13,35 @@ struct balancestruct {
CAmount immature; CAmount immature;
}; };
/** The wallet's Sapling keys as the history helpers use them, gathered once per RPC call. The helpers used to
* look them up for every output and every address, re-deriving each full viewing key (an elliptic-curve
* operation), and walked every note in the wallet for each change check. Build it with pwalletMain->cs_wallet
* held, and keep holding it while the helpers run: that keeps the wallet's keys and notes fixed. The one thing
* it can't stop is the walletpassphrase timer relocking the wallet mid-call; the call then reports the keys as
* they were when it started, where the old per-output lookups switched over partway. */
struct SaplingHistoryKeys {
struct SpendableAddress {
libzcash::SaplingPaymentAddress addr;
libzcash::SaplingIncomingViewingKey ivk; //!< from its spending key: what received outputs are decrypted with
uint256 ovk; //!< from its spending key: what outCiphertexts are decrypted with
libzcash::SaplingIncomingViewingKey walletIvk; //!< GetSaplingIncomingViewingKey(addr), as the change check looked it up
};
//! Every wallet address whose spending key is available (never while the wallet is locked), in
//! GetSaplingPaymentAddresses order.
std::vector<SpendableAddress> spendable;
//! Whether GetNullifiersForAddresses({addr}) would contain (addr, nullifier), given addr's
//! GetSaplingIncomingViewingKey result (zero when the wallet doesn't know addr): nullifier belongs to a
//! wallet note received with that ivk. Walks the wallet's notes once, on first use.
bool IsNullifierOfAddress(const libzcash::SaplingIncomingViewingKey& addrIvk, const uint256& nullifier) const;
private:
mutable boost::optional<std::set<std::pair<libzcash::SaplingIncomingViewingKey, uint256>>> noteNullifiers;
};
SaplingHistoryKeys GetSaplingHistoryKeys();
void zsTxSpendsToJSON(const CWalletTx& wtx, UniValue& spends, CAmount& totalSpends, CAmount& filteredSpends, const std::string& strAddress, bool filterByAddress); void zsTxSpendsToJSON(const CWalletTx& wtx, UniValue& spends, CAmount& totalSpends, CAmount& filteredSpends, const std::string& strAddress, bool filterByAddress);
void zsTxReceivedToJSON(const CWalletTx& wtx, UniValue& received, CAmount& totalReceived, const std::string& strAddress, bool filterByAddress); void zsTxReceivedToJSON(const CWalletTx& wtx, UniValue& received, CAmount& totalReceived, const std::string& strAddress, bool filterByAddress, const SaplingHistoryKeys& keys);
void zsTxSendsToJSON(const CWalletTx& wtx, UniValue& sends, CAmount& totalSends, const std::string& strAddress, bool filterByAddress); void zsTxSendsToJSON(const CWalletTx& wtx, UniValue& sends, CAmount& totalSends, const std::string& strAddress, bool filterByAddress, const SaplingHistoryKeys& keys);
void zsWalletTxJSON(const CWalletTx& wtx, UniValue& ret, const std::string strAddress, bool fBool, const int returnType); void zsWalletTxJSON(const CWalletTx& wtx, UniValue& ret, const std::string strAddress, bool fBool, const int returnType, const SaplingHistoryKeys& keys);
#endif //HUSH_WALLET_RPCWALLET_H #endif //HUSH_WALLET_RPCWALLET_H
+279 -24
View File
@@ -42,6 +42,7 @@
#include "wallet/asyncrpcoperation_mergetoaddress.h" #include "wallet/asyncrpcoperation_mergetoaddress.h"
#include "wallet/asyncrpcoperation_sendmany.h" #include "wallet/asyncrpcoperation_sendmany.h"
#include "wallet/asyncrpcoperation_shieldcoinbase.h" #include "wallet/asyncrpcoperation_shieldcoinbase.h"
#include "wallet/asyncrpcoperation_saplingconsolidation.h"
#include "consensus/upgrades.h" #include "consensus/upgrades.h"
#include "sodium.h" #include "sodium.h"
#include <stdint.h> #include <stdint.h>
@@ -3032,11 +3033,13 @@ UniValue getalldata(const UniValue& params, bool fHelp,const CPubKey&)
} }
//Create Ordered List //Create Ordered List
map<int64_t,CWalletTx> orderedTxs; // Pointers into mapWallet, not copies (a CWalletTx copy deep-copies every note's witness list).
// As before, the first tx inserted for an nOrderPos wins.
map<int64_t,const CWalletTx*> orderedTxs;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) {
const uint256& wtxid = it->first; const uint256& wtxid = it->first;
const CWalletTx& wtx = (*it).second; const CWalletTx& wtx = (*it).second;
orderedTxs.insert(std::pair<int64_t,CWalletTx>(wtx.nOrderPos, wtx)); orderedTxs.insert(std::make_pair(wtx.nOrderPos, &wtx));
unsigned int txType = 0; unsigned int txType = 0;
// 0 Unassigend // 0 Unassigend
@@ -3228,10 +3231,11 @@ UniValue getalldata(const UniValue& params, bool fHelp,const CPubKey&)
} }
const SaplingHistoryKeys historyKeys = GetSaplingHistoryKeys();
uint64_t t = GetTime(); uint64_t t = GetTime();
for (map<int64_t,CWalletTx>::reverse_iterator it = orderedTxs.rbegin(); it != orderedTxs.rend(); ++it) for (map<int64_t,const CWalletTx*>::reverse_iterator it = orderedTxs.rbegin(); it != orderedTxs.rend(); ++it)
{ {
const CWalletTx& wtx = (*it).second; const CWalletTx& wtx = *(*it).second;
if (!CheckFinalTx(wtx)) if (!CheckFinalTx(wtx))
continue; continue;
@@ -3248,7 +3252,7 @@ UniValue getalldata(const UniValue& params, bool fHelp,const CPubKey&)
continue; continue;
} }
zsWalletTxJSON(wtx, trans, "*", false, 0); zsWalletTxJSON(wtx, trans, "*", false, 0, historyKeys);
if (trans.size() >= nCount) break; if (trans.size() >= nCount) break;
} }
@@ -3266,36 +3270,268 @@ UniValue getalldata(const UniValue& params, bool fHelp,const CPubKey&)
return returnObj; return returnObj;
} }
// Whether the wallet's periodic operations hold off because the node is catching up: the same test
// CWallet::ChainTip applies before it runs them. Caller holds cs_main.
static bool AutoWalletOpsSyncing()
{
return IsInitialBlockDownload() || chainActive.Tip() == NULL ||
chainActive.Tip()->GetBlockTime() <= GetTime() - 144*ASSETCHAINS_BLOCKTIME;
}
// Why no consolidation round can start right now, or "" if one can. Caller holds cs_main + cs_wallet.
static std::string ConsolidationDisabledReason()
{
if (!pwalletMain->fSaplingConsolidationEnabled)
return "disabled (-consolidation=0); z_consolidate runs a round on demand";
if (pwalletMain->IsLocked())
return "wallet is locked; rounds are skipped until it is unlocked";
if (AutoWalletOpsSyncing())
return "node is syncing; rounds start once it has caught up";
if (pwalletMain->fSweepRunning)
return "deferred while z_sweep is running; rounds resume when it finishes";
if (pwalletMain->fAutoShieldRunning)
return "deferred while autoshield is running; rounds resume when it finishes";
return "";
}
UniValue z_consolidationstatus(const UniValue& params, bool fHelp, const CPubKey& mypk) UniValue z_consolidationstatus(const UniValue& params, bool fHelp, const CPubKey& mypk)
{ {
if (!EnsureWalletIsAvailable(fHelp)) if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue; return NullUniValue;
if (fHelp || params.size() > 0) if (fHelp || params.size() > 1)
throw runtime_error( throw runtime_error(
"z_consolidationstatus\n" "z_consolidationstatus ( verbose )\n"
"\nGive details about consolidation operations since the node was started." "\nGive details about Sapling note consolidation: its settings, what it has done since the node was\n"
"started, and -- when no round can run -- why.\n"
"\nArguments:\n"
"1. verbose (boolean, optional, default=false) also count every address's eligible notes.\n"
" This walks the whole wallet.\n"
"\nResult:\n"
"{\n"
" \"consolidation\" : true|false, (boolean) whether periodic consolidation (-consolidation) is on\n"
" \"running\" : true|false, (boolean) whether a round is in flight\n"
" \"amount_consolidated\" : n, (numeric) value of the notes created since startup, in puposhis\n"
" \"next_consolidation\" : n, (numeric) height of the next periodic round\n"
" \"consolidationinterval\" : n, (numeric) blocks between periodic rounds\n"
" \"consolidationaddress\" : \"zaddr\", (string) the first -consolidatesaplingaddress; empty: all addresses\n"
" \"consolidationtxfee\" : n, (numeric) fee per transaction, in puposhis\n"
" \"consolidationthreshold\" : n, (numeric) addresses with more eligible notes than this are consolidated\n"
" \"consolidationbatchsize\" : n, (numeric) most notes one transaction spends\n"
" \"consolidationmaxtxs\" : n, (numeric) most transactions per address per round\n"
" \"consolidationaddresses\" : [...], (array) the addresses consolidated; empty: every address with a spending key\n"
" \"rounds\" : n, (numeric) rounds completed since startup\n"
" \"txs_created\" : n, (numeric) consolidation transactions since startup\n"
" \"notes_consolidated\" : n, (numeric) notes merged since startup\n"
" \"last_round\" : { (object, null before the first round)\n"
" \"height\" : n, \"time\" : n, (numeric) tip height and time when it finished\n"
" \"manual\" : true|false, (boolean) run by z_consolidate\n"
" \"txids\" : [...], (array) the transactions it sent\n"
" \"notes_merged\" : n, (numeric)\n"
" \"amount_merged\" : n, (numeric) value of the notes spent, in puposhis\n"
" \"amount_consolidated\" : n, (numeric) value of the notes created, in puposhis\n"
" \"fees\" : n, (numeric) in puposhis\n"
" \"skipped_notes\" : n, (numeric) notes left out for a missing or unusable witness\n"
" \"yielded\" : true|false, (boolean) it stopped after a transaction to let a queued operation\n"
" (z_sendmany, ...) run; the next round goes on\n"
" \"error\" : \"...\" (string) why it stopped early; empty if it did not\n"
" },\n"
" \"disabled_reason\" : \"...\", (string) why no periodic round can start now; empty if one can\n"
" \"addresses\" : [ (array, verbose only) every address with eligible notes\n"
" { \"address\" : \"zaddr\", \"eligible_notes\" : n, \"over_threshold\" : true|false, \"included\" : true|false }\n"
" ],\n"
" \"addresses_over_threshold\" : n, (numeric, verbose only) included addresses over the threshold\n"
" \"consolidation_suggested\" : true|false, (boolean, verbose only) -consolidation is off and some\n"
" address is over the threshold: consider -consolidation=1 or z_consolidate\n"
" \"consolidation_suggested_count\" : n (numeric, verbose only) addresses over the threshold while it is off\n"
"}\n" "}\n"
"\nExamples:\n" "\nExamples:\n"
+ HelpExampleCli("z_consolidationstatus", "") + HelpExampleCli("z_consolidationstatus", "")
+ HelpExampleCli("z_consolidationstatus", "true")
+ HelpExampleRpc("z_consolidationstatus", "") + HelpExampleRpc("z_consolidationstatus", "")
); );
bool fVerbose = params.size() > 0 && !params[0].isNull() && params[0].get_bool();
LOCK2(cs_main, pwalletMain->cs_wallet); LOCK2(cs_main, pwalletMain->cs_wallet);
const SaplingConsolidationStats& stats = pwalletMain->consolidationStats;
UniValue ret(UniValue::VOBJ); UniValue ret(UniValue::VOBJ);
ret.push_back(Pair("consolidation", pwalletMain->fSaplingConsolidationEnabled)); ret.push_back(Pair("consolidation", pwalletMain->fSaplingConsolidationEnabled));
ret.push_back(Pair("running", pwalletMain->fConsolidationRunning)); ret.push_back(Pair("running", pwalletMain->fConsolidationRunning));
ret.push_back(Pair("amount_consolidated", pwalletMain->amountConsolidated)); ret.push_back(Pair("amount_consolidated", (int64_t)stats.amountConsolidated));
ret.push_back(Pair("next_consolidation", pwalletMain->nextConsolidation)); ret.push_back(Pair("next_consolidation", pwalletMain->nextConsolidation));
ret.push_back(Pair("consolidationinterval", pwalletMain->consolidationInterval)); ret.push_back(Pair("consolidationinterval", pwalletMain->consolidationInterval));
ret.push_back(Pair("consolidationaddress", pwalletMain->consolidationAddress)); ret.push_back(Pair("consolidationaddress", pwalletMain->consolidationAddress));
ret.push_back(Pair("consolidationtxfee",(int)fConsolidationTxFee)); ret.push_back(Pair("consolidationtxfee",(int)fConsolidationTxFee));
ret.push_back(Pair("consolidationthreshold", pwalletMain->consolidationThreshold));
ret.push_back(Pair("consolidationbatchsize", pwalletMain->consolidationBatchSize));
ret.push_back(Pair("consolidationmaxtxs", pwalletMain->consolidationMaxTxs));
UniValue addrs(UniValue::VARR);
for (const libzcash::SaplingPaymentAddress& addr : pwalletMain->consolidationAddresses)
addrs.push_back(EncodePaymentAddress(addr));
ret.push_back(Pair("consolidationaddresses", addrs));
ret.push_back(Pair("rounds", stats.rounds));
ret.push_back(Pair("txs_created", stats.txsCreated));
ret.push_back(Pair("notes_consolidated", stats.notesConsolidated));
if (stats.hasLastRound) {
const SaplingConsolidationRound& r = stats.lastRound;
UniValue last(UniValue::VOBJ);
last.push_back(Pair("height", r.height));
last.push_back(Pair("time", r.time));
last.push_back(Pair("manual", r.manual));
UniValue txids(UniValue::VARR);
for (const std::string& txid : r.txids)
txids.push_back(txid);
last.push_back(Pair("txids", txids));
last.push_back(Pair("notes_merged", r.notesMerged));
last.push_back(Pair("amount_merged", (int64_t)r.amountMerged));
last.push_back(Pair("amount_consolidated", (int64_t)r.amountConsolidated));
last.push_back(Pair("fees", (int64_t)r.fees));
last.push_back(Pair("skipped_notes", r.skippedNotes));
last.push_back(Pair("yielded", r.yielded));
last.push_back(Pair("error", r.error));
ret.push_back(Pair("last_round", last));
} else {
ret.push_back(Pair("last_round", NullUniValue));
}
ret.push_back(Pair("disabled_reason", ConsolidationDisabledReason()));
if (fVerbose) {
std::set<libzcash::SaplingPaymentAddress> included(pwalletMain->consolidationAddresses.begin(),
pwalletMain->consolidationAddresses.end());
int over = 0;
UniValue list(UniValue::VARR);
for (const auto& p : pwalletMain->CountConsolidationEligibleNotes()) {
const bool isIncluded = included.empty() || included.count(p.first) > 0;
const bool isOver = p.second > pwalletMain->consolidationThreshold;
if (isIncluded && isOver)
over++;
UniValue entry(UniValue::VOBJ);
entry.push_back(Pair("address", EncodePaymentAddress(p.first)));
entry.push_back(Pair("eligible_notes", p.second));
entry.push_back(Pair("over_threshold", isOver));
entry.push_back(Pair("included", isIncluded));
list.push_back(entry);
}
ret.push_back(Pair("addresses", list));
ret.push_back(Pair("addresses_over_threshold", over));
pwalletMain->SetConsolidationSuggestion(over);
ret.push_back(Pair("consolidation_suggested", !pwalletMain->fSaplingConsolidationEnabled && over > 0));
ret.push_back(Pair("consolidation_suggested_count", pwalletMain->consolidationSuggestCount));
}
return ret; return ret;
} }
UniValue z_consolidate(const UniValue& params, bool fHelp, const CPubKey& mypk)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() > 4)
throw runtime_error(
"z_consolidate ( fee batchsize maxtxs [\"zaddr\",...] )\n"
"\nRun one Sapling consolidation round now, with the -consolidation settings, also when\n"
"-consolidation is off. Every address holding more than -consolidationthreshold eligible notes\n"
"(unspent, unlocked, at least 11 confirmations) gets up to maxtxs transactions, each spending up to\n"
"batchsize of its smallest notes back to that same address, plus 7 zero-value dummy outputs.\n"
"Pass null for an argument to keep its setting.\n"
"\nArguments:\n"
"1. fee (numeric, optional, default=-consolidationtxfee) fee per transaction in " + CURRENCY_UNIT + "\n"
"2. batchsize (numeric, optional, default=-consolidationbatchsize) most notes per transaction, "
+ strprintf("%d to %d", MIN_CONSOLIDATION_BATCHSIZE, MAX_CONSOLIDATION_BATCHSIZE) + "\n"
"3. maxtxs (numeric, optional, default=-consolidationmaxtxs) most transactions per address, "
+ strprintf("1 to %d", MAX_CONSOLIDATION_MAXTXS) + "\n"
"4. addresses (array, optional, default=-consolidatesaplingaddress or all) Sapling addresses to consolidate;\n"
" with -zsweep on, only the sweep address (also the default then)\n"
"\nResult:\n"
"\"operationid\" (string) An operationid to pass to z_getoperationstatus to get the result.\n"
"The fee here is in " + CURRENCY_UNIT + ", like z_sendmany's; -consolidationtxfee and the amounts in\n"
"z_consolidationstatus are in puposhis (1 " + CURRENCY_UNIT + " = 100000000).\n"
"\nExamples:\n"
+ HelpExampleCli("z_consolidate", "")
+ HelpExampleCli("z_consolidate", "null 50 20 '[\"zs1...\"]'")
+ HelpExampleRpc("z_consolidate", "")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
EnsureWalletIsUnlocked();
if (AutoWalletOpsSyncing())
throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Node is syncing; try again once it has caught up");
if (pwalletMain->fConsolidationRunning)
throw JSONRPCError(RPC_WALLET_ERROR, "A consolidation round is already running; see z_consolidationstatus");
if (pwalletMain->fSweepRunning || pwalletMain->fAutoShieldRunning)
throw JSONRPCError(RPC_WALLET_ERROR, strprintf("A %s round is running; try again when it finishes",
pwalletMain->fSweepRunning ? "z_sweep" : "autoshield"));
SaplingConsolidationRequest request;
request.manual = true;
request.fee = fConsolidationTxFee;
request.policy.threshold = pwalletMain->consolidationThreshold;
request.policy.batchSize = pwalletMain->consolidationBatchSize;
request.policy.maxTxs = pwalletMain->consolidationMaxTxs;
request.addresses = pwalletMain->consolidationAddresses;
if (params.size() > 0 && !params[0].isNull()) {
request.fee = AmountFromValue(params[0]);
if (request.fee < CONSOLIDATION_MIN_FEE || request.fee > CONSOLIDATION_MAX_FEE)
throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid fee: must be from %s to %s",
FormatMoney(CONSOLIDATION_MIN_FEE), FormatMoney(CONSOLIDATION_MAX_FEE)));
}
if (params.size() > 1 && !params[1].isNull()) {
request.policy.batchSize = params[1].get_int();
if (request.policy.batchSize < MIN_CONSOLIDATION_BATCHSIZE || request.policy.batchSize > MAX_CONSOLIDATION_BATCHSIZE)
throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid batchsize: must be from %d to %d",
MIN_CONSOLIDATION_BATCHSIZE, MAX_CONSOLIDATION_BATCHSIZE));
}
if (params.size() > 2 && !params[2].isNull()) {
request.policy.maxTxs = params[2].get_int();
if (request.policy.maxTxs < 1 || request.policy.maxTxs > MAX_CONSOLIDATION_MAXTXS)
throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid maxtxs: must be from 1 to %d", MAX_CONSOLIDATION_MAXTXS));
}
if (params.size() > 3 && !params[3].isNull()) {
UniValue addresses = params[3].get_array();
if (addresses.size() == 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid addresses: the array is empty");
request.addresses.clear();
for (size_t i = 0; i < addresses.size(); i++) {
const std::string& str = addresses[i].get_str();
auto zaddr = DecodePaymentAddress(str);
if (!IsValidPaymentAddress(zaddr) || boost::get<libzcash::SaplingPaymentAddress>(&zaddr) == nullptr)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid address, must be a Sapling z-address: " + str);
if (!boost::apply_visitor(HaveSpendingKeyForPaymentAddress(pwalletMain), zaddr))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Wallet does not hold the spending key of " + str);
// As at startup: with zsweep on, consolidating any other address only feeds the next sweep.
if (pwalletMain->fSweepEnabled && str != pwalletMain->sweepAddress)
throw JSONRPCError(RPC_INVALID_PARAMETER, "With -zsweep on, only the sweep address can be consolidated: " + str);
request.addresses.push_back(boost::get<libzcash::SaplingPaymentAddress>(zaddr));
}
}
// Take the scheduler's slot exactly as RunSaplingConsolidation does, so sweep and autoshield
// defer to this round and its completion releases the flag.
pwalletMain->fConsolidationRunning = true;
std::shared_ptr<AsyncRPCQueue> q = getAsyncRPCQueue();
std::shared_ptr<AsyncRPCOperation> lastOperation = q->getOperationForId(pwalletMain->saplingConsolidationOperationId);
if (lastOperation != nullptr) {
lastOperation->cancel();
if (!pwalletMain->saplingConsolidationOpManual)
q->popOperationForId(pwalletMain->saplingConsolidationOperationId);
}
std::shared_ptr<AsyncRPCOperation> operation(
new AsyncRPCOperation_saplingconsolidation(chainActive.Height() + AUTO_OP_TARGET_HEIGHT_OFFSET, request));
pwalletMain->saplingConsolidationOperationId = operation->getId();
pwalletMain->saplingConsolidationOpManual = true;
if (!q->addOperation(operation)) {
pwalletMain->fConsolidationRunning = false;
throw JSONRPCError(RPC_INTERNAL_ERROR, "The async queue is not accepting operations (shutting down?)");
}
return operation->getId();
}
UniValue z_sweepstatus(const UniValue& params, bool fHelp, const CPubKey& mypk) UniValue z_sweepstatus(const UniValue& params, bool fHelp, const CPubKey& mypk)
{ {
@@ -3355,7 +3591,9 @@ UniValue z_autoshieldstatus(const UniValue& params, bool fHelp, const CPubKey& m
" \"hdseedorigin\" : n, (numeric) 0 unrecorded, 1 created, 2 restored, 3 retrofit, 4 unknown\n" " \"hdseedorigin\" : n, (numeric) 0 unrecorded, 1 created, 2 restored, 3 retrofit, 4 unknown\n"
" \"hdseedorigin_desc\" : \"...\", (string) readable form of hdseedorigin\n" " \"hdseedorigin_desc\" : \"...\", (string) readable form of hdseedorigin\n"
" \"seed_recoverable\" : true|false, (boolean) whether a seed phrase can be exported\n" " \"seed_recoverable\" : true|false, (boolean) whether a seed phrase can be exported\n"
" \"disabled_reason\" : \"...\" (string) why auto-shielding is not running, if it is not\n" " \"disabled_reason\" : \"...\", (string) why auto-shielding is not running, if it is not\n"
" \"consolidation_suggested\" : true|false (boolean) -consolidation is off and some address holds more\n"
" than -consolidationthreshold spendable notes (see z_consolidationstatus)\n"
"}\n" "}\n"
"\nExamples:\n" "\nExamples:\n"
+ HelpExampleCli("z_autoshieldstatus", "") + HelpExampleCli("z_autoshieldstatus", "")
@@ -3407,6 +3645,16 @@ UniValue z_autoshieldstatus(const UniValue& params, bool fHelp, const CPubKey& m
} }
ret.push_back(Pair("disabled_reason", why)); ret.push_back(Pair("disabled_reason", why));
// Autoshield is what fills a miner's wallet with notes, one per round, so say here when consolidation
// would help. The count is refreshed at most once per consolidation interval: it walks the wallet.
if (!pwalletMain->fSaplingConsolidationEnabled &&
(pwalletMain->consolidationSuggestHeight < 0 ||
chainActive.Height() - pwalletMain->consolidationSuggestHeight >= pwalletMain->consolidationInterval)) {
pwalletMain->RefreshConsolidationSuggestion();
}
ret.push_back(Pair("consolidation_suggested",
!pwalletMain->fSaplingConsolidationEnabled && pwalletMain->consolidationSuggestCount > 0));
return ret; return ret;
} }
@@ -3515,17 +3763,20 @@ UniValue z_listreceivedaddress(const UniValue& params, bool fHelp,const CPubKey&
throw runtime_error("Filter must be greater that 0."); throw runtime_error("Filter must be greater that 0.");
//Created Ordered Transaction Map //Created Ordered Transaction Map
map<int64_t,CWalletTx> orderedTxs; // Pointers into mapWallet, not copies (a CWalletTx copy deep-copies every note's witness list).
// As before, the first tx inserted for an nOrderPos wins.
map<int64_t,const CWalletTx*> orderedTxs;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) {
const CWalletTx& wtx = (*it).second; const CWalletTx& wtx = (*it).second;
orderedTxs.insert(std::pair<int64_t,CWalletTx>(wtx.nOrderPos, wtx)); orderedTxs.insert(std::make_pair(wtx.nOrderPos, &wtx));
} }
const SaplingHistoryKeys historyKeys = GetSaplingHistoryKeys();
uint64_t t = GetTime(); uint64_t t = GetTime();
//Reverse Iterate thru transactions //Reverse Iterate thru transactions
for (map<int64_t,CWalletTx>::reverse_iterator it = orderedTxs.rbegin(); it != orderedTxs.rend(); ++it) { for (map<int64_t,const CWalletTx*>::reverse_iterator it = orderedTxs.rbegin(); it != orderedTxs.rend(); ++it) {
const CWalletTx& wtx = (*it).second; const CWalletTx& wtx = *(*it).second;
bool includeTransaction = true; bool includeTransaction = true;
//Excude transactions with less confirmations than required //Excude transactions with less confirmations than required
@@ -3546,7 +3797,7 @@ UniValue z_listreceivedaddress(const UniValue& params, bool fHelp,const CPubKey&
} }
if (includeTransaction) { if (includeTransaction) {
zsWalletTxJSON(wtx, ret, params[0].get_str() , true, 2); zsWalletTxJSON(wtx, ret, params[0].get_str() , true, 2, historyKeys);
} }
if (ret.size() > nCount) break; if (ret.size() > nCount) break;
@@ -3698,17 +3949,20 @@ UniValue z_listsentbyaddress(const UniValue& params, bool fHelp,const CPubKey&)
throw runtime_error("Filter must be greater that 0."); throw runtime_error("Filter must be greater that 0.");
//Created Ordered Transaction Map //Created Ordered Transaction Map
map<int64_t,CWalletTx> orderedTxs; // Pointers into mapWallet, not copies (a CWalletTx copy deep-copies every note's witness list).
// As before, the first tx inserted for an nOrderPos wins.
map<int64_t,const CWalletTx*> orderedTxs;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) {
const CWalletTx& wtx = (*it).second; const CWalletTx& wtx = (*it).second;
orderedTxs.insert(std::pair<int64_t,CWalletTx>(wtx.nOrderPos, wtx)); orderedTxs.insert(std::make_pair(wtx.nOrderPos, &wtx));
} }
const SaplingHistoryKeys historyKeys = GetSaplingHistoryKeys();
uint64_t t = GetTime(); uint64_t t = GetTime();
//Reverse Iterate thru transactions //Reverse Iterate thru transactions
for (map<int64_t,CWalletTx>::reverse_iterator it = orderedTxs.rbegin(); it != orderedTxs.rend(); ++it) { for (map<int64_t,const CWalletTx*>::reverse_iterator it = orderedTxs.rbegin(); it != orderedTxs.rend(); ++it) {
const CWalletTx& wtx = (*it).second; const CWalletTx& wtx = *(*it).second;
if (!CheckFinalTx(wtx)) if (!CheckFinalTx(wtx))
continue; continue;
@@ -3731,7 +3985,7 @@ UniValue z_listsentbyaddress(const UniValue& params, bool fHelp,const CPubKey&)
if (nFilterType == 2 && wtx.GetDepthInMainChain() > nFilter) if (nFilterType == 2 && wtx.GetDepthInMainChain() > nFilter)
continue; continue;
zsWalletTxJSON(wtx, ret, "*", false, 0); zsWalletTxJSON(wtx, ret, "*", false, 0, historyKeys);
if (ret.size() >= nCount) break; if (ret.size() >= nCount) break;
@@ -4309,7 +4563,7 @@ UniValue z_listunspent(const UniValue& params, bool fHelp, const CPubKey& mypk)
for (auto & entry : saplingEntries) { for (auto & entry : saplingEntries) {
UniValue obj(UniValue::VOBJ); UniValue obj(UniValue::VOBJ);
int nHeight = tx_height(entry.op.hash); int nHeight = HeightFromDepth(entry.confirmations);
int dpowconfs = hush_dpowconfs(nHeight, entry.confirmations); int dpowconfs = hush_dpowconfs(nHeight, entry.confirmations);
// Only return notarized results when minconf>1 // Only return notarized results when minconf>1
@@ -4642,7 +4896,7 @@ UniValue z_listreceivedbyaddress(const UniValue& params, bool fHelp, const CPubK
if (boost::get<libzcash::SaplingPaymentAddress>(&zaddr) != nullptr) { if (boost::get<libzcash::SaplingPaymentAddress>(&zaddr) != nullptr) {
for (SaplingNoteEntry & entry : saplingEntries) { for (SaplingNoteEntry & entry : saplingEntries) {
UniValue obj(UniValue::VOBJ); UniValue obj(UniValue::VOBJ);
int nHeight = tx_height(entry.op.hash); int nHeight = HeightFromDepth(entry.confirmations);
int dpowconfs = hush_dpowconfs(nHeight, entry.confirmations); int dpowconfs = hush_dpowconfs(nHeight, entry.confirmations);
// Only return notarized results when minconf>1 // Only return notarized results when minconf>1
if (nMinDepth > 1 && dpowconfs == 1) if (nMinDepth > 1 && dpowconfs == 1)
@@ -4662,7 +4916,7 @@ UniValue z_listreceivedbyaddress(const UniValue& params, bool fHelp, const CPubK
} }
obj.push_back(Pair("outindex", (int)entry.op.n)); obj.push_back(Pair("outindex", (int)entry.op.n));
obj.push_back(Pair("rawconfirmations", entry.confirmations)); obj.push_back(Pair("rawconfirmations", entry.confirmations));
auto wtx = pwalletMain->mapWallet.at(entry.op.hash); //.ToString()); const CWalletTx& wtx = pwalletMain->mapWallet.at(entry.op.hash);
obj.push_back(Pair("time", wtx.GetTxTime())); obj.push_back(Pair("time", wtx.GetTxTime()));
obj.push_back(Pair("confirmations", dpowconfs)); obj.push_back(Pair("confirmations", dpowconfs));
@@ -5376,7 +5630,7 @@ UniValue z_sendmany(const UniValue& params, bool fHelp, const CPubKey& mypk)
// sort notes from largest to smallest, which means // sort notes from largest to smallest, which means
// we will spend the largest first // we will spend the largest first
std::sort(saplingEntries.begin(), saplingEntries.end(), std::sort(saplingEntries.begin(), saplingEntries.end(),
[](SaplingNoteEntry i, SaplingNoteEntry j) -> bool { [](const SaplingNoteEntry& i, const SaplingNoteEntry& j) -> bool {
return i.note.value() > j.note.value(); return i.note.value() > j.note.value();
}); });
@@ -6446,6 +6700,7 @@ static const CRPCCommand commands[] =
{ "wallet", "z_sweepstatus", &z_sweepstatus, true }, { "wallet", "z_sweepstatus", &z_sweepstatus, true },
{ "wallet", "z_autoshieldstatus", &z_autoshieldstatus, true }, { "wallet", "z_autoshieldstatus", &z_autoshieldstatus, true },
{ "wallet", "z_consolidationstatus", &z_consolidationstatus, true }, { "wallet", "z_consolidationstatus", &z_consolidationstatus, true },
{ "wallet", "z_consolidate", &z_consolidate, false },
{ "wallet", "z_sendmany", &z_sendmany, false }, { "wallet", "z_sendmany", &z_sendmany, false },
{ "wallet", "z_shieldcoinbase", &z_shieldcoinbase, false }, { "wallet", "z_shieldcoinbase", &z_shieldcoinbase, false },
{ "wallet", "z_getoperationstatus", &z_getoperationstatus, true }, { "wallet", "z_getoperationstatus", &z_getoperationstatus, true },
+789 -129
View File
File diff suppressed because it is too large Load Diff
+230 -14
View File
@@ -62,6 +62,8 @@ extern bool bSpendZeroConfChange;
extern bool fSendFreeTransactions; extern bool fSendFreeTransactions;
extern bool fPayAtLeastCustomFee; extern bool fPayAtLeastCustomFee;
extern bool fTxDeleteEnabled; extern bool fTxDeleteEnabled;
//! -checknotecache: re-decrypt cached Sapling notes in GetFilteredNotes and repair any difference
extern bool fCheckNoteCache;
extern bool fTxConflictDeleteEnabled; extern bool fTxConflictDeleteEnabled;
extern int fDeleteInterval; extern int fDeleteInterval;
extern unsigned int fDeleteTransactionsAfterNBlocks; extern unsigned int fDeleteTransactionsAfterNBlocks;
@@ -110,6 +112,21 @@ static const int MIN_AUTOSHIELD_INTERVAL = 5;
static const int DEFAULT_AUTOSHIELD_MIN_UTXOS = 1; static const int DEFAULT_AUTOSHIELD_MIN_UTXOS = 1;
static const CAmount AUTOSHIELD_MIN_FEE = 1000; // comfortably above minRelayTxFee for a small tx static const CAmount AUTOSHIELD_MIN_FEE = 1000; // comfortably above minRelayTxFee for a small tx
static const CAmount AUTOSHIELD_MAX_FEE = 10000000; // 0.1 DRGX; no sane autoshield fee exceeds this static const CAmount AUTOSHIELD_MAX_FEE = 10000000; // 0.1 DRGX; no sane autoshield fee exceeds this
// Sapling consolidation (-consolidation / z_consolidate). An address is only consolidated once it holds
// MORE than the threshold of spendable notes; a round then sends up to maxtxs transactions per address,
// each spending up to batchsize of its smallest notes back to that same address.
static const int DEFAULT_CONSOLIDATION_INTERVAL = 25;
static const int MIN_CONSOLIDATION_INTERVAL = 5;
static const int DEFAULT_CONSOLIDATION_THRESHOLD = 25;
static const int MIN_CONSOLIDATION_THRESHOLD = 1;
static const int DEFAULT_CONSOLIDATION_BATCHSIZE = 15;
static const int MIN_CONSOLIDATION_BATCHSIZE = 2;
static const int MAX_CONSOLIDATION_BATCHSIZE = 50;
static const int DEFAULT_CONSOLIDATION_MAXTXS = 3;
static const int MAX_CONSOLIDATION_MAXTXS = 100;
static const CAmount CONSOLIDATION_MIN_FEE = AUTOSHIELD_MIN_FEE;
static const CAmount CONSOLIDATION_MAX_FEE = AUTOSHIELD_MAX_FEE;
static const int CONSOLIDATION_MIN_DEPTH = 11; // leaves room for an anchor at height N-10
static const int AUTO_OP_TARGET_HEIGHT_OFFSET = 5; // blocks of lookahead when scheduling an async op static const int AUTO_OP_TARGET_HEIGHT_OFFSET = 5; // blocks of lookahead when scheduling an async op
static const int AUTO_OP_EXPIRY_DELTA = 15; // NU-straddle expiry window, shared by all three ops static const int AUTO_OP_EXPIRY_DELTA = 15; // NU-straddle expiry window, shared by all three ops
@@ -301,6 +318,14 @@ class SproutNoteData
}; };
/** A Sapling note's decrypted plaintext as the wallet uses it: the note (value, rcm, and the address it
* was sent to as (d, pk_d)) and its memo. */
struct SaplingNoteCache
{
libzcash::SaplingNote note;
std::array<unsigned char, HUSH_MEMO_SIZE> memo;
};
class SaplingNoteData class SaplingNoteData
{ {
public: public:
@@ -328,6 +353,15 @@ public:
// read true and short-circuit the witness self-heal in VerifyAndSetInitialWitness. // read true and short-circuit the witness self-heal in VerifyAndSetInitialWitness.
bool witnessRootValidated = false; bool witnessRootValidated = false;
//In Memory Only
// The note's decrypted plaintext, so the balance and note-listing calls don't redo the Sapling
// decryption (several Jubjub scalar multiplications) for every note on every call. It is a pure
// function of (txid, output index, ivk), so nothing invalidates it. Never serialized, and left out
// of operator== and SaplingNoteDataIdentical on purpose: a filled and an unfilled entry persist the
// same state, so filling one must never make a tx look changed and get rewritten. Filled by
// FindMySaplingNotes when the note is found, otherwise by FillSaplingNoteCache.
boost::optional<SaplingNoteCache> cachedPlaintext;
ADD_SERIALIZE_METHODS; ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation> template <typename Stream, typename Operation>
@@ -366,6 +400,47 @@ struct SaplingNoteEntry
int confirmations; int confirmations;
}; };
/** What one Sapling consolidation round did (z_consolidationstatus "last_round"). */
struct SaplingConsolidationRound
{
int height = 0; //!< chain tip when the round finished
bool manual = false; //!< run by z_consolidate
int64_t time = 0;
std::vector<std::string> txids;
int notesMerged = 0;
CAmount amountMerged = 0; //!< value of the notes spent
CAmount amountConsolidated = 0; //!< value of the notes created
CAmount fees = 0;
int skippedNotes = 0; //!< left out for a missing or unusable witness
bool yielded = false; //!< stopped early to let a queued async operation run
std::string error; //!< why the round stopped early, if it did
};
/** Sapling consolidation totals since the node started. */
struct SaplingConsolidationStats
{
int rounds = 0;
int64_t txsCreated = 0;
int64_t notesConsolidated = 0;
CAmount amountConsolidated = 0;
bool hasLastRound = false;
SaplingConsolidationRound lastRound;
void Record(const SaplingConsolidationRound& round) {
rounds++;
txsCreated += round.txids.size();
notesConsolidated += round.notesMerged;
amountConsolidated += round.amountConsolidated;
lastRound = round;
hasLastRound = true;
}
};
/** Height of the active-chain block holding a wallet tx that is nDepth deep (as GetDepthInMainChain
* returns it, and SaplingNoteEntry::confirmations holds it), or 0 when the tx is unconfirmed or not
* in the active chain. Caller holds cs_main. */
int HeightFromDepth(int nDepth);
/** A transaction with a merkle branch linking it to the block chain. */ /** A transaction with a merkle branch linking it to the block chain. */
class CMerkleTx : public CTransaction class CMerkleTx : public CTransaction
{ {
@@ -816,6 +891,8 @@ public:
// Id of the in-flight consolidation op; read by the op to confirm it is // Id of the in-flight consolidation op; read by the op to confirm it is
// still the current one before mutating scheduler state. // still the current one before mutating scheduler state.
AsyncRPCOperationId saplingConsolidationOperationId; AsyncRPCOperationId saplingConsolidationOperationId;
// That op was started by z_consolidate: its result stays in the queue for z_getoperationresult.
bool saplingConsolidationOpManual = false;
bool fSaplingConsolidationEnabled = false; bool fSaplingConsolidationEnabled = false;
bool fConsolidationRunning = false; bool fConsolidationRunning = false;
@@ -833,6 +910,10 @@ public:
bool fAutoShieldRunning = false; bool fAutoShieldRunning = false;
std::atomic<bool> fAbortRescan{false}; std::atomic<bool> fAbortRescan{false};
//! True only when the last ScanForWalletTransactions ran to completion. An aborted or
//! shutdown-interrupted scan leaves this false, so callers must not record the wallet as
//! scanned up to the chain tip -- doing so makes the unscanned range permanently invisible.
bool fLastRescanCompleted = false;
// abort current rescan // abort current rescan
void AbortRescan() { fAbortRescan = true; } void AbortRescan() { fAbortRescan = true; }
// Are we currently aborting a rescan? // Are we currently aborting a rescan?
@@ -850,9 +931,20 @@ public:
// current one before mutating scheduler state. // current one before mutating scheduler state.
AsyncRPCOperationId saplingSweepOperationId; AsyncRPCOperationId saplingSweepOperationId;
int amountSwept = 0; int amountSwept = 0;
int amountConsolidated = 0; // What consolidation rounds have done since startup. Guarded by cs_wallet.
SaplingConsolidationStats consolidationStats;
// With -consolidation off: how many addresses are over the threshold (-1 until counted), at which
// height that was counted, and whether the "consider -consolidation" hint has been logged.
int consolidationSuggestCount = -1;
int consolidationSuggestHeight = -1;
bool fConsolidationSuggestLogged = false;
int sweepInterval = 10; int sweepInterval = 10;
int consolidationInterval = 25; int consolidationInterval = DEFAULT_CONSOLIDATION_INTERVAL;
int consolidationThreshold = DEFAULT_CONSOLIDATION_THRESHOLD;
int consolidationBatchSize = DEFAULT_CONSOLIDATION_BATCHSIZE;
int consolidationMaxTxs = DEFAULT_CONSOLIDATION_MAXTXS;
// -consolidatesaplingaddress (or the zsweep address); empty: every address the wallet can spend.
std::vector<libzcash::SaplingPaymentAddress> consolidationAddresses;
int sweepFee = 10000; int sweepFee = 10000;
int sweepMaxInputs = 200; int sweepMaxInputs = 200;
std::string sweepAddress = ""; std::string sweepAddress = "";
@@ -891,7 +983,7 @@ public:
protected: protected:
int SaplingWitnessMinimumHeight(const uint256& nullifier, int nWitnessHeight, int nMinimumHeight); int SaplingWitnessMinimumHeight(const boost::optional<uint256>& nullifier, int nWitnessHeight, int nMinimumHeight);
/** /**
* pindex is the new tip being connected. * pindex is the new tip being connected.
@@ -904,17 +996,22 @@ protected:
*/ */
void DecrementNoteWitnesses(const CBlockIndex* pindex); void DecrementNoteWitnesses(const CBlockIndex* pindex);
//! Returns true only if the atomic write actually committed. Callers that checkpoint during a
//! long scan need to know: a silently-failing checkpoint would otherwise be retried forever at
//! full cost while never making progress.
template <typename WalletDB> template <typename WalletDB>
void SetBestChainINTERNAL(WalletDB& walletdb, const CBlockLocator& loc) { bool SetBestChainINTERNAL(WalletDB& walletdb, const CBlockLocator& loc) {
if (!walletdb.TxnBegin()) { if (!walletdb.TxnBegin()) {
// This needs to be done atomically, so don't do it at all // This needs to be done atomically, so don't do it at all
LogPrintf("SetBestChain(): Couldn't start atomic write\n"); LogPrintf("SetBestChain(): Couldn't start atomic write\n");
return; return false;
} }
try { try {
LOCK(cs_wallet); LOCK(cs_wallet);
for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) { for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
auto wtx = wtxItem.second; // By reference: a copy here deep-copies every note's witness deque
// (WITNESS_CACHE_SIZE entries) for every transaction, on every call.
const CWalletTx& wtx = wtxItem.second;
// We skip transactions for which mapSaplingNoteData // We skip transactions for which mapSaplingNoteData
// is empty. This covers transactions that have no Sapling data // is empty. This covers transactions that have no Sapling data
// (i.e. are purely transparent), as well as shielding and unshielding // (i.e. are purely transparent), as well as shielding and unshielding
@@ -923,44 +1020,100 @@ protected:
if (!walletdb.WriteTx(wtxItem.first, wtx)) { if (!walletdb.WriteTx(wtxItem.first, wtx)) {
LogPrintf("SetBestChain(): Failed to write CWalletTx, aborting atomic write\n"); LogPrintf("SetBestChain(): Failed to write CWalletTx, aborting atomic write\n");
walletdb.TxnAbort(); walletdb.TxnAbort();
return; return false;
} }
} }
} }
if (!walletdb.WriteWitnessCacheSize(nWitnessCacheSize)) { if (!walletdb.WriteWitnessCacheSize(nWitnessCacheSize)) {
LogPrintf("SetBestChain(): Failed to write nWitnessCacheSize, aborting atomic write\n"); LogPrintf("SetBestChain(): Failed to write nWitnessCacheSize, aborting atomic write\n");
walletdb.TxnAbort(); walletdb.TxnAbort();
return; return false;
} }
if (!walletdb.WriteBestBlock(loc)) { if (!walletdb.WriteBestBlock(loc)) {
LogPrintf("SetBestChain(): Failed to write best block, aborting atomic write\n"); LogPrintf("SetBestChain(): Failed to write best block, aborting atomic write\n");
walletdb.TxnAbort(); walletdb.TxnAbort();
return; return false;
} }
} catch (const std::exception &exc) { } catch (const std::exception &exc) {
// Unexpected failure // Unexpected failure
LogPrintf("SetBestChain(): Unexpected error during atomic write:\n"); LogPrintf("SetBestChain(): Unexpected error during atomic write:\n");
LogPrintf("%s\n", exc.what()); LogPrintf("%s\n", exc.what());
walletdb.TxnAbort(); walletdb.TxnAbort();
return; return false;
} }
if (!walletdb.TxnCommit()) { if (!walletdb.TxnCommit()) {
// Couldn't commit all to db, but in-memory state is fine // Couldn't commit all to db, but in-memory state is fine
LogPrintf("SetBestChain(): Couldn't commit atomic write\n"); LogPrintf("SetBestChain(): Couldn't commit atomic write\n");
return; return false;
} }
return true;
}
//! SetBestChain on an open wallet database (a template so tests can pass a fake one).
template <typename WalletDB>
bool SetBestChainWith(WalletDB& walletdb, const CBlockLocator& loc) {
// FlushStateToDisk passes the chain tip, but ThreadNotifyWallets delivers blocks to the wallet
// asynchronously and can lag it. Stamping a locator ahead of what the wallet has processed makes
// the next start skip those blocks for good (no rescan, no notification): notes received in them
// go missing and spends in them go unseen. So stamp the block the wallet's state reflects (seeded
// by init before the notifier starts, then advanced by ChainTip). Init's own calls, made before
// it is seeded, pass the right locator themselves.
CBlockLocator locator = loc;
const CBlockIndex* pindexStamped = nullptr;
uint64_t nGeneration;
{
LOCK2(cs_main, cs_wallet);
// Read before the write: a change made while it runs bumps the counter past this value, so
// the shutdown save still sees it as unsaved.
nGeneration = nWitnessGeneration;
if (pindexWalletTip != nullptr) {
locator = chainActive.GetLocator(pindexWalletTip);
pindexStamped = pindexWalletTip;
} else if (!loc.vHave.empty()) {
BlockMap::const_iterator mi = mapBlockIndex.find(loc.vHave.front());
if (mi != mapBlockIndex.end())
pindexStamped = mi->second;
}
}
bool fWritten = SetBestChainINTERNAL(walletdb, locator);
if (fWritten)
RecordStatePersisted(pindexStamped, nGeneration);
return fWritten;
} }
private: private:
template <class T> template <class T>
void SyncMetaData(std::pair<typename TxSpendMap<T>::iterator, typename TxSpendMap<T>::iterator>); void SyncMetaData(std::pair<typename TxSpendMap<T>::iterator, typename TxSpendMap<T>::iterator>);
// Last block ThreadNotifyWallets delivered to ChainTip, i.e. the block the wallet's state
// reflects (guarded by cs_wallet). SetBestChain stamps this instead of the chain tip.
const CBlockIndex* pindexWalletTip = nullptr;
// Change tracking for the shutdown save (guarded by cs_wallet). nWitnessGeneration is bumped
// whenever the note state SetBestChain writes changes in memory: witnesses extended, popped,
// reseeded or cleared, or a note-bearing tx added or merged. A committed SetBestChain records
// the block it stamped and the counter it saw, so a shutdown can tell that nothing is left to
// write.
uint64_t nWitnessGeneration = 0;
const CBlockIndex* pindexPersistedTip = nullptr;
uint64_t nPersistedWitnessGeneration = 0;
// Where a rescan of this session that did not complete left the locator on disk (its checkpoint,
// or the older locator it could not advance), or -1 (guarded by cs_wallet). The next start resumes
// the scan from there, so a shutdown must not stamp the wallet tip over it.
int nInterruptedRescanHeight = -1;
void RecordStatePersisted(const CBlockIndex* pindex, uint64_t nGeneration);
protected: protected:
bool UpdatedNoteData(const CWalletTx& wtxIn, CWalletTx& wtx); bool UpdatedNoteData(const CWalletTx& wtxIn, CWalletTx& wtx, bool fSameBlock);
void MarkAffectedTransactionsDirty(const CTransaction& tx); void MarkAffectedTransactionsDirty(const CTransaction& tx);
/* the hd chain data model (chain counters) */ /* the hd chain data model (chain counters) */
CHDChain hdChain; CHDChain hdChain;
//! Set at load time when hdChain cannot be trusted to describe this wallet's HD seed -- the
//! record was missing, or its seedFp does not match the seed actually loaded. While true the
//! wallet is fully usable for existing keys but refuses to DERIVE new ones, because it cannot
//! tell which key tree it belongs to. Never serialized; recomputed on every load.
bool fHDChainUnproven = false;
public: public:
/* /*
@@ -1253,6 +1406,8 @@ public:
std::vector<SaplingOutPoint> notes, std::vector<SaplingOutPoint> notes,
std::vector<boost::optional<SaplingWitness>>& witnesses, std::vector<boost::optional<SaplingWitness>>& witnesses,
uint256 &final_anchor); uint256 &final_anchor);
//! The note's newest cached witness, whatever its root; none if the wallet has none for it.
boost::optional<SaplingWitness> GetSaplingNoteLatestWitness(const SaplingOutPoint& note) const;
isminetype IsMine(const CTxIn& txin) const; isminetype IsMine(const CTxIn& txin) const;
CAmount GetDebit(const CTxIn& txin, const isminefilter& filter) const; CAmount GetDebit(const CTxIn& txin, const isminefilter& filter) const;
@@ -1275,10 +1430,42 @@ public:
const CBlock *pblock, const CBlock *pblock,
boost::optional<std::pair<SproutMerkleTree, SaplingMerkleTree>> added); boost::optional<std::pair<SproutMerkleTree, SaplingMerkleTree>> added);
void RunSaplingConsolidation(int blockHeight); void RunSaplingConsolidation(int blockHeight);
/** Notes a consolidation round would count as eligible, per address. Walks the whole wallet
* under cs_main + cs_wallet, so it is only run on request. */
std::map<libzcash::SaplingPaymentAddress, int> CountConsolidationEligibleNotes();
/** With -consolidation off, counts the addresses over the threshold into consolidationSuggestCount
* and logs, once, that consolidation would help. Walks the wallet like the above. */
void RefreshConsolidationSuggestion();
/** Records a count of addresses over the threshold (from either walk) and logs the hint once. */
void SetConsolidationSuggestion(int overThreshold);
void RunAutoShieldCoinbase(int blockHeight); void RunAutoShieldCoinbase(int blockHeight);
bool CommitAutomatedTx(const CTransaction& tx); bool CommitAutomatedTx(const CTransaction& tx);
/** Saves witness caches and best block locator to disk. */ /** Saves witness caches and best block locator to disk in one atomic write, and reports whether
void SetBestChain(const CBlockLocator& loc); * it committed. Overrides CValidationInterface. */
bool SetBestChain(const CBlockLocator& loc);
/** Init found the locator on disk at pindex and is not rescanning: the wallet in memory is what
* was last saved, so a shutdown with no changes after this has nothing to write. */
void MarkStatePersisted(const CBlockIndex* pindex);
/** Why a clean shutdown must not write the wallet state now, or nullptr if it should. */
const char* ShutdownSaveSkipReason(bool fInitCompleted, bool fChainstateFlushed);
/** Called by Shutdown() under cs_main after the chainstate flush, with every other thread
* stopped: writes the witnesses and the best-block locator (SetBestChain), unless a gate in
* ShutdownSaveSkipReason says not to. Without it a session shorter than the hourly write never
* saves, and the next start rescans and re-extends every witness across the whole session. */
void PersistStateAtShutdown(bool fInitCompleted, bool fChainstateFlushed);
/** Rescan bookkeeping for the shutdown save. A scan reports its start with the height of the
* locator on disk (getting back the height an earlier interrupted scan left, or -1), where it
* stopped if cut short (the height it left the locator at), and its start once it reached the
* tip. Until a scan has covered everything above the locator on disk, a shutdown does not save. */
int NoteRescanStarted(int nPersistedHeight);
void NoteRescanInterrupted(int nResumeHeight);
void NoteRescanCompleted(int nStartHeight, int nInterruptedBefore);
// Seed the block the wallet's state reflects, before ThreadNotifyWallets starts delivering.
void SetWalletTip(const CBlockIndex* pindex);
/** As SetBestChain, but for use INSIDE a long scan: opens the wallet DB with fFlushOnClose=false
* so the call does not trigger a full BDB txn_checkpoint over the whole cache (see the comment
* at CWallet::SetBestChain), and reports whether the write actually committed. */
bool SetBestChainNoFlush(const CBlockLocator& loc);
std::set<std::pair<libzcash::PaymentAddress, uint256>> GetNullifiersForAddresses(const std::set<libzcash::PaymentAddress> & addresses); std::set<std::pair<libzcash::PaymentAddress, uint256>> GetNullifiersForAddresses(const std::set<libzcash::PaymentAddress> & addresses);
bool IsNoteSaplingChange(const std::set<std::pair<libzcash::PaymentAddress, uint256>> & nullifierSet, const libzcash::PaymentAddress & address, const SaplingOutPoint & entry); bool IsNoteSaplingChange(const std::set<std::pair<libzcash::PaymentAddress, uint256>> & nullifierSet, const libzcash::PaymentAddress & address, const SaplingOutPoint & entry);
@@ -1415,6 +1602,12 @@ public:
void SetHDChain(const CHDChain& chain, bool memonly); void SetHDChain(const CHDChain& chain, bool memonly);
const CHDChain& GetHDChain() const { return hdChain; } const CHDChain& GetHDChain() const { return hdChain; }
//! Mark hdChain as untrustworthy for derivation (see the member's declaration). Set only by
//! CWalletDB::LoadWallet; there is deliberately no way to clear it short of reloading, so a
//! degraded wallet cannot be talked back into deriving without a real repair.
void SetHDChainUnproven() { fHDChainUnproven = true; }
bool IsHDChainUnproven() const { return fHDChainUnproven; }
/* Record (in memory and in wallet.dat) how this wallet's HD seed came to /* Record (in memory and in wallet.dat) how this wallet's HD seed came to
exist. Best-effort: a failed write is logged, not fatal — the next start exist. Best-effort: a failed write is logged, not fatal — the next start
simply re-classifies, and re-classification always errs toward simply re-classifies, and re-classification always errs toward
@@ -1433,6 +1626,29 @@ public:
bool LoadCryptedMnemonicEntropy(const uint256& entropyFp, const std::vector<unsigned char>& vchCryptedSecret); bool LoadCryptedMnemonicEntropy(const uint256& entropyFp, const std::vector<unsigned char>& vchCryptedSecret);
/* Find notes filtered by payment address, min depth, ability to spend */ /* Find notes filtered by payment address, min depth, ability to spend */
/** A wallet note whose decrypted plaintext is not cached yet, with the output it decrypts. */
struct SaplingNoteToDecrypt {
SaplingNoteData* nd;
const OutputDescription* output;
};
/** Decrypts each note into nd->cachedPlaintext and returns how many it filled. A note that doesn't
* decrypt under its ivk is left unfilled. Caller holds cs_wallet. */
unsigned int FillSaplingNoteCache(const std::vector<SaplingNoteToDecrypt>& notes);
/** Notes FillSaplingNoteCache has decrypted since startup (FindMySaplingNotes' fills not counted), and
* the threads its last call used. Guarded by cs_wallet. */
uint64_t nSaplingNoteCacheFills = 0;
int nSaplingNoteCacheFillThreads = 0;
struct SaplingNoteCacheWarmup {
unsigned int notes = 0; //!< notes in the wallet
unsigned int filled = 0; //!< decrypted by this call
unsigned int noSuchOutput = 0; //!< naming an output their tx doesn't have
unsigned int undecryptable = 0; //!< not decrypting under their own ivk
};
/** Decrypts every wallet note whose plaintext isn't cached yet (all of them after wallet.dat is loaded).
* Never asserts: a note that can't be decrypted is counted, logged and left unfilled. Run at startup. */
SaplingNoteCacheWarmup WarmSaplingNoteCache();
void GetFilteredNotes(std::vector<SaplingNoteEntry>& saplingEntries, void GetFilteredNotes(std::vector<SaplingNoteEntry>& saplingEntries,
std::string address, std::string address,
int minDepth=1, int minDepth=1,
+69 -13
View File
@@ -421,6 +421,15 @@ public:
// True when that record had to be repaired on read (see the "hdchain" case // True when that record had to be repaired on read (see the "hdchain" case
// in ReadKeyValue); LoadWallet rewrites it in full form afterwards. // in ReadKeyValue); LoadWallet rewrites it in full form afterwards.
bool fHDChainRepaired; bool fHDChainRepaired;
// True once an "hdchain" record was ENCOUNTERED, whether or not it parsed. This is what
// separates the two failure shapes: a v1.0.3-or-earlier -salvagewallet drops the record
// entirely (its IsKeyType has no "hdchain" case), so absent == salvaged and recoverable,
// while present-but-unreadable means wider file damage.
bool fHDChainSeen;
// Fingerprint taken from the KEY of the hdseed/chdseed record. Available even for an
// encrypted wallet, where the seed itself cannot be read at load time.
bool fHDSeedSeen;
uint256 hdSeedFpSeen;
CWalletScanState() { CWalletScanState() {
nKeys = nCKeys = nKeyMeta = nZKeys = nCZKeys = nZKeyMeta = nSapZAddrs = 0; nKeys = nCKeys = nKeyMeta = nZKeys = nCZKeys = nZKeyMeta = nSapZAddrs = 0;
@@ -429,6 +438,8 @@ public:
nFileVersion = 0; nFileVersion = 0;
fHDChainRead = false; fHDChainRead = false;
fHDChainRepaired = false; fHDChainRepaired = false;
fHDChainSeen = false;
fHDSeedSeen = false;
} }
}; };
@@ -836,6 +847,8 @@ ReadKeyValue(CWallet* pwallet, CDataStream& ssKey, CDataStream& ssValue,
strErr = "Error reading wallet database: LoadHDSeed failed"; strErr = "Error reading wallet database: LoadHDSeed failed";
return false; return false;
} }
wss.fHDSeedSeen = true;
wss.hdSeedFpSeen = seedFp;
} }
else if (strType == "chdseed") else if (strType == "chdseed")
{ {
@@ -849,9 +862,15 @@ ReadKeyValue(CWallet* pwallet, CDataStream& ssKey, CDataStream& ssValue,
return false; return false;
} }
wss.fIsEncrypted = true; wss.fIsEncrypted = true;
// The fingerprint is the plaintext KEY of the chdseed record, so this works while
// the wallet is locked and the seed itself is unreadable.
wss.fHDSeedSeen = true;
wss.hdSeedFpSeen = seedFp;
} }
else if (strType == "hdchain") else if (strType == "hdchain")
{ {
// Record the ENCOUNTER before any parsing can fail.
wss.fHDChainSeen = true;
CHDChain chain; CHDChain chain;
// Keep an untouched copy: a failed >> has already consumed part of ssValue. // Keep an untouched copy: a failed >> has already consumed part of ssValue.
CDataStream ssRetry(ssValue.begin(), ssValue.end(), ssValue.GetType(), ssValue.GetVersion()); CDataStream ssRetry(ssValue.begin(), ssValue.end(), ssValue.GetType(), ssValue.GetVersion());
@@ -1046,23 +1065,60 @@ DBErrors CWalletDB::LoadWallet(CWallet* pwallet)
} }
} }
// A wallet that holds an HD seed but whose hdchain record is missing or // A wallet that holds an HD seed but no usable hdchain record cannot safely DERIVE: hdChain
// unreadable is NOT safe to run. hdChain would fall back to its SetNull // falls back to its SetNull defaults, clearing fMnemonicSeed and so switching derivation from
// defaults (walletdb.h:105-113), which (a) clears fMnemonicSeed, switching // the 64-byte BIP39 seed to the raw 32-byte entropy -- an entirely different key tree.
// HD derivation from the 64-byte BIP39 seed to the raw 32-byte entropy //
// (CWallet::GetHDSeedForDerivation, wallet.cpp:2615-2633) -> an entirely // saplingAccountCounter was previously listed here as a second hazard. It is not one:
// different key tree, and (b) resets saplingAccountCounter to 0, so the // GenerateNewSaplingZKey loops `do {...} while (HaveSaplingSpendingKey(...))` and
// next GenerateNewSaplingZKey walks back over accounts that already exist. // DeriveNewChildKey loops `while (HaveKey(...))`, so a counter that starts low walks forward
// Both are silent today (a bad hdchain read is only DB_NONCRITICAL_ERROR). // past accounts that already exist rather than colliding with them.
// Fail loud instead of quietly deriving into the wrong tree. //
if (pwallet->HaveHDSeed() && !wss.fHDChainRead) // Two shapes reach here and only one is real corruption:
// (a) the record is ABSENT -- the signature of a -salvagewallet run by v1.0.3 or earlier,
// whose IsKeyType has no "hdchain" case, so salvage dropped it. The keys are intact.
// Refusing strands the wallet with no way back: the node aborts before the RPC server
// exists, and -mnemonic refuses a non-empty wallet, so there is no user-executable
// recovery path at all.
// (b) the record is PRESENT but unreadable -- wider file damage. Keep refusing.
if (pwallet->HaveHDSeed() && !wss.fHDChainRead && wss.fHDChainSeen)
{ {
LogPrintf("Error loading wallet.dat: HD seed present but the hdchain record is missing or corrupt. " LogPrintf("Error loading wallet.dat: the hdchain record is present but unreadable. Your keys "
"Recover by restoring from the seed phrase: move wallet.dat aside and start with " "are intact -- do NOT delete or replace wallet.dat. Back it up and see debug.log.\n");
"-mnemonic=\"<your seed phrase>\" -rescan\n");
return DB_CORRUPT; return DB_CORRUPT;
} }
{
const char* pszDegraded = NULL;
if (pwallet->HaveHDSeed() && !wss.fHDChainRead)
{
pszDegraded = "the hdchain record is missing (an older -salvagewallet drops it)";
}
// A chain WAS read, but it does not belong to the seed we loaded. No legitimate writer can
// produce that -- InstallHDSeed always stores seedFp = seed.Fingerprint(). It is the mark
// of a wallet that lost its hdchain to an old salvage and was then USED on that old build,
// which persists a SetNull-derived chain carrying a null seedFp. Such a wallet otherwise
// starts up perfectly clean and derives into the WRONG TREE forever, silently -- strictly
// worse than failing to open, which is why it is worth detecting here.
else if (pwallet->HaveHDSeed() && wss.fHDSeedSeen &&
pwallet->GetHDChain().seedFp != wss.hdSeedFpSeen)
{
pszDegraded = "the hdchain record does not belong to this wallet's HD seed";
}
if (pszDegraded != NULL)
{
pwallet->SetHDChainUnproven();
LogPrintf("Wallet opened in DEGRADED mode: %s. Existing keys are intact, spendable and "
"receivable, but no NEW HD-derived key can be generated and new transparent "
"addresses will not be recoverable from a seed phrase. Back up wallet.dat now "
"and do NOT delete or replace it.\n", pszDegraded);
// An old salvage also dropped defaultkey and bestblock, which would make this look like
// a first run and skip the rescan, leaving a permanently zero balance.
SoftSetBoolArg("-rescan", true);
}
}
// Any wallet corruption at all: skip any rewriting or // Any wallet corruption at all: skip any rewriting or
// upgrading, we don't want to make it worse. // upgrading, we don't want to make it worse.
if (result != DB_LOAD_OK) if (result != DB_LOAD_OK)
+37 -3
View File
@@ -115,11 +115,16 @@ boost::optional<SaplingOutgoingPlaintext> SaplingOutgoingPlaintext::decrypt(
} }
} }
boost::optional<SaplingNotePlaintext> SaplingNotePlaintext::decrypt( namespace {
// SaplingNotePlaintext::decrypt with an incoming viewing key, also handing back the pk_d = [ivk]g_d
// it derives to check cmu.
boost::optional<SaplingNotePlaintext> DecryptWithIvk(
const SaplingEncCiphertext &ciphertext, const SaplingEncCiphertext &ciphertext,
const uint256 &ivk, const uint256 &ivk,
const uint256 &epk, const uint256 &epk,
const uint256 &cmu const uint256 &cmu,
uint256 &pk_d
) )
{ {
auto pt = AttemptSaplingEncDecryption(ciphertext, ivk, epk); auto pt = AttemptSaplingEncDecryption(ciphertext, ivk, epk);
@@ -140,7 +145,6 @@ boost::optional<SaplingNotePlaintext> SaplingNotePlaintext::decrypt(
return boost::none; return boost::none;
} }
uint256 pk_d;
if (!librustzcash_ivk_to_pkd(ivk.begin(), ret.d.data(), pk_d.begin())) { if (!librustzcash_ivk_to_pkd(ivk.begin(), ret.d.data(), pk_d.begin())) {
return boost::none; return boost::none;
} }
@@ -164,6 +168,36 @@ boost::optional<SaplingNotePlaintext> SaplingNotePlaintext::decrypt(
return ret; return ret;
} }
}
boost::optional<SaplingNotePlaintext> SaplingNotePlaintext::decrypt(
const SaplingEncCiphertext &ciphertext,
const uint256 &ivk,
const uint256 &epk,
const uint256 &cmu
)
{
uint256 pk_d;
return DecryptWithIvk(ciphertext, ivk, epk, cmu, pk_d);
}
boost::optional<std::pair<SaplingNotePlaintext, SaplingNote>> SaplingNotePlaintext::decrypt_with_note(
const SaplingEncCiphertext &ciphertext,
const uint256 &ivk,
const uint256 &epk,
const uint256 &cmu
)
{
uint256 pk_d;
auto pt = DecryptWithIvk(ciphertext, ivk, epk, cmu, pk_d);
if (!pt) {
return boost::none;
}
// ivk_to_pkd succeeding implies d is a valid diversifier, which is all note(ivk) checks on top.
SaplingNote note(pt->d, pk_d, pt->value(), pt->rcm);
return std::make_pair(*pt, note);
}
boost::optional<SaplingNotePlaintext> SaplingNotePlaintext::decrypt( boost::optional<SaplingNotePlaintext> SaplingNotePlaintext::decrypt(
const SaplingEncCiphertext &ciphertext, const SaplingEncCiphertext &ciphertext,
const uint256 &epk, const uint256 &epk,
+11
View File
@@ -85,6 +85,17 @@ public:
const uint256 &cmu const uint256 &cmu
); );
// decrypt(ciphertext, ivk, epk, cmu) that also returns the note. Building the note needs
// pk_d = [ivk]g_d, which the decryption derives anyway to check cmu; note(ivk) would derive it
// again (another Jubjub scalar multiplication). A distinct name rather than an overload, so it
// can never capture a call meant for the (epk, esk, pk_d, cmu) one.
static boost::optional<std::pair<SaplingNotePlaintext, SaplingNote>> decrypt_with_note(
const SaplingEncCiphertext &ciphertext,
const uint256 &ivk,
const uint256 &epk,
const uint256 &cmu
);
boost::optional<SaplingNote> note(const SaplingIncomingViewingKey& ivk) const; boost::optional<SaplingNote> note(const SaplingIncomingViewingKey& ivk) const;
virtual ~SaplingNotePlaintext() {} virtual ~SaplingNotePlaintext() {}