Files
dragonx/src/wallet/asyncrpcoperation_saplingconsolidation.h
T
DanSandClaude Opus 5.5 27a2f04189 wallet: spend consolidation notes only at a chain anchor
The round took its anchor from GetSaplingNoteWitnesses, a majority vote
over the planned notes alone that never looks at the chain. A real
wallet has had 108 notes desynced onto one root the chain never had, at
the same address as 104 healthy ones. Smallest-first planning can pick
a batch that is mostly desynced notes. The vote then made the healthy
notes the "unusable" ones, and the tx was proved at a non-anchor: Build
succeeds, since witnesses and anchor agree, but CommitTransaction adds
it to the wallet before the mempool refuses it. Its notes then look
spent, and since the plan is nearly deterministic this recurs every
round. One failed tx also ended the round for every other address.

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

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

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

The fee rule moves into SaplingConsolidationTxFee, with a test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 12:54:55 -05:00

143 lines
7.1 KiB
C++

// Copyright (c) 2020 The Hush developers
// Copyright (c) 2019 CryptoForge
// 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"
#include "zcash/Address.hpp"
#include "zcash/zip32.h"
#include "wallet.h" // for SaplingNoteEntry
#include <functional>
#include <map>
#include <utility>
#include <vector>
#include <boost/optional.hpp>
//Default fee used for consolidation transactions, in puposhis
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<size_t> notes; // indices into that address's note values
};
// Most spends a consolidation tx can carry next to its 1 + MIN_ZOUTS outputs within maxTxSize.
int SaplingConsolidationMaxInputs(size_t maxTxSize);
// The batch size actually used: clamped to [MIN_CONSOLIDATION_BATCHSIZE, MAX_CONSOLIDATION_BATCHSIZE]
// and to SaplingConsolidationMaxInputs(maxTxSize).
int ClampSaplingConsolidationBatchSize(int requested, size_t maxTxSize = MAX_TX_SIZE_AFTER_SAPLING);
// Plans one round. groups[i] holds the values of address i's eligible notes. Only an address with more
// than policy.threshold notes is consolidated. Its notes are taken smallest first (so the note an earlier
// round produced is not merged again and again), up to policy.maxTxs transactions, each spending a count
// drawn uniformly from [max(2, ceil(2*batch/3)), batch] so rounds don't all look alike. A transaction never
// takes the address's last remaining note (one stays spendable while the round confirms), and the address
// is done once fewer than two notes could be taken. Batches never mix addresses. rng(n) returns a uniform
// value in [0, n); pure apart from it.
std::vector<SaplingConsolidationBatch> PlanSaplingConsolidation(
const std::vector<std::vector<CAmount>>& groups,
const SaplingConsolidationPolicy& policy,
const std::function<uint64_t(uint64_t)>& rng);
// A round planned over the notes it can spend (see PlanSaplingConsolidationSpends). Note indices are the
// caller's: into the address's values as given.
struct SaplingConsolidationSpendPlan {
std::vector<SaplingConsolidationBatch> batches;
std::map<size_t, uint256> anchors; // per address with batches: the anchor of all its spends
std::vector<std::pair<size_t, size_t>> unusable; // (address, note): no witness, or one at no chain anchor
std::vector<std::pair<size_t, size_t>> deferred; // (address, note): witness at another chain anchor
};
// Plans a round as PlanSaplingConsolidation does, but only over notes that can be spent together. rootOf(g, i)
// is the root of note i of address g's witness (none: there is none), isChainAnchor(root) whether the chain
// holds that root as a Sapling anchor, which is what consensus checks a spend's anchor against. An address's
// spends all use one anchor: preferredAnchor (the tip's root, where the wallet keeps its witnesses) when one
// of its planned notes is there, else the chain anchor most of them share. A planned note whose witness is
// missing or at no chain anchor is left out as unusable; one at another chain anchor is deferred to a later
// round. The round is then planned again without them, until no planned note is left out. Planned notes on a
// root the chain never had therefore can't outvote the address's good ones, however many they are. rootOf is
// called at most once per note and isChainAnchor at most once per root.
SaplingConsolidationSpendPlan PlanSaplingConsolidationSpends(
const std::vector<std::vector<CAmount>>& groups,
const SaplingConsolidationPolicy& policy,
const std::function<uint64_t(uint64_t)>& rng,
const std::function<boost::optional<uint256>(size_t, size_t)>& rootOf,
const std::function<bool(const uint256&)>& isChainAnchor,
const uint256& preferredAnchor);
// The fee of a consolidation tx spending amount: the fee, or none when the notes are worth no more than it.
CAmount SaplingConsolidationTxFee(CAmount amount, CAmount fee);
// What a consolidation operation is asked to do, fixed when it is enqueued.
struct SaplingConsolidationRequest {
bool manual = false; // z_consolidate rather than the -consolidation scheduler
CAmount fee = DEFAULT_CONSOLIDATION_FEE;
SaplingConsolidationPolicy policy;
std::vector<libzcash::SaplingPaymentAddress> addresses; // empty: every address the wallet can spend
};
// What a round did.
struct ConsolidationTally {
std::vector<std::string> txids;
int notesMerged = 0;
CAmount amountMerged = 0; // value of the notes spent
CAmount amountConsolidated = 0; // value of the notes created (amountMerged minus fees)
CAmount fees = 0;
int skippedNotes = 0; // left out for a missing or unusable witness
bool yielded = false; // stopped after a tx to let a queued async operation run
std::string error;
};
class AsyncRPCOperation_saplingconsolidation : public AsyncRPCOperation
{
public:
AsyncRPCOperation_saplingconsolidation(int targetHeight, const SaplingConsolidationRequest& request);
virtual ~AsyncRPCOperation_saplingconsolidation();
// We don't want to be copied or moved around
AsyncRPCOperation_saplingconsolidation(AsyncRPCOperation_saplingconsolidation const&) = delete; // Copy construct
AsyncRPCOperation_saplingconsolidation(AsyncRPCOperation_saplingconsolidation&&) = delete; // Move construct
AsyncRPCOperation_saplingconsolidation& operator=(AsyncRPCOperation_saplingconsolidation const&) = delete; // Copy assign
AsyncRPCOperation_saplingconsolidation& operator=(AsyncRPCOperation_saplingconsolidation&&) = delete; // Move assign
virtual void main();
virtual void cancel();
virtual UniValue getStatus() const;
void unlock_notes();
private:
int targetHeight_;
SaplingConsolidationRequest request_;
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);
};
#endif // HUSH_WALLET_ASYNCRPCOPERATION_SAPLINGCONSOLIDATION_H