]> Git Repo - VerusCoin.git/blob - src/txmempool.cpp
Reserve currency improvements
[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 "cc/CCinclude.h"
20 #include "pbaas/pbaas.h"
21 #include "pbaas/identity.h"
22 #define _COINBASE_MATURITY 100
23
24 using namespace std;
25
26 CTxMemPoolEntry::CTxMemPoolEntry():
27     nFee(0), nTxSize(0), nModSize(0), nUsageSize(0), nTime(0), dPriority(0.0),
28     hadNoDependencies(false), spendsCoinbase(false), hasReserve(false)
29 {
30     nHeight = MEMPOOL_HEIGHT;
31 }
32
33 CTxMemPoolEntry::CTxMemPoolEntry(const CTransaction& _tx, const CAmount& _nFee,
34                                  int64_t _nTime, double _dPriority,
35                                  unsigned int _nHeight, bool poolHasNoInputsOf,
36                                  bool _spendsCoinbase, uint32_t _nBranchId, bool hasreserve):
37     tx(_tx), nFee(_nFee), nTime(_nTime), dPriority(_dPriority), nHeight(_nHeight),
38     hadNoDependencies(poolHasNoInputsOf), hasReserve(hasreserve),
39     spendsCoinbase(_spendsCoinbase), nBranchId(_nBranchId)
40 {
41     nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
42     nModSize = tx.CalculateModifiedSize(nTxSize);
43     nUsageSize = RecursiveDynamicUsage(tx);
44     feeRate = CFeeRate(nFee, nTxSize);
45 }
46
47 CTxMemPoolEntry::CTxMemPoolEntry(const CTxMemPoolEntry& other)
48 {
49     *this = other;
50 }
51
52 double
53 CTxMemPoolEntry::GetPriority(unsigned int currentHeight) const
54 {
55     CAmount nValueIn = tx.GetValueOut()+nFee;
56     CCurrencyState currencyState;
57     unsigned int lastHeight = currentHeight < 1 ? 0 : currentHeight - 1;
58     AssertLockHeld(cs_main);
59     if (hasReserve && (currencyState = ConnectedChains.GetCurrencyState(currentHeight - 1)).IsValid())
60     {
61         nValueIn += currencyState.ReserveToNative(tx.GetReserveValueOut());
62     }
63     double deltaPriority = ((double)(currentHeight-nHeight)*nValueIn)/nModSize;
64     double dResult = dPriority + deltaPriority;
65     return dResult;
66 }
67
68 CTxMemPool::CTxMemPool(const CFeeRate& _minRelayFee) :
69     nTransactionsUpdated(0)
70 {
71     // Sanity checks off by default for performance, because otherwise
72     // accepting transactions becomes O(N^2) where N is the number
73     // of transactions in the pool
74     nCheckFrequency = 0;
75
76     minerPolicyEstimator = new CBlockPolicyEstimator(_minRelayFee);
77 }
78
79 CTxMemPool::~CTxMemPool()
80 {
81     delete minerPolicyEstimator;
82 }
83
84 void CTxMemPool::pruneSpent(const uint256 &hashTx, CCoins &coins)
85 {
86     LOCK(cs);
87
88     std::map<COutPoint, CInPoint>::iterator it = mapNextTx.lower_bound(COutPoint(hashTx, 0));
89
90     // iterate over all COutPoints in mapNextTx whose hash equals the provided hashTx
91     while (it != mapNextTx.end() && it->first.hash == hashTx) {
92         coins.Spend(it->first.n); // and remove those outputs from coins
93         it++;
94     }
95 }
96
97 unsigned int CTxMemPool::GetTransactionsUpdated() const
98 {
99     LOCK(cs);
100     return nTransactionsUpdated;
101 }
102
103 void CTxMemPool::AddTransactionsUpdated(unsigned int n)
104 {
105     LOCK(cs);
106     nTransactionsUpdated += n;
107 }
108
109
110 bool CTxMemPool::addUnchecked(const uint256& hash, const CTxMemPoolEntry &entry, bool fCurrentEstimate)
111 {
112     // Add to memory pool without checking anything.
113     // Used by main.cpp AcceptToMemoryPool(), which DOES do
114     // all the appropriate checks.
115     LOCK(cs);
116     mapTx.insert(entry);
117     const CTransaction& tx = mapTx.find(hash)->GetTx();
118     mapRecentlyAddedTx[tx.GetHash()] = &tx;
119     nRecentlyAddedSequence += 1;
120     if (!tx.IsCoinImport()) {
121         for (unsigned int i = 0; i < tx.vin.size(); i++)
122             mapNextTx[tx.vin[i].prevout] = CInPoint(&tx, i);
123     }
124     BOOST_FOREACH(const JSDescription &joinsplit, tx.vJoinSplit) {
125         BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
126             mapSproutNullifiers[nf] = &tx;
127         }
128     }
129     for (const SpendDescription &spendDescription : tx.vShieldedSpend) {
130         mapSaplingNullifiers[spendDescription.nullifier] = &tx;
131     }
132     nTransactionsUpdated++;
133     totalTxSize += entry.GetTxSize();
134     cachedInnerUsage += entry.DynamicMemoryUsage();
135     minerPolicyEstimator->processTransaction(entry, fCurrentEstimate);
136
137     return true;
138 }
139
140 void CTxMemPool::addAddressIndex(const CTxMemPoolEntry &entry, const CCoinsViewCache &view)
141 {
142     LOCK(cs);
143     const CTransaction& tx = entry.GetTx();
144     std::vector<CMempoolAddressDeltaKey> inserted;
145
146     uint256 txhash = tx.GetHash();
147     if (!tx.IsCoinBase())
148     {
149         for (unsigned int j = 0; j < tx.vin.size(); j++) {
150             const CTxIn input = tx.vin[j];
151             const CTxOut &prevout = view.GetOutputFor(input);
152             COptCCParams p;
153             if (prevout.scriptPubKey.IsPayToCryptoCondition(p))
154             {
155                 std::vector<CTxDestination> dests;
156                 if (p.IsValid())
157                 {
158                     dests = p.GetDestinations();
159                 }
160                 else
161                 {
162                     dests = prevout.scriptPubKey.GetDestinations();
163                 }
164                 for (auto dest : dests)
165                 {
166                     if (dest.which() != COptCCParams::ADDRTYPE_INVALID)
167                     {
168                         CMempoolAddressDeltaKey key(AddressTypeFromDest(dest), GetDestinationID(dest), txhash, j, 1);
169                         CMempoolAddressDelta delta(entry.GetTime(), prevout.nValue * -1, input.prevout.hash, input.prevout.n);
170                         mapAddress.insert(make_pair(key, delta));
171                         inserted.push_back(key);
172                     }
173                 }
174             }
175             else
176             {
177                 CScript::ScriptType type = prevout.scriptPubKey.GetType();
178                 if (type == CScript::UNKNOWN)
179                     continue;
180
181                 CMempoolAddressDeltaKey key(type, prevout.scriptPubKey.AddressHash(), txhash, j, 1);
182                 CMempoolAddressDelta delta(entry.GetTime(), prevout.nValue * -1, input.prevout.hash, input.prevout.n);
183                 mapAddress.insert(make_pair(key, delta));
184                 inserted.push_back(key);
185             }
186         }
187     }
188
189     for (unsigned int j = 0; j < tx.vout.size(); j++) {
190         const CTxOut &out = tx.vout[j];
191
192         COptCCParams p;
193         if (out.scriptPubKey.IsPayToCryptoCondition(p))
194         {
195             std::vector<CTxDestination> dests;
196             if (p.IsValid())
197             {
198                 dests = p.GetDestinations();
199             }
200             else
201             {
202                 dests = out.scriptPubKey.GetDestinations();
203             }
204             for (auto dest : dests)
205             {
206                 if (dest.which() != COptCCParams::ADDRTYPE_INVALID)
207                 {
208                     CMempoolAddressDeltaKey key(AddressTypeFromDest(dest), GetDestinationID(dest), txhash, j, 0);
209                     mapAddress.insert(make_pair(key, CMempoolAddressDelta(entry.GetTime(), out.nValue)));
210                     inserted.push_back(key);
211                 }
212             }
213         }
214         else
215         {
216             CScript::ScriptType type = out.scriptPubKey.GetType();
217             if (type == CScript::UNKNOWN)
218                 continue;
219
220             CMempoolAddressDeltaKey key(type, out.scriptPubKey.AddressHash(), txhash, j, 0);
221             mapAddress.insert(make_pair(key, CMempoolAddressDelta(entry.GetTime(), out.nValue)));
222             inserted.push_back(key);
223         }
224     }
225     mapAddressInserted.insert(make_pair(txhash, inserted));
226 }
227
228 bool CTxMemPool::getAddressIndex(const std::vector<std::pair<uint160, int> > &addresses, std::vector<std::pair<CMempoolAddressDeltaKey, CMempoolAddressDelta> > &results)
229 {
230     LOCK(cs);
231     for (std::vector<std::pair<uint160, int> >::const_iterator it = addresses.begin(); it != addresses.end(); it++) {
232         auto ait = mapAddress.lower_bound(CMempoolAddressDeltaKey((*it).second, (*it).first));
233         while (ait != mapAddress.end() && (*ait).first.addressBytes == (*it).first && (*ait).first.type == (*it).second) {
234             results.push_back(*ait);
235             ait++;
236         }
237     }
238     return true;
239 }
240
241 bool CTxMemPool::removeAddressIndex(const uint256 txhash)
242 {
243     LOCK(cs);
244     auto it = mapAddressInserted.find(txhash);
245
246     if (it != mapAddressInserted.end()) {
247         std::vector<CMempoolAddressDeltaKey> keys = (*it).second;
248         for (std::vector<CMempoolAddressDeltaKey>::iterator mit = keys.begin(); mit != keys.end(); mit++) {
249             mapAddress.erase(*mit);
250         }
251         mapAddressInserted.erase(it);
252     }
253
254     return true;
255 }
256
257 void CTxMemPool::addSpentIndex(const CTxMemPoolEntry &entry, const CCoinsViewCache &view)
258 {
259     LOCK(cs);
260     const CTransaction& tx = entry.GetTx();
261     uint256 txhash = tx.GetHash();
262     std::vector<CSpentIndexKey> inserted;
263
264     for (unsigned int j = 0; j < tx.vin.size(); j++) {
265         const CTxIn input = tx.vin[j];
266         const CTxOut &prevout = view.GetOutputFor(input);
267         CSpentIndexKey key = CSpentIndexKey(input.prevout.hash, input.prevout.n);
268         CSpentIndexValue value = CSpentIndexValue(txhash, j, -1, prevout.nValue,
269             prevout.scriptPubKey.GetType(),
270             prevout.scriptPubKey.AddressHash());
271         mapSpent.insert(make_pair(key, value));
272         inserted.push_back(key);
273     }
274     mapSpentInserted.insert(make_pair(txhash, inserted));
275 }
276
277 bool CTxMemPool::getSpentIndex(const CSpentIndexKey &key, CSpentIndexValue &value)
278 {
279     LOCK(cs);
280     std::map<CSpentIndexKey, CSpentIndexValue, CSpentIndexKeyCompare>::iterator it = mapSpent.find(key);
281     if (it != mapSpent.end()) {
282         value = it->second;
283         return true;
284     }
285     return false;
286 }
287
288 bool CTxMemPool::removeSpentIndex(const uint256 txhash)
289 {
290     LOCK(cs);
291     auto it = mapSpentInserted.find(txhash);
292
293     if (it != mapSpentInserted.end()) {
294         std::vector<CSpentIndexKey> keys = (*it).second;
295         for (std::vector<CSpentIndexKey>::iterator mit = keys.begin(); mit != keys.end(); mit++) {
296             mapSpent.erase(*mit);
297         }
298         mapSpentInserted.erase(it);
299     }
300
301     return true;
302 }
303
304 void CTxMemPool::remove(const CTransaction &origTx, std::list<CTransaction>& removed, bool fRecursive)
305 {
306     // Remove transaction from memory pool
307     {
308         LOCK(cs);
309         std::deque<uint256> txToRemove;
310         txToRemove.push_back(origTx.GetHash());
311         if (fRecursive && !mapTx.count(origTx.GetHash())) {
312             // If recursively removing but origTx isn't in the mempool
313             // be sure to remove any children that are in the pool. This can
314             // happen during chain re-orgs if origTx isn't re-accepted into
315             // the mempool for any reason.
316             for (unsigned int i = 0; i < origTx.vout.size(); i++) {
317                 std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(COutPoint(origTx.GetHash(), i));
318                 if (it == mapNextTx.end())
319                     continue;
320                 txToRemove.push_back(it->second.ptx->GetHash());
321             }
322         }
323         while (!txToRemove.empty())
324         {
325             uint256 hash = txToRemove.front();
326             txToRemove.pop_front();
327             if (!mapTx.count(hash))
328                 continue;
329             const CTransaction& tx = mapTx.find(hash)->GetTx();
330             if (fRecursive) {
331                 for (unsigned int i = 0; i < tx.vout.size(); i++) {
332                     std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(COutPoint(hash, i));
333                     if (it == mapNextTx.end())
334                         continue;
335                     txToRemove.push_back(it->second.ptx->GetHash());
336                 }
337             }
338             mapRecentlyAddedTx.erase(hash);
339             BOOST_FOREACH(const CTxIn& txin, tx.vin)
340                 mapNextTx.erase(txin.prevout);
341             BOOST_FOREACH(const JSDescription& joinsplit, tx.vJoinSplit) {
342                 BOOST_FOREACH(const uint256& nf, joinsplit.nullifiers) {
343                     mapSproutNullifiers.erase(nf);
344                 }
345             }
346             for (const SpendDescription &spendDescription : tx.vShieldedSpend) {
347                 mapSaplingNullifiers.erase(spendDescription.nullifier);
348             }
349             removed.push_back(tx);
350             totalTxSize -= mapTx.find(hash)->GetTxSize();
351             cachedInnerUsage -= mapTx.find(hash)->DynamicMemoryUsage();
352             mapTx.erase(hash);
353             nTransactionsUpdated++;
354             minerPolicyEstimator->removeTx(hash);
355             if (fAddressIndex)
356                 removeAddressIndex(hash);
357             if (fSpentIndex)
358                 removeSpentIndex(hash);
359             ClearPrioritisation(tx.GetHash());
360         }
361     }
362 }
363
364 extern uint64_t ASSETCHAINS_TIMELOCKGTE;
365 int64_t komodo_block_unlocktime(uint32_t nHeight);
366
367 void CTxMemPool::removeForReorg(const CCoinsViewCache *pcoins, unsigned int nMemPoolHeight, int flags)
368 {
369     // Remove transactions spending a coinbase which are now immature
370     extern char ASSETCHAINS_SYMBOL[KOMODO_ASSETCHAIN_MAXLEN];
371
372     if ( ASSETCHAINS_SYMBOL[0] == 0 )
373         COINBASE_MATURITY = _COINBASE_MATURITY;
374
375     // Remove transactions spending a coinbase which are now immature and no-longer-final transactions
376     LOCK(cs);
377     list<CTransaction> transactionsToRemove;
378     for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
379         const CTransaction& tx = it->GetTx();
380         if (!CheckFinalTx(tx, flags)) {
381             transactionsToRemove.push_back(tx);
382         } else if (it->GetSpendsCoinbase()) {
383             BOOST_FOREACH(const CTxIn& txin, tx.vin) {
384                 indexed_transaction_set::const_iterator it2 = mapTx.find(txin.prevout.hash);
385                 if (it2 != mapTx.end())
386                     continue;
387                 const CCoins *coins = pcoins->AccessCoins(txin.prevout.hash);
388                         if (nCheckFrequency != 0) assert(coins);
389
390                 if (!coins || (coins->IsCoinBase() &&
391                                (((signed long)nMemPoolHeight) - coins->nHeight < COINBASE_MATURITY) || 
392                                     ((signed long)nMemPoolHeight < komodo_block_unlocktime(coins->nHeight) && 
393                                         coins->IsAvailable(0) && coins->vout[0].nValue >= ASSETCHAINS_TIMELOCKGTE))) {
394                     transactionsToRemove.push_back(tx);
395                     break;
396                 }
397             }
398         }
399     }
400     BOOST_FOREACH(const CTransaction& tx, transactionsToRemove) {
401         list<CTransaction> removed;
402         remove(tx, removed, true);
403     }
404 }
405
406
407 void CTxMemPool::removeWithAnchor(const uint256 &invalidRoot, ShieldedType type)
408 {
409     // If a block is disconnected from the tip, and the root changed,
410     // we must invalidate transactions from the mempool which spend
411     // from that root -- almost as though they were spending coinbases
412     // which are no longer valid to spend due to coinbase maturity.
413     LOCK(cs);
414     list<CTransaction> transactionsToRemove;
415
416     for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
417         const CTransaction& tx = it->GetTx();
418         switch (type) {
419             case SPROUT:
420                 BOOST_FOREACH(const JSDescription& joinsplit, tx.vJoinSplit) {
421                     if (joinsplit.anchor == invalidRoot) {
422                         transactionsToRemove.push_back(tx);
423                         break;
424                     }
425                 }
426             break;
427             case SAPLING:
428                 BOOST_FOREACH(const SpendDescription& spendDescription, tx.vShieldedSpend) {
429                     if (spendDescription.anchor == invalidRoot) {
430                         transactionsToRemove.push_back(tx);
431                         break;
432                     }
433                 }
434             break;
435             default:
436                 throw runtime_error("Unknown shielded type");
437             break;
438         }
439     }
440
441     BOOST_FOREACH(const CTransaction& tx, transactionsToRemove) {
442         list<CTransaction> removed;
443         remove(tx, removed, true);
444     }
445 }
446
447 bool CTxMemPool::checkNameConflicts(const CTransaction &tx, std::list<CTransaction> &conflicting)
448 {
449     LOCK(cs);
450
451     // easy way to check if there are any transactions in the memory pool that define the name specified but are not the same as tx
452     conflicting.clear();
453
454     // first, be sure that this is a name definition. if so, it will have both a definition and reservation output. if it is a name definition,
455     // our only concern is whether or not there is a conflicting definition in the mempool. we assume that a check for any conflicting definition
456     // in the blockchain has already taken place.
457     CIdentity identity;
458     CNameReservation reservation;
459     for (auto output : tx.vout)
460     {
461         COptCCParams p;
462         if (output.scriptPubKey.IsPayToCryptoCondition(p) && p.IsValid() && p.version >= p.VERSION_V3)
463         {
464             if (p.evalCode == EVAL_IDENTITY_PRIMARY && p.vData.size() > 1)
465             {
466                 if (identity.IsValid())
467                 {
468                     identity = CIdentity();
469                     break;
470                 }
471                 else
472                 {
473                     identity = CIdentity(p.vData[0]);
474                 }
475             }
476             else if (p.evalCode == EVAL_IDENTITY_RESERVATION && p.vData.size() > 1)
477             {
478                 if (reservation.IsValid())
479                 {
480                     reservation = CNameReservation();
481                     break;
482                 }
483                 else
484                 {
485                     reservation = CNameReservation(p.vData[0]);
486                 }
487             }
488         }
489     }
490
491     // it can't conflict if it's not a definition
492     if (!(identity.IsValid() && reservation.IsValid()))
493     {
494         return false;
495     }
496
497     std::vector<std::pair<uint160, int>> addresses = std::vector<std::pair<uint160, int>>({{identity.GetID(), CScript::P2ID}});
498     std::vector<std::pair<CMempoolAddressDeltaKey, CMempoolAddressDelta>> results;
499     if (mempool.getAddressIndex(addresses, results) && results.size())
500     {
501         std::map<uint256, std::pair<CTransaction, int>> txesAndSources;   // first hash is transaction of input of prior identity or commitment output in the mempool, second pair is tx and ID output num if identity
502
503         uint256 txHash = tx.GetHash();
504         CNameReservation conflictingRes;
505         for (auto r : results)
506         {
507             if (r.first.txhash == txHash)
508             {
509                 continue;
510             }
511             CTransaction mpTx;
512             if (lookup(r.first.txhash, mpTx))
513             {
514                 COptCCParams p;
515                 if (mpTx.vout[r.first.index].scriptPubKey.IsPayToCryptoCondition(p) && 
516                     p.IsValid() && 
517                     p.evalCode == EVAL_IDENTITY_RESERVATION && 
518                     p.vData.size() > 1 && 
519                     (conflictingRes = CNameReservation(p.vData[0])).IsValid() &&
520                     CIdentity(mpTx).IsValid())
521                 {
522                     conflicting.push_back(mpTx);
523                 }
524             }
525         }
526     }
527
528     return conflicting.size();
529 }
530
531 void CTxMemPool::removeConflicts(const CTransaction &tx, std::list<CTransaction>& removed)
532 {
533     LOCK(cs);
534
535     // names are enforced as unique without requiring related spends.
536     // if this is a definition that conflicts with an existing, unrelated name definition, remove the
537     // definition that exists in the mempool
538     std::list<CTransaction> conflicting;
539     if (checkNameConflicts(tx, conflicting))
540     {
541         for (auto &remTx : conflicting)
542         {
543             remove(remTx, removed, true);
544         }
545     }
546
547     // Remove transactions which depend on inputs of tx, recursively
548     list<CTransaction> result;
549     BOOST_FOREACH(const CTxIn &txin, tx.vin) {
550         std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(txin.prevout);
551         if (it != mapNextTx.end()) {
552             const CTransaction &txConflict = *it->second.ptx;
553             if (txConflict != tx)
554             {
555                 remove(txConflict, removed, true);
556             }
557         }
558     }
559
560     BOOST_FOREACH(const JSDescription &joinsplit, tx.vJoinSplit) {
561         BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
562             std::map<uint256, const CTransaction*>::iterator it = mapSproutNullifiers.find(nf);
563             if (it != mapSproutNullifiers.end()) {
564                 const CTransaction &txConflict = *it->second;
565                 if (txConflict != tx) {
566                     remove(txConflict, removed, true);
567                 }
568             }
569         }
570     }
571     for (const SpendDescription &spendDescription : tx.vShieldedSpend) {
572         std::map<uint256, const CTransaction*>::iterator it = mapSaplingNullifiers.find(spendDescription.nullifier);
573         if (it != mapSaplingNullifiers.end()) {
574             const CTransaction &txConflict = *it->second;
575             if (txConflict != tx) {
576                 remove(txConflict, removed, true);
577             }
578         }
579     }
580 }
581
582 int32_t komodo_validate_interest(const CTransaction &tx,int32_t txheight,uint32_t nTime,int32_t dispflag);
583 extern char ASSETCHAINS_SYMBOL[];
584
585 void CTxMemPool::removeExpired(unsigned int nBlockHeight)
586 {
587     CBlockIndex *tipindex;
588     // Remove expired txs and leftover coinbases from the mempool
589     LOCK(cs);
590     list<CTransaction> transactionsToRemove;
591     for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++)
592     {
593         const CTransaction& tx = it->GetTx();
594         tipindex = chainActive.LastTip();
595         if (tx.IsCoinBase() || IsExpiredTx(tx, nBlockHeight))
596         {
597             transactionsToRemove.push_back(tx);
598         }
599     }
600     for (const CTransaction& tx : transactionsToRemove) {
601         list<CTransaction> removed;
602         remove(tx, removed, true);
603         LogPrint("mempool", "Removing expired txid: %s\n", tx.GetHash().ToString());
604     }
605 }
606
607 /**
608  * Called when a block is connected. Removes from mempool and updates the miner fee estimator.
609  */
610 void CTxMemPool::removeForBlock(const std::vector<CTransaction>& vtx, unsigned int nBlockHeight,
611                                 std::list<CTransaction>& conflicts, bool fCurrentEstimate)
612 {
613     LOCK(cs);
614     std::vector<CTxMemPoolEntry> entries;
615     BOOST_FOREACH(const CTransaction& tx, vtx)
616     {
617         uint256 hash = tx.GetHash();
618
619         indexed_transaction_set::iterator i = mapTx.find(hash);
620         if (i != mapTx.end())
621             entries.push_back(*i);
622     }
623     BOOST_FOREACH(const CTransaction& tx, vtx)
624     {
625         std::list<CTransaction> dummy;
626         remove(tx, dummy, false);
627         removeConflicts(tx, conflicts);
628         ClearPrioritisation(tx.GetHash());
629     }
630     // After the txs in the new block have been removed from the mempool, update policy estimates
631     minerPolicyEstimator->processBlock(nBlockHeight, entries, fCurrentEstimate);
632 }
633
634 /**
635  * Called whenever the tip changes. Removes transactions which don't commit to
636  * the given branch ID from the mempool.
637  */
638 void CTxMemPool::removeWithoutBranchId(uint32_t nMemPoolBranchId)
639 {
640     LOCK(cs);
641     std::list<CTransaction> transactionsToRemove;
642
643     for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
644         const CTransaction& tx = it->GetTx();
645         if (it->GetValidatedBranchId() != nMemPoolBranchId) {
646             transactionsToRemove.push_back(tx);
647         }
648     }
649
650     for (const CTransaction& tx : transactionsToRemove) {
651         std::list<CTransaction> removed;
652         remove(tx, removed, true);
653     }
654 }
655
656 void CTxMemPool::clear()
657 {
658     LOCK(cs);
659     mapTx.clear();
660     mapNextTx.clear();
661     totalTxSize = 0;
662     cachedInnerUsage = 0;
663     ++nTransactionsUpdated;
664 }
665
666 void CTxMemPool::check(const CCoinsViewCache *pcoins) const
667 {
668     if (nCheckFrequency == 0)
669         return;
670
671     if (insecure_rand() >= nCheckFrequency)
672         return;
673
674     LogPrint("mempool", "Checking mempool with %u transactions and %u inputs\n", (unsigned int)mapTx.size(), (unsigned int)mapNextTx.size());
675
676     uint64_t checkTotal = 0;
677     uint64_t innerUsage = 0;
678
679     CCoinsViewCache mempoolDuplicate(const_cast<CCoinsViewCache*>(pcoins));
680     const int64_t nSpendHeight = GetSpendHeight(mempoolDuplicate);
681
682     LOCK(cs);
683     list<const CTxMemPoolEntry*> waitingOnDependants;
684     for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
685         unsigned int i = 0;
686         checkTotal += it->GetTxSize();
687         innerUsage += it->DynamicMemoryUsage();
688         const CTransaction& tx = it->GetTx();
689         bool fDependsWait = false;
690         BOOST_FOREACH(const CTxIn &txin, tx.vin) {
691             // Check that every mempool transaction's inputs refer to available coins, or other mempool tx's.
692             indexed_transaction_set::const_iterator it2 = mapTx.find(txin.prevout.hash);
693             if (it2 != mapTx.end()) {
694                 const CTransaction& tx2 = it2->GetTx();
695                 assert(tx2.vout.size() > txin.prevout.n && !tx2.vout[txin.prevout.n].IsNull());
696                 fDependsWait = true;
697             } else {
698                 const CCoins* coins = pcoins->AccessCoins(txin.prevout.hash);
699                 assert(coins && coins->IsAvailable(txin.prevout.n));
700             }
701             // Check whether its inputs are marked in mapNextTx.
702             std::map<COutPoint, CInPoint>::const_iterator it3 = mapNextTx.find(txin.prevout);
703             assert(it3 != mapNextTx.end());
704             assert(it3->second.ptx == &tx);
705             assert(it3->second.n == i);
706             i++;
707         }
708
709         boost::unordered_map<uint256, SproutMerkleTree, CCoinsKeyHasher> intermediates;
710
711         BOOST_FOREACH(const JSDescription &joinsplit, tx.vJoinSplit) {
712             BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
713                 assert(!pcoins->GetNullifier(nf, SPROUT));
714             }
715
716             SproutMerkleTree tree;
717             auto it = intermediates.find(joinsplit.anchor);
718             if (it != intermediates.end()) {
719                 tree = it->second;
720             } else {
721                 assert(pcoins->GetSproutAnchorAt(joinsplit.anchor, tree));
722             }
723
724             BOOST_FOREACH(const uint256& commitment, joinsplit.commitments)
725             {
726                 tree.append(commitment);
727             }
728
729             intermediates.insert(std::make_pair(tree.root(), tree));
730         }
731         for (const SpendDescription &spendDescription : tx.vShieldedSpend) {
732             SaplingMerkleTree tree;
733
734             assert(pcoins->GetSaplingAnchorAt(spendDescription.anchor, tree));
735             assert(!pcoins->GetNullifier(spendDescription.nullifier, SAPLING));
736         }
737         if (fDependsWait)
738             waitingOnDependants.push_back(&(*it));
739         else {
740             CValidationState state;
741             bool fCheckResult = tx.IsCoinBase() ||
742                 Consensus::CheckTxInputs(tx, state, mempoolDuplicate, nSpendHeight, Params().GetConsensus());
743             assert(fCheckResult);
744             UpdateCoins(tx, mempoolDuplicate, 1000000);
745         }
746     }
747     unsigned int stepsSinceLastRemove = 0;
748     while (!waitingOnDependants.empty()) {
749         const CTxMemPoolEntry* entry = waitingOnDependants.front();
750         waitingOnDependants.pop_front();
751         CValidationState state;
752         if (!mempoolDuplicate.HaveInputs(entry->GetTx())) {
753             waitingOnDependants.push_back(entry);
754             stepsSinceLastRemove++;
755             assert(stepsSinceLastRemove < waitingOnDependants.size());
756         } else {
757             bool fCheckResult = entry->GetTx().IsCoinBase() ||
758                 Consensus::CheckTxInputs(entry->GetTx(), state, mempoolDuplicate, nSpendHeight, Params().GetConsensus());
759             assert(fCheckResult);
760             UpdateCoins(entry->GetTx(), mempoolDuplicate, 1000000);
761             stepsSinceLastRemove = 0;
762         }
763     }
764     for (std::map<COutPoint, CInPoint>::const_iterator it = mapNextTx.begin(); it != mapNextTx.end(); it++) {
765         uint256 hash = it->second.ptx->GetHash();
766         indexed_transaction_set::const_iterator it2 = mapTx.find(hash);
767         const CTransaction& tx = it2->GetTx();
768         assert(it2 != mapTx.end());
769         assert(&tx == it->second.ptx);
770         assert(tx.vin.size() > it->second.n);
771         assert(it->first == it->second.ptx->vin[it->second.n].prevout);
772     }
773
774     checkNullifiers(SPROUT);
775     checkNullifiers(SAPLING);
776
777     assert(totalTxSize == checkTotal);
778     assert(innerUsage == cachedInnerUsage);
779 }
780
781 void CTxMemPool::checkNullifiers(ShieldedType type) const
782 {
783     const std::map<uint256, const CTransaction*>* mapToUse;
784     switch (type) {
785         case SPROUT:
786             mapToUse = &mapSproutNullifiers;
787             break;
788         case SAPLING:
789             mapToUse = &mapSaplingNullifiers;
790             break;
791         default:
792             throw runtime_error("Unknown nullifier type");
793     }
794     for (const auto& entry : *mapToUse) {
795         uint256 hash = entry.second->GetHash();
796         CTxMemPool::indexed_transaction_set::const_iterator findTx = mapTx.find(hash);
797         const CTransaction& tx = findTx->GetTx();
798         assert(findTx != mapTx.end());
799         assert(&tx == entry.second);
800     }
801 }
802
803 void CTxMemPool::queryHashes(vector<uint256>& vtxid)
804 {
805     vtxid.clear();
806
807     LOCK(cs);
808     vtxid.reserve(mapTx.size());
809     for (indexed_transaction_set::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
810         vtxid.push_back(mi->GetTx().GetHash());
811 }
812
813 bool CTxMemPool::lookup(uint256 hash, CTransaction& result) const
814 {
815     LOCK(cs);
816     indexed_transaction_set::const_iterator i = mapTx.find(hash);
817     if (i == mapTx.end()) return false;
818     result = i->GetTx();
819     return true;
820 }
821
822 CFeeRate CTxMemPool::estimateFee(int nBlocks) const
823 {
824     LOCK(cs);
825     return minerPolicyEstimator->estimateFee(nBlocks);
826 }
827 double CTxMemPool::estimatePriority(int nBlocks) const
828 {
829     LOCK(cs);
830     return minerPolicyEstimator->estimatePriority(nBlocks);
831 }
832
833 bool
834 CTxMemPool::WriteFeeEstimates(CAutoFile& fileout) const
835 {
836     try {
837         LOCK(cs);
838         fileout << 109900; // version required to read: 0.10.99 or later
839         fileout << CLIENT_VERSION; // version that wrote the file
840         minerPolicyEstimator->Write(fileout);
841     }
842     catch (const std::exception&) {
843         LogPrintf("CTxMemPool::WriteFeeEstimates(): unable to write policy estimator data (non-fatal)\n");
844         return false;
845     }
846     return true;
847 }
848
849 bool
850 CTxMemPool::ReadFeeEstimates(CAutoFile& filein)
851 {
852     try {
853         int nVersionRequired, nVersionThatWrote;
854         filein >> nVersionRequired >> nVersionThatWrote;
855         if (nVersionRequired > CLIENT_VERSION)
856             return error("CTxMemPool::ReadFeeEstimates(): up-version (%d) fee estimate file", nVersionRequired);
857
858         LOCK(cs);
859         minerPolicyEstimator->Read(filein);
860     }
861     catch (const std::exception&) {
862         LogPrintf("CTxMemPool::ReadFeeEstimates(): unable to read policy estimator data (non-fatal)\n");
863         return false;
864     }
865     return true;
866 }
867
868 void CTxMemPool::PrioritiseTransaction(const uint256 &hash, const string strHash, double dPriorityDelta, const CAmount& nFeeDelta)
869 {
870     {
871         LOCK(cs);
872         std::pair<double, CAmount> &deltas = mapDeltas[hash];
873         deltas.first += dPriorityDelta;
874         deltas.second += nFeeDelta;
875     }
876     if (fDebug)
877     {
878         LogPrintf("PrioritiseTransaction: %s priority += %f, fee += %d\n", strHash, dPriorityDelta, FormatMoney(nFeeDelta));
879     }
880 }
881
882 void CTxMemPool::ApplyDeltas(const uint256 hash, double &dPriorityDelta, CAmount &nFeeDelta)
883 {
884     LOCK(cs);
885     std::map<uint256, std::pair<double, CAmount> >::iterator pos = mapDeltas.find(hash);
886     if (pos == mapDeltas.end())
887         return;
888     const std::pair<double, CAmount> &deltas = pos->second;
889     dPriorityDelta += deltas.first;
890     nFeeDelta += deltas.second;
891 }
892
893 void CTxMemPool::ClearPrioritisation(const uint256 hash)
894 {
895     LOCK(cs);
896     mapDeltas.erase(hash);
897     mapReserveTransactions.erase(hash);
898 }
899
900 bool CTxMemPool::PrioritiseReserveTransaction(const CReserveTransactionDescriptor &txDesc, const CCurrencyState &currencyState)
901 {
902     LOCK(cs);
903     uint256 hash = txDesc.ptx->GetHash();
904     auto it = mapReserveTransactions.find(hash);
905     if (txDesc.IsValid())
906     {
907         mapReserveTransactions[hash] = txDesc;
908         CAmount feeDelta = txDesc.AllFeesAsNative(currencyState);
909         PrioritiseTransaction(hash, hash.GetHex().c_str(), (double)feeDelta * 100.0, feeDelta);
910         return true;
911     }
912     return false;
913 }
914
915 bool CTxMemPool::IsKnownReserveTransaction(const uint256 &hash, CReserveTransactionDescriptor &txDesc)
916 {
917     LOCK(cs);
918     auto it = mapReserveTransactions.find(hash);
919     if (it != mapReserveTransactions.end() && it->second.IsValid())
920     {
921         // refresh transaction from mempool or delete it if not found (we may not need this at all)
922         indexed_transaction_set::const_iterator i = mapTx.find(hash);
923         if (i == mapTx.end())
924         {
925             ClearPrioritisation(hash);
926         }
927         else
928         {
929             it->second.ptx = &(i->GetTx());
930
931             txDesc = it->second;
932             return true;
933         }
934     }
935     return false;
936 }
937
938 bool CTxMemPool::HasNoInputsOf(const CTransaction &tx) const
939 {
940     for (unsigned int i = 0; i < tx.vin.size(); i++)
941         if (exists(tx.vin[i].prevout.hash))
942             return false;
943     return true;
944 }
945
946 bool CTxMemPool::nullifierExists(const uint256& nullifier, ShieldedType type) const
947 {
948     switch (type) {
949         case SPROUT:
950             return mapSproutNullifiers.count(nullifier);
951         case SAPLING:
952             return mapSaplingNullifiers.count(nullifier);
953         default:
954             throw runtime_error("Unknown nullifier type");
955     }
956 }
957
958 void CTxMemPool::NotifyRecentlyAdded()
959 {
960     uint64_t recentlyAddedSequence;
961     std::vector<CTransaction> txs;
962     {
963         LOCK(cs);
964         recentlyAddedSequence = nRecentlyAddedSequence;
965         for (const auto& kv : mapRecentlyAddedTx) {
966             txs.push_back(*(kv.second));
967         }
968         mapRecentlyAddedTx.clear();
969     }
970
971     // A race condition can occur here between these SyncWithWallets calls, and
972     // the ones triggered by block logic (in ConnectTip and DisconnectTip). It
973     // is harmless because calling SyncWithWallets(_, NULL) does not alter the
974     // wallet transaction's block information.
975     for (auto tx : txs) {
976         try {
977             SyncWithWallets(tx, NULL);
978         } catch (const boost::thread_interrupted&) {
979             throw;
980         } catch (const std::exception& e) {
981             PrintExceptionContinue(&e, "CTxMemPool::NotifyRecentlyAdded()");
982         } catch (...) {
983             PrintExceptionContinue(NULL, "CTxMemPool::NotifyRecentlyAdded()");
984         }
985     }
986
987     // Update the notified sequence number. We only need this in regtest mode,
988     // and should not lock on cs after calling SyncWithWallets otherwise.
989     if (Params().NetworkIDString() == "regtest") {
990         LOCK(cs);
991         nNotifiedSequence = recentlyAddedSequence;
992     }
993 }
994
995 bool CTxMemPool::IsFullyNotified() {
996     assert(Params().NetworkIDString() == "regtest");
997     LOCK(cs);
998     return nRecentlyAddedSequence == nNotifiedSequence;
999 }
1000
1001 CCoinsViewMemPool::CCoinsViewMemPool(CCoinsView *baseIn, CTxMemPool &mempoolIn) : CCoinsViewBacked(baseIn), mempool(mempoolIn) { }
1002
1003 bool CCoinsViewMemPool::GetNullifier(const uint256 &nf, ShieldedType type) const
1004 {
1005     return mempool.nullifierExists(nf, type) || base->GetNullifier(nf, type);
1006 }
1007
1008 bool CCoinsViewMemPool::GetCoins(const uint256 &txid, CCoins &coins) const {
1009     // If an entry in the mempool exists, always return that one, as it's guaranteed to never
1010     // conflict with the underlying cache, and it cannot have pruned entries (as it contains full)
1011     // transactions. First checking the underlying cache risks returning a pruned entry instead.
1012     CTransaction tx;
1013     if (mempool.lookup(txid, tx)) {
1014         coins = CCoins(tx, MEMPOOL_HEIGHT);
1015         return true;
1016     }
1017     return (base->GetCoins(txid, coins) && !coins.IsPruned());
1018 }
1019
1020 bool CCoinsViewMemPool::HaveCoins(const uint256 &txid) const {
1021     return mempool.exists(txid) || base->HaveCoins(txid);
1022 }
1023
1024 size_t CTxMemPool::DynamicMemoryUsage() const {
1025     LOCK(cs);
1026     // Estimate the overhead of mapTx to be 6 pointers + an allocation, as no exact formula for boost::multi_index_contained is implemented.
1027     return memusage::MallocUsage(sizeof(CTxMemPoolEntry) + 6 * sizeof(void*)) * mapTx.size() + memusage::DynamicUsage(mapNextTx) + memusage::DynamicUsage(mapDeltas) + memusage::DynamicUsage(mapDeltas) + memusage::DynamicUsage(mapDeltas) + cachedInnerUsage;
1028 }
This page took 0.082097 seconds and 4 git commands to generate.