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

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