Bitcoin ABC  0.26.2
P2P Digital Currency
txmempool.h
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 http://www.opensource.org/licenses/mit-license.php.
5 
6 #ifndef BITCOIN_TXMEMPOOL_H
7 #define BITCOIN_TXMEMPOOL_H
8 
9 #include <amount.h>
10 #include <coins.h>
11 #include <core_memusage.h>
12 #include <indirectmap.h>
13 #include <primitives/transaction.h>
14 #include <salteduint256hasher.h>
15 #include <sync.h>
16 #include <util/epochguard.h>
17 
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>
22 
23 #include <atomic>
24 #include <map>
25 #include <optional>
26 #include <set>
27 #include <string>
28 #include <utility>
29 #include <vector>
30 
31 class CBlockIndex;
32 class CChainState;
33 class Config;
34 
35 extern RecursiveMutex cs_main;
36 
41 static const uint32_t MEMPOOL_HEIGHT = 0x7FFFFFFF;
42 
43 struct LockPoints {
44  // Will be set to the blockchain height and median time past values that
45  // would be necessary to satisfy all relative locktime constraints (BIP68)
46  // of this tx given our view of block chain history
47  int height;
48  int64_t time;
49  // As long as the current chain descends from the highest height block
50  // containing one of the inputs used in the calculation, then the cached
51  // values are still valid even after a reorg.
53 
54  LockPoints() : height(0), time(0), maxInputBlock(nullptr) {}
55 };
56 
58  // SFINAE for T where T is either a pointer type (e.g., a txiter) or a
59  // reference_wrapper<T> (e.g. a wrapped CTxMemPoolEntry&)
60  template <typename T>
61  bool operator()(const std::reference_wrapper<T> &a,
62  const std::reference_wrapper<T> &b) const {
63  return a.get().GetTx().GetId() < b.get().GetTx().GetId();
64  }
65  template <typename T> bool operator()(const T &a, const T &b) const {
66  return a->GetTx().GetId() < b->GetTx().GetId();
67  }
68 };
69 
82 public:
83  typedef std::reference_wrapper<const CTxMemPoolEntry> CTxMemPoolEntryRef;
84  // two aliases, should the types ever diverge
85  typedef std::set<CTxMemPoolEntryRef, CompareIteratorById> Parents;
86  typedef std::set<CTxMemPoolEntryRef, CompareIteratorById> Children;
87 
88 private:
90  mutable Parents m_parents;
93  const Amount nFee;
95  const size_t nTxSize;
97  const size_t nUsageSize;
99  const int64_t nTime;
101  const unsigned int entryHeight;
103  const bool spendsCoinbase;
110  const int64_t sigOpCount;
116 
117  // Information about descendants of this transaction that are in the
118  // mempool; if we remove this transaction we must remove all of these
119  // descendants as well.
128 
129  // Analogous statistics for ancestor transactions
134 
135 public:
136  CTxMemPoolEntry(const CTransactionRef &_tx, const Amount _nFee,
137  int64_t _nTime, unsigned int _entryHeight,
138  bool spendsCoinbase, int64_t _nSigOpCount, LockPoints lp);
139 
140  const CTransaction &GetTx() const { return *this->tx; }
141  CTransactionRef GetSharedTx() const { return this->tx; }
142  const Amount GetFee() const { return nFee; }
143  size_t GetTxSize() const { return nTxSize; }
144  size_t GetTxVirtualSize() const;
145 
146  std::chrono::seconds GetTime() const { return std::chrono::seconds{nTime}; }
147  unsigned int GetHeight() const { return entryHeight; }
148  int64_t GetSigOpCount() const { return sigOpCount; }
149  Amount GetModifiedFee() const { return nFee + feeDelta; }
150  size_t DynamicMemoryUsage() const { return nUsageSize; }
151  const LockPoints &GetLockPoints() const { return lockPoints; }
152 
153  // Adjusts the descendant state.
154  void UpdateDescendantState(int64_t modifySize, Amount modifyFee,
155  int64_t modifyCount, int64_t modifySigOpCount);
156  // Adjusts the ancestor state
157  void UpdateAncestorState(int64_t modifySize, Amount modifyFee,
158  int64_t modifyCount, int64_t modifySigOps);
159  // Updates the fee delta used for mining priority score, and the
160  // modified fees with descendants.
162  // Update the LockPoints after a reorg
163  void UpdateLockPoints(const LockPoints &lp);
164 
165  uint64_t GetCountWithDescendants() const { return nCountWithDescendants; }
166  uint64_t GetSizeWithDescendants() const { return nSizeWithDescendants; }
167  uint64_t GetVirtualSizeWithDescendants() const;
171  }
172 
173  bool GetSpendsCoinbase() const { return spendsCoinbase; }
174 
175  uint64_t GetCountWithAncestors() const { return nCountWithAncestors; }
176  uint64_t GetSizeWithAncestors() const { return nSizeWithAncestors; }
177  uint64_t GetVirtualSizeWithAncestors() const;
179  int64_t GetSigOpCountWithAncestors() const {
181  }
182 
183  const Parents &GetMemPoolParentsConst() const { return m_parents; }
184  const Children &GetMemPoolChildrenConst() const { return m_children; }
185  Parents &GetMemPoolParents() const { return m_parents; }
187 
189  mutable size_t vTxHashesIdx;
192 };
193 
194 // Helpers for modifying CTxMemPool::mapTx, which is a boost multi_index.
196  update_descendant_state(int64_t _modifySize, Amount _modifyFee,
197  int64_t _modifyCount, int64_t _modifySigOpCount)
198  : modifySize(_modifySize), modifyFee(_modifyFee),
199  modifyCount(_modifyCount), modifySigOpCount(_modifySigOpCount) {}
200 
204  }
205 
206 private:
207  int64_t modifySize;
209  int64_t modifyCount;
211 };
212 
214  update_ancestor_state(int64_t _modifySize, Amount _modifyFee,
215  int64_t _modifyCount, int64_t _modifySigOpCount)
216  : modifySize(_modifySize), modifyFee(_modifyFee),
217  modifyCount(_modifyCount), modifySigOpCount(_modifySigOpCount) {}
218 
222  }
223 
224 private:
225  int64_t modifySize;
227  int64_t modifyCount;
229 };
230 
232  explicit update_fee_delta(Amount _feeDelta) : feeDelta(_feeDelta) {}
233 
235 
236 private:
238 };
239 
241  explicit update_lock_points(const LockPoints &_lp) : lp(_lp) {}
242 
244 
245 private:
246  const LockPoints &lp;
247 };
248 
249 // extracts a transaction id from CTxMemPoolEntry or CTransactionRef
251  typedef TxId result_type;
252  result_type operator()(const CTxMemPoolEntry &entry) const {
253  return entry.GetTx().GetId();
254  }
255 
257  return tx->GetId();
258  }
259 };
260 
267 public:
268  bool operator()(const CTxMemPoolEntry &a, const CTxMemPoolEntry &b) const {
269  double a_mod_fee, a_size, b_mod_fee, b_size;
270 
271  GetModFeeAndSize(a, a_mod_fee, a_size);
272  GetModFeeAndSize(b, b_mod_fee, b_size);
273 
274  // Avoid division by rewriting (a/b > c/d) as (a*d > c*b).
275  double f1 = a_mod_fee * b_size;
276  double f2 = a_size * b_mod_fee;
277 
278  if (f1 == f2) {
279  return a.GetTime() >= b.GetTime();
280  }
281  return f1 < f2;
282  }
283 
284  // Return the fee/size we're using for sorting this entry.
285  void GetModFeeAndSize(const CTxMemPoolEntry &a, double &mod_fee,
286  double &size) const {
287  // Compare feerate with descendants to feerate of the transaction, and
288  // return the fee/size for the max.
289  double f1 =
291  double f2 =
293 
294  if (f2 > f1) {
295  mod_fee = a.GetModFeesWithDescendants() / SATOSHI;
297  } else {
298  mod_fee = a.GetModifiedFee() / SATOSHI;
299  size = a.GetTxVirtualSize();
300  }
301  }
302 };
303 
312 public:
313  bool operator()(const CTxMemPoolEntry &a, const CTxMemPoolEntry &b) const {
314  double f1 = b.GetTxSize() * (a.GetFee() / SATOSHI);
315  double f2 = a.GetTxSize() * (b.GetFee() / SATOSHI);
316  if (f1 == f2) {
317  return b.GetTx().GetId() < a.GetTx().GetId();
318  }
319  return f1 > f2;
320  }
321 };
322 
324 public:
325  bool operator()(const CTxMemPoolEntry &a, const CTxMemPoolEntry &b) const {
326  return a.GetTime() < b.GetTime();
327  }
328 };
329 
336 public:
337  template <typename T> bool operator()(const T &a, const T &b) const {
338  double a_mod_fee, a_size, b_mod_fee, b_size;
339 
340  GetModFeeAndSize(a, a_mod_fee, a_size);
341  GetModFeeAndSize(b, b_mod_fee, b_size);
342 
343  // Avoid division by rewriting (a/b > c/d) as (a*d > c*b).
344  double f1 = a_mod_fee * b_size;
345  double f2 = a_size * b_mod_fee;
346 
347  if (f1 == f2) {
348  return a.GetTx().GetId() < b.GetTx().GetId();
349  }
350  return f1 > f2;
351  }
352 
353  // Return the fee/size we're using for sorting this entry.
354  template <typename T>
355  void GetModFeeAndSize(const T &a, double &mod_fee, double &size) const {
356  // Compare feerate with ancestors to feerate of the transaction, and
357  // return the fee/size for the min.
358  double f1 =
359  a.GetVirtualSizeWithAncestors() * (a.GetModifiedFee() / SATOSHI);
360  double f2 =
361  a.GetTxVirtualSize() * (a.GetModFeesWithAncestors() / SATOSHI);
362 
363  if (f1 > f2) {
364  mod_fee = a.GetModFeesWithAncestors() / SATOSHI;
365  size = a.GetVirtualSizeWithAncestors();
366  } else {
367  mod_fee = a.GetModifiedFee() / SATOSHI;
368  size = a.GetTxVirtualSize();
369  }
370  }
371 };
372 
373 // Multi_index tag names
375 struct entry_time {};
376 struct ancestor_score {};
377 
384 
386  std::chrono::seconds m_time;
387 
390 
392  size_t vsize;
393 
396 };
397 
404  EXPIRY,
406  SIZELIMIT,
408  REORG,
410  BLOCK,
412  CONFLICT,
414  REPLACED
415 };
416 
418 public:
420 
421  size_t operator()(const TxId &txid) const { return hash(txid); }
422 };
423 
497 class CTxMemPool {
498 private:
500  const int m_check_ratio;
502  std::atomic<uint32_t> nTransactionsUpdated{0};
503 
505  uint64_t totalTxSize;
509 
510  mutable int64_t lastRollingFeeUpdate GUARDED_BY(cs);
511  mutable bool blockSinceLastRollingFeeBump GUARDED_BY(cs);
513  mutable double rollingMinimumFeeRate GUARDED_BY(cs);
515 
516  // In-memory counter for external mempool tracking purposes.
517  // This number is incremented once every time a transaction
518  // is added or removed from the mempool for any reason.
519  mutable uint64_t m_sequence_number GUARDED_BY(cs){1};
520 
522 
523  bool m_is_loaded GUARDED_BY(cs){false};
524 
525 public:
526  // public only for testing
527  static const int ROLLING_FEE_HALFLIFE = 60 * 60 * 12;
528 
529  typedef boost::multi_index_container<
530  CTxMemPoolEntry, boost::multi_index::indexed_by<
531  // sorted by txid
532  boost::multi_index::hashed_unique<
534  // sorted by fee rate
535  boost::multi_index::ordered_non_unique<
536  boost::multi_index::tag<descendant_score>,
537  boost::multi_index::identity<CTxMemPoolEntry>,
539  // sorted by entry time
540  boost::multi_index::ordered_non_unique<
541  boost::multi_index::tag<entry_time>,
542  boost::multi_index::identity<CTxMemPoolEntry>,
544  // sorted by fee rate with ancestors
545  boost::multi_index::ordered_non_unique<
546  boost::multi_index::tag<ancestor_score>,
547  boost::multi_index::identity<CTxMemPoolEntry>,
550 
580 
581  using txiter = indexed_transaction_set::nth_index<0>::type::const_iterator;
583  std::vector<std::pair<TxHash, txiter>> vTxHashes GUARDED_BY(cs);
584 
585  typedef std::set<txiter, CompareIteratorById> setEntries;
586 
587  uint64_t CalculateDescendantMaximum(txiter entry) const
589 
590 private:
591  typedef std::map<txiter, setEntries, CompareIteratorById> cacheMap;
592 
593  void UpdateParent(txiter entry, txiter parent, bool add)
595  void UpdateChild(txiter entry, txiter child, bool add)
597 
598  std::vector<indexed_transaction_set::const_iterator>
600 
605  std::set<TxId> m_unbroadcast_txids GUARDED_BY(cs);
606 
607 public:
609  std::map<TxId, Amount> mapDeltas GUARDED_BY(cs);
610 
620  CTxMemPool(int check_ratio = 0);
621  ~CTxMemPool();
622 
629  void check(CChainState &active_chainstate) const
631 
632  // addUnchecked must updated state for all ancestors of a given transaction,
633  // to track size/count of descendant transactions. First version of
634  // addUnchecked can be used to have it call CalculateMemPoolAncestors(), and
635  // then invoke the second version.
636  // Note that addUnchecked is ONLY called from ATMP outside of tests
637  // and any other callers may break wallet's in-mempool tracking (due to
638  // lack of CValidationInterface::TransactionAddedToMempool callbacks).
639  void addUnchecked(const CTxMemPoolEntry &entry)
641  void addUnchecked(const CTxMemPoolEntry &entry, setEntries &setAncestors)
643 
644  void removeRecursive(const CTransaction &tx, MemPoolRemovalReason reason)
646  void removeForReorg(const Config &config, CChainState &active_chainstate,
649  void removeForBlock(const std::vector<CTransactionRef> &vtx,
650  unsigned int nBlockHeight) EXCLUSIVE_LOCKS_REQUIRED(cs);
651 
652  void clear();
653  // lock free
655  bool CompareDepthAndScore(const TxId &txida, const TxId &txidb);
656  void queryHashes(std::vector<uint256> &vtxid) const;
657  bool isSpent(const COutPoint &outpoint) const;
658  unsigned int GetTransactionsUpdated() const;
659  void AddTransactionsUpdated(unsigned int n);
665  bool HasNoInputsOf(const CTransaction &tx) const
667 
669  void PrioritiseTransaction(const TxId &txid, const Amount nFeeDelta);
670  void ApplyDelta(const TxId &txid, Amount &nFeeDelta) const
673 
675  const CTransaction *GetConflictTx(const COutPoint &prevout) const
677 
679  std::optional<txiter> GetIter(const TxId &txid) const
681 
686  setEntries GetIterSet(const std::set<TxId> &txids) const
688 
696  void RemoveStaged(setEntries &stage, bool updateDescendants,
698 
710  void UpdateTransactionsFromBlock(const std::vector<TxId> &txidsToUpdate)
712 
726  const CTxMemPoolEntry &entry, setEntries &setAncestors,
727  uint64_t limitAncestorCount, uint64_t limitAncestorSize,
728  uint64_t limitDescendantCount, uint64_t limitDescendantSize,
729  std::string &errString, bool fSearchForParents = true) const
731 
737  void CalculateDescendants(txiter it, setEntries &setDescendants) const
739 
747  CFeeRate GetMinFee(size_t sizelimit) const;
748 
755  void TrimToSize(size_t sizelimit,
756  std::vector<COutPoint> *pvNoSpendsRemaining = nullptr)
758 
763  int Expire(std::chrono::seconds time) EXCLUSIVE_LOCKS_REQUIRED(cs);
764 
768  void LimitSize(CCoinsViewCache &coins_cache, size_t limit,
769  std::chrono::seconds age)
771 
776  void GetTransactionAncestry(const TxId &txid, size_t &ancestors,
777  size_t &descendants) const;
778 
780  bool IsLoaded() const;
781 
783  void SetIsLoaded(bool loaded);
784 
785  unsigned long size() const {
786  LOCK(cs);
787  return mapTx.size();
788  }
789 
792  return totalTxSize;
793  }
794 
795  bool exists(const TxId &txid) const {
796  LOCK(cs);
797  return mapTx.count(txid) != 0;
798  }
799 
800  CTransactionRef get(const TxId &txid) const;
801  TxMempoolInfo info(const TxId &txid) const;
802  std::vector<TxMempoolInfo> infoAll() const;
803 
804  CFeeRate estimateFee() const;
805 
806  size_t DynamicMemoryUsage() const;
807 
809  void AddUnbroadcastTx(const TxId &txid) {
810  LOCK(cs);
811  // Sanity check the transaction is in the mempool & insert into
812  // unbroadcast set.
813  if (exists(txid)) {
814  m_unbroadcast_txids.insert(txid);
815  }
816  }
817 
819  void RemoveUnbroadcastTx(const TxId &txid, const bool unchecked = false);
820 
822  std::set<TxId> GetUnbroadcastTxs() const {
823  LOCK(cs);
824  return m_unbroadcast_txids;
825  }
826 
828  bool IsUnbroadcastTx(const TxId &txid) const EXCLUSIVE_LOCKS_REQUIRED(cs) {
830  return (m_unbroadcast_txids.count(txid) != 0);
831  }
832 
835  return m_sequence_number++;
836  }
837 
839  return m_sequence_number;
840  }
841 
842 private:
856  void UpdateForDescendants(txiter updateIt, cacheMap &cachedDescendants,
857  const std::set<TxId> &setExclude)
862  void UpdateAncestorsOf(bool add, txiter hash, setEntries &setAncestors)
865  void UpdateEntryForAncestors(txiter it, const setEntries &setAncestors)
872  void UpdateForRemoveFromMempool(const setEntries &entriesToRemove,
873  bool updateDescendants)
877 
886  void removeUnchecked(txiter entry, MemPoolRemovalReason reason)
888 
889 public:
900  return m_epoch.visited(it->m_epoch_marker);
901  }
902 
903  bool visited(std::optional<txiter> it) const
905  // verify guard even when it==nullopt
906  assert(m_epoch.guarded());
907  return !it || visited(*it);
908  }
909 };
910 
924 protected:
926 
927 public:
928  CCoinsViewMemPool(CCoinsView *baseIn, const CTxMemPool &mempoolIn);
929  bool GetCoin(const COutPoint &outpoint, Coin &coin) const override;
930 };
931 
950 // multi_index tag names
951 struct txid_index {};
952 struct insertion_order {};
953 
955 private:
956  typedef boost::multi_index_container<
957  CTransactionRef, boost::multi_index::indexed_by<
958  // sorted by txid
959  boost::multi_index::hashed_unique<
960  boost::multi_index::tag<txid_index>,
962  // sorted by order in the blockchain
963  boost::multi_index::sequenced<
964  boost::multi_index::tag<insertion_order>>>>
966 
968  uint64_t cachedInnerUsage = 0;
969 
970  void addTransaction(const CTransactionRef &tx) {
971  queuedTx.insert(tx);
973  }
974 
975 public:
976  // It's almost certainly a logic bug if we don't clear out queuedTx before
977  // destruction, as we add to it while disconnecting blocks, and then we
978  // need to re-process remaining transactions to ensure mempool consistency.
979  // For now, assert() that we've emptied out this object on destruction.
980  // This assert() can always be removed if the reorg-processing code were
981  // to be refactored such that this assumption is no longer true (for
982  // instance if there was some other way we cleaned up the mempool after a
983  // reorg, besides draining this object).
985 
986  // Estimate the overhead of queuedTx to be 6 pointers + an allocation, as
987  // no exact formula for boost::multi_index_contained is implemented.
988  size_t DynamicMemoryUsage() const {
989  return memusage::MallocUsage(sizeof(CTransactionRef) +
990  6 * sizeof(void *)) *
991  queuedTx.size() +
993  }
994 
996  return queuedTx;
997  }
998 
999  // Import mempool entries in topological order into queuedTx and clear the
1000  // mempool. Caller should call updateMempoolForReorg to reprocess these
1001  // transactions
1002  void importMempool(CTxMemPool &pool) EXCLUSIVE_LOCKS_REQUIRED(pool.cs);
1003 
1004  // Add entries for a block while reconstructing the topological ordering so
1005  // they can be added back to the mempool simply.
1006  void addForBlock(const std::vector<CTransactionRef> &vtx, CTxMemPool &pool)
1007  EXCLUSIVE_LOCKS_REQUIRED(pool.cs);
1008 
1009  // Remove entries based on txid_index, and update memory usage.
1010  void removeForBlock(const std::vector<CTransactionRef> &vtx) {
1011  // Short-circuit in the common case of a block being added to the tip
1012  if (queuedTx.empty()) {
1013  return;
1014  }
1015  for (auto const &tx : vtx) {
1016  auto it = queuedTx.find(tx->GetId());
1017  if (it != queuedTx.end()) {
1019  queuedTx.erase(it);
1020  }
1021  }
1022  }
1023 
1024  // Remove an entry by insertion_order index, and update memory usage.
1025  void removeEntry(indexed_disconnected_transactions::index<
1026  insertion_order>::type::iterator entry) {
1028  queuedTx.get<insertion_order>().erase(entry);
1029  }
1030 
1031  bool isEmpty() const { return queuedTx.empty(); }
1032 
1033  void clear() {
1034  cachedInnerUsage = 0;
1035  queuedTx.clear();
1036  }
1037 
1051  void updateMempoolForReorg(const Config &config,
1052  CChainState &active_chainstate,
1053  bool fAddToMempool, CTxMemPool &pool)
1055 };
1056 
1057 #endif // BITCOIN_TXMEMPOOL_H
static constexpr Amount SATOSHI
Definition: amount.h:153
int flags
Definition: bitcoin-tx.cpp:533
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: blockindex.h:23
CChainState stores and provides an API to update our local knowledge of the current best chain.
Definition: validation.h:747
CCoinsView backed by another CCoinsView.
Definition: coins.h:214
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:233
Abstract view on the open txout dataset.
Definition: coins.h:177
CCoinsView that brings transactions from a mempool into view.
Definition: txmempool.h:923
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: txmempool.cpp:1061
CCoinsViewMemPool(CCoinsView *baseIn, const CTxMemPool &mempoolIn)
Definition: txmempool.cpp:1057
const CTxMemPool & mempool
Definition: txmempool.h:925
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:244
CTxMemPoolEntry stores data about the corresponding transaction, as well as data about all in-mempool...
Definition: txmempool.h:81
const CTransactionRef tx
Definition: txmempool.h:89
const Amount GetFee() const
Definition: txmempool.h:142
Epoch::Marker m_epoch_marker
epoch when last touched, useful for graph algorithms
Definition: txmempool.h:191
std::set< CTxMemPoolEntryRef, CompareIteratorById > Parents
Definition: txmempool.h:85
int64_t nSigOpCountWithDescendants
... and sigop count
Definition: txmempool.h:127
void UpdateAncestorState(int64_t modifySize, Amount modifyFee, int64_t modifyCount, int64_t modifySigOps)
Definition: txmempool.cpp:390
uint64_t GetVirtualSizeWithDescendants() const
Definition: txmempool.cpp:53
const bool spendsCoinbase
keep track of transactions that spend a coinbase
Definition: txmempool.h:103
void UpdateDescendantState(int64_t modifySize, Amount modifyFee, int64_t modifyCount, int64_t modifySigOpCount)
Definition: txmempool.cpp:377
const int64_t sigOpCount
Total sigop plus P2SH sigops count.
Definition: txmempool.h:110
const CTransaction & GetTx() const
Definition: txmempool.h:140
unsigned int GetHeight() const
Definition: txmempool.h:147
const Parents & GetMemPoolParentsConst() const
Definition: txmempool.h:183
std::chrono::seconds GetTime() const
Definition: txmempool.h:146
std::reference_wrapper< const CTxMemPoolEntry > CTxMemPoolEntryRef
Definition: txmempool.h:83
bool GetSpendsCoinbase() const
Definition: txmempool.h:173
const int64_t nTime
Local time when entering the mempool.
Definition: txmempool.h:99
const Amount nFee
Cached to avoid expensive parent-transaction lookups.
Definition: txmempool.h:93
uint64_t GetCountWithDescendants() const
Definition: txmempool.h:165
const size_t nTxSize
... and avoid recomputing tx size
Definition: txmempool.h:95
const size_t nUsageSize
... and total memory usage
Definition: txmempool.h:97
int64_t GetSigOpCountWithAncestors() const
Definition: txmempool.h:179
void UpdateLockPoints(const LockPoints &lp)
Definition: txmempool.cpp:73
uint64_t GetVirtualSizeWithAncestors() const
Definition: txmempool.cpp:60
Amount nModFeesWithAncestors
Definition: txmempool.h:132
const LockPoints & GetLockPoints() const
Definition: txmempool.h:151
void UpdateFeeDelta(Amount feeDelta)
Definition: txmempool.cpp:67
Parents m_parents
Definition: txmempool.h:90
uint64_t nCountWithDescendants
number of descendant transactions
Definition: txmempool.h:121
size_t GetTxSize() const
Definition: txmempool.h:143
Amount feeDelta
Used for determining the priority of the transaction for mining in a block.
Definition: txmempool.h:113
Amount nModFeesWithDescendants
... and total fees (all including us)
Definition: txmempool.h:125
uint64_t GetSizeWithAncestors() const
Definition: txmempool.h:176
int64_t nSigOpCountWithAncestors
Definition: txmempool.h:133
CTransactionRef GetSharedTx() const
Definition: txmempool.h:141
Amount GetModifiedFee() const
Definition: txmempool.h:149
uint64_t nSizeWithDescendants
... and size
Definition: txmempool.h:123
Amount GetModFeesWithDescendants() const
Definition: txmempool.h:168
size_t DynamicMemoryUsage() const
Definition: txmempool.h:150
uint64_t nCountWithAncestors
Definition: txmempool.h:130
size_t GetTxVirtualSize() const
Definition: txmempool.cpp:49
int64_t GetSigOpCountWithDescendants() const
Definition: txmempool.h:169
Parents & GetMemPoolParents() const
Definition: txmempool.h:185
uint64_t GetSizeWithDescendants() const
Definition: txmempool.h:166
uint64_t GetCountWithAncestors() const
Definition: txmempool.h:175
LockPoints lockPoints
Track the height and time at which tx was final.
Definition: txmempool.h:115
uint64_t nSizeWithAncestors
Definition: txmempool.h:131
Children m_children
Definition: txmempool.h:91
std::set< CTxMemPoolEntryRef, CompareIteratorById > Children
Definition: txmempool.h:86
Amount GetModFeesWithAncestors() const
Definition: txmempool.h:178
const Children & GetMemPoolChildrenConst() const
Definition: txmempool.h:184
int64_t GetSigOpCount() const
Definition: txmempool.h:148
CTxMemPoolEntry(const CTransactionRef &_tx, const Amount _nFee, int64_t _nTime, unsigned int _entryHeight, bool spendsCoinbase, int64_t _nSigOpCount, LockPoints lp)
Definition: txmempool.cpp:28
const unsigned int entryHeight
Chain height when entering the mempool.
Definition: txmempool.h:101
Children & GetMemPoolChildren() const
Definition: txmempool.h:186
size_t vTxHashesIdx
Index in mempool's vTxHashes.
Definition: txmempool.h:189
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:497
void removeConflicts(const CTransaction &tx) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:630
bool CompareDepthAndScore(const TxId &txida, const TxId &txidb)
Definition: txmempool.cpp:860
CFeeRate estimateFee() const
Definition: txmempool.cpp:960
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:1047
void ClearPrioritisation(const TxId &txid) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:1017
std::set< txiter, CompareIteratorById > setEntries
Definition: txmempool.h:585
void RemoveUnbroadcastTx(const TxId &txid, const bool unchecked=false)
Removes a transaction from the unbroadcast set.
Definition: txmempool.cpp:1089
void UpdateEntryForAncestors(txiter it, const setEntries &setAncestors) EXCLUSIVE_LOCKS_REQUIRED(cs)
Set ancestor state for an entry.
Definition: txmempool.cpp:290
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:578
void UpdateForDescendants(txiter updateIt, cacheMap &cachedDescendants, const std::set< TxId > &setExclude) EXCLUSIVE_LOCKS_REQUIRED(cs)
UpdateForDescendants is used by UpdateTransactionsFromBlock to update the descendants for a single tr...
Definition: txmempool.cpp:80
void trackPackageRemoved(const CFeeRate &rate) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:1195
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:1172
void removeRecursive(const CTransaction &tx, MemPoolRemovalReason reason) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:540
bool blockSinceLastRollingFeeBump GUARDED_BY(cs)
const int m_check_ratio
Value n means that 1 times in n we check.
Definition: txmempool.h:500
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:1203
return !it visited * it
Definition: txmempool.h:907
void AddTransactionsUpdated(unsigned int n)
Definition: txmempool.cpp:418
void UpdateChildrenForRemoval(txiter entry) EXCLUSIVE_LOCKS_REQUIRED(cs)
Sever link between specified transaction and direct children.
Definition: txmempool.cpp:306
std::map< txiter, setEntries, CompareIteratorById > cacheMap
Definition: txmempool.h:591
TxMempoolInfo info(const TxId &txid) const
Definition: txmempool.cpp:950
std::atomic< uint32_t > nTransactionsUpdated
Used by getblocktemplate to trigger CreateNewBlock() invocation.
Definition: txmempool.h:502
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:1036
void cs_main LOCKS_EXCLUDED(m_epoch)
size_t DynamicMemoryUsage() const
Definition: txmempool.cpp:1077
Epoch m_epoch GUARDED_BY(cs)
std::vector< TxMempoolInfo > infoAll() const
Definition: txmempool.cpp:927
indexed_transaction_set mapTx GUARDED_BY(cs)
void SetIsLoaded(bool loaded)
Sets the current loaded state.
Definition: txmempool.cpp:1297
void UpdateParent(txiter entry, txiter parent, bool add) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:1162
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:469
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:1109
void clear()
Definition: txmempool.cpp:697
bool exists(const TxId &txid) const
Definition: txmempool.h:795
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:272
void GetTransactionAncestry(const TxId &txid, size_t &ancestors, size_t &descendants) const
Calculate the ancestor and descendant count for the given transaction.
Definition: txmempool.cpp:1281
int64_t lastRollingFeeUpdate GUARDED_BY(cs)
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:1128
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:187
static const int ROLLING_FEE_HALFLIFE
Definition: txmempool.h:527
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< 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:549
std::vector< indexed_transaction_set::const_iterator > GetSortedDepthAndScore() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:895
CTransactionRef get(const TxId &txid) const
Definition: txmempool.cpp:940
void RemoveStaged(setEntries &stage, bool updateDescendants, MemPoolRemovalReason reason) EXCLUSIVE_LOCKS_REQUIRED(cs)
Remove a set of transactions from the mempool.
Definition: txmempool.cpp:1100
void removeForBlock(const std::vector< CTransactionRef > &vtx, unsigned int nBlockHeight) EXCLUSIVE_LOCKS_REQUIRED(cs)
Called when a block is connected.
Definition: txmempool.cpp:649
void queryHashes(std::vector< uint256 > &vtxid) const
Definition: txmempool.cpp:909
void PrioritiseTransaction(const TxId &txid, const Amount nFeeDelta)
Affect CreateNewBlock prioritisation of transactions.
Definition: txmempool.cpp:972
uint64_t cachedInnerUsage
sum of dynamic memory usage of all the map elements (NOT the maps themselves)
Definition: txmempool.h:508
uint64_t GetSequence() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.h:838
bool IsUnbroadcastTx(const TxId &txid) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Returns whether a txid is in the unbroadcast set.
Definition: txmempool.h:828
void removeForReorg(const Config &config, CChainState &active_chainstate, int flags) EXCLUSIVE_LOCKS_REQUIRED(cs
Definition: txmempool.cpp:573
indexed_transaction_set::nth_index< 0 >::type::const_iterator txiter
Definition: txmempool.h:581
uint64_t GetAndIncrementSequence() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Guards this internal counter for external reporting.
Definition: txmempool.h:834
void UpdateChild(txiter entry, txiter child, bool add) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:1152
bool IsLoaded() const
Definition: txmempool.cpp:1292
double rollingMinimumFeeRate GUARDED_BY(cs)
minimum fee to get into the pool, decreases exponentially
bool m_epoch
Definition: txmempool.h:899
void UpdateTransactionsFromBlock(const std::vector< TxId > &txidsToUpdate) EXCLUSIVE_LOCKS_REQUIRED(cs
When adding transactions from a disconnected block back to the mempool, new mempool entries may have ...
Definition: txmempool.cpp:137
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:1022
uint64_t totalTxSize
sum of all mempool tx's sizes.
Definition: txmempool.h:505
std::set< TxId > GetUnbroadcastTxs() const
Returns transactions in unbroadcast set.
Definition: txmempool.h:822
void CalculateDescendants(txiter it, setEntries &setDescendants) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Populate setDescendants with all in-mempool descendants of hash.
Definition: txmempool.cpp:515
unsigned long size() const
Definition: txmempool.h:785
void check(CChainState &active_chainstate) const EXCLUSIVE_LOCKS_REQUIRED(void cs_main
Definition: txmempool.h:640
bool m_is_loaded GUARDED_BY(cs)
Definition: txmempool.h:523
uint64_t m_sequence_number GUARDED_BY(cs)
Definition: txmempool.h:519
void ApplyDelta(const TxId &txid, Amount &nFeeDelta) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:1007
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:313
std::vector< std::pair< TxHash, txiter > > vTxHashes GUARDED_BY(cs)
All tx hashes/entries in mapTx, in random order.
std::optional< txiter > GetIter(const TxId &txid) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Returns an iterator to the given txid, if found.
Definition: txmempool.cpp:1027
uint64_t CalculateDescendantMaximum(txiter entry) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:1256
uint64_t GetTotalTxSize() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.h:790
bool isSpent(const COutPoint &outpoint) const
Definition: txmempool.cpp:409
void AddUnbroadcastTx(const TxId &txid)
Adds a transaction to the unbroadcast set.
Definition: txmempool.h:809
unsigned int GetTransactionsUpdated() const
Definition: txmempool.cpp:414
void check(CChainState &active_chainstate) 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:639
void _clear() EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:685
A UTXO entry.
Definition: coins.h:27
Definition: txmempool.h:335
bool operator()(const T &a, const T &b) const
Definition: txmempool.h:337
void GetModFeeAndSize(const T &a, double &mod_fee, double &size) const
Definition: txmempool.h:355
Sort an entry by max(score/size of entry's tx, score/size with all descendants).
Definition: txmempool.h:266
bool operator()(const CTxMemPoolEntry &a, const CTxMemPoolEntry &b) const
Definition: txmempool.h:268
void GetModFeeAndSize(const CTxMemPoolEntry &a, double &mod_fee, double &size) const
Definition: txmempool.h:285
Definition: txmempool.h:323
bool operator()(const CTxMemPoolEntry &a, const CTxMemPoolEntry &b) const
Definition: txmempool.h:325
Sort by feerate of entry (fee/size) in descending order This is only used for transaction relay,...
Definition: txmempool.h:311
bool operator()(const CTxMemPoolEntry &a, const CTxMemPoolEntry &b) const
Definition: txmempool.h:313
Definition: config.h:17
void removeEntry(indexed_disconnected_transactions::index< insertion_order >::type::iterator entry)
Definition: txmempool.h:1025
indexed_disconnected_transactions queuedTx
Definition: txmempool.h:967
void removeForBlock(const std::vector< CTransactionRef > &vtx)
Definition: txmempool.h:1010
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:965
size_t DynamicMemoryUsage() const
Definition: txmempool.h:988
void addTransaction(const CTransactionRef &tx)
Definition: txmempool.h:970
const indexed_disconnected_transactions & GetQueuedTx() const
Definition: txmempool.h:995
void addForBlock(const std::vector< CTransactionRef > &vtx, CTxMemPool &pool) EXCLUSIVE_LOCKS_REQUIRED(pool.cs)
Definition: txmempool.cpp:1305
void updateMempoolForReorg(const Config &config, CChainState &active_chainstate, bool fAddToMempool, CTxMemPool &pool) EXCLUSIVE_LOCKS_REQUIRED(cs_main
Make mempool consistent after a reorg, by re-adding or recursively erasing disconnected block transac...
Definition: txmempool.cpp:1400
void importMempool(CTxMemPool &pool) EXCLUSIVE_LOCKS_REQUIRED(pool.cs)
Definition: txmempool.cpp:1364
Epoch: RAII-style guard for using epoch-based graph traversal algorithms.
Definition: epochguard.h:34
size_t operator()(const TxId &txid) const
Definition: txmempool.h:421
size_t hash(const uint256 &h) const
Map whose keys are pointers, but are compared by their dereferenced values.
Definition: indirectmap.h:26
256-bit opaque blob.
Definition: uint256.h:127
static size_t RecursiveDynamicUsage(const CScript &script)
Definition: core_memusage.h:12
LockPoints lp
static size_t MallocUsage(size_t alloc)
Compute the total memory used by allocating alloc bytes.
Definition: memusage.h:72
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:319
Definition: amount.h:19
bool operator()(const std::reference_wrapper< T > &a, const std::reference_wrapper< T > &b) const
Definition: txmempool.h:61
bool operator()(const T &a, const T &b) const
Definition: txmempool.h:65
CBlockIndex * maxInputBlock
Definition: txmempool.h:52
LockPoints()
Definition: txmempool.h:54
int height
Definition: txmempool.h:47
int64_t time
Definition: txmempool.h:48
A TxId is the identifier of a transaction.
Definition: txid.h:14
Information about a mempool transaction.
Definition: txmempool.h:381
Amount fee
Fee of the transaction.
Definition: txmempool.h:389
Amount nFeeDelta
The fee delta.
Definition: txmempool.h:395
CTransactionRef tx
The transaction itself.
Definition: txmempool.h:383
std::chrono::seconds m_time
Time the transaction entered the mempool.
Definition: txmempool.h:386
size_t vsize
Virtual size of the transaction.
Definition: txmempool.h:392
result_type operator()(const CTxMemPoolEntry &entry) const
Definition: txmempool.h:252
result_type operator()(const CTransactionRef &tx) const
Definition: txmempool.h:256
DisconnectedBlockTransactions.
Definition: txmempool.h:951
void operator()(CTxMemPoolEntry &e)
Definition: txmempool.h:219
int64_t modifySigOpCount
Definition: txmempool.h:228
update_ancestor_state(int64_t _modifySize, Amount _modifyFee, int64_t _modifyCount, int64_t _modifySigOpCount)
Definition: txmempool.h:214
void operator()(CTxMemPoolEntry &e)
Definition: txmempool.h:201
update_descendant_state(int64_t _modifySize, Amount _modifyFee, int64_t _modifyCount, int64_t _modifySigOpCount)
Definition: txmempool.h:196
update_fee_delta(Amount _feeDelta)
Definition: txmempool.h:232
void operator()(CTxMemPoolEntry &e)
Definition: txmempool.h:234
void operator()(CTxMemPoolEntry &e)
Definition: txmempool.h:243
update_lock_points(const LockPoints &_lp)
Definition: txmempool.h:241
const LockPoints & lp
Definition: txmempool.h:246
#define LOCK(cs)
Definition: sync.h:241
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:56
MemPoolRemovalReason
Reason why a transaction was removed from the mempool, this is passed to the notification signal.
Definition: txmempool.h:402
@ 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 Coins to signify they are only in the memory pool(since 0....
Definition: txmempool.h:41
RecursiveMutex cs_main
Global state.
Definition: validation.cpp:91
AssertLockHeld(pool.cs)
assert(!tx.IsCoinBase())