]> Git Repo - VerusCoin.git/blob - src/txmempool.cpp
Incorporate all Zcash updates through 2.0.7-3 in addition to PBaaS, reserves, etc.
[VerusCoin.git] / src / txmempool.cpp
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 .
5
6 #include "txmempool.h"
7
8 #include "clientversion.h"
9 #include "consensus/consensus.h"
10 #include "consensus/validation.h"
11 #include "main.h"
12 #include "policy/fees.h"
13 #include "streams.h"
14 #include "timedata.h"
15 #include "util.h"
16 #include "utilmoneystr.h"
17 #include "validationinterface.h"
18 #include "version.h"
19 #include "pbaas/pbaas.h"
20 #define _COINBASE_MATURITY 100
21
22 using namespace std;
23
24 CTxMemPoolEntry::CTxMemPoolEntry():
25     nFee(0), nTxSize(0), nModSize(0), nUsageSize(0), nTime(0), dPriority(0.0),
26     hadNoDependencies(false), spendsCoinbase(false), hasReserve(false)
27 {
28     nHeight = MEMPOOL_HEIGHT;
29 }
30
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)
38 {
39     nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
40     nModSize = tx.CalculateModifiedSize(nTxSize);
41     nUsageSize = RecursiveDynamicUsage(tx);
42     feeRate = CFeeRate(nFee, nTxSize);
43 }
44
45 CTxMemPoolEntry::CTxMemPoolEntry(const CTxMemPoolEntry& other)
46 {
47     *this = other;
48 }
49
50 double
51 CTxMemPoolEntry::GetPriority(unsigned int currentHeight) const
52 {
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())
57     {
58         nValueIn += currencyState.ReserveToNative(tx.GetReserveValueOut());
59     }
60     double deltaPriority = ((double)(currentHeight-nHeight)*nValueIn)/nModSize;
61     double dResult = dPriority + deltaPriority;
62     return dResult;
63 }
64
65 CTxMemPool::CTxMemPool(const CFeeRate& _minRelayFee) :
66     nTransactionsUpdated(0)
67 {
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
71     nCheckFrequency = 0;
72
73     minerPolicyEstimator = new CBlockPolicyEstimator(_minRelayFee);
74 }
75
76 CTxMemPool::~CTxMemPool()
77 {
78     delete minerPolicyEstimator;
79 }
80
81 void CTxMemPool::pruneSpent(const uint256 &hashTx, CCoins &coins)
82 {
83     LOCK(cs);
84
85     std::map<COutPoint, CInPoint>::iterator it = mapNextTx.lower_bound(COutPoint(hashTx, 0));
86
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
90         it++;
91     }
92 }
93
94 unsigned int CTxMemPool::GetTransactionsUpdated() const
95 {
96     LOCK(cs);
97     return nTransactionsUpdated;
98 }
99
100 void CTxMemPool::AddTransactionsUpdated(unsigned int n)
101 {
102     LOCK(cs);
103     nTransactionsUpdated += n;
104 }
105
106
107 bool CTxMemPool::addUnchecked(const uint256& hash, const CTxMemPoolEntry &entry, bool fCurrentEstimate)
108 {
109     // Add to memory pool without checking anything.
110     // Used by main.cpp AcceptToMemoryPool(), which DOES do
111     // all the appropriate checks.
112     LOCK(cs);
113     mapTx.insert(entry);
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);
120     }
121     BOOST_FOREACH(const JSDescription &joinsplit, tx.vJoinSplit) {
122         BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
123             mapSproutNullifiers[nf] = &tx;
124         }
125     }
126     for (const SpendDescription &spendDescription : tx.vShieldedSpend) {
127         mapSaplingNullifiers[spendDescription.nullifier] = &tx;
128     }
129     nTransactionsUpdated++;
130     totalTxSize += entry.GetTxSize();
131     cachedInnerUsage += entry.DynamicMemoryUsage();
132     minerPolicyEstimator->processTransaction(entry, fCurrentEstimate);
133
134     return true;
135 }
136
137 void CTxMemPool::addAddressIndex(const CTxMemPoolEntry &entry, const CCoinsViewCache &view)
138 {
139     LOCK(cs);
140     const CTransaction& tx = entry.GetTx();
141     std::vector<CMempoolAddressDeltaKey> inserted;
142
143     uint256 txhash = tx.GetHash();
144     if (!tx.IsCoinBase())
145     {
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)
151                 continue;
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);
156         }
157     }
158
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)
163             continue;
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);
167     }
168
169     mapAddressInserted.insert(make_pair(txhash, inserted));
170 }
171
172 bool CTxMemPool::getAddressIndex(const std::vector<std::pair<uint160, int> > &addresses, std::vector<std::pair<CMempoolAddressDeltaKey, CMempoolAddressDelta> > &results)
173 {
174     LOCK(cs);
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);
179             ait++;
180         }
181     }
182     return true;
183 }
184
185 bool CTxMemPool::removeAddressIndex(const uint256 txhash)
186 {
187     LOCK(cs);
188     auto it = mapAddressInserted.find(txhash);
189
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);
194         }
195         mapAddressInserted.erase(it);
196     }
197
198     return true;
199 }
200
201 void CTxMemPool::addSpentIndex(const CTxMemPoolEntry &entry, const CCoinsViewCache &view)
202 {
203     LOCK(cs);
204     const CTransaction& tx = entry.GetTx();
205     uint256 txhash = tx.GetHash();
206     std::vector<CSpentIndexKey> inserted;
207
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);
217     }
218     mapSpentInserted.insert(make_pair(txhash, inserted));
219 }
220
221 bool CTxMemPool::getSpentIndex(const CSpentIndexKey &key, CSpentIndexValue &value)
222 {
223     LOCK(cs);
224     std::map<CSpentIndexKey, CSpentIndexValue, CSpentIndexKeyCompare>::iterator it = mapSpent.find(key);
225     if (it != mapSpent.end()) {
226         value = it->second;
227         return true;
228     }
229     return false;
230 }
231
232 bool CTxMemPool::removeSpentIndex(const uint256 txhash)
233 {
234     LOCK(cs);
235     auto it = mapSpentInserted.find(txhash);
236
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);
241         }
242         mapSpentInserted.erase(it);
243     }
244
245     return true;
246 }
247
248 void CTxMemPool::remove(const CTransaction &origTx, std::list<CTransaction>& removed, bool fRecursive)
249 {
250     // Remove transaction from memory pool
251     {
252         LOCK(cs);
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())
263                     continue;
264                 txToRemove.push_back(it->second.ptx->GetHash());
265             }
266         }
267         while (!txToRemove.empty())
268         {
269             uint256 hash = txToRemove.front();
270             txToRemove.pop_front();
271             if (!mapTx.count(hash))
272                 continue;
273             const CTransaction& tx = mapTx.find(hash)->GetTx();
274             if (fRecursive) {
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())
278                         continue;
279                     txToRemove.push_back(it->second.ptx->GetHash());
280                 }
281             }
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);
288                 }
289             }
290             for (const SpendDescription &spendDescription : tx.vShieldedSpend) {
291                 mapSaplingNullifiers.erase(spendDescription.nullifier);
292             }
293             removed.push_back(tx);
294             totalTxSize -= mapTx.find(hash)->GetTxSize();
295             cachedInnerUsage -= mapTx.find(hash)->DynamicMemoryUsage();
296             mapTx.erase(hash);
297             nTransactionsUpdated++;
298             minerPolicyEstimator->removeTx(hash);
299             if (fAddressIndex)
300                 removeAddressIndex(hash);
301             if (fSpentIndex)
302                 removeSpentIndex(hash);
303             ClearPrioritisation(tx.GetHash());
304         }
305     }
306 }
307
308 extern uint64_t ASSETCHAINS_TIMELOCKGTE;
309 int64_t komodo_block_unlocktime(uint32_t nHeight);
310
311 void CTxMemPool::removeForReorg(const CCoinsViewCache *pcoins, unsigned int nMemPoolHeight, int flags)
312 {
313     // Remove transactions spending a coinbase which are now immature
314     extern char ASSETCHAINS_SYMBOL[KOMODO_ASSETCHAIN_MAXLEN];
315
316     if ( ASSETCHAINS_SYMBOL[0] == 0 )
317         COINBASE_MATURITY = _COINBASE_MATURITY;
318
319     // Remove transactions spending a coinbase which are now immature and no-longer-final transactions
320     LOCK(cs);
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())
330                     continue;
331                 const CCoins *coins = pcoins->AccessCoins(txin.prevout.hash);
332                         if (nCheckFrequency != 0) assert(coins);
333
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);
339                     break;
340                 }
341             }
342         }
343     }
344     BOOST_FOREACH(const CTransaction& tx, transactionsToRemove) {
345         list<CTransaction> removed;
346         remove(tx, removed, true);
347     }
348 }
349
350
351 void CTxMemPool::removeWithAnchor(const uint256 &invalidRoot, ShieldedType type)
352 {
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.
357     LOCK(cs);
358     list<CTransaction> transactionsToRemove;
359
360     for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
361         const CTransaction& tx = it->GetTx();
362         switch (type) {
363             case SPROUT:
364                 BOOST_FOREACH(const JSDescription& joinsplit, tx.vJoinSplit) {
365                     if (joinsplit.anchor == invalidRoot) {
366                         transactionsToRemove.push_back(tx);
367                         break;
368                     }
369                 }
370             break;
371             case SAPLING:
372                 BOOST_FOREACH(const SpendDescription& spendDescription, tx.vShieldedSpend) {
373                     if (spendDescription.anchor == invalidRoot) {
374                         transactionsToRemove.push_back(tx);
375                         break;
376                     }
377                 }
378             break;
379             default:
380                 throw runtime_error("Unknown shielded type");
381             break;
382         }
383     }
384
385     BOOST_FOREACH(const CTransaction& tx, transactionsToRemove) {
386         list<CTransaction> removed;
387         remove(tx, removed, true);
388     }
389 }
390
391 void CTxMemPool::removeConflicts(const CTransaction &tx, std::list<CTransaction>& removed)
392 {
393     // Remove transactions which depend on inputs of tx, recursively
394     list<CTransaction> result;
395     LOCK(cs);
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)
401             {
402                 remove(txConflict, removed, true);
403             }
404         }
405     }
406
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);
414                 }
415             }
416         }
417     }
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);
424             }
425         }
426     }
427 }
428
429 int32_t komodo_validate_interest(const CTransaction &tx,int32_t txheight,uint32_t nTime,int32_t dispflag);
430 extern char ASSETCHAINS_SYMBOL[];
431
432 void CTxMemPool::removeExpired(unsigned int nBlockHeight)
433 {
434     CBlockIndex *tipindex;
435     // Remove expired txs from the mempool
436     LOCK(cs);
437     list<CTransaction> transactionsToRemove;
438     for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++)
439     {
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)
443         {
444             transactionsToRemove.push_back(tx);
445         }
446     }
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());
451     }
452 }
453
454 /**
455  * Called when a block is connected. Removes from mempool and updates the miner fee estimator.
456  */
457 void CTxMemPool::removeForBlock(const std::vector<CTransaction>& vtx, unsigned int nBlockHeight,
458                                 std::list<CTransaction>& conflicts, bool fCurrentEstimate)
459 {
460     LOCK(cs);
461     std::vector<CTxMemPoolEntry> entries;
462     BOOST_FOREACH(const CTransaction& tx, vtx)
463     {
464         uint256 hash = tx.GetHash();
465
466         indexed_transaction_set::iterator i = mapTx.find(hash);
467         if (i != mapTx.end())
468             entries.push_back(*i);
469     }
470     BOOST_FOREACH(const CTransaction& tx, vtx)
471     {
472         std::list<CTransaction> dummy;
473         remove(tx, dummy, false);
474         removeConflicts(tx, conflicts);
475         ClearPrioritisation(tx.GetHash());
476     }
477     // After the txs in the new block have been removed from the mempool, update policy estimates
478     minerPolicyEstimator->processBlock(nBlockHeight, entries, fCurrentEstimate);
479 }
480
481 /**
482  * Called whenever the tip changes. Removes transactions which don't commit to
483  * the given branch ID from the mempool.
484  */
485 void CTxMemPool::removeWithoutBranchId(uint32_t nMemPoolBranchId)
486 {
487     LOCK(cs);
488     std::list<CTransaction> transactionsToRemove;
489
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);
494         }
495     }
496
497     for (const CTransaction& tx : transactionsToRemove) {
498         std::list<CTransaction> removed;
499         remove(tx, removed, true);
500     }
501 }
502
503 void CTxMemPool::clear()
504 {
505     LOCK(cs);
506     mapTx.clear();
507     mapNextTx.clear();
508     totalTxSize = 0;
509     cachedInnerUsage = 0;
510     ++nTransactionsUpdated;
511 }
512
513 void CTxMemPool::check(const CCoinsViewCache *pcoins) const
514 {
515     if (nCheckFrequency == 0)
516         return;
517
518     if (insecure_rand() >= nCheckFrequency)
519         return;
520
521     LogPrint("mempool", "Checking mempool with %u transactions and %u inputs\n", (unsigned int)mapTx.size(), (unsigned int)mapNextTx.size());
522
523     uint64_t checkTotal = 0;
524     uint64_t innerUsage = 0;
525
526     CCoinsViewCache mempoolDuplicate(const_cast<CCoinsViewCache*>(pcoins));
527     const int64_t nSpendHeight = GetSpendHeight(mempoolDuplicate);
528
529     LOCK(cs);
530     list<const CTxMemPoolEntry*> waitingOnDependants;
531     for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
532         unsigned int i = 0;
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());
543                 fDependsWait = true;
544             } else {
545                 const CCoins* coins = pcoins->AccessCoins(txin.prevout.hash);
546                 assert(coins && coins->IsAvailable(txin.prevout.n));
547             }
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);
553             i++;
554         }
555
556         boost::unordered_map<uint256, SproutMerkleTree, CCoinsKeyHasher> intermediates;
557
558         BOOST_FOREACH(const JSDescription &joinsplit, tx.vJoinSplit) {
559             BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
560                 assert(!pcoins->GetNullifier(nf, SPROUT));
561             }
562
563             SproutMerkleTree tree;
564             auto it = intermediates.find(joinsplit.anchor);
565             if (it != intermediates.end()) {
566                 tree = it->second;
567             } else {
568                 assert(pcoins->GetSproutAnchorAt(joinsplit.anchor, tree));
569             }
570
571             BOOST_FOREACH(const uint256& commitment, joinsplit.commitments)
572             {
573                 tree.append(commitment);
574             }
575
576             intermediates.insert(std::make_pair(tree.root(), tree));
577         }
578         for (const SpendDescription &spendDescription : tx.vShieldedSpend) {
579             SaplingMerkleTree tree;
580
581             assert(pcoins->GetSaplingAnchorAt(spendDescription.anchor, tree));
582             assert(!pcoins->GetNullifier(spendDescription.nullifier, SAPLING));
583         }
584         if (fDependsWait)
585             waitingOnDependants.push_back(&(*it));
586         else {
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);
592         }
593     }
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());
603         } else {
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;
609         }
610     }
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);
619     }
620
621     checkNullifiers(SPROUT);
622     checkNullifiers(SAPLING);
623
624     assert(totalTxSize == checkTotal);
625     assert(innerUsage == cachedInnerUsage);
626 }
627
628 void CTxMemPool::checkNullifiers(ShieldedType type) const
629 {
630     const std::map<uint256, const CTransaction*>* mapToUse;
631     switch (type) {
632         case SPROUT:
633             mapToUse = &mapSproutNullifiers;
634             break;
635         case SAPLING:
636             mapToUse = &mapSaplingNullifiers;
637             break;
638         default:
639             throw runtime_error("Unknown nullifier type");
640     }
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);
647     }
648 }
649
650 void CTxMemPool::queryHashes(vector<uint256>& vtxid)
651 {
652     vtxid.clear();
653
654     LOCK(cs);
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());
658 }
659
660 bool CTxMemPool::lookup(uint256 hash, CTransaction& result) const
661 {
662     LOCK(cs);
663     indexed_transaction_set::const_iterator i = mapTx.find(hash);
664     if (i == mapTx.end()) return false;
665     result = i->GetTx();
666     return true;
667 }
668
669 CFeeRate CTxMemPool::estimateFee(int nBlocks) const
670 {
671     LOCK(cs);
672     return minerPolicyEstimator->estimateFee(nBlocks);
673 }
674 double CTxMemPool::estimatePriority(int nBlocks) const
675 {
676     LOCK(cs);
677     return minerPolicyEstimator->estimatePriority(nBlocks);
678 }
679
680 bool
681 CTxMemPool::WriteFeeEstimates(CAutoFile& fileout) const
682 {
683     try {
684         LOCK(cs);
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);
688     }
689     catch (const std::exception&) {
690         LogPrintf("CTxMemPool::WriteFeeEstimates(): unable to write policy estimator data (non-fatal)\n");
691         return false;
692     }
693     return true;
694 }
695
696 bool
697 CTxMemPool::ReadFeeEstimates(CAutoFile& filein)
698 {
699     try {
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);
704
705         LOCK(cs);
706         minerPolicyEstimator->Read(filein);
707     }
708     catch (const std::exception&) {
709         LogPrintf("CTxMemPool::ReadFeeEstimates(): unable to read policy estimator data (non-fatal)\n");
710         return false;
711     }
712     return true;
713 }
714
715 void CTxMemPool::PrioritiseTransaction(const uint256 &hash, const string strHash, double dPriorityDelta, const CAmount& nFeeDelta)
716 {
717     {
718         LOCK(cs);
719         std::pair<double, CAmount> &deltas = mapDeltas[hash];
720         deltas.first += dPriorityDelta;
721         deltas.second += nFeeDelta;
722     }
723     LogPrintf("PrioritiseTransaction: %s priority += %f, fee += %d\n", strHash, dPriorityDelta, FormatMoney(nFeeDelta));
724 }
725
726 void CTxMemPool::ApplyDeltas(const uint256 hash, double &dPriorityDelta, CAmount &nFeeDelta)
727 {
728     LOCK(cs);
729     std::map<uint256, std::pair<double, CAmount> >::iterator pos = mapDeltas.find(hash);
730     if (pos == mapDeltas.end())
731         return;
732     const std::pair<double, CAmount> &deltas = pos->second;
733     dPriorityDelta += deltas.first;
734     nFeeDelta += deltas.second;
735 }
736
737 void CTxMemPool::ClearPrioritisation(const uint256 hash)
738 {
739     LOCK(cs);
740     mapDeltas.erase(hash);
741     mapReserveTransactions.erase(hash);
742 }
743
744 bool CTxMemPool::PrioritiseReserveTransaction(const CReserveTransactionDescriptor &txDesc, const CCurrencyState &currencyState)
745 {
746     LOCK(cs);
747     uint256 hash = txDesc.ptx->GetHash();
748     auto it = mapReserveTransactions.find(hash);
749     if (txDesc.IsValid())
750     {
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);
754         return true;
755     }
756     return false;
757 }
758
759 bool CTxMemPool::IsKnownReserveTransaction(const uint256 &hash, CReserveTransactionDescriptor &txDesc)
760 {
761     LOCK(cs);
762     auto it = mapReserveTransactions.find(hash);
763     if (it != mapReserveTransactions.end() && it->second.IsValid())
764     {
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())
768         {
769             ClearPrioritisation(hash);
770         }
771         else
772         {
773             it->second.ptx = &(i->GetTx());
774
775             txDesc = it->second;
776             return true;
777         }
778     }
779     return false;
780 }
781
782 bool CTxMemPool::HasNoInputsOf(const CTransaction &tx) const
783 {
784     for (unsigned int i = 0; i < tx.vin.size(); i++)
785         if (exists(tx.vin[i].prevout.hash))
786             return false;
787     return true;
788 }
789
790 bool CTxMemPool::nullifierExists(const uint256& nullifier, ShieldedType type) const
791 {
792     switch (type) {
793         case SPROUT:
794             return mapSproutNullifiers.count(nullifier);
795         case SAPLING:
796             return mapSaplingNullifiers.count(nullifier);
797         default:
798             throw runtime_error("Unknown nullifier type");
799     }
800 }
801
802 void CTxMemPool::NotifyRecentlyAdded()
803 {
804     uint64_t recentlyAddedSequence;
805     std::vector<CTransaction> txs;
806     {
807         LOCK(cs);
808         recentlyAddedSequence = nRecentlyAddedSequence;
809         for (const auto& kv : mapRecentlyAddedTx) {
810             txs.push_back(*(kv.second));
811         }
812         mapRecentlyAddedTx.clear();
813     }
814
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) {
820         try {
821             SyncWithWallets(tx, NULL);
822         } catch (const boost::thread_interrupted&) {
823             throw;
824         } catch (const std::exception& e) {
825             PrintExceptionContinue(&e, "CTxMemPool::NotifyRecentlyAdded()");
826         } catch (...) {
827             PrintExceptionContinue(NULL, "CTxMemPool::NotifyRecentlyAdded()");
828         }
829     }
830
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") {
834         LOCK(cs);
835         nNotifiedSequence = recentlyAddedSequence;
836     }
837 }
838
839 bool CTxMemPool::IsFullyNotified() {
840     assert(Params().NetworkIDString() == "regtest");
841     LOCK(cs);
842     return nRecentlyAddedSequence == nNotifiedSequence;
843 }
844
845 CCoinsViewMemPool::CCoinsViewMemPool(CCoinsView *baseIn, CTxMemPool &mempoolIn) : CCoinsViewBacked(baseIn), mempool(mempoolIn) { }
846
847 bool CCoinsViewMemPool::GetNullifier(const uint256 &nf, ShieldedType type) const
848 {
849     return mempool.nullifierExists(nf, type) || base->GetNullifier(nf, type);
850 }
851
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.
856     CTransaction tx;
857     if (mempool.lookup(txid, tx)) {
858         coins = CCoins(tx, MEMPOOL_HEIGHT);
859         return true;
860     }
861     return (base->GetCoins(txid, coins) && !coins.IsPruned());
862 }
863
864 bool CCoinsViewMemPool::HaveCoins(const uint256 &txid) const {
865     return mempool.exists(txid) || base->HaveCoins(txid);
866 }
867
868 size_t CTxMemPool::DynamicMemoryUsage() const {
869     LOCK(cs);
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;
872 }
This page took 0.077253 seconds and 4 git commands to generate.