Skip to content

Commit acd9957

Browse files
committed
Merge #9208: Improve DisconnectTip performance
c1235e3 Add RecursiveDynamicUsage overload for std::shared_ptr (Russell Yanofsky) 71f1903 Store disconnected block transactions outside mempool during reorg (Suhas Daftuar) 9decd64 [qa] Relax assumptions on mempool behavior during reorg (Suhas Daftuar) Tree-SHA512: c160ad853a5cd060d0307af7606a0c77907497ed7033c9599b95e73d83f68fdfcd4214bd8a83db1c5b7a58022722b9de1ed2e6ea2e02f38a7b6c717f079dd0c6
2 parents 5c63d66 + c1235e3 commit acd9957

File tree

6 files changed

+213
-35
lines changed

6 files changed

+213
-35
lines changed

src/core_memusage.h

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,4 +63,9 @@ static inline size_t RecursiveDynamicUsage(const CBlockLocator& locator) {
6363
return memusage::DynamicUsage(locator.vHave);
6464
}
6565

66+
template<typename X>
67+
static inline size_t RecursiveDynamicUsage(const std::shared_ptr<X>& p) {
68+
return p ? memusage::DynamicUsage(p) + RecursiveDynamicUsage(*p) : 0;
69+
}
70+
6671
#endif // BITCOIN_CORE_MEMUSAGE_H

src/txmempool.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ CTxMemPoolEntry::CTxMemPoolEntry(const CTransactionRef& _tx, const CAmount& _nFe
2424
spendsCoinbase(_spendsCoinbase), sigOpCost(_sigOpsCost), lockPoints(lp)
2525
{
2626
nTxWeight = GetTransactionWeight(*tx);
27-
nUsageSize = RecursiveDynamicUsage(*tx) + memusage::DynamicUsage(tx);
27+
nUsageSize = RecursiveDynamicUsage(tx);
2828

2929
nCountWithDescendants = 1;
3030
nSizeWithDescendants = GetTxSize();

src/txmempool.h

Lines changed: 98 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
#include "boost/multi_index_container.hpp"
2525
#include "boost/multi_index/ordered_index.hpp"
2626
#include "boost/multi_index/hashed_index.hpp"
27+
#include <boost/multi_index/sequenced_index.hpp>
2728

2829
#include <boost/signals2/signal.hpp>
2930

@@ -185,14 +186,19 @@ struct update_lock_points
185186
const LockPoints& lp;
186187
};
187188

188-
// extracts a TxMemPoolEntry's transaction hash
189+
// extracts a transaction hash from CTxMempoolEntry or CTransactionRef
189190
struct mempoolentry_txid
190191
{
191192
typedef uint256 result_type;
192193
result_type operator() (const CTxMemPoolEntry &entry) const
193194
{
194195
return entry.GetTx().GetHash();
195196
}
197+
198+
result_type operator() (const CTransactionRef& tx) const
199+
{
200+
return tx->GetHash();
201+
}
196202
};
197203

198204
/** \class CompareTxMemPoolEntryByDescendantScore
@@ -662,4 +668,95 @@ class CCoinsViewMemPool : public CCoinsViewBacked
662668
bool HaveCoins(const uint256 &txid) const;
663669
};
664670

671+
/**
672+
* DisconnectedBlockTransactions
673+
674+
* During the reorg, it's desirable to re-add previously confirmed transactions
675+
* to the mempool, so that anything not re-confirmed in the new chain is
676+
* available to be mined. However, it's more efficient to wait until the reorg
677+
* is complete and process all still-unconfirmed transactions at that time,
678+
* since we expect most confirmed transactions to (typically) still be
679+
* confirmed in the new chain, and re-accepting to the memory pool is expensive
680+
* (and therefore better to not do in the middle of reorg-processing).
681+
* Instead, store the disconnected transactions (in order!) as we go, remove any
682+
* that are included in blocks in the new chain, and then process the remaining
683+
* still-unconfirmed transactions at the end.
684+
*/
685+
686+
// multi_index tag names
687+
struct txid_index {};
688+
struct insertion_order {};
689+
690+
struct DisconnectedBlockTransactions {
691+
typedef boost::multi_index_container<
692+
CTransactionRef,
693+
boost::multi_index::indexed_by<
694+
// sorted by txid
695+
boost::multi_index::hashed_unique<
696+
boost::multi_index::tag<txid_index>,
697+
mempoolentry_txid,
698+
SaltedTxidHasher
699+
>,
700+
// sorted by order in the blockchain
701+
boost::multi_index::sequenced<
702+
boost::multi_index::tag<insertion_order>
703+
>
704+
>
705+
> indexed_disconnected_transactions;
706+
707+
// It's almost certainly a logic bug if we don't clear out queuedTx before
708+
// destruction, as we add to it while disconnecting blocks, and then we
709+
// need to re-process remaining transactions to ensure mempool consistency.
710+
// For now, assert() that we've emptied out this object on destruction.
711+
// This assert() can always be removed if the reorg-processing code were
712+
// to be refactored such that this assumption is no longer true (for
713+
// instance if there was some other way we cleaned up the mempool after a
714+
// reorg, besides draining this object).
715+
~DisconnectedBlockTransactions() { assert(queuedTx.empty()); }
716+
717+
indexed_disconnected_transactions queuedTx;
718+
uint64_t cachedInnerUsage = 0;
719+
720+
// Estimate the overhead of queuedTx to be 6 pointers + an allocation, as
721+
// no exact formula for boost::multi_index_contained is implemented.
722+
size_t DynamicMemoryUsage() const {
723+
return memusage::MallocUsage(sizeof(CTransactionRef) + 6 * sizeof(void*)) * queuedTx.size() + cachedInnerUsage;
724+
}
725+
726+
void addTransaction(const CTransactionRef& tx)
727+
{
728+
queuedTx.insert(tx);
729+
cachedInnerUsage += RecursiveDynamicUsage(tx);
730+
}
731+
732+
// Remove entries based on txid_index, and update memory usage.
733+
void removeForBlock(const std::vector<CTransactionRef>& vtx)
734+
{
735+
// Short-circuit in the common case of a block being added to the tip
736+
if (queuedTx.empty()) {
737+
return;
738+
}
739+
for (auto const &tx : vtx) {
740+
auto it = queuedTx.find(tx->GetHash());
741+
if (it != queuedTx.end()) {
742+
cachedInnerUsage -= RecursiveDynamicUsage(*it);
743+
queuedTx.erase(it);
744+
}
745+
}
746+
}
747+
748+
// Remove an entry by insertion_order index, and update memory usage.
749+
void removeEntry(indexed_disconnected_transactions::index<insertion_order>::type::iterator entry)
750+
{
751+
cachedInnerUsage -= RecursiveDynamicUsage(*entry);
752+
queuedTx.get<insertion_order>().erase(entry);
753+
}
754+
755+
void clear()
756+
{
757+
cachedInnerUsage = 0;
758+
queuedTx.clear();
759+
}
760+
};
761+
665762
#endif // BITCOIN_TXMEMPOOL_H

src/validation.cpp

Lines changed: 95 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -342,6 +342,56 @@ static bool IsCurrentForFeeEstimation()
342342
return true;
343343
}
344344

345+
/* Make mempool consistent after a reorg, by re-adding or recursively erasing
346+
* disconnected block transactions from the mempool, and also removing any
347+
* other transactions from the mempool that are no longer valid given the new
348+
* tip/height.
349+
*
350+
* Note: we assume that disconnectpool only contains transactions that are NOT
351+
* confirmed in the current chain nor already in the mempool (otherwise,
352+
* in-mempool descendants of such transactions would be removed).
353+
*
354+
* Passing fAddToMempool=false will skip trying to add the transactions back,
355+
* and instead just erase from the mempool as needed.
356+
*/
357+
358+
void UpdateMempoolForReorg(DisconnectedBlockTransactions &disconnectpool, bool fAddToMempool)
359+
{
360+
AssertLockHeld(cs_main);
361+
std::vector<uint256> vHashUpdate;
362+
// disconnectpool's insertion_order index sorts the entries from
363+
// oldest to newest, but the oldest entry will be the last tx from the
364+
// latest mined block that was disconnected.
365+
// Iterate disconnectpool in reverse, so that we add transactions
366+
// back to the mempool starting with the earliest transaction that had
367+
// been previously seen in a block.
368+
auto it = disconnectpool.queuedTx.get<insertion_order>().rbegin();
369+
while (it != disconnectpool.queuedTx.get<insertion_order>().rend()) {
370+
// ignore validation errors in resurrected transactions
371+
CValidationState stateDummy;
372+
if (!fAddToMempool || (*it)->IsCoinBase() || !AcceptToMemoryPool(mempool, stateDummy, *it, false, NULL, NULL, true)) {
373+
// If the transaction doesn't make it in to the mempool, remove any
374+
// transactions that depend on it (which would now be orphans).
375+
mempool.removeRecursive(**it, MemPoolRemovalReason::REORG);
376+
} else if (mempool.exists((*it)->GetHash())) {
377+
vHashUpdate.push_back((*it)->GetHash());
378+
}
379+
++it;
380+
}
381+
disconnectpool.queuedTx.clear();
382+
// AcceptToMemoryPool/addUnchecked all assume that new mempool entries have
383+
// no in-mempool children, which is generally not true when adding
384+
// previously-confirmed transactions back to the mempool.
385+
// UpdateTransactionsFromBlock finds descendants of any transactions in
386+
// the disconnectpool that were added back and cleans up the mempool state.
387+
mempool.UpdateTransactionsFromBlock(vHashUpdate);
388+
389+
// We also need to remove any now-immature transactions
390+
mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);
391+
// Re-limit mempool size, in case we added any transactions
392+
LimitMempoolSize(mempool, GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
393+
}
394+
345395
bool AcceptToMemoryPoolWorker(CTxMemPool& pool, CValidationState& state, const CTransactionRef& ptx, bool fLimitFree,
346396
bool* pfMissingInputs, int64_t nAcceptTime, std::list<CTransactionRef>* plTxnReplaced,
347397
bool fOverrideMempoolLimit, const CAmount& nAbsurdFee, std::vector<uint256>& vHashTxnToUncache)
@@ -1877,8 +1927,17 @@ void static UpdateTip(CBlockIndex *pindexNew, const CChainParams& chainParams) {
18771927

18781928
}
18791929

1880-
/** Disconnect chainActive's tip. You probably want to call mempool.removeForReorg and manually re-limit mempool size after this, with cs_main held. */
1881-
bool static DisconnectTip(CValidationState& state, const CChainParams& chainparams, bool fBare = false)
1930+
/** Disconnect chainActive's tip.
1931+
* After calling, the mempool will be in an inconsistent state, with
1932+
* transactions from disconnected blocks being added to disconnectpool. You
1933+
* should make the mempool consistent again by calling UpdateMempoolForReorg.
1934+
* with cs_main held.
1935+
*
1936+
* If disconnectpool is NULL, then no disconnected transactions are added to
1937+
* disconnectpool (note that the caller is responsible for mempool consistency
1938+
* in any case).
1939+
*/
1940+
bool static DisconnectTip(CValidationState& state, const CChainParams& chainparams, DisconnectedBlockTransactions *disconnectpool)
18821941
{
18831942
CBlockIndex *pindexDelete = chainActive.Tip();
18841943
assert(pindexDelete);
@@ -1901,25 +1960,17 @@ bool static DisconnectTip(CValidationState& state, const CChainParams& chainpara
19011960
if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
19021961
return false;
19031962

1904-
if (!fBare) {
1905-
// Resurrect mempool transactions from the disconnected block.
1906-
std::vector<uint256> vHashUpdate;
1907-
for (const auto& it : block.vtx) {
1908-
const CTransaction& tx = *it;
1909-
// ignore validation errors in resurrected transactions
1910-
CValidationState stateDummy;
1911-
if (tx.IsCoinBase() || !AcceptToMemoryPool(mempool, stateDummy, it, false, NULL, NULL, true)) {
1912-
mempool.removeRecursive(tx, MemPoolRemovalReason::REORG);
1913-
} else if (mempool.exists(tx.GetHash())) {
1914-
vHashUpdate.push_back(tx.GetHash());
1915-
}
1963+
if (disconnectpool) {
1964+
// Save transactions to re-add to mempool at end of reorg
1965+
for (auto it = block.vtx.rbegin(); it != block.vtx.rend(); ++it) {
1966+
disconnectpool->addTransaction(*it);
1967+
}
1968+
while (disconnectpool->DynamicMemoryUsage() > MAX_DISCONNECTED_TX_POOL_SIZE * 1000) {
1969+
// Drop the earliest entry, and remove its children from the mempool.
1970+
auto it = disconnectpool->queuedTx.get<insertion_order>().begin();
1971+
mempool.removeRecursive(**it, MemPoolRemovalReason::REORG);
1972+
disconnectpool->removeEntry(it);
19161973
}
1917-
// AcceptToMemoryPool/addUnchecked all assume that new mempool entries have
1918-
// no in-mempool children, which is generally not true when adding
1919-
// previously-confirmed transactions back to the mempool.
1920-
// UpdateTransactionsFromBlock finds descendants of any transactions in this
1921-
// block that were added back and cleans up the mempool state.
1922-
mempool.UpdateTransactionsFromBlock(vHashUpdate);
19231974
}
19241975

19251976
// Update chainActive and related variables.
@@ -2007,7 +2058,7 @@ class ConnectTrace {
20072058
*
20082059
* The block is added to connectTrace if connection succeeds.
20092060
*/
2010-
bool static ConnectTip(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexNew, const std::shared_ptr<const CBlock>& pblock, ConnectTrace& connectTrace)
2061+
bool static ConnectTip(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexNew, const std::shared_ptr<const CBlock>& pblock, ConnectTrace& connectTrace, DisconnectedBlockTransactions &disconnectpool)
20112062
{
20122063
assert(pindexNew->pprev == chainActive.Tip());
20132064
// Read block from disk.
@@ -2049,6 +2100,7 @@ bool static ConnectTip(CValidationState& state, const CChainParams& chainparams,
20492100
LogPrint(BCLog::BENCH, " - Writing chainstate: %.2fms [%.2fs]\n", (nTime5 - nTime4) * 0.001, nTimeChainState * 0.000001);
20502101
// Remove conflicting transactions from the mempool.;
20512102
mempool.removeForBlock(blockConnecting.vtx, pindexNew->nHeight);
2103+
disconnectpool.removeForBlock(blockConnecting.vtx);
20522104
// Update chainActive & related variables.
20532105
UpdateTip(pindexNew, chainparams);
20542106

@@ -2142,9 +2194,14 @@ static bool ActivateBestChainStep(CValidationState& state, const CChainParams& c
21422194

21432195
// Disconnect active blocks which are no longer in the best chain.
21442196
bool fBlocksDisconnected = false;
2197+
DisconnectedBlockTransactions disconnectpool;
21452198
while (chainActive.Tip() && chainActive.Tip() != pindexFork) {
2146-
if (!DisconnectTip(state, chainparams))
2199+
if (!DisconnectTip(state, chainparams, &disconnectpool)) {
2200+
// This is likely a fatal error, but keep the mempool consistent,
2201+
// just in case. Only remove from the mempool in this case.
2202+
UpdateMempoolForReorg(disconnectpool, false);
21472203
return false;
2204+
}
21482205
fBlocksDisconnected = true;
21492206
}
21502207

@@ -2167,7 +2224,7 @@ static bool ActivateBestChainStep(CValidationState& state, const CChainParams& c
21672224

21682225
// Connect new blocks.
21692226
BOOST_REVERSE_FOREACH(CBlockIndex *pindexConnect, vpindexToConnect) {
2170-
if (!ConnectTip(state, chainparams, pindexConnect, pindexConnect == pindexMostWork ? pblock : std::shared_ptr<const CBlock>(), connectTrace)) {
2227+
if (!ConnectTip(state, chainparams, pindexConnect, pindexConnect == pindexMostWork ? pblock : std::shared_ptr<const CBlock>(), connectTrace, disconnectpool)) {
21712228
if (state.IsInvalid()) {
21722229
// The block violates a consensus rule.
21732230
if (!state.CorruptionPossible())
@@ -2178,6 +2235,9 @@ static bool ActivateBestChainStep(CValidationState& state, const CChainParams& c
21782235
break;
21792236
} else {
21802237
// A system error occurred (disk space, database error, ...).
2238+
// Make the mempool consistent with the current tip, just in case
2239+
// any observers try to use it before shutdown.
2240+
UpdateMempoolForReorg(disconnectpool, false);
21812241
return false;
21822242
}
21832243
} else {
@@ -2192,8 +2252,9 @@ static bool ActivateBestChainStep(CValidationState& state, const CChainParams& c
21922252
}
21932253

21942254
if (fBlocksDisconnected) {
2195-
mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);
2196-
LimitMempoolSize(mempool, GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
2255+
// If any blocks were disconnected, disconnectpool may be non empty. Add
2256+
// any disconnected transactions back to the mempool.
2257+
UpdateMempoolForReorg(disconnectpool, true);
21972258
}
21982259
mempool.check(pcoinsTip);
21992260

@@ -2342,20 +2403,25 @@ bool InvalidateBlock(CValidationState& state, const CChainParams& chainparams, C
23422403
setDirtyBlockIndex.insert(pindex);
23432404
setBlockIndexCandidates.erase(pindex);
23442405

2406+
DisconnectedBlockTransactions disconnectpool;
23452407
while (chainActive.Contains(pindex)) {
23462408
CBlockIndex *pindexWalk = chainActive.Tip();
23472409
pindexWalk->nStatus |= BLOCK_FAILED_CHILD;
23482410
setDirtyBlockIndex.insert(pindexWalk);
23492411
setBlockIndexCandidates.erase(pindexWalk);
23502412
// ActivateBestChain considers blocks already in chainActive
23512413
// unconditionally valid already, so force disconnect away from it.
2352-
if (!DisconnectTip(state, chainparams)) {
2353-
mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);
2414+
if (!DisconnectTip(state, chainparams, &disconnectpool)) {
2415+
// It's probably hopeless to try to make the mempool consistent
2416+
// here if DisconnectTip failed, but we can try.
2417+
UpdateMempoolForReorg(disconnectpool, false);
23542418
return false;
23552419
}
23562420
}
23572421

2358-
LimitMempoolSize(mempool, GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
2422+
// DisconnectTip will add transactions to disconnectpool; try to add these
2423+
// back to the mempool.
2424+
UpdateMempoolForReorg(disconnectpool, true);
23592425

23602426
// The resulting new best tip may not be in setBlockIndexCandidates anymore, so
23612427
// add it again.
@@ -2368,7 +2434,6 @@ bool InvalidateBlock(CValidationState& state, const CChainParams& chainparams, C
23682434
}
23692435

23702436
InvalidChainFound(pindex);
2371-
mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);
23722437
uiInterface.NotifyBlockTip(IsInitialBlockDownload(), pindex->pprev);
23732438
return true;
23742439
}
@@ -3482,7 +3547,7 @@ bool RewindBlockIndex(const CChainParams& params)
34823547
// of the blockchain).
34833548
break;
34843549
}
3485-
if (!DisconnectTip(state, params, true)) {
3550+
if (!DisconnectTip(state, params, NULL)) {
34863551
return error("RewindBlockIndex: unable to disconnect block at height %i", pindex->nHeight);
34873552
}
34883553
// Occasionally flush state to disk.

src/validation.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,8 @@ static const unsigned int DEFAULT_DESCENDANT_LIMIT = 25;
7070
static const unsigned int DEFAULT_DESCENDANT_SIZE_LIMIT = 101;
7171
/** Default for -mempoolexpiry, expiration time for mempool transactions in hours */
7272
static const unsigned int DEFAULT_MEMPOOL_EXPIRY = 336;
73+
/** Maximum kilobytes for transactions to store for processing during reorg */
74+
static const unsigned int MAX_DISCONNECTED_TX_POOL_SIZE = 20000;
7375
/** The maximum size of a blk?????.dat file (since 0.8) */
7476
static const unsigned int MAX_BLOCKFILE_SIZE = 0x8000000; // 128 MiB
7577
/** The pre-allocation chunk size for blk?????.dat files (since 0.8) */

0 commit comments

Comments
 (0)