feat(wallet): optional background auto-consolidation (Settings toggle)

A mining/pool wallet can accumulate tens of thousands of shielded notes, and the
manual "Consolidate" run — capped at 20 batches per address per click — needs
many re-runs to flatten a 10k+ note address. This adds a hands-off alternative:
a Settings toggle ("Auto-consolidate notes", full-node, off by default) that
trickle-merges notes in the background while the wallet is idle, so it sheds
notes over hours/days without the user ever opening the dialog.

Deliberately gentle, per the request: a small batch (15 inputs/tx vs 50 manual)
and only 3 batches per address per cycle, with cycles ~10 min apart — each cycle
is a handful of tiny merges that barely touch the node. It only acts when the
wallet is genuinely idle (walletScanReady: connected, synced, unlocked, node not
busy, not rescanning) and no send / shield / manual run is in progress, and it
goes dormant (re-scanning hourly) once every address is tidy.

Implementation reuses the existing paced services::ConsolidationRun engine in
"keep in each address" mode, so there is NO fund-path change and the run's
pacing / failure breakers / note-locking all apply:
- App::pumpAutoConsolidation (pumped from update() after pumpConsolidation):
  finalizes a finished cycle (schedules the cooldown + dismisses the run so the
  manual dialog never shows a stale auto result), else starts a new cycle when
  idle and the cooldown has elapsed.
- postAutoConsolidationScan: a quiet z_listunspent scan (the dialog's loadScope
  minus the UI state), session-guarded; on result picks candidates and starts.
- startConsolidationQuiet: the same guards as startConsolidation but silent, with
  a gentle RunConfig; finishConsolidation stays silent for auto runs (logs only).
- services::autoConsolidateCandidates (pure, unit-tested): addresses above the
  note floor that are worth merging; plus the gentle kAutoConsolidate* constants.
- The one-time large-wallet nudge is suppressed while auto-consolidation is on.

Settings plumbing (auto_consolidate, default false) + a daemon-gated toggle in
the Wallet tab's options, with a tooltip. Build + tests + hygiene green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-10-26 13:18:00 -05:00
co-authored by Claude Opus 4.8
parent 54f8359bd4
commit 64294d1518
10 changed files with 167 additions and 0 deletions
+104
View File
@@ -4256,6 +4256,9 @@ void App::resetChatSession()
lite_send_callback_ = nullptr;
chat_send_queue_.clear();
chat_send_parts_remaining_.clear(); // no queued parts survive a reset — drop their outstanding counts
auto_consolidate_run_ = false; // any auto run is torn down with the connection; start fresh next wallet
auto_consolidate_scan_in_flight_ = false;
auto_consolidate_next_at_ = 0.0;
inflight_op_ = LiteInflightOp{};
chat_verified_note_budget_ = 0;
chat_pipeline_note_count_ = 0;
@@ -6340,6 +6343,14 @@ void App::finishConsolidation()
// 2E: a batch of user ops re-reads the wallet and forces one balance, at its end.
if (s.batchesSucceeded > 0) markWalletMutated(/*forceBalance=*/true);
else if (s.batchesSubmitted > 0) noteWalletMutation();
// A background auto-consolidation cycle surfaces nothing per cycle — it is meant to be invisible.
// pumpAutoConsolidation() schedules the next cycle and dismisses the finished run. Log for diagnostics.
if (auto_consolidate_run_) {
wallet::liteLog("auto-consolidate: cycle done — " + std::to_string(s.batchesSucceeded) + "/" +
std::to_string(s.batchesSubmitted) + " batch(es), " + std::to_string(s.notesMerged) +
" note(s) merged");
return;
}
std::string err = s.firstError.empty() ? std::string(TR("shield_unknown_error")) : s.firstError;
if (err.size() > 160) err = err.substr(0, 160) + "...";
auto& n = ui::Notifications::instance();
@@ -6359,11 +6370,104 @@ void App::finishConsolidation()
}
}
// Start the shared ConsolidationRun with the SAME guards as startConsolidation but SILENTLY and with a
// caller-chosen (gentle) config — the background driver's entry point. No toasts; marks the run as ours.
bool App::startConsolidationQuiet(const std::vector<services::NoteGroup>& groups, services::RunConfig cfg)
{
if (isLiteBuild() || capture_mode_ || shutting_down_.load()) return false;
if (consolidation_.active() || consolidation_.hasRun()) return false; // never fight a manual run
if (show_seed_migration_ || (settings_ && settings_->getSeedMigrationPending())) return false;
if (!rpc_ || !rpc_->isConnected() || !worker_ || !state_.connected || isWalletSwitchInProgress()) return false;
if (!consolidation_.start(groups, cfg, services::steadySeconds())) return false;
auto_consolidate_run_ = true;
wallet::liteLog("auto-consolidate: starting a gentle cycle over " + std::to_string(groups.size()) +
" address(es), limit " + std::to_string(cfg.limit) + ", " + std::to_string(cfg.maxBatches) +
" batch(es) each");
return true;
}
// A quiet whole-wallet note scan for the auto driver (the manual dialog's loadScope, minus the UI state).
// On result: nothing worth merging → go dormant; candidates → start a gentle run; failure → back off.
void App::postAutoConsolidationScan()
{
if (!worker_ || !rpc_) return;
const std::uint64_t session = rpc_session_;
const services::ScanTicket ticket = beginAdhocWalletScan(); // z_listunspent is a whole-wallet scan
auto_consolidate_scan_in_flight_ = true;
worker_->post([this, rpc = rpc_.get(), session, ticket]() -> rpc::RPCWorker::MainCb {
std::vector<services::NoteGroup> groups;
std::string error;
rpc::RpcFailureKind kind = rpc::RpcFailureKind::None;
const auto t0 = std::chrono::steady_clock::now();
try {
MaintenanceCallScope maint(*this);
rpc::RPCClient::TraceScope trace("Auto-consolidate / note scan");
const nlohmann::json zs = rpc->call("z_listunspent", nlohmann::json::array({0}),
services::kScopeCallTimeoutSec);
groups = services::groupSpendableNotes(zs);
} catch (const std::exception& e) {
error = e.what(); if (error.empty()) error = "error";
kind = services::mergeCallFailureKind(e);
} catch (...) { error = "unknown error"; kind = rpc::RpcFailureKind::Other; }
const double secs = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
return [this, groups = std::move(groups), error, kind, secs, session, ticket]() {
endAdhocWalletScan(ticket, secs * 1000.0, services::chatScanOutcome(error.empty(), kind));
auto_consolidate_scan_in_flight_ = false;
if (session != rpc_session_) return; // wallet switched under us — drop
const double now = services::steadySeconds();
if (!error.empty()) { // scan failed — back off and try later
auto_consolidate_next_at_ = now + services::kAutoConsolidateRetrySec;
return;
}
const double fee = services::RunConfig{}.fee; // 0.0001
const auto cand = services::autoConsolidateCandidates(groups, services::kAutoConsolidateMinNotes, fee);
if (cand.empty()) { // tidy enough — go dormant, re-scan rarely
auto_consolidate_next_at_ = now + services::kAutoConsolidateIdleRescanSec;
return;
}
services::RunConfig cfg;
cfg.fee = fee;
cfg.limit = services::kAutoConsolidateLimit;
cfg.maxBatches = services::kAutoConsolidateMaxBatches;
if (!startConsolidationQuiet(cand, cfg)) // a manual run grabbed it, or a transient guard
auto_consolidate_next_at_ = now + services::kAutoConsolidateCooldownSec;
// On success the cooldown is set when the run finishes (pumpAutoConsolidation).
};
});
}
// Drive the background auto-consolidation: finalize a finished cycle, else start a new one when idle and the
// cooldown has elapsed. Pumped from update() right after pumpConsolidation().
void App::pumpAutoConsolidation()
{
// Finalize a cycle we started once its run is no longer active (whether it ended via Finish or an abort):
// schedule the next cycle and dismiss the finished run so the manual dialog never shows a stale result.
if (auto_consolidate_run_ && !consolidation_.active()) {
const services::RunSummary s = consolidation_.summary();
const bool trouble = consolidation_.end() == services::RunEnd::Halted ||
consolidation_.end() == services::RunEnd::Aborted || s.batchesSucceeded == 0;
auto_consolidate_next_at_ = services::steadySeconds() +
(trouble ? services::kAutoConsolidateRetrySec : services::kAutoConsolidateCooldownSec);
consolidation_.dismiss();
auto_consolidate_run_ = false;
return;
}
if (!settings_ || !settings_->getAutoConsolidate()) return;
if (auto_consolidate_scan_in_flight_) return;
if (consolidation_.active() || consolidation_.hasRun()) return; // a manual run owns the engine
if (show_seed_migration_ || settings_->getSeedMigrationPending()) return;
if (!walletScanReady() || walletScanInFlight()) return; // connected, synced, unlocked, not busy/rescanning
if (hasTransactionSendProgress()) return; // our own sends go first
if (services::steadySeconds() < auto_consolidate_next_at_) return; // cooldown / dormancy
postAutoConsolidationScan();
}
void App::maybeWarnLargeWallet()
{
if (capture_mode_ || lite_wallet_) return; // no live nags during a UI sweep; lite has no wallet.dat
if (window_background_) return; // when someone can see it
if (!supportsFullNodeLifecycleActions() || !settings_) return;
if (settings_->getAutoConsolidate()) return; // the background consolidator handles bloat quietly
if (!state_.connected || !state_.encryption_state_known) return;
if (state_.warming_up || state_.daemon_initializing || !state_.sync.isSynced()) return;
if (large_wallet_checked_) return; // stat wallet.dat at most once per launch