From f09f5a7b9504c91726f759c40e01f1dea80fa115 Mon Sep 17 00:00:00 2001 From: DanS Date: Wed, 28 Oct 2026 10:23:20 -0500 Subject: [PATCH 01/33] 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 --- src/init.cpp | 8 ++++++++ src/main.cpp | 4 ++++ src/notarizationdb.cpp | 11 ++++++++++- 3 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/init.cpp b/src/init.cpp index 7e296bebd..34403e3c1 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -274,6 +274,13 @@ void Shutdown() delete pblocktree; 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 if (pwalletMain) @@ -2080,6 +2087,7 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler) delete pcoinscatcher; delete pblocktree; delete pnotarizations; + pnotarizations = NULL; // Shutdown() deletes it, so never leave it dangling if a reopen below throws pblocktree = new CBlockTreeDB(nBlockTreeDBCache, false, fReindex, dbCompression, dbMaxOpenFiles); pcoinsdbview = new CCoinsViewDB(nCoinDBCache, false, fReindex); diff --git a/src/main.cpp b/src/main.cpp index db0af063b..f71435fed 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -2980,6 +2980,8 @@ static bool ApplyTxInUndo(const CTxInUndo& undo, CCoinsViewCache& view, const CO void ConnectNotarizations(const CBlock &block, int height) { + if (pnotarizations == NULL) // closed by Shutdown() + return; NotarizationsInBlock notarizations = ScanBlockNotarizations(block, height); if (notarizations.size() > 0) { CDBBatch batch = CDBBatch(*pnotarizations); @@ -2992,6 +2994,8 @@ void ConnectNotarizations(const CBlock &block, int height) void DisconnectNotarizations(const CBlock &block) { + if (pnotarizations == NULL) // closed by Shutdown() + return; NotarizationsInBlock nibs; if (GetBlockNotarizations(block.GetHash(), nibs)) { CDBBatch batch = CDBBatch(*pnotarizations); diff --git a/src/notarizationdb.cpp b/src/notarizationdb.cpp index 478d00583..26641cbaf 100644 --- a/src/notarizationdb.cpp +++ b/src/notarizationdb.cpp @@ -9,7 +9,10 @@ #include "main.h" #include -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) { } NotarizationsInBlock ScanBlockNotarizations(const CBlock &block, int nHeight) { @@ -55,11 +58,15 @@ NotarizationsInBlock ScanBlockNotarizations(const CBlock &block, int nHeight) { } bool GetBlockNotarizations(uint256 blockHash, NotarizationsInBlock &nibs) { + if (pnotarizations == NULL) + return false; return pnotarizations->Read(blockHash, nibs); } bool GetBackNotarization(uint256 notarizationHash, Notarization &n) { + if (pnotarizations == NULL) + return false; return pnotarizations->Read(notarizationHash, n); } @@ -86,6 +93,8 @@ void EraseBackNotarizations(const NotarizationsInBlock notarizations, CDBBatch & // Scan notarizationsdb backwards for blocks containing a notarization // for given symbol. Return height of matched notarization or 0. int ScanNotarizationsDB(int height, std::string symbol, int scanLimitBlocks, Notarization& out) { + if (pnotarizations == NULL) + return 0; if (height < 0 || height > chainActive.Height()) return false; From 3859a8ce22503947ebd74ba9e3958632c4834c09 Mon Sep 17 00:00:00 2001 From: DanS Date: Wed, 28 Oct 2026 10:25:59 -0500 Subject: [PATCH 02/33] 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 --- src/Makefile.gtest.include | 3 +- src/gtest/test_wallet_consolidation.cpp | 190 ++++++++++++++++++ ...asyncrpcoperation_saplingconsolidation.cpp | 62 ++++++ .../asyncrpcoperation_saplingconsolidation.h | 41 ++++ src/wallet/wallet.h | 15 ++ 5 files changed, 310 insertions(+), 1 deletion(-) create mode 100644 src/gtest/test_wallet_consolidation.cpp diff --git a/src/Makefile.gtest.include b/src/Makefile.gtest.include index eb985f328..28874a6ed 100644 --- a/src/Makefile.gtest.include +++ b/src/Makefile.gtest.include @@ -20,7 +20,8 @@ hush_gtest_SOURCES = \ gtest/test_fd_defense.cpp \ gtest/test_wallet_dbenv.cpp \ gtest/test_wallet_notecache.cpp \ - gtest/test_wallet_history.cpp + gtest/test_wallet_history.cpp \ + gtest/test_wallet_consolidation.cpp hush_gtest_CPPFLAGS = $(AM_CPPFLAGS) -DMULTICORE -fopenmp -DBINARY_OUTPUT -DCURVE_ALT_BN128 -DSTATIC $(BITCOIN_INCLUDES) hush_gtest_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS) diff --git a/src/gtest/test_wallet_consolidation.cpp b/src/gtest/test_wallet_consolidation.cpp new file mode 100644 index 000000000..59c8eb8f7 --- /dev/null +++ b/src/gtest/test_wallet_consolidation.cpp @@ -0,0 +1,190 @@ +// 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 + +#include +#include +#include + +#include "primitives/transaction.h" +#include "random.h" +#include "wallet/asyncrpcoperation_saplingconsolidation.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 Values(size_t n, CAmount start = 1000, CAmount step = 1000) { + std::vector v; + for (size_t i = 0; i < n; i++) + v.push_back(start + step * (CAmount)i); + return v; +} + +size_t PlannedNotes(const std::vector& 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> 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> 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 v = Values(100); + std::vector shuffled = v; + std::reverse(shuffled.begin(), shuffled.end()); + std::rotate(shuffled.begin(), shuffled.begin() + 37, shuffled.end()); + std::vector> groups = { shuffled }; + + auto plan = PlanSaplingConsolidation(groups, policy, RngHigh); + ASSERT_EQ(plan.size(), 3u); + std::set seen; + std::vector 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> 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 txs; + std::map> 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 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"; +} diff --git a/src/wallet/asyncrpcoperation_saplingconsolidation.cpp b/src/wallet/asyncrpcoperation_saplingconsolidation.cpp index 6096d3d19..14ea44631 100644 --- a/src/wallet/asyncrpcoperation_saplingconsolidation.cpp +++ b/src/wallet/asyncrpcoperation_saplingconsolidation.cpp @@ -17,6 +17,9 @@ #include "utilmoneystr.h" #include "wallet.h" +#include +#include + CAmount fConsolidationTxFee = DEFAULT_CONSOLIDATION_FEE; bool fConsolidationMapUsed = false; @@ -28,6 +31,65 @@ static const int MIN_ZOUTS = 7; extern string randomSietchZaddr(); +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((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 PlanSaplingConsolidation( + const std::vector>& groups, + const SaplingConsolidationPolicy& policy, + const std::function& rng) +{ + std::vector 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& 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 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(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; +} + AsyncRPCOperation_saplingconsolidation::AsyncRPCOperation_saplingconsolidation(int targetHeight) : targetHeight_(targetHeight) {} AsyncRPCOperation_saplingconsolidation::~AsyncRPCOperation_saplingconsolidation() {} diff --git a/src/wallet/asyncrpcoperation_saplingconsolidation.h b/src/wallet/asyncrpcoperation_saplingconsolidation.h index 675a56ad7..60effe51c 100644 --- a/src/wallet/asyncrpcoperation_saplingconsolidation.h +++ b/src/wallet/asyncrpcoperation_saplingconsolidation.h @@ -3,6 +3,9 @@ // Distributed under the GPLv3 software license, see the accompanying // 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 "asyncrpcoperation.h" #include "univalue.h" @@ -10,11 +13,47 @@ #include "zcash/zip32.h" #include "wallet.h" // for SaplingNoteEntry +#include +#include + //Default fee used for consolidation transactions, in puposhis static const CAmount DEFAULT_CONSOLIDATION_FEE = 10000; extern CAmount fConsolidationTxFee; 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 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 PlanSaplingConsolidation( + const std::vector>& groups, + const SaplingConsolidationPolicy& policy, + const std::function& rng); + class AsyncRPCOperation_saplingconsolidation : public AsyncRPCOperation { public: @@ -45,3 +84,5 @@ private: void setConsolidationResult(int numTxCreated, const CAmount& amountConsolidated, const std::vector& consolidationTxIds); }; + +#endif // HUSH_WALLET_ASYNCRPCOPERATION_SAPLINGCONSOLIDATION_H diff --git a/src/wallet/wallet.h b/src/wallet/wallet.h index 96bd4b631..41740ddeb 100644 --- a/src/wallet/wallet.h +++ b/src/wallet/wallet.h @@ -112,6 +112,21 @@ static const int MIN_AUTOSHIELD_INTERVAL = 5; 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_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_EXPIRY_DELTA = 15; // NU-straddle expiry window, shared by all three ops From cbd5f8dce45902deb0972fc6730fb6d3ca0f6bb1 Mon Sep 17 00:00:00 2001 From: DanS Date: Wed, 28 Oct 2026 10:26:20 -0500 Subject: [PATCH 03/33] init: do not rename the main thread in Shutdown() Shutdown() called RenameThread("hush-shutoff") on the main thread. On Linux that sets /proc//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 --- src/init.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/init.cpp b/src/init.cpp index 34403e3c1..776699fa9 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -211,9 +211,9 @@ void Shutdown() /// 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 /// module was initialized. - static char shutoffstr[128]; - sprintf(shutoffstr,"%s-shutoff","hush"); - RenameThread(shutoffstr); + // Do not RenameThread() here: Shutdown() runs on the main thread, whose name is the process name + // (/proc//comm). Renaming it made 'pgrep -x dragonxd' stop matching a node that was still + // shutting down and holding its locks, so pgrep-based restart scripts relaunched it too early. mempool.AddTransactionsUpdated(1); if(fDebug) { From 693f81bbbaea5f3a796d4ea31988db61157957f7 Mon Sep 17 00:00:00 2001 From: DanS Date: Wed, 28 Oct 2026 10:36:23 -0500 Subject: [PATCH 04/33] 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 --- src/Makefile.gtest.include | 3 +- src/gtest/test_wallet_dbenv.cpp | 20 ++++++ src/gtest/test_wallet_shutdownsave.cpp | 94 ++++++++++++++++++++++++++ src/init.cpp | 17 ++++- src/validationinterface.cpp | 3 + src/validationinterface.h | 6 +- src/wallet/db.cpp | 11 +++ src/wallet/db.h | 3 + src/wallet/wallet.cpp | 84 ++++++++++++++++++++++- src/wallet/wallet.h | 25 ++++++- 10 files changed, 258 insertions(+), 8 deletions(-) create mode 100644 src/gtest/test_wallet_shutdownsave.cpp diff --git a/src/Makefile.gtest.include b/src/Makefile.gtest.include index eb985f328..a2cfac6d3 100644 --- a/src/Makefile.gtest.include +++ b/src/Makefile.gtest.include @@ -20,7 +20,8 @@ hush_gtest_SOURCES = \ gtest/test_fd_defense.cpp \ gtest/test_wallet_dbenv.cpp \ gtest/test_wallet_notecache.cpp \ - gtest/test_wallet_history.cpp + gtest/test_wallet_history.cpp \ + gtest/test_wallet_shutdownsave.cpp hush_gtest_CPPFLAGS = $(AM_CPPFLAGS) -DMULTICORE -fopenmp -DBINARY_OUTPUT -DCURVE_ALT_BN128 -DSTATIC $(BITCOIN_INCLUDES) hush_gtest_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS) diff --git a/src/gtest/test_wallet_dbenv.cpp b/src/gtest/test_wallet_dbenv.cpp index 9cb0ce327..2d564abc5 100644 --- a/src/gtest/test_wallet_dbenv.cpp +++ b/src/gtest/test_wallet_dbenv.cpp @@ -56,3 +56,23 @@ TEST_F(WalletDbEnv, FailedCheckpointKeepsTheLogs) { 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()); +} diff --git a/src/gtest/test_wallet_shutdownsave.cpp b/src/gtest/test_wallet_shutdownsave.cpp new file mode 100644 index 000000000..ae29fc17c --- /dev/null +++ b/src/gtest/test_wallet_shutdownsave.cpp @@ -0,0 +1,94 @@ +// 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 + +#include + +#include "chain.h" +#include "validationinterface.h" +#include "wallet/wallet.h" + +namespace { + +std::string Reason(CWallet& wallet, bool fInitCompleted) +{ + const char* reason = wallet.ShutdownSaveSkipReason(fInitCompleted); + 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; } +}; + +} + +// 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)); +} + +// 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)); +} + +// The skip paths log and return without opening the wallet database. +TEST_F(WalletShutdownSave, SkippedSaveWritesNothing) { + CWallet wallet; + CBlockIndex tip; + wallet.SetWalletTip(&tip); + wallet.MarkStatePersisted(&tip); + LOCK(cs_main); + ASSERT_NO_THROW(wallet.PersistStateAtShutdown(true)); + ASSERT_NO_THROW(wallet.PersistStateAtShutdown(false)); +} diff --git a/src/init.cpp b/src/init.cpp index 7e296bebd..452e53988 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -99,6 +99,9 @@ extern void hush_init(int32_t height); CWallet* pwalletMain = NULL; #endif 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 fInitCompleted(false); #ifdef WIN32 // Win32 LevelDB doesn't use file descriptors, and the ones used for @@ -257,6 +260,12 @@ void Shutdown() LOCK(cs_main); if (pcoinsTip != NULL) { 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); +#endif } if (pcoinsTip != NULL) { delete pcoinsTip; @@ -2662,6 +2671,9 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler) pindexRescan = FindForkInGlobalIndex(chainActive, locator); else 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) { @@ -2922,5 +2934,8 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler) if(fDebug) fprintf(stderr,"%s end fRequestShutdown=%d\n", __FUNCTION__, !!fRequestShutdown); - return !fRequestShutdown; + bool fOk = !fRequestShutdown; + if (fOk) + fInitCompleted = true; + return fOk; } diff --git a/src/validationinterface.cpp b/src/validationinterface.cpp index 4de52d6f2..1c680cdf6 100644 --- a/src/validationinterface.cpp +++ b/src/validationinterface.cpp @@ -20,6 +20,8 @@ static CMainSignals g_signals; +std::atomic fWalletNotifyFailed(false); + CMainSignals& GetMainSignals() { return g_signals; @@ -103,6 +105,7 @@ bool NotifyWalletsOrShutdown(const std::function& notify) 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"), diff --git a/src/validationinterface.h b/src/validationinterface.h index 98b17abdf..ad3b1d1a7 100644 --- a/src/validationinterface.h +++ b/src/validationinterface.h @@ -8,6 +8,7 @@ #define HUSH_VALIDATIONINTERFACE_H #include +#include #include #include "zcash/IncrementalMerkleTree.hpp" @@ -31,6 +32,9 @@ void UnregisterAllValidationInterfaces(); void EraseFromWallets(const uint256 &hash); /** Rescan all registered wallets */ 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 fWalletNotifyFailed; class CValidationInterface { protected: @@ -39,7 +43,7 @@ protected: virtual void EraseFromWallet(const uint256 &hash) {} virtual void RescanWallet() {} virtual void ChainTip(const CBlockIndex *pindex, const CBlock *pblock, boost::optional> added) {} - virtual void SetBestChain(const CBlockLocator &locator) {} + virtual bool SetBestChain(const CBlockLocator &locator) { return true; } virtual void UpdatedTransaction(const uint256 &hash) {} virtual void ResendWalletTransactions(int64_t nBestBlockTime) {} virtual void BlockChecked(const CBlock&, const CValidationState&) {} diff --git a/src/wallet/db.cpp b/src/wallet/db.cpp index 5f2df38a3..44ae47cb2 100644 --- a/src/wallet/db.cpp +++ b/src/wallet/db.cpp @@ -483,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) { int64_t nStart = GetTimeMillis(); diff --git a/src/wallet/db.h b/src/wallet/db.h index 73ea50e43..599e33e0e 100644 --- a/src/wallet/db.h +++ b/src/wallet/db.h @@ -100,6 +100,9 @@ public: bool Open(const boost::filesystem::path& path); void Close(); 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 CloseDb(const std::string& strFile); diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp index f3f098589..08a9d3ffc 100644 --- a/src/wallet/wallet.cpp +++ b/src/wallet/wallet.cpp @@ -818,7 +818,7 @@ bool CWallet::CommitAutomatedTx(const CTransaction& tx) { return CommitTransaction(wtx, reservekey); } -void CWallet::SetBestChain(const CBlockLocator& loc) +bool CWallet::SetBestChain(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 @@ -827,15 +827,85 @@ void CWallet::SetBestChain(const CBlockLocator& loc) // 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); - if (pindexWalletTip != nullptr) + // 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; + } } // Default ctor => fFlushOnClose=true => ~CDB runs a full BDB txn_checkpoint over the entire // cache. Fine for the hourly/shutdown callers; ruinous inside a scan (see SetBestChainNoFlush). CWalletDB walletdb(strWalletFile); - SetBestChainINTERNAL(walletdb, locator); + bool fWritten = SetBestChainINTERNAL(walletdb, locator); + if (fWritten) + RecordStatePersisted(pindexStamped, nGeneration); + return fWritten; +} + +void CWallet::RecordStatePersisted(const CBlockIndex* pindex, uint64_t nGeneration) +{ + LOCK(cs_wallet); + pindexPersistedTip = pindex; + nPersistedWitnessGeneration = nGeneration; +} + +void CWallet::MarkStatePersisted(const CBlockIndex* pindex) +{ + LOCK(cs_wallet); + RecordStatePersisted(pindex, nWitnessGeneration); +} + +const char* CWallet::ShutdownSaveSkipReason(bool fInitCompleted) +{ + // AppInit2 failed or was cut short: the other threads were interrupted but not joined, and the + // wallet tip may still be unset, in which case SetBestChain would stamp the chain tip over an + // interrupted rescan's checkpoint and the next start would skip the unscanned range. + if (!fInitCompleted) + return "startup did not complete"; + if (fWalletNotifyFailed) + return "the wallet failed to process a block"; + if (!bitdb.IsHealthy()) + return "the wallet database environment reported an error"; + LOCK(cs_wallet); + if (pindexWalletTip == nullptr) + return "the wallet tip is not set"; + if (pindexWalletTip == pindexPersistedTip && nWitnessGeneration == nPersistedWitnessGeneration) + return "nothing changed since the last save"; + return nullptr; +} + +void CWallet::PersistStateAtShutdown(bool fInitCompleted) +{ + LOCK2(cs_main, cs_wallet); + const char* skip = ShutdownSaveSkipReason(fInitCompleted); + if (skip != nullptr) { + LogPrintf("%s: not saving the wallet state: %s\n", __func__, skip); + return; + } + // SetBestChainINTERNAL writes every tx that has Sapling note data, each with its whole witness + // cache, in one transaction: on a large wallet this is the bulk of wallet.dat. A kill while it + // runs rolls back to the previous save at the next start (DB_RECOVER), losing only the saving. + unsigned int nTxs = 0; + for (const std::pair& wtxItem : mapWallet) + if (!wtxItem.second.mapSaplingNoteData.empty()) + nTxs++; + const int nHeight = pindexWalletTip->GetHeight(); + LogPrintf("Saving wallet state (note witnesses and best block %d, %u txs)...\n", nHeight, nTxs); + int64_t nStart = GetTimeMillis(); + bool fWritten = SetBestChain(chainActive.GetLocator()); + LogPrintf("%s: wallet state %s at height %d: %u txs in %dms\n", __func__, + fWritten ? "saved" : "NOT saved (the write failed; the previous save stays on disk)", + nHeight, nTxs, GetTimeMillis() - nStart); } bool CWallet::SetBestChainNoFlush(const CBlockLocator& loc) @@ -1215,6 +1285,7 @@ void CWallet::ClearNoteWitnessCache() notes++; } } + nWitnessGeneration++; LogPrintf("%s: Cleared witness data from %d wallet items and %d SaplingNotes\n", __func__, mapWallet.size(), notes); } @@ -1223,6 +1294,7 @@ void CWallet::DecrementNoteWitnesses(const CBlockIndex* pindex) extern int32_t HUSH_REWIND; LOCK2(cs_main, cs_wallet); + nWitnessGeneration++; for (std::pair& wtxItem : mapWallet) { //Sapling @@ -1355,6 +1427,7 @@ int CWallet::VerifyAndSetInitialWitness(const CBlockIndex* pindex, bool witnessO //Clear witness Cache for all other scenarios pblockindex = chainActive[wtxHeight]; ::ClearSingleNoteWitnessCache(nd); + nWitnessGeneration++; LogPrintf("%s: Setting Initial Sapling Witness for tx %s, %i of %i\n", __func__, wtxHash.ToString(), nWitnessTxIncrement, nWitnessTotalTxCount); @@ -1653,6 +1726,7 @@ void CWallet::BuildWitnessCache(const CBlockIndex* pindex, bool witnessOnly) // (DecrementNoteWitnesses clears it), keeping the heal self-correcting. The unrecoverable count // itself comes from checkRoot() on the workers, and only for a bulk rebuild. if (!work.empty()) { + nWitnessGeneration++; for (SaplingNoteData* nd : work) nd->witnessRootValidated = true; if (bulkRebuild) { @@ -2004,6 +2078,10 @@ bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFromLoadWallet, CWalletD fUpdated = true; } } + // Only a real change: re-adding a tx unchanged (ReacceptWalletTransactions on every start + // for each unconfirmed tx) leaves nothing new for SetBestChain to write. + if ((fInsertedNew || fUpdated) && !wtx.mapSaplingNoteData.empty()) + nWitnessGeneration++; //// debug print LogPrintf("AddToWallet %s at height %d %s%s\n", wtxIn.GetHash().ToString(), hush_blockheight(wtxIn.hashBlock), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : "")); diff --git a/src/wallet/wallet.h b/src/wallet/wallet.h index 96bd4b631..89a3c1089 100644 --- a/src/wallet/wallet.h +++ b/src/wallet/wallet.h @@ -993,6 +993,16 @@ private: // 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; + void RecordStatePersisted(const CBlockIndex* pindex, uint64_t nGeneration); + protected: bool UpdatedNoteData(const CWalletTx& wtxIn, CWalletTx& wtx, bool fSameBlock); void MarkAffectedTransactionsDirty(const CTransaction& tx); @@ -1320,8 +1330,19 @@ public: void RunSaplingConsolidation(int blockHeight); void RunAutoShieldCoinbase(int blockHeight); bool CommitAutomatedTx(const CTransaction& tx); - /** Saves witness caches and best block locator to disk. Overrides CValidationInterface. */ - void SetBestChain(const CBlockLocator& loc); + /** Saves witness caches and best block locator to disk in one atomic write, and reports whether + * 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); + /** 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); // 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 From a800a266e595463b6c411f35e1f31b4564c1c62f Mon Sep 17 00:00:00 2001 From: DanS Date: Wed, 28 Oct 2026 10:37:33 -0500 Subject: [PATCH 05/33] 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 --- src/init.cpp | 104 +++-- ...asyncrpcoperation_saplingconsolidation.cpp | 380 ++++++++++-------- .../asyncrpcoperation_saplingconsolidation.h | 26 +- src/wallet/wallet.cpp | 16 +- src/wallet/wallet.h | 7 +- 5 files changed, 340 insertions(+), 193 deletions(-) diff --git a/src/init.cpp b/src/init.cpp index 7e296bebd..d7c574bf6 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -479,10 +479,13 @@ 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("-hdtransparentgaplimit=", 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=", 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("-consolidationinterval", _("Block interval between consolidations (default: 25)")); - strUsage += HelpMessageOpt("-consolidatesaplingaddress=", _("Specify Sapling Address to Consolidate. (default: all)")); - strUsage += HelpMessageOpt("-consolidationtxfee", strprintf(_("Fee amount in Puposhis used send consolidation transactions. (default %i)"), DEFAULT_CONSOLIDATION_FEE)); + 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", strprintf(_("Block interval between consolidation rounds (default: %i, min %i)"), DEFAULT_CONSOLIDATION_INTERVAL, MIN_CONSOLIDATION_INTERVAL)); + strUsage += HelpMessageOpt("-consolidationthreshold", strprintf(_("Only consolidate addresses with more than this many spendable notes (default: %i)"), DEFAULT_CONSOLIDATION_THRESHOLD)); + 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=", _("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("-zsweepaddress=", _("Specify the shielded address where swept funds will be sent)")); @@ -2409,32 +2412,58 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler) 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); - if(pwalletMain->fSaplingConsolidationEnabled) { - fConsolidationTxFee = GetArg("-consolidationtxfee", DEFAULT_CONSOLIDATION_FEE); - fConsolidationMapUsed = !mapMultiArgs["-consolidatesaplingaddress"].empty(); + { + CAmount consolidationFee = GetArg("-consolidationtxfee", DEFAULT_CONSOLIDATION_FEE); + 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); - if (consolidationInterval < 5) { - LogPrintf("%s: Invalid consolidation interval of %d < 5, setting to default of 25\n", __func__, consolidationInterval); - consolidationInterval = 25; + int consolidationInterval = GetArg("-consolidationinterval", DEFAULT_CONSOLIDATION_INTERVAL); + if (consolidationInterval < MIN_CONSOLIDATION_INTERVAL) { + InitWarning(strprintf(_("consolidation interval %d below the minimum, clamping to %d"), + 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->nextConsolidation = pwalletMain->consolidationInterval + chainActive.Height(); - LogPrintf("%s: set nextConsolidation=%d\n", __func__, pwalletMain->nextConsolidation ); - - //Validate Sapling Addresses - vector& vaddresses = mapMultiArgs["-consolidatesaplingaddress"]; - for (int i = 0; i < vaddresses.size(); i++) { - LogPrintf("Consolidating Sapling Address: %s\n", vaddresses[i]); - auto zAddress = DecodePaymentAddress(vaddresses[i]); - if (!IsValidPaymentAddress(zAddress)) { - return InitError("Invalid consolidation address"); - } + pwalletMain->consolidationInterval = consolidationInterval; + pwalletMain->consolidationThreshold = consolidationThreshold; + pwalletMain->consolidationBatchSize = consolidationBatchSize; + pwalletMain->consolidationMaxTxs = consolidationMaxTxs; + if (pwalletMain->fSaplingConsolidationEnabled) { + pwalletMain->nextConsolidation = pwalletMain->consolidationInterval + chainActive.Height(); + LogPrintf("%s: consolidation enabled, nextConsolidation=%d interval=%d threshold=%d batchsize=%d maxtxs=%d fee=%d\n", + __func__, pwalletMain->nextConsolidation, consolidationInterval, consolidationThreshold, + consolidationBatchSize, consolidationMaxTxs, (int)fConsolidationTxFee); } } + // Set when -zsweep makes consolidation work on the sweep address (see below). + bool fConsolidateSweepAddress = false; //Set Sweep pwalletMain->fSweepEnabled = GetBoolArg("-zsweep", false); @@ -2495,7 +2524,7 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler) //Validate 1 Consolidation address only that matches the sweep address vector& vaddresses = mapMultiArgs["-consolidatesaplingaddress"]; if (vaddresses.size() == 0) { - fConsolidationMapUsed = true; + fConsolidateSweepAddress = true; mapMultiArgs["-consolidatesaplingaddress"] = vSweep; } else { pwalletMain->consolidationAddress = vaddresses[0]; @@ -2508,6 +2537,31 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler) } } + // 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. + { + const vector& vaddresses = mapMultiArgs["-consolidatesaplingaddress"]; + fConsolidationMapUsed = !vaddresses.empty(); + pwalletMain->consolidationAddresses.clear(); + for (size_t i = 0; i < vaddresses.size(); i++) { + LogPrintf("Consolidating Sapling Address: %s\n", vaddresses[i]); + auto zAddress = DecodePaymentAddress(vaddresses[i]); + if (!IsValidPaymentAddress(zAddress) || + boost::get(&zAddress) == nullptr) { + return InitError("Invalid consolidation address: -consolidatesaplingaddress must be a Sapling z-address"); + } + if (!boost::apply_visitor(HaveSpendingKeyForPaymentAddress(pwalletMain), zAddress)) { + if (!fConsolidateSweepAddress) { + return InitError(strprintf("Wallet must hold the spending key of -consolidatesaplingaddress %s", vaddresses[i])); + } + LogPrintf("%s: the zsweep address is external to this wallet, so consolidation has nothing to do\n", __func__); + } + pwalletMain->consolidationAddresses.push_back(boost::get(zAddress)); + } + if (!vaddresses.empty()) + pwalletMain->consolidationAddress = vaddresses[0]; + } + // 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. diff --git a/src/wallet/asyncrpcoperation_saplingconsolidation.cpp b/src/wallet/asyncrpcoperation_saplingconsolidation.cpp index 14ea44631..835d49c28 100644 --- a/src/wallet/asyncrpcoperation_saplingconsolidation.cpp +++ b/src/wallet/asyncrpcoperation_saplingconsolidation.cpp @@ -90,7 +90,8 @@ std::vector PlanSaplingConsolidation( return plan; } -AsyncRPCOperation_saplingconsolidation::AsyncRPCOperation_saplingconsolidation(int targetHeight) : targetHeight_(targetHeight) {} +AsyncRPCOperation_saplingconsolidation::AsyncRPCOperation_saplingconsolidation(int targetHeight, const SaplingConsolidationRequest& request) + : targetHeight_(targetHeight), request_(request) {} AsyncRPCOperation_saplingconsolidation::~AsyncRPCOperation_saplingconsolidation() {} @@ -153,6 +154,10 @@ void AsyncRPCOperation_saplingconsolidation::main() { } } +// Notes whose missing or desynced witness has already been logged, so a note that can't be spent is +// reported once rather than every round. Guarded by pwalletMain->cs_wallet. +static std::set setWitnessSkipLogged; + bool AsyncRPCOperation_saplingconsolidation::main_impl() { bool status=true; auto opid=getId(); @@ -171,197 +176,256 @@ bool AsyncRPCOperation_saplingconsolidation::main_impl() { auto nextActivationHeight = NextActivationHeight(tipHeight, consensusParams); 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); - setConsolidationResult(0, 0, std::vector()); + setConsolidationResult(ConsolidationTally()); return status; } - std::vector saplingEntries; - std::set addresses; + // One address's eligible notes and the key that spends them. + struct AddressNotes { + libzcash::SaplingPaymentAddress addr; + libzcash::SaplingExtendedSpendingKey extsk; + std::vector notes; + }; + // One transaction to build: notes of one address, with witnesses that share one anchor. + struct PlannedTx { + size_t group; + std::vector notes; + std::vector witnesses; + uint256 anchor; + }; + std::vector groups; + std::vector txs; + ConsolidationTally tally; { LOCK2(cs_main, pwalletMain->cs_wallet); // We set minDepth to 11 to avoid unconfirmed notes and in anticipation of specifying - // an anchor at height N-10 for each SpendDescription - // Consider, should notes be sorted? - pwalletMain->GetFilteredNotes(saplingEntries, "", 11); + // an anchor at height N-10 for each SpendDescription. Spent (also by a mempool tx) and + // locked notes are left out, as are notes this wallet can't spend. + std::vector saplingEntries; + pwalletMain->GetFilteredNotes(saplingEntries, "", CONSOLIDATION_MIN_DEPTH); - if(saplingEntries.size() == 0) { - LogPrintf("%s: Nothing to consolidate, done.\n",opid); - return true; + std::set wanted(request_.addresses.begin(), request_.addresses.end()); + std::map groupOf; + std::set noKey; + for (const SaplingNoteEntry& entry : saplingEntries) { + if (!wanted.empty() && wanted.count(entry.address) == 0) + continue; + auto it = groupOf.find(entry.address); + if (it == groupOf.end()) { + if (noKey.count(entry.address)) + continue; + AddressNotes g; + g.addr = entry.address; + if (!pwalletMain->GetSaplingExtendedSpendingKey(entry.address, g.extsk)) { + noKey.insert(entry.address); + continue; + } + it = groupOf.insert(std::make_pair(entry.address, groups.size())).first; + groups.push_back(std::move(g)); + } + groups[it->second].notes.push_back(entry); } - // store sapling inputs so we can correctly lock and unlock them - for (auto entry : saplingEntries) { - z_sapling_inputs_.push_back(entry); - } - - if (fConsolidationMapUsed) { - const vector& v = mapMultiArgs["-consolidatesaplingaddress"]; - for(int i = 0; i < v.size(); i++) { - auto zAddress = DecodePaymentAddress(v[i]); - if (boost::get(&zAddress) != nullptr) { - libzcash::SaplingPaymentAddress saplingAddress = boost::get(zAddress); - addresses.insert(saplingAddress); - } else { - LogPrintf("%s: Invalid zaddr, exiting\n", opid); - return false; + // Plan the round, then fetch the planned notes' witnesses. A note without a usable witness is + // dropped and the round re-planned without it, so it costs the round nothing but a log line. + // Each pass drops at least one note, so this ends. + std::set excluded; + for (;;) { + std::vector> live(groups.size()); + std::vector> values(groups.size()); + for (size_t g = 0; g < groups.size(); g++) { + for (size_t i = 0; i < groups[g].notes.size(); i++) { + if (excluded.count(groups[g].notes[i].op)) + continue; + live[g].push_back(i); + values[g].push_back(CAmount(groups[g].notes[i].note.value())); } } - } else { - pwalletMain->GetSaplingPaymentAddresses(addresses); + std::vector plan = PlanSaplingConsolidation( + values, request_.policy, [](uint64_t n) { return GetRand(n); }); + + // Witnesses per address: every spend of one address's txs then shares that address's anchor. + std::map> opsOf; + for (const SaplingConsolidationBatch& b : plan) + for (size_t idx : b.notes) + opsOf[b.group].push_back(groups[b.group].notes[live[b.group][idx]].op); + std::map witnessOf; + std::map anchorOf; + bool missing = false; + for (const auto& p : opsOf) { + std::vector> witnesses; + uint256 anchor; + pwalletMain->GetSaplingNoteWitnesses(p.second, witnesses, anchor); + anchorOf[p.first] = anchor; + for (size_t i = 0; i < p.second.size(); i++) { + if (witnesses[i]) { + witnessOf.insert(std::make_pair(p.second[i], witnesses[i].get())); + continue; + } + missing = true; + excluded.insert(p.second[i]); + if (setWitnessSkipLogged.insert(p.second[i]).second) + LogPrintf("%s: skipping note %s:%u, it has no usable witness\n", + opid, p.second[i].hash.ToString(), p.second[i].n); + } + } + if (missing) + continue; + + for (const SaplingConsolidationBatch& b : plan) { + PlannedTx tx; + tx.group = b.group; + tx.anchor = anchorOf[b.group]; + for (size_t idx : b.notes) { + const SaplingNoteEntry& entry = groups[b.group].notes[live[b.group][idx]]; + tx.notes.push_back(entry); + tx.witnesses.push_back(witnessOf.at(entry.op)); + } + txs.push_back(std::move(tx)); + } + break; + } + tally.skippedNotes = excluded.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); + } } } - int numTxCreated = 0; - std::vector consolidationTxIds; - CAmount amountConsolidated = 0; - CCoinsViewCache coinsView(pcoinsTip); + if (txs.empty()) { + LogPrintf("%s: Nothing to consolidate (no address over %d eligible notes), done.\n", opid, request_.policy.threshold); + setConsolidationResult(tally); + 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) { - libzcash::SaplingExtendedSpendingKey extsk; - if (pwalletMain->GetSaplingExtendedSpendingKey(addr, extsk)) { + for (const PlannedTx& planned : txs) { + if (isCancelled()) { + LogPrintf("%s: Canceled. Stopping.\n", opid); + tally.error = "cancelled"; + status=false; + break; + } + const AddressNotes& group = groups[planned.group]; - std::vector fromNotes; - CAmount amountToSend = 0; - // max of 8 zins means the tx cannot reduce the anonset, - // since there will be 8 zins and 8 zouts at worst case - // This also helps reduce ztx creation time - int maxQuantity = rand() % 8 + 1; - for (const SaplingNoteEntry& saplingEntry : saplingEntries) { + auto builder = TransactionBuilder(consensusParams, tipHeight, pwalletMain); + builder.SetExpiryHeight(tipHeight + AUTO_OP_EXPIRY_DELTA); - libzcash::SaplingIncomingViewingKey ivk; - pwalletMain->GetSaplingIncomingViewingKey(boost::get(saplingEntry.address), ivk); + CAmount amountToSend = 0; + for (const SaplingNoteEntry& entry : planned.notes) + amountToSend += CAmount(entry.note.value()); + // Notes worth no more than the fee go fee-free rather than being burnt into it. + CAmount thisTxFee = amountToSend <= request_.fee ? 0 : 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)); - //Select Notes from that same address we will be sending to. - if (ivk == extsk.expsk.full_viewing_key().in_viewing_key()) { - amountToSend += CAmount(saplingEntry.note.value()); - fromNotes.push_back(saplingEntry); - } - - //Only use a randomly determined number of notes - if (fromNotes.size() >= maxQuantity) - break; - - } - - // 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 ops; - std::vector notes; - for (auto fromNote : fromNotes) { - ops.push_back(fromNote.op); - notes.push_back(fromNote.note); - } - - // Fetch Sapling anchor and witnesses - uint256 anchor; - std::vector> 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(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; + // Add Sapling spends + bool spendsOk = true; + 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; break; } - CTransaction tx = maybe_tx.get(); + LogPrint("zrpcunsafe", "%s: Added consolidation input %d\n", opid, i); + } + if (!spendsOk) { + LogPrintf("%s: Consolidation inputs do not share one anchor! Stopping.\n", opid); + tally.error = "inputs do not share one anchor"; + status=false; + break; + } - if (isCancelled()) { - LogPrintf("%s: Canceled. Stopping.\n", opid); - status=false; - break; - } + LogPrint("zrpcunsafe", "%s: Using fee=%d\n", opid, thisTxFee); + builder.SetFee(thisTxFee); - // Lock shielded input notes - lock_notes(); - LogPrint("zrpc", "%s: consolidation input notes locked\n", getId()); + // Add the actual consolidation tx + builder.AddSaplingOutput(group.extsk.expsk.ovk, group.addr, actualAmountToSend); + LogPrint("zrpcunsafe", "%s: Added consolidation output %s with amount=%li\n", opid, group.addr.GetHash().ToString().c_str(), actualAmountToSend); - if(pwalletMain->CommitAutomatedTx(tx)) { - LogPrintf("%s: Committed consolidation transaction with txid=%s\n",opid, tx.GetHash().ToString()); - amountConsolidated += actualAmountToSend; - consolidationTxIds.push_back(tx.GetHash().ToString()); - numTxCreated++; + // 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. + bool zoutsOk = true; + 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(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 { - LogPrintf("%s: Consolidation transaction FAILED in CommitTransaction, txid=%s\n",opid , tx.GetHash().ToString()); - - unlock_notes(); - LogPrint("zrpc", "%s: consolidatoin input notes unlocked\n", getId()); - - setConsolidationResult(numTxCreated, amountConsolidated, consolidationTxIds); - status = false; + LogPrintf("%s: Invalid payment address %s! Stopping.\n", opid, zdust); + zoutsOk = false; break; } + } + if (!zoutsOk) { + tally.error = "invalid sietch address"; + 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); + tally.error = "failed to build transaction"; + status=false; + break; + } + CTransaction tx = maybe_tx.get(); + if (isCancelled()) { + LogPrintf("%s: Canceled. Stopping.\n", opid); + tally.error = "cancelled"; + 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()); + tally.error = "transaction was not accepted (CommitTransaction failed)"; + status = false; + break; } } - LogPrintf("%s: Created %d transactions with total Sapling output amount=%s,status=%d\n",opid , numTxCreated, FormatMoney(amountConsolidated), (int)status); - setConsolidationResult(numTxCreated, amountConsolidated, consolidationTxIds); + LogPrintf("%s: Created %d transactions merging %d notes with total Sapling output amount=%s, skipped %d notes, status=%d\n", + opid, tally.txids.size(), tally.notesMerged, FormatMoney(tally.amountConsolidated), tally.skippedNotes, (int)status); + setConsolidationResult(tally); return status; } -void AsyncRPCOperation_saplingconsolidation::setConsolidationResult(int numTxCreated, const CAmount& amountConsolidated, const std::vector& consolidationTxIds) { +void AsyncRPCOperation_saplingconsolidation::setConsolidationResult(const ConsolidationTally& tally) { UniValue res(UniValue::VOBJ); - res.push_back(Pair("num_tx_created", numTxCreated)); - res.push_back(Pair("amount_consolidated", FormatMoney(amountConsolidated))); + res.push_back(Pair("num_tx_created", (int)tally.txids.size())); + res.push_back(Pair("amount_consolidated", FormatMoney(tally.amountConsolidated))); UniValue txIds(UniValue::VARR); - for (const std::string& txId : consolidationTxIds) { + for (const std::string& txId : tally.txids) { txIds.push_back(txId); } 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)); + if (!tally.error.empty()) + res.push_back(Pair("error", tally.error)); set_result(res); } @@ -384,14 +448,6 @@ UniValue AsyncRPCOperation_saplingconsolidation::getStatus() const { 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 void AsyncRPCOperation_saplingconsolidation::unlock_notes() { LOCK2(cs_main, pwalletMain->cs_wallet); diff --git a/src/wallet/asyncrpcoperation_saplingconsolidation.h b/src/wallet/asyncrpcoperation_saplingconsolidation.h index 60effe51c..ac6a0e26f 100644 --- a/src/wallet/asyncrpcoperation_saplingconsolidation.h +++ b/src/wallet/asyncrpcoperation_saplingconsolidation.h @@ -54,10 +54,28 @@ std::vector PlanSaplingConsolidation( const SaplingConsolidationPolicy& policy, const std::function& rng); +// What a consolidation operation is asked to do, fixed when it is enqueued. +struct SaplingConsolidationRequest { + CAmount fee = DEFAULT_CONSOLIDATION_FEE; + SaplingConsolidationPolicy policy; + std::vector addresses; // empty: every address the wallet can spend +}; + +// What a round did. +struct ConsolidationTally { + std::vector 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 + std::string error; +}; + class AsyncRPCOperation_saplingconsolidation : public AsyncRPCOperation { public: - AsyncRPCOperation_saplingconsolidation(int targetHeight); + AsyncRPCOperation_saplingconsolidation(int targetHeight, const SaplingConsolidationRequest& request); virtual ~AsyncRPCOperation_saplingconsolidation(); // We don't want to be copied or moved around @@ -72,16 +90,16 @@ public: virtual UniValue getStatus() const; - void lock_notes(); void unlock_notes(); private: int targetHeight_; + SaplingConsolidationRequest request_; bool main_impl(); - std::vector z_sapling_inputs_; + std::vector z_sapling_inputs_; // the notes this round locked - void setConsolidationResult(int numTxCreated, const CAmount& amountConsolidated, const std::vector& consolidationTxIds); + void setConsolidationResult(const ConsolidationTally& tally); }; diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp index f3f098589..48019e411 100644 --- a/src/wallet/wallet.cpp +++ b/src/wallet/wallet.cpp @@ -710,6 +710,14 @@ void CWallet::RunSaplingConsolidation(int blockHeight) { return; } + // Nothing can be signed while the wallet is locked. Skip the round instead of enqueueing one that + // can spend nothing, and look again an interval later. + if (IsLocked()) { + LogPrintf("%s: wallet locked; not consolidating at height=%d\n", __func__, blockHeight); + nextConsolidation = consolidationInterval + blockHeight; + return; + } + LogPrintf("%s: consolidation enabled at blockHeight=%d fSweepRunning=%d\n", __func__, blockHeight, fSweepRunning ); if (fSweepRunning) { @@ -734,7 +742,13 @@ void CWallet::RunSaplingConsolidation(int blockHeight) { q->popOperationForId(saplingConsolidationOperationId); } pendingSaplingConsolidationTxs.clear(); - std::shared_ptr operation(new AsyncRPCOperation_saplingconsolidation(blockHeight + AUTO_OP_TARGET_HEIGHT_OFFSET)); + SaplingConsolidationRequest request; + request.fee = fConsolidationTxFee; + request.policy.threshold = consolidationThreshold; + request.policy.batchSize = consolidationBatchSize; + request.policy.maxTxs = consolidationMaxTxs; + request.addresses = consolidationAddresses; + std::shared_ptr operation(new AsyncRPCOperation_saplingconsolidation(blockHeight + AUTO_OP_TARGET_HEIGHT_OFFSET, request)); saplingConsolidationOperationId = operation->getId(); if (!q->addOperation(operation)) { // Queue is closing (shutdown). Release the flag we just set, or it stays diff --git a/src/wallet/wallet.h b/src/wallet/wallet.h index 41740ddeb..7a2e1b707 100644 --- a/src/wallet/wallet.h +++ b/src/wallet/wallet.h @@ -895,7 +895,12 @@ public: int amountSwept = 0; int amountConsolidated = 0; 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 consolidationAddresses; int sweepFee = 10000; int sweepMaxInputs = 200; std::string sweepAddress = ""; From a7adcbc954bd187977ab4687d16b19bf11b4ba78 Mon Sep 17 00:00:00 2001 From: DanS Date: Wed, 28 Oct 2026 10:42:30 -0500 Subject: [PATCH 06/33] 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 --- src/init.cpp | 112 ++++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 93 insertions(+), 19 deletions(-) diff --git a/src/init.cpp b/src/init.cpp index 776699fa9..2fca612f4 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -79,6 +79,7 @@ #include #include #include +#include #include #include #include @@ -125,6 +126,97 @@ static const char* DEFAULT_ASMAP_FILENAME="asmap.dat"; // 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 +// 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; + +/** + * Is /LOCK held, by another process or by another open DB in this one? Probed with LevelDB's + * own Env::LockFile, i.e. the same lock DB::Open takes. A missing LOCK file cannot be held. Any other + * failure to take the lock counts as held: the caller then never moves or wipes the directory. + */ +static bool LevelDBLockHeld(const boost::filesystem::path& dbdir) +{ + const boost::filesystem::path lockpath = dbdir / "LOCK"; + boost::system::error_code ec; + if (!boost::filesystem::exists(lockpath, ec)) + return false; + leveldb::Env* env = leveldb::Env::Default(); + leveldb::FileLock* lock = NULL; + if (!env->LockFile(lockpath.string(), &lock).ok()) + return true; + env->UnlockFile(lock); + 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 held (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. If even that fails, fall back to an in-memory DB. + */ +static NotarizationDB* OpenNotarizationDB(bool fWipe) +{ + const boost::filesystem::path ndir = GetDataDir() / "notarizations"; + std::string strError; + try { + return new NotarizationDB(NOTARIZATION_DB_CACHE_BYTES, false, fWipe); + } catch (const std::exception& e) { + strError = e.what(); + } + + if (LevelDBLockHeld(ndir)) { + LogPrintf("%s: notarizations DB failed to open (%s): notarizations/LOCK is held by another process; waiting for a previous dragonxd to release notarizations/LOCK (up to %d s)\n", + __func__, strError, NOTARIZATION_LOCK_WAIT_SECONDS); + int nWaited = 0; + while (nWaited < NOTARIZATION_LOCK_WAIT_SECONDS && !ShutdownRequested() && LevelDBLockHeld(ndir)) { + MilliSleep(1000); + nWaited++; + } + if (!LevelDBLockHeld(ndir)) { + try { + NotarizationDB* pdb = new NotarizationDB(NOTARIZATION_DB_CACHE_BYTES, false, fWipe); + LogPrintf("%s: notarizations/LOCK released after %d s; notarizations DB opened\n", __func__, nWaited); + return pdb; + } catch (const std::exception& e) { + strError = e.what(); + } + } + if (LevelDBLockHeld(ndir)) { + LogPrintf("%s: notarizations/LOCK still held after %d s; using an in-memory notarizations DB for this run (on-disk notarizations DB left untouched)\n", + __func__, nWaited); + return new NotarizationDB(NOTARIZATION_DB_CACHE_BYTES, true, false); + } + // The lock is free but the DB still does not open: treat it as corrupt. + } + + 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) // Shutdown @@ -2093,25 +2185,7 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler) pcoinsdbview = new CCoinsViewDB(nCoinDBCache, false, fReindex); pcoinscatcher = new CCoinsViewErrorCatcher(pcoinsdbview); pcoinsTip = new CCoinsViewCache(pcoinscatcher); - try { - 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); - } + pnotarizations = OpenNotarizationDB(fReindex); if (fReindex) { From 4d7de7a0ebc72ba0d2c8c1cdd632e604a7db350c Mon Sep 17 00:00:00 2001 From: DanS Date: Wed, 28 Oct 2026 10:44:43 -0500 Subject: [PATCH 07/33] 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 --- src/init.cpp | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src/init.cpp b/src/init.cpp index 2fca612f4..aa23fbbe9 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -2174,12 +2174,13 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler) do { try { UnloadBlockIndex(); - delete pcoinsTip; - delete pcoinsdbview; - delete pcoinscatcher; - delete pblocktree; - delete pnotarizations; - pnotarizations = NULL; // Shutdown() deletes it, so never leave it dangling if a reopen below throws + // Shutdown() deletes (and pcoinsTip: flushes) whatever is non-NULL here, so never leave + // a pointer dangling if one of the reopens below throws. + delete pcoinsTip; pcoinsTip = NULL; + delete pcoinsdbview; pcoinsdbview = NULL; + delete pcoinscatcher; pcoinscatcher = NULL; + delete pblocktree; pblocktree = NULL; + delete pnotarizations; pnotarizations = NULL; pblocktree = new CBlockTreeDB(nBlockTreeDBCache, false, fReindex, dbCompression, dbMaxOpenFiles); pcoinsdbview = new CCoinsViewDB(nCoinDBCache, false, fReindex); From bc3867a3125729de857ce72a7d0e55b75b4c707a Mon Sep 17 00:00:00 2001 From: DanS Date: Wed, 28 Oct 2026 10:44:55 -0500 Subject: [PATCH 08/33] 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 --- src/Makefile.gtest.include | 3 +- src/gtest/test_wallet_witnessroots.cpp | 354 +++++++++++++++++++++++++ src/wallet/wallet.cpp | 122 +++++++-- 3 files changed, 453 insertions(+), 26 deletions(-) create mode 100644 src/gtest/test_wallet_witnessroots.cpp diff --git a/src/Makefile.gtest.include b/src/Makefile.gtest.include index a2cfac6d3..ac9c9fc02 100644 --- a/src/Makefile.gtest.include +++ b/src/Makefile.gtest.include @@ -21,7 +21,8 @@ hush_gtest_SOURCES = \ gtest/test_wallet_dbenv.cpp \ gtest/test_wallet_notecache.cpp \ gtest/test_wallet_history.cpp \ - gtest/test_wallet_shutdownsave.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_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS) diff --git a/src/gtest/test_wallet_witnessroots.cpp b/src/gtest/test_wallet_witnessroots.cpp new file mode 100644 index 000000000..bb641ccf4 --- /dev/null +++ b/src/gtest/test_wallet_witnessroots.cpp @@ -0,0 +1,354 @@ +// 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 + +#include +#include +#include + +#include "chain.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 "wallet/wallet.h" +#include "zcash/zip32.h" + +extern std::atomic 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 blocks; + std::deque index; + CBlockIndex* savedTip; + CCoinsView coinsBase; + CCoinsViewCache coins{&coinsBase}; + CCoinsViewCache* savedCoinsTip; + + RootsChain(int nBlocks, const std::vector& inBlock1, const std::map& 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::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> raw(32, 0x5a); + HDSeed seed(raw); + return libzcash::SaplingExtendedSpendingKey::Master(seed); +} + +std::vector Txs(int n) +{ + std::vector 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 Witnesses(int nNotes, int salt, uint256& rootOut) +{ + SaplingMerkleTree tree; + std::vector 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; +} + +enum Kind { VALID_BELOW_TIP, VALID_AT_TIP, AHEAD_OF_CHAIN, ALREADY_VALIDATED, WRONG_ROOT, NOT_IN_CHAIN }; + +struct Fixture { + std::vector txs; + std::map roots; + std::vector wBelow, wAt; + int nTxs; +}; + +// Fills the wallet: tx i gets notes of the kinds kinds(i) returns, in output order. +template +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 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; + } + 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); + } + } +} + +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 States(RootsWallet& wallet) +{ + LOCK(wallet.cs_wallet); + std::map 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(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; + savedThreads = mapArgs.count("-witnessbuildthreads") ? mapArgs["-witnessbuildthreads"] : ""; + } + void TearDown() override { + fRequestShutdown = false; + if (savedThreads.empty()) + mapArgs.erase("-witnessbuildthreads"); + else + mapArgs["-witnessbuildthreads"] = savedThreads; + } +}; + +std::vector 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 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 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 kindOf; + for (int i = 0; i < fx.nTxs; i++) { + std::vector 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 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 ks = MixedKinds(i); + if (i == 17) + ks.push_back(WRONG_ROOT); + return ks; + }; + std::map 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 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{NOT_IN_CHAIN, NOT_IN_CHAIN} : std::vector{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); +} diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp index 08a9d3ffc..1f2c55930 100644 --- a/src/wallet/wallet.cpp +++ b/src/wallet/wallet.cpp @@ -48,6 +48,8 @@ #include #include #include +#include +#include #include "zcash/zip32.h" #include "cc/CCinclude.h" #include @@ -1345,6 +1347,39 @@ int CWallet::SaplingWitnessMinimumHeight(const boost::optional& nullifi return nMinimumHeight; } +// Threads for witness work spread over notes: -witnessbuildthreads, else one per core, and never +// more than there are notes. +static int WitnessThreadCount(size_t nJobs) +{ + int nPar = (int)GetArg("-witnessbuildthreads", 0); + if (nPar <= 0) nPar = (int)std::thread::hardware_concurrency(); + if (nPar <= 0) nPar = 1; + if (nPar > (int)nJobs) nPar = (int)nJobs; + if (nPar < 1) nPar = 1; + return nPar; +} + +// Runs shard(0) .. shard(nPar-1), each exactly once, on up to nPar threads; shard must not throw. +// If the OS refuses a thread (task limit, memory), the remaining shards run here instead of letting +// the exception unwind past joinable threads (std::terminate). The result is unchanged either way. +static void RunWitnessShards(int nPar, const std::function& shard, const char* caller) +{ + if (nPar <= 1) { + shard(0); + return; + } + std::vector threads; + threads.reserve(nPar); + int t = 0; + try { + for (; t < nPar; t++) threads.emplace_back(shard, t); + } catch (const std::system_error& e) { + LogPrintf("%s: could only start %d of %d witness threads (%s); running the rest inline\n", caller, t, nPar, e.what()); + } + for (int u = t; u < nPar; u++) shard(u); + for (std::thread& th : threads) th.join(); +} + int CWallet::VerifyAndSetInitialWitness(const CBlockIndex* pindex, bool witnessOnly) { LOCK2(cs_main, cs_wallet); @@ -1353,6 +1388,64 @@ int CWallet::VerifyAndSetInitialWitness(const CBlockIndex* pindex, bool witnessO int nWitnessTotalTxCount = mapWallet.size(); int nMinimumHeight = pindex->GetHeight(); + // root() walks a witness's whole depth-32 path, ~1.7-2.4ms, and after a restart every note needs + // one: ~30s for a 16k-note wallet, with cs_main and cs_wallet held. So compute those roots first, + // spread over threads the way BuildWitnessCache's Phase 2 spreads the extension, and then run the + // loop below unchanged, taking each root from here instead of computing it. That loop changes a + // note's witnesses only at that note's own turn (a sibling's reseed rewrites nullifiers, never + // witnesses), so each root is the root of the witness the loop checks, and the validated/reseeded + // decisions, their order and nMinimumHeight are exactly the serial ones. The selection mirrors the + // loop's conditions for reaching root(); a note it misses (one that only gains a nullifier from a + // sibling's reseed) has its root computed inline, as does one whose root() threw here, so a throw + // surfaces exactly where it used to. + std::vector rootNotes; + for (const std::pair& wtxItem : mapWallet) { + if (wtxItem.second.mapSaplingNoteData.empty() || wtxItem.second.GetDepthInMainChain() <= 0) + continue; + for (const mapSaplingNoteData_t::value_type& item : wtxItem.second.mapSaplingNoteData) { + const SaplingNoteData* nd = &(item.second); + if (nd->nullifier && !nd->witnesses.empty() && nd->witnessHeight > 0 && !nd->witnessRootValidated && + chainActive[nd->witnessHeight] != NULL && HaveSaplingFullViewingKey(nd->ivk)) + rootNotes.push_back(nd); + } + } + std::vector roots(rootNotes.size()); + std::unordered_map rootIndex; + if (!rootNotes.empty()) { + std::vector haveRoot(rootNotes.size(), 0); + // Starting the threads costs about as much as a root, so a handful stay on this thread. + const int nPar = rootNotes.size() >= 8 ? WitnessThreadCount(rootNotes.size()) : 1; + int64_t r0 = GetTimeMicros(); + RunWitnessShards(nPar, [&](int tid) { + // Workers read only their own notes' witnesses; this thread holds the locks and waits. + for (size_t k = (size_t)tid; k < rootNotes.size(); k += (size_t)nPar) { + if (ShutdownRequested()) + return; + try { + roots[k] = rootNotes[k]->witnesses.front().root(); + haveRoot[k] = 1; + } catch (...) { + } + } + }, __func__); + // Nothing has been changed yet, so stopping here is as if this pass never ran: the next block or + // the next start redoes it. Without this a stop waited for the whole pass. + if (ShutdownRequested()) { + LogPrintf("%s: shutdown requested, skipping the witness check at height %d\n", __func__, pindex->GetHeight()); + return pindex->GetHeight(); + } + for (size_t k = 0; k < rootNotes.size(); k++) + if (haveRoot[k]) + rootIndex[rootNotes[k]] = k; + if (fZdebug) + LogPrintf("%s: %u witness root(s) computed in %ldms using %d thread(s)\n", __func__, + (unsigned)rootNotes.size(), (long)((GetTimeMicros() - r0) / 1000), nPar); + } + auto cachedRoot = [&](const SaplingNoteData* nd) { + std::unordered_map::const_iterator it = rootIndex.find(nd); + return it != rootIndex.end() ? roots[it->second] : nd->witnesses.front().root(); + }; + for (std::pair& wtxItem : mapWallet) { nWitnessTxIncrement += 1; @@ -1405,7 +1498,7 @@ int CWallet::VerifyAndSetInitialWitness(const CBlockIndex* pindex, bool witnessO nMinimumHeight = SaplingWitnessMinimumHeight(item.second.nullifier, nd->witnessHeight, nMinimumHeight); continue; } - if (nd->witnesses.front().root() == whIndex->hashFinalSaplingRoot) { + if (cachedRoot(nd) == whIndex->hashFinalSaplingRoot) { nd->witnessRootValidated = true; nMinimumHeight = SaplingWitnessMinimumHeight(item.second.nullifier, nd->witnessHeight, nMinimumHeight); continue; @@ -1414,7 +1507,7 @@ int CWallet::VerifyAndSetInitialWitness(const CBlockIndex* pindex, bool witnessO } //Validate the witness at the witness height - witnessRoot = nd->witnesses.front().root(); + witnessRoot = cachedRoot(nd); pblockindex = chainActive[nd->witnessHeight]; blockRoot = pblockindex->hashFinalSaplingRoot; if (witnessRoot == blockRoot) { @@ -1604,12 +1697,7 @@ void CWallet::BuildWitnessCache(const CBlockIndex* pindex, bool witnessOnly) nCms += cms.size(); const bool fParallel = bulkRebuild || (uint64_t)work.size() * nCms >= 2000; - int nPar = (int)GetArg("-witnessbuildthreads", 0); - if (nPar <= 0) nPar = (int)std::thread::hardware_concurrency(); - if (nPar <= 0) nPar = 1; - if (nPar > (int)work.size()) nPar = (int)work.size(); - if (nPar < 1) nPar = 1; - if (!fParallel) nPar = 1; + const int nPar = fParallel ? WitnessThreadCount(work.size()) : 1; std::atomic failed(false); std::mutex failMtx; @@ -1694,23 +1782,7 @@ void CWallet::BuildWitnessCache(const CBlockIndex* pindex, bool witnessOnly) }; int64_t e0 = GetTimeMicros(); - if (nPar <= 1) { - worker(0); - } else { - // If the OS refuses a thread (task limit, memory), run the remaining shards here instead of - // letting the exception unwind past joinable threads (std::terminate). Each shard still runs - // exactly once, so the result is unchanged. - std::vector threads; - threads.reserve(nPar); - int t = 0; - try { - for (; t < nPar; t++) threads.emplace_back(worker, t); - } catch (const std::system_error& e) { - LogPrintf("%s: could only start %d of %d witness threads (%s); running the rest inline\n", __func__, t, nPar, e.what()); - } - for (int u = t; u < nPar; u++) worker(u); - for (std::thread& th : threads) th.join(); - } + RunWitnessShards(nPar, worker, __func__); int64_t tExtend = GetTimeMicros() - e0; if (failed) From b4513498e5403bd4a4b47a0b734dcad9fc3d537a Mon Sep 17 00:00:00 2001 From: DanS Date: Wed, 28 Oct 2026 10:48:35 -0500 Subject: [PATCH 09/33] 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 " of " reads like progress although is the tx's place in mapWallet and is mapWallet.size(): transactions, not notes. Append "[reseed ]", the running count of reseeded notes, to the reseed line. Its prefix, the comma after the hash and " of " 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 --- src/wallet/wallet.cpp | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp index 1f2c55930..8994e217f 100644 --- a/src/wallet/wallet.cpp +++ b/src/wallet/wallet.cpp @@ -1387,6 +1387,9 @@ int CWallet::VerifyAndSetInitialWitness(const CBlockIndex* pindex, bool witnessO int nWitnessTxIncrement = 0; int nWitnessTotalTxCount = mapWallet.size(); int nMinimumHeight = pindex->GetHeight(); + // For the end-of-pass summary only; no decision reads them. + const int64_t nPassStart = GetTimeMicros(); + int nNotesValidated = 0, nNotesReseeded = 0, nNotesKnownGood = 0, nNotesAhead = 0; // root() walks a witness's whole depth-32 path, ~1.7-2.4ms, and after a restart every note needs // one: ~30s for a 16k-note wallet, with cs_main and cs_wallet held. So compute those roots first, @@ -1478,11 +1481,14 @@ int CWallet::VerifyAndSetInitialWitness(const CBlockIndex* pindex, bool witnessO if (!nd->witnesses.empty() && nd->witnessHeight > 0) { //Skip all functions for validated witness while witness only = true - if (nd->witnessRootValidated && witnessOnly) + if (nd->witnessRootValidated && witnessOnly) { + nNotesKnownGood++; continue; + } //Skip Validation when witness root has been validated if (nd->witnessRootValidated) { + nNotesKnownGood++; nMinimumHeight = SaplingWitnessMinimumHeight(item.second.nullifier, nd->witnessHeight, nMinimumHeight); continue; } @@ -1495,11 +1501,13 @@ int CWallet::VerifyAndSetInitialWitness(const CBlockIndex* pindex, bool witnessO CBlockIndex* whIndex = chainActive[nd->witnessHeight]; if (whIndex == NULL) { //witnessHeight strictly above the active chain (transient catch-up): cannot validate yet + nNotesAhead++; nMinimumHeight = SaplingWitnessMinimumHeight(item.second.nullifier, nd->witnessHeight, nMinimumHeight); continue; } if (cachedRoot(nd) == whIndex->hashFinalSaplingRoot) { nd->witnessRootValidated = true; + nNotesValidated++; nMinimumHeight = SaplingWitnessMinimumHeight(item.second.nullifier, nd->witnessHeight, nMinimumHeight); continue; } @@ -1512,6 +1520,7 @@ int CWallet::VerifyAndSetInitialWitness(const CBlockIndex* pindex, bool witnessO blockRoot = pblockindex->hashFinalSaplingRoot; if (witnessRoot == blockRoot) { nd->witnessRootValidated = true; + nNotesValidated++; nMinimumHeight = SaplingWitnessMinimumHeight(item.second.nullifier, nd->witnessHeight, nMinimumHeight); continue; } @@ -1521,8 +1530,11 @@ int CWallet::VerifyAndSetInitialWitness(const CBlockIndex* pindex, bool witnessO pblockindex = chainActive[wtxHeight]; ::ClearSingleNoteWitnessCache(nd); nWitnessGeneration++; + nNotesReseeded++; - LogPrintf("%s: Setting Initial Sapling Witness for tx %s, %i of %i\n", __func__, wtxHash.ToString(), nWitnessTxIncrement, nWitnessTotalTxCount); + //The GUI parses this line (the hash between "for tx " and the comma, and the count after " of "): + //keep that part as it is and only append. of is the tx's place in mapWallet, not a note count. + LogPrintf("%s: Setting Initial Sapling Witness for tx %s, %i of %i [reseed %d]\n", __func__, wtxHash.ToString(), nWitnessTxIncrement, nWitnessTotalTxCount, nNotesReseeded); SaplingMerkleTree saplingTree; blockRoot = pblockindex->pprev->hashFinalSaplingRoot; @@ -1570,6 +1582,10 @@ int CWallet::VerifyAndSetInitialWitness(const CBlockIndex* pindex, bool witnessO } } + if (nNotesValidated > 0 || nNotesReseeded > 0) + LogPrintf("%s: block %d: %d note witness(es) validated, %d reseeded, %d already valid, %d ahead of the chain; " + "lowest witness height %d; %ldms\n", __func__, pindex->GetHeight(), nNotesValidated, nNotesReseeded, + nNotesKnownGood, nNotesAhead, nMinimumHeight, (long)((GetTimeMicros() - nPassStart) / 1000)); if(fZdebug) LogPrintf("%s: nMinimumHeight=%d\n",__func__, nMinimumHeight); return nMinimumHeight; From e5791fea714614b1bbae5a4633f560c99820d3b4 Mon Sep 17 00:00:00 2001 From: DanS Date: Wed, 28 Oct 2026 10:49:38 -0500 Subject: [PATCH 10/33] 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 --- src/gtest/test_wallet_consolidation.cpp | 42 ++++++ src/rpc/client.cpp | 1 + ...asyncrpcoperation_saplingconsolidation.cpp | 15 +++ .../asyncrpcoperation_saplingconsolidation.h | 1 + src/wallet/rpcwallet.cpp | 122 +++++++++++++++++- src/wallet/wallet.cpp | 10 ++ src/wallet/wallet.h | 40 +++++- 7 files changed, 226 insertions(+), 5 deletions(-) diff --git a/src/gtest/test_wallet_consolidation.cpp b/src/gtest/test_wallet_consolidation.cpp index 59c8eb8f7..fdd8eaa45 100644 --- a/src/gtest/test_wallet_consolidation.cpp +++ b/src/gtest/test_wallet_consolidation.cpp @@ -11,6 +11,7 @@ #include "primitives/transaction.h" #include "random.h" #include "wallet/asyncrpcoperation_saplingconsolidation.h" +#include "wallet/wallet.h" namespace { @@ -188,3 +189,44 @@ TEST(SaplingConsolidationPlan, RandomCountsStayInRange) { } 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); +} diff --git a/src/rpc/client.cpp b/src/rpc/client.cpp index 3daf6738e..14a8db459 100644 --- a/src/rpc/client.cpp +++ b/src/rpc/client.cpp @@ -151,6 +151,7 @@ static const CRPCConvertParam vRPCConvertParams[] = { "z_shieldcoinbase", 2}, { "z_shieldcoinbase", 3}, { "z_getoperationstatus", 0}, + { "z_consolidationstatus", 0}, { "z_getoperationresult", 0}, { "notaries", 2 }, { "minerids", 1 }, diff --git a/src/wallet/asyncrpcoperation_saplingconsolidation.cpp b/src/wallet/asyncrpcoperation_saplingconsolidation.cpp index 835d49c28..135e29fbd 100644 --- a/src/wallet/asyncrpcoperation_saplingconsolidation.cpp +++ b/src/wallet/asyncrpcoperation_saplingconsolidation.cpp @@ -150,6 +150,20 @@ void AsyncRPCOperation_saplingconsolidation::main() { int tipHeight = (chainActive.Tip() != NULL) ? chainActive.Tip()->GetHeight() : targetHeight_; pwalletMain->nextConsolidation = pwalletMain->consolidationInterval + tipHeight; pwalletMain->fConsolidationRunning = false; + + SaplingConsolidationRound round; + round.height = tipHeight; + 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.error = tally_.error; + if (!success && round.error.empty()) + round.error = getErrorMessage(); + pwalletMain->consolidationStats.Record(round); } } } @@ -412,6 +426,7 @@ bool AsyncRPCOperation_saplingconsolidation::main_impl() { } void AsyncRPCOperation_saplingconsolidation::setConsolidationResult(const ConsolidationTally& tally) { + tally_ = tally; UniValue res(UniValue::VOBJ); res.push_back(Pair("num_tx_created", (int)tally.txids.size())); res.push_back(Pair("amount_consolidated", FormatMoney(tally.amountConsolidated))); diff --git a/src/wallet/asyncrpcoperation_saplingconsolidation.h b/src/wallet/asyncrpcoperation_saplingconsolidation.h index ac6a0e26f..71eb6245d 100644 --- a/src/wallet/asyncrpcoperation_saplingconsolidation.h +++ b/src/wallet/asyncrpcoperation_saplingconsolidation.h @@ -98,6 +98,7 @@ private: bool main_impl(); std::vector z_sapling_inputs_; // the notes this round locked + ConsolidationTally tally_; // what the round did, for z_consolidationstatus void setConsolidationResult(const ConsolidationTally& tally); diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index 893c5ce56..e214be8ab 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -3269,32 +3269,146 @@ UniValue getalldata(const UniValue& params, bool fHelp,const CPubKey&) 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) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; - if (fHelp || params.size() > 0) + if (fHelp || params.size() > 1) throw runtime_error( - "z_consolidationstatus\n" - "\nGive details about consolidation operations since the node was started." + "z_consolidationstatus ( verbose )\n" + "\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" + " \"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" + " \"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" "}\n" "\nExamples:\n" + HelpExampleCli("z_consolidationstatus", "") + + HelpExampleCli("z_consolidationstatus", "true") + HelpExampleRpc("z_consolidationstatus", "") ); + bool fVerbose = params.size() > 0 && !params[0].isNull() && params[0].get_bool(); + LOCK2(cs_main, pwalletMain->cs_wallet); + const SaplingConsolidationStats& stats = pwalletMain->consolidationStats; UniValue ret(UniValue::VOBJ); ret.push_back(Pair("consolidation", pwalletMain->fSaplingConsolidationEnabled)); 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("consolidationinterval", pwalletMain->consolidationInterval)); ret.push_back(Pair("consolidationaddress", pwalletMain->consolidationAddress)); 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)); + 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("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 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)); + } return ret; } diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp index 48019e411..1f2cac79d 100644 --- a/src/wallet/wallet.cpp +++ b/src/wallet/wallet.cpp @@ -759,6 +759,16 @@ void CWallet::RunSaplingConsolidation(int blockHeight) { } } +std::map CWallet::CountConsolidationEligibleNotes() { + LOCK2(cs_main, cs_wallet); + std::vector entries; + GetFilteredNotes(entries, "", CONSOLIDATION_MIN_DEPTH); + std::map counts; + for (const SaplingNoteEntry& entry : entries) + counts[entry.address]++; + return counts; +} + // Periodically drain matured transparent coinbase into a wallet-owned Sapling // z-address. Default-ON but conditional: this is enqueue-only (all gathering // happens on the async worker thread inside the op, which is why we must not diff --git a/src/wallet/wallet.h b/src/wallet/wallet.h index 7a2e1b707..5e2e7e995 100644 --- a/src/wallet/wallet.h +++ b/src/wallet/wallet.h @@ -400,6 +400,40 @@ struct SaplingNoteEntry int confirmations; }; +/** What one Sapling consolidation round did (z_consolidationstatus "last_round"). */ +struct SaplingConsolidationRound +{ + int height = 0; //!< chain tip when the round finished + int64_t time = 0; + std::vector 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 + 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. */ @@ -893,7 +927,8 @@ public: // current one before mutating scheduler state. AsyncRPCOperationId saplingSweepOperationId; int amountSwept = 0; - int amountConsolidated = 0; + // What consolidation rounds have done since startup. Guarded by cs_wallet. + SaplingConsolidationStats consolidationStats; int sweepInterval = 10; int consolidationInterval = DEFAULT_CONSOLIDATION_INTERVAL; int consolidationThreshold = DEFAULT_CONSOLIDATION_THRESHOLD; @@ -1338,6 +1373,9 @@ public: const CBlock *pblock, boost::optional> added); 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 CountConsolidationEligibleNotes(); void RunAutoShieldCoinbase(int blockHeight); bool CommitAutomatedTx(const CTransaction& tx); /** Saves witness caches and best block locator to disk. Overrides CValidationInterface. */ From 52b747f6d3dd61149286e750c3ff656ff1dd1572 Mon Sep 17 00:00:00 2001 From: DanS Date: Wed, 28 Oct 2026 11:09:20 -0500 Subject: [PATCH 11/33] 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 --- src/rpc/client.cpp | 4 + src/rpc/server.h | 1 + ...asyncrpcoperation_saplingconsolidation.cpp | 6 +- .../asyncrpcoperation_saplingconsolidation.h | 1 + src/wallet/rpcwallet.cpp | 105 ++++++++++++++++++ src/wallet/wallet.cpp | 7 +- src/wallet/wallet.h | 3 + 7 files changed, 124 insertions(+), 3 deletions(-) diff --git a/src/rpc/client.cpp b/src/rpc/client.cpp index 14a8db459..90013a070 100644 --- a/src/rpc/client.cpp +++ b/src/rpc/client.cpp @@ -152,6 +152,10 @@ static const CRPCConvertParam vRPCConvertParams[] = { "z_shieldcoinbase", 3}, { "z_getoperationstatus", 0}, { "z_consolidationstatus", 0}, + { "z_consolidate", 0}, + { "z_consolidate", 1}, + { "z_consolidate", 2}, + { "z_consolidate", 3}, { "z_getoperationresult", 0}, { "notaries", 2 }, { "minerids", 1 }, diff --git a/src/rpc/server.h b/src/rpc/server.h index a2d5c17cc..1ceeaff99 100644 --- a/src/rpc/server.h +++ b/src/rpc/server.h @@ -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_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_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_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 diff --git a/src/wallet/asyncrpcoperation_saplingconsolidation.cpp b/src/wallet/asyncrpcoperation_saplingconsolidation.cpp index 135e29fbd..1ef89f9ce 100644 --- a/src/wallet/asyncrpcoperation_saplingconsolidation.cpp +++ b/src/wallet/asyncrpcoperation_saplingconsolidation.cpp @@ -153,6 +153,7 @@ void AsyncRPCOperation_saplingconsolidation::main() { SaplingConsolidationRound round; round.height = tipHeight; + round.manual = request_.manual; round.time = GetTime(); round.txids = tally_.txids; round.notesMerged = tally_.notesMerged; @@ -175,7 +176,9 @@ static std::set setWitnessSkipLogged; bool AsyncRPCOperation_saplingconsolidation::main_impl() { bool status=true; 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(); int tipHeight; { @@ -460,6 +463,7 @@ UniValue AsyncRPCOperation_saplingconsolidation::getStatus() const { UniValue obj = v.get_obj(); obj.push_back(Pair("method", "saplingconsolidation")); obj.push_back(Pair("target_height", targetHeight_)); + obj.push_back(Pair("manual", request_.manual)); return obj; } diff --git a/src/wallet/asyncrpcoperation_saplingconsolidation.h b/src/wallet/asyncrpcoperation_saplingconsolidation.h index 71eb6245d..8a5fc72b2 100644 --- a/src/wallet/asyncrpcoperation_saplingconsolidation.h +++ b/src/wallet/asyncrpcoperation_saplingconsolidation.h @@ -56,6 +56,7 @@ std::vector PlanSaplingConsolidation( // 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 addresses; // empty: every address the wallet can spend diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index e214be8ab..1a254d597 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -42,6 +42,7 @@ #include "wallet/asyncrpcoperation_mergetoaddress.h" #include "wallet/asyncrpcoperation_sendmany.h" #include "wallet/asyncrpcoperation_shieldcoinbase.h" +#include "wallet/asyncrpcoperation_saplingconsolidation.h" #include "consensus/upgrades.h" #include "sodium.h" #include @@ -3325,6 +3326,7 @@ UniValue z_consolidationstatus(const UniValue& params, bool fHelp, const CPubKey " \"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" @@ -3373,6 +3375,7 @@ UniValue z_consolidationstatus(const UniValue& params, bool fHelp, const CPubKey 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); @@ -3413,6 +3416,107 @@ UniValue z_consolidationstatus(const UniValue& params, bool fHelp, const CPubKey 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" + "\nResult:\n" + "\"operationid\" (string) An operationid to pass to z_getoperationstatus to get the result.\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(&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); + request.addresses.push_back(boost::get(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 q = getAsyncRPCQueue(); + std::shared_ptr lastOperation = q->getOperationForId(pwalletMain->saplingConsolidationOperationId); + if (lastOperation != nullptr) { + lastOperation->cancel(); + if (!pwalletMain->saplingConsolidationOpManual) + q->popOperationForId(pwalletMain->saplingConsolidationOperationId); + } + std::shared_ptr 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) { @@ -6569,6 +6673,7 @@ static const CRPCCommand commands[] = { "wallet", "z_sweepstatus", &z_sweepstatus, true }, { "wallet", "z_autoshieldstatus", &z_autoshieldstatus, true }, { "wallet", "z_consolidationstatus", &z_consolidationstatus, true }, + { "wallet", "z_consolidate", &z_consolidate, true }, { "wallet", "z_sendmany", &z_sendmany, false }, { "wallet", "z_shieldcoinbase", &z_shieldcoinbase, false }, { "wallet", "z_getoperationstatus", &z_getoperationstatus, true }, diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp index 1f2cac79d..c3b52c7f3 100644 --- a/src/wallet/wallet.cpp +++ b/src/wallet/wallet.cpp @@ -738,8 +738,10 @@ void CWallet::RunSaplingConsolidation(int blockHeight) { lastOperation->cancel(); // Drop it from the queue's map as well. Nothing else ever removes these: // popOperationForId is only reached from z_getoperationresult, so on a node - // running this every interval the map grew without bound. - q->popOperationForId(saplingConsolidationOperationId); + // running this every interval the map grew without bound. A z_consolidate + // round is the user's: its result stays until z_getoperationresult takes it. + if (!saplingConsolidationOpManual) + q->popOperationForId(saplingConsolidationOperationId); } pendingSaplingConsolidationTxs.clear(); SaplingConsolidationRequest request; @@ -750,6 +752,7 @@ void CWallet::RunSaplingConsolidation(int blockHeight) { request.addresses = consolidationAddresses; std::shared_ptr operation(new AsyncRPCOperation_saplingconsolidation(blockHeight + AUTO_OP_TARGET_HEIGHT_OFFSET, request)); saplingConsolidationOperationId = operation->getId(); + saplingConsolidationOpManual = false; if (!q->addOperation(operation)) { // Queue is closing (shutdown). Release the flag we just set, or it stays // set with no operation in flight and blocks every later round. diff --git a/src/wallet/wallet.h b/src/wallet/wallet.h index 5e2e7e995..183d49972 100644 --- a/src/wallet/wallet.h +++ b/src/wallet/wallet.h @@ -404,6 +404,7 @@ struct SaplingNoteEntry struct SaplingConsolidationRound { int height = 0; //!< chain tip when the round finished + bool manual = false; //!< run by z_consolidate int64_t time = 0; std::vector txids; int notesMerged = 0; @@ -889,6 +890,8 @@ public: // Id of the in-flight consolidation op; read by the op to confirm it is // still the current one before mutating scheduler state. 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 fConsolidationRunning = false; From ead339418884b9f63751982f496979a43d0a3b71 Mon Sep 17 00:00:00 2001 From: DanS Date: Wed, 28 Oct 2026 11:21:06 -0500 Subject: [PATCH 12/33] 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 --- src/init.cpp | 4 ++++ src/wallet/rpcwallet.cpp | 22 ++++++++++++++++++++-- src/wallet/wallet.cpp | 28 ++++++++++++++++++++++++++++ src/wallet/wallet.h | 10 ++++++++++ 4 files changed, 62 insertions(+), 2 deletions(-) diff --git a/src/init.cpp b/src/init.cpp index d7c574bf6..1e80eb76a 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -2771,6 +2771,10 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler) 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)); diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index 1a254d597..72a56282e 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -3339,7 +3339,10 @@ UniValue z_consolidationstatus(const UniValue& params, bool fHelp, const CPubKey " \"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" + " \"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" "\nExamples:\n" + HelpExampleCli("z_consolidationstatus", "") @@ -3411,6 +3414,9 @@ UniValue z_consolidationstatus(const UniValue& params, bool fHelp, const CPubKey } 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; @@ -3576,7 +3582,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_desc\" : \"...\", (string) readable form of hdseedorigin\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" "\nExamples:\n" + HelpExampleCli("z_autoshieldstatus", "") @@ -3628,6 +3636,16 @@ UniValue z_autoshieldstatus(const UniValue& params, bool fHelp, const CPubKey& m } 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; } diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp index c3b52c7f3..d13fe8492 100644 --- a/src/wallet/wallet.cpp +++ b/src/wallet/wallet.cpp @@ -772,6 +772,34 @@ std::map CWallet::CountConsolidationEligib return counts; } +void CWallet::SetConsolidationSuggestion(int overThreshold) { + LOCK2(cs_main, cs_wallet); + if (fSaplingConsolidationEnabled) + overThreshold = 0; + consolidationSuggestCount = overThreshold; + consolidationSuggestHeight = chainActive.Height(); + if (overThreshold > 0 && !fConsolidationSuggestLogged) { + fConsolidationSuggestLogged = true; + LogPrintf("%d %s more than %d spendable notes; consider -consolidation=1 or z_consolidate\n", + overThreshold, overThreshold == 1 ? "address has" : "addresses have", consolidationThreshold); + } +} + +void CWallet::RefreshConsolidationSuggestion() { + LOCK2(cs_main, cs_wallet); + if (fSaplingConsolidationEnabled) { + SetConsolidationSuggestion(0); + return; + } + std::set included(consolidationAddresses.begin(), consolidationAddresses.end()); + int over = 0; + for (const auto& p : CountConsolidationEligibleNotes()) { + if ((included.empty() || included.count(p.first)) && p.second > consolidationThreshold) + over++; + } + SetConsolidationSuggestion(over); +} + // Periodically drain matured transparent coinbase into a wallet-owned Sapling // z-address. Default-ON but conditional: this is enqueue-only (all gathering // happens on the async worker thread inside the op, which is why we must not diff --git a/src/wallet/wallet.h b/src/wallet/wallet.h index 183d49972..64c6d61eb 100644 --- a/src/wallet/wallet.h +++ b/src/wallet/wallet.h @@ -932,6 +932,11 @@ public: int amountSwept = 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 consolidationInterval = DEFAULT_CONSOLIDATION_INTERVAL; int consolidationThreshold = DEFAULT_CONSOLIDATION_THRESHOLD; @@ -1379,6 +1384,11 @@ public: /** 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 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); bool CommitAutomatedTx(const CTransaction& tx); /** Saves witness caches and best block locator to disk. Overrides CValidationInterface. */ From 7983a3dc68e4c1134d400d1438a7d9574e79e81c Mon Sep 17 00:00:00 2001 From: DanS Date: Wed, 28 Oct 2026 11:22:58 -0500 Subject: [PATCH 13/33] 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 --- doc/zsweep-consolidation.md | 65 +++++++++++++++++++++++++++++++++---- src/init.cpp | 2 +- 2 files changed, 59 insertions(+), 8 deletions(-) diff --git a/doc/zsweep-consolidation.md b/doc/zsweep-consolidation.md index ded919365..b99c9cd47 100644 --- a/doc/zsweep-consolidation.md +++ b/doc/zsweep-consolidation.md @@ -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**. -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. @@ -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 | |-------------------|-------------------------| | 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. | | 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 | @@ -41,7 +41,31 @@ Zsweep is when you sweep numerous zutxos into one z-address that you configure. ## 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. A note with a missing or unusable witness is skipped (and logged once); the round goes on without it. +* With the defaults, an address over the threshold loses 27 to 42 notes per round, and a round runs every 25 blocks. + +### Turning it on + +1. Add the following to the conf file as per the Pre-Step. ``` consolidation=1 ``` @@ -50,10 +74,34 @@ Zsweep is when you sweep numerous zutxos into one z-address that you configure. | 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. | - | 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. | + | consolidationinterval=25 | Blocks between rounds (default 25, minimum 5; smaller values are raised to 5). | + | 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. The wallet must hold the address's spending key, or dragonxd refuses to start. | -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..."]'`. 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 @@ -66,6 +114,10 @@ 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. With zsweep on, consolidation only works on the sweep address (a `consolidatesaplingaddress` other than the + sweep address is refused at startup). 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 The DragonX Developers, jahway603, and The Hush Developers @@ -73,4 +125,3 @@ The DragonX Developers, jahway603, and The Hush Developers ### License GPLv3 - diff --git a/src/init.cpp b/src/init.cpp index 1e80eb76a..60af3bce8 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -490,7 +490,7 @@ std::string HelpMessage(HelpMessageMode mode) strUsage += HelpMessageOpt("-zsweep", _("Enable zaddr sweeping, automatically move all shielded funds to a one address once per X blocks")); strUsage += HelpMessageOpt("-zsweepaddress=", _("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("-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)); // 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 From 63e7d6ef2d6550cc512b7c11166fc4ca3550ce6d Mon Sep 17 00:00:00 2001 From: DanS Date: Wed, 28 Oct 2026 11:36:59 -0500 Subject: [PATCH 14/33] 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 --- src/wallet/asyncrpcoperation_saplingconsolidation.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/wallet/asyncrpcoperation_saplingconsolidation.cpp b/src/wallet/asyncrpcoperation_saplingconsolidation.cpp index 1ef89f9ce..82a81e7f0 100644 --- a/src/wallet/asyncrpcoperation_saplingconsolidation.cpp +++ b/src/wallet/asyncrpcoperation_saplingconsolidation.cpp @@ -212,7 +212,8 @@ bool AsyncRPCOperation_saplingconsolidation::main_impl() { }; std::vector groups; std::vector txs; - ConsolidationTally tally; + // The member, not a local: if anything below throws, main() still records what was committed. + ConsolidationTally& tally = tally_; { LOCK2(cs_main, pwalletMain->cs_wallet); // We set minDepth to 11 to avoid unconfirmed notes and in anticipation of specifying @@ -429,7 +430,8 @@ bool AsyncRPCOperation_saplingconsolidation::main_impl() { } void AsyncRPCOperation_saplingconsolidation::setConsolidationResult(const ConsolidationTally& tally) { - tally_ = tally; + if (&tally != &tally_) + tally_ = tally; UniValue res(UniValue::VOBJ); res.push_back(Pair("num_tx_created", (int)tally.txids.size())); res.push_back(Pair("amount_consolidated", FormatMoney(tally.amountConsolidated))); From 8f70f494b3bd4a380badcb096c3f57e0c5e90218 Mon Sep 17 00:00:00 2001 From: DanS Date: Wed, 28 Oct 2026 12:10:21 -0500 Subject: [PATCH 15/33] 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 --- src/init.cpp | 87 ++++++++++++++++++++++++++++++---------------------- 1 file changed, 51 insertions(+), 36 deletions(-) diff --git a/src/init.cpp b/src/init.cpp index aa23fbbe9..5b4d5cae1 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -131,67 +131,82 @@ static const size_t NOTARIZATION_DB_CACHE_BYTES = 100 * 1024 * 1024; // 100 MiB static const int NOTARIZATION_LOCK_WAIT_SECONDS = 30; /** - * Is /LOCK held, by another process or by another open DB in this one? Probed with LevelDB's - * own Env::LockFile, i.e. the same lock DB::Open takes. A missing LOCK file cannot be held. Any other - * failure to take the lock counts as held: the caller then never moves or wipes the directory. + * Try to take /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 bool LevelDBLockHeld(const boost::filesystem::path& dbdir) +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 false; + return leveldb::Status::OK(); leveldb::Env* env = leveldb::Env::Default(); leveldb::FileLock* lock = NULL; - if (!env->LockFile(lockpath.string(), &lock).ok()) - return true; - env->UnlockFile(lock); - return false; + leveldb::Status status = env->LockFile(lockpath.string(), &lock); + if (status.ok()) + env->UnlockFile(lock); + return status; } /** * 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 held (typically a previous dragonxd that is still exiting): wait up to + * - 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. 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; - try { - return new NotarizationDB(NOTARIZATION_DB_CACHE_BYTES, false, fWipe); - } catch (const std::exception& e) { - strError = e.what(); - } - - if (LevelDBLockHeld(ndir)) { - LogPrintf("%s: notarizations DB failed to open (%s): notarizations/LOCK is held by another process; waiting for a previous dragonxd to release notarizations/LOCK (up to %d s)\n", - __func__, strError, NOTARIZATION_LOCK_WAIT_SECONDS); - int nWaited = 0; - while (nWaited < NOTARIZATION_LOCK_WAIT_SECONDS && !ShutdownRequested() && LevelDBLockHeld(ndir)) { - MilliSleep(1000); - nWaited++; - } - if (!LevelDBLockHeld(ndir)) { - try { - NotarizationDB* pdb = new NotarizationDB(NOTARIZATION_DB_CACHE_BYTES, false, fWipe); + 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 + int nWaited = 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__, nWaited); - return pdb; - } catch (const std::exception& e) { - strError = e.what(); + 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; + while (nWaited < NOTARIZATION_LOCK_WAIT_SECONDS && !ShutdownRequested()) { + MilliSleep(1000); + nWaited++; + 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__, nWaited, lockStatus.ToString()); + return new NotarizationDB(NOTARIZATION_DB_CACHE_BYTES, true, false); } } - if (LevelDBLockHeld(ndir)) { - LogPrintf("%s: notarizations/LOCK still held after %d s; using an in-memory notarizations DB for this run (on-disk notarizations DB left untouched)\n", - __func__, nWaited); - return new NotarizationDB(NOTARIZATION_DB_CACHE_BYTES, true, false); - } - // The lock is free but the DB still does not open: treat it as corrupt. + // The lock is free now: open once more before calling the DB corrupt. + fProbedFree = true; } LogPrintf("%s: notarizations DB failed to open (%s); moving aside and regenerating (non-fatal)\n", __func__, strError); From 2bc4a70eb867c0e53864b54b77ae3eacceef5d33 Mon Sep 17 00:00:00 2001 From: DanS Date: Wed, 28 Oct 2026 12:21:55 -0500 Subject: [PATCH 16/33] 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 --- src/init.cpp | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src/init.cpp b/src/init.cpp index 5b4d5cae1..77a496853 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -170,12 +170,12 @@ static NotarizationDB* OpenNotarizationDB(bool fWipe) 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 - int nWaited = 0; + 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__, nWaited); + 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; @@ -191,9 +191,10 @@ static NotarizationDB* OpenNotarizationDB(bool fWipe) 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; - while (nWaited < NOTARIZATION_LOCK_WAIT_SECONDS && !ShutdownRequested()) { - MilliSleep(1000); - nWaited++; + nWaitStart = GetTimeMillis(); + const int64_t nDeadline = nWaitStart + NOTARIZATION_LOCK_WAIT_SECONDS * 1000LL; + while (GetTimeMillis() < nDeadline && !ShutdownRequested()) { + MilliSleep(std::min(1000, std::max(1, nDeadline - GetTimeMillis()))); lockStatus = ProbeLevelDBLock(ndir); if (lockStatus.ok()) break; @@ -201,7 +202,7 @@ static NotarizationDB* OpenNotarizationDB(bool fWipe) } 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__, nWaited, lockStatus.ToString()); + __func__, (GetTimeMillis() - nWaitStart) / 1000, lockStatus.ToString()); return new NotarizationDB(NOTARIZATION_DB_CACHE_BYTES, true, false); } } From ed13277dcb8f95f76ffc86ab51c182006997abd9 Mon Sep 17 00:00:00 2001 From: DanS Date: Wed, 28 Oct 2026 12:27:43 -0500 Subject: [PATCH 17/33] 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 --- src/gtest/test_wallet_shutdownsave.cpp | 53 ++++++++++++++++++++++++++ src/wallet/wallet.cpp | 47 +++++++++++++++++++++-- src/wallet/wallet.h | 11 ++++++ 3 files changed, 108 insertions(+), 3 deletions(-) diff --git a/src/gtest/test_wallet_shutdownsave.cpp b/src/gtest/test_wallet_shutdownsave.cpp index ae29fc17c..f5798011e 100644 --- a/src/gtest/test_wallet_shutdownsave.cpp +++ b/src/gtest/test_wallet_shutdownsave.cpp @@ -82,6 +82,59 @@ TEST_F(WalletShutdownSave, SkipsWhenNothingChangedSinceTheLastSave) { 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 skip paths log and return without opening the wallet database. TEST_F(WalletShutdownSave, SkippedSaveWritesNothing) { CWallet wallet; diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp index 8994e217f..499dc5ed2 100644 --- a/src/wallet/wallet.cpp +++ b/src/wallet/wallet.cpp @@ -881,6 +881,11 @@ const char* CWallet::ShutdownSaveSkipReason(bool fInitCompleted) LOCK(cs_wallet); if (pindexWalletTip == nullptr) return "the wallet tip is not set"; + // A rescan (rescan, z_importkey, ...) that was cut short wrote its own locator, or could not and + // left the older one. Stamping the wallet tip over that would mark the unscanned range as scanned, + // and a key imported with that scan would never see its notes there. + if (nInterruptedRescanHeight >= 0) + return "a rescan did not complete; the next start resumes it from the locator it left"; if (pindexWalletTip == pindexPersistedTip && nWitnessGeneration == nPersistedWitnessGeneration) return "nothing changed since the last save"; return nullptr; @@ -910,6 +915,31 @@ void CWallet::PersistStateAtShutdown(bool fInitCompleted) nHeight, nTxs, GetTimeMillis() - nStart); } +int CWallet::NoteRescanStarted(int nPersistedHeight) +{ + LOCK(cs_wallet); + // Until the scan completes, assume it ends early, even by throwing: the next start then resumes + // from the locator on disk, as it would without a shutdown save. + int nBefore = nInterruptedRescanHeight; + nInterruptedRescanHeight = std::max(nPersistedHeight, 0); + return nBefore; +} + +void CWallet::NoteRescanInterrupted(int nResumeHeight) +{ + LOCK(cs_wallet); + nInterruptedRescanHeight = std::max(nResumeHeight, 0); +} + +void CWallet::NoteRescanCompleted(int nStartHeight, int nInterruptedBefore) +{ + LOCK(cs_wallet); + // A scan that starts above the locator on disk covers what the caller asked for. It is still + // incomplete if an earlier scan was interrupted and this one starts above where that left off. + if (nInterruptedBefore < 0 || nStartHeight <= nInterruptedBefore + 1) + nInterruptedRescanHeight = -1; +} + bool CWallet::SetBestChainNoFlush(const CBlockLocator& loc) { CWalletDB walletdb(strWalletFile, "r+", false); @@ -3796,20 +3826,30 @@ int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate) // already present. No witness work is needed: witnesses are re-derived from each note's own // witnessHeight, and witnessRootValidated is in-memory-only so every note is revalidated // against hashFinalSaplingRoot on the next start. - auto checkpointProgress = [&](const CBlockIndex* pindexStopped) { + const int nInterruptedBefore = NoteRescanStarted(pindexPersisted ? pindexPersisted->GetHeight() : 0); + + // Returns the height the locator on disk is left at, which the next start resumes from. + auto writeCheckpoint = [&](const CBlockIndex* pindexStopped) { + const int nPersisted = pindexPersisted ? pindexPersisted->GetHeight() : 0; if (!fMayCheckpoint || !pindexStopped || !pindexStopped->pprev) - return; + return nPersisted; const CBlockIndex* pindexDone = pindexStopped->pprev; if (pindexDone->GetHeight() <= pindexPersisted->GetHeight()) - return; // never move the locator backwards + return nPersisted; // never move the locator backwards if (SetBestChainNoFlush(chainActive.GetLocator(pindexDone))) { LogPrintf("%s: checkpointed scan progress at height %d\n", __func__, pindexDone->GetHeight()); + return pindexDone->GetHeight(); } else { LogPrintf("%s: FAILED to checkpoint scan progress at height %d; the scan will replay " "from height %d on the next start\n", __func__, pindexDone->GetHeight(), pindexPersisted->GetHeight()); + return nPersisted; } }; + // Also keeps the shutdown save from stamping the wallet tip over what was written here. + auto checkpointProgress = [&](const CBlockIndex* pindexStopped) { + NoteRescanInterrupted(writeCheckpoint(pindexStopped)); + }; ShowProgress(_("Rescanning..."), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup double dProgressStart = Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), pindex, false); @@ -3887,6 +3927,7 @@ int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate) //Update all witness caches BuildWitnessCache(chainActive.Tip(), false); + NoteRescanCompleted(pindexStart->GetHeight(), nInterruptedBefore); ShowProgress(_("Rescanning..."), 100); // hide progress dialog in GUI } diff --git a/src/wallet/wallet.h b/src/wallet/wallet.h index 89a3c1089..5b4f8e4db 100644 --- a/src/wallet/wallet.h +++ b/src/wallet/wallet.h @@ -1001,6 +1001,10 @@ private: 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: @@ -1343,6 +1347,13 @@ public: * 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); + /** 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 From ced37555c44b6432f17ea4197bfe0c9bd4fa4cb3 Mon Sep 17 00:00:00 2001 From: DanS Date: Wed, 28 Oct 2026 12:32:01 -0500 Subject: [PATCH 18/33] 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 --- src/init.cpp | 41 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 40 insertions(+), 1 deletion(-) diff --git a/src/init.cpp b/src/init.cpp index 77a496853..778e1a3c9 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -151,6 +151,33 @@ static leveldb::Status ProbeLevelDBLock(const boost::filesystem::path& dbdir) return status; } +/** + * Does 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"): @@ -159,7 +186,9 @@ static leveldb::Status ProbeLevelDBLock(const boost::filesystem::path& dbdir) * 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. If even that fails, fall back to an in-memory DB. + * 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. @@ -210,6 +239,16 @@ static NotarizationDB* OpenNotarizationDB(bool fWipe) 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. From 0b822cc6b258d37ec6011e1b6d10bb2542271628 Mon Sep 17 00:00:00 2001 From: DanS Date: Wed, 28 Oct 2026 12:32:54 -0500 Subject: [PATCH 19/33] 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 --- src/gtest/test_wallet_shutdownsave.cpp | 39 ++++++++++++++++++++++++++ src/wallet/wallet.cpp | 13 +++++++-- 2 files changed, 50 insertions(+), 2 deletions(-) diff --git a/src/gtest/test_wallet_shutdownsave.cpp b/src/gtest/test_wallet_shutdownsave.cpp index f5798011e..c5b55a916 100644 --- a/src/gtest/test_wallet_shutdownsave.cpp +++ b/src/gtest/test_wallet_shutdownsave.cpp @@ -6,8 +6,13 @@ #include +#include + #include "chain.h" +#include "chainparams.h" +#include "util.h" #include "validationinterface.h" +#include "wallet/db.h" #include "wallet/wallet.h" namespace { @@ -145,3 +150,37 @@ TEST_F(WalletShutdownSave, SkippedSaveWritesNothing) { ASSERT_NO_THROW(wallet.PersistStateAtShutdown(true)); ASSERT_NO_THROW(wallet.PersistStateAtShutdown(false)); } + +// 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)); + } + 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); +} diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp index 499dc5ed2..fc2aff3e7 100644 --- a/src/wallet/wallet.cpp +++ b/src/wallet/wallet.cpp @@ -909,9 +909,18 @@ void CWallet::PersistStateAtShutdown(bool fInitCompleted) const int nHeight = pindexWalletTip->GetHeight(); LogPrintf("Saving wallet state (note witnesses and best block %d, %u txs)...\n", nHeight, nTxs); int64_t nStart = GetTimeMillis(); - bool fWritten = SetBestChain(chainActive.GetLocator()); + bool fWritten = false; + std::string strFailure = "the write failed"; + // Opening the wallet database throws when the environment or the file cannot be opened. Shutdown() + // has no handler, so this must not escape: the rest of the teardown (the coins views, the wallet + // flush, the pidfile) still has to run. + try { + fWritten = SetBestChain(chainActive.GetLocator()); + } catch (const std::exception& e) { + strFailure = e.what(); + } LogPrintf("%s: wallet state %s at height %d: %u txs in %dms\n", __func__, - fWritten ? "saved" : "NOT saved (the write failed; the previous save stays on disk)", + fWritten ? "saved" : strprintf("NOT saved (%s; the previous save stays on disk)", strFailure), nHeight, nTxs, GetTimeMillis() - nStart); } From 6413b8da4e2d03ef8b5b8e7532420a5664b3de47 Mon Sep 17 00:00:00 2001 From: DanS Date: Wed, 28 Oct 2026 12:37:36 -0500 Subject: [PATCH 20/33] 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 --- src/gtest/test_wallet_shutdownsave.cpp | 20 +++++++++++++++----- src/init.cpp | 6 ++++-- src/main.cpp | 5 +++-- src/main.h | 5 +++-- src/wallet/wallet.cpp | 10 +++++++--- src/wallet/wallet.h | 4 ++-- 6 files changed, 34 insertions(+), 16 deletions(-) diff --git a/src/gtest/test_wallet_shutdownsave.cpp b/src/gtest/test_wallet_shutdownsave.cpp index c5b55a916..78dda74ba 100644 --- a/src/gtest/test_wallet_shutdownsave.cpp +++ b/src/gtest/test_wallet_shutdownsave.cpp @@ -17,9 +17,9 @@ namespace { -std::string Reason(CWallet& wallet, bool fInitCompleted) +std::string Reason(CWallet& wallet, bool fInitCompleted, bool fChainstateFlushed = true) { - const char* reason = wallet.ShutdownSaveSkipReason(fInitCompleted); + const char* reason = wallet.ShutdownSaveSkipReason(fInitCompleted, fChainstateFlushed); return reason ? reason : ""; } @@ -58,6 +58,16 @@ TEST_F(WalletShutdownSave, SkipsAfterAWalletFailure) { EXPECT_EQ("", Reason(wallet, true)); } +// 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) { @@ -147,8 +157,8 @@ TEST_F(WalletShutdownSave, SkippedSaveWritesNothing) { wallet.SetWalletTip(&tip); wallet.MarkStatePersisted(&tip); LOCK(cs_main); - ASSERT_NO_THROW(wallet.PersistStateAtShutdown(true)); - ASSERT_NO_THROW(wallet.PersistStateAtShutdown(false)); + ASSERT_NO_THROW(wallet.PersistStateAtShutdown(true, true)); + ASSERT_NO_THROW(wallet.PersistStateAtShutdown(false, true)); } // Opening the wallet database can throw (an environment or file that cannot be opened). Shutdown() has no handler, @@ -176,7 +186,7 @@ TEST_F(WalletShutdownSave, AFailedOpenDoesNotEscape) { ASSERT_EQ("", Reason(wallet, true)); { LOCK(cs_main); - EXPECT_NO_THROW(wallet.PersistStateAtShutdown(true)); + EXPECT_NO_THROW(wallet.PersistStateAtShutdown(true, true)); } EXPECT_EQ("", Reason(wallet, true)) << "a failed save must not be recorded as one"; diff --git a/src/init.cpp b/src/init.cpp index 452e53988..2f2a682dc 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -259,12 +259,14 @@ void Shutdown() { LOCK(cs_main); 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); + pwalletMain->PersistStateAtShutdown(fInitCompleted, fChainstateFlushed); +#else + (void)fChainstateFlushed; #endif } if (pcoinsTip != NULL) { diff --git a/src/main.cpp b/src/main.cpp index db0af063b..7593a43b5 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3846,10 +3846,11 @@ bool static FlushStateToDisk(CValidationState &state, FlushStateMode mode) { return true; } -void FlushStateToDisk() { +bool FlushStateToDisk() { CValidationState state; if ( HUSH_NSPV_FULLNODE ) - FlushStateToDisk(state, FLUSH_STATE_ALWAYS); + return FlushStateToDisk(state, FLUSH_STATE_ALWAYS); + return true; } void PruneAndFlush() { diff --git a/src/main.h b/src/main.h index 89e962497..861ff7d13 100644 --- a/src/main.h +++ b/src/main.h @@ -323,8 +323,9 @@ CBlockIndex * InsertBlockIndex(uint256 hash); bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats); /** Increase a node's misbehavior score. */ void Misbehaving(NodeId nodeid, int howmuch); -/** Flush all state, indexes and buffers to disk. */ -void FlushStateToDisk(); +/** Flush all state, indexes and buffers to disk. False if the flush failed (out of disk space, a write + * error); true also for an nSPV light client, which has no chainstate to flush. */ +bool FlushStateToDisk(); /** Prune block files and flush state to disk. */ void PruneAndFlush(); diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp index fc2aff3e7..430a5c729 100644 --- a/src/wallet/wallet.cpp +++ b/src/wallet/wallet.cpp @@ -867,7 +867,7 @@ void CWallet::MarkStatePersisted(const CBlockIndex* pindex) RecordStatePersisted(pindex, nWitnessGeneration); } -const char* CWallet::ShutdownSaveSkipReason(bool fInitCompleted) +const char* CWallet::ShutdownSaveSkipReason(bool fInitCompleted, bool fChainstateFlushed) { // AppInit2 failed or was cut short: the other threads were interrupted but not joined, and the // wallet tip may still be unset, in which case SetBestChain would stamp the chain tip over an @@ -876,6 +876,10 @@ const char* CWallet::ShutdownSaveSkipReason(bool fInitCompleted) return "startup did not complete"; if (fWalletNotifyFailed) return "the wallet failed to process a block"; + // The locator would then name a block the chainstate and block index on disk may not have, and + // this is typically a full disk, where a write the size of the wallet is the worst thing to start. + if (!fChainstateFlushed) + return "the chainstate flush failed"; if (!bitdb.IsHealthy()) return "the wallet database environment reported an error"; LOCK(cs_wallet); @@ -891,10 +895,10 @@ const char* CWallet::ShutdownSaveSkipReason(bool fInitCompleted) return nullptr; } -void CWallet::PersistStateAtShutdown(bool fInitCompleted) +void CWallet::PersistStateAtShutdown(bool fInitCompleted, bool fChainstateFlushed) { LOCK2(cs_main, cs_wallet); - const char* skip = ShutdownSaveSkipReason(fInitCompleted); + const char* skip = ShutdownSaveSkipReason(fInitCompleted, fChainstateFlushed); if (skip != nullptr) { LogPrintf("%s: not saving the wallet state: %s\n", __func__, skip); return; diff --git a/src/wallet/wallet.h b/src/wallet/wallet.h index 5b4f8e4db..ac614351b 100644 --- a/src/wallet/wallet.h +++ b/src/wallet/wallet.h @@ -1341,12 +1341,12 @@ public: * 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); + 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); + 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 From 9bd2fd2b92f5d7a3d706c8c5ccbff22f84606eb7 Mon Sep 17 00:00:00 2001 From: DanS Date: Wed, 28 Oct 2026 12:39:25 -0500 Subject: [PATCH 21/33] 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 --- src/gtest/test_wallet_shutdownsave.cpp | 12 ++++++++++++ src/init.cpp | 2 ++ src/wallet/wallet.cpp | 4 ++++ 3 files changed, 18 insertions(+) diff --git a/src/gtest/test_wallet_shutdownsave.cpp b/src/gtest/test_wallet_shutdownsave.cpp index 78dda74ba..7a7f34356 100644 --- a/src/gtest/test_wallet_shutdownsave.cpp +++ b/src/gtest/test_wallet_shutdownsave.cpp @@ -58,6 +58,18 @@ TEST_F(WalletShutdownSave, SkipsAfterAWalletFailure) { 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) { diff --git a/src/init.cpp b/src/init.cpp index 2f2a682dc..5248a6231 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -529,6 +529,8 @@ std::string HelpMessage(HelpMessageMode mode) 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("-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("-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)); diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp index 430a5c729..51f8d3691 100644 --- a/src/wallet/wallet.cpp +++ b/src/wallet/wallet.cpp @@ -874,6 +874,10 @@ const char* CWallet::ShutdownSaveSkipReason(bool fInitCompleted, bool fChainstat // interrupted rescan's checkpoint and the next start would skip the unscanned range. if (!fInitCompleted) return "startup did not complete"; + // For deployments whose stop timeout is shorter than the save takes on their wallet: a kill + // during the save rolls it back and only lengthens the next start. + if (!GetBoolArg("-walletsaveatshutdown", true)) + return "disabled by -walletsaveatshutdown=0"; if (fWalletNotifyFailed) return "the wallet failed to process a block"; // The locator would then name a block the chainstate and block index on disk may not have, and From fef79e7b12576fc07ea721ce7ea335c6fd95fa5a Mon Sep 17 00:00:00 2001 From: DanS Date: Wed, 28 Oct 2026 12:40:42 -0500 Subject: [PATCH 22/33] 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 --- src/wallet/wallet.cpp | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp index 51f8d3691..a94c9a1c8 100644 --- a/src/wallet/wallet.cpp +++ b/src/wallet/wallet.cpp @@ -1450,7 +1450,15 @@ int CWallet::VerifyAndSetInitialWitness(const CBlockIndex* pindex, bool witnessO // surfaces exactly where it used to. std::vector rootNotes; for (const std::pair& wtxItem : mapWallet) { - if (wtxItem.second.mapSaplingNoteData.empty() || wtxItem.second.GetDepthInMainChain() <= 0) + // Once every note is validated (the steady state between restarts) nothing here selects one, so + // skip the depth lookup for such a tx. + bool fAnyUnvalidated = false; + for (const mapSaplingNoteData_t::value_type& item : wtxItem.second.mapSaplingNoteData) + if (!item.second.witnessRootValidated) { + fAnyUnvalidated = true; + break; + } + if (!fAnyUnvalidated || wtxItem.second.GetDepthInMainChain() <= 0) continue; for (const mapSaplingNoteData_t::value_type& item : wtxItem.second.mapSaplingNoteData) { const SaplingNoteData* nd = &(item.second); From 6d7ffeb2b909c32a6e8985d00239991aaff4d5ff Mon Sep 17 00:00:00 2001 From: DanS Date: Wed, 28 Oct 2026 12:48:44 -0500 Subject: [PATCH 23/33] 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 --- doc/zsweep-consolidation.md | 4 ++ ...asyncrpcoperation_saplingconsolidation.cpp | 45 +++++++++++++++---- .../asyncrpcoperation_saplingconsolidation.h | 1 + src/wallet/rpcwallet.cpp | 3 ++ src/wallet/wallet.h | 1 + 5 files changed, 46 insertions(+), 8 deletions(-) diff --git a/doc/zsweep-consolidation.md b/doc/zsweep-consolidation.md index b99c9cd47..c93ea7349 100644 --- a/doc/zsweep-consolidation.md +++ b/doc/zsweep-consolidation.md @@ -62,6 +62,10 @@ witness rebuilds. Consolidation keeps that in check. * Only the notes a round actually spends are locked while it proves, so sends made meanwhile still see the rest of the wallet. A note with a missing or unusable witness is skipped (and logged once); the round goes on without it. * 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 diff --git a/src/wallet/asyncrpcoperation_saplingconsolidation.cpp b/src/wallet/asyncrpcoperation_saplingconsolidation.cpp index 82a81e7f0..148654336 100644 --- a/src/wallet/asyncrpcoperation_saplingconsolidation.cpp +++ b/src/wallet/asyncrpcoperation_saplingconsolidation.cpp @@ -8,7 +8,9 @@ #include "asyncrpcoperation_saplingconsolidation.h" #include "init.h" #include "key_io.h" +#include "asyncrpcqueue.h" #include "rpc/protocol.h" +#include "rpc/server.h" #include "random.h" #include "sync.h" #include "tinyformat.h" @@ -31,6 +33,20 @@ static const int MIN_ZOUTS = 7; extern string randomSietchZaddr(); +// 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 q = getAsyncRPCQueue(); + for (const AsyncRPCOperationId& id : q->getAllOperationIds()) { + if (id == self) + continue; + std::shared_ptr 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. @@ -161,6 +177,7 @@ void AsyncRPCOperation_saplingconsolidation::main() { 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(); @@ -323,12 +340,22 @@ bool AsyncRPCOperation_saplingconsolidation::main_impl() { LogPrint("zrpc", "%s: %d consolidation input notes locked for %d transactions\n", opid, z_sapling_inputs_.size(), txs.size()); for (const PlannedTx& planned : txs) { - if (isCancelled()) { - LogPrintf("%s: Canceled. Stopping.\n", opid); - tally.error = "cancelled"; + // The queue's cancel at shutdown never reaches an executing op (AsyncRPCOperation::cancel() is + // not virtual), so look for the shutdown here, or a stop would wait for the whole round. + if (isCancelled() || ShutdownRequested()) { + LogPrintf("%s: %s. Stopping.\n", opid, isCancelled() ? "Canceled" : "Shutting down"); + tally.error = isCancelled() ? "cancelled" : "shutting down"; 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; + } const AddressNotes& group = groups[planned.group]; auto builder = TransactionBuilder(consensusParams, tipHeight, pwalletMain); @@ -401,9 +428,9 @@ bool AsyncRPCOperation_saplingconsolidation::main_impl() { } CTransaction tx = maybe_tx.get(); - if (isCancelled()) { - LogPrintf("%s: Canceled. Stopping.\n", opid); - tally.error = "cancelled"; + if (isCancelled() || ShutdownRequested()) { + LogPrintf("%s: %s. Stopping.\n", opid, isCancelled() ? "Canceled" : "Shutting down"); + tally.error = isCancelled() ? "cancelled" : "shutting down"; status=false; break; } @@ -423,8 +450,9 @@ bool AsyncRPCOperation_saplingconsolidation::main_impl() { } } - LogPrintf("%s: Created %d transactions merging %d notes with total Sapling output amount=%s, skipped %d notes, status=%d\n", - opid, tally.txids.size(), tally.notesMerged, FormatMoney(tally.amountConsolidated), tally.skippedNotes, (int)status); + LogPrintf("%s: Created %d transactions merging %d notes with total Sapling output amount=%s, skipped %d notes, yielded=%d, status=%d\n", + opid, tally.txids.size(), tally.notesMerged, FormatMoney(tally.amountConsolidated), tally.skippedNotes, + (int)tally.yielded, (int)status); setConsolidationResult(tally); return status; } @@ -444,6 +472,7 @@ void AsyncRPCOperation_saplingconsolidation::setConsolidationResult(const Consol 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); diff --git a/src/wallet/asyncrpcoperation_saplingconsolidation.h b/src/wallet/asyncrpcoperation_saplingconsolidation.h index 8a5fc72b2..b7555d023 100644 --- a/src/wallet/asyncrpcoperation_saplingconsolidation.h +++ b/src/wallet/asyncrpcoperation_saplingconsolidation.h @@ -70,6 +70,7 @@ struct ConsolidationTally { 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; }; diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index 72a56282e..e9b0b2d22 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -3333,6 +3333,8 @@ UniValue z_consolidationstatus(const UniValue& params, bool fHelp, const CPubKey " \"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" @@ -3388,6 +3390,7 @@ UniValue z_consolidationstatus(const UniValue& params, bool fHelp, const CPubKey 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 { diff --git a/src/wallet/wallet.h b/src/wallet/wallet.h index 64c6d61eb..b83a718cd 100644 --- a/src/wallet/wallet.h +++ b/src/wallet/wallet.h @@ -412,6 +412,7 @@ struct SaplingConsolidationRound 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 }; From 27a2f041897f150bf06f930ce51c5dba29d3dd05 Mon Sep 17 00:00:00 2001 From: DanS Date: Wed, 28 Oct 2026 12:54:55 -0500 Subject: [PATCH 24/33] 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 --- doc/zsweep-consolidation.md | 9 +- src/gtest/test_wallet_consolidation.cpp | 163 +++++++++++ ...asyncrpcoperation_saplingconsolidation.cpp | 258 ++++++++++++------ .../asyncrpcoperation_saplingconsolidation.h | 33 +++ src/wallet/wallet.cpp | 27 +- src/wallet/wallet.h | 2 + 6 files changed, 403 insertions(+), 89 deletions(-) diff --git a/doc/zsweep-consolidation.md b/doc/zsweep-consolidation.md index c93ea7349..0efe4dbb2 100644 --- a/doc/zsweep-consolidation.md +++ b/doc/zsweep-consolidation.md @@ -60,7 +60,14 @@ witness rebuilds. Consolidation keeps that in check. 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. A note with a missing or unusable witness is skipped (and logged once); the round goes on without it. + 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 diff --git a/src/gtest/test_wallet_consolidation.cpp b/src/gtest/test_wallet_consolidation.cpp index fdd8eaa45..d8761f551 100644 --- a/src/gtest/test_wallet_consolidation.cpp +++ b/src/gtest/test_wallet_consolidation.cpp @@ -8,6 +8,7 @@ #include #include +#include "arith_uint256.h" #include "primitives/transaction.h" #include "random.h" #include "wallet/asyncrpcoperation_saplingconsolidation.h" @@ -230,3 +231,165 @@ TEST(SaplingConsolidationStats, RecordAccumulates) { 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>> roots; + std::set chainAnchors; + std::map, int> rootCalls; + std::map anchorCalls; + + SaplingConsolidationSpendPlan Plan(const std::vector>& 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> groups = { Values(60), Values(10), Values(40) }; + Witnesses w; + w.chainAnchors = { Root(7) }; + for (const auto& g : groups) + w.roots.push_back(std::vector>(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> 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> groups = { Values(40) }; + Witnesses w; + w.chainAnchors = { Root(7) }; + w.roots.assign(1, std::vector>(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> unusable(plan.unusable.begin(), plan.unusable.end()); + EXPECT_EQ(unusable, (std::set>{ {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> groups = { Values(40) }; + Witnesses w; + w.chainAnchors = { Root(7), Root(6) }; + w.roots.assign(1, std::vector>(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> groups = { Values(26) }; + Witnesses w; + w.chainAnchors = { Root(7) }; + w.roots.assign(1, std::vector>(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>(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); +} diff --git a/src/wallet/asyncrpcoperation_saplingconsolidation.cpp b/src/wallet/asyncrpcoperation_saplingconsolidation.cpp index 148654336..1f939a824 100644 --- a/src/wallet/asyncrpcoperation_saplingconsolidation.cpp +++ b/src/wallet/asyncrpcoperation_saplingconsolidation.cpp @@ -21,6 +21,7 @@ #include #include +#include CAmount fConsolidationTxFee = DEFAULT_CONSOLIDATION_FEE; bool fConsolidationMapUsed = false; @@ -106,6 +107,113 @@ std::vector PlanSaplingConsolidation( return plan; } +SaplingConsolidationSpendPlan PlanSaplingConsolidationSpends( + const std::vector>& groups, + const SaplingConsolidationPolicy& policy, + const std::function& rng, + const std::function(size_t, size_t)>& rootOf, + const std::function& isChainAnchor, + const uint256& preferredAnchor) +{ + SaplingConsolidationSpendPlan result; + std::map, boost::optional> roots; + std::map chainAnchor; + // A planned note's root if it is a chain anchor, else none. + auto usableRoot = [&](size_t g, size_t i) -> boost::optional { + const std::pair 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> excluded(groups.size()); + for (;;) { + std::vector> live(groups.size()); + std::vector> 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 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> votes; + for (const SaplingConsolidationBatch& b : plan) { + if (result.anchors.count(b.group)) + continue; + for (size_t i : b.notes) { + boost::optional 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 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 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) {} @@ -186,10 +294,6 @@ void AsyncRPCOperation_saplingconsolidation::main() { } } -// Notes whose missing or desynced witness has already been logged, so a note that can't be spent is -// reported once rather than every round. Guarded by pwalletMain->cs_wallet. -static std::set setWitnessSkipLogged; - bool AsyncRPCOperation_saplingconsolidation::main_impl() { bool status=true; auto opid=getId(); @@ -261,66 +365,57 @@ bool AsyncRPCOperation_saplingconsolidation::main_impl() { groups[it->second].notes.push_back(entry); } - // Plan the round, then fetch the planned notes' witnesses. A note without a usable witness is - // dropped and the round re-planned without it, so it costs the round nothing but a log line. - // Each pass drops at least one note, so this ends. - std::set excluded; - for (;;) { - std::vector> live(groups.size()); - std::vector> values(groups.size()); - for (size_t g = 0; g < groups.size(); g++) { - for (size_t i = 0; i < groups[g].notes.size(); i++) { - if (excluded.count(groups[g].notes[i].op)) - continue; - live[g].push_back(i); - values[g].push_back(CAmount(groups[g].notes[i].note.value())); - } - } - std::vector plan = PlanSaplingConsolidation( - values, request_.policy, [](uint64_t n) { return GetRand(n); }); + // 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> 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, SaplingWitness> witnessOf; + SaplingConsolidationSpendPlan spendPlan = PlanSaplingConsolidationSpends( + values, request_.policy, [](uint64_t n) { return GetRand(n); }, + [&](size_t g, size_t i) -> boost::optional { + boost::optional 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); - // Witnesses per address: every spend of one address's txs then shares that address's anchor. - std::map> opsOf; - for (const SaplingConsolidationBatch& b : plan) - for (size_t idx : b.notes) - opsOf[b.group].push_back(groups[b.group].notes[live[b.group][idx]].op); - std::map witnessOf; - std::map anchorOf; - bool missing = false; - for (const auto& p : opsOf) { - std::vector> witnesses; - uint256 anchor; - pwalletMain->GetSaplingNoteWitnesses(p.second, witnesses, anchor); - anchorOf[p.first] = anchor; - for (size_t i = 0; i < p.second.size(); i++) { - if (witnesses[i]) { - witnessOf.insert(std::make_pair(p.second[i], witnesses[i].get())); - continue; - } - missing = true; - excluded.insert(p.second[i]); - if (setWitnessSkipLogged.insert(p.second[i]).second) - LogPrintf("%s: skipping note %s:%u, it has no usable witness\n", - opid, p.second[i].hash.ToString(), p.second[i].n); - } + 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))); } - if (missing) - continue; - - for (const SaplingConsolidationBatch& b : plan) { - PlannedTx tx; - tx.group = b.group; - tx.anchor = anchorOf[b.group]; - for (size_t idx : b.notes) { - const SaplingNoteEntry& entry = groups[b.group].notes[live[b.group][idx]]; - tx.notes.push_back(entry); - tx.witnesses.push_back(witnessOf.at(entry.op)); - } - txs.push_back(std::move(tx)); - } - break; + txs.push_back(std::move(tx)); } - tally.skippedNotes = excluded.size(); + + // 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. @@ -339,6 +434,18 @@ bool AsyncRPCOperation_saplingconsolidation::main_impl() { } LogPrint("zrpc", "%s: %d consolidation input notes locked for %d transactions\n", opid, z_sapling_inputs_.size(), txs.size()); + // A tx that fails ends its own address's part of the round, not the other addresses'. The round's error + // is the first such failure. + std::set 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; + }; + for (const PlannedTx& planned : txs) { // The queue's cancel at shutdown never reaches an executing op (AsyncRPCOperation::cancel() is // not virtual), so look for the shutdown here, or a stop would wait for the whole round. @@ -356,6 +463,8 @@ bool AsyncRPCOperation_saplingconsolidation::main_impl() { tally.yielded = true; break; } + if (failedGroups.count(planned.group)) + continue; const AddressNotes& group = groups[planned.group]; auto builder = TransactionBuilder(consensusParams, tipHeight, pwalletMain); @@ -364,8 +473,7 @@ bool AsyncRPCOperation_saplingconsolidation::main_impl() { CAmount amountToSend = 0; for (const SaplingNoteEntry& entry : planned.notes) amountToSend += CAmount(entry.note.value()); - // Notes worth no more than the fee go fee-free rather than being burnt into it. - CAmount thisTxFee = amountToSend <= request_.fee ? 0 : request_.fee; + 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)); @@ -380,10 +488,8 @@ bool AsyncRPCOperation_saplingconsolidation::main_impl() { LogPrint("zrpcunsafe", "%s: Added consolidation input %d\n", opid, i); } if (!spendsOk) { - LogPrintf("%s: Consolidation inputs do not share one anchor! Stopping.\n", opid); - tally.error = "inputs do not share one anchor"; - status=false; - break; + failAddress(planned.group, "inputs do not share one anchor"); + continue; } LogPrint("zrpcunsafe", "%s: Using fee=%d\n", opid, thisTxFee); @@ -408,23 +514,20 @@ bool AsyncRPCOperation_saplingconsolidation::main_impl() { // actually add our sietch zoutput, the new way builder.AddSaplingOutput(group.extsk.expsk.ovk, sietchZoutput, amount); } else { - LogPrintf("%s: Invalid payment address %s! Stopping.\n", opid, zdust); + LogPrintf("%s: Invalid payment address %s!\n", opid, zdust); zoutsOk = false; break; } } if (!zoutsOk) { - tally.error = "invalid sietch address"; - status = false; - break; + 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) { - LogPrintf("%s: Failed to build transaction.\n",opid); - tally.error = "failed to build transaction"; - status=false; - break; + failAddress(planned.group, "failed to build transaction"); + continue; } CTransaction tx = maybe_tx.get(); @@ -444,9 +547,8 @@ bool AsyncRPCOperation_saplingconsolidation::main_impl() { tally.fees += thisTxFee; } else { LogPrintf("%s: Consolidation transaction FAILED in CommitTransaction, txid=%s\n",opid , tx.GetHash().ToString()); - tally.error = "transaction was not accepted (CommitTransaction failed)"; - status = false; - break; + failAddress(planned.group, "transaction was not accepted (CommitTransaction failed)"); + continue; } } diff --git a/src/wallet/asyncrpcoperation_saplingconsolidation.h b/src/wallet/asyncrpcoperation_saplingconsolidation.h index b7555d023..e82825fff 100644 --- a/src/wallet/asyncrpcoperation_saplingconsolidation.h +++ b/src/wallet/asyncrpcoperation_saplingconsolidation.h @@ -14,8 +14,12 @@ #include "wallet.h" // for SaplingNoteEntry #include +#include +#include #include +#include + //Default fee used for consolidation transactions, in puposhis static const CAmount DEFAULT_CONSOLIDATION_FEE = 10000; extern CAmount fConsolidationTxFee; @@ -54,6 +58,35 @@ std::vector PlanSaplingConsolidation( const SaplingConsolidationPolicy& policy, const std::function& 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 batches; + std::map anchors; // per address with batches: the anchor of all its spends + std::vector> unusable; // (address, note): no witness, or one at no chain anchor + std::vector> 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>& groups, + const SaplingConsolidationPolicy& policy, + const std::function& rng, + const std::function(size_t, size_t)>& rootOf, + const std::function& 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 diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp index d13fe8492..c737a584c 100644 --- a/src/wallet/wallet.cpp +++ b/src/wallet/wallet.cpp @@ -2402,6 +2402,20 @@ bool CWallet::IsSaplingNullifierFromMe(const uint256& nullifier) const return false; } +boost::optional CWallet::GetSaplingNoteLatestWitness(const SaplingOutPoint& note) const +{ + LOCK(cs_wallet); + // find(), not operator[]: a lookup must not default-construct mapWallet / mapSaplingNoteData entries. + auto wi = mapWallet.find(note.hash); + if (wi == mapWallet.end()) + return boost::none; + const mapSaplingNoteData_t& noteData = wi->second.mapSaplingNoteData; + auto ni = noteData.find(note); + if (ni == noteData.end() || ni->second.witnesses.empty()) + return boost::none; + return ni->second.witnesses.front(); +} + void CWallet::GetSaplingNoteWitnesses(std::vector notes, std::vector>& witnesses, uint256 &final_anchor) @@ -2416,16 +2430,9 @@ void CWallet::GetSaplingNoteWitnesses(std::vector notes, std::vector> cand(notes.size()); std::map rootVotes; for (size_t i = 0; i < notes.size(); i++) { - const SaplingOutPoint& note = notes[i]; - auto wi = mapWallet.find(note.hash); - if (wi == mapWallet.end()) - continue; - const mapSaplingNoteData_t& noteData = wi->second.mapSaplingNoteData; - auto ni = noteData.find(note); - if (ni == noteData.end() || ni->second.witnesses.empty()) - continue; - cand[i] = ni->second.witnesses.front(); - rootVotes[cand[i]->root()]++; + cand[i] = GetSaplingNoteLatestWitness(notes[i]); + if (cand[i]) + rootVotes[cand[i]->root()]++; } // Choose the anchor that the most witnesses agree on (robust even when the FIRST note is the diff --git a/src/wallet/wallet.h b/src/wallet/wallet.h index b83a718cd..0eb3d5b19 100644 --- a/src/wallet/wallet.h +++ b/src/wallet/wallet.h @@ -1360,6 +1360,8 @@ public: std::vector notes, std::vector>& witnesses, uint256 &final_anchor); + //! The note's newest cached witness, whatever its root; none if the wallet has none for it. + boost::optional GetSaplingNoteLatestWitness(const SaplingOutPoint& note) const; isminetype IsMine(const CTxIn& txin) const; CAmount GetDebit(const CTxIn& txin, const isminefilter& filter) const; From 25c79b7512d328f27182a91808e56fe3daf2305b Mon Sep 17 00:00:00 2001 From: DanS Date: Wed, 28 Oct 2026 12:57:58 -0500 Subject: [PATCH 25/33] 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 --- doc/zsweep-consolidation.md | 9 +++--- src/init.cpp | 55 +++++++++++++++++++++---------------- src/wallet/rpcwallet.cpp | 6 +++- 3 files changed, 42 insertions(+), 28 deletions(-) diff --git a/doc/zsweep-consolidation.md b/doc/zsweep-consolidation.md index 0efe4dbb2..caf5bc70c 100644 --- a/doc/zsweep-consolidation.md +++ b/doc/zsweep-consolidation.md @@ -90,7 +90,7 @@ witness rebuilds. Consolidation keeps that in check. | 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. The wallet must hold the address's spending key, or dragonxd refuses to start. | + | 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. `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, @@ -125,9 +125,10 @@ wallet: `N addresses have more than 25 spendable notes; consider -consolidation= 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). Sweep and consolidation never run at the same time, and a sweep is not - started when a consolidation round is due within 5 blocks. +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 diff --git a/src/init.cpp b/src/init.cpp index 60af3bce8..69a683dfa 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -2520,46 +2520,55 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler) pwalletMain->sweepExcludeAddresses.push_back( vSweepExclude[i] ); } - if (pwalletMain->fSaplingConsolidationEnabled) { - //Validate 1 Consolidation address only that matches the sweep address - vector& vaddresses = mapMultiArgs["-consolidatesaplingaddress"]; - if (vaddresses.size() == 0) { - fConsolidateSweepAddress = true; - mapMultiArgs["-consolidatesaplingaddress"] = vSweep; - } else { - pwalletMain->consolidationAddress = vaddresses[0]; - for (int i = 0; i < vaddresses.size(); i++) { - if (vSweep[0] != vaddresses[i]) { - return InitError("Consolidation can only be used on the sweep address when sweep is enabled."); - } - } - } + // With sweep on, consolidation works on the sweep address only, also for z_consolidate with + // -consolidation off: the two would otherwise fight over the same notes and pay fees for nothing. + vector& vaddresses = mapMultiArgs["-consolidatesaplingaddress"]; + bool fOtherAddress = false; + for (size_t i = 0; i < vaddresses.size(); i++) + fOtherAddress |= vSweep[0] != vaddresses[i]; + if (fOtherAddress) { + if (pwalletMain->fSaplingConsolidationEnabled) + return InitError("Consolidation can only be used on the sweep address when sweep is enabled."); + InitWarning(_("-consolidatesaplingaddress is not the sweep address; with -zsweep, consolidation only works on the sweep address")); + } + 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& vaddresses = mapMultiArgs["-consolidatesaplingaddress"]; - fConsolidationMapUsed = !vaddresses.empty(); 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(&zAddress) == nullptr) { - return InitError("Invalid consolidation address: -consolidatesaplingaddress must be a Sapling z-address"); + 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 (!boost::apply_visitor(HaveSpendingKeyForPaymentAddress(pwalletMain), zAddress)) { - if (!fConsolidateSweepAddress) { - return InitError(strprintf("Wallet must hold the spending key of -consolidatesaplingaddress %s", vaddresses[i])); - } - 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(zAddress)); + if (pwalletMain->consolidationAddress.empty()) + pwalletMain->consolidationAddress = vaddresses[i]; } - if (!vaddresses.empty()) - pwalletMain->consolidationAddress = vaddresses[0]; + fConsolidationMapUsed = !pwalletMain->consolidationAddresses.empty(); } // Sweep and consolidation pick notes with GetFilteredNotes at minDepth > 1. Older versions diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index e9b0b2d22..fc419b4d7 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -3444,7 +3444,8 @@ UniValue z_consolidate(const UniValue& params, bool fHelp, const CPubKey& mypk) + 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" + "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" "\nExamples:\n" @@ -3501,6 +3502,9 @@ UniValue z_consolidate(const UniValue& params, bool fHelp, const CPubKey& mypk) 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(zaddr)); } } From 5d5b47d05a670fedc0c62b0a7a663bc7e1c28470 Mon Sep 17 00:00:00 2001 From: DanS Date: Wed, 28 Oct 2026 12:59:46 -0500 Subject: [PATCH 26/33] 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 --- doc/zsweep-consolidation.md | 3 ++- src/wallet/rpcwallet.cpp | 4 +++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/doc/zsweep-consolidation.md b/doc/zsweep-consolidation.md index caf5bc70c..c809989c2 100644 --- a/doc/zsweep-consolidation.md +++ b/doc/zsweep-consolidation.md @@ -103,7 +103,8 @@ witness rebuilds. Consolidation keeps that in check. `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..."]'`. It returns an operation id; `z_getoperationstatus` / +`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. diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index fc419b4d7..5b0457870 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -3448,6 +3448,8 @@ UniValue z_consolidate(const UniValue& params, bool fHelp, const CPubKey& mypk) " 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...\"]'") @@ -6698,7 +6700,7 @@ static const CRPCCommand commands[] = { "wallet", "z_sweepstatus", &z_sweepstatus, true }, { "wallet", "z_autoshieldstatus", &z_autoshieldstatus, true }, { "wallet", "z_consolidationstatus", &z_consolidationstatus, true }, - { "wallet", "z_consolidate", &z_consolidate, true }, + { "wallet", "z_consolidate", &z_consolidate, false }, { "wallet", "z_sendmany", &z_sendmany, false }, { "wallet", "z_shieldcoinbase", &z_shieldcoinbase, false }, { "wallet", "z_getoperationstatus", &z_getoperationstatus, true }, From c0b99a0e1f67ec4f814edc7522820110d5860587 Mon Sep 17 00:00:00 2001 From: DanS Date: Wed, 28 Oct 2026 13:10:41 -0500 Subject: [PATCH 27/33] 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 --- src/gtest/test_wallet_shutdownsave.cpp | 189 ++++++++++++++++++++++++- src/gtest/test_wallet_witnessroots.cpp | 123 +++++++++++++++- src/wallet/wallet.cpp | 28 +--- src/wallet/wallet.h | 32 +++++ 4 files changed, 337 insertions(+), 35 deletions(-) diff --git a/src/gtest/test_wallet_shutdownsave.cpp b/src/gtest/test_wallet_shutdownsave.cpp index 7a7f34356..a823539d4 100644 --- a/src/gtest/test_wallet_shutdownsave.cpp +++ b/src/gtest/test_wallet_shutdownsave.cpp @@ -12,8 +12,10 @@ #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 { @@ -30,6 +32,39 @@ protected: void TearDown() override { fWalletNotifyFailed = false; } }; +class SaveWallet : public CWallet { +public: + explicit SaveWallet(const std::string& strFile = "") : CWallet(strFile) {} + template + 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 @@ -162,15 +197,61 @@ TEST_F(WalletShutdownSave, SkipsAfterAnIncompleteRescan) { EXPECT_EQ("", Reason(wallet, true)); } -// The skip paths log and return without opening the wallet database. -TEST_F(WalletShutdownSave, SkippedSaveWritesNothing) { - CWallet wallet; +// 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); - wallet.MarkStatePersisted(&tip); - LOCK(cs_main); - ASSERT_NO_THROW(wallet.PersistStateAtShutdown(true, true)); - ASSERT_NO_THROW(wallet.PersistStateAtShutdown(false, true)); + { + 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, @@ -206,3 +287,97 @@ TEST_F(WalletShutdownSave, AFailedOpenDoesNotEscape) { 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{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{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"; +} diff --git a/src/gtest/test_wallet_witnessroots.cpp b/src/gtest/test_wallet_witnessroots.cpp index bb641ccf4..3d8a0d72e 100644 --- a/src/gtest/test_wallet_witnessroots.cpp +++ b/src/gtest/test_wallet_witnessroots.cpp @@ -8,7 +8,10 @@ #include #include +#include + #include "chain.h" +#include "chainparams.h" #include "coins.h" #include "init.h" #include "main.h" @@ -16,6 +19,7 @@ #include "primitives/transaction.h" #include "uint256.h" #include "util.h" +#include "validationinterface.h" #include "wallet/wallet.h" #include "zcash/zip32.h" @@ -112,7 +116,9 @@ std::vector Witnesses(int nNotes, int salt, uint256& rootOut) return ws; } -enum Kind { VALID_BELOW_TIP, VALID_AT_TIP, AHEAD_OF_CHAIN, ALREADY_VALIDATED, WRONG_ROOT, NOT_IN_CHAIN }; +// 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 txs; @@ -164,6 +170,11 @@ void Fill(RootsWallet& wallet, const Fixture& fx, const RootsChain& chain, Kinds 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; } @@ -176,6 +187,60 @@ void Fill(RootsWallet& wallet, const Fixture& fx, const RootsChain& chain, Kinds } } +// 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 memo; + memo.fill(0); + auto enc = libzcash::SaplingNotePlaintext(note, memo).encrypt(note.pk_d); + assert(static_cast(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; @@ -216,10 +281,12 @@ 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 @@ -352,3 +419,57 @@ TEST_F(WalletWitnessRoots, UnconfirmedTxIsNotChecked) { 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{WRONG_ROOT, NO_NULLIFIER_VALID} : MixedKinds(i); + }; + const SaplingOutPoint seeded(fx.txs[iSeeded].GetHash(), 0), sibling(fx.txs[iSeeded].GetHash(), 1); + + std::map 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 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); + } +} diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp index a94c9a1c8..64a9445bf 100644 --- a/src/wallet/wallet.cpp +++ b/src/wallet/wallet.cpp @@ -822,36 +822,10 @@ bool CWallet::CommitAutomatedTx(const CTransaction& tx) { bool CWallet::SetBestChain(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; - } - } // Default ctor => fFlushOnClose=true => ~CDB runs a full BDB txn_checkpoint over the entire // cache. Fine for the hourly/shutdown callers; ruinous inside a scan (see SetBestChainNoFlush). CWalletDB walletdb(strWalletFile); - bool fWritten = SetBestChainINTERNAL(walletdb, locator); - if (fWritten) - RecordStatePersisted(pindexStamped, nGeneration); - return fWritten; + return SetBestChainWith(walletdb, loc); } void CWallet::RecordStatePersisted(const CBlockIndex* pindex, uint64_t nGeneration) diff --git a/src/wallet/wallet.h b/src/wallet/wallet.h index ac614351b..5d33601d4 100644 --- a/src/wallet/wallet.h +++ b/src/wallet/wallet.h @@ -985,6 +985,38 @@ protected: return true; } + //! SetBestChain on an open wallet database (a template so tests can pass a fake one). + template + 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: template void SyncMetaData(std::pair::iterator, typename TxSpendMap::iterator>); From 6b67fc0e8e99d5a96a5c9dac9660cc9a194d44a7 Mon Sep 17 00:00:00 2001 From: DanS Date: Wed, 28 Oct 2026 17:05:03 -0500 Subject: [PATCH 28/33] 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 --- src/hush_bitcoind.h | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/hush_bitcoind.h b/src/hush_bitcoind.h index e29b4f5bd..3d09cdac5 100644 --- a/src/hush_bitcoind.h +++ b/src/hush_bitcoind.h @@ -1713,6 +1713,22 @@ int32_t hush_checkPOW(int32_t slowflag,CBlock *pblock,int32_t height) height = pprev->GetHeight() + 1; if ( height == 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 ) { From da7acda6d898743c9884f56018265888ad558d43 Mon Sep 17 00:00:00 2001 From: DanS Date: Wed, 28 Oct 2026 17:05:03 -0500 Subject: [PATCH 29/33] 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 ` (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 --- src/main.cpp | 57 +++++++++++++++++++++++++++++++++++++++------------- 1 file changed, 43 insertions(+), 14 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index db0af063b..1b03f613f 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -4315,23 +4315,52 @@ static bool ActivateBestChainStep(bool fSkipdpow, CValidationState &state, CBloc assert(MAX_REORG_LENGTH > 0);//, "We must be able to reorg some distance"); 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 ` + // (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(_( - "A block chain reorganization has been detected that would roll back %d blocks!!! " - "This is larger than the maximum of %d blocks, and so the node is shutting down for your safety." - ), reorgLength, MAX_REORG_LENGTH) + "\n\n" + + "A block chain reorganization that would roll back %d blocks (more than the maximum of %d) " + "was refused; staying on the current chain." + ), reorgLength, MAX_REORG_LENGTH) + "\n" + _("Reorganization details") + ":\n" + - "- " + strprintf(_("Current tip: %s, height %d, work %s\n"), - pindexOldTip->phashBlock->GetHex(), pindexOldTip->GetHeight(), pindexOldTip->chainPower.chainWork.GetHex()) + "\n" + - "- " + strprintf(_("New 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" + + "- " + strprintf(_("Rejected tip: %s, height %d, work %s"), pindexMostWork->phashBlock->GetHex(), pindexMostWork->GetHeight(), pindexMostWork->chainPower.chainWork.GetHex()) + "\n" + - "- " + strprintf(_("Fork point: %s %s, height %d"), - SMART_CHAIN_SYMBOL,pindexFork->phashBlock->GetHex(), pindexFork->GetHeight()) + "\n\n" + - _("Please help me, wise human!"); - LogPrintf("*** %s\nif you launch with -maxreorg=%d it might be able to resolve this automatically", msg,reorgLength+10); - fprintf(stderr,"*** %s\nif you launch with -maxreorg=%d it might be able to resolve this automatically", msg.c_str(),reorgLength+10); - uiInterface.ThreadSafeMessageBox(msg, "", CClientUIInterface::MSG_ERROR); - StartShutdown(); - return false; + "- " + strprintf(_("Fork point: %s %s, height %d"), + SMART_CHAIN_SYMBOL, pindexFork ? pindexFork->phashBlock->GetHex() : "(none)", pindexFork ? pindexFork->GetHeight() : -1) + "\n" + + strprintf(_("If this is a legitimate deep reorg, recover with: reconsiderblock %s (raise -maxreorg first if needed)"), + pindexBadBase->phashBlock->GetHex()); + LogPrintf("*** %s\n", msg); + fprintf(stderr,"*** %s\n", msg.c_str()); + strMiscWarning = msg; // surfaces in getinfo/getnetworkinfo (GetWarnings), not fatal + + 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. From ae7e085144d238c0860d35001488bb0fe6e539ca Mon Sep 17 00:00:00 2001 From: DanS Date: Thu, 29 Oct 2026 01:25:37 -0500 Subject: [PATCH 30/33] 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 --- src/Makefile.gtest.include | 1 + src/gtest/test_randomx_heightrecover.cpp | 116 +++++++++++++++++++++++ 2 files changed, 117 insertions(+) create mode 100644 src/gtest/test_randomx_heightrecover.cpp diff --git a/src/Makefile.gtest.include b/src/Makefile.gtest.include index eb985f328..6fc713999 100644 --- a/src/Makefile.gtest.include +++ b/src/Makefile.gtest.include @@ -12,6 +12,7 @@ hush_gtest_SOURCES = \ gtest/main.cpp \ gtest/utils.cpp \ gtest/test_randomx_preverify.cpp \ + gtest/test_randomx_heightrecover.cpp \ gtest/test_hdtransparent.cpp \ gtest/test_mnemonic_compat.cpp \ gtest/test_stratum_jobid.cpp \ diff --git a/src/gtest/test_randomx_heightrecover.cpp b/src/gtest/test_randomx_heightrecover.cpp new file mode 100644 index 000000000..03e3a7fb5 --- /dev/null +++ b/src/gtest/test_randomx_heightrecover.cpp @@ -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 +#include +#include + +#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); +} From 661678dd848277be014f990edc8428c243b59ed9 Mon Sep 17 00:00:00 2001 From: DanS Date: Fri, 30 Oct 2026 22:27:41 -0500 Subject: [PATCH 31/33] 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 --- src/miner.cpp | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/src/miner.cpp b/src/miner.cpp index b22cc406a..a7a1ba2ef 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -1436,13 +1436,19 @@ void static RandomXMiner() } CValidationState state; - //{ LOCK(cs_main); - // Skip RandomX re-validation during TestBlockValidity — we already - // computed the correct hash, and re-verifying allocates ~256MB which - // can trigger the OOM killer on memory-constrained systems. - SetSkipRandomXValidation(true); - bool fValid = TestBlockValidity(state,B, chainActive.LastTip(), true, false); - SetSkipRandomXValidation(false); + bool fValid; + { + // Hold cs_main across the LastTip() read and TestBlockValidity: the latter + // asserts pindexPrev == chainActive.Tip(), so without the lock a tip change + // (a block arriving from a peer, or a reorg) between the read and the assert + // aborts the node. The lock was previously removed only to avoid a ~256MB + // 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 ) { LogPrintf("RandomXMiner: TestBlockValidity FAILED at ht.%d, gotinvalid=1, state=%s\n", @@ -1450,7 +1456,6 @@ void static RandomXMiner() gotinvalid = 1; return(false); } - //} SetThreadPriority(THREAD_PRIORITY_NORMAL); LogPrintf("HushRandomXMiner:\n"); LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", B.GetHash().GetHex(), HASHTarget.GetHex()); From 1c29fe86ff4817ba3de964d7ff668b1dcde9dfac Mon Sep 17 00:00:00 2001 From: DanS Date: Fri, 30 Oct 2026 22:28:06 -0500 Subject: [PATCH 32/33] 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 --- src/main.cpp | 55 ++++++++++++++++++++++++++++++++++++++-------------- 1 file changed, 40 insertions(+), 15 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index db0af063b..c82e8c25c 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -328,8 +328,12 @@ namespace { bool fBulkHeaderSeen; //! (server side) time (us) we last served a bulk stream to this peer, for flood throttling. 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; + //! (#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() { fCurrentlyConnected = false; @@ -351,6 +355,7 @@ namespace { fBulkHeaderSeen = false; nLastBulkServeTime = 0; nHeadersProcessed = 0; + nSideBranchHeaders = 0; } }; @@ -7875,6 +7880,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, } CBlockIndex *pindexLast = NULL; + int64_t nSideBranchThisMsg = 0; // newly-stored headers that did NOT extend the best header chain BOOST_FOREACH(const CBlockHeader& header, headers) { if(fDebug) { printf("%s: size.%i, solution size.%i\n", __func__, (int)sizeof(header), (int)header.nSolution.size()); @@ -7887,6 +7893,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, return error("non-continuous headers sequence"); } 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)) { int nDoS; if (state.IsInvalid(nDoS) && futureblock == 0) @@ -7896,29 +7903,47 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, 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 - // store while in IBD. Honest headers-first sync needs at most ~chain-length headers from a - // peer; one that floods far past 2x the known chain length is only trying to bloat - // mapBlockIndex/leveldb (such headers are never selected -- nMinimumChainWork gates that -- - // 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()) { + // SECURITY (#8: header-flood cap): bound how many headers a single peer can make us store, in and + // after IBD. Header-accept does no PoW check (removed as bug-prone), so without a cap a connected + // peer could flood sibling headers of the tip and grow mapBlockIndex linearly (a memory-exhaustion + // DoS). Two complementary per-peer caps, both dropping the peer when exceeded: + { CNodeState *hstate = State(pfrom->GetId()); if (hstate != NULL) { - hstate->nHeadersProcessed += (int64_t)nCount; - // Cap RELATIVE TO THE VALIDATED ACTIVE-CHAIN HEIGHT (attacker-hard -- advancing it requires - // 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. - // The checkpoint height is a fixed floor so honest IBD (blocks still lagging headers) is never capped. + hstate->nHeadersProcessed += (int64_t)nCount; + hstate->nSideBranchHeaders += nSideBranchThisMsg; + + // (1) Tight cap on newly-stored SIDE-BRANCH headers -- the actual mapBlockIndex-growth + // 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(), Checkpoints::GetTotalBlocksEstimate(chainparams.Checkpoints())); int64_t headerCap = 2 * (int64_t)knownH + 200000; if (hstate->nHeadersProcessed > headerCap) { 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); } } From 10217af8e40cc4b5222762c881e9d4c323142803 Mon Sep 17 00:00:00 2001 From: DanS Date: Fri, 30 Oct 2026 22:28:32 -0500 Subject: [PATCH 33/33] 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 --- src/hush_defs.h | 9 +++++++++ src/main.cpp | 9 ++++++++- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/src/hush_defs.h b/src/hush_defs.h index 2264a7160..a31e68029 100644 --- a/src/hush_defs.h +++ b/src/hush_defs.h @@ -32,6 +32,15 @@ #define CRYPTO555_PUBSECPSTR "038a1bd41a08f38edda51042988022933c5775dfce81f7bae0b32a9179650352ac" #define CRYPTO555_HUSHADDR "RFetqf8WUfWnwNeXdknkm8ojk7EXnYFzrv" #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_SAPING_ACTIVATION 1544832000 // Dec 15th, 2018 #define HUSH_SAPING_DEADLINE 1550188800 // Feb 15th, 2019 diff --git a/src/main.cpp b/src/main.cpp index c82e8c25c..d71cb2309 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1598,7 +1598,14 @@ bool CheckTransactionWithoutProofVerification(uint32_t tiptime,const CTransactio char destaddr[65]; 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); if ((ASSETCHAINS_BURN == 1) && isburn && tx.vin.empty()) {