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 http://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"
18 #define _COINBASE_MATURITY 100
22 CTxMemPoolEntry::CTxMemPoolEntry():
23 nFee(0), nTxSize(0), nModSize(0), nUsageSize(0), nTime(0), dPriority(0.0),
24 hadNoDependencies(false), spendsCoinbase(false)
26 nHeight = MEMPOOL_HEIGHT;
29 CTxMemPoolEntry::CTxMemPoolEntry(const CTransaction& _tx, const CAmount& _nFee,
30 int64_t _nTime, double _dPriority,
31 unsigned int _nHeight, bool poolHasNoInputsOf,
32 bool _spendsCoinbase, uint32_t _nBranchId):
33 tx(_tx), nFee(_nFee), nTime(_nTime), dPriority(_dPriority), nHeight(_nHeight),
34 hadNoDependencies(poolHasNoInputsOf),
35 spendsCoinbase(_spendsCoinbase), nBranchId(_nBranchId)
37 nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
38 nModSize = tx.CalculateModifiedSize(nTxSize);
39 nUsageSize = RecursiveDynamicUsage(tx);
40 feeRate = CFeeRate(nFee, nTxSize);
43 CTxMemPoolEntry::CTxMemPoolEntry(const CTxMemPoolEntry& other)
49 CTxMemPoolEntry::GetPriority(unsigned int currentHeight) const
51 CAmount nValueIn = tx.GetValueOut()+nFee;
52 double deltaPriority = ((double)(currentHeight-nHeight)*nValueIn)/nModSize;
53 double dResult = dPriority + deltaPriority;
57 CTxMemPool::CTxMemPool(const CFeeRate& _minRelayFee) :
58 nTransactionsUpdated(0)
60 // Sanity checks off by default for performance, because otherwise
61 // accepting transactions becomes O(N^2) where N is the number
62 // of transactions in the pool
65 minerPolicyEstimator = new CBlockPolicyEstimator(_minRelayFee);
68 CTxMemPool::~CTxMemPool()
70 delete minerPolicyEstimator;
73 void CTxMemPool::pruneSpent(const uint256 &hashTx, CCoins &coins)
77 std::map<COutPoint, CInPoint>::iterator it = mapNextTx.lower_bound(COutPoint(hashTx, 0));
79 // iterate over all COutPoints in mapNextTx whose hash equals the provided hashTx
80 while (it != mapNextTx.end() && it->first.hash == hashTx) {
81 coins.Spend(it->first.n); // and remove those outputs from coins
86 unsigned int CTxMemPool::GetTransactionsUpdated() const
89 return nTransactionsUpdated;
92 void CTxMemPool::AddTransactionsUpdated(unsigned int n)
95 nTransactionsUpdated += n;
99 bool CTxMemPool::addUnchecked(const uint256& hash, const CTxMemPoolEntry &entry, bool fCurrentEstimate)
101 // Add to memory pool without checking anything.
102 // Used by main.cpp AcceptToMemoryPool(), which DOES do
103 // all the appropriate checks.
106 const CTransaction& tx = mapTx.find(hash)->GetTx();
107 if (!tx.IsCoinImport()) {
108 for (unsigned int i = 0; i < tx.vin.size(); i++)
109 mapNextTx[tx.vin[i].prevout] = CInPoint(&tx, i);
111 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
112 BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
113 mapSproutNullifiers[nf] = &tx;
116 for (const SpendDescription &spendDescription : tx.vShieldedSpend) {
117 mapSaplingNullifiers[spendDescription.nullifier] = &tx;
119 nTransactionsUpdated++;
120 totalTxSize += entry.GetTxSize();
121 cachedInnerUsage += entry.DynamicMemoryUsage();
122 minerPolicyEstimator->processTransaction(entry, fCurrentEstimate);
127 void CTxMemPool::addAddressIndex(const CTxMemPoolEntry &entry, const CCoinsViewCache &view)
130 const CTransaction& tx = entry.GetTx();
131 std::vector<CMempoolAddressDeltaKey> inserted;
133 uint256 txhash = tx.GetHash();
134 for (unsigned int j = 0; j < tx.vin.size(); j++) {
135 const CTxIn input = tx.vin[j];
136 const CTxOut &prevout = view.GetOutputFor(input);
137 if (prevout.scriptPubKey.IsPayToScriptHash()) {
138 vector<unsigned char> hashBytes(prevout.scriptPubKey.begin()+2, prevout.scriptPubKey.begin()+22);
139 CMempoolAddressDeltaKey key(2, uint160(hashBytes), txhash, j, 1);
140 CMempoolAddressDelta delta(entry.GetTime(), prevout.nValue * -1, input.prevout.hash, input.prevout.n);
141 mapAddress.insert(make_pair(key, delta));
142 inserted.push_back(key);
144 else if (prevout.scriptPubKey.IsPayToPublicKeyHash()) {
145 vector<unsigned char> hashBytes(prevout.scriptPubKey.begin()+3, prevout.scriptPubKey.begin()+23);
146 CMempoolAddressDeltaKey key(1, uint160(hashBytes), txhash, j, 1);
147 CMempoolAddressDelta delta(entry.GetTime(), prevout.nValue * -1, input.prevout.hash, input.prevout.n);
148 mapAddress.insert(make_pair(key, delta));
149 inserted.push_back(key);
151 else if (prevout.scriptPubKey.IsPayToPublicKey()) {
152 vector<unsigned char> hashBytes(prevout.scriptPubKey.begin()+1, prevout.scriptPubKey.begin()+34);
153 CMempoolAddressDeltaKey key(1, Hash160(hashBytes), txhash, j, 1);
154 CMempoolAddressDelta delta(entry.GetTime(), prevout.nValue * -1, input.prevout.hash, input.prevout.n);
155 mapAddress.insert(make_pair(key, delta));
156 inserted.push_back(key);
158 else if (prevout.scriptPubKey.IsPayToCryptoCondition()) {
159 vector<unsigned char> hashBytes(prevout.scriptPubKey.begin(), prevout.scriptPubKey.end());
160 CMempoolAddressDeltaKey key(1, Hash160(hashBytes), txhash, j, 1);
161 CMempoolAddressDelta delta(entry.GetTime(), prevout.nValue * -1, input.prevout.hash, input.prevout.n);
162 mapAddress.insert(make_pair(key, delta));
163 inserted.push_back(key);
166 for (unsigned int k = 0; k < tx.vout.size(); k++) {
167 const CTxOut &out = tx.vout[k];
168 if (out.scriptPubKey.IsPayToScriptHash()) {
169 vector<unsigned char> hashBytes(out.scriptPubKey.begin()+2, out.scriptPubKey.begin()+22);
170 CMempoolAddressDeltaKey key(2, uint160(hashBytes), txhash, k, 0);
171 mapAddress.insert(make_pair(key, CMempoolAddressDelta(entry.GetTime(), out.nValue)));
172 inserted.push_back(key);
174 else if (out.scriptPubKey.IsPayToPublicKeyHash()) {
175 vector<unsigned char> hashBytes(out.scriptPubKey.begin()+3, out.scriptPubKey.begin()+23);
176 std::pair<addressDeltaMap::iterator,bool> ret;
177 CMempoolAddressDeltaKey key(1, uint160(hashBytes), txhash, k, 0);
178 mapAddress.insert(make_pair(key, CMempoolAddressDelta(entry.GetTime(), out.nValue)));
179 inserted.push_back(key);
181 else if (out.scriptPubKey.IsPayToPublicKey()) {
182 vector<unsigned char> hashBytes(out.scriptPubKey.begin()+1, out.scriptPubKey.begin()+34);
183 std::pair<addressDeltaMap::iterator,bool> ret;
184 CMempoolAddressDeltaKey key(1, Hash160(hashBytes), txhash, k, 0);
185 mapAddress.insert(make_pair(key, CMempoolAddressDelta(entry.GetTime(), out.nValue)));
186 inserted.push_back(key);
188 else if (out.scriptPubKey.IsPayToCryptoCondition()) {
189 vector<unsigned char> hashBytes(out.scriptPubKey.begin(), out.scriptPubKey.end());
190 std::pair<addressDeltaMap::iterator,bool> ret;
191 CMempoolAddressDeltaKey key(1, Hash160(hashBytes), txhash, k, 0);
192 mapAddress.insert(make_pair(key, CMempoolAddressDelta(entry.GetTime(), out.nValue)));
193 inserted.push_back(key);
197 mapAddressInserted.insert(make_pair(txhash, inserted));
200 bool CTxMemPool::getAddressIndex(std::vector<std::pair<uint160, int> > &addresses,
201 std::vector<std::pair<CMempoolAddressDeltaKey, CMempoolAddressDelta> > &results)
204 for (std::vector<std::pair<uint160, int> >::iterator it = addresses.begin(); it != addresses.end(); it++) {
205 addressDeltaMap::iterator ait = mapAddress.lower_bound(CMempoolAddressDeltaKey((*it).second, (*it).first));
206 while (ait != mapAddress.end() && (*ait).first.addressBytes == (*it).first && (*ait).first.type == (*it).second) {
207 results.push_back(*ait);
214 bool CTxMemPool::removeAddressIndex(const uint256 txhash)
217 addressDeltaMapInserted::iterator it = mapAddressInserted.find(txhash);
219 if (it != mapAddressInserted.end()) {
220 std::vector<CMempoolAddressDeltaKey> keys = (*it).second;
221 for (std::vector<CMempoolAddressDeltaKey>::iterator mit = keys.begin(); mit != keys.end(); mit++) {
222 mapAddress.erase(*mit);
224 mapAddressInserted.erase(it);
230 void CTxMemPool::addSpentIndex(const CTxMemPoolEntry &entry, const CCoinsViewCache &view)
234 const CTransaction& tx = entry.GetTx();
235 std::vector<CSpentIndexKey> inserted;
237 uint256 txhash = tx.GetHash();
238 for (unsigned int j = 0; j < tx.vin.size(); j++) {
239 const CTxIn input = tx.vin[j];
240 const CTxOut &prevout = view.GetOutputFor(input);
244 if (prevout.scriptPubKey.IsPayToScriptHash()) {
245 addressHash = uint160(vector<unsigned char> (prevout.scriptPubKey.begin()+2, prevout.scriptPubKey.begin()+22));
248 else if (prevout.scriptPubKey.IsPayToPublicKeyHash()) {
249 addressHash = uint160(vector<unsigned char> (prevout.scriptPubKey.begin()+3, prevout.scriptPubKey.begin()+23));
252 else if (prevout.scriptPubKey.IsPayToPublicKey()) {
253 addressHash = Hash160(vector<unsigned char> (prevout.scriptPubKey.begin()+1, prevout.scriptPubKey.begin()+34));
256 else if (prevout.scriptPubKey.IsPayToCryptoCondition()) {
257 addressHash = Hash160(vector<unsigned char> (prevout.scriptPubKey.begin(), prevout.scriptPubKey.end()));
261 addressHash.SetNull();
265 CSpentIndexKey key = CSpentIndexKey(input.prevout.hash, input.prevout.n);
266 CSpentIndexValue value = CSpentIndexValue(txhash, j, -1, prevout.nValue, addressType, addressHash);
268 mapSpent.insert(make_pair(key, value));
269 inserted.push_back(key);
273 mapSpentInserted.insert(make_pair(txhash, inserted));
276 bool CTxMemPool::getSpentIndex(CSpentIndexKey &key, CSpentIndexValue &value)
279 mapSpentIndex::iterator it;
281 it = mapSpent.find(key);
282 if (it != mapSpent.end()) {
289 bool CTxMemPool::removeSpentIndex(const uint256 txhash)
292 mapSpentIndexInserted::iterator it = mapSpentInserted.find(txhash);
294 if (it != mapSpentInserted.end()) {
295 std::vector<CSpentIndexKey> keys = (*it).second;
296 for (std::vector<CSpentIndexKey>::iterator mit = keys.begin(); mit != keys.end(); mit++) {
297 mapSpent.erase(*mit);
299 mapSpentInserted.erase(it);
305 void CTxMemPool::remove(const CTransaction &origTx, std::list<CTransaction>& removed, bool fRecursive)
307 // Remove transaction from memory pool
310 std::deque<uint256> txToRemove;
311 txToRemove.push_back(origTx.GetHash());
312 if (fRecursive && !mapTx.count(origTx.GetHash())) {
313 // If recursively removing but origTx isn't in the mempool
314 // be sure to remove any children that are in the pool. This can
315 // happen during chain re-orgs if origTx isn't re-accepted into
316 // the mempool for any reason.
317 for (unsigned int i = 0; i < origTx.vout.size(); i++) {
318 std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(COutPoint(origTx.GetHash(), i));
319 if (it == mapNextTx.end())
321 txToRemove.push_back(it->second.ptx->GetHash());
324 while (!txToRemove.empty())
326 uint256 hash = txToRemove.front();
327 txToRemove.pop_front();
328 if (!mapTx.count(hash))
330 const CTransaction& tx = mapTx.find(hash)->GetTx();
332 for (unsigned int i = 0; i < tx.vout.size(); i++) {
333 std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(COutPoint(hash, i));
334 if (it == mapNextTx.end())
336 txToRemove.push_back(it->second.ptx->GetHash());
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);
355 removeAddressIndex(hash);
356 removeSpentIndex(hash);
361 extern uint64_t ASSETCHAINS_TIMELOCKGTE;
362 int64_t komodo_block_unlocktime(uint32_t nHeight);
364 void CTxMemPool::removeForReorg(const CCoinsViewCache *pcoins, unsigned int nMemPoolHeight, int flags)
366 // Remove transactions spending a coinbase which are now immature
367 extern char ASSETCHAINS_SYMBOL[KOMODO_ASSETCHAIN_MAXLEN];
368 if ( ASSETCHAINS_SYMBOL[0] == 0 )
369 COINBASE_MATURITY = _COINBASE_MATURITY;
370 // Remove transactions spending a coinbase which are now immature and no-longer-final transactions
372 list<CTransaction> transactionsToRemove;
373 for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
374 const CTransaction& tx = it->GetTx();
375 if (!CheckFinalTx(tx, flags)) {
376 transactionsToRemove.push_back(tx);
377 } else if (it->GetSpendsCoinbase()) {
378 BOOST_FOREACH(const CTxIn& txin, tx.vin) {
379 indexed_transaction_set::const_iterator it2 = mapTx.find(txin.prevout.hash);
380 if (it2 != mapTx.end())
382 const CCoins *coins = pcoins->AccessCoins(txin.prevout.hash);
383 if (nCheckFrequency != 0) assert(coins);
384 if (!coins || (coins->IsCoinBase() && (((signed long)nMemPoolHeight) - coins->nHeight < COINBASE_MATURITY) &&
385 ((signed long)nMemPoolHeight < komodo_block_unlocktime(coins->nHeight) &&
386 coins->IsAvailable(0) && coins->vout[0].nValue >= ASSETCHAINS_TIMELOCKGTE))) {
387 transactionsToRemove.push_back(tx);
393 BOOST_FOREACH(const CTransaction& tx, transactionsToRemove) {
394 list<CTransaction> removed;
395 remove(tx, removed, true);
400 void CTxMemPool::removeWithAnchor(const uint256 &invalidRoot, ShieldedType type)
402 // If a block is disconnected from the tip, and the root changed,
403 // we must invalidate transactions from the mempool which spend
404 // from that root -- almost as though they were spending coinbases
405 // which are no longer valid to spend due to coinbase maturity.
407 list<CTransaction> transactionsToRemove;
409 for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
410 const CTransaction& tx = it->GetTx();
413 BOOST_FOREACH(const JSDescription& joinsplit, tx.vjoinsplit) {
414 if (joinsplit.anchor == invalidRoot) {
415 transactionsToRemove.push_back(tx);
421 BOOST_FOREACH(const SpendDescription& spendDescription, tx.vShieldedSpend) {
422 if (spendDescription.anchor == invalidRoot) {
423 transactionsToRemove.push_back(tx);
429 throw runtime_error("Unknown shielded type");
434 BOOST_FOREACH(const CTransaction& tx, transactionsToRemove) {
435 list<CTransaction> removed;
436 remove(tx, removed, true);
440 void CTxMemPool::removeConflicts(const CTransaction &tx, std::list<CTransaction>& removed)
442 // Remove transactions which depend on inputs of tx, recursively
443 list<CTransaction> result;
445 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
446 std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(txin.prevout);
447 if (it != mapNextTx.end()) {
448 const CTransaction &txConflict = *it->second.ptx;
449 if (txConflict != tx)
451 remove(txConflict, removed, true);
456 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
457 BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
458 std::map<uint256, const CTransaction*>::iterator it = mapSproutNullifiers.find(nf);
459 if (it != mapSproutNullifiers.end()) {
460 const CTransaction &txConflict = *it->second;
461 if (txConflict != tx) {
462 remove(txConflict, removed, true);
467 for (const SpendDescription &spendDescription : tx.vShieldedSpend) {
468 std::map<uint256, const CTransaction*>::iterator it = mapSaplingNullifiers.find(spendDescription.nullifier);
469 if (it != mapSaplingNullifiers.end()) {
470 const CTransaction &txConflict = *it->second;
471 if (txConflict != tx) {
472 remove(txConflict, removed, true);
478 int32_t komodo_validate_interest(const CTransaction &tx,int32_t txheight,uint32_t nTime,int32_t dispflag);
479 extern char ASSETCHAINS_SYMBOL[];
481 void CTxMemPool::removeExpired(unsigned int nBlockHeight)
483 CBlockIndex *tipindex;
484 // Remove expired txs from the mempool
486 list<CTransaction> transactionsToRemove;
487 for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++)
489 const CTransaction& tx = it->GetTx();
490 tipindex = chainActive.LastTip();
491 if (IsExpiredTx(tx, nBlockHeight) || (ASSETCHAINS_SYMBOL[0] == 0 && tipindex != 0 && komodo_validate_interest(tx,tipindex->GetHeight()+1,tipindex->GetMedianTimePast() + 777,0)) < 0)
493 transactionsToRemove.push_back(tx);
496 for (const CTransaction& tx : transactionsToRemove) {
497 list<CTransaction> removed;
498 remove(tx, removed, true);
499 LogPrint("mempool", "Removing expired txid: %s\n", tx.GetHash().ToString());
504 * Called when a block is connected. Removes from mempool and updates the miner fee estimator.
506 void CTxMemPool::removeForBlock(const std::vector<CTransaction>& vtx, unsigned int nBlockHeight,
507 std::list<CTransaction>& conflicts, bool fCurrentEstimate)
510 std::vector<CTxMemPoolEntry> entries;
511 BOOST_FOREACH(const CTransaction& tx, vtx)
513 uint256 hash = tx.GetHash();
515 indexed_transaction_set::iterator i = mapTx.find(hash);
516 if (i != mapTx.end())
517 entries.push_back(*i);
519 BOOST_FOREACH(const CTransaction& tx, vtx)
521 std::list<CTransaction> dummy;
522 remove(tx, dummy, false);
523 removeConflicts(tx, conflicts);
524 ClearPrioritisation(tx.GetHash());
526 // After the txs in the new block have been removed from the mempool, update policy estimates
527 minerPolicyEstimator->processBlock(nBlockHeight, entries, fCurrentEstimate);
531 * Called whenever the tip changes. Removes transactions which don't commit to
532 * the given branch ID from the mempool.
534 void CTxMemPool::removeWithoutBranchId(uint32_t nMemPoolBranchId)
537 std::list<CTransaction> transactionsToRemove;
539 for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
540 const CTransaction& tx = it->GetTx();
541 if (it->GetValidatedBranchId() != nMemPoolBranchId) {
542 transactionsToRemove.push_back(tx);
546 for (const CTransaction& tx : transactionsToRemove) {
547 std::list<CTransaction> removed;
548 remove(tx, removed, true);
552 void CTxMemPool::clear()
558 cachedInnerUsage = 0;
559 ++nTransactionsUpdated;
562 void CTxMemPool::check(const CCoinsViewCache *pcoins) const
564 if (nCheckFrequency == 0)
567 if (insecure_rand() >= nCheckFrequency)
570 LogPrint("mempool", "Checking mempool with %u transactions and %u inputs\n", (unsigned int)mapTx.size(), (unsigned int)mapNextTx.size());
572 uint64_t checkTotal = 0;
573 uint64_t innerUsage = 0;
575 CCoinsViewCache mempoolDuplicate(const_cast<CCoinsViewCache*>(pcoins));
576 const int64_t nSpendHeight = GetSpendHeight(mempoolDuplicate);
579 list<const CTxMemPoolEntry*> waitingOnDependants;
580 for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
582 checkTotal += it->GetTxSize();
583 innerUsage += it->DynamicMemoryUsage();
584 const CTransaction& tx = it->GetTx();
585 bool fDependsWait = false;
586 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
587 // Check that every mempool transaction's inputs refer to available coins, or other mempool tx's.
588 indexed_transaction_set::const_iterator it2 = mapTx.find(txin.prevout.hash);
589 if (it2 != mapTx.end()) {
590 const CTransaction& tx2 = it2->GetTx();
591 assert(tx2.vout.size() > txin.prevout.n && !tx2.vout[txin.prevout.n].IsNull());
594 const CCoins* coins = pcoins->AccessCoins(txin.prevout.hash);
595 assert(coins && coins->IsAvailable(txin.prevout.n));
597 // Check whether its inputs are marked in mapNextTx.
598 std::map<COutPoint, CInPoint>::const_iterator it3 = mapNextTx.find(txin.prevout);
599 assert(it3 != mapNextTx.end());
600 assert(it3->second.ptx == &tx);
601 assert(it3->second.n == i);
605 boost::unordered_map<uint256, SproutMerkleTree, CCoinsKeyHasher> intermediates;
607 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
608 BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
609 assert(!pcoins->GetNullifier(nf, SPROUT));
612 SproutMerkleTree tree;
613 auto it = intermediates.find(joinsplit.anchor);
614 if (it != intermediates.end()) {
617 assert(pcoins->GetSproutAnchorAt(joinsplit.anchor, tree));
620 BOOST_FOREACH(const uint256& commitment, joinsplit.commitments)
622 tree.append(commitment);
625 intermediates.insert(std::make_pair(tree.root(), tree));
627 for (const SpendDescription &spendDescription : tx.vShieldedSpend) {
628 SaplingMerkleTree tree;
630 assert(pcoins->GetSaplingAnchorAt(spendDescription.anchor, tree));
631 assert(!pcoins->GetNullifier(spendDescription.nullifier, SAPLING));
634 waitingOnDependants.push_back(&(*it));
636 CValidationState state;
637 bool fCheckResult = tx.IsCoinBase() ||
638 Consensus::CheckTxInputs(tx, state, mempoolDuplicate, nSpendHeight, Params().GetConsensus());
639 assert(fCheckResult);
640 UpdateCoins(tx, mempoolDuplicate, 1000000);
643 unsigned int stepsSinceLastRemove = 0;
644 while (!waitingOnDependants.empty()) {
645 const CTxMemPoolEntry* entry = waitingOnDependants.front();
646 waitingOnDependants.pop_front();
647 CValidationState state;
648 if (!mempoolDuplicate.HaveInputs(entry->GetTx())) {
649 waitingOnDependants.push_back(entry);
650 stepsSinceLastRemove++;
651 assert(stepsSinceLastRemove < waitingOnDependants.size());
653 bool fCheckResult = entry->GetTx().IsCoinBase() ||
654 Consensus::CheckTxInputs(entry->GetTx(), state, mempoolDuplicate, nSpendHeight, Params().GetConsensus());
655 assert(fCheckResult);
656 UpdateCoins(entry->GetTx(), mempoolDuplicate, 1000000);
657 stepsSinceLastRemove = 0;
660 for (std::map<COutPoint, CInPoint>::const_iterator it = mapNextTx.begin(); it != mapNextTx.end(); it++) {
661 uint256 hash = it->second.ptx->GetHash();
662 indexed_transaction_set::const_iterator it2 = mapTx.find(hash);
663 const CTransaction& tx = it2->GetTx();
664 assert(it2 != mapTx.end());
665 assert(&tx == it->second.ptx);
666 assert(tx.vin.size() > it->second.n);
667 assert(it->first == it->second.ptx->vin[it->second.n].prevout);
670 checkNullifiers(SPROUT);
671 checkNullifiers(SAPLING);
673 assert(totalTxSize == checkTotal);
674 assert(innerUsage == cachedInnerUsage);
677 void CTxMemPool::checkNullifiers(ShieldedType type) const
679 const std::map<uint256, const CTransaction*>* mapToUse;
682 mapToUse = &mapSproutNullifiers;
685 mapToUse = &mapSaplingNullifiers;
688 throw runtime_error("Unknown nullifier type");
690 for (const auto& entry : *mapToUse) {
691 uint256 hash = entry.second->GetHash();
692 CTxMemPool::indexed_transaction_set::const_iterator findTx = mapTx.find(hash);
693 const CTransaction& tx = findTx->GetTx();
694 assert(findTx != mapTx.end());
695 assert(&tx == entry.second);
699 void CTxMemPool::queryHashes(vector<uint256>& vtxid)
704 vtxid.reserve(mapTx.size());
705 for (indexed_transaction_set::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
706 vtxid.push_back(mi->GetTx().GetHash());
709 bool CTxMemPool::lookup(uint256 hash, CTransaction& result) const
712 indexed_transaction_set::const_iterator i = mapTx.find(hash);
713 if (i == mapTx.end()) return false;
718 CFeeRate CTxMemPool::estimateFee(int nBlocks) const
721 return minerPolicyEstimator->estimateFee(nBlocks);
723 double CTxMemPool::estimatePriority(int nBlocks) const
726 return minerPolicyEstimator->estimatePriority(nBlocks);
730 CTxMemPool::WriteFeeEstimates(CAutoFile& fileout) const
734 fileout << 109900; // version required to read: 0.10.99 or later
735 fileout << CLIENT_VERSION; // version that wrote the file
736 minerPolicyEstimator->Write(fileout);
738 catch (const std::exception&) {
739 LogPrintf("CTxMemPool::WriteFeeEstimates(): unable to write policy estimator data (non-fatal)\n");
746 CTxMemPool::ReadFeeEstimates(CAutoFile& filein)
749 int nVersionRequired, nVersionThatWrote;
750 filein >> nVersionRequired >> nVersionThatWrote;
751 if (nVersionRequired > CLIENT_VERSION)
752 return error("CTxMemPool::ReadFeeEstimates(): up-version (%d) fee estimate file", nVersionRequired);
755 minerPolicyEstimator->Read(filein);
757 catch (const std::exception&) {
758 LogPrintf("CTxMemPool::ReadFeeEstimates(): unable to read policy estimator data (non-fatal)\n");
764 void CTxMemPool::PrioritiseTransaction(const uint256 hash, const string strHash, double dPriorityDelta, const CAmount& nFeeDelta)
768 std::pair<double, CAmount> &deltas = mapDeltas[hash];
769 deltas.first += dPriorityDelta;
770 deltas.second += nFeeDelta;
772 LogPrintf("PrioritiseTransaction: %s priority += %f, fee += %d\n", strHash, dPriorityDelta, FormatMoney(nFeeDelta));
775 void CTxMemPool::ApplyDeltas(const uint256 hash, double &dPriorityDelta, CAmount &nFeeDelta)
778 std::map<uint256, std::pair<double, CAmount> >::iterator pos = mapDeltas.find(hash);
779 if (pos == mapDeltas.end())
781 const std::pair<double, CAmount> &deltas = pos->second;
782 dPriorityDelta += deltas.first;
783 nFeeDelta += deltas.second;
786 void CTxMemPool::ClearPrioritisation(const uint256 hash)
789 mapDeltas.erase(hash);
792 bool CTxMemPool::HasNoInputsOf(const CTransaction &tx) const
794 for (unsigned int i = 0; i < tx.vin.size(); i++)
795 if (exists(tx.vin[i].prevout.hash))
800 bool CTxMemPool::nullifierExists(const uint256& nullifier, ShieldedType type) const
804 return mapSproutNullifiers.count(nullifier);
806 return mapSaplingNullifiers.count(nullifier);
808 throw runtime_error("Unknown nullifier type");
812 CCoinsViewMemPool::CCoinsViewMemPool(CCoinsView *baseIn, CTxMemPool &mempoolIn) : CCoinsViewBacked(baseIn), mempool(mempoolIn) { }
814 bool CCoinsViewMemPool::GetNullifier(const uint256 &nf, ShieldedType type) const
816 return mempool.nullifierExists(nf, type) || base->GetNullifier(nf, type);
819 bool CCoinsViewMemPool::GetCoins(const uint256 &txid, CCoins &coins) const {
820 // If an entry in the mempool exists, always return that one, as it's guaranteed to never
821 // conflict with the underlying cache, and it cannot have pruned entries (as it contains full)
822 // transactions. First checking the underlying cache risks returning a pruned entry instead.
824 if (mempool.lookup(txid, tx)) {
825 coins = CCoins(tx, MEMPOOL_HEIGHT);
828 return (base->GetCoins(txid, coins) && !coins.IsPruned());
831 bool CCoinsViewMemPool::HaveCoins(const uint256 &txid) const {
832 return mempool.exists(txid) || base->HaveCoins(txid);
835 size_t CTxMemPool::DynamicMemoryUsage() const {
837 // Estimate the overhead of mapTx to be 6 pointers + an allocation, as no exact formula for boost::multi_index_contained is implemented.
838 return memusage::MallocUsage(sizeof(CTxMemPoolEntry) + 6 * sizeof(void*)) * mapTx.size() + memusage::DynamicUsage(mapNextTx) + memusage::DynamicUsage(mapDeltas) + cachedInnerUsage;