Skip to content

Commit 71e38b9

Browse files
MarcoFalkevijaydasmp
authored andcommitted
Merge bitcoin#15323: rpc: Expose g_is_mempool_loaded via getmempoolinfo
effe81f Move g_is_mempool_loaded into CTxMemPool::m_is_loaded (Ben Woosley) bb8ae2c rpc: Expose g_is_mempool_loaded via getmempoolinfo and /rest/mempool/info.json (Ben Woosley) Pull request description: And use it to fix a race condition in mempool_persist.py: https://travis-ci.org/Empact/bitcoin/jobs/487577243 Since e.g. getrawmempool returns errors based on this status, this enables users to test it for readiness. Fixes bitcoin#12863 ACKs for commit effe81: MarcoFalke: utACK effe81f jnewbery: utACK effe81f Tree-SHA512: 74328b0c17a97efb8a000d4ee49b9a673c2b6dde7ea30c43a6a2eff961a233351c9471f9a42344412135786c02bdf2ee1b2526651bb8fed68bd94d2120c4ef86
1 parent 89c945e commit 71e38b9

File tree

8 files changed

+49
-27
lines changed

8 files changed

+49
-27
lines changed

doc/REST-interface.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,7 @@ $ curl localhost:19998/rest/getutxos/checkmempool/b2cdfd7b89def827ff8af7cd9bff76
112112

113113
Returns various information about the TX mempool.
114114
Only supports JSON as output format.
115+
* loaded : (boolean) if the mempool is fully loaded
115116
* size : (numeric) the number of transactions in the TX mempool
116117
* bytes : (numeric) size of the TX mempool in bytes
117118
* usage : (numeric) total TX mempool memory usage

src/init.cpp

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -275,8 +275,8 @@ void PrepareShutdown(InitInterfaces& interfaces)
275275
g_txindex.reset();
276276
DestroyAllBlockFilterIndexes();
277277

278-
if (g_is_mempool_loaded && gArgs.GetArg("-persistmempool", DEFAULT_PERSIST_MEMPOOL)) {
279-
DumpMempool();
278+
if (::mempool.IsLoaded() && gArgs.GetArg("-persistmempool", DEFAULT_PERSIST_MEMPOOL)) {
279+
DumpMempool(::mempool);
280280
}
281281

282282
if (fFeeEstimatesInitialized)
@@ -962,9 +962,9 @@ static void ThreadImport(std::vector<fs::path> vImportFiles)
962962
g_wallet_init_interface.AutoLockMasternodeCollaterals();
963963

964964
if (gArgs.GetArg("-persistmempool", DEFAULT_PERSIST_MEMPOOL)) {
965-
LoadMempool();
965+
LoadMempool(::mempool);
966966
}
967-
g_is_mempool_loaded = !ShutdownRequested();
967+
::mempool.SetIsLoaded(!ShutdownRequested());
968968
}
969969

970970
void PeriodicStats()

src/rpc/blockchain.cpp

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1728,6 +1728,7 @@ UniValue MempoolInfoToJSON(const CTxMemPool& pool)
17281728
// Make sure this call is atomic in the pool.
17291729
LOCK(pool.cs);
17301730
UniValue ret(UniValue::VOBJ);
1731+
ret.pushKV("loaded", pool.IsLoaded());
17311732
ret.pushKV("size", (int64_t)pool.size());
17321733
ret.pushKV("bytes", (int64_t)pool.GetTotalTxSize());
17331734
ret.pushKV("usage", (int64_t)pool.DynamicMemoryUsage());
@@ -1749,6 +1750,7 @@ static UniValue getmempoolinfo(const JSONRPCRequest& request)
17491750
{},
17501751
RPCResult{
17511752
"{\n"
1753+
" \"loaded\": true|false (boolean) True if the mempool is fully loaded\n"
17521754
" \"size\": xxxxx, (numeric) Current tx count\n"
17531755
" \"bytes\": xxxxx, (numeric) Sum of all tx sizes\n"
17541756
" \"usage\": xxxxx, (numeric) Total memory usage for the mempool\n"
@@ -2390,11 +2392,11 @@ static UniValue savemempool(const JSONRPCRequest& request)
23902392
}.ToString());
23912393
}
23922394

2393-
if (!g_is_mempool_loaded) {
2395+
if (!::mempool.IsLoaded()) {
23942396
throw JSONRPCError(RPC_MISC_ERROR, "The mempool was not loaded yet");
23952397
}
23962398

2397-
if (!DumpMempool()) {
2399+
if (!DumpMempool(::mempool)) {
23982400
throw JSONRPCError(RPC_MISC_ERROR, "Unable to dump mempool to disk");
23992401
}
24002402

src/txmempool.cpp

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1627,4 +1627,16 @@ CTxMemPool::EpochGuard::~EpochGuard()
16271627
pool.m_has_epoch_guard = false;
16281628
}
16291629

1630+
bool CTxMemPool::IsLoaded() const
1631+
{
1632+
LOCK(cs);
1633+
return m_is_loaded;
1634+
}
1635+
1636+
void CTxMemPool::SetIsLoaded(bool loaded)
1637+
{
1638+
LOCK(cs);
1639+
m_is_loaded = loaded;
1640+
}
1641+
16301642
SaltedTxidHasher::SaltedTxidHasher() : k0(GetRand(std::numeric_limits<uint64_t>::max())), k1(GetRand(std::numeric_limits<uint64_t>::max())) {}

src/txmempool.h

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -462,6 +462,8 @@ class CTxMemPool
462462

463463
void trackPackageRemoved(const CFeeRate& rate) EXCLUSIVE_LOCKS_REQUIRED(cs);
464464

465+
bool m_is_loaded GUARDED_BY(cs){false};
466+
465467
public:
466468

467469
static const int ROLLING_FEE_HALFLIFE = 60 * 60 * 12; // public only for testing
@@ -712,6 +714,12 @@ class CTxMemPool
712714
*/
713715
void GetTransactionAncestry(const uint256& txid, size_t& ancestors, size_t& descendants) const;
714716

717+
/** @returns true if the mempool is fully loaded */
718+
bool IsLoaded() const;
719+
720+
/** Sets the current loaded state */
721+
void SetIsLoaded(bool loaded);
722+
715723
unsigned long size() const
716724
{
717725
LOCK(cs);

src/validation.cpp

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -154,7 +154,6 @@ CFeeRate minRelayTxFee = CFeeRate(DEFAULT_MIN_RELAY_TX_FEE);
154154

155155
CBlockPolicyEstimator feeEstimator;
156156
CTxMemPool mempool(&feeEstimator);
157-
std::atomic_bool g_is_mempool_loaded{false};
158157

159158
// Internal stuff
160159
namespace {
@@ -5269,7 +5268,7 @@ int VersionBitsTipStateSinceHeight(const Consensus::Params& params, Consensus::D
52695268

52705269
static const uint64_t MEMPOOL_DUMP_VERSION = 1;
52715270

5272-
bool LoadMempool()
5271+
bool LoadMempool(CTxMemPool& pool)
52735272
{
52745273
const CChainParams& chainparams = Params();
52755274
int64_t nExpiryTimeout = gArgs.GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60;
@@ -5304,12 +5303,12 @@ bool LoadMempool()
53045303

53055304
CAmount amountdelta = nFeeDelta;
53065305
if (amountdelta) {
5307-
mempool.PrioritiseTransaction(tx->GetHash(), amountdelta);
5306+
pool.PrioritiseTransaction(tx->GetHash(), amountdelta);
53085307
}
53095308
CValidationState state;
53105309
if (nTime + nExpiryTimeout > nNow) {
53115310
LOCK(cs_main);
5312-
AcceptToMemoryPoolWithTime(chainparams, mempool, state, tx, nullptr /* pfMissingInputs */, nTime,
5311+
AcceptToMemoryPoolWithTime(chainparams, pool, state, tx, nullptr /* pfMissingInputs */, nTime,
53135312
false /* bypass_limits */, 0 /* nAbsurdFee */, false /* test_accept */);
53145313
if (state.IsValid()) {
53155314
++count;
@@ -5318,7 +5317,7 @@ bool LoadMempool()
53185317
// wallet(s) having loaded it while we were processing
53195318
// mempool transactions; consider these as valid, instead of
53205319
// failed, but mark them as 'already there'
5321-
if (mempool.exists(tx->GetHash())) {
5320+
if (pool.exists(tx->GetHash())) {
53225321
++already_there;
53235322
} else {
53245323
++failed;
@@ -5334,7 +5333,7 @@ bool LoadMempool()
53345333
file >> mapDeltas;
53355334

53365335
for (const auto& i : mapDeltas) {
5337-
mempool.PrioritiseTransaction(i.first, i.second);
5336+
pool.PrioritiseTransaction(i.first, i.second);
53385337
}
53395338
} catch (const std::exception& e) {
53405339
LogPrintf("Failed to deserialize mempool data on disk: %s. Continuing anyway.\n", e.what());
@@ -5345,7 +5344,7 @@ bool LoadMempool()
53455344
return true;
53465345
}
53475346

5348-
bool DumpMempool()
5347+
bool DumpMempool(const CTxMemPool& pool)
53495348
{
53505349
int64_t start = GetTimeMicros();
53515350

@@ -5356,11 +5355,11 @@ bool DumpMempool()
53565355
LOCK(dump_mutex);
53575356

53585357
{
5359-
LOCK(mempool.cs);
5360-
for (const auto &i : mempool.mapDeltas) {
5358+
LOCK(pool.cs);
5359+
for (const auto &i : pool.mapDeltas) {
53615360
mapDeltas[i.first] = i.second;
53625361
}
5363-
vinfo = mempool.infoAll();
5362+
vinfo = pool.infoAll();
53645363
}
53655364

53665365
int64_t mid = GetTimeMicros();

src/validation.h

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -121,7 +121,6 @@ struct BlockHasher
121121
extern CCriticalSection cs_main;
122122
extern CBlockPolicyEstimator feeEstimator;
123123
extern CTxMemPool mempool;
124-
extern std::atomic_bool g_is_mempool_loaded;
125124
typedef std::unordered_map<uint256, CBlockIndex*, BlockHasher> BlockMap;
126125
typedef std::unordered_multimap<uint256, CBlockIndex*, BlockHasher> PrevBlockMap;
127126
extern uint64_t nLastBlockTx;
@@ -801,10 +800,10 @@ static const unsigned int REJECT_HIGHFEE = 0x100;
801800
CBlockFileInfo* GetBlockFileInfo(size_t n);
802801

803802
/** Dump the mempool to disk. */
804-
bool DumpMempool();
803+
bool DumpMempool(const CTxMemPool& pool);
805804

806805
/** Load the mempool from disk. */
807-
bool LoadMempool();
806+
bool LoadMempool(CTxMemPool& pool);
808807

809808
//! Check whether the block associated with this index entry is pruned or not.
810809
inline bool IsBlockPruned(const CBlockIndex* pblockindex)

test/functional/mempool_persist.py

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,6 @@
3737
"""
3838
from decimal import Decimal
3939
import os
40-
import time
4140

4241
from test_framework.test_framework import BitcoinTestFramework
4342
from test_framework.util import assert_equal, assert_raises_rpc_error, wait_until
@@ -83,9 +82,10 @@ def run_test(self):
8382
self.start_node(1, extra_args=["-persistmempool=0"])
8483
self.start_node(0)
8584
self.start_node(2)
86-
# Give dashd a second to reload the mempool
87-
wait_until(lambda: len(self.nodes[0].getrawmempool()) == 5, timeout=1)
88-
wait_until(lambda: len(self.nodes[2].getrawmempool()) == 5, timeout=1)
85+
wait_until(lambda: self.nodes[0].getmempoolinfo()["loaded"], timeout=1)
86+
wait_until(lambda: self.nodes[2].getmempoolinfo()["loaded"], timeout=1)
87+
assert_equal(len(self.nodes[0].getrawmempool()), 5)
88+
assert_equal(len(self.nodes[2].getrawmempool()), 5)
8989
# The others have loaded their mempool. If node_1 loaded anything, we'd probably notice by now:
9090
assert_equal(len(self.nodes[1].getrawmempool()), 0)
9191

@@ -100,14 +100,14 @@ def run_test(self):
100100
self.log.debug("Stop-start node0 with -persistmempool=0. Verify that it doesn't load its mempool.dat file.")
101101
self.stop_nodes()
102102
self.start_node(0, extra_args=["-persistmempool=0"])
103-
# Give dashd a second to reload the mempool
104-
time.sleep(1)
103+
wait_until(lambda: self.nodes[0].getmempoolinfo()["loaded"])
105104
assert_equal(len(self.nodes[0].getrawmempool()), 0)
106105

107106
self.log.debug("Stop-start node0. Verify that it has the transactions in its mempool.")
108107
self.stop_nodes()
109108
self.start_node(0)
110-
wait_until(lambda: len(self.nodes[0].getrawmempool()) == 5)
109+
wait_until(lambda: self.nodes[0].getmempoolinfo()["loaded"])
110+
assert_equal(len(self.nodes[0].getrawmempool()), 5)
111111

112112
mempooldat0 = os.path.join(self.nodes[0].datadir, self.chain, 'mempool.dat')
113113
mempooldat1 = os.path.join(self.nodes[1].datadir, self.chain, 'mempool.dat')
@@ -120,7 +120,8 @@ def run_test(self):
120120
os.rename(mempooldat0, mempooldat1)
121121
self.stop_nodes()
122122
self.start_node(1, extra_args=[])
123-
wait_until(lambda: len(self.nodes[1].getrawmempool()) == 5)
123+
wait_until(lambda: self.nodes[1].getmempoolinfo()["loaded"])
124+
assert_equal(len(self.nodes[1].getrawmempool()), 5)
124125

125126
self.log.debug("Prevent dashd from writing mempool.dat to disk. Verify that `savemempool` fails")
126127
# to test the exception we are creating a tmp folder called mempool.dat.new

0 commit comments

Comments
 (0)