Remove unused var UNLIKELY_PCT from fees.h
[bitcoinplatinum.git] / src / txmempool.cpp
blob45135a5f7347c4711c48b17bec3373794f04fe9b
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.
6 #include "txmempool.h"
8 #include "clientversion.h"
9 #include "consensus/consensus.h"
10 #include "consensus/validation.h"
11 #include "main.h"
12 #include "policy/policy.h"
13 #include "policy/fees.h"
14 #include "streams.h"
15 #include "timedata.h"
16 #include "util.h"
17 #include "utilmoneystr.h"
18 #include "utiltime.h"
19 #include "version.h"
21 using namespace std;
23 CTxMemPoolEntry::CTxMemPoolEntry(const CTransaction& _tx, const CAmount& _nFee,
24 int64_t _nTime, double _entryPriority, unsigned int _entryHeight,
25 bool poolHasNoInputsOf, CAmount _inChainInputValue,
26 bool _spendsCoinbase, int64_t _sigOpsCost, LockPoints lp):
27 tx(std::make_shared<CTransaction>(_tx)), nFee(_nFee), nTime(_nTime), entryPriority(_entryPriority), entryHeight(_entryHeight),
28 hadNoDependencies(poolHasNoInputsOf), inChainInputValue(_inChainInputValue),
29 spendsCoinbase(_spendsCoinbase), sigOpCost(_sigOpsCost), lockPoints(lp)
31 nTxWeight = GetTransactionWeight(_tx);
32 nModSize = _tx.CalculateModifiedSize(GetTxSize());
33 nUsageSize = RecursiveDynamicUsage(*tx) + memusage::DynamicUsage(tx);
35 nCountWithDescendants = 1;
36 nSizeWithDescendants = GetTxSize();
37 nModFeesWithDescendants = nFee;
38 CAmount nValueIn = _tx.GetValueOut()+nFee;
39 assert(inChainInputValue <= nValueIn);
41 feeDelta = 0;
43 nCountWithAncestors = 1;
44 nSizeWithAncestors = GetTxSize();
45 nModFeesWithAncestors = nFee;
46 nSigOpCostWithAncestors = sigOpCost;
49 CTxMemPoolEntry::CTxMemPoolEntry(const CTxMemPoolEntry& other)
51 *this = other;
54 double
55 CTxMemPoolEntry::GetPriority(unsigned int currentHeight) const
57 double deltaPriority = ((double)(currentHeight-entryHeight)*inChainInputValue)/nModSize;
58 double dResult = entryPriority + deltaPriority;
59 if (dResult < 0) // This should only happen if it was called with a height below entry height
60 dResult = 0;
61 return dResult;
64 void CTxMemPoolEntry::UpdateFeeDelta(int64_t newFeeDelta)
66 nModFeesWithDescendants += newFeeDelta - feeDelta;
67 nModFeesWithAncestors += newFeeDelta - feeDelta;
68 feeDelta = newFeeDelta;
71 void CTxMemPoolEntry::UpdateLockPoints(const LockPoints& lp)
73 lockPoints = lp;
76 size_t CTxMemPoolEntry::GetTxSize() const
78 return GetVirtualTransactionSize(nTxWeight, sigOpCost);
81 // Update the given tx for any in-mempool descendants.
82 // Assumes that setMemPoolChildren is correct for the given tx and all
83 // descendants.
84 void CTxMemPool::UpdateForDescendants(txiter updateIt, cacheMap &cachedDescendants, const std::set<uint256> &setExclude)
86 setEntries stageEntries, setAllDescendants;
87 stageEntries = GetMemPoolChildren(updateIt);
89 while (!stageEntries.empty()) {
90 const txiter cit = *stageEntries.begin();
91 setAllDescendants.insert(cit);
92 stageEntries.erase(cit);
93 const setEntries &setChildren = GetMemPoolChildren(cit);
94 BOOST_FOREACH(const txiter childEntry, setChildren) {
95 cacheMap::iterator cacheIt = cachedDescendants.find(childEntry);
96 if (cacheIt != cachedDescendants.end()) {
97 // We've already calculated this one, just add the entries for this set
98 // but don't traverse again.
99 BOOST_FOREACH(const txiter cacheEntry, cacheIt->second) {
100 setAllDescendants.insert(cacheEntry);
102 } else if (!setAllDescendants.count(childEntry)) {
103 // Schedule for later processing
104 stageEntries.insert(childEntry);
108 // setAllDescendants now contains all in-mempool descendants of updateIt.
109 // Update and add to cached descendant map
110 int64_t modifySize = 0;
111 CAmount modifyFee = 0;
112 int64_t modifyCount = 0;
113 BOOST_FOREACH(txiter cit, setAllDescendants) {
114 if (!setExclude.count(cit->GetTx().GetHash())) {
115 modifySize += cit->GetTxSize();
116 modifyFee += cit->GetModifiedFee();
117 modifyCount++;
118 cachedDescendants[updateIt].insert(cit);
119 // Update ancestor state for each descendant
120 mapTx.modify(cit, update_ancestor_state(updateIt->GetTxSize(), updateIt->GetModifiedFee(), 1, updateIt->GetSigOpCost()));
123 mapTx.modify(updateIt, update_descendant_state(modifySize, modifyFee, modifyCount));
126 // vHashesToUpdate is the set of transaction hashes from a disconnected block
127 // which has been re-added to the mempool.
128 // for each entry, look for descendants that are outside hashesToUpdate, and
129 // add fee/size information for such descendants to the parent.
130 // for each such descendant, also update the ancestor state to include the parent.
131 void CTxMemPool::UpdateTransactionsFromBlock(const std::vector<uint256> &vHashesToUpdate)
133 LOCK(cs);
134 // For each entry in vHashesToUpdate, store the set of in-mempool, but not
135 // in-vHashesToUpdate transactions, so that we don't have to recalculate
136 // descendants when we come across a previously seen entry.
137 cacheMap mapMemPoolDescendantsToUpdate;
139 // Use a set for lookups into vHashesToUpdate (these entries are already
140 // accounted for in the state of their ancestors)
141 std::set<uint256> setAlreadyIncluded(vHashesToUpdate.begin(), vHashesToUpdate.end());
143 // Iterate in reverse, so that whenever we are looking at at a transaction
144 // we are sure that all in-mempool descendants have already been processed.
145 // This maximizes the benefit of the descendant cache and guarantees that
146 // setMemPoolChildren will be updated, an assumption made in
147 // UpdateForDescendants.
148 BOOST_REVERSE_FOREACH(const uint256 &hash, vHashesToUpdate) {
149 // we cache the in-mempool children to avoid duplicate updates
150 setEntries setChildren;
151 // calculate children from mapNextTx
152 txiter it = mapTx.find(hash);
153 if (it == mapTx.end()) {
154 continue;
156 auto iter = mapNextTx.lower_bound(COutPoint(hash, 0));
157 // First calculate the children, and update setMemPoolChildren to
158 // include them, and update their setMemPoolParents to include this tx.
159 for (; iter != mapNextTx.end() && iter->first->hash == hash; ++iter) {
160 const uint256 &childHash = iter->second->GetHash();
161 txiter childIter = mapTx.find(childHash);
162 assert(childIter != mapTx.end());
163 // We can skip updating entries we've encountered before or that
164 // are in the block (which are already accounted for).
165 if (setChildren.insert(childIter).second && !setAlreadyIncluded.count(childHash)) {
166 UpdateChild(it, childIter, true);
167 UpdateParent(childIter, it, true);
170 UpdateForDescendants(it, mapMemPoolDescendantsToUpdate, setAlreadyIncluded);
174 bool CTxMemPool::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
176 setEntries parentHashes;
177 const CTransaction &tx = entry.GetTx();
179 if (fSearchForParents) {
180 // Get parents of this transaction that are in the mempool
181 // GetMemPoolParents() is only valid for entries in the mempool, so we
182 // iterate mapTx to find parents.
183 for (unsigned int i = 0; i < tx.vin.size(); i++) {
184 txiter piter = mapTx.find(tx.vin[i].prevout.hash);
185 if (piter != mapTx.end()) {
186 parentHashes.insert(piter);
187 if (parentHashes.size() + 1 > limitAncestorCount) {
188 errString = strprintf("too many unconfirmed parents [limit: %u]", limitAncestorCount);
189 return false;
193 } else {
194 // If we're not searching for parents, we require this to be an
195 // entry in the mempool already.
196 txiter it = mapTx.iterator_to(entry);
197 parentHashes = GetMemPoolParents(it);
200 size_t totalSizeWithAncestors = entry.GetTxSize();
202 while (!parentHashes.empty()) {
203 txiter stageit = *parentHashes.begin();
205 setAncestors.insert(stageit);
206 parentHashes.erase(stageit);
207 totalSizeWithAncestors += stageit->GetTxSize();
209 if (stageit->GetSizeWithDescendants() + entry.GetTxSize() > limitDescendantSize) {
210 errString = strprintf("exceeds descendant size limit for tx %s [limit: %u]", stageit->GetTx().GetHash().ToString(), limitDescendantSize);
211 return false;
212 } else if (stageit->GetCountWithDescendants() + 1 > limitDescendantCount) {
213 errString = strprintf("too many descendants for tx %s [limit: %u]", stageit->GetTx().GetHash().ToString(), limitDescendantCount);
214 return false;
215 } else if (totalSizeWithAncestors > limitAncestorSize) {
216 errString = strprintf("exceeds ancestor size limit [limit: %u]", limitAncestorSize);
217 return false;
220 const setEntries & setMemPoolParents = GetMemPoolParents(stageit);
221 BOOST_FOREACH(const txiter &phash, setMemPoolParents) {
222 // If this is a new ancestor, add it.
223 if (setAncestors.count(phash) == 0) {
224 parentHashes.insert(phash);
226 if (parentHashes.size() + setAncestors.size() + 1 > limitAncestorCount) {
227 errString = strprintf("too many unconfirmed ancestors [limit: %u]", limitAncestorCount);
228 return false;
233 return true;
236 void CTxMemPool::UpdateAncestorsOf(bool add, txiter it, setEntries &setAncestors)
238 setEntries parentIters = GetMemPoolParents(it);
239 // add or remove this tx as a child of each parent
240 BOOST_FOREACH(txiter piter, parentIters) {
241 UpdateChild(piter, it, add);
243 const int64_t updateCount = (add ? 1 : -1);
244 const int64_t updateSize = updateCount * it->GetTxSize();
245 const CAmount updateFee = updateCount * it->GetModifiedFee();
246 BOOST_FOREACH(txiter ancestorIt, setAncestors) {
247 mapTx.modify(ancestorIt, update_descendant_state(updateSize, updateFee, updateCount));
251 void CTxMemPool::UpdateEntryForAncestors(txiter it, const setEntries &setAncestors)
253 int64_t updateCount = setAncestors.size();
254 int64_t updateSize = 0;
255 CAmount updateFee = 0;
256 int64_t updateSigOpsCost = 0;
257 BOOST_FOREACH(txiter ancestorIt, setAncestors) {
258 updateSize += ancestorIt->GetTxSize();
259 updateFee += ancestorIt->GetModifiedFee();
260 updateSigOpsCost += ancestorIt->GetSigOpCost();
262 mapTx.modify(it, update_ancestor_state(updateSize, updateFee, updateCount, updateSigOpsCost));
265 void CTxMemPool::UpdateChildrenForRemoval(txiter it)
267 const setEntries &setMemPoolChildren = GetMemPoolChildren(it);
268 BOOST_FOREACH(txiter updateIt, setMemPoolChildren) {
269 UpdateParent(updateIt, it, false);
273 void CTxMemPool::UpdateForRemoveFromMempool(const setEntries &entriesToRemove, bool updateDescendants)
275 // For each entry, walk back all ancestors and decrement size associated with this
276 // transaction
277 const uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();
278 if (updateDescendants) {
279 // updateDescendants should be true whenever we're not recursively
280 // removing a tx and all its descendants, eg when a transaction is
281 // confirmed in a block.
282 // Here we only update statistics and not data in mapLinks (which
283 // we need to preserve until we're finished with all operations that
284 // need to traverse the mempool).
285 BOOST_FOREACH(txiter removeIt, entriesToRemove) {
286 setEntries setDescendants;
287 CalculateDescendants(removeIt, setDescendants);
288 setDescendants.erase(removeIt); // don't update state for self
289 int64_t modifySize = -((int64_t)removeIt->GetTxSize());
290 CAmount modifyFee = -removeIt->GetModifiedFee();
291 int modifySigOps = -removeIt->GetSigOpCost();
292 BOOST_FOREACH(txiter dit, setDescendants) {
293 mapTx.modify(dit, update_ancestor_state(modifySize, modifyFee, -1, modifySigOps));
297 BOOST_FOREACH(txiter removeIt, entriesToRemove) {
298 setEntries setAncestors;
299 const CTxMemPoolEntry &entry = *removeIt;
300 std::string dummy;
301 // Since this is a tx that is already in the mempool, we can call CMPA
302 // with fSearchForParents = false. If the mempool is in a consistent
303 // state, then using true or false should both be correct, though false
304 // should be a bit faster.
305 // However, if we happen to be in the middle of processing a reorg, then
306 // the mempool can be in an inconsistent state. In this case, the set
307 // of ancestors reachable via mapLinks will be the same as the set of
308 // ancestors whose packages include this transaction, because when we
309 // add a new transaction to the mempool in addUnchecked(), we assume it
310 // has no children, and in the case of a reorg where that assumption is
311 // false, the in-mempool children aren't linked to the in-block tx's
312 // until UpdateTransactionsFromBlock() is called.
313 // So if we're being called during a reorg, ie before
314 // UpdateTransactionsFromBlock() has been called, then mapLinks[] will
315 // differ from the set of mempool parents we'd calculate by searching,
316 // and it's important that we use the mapLinks[] notion of ancestor
317 // transactions as the set of things to update for removal.
318 CalculateMemPoolAncestors(entry, setAncestors, nNoLimit, nNoLimit, nNoLimit, nNoLimit, dummy, false);
319 // Note that UpdateAncestorsOf severs the child links that point to
320 // removeIt in the entries for the parents of removeIt.
321 UpdateAncestorsOf(false, removeIt, setAncestors);
323 // After updating all the ancestor sizes, we can now sever the link between each
324 // transaction being removed and any mempool children (ie, update setMemPoolParents
325 // for each direct child of a transaction being removed).
326 BOOST_FOREACH(txiter removeIt, entriesToRemove) {
327 UpdateChildrenForRemoval(removeIt);
331 void CTxMemPoolEntry::UpdateDescendantState(int64_t modifySize, CAmount modifyFee, int64_t modifyCount)
333 nSizeWithDescendants += modifySize;
334 assert(int64_t(nSizeWithDescendants) > 0);
335 nModFeesWithDescendants += modifyFee;
336 nCountWithDescendants += modifyCount;
337 assert(int64_t(nCountWithDescendants) > 0);
340 void CTxMemPoolEntry::UpdateAncestorState(int64_t modifySize, CAmount modifyFee, int64_t modifyCount, int modifySigOps)
342 nSizeWithAncestors += modifySize;
343 assert(int64_t(nSizeWithAncestors) > 0);
344 nModFeesWithAncestors += modifyFee;
345 nCountWithAncestors += modifyCount;
346 assert(int64_t(nCountWithAncestors) > 0);
347 nSigOpCostWithAncestors += modifySigOps;
348 assert(int(nSigOpCostWithAncestors) >= 0);
351 CTxMemPool::CTxMemPool(const CFeeRate& _minReasonableRelayFee) :
352 nTransactionsUpdated(0)
354 _clear(); //lock free clear
356 // Sanity checks off by default for performance, because otherwise
357 // accepting transactions becomes O(N^2) where N is the number
358 // of transactions in the pool
359 nCheckFrequency = 0;
361 minerPolicyEstimator = new CBlockPolicyEstimator(_minReasonableRelayFee);
362 minReasonableRelayFee = _minReasonableRelayFee;
365 CTxMemPool::~CTxMemPool()
367 delete minerPolicyEstimator;
370 void CTxMemPool::pruneSpent(const uint256 &hashTx, CCoins &coins)
372 LOCK(cs);
374 auto it = mapNextTx.lower_bound(COutPoint(hashTx, 0));
376 // iterate over all COutPoints in mapNextTx whose hash equals the provided hashTx
377 while (it != mapNextTx.end() && it->first->hash == hashTx) {
378 coins.Spend(it->first->n); // and remove those outputs from coins
379 it++;
383 unsigned int CTxMemPool::GetTransactionsUpdated() const
385 LOCK(cs);
386 return nTransactionsUpdated;
389 void CTxMemPool::AddTransactionsUpdated(unsigned int n)
391 LOCK(cs);
392 nTransactionsUpdated += n;
395 bool CTxMemPool::addUnchecked(const uint256& hash, const CTxMemPoolEntry &entry, setEntries &setAncestors, bool fCurrentEstimate)
397 // Add to memory pool without checking anything.
398 // Used by main.cpp AcceptToMemoryPool(), which DOES do
399 // all the appropriate checks.
400 LOCK(cs);
401 indexed_transaction_set::iterator newit = mapTx.insert(entry).first;
402 mapLinks.insert(make_pair(newit, TxLinks()));
404 // Update transaction for any feeDelta created by PrioritiseTransaction
405 // TODO: refactor so that the fee delta is calculated before inserting
406 // into mapTx.
407 std::map<uint256, std::pair<double, CAmount> >::const_iterator pos = mapDeltas.find(hash);
408 if (pos != mapDeltas.end()) {
409 const std::pair<double, CAmount> &deltas = pos->second;
410 if (deltas.second) {
411 mapTx.modify(newit, update_fee_delta(deltas.second));
415 // Update cachedInnerUsage to include contained transaction's usage.
416 // (When we update the entry for in-mempool parents, memory usage will be
417 // further updated.)
418 cachedInnerUsage += entry.DynamicMemoryUsage();
420 const CTransaction& tx = newit->GetTx();
421 std::set<uint256> setParentTransactions;
422 for (unsigned int i = 0; i < tx.vin.size(); i++) {
423 mapNextTx.insert(std::make_pair(&tx.vin[i].prevout, &tx));
424 setParentTransactions.insert(tx.vin[i].prevout.hash);
426 // Don't bother worrying about child transactions of this one.
427 // Normal case of a new transaction arriving is that there can't be any
428 // children, because such children would be orphans.
429 // An exception to that is if a transaction enters that used to be in a block.
430 // In that case, our disconnect block logic will call UpdateTransactionsFromBlock
431 // to clean up the mess we're leaving here.
433 // Update ancestors with information about this tx
434 BOOST_FOREACH (const uint256 &phash, setParentTransactions) {
435 txiter pit = mapTx.find(phash);
436 if (pit != mapTx.end()) {
437 UpdateParent(newit, pit, true);
440 UpdateAncestorsOf(true, newit, setAncestors);
441 UpdateEntryForAncestors(newit, setAncestors);
443 nTransactionsUpdated++;
444 totalTxSize += entry.GetTxSize();
445 minerPolicyEstimator->processTransaction(entry, fCurrentEstimate);
447 vTxHashes.emplace_back(tx.GetWitnessHash(), newit);
448 newit->vTxHashesIdx = vTxHashes.size() - 1;
450 return true;
453 void CTxMemPool::removeUnchecked(txiter it)
455 const uint256 hash = it->GetTx().GetHash();
456 BOOST_FOREACH(const CTxIn& txin, it->GetTx().vin)
457 mapNextTx.erase(txin.prevout);
459 if (vTxHashes.size() > 1) {
460 vTxHashes[it->vTxHashesIdx] = std::move(vTxHashes.back());
461 vTxHashes[it->vTxHashesIdx].second->vTxHashesIdx = it->vTxHashesIdx;
462 vTxHashes.pop_back();
463 if (vTxHashes.size() * 2 < vTxHashes.capacity())
464 vTxHashes.shrink_to_fit();
465 } else
466 vTxHashes.clear();
468 totalTxSize -= it->GetTxSize();
469 cachedInnerUsage -= it->DynamicMemoryUsage();
470 cachedInnerUsage -= memusage::DynamicUsage(mapLinks[it].parents) + memusage::DynamicUsage(mapLinks[it].children);
471 mapLinks.erase(it);
472 mapTx.erase(it);
473 nTransactionsUpdated++;
474 minerPolicyEstimator->removeTx(hash);
477 // Calculates descendants of entry that are not already in setDescendants, and adds to
478 // setDescendants. Assumes entryit is already a tx in the mempool and setMemPoolChildren
479 // is correct for tx and all descendants.
480 // Also assumes that if an entry is in setDescendants already, then all
481 // in-mempool descendants of it are already in setDescendants as well, so that we
482 // can save time by not iterating over those entries.
483 void CTxMemPool::CalculateDescendants(txiter entryit, setEntries &setDescendants)
485 setEntries stage;
486 if (setDescendants.count(entryit) == 0) {
487 stage.insert(entryit);
489 // Traverse down the children of entry, only adding children that are not
490 // accounted for in setDescendants already (because those children have either
491 // already been walked, or will be walked in this iteration).
492 while (!stage.empty()) {
493 txiter it = *stage.begin();
494 setDescendants.insert(it);
495 stage.erase(it);
497 const setEntries &setChildren = GetMemPoolChildren(it);
498 BOOST_FOREACH(const txiter &childiter, setChildren) {
499 if (!setDescendants.count(childiter)) {
500 stage.insert(childiter);
506 void CTxMemPool::removeRecursive(const CTransaction &origTx, std::vector<std::shared_ptr<const CTransaction>>* removed)
508 // Remove transaction from memory pool
510 LOCK(cs);
511 setEntries txToRemove;
512 txiter origit = mapTx.find(origTx.GetHash());
513 if (origit != mapTx.end()) {
514 txToRemove.insert(origit);
515 } else {
516 // When recursively removing but origTx isn't in the mempool
517 // be sure to remove any children that are in the pool. This can
518 // happen during chain re-orgs if origTx isn't re-accepted into
519 // the mempool for any reason.
520 for (unsigned int i = 0; i < origTx.vout.size(); i++) {
521 auto it = mapNextTx.find(COutPoint(origTx.GetHash(), i));
522 if (it == mapNextTx.end())
523 continue;
524 txiter nextit = mapTx.find(it->second->GetHash());
525 assert(nextit != mapTx.end());
526 txToRemove.insert(nextit);
529 setEntries setAllRemoves;
530 BOOST_FOREACH(txiter it, txToRemove) {
531 CalculateDescendants(it, setAllRemoves);
533 if (removed) {
534 BOOST_FOREACH(txiter it, setAllRemoves) {
535 removed->emplace_back(it->GetSharedTx());
538 RemoveStaged(setAllRemoves, false);
542 void CTxMemPool::removeForReorg(const CCoinsViewCache *pcoins, unsigned int nMemPoolHeight, int flags)
544 // Remove transactions spending a coinbase which are now immature and no-longer-final transactions
545 LOCK(cs);
546 setEntries txToRemove;
547 for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
548 const CTransaction& tx = it->GetTx();
549 LockPoints lp = it->GetLockPoints();
550 bool validLP = TestLockPointValidity(&lp);
551 if (!CheckFinalTx(tx, flags) || !CheckSequenceLocks(tx, flags, &lp, validLP)) {
552 // Note if CheckSequenceLocks fails the LockPoints may still be invalid
553 // So it's critical that we remove the tx and not depend on the LockPoints.
554 txToRemove.insert(it);
555 } else if (it->GetSpendsCoinbase()) {
556 BOOST_FOREACH(const CTxIn& txin, tx.vin) {
557 indexed_transaction_set::const_iterator it2 = mapTx.find(txin.prevout.hash);
558 if (it2 != mapTx.end())
559 continue;
560 const CCoins *coins = pcoins->AccessCoins(txin.prevout.hash);
561 if (nCheckFrequency != 0) assert(coins);
562 if (!coins || (coins->IsCoinBase() && ((signed long)nMemPoolHeight) - coins->nHeight < COINBASE_MATURITY)) {
563 txToRemove.insert(it);
564 break;
568 if (!validLP) {
569 mapTx.modify(it, update_lock_points(lp));
572 setEntries setAllRemoves;
573 for (txiter it : txToRemove) {
574 CalculateDescendants(it, setAllRemoves);
576 RemoveStaged(setAllRemoves, false);
579 void CTxMemPool::removeConflicts(const CTransaction &tx, std::vector<std::shared_ptr<const CTransaction>>* removed)
581 // Remove transactions which depend on inputs of tx, recursively
582 LOCK(cs);
583 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
584 auto it = mapNextTx.find(txin.prevout);
585 if (it != mapNextTx.end()) {
586 const CTransaction &txConflict = *it->second;
587 if (txConflict != tx)
589 removeRecursive(txConflict, removed);
590 ClearPrioritisation(txConflict.GetHash());
597 * Called when a block is connected. Removes from mempool and updates the miner fee estimator.
599 void CTxMemPool::removeForBlock(const std::vector<CTransaction>& vtx, unsigned int nBlockHeight,
600 std::vector<std::shared_ptr<const CTransaction>>* conflicts, bool fCurrentEstimate)
602 LOCK(cs);
603 std::vector<CTxMemPoolEntry> entries;
604 BOOST_FOREACH(const CTransaction& tx, vtx)
606 uint256 hash = tx.GetHash();
608 indexed_transaction_set::iterator i = mapTx.find(hash);
609 if (i != mapTx.end())
610 entries.push_back(*i);
612 BOOST_FOREACH(const CTransaction& tx, vtx)
614 txiter it = mapTx.find(tx.GetHash());
615 if (it != mapTx.end()) {
616 setEntries stage;
617 stage.insert(it);
618 RemoveStaged(stage, true);
620 removeConflicts(tx, conflicts);
621 ClearPrioritisation(tx.GetHash());
623 // After the txs in the new block have been removed from the mempool, update policy estimates
624 minerPolicyEstimator->processBlock(nBlockHeight, entries, fCurrentEstimate);
625 lastRollingFeeUpdate = GetTime();
626 blockSinceLastRollingFeeBump = true;
629 void CTxMemPool::_clear()
631 mapLinks.clear();
632 mapTx.clear();
633 mapNextTx.clear();
634 totalTxSize = 0;
635 cachedInnerUsage = 0;
636 lastRollingFeeUpdate = GetTime();
637 blockSinceLastRollingFeeBump = false;
638 rollingMinimumFeeRate = 0;
639 ++nTransactionsUpdated;
642 void CTxMemPool::clear()
644 LOCK(cs);
645 _clear();
648 void CTxMemPool::check(const CCoinsViewCache *pcoins) const
650 if (nCheckFrequency == 0)
651 return;
653 if (GetRand(std::numeric_limits<uint32_t>::max()) >= nCheckFrequency)
654 return;
656 LogPrint("mempool", "Checking mempool with %u transactions and %u inputs\n", (unsigned int)mapTx.size(), (unsigned int)mapNextTx.size());
658 uint64_t checkTotal = 0;
659 uint64_t innerUsage = 0;
661 CCoinsViewCache mempoolDuplicate(const_cast<CCoinsViewCache*>(pcoins));
662 const int64_t nSpendHeight = GetSpendHeight(mempoolDuplicate);
664 LOCK(cs);
665 list<const CTxMemPoolEntry*> waitingOnDependants;
666 for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
667 unsigned int i = 0;
668 checkTotal += it->GetTxSize();
669 innerUsage += it->DynamicMemoryUsage();
670 const CTransaction& tx = it->GetTx();
671 txlinksMap::const_iterator linksiter = mapLinks.find(it);
672 assert(linksiter != mapLinks.end());
673 const TxLinks &links = linksiter->second;
674 innerUsage += memusage::DynamicUsage(links.parents) + memusage::DynamicUsage(links.children);
675 bool fDependsWait = false;
676 setEntries setParentCheck;
677 int64_t parentSizes = 0;
678 int64_t parentSigOpCost = 0;
679 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
680 // Check that every mempool transaction's inputs refer to available coins, or other mempool tx's.
681 indexed_transaction_set::const_iterator it2 = mapTx.find(txin.prevout.hash);
682 if (it2 != mapTx.end()) {
683 const CTransaction& tx2 = it2->GetTx();
684 assert(tx2.vout.size() > txin.prevout.n && !tx2.vout[txin.prevout.n].IsNull());
685 fDependsWait = true;
686 if (setParentCheck.insert(it2).second) {
687 parentSizes += it2->GetTxSize();
688 parentSigOpCost += it2->GetSigOpCost();
690 } else {
691 const CCoins* coins = pcoins->AccessCoins(txin.prevout.hash);
692 assert(coins && coins->IsAvailable(txin.prevout.n));
694 // Check whether its inputs are marked in mapNextTx.
695 auto it3 = mapNextTx.find(txin.prevout);
696 assert(it3 != mapNextTx.end());
697 assert(it3->first == &txin.prevout);
698 assert(it3->second == &tx);
699 i++;
701 assert(setParentCheck == GetMemPoolParents(it));
702 // Verify ancestor state is correct.
703 setEntries setAncestors;
704 uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();
705 std::string dummy;
706 CalculateMemPoolAncestors(*it, setAncestors, nNoLimit, nNoLimit, nNoLimit, nNoLimit, dummy);
707 uint64_t nCountCheck = setAncestors.size() + 1;
708 uint64_t nSizeCheck = it->GetTxSize();
709 CAmount nFeesCheck = it->GetModifiedFee();
710 int64_t nSigOpCheck = it->GetSigOpCost();
712 BOOST_FOREACH(txiter ancestorIt, setAncestors) {
713 nSizeCheck += ancestorIt->GetTxSize();
714 nFeesCheck += ancestorIt->GetModifiedFee();
715 nSigOpCheck += ancestorIt->GetSigOpCost();
718 assert(it->GetCountWithAncestors() == nCountCheck);
719 assert(it->GetSizeWithAncestors() == nSizeCheck);
720 assert(it->GetSigOpCostWithAncestors() == nSigOpCheck);
721 assert(it->GetModFeesWithAncestors() == nFeesCheck);
723 // Check children against mapNextTx
724 CTxMemPool::setEntries setChildrenCheck;
725 auto iter = mapNextTx.lower_bound(COutPoint(it->GetTx().GetHash(), 0));
726 int64_t childSizes = 0;
727 for (; iter != mapNextTx.end() && iter->first->hash == it->GetTx().GetHash(); ++iter) {
728 txiter childit = mapTx.find(iter->second->GetHash());
729 assert(childit != mapTx.end()); // mapNextTx points to in-mempool transactions
730 if (setChildrenCheck.insert(childit).second) {
731 childSizes += childit->GetTxSize();
734 assert(setChildrenCheck == GetMemPoolChildren(it));
735 // Also check to make sure size is greater than sum with immediate children.
736 // just a sanity check, not definitive that this calc is correct...
737 assert(it->GetSizeWithDescendants() >= childSizes + it->GetTxSize());
739 if (fDependsWait)
740 waitingOnDependants.push_back(&(*it));
741 else {
742 CValidationState state;
743 bool fCheckResult = tx.IsCoinBase() ||
744 Consensus::CheckTxInputs(tx, state, mempoolDuplicate, nSpendHeight);
745 assert(fCheckResult);
746 UpdateCoins(tx, mempoolDuplicate, 1000000);
749 unsigned int stepsSinceLastRemove = 0;
750 while (!waitingOnDependants.empty()) {
751 const CTxMemPoolEntry* entry = waitingOnDependants.front();
752 waitingOnDependants.pop_front();
753 CValidationState state;
754 if (!mempoolDuplicate.HaveInputs(entry->GetTx())) {
755 waitingOnDependants.push_back(entry);
756 stepsSinceLastRemove++;
757 assert(stepsSinceLastRemove < waitingOnDependants.size());
758 } else {
759 bool fCheckResult = entry->GetTx().IsCoinBase() ||
760 Consensus::CheckTxInputs(entry->GetTx(), state, mempoolDuplicate, nSpendHeight);
761 assert(fCheckResult);
762 UpdateCoins(entry->GetTx(), mempoolDuplicate, 1000000);
763 stepsSinceLastRemove = 0;
766 for (auto it = mapNextTx.cbegin(); it != mapNextTx.cend(); it++) {
767 uint256 hash = it->second->GetHash();
768 indexed_transaction_set::const_iterator it2 = mapTx.find(hash);
769 const CTransaction& tx = it2->GetTx();
770 assert(it2 != mapTx.end());
771 assert(&tx == it->second);
774 assert(totalTxSize == checkTotal);
775 assert(innerUsage == cachedInnerUsage);
778 bool CTxMemPool::CompareDepthAndScore(const uint256& hasha, const uint256& hashb)
780 LOCK(cs);
781 indexed_transaction_set::const_iterator i = mapTx.find(hasha);
782 if (i == mapTx.end()) return false;
783 indexed_transaction_set::const_iterator j = mapTx.find(hashb);
784 if (j == mapTx.end()) return true;
785 uint64_t counta = i->GetCountWithAncestors();
786 uint64_t countb = j->GetCountWithAncestors();
787 if (counta == countb) {
788 return CompareTxMemPoolEntryByScore()(*i, *j);
790 return counta < countb;
793 namespace {
794 class DepthAndScoreComparator
796 public:
797 bool operator()(const CTxMemPool::indexed_transaction_set::const_iterator& a, const CTxMemPool::indexed_transaction_set::const_iterator& b)
799 uint64_t counta = a->GetCountWithAncestors();
800 uint64_t countb = b->GetCountWithAncestors();
801 if (counta == countb) {
802 return CompareTxMemPoolEntryByScore()(*a, *b);
804 return counta < countb;
809 std::vector<CTxMemPool::indexed_transaction_set::const_iterator> CTxMemPool::GetSortedDepthAndScore() const
811 std::vector<indexed_transaction_set::const_iterator> iters;
812 AssertLockHeld(cs);
814 iters.reserve(mapTx.size());
816 for (indexed_transaction_set::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi) {
817 iters.push_back(mi);
819 std::sort(iters.begin(), iters.end(), DepthAndScoreComparator());
820 return iters;
823 void CTxMemPool::queryHashes(vector<uint256>& vtxid)
825 LOCK(cs);
826 auto iters = GetSortedDepthAndScore();
828 vtxid.clear();
829 vtxid.reserve(mapTx.size());
831 for (auto it : iters) {
832 vtxid.push_back(it->GetTx().GetHash());
836 static TxMempoolInfo GetInfo(CTxMemPool::indexed_transaction_set::const_iterator it) {
837 return TxMempoolInfo{it->GetSharedTx(), it->GetTime(), CFeeRate(it->GetFee(), it->GetTxSize()), it->GetModifiedFee() - it->GetFee()};
840 std::vector<TxMempoolInfo> CTxMemPool::infoAll() const
842 LOCK(cs);
843 auto iters = GetSortedDepthAndScore();
845 std::vector<TxMempoolInfo> ret;
846 ret.reserve(mapTx.size());
847 for (auto it : iters) {
848 ret.push_back(GetInfo(it));
851 return ret;
854 std::shared_ptr<const CTransaction> CTxMemPool::get(const uint256& hash) const
856 LOCK(cs);
857 indexed_transaction_set::const_iterator i = mapTx.find(hash);
858 if (i == mapTx.end())
859 return nullptr;
860 return i->GetSharedTx();
863 TxMempoolInfo CTxMemPool::info(const uint256& hash) const
865 LOCK(cs);
866 indexed_transaction_set::const_iterator i = mapTx.find(hash);
867 if (i == mapTx.end())
868 return TxMempoolInfo();
869 return GetInfo(i);
872 CFeeRate CTxMemPool::estimateFee(int nBlocks) const
874 LOCK(cs);
875 return minerPolicyEstimator->estimateFee(nBlocks);
877 CFeeRate CTxMemPool::estimateSmartFee(int nBlocks, int *answerFoundAtBlocks) const
879 LOCK(cs);
880 return minerPolicyEstimator->estimateSmartFee(nBlocks, answerFoundAtBlocks, *this);
882 double CTxMemPool::estimatePriority(int nBlocks) const
884 LOCK(cs);
885 return minerPolicyEstimator->estimatePriority(nBlocks);
887 double CTxMemPool::estimateSmartPriority(int nBlocks, int *answerFoundAtBlocks) const
889 LOCK(cs);
890 return minerPolicyEstimator->estimateSmartPriority(nBlocks, answerFoundAtBlocks, *this);
893 bool
894 CTxMemPool::WriteFeeEstimates(CAutoFile& fileout) const
896 try {
897 LOCK(cs);
898 fileout << 139900; // version required to read: 0.13.99 or later
899 fileout << CLIENT_VERSION; // version that wrote the file
900 minerPolicyEstimator->Write(fileout);
902 catch (const std::exception&) {
903 LogPrintf("CTxMemPool::WriteFeeEstimates(): unable to write policy estimator data (non-fatal)\n");
904 return false;
906 return true;
909 bool
910 CTxMemPool::ReadFeeEstimates(CAutoFile& filein)
912 try {
913 int nVersionRequired, nVersionThatWrote;
914 filein >> nVersionRequired >> nVersionThatWrote;
915 if (nVersionRequired > CLIENT_VERSION)
916 return error("CTxMemPool::ReadFeeEstimates(): up-version (%d) fee estimate file", nVersionRequired);
917 LOCK(cs);
918 minerPolicyEstimator->Read(filein, nVersionThatWrote);
920 catch (const std::exception&) {
921 LogPrintf("CTxMemPool::ReadFeeEstimates(): unable to read policy estimator data (non-fatal)\n");
922 return false;
924 return true;
927 void CTxMemPool::PrioritiseTransaction(const uint256 hash, const string strHash, double dPriorityDelta, const CAmount& nFeeDelta)
930 LOCK(cs);
931 std::pair<double, CAmount> &deltas = mapDeltas[hash];
932 deltas.first += dPriorityDelta;
933 deltas.second += nFeeDelta;
934 txiter it = mapTx.find(hash);
935 if (it != mapTx.end()) {
936 mapTx.modify(it, update_fee_delta(deltas.second));
937 // Now update all ancestors' modified fees with descendants
938 setEntries setAncestors;
939 uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();
940 std::string dummy;
941 CalculateMemPoolAncestors(*it, setAncestors, nNoLimit, nNoLimit, nNoLimit, nNoLimit, dummy, false);
942 BOOST_FOREACH(txiter ancestorIt, setAncestors) {
943 mapTx.modify(ancestorIt, update_descendant_state(0, nFeeDelta, 0));
947 LogPrintf("PrioritiseTransaction: %s priority += %f, fee += %d\n", strHash, dPriorityDelta, FormatMoney(nFeeDelta));
950 void CTxMemPool::ApplyDeltas(const uint256 hash, double &dPriorityDelta, CAmount &nFeeDelta) const
952 LOCK(cs);
953 std::map<uint256, std::pair<double, CAmount> >::const_iterator pos = mapDeltas.find(hash);
954 if (pos == mapDeltas.end())
955 return;
956 const std::pair<double, CAmount> &deltas = pos->second;
957 dPriorityDelta += deltas.first;
958 nFeeDelta += deltas.second;
961 void CTxMemPool::ClearPrioritisation(const uint256 hash)
963 LOCK(cs);
964 mapDeltas.erase(hash);
967 bool CTxMemPool::HasNoInputsOf(const CTransaction &tx) const
969 for (unsigned int i = 0; i < tx.vin.size(); i++)
970 if (exists(tx.vin[i].prevout.hash))
971 return false;
972 return true;
975 CCoinsViewMemPool::CCoinsViewMemPool(CCoinsView* baseIn, const CTxMemPool& mempoolIn) : CCoinsViewBacked(baseIn), mempool(mempoolIn) { }
977 bool CCoinsViewMemPool::GetCoins(const uint256 &txid, CCoins &coins) const {
978 // If an entry in the mempool exists, always return that one, as it's guaranteed to never
979 // conflict with the underlying cache, and it cannot have pruned entries (as it contains full)
980 // transactions. First checking the underlying cache risks returning a pruned entry instead.
981 shared_ptr<const CTransaction> ptx = mempool.get(txid);
982 if (ptx) {
983 coins = CCoins(*ptx, MEMPOOL_HEIGHT);
984 return true;
986 return (base->GetCoins(txid, coins) && !coins.IsPruned());
989 bool CCoinsViewMemPool::HaveCoins(const uint256 &txid) const {
990 return mempool.exists(txid) || base->HaveCoins(txid);
993 size_t CTxMemPool::DynamicMemoryUsage() const {
994 LOCK(cs);
995 // Estimate the overhead of mapTx to be 15 pointers + an allocation, as no exact formula for boost::multi_index_contained is implemented.
996 return memusage::MallocUsage(sizeof(CTxMemPoolEntry) + 15 * sizeof(void*)) * mapTx.size() + memusage::DynamicUsage(mapNextTx) + memusage::DynamicUsage(mapDeltas) + memusage::DynamicUsage(mapLinks) + memusage::DynamicUsage(vTxHashes) + cachedInnerUsage;
999 void CTxMemPool::RemoveStaged(setEntries &stage, bool updateDescendants) {
1000 AssertLockHeld(cs);
1001 UpdateForRemoveFromMempool(stage, updateDescendants);
1002 BOOST_FOREACH(const txiter& it, stage) {
1003 removeUnchecked(it);
1007 int CTxMemPool::Expire(int64_t time) {
1008 LOCK(cs);
1009 indexed_transaction_set::index<entry_time>::type::iterator it = mapTx.get<entry_time>().begin();
1010 setEntries toremove;
1011 while (it != mapTx.get<entry_time>().end() && it->GetTime() < time) {
1012 toremove.insert(mapTx.project<0>(it));
1013 it++;
1015 setEntries stage;
1016 BOOST_FOREACH(txiter removeit, toremove) {
1017 CalculateDescendants(removeit, stage);
1019 RemoveStaged(stage, false);
1020 return stage.size();
1023 bool CTxMemPool::addUnchecked(const uint256&hash, const CTxMemPoolEntry &entry, bool fCurrentEstimate)
1025 LOCK(cs);
1026 setEntries setAncestors;
1027 uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();
1028 std::string dummy;
1029 CalculateMemPoolAncestors(entry, setAncestors, nNoLimit, nNoLimit, nNoLimit, nNoLimit, dummy);
1030 return addUnchecked(hash, entry, setAncestors, fCurrentEstimate);
1033 void CTxMemPool::UpdateChild(txiter entry, txiter child, bool add)
1035 setEntries s;
1036 if (add && mapLinks[entry].children.insert(child).second) {
1037 cachedInnerUsage += memusage::IncrementalDynamicUsage(s);
1038 } else if (!add && mapLinks[entry].children.erase(child)) {
1039 cachedInnerUsage -= memusage::IncrementalDynamicUsage(s);
1043 void CTxMemPool::UpdateParent(txiter entry, txiter parent, bool add)
1045 setEntries s;
1046 if (add && mapLinks[entry].parents.insert(parent).second) {
1047 cachedInnerUsage += memusage::IncrementalDynamicUsage(s);
1048 } else if (!add && mapLinks[entry].parents.erase(parent)) {
1049 cachedInnerUsage -= memusage::IncrementalDynamicUsage(s);
1053 const CTxMemPool::setEntries & CTxMemPool::GetMemPoolParents(txiter entry) const
1055 assert (entry != mapTx.end());
1056 txlinksMap::const_iterator it = mapLinks.find(entry);
1057 assert(it != mapLinks.end());
1058 return it->second.parents;
1061 const CTxMemPool::setEntries & CTxMemPool::GetMemPoolChildren(txiter entry) const
1063 assert (entry != mapTx.end());
1064 txlinksMap::const_iterator it = mapLinks.find(entry);
1065 assert(it != mapLinks.end());
1066 return it->second.children;
1069 CFeeRate CTxMemPool::GetMinFee(size_t sizelimit) const {
1070 LOCK(cs);
1071 if (!blockSinceLastRollingFeeBump || rollingMinimumFeeRate == 0)
1072 return CFeeRate(rollingMinimumFeeRate);
1074 int64_t time = GetTime();
1075 if (time > lastRollingFeeUpdate + 10) {
1076 double halflife = ROLLING_FEE_HALFLIFE;
1077 if (DynamicMemoryUsage() < sizelimit / 4)
1078 halflife /= 4;
1079 else if (DynamicMemoryUsage() < sizelimit / 2)
1080 halflife /= 2;
1082 rollingMinimumFeeRate = rollingMinimumFeeRate / pow(2.0, (time - lastRollingFeeUpdate) / halflife);
1083 lastRollingFeeUpdate = time;
1085 if (rollingMinimumFeeRate < minReasonableRelayFee.GetFeePerK() / 2) {
1086 rollingMinimumFeeRate = 0;
1087 return CFeeRate(0);
1090 return std::max(CFeeRate(rollingMinimumFeeRate), minReasonableRelayFee);
1093 void CTxMemPool::trackPackageRemoved(const CFeeRate& rate) {
1094 AssertLockHeld(cs);
1095 if (rate.GetFeePerK() > rollingMinimumFeeRate) {
1096 rollingMinimumFeeRate = rate.GetFeePerK();
1097 blockSinceLastRollingFeeBump = false;
1101 void CTxMemPool::TrimToSize(size_t sizelimit, std::vector<uint256>* pvNoSpendsRemaining) {
1102 LOCK(cs);
1104 unsigned nTxnRemoved = 0;
1105 CFeeRate maxFeeRateRemoved(0);
1106 while (!mapTx.empty() && DynamicMemoryUsage() > sizelimit) {
1107 indexed_transaction_set::index<descendant_score>::type::iterator it = mapTx.get<descendant_score>().begin();
1109 // We set the new mempool min fee to the feerate of the removed set, plus the
1110 // "minimum reasonable fee rate" (ie some value under which we consider txn
1111 // to have 0 fee). This way, we don't allow txn to enter mempool with feerate
1112 // equal to txn which were removed with no block in between.
1113 CFeeRate removed(it->GetModFeesWithDescendants(), it->GetSizeWithDescendants());
1114 removed += minReasonableRelayFee;
1115 trackPackageRemoved(removed);
1116 maxFeeRateRemoved = std::max(maxFeeRateRemoved, removed);
1118 setEntries stage;
1119 CalculateDescendants(mapTx.project<0>(it), stage);
1120 nTxnRemoved += stage.size();
1122 std::vector<CTransaction> txn;
1123 if (pvNoSpendsRemaining) {
1124 txn.reserve(stage.size());
1125 BOOST_FOREACH(txiter iter, stage)
1126 txn.push_back(iter->GetTx());
1128 RemoveStaged(stage, false);
1129 if (pvNoSpendsRemaining) {
1130 BOOST_FOREACH(const CTransaction& tx, txn) {
1131 BOOST_FOREACH(const CTxIn& txin, tx.vin) {
1132 if (exists(txin.prevout.hash))
1133 continue;
1134 auto iter = mapNextTx.lower_bound(COutPoint(txin.prevout.hash, 0));
1135 if (iter == mapNextTx.end() || iter->first->hash != txin.prevout.hash)
1136 pvNoSpendsRemaining->push_back(txin.prevout.hash);
1142 if (maxFeeRateRemoved > CFeeRate(0))
1143 LogPrint("mempool", "Removed %u txn, rolling minimum fee bumped to %s\n", nTxnRemoved, maxFeeRateRemoved.ToString());