Merge branch 'feat/consolidation-policy' into dev

This commit is contained in:
2026-10-31 11:58:36 -05:00
11 changed files with 1515 additions and 235 deletions
+2 -1
View File
@@ -21,7 +21,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)
+395
View File
@@ -0,0 +1,395 @@
// Copyright (c) 2016-2026 The Hush developers
// Distributed under the GPLv3 software license, see the accompanying
// file COPYING or https://www.gnu.org/licenses/gpl-3.0.en.html
#include <gtest/gtest.h>
#include <algorithm>
#include <map>
#include <set>
#include "arith_uint256.h"
#include "primitives/transaction.h"
#include "random.h"
#include "wallet/asyncrpcoperation_saplingconsolidation.h"
#include "wallet/wallet.h"
namespace {
// Always the low end, always the high end, or a fixed sequence.
uint64_t RngLow(uint64_t) { return 0; }
uint64_t RngHigh(uint64_t n) { return n == 0 ? 0 : n - 1; }
std::vector<CAmount> Values(size_t n, CAmount start = 1000, CAmount step = 1000) {
std::vector<CAmount> v;
for (size_t i = 0; i < n; i++)
v.push_back(start + step * (CAmount)i);
return v;
}
size_t PlannedNotes(const std::vector<SaplingConsolidationBatch>& plan, size_t group) {
size_t n = 0;
for (const SaplingConsolidationBatch& b : plan)
if (b.group == group)
n += b.notes.size();
return n;
}
} // namespace
TEST(SaplingConsolidationPlan, ThresholdIsStrict) {
SaplingConsolidationPolicy policy; // threshold 25, batch 15, 3 txs
std::vector<std::vector<CAmount>> groups = { Values(25), Values(26) };
auto plan = PlanSaplingConsolidation(groups, policy, RngHigh);
EXPECT_EQ(PlannedNotes(plan, 0), 0u) << "an address AT the threshold is left alone";
EXPECT_GT(PlannedNotes(plan, 1), 0u) << "an address one note over it is consolidated";
}
TEST(SaplingConsolidationPlan, DefaultsMergeUpToThreeBatches) {
SaplingConsolidationPolicy policy;
std::vector<std::vector<CAmount>> groups = { Values(200) };
auto high = PlanSaplingConsolidation(groups, policy, RngHigh);
ASSERT_EQ(high.size(), 3u);
for (const auto& b : high)
EXPECT_EQ(b.notes.size(), 15u);
// ceil(2*15/3) = 10 at the low end.
auto low = PlanSaplingConsolidation(groups, policy, RngLow);
ASSERT_EQ(low.size(), 3u);
for (const auto& b : low)
EXPECT_EQ(b.notes.size(), 10u);
}
TEST(SaplingConsolidationPlan, SmallestNotesFirstAndDisjoint) {
SaplingConsolidationPolicy policy;
// Shuffled values; the planner must take them in ascending order.
std::vector<CAmount> v = Values(100);
std::vector<CAmount> shuffled = v;
std::reverse(shuffled.begin(), shuffled.end());
std::rotate(shuffled.begin(), shuffled.begin() + 37, shuffled.end());
std::vector<std::vector<CAmount>> groups = { shuffled };
auto plan = PlanSaplingConsolidation(groups, policy, RngHigh);
ASSERT_EQ(plan.size(), 3u);
std::set<size_t> seen;
std::vector<CAmount> taken;
for (const auto& b : plan) {
for (size_t idx : b.notes) {
ASSERT_LT(idx, shuffled.size());
EXPECT_TRUE(seen.insert(idx).second) << "a note is planned twice";
taken.push_back(shuffled[idx]);
}
}
// The 45 notes taken are exactly the 45 smallest, in ascending order across batches.
ASSERT_EQ(taken.size(), 45u);
for (size_t i = 0; i < taken.size(); i++)
EXPECT_EQ(taken[i], v[i]);
}
TEST(SaplingConsolidationPlan, NeverCrossesAddresses) {
SaplingConsolidationPolicy policy;
std::vector<std::vector<CAmount>> groups = { Values(40, 5), Values(3), Values(80, 7), Values(26, 1) };
auto plan = PlanSaplingConsolidation(groups, policy, [](uint64_t n) { return GetRand(n); });
std::map<size_t, int> txs;
std::map<size_t, std::set<size_t>> used;
for (const auto& b : plan) {
ASSERT_LT(b.group, groups.size());
txs[b.group]++;
for (size_t idx : b.notes) {
ASSERT_LT(idx, groups[b.group].size());
EXPECT_TRUE(used[b.group].insert(idx).second);
}
}
EXPECT_EQ(txs.count(1), 0u) << "3 notes is under the threshold";
for (const auto& t : txs)
EXPECT_LE(t.second, policy.maxTxs);
// Each consolidated address keeps at least one note outside the round.
for (const auto& u : used)
EXPECT_LT(u.second.size(), groups[u.first].size());
}
TEST(SaplingConsolidationPlan, LeavesOneNoteAndStopsBelowTwoInputs) {
SaplingConsolidationPolicy policy;
policy.threshold = 2;
// 30 notes, batch 15: 15, then at most 14 (one must stay out), then nothing.
auto plan = PlanSaplingConsolidation({ Values(30) }, policy, RngHigh);
ASSERT_EQ(plan.size(), 2u);
EXPECT_EQ(plan[0].notes.size(), 15u);
EXPECT_EQ(plan[1].notes.size(), 14u);
// 3 notes over a threshold of 2: one tx of 2, the third note stays.
plan = PlanSaplingConsolidation({ Values(3) }, policy, RngHigh);
ASSERT_EQ(plan.size(), 1u);
EXPECT_EQ(plan[0].notes.size(), 2u);
// 2 notes over a threshold of 1: merging both would leave none outside the round.
policy.threshold = 1;
plan = PlanSaplingConsolidation({ Values(2) }, policy, RngHigh);
EXPECT_TRUE(plan.empty());
}
TEST(SaplingConsolidationPlan, MaxTxsAndBatchSize) {
SaplingConsolidationPolicy policy;
policy.maxTxs = 0;
EXPECT_TRUE(PlanSaplingConsolidation({ Values(500) }, policy, RngHigh).empty());
policy.maxTxs = 7;
policy.batchSize = 2;
auto plan = PlanSaplingConsolidation({ Values(500) }, policy, RngLow);
ASSERT_EQ(plan.size(), 7u);
for (const auto& b : plan)
EXPECT_EQ(b.notes.size(), 2u);
// Out-of-range batch sizes are clamped, not trusted.
policy.batchSize = 1;
plan = PlanSaplingConsolidation({ Values(500) }, policy, RngHigh);
for (const auto& b : plan)
EXPECT_EQ(b.notes.size(), 2u);
policy.batchSize = 1000;
plan = PlanSaplingConsolidation({ Values(500) }, policy, RngHigh);
for (const auto& b : plan)
EXPECT_EQ(b.notes.size(), (size_t)MAX_CONSOLIDATION_BATCHSIZE);
}
TEST(SaplingConsolidationPlan, RespectsTxSizeCap) {
// The real cap fits the largest allowed batch with room to spare.
EXPECT_GE(SaplingConsolidationMaxInputs(MAX_TX_SIZE_AFTER_SAPLING), MAX_CONSOLIDATION_BATCHSIZE);
EXPECT_EQ(ClampSaplingConsolidationBatchSize(15), 15);
EXPECT_EQ(ClampSaplingConsolidationBatchSize(0), MIN_CONSOLIDATION_BATCHSIZE);
EXPECT_EQ(ClampSaplingConsolidationBatchSize(51), MAX_CONSOLIDATION_BATCHSIZE);
// A tx size that only fits 5 spends next to the 8 outputs caps every batch at 5.
const size_t outputs = 8 * OUTPUTDESCRIPTION_SIZE;
const size_t small = 1000 + outputs + 5 * SPENDDESCRIPTION_SIZE + SPENDDESCRIPTION_SIZE / 2;
EXPECT_EQ(SaplingConsolidationMaxInputs(small), 5);
EXPECT_EQ(ClampSaplingConsolidationBatchSize(15, small), 5);
SaplingConsolidationPolicy policy;
policy.maxTxSize = small;
auto plan = PlanSaplingConsolidation({ Values(100) }, policy, RngHigh);
ASSERT_EQ(plan.size(), 3u);
for (const auto& b : plan)
EXPECT_EQ(b.notes.size(), 5u);
// Too small for even two spends: nothing is planned.
policy.maxTxSize = 1000 + outputs + SPENDDESCRIPTION_SIZE;
EXPECT_TRUE(PlanSaplingConsolidation({ Values(100) }, policy, RngHigh).empty());
}
TEST(SaplingConsolidationPlan, RandomCountsStayInRange) {
SaplingConsolidationPolicy policy;
std::set<size_t> sizes;
for (int run = 0; run < 200; run++) {
auto plan = PlanSaplingConsolidation({ Values(300) }, policy, [](uint64_t n) { return GetRand(n); });
ASSERT_EQ(plan.size(), 3u);
for (const auto& b : plan) {
EXPECT_GE(b.notes.size(), 10u);
EXPECT_LE(b.notes.size(), 15u);
sizes.insert(b.notes.size());
}
}
EXPECT_GT(sizes.size(), 1u) << "the per-tx input count should vary";
}
TEST(SaplingConsolidationStats, RecordAccumulates) {
SaplingConsolidationStats stats;
EXPECT_FALSE(stats.hasLastRound);
EXPECT_EQ(stats.amountConsolidated, 0);
SaplingConsolidationRound first;
first.height = 100;
first.txids = { "aa", "bb", "cc" };
first.notesMerged = 40;
first.amountMerged = 4000000;
first.fees = 30000;
first.amountConsolidated = 4000000 - 30000;
stats.Record(first);
// A round that found nothing to do still counts as a round and becomes the last one.
SaplingConsolidationRound idle;
idle.height = 125;
stats.Record(idle);
SaplingConsolidationRound failed;
failed.height = 150;
failed.txids = { "dd" };
failed.notesMerged = 12;
failed.amountMerged = 1200000;
failed.fees = 10000;
failed.amountConsolidated = 1190000;
failed.skippedNotes = 2;
failed.error = "transaction was not accepted (CommitTransaction failed)";
stats.Record(failed);
EXPECT_EQ(stats.rounds, 3);
EXPECT_EQ(stats.txsCreated, 4);
EXPECT_EQ(stats.notesConsolidated, 52);
EXPECT_EQ(stats.amountConsolidated, 3970000 + 1190000);
ASSERT_TRUE(stats.hasLastRound);
EXPECT_EQ(stats.lastRound.height, 150);
EXPECT_EQ(stats.lastRound.txids.size(), 1u);
EXPECT_EQ(stats.lastRound.skippedNotes, 2);
EXPECT_EQ(stats.lastRound.error, failed.error);
}
namespace {
uint256 Root(int n) { return ArithToUint256(arith_uint256(n)); }
// Witness roots per note, for PlanSaplingConsolidationSpends; also counts its lookups.
struct Witnesses {
std::vector<std::vector<boost::optional<uint256>>> roots;
std::set<uint256> chainAnchors;
std::map<std::pair<size_t, size_t>, int> rootCalls;
std::map<uint256, int> anchorCalls;
SaplingConsolidationSpendPlan Plan(const std::vector<std::vector<CAmount>>& groups,
const SaplingConsolidationPolicy& policy, const uint256& tip) {
return PlanSaplingConsolidationSpends(groups, policy, RngHigh,
[this](size_t g, size_t i) { rootCalls[std::make_pair(g, i)]++; return roots[g][i]; },
[this](const uint256& r) { anchorCalls[r]++; return chainAnchors.count(r) > 0; },
tip);
}
};
void ExpectAllAt(const SaplingConsolidationSpendPlan& plan, const Witnesses& w) {
for (const auto& b : plan.batches) {
ASSERT_TRUE(plan.anchors.count(b.group));
for (size_t i : b.notes) {
ASSERT_TRUE(w.roots[b.group][i]);
EXPECT_EQ(*w.roots[b.group][i], plan.anchors.at(b.group)) << "note " << i << " of address " << b.group;
}
}
}
} // namespace
TEST(SaplingConsolidationSpends, HealthyWalletPlansAsBefore) {
SaplingConsolidationPolicy policy;
std::vector<std::vector<CAmount>> groups = { Values(60), Values(10), Values(40) };
Witnesses w;
w.chainAnchors = { Root(7) };
for (const auto& g : groups)
w.roots.push_back(std::vector<boost::optional<uint256>>(g.size(), Root(7)));
auto spends = w.Plan(groups, policy, Root(7));
auto plain = PlanSaplingConsolidation(groups, policy, RngHigh);
ASSERT_EQ(spends.batches.size(), plain.size());
for (size_t k = 0; k < plain.size(); k++) {
EXPECT_EQ(spends.batches[k].group, plain[k].group);
EXPECT_EQ(spends.batches[k].notes, plain[k].notes);
}
EXPECT_TRUE(spends.unusable.empty());
EXPECT_TRUE(spends.deferred.empty());
EXPECT_EQ(spends.anchors.size(), 2u) << "the address under the threshold gets no anchor";
EXPECT_EQ(spends.anchors.at(0), Root(7));
// Only planned notes are looked at, each once, and the one root once.
for (const auto& c : w.rootCalls)
EXPECT_EQ(c.second, 1);
EXPECT_EQ(w.rootCalls.size(), PlannedNotes(plain, 0) + PlannedNotes(plain, 2));
EXPECT_EQ(w.anchorCalls.size(), 1u);
EXPECT_EQ(w.anchorCalls[Root(7)], 1);
}
// The case seen on a real wallet: many notes of one address share a root the chain never had, and smallest-first
// planning picks mostly (here: only) those. They must not decide the anchor and take the healthy notes down.
TEST(SaplingConsolidationSpends, DesyncedMajorityDoesNotWin) {
SaplingConsolidationPolicy policy; // 25 / 15 / 3
std::vector<std::vector<CAmount>> groups = { Values(100) };
Witnesses w;
w.chainAnchors = { Root(7) };
w.roots.resize(1);
for (size_t i = 0; i < 100; i++)
w.roots[0].push_back(i < 50 ? Root(666) : Root(7)); // the 50 smallest are desynced
auto plan = w.Plan(groups, policy, Root(7));
ASSERT_EQ(plan.batches.size(), 3u);
EXPECT_EQ(plan.anchors.at(0), Root(7));
ExpectAllAt(plan, w);
for (const auto& b : plan.batches)
for (size_t i : b.notes)
EXPECT_GE(i, 50u);
EXPECT_EQ(plan.unusable.size(), 50u);
EXPECT_TRUE(plan.deferred.empty());
EXPECT_EQ(w.anchorCalls[Root(666)], 1) << "a root is checked against the chain once";
for (const auto& c : w.rootCalls)
EXPECT_EQ(c.second, 1);
// The same when the tip's root is not among them: the chain anchor wins, not the majority.
Witnesses old = w;
old.chainAnchors = { Root(5) };
for (size_t i = 50; i < 100; i++)
old.roots[0][i] = Root(5);
old.rootCalls.clear();
old.anchorCalls.clear();
auto plan2 = old.Plan(groups, policy, Root(7));
ASSERT_EQ(plan2.batches.size(), 3u);
EXPECT_EQ(plan2.anchors.at(0), Root(5));
ExpectAllAt(plan2, old);
}
TEST(SaplingConsolidationSpends, MissingWitnessesAreSkipped) {
SaplingConsolidationPolicy policy;
policy.maxTxs = 1;
std::vector<std::vector<CAmount>> groups = { Values(40) };
Witnesses w;
w.chainAnchors = { Root(7) };
w.roots.assign(1, std::vector<boost::optional<uint256>>(40, Root(7)));
w.roots[0][0] = boost::none;
w.roots[0][3] = boost::none;
auto plan = w.Plan(groups, policy, Root(7));
ASSERT_EQ(plan.batches.size(), 1u);
EXPECT_EQ(plan.batches[0].notes.size(), 15u) << "the dropped notes are replaced by the next smallest";
ExpectAllAt(plan, w);
std::set<std::pair<size_t, size_t>> unusable(plan.unusable.begin(), plan.unusable.end());
EXPECT_EQ(unusable, (std::set<std::pair<size_t, size_t>>{ {0, 0}, {0, 3} }));
}
// Witnesses at a different, real anchor (a rebuild still under way) are deferred, not called unusable.
TEST(SaplingConsolidationSpends, OtherChainAnchorIsDeferred) {
SaplingConsolidationPolicy policy;
policy.maxTxs = 1;
std::vector<std::vector<CAmount>> groups = { Values(40) };
Witnesses w;
w.chainAnchors = { Root(7), Root(6) };
w.roots.assign(1, std::vector<boost::optional<uint256>>(40, Root(7)));
w.roots[0][1] = Root(6);
w.roots[0][2] = Root(6);
auto plan = w.Plan(groups, policy, Root(7));
ASSERT_EQ(plan.batches.size(), 1u);
EXPECT_EQ(plan.anchors.at(0), Root(7));
ExpectAllAt(plan, w);
EXPECT_TRUE(plan.unusable.empty());
EXPECT_EQ(plan.deferred.size(), 2u);
}
// Leaving notes out can bring an address down to the threshold; then it is not consolidated, and needs no anchor.
TEST(SaplingConsolidationSpends, ThresholdCountsUsableNotes) {
SaplingConsolidationPolicy policy;
std::vector<std::vector<CAmount>> groups = { Values(26) };
Witnesses w;
w.chainAnchors = { Root(7) };
w.roots.assign(1, std::vector<boost::optional<uint256>>(26, Root(7)));
w.roots[0][0] = boost::none;
auto plan = w.Plan(groups, policy, Root(7));
EXPECT_TRUE(plan.batches.empty());
EXPECT_TRUE(plan.anchors.empty());
EXPECT_EQ(plan.unusable.size(), 1u);
// Nothing at a chain anchor at all: nothing planned, every looked-at note reported.
Witnesses bad;
bad.roots.assign(1, std::vector<boost::optional<uint256>>(26, Root(666)));
auto none = bad.Plan(groups, policy, Root(7));
EXPECT_TRUE(none.batches.empty());
EXPECT_EQ(none.unusable.size(), 25u) << "the first plan took 25 of the 26, then 1 was too few to plan";
}
TEST(SaplingConsolidationFee, NotesWorthTheFeeGoFeeFree) {
EXPECT_EQ(SaplingConsolidationTxFee(10000, 10000), 0);
EXPECT_EQ(SaplingConsolidationTxFee(9999, 10000), 0);
EXPECT_EQ(SaplingConsolidationTxFee(10001, 10000), 10000);
EXPECT_EQ(SaplingConsolidationTxFee(5000000, 10000), 10000);
}
+106 -39
View File
@@ -633,15 +633,18 @@ std::string HelpMessage(HelpMessageMode mode)
strUsage += HelpMessageOpt("-usemnemonic", strprintf(_("Create new wallets from a fresh BIP39 seed phrase so the 24 words can be exported (z_exportmnemonic) and used in SilentDragonXLite. Set to 0 for a raw random seed with no recovery phrase; existing wallets are never changed (default: %u)"), 1));
strUsage += HelpMessageOpt("-hdtransparentgaplimit=<n>", strprintf(_("On -mnemonic/-hdseed restore, pre-derive this many HD transparent keys so a rescan can find coinbase paid to them (default: %u)"), 1000));
strUsage += HelpMessageOpt("-mnemonicsaplinggap=<n>", strprintf(_("On -mnemonic/-hdseed restore, pre-derive this many shielded (Sapling) addresses so a rescan can find notes sent to them (default: %u)"), 100));
strUsage += HelpMessageOpt("-consolidation", _("Enable auto Sapling note consolidation (default: false)"));
strUsage += HelpMessageOpt("-consolidationinterval", _("Block interval between consolidations (default: 25)"));
strUsage += HelpMessageOpt("-consolidatesaplingaddress=<zaddr>", _("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=<zaddr>", _("Only consolidate this Sapling address; may be repeated. The wallet must hold its spending key (default: all)"));
strUsage += HelpMessageOpt("-consolidationtxfee", strprintf(_("Fee in puposhis per consolidation transaction (default: %i, range %i to %i)"), DEFAULT_CONSOLIDATION_FEE, CONSOLIDATION_MIN_FEE, CONSOLIDATION_MAX_FEE));
strUsage += HelpMessageOpt("-zsweep", _("Enable zaddr sweeping, automatically move all shielded funds to a one address once per X blocks"));
strUsage += HelpMessageOpt("-zsweepaddress=<zaddr>", _("Specify the shielded address where swept funds will be sent)"));
strUsage += HelpMessageOpt("-zsweepfee", strprintf(_("Fee amount in puposhis used send sweep transactions. (default %i)"), DEFAULT_SWEEP_FEE));
strUsage += HelpMessageOpt("-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
@@ -2547,32 +2550,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<string>& 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);
@@ -2629,21 +2658,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<string>& vaddresses = mapMultiArgs["-consolidatesaplingaddress"];
if (vaddresses.size() == 0) {
fConsolidationMapUsed = 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<string>& 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<string>& vaddresses = mapMultiArgs["-consolidatesaplingaddress"];
pwalletMain->consolidationAddresses.clear();
pwalletMain->consolidationAddress.clear();
for (size_t i = 0; i < vaddresses.size(); i++) {
LogPrintf("Consolidating Sapling Address: %s\n", vaddresses[i]);
std::string strProblem;
auto zAddress = DecodePaymentAddress(vaddresses[i]);
if (!IsValidPaymentAddress(zAddress) ||
boost::get<libzcash::SaplingPaymentAddress>(&zAddress) == nullptr) {
strProblem = "Invalid consolidation address: -consolidatesaplingaddress must be a Sapling z-address";
} else if (!boost::apply_visitor(HaveSpendingKeyForPaymentAddress(pwalletMain), zAddress)) {
if (!fConsolidateSweepAddress)
strProblem = strprintf("Wallet must hold the spending key of -consolidatesaplingaddress %s", vaddresses[i]);
else
LogPrintf("%s: the zsweep address is external to this wallet, so consolidation has nothing to do\n", __func__);
}
if (!strProblem.empty()) {
if (pwalletMain->fSaplingConsolidationEnabled)
return InitError(strProblem);
InitWarning(strProblem + "; ignoring it while -consolidation is off");
continue;
}
pwalletMain->consolidationAddresses.push_back(boost::get<libzcash::SaplingPaymentAddress>(zAddress));
if (pwalletMain->consolidationAddress.empty())
pwalletMain->consolidationAddress = vaddresses[i];
}
fConsolidationMapUsed = !pwalletMain->consolidationAddresses.empty();
}
// Sweep and consolidation pick notes with GetFilteredNotes at minDepth > 1. Older versions
@@ -2855,6 +2918,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));
+5
View File
@@ -151,6 +151,11 @@ static const CRPCConvertParam vRPCConvertParams[] =
{ "z_shieldcoinbase", 2},
{ "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 },
+1
View File
@@ -368,6 +368,7 @@ extern UniValue z_sendmany(const UniValue& params, bool fHelp, const CPubKey& my
extern UniValue z_sweepstatus(const UniValue& params, bool fHelp, const CPubKey& mypk); // in rpcwallet.cpp
extern UniValue z_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
@@ -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"
@@ -17,6 +19,10 @@
#include "utilmoneystr.h"
#include "wallet.h"
#include <algorithm>
#include <climits>
#include <set>
CAmount fConsolidationTxFee = DEFAULT_CONSOLIDATION_FEE;
bool fConsolidationMapUsed = false;
@@ -28,7 +34,188 @@ static const int MIN_ZOUTS = 7;
extern string randomSietchZaddr();
AsyncRPCOperation_saplingconsolidation::AsyncRPCOperation_saplingconsolidation(int targetHeight) : targetHeight_(targetHeight) {}
// Whether another operation waits in the async queue. dragonxd has a single async worker, so an
// operation queued during a round (a z_sendmany, say) runs only once the round is over.
static bool OtherAsyncOperationWaiting(const AsyncRPCOperationId& self) {
std::shared_ptr<AsyncRPCQueue> q = getAsyncRPCQueue();
for (const AsyncRPCOperationId& id : q->getAllOperationIds()) {
if (id == self)
continue;
std::shared_ptr<AsyncRPCOperation> op = q->getOperationForId(id);
if (op && op->isReady())
return true;
}
return false;
}
int SaplingConsolidationMaxInputs(size_t maxTxSize) {
// Everything but the descriptions (header, value balance, binding signature, counts) is a few
// hundred bytes; 1000 leaves room to spare.
const size_t overhead = 1000;
const size_t outputs = (1 + MIN_ZOUTS) * OUTPUTDESCRIPTION_SIZE;
if (maxTxSize <= overhead + outputs)
return 0;
return (int)std::min<size_t>((maxTxSize - overhead - outputs) / SPENDDESCRIPTION_SIZE, INT_MAX);
}
int ClampSaplingConsolidationBatchSize(int requested, size_t maxTxSize) {
int batch = std::max(MIN_CONSOLIDATION_BATCHSIZE, std::min(requested, MAX_CONSOLIDATION_BATCHSIZE));
return std::min(batch, SaplingConsolidationMaxInputs(maxTxSize));
}
std::vector<SaplingConsolidationBatch> PlanSaplingConsolidation(
const std::vector<std::vector<CAmount>>& groups,
const SaplingConsolidationPolicy& policy,
const std::function<uint64_t(uint64_t)>& rng)
{
std::vector<SaplingConsolidationBatch> plan;
const int batch = ClampSaplingConsolidationBatchSize(policy.batchSize, policy.maxTxSize);
if (batch < 2)
return plan;
// ceil(2*batch/3), at least 2: the low end of the per-tx input count.
const int low = std::max(2, (2 * batch + 2) / 3);
for (size_t g = 0; g < groups.size(); g++) {
const std::vector<CAmount>& values = groups[g];
if (policy.threshold < 0 || values.size() <= (size_t)policy.threshold)
continue;
// Smallest first; ties keep wallet order so the plan is deterministic for a given rng.
std::vector<size_t> order(values.size());
for (size_t i = 0; i < order.size(); i++)
order[i] = i;
std::stable_sort(order.begin(), order.end(),
[&values](size_t a, size_t b) { return values[a] < values[b]; });
size_t next = 0;
for (int t = 0; t < policy.maxTxs; t++) {
const size_t left = order.size() - next;
size_t take = low + (size_t)rng((uint64_t)(batch - low + 1));
take = std::min<size_t>(take, batch);
// Leave at least one note out of the round so the address stays spendable meanwhile.
if (left == 0 || take > left - 1)
take = (left == 0) ? 0 : left - 1;
if (take < 2)
break;
SaplingConsolidationBatch b;
b.group = g;
b.notes.assign(order.begin() + next, order.begin() + next + take);
next += take;
plan.push_back(std::move(b));
}
}
return plan;
}
SaplingConsolidationSpendPlan PlanSaplingConsolidationSpends(
const std::vector<std::vector<CAmount>>& groups,
const SaplingConsolidationPolicy& policy,
const std::function<uint64_t(uint64_t)>& rng,
const std::function<boost::optional<uint256>(size_t, size_t)>& rootOf,
const std::function<bool(const uint256&)>& isChainAnchor,
const uint256& preferredAnchor)
{
SaplingConsolidationSpendPlan result;
std::map<std::pair<size_t, size_t>, boost::optional<uint256>> roots;
std::map<uint256, bool> chainAnchor;
// A planned note's root if it is a chain anchor, else none.
auto usableRoot = [&](size_t g, size_t i) -> boost::optional<uint256> {
const std::pair<size_t, size_t> key(g, i);
auto ri = roots.find(key);
if (ri == roots.end())
ri = roots.insert(std::make_pair(key, rootOf(g, i))).first;
if (!ri->second)
return boost::none;
auto ai = chainAnchor.find(*ri->second);
if (ai == chainAnchor.end())
ai = chainAnchor.insert(std::make_pair(*ri->second, isChainAnchor(*ri->second))).first;
return ai->second ? ri->second : boost::none;
};
// Each pass leaves out at least one more note or is the last, so this ends.
std::vector<std::set<size_t>> excluded(groups.size());
for (;;) {
std::vector<std::vector<size_t>> live(groups.size());
std::vector<std::vector<CAmount>> values(groups.size());
for (size_t g = 0; g < groups.size(); g++) {
for (size_t i = 0; i < groups[g].size(); i++) {
if (excluded[g].count(i))
continue;
live[g].push_back(i);
values[g].push_back(groups[g][i]);
}
}
std::vector<SaplingConsolidationBatch> plan = PlanSaplingConsolidation(values, policy, rng);
for (SaplingConsolidationBatch& b : plan)
for (size_t& idx : b.notes)
idx = live[b.group][idx];
// An address planned for the first time gets its anchor from its planned notes; it then keeps it.
std::map<size_t, std::map<uint256, int>> votes;
for (const SaplingConsolidationBatch& b : plan) {
if (result.anchors.count(b.group))
continue;
for (size_t i : b.notes) {
boost::optional<uint256> root = usableRoot(b.group, i);
if (root)
votes[b.group][*root]++;
}
}
for (const auto& v : votes) {
if (v.second.count(preferredAnchor)) {
result.anchors[v.first] = preferredAnchor;
continue;
}
int best = 0;
for (const auto& rv : v.second) {
if (rv.second > best) {
best = rv.second;
result.anchors[v.first] = rv.first;
}
}
}
bool dropped = false;
for (const SaplingConsolidationBatch& b : plan) {
auto anchor = result.anchors.find(b.group);
for (size_t i : b.notes) {
boost::optional<uint256> root = usableRoot(b.group, i);
if (root && anchor != result.anchors.end() && *root == anchor->second)
continue;
if (root)
result.deferred.push_back(std::make_pair(b.group, i));
else
result.unusable.push_back(std::make_pair(b.group, i));
excluded[b.group].insert(i);
dropped = true;
}
}
if (!dropped) {
result.batches = std::move(plan);
break;
}
}
// An address whose notes were all left out ends up without batches; it needs no anchor.
std::set<size_t> planned;
for (const SaplingConsolidationBatch& b : result.batches)
planned.insert(b.group);
for (auto it = result.anchors.begin(); it != result.anchors.end(); ) {
if (planned.count(it->first))
++it;
else
it = result.anchors.erase(it);
}
return result;
}
CAmount SaplingConsolidationTxFee(CAmount amount, CAmount fee) {
// Notes worth no more than the fee go fee-free rather than being burnt into it.
return amount <= fee ? 0 : fee;
}
AsyncRPCOperation_saplingconsolidation::AsyncRPCOperation_saplingconsolidation(int targetHeight, const SaplingConsolidationRequest& request)
: targetHeight_(targetHeight), request_(request) {}
AsyncRPCOperation_saplingconsolidation::~AsyncRPCOperation_saplingconsolidation() {}
@@ -87,6 +274,22 @@ 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.manual = request_.manual;
round.time = GetTime();
round.txids = tally_.txids;
round.notesMerged = tally_.notesMerged;
round.amountMerged = tally_.amountMerged;
round.amountConsolidated = tally_.amountConsolidated;
round.fees = tally_.fees;
round.skippedNotes = tally_.skippedNotes;
round.yielded = tally_.yielded;
round.error = tally_.error;
if (!success && round.error.empty())
round.error = getErrorMessage();
pwalletMain->consolidationStats.Record(round);
}
}
}
@@ -94,7 +297,9 @@ void AsyncRPCOperation_saplingconsolidation::main() {
bool AsyncRPCOperation_saplingconsolidation::main_impl() {
bool 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;
{
@@ -109,197 +314,269 @@ 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<std::string>());
setConsolidationResult(ConsolidationTally());
return status;
}
std::vector<SaplingNoteEntry> saplingEntries;
std::set<libzcash::SaplingPaymentAddress> addresses;
// One address's eligible notes and the key that spends them.
struct AddressNotes {
libzcash::SaplingPaymentAddress addr;
libzcash::SaplingExtendedSpendingKey extsk;
std::vector<SaplingNoteEntry> notes;
};
// One transaction to build: notes of one address, with witnesses that share one anchor.
struct PlannedTx {
size_t group;
std::vector<SaplingNoteEntry> notes;
std::vector<SaplingWitness> witnesses;
uint256 anchor;
};
std::vector<AddressNotes> groups;
std::vector<PlannedTx> txs;
// The member, not a local: if anything below throws, main() still records what was committed.
ConsolidationTally& tally = tally_;
{
LOCK2(cs_main, pwalletMain->cs_wallet);
// 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<SaplingNoteEntry> saplingEntries;
pwalletMain->GetFilteredNotes(saplingEntries, "", CONSOLIDATION_MIN_DEPTH);
if(saplingEntries.size() == 0) {
LogPrintf("%s: Nothing to consolidate, done.\n",opid);
return true;
}
// 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<string>& v = mapMultiArgs["-consolidatesaplingaddress"];
for(int i = 0; i < v.size(); i++) {
auto zAddress = DecodePaymentAddress(v[i]);
if (boost::get<libzcash::SaplingPaymentAddress>(&zAddress) != nullptr) {
libzcash::SaplingPaymentAddress saplingAddress = boost::get<libzcash::SaplingPaymentAddress>(zAddress);
addresses.insert(saplingAddress);
} else {
LogPrintf("%s: Invalid zaddr, exiting\n", opid);
return false;
std::set<libzcash::SaplingPaymentAddress> wanted(request_.addresses.begin(), request_.addresses.end());
std::map<libzcash::SaplingPaymentAddress, size_t> groupOf;
std::set<libzcash::SaplingPaymentAddress> 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);
}
// Plan the round over the notes that can be spent: a planned note whose witness is missing, or whose
// root the chain never had as an anchor (a desynced witness), is left out and the round re-planned
// without it. Checking the root against the chain, not just against the other notes, keeps a tx from
// being proved at an anchor no node accepts when the desynced notes are the majority of a batch.
const uint256 tipRoot = (chainActive.Tip() != NULL) ? chainActive.Tip()->hashFinalSaplingRoot : uint256();
std::vector<std::vector<CAmount>> values(groups.size());
for (size_t g = 0; g < groups.size(); g++)
for (const SaplingNoteEntry& entry : groups[g].notes)
values[g].push_back(CAmount(entry.note.value()));
std::map<std::pair<size_t, size_t>, SaplingWitness> witnessOf;
SaplingConsolidationSpendPlan spendPlan = PlanSaplingConsolidationSpends(
values, request_.policy, [](uint64_t n) { return GetRand(n); },
[&](size_t g, size_t i) -> boost::optional<uint256> {
boost::optional<SaplingWitness> w = pwalletMain->GetSaplingNoteLatestWitness(groups[g].notes[i].op);
if (!w)
return boost::none;
witnessOf.insert(std::make_pair(std::make_pair(g, i), *w));
return w->root();
},
[](const uint256& root) {
SaplingMerkleTree tree;
return pcoinsTip->GetSaplingAnchorAt(root, tree);
},
tipRoot);
for (const SaplingConsolidationBatch& b : spendPlan.batches) {
PlannedTx tx;
tx.group = b.group;
tx.anchor = spendPlan.anchors.at(b.group);
for (size_t i : b.notes) {
tx.notes.push_back(groups[b.group].notes[i]);
tx.witnesses.push_back(witnessOf.at(std::make_pair(b.group, i)));
}
txs.push_back(std::move(tx));
}
// One line per round, not one per note: a note can be unusable for a while (a witness rebuild in
// progress) and fine later, so the next round reports it again rather than never.
tally.skippedNotes = spendPlan.unusable.size() + spendPlan.deferred.size();
if (!spendPlan.unusable.empty()) {
std::string some;
for (size_t k = 0; k < spendPlan.unusable.size() && k < 5; k++) {
const SaplingOutPoint& op = groups[spendPlan.unusable[k].first].notes[spendPlan.unusable[k].second].op;
some += strprintf("%s%s:%u", k ? ", " : "", op.hash.ToString(), op.n);
}
LogPrintf("%s: skipping %d notes without a usable witness (none, or not at a chain anchor): %s%s\n",
opid, spendPlan.unusable.size(), some, spendPlan.unusable.size() > 5 ? ", ..." : "");
}
if (!spendPlan.deferred.empty())
LogPrintf("%s: deferring %d notes whose witness is at another anchor than the rest of their address\n",
opid, spendPlan.deferred.size());
// Lock just the notes this round spends, before the locks are released for proving, so a send
// made meanwhile neither picks them nor goes without the rest of the wallet's notes.
for (const PlannedTx& tx : txs) {
for (const SaplingNoteEntry& entry : tx.notes) {
pwalletMain->LockNote(entry.op);
z_sapling_inputs_.push_back(entry);
}
} else {
pwalletMain->GetSaplingPaymentAddresses(addresses);
}
}
int numTxCreated = 0;
std::vector<std::string> 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)) {
// 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<size_t> failedGroups;
auto failAddress = [&](size_t g, const std::string& why) {
LogPrintf("%s: %s; skipping the rest of this round for address %s\n",
opid, why, groups[g].addr.GetHash().ToString());
failedGroups.insert(g);
if (tally.error.empty())
tally.error = why;
status = false;
};
std::vector<SaplingNoteEntry> fromNotes;
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) {
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.
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;
}
if (failedGroups.count(planned.group))
continue;
const AddressNotes& group = groups[planned.group];
libzcash::SaplingIncomingViewingKey ivk;
pwalletMain->GetSaplingIncomingViewingKey(boost::get<libzcash::SaplingPaymentAddress>(saplingEntry.address), ivk);
auto builder = TransactionBuilder(consensusParams, tipHeight, pwalletMain);
builder.SetExpiryHeight(tipHeight + AUTO_OP_EXPIRY_DELTA);
//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);
}
CAmount amountToSend = 0;
for (const SaplingNoteEntry& entry : planned.notes)
amountToSend += CAmount(entry.note.value());
CAmount thisTxFee = SaplingConsolidationTxFee(amountToSend, request_.fee);
CAmount actualAmountToSend = amountToSend - thisTxFee;
LogPrintf("%s: %s Beginning to create transaction with %d Sapling inputs, output amount=%s\n",
__func__, opid, planned.notes.size(), FormatMoney(actualAmountToSend));
//Only use a randomly determined number of notes
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<SaplingOutPoint> ops;
std::vector<libzcash::SaplingNote> notes;
for (auto fromNote : fromNotes) {
ops.push_back(fromNote.op);
notes.push_back(fromNote.note);
}
// Fetch Sapling anchor and witnesses
uint256 anchor;
std::vector<boost::optional<SaplingWitness>> witnesses;
{
LOCK2(cs_main, pwalletMain->cs_wallet);
// LogPrint("zrpcunsafe", "%s: Fetching note witnesses\n", opid);
pwalletMain->GetSaplingNoteWitnesses(ops, witnesses, anchor);
}
// Add Sapling spends
for (size_t i = 0; i < notes.size(); i++) {
if (!witnesses[i]) {
LogPrintf("%s: Missing Witnesses! Stopping.\n", opid);
status=false;
break;
}
builder.AddSaplingSpend(extsk.expsk, notes[i], anchor, witnesses[i].get());
LogPrint("zrpcunsafe", "%s: Added consolidation input %d\n", opid, i);
}
CAmount thisTxFee = amountToSend < fConsolidationTxFee ? 0 : fConsolidationTxFee;
LogPrint("zrpcunsafe", "%s: Using fee=%d\n", opid, thisTxFee);
builder.SetFee(thisTxFee);
// Add the actual consolidation tx
builder.AddSaplingOutput(extsk.expsk.ovk, addr, actualAmountToSend);
LogPrint("zrpcunsafe", "%s: Added consolidation output %s with amount=%li\n", opid, addr.GetHash().ToString().c_str(), actualAmountToSend);
// Add sietch zouts: MIN_ZOUTS dummy zero-value shielded outputs to
// randomly-generated z-addresses, so the consolidation tx does not
// shrink the anonymity set.
for(size_t i = 0; i < MIN_ZOUTS; i++) {
string zdust = randomSietchZaddr();
auto zaddr = DecodePaymentAddress(zdust);
if (IsValidPaymentAddress(zaddr)) {
CAmount amount=0;
auto sietchZoutput = boost::get<libzcash::SaplingPaymentAddress>(zaddr);
LogPrint("zrpcunsafe", "%s: Adding Sietch zdust output %d %s amount=%li\n", opid, i, zdust, amount);
// actually add our sietch zoutput, the new way
builder.AddSaplingOutput(extsk.expsk.ovk, sietchZoutput, amount);
} else {
LogPrintf("%s: Invalid payment address %s! Stopping.\n", opid, zdust);
status = false;
break;
}
}
LogPrint("zrpcunsafe", "%s: Done adding %d sietch zouts\n", opid, MIN_ZOUTS);
auto maybe_tx = builder.Build();
if (!maybe_tx) {
LogPrintf("%s: Failed to build transaction.\n",opid);
status=false;
// 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) {
failAddress(planned.group, "inputs do not share one anchor");
continue;
}
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<libzcash::SaplingPaymentAddress>(zaddr);
LogPrint("zrpcunsafe", "%s: Adding Sietch zdust output %d %s amount=%li\n", opid, i, zdust, amount);
// actually add our sietch zoutput, the new way
builder.AddSaplingOutput(group.extsk.expsk.ovk, sietchZoutput, amount);
} else {
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!\n", opid, zdust);
zoutsOk = false;
break;
}
}
if (!zoutsOk) {
failAddress(planned.group, "invalid sietch address");
continue;
}
LogPrint("zrpcunsafe", "%s: Done adding %d sietch zouts\n", opid, MIN_ZOUTS);
auto maybe_tx = builder.Build();
if (!maybe_tx) {
failAddress(planned.group, "failed to build transaction");
continue;
}
CTransaction tx = maybe_tx.get();
if (isCancelled() || ShutdownRequested()) {
LogPrintf("%s: %s. Stopping.\n", opid, isCancelled() ? "Canceled" : "Shutting down");
tally.error = isCancelled() ? "cancelled" : "shutting down";
status=false;
break;
}
if(pwalletMain->CommitAutomatedTx(tx)) {
LogPrintf("%s: Committed consolidation transaction with txid=%s\n",opid, tx.GetHash().ToString());
tally.txids.push_back(tx.GetHash().ToString());
tally.notesMerged += planned.notes.size();
tally.amountMerged += amountToSend;
tally.amountConsolidated += actualAmountToSend;
tally.fees += thisTxFee;
} else {
LogPrintf("%s: Consolidation transaction FAILED in CommitTransaction, txid=%s\n",opid , tx.GetHash().ToString());
failAddress(planned.group, "transaction was not accepted (CommitTransaction failed)");
continue;
}
}
LogPrintf("%s: Created %d transactions with total Sapling output amount=%s,status=%d\n",opid , numTxCreated, FormatMoney(amountConsolidated), (int)status);
setConsolidationResult(numTxCreated, amountConsolidated, consolidationTxIds);
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;
}
void AsyncRPCOperation_saplingconsolidation::setConsolidationResult(int numTxCreated, const CAmount& amountConsolidated, const std::vector<std::string>& consolidationTxIds) {
void AsyncRPCOperation_saplingconsolidation::setConsolidationResult(const ConsolidationTally& tally) {
if (&tally != &tally_)
tally_ = tally;
UniValue res(UniValue::VOBJ);
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));
res.push_back(Pair("yielded", tally.yielded));
if (!tally.error.empty())
res.push_back(Pair("error", tally.error));
set_result(res);
}
@@ -319,17 +596,10 @@ 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;
}
// 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);
@@ -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,15 +13,104 @@
#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);
AsyncRPCOperation_saplingconsolidation(int targetHeight, const SaplingConsolidationRequest& request);
virtual ~AsyncRPCOperation_saplingconsolidation();
// We don't want to be copied or moved around
@@ -33,15 +125,18 @@ public:
virtual UniValue getStatus() const;
void lock_notes();
void unlock_notes();
private:
int targetHeight_;
SaplingConsolidationRequest request_;
bool main_impl();
std::vector<SaplingNoteEntry> z_sapling_inputs_;
std::vector<SaplingNoteEntry> z_sapling_inputs_; // the notes this round locked
ConsolidationTally tally_; // what the round did, for z_consolidationstatus
void setConsolidationResult(int numTxCreated, const CAmount& amountConsolidated, const std::vector<std::string>& consolidationTxIds);
void setConsolidationResult(const ConsolidationTally& tally);
};
#endif // HUSH_WALLET_ASYNCRPCOPERATION_SAPLINGCONSOLIDATION_H
+251 -5
View File
@@ -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 <stdint.h>
@@ -3269,36 +3270,268 @@ 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"
" \"manual\" : true|false, (boolean) run by z_consolidate\n"
" \"txids\" : [...], (array) the transactions it sent\n"
" \"notes_merged\" : n, (numeric)\n"
" \"amount_merged\" : n, (numeric) value of the notes spent, in puposhis\n"
" \"amount_consolidated\" : n, (numeric) value of the notes created, in puposhis\n"
" \"fees\" : n, (numeric) in puposhis\n"
" \"skipped_notes\" : n, (numeric) notes left out for a missing or unusable witness\n"
" \"yielded\" : true|false, (boolean) it stopped after a transaction to let a queued operation\n"
" (z_sendmany, ...) run; the next round goes on\n"
" \"error\" : \"...\" (string) why it stopped early; empty if it did not\n"
" },\n"
" \"disabled_reason\" : \"...\", (string) why no periodic round can start now; empty if one can\n"
" \"addresses\" : [ (array, verbose only) every address with eligible notes\n"
" { \"address\" : \"zaddr\", \"eligible_notes\" : n, \"over_threshold\" : true|false, \"included\" : true|false }\n"
" ],\n"
" \"addresses_over_threshold\" : n, (numeric, verbose only) included addresses over the threshold\n"
" \"consolidation_suggested\" : true|false, (boolean, verbose only) -consolidation is off and some\n"
" address is over the threshold: consider -consolidation=1 or z_consolidate\n"
" \"consolidation_suggested_count\" : n (numeric, verbose only) addresses over the threshold while it is off\n"
"}\n"
"\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));
last.push_back(Pair("manual", r.manual));
UniValue txids(UniValue::VARR);
for (const std::string& txid : r.txids)
txids.push_back(txid);
last.push_back(Pair("txids", txids));
last.push_back(Pair("notes_merged", r.notesMerged));
last.push_back(Pair("amount_merged", (int64_t)r.amountMerged));
last.push_back(Pair("amount_consolidated", (int64_t)r.amountConsolidated));
last.push_back(Pair("fees", (int64_t)r.fees));
last.push_back(Pair("skipped_notes", r.skippedNotes));
last.push_back(Pair("yielded", r.yielded));
last.push_back(Pair("error", r.error));
ret.push_back(Pair("last_round", last));
} else {
ret.push_back(Pair("last_round", NullUniValue));
}
ret.push_back(Pair("disabled_reason", ConsolidationDisabledReason()));
if (fVerbose) {
std::set<libzcash::SaplingPaymentAddress> included(pwalletMain->consolidationAddresses.begin(),
pwalletMain->consolidationAddresses.end());
int over = 0;
UniValue list(UniValue::VARR);
for (const auto& p : pwalletMain->CountConsolidationEligibleNotes()) {
const bool isIncluded = included.empty() || included.count(p.first) > 0;
const bool isOver = p.second > pwalletMain->consolidationThreshold;
if (isIncluded && isOver)
over++;
UniValue entry(UniValue::VOBJ);
entry.push_back(Pair("address", EncodePaymentAddress(p.first)));
entry.push_back(Pair("eligible_notes", p.second));
entry.push_back(Pair("over_threshold", isOver));
entry.push_back(Pair("included", isIncluded));
list.push_back(entry);
}
ret.push_back(Pair("addresses", list));
ret.push_back(Pair("addresses_over_threshold", over));
pwalletMain->SetConsolidationSuggestion(over);
ret.push_back(Pair("consolidation_suggested", !pwalletMain->fSaplingConsolidationEnabled && over > 0));
ret.push_back(Pair("consolidation_suggested_count", pwalletMain->consolidationSuggestCount));
}
return ret;
}
UniValue z_consolidate(const UniValue& params, bool fHelp, const CPubKey& mypk)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() > 4)
throw runtime_error(
"z_consolidate ( fee batchsize maxtxs [\"zaddr\",...] )\n"
"\nRun one Sapling consolidation round now, with the -consolidation settings, also when\n"
"-consolidation is off. Every address holding more than -consolidationthreshold eligible notes\n"
"(unspent, unlocked, at least 11 confirmations) gets up to maxtxs transactions, each spending up to\n"
"batchsize of its smallest notes back to that same address, plus 7 zero-value dummy outputs.\n"
"Pass null for an argument to keep its setting.\n"
"\nArguments:\n"
"1. fee (numeric, optional, default=-consolidationtxfee) fee per transaction in " + CURRENCY_UNIT + "\n"
"2. batchsize (numeric, optional, default=-consolidationbatchsize) most notes per transaction, "
+ strprintf("%d to %d", MIN_CONSOLIDATION_BATCHSIZE, MAX_CONSOLIDATION_BATCHSIZE) + "\n"
"3. maxtxs (numeric, optional, default=-consolidationmaxtxs) most transactions per address, "
+ strprintf("1 to %d", MAX_CONSOLIDATION_MAXTXS) + "\n"
"4. addresses (array, optional, default=-consolidatesaplingaddress or all) Sapling addresses to consolidate;\n"
" with -zsweep on, only the sweep address (also the default then)\n"
"\nResult:\n"
"\"operationid\" (string) An operationid to pass to z_getoperationstatus to get the result.\n"
"The fee here is in " + CURRENCY_UNIT + ", like z_sendmany's; -consolidationtxfee and the amounts in\n"
"z_consolidationstatus are in puposhis (1 " + CURRENCY_UNIT + " = 100000000).\n"
"\nExamples:\n"
+ HelpExampleCli("z_consolidate", "")
+ HelpExampleCli("z_consolidate", "null 50 20 '[\"zs1...\"]'")
+ HelpExampleRpc("z_consolidate", "")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
EnsureWalletIsUnlocked();
if (AutoWalletOpsSyncing())
throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Node is syncing; try again once it has caught up");
if (pwalletMain->fConsolidationRunning)
throw JSONRPCError(RPC_WALLET_ERROR, "A consolidation round is already running; see z_consolidationstatus");
if (pwalletMain->fSweepRunning || pwalletMain->fAutoShieldRunning)
throw JSONRPCError(RPC_WALLET_ERROR, strprintf("A %s round is running; try again when it finishes",
pwalletMain->fSweepRunning ? "z_sweep" : "autoshield"));
SaplingConsolidationRequest request;
request.manual = true;
request.fee = fConsolidationTxFee;
request.policy.threshold = pwalletMain->consolidationThreshold;
request.policy.batchSize = pwalletMain->consolidationBatchSize;
request.policy.maxTxs = pwalletMain->consolidationMaxTxs;
request.addresses = pwalletMain->consolidationAddresses;
if (params.size() > 0 && !params[0].isNull()) {
request.fee = AmountFromValue(params[0]);
if (request.fee < CONSOLIDATION_MIN_FEE || request.fee > CONSOLIDATION_MAX_FEE)
throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid fee: must be from %s to %s",
FormatMoney(CONSOLIDATION_MIN_FEE), FormatMoney(CONSOLIDATION_MAX_FEE)));
}
if (params.size() > 1 && !params[1].isNull()) {
request.policy.batchSize = params[1].get_int();
if (request.policy.batchSize < MIN_CONSOLIDATION_BATCHSIZE || request.policy.batchSize > MAX_CONSOLIDATION_BATCHSIZE)
throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid batchsize: must be from %d to %d",
MIN_CONSOLIDATION_BATCHSIZE, MAX_CONSOLIDATION_BATCHSIZE));
}
if (params.size() > 2 && !params[2].isNull()) {
request.policy.maxTxs = params[2].get_int();
if (request.policy.maxTxs < 1 || request.policy.maxTxs > MAX_CONSOLIDATION_MAXTXS)
throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid maxtxs: must be from 1 to %d", MAX_CONSOLIDATION_MAXTXS));
}
if (params.size() > 3 && !params[3].isNull()) {
UniValue addresses = params[3].get_array();
if (addresses.size() == 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid addresses: the array is empty");
request.addresses.clear();
for (size_t i = 0; i < addresses.size(); i++) {
const std::string& str = addresses[i].get_str();
auto zaddr = DecodePaymentAddress(str);
if (!IsValidPaymentAddress(zaddr) || boost::get<libzcash::SaplingPaymentAddress>(&zaddr) == nullptr)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid address, must be a Sapling z-address: " + str);
if (!boost::apply_visitor(HaveSpendingKeyForPaymentAddress(pwalletMain), zaddr))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Wallet does not hold the spending key of " + str);
// As at startup: with zsweep on, consolidating any other address only feeds the next sweep.
if (pwalletMain->fSweepEnabled && str != pwalletMain->sweepAddress)
throw JSONRPCError(RPC_INVALID_PARAMETER, "With -zsweep on, only the sweep address can be consolidated: " + str);
request.addresses.push_back(boost::get<libzcash::SaplingPaymentAddress>(zaddr));
}
}
// Take the scheduler's slot exactly as RunSaplingConsolidation does, so sweep and autoshield
// defer to this round and its completion releases the flag.
pwalletMain->fConsolidationRunning = true;
std::shared_ptr<AsyncRPCQueue> q = getAsyncRPCQueue();
std::shared_ptr<AsyncRPCOperation> lastOperation = q->getOperationForId(pwalletMain->saplingConsolidationOperationId);
if (lastOperation != nullptr) {
lastOperation->cancel();
if (!pwalletMain->saplingConsolidationOpManual)
q->popOperationForId(pwalletMain->saplingConsolidationOperationId);
}
std::shared_ptr<AsyncRPCOperation> operation(
new AsyncRPCOperation_saplingconsolidation(chainActive.Height() + AUTO_OP_TARGET_HEIGHT_OFFSET, request));
pwalletMain->saplingConsolidationOperationId = operation->getId();
pwalletMain->saplingConsolidationOpManual = true;
if (!q->addOperation(operation)) {
pwalletMain->fConsolidationRunning = false;
throw JSONRPCError(RPC_INTERNAL_ERROR, "The async queue is not accepting operations (shutting down?)");
}
return operation->getId();
}
UniValue z_sweepstatus(const UniValue& params, bool fHelp, const CPubKey& mypk)
{
@@ -3358,7 +3591,9 @@ UniValue z_autoshieldstatus(const UniValue& params, bool fHelp, const CPubKey& m
" \"hdseedorigin\" : n, (numeric) 0 unrecorded, 1 created, 2 restored, 3 retrofit, 4 unknown\n"
" \"hdseedorigin_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", "")
@@ -3410,6 +3645,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;
}
@@ -6455,6 +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, false },
{ "wallet", "z_sendmany", &z_sendmany, false },
{ "wallet", "z_shieldcoinbase", &z_shieldcoinbase, false },
{ "wallet", "z_getoperationstatus", &z_getoperationstatus, true },
+75 -13
View File
@@ -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) {
@@ -730,12 +738,21 @@ 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();
std::shared_ptr<AsyncRPCOperation> 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<AsyncRPCOperation> 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.
@@ -745,6 +762,44 @@ 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;
}
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<libzcash::SaplingPaymentAddress> 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
@@ -2347,6 +2402,20 @@ bool CWallet::IsSaplingNullifierFromMe(const uint256& nullifier) const
return false;
}
boost::optional<SaplingWitness> 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<SaplingOutPoint> notes,
std::vector<boost::optional<SaplingWitness>>& witnesses,
uint256 &final_anchor)
@@ -2361,16 +2430,9 @@ void CWallet::GetSaplingNoteWitnesses(std::vector<SaplingOutPoint> notes,
std::vector<boost::optional<SaplingWitness>> cand(notes.size());
std::map<uint256, int> 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
+76 -2
View File
@@ -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
@@ -385,6 +400,42 @@ 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
bool manual = false; //!< run by z_consolidate
int64_t time = 0;
std::vector<std::string> txids;
int notesMerged = 0;
CAmount amountMerged = 0; //!< value of the notes spent
CAmount amountConsolidated = 0; //!< value of the notes created
CAmount fees = 0;
int skippedNotes = 0; //!< left out for a missing or unusable witness
bool yielded = false; //!< stopped early to let a queued async operation run
std::string error; //!< why the round stopped early, if it did
};
/** Sapling consolidation totals since the node started. */
struct SaplingConsolidationStats
{
int rounds = 0;
int64_t txsCreated = 0;
int64_t notesConsolidated = 0;
CAmount amountConsolidated = 0;
bool hasLastRound = false;
SaplingConsolidationRound lastRound;
void Record(const SaplingConsolidationRound& round) {
rounds++;
txsCreated += round.txids.size();
notesConsolidated += round.notesMerged;
amountConsolidated += round.amountConsolidated;
lastRound = round;
hasLastRound = true;
}
};
/** Height of the active-chain block holding a wallet tx that is nDepth deep (as GetDepthInMainChain
* returns it, and SaplingNoteEntry::confirmations holds it), or 0 when the tx is unconfirmed or not
* in the active chain. Caller holds cs_main. */
@@ -840,6 +891,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;
@@ -878,9 +931,20 @@ 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;
// 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 = 25;
int consolidationInterval = DEFAULT_CONSOLIDATION_INTERVAL;
int consolidationThreshold = DEFAULT_CONSOLIDATION_THRESHOLD;
int consolidationBatchSize = DEFAULT_CONSOLIDATION_BATCHSIZE;
int consolidationMaxTxs = DEFAULT_CONSOLIDATION_MAXTXS;
// -consolidatesaplingaddress (or the zsweep address); empty: every address the wallet can spend.
std::vector<libzcash::SaplingPaymentAddress> consolidationAddresses;
int sweepFee = 10000;
int sweepMaxInputs = 200;
std::string sweepAddress = "";
@@ -1296,6 +1360,8 @@ public:
std::vector<SaplingOutPoint> notes,
std::vector<boost::optional<SaplingWitness>>& witnesses,
uint256 &final_anchor);
//! The note's newest cached witness, whatever its root; none if the wallet has none for it.
boost::optional<SaplingWitness> GetSaplingNoteLatestWitness(const SaplingOutPoint& note) const;
isminetype IsMine(const CTxIn& txin) const;
CAmount GetDebit(const CTxIn& txin, const isminefilter& filter) const;
@@ -1318,6 +1384,14 @@ 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();
/** 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. */