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 #include "pbaas/pbaas.h"
19 #define _COINBASE_MATURITY 100
23 CTxMemPoolEntry::CTxMemPoolEntry():
24 nFee(0), nTxSize(0), nModSize(0), nUsageSize(0), nTime(0), dPriority(0.0),
25 hadNoDependencies(false), spendsCoinbase(false), hasReserve(false)
27 nHeight = MEMPOOL_HEIGHT;
30 CTxMemPoolEntry::CTxMemPoolEntry(const CTransaction& _tx, const CAmount& _nFee,
31 int64_t _nTime, double _dPriority,
32 unsigned int _nHeight, bool poolHasNoInputsOf,
33 bool _spendsCoinbase, uint32_t _nBranchId, bool hasreserve):
34 tx(_tx), nFee(_nFee), nTime(_nTime), dPriority(_dPriority), nHeight(_nHeight),
35 hadNoDependencies(poolHasNoInputsOf), hasReserve(hasreserve),
36 spendsCoinbase(_spendsCoinbase), nBranchId(_nBranchId)
38 nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
39 nModSize = tx.CalculateModifiedSize(nTxSize);
40 nUsageSize = RecursiveDynamicUsage(tx);
41 feeRate = CFeeRate(nFee, nTxSize);
44 CTxMemPoolEntry::CTxMemPoolEntry(const CTxMemPoolEntry& other)
50 CTxMemPoolEntry::GetPriority(unsigned int currentHeight) const
52 CAmount nValueIn = tx.GetValueOut()+nFee;
53 CCurrencyState currencyState;
56 nValueIn += currencyState.ReserveToNative(tx.GetReserveValueOut(currencyState));
58 double deltaPriority = ((double)(currentHeight-nHeight)*nValueIn)/nModSize;
59 double dResult = dPriority + deltaPriority;
63 CTxMemPool::CTxMemPool(const CFeeRate& _minRelayFee) :
64 nTransactionsUpdated(0)
66 // Sanity checks off by default for performance, because otherwise
67 // accepting transactions becomes O(N^2) where N is the number
68 // of transactions in the pool
71 minerPolicyEstimator = new CBlockPolicyEstimator(_minRelayFee);
74 CTxMemPool::~CTxMemPool()
76 delete minerPolicyEstimator;
79 void CTxMemPool::pruneSpent(const uint256 &hashTx, CCoins &coins)
83 std::map<COutPoint, CInPoint>::iterator it = mapNextTx.lower_bound(COutPoint(hashTx, 0));
85 // iterate over all COutPoints in mapNextTx whose hash equals the provided hashTx
86 while (it != mapNextTx.end() && it->first.hash == hashTx) {
87 coins.Spend(it->first.n); // and remove those outputs from coins
92 unsigned int CTxMemPool::GetTransactionsUpdated() const
95 return nTransactionsUpdated;
98 void CTxMemPool::AddTransactionsUpdated(unsigned int n)
101 nTransactionsUpdated += n;
105 bool CTxMemPool::addUnchecked(const uint256& hash, const CTxMemPoolEntry &entry, bool fCurrentEstimate)
107 // Add to memory pool without checking anything.
108 // Used by main.cpp AcceptToMemoryPool(), which DOES do
109 // all the appropriate checks.
112 const CTransaction& tx = mapTx.find(hash)->GetTx();
113 if (!tx.IsCoinImport()) {
114 for (unsigned int i = 0; i < tx.vin.size(); i++)
115 mapNextTx[tx.vin[i].prevout] = CInPoint(&tx, i);
117 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
118 BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
119 mapSproutNullifiers[nf] = &tx;
122 for (const SpendDescription &spendDescription : tx.vShieldedSpend) {
123 mapSaplingNullifiers[spendDescription.nullifier] = &tx;
125 nTransactionsUpdated++;
126 totalTxSize += entry.GetTxSize();
127 cachedInnerUsage += entry.DynamicMemoryUsage();
128 minerPolicyEstimator->processTransaction(entry, fCurrentEstimate);
133 void CTxMemPool::addAddressIndex(const CTxMemPoolEntry &entry, const CCoinsViewCache &view)
136 const CTransaction& tx = entry.GetTx();
137 std::vector<CMempoolAddressDeltaKey> inserted;
139 uint256 txhash = tx.GetHash();
141 if (!tx.IsCoinBase())
143 for (unsigned int j = 0; j < tx.vin.size(); j++) {
144 const CTxIn input = tx.vin[j];
145 const CTxOut &prevout = view.GetOutputFor(input);
146 if (prevout.scriptPubKey.IsPayToScriptHash()) {
147 vector<unsigned char> hashBytes(prevout.scriptPubKey.begin()+2, prevout.scriptPubKey.begin()+22);
148 CMempoolAddressDeltaKey key(2, uint160(hashBytes), txhash, j, 1);
149 CMempoolAddressDelta delta(entry.GetTime(), prevout.nValue * -1, input.prevout.hash, input.prevout.n);
150 mapAddress.insert(make_pair(key, delta));
151 inserted.push_back(key);
153 else if (prevout.scriptPubKey.IsPayToPublicKeyHash()) {
154 vector<unsigned char> hashBytes(prevout.scriptPubKey.begin()+3, prevout.scriptPubKey.begin()+23);
155 CMempoolAddressDeltaKey key(1, uint160(hashBytes), txhash, j, 1);
156 CMempoolAddressDelta delta(entry.GetTime(), prevout.nValue * -1, input.prevout.hash, input.prevout.n);
157 mapAddress.insert(make_pair(key, delta));
158 inserted.push_back(key);
160 else if (prevout.scriptPubKey.IsPayToPublicKey()) {
161 vector<unsigned char> hashBytes(prevout.scriptPubKey.begin()+1, prevout.scriptPubKey.begin()+34);
162 CMempoolAddressDeltaKey key(1, Hash160(hashBytes), txhash, j, 1);
163 CMempoolAddressDelta delta(entry.GetTime(), prevout.nValue * -1, input.prevout.hash, input.prevout.n);
164 mapAddress.insert(make_pair(key, delta));
165 inserted.push_back(key);
167 else if (prevout.scriptPubKey.IsPayToCryptoCondition()) {
168 vector<unsigned char> hashBytes(prevout.scriptPubKey.begin(), prevout.scriptPubKey.end());
169 CMempoolAddressDeltaKey key(1, Hash160(hashBytes), txhash, j, 1);
170 CMempoolAddressDelta delta(entry.GetTime(), prevout.nValue * -1, input.prevout.hash, input.prevout.n);
171 mapAddress.insert(make_pair(key, delta));
172 inserted.push_back(key);
176 for (unsigned int k = 0; k < tx.vout.size(); k++) {
177 const CTxOut &out = tx.vout[k];
178 if (out.scriptPubKey.IsPayToScriptHash()) {
179 vector<unsigned char> hashBytes(out.scriptPubKey.begin()+2, out.scriptPubKey.begin()+22);
180 CMempoolAddressDeltaKey key(2, uint160(hashBytes), txhash, k, 0);
181 mapAddress.insert(make_pair(key, CMempoolAddressDelta(entry.GetTime(), out.nValue)));
182 inserted.push_back(key);
184 else if (out.scriptPubKey.IsPayToPublicKeyHash()) {
185 vector<unsigned char> hashBytes(out.scriptPubKey.begin()+3, out.scriptPubKey.begin()+23);
186 std::pair<addressDeltaMap::iterator,bool> ret;
187 CMempoolAddressDeltaKey key(1, uint160(hashBytes), txhash, k, 0);
188 mapAddress.insert(make_pair(key, CMempoolAddressDelta(entry.GetTime(), out.nValue)));
189 inserted.push_back(key);
191 else if (out.scriptPubKey.IsPayToPublicKey()) {
192 vector<unsigned char> hashBytes(out.scriptPubKey.begin()+1, out.scriptPubKey.begin()+34);
193 std::pair<addressDeltaMap::iterator,bool> ret;
194 CMempoolAddressDeltaKey key(1, Hash160(hashBytes), txhash, k, 0);
195 mapAddress.insert(make_pair(key, CMempoolAddressDelta(entry.GetTime(), out.nValue)));
196 inserted.push_back(key);
198 else if (out.scriptPubKey.IsPayToCryptoCondition()) {
199 vector<unsigned char> hashBytes(out.scriptPubKey.begin(), out.scriptPubKey.end());
200 std::pair<addressDeltaMap::iterator,bool> ret;
201 CMempoolAddressDeltaKey key(1, Hash160(hashBytes), txhash, k, 0);
202 mapAddress.insert(make_pair(key, CMempoolAddressDelta(entry.GetTime(), out.nValue)));
203 inserted.push_back(key);
207 mapAddressInserted.insert(make_pair(txhash, inserted));
210 bool CTxMemPool::getAddressIndex(std::vector<std::pair<uint160, int> > &addresses,
211 std::vector<std::pair<CMempoolAddressDeltaKey, CMempoolAddressDelta> > &results)
214 for (std::vector<std::pair<uint160, int> >::iterator it = addresses.begin(); it != addresses.end(); it++) {
215 addressDeltaMap::iterator ait = mapAddress.lower_bound(CMempoolAddressDeltaKey((*it).second, (*it).first));
216 while (ait != mapAddress.end() && (*ait).first.addressBytes == (*it).first && (*ait).first.type == (*it).second) {
217 results.push_back(*ait);
224 bool CTxMemPool::removeAddressIndex(const uint256 txhash)
227 addressDeltaMapInserted::iterator it = mapAddressInserted.find(txhash);
229 if (it != mapAddressInserted.end()) {
230 std::vector<CMempoolAddressDeltaKey> keys = (*it).second;
231 for (std::vector<CMempoolAddressDeltaKey>::iterator mit = keys.begin(); mit != keys.end(); mit++) {
232 mapAddress.erase(*mit);
234 mapAddressInserted.erase(it);
240 void CTxMemPool::addSpentIndex(const CTxMemPoolEntry &entry, const CCoinsViewCache &view)
244 const CTransaction& tx = entry.GetTx();
245 std::vector<CSpentIndexKey> inserted;
247 uint256 txhash = tx.GetHash();
248 for (unsigned int j = 0; j < tx.vin.size(); j++) {
249 const CTxIn input = tx.vin[j];
250 const CTxOut &prevout = view.GetOutputFor(input);
254 if (prevout.scriptPubKey.IsPayToScriptHash()) {
255 addressHash = uint160(vector<unsigned char> (prevout.scriptPubKey.begin()+2, prevout.scriptPubKey.begin()+22));
258 else if (prevout.scriptPubKey.IsPayToPublicKeyHash()) {
259 addressHash = uint160(vector<unsigned char> (prevout.scriptPubKey.begin()+3, prevout.scriptPubKey.begin()+23));
262 else if (prevout.scriptPubKey.IsPayToPublicKey()) {
263 addressHash = Hash160(vector<unsigned char> (prevout.scriptPubKey.begin()+1, prevout.scriptPubKey.begin()+34));
266 else if (prevout.scriptPubKey.IsPayToCryptoCondition()) {
267 addressHash = Hash160(vector<unsigned char> (prevout.scriptPubKey.begin(), prevout.scriptPubKey.end()));
271 addressHash.SetNull();
275 CSpentIndexKey key = CSpentIndexKey(input.prevout.hash, input.prevout.n);
276 CSpentIndexValue value = CSpentIndexValue(txhash, j, -1, prevout.nValue, addressType, addressHash);
278 mapSpent.insert(make_pair(key, value));
279 inserted.push_back(key);
283 mapSpentInserted.insert(make_pair(txhash, inserted));
286 bool CTxMemPool::getSpentIndex(CSpentIndexKey &key, CSpentIndexValue &value)
289 mapSpentIndex::iterator it;
291 it = mapSpent.find(key);
292 if (it != mapSpent.end()) {
299 bool CTxMemPool::removeSpentIndex(const uint256 txhash)
302 mapSpentIndexInserted::iterator it = mapSpentInserted.find(txhash);
304 if (it != mapSpentInserted.end()) {
305 std::vector<CSpentIndexKey> keys = (*it).second;
306 for (std::vector<CSpentIndexKey>::iterator mit = keys.begin(); mit != keys.end(); mit++) {
307 mapSpent.erase(*mit);
309 mapSpentInserted.erase(it);
315 void CTxMemPool::remove(const CTransaction &origTx, std::list<CTransaction>& removed, bool fRecursive)
317 // Remove transaction from memory pool
320 std::deque<uint256> txToRemove;
321 txToRemove.push_back(origTx.GetHash());
322 if (fRecursive && !mapTx.count(origTx.GetHash())) {
323 // If recursively removing but origTx isn't in the mempool
324 // be sure to remove any children that are in the pool. This can
325 // happen during chain re-orgs if origTx isn't re-accepted into
326 // the mempool for any reason.
327 for (unsigned int i = 0; i < origTx.vout.size(); i++) {
328 std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(COutPoint(origTx.GetHash(), i));
329 if (it == mapNextTx.end())
331 txToRemove.push_back(it->second.ptx->GetHash());
334 while (!txToRemove.empty())
336 uint256 hash = txToRemove.front();
337 txToRemove.pop_front();
338 if (!mapTx.count(hash))
340 const CTransaction& tx = mapTx.find(hash)->GetTx();
342 for (unsigned int i = 0; i < tx.vout.size(); i++) {
343 std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(COutPoint(hash, i));
344 if (it == mapNextTx.end())
346 txToRemove.push_back(it->second.ptx->GetHash());
349 BOOST_FOREACH(const CTxIn& txin, tx.vin)
350 mapNextTx.erase(txin.prevout);
351 BOOST_FOREACH(const JSDescription& joinsplit, tx.vjoinsplit) {
352 BOOST_FOREACH(const uint256& nf, joinsplit.nullifiers) {
353 mapSproutNullifiers.erase(nf);
356 for (const SpendDescription &spendDescription : tx.vShieldedSpend) {
357 mapSaplingNullifiers.erase(spendDescription.nullifier);
359 removed.push_back(tx);
360 totalTxSize -= mapTx.find(hash)->GetTxSize();
361 cachedInnerUsage -= mapTx.find(hash)->DynamicMemoryUsage();
363 nTransactionsUpdated++;
364 minerPolicyEstimator->removeTx(hash);
365 removeAddressIndex(hash);
366 removeSpentIndex(hash);
367 ClearPrioritisation(tx.GetHash());
372 extern uint64_t ASSETCHAINS_TIMELOCKGTE;
373 int64_t komodo_block_unlocktime(uint32_t nHeight);
375 void CTxMemPool::removeForReorg(const CCoinsViewCache *pcoins, unsigned int nMemPoolHeight, int flags)
377 // Remove transactions spending a coinbase which are now immature
378 extern char ASSETCHAINS_SYMBOL[KOMODO_ASSETCHAIN_MAXLEN];
380 if ( ASSETCHAINS_SYMBOL[0] == 0 )
381 COINBASE_MATURITY = _COINBASE_MATURITY;
383 // Remove transactions spending a coinbase which are now immature and no-longer-final transactions
385 list<CTransaction> transactionsToRemove;
386 for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
387 const CTransaction& tx = it->GetTx();
388 if (!CheckFinalTx(tx, flags)) {
389 transactionsToRemove.push_back(tx);
390 } else if (it->GetSpendsCoinbase()) {
391 BOOST_FOREACH(const CTxIn& txin, tx.vin) {
392 indexed_transaction_set::const_iterator it2 = mapTx.find(txin.prevout.hash);
393 if (it2 != mapTx.end())
395 const CCoins *coins = pcoins->AccessCoins(txin.prevout.hash);
396 if (nCheckFrequency != 0) assert(coins);
398 if (!coins || (coins->IsCoinBase() &&
399 (((signed long)nMemPoolHeight) - coins->nHeight < COINBASE_MATURITY) ||
400 ((signed long)nMemPoolHeight < komodo_block_unlocktime(coins->nHeight) &&
401 coins->IsAvailable(0) && coins->vout[0].nValue >= ASSETCHAINS_TIMELOCKGTE))) {
402 transactionsToRemove.push_back(tx);
408 BOOST_FOREACH(const CTransaction& tx, transactionsToRemove) {
409 list<CTransaction> removed;
410 remove(tx, removed, true);
415 void CTxMemPool::removeWithAnchor(const uint256 &invalidRoot, ShieldedType type)
417 // If a block is disconnected from the tip, and the root changed,
418 // we must invalidate transactions from the mempool which spend
419 // from that root -- almost as though they were spending coinbases
420 // which are no longer valid to spend due to coinbase maturity.
422 list<CTransaction> transactionsToRemove;
424 for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
425 const CTransaction& tx = it->GetTx();
428 BOOST_FOREACH(const JSDescription& joinsplit, tx.vjoinsplit) {
429 if (joinsplit.anchor == invalidRoot) {
430 transactionsToRemove.push_back(tx);
436 BOOST_FOREACH(const SpendDescription& spendDescription, tx.vShieldedSpend) {
437 if (spendDescription.anchor == invalidRoot) {
438 transactionsToRemove.push_back(tx);
444 throw runtime_error("Unknown shielded type");
449 BOOST_FOREACH(const CTransaction& tx, transactionsToRemove) {
450 list<CTransaction> removed;
451 remove(tx, removed, true);
455 void CTxMemPool::removeConflicts(const CTransaction &tx, std::list<CTransaction>& removed)
457 // Remove transactions which depend on inputs of tx, recursively
458 list<CTransaction> result;
460 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
461 std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(txin.prevout);
462 if (it != mapNextTx.end()) {
463 const CTransaction &txConflict = *it->second.ptx;
464 if (txConflict != tx)
466 remove(txConflict, removed, true);
471 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
472 BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
473 std::map<uint256, const CTransaction*>::iterator it = mapSproutNullifiers.find(nf);
474 if (it != mapSproutNullifiers.end()) {
475 const CTransaction &txConflict = *it->second;
476 if (txConflict != tx) {
477 remove(txConflict, removed, true);
482 for (const SpendDescription &spendDescription : tx.vShieldedSpend) {
483 std::map<uint256, const CTransaction*>::iterator it = mapSaplingNullifiers.find(spendDescription.nullifier);
484 if (it != mapSaplingNullifiers.end()) {
485 const CTransaction &txConflict = *it->second;
486 if (txConflict != tx) {
487 remove(txConflict, removed, true);
493 int32_t komodo_validate_interest(const CTransaction &tx,int32_t txheight,uint32_t nTime,int32_t dispflag);
494 extern char ASSETCHAINS_SYMBOL[];
496 void CTxMemPool::removeExpired(unsigned int nBlockHeight)
498 CBlockIndex *tipindex;
499 // Remove expired txs from the mempool
501 list<CTransaction> transactionsToRemove;
502 for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++)
504 const CTransaction& tx = it->GetTx();
505 tipindex = chainActive.LastTip();
506 if (IsExpiredTx(tx, nBlockHeight) || (ASSETCHAINS_SYMBOL[0] == 0 && tipindex != 0 && komodo_validate_interest(tx,tipindex->GetHeight()+1,tipindex->GetMedianTimePast() + 777,0)) < 0)
508 transactionsToRemove.push_back(tx);
511 for (const CTransaction& tx : transactionsToRemove) {
512 list<CTransaction> removed;
513 remove(tx, removed, true);
514 LogPrint("mempool", "Removing expired txid: %s\n", tx.GetHash().ToString());
519 * Called when a block is connected. Removes from mempool and updates the miner fee estimator.
521 void CTxMemPool::removeForBlock(const std::vector<CTransaction>& vtx, unsigned int nBlockHeight,
522 std::list<CTransaction>& conflicts, bool fCurrentEstimate)
525 std::vector<CTxMemPoolEntry> entries;
526 BOOST_FOREACH(const CTransaction& tx, vtx)
528 uint256 hash = tx.GetHash();
530 indexed_transaction_set::iterator i = mapTx.find(hash);
531 if (i != mapTx.end())
532 entries.push_back(*i);
534 BOOST_FOREACH(const CTransaction& tx, vtx)
536 std::list<CTransaction> dummy;
537 remove(tx, dummy, false);
538 removeConflicts(tx, conflicts);
539 ClearPrioritisation(tx.GetHash());
541 // After the txs in the new block have been removed from the mempool, update policy estimates
542 minerPolicyEstimator->processBlock(nBlockHeight, entries, fCurrentEstimate);
546 * Called whenever the tip changes. Removes transactions which don't commit to
547 * the given branch ID from the mempool.
549 void CTxMemPool::removeWithoutBranchId(uint32_t nMemPoolBranchId)
552 std::list<CTransaction> transactionsToRemove;
554 for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
555 const CTransaction& tx = it->GetTx();
556 if (it->GetValidatedBranchId() != nMemPoolBranchId) {
557 transactionsToRemove.push_back(tx);
561 for (const CTransaction& tx : transactionsToRemove) {
562 std::list<CTransaction> removed;
563 remove(tx, removed, true);
567 void CTxMemPool::clear()
573 cachedInnerUsage = 0;
574 ++nTransactionsUpdated;
577 void CTxMemPool::check(const CCoinsViewCache *pcoins) const
579 if (nCheckFrequency == 0)
582 if (insecure_rand() >= nCheckFrequency)
585 LogPrint("mempool", "Checking mempool with %u transactions and %u inputs\n", (unsigned int)mapTx.size(), (unsigned int)mapNextTx.size());
587 uint64_t checkTotal = 0;
588 uint64_t innerUsage = 0;
590 CCoinsViewCache mempoolDuplicate(const_cast<CCoinsViewCache*>(pcoins));
591 const int64_t nSpendHeight = GetSpendHeight(mempoolDuplicate);
594 list<const CTxMemPoolEntry*> waitingOnDependants;
595 for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
597 checkTotal += it->GetTxSize();
598 innerUsage += it->DynamicMemoryUsage();
599 const CTransaction& tx = it->GetTx();
600 bool fDependsWait = false;
601 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
602 // Check that every mempool transaction's inputs refer to available coins, or other mempool tx's.
603 indexed_transaction_set::const_iterator it2 = mapTx.find(txin.prevout.hash);
604 if (it2 != mapTx.end()) {
605 const CTransaction& tx2 = it2->GetTx();
606 assert(tx2.vout.size() > txin.prevout.n && !tx2.vout[txin.prevout.n].IsNull());
609 const CCoins* coins = pcoins->AccessCoins(txin.prevout.hash);
610 assert(coins && coins->IsAvailable(txin.prevout.n));
612 // Check whether its inputs are marked in mapNextTx.
613 std::map<COutPoint, CInPoint>::const_iterator it3 = mapNextTx.find(txin.prevout);
614 assert(it3 != mapNextTx.end());
615 assert(it3->second.ptx == &tx);
616 assert(it3->second.n == i);
620 boost::unordered_map<uint256, SproutMerkleTree, CCoinsKeyHasher> intermediates;
622 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
623 BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
624 assert(!pcoins->GetNullifier(nf, SPROUT));
627 SproutMerkleTree tree;
628 auto it = intermediates.find(joinsplit.anchor);
629 if (it != intermediates.end()) {
632 assert(pcoins->GetSproutAnchorAt(joinsplit.anchor, tree));
635 BOOST_FOREACH(const uint256& commitment, joinsplit.commitments)
637 tree.append(commitment);
640 intermediates.insert(std::make_pair(tree.root(), tree));
642 for (const SpendDescription &spendDescription : tx.vShieldedSpend) {
643 SaplingMerkleTree tree;
645 assert(pcoins->GetSaplingAnchorAt(spendDescription.anchor, tree));
646 assert(!pcoins->GetNullifier(spendDescription.nullifier, SAPLING));
649 waitingOnDependants.push_back(&(*it));
651 CValidationState state;
652 bool fCheckResult = tx.IsCoinBase() ||
653 Consensus::CheckTxInputs(tx, state, mempoolDuplicate, nSpendHeight, Params().GetConsensus());
654 assert(fCheckResult);
655 UpdateCoins(tx, mempoolDuplicate, 1000000);
658 unsigned int stepsSinceLastRemove = 0;
659 while (!waitingOnDependants.empty()) {
660 const CTxMemPoolEntry* entry = waitingOnDependants.front();
661 waitingOnDependants.pop_front();
662 CValidationState state;
663 if (!mempoolDuplicate.HaveInputs(entry->GetTx())) {
664 waitingOnDependants.push_back(entry);
665 stepsSinceLastRemove++;
666 assert(stepsSinceLastRemove < waitingOnDependants.size());
668 bool fCheckResult = entry->GetTx().IsCoinBase() ||
669 Consensus::CheckTxInputs(entry->GetTx(), state, mempoolDuplicate, nSpendHeight, Params().GetConsensus());
670 assert(fCheckResult);
671 UpdateCoins(entry->GetTx(), mempoolDuplicate, 1000000);
672 stepsSinceLastRemove = 0;
675 for (std::map<COutPoint, CInPoint>::const_iterator it = mapNextTx.begin(); it != mapNextTx.end(); it++) {
676 uint256 hash = it->second.ptx->GetHash();
677 indexed_transaction_set::const_iterator it2 = mapTx.find(hash);
678 const CTransaction& tx = it2->GetTx();
679 assert(it2 != mapTx.end());
680 assert(&tx == it->second.ptx);
681 assert(tx.vin.size() > it->second.n);
682 assert(it->first == it->second.ptx->vin[it->second.n].prevout);
685 checkNullifiers(SPROUT);
686 checkNullifiers(SAPLING);
688 assert(totalTxSize == checkTotal);
689 assert(innerUsage == cachedInnerUsage);
692 void CTxMemPool::checkNullifiers(ShieldedType type) const
694 const std::map<uint256, const CTransaction*>* mapToUse;
697 mapToUse = &mapSproutNullifiers;
700 mapToUse = &mapSaplingNullifiers;
703 throw runtime_error("Unknown nullifier type");
705 for (const auto& entry : *mapToUse) {
706 uint256 hash = entry.second->GetHash();
707 CTxMemPool::indexed_transaction_set::const_iterator findTx = mapTx.find(hash);
708 const CTransaction& tx = findTx->GetTx();
709 assert(findTx != mapTx.end());
710 assert(&tx == entry.second);
714 void CTxMemPool::queryHashes(vector<uint256>& vtxid)
719 vtxid.reserve(mapTx.size());
720 for (indexed_transaction_set::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
721 vtxid.push_back(mi->GetTx().GetHash());
724 bool CTxMemPool::lookup(uint256 hash, CTransaction& result) const
727 indexed_transaction_set::const_iterator i = mapTx.find(hash);
728 if (i == mapTx.end()) return false;
733 CFeeRate CTxMemPool::estimateFee(int nBlocks) const
736 return minerPolicyEstimator->estimateFee(nBlocks);
738 double CTxMemPool::estimatePriority(int nBlocks) const
741 return minerPolicyEstimator->estimatePriority(nBlocks);
745 CTxMemPool::WriteFeeEstimates(CAutoFile& fileout) const
749 fileout << 109900; // version required to read: 0.10.99 or later
750 fileout << CLIENT_VERSION; // version that wrote the file
751 minerPolicyEstimator->Write(fileout);
753 catch (const std::exception&) {
754 LogPrintf("CTxMemPool::WriteFeeEstimates(): unable to write policy estimator data (non-fatal)\n");
761 CTxMemPool::ReadFeeEstimates(CAutoFile& filein)
764 int nVersionRequired, nVersionThatWrote;
765 filein >> nVersionRequired >> nVersionThatWrote;
766 if (nVersionRequired > CLIENT_VERSION)
767 return error("CTxMemPool::ReadFeeEstimates(): up-version (%d) fee estimate file", nVersionRequired);
770 minerPolicyEstimator->Read(filein);
772 catch (const std::exception&) {
773 LogPrintf("CTxMemPool::ReadFeeEstimates(): unable to read policy estimator data (non-fatal)\n");
779 void CTxMemPool::PrioritiseTransaction(const uint256 &hash, const string strHash, double dPriorityDelta, const CAmount& nFeeDelta)
783 std::pair<double, CAmount> &deltas = mapDeltas[hash];
784 deltas.first += dPriorityDelta;
785 deltas.second += nFeeDelta;
787 LogPrintf("PrioritiseTransaction: %s priority += %f, fee += %d\n", strHash, dPriorityDelta, FormatMoney(nFeeDelta));
790 void CTxMemPool::ApplyDeltas(const uint256 hash, double &dPriorityDelta, CAmount &nFeeDelta)
793 std::map<uint256, std::pair<double, CAmount> >::iterator pos = mapDeltas.find(hash);
794 if (pos == mapDeltas.end())
796 const std::pair<double, CAmount> &deltas = pos->second;
797 dPriorityDelta += deltas.first;
798 nFeeDelta += deltas.second;
801 void CTxMemPool::ClearPrioritisation(const uint256 hash)
804 mapDeltas.erase(hash);
805 mapReserveTransactions.erase(hash);
808 bool CTxMemPool::PrioritiseReserveTransaction(const CReserveTransactionDescriptor &txDesc, const CCurrencyState ¤cyState)
811 uint256 hash = txDesc.ptx->GetHash();
812 auto it = mapReserveTransactions.find(hash);
813 if (txDesc.IsValid())
815 mapReserveTransactions[hash] = txDesc;
816 PrioritiseTransaction(hash, hash.GetHex().c_str(), currencyState.ReserveToNative(txDesc.ReserveFees()), currencyState.ReserveToNative(txDesc.ReserveFees()));
822 bool CTxMemPool::IsKnownReserveTransaction(const uint256 &hash, CReserveTransactionDescriptor &txDesc)
825 auto it = mapReserveTransactions.find(hash);
826 if (it != mapReserveTransactions.end() && it->second.IsValid())
828 // refresh transaction from mempool or delete it if not found (we may not need this at all)
829 indexed_transaction_set::const_iterator i = mapTx.find(hash);
830 if (i == mapTx.end())
832 ClearPrioritisation(hash);
836 it->second.ptx = &(i->GetTx());
845 bool CTxMemPool::HasNoInputsOf(const CTransaction &tx) const
847 for (unsigned int i = 0; i < tx.vin.size(); i++)
848 if (exists(tx.vin[i].prevout.hash))
853 bool CTxMemPool::nullifierExists(const uint256& nullifier, ShieldedType type) const
857 return mapSproutNullifiers.count(nullifier);
859 return mapSaplingNullifiers.count(nullifier);
861 throw runtime_error("Unknown nullifier type");
865 CCoinsViewMemPool::CCoinsViewMemPool(CCoinsView *baseIn, CTxMemPool &mempoolIn) : CCoinsViewBacked(baseIn), mempool(mempoolIn) { }
867 bool CCoinsViewMemPool::GetNullifier(const uint256 &nf, ShieldedType type) const
869 return mempool.nullifierExists(nf, type) || base->GetNullifier(nf, type);
872 bool CCoinsViewMemPool::GetCoins(const uint256 &txid, CCoins &coins) const {
873 // If an entry in the mempool exists, always return that one, as it's guaranteed to never
874 // conflict with the underlying cache, and it cannot have pruned entries (as it contains full)
875 // transactions. First checking the underlying cache risks returning a pruned entry instead.
877 if (mempool.lookup(txid, tx)) {
878 coins = CCoins(tx, MEMPOOL_HEIGHT);
881 return (base->GetCoins(txid, coins) && !coins.IsPruned());
884 bool CCoinsViewMemPool::HaveCoins(const uint256 &txid) const {
885 return mempool.exists(txid) || base->HaveCoins(txid);
888 size_t CTxMemPool::DynamicMemoryUsage() const {
890 // Estimate the overhead of mapTx to be 6 pointers + an allocation, as no exact formula for boost::multi_index_contained is implemented.
891 return memusage::MallocUsage(sizeof(CTxMemPoolEntry) + 6 * sizeof(void*)) * mapTx.size() + memusage::DynamicUsage(mapNextTx) + memusage::DynamicUsage(mapDeltas) + memusage::DynamicUsage(mapDeltas) + memusage::DynamicUsage(mapDeltas) + cachedInnerUsage;