Fix parameter naming inconsistencies between .h and .cpp files
[bitcoinplatinum.git] / src / txmempool.h
blob4222789510638cddf5a60790dfea94b7e8d14b7e
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.
6 #ifndef BITCOIN_TXMEMPOOL_H
7 #define BITCOIN_TXMEMPOOL_H
9 #include <memory>
10 #include <set>
11 #include <map>
12 #include <vector>
13 #include <utility>
14 #include <string>
16 #include "amount.h"
17 #include "coins.h"
18 #include "indirectmap.h"
19 #include "primitives/transaction.h"
20 #include "sync.h"
21 #include "random.h"
23 #include "boost/multi_index_container.hpp"
24 #include "boost/multi_index/ordered_index.hpp"
25 #include "boost/multi_index/hashed_index.hpp"
27 #include <boost/signals2/signal.hpp>
29 class CAutoFile;
30 class CBlockIndex;
32 /** Fake height value used in CCoins to signify they are only in the memory pool (since 0.8) */
33 static const unsigned int MEMPOOL_HEIGHT = 0x7FFFFFFF;
35 struct LockPoints
37 // Will be set to the blockchain height and median time past
38 // values that would be necessary to satisfy all relative locktime
39 // constraints (BIP68) of this tx given our view of block chain history
40 int height;
41 int64_t time;
42 // As long as the current chain descends from the highest height block
43 // containing one of the inputs used in the calculation, then the cached
44 // values are still valid even after a reorg.
45 CBlockIndex* maxInputBlock;
47 LockPoints() : height(0), time(0), maxInputBlock(NULL) { }
50 class CTxMemPool;
52 /** \class CTxMemPoolEntry
54 * CTxMemPoolEntry stores data about the corresponding transaction, as well
55 * as data about all in-mempool transactions that depend on the transaction
56 * ("descendant" transactions).
58 * When a new entry is added to the mempool, we update the descendant state
59 * (nCountWithDescendants, nSizeWithDescendants, and nModFeesWithDescendants) for
60 * all ancestors of the newly added transaction.
62 * If updating the descendant state is skipped, we can mark the entry as
63 * "dirty", and set nSizeWithDescendants/nModFeesWithDescendants to equal nTxSize/
64 * nFee+feeDelta. (This can potentially happen during a reorg, where we limit the
65 * amount of work we're willing to do to avoid consuming too much CPU.)
69 class CTxMemPoolEntry
71 private:
72 CTransactionRef tx;
73 CAmount nFee; //!< Cached to avoid expensive parent-transaction lookups
74 size_t nTxWeight; //!< ... and avoid recomputing tx weight (also used for GetTxSize())
75 size_t nUsageSize; //!< ... and total memory usage
76 int64_t nTime; //!< Local time when entering the mempool
77 unsigned int entryHeight; //!< Chain height when entering the mempool
78 bool spendsCoinbase; //!< keep track of transactions that spend a coinbase
79 int64_t sigOpCost; //!< Total sigop cost
80 int64_t feeDelta; //!< Used for determining the priority of the transaction for mining in a block
81 LockPoints lockPoints; //!< Track the height and time at which tx was final
83 // Information about descendants of this transaction that are in the
84 // mempool; if we remove this transaction we must remove all of these
85 // descendants as well. if nCountWithDescendants is 0, treat this entry as
86 // dirty, and nSizeWithDescendants and nModFeesWithDescendants will not be
87 // correct.
88 uint64_t nCountWithDescendants; //!< number of descendant transactions
89 uint64_t nSizeWithDescendants; //!< ... and size
90 CAmount nModFeesWithDescendants; //!< ... and total fees (all including us)
92 // Analogous statistics for ancestor transactions
93 uint64_t nCountWithAncestors;
94 uint64_t nSizeWithAncestors;
95 CAmount nModFeesWithAncestors;
96 int64_t nSigOpCostWithAncestors;
98 public:
99 CTxMemPoolEntry(const CTransactionRef& _tx, const CAmount& _nFee,
100 int64_t _nTime, unsigned int _entryHeight,
101 bool spendsCoinbase,
102 int64_t nSigOpsCost, LockPoints lp);
104 CTxMemPoolEntry(const CTxMemPoolEntry& other);
106 const CTransaction& GetTx() const { return *this->tx; }
107 CTransactionRef GetSharedTx() const { return this->tx; }
108 const CAmount& GetFee() const { return nFee; }
109 size_t GetTxSize() const;
110 size_t GetTxWeight() const { return nTxWeight; }
111 int64_t GetTime() const { return nTime; }
112 unsigned int GetHeight() const { return entryHeight; }
113 int64_t GetSigOpCost() const { return sigOpCost; }
114 int64_t GetModifiedFee() const { return nFee + feeDelta; }
115 size_t DynamicMemoryUsage() const { return nUsageSize; }
116 const LockPoints& GetLockPoints() const { return lockPoints; }
118 // Adjusts the descendant state, if this entry is not dirty.
119 void UpdateDescendantState(int64_t modifySize, CAmount modifyFee, int64_t modifyCount);
120 // Adjusts the ancestor state
121 void UpdateAncestorState(int64_t modifySize, CAmount modifyFee, int64_t modifyCount, int modifySigOps);
122 // Updates the fee delta used for mining priority score, and the
123 // modified fees with descendants.
124 void UpdateFeeDelta(int64_t feeDelta);
125 // Update the LockPoints after a reorg
126 void UpdateLockPoints(const LockPoints& lp);
128 uint64_t GetCountWithDescendants() const { return nCountWithDescendants; }
129 uint64_t GetSizeWithDescendants() const { return nSizeWithDescendants; }
130 CAmount GetModFeesWithDescendants() const { return nModFeesWithDescendants; }
132 bool GetSpendsCoinbase() const { return spendsCoinbase; }
134 uint64_t GetCountWithAncestors() const { return nCountWithAncestors; }
135 uint64_t GetSizeWithAncestors() const { return nSizeWithAncestors; }
136 CAmount GetModFeesWithAncestors() const { return nModFeesWithAncestors; }
137 int64_t GetSigOpCostWithAncestors() const { return nSigOpCostWithAncestors; }
139 mutable size_t vTxHashesIdx; //!< Index in mempool's vTxHashes
142 // Helpers for modifying CTxMemPool::mapTx, which is a boost multi_index.
143 struct update_descendant_state
145 update_descendant_state(int64_t _modifySize, CAmount _modifyFee, int64_t _modifyCount) :
146 modifySize(_modifySize), modifyFee(_modifyFee), modifyCount(_modifyCount)
149 void operator() (CTxMemPoolEntry &e)
150 { e.UpdateDescendantState(modifySize, modifyFee, modifyCount); }
152 private:
153 int64_t modifySize;
154 CAmount modifyFee;
155 int64_t modifyCount;
158 struct update_ancestor_state
160 update_ancestor_state(int64_t _modifySize, CAmount _modifyFee, int64_t _modifyCount, int64_t _modifySigOpsCost) :
161 modifySize(_modifySize), modifyFee(_modifyFee), modifyCount(_modifyCount), modifySigOpsCost(_modifySigOpsCost)
164 void operator() (CTxMemPoolEntry &e)
165 { e.UpdateAncestorState(modifySize, modifyFee, modifyCount, modifySigOpsCost); }
167 private:
168 int64_t modifySize;
169 CAmount modifyFee;
170 int64_t modifyCount;
171 int64_t modifySigOpsCost;
174 struct update_fee_delta
176 update_fee_delta(int64_t _feeDelta) : feeDelta(_feeDelta) { }
178 void operator() (CTxMemPoolEntry &e) { e.UpdateFeeDelta(feeDelta); }
180 private:
181 int64_t feeDelta;
184 struct update_lock_points
186 update_lock_points(const LockPoints& _lp) : lp(_lp) { }
188 void operator() (CTxMemPoolEntry &e) { e.UpdateLockPoints(lp); }
190 private:
191 const LockPoints& lp;
194 // extracts a TxMemPoolEntry's transaction hash
195 struct mempoolentry_txid
197 typedef uint256 result_type;
198 result_type operator() (const CTxMemPoolEntry &entry) const
200 return entry.GetTx().GetHash();
204 /** \class CompareTxMemPoolEntryByDescendantScore
206 * Sort an entry by max(score/size of entry's tx, score/size with all descendants).
208 class CompareTxMemPoolEntryByDescendantScore
210 public:
211 bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b)
213 bool fUseADescendants = UseDescendantScore(a);
214 bool fUseBDescendants = UseDescendantScore(b);
216 double aModFee = fUseADescendants ? a.GetModFeesWithDescendants() : a.GetModifiedFee();
217 double aSize = fUseADescendants ? a.GetSizeWithDescendants() : a.GetTxSize();
219 double bModFee = fUseBDescendants ? b.GetModFeesWithDescendants() : b.GetModifiedFee();
220 double bSize = fUseBDescendants ? b.GetSizeWithDescendants() : b.GetTxSize();
222 // Avoid division by rewriting (a/b > c/d) as (a*d > c*b).
223 double f1 = aModFee * bSize;
224 double f2 = aSize * bModFee;
226 if (f1 == f2) {
227 return a.GetTime() >= b.GetTime();
229 return f1 < f2;
232 // Calculate which score to use for an entry (avoiding division).
233 bool UseDescendantScore(const CTxMemPoolEntry &a)
235 double f1 = (double)a.GetModifiedFee() * a.GetSizeWithDescendants();
236 double f2 = (double)a.GetModFeesWithDescendants() * a.GetTxSize();
237 return f2 > f1;
241 /** \class CompareTxMemPoolEntryByScore
243 * Sort by score of entry ((fee+delta)/size) in descending order
245 class CompareTxMemPoolEntryByScore
247 public:
248 bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b)
250 double f1 = (double)a.GetModifiedFee() * b.GetTxSize();
251 double f2 = (double)b.GetModifiedFee() * a.GetTxSize();
252 if (f1 == f2) {
253 return b.GetTx().GetHash() < a.GetTx().GetHash();
255 return f1 > f2;
259 class CompareTxMemPoolEntryByEntryTime
261 public:
262 bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b)
264 return a.GetTime() < b.GetTime();
268 class CompareTxMemPoolEntryByAncestorFee
270 public:
271 bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b)
273 double aFees = a.GetModFeesWithAncestors();
274 double aSize = a.GetSizeWithAncestors();
276 double bFees = b.GetModFeesWithAncestors();
277 double bSize = b.GetSizeWithAncestors();
279 // Avoid division by rewriting (a/b > c/d) as (a*d > c*b).
280 double f1 = aFees * bSize;
281 double f2 = aSize * bFees;
283 if (f1 == f2) {
284 return a.GetTx().GetHash() < b.GetTx().GetHash();
287 return f1 > f2;
291 // Multi_index tag names
292 struct descendant_score {};
293 struct entry_time {};
294 struct mining_score {};
295 struct ancestor_score {};
297 class CBlockPolicyEstimator;
300 * Information about a mempool transaction.
302 struct TxMempoolInfo
304 /** The transaction itself */
305 CTransactionRef tx;
307 /** Time the transaction entered the mempool. */
308 int64_t nTime;
310 /** Feerate of the transaction. */
311 CFeeRate feeRate;
313 /** The fee delta. */
314 int64_t nFeeDelta;
317 /** Reason why a transaction was removed from the mempool,
318 * this is passed to the notification signal.
320 enum class MemPoolRemovalReason {
321 UNKNOWN = 0, //! Manually removed or unknown reason
322 EXPIRY, //! Expired from mempool
323 SIZELIMIT, //! Removed in size limiting
324 REORG, //! Removed for reorganization
325 BLOCK, //! Removed for block
326 CONFLICT, //! Removed for conflict with in-block transaction
327 REPLACED //! Removed for replacement
331 * CTxMemPool stores valid-according-to-the-current-best-chain transactions
332 * that may be included in the next block.
334 * Transactions are added when they are seen on the network (or created by the
335 * local node), but not all transactions seen are added to the pool. For
336 * example, the following new transactions will not be added to the mempool:
337 * - a transaction which doesn't meet the minimum fee requirements.
338 * - a new transaction that double-spends an input of a transaction already in
339 * the pool where the new transaction does not meet the Replace-By-Fee
340 * requirements as defined in BIP 125.
341 * - a non-standard transaction.
343 * CTxMemPool::mapTx, and CTxMemPoolEntry bookkeeping:
345 * mapTx is a boost::multi_index that sorts the mempool on 4 criteria:
346 * - transaction hash
347 * - feerate [we use max(feerate of tx, feerate of tx with all descendants)]
348 * - time in mempool
349 * - mining score (feerate modified by any fee deltas from PrioritiseTransaction)
351 * Note: the term "descendant" refers to in-mempool transactions that depend on
352 * this one, while "ancestor" refers to in-mempool transactions that a given
353 * transaction depends on.
355 * In order for the feerate sort to remain correct, we must update transactions
356 * in the mempool when new descendants arrive. To facilitate this, we track
357 * the set of in-mempool direct parents and direct children in mapLinks. Within
358 * each CTxMemPoolEntry, we track the size and fees of all descendants.
360 * Usually when a new transaction is added to the mempool, it has no in-mempool
361 * children (because any such children would be an orphan). So in
362 * addUnchecked(), we:
363 * - update a new entry's setMemPoolParents to include all in-mempool parents
364 * - update the new entry's direct parents to include the new tx as a child
365 * - update all ancestors of the transaction to include the new tx's size/fee
367 * When a transaction is removed from the mempool, we must:
368 * - update all in-mempool parents to not track the tx in setMemPoolChildren
369 * - update all ancestors to not include the tx's size/fees in descendant state
370 * - update all in-mempool children to not include it as a parent
372 * These happen in UpdateForRemoveFromMempool(). (Note that when removing a
373 * transaction along with its descendants, we must calculate that set of
374 * transactions to be removed before doing the removal, or else the mempool can
375 * be in an inconsistent state where it's impossible to walk the ancestors of
376 * a transaction.)
378 * In the event of a reorg, the assumption that a newly added tx has no
379 * in-mempool children is false. In particular, the mempool is in an
380 * inconsistent state while new transactions are being added, because there may
381 * be descendant transactions of a tx coming from a disconnected block that are
382 * unreachable from just looking at transactions in the mempool (the linking
383 * transactions may also be in the disconnected block, waiting to be added).
384 * Because of this, there's not much benefit in trying to search for in-mempool
385 * children in addUnchecked(). Instead, in the special case of transactions
386 * being added from a disconnected block, we require the caller to clean up the
387 * state, to account for in-mempool, out-of-block descendants for all the
388 * in-block transactions by calling UpdateTransactionsFromBlock(). Note that
389 * until this is called, the mempool state is not consistent, and in particular
390 * mapLinks may not be correct (and therefore functions like
391 * CalculateMemPoolAncestors() and CalculateDescendants() that rely
392 * on them to walk the mempool are not generally safe to use).
394 * Computational limits:
396 * Updating all in-mempool ancestors of a newly added transaction can be slow,
397 * if no bound exists on how many in-mempool ancestors there may be.
398 * CalculateMemPoolAncestors() takes configurable limits that are designed to
399 * prevent these calculations from being too CPU intensive.
401 * Adding transactions from a disconnected block can be very time consuming,
402 * because we don't have a way to limit the number of in-mempool descendants.
403 * To bound CPU processing, we limit the amount of work we're willing to do
404 * to properly update the descendant information for a tx being added from
405 * a disconnected block. If we would exceed the limit, then we instead mark
406 * the entry as "dirty", and set the feerate for sorting purposes to be equal
407 * the feerate of the transaction without any descendants.
410 class CTxMemPool
412 private:
413 uint32_t nCheckFrequency; //!< Value n means that n times in 2^32 we check.
414 unsigned int nTransactionsUpdated;
415 CBlockPolicyEstimator* minerPolicyEstimator;
417 uint64_t totalTxSize; //!< sum of all mempool tx's virtual sizes. Differs from serialized tx size since witness data is discounted. Defined in BIP 141.
418 uint64_t cachedInnerUsage; //!< sum of dynamic memory usage of all the map elements (NOT the maps themselves)
420 mutable int64_t lastRollingFeeUpdate;
421 mutable bool blockSinceLastRollingFeeBump;
422 mutable double rollingMinimumFeeRate; //!< minimum fee to get into the pool, decreases exponentially
424 void trackPackageRemoved(const CFeeRate& rate);
426 public:
428 static const int ROLLING_FEE_HALFLIFE = 60 * 60 * 12; // public only for testing
430 typedef boost::multi_index_container<
431 CTxMemPoolEntry,
432 boost::multi_index::indexed_by<
433 // sorted by txid
434 boost::multi_index::hashed_unique<mempoolentry_txid, SaltedTxidHasher>,
435 // sorted by fee rate
436 boost::multi_index::ordered_non_unique<
437 boost::multi_index::tag<descendant_score>,
438 boost::multi_index::identity<CTxMemPoolEntry>,
439 CompareTxMemPoolEntryByDescendantScore
441 // sorted by entry time
442 boost::multi_index::ordered_non_unique<
443 boost::multi_index::tag<entry_time>,
444 boost::multi_index::identity<CTxMemPoolEntry>,
445 CompareTxMemPoolEntryByEntryTime
447 // sorted by score (for mining prioritization)
448 boost::multi_index::ordered_unique<
449 boost::multi_index::tag<mining_score>,
450 boost::multi_index::identity<CTxMemPoolEntry>,
451 CompareTxMemPoolEntryByScore
453 // sorted by fee rate with ancestors
454 boost::multi_index::ordered_non_unique<
455 boost::multi_index::tag<ancestor_score>,
456 boost::multi_index::identity<CTxMemPoolEntry>,
457 CompareTxMemPoolEntryByAncestorFee
460 > indexed_transaction_set;
462 mutable CCriticalSection cs;
463 indexed_transaction_set mapTx;
465 typedef indexed_transaction_set::nth_index<0>::type::iterator txiter;
466 std::vector<std::pair<uint256, txiter> > vTxHashes; //!< All tx witness hashes/entries in mapTx, in random order
468 struct CompareIteratorByHash {
469 bool operator()(const txiter &a, const txiter &b) const {
470 return a->GetTx().GetHash() < b->GetTx().GetHash();
473 typedef std::set<txiter, CompareIteratorByHash> setEntries;
475 const setEntries & GetMemPoolParents(txiter entry) const;
476 const setEntries & GetMemPoolChildren(txiter entry) const;
477 private:
478 typedef std::map<txiter, setEntries, CompareIteratorByHash> cacheMap;
480 struct TxLinks {
481 setEntries parents;
482 setEntries children;
485 typedef std::map<txiter, TxLinks, CompareIteratorByHash> txlinksMap;
486 txlinksMap mapLinks;
488 void UpdateParent(txiter entry, txiter parent, bool add);
489 void UpdateChild(txiter entry, txiter child, bool add);
491 std::vector<indexed_transaction_set::const_iterator> GetSortedDepthAndScore() const;
493 public:
494 indirectmap<COutPoint, const CTransaction*> mapNextTx;
495 std::map<uint256, CAmount> mapDeltas;
497 /** Create a new CTxMemPool.
499 CTxMemPool();
500 ~CTxMemPool();
503 * If sanity-checking is turned on, check makes sure the pool is
504 * consistent (does not contain two transactions that spend the same inputs,
505 * all inputs are in the mapNextTx array). If sanity-checking is turned off,
506 * check does nothing.
508 void check(const CCoinsViewCache *pcoins) const;
509 void setSanityCheck(double dFrequency = 1.0) { nCheckFrequency = dFrequency * 4294967295.0; }
511 // addUnchecked must updated state for all ancestors of a given transaction,
512 // to track size/count of descendant transactions. First version of
513 // addUnchecked can be used to have it call CalculateMemPoolAncestors(), and
514 // then invoke the second version.
515 bool addUnchecked(const uint256& hash, const CTxMemPoolEntry &entry, bool validFeeEstimate = true);
516 bool addUnchecked(const uint256& hash, const CTxMemPoolEntry &entry, setEntries &setAncestors, bool validFeeEstimate = true);
518 void removeRecursive(const CTransaction &tx, MemPoolRemovalReason reason = MemPoolRemovalReason::UNKNOWN);
519 void removeForReorg(const CCoinsViewCache *pcoins, unsigned int nMemPoolHeight, int flags);
520 void removeConflicts(const CTransaction &tx);
521 void removeForBlock(const std::vector<CTransactionRef>& vtx, unsigned int nBlockHeight);
523 void clear();
524 void _clear(); //lock free
525 bool CompareDepthAndScore(const uint256& hasha, const uint256& hashb);
526 void queryHashes(std::vector<uint256>& vtxid);
527 void pruneSpent(const uint256& hash, CCoins &coins);
528 unsigned int GetTransactionsUpdated() const;
529 void AddTransactionsUpdated(unsigned int n);
531 * Check that none of this transactions inputs are in the mempool, and thus
532 * the tx is not dependent on other mempool transactions to be included in a block.
534 bool HasNoInputsOf(const CTransaction& tx) const;
536 /** Affect CreateNewBlock prioritisation of transactions */
537 void PrioritiseTransaction(const uint256& hash, const CAmount& nFeeDelta);
538 void ApplyDelta(const uint256 hash, CAmount &nFeeDelta) const;
539 void ClearPrioritisation(const uint256 hash);
541 public:
542 /** Remove a set of transactions from the mempool.
543 * If a transaction is in this set, then all in-mempool descendants must
544 * also be in the set, unless this transaction is being removed for being
545 * in a block.
546 * Set updateDescendants to true when removing a tx that was in a block, so
547 * that any in-mempool descendants have their ancestor state updated.
549 void RemoveStaged(setEntries &stage, bool updateDescendants, MemPoolRemovalReason reason = MemPoolRemovalReason::UNKNOWN);
551 /** When adding transactions from a disconnected block back to the mempool,
552 * new mempool entries may have children in the mempool (which is generally
553 * not the case when otherwise adding transactions).
554 * UpdateTransactionsFromBlock() will find child transactions and update the
555 * descendant state for each transaction in vHashesToUpdate (excluding any
556 * child transactions present in vHashesToUpdate, which are already accounted
557 * for). Note: vHashesToUpdate should be the set of transactions from the
558 * disconnected block that have been accepted back into the mempool.
560 void UpdateTransactionsFromBlock(const std::vector<uint256> &vHashesToUpdate);
562 /** Try to calculate all in-mempool ancestors of entry.
563 * (these are all calculated including the tx itself)
564 * limitAncestorCount = max number of ancestors
565 * limitAncestorSize = max size of ancestors
566 * limitDescendantCount = max number of descendants any ancestor can have
567 * limitDescendantSize = max size of descendants any ancestor can have
568 * errString = populated with error reason if any limits are hit
569 * fSearchForParents = whether to search a tx's vin for in-mempool parents, or
570 * look up parents from mapLinks. Must be true for entries not in the mempool
572 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;
574 /** Populate setDescendants with all in-mempool descendants of hash.
575 * Assumes that setDescendants includes all in-mempool descendants of anything
576 * already in it. */
577 void CalculateDescendants(txiter it, setEntries &setDescendants);
579 /** The minimum fee to get into the mempool, which may itself not be enough
580 * for larger-sized transactions.
581 * The incrementalRelayFee policy variable is used to bound the time it
582 * takes the fee rate to go back down all the way to 0. When the feerate
583 * would otherwise be half of this, it is set to 0 instead.
585 CFeeRate GetMinFee(size_t sizelimit) const;
587 /** Remove transactions from the mempool until its dynamic size is <= sizelimit.
588 * pvNoSpendsRemaining, if set, will be populated with the list of transactions
589 * which are not in mempool which no longer have any spends in this mempool.
591 void TrimToSize(size_t sizelimit, std::vector<uint256>* pvNoSpendsRemaining=NULL);
593 /** Expire all transaction (and their dependencies) in the mempool older than time. Return the number of removed transactions. */
594 int Expire(int64_t time);
596 /** Returns false if the transaction is in the mempool and not within the chain limit specified. */
597 bool TransactionWithinChainLimit(const uint256& txid, size_t chainLimit) const;
599 unsigned long size()
601 LOCK(cs);
602 return mapTx.size();
605 uint64_t GetTotalTxSize()
607 LOCK(cs);
608 return totalTxSize;
611 bool exists(uint256 hash) const
613 LOCK(cs);
614 return (mapTx.count(hash) != 0);
617 CTransactionRef get(const uint256& hash) const;
618 TxMempoolInfo info(const uint256& hash) const;
619 std::vector<TxMempoolInfo> infoAll() const;
621 /** Estimate fee rate needed to get into the next nBlocks
622 * If no answer can be given at nBlocks, return an estimate
623 * at the lowest number of blocks where one can be given
625 CFeeRate estimateSmartFee(int nBlocks, int *answerFoundAtBlocks = NULL) const;
627 /** Estimate fee rate needed to get into the next nBlocks */
628 CFeeRate estimateFee(int nBlocks) const;
630 /** Write/Read estimates to disk */
631 bool WriteFeeEstimates(CAutoFile& fileout) const;
632 bool ReadFeeEstimates(CAutoFile& filein);
634 size_t DynamicMemoryUsage() const;
636 boost::signals2::signal<void (CTransactionRef)> NotifyEntryAdded;
637 boost::signals2::signal<void (CTransactionRef, MemPoolRemovalReason)> NotifyEntryRemoved;
639 private:
640 /** UpdateForDescendants is used by UpdateTransactionsFromBlock to update
641 * the descendants for a single transaction that has been added to the
642 * mempool but may have child transactions in the mempool, eg during a
643 * chain reorg. setExclude is the set of descendant transactions in the
644 * mempool that must not be accounted for (because any descendants in
645 * setExclude were added to the mempool after the transaction being
646 * updated and hence their state is already reflected in the parent
647 * state).
649 * cachedDescendants will be updated with the descendants of the transaction
650 * being updated, so that future invocations don't need to walk the
651 * same transaction again, if encountered in another transaction chain.
653 void UpdateForDescendants(txiter updateIt,
654 cacheMap &cachedDescendants,
655 const std::set<uint256> &setExclude);
656 /** Update ancestors of hash to add/remove it as a descendant transaction. */
657 void UpdateAncestorsOf(bool add, txiter hash, setEntries &setAncestors);
658 /** Set ancestor state for an entry */
659 void UpdateEntryForAncestors(txiter it, const setEntries &setAncestors);
660 /** For each transaction being removed, update ancestors and any direct children.
661 * If updateDescendants is true, then also update in-mempool descendants'
662 * ancestor state. */
663 void UpdateForRemoveFromMempool(const setEntries &entriesToRemove, bool updateDescendants);
664 /** Sever link between specified transaction and direct children. */
665 void UpdateChildrenForRemoval(txiter entry);
667 /** Before calling removeUnchecked for a given transaction,
668 * UpdateForRemoveFromMempool must be called on the entire (dependent) set
669 * of transactions being removed at the same time. We use each
670 * CTxMemPoolEntry's setMemPoolParents in order to walk ancestors of a
671 * given transaction that is removed, so we can't remove intermediate
672 * transactions in a chain before we've updated all the state for the
673 * removal.
675 void removeUnchecked(txiter entry, MemPoolRemovalReason reason = MemPoolRemovalReason::UNKNOWN);
678 /**
679 * CCoinsView that brings transactions from a memorypool into view.
680 * It does not check for spendings by memory pool transactions.
682 class CCoinsViewMemPool : public CCoinsViewBacked
684 protected:
685 const CTxMemPool& mempool;
687 public:
688 CCoinsViewMemPool(CCoinsView* baseIn, const CTxMemPool& mempoolIn);
689 bool GetCoins(const uint256 &txid, CCoins &coins) const;
690 bool HaveCoins(const uint256 &txid) const;
693 #endif // BITCOIN_TXMEMPOOL_H