You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

txmempool.cpp 25KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722
  1. // Copyright (c) 2009-2010 Satoshi Nakamoto
  2. // Copyright (c) 2009-2014 The Bitcoin developers
  3. // Distributed under the MIT software license, see the accompanying
  4. // file COPYING or http://www.opensource.org/licenses/mit-license.php.
  5. #include "txmempool.h"
  6. #include "clientversion.h"
  7. #include "main.h"
  8. #include "streams.h"
  9. #include "util.h"
  10. #include "utilmoneystr.h"
  11. #include "version.h"
  12. #include <boost/circular_buffer.hpp>
  13. using namespace std;
  14. CTxMemPoolEntry::CTxMemPoolEntry():
  15. nFee(0), nTxSize(0), nModSize(0), nTime(0), dPriority(0.0)
  16. {
  17. nHeight = MEMPOOL_HEIGHT;
  18. }
  19. CTxMemPoolEntry::CTxMemPoolEntry(const CTransaction& _tx, const CAmount& _nFee,
  20. int64_t _nTime, double _dPriority,
  21. unsigned int _nHeight):
  22. tx(_tx), nFee(_nFee), nTime(_nTime), dPriority(_dPriority), nHeight(_nHeight)
  23. {
  24. nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
  25. nModSize = tx.CalculateModifiedSize(nTxSize);
  26. }
  27. CTxMemPoolEntry::CTxMemPoolEntry(const CTxMemPoolEntry& other)
  28. {
  29. *this = other;
  30. }
  31. double
  32. CTxMemPoolEntry::GetPriority(unsigned int currentHeight) const
  33. {
  34. CAmount nValueIn = tx.GetValueOut()+nFee;
  35. double deltaPriority = ((double)(currentHeight-nHeight)*nValueIn)/nModSize;
  36. double dResult = dPriority + deltaPriority;
  37. return dResult;
  38. }
  39. /**
  40. * Keep track of fee/priority for transactions confirmed within N blocks
  41. */
  42. class CBlockAverage
  43. {
  44. private:
  45. boost::circular_buffer<CFeeRate> feeSamples;
  46. boost::circular_buffer<double> prioritySamples;
  47. template<typename T> std::vector<T> buf2vec(boost::circular_buffer<T> buf) const
  48. {
  49. std::vector<T> vec(buf.begin(), buf.end());
  50. return vec;
  51. }
  52. public:
  53. CBlockAverage() : feeSamples(100), prioritySamples(100) { }
  54. void RecordFee(const CFeeRate& feeRate) {
  55. feeSamples.push_back(feeRate);
  56. }
  57. void RecordPriority(double priority) {
  58. prioritySamples.push_back(priority);
  59. }
  60. size_t FeeSamples() const { return feeSamples.size(); }
  61. size_t GetFeeSamples(std::vector<CFeeRate>& insertInto) const
  62. {
  63. BOOST_FOREACH(const CFeeRate& f, feeSamples)
  64. insertInto.push_back(f);
  65. return feeSamples.size();
  66. }
  67. size_t PrioritySamples() const { return prioritySamples.size(); }
  68. size_t GetPrioritySamples(std::vector<double>& insertInto) const
  69. {
  70. BOOST_FOREACH(double d, prioritySamples)
  71. insertInto.push_back(d);
  72. return prioritySamples.size();
  73. }
  74. /**
  75. * Used as belt-and-suspenders check when reading to detect
  76. * file corruption
  77. */
  78. bool AreSane(const std::vector<CFeeRate>& vecFee, const CFeeRate& minRelayFee)
  79. {
  80. BOOST_FOREACH(CFeeRate fee, vecFee)
  81. {
  82. if (fee < CFeeRate(0))
  83. return false;
  84. if (fee.GetFeePerK() > minRelayFee.GetFeePerK() * 10000)
  85. return false;
  86. }
  87. return true;
  88. }
  89. bool AreSane(const std::vector<double> vecPriority)
  90. {
  91. BOOST_FOREACH(double priority, vecPriority)
  92. {
  93. if (priority < 0)
  94. return false;
  95. }
  96. return true;
  97. }
  98. void Write(CAutoFile& fileout) const
  99. {
  100. std::vector<CFeeRate> vecFee = buf2vec(feeSamples);
  101. fileout << vecFee;
  102. std::vector<double> vecPriority = buf2vec(prioritySamples);
  103. fileout << vecPriority;
  104. }
  105. void Read(CAutoFile& filein, const CFeeRate& minRelayFee) {
  106. std::vector<CFeeRate> vecFee;
  107. filein >> vecFee;
  108. if (AreSane(vecFee, minRelayFee))
  109. feeSamples.insert(feeSamples.end(), vecFee.begin(), vecFee.end());
  110. else
  111. throw runtime_error("Corrupt fee value in estimates file.");
  112. std::vector<double> vecPriority;
  113. filein >> vecPriority;
  114. if (AreSane(vecPriority))
  115. prioritySamples.insert(prioritySamples.end(), vecPriority.begin(), vecPriority.end());
  116. else
  117. throw runtime_error("Corrupt priority value in estimates file.");
  118. if (feeSamples.size() + prioritySamples.size() > 0)
  119. LogPrint("estimatefee", "Read %d fee samples and %d priority samples\n",
  120. feeSamples.size(), prioritySamples.size());
  121. }
  122. };
  123. class CMinerPolicyEstimator
  124. {
  125. private:
  126. /**
  127. * Records observed averages transactions that confirmed within one block, two blocks,
  128. * three blocks etc.
  129. */
  130. std::vector<CBlockAverage> history;
  131. std::vector<CFeeRate> sortedFeeSamples;
  132. std::vector<double> sortedPrioritySamples;
  133. int nBestSeenHeight;
  134. /**
  135. * nBlocksAgo is 0 based, i.e. transactions that confirmed in the highest seen block are
  136. * nBlocksAgo == 0, transactions in the block before that are nBlocksAgo == 1 etc.
  137. */
  138. void seenTxConfirm(const CFeeRate& feeRate, const CFeeRate& minRelayFee, double dPriority, int nBlocksAgo)
  139. {
  140. // Last entry records "everything else".
  141. int nBlocksTruncated = min(nBlocksAgo, (int) history.size() - 1);
  142. assert(nBlocksTruncated >= 0);
  143. // We need to guess why the transaction was included in a block-- either
  144. // because it is high-priority or because it has sufficient fees.
  145. bool sufficientFee = (feeRate > minRelayFee);
  146. bool sufficientPriority = AllowFree(dPriority);
  147. const char* assignedTo = "unassigned";
  148. if (sufficientFee && !sufficientPriority)
  149. {
  150. history[nBlocksTruncated].RecordFee(feeRate);
  151. assignedTo = "fee";
  152. }
  153. else if (sufficientPriority && !sufficientFee)
  154. {
  155. history[nBlocksTruncated].RecordPriority(dPriority);
  156. assignedTo = "priority";
  157. }
  158. else
  159. {
  160. // Neither or both fee and priority sufficient to get confirmed:
  161. // don't know why they got confirmed.
  162. }
  163. LogPrint("estimatefee", "Seen TX confirm: %s : %s fee/%g priority, took %d blocks\n",
  164. assignedTo, feeRate.ToString(), dPriority, nBlocksAgo);
  165. }
  166. public:
  167. CMinerPolicyEstimator(int nEntries) : nBestSeenHeight(0)
  168. {
  169. history.resize(nEntries);
  170. }
  171. void seenBlock(const std::vector<CTxMemPoolEntry>& entries, int nBlockHeight, const CFeeRate minRelayFee)
  172. {
  173. if (nBlockHeight <= nBestSeenHeight)
  174. {
  175. // Ignore side chains and re-orgs; assuming they are random
  176. // they don't affect the estimate.
  177. // And if an attacker can re-org the chain at will, then
  178. // you've got much bigger problems than "attacker can influence
  179. // transaction fees."
  180. return;
  181. }
  182. nBestSeenHeight = nBlockHeight;
  183. // Fill up the history buckets based on how long transactions took
  184. // to confirm.
  185. std::vector<std::vector<const CTxMemPoolEntry*> > entriesByConfirmations;
  186. entriesByConfirmations.resize(history.size());
  187. BOOST_FOREACH(const CTxMemPoolEntry& entry, entries)
  188. {
  189. // How many blocks did it take for miners to include this transaction?
  190. int delta = nBlockHeight - entry.GetHeight();
  191. if (delta <= 0)
  192. {
  193. // Re-org made us lose height, this should only happen if we happen
  194. // to re-org on a difficulty transition point: very rare!
  195. continue;
  196. }
  197. if ((delta-1) >= (int)history.size())
  198. delta = history.size(); // Last bucket is catch-all
  199. entriesByConfirmations.at(delta-1).push_back(&entry);
  200. }
  201. for (size_t i = 0; i < entriesByConfirmations.size(); i++)
  202. {
  203. std::vector<const CTxMemPoolEntry*> &e = entriesByConfirmations.at(i);
  204. // Insert at most 10 random entries per bucket, otherwise a single block
  205. // can dominate an estimate:
  206. if (e.size() > 10) {
  207. std::random_shuffle(e.begin(), e.end());
  208. e.resize(10);
  209. }
  210. BOOST_FOREACH(const CTxMemPoolEntry* entry, e)
  211. {
  212. // Fees are stored and reported as BTC-per-kb:
  213. CFeeRate feeRate(entry->GetFee(), entry->GetTxSize());
  214. double dPriority = entry->GetPriority(entry->GetHeight()); // Want priority when it went IN
  215. seenTxConfirm(feeRate, minRelayFee, dPriority, i);
  216. }
  217. }
  218. // After new samples are added, we have to clear the sorted lists,
  219. // so they'll be resorted the next time someone asks for an estimate
  220. sortedFeeSamples.clear();
  221. sortedPrioritySamples.clear();
  222. for (size_t i = 0; i < history.size(); i++) {
  223. if (history[i].FeeSamples() + history[i].PrioritySamples() > 0)
  224. LogPrint("estimatefee", "estimates: for confirming within %d blocks based on %d/%d samples, fee=%s, prio=%g\n",
  225. i,
  226. history[i].FeeSamples(), history[i].PrioritySamples(),
  227. estimateFee(i+1).ToString(), estimatePriority(i+1));
  228. }
  229. }
  230. /**
  231. * Can return CFeeRate(0) if we don't have any data for that many blocks back. nBlocksToConfirm is 1 based.
  232. */
  233. CFeeRate estimateFee(int nBlocksToConfirm)
  234. {
  235. nBlocksToConfirm--;
  236. if (nBlocksToConfirm < 0 || nBlocksToConfirm >= (int)history.size())
  237. return CFeeRate(0);
  238. if (sortedFeeSamples.size() == 0)
  239. {
  240. for (size_t i = 0; i < history.size(); i++)
  241. history.at(i).GetFeeSamples(sortedFeeSamples);
  242. std::sort(sortedFeeSamples.begin(), sortedFeeSamples.end(),
  243. std::greater<CFeeRate>());
  244. }
  245. if (sortedFeeSamples.size() < 11)
  246. {
  247. // Eleven is Gavin's Favorite Number
  248. // ... but we also take a maximum of 10 samples per block so eleven means
  249. // we're getting samples from at least two different blocks
  250. return CFeeRate(0);
  251. }
  252. int nBucketSize = history.at(nBlocksToConfirm).FeeSamples();
  253. // Estimates should not increase as number of confirmations goes up,
  254. // but the estimates are noisy because confirmations happen discretely
  255. // in blocks. To smooth out the estimates, use all samples in the history
  256. // and use the nth highest where n is (number of samples in previous bucket +
  257. // half the samples in nBlocksToConfirm bucket):
  258. size_t nPrevSize = 0;
  259. for (int i = 0; i < nBlocksToConfirm; i++)
  260. nPrevSize += history.at(i).FeeSamples();
  261. size_t index = min(nPrevSize + nBucketSize/2, sortedFeeSamples.size()-1);
  262. return sortedFeeSamples[index];
  263. }
  264. double estimatePriority(int nBlocksToConfirm)
  265. {
  266. nBlocksToConfirm--;
  267. if (nBlocksToConfirm < 0 || nBlocksToConfirm >= (int)history.size())
  268. return -1;
  269. if (sortedPrioritySamples.size() == 0)
  270. {
  271. for (size_t i = 0; i < history.size(); i++)
  272. history.at(i).GetPrioritySamples(sortedPrioritySamples);
  273. std::sort(sortedPrioritySamples.begin(), sortedPrioritySamples.end(),
  274. std::greater<double>());
  275. }
  276. if (sortedPrioritySamples.size() < 11)
  277. return -1.0;
  278. int nBucketSize = history.at(nBlocksToConfirm).PrioritySamples();
  279. // Estimates should not increase as number of confirmations needed goes up,
  280. // but the estimates are noisy because confirmations happen discretely
  281. // in blocks. To smooth out the estimates, use all samples in the history
  282. // and use the nth highest where n is (number of samples in previous buckets +
  283. // half the samples in nBlocksToConfirm bucket).
  284. size_t nPrevSize = 0;
  285. for (int i = 0; i < nBlocksToConfirm; i++)
  286. nPrevSize += history.at(i).PrioritySamples();
  287. size_t index = min(nPrevSize + nBucketSize/2, sortedPrioritySamples.size()-1);
  288. return sortedPrioritySamples[index];
  289. }
  290. void Write(CAutoFile& fileout) const
  291. {
  292. fileout << nBestSeenHeight;
  293. fileout << history.size();
  294. BOOST_FOREACH(const CBlockAverage& entry, history)
  295. {
  296. entry.Write(fileout);
  297. }
  298. }
  299. void Read(CAutoFile& filein, const CFeeRate& minRelayFee)
  300. {
  301. int nFileBestSeenHeight;
  302. filein >> nFileBestSeenHeight;
  303. size_t numEntries;
  304. filein >> numEntries;
  305. if (numEntries <= 0 || numEntries > 10000)
  306. throw runtime_error("Corrupt estimates file. Must have between 1 and 10k entries.");
  307. std::vector<CBlockAverage> fileHistory;
  308. for (size_t i = 0; i < numEntries; i++)
  309. {
  310. CBlockAverage entry;
  311. entry.Read(filein, minRelayFee);
  312. fileHistory.push_back(entry);
  313. }
  314. // Now that we've processed the entire fee estimate data file and not
  315. // thrown any errors, we can copy it to our history
  316. nBestSeenHeight = nFileBestSeenHeight;
  317. history = fileHistory;
  318. assert(history.size() > 0);
  319. }
  320. };
  321. CTxMemPool::CTxMemPool(const CFeeRate& _minRelayFee) :
  322. nTransactionsUpdated(0),
  323. minRelayFee(_minRelayFee)
  324. {
  325. // Sanity checks off by default for performance, because otherwise
  326. // accepting transactions becomes O(N^2) where N is the number
  327. // of transactions in the pool
  328. fSanityCheck = false;
  329. // 25 blocks is a compromise between using a lot of disk/memory and
  330. // trying to give accurate estimates to people who might be willing
  331. // to wait a day or two to save a fraction of a penny in fees.
  332. // Confirmation times for very-low-fee transactions that take more
  333. // than an hour or three to confirm are highly variable.
  334. minerPolicyEstimator = new CMinerPolicyEstimator(25);
  335. }
  336. CTxMemPool::~CTxMemPool()
  337. {
  338. delete minerPolicyEstimator;
  339. }
  340. void CTxMemPool::pruneSpent(const uint256 &hashTx, CCoins &coins)
  341. {
  342. LOCK(cs);
  343. std::map<COutPoint, CInPoint>::iterator it = mapNextTx.lower_bound(COutPoint(hashTx, 0));
  344. // iterate over all COutPoints in mapNextTx whose hash equals the provided hashTx
  345. while (it != mapNextTx.end() && it->first.hash == hashTx) {
  346. coins.Spend(it->first.n); // and remove those outputs from coins
  347. it++;
  348. }
  349. }
  350. unsigned int CTxMemPool::GetTransactionsUpdated() const
  351. {
  352. LOCK(cs);
  353. return nTransactionsUpdated;
  354. }
  355. void CTxMemPool::AddTransactionsUpdated(unsigned int n)
  356. {
  357. LOCK(cs);
  358. nTransactionsUpdated += n;
  359. }
  360. bool CTxMemPool::addUnchecked(const uint256& hash, const CTxMemPoolEntry &entry)
  361. {
  362. // Add to memory pool without checking anything.
  363. // Used by main.cpp AcceptToMemoryPool(), which DOES do
  364. // all the appropriate checks.
  365. LOCK(cs);
  366. {
  367. mapTx[hash] = entry;
  368. const CTransaction& tx = mapTx[hash].GetTx();
  369. for (unsigned int i = 0; i < tx.vin.size(); i++)
  370. mapNextTx[tx.vin[i].prevout] = CInPoint(&tx, i);
  371. nTransactionsUpdated++;
  372. totalTxSize += entry.GetTxSize();
  373. }
  374. return true;
  375. }
  376. void CTxMemPool::remove(const CTransaction &origTx, std::list<CTransaction>& removed, bool fRecursive)
  377. {
  378. // Remove transaction from memory pool
  379. {
  380. LOCK(cs);
  381. std::deque<uint256> txToRemove;
  382. txToRemove.push_back(origTx.GetHash());
  383. while (!txToRemove.empty())
  384. {
  385. uint256 hash = txToRemove.front();
  386. txToRemove.pop_front();
  387. if (!mapTx.count(hash))
  388. continue;
  389. const CTransaction& tx = mapTx[hash].GetTx();
  390. if (fRecursive) {
  391. for (unsigned int i = 0; i < tx.vout.size(); i++) {
  392. std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(COutPoint(hash, i));
  393. if (it == mapNextTx.end())
  394. continue;
  395. txToRemove.push_back(it->second.ptx->GetHash());
  396. }
  397. }
  398. BOOST_FOREACH(const CTxIn& txin, tx.vin)
  399. mapNextTx.erase(txin.prevout);
  400. removed.push_back(tx);
  401. totalTxSize -= mapTx[hash].GetTxSize();
  402. mapTx.erase(hash);
  403. nTransactionsUpdated++;
  404. }
  405. }
  406. }
  407. void CTxMemPool::removeCoinbaseSpends(const CCoinsViewCache *pcoins, unsigned int nMemPoolHeight)
  408. {
  409. // Remove transactions spending a coinbase which are now immature
  410. LOCK(cs);
  411. list<CTransaction> transactionsToRemove;
  412. for (std::map<uint256, CTxMemPoolEntry>::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
  413. const CTransaction& tx = it->second.GetTx();
  414. BOOST_FOREACH(const CTxIn& txin, tx.vin) {
  415. std::map<uint256, CTxMemPoolEntry>::const_iterator it2 = mapTx.find(txin.prevout.hash);
  416. if (it2 != mapTx.end())
  417. continue;
  418. const CCoins *coins = pcoins->AccessCoins(txin.prevout.hash);
  419. if (fSanityCheck) assert(coins);
  420. if (!coins || (coins->IsCoinBase() && nMemPoolHeight - coins->nHeight < COINBASE_MATURITY)) {
  421. transactionsToRemove.push_back(tx);
  422. break;
  423. }
  424. }
  425. }
  426. BOOST_FOREACH(const CTransaction& tx, transactionsToRemove) {
  427. list<CTransaction> removed;
  428. remove(tx, removed, true);
  429. }
  430. }
  431. void CTxMemPool::removeConflicts(const CTransaction &tx, std::list<CTransaction>& removed)
  432. {
  433. // Remove transactions which depend on inputs of tx, recursively
  434. list<CTransaction> result;
  435. LOCK(cs);
  436. BOOST_FOREACH(const CTxIn &txin, tx.vin) {
  437. std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(txin.prevout);
  438. if (it != mapNextTx.end()) {
  439. const CTransaction &txConflict = *it->second.ptx;
  440. if (txConflict != tx)
  441. {
  442. remove(txConflict, removed, true);
  443. }
  444. }
  445. }
  446. }
  447. /**
  448. * Called when a block is connected. Removes from mempool and updates the miner fee estimator.
  449. */
  450. void CTxMemPool::removeForBlock(const std::vector<CTransaction>& vtx, unsigned int nBlockHeight,
  451. std::list<CTransaction>& conflicts)
  452. {
  453. LOCK(cs);
  454. std::vector<CTxMemPoolEntry> entries;
  455. BOOST_FOREACH(const CTransaction& tx, vtx)
  456. {
  457. uint256 hash = tx.GetHash();
  458. if (mapTx.count(hash))
  459. entries.push_back(mapTx[hash]);
  460. }
  461. minerPolicyEstimator->seenBlock(entries, nBlockHeight, minRelayFee);
  462. BOOST_FOREACH(const CTransaction& tx, vtx)
  463. {
  464. std::list<CTransaction> dummy;
  465. remove(tx, dummy, false);
  466. removeConflicts(tx, conflicts);
  467. ClearPrioritisation(tx.GetHash());
  468. }
  469. }
  470. void CTxMemPool::clear()
  471. {
  472. LOCK(cs);
  473. mapTx.clear();
  474. mapNextTx.clear();
  475. totalTxSize = 0;
  476. ++nTransactionsUpdated;
  477. }
  478. void CTxMemPool::check(const CCoinsViewCache *pcoins) const
  479. {
  480. if (!fSanityCheck)
  481. return;
  482. LogPrint("mempool", "Checking mempool with %u transactions and %u inputs\n", (unsigned int)mapTx.size(), (unsigned int)mapNextTx.size());
  483. uint64_t checkTotal = 0;
  484. CCoinsViewCache mempoolDuplicate(const_cast<CCoinsViewCache*>(pcoins));
  485. LOCK(cs);
  486. list<const CTxMemPoolEntry*> waitingOnDependants;
  487. for (std::map<uint256, CTxMemPoolEntry>::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
  488. unsigned int i = 0;
  489. checkTotal += it->second.GetTxSize();
  490. const CTransaction& tx = it->second.GetTx();
  491. bool fDependsWait = false;
  492. BOOST_FOREACH(const CTxIn &txin, tx.vin) {
  493. // Check that every mempool transaction's inputs refer to available coins, or other mempool tx's.
  494. std::map<uint256, CTxMemPoolEntry>::const_iterator it2 = mapTx.find(txin.prevout.hash);
  495. if (it2 != mapTx.end()) {
  496. const CTransaction& tx2 = it2->second.GetTx();
  497. assert(tx2.vout.size() > txin.prevout.n && !tx2.vout[txin.prevout.n].IsNull());
  498. fDependsWait = true;
  499. } else {
  500. const CCoins* coins = pcoins->AccessCoins(txin.prevout.hash);
  501. assert(coins && coins->IsAvailable(txin.prevout.n));
  502. }
  503. // Check whether its inputs are marked in mapNextTx.
  504. std::map<COutPoint, CInPoint>::const_iterator it3 = mapNextTx.find(txin.prevout);
  505. assert(it3 != mapNextTx.end());
  506. assert(it3->second.ptx == &tx);
  507. assert(it3->second.n == i);
  508. i++;
  509. }
  510. if (fDependsWait)
  511. waitingOnDependants.push_back(&it->second);
  512. else {
  513. CValidationState state; CTxUndo undo;
  514. assert(CheckInputs(tx, state, mempoolDuplicate, false, 0, false, NULL));
  515. UpdateCoins(tx, state, mempoolDuplicate, undo, 1000000);
  516. }
  517. }
  518. unsigned int stepsSinceLastRemove = 0;
  519. while (!waitingOnDependants.empty()) {
  520. const CTxMemPoolEntry* entry = waitingOnDependants.front();
  521. waitingOnDependants.pop_front();
  522. CValidationState state;
  523. if (!mempoolDuplicate.HaveInputs(entry->GetTx())) {
  524. waitingOnDependants.push_back(entry);
  525. stepsSinceLastRemove++;
  526. assert(stepsSinceLastRemove < waitingOnDependants.size());
  527. } else {
  528. assert(CheckInputs(entry->GetTx(), state, mempoolDuplicate, false, 0, false, NULL));
  529. CTxUndo undo;
  530. UpdateCoins(entry->GetTx(), state, mempoolDuplicate, undo, 1000000);
  531. stepsSinceLastRemove = 0;
  532. }
  533. }
  534. for (std::map<COutPoint, CInPoint>::const_iterator it = mapNextTx.begin(); it != mapNextTx.end(); it++) {
  535. uint256 hash = it->second.ptx->GetHash();
  536. map<uint256, CTxMemPoolEntry>::const_iterator it2 = mapTx.find(hash);
  537. const CTransaction& tx = it2->second.GetTx();
  538. assert(it2 != mapTx.end());
  539. assert(&tx == it->second.ptx);
  540. assert(tx.vin.size() > it->second.n);
  541. assert(it->first == it->second.ptx->vin[it->second.n].prevout);
  542. }
  543. assert(totalTxSize == checkTotal);
  544. }
  545. void CTxMemPool::queryHashes(vector<uint256>& vtxid)
  546. {
  547. vtxid.clear();
  548. LOCK(cs);
  549. vtxid.reserve(mapTx.size());
  550. for (map<uint256, CTxMemPoolEntry>::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
  551. vtxid.push_back((*mi).first);
  552. }
  553. bool CTxMemPool::lookup(uint256 hash, CTransaction& result) const
  554. {
  555. LOCK(cs);
  556. map<uint256, CTxMemPoolEntry>::const_iterator i = mapTx.find(hash);
  557. if (i == mapTx.end()) return false;
  558. result = i->second.GetTx();
  559. return true;
  560. }
  561. CFeeRate CTxMemPool::estimateFee(int nBlocks) const
  562. {
  563. LOCK(cs);
  564. return minerPolicyEstimator->estimateFee(nBlocks);
  565. }
  566. double CTxMemPool::estimatePriority(int nBlocks) const
  567. {
  568. LOCK(cs);
  569. return minerPolicyEstimator->estimatePriority(nBlocks);
  570. }
  571. bool
  572. CTxMemPool::WriteFeeEstimates(CAutoFile& fileout) const
  573. {
  574. try {
  575. LOCK(cs);
  576. fileout << 99900; // version required to read: 0.9.99 or later
  577. fileout << CLIENT_VERSION; // version that wrote the file
  578. minerPolicyEstimator->Write(fileout);
  579. }
  580. catch (const std::exception &) {
  581. LogPrintf("CTxMemPool::WriteFeeEstimates() : unable to write policy estimator data (non-fatal)");
  582. return false;
  583. }
  584. return true;
  585. }
  586. bool
  587. CTxMemPool::ReadFeeEstimates(CAutoFile& filein)
  588. {
  589. try {
  590. int nVersionRequired, nVersionThatWrote;
  591. filein >> nVersionRequired >> nVersionThatWrote;
  592. if (nVersionRequired > CLIENT_VERSION)
  593. return error("CTxMemPool::ReadFeeEstimates() : up-version (%d) fee estimate file", nVersionRequired);
  594. LOCK(cs);
  595. minerPolicyEstimator->Read(filein, minRelayFee);
  596. }
  597. catch (const std::exception &) {
  598. LogPrintf("CTxMemPool::ReadFeeEstimates() : unable to read policy estimator data (non-fatal)");
  599. return false;
  600. }
  601. return true;
  602. }
  603. void CTxMemPool::PrioritiseTransaction(const uint256 hash, const string strHash, double dPriorityDelta, const CAmount& nFeeDelta)
  604. {
  605. {
  606. LOCK(cs);
  607. std::pair<double, CAmount> &deltas = mapDeltas[hash];
  608. deltas.first += dPriorityDelta;
  609. deltas.second += nFeeDelta;
  610. }
  611. LogPrintf("PrioritiseTransaction: %s priority += %f, fee += %d\n", strHash, dPriorityDelta, FormatMoney(nFeeDelta));
  612. }
  613. void CTxMemPool::ApplyDeltas(const uint256 hash, double &dPriorityDelta, CAmount &nFeeDelta)
  614. {
  615. LOCK(cs);
  616. std::map<uint256, std::pair<double, CAmount> >::iterator pos = mapDeltas.find(hash);
  617. if (pos == mapDeltas.end())
  618. return;
  619. const std::pair<double, CAmount> &deltas = pos->second;
  620. dPriorityDelta += deltas.first;
  621. nFeeDelta += deltas.second;
  622. }
  623. void CTxMemPool::ClearPrioritisation(const uint256 hash)
  624. {
  625. LOCK(cs);
  626. mapDeltas.erase(hash);
  627. }
  628. CCoinsViewMemPool::CCoinsViewMemPool(CCoinsView *baseIn, CTxMemPool &mempoolIn) : CCoinsViewBacked(baseIn), mempool(mempoolIn) { }
  629. bool CCoinsViewMemPool::GetCoins(const uint256 &txid, CCoins &coins) const {
  630. // If an entry in the mempool exists, always return that one, as it's guaranteed to never
  631. // conflict with the underlying cache, and it cannot have pruned entries (as it contains full)
  632. // transactions. First checking the underlying cache risks returning a pruned entry instead.
  633. CTransaction tx;
  634. if (mempool.lookup(txid, tx)) {
  635. coins = CCoins(tx, MEMPOOL_HEIGHT);
  636. return true;
  637. }
  638. return (base->GetCoins(txid, coins) && !coins.IsPruned());
  639. }
  640. bool CCoinsViewMemPool::HaveCoins(const uint256 &txid) const {
  641. return mempool.exists(txid) || base->HaveCoins(txid);
  642. }