1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2014 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or https://www.opensource.org/licenses/mit-license.php .
8 #include "clientversion.h"
9 #include "consensus/consensus.h"
10 #include "consensus/validation.h"
12 #include "policy/fees.h"
16 #include "utilmoneystr.h"
17 #include "validationinterface.h"
19 #include "cc/CCinclude.h"
20 #include "pbaas/pbaas.h"
21 #include "pbaas/identity.h"
22 #define _COINBASE_MATURITY 100
26 CTxMemPoolEntry::CTxMemPoolEntry():
27 nFee(0), nTxSize(0), nModSize(0), nUsageSize(0), nTime(0), dPriority(0.0),
28 hadNoDependencies(false), spendsCoinbase(false), hasReserve(false)
30 nHeight = MEMPOOL_HEIGHT;
33 CTxMemPoolEntry::CTxMemPoolEntry(const CTransaction& _tx, const CAmount& _nFee,
34 int64_t _nTime, double _dPriority,
35 unsigned int _nHeight, bool poolHasNoInputsOf,
36 bool _spendsCoinbase, uint32_t _nBranchId, bool hasreserve):
37 tx(_tx), nFee(_nFee), nTime(_nTime), dPriority(_dPriority), nHeight(_nHeight),
38 hadNoDependencies(poolHasNoInputsOf), hasReserve(hasreserve),
39 spendsCoinbase(_spendsCoinbase), nBranchId(_nBranchId)
41 nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
42 nModSize = tx.CalculateModifiedSize(nTxSize);
43 nUsageSize = RecursiveDynamicUsage(tx);
44 feeRate = CFeeRate(nFee, nTxSize);
47 CTxMemPoolEntry::CTxMemPoolEntry(const CTxMemPoolEntry& other)
53 CTxMemPoolEntry::GetPriority(unsigned int currentHeight) const
55 CAmount nValueIn = tx.GetValueOut()+nFee;
56 CCurrencyState currencyState;
57 unsigned int lastHeight = currentHeight < 1 ? 0 : currentHeight - 1;
58 AssertLockHeld(cs_main);
59 if (hasReserve && (currencyState = ConnectedChains.GetCurrencyState(currentHeight - 1)).IsValid())
61 nValueIn += currencyState.ReserveToNative(tx.GetReserveValueOut());
63 double deltaPriority = ((double)(currentHeight-nHeight)*nValueIn)/nModSize;
64 double dResult = dPriority + deltaPriority;
68 CTxMemPool::CTxMemPool(const CFeeRate& _minRelayFee) :
69 nTransactionsUpdated(0)
71 // Sanity checks off by default for performance, because otherwise
72 // accepting transactions becomes O(N^2) where N is the number
73 // of transactions in the pool
76 minerPolicyEstimator = new CBlockPolicyEstimator(_minRelayFee);
79 CTxMemPool::~CTxMemPool()
81 delete minerPolicyEstimator;
84 void CTxMemPool::pruneSpent(const uint256 &hashTx, CCoins &coins)
88 std::map<COutPoint, CInPoint>::iterator it = mapNextTx.lower_bound(COutPoint(hashTx, 0));
90 // iterate over all COutPoints in mapNextTx whose hash equals the provided hashTx
91 while (it != mapNextTx.end() && it->first.hash == hashTx) {
92 coins.Spend(it->first.n); // and remove those outputs from coins
97 unsigned int CTxMemPool::GetTransactionsUpdated() const
100 return nTransactionsUpdated;
103 void CTxMemPool::AddTransactionsUpdated(unsigned int n)
106 nTransactionsUpdated += n;
110 bool CTxMemPool::addUnchecked(const uint256& hash, const CTxMemPoolEntry &entry, bool fCurrentEstimate)
112 // Add to memory pool without checking anything.
113 // Used by main.cpp AcceptToMemoryPool(), which DOES do
114 // all the appropriate checks.
117 const CTransaction& tx = mapTx.find(hash)->GetTx();
118 mapRecentlyAddedTx[tx.GetHash()] = &tx;
119 nRecentlyAddedSequence += 1;
120 if (!tx.IsCoinImport()) {
121 for (unsigned int i = 0; i < tx.vin.size(); i++)
122 mapNextTx[tx.vin[i].prevout] = CInPoint(&tx, i);
124 BOOST_FOREACH(const JSDescription &joinsplit, tx.vJoinSplit) {
125 BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
126 mapSproutNullifiers[nf] = &tx;
129 for (const SpendDescription &spendDescription : tx.vShieldedSpend) {
130 mapSaplingNullifiers[spendDescription.nullifier] = &tx;
132 nTransactionsUpdated++;
133 totalTxSize += entry.GetTxSize();
134 cachedInnerUsage += entry.DynamicMemoryUsage();
135 minerPolicyEstimator->processTransaction(entry, fCurrentEstimate);
140 void CTxMemPool::addAddressIndex(const CTxMemPoolEntry &entry, const CCoinsViewCache &view)
143 const CTransaction& tx = entry.GetTx();
144 std::vector<CMempoolAddressDeltaKey> inserted;
146 uint256 txhash = tx.GetHash();
147 if (!tx.IsCoinBase())
149 for (unsigned int j = 0; j < tx.vin.size(); j++) {
150 const CTxIn input = tx.vin[j];
151 const CTxOut &prevout = view.GetOutputFor(input);
153 if (prevout.scriptPubKey.IsPayToCryptoCondition(p))
155 std::vector<CTxDestination> dests;
158 dests = p.GetDestinations();
162 dests = prevout.scriptPubKey.GetDestinations();
165 uint32_t nHeight = chainActive.Height();
166 std::map<uint160, uint32_t> heightOffsets = p.GetIndexHeightOffsets(chainActive.Height());
168 for (auto dest : dests)
170 if (dest.which() != COptCCParams::ADDRTYPE_INVALID)
172 uint160 destID = GetDestinationID(dest);
173 if (!(dest.which() == COptCCParams::ADDRTYPE_INDEX && heightOffsets.count(destID) && heightOffsets[destID] != nHeight))
175 CMempoolAddressDeltaKey key(AddressTypeFromDest(dest), destID, txhash, j, 1);
176 CMempoolAddressDelta delta(entry.GetTime(), prevout.nValue * -1, input.prevout.hash, input.prevout.n);
177 mapAddress.insert(make_pair(key, delta));
178 inserted.push_back(key);
185 CScript::ScriptType type = prevout.scriptPubKey.GetType();
186 if (type == CScript::UNKNOWN)
189 CMempoolAddressDeltaKey key(type, prevout.scriptPubKey.AddressHash(), txhash, j, 1);
190 CMempoolAddressDelta delta(entry.GetTime(), prevout.nValue * -1, input.prevout.hash, input.prevout.n);
191 mapAddress.insert(make_pair(key, delta));
192 inserted.push_back(key);
197 for (unsigned int j = 0; j < tx.vout.size(); j++) {
198 const CTxOut &out = tx.vout[j];
201 if (out.scriptPubKey.IsPayToCryptoCondition(p))
203 std::vector<CTxDestination> dests;
206 dests = p.GetDestinations();
210 dests = out.scriptPubKey.GetDestinations();
213 uint32_t nHeight = chainActive.Height();
214 std::map<uint160, uint32_t> heightOffsets = p.GetIndexHeightOffsets(nHeight);
216 for (auto dest : dests)
218 if (dest.which() != COptCCParams::ADDRTYPE_INVALID)
220 uint160 destID = GetDestinationID(dest);
221 if (!(dest.which() == COptCCParams::ADDRTYPE_INDEX && heightOffsets.count(destID) && heightOffsets[destID] != nHeight))
223 CMempoolAddressDeltaKey key(AddressTypeFromDest(dest), GetDestinationID(dest), txhash, j, 0);
224 mapAddress.insert(make_pair(key, CMempoolAddressDelta(entry.GetTime(), out.nValue)));
225 inserted.push_back(key);
232 CScript::ScriptType type = out.scriptPubKey.GetType();
233 if (type == CScript::UNKNOWN)
236 CMempoolAddressDeltaKey key(type, out.scriptPubKey.AddressHash(), txhash, j, 0);
237 mapAddress.insert(make_pair(key, CMempoolAddressDelta(entry.GetTime(), out.nValue)));
238 inserted.push_back(key);
241 mapAddressInserted.insert(make_pair(txhash, inserted));
244 bool CTxMemPool::getAddressIndex(const std::vector<std::pair<uint160, int> > &addresses, std::vector<std::pair<CMempoolAddressDeltaKey, CMempoolAddressDelta> > &results)
247 for (std::vector<std::pair<uint160, int> >::const_iterator it = addresses.begin(); it != addresses.end(); it++) {
248 auto ait = mapAddress.lower_bound(CMempoolAddressDeltaKey((*it).second, (*it).first));
249 while (ait != mapAddress.end() && (*ait).first.addressBytes == (*it).first && (*ait).first.type == (*it).second) {
250 results.push_back(*ait);
257 bool CTxMemPool::removeAddressIndex(const uint256 txhash)
260 auto it = mapAddressInserted.find(txhash);
262 if (it != mapAddressInserted.end()) {
263 std::vector<CMempoolAddressDeltaKey> keys = (*it).second;
264 for (std::vector<CMempoolAddressDeltaKey>::iterator mit = keys.begin(); mit != keys.end(); mit++) {
265 mapAddress.erase(*mit);
267 mapAddressInserted.erase(it);
273 void CTxMemPool::addSpentIndex(const CTxMemPoolEntry &entry, const CCoinsViewCache &view)
276 const CTransaction& tx = entry.GetTx();
277 uint256 txhash = tx.GetHash();
278 std::vector<CSpentIndexKey> inserted;
280 for (unsigned int j = 0; j < tx.vin.size(); j++) {
281 const CTxIn input = tx.vin[j];
282 const CTxOut &prevout = view.GetOutputFor(input);
283 CSpentIndexKey key = CSpentIndexKey(input.prevout.hash, input.prevout.n);
284 CSpentIndexValue value = CSpentIndexValue(txhash, j, -1, prevout.nValue,
285 prevout.scriptPubKey.GetType(),
286 prevout.scriptPubKey.AddressHash());
287 mapSpent.insert(make_pair(key, value));
288 inserted.push_back(key);
290 mapSpentInserted.insert(make_pair(txhash, inserted));
293 bool CTxMemPool::getSpentIndex(const CSpentIndexKey &key, CSpentIndexValue &value)
296 std::map<CSpentIndexKey, CSpentIndexValue, CSpentIndexKeyCompare>::iterator it = mapSpent.find(key);
297 if (it != mapSpent.end()) {
304 bool CTxMemPool::removeSpentIndex(const uint256 txhash)
307 auto it = mapSpentInserted.find(txhash);
309 if (it != mapSpentInserted.end()) {
310 std::vector<CSpentIndexKey> keys = (*it).second;
311 for (std::vector<CSpentIndexKey>::iterator mit = keys.begin(); mit != keys.end(); mit++) {
312 mapSpent.erase(*mit);
314 mapSpentInserted.erase(it);
320 void CTxMemPool::remove(const CTransaction &origTx, std::list<CTransaction>& removed, bool fRecursive)
322 // Remove transaction from memory pool
325 std::deque<uint256> txToRemove;
326 txToRemove.push_back(origTx.GetHash());
327 if (fRecursive && !mapTx.count(origTx.GetHash())) {
328 // If recursively removing but origTx isn't in the mempool
329 // be sure to remove any children that are in the pool. This can
330 // happen during chain re-orgs if origTx isn't re-accepted into
331 // the mempool for any reason.
332 for (unsigned int i = 0; i < origTx.vout.size(); i++) {
333 std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(COutPoint(origTx.GetHash(), i));
334 if (it == mapNextTx.end())
336 txToRemove.push_back(it->second.ptx->GetHash());
339 while (!txToRemove.empty())
341 uint256 hash = txToRemove.front();
342 txToRemove.pop_front();
343 if (!mapTx.count(hash))
345 const CTransaction& tx = mapTx.find(hash)->GetTx();
347 for (unsigned int i = 0; i < tx.vout.size(); i++) {
348 std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(COutPoint(hash, i));
349 if (it == mapNextTx.end())
351 txToRemove.push_back(it->second.ptx->GetHash());
354 mapRecentlyAddedTx.erase(hash);
355 BOOST_FOREACH(const CTxIn& txin, tx.vin)
356 mapNextTx.erase(txin.prevout);
357 BOOST_FOREACH(const JSDescription& joinsplit, tx.vJoinSplit) {
358 BOOST_FOREACH(const uint256& nf, joinsplit.nullifiers) {
359 mapSproutNullifiers.erase(nf);
362 for (const SpendDescription &spendDescription : tx.vShieldedSpend) {
363 mapSaplingNullifiers.erase(spendDescription.nullifier);
365 removed.push_back(tx);
366 totalTxSize -= mapTx.find(hash)->GetTxSize();
367 cachedInnerUsage -= mapTx.find(hash)->DynamicMemoryUsage();
369 nTransactionsUpdated++;
370 minerPolicyEstimator->removeTx(hash);
372 removeAddressIndex(hash);
374 removeSpentIndex(hash);
375 ClearPrioritisation(tx.GetHash());
380 extern uint64_t ASSETCHAINS_TIMELOCKGTE;
381 int64_t komodo_block_unlocktime(uint32_t nHeight);
383 void CTxMemPool::removeForReorg(const CCoinsViewCache *pcoins, unsigned int nMemPoolHeight, int flags)
385 // Remove transactions spending a coinbase which are now immature
386 extern char ASSETCHAINS_SYMBOL[KOMODO_ASSETCHAIN_MAXLEN];
388 if ( ASSETCHAINS_SYMBOL[0] == 0 )
389 COINBASE_MATURITY = _COINBASE_MATURITY;
391 // Remove transactions spending a coinbase which are now immature and no-longer-final transactions
393 list<CTransaction> transactionsToRemove;
394 for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
395 const CTransaction& tx = it->GetTx();
396 if (!CheckFinalTx(tx, flags)) {
397 transactionsToRemove.push_back(tx);
398 } else if (it->GetSpendsCoinbase()) {
399 BOOST_FOREACH(const CTxIn& txin, tx.vin) {
400 indexed_transaction_set::const_iterator it2 = mapTx.find(txin.prevout.hash);
401 if (it2 != mapTx.end())
403 const CCoins *coins = pcoins->AccessCoins(txin.prevout.hash);
404 if (nCheckFrequency != 0) assert(coins);
406 if (!coins || (coins->IsCoinBase() &&
407 (((signed long)nMemPoolHeight) - coins->nHeight < COINBASE_MATURITY) ||
408 ((signed long)nMemPoolHeight < komodo_block_unlocktime(coins->nHeight) &&
409 coins->IsAvailable(0) && coins->vout[0].nValue >= ASSETCHAINS_TIMELOCKGTE))) {
410 transactionsToRemove.push_back(tx);
416 BOOST_FOREACH(const CTransaction& tx, transactionsToRemove) {
417 list<CTransaction> removed;
418 remove(tx, removed, true);
423 void CTxMemPool::removeWithAnchor(const uint256 &invalidRoot, ShieldedType type)
425 // If a block is disconnected from the tip, and the root changed,
426 // we must invalidate transactions from the mempool which spend
427 // from that root -- almost as though they were spending coinbases
428 // which are no longer valid to spend due to coinbase maturity.
430 list<CTransaction> transactionsToRemove;
432 for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
433 const CTransaction& tx = it->GetTx();
436 BOOST_FOREACH(const JSDescription& joinsplit, tx.vJoinSplit) {
437 if (joinsplit.anchor == invalidRoot) {
438 transactionsToRemove.push_back(tx);
444 BOOST_FOREACH(const SpendDescription& spendDescription, tx.vShieldedSpend) {
445 if (spendDescription.anchor == invalidRoot) {
446 transactionsToRemove.push_back(tx);
452 throw runtime_error("Unknown shielded type");
457 BOOST_FOREACH(const CTransaction& tx, transactionsToRemove) {
458 list<CTransaction> removed;
459 remove(tx, removed, true);
463 bool CTxMemPool::checkNameConflicts(const CTransaction &tx, std::list<CTransaction> &conflicting)
467 // easy way to check if there are any transactions in the memory pool that define the name specified but are not the same as tx
470 // first, be sure that this is a name definition. if so, it will have both a definition and reservation output. if it is a name definition,
471 // our only concern is whether or not there is a conflicting definition in the mempool. we assume that a check for any conflicting definition
472 // in the blockchain has already taken place.
474 CNameReservation reservation;
475 for (auto output : tx.vout)
478 if (output.scriptPubKey.IsPayToCryptoCondition(p) && p.IsValid() && p.version >= p.VERSION_V3)
480 if (p.evalCode == EVAL_IDENTITY_PRIMARY && p.vData.size() > 1)
482 if (identity.IsValid())
484 identity = CIdentity();
489 identity = CIdentity(p.vData[0]);
492 else if (p.evalCode == EVAL_IDENTITY_RESERVATION && p.vData.size() > 1)
494 if (reservation.IsValid())
496 reservation = CNameReservation();
501 reservation = CNameReservation(p.vData[0]);
507 // it can't conflict if it's not a definition
508 if (!(identity.IsValid() && reservation.IsValid()))
513 std::vector<std::pair<uint160, int>> addresses = std::vector<std::pair<uint160, int>>({{identity.GetID(), CScript::P2ID}});
514 std::vector<std::pair<CMempoolAddressDeltaKey, CMempoolAddressDelta>> results;
515 if (mempool.getAddressIndex(addresses, results) && results.size())
517 std::map<uint256, std::pair<CTransaction, int>> txesAndSources; // first hash is transaction of input of prior identity or commitment output in the mempool, second pair is tx and ID output num if identity
519 uint256 txHash = tx.GetHash();
520 CNameReservation conflictingRes;
521 for (auto r : results)
523 if (r.first.txhash == txHash)
528 if (lookup(r.first.txhash, mpTx))
531 if (mpTx.vout[r.first.index].scriptPubKey.IsPayToCryptoCondition(p) &&
533 p.evalCode == EVAL_IDENTITY_RESERVATION &&
534 p.vData.size() > 1 &&
535 (conflictingRes = CNameReservation(p.vData[0])).IsValid() &&
536 CIdentity(mpTx).IsValid())
538 conflicting.push_back(mpTx);
544 return conflicting.size();
547 void CTxMemPool::removeConflicts(const CTransaction &tx, std::list<CTransaction>& removed)
551 // names are enforced as unique without requiring related spends.
552 // if this is a definition that conflicts with an existing, unrelated name definition, remove the
553 // definition that exists in the mempool
554 std::list<CTransaction> conflicting;
555 if (checkNameConflicts(tx, conflicting))
557 for (auto &remTx : conflicting)
559 remove(remTx, removed, true);
563 // Remove transactions which depend on inputs of tx, recursively
564 list<CTransaction> result;
565 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
566 std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(txin.prevout);
567 if (it != mapNextTx.end()) {
568 const CTransaction &txConflict = *it->second.ptx;
569 if (txConflict != tx)
571 remove(txConflict, removed, true);
576 BOOST_FOREACH(const JSDescription &joinsplit, tx.vJoinSplit) {
577 BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
578 std::map<uint256, const CTransaction*>::iterator it = mapSproutNullifiers.find(nf);
579 if (it != mapSproutNullifiers.end()) {
580 const CTransaction &txConflict = *it->second;
581 if (txConflict != tx) {
582 remove(txConflict, removed, true);
587 for (const SpendDescription &spendDescription : tx.vShieldedSpend) {
588 std::map<uint256, const CTransaction*>::iterator it = mapSaplingNullifiers.find(spendDescription.nullifier);
589 if (it != mapSaplingNullifiers.end()) {
590 const CTransaction &txConflict = *it->second;
591 if (txConflict != tx) {
592 remove(txConflict, removed, true);
598 int32_t komodo_validate_interest(const CTransaction &tx,int32_t txheight,uint32_t nTime,int32_t dispflag);
599 extern char ASSETCHAINS_SYMBOL[];
601 void CTxMemPool::removeExpired(unsigned int nBlockHeight)
603 CBlockIndex *tipindex;
604 // Remove expired txs and leftover coinbases from the mempool
606 list<CTransaction> transactionsToRemove;
607 for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++)
609 const CTransaction& tx = it->GetTx();
610 tipindex = chainActive.LastTip();
611 if (tx.IsCoinBase() || IsExpiredTx(tx, nBlockHeight))
613 transactionsToRemove.push_back(tx);
616 for (const CTransaction& tx : transactionsToRemove) {
617 list<CTransaction> removed;
618 remove(tx, removed, true);
619 LogPrint("mempool", "Removing expired txid: %s\n", tx.GetHash().ToString());
624 * Called when a block is connected. Removes from mempool and updates the miner fee estimator.
626 void CTxMemPool::removeForBlock(const std::vector<CTransaction>& vtx, unsigned int nBlockHeight,
627 std::list<CTransaction>& conflicts, bool fCurrentEstimate)
630 std::vector<CTxMemPoolEntry> entries;
631 BOOST_FOREACH(const CTransaction& tx, vtx)
633 uint256 hash = tx.GetHash();
635 indexed_transaction_set::iterator i = mapTx.find(hash);
636 if (i != mapTx.end())
637 entries.push_back(*i);
639 BOOST_FOREACH(const CTransaction& tx, vtx)
641 std::list<CTransaction> dummy;
642 remove(tx, dummy, false);
643 removeConflicts(tx, conflicts);
644 ClearPrioritisation(tx.GetHash());
646 // After the txs in the new block have been removed from the mempool, update policy estimates
647 minerPolicyEstimator->processBlock(nBlockHeight, entries, fCurrentEstimate);
651 * Called whenever the tip changes. Removes transactions which don't commit to
652 * the given branch ID from the mempool.
654 void CTxMemPool::removeWithoutBranchId(uint32_t nMemPoolBranchId)
657 std::list<CTransaction> transactionsToRemove;
659 for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
660 const CTransaction& tx = it->GetTx();
661 if (it->GetValidatedBranchId() != nMemPoolBranchId) {
662 transactionsToRemove.push_back(tx);
666 for (const CTransaction& tx : transactionsToRemove) {
667 std::list<CTransaction> removed;
668 remove(tx, removed, true);
672 void CTxMemPool::clear()
678 cachedInnerUsage = 0;
679 ++nTransactionsUpdated;
682 void CTxMemPool::check(const CCoinsViewCache *pcoins) const
684 if (nCheckFrequency == 0)
687 if (insecure_rand() >= nCheckFrequency)
690 LogPrint("mempool", "Checking mempool with %u transactions and %u inputs\n", (unsigned int)mapTx.size(), (unsigned int)mapNextTx.size());
692 uint64_t checkTotal = 0;
693 uint64_t innerUsage = 0;
695 CCoinsViewCache mempoolDuplicate(const_cast<CCoinsViewCache*>(pcoins));
696 const int64_t nSpendHeight = GetSpendHeight(mempoolDuplicate);
699 list<const CTxMemPoolEntry*> waitingOnDependants;
700 for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
702 checkTotal += it->GetTxSize();
703 innerUsage += it->DynamicMemoryUsage();
704 const CTransaction& tx = it->GetTx();
705 bool fDependsWait = false;
706 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
707 // Check that every mempool transaction's inputs refer to available coins, or other mempool tx's.
708 indexed_transaction_set::const_iterator it2 = mapTx.find(txin.prevout.hash);
709 if (it2 != mapTx.end()) {
710 const CTransaction& tx2 = it2->GetTx();
711 assert(tx2.vout.size() > txin.prevout.n && !tx2.vout[txin.prevout.n].IsNull());
714 const CCoins* coins = pcoins->AccessCoins(txin.prevout.hash);
715 assert(coins && coins->IsAvailable(txin.prevout.n));
717 // Check whether its inputs are marked in mapNextTx.
718 std::map<COutPoint, CInPoint>::const_iterator it3 = mapNextTx.find(txin.prevout);
719 assert(it3 != mapNextTx.end());
720 assert(it3->second.ptx == &tx);
721 assert(it3->second.n == i);
725 boost::unordered_map<uint256, SproutMerkleTree, CCoinsKeyHasher> intermediates;
727 BOOST_FOREACH(const JSDescription &joinsplit, tx.vJoinSplit) {
728 BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
729 assert(!pcoins->GetNullifier(nf, SPROUT));
732 SproutMerkleTree tree;
733 auto it = intermediates.find(joinsplit.anchor);
734 if (it != intermediates.end()) {
737 assert(pcoins->GetSproutAnchorAt(joinsplit.anchor, tree));
740 BOOST_FOREACH(const uint256& commitment, joinsplit.commitments)
742 tree.append(commitment);
745 intermediates.insert(std::make_pair(tree.root(), tree));
747 for (const SpendDescription &spendDescription : tx.vShieldedSpend) {
748 SaplingMerkleTree tree;
750 assert(pcoins->GetSaplingAnchorAt(spendDescription.anchor, tree));
751 assert(!pcoins->GetNullifier(spendDescription.nullifier, SAPLING));
754 waitingOnDependants.push_back(&(*it));
756 CValidationState state;
757 bool fCheckResult = tx.IsCoinBase() ||
758 Consensus::CheckTxInputs(tx, state, mempoolDuplicate, nSpendHeight, Params().GetConsensus());
759 assert(fCheckResult);
760 UpdateCoins(tx, mempoolDuplicate, 1000000);
763 unsigned int stepsSinceLastRemove = 0;
764 while (!waitingOnDependants.empty()) {
765 const CTxMemPoolEntry* entry = waitingOnDependants.front();
766 waitingOnDependants.pop_front();
767 CValidationState state;
768 if (!mempoolDuplicate.HaveInputs(entry->GetTx())) {
769 waitingOnDependants.push_back(entry);
770 stepsSinceLastRemove++;
771 assert(stepsSinceLastRemove < waitingOnDependants.size());
773 bool fCheckResult = entry->GetTx().IsCoinBase() ||
774 Consensus::CheckTxInputs(entry->GetTx(), state, mempoolDuplicate, nSpendHeight, Params().GetConsensus());
775 assert(fCheckResult);
776 UpdateCoins(entry->GetTx(), mempoolDuplicate, 1000000);
777 stepsSinceLastRemove = 0;
780 for (std::map<COutPoint, CInPoint>::const_iterator it = mapNextTx.begin(); it != mapNextTx.end(); it++) {
781 uint256 hash = it->second.ptx->GetHash();
782 indexed_transaction_set::const_iterator it2 = mapTx.find(hash);
783 const CTransaction& tx = it2->GetTx();
784 assert(it2 != mapTx.end());
785 assert(&tx == it->second.ptx);
786 assert(tx.vin.size() > it->second.n);
787 assert(it->first == it->second.ptx->vin[it->second.n].prevout);
790 checkNullifiers(SPROUT);
791 checkNullifiers(SAPLING);
793 assert(totalTxSize == checkTotal);
794 assert(innerUsage == cachedInnerUsage);
797 void CTxMemPool::checkNullifiers(ShieldedType type) const
799 const std::map<uint256, const CTransaction*>* mapToUse;
802 mapToUse = &mapSproutNullifiers;
805 mapToUse = &mapSaplingNullifiers;
808 throw runtime_error("Unknown nullifier type");
810 for (const auto& entry : *mapToUse) {
811 uint256 hash = entry.second->GetHash();
812 CTxMemPool::indexed_transaction_set::const_iterator findTx = mapTx.find(hash);
813 const CTransaction& tx = findTx->GetTx();
814 assert(findTx != mapTx.end());
815 assert(&tx == entry.second);
819 void CTxMemPool::queryHashes(vector<uint256>& vtxid)
824 vtxid.reserve(mapTx.size());
825 for (indexed_transaction_set::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
826 vtxid.push_back(mi->GetTx().GetHash());
829 bool CTxMemPool::lookup(uint256 hash, CTransaction& result) const
832 indexed_transaction_set::const_iterator i = mapTx.find(hash);
833 if (i == mapTx.end()) return false;
838 CFeeRate CTxMemPool::estimateFee(int nBlocks) const
841 return minerPolicyEstimator->estimateFee(nBlocks);
843 double CTxMemPool::estimatePriority(int nBlocks) const
846 return minerPolicyEstimator->estimatePriority(nBlocks);
850 CTxMemPool::WriteFeeEstimates(CAutoFile& fileout) const
854 fileout << 109900; // version required to read: 0.10.99 or later
855 fileout << CLIENT_VERSION; // version that wrote the file
856 minerPolicyEstimator->Write(fileout);
858 catch (const std::exception&) {
859 LogPrintf("CTxMemPool::WriteFeeEstimates(): unable to write policy estimator data (non-fatal)\n");
866 CTxMemPool::ReadFeeEstimates(CAutoFile& filein)
869 int nVersionRequired, nVersionThatWrote;
870 filein >> nVersionRequired >> nVersionThatWrote;
871 if (nVersionRequired > CLIENT_VERSION)
872 return error("CTxMemPool::ReadFeeEstimates(): up-version (%d) fee estimate file", nVersionRequired);
875 minerPolicyEstimator->Read(filein);
877 catch (const std::exception&) {
878 LogPrintf("CTxMemPool::ReadFeeEstimates(): unable to read policy estimator data (non-fatal)\n");
884 void CTxMemPool::PrioritiseTransaction(const uint256 &hash, const string strHash, double dPriorityDelta, const CAmount& nFeeDelta)
888 std::pair<double, CAmount> &deltas = mapDeltas[hash];
889 deltas.first += dPriorityDelta;
890 deltas.second += nFeeDelta;
894 LogPrintf("PrioritiseTransaction: %s priority += %f, fee += %d\n", strHash, dPriorityDelta, FormatMoney(nFeeDelta));
898 void CTxMemPool::ApplyDeltas(const uint256 hash, double &dPriorityDelta, CAmount &nFeeDelta)
901 std::map<uint256, std::pair<double, CAmount> >::iterator pos = mapDeltas.find(hash);
902 if (pos == mapDeltas.end())
904 const std::pair<double, CAmount> &deltas = pos->second;
905 dPriorityDelta += deltas.first;
906 nFeeDelta += deltas.second;
909 void CTxMemPool::ClearPrioritisation(const uint256 hash)
912 mapDeltas.erase(hash);
913 mapReserveTransactions.erase(hash);
916 bool CTxMemPool::PrioritiseReserveTransaction(const CReserveTransactionDescriptor &txDesc, const CCurrencyState ¤cyState)
919 uint256 hash = txDesc.ptx->GetHash();
920 auto it = mapReserveTransactions.find(hash);
921 if (txDesc.IsValid())
923 mapReserveTransactions[hash] = txDesc;
924 CAmount feeDelta = txDesc.AllFeesAsNative(currencyState);
925 PrioritiseTransaction(hash, hash.GetHex().c_str(), (double)feeDelta * 100.0, feeDelta);
931 bool CTxMemPool::IsKnownReserveTransaction(const uint256 &hash, CReserveTransactionDescriptor &txDesc)
934 auto it = mapReserveTransactions.find(hash);
935 if (it != mapReserveTransactions.end() && it->second.IsValid())
937 // refresh transaction from mempool or delete it if not found (we may not need this at all)
938 indexed_transaction_set::const_iterator i = mapTx.find(hash);
939 if (i == mapTx.end())
941 ClearPrioritisation(hash);
945 it->second.ptx = &(i->GetTx());
954 bool CTxMemPool::HasNoInputsOf(const CTransaction &tx) const
956 for (unsigned int i = 0; i < tx.vin.size(); i++)
957 if (exists(tx.vin[i].prevout.hash))
962 bool CTxMemPool::nullifierExists(const uint256& nullifier, ShieldedType type) const
966 return mapSproutNullifiers.count(nullifier);
968 return mapSaplingNullifiers.count(nullifier);
970 throw runtime_error("Unknown nullifier type");
974 void CTxMemPool::NotifyRecentlyAdded()
976 uint64_t recentlyAddedSequence;
977 std::vector<CTransaction> txs;
980 recentlyAddedSequence = nRecentlyAddedSequence;
981 for (const auto& kv : mapRecentlyAddedTx) {
982 txs.push_back(*(kv.second));
984 mapRecentlyAddedTx.clear();
987 // A race condition can occur here between these SyncWithWallets calls, and
988 // the ones triggered by block logic (in ConnectTip and DisconnectTip). It
989 // is harmless because calling SyncWithWallets(_, NULL) does not alter the
990 // wallet transaction's block information.
991 for (auto tx : txs) {
993 SyncWithWallets(tx, NULL);
994 } catch (const boost::thread_interrupted&) {
996 } catch (const std::exception& e) {
997 PrintExceptionContinue(&e, "CTxMemPool::NotifyRecentlyAdded()");
999 PrintExceptionContinue(NULL, "CTxMemPool::NotifyRecentlyAdded()");
1003 // Update the notified sequence number. We only need this in regtest mode,
1004 // and should not lock on cs after calling SyncWithWallets otherwise.
1005 if (Params().NetworkIDString() == "regtest") {
1007 nNotifiedSequence = recentlyAddedSequence;
1011 bool CTxMemPool::IsFullyNotified() {
1012 assert(Params().NetworkIDString() == "regtest");
1014 return nRecentlyAddedSequence == nNotifiedSequence;
1017 CCoinsViewMemPool::CCoinsViewMemPool(CCoinsView *baseIn, CTxMemPool &mempoolIn) : CCoinsViewBacked(baseIn), mempool(mempoolIn) { }
1019 bool CCoinsViewMemPool::GetNullifier(const uint256 &nf, ShieldedType type) const
1021 return mempool.nullifierExists(nf, type) || base->GetNullifier(nf, type);
1024 bool CCoinsViewMemPool::GetCoins(const uint256 &txid, CCoins &coins) const {
1025 // If an entry in the mempool exists, always return that one, as it's guaranteed to never
1026 // conflict with the underlying cache, and it cannot have pruned entries (as it contains full)
1027 // transactions. First checking the underlying cache risks returning a pruned entry instead.
1029 if (mempool.lookup(txid, tx)) {
1030 coins = CCoins(tx, MEMPOOL_HEIGHT);
1033 return (base->GetCoins(txid, coins) && !coins.IsPruned());
1036 bool CCoinsViewMemPool::HaveCoins(const uint256 &txid) const {
1037 return mempool.exists(txid) || base->HaveCoins(txid);
1040 size_t CTxMemPool::DynamicMemoryUsage() const {
1042 // Estimate the overhead of mapTx to be 6 pointers + an allocation, as no exact formula for boost::multi_index_contained is implemented.
1043 return memusage::MallocUsage(sizeof(CTxMemPoolEntry) + 6 * sizeof(void*)) * mapTx.size() + memusage::DynamicUsage(mapNextTx) + memusage::DynamicUsage(mapDeltas) + memusage::DynamicUsage(mapDeltas) + memusage::DynamicUsage(mapDeltas) + cachedInnerUsage;