PIVX Core  5.6.99
P2P Digital Currency
txmempool.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2014 The Bitcoin developers
3 // Copyright (c) 2016-2021 The PIVX Core developers
4 // Distributed under the MIT software license, see the accompanying
5 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 
7 #include "txmempool.h"
8 
9 #include "clientversion.h"
10 #include "bls/bls_wrapper.h"
11 #include "evo/deterministicmns.h"
13 #include "evo/providertx.h"
14 #include "policy/fees.h"
15 #include "reverse_iterate.h"
16 #include "streams.h"
17 #include "timedata.h"
18 #include "util/system.h"
19 #include "utilmoneystr.h"
20 #include "utiltime.h"
21 #include "version.h"
22 #include "validation.h"
23 #include "validationinterface.h"
24 
25 
27  int64_t _nTime, unsigned int _entryHeight,
28  bool _spendsCoinbaseOrCoinstake, unsigned int _sigOps) :
29  tx(MakeTransactionRef(_tx)), nFee(_nFee), nTime(_nTime), entryHeight(_entryHeight),
30  spendsCoinbaseOrCoinstake(_spendsCoinbaseOrCoinstake), sigOpCount(_sigOps)
31 {
32  nTxSize = ::GetSerializeSize(*_tx, PROTOCOL_VERSION);
33  nUsageSize = _tx->DynamicMemoryUsage();
34  hasZerocoins = _tx->ContainsZerocoins();
35  m_isShielded = _tx->IsShieldedTx();
36 
40 
41  feeDelta = 0;
42 
47 }
48 
49 void CTxMemPoolEntry::UpdateFeeDelta(int64_t newFeeDelta)
50 {
51  nModFeesWithDescendants += newFeeDelta - feeDelta;
52  nModFeesWithAncestors += newFeeDelta - feeDelta;
53  feeDelta = newFeeDelta;
54 }
55 
56 // Update the given tx for any in-mempool descendants.
57 // Assumes that setMemPoolChildren is correct for the given tx and all
58 // descendants.
59 void CTxMemPool::UpdateForDescendants(txiter updateIt, cacheMap &cachedDescendants, const std::set<uint256> &setExclude)
60 {
61  setEntries stageEntries, setAllDescendants;
62  stageEntries = GetMemPoolChildren(updateIt);
63 
64  while (!stageEntries.empty()) {
65  const txiter cit = *stageEntries.begin();
66  setAllDescendants.insert(cit);
67  stageEntries.erase(cit);
68  const setEntries &setChildren = GetMemPoolChildren(cit);
69  for (const txiter& childEntry : setChildren) {
70  cacheMap::iterator cacheIt = cachedDescendants.find(childEntry);
71  if (cacheIt != cachedDescendants.end()) {
72  // We've already calculated this one, just add the entries for this set
73  // but don't traverse again.
74  for (const txiter& cacheEntry : cacheIt->second) {
75  setAllDescendants.insert(cacheEntry);
76  }
77  } else if (!setAllDescendants.count(childEntry)) {
78  // Schedule for later processing
79  stageEntries.insert(childEntry);
80  }
81  }
82  }
83  // setAllDescendants now contains all in-mempool descendants of updateIt.
84  // Update and add to cached descendant map
85  int64_t modifySize = 0;
86  CAmount modifyFee = 0;
87  int64_t modifyCount = 0;
88  for (const txiter& cit : setAllDescendants) {
89  if (!setExclude.count(cit->GetTx().GetHash())) {
90  modifySize += cit->GetTxSize();
91  modifyFee += cit->GetModifiedFee();
92  modifyCount++;
93  cachedDescendants[updateIt].insert(cit);
94  // Update ancestor state for each descendant
95  mapTx.modify(cit, update_ancestor_state(updateIt->GetTxSize(), updateIt->GetModifiedFee(), 1, updateIt->GetSigOpCount()));
96  }
97  }
98  mapTx.modify(updateIt, update_descendant_state(modifySize, modifyFee, modifyCount));
99 }
100 
101 // vHashesToUpdate is the set of transaction hashes from a disconnected block
102 // which has been re-added to the mempool.
103 // for each entry, look for descendants that are outside hashesToUpdate, and
104 // add fee/size information for such descendants to the parent.
105 // for each such descendant, also update the ancestor state to include the parent.
106 void CTxMemPool::UpdateTransactionsFromBlock(const std::vector<uint256> &vHashesToUpdate)
107 {
108  LOCK(cs);
109  // For each entry in vHashesToUpdate, store the set of in-mempool, but not
110  // in-vHashesToUpdate transactions, so that we don't have to recalculate
111  // descendants when we come across a previously seen entry.
112  cacheMap mapMemPoolDescendantsToUpdate;
113 
114  // Use a set for lookups into vHashesToUpdate (these entries are already
115  // accounted for in the state of their ancestors)
116  std::set<uint256> setAlreadyIncluded(vHashesToUpdate.begin(), vHashesToUpdate.end());
117 
118  // Iterate in reverse, so that whenever we are looking at at a transaction
119  // we are sure that all in-mempool descendants have already been processed.
120  // This maximizes the benefit of the descendant cache and guarantees that
121  // setMemPoolChildren will be updated, an assumption made in
122  // UpdateForDescendants.
123  for (const uint256 &hash : reverse_iterate(vHashesToUpdate)) {
124  // we cache the in-mempool children to avoid duplicate updates
125  setEntries setChildren;
126  // calculate children from mapNextTx
127  txiter it = mapTx.find(hash);
128  if (it == mapTx.end()) {
129  continue;
130  }
131  auto iter = mapNextTx.lower_bound(COutPoint(hash, 0));
132  // First calculate the children, and update setMemPoolChildren to
133  // include them, and update their setMemPoolParents to include this tx.
134  for (; iter != mapNextTx.end() && iter->first->hash == hash; ++iter) {
135  const uint256 &childHash = iter->second->GetHash();
136  txiter childIter = mapTx.find(childHash);
137  assert(childIter != mapTx.end());
138  // We can skip updating entries we've encountered before or that
139  // are in the block (which are already accounted for).
140  if (setChildren.insert(childIter).second && !setAlreadyIncluded.count(childHash)) {
141  UpdateChild(it, childIter, true);
142  UpdateParent(childIter, it, true);
143  }
144  }
145  UpdateForDescendants(it, mapMemPoolDescendantsToUpdate, setAlreadyIncluded);
146  }
147 }
148 
149 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
150 {
151  setEntries parentHashes;
152  const auto &tx = entry.GetSharedTx();
153 
154  if (fSearchForParents) {
155  // Get parents of this transaction that are in the mempool
156  // GetMemPoolParents() is only valid for entries in the mempool, so we
157  // iterate mapTx to find parents.
158  for (unsigned int i = 0; i < tx->vin.size(); i++) {
159  txiter piter = mapTx.find(tx->vin[i].prevout.hash);
160  if (piter != mapTx.end()) {
161  parentHashes.insert(piter);
162  if (parentHashes.size() + 1 > limitAncestorCount) {
163  errString = strprintf("too many unconfirmed parents [limit: %u]", limitAncestorCount);
164  return false;
165  }
166  }
167  }
168  } else {
169  // If we're not searching for parents, we require this to be an
170  // entry in the mempool already.
171  txiter it = mapTx.iterator_to(entry);
172  parentHashes = GetMemPoolParents(it);
173  }
174 
175  size_t totalSizeWithAncestors = entry.GetTxSize();
176 
177  while (!parentHashes.empty()) {
178  txiter stageit = *parentHashes.begin();
179 
180  setAncestors.insert(stageit);
181  parentHashes.erase(stageit);
182  totalSizeWithAncestors += stageit->GetTxSize();
183 
184  if (stageit->GetSizeWithDescendants() + entry.GetTxSize() > limitDescendantSize) {
185  errString = strprintf("exceeds descendant size limit for tx %s [limit: %u]", stageit->GetTx().GetHash().ToString(), limitDescendantSize);
186  return false;
187  } else if (stageit->GetCountWithDescendants() + 1 > limitDescendantCount) {
188  errString = strprintf("too many descendants for tx %s [limit: %u]", stageit->GetTx().GetHash().ToString(), limitDescendantCount);
189  return false;
190  } else if (totalSizeWithAncestors > limitAncestorSize) {
191  errString = strprintf("exceeds ancestor size limit [limit: %u]", limitAncestorSize);
192  return false;
193  }
194 
195  const setEntries & setMemPoolParents = GetMemPoolParents(stageit);
196  for (const txiter& phash : setMemPoolParents) {
197  // If this is a new ancestor, add it.
198  if (setAncestors.count(phash) == 0) {
199  parentHashes.insert(phash);
200  }
201  if (parentHashes.size() + setAncestors.size() + 1 > limitAncestorCount) {
202  errString = strprintf("too many unconfirmed ancestors [limit: %u]", limitAncestorCount);
203  return false;
204  }
205  }
206  }
207 
208  return true;
209 }
210 
211 void CTxMemPool::UpdateAncestorsOf(bool add, txiter it, setEntries &setAncestors)
212 {
213  setEntries parentIters = GetMemPoolParents(it);
214  // add or remove this tx as a child of each parent
215  for (const txiter& piter : parentIters) {
216  UpdateChild(piter, it, add);
217  }
218  const int64_t updateCount = (add ? 1 : -1);
219  const int64_t updateSize = updateCount * it->GetTxSize();
220  const CAmount updateFee = updateCount * it->GetModifiedFee();
221  for (const txiter& ancestorIt : setAncestors) {
222  mapTx.modify(ancestorIt, update_descendant_state(updateSize, updateFee, updateCount));
223  }
224 }
225 
227 {
228  int64_t updateCount = setAncestors.size();
229  int64_t updateSize = 0;
230  CAmount updateFee = 0;
231  int updateSigOps = 0;
232  for (const txiter& ancestorIt : setAncestors) {
233  updateSize += ancestorIt->GetTxSize();
234  updateFee += ancestorIt->GetModifiedFee();
235  updateSigOps += ancestorIt->GetSigOpCount();
236  }
237  mapTx.modify(it, update_ancestor_state(updateSize, updateFee, updateCount, updateSigOps));
238 }
239 
241 {
242  const setEntries &setMemPoolChildren = GetMemPoolChildren(it);
243  for (const txiter& updateIt : setMemPoolChildren) {
244  UpdateParent(updateIt, it, false);
245  }
246 }
247 
248 void CTxMemPool::UpdateForRemoveFromMempool(const setEntries &entriesToRemove, bool updateDescendants)
249 {
250  // For each entry, walk back all ancestors and decrement size associated with this
251  // transaction
252  const uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();
253  if (updateDescendants) {
254  // updateDescendants should be true whenever we're not recursively
255  // removing a tx and all its descendants, eg when a transaction is
256  // confirmed in a block.
257  // Here we only update statistics and not data in mapLinks (which
258  // we need to preserve until we're finished with all operations that
259  // need to traverse the mempool).
260  for (const txiter& removeIt : entriesToRemove) {
261  setEntries setDescendants;
262  CalculateDescendants(removeIt, setDescendants);
263  setDescendants.erase(removeIt); // don't update state for self
264  int64_t modifySize = -((int64_t)removeIt->GetTxSize());
265  CAmount modifyFee = -removeIt->GetModifiedFee();
266  int modifySigOps = -removeIt->GetSigOpCount();
267  for (const txiter& dit : setDescendants) {
268  mapTx.modify(dit, update_ancestor_state(modifySize, modifyFee, -1, modifySigOps));
269  }
270  }
271  }
272  for (const txiter& removeIt : entriesToRemove) {
273  setEntries setAncestors;
274  const CTxMemPoolEntry &entry = *removeIt;
275  std::string dummy;
276  // Since this is a tx that is already in the mempool, we can call CMPA
277  // with fSearchForParents = false. If the mempool is in a consistent
278  // state, then using true or false should both be correct, though false
279  // should be a bit faster.
280  // However, if we happen to be in the middle of processing a reorg, then
281  // the mempool can be in an inconsistent state. In this case, the set
282  // of ancestors reachable via mapLinks will be the same as the set of
283  // ancestors whose packages include this transaction, because when we
284  // add a new transaction to the mempool in addUnchecked(), we assume it
285  // has no children, and in the case of a reorg where that assumption is
286  // false, the in-mempool children aren't linked to the in-block tx's
287  // until UpdateTransactionsFromBlock() is called.
288  // So if we're being called during a reorg, ie before
289  // UpdateTransactionsFromBlock() has been called, then mapLinks[] will
290  // differ from the set of mempool parents we'd calculate by searching,
291  // and it's important that we use the mapLinks[] notion of ancestor
292  // transactions as the set of things to update for removal.
293  CalculateMemPoolAncestors(entry, setAncestors, nNoLimit, nNoLimit, nNoLimit, nNoLimit, dummy, false);
294  // Note that UpdateAncestorsOf severs the child links that point to
295  // removeIt in the entries for the parents of removeIt.
296  UpdateAncestorsOf(false, removeIt, setAncestors);
297  }
298  // After updating all the ancestor sizes, we can now sever the link between each
299  // transaction being removed and any mempool children (ie, update setMemPoolParents
300  // for each direct child of a transaction being removed).
301  for (const txiter& removeIt : entriesToRemove) {
302  UpdateChildrenForRemoval(removeIt);
303  }
304 }
305 
306 void CTxMemPoolEntry::UpdateDescendantState(int64_t modifySize, CAmount modifyFee, int64_t modifyCount)
307 {
308  nSizeWithDescendants += modifySize;
309  assert(int64_t(nSizeWithDescendants) > 0);
310  nModFeesWithDescendants += modifyFee;
311  nCountWithDescendants += modifyCount;
312  assert(int64_t(nCountWithDescendants) > 0);
313 }
314 
315 void CTxMemPoolEntry::UpdateAncestorState(int64_t modifySize, CAmount modifyFee, int64_t modifyCount, int modifySigOps)
316 {
317  nSizeWithAncestors += modifySize;
318  assert(int64_t(nSizeWithAncestors) > 0);
319  nModFeesWithAncestors += modifyFee;
320  nCountWithAncestors += modifyCount;
321  assert(int64_t(nCountWithAncestors) > 0);
322  nSigOpCountWithAncestors += modifySigOps;
323  assert(int(nSigOpCountWithAncestors) >= 0);
324 }
325 
326 CTxMemPool::CTxMemPool(const CFeeRate& _minReasonableRelayFee) :
327  nTransactionsUpdated(0)
328 {
329  _clear(); // lock-free clear
330 
331  // Sanity checks off by default for performance, because otherwise
332  // accepting transactions becomes O(N^2) where N is the number
333  // of transactions in the pool
334  nCheckFrequency = 0;
335 
336  minerPolicyEstimator = new CBlockPolicyEstimator(_minReasonableRelayFee);
337  minReasonableRelayFee = _minReasonableRelayFee;
338 }
339 
341 {
342  delete minerPolicyEstimator;
343 }
344 
345 bool CTxMemPool::isSpent(const COutPoint& outpoint)
346 {
347  LOCK(cs);
348  return mapNextTx.count(outpoint);
349 }
350 
352 {
353  LOCK(cs);
354  return nTransactionsUpdated;
355 }
356 
358 {
359  LOCK(cs);
361 }
362 
364 {
365  if (!tx.IsSpecialTx()) return;
366 
367  // Invalid special txes never get this far because transactions should be
368  // fully checked by AcceptToMemoryPool() at this point, so we just assume that
369  // everything is fine here.
370  const uint256& txid = tx.GetHash();
371  switch(tx.nType) {
372  case CTransaction::TxType::PROREG: {
373  ProRegPL pl;
374  bool ok = GetTxPayload(tx, pl);
375  assert(ok);
376  if (!pl.collateralOutpoint.hash.IsNull()) {
377  mapProTxRefs.emplace(txid, pl.collateralOutpoint.hash);
378  mapProTxCollaterals.emplace(pl.collateralOutpoint, txid);
379  }
380  mapProTxAddresses.emplace(pl.addr, txid);
381  mapProTxPubKeyIDs.emplace(pl.keyIDOwner, txid);
382  mapProTxBlsPubKeyHashes.emplace(pl.pubKeyOperator.GetHash(), txid);
383  break;
384  }
385 
386  case CTransaction::TxType::PROUPSERV: {
387  ProUpServPL pl;
388  bool ok = GetTxPayload(tx, pl);
389  assert(ok);
390  mapProTxRefs.emplace(pl.proTxHash, txid);
391  mapProTxAddresses.emplace(pl.addr, txid);
392  break;
393  }
394 
395  case CTransaction::TxType::PROUPREG: {
396  ProUpRegPL pl;
397  bool ok = GetTxPayload(tx, pl);
398  assert(ok);
399  mapProTxRefs.emplace(pl.proTxHash, txid);
400  mapProTxBlsPubKeyHashes.emplace(pl.pubKeyOperator.GetHash(), txid);
401  break;
402  }
403 
404  case CTransaction::TxType::PROUPREV: {
405  ProUpRevPL pl;
406  bool ok = GetTxPayload(tx, pl);
407  assert(ok);
408  mapProTxRefs.emplace(pl.proTxHash, txid);
409  break;
410  }
411 
412  }
413 }
414 
415 bool CTxMemPool::addUnchecked(const uint256& hash, const CTxMemPoolEntry &entry, setEntries &setAncestors, bool validFeeEstimate)
416 {
417  // Add to memory pool without checking anything.
418  // Used by AcceptToMemoryPool(), which DOES do all the appropriate checks.
419  LOCK(cs);
420  indexed_transaction_set::iterator newit = mapTx.insert(entry).first;
421  mapLinks.insert(make_pair(newit, TxLinks()));
422 
423  // Update transaction for any feeDelta created by PrioritiseTransaction
424  // TODO: refactor so that the fee delta is calculated before inserting
425  // into mapTx.
426  std::map<uint256, CAmount>::const_iterator pos = mapDeltas.find(hash);
427  if (pos != mapDeltas.end()) {
428  const CAmount &delta = pos->second;
429  if (delta) {
430  mapTx.modify(newit, update_fee_delta(delta));
431  }
432  }
433 
434  // Update cachedInnerUsage to include contained transaction's usage.
435  // (When we update the entry for in-mempool parents, memory usage will be
436  // further updated.)
438 
439  const CTransaction& tx = newit->GetTx();
440  std::set<uint256> setParentTransactions;
441  if(!tx.HasZerocoinSpendInputs()) {
442  for (unsigned int i = 0; i < tx.vin.size(); i++) {
443  mapNextTx.insert(std::make_pair(&tx.vin[i].prevout, newit->GetSharedTx()));
444  setParentTransactions.insert(tx.vin[i].prevout.hash);
445  }
446  }
447  // Don't bother worrying about child transactions of this one.
448  // Normal case of a new transaction arriving is that there can't be any
449  // children, because such children would be orphans.
450  // An exception to that is if a transaction enters that used to be in a block.
451  // In that case, our disconnect block logic will call UpdateTransactionsFromBlock
452  // to clean up the mess we're leaving here.
453 
454  // Update ancestors with information about this tx
455  for (const uint256& phash : setParentTransactions) {
456  txiter pit = mapTx.find(phash);
457  if (pit != mapTx.end()) {
458  UpdateParent(newit, pit, true);
459  }
460  }
461  UpdateAncestorsOf(true, newit, setAncestors);
462  UpdateEntryForAncestors(newit, setAncestors);
463 
464  // Save spent nullifiers
465  if (tx.IsShieldedTx()) {
466  for (const SpendDescription& sd : tx.sapData->vShieldedSpend) {
467  mapSaplingNullifiers[sd.nullifier] = newit->GetSharedTx();
468  }
469  }
470 
472  totalTxSize += entry.GetTxSize();
473  minerPolicyEstimator->processTransaction(entry, validFeeEstimate);
474 
476 
477  return true;
478 }
479 
481 {
482  if (!tx.IsSpecialTx()) return;
483 
484  auto eraseProTxRef = [&](const uint256& proTxHash, const uint256& txHash) {
485  auto its = mapProTxRefs.equal_range(proTxHash);
486  for (auto it = its.first; it != its.second;) {
487  if (it->second == txHash) {
488  it = mapProTxRefs.erase(it);
489  } else {
490  ++it;
491  }
492  }
493  };
494 
495  const uint256& txid = tx.GetHash();
496  switch(tx.nType) {
497  case CTransaction::TxType::PROREG: {
498  ProRegPL pl;
499  bool ok = GetTxPayload(tx, pl);
500  assert(ok);
501  if (!pl.collateralOutpoint.IsNull()) {
502  eraseProTxRef(txid, pl.collateralOutpoint.hash);
503  }
505  mapProTxAddresses.erase(pl.addr);
506  mapProTxPubKeyIDs.erase(pl.keyIDOwner);
508  break;
509  }
510 
511  case CTransaction::TxType::PROUPSERV: {
512  ProUpServPL pl;
513  bool ok = GetTxPayload(tx, pl);
514  assert(ok);
515  eraseProTxRef(pl.proTxHash, txid);
516  mapProTxAddresses.erase(pl.addr);
517  break;
518  }
519 
520  case CTransaction::TxType::PROUPREG: {
521  ProUpRegPL pl;
522  bool ok = GetTxPayload(tx, pl);
523  assert(ok);
524  eraseProTxRef(pl.proTxHash, txid);
526  break;
527  }
528 
529  case CTransaction::TxType::PROUPREV: {
530  ProUpRevPL pl;
531  bool ok = GetTxPayload(tx, pl);
532  assert(ok);
533  eraseProTxRef(pl.proTxHash, txid);
534  break;
535  }
536 
537  }
538 }
539 
541 {
542  if (reason != MemPoolRemovalReason::BLOCK) {
543  // Notify clients that a transaction has been removed from the mempool
544  // for any reason except being included in a block. Clients interested
545  // in transactions included in blocks can subscribe to the BlockConnected
546  // notification.
547  GetMainSignals().TransactionRemovedFromMempool(it->GetSharedTx(), reason);
548  }
549 
551  const CTransaction& tx = it->GetTx();
552  for (const CTxIn& txin : tx.vin)
553  mapNextTx.erase(txin.prevout);
554  // Remove spent nullifiers
555  if (tx.IsShieldedTx()) {
556  for (const SpendDescription& sd : tx.sapData->vShieldedSpend) {
558  }
559  }
560 
562 
563  totalTxSize -= it->GetTxSize();
564  cachedInnerUsage -= it->DynamicMemoryUsage();
565  cachedInnerUsage -= memusage::DynamicUsage(mapLinks[it].parents) + memusage::DynamicUsage(mapLinks[it].children);
566  mapLinks.erase(it);
567  mapTx.erase(it);
570 }
571 
572 // Calculates descendants of entry that are not already in setDescendants, and adds to
573 // setDescendants. Assumes entryit is already a tx in the mempool and setMemPoolChildren
574 // is correct for tx and all descendants.
575 // Also assumes that if an entry is in setDescendants already, then all
576 // in-mempool descendants of it are already in setDescendants as well, so that we
577 // can save time by not iterating over those entries.
578 void CTxMemPool::CalculateDescendants(txiter entryit, setEntries &setDescendants)
579 {
580  setEntries stage;
581  if (setDescendants.count(entryit) == 0) {
582  stage.insert(entryit);
583  }
584  // Traverse down the children of entry, only adding children that are not
585  // accounted for in setDescendants already (because those children have either
586  // already been walked, or will be walked in this iteration).
587  while (!stage.empty()) {
588  txiter it = *stage.begin();
589  setDescendants.insert(it);
590  stage.erase(it);
591 
592  const setEntries &setChildren = GetMemPoolChildren(it);
593  for (const txiter& childiter : setChildren) {
594  if (!setDescendants.count(childiter)) {
595  stage.insert(childiter);
596  }
597  }
598  }
599 }
600 
602 {
603  // Remove transaction from memory pool
604  {
605  LOCK(cs);
606  setEntries txToRemove;
607  txiter origit = mapTx.find(origTx.GetHash());
608  if (origit != mapTx.end()) {
609  txToRemove.insert(origit);
610  } else {
611  // When recursively removing but origTx isn't in the mempool
612  // be sure to remove any children that are in the pool. This can
613  // happen during chain re-orgs if origTx isn't re-accepted into
614  // the mempool for any reason.
615  for (unsigned int i = 0; i < origTx.vout.size(); i++) {
616  auto it = mapNextTx.find(COutPoint(origTx.GetHash(), i));
617  if (it == mapNextTx.end())
618  continue;
619  txiter nextit = mapTx.find(it->second->GetHash());
620  assert(nextit != mapTx.end());
621  txToRemove.insert(nextit);
622  }
623  }
624  setEntries setAllRemoves;
625  for (const txiter& it : txToRemove) {
626  CalculateDescendants(it, setAllRemoves);
627  }
628 
629  RemoveStaged(setAllRemoves, false, reason);
630  }
631 }
632 
633 void CTxMemPool::removeForReorg(const CCoinsViewCache *pcoins, unsigned int nMemPoolHeight, int flags)
634 {
636  // Remove transactions spending a coinbase which are now immature and no-longer-final transactions
637  LOCK(cs);
638  setEntries txToRemove;
639  for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
640  const CTransactionRef& tx = it->GetSharedTx();
641  if (!CheckFinalTx(tx, flags)) {
642  txToRemove.insert(it);
643  } else if (it->GetSpendsCoinbaseOrCoinstake()) {
644  for (const CTxIn& txin : tx->vin) {
645  indexed_transaction_set::const_iterator it2 = mapTx.find(txin.prevout.hash);
646  if (it2 != mapTx.end())
647  continue;
648  const Coin &coin = pcoins->AccessCoin(txin.prevout);
649  if (nCheckFrequency != 0) assert(!coin.IsSpent());
650  if (coin.IsSpent() || ((coin.IsCoinBase() || coin.IsCoinStake()) && ((signed long)nMemPoolHeight) - coin.nHeight < (signed long)Params().GetConsensus().nCoinbaseMaturity)) {
651  txToRemove.insert(it);
652  break;
653  }
654  }
655  }
656  }
657  setEntries setAllRemoves;
658  for (txiter it : txToRemove) {
659  CalculateDescendants(it, setAllRemoves);
660  }
661  RemoveStaged(setAllRemoves, false, MemPoolRemovalReason::REORG);
662 }
663 
664 void CTxMemPool::removeWithAnchor(const uint256& invalidRoot)
665 {
666 
667  // If a block is disconnected from the tip, and the root changed,
668  // we must invalidate transactions from the mempool which spend
669  // from that root -- almost as though they were spending coinbases
670  // which are no longer valid to spend due to coinbase maturity.
671  LOCK(cs);
672  std::list<CTransaction> transactionsToRemove;
673  for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
674  const CTransaction& tx = it->GetTx();
675  if (!tx.IsShieldedTx()) continue;
676  for (const auto& sd : tx.sapData->vShieldedSpend) {
677  if (sd.anchor == invalidRoot) {
678  transactionsToRemove.emplace_back(tx);
679  break;
680  }
681  }
682  }
683  for (const CTransaction& tx : transactionsToRemove) {
684  removeRecursive(tx);
685  }
686 }
687 
689 {
690  // Remove transactions which depend on inputs of tx, recursively
691  std::list<CTransaction> result;
692  LOCK(cs);
693  for (const CTxIn& txin : tx.vin) {
694  auto it = mapNextTx.find(txin.prevout);
695  if (it != mapNextTx.end()) {
696  const CTransaction& txConflict = *it->second;
697  if (txConflict != tx) {
699  ClearPrioritisation(txConflict.GetHash());
700  }
701  }
702  }
703  // Remove txes with conflicting nullifier
704  if (tx.IsShieldedTx()) {
705  for (const SpendDescription& sd : tx.sapData->vShieldedSpend) {
706  const auto& it = mapSaplingNullifiers.find(sd.nullifier);
707  if (it != mapSaplingNullifiers.end()) {
708  const CTransaction& txConflict = *it->second;
709  if (txConflict != tx) {
711  ClearPrioritisation(txConflict.GetHash());
712  }
713  }
714  }
715  }
716 }
717 
719 {
720  if (mapProTxPubKeyIDs.count(keyId)) {
721  const uint256& conflictHash = mapProTxPubKeyIDs.at(keyId);
722  if (conflictHash != tx.GetHash() && mapTx.count(conflictHash)) {
723  removeRecursive(mapTx.find(conflictHash)->GetTx(), MemPoolRemovalReason::CONFLICT);
724  }
725  }
726 }
727 
729 {
730  if (mapProTxBlsPubKeyHashes.count(pubKey.GetHash())) {
731  const uint256& conflictHash = mapProTxBlsPubKeyHashes.at(pubKey.GetHash());
732  if (conflictHash != tx.GetHash() && mapTx.count(conflictHash)) {
733  removeRecursive(mapTx.find(conflictHash)->GetTx(), MemPoolRemovalReason::CONFLICT);
734  }
735  }
736 }
737 
738 void CTxMemPool::removeProTxCollateralConflicts(const CTransaction &tx, const COutPoint &collateralOutpoint)
739 {
740  if (mapProTxCollaterals.count(collateralOutpoint)) {
741  const uint256& conflictHash = mapProTxCollaterals.at(collateralOutpoint);
742  if (conflictHash != tx.GetHash() && mapTx.count(conflictHash)) {
743  removeRecursive(mapTx.find(conflictHash)->GetTx(), MemPoolRemovalReason::CONFLICT);
744  }
745  }
746 }
747 
749 {
750  // Remove TXs that refer to a certain MN
751  while (true) {
752  auto it = mapProTxRefs.find(proTxHash);
753  if (it == mapProTxRefs.end()) {
754  break;
755  }
756  auto conflictIt = mapTx.find(it->second);
757  if (conflictIt != mapTx.end()) {
758  removeRecursive(conflictIt->GetTx(), reason);
759  } else {
760  // Should not happen as we track referencing TXs in addUnchecked/removeUnchecked.
761  // But lets be on the safe side and not run into an endless loop...
762  LogPrint(BCLog::MEMPOOL, "%s: ERROR: found invalid TX ref in mapProTxRefs, proTxHash=%s, txHash=%s\n", __func__, proTxHash.ToString(), it->second.ToString());
763  mapProTxRefs.erase(it);
764  }
765  }
766 }
767 
769 {
770  auto mnList = deterministicMNManager->GetListAtChainTip();
771  for (const auto& in : tx.vin) {
772  auto collateralIt = mapProTxCollaterals.find(in.prevout);
773  if (collateralIt != mapProTxCollaterals.end()) {
774  // These are not yet mined ProRegTxs
776  }
777  auto dmn = mnList.GetMNByCollateral(in.prevout);
778  if (dmn) {
779  // These are updates referring to a mined ProRegTx
781  }
782  }
783 }
784 
786 {
788 
789  if (!tx.IsSpecialTx()) return;
790 
791  const uint256& txid = tx.GetHash();
792  switch(tx.nType) {
793  case CTransaction::TxType::PROREG: {
794  ProRegPL pl;
795  if (!GetTxPayload(tx, pl)) {
796  LogPrint(BCLog::MEMPOOL, "%s: ERROR: Invalid transaction payload, tx: %s\n", __func__, tx.ToString());
797  return;
798  }
799  if (mapProTxAddresses.count(pl.addr)) {
800  const uint256& conflictHash = mapProTxAddresses.at(pl.addr);
801  if (conflictHash != txid && mapTx.count(conflictHash)) {
802  removeRecursive(mapTx.find(conflictHash)->GetTx(), MemPoolRemovalReason::CONFLICT);
803  }
804  }
807  if (!pl.collateralOutpoint.hash.IsNull()) {
809  }
810  break;
811  }
812 
813  case CTransaction::TxType::PROUPSERV: {
814  ProUpServPL pl;
815  if (!GetTxPayload(tx, pl)) {
816  LogPrint(BCLog::MEMPOOL, "%s: ERROR: Invalid transaction payload, tx: %s\n", __func__, tx.ToString());
817  return;
818  }
819  if (mapProTxAddresses.count(pl.addr)) {
820  const uint256& conflictHash = mapProTxAddresses.at(pl.addr);
821  if (conflictHash != txid && mapTx.count(conflictHash)) {
822  removeRecursive(mapTx.find(conflictHash)->GetTx(), MemPoolRemovalReason::CONFLICT);
823  }
824  }
825  break;
826  }
827 
828  case CTransaction::TxType::PROUPREG: {
829  ProUpRegPL pl;
830  if (!GetTxPayload(tx, pl)) {
831  LogPrint(BCLog::MEMPOOL, "%s: ERROR: Invalid transaction payload, tx: %s\n", __func__, tx.ToString());
832  return;
833  }
835  break;
836  }
837 
838  }
839 }
840 
844 void CTxMemPool::removeForBlock(const std::vector<CTransactionRef>& vtx, unsigned int nBlockHeight)
845 {
846  LOCK(cs);
847  std::vector<const CTxMemPoolEntry*> entries;
848  for (const auto& tx : vtx) {
849  uint256 hash = tx->GetHash();
850  indexed_transaction_set::iterator i = mapTx.find(hash);
851  if (i != mapTx.end())
852  entries.push_back(&*i);
853  }
854  // Before the txs in the new block have been removed from the mempool, update policy estimates
855  minerPolicyEstimator->processBlock(nBlockHeight, entries);
856  for (const auto& tx : vtx) {
857  txiter it = mapTx.find(tx->GetHash());
858  if (it != mapTx.end()) {
859  setEntries stage;
860  stage.insert(it);
862  }
863  removeConflicts(*tx);
865  ClearPrioritisation(tx->GetHash());
866  }
869 }
870 
871 
873 {
874  mapLinks.clear();
875  mapTx.clear();
876  mapNextTx.clear();
877  mapProTxAddresses.clear();
878  mapProTxPubKeyIDs.clear();
879  totalTxSize = 0;
880  cachedInnerUsage = 0;
885 }
886 
888 {
889  LOCK(cs);
890  _clear();
891 }
892 
893 void CTxMemPool::check(const CCoinsViewCache* pcoins) const
894 {
895  if (nCheckFrequency == 0)
896  return;
897 
898  if (GetRand(std::numeric_limits<uint32_t>::max()) >= nCheckFrequency)
899  return;
900 
901  LogPrint(BCLog::MEMPOOL, "Checking mempool with %u transactions and %u inputs\n", (unsigned int)mapTx.size(), (unsigned int)mapNextTx.size());
902 
903  uint64_t checkTotal = 0;
904  uint64_t innerUsage = 0;
905 
906  CCoinsViewCache mempoolDuplicate(const_cast<CCoinsViewCache*>(pcoins));
907 
908  LOCK(cs);
909  std::list<const CTxMemPoolEntry*> waitingOnDependants;
910  for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
911  unsigned int i = 0;
912  checkTotal += it->GetTxSize();
913  innerUsage += it->DynamicMemoryUsage();
914  const CTransaction& tx = it->GetTx();
915  txlinksMap::const_iterator linksiter = mapLinks.find(it);
916  assert(linksiter != mapLinks.end());
917  const TxLinks &links = linksiter->second;
918  innerUsage += memusage::DynamicUsage(links.parents) + memusage::DynamicUsage(links.children);
919  bool fDependsWait = false;
920  setEntries setParentCheck;
921  int64_t parentSizes = 0;
922  unsigned int parentSigOpCount = 0;
923  for (const CTxIn& txin : tx.vin) {
924  // Check that every mempool transaction's inputs refer to available coins, or other mempool tx's.
925  indexed_transaction_set::const_iterator it2 = mapTx.find(txin.prevout.hash);
926  if (it2 != mapTx.end()) {
927  const CTransaction& tx2 = it2->GetTx();
928  assert(tx2.vout.size() > txin.prevout.n && !tx2.vout[txin.prevout.n].IsNull());
929  fDependsWait = true;
930  if (setParentCheck.insert(it2).second) {
931  parentSizes += it2->GetTxSize();
932  parentSigOpCount += it2->GetSigOpCount();
933  }
934  } else {
935  assert(pcoins->HaveCoin(txin.prevout));
936  }
937  // Check whether its inputs are marked in mapNextTx.
938  auto it3 = mapNextTx.find(txin.prevout);
939  assert(it3 != mapNextTx.end());
940  assert(it3->first == &txin.prevout);
941  assert(*it3->second == tx);
942  i++;
943  }
944  // sapling txes
945  if (tx.IsShieldedTx()) {
946  for (const SpendDescription& sd : tx.sapData->vShieldedSpend) {
947  SaplingMerkleTree tree;
948  assert(pcoins->GetSaplingAnchorAt(sd.anchor, tree));
949  assert(!pcoins->GetNullifier(sd.nullifier));
950  }
951  }
952  assert(setParentCheck == GetMemPoolParents(it));
953  // Verify ancestor state is correct.
954  setEntries setAncestors;
955  uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();
956  std::string dummy;
957  CalculateMemPoolAncestors(*it, setAncestors, nNoLimit, nNoLimit, nNoLimit, nNoLimit, dummy);
958  uint64_t nCountCheck = setAncestors.size() + 1;
959  uint64_t nSizeCheck = it->GetTxSize();
960  CAmount nFeesCheck = it->GetModifiedFee();
961  unsigned int nSigOpCheck = it->GetSigOpCount();
962 
963  for (const txiter& ancestorIt : setAncestors) {
964  nSizeCheck += ancestorIt->GetTxSize();
965  nFeesCheck += ancestorIt->GetModifiedFee();
966  nSigOpCheck += ancestorIt->GetSigOpCount();
967  }
968 
969  assert(it->GetCountWithAncestors() == nCountCheck);
970  assert(it->GetSizeWithAncestors() == nSizeCheck);
971  assert(it->GetSigOpCountWithAncestors() == nSigOpCheck);
972  assert(it->GetModFeesWithAncestors() == nFeesCheck);
973 
974  // Check children against mapNextTx
975  CTxMemPool::setEntries setChildrenCheck;
976  auto iter = mapNextTx.lower_bound(COutPoint(it->GetTx().GetHash(), 0));
977  int64_t childSizes = 0;
978  for (; iter != mapNextTx.end() && iter->first->hash == tx.GetHash(); ++iter) {
979  txiter childit = mapTx.find(iter->second->GetHash());
980  assert(childit != mapTx.end()); // mapNextTx points to in-mempool transactions
981  if (setChildrenCheck.insert(childit).second) {
982  childSizes += childit->GetTxSize();
983  }
984  }
985  assert(setChildrenCheck == GetMemPoolChildren(it));
986  // Also check to make sure size is greater than sum with immediate children.
987  // just a sanity check, not definitive that this calc is correct...
988  assert(it->GetSizeWithDescendants() >= (uint64_t)(childSizes + it->GetTxSize()));
989 
990 
991  if (fDependsWait)
992  waitingOnDependants.push_back(&(*it));
993  else {
994  CValidationState state;
995  PrecomputedTransactionData precomTxData(tx);
996  assert(CheckInputs(tx, state, mempoolDuplicate, false, 0, false, precomTxData, nullptr));
997  UpdateCoins(tx, mempoolDuplicate, 1000000);
998  }
999  }
1000 
1001  unsigned int stepsSinceLastRemove = 0;
1002  while (!waitingOnDependants.empty()) {
1003  const CTxMemPoolEntry* entry = waitingOnDependants.front();
1004  waitingOnDependants.pop_front();
1005  CValidationState state;
1006  if (!mempoolDuplicate.HaveInputs(entry->GetTx())) {
1007  waitingOnDependants.push_back(entry);
1008  stepsSinceLastRemove++;
1009  assert(stepsSinceLastRemove < waitingOnDependants.size());
1010  } else {
1011  PrecomputedTransactionData precomTxData(entry->GetTx());
1012  assert(CheckInputs(entry->GetTx(), state, mempoolDuplicate, false, 0, false, precomTxData, nullptr));
1013  UpdateCoins(entry->GetTx(), mempoolDuplicate, 1000000);
1014  stepsSinceLastRemove = 0;
1015  }
1016  }
1017  for (auto it = mapNextTx.cbegin(); it != mapNextTx.cend(); it++) {
1018  const uint256& hash = it->second->GetHash();
1019  indexed_transaction_set::const_iterator it2 = mapTx.find(hash);
1020  const CTransactionRef& tx = it2->GetSharedTx();
1021  assert(it2 != mapTx.end());
1022  assert(tx == it->second);
1023  }
1024 
1025  // Consistency check for sapling nullifiers
1026  checkNullifiers();
1027 
1028  assert(totalTxSize == checkTotal);
1029  assert(innerUsage == cachedInnerUsage);
1030 }
1031 
1033 {
1034  for (const auto& it : mapSaplingNullifiers) {
1035  const uint256& hash = it.second->GetHash();
1036  const auto& findTx = mapTx.find(hash);
1037  assert(findTx != mapTx.end());
1038  const CTransactionRef& tx = findTx->GetSharedTx();
1039  assert(*tx == *it.second);
1040  }
1041 }
1042 
1043 bool CTxMemPool::CompareDepthAndScore(const uint256& hasha, const uint256& hashb)
1044 {
1045  LOCK(cs);
1046  indexed_transaction_set::const_iterator i = mapTx.find(hasha);
1047  if (i == mapTx.end()) return false;
1048  indexed_transaction_set::const_iterator j = mapTx.find(hashb);
1049  if (j == mapTx.end()) return true;
1050  uint64_t counta = i->GetCountWithAncestors();
1051  uint64_t countb = j->GetCountWithAncestors();
1052  if (counta == countb) {
1053  return CompareTxMemPoolEntryByScore()(*i, *j);
1054  }
1055  return counta < countb;
1056 }
1057 
1058 namespace {
1059  class DepthAndScoreComparator
1060  {
1061  public:
1062  bool operator()(const CTxMemPool::indexed_transaction_set::const_iterator& a, const CTxMemPool::indexed_transaction_set::const_iterator& b) const
1063  {
1064  uint64_t counta = a->GetCountWithAncestors();
1065  uint64_t countb = b->GetCountWithAncestors();
1066  if (counta == countb) {
1067  return CompareTxMemPoolEntryByScore()(*a, *b);
1068  }
1069  return counta < countb;
1070  }
1071  };
1072 }
1073 
1074 std::vector<CTxMemPool::indexed_transaction_set::const_iterator> CTxMemPool::GetSortedDepthAndScore() const
1075 {
1076  std::vector<indexed_transaction_set::const_iterator> iters;
1077  AssertLockHeld(cs);
1078 
1079  iters.reserve(mapTx.size());
1080 
1081  for (indexed_transaction_set::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi) {
1082  iters.push_back(mi);
1083  }
1084  std::sort(iters.begin(), iters.end(), DepthAndScoreComparator());
1085  return iters;
1086 }
1087 
1088 void CTxMemPool::queryHashes(std::vector<uint256>& vtxid)
1089 {
1090  LOCK(cs);
1091  auto iters = GetSortedDepthAndScore();
1092 
1093  vtxid.clear();
1094  vtxid.reserve(mapTx.size());
1095 
1096  for (auto it : iters) {
1097  vtxid.emplace_back(it->GetTx().GetHash());
1098  }
1099 }
1100 
1101 static TxMempoolInfo GetInfo(CTxMemPool::indexed_transaction_set::const_iterator it) {
1102  return TxMempoolInfo{it->GetSharedTx(), it->GetTime(), CFeeRate(it->GetFee(), it->GetTxSize()), it->GetModifiedFee() - it->GetFee()};
1103 }
1104 
1105 std::vector<TxMempoolInfo> CTxMemPool::infoAll() const
1106 {
1107  LOCK(cs);
1108  auto iters = GetSortedDepthAndScore();
1109 
1110  std::vector<TxMempoolInfo> ret;
1111  ret.reserve(mapTx.size());
1112  for (auto it : iters) {
1113  ret.emplace_back(GetInfo(it));
1114  }
1115 
1116  return ret;
1117 }
1118 
1119 void CTxMemPool::getTransactions(std::set<uint256>& setTxid)
1120 {
1121  setTxid.clear();
1122 
1123  LOCK(cs);
1124  for (indexed_transaction_set::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
1125  setTxid.insert(mi->GetTx().GetHash());
1126 }
1127 
1128 std::shared_ptr<const CTransaction> CTxMemPool::get(const uint256& hash) const
1129 {
1130  LOCK(cs);
1131  indexed_transaction_set::const_iterator i = mapTx.find(hash);
1132  if (i == mapTx.end())
1133  return nullptr;
1134  return i->GetSharedTx();
1135 }
1136 
1138 {
1139  LOCK(cs);
1140  indexed_transaction_set::const_iterator i = mapTx.find(hash);
1141  if (i == mapTx.end())
1142  return TxMempoolInfo();
1143  return GetInfo(i);
1144 }
1145 
1147 {
1148  if (!tx.IsSpecialTx()) return false;
1149 
1150  LOCK(cs);
1151 
1152  switch(tx.nType) {
1153  case CTransaction::TxType::PROREG: {
1154  ProRegPL pl;
1155  if (!GetTxPayload(tx, pl)) {
1156  LogPrint(BCLog::MEMPOOL, "%s: ERROR: Invalid transaction payload, tx: %s\n", __func__, tx.ToString());
1157  return true; // i.e. can't decode payload == conflict
1158  }
1159  if (mapProTxAddresses.count(pl.addr) || mapProTxPubKeyIDs.count(pl.keyIDOwner) ||
1161  return true;
1162  }
1163  if (!pl.collateralOutpoint.hash.IsNull()) {
1164  if (mapProTxCollaterals.count(pl.collateralOutpoint)) {
1165  // there is another ProRegTx that refers to the same collateral
1166  return true;
1167  }
1169  // there is another tx that spends the collateral
1170  return true;
1171  }
1172  }
1173  return false;
1174  }
1175 
1176  case CTransaction::TxType::PROUPSERV: {
1177  ProUpServPL pl;
1178  if (!GetTxPayload(tx, pl)) {
1179  LogPrint(BCLog::MEMPOOL, "%s: ERROR: Invalid transaction payload, tx: %s\n", __func__, tx.ToString());
1180  return true; // i.e. can't decode payload == conflict
1181  }
1182  auto it = mapProTxAddresses.find(pl.addr);
1183  return it != mapProTxAddresses.end() && it->second != pl.proTxHash;
1184  }
1185 
1186  case CTransaction::TxType::PROUPREG: {
1187  ProUpRegPL pl;
1188  if (!GetTxPayload(tx, pl)) {
1189  LogPrint(BCLog::MEMPOOL, "%s: ERROR: Invalid transaction payload, tx: %s\n", __func__, tx.ToString());
1190  return true; // i.e. can't decode payload == conflict
1191  }
1192  auto it = mapProTxBlsPubKeyHashes.find(pl.pubKeyOperator.GetHash());
1193  return it != mapProTxBlsPubKeyHashes.end() && it->second != pl.proTxHash;
1194  }
1195 
1196  }
1197  return false;
1198 }
1199 
1201 {
1202  LOCK(cs);
1203  return minerPolicyEstimator->estimateFee(nBlocks);
1204 }
1205 
1206 CFeeRate CTxMemPool::estimateSmartFee(int nBlocks, int *answerFoundAtBlocks) const
1207 {
1208  LOCK(cs);
1209  return minerPolicyEstimator->estimateSmartFee(nBlocks, answerFoundAtBlocks, *this);
1210 }
1211 
1213 {
1214  try {
1215  LOCK(cs);
1216  fileout << 4029900; // version required to read: 4.2.99
1217  fileout << CLIENT_VERSION; // version that wrote the file
1218  minerPolicyEstimator->Write(fileout);
1219  } catch (const std::exception&) {
1220  LogPrintf("CTxMemPool::WriteFeeEstimates() : unable to write policy estimator data (non-fatal)\n");
1221  return false;
1222  }
1223  return true;
1224 }
1225 
1227 {
1228  try {
1229  int nVersionRequired, nVersionThatWrote;
1230  filein >> nVersionRequired >> nVersionThatWrote;
1231  if (nVersionRequired > CLIENT_VERSION)
1232  return error("CTxMemPool::ReadFeeEstimates() : up-version (%d) fee estimate file\n", nVersionRequired);
1233 
1234  LOCK(cs);
1235  minerPolicyEstimator->Read(filein, nVersionThatWrote);
1236  } catch (const std::exception&) {
1237  LogPrintf("CTxMemPool::ReadFeeEstimates() : unable to read policy estimator data (non-fatal)\n");
1238  return false;
1239  }
1240  return true;
1241 }
1242 
1243 void CTxMemPool::PrioritiseTransaction(const uint256& hash, const CAmount& nFeeDelta)
1244 {
1245  {
1246  LOCK(cs);
1247  CAmount &delta = mapDeltas[hash];
1248  delta += nFeeDelta;
1249  txiter it = mapTx.find(hash);
1250  if (it != mapTx.end()) {
1251  mapTx.modify(it, update_fee_delta(delta));
1252  // Now update all ancestors' modified fees with descendants
1253  setEntries setAncestors;
1254  uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();
1255  std::string dummy;
1256  CalculateMemPoolAncestors(*it, setAncestors, nNoLimit, nNoLimit, nNoLimit, nNoLimit, dummy, false);
1257  for (const txiter& ancestorIt : setAncestors) {
1258  mapTx.modify(ancestorIt, update_descendant_state(0, nFeeDelta, 0));
1259  }
1260  }
1261  }
1262  LogPrintf("PrioritiseTransaction: %s feerate += %s\n", hash.ToString(), FormatMoney(nFeeDelta));
1263 }
1264 
1265 void CTxMemPool::ApplyDelta(const uint256& hash, CAmount& nFeeDelta) const
1266 {
1267  LOCK(cs);
1268  std::map<uint256, CAmount>::const_iterator pos = mapDeltas.find(hash);
1269  if (pos == mapDeltas.end())
1270  return;
1271  const CAmount &delta = pos->second;
1272  nFeeDelta += delta;
1273 }
1274 
1276 {
1277  LOCK(cs);
1278  mapDeltas.erase(hash);
1279 }
1280 
1281 bool CTxMemPool::nullifierExists(const uint256& nullifier) const
1282 {
1283  LOCK(cs);
1284  return mapSaplingNullifiers.count(nullifier);
1285 }
1286 
1288 {
1289  if (tx.HasZerocoinSpendInputs())
1290  return true;
1291  for (unsigned int i = 0; i < tx.vin.size(); i++)
1292  if (exists(tx.vin[i].prevout.hash))
1293  return false;
1294  return true;
1295 }
1296 
1297 
1299 
1300 bool CCoinsViewMemPool::GetCoin(const COutPoint& outpoint, Coin& coin) const
1301 {
1302  // If an entry in the mempool exists, always return that one, as it's guaranteed to never
1303  // conflict with the underlying cache, and it cannot have pruned entries (as it contains full)
1304  // transactions. First checking the underlying cache risks returning a pruned entry instead.
1305  CTransactionRef ptx = mempool.get(outpoint.hash);
1306  if (ptx) {
1307  if (outpoint.n < ptx->vout.size()) {
1308  coin = Coin(ptx->vout[outpoint.n], MEMPOOL_HEIGHT, false, false);
1309  return true;
1310  } else {
1311  return false;
1312  }
1313  }
1314  return (base->GetCoin(outpoint, coin) && !coin.IsSpent());
1315 }
1316 
1317 bool CCoinsViewMemPool::HaveCoin(const COutPoint& outpoint) const
1318 {
1319  return mempool.exists(outpoint) || base->HaveCoin(outpoint);
1320 }
1321 
1322 bool CCoinsViewMemPool::GetNullifier(const uint256& nullifier) const
1323 {
1324  return mempool.nullifierExists(nullifier) || base->GetNullifier(nullifier);
1325 }
1326 
1328 {
1329  LOCK(cs);
1330  // Estimate the overhead of mapTx to be 15 pointers + an allocation, as no exact formula for
1331  // boost::multi_index_contained is implemented.
1332  return memusage::MallocUsage(sizeof(CTxMemPoolEntry) + 15 * sizeof(void*)) * mapTx.size() +
1333  memusage::DynamicUsage(mapNextTx) +
1334  memusage::DynamicUsage(mapDeltas) +
1335  memusage::DynamicUsage(mapLinks) +
1337  memusage::DynamicUsage(mapSaplingNullifiers);
1338 }
1339 
1340 void CTxMemPool::RemoveStaged(setEntries &stage, bool updateDescendants, MemPoolRemovalReason reason)
1341 {
1342  AssertLockHeld(cs);
1343  UpdateForRemoveFromMempool(stage, updateDescendants);
1344  for (const txiter& it : stage) {
1345  removeUnchecked(it, reason);
1346  }
1347 }
1348 
1349 int CTxMemPool::Expire(int64_t time)
1350 {
1351  LOCK(cs);
1352  indexed_transaction_set::index<entry_time>::type::iterator it = mapTx.get<entry_time>().begin();
1353  setEntries toremove;
1354  while (it != mapTx.get<entry_time>().end() && it->GetTime() < time) {
1355  toremove.insert(mapTx.project<0>(it));
1356  it++;
1357  }
1358  setEntries stage;
1359  for (const txiter& removeit : toremove) {
1360  CalculateDescendants(removeit, stage);
1361  }
1363  return stage.size();
1364 }
1365 
1366 bool CTxMemPool::addUnchecked(const uint256&hash, const CTxMemPoolEntry &entry, bool validFeeEstimate)
1367 {
1368  LOCK(cs);
1369  setEntries setAncestors;
1370  uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();
1371  std::string dummy;
1372  CalculateMemPoolAncestors(entry, setAncestors, nNoLimit, nNoLimit, nNoLimit, nNoLimit, dummy);
1373  return addUnchecked(hash, entry, setAncestors, validFeeEstimate);
1374 }
1375 
1376 void CTxMemPool::UpdateChild(txiter entry, txiter child, bool add)
1377 {
1378  setEntries s;
1379  if (add && mapLinks[entry].children.insert(child).second) {
1380  cachedInnerUsage += memusage::IncrementalDynamicUsage(s);
1381  } else if (!add && mapLinks[entry].children.erase(child)) {
1382  cachedInnerUsage -= memusage::IncrementalDynamicUsage(s);
1383  }
1384 }
1385 
1386 void CTxMemPool::UpdateParent(txiter entry, txiter parent, bool add)
1387 {
1388  setEntries s;
1389  if (add && mapLinks[entry].parents.insert(parent).second) {
1390  cachedInnerUsage += memusage::IncrementalDynamicUsage(s);
1391  } else if (!add && mapLinks[entry].parents.erase(parent)) {
1392  cachedInnerUsage -= memusage::IncrementalDynamicUsage(s);
1393  }
1394 }
1395 
1397 {
1398  assert (entry != mapTx.end());
1399  txlinksMap::const_iterator it = mapLinks.find(entry);
1400  assert(it != mapLinks.end());
1401  return it->second.parents;
1402 }
1403 
1405 {
1406  assert (entry != mapTx.end());
1407  txlinksMap::const_iterator it = mapLinks.find(entry);
1408  assert(it != mapLinks.end());
1409  return it->second.children;
1410 }
1411 
1412 CFeeRate CTxMemPool::GetMinFee(size_t sizelimit) const
1413 {
1414  LOCK(cs);
1417 
1418  int64_t time = GetTime();
1419  if (time > lastRollingFeeUpdate + 10) {
1420  double halflife = ROLLING_FEE_HALFLIFE;
1421  if (DynamicMemoryUsage() < sizelimit / 4)
1422  halflife /= 4;
1423  else if (DynamicMemoryUsage() < sizelimit / 2)
1424  halflife /= 2;
1425 
1426  rollingMinimumFeeRate = rollingMinimumFeeRate / pow(2.0, (time - lastRollingFeeUpdate) / halflife);
1427  lastRollingFeeUpdate = time;
1428 
1431  return CFeeRate(0);
1432  }
1433  }
1435 }
1436 
1438 {
1439  AssertLockHeld(cs);
1440  if (rate.GetFeePerK() > rollingMinimumFeeRate) {
1443  }
1444 }
1445 
1446 void CTxMemPool::TrimToSize(size_t sizelimit, std::vector<COutPoint>* pvNoSpendsRemaining)
1447 {
1448  LOCK(cs);
1449  unsigned nTxnRemoved = 0;
1450  CFeeRate maxFeeRateRemoved(0);
1451  while (DynamicMemoryUsage() > sizelimit) {
1452  indexed_transaction_set::index<descendant_score>::type::iterator it = mapTx.get<descendant_score>().begin();
1453 
1454  // We set the new mempool min fee to the feerate of the removed set, plus the
1455  // "minimum reasonable fee rate" (ie some value under which we consider txn
1456  // to have 0 fee). This way, we don't allow txn to enter mempool with feerate
1457  // equal to txn which were removed with no block in between.
1458  CFeeRate removed(it->GetModFeesWithDescendants(), it->GetSizeWithDescendants());
1459  removed += minReasonableRelayFee;
1460  trackPackageRemoved(removed);
1461  maxFeeRateRemoved = std::max(maxFeeRateRemoved, removed);
1462 
1463  setEntries stage;
1464  CalculateDescendants(mapTx.project<0>(it), stage);
1465  nTxnRemoved += stage.size();
1466 
1467  std::vector<CTransaction> txn;
1468  if (pvNoSpendsRemaining) {
1469  txn.reserve(stage.size());
1470  for (txiter it: stage)
1471  txn.push_back(it->GetTx());
1472  }
1474  if (pvNoSpendsRemaining) {
1475  for (const CTransaction& tx: txn) {
1476  for (const CTxIn& txin: tx.vin) {
1477  if (exists(txin.prevout.hash)) continue;
1478  if (!mapNextTx.count(txin.prevout)) {
1479  pvNoSpendsRemaining->push_back(txin.prevout);
1480  }
1481  }
1482  }
1483  }
1484  }
1485 
1486  if (maxFeeRateRemoved > CFeeRate(0))
1487  LogPrint(BCLog::MEMPOOL, "Removed %u txn, rolling minimum fee bumped to %s\n", nTxnRemoved, maxFeeRateRemoved.ToString());
1488 }
1489 
1490 bool CTxMemPool::TransactionWithinChainLimit(const uint256& txid, size_t chainLimit) const {
1491  LOCK(cs);
1492  auto it = mapTx.find(txid);
1493  return it == mapTx.end() || (it->GetCountWithAncestors() < chainLimit &&
1494  it->GetCountWithDescendants() < chainLimit);
1495 }
1496 
1498 {
1499  LOCK(cs);
1500  return m_is_loaded;
1501 }
1502 
1503 void CTxMemPool::SetIsLoaded(bool loaded)
1504 {
1505  LOCK(cs);
1506  m_is_loaded = loaded;
1507 }
1508 
int64_t CAmount
Amount in PIV (Can be negative)
Definition: amount.h:13
const CChainParams & Params()
Return the currently selected parameters.
uint256 hash
Definition: transaction.h:35
bool IsNull() const
Definition: transaction.h:46
uint32_t n
Definition: transaction.h:36
Non-refcounted RAII wrapper for FILE*.
Definition: streams.h:452
const uint256 & GetHash() const
Definition: bls_wrapper.h:124
We want to be able to estimate feerates or priorities that are needed on tx's to be included in a cer...
Definition: fees.h:201
bool removeTx(const uint256 &hash)
Remove a transaction from the mempool tracking stats.
Definition: fees.cpp:287
void Write(CAutoFile &fileout)
Write estimation data to a file.
Definition: fees.cpp:457
CFeeRate estimateFee(int confTarget)
Return a feerate estimate.
Definition: fees.cpp:416
void Read(CAutoFile &filein, int nFileVersion)
Read estimation data from a file.
Definition: fees.cpp:463
CFeeRate estimateSmartFee(int confTarget, int *answerFoundAtTarget, const CTxMemPool &pool)
Estimate feerate needed to get be included in a block within confTarget blocks.
Definition: fees.cpp:430
void processTransaction(const CTxMemPoolEntry &entry, bool validFeeEstimate)
Process a transaction accepted to the mempool.
Definition: fees.cpp:311
void processBlock(unsigned int nBlockHeight, std::vector< const CTxMemPoolEntry * > &entries)
Process all the transactions that have been included in a block.
Definition: fees.cpp:379
CCoinsView backed by another CCoinsView.
Definition: coins.h:250
CCoinsView * base
Definition: coins.h:252
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:283
bool HaveInputs(const CTransaction &tx) const
Check whether all prevouts of the transaction are present in the UTXO set represented by this view.
Definition: coins.cpp:357
bool GetSaplingAnchorAt(const uint256 &rt, SaplingMerkleTree &tree) const override
Retrieve the tree (Sapling) at a particular anchored root in the chain.
Definition: coins.cpp:422
bool GetNullifier(const uint256 &nullifier) const override
Determine whether a nullifier is spent or not.
Definition: coins.cpp:446
bool HaveCoin(const COutPoint &outpoint) const override
Just check whether we have data for a given outpoint.
Definition: coins.cpp:161
const Coin & AccessCoin(const COutPoint &output) const
Return a reference to a Coin in the cache, or a pruned one if not found.
Definition: coins.cpp:151
Abstract view on the open txout dataset.
Definition: coins.h:201
virtual bool GetCoin(const COutPoint &outpoint, Coin &coin) const
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:16
virtual bool GetNullifier(const uint256 &nullifier) const
Determine whether a nullifier is spent or not.
Definition: coins.cpp:30
virtual bool HaveCoin(const COutPoint &outpoint) const
Just check whether we have data for a given outpoint.
Definition: coins.cpp:17
bool HaveCoin(const COutPoint &outpoint) const
Just check whether we have data for a given outpoint.
Definition: txmempool.cpp:1317
bool GetCoin(const COutPoint &outpoint, Coin &coin) const
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: txmempool.cpp:1300
CTxMemPool & mempool
Definition: txmempool.h:731
bool GetNullifier(const uint256 &nullifier) const
Determine whether a nullifier is spent or not.
Definition: txmempool.cpp:1322
CCoinsViewMemPool(CCoinsView *baseIn, CTxMemPool &mempoolIn)
Definition: txmempool.cpp:1298
Fee rate in PIV per kilobyte: CAmount / kB.
Definition: feerate.h:20
std::string ToString() const
Definition: feerate.cpp:31
CAmount GetFee(size_t size) const
Definition: feerate.cpp:21
CAmount GetFeePerK() const
Definition: feerate.h:29
A reference to a CKey: the Hash160 of its serialized public key.
Definition: pubkey.h:21
void TransactionRemovedFromMempool(const CTransactionRef &, MemPoolRemovalReason)
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:72
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:244
bool HasZerocoinSpendInputs() const
const int16_t nType
Definition: transaction.h:273
std::vector< CTxIn > vin
Definition: transaction.h:270
bool IsShieldedTx() const
Definition: transaction.h:319
const uint256 & GetHash() const
Definition: transaction.h:301
std::string ToString() const
bool IsSpecialTx() const
Definition: transaction.h:329
Optional< SaplingTxData > sapData
Definition: transaction.h:275
std::vector< CTxOut > vout
Definition: transaction.h:271
An input of a transaction.
Definition: transaction.h:94
COutPoint prevout
Definition: transaction.h:96
CTxMemPoolEntry stores data about the corresponding transaction, as well as data about all in-mempool...
Definition: txmempool.h:55
void UpdateFeeDelta(int64_t feeDelta)
Definition: txmempool.cpp:49
size_t nTxSize
Cached to avoid expensive parent-transaction lookups.
Definition: txmempool.h:59
const CTransaction & GetTx() const
Definition: txmempool.h:90
int64_t feeDelta
Legacy sig ops plus P2SH sig op count.
Definition: txmempool.h:68
void UpdateDescendantState(int64_t modifySize, CAmount modifyFee, int64_t modifyCount)
Definition: txmempool.cpp:306
size_t nUsageSize
... and avoid recomputing tx size
Definition: txmempool.h:60
void UpdateAncestorState(int64_t modifySize, CAmount modifyFee, int64_t modifyCount, int modifySigOps)
Definition: txmempool.cpp:315
CAmount nModFeesWithAncestors
Definition: txmempool.h:82
unsigned int nSigOpCountWithAncestors
Definition: txmempool.h:83
bool hasZerocoins
... and fee per kB
Definition: txmempool.h:62
uint64_t nCountWithDescendants
Used for determining the priority of the transaction for mining in a block.
Definition: txmempool.h:75
size_t GetTxSize() const
Definition: txmempool.h:93
unsigned int sigOpCount
keep track of transactions that spend a coinbase or a coinstake
Definition: txmempool.h:67
bool m_isShielded
... and checking if it contains zPIV (mints/spends)
Definition: txmempool.h:63
std::shared_ptr< const CTransaction > GetSharedTx() const
Definition: txmempool.h:91
uint64_t nSizeWithDescendants
number of descendant transactions
Definition: txmempool.h:76
CTxMemPoolEntry(const CTransactionRef &_tx, const CAmount &_nFee, int64_t _nTime, unsigned int _entryHeight, bool _spendsCoinbaseOrCoinstake, unsigned int nSigOps)
Definition: txmempool.cpp:26
size_t DynamicMemoryUsage() const
Definition: txmempool.h:100
CAmount nModFeesWithDescendants
... and size
Definition: txmempool.h:77
uint64_t nCountWithAncestors
... and total fees (all including us)
Definition: txmempool.h:80
uint64_t nSizeWithAncestors
Definition: txmempool.h:81
CAmount nFee
Definition: txmempool.h:58
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:384
void PrioritiseTransaction(const uint256 &hash, const CAmount &nFeeDelta)
Affect CreateNewBlock prioritisation of transactions.
Definition: txmempool.cpp:1243
txlinksMap mapLinks
Definition: txmempool.h:495
bool TransactionWithinChainLimit(const uint256 &txid, size_t chainLimit) const
Returns false if the transaction is in the mempool and not within the chain limit specified.
Definition: txmempool.cpp:1490
bool ReadFeeEstimates(CAutoFile &filein)
Definition: txmempool.cpp:1226
const setEntries & GetMemPoolChildren(txiter entry) const
Definition: txmempool.cpp:1404
void ClearPrioritisation(const uint256 hash)
Definition: txmempool.cpp:1275
void removeWithAnchor(const uint256 &invalidRoot)
Definition: txmempool.cpp:664
void removeRecursive(const CTransaction &tx, MemPoolRemovalReason reason=MemPoolRemovalReason::UNKNOWN)
Definition: txmempool.cpp:601
void UpdateAncestorsOf(bool add, txiter hash, setEntries &setAncestors)
Update ancestors of hash to add/remove it as a descendant transaction.
Definition: txmempool.cpp:211
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it.
Definition: txmempool.h:471
unsigned int nTransactionsUpdated
Value n means that n times in 2^32 we check.
Definition: txmempool.h:387
std::map< uint256, CTransactionRef > mapSaplingNullifiers
Definition: txmempool.h:403
CFeeRate GetMinFee(size_t sizelimit) const
The minimum fee to get into the mempool, which may itself not be enough for larger-sized transactions...
Definition: txmempool.cpp:1412
CTransactionRef get(const uint256 &hash) const
Definition: txmempool.cpp:1128
bool WriteFeeEstimates(CAutoFile &fileout) const
Write/Read estimates to disk.
Definition: txmempool.cpp:1212
std::map< CKeyID, uint256 > mapProTxPubKeyIDs
Definition: txmempool.h:499
int Expire(int64_t time)
Expire all transaction (and their dependencies) in the mempool older than time.
Definition: txmempool.cpp:1349
uint32_t nCheckFrequency
Definition: txmempool.h:386
void getTransactions(std::set< uint256 > &setTxid)
Definition: txmempool.cpp:1119
void _clear()
Definition: txmempool.cpp:872
void AddTransactionsUpdated(unsigned int n)
Definition: txmempool.cpp:357
CFeeRate estimateFee(int nBlocks) const
Estimate fee rate needed to get into the next nBlocks.
Definition: txmempool.cpp:1200
indirectmap< COutPoint, CTransactionRef > mapNextTx
Definition: txmempool.h:509
void removeProTxReferences(const uint256 &proTxHash, MemPoolRemovalReason reason)
Definition: txmempool.cpp:748
CFeeRate estimateSmartFee(int nBlocks, int *answerFoundAtBlocks=nullptr) const
Estimate fee rate needed to get into the next nBlocks If no answer can be given at nBlocks,...
Definition: txmempool.cpp:1206
double rollingMinimumFeeRate
Definition: txmempool.h:398
void queryHashes(std::vector< uint256 > &vtxid)
Definition: txmempool.cpp:1088
std::vector< indexed_transaction_set::const_iterator > GetSortedDepthAndScore() const
Definition: txmempool.cpp:1074
void UpdateForDescendants(txiter updateIt, cacheMap &cachedDescendants, const std::set< uint256 > &setExclude)
UpdateForDescendants is used by UpdateTransactionsFromBlock to update the descendants for a single tr...
Definition: txmempool.cpp:59
void removeUnchecked(txiter entry, MemPoolRemovalReason reason=MemPoolRemovalReason::UNKNOWN)
Before calling removeUnchecked for a given transaction, UpdateForRemoveFromMempool must be called on ...
Definition: txmempool.cpp:540
bool addUnchecked(const uint256 &hash, const CTxMemPoolEntry &entry, bool validFeeEstimate=true)
Definition: txmempool.cpp:1366
size_t DynamicMemoryUsage() const
Definition: txmempool.cpp:1327
std::vector< TxMempoolInfo > infoAll() const
Definition: txmempool.cpp:1105
void SetIsLoaded(bool loaded)
Sets the current loaded state.
Definition: txmempool.cpp:1503
int64_t lastRollingFeeUpdate
Definition: txmempool.h:396
std::map< uint256, CAmount > mapDeltas
Definition: txmempool.h:510
void trackPackageRemoved(const CFeeRate &rate)
minimum fee to get into the pool, decreases exponentially
Definition: txmempool.cpp:1437
void checkNullifiers() const
Definition: txmempool.cpp:1032
void addUncheckedSpecialTx(const CTransaction &tx)
Special txes.
Definition: txmempool.cpp:363
void clear()
Definition: txmempool.cpp:887
void removeProTxPubKeyConflicts(const CTransaction &tx, const CKeyID &keyId)
Definition: txmempool.cpp:718
CFeeRate minReasonableRelayFee
sum of dynamic memory usage of all the map elements (NOT the maps themselves)
Definition: txmempool.h:394
void removeProTxCollateralConflicts(const CTransaction &tx, const COutPoint &collateralOutpoint)
Definition: txmempool.cpp:738
bool HasNoInputsOf(const CTransaction &tx) const
Check that none of this transactions inputs are in the mempool, and thus the tx is not dependent on o...
Definition: txmempool.cpp:1287
void UpdateForRemoveFromMempool(const setEntries &entriesToRemove, bool updateDescendants)
For each transaction being removed, update ancestors and any direct children.
Definition: txmempool.cpp:248
void UpdateTransactionsFromBlock(const std::vector< uint256 > &hashesToUpdate)
When adding transactions from a disconnected block back to the mempool, new mempool entries may have ...
Definition: txmempool.cpp:106
bool existsProviderTxConflict(const CTransaction &tx) const
Definition: txmempool.cpp:1146
bool CompareDepthAndScore(const uint256 &hasha, const uint256 &hashb)
Definition: txmempool.cpp:1043
void UpdateChildrenForRemoval(txiter entry)
Sever link between specified transaction and direct children.
Definition: txmempool.cpp:240
void removeProTxConflicts(const CTransaction &tx)
Definition: txmempool.cpp:785
bool CalculateMemPoolAncestors(const CTxMemPoolEntry &entry, setEntries &setAncestors, uint64_t limitAncestorCount, uint64_t limitAncestorSize, uint64_t limitDescendantCount, uint64_t limitDescendantSize, std::string &errString, bool fSearchForParents=true) const
Try to calculate all in-mempool ancestors of entry.
Definition: txmempool.cpp:149
bool exists(uint256 hash) const
Definition: txmempool.h:640
static const int ROLLING_FEE_HALFLIFE
Definition: txmempool.h:410
std::set< txiter, CompareIteratorByHash > setEntries
Definition: txmempool.h:481
void removeConflicts(const CTransaction &tx)
Definition: txmempool.cpp:688
void UpdateChild(txiter entry, txiter child, bool add)
Definition: txmempool.cpp:1376
uint64_t cachedInnerUsage
sum of all mempool tx' byte sizes
Definition: txmempool.h:392
indexed_transaction_set::nth_index< 0 >::type::iterator txiter
Definition: txmempool.h:474
void removeUncheckedSpecialTx(const CTransaction &tx)
Definition: txmempool.cpp:480
std::map< CService, uint256 > mapProTxAddresses
Definition: txmempool.h:498
bool IsLoaded() const
Definition: txmempool.cpp:1497
void check(const CCoinsViewCache *pcoins) const
If sanity-checking is turned on, check makes sure the pool is consistent (does not contain two transa...
Definition: txmempool.cpp:893
std::multimap< uint256, uint256 > mapProTxRefs
Definition: txmempool.h:497
std::map< txiter, setEntries, CompareIteratorByHash > cacheMap
Definition: txmempool.h:487
CTxMemPool(const CFeeRate &_minReasonableRelayFee)
Create a new CTxMemPool.
Definition: txmempool.cpp:326
const setEntries & GetMemPoolParents(txiter entry) const
Definition: txmempool.cpp:1396
uint64_t totalTxSize
Passed to constructor to avoid dependency on main.
Definition: txmempool.h:391
void RemoveStaged(setEntries &stage, bool updateDescendants, MemPoolRemovalReason reason=MemPoolRemovalReason::UNKNOWN)
Remove a set of transactions from the mempool.
Definition: txmempool.cpp:1340
indexed_transaction_set mapTx
Definition: txmempool.h:472
void removeForReorg(const CCoinsViewCache *pcoins, unsigned int nMemPoolHeight, int flags)
Definition: txmempool.cpp:633
TxMempoolInfo info(const uint256 &hash) const
Definition: txmempool.cpp:1137
std::map< uint256, uint256 > mapProTxBlsPubKeyHashes
Definition: txmempool.h:500
void TrimToSize(size_t sizelimit, std::vector< COutPoint > *pvNoSpendsRemaining=nullptr)
Remove transactions from the mempool until its dynamic size is <= sizelimit.
Definition: txmempool.cpp:1446
bool isSpent(const COutPoint &outpoint)
Definition: txmempool.cpp:345
void UpdateParent(txiter entry, txiter parent, bool add)
Definition: txmempool.cpp:1386
void CalculateDescendants(txiter it, setEntries &setDescendants)
Populate setDescendants with all in-mempool descendants of hash.
Definition: txmempool.cpp:578
void UpdateEntryForAncestors(txiter it, const setEntries &setAncestors)
Set ancestor state for an entry.
Definition: txmempool.cpp:226
void removeForBlock(const std::vector< CTransactionRef > &vtx, unsigned int nBlockHeight)
Called when a block is connected.
Definition: txmempool.cpp:844
std::map< COutPoint, uint256 > mapProTxCollaterals
Definition: txmempool.h:501
bool blockSinceLastRollingFeeBump
Definition: txmempool.h:397
void removeProTxSpentCollateralConflicts(const CTransaction &tx)
Definition: txmempool.cpp:768
CBlockPolicyEstimator * minerPolicyEstimator
Definition: txmempool.h:388
bool nullifierExists(const uint256 &nullifier) const
Definition: txmempool.cpp:1281
void ApplyDelta(const uint256 &hash, CAmount &nFeeDelta) const
Definition: txmempool.cpp:1265
unsigned int GetTransactionsUpdated() const
Definition: txmempool.cpp:351
Capture information about block/transaction validation.
Definition: validation.h:24
A UTXO entry.
Definition: coins.h:32
bool IsCoinBase() const
Definition: coins.h:60
bool IsCoinStake() const
Definition: coins.h:64
bool IsSpent() const
Definition: coins.h:86
uint32_t nHeight
at which height the containing transaction was included in the active block chain
Definition: coins.h:44
Sort by score of entry ((fee+delta)/size) in descending order.
Definition: txmempool.h:221
COutPoint collateralOutpoint
Definition: providertx.h:29
CBLSPublicKey pubKeyOperator
Definition: providertx.h:32
CKeyID keyIDOwner
Definition: providertx.h:31
CService addr
Definition: providertx.h:30
uint256 proTxHash
Definition: providertx.h:110
CBLSPublicKey pubKeyOperator
Definition: providertx.h:112
uint256 proTxHash
Definition: providertx.h:151
CService addr
Definition: providertx.h:81
uint256 proTxHash
Definition: providertx.h:80
A shielded input to a transaction.
uint256 anchor
A Merkle root of the Sapling note commitment tree at some block height in the past.
uint256 nullifier
The nullifier of the input note.
std::string ToString() const
Definition: uint256.cpp:65
bool IsNull() const
Definition: uint256.h:36
iterator lower_bound(const K &key)
Definition: indirectmap.h:40
const_iterator cbegin() const
Definition: indirectmap.h:54
std::pair< iterator, bool > insert(const value_type &value)
Definition: indirectmap.h:35
size_type size() const
Definition: indirectmap.h:47
iterator find(const K &key)
Definition: indirectmap.h:38
const_iterator cend() const
Definition: indirectmap.h:55
size_type erase(const K &key)
Definition: indirectmap.h:42
iterator end()
Definition: indirectmap.h:51
size_type count(const K &key) const
Definition: indirectmap.h:43
void clear()
Definition: indirectmap.h:49
256-bit opaque blob.
Definition: uint256.h:138
void UpdateCoins(const CTransaction &tx, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight, bool fSkipInvalid=false)
std::unique_ptr< CDeterministicMNManager > deterministicMNManager
@ LOCK
Definition: lockunlock.h:16
#define LogPrint(category,...)
Definition: logging.h:163
@ MEMPOOL
Definition: logging.h:43
RecursiveMutex cs_main
Global state.
Definition: validation.cpp:80
int flags
Definition: pivx-tx.cpp:400
uint64_t GetRand(uint64_t nMax) noexcept
Definition: random.cpp:586
reverse_range< T > reverse_iterate(T &x)
@ proTxHash
Definition: rpcevo.cpp:50
unsigned int GetSerializeSize(const std::array< T, N > &item)
array
Definition: serialize.h:847
Information about a mempool transaction.
Definition: txmempool.h:278
#define AssertLockHeld(cs)
Definition: sync.h:75
bool error(const char *fmt, const Args &... args)
Definition: system.h:77
#define strprintf
Definition: tinyformat.h:1056
bool GetTxPayload(const std::vector< unsigned char > &payload, T &obj)
Definition: transaction.h:464
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:456
MemPoolRemovalReason
Reason why a transaction was removed from the mempool, this is passed to the notification signal.
Definition: txmempool.h:295
@ SIZELIMIT
Expired from mempool.
@ BLOCK
Removed for reorganization.
@ EXPIRY
Manually removed or unknown reason.
@ CONFLICT
Removed for block.
@ REORG
Removed in size limiting.
std::string FormatMoney(const CAmount &n, bool fPlus)
Money parsing/formatting utilities.
int64_t GetTime()
DEPRECATED Use either GetSystemTimeInSeconds (not mockable) or GetTime<T> (mockable)
Definition: utiltime.cpp:27
bool CheckFinalTx(const CTransactionRef &tx, int flags)
Check if transaction will be final in the next block to be created.
Definition: validation.cpp:224
bool CheckInputs(const CTransaction &tx, CValidationState &state, const CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, bool cacheStore, PrecomputedTransactionData &precomTxData, std::vector< CScriptCheck > *pvChecks)
Check transaction inputs, and make sure any pay-to-script-hash transactions are evaluating IsStandard...
CTxMemPool mempool(::minRelayTxFee)
CMainSignals & GetMainSignals()