Bitcoin Core  29.1.0
P2P Digital Currency
txmempool.h
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2022 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 <coins.h>
10 #include <consensus/amount.h>
11 #include <indirectmap.h>
12 #include <kernel/cs_main.h>
13 #include <kernel/mempool_entry.h> // IWYU pragma: export
14 #include <kernel/mempool_limits.h> // IWYU pragma: export
15 #include <kernel/mempool_options.h> // IWYU pragma: export
16 #include <kernel/mempool_removal_reason.h> // IWYU pragma: export
17 #include <policy/feerate.h>
18 #include <policy/packages.h>
19 #include <primitives/transaction.h>
20 #include <sync.h>
21 #include <util/epochguard.h>
22 #include <util/hasher.h>
23 #include <util/result.h>
24 #include <util/feefrac.h>
25 
26 #include <boost/multi_index/hashed_index.hpp>
27 #include <boost/multi_index/identity.hpp>
28 #include <boost/multi_index/indexed_by.hpp>
29 #include <boost/multi_index/ordered_index.hpp>
30 #include <boost/multi_index/sequenced_index.hpp>
31 #include <boost/multi_index/tag.hpp>
32 #include <boost/multi_index_container.hpp>
33 
34 #include <atomic>
35 #include <map>
36 #include <optional>
37 #include <set>
38 #include <string>
39 #include <string_view>
40 #include <utility>
41 #include <vector>
42 
43 class CChain;
44 class ValidationSignals;
45 
46 struct bilingual_str;
47 
49 static const uint32_t MEMPOOL_HEIGHT = 0x7FFFFFFF;
50 
55 
56 // extracts a transaction hash from CTxMemPoolEntry or CTransactionRef
58 {
61  {
62  return entry.GetTx().GetHash();
63  }
64 
66  {
67  return tx->GetHash();
68  }
69 };
70 
71 // extracts a transaction witness-hash from CTxMemPoolEntry or CTransactionRef
73 {
76  {
77  return entry.GetTx().GetWitnessHash();
78  }
79 
81  {
82  return tx->GetWitnessHash();
83  }
84 };
85 
86 
92 {
93 public:
94  bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) const
95  {
96  double a_mod_fee, a_size, b_mod_fee, b_size;
97 
98  GetModFeeAndSize(a, a_mod_fee, a_size);
99  GetModFeeAndSize(b, b_mod_fee, b_size);
100 
101  // Avoid division by rewriting (a/b > c/d) as (a*d > c*b).
102  double f1 = a_mod_fee * b_size;
103  double f2 = a_size * b_mod_fee;
104 
105  if (f1 == f2) {
106  return a.GetTime() >= b.GetTime();
107  }
108  return f1 < f2;
109  }
110 
111  // Return the fee/size we're using for sorting this entry.
112  void GetModFeeAndSize(const CTxMemPoolEntry &a, double &mod_fee, double &size) const
113  {
114  // Compare feerate with descendants to feerate of the transaction, and
115  // return the fee/size for the max.
116  double f1 = (double)a.GetModifiedFee() * a.GetSizeWithDescendants();
117  double f2 = (double)a.GetModFeesWithDescendants() * a.GetTxSize();
118 
119  if (f2 > f1) {
120  mod_fee = a.GetModFeesWithDescendants();
121  size = a.GetSizeWithDescendants();
122  } else {
123  mod_fee = a.GetModifiedFee();
124  size = a.GetTxSize();
125  }
126  }
127 };
128 
137 {
138 public:
139  bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) const
140  {
141  double f1 = (double)a.GetFee() * b.GetTxSize();
142  double f2 = (double)b.GetFee() * a.GetTxSize();
143  if (f1 == f2) {
144  return b.GetTx().GetHash() < a.GetTx().GetHash();
145  }
146  return f1 > f2;
147  }
148 };
149 
151 {
152 public:
153  bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) const
154  {
155  return a.GetTime() < b.GetTime();
156  }
157 };
158 
164 {
165 public:
166  template<typename T>
167  bool operator()(const T& a, const T& b) const
168  {
169  double a_mod_fee, a_size, b_mod_fee, b_size;
170 
171  GetModFeeAndSize(a, a_mod_fee, a_size);
172  GetModFeeAndSize(b, b_mod_fee, b_size);
173 
174  // Avoid division by rewriting (a/b > c/d) as (a*d > c*b).
175  double f1 = a_mod_fee * b_size;
176  double f2 = a_size * b_mod_fee;
177 
178  if (f1 == f2) {
179  return a.GetTx().GetHash() < b.GetTx().GetHash();
180  }
181  return f1 > f2;
182  }
183 
184  // Return the fee/size we're using for sorting this entry.
185  template <typename T>
186  void GetModFeeAndSize(const T &a, double &mod_fee, double &size) const
187  {
188  // Compare feerate with ancestors to feerate of the transaction, and
189  // return the fee/size for the min.
190  double f1 = (double)a.GetModifiedFee() * a.GetSizeWithAncestors();
191  double f2 = (double)a.GetModFeesWithAncestors() * a.GetTxSize();
192 
193  if (f1 > f2) {
194  mod_fee = a.GetModFeesWithAncestors();
195  size = a.GetSizeWithAncestors();
196  } else {
197  mod_fee = a.GetModifiedFee();
198  size = a.GetTxSize();
199  }
200  }
201 };
202 
203 // Multi_index tag names
205 struct entry_time {};
206 struct ancestor_score {};
207 struct index_by_wtxid {};
208 
213 {
216 
218  std::chrono::seconds m_time;
219 
222 
224  int32_t vsize;
225 
227  int64_t nFeeDelta;
228 };
229 
304 {
305 protected:
306  std::atomic<unsigned int> nTransactionsUpdated{0};
307 
308  uint64_t totalTxSize GUARDED_BY(cs){0};
309  CAmount m_total_fee GUARDED_BY(cs){0};
310  uint64_t cachedInnerUsage GUARDED_BY(cs){0};
311 
312  mutable int64_t lastRollingFeeUpdate GUARDED_BY(cs){GetTime()};
313  mutable bool blockSinceLastRollingFeeBump GUARDED_BY(cs){false};
314  mutable double rollingMinimumFeeRate GUARDED_BY(cs){0};
316 
317  // In-memory counter for external mempool tracking purposes.
318  // This number is incremented once every time a transaction
319  // is added or removed from the mempool for any reason.
320  mutable uint64_t m_sequence_number GUARDED_BY(cs){1};
321 
323 
324  bool m_load_tried GUARDED_BY(cs){false};
325 
326  CFeeRate GetMinFee(size_t sizelimit) const;
327 
328 public:
329 
330  static const int ROLLING_FEE_HALFLIFE = 60 * 60 * 12; // public only for testing
331 
332  struct CTxMemPoolEntry_Indices final : boost::multi_index::indexed_by<
333  // sorted by txid
334  boost::multi_index::hashed_unique<mempoolentry_txid, SaltedTxidHasher>,
335  // sorted by wtxid
336  boost::multi_index::hashed_unique<
337  boost::multi_index::tag<index_by_wtxid>,
338  mempoolentry_wtxid,
339  SaltedTxidHasher
340  >,
341  // sorted by fee rate
342  boost::multi_index::ordered_non_unique<
343  boost::multi_index::tag<descendant_score>,
344  boost::multi_index::identity<CTxMemPoolEntry>,
345  CompareTxMemPoolEntryByDescendantScore
346  >,
347  // sorted by entry time
348  boost::multi_index::ordered_non_unique<
349  boost::multi_index::tag<entry_time>,
350  boost::multi_index::identity<CTxMemPoolEntry>,
351  CompareTxMemPoolEntryByEntryTime
352  >,
353  // sorted by fee rate with ancestors
354  boost::multi_index::ordered_non_unique<
355  boost::multi_index::tag<ancestor_score>,
356  boost::multi_index::identity<CTxMemPoolEntry>,
357  CompareTxMemPoolEntryByAncestorFee
358  >
359  >
360  {};
361  typedef boost::multi_index_container<
365 
392 
393  using txiter = indexed_transaction_set::nth_index<0>::type::const_iterator;
394  std::vector<CTransactionRef> txns_randomized GUARDED_BY(cs);
395 
396  typedef std::set<txiter, CompareIteratorByHash> setEntries;
397 
399 
401 private:
402  typedef std::map<txiter, setEntries, CompareIteratorByHash> cacheMap;
403 
404 
405  void UpdateParent(txiter entry, txiter parent, bool add) EXCLUSIVE_LOCKS_REQUIRED(cs);
406  void UpdateChild(txiter entry, txiter child, bool add) EXCLUSIVE_LOCKS_REQUIRED(cs);
407 
408  std::vector<indexed_transaction_set::const_iterator> GetSortedDepthAndScore() const EXCLUSIVE_LOCKS_REQUIRED(cs);
409 
413  std::set<uint256> m_unbroadcast_txids GUARDED_BY(cs);
414 
415 
428  size_t entry_count,
429  CTxMemPoolEntry::Parents &staged_ancestors,
430  const Limits& limits
431  ) const EXCLUSIVE_LOCKS_REQUIRED(cs);
432 
433 public:
434  indirectmap<COutPoint, const CTransaction*> mapNextTx GUARDED_BY(cs);
435  std::map<uint256, CAmount> mapDeltas GUARDED_BY(cs);
436 
437  using Options = kernel::MemPoolOptions;
438 
440 
446  explicit CTxMemPool(Options opts, bilingual_str& error);
447 
454  void check(const CCoinsViewCache& active_coins_tip, int64_t spendheight) const EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
455 
456 
465  void removeForReorg(CChain& chain, std::function<bool(txiter)> filter_final_and_mature) EXCLUSIVE_LOCKS_REQUIRED(cs, cs_main);
467  void removeForBlock(const std::vector<CTransactionRef>& vtx, unsigned int nBlockHeight) EXCLUSIVE_LOCKS_REQUIRED(cs);
468 
469  bool CompareDepthAndScore(const uint256& hasha, const uint256& hashb, bool wtxid=false);
470  bool isSpent(const COutPoint& outpoint) const;
471  unsigned int GetTransactionsUpdated() const;
472  void AddTransactionsUpdated(unsigned int n);
477  bool HasNoInputsOf(const CTransaction& tx) const EXCLUSIVE_LOCKS_REQUIRED(cs);
478 
480  void PrioritiseTransaction(const uint256& hash, const CAmount& nFeeDelta);
481  void ApplyDelta(const uint256& hash, CAmount &nFeeDelta) const EXCLUSIVE_LOCKS_REQUIRED(cs);
483 
484  struct delta_info {
486  const bool in_mempool;
488  const CAmount delta;
490  std::optional<CAmount> modified_fee;
492  const uint256 txid;
493  };
495  std::vector<delta_info> GetPrioritisedTransactions() const EXCLUSIVE_LOCKS_REQUIRED(!cs);
496 
498  const CTransaction* GetConflictTx(const COutPoint& prevout) const EXCLUSIVE_LOCKS_REQUIRED(cs);
499 
501  std::optional<txiter> GetIter(const uint256& txid) const EXCLUSIVE_LOCKS_REQUIRED(cs);
502 
506  setEntries GetIterSet(const std::set<Txid>& hashes) const EXCLUSIVE_LOCKS_REQUIRED(cs);
507 
511  std::vector<txiter> GetIterVec(const std::vector<uint256>& txids) const EXCLUSIVE_LOCKS_REQUIRED(cs);
512 
527 
541  const Limits& limits,
542  bool fSearchForParents = true) const EXCLUSIVE_LOCKS_REQUIRED(cs);
543 
559  std::string_view calling_fn_name,
560  const CTxMemPoolEntry &entry,
561  const Limits& limits,
562  bool fSearchForParents = true) const EXCLUSIVE_LOCKS_REQUIRED(cs);
563 
568  std::vector<txiter> GatherClusters(const std::vector<uint256>& txids) const EXCLUSIVE_LOCKS_REQUIRED(cs);
569 
582  util::Result<void> CheckPackageLimits(const Package& package,
583  int64_t total_vsize) const EXCLUSIVE_LOCKS_REQUIRED(cs);
584 
588  void CalculateDescendants(txiter it, setEntries& setDescendants) const EXCLUSIVE_LOCKS_REQUIRED(cs);
589 
596  CFeeRate GetMinFee() const {
598  }
599 
604  void TrimToSize(size_t sizelimit, std::vector<COutPoint>* pvNoSpendsRemaining = nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs);
605 
607  int Expire(std::chrono::seconds time) EXCLUSIVE_LOCKS_REQUIRED(cs);
608 
615  void GetTransactionAncestry(const uint256& txid, size_t& ancestors, size_t& descendants, size_t* ancestorsize = nullptr, CAmount* ancestorfees = nullptr) const;
616 
621  bool GetLoadTried() const;
622 
627  void SetLoadTried(bool load_tried);
628 
629  unsigned long size() const
630  {
631  LOCK(cs);
632  return mapTx.size();
633  }
634 
636  {
638  return totalTxSize;
639  }
640 
642  {
644  return m_total_fee;
645  }
646 
647  bool exists(const GenTxid& gtxid) const
648  {
649  LOCK(cs);
650  if (gtxid.IsWtxid()) {
651  return (mapTx.get<index_by_wtxid>().count(gtxid.GetHash()) != 0);
652  }
653  return (mapTx.count(gtxid.GetHash()) != 0);
654  }
655 
657 
658  CTransactionRef get(const uint256& hash) const;
660  {
662  return mapTx.project<0>(mapTx.get<index_by_wtxid>().find(wtxid));
663  }
664  TxMempoolInfo info(const GenTxid& gtxid) const;
665 
667  TxMempoolInfo info_for_relay(const GenTxid& gtxid, uint64_t last_sequence) const;
668 
669  std::vector<CTxMemPoolEntryRef> entryAll() const EXCLUSIVE_LOCKS_REQUIRED(cs);
670  std::vector<TxMempoolInfo> infoAll() const;
671 
672  size_t DynamicMemoryUsage() const;
673 
675  void AddUnbroadcastTx(const uint256& txid)
676  {
677  LOCK(cs);
678  // Sanity check the transaction is in the mempool & insert into
679  // unbroadcast set.
680  if (exists(GenTxid::Txid(txid))) m_unbroadcast_txids.insert(txid);
681  };
682 
684  void RemoveUnbroadcastTx(const uint256& txid, const bool unchecked = false);
685 
687  std::set<uint256> GetUnbroadcastTxs() const
688  {
689  LOCK(cs);
690  return m_unbroadcast_txids;
691  }
692 
695  {
697  return m_unbroadcast_txids.count(txid) != 0;
698  }
699 
702  return m_sequence_number++;
703  }
704 
706  return m_sequence_number;
707  }
708 
709  /* Check that all direct conflicts are in a cluster size of two or less. Each
710  * direct conflict may be in a separate cluster.
711  */
712  std::optional<std::string> CheckConflictTopology(const setEntries& direct_conflicts);
713 
714 private:
722  void RemoveStaged(setEntries& stage, bool updateDescendants, MemPoolRemovalReason reason) EXCLUSIVE_LOCKS_REQUIRED(cs);
723 
752  void UpdateForDescendants(txiter updateIt, cacheMap& cachedDescendants,
753  const std::set<uint256>& setExclude, std::set<uint256>& descendants_to_remove) EXCLUSIVE_LOCKS_REQUIRED(cs);
755  void UpdateAncestorsOf(bool add, txiter hash, setEntries &setAncestors) EXCLUSIVE_LOCKS_REQUIRED(cs);
761  void UpdateForRemoveFromMempool(const setEntries &entriesToRemove, bool updateDescendants) EXCLUSIVE_LOCKS_REQUIRED(cs);
764 
774 public:
783  bool visited(const txiter it) const EXCLUSIVE_LOCKS_REQUIRED(cs, m_epoch)
784  {
785  return m_epoch.visited(it->m_epoch_marker);
786  }
787 
788  bool visited(std::optional<txiter> it) const EXCLUSIVE_LOCKS_REQUIRED(cs, m_epoch)
789  {
790  assert(m_epoch.guarded()); // verify guard even when it==nullopt
791  return !it || visited(*it);
792  }
793 
794  /*
795  * CTxMemPool::ChangeSet:
796  *
797  * This class is used for all mempool additions and associated removals (eg
798  * due to rbf). Removals that don't need to be evaluated for acceptance,
799  * such as removing transactions that appear in a block, or due to reorg,
800  * or removals related to mempool limiting or expiry do not need to use
801  * this.
802  *
803  * Callers can interleave calls to StageAddition()/StageRemoval(), and
804  * removals may be invoked in any order, but additions must be done in a
805  * topological order in the case of transaction packages (ie, parents must
806  * be added before children).
807  *
808  * CalculateChunksForRBF() can be used to calculate the feerate diagram of
809  * the proposed set of new transactions and compare with the existing
810  * mempool.
811  *
812  * CalculateMemPoolAncestors() calculates the in-mempool (not including
813  * what is in the change set itself) ancestors of a given transaction.
814  *
815  * Apply() will apply the removals and additions that are staged into the
816  * mempool.
817  *
818  * Only one changeset may exist at a time. While a changeset is
819  * outstanding, no removals or additions may be made directly to the
820  * mempool.
821  */
822  class ChangeSet {
823  public:
824  explicit ChangeSet(CTxMemPool* pool) : m_pool(pool) {}
825  ~ChangeSet() EXCLUSIVE_LOCKS_REQUIRED(m_pool->cs) { m_pool->m_have_changeset = false; }
826 
827  ChangeSet(const ChangeSet&) = delete;
828  ChangeSet& operator=(const ChangeSet&) = delete;
829 
831 
832  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);
834 
835  const CTxMemPool::setEntries& GetRemovals() const { return m_to_remove; }
836 
838  {
839  // Look up transaction in our cache first
840  auto it = m_ancestors.find(tx);
841  if (it != m_ancestors.end()) return it->second;
842 
843  // If not found, try to have the mempool calculate it, and cache
844  // for later.
845  LOCK(m_pool->cs);
846  auto ret{m_pool->CalculateMemPoolAncestors(*tx, limits)};
847  if (ret) m_ancestors.try_emplace(tx, *ret);
848  return ret;
849  }
850 
851  std::vector<CTransactionRef> GetAddedTxns() const {
852  std::vector<CTransactionRef> ret;
853  ret.reserve(m_entry_vec.size());
854  for (const auto& entry : m_entry_vec) {
855  ret.emplace_back(entry->GetSharedTx());
856  }
857  return ret;
858  }
859 
867 
868  size_t GetTxCount() const { return m_entry_vec.size(); }
869  const CTransaction& GetAddedTxn(size_t index) const { return m_entry_vec.at(index)->GetTx(); }
870 
872 
873  private:
876  std::vector<CTxMemPool::txiter> m_entry_vec; // track the added transactions' insertion order
877  // map from the m_to_add index to the ancestors for the transaction
880 
881  friend class CTxMemPool;
882  };
883 
885  Assume(!m_have_changeset);
886  m_have_changeset = true;
887  return std::make_unique<ChangeSet>(this);
888  }
889 
890  bool m_have_changeset GUARDED_BY(cs){false};
891 
892  friend class CTxMemPool::ChangeSet;
893 
894 private:
895  // Apply the given changeset to the mempool, by removing transactions in
896  // the to_remove set and adding transactions in the to_add set.
898 
899  // addNewTransaction must update state for all ancestors of a given transaction,
900  // to track size/count of descendant transactions. First version of
901  // addNewTransaction can be used to have it call CalculateMemPoolAncestors(), and
902  // then invoke the second version.
903  // Note that addNewTransaction is ONLY called (via Apply()) from ATMP
904  // outside of tests and any other callers may break wallet's in-mempool
905  // tracking (due to lack of CValidationInterface::TransactionAddedToMempool
906  // callbacks).
909 };
910 
925 {
930  std::unordered_map<COutPoint, Coin, SaltedOutpointHasher> m_temp_added;
931 
936  mutable std::unordered_set<COutPoint, SaltedOutpointHasher> m_non_base_coins;
937 protected:
939 
940 public:
941  CCoinsViewMemPool(CCoinsView* baseIn, const CTxMemPool& mempoolIn);
944  std::optional<Coin> GetCoin(const COutPoint& outpoint) const override;
947  void PackageAddTransaction(const CTransactionRef& tx);
949  std::unordered_set<COutPoint, SaltedOutpointHasher> GetNonBaseCoins() const { return m_non_base_coins; }
951  void Reset();
952 };
953 #endif // BITCOIN_TXMEMPOOL_H
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:423
int64_t lastRollingFeeUpdate GUARDED_BY(cs)
sum of dynamic memory usage of all the map elements (NOT the maps themselves)
Definition: txmempool.h:312
const bool in_mempool
Whether this transaction is in the mempool.
Definition: txmempool.h:486
Information about a mempool transaction.
Definition: txmempool.h:212
std::vector< txiter > GetIterVec(const std::vector< uint256 > &txids) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Translate a list of hashes into a list of mempool iterators to avoid repeated lookups.
Definition: txmempool.cpp:1004
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...
Definition: txmempool.h:936
int ret
ChangeSet & operator=(const ChangeSet &)=delete
bool m_have_changeset GUARDED_BY(cs)
Definition: txmempool.h:890
util::Result< CTxMemPool::setEntries > CalculateMemPoolAncestors(TxHandle tx, const Limits &limits)
Definition: txmempool.h:837
AssertLockHeld(pool.cs)
indexed_transaction_set::nth_index< 0 >::type::const_iterator txiter
Definition: txmempool.h:393
assert(!tx.IsCoinBase())
std::vector< TxMempoolInfo > infoAll() const
Definition: txmempool.cpp:863
int32_t GetTxSize() const
const CTransaction & GetAddedTxn(size_t index) const
Definition: txmempool.h:869
Bilingual messages:
Definition: translation.h:24
bool exists(const GenTxid &gtxid) const
Definition: txmempool.h:647
void UpdateTransactionsFromBlock(const std::vector< uint256 > &vHashesToUpdate) EXCLUSIVE_LOCKS_REQUIRED(cs
UpdateTransactionsFromBlock is called when adding transactions from a disconnected block back to the ...
Definition: txmempool.cpp:108
const uint256 txid
The prioritised transaction&#39;s txid.
Definition: txmempool.h:492
~ChangeSet() EXCLUSIVE_LOCKS_REQUIRED(m_pool -> cs)
Definition: txmempool.h:825
Options struct containing limit options for a CTxMemPool.
An in-memory indexed chain of blocks.
Definition: chain.h:416
Epoch m_epoch GUARDED_BY(cs)
minimum fee to get into the pool, decreases exponentially
Definition: txmempool.h:315
void CalculateDescendants(txiter it, setEntries &setDescendants) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Populate setDescendants with all in-mempool descendants of hash.
Definition: txmempool.cpp:571
size_t DynamicMemoryUsage() const
Definition: txmempool.cpp:1063
std::vector< CTransactionRef > Package
A package is an ordered list of transactions.
Definition: packages.h:50
bool operator()(const CTxMemPoolEntry &a, const CTxMemPoolEntry &b) const
Definition: txmempool.h:153
MemPoolRemovalReason
Reason why a transaction was removed from the mempool, this is passed to the notification signal...
void removeConflicts(const CTransaction &tx) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:647
std::map< CTxMemPool::txiter, CTxMemPool::setEntries, CompareIteratorByHash > m_ancestors
Definition: txmempool.h:878
size_t GetTxCount() const
Definition: txmempool.h:868
CAmount GetModFeesWithDescendants() const
ChangeSet(CTxMemPool *pool)
Definition: txmempool.h:824
void RemoveStaged(setEntries &stage, bool updateDescendants, MemPoolRemovalReason reason) EXCLUSIVE_LOCKS_REQUIRED(cs)
Remove a set of transactions from the mempool.
Definition: txmempool.cpp:1078
unsigned long size() const
Definition: txmempool.h:629
uint64_t GetSequence() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.h:705
std::unique_ptr< ChangeSet > GetChangeSet() EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.h:884
bool CompareDepthAndScore(const uint256 &hasha, const uint256 &hashb, bool wtxid=false)
Definition: txmempool.cpp:797
std::set< txiter, CompareIteratorByHash > setEntries
Definition: txmempool.h:396
bool operator()(const CTxMemPoolEntry &a, const CTxMemPoolEntry &b) const
Definition: txmempool.h:94
std::unordered_set< COutPoint, SaltedOutpointHasher > GetNonBaseCoins() const
Get all coins in m_non_base_coins.
Definition: txmempool.h:949
std::atomic< unsigned int > nTransactionsUpdated
Used by getblocktemplate to trigger CreateNewBlock() invocation.
Definition: txmempool.h:306
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...
Definition: txmempool.h:457
void SetLoadTried(bool load_tried)
Set whether or not an initial attempt to load the persisted mempool was made (regardless of whether t...
Definition: txmempool.cpp:1242
void StageRemoval(CTxMemPool::txiter it)
Definition: txmempool.h:833
CFeeRate GetMinFee() const
The minimum fee to get into the mempool, which may itself not be enough for larger-sized transactions...
Definition: txmempool.h:596
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.
Definition: txmempool.cpp:275
CTxMemPool::indexed_transaction_set m_to_add
Definition: txmempool.h:875
CAmount GetModifiedFee() const
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.
Definition: txmempool.cpp:243
int64_t nFeeDelta
The fee delta.
Definition: txmempool.h:227
bool isSpent(const COutPoint &outpoint) const
Definition: txmempool.cpp:419
const CTxMemPool::setEntries & GetRemovals() const
Definition: txmempool.h:835
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...
Definition: txmempool.cpp:626
std::vector< txiter > GatherClusters(const std::vector< uint256 > &txids) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Collect the entire cluster of connected transactions for each transaction in txids.
Definition: txmempool.cpp:1248
const CAmount delta
The fee delta added using PrioritiseTransaction().
Definition: txmempool.h:488
CTransactionRef tx
The transaction itself.
Definition: txmempool.h:215
CTxMemPoolEntry stores data about the corresponding transaction, as well as data about all in-mempool...
Definition: mempool_entry.h:65
void GetModFeeAndSize(const T &a, double &mod_fee, double &size) const
Definition: txmempool.h:186
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:289
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
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...
Definition: txmempool.cpp:57
bool operator()(const T &a, const T &b) const
Definition: txmempool.h:167
CTxMemPool * m_pool
Definition: txmempool.h:874
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:49
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...
Definition: txmempool.cpp:1315
bool blockSinceLastRollingFeeBump GUARDED_BY(cs)
Definition: txmempool.h:313
result_type operator()(const CTxMemPoolEntry &entry) const
Definition: txmempool.h:60
void AddUnbroadcastTx(const uint256 &txid)
Adds a transaction to the unbroadcast set.
Definition: txmempool.h:675
#define LIFETIMEBOUND
Definition: attributes.h:16
Definition: txmempool.h:163
Abstract view on the open txout dataset.
Definition: coins.h:309
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:1086
#define LOCK(cs)
Definition: sync.h:257
bool m_load_tried GUARDED_BY(cs)
Definition: txmempool.h:324
const CAmount & GetFee() const
result_type operator()(const CTxMemPoolEntry &entry) const
Definition: txmempool.h:75
double rollingMinimumFeeRate GUARDED_BY(cs)
Definition: txmempool.h:314
std::vector< CTxMemPool::txiter > m_entry_vec
Definition: txmempool.h:876
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:520
uint64_t cachedInnerUsage GUARDED_BY(cs)
sum of all mempool tx&#39;s fees (NOT modified fee)
Definition: txmempool.h:310
std::vector< delta_info > GetPrioritisedTransactions() const EXCLUSIVE_LOCKS_REQUIRED(!cs)
Return a vector of all entries in mapDeltas with their corresponding delta_info.
Definition: txmempool.cpp:965
CTxMemPool::txiter TxHandle
Definition: txmempool.h:830
Sort an entry by max(score/size of entry&#39;s tx, score/size with all descendants).
Definition: txmempool.h:91
static const int ROLLING_FEE_HALFLIFE
Definition: txmempool.h:330
uint64_t GetTotalTxSize() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.h:635
uint64_t m_sequence_number GUARDED_BY(cs)
Definition: txmempool.h:320
boost::multi_index_container< CTxMemPoolEntry, CTxMemPoolEntry_Indices > indexed_transaction_set
Definition: txmempool.h:364
std::chrono::seconds GetTime() const
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:981
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:28
void AddTransactionsUpdated(unsigned int n)
Definition: txmempool.cpp:430
uint256 result_type
Definition: txmempool.h:59
void ApplyDelta(const uint256 &hash, CAmount &nFeeDelta) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:949
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)
Definition: txmempool.cpp:1406
#define Assume(val)
Assume is the identity function.
Definition: check.h:97
bool IsWtxid() const
Definition: transaction.h:436
uint64_t CalculateDescendantMaximum(txiter entry) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:1202
bool GetLoadTried() const
Definition: txmempool.cpp:1236
TxMempoolInfo info_for_relay(const GenTxid &gtxid, uint64_t last_sequence) const
Returns info for a transaction if its entry_sequence < last_sequence.
Definition: txmempool.cpp:902
std::vector< CTransactionRef > GetAddedTxns() const
Definition: txmempool.h:851
std::optional< CAmount > modified_fee
The modified fee (base fee + delta) of this entry.
Definition: txmempool.h:490
std::optional< txiter > GetIter(const uint256 &txid) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Returns an iterator to the given hash, if found.
Definition: txmempool.cpp:987
void cs_main
Definition: txmempool.h:465
256-bit opaque blob.
Definition: uint256.h:201
void Apply() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: txmempool.cpp:1419
const CTxMemPoolEntry * GetEntry(const Txid &txid) const LIFETIMEBOUND EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:877
int32_t vsize
Virtual size of the transaction.
Definition: txmempool.h:224
uint64_t GetAndIncrementSequence() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Guards this internal counter for external reporting.
Definition: txmempool.h:701
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
std::vector< indexed_transaction_set::const_iterator > GetSortedDepthAndScore() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:833
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...
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:303
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:1017
CTxMemPool::setEntries m_to_remove
Definition: txmempool.h:879
std::map< txiter, setEntries, CompareIteratorByHash > cacheMap
Definition: txmempool.h:402
std::set< uint256 > GetUnbroadcastTxs() const
Returns transactions in unbroadcast set.
Definition: txmempool.h:687
const CTransaction & GetTx() const
void UpdateEntryForAncestors(txiter it, const setEntries &setAncestors) EXCLUSIVE_LOCKS_REQUIRED(cs)
Set ancestor state for an entry.
Definition: txmempool.cpp:304
CAmount GetTotalFee() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.h:641
bool m_epoch
Definition: txmempool.h:784
TxMempoolInfo info(const GenTxid &gtxid) const
Definition: txmempool.cpp:893
txiter get_iter_from_wtxid(const uint256 &wtxid) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.h:659
void UpdateChild(txiter entry, txiter child, bool add) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:1104
void ClearPrioritisation(const uint256 &hash) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:959
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:1224
std::optional< std::string > CheckConflictTopology(const setEntries &direct_conflicts)
Definition: txmempool.cpp:1275
Fee rate in satoshis per kilovirtualbyte: CAmount / kvB.
Definition: feerate.h:32
unsigned int GetTransactionsUpdated() const
Definition: txmempool.cpp:425
CAmount fee
Fee of the transaction.
Definition: txmempool.h:221
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:1158
Definition: txmempool.h:332
util::Result< setEntries > CalculateAncestorsAndCheckLimits(int64_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...
Definition: txmempool.cpp:163
void RemoveUnbroadcastTx(const uint256 &txid, const bool unchecked=false)
Removes a transaction from the unbroadcast set.
Definition: txmempool.cpp:1069
void trackPackageRemoved(const CFeeRate &rate) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:1150
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. ...
Definition: txmempool.cpp:40
Options struct containing options for constructing a CTxMemPool.
CAmount m_total_fee GUARDED_BY(cs)
sum of all mempool tx&#39;s virtual sizes. Differs from serialized tx size since witness data is discount...
Definition: txmempool.h:309
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:295
CCoinsView backed by another CCoinsView.
Definition: coins.h:343
bool IsUnbroadcastTx(const uint256 &txid) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Returns whether a txid is in the unbroadcast set.
Definition: txmempool.h:694
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:362
Sort by feerate of entry (fee/size) in descending order This is only used for transaction relay...
Definition: txmempool.h:136
void UpdateParent(txiter entry, txiter parent, bool add) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:1115
const CTxMemPool & mempool
Definition: txmempool.h:938
int64_t GetTime()
DEPRECATED, see GetTime.
Definition: time.cpp:76
void UpdateChildrenForRemoval(txiter entry) EXCLUSIVE_LOCKS_REQUIRED(cs)
Sever link between specified transaction and direct children.
Definition: txmempool.cpp:318
uint256 result_type
Definition: txmempool.h:74
std::chrono::seconds m_time
Time the transaction entered the mempool.
Definition: txmempool.h:218
void GetModFeeAndSize(const CTxMemPoolEntry &a, double &mod_fee, double &size) const
Definition: txmempool.h:112
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate...
Definition: cs_main.cpp:8
return !it visited * it
Definition: txmempool.h:791
void addNewTransaction(CTxMemPool::txiter it) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:471
CCoinsView that brings transactions from a mempool into view.
Definition: txmempool.h:924
util::Result< void > CheckPackageLimits(const Package &package, int64_t total_vsize) 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:205
void removeForBlock(const std::vector< CTransactionRef > &vtx, unsigned int nBlockHeight) EXCLUSIVE_LOCKS_REQUIRED(cs)
Called when a block is connected.
Definition: txmempool.cpp:667
LockPoints lp
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. ...
Definition: txmempool.cpp:994
void PrioritiseTransaction(const uint256 &hash, const CAmount &nFeeDelta)
Affect CreateNewBlock prioritisation of transactions.
Definition: txmempool.cpp:913
A generic txid reference (txid or wtxid).
Definition: transaction.h:427
std::unordered_map< COutPoint, Coin, SaltedOutpointHasher > m_temp_added
Coins made available by transactions being validated.
Definition: txmempool.h:930
static GenTxid Txid(const uint256 &hash)
Definition: transaction.h:434
const Wtxid & GetWitnessHash() const LIFETIMEBOUND
Definition: transaction.h:344
std::vector< CTxMemPoolEntryRef > entryAll() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:851
uint64_t fee
bool operator()(const CTxMemPoolEntry &a, const CTxMemPoolEntry &b) const
Definition: txmempool.h:139
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:326
const uint256 & GetHash() const LIFETIMEBOUND
Definition: transaction.h:437
int64_t GetSizeWithDescendants() const
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it...
Definition: txmempool.h:390
void cs_main LOCKS_EXCLUDED(m_epoch)
Definition: txmempool.h:150
const Txid & GetHash() const LIFETIMEBOUND
Definition: transaction.h:343
Epoch: RAII-style guard for using epoch-based graph traversal algorithms.
Definition: epochguard.h:34
const Options m_opts
Definition: txmempool.h:439
uint64_t totalTxSize GUARDED_BY(cs)
Definition: txmempool.h:308