#include "init.h" #include "ui_interface.h" // Fixture for tests that a detected Orchard note commitment tree divergence triggers // the clean-shutdown recovery (OrchardNoteCommitmentTreeDiverged) instead of aborting. // SetUp connects a mock for the operator notification; TearDown disconnects it and // clears any requested shutdown — guaranteed even on an early return (ASSERT_*) or an // exception. class OrchardDivergenceTest : public ::testing::Test { protected: void SetUp() override { ConnectMockUIInterface(mock_); } void TearDown() override { DisconnectMockUIInterface(); } MockUIInterface mock_; }; // Regression test for #5960. When the re-enabled forward consistency check connects a // block near the tip and finds the wallet's Orchard note commitment tree root // inconsistent with the block's consensus root, it must request a clean shutdown (so // the operator can restart with -rescan) rather than abort the node. TEST_F(OrchardDivergenceTest, ForwardConsistencyCheckRequestsCleanShutdown) { auto consensusParams = RegtestActivateNU5(); TestWallet wallet(Params()); wallet.GenerateNewSeed(); LOCK2(cs_main, wallet.cs_wallet); MerkleFrontiers frontiers; CBlock block; CBlockIndex fakeIndex {block}; fakeIndex.nHeight = 0; // Record a consensus Orchard root that the wallet's tree will not match, standing // in for a divergence between the wallet and consensus. fakeIndex.hashFinalOrchardRoot = uint256S("ff"); auto blockHash = block.GetHash(); mapBlockIndex.insert(std::make_pair(blockHash, &fakeIndex)); chainActive.SetTip(&fakeIndex); ASSERT_FALSE(ShutdownRequested()); // The divergence handler must notify the operator via ThreadSafeMessageBox. EXPECT_CALL(mock_, ThreadSafeMessageBox( ::testing::_, ::testing::_, CClientUIInterface::MSG_ERROR)).WillOnce(::testing::Return(false)); // Connect the block with the consistency check enabled. wallet.IncrementNoteWitnesses(consensusParams, &fakeIndex, &block, frontiers, true, true); // The divergence must have been detected and a clean shutdown requested, not an abort. EXPECT_TRUE(ShutdownRequested()); // Tear down (the mock and shutdown cleanup is handled by the fixture's TearDown). chainActive.SetTip(NULL); mapBlockIndex.erase(blockHash); RegtestDeactivateNU5(); } // Regression test for #5960. When a reorg disconnects a block and DecrementNoteWitnesses // finds the rewound wallet Orchard tree inconsistent with the parent block's consensus // root, it must request a clean shutdown rather than abort the node — the restart-proof // crash loop that motivated this work. Previously this was a fatal assertion. TEST_F(OrchardDivergenceTest, DisconnectRequestsCleanShutdown) { auto consensusParams = RegtestActivateNU5(); TestWallet wallet(Params()); wallet.GenerateNewSeed(); LOCK2(cs_main, wallet.cs_wallet); MerkleFrontiers frontiers; // Connect two blocks so the wallet has checkpoints at heights 0 and 1, so that // disconnecting block 1 rewinds to block 0. The consistency check is left off // during setup (false) so the connect path does not itself request a shutdown. CBlock block0; CBlockIndex fakeIndex0 {block0}; fakeIndex0.nHeight = 0; // Record a consensus Orchard root for block 0 that the wallet will not match. fakeIndex0.hashFinalOrchardRoot = uint256S("ff"); auto blockHash0 = block0.GetHash(); mapBlockIndex.insert(std::make_pair(blockHash0, &fakeIndex0)); chainActive.SetTip(&fakeIndex0); wallet.IncrementNoteWitnesses(consensusParams, &fakeIndex0, &block0, frontiers, true, false); CBlock block1; block1.hashPrevBlock = blockHash0; CBlockIndex fakeIndex1 {block1}; fakeIndex1.nHeight = 1; fakeIndex1.pprev = &fakeIndex0; auto blockHash1 = block1.GetHash(); mapBlockIndex.insert(std::make_pair(blockHash1, &fakeIndex1)); chainActive.SetTip(&fakeIndex1); wallet.IncrementNoteWitnesses(consensusParams, &fakeIndex1, &block1, frontiers, true, false); ASSERT_FALSE(ShutdownRequested()); // The divergence handler must notify the operator via ThreadSafeMessageBox. EXPECT_CALL(mock_, ThreadSafeMessageBox( ::testing::_, ::testing::_, CClientUIInterface::MSG_ERROR)).WillOnce(::testing::Return(false)); // Disconnect block 1: this rewinds to block 0, whose recorded consensus root does // not match the wallet's, so a clean shutdown must be requested. wallet.DecrementNoteWitnesses(consensusParams, &fakeIndex1); EXPECT_TRUE(ShutdownRequested()); // Tear down (the mock and shutdown cleanup is handled by the fixture's TearDown). chainActive.SetTip(NULL); mapBlockIndex.erase(blockHash0); mapBlockIndex.erase(blockHash1); RegtestDeactivateNU5(); } #include "gtest/utils.h" ConnectMockUIInterface(mock_); DisconnectMockUIInterface(); #include "ui_interface.h" #include void ConnectMockUIInterface(MockUIInterface& mock) { uiInterface.ThreadSafeMessageBox.disconnect_all_slots(); uiInterface.ThreadSafeMessageBox.connect( [&mock](const std::string& message, const std::string& caption, unsigned int style) { return mock.ThreadSafeMessageBox(message, caption, style); }); } // Defined in init.cpp. extern std::atomic fRequestShutdown; void DisconnectMockUIInterface() { uiInterface.ThreadSafeMessageBox.disconnect_all_slots(); fRequestShutdown = false; } #include // A mock for uiInterface.ThreadSafeMessageBox, for tests of code that notifies the // user via that signal (e.g. a divergence-triggered shutdown or end-of-service // halt). The gtest harness connects no slot, so without one the signals2 combiner // throws on zero slots; ConnectMockUIInterface connects this mock. class MockUIInterface { public: MOCK_METHOD3(ThreadSafeMessageBox, bool(const std::string& message, const std::string& caption, unsigned int style)); }; // Replace any slots on uiInterface.ThreadSafeMessageBox with one forwarding to `mock`. // `mock` must outlive the connection; pair with DisconnectMockUIInterface, which must // be called before `mock` is destroyed. void ConnectMockUIInterface(MockUIInterface& mock); // Teardown counterpart to ConnectMockUIInterface for tests of code that may request a // shutdown: disconnect all slots from uiInterface.ThreadSafeMessageBox and clear any // shutdown the test requested (StartShutdown sets fRequestShutdown, which has no // production reset). Clearing the flag needs no synchronization: in the gtest process // nothing consumes it (the node main loop and wallet notification thread are not // running), so there is no concurrent observer. void DisconnectMockUIInterface(); bool performOrchardWalletUpdates, bool performConsistencyCheck) { consensus, pindex, pblock, frontiers, performOrchardWalletUpdates, performConsistencyCheck); wallet.IncrementNoteWitnesses(Params().GetConsensus(), &index, &block, frontiers, true, false); wallet.IncrementNoteWitnesses(consensusParams, &fakeIndex, &block, frontiers, true, false); // Simulate receiving a new block and ChainTip signal at the chain tip, exercising // the Orchard consistency check (performConsistencyCheck = true). This block's // hashFinalOrchardRoot was set consistently above, so the check passes. wallet.IncrementNoteWitnesses(consensusParams, &fakeIndex, &block, frontiers, true, true); wallet.IncrementNoteWitnesses(consensusParams, &fakeIndex, &block, frontiers, true, false); wallet.IncrementNoteWitnesses(consensusParams, &fakeIndex, &block, frontiers, true, false); wallet.IncrementNoteWitnesses(params, &index, &block, frontiers, true, false); wallet.IncrementNoteWitnesses(params, &another_index, &another_block, frontiers, true, false); wallet.IncrementNoteWitnesses(params, &another_index, &another_block, frontiers, true, false); wallet.IncrementNoteWitnesses(params, &last_index, &last_block, frontiers, true, false); wallet.IncrementNoteWitnesses(Params().GetConsensus(), &index2, &block2, frontiers2, true, false); wallet.IncrementNoteWitnesses(Params().GetConsensus(), &index2, &block2, frontiers, true, false); wallet.IncrementNoteWitnesses(Params().GetConsensus(), &index2, &block2, frontiers, true, false); wallet.IncrementNoteWitnesses(Params().GetConsensus(), &index2, &block2, frontiers, true, false); wallet.IncrementNoteWitnesses(Params().GetConsensus(), &(indices[i]), &(blocks[i]), riFrontiers, true, false); wallet.IncrementNoteWitnesses(Params().GetConsensus(), &(indices[i]), &(blocks[i]), riPrevFrontiers, true, false); wallet.IncrementNoteWitnesses(consensusParams, &fakeIndex, &block, frontiers, true, false); wallet.IncrementNoteWitnesses(consensusParams, &fakeIndex, &block, frontiers, true, false); bool performOrchardWalletUpdates, bool performConsistencyCheck) frontiers, performOrchardWalletUpdates, performConsistencyCheck); // Connecting a block at the chain tip: run the Orchard note commitment tree // consistency check (performConsistencyCheck = true) to detect a divergence // (#5960) as it occurs. This is cheap on every connected block because the // wallet's anchor is memoized; see IncrementNoteWitnesses. ChainTipAdded(pindex, pblock, added.value(), true, true); bool performOrchardWalletUpdates, bool performConsistencyCheck) // Verify the wallet's Orchard note commitment tree root against the block's // consensus root, to catch a divergence (#5960) as soon as it occurs rather // than only later, fatally, on the disconnect path during a reorg. Computing // the wallet's anchor used to re-fold the commitment tree frontier on every // block, which is why #6052 disabled this check; the frontier root is now // memoized and recomputed only when the tree changes, so a block that appends // no Orchard commitments costs nothing here and the check runs on every block // connected by ChainTip. The caller passes performConsistencyCheck = false only // for a bulk rescan, which rebuilds the tree from the consensus frontier and so // cannot have diverged from it. On divergence, request a clean shutdown and // prompt the operator to `-rescan` (the same recovery as the disconnect path). if (performConsistencyCheck && pindex->hashFinalOrchardRoot != orchardWallet.GetLatestAnchor()) { OrchardNoteCommitmentTreeDiverged(pindex->nHeight); return; } // Connecting a block during a bulk rescan: skip the Orchard note commitment // tree consistency check (performConsistencyCheck = false). The rescan // rebuilds the tree from the consensus frontier, so it cannot have diverged // (#5960), and running the check would reintroduce the per-block cost #6052 // removed; see IncrementNoteWitnesses. ChainTipAdded(pindex, &block, frontiers, performOrchardWalletUpdates, false); bool performOrchardWalletUpdates, // When true, verify the wallet's Orchard note commitment tree root against // the connected block's consensus root (#5960). The tip-connection path // passes true (cheap on every block now that the anchor is memoized); a bulk // rescan passes false, as it cannot diverge from the consensus frontier it // rebuilds from (and the check was too slow there before; #6052). bool performConsistencyCheck bool performOrchardWalletUpdates, bool performConsistencyCheck); // Regression test for #7150. GetSpendInfo resolves the spend against the anchor at // its absolute height, so it must still succeed when the wallet's latest checkpoint // has advanced past that height — e.g. a block connecting between anchor selection // and spend construction. Before the #7150 fix, GetSpendInfo derived the checkpoint // depth from a fixed confirmation count relative to the latest checkpoint, so an // advanced tip made it read the wrong checkpoint and spuriously fail even though the // wallet's tree had not diverged. TEST(OrchardWalletTests, SpendResolvesAnchorByAbsoluteHeight) { auto consensusParams = RegtestActivateNU5(); OrchardWallet wallet; // Receive a note into the wallet. auto sk = RandomOrchardSpendingKey(); wallet.AddSpendingKey(sk); libzcash::diversifier_index_t j(0); auto txRecv = FakeOrchardTx(sk, j); wallet.AddNotesIfInvolvingMe(txRecv); std::vector notes; wallet.GetFilteredNotes( notes, sk.ToFullViewingKey().ToIncomingViewingKey(), true, true); ASSERT_EQ(notes.size(), 1); // Connect the note's block at height 2 and capture the anchor at that height. CBlock block2; block2.vtx.resize(2); block2.vtx[1] = txRecv; ASSERT_TRUE(wallet.CheckpointNoteCommitmentTree(2)); ASSERT_TRUE(wallet.AppendNoteCommitments(2, block2)); uint256 anchorAtHeight2 = wallet.GetLatestAnchor(); // Connect several further blocks, each adding an unrelated Orchard commitment so // the tree root changes and the latest checkpoint moves well past height 2. for (int h = 3; h <= 7; h++) { CBlock block; block.vtx.resize(2); block.vtx[1] = FakeOrchardTx(RandomOrchardSpendingKey(), j); ASSERT_TRUE(wallet.CheckpointNoteCommitmentTree(h)); ASSERT_TRUE(wallet.AppendNoteCommitments(h, block)); } ASSERT_EQ(wallet.GetLastCheckpointHeight().value(), 7); // The tip's anchor now differs from the anchor at height 2, so the spend can only // succeed if GetSpendInfo resolves by absolute height (depth = 7 - 2 = 5) rather // than against the latest checkpoint. ASSERT_NE(wallet.GetLatestAnchor(), anchorAtHeight2); auto spendInfo = wallet.GetSpendInfo(notes, anchorAtHeight2, 2); ASSERT_EQ(spendInfo.size(), 1); EXPECT_EQ(spendInfo[0].second.Value(), 40000); RegtestDeactivateNU5(); } // Checkpoint the tree at height 2 (the height of the block whose commitments // are appended below). GetSpendInfo addresses the wallet's tree by absolute // height (#7150), so it needs a checkpoint to resolve the anchor against. ASSERT_TRUE(wallet.CheckpointNoteCommitmentTree(2)); ASSERT_THROW(wallet.GetSpendInfo(notes, wallet.GetLatestAnchor(), 2), std::logic_error); auto spendInfo = wallet.GetSpendInfo(notes, wallet.GetLatestAnchor(), 2); // The wallet checkpointed this single block at height 0, so the anchor (the // tree root after that block) is at absolute height 0. auto noteToSpend = std::move(wallet.GetOrchardSpendInfo(orchardEntries, orchardTree.root(), 0)[0]); auto noteToSpend2 = std::move(wallet.GetOrchardSpendInfo(orchardEntries, orchardTree.root(), 0)[0]); const uint256& anchor, int anchorHeight) const // The caller pins `anchor` to the consensus Orchard tree root at the absolute // height `anchorHeight`. Derive the wallet checkpoint depth from that absolute // height rather than from a fixed confirmation count, so that a block connecting // (or a short reorg) between anchor selection and spend construction does not // shift which checkpoint we compare against or witness from (#7150). auto lastCheckpointHeight = GetLastCheckpointHeight(); if (!lastCheckpointHeight.has_value() || lastCheckpointHeight.value() < anchorHeight) { // The wallet's latest checkpoint is below the anchor height. This is not a // divergence: the wallet may not have scanned that far yet, the caller may // have passed a height above the chain tip, or the anchor's block may have // been reorged away. // // Known limitation (not fixed here, and probably never in zcashd): the // wallet's Orchard note commitment tree is updated on the asynchronous wallet // notification thread, so if it falls more than `anchorconfirmations` blocks // behind the chain tip —for example, several blocks are connected in quick // succession and an Orchard spend is attempted immediately afterwards— this // fires spuriously even though nothing is wrong. The caller must wait for the // wallet to catch up, or retry, rather than treating it as a permanent error. throw std::runtime_error( "Could not create this Orchard transaction: the wallet has not reached " "the block its anchor refers to. Please try again after giving the wallet " "time to catch up."); } int checkpointDepth = lastCheckpointHeight.value() - anchorHeight; assert(checkpointDepth >= 0); // non-negative by the guard above auto walletAnchor = GetAnchorAtCheckpointDepth((size_t) checkpointDepth); if (!walletAnchor.has_value()) { // The anchor is older than the checkpoints the wallet retains. Again not a // divergence; the spend just cannot be built against an anchor this old. throw std::runtime_error( "Could not create this Orchard transaction: too many blocks have been " "mined since its anchor was chosen, so the anchor is older than the note " "commitment tree checkpoints the wallet retains. Please try again to " "build the transaction against a more recent anchor."); } if (walletAnchor.value() != anchor) { // A checkpoint exists at the anchor height but its root differs from the // consensus root: the wallet's Orchard tree has genuinely diverged (#5960). "The wallet's Orchard note commitment tree is inconsistent with the " "block chain. Restart with -rescan to rebuild it."); (size_t) checkpointDepth); std::optional GetAnchorAtCheckpointDepth(size_t checkpointDepth) const { if (orchard_wallet_commitment_tree_root(inner.get(), checkpointDepth, value.begin())) { const uint256& anchor, int anchorHeight) const; const uint256& anchor, int anchorHeight) const return orchardWallet.GetSpendInfo(orchardNoteMetadata, anchor, anchorHeight); const uint256& anchor, int anchorHeight) const; orchardAnchor.value(), anchorHeight); if (!walletAnchor.has_value() || walletAnchor.value() != anchor) { // Reachable on the ordinary spend path, so throw rather than aborting the // node (as an assertion did previously) on an anchor mismatch (#5960, #7150). throw std::runtime_error( "The wallet's Orchard note commitment tree does not match the anchor " "selected for this spend."); } // Refuse to construct an Orchard spend once a shutdown has been requested. // Shutdown is asynchronous, so the node may still be up, but Orchard proof // construction is slow relative to the shutdown process, so a spend started now // is unlikely to complete. More importantly, when the shutdown was triggered by // a detected Orchard note commitment tree divergence (see // OrchardNoteCommitmentTreeDiverged), the tree we would read here is known to // be inconsistent. cs_wallet —held here and by the divergence detector when it // requests the shutdown— ensures we observe the request, closing the window in // which a spend could read the diverged tree. if (ShutdownRequested()) { throw std::runtime_error( "Cannot create an Orchard spend while the node is shutting down."); } // If a shutdown has already been requested, stop processing further blocks. // This could happen, for example, because a divergence was detected while // processing an earlier block in this connect/disconnect batch — see // OrchardNoteCommitmentTreeDiverged. // StartShutdown only requests an asynchronous shutdown, so without this the // notification thread would keep mutating wallet state. Returning here, rather // than inside Increment/DecrementNoteWitnesses, skips the whole block: it keeps // the note commitment trees and the persisted best block (written by // SetBestChain in ChainTipAdded) in lockstep, and avoids re-reaching the // remaining fatal rewind/witness assertions for the rest of the batch. if (ShutdownRequested()) return; // Handle a detected divergence between the wallet's Orchard note commitment tree // and the consensus note commitment tree. This is a recoverable wallet-internal // inconsistency. The previous behaviour was to abort() the node, which shuts down // uncleanly and —because the diverged tree is durable on disk— recurs on the // next reorg as a restart-proof crash loop (#5960). Instead, log, notify the // operator, and request a clean shutdown; restarting with `-rescan` rebuilds the // wallet's Orchard state from the consensus note commitment tree. // // This runs on the wallet notification thread (ThreadNotifyWallets), so it must // request a clean shutdown via StartShutdown rather than throw: an exception // escaping onto that thread would terminate the process. static void OrchardNoteCommitmentTreeDiverged(int nHeight) { LogPrintf( "*** Orchard note commitment tree diverged from consensus at height %d; the " "wallet's Orchard state is inconsistent and must be rebuilt with -rescan.\n", nHeight); uiInterface.ThreadSafeMessageBox( _("Error: The wallet's Orchard note commitment tree has become inconsistent " "with the block chain. The zcashd node will now shut down; please restart " "with the -rescan option to rebuild the wallet's Orchard note commitment " "tree."), "", CClientUIInterface::MSG_ERROR); StartShutdown(); } if (walletLastCheckpointHeight.has_value() && pindex->pprev->hashFinalOrchardRoot != orchardWallet.GetLatestAnchor()) { // The wallet's Orchard note commitment tree has diverged from consensus. // Recover by requesting a clean shutdown (and `-rescan` on the next start) // rather than aborting the node; see OrchardNoteCommitmentTreeDiverged // and #5960. OrchardNoteCommitmentTreeDiverged(pindex->pprev->nHeight); return; // // Uses `ASSERT_*` internally (which expand to conditional `return;`, returning only from this // helper, not the calling test); so callers must invoke it via `ASSERT_NO_FATAL_FAILURE(...)` // for a failed assumption to abort the test rather than continue with an unset `outTx`. // Uses `ASSERT_*` internally (which expand to conditional `return;`, returning only from this // helper, not the calling test); so callers must invoke it via `ASSERT_NO_FATAL_FAILURE(...)` // for a failed assumption to abort the test rather than continue with an unset `outBytes`. ASSERT_NO_FATAL_FAILURE(BuildOrchardSpend(tx)); ASSERT_NO_FATAL_FAILURE(BuildOrchardSpend(tx)); ASSERT_NO_FATAL_FAILURE(BuildOrchardSpend(tx)); ASSERT_NO_FATAL_FAILURE(BuildOrchardSpend(tx)); ASSERT_NO_FATAL_FAILURE(BuildOrchardSpend(tx)); /// Whether a transaction built for `nHeight` should be proved against the fixed /// (NU6.2-onward) Orchard circuit rather than the historical (insecure) one. /// /// On testnet and regtest, it follows NU6.2 activation (on regtest so that tests can /// reconstruct pre-NU6.2 Orchard history; on testnet because the emergency soft fork /// to disable Orchard will not activate until NU6.2). On mainnet, the fixed Orchard /// circuit is used unconditionally: we know that the emergency soft fork has already /// activated on mainnet, and this makes it easier to reason about the behaviour during /// sync or when eclipsed. bool UseFixedCircuitForProving(int nHeight) const { return NetworkIDString() == CBaseChainParams::MAIN || GetConsensus().NetworkUpgradeActive(nHeight, Consensus::UPGRADE_NU6_2); } // The bundle proves against the circuit version its builder was created with. // Choose the Orchard circuit to prove against (see CChainParams::UseFixedCircuitForProving). bool useFixedCircuitForProving = chainparams.UseFixedCircuitForProving(nHeight); auto builder = orchard::Builder(true, orchardAnchor, useFixedCircuitForProving); uint256 anchor, bool useFixedCircuitForProving) : inner(nullptr, orchard_builder_free) inner.reset(orchard_builder_new(coinbase, anchor.IsNull() ? nullptr : anchor.begin(), useFixedCircuitForProving)); // Choose the Orchard circuit to prove against (see CChainParams::UseFixedCircuitForProving). bool useFixedCircuitForProving = Params().UseFixedCircuitForProving(nHeight); orchardBuilder = orchard::Builder(false, orchardAnchor.value(), useFixedCircuitForProving); // The bundle proves against the circuit version its builder was created with. // `useFixedCircuitForProving` selects the circuit version to prove against (the fixed circuit, else // the historical insecure one). The bundle records it and reuses it in ProveAndSign. Compute // it with `CChainParams::UseFixedCircuitForProving`; the default (true) is correct for non-test callers. Builder(bool coinbase, uint256 anchor, bool useFixedCircuitForProving = true); // Rules that apply to NU6.2 or later: if (nu6point2Active) { // - The Orchard verifying key change is in the `orchard::init_batch_validator` // constructor, in AcceptToMemoryPool and ConnectBlock. // - Orchard proof size enforcement is in the Rust `Transaction` parser. } else { // Rules that apply generally before NU6.2. These were previously // noncontextual checks that became contextual after NU5 activation. // Soft fork: temporarily require transactions to not contain Orchard actions. // // This soft fork was added while NU 6.1 was the active epoch on the Zcash chain, but // we apply it uniformly even if NU 6.1 is not active in case it is ported to other // chains with a different sequence of NUs. if (consensus.TemporaryOrchardDisablingSoftForkActive(nHeight) && orchard_bundle.IsPresent()) { return state.Invalid( error("ContextualCheckTransaction(): transaction has Orchard actions (temporarily disabled)"), REJECT_INVALID, "bad-tx-has-orchard-actions"); } // Orchard bundle contains at least two signatures. The batch is typed to the Orchard // circuit in force at the next block height: NU6.2 changed the circuit and thus the // verifying key. std::optional> orchardAuth = orchard::init_batch_validator( true, chainparams.GetConsensus().NetworkUpgradeActive(nextBlockHeight, Consensus::UPGRADE_NU6_2)); // The batch is typed to the Orchard circuit in force at this block's height: NU6.2 changed // the circuit and thus the verifying key. std::optional(orchard::init_batch_validator( fCacheResults, consensusParams.NetworkUpgradeActive(pindex->nHeight, Consensus::UPGRADE_NU6_2))) : std::nullopt; TEST(TransactionBuilder, OrchardToOrchardNU6point2) { LoadProofParameters(); // Under NU6.2, build a fresh Orchard-spending transaction with a canonically-sized proof. // NU6.2 is the active epoch from height 1, so the transaction's consensus branch id matches // at the heights under test. auto consensusParams = RegtestActivateNU6point2(false, 1); CTransaction tx; BuildOrchardSpend(tx); // A canonical-proof Orchard transaction is accepted under NU6.2. { CValidationState state; EXPECT_TRUE(ContextualCheckTransaction(tx, state, Params(), 2, true)); EXPECT_EQ(state.GetRejectReason(), ""); } RegtestDeactivateNU6point2(); } // CONSENSUS: `zcash_transaction_digests` reparses the serialized transaction through // librustzcash, which enforces consensus encoding rules (e.g. canonical Orchard element // encodings, and from NU6.2 the canonical Orchard proof size, keyed on the transaction's // own v5+ consensus branch id; see `zcash_transaction_digests` in src/rust/src/ // transaction_ffi.rs). This runs on construction of every CTransaction, so the throw // below is how those rules reject a malformed transaction. Do not weaken this throw or // skip the reparse on the assumption it is only computing hashes. // Sets `outBytes` to the v5 serialization of `tx` with its Orchard proof padded by one byte, // so that the proof length is no longer canonical for the number of actions. The returned // bytes are not re-parsed here (parsing is what the callers exercise). // // The v5 transaction format encodes the Orchard proof as a CompactSize length followed by // that many bytes. For the proof sizes in use (a few thousand bytes) the length is encoded // in the 3-byte CompactSize form, and incrementing it by one cannot change that encoding's // width, so the field can be rewritten in place and one byte inserted into the proof. // // Uses an out-parameter rather than a return value so that the ASSERT_* macros (which expand // to `return;`) can be used to abort the test on a malformed assumption. void MakeOrchardProofNonCanonicalBytes(const CTransaction& tx, std::vector& outBytes) { CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss << tx; std::vector bytes(ss.begin(), ss.end()); // Walk the v5 serialization to the Orchard proof's CompactSize length field: // header (nVersion, nVersionGroupId, nConsensusBranchId, nLockTime, nExpiryHeight) size_t pos = 4 + 4 + 4 + 4 + 4; // four empty vectors: transparent in, transparent out, Sapling spends, Sapling outputs. for (int i = 0; i < 4; i++) { ASSERT_EQ(bytes[pos], 0); pos += 1; } // nActionsOrchard, then that many 820-byte action descriptions. These tests build a small // number of actions, so nActionsOrchard is a single-byte CompactSize. size_t nActions = bytes[pos]; ASSERT_GT(nActions, 0u); ASSERT_LT(nActions, 253u); pos += 1 + nActions * 820; // flagsOrchard (1) + valueBalanceOrchard (8) + anchorOrchard (32). pos += 1 + 8 + 32; // proofsOrchard: a 3-byte CompactSize length (0xfd followed by a little-endian u16). ASSERT_EQ(bytes[pos], 0xfd); size_t proofLen = bytes[pos + 1] | (bytes[pos + 2] << 8); size_t newProofLen = proofLen + 1; ASSERT_LT(newProofLen, 0x10000u); // still fits the 3-byte CompactSize form bytes[pos + 1] = newProofLen & 0xff; bytes[pos + 2] = (newProofLen >> 8) & 0xff; // Insert one byte at the start of the proof body. bytes.insert(bytes.begin() + pos + 3, 0); outBytes = bytes; } // Overwrites the nConsensusBranchId field (a little-endian uint32 at byte offset 8 in the v5 // header) in place. void SetConsensusBranchId(std::vector& bytes, uint32_t branchId) { for (int i = 0; i < 4; i++) { bytes[8 + i] = (branchId >> (8 * i)) & 0xff; } } // Deserializes a transaction from raw bytes, returning whether it parsed successfully. zcashd // computes the transaction's hashes by reparsing through librustzcash (see // CTransaction::UpdateHash), which is where the Orchard proof size is enforced for NU6.2. bool TryDeserializeTx(const std::vector& bytes) { CDataStream ss(bytes, SER_NETWORK, PROTOCOL_VERSION); try { CTransaction tx; ss >> tx; return true; } catch (const std::ios_base::failure&) { return false; } } // From NU6.2, an Orchard proof must have the canonical length for its number of actions. zcashd // enforces this through librustzcash when it reparses a transaction to compute its hashes (see // CTransaction::UpdateHash), keyed on the transaction's own consensus branch id. This checks // that a NU6.2 transaction with a padded (non-canonical) proof fails to deserialize, while the // same transaction with a canonical proof deserializes successfully. TEST(TransactionBuilder, OrchardNonCanonicalProofSizeRejectedFromNU6point2) { LoadProofParameters(); auto consensusParams = RegtestActivateNU6point2(false, 1); CTransaction tx; BuildOrchardSpend(tx); // The unmodified (canonical-proof) NU6.2 transaction deserializes. { CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss << tx; std::vector bytes(ss.begin(), ss.end()); EXPECT_TRUE(TryDeserializeTx(bytes)); } // With the proof padded to a non-canonical length, it does not. std::vector tampered; ASSERT_NO_FATAL_FAILURE(MakeOrchardProofNonCanonicalBytes(tx, tampered)); EXPECT_FALSE(TryDeserializeTx(tampered)); RegtestDeactivateNU6point2(); } // The proof-size rule is keyed on the NU6.2 consensus branch id, so it does not apply to // transactions from earlier epochs. A node must still be able to deserialize a pre-NU6.2 // transaction carrying a non-canonical proof, so that it can sync and reindex chain history // (which may contain such a proof mined before the rule took effect). This takes the same // padded-proof bytes and rewrites the consensus branch id to NU6.1, then checks they // deserialize successfully. TEST(TransactionBuilder, OrchardNonCanonicalProofSizeAllowedBeforeNU6point2) { LoadProofParameters(); auto consensusParams = RegtestActivateNU6point2(false, 1); CTransaction tx; BuildOrchardSpend(tx); std::vector tampered; ASSERT_NO_FATAL_FAILURE(MakeOrchardProofNonCanonicalBytes(tx, tampered)); // Sanity check: under the NU6.2 branch id these bytes are rejected. ASSERT_FALSE(TryDeserializeTx(tampered)); // Under the NU6.1 branch id the same non-canonical proof is accepted at deserialization. SetConsensusBranchId(tampered, 0x4dec4df0); EXPECT_TRUE(TryDeserializeTx(tampered)); RegtestDeactivateNU6point2(); } // A coinbase transaction has no Sapling spends or spend-enabled Orchard // actions (rejected above), so its shielded value balance is the negation // of the value of its shielded outputs and cannot be positive. A positive // value balance would be unsatisfiable by the binding signature, hence // always invalid (independently of the NU6 exact-coinbase-balance rule). // Rejecting it here, rather than only via the binding-signature check in // ConnectBlock, prevents a malformed coinbase from reaching the chain // supply consistency check with inconsistent pool accounting // (GHSA-g4x5-crjh-29ff). if (tx.GetValueBalanceSapling() > 0) return state.DoS(100, error("CheckTransaction(): coinbase has positive Sapling value balance"), REJECT_INVALID, "bad-cb-positive-sapling-valuebalance"); if (orchard_bundle.GetValueBalance() > 0) return state.DoS(100, error("CheckTransaction(): coinbase has positive Orchard value balance"), REJECT_INVALID, "bad-cb-positive-orchard-valuebalance"); // Validate the Sapling and Orchard binding signatures here, before the // chain supply consistency check below. The binding signatures are what // enforce that each bundle's value balance is consistent with its // shielded inputs and outputs. If they are not checked first, a block // containing a malformed value balance could reach the supply consistency // check with inconsistent pool accounting, and trigger AbortNode instead // of being cleanly rejected as invalid (GHSA-g4x5-crjh-29ff). // // This must run for both `fJustCheck` and full connection, so it is // placed before the `if (!fJustCheck)` block. The `has_value()` guards // mean that the validators run only when expensive checks are enabled // (`fExpensiveChecks`); they are skipped for block-template checks and // for ancestors of the last checkpoint. if (saplingAuth.has_value() && !saplingAuth.value()->validate()) { return state.DoS(100, error("%s: a Sapling bundle within the block is invalid", __func__), REJECT_INVALID, "bad-sapling-bundle-authorization"); } if (orchardAuth.has_value() && !orchardAuth.value()->validate()) { return state.DoS(100, error("%s: an Orchard bundle within the block is invalid", __func__), REJECT_INVALID, "bad-orchard-bundle-authorization"); } // (The Sapling and Orchard bundle authorizations are validated earlier, // before the chain supply consistency check; see GHSA-g4x5-crjh-29ff.) // Unit test for GHSA-78pp-mc9g-g4mw: a block whose aggregate per-pool value // delta is out of range must be rejected through `state.DoS(100, ...)` so that // the sending peer is banned, rather than via a bare `error()` that leaves the // state MODE_VALID. This drives ReceivedBlockTransactions on a fake index and // asserts the DoS score and reject reason directly. The black-box regression // test in `p2p_ban_pool_value_out_of_range.py` exercises the same path over // P2P but can only observe the resulting disconnection. TEST(Validation, BanOnPoolValueOutOfRange) { SelectParams(CBaseChainParams::REGTEST); const auto chainParams = Params(); const auto sk = libzcash::SproutSpendingKey::random(); // Parent block + index, just so the child is not treated as genesis. CBlock block1; block1.vtx.push_back(GetValidSproutReceive(sk, 5, true)); block1.hashMerkleRoot = BlockMerkleRoot(block1); CBlockIndex fakeIndex1 {block1}; // Child block whose aggregate Sprout pool delta is out of range. // GetValidSproutReceiveTransaction sets `vpub_old = 2 * value`, so // `value = MAX_MONEY / 2` gives `vpub_old = MAX_MONEY` per transaction. // Each is in range individually, but ComputePoolDeltas sums them to // `2 * MAX_MONEY`, overflowing MoneyDeltaRange. CBlock block2; block2.hashPrevBlock = block1.GetHash(); block2.vtx.push_back(GetValidSproutReceive(sk, MAX_MONEY / 2, true)); block2.vtx.push_back(GetValidSproutReceive(sk, MAX_MONEY / 2, true)); block2.hashMerkleRoot = BlockMerkleRoot(block2); CBlockIndex fakeIndex2 {block2}; fakeIndex2.pprev = &fakeIndex1; ASSERT_TRUE(fakeIndex1.RaiseValidity(BLOCK_VALID_TREE)); ASSERT_TRUE(fakeIndex2.RaiseValidity(BLOCK_VALID_TREE)); CDiskBlockPos pos2; CValidationState state; { // Taking cs_main is required even when working on a fake index. LOCK(cs_main); // The overflow is detected in ComputePoolDeltas, so SetChainPoolValues // fails, and ReceivedBlockTransactions routes that failure through DoS. EXPECT_FALSE(SetChainPoolValues(chainParams, block2, &fakeIndex2)); EXPECT_FALSE(ReceivedBlockTransactions(block2, state, chainParams, &fakeIndex2, pos2)); } int nDoS = 0; EXPECT_TRUE(state.IsInvalid(nDoS)); EXPECT_EQ(100, nDoS); EXPECT_EQ("bad-blk-pool-value-out-of-range", state.GetRejectReason()); // The block must not have been recorded as having data; leaving it // header-only is what, absent the ban, enables the replay re-write. EXPECT_FALSE(fakeIndex2.IsValid(BLOCK_PARTIALLY_VALID_TRANSACTIONS)); EXPECT_FALSE(fakeIndex2.nStatus & BLOCK_HAVE_DATA); // No fake CBlockIndex should be referenced by mapBlocksUnlinked. EnsureUnreferencedAsKeyOfMapBlocksUnlinked(&fakeIndex1); EnsureUnreferencedAsKeyOfMapBlocksUnlinked(&fakeIndex2); } // monetary range. On failure `pindexNew` is left in its prior // (header-only) state and the sending peer is banned (see below). // The aggregate pool-value delta is outside the valid monetary range. // This is a deterministic property of the block (ComputePoolDeltas reads // only `block`, `chainparams`, and `nHeight`), so every honest node // rejects the same block and the sending peer can safely be banned. // The DoS score is what bounds the otherwise-unbounded re-write replay // (GHSA-78pp-mc9g-g4mw). return state.DoS(100, error("ReceivedBlockTransactions(): SetChainPoolValues failed"), REJECT_INVALID, "bad-blk-pool-value-out-of-range"); error("ReceivedBlockTransactions(): AccumulateChainPoolValues failed at height %d", pindex->nHeight); // A cumulative pool value is out of range: a deterministic // consensus failure. `state` belongs to `pindexNew`, so only // its own failure can be recorded through it. A descendant // (linked in from `mapBlocksUnlinked`, possibly from another // peer) is left for `ConnectBlock` to reject, to avoid // mis-attributing the ban. if (pindex == pindexNew) { return state.DoS(100, false, REJECT_INVALID, "bad-blk-pool-value-out-of-range"); } return false; LoadProofParameters(); int orchardDisabledHeight = 5; auto builder = TransactionBuilder(Params(), 1, orchardAnchor, SaplingMerkleTree::empty_root(), &keystore); // The soft fork activates at exactly orchardDisabledHeight (nHeight >= height); one // block earlier the same transaction is still accepted. { CValidationState state; EXPECT_TRUE(ContextualCheckTransaction(tx, state, Params(), orchardDisabledHeight - 1, true)); } // Rejected at the activation height, in both block (isMined = true) and mempool // (isMined = false) validation. for (bool isMined : {true, false}) { CValidationState state; EXPECT_FALSE(ContextualCheckTransaction(tx, state, Params(), orchardDisabledHeight, isMined)); EXPECT_EQ(state.GetRejectReason(), "bad-tx-has-orchard-actions"); } // Revert to default RegtestDeactivateNU6point1(); } // Negative control: a transaction with no Orchard actions is unaffected by the soft fork. TEST(TransactionBuilder, AcceptsNonOrchardWhenOrchardDisabled) { int orchardDisabledHeight = 1; auto consensusParams = RegtestActivateNU6point1( false, Consensus::NetworkUpgrade::ALWAYS_ACTIVE, orchardDisabledHeight); CBasicKeyStore keystore; CKey tsk = AddTestCKeyToKeyStore(keystore); auto scriptPubKey = GetScriptForDestination(tsk.GetPubKey().GetID()); CTxDestination taddr = tsk.GetPubKey().GetID(); // Transparent-to-transparent: 0.00005 t-ZEC in, 0.00004 t-ZEC out, default fee. auto builder = TransactionBuilder(Params(), orchardDisabledHeight, std::nullopt, SaplingMerkleTree::empty_root(), &keystore); builder.AddTransparentInput(COutPoint(uint256S("1234"), 0), scriptPubKey, 5000); builder.AddTransparentOutput(taddr, 4000); auto maybeTx = builder.Build(); ASSERT_TRUE(maybeTx.IsTx()); auto tx = maybeTx.GetTxOrThrow(); ASSERT_FALSE(tx.GetOrchardBundle().IsPresent()); EXPECT_TRUE(ContextualCheckTransaction(tx, state, Params(), 2, true)); // Builds a fresh Orchard-spending transaction under the currently-active consensus // parameters, so that its consensus branch id matches the active epoch (allowing the // same flow to be exercised under both NU5 and NU6.1). void BuildOrchardSpend(CTransaction& outTx) { ASSERT_THROW(wallet.GetSpendInfo(notes, 1, wallet.GetLatestAnchor()), std::logic_error); ASSERT_EQ(spendInfo[0].second.Value(), 40000); auto builder = TransactionBuilder(Params(), 2, tree.root(), SaplingMerkleTree::empty_root()); ASSERT_TRUE(builder.AddOrchardSpend(sk, std::move(spendInfo[0].second))); ASSERT_TRUE(maybeTx.IsTx()); ASSERT_EQ(tx.vin.size(), 0); ASSERT_EQ(tx.vout.size(), 0); ASSERT_EQ(tx.vJoinSplit.size(), 0); ASSERT_EQ(tx.GetSaplingSpendsCount(), 0); ASSERT_EQ(tx.GetSaplingOutputsCount(), 0); ASSERT_TRUE(tx.GetOrchardBundle().IsPresent()); ASSERT_EQ(tx.GetOrchardBundle().GetValueBalance(), 1000); outTx = tx; } // These tests are here instead of test_transaction_builder.cpp because they depend // on OrchardWallet, which only exists if the wallet is compiled in. TEST(TransactionBuilder, OrchardToOrchardNU5) { LoadProofParameters(); // Under NU5, the Orchard-spending transaction is accepted. auto consensusParams = RegtestActivateNU5(); CTransaction tx; BuildOrchardSpend(tx); { CValidationState state; EXPECT_TRUE(ContextualCheckTransaction(tx, state, Params(), 1, true)); EXPECT_EQ(state.GetRejectReason(), ""); } TEST(TransactionBuilder, OrchardToOrchardNU6point1) { LoadProofParameters(); // Under NU6.1, with the temporary Orchard-disabling soft fork activating at height 3, // build a fresh (NU6.1) Orchard-spending transaction. auto consensusParams = RegtestActivateNU6point1(false, 1, 2); CTransaction tx; BuildOrchardSpend(tx); // Before the soft-fork height the spend is still accepted... { CValidationState state; EXPECT_TRUE(ContextualCheckTransaction(tx, state, Params(), 1, true)); EXPECT_EQ(state.GetRejectReason(), ""); } // ... and at the soft-fork height it is rejected: the soft fork disables Orchard // spends as well as outputs. { CValidationState state; EXPECT_FALSE(ContextualCheckTransaction(tx, state, Params(), 2, true)); EXPECT_EQ(state.GetRejectReason(), "bad-tx-has-orchard-actions"); } RegtestDeactivateNU6point1(); } /** * Classifies a validation failure by how it relates to the block body, which * determines whether the failure may be cached as permanent header invalidity. * Passed to `CValidationState::DoS`; see `CValidationState::corruptionPossible` * and the `hash*Checked` commitment-tracking flags for the underlying mechanism. */ enum class BodyCorruption { /** * The failure is body-replaceable: a different body matching the same * header could exist and pass, so the failure must NOT be cached as * permanent header invalidity. Use when the triggering field is bound only * by a header-to-body commitment that has not yet been verified at the * point of rejection (e.g. an authdata-bound field, before * `CheckBlockBodyAuthCommitment` has run). */ Possible, /** * Defer to the commitment-tracking flags: the failure is body-replaceable * if and only if the body is not yet fully pinned to the header (i.e. if * `!(hashMerkleRootChecked && hashBlockCommitmentsChecked)`). This is the * default for body-derived checks. */ Default, /** * The failure depends only on the header and chain context, never on the * body — proof of work, difficulty, timestamp, version, prev-block. A * different body cannot fix it, so it is never body-replaceable. */ HeaderOnly, }; bool hashMerkleRootChecked; bool hashBlockCommitmentsChecked; CValidationState() : mode(MODE_VALID), nDoS(0), chRejectCode(0), corruptionPossible(false), hashMerkleRootChecked(false), hashBlockCommitmentsChecked(false) {} BodyCorruption bodyCorruption=BodyCorruption::Default, // Classify whether this rejection is body-replaceable (`corruptionPossible`). // `Default` defers to the commitment-tracking flags: a body-derived check // raised before the body is fully pinned to the header by both commitments // is considered body-replaceable. switch (bodyCorruption) { case BodyCorruption::Possible: corruptionPossible = true; break; case BodyCorruption::HeaderOnly: corruptionPossible = false; break; case BodyCorruption::Default: corruptionPossible = !(hashMerkleRootChecked && hashBlockCommitmentsChecked); break; } // Reset both commitment-tracking flags at the start of a block-validation // pass. See the flags' documentation for why this is per-pass and why it // belongs in `AcceptBlock` / `ConnectBlock` rather than `CheckBlock`. virtual void ResetBodyCommitmentChecks() { hashMerkleRootChecked = false; hashBlockCommitmentsChecked = false; } virtual void SetMerkleRootChecked() { hashMerkleRootChecked = true; } virtual void SetBlockCommitmentsChecked() { hashBlockCommitmentsChecked = true; } return DoS(0, ret, _chRejectCode, _strRejectReason, BodyCorruption::Default, _strDebugMessage); BodyCorruption bodyCorruption, EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, "version-too-low", BodyCorruption::HeaderOnly, "")).Times(1); EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, "bad-txns-version-too-low", BodyCorruption::Default, "")).Times(1); EXPECT_FALSE(CheckBlock(block, state, Params(), verifier, false, false, true)); } // The following five tests pin the `BodyCorruption` argument that `CheckBlock`'s // own body-derived rejections pass to `state.DoS`. The classification mechanism // itself is covered by `Validation.BodyCorruptionClassification`; these tests // guard the *wiring* — that each rejection passes the intended value. // // For the three `Possible` rejections the explicit argument is defence in depth: // the commitment-tracking flags on `CValidationState` and the active-tip // auth-commitment pre-check in `AcceptBlock` already classify these rejections // correctly without it. These tests verify that the defence-in-depth argument is // actually present, so it is not dropped inadvertently; whether dropping it would // in fact re-open the GHSA-rpcw-q5mr-gq35 / GHSA-qvwc-hc2r-82qv / // GHSA-wmwc-773c-qcvv / GHSA-382w-958v-m5jr block-body-poisoning class would // depend on the refactor. // // The Merkle-derived rejections (`bad-txns-duplicate`, `bad-txnmrklroot`) are // `Possible` because they fire before `hashMerkleRoot` is pinned; the block-size // rejection (`bad-blk-length`) is `Possible` because the serialized size includes // v5 authdata. The two coinbase-shape rejections (`bad-cb-missing`, // `bad-cb-multiple`) are `Default`: coinbase-ness is determined by `vin[0].prevout`, // which is pinned by `hashMerkleRoot`. namespace { // A minimal valid coinbase transaction (one null-prevout input, one output). CTransaction MakeCoinbaseTx() { CMutableTransaction mtx; mtx.fOverwintered = false; mtx.nVersion = 1; mtx.vin.resize(1); mtx.vin[0].prevout.SetNull(); mtx.vin[0].scriptSig = CScript() << 1 << OP_0; mtx.vout.resize(1); mtx.vout[0].scriptPubKey = CScript() << OP_TRUE; mtx.vout[0].nValue = 0; return CTransaction(mtx); } // A minimal non-coinbase transaction (one non-null-prevout input). CTransaction MakeNonCoinbaseTx() { CMutableTransaction mtx; mtx.fOverwintered = false; mtx.nVersion = 1; mtx.vin.resize(1); mtx.vin[0].prevout = COutPoint(uint256S("01"), 0); mtx.vout.resize(1); mtx.vout[0].scriptPubKey = CScript() << OP_TRUE; mtx.vout[0].nValue = 0; return CTransaction(mtx); } } // namespace // An empty block hits the `block.vtx.empty()` arm of the size-limit check, the // cheapest way to reach `bad-blk-length` (which is `BodyCorruption::Possible`). TEST(CheckBlock, SizeLimitsBadBlockLength) { SelectParams(CBaseChainParams::MAIN); auto verifier = ProofVerifier::Strict(); CBlock block; // no transactions MockCValidationState state; EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, "bad-blk-length", BodyCorruption::Possible, "")).Times(1); // fCheckMerkleRoot=false so we reach the size check directly. EXPECT_FALSE(CheckBlock(block, state, Params(), verifier, false, false, true)); } // A Merkle root that does not match the (un-malleated) transaction set is // rejected as `bad-txnmrklroot` (`BodyCorruption::Possible`). TEST(CheckBlock, MerkleRootMismatch) { SelectParams(CBaseChainParams::MAIN); auto verifier = ProofVerifier::Strict(); CBlock block; block.vtx.push_back(MakeCoinbaseTx()); // Leave hashMerkleRoot at its null default; the real root is nonzero. MockCValidationState state; EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, "bad-txnmrklroot", BodyCorruption::Possible, "")).Times(1); EXPECT_FALSE(CheckBlock(block, state, Params(), verifier, false, true, true)); } // Two identical transactions make the Merkle tree malleable (CVE-2012-2459): // the mutation flag is set, yielding `bad-txns-duplicate` (`BodyCorruption::Possible`). TEST(CheckBlock, DuplicateTransactions) { SelectParams(CBaseChainParams::MAIN); auto verifier = ProofVerifier::Strict(); CBlock block; auto cb = MakeCoinbaseTx(); block.vtx.push_back(cb); block.vtx.push_back(cb); // adjacent equal leaves -> mutation MockCValidationState state; EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, "bad-txns-duplicate", BodyCorruption::Possible, "")).Times(1); EXPECT_FALSE(CheckBlock(block, state, Params(), verifier, false, true, true)); } // A block whose first transaction is not a coinbase is rejected as // `bad-cb-missing` (`BodyCorruption::Default`). TEST(CheckBlock, FirstTxNotCoinbase) { SelectParams(CBaseChainParams::MAIN); auto verifier = ProofVerifier::Strict(); CBlock block; block.vtx.push_back(MakeNonCoinbaseTx()); MockCValidationState state; EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, "bad-cb-missing", BodyCorruption::Default, "")).Times(1); EXPECT_FALSE(CheckBlock(block, state, Params(), verifier, false, false, true)); } // A block with more than one coinbase is rejected as `bad-cb-multiple` // (`BodyCorruption::Default`). TEST(CheckBlock, MultipleCoinbase) { SelectParams(CBaseChainParams::MAIN); auto verifier = ProofVerifier::Strict(); CBlock block; block.vtx.push_back(MakeCoinbaseTx()); block.vtx.push_back(MakeCoinbaseTx()); MockCValidationState state; EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, "bad-cb-multiple", BodyCorruption::Default, "")).Times(1); // fCheckMerkleRoot=false so identical-leaf mutation does not pre-empt the // coinbase-shape check. EXPECT_CALL(state, DoS(level, false, REJECT_INVALID, reason, BodyCorruption::Default, "")).Times(1); EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, "bad-cb-height", BodyCorruption::Default, "")).Times(1); EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, "bad-cb-height", BodyCorruption::Default, "")).Times(1); BodyCorruption bodyCorruption, EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, "bad-txns-version-too-low", BodyCorruption::Default, "")).Times(1); EXPECT_CALL(state, DoS(10, false, REJECT_INVALID, "bad-txns-no-source-of-funds", BodyCorruption::Default, "")).Times(1); EXPECT_CALL(state, DoS(10, false, REJECT_INVALID, "bad-txns-no-sink-of-funds", BodyCorruption::Default, "")).Times(1); EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, "bad-txns-oversize", BodyCorruption::Default, "")).Times(1); EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, "bad-txns-oversize", BodyCorruption::Default, "")).Times(1); EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, "bad-txns-vout-negative", BodyCorruption::Default, "")).Times(1); EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, "bad-txns-vout-toolarge", BodyCorruption::Default, "")).Times(1); EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, "bad-txns-txouttotal-toolarge", BodyCorruption::Default, "")).Times(1); EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, "bad-txns-valuebalance-nonzero", BodyCorruption::Default, "")).Times(1); EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, "bad-txns-txouttotal-toolarge", BodyCorruption::Default, "")).Times(1); EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, "bad-txns-txouttotal-toolarge", BodyCorruption::Default, "")).Times(1); EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, "bad-txns-txintotal-toolarge", BodyCorruption::Default, "")).Times(1); EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, "bad-txns-vpub_old-negative", BodyCorruption::Default, "")).Times(1); EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, "bad-txns-vpub_new-negative", BodyCorruption::Default, "")).Times(1); EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, "bad-txns-vpub_old-toolarge", BodyCorruption::Default, "")).Times(1); EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, "bad-txns-vpub_new-toolarge", BodyCorruption::Default, "")).Times(1); EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, "bad-txns-vpubs-both-nonzero", BodyCorruption::Default, "")).Times(1); EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, "bad-txns-inputs-duplicate", BodyCorruption::Default, "")).Times(1); EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, "bad-joinsplits-nullifiers-duplicate", BodyCorruption::Default, "")).Times(1); EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, "bad-joinsplits-nullifiers-duplicate", BodyCorruption::Default, "")).Times(1); EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, "bad-cb-has-joinsplits", BodyCorruption::Default, "")).Times(1); EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, "bad-cb-length", BodyCorruption::Default, "")).Times(1); EXPECT_CALL(state, DoS(10, false, REJECT_INVALID, "bad-txns-prevout-null", BodyCorruption::Default, "")).Times(1); EXPECT_CALL(state, DoS(0, false, REJECT_INVALID, "bad-txns-invalid-joinsplit-signature", BodyCorruption::Default, "")).Times(1); EXPECT_CALL(state, DoS(10, false, REJECT_INVALID, "bad-txns-invalid-joinsplit-signature", BodyCorruption::Default, "")).Times(1); EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, "bad-txns-invalid-joinsplit-signature", BodyCorruption::Default, "")).Times(1); EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, "bad-txns-invalid-joinsplit-signature", BodyCorruption::Default, "")).Times(1); BodyCorruption::Default, "")).Times(1); "bad-txns-invalid-joinsplit-signature", BodyCorruption::Default, "")).Times(1); EXPECT_CALL(state, DoS(0, false, REJECT_INVALID, "bad-txns-invalid-joinsplit-signature", BodyCorruption::Default, "")).Times(1); EXPECT_CALL(state, DoS(10, false, REJECT_INVALID, "bad-txns-invalid-joinsplit-signature", BodyCorruption::Default, "")).Times(1); EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, "bad-txns-invalid-joinsplit-signature", BodyCorruption::Default, "")).Times(1); EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, "bad-txns-invalid-joinsplit-signature", BodyCorruption::Default, "")).Times(1); EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, "bad-tx-expiry-height-too-high", BodyCorruption::Default, "")).Times(1); EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, "bad-tx-expiry-height-too-high", BodyCorruption::Default, "")).Times(1); EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, "bad-txns-version-too-low", BodyCorruption::Default, "")).Times(1); EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, "bad-txns-txintotal-toolarge", BodyCorruption::Default, "")).Times(1); EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, "bad-tx-overwinter-version-too-low", BodyCorruption::Default, "")).Times(1); EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, "bad-tx-overwinter-version-too-high", BodyCorruption::Default, "")).Times(1); EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, "bad-tx-version-group-id", BodyCorruption::Default, "")).Times(1); EXPECT_CALL(state, DoS(0, false, REJECT_INVALID, "tx-overwinter-not-active", BodyCorruption::Default, "")).Times(1); EXPECT_CALL(state, DoS(10, false, REJECT_INVALID, "tx-overwinter-not-active", BodyCorruption::Default, "")).Times(1); EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, "tx-overwinter-not-active", BodyCorruption::Default, "")).Times(1); EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, "tx-overwinter-not-active", BodyCorruption::Default, "")).Times(1); EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, "tx-overwintered-flag-not-set", BodyCorruption::Default, "")).Times(1); EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, "bad-cb-has-output-description", BodyCorruption::Default, "")).Times(1); EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, "bad-cb-output-desc-invalid-ct", BodyCorruption::Default, "")).Times(1); EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, "bad-cb-output-desc-invalid-ct", BodyCorruption::Default, "")).Times(1); EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, "bad-cb-output-desc-invalid-ct", BodyCorruption::Default, "")).Times(1); EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, "bad-cb-output-desc-invalid-ct", BodyCorruption::Default, "")).Times(1); EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, "bad-txns-valuebalance-nonzero", BodyCorruption::Default, "")).Times(1); EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, "bad-txns-vpub_old-nonzero", BodyCorruption::Default, "")).Times(1); EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, "bad-sapling-tx-version-group-id", BodyCorruption::Default, "")).Times(1); EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, "bad-cb-action-invalid-ciphertext", BodyCorruption::Default, "")).Times(1); EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, "bad-cb-action-invalid-ciphertext", BodyCorruption::Default, "")).Times(1); EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, "bad-cb-action-invalid-ciphertext", BodyCorruption::Default, "")).Times(1); EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, "bad-cb-action-invalid-ciphertext", BodyCorruption::Default, "")).Times(1); // EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, "bad-txns-valuebalance-toolarge", BodyCorruption::Default, "")).Times(1); // EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, "bad-txns-valuebalance-toolarge", BodyCorruption::Default, "")).Times(1); BodyCorruption bodyCorruption, // Directly exercises the `CValidationState::DoS` classification logic that the // `MockCValidationState` in this and the other gtest files necessarily bypasses: // the mock overrides `DoS`, so the `BodyCorruption` switch and the // `Default` -> `!(hashMerkleRootChecked && hashBlockCommitmentsChecked)` rule that // underpin the GHSA-rpcw-q5mr-gq35 / GHSA-qvwc-hc2r-82qv / GHSA-wmwc-773c-qcvv / // GHSA-382w-958v-m5jr body-poisoning fixes are never run there. TEST(Validation, BodyCorruptionClassification) { // `Possible`: always corruption-possible, regardless of commitment flags. { CValidationState s; s.DoS(100, false, REJECT_INVALID, "x", BodyCorruption::Possible); EXPECT_TRUE(s.CorruptionPossible()); } { // Even when the body is fully pinned, `Possible` forces corruption-possible. CValidationState s; s.SetMerkleRootChecked(); s.SetBlockCommitmentsChecked(); s.DoS(100, false, REJECT_INVALID, "x", BodyCorruption::Possible); EXPECT_TRUE(s.CorruptionPossible()); } // `HeaderOnly`: never corruption-possible, regardless of commitment flags. { CValidationState s; s.DoS(100, false, REJECT_INVALID, "x", BodyCorruption::HeaderOnly); EXPECT_FALSE(s.CorruptionPossible()); } { CValidationState s; s.SetMerkleRootChecked(); s.SetBlockCommitmentsChecked(); s.DoS(100, false, REJECT_INVALID, "x", BodyCorruption::HeaderOnly); EXPECT_FALSE(s.CorruptionPossible()); } // `Default`: corruption-possible iff NOT (merkle && commitments) both checked. { CValidationState s; // (merkle=F, commitments=F) s.DoS(100, false, REJECT_INVALID, "x", BodyCorruption::Default); EXPECT_TRUE(s.CorruptionPossible()); } { CValidationState s; // (merkle=T, commitments=F) s.SetMerkleRootChecked(); s.DoS(100, false, REJECT_INVALID, "x", BodyCorruption::Default); EXPECT_TRUE(s.CorruptionPossible()); } { CValidationState s; // (merkle=F, commitments=T) s.SetBlockCommitmentsChecked(); s.DoS(100, false, REJECT_INVALID, "x", BodyCorruption::Default); EXPECT_TRUE(s.CorruptionPossible()); } { CValidationState s; // (merkle=T, commitments=T) -> fully pinned s.SetMerkleRootChecked(); s.SetBlockCommitmentsChecked(); s.DoS(100, false, REJECT_INVALID, "x", BodyCorruption::Default); EXPECT_FALSE(s.CorruptionPossible()); } // `ResetBodyCommitmentChecks` clears both flags, so a subsequent `Default` // rejection is classified corruption-possible again. (This reset runs at the // start of each block-validation pass because a single `CValidationState` is // reused across successive block connections.) { CValidationState s; s.SetMerkleRootChecked(); s.SetBlockCommitmentsChecked(); s.ResetBodyCommitmentChecks(); s.DoS(100, false, REJECT_INVALID, "x", BodyCorruption::Default); EXPECT_TRUE(s.CorruptionPossible()); } // `Invalid()` defaults to `Default` classification. { CValidationState s; s.Invalid(false, REJECT_INVALID, "x"); EXPECT_TRUE(s.CorruptionPossible()); } } BodyCorruption::Default, "")).Times(1); BodyCorruption::Default, "")).Times(1); BodyCorruption::Default, "")).Times(1); BodyCorruption::Default, "")).Times(1); return state.DoS(0, false, REJECT_NONSTANDARD, "bad-txns-nonstandard-inputs", BodyCorruption::Possible); return state.DoS(0, false, REJECT_NONSTANDARD, "bad-txns-too-many-sigops", BodyCorruption::Possible, return state.DoS(0, false, REJECT_NONSTANDARD, "too-long-mempool-chain", BodyCorruption::Default, errString); return state.DoS(100, false, REJECT_INVALID, "bad-txns-in-belowout", BodyCorruption::Default, // The block body has been received but has NOT yet been verified against the // header's commitments. This reset is per-block: a single `CValidationState` // is reused across successive connections in `ActivateBestChainStep`, so the // flags must start false here regardless of any prior block's checks. // There are two flags set by `CheckBlock` and `CheckBlockBodyAuthCommitment` // (called below); until both are set, body-derived rejections are classified // `corruptionPossible`. This is the sidechain counterpart to `AcceptBlock`'s // active-tip pre-check. See `consensus/validation.h`. state.ResetBodyCommitmentChecks(); // All checks here are header-only (PoW, solution, version): they depend // solely on the header bytes, never on the block body, so failures are not // body-replaceable and pass `BodyCorruption::HeaderOnly`. REJECT_INVALID, "version-too-low", BodyCorruption::HeaderOnly); REJECT_INVALID, "invalid-solution", BodyCorruption::HeaderOnly); REJECT_INVALID, "high-hash", BodyCorruption::HeaderOnly); // Check the Merkle root. On success this pins the body's txids to the // header's `hashMerkleRoot` (the `txid_digest` side of the body // commitment); record that so `DoS` stops treating txid-pinned // rejections below as body-replaceable. The two failure cases here ARE // body-replaceable (a different body could reconstruct the committed // Merkle root), and are flagged `BodyCorruption::Possible` since // `hashMerkleRootChecked` is not yet set when they fire. REJECT_INVALID, "bad-txns-duplicate", BodyCorruption::Possible); REJECT_INVALID, "bad-txnmrklroot", BodyCorruption::Possible); state.SetMerkleRootChecked(); // because we receive the wrong transactions for it. For NU5+ blocks the // auth-data side of the body is not pinned until // `CheckBlockBodyAuthCommitment` has run; until then the commitment-tracking // flags in `state` keep body-derived rejections classified as // corruption-possible via `BodyCorruption::Default`. // // Two rejections below carry an explicit `BodyCorruption::Possible` because // they depend on fields that are authdata-bound rather than txid-bound, so // they remain body-mutable even after `hashMerkleRoot` has been pinned by // `SetMerkleRootChecked` above: // - `bad-blk-length`: the serialized block size includes v5 `scriptSig` // bytes, which are in `auth_digest`, not `txid_digest`. // - `bad-blk-sigops`: the sigop count walks `scriptSig`, same reason. // // The explicit `Possible` is defence-in-depth, not load-bearing: on both // paths `BodyCorruption::Default` already yields the correct classification. // On the sidechain path `hashBlockCommitmentsChecked` is still unset, so // `Default` resolves to corruption-possible. On the active-tip path a body // that reaches these checks has already passed `CheckBlockBodyAuthCommitment` // (which set `hashBlockCommitmentsChecked`) and is therefore fully pinned to // the header, so a genuine failure here is correctly *not* corruption- // possible. We keep the explicit `Possible` as defence in depth against a // commitment-flag logic error or a future reordering of these checks // relative to the auth-commitment pre-check (cf. the matching rationale at // the sidechain pre-check below). REJECT_INVALID, "bad-blk-length", BodyCorruption::Possible); // First transaction must be coinbase, the rest must not be. Coinbase-ness // is determined by `vin[0].prevout`, which is pinned by `hashMerkleRoot`, // so `BodyCorruption::Default` correctly classifies these post-Merkle-check. REJECT_INVALID, "bad-blk-sigops", BodyCorruption::Possible); // All checks here are header-only (difficulty, timestamp, checkpoint // position, version): they depend on the header and chain context, never // on the block body, so failures are not body-replaceable and pass // `BodyCorruption::HeaderOnly`. REJECT_INVALID, "bad-diffbits", BodyCorruption::HeaderOnly); return state.DoS(0, error("%s: block at height %d, timestamp %d is not later than median-time-past %d", __func__, nHeight, block.GetBlockTime(), medianTimePast), REJECT_INVALID, "time-too-old", BodyCorruption::HeaderOnly); return state.DoS(0, error("%s: block at height %d, timestamp %d is too far ahead of median-time-past, limit is %d", __func__, nHeight, block.GetBlockTime(), medianTimePast + MAX_FUTURE_BLOCK_TIME_MTP), REJECT_INVALID, "time-too-far-ahead-of-mtp", BodyCorruption::HeaderOnly); return state.DoS(0, error("%s: block at height %d, timestamp %d is too far ahead of local time, limit is %d", __func__, nHeight, block.GetBlockTime(), nTimeLimit), REJECT_INVALID, "time-too-new", BodyCorruption::HeaderOnly); return state.DoS(100, error("%s: forked chain older than last checkpoint (height %d)", __func__, nHeight), 0, "", BodyCorruption::HeaderOnly); return state.DoS(0, error("%s : rejected nVersion<4 block", __func__), REJECT_OBSOLETE, "bad-version", BodyCorruption::HeaderOnly); return state.DoS(10, error("%s: prev block not found", __func__), 0, "bad-prevblk", BodyCorruption::HeaderOnly); return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk", BodyCorruption::HeaderOnly); // The body's hashAuthDataRoot doesn't match what the header committed to. // We pass `BodyCorruption::Possible` for defence in depth (the auth-commitment // flag below is not set on this failure path, so the body is not fully pinned). REJECT_INVALID, "bad-block-commitments-hash", BodyCorruption::Possible); // The auth-data side of the body is now verified against the header's // `hashBlockCommitments` (or, pre-NU5, there is no such commitment and // this is vacuously satisfied). Record it. Once `hashMerkleRootChecked` // is also set (by `CheckBlock`), the body is fully pinned to the header // and subsequent `state.DoS` rejections are classified as // non-corruption-possible by default. state.SetBlockCommitmentsChecked(); // The block body has been received but has NOT yet been verified against the // header's commitments. This reset is per-block: a single `CValidationState` // is reused across successive connections in `ActivateBestChainStep`, so the // flags must start false here regardless of any prior block's checks. See // `consensus/validation.h` for the structural argument. state.ResetBodyCommitmentChecks(); // body-mutable rejections in CheckBlock therefore continue to pass // `BodyCorruption::Possible` on each rejection that depends on a // field bound by `hashAuthDataRoot`. This provides defence in depth // in case of any problem with the `hashMerkleRootChecked` / // `hashBlockCommitmentChecks` logic used by `BodyCorruption::Default`. // The body hasn't been verified against the header's commitments yet. // Reset the commitment-tracking flags here for the same reason as in // `AcceptBlock` / `ConnectBlock`. For the miner-constructed-block case the // resulting `corruptionPossible` classification doesn't affect behaviour // (the temporary state never reaches `BLOCK_FAILED_VALID` propagation), // but keeping the flags consistent helps debugging and lets us treat // body-mutable rejection codes uniformly without per-call-site exceptions. state.ResetBodyCommitmentChecks(); // Body-vs-header commitment pre-check for active-tip extensions. // This runs BEFORE CheckBlock / ContextualCheckBlock, so that any // body-mutable rejection downstream (one whose triggering field is // bound by `hashAuthDataRoot` rather than `hashMerkleRoot` — e.g. // per-block sigop count, transparent script verification, Sapling / // Orchard proof and signature verification) cannot fire on a body // whose `hashAuthDataRoot` does not match what the header committed to. // // This closes the GHSA-rpcw-q5mr-gq35 / GHSA-qvwc-hc2r-82qv / // GHSA-382w-958v-m5jr class of NU5+ block-body poisoning structurally: // the body is verified against the header's commitments before any // body-mutable consensus check has the chance to mark the shared // header `BLOCK_FAILED_VALID` based on a mutated body. The check also // runs before the body is persisted to disk and `BLOCK_HAVE_DATA` is // set on the index entry. // // For sidechain blocks, the check has to wait until ConnectBlock // (reconstructing the chain history MMR at an arbitrary `pprev` is // infeasible); the body-replaceable failure path in ConnectTip / // InvalidBlockFound then cleans up persisted body data so that a // subsequent matching body can still be accepted. Sidechain // body-mutable rejections in CheckBlock therefore continue to need // `corruptionIn=true` set on each rejection that depends on a field // bound by `hashAuthDataRoot`, to avoid the same header-poisoning // failure mode in the sidechain case. bool fCheckTransactions = ShouldCheckTransactions(chainparams, pindex); if ((!CheckBlock(block, state, chainparams, verifier, true, true, fCheckTransactions)) || !ContextualCheckBlock(block, state, chainparams, pindex->pprev, fCheckTransactions)) { if (state.IsInvalid() && !state.CorruptionPossible()) { pindex->nStatus |= BLOCK_FAILED_VALID; setDirtyBlockIndex.insert(pindex); } return false; } try { DecodeHexTx(txDecodeTmp, strHexTx); } catch (const std::exception& e) { throw std::runtime_error(std::string("invalid transaction encoding: ") + e.what()); } #include /** * Exception thrown by deserializers when the input bytes violate a consensus * rule (a structural/type violation enforced at the parsing layer, e.g. a * rule like "Elements of a Spend description MUST be valid encodings of the * types given above" that the spec enforces on well-formedness of the wire * format). * * This is distinct from other `std::ios_base::failure` throws (unexpected * end of stream, resource exhaustion, etc.) that are not consensus rule * violations and therefore do not warrant the same treatment. * * Callers with peer context (i.e. P2P message handlers) SHOULD catch this * specifically and apply `Misbehaving(pnode, 100)`; other parse failures * may be handled more leniently. */ class consensus_rule_failure : public std::ios_base::failure { public: using std::ios_base::failure::failure; }; /** * Deserialize a transaction from a hex string. * * On success, populates `tx`. On failure, throws an exception: * - `consensus_rule_failure` if the input bytes violate a consensus rule * (e.g. a structural/type violation enforced at the parsing layer). * Callers with peer context (i.e. P2P handlers) SHOULD treat this as * grounds for `Misbehaving(pnode, 100)`. * - `std::ios_base::failure` for other deserialization failures (not a * valid hex string, unexpected end of stream, etc.). * * Note: the P2P `tx` and `block` message handlers do not go through this * function; they read directly from a `CDataStream` and must apply the same * policy themselves via a try/catch around the read. */ extern void DecodeHexTx(CTransaction& tx, const std::string& strHexTx); void DecodeHexTx(CTransaction& tx, const std::string& strHexTx) if (!IsHex(strHexTx)) { throw std::ios_base::failure("not a valid hex string"); } ssData >> tx; extern void DecodeHexTx(CTransaction& tx, const std::string& strHexTx); try { DecodeHexTx(tx, strHexTx); return true; } catch (const std::exception&) { return false; } ASSERT_NO_THROW(DecodeHexTx(tx, triggerTx)); #include "consensus/validation.h" // All errors from `parse_v4_components` (both the wire-format // parser's I/O errors and the `valueBalanceSapling` consensus // check) are consensus rule violations: the input bytes do not // encode a valid Sapling v4 bundle. Throw `consensus_rule_failure` // so that P2P handlers can distinguish and apply DoS scoring // accordingly. throw consensus_rule_failure(e.what()); try { DecodeHexTx(tx, params[0].get_str()); } catch (const std::exception& e) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, std::string("TX decode failed: ") + e.what()); } try { DecodeHexTx(tx, params[0].get_str()); } catch (const std::exception& e) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, std::string("TX decode failed: ") + e.what()); } try { DecodeHexTx(origTx, params[0].get_str()); } catch (const std::exception& e) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, std::string("TX decode failed: ") + e.what()); } #include // Build a parent -> children map once over `mapBlockIndex`. Subsequent // subtree traversal and per-node descendant checks are then O(1) per // edge. std::unordered_map> children; children.reserve(mapBlockIndex.size()); for (const auto& entry : mapBlockIndex) { CBlockIndex* p = entry.second; if (p->pprev != nullptr) { children[p->pprev].push_back(p); } } // walking children directly via the precomputed map. const auto cit = children.find(subtree[i]); if (cit != children.end()) { subtree.insert(subtree.end(), cit->second.begin(), cit->second.end()); // is reset, the no-descendant-`nChainTx > 0` precondition already holds. // 2. No direct child of `p` has `nChainTx > 0`. By the // `ReceivedBlockTransactions` propagation invariant // (`nChainTx` is only assigned from `pprev->nChainTx + nTx` // once the parent's `nChainTx` is non-zero), `nChainTx > 0` // propagates strictly from parent to descendant, so this is // equivalent to "no descendant has `nChainTx > 0`". The const auto cit = children.find(p); if (cit != children.end()) { for (const CBlockIndex* c : cit->second) { assert(c->nChainTx == 0); } } static bool CheckBlockBodyAuthCommitment( const CBlock& block, int nHeight, const CCoinsViewCache& view, const Consensus::Params& consensusParams, CValidationState& state, std::optional& hashAuthDataRoot, std::optional& hashChainHistoryRoot); // Compute hashAuthDataRoot and hashChainHistoryRoot and perform the // NU5+ hashBlockCommitments check here, ahead of the per-tx loop. if (!CheckBlockBodyAuthCommitment(block, pindex->nHeight, view, consensusParams, state, hashAuthDataRoot, hashChainHistoryRoot)) { return false; assert(hashAuthDataRoot.has_value()); assert(hashChainHistoryRoot.has_value()); assert(hashChainHistoryRoot.has_value()); int nHeight, CValidationState& state, std::optional& hashAuthDataRoot, std::optional& hashChainHistoryRoot) if (consensusParams.NetworkUpgradeActive(nHeight, Consensus::UPGRADE_HEARTWOOD)) { auto prevConsensusBranchId = CurrentEpochBranchId(nHeight - 1, consensusParams); hashChainHistoryRoot = view.GetHistoryRoot(prevConsensusBranchId); if (consensusParams.NetworkUpgradeActive(nHeight, Consensus::UPGRADE_NU5)) { hashAuthDataRoot = block.BuildAuthDataMerkleTree(); // For NU5+ blocks, block.hashBlockCommitments must be the top digest // of the ZIP 244 block commitments linked list. // https://zips.z.cash/zip-0244#block-header-changes uint256 hashBlockCommitments = DeriveBlockCommitmentsHash( hashChainHistoryRoot.value(), hashAuthDataRoot.value()); if (block.hashBlockCommitments != hashBlockCommitments) { return state.DoS(100, error("%s: block's hashBlockCommitments is incorrect (should be ZIP 244 block commitment)", __func__), REJECT_INVALID, "bad-block-commitments-hash", true /* corruptionIn */); } } int nHeight = pindex->nHeight; // // Null `pindex->pprev` can only occur at genesis during a reindex. if (pindex->pprev != nullptr && pindex->pprev == chainActive.Tip()) { std::optional hashAuthDataRoot_, hashChainHistoryRoot_; if (!CheckBlockBodyAuthCommitment(block, nHeight, *pcoinsTip, chainparams.GetConsensus(), state, hashAuthDataRoot_, hashChainHistoryRoot_)) { break; // This case does not disable any verification work. It is retained // because it disables `fCacheResults` below, so that per-tx // verification results are not cached across benchmark runs. if (consensusParams.NetworkUpgradeActive(pindex->nHeight, Consensus::UPGRADE_NU5)) { // Override `block.hashBlockCommitments` so the NU5+ check inside // `ConnectBlock` passes against a synthetic `FakeCoinsViewDB`-backed // view, which does not reproduce the chain-history MMR state at the // benchmark height. No-op for pre-NU5 blocks. Callers should invoke // outside the timed region. static void recompute_hash_block_commitments( CBlock& block, const CBlockIndex& index, const CCoinsViewCache& view) { const auto& consensusParams = Params().GetConsensus(); if (consensusParams.NetworkUpgradeActive(index.nHeight, Consensus::UPGRADE_NU5)) { auto prevBranch = CurrentEpochBranchId(index.nHeight - 1, consensusParams); block.hashBlockCommitments = DeriveBlockCommitmentsHash( view.GetHistoryRoot(prevBranch), block.BuildAuthDataMerkleTree()); } } recompute_hash_block_commitments(block, index, view); recompute_hash_block_commitments(block, index, view); recompute_hash_block_commitments(block, index, view); /** * Reset body state on `root` and every descendant of `root` in * `mapBlockIndex`, post-order so that each descendant's `nChainTx` is * cleared before its parent's. Caller must hold `cs_main`. Used by * `InvalidBlockFound` to handle a body-replaceable failure on a block * that may have descendants with their own bodies (the sidechain * case): leaving descendant `nChainTx > 0` while the root's `nChainTx` * is zero would violate `CheckBlockIndex`'s `pindexFirstNeverProcessed` * invariant on each such descendant, and let `FindMostWorkChain` walk * through the stranded subtree. */ static void ResetBodyStateForSubtree(CBlockIndex* root) { AssertLockHeld(cs_main); // Collect the subtree rooted at `root` in BFS order (parents before // children), iterating once so we don't re-scan `mapBlockIndex` per // depth level. std::vector subtree = {root}; for (size_t i = 0; i < subtree.size(); ++i) { CBlockIndex* p = subtree[i]; for (const auto& entry : mapBlockIndex) { if (entry.second->pprev == p) { subtree.push_back(entry.second); } } } // Reset in reverse BFS order: descendants first, so by the time each // ancestor is reset its `HasChildWithChainTx`-equivalent precondition // already holds. for (auto it = subtree.rbegin(); it != subtree.rend(); ++it) { CBlockIndex* p = *it; // Erase from `setBlockIndexCandidates` *before* `ResetBodyState` // mutates `nSequenceId`. The set is ordered by // `(nChainWork, nSequenceId, ptr)` per `CBlockIndexWorkComparator`; // erasing after the mutation would fail to find `p`. setBlockIndexCandidates.erase(p); p->ResetBodyState(); setDirtyBlockIndex.insert(p); } } if (state.CorruptionPossible()) { // Body-replaceable failure: discard persisted body data and disk // pointers for `pindex` and its descendants, so a subsequent // submission of a matching body for the same header can be // processed normally. Do NOT mark BLOCK_FAILED_VALID, which would // permanently reject the header and prevent the canonical body // from ever replacing the mismatched one. The helper handles // `setBlockIndexCandidates.erase` and `setDirtyBlockIndex.insert` // for each node it resets, including `pindex`. ResetBodyStateForSubtree(pindex); } else { // Run `InvalidChainFound` regardless of `CorruptionPossible()`, so // that operators see the invalid-block log lines and so that // `pindexBestInvalid` / `CheckForkWarningConditions` always track // adversarial chains. The 6-block threshold in // `CheckForkWarningConditions` filters out non-fork incidents. InvalidChainFound(pindex, chainParams); // Compute hashAuthDataRoot and hashChainHistoryRoot here, ahead of the // per-tx loop, so the NU5+ hashBlockCommitments check below runs first. // See `corruptionPossible` in `consensus/validation.h` — checking // hashBlockCommitments first means any later per-tx auth-data failure // is not body-replaceable. std::optional hashAuthDataRoot; std::optional hashChainHistoryRoot; if (consensusParams.NetworkUpgradeActive(pindex->nHeight, Consensus::UPGRADE_NU5)) { hashAuthDataRoot = block.BuildAuthDataMerkleTree(); } if (consensusParams.NetworkUpgradeActive(pindex->nHeight, Consensus::UPGRADE_HEARTWOOD)) { auto prevConsensusBranchId = CurrentEpochBranchId(pindex->nHeight - 1, consensusParams); hashChainHistoryRoot = view.GetHistoryRoot(prevConsensusBranchId); } if (consensusParams.NetworkUpgradeActive(pindex->nHeight, Consensus::UPGRADE_NU5) && fCheckAuthDataRoot) { // For NU5+ blocks, block.hashBlockCommitments must be the top digest // of the ZIP 244 block commitments linked list. // https://zips.z.cash/zip-0244#block-header-changes uint256 hashBlockCommitments = DeriveBlockCommitmentsHash( hashChainHistoryRoot.value(), hashAuthDataRoot.value()); if (block.hashBlockCommitments != hashBlockCommitments) { return state.DoS(100, error("%s: block's hashBlockCommitments is incorrect (should be ZIP 244 block commitment)", __func__), REJECT_INVALID, "bad-block-commitments-hash", true /*corruptionIn*/); } } // Grab the consensus branch ID for this block. // NU5+ hashBlockCommitments was checked earlier in ConnectBlock, // before per-tx verification. /** * Pre-check that the block's `hashBlockCommitments` is consistent with the * received body's authorizing data, to catch NU5+ body-poisoning attacks * before the body is persisted. This duplicates only the NU5+ branch of * the full `hashBlockCommitments` validation in `ConnectBlock`, which * remains the authoritative check (and the only place pre-NU5 cases * —Heartwood-activation null check, Heartwood-active chain-history-root * check, Sapling tree root check— are validated). Pre-NU5 blocks aren't * body-poisoning vulnerable: those commitments are either independent of * the current block body (Heartwood-activation, Heartwood-active) or * commit to body data (Sapling tree root) that is also covered by * `hashMerkleRoot`. * * `view` must be a coins view positioned at the chain state up to and * including `pindexPrev`. The current caller (`AcceptBlock`) only invokes * this when `pindexPrev == chainActive.Tip()`, so passing `*pcoinsTip` * satisfies the requirement. Reconstructing the chain-history MMR state * at an arbitrary `pindexPrev` would require disconnecting and * reconnecting blocks, so for sidechain blocks the same check fires * later in `ConnectBlock`; the body-replaceable failure path then cleans * up persisted body data for the affected block index entry so that a * different body for the same header can still be accepted. * * On mismatch, returns `state.DoS(100, ..., corruptionIn=true)` so that * `InvalidBlockFound` and `ActivateBestChainStep` do not cache the failure * as permanent header invalidity. */ static bool CheckBlockBodyAuthCommitment( const CBlock& block, const CBlockIndex* pindexPrev, const CCoinsViewCache& view, const Consensus::Params& consensusParams, CValidationState& state) { // Reachable at genesis during a reindex when both `pindexPrev` and // `chainActive.Tip()` are null. NU5 cannot be active at height 0, // so this should be a no-op. if (pindexPrev == nullptr) { return true; } int nHeight = pindexPrev->nHeight + 1; if (!consensusParams.NetworkUpgradeActive(nHeight, Consensus::UPGRADE_NU5)) { return true; } auto prevConsensusBranchId = CurrentEpochBranchId(pindexPrev->nHeight, consensusParams); uint256 hashAuthDataRoot = block.BuildAuthDataMerkleTree(); uint256 hashChainHistoryRoot = view.GetHistoryRoot(prevConsensusBranchId); uint256 hashBlockCommitments = DeriveBlockCommitmentsHash( hashChainHistoryRoot, hashAuthDataRoot); if (block.hashBlockCommitments != hashBlockCommitments) { return state.DoS(100, error("%s: block's hashBlockCommitments is incorrect (should be ZIP 244 block commitment)", __func__), REJECT_INVALID, "bad-block-commitments-hash", true /* corruptionIn */); } return true; } // Body-vs-header commitment pre-check for active-tip extensions: catches // NU5+ body-poisoning attacks before the body is persisted to disk and // BLOCK_HAVE_DATA is set on the index entry. For sidechain blocks the // check has to wait until ConnectBlock (since reconstructing the chain // history MMR at an arbitrary `pprev` is infeasible); the body-replaceable // failure path in ConnectTip / InvalidBlockFound then cleans up persisted // body data so that a subsequent matching body can still be accepted. if (pindex->pprev == chainActive.Tip()) { if (!CheckBlockBodyAuthCommitment(block, pindex->pprev, *pcoinsTip, chainparams.GetConsensus(), state)) { return false; } } //! Reset all body-related state on this block index entry, leaving header //! and tree-position fields (`phashBlock`, `pprev`, `pskip`, `nHeight`, //! `nChainWork`, `nCachedBranchId`, the deserialized header) intact. //! Lowers the validity ladder back to `BLOCK_VALID_TREE` to reflect that //! the body data is gone but the header remains validated up to where //! `AcceptBlockHeader` left it. Used by `InvalidBlockFound` when //! `CValidationState::CorruptionPossible()` is set, to discard body data //! persisted from a body/header mismatch so that a subsequent submission //! of a matching body for the same header can be processed normally. //! //! Preconditions, enforced by callers: //! //! - Validity is at least `BLOCK_VALID_TREE`. //! - This entry is not in `setBlockIndexCandidates`. //! - No descendant of this entry has `nChainTx > 0`. Setting //! `nChainTx` to 0 here while a descendant retains `nChainTx > 0` //! would violate `CheckBlockIndex`'s `pindexFirstNeverProcessed` //! invariant on each such descendant: after the reset, the //! descendant's walk-tracker becomes set to this entry (because we //! now have `nTx == 0`), but the descendant's own `nChainTx` is //! still nonzero, breaking the equivalence between //! `pindexFirstNeverProcessed != NULL` and `nChainTx == 0`. Callers //! that may have such descendants must reset the descendant subtree //! (post-order) before this entry. void ResetBodyState() { assert((nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE); nStatus = (nStatus & ~(BLOCK_VALID_MASK | BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO)) | BLOCK_VALID_TREE; nFile = 0; nDataPos = 0; nUndoPos = 0; nTx = 0; nChainTx = 0; // `CheckBlockIndex` invariant: `nChainTx == 0` implies `nSequenceId == 0`. nSequenceId = 0; nChainSupplyDelta = std::nullopt; nTransparentValue = std::nullopt; nChainTotalSupply = std::nullopt; nChainTransparentValue = std::nullopt; nSproutValue = std::nullopt; nChainSproutValue = std::nullopt; nSaplingValue = 0; nChainSaplingValue = std::nullopt; nOrchardValue = 0; nChainOrchardValue = std::nullopt; nLockboxValue = 0; nChainLockboxValue = std::nullopt; hashSproutAnchor = uint256(); hashFinalSproutRoot = uint256(); hashFinalSaplingRoot = uint256(); hashAuthDataRoot = uint256(); hashFinalOrchardRoot = uint256(); hashChainHistoryRoot = uint256(); } /** * Marks a validation failure as body-replaceable: the body is inconsistent * with what the header committed to, so a different body matching the * same header could exist and pass validation. When set, callers must: * * - NOT cache the failure as permanent header invalidity * (`BLOCK_FAILED_VALID`); and * - discard persisted body data and disk pointers for the affected * block index entry (via `CBlockIndex::ResetBodyState`) so that a * subsequent submission of a matching body for the same header can * be processed. * * For a failure to be body-replaceable, the failing field must not be * pinned by either of the two header-to-body commitments: * * - `hashMerkleRoot` pins everything in `txid_digest`: vin prevouts, * vout values, value balances, anchors, nullifiers, expiry, locktime, * and (for pre-v5 transactions) `scriptSig` and Sapling sig/proof * material. * - `hashBlockCommitments` (NU5+) commits to `hashAuthDataRoot`, which * covers the v5+ auth-data fields (`scriptSig`, `bindingSig`, * `spendAuthSig`, proofs) that `txid_digest` deliberately excludes. * * Together these pin the entire block body, so the only failure modes * not pinned by `hashMerkleRoot` alone are `hashBlockCommitments` * itself and the two `CheckBlock` Merkle-root cases. Set * `corruptionIn=true` at exactly those sites: * * - `bad-txnmrklroot` and `bad-txns-duplicate` in `CheckBlock`. The * given body's txids do not reconstruct `hashMerkleRoot`, so the * body is malformed; a different body matching the header could * exist (`bad-txns-duplicate` is the CVE-2012-2459 Merkle padding * ambiguity). * - `bad-block-commitments-hash` (NU5+ only) in `ConnectBlock` and * in the `CheckBlockBodyAuthCommitment` active-tip pre-check. The * body's auth-data does not match the header's `hashAuthDataRoot`. * * Every other `ConnectBlock` failure is pinned by `hashMerkleRoot` * (`bad-txns-inputs-missingorspent`, `bad-cb-amount`, BIP30, sigops, * turnstile, etc.) and is therefore not body-replaceable. Per-tx * NU5+ auth-data verification (proofs, binding signatures) is not * body-replaceable either, because `ConnectBlock` checks * `hashBlockCommitments` first, pinning the auth-data via * `hashAuthDataRoot` before per-tx verification runs. */ REJECT_INVALID, "bad-blk-sigops"); // requiring a reindex. The other pool balances are included so that // we do not need to trust that the computed values from before the // checkpoint are correct. static bool CheckBlockMerkleRoot(const CBlock& block, bool* mutated); // Compute per-block pool value deltas from a block's transactions and // consensus rules. Used by both SetChainPoolValues (when a new block is // received) and CheckRecomputedPoolDeltas (when verifying persisted // deltas on load). // // `corruptionHint` is appended to any range-error message, and should be // either "" (for newly-received blocks where an overflow implies a bug or // malformed block) or a hint telling the user to reindex (for the on-load // path where an overflow implies persisted-data corruption). // any running sum goes out of MoneyDeltaRange. const char* corruptionHint, if (!MoneyDeltaRange(lockboxValue)) { return error("%s: lockbox value delta out of range: %d at height %d.%s", __func__, lockboxValue, nHeight, corruptionHint); } if (!MoneyDeltaRange(lockboxValue)) { return error("%s: lockbox value delta out of range: %d at height %d.%s", __func__, lockboxValue, nHeight, corruptionHint); } return error("%s: sapling value delta out of range: %d at height %d.%s", __func__, saplingValue, nHeight, corruptionHint); return error("%s: orchard value delta out of range: %d at height %d.%s", __func__, orchardValue, nHeight, corruptionHint); return error("%s: sprout value delta out of range: %d at height %d.%s", __func__, sproutValue, nHeight, corruptionHint); return error("%s: sprout value delta out of range: %d at height %d.%s", __func__, sproutValue, nHeight, corruptionHint); // Recompute shielded pool per-block deltas from the actual block data on // disk, returning false if they are inconsistent with the persisted values // on `pindex`. This is used during LoadBlockIndexDB for blocks at or after // the chain supply checkpoint to ensure that corrupted persisted deltas // cannot propagate wrong chain values. // // The Merkle root is verified against the header (which has already been // validated by PoW) to ensure the transactions have not been tampered with // on disk. Proofs are NOT re-verified — only pool deltas are recomputed. // // If fHavePruned is set (indicating intentional pruning), tolerate the // block data being missing. // // Returns false on error or if an inconsistency is detected. static bool CheckRecomputedPoolDeltas(const CBlockIndex* pindex, const CChainParams& chainparams, bool fHavePruned) { CBlock block; if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus())) { if (fHavePruned) { // We cannot check the pool deltas but this is likely because of // intentional pruning. Just trust the persisted deltas in this case. return true; } else { return error("%s: failed to read block at height %d from disk. " "This may indicate on-disk corruption; please restart with -reindex.", __func__, pindex->nHeight); } } // Verify that the transactions match the header's Merkle root. bool mutated = false; if (!CheckBlockMerkleRoot(block, &mutated)) { return error("%s: Merkle root check failed at height %d (mutated=%s). " "This may indicate on-disk corruption; please restart with -reindex.", __func__, pindex->nHeight, mutated ? "true" : "false"); } // Recompute pool deltas from the block data. If an overflow is detected // here, it indicates persisted-deltas corruption (since the same block // was accepted at tip previously), so hint at reindexing. CAmount sproutValue, saplingValue, orchardValue, lockboxValue; if (!ComputePoolDeltas(block, chainparams, pindex->nHeight, " This may indicate on-disk corruption; please restart with -reindex.", sproutValue, saplingValue, orchardValue, lockboxValue)) { return false; } // Abort if (non-nullopt) persisted differs from recomputed, since that indicates corruption. auto checkDelta = [&](const char* name, CAmount persisted, CAmount recomputed) -> bool { if (persisted != recomputed) { return error("%s: %s mismatch at height %d: persisted %d, recomputed %d. " "This may indicate on-disk corruption; please restart with -reindex.", __func__, name, pindex->nHeight, persisted, recomputed); } return true; }; // Check recomputed deltas against persisted values. // // nSproutValue may be nullopt on legacy block indexes written before SPROUT_VALUE_VERSION, // but this should not occur at heights >= the chain supply checkpoint. if (!pindex->nSproutValue.has_value()) { return error("%s: Sprout value is nullopt at height %d, which should not occur " "after the chain supply checkpoint at height %d. " "This may indicate on-disk corruption; please restart with -reindex.", __func__, pindex->nHeight, chainparams.ChainSupplyCheckpointHeight()); } return checkDelta("nSproutValue", pindex->nSproutValue.value(), sproutValue) && checkDelta("nSaplingValue", pindex->nSaplingValue, saplingValue) && checkDelta("nOrchardValue", pindex->nOrchardValue, orchardValue) && checkDelta("nLockboxValue", pindex->nLockboxValue, lockboxValue); } if (!ComputePoolDeltas(block, chainparams, pindex->nHeight, "", // Check whether we have ever pruned block & undo files pblocktree->ReadFlag("prunedblockfiles", fHavePruned); if (fHavePruned) { LogPrintf("LoadBlockIndexDB(): Block files have previously been pruned\n"); } if (pindex->nTx == 0 && pindex->IsValid(BLOCK_PARTIALLY_VALID_TRANSACTIONS) && pindex->nHeight >= chainparams.ChainSupplyCheckpointHeight() && !fHavePruned) { // We want to avoid CheckRecomputedPoolDeltas below being // incorrectly skipped in the `pindex->nTx == 0` case. // // nTx and BLOCK_PARTIALLY_VALID_TRANSACTIONS are set together // in ReceivedBlockTransactions, and neither is ever cleared. // So IsValid(BLOCK_PARTIALLY_VALID_TRANSACTIONS) with nTx == 0 // can only arise from block index corruption, not from normal // operation. The !fHavePruned guard is consistent with the fact // that we don't guarantee delta checking on a pruned node. return error("%s: block at height %d was previously validated " "but has no transaction data; cannot verify pool deltas. " "Please restart with -reindex.", __func__, pindex->nHeight); } // For blocks at or after the chain supply checkpoint, recompute the // shielded pool deltas from the actual block data on disk and check // the persisted values against them. This protects against corrupted // deltas from the duplicate-header clobbering bug or other on-disk // corruption. if (pindex->nHeight >= chainparams.ChainSupplyCheckpointHeight() && !CheckRecomputedPoolDeltas(pindex, chainparams, fHavePruned)) { return false; } // Compute per-block shielded pool deltas (Sprout, Sapling, Orchard, lockbox) // for `block` at `nHeight` from its transactions and consensus rules. // // On success, sets sproutValue, saplingValue, orchardValue, and lockboxValue // to the corresponding per-block deltas, and returns true. Returns false if // any running Sprout/Sapling/Orchard sum goes out of MoneyDeltaRange. static bool ComputePoolDeltas( const CBlock& block, const CChainParams& chainparams, int nHeight, CAmount& sproutValue, CAmount& saplingValue, CAmount& orchardValue, CAmount& lockboxValue) { sproutValue = 0; saplingValue = 0; orchardValue = 0; // Each lockbox disbursement produces a negative change to the lockbox value. // Each lockbox funding stream produces a positive change to the lockbox value. lockboxValue = 0; for (auto disbursement : chainparams.GetConsensus().GetLockboxDisbursementsForHeight(nHeight)) { lockboxValue -= disbursement.GetAmount(); } for (auto elem : chainparams.GetConsensus().GetActiveFundingStreamElements(nHeight)) { if (std::holds_alternative(elem.first)) { lockboxValue += elem.second; } } for (const auto& tx : block.vtx) { // Negative valueBalanceSapling "takes" money from the transparent value pool // and adds it to the Sapling value pool. Positive valueBalanceSapling "gives" // money to the transparent value pool, removing from the Sapling value // pool. So we invert the sign here. saplingValue -= tx.GetValueBalanceSapling(); if (!MoneyDeltaRange(saplingValue)) { return error("%s: sapling value delta out of range: %d at height %d", __func__, saplingValue, nHeight); } // valueBalanceOrchard behaves the same way as valueBalanceSapling. orchardValue -= tx.GetOrchardBundle().GetValueBalance(); if (!MoneyDeltaRange(orchardValue)) { return error("%s: orchard value delta out of range: %d at height %d", __func__, orchardValue, nHeight); } for (const auto& js : tx.vJoinSplit) { sproutValue += js.vpub_old; if (!MoneyDeltaRange(sproutValue)) { return error("%s: sprout value delta out of range: %d at height %d", __func__, sproutValue, nHeight); } sproutValue -= js.vpub_new; if (!MoneyDeltaRange(sproutValue)) { return error("%s: sprout value delta out of range: %d at height %d", __func__, sproutValue, nHeight); } } } return true; } // pindex->pprev is only permitted to be null for the genesis block assert (pindex->pprev || pindex->nHeight == 0); CAmount sproutValue, saplingValue, orchardValue, lockboxValue; if (!ComputePoolDeltas(block, chainparams, pindex->nHeight, sproutValue, saplingValue, orchardValue, lockboxValue)) { return false; // These values can only be computed here for the genesis block. // For all other blocks, we update them in ConnectBlock instead. if (pindex->pprev == nullptr) { CAmount chainSupplyDelta = 0; CAmount transparentValueDelta = 0; for (const auto& tx : block.vtx) { // Verify that the block's transactions produce the expected Merkle root // and that the tree is not malleated (CVE-2012-2459: repeating sequences // of transactions can leave the Merkle root unchanged while invalidating // the block). static bool CheckBlockMerkleRoot(const CBlock& block, bool* mutated) { uint256 computedRoot = BlockMerkleRoot(block, mutated); return !*mutated && computedRoot == block.hashMerkleRoot; } bool mutated = false; if (!CheckBlockMerkleRoot(block, &mutated)) { if (mutated) { return state.DoS(100, error("CheckBlock(): duplicate transaction"), REJECT_INVALID, "bad-txns-duplicate", true); } else { return state.DoS(100, error("CheckBlock(): hashMerkleRoot mismatch"), REJECT_INVALID, "bad-txnmrklroot", true); } } merkle root. Claim: assuming no double-SHA256 collisions, the (root, mutated) pair returned by ComputeMerkleRoot uniquely determines the input hash list when mutated is false. Proof by strong induction on max(|L1|, |L2|) for two lists that produce the same root with mutated = false: Base (max <= 1): single-element lists with the same root must have the same element; mismatched lengths produce different roots. Inductive step (both lists have size >= 2): after one hashing round, L1 and L2 produce intermediate lists M1 and M2 with lengths ceil(|L1|/2) < |L1| and ceil(|L2|/2) < |L2|. Since the overall mutated flag is false, no mutation occurs at any subsequent level either, so by the inductive hypothesis M1 = M2. Equal intermediate lengths imply |L1| and |L2| differ by at most 1. If they are equal, collision-freeness of the hash gives L1[i] = L2[i] for each position. If they differ by 1, wlog say |L1| = n-1 (odd) and |L2| = n (even), the last intermediate hash of L1 comes from duplicating its last element: H(L1[n-2] || L1[n-2]) = H(L2[n-2] || L2[n-1]). Collision-freeness gives L2[n-2] = L2[n-1]. But L2 has even length, so (n-2, n-1) is a checked pair in the mutation scan. This pair being equal causes the mutated flag to be set, contradicting the assumption. ∎ // Enable ZIP 209 enforcement without zeroing shielded pool balances. if (network == CBaseChainParams::REGTEST && mapArgs.count("-regtestenablezip209")) { regTestParams.SetRegTestZIP209Enabled(); } strUsage += HelpMessageOpt("-regtestenablezip209", "Enable ZIP 209 turnstile enforcement on regtest without zeroing shielded pool balances (regtest-only)"); if (mapArgs.count("-regtestenablezip209") && chainparams.NetworkIDString() != "regtest") { return InitError("-regtestenablezip209 may only be used on regtest."); } // Chain supply checkpoint at NU6.1 activation (height 3146400). // This allows nodes with legacy block index data (written by zcashd // versions older than 5.4.0, which did not serialize nChainSupplyDelta) // to bootstrap nChainTotalSupply and nChainTransparentValue without // requiring a reindex. nChainSupplyCheckpointHeight = 3146400; nChainSupplyCheckpointTotalSupply = 1640588297804480; nChainSupplyCheckpointTransparentValue = 1158133657237751; nChainSupplyCheckpointSproutValue = 2562695744028; nChainSupplyCheckpointSaplingValue = 64691367655556; nChainSupplyCheckpointOrchardValue = 415200558417145; nChainSupplyCheckpointLockboxValue = 18750000; // Chain supply checkpoint at NU6.1 activation (height 3536500). nChainSupplyCheckpointHeight = 3536500; nChainSupplyCheckpointTotalSupply = 1690647512835043; nChainSupplyCheckpointTransparentValue = 1499728640946163; nChainSupplyCheckpointSproutValue = 42832983037484; nChainSupplyCheckpointSaplingValue = 140562922195481; nChainSupplyCheckpointOrchardValue = 7522947905915; nChainSupplyCheckpointLockboxValue = 18750000; void SetRegTestAllowLegacyChainSupplyData() { fRegTestAllowLegacyChainSupplyData = true; } void SetRegTestChainSupplyCheckpoint() { // Hardcoded checkpoint at height 200 (the tip of the regtest caches). // The block hash is left null; FallbackChainSupplyCheckpoint // skips the hash check when it is null. // Values from the sprout regtest cache at height 200. // The sprout cache has 4 × 50 ZEC = 200 ZEC shielded into Sprout. nChainSupplyCheckpointHeight = 200; nChainSupplyCheckpointTotalSupply = 214375000000; nChainSupplyCheckpointTransparentValue = 194375000000; nChainSupplyCheckpointSproutValue = 20000000000; nChainSupplyCheckpointSaplingValue = 0; nChainSupplyCheckpointOrchardValue = 0; nChainSupplyCheckpointLockboxValue = 0; hashChainSupplyCheckpointBlock.SetNull(); } // Allow regtest tests that use legacy block index data (lacking nChainSupplyDelta) // to skip the supply consistency check rather than aborting the node. if (network == CBaseChainParams::REGTEST && mapArgs.count("-regtestallowlegacychainsupplydata")) { regTestParams.SetRegTestAllowLegacyChainSupplyData(); } if (network == CBaseChainParams::REGTEST && mapArgs.count("-regtestchainsupplycheckpoint")) { regTestParams.SetRegTestChainSupplyCheckpoint(); } int ChainSupplyCheckpointHeight() const { return nChainSupplyCheckpointHeight; } CAmount ChainSupplyCheckpointTotalSupply() const { return nChainSupplyCheckpointTotalSupply; } CAmount ChainSupplyCheckpointTransparentValue() const { return nChainSupplyCheckpointTransparentValue; } CAmount ChainSupplyCheckpointSproutValue() const { return nChainSupplyCheckpointSproutValue; } CAmount ChainSupplyCheckpointSaplingValue() const { return nChainSupplyCheckpointSaplingValue; } CAmount ChainSupplyCheckpointOrchardValue() const { return nChainSupplyCheckpointOrchardValue; } CAmount ChainSupplyCheckpointLockboxValue() const { return nChainSupplyCheckpointLockboxValue; } uint256 ChainSupplyCheckpointBlockHash() const { return hashChainSupplyCheckpointBlock; } /** * Regtest-only: when true, the supply consistency check in `ConnectBlock` * skips on blocks where chain supply tracking fields (`nChainTotalSupply`, * `nChainTransparentValue`) are missing, instead of aborting the node with * a "reindex required" message. This is needed only by tests that use the * `sprout` regtest cache, which was generated by a zcashd version older * than `TRANSPARENT_VALUE_VERSION`. The flag is set via * `-regtestallowlegacychainsupplydata` and is rejected outside regtest. */ bool RegTestAllowLegacyChainSupplyData() const { return fRegTestAllowLegacyChainSupplyData; } int nChainSupplyCheckpointHeight = 0; CAmount nChainSupplyCheckpointTotalSupply = 0; CAmount nChainSupplyCheckpointTransparentValue = 0; CAmount nChainSupplyCheckpointSproutValue = 0; CAmount nChainSupplyCheckpointSaplingValue = 0; CAmount nChainSupplyCheckpointOrchardValue = 0; CAmount nChainSupplyCheckpointLockboxValue = 0; uint256 hashChainSupplyCheckpointBlock; bool fRegTestAllowLegacyChainSupplyData = false; extern bool FallbackChainSupplyCheckpoint(CBlockIndex *pindex, const CChainParams& chainparams); TEST(Validation, FallbackChainSupplyCheckpoint) { // Use mainnet params which have a real checkpoint at NU6.1 activation. const CChainParams& chainparams = Params(CBaseChainParams::MAIN); const int cpHeight = chainparams.ChainSupplyCheckpointHeight(); const uint256 cpHash = chainparams.ChainSupplyCheckpointBlockHash(); const CAmount cpTotalSupply = chainparams.ChainSupplyCheckpointTotalSupply(); const CAmount cpTransparentValue = chainparams.ChainSupplyCheckpointTransparentValue(); const CAmount cpSproutValue = chainparams.ChainSupplyCheckpointSproutValue(); const CAmount cpSaplingValue = chainparams.ChainSupplyCheckpointSaplingValue(); const CAmount cpOrchardValue = chainparams.ChainSupplyCheckpointOrchardValue(); const CAmount cpLockboxValue = chainparams.ChainSupplyCheckpointLockboxValue(); CBlockHeader header; // Before the checkpoint, chain values remain nullopt. const uint256 someHash = uint256S("0123456789abcdef"); CBlockIndex beforeCheckpoint(header); beforeCheckpoint.nHeight = cpHeight - 1; beforeCheckpoint.phashBlock = &someHash; FallbackChainSupplyCheckpoint(&beforeCheckpoint, chainparams); EXPECT_FALSE(beforeCheckpoint.nChainTotalSupply.has_value()); EXPECT_FALSE(beforeCheckpoint.nChainTransparentValue.has_value()); EXPECT_FALSE(beforeCheckpoint.nChainSproutValue.has_value()); EXPECT_FALSE(beforeCheckpoint.nChainSaplingValue.has_value()); EXPECT_FALSE(beforeCheckpoint.nChainOrchardValue.has_value()); EXPECT_FALSE(beforeCheckpoint.nChainLockboxValue.has_value()); // At the checkpoint height with the correct hash, values are injected. CBlockIndex atCheckpoint(header); atCheckpoint.nHeight = cpHeight; atCheckpoint.phashBlock = &cpHash; // Initially nullopt. EXPECT_FALSE(atCheckpoint.nChainTotalSupply.has_value()); EXPECT_FALSE(atCheckpoint.nChainTransparentValue.has_value()); EXPECT_FALSE(atCheckpoint.nChainSproutValue.has_value()); EXPECT_FALSE(atCheckpoint.nChainSaplingValue.has_value()); EXPECT_FALSE(atCheckpoint.nChainOrchardValue.has_value()); EXPECT_FALSE(atCheckpoint.nChainLockboxValue.has_value()); FallbackChainSupplyCheckpoint(&atCheckpoint, chainparams); ASSERT_TRUE(atCheckpoint.nChainTotalSupply.has_value()); EXPECT_EQ(atCheckpoint.nChainTotalSupply.value(), cpTotalSupply); ASSERT_TRUE(atCheckpoint.nChainTransparentValue.has_value()); EXPECT_EQ(atCheckpoint.nChainTransparentValue.value(), cpTransparentValue); ASSERT_TRUE(atCheckpoint.nChainSproutValue.has_value()); EXPECT_EQ(atCheckpoint.nChainSproutValue.value(), cpSproutValue); ASSERT_TRUE(atCheckpoint.nChainSaplingValue.has_value()); EXPECT_EQ(atCheckpoint.nChainSaplingValue.value(), cpSaplingValue); ASSERT_TRUE(atCheckpoint.nChainOrchardValue.has_value()); EXPECT_EQ(atCheckpoint.nChainOrchardValue.value(), cpOrchardValue); ASSERT_TRUE(atCheckpoint.nChainLockboxValue.has_value()); EXPECT_EQ(atCheckpoint.nChainLockboxValue.value(), cpLockboxValue); // If values are already set correctly, the fallback should succeed // and not overwrite them. EXPECT_TRUE(FallbackChainSupplyCheckpoint(&atCheckpoint, chainparams)); EXPECT_EQ(atCheckpoint.nChainTotalSupply.value(), cpTotalSupply); EXPECT_EQ(atCheckpoint.nChainTransparentValue.value(), cpTransparentValue); EXPECT_EQ(atCheckpoint.nChainSproutValue.value(), cpSproutValue); EXPECT_EQ(atCheckpoint.nChainSaplingValue.value(), cpSaplingValue); EXPECT_EQ(atCheckpoint.nChainOrchardValue.value(), cpOrchardValue); EXPECT_EQ(atCheckpoint.nChainLockboxValue.value(), cpLockboxValue); // If values are set but WRONG, the fallback should return false // (indicating corruption). CBlockIndex wrongTotalSupply(header); wrongTotalSupply.nHeight = cpHeight; wrongTotalSupply.phashBlock = &cpHash; wrongTotalSupply.nChainTotalSupply = 12345; EXPECT_FALSE(FallbackChainSupplyCheckpoint(&wrongTotalSupply, chainparams)); EXPECT_EQ(wrongTotalSupply.nChainTotalSupply.value(), 12345); CBlockIndex wrongTransparentValue(header); wrongTransparentValue.nHeight = cpHeight; wrongTransparentValue.phashBlock = &cpHash; wrongTransparentValue.nChainTotalSupply = cpTotalSupply; wrongTransparentValue.nChainTransparentValue = 67890; EXPECT_FALSE(FallbackChainSupplyCheckpoint(&wrongTransparentValue, chainparams)); EXPECT_EQ(wrongTransparentValue.nChainTransparentValue.value(), 67890); CBlockIndex wrongSaplingValue(header); wrongSaplingValue.nHeight = cpHeight; wrongSaplingValue.phashBlock = &cpHash; wrongSaplingValue.nChainTotalSupply = cpTotalSupply; wrongSaplingValue.nChainTransparentValue = cpTransparentValue; wrongSaplingValue.nChainSproutValue = cpSproutValue; wrongSaplingValue.nChainSaplingValue = 99999; EXPECT_FALSE(FallbackChainSupplyCheckpoint(&wrongSaplingValue, chainparams)); EXPECT_EQ(wrongSaplingValue.nChainSaplingValue.value(), 99999); // After the checkpoint, values accumulate from the injected base. // Create a child block one height after the checkpoint, with known deltas. CBlockIndex afterCheckpoint(header); afterCheckpoint.nHeight = cpHeight + 1; afterCheckpoint.phashBlock = &someHash; afterCheckpoint.pprev = &atCheckpoint; afterCheckpoint.nChainSupplyDelta = 312500000; // 3.125 ZEC subsidy afterCheckpoint.nTransparentValue = 200000000; // 2 ZEC transparent delta // Simulate the accumulation that LoadBlockIndexDB performs: // nChainTotalSupply = pprev->nChainTotalSupply + nChainSupplyDelta // nChainTransparentValue = pprev->nChainTransparentValue + nTransparentValue ASSERT_TRUE(afterCheckpoint.pprev->nChainTotalSupply.has_value()); ASSERT_TRUE(afterCheckpoint.nChainSupplyDelta.has_value()); afterCheckpoint.nChainTotalSupply = afterCheckpoint.pprev->nChainTotalSupply.value() + afterCheckpoint.nChainSupplyDelta.value(); ASSERT_TRUE(afterCheckpoint.pprev->nChainTransparentValue.has_value()); ASSERT_TRUE(afterCheckpoint.nTransparentValue.has_value()); afterCheckpoint.nChainTransparentValue = afterCheckpoint.pprev->nChainTransparentValue.value() + afterCheckpoint.nTransparentValue.value(); ASSERT_TRUE(afterCheckpoint.nChainTotalSupply.has_value()); EXPECT_EQ(afterCheckpoint.nChainTotalSupply.value(), cpTotalSupply + 312500000); ASSERT_TRUE(afterCheckpoint.nChainTransparentValue.has_value()); EXPECT_EQ(afterCheckpoint.nChainTransparentValue.value(), cpTransparentValue + 200000000); // The fallback should NOT inject at this height (it's past the checkpoint). afterCheckpoint.nChainTotalSupply = std::nullopt; afterCheckpoint.nChainTransparentValue = std::nullopt; afterCheckpoint.nChainSproutValue = std::nullopt; afterCheckpoint.nChainSaplingValue = std::nullopt; afterCheckpoint.nChainOrchardValue = std::nullopt; afterCheckpoint.nChainLockboxValue = std::nullopt; FallbackChainSupplyCheckpoint(&afterCheckpoint, chainparams); EXPECT_FALSE(afterCheckpoint.nChainTotalSupply.has_value()); EXPECT_FALSE(afterCheckpoint.nChainTransparentValue.has_value()); EXPECT_FALSE(afterCheckpoint.nChainSproutValue.has_value()); EXPECT_FALSE(afterCheckpoint.nChainSaplingValue.has_value()); EXPECT_FALSE(afterCheckpoint.nChainOrchardValue.has_value()); EXPECT_FALSE(afterCheckpoint.nChainLockboxValue.has_value()); } strUsage += HelpMessageOpt("-regtestallowlegacychainsupplydata", "Skip the chain supply consistency check on blocks where chain supply tracking fields are missing, instead of aborting the node (regtest-only). Needed only for tests that load a regtest cache generated by a zcashd version before v5.4.0"); strUsage += HelpMessageOpt("-regtestchainsupplycheckpoint", "Enable a hardcoded chain supply checkpoint at the regtest cache tip height, to test the checkpoint fallback for legacy block index data (regtest-only)"); if (mapArgs.count("-regtestallowlegacychainsupplydata") && chainparams.NetworkIDString() != "regtest") { return InitError("-regtestallowlegacychainsupplydata may only be used on regtest."); } if (mapArgs.count("-regtestchainsupplycheckpoint") && chainparams.NetworkIDString() != "regtest") { return InitError("-regtestchainsupplycheckpoint may only be used on regtest."); } // This is normally a "reindex required" condition, but on regtest the // `-regtestallowlegacychainsupplydata` flag allows tests that load such // legacy caches to skip the check instead. } else if (chainparams.RegTestAllowLegacyChainSupplyData()) { LogPrintf("%s: skipping chain supply consistency check at height %d because chain supply tracking fields are missing (-regtestallowlegacychainsupplydata)\n", __func__, } else if (pindex->nHeight >= chainparams.ChainSupplyCheckpointHeight()) { // The chain supply checkpoint should have injected values at // the checkpoint height. If we're past that height and the // values are still missing, something is wrong. return AbortNode(state, "Chain supply tracking fields are missing; please restart with -reindex to recover."); void FallbackSproutValuePoolBalance(CBlockIndex *pindex, const CChainParams& chainparams) bool FallbackChainSupplyCheckpoint(CBlockIndex *pindex, const CChainParams& chainparams) { // Check if the height of this block matches the chain supply checkpoint if (pindex->nHeight != chainparams.ChainSupplyCheckpointHeight()) { return true; } if (!chainparams.ChainSupplyCheckpointBlockHash().IsNull() && pindex->GetBlockHash() != chainparams.ChainSupplyCheckpointBlockHash()) { return error("%s: checkpoint block hash mismatch at height %d: " "expected %s, got %s", __func__, pindex->nHeight, chainparams.ChainSupplyCheckpointBlockHash().ToString(), pindex->GetBlockHash().ToString()); } // Verify that the checkpoint pool values sum to the total supply. assert(chainparams.ChainSupplyCheckpointTransparentValue() + chainparams.ChainSupplyCheckpointSproutValue() + chainparams.ChainSupplyCheckpointSaplingValue() + chainparams.ChainSupplyCheckpointOrchardValue() + chainparams.ChainSupplyCheckpointLockboxValue() == chainparams.ChainSupplyCheckpointTotalSupply()); // Helper: inject a checkpoint value if nullopt, or error if it mismatches. auto applyCheckpoint = [&](const char* fieldName, std::optional& field, CAmount expected) -> bool { if (!field.has_value()) { field = expected; } else if (field.value() != expected) { return error("%s: %s mismatch at checkpoint height %d: " "expected %d, got %d. This may indicate chain value corruption; " "please restart with -reindex.", __func__, fieldName, pindex->nHeight, expected, field.value()); } return true; }; return applyCheckpoint("nChainTotalSupply", pindex->nChainTotalSupply, chainparams.ChainSupplyCheckpointTotalSupply()) && applyCheckpoint("nChainTransparentValue", pindex->nChainTransparentValue, chainparams.ChainSupplyCheckpointTransparentValue()) && applyCheckpoint("nChainSproutValue", pindex->nChainSproutValue, chainparams.ChainSupplyCheckpointSproutValue()) && applyCheckpoint("nChainSaplingValue", pindex->nChainSaplingValue, chainparams.ChainSupplyCheckpointSaplingValue()) && applyCheckpoint("nChainOrchardValue", pindex->nChainOrchardValue, chainparams.ChainSupplyCheckpointOrchardValue()) && applyCheckpoint("nChainLockboxValue", pindex->nChainLockboxValue, chainparams.ChainSupplyCheckpointLockboxValue()); } // Fall back to hardcoded chain supply values, or verify // existing values match the checkpoint. if (!FallbackChainSupplyCheckpoint(pindex, chainparams)) { return false; } // override and set the in-memory size of shielded pools to zero. // An unshielding transaction can then be used to trigger and test // the handling of turnstile violations. // The returned CTxOut has nValue in MoneyRange. This is guaranteed by // CheckTransaction for outputs that entered the UTXO set through normal // block connection, and re-validated here to defend against on-disk // corruption of the chainstate database. const CTxOut& out = coins->vout[input.prevout.n]; if (!MoneyRange(out.nValue)) { throw std::runtime_error("CCoinsViewCache::GetOutputFor(): output value out of range"); } return out; try { if (chainparams.RequireStandard() && !AreInputsStandard(tx, view, consensusBranchId)) return state.Invalid(false, REJECT_NONSTANDARD, "bad-txns-nonstandard-inputs"); } catch (const std::runtime_error& e) { return state.DoS(100, false, REJECT_INVALID, "bad-txns-input-value-out-of-range"); } try { nSigOps += GetP2SHSigOpCount(tx, view); } catch (const std::runtime_error& e) { return state.DoS(100, false, REJECT_INVALID, "bad-txns-input-value-out-of-range"); } try { for (const auto& input : tx.vin) { allPrevOutputs.push_back(view.GetOutputFor(input)); } } catch (const std::runtime_error& e) { return state.DoS(100, false, REJECT_INVALID, "bad-txns-input-value-out-of-range"); try { // Add memory address index if (fAddressIndex) { pool.addAddressIndex(entry, view); } // insightexplorer: Add memory spent index if (fSpentIndex) { pool.addSpentIndex(entry, view); } } catch (const std::runtime_error& e) { return state.DoS(100, false, REJECT_INVALID, "bad-txns-input-value-out-of-range"); CTxOut prevout; try { prevout = view.GetOutputFor(input); } catch (const std::runtime_error& e) { error("DisconnectBlock(): %s", e.what()); return DISCONNECT_FAILED; } assert(MoneyRange(prevout.nValue)); CTxOut prevout; try { prevout = view.GetOutputFor(input); } catch (const std::runtime_error& e) { return state.DoS(100, error("%s: %s", __func__, e.what()), REJECT_INVALID, "bad-txns-input-value-out-of-range"); } try { nSigOps += GetP2SHSigOpCount(tx, view); } catch (const std::runtime_error& e) { return state.DoS(100, error("%s: %s", __func__, e.what()), REJECT_INVALID, "bad-txns-input-value-out-of-range"); } /** * When true, the turnstile checks defined by ZIP 209 are enforced in * `ConnectBlock`. Always true on mainnet and testnet (these are consensus * rules). On regtest, defaults to false (so that regtest tests can * construct chains that don't satisfy the turnstile invariants without * being rejected) and is enabled only when `-developersetpoolsizezero` is * set, allowing turnstile violations to be exercised by tests and developer * debugging. */ // Compute per-block pool value deltas first. `SetChainPoolValues` can // fail if the running sum of per-pool values overflows the valid // monetary range. If it does, return without mutating `pindexNew`: // leaving the block index in its prior (header-only) state means // future processing will not consider the block as having data, and // the on-disk block file is harmlessly orphaned (it will be ignored, // or cleaned up by the next reindex). //! All consensus rules satisfied: transparent script execution, shielded proofs (Sprout JoinSplit, //! Sapling Spend/Output, Orchard Action), shielded signatures, turnstile/lockbox checks, and all //! other consensus checks performed in `ConnectBlock`. Implies all parents are also at least //! CONSENSUS. BLOCK_VALID_CONSENSUS = 5, BLOCK_VALID_CHAIN | BLOCK_VALID_CONSENSUS, if (pindex->GetUndoPos().IsNull() || !pindex->IsValid(BLOCK_VALID_CONSENSUS)) // Now that all consensus rules have been validated, set nCachedBranchId // and raise validity to BLOCK_VALID_CONSENSUS. pindex->RaiseValidity(BLOCK_VALID_CONSENSUS); CBlockIndex* pindexFirstNotConsensusValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_CONSENSUS (regardless of being valid or not). if (pindex->pprev != NULL && pindexFirstNotConsensusValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_CONSENSUS) pindexFirstNotConsensusValid = pindex; if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_CONSENSUS) assert(pindexFirstNotConsensusValid == NULL); // CONSENSUS valid implies all parents are CONSENSUS valid if (pindex == pindexFirstNotConsensusValid) pindexFirstNotConsensusValid = NULL; send = mi->second->IsValid(BLOCK_VALID_CONSENSUS) && (pindexBestHeader != NULL) && } else if (block->IsValid(BLOCK_VALID_CONSENSUS)) { if (pindex->IsValid(BLOCK_VALID_CONSENSUS)) if (pindex->IsValid(BLOCK_VALID_CONSENSUS)) BLOCK_PARTIALLY_VALID_TRANSACTIONS = 3, BLOCK_VALID_MASK = BLOCK_VALID_HEADER | BLOCK_VALID_TREE | BLOCK_PARTIALLY_VALID_TRANSACTIONS | bool IsValid(enum BlockStatus nUpTo = BLOCK_PARTIALLY_VALID_TRANSACTIONS) const EXPECT_FALSE(fakeIndex1.IsValid(BLOCK_PARTIALLY_VALID_TRANSACTIONS)); EXPECT_FALSE(fakeIndex2.IsValid(BLOCK_PARTIALLY_VALID_TRANSACTIONS)); EXPECT_FALSE(fakeIndex1.IsValid(BLOCK_PARTIALLY_VALID_TRANSACTIONS)); EXPECT_TRUE(fakeIndex2.IsValid(BLOCK_PARTIALLY_VALID_TRANSACTIONS)); EXPECT_TRUE(fakeIndex1.IsValid(BLOCK_PARTIALLY_VALID_TRANSACTIONS)); EXPECT_TRUE(fakeIndex2.IsValid(BLOCK_PARTIALLY_VALID_TRANSACTIONS)); if (it->second->IsValid(BLOCK_PARTIALLY_VALID_TRANSACTIONS) && it->second->nChainTx && !setBlockIndexCandidates.value_comp()(it->second, chainActive.Tip())) { if (it->second->IsValid(BLOCK_PARTIALLY_VALID_TRANSACTIONS) && it->second->nChainTx && setBlockIndexCandidates.value_comp()(chainActive.Tip(), it->second)) { pindexNew->RaiseValidity(BLOCK_PARTIALLY_VALID_TRANSACTIONS); // If pindexNew is the genesis block or all parents are BLOCK_PARTIALLY_VALID_TRANSACTIONS. if (pindex->IsValid(BLOCK_PARTIALLY_VALID_TRANSACTIONS) && (pindex->nChainTx || pindex->pprev == NULL)) } else if (pindexIter->IsValid(BLOCK_PARTIALLY_VALID_TRANSACTIONS) && pindexIter->nChainTx) { CBlockIndex* pindexFirstNotTransactionsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_PARTIALLY_VALID_TRANSACTIONS (regardless of being valid or not). if (pindex->pprev != NULL && pindexFirstNotTransactionsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_PARTIALLY_VALID_TRANSACTIONS) pindexFirstNotTransactionsValid = pindex; // PARTIALLY_VALID_TRANSACTIONS is equivalent to nTx > 0 for all nodes (whether or not pruning has occurred). // HAVE_DATA is only equivalent to nTx > 0 (or PARTIALLY_VALID_TRANSACTIONS) if no pruning has occurred. assert(((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_PARTIALLY_VALID_TRANSACTIONS) == (pindex->nTx > 0)); // This is pruning-independent. // available to ConnectBlock in the TestNewBlockAtTipValidity path, where bool TestNewBlockAtTipValidity( const CBlock& block, bool fIsBlockTemplate) CBlockIndex* pindexPrev = chainActive.Tip(); assert(block.hashPrevBlock == pindexPrev->GetBlockHash()); bool TestNewBlockAtTipValidity(CValidationState& state, const CChainParams& chainparams, const CBlock& block, bool fIsBlockTemplate); if (!TestNewBlockAtTipValidity(state, chainparams, *pblock, true)) { throw std::runtime_error(strprintf("%s: TestNewBlockAtTipValidity failed: %s", __func__, FormatStateMessage(state))); // TestNewBlockAtTipValidity only supports blocks built on the current Tip if (block.hashPrevBlock != chainActive.Tip()->GetBlockHash()) TestNewBlockAtTipValidity(state, Params(), block, false); if (pindex->pprev->nChainTotalSupply.has_value()) { if (pindex->pprev->nChainTransparentValue.has_value()) { if (!pindex->nChainSproutValue.has_value()) { assert(pindex->nChainSproutValue.value() == chainparams.SproutValuePoolCheckpointBalance()); assert(pindex->nSproutValue.has_value()); // Track the chain pool value pool balances for turnstile enforcement. // // `pindexPrev` is `chainActive.Tip()` (set above), and the active tip is // guaranteed to have populated chain pool values: // // - For Sapling and Orchard, `ConnectBlock` asserts via // `assert(pindex->nChain*Value.has_value())` that these are populated; // the active tip could not have been set otherwise. // - For Sprout, `ConnectBlock` halts with a "reindex required" message // via `AbortNode` if `nChainSproutValue` is missing (which only // happens with legacy block index data written by clients older than // `SPROUT_VALUE_VERSION`); the active tip could not have been // advanced past such a state without the user reindexing first. // // Therefore the assertions below cannot fail in any reachable state. assert(pindexPrev->nChainSproutValue.has_value()); assert(pindexPrev->nChainSaplingValue.has_value()); assert(pindexPrev->nChainOrchardValue.has_value()); sproutValue = pindexPrev->nChainSproutValue.value(); saplingValue = pindexPrev->nChainSaplingValue.value(); orchardValue = pindexPrev->nChainOrchardValue.value(); if (chainparams.ZIP209Enabled()) { return AbortNode( state, strprintf("%s: chain total supply does not match sum of pool balances at height %d (sprout=%d, sapling=%d, orchard=%d, lockbox=%d, transparent=%d, total=%d)", __func__, pindex->nHeight, sprout_supply, sapling_supply, orchard_supply, lockbox_supply, transparent_supply, total_supply), _("The chain total supply does not match the sum of the pool balances. This indicates a fatal problem with the node's pool accounting. " "Please restart zcashd with -reindex.")); const CAmount sapling_supply = pindex->nChainSaplingValue.value(); const CAmount orchard_supply = pindex->nChainOrchardValue.value(); const CAmount lockbox_supply = pindex->nChainLockboxValue.value(); // Reject a block that results in an out-of-range shielded value pool // balance. if (!MoneyRange(pindex->nChainSproutValue.value())) { return state.DoS(100, error("%s: turnstile violation in Sprout shielded value pool at height %d (sprout=%d, sapling=%d, orchard=%d, lockbox=%d)", __func__, pindex->nHeight, pindex->nChainSproutValue.value(), sapling_supply, orchard_supply, lockbox_supply), REJECT_INVALID, "turnstile-violation-sprout-shielded-pool"); if (!MoneyRange(sapling_supply)) { return state.DoS(100, error("%s: turnstile violation in Sapling shielded value pool at height %d (sprout=%d, sapling=%d, orchard=%d, lockbox=%d)", __func__, pindex->nHeight, pindex->nChainSproutValue.value(), sapling_supply, orchard_supply, lockbox_supply), REJECT_INVALID, "turnstile-violation-sapling-shielded-pool"); if (!MoneyRange(orchard_supply)) { return state.DoS(100, error("%s: turnstile violation in Orchard shielded value pool at height %d (sprout=%d, sapling=%d, orchard=%d, lockbox=%d)", __func__, pindex->nHeight, pindex->nChainSproutValue.value(), sapling_supply, orchard_supply, lockbox_supply), REJECT_INVALID, "turnstile-violation-orchard"); // This check is a necessary consensus rule when transaction-defined lockbox // disbursement is present. zcashd will never implement v6 transactions, and // so this check in practice is defending against a protocol specification // error in defining the one-time lockbox disbursement(s). It should not be // conditional on `chainparams.ZIP209Enabled()`. if (!MoneyRange(lockbox_supply)) { return state.DoS(100, error("%s: invalid lockbox disbursement amount at height %d (sprout=%s, sapling=%d, orchard=%d, lockbox=%d)", __func__, pindex->nHeight, pindex->nChainSproutValue.has_value() ? strprintf("%d", pindex->nChainSproutValue.value()) : "nullopt", sapling_supply, orchard_supply, lockbox_supply), REJECT_INVALID, "invalid-lockbox-disbursement-amount"); // Ensure that the total chain supply is consistent with the value in each pool. if (chainparams.ZIP209Enabled()) { // These conditions were checked in the turnstile section above. assert(pindex->nChainSproutValue.has_value()); const CAmount sprout_supply = pindex->nChainSproutValue.value(); assert(MoneyRange(sprout_supply)); assert(MoneyRange(sapling_supply)); assert(MoneyRange(orchard_supply)); assert(MoneyRange(lockbox_supply)); // `nChainTotalSupply` and `nChainTransparentValue` may be unpopulated // if a parent block index entry was written by a zcashd version older // than `TRANSPARENT_VALUE_VERSION` and so lacks `nChainSupplyDelta`. if (pindex->nChainTotalSupply.has_value() && pindex->nChainTransparentValue.has_value()) { const CAmount transparent_supply = pindex->nChainTransparentValue.value(); const CAmount total_supply = pindex->nChainTotalSupply.value(); if (!MoneyRange(transparent_supply)) { return state.DoS(100, error("%s: turnstile violation in transparent value pool at height %d (sprout=%d, sapling=%d, orchard=%d, lockbox=%d, transparent=%d, total=%d)", __func__, pindex->nHeight, sprout_supply, sapling_supply, orchard_supply, lockbox_supply, transparent_supply, total_supply), REJECT_INVALID, "turnstile-violation-transparent"); } if (!MoneyRange(total_supply)) { return state.DoS(100, error("%s: turnstile violation in total supply at height %d (sprout=%d, sapling=%d, orchard=%d, lockbox=%d, transparent=%d, total=%d)", __func__, pindex->nHeight, sprout_supply, sapling_supply, orchard_supply, lockbox_supply, transparent_supply, total_supply), REJECT_INVALID, "turnstile-violation-total"); } static_assert(MAX_MONEY <= std::numeric_limits::max() / 5, "sum of five MoneyRange CAmounts must fit in CAmount"); const CAmount expected_total_supply = transparent_supply + sprout_supply + sapling_supply + orchard_supply + lockbox_supply; if (expected_total_supply != total_supply) { // This may be added as a rule to ZIP 209 and return a failure in a future soft-fork. error("%s: chain total supply (%d) does not match sum of pool balances (%d) at height %d", __func__, total_supply, expected_total_supply, pindex->nHeight); } } else { LogPrintf("%s: skipping chain supply consistency check at height %d because chain supply tracking fields are missing\n", __func__, pindex->nHeight); } } try { nValueIn = view.GetValueIn(tx); } catch (const std::runtime_error& e) { return state.DoS(100, false, REJECT_INVALID, "bad-txns-input-value-out-of-range"); } CAmount nValueOut; try { nValueOut = tx.GetValueOut(); } catch (const std::runtime_error& e) { return state.DoS(100, false, REJECT_INVALID, "bad-txns-output-value-out-of-range"); } try { nValueIn += tx.GetShieldedValueIn(); } catch (const std::runtime_error& e) { return state.DoS(100, false, REJECT_INVALID, "bad-txns-inputvalues-outofrange"); } CAmount nValueOut; try { nValueOut = tx.GetValueOut(); } catch (const std::runtime_error& e) { return state.DoS(100, false, REJECT_INVALID, "bad-txns-outputvalues-outofrange"); } if (nValueIn < nValueOut) strprintf("value in (%s) < value out (%s)", FormatMoney(nValueIn), FormatMoney(nValueOut))); CAmount nTxFee = nValueIn - nValueOut; return state.DoS(100, error("%s: chain supply delta out of range: %d at height %d", __func__, chainSupplyDelta, pindex->nHeight), REJECT_INVALID, "bad-chain-supply-delta-out-of-range"); return state.DoS(100, error("%s: transparent value delta out of range: %d at height %d", __func__, transparentValueDelta, pindex->nHeight), REJECT_INVALID, "bad-transparent-value-delta-out-of-range"); try { chainSupplyDelta += tx.GetValueOut(); } catch (const std::runtime_error& e) { return state.DoS(100, error("%s: coinbase output value out of range at height %d", __func__, pindex->nHeight), REJECT_INVALID, "bad-cb-output-value-out-of-range"); } return state.DoS(100, error("%s: chain supply delta out of range: %d at height %d", __func__, chainSupplyDelta, pindex->nHeight), REJECT_INVALID, "bad-chain-supply-delta-out-of-range"); CAmount txFee; try { txFee = view.GetValueIn(tx) - tx.GetValueOut(); } catch (const std::runtime_error& e) { return state.DoS(100, error("%s: tx value out of range at height %d", __func__, pindex->nHeight), REJECT_INVALID, "bad-txns-value-out-of-range"); } return state.DoS(100, error("%s: transaction fee out of range: %d at height %d", __func__, txFee, pindex->nHeight), REJECT_INVALID, "bad-txns-fee-out-of-range"); return state.DoS(100, error("%s: total fees out of range: %d at height %d", __func__, nFees, pindex->nHeight), REJECT_INVALID, "bad-txns-total-fees-out-of-range"); return state.DoS(100, error("%s: chain supply delta out of range: %d at height %d", __func__, chainSupplyDelta, pindex->nHeight), REJECT_INVALID, "bad-chain-supply-delta-out-of-range"); return state.DoS(100, error("%s: transparent value delta out of range: %d at height %d", __func__, transparentValueDelta, pindex->nHeight), REJECT_INVALID, "bad-transparent-value-delta-out-of-range"); return state.DoS(100, error("%s: previous total supply out of range: %d at height %d", __func__, chainTotalSupply, pindex->nHeight), REJECT_INVALID, "bad-chain-total-supply-out-of-range"); return state.DoS(100, error("%s: new total supply out of range: %d at height %d", __func__, chainTotalSupply, pindex->nHeight), REJECT_INVALID, "bad-chain-total-supply-out-of-range"); return state.DoS(100, error("%s: previous chain transparent value out of range: %d at height %d", __func__, chainTransparentValue, pindex->nHeight), REJECT_INVALID, "bad-chain-transparent-value-out-of-range"); return state.DoS(100, error("%s: new chain transparent value out of range: %d at height %d", __func__, chainTransparentValue, pindex->nHeight), REJECT_INVALID, "bad-chain-transparent-value-out-of-range"); CAmount cbTotalOutputValue; try { cbTotalOutputValue = block.vtx[0].GetValueOut(); } catch (const std::runtime_error& e) { return state.DoS(100, error("%s: coinbase output value out of range at height %d", __func__, pindex->nHeight), REJECT_INVALID, "bad-cb-output-value-out-of-range"); } cbTotalOutputValue += pindex->nLockboxValue; try { chainSupplyDelta = tx.GetValueOut(); } catch (const std::runtime_error& e) { return error("%s: genesis coinbase output value out of range", __func__); } inline bool MoneyDeltaRange(const CAmount& nValue) { return (nValue >= -MAX_MONEY && nValue <= MAX_MONEY); } CAmount nResult = GetTransparentValueIn(tx) + tx.GetShieldedValueIn(); if (!MoneyRange(nResult)) { throw std::runtime_error("CCoinsViewCache::GetValueIn(): nResult out of range"); } return nResult; for (unsigned int i = 0; i < tx.vin.size(); i++) { if (!MoneyRange(nResult)) { throw std::runtime_error("CCoinsViewCache::GetTransparentValueIn(): nResult out of range"); } } extern bool SetChainPoolValues( if (!MoneyDeltaRange(chainSupplyDelta)) { return error("%s: chain supply delta out of range: %d at height %d", __func__, chainSupplyDelta, pindex->nHeight); } if (!MoneyDeltaRange(transparentValueDelta)) { return error("%s: transparent value delta out of range: %d at height %d", __func__, transparentValueDelta, pindex->nHeight); } if (!MoneyDeltaRange(chainSupplyDelta)) { return error("%s: chain supply delta out of range: %d at height %d", __func__, chainSupplyDelta, pindex->nHeight); } if (!MoneyRange(txFee)) { return error("%s: transaction fee out of range: %d at height %d", __func__, txFee, pindex->nHeight); } if (!MoneyRange(nFees)) { return error("%s: total fees out of range: %d at height %d", __func__, nFees, pindex->nHeight); } if (!MoneyDeltaRange(chainSupplyDelta)) { return error("%s: chain supply delta out of range: %d at height %d", __func__, chainSupplyDelta, pindex->nHeight); } if (!MoneyDeltaRange(transparentValueDelta)) { return error("%s: transparent value delta out of range: %d at height %d", __func__, transparentValueDelta, pindex->nHeight); } CAmount chainTotalSupply = pindex->pprev->nChainTotalSupply.value(); if (!MoneyRange(chainTotalSupply)) { return error("%s: previous total supply out of range: %d at height %d", __func__, chainTotalSupply, pindex->nHeight); } chainTotalSupply += chainSupplyDelta; if (!MoneyRange(chainTotalSupply)) { return error("%s: new total supply out of range: %d at height %d", __func__, chainTotalSupply, pindex->nHeight); } pindex->nChainTotalSupply = chainTotalSupply; CAmount chainTransparentValue = pindex->pprev->nChainTransparentValue.value(); if (!MoneyRange(chainTransparentValue)) { return error("%s: previous chain transparent value out of range: %d at height %d", __func__, chainTransparentValue, pindex->nHeight); } chainTransparentValue += transparentValueDelta; if (!MoneyRange(chainTransparentValue)) { return error("%s: new chain transparent value out of range: %d at height %d", __func__, chainTransparentValue, pindex->nHeight); } pindex->nChainTransparentValue = chainTransparentValue; if (!MoneyRange(cbTotalOutputValue)) { return state.DoS(100, error("%s: coinbase output value out of range at height %d", __func__, pindex->nHeight), REJECT_INVALID, "bad-cb-output-value-out-of-range"); } if (!MoneyRange(cbTotalInputValue)) { return state.DoS(100, error("%s: coinbase input value out of range at height %d", __func__, pindex->nHeight), REJECT_INVALID, "bad-cb-input-value-out-of-range"); } if (!MoneyRange(pindex->nChainTotalSupply.value()) || !MoneyRange(pindex->nChainTransparentValue.value()) || !MoneyRange(pindex->nChainSproutValue.value()) || !MoneyRange(pindex->nChainSaplingValue.value()) || !MoneyRange(pindex->nChainOrchardValue.value()) || !MoneyRange(pindex->nChainLockboxValue.value())) { return state.DoS(100, error("%s: chain accounting value out of range at height %d", __func__, pindex->nHeight), REJECT_INVALID, "bad-chain-supply-out-of-range"); } // // Returns false if the block's aggregate per-pool value deltas overflow the // valid monetary range at any step of the accumulation. bool SetChainPoolValues( saplingValue -= tx.GetValueBalanceSapling(); if (!MoneyDeltaRange(saplingValue)) { return error("%s: sapling value delta out of range: %d at height %d", __func__, saplingValue, pindex->nHeight); } orchardValue -= tx.GetOrchardBundle().GetValueBalance(); if (!MoneyDeltaRange(orchardValue)) { return error("%s: orchard value delta out of range: %d at height %d", __func__, orchardValue, pindex->nHeight); } if (!MoneyDeltaRange(sproutValue)) { return error("%s: sprout value delta out of range: %d at height %d", __func__, sproutValue, pindex->nHeight); } if (!MoneyDeltaRange(sproutValue)) { return error("%s: sprout value delta out of range: %d at height %d", __func__, sproutValue, pindex->nHeight); } return true; if (!SetChainPoolValues(chainparams, block, pindexNew)) { return error("ReceivedBlockTransactions(): SetChainPoolValues failed"); } // Calculate the block's effect on the Sapling chain value pool balance. if (pindex->pprev->nChainSproutValue.has_value() && pindex->nSproutValue.has_value()) { CAmount chainSproutValue = pindex->pprev->nChainSproutValue.value(); if (!MoneyRange(chainSproutValue) || !MoneyDeltaRange(pindex->nSproutValue.value())) { return error("%s: previous sprout pool value out of range at height %d", __func__, pindex->nHeight); } pindex->nChainSproutValue = chainSproutValue + pindex->nSproutValue.value(); if (pindex->pprev->nChainSaplingValue.has_value()) { CAmount chainSaplingValue = pindex->pprev->nChainSaplingValue.value(); if (!MoneyRange(chainSaplingValue) || !MoneyDeltaRange(pindex->nSaplingValue)) { return error("%s: previous sapling pool value out of range at height %d", __func__, pindex->nHeight); } pindex->nChainSaplingValue = chainSaplingValue + pindex->nSaplingValue; if (pindex->pprev->nChainOrchardValue.has_value()) { CAmount chainOrchardValue = pindex->pprev->nChainOrchardValue.value(); if (!MoneyRange(chainOrchardValue) || !MoneyDeltaRange(pindex->nOrchardValue)) { return error("%s: previous orchard pool value out of range at height %d", __func__, pindex->nHeight); } pindex->nChainOrchardValue = chainOrchardValue + pindex->nOrchardValue; if (pindex->pprev->nChainLockboxValue.has_value()) { CAmount chainLockboxValue = pindex->pprev->nChainLockboxValue.value(); if (!MoneyRange(chainLockboxValue) || !MoneyDeltaRange(pindex->nLockboxValue)) { return error("%s: previous lockbox pool value out of range at height %d", __func__, pindex->nHeight); } pindex->nChainLockboxValue = chainLockboxValue + pindex->nLockboxValue; if (!SetChainPoolValues(chainparams, block, &indexDummy)) { return false; } // Pre-addition range checks to prevent signed integer // overflow (UB). On-disk per-block deltas could be // corrupted, so we cannot assume they are in range. if (pindex->pprev->nChainTotalSupply.has_value() && pindex->nChainSupplyDelta.has_value()) { CAmount chainTotalSupply = pindex->pprev->nChainTotalSupply.value(); if (!MoneyRange(chainTotalSupply) || !MoneyDeltaRange(pindex->nChainSupplyDelta.value())) { return error("%s: previous total supply value out of range at height %d", __func__, pindex->nHeight); } chainTotalSupply += pindex->nChainSupplyDelta.value(); if (!MoneyRange(chainTotalSupply)) { return error("%s: new total supply value out of range at height %d", __func__, pindex->nHeight); } pindex->nChainTotalSupply = chainTotalSupply; if (pindex->pprev->nChainTransparentValue.has_value() && pindex->nTransparentValue.has_value()) { CAmount chainTransparentValue = pindex->pprev->nChainTransparentValue.value(); if (!MoneyRange(chainTransparentValue) || !MoneyDeltaRange(pindex->nTransparentValue.value())) { return error("%s: previous transparent value out of range at height %d", __func__, pindex->nHeight); } chainTransparentValue += pindex->nTransparentValue.value(); if (!MoneyRange(chainTransparentValue)) { return error("%s: new transparent value out of range at height %d", __func__, pindex->nHeight); } pindex->nChainTransparentValue = chainTransparentValue; if (pindex->pprev->nChainSproutValue.has_value() && pindex->nSproutValue.has_value()) { CAmount chainSproutValue = pindex->pprev->nChainSproutValue.value(); if (!MoneyRange(chainSproutValue) || !MoneyDeltaRange(pindex->nSproutValue.value())) { return error("%s: previous sprout value out of range at height %d", __func__, pindex->nHeight); } chainSproutValue += pindex->nSproutValue.value(); if (!MoneyRange(chainSproutValue)) { return error("%s: new sprout value out of range at height %d", __func__, pindex->nHeight); } pindex->nChainSproutValue = chainSproutValue; if (pindex->pprev->nChainSaplingValue.has_value()) { CAmount chainSaplingValue = pindex->pprev->nChainSaplingValue.value(); if (!MoneyRange(chainSaplingValue) || !MoneyDeltaRange(pindex->nSaplingValue)) { return error("%s: previous sapling value out of range at height %d", __func__, pindex->nHeight); } chainSaplingValue += pindex->nSaplingValue; if (!MoneyRange(chainSaplingValue)) { return error("%s: new sapling value out of range at height %d", __func__, pindex->nHeight); } pindex->nChainSaplingValue = chainSaplingValue; if (pindex->pprev->nChainOrchardValue.has_value()) { CAmount chainOrchardValue = pindex->pprev->nChainOrchardValue.value(); if (!MoneyRange(chainOrchardValue) || !MoneyDeltaRange(pindex->nOrchardValue)) { return error("%s: previous orchard value out of range at height %d", __func__, pindex->nHeight); } chainOrchardValue += pindex->nOrchardValue; if (!MoneyRange(chainOrchardValue)) { return error("%s: new orchard value out of range at height %d", __func__, pindex->nHeight); } pindex->nChainOrchardValue = chainOrchardValue; if (pindex->pprev->nChainLockboxValue.has_value()) { CAmount chainLockboxValue = pindex->pprev->nChainLockboxValue.value(); if (!MoneyRange(chainLockboxValue) || !MoneyDeltaRange(pindex->nLockboxValue)) { return error("%s: previous lockbox value out of range at height %d", __func__, pindex->nHeight); } chainLockboxValue += pindex->nLockboxValue; if (!MoneyRange(chainLockboxValue)) { return error("%s: new lockbox value out of range at height %d", __func__, pindex->nHeight); } pindex->nChainLockboxValue = chainLockboxValue; if (!MoneyDeltaRange(valueBalanceSapling)) { if (!MoneyDeltaRange(valueBalanceOrchard)) { #include "util/strencodings.h" AlertNotify(const std::string& strMessage, bool fThread) // To be safe we first strip anything not in safeChars, then add single quotes around void AlertNotify(const std::string& strMessage, bool fThread); AlertNotify(msg, fThread); AlertNotify(msg, fThread); strUsage += HelpMessageOpt("-alertnotify=", _("Execute command on node end-of-service or when we see a really long fork (%s in cmd is replaced by message)")); AlertNotify(warning, true); AlertNotify(warning, true); // TODO: If NU6.1 active, get the set of expected one-time lockbox disbursements, // and ensure that the coinbase transaction contains them. // Apply the input-side effect of lockbox disbursement: // - Subtract any one-time disbursements from the chain supply (to cancel // out their re-addition by the coinbase tx outputs below). // TODO: Get the set of one-time disbursements to subtract. // Each lockbox disbursement produces a negative change to the lockbox value. // TODO: Subtract any disbursements that apply to pindex->nHeight. These are // hard-coded because we need to be able to calculate lockboxValue once we have // received a full block and knowing its height, but before we've received all // of its ancestors. #define CLIENT_VERSION_BUILD 50 static const int APPROX_RELEASE_HEIGHT = 2892076; #define CLIENT_VERSION_MINOR 2 #define CLIENT_VERSION_BUILD 25 static const int APPROX_RELEASE_HEIGHT = 2884800; std::string Deprecated(bool enabled, std::string method, std::string instead) { auto status = enabled ? "DEPRECATED" : "DISABLED"; auto reenable = enabled ? std::string("") : (std::string("You can restart the node with `-allowdeprecated=") + method + "`\n" "to re-enable this method during its deprecation period.\n"); return std::string("\n") + method + " is " + status + " and will be removed in a future release.\n" + instead + "\n" + reenable + "See https://zcash.github.io/zcash/user/deprecation.html for more information.\n"; } /** * Returns a string to be included in the help text of a deprecated RPC method. */ std::string Deprecated(bool enabled, std::string method, std::string instead); if (!fEnableGetNetworkHashPS || fHelp || params.size() > 2) + Deprecated(fEnableGetNetworkHashPS, "getnetworkhashps", "Please use getnetworksolps instead.") + ); if (!fEnableCreateRawTransaction || fHelp || params.size() < 2 || params.size() > 4) + Deprecated(fEnableCreateRawTransaction, "createrawtransaction", "Zallet will instead provide new RPC methods that operate on PCZTs:\n" "https://github.com/zcash/wallet/issues/99") + if (!fEnableSignRawTransaction || fHelp || params.size() < 1 || params.size() > 5) + Deprecated(fEnableSignRawTransaction, "signrawtransaction", "Zallet will instead provide new RPC methods that operate on PCZTs:\n" "https://github.com/zcash/wallet/issues/99") + if (!pwalletMain) { if (!avoidException) { throw JSONRPCError( RPC_METHOD_NOT_FOUND, #if ENABLE_WALLET "This wallet method is disabled because the `disablewallet` flag was used." #else "This wallet method is disabled because the node was not built with wallet support." #endif ); } else { } if (!fEnableGetNewAddress || fHelp || params.size() > 1) + Deprecated(fEnableGetNewAddress, "getnewaddress", "Please use z_getnewaccount and z_getaddressforaccount instead.") + if (!fEnableGetRawChangeAddress || fHelp || params.size() > 1) + Deprecated(fEnableGetRawChangeAddress, "getrawchangeaddress", "Change addresses are a wallet-internal feature. Use a unified address\n" "for a dedicated change account instead.") + ); if (!fEnableKeyPoolRefill || fHelp || params.size() > 1) + Deprecated(fEnableKeyPoolRefill, "keypoolrefill", "It will not be needed for Zallet.") + if (!fEnableSetTxFee || fHelp || params.size() < 1 || params.size() > 1) + Deprecated(fEnableSetTxFee, "settxfee", "It is strongly recommended to use the default ZIP 317 fee, which is not\n" "expressible using settxfee.") + if (!fEnableFundRawTransaction || fHelp || params.size() < 1 || params.size() > 2) + Deprecated(fEnableFundRawTransaction, "fundrawtransaction", "Zallet will instead provide new RPC methods that operate on PCZTs:\n" "https://github.com/zcash/wallet/issues/99") + if (!fEnableZGetNewAddress || fHelp || params.size() > 1) + Deprecated(fEnableZGetNewAddress, "z_getnewaddress", "Please use z_getnewaccount and z_getaddressforaccount instead.") + "\nWith no arguments, this currently returns a Sapling address (but that\n" "should not be relied on).\n" if (!fEnableZListAddresses || fHelp || params.size() > 1) + Deprecated(fEnableZListAddresses, "z_listaddresses", "Please use `listaddresses` instead.") + if (!fEnableZGetBalance || fHelp || params.size() == 0 || params.size() > 3) + Deprecated(fEnableZGetBalance, "z_getbalance", "Please use z_getbalanceforaccount, z_getbalanceforviewingkey, or getbalance (for legacy\n" "transparent balance) instead.") + if (!fEnableZGetTotalBalance || fHelp || params.size() > 2) + Deprecated(fEnableZGetTotalBalance, "z_gettotalbalance", "Please use z_getbalanceforaccount, or getbalance (for legacy transparent balance) instead.") + "to re-enable this method during its deprecation period.\n" "\nZallet will instead provide new RPC methods that work on PCZTs:\n" "Restart with `-allowdeprecated=createrawtransaction` to re-enable this method\n" "during its deprecation period.\n" "Restart with `-allowdeprecated=createrawtransaction` to re-enable this method\n" "during its deprecation period.\n" "with `-allowdeprecated=getnewaddress` to re-enable this method during\n" "its deprecation period.\n" "a dedicated change account instead, or restart with `-allowdeprecated=getrawchangeaddress`\n" "to re-enable this method during its deprecation period.\n" "to re-enable this method during its deprecation period.\n" "expressible using settxfee. Restart with `-allowdeprecated=settxfee` to\n" "re-enable this method during its deprecation period.\n" "\nZallet will instead provide new RPC methods that work on PCZTs:\n" "Restart with `-allowdeprecated=createrawtransaction` to re-enable this method\n" "during its deprecation period.\n" "with `-allowdeprecated=z_getnewaddress` to re-enable this method during\n" "its deprecation period.\n" "to re-enable this method during its deprecation period.\n" "to re-enable this method during its deprecation period.\n" "\nUse z_getbalanceforaccount, or getbalance (for legacy transparent balance) instead,\n" "or restart with `-allowdeprecated=z_gettotalbalance` to re-enable this method during\n" "its deprecation period.\n" "z_gettotalbalance", "gbt_oldhashes", "deprecationinfo_deprecationheight", "addrtype", "z_getbalance", "legacy_privacy", "\nGenerate a payment disclosure for a given joinsplit output. This only supports Sprout.\n" "\nEXPERIMENTAL, DEPRECATED FEATURE\n" "\nValidates a payment disclosure. This only supports Sprout.\n" "\nEXPERIMENTAL, DEPRECATED FEATURE\n" if (!fEnableGetNewAddress) { "getnewaddress is DEPRECATED and will be removed in a future release.\n" "\nUse z_getnewaccount and z_getaddressforaccount instead, or restart\n" } if (!fEnableGetRawChangeAddress) { "getrawchangeaddress is DEPRECATED and will be removed in a future release.\n" } if (!fEnableZGetNewAddress) { "z_getnewaddress is DEPRECATED and will be removed in a future release.\n" "\nUse z_getnewaccount and z_getaddressforaccount instead, or restart\n" } if (!fEnableZListAddresses) { "z_listaddresses is DEPRECATED and will be removed in a future release.\n" } if (!fEnableZGetBalance) { "z_getbalance is DEPRECATED and will be removed in a future release.\n" "\nUse z_getbalanceforaccount, z_getbalanceforviewingkey, or getbalance (for\n" } if (!fEnableZGetTotalBalance) { "z_gettotalbalance is DEPRECATED and will be removed in a future release.\n" "\nUse z_getbalanceforaccount, or getbalance (for legacy transparent balance) instead, or\n" } bool fEnableGetNetworkHashPS = true; bool fEnableCreateRawTransaction = true; bool fEnableSignRawTransaction = true; bool fEnableFundRawTransaction = true; bool fEnableKeyPoolRefill = true; bool fEnableSetTxFee = true; "createrawtransaction", "signrawtransaction", "getnetworkhashps", "fundrawtransaction", "keypoolrefill", "settxfee", extern bool fEnableGetNetworkHashPS; extern bool fEnableCreateRawTransaction; extern bool fEnableSignRawTransaction; extern bool fEnableFundRawTransaction; extern bool fEnableKeyPoolRefill; extern bool fEnableSetTxFee; if (!fEnableGetNetworkHashPS) { throw runtime_error( "getnetworkhashps is DEPRECATED and will be removed in a future release.\n" "\nUse getnetworksolps or restart with `-allowdeprecated=getnetworkhashps`\n" "if you require backward compatibility.\n" "See https://zcash.github.io/zcash/user/deprecation.html for more information."); } if (!fEnableCreateRawTransaction) { throw runtime_error( "createrawtransaction is DEPRECATED and will be removed in a future release.\n" "\nZallet will instead have new RPC methods that work on PCZTs:\n" "https://github.com/zcash/wallet/issues/99\n" "Restart with `-allowdeprecated=createrawtransaction` if you require backward\n" "compatibility.\n" "See https://zcash.github.io/zcash/user/deprecation.html for more information."); } if (!fEnableSignRawTransaction) { throw runtime_error( "signrawtransaction is DEPRECATED and will be removed in a future release.\n" "\nZallet will instead have new RPC methods that work on PCZTs:\n" "https://github.com/zcash/wallet/issues/99\n" "Restart with `-allowdeprecated=createrawtransaction` if you require backward\n" "compatibility.\n" "See https://zcash.github.io/zcash/user/deprecation.html for more information."); } // This is only a helper for tests. if (!fEnableKeyPoolRefill) { throw runtime_error( "keypoolrefill is DEPRECATED and will be removed in a future release.\n" "\nIt will not be needed for Zallet. Restart with `-allowdeprecated=keypoolrefill`\n" "if you require backward compatibility.\n" "See https://zcash.github.io/zcash/user/deprecation.html for more information."); } if (!fEnableSetTxFee) { throw runtime_error( "settxfee is DEPRECATED and will be removed in a future release.\n" "\nIt is strongly recommended to use the default ZIP 317 fee, which is not\n" "expressible using settxfee. Restart with `-allowdeprecated=settxfee` if you\n" "require backward compatibility.\n" "See https://zcash.github.io/zcash/user/deprecation.html for more information."); } if (!fEnableFundRawTransaction) { throw runtime_error( "fundrawtransaction is DEPRECATED and will be removed in a future release.\n" "\nZallet will instead have new RPC methods that work on PCZTs:\n" "https://github.com/zcash/wallet/issues/99\n" "Restart with `-allowdeprecated=createrawtransaction` if you require backward\n" "compatibility.\n" "See https://zcash.github.io/zcash/user/deprecation.html for more information."); } // Set the clock to the timestamp of the last "mined" block, to ensure we satisfy the // future timestamp soft fork rule. We use a fixed clock here because the time should // not advance from `nTime` for the calls to `CreateNewBlock`. // Set the clock back to the timestamp of the last "mined" block (and allow it to advance // from that point), to ensure we satisfy both the rule that it is after the MTP, and the // future timestamp soft fork rule. unsigned int chRejectCodeIn, const std::string &strRejectReasonIn, // The following indexed access is safe as Consensus::MAX_FUNDING_STREAMS is used // in the definition of vFundingStreams. // Funding period is [startHeight, endHeight). for (const auto& [fsinfo, fs] : GetActiveFundingStreams(nHeight)) { requiredElements.insert(std::make_pair( fs.Recipient(*this, nHeight), fsinfo.Value(blockSubsidy))); const auto& consensus = chainparams.GetConsensus(); const auto block_subsidy = consensus.GetBlockSubsidy(nHeight); for (const auto& [fsinfo, fs] : consensus.GetActiveFundingStreams(nHeight)) { const auto amount = fsinfo.Value(block_subsidy); miner_reward -= amount; examine(fs.Recipient(consensus, nHeight), match { LogPrint("pow", "%s: Adding Sapling funding stream output of value %d", __func__, amount); amount, LogPrint("pow", "%s: Adding transparent funding stream output of value %d", __func__, amount); mtx.vout.emplace_back(amount, scriptPubKey); LogPrint("pow", "%s: Noting lockbox output of value %d", __func__, amount); const auto vFoundersReward = miner_reward / 5; return FundingStreamError::INSUFFICIENT_RECIPIENTS; case FundingStreamError::INSUFFICIENT_RECIPIENTS: throw std::runtime_error("Insufficient recipient identifiers to fully exhaust funding stream."); INSUFFICIENT_RECIPIENTS, // The timestamp of a given block template should not go backwards. // Setting nTime to 0 and then calling UpdateTime ensures that it is set to the // nearest timestamp to the current time in the consensus-valid range (see #6960). pblock->nTime = 0; UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev); auto nTime = pblocktemplate->block.nTime; delete pblocktemplate; FixedClock::SetGlobal(); FixedClock::Instance()->Set(std::chrono::seconds(nTime)); // Just to make sure we can still make simple blocks BOOST_CHECK(pblocktemplate = BlockAssembler(chainparams).CreateNewBlock(scriptPubKey)); BOOST_CHECK_EQUAL(pblocktemplate->block.nTime, nTime); auto mtp = chainActive.Tip()->GetMedianTimePast(); auto minTime = mtp + 1; auto maxTime = mtp + MAX_FUTURE_BLOCK_TIME_MTP; // Set the clock to be too far ahead of the MTP, violating the future timestamp rule. FixedClock::Instance()->Set(std::chrono::seconds(maxTime + 1)); // This should succeed, and nTime should be clamped to the maximum consensus-valid value. BOOST_CHECK(pblocktemplate = BlockAssembler(chainparams).CreateNewBlock(scriptPubKey)); BOOST_CHECK_EQUAL(pblocktemplate->block.nTime, maxTime); delete pblocktemplate; // Set the clock to be equal to the median-time-past, violating the rule that it must // be after the MTP. FixedClock::Instance()->Set(std::chrono::seconds(minTime - 1)); // This should succeed, and nTime should be clamped to the minimum consensus-valid value. BOOST_CHECK_EQUAL(pblocktemplate->block.nTime, minTime); auto curTime = GetTime(); OffsetClock::SetGlobal(); OffsetClock::Instance()->Set(std::chrono::seconds(-curTime + nTime)); consensus.vUpgrades[Consensus::UPGRADE_NU6].nActivationHeight = 2726400; auto canopyActivation = consensus.vUpgrades[Consensus::UPGRADE_CANOPY].nActivationHeight; auto nu6Activation = consensus.vUpgrades[Consensus::UPGRADE_NU6].nActivationHeight; // ZIP 214 Revision 0 canopyActivation, nu6Activation, canopyActivation, nu6Activation, canopyActivation, nu6Activation, // ZIP 214 Revision 1 // FPF uses a single address repeated 12 times, once for each funding period. std::vector fpf_addresses(12, "t3cFfPt1Bcvgez9ZbMBFWeZsskxTkPzGCow"); consensus.AddZIP207FundingStream( keyConstants, Consensus::FS_FPF_ZCG, nu6Activation, 3146400, fpf_addresses); consensus.AddZIP207LockboxStream( keyConstants, Consensus::FS_DEFERRED, nu6Activation, 3146400); auto canopyActivation = consensus.vUpgrades[Consensus::UPGRADE_CANOPY].nActivationHeight; auto nu6Activation = consensus.vUpgrades[Consensus::UPGRADE_NU6].nActivationHeight; // ZIP 214 Revision 0 canopyActivation, 2796000, // *not* the NU6 activation height canopyActivation, 2796000, // *not* the NU6 activation height canopyActivation, 2796000, // *not* the NU6 activation height // ZIP 214 Revision 1 // FPF uses a single address repeated 13 times, once for each funding period. // There are 13 periods because the start height does not align with a period boundary. std::vector fpf_addresses(13, "t2HifwjUj9uyxr9bknR8LFuQbc98c3vkXtu"); fpf_addresses); static const int PROTOCOL_VERSION = 170120; #include // The amount chosen includes the fee for this transaction, as it will be after // adding the Sapling output. The first JoinSplit will consume two real inputs and // each subsequent JoinSplit will consume one real input, usually (it is possible // for the builder to use fewer JoinSplits but this only results in overestimating // the fee). The number of Sapling outputs will be padded to 2. auto fee = CalculateConventionalFee(2 * fromNotes.size() + 2); builder.SetFee(fee); amountToSend - fee, amountMigrated += amountToSend - fee; return state.DoS(0, false, REJECT_INSUFFICIENTFEE, strprintf("tx unpaid action limit exceeded: %d action(s) exceeds limit of %d", nUnpaidActionCount, nTxUnpaidActionLimit)); static const size_t DEFAULT_BLOCK_UNPAID_ACTION_LIMIT = 0; std::vector bp_addresses = { bp_addresses); std::vector bp_addresses = { bp_addresses); //! nTime field added to CAddress, starting with this version. //! This can't be removed because it affects the encoding of the //! `addrFrom` field in a "version" message. // Consensus::FS_FPF_ZCG, // Consensus::FS_DEFERRED, FS_FPF_ZCG, FS_DEFERRED, CAmount nFeeRequired = -1; int nChangePosRet = -1; // never used if (!fSubtractFeeFromAmount && nFeeRequired >= 0 && nValue + nFeeRequired > curBalance) { CAmount nFeeRequired = -1; // never used int nChangePosRet = -1; // never used CAmount nFee = -1; extern void EnsureUnreferencedAsKeyOfMapBlocksUnlinked( const CBlockIndex *pindex); // Ensure that the fake CBlockIndex objects aren't still referenced by mapBlocksUnlinked. // (In practice, we only have &fakeIndex1 as a key pointing to &fakeIndex2 after the // first call to ReceivedBlockTransactions, which is removed by the second call.) EnsureUnreferencedAsKeyOfMapBlocksUnlinked(&fakeIndex1); EnsureUnreferencedAsKeyOfMapBlocksUnlinked(&fakeIndex2); // This should not be used outside tests. void EnsureUnreferencedAsKeyOfMapBlocksUnlinked(const CBlockIndex *pindex) { LOCK(cs_main); assert(mapBlocksUnlinked.erase(const_cast(pindex)) == 0); } { // Taking cs_main is required even when working on a fake index. LOCK(cs_main); SetChainPoolValues(chainParams, block2, &fakeIndex2); EXPECT_TRUE(ReceivedBlockTransactions(block2, state, chainParams, &fakeIndex2, pos2)); } { // Taking cs_main is required even when working on a fake index. LOCK(cs_main); SetChainPoolValues(chainParams, block1, &fakeIndex1); EXPECT_TRUE(ReceivedBlockTransactions(block1, state, chainParams, &fakeIndex1, pos1)); } /** * Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS). * The caller is expected to mark `pindexNew` as dirty by adding it to `setDirtyBlockIndex`. */ if (dbp == NULL) { if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart())) { } } setDirtyBlockIndex.insert(pindex); if (!ReceivedBlockTransactions(block, state, chainparams, pindex, blockPos)) { } setDirtyBlockIndex.insert(pindex); if (!ReceivedBlockTransactions(block, state, chainparams, pindex, blockPos)) { } // Sapling pool values should not be set { SCOPED_TRACE("ExpectAmount"); ExpectAmount(0, fakeIndex1.nSaplingValue); } EXPECT_FALSE(fakeIndex1.nChainSaplingValue.has_value()); { SCOPED_TRACE("ExpectAmount"); ExpectAmount(0, fakeIndex2.nSaplingValue); } EXPECT_FALSE(fakeIndex2.nChainSaplingValue.has_value()); // Orchard pool values should not be set { SCOPED_TRACE("ExpectAmount"); ExpectAmount(0, fakeIndex1.nOrchardValue); } EXPECT_FALSE(fakeIndex1.nChainOrchardValue.has_value()); { SCOPED_TRACE("ExpectAmount"); ExpectAmount(0, fakeIndex2.nOrchardValue); } EXPECT_FALSE(fakeIndex2.nChainOrchardValue.has_value()); // Lockbox pool values should not be set { SCOPED_TRACE("ExpectAmount"); ExpectAmount(0, fakeIndex1.nLockboxValue); } EXPECT_FALSE(fakeIndex1.nChainLockboxValue.has_value()); { SCOPED_TRACE("ExpectAmount"); ExpectAmount(0, fakeIndex2.nLockboxValue); } EXPECT_FALSE(fakeIndex2.nChainLockboxValue.has_value()); // Same for Sapling (TODO: make these nonzero) { SCOPED_TRACE("ExpectAmount"); ExpectAmount(0, fakeIndex1.nSaplingValue); } EXPECT_FALSE(fakeIndex1.nChainSaplingValue.has_value()); { SCOPED_TRACE("ExpectAmount"); ExpectAmount(0, fakeIndex2.nSaplingValue); } EXPECT_FALSE(fakeIndex2.nChainSaplingValue.has_value()); // Same for Orchard (TODO: make these nonzero) { SCOPED_TRACE("ExpectAmount"); ExpectAmount(0, fakeIndex1.nOrchardValue); } EXPECT_FALSE(fakeIndex1.nChainOrchardValue.has_value()); { SCOPED_TRACE("ExpectAmount"); ExpectAmount(0, fakeIndex2.nOrchardValue); } EXPECT_FALSE(fakeIndex2.nChainOrchardValue.has_value()); // Same for the lockbox (TODO: make these nonzero) { SCOPED_TRACE("ExpectAmount"); ExpectAmount(0, fakeIndex1.nLockboxValue); } EXPECT_FALSE(fakeIndex1.nChainLockboxValue.has_value()); { SCOPED_TRACE("ExpectAmount"); ExpectAmount(0, fakeIndex2.nLockboxValue); } EXPECT_FALSE(fakeIndex2.nChainLockboxValue.has_value()); // Sapling pool values should now be set for both blocks (TODO: make these nonzero) { SCOPED_TRACE("ExpectAmount"); ExpectAmount(0, fakeIndex1.nSaplingValue); } { SCOPED_TRACE("ExpectAmount"); ExpectAmount(0, fakeIndex1.nChainSaplingValue); } { SCOPED_TRACE("ExpectAmount"); ExpectAmount(0, fakeIndex2.nSaplingValue); } { SCOPED_TRACE("ExpectAmount"); ExpectAmount(0, fakeIndex2.nChainSaplingValue); } // Orchard pool values should now be set for both blocks (TODO: make these nonzero) { SCOPED_TRACE("ExpectAmount"); ExpectAmount(0, fakeIndex1.nOrchardValue); } { SCOPED_TRACE("ExpectAmount"); ExpectAmount(0, fakeIndex1.nChainOrchardValue); } { SCOPED_TRACE("ExpectAmount"); ExpectAmount(0, fakeIndex2.nOrchardValue); } { SCOPED_TRACE("ExpectAmount"); ExpectAmount(0, fakeIndex2.nChainOrchardValue); } // Lockbox pool values should now be set for both blocks (TODO: make these nonzero) { SCOPED_TRACE("ExpectAmount"); ExpectAmount(0, fakeIndex1.nLockboxValue); } { SCOPED_TRACE("ExpectAmount"); ExpectAmount(0, fakeIndex1.nChainLockboxValue); } { SCOPED_TRACE("ExpectAmount"); ExpectAmount(0, fakeIndex2.nLockboxValue); } { SCOPED_TRACE("ExpectAmount"); ExpectAmount(0, fakeIndex2.nChainLockboxValue); } void ExpectAmount(CAmount expected, std::optional actual) { EXPECT_EQ(std::make_optional(expected), actual); const auto chainParams = Params(); const auto sk = libzcash::SproutSpendingKey::random(); EXPECT_FALSE(fakeIndex1.nSproutValue.has_value()); EXPECT_FALSE(fakeIndex1.nChainSproutValue.has_value()); EXPECT_FALSE(fakeIndex2.nSproutValue.has_value()); EXPECT_FALSE(fakeIndex2.nChainSproutValue.has_value()); EXPECT_FALSE(fakeIndex1.nSproutValue.has_value()); EXPECT_FALSE(fakeIndex1.nChainSproutValue.has_value()); { SCOPED_TRACE("ExpectAmount"); ExpectAmount(20, fakeIndex2.nSproutValue); } EXPECT_FALSE(fakeIndex2.nChainSproutValue.has_value()); { SCOPED_TRACE("ExpectAmount"); ExpectAmount(10, fakeIndex1.nSproutValue); } { SCOPED_TRACE("ExpectAmount"); ExpectAmount(10, fakeIndex1.nChainSproutValue); } { SCOPED_TRACE("ExpectAmount"); ExpectAmount(20, fakeIndex2.nSproutValue); } { SCOPED_TRACE("ExpectAmount"); ExpectAmount(30, fakeIndex2.nChainSproutValue); } // Also test with the last three upgrades. // If this changes, remember to update RegtestDeactivate* at the end of the test. const Consensus::UpgradeIndex lastUpgrade = Consensus::UPGRADE_NU6; static_assert(lastUpgrade > Consensus::UPGRADE_OVERWINTER + 2); // in-range and not redundant UpdateNetworkUpgradeParameters(Consensus::UpgradeIndex(lastUpgrade - 2), 40); UpdateNetworkUpgradeParameters(Consensus::UpgradeIndex(lastUpgrade - 1), 50); UpdateNetworkUpgradeParameters(lastUpgrade, 60); auto antepenultimateBranchId = NetworkUpgradeInfo[lastUpgrade - 2].nBranchId; auto penultimateBranchId = NetworkUpgradeInfo[lastUpgrade - 1].nBranchId; auto lastBranchId = NetworkUpgradeInfo[lastUpgrade].nBranchId; { ValidationFakeCoinsViewDB fakeDB(blockHash, utxo.hash, txOut, 12); CCoinsViewCache view(&fakeDB); // Create a transparent transaction that spends the coin, targeting // a height during the Overwinter epoch. auto builder = TransactionBuilder(params, 15, std::nullopt, SaplingMerkleTree::empty_root(), &keystore); builder.AddTransparentInput(utxo, scriptPubKey, coinValue); builder.AddTransparentOutput(destination, 4000); auto tx = builder.Build().GetTxOrThrow(); ASSERT_FALSE(tx.IsCoinBase()); // Ensure that the inputs validate against Overwinter. CValidationState state; PrecomputedTransactionData txdata(tx, {CTxOut(coinValue, scriptPubKey)}); EXPECT_TRUE(ContextualCheckInputs( tx, state, view, true, 0, false, txdata, consensusParams, overwinterBranchId)); // Attempt to validate the inputs against Sapling. We should be notified // that an old consensus branch ID was used for an input. MockCValidationState mockState; EXPECT_CALL(mockState, DoS( 10, false, REJECT_INVALID, strprintf("old-consensus-branch-id (Expected %s, found %s)", HexInt(saplingBranchId), HexInt(overwinterBranchId)), false, "")).Times(1); EXPECT_FALSE(ContextualCheckInputs( tx, mockState, view, true, 0, false, txdata, consensusParams, saplingBranchId)); // Attempt to validate the inputs against Blossom. All we should learn is // that the signature is invalid, because we don't check more than one // network upgrade back. EXPECT_CALL(mockState, DoS( 100, false, REJECT_INVALID, "mandatory-script-verify-flag-failed (Script evaluated without error but finished with a false/empty top stack element)", false, "")).Times(1); EXPECT_FALSE(ContextualCheckInputs( tx, mockState, view, true, 0, false, txdata, consensusParams, blossomBranchId)); } // Check that we didn't break this by repeating for the last three upgrades. { ValidationFakeCoinsViewDB fakeDB(blockHash, utxo.hash, txOut, 42); CCoinsViewCache view(&fakeDB); // Create a transparent transaction that spends the coin, targeting // a height during the antepenultimate epoch. auto builder = TransactionBuilder(params, 45, std::nullopt, SaplingMerkleTree::empty_root(), &keystore); builder.AddTransparentInput(utxo, scriptPubKey, coinValue); builder.AddTransparentOutput(destination, 4000); auto tx = builder.Build().GetTxOrThrow(); ASSERT_FALSE(tx.IsCoinBase()); // Ensure that the inputs validate against the antepenultimate epoch. CValidationState state; PrecomputedTransactionData txdata(tx, {CTxOut(coinValue, scriptPubKey)}); EXPECT_TRUE(ContextualCheckInputs( tx, state, view, true, 0, false, txdata, consensusParams, antepenultimateBranchId)); // Attempt to validate the inputs against the penultimate epoch. // We should be notified that an old consensus branch ID was used for an input. MockCValidationState mockState; EXPECT_CALL(mockState, DoS( 10, false, REJECT_INVALID, strprintf("old-consensus-branch-id (Expected %s, found %s)", HexInt(penultimateBranchId), HexInt(antepenultimateBranchId)), false, "")).Times(1); EXPECT_FALSE(ContextualCheckInputs( tx, mockState, view, true, 0, false, txdata, consensusParams, penultimateBranchId)); // Attempt to validate the inputs against the last epoch. All we should learn // is that the signature is invalid, because we don't check more than one // network upgrade back. EXPECT_CALL(mockState, DoS( 100, false, REJECT_INVALID, "mandatory-script-verify-flag-failed (Script evaluated without error but finished with a false/empty top stack element)", false, "")).Times(1); EXPECT_FALSE(ContextualCheckInputs( tx, mockState, view, true, 0, false, txdata, consensusParams, lastBranchId)); } RegtestDeactivateNU6(); RegtestDeactivateNU5(); RegtestDeactivateCanopy(); CAmount cbTotalOutputValue = block.vtx[0].GetValueOut() + pindex->nLockboxValue; CAmount cbTotalInputValue = consensusParams.GetBlockSubsidy(pindex->nHeight) + nFees; if (cbTotalOutputValue > cbTotalInputValue) { error("ConnectBlock(): coinbase pays too much (actual=%d vs limit=%d)", cbTotalOutputValue - pindex->nLockboxValue, cbTotalInputValue - pindex->nLockboxValue), REJECT_INVALID, "bad-cb-amount"); } else if ( consensusParams.NetworkUpgradeActive(pindex->nHeight, Consensus::UPGRADE_NU6) && cbTotalOutputValue != cbTotalInputValue ) { return state.DoS(100, error("ConnectBlock(): coinbase pays the wrong amount (actual=%d vs expected=%d)", cbTotalOutputValue - pindex->nLockboxValue, cbTotalInputValue - pindex->nLockboxValue), REJECT_INVALID, "bad-cb-not-exact"); } typedef int64_t NodeId; LOCK(cs_main); CNodeState* state = State(pfrom->GetId()); assert(state != nullptr); if (state->fCurrentlyConnected) { pfrom->PushMessage("reject", strCommand, REJECT_DUPLICATE, std::string("Duplicate verack message")); Misbehaving(pfrom->GetId(), 1); return false; } state->fCurrentlyConnected = true; pfrom->PushMessage("reject", strCommand, REJECT_DUPLICATE, std::string("Duplicate version message")); // It's necessary to initialize nVersion because if the message is less than 4 bytes, // it will not be set (but is read in the catch block for std::ios_base::failure). try { uint64_t nServices; vRecv >> nVersion >> nServices >> nTime >> addrMe; if (nVersion < MIN_PEER_PROTO_VERSION) { // disconnect from peers older than this proto version LogPrintf("peer=%d using obsolete version %i; disconnecting\n", pfrom->id, nVersion); pfrom->PushMessage("reject", strCommand, REJECT_OBSOLETE, strprintf("Version must be %d or greater", MIN_PEER_PROTO_VERSION)); pfrom->fDisconnect = true; return false; } if (chainparams.NetworkIDString() == "test" && nVersion < MIN_TESTNET_PEER_PROTO_VERSION) { // disconnect from testnet peers older than this proto version LogPrintf("peer=%d using obsolete version %i; disconnecting\n", pfrom->id, nVersion); pfrom->PushMessage("reject", strCommand, REJECT_OBSOLETE, strprintf("Version must be %d or greater", MIN_TESTNET_PEER_PROTO_VERSION)); pfrom->fDisconnect = true; return false; } // Reject incoming connections from nodes that don't know about the current epoch const Consensus::Params& consensusParams = chainparams.GetConsensus(); auto currentEpoch = CurrentEpoch(GetHeight(), consensusParams); if (nVersion < consensusParams.vUpgrades[currentEpoch].nProtocolVersion && !( chainparams.NetworkIDString() == "regtest" && !GetBoolArg("-nurejectoldversions", DEFAULT_NU_REJECT_OLD_VERSIONS) ) ) { LogPrintf("peer=%d using obsolete version %i; disconnecting\n", pfrom->id, nVersion); pfrom->PushMessage("reject", strCommand, REJECT_OBSOLETE, strprintf("Version must be %d or greater", consensusParams.vUpgrades[currentEpoch].nProtocolVersion)); pfrom->fDisconnect = true; return false; } // We've successfully parsed the mandatory fields and checked the version. // It's safe to leave these set even if subsequent parsing fails. pfrom->nVersion = nVersion; pfrom->nServices = nServices; vRecv >> addrFrom >> nNonce; } if (!vRecv.empty()) { vRecv >> LIMITED_STRING(strSubVer, MAX_SUBVERSION_LENGTH); cleanSubVer = SanitizeString(strSubVer, SAFE_CHARS_SUBVERSION); if (!vRecv.empty()) { int32_t nStartingHeight; vRecv >> nStartingHeight; pfrom->nStartingHeight = nStartingHeight; } { LOCK(pfrom->cs_filter); if (!vRecv.empty()) { vRecv >> pfrom->fRelayTxes; // set to true after we get the first filter* message } else { pfrom->fRelayTxes = true; } } } catch (const std::ios_base::failure&) { LogPrintf("peer=%d using version %i sent malformed version message; disconnecting\n", pfrom->id, nVersion); pfrom->PushMessage("reject", strCommand, REJECT_MALFORMED, std::string("Malformed version message")); pfrom->fDisconnect = true; return false; int32_t nVersion = 0; int64_t nTime = 0; vRecv >> nVersion >> nServices >> nTime >> addrMe; if (nVersion < MIN_PEER_PROTO_VERSION) LogPrintf("peer=%d using obsolete version %i; disconnecting\n", pfrom->id, nVersion); nVersion < MIN_TESTNET_PEER_PROTO_VERSION) LogPrintf("peer=%d using obsolete version %i; disconnecting\n", pfrom->id, nVersion); if (nVersion < consensusParams.vUpgrades[currentEpoch].nProtocolVersion && LogPrintf("peer=%d using obsolete version %i; disconnecting\n", pfrom->id, nVersion); // We've successfully parsed the mandatory fields and checked the version. // It's safe to leave these set even if subsequent parsing fails. pfrom->nVersion = nVersion; pfrom->nServices = nServices; if (!vRecv.empty()) { } int32_t nStartingHeight; if (!vRecv.empty()) { } else { } pfrom->nTimeOffset = timeWarning.AddTimeData(pfrom->addr, nTime, GetTime()); ? "; note that coinbase outputs will not be selected if you specify " "ANY_TADDR, any transparent recipients are included, or if the " "`privacyPolicy` parameter is not set to `AllowRevealedSenders` or weaker" ? ". (This transaction may require selecting transparent coins that were sent " "to multiple addresses, which is not enabled by default because it would " "create a public link between those addresses. THIS MAY AFFECT YOUR PRIVACY. " "Resubmit with the `privacyPolicy` parameter set to " "`AllowLinkingAccountAddresses` or weaker if you wish to allow this " "transaction to proceed anyway.)" + (selector.TransparentCoinbasePolicy() == TransparentCoinbasePolicy::Disallow ? "`privacyPolicy` parameter is not set to `AllowRevealedSenders` or weaker" : "") + (suggestLinkingAddresses ? "transaction to proceed anyway.)" : ".")); std::nullopt); bool suggestLinkingAddresses = !strategy.AllowLinkingAccountAddresses() && examine(selector.GetPattern(), match { [](const libzcash::UnifiedAddress&) { return true; }, [](const AccountZTXOPattern&) { return true; }, [](const auto&) { return false; }, }); + (!suggestLinkingAddresses ? "." : strategy.PermittedAccountSpendingPolicy()).value(); auto selector = pwalletMain->ZTXOSelectorForAddress( addr, true, TransparentCoinbasePolicy::Allow, std::nullopt); strategy.PermittedAccountSpendingPolicy()); strategy.PermittedAccountSpendingPolicy()); strategy.PermittedAccountSpendingPolicy()); strategy.PermittedAccountSpendingPolicy()); std::nullopt).has_value()); TransactionStrategy strategy(PrivacyPolicy::AllowRevealedSenders); strategy.PermittedAccountSpendingPolicy()).value(); TransactionStrategy strategy(PrivacyPolicy::AllowRevealedRecipients); strategy.PermittedAccountSpendingPolicy()).value(); UnifiedAccountSpendingPolicy::ShieldedWithSingleTransparentAddress).value(); std::optional spendingPolicy) const if (spendingPolicy.has_value()) { auto receiverTypes = ua.GetKnownReceiverTypes(); switch (spendingPolicy.value()) { case UnifiedAccountSpendingPolicy::ShieldedWithSingleTransparentAddress: // NB: If we only allow sending from a single transparent receiver, // we check if the UA even has transparent receivers. If so, we // use the UA directly, but if not, we can use the account // without selecting any transparent receivers, and without // worrying that the UA had a transparent receiver that we // should have used. if (receiverTypes.find(ReceiverType::P2SH) != receiverTypes.end() || receiverTypes.find(ReceiverType::P2PKH) != receiverTypes.end()) { pattern = ua; } else { pattern = AccountZTXOPattern(accountId.value(), receiverTypes); } break; case UnifiedAccountSpendingPolicy::ShieldedOnly: receiverTypes.erase(ReceiverType::P2SH); receiverTypes.erase(ReceiverType::P2PKH); [[fallthrough]]; case UnifiedAccountSpendingPolicy::AnyAddresses: pattern = AccountZTXOPattern(accountId.value(), receiverTypes); break; } UnifiedAccountSpendingPolicy TransactionStrategy::PermittedAccountSpendingPolicy() const { if (!AllowRevealedSenders()) return UnifiedAccountSpendingPolicy::ShieldedOnly; if (AllowLinkingAccountAddresses()) return UnifiedAccountSpendingPolicy::AnyAddresses; else return UnifiedAccountSpendingPolicy::ShieldedWithSingleTransparentAddress; } /** * Indicates which addresses can be used when selecting notes to spend from a unified account. */ enum UnifiedAccountSpendingPolicy { /// Can only send from non-transparent receivers in the account. ShieldedOnly, /// Can send from a single transparent address in the account. ShieldedWithSingleTransparentAddress, /// Can send from any combination of receivers in the account. AnyAddresses, }; /** * This lets us know which combinations of notes we can select from a unified account. */ UnifiedAccountSpendingPolicy PermittedAccountSpendingPolicy() const; /// This determines if and how we treat a UA `addr` as a proxy for an account. It should /// be `std::nullopt` when it’s not desirable to use the UA as a proxy (e.g., getting a /// balance for a specific UA). std::optional spendingPolicy) const; strError = strprintf("Error: Insufficient funds to pay the fee. This transaction needs to spend %s " "plus a fee of at least %s, but only %s is available", DisplayMoney(nValue), DisplayMoney(nFeeRequired), DisplayMoney(curBalance)); strUsage += HelpMessageOpt("-datacarriersize=", strprintf(_("Maximum size of data in data carrier transactions we relay and mine (default: %u)"), MAX_OP_RETURN_RELAY)); strUsage += HelpMessageOpt("-txunpaidactionlimit=", strprintf(_("Transactions with more than this number of unpaid actions will not be accepted to the mempool or relayed (default: %u)"), DEFAULT_TX_UNPAID_ACTION_LIMIT)); if (GetArg("-txunpaidactionlimit", 0) < 0) { return InitError(_("-txunpaidactionlimit cannot be configured with a negative value.")); } nTxUnpaidActionLimit = GetArg("-txunpaidactionlimit", DEFAULT_TX_UNPAID_ACTION_LIMIT); #include "zip317.h" CAmount nTxUnpaidActionLimit = DEFAULT_TX_UNPAID_ACTION_LIMIT; // Transactions with more than `-txunpaidactionlimit` unpaid actions (calculated // using the modified fee) are not accepted to the mempool or relayed. // size_t nUnpaidActionCount = entry.GetUnpaidActionCount(); if (nUnpaidActionCount > nTxUnpaidActionLimit) { LogPrint("mempool", "Not accepting transaction with txid %s, size %d bytes, effective fee %d " + MINOR_CURRENCY_UNIT + ", and fee delta %d " + MINOR_CURRENCY_UNIT + " to the mempool because it has %d unpaid actions" ", which is over the limit of %d. The conventional fee for this transaction is %d " + MINOR_CURRENCY_UNIT, tx.GetHash().ToString(), nSize, nModifiedFees, nModifiedFees - nFees, nUnpaidActionCount, nTxUnpaidActionLimit, tx.GetConventionalFee()); return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "tx unpaid action limit exceeded"); } /** Limit on the number of unpaid actions a transaction can have to be accepted to the mempool. */ extern CAmount nTxUnpaidActionLimit; /** Whether alert messages are processed. */ LogPrint("zrpc", "%s, conventional fee: %s\n", id, FormatMoney(tx.GetConventionalFee())); LogPrint("zrpcunsafe", "%s: requested fee: %s\n", getId(), fee_.has_value() ? FormatMoney(fee_.value()) : "default"); LogPrint("zrpc", "%s, conventional fee: %s\n", getId(), FormatMoney(tx.GetConventionalFee())); LogPrint("zrpcunsafe", "%s: requested fee: %s\n", getId(), fee_.has_value() ? FormatMoney(fee_.value()) : "default"); LogPrint("zrpc", "%s, conventional fee: %s\n", getId(), FormatMoney(tx.GetConventionalFee())); if (!fSubtractFeeFromAmount && nValue + nFeeRequired > curBalance) { strError = strprintf("Error: Insufficient funds to pay the fee. This transaction needs to spend %s " + CURRENCY_UNIT + " plus a fee of at least %s " + CURRENCY_UNIT + ", but only %s " + CURRENCY_UNIT + " is available", FormatMoney(nValue), FormatMoney(nFeeRequired), FormatMoney(curBalance)); throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, strError); } else { throw JSONRPCError(RPC_WALLET_ERROR, strError); } /// Limit on the number of unpaid actions a transaction can have to be accepted to the mempool. static const size_t DEFAULT_TX_UNPAID_ACTION_LIMIT = DEFAULT_BLOCK_UNPAID_ACTION_LIMIT; /// passed as a JSON string, verbatim if (conversion == Conversion::None) { params.push_back(strVal); } else { auto parsedParam = ParseNonRFCJSONValue(strVal); if (conversion == Conversion::NullableString) { } else if (conversion == Conversion::JSON) { } else { } #endif #if defined(__MINGW32__) || !defined(WIN32) // MinGW needs this for isatty. return std::min(GetFee(nSize), LEGACY_DEFAULT_FEE); static const CAmount LEGACY_DEFAULT_FEE = 1000; // than LEGACY_DEFAULT_FEE zatoshis. CAmount fee = LEGACY_DEFAULT_FEE; LogPrint("zrpcunsafe", "%s: Beginning creating transaction with Sapling output amount=%s\n", getId(), FormatMoney(amountToSend - LEGACY_DEFAULT_FEE)); builder.SetFee(LEGACY_DEFAULT_FEE); builder.AddSaplingOutput(ovkForShieldingFromTaddr(seed), migrationDestAddress, amountToSend - LEGACY_DEFAULT_FEE); amountMigrated += amountToSend - LEGACY_DEFAULT_FEE; /** The legacy default fee that was defined in ZIP 313. */ static const CAmount DEFAULT_FEE = 1000; std::string debugCategories = "addrman, alert, bench, coindb, db, http, libevent, lock, mempool, mempoolrej, net, partitioncheck, pow, proxy, prune, " pool.addUnchecked(hash, entry, setAncestors); mempool.removeForBlock(pblock->vtx, pindexNew->nHeight, txConflicted); bool CTxMemPool::addUnchecked(const uint256& hash, const CTxMemPoolEntry &entry, setEntries &setAncestors) std::list& conflicts) bool CTxMemPool::addUnchecked(const uint256&hash, const CTxMemPoolEntry &entry) return addUnchecked(hash, entry, setAncestors); bool addUnchecked(const uint256& hash, const CTxMemPoolEntry &entry); bool addUnchecked(const uint256& hash, const CTxMemPoolEntry &entry, setEntries &setAncestors); std::list& conflicts); #ifdef ENABLE_MINING KeyIO keyIO(chainparams); KeyIO keyIO(chainparams); #ifdef ENABLE_MINING #endif #ifdef ENABLE_MINING #else assert(false); #endif strUsage += HelpMessageOpt("-printpriority", strprintf("Log the modified fee, conventional fee, size, number of logical actions, and number of unpaid actions for each transaction when mining blocks (default: %u)", DEFAULT_PRINTPRIORITY)); LogPrintf("%s: txid %s; modified fee %s; conventional fee %s; size %d bytes; logical actions %d; unpaid actions %d\n", iter->GetTx().GetHash().ToString(), FormatMoney(iter->GetModifiedFee()), FormatMoney(iter->GetTx().GetConventionalFee()), iter->GetTxSize(), iter->GetTx().GetLogicalActionCount(), iter->GetUnpaidActionCount()); /** Fill the buffer buf of length num with random unformly distributed bytes, via the rand_core OsRng. */ /** * Return a random value of type I uniformly distributed on [0, nMax), unless nMax is 0 in which case return 0. * I must be an unsigned numeric type. */ // I() for primitive integer types returns 0. /** Return a random uint128_t uniformly distributed on [0, nMax), unless nMax is 0 in which case return 0. */ /** Return a random int128_t uniformly distributed on [0, nMax), unless nMax is 0 in which case return 0. nMax must be >= 0. */ /** Return a random uint64_t uniformly distributed on [0, nMax), unless nMax is 0 in which case return 0. */ /** Return a random int64_t uniformly distributed on [0, nMax), unless nMax is 0 in which case return 0. nMax must be >= 0. */ /** Return a random int uniformly distributed on [0, nMax), unless nMax is 0 in which case return 0. nMax must be >= 0. */ /** Return a random uniformly distributed uint256. */ // Precomputed nonces and Equihash solutions. These were CPU-mined by the code in MineBlockForTest. // This is only useful if the test changes to require more blocks, but we keep it // compiling to avoid bitrot. void MineBlockForTest(const CChainParams& chainparams, CBlock* pblock) { arith_uint256 try_nonce(0); unsigned int n = chainparams.GetConsensus().nEquihashN; unsigned int k = chainparams.GetConsensus().nEquihashK; // Hash state eh_HashState eh_state = EhInitialiseState(n, k); // I = the block header minus nonce and solution. CEquihashInput I{*pblock}; CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss << I; // H(I||... eh_state.Update((unsigned char*)&ss[0], ss.size()); while (true) { pblock->nNonce = ArithToUint256(try_nonce); // H(I||V||... eh_HashState curr_state(eh_state); curr_state.Update(pblock->nNonce.begin(), pblock->nNonce.size()); std::function incrementRuns = [&]() {}; std::function&)> checkSolution = [&](size_t s, const std::vector& index_vector) { auto soln = GetMinimalFromIndices(index_vector, DIGITBITS); pblock->nSolution = soln; if (!equihash::is_valid( n, k, {(const unsigned char*)ss.data(), ss.size()}, {pblock->nNonce.begin(), pblock->nNonce.size()}, {soln.data(), soln.size()})) { return false; } CValidationState state; return ProcessNewBlock(state, chainparams, NULL, pblock, true, NULL) && state.IsValid(); }; if (equihash_solve(curr_state.inner, incrementRuns, checkSolution)) break; try_nonce += 1; } } // If you need to mine more blocks than are currently in blockinfo, increase // nblocks and then this code will do so. MineBlockForTest(chainparams, pblock); auto PrepareMempool = [&](size_t numTransactions, CAmount fee, std::function addTx) { PrepareMempool(1000, MINIMUM_FEE, [&](size_t i, auto& entry, auto& tx) { PrepareMempool(1000, MINIMUM_FEE, [&](size_t i, auto& entry, auto& tx) { PrepareMempool(210, CalculateConventionalFee(64), [&](size_t i, auto& entry, auto& tx) { PrepareMempool(211, CalculateConventionalFee(64), [&](size_t i, auto& entry, auto& tx) { // We can't check the exact block size because which tx will be excluded is nondeterministic, // and they are different sizes. PrepareMempool(2, MINIMUM_FEE, [&](size_t i, auto& entry, auto& tx) { int64_t newTime = chainActive.Tip()->GetMedianTimePast()+2; // We can't test this by directly calling CheckFinalTx(tx*, LOCKTIME_MEDIAN_TIME_PAST) // because that would use chainActive.Height() which isn't fooled by monkey-patching nHeight. // However, this should be equivalent: BOOST_CHECK(IsFinalTx(tx, chainActive.Tip()->nHeight+1, newTime)); BOOST_CHECK(IsFinalTx(tx2, chainActive.Tip()->nHeight+1, newTime)); FixedClock::Instance()->Set(std::chrono::seconds(newTime)); #include "zip317.h" strUsage += HelpMessageOpt("-blockunpaidactionlimit=", strprintf(_("Set the limit on unpaid actions that will be accepted in a block for transactions paying less than the ZIP 317 fee (default: %d)"), DEFAULT_BLOCK_UNPAID_ACTION_LIMIT)); if (GetArg("-blockunpaidactionlimit", 0) < 0) { return InitError(_("-blockunpaidactionlimit cannot be configured with a negative value.")); } // Number of unpaid actions allowed in a block: nBlockUnpaidActionLimit = (size_t) GetArg("-blockunpaidactionlimit", DEFAULT_BLOCK_UNPAID_ACTION_LIMIT); if (nBlockUnpaidActions + txUnpaidActions > nBlockUnpaidActionLimit) { // Configuration parameters for the block size and unpaid action limit size_t nBlockUnpaidActionLimit; static const size_t DEFAULT_BLOCK_UNPAID_ACTION_LIMIT = 50; if (GetArg("-blockminsize", 0) != 0) { InitWarning(_("The argument -blockminsize is no longer supported.")); } // Configuration parameter for the block size unsigned int nBlockMaxSize; /** Default for -blockmaxsize, which controls the maximum block size the mining code will create **/ #include "zip317.h" #include // Precomputed nonces and Equihash solutions. These were CPU-mined by the code in `CreateNewBlock_validity`. // CreateNewBlock_validity will recreate blocks from these via ProcessNewBlock, which would fail if they were incorrect. // We can't make transactions until we have inputs. Therefore, load 200 blocks. const int nblocks = 200; auto CoinbaseTx = [&](int height) { assert(0 <= height-1 && height-1 < txFirst.size()); return txFirst[height-1]; }; txFirst.push_back(new CTransaction(pblock->vtx[0])); TestMemPoolEntryHelper entry; entry.nFee = 0; entry.nHeight = 0; auto PrepareTemplate = [&](size_t numTransactions, CAmount fee, std::function addTx) { // This relies on tx.{vin,vout} having been prepared for the specific check. assert(fee >= 0); int coinbaseHeight = 20 - 1; tx.vout[0].nValue = -1; // always spend coinbase in the first transaction for (size_t i = 0; i < numTransactions; ++i) { bool spendsCoinbase = tx.vout[0].nValue < fee; if (spendsCoinbase) { ++coinbaseHeight; tx.vin[0].prevout.hash = CoinbaseTx(coinbaseHeight)->GetHash(); tx.vout[0].nValue = MinerSubsidy(coinbaseHeight); } assert(tx.vout[0].nValue >= fee); tx.vout[0].nValue -= fee; addTx(i, entry.Fee(fee).Time(GetTime()).SpendsCoinbase(spendsCoinbase), tx); tx.vin[0].prevout.hash = tx.GetHash(); } }; // NOTE: OP_NOP is used to force 20 legacy sigops for the CHECKMULTISIG. // If we don't set the # of sigops in the CTxMemPoolEntry, template creation fails. PrepareTemplate(1000, MINIMUM_FEE, [&](size_t i, auto& entry, auto& tx) { mempool.addUnchecked(tx.GetHash(), entry.FromTx(tx)); }); // If we do set the # of sigops in the CTxMemPoolEntry, template creation passes. PrepareTemplate(1000, MINIMUM_FEE, [&](size_t i, auto& entry, auto& tx) { mempool.addUnchecked(tx.GetHash(), entry.SigOps(20).FromTx(tx)); }); // We reserve 100 sigops for the coinbase tx, which actually takes 1 sigop. We finish the template // when the estimated number of sigops is 19980 (since BlockAssembler::TestForBlock does not allow // exactly the limit of 20000). So the block template will have 19980 - 100 + 1 = 19881 sigops. // This takes (19881-1)/20 = 994 transactions, plus the coinbase tx. BOOST_CHECK_EQUAL(19881, std::reduce(pblocktemplate->vTxSigOps.begin(), pblocktemplate->vTxSigOps.end())); BOOST_CHECK_EQUAL(995, pblocktemplate->block.vtx.size()); // Test block size just under the 2000000-byte limit. PrepareTemplate(210, CalculateConventionalFee(64), [&](size_t i, auto& entry, auto& tx) { mempool.addUnchecked(tx.GetHash(), entry.FromTx(tx)); }); BOOST_CHECK_EQUAL(211, pblocktemplate->block.vtx.size()); BOOST_CHECK_EQUAL(1994255, ::GetSerializeSize(pblocktemplate->block, SER_NETWORK, PROTOCOL_VERSION)); // ... and just over the limit. PrepareTemplate(211, CalculateConventionalFee(64), [&](size_t i, auto& entry, auto& tx) { mempool.addUnchecked(tx.GetHash(), entry.FromTx(tx)); }); BOOST_CHECK(pblocktemplate = BlockAssembler(chainparams).CreateNewBlock(scriptPubKey)); // only 211 transactions including coinbase, not 212 BOOST_CHECK_EQUAL(211, pblocktemplate->block.vtx.size()); BOOST_CHECK_GE(2000000, ::GetSerializeSize(pblocktemplate->block, SER_NETWORK, PROTOCOL_VERSION)); delete pblocktemplate; // Test with an orphan tx in the mempool. Note that this is testing a case that should never occur, // because AcceptToMemoryPool would reject the orphan. Using addUnchecked bypasses that rejection. PrepareTemplate(2, MINIMUM_FEE, [&](size_t i, auto& entry, auto& tx) { if (i != 0) mempool.addUnchecked(tx.GetHash(), entry.SigOps(1).FromTx(tx)); }); BOOST_CHECK_EXCEPTION(BlockAssembler(chainparams).CreateNewBlock(scriptPubKey), std::runtime_error, err_is("bad-txns-inputs-missingorspent")); // child with higher priority than parent // TODO: re-enable this when we have implemented priority logic for ZIP 317 block construction. // const CAmount HIGHFEE = MINIMUM_FEE*2; // const CAmount HIGHERFEE = MINIMUM_FEE*3; // // tx.vin[0].scriptSig = CScript() << OP_1; // tx.vin[0].prevout.hash = CoinbaseTx(1)->GetHash(); // tx.vin[0].prevout.n = 0; // tx.vout[0].nValue = MinerSubsidy(1) - HIGHFEE; // hash = tx.GetHash(); // mempool.addUnchecked(hash, entry.Fee(HIGHFEE).Time(GetTime()).SpendsCoinbase(true).FromTx(tx)); // tx.vin[0].prevout.hash = hash; // tx.vin.resize(2); // tx.vin[1].scriptSig = CScript() << OP_1; // tx.vin[1].prevout.hash = CoinbaseTx(2)->GetHash(); // tx.vin[1].prevout.n = 0; // tx.vout[0].nValue = tx.vout[0].nValue + MinerSubsidy(2) - HIGHERFEE; // First txn output + fresh coinbase - new txn fee // hash = tx.GetHash(); // mempool.addUnchecked(hash, entry.Fee(HIGHERFEE).Time(GetTime()).SpendsCoinbase(true).FromTx(tx)); // BOOST_CHECK(pblocktemplate = BlockAssembler(chainparams).CreateNewBlock(scriptPubKey)); // delete pblocktemplate; // mempool.clear(); mempool.addUnchecked(hash, entry.Fee(MINIMUM_FEE).Time(GetTime()).SpendsCoinbase(false).FromTx(tx)); tx.vin[0].prevout.hash = CoinbaseTx(1)->GetHash(); tx.vout[0].nValue = MinerSubsidy(1) - MINIMUM_FEE; assert(tx.vout[0].nValue >= 0); mempool.addUnchecked(hash, entry.Fee(MINIMUM_FEE).Time(GetTime()).SpendsCoinbase(true).FromTx(tx)); tx.vout[0].nValue -= MINIMUM_FEE; assert(tx.vout[0].nValue >= 0); mempool.addUnchecked(hash, entry.Fee(MINIMUM_FEE).Time(GetTime()).SpendsCoinbase(false).FromTx(tx)); tx.vin[0].prevout.hash = CoinbaseTx(1)->GetHash(); tx.vout[0].nValue = MinerSubsidy(1) - MINIMUM_FEE; mempool.addUnchecked(hash, entry.Fee(MINIMUM_FEE).Time(GetTime()).SpendsCoinbase(true).FromTx(tx)); mempool.addUnchecked(hash, entry.Fee(MINIMUM_FEE).Time(GetTime()).SpendsCoinbase(true).FromTx(tx)); tx.vin[0].prevout.hash = CoinbaseTx(1)->GetHash(); tx.vout[0].nValue = MinerSubsidy(1) - MINIMUM_FEE; mempool.addUnchecked(hash, entry.Fee(MINIMUM_FEE).Time(GetTime()).SpendsCoinbase(true).FromTx(tx)); tx2.vin[0].prevout.hash = CoinbaseTx(2)->GetHash(); tx2.vout[0].nValue = MinerSubsidy(2) - MINIMUM_FEE; mempool.addUnchecked(hash, entry.Fee(MINIMUM_FEE).Time(GetTime()).SpendsCoinbase(true).FromTx(tx2)); for (CTransaction *tx : txFirst) { } assert(nMax >= 0); assert(nMax >= 0); assert(nMax >= 0); // I must be an unsigned numeric type. // I() for primitive signed integer types returns 0. assert(nMax >= 0); // random(w) (which will only be called with positive w) must be defined to // return a uniform random value between zero inclusive and w exclusive. // The type W must be a signed numeric type that supports addition, binary // and unary -, and < and <= comparisons, and W() must construct the zero value // (these constraints are met for primitive signed integer types). // W must be a signed numeric type. static_assert(std::numeric_limits::min() < W()); assert(W() < totalWeight); #include "zip317.h" constructZIP317BlockTemplate(); void BlockAssembler::constructZIP317BlockTemplate() { CTxMemPool::weightedCandidates candidatesPayingConventionalFee; CTxMemPool::weightedCandidates candidatesNotPayingConventionalFee; for (auto mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi) { int128_t weightRatio = mi->GetWeightRatio(); if (weightRatio >= WEIGHT_RATIO_SCALE) { candidatesPayingConventionalFee.add(mi->GetTx().GetHash(), mi, weightRatio); } else { candidatesNotPayingConventionalFee.add(mi->GetTx().GetHash(), mi, weightRatio); } } CTxMemPool::queueEntries waiting; CTxMemPool::queueEntries cleared; addTransactions(candidatesPayingConventionalFee, waiting, cleared); addTransactions(candidatesNotPayingConventionalFee, waiting, cleared); } void BlockAssembler::addTransactions( CTxMemPool::weightedCandidates& candidates, CTxMemPool::queueEntries& waiting, CTxMemPool::queueEntries& cleared) { size_t nBlockUnpaidActions = 0; while (!blockFinished && !(candidates.empty() && cleared.empty())) { CTxMemPool::txiter iter; if (cleared.empty()) { // If no txs that were previously postponed are available to try // again, then select the next transaction randomly by weight ratio // from the candidate set. assert(!candidates.empty()); iter = std::get<1>(candidates.takeRandom().value()); } else { // If a previously postponed tx is available to try again, then it // has already been randomly sampled, so just take it in order. iter = cleared.front(); cleared.pop_front(); } // The tx should never already be in the block for ZIP 317. assert(inBlock.count(iter) == 0); // If the tx would cause the block to exceed the unpaid action limit, skip it. // A tx that pays at least the conventional fee will have no unpaid actions. size_t txUnpaidActions = iter->GetUnpaidActionCount(); if (nBlockUnpaidActions + txUnpaidActions > BLOCK_UNPAID_ACTION_LIMIT) { continue; } // If tx is dependent on other mempool transactions that haven't yet been // included then put it in the waiting queue. if (isStillDependent(iter)) { waiting.push_back(iter); continue; } // If this tx fits in the block add it, otherwise keep looping. if (TestForBlock(iter)) { AddToBlock(iter); nBlockUnpaidActions += txUnpaidActions; // This tx was successfully added, so add waiting transactions that // depend on this one to the cleared queue to try again. // // TODO: This makes the overall algorithm O(n^2 log n) in the worst case // of a linear dependency chain. (children is a std::map; its count method // is O(log n) given the maximum number of children at each step, and is // called O(n^2) times.) Daira conjectures that O(n log n) is possible. auto children = mempool.GetMemPoolChildren(iter); CTxMemPool::queueEntries stillWaiting; for (CTxMemPool::txiter maybeChild : waiting) { if (children.count(maybeChild) > 0) { cleared.push_back(maybeChild); } else { stillWaiting.push_back(maybeChild); } } waiting.swap(stillWaiting); } } } #include "weighted_map.h" void constructZIP317BlockTemplate(); void addTransactions( CTxMemPool::weightedCandidates& candidates, CTxMemPool::queueEntries& waiting, CTxMemPool::queueEntries& cleared); uint128_t GetRandUInt128(uint128_t nMax) return GetRandGeneric(nMax); } int128_t GetRandInt128(int128_t nMax) { return GetRandUInt128(nMax); } uint64_t GetRand(uint64_t nMax) { return GetRandGeneric(nMax); #include "int128.h" template I GetRandGeneric(I nMax) { static_assert(std::numeric_limits::min() == 0); if (nMax == I()) return I(); // The range of the random source must be a multiple of the modulus // to give every possible output value an equal possibility I nRange = (std::numeric_limits::max() / nMax) * nMax; I nRand = I(); do { GetRandBytes((unsigned char*)&nRand, sizeof(nRand)); } while (nRand >= nRange); return (nRand % nMax); } uint128_t GetRandUInt128(uint128_t nMax); int128_t GetRandInt128(int128_t nMax); #include "weighted_map.h" typedef std::deque queueEntries; // Type of a set of candidate transactions to be added to a block template. typedef WeightedMap weightedCandidates; // used to implement mempool limiting specified in ZIP 401, and the block template // construction algorithm specified in ZIP 317. #ifndef ZCASH_INT128_H #define ZCASH_INT128_H #include // will define INT128_MAX iff (in some future world) it provides int128_t. // Otherwise use the __int128 extension which is supported in clang and gcc. #ifndef INT128_MAX typedef __int128 int128_t; #define INT128_MAX (std::numeric_limits::max()) #define INT128_MIN (std::numeric_limits::min()) #endif // will define UINT128_MAX iff (in some future world) it provides uint128_t. // Otherwise use the __uint128_t extension which is supported in clang and gcc. #ifndef UINT128_MAX typedef __uint128_t uint128_t; #define UINT128_MAX (std::numeric_limits::max()) #endif #endif // ZCASH_INT128_H #include "mempool_limit.h" #include "zip317.h" size_t CTxMemPoolEntry::GetUnpaidActionCount() const { if (tx->IsCoinBase()) { return 0; } else { return std::max( int64_t {0}, (int64_t) std::max(GRACE_ACTIONS, tx->GetLogicalActionCount()) - (GetModifiedFee() / MARGINAL_FEE)); } } // Return a fixed-point representation of the entry's weight ratio, where 1 is represented by WEIGHT_RATIO_SCALE. int128_t CTxMemPoolEntry::GetWeightRatio() const { // ensure that the result will always be nonzero static_assert(WEIGHT_RATIO_SCALE > MAX_MONEY); return std::min( (int128_t {WEIGHT_RATIO_SCALE} * std::max(CAmount {1}, GetModifiedFee())) / tx->GetConventionalFee(), int128_t {WEIGHT_RATIO_SCALE} * WEIGHT_RATIO_CAP); } #include "int128.h" // Return the number of unpaid actions calculated according to ZIP 317. // size_t GetUnpaidActionCount() const; // Return a fixed-point representation of the entry's weight ratio according // to ZIP 317, where 1 is represented by WEIGHT_RATIO_SCALE. int128_t GetWeightRatio() const; mempool.addUnchecked(hash, entry.Fee(HIGHFEE).Time(GetTime()).FromTx(tx)); return strprintf("%d.%08d %s per 1000 bytes", nSatoshisPerK / COIN, nSatoshisPerK % COIN, CURRENCY_UNIT); strUsage += HelpMessageOpt("-minrelaytxfee=", strprintf(_("Transactions must have at least this fee rate (in %s per 1000 bytes) for relaying, mining and transaction creation (default: %s). This is not the only fee constraint."), // Fee rate in zatoshis per 1000 bytes required for mempool acceptance and relay. // TODO(update when ZIP 317 is implemented): // If you are mining, be careful setting this. If you set it too low then a // transaction spammer can cheaply fill blocks. It should be set above the real /** Default for -minrelaytxfee, minimum relay fee rate for transactions in zatoshis per 1000 bytes. TODO(misnamed, this is a rate) */ /** Default for -maxtxfee in zatoshis. */ /** Discourage users from setting fee rates higher than this in zatoshis per 1000 bytes. */ /** Warn if -maxtxfee is set to a fee higher than this in zatoshis. */ /** Transactions must have at least this fee rate (in zatoshis per 1000 bytes) for relaying, mining and transaction creation. */ /** Absolute maximum transaction fee (in zatoshis) used by wallet and mempool (rejects high fee in sendrawtransaction). */ // NOTE: Unlike wallet RPCs (which use ZEC values), mining RPCs follow GBT (BIP 22) in using zatoshi amounts. " \"fee\": n, (numeric) difference in value between transaction inputs and outputs (in " + MINOR_CURRENCY_UNIT + "); for coinbase transactions, this is a negative Number of the total collected block fees (i.e., not including the block subsidy); if key is not present, fee is unknown and clients MUST NOT assume there isn't one\n" // " \"coinbasevalue\" : n, (numeric) maximum allowable input to coinbase transaction, including the generation award and transaction fees (in " + MINOR_CURRENCY_UNIT + ")\n" " \"paytxfee\": x.xxxx, (numeric) the transaction fee rate set in " + CURRENCY_UNIT + " per 1000 bytes\n" " \"relayfee\": x.xxxx, (numeric) minimum relay fee rate for transactions in " + CURRENCY_UNIT + " per 1000 bytes\n" " \"satoshis\" (number) The difference of " + MINOR_CURRENCY_UNIT + "\n" " \"satoshis\" (number) The number of " + MINOR_CURRENCY_UNIT + " of the output\n" " \"satoshis\" (number) The number of " + MINOR_CURRENCY_UNIT + " of the output\n" " \"satoshis\" (number) The difference of " + MINOR_CURRENCY_UNIT + "\n" " \"satoshis\" (number) The difference of " + MINOR_CURRENCY_UNIT + "\n" " \"balance\" (string) The current balance in " + MINOR_CURRENCY_UNIT + "\n" " \"received\" (string) The total number of " + MINOR_CURRENCY_UNIT + " received (including change)\n" " \"relayfee\": x.xxxxxxxx, (numeric) minimum relay fee rate for transactions in " + CURRENCY_UNIT + " per 1000 bytes\n" // Bitcoin addresses should fail parsing "\nSet the preferred transaction fee rate per 1000 bytes. This is only used by legacy transaction creation APIs (sendtoaddress, sendmany, and fundrawtransaction). Overwrites the paytxfee parameter.\n" "1. amount (numeric, required) The transaction fee rate in " + CURRENCY_UNIT + " per 1000 bytes rounded to the nearest 0.00000001\n" " \"paytxfee\": x.xxxx, (numeric) the preferred transaction fee rate used for transactions created by legacy APIs, set in " + CURRENCY_UNIT + " per 1000 bytes\n" " \"valueZat\" : xxxx (numeric) The amount in " + MINOR_CURRENCY_UNIT + "\n" " \"valueZat\" : xxxx (numeric) The amount in " + MINOR_CURRENCY_UNIT + "\n" BOOST_CHECK_EQUAL(nValueRet, 1 * COIN); // we should get 1 ZEC in 1 coin BOOST_CHECK_EQUAL(nValueRet, 2 * COIN); // we should get 2 ZEC in 1 coin // TODO: fPayAtLeastCustomFee is always true so we could simplify this by saying // `payTxFee.GetFee(std::max(1000, nTxBytes))` above, if we do not remove this code // completely. strUsage += HelpMessageOpt("-mintxfee=", strprintf(_("The fallback fee rate (in %s per 1000 bytes) used by legacy APIs (sendtoaddress, sendmany, and fundrawtransaction) when -paytxfee " "has not been set and there is insufficient mempool data to estimate a fee according to the -txconfirmtarget option (default: %s)"), strUsage += HelpMessageOpt("-paytxfee=", strprintf(_("The preferred fee rate (in %s per 1000 bytes) used for transactions created by legacy APIs (sendtoaddress, sendmany, and fundrawtransaction). " "If the transaction is less than 1000 bytes then the fee rate is applied as though it were 1000 bytes. See the descriptions of -txconfirmtarget " "and -mintxfee options for how the fee is calculated when this option is not set."), CURRENCY_UNIT)); strUsage += HelpMessageOpt("-txconfirmtarget=", strprintf(_("If -paytxfee is not set, include enough fee that transactions created by legacy APIs (sendtoaddress, sendmany, and fundrawtransaction) " "begin confirmation on average within n blocks. This is only used if there is sufficient mempool data to estimate the fee; if not, the " "fallback fee set by -mintxfee is used. (default: %u)"), DEFAULT_TX_CONFIRM_TARGET)); UIWarning(_("-paytxfee is set to a very high fee rate! This is the fee rate you will pay if you send a transaction.")); return UIError(strprintf(_("Invalid amount for -paytxfee=: '%s' (must be at least the minimum relay fee rate %s)"), UIWarning(_("-maxtxfee is set to a very high fee rate! Fee rates this large could be paid on a single transaction.")); return UIError(strprintf(_("Invalid amount for -maxtxfee=: '%s' (must be at least the minimum relay fee rate of %s to prevent stuck transactions)"), } else if (txout.IsDust()) { /** * The rate used to calculate the dust threshold, in zatoshis per 1000 bytes. * This will effectively be multiplied by 3 (it is necessary to express it this * way to ensure that rounding will be calculated the same as before #6542). * * Bitcoin Core added the concept of "dust" in bitcoin/bitcoin#2577. At that * point the dust threshold rate was tied to three times the minRelayTxFee rate, * with the motivation that if you'd pay more than a third of the minimum relay * fee to spend something, it should be considered dust. This was implemented * as a standard rule rejecting dust outputs. * * This motivation will not apply after ZIP 317 block construction is implemented: * at that point the ZIP 317 marginal fee will be 5000 zats per logical action, * but the dust threshold rate will still be 300 zats per 1000 bytes. Those costs * would only coincide if the marginal size per logical action were * 5000/300 * 1000 ~= 16667 bytes, and in practice the marginal size for any * kind of input is much smaller than that. * * However, to avoid interoperability problems (older wallets creating transactions * that newer nodes will reject because they view the outputs as dust), we will have * to coordinate any increase in the dust threshold carefully. * * More history: in Zcash the minRelayTxFee rate was 5000 zats/1000 bytes at launch, * changed to 1000 zats/1000 bytes in zcashd v1.0.3 and to 100 zats/1000 bytes in * zcashd v1.0.7-1 (#2141). The relaying problem for shielded transactions (#1969) * that prompted the latter change was fixed more thoroughly by the addition of * `CFeeRate::GetFeeForRelay` in #4916, ensuring that a transaction paying * `DEFAULT_FEE` can always be relayed. At the same time the default fee was set * to 1000 zats, per ZIP 313. * * #6542 changed relaying policy to be more strict about enforcing minRelayTxFee. * It also allowed `-minrelaytxfee=0`, which we are using to avoid some test * breakage. But if the dust threshold rate were still set to three times the * minRelayTxFee rate, then setting `-minrelaytxfee=0` would have the side effect * of setting the dust threshold to zero, which is not intended. * * Bitcoin Core took a different approach to disentangling the dust threshold from * the relay threshold, adding a `-dustrelayfee` option (bitcoin/bitcoin#9380). * We don't want to do that because it is likely that we will change the dust policy * again, and adding a user-visible config option might conflict with that. Also, * it isn't a good idea for the dust threshold rate to be configurable per node; * it's a standard rule parameter and should only be changed with network-wide * coordination (if it is increased then wallets have to change before nodes, and * vice versa if it is decreased). So for now we set it to a constant that matches * the behaviour before #6542. */ static const unsigned int ONE_THIRD_DUST_THRESHOLD_RATE = 100; #include "policy/policy.h" CAmount CTxOut::GetDustThreshold() const { // See the comment on ONE_THIRD_DUST_THRESHOLD_RATE in policy.h. static const CFeeRate oneThirdDustThresholdRate {ONE_THIRD_DUST_THRESHOLD_RATE}; if (scriptPubKey.IsUnspendable()) return 0; // A typical spendable txout is 34 bytes, and will need a txin of at // least 148 bytes to spend. With ONE_THIRD_DUST_THRESHOLD_RATE == 100, // the dust threshold for such a txout would be // 3*floor(100*(34 + 148)/1000) zats = 54 zats. size_t nSize = GetSerializeSize(*this, SER_DISK, 0) + 148u; return 3*oneThirdDustThresholdRate.GetFee(nSize); } CAmount GetDustThreshold() const; bool IsDust() const return nValue < GetDustThreshold(); // Check dust threshold: CFeeRate oneThirdDustThresholdRate{ONE_THIRD_DUST_THRESHOLD_RATE}; CAmount nDustThreshold = (34 + 148) * oneThirdDustThresholdRate.GetFeePerK()/1000 * 3; if (txout.IsDust()) if (nSubtractFeeFromAmount > 0 && newTxOut.IsDust()) CAmount nDust = newTxOut.GetDustThreshold() - newTxOut.nValue; if (txNew.vout[i].IsDust()) if (newTxOut.IsDust()) // dustThreshold cannot be zero because it is no longer configured via `-minrelaytxfee`. return txout.GetDustThreshold(); CAmount minRelayFee = ::minRelayTxFee.GetFeeForRelay(nSize); if (fLimitFree && nModifiedFees < minRelayFee) { LogPrint("mempool", "Not accepting transaction with txid %s, size %d bytes, effective fee %d " + MINOR_CURRENCY_UNIT + ", and fee delta %d " + MINOR_CURRENCY_UNIT + " to the mempool due to insufficient fee. " + " The minimum acceptance/relay fee for this transaction is %d " + MINOR_CURRENCY_UNIT, tx.GetHash().ToString(), nSize, nModifiedFees, nModifiedFees - nFees, minRelayFee); if (GetArg("-blockprioritysize", 0) != 0) { InitWarning(_("The argument -blockprioritysize is no longer supported.")); } #include "zip317.h" #include "core_memusage.h" EXPECT_EQ(10000, limitSet.getTotalWeight()); EXPECT_EQ(20000, limitSet.getTotalWeight()); EXPECT_EQ(30000 + LOW_FEE_PENALTY, limitSet.getTotalWeight()); ASSERT_EQ(txid == TX_ID3 ? 20000 : 20000 + LOW_FEE_PENALTY, limitSet.getTotalWeight()); CAmount funds = 66000; auto testNote = GetTestSaplingNote(sk.default_address(), funds); auto [cost, evictionWeight] = MempoolCostAndEvictionWeight(builder.Build().GetTxOrThrow(), MINIMUM_FEE); static_assert(MINIMUM_FEE == 10000); builder.SetFee(MINIMUM_FEE-1); auto [cost, evictionWeight] = MempoolCostAndEvictionWeight(builder.Build().GetTxOrThrow(), MINIMUM_FEE-1); for (int i = 0; i < 10; i++) { builder.AddSaplingOutput(sk.full_viewing_key().ovk, sk.default_address(), 1000, {}); } // max(1 input, 10 outputs + 1 change output) => 11 logical actions. CAmount zip317_fee = CalculateConventionalFee(11); ASSERT_GT(funds, 1000*10 + zip317_fee); const CTransaction tx {result.GetTxOrThrow()}; EXPECT_EQ(11, tx.GetLogicalActionCount()); // For the test to be valid, we want the memory usage of this transaction to be more than MIN_TX_COST. // Avoid hard-coding the usage because it might be platform-dependent. ASSERT_GT(GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION), MIN_TX_COST); size_t tx_usage = RecursiveDynamicUsage(tx); EXPECT_GT(tx_usage, MIN_TX_COST); auto [cost, evictionWeight] = MempoolCostAndEvictionWeight(tx, zip317_fee); EXPECT_EQ(tx_usage, cost); EXPECT_EQ(tx_usage, evictionWeight); // If we pay less than the conventional fee for 11 actions, we should incur a low fee penalty. auto [cost2, evictionWeight2] = MempoolCostAndEvictionWeight(tx, zip317_fee-1); EXPECT_EQ(tx_usage, cost2); EXPECT_EQ(tx_usage + LOW_FEE_PENALTY, evictionWeight2); const int64_t MIN_TX_COST = 10000; const int64_t LOW_FEE_PENALTY = 40000; if (fee < tx.GetConventionalFee()) { "%s). There is no prioritisation benefit to a fee this large (see " "https://zips.z.cash/zip-0317#recommended-algorithm-for-block-template-construction), " "and it likely indicates a mistake in setting the fee.", for (const auto& r : payments.GetResolvedPayments()) { std::optional result; examine(r.address, match { [&](const CKeyID& keyId) { if (r.memo.has_value()) { result = TransactionBuilderResult("Memos cannot be sent to transparent addresses."); } else { builder.AddTransparentOutput(keyId, r.amount); } }, [&](const CScriptID& scriptId) { if (r.memo.has_value()) { result = TransactionBuilderResult("Memos cannot be sent to transparent addresses."); } else { builder.AddTransparentOutput(scriptId, r.amount); } }, [&](const libzcash::SaplingPaymentAddress& addr) { builder.AddSaplingOutput( r.isInternal ? internalOVK : externalOVK, addr, r.amount, r.memo.has_value() ? r.memo.value().ToBytes() : Memo::NoMemo().ToBytes()); }, [&](const libzcash::OrchardRawAddress& addr) { builder.AddOrchardOutput( r.isInternal ? internalOVK : externalOVK, addr, r.amount, r.memo.has_value() ? std::optional(r.memo.value().ToBytes()) : std::nullopt); }, }); if (result.has_value()) { return result.value(); return examine(preferred.value(), match { [&](const libzcash::OrchardRawAddress addr) -> std::optional { return MinerAddress(addr); }, [&](const libzcash::SaplingPaymentAddress addr) -> std::optional { return MinerAddress(addr); }, [&](const CKeyID keyID) -> std::optional { return operator()(keyID); }, [&](const auto other) -> std::optional { return std::nullopt; } auto GetSourceForDestination = match { [&](const CKeyID& addr) -> std::optional { return GetSourceForPaymentAddress(pwalletMain)(addr); }, [&](const CScriptID& addr) -> std::optional { return GetSourceForPaymentAddress(pwalletMain)(addr); }, [&](const CNoDestination& addr) -> std::optional { return std::nullopt; }, }; std::optional source = std::visit(GetSourceForDestination, item.first); std::optional source = std::visit(GetSourceForDestination, item.first); examine(addr.value(), match { }); return examine(DecodeDestination(str), match { }); return examine(address, match { }); examine(vk, match { }); nBlockSize = examine(minerAddress, match { }); examine(preferred.value(), match { }); examine(changeAddr, match { }); examine(err, match { examine(err.reason, match { })) }); examine(recipient.first, match { }); examine(preparedTx, match { }); examine(toAddress, match { }); return examine(Memo::FromHex(memoHex), match { }); std::string result = examine(address.value(), match { }); examine(item.first, match { }); examine(item.first, match { }); examine(res, match { }); examine(receiver, match { }); if (examine(decoded.value(), match { })) { examine(decoded.value(), match { examine(receiver, match { }); }); examine(pa.value(), match { }); examine(recipient.GetAddress(), match { }); examine(Memo::FromHex(memoHex), match { }); examine(addr.value(), match { examine(preferredRecipient.value(), match { }); }); examine(decoded.value(), match { }); examine(destaddress.value(), match { }); examine(addr.value(), match { }); examine(destaddress.value(), match { }); return examine(result, match { }); std::pair defaultAddress = examine(recipient, match { }); return examine(recipient, match { }); bool restored = examine(ufvk.value().Address(j, receiverTypes), match { }); examine(addr, match { }); examine(vk, match { }); examine(selector.GetPattern(), match { }); return examine(selector.GetPattern(), match { bool matches = examine(receiver, match { }); }); return examine(selector.GetPattern(), match { }); return examine(selector.GetPattern(), match { }); auto orchardIvks = examine(selector.GetPattern(), match { }); return examine(address, match { }); examine(addr, match { examine(receiver, match { }); }); return examine(this->pattern, match { }); return transparentCoinbasePolicy != TransparentCoinbasePolicy::Require && examine(this->pattern, match { }); return transparentCoinbasePolicy != TransparentCoinbasePolicy::Require && examine(this->pattern, match { }); return transparentCoinbasePolicy != TransparentCoinbasePolicy::Require && examine(this->pattern, match { }); changeAddr = examine(selector.GetPattern(), match { }); examine(payment.GetAddress(), match { }); return examine(selector.GetPattern(), match { }); examine(r.address, match { }); examine(changeAddr.value(), match { }); examine(payment.address, match { }); examine(recipient, match { }); examine(receiver, match { }); return examine(receiver, match { }); return examine(recipient, match { }); return examine(receiver, match { }); examine(req, match { }); // A wrapper around two-argument `std::visit` that reverses the arguments, putting the // value to be visited first. This is normally used as: // // examine(specimen, match { // ... // }) // // The return type is inferred as it would be for `std::visit`. template decltype(auto) examine(Specimen&& specimen, Visitor&& visitor) { return std::visit(visitor, specimen); } #include "zip317.h" CAmount CTransaction::GetConventionalFee() const { return CalculateConventionalFee(GetLogicalActionCount()); } size_t CTransaction::GetLogicalActionCount() const { return CalculateLogicalActionCount( vin, vout, vJoinSplit.size(), vShieldedSpend.size(), vShieldedOutput.size(), orchardBundle.GetNumActions()); } // Return the conventional fee for this transaction calculated according to // . CAmount GetConventionalFee() const; // Return the number of logical actions calculated according to // . size_t GetLogicalActionCount() const; #include "zip317.h" #include static size_t ceil_div(size_t num, size_t den) { return (num + den - 1)/den; } CAmount CalculateConventionalFee(size_t logicalActionCount) { return MARGINAL_FEE * std::max(GRACE_ACTIONS, logicalActionCount); } size_t CalculateLogicalActionCount( const std::vector& vin, const std::vector& vout, unsigned int joinSplitCount, unsigned int saplingSpendCount, unsigned int saplingOutputCount, unsigned int orchardActionCount) { const size_t tx_in_total_size = GetSerializeSize(vin, SER_NETWORK, PROTOCOL_VERSION); const size_t tx_out_total_size = GetSerializeSize(vout, SER_NETWORK, PROTOCOL_VERSION); return std::max(ceil_div(tx_in_total_size, P2PKH_STANDARD_INPUT_SIZE), ceil_div(tx_out_total_size, P2PKH_STANDARD_OUTPUT_SIZE)) + 2 * joinSplitCount + std::max(saplingSpendCount, saplingOutputCount) + orchardActionCount; } #ifndef ZCASH_ZIP317_H #define ZCASH_ZIP317_H #include "amount.h" #include "primitives/transaction.h" #include #include #include // Constants for fee calculation. static const CAmount MARGINAL_FEE = 5000; static const size_t GRACE_ACTIONS = 2; static const size_t P2PKH_STANDARD_INPUT_SIZE = 150; static const size_t P2PKH_STANDARD_OUTPUT_SIZE = 34; // Constants for block template construction. static const int64_t WEIGHT_RATIO_SCALE = INT64_C(10000000000000000); static const int64_t WEIGHT_RATIO_CAP = 4; static const size_t BLOCK_UNPAID_ACTION_LIMIT = 50; /// Return the conventional fee for the given `logicalActionCount` calculated according to /// . CAmount CalculateConventionalFee(size_t logicalActionCount); /// Return the number of logical actions calculated according to /// . size_t CalculateLogicalActionCount( const std::vector& vin, const std::vector& vout, unsigned int joinSplitCount, unsigned int saplingSpendCount, unsigned int saplingOutputCount, unsigned int orchardActionCount); #endif // ZCASH_ZIP317_H std::vector GetMinimalFromIndices(const std::vector& indices, std::vector GetMinimalFromIndices(const std::vector& indices, std::function incrementRuns = [&]() { ehSolverRuns.increment(); }; std::function&)> checkSolution = [&](size_t s, const std::vector& index_vector) { return validBlock(GetMinimalFromIndices(index_vector, DIGITBITS)); }; equihash_solve(curr_state.inner, incrementRuns, checkSolution); #include "pow/tromp/equi.h" #include // We can't make transactions until we have inputs. Therefore, load 110 blocks. const int nblocks = 110; assert(nblocks < chainparams.GetConsensus().SubsidySlowStartShift()); auto MinerSubsidy = [](int height) { return height*50000; }; auto FoundersReward = [](int height) { return height*12500; }; std::vector txFirst; for (unsigned int i = 0; i < nblocks; ++i) int height = i+1; pblock->nTime = chainActive.Tip()->GetMedianTimePast() + 6*chainparams.GetConsensus().PoWTargetSpacing(i); txCoinbase.vout[0].nValue = MinerSubsidy(height); txCoinbase.vout[1].nValue = FoundersReward(height); if (i < sizeof(blockinfo)/sizeof(*blockinfo)) { pblock->nNonce = uint256S(blockinfo[i].nonce_hex); pblock->nSolution = ParseHex(blockinfo[i].solution_hex); } else { // If you need to mine more blocks than are currently in blockinfo, this code will do so. // We leave it compiling so that it doesn't bitrot. arith_uint256 try_nonce(0); unsigned int n = chainparams.GetConsensus().nEquihashN; unsigned int k = chainparams.GetConsensus().nEquihashK; // Hash state eh_HashState eh_state = EhInitialiseState(n, k); // I = the block header minus nonce and solution. CEquihashInput I{*pblock}; CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss << I; // H(I||... eh_state.Update((unsigned char*)&ss[0], ss.size()); while (true) { pblock->nNonce = ArithToUint256(try_nonce); // H(I||V||... eh_HashState curr_state(eh_state); curr_state.Update(pblock->nNonce.begin(), pblock->nNonce.size()); std::function incrementRuns = [&]() {}; std::function&)> checkSolution = [&](size_t s, const std::vector& index_vector) { auto soln = GetMinimalFromIndices(index_vector, DIGITBITS); pblock->nSolution = soln; if (!equihash::is_valid( n, k, {(const unsigned char*)ss.data(), ss.size()}, {pblock->nNonce.begin(), pblock->nNonce.size()}, {soln.data(), soln.size()})) { return false; } CValidationState state; return ProcessNewBlock(state, chainparams, NULL, pblock, true, NULL) && state.IsValid(); }; if (equihash_solve(curr_state.inner, incrementRuns, checkSolution)) break; try_nonce += 1; // Stop here if we needed to mine more blocks. assert(nblocks == sizeof(blockinfo)/sizeof(*blockinfo)); bool zip_212_enabled; libzcash::SaplingPaymentAddress zaddr; CAmount value; // EoS height for 5.3.3 and 5.4.2 is 2121024. if (nHeight >= 2121200) { } else { } { } W rightWeight = getWeightAt(fromIndex) - getWeightAt(rightChild(fromIndex)); // conventional fee, otherwise 0. auto it = indexMap.find(key); if (it == indexMap.end()) { size_t removeIndex = it->second; indexMap.erase(it); TEST(MempoolLimitTests, MempoolLimitTxSetCheckSizeAfterDropping) MempoolLimitTxSet limitSet(MIN_TX_COST * 2); EXPECT_EQ(0, limitSet.getTotalWeight()); limitSet.add(TX_ID1, MIN_TX_COST, MIN_TX_COST); EXPECT_EQ(4000, limitSet.getTotalWeight()); limitSet.add(TX_ID2, MIN_TX_COST, MIN_TX_COST); EXPECT_EQ(8000, limitSet.getTotalWeight()); EXPECT_FALSE(limitSet.maybeDropRandom().has_value()); limitSet.add(TX_ID3, MIN_TX_COST, MIN_TX_COST + LOW_FEE_PENALTY); EXPECT_EQ(12000 + LOW_FEE_PENALTY, limitSet.getTotalWeight()); std::optional drop = limitSet.maybeDropRandom(); ASSERT_EQ(txid == TX_ID3 ? 8000 : 8000 + LOW_FEE_PENALTY, limitSet.getTotalWeight()); TEST(MempoolLimitTests, MempoolCostAndEvictionWeight) auto [cost, evictionWeight] = MempoolCostAndEvictionWeight(builder.Build().GetTxOrThrow(), DEFAULT_FEE); EXPECT_EQ(MIN_TX_COST, cost); EXPECT_EQ(MIN_TX_COST, evictionWeight); auto [cost, evictionWeight] = MempoolCostAndEvictionWeight(builder.Build().GetTxOrThrow(), DEFAULT_FEE-1); EXPECT_EQ(MIN_TX_COST, cost); EXPECT_EQ(MIN_TX_COST + LOW_FEE_PENALTY, evictionWeight); auto [cost, evictionWeight] = MempoolCostAndEvictionWeight(result.GetTxOrThrow(), DEFAULT_FEE); EXPECT_EQ(5168, cost); EXPECT_EQ(5168, evictionWeight); #include #include "weighted_map.h" #include "gtest/utils.h" #include "util/test.h" TEST(WeightedMapTests, WeightedMap) { WeightedMap m; EXPECT_EQ(0, m.size()); EXPECT_TRUE(m.empty()); EXPECT_EQ(0, m.getTotalWeight()); m.checkInvariants(); EXPECT_TRUE(m.add(3, 30, 3)); EXPECT_EQ(1, m.size()); EXPECT_FALSE(m.empty()); EXPECT_EQ(3, m.getTotalWeight()); m.checkInvariants(); EXPECT_TRUE(m.add(1, 10, 2)); EXPECT_EQ(2, m.size()); EXPECT_FALSE(m.empty()); EXPECT_EQ(5, m.getTotalWeight()); m.checkInvariants(); // adding a duplicate element should be ignored EXPECT_FALSE(m.add(1, 15, 64)); EXPECT_EQ(2, m.size()); EXPECT_FALSE(m.empty()); EXPECT_EQ(5, m.getTotalWeight()); m.checkInvariants(); EXPECT_TRUE(m.add(2, 20, 1)); EXPECT_EQ(3, m.size()); EXPECT_FALSE(m.empty()); EXPECT_EQ(6, m.getTotalWeight()); m.checkInvariants(); // regression test: adding three elements and deleting the first caused an invariant violation (not in committed code) EXPECT_EQ(30, m.remove(3).value()); EXPECT_EQ(2, m.size()); EXPECT_FALSE(m.empty()); EXPECT_EQ(3, m.getTotalWeight()); m.checkInvariants(); // try to remove a non-existent element EXPECT_FALSE(m.remove(42).has_value()); EXPECT_EQ(2, m.size()); EXPECT_FALSE(m.empty()); EXPECT_EQ(3, m.getTotalWeight()); m.checkInvariants(); EXPECT_EQ(20, m.remove(2).value()); EXPECT_EQ(1, m.size()); EXPECT_FALSE(m.empty()); EXPECT_EQ(2, m.getTotalWeight()); m.checkInvariants(); EXPECT_TRUE(m.add(2, 20, 1)); EXPECT_EQ(2, m.size()); EXPECT_FALSE(m.empty()); EXPECT_EQ(3, m.getTotalWeight()); m.checkInvariants(); // at this point the map should contain 1->10 (weight 2) and 2->20 (weight 1) auto [e1, c1, w1] = m.takeRandom().value(); EXPECT_TRUE(e1 == 1 || e1 == 2); EXPECT_EQ(c1, e1*10); EXPECT_EQ(w1, 3-e1); EXPECT_EQ(1, m.size()); EXPECT_FALSE(m.empty()); EXPECT_EQ(3-w1, m.getTotalWeight()); m.checkInvariants(); auto [e2, c2, w2] = m.takeRandom().value(); EXPECT_EQ(3, e1 + e2); EXPECT_EQ(c2, e2*10); EXPECT_EQ(w2, 3-e2); EXPECT_EQ(0, m.size()); EXPECT_TRUE(m.empty()); EXPECT_EQ(0, m.getTotalWeight()); m.checkInvariants(); EXPECT_FALSE(m.takeRandom().has_value()); EXPECT_EQ(0, m.size()); EXPECT_TRUE(m.empty()); EXPECT_EQ(0, m.getTotalWeight()); m.checkInvariants(); } TEST(WeightedMapTests, WeightedMapRandomOps) { WeightedMap m; std::map expected; // element -> weight int total_weight = 0; const int iterations = 1000; const int element_range = 20; const int max_weight = 10; static_assert(iterations <= std::numeric_limits::max() / max_weight); // ensure total_weight cannot overflow EXPECT_EQ(0, m.size()); EXPECT_TRUE(m.empty()); EXPECT_EQ(0, m.getTotalWeight()); m.checkInvariants(); for (int i = 0; i < iterations; i++) { switch (GetRandInt(4)) { // probability of add should be balanced with (remove or takeRandom) case 0: case 1: { int e = GetRandInt(element_range); int w = GetRandInt(max_weight) + 1; bool added = m.add(e, e*10, w); EXPECT_EQ(added, expected.count(e) == 0); if (added) { total_weight += w; expected[e] = w; } break; } case 2: { int e = GetRandInt(element_range); auto c = m.remove(e); if (expected.count(e) == 0) { EXPECT_FALSE(c.has_value()); } else { ASSERT_TRUE(c.has_value()); EXPECT_EQ(c.value(), e*10); total_weight -= expected[e]; expected.erase(e); } break; } case 3: { auto r = m.takeRandom(); if (expected.empty()) { EXPECT_FALSE(r.has_value()); } else { ASSERT_TRUE(r.has_value()); auto [e, c, w] = r.value(); EXPECT_EQ(1, expected.count(e)); EXPECT_EQ(c, e*10); EXPECT_EQ(w, expected[e]); total_weight -= expected[e]; expected.erase(e); } break; } } EXPECT_EQ(expected.size(), m.size()); EXPECT_EQ(expected.empty(), m.empty()); EXPECT_EQ(total_weight, m.getTotalWeight()); m.checkInvariants(); } } std::pair MempoolCostAndEvictionWeight(const CTransaction& tx, const CAmount& fee) return std::make_pair(cost, evictionWeight); #include "logging.h" #include "random.h" #include "weighted_map.h" const int64_t MIN_TX_COST = 4000; const int64_t LOW_FEE_PENALTY = 16000; // max(memory usage in bytes, 4000) // // where *fee_penalty* is 16000 if the transaction pays a fee less than the // ZIP 317 conventional fee, otherwise 0. // Calculate cost and eviction weight based on the memory usage and fee. std::pair MempoolCostAndEvictionWeight(const CTransaction& tx, const CAmount& fee); class MempoolLimitTxSet WeightedMap txmap; int64_t capacity; int64_t cost; MempoolLimitTxSet(int64_t capacity_) : capacity(capacity_), cost(0) { int64_t getTotalWeight() const { return txmap.getTotalWeight(); } bool empty() const { return txmap.empty(); } void add(const uint256& txId, int64_t txCost, int64_t txWeight) { if (txmap.add(txId, txCost, txWeight)) { cost += txCost; } } void remove(const uint256& txId) { cost -= txmap.remove(txId).value_or(0); } // If the total cost limit has not been exceeded, return std::nullopt. Otherwise, // pick a transaction at random with probability proportional to its eviction weight; // remove and return that transaction's txid. std::optional maybeDropRandom() { if (cost <= capacity) { return std::nullopt; } LogPrint("mempool", "Mempool cost limit exceeded (cost=%d, limit=%d)\n", cost, capacity); assert(!txmap.empty()); auto [txId, txCost, txWeight] = txmap.takeRandom().value(); cost -= txCost; LogPrint("mempool", "Evicting transaction (txid=%s, cost=%d, weight=%d)\n", txId.ToString(), txCost, txWeight); return txId; } int64_t GetRandInt64(int64_t nMax) { return GetRand(nMax); } int64_t GetRandInt64(int64_t nMax); delete limitSet; auto [cost, evictionWeight] = MempoolCostAndEvictionWeight(entry.GetTx(), entry.GetFee()); limitSet->add(entry.GetTx().GetHash(), cost, evictionWeight); limitSet->remove(tx.GetHash()); total += memusage::DynamicUsage(recentlyEvicted) + memusage::DynamicUsage(limitSet); delete limitSet; limitSet = new MempoolLimitTxSet(totalCostLimit); while ((maybeDropTxId = limitSet->maybeDropRandom()).has_value()) { MempoolLimitTxSet* limitSet = new MempoolLimitTxSet(DEFAULT_MEMPOOL_TOTAL_COST_LIMIT); #ifndef ZCASH_WEIGHTED_MAP_H #define ZCASH_WEIGHTED_MAP_H #include #include #include #include #include // A WeightedMap represents a map from keys (of type K) to values (of type V), // each entry having a weight (of type W). Elements can be randomly selected and // removed from the map with probability in proportion to their weight. This is // used to implement mempool limiting specified in ZIP 401. // // In order to efficiently implement random selection by weight, we keep track // of the total weight of all keys in the map. For performance reasons, the // map is represented as a binary tree where each node knows the sum of the // weights of the children. This allows for addition, removal, and random // selection/dropping in logarithmic time. // // random(w) must be defined to return a uniform random value between zero // inclusive and w exclusive. The type W must support addition, binary and // unary -, and < comparisons, and W() must construct the zero value (these // constraints are met for primitive signed integer types). template class WeightedMap { struct Node { K key; V value; W weight; W sumOfDescendantWeights; }; // The following vector is the tree representation of this collection. // For each node, we keep track of the key, its associated value, // its weight, and the sum of the weights of all its descendants. std::vector nodes; // The following map is to simplify removal. std::map indexMap; static inline size_t leftChild(size_t i) { return i*2 + 1; } static inline size_t rightChild(size_t i) { return i*2 + 2; } static inline size_t parent(size_t i) { return (i-1)/2; } public: // Check internal invariants (for tests). void checkInvariants() const { assert(indexMap.size() == nodes.size()); for (size_t i = 0; i < nodes.size(); i++) { assert(indexMap.at(nodes.at(i).key) == i); assert(nodes.at(i).sumOfDescendantWeights == getWeightAt(leftChild(i)) + getWeightAt(rightChild(i))); } } private: // Return the sum of weights of the node at a given index and all of its descendants. W getWeightAt(size_t index) const { if (index >= nodes.size()) { return W(); } auto& node = nodes.at(index); return node.weight + node.sumOfDescendantWeights; } // When adding and removing a node we need to update its parent and all of its // ancestors to reflect its weight. void backPropagate(size_t fromIndex, W weightDelta) { while (fromIndex > 0) { fromIndex = parent(fromIndex); nodes[fromIndex].sumOfDescendantWeights += weightDelta; } } // For a given random weight, this method recursively finds the index of the // correct entry. This is used by WeightedMap::takeRandom(). size_t findByWeight(size_t fromIndex, W weightToFind) const { W leftWeight = getWeightAt(leftChild(fromIndex)); W rightWeight = getWeightAt(fromIndex) - getWeightAt(rightChild(fromIndex)); // On Left if (weightToFind < leftWeight) { return findByWeight(leftChild(fromIndex), weightToFind); } // Found if (weightToFind < rightWeight) { return fromIndex; } // On Right return findByWeight(rightChild(fromIndex), weightToFind - rightWeight); } public: WeightedMap() {} // Return the total weight of all entries in the map. W getTotalWeight() const { return getWeightAt(0); } // Return true when the map has no entries. bool empty() const { return nodes.empty(); } // Return the number of entries. size_t size() const { return nodes.size(); } // Return false if the key already exists in the map. // Otherwise, add an entry mapping `key` to `value` with the given weight, // and return true. The weight must be positive. bool add(K key, V value, W weight) { assert(W() < weight); if (indexMap.count(key) > 0) { return false; } size_t index = nodes.size(); nodes.push_back(Node { .key = key, .value = value, .weight = weight, .sumOfDescendantWeights = W(), }); indexMap[key] = index; backPropagate(index, weight); return true; } // If the given key is not present in the map, return std::nullopt. // Otherwise, remove that key's entry and return its associated value. std::optional remove(K key) { if (indexMap.count(key) == 0) { return std::nullopt; } size_t removeIndex = indexMap.at(key); V removeValue = nodes.at(removeIndex).value; size_t lastIndex = nodes.size()-1; Node lastNode = nodes.at(lastIndex); W weightDelta = lastNode.weight - nodes.at(removeIndex).weight; backPropagate(lastIndex, -lastNode.weight); if (removeIndex < lastIndex) { nodes[removeIndex].key = lastNode.key; nodes[removeIndex].value = lastNode.value; nodes[removeIndex].weight = lastNode.weight; // nodes[removeIndex].sumOfDescendantWeights should not change here. indexMap[lastNode.key] = removeIndex; backPropagate(removeIndex, weightDelta); } indexMap.erase(key); nodes.pop_back(); return removeValue; } // If the map is empty, return std::nullopt. Otherwise, pick a random entry // with probability proportional to its weight; remove it and return a tuple of // the key, its associated value, and its weight. std::optional> takeRandom() { if (empty()) { return std::nullopt; } W totalWeight = getTotalWeight(); W randomWeight = random(totalWeight); assert(W() <= randomWeight && randomWeight < totalWeight); size_t index = findByWeight(0, randomWeight); assert(index < nodes.size()); const Node& drop = nodes.at(index); auto res = std::make_tuple(drop.key, drop.value, drop.weight); // copy values remove(drop.key); return res; } }; #endif // ZCASH_WEIGHTED_MAP_H pfrom->AddKnownWTxId(WTxId(inv.hash, inv.hashAux)); pfrom->AddKnownWTxId(wtxid); pto->AddKnownTxId(hash); if (pto->HasKnownTxId(hash)) { pto->AddKnownTxId(hash); // Inventory based relay // This filter is protected by cs_inventory and contains both txids and wtxids. CRollingBloomFilter filterInventoryKnown; mutable CCriticalSection cs_inventory; void AddKnownWTxId(const WTxId& wtxid) void AddKnownTxId(const uint256& txid) { LOCK(cs_inventory); if (!fDisconnect) { filterInventoryKnown.insert(txid); } } bool HasKnownTxId(const uint256& txid) const { LOCK(cs_inventory); return filterInventoryKnown.contains(txid); } pfrom->AddAddressIfNotAlreadyKnown(addr); if (pto->AddAddressIfNotAlreadyKnown(addr)) // Avoid possibly adding to pto->filterInventoryKnown after it has been reset in CloseSocketDisconnect. if (pto->fDisconnect) { // We can safely return here because SendMessages would, in any case, do nothing after // this block if pto->fDisconnect is set. return true; } { LOCK(cs_addrKnown); addrKnown.reset(); } { LOCK(cs_inventory); filterInventoryKnown.reset(); } CRollingBloomFilter addrKnown; mutable CCriticalSection cs_addrKnown; // List of block ids we still have to announce. bool AddAddressIfNotAlreadyKnown(const CAddress& addr) { LOCK(cs_addrKnown); // Avoid adding to addrKnown after it has been reset in CloseSocketDisconnect. if (fDisconnect) { return false; } if (!addrKnown.contains(addr.GetKey())) { addrKnown.insert(addr.GetKey()); return true; } else { return false; } } bool IsAddressKnown(const CAddress& addr) const LOCK(cs_addrKnown); return addrKnown.contains(addr.GetKey()); if (addr.IsValid() && !IsAddressKnown(addr)) { LOCK(cs_inventory); if (!fDisconnect) { if (!fDisconnect && !filterInventoryKnown.contains(wtxid.ToBytes())) { if (!fDisconnect) { vInventoryBlockToSend.push_back(hash); } nFilterBits = (uint32_t)ceil(-1.0 * nHashFuncs * nMaxElements / log(1.0 - exp(logFpRate / nHashFuncs))); if (data.empty()) { initialize(); } if (data.empty()) { return false; } void CRollingBloomFilter::reset() { std::vector().swap(data); } void CRollingBloomFilter::initialize() /* For each data element we need to store 2 bits. If both bits are 0, the * bit is treated as unset. If the bits are (01), (10), or (11), the bit is * treated as set in generation 1, 2, or 3 respectively. * These bits are stored in separate integers: position P corresponds to bit * (P & 63) of the integers data[(P >> 6) * 2] and data[(P >> 6) * 2 + 1]. */ data.resize(((nFilterBits + 63) / 64) << 1); protected: bool is_data_empty() const { return data.empty(); } void initialize(); uint32_t nFilterBits; BOOST_AUTO_TEST_CASE(rolling_bloom_reset) { struct TestRollingBloomFilter : CRollingBloomFilter { TestRollingBloomFilter() : CRollingBloomFilter(100, 0.01) {} bool is_data_empty() const { return CRollingBloomFilter::is_data_empty(); } }; TestRollingBloomFilter rb; BOOST_CHECK(rb.is_data_empty()); std::vector d = RandomData(); rb.insert(d); BOOST_CHECK(!rb.is_data_empty()); BOOST_CHECK(rb.contains(d)); // reset() should ensure minimal memory usage. rb.reset(); BOOST_CHECK(rb.is_data_empty()); BOOST_CHECK(!rb.contains(d)); rb.insert(d); BOOST_CHECK(!rb.is_data_empty()); BOOST_CHECK(rb.contains(d)); } static const int64_t WALLET_INITIAL_SYNC_TIMEOUT = 1000 * 60 * 60 * 2; UniValue dumpwallet(const UniValue& params, bool fHelp) { throw JSONRPCError(RPC_METHOD_NOT_FOUND, "dumpwallet has been removed. Use z_exportwallet instead."); } std::set sproutAddresses; pwalletMain->GetSproutPaymentAddresses(sproutAddresses); file << "\n"; file << "# Zkeys\n"; file << "\n"; for (auto addr : sproutAddresses) { libzcash::SproutSpendingKey key; if (pwalletMain->GetSproutSpendingKey(addr, key)) { std::string strTime = EncodeDumpTime(pwalletMain->mapSproutZKeyMetadata[addr].nCreateTime); file << strprintf("%s %s # zaddr=%s\n", keyIO.EncodeSpendingKey(key), strTime, keyIO.EncodePaymentAddress(addr)); } std::set saplingAddresses; pwalletMain->GetSaplingPaymentAddresses(saplingAddresses); file << "\n"; file << "# Sapling keys\n"; file << "\n"; for (auto addr : saplingAddresses) { libzcash::SaplingExtendedSpendingKey extsk; if (pwalletMain->GetSaplingExtendedSpendingKey(addr, extsk)) { auto ivk = extsk.expsk.full_viewing_key().in_viewing_key(); CKeyMetadata keyMeta = pwalletMain->mapSaplingZKeyMetadata[ivk]; std::string strTime = EncodeDumpTime(keyMeta.nCreateTime); file << strprintf("%s %s", keyIO.EncodeSpendingKey(extsk), strTime); // Keys imported with z_importkey do not have zip32 metadata if (!(keyMeta.hdKeypath.empty() || keyMeta.seedFp.IsNull())) { file << strprintf(" %s %s", keyMeta.hdKeypath, keyMeta.seedFp.GetHex()); file << strprintf(" # zaddr=%s\n", keyIO.EncodePaymentAddress(addr)); file << "\n"; #include tl::expected CCoinsViewCache::CheckShieldedRequirements(const CTransaction& tx) const return tl::unexpected(UnsatisfiedShieldedReq::SproutDuplicateNullifier); return tl::unexpected(UnsatisfiedShieldedReq::SproutUnknownAnchor); return tl::unexpected(UnsatisfiedShieldedReq::SaplingDuplicateNullifier); return tl::unexpected(UnsatisfiedShieldedReq::SaplingUnknownAnchor); return tl::unexpected(UnsatisfiedShieldedReq::OrchardDuplicateNullifier); return tl::unexpected(UnsatisfiedShieldedReq::OrchardUnknownAnchor); return {}; #include tl::expected CheckShieldedRequirements(const CTransaction& tx) const; auto unmetShieldedReq = view.CheckShieldedRequirements(tx); if (!unmetShieldedReq.has_value()) { auto rejectCode = ShieldedReqRejectCode(unmetShieldedReq.error()); auto rejectReason = ShieldedReqRejectReason(unmetShieldedReq.error()); BOOST_CHECK(cache.CheckShieldedRequirements(mtx) == tl::unexpected(UnsatisfiedShieldedReq::SproutUnknownAnchor)); BOOST_CHECK(cache.CheckShieldedRequirements(mtx) == tl::unexpected(UnsatisfiedShieldedReq::SproutUnknownAnchor)); BOOST_CHECK(cache.CheckShieldedRequirements(mtx).has_value()); BOOST_CHECK(cache.CheckShieldedRequirements(mtx).has_value()); BOOST_CHECK(cache.CheckShieldedRequirements(mtx).has_value()); #define CLIENT_VERSION_REVISION 2 static const int APPROX_RELEASE_HEIGHT = 1900500; #define CLIENT_VERSION_BUILD 50 static const int APPROX_RELEASE_HEIGHT = 1898500; bool CBlockTreeDB::ReadBlockFileInfo(int nFile, CBlockFileInfo &info) const { bool CBlockTreeDB::ReadReindexing(bool &fReindexing) const { bool CBlockTreeDB::ReadLastBlockFile(int &nFile) const { bool CBlockTreeDB::ReadDiskBlockIndex(const uint256 &blockhash, CDiskBlockIndex &dbindex) const { bool CBlockTreeDB::ReadTxIndex(const uint256 &txid, CDiskTxPos &pos) const { bool CBlockTreeDB::ReadSpentIndex(CSpentIndexKey &key, CSpentIndexValue &value) const { bool CBlockTreeDB::ReadTimestampBlockIndex(const uint256 &hash, unsigned int <imestamp) const bool CBlockTreeDB::ReadFlag(const std::string &name, bool &fValue) const { bool ReadBlockFileInfo(int nFile, CBlockFileInfo &info) const; bool ReadLastBlockFile(int &nFile) const; bool ReadReindexing(bool &fReindexing) const; bool ReadDiskBlockIndex(const uint256 &blockhash, CDiskBlockIndex &dbindex) const; bool ReadTxIndex(const uint256 &txid, CDiskTxPos &pos) const; bool ReadSpentIndex(CSpentIndexKey &key, CSpentIndexValue &value) const; bool ReadTimestampBlockIndex(const uint256 &hash, unsigned int &logicalTS) const; bool ReadFlag(const std::string &name, bool &fValue) const; #include MetricsIncrementCounter("zcashd.debug.memory.trimmed_equihash_solutions"); MetricsIncrementCounter("zcashd.debug.blocktree.trimmed_equihash_read_dbindex"); #include MetricsIncrementCounter("zcashd.debug.memory.allocated_equihash_solutions"); #include MetricsIncrementCounter("zcashd.debug.blocktree.write_batch"); MetricsIncrementCounter("zcashd.debug.blocktree.write_batch_read_dbindex"); if (!pblocktree->ReadDiskBlockIndex(GetBlockHash(), dbindex)) { LogPrintf("%s: Failed to read index entry", __func__); throw std::runtime_error("Failed to read index entry"); } // try { // assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash()); // Perhaps too slow // } catch (const runtime_error&) { // assert(!"Failed to read index entry"); // } try { for (const CBlockIndex *pindex : headers) { ssHeader << pindex->GetBlockHeader(); } } catch (const std::runtime_error&) { return RESTERR(req, HTTP_INTERNAL_SERVER_ERROR, "Failed to read index entry"); try { if (!fVerbose) { CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION); ssBlock << pblockindex->GetBlockHeader(); std::string strHex = HexStr(ssBlock.begin(), ssBlock.end()); return strHex; } else { return blockheaderToJSON(pblockindex); } } catch (const runtime_error&) { throw JSONRPCError(RPC_DATABASE_ERROR, "Failed to read index entry"); try { header = pindexNew->GetBlockHeader(); } catch (const runtime_error&) { return error("LoadBlockIndex(): failed to read index entry: diskindex hash = %s", diskindex.GetBlockHash().ToString()); } #include "main.h" #include "txdb.h" void CBlockIndex::TrimSolution() { AssertLockHeld(cs_main); // We can correctly trim a solution as soon as the block index entry has been added // to leveldb. Updates to the block index entry (to update validity status) will be // handled by re-reading the solution from the existing db entry. It does not help to // try to avoid these reads by gating trimming on the validity status: the re-reads are // efficient anyway because of caching in leveldb, and most of them are unavoidable. if (HasSolution()) { MetricsIncrementCounter("zcashd.trimmed_equihash_solutions"); std::vector empty; nSolution.swap(empty); } } CBlockHeader CBlockIndex::GetBlockHeader() const { AssertLockHeld(cs_main); CBlockHeader header; header.nVersion = nVersion; if (pprev) { header.hashPrevBlock = pprev->GetBlockHash(); } header.hashMerkleRoot = hashMerkleRoot; header.hashBlockCommitments = hashBlockCommitments; header.nTime = nTime; header.nBits = nBits; header.nNonce = nNonce; if (HasSolution()) { header.nSolution = nSolution; } else { CDiskBlockIndex dbindex; assert(pblocktree->ReadDiskBlockIndex(GetBlockHash(), dbindex)); header.nSolution = dbindex.GetSolution(); } return header; } #include "util/strencodings.h" protected: // The Equihash solution, if it is stored. Once we know that the block index // entry is present in leveldb, this field can be cleared via the TrimSolution // method to save memory. public: //! Get the block header for this block index. Requires cs_main. CBlockHeader GetBlockHeader() const; //! Clear the Equihash solution to save memory. Requires cs_main. void TrimSolution(); return strprintf("CBlockIndex(pprev=%p, nHeight=%d, merkle=%s, hashBlock=%s, HasSolution=%s)", phashBlock ? GetBlockHash().ToString() : "(nil)", HasSolution()); //! Is the Equihash solution stored? bool HasSolution() const { return !nSolution.empty(); } explicit CDiskBlockIndex(const CBlockIndex* pindex, std::function()> getSolution) : CBlockIndex(*pindex) { if (!HasSolution()) { nSolution = getSolution(); } //! Get the block header for this block index. CBlockHeader GetBlockHeader() const { CBlockHeader header; header.nVersion = nVersion; header.hashPrevBlock = hashPrev; header.hashMerkleRoot = hashMerkleRoot; header.hashBlockCommitments = hashBlockCommitments; header.nTime = nTime; header.nBits = nBits; header.nNonce = nNonce; header.nSolution = nSolution; return header; } return GetBlockHeader().GetHash(); std::vector GetSolution() const { assert(HasSolution()); return nSolution; } private: //! This method should not be called on a CDiskBlockIndex. void TrimSolution() { assert(!"called CDiskBlockIndex::TrimSolution"); } std::vector vBlocks; // Now that we have written the block indices to the database, we do not // need to store solutions for these CBlockIndex objects in memory. // cs_main must be held here. for (CBlockIndex *pblockindex : vBlocks) { pblockindex->TrimSolution(); } CDataStream ssHeader(SER_NETWORK, PROTOCOL_VERSION); if (rf == RF_BINARY || rf == RF_HEX) { for (const CBlockIndex *pindex : headers) { ssHeader << pindex->GetBlockHeader(); } } result.pushKV("solution", HexStr(blockindex->GetBlockHeader().nSolution)); bool CBlockTreeDB::WriteBatchSync(const std::vector >& fileInfo, int nLastFile, const std::vector& blockinfo) { std::pair key = make_pair(DB_BLOCK_INDEX, (*it)->GetBlockHash()); try { CDiskBlockIndex dbindex {*it, [this, &key]() { // It can happen that the index entry is written, then the Equihash solution is cleared from memory, // then the index entry is rewritten. In that case we must read the solution from the old entry. CDiskBlockIndex dbindex_old; if (!Read(key, dbindex_old)) { LogPrintf("%s: Failed to read index entry", __func__); throw runtime_error("Failed to read index entry"); } return dbindex_old.GetSolution(); }}; batch.Write(key, dbindex); } catch (const runtime_error&) { return false; } bool CBlockTreeDB::ReadDiskBlockIndex(const uint256 &blockhash, CDiskBlockIndex &dbindex) { return Read(make_pair(DB_BLOCK_INDEX, blockhash), dbindex); } // the Equihash solution will be loaded lazily from the dbindex entry CBlockHeader header; { LOCK(cs_main); header = pindexNew->GetBlockHeader(); } bool WriteBatchSync(const std::vector >& fileInfo, int nLastFile, const std::vector& blockinfo); bool ReadDiskBlockIndex(const uint256 &blockhash, CDiskBlockIndex &dbindex); assert(phashBlock); phashBlock ? GetBlockHash().ToString() : "(nil)"); if (header.GetHash() != diskindex.GetBlockHash()) return error("LoadBlockIndex(): inconsistent header vs diskindex hash: header hash = %s, diskindex hash = %s", header.GetHash().ToString(), diskindex.GetBlockHash().ToString()); diskindex.ToString(), pindexNew->ToString()); // There is no need to read and scan blocks that were created before // our wallet birthday (as adjusted for block time variability). // If there is an Orchard wallet checkpoint, the rewind point must not // be advanced past the last Orchard wallet checkpoint height. auto optOrchardCheckpointHeight = orchardWallet.GetLastCheckpointHeight(); while (chainActive.Next(pindex) != NULL && nTimeFirstKey && pindex->GetBlockTime() < nTimeFirstKey - TIMESTAMP_WINDOW && (!optOrchardCheckpointHeight.has_value() || pindex->nHeight < optOrchardCheckpointHeight.value())) { if (optOrchardCheckpointHeight.has_value()) { optOrchardCheckpointHeight.value()); auto& orchard_bundle = tx.GetOrchardBundle(); throw std::logic_error("Called WalletBatchScanner::AddToWalletIfInvolvingMe with a tx that wasn't passed to AddTransaction"); SystemClock(SystemClock const&) = delete; SystemClock& operator=(const SystemClock&) = delete; FixedClock(FixedClock const&) = delete; FixedClock& operator=(const FixedClock&) = delete; OffsetClock(OffsetClock const&) = delete; OffsetClock& operator=(const OffsetClock&) = delete; const auto& params = Params().GetConsensus(); wallet.IncrementNoteWitnesses(params, &index, &block, frontiers, true); EXPECT_DEATH(::GetWitnessesAndAnchors(wallet, sproutNotes, saplingNotes, sproutWitnesses, saplingWitnesses), ".*it != end.*"); for (int i = 1; i <= 8; i++) { CBlock another_block; CBlockIndex another_index(another_block); another_index.nHeight = i; wallet.IncrementNoteWitnesses(params, &another_index, &another_block, frontiers, true); } EXPECT_DEATH(::GetWitnessesAndAnchors(wallet, sproutNotes, saplingNotes, sproutWitnesses, saplingWitnesses), ".*it != end.*"); CBlock last_block; CBlockIndex last_index(last_block); last_index.nHeight = 9; wallet.IncrementNoteWitnesses(params, &last_index, &last_block, frontiers, true); for (int i = 9; i >= 1; i--) { CBlock another_block; CBlockIndex another_index(another_block); another_index.nHeight = i; wallet.DecrementNoteWitnesses(params, &another_index); } EXPECT_DEATH(wallet.DecrementNoteWitnesses(params, &index), pwalletMain->GetFilteredNotes(sproutEntries, saplingEntries, orchardEntries, noteFilter, nAnchorConfirmations); auto noteWitnesses = mapWallet[note.hash].mapSproutNoteData[note].witnesses; auto it = noteWitnesses.cbegin(), end = noteWitnesses.cend(); for (int i = 1; i < nAnchorConfirmations; i++) { assert(it != end); ++it; } assert(it != end); witnesses[i] = *it; auto noteWitnesses = mapWallet[note.hash].mapSaplingNoteData[note].witnesses; auto it = noteWitnesses.cbegin(), end = noteWitnesses.cend(); for (int i = 1; i < nAnchorConfirmations; i++) { assert(it != end); ++it; } assert(it != end); witnesses[i] = *it; "3. minconf (numeric, optional, default=" + strprintf("%u", nAnchorConfirmations) + ") Only use funds confirmed at least this many times.\n" int nMinDepth = nAnchorConfirmations; auto orchardAnchorHeight = nextBlockHeight - std::min((unsigned int) nMinDepth, nAnchorConfirmations); auto orchardAnchorHeight = nextBlockHeight - nAnchorConfirmations; auto orchardAnchorHeight = nextBlockHeight - nAnchorConfirmations; unsigned int nAnchorConfirmations = DEFAULT_ANCHOR_CONFIRMATIONS; if (mapArgs.count("-anchorconfirmations")) { int64_t confirmations = atoi64(mapArgs["-anchorconfirmations"]); return UIError(strprintf(_("Invalid value for -anchorconfirmations='%u' (must be least 1)"), confirmations)); nAnchorConfirmations = confirmations; extern unsigned int nAnchorConfirmations; //! -anchorconfirmations default static const unsigned int DEFAULT_ANCHOR_CONFIRMATIONS = 10; int minDepth, #ifdef ENABLE_WALLET strUsage += HelpMessageOpt("-reindex-chainstate", _("Rebuild chain state from the currently indexed blocks (implies -rescan unless pruning or unless -rescan=0 is explicitly specified")); strUsage += HelpMessageOpt("-reindex", _("Rebuild chain state and block index from the blk*.dat files on disk (implies -rescan unless pruning or unless -rescan=0 is explicitly specified)")); #else #endif #ifdef ENABLE_WALLET // -rescan only affects the wallet. if (GetBoolArg("-reindex", false) && !GetArg("-prune", 0)) { if (SoftSetBoolArg("-rescan", true)) LogPrintf("%s: parameter interaction: -reindex=1 and not pruning -> setting -rescan=1\n", __func__); } if (GetBoolArg("-reindex-chainstate", false) && !GetArg("-prune", 0)) { if (SoftSetBoolArg("-rescan", true)) LogPrintf("%s: parameter interaction: -reindex-chainstate=1 and not pruning -> setting -rescan=1\n", __func__); } #endif strUsage += HelpMessageOpt("-salvagewallet", _("Attempt to recover private keys from a corrupt wallet on startup (implies -rescan)")); // Check for conflicts with in-memory transactions. // This is redundant with the call to HaveInputs (for non-coinbase transactions) // below, but we do it here for consistency with Bitcoin and because this check // doesn't require loading the coins view. // We don't do the corresponding check for nullifiers, because that would also // be redundant, and we have no need to avoid semantic conflicts with Bitcoin // backports in the case of the shielded protocol. checkNullifiers(ORCHARD); #ifndef ZCASH_GTEST_DATA_TX_ORCHARD_DUPLICATE_NULLIFIERS_H #define ZCASH_GTEST_DATA_TX_ORCHARD_DUPLICATE_NULLIFIERS_H #endif // ZCASH_GTEST_DATA_TX_ORCHARD_DUPLICATE_NULLIFIERS_H if (!GetBoolArg("-reindex", false)) { CBanDB bandb; banmap_t banmap; if (bandb.Read(banmap)) { CNode::SetBanned(banmap); // thread save setter CNode::SetBannedSetDirty(false); // no need to write down, just read data CNode::SweepBanned(); // sweep out unused entries LogPrint("net", "Loaded %d banned node ips/subnets from banlist.dat %dms\n", banmap.size(), GetTimeMillis() - nStart); } else { LogPrintf("Invalid or missing banlist.dat; recreating\n"); CNode::SetBannedSetDirty(true); // force write DumpBanlist(); } LogPrintf("Clearing banlist.dat for reindex\n"); strUsage += HelpMessageOpt("-datadir=", _("Specify data directory (this path cannot use '~')")); strUsage += HelpMessageOpt("-datadir=", _("Specify data directory (this path cannot use '~')")); "\nCAUTION: This is an internal method that is not intended to be called directly by\n" "users. Please use the zcashd-wallet-tool utility (built or installed in the same directory\n" "as zcashd) instead. In particular, this method should not be used from zcash-cli, in order\n" "to avoid exposing the recovery phrase on the command line.\n\n" "Notify the wallet that the user has backed up the emergency recovery phrase,\n" _clear(); // unlocked clear void _clear(); // unlocked error("ConnectBlock(): block would overfill the Orchard commitment tree."), #include #include WeightedTxInfo info = WeightedTxInfo::from(builder.Build().GetTxOrThrow(), DEFAULT_FEE); builder.SetFee(DEFAULT_FEE-1); WeightedTxInfo info = WeightedTxInfo::from(result.GetTxOrThrow(), DEFAULT_FEE); #include "policy/fees.h" CAmount CFeeRate::GetFeeForRelay(size_t nSize) const { return std::min(GetFee(nSize), DEFAULT_FEE); } CAmount nSatoshisPerK; // unit is zatoshis-per-1,000-bytes CAmount GetFeeForRelay(size_t size) const; // unit returned is zatoshis CAmount GetFee(size_t size) const; // unit returned is zatoshis CAmount GetFeePerK() const { return GetFee(1000); } // zatoshis-per-1000-bytes CAmount nMinFee = ::minRelayTxFee.GetFeeForRelay(nBytes); // Before zcashd 4.2.0, we had a condition here to always accept a tx if it contained // JoinSplits and had at least the default fee. It is no longer necessary to treat // that as a special case, because the fee returned by GetMinRelayFee is always at // most DEFAULT_FEE. CAmount txMinFee = GetMinRelayFee(tx, nSize, true); if (fLimitFree && nFees < txMinFee) { return state.DoS(0, error("AcceptToMemoryPool: not enough fees %s, %d < %d", hash.ToString(), nFees, txMinFee), REJECT_INSUFFICIENTFEE, "insufficient fee"); if (GetBoolArg("-relaypriority", DEFAULT_RELAYPRIORITY) && nFees < ::minRelayTxFee.GetFeeForRelay(nSize) && !AllowFree(view.GetPriority(tx, chainActive.Height() + 1))) { if (fLimitFree && nFees < ::minRelayTxFee.GetFeeForRelay(nSize)) if (nFeeNeeded < ::minRelayTxFee.GetFeeForRelay(nBytes)) return std::max(minTxFee.GetFee(nTxBytes), ::minRelayTxFee.GetFeeForRelay(nTxBytes)); if (nFeeNeeded < ::minRelayTxFee.GetFeeForRelay(nTxBytes)) nFeeNeeded = ::minRelayTxFee.GetFeeForRelay(nTxBytes); static_assert(DEFAULT_FEE == 1000); WeightedTxInfo info = WeightedTxInfo::from(builder.Build().GetTxOrThrow(), DEFAULT_FEE-1); // 0.0005 t-ZEC in, 0.0004 z-ZEC out, default fee // 0.0004 z-ZEC in, 0.00025 z-ZEC out, default fee, 0.00005 z-ZEC change // - default t-ZEC fee // 0.0005 z-ZEC out, default fee // 0.0005 t-ZEC out, default fee // 0.0005 t-ZEC out, default fee, 0.00059999 z-ZEC in // Accept a tx if it contains joinsplits and has at least the default fee for z_* operations. if (tx.vJoinSplit.size() > 0 && nFees >= DEFAULT_FEE) { #include "policy/fees.h" // in order to prevent them from being re-accepted for a given amount of time. RecentlyEvictedList(size_t capacity_, int64_t timeToKeep_) : capacity(capacity_), timeToKeep(timeToKeep_) static const CAmount DEFAULT_FEE = 1000; CAmount fee = DEFAULT_FEE, LogPrint("zrpcunsafe", "%s: Beginning creating transaction with Sapling output amount=%s\n", getId(), FormatMoney(amountToSend - DEFAULT_FEE)); // The amount chosen *includes* the default fee for this transaction, i.e. // the value of the Sapling output will be 0.00001 ZEC less. builder.SetFee(DEFAULT_FEE); builder.AddSaplingOutput(ovkForShieldingFromTaddr(seed), migrationDestAddress, amountToSend - DEFAULT_FEE); amountMigrated += amountToSend - DEFAULT_FEE; CAmount fee = DEFAULT_FEE, CAmount fee = DEFAULT_FEE, // 0.0005 t-ZEC in, 0.0004 z-ZEC out, default fee // 0.0004 z-ZEC in, 0.00025 z-ZEC out, default fee, 0.00005 z-ZEC change + strprintf("%s", FormatMoney(DEFAULT_FEE)) + ") The fee amount to attach to this transaction.\n" CAmount nFee = DEFAULT_FEE; + strprintf("%s", FormatMoney(DEFAULT_FEE)) + ") The fee amount to attach to this transaction.\n" CAmount nFee = DEFAULT_FEE; + strprintf("%s", FormatMoney(DEFAULT_FEE)) + ") The fee amount to attach to this transaction.\n" CAmount nFee = DEFAULT_FEE; #include "policy/fees.h" // for DEFAULT_FEE "1 -0.00001" "-0.00001" CheckRPCThrows("z_mergetoaddress [\"" + taddr1 + "\"] " + taddr2 + " -0.00001", CheckRPCThrows("z_mergetoaddress [\"" + taddr1 + "\"] " + taddr2 + " 0.00001 -1", CheckRPCThrows("z_mergetoaddress [\"" + taddr1 + "\"] " + taddr2 + " 0.00001 100 -1", CheckRPCThrows("z_mergetoaddress [\"" + taddr1 + "\"] " + aSproutAddr + " 0.00001 100 100 " + badmemo, BOOST_CHECK( msg.find("Insufficient funds, have 0.00 and miners fee is 0.00001") != string::npos); // The protocol specification leaves MeanTarget(height) as a rational, and takes the floor // only after dividing by AveragingWindowTimespan in the computation of Threshold(height): // // // Here we take the floor of MeanTarget(height) immediately, but that is equivalent to doing // so only after a further division, as proven in . "\nNOTE: If \"blockhash\" is not provided and the -txindex option is not enabled, then this call only\n" "works for mempool transactions. If either \"blockhash\" is provided or the -txindex option is\n" "2. verbose (numeric, optional, default=0) If 0, return a string of hex-encoded data, otherwise return a JSON object\n" Consensus::FS_ZIP214_BP, Consensus::FS_ZIP214_BP, FS_ZIP214_BP, const auto FIRST_FUNDING_STREAM = FS_ZIP214_BP; // The "threadsafe" style is necessary for correct operation of death/exit // tests on macOS (https://github.com/zcash/zcash/issues/4802). testing::FLAGS_gtest_death_test_style = "threadsafe"; error("ContextualCheckTransaction(): fOverwintered flag must be set when Overwinter is active"), error("ContextualCheckTransaction(): overwinter version too high"), error("ContextualCheckTransaction(): invalid Overwinter tx version"), error("ContextualCheckTransaction(): invalid Sapling tx version"), error("ContextualCheckTransaction(): Sapling version too low"), error("ContextualCheckTransaction(): Sapling version too high"), error("ContextualCheckTransaction(): coinbase output description has invalid outCiphertext"), error("ContextualCheckTransaction(): coinbase output description has invalid encCiphertext"), error("ContextualCheckTransaction(): coinbase output description has invalid note plaintext version"), error("ContextualCheckTransaction(): coinbase has output descriptions"), return state.DoS(DOS_LEVEL_BLOCK, error("ContextualCheckTransaction(): joinsplit.vpub_old nonzero"), REJECT_INVALID, "bad-txns-vpub_old-nonzero"); return state.DoS(100, error("ContextualCheckTransaction(): funding stream missing at height %d", nHeight), return state.DoS(100, error("ContextualCheckTransaction(): error computing signature hash"), REJECT_INVALID, "error-computing-signature-hash"); error("ContextualCheckTransaction(): invalid joinsplit signature"), // Sapling zk-SNARK proofs are checked in librustzcash_sapling_check_{spend,output}, // called from ContextualCheckTransaction. std::string DisplayDuration(int64_t duration, DurationFormat format) int64_t days = duration / (24 * 60 * 60); int64_t hours = (duration - (days * 24 * 60 * 60)) / (60 * 60); int64_t minutes = (duration - (((days * 24) + hours) * 60 * 60)) / 60; int64_t seconds = duration - (((((days * 24) + hours) * 60) + minutes) * 60); int64_t days = time / (24 * 60 * 60); int64_t hours = (time - (days * 24 * 60 * 60)) / (60 * 60); int64_t minutes = (time - (((days * 24) + hours) * 60 * 60)) / 60; int64_t seconds = time - (((((days * 24) + hours) * 60) + minutes) * 60); log2(pindexNew->nChainWork.getdouble()), DateTimeStrFormat("%Y-%m-%d %H:%M:%S", tip->GetBlockHash().ToString(), chainActive.Height(), log2(tip->nChainWork.getdouble()), auto log2_work = tfm::format("%.8g", log2(chainActive.Tip()->nChainWork.getdouble())); statusbar.second = rpc.second = GetTime(); statusbar.second = rpc.second = GetTime(); statusbar.second = GetTime(); rpc.second = statusbar.second; std::vector recipients = { SendManyRecipient("dummy", 1*COIN, "") }; std::vector recipients = { SendManyRecipient("dummy", 1*COIN, "") }; std::vector recipients = { SendManyRecipient("dummy", 1*COIN, "") }; std::vector recipients = { SendManyRecipient(zaddr1, 100*COIN, "DEADBEEF") }; std::vector recipients = {SendManyRecipient(taddr1, 100*COIN, "DEADBEEF")}; std::vector recipients = { SendManyRecipient(taddr1, 100*COIN, "DEADBEEF") }; std::vector recipients = { SendManyRecipient(zaddr1, 100*COIN, "DEADBEEF") }; std::vector recipients = { SendManyRecipient(zaddr1, 100*COIN, "DEADBEEF") }; CAmount amount = 12345600000; amount = 111100000; SendManyRecipient("tmTGScYwiLMzHe4uGZtBYmuqoW4iEoYNMXt", 123000000, ""), SendManyRecipient("tmUSbHz3vxnwLvRyNDXbwkZxjVyDodMJEhh", 456000000, ""), SendManyRecipient("tmYZAXYPCP56Xa5JQWWPZuK7o7bfUQW6kkd", 789000000, ""), BOOST_CHECK_EQUAL(tx.vout[0].nValue, 123000000); BOOST_CHECK_EQUAL(tx.vout[1].nValue, 456000000); BOOST_CHECK_EQUAL(tx.vout[2].nValue, 789000000); std::vector recipients = { SendManyRecipient(zaddr1, 50000, "ABCD") }; std::vector recipients = { SendManyRecipient(zaddr1, 1*COIN, "ABCD") }; #include using namespace boost::placeholders; #include using namespace boost::placeholders; #include using namespace boost::placeholders; "rand, receiveunsafe, reindex, rpc, selectcoins, tor, zmq, zrpc, zrpcunsafe (implies zrpc)"; // Don't translate these LogPrint("receiveunsafe", "Received note plaintext with invalid lead byte %d at height %d", plaintext.get_leadbyte(), height); LogPrint("receiveunsafe", "Received note plaintext with invalid lead byte %d at height %d", plaintext.get_leadbyte(), height); inline bool operator==(const int64_t& rhs) const { return m_value == rhs; } inline bool operator!=(const int64_t& rhs) const { return m_value != rhs; } inline bool operator<=(const int64_t& rhs) const { return m_value <= rhs; } inline bool operator< (const int64_t& rhs) const { return m_value < rhs; } inline bool operator>=(const int64_t& rhs) const { return m_value >= rhs; } inline bool operator> (const int64_t& rhs) const { return m_value > rhs; } inline CScriptNum& operator=( const int64_t& rhs) inline bool operator==(const int64_t& rhs) const { return m_value == rhs; } inline bool operator!=(const int64_t& rhs) const { return m_value != rhs; } inline bool operator<=(const int64_t& rhs) const { return m_value <= rhs; } inline bool operator< (const int64_t& rhs) const { return m_value < rhs; } inline bool operator>=(const int64_t& rhs) const { return m_value >= rhs; } inline bool operator> (const int64_t& rhs) const { return m_value > rhs; } inline CScriptNum10 operator-() const inline CScriptNum10& operator=( const int64_t& rhs) BOOST_CHECK((bignum1 != bignum1) == (scriptnum1 != scriptnum1)); BOOST_CHECK((bignum1 < bignum1) == (scriptnum1 < scriptnum1)); BOOST_CHECK((bignum1 > bignum1) == (scriptnum1 > scriptnum1)); BOOST_CHECK((bignum1 >= bignum1) == (scriptnum1 >= scriptnum1)); BOOST_CHECK((bignum1 <= bignum1) == (scriptnum1 <= scriptnum1)); BOOST_CHECK((bignum1 != bignum1) == (scriptnum1 != num1)); BOOST_CHECK((bignum1 < bignum1) == (scriptnum1 < num1)); BOOST_CHECK((bignum1 > bignum1) == (scriptnum1 > num1)); BOOST_CHECK((bignum1 >= bignum1) == (scriptnum1 >= num1)); BOOST_CHECK((bignum1 <= bignum1) == (scriptnum1 <= num1)); BOOST_CHECK((bignum1 == bignum2) == (scriptnum1 == scriptnum2)); BOOST_CHECK((bignum1 != bignum2) == (scriptnum1 != scriptnum2)); BOOST_CHECK((bignum1 < bignum2) == (scriptnum1 < scriptnum2)); BOOST_CHECK((bignum1 > bignum2) == (scriptnum1 > scriptnum2)); BOOST_CHECK((bignum1 >= bignum2) == (scriptnum1 >= scriptnum2)); BOOST_CHECK((bignum1 <= bignum2) == (scriptnum1 <= scriptnum2)); BOOST_CHECK((bignum1 == bignum2) == (scriptnum1 == num2)); BOOST_CHECK((bignum1 != bignum2) == (scriptnum1 != num2)); BOOST_CHECK((bignum1 < bignum2) == (scriptnum1 < num2)); BOOST_CHECK((bignum1 > bignum2) == (scriptnum1 > num2)); BOOST_CHECK((bignum1 >= bignum2) == (scriptnum1 >= num2)); BOOST_CHECK((bignum1 <= bignum2) == (scriptnum1 <= num2)); CheckCreateVch(num); } else { BOOST_CHECK_THROW(CheckCreateVch(num), scriptnum10_error); for (size_t i = 0; i < sizeof(values) / sizeof(values[0]); ++i) for (size_t j = 0; j < sizeof(offsets) / sizeof(offsets[0]); ++j) for (size_t i = 0; i < sizeof(values) / sizeof(values[0]); ++i) static void CheckCreateVch(int64_t num) static void CheckCreateInt(int64_t num) static void CheckAdd(int64_t num1, int64_t num2) static void CheckNegate(int64_t num) static void CheckSubtract(int64_t num1, int64_t num2) static void CheckCompare(int64_t num1, int64_t num2) static void RunCreate(int64_t num) static void RunOperators(int64_t num1, int64_t num2) inline CScriptNum operator+( const int64_t& rhs) const { assert(rhs == 0 || (rhs > 0 && m_value <= std::numeric_limits::max() - rhs) || (rhs < 0 && m_value >= std::numeric_limits::min() - rhs)); return CScriptNum(m_value + rhs); } inline CScriptNum operator-( const int64_t& rhs) const { assert(rhs == 0 || (rhs > 0 && m_value >= std::numeric_limits::min() + rhs) || (rhs < 0 && m_value <= std::numeric_limits::max() + rhs)); return CScriptNum(m_value - rhs); } inline CScriptNum10 operator+( const int64_t& rhs) const { assert(rhs == 0 || (rhs > 0 && m_value <= std::numeric_limits::max() - rhs) || (rhs < 0 && m_value >= std::numeric_limits::min() - rhs)); return CScriptNum10(m_value + rhs); } inline CScriptNum10 operator-( const int64_t& rhs) const { assert(rhs == 0 || (rhs > 0 && m_value >= std::numeric_limits::min() + rhs) || (rhs < 0 && m_value <= std::numeric_limits::max() + rhs)); return CScriptNum10(m_value - rhs); } // This could result in undefined behaviour in Bitcoin 0.10.0 and // Zcash prior to https://github.com/zcash/zcash/pull/4454 . // Since we only use this implementation for tests, we just assert // that the tests are not triggering this case (which is tested // separately for the real implementation). assert(value != INT64_MIN); // This could result in undefined behaviour in Bitcoin 0.10.0 and // Zcash prior to https://github.com/zcash/zcash/pull/4454 . // Since we only use this implementation for tests, we just assert // that the tests are not triggering this case (which is tested // separately for the real implementation). assert(vch.size() <= 8); { 0, 1, CHAR_MIN, CHAR_MAX, UCHAR_MAX, SHRT_MIN, USHRT_MAX, INT_MIN, INT_MAX, UINT_MAX, INT64_MIN, INT64_MAX }; static bool addition_in_range(int64_t a, int64_t b) { // intentionally excludes cases where the result would be INT64_MIN return b > 0 ? (a <= INT64_MAX - b) : (a > INT64_MIN - b); } static bool subtraction_in_range(int64_t a, int64_t b) { // intentionally excludes cases where the result would be INT64_MIN return b >= 0 ? (a > INT64_MIN + b) : (a <= INT64_MAX + b); } static bool value_in_range(int64_t a) { return a != INT64_MIN; } std::vector scriptnum_vch = scriptnum.getvch(); // The 9-byte case is exercised by the 'intmin' test. BOOST_CHECK(scriptnum_vch.size() <= 8); CScriptNum scriptnum2(scriptnum_vch, false); if (addition_in_range(num1, num2)) BOOST_CHECK(verify(-bignum, -scriptnum)); if (subtraction_in_range(num1, num2)) if (subtraction_in_range(num2, num1)) if (value_in_range(values[i])) { RunCreate(values[i]); } if (addition_in_range(values[i], offsets[j])) { RunCreate(values[i] + offsets[j]); } if (subtraction_in_range(values[i], offsets[j])) { RunCreate(values[i] - offsets[j]); } for (size_t j = 0; j < sizeof(values) / sizeof(values[0]); ++j) if (value_in_range(values[i])) { RunOperators(values[i], values[i]); RunOperators(values[i], -values[i]); } if (value_in_range(values[i]) && value_in_range(values[j])) { RunOperators(values[i], values[j]); RunOperators(values[i], -values[j]); } if (addition_in_range(values[i], values[j]) && value_in_range(values[j])) { RunOperators(values[i] + values[j], values[j]); RunOperators(values[i] + values[j], -values[j]); RunOperators(values[i] + values[j], values[i] + values[j]); } if (subtraction_in_range(values[i], values[j]) && value_in_range(values[j])) { RunOperators(values[i] - values[j], values[j]); RunOperators(values[i] - values[j], -values[j]); RunOperators(values[i] - values[j], values[i] - values[j]); } if (addition_in_range(values[i], values[j]) && subtraction_in_range(values[i], values[j])) { RunOperators(values[i] + values[j], values[i] - values[j]); RunOperators(values[i] - values[j], values[i] + values[j]); } //! Initialize from a CPrivKey (serialized OpenSSL-format private key data). BOOST_CHECK_MESSAGE(ECC_InitSanityCheck() == true, "ECC sanity test"); return UIError(strprintf(_("Absolute path %s does not exist"), walletFile)); return UIError(strprintf(_("Relative path %s does not exist"), walletFile)); " \"shielded_balance\": xxxxxxx, (numeric) the total confirmed shielded balance of the wallet in " + CURRENCY_UNIT + "\n" " \"shielded_unconfirmed_balance\": xxx, (numeric) the total unconfirmed shielded balance of the wallet in " + CURRENCY_UNIT + "\n" obj.pushKV("shielded_balance", FormatMoney(getBalanceZaddr("", 1, INT_MAX))); obj.pushKV("shielded_unconfirmed_balance", FormatMoney(getBalanceZaddr("", 0, 0))); // ZF and MG each use a single address repeated 48 times, // once for each funding period. return int(vChain.size()) - 1; bytes.push_back((unsigned char) (val_int >> (i * 8))); throw std::ios_base::failure(eof() ? "CBufferedFile::Fill: end of file" : "CBufferedFile::Fill: fread failed"); assert(nReadPos == nSrcPos); unsigned int nAvail = vchBuf.size() - nRewind; // Used in TestEquihashValidator. void CompressArray(const unsigned char* in, size_t in_len, unsigned char* out, size_t out_len, size_t bit_len, size_t byte_pad) assert(bit_len >= 8); assert(8*sizeof(uint32_t) >= 7+bit_len); size_t in_width { (bit_len+7)/8 + byte_pad }; assert(out_len == bit_len*in_len/(8*in_width)); uint32_t bit_len_mask { ((uint32_t)1 << bit_len) - 1 }; // The acc_bits least-significant bits of acc_value represent a bit sequence // in big-endian order. size_t acc_bits = 0; uint32_t acc_value = 0; size_t j = 0; for (size_t i = 0; i < out_len; i++) { // When we have fewer than 8 bits left in the accumulator, read the next // input element. if (acc_bits < 8) { acc_value = acc_value << bit_len; for (size_t x = byte_pad; x < in_width; x++) { acc_value = acc_value | ( ( // Apply bit_len_mask across byte boundaries in[j+x] & ((bit_len_mask >> (8*(in_width-x-1))) & 0xFF) ) << (8*(in_width-x-1))); // Big-endian } j += in_width; acc_bits += bit_len; } acc_bits -= 8; out[i] = (acc_value >> acc_bits) & 0xFF; } // Big-endian so that lexicographic array comparison is equivalent to integer // comparison void EhIndexToArray(const eh_index i, unsigned char* array) BOOST_STATIC_ASSERT(sizeof(eh_index) == 4); eh_index bei = htobe32(i); memcpy(array, &bei, sizeof(eh_index)); } std::vector GetMinimalFromIndices(std::vector indices, size_t cBitLen) { assert(((cBitLen+1)+7)/8 <= sizeof(eh_index)); size_t lenIndices { indices.size()*sizeof(eh_index) }; size_t minLen { (cBitLen+1)*lenIndices/(8*sizeof(eh_index)) }; size_t bytePad { sizeof(eh_index) - ((cBitLen+1)+7)/8 }; std::vector array(lenIndices); for (int i = 0; i < indices.size(); i++) { EhIndexToArray(indices[i], array.data()+(i*sizeof(eh_index))); } std::vector ret(minLen); CompressArray(array.data(), lenIndices, ret.data(), minLen, cBitLen+1, bytePad); return ret; } #ifdef ENABLE_MINING #include #include #include #include static EhSolverCancelledException solver_cancelled; template int Equihash::InitialiseState(eh_HashState& base_state) { uint32_t le_N = htole32(N); uint32_t le_K = htole32(K); unsigned char personalization[crypto_generichash_blake2b_PERSONALBYTES] = {}; memcpy(personalization, "ZcashPoW", 8); memcpy(personalization+8, &le_N, 4); memcpy(personalization+12, &le_K, 4); return crypto_generichash_blake2b_init_salt_personal(&base_state, NULL, 0, // No key. (512/N)*N/8, NULL, // No salt. personalization); void GenerateHash(const eh_HashState& base_state, eh_index g, unsigned char* hash, size_t hLen) eh_HashState state; state = base_state; eh_index lei = htole32(g); crypto_generichash_blake2b_update(&state, (const unsigned char*) &lei, sizeof(eh_index)); crypto_generichash_blake2b_final(&state, hash, hLen); #include #include typedef uint32_t eh_index; typedef uint8_t eh_trunc; std::vector GetMinimalFromIndices(std::vector indices, size_t cBitLen); void CompressArray(const unsigned char* in, size_t in_len, unsigned char* out, size_t out_len, size_t bit_len, size_t byte_pad=0); void ExpandArray(const unsigned char* in, size_t in_len, unsigned char* out, size_t out_len, size_t bit_len, size_t byte_pad=0); void EhIndexToArray(const eh_index i, unsigned char* array); #include "utilstrencodings.h" #if ENABLE_MINING #endif #if ENABLE_MINING #if ENABLE_MINING #endif // ENABLE_MINING inline constexpr size_t equihash_solution_size(unsigned int N, unsigned int K) { return (1 << K)*(N/(K+1)+1)/8; } TEST(Metrics, DisplayFunctions) { EXPECT_EQ(DisplayDuration(0, DurationFormat::REDUCED), "0 seconds"); EXPECT_EQ(DisplayDuration(59, DurationFormat::REDUCED), "59 seconds"); EXPECT_EQ(DisplayDuration(60, DurationFormat::REDUCED), "1 minutes"); EXPECT_EQ(DisplayDuration(61, DurationFormat::REDUCED), "1 minutes"); EXPECT_EQ(DisplayDuration(3599, DurationFormat::REDUCED), "59 minutes"); EXPECT_EQ(DisplayDuration(3600, DurationFormat::REDUCED), "1 hours"); EXPECT_EQ(DisplayDuration(86399, DurationFormat::REDUCED), "23 hours"); EXPECT_EQ(DisplayDuration(86400, DurationFormat::REDUCED), "1 days"); EXPECT_EQ(DisplayDuration(8640000, DurationFormat::REDUCED), "100 days"); EXPECT_EQ(DisplayDuration(185542587100800, DurationFormat::REDUCED), "2147483647 days"); EXPECT_EQ(DisplayDuration(185542587187199, DurationFormat::REDUCED), "2147483647 days"); EXPECT_EQ(DisplayDuration(0, DurationFormat::FULL), "0 seconds"); EXPECT_EQ(DisplayDuration(59, DurationFormat::FULL), "59 seconds"); EXPECT_EQ(DisplayDuration(60, DurationFormat::FULL), "1 minutes, 0 seconds"); EXPECT_EQ(DisplayDuration(61, DurationFormat::FULL), "1 minutes, 1 seconds"); EXPECT_EQ(DisplayDuration(3599, DurationFormat::FULL), "59 minutes, 59 seconds"); EXPECT_EQ(DisplayDuration(3600, DurationFormat::FULL), "1 hours, 0 minutes, 0 seconds"); EXPECT_EQ(DisplayDuration(86399, DurationFormat::FULL), "23 hours, 59 minutes, 59 seconds"); EXPECT_EQ(DisplayDuration(86400, DurationFormat::FULL), "1 days, 0 hours, 0 minutes, 0 seconds"); EXPECT_EQ(DisplayDuration(8640000, DurationFormat::FULL), "100 days, 0 hours, 0 minutes, 0 seconds"); EXPECT_EQ(DisplayDuration(185542587100800, DurationFormat::FULL), "2147483647 days, 0 hours, 0 minutes, 0 seconds"); EXPECT_EQ(DisplayDuration(185542587187199, DurationFormat::FULL), "2147483647 days, 23 hours, 59 minutes, 59 seconds"); EXPECT_EQ(DisplaySize(0), "0 Bytes"); EXPECT_EQ(DisplaySize(123), "123 Bytes"); EXPECT_EQ(DisplaySize(123456), "120.56 KiB"); EXPECT_EQ(DisplaySize(123456789), "117.74 MiB"); EXPECT_EQ(DisplaySize(123456789012), "114.98 GiB"); EXPECT_EQ(DisplaySize(1234567890123), "1.12 TiB"); EXPECT_EQ(DisplaySize(INT64_MAX), "8388608.00 TiB"); EXPECT_EQ(DisplayHashRate(0.0), "0.000 Sol/s"); EXPECT_EQ(DisplayHashRate(0.1234), "0.123 Sol/s"); EXPECT_EQ(DisplayHashRate(123.45), "123.450 Sol/s"); EXPECT_EQ(DisplayHashRate(1234.5), "1.234 kSol/s"); EXPECT_EQ(DisplayHashRate(1234567.8), "1.235 MSol/s"); EXPECT_EQ(DisplayHashRate(1234567890.1), "1.235 GSol/s"); EXPECT_EQ(DisplayHashRate(1234567890123.4), "1.235 TSol/s"); } std::string DisplayHashRate(double value) { double coef = 1.0; if (value < 1000.0 * coef) return strprintf(_("%.3f Sol/s"), value); coef *= 1000.0; if (value < 1000.0 * coef) return strprintf(_("%.3f kSol/s"), value / coef); coef *= 1000.0; if (value < 1000.0 * coef) return strprintf(_("%.3f MSol/s"), value / coef); coef *= 1000.0; if (value < 1000.0 * coef) return strprintf(_("%.3f GSol/s"), value / coef); coef *= 1000.0; return strprintf(_("%.3f TSol/s"), value / coef); } std::cout << " " << _("Network solution rate") << " | " << DisplayHashRate(netsolps) << std::endl; std::cout << " " << _("Local solution rate") << " | " << DisplayHashRate(localsolps) << std::endl; std::string DisplaySize(size_t value); std::string DisplayHashRate(double value); queue.push_back(range.first->second); range.first = mapBlocksUnlinked.erase(range.first); if (range.first->second == pindex) { range.first = mapBlocksUnlinked.erase(range.first); } else { ++range.first; if (ReadBlockFromDisk(block, range.first->second, chainparams.GetConsensus())) if (ProcessNewBlock(dummy, chainparams, NULL, &block, true, &(range.first->second))) range.first = mapBlocksUnknownParent.erase(range.first); ret.first = mapBlocksUnlinked.erase(ret.first); bitdb.mapFileUseCount.erase(mi); mi = mapAlerts.erase(mi); mi = mapAlerts.erase(mi); child_it = mapNullifiers.erase(child_it); child_it = mapAnchors.erase(child_it); it = mapCoins.erase(it); it = setDirtyFileInfo.erase(it); it = setDirtyBlockIndex.erase(it); it = setBlockIndexCandidates.erase(it); it = mapNullifiers.erase(it); it = mapAnchors.erase(it); it = mapCoins.erase(it); it = mapToUse.erase(it); it = mapToUse.erase(it); it = mapCoins.erase(it); mi = mapFileUseCount.erase(mi); const KeyConstants& keyConstants, const KeyConstants& keyConstants, keyConstants.base58Prefixes[ZCPAYMENT_ADDRESS] = {0x16,0x9A}; keyConstants.base58Prefixes[ZCPAYMENT_ADDRESS] = {0x16,0xB6}; keyConstants.base58Prefixes[ZCPAYMENT_ADDRESS] = {0x16,0xB6}; // H := blossom activation height; // SS := SubsidySlowStartShift(); // (The following calculation depends on BLOSSOM_POW_TARGET_SPACING_RATIO being an integer.) // HalvingHeight(i) = postInterval * i - R * (H - SS) + H return // If the start height of the funding period is not aligned to a multiple of the // funding period length. // throw here. FundingStreamAddress FundingStream::RecipientAddress(const Consensus::Params& params, int nHeight) const auto fsinfos = Consensus::GetActiveFundingStreams(nHeight, consensus); for (auto fsinfo : fsinfos) { CAmount nStreamAmount = fsinfo.Value(nBlockSubsidy); fundingstreams.pushKV(fsinfo.recipient, ValueFromAmount(nStreamAmount)); nMinerReward -= nStreamAmount; #include "consensus/funding.h" " \"fundingstreams\" : {...} (optional map) A map from funding stream recipients to amounts in " + CURRENCY_UNIT + ".\n" auto consensus = Params().GetConsensus(); CAmount nBlockSubsidy = GetBlockSubsidy(nHeight, consensus); CAmount nMinerReward = nBlockSubsidy; bool canopyActive = consensus.NetworkUpgradeActive(nHeight, Consensus::UPGRADE_CANOPY); if (canopyActive) { UniValue fundingstreams(UniValue::VOBJ); auto elems = Consensus::GetActiveFundingStreams(nHeight, consensus); for (auto elem : elems) { CAmount value = elem.Value(nBlockSubsidy); fundingstreams.pushKV(elem.recipient, value); nMinerReward -= value; } result.pushKV("fundingstreams", fundingstreams); } else if (nHeight > 0 && nHeight <= consensus.GetLastFoundersRewardBlockHeight(nHeight)) { nFoundersReward = nBlockSubsidy/5; nMinerReward -= nFoundersReward; } result.pushKV("miner", ValueFromAmount(nMinerReward)); BOOST_CHECK(!obj.exists("fundingstreams")); BOOST_CHECK(!obj.exists("fundingstreams")); BOOST_CHECK(!obj.exists("fundingstreams")); BOOST_CHECK(!obj.exists("fundingstreams")); auto check_funding_streams = [](UniValue obj, double ecc_slice, double zf_slice, double mg_slice) { std::map fundingstreams; find_value(obj, "fundingstreams").getObjMap(fundingstreams); BOOST_CHECK_EQUAL(fundingstreams.size(), 3); if (fundingstreams.size() != 3) return; BOOST_CHECK_EQUAL(fundingstreams["Electric Coin Company"].get_real(), ecc_slice); BOOST_CHECK_EQUAL(fundingstreams["Zcash Foundation"].get_real(), zf_slice); BOOST_CHECK_EQUAL(fundingstreams["Major Grants"].get_real(), mg_slice); }; bool canopyEnabled = Params().GetConsensus().vUpgrades[Consensus::UPGRADE_CANOPY].nActivationHeight != Consensus::NetworkUpgrade::NO_ACTIVATION_HEIGHT; BOOST_CHECK_EQUAL(find_value(obj, "miner").get_real(), canopyEnabled ? 2.5 : 3.125); if (canopyEnabled) check_funding_streams(obj, 0.21875, 0.15625, 0.25); BOOST_CHECK_EQUAL(find_value(obj, "miner").get_real(), canopyEnabled ? 2.5 : 3.125); if (canopyEnabled) check_funding_streams(obj, 0.21875, 0.15625, 0.25); BOOST_CHECK(find_value(obj, "fundingstreams").empty()); std::vector GetActiveFundingStreams( int nHeight, const Consensus::Params& params) { std::vector activeStreams; for (uint32_t idx = Consensus::FIRST_FUNDING_STREAM; idx < Consensus::MAX_FUNDING_STREAMS; idx++) { auto fs = params.vFundingStreams[idx]; if (fs && nHeight >= fs.get().GetStartHeight() && nHeight < fs.get().GetEndHeight()) { activeStreams.push_back(FundingStreamInfo[idx]); } } return activeStreams; }; std::vector GetActiveFundingStreams( int nHeight, const Consensus::Params& params); consensus.vUpgrades[Consensus::UPGRADE_CANOPY].nProtocolVersion = 170013; consensus.vUpgrades[Consensus::UPGRADE_CANOPY].nActivationHeight = consensus.vUpgrades[Consensus::UPGRADE_CANOPY].nProtocolVersion = 170012; consensus.vUpgrades[Consensus::UPGRADE_CANOPY].nActivationHeight = consensus.vUpgrades[Consensus::UPGRADE_CANOPY].nProtocolVersion = 170012; consensus.vUpgrades[Consensus::UPGRADE_CANOPY].nActivationHeight = UPGRADE_CANOPY, /*.strName =*/ "Canopy", /*.strInfo =*/ "See https://z.cash/upgrade/canopy/ for details.", const Consensus::Params& RegtestActivateCanopy(bool updatePow, int canopyActivationHeight) { UpdateNetworkUpgradeParameters(Consensus::UPGRADE_CANOPY, canopyActivationHeight); void RegtestDeactivateCanopy() { UpdateNetworkUpgradeParameters(Consensus::UPGRADE_CANOPY, Consensus::NetworkUpgrade::NO_ACTIVATION_HEIGHT); const Consensus::Params& RegtestActivateCanopy(bool updatePow, int canopyActivationHeight = Consensus::NetworkUpgrade::ALWAYS_ACTIVE); void RegtestDeactivateCanopy(); "LoadBlockIndex(): block index inconsistency detected (post-Heartwood; hashLightClientRoot %s != hashChainHistoryRoot %s): %s", "LoadBlockIndex(): block index inconsistency detected (pre-Heartwood; hashLightClientRoot %s != hashFinalSaplingRoot %s): %s", pindexNew->hashLightClientRoot.ToString(), pindexNew->hashFinalSaplingRoot.ToString(), pindexNew->ToString()); /** * The period before a network upgrade activates, where connections to upgrading peers are preferred (in blocks). * This was three days for upgrades up to and including Blossom, and is 1.5 days from Heartwood onward. */ static const int NETWORK_UPGRADE_PEER_PREFERENCE_BLOCK_PERIOD = 1728; uint32_t alt, HistoryEntry newEntry = alt == 0 // peak_pos - (1 << alt) is the mmr position of left child, -1 to that is this position of entry in : libzcash::NodeToEntry(nodeData, peak_pos - (1 << alt) - 1, peak_pos - 2); // Computes floor(log2(x)). static inline uint32_t floor_log2(uint32_t x) { while (x >>= 1) { ++log; } // Computes the altitude of the largest subtree for an MMR with n nodes, // which is floor(log2(n + 1)) - 1. static inline uint32_t altitude(uint32_t n) { return floor_log2(n + 1) - 1; uint32_t last_peak_alt = 0; uint32_t alt = 0; alt = altitude(treeLength); peak_pos = (1 << (alt + 1)) - 1; while (alt != 0) { // left child, -2^alt peak_pos = peak_pos - (1 << alt); alt = alt - 1; draftMMRNode(entry_indices, entries, GetHistoryAt(epochId, peak_pos-1), alt, peak_pos); last_peak_alt = alt; peak_pos = peak_pos + (1 << (alt + 1)) - 1; alt = last_peak_alt; while (alt > 0) { uint32_t left_pos = peak_pos - (1 << alt); alt = alt - 1; draftMMRNode(entry_indices, entries, GetHistoryAt(epochId, left_pos-1), alt, left_pos); draftMMRNode(entry_indices, entries, GetHistoryAt(epochId, right_pos-1), alt, right_pos); sa.sa_flags = SA_RESTART; sa_hup.sa_flags = SA_RESTART; SendManyRecipient(std::string address_, CAmount amount_, std::string memo_) : nFullSizeToReindex = std::max(1, fullSize); // 15-minute spacing is ~105 minutes, which exceeds the limit imposed by the soft fork of return state.DoS(10, error("%s: contains a non-final transaction", __func__), REJECT_INVALID, "bad-txns-nonfinal"); return state.DoS(100, error("%s: block height mismatch in coinbase", __func__), REJECT_INVALID, "bad-cb-height"); // the block subsidy to a Founders' Reward script, until the last Founders' // Reward block is reached, with exception of the genesis block. // The last Founders' Reward block is defined as the block just before the // first subsidy halving block, which occurs at halving_interval + slow_start_shift. return state.DoS(100, error("%s: founders reward missing", __func__), REJECT_INVALID, "cb-no-founders-reward"); if (!fHaveGenesis) { return false; } // This is defined to be an interruption point. // assert(fRequestShutdown.is_lock_free()); assert(fReopenDebugLog.is_lock_free()); { CBlockIndex *pindexLastTip; { LOCK(cs_main); pindexLastTip = chainActive.Tip(); } boost::function threadnotifywallets = boost::bind(&ThreadNotifyWallets, pindexLastTip); threadGroup.create_thread( boost::bind(&TraceThread>, "txnotify", threadnotifywallets) ); } #include #include #include "timedata.h" #include "random.h" #include "netbase.h" using ::testing::StrictMock; class MockCTimeWarning : public CTimeWarning { public: MOCK_METHOD2(Warn, void(size_t, size_t)); }; CNetAddr GetUniqueAddr() { uint8_t buf[16] = { 0xFD }; // RFC 4193 address in FC00::/7 with L = 1 (locally assigned) GetRandBytes(&buf[1], 15); CNetAddr ip; ip.SetRaw(NET_IPV6, buf); assert(ip.IsRFC4193()); return ip; } TEST(TimeWarning, Assertions) { StrictMock tw; EXPECT_DEATH(tw.AddTimeData(GetUniqueAddr(), 0, INT64_MIN), ""); EXPECT_DEATH(tw.AddTimeData(GetUniqueAddr(), 0, -1), ""); EXPECT_DEATH(tw.AddTimeData(GetUniqueAddr(), 0, INT64_MAX - CTimeWarning::TIMEDATA_IGNORE_THRESHOLD + 1), ""); EXPECT_DEATH(tw.AddTimeData(GetUniqueAddr(), 0, INT64_MAX), ""); } TEST(TimeWarning, NoWarning) { StrictMock tw; int64_t now = GetTime(); EXPECT_CALL(tw, Warn(CTimeWarning::TIMEDATA_WARNING_SAMPLES, 0)).Times(0); tw.AddTimeData(GetUniqueAddr(), now - CTimeWarning::TIMEDATA_IGNORE_THRESHOLD, now); tw.AddTimeData(GetUniqueAddr(), now + CTimeWarning::TIMEDATA_IGNORE_THRESHOLD, now); tw.AddTimeData(GetUniqueAddr(), now - CTimeWarning::TIMEDATA_WARNING_THRESHOLD, now); tw.AddTimeData(GetUniqueAddr(), now + CTimeWarning::TIMEDATA_WARNING_THRESHOLD, now); for (size_t i = 0; i < CTimeWarning::TIMEDATA_WARNING_SAMPLES - 2; i++) { tw.AddTimeData(GetUniqueAddr(), now + CTimeWarning::TIMEDATA_WARNING_THRESHOLD + 1, now); } CNetAddr duplicateIp = GetUniqueAddr(); for (size_t i = 0; i < 2; i++) { tw.AddTimeData(duplicateIp, now + CTimeWarning::TIMEDATA_WARNING_THRESHOLD + 1, now); } } TEST(TimeWarning, PeersAhead) { StrictMock tw; int64_t now = GetTime(); EXPECT_CALL(tw, Warn(CTimeWarning::TIMEDATA_WARNING_SAMPLES, 0)); for (size_t i = 0; i < CTimeWarning::TIMEDATA_WARNING_SAMPLES - 1; i++) { tw.AddTimeData(GetUniqueAddr(), now + CTimeWarning::TIMEDATA_WARNING_THRESHOLD + 1, now); } tw.AddTimeData(GetUniqueAddr(), now + CTimeWarning::TIMEDATA_IGNORE_THRESHOLD - 1, now); } TEST(TimeWarning, PeersBehind) { StrictMock tw; int64_t now = GetTime(); EXPECT_CALL(tw, Warn(0, CTimeWarning::TIMEDATA_WARNING_SAMPLES)); for (size_t i = 0; i < CTimeWarning::TIMEDATA_WARNING_SAMPLES - 1; i++) { tw.AddTimeData(GetUniqueAddr(), now - CTimeWarning::TIMEDATA_WARNING_THRESHOLD - 1, now); } tw.AddTimeData(GetUniqueAddr(), now - CTimeWarning::TIMEDATA_IGNORE_THRESHOLD + 1, now); } TEST(TimeWarning, PeersMixed) { StrictMock tw; int64_t now = GetTime(); EXPECT_CALL(tw, Warn(CTimeWarning::TIMEDATA_WARNING_SAMPLES/2, (CTimeWarning::TIMEDATA_WARNING_SAMPLES+1)/2)); for (size_t i = 0; i < CTimeWarning::TIMEDATA_WARNING_SAMPLES/2; i++) { tw.AddTimeData(GetUniqueAddr(), now + CTimeWarning::TIMEDATA_WARNING_THRESHOLD + 1, now); } for (size_t i = 0; i < (CTimeWarning::TIMEDATA_WARNING_SAMPLES-1)/2; i++) { tw.AddTimeData(GetUniqueAddr(), now - CTimeWarning::TIMEDATA_WARNING_THRESHOLD - 1, now); } tw.AddTimeData(GetUniqueAddr(), now - CTimeWarning::TIMEDATA_IGNORE_THRESHOLD + 1, now); } pfrom->nTimeOffset = timeWarning.AddTimeData(pfrom->addr, nTime, GetTime()); int64_t GetAdjustedTime() { return GetTime(); } CTimeWarning timeWarning; int64_t CTimeWarning::AddTimeData(const CNetAddr& ip, int64_t nTime, int64_t now) assert(now >= 0 && now <= INT64_MAX - TIMEDATA_IGNORE_THRESHOLD); if (nTime <= now - TIMEDATA_IGNORE_THRESHOLD || nTime >= now + TIMEDATA_IGNORE_THRESHOLD) { return 0; } int64_t nTimeOffset = nTime - now; LOCK(cs); // Ignore duplicate IPs. if (setKnown.size() == TIMEDATA_MAX_SAMPLES || !setKnown.insert(ip).second) { return nTimeOffset; } LogPrintf("Added time data, samples %d, offset %+d (%+d minutes)\n", setKnown.size(), nTimeOffset, nTimeOffset/60); if (nPeersBehind + nPeersAhead < TIMEDATA_WARNING_SAMPLES) { if (nTimeOffset < -TIMEDATA_WARNING_THRESHOLD) { nPeersBehind++; } else if (nTimeOffset > TIMEDATA_WARNING_THRESHOLD) { nPeersAhead++; if (nPeersBehind + nPeersAhead == TIMEDATA_WARNING_SAMPLES) { Warn(nPeersAhead, nPeersBehind); return nTimeOffset; } void CTimeWarning::Warn(size_t peersAhead, size_t peersBehind) { std::string strMessage; if (peersBehind >= TIMEDATA_WARNING_MAJORITY) { strMessage = _("Warning: Your computer's date and time may be ahead of the rest of the network! If your clock is wrong Zcash will not work properly."); } else if (peersAhead >= TIMEDATA_WARNING_MAJORITY) { strMessage = _("Warning: Your computer's date and time may be behind the rest of the network! If your clock is wrong Zcash will not work properly."); } else { strMessage = _("Warning: Please check that your computer's date and time are correct! If your clock is wrong Zcash will not work properly."); } SetMiscWarning(strMessage); LogPrintf("*** %s\n", strMessage); uiInterface.ThreadSafeMessageBox(strMessage, "", CClientUIInterface::MSG_WARNING); #include #include "netbase.h" #include "sync.h" /** Functions to keep track of "adjusted" P2P time */ int64_t GetAdjustedTime(); class CTimeWarning { private: CCriticalSection cs; std::set setKnown; size_t nPeersAhead; size_t nPeersBehind; public: static const size_t TIMEDATA_WARNING_SAMPLES = 8; static const size_t TIMEDATA_WARNING_MAJORITY = 6; static const size_t TIMEDATA_MAX_SAMPLES = 20; static const int64_t TIMEDATA_WARNING_THRESHOLD = 10 * 60; static const int64_t TIMEDATA_IGNORE_THRESHOLD = 10 * 24 * 60 * 60; CTimeWarning() : nPeersBehind(0), nPeersAhead(0) {} virtual ~CTimeWarning() {} int64_t AddTimeData(const CNetAddr& ip, int64_t nTime, int64_t now); virtual void Warn(size_t peersAhead, size_t peersBehind); extern CTimeWarning timeWarning; " \"timeoffset\": xxxxx, (numeric) the time offset (deprecated; always 0)\n" obj.push_back(Pair("timeoffset", 0)); " \"timeoffset\": xxxxx, (numeric) the time offset (deprecated; always 0)\n" obj.push_back(Pair("timeoffset", 0)); // Test that a block evaluated under Blossom rules can contain Blossom transactions. TEST_F(ContextualCheckBlockTest, BlockBlossomRulesAcceptBlossomTx) { SelectParams(CBaseChainParams::REGTEST); UpdateNetworkUpgradeParameters(Consensus::UPGRADE_OVERWINTER, 1); UpdateNetworkUpgradeParameters(Consensus::UPGRADE_SAPLING, 1); UpdateNetworkUpgradeParameters(Consensus::UPGRADE_BLOSSOM, 1); CMutableTransaction mtx = GetFirstBlockCoinbaseTx(); // Make it a Blossom transaction (using Sapling version/group id). mtx.fOverwintered = true; mtx.nVersion = SAPLING_TX_VERSION; mtx.nVersionGroupId = SAPLING_VERSION_GROUP_ID; SCOPED_TRACE("BlockBlossomRulesAcceptBlossomTx"); ExpectValidBlockFromTx(CTransaction(mtx)); } // types. Currently (February 2020) this means with each of four *branches* active // (Sprout, Overwinter, Sapling, Blossom), we'll test that transactions for tx // *versions* not valid on that branch are rejected. // // Note that Sapling and Blossom transactions use the same tx version and version // group id, but different consensus branch ids. These tests use transactions with // no inputs and only a transparent output, therefore they are not signed and do not // depend on the consensus branch id. Testing that Sapling rejects transactions that // are signed for Blossom, and vice versa, is outside the scope of these tests. // // TODO: Change the testing approach to not require O(branches * versions) code. // Test block evaluated under Blossom rules cannot contain non-Blossom transactions. TEST_F(ContextualCheckBlockTest, BlockBlossomRulesRejectOtherTx) { SelectParams(CBaseChainParams::REGTEST); UpdateNetworkUpgradeParameters(Consensus::UPGRADE_OVERWINTER, 1); UpdateNetworkUpgradeParameters(Consensus::UPGRADE_SAPLING, 1); UpdateNetworkUpgradeParameters(Consensus::UPGRADE_BLOSSOM, 1); CMutableTransaction mtx = GetFirstBlockCoinbaseTx(); // Set the version to Sprout+JoinSplit (but nJoinSplit will be 0). mtx.nVersion = 2; { SCOPED_TRACE("BlockBlossomRulesRejectSproutTx"); ExpectInvalidBlockFromTx(CTransaction(mtx), 100, "tx-overwinter-active"); } // Make it an Overwinter transaction mtx.fOverwintered = true; mtx.nVersion = OVERWINTER_TX_VERSION; mtx.nVersionGroupId = OVERWINTER_VERSION_GROUP_ID; { SCOPED_TRACE("BlockBlossomRulesRejectOverwinterTx"); ExpectInvalidBlockFromTx(CTransaction(mtx), 100, "bad-sapling-tx-version-group-id"); } } static_assert(MAX_FUTURE_BLOCK_TIME_ADJUSTED > MAX_FUTURE_BLOCK_TIME_MTP, "MAX_FUTURE_BLOCK_TIME_ADJUSTED must be greater than MAX_FUTURE_BLOCK_TIME_MTP"); static_assert(TIMESTAMP_WINDOW > MAX_FUTURE_BLOCK_TIME_ADJUSTED, "TIMESTAMP_WINDOW must be greater than MAX_FUTURE_BLOCK_TIME_ADJUSTED"); static_assert(6 * Consensus::POST_BLOSSOM_POW_TARGET_SPACING * 7 < MAX_FUTURE_BLOCK_TIME_MTP - 60, "MAX_FUTURE_BLOCK_TIME_MTP is too low given block target spacing"); static_assert(LIMIT_MAX_TIME_ADJUSTMENT * 2 < MAX_FUTURE_BLOCK_TIME_MTP, "LIMIT_MAX_TIME_ADJUSTMENT is too high given MAX_FUTURE_BLOCK_TIME_MTP"); static_assert(MAX_FUTURE_BLOCK_TIME_MTP + LIMIT_MAX_TIME_ADJUSTMENT < MAX_FUTURE_BLOCK_TIME_ADJUSTED, "LIMIT_MAX_TIME_ADJUSTMENT is too high given MAX_FUTURE_BLOCK_TIME_MTP and MAX_FUTURE_BLOCK_TIME_ADJUSTED"); ExpectInvalidBlockFromTx(CTransaction(mtx), 100, "tx-overwinter-not-active"); ExpectInvalidBlockFromTx(CTransaction(mtx), 100, "tx-overwinter-not-active"); ExpectInvalidBlockFromTx(CTransaction(mtx), 100, "bad-overwinter-tx-version-group-id"); ExpectInvalidBlockFromTx(CTransaction(mtx), 100, "bad-sapling-tx-version-group-id"); #include "timedata.h" strUsage += HelpMessageOpt("-maxtimeadjustment=", strprintf(_("Maximum allowed median peer time offset adjustment, in seconds. Local perspective of time may be influenced by peers forward or backward by this amount. (default: %u seconds, maximum: %u seconds)"), DEFAULT_MAX_TIME_ADJUSTMENT, LIMIT_MAX_TIME_ADJUSTMENT)); int64_t nMaxTimeAdjustment = GetArg("-maxtimeadjustment", DEFAULT_MAX_TIME_ADJUSTMENT); if (nMaxTimeAdjustment < 0 || nMaxTimeAdjustment > LIMIT_MAX_TIME_ADJUSTMENT) { return InitError(strprintf(_("-maxtimeadjustment must be in the range 0 to %u seconds"), LIMIT_MAX_TIME_ADJUSTMENT)); } if (abs64(nMedian) <= GetArg("-maxtimeadjustment", DEFAULT_MAX_TIME_ADJUSTMENT)) #include "chain.h" static const int64_t DEFAULT_MAX_TIME_ADJUSTMENT = 0; static const int64_t LIMIT_MAX_TIME_ADJUSTMENT = 25 * 60; static_assert(LIMIT_MAX_TIME_ADJUSTMENT * 2 < MAX_FUTURE_BLOCK_TIME_MTP); static_assert(MAX_FUTURE_BLOCK_TIME_MTP + LIMIT_MAX_TIME_ADJUSTMENT < MAX_FUTURE_BLOCK_TIME_ADJUSTED); if (hash == consensusParams.hashGenesisBlock) { } if (block.nBits != GetNextWorkRequired(pindexPrev, &block, consensusParams)) { } if (fCheckpointsEnabled) { if (pcheckpoint && nHeight < pcheckpoint->nHeight) { } if (block.nVersion < 4) { } // On testnet we activate this rule 6 blocks after Blossom activation. From block 299188 and // prior to Blossom activation, the testnet minimum-difficulty threshold was 15 minutes (i.e. // a minimum difficulty block can be mined if no block is mined normally within 15 minutes): // // However the median-time-past is 6 blocks behind, and the worst-case time for 7 blocks at a // 15-minute spacing is ~105 minutes, which is exceeds the limit imposed by the soft fork of // 90 minutes. // // After Blossom, the minimum difficulty threshold time is changed to 6 times the block target // spacing, which is 7.5 minutes: // // 7 times that is 52.5 minutes which is well within the limit imposed by the soft fork. static_assert(6 * Consensus::POST_BLOSSOM_POW_TARGET_SPACING * 7 < MAX_FUTURE_BLOCK_TIME_MTP - 60); consensus.nFutureTimestampSoftForkHeight = consensus.vUpgrades[Consensus::UPGRADE_BLOSSOM].nActivationHeight + 6; bool Params::FutureTimestampSoftForkActive(int nHeight) const { return nHeight >= nFutureTimestampSoftForkHeight; } bool FutureTimestampSoftForkActive(int nHeight) const; /** * Default block height at which the future timestamp soft fork rule activates. * * Genesis blocks are hard-coded into the binary for all networks * (mainnet, testnet, regtest), and have now-ancient timestamps. So we need to * handle the case where we might use the genesis block's timestamp as the * median-time-past. * * GetMedianTimePast() is implemented such that the chosen block is the * median of however many blocks we are able to select up to * nMedianTimeSpan = 11. For example, if nHeight == 6: * * ,- medianTimePast + MAX_FUTURE_BLOCK_TIME_MTP) { if (consensusParams.FutureTimestampSoftForkActive(pindexPrev->nHeight + 1)) { auto medianTimePast = pindexPrev->GetMedianTimePast(); auto nTime = std::max(medianTimePast + 1, GetAdjustedTime()); // See the comment in ContextualCheckBlockHeader() for background. if (pindexPrev->nHeight >= 1) { nTime = std::min(nTime, medianTimePast + MAX_FUTURE_BLOCK_TIME_MTP); } pblock->nTime = nTime; /** * Maximum amount of time that a block timestamp is allowed to be ahead of the * median-time-past of the previous block. */ static const int64_t MAX_FUTURE_BLOCK_TIME_MTP = 90 * 60; static_assert(MAX_FUTURE_BLOCK_TIME_ADJUSTED > MAX_FUTURE_BLOCK_TIME_MTP); // Genesis blocks are hard-coded into the binary, and both testnet and // regtest have now-ancient timestamps, so we need to handle the case // where we might use the genesis block's timestamp as the median-time-past. // // GetMedianTimePast() is implemented such that the chosen block is the // median of however many blocks we are able to select up to // nMedianTimeSpan = 11. For example, if nHeight == 6: // // ,-= 2 && block.GetBlockTime() > medianTimePast + MAX_FUTURE_BLOCK_TIME_MTP) { return state.Invalid(error("%s: block at height %d, timestamp %d is too far ahead of median-time-past, limit is %d", __func__, nHeight, block.GetBlockTime(), medianTimePast + MAX_FUTURE_BLOCK_TIME_MTP), REJECT_INVALID, "time-too-far-ahead-of-mtp"); } return state.Invalid(error("%s: block at height %d, timestamp %d is too far ahead of adjusted time, limit is %d", /** * Maximum amount of time that a block timestamp is allowed to be ahead of the * current network-adjusted time. */ static const int64_t MAX_FUTURE_BLOCK_TIME_ADJUSTED = 2 * 60 * 60; /** * Timestamp window used as a grace period by code that compares external * timestamps (such as timestamps passed to RPCs, or wallet key creation times) * to block timestamps. */ static const int64_t TIMESTAMP_WINDOW = MAX_FUTURE_BLOCK_TIME_ADJUSTED + 60; static_assert(TIMESTAMP_WINDOW > MAX_FUTURE_BLOCK_TIME_ADJUSTED); auto nTimeLimit = GetAdjustedTime() + MAX_FUTURE_BLOCK_TIME_ADJUSTED; while (pindex && pindex->pprev && pindex->GetBlockTime() > nTimeBegin - TIMESTAMP_WINDOW) { } while (pindex && nTimeFirstKey && pindex->GetBlockTime() < nTimeFirstKey - TIMESTAMP_WINDOW) { } for (std::map::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++) { mapKeyBirth[it->first] = it->second->GetBlockTime() - TIMESTAMP_WINDOW; // block times can be off } auto medianTimePast = pindexPrev->GetMedianTimePast(); if (block.GetBlockTime() <= medianTimePast) { return state.Invalid(error("%s: block at height %d, timestamp %d is not later than median-time-past %d", __func__, nHeight, block.GetBlockTime(), medianTimePast), } auto nTimeLimit = GetAdjustedTime() + 2 * 60 * 60; if (block.GetBlockTime() > nTimeLimit) { return state.Invalid(error("%s: block at height %d. timestamp %d is too far ahead of adjusted time, limit is %d", __func__, nHeight, block.GetBlockTime(), nTimeLimit), } static const int APPROX_RELEASE_HEIGHT = 684936; static const int DEPRECATION_HEIGHT = APPROX_RELEASE_HEIGHT + (WEEKS_UNTIL_DEPRECATION * 7 * 24 * 48); if (nExpiryHeight != 0 && nextBlockHeight + TX_EXPIRING_SOON_THRESHOLD > nExpiryHeight) { #define CLIENT_VERSION_BUILD 53 (networkID == "test" && nHeight == 584000 && *phashFirstInsufValidated == #define CLIENT_VERSION_BUILD 50 static const int APPROX_RELEASE_HEIGHT = 553000; #define CLIENT_VERSION_REVISION 6 #define CLIENT_VERSION_BUILD 25 static const int APPROX_RELEASE_HEIGHT = 549200; "the wallet’s Sprout balance is below " + strprintf("%s %s", FormatMoney(CENT), CURRENCY_UNIT) + ".\n" const int MIGRATION_EXPIRY_DELTA = 450; auto builder = TransactionBuilder(consensusParams, targetHeight_, MIGRATION_EXPIRY_DELTA, pwalletMain, pzcashParams, auto builder = TransactionBuilder(consensusParams, 1, expiryDelta, &keystore); auto builder = TransactionBuilder(consensusParams, 2, expiryDelta); auto builder = TransactionBuilder(consensusParams, 2, expiryDelta, nullptr, params); auto builder = TransactionBuilder(consensusParams, 2, expiryDelta, nullptr, params, &view); auto builder = TransactionBuilder(consensusParams, 1, expiryDelta); auto builder = TransactionBuilder(consensusParams, 1, expiryDelta); auto builder = TransactionBuilder(consensusParams, 1, expiryDelta); auto builder = TransactionBuilder(consensusParams, 1, expiryDelta); auto builder = TransactionBuilder(consensusParams, 1, expiryDelta); builder = TransactionBuilder(consensusParams, 1, expiryDelta, &keystore); auto builder = TransactionBuilder(consensusParams, 1, expiryDelta, &keystore); auto builder = TransactionBuilder(consensusParams, 1, expiryDelta, &keystore); auto builder = TransactionBuilder(consensusParams, 1, expiryDelta, &keystore); auto builder = TransactionBuilder(consensusParams, 1, expiryDelta, &keystore); auto builder = TransactionBuilder(consensusParams, 1, expiryDelta); auto builder = TransactionBuilder(consensusParams, 1, expiryDelta); auto builder = TransactionBuilder(consensusParams, 1, expiryDelta); auto builder = TransactionBuilder(consensusParams, nextBlockHeight, expiryDelta, pwalletMain); auto builder = TransactionBuilder(consensusParams, 1, expiryDelta, &keyStore); auto builder = TransactionBuilder(consensusParams, 1, expiryDelta); auto builder = TransactionBuilder(consensusParams, 1, expiryDelta); auto builder = TransactionBuilder(consensusParams, 1, expiryDelta); auto builder2 = TransactionBuilder(consensusParams, 2, expiryDelta); auto builder3 = TransactionBuilder(consensusParams, 2, expiryDelta); auto builder = TransactionBuilder(consensusParams, 1, expiryDelta); auto builder = TransactionBuilder(consensusParams, 1, expiryDelta); auto builder = TransactionBuilder(consensusParams, 1, expiryDelta); auto builder2 = TransactionBuilder(consensusParams, 2, expiryDelta); auto builder = TransactionBuilder(consensusParams, 1, expiryDelta); auto builder = TransactionBuilder(consensusParams, 1, expiryDelta, &keystore); auto builder2 = TransactionBuilder(consensusParams, 2, expiryDelta); return CreateNewContextualCMutableTransaction(consensusParams, nHeight, expiryDelta); } CMutableTransaction CreateNewContextualCMutableTransaction(const Consensus::Params& consensusParams, int nHeight, int nExpiryDelta) { CMutableTransaction mtx; mtx.nExpiryHeight = nHeight + nExpiryDelta; if (mtx.nExpiryHeight <= 0 || mtx.nExpiryHeight >= TX_EXPIRY_HEIGHT_THRESHOLD) { throw new std::runtime_error("CreateNewContextualCMutableTransaction: invalid expiry height"); } /** Return a CMutableTransaction with contextual default values based on set of consensus rules at nHeight, and the default expiry delta. */ /** Return a CMutableTransaction with contextual default values based on set of consensus rules at nHeight, and given expiry delta. */ CMutableTransaction CreateNewContextualCMutableTransaction(const Consensus::Params& consensusParams, int nHeight, int nExpiryDelta); int nExpiryDelta, mtx = CreateNewContextualCMutableTransaction(consensusParams, nHeight, nExpiryDelta); int nExpiryDelta, auto builder = TransactionBuilder(consensusParams, targetHeight_, expiryDelta, pwalletMain, pzcashParams, &coinsView, &cs_main); builder = TransactionBuilder(Params().GetConsensus(), nextBlockHeight, expiryDelta, pwalletMain); Params().GetConsensus(), nextBlockHeight, expiryDelta, pwalletMain); builder = TransactionBuilder(Params().GetConsensus(), nextBlockHeight, expiryDelta, pwalletMain); bool clearWitnessCaches = false; if (!RewindBlockIndex(chainparams, clearWitnessCaches)) { if (clearWitnessCaches || GetBoolArg("-rescan", false)) bool RewindBlockIndex(const CChainParams& params, bool& clearWitnessCaches) LogPrintf("*** First insufficiently validated block at height %d, rewind length %d\n", nHeight, rewindLength); clearWitnessCaches = false; if (rewindLength > 0) { const uint256 *phashFirstInsufValidated = chainActive[nHeight]->phashBlock; auto networkID = params.NetworkIDString(); // This is true when we intend to do a long rewind. bool intendedRewind = (networkID == "test" && nHeight == 252500 && *phashFirstInsufValidated == clearWitnessCaches = (rewindLength > MAX_REORG_LENGTH && intendedRewind); if (clearWitnessCaches) { auto msg = strprintf(_( "An intended block chain rewind has been detected: network %s, hash %s, height %d" ), networkID, phashFirstInsufValidated->GetHex(), nHeight); LogPrintf("*** %s\n", msg); } if (rewindLength > MAX_REORG_LENGTH && !intendedRewind) { auto pindexOldTip = chainActive.Tip(); auto pindexRewind = chainActive[nHeight - 1]; auto msg = strprintf(_( "A block chain rewind 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." ), rewindLength, MAX_REORG_LENGTH) + "\n\n" + _("Rewind details") + ":\n" + "- " + strprintf(_("Current tip: %s, height %d"), pindexOldTip->phashBlock->GetHex(), pindexOldTip->nHeight) + "\n" + "- " + strprintf(_("Rewinding to: %s, height %d"), pindexRewind->phashBlock->GetHex(), pindexRewind->nHeight) + "\n\n" + _("Please help, human!"); LogPrintf("*** %s\n", msg); uiInterface.ThreadSafeMessageBox(msg, "", CClientUIInterface::MSG_ERROR); StartShutdown(); return false; } bool RewindBlockIndex(const CChainParams& params, bool& clearWitnessCaches); // Don't increase banscore if the transaction only just expired int expiredDosLevel = IsExpiredTx(tx, nHeight - 1) ? dosLevel : 0; return state.DoS(expiredDosLevel, error("ContextualCheckTransaction(): transaction is expired"), REJECT_INVALID, "tx-overwinter-expired"); //! Wraps GetRandInt to allow tests to override RandomInt and make it deterministic. //if base58 encoded data not holds a ext key, return a !IsValid() key // txouts // Check it still fails as expected // Do not translate _(...) -help-debug options, many technical terms, and only a very small audience, so is unnecessary stress to translators // are not yet downloaded and not in flight to vBlocks. In the meantime, update if (i == NULL) return; // Ran out of chain, we must not be fully synced // hash at height 0 is the txid itself // calculate right hash if not beyond the end of the array - copy left hash otherwise /** calculate the hash of a node in the merkle tree (at leaf level: the txid itself) */ // Initialization done, start algo driver. // receiving data. This means properly utilizing TCP flow control signaling. // Should set the timeout limit to a reasonable value to avoid bool IsRFC2544() const; // IPv4 inter-network communications (192.18.0.0/15) // Sum the total priority/fee of all txs in each bucket // throw exception in case of an empty request // check spentness and form a bitmap (as well as a JSON capable human-readable string representation) "\nReturns the number of blocks in the best valid block chain.\n" "3. includemempool (boolean, optional) Whether to include the mempool\n" // corrupting or modifying the JSON output by putting special characters in " \"address\": x.xxx (numeric, required) The key is the Zcash address, the value is the " + CURRENCY_UNIT + " amount\n" // possible encoding for a positive integer (which means no null bytes at // expansion // Since there can be no more than 20,000 signature operations per block /** A signature creator that just produces 72-byte empty signatures. */ // when it's first needed and also destructed after all objects that use // have a static destruction order/problem, but the check in // Test 31: Ports should not affect bucket placement in the addr BOOST_AUTO_TEST_SUITE_END() // Neither tx should have made it into the template. // must throw an exception because 127.0.0.1 is in already banned subnet range /** Get name for file to store private key in */ // Zero-confirmation notes belong to transactions which have not yet been mined // If we also ignore spent notes at this depth, we won't find any notes. "1. \"zcashaddress\" (string, required) The Zcash address to send to.\n" "\nThe amount with at least 6 confirmations, very safe\n" "2. \"tozcashaddress\" (string, required) The Zcash address to send funds to.\n" " \"address\":amount (numeric) The Zcash address is the key, the numeric amount in " + CURRENCY_UNIT + " is the value\n" " \"address\" : \"address\", (string) the Zcash address\n" throw JSONRPCError(RPC_INVALID_PARAMETER, "Memo cannot be used with a taddr. It can only be used with a zaddr."); "1. \"status\" (string, optional) Filter result by the operation's state e.g. \"success\".\n" /** A note outpoint */ // do not try to retrieve public IP when not listening (pointless) LOCAL_UPNP, // unused (was: address reported by UPnP) FormatParagraph(_("This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit and cryptographic software written by Eric Young.")) + alert.nExpiration = GetTime() + 12 * 30 * 24 * 60 * 60; alert.nID = 1004; // use https://github.com/zcash/zcash/wiki/specification#assigned-numbers to keep track of alert IDs alert.nPriority = 4000; alert.strStatusBar = "Your client version 1.0.10 has degraded networking behavior. Please update to the most recent version of Zcash (1.0.10-1 or later)."; alert.setSubVer.insert(std::string("/"+useragent+":1.0.10/")); // Enforce BIP 34 rule that the coinbase starts with serialized block height. // In Zcash this has been enforced since launch, except that the genesis // block didn't include the height in the coinbase (see Zcash protocol spec // section '6.8 Bitcoin Improvement Proposals'). std::string comment(""); BOOST_ERROR("Bad test: " << strTest << comment); BOOST_ERROR("Bad test: " << strTest << comment); BOOST_CHECK_MESSAGE(CheckTransaction(tx, state, verifier), strTest + comment); BOOST_CHECK_MESSAGE(state.IsValid(), comment); BOOST_ERROR("Bad test: " << strTest << comment); strTest + comment); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err) + comment); comment = ""; } else if (test.size() == 1) { comment += "\n# "; comment += test[0].write(); std::string comment(""); BOOST_ERROR("Bad test: " << strTest << comment); BOOST_ERROR("Bad test: " << strTest << comment); BOOST_ERROR("Bad test: " << strTest << comment); BOOST_CHECK_MESSAGE(!fValid, strTest + comment); BOOST_CHECK_MESSAGE(err != SCRIPT_ERR_OK, ScriptErrorString(err) + comment); comment = ""; } else if (test.size() == 1) { comment += "\n# "; comment += test[0].write(); unsigned int flags = SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY; // DERSIG (BIP66) is also always enforced, but does not have a flag. if (!IsValidSignatureEncoding(vchSig)) { // In Zcash this is required, and validation of non-strict-DER signatures is not implemented. //SCRIPT_VERIFY_DERSIG = (1U << 2), // SCRIPT_VERIFY_DERSIG is always enforced "P2PK with too much R padding", 0 "P2PK with too much S padding", 0 "P2PK with too little R padding", 0 "P2PK NOT with bad sig with too much R padding", 0 "P2PK NOT with too much R padding", 0 "BIP66 example 1", 0 "BIP66 example 2", 0 "BIP66 example 3", 0 "BIP66 example 4", 0 "BIP66 example 5", 0 "BIP66 example 6", 0 "BIP66 example 7", 0 "BIP66 example 8", 0 "BIP66 example 9", 0 "BIP66 example 10", 0 "BIP66 example 11", 0 "BIP66 example 12", 0 "P2PK with multi-byte hashtype", 0 /* Zcash, unlike Bitcoin, has always enforced strict DER signatures. */ if (!secp256k1_ecdsa_signature_parse_der(secp256k1_context_verify, &sig, &vchSig[0], vchSig.size())) { /* Zcash, unlike Bitcoin, has always enforced strict DER signatures. */ if (!secp256k1_ecdsa_signature_parse_der(secp256k1_context_verify, &sig, &vchSig[0], vchSig.size())) { alert.nExpiration = GetTime() + 6 * 30 * 24 * 60 * 60; alert.nID = 1003; // use https://github.com/zcash/zcash/wiki/specification#assigned-numbers to keep track of alert IDs alert.nCancel = 1001; // cancels previous messages up to this ID number alert.nPriority = 1500; alert.strStatusBar = "Your client is out of date and vulnerable to denial of service. Please update to the most recent version of Zcash (1.0.8-1 or later). More info at: https://z.cash/support/security/"; alert.setSubVer.insert(std::string("/"+useragent+":1.0.3/")); alert.setSubVer.insert(std::string("/"+useragent+":1.0.4/")); alert.setSubVer.insert(std::string("/"+useragent+":1.0.5/")); alert.setSubVer.insert(std::string("/"+useragent+":1.0.6/")); alert.setSubVer.insert(std::string("/"+useragent+":1.0.7/")); alert.setSubVer.insert(std::string("/"+useragent+":1.0.7-1/")); alert.setSubVer.insert(std::string("/"+useragent+":1.0.8/")); alert.nExpiration = GetTime() + 20 * 365 * 24 * 60 * 60; alert.nID = 1002; // use https://github.com/zcash/zcash/wiki/specification#assigned-numbers to keep track of alert IDs alert.nCancel = 1000; // cancels previous messages up to this ID number // main.cpp: // 2000 for longer invalid proof-of-work chain alert.nPriority = 4000; alert.strStatusBar = "Your client is out of date and potentially vulnerable to blockchain disruption. Please update to the most recent version of Zcash and use -reindex to ensure integrity of your blockchain state. More info at: https://z.cash/support/security/"; alert.strRPCError = alert.strStatusBar; const std::vector useragents = {"MagicBean", "BeanStalk", "AppleSeed", "EleosZcash"}; BOOST_FOREACH(const std::string& useragent, useragents) { alert.setSubVer.insert(std::string("/"+useragent+":1.0.0/")); alert.setSubVer.insert(std::string("/"+useragent+":1.0.1/")); alert.setSubVer.insert(std::string("/"+useragent+":1.0.2/")); } #include "policy/fees.h" EXPECT_EQ(dPriority, MAX_PRIORITY); #include "policy/fees.h" // Joinsplits do not reveal any information about the value or age of a note, so we // cannot apply the priority algorithm used for transparent utxos. Instead, we just // use the maximum priority whenever a transaction contains any JoinSplits. // (Note that coinbase transactions cannot contain JoinSplits.) // FIXME: this logic is partially duplicated between here and CreateNewBlock in miner.cpp. if (tx.vjoinsplit.size() > 0) { return MAX_PRIORITY; } buckets.insert(buckets.end(), defaultBuckets.begin(), defaultBuckets.end()); buckets.push_back(std::numeric_limits::infinity()); for (unsigned int i = 0; i < buckets.size(); i++) { bucketMap[buckets[i]] = i; unsigned int TxConfirmStats::FindBucketIndex(double val) { auto it = bucketMap.lower_bound(val); assert(it != bucketMap.end()); return it->second; } unsigned int bucketindex = FindBucketIndex(val); unsigned int bucketindex = FindBucketIndex(val); /** Find the bucket index of a given value */ unsigned int FindBucketIndex(double val); BOOST_AUTO_TEST_CASE(TxConfirmStats_FindBucketIndex) { std::vector buckets {0.0, 3.5, 42.0}; TxConfirmStats txcs; txcs.Initialize(buckets, MAX_BLOCK_CONFIRMS, DEFAULT_DECAY, "Test"); BOOST_CHECK_EQUAL(txcs.FindBucketIndex(-1.0), 0); BOOST_CHECK_EQUAL(txcs.FindBucketIndex(0.0), 0); BOOST_CHECK_EQUAL(txcs.FindBucketIndex(1.0), 1); BOOST_CHECK_EQUAL(txcs.FindBucketIndex(3.5), 1); BOOST_CHECK_EQUAL(txcs.FindBucketIndex(4.0), 2); BOOST_CHECK_EQUAL(txcs.FindBucketIndex(43.0), 3); BOOST_CHECK_EQUAL(txcs.FindBucketIndex(INF_FEERATE), 3); BOOST_CHECK_EQUAL(txcs.FindBucketIndex(2.0*INF_FEERATE), 3); BOOST_CHECK_EQUAL(txcs.FindBucketIndex(nan("")), 0); } pfrom->PushMessage("getaddr"); pfrom->fGetAddr = true; uint64_t nonce = 0; vRecv >> nonce; // Echo the message back with the nonce. This allows for two useful features: // // 1) A remote node can quickly check if the connection is operational // 2) Remote nodes can measure the latency of the network thread. If this node // is overloaded it won't respond to pings quickly and the remote node can // avoid sending us more work, like chain download requests. // // The nonce stops the remote getting confused between different pings: without // it, if the remote node sends a ping once per second and this node takes 5 // seconds to respond to each, the 5th ping the remote sends would appear to // return very quickly. pfrom->PushMessage("pong", nonce); pto->nPingNonceSent = nonce; pto->PushMessage("ping", nonce); else if (nTime - pnode->nLastRecv > TIMEOUT_INTERVAL) if ((nType & SER_DISK) || !(nType & SER_GETHASH)) static const int INIT_PROTO_VERSION = 170002; std::string strUsage = _("Zcash RPC client version") + " " + FormatFullVersion() + "\n" + PrivacyInfo(); std::string strUsage = _("Zcash Daemon") + " " + _("version") + " " + FormatFullVersion() + "\n" + PrivacyInfo(); // Privacy notice text std::cout << PrivacyInfo(); std::string PrivacyInfo() { return "\n" + FormatParagraph(strprintf(_("In order to ensure you are adequately protecting your privacy when using Zcash, please see <%s>."), "https://z.cash/support/security/index.html")) + "\n"; } return "\n" + /** Returns privacy notice (for -version, -help and metrics screen) */ std::string PrivacyInfo(); if (nSize < 253) return 1; else if (nSize <= 0xFFFFu) return 3; else if (nSize <= 0xFFFFFFFFu) return 5; else return 9; else if (nSize <= 0xFFFFu) else if (nSize <= 0xFFFFFFFFu) if (GetBoolArg("-minetolocalwallet", false)) { if (GetArg("-mineraddress", "").empty() && GetBoolArg("-gen", false)) { if (GetBoolArg("-minetolocalwallet", true) && !minerAddressInLocalWallet) { #ifndef ENABLE_WALLET auto mineToLocalWallet = GetBoolArg("-minetolocalwallet", false); if (mineToLocalWallet) { return InitError(_("Zcash was not built with wallet support. Set -minetolocalwallet=0 to use -mineraddress, or rebuild Zcash with wallet support.")); } if (!mapArgs.count("-mineraddress")) { return InitError(_("Zcash was not built with wallet support. Set -mineraddress, or rebuild Zcash with wallet support.")); } #endif // !ENABLE_WALLET #ifdef ENABLE_WALLET #endif // ENABLE_WALLET #include "consensus/consensus.h" static_assert(MIN_CURRENT_VERSION >= MIN_TX_VERSION, "standard rule for tx version should be consistent with network rule"); assert(solver == "tromp" || solver == "default"); // TODO: factor this out into a function with the same API for each solver. strUsage += HelpMessageOpt("-equihashsolver=", _("Specify the Equihash solver to be used if enabled (default: \"default\")")); #include return std::chrono::duration_cast( std::chrono::system_clock::now().time_since_epoch()).count(); return std::chrono::duration_cast( std::chrono::system_clock::now().time_since_epoch()).count(); #include if (newVersion < CTransaction::MIN_CURRENT_VERSION || newVersion > CTransaction::MAX_CURRENT_VERSION) unsigned int sz = tx.GetSerializeSize(SER_NETWORK, tx.nVersion); if (tx.nVersion > CTransaction::MAX_CURRENT_VERSION || tx.nVersion < CTransaction::MIN_CURRENT_VERSION) { CMutableTransaction::CMutableTransaction() : nVersion(CTransaction::MIN_CURRENT_VERSION), nLockTime(0) {} CTransaction::CTransaction() : nVersion(CTransaction::MIN_CURRENT_VERSION), vin(), vout(), nLockTime(0), vjoinsplit(), joinSplitPubKey(), joinSplitSig() { } // Transactions that include a list of JoinSplits are version 2. static const int32_t MIN_CURRENT_VERSION = 1; static const int32_t MAX_CURRENT_VERSION = 2; BOOST_AUTO_TEST_CASE(test_IsStandardV2) { LOCK(cs_main); CBasicKeyStore keystore; CCoinsView coinsDummy; CCoinsViewCache coins(&coinsDummy); std::vector dummyTransactions = SetupDummyInputs(keystore, coins); CMutableTransaction t; t.vin.resize(1); t.vin[0].prevout.hash = dummyTransactions[0].GetHash(); t.vin[0].prevout.n = 1; t.vin[0].scriptSig << std::vector(65, 0); t.vout.resize(1); t.vout[0].nValue = 90*CENT; CKey key; key.MakeNewKey(true); t.vout[0].scriptPubKey = GetScriptForDestination(key.GetPubKey().GetID()); string reason; // A v2 transaction with no JoinSplits is still standard. t.nVersion = 2; BOOST_CHECK(IsStandardTx(t, reason)); // ... and with one JoinSplit. t.vjoinsplit.push_back(JSDescription()); BOOST_CHECK(IsStandardTx(t, reason)); // ... and when that JoinSplit takes from a transparent input. JSDescription *jsdesc = &t.vjoinsplit[0]; jsdesc->vpub_old = 10*CENT; t.vout[0].nValue -= 10*CENT; BOOST_CHECK(IsStandardTx(t, reason)); // A v2 transaction with JoinSplits but no transparent inputs is standard. jsdesc->vpub_old = 0; jsdesc->vpub_new = 100*CENT; t.vout[0].nValue = 90*CENT; t.vin.resize(0); BOOST_CHECK(IsStandardTx(t, reason)); // v2 transactions can still be non-standard for the same reasons as v1. t.vout[0].nValue = 501; // dust BOOST_CHECK(!IsStandardTx(t, reason)); // v3 is not standard. t.nVersion = 3; t.vout[0].nValue = 90*CENT; BOOST_CHECK(!IsStandardTx(t, reason)); } assert(nd->witnesses.size() == 0); CNoteData* nd = &(mapWallet[hash].mapNoteData[jsoutpt]); nd->witnesses.push_front(tree.witness()); // Check the validity of the cache assert(nWitnessCacheSize >= nd->witnesses.size()); bool CBase58Data::SetString(const std::string& str, unsigned int nVersionBytes) return SetString(str.c_str(), nVersionBytes); bool CBitcoinAddress::SetString(const char* pszAddress) { return CBase58Data::SetString(pszAddress, 2); } bool CBitcoinAddress::SetString(const std::string& strAddress) { return SetString(strAddress.c_str()); } return CBase58Data::SetString(pszSecret, 1) && IsValid(); bool SetString(const char* psz, unsigned int nVersionBytes); bool SetString(const std::string& str, unsigned int nVersionBytes); bool SetString(const char* pszSecret); bool SetString(const std::string& strSecret); BOOST_CHECK_EQUAL(FormatSubVersion("Test", 99900, std::vector()), std::string("/Test:0.9.99-beta1/")); BOOST_CHECK_EQUAL(FormatSubVersion("Test", 99924, std::vector()), std::string("/Test:0.9.99-beta25/")); BOOST_CHECK_EQUAL(FormatSubVersion("Test", 99925, std::vector()), std::string("/Test:0.9.99-rc1/")); BOOST_CHECK_EQUAL(FormatSubVersion("Test", 99949, std::vector()), std::string("/Test:0.9.99-rc25/")); BOOST_CHECK_EQUAL(FormatSubVersion("Test", 99950, std::vector()), std::string("/Test:0.9.99/")); BOOST_CHECK_EQUAL(FormatSubVersion("Test", 99951, std::vector()), std::string("/Test:0.9.99-1/")); BOOST_CHECK_EQUAL(FormatSubVersion("Test", 99999, std::vector()), std::string("/Test:0.9.99-49/")); BOOST_CHECK_EQUAL(FormatSubVersion("Test", 99900, comments), std::string("/Test:0.9.99-beta1(comment1)/")); BOOST_CHECK_EQUAL(FormatSubVersion("Test", 99950, comments), std::string("/Test:0.9.99(comment1)/")); BOOST_CHECK_EQUAL(FormatSubVersion("Test", 99900, comments2), std::string("/Test:0.9.99-beta1(comment1; comment2)/")); BOOST_CHECK_EQUAL(FormatSubVersion("Test", 99950, comments2), std::string("/Test:0.9.99(comment1; comment2)/")); bool fSuccess = checker.CheckSig(vchSig, vchPubKey, script); bool fOk = checker.CheckSig(vchSig, vchPubKey, script); #define CLIENT_VERSION_ZCASH 9 static const unsigned int MAX_HEADERS_RESULTS = 160; BOOST_STATIC_ASSERT(sizeof(eh_index) == 4); BOOST_STATIC_ASSERT(sizeof(eh_index) == 4); BOOST_STATIC_ASSERT(sizeof(eh_trunc) == 1); BOOST_STATIC_ASSERT(W <= WIDTH); #include "main.h" #include "crypto/equihash.h" const size_t N = 200, K = 9; BOOST_STATIC_ASSERT(equihash_parameters_acceptable(N, K)); nEquihashN = N; nEquihashK = K; const size_t N = 48, K = 5; BOOST_STATIC_ASSERT(equihash_parameters_acceptable(N, K)); nEquihashN = N; nEquihashK = K; if (DistinctIndices(X[i+l], X[i+m], hashLen, lenIndices)) { auto soln = res.GetIndices(hashLen, 2*lenIndices, CollisionBitLength); assert(soln.size() == equihash_solution_size(N, K)); if (validBlock(soln)) { return true; } auto soln = row.GetIndices(hashLen, lenIndices, CollisionBitLength); assert(soln.size() == equihash_solution_size(N, K)); solns.insert(soln); inline constexpr size_t equihash_solution_size(unsigned int N, unsigned int K) { return (1 << K)*(N/(K+1)+1)/8; } #include #include "primitives/block.h" TEST(block_tests, header_size_is_expected) { // Dummy header with an empty Equihash solution. CBlockHeader header; CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss << header; ASSERT_EQ(ss.size(), CBlockHeader::HEADER_SIZE); } #define equihash_parameters_acceptable(N, K) \ ((CBlockHeader::HEADER_SIZE + equihash_solution_size(N, K))*MAX_HEADERS_RESULTS < \ MAX_PROTOCOL_MESSAGE_LENGTH-1000) static const size_t HEADER_SIZE=4+32+32+32+4+4+32; // excluding Equihash solution BOOST_FOREACH(const uint256 ¬e_commitment, joinsplit.commitments) { // Insert the note commitments into our temporary tree. tree.append(note_commitment); // JoinSplits are always anchored to a root in the note // are derived from the secrets placed in the note // Note commitments are introduced into the commitment // destinations involved in the JoinSplit. The presence of // a commitment in the note commitment tree is required "zcrawreceive zcsecretkey encryptednote\n" "Decrypts encryptednote and checks if the coin commitments\n" " \"note\": noteplaintext,\n" CDataStream ssData(ParseHexV(params[1], "encrypted_note"), SER_NETWORK, PROTOCOL_VERSION); "encrypted_note could not be decoded" pwalletMain->WitnessNoteCommitment( result.push_back(Pair("note", HexStr(ss.begin(), ss.end()))); " inputs: a JSON object mapping {note: zcsecretkey, ...}\n" " \"encryptednote1\": enc1,\n" " \"encryptednote2\": enc2,\n" CDataStream ssData(ParseHexV(s.name_, "note"), SER_NETWORK, PROTOCOL_VERSION); pwalletMain->WitnessNoteCommitment(commitments, witnesses, anchor); std::string encryptedNote1; std::string encryptedNote2; encryptedNote1 = HexStr(ss2.begin(), ss2.end()); encryptedNote2 = HexStr(ss2.begin(), ss2.end()); result.push_back(Pair("encryptednote1", encryptedNote1)); result.push_back(Pair("encryptednote2", encryptedNote2)); void CWallet::WitnessNoteCommitment(std::vector commitments, std::vector>& witnesses, uint256 &final_anchor) BOOST_FOREACH(const uint256 ¬e_commitment, pour.commitments) tree.append(note_commitment); wit->append(note_commitment); if (note_commitment == commitment) { void WitnessNoteCommitment( bool* pfMissingInputs, bool fRejectAbsurdFee) if (fRejectAbsurdFee && nFees > ::minRelayTxFee.GetFee(nSize) * 10000) return error("AcceptToMemoryPool: absurdly high fees %s, %d > %d", bool* pfMissingInputs, bool fRejectAbsurdFee=false); case WalletModel::AbsurdFee: msgParams.first = tr("A fee higher than %1 is considered an absurdly high fee.").arg(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), 10000000)); // reject absurdly high fee > 0.1 bitcoin return AbsurdFee; AbsurdFee, bool CMerkleTx::AcceptToMemoryPool(bool fLimitFree, bool fRejectAbsurdFee) return ::AcceptToMemoryPool(mempool, state, *this, fLimitFree, NULL, fRejectAbsurdFee); bool AcceptToMemoryPool(bool fLimitFree=true, bool fRejectAbsurdFee=true);