Merge branch 'dev'

This commit is contained in:
2026-11-08 11:22:26 -06:00
25 changed files with 3185 additions and 354 deletions
+71 -7
View File
@@ -13,7 +13,7 @@ This is to document zsweep and consolidation for advanced DragonX users.
A user can use these options at the command line, but it is **recommended to configure these options within the DRAGONX.conf file**.
Consolidation takes many unspent shielded UTXOs (zutxos) into one zutxo, which makes spending them in the future faster and potentially cost less in fees. It also helps prevent certain kinds of metadata leakages and spam attacks. It is not recommended for very large wallets (wallet.dat files with thousands of transactions) for performance reasons. This is why it defaults to OFF for CLI full nodes but ON for GUI wallets that use an embedded dragonxd.
Consolidation merges many unspent shielded notes (zutxos) of one z-address into a few notes of that same address, which makes spending them later faster and cheaper, keeps the wallet smaller and shortens witness rebuilds and rescans. It never moves funds between addresses. Both zsweep and consolidation are **off by default** in dragonxd, for CLI nodes and for GUI wallets that run an embedded dragonxd alike (the ObsidianDragon GUI does its own, separate auto-consolidation through `z_mergetoaddress`).
Zsweep is when you sweep numerous zutxos into one z-address that you configure. This z-address can be local to that system or it can be configured to sweep to a remote wallet on a different system with the zsweepexternal=1 option, which is explained below in the Zsweep section.
@@ -32,7 +32,7 @@ Zsweep is when you sweep numerous zutxos into one z-address that you configure.
| Zsweep Option Name| Details of what it does |
|-------------------|-------------------------|
| zsweepexternal=1 | Will enable the option to zsweep to an "external" z-address which exists in a wallet on a different system. |
| zsweepinterval=5 | By default zsweep runs every 5 blocks, so set and modify this value to change that. |
| zsweepinterval=10 | By default zsweep runs every 10 blocks (values below 5 fall back to 10), so set and modify this value to change that. |
| zsweepmaxinputs=8 | By default zsweep makes sure to not reduce the anonset in any tx by having a maximum number of inputs of 8. This should be fine for new wallets, but if you have an existing wallet with many zutxos it can be changed with this option. Keep in mind that large values will make sweeping faster at the expense of reducing the AnonSet. |
| zsweepfee=0 | The default zsweep fee is 10000 puposhis or 0.0001 DRAGONX, the default for all transactions. To use fee=0 for zsweep transactions, set this option. |
| zsweepexclude=zs1... | Exclude a certain address from being swept. Can be used multiple times to exclude multiple addressses |
@@ -41,7 +41,42 @@ Zsweep is when you sweep numerous zutxos into one z-address that you configure.
## Consolidation
1. We add the following to our conf file as per the Pre-Step.
Mining with auto-shielding on (the default for wallets created or restored by dragonxd) adds one shielded note to the
wallet per auto-shield round. Over weeks that is thousands of small notes, which slow down sends, balance calls and
witness rebuilds. Consolidation keeps that in check.
### What a round does
* An address is consolidated only when it holds **more than** `consolidationthreshold` (default 25) *eligible*
notes: unspent (also not spent by a transaction still in the mempool), not locked by another operation, spendable
by this wallet, and at least 11 confirmations deep. Addresses at or below the threshold are left alone.
* For each such address a round sends up to `consolidationmaxtxs` (default 3) transactions. Each spends up to
`consolidationbatchsize` (default 15) of the address's **smallest** notes and pays their value, minus the fee, back
to **the same address**. The big note an earlier round produced is therefore not merged again every round.
* The number of inputs per transaction is drawn at random between two thirds of the batch size and the batch size
(10 to 15 by default), so rounds don't all look alike. A transaction never takes an address's last remaining note,
so every address keeps at least one spendable note while the round confirms.
* Each transaction has exactly 8 shielded outputs: the real one plus 7 zero-value dummy ("Sietch") outputs to random
addresses, so it does not shrink the anonymity set. It pays `consolidationtxfee`, or no fee when its notes are worth
no more than the fee, and expires 15 blocks after it is made.
* Only the notes a round actually spends are locked while it proves, so sends made meanwhile still see the rest of
the wallet.
* All spends of one transaction must use one anchor (Sapling tree root). An address's spends use the tip's root,
where the wallet keeps its witnesses, or else the chain anchor most of its planned notes are at. A note without a
witness, or whose witness root the chain never had (a desynced witness), is skipped and the round goes on without
it; so is, until a later round, a note whose witness is at another real anchor. Each round logs how many it
skipped (`last_round.skipped_notes`).
* If one transaction fails to build or is not accepted, the rest of that address's transactions are skipped for
the round, but the other addresses still get theirs; `last_round.error` gives the first failure.
* With the defaults, an address over the threshold loses 27 to 42 notes per round, and a round runs every 25 blocks.
* dragonxd runs one async operation at a time. So that a `z_sendmany` (or any other async RPC) made during a round
does not wait for all of it, the round ends after its current transaction when another operation is queued
(`last_round.yielded`); the notes it did not get to are unlocked and taken up by the next round. A node that is
asked to stop also ends the round after the current transaction.
### Turning it on
1. Add the following to the conf file as per the Pre-Step.
```
consolidation=1
```
@@ -50,10 +85,35 @@ Zsweep is when you sweep numerous zutxos into one z-address that you configure.
| Consolidation Option Name| Details of what it does |
|--------------------------|-------------------------|
| consolidationtxfee=0 | The default consolidation fee is 10000 puposhis or 0.0001 DRAGONX, the default for all transactions. To use fee=0 for consolidation transactions, set this option. |
| consolidatesaplingaddress=zs1... | Default of consolidation is set to all, but you can set this option if you have one specific z-address (zs1... is a placeholder for this documentation) that you want to only consolidate to. |
| consolidationinterval=25 | Blocks between rounds (default 25, minimum 5; smaller values are raised to 5). |
| consolidationthreshold=25 | Only addresses with more than this many eligible notes are consolidated (default 25, minimum 1). |
| consolidationbatchsize=15 | Most notes one consolidation transaction spends (default 15, clamped to 2..50). |
| consolidationmaxtxs=3 | Most consolidation transactions per address per round (default 3, clamped to 1..100). |
| consolidationtxfee=10000 | Fee in puposhis per consolidation transaction (default 10000 = 0.0001 DRAGONX; allowed range 1000..10000000, anything else falls back to the default). |
| consolidatesaplingaddress=zs1... | Only consolidate this address (may be given several times). The default is every address the wallet can spend. With `consolidation=1` the wallet must hold the address's spending key, or dragonxd refuses to start; with it off, such an address is ignored with a warning (and `z_consolidate` works on all addresses unless given its own). |
1. The following DragonX RPC will let you view your consolidation configuration options and run-time stats at the command line: `dragonx-cli z_sweepstatus`
1. `dragonx-cli z_consolidationstatus` shows the settings, whether a round is running, when the next one is due,
cumulative totals (`notes_consolidated`, `amount_consolidated` in puposhis), the last round (`last_round`: height,
time, txids, notes merged, amount merged, notes skipped, error) and, when rounds can't run, why
(`disabled_reason`). `dragonx-cli z_consolidationstatus true` also counts the eligible notes of every address and
lists which are over the threshold (this walks the whole wallet, so it is only done on request).
### Consolidating on demand
`dragonx-cli z_consolidate` runs one round now with the current settings, also when `consolidation` is off, so a CLI
miner can clean up whenever it suits them. It takes optional overrides, in order: fee (in DRAGONX), batch size,
maximum transactions per address, and a JSON array of addresses; pass `null` to keep a setting, e.g.
`dragonx-cli z_consolidate null 50 20 '["zs1..."]'`. Its fee is in DRAGONX like `z_sendmany`'s, while `consolidationtxfee` and the amounts in
`z_consolidationstatus` are in puposhis. It returns an operation id; `z_getoperationstatus` /
`z_getoperationresult` give the result. It refuses while the node is syncing, while the wallet is locked, and while a
consolidation, zsweep or auto-shield round is in flight.
### Off, but suggested
When consolidation is off and some address has more notes than the threshold, dragonxd logs once after loading the
wallet: `N addresses have more than 25 spendable notes; consider -consolidation=1 or z_consolidate`.
`z_autoshieldstatus` then reports `consolidation_suggested: true`, and `z_consolidationstatus true` reports
`consolidation_suggested` and `consolidation_suggested_count`.
## Zsweep & Consolidation Together
@@ -66,6 +126,11 @@ Zsweep is when you sweep numerous zutxos into one z-address that you configure.
1. Then follow along with the zsweep section above if you want to set specific options for the zsweep behavior.
1. With zsweep on, consolidation only works on the sweep address: a `consolidatesaplingaddress` other than the
sweep address is refused at startup (with `consolidation=0` it is replaced by the sweep address, with a warning),
and `z_consolidate` refuses any other address too. Sweep and consolidation never run at the same time, and a
sweep is not started when a consolidation round is due within 5 blocks.
### Copyright
The DragonX Developers, jahway603, and The Hush Developers
@@ -73,4 +138,3 @@ The DragonX Developers, jahway603, and The Hush Developers
### License
GPLv3
+5 -1
View File
@@ -12,6 +12,7 @@ hush_gtest_SOURCES = \
gtest/main.cpp \
gtest/utils.cpp \
gtest/test_randomx_preverify.cpp \
gtest/test_randomx_heightrecover.cpp \
gtest/test_hdtransparent.cpp \
gtest/test_mnemonic_compat.cpp \
gtest/test_stratum_jobid.cpp \
@@ -20,7 +21,10 @@ 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 \
gtest/test_wallet_shutdownsave.cpp \
gtest/test_wallet_witnessroots.cpp
hush_gtest_CPPFLAGS = $(AM_CPPFLAGS) -DMULTICORE -fopenmp -DBINARY_OUTPUT -DCURVE_ALT_BN128 -DSTATIC $(BITCOIN_INCLUDES)
hush_gtest_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS)
+116
View File
@@ -0,0 +1,116 @@
// Copyright (c) 2024-2026 The DragonX developers
// Distributed under the GPLv3 software license, see the accompanying
// file COPYING or https://www.gnu.org/licenses/gpl-3.0.en.html
//
// Regression guard for the hush_checkPOW height-0 RandomX fix. A block arriving over P2P reaches
// hush_checkPOW with height==0; the first CheckRandomXSolution runs at height 0 (where
// RandomXValidationRequired is false, so it is skipped), the real height is then recovered from
// hashPrevBlock, and the fix re-runs CheckRandomXSolution at that height. Without the fix a block
// with a forged RandomX solution would be accepted on that path. We prove: (1) CheckRandomXSolution
// is skipped at height 0 but rejects the forged solution at the real height; (2) hush_checkPOW lets
// the forged block through only while the parent is unknown (height cannot be recovered), and
// rejects it once the parent is known and the height recovers -- which is exactly what the fix does.
#include <gtest/gtest.h>
#include <cstring>
#include <string>
#include "arith_uint256.h"
#include "chain.h"
#include "chainparams.h"
#include "chainparamsbase.h"
#include "pow.h"
#include "primitives/block.h"
#include "primitives/transaction.h"
#include "RandomX/src/randomx.h"
#include "hush_defs.h"
#include "main.h"
#include "sync.h"
#include "uint256.h"
extern int32_t HUSH_LOADINGBLOCKS;
extern bool fCheckpointsEnabled;
int32_t hush_checkPOW(int32_t slowflag, CBlock *pblock, int32_t height);
TEST(RandomXHeightRecover, ForgedSolutionRejectedOnceHeightIsRecovered)
{
// hush_checkPOW calls Params(); give it a selected chain. Done before the ASSETCHAINS_* globals
// below so params init cannot clobber them. RandomX is enforced via ASSETCHAINS_RANDOMX_VALIDATION,
// not the chain's activation height, so MAIN's high activation height is irrelevant here.
SelectParams(CBaseChainParams::MAIN);
// Save the globals this test flips.
uint32_t sAlgo = ASSETCHAINS_ALGO, sRx = ASSETCHAINS_RANDOMX;
int32_t sVal = ASSETCHAINS_RANDOMX_VALIDATION, sLoad = HUSH_LOADINGBLOCKS;
bool sCkpt = fCheckpointsEnabled;
char sSym[sizeof(SMART_CHAIN_SYMBOL)];
std::memcpy(sSym, SMART_CHAIN_SYMBOL, sizeof sSym);
ASSETCHAINS_RANDOMX = 2; // a distinct nonzero algo id
ASSETCHAINS_ALGO = ASSETCHAINS_RANDOMX;
ASSETCHAINS_RANDOMX_VALIDATION = 1; // enforce from height 1
HUSH_LOADINGBLOCKS = 0; // not initial-load (else RandomX skipped)
fCheckpointsEnabled = false; // avoid the below-checkpoint skip
std::strcpy(SMART_CHAIN_SYMBOL, "DRGXTEST"); // non-empty: not the default regtest chain
// A block with a FORGED RandomX solution (all zero bytes -- overwhelmingly not the real hash).
CBlock block;
block.nVersion = 4;
block.hashPrevBlock = uint256S("0x0000000000000000000000000000000000000000000000000000000000000011");
block.hashMerkleRoot = uint256S("0x0000000000000000000000000000000000000000000000000000000000000022");
block.hashFinalSaplingRoot = uint256S("0x0000000000000000000000000000000000000000000000000000000000000033");
block.nTime = 1700000000;
block.nBits = 0x200f0f0f;
block.nNonce = uint256S("0x0000000000000000000000000000000000000000000000000000000000000001");
block.nSolution.assign(RANDOMX_HASH_SIZE, 0);
// hush_block2pubkey33 reads vtx[0]; give the block a minimal coinbase so it is never a null deref.
CMutableTransaction cb;
cb.vin.resize(1);
cb.vin[0].prevout.SetNull();
cb.vout.resize(1);
block.vtx.push_back(CTransaction(cb));
// Grind the nonce so the block's SHA target check passes. Then the ONLY thing that can reject it
// in hush_checkPOW at the recovered height is the RandomX re-check, so the test isolates the fix
// (without the fix the block would fall through the target check and be accepted).
arith_uint256 bnTarget;
bool neg, over;
bnTarget.SetCompact(block.nBits, &neg, &over);
for (uint32_t n = 1; n < 100000; n++) {
block.nNonce = ArithToUint256(arith_uint256(n));
if (UintToArith256(block.GetHash()) <= bnTarget) break;
}
ASSERT_LE(UintToArith256(block.GetHash()), bnTarget) << "could not grind a passing SHA target";
// (1) The primitive the fix relies on: skipped at height 0, rejects the forgery at the real height.
EXPECT_TRUE(CheckRandomXSolution(&block, 0)) << "RandomX must be skipped at height 0";
EXPECT_FALSE(CheckRandomXSolution(&block, 10)) << "a forged solution must be rejected at its real height";
// (2a) Parent unknown: hush_checkPOW cannot recover the height, so it stays 0 and the block is NOT
// rejected here -- the pre-fix behavior for an unrecoverable height.
EXPECT_GE(hush_checkPOW(0, &block, 0), 0)
<< "with no recoverable height the forged block is not rejected on this path";
// (2b) Parent known at height 9: the height recovers to 10 and the fix re-checks RandomX -> rejected.
CBlockIndex prev;
prev.SetHeight(9);
uint256 prevHash = block.hashPrevBlock;
prev.phashBlock = &prevHash;
{
LOCK(cs_main);
mapBlockIndex[prevHash] = &prev;
}
EXPECT_LT(hush_checkPOW(0, &block, 0), 0)
<< "once the height recovers, the fix must reject the forged RandomX solution";
{
LOCK(cs_main);
mapBlockIndex.erase(prevHash);
}
// Restore.
ASSETCHAINS_ALGO = sAlgo; ASSETCHAINS_RANDOMX = sRx;
ASSETCHAINS_RANDOMX_VALIDATION = sVal; HUSH_LOADINGBLOCKS = sLoad;
fCheckpointsEnabled = sCkpt;
std::memcpy(SMART_CHAIN_SYMBOL, sSym, sizeof sSym);
}
+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);
}
+20
View File
@@ -56,3 +56,23 @@ TEST_F(WalletDbEnv, FailedCheckpointKeepsTheLogs) {
env.Flush(true);
EXPECT_TRUE(boost::filesystem::exists(Log()));
}
// The shutdown wallet save asks before writing: a failed flush or a panicked environment means the logs are what
// recovery needs, and a large write into it would fail or make things worse.
TEST_F(WalletDbEnv, HealthyUntilAFlushFailsOrTheEnvironmentPanics) {
EXPECT_TRUE(env.IsHealthy());
env.Flush(false);
EXPECT_TRUE(env.IsHealthy());
ASSERT_EQ(0, env.dbenv->set_flags(DB_PANIC_ENVIRONMENT, 1));
EXPECT_FALSE(env.IsHealthy());
}
TEST_F(WalletDbEnv, UnhealthyAfterAFailedCheckpoint) {
env.CheckpointLSN("no-such-file.dat"); // lsn_reset fails
EXPECT_FALSE(env.IsHealthy());
}
TEST(WalletDbEnvNotOpen, NotOpenIsHealthy) {
CDBEnv env;
EXPECT_TRUE(env.IsHealthy());
}
+383
View File
@@ -0,0 +1,383 @@
// Copyright (c) 2016-2024 The Hush developers
// Distributed under the GPLv3 software license, see the accompanying
// file COPYING or https://www.gnu.org/licenses/gpl-3.0.en.html
#include <gtest/gtest.h>
#include <string>
#include <boost/filesystem.hpp>
#include "chain.h"
#include "chainparams.h"
#include "util.h"
#include "validationinterface.h"
#include "main.h"
#include "wallet/db.h"
#include "wallet/wallet.h"
#include "wallet/walletdb.h"
namespace {
std::string Reason(CWallet& wallet, bool fInitCompleted, bool fChainstateFlushed = true)
{
const char* reason = wallet.ShutdownSaveSkipReason(fInitCompleted, fChainstateFlushed);
return reason ? reason : "";
}
// fWalletNotifyFailed is process-wide, and other suites drive NotifyWalletsOrShutdown's failure path.
class WalletShutdownSave : public ::testing::Test {
protected:
void SetUp() override { fWalletNotifyFailed = false; }
void TearDown() override { fWalletNotifyFailed = false; }
};
class SaveWallet : public CWallet {
public:
explicit SaveWallet(const std::string& strFile = "") : CWallet(strFile) {}
template <typename WalletDB>
bool SetBestChainWith(WalletDB& walletdb, const CBlockLocator& loc) { return CWallet::SetBestChainWith(walletdb, loc); }
void DecrementNoteWitnesses(const CBlockIndex* pindex) { CWallet::DecrementNoteWitnesses(pindex); }
};
// Each step of SetBestChainINTERNAL's transaction can be made to fail.
struct FakeWalletDB {
bool fBegin = true, fWriteTx = true, fCacheSize = true, fBestBlock = true, fCommit = true;
int nAborts = 0;
CBlockLocator written;
bool TxnBegin() { return fBegin; }
bool TxnCommit() { return fCommit; }
bool TxnAbort() { nAborts++; return true; }
bool WriteTx(uint256, const CWalletTx&) { return fWriteTx; }
bool WriteWitnessCacheSize(int64_t) { return fCacheSize; }
bool WriteBestBlock(const CBlockLocator& loc) { written = loc; return fBestBlock; }
};
// A wallet with one note, so the transaction writes a tx.
void AddNote(CWallet& wallet)
{
CMutableTransaction mtx;
mtx.nLockTime = 4242;
CWalletTx wtx(&wallet, CTransaction(mtx));
SaplingNoteData nd(uint256S("01"), uint256S("02"));
wtx.mapSaplingNoteData[SaplingOutPoint(wtx.GetHash(), 0)] = nd;
LOCK(wallet.cs_wallet);
ASSERT_TRUE(wallet.AddToWallet(wtx, true, nullptr));
}
}
// A startup that failed or was cut short never writes: its threads were not joined, and an unset wallet
// tip would make SetBestChain stamp the chain tip over an interrupted rescan's checkpoint.
TEST_F(WalletShutdownSave, SkipsWhenStartupDidNotComplete) {
CWallet wallet;
CBlockIndex tip;
wallet.SetWalletTip(&tip);
EXPECT_EQ("startup did not complete", Reason(wallet, false));
EXPECT_EQ("", Reason(wallet, true));
}
TEST_F(WalletShutdownSave, SkipsWithoutAWalletTip) {
CWallet wallet;
EXPECT_EQ("the wallet tip is not set", Reason(wallet, true));
}
// A shutdown caused by the wallet failing on a block must not write the whole wallet into that database.
TEST_F(WalletShutdownSave, SkipsAfterAWalletFailure) {
CWallet wallet;
CBlockIndex tip;
wallet.SetWalletTip(&tip);
fWalletNotifyFailed = true;
EXPECT_EQ("the wallet failed to process a block", Reason(wallet, true));
fWalletNotifyFailed = false;
EXPECT_EQ("", Reason(wallet, true));
}
TEST_F(WalletShutdownSave, CanBeTurnedOff) {
CWallet wallet;
CBlockIndex tip;
wallet.SetWalletTip(&tip);
mapArgs["-walletsaveatshutdown"] = "0";
EXPECT_EQ("disabled by -walletsaveatshutdown=0", Reason(wallet, true));
mapArgs["-walletsaveatshutdown"] = "1";
EXPECT_EQ("", Reason(wallet, true));
mapArgs.erase("-walletsaveatshutdown");
EXPECT_EQ("", Reason(wallet, true)) << "on by default";
}
// A failed chainstate flush (typically a full disk) leaves the block the locator would name possibly missing from the
// chainstate on disk.
TEST_F(WalletShutdownSave, SkipsWhenTheChainstateFlushFailed) {
CWallet wallet;
CBlockIndex tip;
wallet.SetWalletTip(&tip);
EXPECT_EQ("the chainstate flush failed", Reason(wallet, true, false));
EXPECT_EQ("", Reason(wallet, true, true));
}
// Once a save (or init, finding nothing to rescan) has recorded the wallet's block, a shutdown writes again
// only if the wallet moved to another block or its note state changed.
TEST_F(WalletShutdownSave, SkipsWhenNothingChangedSinceTheLastSave) {
CWallet wallet;
CBlockIndex a, b;
a.SetHeight(10);
b.SetHeight(11);
b.pprev = &a;
wallet.SetWalletTip(&a);
EXPECT_EQ("", Reason(wallet, true));
wallet.MarkStatePersisted(&a);
EXPECT_EQ("nothing changed since the last save", Reason(wallet, true));
wallet.SetWalletTip(&b);
EXPECT_EQ("", Reason(wallet, true)) << "a new block";
wallet.MarkStatePersisted(&b);
EXPECT_EQ("nothing changed since the last save", Reason(wallet, true));
wallet.ClearNoteWitnessCache();
EXPECT_EQ("", Reason(wallet, true)) << "witnesses changed at the same block";
wallet.MarkStatePersisted(&b);
EXPECT_EQ("nothing changed since the last save", Reason(wallet, true));
// A save recorded at another block than the one the wallet is at does not count.
wallet.MarkStatePersisted(&a);
EXPECT_EQ("", Reason(wallet, true));
}
// A rescan that did not complete (abortrescan, a stop, a throw) left the locator on disk below the wallet tip: the
// next start resumes from there only if the shutdown does not stamp the tip over it. A later scan clears that once it
// covers the range from where the locator stands.
TEST_F(WalletShutdownSave, SkipsAfterAnIncompleteRescan) {
const std::string incomplete = "a rescan did not complete; the next start resumes it from the locator it left";
CWallet wallet;
CBlockIndex tip;
tip.SetHeight(841);
wallet.SetWalletTip(&tip);
// Interrupted after a checkpoint at 833.
EXPECT_EQ(-1, wallet.NoteRescanStarted(821));
EXPECT_EQ(incomplete, Reason(wallet, true)) << "while it runs";
wallet.NoteRescanInterrupted(833);
EXPECT_EQ(incomplete, Reason(wallet, true));
// A complete scan from above the checkpoint leaves 834.. unscanned from where the disk stands.
int before = wallet.NoteRescanStarted(833);
EXPECT_EQ(833, before);
wallet.NoteRescanCompleted(835, before);
EXPECT_EQ(incomplete, Reason(wallet, true));
// One from the block after it covers everything.
before = wallet.NoteRescanStarted(833);
wallet.NoteRescanCompleted(834, before);
EXPECT_EQ("", Reason(wallet, true));
// A scan that throws never reports an end.
wallet.NoteRescanStarted(841);
EXPECT_EQ(incomplete, Reason(wallet, true));
before = wallet.NoteRescanStarted(841);
wallet.NoteRescanCompleted(100, before);
EXPECT_EQ("", Reason(wallet, true));
// With nothing interrupted before it, a complete scan is what was asked for, wherever it starts
// (z_importkey with a start height above the locator).
before = wallet.NoteRescanStarted(821);
EXPECT_EQ(-1, before);
wallet.NoteRescanCompleted(840, before);
EXPECT_EQ("", Reason(wallet, true));
// No locator on disk: resume from genesis.
wallet.NoteRescanStarted(-1);
wallet.NoteRescanInterrupted(-1);
EXPECT_EQ(incomplete, Reason(wallet, true));
before = wallet.NoteRescanStarted(-1);
EXPECT_EQ(0, before);
wallet.NoteRescanCompleted(2, before);
EXPECT_EQ(incomplete, Reason(wallet, true));
wallet.NoteRescanCompleted(1, before);
EXPECT_EQ("", Reason(wallet, true));
}
// The save writes through the real wallet database (an in-memory BDB environment here), and a skip writes nothing.
class WalletShutdownSaveDb : public WalletShutdownSave {
protected:
void SetUp() override {
WalletShutdownSave::SetUp();
bitdb.MakeMock();
CWalletDB create(strFile, "cr+");
}
void TearDown() override {
bitdb.Flush(true);
bitdb.Reset();
WalletShutdownSave::TearDown();
}
const std::string strFile = "shutdownsave.dat";
bool ReadBestBlock(CBlockLocator& loc) {
CWalletDB walletdb(strFile, "r");
return walletdb.ReadBestBlock(loc);
}
};
TEST_F(WalletShutdownSaveDb, SavesTheWalletTipAndRecordsIt) {
CWallet wallet(strFile);
AddNote(wallet);
uint256 hash = uint256S("0abc");
CBlockIndex tip;
tip.phashBlock = &hash;
wallet.SetWalletTip(&tip);
{
LOCK(cs_main);
wallet.PersistStateAtShutdown(true, true);
}
CBlockLocator loc;
ASSERT_TRUE(ReadBestBlock(loc));
ASSERT_FALSE(loc.vHave.empty());
EXPECT_EQ(hash, loc.vHave.front());
EXPECT_EQ("nothing changed since the last save", Reason(wallet, true));
}
TEST_F(WalletShutdownSaveDb, SkippedSaveWritesNothing) {
CWallet wallet(strFile);
AddNote(wallet);
uint256 hash = uint256S("0abc");
CBlockIndex tip;
tip.phashBlock = &hash;
wallet.SetWalletTip(&tip);
{
LOCK(cs_main);
wallet.PersistStateAtShutdown(false, true);
wallet.PersistStateAtShutdown(true, false);
wallet.NoteRescanStarted(0);
wallet.PersistStateAtShutdown(true, true);
}
CBlockLocator loc;
EXPECT_FALSE(ReadBestBlock(loc));
EXPECT_EQ("a rescan did not complete; the next start resumes it from the locator it left", Reason(wallet, true));
}
// Opening the wallet database can throw (an environment or file that cannot be opened). Shutdown() has no handler,
// so the save must catch it, record nothing, and return.
TEST_F(WalletShutdownSave, AFailedOpenDoesNotEscape) {
SelectParams(CBaseChainParams::MAIN);
const boost::filesystem::path dir = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path("shutdownsave-%%%%%%%%");
const bool hadDatadir = mapArgs.count("-datadir") > 0;
const std::string oldDatadir = hadDatadir ? mapArgs["-datadir"] : "";
boost::filesystem::create_directories(dir);
mapArgs["-datadir"] = dir.string();
ClearDatadirCache();
// The environment's log directory is a regular file, so opening the environment throws.
{
FILE* f = fopen((GetDataDir() / "database").string().c_str(), "wb");
ASSERT_TRUE(f != nullptr);
fclose(f);
}
CWallet wallet("wallet.dat");
uint256 hash = uint256S("0123");
CBlockIndex tip;
tip.phashBlock = &hash;
wallet.SetWalletTip(&tip);
ASSERT_EQ("", Reason(wallet, true));
{
LOCK(cs_main);
EXPECT_NO_THROW(wallet.PersistStateAtShutdown(true, true));
}
EXPECT_EQ("", Reason(wallet, true)) << "a failed save must not be recorded as one";
if (hadDatadir) mapArgs["-datadir"] = oldDatadir; else mapArgs.erase("-datadir");
ClearDatadirCache();
boost::filesystem::remove_all(dir);
}
// The shutdown save may skip only what a committed write saved: a write that failed at any step records nothing.
TEST_F(WalletShutdownSave, RecordsOnlyACommittedWrite) {
SaveWallet wallet;
AddNote(wallet);
uint256 hash = uint256S("0abc");
CBlockIndex tip;
tip.phashBlock = &hash;
wallet.SetWalletTip(&tip);
CBlockLocator chainTip(std::vector<uint256>{uint256S("0def")});
for (int step = 0; step < 5; step++) {
FakeWalletDB db;
bool* steps[5] = {&db.fBegin, &db.fWriteTx, &db.fCacheSize, &db.fBestBlock, &db.fCommit};
*steps[step] = false;
EXPECT_FALSE(wallet.SetBestChainWith(db, chainTip)) << "step " << step;
EXPECT_EQ("", Reason(wallet, true)) << "step " << step;
EXPECT_EQ(step >= 1 && step <= 3 ? 1 : 0, db.nAborts) << "step " << step;
}
FakeWalletDB db;
EXPECT_TRUE(wallet.SetBestChainWith(db, chainTip));
EXPECT_EQ("nothing changed since the last save", Reason(wallet, true));
ASSERT_FALSE(db.written.vHave.empty());
EXPECT_EQ(hash, db.written.vHave.front()) << "the wallet tip is stamped, not the chain tip passed in";
}
// Before init seeds the wallet tip, the block recorded is the one the locator passed in names.
TEST_F(WalletShutdownSave, RecordsTheLocatorsBlockWithoutAWalletTip) {
SaveWallet wallet;
CBlock block;
block.nTime = 1720000000;
CBlockIndex index(block);
{
LOCK(cs_main);
index.phashBlock = &mapBlockIndex.insert(std::make_pair(block.GetHash(), &index)).first->first;
}
FakeWalletDB db;
EXPECT_TRUE(wallet.SetBestChainWith(db, CBlockLocator(std::vector<uint256>{block.GetHash()})));
EXPECT_EQ(block.GetHash(), db.written.vHave.front());
wallet.SetWalletTip(&index);
EXPECT_EQ("nothing changed since the last save", Reason(wallet, true));
LOCK(cs_main);
mapBlockIndex.erase(block.GetHash());
}
// Every change to what SetBestChain writes makes the next shutdown write again.
TEST_F(WalletShutdownSave, NoteChangesNeedASave) {
SaveWallet wallet;
CBlockIndex tip;
tip.SetHeight(5);
wallet.SetWalletTip(&tip);
wallet.MarkStatePersisted(&tip);
ASSERT_EQ("nothing changed since the last save", Reason(wallet, true));
// As set from the chain parameters at startup; DecrementNoteWitnesses asserts it was.
extern unsigned int WITNESS_CACHE_SIZE;
const unsigned int nSavedCacheSize = WITNESS_CACHE_SIZE;
WITNESS_CACHE_SIZE = MAX_REORG_LENGTH + 10;
wallet.DecrementNoteWitnesses(&tip);
WITNESS_CACHE_SIZE = nSavedCacheSize;
EXPECT_EQ("", Reason(wallet, true)) << "a disconnected block";
wallet.MarkStatePersisted(&tip);
wallet.ClearNoteWitnessCache();
EXPECT_EQ("", Reason(wallet, true)) << "witnesses cleared";
}
// Adding a note-bearing tx, or changing one, is a change to save; re-adding one unchanged (as
// ReacceptWalletTransactions does for every unconfirmed tx at each start) is not, nor is a tx without notes.
TEST_F(WalletShutdownSaveDb, AddingANoteNeedsASave) {
CWallet wallet(strFile);
CBlockIndex tip;
wallet.SetWalletTip(&tip);
wallet.MarkStatePersisted(&tip);
CWalletDB walletdb(strFile, "r+");
LOCK(wallet.cs_wallet);
CMutableTransaction mtx;
mtx.nLockTime = 777;
CWalletTx plain(&wallet, CTransaction(mtx));
ASSERT_TRUE(wallet.AddToWallet(plain, false, &walletdb));
EXPECT_EQ("nothing changed since the last save", Reason(wallet, true)) << "no notes";
mtx.nLockTime = 778;
CWalletTx wtx(&wallet, CTransaction(mtx));
wtx.mapSaplingNoteData[SaplingOutPoint(wtx.GetHash(), 0)] = SaplingNoteData(uint256S("01"), uint256S("02"));
ASSERT_TRUE(wallet.AddToWallet(wtx, false, &walletdb));
EXPECT_EQ("", Reason(wallet, true)) << "a new note";
wallet.MarkStatePersisted(&tip);
ASSERT_TRUE(wallet.AddToWallet(wtx, false, &walletdb));
EXPECT_EQ("nothing changed since the last save", Reason(wallet, true)) << "the same tx again";
}
+475
View File
@@ -0,0 +1,475 @@
// Copyright (c) 2016-2024 The Hush developers
// Distributed under the GPLv3 software license, see the accompanying
// file COPYING or https://www.gnu.org/licenses/gpl-3.0.en.html
#include <gtest/gtest.h>
#include <deque>
#include <map>
#include <stdexcept>
#include <boost/filesystem.hpp>
#include "chain.h"
#include "chainparams.h"
#include "coins.h"
#include "init.h"
#include "main.h"
#include "primitives/block.h"
#include "primitives/transaction.h"
#include "uint256.h"
#include "util.h"
#include "validationinterface.h"
#include "wallet/wallet.h"
#include "zcash/zip32.h"
extern std::atomic<bool> fRequestShutdown;
// VerifyAndSetInitialWitness computes the witness roots it checks on worker threads before its serial loop. These
// tests run the same synthetic wallet with one thread and with several and compare every note's resulting state.
namespace {
class RootsWallet : public CWallet {
public:
int VerifyAndSetInitialWitness(const CBlockIndex* pindex, bool witnessOnly) {
return CWallet::VerifyAndSetInitialWitness(pindex, witnessOnly);
}
};
// An active chain of nBlocks blocks (heights 0..nBlocks-1) whose block 1 holds the given txs, with a chosen
// hashFinalSaplingRoot per height. Undone on destruction: chainActive, mapBlockIndex and pcoinsTip are process-wide.
struct RootsChain {
std::deque<CBlock> blocks;
std::deque<CBlockIndex> index;
CBlockIndex* savedTip;
CCoinsView coinsBase;
CCoinsViewCache coins{&coinsBase};
CCoinsViewCache* savedCoinsTip;
RootsChain(int nBlocks, const std::vector<CTransaction>& inBlock1, const std::map<int, uint256>& roots) {
LOCK(cs_main);
savedTip = chainActive.Tip();
savedCoinsTip = pcoinsTip;
pcoinsTip = &coins;
for (int h = 0; h < nBlocks; h++) {
blocks.emplace_back();
CBlock& block = blocks.back();
block.nTime = 1710000000 + h;
block.nNonce = uint256S(strprintf("%x", 0x900 + h));
if (h > 0)
block.hashPrevBlock = blocks[h - 1].GetHash();
if (h == 1)
block.vtx = inBlock1;
block.hashMerkleRoot = block.BuildMerkleTree();
index.emplace_back(block);
CBlockIndex& bi = index.back();
bi.SetHeight(h);
bi.pprev = h > 0 ? &index[h - 1] : nullptr;
std::map<int, uint256>::const_iterator it = roots.find(h);
if (it != roots.end())
bi.hashFinalSaplingRoot = it->second;
bi.phashBlock = &mapBlockIndex.insert(std::make_pair(block.GetHash(), &bi)).first->first;
}
chainActive.SetTip(&index.back());
}
~RootsChain() {
LOCK(cs_main);
chainActive.SetTip(savedTip);
for (const CBlock& block : blocks)
mapBlockIndex.erase(block.GetHash());
pcoinsTip = savedCoinsTip;
}
};
libzcash::SaplingExtendedSpendingKey TestKey()
{
std::vector<unsigned char, secure_allocator<unsigned char>> raw(32, 0x5a);
HDSeed seed(raw);
return libzcash::SaplingExtendedSpendingKey::Master(seed);
}
std::vector<CTransaction> Txs(int n)
{
std::vector<CTransaction> txs;
for (int i = 0; i < n; i++) {
CMutableTransaction mtx;
mtx.nLockTime = 1000 + i; // distinct txids
txs.push_back(CTransaction(mtx));
}
return txs;
}
// Witnesses of nNotes positions in one tree: all share the tree's root. Each is a distinct witness object.
std::vector<SaplingWitness> Witnesses(int nNotes, int salt, uint256& rootOut)
{
SaplingMerkleTree tree;
std::vector<SaplingWitness> ws;
for (int i = 0; i < nNotes; i++) {
uint256 cm = uint256S(strprintf("%x%04x", salt, i + 1));
tree.append(cm);
for (SaplingWitness& w : ws)
w.append(cm);
ws.push_back(tree.witness());
}
rootOut = tree.root();
return ws;
}
// NO_NULLIFIER_VALID: a valid witness at height 2 but no nullifier yet, which only a sibling's reseed gives it.
enum Kind { VALID_BELOW_TIP, VALID_AT_TIP, AHEAD_OF_CHAIN, ALREADY_VALIDATED, WRONG_ROOT, NOT_IN_CHAIN,
NO_NULLIFIER_VALID };
struct Fixture {
std::vector<CTransaction> txs;
std::map<int, uint256> roots;
std::vector<SaplingWitness> wBelow, wAt;
int nTxs;
};
// Fills the wallet: tx i gets notes of the kinds kinds(i) returns, in output order.
template <typename KindsOf>
void Fill(RootsWallet& wallet, const Fixture& fx, const RootsChain& chain, KindsOf kinds)
{
auto sk = TestKey();
auto ivk = sk.expsk.full_viewing_key().in_viewing_key();
LOCK2(cs_main, wallet.cs_wallet);
ASSERT_TRUE(wallet.AddSaplingZKey(sk, sk.DefaultAddress()));
ASSERT_TRUE(wallet.HaveSaplingFullViewingKey(ivk));
size_t nBelow = 0, nAt = 0;
for (int i = 0; i < fx.nTxs; i++) {
const CTransaction& tx = fx.txs[i];
CWalletTx wtx(&wallet, tx);
std::vector<Kind> ks = kinds(i);
mapSaplingNoteData_t notes;
for (size_t n = 0; n < ks.size(); n++) {
SaplingNoteData nd(ivk, uint256S(strprintf("f%03x%03x", i, (int)n)));
switch (ks[n]) {
case VALID_BELOW_TIP:
nd.witnesses.push_front(fx.wBelow[nBelow++ % fx.wBelow.size()]);
nd.witnessHeight = 2;
break;
case VALID_AT_TIP:
nd.witnesses.push_front(fx.wAt[nAt++ % fx.wAt.size()]);
nd.witnessHeight = 3;
break;
case AHEAD_OF_CHAIN:
nd.witnesses.push_front(fx.wAt[0]);
nd.witnessHeight = 9;
break;
case ALREADY_VALIDATED:
nd.witnesses.push_front(fx.wBelow[0]);
nd.witnessHeight = 2;
nd.witnessRootValidated = true;
break;
case WRONG_ROOT:
nd.witnesses.push_front(fx.wAt[0]); // the tip's tree, checked against block 2's root
nd.witnessHeight = 2;
break;
case NOT_IN_CHAIN:
nd.witnesses.push_front(fx.wBelow[0]);
nd.witnessHeight = 2;
break;
case NO_NULLIFIER_VALID:
nd.witnesses.push_front(fx.wBelow[1]);
nd.witnessHeight = 2;
nd.nullifier = boost::none;
break;
}
notes[SaplingOutPoint(tx.GetHash(), n)] = nd;
}
wtx.mapSaplingNoteData = notes; // the txs carry no outputs; nothing here decrypts
ASSERT_TRUE(wallet.AddToWallet(wtx, true, nullptr));
if (ks.empty() || ks[0] != NOT_IN_CHAIN) {
wallet.mapWallet.at(tx.GetHash()).SetMerkleBranch(chain.blocks[1]);
ASSERT_GT(wallet.mapWallet.at(tx.GetHash()).GetDepthInMainChain(), 0);
}
}
}
// A tx with real Sapling outputs to the test key, which the reseed decrypts to derive nullifiers (it never checks
// the proofs or the value commitments).
CTransaction TxWithOutputs(int nOutputs)
{
auto pa = TestKey().DefaultAddress();
CMutableTransaction mtx;
mtx.fOverwintered = true; // or the outputs are not serialized into the block file
mtx.nVersion = SAPLING_TX_VERSION;
mtx.nVersionGroupId = SAPLING_VERSION_GROUP_ID;
mtx.nLockTime = 5000;
for (int i = 0; i < nOutputs; i++) {
libzcash::SaplingNote note(pa, 1000 + i);
std::array<unsigned char, HUSH_MEMO_SIZE> memo;
memo.fill(0);
auto enc = libzcash::SaplingNotePlaintext(note, memo).encrypt(note.pk_d);
assert(static_cast<bool>(enc));
OutputDescription od;
od.cv = GetRandHash();
od.cm = note.cm().get();
od.ephemeralKey = enc->second.get_epk();
od.encCiphertext = enc->first;
mtx.vShieldedOutput.push_back(od);
}
return CTransaction(mtx);
}
// Block files for the reseed to read, in a temporary datadir. Undone on destruction.
struct BlockFiles {
boost::filesystem::path dir;
bool hadDatadir;
std::string oldDatadir;
BlockFiles() {
SelectParams(CBaseChainParams::MAIN);
dir = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path("witnessroots-%%%%%%%%");
boost::filesystem::create_directories(dir);
hadDatadir = mapArgs.count("-datadir") > 0;
oldDatadir = hadDatadir ? mapArgs["-datadir"] : "";
mapArgs["-datadir"] = dir.string();
ClearDatadirCache();
}
void Write(const CBlock& block, CBlockIndex& index) {
CDiskBlockPos pos(0, index.GetHeight() == 0 ? 0 : (unsigned int)boost::filesystem::file_size(GetBlockPosFilename(CDiskBlockPos(0, 0), "blk")));
ASSERT_TRUE(WriteBlockToDisk(block, pos, Params().MessageStart()));
index.nFile = pos.nFile;
index.nDataPos = pos.nPos;
index.nStatus |= BLOCK_HAVE_DATA;
}
~BlockFiles() {
if (hadDatadir) mapArgs["-datadir"] = oldDatadir; else mapArgs.erase("-datadir");
ClearDatadirCache();
boost::filesystem::remove_all(dir);
}
};
struct NoteState {
bool validated;
int witnessHeight;
size_t nWitnesses;
bool hasNullifier;
bool operator==(const NoteState& o) const {
return validated == o.validated && witnessHeight == o.witnessHeight && nWitnesses == o.nWitnesses &&
hasNullifier == o.hasNullifier;
}
};
std::map<SaplingOutPoint, NoteState> States(RootsWallet& wallet)
{
LOCK(wallet.cs_wallet);
std::map<SaplingOutPoint, NoteState> out;
for (const auto& wtxItem : wallet.mapWallet)
for (const auto& item : wtxItem.second.mapSaplingNoteData)
out[item.first] = {item.second.witnessRootValidated, item.second.witnessHeight,
item.second.witnesses.size(), static_cast<bool>(item.second.nullifier)};
return out;
}
Fixture MakeFixture(int nTxs)
{
Fixture fx;
fx.nTxs = nTxs;
fx.txs = Txs(nTxs);
uint256 rootBelow, rootAt;
fx.wBelow = Witnesses(24, 0xb, rootBelow);
fx.wAt = Witnesses(24, 0xa, rootAt);
fx.roots[2] = rootBelow;
fx.roots[3] = rootAt;
return fx;
}
class WalletWitnessRoots : public ::testing::Test {
protected:
std::string savedThreads;
void SetUp() override {
fRequestShutdown = false;
fWalletNotifyFailed = false; // process-wide; the shutdown-save check below reads it
savedThreads = mapArgs.count("-witnessbuildthreads") ? mapArgs["-witnessbuildthreads"] : "";
}
void TearDown() override {
fRequestShutdown = false;
fWalletNotifyFailed = false;
if (savedThreads.empty())
mapArgs.erase("-witnessbuildthreads");
else
mapArgs["-witnessbuildthreads"] = savedThreads;
}
};
std::vector<Kind> MixedKinds(int i)
{
static const Kind cycle[] = {VALID_BELOW_TIP, VALID_AT_TIP, VALID_BELOW_TIP, AHEAD_OF_CHAIN, ALREADY_VALIDATED,
VALID_AT_TIP};
std::vector<Kind> ks;
for (int n = 0; n < 1 + i % 3; n++)
ks.push_back(cycle[(i + n) % 6]);
return ks;
}
}
// Every note is validated, skipped or deferred exactly as the serial pass does it, and the minimum height
// matches, whether the roots come from one thread or eight.
TEST_F(WalletWitnessRoots, ParallelMatchesSerial) {
Fixture fx = MakeFixture(60);
RootsChain chain(4, fx.txs, fx.roots);
std::map<SaplingOutPoint, NoteState> results[2];
int minHeight[2];
const char* threads[2] = {"1", "8"};
for (int r = 0; r < 2; r++) {
mapArgs["-witnessbuildthreads"] = threads[r];
RootsWallet wallet;
Fill(wallet, fx, chain, MixedKinds);
minHeight[r] = wallet.VerifyAndSetInitialWitness(chainActive.Tip(), false);
results[r] = States(wallet);
}
EXPECT_EQ(minHeight[0], minHeight[1]);
EXPECT_EQ(2, minHeight[0]) << "the lowest witness height among the checked notes";
ASSERT_EQ(results[0].size(), results[1].size());
EXPECT_TRUE(results[0] == results[1]);
// And the outcome is the one the serial rules give for each kind.
std::map<SaplingOutPoint, Kind> kindOf;
for (int i = 0; i < fx.nTxs; i++) {
std::vector<Kind> ks = MixedKinds(i);
for (size_t n = 0; n < ks.size(); n++)
kindOf[SaplingOutPoint(fx.txs[i].GetHash(), n)] = ks[n];
}
int nValidated = 0;
for (const auto& r : results[1]) {
Kind k = kindOf.at(r.first);
bool expectValidated = k != AHEAD_OF_CHAIN;
EXPECT_EQ(expectValidated, r.second.validated) << "kind " << k;
EXPECT_EQ(1u, r.second.nWitnesses);
EXPECT_TRUE(r.second.hasNullifier);
nValidated += r.second.validated && k != ALREADY_VALIDATED;
}
EXPECT_GT(nValidated, 40) << "enough roots to spread over the threads";
}
// With witnessOnly the already-validated notes are skipped outright; the rest is the same.
TEST_F(WalletWitnessRoots, ParallelMatchesSerialWitnessOnly) {
Fixture fx = MakeFixture(40);
RootsChain chain(4, fx.txs, fx.roots);
std::map<SaplingOutPoint, NoteState> results[2];
int minHeight[2];
const char* threads[2] = {"1", "6"};
for (int r = 0; r < 2; r++) {
mapArgs["-witnessbuildthreads"] = threads[r];
RootsWallet wallet;
Fill(wallet, fx, chain, MixedKinds);
minHeight[r] = wallet.VerifyAndSetInitialWitness(chainActive.Tip(), true);
results[r] = States(wallet);
}
EXPECT_EQ(minHeight[0], minHeight[1]);
EXPECT_TRUE(results[0] == results[1]);
}
// A wrong root sends the note to the reseed, which reads its block from disk; there are no block files here, so
// it throws. Every note before it in wallet order has been decided, every note after it not, identically.
TEST_F(WalletWitnessRoots, MismatchIsHandledInSerialOrder) {
Fixture fx = MakeFixture(30);
RootsChain chain(4, fx.txs, fx.roots);
auto kinds = [](int i) {
std::vector<Kind> ks = MixedKinds(i);
if (i == 17)
ks.push_back(WRONG_ROOT);
return ks;
};
std::map<SaplingOutPoint, NoteState> results[2];
const char* threads[2] = {"1", "8"};
for (int r = 0; r < 2; r++) {
mapArgs["-witnessbuildthreads"] = threads[r];
RootsWallet wallet;
Fill(wallet, fx, chain, kinds);
EXPECT_THROW(wallet.VerifyAndSetInitialWitness(chainActive.Tip(), false), std::runtime_error);
results[r] = States(wallet);
}
EXPECT_TRUE(results[0] == results[1]);
int nDecided = 0, nUndecided = 0;
for (const auto& r : results[1])
(r.second.validated ? nDecided : nUndecided)++;
EXPECT_GT(nDecided, 0);
EXPECT_GT(nUndecided, 0);
}
// A stop requested while the roots are computed ends the pass before it changes anything.
TEST_F(WalletWitnessRoots, ShutdownSkipsThePassUnchanged) {
Fixture fx = MakeFixture(20);
RootsChain chain(4, fx.txs, fx.roots);
mapArgs["-witnessbuildthreads"] = "4";
RootsWallet wallet;
Fill(wallet, fx, chain, MixedKinds);
std::map<SaplingOutPoint, NoteState> before = States(wallet);
fRequestShutdown = true;
EXPECT_EQ(chainActive.Height(), wallet.VerifyAndSetInitialWitness(chainActive.Tip(), false));
EXPECT_TRUE(before == States(wallet));
}
// Notes of a tx that is not in the active chain are never checked.
TEST_F(WalletWitnessRoots, UnconfirmedTxIsNotChecked) {
Fixture fx = MakeFixture(12);
RootsChain chain(4, fx.txs, fx.roots);
mapArgs["-witnessbuildthreads"] = "4";
RootsWallet wallet;
Fill(wallet, fx, chain, [](int i) {
return i % 2 ? std::vector<Kind>{NOT_IN_CHAIN, NOT_IN_CHAIN} : std::vector<Kind>{VALID_BELOW_TIP, VALID_AT_TIP};
});
wallet.VerifyAndSetInitialWitness(chainActive.Tip(), false);
for (int i = 0; i < fx.nTxs; i++)
for (int n = 0; n < 2; n++)
EXPECT_EQ(i % 2 == 0, States(wallet).at(SaplingOutPoint(fx.txs[i].GetHash(), n)).validated);
}
// A reseed that succeeds: the loop goes on past it, and a sibling that had no nullifier, and so no precomputed root,
// gets one from that reseed and is then checked with its root computed inline. Each note ends as the serial rules
// say, whether the other roots come from one thread or eight, and the reseed counts as a change to save.
TEST_F(WalletWitnessRoots, SuccessfulReseedAndItsSibling) {
Fixture fx = MakeFixture(30);
const int iSeeded = 11;
fx.txs[iSeeded] = TxWithOutputs(2);
BlockFiles files;
RootsChain chain(4, fx.txs, fx.roots);
for (int h = 0; h < 4; h++)
files.Write(chain.blocks[h], chain.index[h]);
auto kinds = [&](int i) {
return i == iSeeded ? std::vector<Kind>{WRONG_ROOT, NO_NULLIFIER_VALID} : MixedKinds(i);
};
const SaplingOutPoint seeded(fx.txs[iSeeded].GetHash(), 0), sibling(fx.txs[iSeeded].GetHash(), 1);
std::map<SaplingOutPoint, NoteState> results[2];
int minHeight[2];
const char* threads[2] = {"1", "8"};
for (int r = 0; r < 2; r++) {
mapArgs["-witnessbuildthreads"] = threads[r];
RootsWallet wallet;
Fill(wallet, fx, chain, kinds);
wallet.SetWalletTip(chainActive.Tip());
wallet.MarkStatePersisted(chainActive.Tip());
minHeight[r] = wallet.VerifyAndSetInitialWitness(chainActive.Tip(), false);
results[r] = States(wallet);
const char* reason = wallet.ShutdownSaveSkipReason(true, true);
EXPECT_TRUE(reason == nullptr) << "the reseed changed a witness: " << (reason ? reason : "");
}
EXPECT_EQ(minHeight[0], minHeight[1]);
EXPECT_EQ(1, minHeight[0]) << "the reseeded note's witness is at its own block";
EXPECT_TRUE(results[0] == results[1]);
for (int r = 0; r < 2; r++) {
const NoteState& s = results[r].at(seeded);
EXPECT_FALSE(s.validated);
EXPECT_EQ(1, s.witnessHeight);
EXPECT_EQ(1u, s.nWitnesses);
EXPECT_TRUE(s.hasNullifier);
const NoteState& t = results[r].at(sibling);
EXPECT_TRUE(t.validated) << "the sibling's own witness is valid; threads " << threads[r];
EXPECT_EQ(2, t.witnessHeight);
EXPECT_TRUE(t.hasNullifier);
}
for (int i = 0; i < fx.nTxs; i++) {
if (i == iSeeded)
continue;
std::vector<Kind> ks = MixedKinds(i);
for (size_t n = 0; n < ks.size(); n++)
EXPECT_EQ(ks[n] != AHEAD_OF_CHAIN, results[1].at(SaplingOutPoint(fx.txs[i].GetHash(), n)).validated);
}
}
+16
View File
@@ -1713,6 +1713,22 @@ int32_t hush_checkPOW(int32_t slowflag,CBlock *pblock,int32_t height)
height = pprev->GetHeight() + 1;
if ( height == 0 )
return(0);
// The CheckRandomXSolution() above ran with height==0, where RandomXValidationRequired(0)
// is false, so RandomX was NOT verified. Re-verify now that the real height is recovered
// from hashPrevBlock. Without this, a peer block entering via ProcessNewBlock(0,0,...) (the
// net BLOCK handler, main.cpp) becomes a setBlockIndexCandidate with its PoW never checked
// at its real height: both CheckBlock() calls on that accept path pass fCheckPOW=0, so
// CheckBlockHeader's RandomX check never runs there -- this hush_checkPOW(0,...) is the ONLY
// real-height PoW gate before candidacy. A forged-RandomX fork could then trip the reorg
// guard before the connect-time check rejects it. This is a no-op wherever the first call
// was already a no-op: RandomXValidationRequired() gates on algo, the activation height
// (regtest heights are far below it), HUSH_LOADINGBLOCKS (IBD/reindex), and the last
// in-index checkpoint, and the thread-local fSkipRandomXValidation still skips the miner self-check.
if ( !CheckRandomXSolution(pblock, height) )
{
fprintf(stderr,"hush_checkPOW slowflag.%d ht.%d CheckRandomXSolution failed (post height-recovery)\n",slowflag,height);
return(-1);
}
}
if ( (SMART_CHAIN_SYMBOL[0] != 0) && bhash > bnTarget ) {
+9
View File
@@ -32,6 +32,15 @@
#define CRYPTO555_PUBSECPSTR "038a1bd41a08f38edda51042988022933c5775dfce81f7bae0b32a9179650352ac"
#define CRYPTO555_HUSHADDR "RFetqf8WUfWnwNeXdknkm8ojk7EXnYFzrv"
#define CRYPTO555_RMD160STR "deadbeefbadcaca748c4986b240ff7d7bc3fffb0"
// DragonX: block time at/after which the inherited CRYPTO555/notary transparent-vout exemption on
// the fully-private chain is removed, so those vouts become invalid like any other taddr. Dropping
// a previously-accepted output is a consensus change, so it is activated by block time (same
// mechanism as HUSH_SAPING_ACTIVATION) to let the whole network upgrade before it bites.
// 0xFFFFFFFF is a SENTINEL meaning "never active": the operator sets a real future timestamp once
// the upgrade window has passed AND they have confirmed no active dPoW notarization posts
// transparent notary vouts on-chain (which this ban would otherwise reject). Until then this commit
// is a no-op and changes no validation behavior.
#define DRAGONX_NOTARYVOUT_BAN_TIME 0xFFFFFFFF
#define HUSH_FIRSTFUNGIBLEID 100
#define HUSH_SAPING_ACTIVATION 1544832000 // Dec 15th, 2018
#define HUSH_SAPING_DEADLINE 1550188800 // Feb 15th, 2019
+285 -61
View File
@@ -79,6 +79,7 @@
#include <boost/function.hpp>
#include <boost/interprocess/sync/file_lock.hpp>
#include <boost/thread.hpp>
#include <leveldb/env.h>
#include <chrono>
#include <wolfssl/options.h>
#include <wolfssl/ssl.h>
@@ -99,6 +100,9 @@ extern void hush_init(int32_t height);
CWallet* pwalletMain = NULL;
#endif
bool fFeeEstimatesInitialized = false;
// AppInit2 ran to the end and is returning success, so AppInit joins every thread before Shutdown().
// On any other path Shutdown() runs with threads only interrupted and must not write wallet state.
static std::atomic<bool> fInitCompleted(false);
#ifdef WIN32
// Win32 LevelDB doesn't use file descriptors, and the ones used for
@@ -125,6 +129,152 @@ static const char* DEFAULT_ASMAP_FILENAME="asmap.dat";
// in-memory cache the DB is opened with; the value here does not affect validation.
static const size_t NOTARIZATION_DB_CACHE_BYTES = 100 * 1024 * 1024; // 100 MiB
// How long AppInit2() waits for another process to release notarizations/LOCK before it gives up and
// runs on an in-memory notarizations DB.
static const int NOTARIZATION_LOCK_WAIT_SECONDS = 30;
/**
* Try to take <dbdir>/LOCK with LevelDB's own Env::LockFile, i.e. the same lock DB::Open takes, and
* release it at once. ok() means the lock is free (a missing LOCK file cannot be held). Anything else
* means it could not be taken: usually another process holds it ("Resource temporarily unavailable"),
* but it may also be e.g. a permission error. The caller treats every non-ok status as held, and so
* never moves or wipes the directory on its strength.
*/
static leveldb::Status ProbeLevelDBLock(const boost::filesystem::path& dbdir)
{
const boost::filesystem::path lockpath = dbdir / "LOCK";
boost::system::error_code ec;
if (!boost::filesystem::exists(lockpath, ec))
return leveldb::Status::OK();
leveldb::Env* env = leveldb::Env::Default();
leveldb::FileLock* lock = NULL;
leveldb::Status status = env->LockFile(lockpath.string(), &lock);
if (status.ok())
env->UnlockFile(lock);
return status;
}
/**
* Does <dbdir> hold any LevelDB data, i.e. a non-empty table (.ldb/.sst) or write-ahead log (.log)?
* CURRENT, MANIFEST-*, LOCK and the LOG/LOG.old info logs carry no records. When in doubt (the
* directory cannot be listed) say yes, so the caller keeps a copy.
*/
static bool LevelDBDirHasData(const boost::filesystem::path& dbdir)
{
boost::system::error_code ec;
if (!boost::filesystem::exists(dbdir, ec))
return ec ? true : false;
boost::filesystem::directory_iterator it(dbdir, ec), end;
if (ec)
return true;
for (; it != end; it.increment(ec)) {
if (ec)
return true;
const std::string ext = it->path().extension().string();
if (ext != ".ldb" && ext != ".sst" && ext != ".log")
continue;
boost::system::error_code sizeEc;
const uintmax_t size = boost::filesystem::file_size(it->path(), sizeEc);
if (sizeEc || size > 0)
return true;
}
return false;
}
/**
* Open the notarizations (dPoW) DB. It is non-essential and node-regenerable, so nothing here may fail
* startup (previously any open failure surfaced as a spurious "Error opening block database"):
* - LOCK cannot be taken (typically a previous dragonxd that is still exiting): wait up to
* NOTARIZATION_LOCK_WAIT_SECONDS for it and retry; if it is still held, run this session on an
* in-memory DB and leave the on-disk one alone.
* - otherwise the DB is unreadable (seen: a torn snapshot, 0-byte log -> leveldb "Database I/O error"):
* move it aside under a timestamped notarizations.corrupt-* name, never deleting an earlier copy, and
* create a fresh one. A directory holding no data is recreated in place instead, so a persistent
* failure (e.g. disk full) does not add another empty copy on every start. If even that fails, fall
* back to an in-memory DB.
* The lock is probed only after an open fails, so a holder that exits between the failed open and the
* probe makes the probe report "free" for a DB that is fine. The DB is therefore treated as corrupt only
* when an open fails although the probe just before that open found the lock free.
*/
static NotarizationDB* OpenNotarizationDB(bool fWipe)
{
const boost::filesystem::path ndir = GetDataDir() / "notarizations";
std::string strError;
bool fWaited = false; // the bounded wait for the lock has been used up
bool fProbedFree = false; // the probe right before the last open attempt found the lock free
int64_t nWaitStart = 0;
while (true) {
try {
NotarizationDB* pdb = new NotarizationDB(NOTARIZATION_DB_CACHE_BYTES, false, fWipe);
if (fWaited)
LogPrintf("%s: notarizations/LOCK released after %d s; notarizations DB opened\n", __func__, (GetTimeMillis() - nWaitStart) / 1000);
else if (fProbedFree)
LogPrintf("%s: notarizations DB opened on retry (notarizations/LOCK was released after the first attempt)\n", __func__);
return pdb;
} catch (const std::exception& e) {
strError = e.what();
}
if (fProbedFree)
break; // failed with the lock free beforehand: genuinely unreadable
leveldb::Status lockStatus = ProbeLevelDBLock(ndir);
if (!lockStatus.ok()) {
if (!fWaited) {
LogPrintf("%s: notarizations DB failed to open (%s): notarizations/LOCK could not be taken (%s); waiting for a previous dragonxd to release notarizations/LOCK (up to %d s)\n",
__func__, strError, lockStatus.ToString(), NOTARIZATION_LOCK_WAIT_SECONDS);
fWaited = true;
nWaitStart = GetTimeMillis();
const int64_t nDeadline = nWaitStart + NOTARIZATION_LOCK_WAIT_SECONDS * 1000LL;
while (GetTimeMillis() < nDeadline && !ShutdownRequested()) {
MilliSleep(std::min<int64_t>(1000, std::max<int64_t>(1, nDeadline - GetTimeMillis())));
lockStatus = ProbeLevelDBLock(ndir);
if (lockStatus.ok())
break;
}
}
if (!lockStatus.ok()) {
LogPrintf("%s: notarizations/LOCK still could not be taken after %d s (%s); using an in-memory notarizations DB for this run (on-disk notarizations DB left untouched)\n",
__func__, (GetTimeMillis() - nWaitStart) / 1000, lockStatus.ToString());
return new NotarizationDB(NOTARIZATION_DB_CACHE_BYTES, true, false);
}
}
// The lock is free now: open once more before calling the DB corrupt.
fProbedFree = true;
}
if (!LevelDBDirHasData(ndir)) {
LogPrintf("%s: notarizations DB failed to open (%s) and holds no data; recreating it in place (non-fatal)\n", __func__, strError);
try {
return new NotarizationDB(NOTARIZATION_DB_CACHE_BYTES, false, true);
} catch (const std::exception& e) {
LogPrintf("%s: could not recreate the notarizations DB (%s); using an in-memory notarizations DB for this run\n", __func__, e.what());
return new NotarizationDB(NOTARIZATION_DB_CACHE_BYTES, true, false);
}
}
LogPrintf("%s: notarizations DB failed to open (%s); moving aside and regenerating (non-fatal)\n", __func__, strError);
// Move (do NOT delete) the old DB aside, so a transient open failure (fd exhaustion, disk full,
// permissions) cannot permanently destroy notarization history. Earlier copies are kept too.
try {
const std::string base = ndir.string() + ".corrupt-" + DateTimeStrFormat("%Y%m%d-%H%M%S", GetTime());
boost::filesystem::path aside(base);
for (int i = 1; boost::filesystem::exists(aside); i++)
aside = base + strprintf(".%d", i);
boost::filesystem::rename(ndir, aside);
LogPrintf("%s: moved the old notarizations DB to %s\n", __func__, aside.string());
} catch (const std::exception& e) {
LogPrintf("%s: could not move the notarizations DB aside (%s); using an in-memory notarizations DB for this run (on-disk notarizations DB left untouched)\n",
__func__, e.what());
return new NotarizationDB(NOTARIZATION_DB_CACHE_BYTES, true, false);
}
try {
return new NotarizationDB(NOTARIZATION_DB_CACHE_BYTES, false, true);
} catch (const std::exception& e) {
LogPrintf("%s: could not recreate the notarizations DB (%s); using an in-memory notarizations DB for this run\n", __func__, e.what());
return new NotarizationDB(NOTARIZATION_DB_CACHE_BYTES, true, false);
}
}
CClientUIInterface uiInterface; // global UI callback dispatcher (declared extern in ui_interface.h)
// Shutdown
@@ -211,9 +361,9 @@ void Shutdown()
/// for example if the data directory was found to be locked.
/// Be sure that anything that writes files or flushes caches only does this if the respective
/// module was initialized.
static char shutoffstr[128];
sprintf(shutoffstr,"%s-shutoff","hush");
RenameThread(shutoffstr);
// Do not RenameThread() here: Shutdown() runs on the main thread, whose name is the process name
// (/proc/<pid>/comm). Renaming it made 'pgrep -x dragonxd' stop matching a node that was still
// shutting down and holding its locks, so pgrep-based restart scripts relaunched it too early.
mempool.AddTransactionsUpdated(1);
if(fDebug) {
@@ -256,7 +406,15 @@ void Shutdown()
{
LOCK(cs_main);
if (pcoinsTip != NULL) {
FlushStateToDisk();
bool fChainstateFlushed = FlushStateToDisk();
#ifdef ENABLE_WALLET
// The hourly SetBestChain in FlushStateToDisk rarely fires here, so a session shorter
// than an hour would otherwise never save its witnesses and best block.
if (pwalletMain)
pwalletMain->PersistStateAtShutdown(fInitCompleted, fChainstateFlushed);
#else
(void)fChainstateFlushed;
#endif
}
if (pcoinsTip != NULL) {
delete pcoinsTip;
@@ -274,6 +432,13 @@ void Shutdown()
delete pblocktree;
pblocktree = NULL;
}
// Close the notarizations DB with the other LevelDBs. It used to be left open until process
// teardown, which made notarizations/LOCK the one LevelDB lock still held after "Shutdown: done"
// (and after the datadir .lock was released), so a quickly restarted successor failed to open it.
if (pnotarizations != NULL) {
delete pnotarizations;
pnotarizations = NULL;
}
}
#ifdef ENABLE_WALLET
if (pwalletMain)
@@ -479,15 +644,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
@@ -518,6 +686,8 @@ std::string HelpMessage(HelpMessageMode mode)
if (showDebug)
strUsage += HelpMessageOpt("-checknotecache", "On every balance or note-listing call, decrypt each cached note it considers again and log and repair any difference from the cache (slow; default: 0)");
strUsage += HelpMessageOpt("-rescan", _("Rescan the block chain for missing wallet transactions") + " " + _("on startup"));
strUsage += HelpMessageOpt("-walletsaveatshutdown", "Save the note witnesses and best block at a clean shutdown, so the next start does not rescan the session's blocks. "
"On a large wallet this can add a minute or more to the stop (default: 1)");
strUsage += HelpMessageOpt("-rescanheight", _("Rescan from specified height when rescan=1 on startup"));
strUsage += HelpMessageOpt("-salvagewallet", _("Attempt to recover private keys from a corrupt wallet.dat") + " " + _("on startup"));
strUsage += HelpMessageOpt("-sendfreetransactions", strprintf(_("Send transactions as zero-fee transactions if possible (default: %u)"), 0));
@@ -2075,35 +2245,19 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler)
do {
try {
UnloadBlockIndex();
delete pcoinsTip;
delete pcoinsdbview;
delete pcoinscatcher;
delete pblocktree;
delete pnotarizations;
// Shutdown() deletes (and pcoinsTip: flushes) whatever is non-NULL here, so never leave
// a pointer dangling if one of the reopens below throws.
delete pcoinsTip; pcoinsTip = NULL;
delete pcoinsdbview; pcoinsdbview = NULL;
delete pcoinscatcher; pcoinscatcher = NULL;
delete pblocktree; pblocktree = NULL;
delete pnotarizations; pnotarizations = NULL;
pblocktree = new CBlockTreeDB(nBlockTreeDBCache, false, fReindex, dbCompression, dbMaxOpenFiles);
pcoinsdbview = new CCoinsViewDB(nCoinDBCache, false, fReindex);
pcoinscatcher = new CCoinsViewErrorCatcher(pcoinsdbview);
pcoinsTip = new CCoinsViewCache(pcoinscatcher);
try {
pnotarizations = new NotarizationDB(NOTARIZATION_DB_CACHE_BYTES, false, fReindex);
} catch (const std::exception& e) {
// The notarizations (dPoW) DB is non-essential and node-regenerable. It has been seen to
// snapshot/flush torn (0-byte log -> leveldb "Database I/O error" on reopen), which
// previously aborted startup with a spurious "Error opening block database" and forced a
// full resync. Wipe and recreate it instead of failing hard.
LogPrintf("%s: notarizations DB failed to open (%s); moving aside and regenerating (non-fatal)\n", __FUNCTION__, e.what());
// Move (do NOT delete) the old DB aside, so a transient open failure (fd
// exhaustion, disk full, permissions) cannot permanently destroy notarization
// history. If the recreate below also fails it propagates as fatal and the old
// data survives in notarizations.corrupt for recovery.
{
boost::filesystem::path ndir = GetDataDir() / "notarizations";
boost::filesystem::remove_all(ndir.string() + ".corrupt");
boost::filesystem::rename(ndir, ndir.string() + ".corrupt");
}
pnotarizations = new NotarizationDB(NOTARIZATION_DB_CACHE_BYTES, false, true);
}
pnotarizations = OpenNotarizationDB(fReindex);
if (fReindex) {
@@ -2409,32 +2563,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->consolidationThreshold = consolidationThreshold;
pwalletMain->consolidationBatchSize = consolidationBatchSize;
pwalletMain->consolidationMaxTxs = consolidationMaxTxs;
if (pwalletMain->fSaplingConsolidationEnabled) {
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");
}
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);
@@ -2491,21 +2671,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
// 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"];
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]) {
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
@@ -2662,6 +2876,9 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler)
pindexRescan = FindForkInGlobalIndex(chainActive, locator);
else
pindexRescan = chainActive.Genesis();
// Nothing to rescan: the wallet as loaded is what the last save wrote at this block.
if (pindexRescan != NULL && pindexRescan == chainActive.Tip())
pwalletMain->MarkStatePersisted(pindexRescan);
}
if (chainActive.Tip() && chainActive.Tip() != pindexRescan)
{
@@ -2717,6 +2934,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));
@@ -2922,5 +3143,8 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler)
if(fDebug)
fprintf(stderr,"%s end fRequestShutdown=%d\n", __FUNCTION__, !!fRequestShutdown);
return !fRequestShutdown;
bool fOk = !fRequestShutdown;
if (fOk)
fInitCompleted = true;
return fOk;
}
+95 -29
View File
@@ -328,8 +328,12 @@ namespace {
bool fBulkHeaderSeen;
//! (server side) time (us) we last served a bulk stream to this peer, for flood throttling.
int64_t nLastBulkServeTime;
//! (#8 IBD header-flood cap) cumulative headers this peer made us process while in IBD.
//! (#8 header-flood cap) cumulative headers this peer made us process.
int64_t nHeadersProcessed;
//! (#8 header-flood cap) newly-stored headers from this peer that did NOT extend the best
//! header chain (side-branch/sibling): the real mapBlockIndex-growth vector. Honest sync and
//! new-block announcements are best-extending and never increment this.
int64_t nSideBranchHeaders;
CNodeState() {
fCurrentlyConnected = false;
@@ -351,6 +355,7 @@ namespace {
fBulkHeaderSeen = false;
nLastBulkServeTime = 0;
nHeadersProcessed = 0;
nSideBranchHeaders = 0;
}
};
@@ -1593,7 +1598,14 @@ bool CheckTransactionWithoutProofVerification(uint32_t tiptime,const CTransactio
char destaddr[65];
Getscriptaddress(destaddr,txout.scriptPubKey);
if ( hush_isnotaryvout(destaddr,tiptime) == 0 )
// The CRYPTO555/notary allowlist exempts those transparent vouts from the private-chain
// ban, leaving a public UTXO on a chain users treat as fully shielded. At/after the
// activation time that exemption is dropped and such vouts are rejected like any other
// taddr (time-gated + default-off via the sentinel so the whole network upgrades first).
// The gate is checked first so the allowlist lookup is skipped entirely once active.
int32_t isNotaryVout = ( tiptime >= DRAGONX_NOTARYVOUT_BAN_TIME )
? 0 : hush_isnotaryvout(destaddr,tiptime);
if ( isNotaryVout == 0 )
{
const bool isburn = (strcmp(destaddr,BURN_ADDRESS) == 0);
if ((ASSETCHAINS_BURN == 1) && isburn && tx.vin.empty()) {
@@ -2980,6 +2992,8 @@ static bool ApplyTxInUndo(const CTxInUndo& undo, CCoinsViewCache& view, const CO
void ConnectNotarizations(const CBlock &block, int height)
{
if (pnotarizations == NULL) // closed by Shutdown()
return;
NotarizationsInBlock notarizations = ScanBlockNotarizations(block, height);
if (notarizations.size() > 0) {
CDBBatch batch = CDBBatch(*pnotarizations);
@@ -2992,6 +3006,8 @@ void ConnectNotarizations(const CBlock &block, int height)
void DisconnectNotarizations(const CBlock &block)
{
if (pnotarizations == NULL) // closed by Shutdown()
return;
NotarizationsInBlock nibs;
if (GetBlockNotarizations(block.GetHash(), nibs)) {
CDBBatch batch = CDBBatch(*pnotarizations);
@@ -3846,10 +3862,11 @@ bool static FlushStateToDisk(CValidationState &state, FlushStateMode mode) {
return true;
}
void FlushStateToDisk() {
bool FlushStateToDisk() {
CValidationState state;
if ( HUSH_NSPV_FULLNODE )
FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
return FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
return true;
}
void PruneAndFlush() {
@@ -4315,23 +4332,52 @@ static bool ActivateBestChainStep(bool fSkipdpow, CValidationState &state, CBloc
assert(MAX_REORG_LENGTH > 0);//, "We must be able to reorg some distance");
if ( reorgLength > MAX_REORG_LENGTH)
{
// A peer-delivered fork that would roll back more than MAX_REORG_LENGTH
// (-maxreorg, default 99) blocks. This used to StartShutdown() the whole
// process, which is a per-reachability remote DoS: the attacker's fork is
// re-pulled from addrman after every restart and re-kills the node. Instead
// refuse the fork, poison the attacker branch so it leaves
// setBlockIndexCandidates and is never re-selected or re-pulled, stay up on
// the current chain, and penalize the delivering peer (DoS(100); the default
// banscore 101 bans on the second such trip). This mirrors the
// past-notarized-height branch above, which already refuses a fork with
// InvalidateBlock + DoS(100) and keeps running.
//
// Invalidate the BASE of the attacker branch (the first block above the fork
// point), not just its tip: FindMostWorkChain's fFailedChain sweep then
// erases the whole branch from the candidate set in one pass, and
// AcceptBlockHeader rejects any future extension (pprev is BLOCK_FAILED_CHILD).
// The base is strictly on the fork side (height forkHeight+1), so it is never
// in chainActive and no honest block is disconnected or poisoned.
CBlockIndex *pindexBadBase = (pindexFork != 0) ? pindexMostWork->GetAncestor(pindexFork->GetHeight() + 1) : pindexMostWork;
if (pindexBadBase == 0)
pindexBadBase = pindexMostWork;
// Because the refusal is PERSISTED (BLOCK_FAILED on the base), raising
// -maxreorg alone does NOT make the node follow this fork after a trip --
// recovery for a genuine deep reorg is an explicit `reconsiderblock <base>`
// (optionally with a raised -maxreorg so it isn't re-refused). Say so, and
// surface it in getinfo "errors" so a refused node is never silently stranded.
auto msg = strprintf(_(
"A block chain reorganization has been detected that would roll back %d blocks!!! "
"This is larger than the maximum of %d blocks, and so the node is shutting down for your safety."
), reorgLength, MAX_REORG_LENGTH) + "\n\n" +
"A block chain reorganization that would roll back %d blocks (more than the maximum of %d) "
"was refused; staying on the current chain."
), reorgLength, MAX_REORG_LENGTH) + "\n" +
_("Reorganization details") + ":\n" +
"- " + strprintf(_("Current tip: %s, height %d, work %s\n"),
"- " + strprintf(_("Current tip: %s, height %d, work %s"),
pindexOldTip->phashBlock->GetHex(), pindexOldTip->GetHeight(), pindexOldTip->chainPower.chainWork.GetHex()) + "\n" +
"- " + strprintf(_("New tip: %s, height %d, work %s\n"),
"- " + strprintf(_("Rejected tip: %s, height %d, work %s"),
pindexMostWork->phashBlock->GetHex(), pindexMostWork->GetHeight(), pindexMostWork->chainPower.chainWork.GetHex()) + "\n" +
"- " + strprintf(_("Fork point: %s %s, height %d"),
SMART_CHAIN_SYMBOL,pindexFork->phashBlock->GetHex(), pindexFork->GetHeight()) + "\n\n" +
_("Please help me, wise human!");
LogPrintf("*** %s\nif you launch with -maxreorg=%d it might be able to resolve this automatically", msg,reorgLength+10);
fprintf(stderr,"*** %s\nif you launch with -maxreorg=%d it might be able to resolve this automatically", msg.c_str(),reorgLength+10);
uiInterface.ThreadSafeMessageBox(msg, "", CClientUIInterface::MSG_ERROR);
StartShutdown();
return false;
SMART_CHAIN_SYMBOL, pindexFork ? pindexFork->phashBlock->GetHex() : "(none)", pindexFork ? pindexFork->GetHeight() : -1) + "\n" +
strprintf(_("If this is a legitimate deep reorg, recover with: reconsiderblock %s (raise -maxreorg first if needed)"),
pindexBadBase->phashBlock->GetHex());
LogPrintf("*** %s\n", msg);
fprintf(stderr,"*** %s\n", msg.c_str());
strMiscWarning = msg; // surfaces in getinfo/getnetworkinfo (GetWarnings), not fatal
CValidationState tmpstate;
InvalidateBlock(tmpstate, pindexBadBase);
return state.DoS(100, error("ActivateBestChainStep(): reorg of %d blocks exceeds maximum of %d; refusing fork and staying on current chain",
reorgLength, MAX_REORG_LENGTH), REJECT_INVALID, "oversized-reorg");
}
// Disconnect active blocks which are no longer in the best chain.
@@ -7875,6 +7921,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv,
}
CBlockIndex *pindexLast = NULL;
int64_t nSideBranchThisMsg = 0; // newly-stored headers that did NOT extend the best header chain
BOOST_FOREACH(const CBlockHeader& header, headers) {
if(fDebug) {
printf("%s: size.%i, solution size.%i\n", __func__, (int)sizeof(header), (int)header.nSolution.size());
@@ -7887,6 +7934,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv,
return error("non-continuous headers sequence");
}
int32_t futureblock;
const bool fWasNew = (mapBlockIndex.count(header.GetHash()) == 0); // not already stored (duplicates don't grow mapBlockIndex)
if (!AcceptBlockHeader(&futureblock,header, state, &pindexLast)) {
int nDoS;
if (state.IsInvalid(nDoS) && futureblock == 0)
@@ -7896,29 +7944,47 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv,
return error("invalid header received");
}
}
else if (fWasNew && pindexLast != NULL && pindexLast != pindexBestHeader) {
// Newly added to mapBlockIndex but NOT the best-known header: a side-branch/sibling,
// which is exactly the flood vector. Honest headers-first sync and new-block
// announcements extend the best chain, so they are never counted here.
nSideBranchThisMsg++;
}
}
// SECURITY (#8: IBD header-flood cap): bound how many headers a single peer can make us
// store while in IBD. Honest headers-first sync needs at most ~chain-length headers from a
// peer; one that floods far past 2x the known chain length is only trying to bloat
// mapBlockIndex/leveldb (such headers are never selected -- nMinimumChainWork gates that --
// but they still cost memory/disk). Cap per-peer and drop the peer. IBD-only: post-IBD there is
// no header-accept PoW check (removed as bug-prone), so a post-IBD flood is bounded only by
// nMinimumChainWork gating selection -- memory/disk growth there is accepted as low-severity.
if (IsInitialBlockDownload()) {
// SECURITY (#8: header-flood cap): bound how many headers a single peer can make us store, in and
// after IBD. Header-accept does no PoW check (removed as bug-prone), so without a cap a connected
// peer could flood sibling headers of the tip and grow mapBlockIndex linearly (a memory-exhaustion
// DoS). Two complementary per-peer caps, both dropping the peer when exceeded:
{
CNodeState *hstate = State(pfrom->GetId());
if (hstate != NULL) {
hstate->nHeadersProcessed += (int64_t)nCount;
// Cap RELATIVE TO THE VALIDATED ACTIVE-CHAIN HEIGHT (attacker-hard -- advancing it requires
// connecting real PoW blocks), NOT pindexBestHeader: a forward-extending header flood advances
// pindexBestHeader in lockstep with the attacker, so a pindexBestHeader-relative cap never fires.
// The checkpoint height is a fixed floor so honest IBD (blocks still lagging headers) is never capped.
hstate->nSideBranchHeaders += nSideBranchThisMsg;
// (1) Tight cap on newly-stored SIDE-BRANCH headers -- the actual mapBlockIndex-growth
// vector. A legitimate competing fork is bounded by the reorg window (MAX_REORG_LENGTH);
// this allows many times that for slack while bounding a flood to a few thousand entries
// per peer. Honest best-extending sync never increments the counter, so it is safe to
// keep small.
const int64_t kSideBranchCap = 2000;
if (hstate->nSideBranchHeaders > kSideBranchCap) {
Misbehaving(pfrom->GetId(), 100);
return error("%s: peer=%d flooded %lld side-branch headers (cap %lld)", __func__,
pfrom->id, (long long)hstate->nSideBranchHeaders, (long long)kSideBranchCap);
}
// (2) Loose cumulative backstop against an attacker who grinds a long FORWARD chain of
// correct-nBits headers (those do extend the best chain, so (1) never sees them). Cap
// RELATIVE TO THE VALIDATED ACTIVE-CHAIN HEIGHT (attacker-hard -- advancing it needs real
// PoW), NOT pindexBestHeader (a forward flood advances that in lockstep). The checkpoint
// height is a fixed floor so honest IBD (blocks lagging headers) is never capped.
int knownH = std::max((int)chainActive.Height(),
Checkpoints::GetTotalBlocksEstimate(chainparams.Checkpoints()));
int64_t headerCap = 2 * (int64_t)knownH + 200000;
if (hstate->nHeadersProcessed > headerCap) {
Misbehaving(pfrom->GetId(), 100);
return error("%s: peer=%d flooded %lld headers during IBD (cap %lld)", __func__,
return error("%s: peer=%d flooded %lld headers (cap %lld)", __func__,
pfrom->id, (long long)hstate->nHeadersProcessed, (long long)headerCap);
}
}
+3 -2
View File
@@ -323,8 +323,9 @@ CBlockIndex * InsertBlockIndex(uint256 hash);
bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats);
/** Increase a node's misbehavior score. */
void Misbehaving(NodeId nodeid, int howmuch);
/** Flush all state, indexes and buffers to disk. */
void FlushStateToDisk();
/** Flush all state, indexes and buffers to disk. False if the flush failed (out of disk space, a write
* error); true also for an nSPV light client, which has no chainstate to flush. */
bool FlushStateToDisk();
/** Prune block files and flush state to disk. */
void PruneAndFlush();
+11 -6
View File
@@ -1436,13 +1436,19 @@ void static RandomXMiner()
}
CValidationState state;
//{ LOCK(cs_main);
// Skip RandomX re-validation during TestBlockValidity — we already
// computed the correct hash, and re-verifying allocates ~256MB which
// can trigger the OOM killer on memory-constrained systems.
bool fValid;
{
// Hold cs_main across the LastTip() read and TestBlockValidity: the latter
// asserts pindexPrev == chainActive.Tip(), so without the lock a tip change
// (a block arriving from a peer, or a reorg) between the read and the assert
// aborts the node. The lock was previously removed only to avoid a ~256MB
// RandomX re-validation alloc; SetSkipRandomXValidation() already skips that
// re-validation here, so holding the lock is cheap and safe.
LOCK(cs_main);
SetSkipRandomXValidation(true);
bool fValid = TestBlockValidity(state,B, chainActive.LastTip(), true, false);
fValid = TestBlockValidity(state, B, chainActive.LastTip(), true, false);
SetSkipRandomXValidation(false);
}
if ( !fValid )
{
LogPrintf("RandomXMiner: TestBlockValidity FAILED at ht.%d, gotinvalid=1, state=%s\n",
@@ -1450,7 +1456,6 @@ void static RandomXMiner()
gotinvalid = 1;
return(false);
}
//}
SetThreadPriority(THREAD_PRIORITY_NORMAL);
LogPrintf("HushRandomXMiner:\n");
LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", B.GetHash().GetHex(), HASHTarget.GetHex());
+10 -1
View File
@@ -9,7 +9,10 @@
#include "main.h"
#include <boost/foreach.hpp>
NotarizationDB *pnotarizations;
// Owned by init: opened in AppInit2() and closed (set back to NULL) in Shutdown(), so that
// notarizations/LOCK is released together with the other LevelDB locks. Every accessor treats NULL
// as an empty DB, so a straggler after Shutdown() cannot dereference it.
NotarizationDB *pnotarizations = NULL;
NotarizationDB::NotarizationDB(size_t nCacheSize, bool fMemory, bool fWipe) : CDBWrapper(GetDataDir() / "notarizations", nCacheSize, fMemory, fWipe, false, 64) { }
NotarizationsInBlock ScanBlockNotarizations(const CBlock &block, int nHeight) {
@@ -55,11 +58,15 @@ NotarizationsInBlock ScanBlockNotarizations(const CBlock &block, int nHeight) {
}
bool GetBlockNotarizations(uint256 blockHash, NotarizationsInBlock &nibs) {
if (pnotarizations == NULL)
return false;
return pnotarizations->Read(blockHash, nibs);
}
bool GetBackNotarization(uint256 notarizationHash, Notarization &n) {
if (pnotarizations == NULL)
return false;
return pnotarizations->Read(notarizationHash, n);
}
@@ -86,6 +93,8 @@ void EraseBackNotarizations(const NotarizationsInBlock notarizations, CDBBatch &
// Scan notarizationsdb backwards for blocks containing a notarization
// for given symbol. Return height of matched notarization or 0.
int ScanNotarizationsDB(int height, std::string symbol, int scanLimitBlocks, Notarization& out) {
if (pnotarizations == NULL)
return 0;
if (height < 0 || height > chainActive.Height())
return false;
+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
+3
View File
@@ -20,6 +20,8 @@
static CMainSignals g_signals;
std::atomic<bool> fWalletNotifyFailed(false);
CMainSignals& GetMainSignals()
{
return g_signals;
@@ -103,6 +105,7 @@ bool NotifyWalletsOrShutdown(const std::function<void()>& notify)
PrintExceptionContinue(NULL, "ThreadNotifyWallets()");
}
LogPrintf("*** %s\n", "Wallet failed to process a block notification; shutting down");
fWalletNotifyFailed = true;
StartShutdown();
uiInterface.ThreadSafeMessageBox(
_("Error: A fatal internal error occurred, see debug.log for details"),
+5 -1
View File
@@ -8,6 +8,7 @@
#define HUSH_VALIDATIONINTERFACE_H
#include <boost/signals2/signal.hpp>
#include <atomic>
#include <functional>
#include "zcash/IncrementalMerkleTree.hpp"
@@ -31,6 +32,9 @@ void UnregisterAllValidationInterfaces();
void EraseFromWallets(const uint256 &hash);
/** Rescan all registered wallets */
void RescanWallets();
/** Set when a wallet failed to process a block notification and the node is shutting down because of it:
* the shutdown must not then try to write the whole wallet into the database that just failed. */
extern std::atomic<bool> fWalletNotifyFailed;
class CValidationInterface {
protected:
@@ -39,7 +43,7 @@ protected:
virtual void EraseFromWallet(const uint256 &hash) {}
virtual void RescanWallet() {}
virtual void ChainTip(const CBlockIndex *pindex, const CBlock *pblock, boost::optional<std::pair<SproutMerkleTree, SaplingMerkleTree>> added) {}
virtual void SetBestChain(const CBlockLocator &locator) {}
virtual bool SetBestChain(const CBlockLocator &locator) { return true; }
virtual void UpdatedTransaction(const uint256 &hash) {}
virtual void ResendWalletTransactions(int64_t nBestBlockTime) {}
virtual void BlockChecked(const CBlock&, const CValidationState&) {}
@@ -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,129 +314,195 @@ 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;
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);
}
// store sapling inputs so we can correctly lock and unlock them
for (auto entry : saplingEntries) {
// 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);
}
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;
}
}
} else {
pwalletMain->GetSaplingPaymentAddresses(addresses);
}
}
int numTxCreated = 0;
std::vector<std::string> consolidationTxIds;
CAmount amountConsolidated = 0;
CCoinsViewCache coinsView(pcoinsTip);
for (auto addr : addresses) {
libzcash::SaplingExtendedSpendingKey extsk;
if (pwalletMain->GetSaplingExtendedSpendingKey(addr, extsk)) {
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) {
libzcash::SaplingIncomingViewingKey ivk;
pwalletMain->GetSaplingIncomingViewingKey(boost::get<libzcash::SaplingPaymentAddress>(saplingEntry.address), ivk);
//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);
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());
//Only use a randomly determined number of notes
if (fromNotes.size() >= maxQuantity)
break;
// 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;
};
}
// 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);
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;
}
builder.AddSaplingSpend(extsk.expsk, notes[i], anchor, witnesses[i].get());
// 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];
auto builder = TransactionBuilder(consensusParams, tipHeight, pwalletMain);
builder.SetExpiryHeight(tipHeight + AUTO_OP_EXPIRY_DELTA);
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));
// 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;
}
LogPrint("zrpcunsafe", "%s: Added consolidation input %d\n", opid, i);
}
if (!spendsOk) {
failAddress(planned.group, "inputs do not share one anchor");
continue;
}
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);
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);
// 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);
@@ -241,65 +512,71 @@ bool AsyncRPCOperation_saplingconsolidation::main_impl() {
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);
builder.AddSaplingOutput(group.extsk.expsk.ovk, sietchZoutput, amount);
} else {
LogPrintf("%s: Invalid payment address %s! Stopping.\n", opid, zdust);
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) {
LogPrintf("%s: Failed to build transaction.\n",opid);
status=false;
break;
failAddress(planned.group, "failed to build transaction");
continue;
}
CTransaction tx = maybe_tx.get();
if (isCancelled()) {
LogPrintf("%s: Canceled. Stopping.\n", opid);
if (isCancelled() || ShutdownRequested()) {
LogPrintf("%s: %s. Stopping.\n", opid, isCancelled() ? "Canceled" : "Shutting down");
tally.error = isCancelled() ? "cancelled" : "shutting down";
status=false;
break;
}
// Lock shielded input notes
lock_notes();
LogPrint("zrpc", "%s: consolidation input notes locked\n", getId());
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++;
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());
unlock_notes();
LogPrint("zrpc", "%s: consolidatoin input notes unlocked\n", getId());
setConsolidationResult(numTxCreated, amountConsolidated, consolidationTxIds);
status = false;
break;
}
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
+11
View File
@@ -483,6 +483,17 @@ bool CDB::Rewrite(const string& strFile, const char* pszSkip)
}
bool CDBEnv::IsHealthy()
{
if (fKeepLogs)
return false;
if (!fDbEnvInit)
return true;
// get_flags itself fails with DB_RUNRECOVERY once the environment has panicked.
u_int32_t envFlags = 0;
return dbenv->get_flags(&envFlags) == 0 && !(envFlags & DB_PANIC_ENVIRONMENT);
}
void CDBEnv::Flush(bool fShutdown)
{
int64_t nStart = GetTimeMillis();
+3
View File
@@ -100,6 +100,9 @@ public:
bool Open(const boost::filesystem::path& path);
void Close();
void Flush(bool fShutdown);
//! False once a checkpoint or lsn_reset has failed or the environment has panicked (BDB0060): a
//! large write into it then fails or deepens the damage, and the logs are what recovery needs.
bool IsHealthy();
void CheckpointLSN(const std::string& strFile);
void CloseDb(const std::string& strFile);
+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 },
+323 -55
View File
@@ -48,6 +48,8 @@
#include <chrono>
#include <atomic>
#include <mutex>
#include <functional>
#include <unordered_map>
#include "zcash/zip32.h"
#include "cc/CCinclude.h"
#include <assert.h>
@@ -710,6 +712,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 +740,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.
// 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 +764,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
@@ -818,24 +875,115 @@ bool CWallet::CommitAutomatedTx(const CTransaction& tx) {
return CommitTransaction(wtx, reservekey);
}
void CWallet::SetBestChain(const CBlockLocator& loc)
bool CWallet::SetBestChain(const CBlockLocator& loc)
{
// FlushStateToDisk passes the chain tip, but ThreadNotifyWallets delivers blocks to the wallet
// asynchronously and can lag it. Stamping a locator ahead of what the wallet has processed makes
// the next start skip those blocks for good (no rescan, no notification): notes received in them
// go missing and spends in them go unseen. So stamp the block the wallet's state reflects (seeded
// by init before the notifier starts, then advanced by ChainTip). Init's own calls, made before
// it is seeded, pass the right locator themselves.
CBlockLocator locator = loc;
{
LOCK2(cs_main, cs_wallet);
if (pindexWalletTip != nullptr)
locator = chainActive.GetLocator(pindexWalletTip);
}
// Default ctor => fFlushOnClose=true => ~CDB runs a full BDB txn_checkpoint over the entire
// cache. Fine for the hourly/shutdown callers; ruinous inside a scan (see SetBestChainNoFlush).
CWalletDB walletdb(strWalletFile);
SetBestChainINTERNAL(walletdb, locator);
return SetBestChainWith(walletdb, loc);
}
void CWallet::RecordStatePersisted(const CBlockIndex* pindex, uint64_t nGeneration)
{
LOCK(cs_wallet);
pindexPersistedTip = pindex;
nPersistedWitnessGeneration = nGeneration;
}
void CWallet::MarkStatePersisted(const CBlockIndex* pindex)
{
LOCK(cs_wallet);
RecordStatePersisted(pindex, nWitnessGeneration);
}
const char* CWallet::ShutdownSaveSkipReason(bool fInitCompleted, bool fChainstateFlushed)
{
// AppInit2 failed or was cut short: the other threads were interrupted but not joined, and the
// wallet tip may still be unset, in which case SetBestChain would stamp the chain tip over an
// interrupted rescan's checkpoint and the next start would skip the unscanned range.
if (!fInitCompleted)
return "startup did not complete";
// For deployments whose stop timeout is shorter than the save takes on their wallet: a kill
// during the save rolls it back and only lengthens the next start.
if (!GetBoolArg("-walletsaveatshutdown", true))
return "disabled by -walletsaveatshutdown=0";
if (fWalletNotifyFailed)
return "the wallet failed to process a block";
// The locator would then name a block the chainstate and block index on disk may not have, and
// this is typically a full disk, where a write the size of the wallet is the worst thing to start.
if (!fChainstateFlushed)
return "the chainstate flush failed";
if (!bitdb.IsHealthy())
return "the wallet database environment reported an error";
LOCK(cs_wallet);
if (pindexWalletTip == nullptr)
return "the wallet tip is not set";
// A rescan (rescan, z_importkey, ...) that was cut short wrote its own locator, or could not and
// left the older one. Stamping the wallet tip over that would mark the unscanned range as scanned,
// and a key imported with that scan would never see its notes there.
if (nInterruptedRescanHeight >= 0)
return "a rescan did not complete; the next start resumes it from the locator it left";
if (pindexWalletTip == pindexPersistedTip && nWitnessGeneration == nPersistedWitnessGeneration)
return "nothing changed since the last save";
return nullptr;
}
void CWallet::PersistStateAtShutdown(bool fInitCompleted, bool fChainstateFlushed)
{
LOCK2(cs_main, cs_wallet);
const char* skip = ShutdownSaveSkipReason(fInitCompleted, fChainstateFlushed);
if (skip != nullptr) {
LogPrintf("%s: not saving the wallet state: %s\n", __func__, skip);
return;
}
// SetBestChainINTERNAL writes every tx that has Sapling note data, each with its whole witness
// cache, in one transaction: on a large wallet this is the bulk of wallet.dat. A kill while it
// runs rolls back to the previous save at the next start (DB_RECOVER), losing only the saving.
unsigned int nTxs = 0;
for (const std::pair<const uint256, CWalletTx>& wtxItem : mapWallet)
if (!wtxItem.second.mapSaplingNoteData.empty())
nTxs++;
const int nHeight = pindexWalletTip->GetHeight();
LogPrintf("Saving wallet state (note witnesses and best block %d, %u txs)...\n", nHeight, nTxs);
int64_t nStart = GetTimeMillis();
bool fWritten = false;
std::string strFailure = "the write failed";
// Opening the wallet database throws when the environment or the file cannot be opened. Shutdown()
// has no handler, so this must not escape: the rest of the teardown (the coins views, the wallet
// flush, the pidfile) still has to run.
try {
fWritten = SetBestChain(chainActive.GetLocator());
} catch (const std::exception& e) {
strFailure = e.what();
}
LogPrintf("%s: wallet state %s at height %d: %u txs in %dms\n", __func__,
fWritten ? "saved" : strprintf("NOT saved (%s; the previous save stays on disk)", strFailure),
nHeight, nTxs, GetTimeMillis() - nStart);
}
int CWallet::NoteRescanStarted(int nPersistedHeight)
{
LOCK(cs_wallet);
// Until the scan completes, assume it ends early, even by throwing: the next start then resumes
// from the locator on disk, as it would without a shutdown save.
int nBefore = nInterruptedRescanHeight;
nInterruptedRescanHeight = std::max(nPersistedHeight, 0);
return nBefore;
}
void CWallet::NoteRescanInterrupted(int nResumeHeight)
{
LOCK(cs_wallet);
nInterruptedRescanHeight = std::max(nResumeHeight, 0);
}
void CWallet::NoteRescanCompleted(int nStartHeight, int nInterruptedBefore)
{
LOCK(cs_wallet);
// A scan that starts above the locator on disk covers what the caller asked for. It is still
// incomplete if an earlier scan was interrupted and this one starts above where that left off.
if (nInterruptedBefore < 0 || nStartHeight <= nInterruptedBefore + 1)
nInterruptedRescanHeight = -1;
}
bool CWallet::SetBestChainNoFlush(const CBlockLocator& loc)
@@ -1215,6 +1363,7 @@ void CWallet::ClearNoteWitnessCache()
notes++;
}
}
nWitnessGeneration++;
LogPrintf("%s: Cleared witness data from %d wallet items and %d SaplingNotes\n", __func__, mapWallet.size(), notes);
}
@@ -1223,6 +1372,7 @@ void CWallet::DecrementNoteWitnesses(const CBlockIndex* pindex)
extern int32_t HUSH_REWIND;
LOCK2(cs_main, cs_wallet);
nWitnessGeneration++;
for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
//Sapling
@@ -1273,6 +1423,39 @@ int CWallet::SaplingWitnessMinimumHeight(const boost::optional<uint256>& nullifi
return nMinimumHeight;
}
// Threads for witness work spread over notes: -witnessbuildthreads, else one per core, and never
// more than there are notes.
static int WitnessThreadCount(size_t nJobs)
{
int nPar = (int)GetArg("-witnessbuildthreads", 0);
if (nPar <= 0) nPar = (int)std::thread::hardware_concurrency();
if (nPar <= 0) nPar = 1;
if (nPar > (int)nJobs) nPar = (int)nJobs;
if (nPar < 1) nPar = 1;
return nPar;
}
// Runs shard(0) .. shard(nPar-1), each exactly once, on up to nPar threads; shard must not throw.
// If the OS refuses a thread (task limit, memory), the remaining shards run here instead of letting
// the exception unwind past joinable threads (std::terminate). The result is unchanged either way.
static void RunWitnessShards(int nPar, const std::function<void(int)>& shard, const char* caller)
{
if (nPar <= 1) {
shard(0);
return;
}
std::vector<std::thread> threads;
threads.reserve(nPar);
int t = 0;
try {
for (; t < nPar; t++) threads.emplace_back(shard, t);
} catch (const std::system_error& e) {
LogPrintf("%s: could only start %d of %d witness threads (%s); running the rest inline\n", caller, t, nPar, e.what());
}
for (int u = t; u < nPar; u++) shard(u);
for (std::thread& th : threads) th.join();
}
int CWallet::VerifyAndSetInitialWitness(const CBlockIndex* pindex, bool witnessOnly)
{
LOCK2(cs_main, cs_wallet);
@@ -1280,6 +1463,75 @@ int CWallet::VerifyAndSetInitialWitness(const CBlockIndex* pindex, bool witnessO
int nWitnessTxIncrement = 0;
int nWitnessTotalTxCount = mapWallet.size();
int nMinimumHeight = pindex->GetHeight();
// For the end-of-pass summary only; no decision reads them.
const int64_t nPassStart = GetTimeMicros();
int nNotesValidated = 0, nNotesReseeded = 0, nNotesKnownGood = 0, nNotesAhead = 0;
// root() walks a witness's whole depth-32 path, ~1.7-2.4ms, and after a restart every note needs
// one: ~30s for a 16k-note wallet, with cs_main and cs_wallet held. So compute those roots first,
// spread over threads the way BuildWitnessCache's Phase 2 spreads the extension, and then run the
// loop below unchanged, taking each root from here instead of computing it. That loop changes a
// note's witnesses only at that note's own turn (a sibling's reseed rewrites nullifiers, never
// witnesses), so each root is the root of the witness the loop checks, and the validated/reseeded
// decisions, their order and nMinimumHeight are exactly the serial ones. The selection mirrors the
// loop's conditions for reaching root(); a note it misses (one that only gains a nullifier from a
// sibling's reseed) has its root computed inline, as does one whose root() threw here, so a throw
// surfaces exactly where it used to.
std::vector<const SaplingNoteData*> rootNotes;
for (const std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
// Once every note is validated (the steady state between restarts) nothing here selects one, so
// skip the depth lookup for such a tx.
bool fAnyUnvalidated = false;
for (const mapSaplingNoteData_t::value_type& item : wtxItem.second.mapSaplingNoteData)
if (!item.second.witnessRootValidated) {
fAnyUnvalidated = true;
break;
}
if (!fAnyUnvalidated || wtxItem.second.GetDepthInMainChain() <= 0)
continue;
for (const mapSaplingNoteData_t::value_type& item : wtxItem.second.mapSaplingNoteData) {
const SaplingNoteData* nd = &(item.second);
if (nd->nullifier && !nd->witnesses.empty() && nd->witnessHeight > 0 && !nd->witnessRootValidated &&
chainActive[nd->witnessHeight] != NULL && HaveSaplingFullViewingKey(nd->ivk))
rootNotes.push_back(nd);
}
}
std::vector<uint256> roots(rootNotes.size());
std::unordered_map<const SaplingNoteData*, size_t> rootIndex;
if (!rootNotes.empty()) {
std::vector<char> haveRoot(rootNotes.size(), 0);
// Starting the threads costs about as much as a root, so a handful stay on this thread.
const int nPar = rootNotes.size() >= 8 ? WitnessThreadCount(rootNotes.size()) : 1;
int64_t r0 = GetTimeMicros();
RunWitnessShards(nPar, [&](int tid) {
// Workers read only their own notes' witnesses; this thread holds the locks and waits.
for (size_t k = (size_t)tid; k < rootNotes.size(); k += (size_t)nPar) {
if (ShutdownRequested())
return;
try {
roots[k] = rootNotes[k]->witnesses.front().root();
haveRoot[k] = 1;
} catch (...) {
}
}
}, __func__);
// Nothing has been changed yet, so stopping here is as if this pass never ran: the next block or
// the next start redoes it. Without this a stop waited for the whole pass.
if (ShutdownRequested()) {
LogPrintf("%s: shutdown requested, skipping the witness check at height %d\n", __func__, pindex->GetHeight());
return pindex->GetHeight();
}
for (size_t k = 0; k < rootNotes.size(); k++)
if (haveRoot[k])
rootIndex[rootNotes[k]] = k;
if (fZdebug)
LogPrintf("%s: %u witness root(s) computed in %ldms using %d thread(s)\n", __func__,
(unsigned)rootNotes.size(), (long)((GetTimeMicros() - r0) / 1000), nPar);
}
auto cachedRoot = [&](const SaplingNoteData* nd) {
std::unordered_map<const SaplingNoteData*, size_t>::const_iterator it = rootIndex.find(nd);
return it != rootIndex.end() ? roots[it->second] : nd->witnesses.front().root();
};
for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
nWitnessTxIncrement += 1;
@@ -1313,11 +1565,14 @@ int CWallet::VerifyAndSetInitialWitness(const CBlockIndex* pindex, bool witnessO
if (!nd->witnesses.empty() && nd->witnessHeight > 0) {
//Skip all functions for validated witness while witness only = true
if (nd->witnessRootValidated && witnessOnly)
if (nd->witnessRootValidated && witnessOnly) {
nNotesKnownGood++;
continue;
}
//Skip Validation when witness root has been validated
if (nd->witnessRootValidated) {
nNotesKnownGood++;
nMinimumHeight = SaplingWitnessMinimumHeight(item.second.nullifier, nd->witnessHeight, nMinimumHeight);
continue;
}
@@ -1330,11 +1585,13 @@ int CWallet::VerifyAndSetInitialWitness(const CBlockIndex* pindex, bool witnessO
CBlockIndex* whIndex = chainActive[nd->witnessHeight];
if (whIndex == NULL) {
//witnessHeight strictly above the active chain (transient catch-up): cannot validate yet
nNotesAhead++;
nMinimumHeight = SaplingWitnessMinimumHeight(item.second.nullifier, nd->witnessHeight, nMinimumHeight);
continue;
}
if (nd->witnesses.front().root() == whIndex->hashFinalSaplingRoot) {
if (cachedRoot(nd) == whIndex->hashFinalSaplingRoot) {
nd->witnessRootValidated = true;
nNotesValidated++;
nMinimumHeight = SaplingWitnessMinimumHeight(item.second.nullifier, nd->witnessHeight, nMinimumHeight);
continue;
}
@@ -1342,11 +1599,12 @@ int CWallet::VerifyAndSetInitialWitness(const CBlockIndex* pindex, bool witnessO
}
//Validate the witness at the witness height
witnessRoot = nd->witnesses.front().root();
witnessRoot = cachedRoot(nd);
pblockindex = chainActive[nd->witnessHeight];
blockRoot = pblockindex->hashFinalSaplingRoot;
if (witnessRoot == blockRoot) {
nd->witnessRootValidated = true;
nNotesValidated++;
nMinimumHeight = SaplingWitnessMinimumHeight(item.second.nullifier, nd->witnessHeight, nMinimumHeight);
continue;
}
@@ -1355,8 +1613,12 @@ int CWallet::VerifyAndSetInitialWitness(const CBlockIndex* pindex, bool witnessO
//Clear witness Cache for all other scenarios
pblockindex = chainActive[wtxHeight];
::ClearSingleNoteWitnessCache(nd);
nWitnessGeneration++;
nNotesReseeded++;
LogPrintf("%s: Setting Initial Sapling Witness for tx %s, %i of %i\n", __func__, wtxHash.ToString(), nWitnessTxIncrement, nWitnessTotalTxCount);
//The GUI parses this line (the hash between "for tx " and the comma, and the count after " of "):
//keep that part as it is and only append. <i> of <N> is the tx's place in mapWallet, not a note count.
LogPrintf("%s: Setting Initial Sapling Witness for tx %s, %i of %i [reseed %d]\n", __func__, wtxHash.ToString(), nWitnessTxIncrement, nWitnessTotalTxCount, nNotesReseeded);
SaplingMerkleTree saplingTree;
blockRoot = pblockindex->pprev->hashFinalSaplingRoot;
@@ -1404,6 +1666,10 @@ int CWallet::VerifyAndSetInitialWitness(const CBlockIndex* pindex, bool witnessO
}
}
if (nNotesValidated > 0 || nNotesReseeded > 0)
LogPrintf("%s: block %d: %d note witness(es) validated, %d reseeded, %d already valid, %d ahead of the chain; "
"lowest witness height %d; %ldms\n", __func__, pindex->GetHeight(), nNotesValidated, nNotesReseeded,
nNotesKnownGood, nNotesAhead, nMinimumHeight, (long)((GetTimeMicros() - nPassStart) / 1000));
if(fZdebug)
LogPrintf("%s: nMinimumHeight=%d\n",__func__, nMinimumHeight);
return nMinimumHeight;
@@ -1531,12 +1797,7 @@ void CWallet::BuildWitnessCache(const CBlockIndex* pindex, bool witnessOnly)
nCms += cms.size();
const bool fParallel = bulkRebuild || (uint64_t)work.size() * nCms >= 2000;
int nPar = (int)GetArg("-witnessbuildthreads", 0);
if (nPar <= 0) nPar = (int)std::thread::hardware_concurrency();
if (nPar <= 0) nPar = 1;
if (nPar > (int)work.size()) nPar = (int)work.size();
if (nPar < 1) nPar = 1;
if (!fParallel) nPar = 1;
const int nPar = fParallel ? WitnessThreadCount(work.size()) : 1;
std::atomic<bool> failed(false);
std::mutex failMtx;
@@ -1621,23 +1882,7 @@ void CWallet::BuildWitnessCache(const CBlockIndex* pindex, bool witnessOnly)
};
int64_t e0 = GetTimeMicros();
if (nPar <= 1) {
worker(0);
} else {
// If the OS refuses a thread (task limit, memory), run the remaining shards here instead of
// letting the exception unwind past joinable threads (std::terminate). Each shard still runs
// exactly once, so the result is unchanged.
std::vector<std::thread> threads;
threads.reserve(nPar);
int t = 0;
try {
for (; t < nPar; t++) threads.emplace_back(worker, t);
} catch (const std::system_error& e) {
LogPrintf("%s: could only start %d of %d witness threads (%s); running the rest inline\n", __func__, t, nPar, e.what());
}
for (int u = t; u < nPar; u++) worker(u);
for (std::thread& th : threads) th.join();
}
RunWitnessShards(nPar, worker, __func__);
int64_t tExtend = GetTimeMicros() - e0;
if (failed)
@@ -1653,6 +1898,7 @@ void CWallet::BuildWitnessCache(const CBlockIndex* pindex, bool witnessOnly)
// (DecrementNoteWitnesses clears it), keeping the heal self-correcting. The unrecoverable count
// itself comes from checkRoot() on the workers, and only for a bulk rebuild.
if (!work.empty()) {
nWitnessGeneration++;
for (SaplingNoteData* nd : work)
nd->witnessRootValidated = true;
if (bulkRebuild) {
@@ -2004,6 +2250,10 @@ bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFromLoadWallet, CWalletD
fUpdated = true;
}
}
// Only a real change: re-adding a tx unchanged (ReacceptWalletTransactions on every start
// for each unconfirmed tx) leaves nothing new for SetBestChain to write.
if ((fInsertedNew || fUpdated) && !wtx.mapSaplingNoteData.empty())
nWitnessGeneration++;
//// debug print
LogPrintf("AddToWallet %s at height %d %s%s\n", wtxIn.GetHash().ToString(), hush_blockheight(wtxIn.hashBlock), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
@@ -2347,6 +2597,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,15 +2625,8 @@ 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();
cand[i] = GetSaplingNoteLatestWitness(notes[i]);
if (cand[i])
rootVotes[cand[i]->root()]++;
}
@@ -3630,20 +3887,30 @@ int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
// already present. No witness work is needed: witnesses are re-derived from each note's own
// witnessHeight, and witnessRootValidated is in-memory-only so every note is revalidated
// against hashFinalSaplingRoot on the next start.
auto checkpointProgress = [&](const CBlockIndex* pindexStopped) {
const int nInterruptedBefore = NoteRescanStarted(pindexPersisted ? pindexPersisted->GetHeight() : 0);
// Returns the height the locator on disk is left at, which the next start resumes from.
auto writeCheckpoint = [&](const CBlockIndex* pindexStopped) {
const int nPersisted = pindexPersisted ? pindexPersisted->GetHeight() : 0;
if (!fMayCheckpoint || !pindexStopped || !pindexStopped->pprev)
return;
return nPersisted;
const CBlockIndex* pindexDone = pindexStopped->pprev;
if (pindexDone->GetHeight() <= pindexPersisted->GetHeight())
return; // never move the locator backwards
return nPersisted; // never move the locator backwards
if (SetBestChainNoFlush(chainActive.GetLocator(pindexDone))) {
LogPrintf("%s: checkpointed scan progress at height %d\n", __func__, pindexDone->GetHeight());
return pindexDone->GetHeight();
} else {
LogPrintf("%s: FAILED to checkpoint scan progress at height %d; the scan will replay "
"from height %d on the next start\n", __func__, pindexDone->GetHeight(),
pindexPersisted->GetHeight());
return nPersisted;
}
};
// Also keeps the shutdown save from stamping the wallet tip over what was written here.
auto checkpointProgress = [&](const CBlockIndex* pindexStopped) {
NoteRescanInterrupted(writeCheckpoint(pindexStopped));
};
ShowProgress(_("Rescanning..."), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup
double dProgressStart = Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), pindex, false);
@@ -3721,6 +3988,7 @@ int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
//Update all witness caches
BuildWitnessCache(chainActive.Tip(), false);
NoteRescanCompleted(pindexStart->GetHeight(), nInterruptedBefore);
ShowProgress(_("Rescanning..."), 100); // hide progress dialog in GUI
}
+142 -4
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 = "";
@@ -985,6 +1049,38 @@ protected:
return true;
}
//! SetBestChain on an open wallet database (a template so tests can pass a fake one).
template <typename WalletDB>
bool SetBestChainWith(WalletDB& walletdb, const CBlockLocator& loc) {
// FlushStateToDisk passes the chain tip, but ThreadNotifyWallets delivers blocks to the wallet
// asynchronously and can lag it. Stamping a locator ahead of what the wallet has processed makes
// the next start skip those blocks for good (no rescan, no notification): notes received in them
// go missing and spends in them go unseen. So stamp the block the wallet's state reflects (seeded
// by init before the notifier starts, then advanced by ChainTip). Init's own calls, made before
// it is seeded, pass the right locator themselves.
CBlockLocator locator = loc;
const CBlockIndex* pindexStamped = nullptr;
uint64_t nGeneration;
{
LOCK2(cs_main, cs_wallet);
// Read before the write: a change made while it runs bumps the counter past this value, so
// the shutdown save still sees it as unsaved.
nGeneration = nWitnessGeneration;
if (pindexWalletTip != nullptr) {
locator = chainActive.GetLocator(pindexWalletTip);
pindexStamped = pindexWalletTip;
} else if (!loc.vHave.empty()) {
BlockMap::const_iterator mi = mapBlockIndex.find(loc.vHave.front());
if (mi != mapBlockIndex.end())
pindexStamped = mi->second;
}
}
bool fWritten = SetBestChainINTERNAL(walletdb, locator);
if (fWritten)
RecordStatePersisted(pindexStamped, nGeneration);
return fWritten;
}
private:
template <class T>
void SyncMetaData(std::pair<typename TxSpendMap<T>::iterator, typename TxSpendMap<T>::iterator>);
@@ -993,6 +1089,20 @@ private:
// reflects (guarded by cs_wallet). SetBestChain stamps this instead of the chain tip.
const CBlockIndex* pindexWalletTip = nullptr;
// Change tracking for the shutdown save (guarded by cs_wallet). nWitnessGeneration is bumped
// whenever the note state SetBestChain writes changes in memory: witnesses extended, popped,
// reseeded or cleared, or a note-bearing tx added or merged. A committed SetBestChain records
// the block it stamped and the counter it saw, so a shutdown can tell that nothing is left to
// write.
uint64_t nWitnessGeneration = 0;
const CBlockIndex* pindexPersistedTip = nullptr;
uint64_t nPersistedWitnessGeneration = 0;
// Where a rescan of this session that did not complete left the locator on disk (its checkpoint,
// or the older locator it could not advance), or -1 (guarded by cs_wallet). The next start resumes
// the scan from there, so a shutdown must not stamp the wallet tip over it.
int nInterruptedRescanHeight = -1;
void RecordStatePersisted(const CBlockIndex* pindex, uint64_t nGeneration);
protected:
bool UpdatedNoteData(const CWalletTx& wtxIn, CWalletTx& wtx, bool fSameBlock);
void MarkAffectedTransactionsDirty(const CTransaction& tx);
@@ -1296,6 +1406,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,10 +1430,36 @@ 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. */
void SetBestChain(const CBlockLocator& loc);
/** Saves witness caches and best block locator to disk in one atomic write, and reports whether
* it committed. Overrides CValidationInterface. */
bool SetBestChain(const CBlockLocator& loc);
/** Init found the locator on disk at pindex and is not rescanning: the wallet in memory is what
* was last saved, so a shutdown with no changes after this has nothing to write. */
void MarkStatePersisted(const CBlockIndex* pindex);
/** Why a clean shutdown must not write the wallet state now, or nullptr if it should. */
const char* ShutdownSaveSkipReason(bool fInitCompleted, bool fChainstateFlushed);
/** Called by Shutdown() under cs_main after the chainstate flush, with every other thread
* stopped: writes the witnesses and the best-block locator (SetBestChain), unless a gate in
* ShutdownSaveSkipReason says not to. Without it a session shorter than the hourly write never
* saves, and the next start rescans and re-extends every witness across the whole session. */
void PersistStateAtShutdown(bool fInitCompleted, bool fChainstateFlushed);
/** Rescan bookkeeping for the shutdown save. A scan reports its start with the height of the
* locator on disk (getting back the height an earlier interrupted scan left, or -1), where it
* stopped if cut short (the height it left the locator at), and its start once it reached the
* tip. Until a scan has covered everything above the locator on disk, a shutdown does not save. */
int NoteRescanStarted(int nPersistedHeight);
void NoteRescanInterrupted(int nResumeHeight);
void NoteRescanCompleted(int nStartHeight, int nInterruptedBefore);
// Seed the block the wallet's state reflects, before ThreadNotifyWallets starts delivering.
void SetWalletTip(const CBlockIndex* pindex);
/** As SetBestChain, but for use INSIDE a long scan: opens the wallet DB with fFlushOnClose=false