[tests] Add -blocknotify functional test
[bitcoinplatinum.git] / src / txmempool.h
blob929d2235883646fa901592000479ed55e11443d6
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/hashed_index.hpp>
26 #include <boost/multi_index/ordered_index.hpp>
27 #include <boost/multi_index/sequenced_index.hpp>
28 #include <boost/signals2/signal.hpp>
30 class CBlockIndex;
32 /** Fake height value used in Coin to signify they are only in the memory pool (since 0.8) */
33 static const uint32_t 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(nullptr) { }
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.
64 class CTxMemPoolEntry
66 private:
67 CTransactionRef tx;
68 CAmount nFee; //!< Cached to avoid expensive parent-transaction lookups
69 size_t nTxWeight; //!< ... and avoid recomputing tx weight (also used for GetTxSize())
70 size_t nUsageSize; //!< ... and total memory usage
71 int64_t nTime; //!< Local time when entering the mempool
72 unsigned int entryHeight; //!< Chain height when entering the mempool
73 bool spendsCoinbase; //!< keep track of transactions that spend a coinbase
74 int64_t sigOpCost; //!< Total sigop cost
75 int64_t feeDelta; //!< Used for determining the priority of the transaction for mining in a block
76 LockPoints lockPoints; //!< Track the height and time at which tx was final
78 // Information about descendants of this transaction that are in the
79 // mempool; if we remove this transaction we must remove all of these
80 // descendants as well.
81 uint64_t nCountWithDescendants; //!< number of descendant transactions
82 uint64_t nSizeWithDescendants; //!< ... and size
83 CAmount nModFeesWithDescendants; //!< ... and total fees (all including us)
85 // Analogous statistics for ancestor transactions
86 uint64_t nCountWithAncestors;
87 uint64_t nSizeWithAncestors;
88 CAmount nModFeesWithAncestors;
89 int64_t nSigOpCostWithAncestors;
91 public:
92 CTxMemPoolEntry(const CTransactionRef& _tx, const CAmount& _nFee,
93 int64_t _nTime, unsigned int _entryHeight,
94 bool spendsCoinbase,
95 int64_t nSigOpsCost, LockPoints lp);
97 const CTransaction& GetTx() const { return *this->tx; }
98 CTransactionRef GetSharedTx() const { return this->tx; }
99 const CAmount& GetFee() const { return nFee; }
100 size_t GetTxSize() const;
101 size_t GetTxWeight() const { return nTxWeight; }
102 int64_t GetTime() const { return nTime; }
103 unsigned int GetHeight() const { return entryHeight; }
104 int64_t GetSigOpCost() const { return sigOpCost; }
105 int64_t GetModifiedFee() const { return nFee + feeDelta; }
106 size_t DynamicMemoryUsage() const { return nUsageSize; }
107 const LockPoints& GetLockPoints() const { return lockPoints; }
109 // Adjusts the descendant state.
110 void UpdateDescendantState(int64_t modifySize, CAmount modifyFee, int64_t modifyCount);
111 // Adjusts the ancestor state
112 void UpdateAncestorState(int64_t modifySize, CAmount modifyFee, int64_t modifyCount, int modifySigOps);
113 // Updates the fee delta used for mining priority score, and the
114 // modified fees with descendants.
115 void UpdateFeeDelta(int64_t feeDelta);
116 // Update the LockPoints after a reorg
117 void UpdateLockPoints(const LockPoints& lp);
119 uint64_t GetCountWithDescendants() const { return nCountWithDescendants; }
120 uint64_t GetSizeWithDescendants() const { return nSizeWithDescendants; }
121 CAmount GetModFeesWithDescendants() const { return nModFeesWithDescendants; }
123 bool GetSpendsCoinbase() const { return spendsCoinbase; }
125 uint64_t GetCountWithAncestors() const { return nCountWithAncestors; }
126 uint64_t GetSizeWithAncestors() const { return nSizeWithAncestors; }
127 CAmount GetModFeesWithAncestors() const { return nModFeesWithAncestors; }
128 int64_t GetSigOpCostWithAncestors() const { return nSigOpCostWithAncestors; }
130 mutable size_t vTxHashesIdx; //!< Index in mempool's vTxHashes
133 // Helpers for modifying CTxMemPool::mapTx, which is a boost multi_index.
134 struct update_descendant_state
136 update_descendant_state(int64_t _modifySize, CAmount _modifyFee, int64_t _modifyCount) :
137 modifySize(_modifySize), modifyFee(_modifyFee), modifyCount(_modifyCount)
140 void operator() (CTxMemPoolEntry &e)
141 { e.UpdateDescendantState(modifySize, modifyFee, modifyCount); }
143 private:
144 int64_t modifySize;
145 CAmount modifyFee;
146 int64_t modifyCount;
149 struct update_ancestor_state
151 update_ancestor_state(int64_t _modifySize, CAmount _modifyFee, int64_t _modifyCount, int64_t _modifySigOpsCost) :
152 modifySize(_modifySize), modifyFee(_modifyFee), modifyCount(_modifyCount), modifySigOpsCost(_modifySigOpsCost)
155 void operator() (CTxMemPoolEntry &e)
156 { e.UpdateAncestorState(modifySize, modifyFee, modifyCount, modifySigOpsCost); }
158 private:
159 int64_t modifySize;
160 CAmount modifyFee;
161 int64_t modifyCount;
162 int64_t modifySigOpsCost;
165 struct update_fee_delta
167 explicit update_fee_delta(int64_t _feeDelta) : feeDelta(_feeDelta) { }
169 void operator() (CTxMemPoolEntry &e) { e.UpdateFeeDelta(feeDelta); }
171 private:
172 int64_t feeDelta;
175 struct update_lock_points
177 explicit update_lock_points(const LockPoints& _lp) : lp(_lp) { }
179 void operator() (CTxMemPoolEntry &e) { e.UpdateLockPoints(lp); }
181 private:
182 const LockPoints& lp;
185 // extracts a transaction hash from CTxMempoolEntry or CTransactionRef
186 struct mempoolentry_txid
188 typedef uint256 result_type;
189 result_type operator() (const CTxMemPoolEntry &entry) const
191 return entry.GetTx().GetHash();
194 result_type operator() (const CTransactionRef& tx) const
196 return tx->GetHash();
200 /** \class CompareTxMemPoolEntryByDescendantScore
202 * Sort an entry by max(score/size of entry's tx, score/size with all descendants).
204 class CompareTxMemPoolEntryByDescendantScore
206 public:
207 bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b)
209 bool fUseADescendants = UseDescendantScore(a);
210 bool fUseBDescendants = UseDescendantScore(b);
212 double aModFee = fUseADescendants ? a.GetModFeesWithDescendants() : a.GetModifiedFee();
213 double aSize = fUseADescendants ? a.GetSizeWithDescendants() : a.GetTxSize();
215 double bModFee = fUseBDescendants ? b.GetModFeesWithDescendants() : b.GetModifiedFee();
216 double bSize = fUseBDescendants ? b.GetSizeWithDescendants() : b.GetTxSize();
218 // Avoid division by rewriting (a/b > c/d) as (a*d > c*b).
219 double f1 = aModFee * bSize;
220 double f2 = aSize * bModFee;
222 if (f1 == f2) {
223 return a.GetTime() >= b.GetTime();
225 return f1 < f2;
228 // Calculate which score to use for an entry (avoiding division).
229 bool UseDescendantScore(const CTxMemPoolEntry &a)
231 double f1 = (double)a.GetModifiedFee() * a.GetSizeWithDescendants();
232 double f2 = (double)a.GetModFeesWithDescendants() * a.GetTxSize();
233 return f2 > f1;
237 /** \class CompareTxMemPoolEntryByScore
239 * Sort by score of entry ((fee+delta)/size) in descending order
241 class CompareTxMemPoolEntryByScore
243 public:
244 bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b)
246 double f1 = (double)a.GetModifiedFee() * b.GetTxSize();
247 double f2 = (double)b.GetModifiedFee() * a.GetTxSize();
248 if (f1 == f2) {
249 return b.GetTx().GetHash() < a.GetTx().GetHash();
251 return f1 > f2;
255 class CompareTxMemPoolEntryByEntryTime
257 public:
258 bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b)
260 return a.GetTime() < b.GetTime();
264 class CompareTxMemPoolEntryByAncestorFee
266 public:
267 bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b)
269 double aFees = a.GetModFeesWithAncestors();
270 double aSize = a.GetSizeWithAncestors();
272 double bFees = b.GetModFeesWithAncestors();
273 double bSize = b.GetSizeWithAncestors();
275 // Avoid division by rewriting (a/b > c/d) as (a*d > c*b).
276 double f1 = aFees * bSize;
277 double f2 = aSize * bFees;
279 if (f1 == f2) {
280 return a.GetTx().GetHash() < b.GetTx().GetHash();
283 return f1 > f2;
287 // Multi_index tag names
288 struct descendant_score {};
289 struct entry_time {};
290 struct mining_score {};
291 struct ancestor_score {};
293 class CBlockPolicyEstimator;
296 * Information about a mempool transaction.
298 struct TxMempoolInfo
300 /** The transaction itself */
301 CTransactionRef tx;
303 /** Time the transaction entered the mempool. */
304 int64_t nTime;
306 /** Feerate of the transaction. */
307 CFeeRate feeRate;
309 /** The fee delta. */
310 int64_t nFeeDelta;
313 /** Reason why a transaction was removed from the mempool,
314 * this is passed to the notification signal.
316 enum class MemPoolRemovalReason {
317 UNKNOWN = 0, //! Manually removed or unknown reason
318 EXPIRY, //! Expired from mempool
319 SIZELIMIT, //! Removed in size limiting
320 REORG, //! Removed for reorganization
321 BLOCK, //! Removed for block
322 CONFLICT, //! Removed for conflict with in-block transaction
323 REPLACED //! Removed for replacement
326 class SaltedTxidHasher
328 private:
329 /** Salt */
330 const uint64_t k0, k1;
332 public:
333 SaltedTxidHasher();
335 size_t operator()(const uint256& txid) const {
336 return SipHashUint256(k0, k1, txid);
341 * CTxMemPool stores valid-according-to-the-current-best-chain transactions
342 * that may be included in the next block.
344 * Transactions are added when they are seen on the network (or created by the
345 * local node), but not all transactions seen are added to the pool. For
346 * example, the following new transactions will not be added to the mempool:
347 * - a transaction which doesn't meet the minimum fee requirements.
348 * - a new transaction that double-spends an input of a transaction already in
349 * the pool where the new transaction does not meet the Replace-By-Fee
350 * requirements as defined in BIP 125.
351 * - a non-standard transaction.
353 * CTxMemPool::mapTx, and CTxMemPoolEntry bookkeeping:
355 * mapTx is a boost::multi_index that sorts the mempool on 4 criteria:
356 * - transaction hash
357 * - feerate [we use max(feerate of tx, feerate of tx with all descendants)]
358 * - time in mempool
359 * - mining score (feerate modified by any fee deltas from PrioritiseTransaction)
361 * Note: the term "descendant" refers to in-mempool transactions that depend on
362 * this one, while "ancestor" refers to in-mempool transactions that a given
363 * transaction depends on.
365 * In order for the feerate sort to remain correct, we must update transactions
366 * in the mempool when new descendants arrive. To facilitate this, we track
367 * the set of in-mempool direct parents and direct children in mapLinks. Within
368 * each CTxMemPoolEntry, we track the size and fees of all descendants.
370 * Usually when a new transaction is added to the mempool, it has no in-mempool
371 * children (because any such children would be an orphan). So in
372 * addUnchecked(), we:
373 * - update a new entry's setMemPoolParents to include all in-mempool parents
374 * - update the new entry's direct parents to include the new tx as a child
375 * - update all ancestors of the transaction to include the new tx's size/fee
377 * When a transaction is removed from the mempool, we must:
378 * - update all in-mempool parents to not track the tx in setMemPoolChildren
379 * - update all ancestors to not include the tx's size/fees in descendant state
380 * - update all in-mempool children to not include it as a parent
382 * These happen in UpdateForRemoveFromMempool(). (Note that when removing a
383 * transaction along with its descendants, we must calculate that set of
384 * transactions to be removed before doing the removal, or else the mempool can
385 * be in an inconsistent state where it's impossible to walk the ancestors of
386 * a transaction.)
388 * In the event of a reorg, the assumption that a newly added tx has no
389 * in-mempool children is false. In particular, the mempool is in an
390 * inconsistent state while new transactions are being added, because there may
391 * be descendant transactions of a tx coming from a disconnected block that are
392 * unreachable from just looking at transactions in the mempool (the linking
393 * transactions may also be in the disconnected block, waiting to be added).
394 * Because of this, there's not much benefit in trying to search for in-mempool
395 * children in addUnchecked(). Instead, in the special case of transactions
396 * being added from a disconnected block, we require the caller to clean up the
397 * state, to account for in-mempool, out-of-block descendants for all the
398 * in-block transactions by calling UpdateTransactionsFromBlock(). Note that
399 * until this is called, the mempool state is not consistent, and in particular
400 * mapLinks may not be correct (and therefore functions like
401 * CalculateMemPoolAncestors() and CalculateDescendants() that rely
402 * on them to walk the mempool are not generally safe to use).
404 * Computational limits:
406 * Updating all in-mempool ancestors of a newly added transaction can be slow,
407 * if no bound exists on how many in-mempool ancestors there may be.
408 * CalculateMemPoolAncestors() takes configurable limits that are designed to
409 * prevent these calculations from being too CPU intensive.
412 class CTxMemPool
414 private:
415 uint32_t nCheckFrequency; //!< Value n means that n times in 2^32 we check.
416 unsigned int nTransactionsUpdated; //!< Used by getblocktemplate to trigger CreateNewBlock() invocation
417 CBlockPolicyEstimator* minerPolicyEstimator;
419 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.
420 uint64_t cachedInnerUsage; //!< sum of dynamic memory usage of all the map elements (NOT the maps themselves)
422 mutable int64_t lastRollingFeeUpdate;
423 mutable bool blockSinceLastRollingFeeBump;
424 mutable double rollingMinimumFeeRate; //!< minimum fee to get into the pool, decreases exponentially
426 void trackPackageRemoved(const CFeeRate& rate);
428 public:
430 static const int ROLLING_FEE_HALFLIFE = 60 * 60 * 12; // public only for testing
432 typedef boost::multi_index_container<
433 CTxMemPoolEntry,
434 boost::multi_index::indexed_by<
435 // sorted by txid
436 boost::multi_index::hashed_unique<mempoolentry_txid, SaltedTxidHasher>,
437 // sorted by fee rate
438 boost::multi_index::ordered_non_unique<
439 boost::multi_index::tag<descendant_score>,
440 boost::multi_index::identity<CTxMemPoolEntry>,
441 CompareTxMemPoolEntryByDescendantScore
443 // sorted by entry time
444 boost::multi_index::ordered_non_unique<
445 boost::multi_index::tag<entry_time>,
446 boost::multi_index::identity<CTxMemPoolEntry>,
447 CompareTxMemPoolEntryByEntryTime
449 // sorted by score (for mining prioritization)
450 boost::multi_index::ordered_unique<
451 boost::multi_index::tag<mining_score>,
452 boost::multi_index::identity<CTxMemPoolEntry>,
453 CompareTxMemPoolEntryByScore
455 // sorted by fee rate with ancestors
456 boost::multi_index::ordered_non_unique<
457 boost::multi_index::tag<ancestor_score>,
458 boost::multi_index::identity<CTxMemPoolEntry>,
459 CompareTxMemPoolEntryByAncestorFee
462 > indexed_transaction_set;
464 mutable CCriticalSection cs;
465 indexed_transaction_set mapTx;
467 typedef indexed_transaction_set::nth_index<0>::type::iterator txiter;
468 std::vector<std::pair<uint256, txiter> > vTxHashes; //!< All tx witness hashes/entries in mapTx, in random order
470 struct CompareIteratorByHash {
471 bool operator()(const txiter &a, const txiter &b) const {
472 return a->GetTx().GetHash() < b->GetTx().GetHash();
475 typedef std::set<txiter, CompareIteratorByHash> setEntries;
477 const setEntries & GetMemPoolParents(txiter entry) const;
478 const setEntries & GetMemPoolChildren(txiter entry) const;
479 private:
480 typedef std::map<txiter, setEntries, CompareIteratorByHash> cacheMap;
482 struct TxLinks {
483 setEntries parents;
484 setEntries children;
487 typedef std::map<txiter, TxLinks, CompareIteratorByHash> txlinksMap;
488 txlinksMap mapLinks;
490 void UpdateParent(txiter entry, txiter parent, bool add);
491 void UpdateChild(txiter entry, txiter child, bool add);
493 std::vector<indexed_transaction_set::const_iterator> GetSortedDepthAndScore() const;
495 public:
496 indirectmap<COutPoint, const CTransaction*> mapNextTx;
497 std::map<uint256, CAmount> mapDeltas;
499 /** Create a new CTxMemPool.
501 explicit CTxMemPool(CBlockPolicyEstimator* estimator = nullptr);
504 * If sanity-checking is turned on, check makes sure the pool is
505 * consistent (does not contain two transactions that spend the same inputs,
506 * all inputs are in the mapNextTx array). If sanity-checking is turned off,
507 * check does nothing.
509 void check(const CCoinsViewCache *pcoins) const;
510 void setSanityCheck(double dFrequency = 1.0) { nCheckFrequency = static_cast<uint32_t>(dFrequency * 4294967295.0); }
512 // addUnchecked must updated state for all ancestors of a given transaction,
513 // to track size/count of descendant transactions. First version of
514 // addUnchecked can be used to have it call CalculateMemPoolAncestors(), and
515 // then invoke the second version.
516 bool addUnchecked(const uint256& hash, const CTxMemPoolEntry &entry, bool validFeeEstimate = true);
517 bool addUnchecked(const uint256& hash, const CTxMemPoolEntry &entry, setEntries &setAncestors, bool validFeeEstimate = true);
519 void removeRecursive(const CTransaction &tx, MemPoolRemovalReason reason = MemPoolRemovalReason::UNKNOWN);
520 void removeForReorg(const CCoinsViewCache *pcoins, unsigned int nMemPoolHeight, int flags);
521 void removeConflicts(const CTransaction &tx);
522 void removeForBlock(const std::vector<CTransactionRef>& vtx, unsigned int nBlockHeight);
524 void clear();
525 void _clear(); //lock free
526 bool CompareDepthAndScore(const uint256& hasha, const uint256& hashb);
527 void queryHashes(std::vector<uint256>& vtxid);
528 bool isSpent(const COutPoint& outpoint);
529 unsigned int GetTransactionsUpdated() const;
530 void AddTransactionsUpdated(unsigned int n);
532 * Check that none of this transactions inputs are in the mempool, and thus
533 * the tx is not dependent on other mempool transactions to be included in a block.
535 bool HasNoInputsOf(const CTransaction& tx) const;
537 /** Affect CreateNewBlock prioritisation of transactions */
538 void PrioritiseTransaction(const uint256& hash, const CAmount& nFeeDelta);
539 void ApplyDelta(const uint256 hash, CAmount &nFeeDelta) const;
540 void ClearPrioritisation(const uint256 hash);
542 public:
543 /** Remove a set of transactions from the mempool.
544 * If a transaction is in this set, then all in-mempool descendants must
545 * also be in the set, unless this transaction is being removed for being
546 * in a block.
547 * Set updateDescendants to true when removing a tx that was in a block, so
548 * that any in-mempool descendants have their ancestor state updated.
550 void RemoveStaged(setEntries &stage, bool updateDescendants, MemPoolRemovalReason reason = MemPoolRemovalReason::UNKNOWN);
552 /** When adding transactions from a disconnected block back to the mempool,
553 * new mempool entries may have children in the mempool (which is generally
554 * not the case when otherwise adding transactions).
555 * UpdateTransactionsFromBlock() will find child transactions and update the
556 * descendant state for each transaction in vHashesToUpdate (excluding any
557 * child transactions present in vHashesToUpdate, which are already accounted
558 * for). Note: vHashesToUpdate should be the set of transactions from the
559 * disconnected block that have been accepted back into the mempool.
561 void UpdateTransactionsFromBlock(const std::vector<uint256> &vHashesToUpdate);
563 /** Try to calculate all in-mempool ancestors of entry.
564 * (these are all calculated including the tx itself)
565 * limitAncestorCount = max number of ancestors
566 * limitAncestorSize = max size of ancestors
567 * limitDescendantCount = max number of descendants any ancestor can have
568 * limitDescendantSize = max size of descendants any ancestor can have
569 * errString = populated with error reason if any limits are hit
570 * fSearchForParents = whether to search a tx's vin for in-mempool parents, or
571 * look up parents from mapLinks. Must be true for entries not in the mempool
573 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 /** Populate setDescendants with all in-mempool descendants of hash.
576 * Assumes that setDescendants includes all in-mempool descendants of anything
577 * already in it. */
578 void CalculateDescendants(txiter it, setEntries &setDescendants);
580 /** The minimum fee to get into the mempool, which may itself not be enough
581 * for larger-sized transactions.
582 * The incrementalRelayFee policy variable is used to bound the time it
583 * takes the fee rate to go back down all the way to 0. When the feerate
584 * would otherwise be half of this, it is set to 0 instead.
586 CFeeRate GetMinFee(size_t sizelimit) const;
588 /** Remove transactions from the mempool until its dynamic size is <= sizelimit.
589 * pvNoSpendsRemaining, if set, will be populated with the list of outpoints
590 * which are not in mempool which no longer have any spends in this mempool.
592 void TrimToSize(size_t sizelimit, std::vector<COutPoint>* pvNoSpendsRemaining=nullptr);
594 /** Expire all transaction (and their dependencies) in the mempool older than time. Return the number of removed transactions. */
595 int Expire(int64_t time);
597 /** Returns false if the transaction is in the mempool and not within the chain limit specified. */
598 bool TransactionWithinChainLimit(const uint256& txid, size_t chainLimit) const;
600 unsigned long size()
602 LOCK(cs);
603 return mapTx.size();
606 uint64_t GetTotalTxSize() const
608 LOCK(cs);
609 return totalTxSize;
612 bool exists(uint256 hash) const
614 LOCK(cs);
615 return (mapTx.count(hash) != 0);
618 CTransactionRef get(const uint256& hash) const;
619 TxMempoolInfo info(const uint256& hash) const;
620 std::vector<TxMempoolInfo> infoAll() const;
622 size_t DynamicMemoryUsage() const;
624 boost::signals2::signal<void (CTransactionRef)> NotifyEntryAdded;
625 boost::signals2::signal<void (CTransactionRef, MemPoolRemovalReason)> NotifyEntryRemoved;
627 private:
628 /** UpdateForDescendants is used by UpdateTransactionsFromBlock to update
629 * the descendants for a single transaction that has been added to the
630 * mempool but may have child transactions in the mempool, eg during a
631 * chain reorg. setExclude is the set of descendant transactions in the
632 * mempool that must not be accounted for (because any descendants in
633 * setExclude were added to the mempool after the transaction being
634 * updated and hence their state is already reflected in the parent
635 * state).
637 * cachedDescendants will be updated with the descendants of the transaction
638 * being updated, so that future invocations don't need to walk the
639 * same transaction again, if encountered in another transaction chain.
641 void UpdateForDescendants(txiter updateIt,
642 cacheMap &cachedDescendants,
643 const std::set<uint256> &setExclude);
644 /** Update ancestors of hash to add/remove it as a descendant transaction. */
645 void UpdateAncestorsOf(bool add, txiter hash, setEntries &setAncestors);
646 /** Set ancestor state for an entry */
647 void UpdateEntryForAncestors(txiter it, const setEntries &setAncestors);
648 /** For each transaction being removed, update ancestors and any direct children.
649 * If updateDescendants is true, then also update in-mempool descendants'
650 * ancestor state. */
651 void UpdateForRemoveFromMempool(const setEntries &entriesToRemove, bool updateDescendants);
652 /** Sever link between specified transaction and direct children. */
653 void UpdateChildrenForRemoval(txiter entry);
655 /** Before calling removeUnchecked for a given transaction,
656 * UpdateForRemoveFromMempool must be called on the entire (dependent) set
657 * of transactions being removed at the same time. We use each
658 * CTxMemPoolEntry's setMemPoolParents in order to walk ancestors of a
659 * given transaction that is removed, so we can't remove intermediate
660 * transactions in a chain before we've updated all the state for the
661 * removal.
663 void removeUnchecked(txiter entry, MemPoolRemovalReason reason = MemPoolRemovalReason::UNKNOWN);
666 /**
667 * CCoinsView that brings transactions from a memorypool into view.
668 * It does not check for spendings by memory pool transactions.
669 * Instead, it provides access to all Coins which are either unspent in the
670 * base CCoinsView, or are outputs from any mempool transaction!
671 * This allows transaction replacement to work as expected, as you want to
672 * have all inputs "available" to check signatures, and any cycles in the
673 * dependency graph are checked directly in AcceptToMemoryPool.
674 * It also allows you to sign a double-spend directly in signrawtransaction,
675 * as long as the conflicting transaction is not yet confirmed.
677 class CCoinsViewMemPool : public CCoinsViewBacked
679 protected:
680 const CTxMemPool& mempool;
682 public:
683 CCoinsViewMemPool(CCoinsView* baseIn, const CTxMemPool& mempoolIn);
684 bool GetCoin(const COutPoint &outpoint, Coin &coin) const override;
688 * DisconnectedBlockTransactions
690 * During the reorg, it's desirable to re-add previously confirmed transactions
691 * to the mempool, so that anything not re-confirmed in the new chain is
692 * available to be mined. However, it's more efficient to wait until the reorg
693 * is complete and process all still-unconfirmed transactions at that time,
694 * since we expect most confirmed transactions to (typically) still be
695 * confirmed in the new chain, and re-accepting to the memory pool is expensive
696 * (and therefore better to not do in the middle of reorg-processing).
697 * Instead, store the disconnected transactions (in order!) as we go, remove any
698 * that are included in blocks in the new chain, and then process the remaining
699 * still-unconfirmed transactions at the end.
702 // multi_index tag names
703 struct txid_index {};
704 struct insertion_order {};
706 struct DisconnectedBlockTransactions {
707 typedef boost::multi_index_container<
708 CTransactionRef,
709 boost::multi_index::indexed_by<
710 // sorted by txid
711 boost::multi_index::hashed_unique<
712 boost::multi_index::tag<txid_index>,
713 mempoolentry_txid,
714 SaltedTxidHasher
716 // sorted by order in the blockchain
717 boost::multi_index::sequenced<
718 boost::multi_index::tag<insertion_order>
721 > indexed_disconnected_transactions;
723 // It's almost certainly a logic bug if we don't clear out queuedTx before
724 // destruction, as we add to it while disconnecting blocks, and then we
725 // need to re-process remaining transactions to ensure mempool consistency.
726 // For now, assert() that we've emptied out this object on destruction.
727 // This assert() can always be removed if the reorg-processing code were
728 // to be refactored such that this assumption is no longer true (for
729 // instance if there was some other way we cleaned up the mempool after a
730 // reorg, besides draining this object).
731 ~DisconnectedBlockTransactions() { assert(queuedTx.empty()); }
733 indexed_disconnected_transactions queuedTx;
734 uint64_t cachedInnerUsage = 0;
736 // Estimate the overhead of queuedTx to be 6 pointers + an allocation, as
737 // no exact formula for boost::multi_index_contained is implemented.
738 size_t DynamicMemoryUsage() const {
739 return memusage::MallocUsage(sizeof(CTransactionRef) + 6 * sizeof(void*)) * queuedTx.size() + cachedInnerUsage;
742 void addTransaction(const CTransactionRef& tx)
744 queuedTx.insert(tx);
745 cachedInnerUsage += RecursiveDynamicUsage(tx);
748 // Remove entries based on txid_index, and update memory usage.
749 void removeForBlock(const std::vector<CTransactionRef>& vtx)
751 // Short-circuit in the common case of a block being added to the tip
752 if (queuedTx.empty()) {
753 return;
755 for (auto const &tx : vtx) {
756 auto it = queuedTx.find(tx->GetHash());
757 if (it != queuedTx.end()) {
758 cachedInnerUsage -= RecursiveDynamicUsage(*it);
759 queuedTx.erase(it);
764 // Remove an entry by insertion_order index, and update memory usage.
765 void removeEntry(indexed_disconnected_transactions::index<insertion_order>::type::iterator entry)
767 cachedInnerUsage -= RecursiveDynamicUsage(*entry);
768 queuedTx.get<insertion_order>().erase(entry);
771 void clear()
773 cachedInnerUsage = 0;
774 queuedTx.clear();
778 #endif // BITCOIN_TXMEMPOOL_H