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

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