Merge #11997: [tests] util_tests.cpp: actually check ignored args
[bitcoinplatinum.git] / src / txmempool.cpp
blobffb024aef94156f28be5f5cbbb8f011194d75e85
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2017 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 <reverse_iterator.h>
15 #include <streams.h>
16 #include <timedata.h>
17 #include <util.h>
18 #include <utilmoneystr.h>
19 #include <utiltime.h>
21 CTxMemPoolEntry::CTxMemPoolEntry(const CTransactionRef& _tx, const CAmount& _nFee,
22 int64_t _nTime, unsigned int _entryHeight,
23 bool _spendsCoinbase, int64_t _sigOpsCost, LockPoints lp):
24 tx(_tx), nFee(_nFee), nTime(_nTime), entryHeight(_entryHeight),
25 spendsCoinbase(_spendsCoinbase), sigOpCost(_sigOpsCost), lockPoints(lp)
27 nTxWeight = GetTransactionWeight(*tx);
28 nUsageSize = RecursiveDynamicUsage(tx);
30 nCountWithDescendants = 1;
31 nSizeWithDescendants = GetTxSize();
32 nModFeesWithDescendants = nFee;
34 feeDelta = 0;
36 nCountWithAncestors = 1;
37 nSizeWithAncestors = GetTxSize();
38 nModFeesWithAncestors = nFee;
39 nSigOpCostWithAncestors = sigOpCost;
42 void CTxMemPoolEntry::UpdateFeeDelta(int64_t newFeeDelta)
44 nModFeesWithDescendants += newFeeDelta - feeDelta;
45 nModFeesWithAncestors += newFeeDelta - feeDelta;
46 feeDelta = newFeeDelta;
49 void CTxMemPoolEntry::UpdateLockPoints(const LockPoints& lp)
51 lockPoints = lp;
54 size_t CTxMemPoolEntry::GetTxSize() const
56 return GetVirtualTransactionSize(nTxWeight, sigOpCost);
59 // Update the given tx for any in-mempool descendants.
60 // Assumes that setMemPoolChildren is correct for the given tx and all
61 // descendants.
62 void CTxMemPool::UpdateForDescendants(txiter updateIt, cacheMap &cachedDescendants, const std::set<uint256> &setExclude)
64 setEntries stageEntries, setAllDescendants;
65 stageEntries = GetMemPoolChildren(updateIt);
67 while (!stageEntries.empty()) {
68 const txiter cit = *stageEntries.begin();
69 setAllDescendants.insert(cit);
70 stageEntries.erase(cit);
71 const setEntries &setChildren = GetMemPoolChildren(cit);
72 for (const txiter childEntry : setChildren) {
73 cacheMap::iterator cacheIt = cachedDescendants.find(childEntry);
74 if (cacheIt != cachedDescendants.end()) {
75 // We've already calculated this one, just add the entries for this set
76 // but don't traverse again.
77 for (const txiter cacheEntry : cacheIt->second) {
78 setAllDescendants.insert(cacheEntry);
80 } else if (!setAllDescendants.count(childEntry)) {
81 // Schedule for later processing
82 stageEntries.insert(childEntry);
86 // setAllDescendants now contains all in-mempool descendants of updateIt.
87 // Update and add to cached descendant map
88 int64_t modifySize = 0;
89 CAmount modifyFee = 0;
90 int64_t modifyCount = 0;
91 for (txiter cit : setAllDescendants) {
92 if (!setExclude.count(cit->GetTx().GetHash())) {
93 modifySize += cit->GetTxSize();
94 modifyFee += cit->GetModifiedFee();
95 modifyCount++;
96 cachedDescendants[updateIt].insert(cit);
97 // Update ancestor state for each descendant
98 mapTx.modify(cit, update_ancestor_state(updateIt->GetTxSize(), updateIt->GetModifiedFee(), 1, updateIt->GetSigOpCost()));
101 mapTx.modify(updateIt, update_descendant_state(modifySize, modifyFee, modifyCount));
104 // vHashesToUpdate is the set of transaction hashes from a disconnected block
105 // which has been re-added to the mempool.
106 // for each entry, look for descendants that are outside vHashesToUpdate, and
107 // add fee/size information for such descendants to the parent.
108 // for each such descendant, also update the ancestor state to include the parent.
109 void CTxMemPool::UpdateTransactionsFromBlock(const std::vector<uint256> &vHashesToUpdate)
111 LOCK(cs);
112 // For each entry in vHashesToUpdate, store the set of in-mempool, but not
113 // in-vHashesToUpdate transactions, so that we don't have to recalculate
114 // descendants when we come across a previously seen entry.
115 cacheMap mapMemPoolDescendantsToUpdate;
117 // Use a set for lookups into vHashesToUpdate (these entries are already
118 // accounted for in the state of their ancestors)
119 std::set<uint256> setAlreadyIncluded(vHashesToUpdate.begin(), vHashesToUpdate.end());
121 // Iterate in reverse, so that whenever we are looking at a transaction
122 // we are sure that all in-mempool descendants have already been processed.
123 // This maximizes the benefit of the descendant cache and guarantees that
124 // setMemPoolChildren will be updated, an assumption made in
125 // UpdateForDescendants.
126 for (const uint256 &hash : reverse_iterate(vHashesToUpdate)) {
127 // we cache the in-mempool children to avoid duplicate updates
128 setEntries setChildren;
129 // calculate children from mapNextTx
130 txiter it = mapTx.find(hash);
131 if (it == mapTx.end()) {
132 continue;
134 auto iter = mapNextTx.lower_bound(COutPoint(hash, 0));
135 // First calculate the children, and update setMemPoolChildren to
136 // include them, and update their setMemPoolParents to include this tx.
137 for (; iter != mapNextTx.end() && iter->first->hash == hash; ++iter) {
138 const uint256 &childHash = iter->second->GetHash();
139 txiter childIter = mapTx.find(childHash);
140 assert(childIter != mapTx.end());
141 // We can skip updating entries we've encountered before or that
142 // are in the block (which are already accounted for).
143 if (setChildren.insert(childIter).second && !setAlreadyIncluded.count(childHash)) {
144 UpdateChild(it, childIter, true);
145 UpdateParent(childIter, it, true);
148 UpdateForDescendants(it, mapMemPoolDescendantsToUpdate, setAlreadyIncluded);
152 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
154 LOCK(cs);
156 setEntries parentHashes;
157 const CTransaction &tx = entry.GetTx();
159 if (fSearchForParents) {
160 // Get parents of this transaction that are in the mempool
161 // GetMemPoolParents() is only valid for entries in the mempool, so we
162 // iterate mapTx to find parents.
163 for (unsigned int i = 0; i < tx.vin.size(); i++) {
164 txiter piter = mapTx.find(tx.vin[i].prevout.hash);
165 if (piter != mapTx.end()) {
166 parentHashes.insert(piter);
167 if (parentHashes.size() + 1 > limitAncestorCount) {
168 errString = strprintf("too many unconfirmed parents [limit: %u]", limitAncestorCount);
169 return false;
173 } else {
174 // If we're not searching for parents, we require this to be an
175 // entry in the mempool already.
176 txiter it = mapTx.iterator_to(entry);
177 parentHashes = GetMemPoolParents(it);
180 size_t totalSizeWithAncestors = entry.GetTxSize();
182 while (!parentHashes.empty()) {
183 txiter stageit = *parentHashes.begin();
185 setAncestors.insert(stageit);
186 parentHashes.erase(stageit);
187 totalSizeWithAncestors += stageit->GetTxSize();
189 if (stageit->GetSizeWithDescendants() + entry.GetTxSize() > limitDescendantSize) {
190 errString = strprintf("exceeds descendant size limit for tx %s [limit: %u]", stageit->GetTx().GetHash().ToString(), limitDescendantSize);
191 return false;
192 } else if (stageit->GetCountWithDescendants() + 1 > limitDescendantCount) {
193 errString = strprintf("too many descendants for tx %s [limit: %u]", stageit->GetTx().GetHash().ToString(), limitDescendantCount);
194 return false;
195 } else if (totalSizeWithAncestors > limitAncestorSize) {
196 errString = strprintf("exceeds ancestor size limit [limit: %u]", limitAncestorSize);
197 return false;
200 const setEntries & setMemPoolParents = GetMemPoolParents(stageit);
201 for (const txiter &phash : setMemPoolParents) {
202 // If this is a new ancestor, add it.
203 if (setAncestors.count(phash) == 0) {
204 parentHashes.insert(phash);
206 if (parentHashes.size() + setAncestors.size() + 1 > limitAncestorCount) {
207 errString = strprintf("too many unconfirmed ancestors [limit: %u]", limitAncestorCount);
208 return false;
213 return true;
216 void CTxMemPool::UpdateAncestorsOf(bool add, txiter it, setEntries &setAncestors)
218 setEntries parentIters = GetMemPoolParents(it);
219 // add or remove this tx as a child of each parent
220 for (txiter piter : parentIters) {
221 UpdateChild(piter, it, add);
223 const int64_t updateCount = (add ? 1 : -1);
224 const int64_t updateSize = updateCount * it->GetTxSize();
225 const CAmount updateFee = updateCount * it->GetModifiedFee();
226 for (txiter ancestorIt : setAncestors) {
227 mapTx.modify(ancestorIt, update_descendant_state(updateSize, updateFee, updateCount));
231 void CTxMemPool::UpdateEntryForAncestors(txiter it, const setEntries &setAncestors)
233 int64_t updateCount = setAncestors.size();
234 int64_t updateSize = 0;
235 CAmount updateFee = 0;
236 int64_t updateSigOpsCost = 0;
237 for (txiter ancestorIt : setAncestors) {
238 updateSize += ancestorIt->GetTxSize();
239 updateFee += ancestorIt->GetModifiedFee();
240 updateSigOpsCost += ancestorIt->GetSigOpCost();
242 mapTx.modify(it, update_ancestor_state(updateSize, updateFee, updateCount, updateSigOpsCost));
245 void CTxMemPool::UpdateChildrenForRemoval(txiter it)
247 const setEntries &setMemPoolChildren = GetMemPoolChildren(it);
248 for (txiter updateIt : setMemPoolChildren) {
249 UpdateParent(updateIt, it, false);
253 void CTxMemPool::UpdateForRemoveFromMempool(const setEntries &entriesToRemove, bool updateDescendants)
255 // For each entry, walk back all ancestors and decrement size associated with this
256 // transaction
257 const uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();
258 if (updateDescendants) {
259 // updateDescendants should be true whenever we're not recursively
260 // removing a tx and all its descendants, eg when a transaction is
261 // confirmed in a block.
262 // Here we only update statistics and not data in mapLinks (which
263 // we need to preserve until we're finished with all operations that
264 // need to traverse the mempool).
265 for (txiter removeIt : entriesToRemove) {
266 setEntries setDescendants;
267 CalculateDescendants(removeIt, setDescendants);
268 setDescendants.erase(removeIt); // don't update state for self
269 int64_t modifySize = -((int64_t)removeIt->GetTxSize());
270 CAmount modifyFee = -removeIt->GetModifiedFee();
271 int modifySigOps = -removeIt->GetSigOpCost();
272 for (txiter dit : setDescendants) {
273 mapTx.modify(dit, update_ancestor_state(modifySize, modifyFee, -1, modifySigOps));
277 for (txiter removeIt : entriesToRemove) {
278 setEntries setAncestors;
279 const CTxMemPoolEntry &entry = *removeIt;
280 std::string dummy;
281 // Since this is a tx that is already in the mempool, we can call CMPA
282 // with fSearchForParents = false. If the mempool is in a consistent
283 // state, then using true or false should both be correct, though false
284 // should be a bit faster.
285 // However, if we happen to be in the middle of processing a reorg, then
286 // the mempool can be in an inconsistent state. In this case, the set
287 // of ancestors reachable via mapLinks will be the same as the set of
288 // ancestors whose packages include this transaction, because when we
289 // add a new transaction to the mempool in addUnchecked(), we assume it
290 // has no children, and in the case of a reorg where that assumption is
291 // false, the in-mempool children aren't linked to the in-block tx's
292 // until UpdateTransactionsFromBlock() is called.
293 // So if we're being called during a reorg, ie before
294 // UpdateTransactionsFromBlock() has been called, then mapLinks[] will
295 // differ from the set of mempool parents we'd calculate by searching,
296 // and it's important that we use the mapLinks[] notion of ancestor
297 // transactions as the set of things to update for removal.
298 CalculateMemPoolAncestors(entry, setAncestors, nNoLimit, nNoLimit, nNoLimit, nNoLimit, dummy, false);
299 // Note that UpdateAncestorsOf severs the child links that point to
300 // removeIt in the entries for the parents of removeIt.
301 UpdateAncestorsOf(false, removeIt, setAncestors);
303 // After updating all the ancestor sizes, we can now sever the link between each
304 // transaction being removed and any mempool children (ie, update setMemPoolParents
305 // for each direct child of a transaction being removed).
306 for (txiter removeIt : entriesToRemove) {
307 UpdateChildrenForRemoval(removeIt);
311 void CTxMemPoolEntry::UpdateDescendantState(int64_t modifySize, CAmount modifyFee, int64_t modifyCount)
313 nSizeWithDescendants += modifySize;
314 assert(int64_t(nSizeWithDescendants) > 0);
315 nModFeesWithDescendants += modifyFee;
316 nCountWithDescendants += modifyCount;
317 assert(int64_t(nCountWithDescendants) > 0);
320 void CTxMemPoolEntry::UpdateAncestorState(int64_t modifySize, CAmount modifyFee, int64_t modifyCount, int64_t modifySigOps)
322 nSizeWithAncestors += modifySize;
323 assert(int64_t(nSizeWithAncestors) > 0);
324 nModFeesWithAncestors += modifyFee;
325 nCountWithAncestors += modifyCount;
326 assert(int64_t(nCountWithAncestors) > 0);
327 nSigOpCostWithAncestors += modifySigOps;
328 assert(int(nSigOpCostWithAncestors) >= 0);
331 CTxMemPool::CTxMemPool(CBlockPolicyEstimator* estimator) :
332 nTransactionsUpdated(0), minerPolicyEstimator(estimator)
334 _clear(); //lock free clear
336 // Sanity checks off by default for performance, because otherwise
337 // accepting transactions becomes O(N^2) where N is the number
338 // of transactions in the pool
339 nCheckFrequency = 0;
342 bool CTxMemPool::isSpent(const COutPoint& outpoint)
344 LOCK(cs);
345 return mapNextTx.count(outpoint);
348 unsigned int CTxMemPool::GetTransactionsUpdated() const
350 LOCK(cs);
351 return nTransactionsUpdated;
354 void CTxMemPool::AddTransactionsUpdated(unsigned int n)
356 LOCK(cs);
357 nTransactionsUpdated += n;
360 bool CTxMemPool::addUnchecked(const uint256& hash, const CTxMemPoolEntry &entry, setEntries &setAncestors, bool validFeeEstimate)
362 NotifyEntryAdded(entry.GetSharedTx());
363 // Add to memory pool without checking anything.
364 // Used by AcceptToMemoryPool(), which DOES do
365 // all the appropriate checks.
366 LOCK(cs);
367 indexed_transaction_set::iterator newit = mapTx.insert(entry).first;
368 mapLinks.insert(make_pair(newit, TxLinks()));
370 // Update transaction for any feeDelta created by PrioritiseTransaction
371 // TODO: refactor so that the fee delta is calculated before inserting
372 // into mapTx.
373 std::map<uint256, CAmount>::const_iterator pos = mapDeltas.find(hash);
374 if (pos != mapDeltas.end()) {
375 const CAmount &delta = pos->second;
376 if (delta) {
377 mapTx.modify(newit, update_fee_delta(delta));
381 // Update cachedInnerUsage to include contained transaction's usage.
382 // (When we update the entry for in-mempool parents, memory usage will be
383 // further updated.)
384 cachedInnerUsage += entry.DynamicMemoryUsage();
386 const CTransaction& tx = newit->GetTx();
387 std::set<uint256> setParentTransactions;
388 for (unsigned int i = 0; i < tx.vin.size(); i++) {
389 mapNextTx.insert(std::make_pair(&tx.vin[i].prevout, &tx));
390 setParentTransactions.insert(tx.vin[i].prevout.hash);
392 // Don't bother worrying about child transactions of this one.
393 // Normal case of a new transaction arriving is that there can't be any
394 // children, because such children would be orphans.
395 // An exception to that is if a transaction enters that used to be in a block.
396 // In that case, our disconnect block logic will call UpdateTransactionsFromBlock
397 // to clean up the mess we're leaving here.
399 // Update ancestors with information about this tx
400 for (const uint256 &phash : setParentTransactions) {
401 txiter pit = mapTx.find(phash);
402 if (pit != mapTx.end()) {
403 UpdateParent(newit, pit, true);
406 UpdateAncestorsOf(true, newit, setAncestors);
407 UpdateEntryForAncestors(newit, setAncestors);
409 nTransactionsUpdated++;
410 totalTxSize += entry.GetTxSize();
411 if (minerPolicyEstimator) {minerPolicyEstimator->processTransaction(entry, validFeeEstimate);}
413 vTxHashes.emplace_back(tx.GetWitnessHash(), newit);
414 newit->vTxHashesIdx = vTxHashes.size() - 1;
416 return true;
419 void CTxMemPool::removeUnchecked(txiter it, MemPoolRemovalReason reason)
421 NotifyEntryRemoved(it->GetSharedTx(), reason);
422 const uint256 hash = it->GetTx().GetHash();
423 for (const CTxIn& txin : it->GetTx().vin)
424 mapNextTx.erase(txin.prevout);
426 if (vTxHashes.size() > 1) {
427 vTxHashes[it->vTxHashesIdx] = std::move(vTxHashes.back());
428 vTxHashes[it->vTxHashesIdx].second->vTxHashesIdx = it->vTxHashesIdx;
429 vTxHashes.pop_back();
430 if (vTxHashes.size() * 2 < vTxHashes.capacity())
431 vTxHashes.shrink_to_fit();
432 } else
433 vTxHashes.clear();
435 totalTxSize -= it->GetTxSize();
436 cachedInnerUsage -= it->DynamicMemoryUsage();
437 cachedInnerUsage -= memusage::DynamicUsage(mapLinks[it].parents) + memusage::DynamicUsage(mapLinks[it].children);
438 mapLinks.erase(it);
439 mapTx.erase(it);
440 nTransactionsUpdated++;
441 if (minerPolicyEstimator) {minerPolicyEstimator->removeTx(hash, false);}
444 // Calculates descendants of entry that are not already in setDescendants, and adds to
445 // setDescendants. Assumes entryit is already a tx in the mempool and setMemPoolChildren
446 // is correct for tx and all descendants.
447 // Also assumes that if an entry is in setDescendants already, then all
448 // in-mempool descendants of it are already in setDescendants as well, so that we
449 // can save time by not iterating over those entries.
450 void CTxMemPool::CalculateDescendants(txiter entryit, setEntries &setDescendants)
452 setEntries stage;
453 if (setDescendants.count(entryit) == 0) {
454 stage.insert(entryit);
456 // Traverse down the children of entry, only adding children that are not
457 // accounted for in setDescendants already (because those children have either
458 // already been walked, or will be walked in this iteration).
459 while (!stage.empty()) {
460 txiter it = *stage.begin();
461 setDescendants.insert(it);
462 stage.erase(it);
464 const setEntries &setChildren = GetMemPoolChildren(it);
465 for (const txiter &childiter : setChildren) {
466 if (!setDescendants.count(childiter)) {
467 stage.insert(childiter);
473 void CTxMemPool::removeRecursive(const CTransaction &origTx, MemPoolRemovalReason reason)
475 // Remove transaction from memory pool
477 LOCK(cs);
478 setEntries txToRemove;
479 txiter origit = mapTx.find(origTx.GetHash());
480 if (origit != mapTx.end()) {
481 txToRemove.insert(origit);
482 } else {
483 // When recursively removing but origTx isn't in the mempool
484 // be sure to remove any children that are in the pool. This can
485 // happen during chain re-orgs if origTx isn't re-accepted into
486 // the mempool for any reason.
487 for (unsigned int i = 0; i < origTx.vout.size(); i++) {
488 auto it = mapNextTx.find(COutPoint(origTx.GetHash(), i));
489 if (it == mapNextTx.end())
490 continue;
491 txiter nextit = mapTx.find(it->second->GetHash());
492 assert(nextit != mapTx.end());
493 txToRemove.insert(nextit);
496 setEntries setAllRemoves;
497 for (txiter it : txToRemove) {
498 CalculateDescendants(it, setAllRemoves);
501 RemoveStaged(setAllRemoves, false, reason);
505 void CTxMemPool::removeForReorg(const CCoinsViewCache *pcoins, unsigned int nMemPoolHeight, int flags)
507 // Remove transactions spending a coinbase which are now immature and no-longer-final transactions
508 LOCK(cs);
509 setEntries txToRemove;
510 for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
511 const CTransaction& tx = it->GetTx();
512 LockPoints lp = it->GetLockPoints();
513 bool validLP = TestLockPointValidity(&lp);
514 if (!CheckFinalTx(tx, flags) || !CheckSequenceLocks(tx, flags, &lp, validLP)) {
515 // Note if CheckSequenceLocks fails the LockPoints may still be invalid
516 // So it's critical that we remove the tx and not depend on the LockPoints.
517 txToRemove.insert(it);
518 } else if (it->GetSpendsCoinbase()) {
519 for (const CTxIn& txin : tx.vin) {
520 indexed_transaction_set::const_iterator it2 = mapTx.find(txin.prevout.hash);
521 if (it2 != mapTx.end())
522 continue;
523 const Coin &coin = pcoins->AccessCoin(txin.prevout);
524 if (nCheckFrequency != 0) assert(!coin.IsSpent());
525 if (coin.IsSpent() || (coin.IsCoinBase() && ((signed long)nMemPoolHeight) - coin.nHeight < COINBASE_MATURITY)) {
526 txToRemove.insert(it);
527 break;
531 if (!validLP) {
532 mapTx.modify(it, update_lock_points(lp));
535 setEntries setAllRemoves;
536 for (txiter it : txToRemove) {
537 CalculateDescendants(it, setAllRemoves);
539 RemoveStaged(setAllRemoves, false, MemPoolRemovalReason::REORG);
542 void CTxMemPool::removeConflicts(const CTransaction &tx)
544 // Remove transactions which depend on inputs of tx, recursively
545 LOCK(cs);
546 for (const CTxIn &txin : tx.vin) {
547 auto it = mapNextTx.find(txin.prevout);
548 if (it != mapNextTx.end()) {
549 const CTransaction &txConflict = *it->second;
550 if (txConflict != tx)
552 ClearPrioritisation(txConflict.GetHash());
553 removeRecursive(txConflict, MemPoolRemovalReason::CONFLICT);
560 * Called when a block is connected. Removes from mempool and updates the miner fee estimator.
562 void CTxMemPool::removeForBlock(const std::vector<CTransactionRef>& vtx, unsigned int nBlockHeight)
564 LOCK(cs);
565 std::vector<const CTxMemPoolEntry*> entries;
566 for (const auto& tx : vtx)
568 uint256 hash = tx->GetHash();
570 indexed_transaction_set::iterator i = mapTx.find(hash);
571 if (i != mapTx.end())
572 entries.push_back(&*i);
574 // Before the txs in the new block have been removed from the mempool, update policy estimates
575 if (minerPolicyEstimator) {minerPolicyEstimator->processBlock(nBlockHeight, entries);}
576 for (const auto& tx : vtx)
578 txiter it = mapTx.find(tx->GetHash());
579 if (it != mapTx.end()) {
580 setEntries stage;
581 stage.insert(it);
582 RemoveStaged(stage, true, MemPoolRemovalReason::BLOCK);
584 removeConflicts(*tx);
585 ClearPrioritisation(tx->GetHash());
587 lastRollingFeeUpdate = GetTime();
588 blockSinceLastRollingFeeBump = true;
591 void CTxMemPool::_clear()
593 mapLinks.clear();
594 mapTx.clear();
595 mapNextTx.clear();
596 totalTxSize = 0;
597 cachedInnerUsage = 0;
598 lastRollingFeeUpdate = GetTime();
599 blockSinceLastRollingFeeBump = false;
600 rollingMinimumFeeRate = 0;
601 ++nTransactionsUpdated;
604 void CTxMemPool::clear()
606 LOCK(cs);
607 _clear();
610 static void CheckInputsAndUpdateCoins(const CTransaction& tx, CCoinsViewCache& mempoolDuplicate, const int64_t spendheight)
612 CValidationState state;
613 CAmount txfee = 0;
614 bool fCheckResult = tx.IsCoinBase() || Consensus::CheckTxInputs(tx, state, mempoolDuplicate, spendheight, txfee);
615 assert(fCheckResult);
616 UpdateCoins(tx, mempoolDuplicate, 1000000);
619 void CTxMemPool::check(const CCoinsViewCache *pcoins) const
621 if (nCheckFrequency == 0)
622 return;
624 if (GetRand(std::numeric_limits<uint32_t>::max()) >= nCheckFrequency)
625 return;
627 LogPrint(BCLog::MEMPOOL, "Checking mempool with %u transactions and %u inputs\n", (unsigned int)mapTx.size(), (unsigned int)mapNextTx.size());
629 uint64_t checkTotal = 0;
630 uint64_t innerUsage = 0;
632 CCoinsViewCache mempoolDuplicate(const_cast<CCoinsViewCache*>(pcoins));
633 const int64_t spendheight = GetSpendHeight(mempoolDuplicate);
635 LOCK(cs);
636 std::list<const CTxMemPoolEntry*> waitingOnDependants;
637 for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
638 unsigned int i = 0;
639 checkTotal += it->GetTxSize();
640 innerUsage += it->DynamicMemoryUsage();
641 const CTransaction& tx = it->GetTx();
642 txlinksMap::const_iterator linksiter = mapLinks.find(it);
643 assert(linksiter != mapLinks.end());
644 const TxLinks &links = linksiter->second;
645 innerUsage += memusage::DynamicUsage(links.parents) + memusage::DynamicUsage(links.children);
646 bool fDependsWait = false;
647 setEntries setParentCheck;
648 int64_t parentSizes = 0;
649 int64_t parentSigOpCost = 0;
650 for (const CTxIn &txin : tx.vin) {
651 // Check that every mempool transaction's inputs refer to available coins, or other mempool tx's.
652 indexed_transaction_set::const_iterator it2 = mapTx.find(txin.prevout.hash);
653 if (it2 != mapTx.end()) {
654 const CTransaction& tx2 = it2->GetTx();
655 assert(tx2.vout.size() > txin.prevout.n && !tx2.vout[txin.prevout.n].IsNull());
656 fDependsWait = true;
657 if (setParentCheck.insert(it2).second) {
658 parentSizes += it2->GetTxSize();
659 parentSigOpCost += it2->GetSigOpCost();
661 } else {
662 assert(pcoins->HaveCoin(txin.prevout));
664 // Check whether its inputs are marked in mapNextTx.
665 auto it3 = mapNextTx.find(txin.prevout);
666 assert(it3 != mapNextTx.end());
667 assert(it3->first == &txin.prevout);
668 assert(it3->second == &tx);
669 i++;
671 assert(setParentCheck == GetMemPoolParents(it));
672 // Verify ancestor state is correct.
673 setEntries setAncestors;
674 uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();
675 std::string dummy;
676 CalculateMemPoolAncestors(*it, setAncestors, nNoLimit, nNoLimit, nNoLimit, nNoLimit, dummy);
677 uint64_t nCountCheck = setAncestors.size() + 1;
678 uint64_t nSizeCheck = it->GetTxSize();
679 CAmount nFeesCheck = it->GetModifiedFee();
680 int64_t nSigOpCheck = it->GetSigOpCost();
682 for (txiter ancestorIt : setAncestors) {
683 nSizeCheck += ancestorIt->GetTxSize();
684 nFeesCheck += ancestorIt->GetModifiedFee();
685 nSigOpCheck += ancestorIt->GetSigOpCost();
688 assert(it->GetCountWithAncestors() == nCountCheck);
689 assert(it->GetSizeWithAncestors() == nSizeCheck);
690 assert(it->GetSigOpCostWithAncestors() == nSigOpCheck);
691 assert(it->GetModFeesWithAncestors() == nFeesCheck);
693 // Check children against mapNextTx
694 CTxMemPool::setEntries setChildrenCheck;
695 auto iter = mapNextTx.lower_bound(COutPoint(it->GetTx().GetHash(), 0));
696 int64_t childSizes = 0;
697 for (; iter != mapNextTx.end() && iter->first->hash == it->GetTx().GetHash(); ++iter) {
698 txiter childit = mapTx.find(iter->second->GetHash());
699 assert(childit != mapTx.end()); // mapNextTx points to in-mempool transactions
700 if (setChildrenCheck.insert(childit).second) {
701 childSizes += childit->GetTxSize();
704 assert(setChildrenCheck == GetMemPoolChildren(it));
705 // Also check to make sure size is greater than sum with immediate children.
706 // just a sanity check, not definitive that this calc is correct...
707 assert(it->GetSizeWithDescendants() >= childSizes + it->GetTxSize());
709 if (fDependsWait)
710 waitingOnDependants.push_back(&(*it));
711 else {
712 CheckInputsAndUpdateCoins(tx, mempoolDuplicate, spendheight);
715 unsigned int stepsSinceLastRemove = 0;
716 while (!waitingOnDependants.empty()) {
717 const CTxMemPoolEntry* entry = waitingOnDependants.front();
718 waitingOnDependants.pop_front();
719 CValidationState state;
720 if (!mempoolDuplicate.HaveInputs(entry->GetTx())) {
721 waitingOnDependants.push_back(entry);
722 stepsSinceLastRemove++;
723 assert(stepsSinceLastRemove < waitingOnDependants.size());
724 } else {
725 CheckInputsAndUpdateCoins(entry->GetTx(), mempoolDuplicate, spendheight);
726 stepsSinceLastRemove = 0;
729 for (auto it = mapNextTx.cbegin(); it != mapNextTx.cend(); it++) {
730 uint256 hash = it->second->GetHash();
731 indexed_transaction_set::const_iterator it2 = mapTx.find(hash);
732 const CTransaction& tx = it2->GetTx();
733 assert(it2 != mapTx.end());
734 assert(&tx == it->second);
737 assert(totalTxSize == checkTotal);
738 assert(innerUsage == cachedInnerUsage);
741 bool CTxMemPool::CompareDepthAndScore(const uint256& hasha, const uint256& hashb)
743 LOCK(cs);
744 indexed_transaction_set::const_iterator i = mapTx.find(hasha);
745 if (i == mapTx.end()) return false;
746 indexed_transaction_set::const_iterator j = mapTx.find(hashb);
747 if (j == mapTx.end()) return true;
748 uint64_t counta = i->GetCountWithAncestors();
749 uint64_t countb = j->GetCountWithAncestors();
750 if (counta == countb) {
751 return CompareTxMemPoolEntryByScore()(*i, *j);
753 return counta < countb;
756 namespace {
757 class DepthAndScoreComparator
759 public:
760 bool operator()(const CTxMemPool::indexed_transaction_set::const_iterator& a, const CTxMemPool::indexed_transaction_set::const_iterator& b)
762 uint64_t counta = a->GetCountWithAncestors();
763 uint64_t countb = b->GetCountWithAncestors();
764 if (counta == countb) {
765 return CompareTxMemPoolEntryByScore()(*a, *b);
767 return counta < countb;
770 } // namespace
772 std::vector<CTxMemPool::indexed_transaction_set::const_iterator> CTxMemPool::GetSortedDepthAndScore() const
774 std::vector<indexed_transaction_set::const_iterator> iters;
775 AssertLockHeld(cs);
777 iters.reserve(mapTx.size());
779 for (indexed_transaction_set::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi) {
780 iters.push_back(mi);
782 std::sort(iters.begin(), iters.end(), DepthAndScoreComparator());
783 return iters;
786 void CTxMemPool::queryHashes(std::vector<uint256>& vtxid)
788 LOCK(cs);
789 auto iters = GetSortedDepthAndScore();
791 vtxid.clear();
792 vtxid.reserve(mapTx.size());
794 for (auto it : iters) {
795 vtxid.push_back(it->GetTx().GetHash());
799 static TxMempoolInfo GetInfo(CTxMemPool::indexed_transaction_set::const_iterator it) {
800 return TxMempoolInfo{it->GetSharedTx(), it->GetTime(), CFeeRate(it->GetFee(), it->GetTxSize()), it->GetModifiedFee() - it->GetFee()};
803 std::vector<TxMempoolInfo> CTxMemPool::infoAll() const
805 LOCK(cs);
806 auto iters = GetSortedDepthAndScore();
808 std::vector<TxMempoolInfo> ret;
809 ret.reserve(mapTx.size());
810 for (auto it : iters) {
811 ret.push_back(GetInfo(it));
814 return ret;
817 CTransactionRef CTxMemPool::get(const uint256& hash) const
819 LOCK(cs);
820 indexed_transaction_set::const_iterator i = mapTx.find(hash);
821 if (i == mapTx.end())
822 return nullptr;
823 return i->GetSharedTx();
826 TxMempoolInfo CTxMemPool::info(const uint256& hash) const
828 LOCK(cs);
829 indexed_transaction_set::const_iterator i = mapTx.find(hash);
830 if (i == mapTx.end())
831 return TxMempoolInfo();
832 return GetInfo(i);
835 void CTxMemPool::PrioritiseTransaction(const uint256& hash, const CAmount& nFeeDelta)
838 LOCK(cs);
839 CAmount &delta = mapDeltas[hash];
840 delta += nFeeDelta;
841 txiter it = mapTx.find(hash);
842 if (it != mapTx.end()) {
843 mapTx.modify(it, update_fee_delta(delta));
844 // Now update all ancestors' modified fees with descendants
845 setEntries setAncestors;
846 uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();
847 std::string dummy;
848 CalculateMemPoolAncestors(*it, setAncestors, nNoLimit, nNoLimit, nNoLimit, nNoLimit, dummy, false);
849 for (txiter ancestorIt : setAncestors) {
850 mapTx.modify(ancestorIt, update_descendant_state(0, nFeeDelta, 0));
852 // Now update all descendants' modified fees with ancestors
853 setEntries setDescendants;
854 CalculateDescendants(it, setDescendants);
855 setDescendants.erase(it);
856 for (txiter descendantIt : setDescendants) {
857 mapTx.modify(descendantIt, update_ancestor_state(0, nFeeDelta, 0, 0));
859 ++nTransactionsUpdated;
862 LogPrintf("PrioritiseTransaction: %s feerate += %s\n", hash.ToString(), FormatMoney(nFeeDelta));
865 void CTxMemPool::ApplyDelta(const uint256 hash, CAmount &nFeeDelta) const
867 LOCK(cs);
868 std::map<uint256, CAmount>::const_iterator pos = mapDeltas.find(hash);
869 if (pos == mapDeltas.end())
870 return;
871 const CAmount &delta = pos->second;
872 nFeeDelta += delta;
875 void CTxMemPool::ClearPrioritisation(const uint256 hash)
877 LOCK(cs);
878 mapDeltas.erase(hash);
881 bool CTxMemPool::HasNoInputsOf(const CTransaction &tx) const
883 for (unsigned int i = 0; i < tx.vin.size(); i++)
884 if (exists(tx.vin[i].prevout.hash))
885 return false;
886 return true;
889 CCoinsViewMemPool::CCoinsViewMemPool(CCoinsView* baseIn, const CTxMemPool& mempoolIn) : CCoinsViewBacked(baseIn), mempool(mempoolIn) { }
891 bool CCoinsViewMemPool::GetCoin(const COutPoint &outpoint, Coin &coin) const {
892 // If an entry in the mempool exists, always return that one, as it's guaranteed to never
893 // conflict with the underlying cache, and it cannot have pruned entries (as it contains full)
894 // transactions. First checking the underlying cache risks returning a pruned entry instead.
895 CTransactionRef ptx = mempool.get(outpoint.hash);
896 if (ptx) {
897 if (outpoint.n < ptx->vout.size()) {
898 coin = Coin(ptx->vout[outpoint.n], MEMPOOL_HEIGHT, false);
899 return true;
900 } else {
901 return false;
904 return base->GetCoin(outpoint, coin);
907 size_t CTxMemPool::DynamicMemoryUsage() const {
908 LOCK(cs);
909 // Estimate the overhead of mapTx to be 15 pointers + an allocation, as no exact formula for boost::multi_index_contained is implemented.
910 return memusage::MallocUsage(sizeof(CTxMemPoolEntry) + 15 * sizeof(void*)) * mapTx.size() + memusage::DynamicUsage(mapNextTx) + memusage::DynamicUsage(mapDeltas) + memusage::DynamicUsage(mapLinks) + memusage::DynamicUsage(vTxHashes) + cachedInnerUsage;
913 void CTxMemPool::RemoveStaged(setEntries &stage, bool updateDescendants, MemPoolRemovalReason reason) {
914 AssertLockHeld(cs);
915 UpdateForRemoveFromMempool(stage, updateDescendants);
916 for (const txiter& it : stage) {
917 removeUnchecked(it, reason);
921 int CTxMemPool::Expire(int64_t time) {
922 LOCK(cs);
923 indexed_transaction_set::index<entry_time>::type::iterator it = mapTx.get<entry_time>().begin();
924 setEntries toremove;
925 while (it != mapTx.get<entry_time>().end() && it->GetTime() < time) {
926 toremove.insert(mapTx.project<0>(it));
927 it++;
929 setEntries stage;
930 for (txiter removeit : toremove) {
931 CalculateDescendants(removeit, stage);
933 RemoveStaged(stage, false, MemPoolRemovalReason::EXPIRY);
934 return stage.size();
937 bool CTxMemPool::addUnchecked(const uint256&hash, const CTxMemPoolEntry &entry, bool validFeeEstimate)
939 LOCK(cs);
940 setEntries setAncestors;
941 uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();
942 std::string dummy;
943 CalculateMemPoolAncestors(entry, setAncestors, nNoLimit, nNoLimit, nNoLimit, nNoLimit, dummy);
944 return addUnchecked(hash, entry, setAncestors, validFeeEstimate);
947 void CTxMemPool::UpdateChild(txiter entry, txiter child, bool add)
949 setEntries s;
950 if (add && mapLinks[entry].children.insert(child).second) {
951 cachedInnerUsage += memusage::IncrementalDynamicUsage(s);
952 } else if (!add && mapLinks[entry].children.erase(child)) {
953 cachedInnerUsage -= memusage::IncrementalDynamicUsage(s);
957 void CTxMemPool::UpdateParent(txiter entry, txiter parent, bool add)
959 setEntries s;
960 if (add && mapLinks[entry].parents.insert(parent).second) {
961 cachedInnerUsage += memusage::IncrementalDynamicUsage(s);
962 } else if (!add && mapLinks[entry].parents.erase(parent)) {
963 cachedInnerUsage -= memusage::IncrementalDynamicUsage(s);
967 const CTxMemPool::setEntries & CTxMemPool::GetMemPoolParents(txiter entry) const
969 assert (entry != mapTx.end());
970 txlinksMap::const_iterator it = mapLinks.find(entry);
971 assert(it != mapLinks.end());
972 return it->second.parents;
975 const CTxMemPool::setEntries & CTxMemPool::GetMemPoolChildren(txiter entry) const
977 assert (entry != mapTx.end());
978 txlinksMap::const_iterator it = mapLinks.find(entry);
979 assert(it != mapLinks.end());
980 return it->second.children;
983 CFeeRate CTxMemPool::GetMinFee(size_t sizelimit) const {
984 LOCK(cs);
985 if (!blockSinceLastRollingFeeBump || rollingMinimumFeeRate == 0)
986 return CFeeRate(llround(rollingMinimumFeeRate));
988 int64_t time = GetTime();
989 if (time > lastRollingFeeUpdate + 10) {
990 double halflife = ROLLING_FEE_HALFLIFE;
991 if (DynamicMemoryUsage() < sizelimit / 4)
992 halflife /= 4;
993 else if (DynamicMemoryUsage() < sizelimit / 2)
994 halflife /= 2;
996 rollingMinimumFeeRate = rollingMinimumFeeRate / pow(2.0, (time - lastRollingFeeUpdate) / halflife);
997 lastRollingFeeUpdate = time;
999 if (rollingMinimumFeeRate < (double)incrementalRelayFee.GetFeePerK() / 2) {
1000 rollingMinimumFeeRate = 0;
1001 return CFeeRate(0);
1004 return std::max(CFeeRate(llround(rollingMinimumFeeRate)), incrementalRelayFee);
1007 void CTxMemPool::trackPackageRemoved(const CFeeRate& rate) {
1008 AssertLockHeld(cs);
1009 if (rate.GetFeePerK() > rollingMinimumFeeRate) {
1010 rollingMinimumFeeRate = rate.GetFeePerK();
1011 blockSinceLastRollingFeeBump = false;
1015 void CTxMemPool::TrimToSize(size_t sizelimit, std::vector<COutPoint>* pvNoSpendsRemaining) {
1016 LOCK(cs);
1018 unsigned nTxnRemoved = 0;
1019 CFeeRate maxFeeRateRemoved(0);
1020 while (!mapTx.empty() && DynamicMemoryUsage() > sizelimit) {
1021 indexed_transaction_set::index<descendant_score>::type::iterator it = mapTx.get<descendant_score>().begin();
1023 // We set the new mempool min fee to the feerate of the removed set, plus the
1024 // "minimum reasonable fee rate" (ie some value under which we consider txn
1025 // to have 0 fee). This way, we don't allow txn to enter mempool with feerate
1026 // equal to txn which were removed with no block in between.
1027 CFeeRate removed(it->GetModFeesWithDescendants(), it->GetSizeWithDescendants());
1028 removed += incrementalRelayFee;
1029 trackPackageRemoved(removed);
1030 maxFeeRateRemoved = std::max(maxFeeRateRemoved, removed);
1032 setEntries stage;
1033 CalculateDescendants(mapTx.project<0>(it), stage);
1034 nTxnRemoved += stage.size();
1036 std::vector<CTransaction> txn;
1037 if (pvNoSpendsRemaining) {
1038 txn.reserve(stage.size());
1039 for (txiter iter : stage)
1040 txn.push_back(iter->GetTx());
1042 RemoveStaged(stage, false, MemPoolRemovalReason::SIZELIMIT);
1043 if (pvNoSpendsRemaining) {
1044 for (const CTransaction& tx : txn) {
1045 for (const CTxIn& txin : tx.vin) {
1046 if (exists(txin.prevout.hash)) continue;
1047 pvNoSpendsRemaining->push_back(txin.prevout);
1053 if (maxFeeRateRemoved > CFeeRate(0)) {
1054 LogPrint(BCLog::MEMPOOL, "Removed %u txn, rolling minimum fee bumped to %s\n", nTxnRemoved, maxFeeRateRemoved.ToString());
1058 bool CTxMemPool::TransactionWithinChainLimit(const uint256& txid, size_t chainLimit) const {
1059 LOCK(cs);
1060 auto it = mapTx.find(txid);
1061 return it == mapTx.end() || (it->GetCountWithAncestors() < chainLimit &&
1062 it->GetCountWithDescendants() < chainLimit);
1065 SaltedTxidHasher::SaltedTxidHasher() : k0(GetRand(std::numeric_limits<uint64_t>::max())), k1(GetRand(std::numeric_limits<uint64_t>::max())) {}