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