Bitcoin ABC  0.26.3
P2P Digital Currency
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or
9 #include <coins.h>
10 #include <consensus/amount.h>
11 #include <core_memusage.h>
12 #include <indirectmap.h>
13 #include <policy/packages.h>
14 #include <primitives/transaction.h>
15 #include <sync.h>
16 #include <util/hasher.h>
18 #include <boost/multi_index/hashed_index.hpp>
19 #include <boost/multi_index/ordered_index.hpp>
20 #include <boost/multi_index/sequenced_index.hpp>
21 #include <boost/multi_index_container.hpp>
23 #include <atomic>
24 #include <map>
25 #include <optional>
26 #include <set>
27 #include <string>
28 #include <unordered_map>
29 #include <utility>
30 #include <vector>
32 class CBlockIndex;
33 class CChain;
34 class Chainstate;
35 class Config;
37 extern RecursiveMutex cs_main;
43 static const uint32_t MEMPOOL_HEIGHT = 0x7FFFFFFF;
45 struct LockPoints {
46  // Will be set to the blockchain height and median time past values that
47  // would be necessary to satisfy all relative locktime constraints (BIP68)
48  // of this tx given our view of block chain history
49  int height{0};
50  int64_t time{0};
51  // As long as the current chain descends from the highest height block
52  // containing one of the inputs used in the calculation, then the cached
53  // values are still valid even after a reorg.
55 };
61 bool TestLockPointValidity(const CChain &active_chain, const LockPoints &lp)
65  // SFINAE for T where T is either a pointer type (e.g., a txiter) or a
66  // reference_wrapper<T> (e.g. a wrapped CTxMemPoolEntry&)
67  template <typename T>
68  bool operator()(const std::reference_wrapper<T> &a,
69  const std::reference_wrapper<T> &b) const {
70  return a.get().GetTx().GetId() < b.get().GetTx().GetId();
71  }
72  template <typename T> bool operator()(const T &a, const T &b) const {
73  return a->GetTx().GetId() < b->GetTx().GetId();
74  }
75 };
89 public:
90  typedef std::reference_wrapper<const CTxMemPoolEntry> CTxMemPoolEntryRef;
91  // two aliases, should the types ever diverge
92  typedef std::set<CTxMemPoolEntryRef, CompareIteratorById> Parents;
93  typedef std::set<CTxMemPoolEntryRef, CompareIteratorById> Children;
95 private:
97  uint64_t entryId = 0;
103  const Amount nFee;
105  const size_t nTxSize;
107  const size_t nUsageSize;
109  const int64_t nTime;
111  const unsigned int entryHeight;
113  const bool spendsCoinbase;
115  const int64_t sigChecks;
122  // NOTE:
123  // The below members will stop being updated after Wellington activation,
124  // and should be removed in the release after Wellington is checkpointed.
125  //
126  // Information about descendants of this transaction that are in the
127  // mempool; if we remove this transaction we must remove all of these
128  // descendants as well.
138  // Analogous statistics for ancestor transactions
139  uint64_t nCountWithAncestors{1};
144 public:
145  CTxMemPoolEntry(const CTransactionRef &_tx, const Amount fee, int64_t time,
146  unsigned int entry_height, bool spends_coinbase,
147  int64_t sigchecks, LockPoints lp);
149  uint64_t GetEntryId() const { return entryId; }
152  void SetEntryId(uint64_t eid) { entryId = eid; }
154  const CTransaction &GetTx() const { return *this->tx; }
155  CTransactionRef GetSharedTx() const { return this->tx; }
156  Amount GetFee() const { return nFee; }
157  size_t GetTxSize() const { return nTxSize; }
158  size_t GetTxVirtualSize() const;
160  std::chrono::seconds GetTime() const { return std::chrono::seconds{nTime}; }
161  unsigned int GetHeight() const { return entryHeight; }
162  int64_t GetSigChecks() const { return sigChecks; }
163  Amount GetModifiedFee() const { return nFee + feeDelta; }
166  }
167  size_t DynamicMemoryUsage() const { return nUsageSize; }
168  const LockPoints &GetLockPoints() const { return lockPoints; }
170  // Adjusts the descendant state. -- To be removed after Wellington
171  void UpdateDescendantState(int64_t modifySize, Amount modifyFee,
172  int64_t modifyCount, int64_t modifySigChecks);
173  // Adjusts the ancestor state -- To be removed after Wellington
174  void UpdateAncestorState(int64_t modifySize, Amount modifyFee,
175  int64_t modifyCount, int64_t modifySigChecks);
177  // Updates the fee delta used for mining priority score, and the
178  // modified fees with descendants.
180  // Update the LockPoints after a reorg
181  void UpdateLockPoints(const LockPoints &lp);
183  uint64_t GetCountWithDescendants() const { return nCountWithDescendants; }
184  uint64_t GetSizeWithDescendants() const { return nSizeWithDescendants; }
185  uint64_t GetVirtualSizeWithDescendants() const;
187  int64_t GetSigChecksWithDescendants() const {
189  }
191  bool GetSpendsCoinbase() const { return spendsCoinbase; }
193  uint64_t GetCountWithAncestors() const { return nCountWithAncestors; }
194  uint64_t GetSizeWithAncestors() const { return nSizeWithAncestors; }
195  uint64_t GetVirtualSizeWithAncestors() const;
197  int64_t GetSigChecksWithAncestors() const {
199  }
201  const Parents &GetMemPoolParentsConst() const { return m_parents; }
202  const Children &GetMemPoolChildrenConst() const { return m_children; }
203  Parents &GetMemPoolParents() const { return m_parents; }
205 };
207 // extracts a transaction id from CTxMemPoolEntry or CTransactionRef
209  typedef TxId result_type;
210  result_type operator()(const CTxMemPoolEntry &entry) const {
211  return entry.GetTx().GetId();
212  }
215  return tx->GetId();
216  }
217 };
219 // used by the entry_time index
221  bool operator()(const CTxMemPoolEntry &a, const CTxMemPoolEntry &b) const {
222  return a.GetTime() < b.GetTime();
223  }
224 };
226 // used by the entry_id index
228  bool operator()(const CTxMemPoolEntry &a, const CTxMemPoolEntry &b) const {
229  return a.GetEntryId() < b.GetEntryId();
230  }
231 };
240  bool operator()(const CTxMemPoolEntry &a, const CTxMemPoolEntry &b) const {
241  const CFeeRate frA = a.GetModifiedFeeRate();
242  const CFeeRate frB = b.GetModifiedFeeRate();
244  // Sort by modified fee rate first
245  if (frA != frB) {
246  return frA > frB;
247  }
249  // Ties are broken by whichever is topologically earlier
250  // (this helps mining code avoid some backtracking).
251  if (a.GetEntryId() != b.GetEntryId()) {
252  return a.GetEntryId() < b.GetEntryId();
253  }
255  // If nothing else, sort by txid (this should never happen as entryID is
256  // expected to be unique).
257  return a.GetSharedTx()->GetId() < b.GetSharedTx()->GetId();
258  }
259 };
261 // Multi_index tag names
262 struct entry_time {};
264 struct entry_id {};
274  std::chrono::seconds m_time;
280  size_t vsize;
284 };
292  EXPIRY,
296  REORG,
298  BLOCK,
303 };
355 class CTxMemPool {
356 private:
358  const int m_check_ratio;
360  std::atomic<uint32_t> nTransactionsUpdated{0};
363  uint64_t totalTxSize GUARDED_BY(cs);
365  Amount m_total_fee GUARDED_BY(cs);
368  uint64_t cachedInnerUsage GUARDED_BY(cs);
370  mutable int64_t lastRollingFeeUpdate GUARDED_BY(cs);
371  mutable bool blockSinceLastRollingFeeBump GUARDED_BY(cs);
373  mutable double rollingMinimumFeeRate GUARDED_BY(cs);
375  // In-memory counter for external mempool tracking purposes.
376  // This number is incremented once every time a transaction
377  // is added or removed from the mempool for any reason.
378  mutable uint64_t m_sequence_number GUARDED_BY(cs){1};
382  bool m_is_loaded GUARDED_BY(cs){false};
386  uint64_t nextEntryId GUARDED_BY(cs) = 1;
388 public:
389  // public only for testing
390  static const int ROLLING_FEE_HALFLIFE = 60 * 60 * 12;
392  typedef boost::multi_index_container<
393  CTxMemPoolEntry, boost::multi_index::indexed_by<
394  // indexed by txid
395  boost::multi_index::hashed_unique<
397  // sorted by fee rate
398  boost::multi_index::ordered_non_unique<
399  boost::multi_index::tag<modified_feerate>,
400  boost::multi_index::identity<CTxMemPoolEntry>,
402  // sorted by entry time
403  boost::multi_index::ordered_non_unique<
404  boost::multi_index::tag<entry_time>,
405  boost::multi_index::identity<CTxMemPoolEntry>,
407  // sorted topologically (insertion order)
408  boost::multi_index::ordered_unique<
409  boost::multi_index::tag<entry_id>,
410  boost::multi_index::identity<CTxMemPoolEntry>,
444  using txiter = indexed_transaction_set::nth_index<0>::type::const_iterator;
445  typedef std::set<txiter, CompareIteratorById> setEntries;
448  uint64_t CalculateDescendantMaximum(txiter entry) const
451 private:
452  void UpdateParent(txiter entry, txiter parent, bool add)
454  void UpdateChild(txiter entry, txiter child, bool add)
461  std::set<TxId> m_unbroadcast_txids GUARDED_BY(cs);
475  size_t entry_size, size_t entry_count, setEntries &setAncestors,
476  CTxMemPoolEntry::Parents &staged_ancestors, uint64_t limitAncestorCount,
477  uint64_t limitAncestorSize, uint64_t limitDescendantCount,
478  uint64_t limitDescendantSize, std::string &errString) const
481 public:
483  std::map<TxId, Amount> mapDeltas GUARDED_BY(cs);
492  std::atomic<bool> wellingtonLatched{false};
503  CTxMemPool(int check_ratio = 0);
504  ~CTxMemPool();
512  void check(const CCoinsViewCache &active_coins_tip,
513  int64_t spendheight) const EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
515  // addUnchecked must update state for all parents of a given transaction,
516  // updating child links as necessary.
517  // Pre-wellington: automatically calculates setAncestors, calls
518  // addUnchecked(entry, setAncestors)
519  // Post-wellington: identical to just calling addUnchecked(entry, {})
520  // These 2 overloads should be collapsed down into 1 post-wellington (just a
521  // single-argument version).
522  void addUnchecked(const CTxMemPoolEntry &entry)
524  void
526  const setEntries &setAncestors /* only used pre-wellington */)
529  void removeRecursive(const CTransaction &tx, MemPoolRemovalReason reason)
532  void removeForBlock(const std::vector<CTransactionRef> &vtx)
535  void clear();
536  // lock free
538  bool CompareTopologically(const TxId &txida, const TxId &txidb) const;
539  void getAllTxIds(std::vector<TxId> &vtxid) const;
540  bool isSpent(const COutPoint &outpoint) const;
541  unsigned int GetTransactionsUpdated() const;
542  void AddTransactionsUpdated(unsigned int n);
548  bool HasNoInputsOf(const CTransaction &tx) const
552  void PrioritiseTransaction(const TxId &txid, const Amount nFeeDelta);
553  void ApplyDelta(const TxId &txid, Amount &nFeeDelta) const
558  const CTransaction *GetConflictTx(const COutPoint &prevout) const
562  std::optional<txiter> GetIter(const TxId &txid) const
569  setEntries GetIterSet(const std::set<TxId> &txids) const
580  void RemoveStaged(const setEntries &stage, bool updateDescendants,
596  const CTxMemPoolEntry &entry, setEntries &setAncestors,
597  uint64_t limitAncestorCount, uint64_t limitAncestorSize,
598  uint64_t limitDescendantCount, uint64_t limitDescendantSize,
599  std::string &errString, bool fSearchForParents = true) const
622  bool CheckPackageLimits(const Package &package, uint64_t limitAncestorCount,
623  uint64_t limitAncestorSize,
624  uint64_t limitDescendantCount,
625  uint64_t limitDescendantSize,
626  std::string &errString) const
634  void CalculateDescendants(txiter it, setEntries &setDescendants) const
644  CFeeRate GetMinFee(size_t sizelimit) const;
652  void TrimToSize(size_t sizelimit,
653  std::vector<COutPoint> *pvNoSpendsRemaining = nullptr)
660  int Expire(std::chrono::seconds time) EXCLUSIVE_LOCKS_REQUIRED(cs);
665  void LimitSize(CCoinsViewCache &coins_cache, size_t limit,
666  std::chrono::seconds age)
681  void GetTransactionAncestry(const TxId &txid, size_t &ancestors,
682  size_t &descendants,
683  size_t *ancestorsize = nullptr,
684  Amount *ancestorfees = nullptr) const;
687  bool IsLoaded() const;
690  void SetIsLoaded(bool loaded);
692  unsigned long size() const {
693  LOCK(cs);
694  return mapTx.size();
695  }
699  return totalTxSize;
700  }
704  return m_total_fee;
705  }
707  bool exists(const TxId &txid) const {
708  LOCK(cs);
709  return mapTx.count(txid) != 0;
710  }
712  CTransactionRef get(const TxId &txid) const;
713  TxMempoolInfo info(const TxId &txid) const;
714  std::vector<TxMempoolInfo> infoAll() const;
716  CFeeRate estimateFee() const;
718  size_t DynamicMemoryUsage() const;
721  void AddUnbroadcastTx(const TxId &txid) {
722  LOCK(cs);
723  // Sanity check the transaction is in the mempool & insert into
724  // unbroadcast set.
725  if (exists(txid)) {
726  m_unbroadcast_txids.insert(txid);
727  }
728  }
731  void RemoveUnbroadcastTx(const TxId &txid, const bool unchecked = false);
734  std::set<TxId> GetUnbroadcastTxs() const {
735  LOCK(cs);
736  return m_unbroadcast_txids;
737  }
740  bool IsUnbroadcastTx(const TxId &txid) const EXCLUSIVE_LOCKS_REQUIRED(cs) {
742  return (m_unbroadcast_txids.count(txid) != 0);
743  }
747  return m_sequence_number++;
748  }
751  return m_sequence_number;
752  }
754 private:
756  void UpdateEntryForAncestors(txiter it, const setEntries *setAncestors)
761  void UpdateParentsOf(
762  bool add, txiter it,
763  const setEntries *setAncestors = nullptr /* only used pre-wellington */)
771  void UpdateForRemoveFromMempool(const setEntries &entriesToRemove,
772  bool updateDescendants)
785  void removeUnchecked(txiter entry, MemPoolRemovalReason reason)
787 };
808  std::unordered_map<COutPoint, Coin, SaltedOutpointHasher> m_temp_added;
810 protected:
813 public:
814  CCoinsViewMemPool(CCoinsView *baseIn, const CTxMemPool &mempoolIn);
815  bool GetCoin(const COutPoint &outpoint, Coin &coin) const override;
821  void PackageAddTransaction(const CTransactionRef &tx);
822 };
842 // multi_index tag names
843 struct txid_index {};
844 struct insertion_order {};
847 private:
848  typedef boost::multi_index_container<
849  CTransactionRef, boost::multi_index::indexed_by<
850  // hashed by txid
851  boost::multi_index::hashed_unique<
852  boost::multi_index::tag<txid_index>,
854  // sorted by order in the blockchain
855  boost::multi_index::sequenced<
856  boost::multi_index::tag<insertion_order>>>>
860  uint64_t cachedInnerUsage = 0;
862  struct TxInfo {
863  const std::chrono::seconds time;
865  const unsigned height;
866  TxInfo(const std::chrono::seconds &time_, Amount feeDelta_,
867  unsigned height_) noexcept
868  : time(time_), feeDelta(feeDelta_), height(height_) {}
869  };
871  using TxInfoMap = std::unordered_map<TxId, TxInfo, SaltedTxIdHasher>;
875  void addTransaction(const CTransactionRef &tx) {
876  queuedTx.insert(tx);
877  cachedInnerUsage += RecursiveDynamicUsage(tx);
878  }
883  const TxInfo *getTxInfo(const CTransactionRef &tx) const;
885 public:
886  // It's almost certainly a logic bug if we don't clear out queuedTx before
887  // destruction, as we add to it while disconnecting blocks, and then we
888  // need to re-process remaining transactions to ensure mempool consistency.
889  // For now, assert() that we've emptied out this object on destruction.
890  // This assert() can always be removed if the reorg-processing code were
891  // to be refactored such that this assumption is no longer true (for
892  // instance if there was some other way we cleaned up the mempool after a
893  // reorg, besides draining this object).
894  ~DisconnectedBlockTransactions() { assert(queuedTx.empty()); }
896  // Estimate the overhead of queuedTx to be 6 pointers + an allocation, as
897  // no exact formula for boost::multi_index_contained is implemented.
898  size_t DynamicMemoryUsage() const {
899  return memusage::MallocUsage(sizeof(CTransactionRef) +
900  6 * sizeof(void *)) *
901  queuedTx.size() +
902  memusage::DynamicUsage(txInfo) + cachedInnerUsage;
903  }
906  return queuedTx;
907  }
909  // Import mempool entries in topological order into queuedTx and clear the
910  // mempool. Caller should call updateMempoolForReorg to reprocess these
911  // transactions
912  void importMempool(CTxMemPool &pool) EXCLUSIVE_LOCKS_REQUIRED(pool.cs);
914  // Add entries for a block while reconstructing the topological ordering so
915  // they can be added back to the mempool simply.
916  void addForBlock(const std::vector<CTransactionRef> &vtx, CTxMemPool &pool)
919  // Remove entries based on txid_index, and update memory usage.
920  void removeForBlock(const std::vector<CTransactionRef> &vtx) {
921  // Short-circuit in the common case of a block being added to the tip
922  if (queuedTx.empty()) {
923  return;
924  }
925  for (auto const &tx : vtx) {
926  auto it = queuedTx.find(tx->GetId());
927  if (it != queuedTx.end()) {
928  cachedInnerUsage -= RecursiveDynamicUsage(*it);
929  queuedTx.erase(it);
930  txInfo.erase(tx->GetId());
931  }
932  }
933  }
935  // Remove an entry by insertion_order index, and update memory usage.
936  void removeEntry(indexed_disconnected_transactions::index<
937  insertion_order>::type::iterator entry) {
938  cachedInnerUsage -= RecursiveDynamicUsage(*entry);
939  txInfo.erase((*entry)->GetId());
940  queuedTx.get<insertion_order>().erase(entry);
941  }
943  bool isEmpty() const { return queuedTx.empty(); }
945  void clear() {
946  cachedInnerUsage = 0;
947  queuedTx.clear();
948  txInfo.clear();
949  }
964  void updateMempoolForReorg(const Config &config,
965  Chainstate &active_chainstate,
966  bool fAddToMempool, CTxMemPool &pool)
968 };
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: blockindex.h:26
An in-memory indexed chain of blocks.
Definition: chain.h:141
CCoinsView backed by another CCoinsView.
Definition: coins.h:184
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:203
Abstract view on the open txout dataset.
Definition: coins.h:147
CCoinsView that brings transactions from a mempool into view.
Definition: txmempool.h:802
std::unordered_map< COutPoint, Coin, SaltedOutpointHasher > m_temp_added
Coins made available by transactions being validated.
Definition: txmempool.h:808
const CTxMemPool & mempool
Definition: txmempool.h:811
Fee rate in satoshis per kilobyte: Amount / kB.
Definition: feerate.h:21
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:22
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:194
const TxId GetId() const
Definition: transaction.h:246
CTxMemPoolEntry stores data about the corresponding transaction, as well as data about all in-mempool...
Definition: txmempool.h:88
const CTransactionRef tx
Definition: txmempool.h:99
int64_t GetSigChecksWithDescendants() const
Definition: txmempool.h:187
std::set< CTxMemPoolEntryRef, CompareIteratorById > Parents
Definition: txmempool.h:92
uint64_t GetVirtualSizeWithDescendants() const
Definition: txmempool.cpp:110
const bool spendsCoinbase
keep track of transactions that spend a coinbase
Definition: txmempool.h:113
int64_t nSigChecksWithDescendants
... and sichecks
Definition: txmempool.h:136
const CTransaction & GetTx() const
Definition: txmempool.h:154
unsigned int GetHeight() const
Definition: txmempool.h:161
const Parents & GetMemPoolParentsConst() const
Definition: txmempool.h:201
std::chrono::seconds GetTime() const
Definition: txmempool.h:160
int64_t GetSigChecksWithAncestors() const
Definition: txmempool.h:197
uint64_t GetEntryId() const
Definition: txmempool.h:149
std::reference_wrapper< const CTxMemPoolEntry > CTxMemPoolEntryRef
Definition: txmempool.h:90
bool GetSpendsCoinbase() const
Definition: txmempool.h:191
const int64_t nTime
Local time when entering the mempool.
Definition: txmempool.h:109
const Amount nFee
Cached to avoid expensive parent-transaction lookups.
Definition: txmempool.h:103
uint64_t GetCountWithDescendants() const
Definition: txmempool.h:183
void UpdateAncestorState(int64_t modifySize, Amount modifyFee, int64_t modifyCount, int64_t modifySigChecks)
Definition: txmempool.cpp:394
const size_t nTxSize
... and avoid recomputing tx size
Definition: txmempool.h:105
const size_t nUsageSize
... and total memory usage
Definition: txmempool.h:107
Amount GetFee() const
Definition: txmempool.h:156
void UpdateLockPoints(const LockPoints &lp)
Definition: txmempool.cpp:132
uint64_t GetVirtualSizeWithAncestors() const
Definition: txmempool.cpp:118
Amount nModFeesWithAncestors
Definition: txmempool.h:141
const LockPoints & GetLockPoints() const
Definition: txmempool.h:168
int64_t GetSigChecks() const
Definition: txmempool.h:162
void UpdateFeeDelta(Amount feeDelta)
Definition: txmempool.cpp:125
void SetEntryId(uint64_t eid)
This should only be set by addUnchecked() before entry insertion into mempool.
Definition: txmempool.h:152
int64_t nSigChecksWithAncestors
Definition: txmempool.h:142
Parents m_parents
Definition: txmempool.h:100
uint64_t nCountWithDescendants
number of descendant transactions
Definition: txmempool.h:130
size_t GetTxSize() const
Definition: txmempool.h:157
Amount feeDelta
Used for determining the priority of the transaction for mining in a block.
Definition: txmempool.h:118
CTxMemPoolEntry(const CTransactionRef &_tx, const Amount fee, int64_t time, unsigned int entry_height, bool spends_coinbase, int64_t sigchecks, LockPoints lp)
Definition: txmempool.cpp:93
Amount nModFeesWithDescendants
... and total fees (all including us)
Definition: txmempool.h:134
uint64_t GetSizeWithAncestors() const
Definition: txmempool.h:194
CTransactionRef GetSharedTx() const
Definition: txmempool.h:155
Amount GetModifiedFee() const
Definition: txmempool.h:163
uint64_t nSizeWithDescendants
... and size
Definition: txmempool.h:132
CFeeRate GetModifiedFeeRate() const
Definition: txmempool.h:164
Amount GetModFeesWithDescendants() const
Definition: txmempool.h:186
size_t DynamicMemoryUsage() const
Definition: txmempool.h:167
uint64_t nCountWithAncestors
Definition: txmempool.h:139
size_t GetTxVirtualSize() const
Definition: txmempool.cpp:105
void UpdateDescendantState(int64_t modifySize, Amount modifyFee, int64_t modifyCount, int64_t modifySigChecks)
Definition: txmempool.cpp:381
uint64_t entryId
Unique identifier – used for topological sorting.
Definition: txmempool.h:97
Parents & GetMemPoolParents() const
Definition: txmempool.h:203
uint64_t GetSizeWithDescendants() const
Definition: txmempool.h:184
uint64_t GetCountWithAncestors() const
Definition: txmempool.h:193
LockPoints lockPoints
Track the height and time at which tx was final.
Definition: txmempool.h:120
uint64_t nSizeWithAncestors
Definition: txmempool.h:140
Children m_children
Definition: txmempool.h:101
std::set< CTxMemPoolEntryRef, CompareIteratorById > Children
Definition: txmempool.h:93
Amount GetModFeesWithAncestors() const
Definition: txmempool.h:196
const Children & GetMemPoolChildrenConst() const
Definition: txmempool.h:202
const unsigned int entryHeight
Chain height when entering the mempool.
Definition: txmempool.h:111
Children & GetMemPoolChildren() const
Definition: txmempool.h:204
const int64_t sigChecks
Total sigChecks.
Definition: txmempool.h:115
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:355
void removeConflicts(const CTransaction &tx) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:570
CFeeRate estimateFee() const
Definition: txmempool.cpp:854
uint64_t nextEntryId GUARDED_BY(cs)
Used by addUnchecked to generate ever-increasing CTxMemPoolEntry::entryId's.
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:944
void ClearPrioritisation(const TxId &txid) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:914
std::set< txiter, CompareIteratorById > setEntries
Definition: txmempool.h:445
void RemoveUnbroadcastTx(const TxId &txid, const bool unchecked=false)
Removes a transaction from the unbroadcast set.
Definition: txmempool.cpp:999
void UpdateParentsOf(bool add, txiter it, const setEntries *setAncestors=nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs)
Update parents of it to add/remove it as a child transaction.
Definition: txmempool.cpp:272
uint64_t cachedInnerUsage GUARDED_BY(cs)
sum of dynamic memory usage of all the map elements (NOT the maps themselves)
Amount m_total_fee GUARDED_BY(cs)
sum of all mempool tx's fees (NOT modified fee)
void UpdateEntryForAncestors(txiter it, const setEntries *setAncestors) EXCLUSIVE_LOCKS_REQUIRED(cs)
Set ancestor state for an entry.
Definition: txmempool.cpp:293
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it.
Definition: txmempool.h:441
void trackPackageRemoved(const CFeeRate &rate) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:1108
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:1085
Amount GetTotalFee() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.h:702
void removeRecursive(const CTransaction &tx, MemPoolRemovalReason reason) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:539
bool blockSinceLastRollingFeeBump GUARDED_BY(cs)
const int m_check_ratio
Value n means that 1 times in n we check.
Definition: txmempool.h:358
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:1116
void AddTransactionsUpdated(unsigned int n)
Definition: txmempool.cpp:422
void UpdateChildrenForRemoval(txiter entry) EXCLUSIVE_LOCKS_REQUIRED(cs)
Sever link between specified transaction and direct children.
Definition: txmempool.cpp:313
bool CompareTopologically(const TxId &txida, const TxId &txidb) const
Definition: txmempool.cpp:789
TxMempoolInfo info(const TxId &txid) const
Definition: txmempool.cpp:844
void getAllTxIds(std::vector< TxId > &vtxid) const
Definition: txmempool.cpp:803
std::atomic< uint32_t > nTransactionsUpdated
Used by getblocktemplate to trigger CreateNewBlock() invocation.
Definition: txmempool.h:360
setEntries GetIterSet(const std::set< TxId > &txids) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Translate a set of txids into a set of pool iterators to avoid repeated lookups.
Definition: txmempool.cpp:933
boost::multi_index_container< CTxMemPoolEntry, boost::multi_index::indexed_by< boost::multi_index::hashed_unique< mempoolentry_txid, SaltedTxIdHasher >, boost::multi_index::ordered_non_unique< boost::multi_index::tag< modified_feerate >, boost::multi_index::identity< CTxMemPoolEntry >, CompareTxMemPoolEntryByModifiedFeeRate >, boost::multi_index::ordered_non_unique< boost::multi_index::tag< entry_time >, boost::multi_index::identity< CTxMemPoolEntry >, CompareTxMemPoolEntryByEntryTime >, boost::multi_index::ordered_unique< boost::multi_index::tag< entry_id >, boost::multi_index::identity< CTxMemPoolEntry >, CompareTxMemPoolEntryByEntryId > > > indexed_transaction_set
Definition: txmempool.h:412
size_t DynamicMemoryUsage() const
Definition: txmempool.cpp:988
std::vector< TxMempoolInfo > infoAll() const
Definition: txmempool.cpp:820
indexed_transaction_set mapTx GUARDED_BY(cs)
void SetIsLoaded(bool loaded)
Sets the current loaded state.
Definition: txmempool.cpp:1211
void UpdateParent(txiter entry, txiter parent, bool add) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:1075
indirectmap< COutPoint, const CTransaction * > mapNextTx GUARDED_BY(cs)
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:478
uint64_t totalTxSize GUARDED_BY(cs)
sum of all mempool tx's sizes.
void removeForBlock(const std::vector< CTransactionRef > &vtx) EXCLUSIVE_LOCKS_REQUIRED(cs)
Called when a block is connected.
Definition: txmempool.cpp:589
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:1019
void clear()
Definition: txmempool.cpp:636
bool exists(const TxId &txid) const
Definition: txmempool.h:707
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:195
std::map< TxId, Amount > mapDeltas GUARDED_BY(cs)
int64_t lastRollingFeeUpdate GUARDED_BY(cs)
CTxMemPool(int check_ratio=0)
Create a new CTxMemPool.
Definition: txmempool.cpp:406
void LimitSize(CCoinsViewCache &coins_cache, size_t limit, std::chrono::seconds age) EXCLUSIVE_LOCKS_REQUIRED(cs
Reduce the size of the mempool by expiring and then trimming the mempool.
Definition: txmempool.cpp:1038
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:235
static const int ROLLING_FEE_HALFLIFE
Definition: txmempool.h:390
void GetTransactionAncestry(const TxId &txid, size_t &ancestors, size_t &descendants, size_t *ancestorsize=nullptr, Amount *ancestorfees=nullptr) const
Calculate the ancestor and descendant count for the given transaction.
Definition: txmempool.cpp:1187
CTransactionRef get(const TxId &txid) const
Definition: txmempool.cpp:834
void PrioritiseTransaction(const TxId &txid, const Amount nFeeDelta)
Affect CreateNewBlock prioritisation of transactions.
Definition: txmempool.cpp:866
std::set< TxId > m_unbroadcast_txids GUARDED_BY(cs)
Track locally submitted transactions to periodically retry initial broadcast.
uint64_t GetSequence() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.h:750
bool IsUnbroadcastTx(const TxId &txid) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Returns whether a txid is in the unbroadcast set.
Definition: txmempool.h:740
indexed_transaction_set::nth_index< 0 >::type::const_iterator txiter
Definition: txmempool.h:444
uint64_t GetAndIncrementSequence() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Guards this internal counter for external reporting.
Definition: txmempool.h:746
void UpdateChild(txiter entry, txiter child, bool add) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:1065
bool IsLoaded() const
Definition: txmempool.cpp:1206
double rollingMinimumFeeRate GUARDED_BY(cs)
minimum fee to get into the pool, decreases exponentially
std::atomic< bool > wellingtonLatched
Wellington activation latch.
Definition: txmempool.h:492
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:919
std::set< TxId > GetUnbroadcastTxs() const
Returns transactions in unbroadcast set.
Definition: txmempool.h:734
void RemoveStaged(const setEntries &stage, bool updateDescendants, MemPoolRemovalReason reason) EXCLUSIVE_LOCKS_REQUIRED(cs)
Remove a set of transactions from the mempool.
Definition: txmempool.cpp:1010
void CalculateDescendants(txiter it, setEntries &setDescendants) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Populate setDescendants with all in-mempool descendants of hash.
Definition: txmempool.cpp:514
unsigned long size() const
Definition: txmempool.h:692
bool m_is_loaded GUARDED_BY(cs)
Definition: txmempool.h:382
uint64_t m_sequence_number GUARDED_BY(cs)
Definition: txmempool.h:378
void ApplyDelta(const TxId &txid, Amount &nFeeDelta) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:904
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:320
std::optional< txiter > GetIter(const TxId &txid) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Returns an iterator to the given txid, if found.
Definition: txmempool.cpp:924
void check(const CCoinsViewCache &active_coins_tip, int64_t spendheight) const EXCLUSIVE_LOCKS_REQUIRED(void cs_main
Definition: txmempool.h:523
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:136
uint64_t CalculateDescendantMaximum(txiter entry) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Remove after wellington activates as this will be inaccurate.
Definition: txmempool.cpp:1162
uint64_t GetTotalTxSize() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.h:697
bool isSpent(const COutPoint &outpoint) const
Definition: txmempool.cpp:413
void AddUnbroadcastTx(const TxId &txid)
Adds a transaction to the unbroadcast set.
Definition: txmempool.h:721
unsigned int GetTransactionsUpdated() const
Definition: txmempool.cpp:418
void check(const CCoinsViewCache &active_coins_tip, int64_t spendheight) const EXCLUSIVE_LOCKS_REQUIRED(void addUnchecked(const CTxMemPoolEntry &entry) 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:522
Definition: txmempool.cpp:624
Chainstate stores and provides an API to update our local knowledge of the current best chain.
Definition: validation.h:646
A UTXO entry.
Definition: coins.h:27
Definition: config.h:17
std::unordered_map< TxId, TxInfo, SaltedTxIdHasher > TxInfoMap
Definition: txmempool.h:871
void removeEntry(indexed_disconnected_transactions::index< insertion_order >::type::iterator entry)
Definition: txmempool.h:936
indexed_disconnected_transactions queuedTx
Definition: txmempool.h:859
TxInfoMap txInfo
populated by importMempool(); the original tx entry times and feeDeltas
Definition: txmempool.h:873
void removeForBlock(const std::vector< CTransactionRef > &vtx)
Definition: txmempool.h:920
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:857
size_t DynamicMemoryUsage() const
Definition: txmempool.h:898
void addTransaction(const CTransactionRef &tx)
Definition: txmempool.h:875
const indexed_disconnected_transactions & GetQueuedTx() const
Definition: txmempool.h:905
Map whose keys are pointers, but are compared by their dereferenced values.
Definition: indirectmap.h:26
static size_t RecursiveDynamicUsage(const CScript &script)
Definition: core_memusage.h:12
LockPoints lp
static size_t DynamicUsage(const int8_t &v)
Dynamic memory usage for built-in types is zero.
Definition: memusage.h:26
static size_t MallocUsage(size_t alloc)
Compute the total memory used by allocating alloc bytes.
Definition: memusage.h:72
std::vector< CTransactionRef > Package
A package is an ordered list of transactions.
Definition: packages.h:38
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:321
Definition: amount.h:19
static constexpr Amount zero()
Definition: amount.h:32
bool operator()(const std::reference_wrapper< T > &a, const std::reference_wrapper< T > &b) const
Definition: txmempool.h:68
bool operator()(const T &a, const T &b) const
Definition: txmempool.h:72
Definition: txmempool.h:227
bool operator()(const CTxMemPoolEntry &a, const CTxMemPoolEntry &b) const
Definition: txmempool.h:228
Definition: txmempool.h:220
bool operator()(const CTxMemPoolEntry &a, const CTxMemPoolEntry &b) const
Definition: txmempool.h:221
Sort by feerate of entry (modfee/vsize) in descending order.
Definition: txmempool.h:239
bool operator()(const CTxMemPoolEntry &a, const CTxMemPoolEntry &b) const
Definition: txmempool.h:240
TxInfo(const std::chrono::seconds &time_, Amount feeDelta_, unsigned height_) noexcept
Definition: txmempool.h:866
const std::chrono::seconds time
Definition: txmempool.h:863
CBlockIndex * maxInputBlock
Definition: txmempool.h:54
int height
Definition: txmempool.h:49
int64_t time
Definition: txmempool.h:50
A TxId is the identifier of a transaction.
Definition: txid.h:14
Information about a mempool transaction.
Definition: txmempool.h:269
Amount fee
Fee of the transaction.
Definition: txmempool.h:277
Amount nFeeDelta
The fee delta.
Definition: txmempool.h:283
CTransactionRef tx
The transaction itself.
Definition: txmempool.h:271
std::chrono::seconds m_time
Time the transaction entered the mempool.
Definition: txmempool.h:274
size_t vsize
Virtual size of the transaction.
Definition: txmempool.h:280
result_type operator()(const CTxMemPoolEntry &entry) const
Definition: txmempool.h:210
result_type operator()(const CTransactionRef &tx) const
Definition: txmempool.h:214
Definition: txmempool.h:843
#define LOCK(cs)
Definition: sync.h:243
Definition: threadsafety.h:56
Reason why a transaction was removed from the mempool, this is passed to the notification signal.
Definition: txmempool.h:290
Removed in size limiting.
Removed for block.
Expired from mempool.
Removed for replacement.
Removed for conflict with in-block transaction.
Removed for reorganization.
static const uint32_t MEMPOOL_HEIGHT
Fake height value used in Coins to signify they are only in the memory pool(since 0....
Definition: txmempool.h:43
RecursiveMutex cs_main
Global state.
Definition: validation.cpp:113
bool TestLockPointValidity(const 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:75