diff --git a/src/init.cpp b/src/init.cpp index e01d7f43fa..3e9462fa0d 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -190,7 +190,7 @@ void Shutdown(NodeContext& node) /// Be sure that anything that writes files or flushes caches only does this if the respective /// module was initialized. util::ThreadRename("shutoff"); - mempool.AddTransactionsUpdated(1); + if (node.mempool) node.mempool->AddTransactionsUpdated(1); StopHTTPRPC(); StopREST(); @@ -235,8 +235,8 @@ void Shutdown(NodeContext& node) node.connman.reset(); node.banman.reset(); - if (::mempool.IsLoaded() && node.args->GetArg("-persistmempool", DEFAULT_PERSIST_MEMPOOL)) { - DumpMempool(::mempool); + if (node.mempool && node.mempool->IsLoaded() && node.args->GetArg("-persistmempool", DEFAULT_PERSIST_MEMPOOL)) { + DumpMempool(*node.mempool); } if (fFeeEstimatesInitialized) @@ -306,7 +306,7 @@ void Shutdown(NodeContext& node) GetMainSignals().UnregisterBackgroundSignalScheduler(); globalVerifyHandle.reset(); ECC_Stop(); - node.mempool = nullptr; + node.mempool.reset(); node.chainman = nullptr; node.scheduler.reset(); node.reverification_scheduler.reset(); @@ -787,10 +787,7 @@ static void ThreadImport(ChainstateManager& chainman, std::vector vImp return; } } // End scope of CImportingNow - if (args.GetArg("-persistmempool", DEFAULT_PERSIST_MEMPOOL)) { - LoadMempool(::mempool); - } - ::mempool.SetIsLoaded(!ShutdownRequested()); + chainman.ActiveChainstate().LoadMempool(args); } /** Sanity checks @@ -1093,11 +1090,6 @@ bool AppInitParameterInteraction(const ArgsManager& args) } } - // Checkmempool and checkblockindex default to true in regtest mode - int ratio = std::min(std::max(args.GetArg("-checkmempool", chainparams.DefaultConsistencyChecks() ? 1 : 0), 0), 1000000); - if (ratio != 0) { - mempool.setSanityCheck(1.0 / ratio); - } fCheckBlockIndex = args.GetBoolArg("-checkblockindex", chainparams.DefaultConsistencyChecks()); fCheckpointsEnabled = args.GetBoolArg("-checkpoints", DEFAULT_CHECKPOINTS_ENABLED); @@ -1422,10 +1414,18 @@ bool AppInitMain(const util::Ref& context, NodeContext& node, interfaces::BlockA node.banman = MakeUnique(GetDataDir() / "banlist.dat", &uiInterface, args.GetArg("-bantime", DEFAULT_MISBEHAVING_BANTIME)); assert(!node.connman); node.connman = MakeUnique(GetRand(std::numeric_limits::max()), GetRand(std::numeric_limits::max()), args.GetBoolArg("-networkactive", true)); + // Make mempool generally available in the node context. For example the connection manager, wallet, or RPC threads, // which are all started after this, may use it from the node context. assert(!node.mempool); - node.mempool = &::mempool; + node.mempool = MakeUnique(&::feeEstimator); + if (node.mempool) { + int ratio = std::min(std::max(args.GetArg("-checkmempool", chainparams.DefaultConsistencyChecks() ? 1 : 0), 0), 1000000); + if (ratio != 0) { + node.mempool->setSanityCheck(1.0 / ratio); + } + } + assert(!node.chainman); node.chainman = &g_chainman; ChainstateManager& chainman = *Assert(node.chainman); @@ -1613,7 +1613,7 @@ bool AppInitMain(const util::Ref& context, NodeContext& node, interfaces::BlockA chainman.m_total_coinstip_cache = nCoinCacheUsage; chainman.m_total_coinsdb_cache = nCoinDBCache; - UnloadBlockIndex(node.mempool); + UnloadBlockIndex(node.mempool.get()); // new CBlockTreeDB tries to delete the existing file, which // fails if it's still open from the previous loop. Close it first: diff --git a/src/interfaces/chain.cpp b/src/interfaces/chain.cpp index 282fe4c1dd..265a9ef1de 100644 --- a/src/interfaces/chain.cpp +++ b/src/interfaces/chain.cpp @@ -409,6 +409,12 @@ public: notifications.transactionAddedToMempool(entry.GetSharedTx()); } } +// ELEMENTS + bool testPeginClaimAcceptance(TxValidationState& acceptState, const CTransactionRef tx, const CAmount& max_tx_fee) override { + LOCK(::cs_main); + return ::AcceptToMemoryPool(*m_node.mempool, acceptState, tx, nullptr /* plTxnReplaced */, false /* bypass_limits */, max_tx_fee, true /* test_accept */); + } +// end ELEMENTS NodeContext& m_node; }; } // namespace diff --git a/src/interfaces/chain.h b/src/interfaces/chain.h index 6e50ccb27a..60e05647fb 100644 --- a/src/interfaces/chain.h +++ b/src/interfaces/chain.h @@ -29,6 +29,7 @@ struct bilingual_str; struct CBlockLocator; struct FeeCalculation; struct NodeContext; +class TxValidationState; namespace interfaces { @@ -285,6 +286,9 @@ public: //! to be prepared to handle this by ignoring notifications about unknown //! removed transactions and already added new transactions. virtual void requestMempoolTransactions(Notifications& notifications) = 0; + +// ELEMENTS + virtual bool testPeginClaimAcceptance(TxValidationState& acceptState, const CTransactionRef tx, const CAmount& max_tx_fee) = 0; }; //! Interface to let node manage chain clients (wallets, or maybe tools for diff --git a/src/net_processing.cpp b/src/net_processing.cpp index 8d6ecf2779..15508683ce 100644 --- a/src/net_processing.cpp +++ b/src/net_processing.cpp @@ -1710,7 +1710,7 @@ void static ProcessGetBlockData(CNode& pfrom, const CChainParams& chainparams, c } //! Determine whether or not a peer can request a transaction, and return it (or nullptr if not found or not allowed). -CTransactionRef static FindTxForGetData(const CNode& peer, const GenTxid& gtxid, const std::chrono::seconds mempool_req, const std::chrono::seconds now) LOCKS_EXCLUDED(cs_main) +static CTransactionRef FindTxForGetData(const CTxMemPool& mempool, const CNode& peer, const GenTxid& gtxid, const std::chrono::seconds mempool_req, const std::chrono::seconds now) LOCKS_EXCLUDED(cs_main) { auto txinfo = mempool.info(gtxid); if (txinfo.tx) { @@ -1766,7 +1766,7 @@ void static ProcessGetData(CNode& pfrom, const CChainParams& chainparams, CConnm continue; } - CTransactionRef tx = FindTxForGetData(pfrom, ToGenTxid(inv), mempool_req, now); + CTransactionRef tx = FindTxForGetData(mempool, pfrom, ToGenTxid(inv), mempool_req, now); if (tx) { // WTX and WITNESS_TX imply we serialize with witness int nSendFlags = (inv.IsMsgTx() ? SERIALIZE_TRANSACTION_NO_WITNESS : 0); @@ -2732,7 +2732,7 @@ void PeerLogicValidation::ProcessMessage(CNode& pfrom, const std::string& msg_ty } } else if (inv.IsGenTxMsg()) { const GenTxid gtxid = ToGenTxid(inv); - const bool fAlreadyHave = AlreadyHaveTx(gtxid, mempool); + const bool fAlreadyHave = AlreadyHaveTx(gtxid, m_mempool); LogPrint(BCLog::NET, "got inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom.GetId()); pfrom.AddKnownTx(inv.hash); @@ -3003,7 +3003,7 @@ void PeerLogicValidation::ProcessMessage(CNode& pfrom, const std::string& msg_ty std::list lRemovedTxn; - // We do the AlreadyHave() check using wtxid, rather than txid - in the + // We do the AlreadyHaveTx() check using wtxid, rather than txid - in the // absence of witness malleation, this is strictly better, because the // recent rejects filter may contain the wtxid but rarely contains // the txid of a segwit transaction that has been rejected. diff --git a/src/node/context.cpp b/src/node/context.cpp index 0238aab0d9..49d0c37235 100644 --- a/src/node/context.cpp +++ b/src/node/context.cpp @@ -9,6 +9,7 @@ #include #include #include +#include NodeContext::NodeContext() {} NodeContext::~NodeContext() {} diff --git a/src/node/context.h b/src/node/context.h index d73c77302d..7302d66e05 100644 --- a/src/node/context.h +++ b/src/node/context.h @@ -35,7 +35,7 @@ class WalletClient; //! be used without pulling in unwanted dependencies or functionality. struct NodeContext { std::unique_ptr connman; - CTxMemPool* mempool{nullptr}; // Currently a raw pointer because the memory is not managed by this struct + std::unique_ptr mempool; std::unique_ptr peer_logic; ChainstateManager* chainman{nullptr}; // Currently a raw pointer because the memory is not managed by this struct std::unique_ptr banman; diff --git a/src/rest.cpp b/src/rest.cpp index 8a8b5e401d..988091a9dc 100644 --- a/src/rest.cpp +++ b/src/rest.cpp @@ -102,7 +102,7 @@ static CTxMemPool* GetMemPool(const util::Ref& context, HTTPRequest* req) RESTERR(req, HTTP_NOT_FOUND, "Mempool disabled or instance not found"); return nullptr; } - return node->mempool; + return node->mempool.get(); } static RetFormat ParseDataFormat(std::string& param, const std::string& strReq) @@ -393,7 +393,7 @@ static bool rest_tx(const util::Ref& context, HTTPRequest* req, const std::strin const NodeContext* const node = GetNodeContext(context, req); if (!node) return false; uint256 hashBlock = uint256(); - const CTransactionRef tx = GetTransaction(/* block_index */ nullptr, node->mempool, hash, Params().GetConsensus(), hashBlock); + const CTransactionRef tx = GetTransaction(/* block_index */ nullptr, node->mempool.get(), hash, Params().GetConsensus(), hashBlock); if (!tx) { return RESTERR(req, HTTP_NOT_FOUND, hashStr + " not found"); } diff --git a/src/rpc/mining.cpp b/src/rpc/mining.cpp index 7e8746de76..312dfcbb3b 100644 --- a/src/rpc/mining.cpp +++ b/src/rpc/mining.cpp @@ -1319,7 +1319,8 @@ UniValue getnewblockhex(const JSONRPCRequest& request) CScript feeDestinationScript = Params().GetConsensus().mandatory_coinbase_destination; if (feeDestinationScript == CScript()) feeDestinationScript = CScript() << OP_TRUE; - std::unique_ptr pblocktemplate(BlockAssembler(mempool, Params()).CreateNewBlock(feeDestinationScript, std::chrono::seconds(required_wait), &proposed, data_commitment.empty() ? nullptr : &data_commitment)); + const NodeContext& node = EnsureNodeContext(request.context); + std::unique_ptr pblocktemplate(BlockAssembler(*node.mempool, Params()).CreateNewBlock(feeDestinationScript, std::chrono::seconds(required_wait), &proposed, data_commitment.empty() ? nullptr : &data_commitment)); if (!pblocktemplate.get()) { throw JSONRPCError(RPC_INTERNAL_ERROR, "Wallet keypool empty"); } @@ -1495,8 +1496,9 @@ UniValue consumecompactsketch(const JSONRPCRequest& request) CBlockHeaderAndShortTxIDs cmpctblock; ssBlock >> cmpctblock; - LOCK(mempool.cs); - PartiallyDownloadedBlock partialBlock(&mempool); + const NodeContext& node = EnsureNodeContext(request.context); + LOCK(node.mempool->cs); + PartiallyDownloadedBlock partialBlock(node.mempool.get()); const std::vector> dummy; ReadStatus status = partialBlock.InitData(cmpctblock, dummy); if (status != READ_STATUS_OK) { diff --git a/src/rpc/rawtransaction.cpp b/src/rpc/rawtransaction.cpp index 85723b3bfa..78c009a7a2 100644 --- a/src/rpc/rawtransaction.cpp +++ b/src/rpc/rawtransaction.cpp @@ -211,7 +211,7 @@ static UniValue getrawtransaction(const JSONRPCRequest& request) } uint256 hash_block; - const CTransactionRef tx = GetTransaction(blockindex, node.mempool, hash, Params().GetConsensus(), hash_block); + const CTransactionRef tx = GetTransaction(blockindex, node.mempool.get(), hash, Params().GetConsensus(), hash_block); if (!tx) { std::string errmsg; if (blockindex) { diff --git a/src/test/util/setup_common.cpp b/src/test/util/setup_common.cpp index a5455328b4..6bd671f40a 100644 --- a/src/test/util/setup_common.cpp +++ b/src/test/util/setup_common.cpp @@ -166,7 +166,7 @@ TestingSetup::TestingSetup(const std::string& chainName, const std::string& fedp pblocktree.reset(new CBlockTreeDB(1 << 20, true)); - m_node.mempool = &::mempool; + m_node.mempool = MakeUnique(&::feeEstimator); m_node.mempool->setSanityCheck(1.0); m_node.chainman = &::g_chainman; @@ -212,8 +212,8 @@ TestingSetup::~TestingSetup() m_node.connman.reset(); m_node.banman.reset(); m_node.args = nullptr; - UnloadBlockIndex(m_node.mempool); - m_node.mempool = nullptr; + UnloadBlockIndex(m_node.mempool.get()); + m_node.mempool.reset(); m_node.scheduler.reset(); m_node.chainman->Reset(); m_node.chainman = nullptr; diff --git a/src/validation.cpp b/src/validation.cpp index 0b83916f4b..80891cde03 100644 --- a/src/validation.cpp +++ b/src/validation.cpp @@ -154,7 +154,6 @@ arith_uint256 nMinimumChainWork; CFeeRate minRelayTxFee = CFeeRate(DEFAULT_MIN_RELAY_TX_FEE); CBlockPolicyEstimator feeEstimator; -CTxMemPool mempool(&feeEstimator); // Internal stuff namespace { @@ -4564,6 +4563,14 @@ bool static LoadBlockIndexDB(ChainstateManager& chainman, const CChainParams& ch return true; } +void CChainState::LoadMempool(const ArgsManager& args) +{ + if (args.GetArg("-persistmempool", DEFAULT_PERSIST_MEMPOOL)) { + ::LoadMempool(m_mempool); + } + m_mempool.SetIsLoaded(!ShutdownRequested()); +} + bool CChainState::LoadChainTip(const CChainParams& chainparams) { AssertLockHeld(cs_main); diff --git a/src/validation.h b/src/validation.h index a61c855e36..bd60963506 100644 --- a/src/validation.h +++ b/src/validation.h @@ -125,7 +125,6 @@ enum class SynchronizationState { extern RecursiveMutex cs_main; extern CBlockPolicyEstimator feeEstimator; -extern CTxMemPool mempool; typedef std::unordered_map BlockMap; extern Mutex g_best_block_mutex; extern std::condition_variable g_best_block_cv; @@ -675,6 +674,9 @@ public: */ void CheckBlockIndex(const Consensus::Params& consensusParams); + /** Load the persisted mempool from disk */ + void LoadMempool(const ArgsManager& args); + /** Update the chain tip based on database information, i.e. CoinsTip()'s best block. */ bool LoadChainTip(const CChainParams& chainparams) EXCLUSIVE_LOCKS_REQUIRED(cs_main); diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index 75b3e5bae3..d423d1e6ec 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -3325,19 +3325,7 @@ void FundTransaction(CWallet* const pwallet, CMutableTransaction& tx, CAmount& f coinControl.SelectExternal(txin.prevout, txout); } } - CCoinsView viewDummy; - CCoinsViewCache view(&viewDummy); - { - LOCK2(cs_main, mempool.cs); - CCoinsViewCache& chain_view = ::ChainstateActive().CoinsTip(); - CCoinsViewMemPool mempool_view(&chain_view, mempool); - for (auto& coin : coins) { - if (!mempool_view.GetCoin(coin.first, coin.second)) { - // Either the coin is not in the CCoinsViewCache or is spent. Clear it. - coin.second.Clear(); - } - } - } + pwallet->chain().findCoins(coins); for (const auto& coin : coins) { if (!coin.second.out.IsNull()) { coinControl.SelectExternal(coin.first, coin.second.out); @@ -5695,9 +5683,7 @@ UniValue claimpegin(const JSONRPCRequest& request) // To check if it's not double spending an existing pegin UTXO, we check mempool acceptance. TxValidationState acceptState; - LOCK(::cs_main); - bool accepted = ::AcceptToMemoryPool(mempool, acceptState, MakeTransactionRef(mtx), - nullptr /* plTxnReplaced */, false /* bypass_limits */, pwallet->m_default_max_tx_fee, true /* test_accept */); + bool accepted = pwallet->chain().testPeginClaimAcceptance(acceptState, MakeTransactionRef(mtx), pwallet->m_default_max_tx_fee); if (!accepted) { bilingual_str error = Untranslated(strprintf("Error: The transaction was rejected! Reason given: %s", acceptState.ToString())); throw JSONRPCError(RPC_WALLET_ERROR, error.original);