Bitcoin Core 22.99.0
P2P Digital Currency
txmempool.h
Go to the documentation of this file.
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_TXMEMPOOL_H
7#define BITCOIN_TXMEMPOOL_H
8
9#include <atomic>
10#include <map>
11#include <optional>
12#include <set>
13#include <string>
14#include <utility>
15#include <vector>
16
17#include <coins.h>
18#include <consensus/amount.h>
19#include <indirectmap.h>
20#include <policy/feerate.h>
21#include <policy/packages.h>
23#include <random.h>
24#include <sync.h>
25#include <util/epochguard.h>
26#include <util/hasher.h>
27
28#include <boost/multi_index_container.hpp>
29#include <boost/multi_index/hashed_index.hpp>
30#include <boost/multi_index/ordered_index.hpp>
31#include <boost/multi_index/sequenced_index.hpp>
32
33class CBlockIndex;
34class CChainState;
36
38static const uint32_t MEMPOOL_HEIGHT = 0x7FFFFFFF;
39
40struct LockPoints {
41 // Will be set to the blockchain height and median time past
42 // values that would be necessary to satisfy all relative locktime
43 // constraints (BIP68) of this tx given our view of block chain history
44 int height{0};
45 int64_t time{0};
46 // As long as the current chain descends from the highest height block
47 // containing one of the inputs used in the calculation, then the cached
48 // values are still valid even after a reorg.
50};
51
53 // SFINAE for T where T is either a pointer type (e.g., a txiter) or a reference_wrapper<T>
54 // (e.g. a wrapped CTxMemPoolEntry&)
55 template <typename T>
56 bool operator()(const std::reference_wrapper<T>& a, const std::reference_wrapper<T>& b) const
57 {
58 return a.get().GetTx().GetHash() < b.get().GetTx().GetHash();
59 }
60 template <typename T>
61 bool operator()(const T& a, const T& b) const
62 {
63 return a->GetTx().GetHash() < b->GetTx().GetHash();
64 }
65};
66
80{
81public:
82 typedef std::reference_wrapper<const CTxMemPoolEntry> CTxMemPoolEntryRef;
83 // two aliases, should the types ever diverge
84 typedef std::set<CTxMemPoolEntryRef, CompareIteratorByHash> Parents;
85 typedef std::set<CTxMemPoolEntryRef, CompareIteratorByHash> Children;
86
87private:
91 const CAmount nFee;
92 const size_t nTxWeight;
93 const size_t nUsageSize;
94 const int64_t nTime;
95 const unsigned int entryHeight;
96 const bool spendsCoinbase;
97 const int64_t sigOpCost;
98 int64_t feeDelta{0};
100
101 // Information about descendants of this transaction that are in the
102 // mempool; if we remove this transaction we must remove all of these
103 // descendants as well.
107
108 // Analogous statistics for ancestor transactions
113
114public:
116 int64_t time, unsigned int entry_height,
117 bool spends_coinbase,
118 int64_t sigops_cost, LockPoints lp);
119
120 const CTransaction& GetTx() const { return *this->tx; }
121 CTransactionRef GetSharedTx() const { return this->tx; }
122 const CAmount& GetFee() const { return nFee; }
123 size_t GetTxSize() const;
124 size_t GetTxWeight() const { return nTxWeight; }
125 std::chrono::seconds GetTime() const { return std::chrono::seconds{nTime}; }
126 unsigned int GetHeight() const { return entryHeight; }
127 int64_t GetSigOpCost() const { return sigOpCost; }
128 int64_t GetModifiedFee() const { return nFee + feeDelta; }
129 size_t DynamicMemoryUsage() const { return nUsageSize; }
130 const LockPoints& GetLockPoints() const { return lockPoints; }
131
132 // Adjusts the descendant state.
133 void UpdateDescendantState(int64_t modifySize, CAmount modifyFee, int64_t modifyCount);
134 // Adjusts the ancestor state
135 void UpdateAncestorState(int64_t modifySize, CAmount modifyFee, int64_t modifyCount, int64_t modifySigOps);
136 // Updates the fee delta used for mining priority score, and the
137 // modified fees with descendants.
138 void UpdateFeeDelta(int64_t feeDelta);
139 // Update the LockPoints after a reorg
140 void UpdateLockPoints(const LockPoints& lp);
141
143 uint64_t GetSizeWithDescendants() const { return nSizeWithDescendants; }
145
146 bool GetSpendsCoinbase() const { return spendsCoinbase; }
147
148 uint64_t GetCountWithAncestors() const { return nCountWithAncestors; }
149 uint64_t GetSizeWithAncestors() const { return nSizeWithAncestors; }
152
153 const Parents& GetMemPoolParentsConst() const { return m_parents; }
154 const Children& GetMemPoolChildrenConst() const { return m_children; }
157
158 mutable size_t vTxHashesIdx;
160};
161
162// extracts a transaction hash from CTxMemPoolEntry or CTransactionRef
164{
167 {
168 return entry.GetTx().GetHash();
169 }
170
172 {
173 return tx->GetHash();
174 }
175};
176
177// extracts a transaction witness-hash from CTxMemPoolEntry or CTransactionRef
179{
182 {
183 return entry.GetTx().GetWitnessHash();
184 }
185
187 {
188 return tx->GetWitnessHash();
189 }
190};
191
192
198{
199public:
200 bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) const
201 {
202 double a_mod_fee, a_size, b_mod_fee, b_size;
203
204 GetModFeeAndSize(a, a_mod_fee, a_size);
205 GetModFeeAndSize(b, b_mod_fee, b_size);
206
207 // Avoid division by rewriting (a/b > c/d) as (a*d > c*b).
208 double f1 = a_mod_fee * b_size;
209 double f2 = a_size * b_mod_fee;
210
211 if (f1 == f2) {
212 return a.GetTime() >= b.GetTime();
213 }
214 return f1 < f2;
215 }
216
217 // Return the fee/size we're using for sorting this entry.
218 void GetModFeeAndSize(const CTxMemPoolEntry &a, double &mod_fee, double &size) const
219 {
220 // Compare feerate with descendants to feerate of the transaction, and
221 // return the fee/size for the max.
222 double f1 = (double)a.GetModifiedFee() * a.GetSizeWithDescendants();
223 double f2 = (double)a.GetModFeesWithDescendants() * a.GetTxSize();
224
225 if (f2 > f1) {
226 mod_fee = a.GetModFeesWithDescendants();
227 size = a.GetSizeWithDescendants();
228 } else {
229 mod_fee = a.GetModifiedFee();
230 size = a.GetTxSize();
231 }
232 }
233};
234
243{
244public:
245 bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) const
246 {
247 double f1 = (double)a.GetFee() * b.GetTxSize();
248 double f2 = (double)b.GetFee() * a.GetTxSize();
249 if (f1 == f2) {
250 return b.GetTx().GetHash() < a.GetTx().GetHash();
251 }
252 return f1 > f2;
253 }
254};
255
257{
258public:
259 bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) const
260 {
261 return a.GetTime() < b.GetTime();
262 }
263};
264
270{
271public:
272 template<typename T>
273 bool operator()(const T& a, const T& b) const
274 {
275 double a_mod_fee, a_size, b_mod_fee, b_size;
276
277 GetModFeeAndSize(a, a_mod_fee, a_size);
278 GetModFeeAndSize(b, b_mod_fee, b_size);
279
280 // Avoid division by rewriting (a/b > c/d) as (a*d > c*b).
281 double f1 = a_mod_fee * b_size;
282 double f2 = a_size * b_mod_fee;
283
284 if (f1 == f2) {
285 return a.GetTx().GetHash() < b.GetTx().GetHash();
286 }
287 return f1 > f2;
288 }
289
290 // Return the fee/size we're using for sorting this entry.
291 template <typename T>
292 void GetModFeeAndSize(const T &a, double &mod_fee, double &size) const
293 {
294 // Compare feerate with ancestors to feerate of the transaction, and
295 // return the fee/size for the min.
296 double f1 = (double)a.GetModifiedFee() * a.GetSizeWithAncestors();
297 double f2 = (double)a.GetModFeesWithAncestors() * a.GetTxSize();
298
299 if (f1 > f2) {
300 mod_fee = a.GetModFeesWithAncestors();
301 size = a.GetSizeWithAncestors();
302 } else {
303 mod_fee = a.GetModifiedFee();
304 size = a.GetTxSize();
305 }
306 }
307};
308
309// Multi_index tag names
311struct entry_time {};
314
316
321{
324
326 std::chrono::seconds m_time;
327
330
332 size_t vsize;
333
335 int64_t nFeeDelta;
336};
337
342 EXPIRY,
343 SIZELIMIT,
344 REORG,
345 BLOCK,
346 CONFLICT,
347 REPLACED,
348};
349
424{
425protected:
426 const int m_check_ratio;
427 std::atomic<unsigned int> nTransactionsUpdated{0};
429
430 uint64_t totalTxSize GUARDED_BY(cs);
431 CAmount m_total_fee GUARDED_BY(cs);
432 uint64_t cachedInnerUsage GUARDED_BY(cs);
433
434 mutable int64_t lastRollingFeeUpdate GUARDED_BY(cs);
435 mutable bool blockSinceLastRollingFeeBump GUARDED_BY(cs);
436 mutable double rollingMinimumFeeRate GUARDED_BY(cs);
438
439 // In-memory counter for external mempool tracking purposes.
440 // This number is incremented once every time a transaction
441 // is added or removed from the mempool for any reason.
442 mutable uint64_t m_sequence_number GUARDED_BY(cs){1};
443
445
446 bool m_is_loaded GUARDED_BY(cs){false};
447
448public:
449
450 static const int ROLLING_FEE_HALFLIFE = 60 * 60 * 12; // public only for testing
451
452 typedef boost::multi_index_container<
454 boost::multi_index::indexed_by<
455 // sorted by txid
456 boost::multi_index::hashed_unique<mempoolentry_txid, SaltedTxidHasher>,
457 // sorted by wtxid
458 boost::multi_index::hashed_unique<
459 boost::multi_index::tag<index_by_wtxid>,
462 >,
463 // sorted by fee rate
464 boost::multi_index::ordered_non_unique<
465 boost::multi_index::tag<descendant_score>,
466 boost::multi_index::identity<CTxMemPoolEntry>,
468 >,
469 // sorted by entry time
470 boost::multi_index::ordered_non_unique<
471 boost::multi_index::tag<entry_time>,
472 boost::multi_index::identity<CTxMemPoolEntry>,
474 >,
475 // sorted by fee rate with ancestors
476 boost::multi_index::ordered_non_unique<
477 boost::multi_index::tag<ancestor_score>,
478 boost::multi_index::identity<CTxMemPoolEntry>,
480 >
481 >
483
513
514 using txiter = indexed_transaction_set::nth_index<0>::type::const_iterator;
515 std::vector<std::pair<uint256, txiter>> vTxHashes GUARDED_BY(cs);
516
517 typedef std::set<txiter, CompareIteratorByHash> setEntries;
518
520private:
521 typedef std::map<txiter, setEntries, CompareIteratorByHash> cacheMap;
522
523
524 void UpdateParent(txiter entry, txiter parent, bool add) EXCLUSIVE_LOCKS_REQUIRED(cs);
525 void UpdateChild(txiter entry, txiter child, bool add) EXCLUSIVE_LOCKS_REQUIRED(cs);
526
527 std::vector<indexed_transaction_set::const_iterator> GetSortedDepthAndScore() const EXCLUSIVE_LOCKS_REQUIRED(cs);
528
532 std::set<uint256> m_unbroadcast_txids GUARDED_BY(cs);
533
534
543 bool CalculateAncestorsAndCheckLimits(size_t entry_size,
544 size_t entry_count,
545 setEntries& setAncestors,
546 CTxMemPoolEntry::Parents &staged_ancestors,
547 uint64_t limitAncestorCount,
548 uint64_t limitAncestorSize,
549 uint64_t limitDescendantCount,
550 uint64_t limitDescendantSize,
551 std::string &errString) const EXCLUSIVE_LOCKS_REQUIRED(cs);
552
553public:
555 std::map<uint256, CAmount> mapDeltas GUARDED_BY(cs);
556
565 explicit CTxMemPool(CBlockPolicyEstimator* estimator = nullptr, int check_ratio = 0);
566
573 void check(const CCoinsViewCache& active_coins_tip, int64_t spendheight) const EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
574
575 // addUnchecked must updated state for all ancestors of a given transaction,
576 // to track size/count of descendant transactions. First version of
577 // addUnchecked can be used to have it call CalculateMemPoolAncestors(), and
578 // then invoke the second version.
579 // Note that addUnchecked is ONLY called from ATMP outside of tests
580 // and any other callers may break wallet's in-mempool tracking (due to
581 // lack of CValidationInterface::TransactionAddedToMempool callbacks).
582 void addUnchecked(const CTxMemPoolEntry& entry, bool validFeeEstimate = true) EXCLUSIVE_LOCKS_REQUIRED(cs, cs_main);
583 void addUnchecked(const CTxMemPoolEntry& entry, setEntries& setAncestors, bool validFeeEstimate = true) EXCLUSIVE_LOCKS_REQUIRED(cs, cs_main);
584
586 void removeForReorg(CChainState& active_chainstate, int flags) EXCLUSIVE_LOCKS_REQUIRED(cs, cs_main);
588 void removeForBlock(const std::vector<CTransactionRef>& vtx, unsigned int nBlockHeight) EXCLUSIVE_LOCKS_REQUIRED(cs);
589
590 void clear();
591 void _clear() EXCLUSIVE_LOCKS_REQUIRED(cs); //lock free
592 bool CompareDepthAndScore(const uint256& hasha, const uint256& hashb, bool wtxid=false);
593 void queryHashes(std::vector<uint256>& vtxid) const;
594 bool isSpent(const COutPoint& outpoint) const;
595 unsigned int GetTransactionsUpdated() const;
596 void AddTransactionsUpdated(unsigned int n);
602
604 void PrioritiseTransaction(const uint256& hash, const CAmount& nFeeDelta);
605 void ApplyDelta(const uint256& hash, CAmount &nFeeDelta) const EXCLUSIVE_LOCKS_REQUIRED(cs);
607
609 const CTransaction* GetConflictTx(const COutPoint& prevout) const EXCLUSIVE_LOCKS_REQUIRED(cs);
610
612 std::optional<txiter> GetIter(const uint256& txid) const EXCLUSIVE_LOCKS_REQUIRED(cs);
613
615 setEntries GetIterSet(const std::set<uint256>& hashes) const EXCLUSIVE_LOCKS_REQUIRED(cs);
616
624 void RemoveStaged(setEntries& stage, bool updateDescendants, MemPoolRemovalReason reason) EXCLUSIVE_LOCKS_REQUIRED(cs);
625
636
647 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);
648
664 bool CheckPackageLimits(const Package& package,
665 uint64_t limitAncestorCount,
666 uint64_t limitAncestorSize,
667 uint64_t limitDescendantCount,
668 uint64_t limitDescendantSize,
669 std::string &errString) const EXCLUSIVE_LOCKS_REQUIRED(cs);
670
675
682 CFeeRate GetMinFee(size_t sizelimit) const;
683
688 void TrimToSize(size_t sizelimit, std::vector<COutPoint>* pvNoSpendsRemaining = nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs);
689
691 int Expire(std::chrono::seconds time) EXCLUSIVE_LOCKS_REQUIRED(cs);
692
699 void GetTransactionAncestry(const uint256& txid, size_t& ancestors, size_t& descendants, size_t* ancestorsize = nullptr, CAmount* ancestorfees = nullptr) const;
700
702 bool IsLoaded() const;
703
705 void SetIsLoaded(bool loaded);
706
707 unsigned long size() const
708 {
709 LOCK(cs);
710 return mapTx.size();
711 }
712
714 {
716 return totalTxSize;
717 }
718
720 {
722 return m_total_fee;
723 }
724
725 bool exists(const GenTxid& gtxid) const
726 {
727 LOCK(cs);
728 if (gtxid.IsWtxid()) {
729 return (mapTx.get<index_by_wtxid>().count(gtxid.GetHash()) != 0);
730 }
731 return (mapTx.count(gtxid.GetHash()) != 0);
732 }
733
734 CTransactionRef get(const uint256& hash) const;
736 {
738 return mapTx.project<0>(mapTx.get<index_by_wtxid>().find(wtxid));
739 }
740 TxMempoolInfo info(const GenTxid& gtxid) const;
741 std::vector<TxMempoolInfo> infoAll() const;
742
743 size_t DynamicMemoryUsage() const;
744
746 void AddUnbroadcastTx(const uint256& txid)
747 {
748 LOCK(cs);
749 // Sanity check the transaction is in the mempool & insert into
750 // unbroadcast set.
751 if (exists(GenTxid::Txid(txid))) m_unbroadcast_txids.insert(txid);
752 };
753
755 void RemoveUnbroadcastTx(const uint256& txid, const bool unchecked = false);
756
758 std::set<uint256> GetUnbroadcastTxs() const
759 {
760 LOCK(cs);
761 return m_unbroadcast_txids;
762 }
763
766 {
768 return m_unbroadcast_txids.count(txid) != 0;
769 }
770
773 return m_sequence_number++;
774 }
775
777 return m_sequence_number;
778 }
779
780private:
794 void UpdateForDescendants(txiter updateIt,
795 cacheMap &cachedDescendants,
796 const std::set<uint256> &setExclude) EXCLUSIVE_LOCKS_REQUIRED(cs);
798 void UpdateAncestorsOf(bool add, txiter hash, setEntries &setAncestors) EXCLUSIVE_LOCKS_REQUIRED(cs);
804 void UpdateForRemoveFromMempool(const setEntries &entriesToRemove, bool updateDescendants) EXCLUSIVE_LOCKS_REQUIRED(cs);
807
817public:
827 {
828 return m_epoch.visited(it->m_epoch_marker);
829 }
830
831 bool visited(std::optional<txiter> it) const EXCLUSIVE_LOCKS_REQUIRED(cs, m_epoch)
832 {
833 assert(m_epoch.guarded()); // verify guard even when it==nullopt
834 return !it || visited(*it);
835 }
836};
837
852{
857 std::unordered_map<COutPoint, Coin, SaltedOutpointHasher> m_temp_added;
858protected:
860
861public:
862 CCoinsViewMemPool(CCoinsView* baseIn, const CTxMemPool& mempoolIn);
863 bool GetCoin(const COutPoint &outpoint, Coin &coin) const override;
867};
868
884// multi_index tag names
885struct txid_index {};
887
889 typedef boost::multi_index_container<
891 boost::multi_index::indexed_by<
892 // sorted by txid
893 boost::multi_index::hashed_unique<
894 boost::multi_index::tag<txid_index>,
897 >,
898 // sorted by order in the blockchain
899 boost::multi_index::sequenced<
900 boost::multi_index::tag<insertion_order>
901 >
902 >
904
905 // It's almost certainly a logic bug if we don't clear out queuedTx before
906 // destruction, as we add to it while disconnecting blocks, and then we
907 // need to re-process remaining transactions to ensure mempool consistency.
908 // For now, assert() that we've emptied out this object on destruction.
909 // This assert() can always be removed if the reorg-processing code were
910 // to be refactored such that this assumption is no longer true (for
911 // instance if there was some other way we cleaned up the mempool after a
912 // reorg, besides draining this object).
914
916 uint64_t cachedInnerUsage = 0;
917
918 // Estimate the overhead of queuedTx to be 6 pointers + an allocation, as
919 // no exact formula for boost::multi_index_contained is implemented.
920 size_t DynamicMemoryUsage() const {
921 return memusage::MallocUsage(sizeof(CTransactionRef) + 6 * sizeof(void*)) * queuedTx.size() + cachedInnerUsage;
922 }
923
925 {
926 queuedTx.insert(tx);
928 }
929
930 // Remove entries based on txid_index, and update memory usage.
931 void removeForBlock(const std::vector<CTransactionRef>& vtx)
932 {
933 // Short-circuit in the common case of a block being added to the tip
934 if (queuedTx.empty()) {
935 return;
936 }
937 for (auto const &tx : vtx) {
938 auto it = queuedTx.find(tx->GetHash());
939 if (it != queuedTx.end()) {
941 queuedTx.erase(it);
942 }
943 }
944 }
945
946 // Remove an entry by insertion_order index, and update memory usage.
947 void removeEntry(indexed_disconnected_transactions::index<insertion_order>::type::iterator entry)
948 {
950 queuedTx.get<insertion_order>().erase(entry);
951 }
952
953 void clear()
954 {
956 queuedTx.clear();
957 }
958};
959
960#endif // BITCOIN_TXMEMPOOL_H
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
int flags
Definition: bitcoin-tx.cpp:525
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:146
The BlockPolicyEstimator is used for estimating the feerate needed for a transaction to be included i...
Definition: fees.h:132
CChainState stores and provides an API to update our local knowledge of the current best chain.
Definition: validation.h:544
CCoinsView backed by another CCoinsView.
Definition: coins.h:195
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:214
Abstract view on the open txout dataset.
Definition: coins.h:158
CCoinsView that brings transactions from a mempool into view.
Definition: txmempool.h:852
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: txmempool.cpp:1008
std::unordered_map< COutPoint, Coin, SaltedOutpointHasher > m_temp_added
Coins made available by transactions being validated.
Definition: txmempool.h:857
CCoinsViewMemPool(CCoinsView *baseIn, const CTxMemPool &mempoolIn)
Definition: txmempool.cpp:1006
void PackageAddTransaction(const CTransactionRef &tx)
Add the coins created by this transaction.
Definition: txmempool.cpp:1031
const CTxMemPool & mempool
Definition: txmempool.h:859
Fee rate in satoshis per kilobyte: CAmount / kB.
Definition: feerate.h:30
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:27
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:260
const uint256 & GetWitnessHash() const
Definition: transaction.h:303
const uint256 & GetHash() const
Definition: transaction.h:302
CTxMemPoolEntry stores data about the corresponding transaction, as well as data about all in-mempool...
Definition: txmempool.h:80
CTxMemPoolEntry(const CTransactionRef &tx, CAmount fee, int64_t time, unsigned int entry_height, bool spends_coinbase, int64_t sigops_cost, LockPoints lp)
Definition: txmempool.cpp:77
const int64_t sigOpCost
Total sigop cost.
Definition: txmempool.h:97
const CTransactionRef tx
Definition: txmempool.h:88
const LockPoints & GetLockPoints() const
Definition: txmempool.h:130
Epoch::Marker m_epoch_marker
epoch when last touched, useful for graph algorithms
Definition: txmempool.h:159
int64_t GetSigOpCostWithAncestors() const
Definition: txmempool.h:151
void UpdateFeeDelta(int64_t feeDelta)
Definition: txmempool.cpp:95
const bool spendsCoinbase
keep track of transactions that spend a coinbase
Definition: txmempool.h:96
const size_t nTxWeight
... and avoid recomputing tx weight (also used for GetTxSize())
Definition: txmempool.h:92
int64_t nSigOpCostWithAncestors
Definition: txmempool.h:112
int64_t feeDelta
Used for determining the priority of the transaction for mining in a block.
Definition: txmempool.h:98
unsigned int GetHeight() const
Definition: txmempool.h:126
std::chrono::seconds GetTime() const
Definition: txmempool.h:125
const CTransaction & GetTx() const
Definition: txmempool.h:120
Children & GetMemPoolChildren() const
Definition: txmempool.h:156
void UpdateDescendantState(int64_t modifySize, CAmount modifyFee, int64_t modifyCount)
Definition: txmempool.cpp:427
std::reference_wrapper< const CTxMemPoolEntry > CTxMemPoolEntryRef
Definition: txmempool.h:82
bool GetSpendsCoinbase() const
Definition: txmempool.h:146
const int64_t nTime
Local time when entering the mempool.
Definition: txmempool.h:94
uint64_t GetCountWithDescendants() const
Definition: txmempool.h:142
const size_t nUsageSize
... and total memory usage
Definition: txmempool.h:93
void UpdateLockPoints(const LockPoints &lp)
Definition: txmempool.cpp:102
CAmount nModFeesWithAncestors
Definition: txmempool.h:111
const Children & GetMemPoolChildrenConst() const
Definition: txmempool.h:154
CAmount GetModFeesWithDescendants() const
Definition: txmempool.h:144
Parents m_parents
Definition: txmempool.h:89
int64_t GetSigOpCost() const
Definition: txmempool.h:127
uint64_t nCountWithDescendants
number of descendant transactions
Definition: txmempool.h:104
size_t GetTxSize() const
Definition: txmempool.cpp:107
void UpdateAncestorState(int64_t modifySize, CAmount modifyFee, int64_t modifyCount, int64_t modifySigOps)
Definition: txmempool.cpp:436
uint64_t GetSizeWithAncestors() const
Definition: txmempool.h:149
CTransactionRef GetSharedTx() const
Definition: txmempool.h:121
const Parents & GetMemPoolParentsConst() const
Definition: txmempool.h:153
uint64_t nSizeWithDescendants
... and size
Definition: txmempool.h:105
size_t DynamicMemoryUsage() const
Definition: txmempool.h:129
std::set< CTxMemPoolEntryRef, CompareIteratorByHash > Children
Definition: txmempool.h:85
CAmount nModFeesWithDescendants
... and total fees (all including us)
Definition: txmempool.h:106
uint64_t nCountWithAncestors
Definition: txmempool.h:109
const CAmount nFee
Cached to avoid expensive parent-transaction lookups.
Definition: txmempool.h:91
Parents & GetMemPoolParents() const
Definition: txmempool.h:155
const CAmount & GetFee() const
Definition: txmempool.h:122
CAmount GetModFeesWithAncestors() const
Definition: txmempool.h:150
uint64_t GetSizeWithDescendants() const
Definition: txmempool.h:143
uint64_t GetCountWithAncestors() const
Definition: txmempool.h:148
LockPoints lockPoints
Track the height and time at which tx was final.
Definition: txmempool.h:99
uint64_t nSizeWithAncestors
Definition: txmempool.h:110
int64_t GetModifiedFee() const
Definition: txmempool.h:128
Children m_children
Definition: txmempool.h:90
const unsigned int entryHeight
Chain height when entering the mempool.
Definition: txmempool.h:95
size_t vTxHashesIdx
Index in mempool's vTxHashes.
Definition: txmempool.h:158
std::set< CTxMemPoolEntryRef, CompareIteratorByHash > Parents
Definition: txmempool.h:84
size_t GetTxWeight() const
Definition: txmempool.h:124
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:424
void removeConflicts(const CTransaction &tx) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:659
std::atomic< unsigned int > nTransactionsUpdated
Used by getblocktemplate to trigger CreateNewBlock() invocation.
Definition: txmempool.h:427
void RemoveUnbroadcastTx(const uint256 &txid, const bool unchecked=false)
Removes a transaction from the unbroadcast set.
Definition: txmempool.cpp:1044
void PrioritiseTransaction(const uint256 &hash, const CAmount &nFeeDelta)
Affect CreateNewBlock prioritisation of transactions.
Definition: txmempool.cpp:929
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...
Definition: txmempool.cpp:998
std::set< uint256 > GetUnbroadcastTxs() const
Returns transactions in unbroadcast set.
Definition: txmempool.h:758
void AddUnbroadcastTx(const uint256 &txid)
Adds a transaction to the unbroadcast set.
Definition: txmempool.h:746
uint64_t cachedInnerUsage GUARDED_BY(cs)
sum of dynamic memory usage of all the map elements (NOT the maps themselves)
void UpdateEntryForAncestors(txiter it, const setEntries &setAncestors) EXCLUSIVE_LOCKS_REQUIRED(cs)
Set ancestor state for an entry.
Definition: txmempool.cpp:345
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
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it.
Definition: txmempool.h:511
void ClearPrioritisation(const uint256 &hash) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:969
void trackPackageRemoved(const CFeeRate &rate) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:1133
CFeeRate GetMinFee(size_t sizelimit) const
The minimum fee to get into the mempool, which may itself not be enough for larger-sized transactions...
Definition: txmempool.cpp:1109
void removeRecursive(const CTransaction &tx, MemPoolRemovalReason reason) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:589
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...
Definition: txmempool.h:582
bool blockSinceLastRollingFeeBump GUARDED_BY(cs)
const int m_check_ratio
Value n means that 1 times in n we check.
Definition: txmempool.h:426
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.
Definition: txmempool.cpp:1141
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 ...
Definition: txmempool.cpp:162
return !it visited * it
Definition: txmempool.h:834
void AddTransactionsUpdated(unsigned int n)
Definition: txmempool.cpp:464
void UpdateChildrenForRemoval(txiter entry) EXCLUSIVE_LOCKS_REQUIRED(cs)
Sever link between specified transaction and direct children.
Definition: txmempool.cpp:359
void removeForReorg(CChainState &active_chainstate, int flags) EXCLUSIVE_LOCKS_REQUIRED(cs
Definition: txmempool.cpp:619
std::optional< txiter > GetIter(const uint256 &txid) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Returns an iterator to the given hash, if found.
Definition: txmempool.cpp:981
void cs_main LOCKS_EXCLUDED(m_epoch)
CTransactionRef get(const uint256 &hash) const
Definition: txmempool.cpp:911
size_t DynamicMemoryUsage() const
Definition: txmempool.cpp:1038
Epoch m_epoch GUARDED_BY(cs)
std::vector< TxMempoolInfo > infoAll() const
Definition: txmempool.cpp:897
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.
Definition: txmempool.cpp:1206
indexed_transaction_set mapTx GUARDED_BY(cs)
void SetIsLoaded(bool loaded)
Sets the current loaded state.
Definition: txmempool.cpp:1224
bool IsUnbroadcastTx(const uint256 &txid) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Returns whether a txid is in the unbroadcast set.
Definition: txmempool.h:765
void UpdateParent(txiter entry, txiter parent, bool add) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:1098
std::vector< std::pair< uint256, txiter > > vTxHashes GUARDED_BY(cs)
All tx witness hashes/entries in mapTx, in random order.
void removeUnchecked(txiter entry, MemPoolRemovalReason reason) EXCLUSIVE_LOCKS_REQUIRED(cs)
Before calling removeUnchecked for a given transaction, UpdateForRemoveFromMempool must be called on ...
Definition: txmempool.cpp:521
uint64_t totalTxSize GUARDED_BY(cs)
sum of all mempool tx's virtual sizes. Differs from serialized tx size since witness data is discount...
int Expire(std::chrono::seconds time) EXCLUSIVE_LOCKS_REQUIRED(cs)
Expire all transaction (and their dependencies) in the mempool older than time.
Definition: txmempool.cpp:1061
void clear()
Definition: txmempool.cpp:721
txiter get_iter_from_wtxid(const uint256 &wtxid) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.h:735
void UpdateAncestorsOf(bool add, txiter hash, setEntries &setAncestors) EXCLUSIVE_LOCKS_REQUIRED(cs)
Update ancestors of hash to add/remove it as a descendant transaction.
Definition: txmempool.cpp:330
CBlockPolicyEstimator *const minerPolicyEstimator
Definition: txmempool.h:428
bool CheckPackageLimits(const Package &package, uint64_t limitAncestorCount, uint64_t limitAncestorSize, uint64_t limitDescendantCount, uint64_t limitDescendantSize, 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...
Definition: txmempool.cpp:256
TxMempoolInfo info(const GenTxid &gtxid) const
Definition: txmempool.cpp:920
void ApplyDelta(const uint256 &hash, CAmount &nFeeDelta) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:959
int64_t lastRollingFeeUpdate GUARDED_BY(cs)
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.
Definition: txmempool.cpp:291
static const int ROLLING_FEE_HALFLIFE
Definition: txmempool.h:450
std::set< txiter, CompareIteratorByHash > setEntries
Definition: txmempool.h:517
std::vector< indexed_transaction_set::const_iterator > GetSortedDepthAndScore() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:866
void RemoveStaged(setEntries &stage, bool updateDescendants, MemPoolRemovalReason reason) EXCLUSIVE_LOCKS_REQUIRED(cs)
Remove a set of transactions from the mempool.
Definition: txmempool.cpp:1053
void removeForBlock(const std::vector< CTransactionRef > &vtx, unsigned int nBlockHeight) EXCLUSIVE_LOCKS_REQUIRED(cs)
Called when a block is connected.
Definition: txmempool.cpp:679
void queryHashes(std::vector< uint256 > &vtxid) const
Definition: txmempool.cpp:880
uint64_t GetSequence() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.h:776
indexed_transaction_set::nth_index< 0 >::type::const_iterator txiter
Definition: txmempool.h:514
uint64_t GetAndIncrementSequence() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Guards this internal counter for external reporting.
Definition: txmempool.h:772
void UpdateChild(txiter entry, txiter child, bool add) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:1087
bool IsLoaded() const
Definition: txmempool.cpp:1218
double rollingMinimumFeeRate GUARDED_BY(cs)
minimum fee to get into the pool, decreases exponentially
bool exists(const GenTxid &gtxid) const
Definition: txmempool.h:725
std::map< txiter, setEntries, CompareIteratorByHash > cacheMap
Definition: txmempool.h:521
bool m_epoch
Definition: txmempool.h:827
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...
Definition: txmempool.cpp:115
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.
Definition: txmempool.cpp:988
const CTransaction * GetConflictTx(const COutPoint &prevout) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Get the transaction in the pool that spends the same prevout.
Definition: txmempool.cpp:975
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
Definition: txmempool.h:482
bool CompareDepthAndScore(const uint256 &hasha, const uint256 &hashb, bool wtxid=false)
Definition: txmempool.cpp:835
void CalculateDescendants(txiter it, setEntries &setDescendants) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Populate setDescendants with all in-mempool descendants of hash.
Definition: txmempool.cpp:565
unsigned long size() const
Definition: txmempool.h:707
void check(const CCoinsViewCache &active_coins_tip, int64_t spendheight) const EXCLUSIVE_LOCKS_REQUIRED(void cs_main
Definition: txmempool.h:582
bool m_is_loaded GUARDED_BY(cs)
Definition: txmempool.h:446
uint64_t m_sequence_number GUARDED_BY(cs)
Definition: txmempool.h:442
void UpdateForRemoveFromMempool(const setEntries &entriesToRemove, bool updateDescendants) EXCLUSIVE_LOCKS_REQUIRED(cs)
For each transaction being removed, update ancestors and any direct children.
Definition: txmempool.cpp:367
bool CalculateAncestorsAndCheckLimits(size_t entry_size, size_t entry_count, setEntries &setAncestors, CTxMemPoolEntry::Parents &staged_ancestors, uint64_t limitAncestorCount, uint64_t limitAncestorSize, uint64_t limitDescendantCount, uint64_t limitDescendantSize, std::string &errString) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Helper function to calculate all in-mempool ancestors of staged_ancestors and apply ancestor and desc...
Definition: txmempool.cpp:207
CAmount GetTotalFee() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.h:719
uint64_t CalculateDescendantMaximum(txiter entry) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:1184
uint64_t GetTotalTxSize() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.h:713
bool isSpent(const COutPoint &outpoint) const
Definition: txmempool.cpp:453
unsigned int GetTransactionsUpdated() const
Definition: txmempool.cpp:459
CAmount m_total_fee GUARDED_BY(cs)
sum of all mempool tx's fees (NOT modified fee)
void _clear() EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:708
A UTXO entry.
Definition: coins.h:31
Definition: txmempool.h:270
bool operator()(const T &a, const T &b) const
Definition: txmempool.h:273
void GetModFeeAndSize(const T &a, double &mod_fee, double &size) const
Definition: txmempool.h:292
Sort an entry by max(score/size of entry's tx, score/size with all descendants).
Definition: txmempool.h:198
bool operator()(const CTxMemPoolEntry &a, const CTxMemPoolEntry &b) const
Definition: txmempool.h:200
void GetModFeeAndSize(const CTxMemPoolEntry &a, double &mod_fee, double &size) const
Definition: txmempool.h:218
Definition: txmempool.h:257
bool operator()(const CTxMemPoolEntry &a, const CTxMemPoolEntry &b) const
Definition: txmempool.h:259
Sort by feerate of entry (fee/size) in descending order This is only used for transaction relay,...
Definition: txmempool.h:243
bool operator()(const CTxMemPoolEntry &a, const CTxMemPoolEntry &b) const
Definition: txmempool.h:245
Epoch: RAII-style guard for using epoch-based graph traversal algorithms.
Definition: epochguard.h:34
A generic txid reference (txid or wtxid).
Definition: transaction.h:391
bool IsWtxid() const
Definition: transaction.h:399
const uint256 & GetHash() const
Definition: transaction.h:400
static GenTxid Txid(const uint256 &hash)
Definition: transaction.h:397
256-bit opaque blob.
Definition: uint256.h:124
static size_t RecursiveDynamicUsage(const CScript &script)
Definition: core_memusage.h:12
#define T(expected, seed, data)
LockPoints lp
static size_t MallocUsage(size_t alloc)
Compute the total memory used by allocating alloc bytes.
Definition: memusage.h:50
std::vector< CTransactionRef > Package
A package is an ordered list of transactions.
Definition: packages.h:32
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:386
bool operator()(const T &a, const T &b) const
Definition: txmempool.h:61
bool operator()(const std::reference_wrapper< T > &a, const std::reference_wrapper< T > &b) const
Definition: txmempool.h:56
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
Definition: txmempool.h:903
void removeEntry(indexed_disconnected_transactions::index< insertion_order >::type::iterator entry)
Definition: txmempool.h:947
indexed_disconnected_transactions queuedTx
Definition: txmempool.h:915
void removeForBlock(const std::vector< CTransactionRef > &vtx)
Definition: txmempool.h:931
size_t DynamicMemoryUsage() const
Definition: txmempool.h:920
void addTransaction(const CTransactionRef &tx)
Definition: txmempool.h:924
CBlockIndex * maxInputBlock
Definition: txmempool.h:49
int height
Definition: txmempool.h:44
int64_t time
Definition: txmempool.h:45
Information about a mempool transaction.
Definition: txmempool.h:321
int64_t nFeeDelta
The fee delta.
Definition: txmempool.h:335
CAmount fee
Fee of the transaction.
Definition: txmempool.h:329
CTransactionRef tx
The transaction itself.
Definition: txmempool.h:323
std::chrono::seconds m_time
Time the transaction entered the mempool.
Definition: txmempool.h:326
size_t vsize
Virtual size of the transaction.
Definition: txmempool.h:332
result_type operator()(const CTxMemPoolEntry &entry) const
Definition: txmempool.h:166
uint256 result_type
Definition: txmempool.h:165
uint256 result_type
Definition: txmempool.h:180
result_type operator()(const CTxMemPoolEntry &entry) const
Definition: txmempool.h:181
DisconnectedBlockTransactions.
Definition: txmempool.h:885
#define LOCK(cs)
Definition: sync.h:226
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
MemPoolRemovalReason
Reason why a transaction was removed from the mempool, this is passed to the notification signal.
Definition: txmempool.h:341
@ 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....
Definition: txmempool.h:38
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: validation.cpp:118
AssertLockHeld(pool.cs)
assert(!tx.IsCoinBase())