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 "pbaas/pbaas.h"
20 #define _COINBASE_MATURITY 100
24 CTxMemPoolEntry::CTxMemPoolEntry():
25 nFee(0), nTxSize(0), nModSize(0), nUsageSize(0), nTime(0), dPriority(0.0),
26 hadNoDependencies(false), spendsCoinbase(false), hasReserve(false)
28 nHeight = MEMPOOL_HEIGHT;
31 CTxMemPoolEntry::CTxMemPoolEntry(const CTransaction& _tx, const CAmount& _nFee,
32 int64_t _nTime, double _dPriority,
33 unsigned int _nHeight, bool poolHasNoInputsOf,
34 bool _spendsCoinbase, uint32_t _nBranchId, bool hasreserve):
35 tx(_tx), nFee(_nFee), nTime(_nTime), dPriority(_dPriority), nHeight(_nHeight),
36 hadNoDependencies(poolHasNoInputsOf), hasReserve(hasreserve),
37 spendsCoinbase(_spendsCoinbase), nBranchId(_nBranchId)
39 nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
40 nModSize = tx.CalculateModifiedSize(nTxSize);
41 nUsageSize = RecursiveDynamicUsage(tx);
42 feeRate = CFeeRate(nFee, nTxSize);
45 CTxMemPoolEntry::CTxMemPoolEntry(const CTxMemPoolEntry& other)
51 CTxMemPoolEntry::GetPriority(unsigned int currentHeight) const
53 CAmount nValueIn = tx.GetValueOut()+nFee;
54 CCurrencyState currencyState;
55 unsigned int lastHeight = currentHeight < 1 ? 0 : currentHeight - 1;
56 if (hasReserve && (currencyState = ConnectedChains.GetCurrencyState(currentHeight - 1)).IsValid())
58 nValueIn += currencyState.ReserveToNative(tx.GetReserveValueOut());
60 double deltaPriority = ((double)(currentHeight-nHeight)*nValueIn)/nModSize;
61 double dResult = dPriority + deltaPriority;
65 CTxMemPool::CTxMemPool(const CFeeRate& _minRelayFee) :
66 nTransactionsUpdated(0)
68 // Sanity checks off by default for performance, because otherwise
69 // accepting transactions becomes O(N^2) where N is the number
70 // of transactions in the pool
73 minerPolicyEstimator = new CBlockPolicyEstimator(_minRelayFee);
76 CTxMemPool::~CTxMemPool()
78 delete minerPolicyEstimator;
81 void CTxMemPool::pruneSpent(const uint256 &hashTx, CCoins &coins)
85 std::map<COutPoint, CInPoint>::iterator it = mapNextTx.lower_bound(COutPoint(hashTx, 0));
87 // iterate over all COutPoints in mapNextTx whose hash equals the provided hashTx
88 while (it != mapNextTx.end() && it->first.hash == hashTx) {
89 coins.Spend(it->first.n); // and remove those outputs from coins
94 unsigned int CTxMemPool::GetTransactionsUpdated() const
97 return nTransactionsUpdated;
100 void CTxMemPool::AddTransactionsUpdated(unsigned int n)
103 nTransactionsUpdated += n;
107 bool CTxMemPool::addUnchecked(const uint256& hash, const CTxMemPoolEntry &entry, bool fCurrentEstimate)
109 // Add to memory pool without checking anything.
110 // Used by main.cpp AcceptToMemoryPool(), which DOES do
111 // all the appropriate checks.
114 const CTransaction& tx = mapTx.find(hash)->GetTx();
115 mapRecentlyAddedTx[tx.GetHash()] = &tx;
116 nRecentlyAddedSequence += 1;
117 if (!tx.IsCoinImport()) {
118 for (unsigned int i = 0; i < tx.vin.size(); i++)
119 mapNextTx[tx.vin[i].prevout] = CInPoint(&tx, i);
121 BOOST_FOREACH(const JSDescription &joinsplit, tx.vJoinSplit) {
122 BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
123 mapSproutNullifiers[nf] = &tx;
126 for (const SpendDescription &spendDescription : tx.vShieldedSpend) {
127 mapSaplingNullifiers[spendDescription.nullifier] = &tx;
129 nTransactionsUpdated++;
130 totalTxSize += entry.GetTxSize();
131 cachedInnerUsage += entry.DynamicMemoryUsage();
132 minerPolicyEstimator->processTransaction(entry, fCurrentEstimate);
137 void CTxMemPool::addAddressIndex(const CTxMemPoolEntry &entry, const CCoinsViewCache &view)
140 const CTransaction& tx = entry.GetTx();
141 std::vector<CMempoolAddressDeltaKey> inserted;
143 uint256 txhash = tx.GetHash();
144 if (!tx.IsCoinBase())
146 for (unsigned int j = 0; j < tx.vin.size(); j++) {
147 const CTxIn input = tx.vin[j];
148 const CTxOut &prevout = view.GetOutputFor(input);
149 CScript::ScriptType type = prevout.scriptPubKey.GetType();
150 if (type == CScript::UNKNOWN)
152 CMempoolAddressDeltaKey key(type, prevout.scriptPubKey.AddressHash(), txhash, j, 1);
153 CMempoolAddressDelta delta(entry.GetTime(), prevout.nValue * -1, input.prevout.hash, input.prevout.n);
154 mapAddress.insert(make_pair(key, delta));
155 inserted.push_back(key);
159 for (unsigned int j = 0; j < tx.vout.size(); j++) {
160 const CTxOut &out = tx.vout[j];
161 CScript::ScriptType type = out.scriptPubKey.GetType();
162 if (type == CScript::UNKNOWN)
164 CMempoolAddressDeltaKey key(type, out.scriptPubKey.AddressHash(), txhash, j, 0);
165 mapAddress.insert(make_pair(key, CMempoolAddressDelta(entry.GetTime(), out.nValue)));
166 inserted.push_back(key);
169 mapAddressInserted.insert(make_pair(txhash, inserted));
172 bool CTxMemPool::getAddressIndex(const std::vector<std::pair<uint160, int> > &addresses, std::vector<std::pair<CMempoolAddressDeltaKey, CMempoolAddressDelta> > &results)
175 for (std::vector<std::pair<uint160, int> >::const_iterator it = addresses.begin(); it != addresses.end(); it++) {
176 auto ait = mapAddress.lower_bound(CMempoolAddressDeltaKey((*it).second, (*it).first));
177 while (ait != mapAddress.end() && (*ait).first.addressBytes == (*it).first && (*ait).first.type == (*it).second) {
178 results.push_back(*ait);
185 bool CTxMemPool::removeAddressIndex(const uint256 txhash)
188 auto it = mapAddressInserted.find(txhash);
190 if (it != mapAddressInserted.end()) {
191 std::vector<CMempoolAddressDeltaKey> keys = (*it).second;
192 for (std::vector<CMempoolAddressDeltaKey>::iterator mit = keys.begin(); mit != keys.end(); mit++) {
193 mapAddress.erase(*mit);
195 mapAddressInserted.erase(it);
201 void CTxMemPool::addSpentIndex(const CTxMemPoolEntry &entry, const CCoinsViewCache &view)
204 const CTransaction& tx = entry.GetTx();
205 uint256 txhash = tx.GetHash();
206 std::vector<CSpentIndexKey> inserted;
208 for (unsigned int j = 0; j < tx.vin.size(); j++) {
209 const CTxIn input = tx.vin[j];
210 const CTxOut &prevout = view.GetOutputFor(input);
211 CSpentIndexKey key = CSpentIndexKey(input.prevout.hash, input.prevout.n);
212 CSpentIndexValue value = CSpentIndexValue(txhash, j, -1, prevout.nValue,
213 prevout.scriptPubKey.GetType(),
214 prevout.scriptPubKey.AddressHash());
215 mapSpent.insert(make_pair(key, value));
216 inserted.push_back(key);
218 mapSpentInserted.insert(make_pair(txhash, inserted));
221 bool CTxMemPool::getSpentIndex(const CSpentIndexKey &key, CSpentIndexValue &value)
224 std::map<CSpentIndexKey, CSpentIndexValue, CSpentIndexKeyCompare>::iterator it = mapSpent.find(key);
225 if (it != mapSpent.end()) {
232 bool CTxMemPool::removeSpentIndex(const uint256 txhash)
235 auto it = mapSpentInserted.find(txhash);
237 if (it != mapSpentInserted.end()) {
238 std::vector<CSpentIndexKey> keys = (*it).second;
239 for (std::vector<CSpentIndexKey>::iterator mit = keys.begin(); mit != keys.end(); mit++) {
240 mapSpent.erase(*mit);
242 mapSpentInserted.erase(it);
248 void CTxMemPool::remove(const CTransaction &origTx, std::list<CTransaction>& removed, bool fRecursive)
250 // Remove transaction from memory pool
253 std::deque<uint256> txToRemove;
254 txToRemove.push_back(origTx.GetHash());
255 if (fRecursive && !mapTx.count(origTx.GetHash())) {
256 // If recursively removing but origTx isn't in the mempool
257 // be sure to remove any children that are in the pool. This can
258 // happen during chain re-orgs if origTx isn't re-accepted into
259 // the mempool for any reason.
260 for (unsigned int i = 0; i < origTx.vout.size(); i++) {
261 std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(COutPoint(origTx.GetHash(), i));
262 if (it == mapNextTx.end())
264 txToRemove.push_back(it->second.ptx->GetHash());
267 while (!txToRemove.empty())
269 uint256 hash = txToRemove.front();
270 txToRemove.pop_front();
271 if (!mapTx.count(hash))
273 const CTransaction& tx = mapTx.find(hash)->GetTx();
275 for (unsigned int i = 0; i < tx.vout.size(); i++) {
276 std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(COutPoint(hash, i));
277 if (it == mapNextTx.end())
279 txToRemove.push_back(it->second.ptx->GetHash());
282 mapRecentlyAddedTx.erase(hash);
283 BOOST_FOREACH(const CTxIn& txin, tx.vin)
284 mapNextTx.erase(txin.prevout);
285 BOOST_FOREACH(const JSDescription& joinsplit, tx.vJoinSplit) {
286 BOOST_FOREACH(const uint256& nf, joinsplit.nullifiers) {
287 mapSproutNullifiers.erase(nf);
290 for (const SpendDescription &spendDescription : tx.vShieldedSpend) {
291 mapSaplingNullifiers.erase(spendDescription.nullifier);
293 removed.push_back(tx);
294 totalTxSize -= mapTx.find(hash)->GetTxSize();
295 cachedInnerUsage -= mapTx.find(hash)->DynamicMemoryUsage();
297 nTransactionsUpdated++;
298 minerPolicyEstimator->removeTx(hash);
300 removeAddressIndex(hash);
302 removeSpentIndex(hash);
303 ClearPrioritisation(tx.GetHash());
308 extern uint64_t ASSETCHAINS_TIMELOCKGTE;
309 int64_t komodo_block_unlocktime(uint32_t nHeight);
311 void CTxMemPool::removeForReorg(const CCoinsViewCache *pcoins, unsigned int nMemPoolHeight, int flags)
313 // Remove transactions spending a coinbase which are now immature
314 extern char ASSETCHAINS_SYMBOL[KOMODO_ASSETCHAIN_MAXLEN];
316 if ( ASSETCHAINS_SYMBOL[0] == 0 )
317 COINBASE_MATURITY = _COINBASE_MATURITY;
319 // Remove transactions spending a coinbase which are now immature and no-longer-final transactions
321 list<CTransaction> transactionsToRemove;
322 for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
323 const CTransaction& tx = it->GetTx();
324 if (!CheckFinalTx(tx, flags)) {
325 transactionsToRemove.push_back(tx);
326 } else if (it->GetSpendsCoinbase()) {
327 BOOST_FOREACH(const CTxIn& txin, tx.vin) {
328 indexed_transaction_set::const_iterator it2 = mapTx.find(txin.prevout.hash);
329 if (it2 != mapTx.end())
331 const CCoins *coins = pcoins->AccessCoins(txin.prevout.hash);
332 if (nCheckFrequency != 0) assert(coins);
334 if (!coins || (coins->IsCoinBase() &&
335 (((signed long)nMemPoolHeight) - coins->nHeight < COINBASE_MATURITY) ||
336 ((signed long)nMemPoolHeight < komodo_block_unlocktime(coins->nHeight) &&
337 coins->IsAvailable(0) && coins->vout[0].nValue >= ASSETCHAINS_TIMELOCKGTE))) {
338 transactionsToRemove.push_back(tx);
344 BOOST_FOREACH(const CTransaction& tx, transactionsToRemove) {
345 list<CTransaction> removed;
346 remove(tx, removed, true);
351 void CTxMemPool::removeWithAnchor(const uint256 &invalidRoot, ShieldedType type)
353 // If a block is disconnected from the tip, and the root changed,
354 // we must invalidate transactions from the mempool which spend
355 // from that root -- almost as though they were spending coinbases
356 // which are no longer valid to spend due to coinbase maturity.
358 list<CTransaction> transactionsToRemove;
360 for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
361 const CTransaction& tx = it->GetTx();
364 BOOST_FOREACH(const JSDescription& joinsplit, tx.vJoinSplit) {
365 if (joinsplit.anchor == invalidRoot) {
366 transactionsToRemove.push_back(tx);
372 BOOST_FOREACH(const SpendDescription& spendDescription, tx.vShieldedSpend) {
373 if (spendDescription.anchor == invalidRoot) {
374 transactionsToRemove.push_back(tx);
380 throw runtime_error("Unknown shielded type");
385 BOOST_FOREACH(const CTransaction& tx, transactionsToRemove) {
386 list<CTransaction> removed;
387 remove(tx, removed, true);
391 void CTxMemPool::removeConflicts(const CTransaction &tx, std::list<CTransaction>& removed)
393 // Remove transactions which depend on inputs of tx, recursively
394 list<CTransaction> result;
396 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
397 std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(txin.prevout);
398 if (it != mapNextTx.end()) {
399 const CTransaction &txConflict = *it->second.ptx;
400 if (txConflict != tx)
402 remove(txConflict, removed, true);
407 BOOST_FOREACH(const JSDescription &joinsplit, tx.vJoinSplit) {
408 BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
409 std::map<uint256, const CTransaction*>::iterator it = mapSproutNullifiers.find(nf);
410 if (it != mapSproutNullifiers.end()) {
411 const CTransaction &txConflict = *it->second;
412 if (txConflict != tx) {
413 remove(txConflict, removed, true);
418 for (const SpendDescription &spendDescription : tx.vShieldedSpend) {
419 std::map<uint256, const CTransaction*>::iterator it = mapSaplingNullifiers.find(spendDescription.nullifier);
420 if (it != mapSaplingNullifiers.end()) {
421 const CTransaction &txConflict = *it->second;
422 if (txConflict != tx) {
423 remove(txConflict, removed, true);
429 int32_t komodo_validate_interest(const CTransaction &tx,int32_t txheight,uint32_t nTime,int32_t dispflag);
430 extern char ASSETCHAINS_SYMBOL[];
432 void CTxMemPool::removeExpired(unsigned int nBlockHeight)
434 CBlockIndex *tipindex;
435 // Remove expired txs from the mempool
437 list<CTransaction> transactionsToRemove;
438 for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++)
440 const CTransaction& tx = it->GetTx();
441 tipindex = chainActive.LastTip();
442 if (IsExpiredTx(tx, nBlockHeight) || (ASSETCHAINS_SYMBOL[0] == 0 && tipindex != 0 && komodo_validate_interest(tx,tipindex->GetHeight()+1,tipindex->GetMedianTimePast() + 777,0)) < 0)
444 transactionsToRemove.push_back(tx);
447 for (const CTransaction& tx : transactionsToRemove) {
448 list<CTransaction> removed;
449 remove(tx, removed, true);
450 LogPrint("mempool", "Removing expired txid: %s\n", tx.GetHash().ToString());
455 * Called when a block is connected. Removes from mempool and updates the miner fee estimator.
457 void CTxMemPool::removeForBlock(const std::vector<CTransaction>& vtx, unsigned int nBlockHeight,
458 std::list<CTransaction>& conflicts, bool fCurrentEstimate)
461 std::vector<CTxMemPoolEntry> entries;
462 BOOST_FOREACH(const CTransaction& tx, vtx)
464 uint256 hash = tx.GetHash();
466 indexed_transaction_set::iterator i = mapTx.find(hash);
467 if (i != mapTx.end())
468 entries.push_back(*i);
470 BOOST_FOREACH(const CTransaction& tx, vtx)
472 std::list<CTransaction> dummy;
473 remove(tx, dummy, false);
474 removeConflicts(tx, conflicts);
475 ClearPrioritisation(tx.GetHash());
477 // After the txs in the new block have been removed from the mempool, update policy estimates
478 minerPolicyEstimator->processBlock(nBlockHeight, entries, fCurrentEstimate);
482 * Called whenever the tip changes. Removes transactions which don't commit to
483 * the given branch ID from the mempool.
485 void CTxMemPool::removeWithoutBranchId(uint32_t nMemPoolBranchId)
488 std::list<CTransaction> transactionsToRemove;
490 for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
491 const CTransaction& tx = it->GetTx();
492 if (it->GetValidatedBranchId() != nMemPoolBranchId) {
493 transactionsToRemove.push_back(tx);
497 for (const CTransaction& tx : transactionsToRemove) {
498 std::list<CTransaction> removed;
499 remove(tx, removed, true);
503 void CTxMemPool::clear()
509 cachedInnerUsage = 0;
510 ++nTransactionsUpdated;
513 void CTxMemPool::check(const CCoinsViewCache *pcoins) const
515 if (nCheckFrequency == 0)
518 if (insecure_rand() >= nCheckFrequency)
521 LogPrint("mempool", "Checking mempool with %u transactions and %u inputs\n", (unsigned int)mapTx.size(), (unsigned int)mapNextTx.size());
523 uint64_t checkTotal = 0;
524 uint64_t innerUsage = 0;
526 CCoinsViewCache mempoolDuplicate(const_cast<CCoinsViewCache*>(pcoins));
527 const int64_t nSpendHeight = GetSpendHeight(mempoolDuplicate);
530 list<const CTxMemPoolEntry*> waitingOnDependants;
531 for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
533 checkTotal += it->GetTxSize();
534 innerUsage += it->DynamicMemoryUsage();
535 const CTransaction& tx = it->GetTx();
536 bool fDependsWait = false;
537 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
538 // Check that every mempool transaction's inputs refer to available coins, or other mempool tx's.
539 indexed_transaction_set::const_iterator it2 = mapTx.find(txin.prevout.hash);
540 if (it2 != mapTx.end()) {
541 const CTransaction& tx2 = it2->GetTx();
542 assert(tx2.vout.size() > txin.prevout.n && !tx2.vout[txin.prevout.n].IsNull());
545 const CCoins* coins = pcoins->AccessCoins(txin.prevout.hash);
546 assert(coins && coins->IsAvailable(txin.prevout.n));
548 // Check whether its inputs are marked in mapNextTx.
549 std::map<COutPoint, CInPoint>::const_iterator it3 = mapNextTx.find(txin.prevout);
550 assert(it3 != mapNextTx.end());
551 assert(it3->second.ptx == &tx);
552 assert(it3->second.n == i);
556 boost::unordered_map<uint256, SproutMerkleTree, CCoinsKeyHasher> intermediates;
558 BOOST_FOREACH(const JSDescription &joinsplit, tx.vJoinSplit) {
559 BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
560 assert(!pcoins->GetNullifier(nf, SPROUT));
563 SproutMerkleTree tree;
564 auto it = intermediates.find(joinsplit.anchor);
565 if (it != intermediates.end()) {
568 assert(pcoins->GetSproutAnchorAt(joinsplit.anchor, tree));
571 BOOST_FOREACH(const uint256& commitment, joinsplit.commitments)
573 tree.append(commitment);
576 intermediates.insert(std::make_pair(tree.root(), tree));
578 for (const SpendDescription &spendDescription : tx.vShieldedSpend) {
579 SaplingMerkleTree tree;
581 assert(pcoins->GetSaplingAnchorAt(spendDescription.anchor, tree));
582 assert(!pcoins->GetNullifier(spendDescription.nullifier, SAPLING));
585 waitingOnDependants.push_back(&(*it));
587 CValidationState state;
588 bool fCheckResult = tx.IsCoinBase() ||
589 Consensus::CheckTxInputs(tx, state, mempoolDuplicate, nSpendHeight, Params().GetConsensus());
590 assert(fCheckResult);
591 UpdateCoins(tx, mempoolDuplicate, 1000000);
594 unsigned int stepsSinceLastRemove = 0;
595 while (!waitingOnDependants.empty()) {
596 const CTxMemPoolEntry* entry = waitingOnDependants.front();
597 waitingOnDependants.pop_front();
598 CValidationState state;
599 if (!mempoolDuplicate.HaveInputs(entry->GetTx())) {
600 waitingOnDependants.push_back(entry);
601 stepsSinceLastRemove++;
602 assert(stepsSinceLastRemove < waitingOnDependants.size());
604 bool fCheckResult = entry->GetTx().IsCoinBase() ||
605 Consensus::CheckTxInputs(entry->GetTx(), state, mempoolDuplicate, nSpendHeight, Params().GetConsensus());
606 assert(fCheckResult);
607 UpdateCoins(entry->GetTx(), mempoolDuplicate, 1000000);
608 stepsSinceLastRemove = 0;
611 for (std::map<COutPoint, CInPoint>::const_iterator it = mapNextTx.begin(); it != mapNextTx.end(); it++) {
612 uint256 hash = it->second.ptx->GetHash();
613 indexed_transaction_set::const_iterator it2 = mapTx.find(hash);
614 const CTransaction& tx = it2->GetTx();
615 assert(it2 != mapTx.end());
616 assert(&tx == it->second.ptx);
617 assert(tx.vin.size() > it->second.n);
618 assert(it->first == it->second.ptx->vin[it->second.n].prevout);
621 checkNullifiers(SPROUT);
622 checkNullifiers(SAPLING);
624 assert(totalTxSize == checkTotal);
625 assert(innerUsage == cachedInnerUsage);
628 void CTxMemPool::checkNullifiers(ShieldedType type) const
630 const std::map<uint256, const CTransaction*>* mapToUse;
633 mapToUse = &mapSproutNullifiers;
636 mapToUse = &mapSaplingNullifiers;
639 throw runtime_error("Unknown nullifier type");
641 for (const auto& entry : *mapToUse) {
642 uint256 hash = entry.second->GetHash();
643 CTxMemPool::indexed_transaction_set::const_iterator findTx = mapTx.find(hash);
644 const CTransaction& tx = findTx->GetTx();
645 assert(findTx != mapTx.end());
646 assert(&tx == entry.second);
650 void CTxMemPool::queryHashes(vector<uint256>& vtxid)
655 vtxid.reserve(mapTx.size());
656 for (indexed_transaction_set::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
657 vtxid.push_back(mi->GetTx().GetHash());
660 bool CTxMemPool::lookup(uint256 hash, CTransaction& result) const
663 indexed_transaction_set::const_iterator i = mapTx.find(hash);
664 if (i == mapTx.end()) return false;
669 CFeeRate CTxMemPool::estimateFee(int nBlocks) const
672 return minerPolicyEstimator->estimateFee(nBlocks);
674 double CTxMemPool::estimatePriority(int nBlocks) const
677 return minerPolicyEstimator->estimatePriority(nBlocks);
681 CTxMemPool::WriteFeeEstimates(CAutoFile& fileout) const
685 fileout << 109900; // version required to read: 0.10.99 or later
686 fileout << CLIENT_VERSION; // version that wrote the file
687 minerPolicyEstimator->Write(fileout);
689 catch (const std::exception&) {
690 LogPrintf("CTxMemPool::WriteFeeEstimates(): unable to write policy estimator data (non-fatal)\n");
697 CTxMemPool::ReadFeeEstimates(CAutoFile& filein)
700 int nVersionRequired, nVersionThatWrote;
701 filein >> nVersionRequired >> nVersionThatWrote;
702 if (nVersionRequired > CLIENT_VERSION)
703 return error("CTxMemPool::ReadFeeEstimates(): up-version (%d) fee estimate file", nVersionRequired);
706 minerPolicyEstimator->Read(filein);
708 catch (const std::exception&) {
709 LogPrintf("CTxMemPool::ReadFeeEstimates(): unable to read policy estimator data (non-fatal)\n");
715 void CTxMemPool::PrioritiseTransaction(const uint256 &hash, const string strHash, double dPriorityDelta, const CAmount& nFeeDelta)
719 std::pair<double, CAmount> &deltas = mapDeltas[hash];
720 deltas.first += dPriorityDelta;
721 deltas.second += nFeeDelta;
723 LogPrintf("PrioritiseTransaction: %s priority += %f, fee += %d\n", strHash, dPriorityDelta, FormatMoney(nFeeDelta));
726 void CTxMemPool::ApplyDeltas(const uint256 hash, double &dPriorityDelta, CAmount &nFeeDelta)
729 std::map<uint256, std::pair<double, CAmount> >::iterator pos = mapDeltas.find(hash);
730 if (pos == mapDeltas.end())
732 const std::pair<double, CAmount> &deltas = pos->second;
733 dPriorityDelta += deltas.first;
734 nFeeDelta += deltas.second;
737 void CTxMemPool::ClearPrioritisation(const uint256 hash)
740 mapDeltas.erase(hash);
741 mapReserveTransactions.erase(hash);
744 bool CTxMemPool::PrioritiseReserveTransaction(const CReserveTransactionDescriptor &txDesc, const CCurrencyState ¤cyState)
747 uint256 hash = txDesc.ptx->GetHash();
748 auto it = mapReserveTransactions.find(hash);
749 if (txDesc.IsValid())
751 mapReserveTransactions[hash] = txDesc;
752 CAmount feeDelta = currencyState.ReserveToNative(txDesc.ReserveFees() + txDesc.reserveConversionFees) + txDesc.nativeConversionFees;
753 PrioritiseTransaction(hash, hash.GetHex().c_str(), (double)feeDelta * 100.0, feeDelta);
759 bool CTxMemPool::IsKnownReserveTransaction(const uint256 &hash, CReserveTransactionDescriptor &txDesc)
762 auto it = mapReserveTransactions.find(hash);
763 if (it != mapReserveTransactions.end() && it->second.IsValid())
765 // refresh transaction from mempool or delete it if not found (we may not need this at all)
766 indexed_transaction_set::const_iterator i = mapTx.find(hash);
767 if (i == mapTx.end())
769 ClearPrioritisation(hash);
773 it->second.ptx = &(i->GetTx());
782 bool CTxMemPool::HasNoInputsOf(const CTransaction &tx) const
784 for (unsigned int i = 0; i < tx.vin.size(); i++)
785 if (exists(tx.vin[i].prevout.hash))
790 bool CTxMemPool::nullifierExists(const uint256& nullifier, ShieldedType type) const
794 return mapSproutNullifiers.count(nullifier);
796 return mapSaplingNullifiers.count(nullifier);
798 throw runtime_error("Unknown nullifier type");
802 void CTxMemPool::NotifyRecentlyAdded()
804 uint64_t recentlyAddedSequence;
805 std::vector<CTransaction> txs;
808 recentlyAddedSequence = nRecentlyAddedSequence;
809 for (const auto& kv : mapRecentlyAddedTx) {
810 txs.push_back(*(kv.second));
812 mapRecentlyAddedTx.clear();
815 // A race condition can occur here between these SyncWithWallets calls, and
816 // the ones triggered by block logic (in ConnectTip and DisconnectTip). It
817 // is harmless because calling SyncWithWallets(_, NULL) does not alter the
818 // wallet transaction's block information.
819 for (auto tx : txs) {
821 SyncWithWallets(tx, NULL);
822 } catch (const boost::thread_interrupted&) {
824 } catch (const std::exception& e) {
825 PrintExceptionContinue(&e, "CTxMemPool::NotifyRecentlyAdded()");
827 PrintExceptionContinue(NULL, "CTxMemPool::NotifyRecentlyAdded()");
831 // Update the notified sequence number. We only need this in regtest mode,
832 // and should not lock on cs after calling SyncWithWallets otherwise.
833 if (Params().NetworkIDString() == "regtest") {
835 nNotifiedSequence = recentlyAddedSequence;
839 bool CTxMemPool::IsFullyNotified() {
840 assert(Params().NetworkIDString() == "regtest");
842 return nRecentlyAddedSequence == nNotifiedSequence;
845 CCoinsViewMemPool::CCoinsViewMemPool(CCoinsView *baseIn, CTxMemPool &mempoolIn) : CCoinsViewBacked(baseIn), mempool(mempoolIn) { }
847 bool CCoinsViewMemPool::GetNullifier(const uint256 &nf, ShieldedType type) const
849 return mempool.nullifierExists(nf, type) || base->GetNullifier(nf, type);
852 bool CCoinsViewMemPool::GetCoins(const uint256 &txid, CCoins &coins) const {
853 // If an entry in the mempool exists, always return that one, as it's guaranteed to never
854 // conflict with the underlying cache, and it cannot have pruned entries (as it contains full)
855 // transactions. First checking the underlying cache risks returning a pruned entry instead.
857 if (mempool.lookup(txid, tx)) {
858 coins = CCoins(tx, MEMPOOL_HEIGHT);
861 return (base->GetCoins(txid, coins) && !coins.IsPruned());
864 bool CCoinsViewMemPool::HaveCoins(const uint256 &txid) const {
865 return mempool.exists(txid) || base->HaveCoins(txid);
868 size_t CTxMemPool::DynamicMemoryUsage() const {
870 // Estimate the overhead of mapTx to be 6 pointers + an allocation, as no exact formula for boost::multi_index_contained is implemented.
871 return memusage::MallocUsage(sizeof(CTxMemPoolEntry) + 6 * sizeof(void*)) * mapTx.size() + memusage::DynamicUsage(mapNextTx) + memusage::DynamicUsage(mapDeltas) + memusage::DynamicUsage(mapDeltas) + memusage::DynamicUsage(mapDeltas) + cachedInnerUsage;