]> Git Repo - VerusCoin.git/blame - src/txmempool.cpp
Continue attempting to notarize after running out of notary rewards
[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
319b1160
GA
4// file COPYING or http://www.opensource.org/licenses/mit-license.php.
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"
85c579e3 17#include "version.h"
41f170fd 18#include "pbaas/pbaas.h"
7e2cbee1 19#define _COINBASE_MATURITY 100
319b1160
GA
20
21using namespace std;
22
8bdd2877 23CTxMemPoolEntry::CTxMemPoolEntry():
a4b25180 24 nFee(0), nTxSize(0), nModSize(0), nUsageSize(0), nTime(0), dPriority(0.0),
41f170fd 25 hadNoDependencies(false), spendsCoinbase(false), hasReserve(false)
4d707d51
GA
26{
27 nHeight = MEMPOOL_HEIGHT;
28}
29
a372168e 30CTxMemPoolEntry::CTxMemPoolEntry(const CTransaction& _tx, const CAmount& _nFee,
4d707d51 31 int64_t _nTime, double _dPriority,
a4b25180 32 unsigned int _nHeight, bool poolHasNoInputsOf,
41f170fd 33 bool _spendsCoinbase, uint32_t _nBranchId, bool hasreserve):
b649e039 34 tx(_tx), nFee(_nFee), nTime(_nTime), dPriority(_dPriority), nHeight(_nHeight),
41f170fd 35 hadNoDependencies(poolHasNoInputsOf), hasReserve(hasreserve),
34a64fe0 36 spendsCoinbase(_spendsCoinbase), nBranchId(_nBranchId)
4d707d51
GA
37{
38 nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
c26649f9 39 nModSize = tx.CalculateModifiedSize(nTxSize);
6bd1d60c 40 nUsageSize = RecursiveDynamicUsage(tx);
e328fa32 41 feeRate = CFeeRate(nFee, nTxSize);
4d707d51
GA
42}
43
44CTxMemPoolEntry::CTxMemPoolEntry(const CTxMemPoolEntry& other)
45{
46 *this = other;
47}
48
49double
50CTxMemPoolEntry::GetPriority(unsigned int currentHeight) const
51{
a372168e 52 CAmount nValueIn = tx.GetValueOut()+nFee;
41f170fd 53 CCurrencyState currencyState;
1e583775 54 unsigned int lastHeight = currentHeight < 1 ? 0 : currentHeight - 1;
55 if (hasReserve && (currencyState = ConnectedChains.GetCurrencyState(currentHeight - 1)).IsValid())
41f170fd 56 {
1e583775 57 nValueIn += currencyState.ReserveToNative(tx.GetReserveValueOut());
41f170fd 58 }
c26649f9 59 double deltaPriority = ((double)(currentHeight-nHeight)*nValueIn)/nModSize;
4d707d51
GA
60 double dResult = dPriority + deltaPriority;
61 return dResult;
62}
63
8bdd2877 64CTxMemPool::CTxMemPool(const CFeeRate& _minRelayFee) :
b649e039 65 nTransactionsUpdated(0)
319b1160
GA
66{
67 // Sanity checks off by default for performance, because otherwise
68 // accepting transactions becomes O(N^2) where N is the number
69 // of transactions in the pool
934fd197 70 nCheckFrequency = 0;
171ca774 71
b649e039 72 minerPolicyEstimator = new CBlockPolicyEstimator(_minRelayFee);
171ca774
GA
73}
74
75CTxMemPool::~CTxMemPool()
76{
77 delete minerPolicyEstimator;
319b1160
GA
78}
79
80void CTxMemPool::pruneSpent(const uint256 &hashTx, CCoins &coins)
81{
82 LOCK(cs);
83
84 std::map<COutPoint, CInPoint>::iterator it = mapNextTx.lower_bound(COutPoint(hashTx, 0));
85
86 // iterate over all COutPoints in mapNextTx whose hash equals the provided hashTx
87 while (it != mapNextTx.end() && it->first.hash == hashTx) {
88 coins.Spend(it->first.n); // and remove those outputs from coins
89 it++;
90 }
91}
92
93unsigned int CTxMemPool::GetTransactionsUpdated() const
94{
95 LOCK(cs);
96 return nTransactionsUpdated;
97}
98
99void CTxMemPool::AddTransactionsUpdated(unsigned int n)
100{
101 LOCK(cs);
102 nTransactionsUpdated += n;
103}
104
105
b649e039 106bool CTxMemPool::addUnchecked(const uint256& hash, const CTxMemPoolEntry &entry, bool fCurrentEstimate)
319b1160
GA
107{
108 // Add to memory pool without checking anything.
109 // Used by main.cpp AcceptToMemoryPool(), which DOES do
110 // all the appropriate checks.
111 LOCK(cs);
e328fa32
AH
112 mapTx.insert(entry);
113 const CTransaction& tx = mapTx.find(hash)->GetTx();
0cb91a8d
SS
114 if (!tx.IsCoinImport()) {
115 for (unsigned int i = 0; i < tx.vin.size(); i++)
116 mapNextTx[tx.vin[i].prevout] = CInPoint(&tx, i);
117 }
b7e4abd6 118 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
22de1602 119 BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
9669920f 120 mapSproutNullifiers[nf] = &tx;
d66877af
SB
121 }
122 }
cab341e1
EOW
123 for (const SpendDescription &spendDescription : tx.vShieldedSpend) {
124 mapSaplingNullifiers[spendDescription.nullifier] = &tx;
125 }
b649e039
AM
126 nTransactionsUpdated++;
127 totalTxSize += entry.GetTxSize();
bde5c8b0 128 cachedInnerUsage += entry.DynamicMemoryUsage();
b649e039
AM
129 minerPolicyEstimator->processTransaction(entry, fCurrentEstimate);
130
319b1160
GA
131 return true;
132}
133
8b78a819
T
134void CTxMemPool::addAddressIndex(const CTxMemPoolEntry &entry, const CCoinsViewCache &view)
135{
136 LOCK(cs);
137 const CTransaction& tx = entry.GetTx();
138 std::vector<CMempoolAddressDeltaKey> inserted;
139
140 uint256 txhash = tx.GetHash();
1fa4454d
MT
141
142 if (!tx.IsCoinBase())
143 {
144 for (unsigned int j = 0; j < tx.vin.size(); j++) {
145 const CTxIn input = tx.vin[j];
146 const CTxOut &prevout = view.GetOutputFor(input);
147 if (prevout.scriptPubKey.IsPayToScriptHash()) {
148 vector<unsigned char> hashBytes(prevout.scriptPubKey.begin()+2, prevout.scriptPubKey.begin()+22);
149 CMempoolAddressDeltaKey key(2, uint160(hashBytes), txhash, j, 1);
150 CMempoolAddressDelta delta(entry.GetTime(), prevout.nValue * -1, input.prevout.hash, input.prevout.n);
151 mapAddress.insert(make_pair(key, delta));
152 inserted.push_back(key);
153 }
154 else if (prevout.scriptPubKey.IsPayToPublicKeyHash()) {
155 vector<unsigned char> hashBytes(prevout.scriptPubKey.begin()+3, prevout.scriptPubKey.begin()+23);
156 CMempoolAddressDeltaKey key(1, uint160(hashBytes), txhash, j, 1);
157 CMempoolAddressDelta delta(entry.GetTime(), prevout.nValue * -1, input.prevout.hash, input.prevout.n);
158 mapAddress.insert(make_pair(key, delta));
159 inserted.push_back(key);
160 }
161 else if (prevout.scriptPubKey.IsPayToPublicKey()) {
162 vector<unsigned char> hashBytes(prevout.scriptPubKey.begin()+1, prevout.scriptPubKey.begin()+34);
163 CMempoolAddressDeltaKey key(1, Hash160(hashBytes), txhash, j, 1);
164 CMempoolAddressDelta delta(entry.GetTime(), prevout.nValue * -1, input.prevout.hash, input.prevout.n);
165 mapAddress.insert(make_pair(key, delta));
166 inserted.push_back(key);
167 }
168 else if (prevout.scriptPubKey.IsPayToCryptoCondition()) {
169 vector<unsigned char> hashBytes(prevout.scriptPubKey.begin(), prevout.scriptPubKey.end());
170 CMempoolAddressDeltaKey key(1, Hash160(hashBytes), txhash, j, 1);
171 CMempoolAddressDelta delta(entry.GetTime(), prevout.nValue * -1, input.prevout.hash, input.prevout.n);
172 mapAddress.insert(make_pair(key, delta));
173 inserted.push_back(key);
174 } }
175 }
8b78a819
T
176
177 for (unsigned int k = 0; k < tx.vout.size(); k++) {
178 const CTxOut &out = tx.vout[k];
179 if (out.scriptPubKey.IsPayToScriptHash()) {
180 vector<unsigned char> hashBytes(out.scriptPubKey.begin()+2, out.scriptPubKey.begin()+22);
181 CMempoolAddressDeltaKey key(2, uint160(hashBytes), txhash, k, 0);
182 mapAddress.insert(make_pair(key, CMempoolAddressDelta(entry.GetTime(), out.nValue)));
183 inserted.push_back(key);
fa7bf712 184 }
185 else if (out.scriptPubKey.IsPayToPublicKeyHash()) {
8b78a819
T
186 vector<unsigned char> hashBytes(out.scriptPubKey.begin()+3, out.scriptPubKey.begin()+23);
187 std::pair<addressDeltaMap::iterator,bool> ret;
188 CMempoolAddressDeltaKey key(1, uint160(hashBytes), txhash, k, 0);
189 mapAddress.insert(make_pair(key, CMempoolAddressDelta(entry.GetTime(), out.nValue)));
190 inserted.push_back(key);
191 }
fa7bf712 192 else if (out.scriptPubKey.IsPayToPublicKey()) {
193 vector<unsigned char> hashBytes(out.scriptPubKey.begin()+1, out.scriptPubKey.begin()+34);
194 std::pair<addressDeltaMap::iterator,bool> ret;
dc276bd0 195 CMempoolAddressDeltaKey key(1, Hash160(hashBytes), txhash, k, 0);
fa7bf712 196 mapAddress.insert(make_pair(key, CMempoolAddressDelta(entry.GetTime(), out.nValue)));
197 inserted.push_back(key);
198 }
7f190223 199 else if (out.scriptPubKey.IsPayToCryptoCondition()) {
200 vector<unsigned char> hashBytes(out.scriptPubKey.begin(), out.scriptPubKey.end());
201 std::pair<addressDeltaMap::iterator,bool> ret;
202 CMempoolAddressDeltaKey key(1, Hash160(hashBytes), txhash, k, 0);
203 mapAddress.insert(make_pair(key, CMempoolAddressDelta(entry.GetTime(), out.nValue)));
204 inserted.push_back(key);
205 }
8b78a819
T
206 }
207
208 mapAddressInserted.insert(make_pair(txhash, inserted));
209}
210
211bool CTxMemPool::getAddressIndex(std::vector<std::pair<uint160, int> > &addresses,
212 std::vector<std::pair<CMempoolAddressDeltaKey, CMempoolAddressDelta> > &results)
213{
214 LOCK(cs);
215 for (std::vector<std::pair<uint160, int> >::iterator it = addresses.begin(); it != addresses.end(); it++) {
216 addressDeltaMap::iterator ait = mapAddress.lower_bound(CMempoolAddressDeltaKey((*it).second, (*it).first));
217 while (ait != mapAddress.end() && (*ait).first.addressBytes == (*it).first && (*ait).first.type == (*it).second) {
218 results.push_back(*ait);
219 ait++;
220 }
221 }
222 return true;
223}
224
225bool CTxMemPool::removeAddressIndex(const uint256 txhash)
226{
227 LOCK(cs);
228 addressDeltaMapInserted::iterator it = mapAddressInserted.find(txhash);
229
230 if (it != mapAddressInserted.end()) {
231 std::vector<CMempoolAddressDeltaKey> keys = (*it).second;
232 for (std::vector<CMempoolAddressDeltaKey>::iterator mit = keys.begin(); mit != keys.end(); mit++) {
233 mapAddress.erase(*mit);
234 }
235 mapAddressInserted.erase(it);
236 }
237
238 return true;
239}
240
241void CTxMemPool::addSpentIndex(const CTxMemPoolEntry &entry, const CCoinsViewCache &view)
242{
243 LOCK(cs);
244
245 const CTransaction& tx = entry.GetTx();
246 std::vector<CSpentIndexKey> inserted;
247
248 uint256 txhash = tx.GetHash();
249 for (unsigned int j = 0; j < tx.vin.size(); j++) {
250 const CTxIn input = tx.vin[j];
251 const CTxOut &prevout = view.GetOutputFor(input);
252 uint160 addressHash;
253 int addressType;
254
255 if (prevout.scriptPubKey.IsPayToScriptHash()) {
256 addressHash = uint160(vector<unsigned char> (prevout.scriptPubKey.begin()+2, prevout.scriptPubKey.begin()+22));
257 addressType = 2;
fa7bf712 258 }
259 else if (prevout.scriptPubKey.IsPayToPublicKeyHash()) {
8b78a819
T
260 addressHash = uint160(vector<unsigned char> (prevout.scriptPubKey.begin()+3, prevout.scriptPubKey.begin()+23));
261 addressType = 1;
fa7bf712 262 }
263 else if (prevout.scriptPubKey.IsPayToPublicKey()) {
264 addressHash = Hash160(vector<unsigned char> (prevout.scriptPubKey.begin()+1, prevout.scriptPubKey.begin()+34));
dc276bd0 265 addressType = 1;
fa7bf712 266 }
7f190223 267 else if (prevout.scriptPubKey.IsPayToCryptoCondition()) {
268 addressHash = Hash160(vector<unsigned char> (prevout.scriptPubKey.begin(), prevout.scriptPubKey.end()));
269 addressType = 1;
270 }
fa7bf712 271 else {
8b78a819
T
272 addressHash.SetNull();
273 addressType = 0;
274 }
275
276 CSpentIndexKey key = CSpentIndexKey(input.prevout.hash, input.prevout.n);
277 CSpentIndexValue value = CSpentIndexValue(txhash, j, -1, prevout.nValue, addressType, addressHash);
278
279 mapSpent.insert(make_pair(key, value));
280 inserted.push_back(key);
281
282 }
283
284 mapSpentInserted.insert(make_pair(txhash, inserted));
285}
286
287bool CTxMemPool::getSpentIndex(CSpentIndexKey &key, CSpentIndexValue &value)
288{
289 LOCK(cs);
290 mapSpentIndex::iterator it;
291
292 it = mapSpent.find(key);
293 if (it != mapSpent.end()) {
294 value = it->second;
295 return true;
296 }
297 return false;
298}
299
300bool CTxMemPool::removeSpentIndex(const uint256 txhash)
301{
302 LOCK(cs);
303 mapSpentIndexInserted::iterator it = mapSpentInserted.find(txhash);
304
305 if (it != mapSpentInserted.end()) {
306 std::vector<CSpentIndexKey> keys = (*it).second;
307 for (std::vector<CSpentIndexKey>::iterator mit = keys.begin(); mit != keys.end(); mit++) {
308 mapSpent.erase(*mit);
309 }
310 mapSpentInserted.erase(it);
311 }
312
313 return true;
314}
319b1160 315
7fd6219a 316void CTxMemPool::remove(const CTransaction &origTx, std::list<CTransaction>& removed, bool fRecursive)
319b1160
GA
317{
318 // Remove transaction from memory pool
319 {
320 LOCK(cs);
7fd6219a 321 std::deque<uint256> txToRemove;
805344dc
S
322 txToRemove.push_back(origTx.GetHash());
323 if (fRecursive && !mapTx.count(origTx.GetHash())) {
ad9e86dc
GA
324 // If recursively removing but origTx isn't in the mempool
325 // be sure to remove any children that are in the pool. This can
326 // happen during chain re-orgs if origTx isn't re-accepted into
327 // the mempool for any reason.
328 for (unsigned int i = 0; i < origTx.vout.size(); i++) {
805344dc 329 std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(COutPoint(origTx.GetHash(), i));
ad9e86dc
GA
330 if (it == mapNextTx.end())
331 continue;
805344dc 332 txToRemove.push_back(it->second.ptx->GetHash());
ad9e86dc
GA
333 }
334 }
7fd6219a 335 while (!txToRemove.empty())
319b1160 336 {
7fd6219a
MC
337 uint256 hash = txToRemove.front();
338 txToRemove.pop_front();
339 if (!mapTx.count(hash))
340 continue;
e328fa32 341 const CTransaction& tx = mapTx.find(hash)->GetTx();
7fd6219a
MC
342 if (fRecursive) {
343 for (unsigned int i = 0; i < tx.vout.size(); i++) {
344 std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(COutPoint(hash, i));
345 if (it == mapNextTx.end())
346 continue;
805344dc 347 txToRemove.push_back(it->second.ptx->GetHash());
7fd6219a
MC
348 }
349 }
319b1160
GA
350 BOOST_FOREACH(const CTxIn& txin, tx.vin)
351 mapNextTx.erase(txin.prevout);
b7e4abd6 352 BOOST_FOREACH(const JSDescription& joinsplit, tx.vjoinsplit) {
22de1602 353 BOOST_FOREACH(const uint256& nf, joinsplit.nullifiers) {
9669920f 354 mapSproutNullifiers.erase(nf);
d66877af
SB
355 }
356 }
cab341e1
EOW
357 for (const SpendDescription &spendDescription : tx.vShieldedSpend) {
358 mapSaplingNullifiers.erase(spendDescription.nullifier);
359 }
7fd6219a 360 removed.push_back(tx);
e328fa32
AH
361 totalTxSize -= mapTx.find(hash)->GetTxSize();
362 cachedInnerUsage -= mapTx.find(hash)->DynamicMemoryUsage();
319b1160
GA
363 mapTx.erase(hash);
364 nTransactionsUpdated++;
b649e039 365 minerPolicyEstimator->removeTx(hash);
8b78a819
T
366 removeAddressIndex(hash);
367 removeSpentIndex(hash);
41f170fd 368 ClearPrioritisation(tx.GetHash());
319b1160
GA
369 }
370 }
319b1160
GA
371}
372
0a962eb9 373extern uint64_t ASSETCHAINS_TIMELOCKGTE;
e980a26d 374int64_t komodo_block_unlocktime(uint32_t nHeight);
375
233c9eb6 376void CTxMemPool::removeForReorg(const CCoinsViewCache *pcoins, unsigned int nMemPoolHeight, int flags)
723d12c0
MC
377{
378 // Remove transactions spending a coinbase which are now immature
9edf27ec 379 extern char ASSETCHAINS_SYMBOL[KOMODO_ASSETCHAIN_MAXLEN];
b2a98c42 380
7a90b9dd 381 if ( ASSETCHAINS_SYMBOL[0] == 0 )
382 COINBASE_MATURITY = _COINBASE_MATURITY;
b2a98c42 383
c944d161 384 // Remove transactions spending a coinbase which are now immature and no-longer-final transactions
723d12c0
MC
385 LOCK(cs);
386 list<CTransaction> transactionsToRemove;
e328fa32
AH
387 for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
388 const CTransaction& tx = it->GetTx();
233c9eb6 389 if (!CheckFinalTx(tx, flags)) {
f5b35d23 390 transactionsToRemove.push_back(tx);
a4b25180 391 } else if (it->GetSpendsCoinbase()) {
f5b35d23
MC
392 BOOST_FOREACH(const CTxIn& txin, tx.vin) {
393 indexed_transaction_set::const_iterator it2 = mapTx.find(txin.prevout.hash);
394 if (it2 != mapTx.end())
395 continue;
396 const CCoins *coins = pcoins->AccessCoins(txin.prevout.hash);
e980a26d 397 if (nCheckFrequency != 0) assert(coins);
b2a98c42
MT
398
399 if (!coins || (coins->IsCoinBase() &&
400 (((signed long)nMemPoolHeight) - coins->nHeight < COINBASE_MATURITY) ||
401 ((signed long)nMemPoolHeight < komodo_block_unlocktime(coins->nHeight) &&
402 coins->IsAvailable(0) && coins->vout[0].nValue >= ASSETCHAINS_TIMELOCKGTE))) {
f5b35d23
MC
403 transactionsToRemove.push_back(tx);
404 break;
405 }
723d12c0
MC
406 }
407 }
408 }
409 BOOST_FOREACH(const CTransaction& tx, transactionsToRemove) {
410 list<CTransaction> removed;
411 remove(tx, removed, true);
412 }
413}
414
a8ac403d 415
98d2f090 416void CTxMemPool::removeWithAnchor(const uint256 &invalidRoot, ShieldedType type)
a8ac403d
SB
417{
418 // If a block is disconnected from the tip, and the root changed,
419 // we must invalidate transactions from the mempool which spend
420 // from that root -- almost as though they were spending coinbases
421 // which are no longer valid to spend due to coinbase maturity.
422 LOCK(cs);
423 list<CTransaction> transactionsToRemove;
424
e328fa32
AH
425 for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
426 const CTransaction& tx = it->GetTx();
98d2f090
SB
427 switch (type) {
428 case SPROUT:
429 BOOST_FOREACH(const JSDescription& joinsplit, tx.vjoinsplit) {
430 if (joinsplit.anchor == invalidRoot) {
431 transactionsToRemove.push_back(tx);
432 break;
433 }
434 }
435 break;
436 case SAPLING:
437 BOOST_FOREACH(const SpendDescription& spendDescription, tx.vShieldedSpend) {
438 if (spendDescription.anchor == invalidRoot) {
439 transactionsToRemove.push_back(tx);
440 break;
441 }
442 }
443 break;
444 default:
8c57bbac 445 throw runtime_error("Unknown shielded type");
98d2f090 446 break;
a8ac403d
SB
447 }
448 }
449
450 BOOST_FOREACH(const CTransaction& tx, transactionsToRemove) {
451 list<CTransaction> removed;
452 remove(tx, removed, true);
453 }
454}
455
93a18a36 456void CTxMemPool::removeConflicts(const CTransaction &tx, std::list<CTransaction>& removed)
319b1160
GA
457{
458 // Remove transactions which depend on inputs of tx, recursively
98e84aae 459 list<CTransaction> result;
319b1160
GA
460 LOCK(cs);
461 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
462 std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(txin.prevout);
463 if (it != mapNextTx.end()) {
464 const CTransaction &txConflict = *it->second.ptx;
465 if (txConflict != tx)
93a18a36
GA
466 {
467 remove(txConflict, removed, true);
468 }
319b1160
GA
469 }
470 }
d66877af 471
b7e4abd6 472 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
22de1602 473 BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
9669920f
EOW
474 std::map<uint256, const CTransaction*>::iterator it = mapSproutNullifiers.find(nf);
475 if (it != mapSproutNullifiers.end()) {
d66877af 476 const CTransaction &txConflict = *it->second;
9669920f 477 if (txConflict != tx) {
d66877af
SB
478 remove(txConflict, removed, true);
479 }
480 }
481 }
482 }
cab341e1
EOW
483 for (const SpendDescription &spendDescription : tx.vShieldedSpend) {
484 std::map<uint256, const CTransaction*>::iterator it = mapSaplingNullifiers.find(spendDescription.nullifier);
485 if (it != mapSaplingNullifiers.end()) {
486 const CTransaction &txConflict = *it->second;
9669920f 487 if (txConflict != tx) {
cab341e1 488 remove(txConflict, removed, true);
9669920f 489 }
cab341e1
EOW
490 }
491 }
319b1160
GA
492}
493
f045635e 494int32_t komodo_validate_interest(const CTransaction &tx,int32_t txheight,uint32_t nTime,int32_t dispflag);
f839d3f5 495extern char ASSETCHAINS_SYMBOL[];
f045635e 496
9bb37bf0
JG
497void CTxMemPool::removeExpired(unsigned int nBlockHeight)
498{
f045635e 499 CBlockIndex *tipindex;
9bb37bf0
JG
500 // Remove expired txs from the mempool
501 LOCK(cs);
502 list<CTransaction> transactionsToRemove;
503 for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++)
504 {
505 const CTransaction& tx = it->GetTx();
86131275 506 tipindex = chainActive.LastTip();
4b729ec5 507 if (IsExpiredTx(tx, nBlockHeight) || (ASSETCHAINS_SYMBOL[0] == 0 && tipindex != 0 && komodo_validate_interest(tx,tipindex->GetHeight()+1,tipindex->GetMedianTimePast() + 777,0)) < 0)
4825cbeb 508 {
9bb37bf0
JG
509 transactionsToRemove.push_back(tx);
510 }
511 }
512 for (const CTransaction& tx : transactionsToRemove) {
513 list<CTransaction> removed;
514 remove(tx, removed, true);
eb138626 515 LogPrint("mempool", "Removing expired txid: %s\n", tx.GetHash().ToString());
9bb37bf0
JG
516 }
517}
518
7329fdd1
MF
519/**
520 * Called when a block is connected. Removes from mempool and updates the miner fee estimator.
521 */
171ca774 522void CTxMemPool::removeForBlock(const std::vector<CTransaction>& vtx, unsigned int nBlockHeight,
b649e039 523 std::list<CTransaction>& conflicts, bool fCurrentEstimate)
171ca774
GA
524{
525 LOCK(cs);
526 std::vector<CTxMemPoolEntry> entries;
527 BOOST_FOREACH(const CTransaction& tx, vtx)
528 {
805344dc 529 uint256 hash = tx.GetHash();
e328fa32
AH
530
531 indexed_transaction_set::iterator i = mapTx.find(hash);
532 if (i != mapTx.end())
533 entries.push_back(*i);
171ca774 534 }
171ca774
GA
535 BOOST_FOREACH(const CTransaction& tx, vtx)
536 {
537 std::list<CTransaction> dummy;
538 remove(tx, dummy, false);
539 removeConflicts(tx, conflicts);
805344dc 540 ClearPrioritisation(tx.GetHash());
171ca774 541 }
b649e039
AM
542 // After the txs in the new block have been removed from the mempool, update policy estimates
543 minerPolicyEstimator->processBlock(nBlockHeight, entries, fCurrentEstimate);
171ca774
GA
544}
545
34a64fe0
JG
546/**
547 * Called whenever the tip changes. Removes transactions which don't commit to
548 * the given branch ID from the mempool.
549 */
550void CTxMemPool::removeWithoutBranchId(uint32_t nMemPoolBranchId)
551{
552 LOCK(cs);
553 std::list<CTransaction> transactionsToRemove;
554
555 for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
556 const CTransaction& tx = it->GetTx();
557 if (it->GetValidatedBranchId() != nMemPoolBranchId) {
558 transactionsToRemove.push_back(tx);
559 }
560 }
561
562 for (const CTransaction& tx : transactionsToRemove) {
563 std::list<CTransaction> removed;
564 remove(tx, removed, true);
565 }
566}
567
319b1160
GA
568void CTxMemPool::clear()
569{
570 LOCK(cs);
571 mapTx.clear();
572 mapNextTx.clear();
6f2c26a4 573 totalTxSize = 0;
bde5c8b0 574 cachedInnerUsage = 0;
319b1160
GA
575 ++nTransactionsUpdated;
576}
577
d0867acb 578void CTxMemPool::check(const CCoinsViewCache *pcoins) const
319b1160 579{
934fd197
PW
580 if (nCheckFrequency == 0)
581 return;
582
583 if (insecure_rand() >= nCheckFrequency)
319b1160
GA
584 return;
585
586 LogPrint("mempool", "Checking mempool with %u transactions and %u inputs\n", (unsigned int)mapTx.size(), (unsigned int)mapNextTx.size());
587
6f2c26a4 588 uint64_t checkTotal = 0;
bde5c8b0 589 uint64_t innerUsage = 0;
6f2c26a4 590
b7b4318f 591 CCoinsViewCache mempoolDuplicate(const_cast<CCoinsViewCache*>(pcoins));
722d811f 592 const int64_t nSpendHeight = GetSpendHeight(mempoolDuplicate);
b7b4318f 593
319b1160 594 LOCK(cs);
b7b4318f 595 list<const CTxMemPoolEntry*> waitingOnDependants;
e328fa32 596 for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
319b1160 597 unsigned int i = 0;
e328fa32
AH
598 checkTotal += it->GetTxSize();
599 innerUsage += it->DynamicMemoryUsage();
600 const CTransaction& tx = it->GetTx();
b7b4318f 601 bool fDependsWait = false;
4d707d51 602 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
319b1160 603 // Check that every mempool transaction's inputs refer to available coins, or other mempool tx's.
e328fa32 604 indexed_transaction_set::const_iterator it2 = mapTx.find(txin.prevout.hash);
319b1160 605 if (it2 != mapTx.end()) {
e328fa32 606 const CTransaction& tx2 = it2->GetTx();
4d707d51 607 assert(tx2.vout.size() > txin.prevout.n && !tx2.vout[txin.prevout.n].IsNull());
b7b4318f 608 fDependsWait = true;
319b1160 609 } else {
629d75fa
PW
610 const CCoins* coins = pcoins->AccessCoins(txin.prevout.hash);
611 assert(coins && coins->IsAvailable(txin.prevout.n));
319b1160
GA
612 }
613 // Check whether its inputs are marked in mapNextTx.
614 std::map<COutPoint, CInPoint>::const_iterator it3 = mapNextTx.find(txin.prevout);
615 assert(it3 != mapNextTx.end());
4d707d51 616 assert(it3->second.ptx == &tx);
319b1160
GA
617 assert(it3->second.n == i);
618 i++;
619 }
a667caec 620
4fc309f0 621 boost::unordered_map<uint256, SproutMerkleTree, CCoinsKeyHasher> intermediates;
a667caec 622
b7e4abd6 623 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
22de1602 624 BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
28d20bdb 625 assert(!pcoins->GetNullifier(nf, SPROUT));
d66877af
SB
626 }
627
4fc309f0 628 SproutMerkleTree tree;
b7e4abd6 629 auto it = intermediates.find(joinsplit.anchor);
a667caec
SB
630 if (it != intermediates.end()) {
631 tree = it->second;
632 } else {
008f4ee8 633 assert(pcoins->GetSproutAnchorAt(joinsplit.anchor, tree));
a667caec
SB
634 }
635
b7e4abd6 636 BOOST_FOREACH(const uint256& commitment, joinsplit.commitments)
a667caec
SB
637 {
638 tree.append(commitment);
639 }
640
641 intermediates.insert(std::make_pair(tree.root(), tree));
d66877af 642 }
cab341e1 643 for (const SpendDescription &spendDescription : tx.vShieldedSpend) {
4fc309f0 644 SaplingMerkleTree tree;
b4ff7076
SB
645
646 assert(pcoins->GetSaplingAnchorAt(spendDescription.anchor, tree));
28d20bdb 647 assert(!pcoins->GetNullifier(spendDescription.nullifier, SAPLING));
cab341e1 648 }
b7b4318f 649 if (fDependsWait)
e328fa32 650 waitingOnDependants.push_back(&(*it));
b7b4318f 651 else {
d7621ccf 652 CValidationState state;
722d811f
JT
653 bool fCheckResult = tx.IsCoinBase() ||
654 Consensus::CheckTxInputs(tx, state, mempoolDuplicate, nSpendHeight, Params().GetConsensus());
655 assert(fCheckResult);
8cb98d91 656 UpdateCoins(tx, mempoolDuplicate, 1000000);
b7b4318f
MC
657 }
658 }
659 unsigned int stepsSinceLastRemove = 0;
660 while (!waitingOnDependants.empty()) {
661 const CTxMemPoolEntry* entry = waitingOnDependants.front();
662 waitingOnDependants.pop_front();
663 CValidationState state;
664 if (!mempoolDuplicate.HaveInputs(entry->GetTx())) {
665 waitingOnDependants.push_back(entry);
666 stepsSinceLastRemove++;
667 assert(stepsSinceLastRemove < waitingOnDependants.size());
668 } else {
722d811f
JT
669 bool fCheckResult = entry->GetTx().IsCoinBase() ||
670 Consensus::CheckTxInputs(entry->GetTx(), state, mempoolDuplicate, nSpendHeight, Params().GetConsensus());
671 assert(fCheckResult);
8cb98d91 672 UpdateCoins(entry->GetTx(), mempoolDuplicate, 1000000);
b7b4318f
MC
673 stepsSinceLastRemove = 0;
674 }
319b1160
GA
675 }
676 for (std::map<COutPoint, CInPoint>::const_iterator it = mapNextTx.begin(); it != mapNextTx.end(); it++) {
805344dc 677 uint256 hash = it->second.ptx->GetHash();
e328fa32
AH
678 indexed_transaction_set::const_iterator it2 = mapTx.find(hash);
679 const CTransaction& tx = it2->GetTx();
319b1160 680 assert(it2 != mapTx.end());
4d707d51
GA
681 assert(&tx == it->second.ptx);
682 assert(tx.vin.size() > it->second.n);
319b1160
GA
683 assert(it->first == it->second.ptx->vin[it->second.n].prevout);
684 }
6f2c26a4 685
28d20bdb
SB
686 checkNullifiers(SPROUT);
687 checkNullifiers(SAPLING);
d66877af 688
6f2c26a4 689 assert(totalTxSize == checkTotal);
bde5c8b0 690 assert(innerUsage == cachedInnerUsage);
319b1160
GA
691}
692
28d20bdb 693void CTxMemPool::checkNullifiers(ShieldedType type) const
685e936c 694{
708c87f1
EOW
695 const std::map<uint256, const CTransaction*>* mapToUse;
696 switch (type) {
28d20bdb 697 case SPROUT:
9669920f 698 mapToUse = &mapSproutNullifiers;
708c87f1 699 break;
28d20bdb 700 case SAPLING:
708c87f1
EOW
701 mapToUse = &mapSaplingNullifiers;
702 break;
703 default:
1f9dfbb9 704 throw runtime_error("Unknown nullifier type");
708c87f1 705 }
685e936c
EOW
706 for (const auto& entry : *mapToUse) {
707 uint256 hash = entry.second->GetHash();
708 CTxMemPool::indexed_transaction_set::const_iterator findTx = mapTx.find(hash);
709 const CTransaction& tx = findTx->GetTx();
710 assert(findTx != mapTx.end());
711 assert(&tx == entry.second);
712 }
713}
714
4d707d51 715void CTxMemPool::queryHashes(vector<uint256>& vtxid)
319b1160
GA
716{
717 vtxid.clear();
718
719 LOCK(cs);
720 vtxid.reserve(mapTx.size());
e328fa32
AH
721 for (indexed_transaction_set::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
722 vtxid.push_back(mi->GetTx().GetHash());
319b1160
GA
723}
724
725bool CTxMemPool::lookup(uint256 hash, CTransaction& result) const
726{
727 LOCK(cs);
e328fa32 728 indexed_transaction_set::const_iterator i = mapTx.find(hash);
319b1160 729 if (i == mapTx.end()) return false;
e328fa32 730 result = i->GetTx();
319b1160
GA
731 return true;
732}
a0fa20a1 733
171ca774
GA
734CFeeRate CTxMemPool::estimateFee(int nBlocks) const
735{
736 LOCK(cs);
737 return minerPolicyEstimator->estimateFee(nBlocks);
738}
739double CTxMemPool::estimatePriority(int nBlocks) const
740{
741 LOCK(cs);
742 return minerPolicyEstimator->estimatePriority(nBlocks);
743}
744
745bool
746CTxMemPool::WriteFeeEstimates(CAutoFile& fileout) const
747{
748 try {
749 LOCK(cs);
b649e039 750 fileout << 109900; // version required to read: 0.10.99 or later
171ca774
GA
751 fileout << CLIENT_VERSION; // version that wrote the file
752 minerPolicyEstimator->Write(fileout);
753 }
27df4123 754 catch (const std::exception&) {
7ff9d122 755 LogPrintf("CTxMemPool::WriteFeeEstimates(): unable to write policy estimator data (non-fatal)\n");
171ca774
GA
756 return false;
757 }
758 return true;
759}
760
761bool
762CTxMemPool::ReadFeeEstimates(CAutoFile& filein)
763{
764 try {
765 int nVersionRequired, nVersionThatWrote;
766 filein >> nVersionRequired >> nVersionThatWrote;
767 if (nVersionRequired > CLIENT_VERSION)
5262fde0 768 return error("CTxMemPool::ReadFeeEstimates(): up-version (%d) fee estimate file", nVersionRequired);
171ca774
GA
769
770 LOCK(cs);
b649e039 771 minerPolicyEstimator->Read(filein);
171ca774 772 }
27df4123 773 catch (const std::exception&) {
7ff9d122 774 LogPrintf("CTxMemPool::ReadFeeEstimates(): unable to read policy estimator data (non-fatal)\n");
171ca774
GA
775 return false;
776 }
777 return true;
778}
779
41f170fd 780void CTxMemPool::PrioritiseTransaction(const uint256 &hash, const string strHash, double dPriorityDelta, const CAmount& nFeeDelta)
2a72d459
LD
781{
782 {
783 LOCK(cs);
a372168e 784 std::pair<double, CAmount> &deltas = mapDeltas[hash];
2a72d459
LD
785 deltas.first += dPriorityDelta;
786 deltas.second += nFeeDelta;
787 }
a372168e 788 LogPrintf("PrioritiseTransaction: %s priority += %f, fee += %d\n", strHash, dPriorityDelta, FormatMoney(nFeeDelta));
2a72d459
LD
789}
790
a372168e 791void CTxMemPool::ApplyDeltas(const uint256 hash, double &dPriorityDelta, CAmount &nFeeDelta)
2a72d459
LD
792{
793 LOCK(cs);
a372168e 794 std::map<uint256, std::pair<double, CAmount> >::iterator pos = mapDeltas.find(hash);
2a72d459
LD
795 if (pos == mapDeltas.end())
796 return;
a372168e 797 const std::pair<double, CAmount> &deltas = pos->second;
2a72d459
LD
798 dPriorityDelta += deltas.first;
799 nFeeDelta += deltas.second;
800}
801
802void CTxMemPool::ClearPrioritisation(const uint256 hash)
803{
804 LOCK(cs);
805 mapDeltas.erase(hash);
41f170fd
MT
806 mapReserveTransactions.erase(hash);
807}
808
47aecf2f 809bool CTxMemPool::PrioritiseReserveTransaction(const CReserveTransactionDescriptor &txDesc, const CCurrencyState &currencyState)
41f170fd
MT
810{
811 LOCK(cs);
812 uint256 hash = txDesc.ptx->GetHash();
813 auto it = mapReserveTransactions.find(hash);
47aecf2f 814 if (txDesc.IsValid())
41f170fd
MT
815 {
816 mapReserveTransactions[hash] = txDesc;
a1a4dc8b 817 CAmount feeDelta = currencyState.ReserveToNative(txDesc.ReserveFees() + txDesc.reserveConversionFees) + txDesc.nativeConversionFees;
818 PrioritiseTransaction(hash, hash.GetHex().c_str(), (double)feeDelta * 100.0, feeDelta);
47aecf2f 819 return true;
41f170fd 820 }
47aecf2f 821 return false;
41f170fd
MT
822}
823
47aecf2f 824bool CTxMemPool::IsKnownReserveTransaction(const uint256 &hash, CReserveTransactionDescriptor &txDesc)
41f170fd
MT
825{
826 LOCK(cs);
827 auto it = mapReserveTransactions.find(hash);
828 if (it != mapReserveTransactions.end() && it->second.IsValid())
829 {
1c3499f9 830 // refresh transaction from mempool or delete it if not found (we may not need this at all)
47aecf2f 831 indexed_transaction_set::const_iterator i = mapTx.find(hash);
832 if (i == mapTx.end())
833 {
834 ClearPrioritisation(hash);
835 }
836 else
837 {
838 it->second.ptx = &(i->GetTx());
839
840 txDesc = it->second;
841 return true;
842 }
41f170fd
MT
843 }
844 return false;
2a72d459
LD
845}
846
b649e039
AM
847bool CTxMemPool::HasNoInputsOf(const CTransaction &tx) const
848{
849 for (unsigned int i = 0; i < tx.vin.size(); i++)
850 if (exists(tx.vin[i].prevout.hash))
851 return false;
852 return true;
853}
171ca774 854
28d20bdb 855bool CTxMemPool::nullifierExists(const uint256& nullifier, ShieldedType type) const
685e936c 856{
708c87f1 857 switch (type) {
28d20bdb 858 case SPROUT:
9669920f 859 return mapSproutNullifiers.count(nullifier);
28d20bdb 860 case SAPLING:
708c87f1
EOW
861 return mapSaplingNullifiers.count(nullifier);
862 default:
1f9dfbb9 863 throw runtime_error("Unknown nullifier type");
708c87f1 864 }
685e936c 865}
a0fa20a1 866
685e936c 867CCoinsViewMemPool::CCoinsViewMemPool(CCoinsView *baseIn, CTxMemPool &mempoolIn) : CCoinsViewBacked(baseIn), mempool(mempoolIn) { }
d66877af 868
28d20bdb 869bool CCoinsViewMemPool::GetNullifier(const uint256 &nf, ShieldedType type) const
685e936c 870{
708c87f1 871 return mempool.nullifierExists(nf, type) || base->GetNullifier(nf, type);
d66877af
SB
872}
873
a3dc587a 874bool CCoinsViewMemPool::GetCoins(const uint256 &txid, CCoins &coins) const {
ad08d0b9
PW
875 // If an entry in the mempool exists, always return that one, as it's guaranteed to never
876 // conflict with the underlying cache, and it cannot have pruned entries (as it contains full)
877 // transactions. First checking the underlying cache risks returning a pruned entry instead.
a0fa20a1
PW
878 CTransaction tx;
879 if (mempool.lookup(txid, tx)) {
880 coins = CCoins(tx, MEMPOOL_HEIGHT);
881 return true;
882 }
ad08d0b9 883 return (base->GetCoins(txid, coins) && !coins.IsPruned());
a0fa20a1
PW
884}
885
a3dc587a 886bool CCoinsViewMemPool::HaveCoins(const uint256 &txid) const {
a0fa20a1
PW
887 return mempool.exists(txid) || base->HaveCoins(txid);
888}
bde5c8b0
PW
889
890size_t CTxMemPool::DynamicMemoryUsage() const {
891 LOCK(cs);
e328fa32 892 // Estimate the overhead of mapTx to be 6 pointers + an allocation, as no exact formula for boost::multi_index_contained is implemented.
41f170fd 893 return memusage::MallocUsage(sizeof(CTxMemPoolEntry) + 6 * sizeof(void*)) * mapTx.size() + memusage::DynamicUsage(mapNextTx) + memusage::DynamicUsage(mapDeltas) + memusage::DynamicUsage(mapDeltas) + memusage::DynamicUsage(mapDeltas) + cachedInnerUsage;
bde5c8b0 894}
This page took 0.464476 seconds and 4 git commands to generate.