// 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 #include #include #include #include #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 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 blocks; std::deque index; CBlockIndex* savedTip; CCoinsView coinsBase; CCoinsViewCache coins{&coinsBase}; CCoinsViewCache* savedCoinsTip; RootsChain(int nBlocks, const std::vector& inBlock1, const std::map& 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::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> raw(32, 0x5a); HDSeed seed(raw); return libzcash::SaplingExtendedSpendingKey::Master(seed); } std::vector Txs(int n) { std::vector 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 Witnesses(int nNotes, int salt, uint256& rootOut) { SaplingMerkleTree tree; std::vector 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 txs; std::map roots; std::vector wBelow, wAt; int nTxs; }; // Fills the wallet: tx i gets notes of the kinds kinds(i) returns, in output order. template 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 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 memo; memo.fill(0); auto enc = libzcash::SaplingNotePlaintext(note, memo).encrypt(note.pk_d); assert(static_cast(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 States(RootsWallet& wallet) { LOCK(wallet.cs_wallet); std::map 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(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 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 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 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 kindOf; for (int i = 0; i < fx.nTxs; i++) { std::vector 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 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 ks = MixedKinds(i); if (i == 17) ks.push_back(WRONG_ROOT); return ks; }; std::map 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 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{NOT_IN_CHAIN, NOT_IN_CHAIN} : std::vector{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{WRONG_ROOT, NO_NULLIFIER_VALID} : MixedKinds(i); }; const SaplingOutPoint seeded(fx.txs[iSeeded].GetHash(), 0), sibling(fx.txs[iSeeded].GetHash(), 1); std::map 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 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); } }