6 #ifndef BITCOIN_TXMEMPOOL_H
7 #define BITCOIN_TXMEMPOOL_H
26 #include <boost/multi_index_container.hpp>
27 #include <boost/multi_index/hashed_index.hpp>
28 #include <boost/multi_index/ordered_index.hpp>
29 #include <boost/multi_index/sequenced_index.hpp>
56 bool operator()(
const std::reference_wrapper<T>& a,
const std::reference_wrapper<T>& b)
const
58 return a.get().GetTx().GetHash() < b.get().GetTx().GetHash();
63 return a->GetTx().GetHash() < b->GetTx().GetHash();
83 typedef std::set<CTxMemPoolEntryRef, CompareIteratorByHash>
Parents;
84 typedef std::set<CTxMemPoolEntryRef, CompareIteratorByHash>
Children;
115 int64_t _nTime,
unsigned int _entryHeight,
124 std::chrono::seconds
GetTime()
const {
return std::chrono::seconds{
nTime}; }
224 return tx->GetHash();
239 return tx->GetWitnessHash();
253 double a_mod_fee, a_size, b_mod_fee, b_size;
259 double f1 = a_mod_fee * b_size;
260 double f2 = a_size * b_mod_fee;
326 double a_mod_fee, a_size, b_mod_fee, b_size;
332 double f1 = a_mod_fee * b_size;
333 double f2 = a_size * b_mod_fee;
336 return a.GetTx().GetHash() < b.GetTx().GetHash();
342 template <
typename T>
347 double f1 = (double)a.GetModifiedFee() * a.GetSizeWithAncestors();
348 double f2 = (double)a.GetModFeesWithAncestors() * a.GetTxSize();
351 mod_fee = a.GetModFeesWithAncestors();
352 size = a.GetSizeWithAncestors();
354 mod_fee = a.GetModifiedFee();
355 size = a.GetTxSize();
517 typedef boost::multi_index_container<
519 boost::multi_index::indexed_by<
521 boost::multi_index::hashed_unique<mempoolentry_txid, SaltedTxidHasher>,
523 boost::multi_index::hashed_unique<
524 boost::multi_index::tag<index_by_wtxid>,
529 boost::multi_index::ordered_non_unique<
530 boost::multi_index::tag<descendant_score>,
531 boost::multi_index::identity<CTxMemPoolEntry>,
535 boost::multi_index::ordered_non_unique<
536 boost::multi_index::tag<entry_time>,
537 boost::multi_index::identity<CTxMemPoolEntry>,
541 boost::multi_index::ordered_non_unique<
542 boost::multi_index::tag<ancestor_score>,
543 boost::multi_index::identity<CTxMemPoolEntry>,
579 using txiter = indexed_transaction_set::nth_index<0>::type::const_iterator;
586 typedef std::map<txiter, setEntries, CompareIteratorByHash>
cacheMap;
614 void setSanityCheck(
double dFrequency = 1.0) {
LOCK(
cs); nCheckFrequency =
static_cast<uint32_t
>(dFrequency * 4294967295.0); }
742 return (mapTx.count(gtxid.
GetHash()) != 0);
754 std::vector<TxMempoolInfo>
infoAll()
const;
764 if (
exists(txid)) m_unbroadcast_txids.insert(txid);
774 return m_unbroadcast_txids;
781 return m_unbroadcast_txids.count(txid) != 0;
923 typedef boost::multi_index_container<
925 boost::multi_index::indexed_by<
927 boost::multi_index::hashed_unique<
928 boost::multi_index::tag<txid_index>,
933 boost::multi_index::sequenced<
934 boost::multi_index::tag<insertion_order>
971 for (
auto const &tx : vtx) {
981 void removeEntry(indexed_disconnected_transactions::index<insertion_order>::type::iterator entry)
int64_t CAmount
Amount in satoshis (Can be negative)
The block chain is a tree shaped structure starting with the genesis block at the root,...
The BlockPolicyEstimator is used for estimating the feerate needed for a transaction to be included i...
CCoinsView backed by another CCoinsView.
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Abstract view on the open txout dataset.
CCoinsView that brings transactions from a mempool into view.
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
CCoinsViewMemPool(CCoinsView *baseIn, const CTxMemPool &mempoolIn)
const CTxMemPool & mempool
Fee rate in satoshis per kilobyte: CAmount / kB.
An outpoint - a combination of a transaction hash and an index n into its vout.
The basic transaction that is broadcasted on the network and contained in blocks.
const uint256 & GetHash() const
const uint256 & GetWitnessHash() const
EpochGuard: RAII-style guard for using epoch-based graph traversal algorithms.
EpochGuard(const CTxMemPool &in)
CTxMemPoolEntry stores data about the corresponding transaction, as well as data about all in-mempool...
const int64_t sigOpCost
Total sigop cost.
CTxMemPoolEntry(const CTransactionRef &_tx, const CAmount &_nFee, int64_t _nTime, unsigned int _entryHeight, bool spendsCoinbase, int64_t nSigOpsCost, LockPoints lp)
int64_t GetSigOpCostWithAncestors() const
void UpdateFeeDelta(int64_t feeDelta)
const bool spendsCoinbase
keep track of transactions that spend a coinbase
const size_t nTxWeight
... and avoid recomputing tx weight (also used for GetTxSize())
int64_t nSigOpCostWithAncestors
const CTransaction & GetTx() const
int64_t feeDelta
Used for determining the priority of the transaction for mining in a block.
unsigned int GetHeight() const
const Parents & GetMemPoolParentsConst() const
std::chrono::seconds GetTime() const
void UpdateDescendantState(int64_t modifySize, CAmount modifyFee, int64_t modifyCount)
std::reference_wrapper< const CTxMemPoolEntry > CTxMemPoolEntryRef
bool GetSpendsCoinbase() const
const int64_t nTime
Local time when entering the mempool.
uint64_t GetCountWithDescendants() const
const size_t nUsageSize
... and total memory usage
void UpdateLockPoints(const LockPoints &lp)
CAmount nModFeesWithAncestors
const LockPoints & GetLockPoints() const
CAmount GetModFeesWithDescendants() const
int64_t GetSigOpCost() const
uint64_t nCountWithDescendants
number of descendant transactions
void UpdateAncestorState(int64_t modifySize, CAmount modifyFee, int64_t modifyCount, int64_t modifySigOps)
uint64_t GetSizeWithAncestors() const
CTransactionRef GetSharedTx() const
uint64_t nSizeWithDescendants
... and size
uint64_t m_epoch
epoch when last touched, useful for graph algorithms
size_t DynamicMemoryUsage() const
std::set< CTxMemPoolEntryRef, CompareIteratorByHash > Children
CAmount nModFeesWithDescendants
... and total fees (all including us)
uint64_t nCountWithAncestors
const CAmount nFee
Cached to avoid expensive parent-transaction lookups.
Parents & GetMemPoolParents() const
CAmount GetModFeesWithAncestors() const
uint64_t GetSizeWithDescendants() const
uint64_t GetCountWithAncestors() const
LockPoints lockPoints
Track the height and time at which tx was final.
uint64_t nSizeWithAncestors
int64_t GetModifiedFee() const
const CAmount & GetFee() const
const Children & GetMemPoolChildrenConst() const
const unsigned int entryHeight
Chain height when entering the mempool.
Children & GetMemPoolChildren() const
size_t vTxHashesIdx
Index in mempool's vTxHashes.
std::set< CTxMemPoolEntryRef, CompareIteratorByHash > Parents
size_t GetTxWeight() const
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
void removeConflicts(const CTransaction &tx) EXCLUSIVE_LOCKS_REQUIRED(cs)
std::atomic< unsigned int > nTransactionsUpdated
Used by getblocktemplate to trigger CreateNewBlock() invocation.
void GetTransactionAncestry(const uint256 &txid, size_t &ancestors, size_t &descendants) const
Calculate the ancestor and descendant count for the given transaction.
void RemoveUnbroadcastTx(const uint256 &txid, const bool unchecked=false)
Removes a transaction from the unbroadcast set.
void PrioritiseTransaction(const uint256 &hash, const CAmount &nFeeDelta)
Affect CreateNewBlock prioritisation of transactions.
bool HasNoInputsOf(const CTransaction &tx) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Check that none of this transactions inputs are in the mempool, and thus the tx is not dependent on o...
bool visited(Optional< txiter > it) const EXCLUSIVE_LOCKS_REQUIRED(cs)
void AddUnbroadcastTx(const uint256 &txid)
Adds a transaction to the unbroadcast set.
bool visited(txiter it) const EXCLUSIVE_LOCKS_REQUIRED(cs)
visited marks a CTxMemPoolEntry as having been traversed during the lifetime of the most recently cre...
void UpdateEntryForAncestors(txiter it, const setEntries &setAncestors) EXCLUSIVE_LOCKS_REQUIRED(cs)
Set ancestor state for an entry.
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it.
void ClearPrioritisation(const uint256 &hash) EXCLUSIVE_LOCKS_REQUIRED(cs)
void trackPackageRemoved(const CFeeRate &rate) EXCLUSIVE_LOCKS_REQUIRED(cs)
CFeeRate GetMinFee(size_t sizelimit) const
The minimum fee to get into the mempool, which may itself not be enough for larger-sized transactions...
void removeRecursive(const CTransaction &tx, MemPoolRemovalReason reason) EXCLUSIVE_LOCKS_REQUIRED(cs)
void addUnchecked(const CTxMemPoolEntry &entry, bool validFeeEstimate=true) EXCLUSIVE_LOCKS_REQUIRED(cs
void removeForReorg(const CCoinsViewCache *pcoins, unsigned int nMemPoolHeight, int flags) EXCLUSIVE_LOCKS_REQUIRED(cs
void TrimToSize(size_t sizelimit, std::vector< COutPoint > *pvNoSpendsRemaining=nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs)
Remove transactions from the mempool until its dynamic size is <= sizelimit.
void UpdateTransactionsFromBlock(const std::vector< uint256 > &vHashesToUpdate) EXCLUSIVE_LOCKS_REQUIRED(cs
When adding transactions from a disconnected block back to the mempool, new mempool entries may have ...
void AddTransactionsUpdated(unsigned int n)
void UpdateChildrenForRemoval(txiter entry) EXCLUSIVE_LOCKS_REQUIRED(cs)
Sever link between specified transaction and direct children.
void setSanityCheck(double dFrequency=1.0)
double rollingMinimumFeeRate
minimum fee to get into the pool, decreases exponentially
uint32_t nCheckFrequency GUARDED_BY(cs)
Value n means that n times in 2^32 we check.
CTransactionRef get(const uint256 &hash) const
size_t DynamicMemoryUsage() const
std::vector< TxMempoolInfo > infoAll() const
indexed_transaction_set mapTx GUARDED_BY(cs)
void SetIsLoaded(bool loaded)
Sets the current loaded state.
bool IsUnbroadcastTx(const uint256 &txid) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Returns whether a txid is in the unbroadcast set.
int64_t lastRollingFeeUpdate
void UpdateParent(txiter entry, txiter parent, bool add) EXCLUSIVE_LOCKS_REQUIRED(cs)
std::map< uint256, CAmount > mapDeltas
bool exists(const uint256 &txid) const
void removeUnchecked(txiter entry, MemPoolRemovalReason reason) EXCLUSIVE_LOCKS_REQUIRED(cs)
Before calling removeUnchecked for a given transaction, UpdateForRemoveFromMempool must be called on ...
int Expire(std::chrono::seconds time) EXCLUSIVE_LOCKS_REQUIRED(cs)
Expire all transaction (and their dependencies) in the mempool older than time.
txiter get_iter_from_wtxid(const uint256 &wtxid) const EXCLUSIVE_LOCKS_REQUIRED(cs)
void UpdateAncestorsOf(bool add, txiter hash, setEntries &setAncestors) EXCLUSIVE_LOCKS_REQUIRED(cs)
Update ancestors of hash to add/remove it as a descendant transaction.
void ApplyDelta(const uint256 &hash, CAmount &nFeeDelta) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Optional< txiter > GetIter(const uint256 &txid) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Returns an iterator to the given hash, if found.
bool CalculateMemPoolAncestors(const CTxMemPoolEntry &entry, setEntries &setAncestors, uint64_t limitAncestorCount, uint64_t limitAncestorSize, uint64_t limitDescendantCount, uint64_t limitDescendantSize, std::string &errString, bool fSearchForParents=true) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Try to calculate all in-mempool ancestors of entry.
static const int ROLLING_FEE_HALFLIFE
std::set< txiter, CompareIteratorByHash > setEntries
std::vector< indexed_transaction_set::const_iterator > GetSortedDepthAndScore() const EXCLUSIVE_LOCKS_REQUIRED(cs)
void RemoveStaged(setEntries &stage, bool updateDescendants, MemPoolRemovalReason reason) EXCLUSIVE_LOCKS_REQUIRED(cs)
Remove a set of transactions from the mempool.
void removeForBlock(const std::vector< CTransactionRef > &vtx, unsigned int nBlockHeight) EXCLUSIVE_LOCKS_REQUIRED(cs)
Called when a block is connected.
std::set< uint256 > GetUnbroadcastTxs() const
Returns transactions in unbroadcast set.
void queryHashes(std::vector< uint256 > &vtxid) const
uint64_t cachedInnerUsage
sum of dynamic memory usage of all the map elements (NOT the maps themselves)
uint64_t GetSequence() const EXCLUSIVE_LOCKS_REQUIRED(cs)
indexed_transaction_set::nth_index< 0 >::type::const_iterator txiter
uint64_t GetAndIncrementSequence() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Guards this internal counter for external reporting.
EpochGuard GetFreshEpoch() const EXCLUSIVE_LOCKS_REQUIRED(cs)
void UpdateChild(txiter entry, txiter child, bool add) EXCLUSIVE_LOCKS_REQUIRED(cs)
void check(const CCoinsViewCache *pcoins) const
If sanity-checking is turned on, check makes sure the pool is consistent (does not contain two transa...
bool exists(const GenTxid >xid) const
std::map< txiter, setEntries, CompareIteratorByHash > cacheMap
void UpdateForDescendants(txiter updateIt, cacheMap &cachedDescendants, const std::set< uint256 > &setExclude) EXCLUSIVE_LOCKS_REQUIRED(cs)
UpdateForDescendants is used by UpdateTransactionsFromBlock to update the descendants for a single tr...
setEntries GetIterSet(const std::set< uint256 > &hashes) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Translate a set of hashes into a set of pool iterators to avoid repeated lookups.
const CTransaction * GetConflictTx(const COutPoint &prevout) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Get the transaction in the pool that spends the same prevout.
boost::multi_index_container< CTxMemPoolEntry, boost::multi_index::indexed_by< boost::multi_index::hashed_unique< mempoolentry_txid, SaltedTxidHasher >, boost::multi_index::hashed_unique< boost::multi_index::tag< index_by_wtxid >, mempoolentry_wtxid, SaltedTxidHasher >, boost::multi_index::ordered_non_unique< boost::multi_index::tag< descendant_score >, boost::multi_index::identity< CTxMemPoolEntry >, CompareTxMemPoolEntryByDescendantScore >, boost::multi_index::ordered_non_unique< boost::multi_index::tag< entry_time >, boost::multi_index::identity< CTxMemPoolEntry >, CompareTxMemPoolEntryByEntryTime >, boost::multi_index::ordered_non_unique< boost::multi_index::tag< ancestor_score >, boost::multi_index::identity< CTxMemPoolEntry >, CompareTxMemPoolEntryByAncestorFee > > > indexed_transaction_set
uint64_t totalTxSize
sum of all mempool tx's virtual sizes. Differs from serialized tx size since witness data is discount...
TxMempoolInfo info(const uint256 &hash) const
bool CompareDepthAndScore(const uint256 &hasha, const uint256 &hashb, bool wtxid=false)
void CalculateDescendants(txiter it, setEntries &setDescendants) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Populate setDescendants with all in-mempool descendants of hash.
unsigned long size() const
bool m_is_loaded GUARDED_BY(cs)
uint64_t m_sequence_number
void UpdateForRemoveFromMempool(const setEntries &entriesToRemove, bool updateDescendants) EXCLUSIVE_LOCKS_REQUIRED(cs)
For each transaction being removed, update ancestors and any direct children.
uint64_t CalculateDescendantMaximum(txiter entry) const EXCLUSIVE_LOCKS_REQUIRED(cs)
bool blockSinceLastRollingFeeBump
uint64_t GetTotalTxSize() const EXCLUSIVE_LOCKS_REQUIRED(cs)
bool isSpent(const COutPoint &outpoint) const
CBlockPolicyEstimator * minerPolicyEstimator
std::vector< std::pair< uint256, txiter > > vTxHashes GUARDED_BY(cs)
All tx witness hashes/entries in mapTx, in random order.
unsigned int GetTransactionsUpdated() const
void _clear() EXCLUSIVE_LOCKS_REQUIRED(cs)
bool operator()(const T &a, const T &b) const
void GetModFeeAndSize(const T &a, double &mod_fee, double &size) const
Sort an entry by max(score/size of entry's tx, score/size with all descendants).
bool operator()(const CTxMemPoolEntry &a, const CTxMemPoolEntry &b) const
void GetModFeeAndSize(const CTxMemPoolEntry &a, double &mod_fee, double &size) const
bool operator()(const CTxMemPoolEntry &a, const CTxMemPoolEntry &b) const
Sort by feerate of entry (fee/size) in descending order This is only used for transaction relay,...
bool operator()(const CTxMemPoolEntry &a, const CTxMemPoolEntry &b) const
A generic txid reference (txid or wtxid).
const uint256 & GetHash() const
size_t operator()(const uint256 &txid) const
static size_t RecursiveDynamicUsage(const CScript &script)
static size_t MallocUsage(size_t alloc)
Compute the total memory used by allocating alloc bytes.
peer m_getdata_requests erase(peer.m_getdata_requests.begin(), it)
std::deque< CInv >::iterator it
boost::optional< T > Optional
Substitute for C++17 std::optional.
std::shared_ptr< const CTransaction > CTransactionRef
uint64_t SipHashUint256(uint64_t k0, uint64_t k1, const uint256 &val)
Optimized SipHash-2-4 implementation for uint256.
bool operator()(const T &a, const T &b) const
bool operator()(const std::reference_wrapper< T > &a, const std::reference_wrapper< T > &b) const
boost::multi_index_container< CTransactionRef, boost::multi_index::indexed_by< boost::multi_index::hashed_unique< boost::multi_index::tag< txid_index >, mempoolentry_txid, SaltedTxidHasher >, boost::multi_index::sequenced< boost::multi_index::tag< insertion_order > > > > indexed_disconnected_transactions
void removeEntry(indexed_disconnected_transactions::index< insertion_order >::type::iterator entry)
indexed_disconnected_transactions queuedTx
~DisconnectedBlockTransactions()
void removeForBlock(const std::vector< CTransactionRef > &vtx)
uint64_t cachedInnerUsage
size_t DynamicMemoryUsage() const
void addTransaction(const CTransactionRef &tx)
CBlockIndex * maxInputBlock
Information about a mempool transaction.
int64_t nFeeDelta
The fee delta.
CAmount fee
Fee of the transaction.
CTransactionRef tx
The transaction itself.
std::chrono::seconds m_time
Time the transaction entered the mempool.
size_t vsize
Virtual size of the transaction.
result_type operator()(const CTxMemPoolEntry &entry) const
result_type operator()(const CTxMemPoolEntry &entry) const
DisconnectedBlockTransactions.
void operator()(CTxMemPoolEntry &e)
update_ancestor_state(int64_t _modifySize, CAmount _modifyFee, int64_t _modifyCount, int64_t _modifySigOpsCost)
void operator()(CTxMemPoolEntry &e)
update_descendant_state(int64_t _modifySize, CAmount _modifyFee, int64_t _modifyCount)
update_fee_delta(int64_t _feeDelta)
void operator()(CTxMemPoolEntry &e)
void operator()(CTxMemPoolEntry &e)
update_lock_points(const LockPoints &_lp)
#define EXCLUSIVE_LOCKS_REQUIRED(...)
MemPoolRemovalReason
Reason why a transaction was removed from the mempool, this is passed to the notification signal.
@ SIZELIMIT
Removed in size limiting.
@ BLOCK
Removed for block.
@ EXPIRY
Expired from mempool.
@ REPLACED
Removed for replacement.
@ CONFLICT
Removed for conflict with in-block transaction.
@ REORG
Removed for reorganization.
static const uint32_t MEMPOOL_HEIGHT
Fake height value used in Coin to signify they are only in the memory pool (since 0....
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
AssertLockHeld(mempool.cs)