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();
164 for (auto dest : dests)
166 if (dest.which() != COptCCParams::ADDRTYPE_INVALID)
168 CMempoolAddressDeltaKey key(AddressTypeFromDest(dest), GetDestinationID(dest), txhash, j, 1);
169 CMempoolAddressDelta delta(entry.GetTime(), prevout.nValue * -1, input.prevout.hash, input.prevout.n);
170 mapAddress.insert(make_pair(key, delta));
171 inserted.push_back(key);
177 CScript::ScriptType type = prevout.scriptPubKey.GetType();
178 if (type == CScript::UNKNOWN)
181 CMempoolAddressDeltaKey key(type, prevout.scriptPubKey.AddressHash(), txhash, j, 1);
182 CMempoolAddressDelta delta(entry.GetTime(), prevout.nValue * -1, input.prevout.hash, input.prevout.n);
183 mapAddress.insert(make_pair(key, delta));
184 inserted.push_back(key);
189 for (unsigned int j = 0; j < tx.vout.size(); j++) {
190 const CTxOut &out = tx.vout[j];
193 if (out.scriptPubKey.IsPayToCryptoCondition(p))
195 std::vector<CTxDestination> dests;
198 dests = p.GetDestinations();
202 dests = out.scriptPubKey.GetDestinations();
204 for (auto dest : dests)
206 if (dest.which() != COptCCParams::ADDRTYPE_INVALID)
208 CMempoolAddressDeltaKey key(AddressTypeFromDest(dest), GetDestinationID(dest), txhash, j, 0);
209 mapAddress.insert(make_pair(key, CMempoolAddressDelta(entry.GetTime(), out.nValue)));
210 inserted.push_back(key);
216 CScript::ScriptType type = out.scriptPubKey.GetType();
217 if (type == CScript::UNKNOWN)
220 CMempoolAddressDeltaKey key(type, out.scriptPubKey.AddressHash(), txhash, j, 0);
221 mapAddress.insert(make_pair(key, CMempoolAddressDelta(entry.GetTime(), out.nValue)));
222 inserted.push_back(key);
225 mapAddressInserted.insert(make_pair(txhash, inserted));
228 bool CTxMemPool::getAddressIndex(const std::vector<std::pair<uint160, int> > &addresses, std::vector<std::pair<CMempoolAddressDeltaKey, CMempoolAddressDelta> > &results)
231 for (std::vector<std::pair<uint160, int> >::const_iterator it = addresses.begin(); it != addresses.end(); it++) {
232 auto ait = mapAddress.lower_bound(CMempoolAddressDeltaKey((*it).second, (*it).first));
233 while (ait != mapAddress.end() && (*ait).first.addressBytes == (*it).first && (*ait).first.type == (*it).second) {
234 results.push_back(*ait);
241 bool CTxMemPool::removeAddressIndex(const uint256 txhash)
244 auto it = mapAddressInserted.find(txhash);
246 if (it != mapAddressInserted.end()) {
247 std::vector<CMempoolAddressDeltaKey> keys = (*it).second;
248 for (std::vector<CMempoolAddressDeltaKey>::iterator mit = keys.begin(); mit != keys.end(); mit++) {
249 mapAddress.erase(*mit);
251 mapAddressInserted.erase(it);
257 void CTxMemPool::addSpentIndex(const CTxMemPoolEntry &entry, const CCoinsViewCache &view)
260 const CTransaction& tx = entry.GetTx();
261 uint256 txhash = tx.GetHash();
262 std::vector<CSpentIndexKey> inserted;
264 for (unsigned int j = 0; j < tx.vin.size(); j++) {
265 const CTxIn input = tx.vin[j];
266 const CTxOut &prevout = view.GetOutputFor(input);
267 CSpentIndexKey key = CSpentIndexKey(input.prevout.hash, input.prevout.n);
268 CSpentIndexValue value = CSpentIndexValue(txhash, j, -1, prevout.nValue,
269 prevout.scriptPubKey.GetType(),
270 prevout.scriptPubKey.AddressHash());
271 mapSpent.insert(make_pair(key, value));
272 inserted.push_back(key);
274 mapSpentInserted.insert(make_pair(txhash, inserted));
277 bool CTxMemPool::getSpentIndex(const CSpentIndexKey &key, CSpentIndexValue &value)
280 std::map<CSpentIndexKey, CSpentIndexValue, CSpentIndexKeyCompare>::iterator it = mapSpent.find(key);
281 if (it != mapSpent.end()) {
288 bool CTxMemPool::removeSpentIndex(const uint256 txhash)
291 auto it = mapSpentInserted.find(txhash);
293 if (it != mapSpentInserted.end()) {
294 std::vector<CSpentIndexKey> keys = (*it).second;
295 for (std::vector<CSpentIndexKey>::iterator mit = keys.begin(); mit != keys.end(); mit++) {
296 mapSpent.erase(*mit);
298 mapSpentInserted.erase(it);
304 void CTxMemPool::remove(const CTransaction &origTx, std::list<CTransaction>& removed, bool fRecursive)
306 // Remove transaction from memory pool
309 std::deque<uint256> txToRemove;
310 txToRemove.push_back(origTx.GetHash());
311 if (fRecursive && !mapTx.count(origTx.GetHash())) {
312 // If recursively removing but origTx isn't in the mempool
313 // be sure to remove any children that are in the pool. This can
314 // happen during chain re-orgs if origTx isn't re-accepted into
315 // the mempool for any reason.
316 for (unsigned int i = 0; i < origTx.vout.size(); i++) {
317 std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(COutPoint(origTx.GetHash(), i));
318 if (it == mapNextTx.end())
320 txToRemove.push_back(it->second.ptx->GetHash());
323 while (!txToRemove.empty())
325 uint256 hash = txToRemove.front();
326 txToRemove.pop_front();
327 if (!mapTx.count(hash))
329 const CTransaction& tx = mapTx.find(hash)->GetTx();
331 for (unsigned int i = 0; i < tx.vout.size(); i++) {
332 std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(COutPoint(hash, i));
333 if (it == mapNextTx.end())
335 txToRemove.push_back(it->second.ptx->GetHash());
338 mapRecentlyAddedTx.erase(hash);
339 BOOST_FOREACH(const CTxIn& txin, tx.vin)
340 mapNextTx.erase(txin.prevout);
341 BOOST_FOREACH(const JSDescription& joinsplit, tx.vJoinSplit) {
342 BOOST_FOREACH(const uint256& nf, joinsplit.nullifiers) {
343 mapSproutNullifiers.erase(nf);
346 for (const SpendDescription &spendDescription : tx.vShieldedSpend) {
347 mapSaplingNullifiers.erase(spendDescription.nullifier);
349 removed.push_back(tx);
350 totalTxSize -= mapTx.find(hash)->GetTxSize();
351 cachedInnerUsage -= mapTx.find(hash)->DynamicMemoryUsage();
353 nTransactionsUpdated++;
354 minerPolicyEstimator->removeTx(hash);
356 removeAddressIndex(hash);
358 removeSpentIndex(hash);
359 ClearPrioritisation(tx.GetHash());
364 extern uint64_t ASSETCHAINS_TIMELOCKGTE;
365 int64_t komodo_block_unlocktime(uint32_t nHeight);
367 void CTxMemPool::removeForReorg(const CCoinsViewCache *pcoins, unsigned int nMemPoolHeight, int flags)
369 // Remove transactions spending a coinbase which are now immature
370 extern char ASSETCHAINS_SYMBOL[KOMODO_ASSETCHAIN_MAXLEN];
372 if ( ASSETCHAINS_SYMBOL[0] == 0 )
373 COINBASE_MATURITY = _COINBASE_MATURITY;
375 // Remove transactions spending a coinbase which are now immature and no-longer-final transactions
377 list<CTransaction> transactionsToRemove;
378 for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
379 const CTransaction& tx = it->GetTx();
380 if (!CheckFinalTx(tx, flags)) {
381 transactionsToRemove.push_back(tx);
382 } else if (it->GetSpendsCoinbase()) {
383 BOOST_FOREACH(const CTxIn& txin, tx.vin) {
384 indexed_transaction_set::const_iterator it2 = mapTx.find(txin.prevout.hash);
385 if (it2 != mapTx.end())
387 const CCoins *coins = pcoins->AccessCoins(txin.prevout.hash);
388 if (nCheckFrequency != 0) assert(coins);
390 if (!coins || (coins->IsCoinBase() &&
391 (((signed long)nMemPoolHeight) - coins->nHeight < COINBASE_MATURITY) ||
392 ((signed long)nMemPoolHeight < komodo_block_unlocktime(coins->nHeight) &&
393 coins->IsAvailable(0) && coins->vout[0].nValue >= ASSETCHAINS_TIMELOCKGTE))) {
394 transactionsToRemove.push_back(tx);
400 BOOST_FOREACH(const CTransaction& tx, transactionsToRemove) {
401 list<CTransaction> removed;
402 remove(tx, removed, true);
407 void CTxMemPool::removeWithAnchor(const uint256 &invalidRoot, ShieldedType type)
409 // If a block is disconnected from the tip, and the root changed,
410 // we must invalidate transactions from the mempool which spend
411 // from that root -- almost as though they were spending coinbases
412 // which are no longer valid to spend due to coinbase maturity.
414 list<CTransaction> transactionsToRemove;
416 for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
417 const CTransaction& tx = it->GetTx();
420 BOOST_FOREACH(const JSDescription& joinsplit, tx.vJoinSplit) {
421 if (joinsplit.anchor == invalidRoot) {
422 transactionsToRemove.push_back(tx);
428 BOOST_FOREACH(const SpendDescription& spendDescription, tx.vShieldedSpend) {
429 if (spendDescription.anchor == invalidRoot) {
430 transactionsToRemove.push_back(tx);
436 throw runtime_error("Unknown shielded type");
441 BOOST_FOREACH(const CTransaction& tx, transactionsToRemove) {
442 list<CTransaction> removed;
443 remove(tx, removed, true);
447 bool CTxMemPool::checkNameConflicts(const CTransaction &tx, std::list<CTransaction> &conflicting)
451 // 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
454 // 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,
455 // our only concern is whether or not there is a conflicting definition in the mempool. we assume that a check for any conflicting definition
456 // in the blockchain has already taken place.
458 CNameReservation reservation;
459 for (auto output : tx.vout)
462 if (output.scriptPubKey.IsPayToCryptoCondition(p) && p.IsValid() && p.version >= p.VERSION_V3)
464 if (p.evalCode == EVAL_IDENTITY_PRIMARY && p.vData.size() > 1)
466 if (identity.IsValid())
468 identity = CIdentity();
473 identity = CIdentity(p.vData[0]);
476 else if (p.evalCode == EVAL_IDENTITY_RESERVATION && p.vData.size() > 1)
478 if (reservation.IsValid())
480 reservation = CNameReservation();
485 reservation = CNameReservation(p.vData[0]);
491 // it can't conflict if it's not a definition
492 if (!(identity.IsValid() && reservation.IsValid()))
497 std::vector<std::pair<uint160, int>> addresses = std::vector<std::pair<uint160, int>>({{identity.GetID(), CScript::P2ID}});
498 std::vector<std::pair<CMempoolAddressDeltaKey, CMempoolAddressDelta>> results;
499 if (mempool.getAddressIndex(addresses, results) && results.size())
501 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
503 uint256 txHash = tx.GetHash();
504 CNameReservation conflictingRes;
505 for (auto r : results)
507 if (r.first.txhash == txHash)
512 if (lookup(r.first.txhash, mpTx))
515 if (mpTx.vout[r.first.index].scriptPubKey.IsPayToCryptoCondition(p) &&
517 p.evalCode == EVAL_IDENTITY_RESERVATION &&
518 p.vData.size() > 1 &&
519 (conflictingRes = CNameReservation(p.vData[0])).IsValid() &&
520 CIdentity(mpTx).IsValid())
522 conflicting.push_back(mpTx);
528 return conflicting.size();
531 void CTxMemPool::removeConflicts(const CTransaction &tx, std::list<CTransaction>& removed)
535 // names are enforced as unique without requiring related spends.
536 // if this is a definition that conflicts with an existing, unrelated name definition, remove the
537 // definition that exists in the mempool
538 std::list<CTransaction> conflicting;
539 if (checkNameConflicts(tx, conflicting))
541 for (auto &remTx : conflicting)
543 remove(remTx, removed, true);
547 // Remove transactions which depend on inputs of tx, recursively
548 list<CTransaction> result;
549 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
550 std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(txin.prevout);
551 if (it != mapNextTx.end()) {
552 const CTransaction &txConflict = *it->second.ptx;
553 if (txConflict != tx)
555 remove(txConflict, removed, true);
560 BOOST_FOREACH(const JSDescription &joinsplit, tx.vJoinSplit) {
561 BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
562 std::map<uint256, const CTransaction*>::iterator it = mapSproutNullifiers.find(nf);
563 if (it != mapSproutNullifiers.end()) {
564 const CTransaction &txConflict = *it->second;
565 if (txConflict != tx) {
566 remove(txConflict, removed, true);
571 for (const SpendDescription &spendDescription : tx.vShieldedSpend) {
572 std::map<uint256, const CTransaction*>::iterator it = mapSaplingNullifiers.find(spendDescription.nullifier);
573 if (it != mapSaplingNullifiers.end()) {
574 const CTransaction &txConflict = *it->second;
575 if (txConflict != tx) {
576 remove(txConflict, removed, true);
582 int32_t komodo_validate_interest(const CTransaction &tx,int32_t txheight,uint32_t nTime,int32_t dispflag);
583 extern char ASSETCHAINS_SYMBOL[];
585 void CTxMemPool::removeExpired(unsigned int nBlockHeight)
587 CBlockIndex *tipindex;
588 // Remove expired txs and leftover coinbases from the mempool
590 list<CTransaction> transactionsToRemove;
591 for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++)
593 const CTransaction& tx = it->GetTx();
594 tipindex = chainActive.LastTip();
595 if (tx.IsCoinBase() || IsExpiredTx(tx, nBlockHeight))
597 transactionsToRemove.push_back(tx);
600 for (const CTransaction& tx : transactionsToRemove) {
601 list<CTransaction> removed;
602 remove(tx, removed, true);
603 LogPrint("mempool", "Removing expired txid: %s\n", tx.GetHash().ToString());
608 * Called when a block is connected. Removes from mempool and updates the miner fee estimator.
610 void CTxMemPool::removeForBlock(const std::vector<CTransaction>& vtx, unsigned int nBlockHeight,
611 std::list<CTransaction>& conflicts, bool fCurrentEstimate)
614 std::vector<CTxMemPoolEntry> entries;
615 BOOST_FOREACH(const CTransaction& tx, vtx)
617 uint256 hash = tx.GetHash();
619 indexed_transaction_set::iterator i = mapTx.find(hash);
620 if (i != mapTx.end())
621 entries.push_back(*i);
623 BOOST_FOREACH(const CTransaction& tx, vtx)
625 std::list<CTransaction> dummy;
626 remove(tx, dummy, false);
627 removeConflicts(tx, conflicts);
628 ClearPrioritisation(tx.GetHash());
630 // After the txs in the new block have been removed from the mempool, update policy estimates
631 minerPolicyEstimator->processBlock(nBlockHeight, entries, fCurrentEstimate);
635 * Called whenever the tip changes. Removes transactions which don't commit to
636 * the given branch ID from the mempool.
638 void CTxMemPool::removeWithoutBranchId(uint32_t nMemPoolBranchId)
641 std::list<CTransaction> transactionsToRemove;
643 for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
644 const CTransaction& tx = it->GetTx();
645 if (it->GetValidatedBranchId() != nMemPoolBranchId) {
646 transactionsToRemove.push_back(tx);
650 for (const CTransaction& tx : transactionsToRemove) {
651 std::list<CTransaction> removed;
652 remove(tx, removed, true);
656 void CTxMemPool::clear()
662 cachedInnerUsage = 0;
663 ++nTransactionsUpdated;
666 void CTxMemPool::check(const CCoinsViewCache *pcoins) const
668 if (nCheckFrequency == 0)
671 if (insecure_rand() >= nCheckFrequency)
674 LogPrint("mempool", "Checking mempool with %u transactions and %u inputs\n", (unsigned int)mapTx.size(), (unsigned int)mapNextTx.size());
676 uint64_t checkTotal = 0;
677 uint64_t innerUsage = 0;
679 CCoinsViewCache mempoolDuplicate(const_cast<CCoinsViewCache*>(pcoins));
680 const int64_t nSpendHeight = GetSpendHeight(mempoolDuplicate);
683 list<const CTxMemPoolEntry*> waitingOnDependants;
684 for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
686 checkTotal += it->GetTxSize();
687 innerUsage += it->DynamicMemoryUsage();
688 const CTransaction& tx = it->GetTx();
689 bool fDependsWait = false;
690 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
691 // Check that every mempool transaction's inputs refer to available coins, or other mempool tx's.
692 indexed_transaction_set::const_iterator it2 = mapTx.find(txin.prevout.hash);
693 if (it2 != mapTx.end()) {
694 const CTransaction& tx2 = it2->GetTx();
695 assert(tx2.vout.size() > txin.prevout.n && !tx2.vout[txin.prevout.n].IsNull());
698 const CCoins* coins = pcoins->AccessCoins(txin.prevout.hash);
699 assert(coins && coins->IsAvailable(txin.prevout.n));
701 // Check whether its inputs are marked in mapNextTx.
702 std::map<COutPoint, CInPoint>::const_iterator it3 = mapNextTx.find(txin.prevout);
703 assert(it3 != mapNextTx.end());
704 assert(it3->second.ptx == &tx);
705 assert(it3->second.n == i);
709 boost::unordered_map<uint256, SproutMerkleTree, CCoinsKeyHasher> intermediates;
711 BOOST_FOREACH(const JSDescription &joinsplit, tx.vJoinSplit) {
712 BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
713 assert(!pcoins->GetNullifier(nf, SPROUT));
716 SproutMerkleTree tree;
717 auto it = intermediates.find(joinsplit.anchor);
718 if (it != intermediates.end()) {
721 assert(pcoins->GetSproutAnchorAt(joinsplit.anchor, tree));
724 BOOST_FOREACH(const uint256& commitment, joinsplit.commitments)
726 tree.append(commitment);
729 intermediates.insert(std::make_pair(tree.root(), tree));
731 for (const SpendDescription &spendDescription : tx.vShieldedSpend) {
732 SaplingMerkleTree tree;
734 assert(pcoins->GetSaplingAnchorAt(spendDescription.anchor, tree));
735 assert(!pcoins->GetNullifier(spendDescription.nullifier, SAPLING));
738 waitingOnDependants.push_back(&(*it));
740 CValidationState state;
741 bool fCheckResult = tx.IsCoinBase() ||
742 Consensus::CheckTxInputs(tx, state, mempoolDuplicate, nSpendHeight, Params().GetConsensus());
743 assert(fCheckResult);
744 UpdateCoins(tx, mempoolDuplicate, 1000000);
747 unsigned int stepsSinceLastRemove = 0;
748 while (!waitingOnDependants.empty()) {
749 const CTxMemPoolEntry* entry = waitingOnDependants.front();
750 waitingOnDependants.pop_front();
751 CValidationState state;
752 if (!mempoolDuplicate.HaveInputs(entry->GetTx())) {
753 waitingOnDependants.push_back(entry);
754 stepsSinceLastRemove++;
755 assert(stepsSinceLastRemove < waitingOnDependants.size());
757 bool fCheckResult = entry->GetTx().IsCoinBase() ||
758 Consensus::CheckTxInputs(entry->GetTx(), state, mempoolDuplicate, nSpendHeight, Params().GetConsensus());
759 assert(fCheckResult);
760 UpdateCoins(entry->GetTx(), mempoolDuplicate, 1000000);
761 stepsSinceLastRemove = 0;
764 for (std::map<COutPoint, CInPoint>::const_iterator it = mapNextTx.begin(); it != mapNextTx.end(); it++) {
765 uint256 hash = it->second.ptx->GetHash();
766 indexed_transaction_set::const_iterator it2 = mapTx.find(hash);
767 const CTransaction& tx = it2->GetTx();
768 assert(it2 != mapTx.end());
769 assert(&tx == it->second.ptx);
770 assert(tx.vin.size() > it->second.n);
771 assert(it->first == it->second.ptx->vin[it->second.n].prevout);
774 checkNullifiers(SPROUT);
775 checkNullifiers(SAPLING);
777 assert(totalTxSize == checkTotal);
778 assert(innerUsage == cachedInnerUsage);
781 void CTxMemPool::checkNullifiers(ShieldedType type) const
783 const std::map<uint256, const CTransaction*>* mapToUse;
786 mapToUse = &mapSproutNullifiers;
789 mapToUse = &mapSaplingNullifiers;
792 throw runtime_error("Unknown nullifier type");
794 for (const auto& entry : *mapToUse) {
795 uint256 hash = entry.second->GetHash();
796 CTxMemPool::indexed_transaction_set::const_iterator findTx = mapTx.find(hash);
797 const CTransaction& tx = findTx->GetTx();
798 assert(findTx != mapTx.end());
799 assert(&tx == entry.second);
803 void CTxMemPool::queryHashes(vector<uint256>& vtxid)
808 vtxid.reserve(mapTx.size());
809 for (indexed_transaction_set::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
810 vtxid.push_back(mi->GetTx().GetHash());
813 bool CTxMemPool::lookup(uint256 hash, CTransaction& result) const
816 indexed_transaction_set::const_iterator i = mapTx.find(hash);
817 if (i == mapTx.end()) return false;
822 CFeeRate CTxMemPool::estimateFee(int nBlocks) const
825 return minerPolicyEstimator->estimateFee(nBlocks);
827 double CTxMemPool::estimatePriority(int nBlocks) const
830 return minerPolicyEstimator->estimatePriority(nBlocks);
834 CTxMemPool::WriteFeeEstimates(CAutoFile& fileout) const
838 fileout << 109900; // version required to read: 0.10.99 or later
839 fileout << CLIENT_VERSION; // version that wrote the file
840 minerPolicyEstimator->Write(fileout);
842 catch (const std::exception&) {
843 LogPrintf("CTxMemPool::WriteFeeEstimates(): unable to write policy estimator data (non-fatal)\n");
850 CTxMemPool::ReadFeeEstimates(CAutoFile& filein)
853 int nVersionRequired, nVersionThatWrote;
854 filein >> nVersionRequired >> nVersionThatWrote;
855 if (nVersionRequired > CLIENT_VERSION)
856 return error("CTxMemPool::ReadFeeEstimates(): up-version (%d) fee estimate file", nVersionRequired);
859 minerPolicyEstimator->Read(filein);
861 catch (const std::exception&) {
862 LogPrintf("CTxMemPool::ReadFeeEstimates(): unable to read policy estimator data (non-fatal)\n");
868 void CTxMemPool::PrioritiseTransaction(const uint256 &hash, const string strHash, double dPriorityDelta, const CAmount& nFeeDelta)
872 std::pair<double, CAmount> &deltas = mapDeltas[hash];
873 deltas.first += dPriorityDelta;
874 deltas.second += nFeeDelta;
878 LogPrintf("PrioritiseTransaction: %s priority += %f, fee += %d\n", strHash, dPriorityDelta, FormatMoney(nFeeDelta));
882 void CTxMemPool::ApplyDeltas(const uint256 hash, double &dPriorityDelta, CAmount &nFeeDelta)
885 std::map<uint256, std::pair<double, CAmount> >::iterator pos = mapDeltas.find(hash);
886 if (pos == mapDeltas.end())
888 const std::pair<double, CAmount> &deltas = pos->second;
889 dPriorityDelta += deltas.first;
890 nFeeDelta += deltas.second;
893 void CTxMemPool::ClearPrioritisation(const uint256 hash)
896 mapDeltas.erase(hash);
897 mapReserveTransactions.erase(hash);
900 bool CTxMemPool::PrioritiseReserveTransaction(const CReserveTransactionDescriptor &txDesc, const CCurrencyState ¤cyState)
903 uint256 hash = txDesc.ptx->GetHash();
904 auto it = mapReserveTransactions.find(hash);
905 if (txDesc.IsValid())
907 mapReserveTransactions[hash] = txDesc;
908 CAmount feeDelta = txDesc.AllFeesAsNative(currencyState);
909 PrioritiseTransaction(hash, hash.GetHex().c_str(), (double)feeDelta * 100.0, feeDelta);
915 bool CTxMemPool::IsKnownReserveTransaction(const uint256 &hash, CReserveTransactionDescriptor &txDesc)
918 auto it = mapReserveTransactions.find(hash);
919 if (it != mapReserveTransactions.end() && it->second.IsValid())
921 // refresh transaction from mempool or delete it if not found (we may not need this at all)
922 indexed_transaction_set::const_iterator i = mapTx.find(hash);
923 if (i == mapTx.end())
925 ClearPrioritisation(hash);
929 it->second.ptx = &(i->GetTx());
938 bool CTxMemPool::HasNoInputsOf(const CTransaction &tx) const
940 for (unsigned int i = 0; i < tx.vin.size(); i++)
941 if (exists(tx.vin[i].prevout.hash))
946 bool CTxMemPool::nullifierExists(const uint256& nullifier, ShieldedType type) const
950 return mapSproutNullifiers.count(nullifier);
952 return mapSaplingNullifiers.count(nullifier);
954 throw runtime_error("Unknown nullifier type");
958 void CTxMemPool::NotifyRecentlyAdded()
960 uint64_t recentlyAddedSequence;
961 std::vector<CTransaction> txs;
964 recentlyAddedSequence = nRecentlyAddedSequence;
965 for (const auto& kv : mapRecentlyAddedTx) {
966 txs.push_back(*(kv.second));
968 mapRecentlyAddedTx.clear();
971 // A race condition can occur here between these SyncWithWallets calls, and
972 // the ones triggered by block logic (in ConnectTip and DisconnectTip). It
973 // is harmless because calling SyncWithWallets(_, NULL) does not alter the
974 // wallet transaction's block information.
975 for (auto tx : txs) {
977 SyncWithWallets(tx, NULL);
978 } catch (const boost::thread_interrupted&) {
980 } catch (const std::exception& e) {
981 PrintExceptionContinue(&e, "CTxMemPool::NotifyRecentlyAdded()");
983 PrintExceptionContinue(NULL, "CTxMemPool::NotifyRecentlyAdded()");
987 // Update the notified sequence number. We only need this in regtest mode,
988 // and should not lock on cs after calling SyncWithWallets otherwise.
989 if (Params().NetworkIDString() == "regtest") {
991 nNotifiedSequence = recentlyAddedSequence;
995 bool CTxMemPool::IsFullyNotified() {
996 assert(Params().NetworkIDString() == "regtest");
998 return nRecentlyAddedSequence == nNotifiedSequence;
1001 CCoinsViewMemPool::CCoinsViewMemPool(CCoinsView *baseIn, CTxMemPool &mempoolIn) : CCoinsViewBacked(baseIn), mempool(mempoolIn) { }
1003 bool CCoinsViewMemPool::GetNullifier(const uint256 &nf, ShieldedType type) const
1005 return mempool.nullifierExists(nf, type) || base->GetNullifier(nf, type);
1008 bool CCoinsViewMemPool::GetCoins(const uint256 &txid, CCoins &coins) const {
1009 // If an entry in the mempool exists, always return that one, as it's guaranteed to never
1010 // conflict with the underlying cache, and it cannot have pruned entries (as it contains full)
1011 // transactions. First checking the underlying cache risks returning a pruned entry instead.
1013 if (mempool.lookup(txid, tx)) {
1014 coins = CCoins(tx, MEMPOOL_HEIGHT);
1017 return (base->GetCoins(txid, coins) && !coins.IsPruned());
1020 bool CCoinsViewMemPool::HaveCoins(const uint256 &txid) const {
1021 return mempool.exists(txid) || base->HaveCoins(txid);
1024 size_t CTxMemPool::DynamicMemoryUsage() const {
1026 // Estimate the overhead of mapTx to be 6 pointers + an allocation, as no exact formula for boost::multi_index_contained is implemented.
1027 return memusage::MallocUsage(sizeof(CTxMemPoolEntry) + 6 * sizeof(void*)) * mapTx.size() + memusage::DynamicUsage(mapNextTx) + memusage::DynamicUsage(mapDeltas) + memusage::DynamicUsage(mapDeltas) + memusage::DynamicUsage(mapDeltas) + cachedInnerUsage;