6 #ifndef BITCOIN_TXMEMPOOL_H
7 #define BITCOIN_TXMEMPOOL_H
14 #include <string_view>
35 #include <boost/multi_index/hashed_index.hpp>
36 #include <boost/multi_index/ordered_index.hpp>
37 #include <boost/multi_index/sequenced_index.hpp>
38 #include <boost/multi_index_container.hpp>
78 return tx->GetWitnessHash();
92 double a_mod_fee, a_size, b_mod_fee, b_size;
98 double f1 = a_mod_fee * b_size;
99 double f2 = a_size * b_mod_fee;
165 double a_mod_fee, a_size, b_mod_fee, b_size;
171 double f1 = a_mod_fee * b_size;
172 double f2 = a_size * b_mod_fee;
175 return a.GetTx().GetHash() < b.GetTx().GetHash();
181 template <
typename T>
186 double f1 = (double)a.GetModifiedFee() * a.GetSizeWithAncestors();
187 double f2 = (double)a.GetModFeesWithAncestors() * a.GetTxSize();
190 mod_fee = a.GetModFeesWithAncestors();
191 size = a.GetSizeWithAncestors();
193 mod_fee = a.GetModifiedFee();
194 size = a.GetTxSize();
346 typedef boost::multi_index_container<
348 boost::multi_index::indexed_by<
350 boost::multi_index::hashed_unique<mempoolentry_txid, SaltedTxidHasher>,
352 boost::multi_index::hashed_unique<
353 boost::multi_index::tag<index_by_wtxid>,
358 boost::multi_index::ordered_non_unique<
359 boost::multi_index::tag<descendant_score>,
360 boost::multi_index::identity<CTxMemPoolEntry>,
364 boost::multi_index::ordered_non_unique<
365 boost::multi_index::tag<entry_time>,
366 boost::multi_index::identity<CTxMemPoolEntry>,
370 boost::multi_index::ordered_non_unique<
371 boost::multi_index::tag<ancestor_score>,
372 boost::multi_index::identity<CTxMemPoolEntry>,
408 using txiter = indexed_transaction_set::nth_index<0>::type::const_iterator;
417 typedef std::map<txiter, setEntries, CompareIteratorByHash>
cacheMap;
583 std::string_view calling_fn_name,
672 return (mapTx.count(gtxid.
GetHash()) != 0);
682 std::vector<TxMempoolInfo>
infoAll()
const;
702 return m_unbroadcast_txids;
709 return m_unbroadcast_txids.count(txid) != 0;
714 return m_sequence_number++;
718 return m_sequence_number;
783 return m_epoch.visited(
it->m_epoch_marker);
812 std::unordered_map<COutPoint, Coin, SaltedOutpointHasher>
m_temp_added;
844 typedef boost::multi_index_container<
846 boost::multi_index::indexed_by<
848 boost::multi_index::hashed_unique<
849 boost::multi_index::tag<txid_index>,
854 boost::multi_index::sequenced<
855 boost::multi_index::tag<insertion_order>
892 for (
auto const &tx : vtx) {
893 auto it =
queuedTx.find(tx->GetHash());
902 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...
An in-memory indexed chain of blocks.
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.
std::unordered_map< COutPoint, Coin, SaltedOutpointHasher > m_temp_added
Coins made available by transactions being validated.
CCoinsViewMemPool(CCoinsView *baseIn, const CTxMemPool &mempoolIn)
void PackageAddTransaction(const CTransactionRef &tx)
Add the coins created by this transaction.
const CTxMemPool & mempool
Fee rate in satoshis per kilovirtualbyte: CAmount / kvB.
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
CTxMemPoolEntry stores data about the corresponding transaction, as well as data about all in-mempool...
const CTransaction & GetTx() const
std::chrono::seconds GetTime() const
CAmount GetModFeesWithDescendants() const
uint64_t GetSizeWithDescendants() const
CAmount GetModifiedFee() const
const CAmount & GetFee() 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 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.
setEntries AssumeCalculateMemPoolAncestors(std::string_view calling_fn_name, const CTxMemPoolEntry &entry, const Limits &limits, bool fSearchForParents=true) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Same as CalculateMemPoolAncestors, but always returns a (non-optional) setEntries.
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...
const bool m_require_standard
void AddUnbroadcastTx(const uint256 &txid)
Adds a transaction to the unbroadcast set.
uint64_t cachedInnerUsage GUARDED_BY(cs)
sum of all mempool tx's fees (NOT modified fee)
void UpdateEntryForAncestors(txiter it, const setEntries &setAncestors) EXCLUSIVE_LOCKS_REQUIRED(cs)
Set ancestor state for an entry.
bool GetLoadTried() const
bool visited(const txiter it) const EXCLUSIVE_LOCKS_REQUIRED(cs
visited marks a CTxMemPoolEntry as having been traversed during the lifetime of the most recently cre...
bool visited(std::optional< txiter > it) const EXCLUSIVE_LOCKS_REQUIRED(cs
CFeeRate GetMinFee() const
The minimum fee to get into the mempool, which may itself not be enough for larger-sized transactions...
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)
util::Result< setEntries > CalculateMemPoolAncestors(const CTxMemPoolEntry &entry, const Limits &limits, bool fSearchForParents=true) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Try to calculate all in-mempool ancestors of entry.
void removeRecursive(const CTransaction &tx, MemPoolRemovalReason reason) EXCLUSIVE_LOCKS_REQUIRED(cs)
void check(const CCoinsViewCache &active_coins_tip, int64_t spendheight) const EXCLUSIVE_LOCKS_REQUIRED(void addUnchecked(const CTxMemPoolEntry &entry, bool validFeeEstimate=true) EXCLUSIVE_LOCKS_REQUIRED(cs
If sanity-checking is turned on, check makes sure the pool is consistent (does not contain two transa...
bool blockSinceLastRollingFeeBump GUARDED_BY(cs)
const int m_check_ratio
Value n means that 1 times in n we check.
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.
const std::chrono::seconds m_expiry
const std::optional< unsigned > m_max_datacarrier_bytes
void UpdateTransactionsFromBlock(const std::vector< uint256 > &vHashesToUpdate) EXCLUSIVE_LOCKS_REQUIRED(cs
UpdateTransactionsFromBlock is called when adding transactions from a disconnected block back to the ...
void AddTransactionsUpdated(unsigned int n)
void UpdateChildrenForRemoval(txiter entry) EXCLUSIVE_LOCKS_REQUIRED(cs)
Sever link between specified transaction and direct children.
std::optional< txiter > GetIter(const uint256 &txid) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Returns an iterator to the given hash, if found.
const int64_t m_max_size_bytes
void cs_main LOCKS_EXCLUDED(m_epoch)
util::Result< setEntries > CalculateAncestorsAndCheckLimits(size_t entry_size, size_t entry_count, CTxMemPoolEntry::Parents &staged_ancestors, const Limits &limits) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Helper function to calculate all in-mempool ancestors of staged_ancestors and apply ancestor and desc...
CTransactionRef get(const uint256 &hash) const
size_t DynamicMemoryUsage() const
Epoch m_epoch GUARDED_BY(cs)
minimum fee to get into the pool, decreases exponentially
std::vector< TxMempoolInfo > infoAll() const
void GetTransactionAncestry(const uint256 &txid, size_t &ancestors, size_t &descendants, size_t *ancestorsize=nullptr, CAmount *ancestorfees=nullptr) const
Calculate the ancestor and descendant count for the given transaction.
indexed_transaction_set mapTx GUARDED_BY(cs)
bool IsUnbroadcastTx(const uint256 &txid) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Returns whether a txid is in the unbroadcast set.
void UpdateParent(txiter entry, txiter parent, bool add) EXCLUSIVE_LOCKS_REQUIRED(cs)
bool CheckPackageLimits(const Package &package, const Limits &limits, std::string &errString) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Calculate all in-mempool ancestors of a set of transactions not already in the mempool and check ance...
void removeUnchecked(txiter entry, MemPoolRemovalReason reason) EXCLUSIVE_LOCKS_REQUIRED(cs)
Before calling removeUnchecked for a given transaction, UpdateForRemoveFromMempool must be called on ...
uint64_t totalTxSize GUARDED_BY(cs)
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.
CBlockPolicyEstimator *const minerPolicyEstimator
void removeForReorg(CChain &chain, std::function< bool(txiter)> filter_final_and_mature) EXCLUSIVE_LOCKS_REQUIRED(cs
After reorg, filter the entries that would no longer be valid in the next block, and update the entri...
TxMempoolInfo info(const GenTxid >xid) const
void ApplyDelta(const uint256 &hash, CAmount &nFeeDelta) const EXCLUSIVE_LOCKS_REQUIRED(cs)
int64_t lastRollingFeeUpdate GUARDED_BY(cs)
sum of dynamic memory usage of all the map elements (NOT the maps themselves)
const bool m_permit_bare_multisig
void UpdateForDescendants(txiter updateIt, cacheMap &cachedDescendants, const std::set< uint256 > &setExclude, std::set< uint256 > &descendants_to_remove) EXCLUSIVE_LOCKS_REQUIRED(cs)
UpdateForDescendants is used by UpdateTransactionsFromBlock to update the descendants for a single tr...
bool m_load_tried GUARDED_BY(cs)
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
const CFeeRate m_min_relay_feerate
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.
void UpdateChild(txiter entry, txiter child, bool add) EXCLUSIVE_LOCKS_REQUIRED(cs)
double rollingMinimumFeeRate GUARDED_BY(cs)
bool exists(const GenTxid >xid) const
std::map< txiter, setEntries, CompareIteratorByHash > cacheMap
const CFeeRate m_incremental_relay_feerate
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
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
void check(const CCoinsViewCache &active_coins_tip, int64_t spendheight) const EXCLUSIVE_LOCKS_REQUIRED(void cs_main
uint64_t m_sequence_number GUARDED_BY(cs)
void SetLoadTried(bool load_tried)
Set whether or not we've made an attempt to load the mempool (regardless of whether the attempt was s...
const CFeeRate m_dust_relay_feerate
void UpdateForRemoveFromMempool(const setEntries &entriesToRemove, bool updateDescendants) EXCLUSIVE_LOCKS_REQUIRED(cs)
For each transaction being removed, update ancestors and any direct children.
CAmount GetTotalFee() const EXCLUSIVE_LOCKS_REQUIRED(cs)
uint64_t CalculateDescendantMaximum(txiter entry) const EXCLUSIVE_LOCKS_REQUIRED(cs)
uint64_t GetTotalTxSize() const EXCLUSIVE_LOCKS_REQUIRED(cs)
bool isSpent(const COutPoint &outpoint) const
std::vector< std::pair< uint256, txiter > > vTxHashes GUARDED_BY(cs)
All tx witness hashes/entries in mapTx, in random order.
unsigned int GetTransactionsUpdated() const
CAmount m_total_fee GUARDED_BY(cs)
sum of all mempool tx's virtual sizes. Differs from serialized tx size since witness data is discount...
Chainstate stores and provides an API to update our local knowledge of the current best chain.
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
Epoch: RAII-style guard for using epoch-based graph traversal algorithms.
A generic txid reference (txid or wtxid).
const uint256 & GetHash() const
static GenTxid Txid(const uint256 &hash)
static size_t RecursiveDynamicUsage(const CScript &script)
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
static size_t MallocUsage(size_t alloc)
Compute the total memory used by allocating alloc bytes.
std::vector< CTransactionRef > Package
A package is an ordered list of transactions.
std::shared_ptr< const CTransaction > CTransactionRef
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)
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.
Options struct containing limit options for a CTxMemPool.
Options struct containing options for constructing a CTxMemPool.
result_type operator()(const CTxMemPoolEntry &entry) const
result_type operator()(const CTxMemPoolEntry &entry) const
DisconnectedBlockTransactions.
#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.
std::string RemovalReasonToString(const MemPoolRemovalReason &r) noexcept
static const uint32_t MEMPOOL_HEIGHT
Fake height value used in Coin to signify they are only in the memory pool (since 0....
bool TestLockPointValidity(CChain &active_chain, const LockPoints &lp) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Test whether the LockPoints height and time are still valid on the current chain.