wallet: compute the witness roots of the startup check on worker threads
After every start the first VerifyAndSetInitialWitness pass checks each note's witness: front().root(), compared with hashFinalSaplingRoot at the witness height. root() walks the whole depth-32 path, about 1.7-2.4 ms per note, serially and with cs_main and cs_wallet held: about 14 s for 8,200 notes on regtest, 28-39 s for a 16k-note wallet. With the witnesses now saved at shutdown this pass no longer hides behind the rescan; it holds the first block after start, and every RPC waiting on those locks, for that long, and a stop sent meanwhile waited for all of it. Compute those roots first, the way BuildWitnessCache's Phase 2 spreads the extension: under the existing locks collect the notes the loop will call root() for (confirmed tx, full viewing key, nullifier, witnesses, witnessHeight > 0, not yet validated, block at witnessHeight on the active chain), compute their roots on -witnessbuildthreads threads (one per core by default; inline below 8 notes, or for any shard whose thread cannot start), then run the existing loop unchanged, taking each root from that table. The loop changes a note's witnesses only at that note's own turn (a sibling's reseed rewrites nullifiers, never witnesses), so every root is the root of the witness being checked and the validated/reseeded decisions, their order and nMinimumHeight are those of the serial code. A note the selection misses, or whose root() threw on a worker, gets its root computed inline as before, so a throw surfaces at the same note. The root-equality check and the reseed on a mismatch are untouched. Between the two phases nothing has been changed yet, so a stop requested while the roots are computed ends the pass there; the next block or the next start redoes it. The thread-count and thread-start-with-fallback code is shared with Phase 2 (WitnessThreadCount, RunWitnessShards), with the same results. On regtest (U.base, 24 threads): 2,063 roots in 920 ms against 3.2-4.2 s for the serial pass. The new gtests run the same synthetic wallet with one thread and with several and compare every note's resulting state, including a root mismatch whose reseed throws mid-pass. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -21,7 +21,8 @@ hush_gtest_SOURCES = \
|
||||
gtest/test_wallet_dbenv.cpp \
|
||||
gtest/test_wallet_notecache.cpp \
|
||||
gtest/test_wallet_history.cpp \
|
||||
gtest/test_wallet_shutdownsave.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)
|
||||
|
||||
@@ -0,0 +1,354 @@
|
||||
// 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 "chain.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 "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;
|
||||
}
|
||||
|
||||
enum Kind { VALID_BELOW_TIP, VALID_AT_TIP, AHEAD_OF_CHAIN, ALREADY_VALIDATED, WRONG_ROOT, NOT_IN_CHAIN };
|
||||
|
||||
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;
|
||||
}
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
savedThreads = mapArgs.count("-witnessbuildthreads") ? mapArgs["-witnessbuildthreads"] : "";
|
||||
}
|
||||
void TearDown() override {
|
||||
fRequestShutdown = 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);
|
||||
}
|
||||
+97
-25
@@ -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>
|
||||
@@ -1345,6 +1347,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);
|
||||
@@ -1353,6 +1388,64 @@ int CWallet::VerifyAndSetInitialWitness(const CBlockIndex* pindex, bool witnessO
|
||||
int nWitnessTotalTxCount = mapWallet.size();
|
||||
int nMinimumHeight = pindex->GetHeight();
|
||||
|
||||
// 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) {
|
||||
if (wtxItem.second.mapSaplingNoteData.empty() || 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;
|
||||
|
||||
@@ -1405,7 +1498,7 @@ int CWallet::VerifyAndSetInitialWitness(const CBlockIndex* pindex, bool witnessO
|
||||
nMinimumHeight = SaplingWitnessMinimumHeight(item.second.nullifier, nd->witnessHeight, nMinimumHeight);
|
||||
continue;
|
||||
}
|
||||
if (nd->witnesses.front().root() == whIndex->hashFinalSaplingRoot) {
|
||||
if (cachedRoot(nd) == whIndex->hashFinalSaplingRoot) {
|
||||
nd->witnessRootValidated = true;
|
||||
nMinimumHeight = SaplingWitnessMinimumHeight(item.second.nullifier, nd->witnessHeight, nMinimumHeight);
|
||||
continue;
|
||||
@@ -1414,7 +1507,7 @@ 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) {
|
||||
@@ -1604,12 +1697,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;
|
||||
@@ -1694,23 +1782,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)
|
||||
|
||||
Reference in New Issue
Block a user