Dash Core Source Documentation (0.16.0.1)

Find detailed information regarding the Dash Core source code.

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