[depends] ZeroMQ 4.1.5
[bitcoinplatinum.git] / src / txmempool.h
blob2c2127f326de2cce875c5a4c3689dbb7f25d6b0c
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2015 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.
6 #ifndef BITCOIN_TXMEMPOOL_H
7 #define BITCOIN_TXMEMPOOL_H
9 #include <list>
10 #include <memory>
11 #include <set>
13 #include "amount.h"
14 #include "coins.h"
15 #include "indirectmap.h"
16 #include "primitives/transaction.h"
17 #include "sync.h"
19 #undef foreach
20 #include "boost/multi_index_container.hpp"
21 #include "boost/multi_index/ordered_index.hpp"
22 #include "boost/multi_index/hashed_index.hpp"
24 class CAutoFile;
25 class CBlockIndex;
27 inline double AllowFreeThreshold()
29 return COIN * 144 / 250;
32 inline bool AllowFree(double dPriority)
34 // Large (in bytes) low-priority (new, small-coin) transactions
35 // need a fee.
36 return dPriority > AllowFreeThreshold();
39 /** Fake height value used in CCoins to signify they are only in the memory pool (since 0.8) */
40 static const unsigned int MEMPOOL_HEIGHT = 0x7FFFFFFF;
42 struct LockPoints
44 // Will be set to the blockchain height and median time past
45 // values that would be necessary to satisfy all relative locktime
46 // constraints (BIP68) 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.
52 CBlockIndex* maxInputBlock;
54 LockPoints() : height(0), time(0), maxInputBlock(NULL) { }
57 class CTxMemPool;
59 /** \class CTxMemPoolEntry
61 * CTxMemPoolEntry stores data about the correponding transaction, as well
62 * as data about all in-mempool transactions that depend on the transaction
63 * ("descendant" transactions).
65 * When a new entry is added to the mempool, we update the descendant state
66 * (nCountWithDescendants, nSizeWithDescendants, and nModFeesWithDescendants) for
67 * all ancestors of the newly added transaction.
69 * If updating the descendant state is skipped, we can mark the entry as
70 * "dirty", and set nSizeWithDescendants/nModFeesWithDescendants to equal nTxSize/
71 * nFee+feeDelta. (This can potentially happen during a reorg, where we limit the
72 * amount of work we're willing to do to avoid consuming too much CPU.)
76 class CTxMemPoolEntry
78 private:
79 std::shared_ptr<const CTransaction> tx;
80 CAmount nFee; //!< Cached to avoid expensive parent-transaction lookups
81 size_t nTxWeight; //!< ... and avoid recomputing tx weight (also used for GetTxSize())
82 size_t nModSize; //!< ... and modified size for priority
83 size_t nUsageSize; //!< ... and total memory usage
84 int64_t nTime; //!< Local time when entering the mempool
85 double entryPriority; //!< Priority when entering the mempool
86 unsigned int entryHeight; //!< Chain height when entering the mempool
87 bool hadNoDependencies; //!< Not dependent on any other txs when it entered the mempool
88 CAmount inChainInputValue; //!< Sum of all txin values that are already in blockchain
89 bool spendsCoinbase; //!< keep track of transactions that spend a coinbase
90 int64_t sigOpCost; //!< Total sigop cost
91 int64_t feeDelta; //!< Used for determining the priority of the transaction for mining in a block
92 LockPoints lockPoints; //!< Track the height and time at which tx was final
94 // Information about descendants of this transaction that are in the
95 // mempool; if we remove this transaction we must remove all of these
96 // descendants as well. if nCountWithDescendants is 0, treat this entry as
97 // dirty, and nSizeWithDescendants and nModFeesWithDescendants will not be
98 // correct.
99 uint64_t nCountWithDescendants; //!< number of descendant transactions
100 uint64_t nSizeWithDescendants; //!< ... and size
101 CAmount nModFeesWithDescendants; //!< ... and total fees (all including us)
103 // Analogous statistics for ancestor transactions
104 uint64_t nCountWithAncestors;
105 uint64_t nSizeWithAncestors;
106 CAmount nModFeesWithAncestors;
107 int64_t nSigOpCostWithAncestors;
109 public:
110 CTxMemPoolEntry(const CTransaction& _tx, const CAmount& _nFee,
111 int64_t _nTime, double _entryPriority, unsigned int _entryHeight,
112 bool poolHasNoInputsOf, CAmount _inChainInputValue, bool spendsCoinbase,
113 int64_t nSigOpsCost, LockPoints lp);
114 CTxMemPoolEntry(const CTxMemPoolEntry& other);
116 const CTransaction& GetTx() const { return *this->tx; }
117 std::shared_ptr<const CTransaction> GetSharedTx() const { return this->tx; }
119 * Fast calculation of lower bound of current priority as update
120 * from entry priority. Only inputs that were originally in-chain will age.
122 double GetPriority(unsigned int currentHeight) const;
123 const CAmount& GetFee() const { return nFee; }
124 size_t GetTxSize() const;
125 size_t GetTxWeight() const { return nTxWeight; }
126 int64_t GetTime() const { return nTime; }
127 unsigned int GetHeight() const { return entryHeight; }
128 bool WasClearAtEntry() const { return hadNoDependencies; }
129 int64_t GetSigOpCost() const { return sigOpCost; }
130 int64_t GetModifiedFee() const { return nFee + feeDelta; }
131 size_t DynamicMemoryUsage() const { return nUsageSize; }
132 const LockPoints& GetLockPoints() const { return lockPoints; }
134 // Adjusts the descendant state, if this entry is not dirty.
135 void UpdateDescendantState(int64_t modifySize, CAmount modifyFee, int64_t modifyCount);
136 // Adjusts the ancestor state
137 void UpdateAncestorState(int64_t modifySize, CAmount modifyFee, int64_t modifyCount, int modifySigOps);
138 // Updates the fee delta used for mining priority score, and the
139 // modified fees with descendants.
140 void UpdateFeeDelta(int64_t feeDelta);
141 // Update the LockPoints after a reorg
142 void UpdateLockPoints(const LockPoints& lp);
144 uint64_t GetCountWithDescendants() const { return nCountWithDescendants; }
145 uint64_t GetSizeWithDescendants() const { return nSizeWithDescendants; }
146 CAmount GetModFeesWithDescendants() const { return nModFeesWithDescendants; }
148 bool GetSpendsCoinbase() const { return spendsCoinbase; }
150 uint64_t GetCountWithAncestors() const { return nCountWithAncestors; }
151 uint64_t GetSizeWithAncestors() const { return nSizeWithAncestors; }
152 CAmount GetModFeesWithAncestors() const { return nModFeesWithAncestors; }
153 int64_t GetSigOpCostWithAncestors() const { return nSigOpCostWithAncestors; }
155 mutable size_t vTxHashesIdx; //!< Index in mempool's vTxHashes
158 // Helpers for modifying CTxMemPool::mapTx, which is a boost multi_index.
159 struct update_descendant_state
161 update_descendant_state(int64_t _modifySize, CAmount _modifyFee, int64_t _modifyCount) :
162 modifySize(_modifySize), modifyFee(_modifyFee), modifyCount(_modifyCount)
165 void operator() (CTxMemPoolEntry &e)
166 { e.UpdateDescendantState(modifySize, modifyFee, modifyCount); }
168 private:
169 int64_t modifySize;
170 CAmount modifyFee;
171 int64_t modifyCount;
174 struct update_ancestor_state
176 update_ancestor_state(int64_t _modifySize, CAmount _modifyFee, int64_t _modifyCount, int64_t _modifySigOpsCost) :
177 modifySize(_modifySize), modifyFee(_modifyFee), modifyCount(_modifyCount), modifySigOpsCost(_modifySigOpsCost)
180 void operator() (CTxMemPoolEntry &e)
181 { e.UpdateAncestorState(modifySize, modifyFee, modifyCount, modifySigOpsCost); }
183 private:
184 int64_t modifySize;
185 CAmount modifyFee;
186 int64_t modifyCount;
187 int64_t modifySigOpsCost;
190 struct update_fee_delta
192 update_fee_delta(int64_t _feeDelta) : feeDelta(_feeDelta) { }
194 void operator() (CTxMemPoolEntry &e) { e.UpdateFeeDelta(feeDelta); }
196 private:
197 int64_t feeDelta;
200 struct update_lock_points
202 update_lock_points(const LockPoints& _lp) : lp(_lp) { }
204 void operator() (CTxMemPoolEntry &e) { e.UpdateLockPoints(lp); }
206 private:
207 const LockPoints& lp;
210 // extracts a TxMemPoolEntry's transaction hash
211 struct mempoolentry_txid
213 typedef uint256 result_type;
214 result_type operator() (const CTxMemPoolEntry &entry) const
216 return entry.GetTx().GetHash();
220 /** \class CompareTxMemPoolEntryByDescendantScore
222 * Sort an entry by max(score/size of entry's tx, score/size with all descendants).
224 class CompareTxMemPoolEntryByDescendantScore
226 public:
227 bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b)
229 bool fUseADescendants = UseDescendantScore(a);
230 bool fUseBDescendants = UseDescendantScore(b);
232 double aModFee = fUseADescendants ? a.GetModFeesWithDescendants() : a.GetModifiedFee();
233 double aSize = fUseADescendants ? a.GetSizeWithDescendants() : a.GetTxSize();
235 double bModFee = fUseBDescendants ? b.GetModFeesWithDescendants() : b.GetModifiedFee();
236 double bSize = fUseBDescendants ? b.GetSizeWithDescendants() : b.GetTxSize();
238 // Avoid division by rewriting (a/b > c/d) as (a*d > c*b).
239 double f1 = aModFee * bSize;
240 double f2 = aSize * bModFee;
242 if (f1 == f2) {
243 return a.GetTime() >= b.GetTime();
245 return f1 < f2;
248 // Calculate which score to use for an entry (avoiding division).
249 bool UseDescendantScore(const CTxMemPoolEntry &a)
251 double f1 = (double)a.GetModifiedFee() * a.GetSizeWithDescendants();
252 double f2 = (double)a.GetModFeesWithDescendants() * a.GetTxSize();
253 return f2 > f1;
257 /** \class CompareTxMemPoolEntryByScore
259 * Sort by score of entry ((fee+delta)/size) in descending order
261 class CompareTxMemPoolEntryByScore
263 public:
264 bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b)
266 double f1 = (double)a.GetModifiedFee() * b.GetTxSize();
267 double f2 = (double)b.GetModifiedFee() * a.GetTxSize();
268 if (f1 == f2) {
269 return b.GetTx().GetHash() < a.GetTx().GetHash();
271 return f1 > f2;
275 class CompareTxMemPoolEntryByEntryTime
277 public:
278 bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b)
280 return a.GetTime() < b.GetTime();
284 class CompareTxMemPoolEntryByAncestorFee
286 public:
287 bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b)
289 double aFees = a.GetModFeesWithAncestors();
290 double aSize = a.GetSizeWithAncestors();
292 double bFees = b.GetModFeesWithAncestors();
293 double bSize = b.GetSizeWithAncestors();
295 // Avoid division by rewriting (a/b > c/d) as (a*d > c*b).
296 double f1 = aFees * bSize;
297 double f2 = aSize * bFees;
299 if (f1 == f2) {
300 return a.GetTx().GetHash() < b.GetTx().GetHash();
303 return f1 > f2;
307 // Multi_index tag names
308 struct descendant_score {};
309 struct entry_time {};
310 struct mining_score {};
311 struct ancestor_score {};
313 class CBlockPolicyEstimator;
316 * Information about a mempool transaction.
318 struct TxMempoolInfo
320 /** The transaction itself */
321 std::shared_ptr<const CTransaction> tx;
323 /** Time the transaction entered the mempool. */
324 int64_t nTime;
326 /** Feerate of the transaction. */
327 CFeeRate feeRate;
331 * CTxMemPool stores valid-according-to-the-current-best-chain
332 * transactions that may be included in the next block.
334 * Transactions are added when they are seen on the network
335 * (or created by the local node), but not all transactions seen
336 * are added to the pool: if a new transaction double-spends
337 * an input of a transaction in the pool, it is dropped,
338 * as are non-standard transactions.
340 * CTxMemPool::mapTx, and CTxMemPoolEntry bookkeeping:
342 * mapTx is a boost::multi_index that sorts the mempool on 4 criteria:
343 * - transaction hash
344 * - feerate [we use max(feerate of tx, feerate of tx with all descendants)]
345 * - time in mempool
346 * - mining score (feerate modified by any fee deltas from PrioritiseTransaction)
348 * Note: the term "descendant" refers to in-mempool transactions that depend on
349 * this one, while "ancestor" refers to in-mempool transactions that a given
350 * transaction depends on.
352 * In order for the feerate sort to remain correct, we must update transactions
353 * in the mempool when new descendants arrive. To facilitate this, we track
354 * the set of in-mempool direct parents and direct children in mapLinks. Within
355 * each CTxMemPoolEntry, we track the size and fees of all descendants.
357 * Usually when a new transaction is added to the mempool, it has no in-mempool
358 * children (because any such children would be an orphan). So in
359 * addUnchecked(), we:
360 * - update a new entry's setMemPoolParents to include all in-mempool parents
361 * - update the new entry's direct parents to include the new tx as a child
362 * - update all ancestors of the transaction to include the new tx's size/fee
364 * When a transaction is removed from the mempool, we must:
365 * - update all in-mempool parents to not track the tx in setMemPoolChildren
366 * - update all ancestors to not include the tx's size/fees in descendant state
367 * - update all in-mempool children to not include it as a parent
369 * These happen in UpdateForRemoveFromMempool(). (Note that when removing a
370 * transaction along with its descendants, we must calculate that set of
371 * transactions to be removed before doing the removal, or else the mempool can
372 * be in an inconsistent state where it's impossible to walk the ancestors of
373 * a transaction.)
375 * In the event of a reorg, the assumption that a newly added tx has no
376 * in-mempool children is false. In particular, the mempool is in an
377 * inconsistent state while new transactions are being added, because there may
378 * be descendant transactions of a tx coming from a disconnected block that are
379 * unreachable from just looking at transactions in the mempool (the linking
380 * transactions may also be in the disconnected block, waiting to be added).
381 * Because of this, there's not much benefit in trying to search for in-mempool
382 * children in addUnchecked(). Instead, in the special case of transactions
383 * being added from a disconnected block, we require the caller to clean up the
384 * state, to account for in-mempool, out-of-block descendants for all the
385 * in-block transactions by calling UpdateTransactionsFromBlock(). Note that
386 * until this is called, the mempool state is not consistent, and in particular
387 * mapLinks may not be correct (and therefore functions like
388 * CalculateMemPoolAncestors() and CalculateDescendants() that rely
389 * on them to walk the mempool are not generally safe to use).
391 * Computational limits:
393 * Updating all in-mempool ancestors of a newly added transaction can be slow,
394 * if no bound exists on how many in-mempool ancestors there may be.
395 * CalculateMemPoolAncestors() takes configurable limits that are designed to
396 * prevent these calculations from being too CPU intensive.
398 * Adding transactions from a disconnected block can be very time consuming,
399 * because we don't have a way to limit the number of in-mempool descendants.
400 * To bound CPU processing, we limit the amount of work we're willing to do
401 * to properly update the descendant information for a tx being added from
402 * a disconnected block. If we would exceed the limit, then we instead mark
403 * the entry as "dirty", and set the feerate for sorting purposes to be equal
404 * the feerate of the transaction without any descendants.
407 class CTxMemPool
409 private:
410 uint32_t nCheckFrequency; //!< Value n means that n times in 2^32 we check.
411 unsigned int nTransactionsUpdated;
412 CBlockPolicyEstimator* minerPolicyEstimator;
414 uint64_t totalTxSize; //!< sum of all mempool tx' byte sizes
415 uint64_t cachedInnerUsage; //!< sum of dynamic memory usage of all the map elements (NOT the maps themselves)
417 CFeeRate minReasonableRelayFee;
419 mutable int64_t lastRollingFeeUpdate;
420 mutable bool blockSinceLastRollingFeeBump;
421 mutable double rollingMinimumFeeRate; //!< minimum fee to get into the pool, decreases exponentially
423 void trackPackageRemoved(const CFeeRate& rate);
425 public:
427 static const int ROLLING_FEE_HALFLIFE = 60 * 60 * 12; // public only for testing
429 typedef boost::multi_index_container<
430 CTxMemPoolEntry,
431 boost::multi_index::indexed_by<
432 // sorted by txid
433 boost::multi_index::hashed_unique<mempoolentry_txid, SaltedTxidHasher>,
434 // sorted by fee rate
435 boost::multi_index::ordered_non_unique<
436 boost::multi_index::tag<descendant_score>,
437 boost::multi_index::identity<CTxMemPoolEntry>,
438 CompareTxMemPoolEntryByDescendantScore
440 // sorted by entry time
441 boost::multi_index::ordered_non_unique<
442 boost::multi_index::tag<entry_time>,
443 boost::multi_index::identity<CTxMemPoolEntry>,
444 CompareTxMemPoolEntryByEntryTime
446 // sorted by score (for mining prioritization)
447 boost::multi_index::ordered_unique<
448 boost::multi_index::tag<mining_score>,
449 boost::multi_index::identity<CTxMemPoolEntry>,
450 CompareTxMemPoolEntryByScore
452 // sorted by fee rate with ancestors
453 boost::multi_index::ordered_non_unique<
454 boost::multi_index::tag<ancestor_score>,
455 boost::multi_index::identity<CTxMemPoolEntry>,
456 CompareTxMemPoolEntryByAncestorFee
459 > indexed_transaction_set;
461 mutable CCriticalSection cs;
462 indexed_transaction_set mapTx;
464 typedef indexed_transaction_set::nth_index<0>::type::iterator txiter;
465 std::vector<std::pair<uint256, txiter> > vTxHashes; //!< All tx hashes/entries in mapTx, in random order
467 struct CompareIteratorByHash {
468 bool operator()(const txiter &a, const txiter &b) const {
469 return a->GetTx().GetHash() < b->GetTx().GetHash();
472 typedef std::set<txiter, CompareIteratorByHash> setEntries;
474 const setEntries & GetMemPoolParents(txiter entry) const;
475 const setEntries & GetMemPoolChildren(txiter entry) const;
476 private:
477 typedef std::map<txiter, setEntries, CompareIteratorByHash> cacheMap;
479 struct TxLinks {
480 setEntries parents;
481 setEntries children;
484 typedef std::map<txiter, TxLinks, CompareIteratorByHash> txlinksMap;
485 txlinksMap mapLinks;
487 void UpdateParent(txiter entry, txiter parent, bool add);
488 void UpdateChild(txiter entry, txiter child, bool add);
490 std::vector<indexed_transaction_set::const_iterator> GetSortedDepthAndScore() const;
492 public:
493 indirectmap<COutPoint, const CTransaction*> mapNextTx;
494 std::map<uint256, std::pair<double, CAmount> > mapDeltas;
496 /** Create a new CTxMemPool.
497 * minReasonableRelayFee should be a feerate which is, roughly, somewhere
498 * around what it "costs" to relay a transaction around the network and
499 * below which we would reasonably say a transaction has 0-effective-fee.
501 CTxMemPool(const CFeeRate& _minReasonableRelayFee);
502 ~CTxMemPool();
505 * If sanity-checking is turned on, check makes sure the pool is
506 * consistent (does not contain two transactions that spend the same inputs,
507 * all inputs are in the mapNextTx array). If sanity-checking is turned off,
508 * check does nothing.
510 void check(const CCoinsViewCache *pcoins) const;
511 void setSanityCheck(double dFrequency = 1.0) { nCheckFrequency = dFrequency * 4294967295.0; }
513 // addUnchecked must updated state for all ancestors of a given transaction,
514 // to track size/count of descendant transactions. First version of
515 // addUnchecked can be used to have it call CalculateMemPoolAncestors(), and
516 // then invoke the second version.
517 bool addUnchecked(const uint256& hash, const CTxMemPoolEntry &entry, bool fCurrentEstimate = true);
518 bool addUnchecked(const uint256& hash, const CTxMemPoolEntry &entry, setEntries &setAncestors, bool fCurrentEstimate = true);
520 void removeRecursive(const CTransaction &tx, std::list<CTransaction>& removed);
521 void removeForReorg(const CCoinsViewCache *pcoins, unsigned int nMemPoolHeight, int flags);
522 void removeConflicts(const CTransaction &tx, std::list<CTransaction>& removed);
523 void removeForBlock(const std::vector<CTransaction>& vtx, unsigned int nBlockHeight,
524 std::list<CTransaction>& conflicts, bool fCurrentEstimate = true);
525 void clear();
526 void _clear(); //lock free
527 bool CompareDepthAndScore(const uint256& hasha, const uint256& hashb);
528 void queryHashes(std::vector<uint256>& vtxid);
529 void pruneSpent(const uint256& hash, CCoins &coins);
530 unsigned int GetTransactionsUpdated() const;
531 void AddTransactionsUpdated(unsigned int n);
533 * Check that none of this transactions inputs are in the mempool, and thus
534 * the tx is not dependent on other mempool transactions to be included in a block.
536 bool HasNoInputsOf(const CTransaction& tx) const;
538 /** Affect CreateNewBlock prioritisation of transactions */
539 void PrioritiseTransaction(const uint256 hash, const std::string strHash, double dPriorityDelta, const CAmount& nFeeDelta);
540 void ApplyDeltas(const uint256 hash, double &dPriorityDelta, CAmount &nFeeDelta) const;
541 void ClearPrioritisation(const uint256 hash);
543 public:
544 /** Remove a set of transactions from the mempool.
545 * If a transaction is in this set, then all in-mempool descendants must
546 * also be in the set, unless this transaction is being removed for being
547 * in a block.
548 * Set updateDescendants to true when removing a tx that was in a block, so
549 * that any in-mempool descendants have their ancestor state updated.
551 void RemoveStaged(setEntries &stage, bool updateDescendants);
553 /** When adding transactions from a disconnected block back to the mempool,
554 * new mempool entries may have children in the mempool (which is generally
555 * not the case when otherwise adding transactions).
556 * UpdateTransactionsFromBlock() will find child transactions and update the
557 * descendant state for each transaction in hashesToUpdate (excluding any
558 * child transactions present in hashesToUpdate, which are already accounted
559 * for). Note: hashesToUpdate should be the set of transactions from the
560 * disconnected block that have been accepted back into the mempool.
562 void UpdateTransactionsFromBlock(const std::vector<uint256> &hashesToUpdate);
564 /** Try to calculate all in-mempool ancestors of entry.
565 * (these are all calculated including the tx itself)
566 * limitAncestorCount = max number of ancestors
567 * limitAncestorSize = max size of ancestors
568 * limitDescendantCount = max number of descendants any ancestor can have
569 * limitDescendantSize = max size of descendants any ancestor can have
570 * errString = populated with error reason if any limits are hit
571 * fSearchForParents = whether to search a tx's vin for in-mempool parents, or
572 * look up parents from mapLinks. Must be true for entries not in the mempool
574 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;
576 /** Populate setDescendants with all in-mempool descendants of hash.
577 * Assumes that setDescendants includes all in-mempool descendants of anything
578 * already in it. */
579 void CalculateDescendants(txiter it, setEntries &setDescendants);
581 /** The minimum fee to get into the mempool, which may itself not be enough
582 * for larger-sized transactions.
583 * The minReasonableRelayFee constructor arg is used to bound the time it
584 * takes the fee rate to go back down all the way to 0. When the feerate
585 * would otherwise be half of this, it is set to 0 instead.
587 CFeeRate GetMinFee(size_t sizelimit) const;
589 /** Remove transactions from the mempool until its dynamic size is <= sizelimit.
590 * pvNoSpendsRemaining, if set, will be populated with the list of transactions
591 * which are not in mempool which no longer have any spends in this mempool.
593 void TrimToSize(size_t sizelimit, std::vector<uint256>* pvNoSpendsRemaining=NULL);
595 /** Expire all transaction (and their dependencies) in the mempool older than time. Return the number of removed transactions. */
596 int Expire(int64_t time);
598 unsigned long size()
600 LOCK(cs);
601 return mapTx.size();
604 uint64_t GetTotalTxSize()
606 LOCK(cs);
607 return totalTxSize;
610 bool exists(uint256 hash) const
612 LOCK(cs);
613 return (mapTx.count(hash) != 0);
616 std::shared_ptr<const CTransaction> get(const uint256& hash) const;
617 TxMempoolInfo info(const uint256& hash) const;
618 std::vector<TxMempoolInfo> infoAll() const;
620 /** Estimate fee rate needed to get into the next nBlocks
621 * If no answer can be given at nBlocks, return an estimate
622 * at the lowest number of blocks where one can be given
624 CFeeRate estimateSmartFee(int nBlocks, int *answerFoundAtBlocks = NULL) const;
626 /** Estimate fee rate needed to get into the next nBlocks */
627 CFeeRate estimateFee(int nBlocks) const;
629 /** Estimate priority needed to get into the next nBlocks
630 * If no answer can be given at nBlocks, return an estimate
631 * at the lowest number of blocks where one can be given
633 double estimateSmartPriority(int nBlocks, int *answerFoundAtBlocks = NULL) const;
635 /** Estimate priority needed to get into the next nBlocks */
636 double estimatePriority(int nBlocks) const;
638 /** Write/Read estimates to disk */
639 bool WriteFeeEstimates(CAutoFile& fileout) const;
640 bool ReadFeeEstimates(CAutoFile& filein);
642 size_t DynamicMemoryUsage() const;
644 private:
645 /** UpdateForDescendants is used by UpdateTransactionsFromBlock to update
646 * the descendants for a single transaction that has been added to the
647 * mempool but may have child transactions in the mempool, eg during a
648 * chain reorg. setExclude is the set of descendant transactions in the
649 * mempool that must not be accounted for (because any descendants in
650 * setExclude were added to the mempool after the transaction being
651 * updated and hence their state is already reflected in the parent
652 * state).
654 * cachedDescendants will be updated with the descendants of the transaction
655 * being updated, so that future invocations don't need to walk the
656 * same transaction again, if encountered in another transaction chain.
658 void UpdateForDescendants(txiter updateIt,
659 cacheMap &cachedDescendants,
660 const std::set<uint256> &setExclude);
661 /** Update ancestors of hash to add/remove it as a descendant transaction. */
662 void UpdateAncestorsOf(bool add, txiter hash, setEntries &setAncestors);
663 /** Set ancestor state for an entry */
664 void UpdateEntryForAncestors(txiter it, const setEntries &setAncestors);
665 /** For each transaction being removed, update ancestors and any direct children.
666 * If updateDescendants is true, then also update in-mempool descendants'
667 * ancestor state. */
668 void UpdateForRemoveFromMempool(const setEntries &entriesToRemove, bool updateDescendants);
669 /** Sever link between specified transaction and direct children. */
670 void UpdateChildrenForRemoval(txiter entry);
672 /** Before calling removeUnchecked for a given transaction,
673 * UpdateForRemoveFromMempool must be called on the entire (dependent) set
674 * of transactions being removed at the same time. We use each
675 * CTxMemPoolEntry's setMemPoolParents in order to walk ancestors of a
676 * given transaction that is removed, so we can't remove intermediate
677 * transactions in a chain before we've updated all the state for the
678 * removal.
680 void removeUnchecked(txiter entry);
683 /**
684 * CCoinsView that brings transactions from a memorypool into view.
685 * It does not check for spendings by memory pool transactions.
687 class CCoinsViewMemPool : public CCoinsViewBacked
689 protected:
690 const CTxMemPool& mempool;
692 public:
693 CCoinsViewMemPool(CCoinsView* baseIn, const CTxMemPool& mempoolIn);
694 bool GetCoins(const uint256 &txid, CCoins &coins) const;
695 bool HaveCoins(const uint256 &txid) const;
698 // We want to sort transactions by coin age priority
699 typedef std::pair<double, CTxMemPool::txiter> TxCoinAgePriority;
701 struct TxCoinAgePriorityCompare
703 bool operator()(const TxCoinAgePriority& a, const TxCoinAgePriority& b)
705 if (a.first == b.first)
706 return CompareTxMemPoolEntryByScore()(*(b.second), *(a.second)); //Reverse order to make sort less than
707 return a.first < b.first;
711 #endif // BITCOIN_TXMEMPOOL_H