Skip to content

Commit fd6580e

Browse files
committed
[refactor] txmempool: split epoch logic into class
1 parent b09ad73 commit fd6580e

File tree

4 files changed

+107
-63
lines changed

4 files changed

+107
-63
lines changed

src/Makefile.am

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -231,6 +231,7 @@ BITCOIN_CORE_H = \
231231
util/bip32.h \
232232
util/bytevectorhash.h \
233233
util/check.h \
234+
util/epochguard.h \
234235
util/error.h \
235236
util/fees.h \
236237
util/golombrice.h \

src/txmempool.cpp

Lines changed: 2 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ CTxMemPoolEntry::CTxMemPoolEntry(const CTransactionRef& _tx, const CAmount& _nFe
2323
int64_t _nTime, unsigned int _entryHeight,
2424
bool _spendsCoinbase, int64_t _sigOpsCost, LockPoints lp)
2525
: tx(_tx), nFee(_nFee), nTxWeight(GetTransactionWeight(*tx)), nUsageSize(RecursiveDynamicUsage(tx)), nTime(_nTime), entryHeight(_entryHeight),
26-
spendsCoinbase(_spendsCoinbase), sigOpCost(_sigOpsCost), lockPoints(lp), m_epoch(0)
26+
spendsCoinbase(_spendsCoinbase), sigOpCost(_sigOpsCost), lockPoints(lp)
2727
{
2828
nCountWithDescendants = 1;
2929
nSizeWithDescendants = GetTxSize();
@@ -132,7 +132,7 @@ void CTxMemPool::UpdateTransactionsFromBlock(const std::vector<uint256> &vHashes
132132
// include them, and update their CTxMemPoolEntry::m_parents to include this tx.
133133
// we cache the in-mempool children to avoid duplicate updates
134134
{
135-
const auto epoch = GetFreshEpoch();
135+
WITH_FRESH_EPOCH(m_epoch);
136136
for (; iter != mapNextTx.end() && iter->first->hash == hash; ++iter) {
137137
const uint256 &childHash = iter->second->GetHash();
138138
txiter childIter = mapTx.find(childHash);
@@ -1117,22 +1117,3 @@ void CTxMemPool::SetIsLoaded(bool loaded)
11171117
LOCK(cs);
11181118
m_is_loaded = loaded;
11191119
}
1120-
1121-
1122-
CTxMemPool::EpochGuard CTxMemPool::GetFreshEpoch() const
1123-
{
1124-
return EpochGuard(*this);
1125-
}
1126-
CTxMemPool::EpochGuard::EpochGuard(const CTxMemPool& in) : pool(in)
1127-
{
1128-
assert(!pool.m_has_epoch_guard);
1129-
++pool.m_epoch;
1130-
pool.m_has_epoch_guard = true;
1131-
}
1132-
1133-
CTxMemPool::EpochGuard::~EpochGuard()
1134-
{
1135-
// prevents stale results being used
1136-
++pool.m_epoch;
1137-
pool.m_has_epoch_guard = false;
1138-
}

src/txmempool.h

Lines changed: 13 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
#include <primitives/transaction.h>
2222
#include <random.h>
2323
#include <sync.h>
24+
#include <util/epochguard.h>
2425
#include <util/hasher.h>
2526

2627
#include <boost/multi_index_container.hpp>
@@ -63,6 +64,7 @@ struct CompareIteratorByHash {
6364
return a->GetTx().GetHash() < b->GetTx().GetHash();
6465
}
6566
};
67+
6668
/** \class CTxMemPoolEntry
6769
*
6870
* CTxMemPoolEntry stores data about the corresponding transaction, as well
@@ -155,7 +157,7 @@ class CTxMemPoolEntry
155157
Children& GetMemPoolChildren() const { return m_children; }
156158

157159
mutable size_t vTxHashesIdx; //!< Index in mempool's vTxHashes
158-
mutable uint64_t m_epoch; //!< epoch when last touched, useful for graph algorithms
160+
mutable Epoch::Marker m_epoch_marker; //!< epoch when last touched, useful for graph algorithms
159161
};
160162

161163
// Helpers for modifying CTxMemPool::mapTx, which is a boost multi_index.
@@ -485,8 +487,7 @@ class CTxMemPool
485487
mutable int64_t lastRollingFeeUpdate;
486488
mutable bool blockSinceLastRollingFeeBump;
487489
mutable double rollingMinimumFeeRate; //!< minimum fee to get into the pool, decreases exponentially
488-
mutable uint64_t m_epoch{0};
489-
mutable bool m_has_epoch_guard{false};
490+
mutable Epoch m_epoch GUARDED_BY(cs);
490491

491492
// In-memory counter for external mempool tracking purposes.
492493
// This number is incremented once every time a transaction
@@ -665,7 +666,7 @@ class CTxMemPool
665666
* for). Note: vHashesToUpdate should be the set of transactions from the
666667
* disconnected block that have been accepted back into the mempool.
667668
*/
668-
void UpdateTransactionsFromBlock(const std::vector<uint256>& vHashesToUpdate) EXCLUSIVE_LOCKS_REQUIRED(cs, cs_main);
669+
void UpdateTransactionsFromBlock(const std::vector<uint256>& vHashesToUpdate) EXCLUSIVE_LOCKS_REQUIRED(cs, cs_main) LOCKS_EXCLUDED(m_epoch);
669670

670671
/** Try to calculate all in-mempool ancestors of entry.
671672
* (these are all calculated including the tx itself)
@@ -826,52 +827,22 @@ class CTxMemPool
826827
*/
827828
void removeUnchecked(txiter entry, MemPoolRemovalReason reason) EXCLUSIVE_LOCKS_REQUIRED(cs);
828829
public:
829-
/** EpochGuard: RAII-style guard for using epoch-based graph traversal algorithms.
830-
* When walking ancestors or descendants, we generally want to avoid
831-
* visiting the same transactions twice. Some traversal algorithms use
832-
* std::set (or setEntries) to deduplicate the transaction we visit.
833-
* However, use of std::set is algorithmically undesirable because it both
834-
* adds an asymptotic factor of O(log n) to traverals cost and triggers O(n)
835-
* more dynamic memory allocations.
836-
* In many algorithms we can replace std::set with an internal mempool
837-
* counter to track the time (or, "epoch") that we began a traversal, and
838-
* check + update a per-transaction epoch for each transaction we look at to
839-
* determine if that transaction has not yet been visited during the current
840-
* traversal's epoch.
841-
* Algorithms using std::set can be replaced on a one by one basis.
842-
* Both techniques are not fundamentally incompatible across the codebase.
843-
* Generally speaking, however, the remaining use of std::set for mempool
844-
* traversal should be viewed as a TODO for replacement with an epoch based
845-
* traversal, rather than a preference for std::set over epochs in that
846-
* algorithm.
847-
*/
848-
class EpochGuard {
849-
const CTxMemPool& pool;
850-
public:
851-
explicit EpochGuard(const CTxMemPool& in);
852-
~EpochGuard();
853-
};
854-
// N.B. GetFreshEpoch modifies mutable state via the EpochGuard construction
855-
// (and later destruction)
856-
EpochGuard GetFreshEpoch() const EXCLUSIVE_LOCKS_REQUIRED(cs);
857-
858830
/** visited marks a CTxMemPoolEntry as having been traversed
859-
* during the lifetime of the most recently created EpochGuard
831+
* during the lifetime of the most recently created Epoch::Guard
860832
* and returns false if we are the first visitor, true otherwise.
861833
*
862-
* An EpochGuard must be held when visited is called or an assert will be
834+
* An Epoch::Guard must be held when visited is called or an assert will be
863835
* triggered.
864836
*
865837
*/
866-
bool visited(txiter it) const EXCLUSIVE_LOCKS_REQUIRED(cs) {
867-
assert(m_has_epoch_guard);
868-
bool ret = it->m_epoch >= m_epoch;
869-
it->m_epoch = std::max(it->m_epoch, m_epoch);
870-
return ret;
838+
bool visited(const txiter it) const EXCLUSIVE_LOCKS_REQUIRED(cs, m_epoch)
839+
{
840+
return m_epoch.visited(it->m_epoch_marker);
871841
}
872842

873-
bool visited(Optional<txiter> it) const EXCLUSIVE_LOCKS_REQUIRED(cs) {
874-
assert(m_has_epoch_guard);
843+
bool visited(Optional<txiter> it) const EXCLUSIVE_LOCKS_REQUIRED(cs, m_epoch)
844+
{
845+
assert(m_epoch.guarded()); // verify guard even when it==nullopt
875846
return !it || visited(*it);
876847
}
877848
};

src/util/epochguard.h

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
// Copyright (c) 2009-2010 Satoshi Nakamoto
2+
// Copyright (c) 2009-2020 The Bitcoin Core developers
3+
// Distributed under the MIT software license, see the accompanying
4+
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
5+
6+
#ifndef BITCOIN_UTIL_EPOCHGUARD_H
7+
#define BITCOIN_UTIL_EPOCHGUARD_H
8+
9+
#include <threadsafety.h>
10+
11+
#include <cassert>
12+
13+
/** Epoch: RAII-style guard for using epoch-based graph traversal algorithms.
14+
* When walking ancestors or descendants, we generally want to avoid
15+
* visiting the same transactions twice. Some traversal algorithms use
16+
* std::set (or setEntries) to deduplicate the transaction we visit.
17+
* However, use of std::set is algorithmically undesirable because it both
18+
* adds an asymptotic factor of O(log n) to traversals cost and triggers O(n)
19+
* more dynamic memory allocations.
20+
* In many algorithms we can replace std::set with an internal mempool
21+
* counter to track the time (or, "epoch") that we began a traversal, and
22+
* check + update a per-transaction epoch for each transaction we look at to
23+
* determine if that transaction has not yet been visited during the current
24+
* traversal's epoch.
25+
* Algorithms using std::set can be replaced on a one by one basis.
26+
* Both techniques are not fundamentally incompatible across the codebase.
27+
* Generally speaking, however, the remaining use of std::set for mempool
28+
* traversal should be viewed as a TODO for replacement with an epoch based
29+
* traversal, rather than a preference for std::set over epochs in that
30+
* algorithm.
31+
*/
32+
33+
class LOCKABLE Epoch
34+
{
35+
private:
36+
uint64_t m_raw_epoch = 0;
37+
bool m_guarded = false;
38+
39+
public:
40+
Epoch() = default;
41+
Epoch(const Epoch&) = delete;
42+
Epoch& operator=(const Epoch&) = delete;
43+
44+
bool guarded() const { return m_guarded; }
45+
46+
class Marker
47+
{
48+
private:
49+
uint64_t m_marker = 0;
50+
51+
// only allow modification via Epoch member functions
52+
friend class Epoch;
53+
Marker& operator=(const Marker&) = delete;
54+
};
55+
56+
class SCOPED_LOCKABLE Guard
57+
{
58+
private:
59+
Epoch& m_epoch;
60+
61+
public:
62+
explicit Guard(Epoch& epoch) EXCLUSIVE_LOCK_FUNCTION(epoch) : m_epoch(epoch)
63+
{
64+
assert(!m_epoch.m_guarded);
65+
++m_epoch.m_raw_epoch;
66+
m_epoch.m_guarded = true;
67+
}
68+
~Guard() UNLOCK_FUNCTION()
69+
{
70+
assert(m_epoch.m_guarded);
71+
++m_epoch.m_raw_epoch; // ensure clear separation between epochs
72+
m_epoch.m_guarded = false;
73+
}
74+
};
75+
76+
bool visited(Marker& marker) const EXCLUSIVE_LOCKS_REQUIRED(*this)
77+
{
78+
assert(m_guarded);
79+
if (marker.m_marker < m_raw_epoch) {
80+
// marker is from a previous epoch, so this is its first visit
81+
marker.m_marker = m_raw_epoch;
82+
return false;
83+
} else {
84+
return true;
85+
}
86+
}
87+
};
88+
89+
#define WITH_FRESH_EPOCH(epoch) const Epoch::Guard PASTE2(epoch_guard_, __COUNTER__)(epoch)
90+
91+
#endif // BITCOIN_UTIL_EPOCHGUARD_H

0 commit comments

Comments
 (0)