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.
11 #include "utilmoneystr.h"
14 #include <boost/circular_buffer.hpp>
18 CTxMemPoolEntry::CTxMemPoolEntry():
19 nFee(0), nTxSize(0), nModSize(0), nTime(0), dPriority(0.0)
21 nHeight = MEMPOOL_HEIGHT;
24 CTxMemPoolEntry::CTxMemPoolEntry(const CTransaction& _tx, const CAmount& _nFee,
25 int64_t _nTime, double _dPriority,
26 unsigned int _nHeight):
27 tx(_tx), nFee(_nFee), nTime(_nTime), dPriority(_dPriority), nHeight(_nHeight)
29 nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
31 nModSize = tx.CalculateModifiedSize(nTxSize);
34 CTxMemPoolEntry::CTxMemPoolEntry(const CTxMemPoolEntry& other)
40 CTxMemPoolEntry::GetPriority(unsigned int currentHeight) const
42 CAmount nValueIn = tx.GetValueOut()+nFee;
43 double deltaPriority = ((double)(currentHeight-nHeight)*nValueIn)/nModSize;
44 double dResult = dPriority + deltaPriority;
49 // Keep track of fee/priority for transactions confirmed within N blocks
54 boost::circular_buffer<CFeeRate> feeSamples;
55 boost::circular_buffer<double> prioritySamples;
57 template<typename T> std::vector<T> buf2vec(boost::circular_buffer<T> buf) const
59 std::vector<T> vec(buf.begin(), buf.end());
64 CBlockAverage() : feeSamples(100), prioritySamples(100) { }
66 void RecordFee(const CFeeRate& feeRate) {
67 feeSamples.push_back(feeRate);
70 void RecordPriority(double priority) {
71 prioritySamples.push_back(priority);
74 size_t FeeSamples() const { return feeSamples.size(); }
75 size_t GetFeeSamples(std::vector<CFeeRate>& insertInto) const
77 BOOST_FOREACH(const CFeeRate& f, feeSamples)
78 insertInto.push_back(f);
79 return feeSamples.size();
81 size_t PrioritySamples() const { return prioritySamples.size(); }
82 size_t GetPrioritySamples(std::vector<double>& insertInto) const
84 BOOST_FOREACH(double d, prioritySamples)
85 insertInto.push_back(d);
86 return prioritySamples.size();
89 // Used as belt-and-suspenders check when reading to detect
91 bool AreSane(const std::vector<CFeeRate>& vecFee, const CFeeRate& minRelayFee)
93 BOOST_FOREACH(CFeeRate fee, vecFee)
95 if (fee < CFeeRate(0))
97 if (fee.GetFeePerK() > minRelayFee.GetFeePerK() * 10000)
102 bool AreSane(const std::vector<double> vecPriority)
104 BOOST_FOREACH(double priority, vecPriority)
112 void Write(CAutoFile& fileout) const
114 std::vector<CFeeRate> vecFee = buf2vec(feeSamples);
116 std::vector<double> vecPriority = buf2vec(prioritySamples);
117 fileout << vecPriority;
120 void Read(CAutoFile& filein, const CFeeRate& minRelayFee) {
121 std::vector<CFeeRate> vecFee;
123 if (AreSane(vecFee, minRelayFee))
124 feeSamples.insert(feeSamples.end(), vecFee.begin(), vecFee.end());
126 throw runtime_error("Corrupt fee value in estimates file.");
127 std::vector<double> vecPriority;
128 filein >> vecPriority;
129 if (AreSane(vecPriority))
130 prioritySamples.insert(prioritySamples.end(), vecPriority.begin(), vecPriority.end());
132 throw runtime_error("Corrupt priority value in estimates file.");
133 if (feeSamples.size() + prioritySamples.size() > 0)
134 LogPrint("estimatefee", "Read %d fee samples and %d priority samples\n",
135 feeSamples.size(), prioritySamples.size());
139 class CMinerPolicyEstimator
142 // Records observed averages transactions that confirmed within one block, two blocks,
144 std::vector<CBlockAverage> history;
145 std::vector<CFeeRate> sortedFeeSamples;
146 std::vector<double> sortedPrioritySamples;
150 // nBlocksAgo is 0 based, i.e. transactions that confirmed in the highest seen block are
151 // nBlocksAgo == 0, transactions in the block before that are nBlocksAgo == 1 etc.
152 void seenTxConfirm(const CFeeRate& feeRate, const CFeeRate& minRelayFee, double dPriority, int nBlocksAgo)
154 // Last entry records "everything else".
155 int nBlocksTruncated = min(nBlocksAgo, (int) history.size() - 1);
156 assert(nBlocksTruncated >= 0);
158 // We need to guess why the transaction was included in a block-- either
159 // because it is high-priority or because it has sufficient fees.
160 bool sufficientFee = (feeRate > minRelayFee);
161 bool sufficientPriority = AllowFree(dPriority);
162 const char* assignedTo = "unassigned";
163 if (sufficientFee && !sufficientPriority)
165 history[nBlocksTruncated].RecordFee(feeRate);
168 else if (sufficientPriority && !sufficientFee)
170 history[nBlocksTruncated].RecordPriority(dPriority);
171 assignedTo = "priority";
175 // Neither or both fee and priority sufficient to get confirmed:
176 // don't know why they got confirmed.
178 LogPrint("estimatefee", "Seen TX confirm: %s : %s fee/%g priority, took %d blocks\n",
179 assignedTo, feeRate.ToString(), dPriority, nBlocksAgo);
183 CMinerPolicyEstimator(int nEntries) : nBestSeenHeight(0)
185 history.resize(nEntries);
188 void seenBlock(const std::vector<CTxMemPoolEntry>& entries, int nBlockHeight, const CFeeRate minRelayFee)
190 if (nBlockHeight <= nBestSeenHeight)
192 // Ignore side chains and re-orgs; assuming they are random
193 // they don't affect the estimate.
194 // And if an attacker can re-org the chain at will, then
195 // you've got much bigger problems than "attacker can influence
196 // transaction fees."
199 nBestSeenHeight = nBlockHeight;
201 // Fill up the history buckets based on how long transactions took
203 std::vector<std::vector<const CTxMemPoolEntry*> > entriesByConfirmations;
204 entriesByConfirmations.resize(history.size());
205 BOOST_FOREACH(const CTxMemPoolEntry& entry, entries)
207 // How many blocks did it take for miners to include this transaction?
208 int delta = nBlockHeight - entry.GetHeight();
211 // Re-org made us lose height, this should only happen if we happen
212 // to re-org on a difficulty transition point: very rare!
215 if ((delta-1) >= (int)history.size())
216 delta = history.size(); // Last bucket is catch-all
217 entriesByConfirmations.at(delta-1).push_back(&entry);
219 for (size_t i = 0; i < entriesByConfirmations.size(); i++)
221 std::vector<const CTxMemPoolEntry*> &e = entriesByConfirmations.at(i);
222 // Insert at most 10 random entries per bucket, otherwise a single block
223 // can dominate an estimate:
225 std::random_shuffle(e.begin(), e.end());
228 BOOST_FOREACH(const CTxMemPoolEntry* entry, e)
230 // Fees are stored and reported as BTC-per-kb:
231 CFeeRate feeRate(entry->GetFee(), entry->GetTxSize());
232 double dPriority = entry->GetPriority(entry->GetHeight()); // Want priority when it went IN
233 seenTxConfirm(feeRate, minRelayFee, dPriority, i);
237 //After new samples are added, we have to clear the sorted lists,
238 //so they'll be resorted the next time someone asks for an estimate
239 sortedFeeSamples.clear();
240 sortedPrioritySamples.clear();
242 for (size_t i = 0; i < history.size(); i++) {
243 if (history[i].FeeSamples() + history[i].PrioritySamples() > 0)
244 LogPrint("estimatefee", "estimates: for confirming within %d blocks based on %d/%d samples, fee=%s, prio=%g\n",
246 history[i].FeeSamples(), history[i].PrioritySamples(),
247 estimateFee(i+1).ToString(), estimatePriority(i+1));
251 // Can return CFeeRate(0) if we don't have any data for that many blocks back. nBlocksToConfirm is 1 based.
252 CFeeRate estimateFee(int nBlocksToConfirm)
256 if (nBlocksToConfirm < 0 || nBlocksToConfirm >= (int)history.size())
259 if (sortedFeeSamples.size() == 0)
261 for (size_t i = 0; i < history.size(); i++)
262 history.at(i).GetFeeSamples(sortedFeeSamples);
263 std::sort(sortedFeeSamples.begin(), sortedFeeSamples.end(),
264 std::greater<CFeeRate>());
266 if (sortedFeeSamples.size() < 11)
268 // Eleven is Gavin's Favorite Number
269 // ... but we also take a maximum of 10 samples per block so eleven means
270 // we're getting samples from at least two different blocks
274 int nBucketSize = history.at(nBlocksToConfirm).FeeSamples();
276 // Estimates should not increase as number of confirmations goes up,
277 // but the estimates are noisy because confirmations happen discretely
278 // in blocks. To smooth out the estimates, use all samples in the history
279 // and use the nth highest where n is (number of samples in previous bucket +
280 // half the samples in nBlocksToConfirm bucket):
281 size_t nPrevSize = 0;
282 for (int i = 0; i < nBlocksToConfirm; i++)
283 nPrevSize += history.at(i).FeeSamples();
284 size_t index = min(nPrevSize + nBucketSize/2, sortedFeeSamples.size()-1);
285 return sortedFeeSamples[index];
287 double estimatePriority(int nBlocksToConfirm)
291 if (nBlocksToConfirm < 0 || nBlocksToConfirm >= (int)history.size())
294 if (sortedPrioritySamples.size() == 0)
296 for (size_t i = 0; i < history.size(); i++)
297 history.at(i).GetPrioritySamples(sortedPrioritySamples);
298 std::sort(sortedPrioritySamples.begin(), sortedPrioritySamples.end(),
299 std::greater<double>());
301 if (sortedPrioritySamples.size() < 11)
304 int nBucketSize = history.at(nBlocksToConfirm).PrioritySamples();
306 // Estimates should not increase as number of confirmations needed goes up,
307 // but the estimates are noisy because confirmations happen discretely
308 // in blocks. To smooth out the estimates, use all samples in the history
309 // and use the nth highest where n is (number of samples in previous buckets +
310 // half the samples in nBlocksToConfirm bucket).
311 size_t nPrevSize = 0;
312 for (int i = 0; i < nBlocksToConfirm; i++)
313 nPrevSize += history.at(i).PrioritySamples();
314 size_t index = min(nPrevSize + nBucketSize/2, sortedPrioritySamples.size()-1);
315 return sortedPrioritySamples[index];
318 void Write(CAutoFile& fileout) const
320 fileout << nBestSeenHeight;
321 fileout << history.size();
322 BOOST_FOREACH(const CBlockAverage& entry, history)
324 entry.Write(fileout);
328 void Read(CAutoFile& filein, const CFeeRate& minRelayFee)
330 int nFileBestSeenHeight;
331 filein >> nFileBestSeenHeight;
333 filein >> numEntries;
334 if (numEntries <= 0 || numEntries > 10000)
335 throw runtime_error("Corrupt estimates file. Must have between 1 and 10k entires.");
337 std::vector<CBlockAverage> fileHistory;
339 for (size_t i = 0; i < numEntries; i++)
342 entry.Read(filein, minRelayFee);
343 fileHistory.push_back(entry);
346 //Now that we've processed the entire fee estimate data file and not
347 //thrown any errors, we can copy it to our history
348 nBestSeenHeight = nFileBestSeenHeight;
349 history = fileHistory;
350 assert(history.size() > 0);
355 CTxMemPool::CTxMemPool(const CFeeRate& _minRelayFee) :
356 nTransactionsUpdated(0),
357 minRelayFee(_minRelayFee)
359 // Sanity checks off by default for performance, because otherwise
360 // accepting transactions becomes O(N^2) where N is the number
361 // of transactions in the pool
362 fSanityCheck = false;
364 // 25 blocks is a compromise between using a lot of disk/memory and
365 // trying to give accurate estimates to people who might be willing
366 // to wait a day or two to save a fraction of a penny in fees.
367 // Confirmation times for very-low-fee transactions that take more
368 // than an hour or three to confirm are highly variable.
369 minerPolicyEstimator = new CMinerPolicyEstimator(25);
372 CTxMemPool::~CTxMemPool()
374 delete minerPolicyEstimator;
377 void CTxMemPool::pruneSpent(const uint256 &hashTx, CCoins &coins)
381 std::map<COutPoint, CInPoint>::iterator it = mapNextTx.lower_bound(COutPoint(hashTx, 0));
383 // iterate over all COutPoints in mapNextTx whose hash equals the provided hashTx
384 while (it != mapNextTx.end() && it->first.hash == hashTx) {
385 coins.Spend(it->first.n); // and remove those outputs from coins
390 unsigned int CTxMemPool::GetTransactionsUpdated() const
393 return nTransactionsUpdated;
396 void CTxMemPool::AddTransactionsUpdated(unsigned int n)
399 nTransactionsUpdated += n;
403 bool CTxMemPool::addUnchecked(const uint256& hash, const CTxMemPoolEntry &entry)
405 // Add to memory pool without checking anything.
406 // Used by main.cpp AcceptToMemoryPool(), which DOES do
407 // all the appropriate checks.
411 const CTransaction& tx = mapTx[hash].GetTx();
412 for (unsigned int i = 0; i < tx.vin.size(); i++)
413 mapNextTx[tx.vin[i].prevout] = CInPoint(&tx, i);
414 nTransactionsUpdated++;
415 totalTxSize += entry.GetTxSize();
421 void CTxMemPool::remove(const CTransaction &tx, std::list<CTransaction>& removed, bool fRecursive)
423 // Remove transaction from memory pool
426 uint256 hash = tx.GetHash();
428 for (unsigned int i = 0; i < tx.vout.size(); i++) {
429 std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(COutPoint(hash, i));
430 if (it == mapNextTx.end())
432 remove(*it->second.ptx, removed, true);
435 if (mapTx.count(hash))
437 removed.push_front(tx);
438 BOOST_FOREACH(const CTxIn& txin, tx.vin)
439 mapNextTx.erase(txin.prevout);
441 totalTxSize -= mapTx[hash].GetTxSize();
443 nTransactionsUpdated++;
448 void CTxMemPool::removeConflicts(const CTransaction &tx, std::list<CTransaction>& removed)
450 // Remove transactions which depend on inputs of tx, recursively
451 list<CTransaction> result;
453 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
454 std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(txin.prevout);
455 if (it != mapNextTx.end()) {
456 const CTransaction &txConflict = *it->second.ptx;
457 if (txConflict != tx)
459 remove(txConflict, removed, true);
465 // Called when a block is connected. Removes from mempool and updates the miner fee estimator.
466 void CTxMemPool::removeForBlock(const std::vector<CTransaction>& vtx, unsigned int nBlockHeight,
467 std::list<CTransaction>& conflicts)
470 std::vector<CTxMemPoolEntry> entries;
471 BOOST_FOREACH(const CTransaction& tx, vtx)
473 uint256 hash = tx.GetHash();
474 if (mapTx.count(hash))
475 entries.push_back(mapTx[hash]);
477 minerPolicyEstimator->seenBlock(entries, nBlockHeight, minRelayFee);
478 BOOST_FOREACH(const CTransaction& tx, vtx)
480 std::list<CTransaction> dummy;
481 remove(tx, dummy, false);
482 removeConflicts(tx, conflicts);
483 ClearPrioritisation(tx.GetHash());
488 void CTxMemPool::clear()
494 ++nTransactionsUpdated;
497 void CTxMemPool::check(const CCoinsViewCache *pcoins) const
502 LogPrint("mempool", "Checking mempool with %u transactions and %u inputs\n", (unsigned int)mapTx.size(), (unsigned int)mapNextTx.size());
504 uint64_t checkTotal = 0;
507 for (std::map<uint256, CTxMemPoolEntry>::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
509 checkTotal += it->second.GetTxSize();
510 const CTransaction& tx = it->second.GetTx();
511 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
512 // Check that every mempool transaction's inputs refer to available coins, or other mempool tx's.
513 std::map<uint256, CTxMemPoolEntry>::const_iterator it2 = mapTx.find(txin.prevout.hash);
514 if (it2 != mapTx.end()) {
515 const CTransaction& tx2 = it2->second.GetTx();
516 assert(tx2.vout.size() > txin.prevout.n && !tx2.vout[txin.prevout.n].IsNull());
518 const CCoins* coins = pcoins->AccessCoins(txin.prevout.hash);
519 assert(coins && coins->IsAvailable(txin.prevout.n));
521 // Check whether its inputs are marked in mapNextTx.
522 std::map<COutPoint, CInPoint>::const_iterator it3 = mapNextTx.find(txin.prevout);
523 assert(it3 != mapNextTx.end());
524 assert(it3->second.ptx == &tx);
525 assert(it3->second.n == i);
529 for (std::map<COutPoint, CInPoint>::const_iterator it = mapNextTx.begin(); it != mapNextTx.end(); it++) {
530 uint256 hash = it->second.ptx->GetHash();
531 map<uint256, CTxMemPoolEntry>::const_iterator it2 = mapTx.find(hash);
532 const CTransaction& tx = it2->second.GetTx();
533 assert(it2 != mapTx.end());
534 assert(&tx == it->second.ptx);
535 assert(tx.vin.size() > it->second.n);
536 assert(it->first == it->second.ptx->vin[it->second.n].prevout);
539 assert(totalTxSize == checkTotal);
542 void CTxMemPool::queryHashes(vector<uint256>& vtxid)
547 vtxid.reserve(mapTx.size());
548 for (map<uint256, CTxMemPoolEntry>::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
549 vtxid.push_back((*mi).first);
552 bool CTxMemPool::lookup(uint256 hash, CTransaction& result) const
555 map<uint256, CTxMemPoolEntry>::const_iterator i = mapTx.find(hash);
556 if (i == mapTx.end()) return false;
557 result = i->second.GetTx();
561 CFeeRate CTxMemPool::estimateFee(int nBlocks) const
564 return minerPolicyEstimator->estimateFee(nBlocks);
566 double CTxMemPool::estimatePriority(int nBlocks) const
569 return minerPolicyEstimator->estimatePriority(nBlocks);
573 CTxMemPool::WriteFeeEstimates(CAutoFile& fileout) const
577 fileout << 99900; // version required to read: 0.9.99 or later
578 fileout << CLIENT_VERSION; // version that wrote the file
579 minerPolicyEstimator->Write(fileout);
581 catch (const std::exception &) {
582 LogPrintf("CTxMemPool::WriteFeeEstimates() : unable to write policy estimator data (non-fatal)");
589 CTxMemPool::ReadFeeEstimates(CAutoFile& filein)
592 int nVersionRequired, nVersionThatWrote;
593 filein >> nVersionRequired >> nVersionThatWrote;
594 if (nVersionRequired > CLIENT_VERSION)
595 return error("CTxMemPool::ReadFeeEstimates() : up-version (%d) fee estimate file", nVersionRequired);
598 minerPolicyEstimator->Read(filein, minRelayFee);
600 catch (const std::exception &) {
601 LogPrintf("CTxMemPool::ReadFeeEstimates() : unable to read policy estimator data (non-fatal)");
607 void CTxMemPool::PrioritiseTransaction(const uint256 hash, const string strHash, double dPriorityDelta, const CAmount& nFeeDelta)
611 std::pair<double, CAmount> &deltas = mapDeltas[hash];
612 deltas.first += dPriorityDelta;
613 deltas.second += nFeeDelta;
615 LogPrintf("PrioritiseTransaction: %s priority += %f, fee += %d\n", strHash, dPriorityDelta, FormatMoney(nFeeDelta));
618 void CTxMemPool::ApplyDeltas(const uint256 hash, double &dPriorityDelta, CAmount &nFeeDelta)
621 std::map<uint256, std::pair<double, CAmount> >::iterator pos = mapDeltas.find(hash);
622 if (pos == mapDeltas.end())
624 const std::pair<double, CAmount> &deltas = pos->second;
625 dPriorityDelta += deltas.first;
626 nFeeDelta += deltas.second;
629 void CTxMemPool::ClearPrioritisation(const uint256 hash)
632 mapDeltas.erase(hash);
636 CCoinsViewMemPool::CCoinsViewMemPool(CCoinsView *baseIn, CTxMemPool &mempoolIn) : CCoinsViewBacked(baseIn), mempool(mempoolIn) { }
638 bool CCoinsViewMemPool::GetCoins(const uint256 &txid, CCoins &coins) const {
639 // If an entry in the mempool exists, always return that one, as it's guaranteed to never
640 // conflict with the underlying cache, and it cannot have pruned entries (as it contains full)
641 // transactions. First checking the underlying cache risks returning a pruned entry instead.
643 if (mempool.lookup(txid, tx)) {
644 coins = CCoins(tx, MEMPOOL_HEIGHT);
647 return (base->GetCoins(txid, coins) && !coins.IsPruned());
650 bool CCoinsViewMemPool::HaveCoins(const uint256 &txid) const {
651 return mempool.exists(txid) || base->HaveCoins(txid);