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 22KB

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