Remove unused variable int64_t nEnd
[bitcoinplatinum.git] / src / txmempool.h
blobd272114a7c551e29f687e38fec85f8ad05cf5431
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 "policy/feerate.h"
20 #include "primitives/transaction.h"
21 #include "sync.h"
22 #include "random.h"
24 #include "boost/multi_index_container.hpp"
25 #include "boost/multi_index/ordered_index.hpp"
26 #include "boost/multi_index/hashed_index.hpp"
27 #include <boost/multi_index/sequenced_index.hpp>
29 #include <boost/signals2/signal.hpp>
31 class CBlockIndex;
33 /** Fake height value used in Coin to signify they are only in the memory pool (since 0.8) */
34 static const uint32_t MEMPOOL_HEIGHT = 0x7FFFFFFF;
36 struct LockPoints
38 // Will be set to the blockchain height and median time past
39 // values that would be necessary to satisfy all relative locktime
40 // constraints (BIP68) of this tx given our view of block chain history
41 int height;
42 int64_t time;
43 // As long as the current chain descends from the highest height block
44 // containing one of the inputs used in the calculation, then the cached
45 // values are still valid even after a reorg.
46 CBlockIndex* maxInputBlock;
48 LockPoints() : height(0), time(0), maxInputBlock(NULL) { }
51 class CTxMemPool;
53 /** \class CTxMemPoolEntry
55 * CTxMemPoolEntry stores data about the corresponding transaction, as well
56 * as data about all in-mempool transactions that depend on the transaction
57 * ("descendant" transactions).
59 * When a new entry is added to the mempool, we update the descendant state
60 * (nCountWithDescendants, nSizeWithDescendants, and nModFeesWithDescendants) for
61 * all ancestors of the newly added transaction.
65 class CTxMemPoolEntry
67 private:
68 CTransactionRef tx;
69 CAmount nFee; //!< Cached to avoid expensive parent-transaction lookups
70 size_t nTxWeight; //!< ... and avoid recomputing tx weight (also used for GetTxSize())
71 size_t nUsageSize; //!< ... and total memory usage
72 int64_t nTime; //!< Local time when entering the mempool
73 unsigned int entryHeight; //!< Chain height when entering the mempool
74 bool spendsCoinbase; //!< keep track of transactions that spend a coinbase
75 int64_t sigOpCost; //!< Total sigop cost
76 int64_t feeDelta; //!< Used for determining the priority of the transaction for mining in a block
77 LockPoints lockPoints; //!< Track the height and time at which tx was final
79 // Information about descendants of this transaction that are in the
80 // mempool; if we remove this transaction we must remove all of these
81 // descendants as well.
82 uint64_t nCountWithDescendants; //!< number of descendant transactions
83 uint64_t nSizeWithDescendants; //!< ... and size
84 CAmount nModFeesWithDescendants; //!< ... and total fees (all including us)
86 // Analogous statistics for ancestor transactions
87 uint64_t nCountWithAncestors;
88 uint64_t nSizeWithAncestors;
89 CAmount nModFeesWithAncestors;
90 int64_t nSigOpCostWithAncestors;
92 public:
93 CTxMemPoolEntry(const CTransactionRef& _tx, const CAmount& _nFee,
94 int64_t _nTime, unsigned int _entryHeight,
95 bool spendsCoinbase,
96 int64_t nSigOpsCost, LockPoints lp);
98 CTxMemPoolEntry(const CTxMemPoolEntry& other);
100 const CTransaction& GetTx() const { return *this->tx; }
101 CTransactionRef GetSharedTx() const { return this->tx; }
102 const CAmount& GetFee() const { return nFee; }
103 size_t GetTxSize() const;
104 size_t GetTxWeight() const { return nTxWeight; }
105 int64_t GetTime() const { return nTime; }
106 unsigned int GetHeight() const { return entryHeight; }
107 int64_t GetSigOpCost() const { return sigOpCost; }
108 int64_t GetModifiedFee() const { return nFee + feeDelta; }
109 size_t DynamicMemoryUsage() const { return nUsageSize; }
110 const LockPoints& GetLockPoints() const { return lockPoints; }
112 // Adjusts the descendant state.
113 void UpdateDescendantState(int64_t modifySize, CAmount modifyFee, int64_t modifyCount);
114 // Adjusts the ancestor state
115 void UpdateAncestorState(int64_t modifySize, CAmount modifyFee, int64_t modifyCount, int modifySigOps);
116 // Updates the fee delta used for mining priority score, and the
117 // modified fees with descendants.
118 void UpdateFeeDelta(int64_t feeDelta);
119 // Update the LockPoints after a reorg
120 void UpdateLockPoints(const LockPoints& lp);
122 uint64_t GetCountWithDescendants() const { return nCountWithDescendants; }
123 uint64_t GetSizeWithDescendants() const { return nSizeWithDescendants; }
124 CAmount GetModFeesWithDescendants() const { return nModFeesWithDescendants; }
126 bool GetSpendsCoinbase() const { return spendsCoinbase; }
128 uint64_t GetCountWithAncestors() const { return nCountWithAncestors; }
129 uint64_t GetSizeWithAncestors() const { return nSizeWithAncestors; }
130 CAmount GetModFeesWithAncestors() const { return nModFeesWithAncestors; }
131 int64_t GetSigOpCostWithAncestors() const { return nSigOpCostWithAncestors; }
133 mutable size_t vTxHashesIdx; //!< Index in mempool's vTxHashes
136 // Helpers for modifying CTxMemPool::mapTx, which is a boost multi_index.
137 struct update_descendant_state
139 update_descendant_state(int64_t _modifySize, CAmount _modifyFee, int64_t _modifyCount) :
140 modifySize(_modifySize), modifyFee(_modifyFee), modifyCount(_modifyCount)
143 void operator() (CTxMemPoolEntry &e)
144 { e.UpdateDescendantState(modifySize, modifyFee, modifyCount); }
146 private:
147 int64_t modifySize;
148 CAmount modifyFee;
149 int64_t modifyCount;
152 struct update_ancestor_state
154 update_ancestor_state(int64_t _modifySize, CAmount _modifyFee, int64_t _modifyCount, int64_t _modifySigOpsCost) :
155 modifySize(_modifySize), modifyFee(_modifyFee), modifyCount(_modifyCount), modifySigOpsCost(_modifySigOpsCost)
158 void operator() (CTxMemPoolEntry &e)
159 { e.UpdateAncestorState(modifySize, modifyFee, modifyCount, modifySigOpsCost); }
161 private:
162 int64_t modifySize;
163 CAmount modifyFee;
164 int64_t modifyCount;
165 int64_t modifySigOpsCost;
168 struct update_fee_delta
170 update_fee_delta(int64_t _feeDelta) : feeDelta(_feeDelta) { }
172 void operator() (CTxMemPoolEntry &e) { e.UpdateFeeDelta(feeDelta); }
174 private:
175 int64_t feeDelta;
178 struct update_lock_points
180 update_lock_points(const LockPoints& _lp) : lp(_lp) { }
182 void operator() (CTxMemPoolEntry &e) { e.UpdateLockPoints(lp); }
184 private:
185 const LockPoints& lp;
188 // extracts a transaction hash from CTxMempoolEntry or CTransactionRef
189 struct mempoolentry_txid
191 typedef uint256 result_type;
192 result_type operator() (const CTxMemPoolEntry &entry) const
194 return entry.GetTx().GetHash();
197 result_type operator() (const CTransactionRef& tx) const
199 return tx->GetHash();
203 /** \class CompareTxMemPoolEntryByDescendantScore
205 * Sort an entry by max(score/size of entry's tx, score/size with all descendants).
207 class CompareTxMemPoolEntryByDescendantScore
209 public:
210 bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b)
212 bool fUseADescendants = UseDescendantScore(a);
213 bool fUseBDescendants = UseDescendantScore(b);
215 double aModFee = fUseADescendants ? a.GetModFeesWithDescendants() : a.GetModifiedFee();
216 double aSize = fUseADescendants ? a.GetSizeWithDescendants() : a.GetTxSize();
218 double bModFee = fUseBDescendants ? b.GetModFeesWithDescendants() : b.GetModifiedFee();
219 double bSize = fUseBDescendants ? b.GetSizeWithDescendants() : b.GetTxSize();
221 // Avoid division by rewriting (a/b > c/d) as (a*d > c*b).
222 double f1 = aModFee * bSize;
223 double f2 = aSize * bModFee;
225 if (f1 == f2) {
226 return a.GetTime() >= b.GetTime();
228 return f1 < f2;
231 // Calculate which score to use for an entry (avoiding division).
232 bool UseDescendantScore(const CTxMemPoolEntry &a)
234 double f1 = (double)a.GetModifiedFee() * a.GetSizeWithDescendants();
235 double f2 = (double)a.GetModFeesWithDescendants() * a.GetTxSize();
236 return f2 > f1;
240 /** \class CompareTxMemPoolEntryByScore
242 * Sort by score of entry ((fee+delta)/size) in descending order
244 class CompareTxMemPoolEntryByScore
246 public:
247 bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b)
249 double f1 = (double)a.GetModifiedFee() * b.GetTxSize();
250 double f2 = (double)b.GetModifiedFee() * a.GetTxSize();
251 if (f1 == f2) {
252 return b.GetTx().GetHash() < a.GetTx().GetHash();
254 return f1 > f2;
258 class CompareTxMemPoolEntryByEntryTime
260 public:
261 bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b)
263 return a.GetTime() < b.GetTime();
267 class CompareTxMemPoolEntryByAncestorFee
269 public:
270 bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b)
272 double aFees = a.GetModFeesWithAncestors();
273 double aSize = a.GetSizeWithAncestors();
275 double bFees = b.GetModFeesWithAncestors();
276 double bSize = b.GetSizeWithAncestors();
278 // Avoid division by rewriting (a/b > c/d) as (a*d > c*b).
279 double f1 = aFees * bSize;
280 double f2 = aSize * bFees;
282 if (f1 == f2) {
283 return a.GetTx().GetHash() < b.GetTx().GetHash();
286 return f1 > f2;
290 // Multi_index tag names
291 struct descendant_score {};
292 struct entry_time {};
293 struct mining_score {};
294 struct ancestor_score {};
296 class CBlockPolicyEstimator;
299 * Information about a mempool transaction.
301 struct TxMempoolInfo
303 /** The transaction itself */
304 CTransactionRef tx;
306 /** Time the transaction entered the mempool. */
307 int64_t nTime;
309 /** Feerate of the transaction. */
310 CFeeRate feeRate;
312 /** The fee delta. */
313 int64_t nFeeDelta;
316 /** Reason why a transaction was removed from the mempool,
317 * this is passed to the notification signal.
319 enum class MemPoolRemovalReason {
320 UNKNOWN = 0, //! Manually removed or unknown reason
321 EXPIRY, //! Expired from mempool
322 SIZELIMIT, //! Removed in size limiting
323 REORG, //! Removed for reorganization
324 BLOCK, //! Removed for block
325 CONFLICT, //! Removed for conflict with in-block transaction
326 REPLACED //! Removed for replacement
329 class SaltedTxidHasher
331 private:
332 /** Salt */
333 const uint64_t k0, k1;
335 public:
336 SaltedTxidHasher();
338 size_t operator()(const uint256& txid) const {
339 return SipHashUint256(k0, k1, txid);
344 * CTxMemPool stores valid-according-to-the-current-best-chain transactions
345 * that may be included in the next block.
347 * Transactions are added when they are seen on the network (or created by the
348 * local node), but not all transactions seen are added to the pool. For
349 * example, the following new transactions will not be added to the mempool:
350 * - a transaction which doesn't meet the minimum fee requirements.
351 * - a new transaction that double-spends an input of a transaction already in
352 * the pool where the new transaction does not meet the Replace-By-Fee
353 * requirements as defined in BIP 125.
354 * - a non-standard transaction.
356 * CTxMemPool::mapTx, and CTxMemPoolEntry bookkeeping:
358 * mapTx is a boost::multi_index that sorts the mempool on 4 criteria:
359 * - transaction hash
360 * - feerate [we use max(feerate of tx, feerate of tx with all descendants)]
361 * - time in mempool
362 * - mining score (feerate modified by any fee deltas from PrioritiseTransaction)
364 * Note: the term "descendant" refers to in-mempool transactions that depend on
365 * this one, while "ancestor" refers to in-mempool transactions that a given
366 * transaction depends on.
368 * In order for the feerate sort to remain correct, we must update transactions
369 * in the mempool when new descendants arrive. To facilitate this, we track
370 * the set of in-mempool direct parents and direct children in mapLinks. Within
371 * each CTxMemPoolEntry, we track the size and fees of all descendants.
373 * Usually when a new transaction is added to the mempool, it has no in-mempool
374 * children (because any such children would be an orphan). So in
375 * addUnchecked(), we:
376 * - update a new entry's setMemPoolParents to include all in-mempool parents
377 * - update the new entry's direct parents to include the new tx as a child
378 * - update all ancestors of the transaction to include the new tx's size/fee
380 * When a transaction is removed from the mempool, we must:
381 * - update all in-mempool parents to not track the tx in setMemPoolChildren
382 * - update all ancestors to not include the tx's size/fees in descendant state
383 * - update all in-mempool children to not include it as a parent
385 * These happen in UpdateForRemoveFromMempool(). (Note that when removing a
386 * transaction along with its descendants, we must calculate that set of
387 * transactions to be removed before doing the removal, or else the mempool can
388 * be in an inconsistent state where it's impossible to walk the ancestors of
389 * a transaction.)
391 * In the event of a reorg, the assumption that a newly added tx has no
392 * in-mempool children is false. In particular, the mempool is in an
393 * inconsistent state while new transactions are being added, because there may
394 * be descendant transactions of a tx coming from a disconnected block that are
395 * unreachable from just looking at transactions in the mempool (the linking
396 * transactions may also be in the disconnected block, waiting to be added).
397 * Because of this, there's not much benefit in trying to search for in-mempool
398 * children in addUnchecked(). Instead, in the special case of transactions
399 * being added from a disconnected block, we require the caller to clean up the
400 * state, to account for in-mempool, out-of-block descendants for all the
401 * in-block transactions by calling UpdateTransactionsFromBlock(). Note that
402 * until this is called, the mempool state is not consistent, and in particular
403 * mapLinks may not be correct (and therefore functions like
404 * CalculateMemPoolAncestors() and CalculateDescendants() that rely
405 * on them to walk the mempool are not generally safe to use).
407 * Computational limits:
409 * Updating all in-mempool ancestors of a newly added transaction can be slow,
410 * if no bound exists on how many in-mempool ancestors there may be.
411 * CalculateMemPoolAncestors() takes configurable limits that are designed to
412 * prevent these calculations from being too CPU intensive.
415 class CTxMemPool
417 private:
418 uint32_t nCheckFrequency; //!< Value n means that n times in 2^32 we check.
419 unsigned int nTransactionsUpdated; //!< Used by getblocktemplate to trigger CreateNewBlock() invocation
420 CBlockPolicyEstimator* minerPolicyEstimator;
422 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.
423 uint64_t cachedInnerUsage; //!< sum of dynamic memory usage of all the map elements (NOT the maps themselves)
425 mutable int64_t lastRollingFeeUpdate;
426 mutable bool blockSinceLastRollingFeeBump;
427 mutable double rollingMinimumFeeRate; //!< minimum fee to get into the pool, decreases exponentially
429 void trackPackageRemoved(const CFeeRate& rate);
431 public:
433 static const int ROLLING_FEE_HALFLIFE = 60 * 60 * 12; // public only for testing
435 typedef boost::multi_index_container<
436 CTxMemPoolEntry,
437 boost::multi_index::indexed_by<
438 // sorted by txid
439 boost::multi_index::hashed_unique<mempoolentry_txid, SaltedTxidHasher>,
440 // sorted by fee rate
441 boost::multi_index::ordered_non_unique<
442 boost::multi_index::tag<descendant_score>,
443 boost::multi_index::identity<CTxMemPoolEntry>,
444 CompareTxMemPoolEntryByDescendantScore
446 // sorted by entry time
447 boost::multi_index::ordered_non_unique<
448 boost::multi_index::tag<entry_time>,
449 boost::multi_index::identity<CTxMemPoolEntry>,
450 CompareTxMemPoolEntryByEntryTime
452 // sorted by score (for mining prioritization)
453 boost::multi_index::ordered_unique<
454 boost::multi_index::tag<mining_score>,
455 boost::multi_index::identity<CTxMemPoolEntry>,
456 CompareTxMemPoolEntryByScore
458 // sorted by fee rate with ancestors
459 boost::multi_index::ordered_non_unique<
460 boost::multi_index::tag<ancestor_score>,
461 boost::multi_index::identity<CTxMemPoolEntry>,
462 CompareTxMemPoolEntryByAncestorFee
465 > indexed_transaction_set;
467 mutable CCriticalSection cs;
468 indexed_transaction_set mapTx;
470 typedef indexed_transaction_set::nth_index<0>::type::iterator txiter;
471 std::vector<std::pair<uint256, txiter> > vTxHashes; //!< All tx witness hashes/entries in mapTx, in random order
473 struct CompareIteratorByHash {
474 bool operator()(const txiter &a, const txiter &b) const {
475 return a->GetTx().GetHash() < b->GetTx().GetHash();
478 typedef std::set<txiter, CompareIteratorByHash> setEntries;
480 const setEntries & GetMemPoolParents(txiter entry) const;
481 const setEntries & GetMemPoolChildren(txiter entry) const;
482 private:
483 typedef std::map<txiter, setEntries, CompareIteratorByHash> cacheMap;
485 struct TxLinks {
486 setEntries parents;
487 setEntries children;
490 typedef std::map<txiter, TxLinks, CompareIteratorByHash> txlinksMap;
491 txlinksMap mapLinks;
493 void UpdateParent(txiter entry, txiter parent, bool add);
494 void UpdateChild(txiter entry, txiter child, bool add);
496 std::vector<indexed_transaction_set::const_iterator> GetSortedDepthAndScore() const;
498 public:
499 indirectmap<COutPoint, const CTransaction*> mapNextTx;
500 std::map<uint256, CAmount> mapDeltas;
502 /** Create a new CTxMemPool.
504 CTxMemPool(CBlockPolicyEstimator* estimator = nullptr);
507 * If sanity-checking is turned on, check makes sure the pool is
508 * consistent (does not contain two transactions that spend the same inputs,
509 * all inputs are in the mapNextTx array). If sanity-checking is turned off,
510 * check does nothing.
512 void check(const CCoinsViewCache *pcoins) const;
513 void setSanityCheck(double dFrequency = 1.0) { nCheckFrequency = dFrequency * 4294967295.0; }
515 // addUnchecked must updated state for all ancestors of a given transaction,
516 // to track size/count of descendant transactions. First version of
517 // addUnchecked can be used to have it call CalculateMemPoolAncestors(), and
518 // then invoke the second version.
519 bool addUnchecked(const uint256& hash, const CTxMemPoolEntry &entry, bool validFeeEstimate = true);
520 bool addUnchecked(const uint256& hash, const CTxMemPoolEntry &entry, setEntries &setAncestors, bool validFeeEstimate = true);
522 void removeRecursive(const CTransaction &tx, MemPoolRemovalReason reason = MemPoolRemovalReason::UNKNOWN);
523 void removeForReorg(const CCoinsViewCache *pcoins, unsigned int nMemPoolHeight, int flags);
524 void removeConflicts(const CTransaction &tx);
525 void removeForBlock(const std::vector<CTransactionRef>& vtx, unsigned int nBlockHeight);
527 void clear();
528 void _clear(); //lock free
529 bool CompareDepthAndScore(const uint256& hasha, const uint256& hashb);
530 void queryHashes(std::vector<uint256>& vtxid);
531 bool isSpent(const COutPoint& outpoint);
532 unsigned int GetTransactionsUpdated() const;
533 void AddTransactionsUpdated(unsigned int n);
535 * Check that none of this transactions inputs are in the mempool, and thus
536 * the tx is not dependent on other mempool transactions to be included in a block.
538 bool HasNoInputsOf(const CTransaction& tx) const;
540 /** Affect CreateNewBlock prioritisation of transactions */
541 void PrioritiseTransaction(const uint256& hash, const CAmount& nFeeDelta);
542 void ApplyDelta(const uint256 hash, CAmount &nFeeDelta) const;
543 void ClearPrioritisation(const uint256 hash);
545 public:
546 /** Remove a set of transactions from the mempool.
547 * If a transaction is in this set, then all in-mempool descendants must
548 * also be in the set, unless this transaction is being removed for being
549 * in a block.
550 * Set updateDescendants to true when removing a tx that was in a block, so
551 * that any in-mempool descendants have their ancestor state updated.
553 void RemoveStaged(setEntries &stage, bool updateDescendants, MemPoolRemovalReason reason = MemPoolRemovalReason::UNKNOWN);
555 /** When adding transactions from a disconnected block back to the mempool,
556 * new mempool entries may have children in the mempool (which is generally
557 * not the case when otherwise adding transactions).
558 * UpdateTransactionsFromBlock() will find child transactions and update the
559 * descendant state for each transaction in vHashesToUpdate (excluding any
560 * child transactions present in vHashesToUpdate, which are already accounted
561 * for). Note: vHashesToUpdate should be the set of transactions from the
562 * disconnected block that have been accepted back into the mempool.
564 void UpdateTransactionsFromBlock(const std::vector<uint256> &vHashesToUpdate);
566 /** Try to calculate all in-mempool ancestors of entry.
567 * (these are all calculated including the tx itself)
568 * limitAncestorCount = max number of ancestors
569 * limitAncestorSize = max size of ancestors
570 * limitDescendantCount = max number of descendants any ancestor can have
571 * limitDescendantSize = max size of descendants any ancestor can have
572 * errString = populated with error reason if any limits are hit
573 * fSearchForParents = whether to search a tx's vin for in-mempool parents, or
574 * look up parents from mapLinks. Must be true for entries not in the mempool
576 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;
578 /** Populate setDescendants with all in-mempool descendants of hash.
579 * Assumes that setDescendants includes all in-mempool descendants of anything
580 * already in it. */
581 void CalculateDescendants(txiter it, setEntries &setDescendants);
583 /** The minimum fee to get into the mempool, which may itself not be enough
584 * for larger-sized transactions.
585 * The incrementalRelayFee policy variable is used to bound the time it
586 * takes the fee rate to go back down all the way to 0. When the feerate
587 * would otherwise be half of this, it is set to 0 instead.
589 CFeeRate GetMinFee(size_t sizelimit) const;
591 /** Remove transactions from the mempool until its dynamic size is <= sizelimit.
592 * pvNoSpendsRemaining, if set, will be populated with the list of outpoints
593 * which are not in mempool which no longer have any spends in this mempool.
595 void TrimToSize(size_t sizelimit, std::vector<COutPoint>* pvNoSpendsRemaining=NULL);
597 /** Expire all transaction (and their dependencies) in the mempool older than time. Return the number of removed transactions. */
598 int Expire(int64_t time);
600 /** Returns false if the transaction is in the mempool and not within the chain limit specified. */
601 bool TransactionWithinChainLimit(const uint256& txid, size_t chainLimit) const;
603 unsigned long size()
605 LOCK(cs);
606 return mapTx.size();
609 uint64_t GetTotalTxSize()
611 LOCK(cs);
612 return totalTxSize;
615 bool exists(uint256 hash) const
617 LOCK(cs);
618 return (mapTx.count(hash) != 0);
621 CTransactionRef get(const uint256& hash) const;
622 TxMempoolInfo info(const uint256& hash) const;
623 std::vector<TxMempoolInfo> infoAll() const;
625 size_t DynamicMemoryUsage() const;
627 boost::signals2::signal<void (CTransactionRef)> NotifyEntryAdded;
628 boost::signals2::signal<void (CTransactionRef, MemPoolRemovalReason)> NotifyEntryRemoved;
630 private:
631 /** UpdateForDescendants is used by UpdateTransactionsFromBlock to update
632 * the descendants for a single transaction that has been added to the
633 * mempool but may have child transactions in the mempool, eg during a
634 * chain reorg. setExclude is the set of descendant transactions in the
635 * mempool that must not be accounted for (because any descendants in
636 * setExclude were added to the mempool after the transaction being
637 * updated and hence their state is already reflected in the parent
638 * state).
640 * cachedDescendants will be updated with the descendants of the transaction
641 * being updated, so that future invocations don't need to walk the
642 * same transaction again, if encountered in another transaction chain.
644 void UpdateForDescendants(txiter updateIt,
645 cacheMap &cachedDescendants,
646 const std::set<uint256> &setExclude);
647 /** Update ancestors of hash to add/remove it as a descendant transaction. */
648 void UpdateAncestorsOf(bool add, txiter hash, setEntries &setAncestors);
649 /** Set ancestor state for an entry */
650 void UpdateEntryForAncestors(txiter it, const setEntries &setAncestors);
651 /** For each transaction being removed, update ancestors and any direct children.
652 * If updateDescendants is true, then also update in-mempool descendants'
653 * ancestor state. */
654 void UpdateForRemoveFromMempool(const setEntries &entriesToRemove, bool updateDescendants);
655 /** Sever link between specified transaction and direct children. */
656 void UpdateChildrenForRemoval(txiter entry);
658 /** Before calling removeUnchecked for a given transaction,
659 * UpdateForRemoveFromMempool must be called on the entire (dependent) set
660 * of transactions being removed at the same time. We use each
661 * CTxMemPoolEntry's setMemPoolParents in order to walk ancestors of a
662 * given transaction that is removed, so we can't remove intermediate
663 * transactions in a chain before we've updated all the state for the
664 * removal.
666 void removeUnchecked(txiter entry, MemPoolRemovalReason reason = MemPoolRemovalReason::UNKNOWN);
669 /**
670 * CCoinsView that brings transactions from a memorypool into view.
671 * It does not check for spendings by memory pool transactions.
672 * Instead, it provides access to all Coins which are either unspent in the
673 * base CCoinsView, or are outputs from any mempool transaction!
674 * This allows transaction replacement to work as expected, as you want to
675 * have all inputs "available" to check signatures, and any cycles in the
676 * dependency graph are checked directly in AcceptToMemoryPool.
677 * It also allows you to sign a double-spend directly in signrawtransaction,
678 * as long as the conflicting transaction is not yet confirmed.
680 class CCoinsViewMemPool : public CCoinsViewBacked
682 protected:
683 const CTxMemPool& mempool;
685 public:
686 CCoinsViewMemPool(CCoinsView* baseIn, const CTxMemPool& mempoolIn);
687 bool GetCoin(const COutPoint &outpoint, Coin &coin) const override;
691 * DisconnectedBlockTransactions
693 * During the reorg, it's desirable to re-add previously confirmed transactions
694 * to the mempool, so that anything not re-confirmed in the new chain is
695 * available to be mined. However, it's more efficient to wait until the reorg
696 * is complete and process all still-unconfirmed transactions at that time,
697 * since we expect most confirmed transactions to (typically) still be
698 * confirmed in the new chain, and re-accepting to the memory pool is expensive
699 * (and therefore better to not do in the middle of reorg-processing).
700 * Instead, store the disconnected transactions (in order!) as we go, remove any
701 * that are included in blocks in the new chain, and then process the remaining
702 * still-unconfirmed transactions at the end.
705 // multi_index tag names
706 struct txid_index {};
707 struct insertion_order {};
709 struct DisconnectedBlockTransactions {
710 typedef boost::multi_index_container<
711 CTransactionRef,
712 boost::multi_index::indexed_by<
713 // sorted by txid
714 boost::multi_index::hashed_unique<
715 boost::multi_index::tag<txid_index>,
716 mempoolentry_txid,
717 SaltedTxidHasher
719 // sorted by order in the blockchain
720 boost::multi_index::sequenced<
721 boost::multi_index::tag<insertion_order>
724 > indexed_disconnected_transactions;
726 // It's almost certainly a logic bug if we don't clear out queuedTx before
727 // destruction, as we add to it while disconnecting blocks, and then we
728 // need to re-process remaining transactions to ensure mempool consistency.
729 // For now, assert() that we've emptied out this object on destruction.
730 // This assert() can always be removed if the reorg-processing code were
731 // to be refactored such that this assumption is no longer true (for
732 // instance if there was some other way we cleaned up the mempool after a
733 // reorg, besides draining this object).
734 ~DisconnectedBlockTransactions() { assert(queuedTx.empty()); }
736 indexed_disconnected_transactions queuedTx;
737 uint64_t cachedInnerUsage = 0;
739 // Estimate the overhead of queuedTx to be 6 pointers + an allocation, as
740 // no exact formula for boost::multi_index_contained is implemented.
741 size_t DynamicMemoryUsage() const {
742 return memusage::MallocUsage(sizeof(CTransactionRef) + 6 * sizeof(void*)) * queuedTx.size() + cachedInnerUsage;
745 void addTransaction(const CTransactionRef& tx)
747 queuedTx.insert(tx);
748 cachedInnerUsage += RecursiveDynamicUsage(tx);
751 // Remove entries based on txid_index, and update memory usage.
752 void removeForBlock(const std::vector<CTransactionRef>& vtx)
754 // Short-circuit in the common case of a block being added to the tip
755 if (queuedTx.empty()) {
756 return;
758 for (auto const &tx : vtx) {
759 auto it = queuedTx.find(tx->GetHash());
760 if (it != queuedTx.end()) {
761 cachedInnerUsage -= RecursiveDynamicUsage(*it);
762 queuedTx.erase(it);
767 // Remove an entry by insertion_order index, and update memory usage.
768 void removeEntry(indexed_disconnected_transactions::index<insertion_order>::type::iterator entry)
770 cachedInnerUsage -= RecursiveDynamicUsage(*entry);
771 queuedTx.get<insertion_order>().erase(entry);
774 void clear()
776 cachedInnerUsage = 0;
777 queuedTx.clear();
781 #endif // BITCOIN_TXMEMPOOL_H