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.
5 
6 #ifndef BITCOIN_TXMEMPOOL_H
7 #define BITCOIN_TXMEMPOOL_H
8 
9 #include <list>
10 #include <memory>
11 #include <set>
12 
13 #include "amount.h"
14 #include "coins.h"
15 #include "indirectmap.h"
16 #include "primitives/transaction.h"
17 #include "sync.h"
18 
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"
23 
24 class CAutoFile;
25 class CBlockIndex;
26 
AllowFreeThreshold()27 inline double AllowFreeThreshold()
28 {
29     return COIN * 144 / 250;
30 }
31 
AllowFree(double dPriority)32 inline bool AllowFree(double dPriority)
33 {
34     // Large (in bytes) low-priority (new, small-coin) transactions
35     // need a fee.
36     return dPriority > AllowFreeThreshold();
37 }
38 
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;
41 
42 struct LockPoints
43 {
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;
53 
LockPointsLockPoints54     LockPoints() : height(0), time(0), maxInputBlock(NULL) { }
55 };
56 
57 class CTxMemPool;
58 
59 /** \class CTxMemPoolEntry
60  *
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).
64  *
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.
68  *
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.)
73  *
74  */
75 
76 class CTxMemPoolEntry
77 {
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
93 
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)
102 
103     // Analogous statistics for ancestor transactions
104     uint64_t nCountWithAncestors;
105     uint64_t nSizeWithAncestors;
106     CAmount nModFeesWithAncestors;
107     int64_t nSigOpCostWithAncestors;
108 
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);
115 
GetTx()116     const CTransaction& GetTx() const { return *this->tx; }
GetSharedTx()117     std::shared_ptr<const CTransaction> GetSharedTx() const { return this->tx; }
118     /**
119      * Fast calculation of lower bound of current priority as update
120      * from entry priority. Only inputs that were originally in-chain will age.
121      */
122     double GetPriority(unsigned int currentHeight) const;
GetFee()123     const CAmount& GetFee() const { return nFee; }
124     size_t GetTxSize() const;
GetTxWeight()125     size_t GetTxWeight() const { return nTxWeight; }
GetTime()126     int64_t GetTime() const { return nTime; }
GetHeight()127     unsigned int GetHeight() const { return entryHeight; }
WasClearAtEntry()128     bool WasClearAtEntry() const { return hadNoDependencies; }
GetSigOpCost()129     int64_t GetSigOpCost() const { return sigOpCost; }
GetModifiedFee()130     int64_t GetModifiedFee() const { return nFee + feeDelta; }
DynamicMemoryUsage()131     size_t DynamicMemoryUsage() const { return nUsageSize; }
GetLockPoints()132     const LockPoints& GetLockPoints() const { return lockPoints; }
133 
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);
143 
GetCountWithDescendants()144     uint64_t GetCountWithDescendants() const { return nCountWithDescendants; }
GetSizeWithDescendants()145     uint64_t GetSizeWithDescendants() const { return nSizeWithDescendants; }
GetModFeesWithDescendants()146     CAmount GetModFeesWithDescendants() const { return nModFeesWithDescendants; }
147 
GetSpendsCoinbase()148     bool GetSpendsCoinbase() const { return spendsCoinbase; }
149 
GetCountWithAncestors()150     uint64_t GetCountWithAncestors() const { return nCountWithAncestors; }
GetSizeWithAncestors()151     uint64_t GetSizeWithAncestors() const { return nSizeWithAncestors; }
GetModFeesWithAncestors()152     CAmount GetModFeesWithAncestors() const { return nModFeesWithAncestors; }
GetSigOpCostWithAncestors()153     int64_t GetSigOpCostWithAncestors() const { return nSigOpCostWithAncestors; }
154 
155     mutable size_t vTxHashesIdx; //!< Index in mempool's vTxHashes
156 };
157 
158 // Helpers for modifying CTxMemPool::mapTx, which is a boost multi_index.
159 struct update_descendant_state
160 {
update_descendant_stateupdate_descendant_state161     update_descendant_state(int64_t _modifySize, CAmount _modifyFee, int64_t _modifyCount) :
162         modifySize(_modifySize), modifyFee(_modifyFee), modifyCount(_modifyCount)
163     {}
164 
operatorupdate_descendant_state165     void operator() (CTxMemPoolEntry &e)
166         { e.UpdateDescendantState(modifySize, modifyFee, modifyCount); }
167 
168     private:
169         int64_t modifySize;
170         CAmount modifyFee;
171         int64_t modifyCount;
172 };
173 
174 struct update_ancestor_state
175 {
update_ancestor_stateupdate_ancestor_state176     update_ancestor_state(int64_t _modifySize, CAmount _modifyFee, int64_t _modifyCount, int64_t _modifySigOpsCost) :
177         modifySize(_modifySize), modifyFee(_modifyFee), modifyCount(_modifyCount), modifySigOpsCost(_modifySigOpsCost)
178     {}
179 
operatorupdate_ancestor_state180     void operator() (CTxMemPoolEntry &e)
181         { e.UpdateAncestorState(modifySize, modifyFee, modifyCount, modifySigOpsCost); }
182 
183     private:
184         int64_t modifySize;
185         CAmount modifyFee;
186         int64_t modifyCount;
187         int64_t modifySigOpsCost;
188 };
189 
190 struct update_fee_delta
191 {
update_fee_deltaupdate_fee_delta192     update_fee_delta(int64_t _feeDelta) : feeDelta(_feeDelta) { }
193 
operatorupdate_fee_delta194     void operator() (CTxMemPoolEntry &e) { e.UpdateFeeDelta(feeDelta); }
195 
196 private:
197     int64_t feeDelta;
198 };
199 
200 struct update_lock_points
201 {
update_lock_pointsupdate_lock_points202     update_lock_points(const LockPoints& _lp) : lp(_lp) { }
203 
operatorupdate_lock_points204     void operator() (CTxMemPoolEntry &e) { e.UpdateLockPoints(lp); }
205 
206 private:
207     const LockPoints& lp;
208 };
209 
210 // extracts a TxMemPoolEntry's transaction hash
211 struct mempoolentry_txid
212 {
213     typedef uint256 result_type;
operatormempoolentry_txid214     result_type operator() (const CTxMemPoolEntry &entry) const
215     {
216         return entry.GetTx().GetHash();
217     }
218 };
219 
220 /** \class CompareTxMemPoolEntryByDescendantScore
221  *
222  *  Sort an entry by max(score/size of entry's tx, score/size with all descendants).
223  */
224 class CompareTxMemPoolEntryByDescendantScore
225 {
226 public:
operator()227     bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) const
228     {
229         bool fUseADescendants = UseDescendantScore(a);
230         bool fUseBDescendants = UseDescendantScore(b);
231 
232         double aModFee = fUseADescendants ? a.GetModFeesWithDescendants() : a.GetModifiedFee();
233         double aSize = fUseADescendants ? a.GetSizeWithDescendants() : a.GetTxSize();
234 
235         double bModFee = fUseBDescendants ? b.GetModFeesWithDescendants() : b.GetModifiedFee();
236         double bSize = fUseBDescendants ? b.GetSizeWithDescendants() : b.GetTxSize();
237 
238         // Avoid division by rewriting (a/b > c/d) as (a*d > c*b).
239         double f1 = aModFee * bSize;
240         double f2 = aSize * bModFee;
241 
242         if (f1 == f2) {
243             return a.GetTime() >= b.GetTime();
244         }
245         return f1 < f2;
246     }
247 
248     // Calculate which score to use for an entry (avoiding division).
UseDescendantScore(const CTxMemPoolEntry & a)249     bool UseDescendantScore(const CTxMemPoolEntry &a) const
250     {
251         double f1 = (double)a.GetModifiedFee() * a.GetSizeWithDescendants();
252         double f2 = (double)a.GetModFeesWithDescendants() * a.GetTxSize();
253         return f2 > f1;
254     }
255 };
256 
257 /** \class CompareTxMemPoolEntryByScore
258  *
259  *  Sort by score of entry ((fee+delta)/size) in descending order
260  */
261 class CompareTxMemPoolEntryByScore
262 {
263 public:
operator()264     bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) const
265     {
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();
270         }
271         return f1 > f2;
272     }
273 };
274 
275 class CompareTxMemPoolEntryByEntryTime
276 {
277 public:
operator()278     bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) const
279     {
280         return a.GetTime() < b.GetTime();
281     }
282 };
283 
284 class CompareTxMemPoolEntryByAncestorFee
285 {
286 public:
operator()287     bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) const
288     {
289         double aFees = a.GetModFeesWithAncestors();
290         double aSize = a.GetSizeWithAncestors();
291 
292         double bFees = b.GetModFeesWithAncestors();
293         double bSize = b.GetSizeWithAncestors();
294 
295         // Avoid division by rewriting (a/b > c/d) as (a*d > c*b).
296         double f1 = aFees * bSize;
297         double f2 = aSize * bFees;
298 
299         if (f1 == f2) {
300             return a.GetTx().GetHash() < b.GetTx().GetHash();
301         }
302 
303         return f1 > f2;
304     }
305 };
306 
307 // Multi_index tag names
308 struct descendant_score {};
309 struct entry_time {};
310 struct mining_score {};
311 struct ancestor_score {};
312 
313 class CBlockPolicyEstimator;
314 
315 /**
316  * Information about a mempool transaction.
317  */
318 struct TxMempoolInfo
319 {
320     /** The transaction itself */
321     std::shared_ptr<const CTransaction> tx;
322 
323     /** Time the transaction entered the mempool. */
324     int64_t nTime;
325 
326     /** Feerate of the transaction. */
327     CFeeRate feeRate;
328 };
329 
330 /**
331  * CTxMemPool stores valid-according-to-the-current-best-chain
332  * transactions that may be included in the next block.
333  *
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.
339  *
340  * CTxMemPool::mapTx, and CTxMemPoolEntry bookkeeping:
341  *
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)
347  *
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.
351  *
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.
356  *
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
363  *
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
368  *
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.)
374  *
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).
390  *
391  * Computational limits:
392  *
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.
397  *
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.
405  *
406  */
407 class CTxMemPool
408 {
409 private:
410     uint32_t nCheckFrequency; //!< Value n means that n times in 2^32 we check.
411     unsigned int nTransactionsUpdated;
412     CBlockPolicyEstimator* minerPolicyEstimator;
413 
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)
416 
417     CFeeRate minReasonableRelayFee;
418 
419     mutable int64_t lastRollingFeeUpdate;
420     mutable bool blockSinceLastRollingFeeBump;
421     mutable double rollingMinimumFeeRate; //!< minimum fee to get into the pool, decreases exponentially
422 
423     void trackPackageRemoved(const CFeeRate& rate);
424 
425 public:
426 
427     static const int ROLLING_FEE_HALFLIFE = 60 * 60 * 12; // public only for testing
428 
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
439             >,
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
445             >,
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
451             >,
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
457             >
458         >
459     > indexed_transaction_set;
460 
461     mutable CCriticalSection cs;
462     indexed_transaction_set mapTx;
463 
464     typedef indexed_transaction_set::nth_index<0>::type::iterator txiter;
465     std::vector<std::pair<uint256, txiter> > vTxHashes; //!< All tx witness hashes/entries in mapTx, in random order
466 
467     struct CompareIteratorByHash {
operatorCompareIteratorByHash468         bool operator()(const txiter &a, const txiter &b) const {
469             return a->GetTx().GetHash() < b->GetTx().GetHash();
470         }
471     };
472     typedef std::set<txiter, CompareIteratorByHash> setEntries;
473 
474     const setEntries & GetMemPoolParents(txiter entry) const;
475     const setEntries & GetMemPoolChildren(txiter entry) const;
476 private:
477     typedef std::map<txiter, setEntries, CompareIteratorByHash> cacheMap;
478 
479     struct TxLinks {
480         setEntries parents;
481         setEntries children;
482     };
483 
484     typedef std::map<txiter, TxLinks, CompareIteratorByHash> txlinksMap;
485     txlinksMap mapLinks;
486 
487     void UpdateParent(txiter entry, txiter parent, bool add);
488     void UpdateChild(txiter entry, txiter child, bool add);
489 
490     std::vector<indexed_transaction_set::const_iterator> GetSortedDepthAndScore() const;
491 
492 public:
493     indirectmap<COutPoint, const CTransaction*> mapNextTx;
494     std::map<uint256, std::pair<double, CAmount> > mapDeltas;
495 
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.
500      */
501     CTxMemPool(const CFeeRate& _minReasonableRelayFee);
502     ~CTxMemPool();
503 
504     /**
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.
509      */
510     void check(const CCoinsViewCache *pcoins) const;
511     void setSanityCheck(double dFrequency = 1.0) { nCheckFrequency = dFrequency * 4294967295.0; }
512 
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);
519 
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);
532     /**
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.
535      */
536     bool HasNoInputsOf(const CTransaction& tx) const;
537 
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);
542 
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.
550      */
551     void RemoveStaged(setEntries &stage, bool updateDescendants);
552 
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.
561      */
562     void UpdateTransactionsFromBlock(const std::vector<uint256> &hashesToUpdate);
563 
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
573      */
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;
575 
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);
580 
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.
586       */
587     CFeeRate GetMinFee(size_t sizelimit) const;
588 
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.
592       */
593     void TrimToSize(size_t sizelimit, std::vector<uint256>* pvNoSpendsRemaining=NULL);
594 
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);
597 
598     /** Returns false if the transaction is in the mempool and not within the chain limit specified. */
599     bool TransactionWithinChainLimit(const uint256& txid, size_t chainLimit) const;
600 
size()601     unsigned long size()
602     {
603         LOCK(cs);
604         return mapTx.size();
605     }
606 
GetTotalTxSize()607     uint64_t GetTotalTxSize()
608     {
609         LOCK(cs);
610         return totalTxSize;
611     }
612 
exists(uint256 hash)613     bool exists(uint256 hash) const
614     {
615         LOCK(cs);
616         return (mapTx.count(hash) != 0);
617     }
618 
619     std::shared_ptr<const CTransaction> get(const uint256& hash) const;
620     TxMempoolInfo info(const uint256& hash) const;
621     std::vector<TxMempoolInfo> infoAll() const;
622 
623     /** Estimate fee rate needed to get into the next nBlocks
624      *  If no answer can be given at nBlocks, return an estimate
625      *  at the lowest number of blocks where one can be given
626      */
627     CFeeRate estimateSmartFee(int nBlocks, int *answerFoundAtBlocks = NULL) const;
628 
629     /** Estimate fee rate needed to get into the next nBlocks */
630     CFeeRate estimateFee(int nBlocks) const;
631 
632     /** Estimate priority needed to get into the next nBlocks
633      *  If no answer can be given at nBlocks, return an estimate
634      *  at the lowest number of blocks where one can be given
635      */
636     double estimateSmartPriority(int nBlocks, int *answerFoundAtBlocks = NULL) const;
637 
638     /** Estimate priority needed to get into the next nBlocks */
639     double estimatePriority(int nBlocks) const;
640 
641     /** Write/Read estimates to disk */
642     bool WriteFeeEstimates(CAutoFile& fileout) const;
643     bool ReadFeeEstimates(CAutoFile& filein);
644 
645     size_t DynamicMemoryUsage() const;
646 
647 private:
648     /** UpdateForDescendants is used by UpdateTransactionsFromBlock to update
649      *  the descendants for a single transaction that has been added to the
650      *  mempool but may have child transactions in the mempool, eg during a
651      *  chain reorg.  setExclude is the set of descendant transactions in the
652      *  mempool that must not be accounted for (because any descendants in
653      *  setExclude were added to the mempool after the transaction being
654      *  updated and hence their state is already reflected in the parent
655      *  state).
656      *
657      *  cachedDescendants will be updated with the descendants of the transaction
658      *  being updated, so that future invocations don't need to walk the
659      *  same transaction again, if encountered in another transaction chain.
660      */
661     void UpdateForDescendants(txiter updateIt,
662             cacheMap &cachedDescendants,
663             const std::set<uint256> &setExclude);
664     /** Update ancestors of hash to add/remove it as a descendant transaction. */
665     void UpdateAncestorsOf(bool add, txiter hash, setEntries &setAncestors);
666     /** Set ancestor state for an entry */
667     void UpdateEntryForAncestors(txiter it, const setEntries &setAncestors);
668     /** For each transaction being removed, update ancestors and any direct children.
669       * If updateDescendants is true, then also update in-mempool descendants'
670       * ancestor state. */
671     void UpdateForRemoveFromMempool(const setEntries &entriesToRemove, bool updateDescendants);
672     /** Sever link between specified transaction and direct children. */
673     void UpdateChildrenForRemoval(txiter entry);
674 
675     /** Before calling removeUnchecked for a given transaction,
676      *  UpdateForRemoveFromMempool must be called on the entire (dependent) set
677      *  of transactions being removed at the same time.  We use each
678      *  CTxMemPoolEntry's setMemPoolParents in order to walk ancestors of a
679      *  given transaction that is removed, so we can't remove intermediate
680      *  transactions in a chain before we've updated all the state for the
681      *  removal.
682      */
683     void removeUnchecked(txiter entry);
684 };
685 
686 /**
687  * CCoinsView that brings transactions from a memorypool into view.
688  * It does not check for spendings by memory pool transactions.
689  */
690 class CCoinsViewMemPool : public CCoinsViewBacked
691 {
692 protected:
693     const CTxMemPool& mempool;
694 
695 public:
696     CCoinsViewMemPool(CCoinsView* baseIn, const CTxMemPool& mempoolIn);
697     bool GetCoins(const uint256 &txid, CCoins &coins) const;
698     bool HaveCoins(const uint256 &txid) const;
699 };
700 
701 // We want to sort transactions by coin age priority
702 typedef std::pair<double, CTxMemPool::txiter> TxCoinAgePriority;
703 
704 struct TxCoinAgePriorityCompare
705 {
operatorTxCoinAgePriorityCompare706     bool operator()(const TxCoinAgePriority& a, const TxCoinAgePriority& b)
707     {
708         if (a.first == b.first)
709             return CompareTxMemPoolEntryByScore()(*(b.second), *(a.second)); //Reverse order to make sort less than
710         return a.first < b.first;
711     }
712 };
713 
714 #endif // BITCOIN_TXMEMPOOL_H
715