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 29KB

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