wallet/rpc: make z_consolidationstatus report what consolidation does

z_consolidationstatus reported amount_consolidated from an int that
nothing ever added to (so always 0, and it would have overflowed past
21 DRGX), no policy, nothing about the rounds, and no hint of why a
round would not run.

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

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-28 10:49:38 -05:00
co-authored by Claude Opus 5.5
parent a800a266e5
commit e5791fea71
7 changed files with 226 additions and 5 deletions
+42
View File
@@ -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);
}
+1
View File
@@ -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 },
@@ -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)));
@@ -98,6 +98,7 @@ private:
bool main_impl();
std::vector<SaplingNoteEntry> z_sapling_inputs_; // the notes this round locked
ConsolidationTally tally_; // what the round did, for z_consolidationstatus
void setConsolidationResult(const ConsolidationTally& tally);
+118 -4
View File
@@ -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<libzcash::SaplingPaymentAddress> included(pwalletMain->consolidationAddresses.begin(),
pwalletMain->consolidationAddresses.end());
int over = 0;
UniValue list(UniValue::VARR);
for (const auto& p : pwalletMain->CountConsolidationEligibleNotes()) {
const bool isIncluded = included.empty() || included.count(p.first) > 0;
const bool isOver = p.second > pwalletMain->consolidationThreshold;
if (isIncluded && isOver)
over++;
UniValue entry(UniValue::VOBJ);
entry.push_back(Pair("address", EncodePaymentAddress(p.first)));
entry.push_back(Pair("eligible_notes", p.second));
entry.push_back(Pair("over_threshold", isOver));
entry.push_back(Pair("included", isIncluded));
list.push_back(entry);
}
ret.push_back(Pair("addresses", list));
ret.push_back(Pair("addresses_over_threshold", over));
}
return ret;
}
+10
View File
@@ -759,6 +759,16 @@ void CWallet::RunSaplingConsolidation(int blockHeight) {
}
}
std::map<libzcash::SaplingPaymentAddress, int> CWallet::CountConsolidationEligibleNotes() {
LOCK2(cs_main, cs_wallet);
std::vector<SaplingNoteEntry> entries;
GetFilteredNotes(entries, "", CONSOLIDATION_MIN_DEPTH);
std::map<libzcash::SaplingPaymentAddress, int> 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
+39 -1
View File
@@ -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<std::string> txids;
int notesMerged = 0;
CAmount amountMerged = 0; //!< value of the notes spent
CAmount amountConsolidated = 0; //!< value of the notes created
CAmount fees = 0;
int skippedNotes = 0; //!< left out for a missing or unusable witness
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<std::pair<SproutMerkleTree, SaplingMerkleTree>> 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<libzcash::SaplingPaymentAddress, int> CountConsolidationEligibleNotes();
void RunAutoShieldCoinbase(int blockHeight);
bool CommitAutomatedTx(const CTransaction& tx);
/** Saves witness caches and best block locator to disk. Overrides CValidationInterface. */