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

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