Compare commits
18
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
aea4bb7fa3 | ||
|
|
a7b15e40a0 | ||
|
|
2a2eaa2078 | ||
|
|
c4b0a23911 | ||
|
|
7c0702affa | ||
|
|
19f20736df | ||
|
|
9c7c5835bd | ||
|
|
722c3a7d7a | ||
|
|
8dc2e3c93c | ||
|
|
3e75769a48 | ||
|
|
66b74aa6aa | ||
|
|
23159fcb25 | ||
|
|
4538a8cd76 | ||
|
|
0ac7812b11 | ||
|
|
5770f73b3d | ||
|
|
8e34bcbba7 | ||
|
|
7d5893cd2a | ||
|
|
bc36fa5a74 |
@@ -58,7 +58,8 @@ witness rebuilds. Consolidation keeps that in check.
|
||||
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.
|
||||
no more than the fee, and expires `-txexpirydelta` blocks (default 200) after it is made, like any other wallet
|
||||
transaction, so the wallet's periodic rebroadcast can still retry it.
|
||||
* 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,
|
||||
@@ -128,8 +129,10 @@ wallet: `N addresses have more than 25 spendable notes; consider -consolidation=
|
||||
|
||||
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.
|
||||
and `z_consolidate` refuses any other address too. Sweep and consolidation never run at the same time, and they take
|
||||
strict turns: a round that comes due while the other op is running goes next, and the other op starts no new
|
||||
round until it has run, so neither can starve the other. `z_sweepstatus` shows `"waiting_for_consolidation": true`
|
||||
and `z_consolidationstatus` shows `"waiting_for_sweep": true` while a round is waiting for its turn.
|
||||
|
||||
### Copyright
|
||||
|
||||
|
||||
@@ -19,6 +19,7 @@ hush_gtest_SOURCES = \
|
||||
gtest/test_sweep_note_selection.cpp \
|
||||
gtest/test_asyncrpc_cancel.cpp \
|
||||
gtest/test_wallet_notedata.cpp \
|
||||
gtest/test_wallet_witnesstrim.cpp \
|
||||
gtest/test_net_closesocket.cpp \
|
||||
gtest/test_net_addrrelay.cpp \
|
||||
gtest/test_fd_defense.cpp \
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
// 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
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include "random.h"
|
||||
#include "uint256.h"
|
||||
#include "wallet/wallet.h"
|
||||
#include "zcash/IncrementalMerkleTree.hpp"
|
||||
|
||||
namespace {
|
||||
|
||||
libzcash::SaplingIncomingViewingKey TestIvk()
|
||||
{
|
||||
return libzcash::SaplingIncomingViewingKey(uint256S("0202020202020202020202020202020202020202020202020202020202020202"));
|
||||
}
|
||||
|
||||
// A note with a witness for every one of nSnapshots blocks, newest at the front, the way
|
||||
// BuildWitnessCache leaves it: each snapshot is the previous one plus one more commitment.
|
||||
SaplingNoteData NoteWithHistory(int nSnapshots, int tipHeight, bool fNullifier = true)
|
||||
{
|
||||
SaplingNoteData nd = fNullifier ? SaplingNoteData(TestIvk(), GetRandHash()) : SaplingNoteData(TestIvk());
|
||||
SaplingMerkleTree tree;
|
||||
tree.append(GetRandHash()); // the note's own commitment
|
||||
nd.witnesses.push_front(tree.witness());
|
||||
for (int i = 1; i < nSnapshots; i++) {
|
||||
nd.witnesses.push_front(nd.witnesses.front());
|
||||
nd.witnesses.front().append(GetRandHash());
|
||||
}
|
||||
nd.witnessHeight = tipHeight;
|
||||
return nd;
|
||||
}
|
||||
|
||||
const unsigned int CACHE = 109; // WITNESS_CACHE_SIZE on DragonX: MAX_REORG_LENGTH (99) + 10
|
||||
|
||||
} // namespace
|
||||
|
||||
// Spent deeper than the cache: only the newest witness survives, unchanged, and the note keeps the
|
||||
// position and height its nullifier and startup validation depend on.
|
||||
TEST(WalletWitnessTrim, DeeplySpentNoteKeepsOnlyNewestWitness)
|
||||
{
|
||||
SaplingNoteData nd = NoteWithHistory(CACHE, 5000);
|
||||
const uint256 rootBefore = nd.witnesses.front().root();
|
||||
const uint64_t posBefore = nd.witnesses.front().position();
|
||||
const boost::optional<uint256> nfBefore = nd.nullifier;
|
||||
|
||||
EXPECT_TRUE(TrimDeeplySpentNoteWitnesses(nd, CACHE + 1, CACHE));
|
||||
ASSERT_EQ(nd.witnesses.size(), 1u);
|
||||
EXPECT_EQ(nd.witnesses.front().root(), rootBefore);
|
||||
EXPECT_EQ(nd.witnesses.front().position(), posBefore);
|
||||
EXPECT_EQ(nd.witnessHeight, 5000);
|
||||
EXPECT_TRUE(nd.nullifier == nfBefore);
|
||||
|
||||
// Already trimmed: nothing more to do.
|
||||
EXPECT_FALSE(TrimDeeplySpentNoteWitnesses(nd, CACHE + 50, CACHE));
|
||||
EXPECT_EQ(nd.witnesses.size(), 1u);
|
||||
}
|
||||
|
||||
// Unspent (depth 0) and spent within reorg reach: a reorg may still need the older snapshots.
|
||||
TEST(WalletWitnessTrim, UnspentAndShallowSpentNotesAreUntouched)
|
||||
{
|
||||
SaplingNoteData unspent = NoteWithHistory(CACHE, 5000);
|
||||
EXPECT_FALSE(TrimDeeplySpentNoteWitnesses(unspent, 0, CACHE));
|
||||
EXPECT_EQ(unspent.witnesses.size(), CACHE);
|
||||
|
||||
SaplingNoteData shallow = NoteWithHistory(CACHE, 5000);
|
||||
EXPECT_FALSE(TrimDeeplySpentNoteWitnesses(shallow, CACHE, CACHE)); // depth == cache size: still in reach
|
||||
EXPECT_EQ(shallow.witnesses.size(), CACHE);
|
||||
}
|
||||
|
||||
// A note without a nullifier is never trimmed (it is not known to be spent), and an empty list stays
|
||||
// empty: trimming must never be what leaves a note with no witnesses.
|
||||
TEST(WalletWitnessTrim, NoNullifierOrNoWitnessesIsLeftAlone)
|
||||
{
|
||||
SaplingNoteData noNf = NoteWithHistory(CACHE, 5000, false);
|
||||
EXPECT_FALSE(TrimDeeplySpentNoteWitnesses(noNf, CACHE + 1, CACHE));
|
||||
EXPECT_EQ(noNf.witnesses.size(), CACHE);
|
||||
|
||||
SaplingNoteData empty(TestIvk(), GetRandHash());
|
||||
EXPECT_FALSE(TrimDeeplySpentNoteWitnesses(empty, CACHE + 1, CACHE));
|
||||
EXPECT_TRUE(empty.witnesses.empty());
|
||||
}
|
||||
|
||||
// The serialized note shrinks with the list: what SetBestChain rewrites for every spent note.
|
||||
TEST(WalletWitnessTrim, SerializedSizeShrinks)
|
||||
{
|
||||
SaplingNoteData nd = NoteWithHistory(CACHE, 5000);
|
||||
const size_t before = ::GetSerializeSize(nd, SER_DISK, CLIENT_VERSION);
|
||||
ASSERT_TRUE(TrimDeeplySpentNoteWitnesses(nd, CACHE + 1, CACHE));
|
||||
const size_t after = ::GetSerializeSize(nd, SER_DISK, CLIENT_VERSION);
|
||||
EXPECT_LT(after * 20, before);
|
||||
}
|
||||
+5
-2
@@ -8398,9 +8398,12 @@ bool SendMessages(CNode* pto, bool fSendTrickle)
|
||||
LOCK(cs_vNodes);
|
||||
BOOST_FOREACH(CNode* pnode, vNodes)
|
||||
{
|
||||
// Periodically clear addrKnown to allow refresh broadcasts
|
||||
if (nLastRebroadcast)
|
||||
// Periodically clear addrKnown to allow refresh broadcasts. Under cs_addrKnown, as in
|
||||
// CloseSocketDisconnect: the message handler reads and inserts into it concurrently.
|
||||
if (nLastRebroadcast) {
|
||||
LOCK(pnode->cs_addrKnown);
|
||||
pnode->addrKnown.reset();
|
||||
}
|
||||
|
||||
// Rebroadcast our address
|
||||
AdvertizeLocal(pnode);
|
||||
|
||||
+6
-19
@@ -224,10 +224,12 @@ CBlockTemplate* CreateNewBlock(CPubKey _pk,const CScript& _scriptPubKeyIn, int32
|
||||
|
||||
CBlockIndex* pindexPrev = 0;
|
||||
{
|
||||
// this should stop create block ever exiting until it has returned something.
|
||||
boost::this_thread::disable_interruption();
|
||||
ENTER_CRITICAL_SECTION(cs_main);
|
||||
ENTER_CRITICAL_SECTION(mempool.cs);
|
||||
// Scoped, so every return below and any exception releases both, in reverse order. They
|
||||
// were taken and released by hand, which leaked them whenever something in here threw, and
|
||||
// released cs_main before mempool.cs. (The boost::this_thread::disable_interruption() that
|
||||
// stood here built a temporary, so it never disabled anything; with scoped locks an
|
||||
// interruption now unwinds cleanly.)
|
||||
LOCK2(cs_main, mempool.cs);
|
||||
pindexPrev = chainActive.LastTip();
|
||||
const int nHeight = pindexPrev->GetHeight() + 1;
|
||||
const Consensus::Params &consensusParams = chainparams.GetConsensus();
|
||||
@@ -664,8 +666,6 @@ CBlockTemplate* CreateNewBlock(CPubKey _pk,const CScript& _scriptPubKeyIn, int32
|
||||
}
|
||||
} else if ( (uint64_t)(txNew.vout[0].nValue) >= ASSETCHAINS_TIMELOCKGTE) {
|
||||
LogPrintf("timelocked chains not supported in this code!\n");
|
||||
LEAVE_CRITICAL_SECTION(cs_main);
|
||||
LEAVE_CRITICAL_SECTION(mempool.cs);
|
||||
return(0);
|
||||
} else if ( fNotarizationBlock && ASSETCHAINS_NOTARY_PAY[0] != 0 && pblock->vtx[1].vout.size() == 2 && pblock->vtx[1].vout[1].nValue == 0 ) {
|
||||
// Get the OP_RETURN for the notarization
|
||||
@@ -677,11 +677,6 @@ CBlockTemplate* CreateNewBlock(CPubKey _pk,const CScript& _scriptPubKeyIn, int32
|
||||
if ( totalsats == 0 )
|
||||
{
|
||||
LogPrintf("Could not create notary payment, trying again.\n");
|
||||
// Release unconditionally to match the unconditional ENTER above. The old
|
||||
// `if(!isStake)` guard leaked cs_main/mempool.cs on the isStake path (this
|
||||
// still return(0)s), while the success and timelock paths always release.
|
||||
LEAVE_CRITICAL_SECTION(cs_main);
|
||||
LEAVE_CRITICAL_SECTION(mempool.cs);
|
||||
return(0);
|
||||
}
|
||||
} else LogPrintf("vout 2 of notarization is not OP_RETURN scriptlen.%i\n", scriptlen);
|
||||
@@ -726,11 +721,6 @@ CBlockTemplate* CreateNewBlock(CPubKey _pk,const CScript& _scriptPubKeyIn, int32
|
||||
CValidationState state;
|
||||
if ( !TestBlockValidity(state, *pblock, pindexPrev, false, false)) // invokes CC checks
|
||||
{
|
||||
// Release unconditionally to match the unconditional ENTER above. The old
|
||||
// `if(!isStake)` guard leaked cs_main/mempool.cs on the isStake path (this
|
||||
// still return(0)s), while the success and timelock paths always release.
|
||||
LEAVE_CRITICAL_SECTION(cs_main);
|
||||
LEAVE_CRITICAL_SECTION(mempool.cs);
|
||||
LogPrintf("%s: TestBlockValidity failed!\n", __func__);
|
||||
//throw std::runtime_error("CreateNewBlock(): TestBlockValidity failed"); // crashes the node, moved to GetBlockTemplate and issue return.
|
||||
return(0);
|
||||
@@ -738,9 +728,6 @@ CBlockTemplate* CreateNewBlock(CPubKey _pk,const CScript& _scriptPubKeyIn, int32
|
||||
}
|
||||
}
|
||||
|
||||
LEAVE_CRITICAL_SECTION(cs_main);
|
||||
LEAVE_CRITICAL_SECTION(mempool.cs);
|
||||
|
||||
return pblocktemplate.release();
|
||||
}
|
||||
|
||||
|
||||
@@ -861,6 +861,11 @@ UniValue gettxoutsetinfo(const UniValue& params, bool fHelp, const CPubKey& mypk
|
||||
UniValue ret(UniValue::VOBJ);
|
||||
|
||||
CCoinsStats stats;
|
||||
// Hold cs_main across the flush and the scan: GetStats reads the best block and iterates a
|
||||
// snapshot of the coins database separately, and a flush landing in between would report the
|
||||
// UTXO totals of a different block than "height"/"bestblock" claim. The transparent UTXO set
|
||||
// of a fully shielded chain is small, so the scan is short.
|
||||
LOCK(cs_main);
|
||||
FlushStateToDisk();
|
||||
if (pcoinsTip->GetStats(stats)) {
|
||||
ret.push_back(Pair("height", (int64_t)stats.nHeight));
|
||||
|
||||
+10
-9
@@ -765,12 +765,10 @@ UniValue getblocktemplate(const UniValue& params, bool fHelp, const CPubKey& myp
|
||||
CBlockIndex* pindexPrevNew = chainActive.LastTip();
|
||||
nStart = GetTime();
|
||||
|
||||
// Create new block
|
||||
if(pblocktemplate)
|
||||
{
|
||||
delete pblocktemplate;
|
||||
pblocktemplate = NULL;
|
||||
}
|
||||
// Create new block. cs_main is released while it is built, so another getblocktemplate call can
|
||||
// run this block meanwhile: build into a local and only touch the shared pblocktemplate once cs_main
|
||||
// is held again, or that call could delete or overwrite it under us.
|
||||
CBlockTemplate* pblocktemplateNew = NULL;
|
||||
#ifdef ENABLE_WALLET
|
||||
CReserveKey reservekey(pwalletMain);
|
||||
#endif
|
||||
@@ -778,15 +776,18 @@ UniValue getblocktemplate(const UniValue& params, bool fHelp, const CPubKey& myp
|
||||
// CreateNewBlockWithKey can throw (keypool/wallet DB errors); cs_main must be held again by then.
|
||||
CMainUnlockScope unlockMain;
|
||||
#ifdef ENABLE_WALLET
|
||||
pblocktemplate = CreateNewBlockWithKey(reservekey,pindexPrevNew->GetHeight()+1,HUSH_MAXGPUCOUNT,false);
|
||||
pblocktemplateNew = CreateNewBlockWithKey(reservekey,pindexPrevNew->GetHeight()+1,HUSH_MAXGPUCOUNT,false);
|
||||
#else
|
||||
pblocktemplate = CreateNewBlockWithKey();
|
||||
pblocktemplateNew = CreateNewBlockWithKey();
|
||||
#endif
|
||||
}
|
||||
if (!pblocktemplate)
|
||||
if (!pblocktemplateNew)
|
||||
throw std::runtime_error("CreateNewBlock(): create block failed");
|
||||
//throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory or no available utxo for staking");
|
||||
|
||||
delete pblocktemplate;
|
||||
pblocktemplate = pblocktemplateNew;
|
||||
|
||||
// Need to update only after we know CreateNewBlockWithKey succeeded
|
||||
pindexPrev = pindexPrevNew;
|
||||
}
|
||||
|
||||
+4
-2
@@ -1274,14 +1274,16 @@ UniValue stratum_mining_authorize(StratumClient& client, const UniValue& params)
|
||||
boost::trim_right(username);
|
||||
}
|
||||
|
||||
CBitcoinAddress addr(get_stripped_username(username));
|
||||
const std::string strippedUsername = get_stripped_username(username);
|
||||
CBitcoinAddress addr(strippedUsername);
|
||||
|
||||
// If given the special address "x", mine to the default address given by -stratumaddress
|
||||
// This means a miner can run a private pool without TLS and not
|
||||
// worry about MITM attacks that change addresses, and leaks less metadata.
|
||||
// It also means many miners can be used and updating their mining address does not
|
||||
// require any changes on each miner, just restart dragonxd with a new -stratumaddress
|
||||
if(addr.ToString() == "x") {
|
||||
// Compare the name as sent: "x" is not a valid address, so addr.ToString() never returns it.
|
||||
if(strippedUsername == "x") {
|
||||
addr = CBitcoinAddress(GetArg("-stratumaddress", ""));
|
||||
const std::string msg = strprintf("%s: Authorized client with default stratum address=%s", __func__, addr.ToString());
|
||||
LogPrint("stratum", "%s\n", msg);
|
||||
|
||||
@@ -294,7 +294,7 @@ bool AsyncRPCOperation_autoshieldcoinbase::main_impl() {
|
||||
// from below), not the stale enqueue-time targetHeight_, so a queue delay
|
||||
// cannot slip a straddling expiry past this guard.
|
||||
auto nextActivationHeight = NextActivationHeight(tipHeight, consensusParams);
|
||||
if (nextActivationHeight && tipHeight + AUTO_OP_EXPIRY_DELTA >= nextActivationHeight.get()) {
|
||||
if (nextActivationHeight && tipHeight + AutoOpExpiryDelta() >= nextActivationHeight.get()) {
|
||||
LogPrintf("%s: autoshield tx could expire across a NU activation. Skipping this round.\n", opid);
|
||||
return true;
|
||||
}
|
||||
@@ -414,7 +414,7 @@ bool AsyncRPCOperation_autoshieldcoinbase::main_impl() {
|
||||
// stale enqueue-time height here meant the guard was checking a height the
|
||||
// transaction was not actually signed against.
|
||||
auto builder = TransactionBuilder(consensusParams, tipHeight, pwalletMain);
|
||||
builder.SetExpiryHeight(tipHeight + AUTO_OP_EXPIRY_DELTA);
|
||||
builder.SetExpiryHeight(tipHeight + AutoOpExpiryDelta());
|
||||
builder.SetFee(fee);
|
||||
|
||||
for (const auto& t : inputs) {
|
||||
@@ -461,6 +461,9 @@ bool AsyncRPCOperation_autoshieldcoinbase::main_impl() {
|
||||
}
|
||||
|
||||
LogPrintf("%s: autoshield tx FAILED in CommitTransaction, txid=%s\n", opid, tx.GetHash().ToString());
|
||||
set_error_code(RPC_WALLET_ERROR);
|
||||
set_error_message(strprintf("Autoshield transaction %s was not accepted into the mempool (see debug.log for the "
|
||||
"reason). The next round tries again.", tx.GetHash().ToString()));
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
@@ -313,7 +313,7 @@ bool AsyncRPCOperation_saplingconsolidation::main_impl() {
|
||||
// the NU-straddle guard agree with the height the tx is signed for. Mirrors
|
||||
// the autoshield op (commit 65130c312).
|
||||
auto nextActivationHeight = NextActivationHeight(tipHeight, consensusParams);
|
||||
if (nextActivationHeight && tipHeight + AUTO_OP_EXPIRY_DELTA >= nextActivationHeight.get()) {
|
||||
if (nextActivationHeight && tipHeight + AutoOpExpiryDelta() >= nextActivationHeight.get()) {
|
||||
LogPrintf("%s: Consolidation txs would be created before a NU activation but may expire after. Skipping this round.\n",opid);
|
||||
setConsolidationResult(ConsolidationTally());
|
||||
return status;
|
||||
@@ -469,7 +469,7 @@ bool AsyncRPCOperation_saplingconsolidation::main_impl() {
|
||||
const AddressNotes& group = groups[planned.group];
|
||||
|
||||
auto builder = TransactionBuilder(consensusParams, tipHeight, pwalletMain);
|
||||
builder.SetExpiryHeight(tipHeight + AUTO_OP_EXPIRY_DELTA);
|
||||
builder.SetExpiryHeight(tipHeight + AutoOpExpiryDelta());
|
||||
|
||||
CAmount amountToSend = 0;
|
||||
for (const SaplingNoteEntry& entry : planned.notes)
|
||||
|
||||
@@ -192,7 +192,7 @@ bool AsyncRPCOperation_sweep::main_impl() {
|
||||
// targetHeight_, so a queue delay cannot slip a straddling expiry past this
|
||||
// guard. Mirrors the autoshield op (commit 65130c312).
|
||||
auto nextActivationHeight = NextActivationHeight(tipHeight, consensusParams);
|
||||
if (nextActivationHeight && tipHeight + AUTO_OP_EXPIRY_DELTA >= nextActivationHeight.get()) {
|
||||
if (nextActivationHeight && tipHeight + AutoOpExpiryDelta() >= nextActivationHeight.get()) {
|
||||
LogPrintf("%s: Sweep txs would be created before a NU activation but may expire after. Skipping this round.\n", getId());
|
||||
setSweepResult(0, 0, std::vector<std::string>());
|
||||
sweepComplete_ = true; // nothing to do this round; back nextSweep off one interval instead of re-dispatching every block
|
||||
@@ -347,12 +347,12 @@ bool AsyncRPCOperation_sweep::main_impl() {
|
||||
buildHeight = (chainActive.Tip() != NULL) ? chainActive.Tip()->GetHeight() : tipHeight;
|
||||
}
|
||||
auto nextActivation = NextActivationHeight(buildHeight, consensusParams);
|
||||
if (nextActivation && buildHeight + AUTO_OP_EXPIRY_DELTA >= nextActivation.get()) {
|
||||
if (nextActivation && buildHeight + AutoOpExpiryDelta() >= nextActivation.get()) {
|
||||
LogPrintf("%s: Sweep txs would now be created before a NU activation but may expire after. Stopping this round.\n", getId());
|
||||
break;
|
||||
}
|
||||
auto builder = TransactionBuilder(consensusParams, buildHeight, pwalletMain);
|
||||
builder.SetExpiryHeight(buildHeight + AUTO_OP_EXPIRY_DELTA);
|
||||
builder.SetExpiryHeight(buildHeight + AutoOpExpiryDelta());
|
||||
LogPrintf("%s: Beginning creating transaction with Sapling output amount=%s\n", getId(), FormatMoney(amountToSend - fee));
|
||||
|
||||
// Add Sapling spends, each with the witness it was selected with
|
||||
@@ -411,6 +411,12 @@ bool AsyncRPCOperation_sweep::main_impl() {
|
||||
numTxCreated++;
|
||||
} else {
|
||||
LogPrintf("%s: Sweep transaction FAILED in CommitTransaction, txid=%s\n",opid , tx.GetHash().ToString());
|
||||
// Say why the round failed: this used to finish as "failed" with an empty error. The mempool's
|
||||
// reason is in debug.log just above (most often a note already spent by another transaction).
|
||||
set_error_code(RPC_WALLET_ERROR);
|
||||
set_error_message(strprintf("Sweep transaction %s was not accepted into the mempool (see debug.log for "
|
||||
"the reason; usually one of its notes was spent by another transaction "
|
||||
"meanwhile). The next round sweeps what is left.", tx.GetHash().ToString()));
|
||||
setSweepResult(numTxCreated, amountSwept, sweepTxIds);
|
||||
status = false;
|
||||
break;
|
||||
|
||||
@@ -113,23 +113,6 @@ void EnsureWalletIsUnlocked()
|
||||
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first.");
|
||||
}
|
||||
|
||||
void Lock2NSPV(const CPubKey &pk)
|
||||
{
|
||||
if (!pk.IsValid())
|
||||
{
|
||||
ENTER_CRITICAL_SECTION(cs_main);
|
||||
ENTER_CRITICAL_SECTION(pwalletMain->cs_wallet);
|
||||
}
|
||||
}
|
||||
|
||||
void Unlock2NSPV(const CPubKey &pk)
|
||||
{
|
||||
if (!pk.IsValid())
|
||||
{
|
||||
LEAVE_CRITICAL_SECTION(cs_main);
|
||||
LEAVE_CRITICAL_SECTION(pwalletMain->cs_wallet);
|
||||
}
|
||||
}
|
||||
|
||||
void WalletTxToJSON(const CWalletTx& wtx, UniValue& entry)
|
||||
{
|
||||
@@ -3317,6 +3300,8 @@ UniValue z_consolidationstatus(const UniValue& params, bool fHelp, const CPubKey
|
||||
"{\n"
|
||||
" \"consolidation\" : true|false, (boolean) whether periodic consolidation (-consolidation) is on\n"
|
||||
" \"running\" : true|false, (boolean) whether a round is in flight\n"
|
||||
" \"waiting_for_sweep\" : true|false, (boolean) a due round is waiting for a zsweep round to end;\n"
|
||||
" no new sweep round starts until it has run\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"
|
||||
@@ -3365,6 +3350,7 @@ UniValue z_consolidationstatus(const UniValue& params, bool fHelp, const CPubKey
|
||||
UniValue ret(UniValue::VOBJ);
|
||||
ret.push_back(Pair("consolidation", pwalletMain->fSaplingConsolidationEnabled));
|
||||
ret.push_back(Pair("running", pwalletMain->fConsolidationRunning));
|
||||
ret.push_back(Pair("waiting_for_sweep", pwalletMain->fConsolidationWaiting));
|
||||
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));
|
||||
@@ -3553,6 +3539,8 @@ UniValue z_sweepstatus(const UniValue& params, bool fHelp, const CPubKey& mypk)
|
||||
" \"running\" : true|false, (boolean) whether a sweep round is in flight\n"
|
||||
" \"wallet_locked\" : true|false, (boolean) the wallet is encrypted and locked, so nothing can be swept\n"
|
||||
" until it is unlocked with walletpassphrase\n"
|
||||
" \"waiting_for_consolidation\" : true|false, (boolean) a due round is waiting for a consolidation round to end;\n"
|
||||
" no new consolidation round starts until it has run\n"
|
||||
" \"amount_swept\" : x.xxx, (numeric) DRGX sent to the sweep address since startup\n"
|
||||
" \"next_zsweep\" : n, (numeric) height of the next round\n"
|
||||
" \"zsweepinterval\" : n, (numeric) blocks between rounds\n"
|
||||
@@ -3573,6 +3561,7 @@ UniValue z_sweepstatus(const UniValue& params, bool fHelp, const CPubKey& mypk)
|
||||
ret.push_back(Pair("zsweep", pwalletMain->fSweepEnabled));
|
||||
ret.push_back(Pair("running", pwalletMain->fSweepRunning));
|
||||
ret.push_back(Pair("wallet_locked", pwalletMain->IsLocked()));
|
||||
ret.push_back(Pair("waiting_for_consolidation", pwalletMain->fSweepWaiting));
|
||||
ret.push_back(Pair("amount_swept", ValueFromAmount(pwalletMain->amountSwept)));
|
||||
ret.push_back(Pair("next_zsweep", pwalletMain->nextSweep));
|
||||
ret.push_back(Pair("zsweepinterval", pwalletMain->sweepInterval));
|
||||
|
||||
+66
-13
@@ -640,6 +640,7 @@ void CWallet::RunSaplingSweep(int blockHeight) {
|
||||
}
|
||||
|
||||
if (!fSweepEnabled) {
|
||||
fSweepWaiting = false;
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -666,18 +667,23 @@ void CWallet::RunSaplingSweep(int blockHeight) {
|
||||
LogPrintf("%s: wallet locked; not sweeping at height=%d. Unlock it with walletpassphrase "
|
||||
"for zsweep to resume\n", __func__, blockHeight);
|
||||
nextSweep = sweepInterval + blockHeight;
|
||||
fSweepWaiting = false;
|
||||
return;
|
||||
}
|
||||
|
||||
//Don't Run if consolidation will run soon.
|
||||
if (fSaplingConsolidationEnabled && nextConsolidation - 5 <= blockHeight) {
|
||||
LogPrintf("%s: not sweeping since next consolidation is within 5 blocks, nextConsolidation=%d , blockHeight=%d\n", __func__, nextConsolidation, blockHeight);
|
||||
return;
|
||||
}
|
||||
|
||||
//Don't Run While consolidation is running.
|
||||
// Strict turns with consolidation (see fSweepWaiting / fConsolidationWaiting). This replaces a
|
||||
// "consolidation is due within 5 blocks" blackout, which with consolidationinterval=5 was always true.
|
||||
//Don't Run While consolidation is running: wait, and take the next turn.
|
||||
if (fConsolidationRunning) {
|
||||
LogPrintf("%s: not sweeping since consolidation is currently running at height=%d\n", __func__, blockHeight);
|
||||
LogPrintf("%s: not sweeping since consolidation is currently running at height=%d; the sweep goes next\n", __func__, blockHeight);
|
||||
fSweepWaiting = true;
|
||||
return;
|
||||
}
|
||||
|
||||
//A consolidation round that came due while a sweep was running goes first.
|
||||
if (fConsolidationWaiting && fSaplingConsolidationEnabled) {
|
||||
LogPrintf("%s: not sweeping since a consolidation round is waiting for its turn at height=%d\n", __func__, blockHeight);
|
||||
fSweepWaiting = false; // never both waiting: that would leave neither op able to start
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -688,6 +694,7 @@ void CWallet::RunSaplingSweep(int blockHeight) {
|
||||
}
|
||||
|
||||
fSweepRunning = true;
|
||||
fSweepWaiting = false;
|
||||
|
||||
std::shared_ptr<AsyncRPCQueue> q = getAsyncRPCQueue();
|
||||
std::shared_ptr<AsyncRPCOperation> lastOperation = q->getOperationForId(saplingSweepOperationId);
|
||||
@@ -720,6 +727,7 @@ void CWallet::RunSaplingConsolidation(int blockHeight) {
|
||||
LOCK(cs_wallet);
|
||||
|
||||
if (!fSaplingConsolidationEnabled) {
|
||||
fConsolidationWaiting = false;
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -739,13 +747,23 @@ void CWallet::RunSaplingConsolidation(int blockHeight) {
|
||||
if (IsLocked()) {
|
||||
LogPrintf("%s: wallet locked; not consolidating at height=%d\n", __func__, blockHeight);
|
||||
nextConsolidation = consolidationInterval + blockHeight;
|
||||
fConsolidationWaiting = false;
|
||||
return;
|
||||
}
|
||||
|
||||
LogPrintf("%s: consolidation enabled at blockHeight=%d fSweepRunning=%d\n", __func__, blockHeight, fSweepRunning );
|
||||
|
||||
//Don't Run While a sweep is running: wait, and take the next turn (nextConsolidation stays put).
|
||||
if (fSweepRunning) {
|
||||
LogPrintf("%s: not consolidating since sweep is currently running at height=%d\n", __func__, blockHeight);
|
||||
LogPrintf("%s: not consolidating since sweep is currently running at height=%d; consolidation goes next\n", __func__, blockHeight);
|
||||
fConsolidationWaiting = true;
|
||||
return;
|
||||
}
|
||||
|
||||
//A sweep that came due while this op was running goes first.
|
||||
if (fSweepWaiting && fSweepEnabled) {
|
||||
LogPrintf("%s: not consolidating since a due sweep is waiting for its turn at height=%d\n", __func__, blockHeight);
|
||||
fConsolidationWaiting = false; // never both waiting
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -756,6 +774,7 @@ void CWallet::RunSaplingConsolidation(int blockHeight) {
|
||||
|
||||
LogPrintf("%s: creating consolidation operation at blockHeight=%d\n", __func__, blockHeight);
|
||||
fConsolidationRunning = true;
|
||||
fConsolidationWaiting = false;
|
||||
std::shared_ptr<AsyncRPCQueue> q = getAsyncRPCQueue();
|
||||
std::shared_ptr<AsyncRPCOperation> lastOperation = q->getOperationForId(saplingConsolidationOperationId);
|
||||
if (lastOperation != nullptr) {
|
||||
@@ -1435,6 +1454,17 @@ void ClearSingleNoteWitnessCache(NoteData* nd)
|
||||
nd->witnessRootValidated = false;
|
||||
}
|
||||
|
||||
bool TrimDeeplySpentNoteWitnesses(SaplingNoteData& nd, unsigned int nSpendDepth, unsigned int nCacheSize)
|
||||
{
|
||||
// Never empty the list: UpdateSaplingNullifierNoteMapWithTx drops the nullifier of a note with no
|
||||
// witnesses, and a spent note without a nullifier is counted as unspent by GetFilteredNotes.
|
||||
if (!nd.nullifier || nSpendDepth <= nCacheSize || nd.witnesses.size() <= 1)
|
||||
return false;
|
||||
while (nd.witnesses.size() > 1)
|
||||
nd.witnesses.pop_back(); // oldest snapshots are at the back; front() stays the one at witnessHeight
|
||||
return true;
|
||||
}
|
||||
|
||||
// A note without a nullifier is never extended by BuildWitnessCache (its pending-note gate requires one),
|
||||
// so it doesn't pull the rebuild's start height down.
|
||||
int CWallet::SaplingWitnessMinimumHeight(const boost::optional<uint256>& nullifier, int nWitnessHeight, int nMinimumHeight)
|
||||
@@ -1735,6 +1765,7 @@ void CWallet::BuildWitnessCache(const CBlockIndex* pindex, bool witnessOnly)
|
||||
// cost changes from O(blocks * walletSize) to O(blocks + activeNotes).
|
||||
struct PendingNote { int startWitnessHeight; SaplingNoteData* nd; };
|
||||
std::vector<PendingNote> pending;
|
||||
int nNotesTrimmed = 0;
|
||||
for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
|
||||
if (wtxItem.second.mapSaplingNoteData.empty())
|
||||
continue;
|
||||
@@ -1746,14 +1777,24 @@ void CWallet::BuildWitnessCache(const CBlockIndex* pindex, bool witnessOnly)
|
||||
continue;
|
||||
if (nd->witnesses.empty()) // cannot extend (front() would be UB); the original gate also never matched these in practice
|
||||
continue;
|
||||
if (GetSaplingSpendDepth(*nd->nullifier) > WITNESS_CACHE_SIZE)
|
||||
const unsigned int nSpendDepth = GetSaplingSpendDepth(*nd->nullifier);
|
||||
if (nSpendDepth > WITNESS_CACHE_SIZE) {
|
||||
// Spent beyond reorg reach: no longer extended, so its older snapshots are dead weight.
|
||||
if (TrimDeeplySpentNoteWitnesses(*nd, nSpendDepth, WITNESS_CACHE_SIZE))
|
||||
nNotesTrimmed++;
|
||||
continue;
|
||||
}
|
||||
// Only notes that still lag the build target need extension. The lowest such witnessHeight
|
||||
// is exactly startHeight-1 (startHeight = nMinimumHeight+1 from SaplingWitnessMinimumHeight).
|
||||
if (nd->witnessHeight >= startHeight - 1 && nd->witnessHeight <= pindex->GetHeight() - 1)
|
||||
pending.push_back({ nd->witnessHeight, nd });
|
||||
}
|
||||
}
|
||||
if (nNotesTrimmed > 0) {
|
||||
nWitnessGeneration++; // the next SetBestChain (or the shutdown save) writes the shorter lists
|
||||
LogPrintf("%s: dropped the older witnesses of %d note(s) spent more than %u blocks ago\n",
|
||||
__func__, nNotesTrimmed, WITNESS_CACHE_SIZE);
|
||||
}
|
||||
std::sort(pending.begin(), pending.end(),
|
||||
[](const PendingNote& a, const PendingNote& b) { return a.startWitnessHeight < b.startWitnessHeight; });
|
||||
|
||||
@@ -4310,7 +4351,9 @@ std::vector<uint256> CWallet::ResendWalletTransactionsBefore(int64_t nTime)
|
||||
{
|
||||
std::vector<uint256> result;
|
||||
|
||||
LOCK(cs_wallet);
|
||||
// Both callers (the periodic Broadcast signal from SendMessages, and resendwallettransactions) hold
|
||||
// cs_main already; GetDepthInMainChain below needs it.
|
||||
LOCK2(cs_main, cs_wallet);
|
||||
// Sort them in chronological order
|
||||
multimap<unsigned int, CWalletTx*> mapSorted;
|
||||
uint32_t now = (uint32_t)time(NULL);
|
||||
@@ -4318,7 +4361,7 @@ std::vector<uint256> CWallet::ResendWalletTransactionsBefore(int64_t nTime)
|
||||
|
||||
// vector of wallet transactions to delete
|
||||
std::vector<uint256> vwtxh;
|
||||
uint32_t erased = 0, skipped = 0;
|
||||
uint32_t erased = 0, skipped = 0, expired = 0;
|
||||
|
||||
BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
|
||||
{
|
||||
@@ -4327,10 +4370,18 @@ std::vector<uint256> CWallet::ResendWalletTransactionsBefore(int64_t nTime)
|
||||
if (wtx.nTimeReceived > nTime)
|
||||
continue;
|
||||
|
||||
// A mined transaction has nothing to rebroadcast. It used to reach the expiry test below, and every
|
||||
// confirmed tx is past its expiry height a few hundred blocks after it was mined, so each pass logged
|
||||
// one "ignoring expired tx" line per wallet tx ever made: 1.1M lines (354 MB of debug.log) in a day on
|
||||
// an exchange-style wallet of ~15k txs.
|
||||
if (wtx.GetDepthInMainChain() > 0)
|
||||
continue;
|
||||
|
||||
// Do not relay expired transactions, to avoid other nodes banning us
|
||||
// Current code will not ban nodes relaying expired txs but older nodes will
|
||||
if (wtx.nExpiryHeight > 0 && wtx.nExpiryHeight < chainActive.LastTip()->GetHeight()) {
|
||||
LogPrintf("%s: ignoring expired tx %s with expiry %d at height %d\n", __func__, wtx.GetHash().ToString().c_str(), wtx.nExpiryHeight, chainActive.LastTip()->GetHeight() );
|
||||
LogPrint("wallet", "%s: ignoring expired tx %s with expiry %d at height %d\n", __func__, wtx.GetHash().ToString().c_str(), wtx.nExpiryHeight, chainActive.LastTip()->GetHeight() );
|
||||
expired++;
|
||||
// TODO: expired detection doesn't seem to work right
|
||||
// append to list of txs to delete
|
||||
// vwtxh.push_back(wtx.GetHash());
|
||||
@@ -4376,6 +4427,8 @@ std::vector<uint256> CWallet::ResendWalletTransactionsBefore(int64_t nTime)
|
||||
if(erased > 0 || skipped > 0) {
|
||||
LogPrintf("%s: Prevented relaying %d and erased %d transactions which are too old\n", __func__, skipped, erased);
|
||||
}
|
||||
if (expired > 0)
|
||||
LogPrintf("%s: not relaying %u expired unconfirmed transaction(s) (-debug=wallet lists them)\n", __func__, expired);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
+22
-1
@@ -132,7 +132,12 @@ 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
|
||||
// Expiry window for the transactions zsweep, consolidation and autoshield build, and for their NU-straddle
|
||||
// guards: the same -txexpirydelta (default 200) as any other wallet transaction. These used a fixed 15 blocks,
|
||||
// which ran out before the wallet's rebroadcast (every 0-30 min, and only for txs a few minutes older than the
|
||||
// last block) ever retried a tx the half-of-peers relay had not carried to a miner: on a node with a handful of
|
||||
// peers about one sweep tx in five expired unmined, while the sweep had already counted it as swept.
|
||||
inline int AutoOpExpiryDelta() { return (int)expiryDelta; }
|
||||
|
||||
extern const char * DEFAULT_WALLET_DAT;
|
||||
|
||||
@@ -394,6 +399,13 @@ public:
|
||||
typedef std::map<JSOutPoint, SproutNoteData> mapSproutNoteData_t;
|
||||
typedef std::map<SaplingOutPoint, SaplingNoteData> mapSaplingNoteData_t;
|
||||
|
||||
//! For a note spent nSpendDepth blocks ago: once that is deeper than nCacheSize (WITNESS_CACHE_SIZE) no reorg
|
||||
//! can un-spend it and BuildWitnessCache stops extending it, so only the newest witness is kept. That one holds
|
||||
//! the note's position (its nullifier) and the root VerifyAndSetInitialWitness validates; the older snapshots,
|
||||
//! up to nCacheSize per note, were otherwise kept in memory and rewritten to wallet.dat for every spent note
|
||||
//! the wallet ever had. Returns true if anything was dropped; never empties the list.
|
||||
bool TrimDeeplySpentNoteWitnesses(SaplingNoteData& nd, unsigned int nSpendDepth, unsigned int nCacheSize);
|
||||
|
||||
/** Sapling note, its location in a transaction, and number of confirmations. */
|
||||
struct SaplingNoteEntry
|
||||
{
|
||||
@@ -903,6 +915,15 @@ public:
|
||||
bool fSweepEnabled = false;
|
||||
bool fSweepExternalEnabled = false;
|
||||
bool fSweepRunning = false;
|
||||
// Strict turns between zsweep and consolidation: an op that came due while the other was running
|
||||
// goes next. fSweepWaiting is set when a due sweep finds a consolidation round running, and keeps a
|
||||
// new consolidation round from starting; fConsolidationWaiting is the same the other way round, and
|
||||
// keeps a new sweep round from starting. Each is cleared when its own op is dispatched (or turned
|
||||
// off, or skipped for a locked wallet). Without them the two starved each other: the sweep lost every
|
||||
// block to a 5-block "consolidation is due soon" blackout, and once that was relaxed, back-to-back
|
||||
// sweep rounds left consolidation no block at all.
|
||||
bool fSweepWaiting = false;
|
||||
bool fConsolidationWaiting = false;
|
||||
|
||||
// Automatic coinbase shielding (t->z). The real default is computed in
|
||||
// init.cpp: ON only for known-recoverable seed provenance (CREATED/RESTORED),
|
||||
|
||||
Reference in New Issue
Block a user