]> Git Repo - VerusCoin.git/blame - src/txmempool.cpp
Support full identity history and manual hold for automatic transaction sync
[VerusCoin.git] / src / txmempool.cpp
CommitLineData
319b1160 1// Copyright (c) 2009-2010 Satoshi Nakamoto
f914f1a7 2// Copyright (c) 2009-2014 The Bitcoin Core developers
7329fdd1 3// Distributed under the MIT software license, see the accompanying
bc909a7a 4// file COPYING or https://www.opensource.org/licenses/mit-license.php .
319b1160 5
319b1160 6#include "txmempool.h"
611116d4 7
71697f97 8#include "clientversion.h"
691161d4 9#include "consensus/consensus.h"
da29ecbc 10#include "consensus/validation.h"
b7b4318f 11#include "main.h"
b649e039 12#include "policy/fees.h"
fa736190 13#include "streams.h"
f5b35d23 14#include "timedata.h"
ad49c256 15#include "util.h"
a372168e 16#include "utilmoneystr.h"
3ff68c50 17#include "validationinterface.h"
85c579e3 18#include "version.h"
41f170fd 19#include "pbaas/pbaas.h"
7e2cbee1 20#define _COINBASE_MATURITY 100
319b1160
GA
21
22using namespace std;
23
8bdd2877 24CTxMemPoolEntry::CTxMemPoolEntry():
a4b25180 25 nFee(0), nTxSize(0), nModSize(0), nUsageSize(0), nTime(0), dPriority(0.0),
41f170fd 26 hadNoDependencies(false), spendsCoinbase(false), hasReserve(false)
4d707d51
GA
27{
28 nHeight = MEMPOOL_HEIGHT;
29}
30
a372168e 31CTxMemPoolEntry::CTxMemPoolEntry(const CTransaction& _tx, const CAmount& _nFee,
4d707d51 32 int64_t _nTime, double _dPriority,
a4b25180 33 unsigned int _nHeight, bool poolHasNoInputsOf,
41f170fd 34 bool _spendsCoinbase, uint32_t _nBranchId, bool hasreserve):
b649e039 35 tx(_tx), nFee(_nFee), nTime(_nTime), dPriority(_dPriority), nHeight(_nHeight),
41f170fd 36 hadNoDependencies(poolHasNoInputsOf), hasReserve(hasreserve),
34a64fe0 37 spendsCoinbase(_spendsCoinbase), nBranchId(_nBranchId)
4d707d51
GA
38{
39 nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
c26649f9 40 nModSize = tx.CalculateModifiedSize(nTxSize);
6bd1d60c 41 nUsageSize = RecursiveDynamicUsage(tx);
e328fa32 42 feeRate = CFeeRate(nFee, nTxSize);
4d707d51
GA
43}
44
45CTxMemPoolEntry::CTxMemPoolEntry(const CTxMemPoolEntry& other)
46{
47 *this = other;
48}
49
50double
51CTxMemPoolEntry::GetPriority(unsigned int currentHeight) const
52{
a372168e 53 CAmount nValueIn = tx.GetValueOut()+nFee;
41f170fd 54 CCurrencyState currencyState;
1e583775 55 unsigned int lastHeight = currentHeight < 1 ? 0 : currentHeight - 1;
56 if (hasReserve && (currencyState = ConnectedChains.GetCurrencyState(currentHeight - 1)).IsValid())
41f170fd 57 {
1e583775 58 nValueIn += currencyState.ReserveToNative(tx.GetReserveValueOut());
41f170fd 59 }
c26649f9 60 double deltaPriority = ((double)(currentHeight-nHeight)*nValueIn)/nModSize;
4d707d51
GA
61 double dResult = dPriority + deltaPriority;
62 return dResult;
63}
64
8bdd2877 65CTxMemPool::CTxMemPool(const CFeeRate& _minRelayFee) :
b649e039 66 nTransactionsUpdated(0)
319b1160
GA
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
934fd197 71 nCheckFrequency = 0;
171ca774 72
b649e039 73 minerPolicyEstimator = new CBlockPolicyEstimator(_minRelayFee);
171ca774
GA
74}
75
76CTxMemPool::~CTxMemPool()
77{
78 delete minerPolicyEstimator;
319b1160
GA
79}
80
81void 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
94unsigned int CTxMemPool::GetTransactionsUpdated() const
95{
96 LOCK(cs);
97 return nTransactionsUpdated;
98}
99
100void CTxMemPool::AddTransactionsUpdated(unsigned int n)
101{
102 LOCK(cs);
103 nTransactionsUpdated += n;
104}
105
106
b649e039 107bool CTxMemPool::addUnchecked(const uint256& hash, const CTxMemPoolEntry &entry, bool fCurrentEstimate)
319b1160
GA
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);
e328fa32
AH
113 mapTx.insert(entry);
114 const CTransaction& tx = mapTx.find(hash)->GetTx();
3ff68c50 115 mapRecentlyAddedTx[tx.GetHash()] = &tx;
9d8322a3 116 nRecentlyAddedSequence += 1;
0cb91a8d
SS
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 }
f57f76d7 121 BOOST_FOREACH(const JSDescription &joinsplit, tx.vJoinSplit) {
22de1602 122 BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
9669920f 123 mapSproutNullifiers[nf] = &tx;
d66877af
SB
124 }
125 }
cab341e1
EOW
126 for (const SpendDescription &spendDescription : tx.vShieldedSpend) {
127 mapSaplingNullifiers[spendDescription.nullifier] = &tx;
128 }
b649e039
AM
129 nTransactionsUpdated++;
130 totalTxSize += entry.GetTxSize();
bde5c8b0 131 cachedInnerUsage += entry.DynamicMemoryUsage();
b649e039
AM
132 minerPolicyEstimator->processTransaction(entry, fCurrentEstimate);
133
319b1160
GA
134 return true;
135}
136
8b78a819
T
137void 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();
1fa4454d
MT
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);
88d014d0 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));
7f190223 155 inserted.push_back(key);
156 }
8b78a819
T
157 }
158
68e174e2
LR
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
8b78a819
T
169 mapAddressInserted.insert(make_pair(txhash, inserted));
170}
171
88d014d0 172bool CTxMemPool::getAddressIndex(const std::vector<std::pair<uint160, int> > &addresses, std::vector<std::pair<CMempoolAddressDeltaKey, CMempoolAddressDelta> > &results)
8b78a819
T
173{
174 LOCK(cs);
88d014d0 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));
8b78a819
T
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
185bool CTxMemPool::removeAddressIndex(const uint256 txhash)
186{
187 LOCK(cs);
68e174e2 188 auto it = mapAddressInserted.find(txhash);
8b78a819
T
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
201void CTxMemPool::addSpentIndex(const CTxMemPoolEntry &entry, const CCoinsViewCache &view)
202{
203 LOCK(cs);
8b78a819 204 const CTransaction& tx = entry.GetTx();
86b23f37 205 uint256 txhash = tx.GetHash();
8b78a819
T
206 std::vector<CSpentIndexKey> inserted;
207
8b78a819
T
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);
8b78a819 211 CSpentIndexKey key = CSpentIndexKey(input.prevout.hash, input.prevout.n);
86b23f37
LR
212 CSpentIndexValue value = CSpentIndexValue(txhash, j, -1, prevout.nValue,
213 prevout.scriptPubKey.GetType(),
214 prevout.scriptPubKey.AddressHash());
8b78a819
T
215 mapSpent.insert(make_pair(key, value));
216 inserted.push_back(key);
8b78a819 217 }
8b78a819
T
218 mapSpentInserted.insert(make_pair(txhash, inserted));
219}
220
86b23f37 221bool CTxMemPool::getSpentIndex(const CSpentIndexKey &key, CSpentIndexValue &value)
8b78a819
T
222{
223 LOCK(cs);
86b23f37 224 std::map<CSpentIndexKey, CSpentIndexValue, CSpentIndexKeyCompare>::iterator it = mapSpent.find(key);
8b78a819
T
225 if (it != mapSpent.end()) {
226 value = it->second;
227 return true;
228 }
229 return false;
230}
231
232bool CTxMemPool::removeSpentIndex(const uint256 txhash)
233{
234 LOCK(cs);
86b23f37 235 auto it = mapSpentInserted.find(txhash);
8b78a819
T
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}
319b1160 247
7fd6219a 248void CTxMemPool::remove(const CTransaction &origTx, std::list<CTransaction>& removed, bool fRecursive)
319b1160
GA
249{
250 // Remove transaction from memory pool
251 {
252 LOCK(cs);
7fd6219a 253 std::deque<uint256> txToRemove;
805344dc
S
254 txToRemove.push_back(origTx.GetHash());
255 if (fRecursive && !mapTx.count(origTx.GetHash())) {
ad9e86dc
GA
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++) {
805344dc 261 std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(COutPoint(origTx.GetHash(), i));
ad9e86dc
GA
262 if (it == mapNextTx.end())
263 continue;
805344dc 264 txToRemove.push_back(it->second.ptx->GetHash());
ad9e86dc
GA
265 }
266 }
7fd6219a 267 while (!txToRemove.empty())
319b1160 268 {
7fd6219a
MC
269 uint256 hash = txToRemove.front();
270 txToRemove.pop_front();
271 if (!mapTx.count(hash))
272 continue;
e328fa32 273 const CTransaction& tx = mapTx.find(hash)->GetTx();
7fd6219a
MC
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;
805344dc 279 txToRemove.push_back(it->second.ptx->GetHash());
7fd6219a
MC
280 }
281 }
3ff68c50 282 mapRecentlyAddedTx.erase(hash);
319b1160
GA
283 BOOST_FOREACH(const CTxIn& txin, tx.vin)
284 mapNextTx.erase(txin.prevout);
f57f76d7 285 BOOST_FOREACH(const JSDescription& joinsplit, tx.vJoinSplit) {
22de1602 286 BOOST_FOREACH(const uint256& nf, joinsplit.nullifiers) {
9669920f 287 mapSproutNullifiers.erase(nf);
d66877af
SB
288 }
289 }
cab341e1
EOW
290 for (const SpendDescription &spendDescription : tx.vShieldedSpend) {
291 mapSaplingNullifiers.erase(spendDescription.nullifier);
292 }
7fd6219a 293 removed.push_back(tx);
e328fa32
AH
294 totalTxSize -= mapTx.find(hash)->GetTxSize();
295 cachedInnerUsage -= mapTx.find(hash)->DynamicMemoryUsage();
319b1160
GA
296 mapTx.erase(hash);
297 nTransactionsUpdated++;
b649e039 298 minerPolicyEstimator->removeTx(hash);
68e174e2
LR
299 if (fAddressIndex)
300 removeAddressIndex(hash);
86b23f37
LR
301 if (fSpentIndex)
302 removeSpentIndex(hash);
41f170fd 303 ClearPrioritisation(tx.GetHash());
319b1160
GA
304 }
305 }
319b1160
GA
306}
307
0a962eb9 308extern uint64_t ASSETCHAINS_TIMELOCKGTE;
e980a26d 309int64_t komodo_block_unlocktime(uint32_t nHeight);
310
233c9eb6 311void CTxMemPool::removeForReorg(const CCoinsViewCache *pcoins, unsigned int nMemPoolHeight, int flags)
723d12c0
MC
312{
313 // Remove transactions spending a coinbase which are now immature
9edf27ec 314 extern char ASSETCHAINS_SYMBOL[KOMODO_ASSETCHAIN_MAXLEN];
b2a98c42 315
7a90b9dd 316 if ( ASSETCHAINS_SYMBOL[0] == 0 )
317 COINBASE_MATURITY = _COINBASE_MATURITY;
b2a98c42 318
c944d161 319 // Remove transactions spending a coinbase which are now immature and no-longer-final transactions
723d12c0
MC
320 LOCK(cs);
321 list<CTransaction> transactionsToRemove;
e328fa32
AH
322 for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
323 const CTransaction& tx = it->GetTx();
233c9eb6 324 if (!CheckFinalTx(tx, flags)) {
f5b35d23 325 transactionsToRemove.push_back(tx);
a4b25180 326 } else if (it->GetSpendsCoinbase()) {
f5b35d23
MC
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);
e980a26d 332 if (nCheckFrequency != 0) assert(coins);
b2a98c42
MT
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))) {
f5b35d23
MC
338 transactionsToRemove.push_back(tx);
339 break;
340 }
723d12c0
MC
341 }
342 }
343 }
344 BOOST_FOREACH(const CTransaction& tx, transactionsToRemove) {
345 list<CTransaction> removed;
346 remove(tx, removed, true);
347 }
348}
349
a8ac403d 350
98d2f090 351void CTxMemPool::removeWithAnchor(const uint256 &invalidRoot, ShieldedType type)
a8ac403d
SB
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
e328fa32
AH
360 for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
361 const CTransaction& tx = it->GetTx();
98d2f090
SB
362 switch (type) {
363 case SPROUT:
f57f76d7 364 BOOST_FOREACH(const JSDescription& joinsplit, tx.vJoinSplit) {
98d2f090
SB
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:
8c57bbac 380 throw runtime_error("Unknown shielded type");
98d2f090 381 break;
a8ac403d
SB
382 }
383 }
384
385 BOOST_FOREACH(const CTransaction& tx, transactionsToRemove) {
386 list<CTransaction> removed;
387 remove(tx, removed, true);
388 }
389}
390
93a18a36 391void CTxMemPool::removeConflicts(const CTransaction &tx, std::list<CTransaction>& removed)
319b1160
GA
392{
393 // Remove transactions which depend on inputs of tx, recursively
98e84aae 394 list<CTransaction> result;
319b1160
GA
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)
93a18a36
GA
401 {
402 remove(txConflict, removed, true);
403 }
319b1160
GA
404 }
405 }
d66877af 406
f57f76d7 407 BOOST_FOREACH(const JSDescription &joinsplit, tx.vJoinSplit) {
22de1602 408 BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
9669920f
EOW
409 std::map<uint256, const CTransaction*>::iterator it = mapSproutNullifiers.find(nf);
410 if (it != mapSproutNullifiers.end()) {
d66877af 411 const CTransaction &txConflict = *it->second;
9669920f 412 if (txConflict != tx) {
d66877af
SB
413 remove(txConflict, removed, true);
414 }
415 }
416 }
417 }
cab341e1
EOW
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;
9669920f 422 if (txConflict != tx) {
cab341e1 423 remove(txConflict, removed, true);
9669920f 424 }
cab341e1
EOW
425 }
426 }
319b1160
GA
427}
428
f045635e 429int32_t komodo_validate_interest(const CTransaction &tx,int32_t txheight,uint32_t nTime,int32_t dispflag);
f839d3f5 430extern char ASSETCHAINS_SYMBOL[];
f045635e 431
9bb37bf0
JG
432void CTxMemPool::removeExpired(unsigned int nBlockHeight)
433{
f045635e 434 CBlockIndex *tipindex;
9bb37bf0
JG
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();
86131275 441 tipindex = chainActive.LastTip();
4b729ec5 442 if (IsExpiredTx(tx, nBlockHeight) || (ASSETCHAINS_SYMBOL[0] == 0 && tipindex != 0 && komodo_validate_interest(tx,tipindex->GetHeight()+1,tipindex->GetMedianTimePast() + 777,0)) < 0)
4825cbeb 443 {
9bb37bf0
JG
444 transactionsToRemove.push_back(tx);
445 }
446 }
447 for (const CTransaction& tx : transactionsToRemove) {
448 list<CTransaction> removed;
449 remove(tx, removed, true);
eb138626 450 LogPrint("mempool", "Removing expired txid: %s\n", tx.GetHash().ToString());
9bb37bf0
JG
451 }
452}
453
7329fdd1
MF
454/**
455 * Called when a block is connected. Removes from mempool and updates the miner fee estimator.
456 */
171ca774 457void CTxMemPool::removeForBlock(const std::vector<CTransaction>& vtx, unsigned int nBlockHeight,
b649e039 458 std::list<CTransaction>& conflicts, bool fCurrentEstimate)
171ca774
GA
459{
460 LOCK(cs);
461 std::vector<CTxMemPoolEntry> entries;
462 BOOST_FOREACH(const CTransaction& tx, vtx)
463 {
805344dc 464 uint256 hash = tx.GetHash();
e328fa32
AH
465
466 indexed_transaction_set::iterator i = mapTx.find(hash);
467 if (i != mapTx.end())
468 entries.push_back(*i);
171ca774 469 }
171ca774
GA
470 BOOST_FOREACH(const CTransaction& tx, vtx)
471 {
472 std::list<CTransaction> dummy;
473 remove(tx, dummy, false);
474 removeConflicts(tx, conflicts);
805344dc 475 ClearPrioritisation(tx.GetHash());
171ca774 476 }
b649e039
AM
477 // After the txs in the new block have been removed from the mempool, update policy estimates
478 minerPolicyEstimator->processBlock(nBlockHeight, entries, fCurrentEstimate);
171ca774
GA
479}
480
34a64fe0
JG
481/**
482 * Called whenever the tip changes. Removes transactions which don't commit to
483 * the given branch ID from the mempool.
484 */
485void 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
319b1160
GA
503void CTxMemPool::clear()
504{
505 LOCK(cs);
506 mapTx.clear();
507 mapNextTx.clear();
6f2c26a4 508 totalTxSize = 0;
bde5c8b0 509 cachedInnerUsage = 0;
319b1160
GA
510 ++nTransactionsUpdated;
511}
512
d0867acb 513void CTxMemPool::check(const CCoinsViewCache *pcoins) const
319b1160 514{
934fd197
PW
515 if (nCheckFrequency == 0)
516 return;
517
518 if (insecure_rand() >= nCheckFrequency)
319b1160
GA
519 return;
520
521 LogPrint("mempool", "Checking mempool with %u transactions and %u inputs\n", (unsigned int)mapTx.size(), (unsigned int)mapNextTx.size());
522
6f2c26a4 523 uint64_t checkTotal = 0;
bde5c8b0 524 uint64_t innerUsage = 0;
6f2c26a4 525
b7b4318f 526 CCoinsViewCache mempoolDuplicate(const_cast<CCoinsViewCache*>(pcoins));
722d811f 527 const int64_t nSpendHeight = GetSpendHeight(mempoolDuplicate);
b7b4318f 528
319b1160 529 LOCK(cs);
b7b4318f 530 list<const CTxMemPoolEntry*> waitingOnDependants;
e328fa32 531 for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
319b1160 532 unsigned int i = 0;
e328fa32
AH
533 checkTotal += it->GetTxSize();
534 innerUsage += it->DynamicMemoryUsage();
535 const CTransaction& tx = it->GetTx();
b7b4318f 536 bool fDependsWait = false;
4d707d51 537 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
319b1160 538 // Check that every mempool transaction's inputs refer to available coins, or other mempool tx's.
e328fa32 539 indexed_transaction_set::const_iterator it2 = mapTx.find(txin.prevout.hash);
319b1160 540 if (it2 != mapTx.end()) {
e328fa32 541 const CTransaction& tx2 = it2->GetTx();
4d707d51 542 assert(tx2.vout.size() > txin.prevout.n && !tx2.vout[txin.prevout.n].IsNull());
b7b4318f 543 fDependsWait = true;
319b1160 544 } else {
629d75fa
PW
545 const CCoins* coins = pcoins->AccessCoins(txin.prevout.hash);
546 assert(coins && coins->IsAvailable(txin.prevout.n));
319b1160
GA
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());
4d707d51 551 assert(it3->second.ptx == &tx);
319b1160
GA
552 assert(it3->second.n == i);
553 i++;
554 }
a667caec 555
4fc309f0 556 boost::unordered_map<uint256, SproutMerkleTree, CCoinsKeyHasher> intermediates;
a667caec 557
f57f76d7 558 BOOST_FOREACH(const JSDescription &joinsplit, tx.vJoinSplit) {
22de1602 559 BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
28d20bdb 560 assert(!pcoins->GetNullifier(nf, SPROUT));
d66877af
SB
561 }
562
4fc309f0 563 SproutMerkleTree tree;
b7e4abd6 564 auto it = intermediates.find(joinsplit.anchor);
a667caec
SB
565 if (it != intermediates.end()) {
566 tree = it->second;
567 } else {
008f4ee8 568 assert(pcoins->GetSproutAnchorAt(joinsplit.anchor, tree));
a667caec
SB
569 }
570
b7e4abd6 571 BOOST_FOREACH(const uint256& commitment, joinsplit.commitments)
a667caec
SB
572 {
573 tree.append(commitment);
574 }
575
576 intermediates.insert(std::make_pair(tree.root(), tree));
d66877af 577 }
cab341e1 578 for (const SpendDescription &spendDescription : tx.vShieldedSpend) {
4fc309f0 579 SaplingMerkleTree tree;
b4ff7076
SB
580
581 assert(pcoins->GetSaplingAnchorAt(spendDescription.anchor, tree));
28d20bdb 582 assert(!pcoins->GetNullifier(spendDescription.nullifier, SAPLING));
cab341e1 583 }
b7b4318f 584 if (fDependsWait)
e328fa32 585 waitingOnDependants.push_back(&(*it));
b7b4318f 586 else {
d7621ccf 587 CValidationState state;
722d811f
JT
588 bool fCheckResult = tx.IsCoinBase() ||
589 Consensus::CheckTxInputs(tx, state, mempoolDuplicate, nSpendHeight, Params().GetConsensus());
590 assert(fCheckResult);
8cb98d91 591 UpdateCoins(tx, mempoolDuplicate, 1000000);
b7b4318f
MC
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 {
722d811f
JT
604 bool fCheckResult = entry->GetTx().IsCoinBase() ||
605 Consensus::CheckTxInputs(entry->GetTx(), state, mempoolDuplicate, nSpendHeight, Params().GetConsensus());
606 assert(fCheckResult);
8cb98d91 607 UpdateCoins(entry->GetTx(), mempoolDuplicate, 1000000);
b7b4318f
MC
608 stepsSinceLastRemove = 0;
609 }
319b1160
GA
610 }
611 for (std::map<COutPoint, CInPoint>::const_iterator it = mapNextTx.begin(); it != mapNextTx.end(); it++) {
805344dc 612 uint256 hash = it->second.ptx->GetHash();
e328fa32
AH
613 indexed_transaction_set::const_iterator it2 = mapTx.find(hash);
614 const CTransaction& tx = it2->GetTx();
319b1160 615 assert(it2 != mapTx.end());
4d707d51
GA
616 assert(&tx == it->second.ptx);
617 assert(tx.vin.size() > it->second.n);
319b1160
GA
618 assert(it->first == it->second.ptx->vin[it->second.n].prevout);
619 }
6f2c26a4 620
28d20bdb
SB
621 checkNullifiers(SPROUT);
622 checkNullifiers(SAPLING);
d66877af 623
6f2c26a4 624 assert(totalTxSize == checkTotal);
bde5c8b0 625 assert(innerUsage == cachedInnerUsage);
319b1160
GA
626}
627
28d20bdb 628void CTxMemPool::checkNullifiers(ShieldedType type) const
685e936c 629{
708c87f1
EOW
630 const std::map<uint256, const CTransaction*>* mapToUse;
631 switch (type) {
28d20bdb 632 case SPROUT:
9669920f 633 mapToUse = &mapSproutNullifiers;
708c87f1 634 break;
28d20bdb 635 case SAPLING:
708c87f1
EOW
636 mapToUse = &mapSaplingNullifiers;
637 break;
638 default:
1f9dfbb9 639 throw runtime_error("Unknown nullifier type");
708c87f1 640 }
685e936c
EOW
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
4d707d51 650void CTxMemPool::queryHashes(vector<uint256>& vtxid)
319b1160
GA
651{
652 vtxid.clear();
653
654 LOCK(cs);
655 vtxid.reserve(mapTx.size());
e328fa32
AH
656 for (indexed_transaction_set::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
657 vtxid.push_back(mi->GetTx().GetHash());
319b1160
GA
658}
659
660bool CTxMemPool::lookup(uint256 hash, CTransaction& result) const
661{
662 LOCK(cs);
e328fa32 663 indexed_transaction_set::const_iterator i = mapTx.find(hash);
319b1160 664 if (i == mapTx.end()) return false;
e328fa32 665 result = i->GetTx();
319b1160
GA
666 return true;
667}
a0fa20a1 668
171ca774
GA
669CFeeRate CTxMemPool::estimateFee(int nBlocks) const
670{
671 LOCK(cs);
672 return minerPolicyEstimator->estimateFee(nBlocks);
673}
674double CTxMemPool::estimatePriority(int nBlocks) const
675{
676 LOCK(cs);
677 return minerPolicyEstimator->estimatePriority(nBlocks);
678}
679
680bool
681CTxMemPool::WriteFeeEstimates(CAutoFile& fileout) const
682{
683 try {
684 LOCK(cs);
b649e039 685 fileout << 109900; // version required to read: 0.10.99 or later
171ca774
GA
686 fileout << CLIENT_VERSION; // version that wrote the file
687 minerPolicyEstimator->Write(fileout);
688 }
27df4123 689 catch (const std::exception&) {
7ff9d122 690 LogPrintf("CTxMemPool::WriteFeeEstimates(): unable to write policy estimator data (non-fatal)\n");
171ca774
GA
691 return false;
692 }
693 return true;
694}
695
696bool
697CTxMemPool::ReadFeeEstimates(CAutoFile& filein)
698{
699 try {
700 int nVersionRequired, nVersionThatWrote;
701 filein >> nVersionRequired >> nVersionThatWrote;
702 if (nVersionRequired > CLIENT_VERSION)
5262fde0 703 return error("CTxMemPool::ReadFeeEstimates(): up-version (%d) fee estimate file", nVersionRequired);
171ca774
GA
704
705 LOCK(cs);
b649e039 706 minerPolicyEstimator->Read(filein);
171ca774 707 }
27df4123 708 catch (const std::exception&) {
7ff9d122 709 LogPrintf("CTxMemPool::ReadFeeEstimates(): unable to read policy estimator data (non-fatal)\n");
171ca774
GA
710 return false;
711 }
712 return true;
713}
714
41f170fd 715void CTxMemPool::PrioritiseTransaction(const uint256 &hash, const string strHash, double dPriorityDelta, const CAmount& nFeeDelta)
2a72d459
LD
716{
717 {
718 LOCK(cs);
a372168e 719 std::pair<double, CAmount> &deltas = mapDeltas[hash];
2a72d459
LD
720 deltas.first += dPriorityDelta;
721 deltas.second += nFeeDelta;
722 }
a372168e 723 LogPrintf("PrioritiseTransaction: %s priority += %f, fee += %d\n", strHash, dPriorityDelta, FormatMoney(nFeeDelta));
2a72d459
LD
724}
725
a372168e 726void CTxMemPool::ApplyDeltas(const uint256 hash, double &dPriorityDelta, CAmount &nFeeDelta)
2a72d459
LD
727{
728 LOCK(cs);
a372168e 729 std::map<uint256, std::pair<double, CAmount> >::iterator pos = mapDeltas.find(hash);
2a72d459
LD
730 if (pos == mapDeltas.end())
731 return;
a372168e 732 const std::pair<double, CAmount> &deltas = pos->second;
2a72d459
LD
733 dPriorityDelta += deltas.first;
734 nFeeDelta += deltas.second;
735}
736
737void CTxMemPool::ClearPrioritisation(const uint256 hash)
738{
739 LOCK(cs);
740 mapDeltas.erase(hash);
41f170fd
MT
741 mapReserveTransactions.erase(hash);
742}
743
47aecf2f 744bool CTxMemPool::PrioritiseReserveTransaction(const CReserveTransactionDescriptor &txDesc, const CCurrencyState &currencyState)
41f170fd
MT
745{
746 LOCK(cs);
747 uint256 hash = txDesc.ptx->GetHash();
748 auto it = mapReserveTransactions.find(hash);
47aecf2f 749 if (txDesc.IsValid())
41f170fd
MT
750 {
751 mapReserveTransactions[hash] = txDesc;
a1a4dc8b 752 CAmount feeDelta = currencyState.ReserveToNative(txDesc.ReserveFees() + txDesc.reserveConversionFees) + txDesc.nativeConversionFees;
753 PrioritiseTransaction(hash, hash.GetHex().c_str(), (double)feeDelta * 100.0, feeDelta);
47aecf2f 754 return true;
41f170fd 755 }
47aecf2f 756 return false;
41f170fd
MT
757}
758
47aecf2f 759bool CTxMemPool::IsKnownReserveTransaction(const uint256 &hash, CReserveTransactionDescriptor &txDesc)
41f170fd
MT
760{
761 LOCK(cs);
762 auto it = mapReserveTransactions.find(hash);
763 if (it != mapReserveTransactions.end() && it->second.IsValid())
764 {
1c3499f9 765 // refresh transaction from mempool or delete it if not found (we may not need this at all)
47aecf2f 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 }
41f170fd
MT
778 }
779 return false;
2a72d459
LD
780}
781
b649e039
AM
782bool 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}
171ca774 789
28d20bdb 790bool CTxMemPool::nullifierExists(const uint256& nullifier, ShieldedType type) const
685e936c 791{
708c87f1 792 switch (type) {
28d20bdb 793 case SPROUT:
9669920f 794 return mapSproutNullifiers.count(nullifier);
28d20bdb 795 case SAPLING:
708c87f1
EOW
796 return mapSaplingNullifiers.count(nullifier);
797 default:
1f9dfbb9 798 throw runtime_error("Unknown nullifier type");
708c87f1 799 }
685e936c 800}
a0fa20a1 801
3ff68c50
JG
802void CTxMemPool::NotifyRecentlyAdded()
803{
9d8322a3 804 uint64_t recentlyAddedSequence;
3ff68c50
JG
805 std::vector<CTransaction> txs;
806 {
807 LOCK(cs);
9d8322a3 808 recentlyAddedSequence = nRecentlyAddedSequence;
3ff68c50
JG
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 }
9d8322a3
JG
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
839bool CTxMemPool::IsFullyNotified() {
840 assert(Params().NetworkIDString() == "regtest");
841 LOCK(cs);
842 return nRecentlyAddedSequence == nNotifiedSequence;
3ff68c50
JG
843}
844
685e936c 845CCoinsViewMemPool::CCoinsViewMemPool(CCoinsView *baseIn, CTxMemPool &mempoolIn) : CCoinsViewBacked(baseIn), mempool(mempoolIn) { }
d66877af 846
28d20bdb 847bool CCoinsViewMemPool::GetNullifier(const uint256 &nf, ShieldedType type) const
685e936c 848{
708c87f1 849 return mempool.nullifierExists(nf, type) || base->GetNullifier(nf, type);
d66877af
SB
850}
851
a3dc587a 852bool CCoinsViewMemPool::GetCoins(const uint256 &txid, CCoins &coins) const {
ad08d0b9
PW
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.
a0fa20a1
PW
856 CTransaction tx;
857 if (mempool.lookup(txid, tx)) {
858 coins = CCoins(tx, MEMPOOL_HEIGHT);
859 return true;
860 }
ad08d0b9 861 return (base->GetCoins(txid, coins) && !coins.IsPruned());
a0fa20a1
PW
862}
863
a3dc587a 864bool CCoinsViewMemPool::HaveCoins(const uint256 &txid) const {
a0fa20a1
PW
865 return mempool.exists(txid) || base->HaveCoins(txid);
866}
bde5c8b0
PW
867
868size_t CTxMemPool::DynamicMemoryUsage() const {
869 LOCK(cs);
e328fa32 870 // Estimate the overhead of mapTx to be 6 pointers + an allocation, as no exact formula for boost::multi_index_contained is implemented.
41f170fd 871 return memusage::MallocUsage(sizeof(CTxMemPoolEntry) + 6 * sizeof(void*)) * mapTx.size() + memusage::DynamicUsage(mapNextTx) + memusage::DynamicUsage(mapDeltas) + memusage::DynamicUsage(mapDeltas) + memusage::DynamicUsage(mapDeltas) + cachedInnerUsage;
bde5c8b0 872}
This page took 0.459546 seconds and 4 git commands to generate.