You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

txmempool.h 28KB

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