6#ifndef BITCOIN_TXMEMPOOL_H
7#define BITCOIN_TXMEMPOOL_H
28#include <boost/multi_index/hashed_index.hpp>
29#include <boost/multi_index/identity.hpp>
30#include <boost/multi_index/indexed_by.hpp>
31#include <boost/multi_index/ordered_index.hpp>
32#include <boost/multi_index/sequenced_index.hpp>
33#include <boost/multi_index/tag.hpp>
34#include <boost/multi_index_container.hpp>
93 return tx->GetWitnessHash();
219 boost::multi_index::hashed_unique<mempoolentry_txid, SaltedTxidHasher>,
221 boost::multi_index::hashed_unique<
222 boost::multi_index::tag<index_by_wtxid>,
227 boost::multi_index::ordered_non_unique<
228 boost::multi_index::tag<entry_time>,
229 boost::multi_index::identity<CTxMemPoolEntry>,
230 CompareTxMemPoolEntryByEntryTime
234 typedef boost::multi_index_container<
265 mutable std::unique_ptr<TxGraph::BlockBuilder> m_builder
GUARDED_BY(
cs);
268 using txiter = indexed_transaction_set::nth_index<0>::type::const_iterator;
284 typedef std::map<txiter, setEntries, CompareIteratorByHash>
cacheMap;
296 return TxMempoolInfo{
it->GetSharedTx(),
it->GetTime(),
it->GetFee(),
it->GetTxSize(),
it->GetModifiedFee() -
it->GetFee()};
399 return m_txgraph->GetMainChunkFeerate(tx);
405 std::vector<const CTxMemPoolEntry*>
ret;
406 ret.reserve(cluster.size());
407 for (
const auto& tx : cluster) {
415 std::vector<const TxGraph::Ref *> entries;
416 entries.reserve(iters_conflicting.size());
417 for (
auto it : iters_conflicting) {
418 entries.emplace_back(&*
it);
507 return (mapTx.count(txid) != 0);
520 template <Tx
idOrWtx
id T>
529 template <Tx
idOrWtx
id T>
534 return (i.has_value() && i.value()->GetSequence() < last_sequence) ?
GetInfo(*i) :
TxMempoolInfo{};
548 if (
exists(txid)) m_unbroadcast_txids.insert(txid);
560 return m_unbroadcast_txids;
567 return m_unbroadcast_txids.count(txid) != 0;
572 return m_sequence_number++;
576 return m_sequence_number;
609 return m_epoch.visited(
it->m_epoch_marker);
651 if (
m_pool->m_txgraph->HaveStaging()) {
652 m_pool->m_txgraph->AbortStaging();
654 m_pool->m_have_changeset =
false;
686 std::vector<CTransactionRef>
ret;
689 ret.emplace_back(entry->GetSharedTx());
722 Assume(!m_have_changeset);
723 m_have_changeset =
true;
724 return std::make_unique<ChangeSet>(
this);
749 if (!m_builder) {
return {}; }
751 auto res = m_builder->GetCurrentChunk();
752 if (!res) {
return {}; }
754 auto [chunk_entries, chunk_feerate] = *res;
758 return chunk_feerate;
784 std::unordered_map<COutPoint, Coin, SaltedOutpointHasher>
m_temp_added;
int64_t CAmount
Amount in satoshis (Can be negative)
#define Assume(val)
Assume is the identity function.
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.
std::optional< Coin > GetCoin(const COutPoint &outpoint) const override
GetCoin, returning whether it exists and is not spent.
void Reset()
Clear m_temp_added and m_non_base_coins.
const std::unordered_set< COutPoint, SaltedOutpointHasher > & GetNonBaseCoins() const
Get all coins in m_non_base_coins.
std::unordered_map< COutPoint, Coin, SaltedOutpointHasher > m_temp_added
Coins made available by transactions being validated.
CCoinsViewMemPool(CCoinsView *baseIn, const CTxMemPool &mempoolIn)
std::unordered_set< COutPoint, SaltedOutpointHasher > m_non_base_coins
Set of all coins that have been fetched from mempool or created using PackageAddTransaction (not base...
void PackageAddTransaction(const CTransactionRef &tx)
Add the coins created by this transaction.
const CTxMemPool & mempool
Fee rate in satoshis per virtualbyte: CAmount / vB the feerate is represented internally as FeeFrac.
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 Wtxid & GetWitnessHash() const LIFETIMEBOUND
const Txid & GetHash() const LIFETIMEBOUND
size_t GetTxCount() const
const CTransaction & GetAddedTxn(size_t index) const
CTxMemPool::setEntries m_to_remove
ChangeSet(CTxMemPool *pool)
void Apply() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
void StageRemoval(CTxMemPool::txiter it)
TxHandle StageAddition(const CTransactionRef &tx, const CAmount fee, int64_t time, unsigned int entry_height, uint64_t entry_sequence, bool spends_coinbase, int64_t sigops_cost, LockPoints lp)
util::Result< std::pair< std::vector< FeeFrac >, std::vector< FeeFrac > > > CalculateChunksForRBF()
Calculate the sorted chunks for the old and new mempool relating to the clusters that would be affect...
CTxMemPool::txiter TxHandle
CTxMemPool::indexed_transaction_set m_to_add
~ChangeSet() EXCLUSIVE_LOCKS_REQUIRED(m_pool -> cs)
ChangeSet(const ChangeSet &)=delete
const CTxMemPool::setEntries & GetRemovals() const
CTxMemPool::setEntries CalculateMemPoolAncestors(TxHandle tx)
bool CheckMemPoolPolicyLimits()
Check if any cluster limits are exceeded.
std::map< CTxMemPool::txiter, CTxMemPool::setEntries, CompareIteratorByHash > m_ancestors
std::vector< CTransactionRef > GetAddedTxns() const
bool m_dependencies_processed
ChangeSet & operator=(const ChangeSet &)=delete
void ProcessDependencies()
std::vector< CTxMemPool::txiter > m_entry_vec
CTxMemPoolEntry stores data about the corresponding transaction, as well as data about all in-mempool...
std::chrono::seconds GetTime() const
const CTransaction & GetTx() 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 Apply(CTxMemPool::ChangeSet *changeset) EXCLUSIVE_LOCKS_REQUIRED(cs)
void PrioritiseTransaction(const Txid &hash, const CAmount &nFeeDelta)
Affect CreateNewBlock prioritisation of transactions.
std::unique_ptr< ChangeSet > GetChangeSet() EXCLUSIVE_LOCKS_REQUIRED(cs)
bool CompareMiningScoreWithTopology(const Wtxid &hasha, const Wtxid &hashb) const
std::map< Txid, CAmount > mapDeltas GUARDED_BY(cs)
static TxMempoolInfo GetInfo(CTxMemPool::indexed_transaction_set::const_iterator it)
TxMempoolInfo info_for_relay(const T &id, uint64_t last_sequence) const
Returns info for a transaction if its entry_sequence < last_sequence.
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...
std::vector< const CTxMemPoolEntry * > GetCluster(Txid txid) const EXCLUSIVE_LOCKS_REQUIRED(cs)
setEntries GetIterSet(const std::set< Txid > &hashes) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Translate a set of hashes into a set of pool iterators to avoid repeated lookups.
void ClearPrioritisation(const Txid &hash) EXCLUSIVE_LOCKS_REQUIRED(cs)
uint64_t cachedInnerUsage GUARDED_BY(cs)
sum of all mempool tx's fees (NOT modified fee)
std::optional< txiter > GetIter(const Txid &txid) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Returns an iterator to the given hash, if found.
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...
void StopBlockBuilding() const EXCLUSIVE_LOCKS_REQUIRED(cs)
bool exists(const Wtxid &wtxid) const
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 trackPackageRemoved(const CFeeRate &rate) EXCLUSIVE_LOCKS_REQUIRED(cs)
std::vector< std::pair< Wtxid, txiter > > txns_randomized GUARDED_BY(cs)
All transactions in mapTx with their wtxids, in arbitrary order.
void check(const CCoinsViewCache &active_coins_tip, int64_t spendheight) const EXCLUSIVE_LOCKS_REQUIRED(void removeRecursive(const CTransaction &tx, MemPoolRemovalReason reason) 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)
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 GetTransactionAncestry(const Txid &txid, size_t &ancestors, size_t &cluster_count, size_t *ancestorsize=nullptr, CAmount *ancestorfees=nullptr) const
Calculate the ancestor and cluster count for the given transaction.
void UpdateTransactionsFromBlock(const std::vector< Txid > &vHashesToUpdate) EXCLUSIVE_LOCKS_REQUIRED(cs
UpdateTransactionsFromBlock is called when adding transactions from a disconnected block back to the ...
void AddTransactionsUpdated(unsigned int n)
bool HasDescendants(const Txid &txid) const
std::vector< indexed_transaction_set::const_iterator > GetSortedScoreWithTopology() const EXCLUSIVE_LOCKS_REQUIRED(cs)
void StartBlockBuilding() const EXCLUSIVE_LOCKS_REQUIRED(cs)
CTransactionRef get(const Txid &hash) const
bool m_have_changeset GUARDED_BY(cs)
void cs_main LOCKS_EXCLUDED(m_epoch)
size_t GetUniqueClusterCount(const setEntries &iters_conflicting) const EXCLUSIVE_LOCKS_REQUIRED(cs)
size_t DynamicMemoryUsage() const
Epoch m_epoch GUARDED_BY(cs)
minimum fee to get into the pool, decreases exponentially
std::vector< TxMempoolInfo > infoAll() const
indexed_transaction_set mapTx GUARDED_BY(cs)
TxMempoolInfo info(const T &id) const
CTxMemPool(Options opts, bilingual_str &error)
Create a new CTxMemPool.
void addNewTransaction(CTxMemPool::txiter it) EXCLUSIVE_LOCKS_REQUIRED(cs)
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)
boost::multi_index_container< CTxMemPoolEntry, CTxMemPoolEntry_Indices > indexed_transaction_set
void RemoveUnbroadcastTx(const Txid &txid, const bool unchecked=false)
Removes a transaction from the unbroadcast set.
int Expire(std::chrono::seconds time) EXCLUSIVE_LOCKS_REQUIRED(cs)
Expire all transaction (and their dependencies) in the mempool older than time.
int64_t GetDescendantCount(txiter it) const
void IncludeBuilderChunk() const EXCLUSIVE_LOCKS_REQUIRED(cs)
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...
std::vector< FeePerWeight > GetFeerateDiagram() const EXCLUSIVE_LOCKS_REQUIRED(cs)
std::tuple< size_t, size_t, CAmount > CalculateDescendantData(const CTxMemPoolEntry &entry) const EXCLUSIVE_LOCKS_REQUIRED(cs)
bool exists(const Txid &txid) const
int64_t lastRollingFeeUpdate GUARDED_BY(cs)
sum of dynamic memory usage of all the map elements (NOT the maps themselves)
std::vector< txiter > GetIterVec(const std::vector< Txid > &txids) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Translate a list of hashes into a list of mempool iterators to avoid repeated lookups.
bool m_load_tried GUARDED_BY(cs)
static const int ROLLING_FEE_HALFLIFE
std::set< txiter, CompareIteratorByHash > setEntries
std::vector< CTxMemPoolEntry::CTxMemPoolEntryRef > GetParents(const CTxMemPoolEntry &entry) const
FeePerWeight GetMainChunkFeerate(const CTxMemPoolEntry &tx) const EXCLUSIVE_LOCKS_REQUIRED(cs)
void ApplyDelta(const Txid &hash, CAmount &nFeeDelta) 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)
std::vector< delta_info > GetPrioritisedTransactions() const EXCLUSIVE_LOCKS_REQUIRED(!cs)
Return a vector of all entries in mapDeltas with their corresponding delta_info.
uint64_t GetSequence() const EXCLUSIVE_LOCKS_REQUIRED(cs)
int64_t GetAncestorCount(const CTxMemPoolEntry &e) const
std::vector< txiter > GatherClusters(const std::vector< Txid > &txids) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Collect the entire cluster of connected transactions for each transaction in txids.
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.
bool CheckPolicyLimits(const CTransactionRef &tx)
double rollingMinimumFeeRate GUARDED_BY(cs)
std::map< txiter, setEntries, CompareIteratorByHash > cacheMap
int64_t GetDescendantCount(const CTxMemPoolEntry &e) const
void SkipBuilderChunk() const EXCLUSIVE_LOCKS_REQUIRED(cs)
void AddUnbroadcastTx(const Txid &txid)
Adds a transaction to the unbroadcast set.
const CTransaction * GetConflictTx(const COutPoint &prevout) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Get the transaction in the pool that spends the same prevout.
bool IsUnbroadcastTx(const Txid &txid) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Returns whether a txid is in the unbroadcast set.
std::unique_ptr< TxGraph > m_txgraph GUARDED_BY(cs)
std::set< Txid > GetUnbroadcastTxs() const
Returns transactions in unbroadcast set.
void CalculateDescendants(txiter it, setEntries &setDescendants) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Populate setDescendants with all in-mempool descendants of given transaction.
std::tuple< size_t, size_t, CAmount > CalculateAncestorData(const CTxMemPoolEntry &entry) const EXCLUSIVE_LOCKS_REQUIRED(cs)
unsigned long size() const
std::vector< CTxMemPoolEntry::CTxMemPoolEntryRef > GetChildren(const CTxMemPoolEntry &entry) const
setEntries CalculateMemPoolAncestors(const CTxMemPoolEntry &entry) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Calculate all in-mempool ancestors of entry (not including the tx itself)
uint64_t m_sequence_number GUARDED_BY(cs)
void SetLoadTried(bool load_tried)
Set whether or not an initial attempt to load the persisted mempool was made (regardless of whether t...
std::unique_ptr< TxGraph::BlockBuilder > m_builder GUARDED_BY(cs)
std::vector< CTxMemPoolEntryRef > entryAll() const EXCLUSIVE_LOCKS_REQUIRED(cs)
CAmount GetTotalFee() const EXCLUSIVE_LOCKS_REQUIRED(cs)
indirectmap< COutPoint, txiter > mapNextTx GUARDED_BY(cs)
uint64_t GetTotalTxSize() const EXCLUSIVE_LOCKS_REQUIRED(cs)
bool isSpent(const COutPoint &outpoint) const
FeePerWeight GetBlockBuilderChunk(std::vector< CTxMemPoolEntry::CTxMemPoolEntryRef > &entries) const EXCLUSIVE_LOCKS_REQUIRED(cs)
const CTxMemPoolEntry * GetEntry(const Txid &txid) const LIFETIMEBOUND EXCLUSIVE_LOCKS_REQUIRED(cs)
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...
bool operator()(const CTxMemPoolEntry &a, const CTxMemPoolEntry &b) const
Epoch: RAII-style guard for using epoch-based graph traversal algorithms.
@ MAIN
Always refers to the main graph, whether staging is present or not.
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
MemPoolRemovalReason
Reason why a transaction was removed from the mempool, this is passed to the notification signal.
std::shared_ptr< const CTransaction > CTransactionRef
const CAmount delta
The fee delta added using PrioritiseTransaction().
const bool in_mempool
Whether this transaction is in the mempool.
std::optional< CAmount > modified_fee
The modified fee (base fee + delta) of this entry.
const Txid txid
The prioritised transaction's txid.
Tagged wrapper around FeeFrac to avoid unit confusion.
Information about a mempool transaction.
int64_t nFeeDelta
The fee delta.
int32_t vsize
Virtual size of the transaction.
CAmount fee
Fee of the transaction.
CTransactionRef tx
The transaction itself.
std::chrono::seconds m_time
Time the transaction entered the mempool.
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
#define EXCLUSIVE_LOCKS_REQUIRED(...)
static constexpr uint64_t ACCEPTABLE_ITERS
How many linearization iterations required for TxGraph clusters to have "acceptable" quality,...
static constexpr uint64_t POST_CHANGE_WORK
How much work we ask TxGraph to do after a mempool change occurs (either due to a changeset being app...
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.
int64_t GetTime()
DEPRECATED Use either ClockType::now() or Now<TimePointType>() if a cast is needed.