]> Git Repo - VerusCoin.git/blob - src/txmempool.cpp
Improve support for ID address differentiation and begin referral validation
[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
153             if (type == CScript::P2CC)
154             {
155                 std::vector<CTxDestination> dests = prevout.scriptPubKey.GetDestinations();
156                 for (auto dest : dests)
157                 {
158                     if (dest.which() != COptCCParams::ADDRTYPE_INVALID)
159                     {
160                         CMempoolAddressDeltaKey key(AddressTypeFromDest(dest), GetDestinationID(dest), 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);
164                     }
165                 }
166             }
167             else
168             {
169                 CMempoolAddressDeltaKey key(type, prevout.scriptPubKey.AddressHash(), 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);
173             }
174         }
175     }
176
177     for (unsigned int j = 0; j < tx.vout.size(); j++) {
178         const CTxOut &out = tx.vout[j];
179         CScript::ScriptType type = out.scriptPubKey.GetType();
180         if (type == CScript::UNKNOWN)
181             continue;
182
183
184         if (type == CScript::P2CC)
185         {
186             std::vector<CTxDestination> dests = out.scriptPubKey.GetDestinations();
187             for (auto dest : dests)
188             {
189                 if (dest.which() != COptCCParams::ADDRTYPE_INVALID)
190                 {
191                     CMempoolAddressDeltaKey key(AddressTypeFromDest(dest), GetDestinationID(dest), txhash, j, 0);
192                     mapAddress.insert(make_pair(key, CMempoolAddressDelta(entry.GetTime(), out.nValue)));
193                     inserted.push_back(key);
194                 }
195             }
196         }
197         else
198         {
199             CMempoolAddressDeltaKey key(type, out.scriptPubKey.AddressHash(), txhash, j, 0);
200             mapAddress.insert(make_pair(key, CMempoolAddressDelta(entry.GetTime(), out.nValue)));
201             inserted.push_back(key);
202         }
203     }
204
205     mapAddressInserted.insert(make_pair(txhash, inserted));
206 }
207
208 bool CTxMemPool::getAddressIndex(const std::vector<std::pair<uint160, int> > &addresses, std::vector<std::pair<CMempoolAddressDeltaKey, CMempoolAddressDelta> > &results)
209 {
210     LOCK(cs);
211     for (std::vector<std::pair<uint160, int> >::const_iterator it = addresses.begin(); it != addresses.end(); it++) {
212         auto ait = mapAddress.lower_bound(CMempoolAddressDeltaKey((*it).second, (*it).first));
213         while (ait != mapAddress.end() && (*ait).first.addressBytes == (*it).first && (*ait).first.type == (*it).second) {
214             results.push_back(*ait);
215             ait++;
216         }
217     }
218     return true;
219 }
220
221 bool CTxMemPool::removeAddressIndex(const uint256 txhash)
222 {
223     LOCK(cs);
224     auto it = mapAddressInserted.find(txhash);
225
226     if (it != mapAddressInserted.end()) {
227         std::vector<CMempoolAddressDeltaKey> keys = (*it).second;
228         for (std::vector<CMempoolAddressDeltaKey>::iterator mit = keys.begin(); mit != keys.end(); mit++) {
229             mapAddress.erase(*mit);
230         }
231         mapAddressInserted.erase(it);
232     }
233
234     return true;
235 }
236
237 void CTxMemPool::addSpentIndex(const CTxMemPoolEntry &entry, const CCoinsViewCache &view)
238 {
239     LOCK(cs);
240     const CTransaction& tx = entry.GetTx();
241     uint256 txhash = tx.GetHash();
242     std::vector<CSpentIndexKey> inserted;
243
244     for (unsigned int j = 0; j < tx.vin.size(); j++) {
245         const CTxIn input = tx.vin[j];
246         const CTxOut &prevout = view.GetOutputFor(input);
247         CSpentIndexKey key = CSpentIndexKey(input.prevout.hash, input.prevout.n);
248         CSpentIndexValue value = CSpentIndexValue(txhash, j, -1, prevout.nValue,
249             prevout.scriptPubKey.GetType(),
250             prevout.scriptPubKey.AddressHash());
251         mapSpent.insert(make_pair(key, value));
252         inserted.push_back(key);
253     }
254     mapSpentInserted.insert(make_pair(txhash, inserted));
255 }
256
257 bool CTxMemPool::getSpentIndex(const CSpentIndexKey &key, CSpentIndexValue &value)
258 {
259     LOCK(cs);
260     std::map<CSpentIndexKey, CSpentIndexValue, CSpentIndexKeyCompare>::iterator it = mapSpent.find(key);
261     if (it != mapSpent.end()) {
262         value = it->second;
263         return true;
264     }
265     return false;
266 }
267
268 bool CTxMemPool::removeSpentIndex(const uint256 txhash)
269 {
270     LOCK(cs);
271     auto it = mapSpentInserted.find(txhash);
272
273     if (it != mapSpentInserted.end()) {
274         std::vector<CSpentIndexKey> keys = (*it).second;
275         for (std::vector<CSpentIndexKey>::iterator mit = keys.begin(); mit != keys.end(); mit++) {
276             mapSpent.erase(*mit);
277         }
278         mapSpentInserted.erase(it);
279     }
280
281     return true;
282 }
283
284 void CTxMemPool::remove(const CTransaction &origTx, std::list<CTransaction>& removed, bool fRecursive)
285 {
286     // Remove transaction from memory pool
287     {
288         LOCK(cs);
289         std::deque<uint256> txToRemove;
290         txToRemove.push_back(origTx.GetHash());
291         if (fRecursive && !mapTx.count(origTx.GetHash())) {
292             // If recursively removing but origTx isn't in the mempool
293             // be sure to remove any children that are in the pool. This can
294             // happen during chain re-orgs if origTx isn't re-accepted into
295             // the mempool for any reason.
296             for (unsigned int i = 0; i < origTx.vout.size(); i++) {
297                 std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(COutPoint(origTx.GetHash(), i));
298                 if (it == mapNextTx.end())
299                     continue;
300                 txToRemove.push_back(it->second.ptx->GetHash());
301             }
302         }
303         while (!txToRemove.empty())
304         {
305             uint256 hash = txToRemove.front();
306             txToRemove.pop_front();
307             if (!mapTx.count(hash))
308                 continue;
309             const CTransaction& tx = mapTx.find(hash)->GetTx();
310             if (fRecursive) {
311                 for (unsigned int i = 0; i < tx.vout.size(); i++) {
312                     std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(COutPoint(hash, i));
313                     if (it == mapNextTx.end())
314                         continue;
315                     txToRemove.push_back(it->second.ptx->GetHash());
316                 }
317             }
318             mapRecentlyAddedTx.erase(hash);
319             BOOST_FOREACH(const CTxIn& txin, tx.vin)
320                 mapNextTx.erase(txin.prevout);
321             BOOST_FOREACH(const JSDescription& joinsplit, tx.vJoinSplit) {
322                 BOOST_FOREACH(const uint256& nf, joinsplit.nullifiers) {
323                     mapSproutNullifiers.erase(nf);
324                 }
325             }
326             for (const SpendDescription &spendDescription : tx.vShieldedSpend) {
327                 mapSaplingNullifiers.erase(spendDescription.nullifier);
328             }
329             removed.push_back(tx);
330             totalTxSize -= mapTx.find(hash)->GetTxSize();
331             cachedInnerUsage -= mapTx.find(hash)->DynamicMemoryUsage();
332             mapTx.erase(hash);
333             nTransactionsUpdated++;
334             minerPolicyEstimator->removeTx(hash);
335             if (fAddressIndex)
336                 removeAddressIndex(hash);
337             if (fSpentIndex)
338                 removeSpentIndex(hash);
339             ClearPrioritisation(tx.GetHash());
340         }
341     }
342 }
343
344 extern uint64_t ASSETCHAINS_TIMELOCKGTE;
345 int64_t komodo_block_unlocktime(uint32_t nHeight);
346
347 void CTxMemPool::removeForReorg(const CCoinsViewCache *pcoins, unsigned int nMemPoolHeight, int flags)
348 {
349     // Remove transactions spending a coinbase which are now immature
350     extern char ASSETCHAINS_SYMBOL[KOMODO_ASSETCHAIN_MAXLEN];
351
352     if ( ASSETCHAINS_SYMBOL[0] == 0 )
353         COINBASE_MATURITY = _COINBASE_MATURITY;
354
355     // Remove transactions spending a coinbase which are now immature and no-longer-final transactions
356     LOCK(cs);
357     list<CTransaction> transactionsToRemove;
358     for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
359         const CTransaction& tx = it->GetTx();
360         if (!CheckFinalTx(tx, flags)) {
361             transactionsToRemove.push_back(tx);
362         } else if (it->GetSpendsCoinbase()) {
363             BOOST_FOREACH(const CTxIn& txin, tx.vin) {
364                 indexed_transaction_set::const_iterator it2 = mapTx.find(txin.prevout.hash);
365                 if (it2 != mapTx.end())
366                     continue;
367                 const CCoins *coins = pcoins->AccessCoins(txin.prevout.hash);
368                         if (nCheckFrequency != 0) assert(coins);
369
370                 if (!coins || (coins->IsCoinBase() &&
371                                (((signed long)nMemPoolHeight) - coins->nHeight < COINBASE_MATURITY) || 
372                                     ((signed long)nMemPoolHeight < komodo_block_unlocktime(coins->nHeight) && 
373                                         coins->IsAvailable(0) && coins->vout[0].nValue >= ASSETCHAINS_TIMELOCKGTE))) {
374                     transactionsToRemove.push_back(tx);
375                     break;
376                 }
377             }
378         }
379     }
380     BOOST_FOREACH(const CTransaction& tx, transactionsToRemove) {
381         list<CTransaction> removed;
382         remove(tx, removed, true);
383     }
384 }
385
386
387 void CTxMemPool::removeWithAnchor(const uint256 &invalidRoot, ShieldedType type)
388 {
389     // If a block is disconnected from the tip, and the root changed,
390     // we must invalidate transactions from the mempool which spend
391     // from that root -- almost as though they were spending coinbases
392     // which are no longer valid to spend due to coinbase maturity.
393     LOCK(cs);
394     list<CTransaction> transactionsToRemove;
395
396     for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
397         const CTransaction& tx = it->GetTx();
398         switch (type) {
399             case SPROUT:
400                 BOOST_FOREACH(const JSDescription& joinsplit, tx.vJoinSplit) {
401                     if (joinsplit.anchor == invalidRoot) {
402                         transactionsToRemove.push_back(tx);
403                         break;
404                     }
405                 }
406             break;
407             case SAPLING:
408                 BOOST_FOREACH(const SpendDescription& spendDescription, tx.vShieldedSpend) {
409                     if (spendDescription.anchor == invalidRoot) {
410                         transactionsToRemove.push_back(tx);
411                         break;
412                     }
413                 }
414             break;
415             default:
416                 throw runtime_error("Unknown shielded type");
417             break;
418         }
419     }
420
421     BOOST_FOREACH(const CTransaction& tx, transactionsToRemove) {
422         list<CTransaction> removed;
423         remove(tx, removed, true);
424     }
425 }
426
427 void CTxMemPool::removeConflicts(const CTransaction &tx, std::list<CTransaction>& removed)
428 {
429     // Remove transactions which depend on inputs of tx, recursively
430     list<CTransaction> result;
431     LOCK(cs);
432     BOOST_FOREACH(const CTxIn &txin, tx.vin) {
433         std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(txin.prevout);
434         if (it != mapNextTx.end()) {
435             const CTransaction &txConflict = *it->second.ptx;
436             if (txConflict != tx)
437             {
438                 remove(txConflict, removed, true);
439             }
440         }
441     }
442
443     BOOST_FOREACH(const JSDescription &joinsplit, tx.vJoinSplit) {
444         BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
445             std::map<uint256, const CTransaction*>::iterator it = mapSproutNullifiers.find(nf);
446             if (it != mapSproutNullifiers.end()) {
447                 const CTransaction &txConflict = *it->second;
448                 if (txConflict != tx) {
449                     remove(txConflict, removed, true);
450                 }
451             }
452         }
453     }
454     for (const SpendDescription &spendDescription : tx.vShieldedSpend) {
455         std::map<uint256, const CTransaction*>::iterator it = mapSaplingNullifiers.find(spendDescription.nullifier);
456         if (it != mapSaplingNullifiers.end()) {
457             const CTransaction &txConflict = *it->second;
458             if (txConflict != tx) {
459                 remove(txConflict, removed, true);
460             }
461         }
462     }
463 }
464
465 int32_t komodo_validate_interest(const CTransaction &tx,int32_t txheight,uint32_t nTime,int32_t dispflag);
466 extern char ASSETCHAINS_SYMBOL[];
467
468 void CTxMemPool::removeExpired(unsigned int nBlockHeight)
469 {
470     CBlockIndex *tipindex;
471     // Remove expired txs from the mempool
472     LOCK(cs);
473     list<CTransaction> transactionsToRemove;
474     for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++)
475     {
476         const CTransaction& tx = it->GetTx();
477         tipindex = chainActive.LastTip();
478         if (IsExpiredTx(tx, nBlockHeight) || (ASSETCHAINS_SYMBOL[0] == 0 && tipindex != 0 && komodo_validate_interest(tx,tipindex->GetHeight()+1,tipindex->GetMedianTimePast() + 777,0)) < 0)
479         {
480             transactionsToRemove.push_back(tx);
481         }
482     }
483     for (const CTransaction& tx : transactionsToRemove) {
484         list<CTransaction> removed;
485         remove(tx, removed, true);
486         LogPrint("mempool", "Removing expired txid: %s\n", tx.GetHash().ToString());
487     }
488 }
489
490 /**
491  * Called when a block is connected. Removes from mempool and updates the miner fee estimator.
492  */
493 void CTxMemPool::removeForBlock(const std::vector<CTransaction>& vtx, unsigned int nBlockHeight,
494                                 std::list<CTransaction>& conflicts, bool fCurrentEstimate)
495 {
496     LOCK(cs);
497     std::vector<CTxMemPoolEntry> entries;
498     BOOST_FOREACH(const CTransaction& tx, vtx)
499     {
500         uint256 hash = tx.GetHash();
501
502         indexed_transaction_set::iterator i = mapTx.find(hash);
503         if (i != mapTx.end())
504             entries.push_back(*i);
505     }
506     BOOST_FOREACH(const CTransaction& tx, vtx)
507     {
508         std::list<CTransaction> dummy;
509         remove(tx, dummy, false);
510         removeConflicts(tx, conflicts);
511         ClearPrioritisation(tx.GetHash());
512     }
513     // After the txs in the new block have been removed from the mempool, update policy estimates
514     minerPolicyEstimator->processBlock(nBlockHeight, entries, fCurrentEstimate);
515 }
516
517 /**
518  * Called whenever the tip changes. Removes transactions which don't commit to
519  * the given branch ID from the mempool.
520  */
521 void CTxMemPool::removeWithoutBranchId(uint32_t nMemPoolBranchId)
522 {
523     LOCK(cs);
524     std::list<CTransaction> transactionsToRemove;
525
526     for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
527         const CTransaction& tx = it->GetTx();
528         if (it->GetValidatedBranchId() != nMemPoolBranchId) {
529             transactionsToRemove.push_back(tx);
530         }
531     }
532
533     for (const CTransaction& tx : transactionsToRemove) {
534         std::list<CTransaction> removed;
535         remove(tx, removed, true);
536     }
537 }
538
539 void CTxMemPool::clear()
540 {
541     LOCK(cs);
542     mapTx.clear();
543     mapNextTx.clear();
544     totalTxSize = 0;
545     cachedInnerUsage = 0;
546     ++nTransactionsUpdated;
547 }
548
549 void CTxMemPool::check(const CCoinsViewCache *pcoins) const
550 {
551     if (nCheckFrequency == 0)
552         return;
553
554     if (insecure_rand() >= nCheckFrequency)
555         return;
556
557     LogPrint("mempool", "Checking mempool with %u transactions and %u inputs\n", (unsigned int)mapTx.size(), (unsigned int)mapNextTx.size());
558
559     uint64_t checkTotal = 0;
560     uint64_t innerUsage = 0;
561
562     CCoinsViewCache mempoolDuplicate(const_cast<CCoinsViewCache*>(pcoins));
563     const int64_t nSpendHeight = GetSpendHeight(mempoolDuplicate);
564
565     LOCK(cs);
566     list<const CTxMemPoolEntry*> waitingOnDependants;
567     for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
568         unsigned int i = 0;
569         checkTotal += it->GetTxSize();
570         innerUsage += it->DynamicMemoryUsage();
571         const CTransaction& tx = it->GetTx();
572         bool fDependsWait = false;
573         BOOST_FOREACH(const CTxIn &txin, tx.vin) {
574             // Check that every mempool transaction's inputs refer to available coins, or other mempool tx's.
575             indexed_transaction_set::const_iterator it2 = mapTx.find(txin.prevout.hash);
576             if (it2 != mapTx.end()) {
577                 const CTransaction& tx2 = it2->GetTx();
578                 assert(tx2.vout.size() > txin.prevout.n && !tx2.vout[txin.prevout.n].IsNull());
579                 fDependsWait = true;
580             } else {
581                 const CCoins* coins = pcoins->AccessCoins(txin.prevout.hash);
582                 assert(coins && coins->IsAvailable(txin.prevout.n));
583             }
584             // Check whether its inputs are marked in mapNextTx.
585             std::map<COutPoint, CInPoint>::const_iterator it3 = mapNextTx.find(txin.prevout);
586             assert(it3 != mapNextTx.end());
587             assert(it3->second.ptx == &tx);
588             assert(it3->second.n == i);
589             i++;
590         }
591
592         boost::unordered_map<uint256, SproutMerkleTree, CCoinsKeyHasher> intermediates;
593
594         BOOST_FOREACH(const JSDescription &joinsplit, tx.vJoinSplit) {
595             BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
596                 assert(!pcoins->GetNullifier(nf, SPROUT));
597             }
598
599             SproutMerkleTree tree;
600             auto it = intermediates.find(joinsplit.anchor);
601             if (it != intermediates.end()) {
602                 tree = it->second;
603             } else {
604                 assert(pcoins->GetSproutAnchorAt(joinsplit.anchor, tree));
605             }
606
607             BOOST_FOREACH(const uint256& commitment, joinsplit.commitments)
608             {
609                 tree.append(commitment);
610             }
611
612             intermediates.insert(std::make_pair(tree.root(), tree));
613         }
614         for (const SpendDescription &spendDescription : tx.vShieldedSpend) {
615             SaplingMerkleTree tree;
616
617             assert(pcoins->GetSaplingAnchorAt(spendDescription.anchor, tree));
618             assert(!pcoins->GetNullifier(spendDescription.nullifier, SAPLING));
619         }
620         if (fDependsWait)
621             waitingOnDependants.push_back(&(*it));
622         else {
623             CValidationState state;
624             bool fCheckResult = tx.IsCoinBase() ||
625                 Consensus::CheckTxInputs(tx, state, mempoolDuplicate, nSpendHeight, Params().GetConsensus());
626             assert(fCheckResult);
627             UpdateCoins(tx, mempoolDuplicate, 1000000);
628         }
629     }
630     unsigned int stepsSinceLastRemove = 0;
631     while (!waitingOnDependants.empty()) {
632         const CTxMemPoolEntry* entry = waitingOnDependants.front();
633         waitingOnDependants.pop_front();
634         CValidationState state;
635         if (!mempoolDuplicate.HaveInputs(entry->GetTx())) {
636             waitingOnDependants.push_back(entry);
637             stepsSinceLastRemove++;
638             assert(stepsSinceLastRemove < waitingOnDependants.size());
639         } else {
640             bool fCheckResult = entry->GetTx().IsCoinBase() ||
641                 Consensus::CheckTxInputs(entry->GetTx(), state, mempoolDuplicate, nSpendHeight, Params().GetConsensus());
642             assert(fCheckResult);
643             UpdateCoins(entry->GetTx(), mempoolDuplicate, 1000000);
644             stepsSinceLastRemove = 0;
645         }
646     }
647     for (std::map<COutPoint, CInPoint>::const_iterator it = mapNextTx.begin(); it != mapNextTx.end(); it++) {
648         uint256 hash = it->second.ptx->GetHash();
649         indexed_transaction_set::const_iterator it2 = mapTx.find(hash);
650         const CTransaction& tx = it2->GetTx();
651         assert(it2 != mapTx.end());
652         assert(&tx == it->second.ptx);
653         assert(tx.vin.size() > it->second.n);
654         assert(it->first == it->second.ptx->vin[it->second.n].prevout);
655     }
656
657     checkNullifiers(SPROUT);
658     checkNullifiers(SAPLING);
659
660     assert(totalTxSize == checkTotal);
661     assert(innerUsage == cachedInnerUsage);
662 }
663
664 void CTxMemPool::checkNullifiers(ShieldedType type) const
665 {
666     const std::map<uint256, const CTransaction*>* mapToUse;
667     switch (type) {
668         case SPROUT:
669             mapToUse = &mapSproutNullifiers;
670             break;
671         case SAPLING:
672             mapToUse = &mapSaplingNullifiers;
673             break;
674         default:
675             throw runtime_error("Unknown nullifier type");
676     }
677     for (const auto& entry : *mapToUse) {
678         uint256 hash = entry.second->GetHash();
679         CTxMemPool::indexed_transaction_set::const_iterator findTx = mapTx.find(hash);
680         const CTransaction& tx = findTx->GetTx();
681         assert(findTx != mapTx.end());
682         assert(&tx == entry.second);
683     }
684 }
685
686 void CTxMemPool::queryHashes(vector<uint256>& vtxid)
687 {
688     vtxid.clear();
689
690     LOCK(cs);
691     vtxid.reserve(mapTx.size());
692     for (indexed_transaction_set::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
693         vtxid.push_back(mi->GetTx().GetHash());
694 }
695
696 bool CTxMemPool::lookup(uint256 hash, CTransaction& result) const
697 {
698     LOCK(cs);
699     indexed_transaction_set::const_iterator i = mapTx.find(hash);
700     if (i == mapTx.end()) return false;
701     result = i->GetTx();
702     return true;
703 }
704
705 CFeeRate CTxMemPool::estimateFee(int nBlocks) const
706 {
707     LOCK(cs);
708     return minerPolicyEstimator->estimateFee(nBlocks);
709 }
710 double CTxMemPool::estimatePriority(int nBlocks) const
711 {
712     LOCK(cs);
713     return minerPolicyEstimator->estimatePriority(nBlocks);
714 }
715
716 bool
717 CTxMemPool::WriteFeeEstimates(CAutoFile& fileout) const
718 {
719     try {
720         LOCK(cs);
721         fileout << 109900; // version required to read: 0.10.99 or later
722         fileout << CLIENT_VERSION; // version that wrote the file
723         minerPolicyEstimator->Write(fileout);
724     }
725     catch (const std::exception&) {
726         LogPrintf("CTxMemPool::WriteFeeEstimates(): unable to write policy estimator data (non-fatal)\n");
727         return false;
728     }
729     return true;
730 }
731
732 bool
733 CTxMemPool::ReadFeeEstimates(CAutoFile& filein)
734 {
735     try {
736         int nVersionRequired, nVersionThatWrote;
737         filein >> nVersionRequired >> nVersionThatWrote;
738         if (nVersionRequired > CLIENT_VERSION)
739             return error("CTxMemPool::ReadFeeEstimates(): up-version (%d) fee estimate file", nVersionRequired);
740
741         LOCK(cs);
742         minerPolicyEstimator->Read(filein);
743     }
744     catch (const std::exception&) {
745         LogPrintf("CTxMemPool::ReadFeeEstimates(): unable to read policy estimator data (non-fatal)\n");
746         return false;
747     }
748     return true;
749 }
750
751 void CTxMemPool::PrioritiseTransaction(const uint256 &hash, const string strHash, double dPriorityDelta, const CAmount& nFeeDelta)
752 {
753     {
754         LOCK(cs);
755         std::pair<double, CAmount> &deltas = mapDeltas[hash];
756         deltas.first += dPriorityDelta;
757         deltas.second += nFeeDelta;
758     }
759     LogPrintf("PrioritiseTransaction: %s priority += %f, fee += %d\n", strHash, dPriorityDelta, FormatMoney(nFeeDelta));
760 }
761
762 void CTxMemPool::ApplyDeltas(const uint256 hash, double &dPriorityDelta, CAmount &nFeeDelta)
763 {
764     LOCK(cs);
765     std::map<uint256, std::pair<double, CAmount> >::iterator pos = mapDeltas.find(hash);
766     if (pos == mapDeltas.end())
767         return;
768     const std::pair<double, CAmount> &deltas = pos->second;
769     dPriorityDelta += deltas.first;
770     nFeeDelta += deltas.second;
771 }
772
773 void CTxMemPool::ClearPrioritisation(const uint256 hash)
774 {
775     LOCK(cs);
776     mapDeltas.erase(hash);
777     mapReserveTransactions.erase(hash);
778 }
779
780 bool CTxMemPool::PrioritiseReserveTransaction(const CReserveTransactionDescriptor &txDesc, const CCurrencyState &currencyState)
781 {
782     LOCK(cs);
783     uint256 hash = txDesc.ptx->GetHash();
784     auto it = mapReserveTransactions.find(hash);
785     if (txDesc.IsValid())
786     {
787         mapReserveTransactions[hash] = txDesc;
788         CAmount feeDelta = currencyState.ReserveToNative(txDesc.ReserveFees() + txDesc.reserveConversionFees) + txDesc.nativeConversionFees;
789         PrioritiseTransaction(hash, hash.GetHex().c_str(), (double)feeDelta * 100.0, feeDelta);
790         return true;
791     }
792     return false;
793 }
794
795 bool CTxMemPool::IsKnownReserveTransaction(const uint256 &hash, CReserveTransactionDescriptor &txDesc)
796 {
797     LOCK(cs);
798     auto it = mapReserveTransactions.find(hash);
799     if (it != mapReserveTransactions.end() && it->second.IsValid())
800     {
801         // refresh transaction from mempool or delete it if not found (we may not need this at all)
802         indexed_transaction_set::const_iterator i = mapTx.find(hash);
803         if (i == mapTx.end())
804         {
805             ClearPrioritisation(hash);
806         }
807         else
808         {
809             it->second.ptx = &(i->GetTx());
810
811             txDesc = it->second;
812             return true;
813         }
814     }
815     return false;
816 }
817
818 bool CTxMemPool::HasNoInputsOf(const CTransaction &tx) const
819 {
820     for (unsigned int i = 0; i < tx.vin.size(); i++)
821         if (exists(tx.vin[i].prevout.hash))
822             return false;
823     return true;
824 }
825
826 bool CTxMemPool::nullifierExists(const uint256& nullifier, ShieldedType type) const
827 {
828     switch (type) {
829         case SPROUT:
830             return mapSproutNullifiers.count(nullifier);
831         case SAPLING:
832             return mapSaplingNullifiers.count(nullifier);
833         default:
834             throw runtime_error("Unknown nullifier type");
835     }
836 }
837
838 void CTxMemPool::NotifyRecentlyAdded()
839 {
840     uint64_t recentlyAddedSequence;
841     std::vector<CTransaction> txs;
842     {
843         LOCK(cs);
844         recentlyAddedSequence = nRecentlyAddedSequence;
845         for (const auto& kv : mapRecentlyAddedTx) {
846             txs.push_back(*(kv.second));
847         }
848         mapRecentlyAddedTx.clear();
849     }
850
851     // A race condition can occur here between these SyncWithWallets calls, and
852     // the ones triggered by block logic (in ConnectTip and DisconnectTip). It
853     // is harmless because calling SyncWithWallets(_, NULL) does not alter the
854     // wallet transaction's block information.
855     for (auto tx : txs) {
856         try {
857             SyncWithWallets(tx, NULL);
858         } catch (const boost::thread_interrupted&) {
859             throw;
860         } catch (const std::exception& e) {
861             PrintExceptionContinue(&e, "CTxMemPool::NotifyRecentlyAdded()");
862         } catch (...) {
863             PrintExceptionContinue(NULL, "CTxMemPool::NotifyRecentlyAdded()");
864         }
865     }
866
867     // Update the notified sequence number. We only need this in regtest mode,
868     // and should not lock on cs after calling SyncWithWallets otherwise.
869     if (Params().NetworkIDString() == "regtest") {
870         LOCK(cs);
871         nNotifiedSequence = recentlyAddedSequence;
872     }
873 }
874
875 bool CTxMemPool::IsFullyNotified() {
876     assert(Params().NetworkIDString() == "regtest");
877     LOCK(cs);
878     return nRecentlyAddedSequence == nNotifiedSequence;
879 }
880
881 CCoinsViewMemPool::CCoinsViewMemPool(CCoinsView *baseIn, CTxMemPool &mempoolIn) : CCoinsViewBacked(baseIn), mempool(mempoolIn) { }
882
883 bool CCoinsViewMemPool::GetNullifier(const uint256 &nf, ShieldedType type) const
884 {
885     return mempool.nullifierExists(nf, type) || base->GetNullifier(nf, type);
886 }
887
888 bool CCoinsViewMemPool::GetCoins(const uint256 &txid, CCoins &coins) const {
889     // If an entry in the mempool exists, always return that one, as it's guaranteed to never
890     // conflict with the underlying cache, and it cannot have pruned entries (as it contains full)
891     // transactions. First checking the underlying cache risks returning a pruned entry instead.
892     CTransaction tx;
893     if (mempool.lookup(txid, tx)) {
894         coins = CCoins(tx, MEMPOOL_HEIGHT);
895         return true;
896     }
897     return (base->GetCoins(txid, coins) && !coins.IsPruned());
898 }
899
900 bool CCoinsViewMemPool::HaveCoins(const uint256 &txid) const {
901     return mempool.exists(txid) || base->HaveCoins(txid);
902 }
903
904 size_t CTxMemPool::DynamicMemoryUsage() const {
905     LOCK(cs);
906     // Estimate the overhead of mapTx to be 6 pointers + an allocation, as no exact formula for boost::multi_index_contained is implemented.
907     return memusage::MallocUsage(sizeof(CTxMemPoolEntry) + 6 * sizeof(void*)) * mapTx.size() + memusage::DynamicUsage(mapNextTx) + memusage::DynamicUsage(mapDeltas) + memusage::DynamicUsage(mapDeltas) + memusage::DynamicUsage(mapDeltas) + cachedInnerUsage;
908 }
This page took 0.074928 seconds and 4 git commands to generate.