Skip to content

Commit 0708705

Browse files
author
MarcoFalke
committed
Merge #19556: Remove mempool global
fafb381 Remove mempool global (MarcoFalke) fa0359c Remove mempool global from p2p (MarcoFalke) eeee110 Remove mempool global from init (MarcoFalke) Pull request description: This refactor unlocks some nice potential features, such as, but not limited to: * Removing the fee estimates global (would avoid slightly fragile workarounds such as #18766) * Making the mempool optional for a "blocksonly" operation mode Even absent those features, the new code without the global should be easier to maintain, read and write tests for. ACKs for top commit: jnewbery: utACK fafb381 hebasto: ACK fafb381, I have reviewed the code and it looks OK, I agree it can be merged. darosior: ACK fafb381 Tree-SHA512: a2e696dc377e2e81eaf9c389e6d13dde4a48d81f3538df88f4da502d3012dd61078495140ab5a5854f360a06249fe0e1f6a094c4e006d8b5cc2552a946becf26
2 parents 78cb45d + fafb381 commit 0708705

File tree

9 files changed

+38
-28
lines changed

9 files changed

+38
-28
lines changed

src/init.cpp

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -187,7 +187,7 @@ void Shutdown(NodeContext& node)
187187
/// Be sure that anything that writes files or flushes caches only does this if the respective
188188
/// module was initialized.
189189
util::ThreadRename("shutoff");
190-
mempool.AddTransactionsUpdated(1);
190+
if (node.mempool) node.mempool->AddTransactionsUpdated(1);
191191

192192
StopHTTPRPC();
193193
StopREST();
@@ -231,8 +231,8 @@ void Shutdown(NodeContext& node)
231231
node.connman.reset();
232232
node.banman.reset();
233233

234-
if (::mempool.IsLoaded() && node.args->GetArg("-persistmempool", DEFAULT_PERSIST_MEMPOOL)) {
235-
DumpMempool(::mempool);
234+
if (node.mempool && node.mempool->IsLoaded() && node.args->GetArg("-persistmempool", DEFAULT_PERSIST_MEMPOOL)) {
235+
DumpMempool(*node.mempool);
236236
}
237237

238238
if (fFeeEstimatesInitialized)
@@ -302,7 +302,7 @@ void Shutdown(NodeContext& node)
302302
GetMainSignals().UnregisterBackgroundSignalScheduler();
303303
globalVerifyHandle.reset();
304304
ECC_Stop();
305-
node.mempool = nullptr;
305+
node.mempool.reset();
306306
node.chainman = nullptr;
307307
node.scheduler.reset();
308308

@@ -738,10 +738,7 @@ static void ThreadImport(ChainstateManager& chainman, std::vector<fs::path> vImp
738738
return;
739739
}
740740
} // End scope of CImportingNow
741-
if (args.GetArg("-persistmempool", DEFAULT_PERSIST_MEMPOOL)) {
742-
LoadMempool(::mempool);
743-
}
744-
::mempool.SetIsLoaded(!ShutdownRequested());
741+
chainman.ActiveChainstate().LoadMempool(args);
745742
}
746743

747744
/** Sanity checks
@@ -1054,11 +1051,6 @@ bool AppInitParameterInteraction(const ArgsManager& args)
10541051
}
10551052
}
10561053

1057-
// Checkmempool and checkblockindex default to true in regtest mode
1058-
int ratio = std::min<int>(std::max<int>(args.GetArg("-checkmempool", chainparams.DefaultConsistencyChecks() ? 1 : 0), 0), 1000000);
1059-
if (ratio != 0) {
1060-
mempool.setSanityCheck(1.0 / ratio);
1061-
}
10621054
fCheckBlockIndex = args.GetBoolArg("-checkblockindex", chainparams.DefaultConsistencyChecks());
10631055
fCheckpointsEnabled = args.GetBoolArg("-checkpoints", DEFAULT_CHECKPOINTS_ENABLED);
10641056

@@ -1368,10 +1360,18 @@ bool AppInitMain(const util::Ref& context, NodeContext& node, interfaces::BlockA
13681360
node.banman = MakeUnique<BanMan>(GetDataDir() / "banlist.dat", &uiInterface, args.GetArg("-bantime", DEFAULT_MISBEHAVING_BANTIME));
13691361
assert(!node.connman);
13701362
node.connman = MakeUnique<CConnman>(GetRand(std::numeric_limits<uint64_t>::max()), GetRand(std::numeric_limits<uint64_t>::max()), args.GetBoolArg("-networkactive", true));
1363+
13711364
// Make mempool generally available in the node context. For example the connection manager, wallet, or RPC threads,
13721365
// which are all started after this, may use it from the node context.
13731366
assert(!node.mempool);
1374-
node.mempool = &::mempool;
1367+
node.mempool = MakeUnique<CTxMemPool>(&::feeEstimator);
1368+
if (node.mempool) {
1369+
int ratio = std::min<int>(std::max<int>(args.GetArg("-checkmempool", chainparams.DefaultConsistencyChecks() ? 1 : 0), 0), 1000000);
1370+
if (ratio != 0) {
1371+
node.mempool->setSanityCheck(1.0 / ratio);
1372+
}
1373+
}
1374+
13751375
assert(!node.chainman);
13761376
node.chainman = &g_chainman;
13771377
ChainstateManager& chainman = *Assert(node.chainman);
@@ -1559,7 +1559,7 @@ bool AppInitMain(const util::Ref& context, NodeContext& node, interfaces::BlockA
15591559
chainman.m_total_coinstip_cache = nCoinCacheUsage;
15601560
chainman.m_total_coinsdb_cache = nCoinDBCache;
15611561

1562-
UnloadBlockIndex(node.mempool);
1562+
UnloadBlockIndex(node.mempool.get());
15631563

15641564
// new CBlockTreeDB tries to delete the existing file, which
15651565
// fails if it's still open from the previous loop. Close it first:

src/net_processing.cpp

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1710,7 +1710,7 @@ void static ProcessGetBlockData(CNode& pfrom, const CChainParams& chainparams, c
17101710
}
17111711

17121712
//! Determine whether or not a peer can request a transaction, and return it (or nullptr if not found or not allowed).
1713-
CTransactionRef static FindTxForGetData(const CNode& peer, const GenTxid& gtxid, const std::chrono::seconds mempool_req, const std::chrono::seconds now) LOCKS_EXCLUDED(cs_main)
1713+
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)
17141714
{
17151715
auto txinfo = mempool.info(gtxid);
17161716
if (txinfo.tx) {
@@ -1766,7 +1766,7 @@ void static ProcessGetData(CNode& pfrom, const CChainParams& chainparams, CConnm
17661766
continue;
17671767
}
17681768

1769-
CTransactionRef tx = FindTxForGetData(pfrom, ToGenTxid(inv), mempool_req, now);
1769+
CTransactionRef tx = FindTxForGetData(mempool, pfrom, ToGenTxid(inv), mempool_req, now);
17701770
if (tx) {
17711771
// WTX and WITNESS_TX imply we serialize with witness
17721772
int nSendFlags = (inv.IsMsgTx() ? SERIALIZE_TRANSACTION_NO_WITNESS : 0);
@@ -2732,7 +2732,7 @@ void PeerLogicValidation::ProcessMessage(CNode& pfrom, const std::string& msg_ty
27322732
}
27332733
} else if (inv.IsGenTxMsg()) {
27342734
const GenTxid gtxid = ToGenTxid(inv);
2735-
const bool fAlreadyHave = AlreadyHaveTx(gtxid, mempool);
2735+
const bool fAlreadyHave = AlreadyHaveTx(gtxid, m_mempool);
27362736
LogPrint(BCLog::NET, "got inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom.GetId());
27372737

27382738
pfrom.AddKnownTx(inv.hash);
@@ -3003,7 +3003,7 @@ void PeerLogicValidation::ProcessMessage(CNode& pfrom, const std::string& msg_ty
30033003

30043004
std::list<CTransactionRef> lRemovedTxn;
30053005

3006-
// We do the AlreadyHave() check using wtxid, rather than txid - in the
3006+
// We do the AlreadyHaveTx() check using wtxid, rather than txid - in the
30073007
// absence of witness malleation, this is strictly better, because the
30083008
// recent rejects filter may contain the wtxid but rarely contains
30093009
// the txid of a segwit transaction that has been rejected.

src/node/context.cpp

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
#include <net.h>
1010
#include <net_processing.h>
1111
#include <scheduler.h>
12+
#include <txmempool.h>
1213

1314
NodeContext::NodeContext() {}
1415
NodeContext::~NodeContext() {}

src/node/context.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ class WalletClient;
3535
//! be used without pulling in unwanted dependencies or functionality.
3636
struct NodeContext {
3737
std::unique_ptr<CConnman> connman;
38-
CTxMemPool* mempool{nullptr}; // Currently a raw pointer because the memory is not managed by this struct
38+
std::unique_ptr<CTxMemPool> mempool;
3939
std::unique_ptr<PeerLogicValidation> peer_logic;
4040
ChainstateManager* chainman{nullptr}; // Currently a raw pointer because the memory is not managed by this struct
4141
std::unique_ptr<BanMan> banman;

src/rest.cpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,7 @@ static CTxMemPool* GetMemPool(const util::Ref& context, HTTPRequest* req)
102102
RESTERR(req, HTTP_NOT_FOUND, "Mempool disabled or instance not found");
103103
return nullptr;
104104
}
105-
return node->mempool;
105+
return node->mempool.get();
106106
}
107107

108108
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
393393
const NodeContext* const node = GetNodeContext(context, req);
394394
if (!node) return false;
395395
uint256 hashBlock = uint256();
396-
const CTransactionRef tx = GetTransaction(/* block_index */ nullptr, node->mempool, hash, Params().GetConsensus(), hashBlock);
396+
const CTransactionRef tx = GetTransaction(/* block_index */ nullptr, node->mempool.get(), hash, Params().GetConsensus(), hashBlock);
397397
if (!tx) {
398398
return RESTERR(req, HTTP_NOT_FOUND, hashStr + " not found");
399399
}

src/rpc/rawtransaction.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -191,7 +191,7 @@ static UniValue getrawtransaction(const JSONRPCRequest& request)
191191
}
192192

193193
uint256 hash_block;
194-
const CTransactionRef tx = GetTransaction(blockindex, node.mempool, hash, Params().GetConsensus(), hash_block);
194+
const CTransactionRef tx = GetTransaction(blockindex, node.mempool.get(), hash, Params().GetConsensus(), hash_block);
195195
if (!tx) {
196196
std::string errmsg;
197197
if (blockindex) {

src/test/util/setup_common.cpp

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -141,7 +141,7 @@ TestingSetup::TestingSetup(const std::string& chainName, const std::vector<const
141141

142142
pblocktree.reset(new CBlockTreeDB(1 << 20, true));
143143

144-
m_node.mempool = &::mempool;
144+
m_node.mempool = MakeUnique<CTxMemPool>(&::feeEstimator);
145145
m_node.mempool->setSanityCheck(1.0);
146146

147147
m_node.chainman = &::g_chainman;
@@ -187,8 +187,8 @@ TestingSetup::~TestingSetup()
187187
m_node.connman.reset();
188188
m_node.banman.reset();
189189
m_node.args = nullptr;
190-
UnloadBlockIndex(m_node.mempool);
191-
m_node.mempool = nullptr;
190+
UnloadBlockIndex(m_node.mempool.get());
191+
m_node.mempool.reset();
192192
m_node.scheduler.reset();
193193
m_node.chainman->Reset();
194194
m_node.chainman = nullptr;

src/validation.cpp

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,6 @@ arith_uint256 nMinimumChainWork;
148148
CFeeRate minRelayTxFee = CFeeRate(DEFAULT_MIN_RELAY_TX_FEE);
149149

150150
CBlockPolicyEstimator feeEstimator;
151-
CTxMemPool mempool(&feeEstimator);
152151

153152
// Internal stuff
154153
namespace {
@@ -4227,6 +4226,14 @@ bool static LoadBlockIndexDB(ChainstateManager& chainman, const CChainParams& ch
42274226
return true;
42284227
}
42294228

4229+
void CChainState::LoadMempool(const ArgsManager& args)
4230+
{
4231+
if (args.GetArg("-persistmempool", DEFAULT_PERSIST_MEMPOOL)) {
4232+
::LoadMempool(m_mempool);
4233+
}
4234+
m_mempool.SetIsLoaded(!ShutdownRequested());
4235+
}
4236+
42304237
bool CChainState::LoadChainTip(const CChainParams& chainparams)
42314238
{
42324239
AssertLockHeld(cs_main);

src/validation.h

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,6 @@ enum class SynchronizationState {
113113

114114
extern RecursiveMutex cs_main;
115115
extern CBlockPolicyEstimator feeEstimator;
116-
extern CTxMemPool mempool;
117116
typedef std::unordered_map<uint256, CBlockIndex*, BlockHasher> BlockMap;
118117
extern Mutex g_best_block_mutex;
119118
extern std::condition_variable g_best_block_cv;
@@ -671,6 +670,9 @@ class CChainState {
671670
*/
672671
void CheckBlockIndex(const Consensus::Params& consensusParams);
673672

673+
/** Load the persisted mempool from disk */
674+
void LoadMempool(const ArgsManager& args);
675+
674676
/** Update the chain tip based on database information, i.e. CoinsTip()'s best block. */
675677
bool LoadChainTip(const CChainParams& chainparams) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
676678

0 commit comments

Comments
 (0)