Header include guideline
[bitcoinplatinum.git] / src / txmempool.cpp
blob17389db9f089827d7c120f729b012e45f65e2aeb
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 #include "txmempool.h"
8 #include "consensus/consensus.h"
9 #include "consensus/tx_verify.h"
10 #include "consensus/validation.h"
11 #include "validation.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"
20 CTxMemPoolEntry::CTxMemPoolEntry(const CTransactionRef& _tx, const CAmount& _nFee,
21 int64_t _nTime, unsigned int _entryHeight,
22 bool _spendsCoinbase, int64_t _sigOpsCost, LockPoints lp):
23 tx(_tx), nFee(_nFee), nTime(_nTime), entryHeight(_entryHeight),
24 spendsCoinbase(_spendsCoinbase), sigOpCost(_sigOpsCost), lockPoints(lp)
26 nTxWeight = GetTransactionWeight(*tx);
27 nUsageSize = RecursiveDynamicUsage(tx);
29 nCountWithDescendants = 1;
30 nSizeWithDescendants = GetTxSize();
31 nModFeesWithDescendants = nFee;
33 feeDelta = 0;
35 nCountWithAncestors = 1;
36 nSizeWithAncestors = GetTxSize();
37 nModFeesWithAncestors = nFee;
38 nSigOpCostWithAncestors = sigOpCost;
41 CTxMemPoolEntry::CTxMemPoolEntry(const CTxMemPoolEntry& other)
43 *this = other;
46 void CTxMemPoolEntry::UpdateFeeDelta(int64_t newFeeDelta)
48 nModFeesWithDescendants += newFeeDelta - feeDelta;
49 nModFeesWithAncestors += newFeeDelta - feeDelta;
50 feeDelta = newFeeDelta;
53 void CTxMemPoolEntry::UpdateLockPoints(const LockPoints& lp)
55 lockPoints = lp;
58 size_t CTxMemPoolEntry::GetTxSize() const
60 return GetVirtualTransactionSize(nTxWeight, sigOpCost);
63 // Update the given tx for any in-mempool descendants.
64 // Assumes that setMemPoolChildren is correct for the given tx and all
65 // descendants.
66 void CTxMemPool::UpdateForDescendants(txiter updateIt, cacheMap &cachedDescendants, const std::set<uint256> &setExclude)
68 setEntries stageEntries, setAllDescendants;
69 stageEntries = GetMemPoolChildren(updateIt);
71 while (!stageEntries.empty()) {
72 const txiter cit = *stageEntries.begin();
73 setAllDescendants.insert(cit);
74 stageEntries.erase(cit);
75 const setEntries &setChildren = GetMemPoolChildren(cit);
76 BOOST_FOREACH(const txiter childEntry, setChildren) {
77 cacheMap::iterator cacheIt = cachedDescendants.find(childEntry);
78 if (cacheIt != cachedDescendants.end()) {
79 // We've already calculated this one, just add the entries for this set
80 // but don't traverse again.
81 BOOST_FOREACH(const txiter cacheEntry, cacheIt->second) {
82 setAllDescendants.insert(cacheEntry);
84 } else if (!setAllDescendants.count(childEntry)) {
85 // Schedule for later processing
86 stageEntries.insert(childEntry);
90 // setAllDescendants now contains all in-mempool descendants of updateIt.
91 // Update and add to cached descendant map
92 int64_t modifySize = 0;
93 CAmount modifyFee = 0;
94 int64_t modifyCount = 0;
95 BOOST_FOREACH(txiter cit, setAllDescendants) {
96 if (!setExclude.count(cit->GetTx().GetHash())) {
97 modifySize += cit->GetTxSize();
98 modifyFee += cit->GetModifiedFee();
99 modifyCount++;
100 cachedDescendants[updateIt].insert(cit);
101 // Update ancestor state for each descendant
102 mapTx.modify(cit, update_ancestor_state(updateIt->GetTxSize(), updateIt->GetModifiedFee(), 1, updateIt->GetSigOpCost()));
105 mapTx.modify(updateIt, update_descendant_state(modifySize, modifyFee, modifyCount));
108 // vHashesToUpdate is the set of transaction hashes from a disconnected block
109 // which has been re-added to the mempool.
110 // for each entry, look for descendants that are outside vHashesToUpdate, and
111 // add fee/size information for such descendants to the parent.
112 // for each such descendant, also update the ancestor state to include the parent.
113 void CTxMemPool::UpdateTransactionsFromBlock(const std::vector<uint256> &vHashesToUpdate)
115 LOCK(cs);
116 // For each entry in vHashesToUpdate, store the set of in-mempool, but not
117 // in-vHashesToUpdate transactions, so that we don't have to recalculate
118 // descendants when we come across a previously seen entry.
119 cacheMap mapMemPoolDescendantsToUpdate;
121 // Use a set for lookups into vHashesToUpdate (these entries are already
122 // accounted for in the state of their ancestors)
123 std::set<uint256> setAlreadyIncluded(vHashesToUpdate.begin(), vHashesToUpdate.end());
125 // Iterate in reverse, so that whenever we are looking at at a transaction
126 // we are sure that all in-mempool descendants have already been processed.
127 // This maximizes the benefit of the descendant cache and guarantees that
128 // setMemPoolChildren will be updated, an assumption made in
129 // UpdateForDescendants.
130 BOOST_REVERSE_FOREACH(const uint256 &hash, vHashesToUpdate) {
131 // we cache the in-mempool children to avoid duplicate updates
132 setEntries setChildren;
133 // calculate children from mapNextTx
134 txiter it = mapTx.find(hash);
135 if (it == mapTx.end()) {
136 continue;
138 auto iter = mapNextTx.lower_bound(COutPoint(hash, 0));
139 // First calculate the children, and update setMemPoolChildren to
140 // include them, and update their setMemPoolParents to include this tx.
141 for (; iter != mapNextTx.end() && iter->first->hash == hash; ++iter) {
142 const uint256 &childHash = iter->second->GetHash();
143 txiter childIter = mapTx.find(childHash);
144 assert(childIter != mapTx.end());
145 // We can skip updating entries we've encountered before or that
146 // are in the block (which are already accounted for).
147 if (setChildren.insert(childIter).second && !setAlreadyIncluded.count(childHash)) {
148 UpdateChild(it, childIter, true);
149 UpdateParent(childIter, it, true);
152 UpdateForDescendants(it, mapMemPoolDescendantsToUpdate, setAlreadyIncluded);
156 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
158 LOCK(cs);
160 setEntries parentHashes;
161 const CTransaction &tx = entry.GetTx();
163 if (fSearchForParents) {
164 // Get parents of this transaction that are in the mempool
165 // GetMemPoolParents() is only valid for entries in the mempool, so we
166 // iterate mapTx to find parents.
167 for (unsigned int i = 0; i < tx.vin.size(); i++) {
168 txiter piter = mapTx.find(tx.vin[i].prevout.hash);
169 if (piter != mapTx.end()) {
170 parentHashes.insert(piter);
171 if (parentHashes.size() + 1 > limitAncestorCount) {
172 errString = strprintf("too many unconfirmed parents [limit: %u]", limitAncestorCount);
173 return false;
177 } else {
178 // If we're not searching for parents, we require this to be an
179 // entry in the mempool already.
180 txiter it = mapTx.iterator_to(entry);
181 parentHashes = GetMemPoolParents(it);
184 size_t totalSizeWithAncestors = entry.GetTxSize();
186 while (!parentHashes.empty()) {
187 txiter stageit = *parentHashes.begin();
189 setAncestors.insert(stageit);
190 parentHashes.erase(stageit);
191 totalSizeWithAncestors += stageit->GetTxSize();
193 if (stageit->GetSizeWithDescendants() + entry.GetTxSize() > limitDescendantSize) {
194 errString = strprintf("exceeds descendant size limit for tx %s [limit: %u]", stageit->GetTx().GetHash().ToString(), limitDescendantSize);
195 return false;
196 } else if (stageit->GetCountWithDescendants() + 1 > limitDescendantCount) {
197 errString = strprintf("too many descendants for tx %s [limit: %u]", stageit->GetTx().GetHash().ToString(), limitDescendantCount);
198 return false;
199 } else if (totalSizeWithAncestors > limitAncestorSize) {
200 errString = strprintf("exceeds ancestor size limit [limit: %u]", limitAncestorSize);
201 return false;
204 const setEntries & setMemPoolParents = GetMemPoolParents(stageit);
205 BOOST_FOREACH(const txiter &phash, setMemPoolParents) {
206 // If this is a new ancestor, add it.
207 if (setAncestors.count(phash) == 0) {
208 parentHashes.insert(phash);
210 if (parentHashes.size() + setAncestors.size() + 1 > limitAncestorCount) {
211 errString = strprintf("too many unconfirmed ancestors [limit: %u]", limitAncestorCount);
212 return false;
217 return true;
220 void CTxMemPool::UpdateAncestorsOf(bool add, txiter it, setEntries &setAncestors)
222 setEntries parentIters = GetMemPoolParents(it);
223 // add or remove this tx as a child of each parent
224 BOOST_FOREACH(txiter piter, parentIters) {
225 UpdateChild(piter, it, add);
227 const int64_t updateCount = (add ? 1 : -1);
228 const int64_t updateSize = updateCount * it->GetTxSize();
229 const CAmount updateFee = updateCount * it->GetModifiedFee();
230 BOOST_FOREACH(txiter ancestorIt, setAncestors) {
231 mapTx.modify(ancestorIt, update_descendant_state(updateSize, updateFee, updateCount));
235 void CTxMemPool::UpdateEntryForAncestors(txiter it, const setEntries &setAncestors)
237 int64_t updateCount = setAncestors.size();
238 int64_t updateSize = 0;
239 CAmount updateFee = 0;
240 int64_t updateSigOpsCost = 0;
241 BOOST_FOREACH(txiter ancestorIt, setAncestors) {
242 updateSize += ancestorIt->GetTxSize();
243 updateFee += ancestorIt->GetModifiedFee();
244 updateSigOpsCost += ancestorIt->GetSigOpCost();
246 mapTx.modify(it, update_ancestor_state(updateSize, updateFee, updateCount, updateSigOpsCost));
249 void CTxMemPool::UpdateChildrenForRemoval(txiter it)
251 const setEntries &setMemPoolChildren = GetMemPoolChildren(it);
252 BOOST_FOREACH(txiter updateIt, setMemPoolChildren) {
253 UpdateParent(updateIt, it, false);
257 void CTxMemPool::UpdateForRemoveFromMempool(const setEntries &entriesToRemove, bool updateDescendants)
259 // For each entry, walk back all ancestors and decrement size associated with this
260 // transaction
261 const uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();
262 if (updateDescendants) {
263 // updateDescendants should be true whenever we're not recursively
264 // removing a tx and all its descendants, eg when a transaction is
265 // confirmed in a block.
266 // Here we only update statistics and not data in mapLinks (which
267 // we need to preserve until we're finished with all operations that
268 // need to traverse the mempool).
269 BOOST_FOREACH(txiter removeIt, entriesToRemove) {
270 setEntries setDescendants;
271 CalculateDescendants(removeIt, setDescendants);
272 setDescendants.erase(removeIt); // don't update state for self
273 int64_t modifySize = -((int64_t)removeIt->GetTxSize());
274 CAmount modifyFee = -removeIt->GetModifiedFee();
275 int modifySigOps = -removeIt->GetSigOpCost();
276 BOOST_FOREACH(txiter dit, setDescendants) {
277 mapTx.modify(dit, update_ancestor_state(modifySize, modifyFee, -1, modifySigOps));
281 BOOST_FOREACH(txiter removeIt, entriesToRemove) {
282 setEntries setAncestors;
283 const CTxMemPoolEntry &entry = *removeIt;
284 std::string dummy;
285 // Since this is a tx that is already in the mempool, we can call CMPA
286 // with fSearchForParents = false. If the mempool is in a consistent
287 // state, then using true or false should both be correct, though false
288 // should be a bit faster.
289 // However, if we happen to be in the middle of processing a reorg, then
290 // the mempool can be in an inconsistent state. In this case, the set
291 // of ancestors reachable via mapLinks will be the same as the set of
292 // ancestors whose packages include this transaction, because when we
293 // add a new transaction to the mempool in addUnchecked(), we assume it
294 // has no children, and in the case of a reorg where that assumption is
295 // false, the in-mempool children aren't linked to the in-block tx's
296 // until UpdateTransactionsFromBlock() is called.
297 // So if we're being called during a reorg, ie before
298 // UpdateTransactionsFromBlock() has been called, then mapLinks[] will
299 // differ from the set of mempool parents we'd calculate by searching,
300 // and it's important that we use the mapLinks[] notion of ancestor
301 // transactions as the set of things to update for removal.
302 CalculateMemPoolAncestors(entry, setAncestors, nNoLimit, nNoLimit, nNoLimit, nNoLimit, dummy, false);
303 // Note that UpdateAncestorsOf severs the child links that point to
304 // removeIt in the entries for the parents of removeIt.
305 UpdateAncestorsOf(false, removeIt, setAncestors);
307 // After updating all the ancestor sizes, we can now sever the link between each
308 // transaction being removed and any mempool children (ie, update setMemPoolParents
309 // for each direct child of a transaction being removed).
310 BOOST_FOREACH(txiter removeIt, entriesToRemove) {
311 UpdateChildrenForRemoval(removeIt);
315 void CTxMemPoolEntry::UpdateDescendantState(int64_t modifySize, CAmount modifyFee, int64_t modifyCount)
317 nSizeWithDescendants += modifySize;
318 assert(int64_t(nSizeWithDescendants) > 0);
319 nModFeesWithDescendants += modifyFee;
320 nCountWithDescendants += modifyCount;
321 assert(int64_t(nCountWithDescendants) > 0);
324 void CTxMemPoolEntry::UpdateAncestorState(int64_t modifySize, CAmount modifyFee, int64_t modifyCount, int modifySigOps)
326 nSizeWithAncestors += modifySize;
327 assert(int64_t(nSizeWithAncestors) > 0);
328 nModFeesWithAncestors += modifyFee;
329 nCountWithAncestors += modifyCount;
330 assert(int64_t(nCountWithAncestors) > 0);
331 nSigOpCostWithAncestors += modifySigOps;
332 assert(int(nSigOpCostWithAncestors) >= 0);
335 CTxMemPool::CTxMemPool(CBlockPolicyEstimator* estimator) :
336 nTransactionsUpdated(0), minerPolicyEstimator(estimator)
338 _clear(); //lock free clear
340 // Sanity checks off by default for performance, because otherwise
341 // accepting transactions becomes O(N^2) where N is the number
342 // of transactions in the pool
343 nCheckFrequency = 0;
346 bool CTxMemPool::isSpent(const COutPoint& outpoint)
348 LOCK(cs);
349 return mapNextTx.count(outpoint);
352 unsigned int CTxMemPool::GetTransactionsUpdated() const
354 LOCK(cs);
355 return nTransactionsUpdated;
358 void CTxMemPool::AddTransactionsUpdated(unsigned int n)
360 LOCK(cs);
361 nTransactionsUpdated += n;
364 bool CTxMemPool::addUnchecked(const uint256& hash, const CTxMemPoolEntry &entry, setEntries &setAncestors, bool validFeeEstimate)
366 NotifyEntryAdded(entry.GetSharedTx());
367 // Add to memory pool without checking anything.
368 // Used by AcceptToMemoryPool(), which DOES do
369 // all the appropriate checks.
370 LOCK(cs);
371 indexed_transaction_set::iterator newit = mapTx.insert(entry).first;
372 mapLinks.insert(make_pair(newit, TxLinks()));
374 // Update transaction for any feeDelta created by PrioritiseTransaction
375 // TODO: refactor so that the fee delta is calculated before inserting
376 // into mapTx.
377 std::map<uint256, CAmount>::const_iterator pos = mapDeltas.find(hash);
378 if (pos != mapDeltas.end()) {
379 const CAmount &delta = pos->second;
380 if (delta) {
381 mapTx.modify(newit, update_fee_delta(delta));
385 // Update cachedInnerUsage to include contained transaction's usage.
386 // (When we update the entry for in-mempool parents, memory usage will be
387 // further updated.)
388 cachedInnerUsage += entry.DynamicMemoryUsage();
390 const CTransaction& tx = newit->GetTx();
391 std::set<uint256> setParentTransactions;
392 for (unsigned int i = 0; i < tx.vin.size(); i++) {
393 mapNextTx.insert(std::make_pair(&tx.vin[i].prevout, &tx));
394 setParentTransactions.insert(tx.vin[i].prevout.hash);
396 // Don't bother worrying about child transactions of this one.
397 // Normal case of a new transaction arriving is that there can't be any
398 // children, because such children would be orphans.
399 // An exception to that is if a transaction enters that used to be in a block.
400 // In that case, our disconnect block logic will call UpdateTransactionsFromBlock
401 // to clean up the mess we're leaving here.
403 // Update ancestors with information about this tx
404 BOOST_FOREACH (const uint256 &phash, setParentTransactions) {
405 txiter pit = mapTx.find(phash);
406 if (pit != mapTx.end()) {
407 UpdateParent(newit, pit, true);
410 UpdateAncestorsOf(true, newit, setAncestors);
411 UpdateEntryForAncestors(newit, setAncestors);
413 nTransactionsUpdated++;
414 totalTxSize += entry.GetTxSize();
415 if (minerPolicyEstimator) {minerPolicyEstimator->processTransaction(entry, validFeeEstimate);}
417 vTxHashes.emplace_back(tx.GetWitnessHash(), newit);
418 newit->vTxHashesIdx = vTxHashes.size() - 1;
420 return true;
423 void CTxMemPool::removeUnchecked(txiter it, MemPoolRemovalReason reason)
425 NotifyEntryRemoved(it->GetSharedTx(), reason);
426 const uint256 hash = it->GetTx().GetHash();
427 BOOST_FOREACH(const CTxIn& txin, it->GetTx().vin)
428 mapNextTx.erase(txin.prevout);
430 if (vTxHashes.size() > 1) {
431 vTxHashes[it->vTxHashesIdx] = std::move(vTxHashes.back());
432 vTxHashes[it->vTxHashesIdx].second->vTxHashesIdx = it->vTxHashesIdx;
433 vTxHashes.pop_back();
434 if (vTxHashes.size() * 2 < vTxHashes.capacity())
435 vTxHashes.shrink_to_fit();
436 } else
437 vTxHashes.clear();
439 totalTxSize -= it->GetTxSize();
440 cachedInnerUsage -= it->DynamicMemoryUsage();
441 cachedInnerUsage -= memusage::DynamicUsage(mapLinks[it].parents) + memusage::DynamicUsage(mapLinks[it].children);
442 mapLinks.erase(it);
443 mapTx.erase(it);
444 nTransactionsUpdated++;
445 if (minerPolicyEstimator) {minerPolicyEstimator->removeTx(hash, false);}
448 // Calculates descendants of entry that are not already in setDescendants, and adds to
449 // setDescendants. Assumes entryit is already a tx in the mempool and setMemPoolChildren
450 // is correct for tx and all descendants.
451 // Also assumes that if an entry is in setDescendants already, then all
452 // in-mempool descendants of it are already in setDescendants as well, so that we
453 // can save time by not iterating over those entries.
454 void CTxMemPool::CalculateDescendants(txiter entryit, setEntries &setDescendants)
456 setEntries stage;
457 if (setDescendants.count(entryit) == 0) {
458 stage.insert(entryit);
460 // Traverse down the children of entry, only adding children that are not
461 // accounted for in setDescendants already (because those children have either
462 // already been walked, or will be walked in this iteration).
463 while (!stage.empty()) {
464 txiter it = *stage.begin();
465 setDescendants.insert(it);
466 stage.erase(it);
468 const setEntries &setChildren = GetMemPoolChildren(it);
469 BOOST_FOREACH(const txiter &childiter, setChildren) {
470 if (!setDescendants.count(childiter)) {
471 stage.insert(childiter);
477 void CTxMemPool::removeRecursive(const CTransaction &origTx, MemPoolRemovalReason reason)
479 // Remove transaction from memory pool
481 LOCK(cs);
482 setEntries txToRemove;
483 txiter origit = mapTx.find(origTx.GetHash());
484 if (origit != mapTx.end()) {
485 txToRemove.insert(origit);
486 } else {
487 // When recursively removing but origTx isn't in the mempool
488 // be sure to remove any children that are in the pool. This can
489 // happen during chain re-orgs if origTx isn't re-accepted into
490 // the mempool for any reason.
491 for (unsigned int i = 0; i < origTx.vout.size(); i++) {
492 auto it = mapNextTx.find(COutPoint(origTx.GetHash(), i));
493 if (it == mapNextTx.end())
494 continue;
495 txiter nextit = mapTx.find(it->second->GetHash());
496 assert(nextit != mapTx.end());
497 txToRemove.insert(nextit);
500 setEntries setAllRemoves;
501 BOOST_FOREACH(txiter it, txToRemove) {
502 CalculateDescendants(it, setAllRemoves);
505 RemoveStaged(setAllRemoves, false, reason);
509 void CTxMemPool::removeForReorg(const CCoinsViewCache *pcoins, unsigned int nMemPoolHeight, int flags)
511 // Remove transactions spending a coinbase which are now immature and no-longer-final transactions
512 LOCK(cs);
513 setEntries txToRemove;
514 for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
515 const CTransaction& tx = it->GetTx();
516 LockPoints lp = it->GetLockPoints();
517 bool validLP = TestLockPointValidity(&lp);
518 if (!CheckFinalTx(tx, flags) || !CheckSequenceLocks(tx, flags, &lp, validLP)) {
519 // Note if CheckSequenceLocks fails the LockPoints may still be invalid
520 // So it's critical that we remove the tx and not depend on the LockPoints.
521 txToRemove.insert(it);
522 } else if (it->GetSpendsCoinbase()) {
523 BOOST_FOREACH(const CTxIn& txin, tx.vin) {
524 indexed_transaction_set::const_iterator it2 = mapTx.find(txin.prevout.hash);
525 if (it2 != mapTx.end())
526 continue;
527 const Coin &coin = pcoins->AccessCoin(txin.prevout);
528 if (nCheckFrequency != 0) assert(!coin.IsSpent());
529 if (coin.IsSpent() || (coin.IsCoinBase() && ((signed long)nMemPoolHeight) - coin.nHeight < COINBASE_MATURITY)) {
530 txToRemove.insert(it);
531 break;
535 if (!validLP) {
536 mapTx.modify(it, update_lock_points(lp));
539 setEntries setAllRemoves;
540 for (txiter it : txToRemove) {
541 CalculateDescendants(it, setAllRemoves);
543 RemoveStaged(setAllRemoves, false, MemPoolRemovalReason::REORG);
546 void CTxMemPool::removeConflicts(const CTransaction &tx)
548 // Remove transactions which depend on inputs of tx, recursively
549 LOCK(cs);
550 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
551 auto it = mapNextTx.find(txin.prevout);
552 if (it != mapNextTx.end()) {
553 const CTransaction &txConflict = *it->second;
554 if (txConflict != tx)
556 ClearPrioritisation(txConflict.GetHash());
557 removeRecursive(txConflict, MemPoolRemovalReason::CONFLICT);
564 * Called when a block is connected. Removes from mempool and updates the miner fee estimator.
566 void CTxMemPool::removeForBlock(const std::vector<CTransactionRef>& vtx, unsigned int nBlockHeight)
568 LOCK(cs);
569 std::vector<const CTxMemPoolEntry*> entries;
570 for (const auto& tx : vtx)
572 uint256 hash = tx->GetHash();
574 indexed_transaction_set::iterator i = mapTx.find(hash);
575 if (i != mapTx.end())
576 entries.push_back(&*i);
578 // Before the txs in the new block have been removed from the mempool, update policy estimates
579 if (minerPolicyEstimator) {minerPolicyEstimator->processBlock(nBlockHeight, entries);}
580 for (const auto& tx : vtx)
582 txiter it = mapTx.find(tx->GetHash());
583 if (it != mapTx.end()) {
584 setEntries stage;
585 stage.insert(it);
586 RemoveStaged(stage, true, MemPoolRemovalReason::BLOCK);
588 removeConflicts(*tx);
589 ClearPrioritisation(tx->GetHash());
591 lastRollingFeeUpdate = GetTime();
592 blockSinceLastRollingFeeBump = true;
595 void CTxMemPool::_clear()
597 mapLinks.clear();
598 mapTx.clear();
599 mapNextTx.clear();
600 totalTxSize = 0;
601 cachedInnerUsage = 0;
602 lastRollingFeeUpdate = GetTime();
603 blockSinceLastRollingFeeBump = false;
604 rollingMinimumFeeRate = 0;
605 ++nTransactionsUpdated;
608 void CTxMemPool::clear()
610 LOCK(cs);
611 _clear();
614 void CTxMemPool::check(const CCoinsViewCache *pcoins) const
616 if (nCheckFrequency == 0)
617 return;
619 if (GetRand(std::numeric_limits<uint32_t>::max()) >= nCheckFrequency)
620 return;
622 LogPrint(BCLog::MEMPOOL, "Checking mempool with %u transactions and %u inputs\n", (unsigned int)mapTx.size(), (unsigned int)mapNextTx.size());
624 uint64_t checkTotal = 0;
625 uint64_t innerUsage = 0;
627 CCoinsViewCache mempoolDuplicate(const_cast<CCoinsViewCache*>(pcoins));
628 const int64_t nSpendHeight = GetSpendHeight(mempoolDuplicate);
630 LOCK(cs);
631 std::list<const CTxMemPoolEntry*> waitingOnDependants;
632 for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
633 unsigned int i = 0;
634 checkTotal += it->GetTxSize();
635 innerUsage += it->DynamicMemoryUsage();
636 const CTransaction& tx = it->GetTx();
637 txlinksMap::const_iterator linksiter = mapLinks.find(it);
638 assert(linksiter != mapLinks.end());
639 const TxLinks &links = linksiter->second;
640 innerUsage += memusage::DynamicUsage(links.parents) + memusage::DynamicUsage(links.children);
641 bool fDependsWait = false;
642 setEntries setParentCheck;
643 int64_t parentSizes = 0;
644 int64_t parentSigOpCost = 0;
645 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
646 // Check that every mempool transaction's inputs refer to available coins, or other mempool tx's.
647 indexed_transaction_set::const_iterator it2 = mapTx.find(txin.prevout.hash);
648 if (it2 != mapTx.end()) {
649 const CTransaction& tx2 = it2->GetTx();
650 assert(tx2.vout.size() > txin.prevout.n && !tx2.vout[txin.prevout.n].IsNull());
651 fDependsWait = true;
652 if (setParentCheck.insert(it2).second) {
653 parentSizes += it2->GetTxSize();
654 parentSigOpCost += it2->GetSigOpCost();
656 } else {
657 assert(pcoins->HaveCoin(txin.prevout));
659 // Check whether its inputs are marked in mapNextTx.
660 auto it3 = mapNextTx.find(txin.prevout);
661 assert(it3 != mapNextTx.end());
662 assert(it3->first == &txin.prevout);
663 assert(it3->second == &tx);
664 i++;
666 assert(setParentCheck == GetMemPoolParents(it));
667 // Verify ancestor state is correct.
668 setEntries setAncestors;
669 uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();
670 std::string dummy;
671 CalculateMemPoolAncestors(*it, setAncestors, nNoLimit, nNoLimit, nNoLimit, nNoLimit, dummy);
672 uint64_t nCountCheck = setAncestors.size() + 1;
673 uint64_t nSizeCheck = it->GetTxSize();
674 CAmount nFeesCheck = it->GetModifiedFee();
675 int64_t nSigOpCheck = it->GetSigOpCost();
677 BOOST_FOREACH(txiter ancestorIt, setAncestors) {
678 nSizeCheck += ancestorIt->GetTxSize();
679 nFeesCheck += ancestorIt->GetModifiedFee();
680 nSigOpCheck += ancestorIt->GetSigOpCost();
683 assert(it->GetCountWithAncestors() == nCountCheck);
684 assert(it->GetSizeWithAncestors() == nSizeCheck);
685 assert(it->GetSigOpCostWithAncestors() == nSigOpCheck);
686 assert(it->GetModFeesWithAncestors() == nFeesCheck);
688 // Check children against mapNextTx
689 CTxMemPool::setEntries setChildrenCheck;
690 auto iter = mapNextTx.lower_bound(COutPoint(it->GetTx().GetHash(), 0));
691 int64_t childSizes = 0;
692 for (; iter != mapNextTx.end() && iter->first->hash == it->GetTx().GetHash(); ++iter) {
693 txiter childit = mapTx.find(iter->second->GetHash());
694 assert(childit != mapTx.end()); // mapNextTx points to in-mempool transactions
695 if (setChildrenCheck.insert(childit).second) {
696 childSizes += childit->GetTxSize();
699 assert(setChildrenCheck == GetMemPoolChildren(it));
700 // Also check to make sure size is greater than sum with immediate children.
701 // just a sanity check, not definitive that this calc is correct...
702 assert(it->GetSizeWithDescendants() >= childSizes + it->GetTxSize());
704 if (fDependsWait)
705 waitingOnDependants.push_back(&(*it));
706 else {
707 CValidationState state;
708 bool fCheckResult = tx.IsCoinBase() ||
709 Consensus::CheckTxInputs(tx, state, mempoolDuplicate, nSpendHeight);
710 assert(fCheckResult);
711 UpdateCoins(tx, mempoolDuplicate, 1000000);
714 unsigned int stepsSinceLastRemove = 0;
715 while (!waitingOnDependants.empty()) {
716 const CTxMemPoolEntry* entry = waitingOnDependants.front();
717 waitingOnDependants.pop_front();
718 CValidationState state;
719 if (!mempoolDuplicate.HaveInputs(entry->GetTx())) {
720 waitingOnDependants.push_back(entry);
721 stepsSinceLastRemove++;
722 assert(stepsSinceLastRemove < waitingOnDependants.size());
723 } else {
724 bool fCheckResult = entry->GetTx().IsCoinBase() ||
725 Consensus::CheckTxInputs(entry->GetTx(), state, mempoolDuplicate, nSpendHeight);
726 assert(fCheckResult);
727 UpdateCoins(entry->GetTx(), mempoolDuplicate, 1000000);
728 stepsSinceLastRemove = 0;
731 for (auto it = mapNextTx.cbegin(); it != mapNextTx.cend(); it++) {
732 uint256 hash = it->second->GetHash();
733 indexed_transaction_set::const_iterator it2 = mapTx.find(hash);
734 const CTransaction& tx = it2->GetTx();
735 assert(it2 != mapTx.end());
736 assert(&tx == it->second);
739 assert(totalTxSize == checkTotal);
740 assert(innerUsage == cachedInnerUsage);
743 bool CTxMemPool::CompareDepthAndScore(const uint256& hasha, const uint256& hashb)
745 LOCK(cs);
746 indexed_transaction_set::const_iterator i = mapTx.find(hasha);
747 if (i == mapTx.end()) return false;
748 indexed_transaction_set::const_iterator j = mapTx.find(hashb);
749 if (j == mapTx.end()) return true;
750 uint64_t counta = i->GetCountWithAncestors();
751 uint64_t countb = j->GetCountWithAncestors();
752 if (counta == countb) {
753 return CompareTxMemPoolEntryByScore()(*i, *j);
755 return counta < countb;
758 namespace {
759 class DepthAndScoreComparator
761 public:
762 bool operator()(const CTxMemPool::indexed_transaction_set::const_iterator& a, const CTxMemPool::indexed_transaction_set::const_iterator& b)
764 uint64_t counta = a->GetCountWithAncestors();
765 uint64_t countb = b->GetCountWithAncestors();
766 if (counta == countb) {
767 return CompareTxMemPoolEntryByScore()(*a, *b);
769 return counta < countb;
774 std::vector<CTxMemPool::indexed_transaction_set::const_iterator> CTxMemPool::GetSortedDepthAndScore() const
776 std::vector<indexed_transaction_set::const_iterator> iters;
777 AssertLockHeld(cs);
779 iters.reserve(mapTx.size());
781 for (indexed_transaction_set::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi) {
782 iters.push_back(mi);
784 std::sort(iters.begin(), iters.end(), DepthAndScoreComparator());
785 return iters;
788 void CTxMemPool::queryHashes(std::vector<uint256>& vtxid)
790 LOCK(cs);
791 auto iters = GetSortedDepthAndScore();
793 vtxid.clear();
794 vtxid.reserve(mapTx.size());
796 for (auto it : iters) {
797 vtxid.push_back(it->GetTx().GetHash());
801 static TxMempoolInfo GetInfo(CTxMemPool::indexed_transaction_set::const_iterator it) {
802 return TxMempoolInfo{it->GetSharedTx(), it->GetTime(), CFeeRate(it->GetFee(), it->GetTxSize()), it->GetModifiedFee() - it->GetFee()};
805 std::vector<TxMempoolInfo> CTxMemPool::infoAll() const
807 LOCK(cs);
808 auto iters = GetSortedDepthAndScore();
810 std::vector<TxMempoolInfo> ret;
811 ret.reserve(mapTx.size());
812 for (auto it : iters) {
813 ret.push_back(GetInfo(it));
816 return ret;
819 CTransactionRef CTxMemPool::get(const uint256& hash) const
821 LOCK(cs);
822 indexed_transaction_set::const_iterator i = mapTx.find(hash);
823 if (i == mapTx.end())
824 return nullptr;
825 return i->GetSharedTx();
828 TxMempoolInfo CTxMemPool::info(const uint256& hash) const
830 LOCK(cs);
831 indexed_transaction_set::const_iterator i = mapTx.find(hash);
832 if (i == mapTx.end())
833 return TxMempoolInfo();
834 return GetInfo(i);
837 void CTxMemPool::PrioritiseTransaction(const uint256& hash, const CAmount& nFeeDelta)
840 LOCK(cs);
841 CAmount &delta = mapDeltas[hash];
842 delta += nFeeDelta;
843 txiter it = mapTx.find(hash);
844 if (it != mapTx.end()) {
845 mapTx.modify(it, update_fee_delta(delta));
846 // Now update all ancestors' modified fees with descendants
847 setEntries setAncestors;
848 uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();
849 std::string dummy;
850 CalculateMemPoolAncestors(*it, setAncestors, nNoLimit, nNoLimit, nNoLimit, nNoLimit, dummy, false);
851 BOOST_FOREACH(txiter ancestorIt, setAncestors) {
852 mapTx.modify(ancestorIt, update_descendant_state(0, nFeeDelta, 0));
854 // Now update all descendants' modified fees with ancestors
855 setEntries setDescendants;
856 CalculateDescendants(it, setDescendants);
857 setDescendants.erase(it);
858 BOOST_FOREACH(txiter descendantIt, setDescendants) {
859 mapTx.modify(descendantIt, update_ancestor_state(0, nFeeDelta, 0, 0));
861 ++nTransactionsUpdated;
864 LogPrintf("PrioritiseTransaction: %s feerate += %s\n", hash.ToString(), FormatMoney(nFeeDelta));
867 void CTxMemPool::ApplyDelta(const uint256 hash, CAmount &nFeeDelta) const
869 LOCK(cs);
870 std::map<uint256, CAmount>::const_iterator pos = mapDeltas.find(hash);
871 if (pos == mapDeltas.end())
872 return;
873 const CAmount &delta = pos->second;
874 nFeeDelta += delta;
877 void CTxMemPool::ClearPrioritisation(const uint256 hash)
879 LOCK(cs);
880 mapDeltas.erase(hash);
883 bool CTxMemPool::HasNoInputsOf(const CTransaction &tx) const
885 for (unsigned int i = 0; i < tx.vin.size(); i++)
886 if (exists(tx.vin[i].prevout.hash))
887 return false;
888 return true;
891 CCoinsViewMemPool::CCoinsViewMemPool(CCoinsView* baseIn, const CTxMemPool& mempoolIn) : CCoinsViewBacked(baseIn), mempool(mempoolIn) { }
893 bool CCoinsViewMemPool::GetCoin(const COutPoint &outpoint, Coin &coin) const {
894 // If an entry in the mempool exists, always return that one, as it's guaranteed to never
895 // conflict with the underlying cache, and it cannot have pruned entries (as it contains full)
896 // transactions. First checking the underlying cache risks returning a pruned entry instead.
897 CTransactionRef ptx = mempool.get(outpoint.hash);
898 if (ptx) {
899 if (outpoint.n < ptx->vout.size()) {
900 coin = Coin(ptx->vout[outpoint.n], MEMPOOL_HEIGHT, false);
901 return true;
902 } else {
903 return false;
906 return (base->GetCoin(outpoint, coin) && !coin.IsSpent());
909 bool CCoinsViewMemPool::HaveCoin(const COutPoint &outpoint) const {
910 return mempool.exists(outpoint) || base->HaveCoin(outpoint);
913 size_t CTxMemPool::DynamicMemoryUsage() const {
914 LOCK(cs);
915 // Estimate the overhead of mapTx to be 15 pointers + an allocation, as no exact formula for boost::multi_index_contained is implemented.
916 return memusage::MallocUsage(sizeof(CTxMemPoolEntry) + 15 * sizeof(void*)) * mapTx.size() + memusage::DynamicUsage(mapNextTx) + memusage::DynamicUsage(mapDeltas) + memusage::DynamicUsage(mapLinks) + memusage::DynamicUsage(vTxHashes) + cachedInnerUsage;
919 void CTxMemPool::RemoveStaged(setEntries &stage, bool updateDescendants, MemPoolRemovalReason reason) {
920 AssertLockHeld(cs);
921 UpdateForRemoveFromMempool(stage, updateDescendants);
922 BOOST_FOREACH(const txiter& it, stage) {
923 removeUnchecked(it, reason);
927 int CTxMemPool::Expire(int64_t time) {
928 LOCK(cs);
929 indexed_transaction_set::index<entry_time>::type::iterator it = mapTx.get<entry_time>().begin();
930 setEntries toremove;
931 while (it != mapTx.get<entry_time>().end() && it->GetTime() < time) {
932 toremove.insert(mapTx.project<0>(it));
933 it++;
935 setEntries stage;
936 BOOST_FOREACH(txiter removeit, toremove) {
937 CalculateDescendants(removeit, stage);
939 RemoveStaged(stage, false, MemPoolRemovalReason::EXPIRY);
940 return stage.size();
943 bool CTxMemPool::addUnchecked(const uint256&hash, const CTxMemPoolEntry &entry, bool validFeeEstimate)
945 LOCK(cs);
946 setEntries setAncestors;
947 uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();
948 std::string dummy;
949 CalculateMemPoolAncestors(entry, setAncestors, nNoLimit, nNoLimit, nNoLimit, nNoLimit, dummy);
950 return addUnchecked(hash, entry, setAncestors, validFeeEstimate);
953 void CTxMemPool::UpdateChild(txiter entry, txiter child, bool add)
955 setEntries s;
956 if (add && mapLinks[entry].children.insert(child).second) {
957 cachedInnerUsage += memusage::IncrementalDynamicUsage(s);
958 } else if (!add && mapLinks[entry].children.erase(child)) {
959 cachedInnerUsage -= memusage::IncrementalDynamicUsage(s);
963 void CTxMemPool::UpdateParent(txiter entry, txiter parent, bool add)
965 setEntries s;
966 if (add && mapLinks[entry].parents.insert(parent).second) {
967 cachedInnerUsage += memusage::IncrementalDynamicUsage(s);
968 } else if (!add && mapLinks[entry].parents.erase(parent)) {
969 cachedInnerUsage -= memusage::IncrementalDynamicUsage(s);
973 const CTxMemPool::setEntries & CTxMemPool::GetMemPoolParents(txiter entry) const
975 assert (entry != mapTx.end());
976 txlinksMap::const_iterator it = mapLinks.find(entry);
977 assert(it != mapLinks.end());
978 return it->second.parents;
981 const CTxMemPool::setEntries & CTxMemPool::GetMemPoolChildren(txiter entry) const
983 assert (entry != mapTx.end());
984 txlinksMap::const_iterator it = mapLinks.find(entry);
985 assert(it != mapLinks.end());
986 return it->second.children;
989 CFeeRate CTxMemPool::GetMinFee(size_t sizelimit) const {
990 LOCK(cs);
991 if (!blockSinceLastRollingFeeBump || rollingMinimumFeeRate == 0)
992 return CFeeRate(rollingMinimumFeeRate);
994 int64_t time = GetTime();
995 if (time > lastRollingFeeUpdate + 10) {
996 double halflife = ROLLING_FEE_HALFLIFE;
997 if (DynamicMemoryUsage() < sizelimit / 4)
998 halflife /= 4;
999 else if (DynamicMemoryUsage() < sizelimit / 2)
1000 halflife /= 2;
1002 rollingMinimumFeeRate = rollingMinimumFeeRate / pow(2.0, (time - lastRollingFeeUpdate) / halflife);
1003 lastRollingFeeUpdate = time;
1005 if (rollingMinimumFeeRate < (double)incrementalRelayFee.GetFeePerK() / 2) {
1006 rollingMinimumFeeRate = 0;
1007 return CFeeRate(0);
1010 return std::max(CFeeRate(rollingMinimumFeeRate), incrementalRelayFee);
1013 void CTxMemPool::trackPackageRemoved(const CFeeRate& rate) {
1014 AssertLockHeld(cs);
1015 if (rate.GetFeePerK() > rollingMinimumFeeRate) {
1016 rollingMinimumFeeRate = rate.GetFeePerK();
1017 blockSinceLastRollingFeeBump = false;
1021 void CTxMemPool::TrimToSize(size_t sizelimit, std::vector<COutPoint>* pvNoSpendsRemaining) {
1022 LOCK(cs);
1024 unsigned nTxnRemoved = 0;
1025 CFeeRate maxFeeRateRemoved(0);
1026 while (!mapTx.empty() && DynamicMemoryUsage() > sizelimit) {
1027 indexed_transaction_set::index<descendant_score>::type::iterator it = mapTx.get<descendant_score>().begin();
1029 // We set the new mempool min fee to the feerate of the removed set, plus the
1030 // "minimum reasonable fee rate" (ie some value under which we consider txn
1031 // to have 0 fee). This way, we don't allow txn to enter mempool with feerate
1032 // equal to txn which were removed with no block in between.
1033 CFeeRate removed(it->GetModFeesWithDescendants(), it->GetSizeWithDescendants());
1034 removed += incrementalRelayFee;
1035 trackPackageRemoved(removed);
1036 maxFeeRateRemoved = std::max(maxFeeRateRemoved, removed);
1038 setEntries stage;
1039 CalculateDescendants(mapTx.project<0>(it), stage);
1040 nTxnRemoved += stage.size();
1042 std::vector<CTransaction> txn;
1043 if (pvNoSpendsRemaining) {
1044 txn.reserve(stage.size());
1045 BOOST_FOREACH(txiter iter, stage)
1046 txn.push_back(iter->GetTx());
1048 RemoveStaged(stage, false, MemPoolRemovalReason::SIZELIMIT);
1049 if (pvNoSpendsRemaining) {
1050 BOOST_FOREACH(const CTransaction& tx, txn) {
1051 BOOST_FOREACH(const CTxIn& txin, tx.vin) {
1052 if (exists(txin.prevout.hash)) continue;
1053 if (!mapNextTx.count(txin.prevout)) {
1054 pvNoSpendsRemaining->push_back(txin.prevout);
1061 if (maxFeeRateRemoved > CFeeRate(0)) {
1062 LogPrint(BCLog::MEMPOOL, "Removed %u txn, rolling minimum fee bumped to %s\n", nTxnRemoved, maxFeeRateRemoved.ToString());
1066 bool CTxMemPool::TransactionWithinChainLimit(const uint256& txid, size_t chainLimit) const {
1067 LOCK(cs);
1068 auto it = mapTx.find(txid);
1069 return it == mapTx.end() || (it->GetCountWithAncestors() < chainLimit &&
1070 it->GetCountWithDescendants() < chainLimit);
1073 SaltedTxidHasher::SaltedTxidHasher() : k0(GetRand(std::numeric_limits<uint64_t>::max())), k1(GetRand(std::numeric_limits<uint64_t>::max())) {}