Merge #11923: Wallet : remove unused fNoncriticalErrors variable from CWalletDB:...
[bitcoinplatinum.git] / src / policy / fees.cpp
blobdc88c4f91ada59dbacefcf16c13a33619b91e0ac
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 #include <policy/fees.h>
7 #include <policy/policy.h>
9 #include <clientversion.h>
10 #include <primitives/transaction.h>
11 #include <streams.h>
12 #include <txmempool.h>
13 #include <util.h>
15 static constexpr double INF_FEERATE = 1e99;
17 std::string StringForFeeEstimateHorizon(FeeEstimateHorizon horizon) {
18 static const std::map<FeeEstimateHorizon, std::string> horizon_strings = {
19 {FeeEstimateHorizon::SHORT_HALFLIFE, "short"},
20 {FeeEstimateHorizon::MED_HALFLIFE, "medium"},
21 {FeeEstimateHorizon::LONG_HALFLIFE, "long"},
23 auto horizon_string = horizon_strings.find(horizon);
25 if (horizon_string == horizon_strings.end()) return "unknown";
27 return horizon_string->second;
30 std::string StringForFeeReason(FeeReason reason) {
31 static const std::map<FeeReason, std::string> fee_reason_strings = {
32 {FeeReason::NONE, "None"},
33 {FeeReason::HALF_ESTIMATE, "Half Target 60% Threshold"},
34 {FeeReason::FULL_ESTIMATE, "Target 85% Threshold"},
35 {FeeReason::DOUBLE_ESTIMATE, "Double Target 95% Threshold"},
36 {FeeReason::CONSERVATIVE, "Conservative Double Target longer horizon"},
37 {FeeReason::MEMPOOL_MIN, "Mempool Min Fee"},
38 {FeeReason::PAYTXFEE, "PayTxFee set"},
39 {FeeReason::FALLBACK, "Fallback fee"},
40 {FeeReason::REQUIRED, "Minimum Required Fee"},
41 {FeeReason::MAXTXFEE, "MaxTxFee limit"}
43 auto reason_string = fee_reason_strings.find(reason);
45 if (reason_string == fee_reason_strings.end()) return "Unknown";
47 return reason_string->second;
50 bool FeeModeFromString(const std::string& mode_string, FeeEstimateMode& fee_estimate_mode) {
51 static const std::map<std::string, FeeEstimateMode> fee_modes = {
52 {"UNSET", FeeEstimateMode::UNSET},
53 {"ECONOMICAL", FeeEstimateMode::ECONOMICAL},
54 {"CONSERVATIVE", FeeEstimateMode::CONSERVATIVE},
56 auto mode = fee_modes.find(mode_string);
58 if (mode == fee_modes.end()) return false;
60 fee_estimate_mode = mode->second;
61 return true;
64 /**
65 * We will instantiate an instance of this class to track transactions that were
66 * included in a block. We will lump transactions into a bucket according to their
67 * approximate feerate and then track how long it took for those txs to be included in a block
69 * The tracking of unconfirmed (mempool) transactions is completely independent of the
70 * historical tracking of transactions that have been confirmed in a block.
72 class TxConfirmStats
74 private:
75 //Define the buckets we will group transactions into
76 const std::vector<double>& buckets; // The upper-bound of the range for the bucket (inclusive)
77 const std::map<double, unsigned int>& bucketMap; // Map of bucket upper-bound to index into all vectors by bucket
79 // For each bucket X:
80 // Count the total # of txs in each bucket
81 // Track the historical moving average of this total over blocks
82 std::vector<double> txCtAvg;
84 // Count the total # of txs confirmed within Y blocks in each bucket
85 // Track the historical moving average of theses totals over blocks
86 std::vector<std::vector<double>> confAvg; // confAvg[Y][X]
88 // Track moving avg of txs which have been evicted from the mempool
89 // after failing to be confirmed within Y blocks
90 std::vector<std::vector<double>> failAvg; // failAvg[Y][X]
92 // Sum the total feerate of all tx's in each bucket
93 // Track the historical moving average of this total over blocks
94 std::vector<double> avg;
96 // Combine the conf counts with tx counts to calculate the confirmation % for each Y,X
97 // Combine the total value with the tx counts to calculate the avg feerate per bucket
99 double decay;
101 // Resolution (# of blocks) with which confirmations are tracked
102 unsigned int scale;
104 // Mempool counts of outstanding transactions
105 // For each bucket X, track the number of transactions in the mempool
106 // that are unconfirmed for each possible confirmation value Y
107 std::vector<std::vector<int> > unconfTxs; //unconfTxs[Y][X]
108 // transactions still unconfirmed after GetMaxConfirms for each bucket
109 std::vector<int> oldUnconfTxs;
111 void resizeInMemoryCounters(size_t newbuckets);
113 public:
115 * Create new TxConfirmStats. This is called by BlockPolicyEstimator's
116 * constructor with default values.
117 * @param defaultBuckets contains the upper limits for the bucket boundaries
118 * @param maxPeriods max number of periods to track
119 * @param decay how much to decay the historical moving average per block
121 TxConfirmStats(const std::vector<double>& defaultBuckets, const std::map<double, unsigned int>& defaultBucketMap,
122 unsigned int maxPeriods, double decay, unsigned int scale);
124 /** Roll the circular buffer for unconfirmed txs*/
125 void ClearCurrent(unsigned int nBlockHeight);
128 * Record a new transaction data point in the current block stats
129 * @param blocksToConfirm the number of blocks it took this transaction to confirm
130 * @param val the feerate of the transaction
131 * @warning blocksToConfirm is 1-based and has to be >= 1
133 void Record(int blocksToConfirm, double val);
135 /** Record a new transaction entering the mempool*/
136 unsigned int NewTx(unsigned int nBlockHeight, double val);
138 /** Remove a transaction from mempool tracking stats*/
139 void removeTx(unsigned int entryHeight, unsigned int nBestSeenHeight,
140 unsigned int bucketIndex, bool inBlock);
142 /** Update our estimates by decaying our historical moving average and updating
143 with the data gathered from the current block */
144 void UpdateMovingAverages();
147 * Calculate a feerate estimate. Find the lowest value bucket (or range of buckets
148 * to make sure we have enough data points) whose transactions still have sufficient likelihood
149 * of being confirmed within the target number of confirmations
150 * @param confTarget target number of confirmations
151 * @param sufficientTxVal required average number of transactions per block in a bucket range
152 * @param minSuccess the success probability we require
153 * @param requireGreater return the lowest feerate such that all higher values pass minSuccess OR
154 * return the highest feerate such that all lower values fail minSuccess
155 * @param nBlockHeight the current block height
157 double EstimateMedianVal(int confTarget, double sufficientTxVal,
158 double minSuccess, bool requireGreater, unsigned int nBlockHeight,
159 EstimationResult *result = nullptr) const;
161 /** Return the max number of confirms we're tracking */
162 unsigned int GetMaxConfirms() const { return scale * confAvg.size(); }
164 /** Write state of estimation data to a file*/
165 void Write(CAutoFile& fileout) const;
168 * Read saved state of estimation data from a file and replace all internal data structures and
169 * variables with this state.
171 void Read(CAutoFile& filein, int nFileVersion, size_t numBuckets);
175 TxConfirmStats::TxConfirmStats(const std::vector<double>& defaultBuckets,
176 const std::map<double, unsigned int>& defaultBucketMap,
177 unsigned int maxPeriods, double _decay, unsigned int _scale)
178 : buckets(defaultBuckets), bucketMap(defaultBucketMap)
180 decay = _decay;
181 assert(_scale != 0 && "_scale must be non-zero");
182 scale = _scale;
183 confAvg.resize(maxPeriods);
184 for (unsigned int i = 0; i < maxPeriods; i++) {
185 confAvg[i].resize(buckets.size());
187 failAvg.resize(maxPeriods);
188 for (unsigned int i = 0; i < maxPeriods; i++) {
189 failAvg[i].resize(buckets.size());
192 txCtAvg.resize(buckets.size());
193 avg.resize(buckets.size());
195 resizeInMemoryCounters(buckets.size());
198 void TxConfirmStats::resizeInMemoryCounters(size_t newbuckets) {
199 // newbuckets must be passed in because the buckets referred to during Read have not been updated yet.
200 unconfTxs.resize(GetMaxConfirms());
201 for (unsigned int i = 0; i < unconfTxs.size(); i++) {
202 unconfTxs[i].resize(newbuckets);
204 oldUnconfTxs.resize(newbuckets);
207 // Roll the unconfirmed txs circular buffer
208 void TxConfirmStats::ClearCurrent(unsigned int nBlockHeight)
210 for (unsigned int j = 0; j < buckets.size(); j++) {
211 oldUnconfTxs[j] += unconfTxs[nBlockHeight%unconfTxs.size()][j];
212 unconfTxs[nBlockHeight%unconfTxs.size()][j] = 0;
217 void TxConfirmStats::Record(int blocksToConfirm, double val)
219 // blocksToConfirm is 1-based
220 if (blocksToConfirm < 1)
221 return;
222 int periodsToConfirm = (blocksToConfirm + scale - 1)/scale;
223 unsigned int bucketindex = bucketMap.lower_bound(val)->second;
224 for (size_t i = periodsToConfirm; i <= confAvg.size(); i++) {
225 confAvg[i - 1][bucketindex]++;
227 txCtAvg[bucketindex]++;
228 avg[bucketindex] += val;
231 void TxConfirmStats::UpdateMovingAverages()
233 for (unsigned int j = 0; j < buckets.size(); j++) {
234 for (unsigned int i = 0; i < confAvg.size(); i++)
235 confAvg[i][j] = confAvg[i][j] * decay;
236 for (unsigned int i = 0; i < failAvg.size(); i++)
237 failAvg[i][j] = failAvg[i][j] * decay;
238 avg[j] = avg[j] * decay;
239 txCtAvg[j] = txCtAvg[j] * decay;
243 // returns -1 on error conditions
244 double TxConfirmStats::EstimateMedianVal(int confTarget, double sufficientTxVal,
245 double successBreakPoint, bool requireGreater,
246 unsigned int nBlockHeight, EstimationResult *result) const
248 // Counters for a bucket (or range of buckets)
249 double nConf = 0; // Number of tx's confirmed within the confTarget
250 double totalNum = 0; // Total number of tx's that were ever confirmed
251 int extraNum = 0; // Number of tx's still in mempool for confTarget or longer
252 double failNum = 0; // Number of tx's that were never confirmed but removed from the mempool after confTarget
253 int periodTarget = (confTarget + scale - 1)/scale;
255 int maxbucketindex = buckets.size() - 1;
257 // requireGreater means we are looking for the lowest feerate such that all higher
258 // values pass, so we start at maxbucketindex (highest feerate) and look at successively
259 // smaller buckets until we reach failure. Otherwise, we are looking for the highest
260 // feerate such that all lower values fail, and we go in the opposite direction.
261 unsigned int startbucket = requireGreater ? maxbucketindex : 0;
262 int step = requireGreater ? -1 : 1;
264 // We'll combine buckets until we have enough samples.
265 // The near and far variables will define the range we've combined
266 // The best variables are the last range we saw which still had a high
267 // enough confirmation rate to count as success.
268 // The cur variables are the current range we're counting.
269 unsigned int curNearBucket = startbucket;
270 unsigned int bestNearBucket = startbucket;
271 unsigned int curFarBucket = startbucket;
272 unsigned int bestFarBucket = startbucket;
274 bool foundAnswer = false;
275 unsigned int bins = unconfTxs.size();
276 bool newBucketRange = true;
277 bool passing = true;
278 EstimatorBucket passBucket;
279 EstimatorBucket failBucket;
281 // Start counting from highest(default) or lowest feerate transactions
282 for (int bucket = startbucket; bucket >= 0 && bucket <= maxbucketindex; bucket += step) {
283 if (newBucketRange) {
284 curNearBucket = bucket;
285 newBucketRange = false;
287 curFarBucket = bucket;
288 nConf += confAvg[periodTarget - 1][bucket];
289 totalNum += txCtAvg[bucket];
290 failNum += failAvg[periodTarget - 1][bucket];
291 for (unsigned int confct = confTarget; confct < GetMaxConfirms(); confct++)
292 extraNum += unconfTxs[(nBlockHeight - confct)%bins][bucket];
293 extraNum += oldUnconfTxs[bucket];
294 // If we have enough transaction data points in this range of buckets,
295 // we can test for success
296 // (Only count the confirmed data points, so that each confirmation count
297 // will be looking at the same amount of data and same bucket breaks)
298 if (totalNum >= sufficientTxVal / (1 - decay)) {
299 double curPct = nConf / (totalNum + failNum + extraNum);
301 // Check to see if we are no longer getting confirmed at the success rate
302 if ((requireGreater && curPct < successBreakPoint) || (!requireGreater && curPct > successBreakPoint)) {
303 if (passing == true) {
304 // First time we hit a failure record the failed bucket
305 unsigned int failMinBucket = std::min(curNearBucket, curFarBucket);
306 unsigned int failMaxBucket = std::max(curNearBucket, curFarBucket);
307 failBucket.start = failMinBucket ? buckets[failMinBucket - 1] : 0;
308 failBucket.end = buckets[failMaxBucket];
309 failBucket.withinTarget = nConf;
310 failBucket.totalConfirmed = totalNum;
311 failBucket.inMempool = extraNum;
312 failBucket.leftMempool = failNum;
313 passing = false;
315 continue;
317 // Otherwise update the cumulative stats, and the bucket variables
318 // and reset the counters
319 else {
320 failBucket = EstimatorBucket(); // Reset any failed bucket, currently passing
321 foundAnswer = true;
322 passing = true;
323 passBucket.withinTarget = nConf;
324 nConf = 0;
325 passBucket.totalConfirmed = totalNum;
326 totalNum = 0;
327 passBucket.inMempool = extraNum;
328 passBucket.leftMempool = failNum;
329 failNum = 0;
330 extraNum = 0;
331 bestNearBucket = curNearBucket;
332 bestFarBucket = curFarBucket;
333 newBucketRange = true;
338 double median = -1;
339 double txSum = 0;
341 // Calculate the "average" feerate of the best bucket range that met success conditions
342 // Find the bucket with the median transaction and then report the average feerate from that bucket
343 // This is a compromise between finding the median which we can't since we don't save all tx's
344 // and reporting the average which is less accurate
345 unsigned int minBucket = std::min(bestNearBucket, bestFarBucket);
346 unsigned int maxBucket = std::max(bestNearBucket, bestFarBucket);
347 for (unsigned int j = minBucket; j <= maxBucket; j++) {
348 txSum += txCtAvg[j];
350 if (foundAnswer && txSum != 0) {
351 txSum = txSum / 2;
352 for (unsigned int j = minBucket; j <= maxBucket; j++) {
353 if (txCtAvg[j] < txSum)
354 txSum -= txCtAvg[j];
355 else { // we're in the right bucket
356 median = avg[j] / txCtAvg[j];
357 break;
361 passBucket.start = minBucket ? buckets[minBucket-1] : 0;
362 passBucket.end = buckets[maxBucket];
365 // If we were passing until we reached last few buckets with insufficient data, then report those as failed
366 if (passing && !newBucketRange) {
367 unsigned int failMinBucket = std::min(curNearBucket, curFarBucket);
368 unsigned int failMaxBucket = std::max(curNearBucket, curFarBucket);
369 failBucket.start = failMinBucket ? buckets[failMinBucket - 1] : 0;
370 failBucket.end = buckets[failMaxBucket];
371 failBucket.withinTarget = nConf;
372 failBucket.totalConfirmed = totalNum;
373 failBucket.inMempool = extraNum;
374 failBucket.leftMempool = failNum;
377 LogPrint(BCLog::ESTIMATEFEE, "FeeEst: %d %s%.0f%% decay %.5f: feerate: %g from (%g - %g) %.2f%% %.1f/(%.1f %d mem %.1f out) Fail: (%g - %g) %.2f%% %.1f/(%.1f %d mem %.1f out)\n",
378 confTarget, requireGreater ? ">" : "<", 100.0 * successBreakPoint, decay,
379 median, passBucket.start, passBucket.end,
380 100 * passBucket.withinTarget / (passBucket.totalConfirmed + passBucket.inMempool + passBucket.leftMempool),
381 passBucket.withinTarget, passBucket.totalConfirmed, passBucket.inMempool, passBucket.leftMempool,
382 failBucket.start, failBucket.end,
383 100 * failBucket.withinTarget / (failBucket.totalConfirmed + failBucket.inMempool + failBucket.leftMempool),
384 failBucket.withinTarget, failBucket.totalConfirmed, failBucket.inMempool, failBucket.leftMempool);
387 if (result) {
388 result->pass = passBucket;
389 result->fail = failBucket;
390 result->decay = decay;
391 result->scale = scale;
393 return median;
396 void TxConfirmStats::Write(CAutoFile& fileout) const
398 fileout << decay;
399 fileout << scale;
400 fileout << avg;
401 fileout << txCtAvg;
402 fileout << confAvg;
403 fileout << failAvg;
406 void TxConfirmStats::Read(CAutoFile& filein, int nFileVersion, size_t numBuckets)
408 // Read data file and do some very basic sanity checking
409 // buckets and bucketMap are not updated yet, so don't access them
410 // If there is a read failure, we'll just discard this entire object anyway
411 size_t maxConfirms, maxPeriods;
413 // The current version will store the decay with each individual TxConfirmStats and also keep a scale factor
414 if (nFileVersion >= 149900) {
415 filein >> decay;
416 if (decay <= 0 || decay >= 1) {
417 throw std::runtime_error("Corrupt estimates file. Decay must be between 0 and 1 (non-inclusive)");
419 filein >> scale;
420 if (scale == 0) {
421 throw std::runtime_error("Corrupt estimates file. Scale must be non-zero");
425 filein >> avg;
426 if (avg.size() != numBuckets) {
427 throw std::runtime_error("Corrupt estimates file. Mismatch in feerate average bucket count");
429 filein >> txCtAvg;
430 if (txCtAvg.size() != numBuckets) {
431 throw std::runtime_error("Corrupt estimates file. Mismatch in tx count bucket count");
433 filein >> confAvg;
434 maxPeriods = confAvg.size();
435 maxConfirms = scale * maxPeriods;
437 if (maxConfirms <= 0 || maxConfirms > 6 * 24 * 7) { // one week
438 throw std::runtime_error("Corrupt estimates file. Must maintain estimates for between 1 and 1008 (one week) confirms");
440 for (unsigned int i = 0; i < maxPeriods; i++) {
441 if (confAvg[i].size() != numBuckets) {
442 throw std::runtime_error("Corrupt estimates file. Mismatch in feerate conf average bucket count");
446 if (nFileVersion >= 149900) {
447 filein >> failAvg;
448 if (maxPeriods != failAvg.size()) {
449 throw std::runtime_error("Corrupt estimates file. Mismatch in confirms tracked for failures");
451 for (unsigned int i = 0; i < maxPeriods; i++) {
452 if (failAvg[i].size() != numBuckets) {
453 throw std::runtime_error("Corrupt estimates file. Mismatch in one of failure average bucket counts");
456 } else {
457 failAvg.resize(confAvg.size());
458 for (unsigned int i = 0; i < failAvg.size(); i++) {
459 failAvg[i].resize(numBuckets);
463 // Resize the current block variables which aren't stored in the data file
464 // to match the number of confirms and buckets
465 resizeInMemoryCounters(numBuckets);
467 LogPrint(BCLog::ESTIMATEFEE, "Reading estimates: %u buckets counting confirms up to %u blocks\n",
468 numBuckets, maxConfirms);
471 unsigned int TxConfirmStats::NewTx(unsigned int nBlockHeight, double val)
473 unsigned int bucketindex = bucketMap.lower_bound(val)->second;
474 unsigned int blockIndex = nBlockHeight % unconfTxs.size();
475 unconfTxs[blockIndex][bucketindex]++;
476 return bucketindex;
479 void TxConfirmStats::removeTx(unsigned int entryHeight, unsigned int nBestSeenHeight, unsigned int bucketindex, bool inBlock)
481 //nBestSeenHeight is not updated yet for the new block
482 int blocksAgo = nBestSeenHeight - entryHeight;
483 if (nBestSeenHeight == 0) // the BlockPolicyEstimator hasn't seen any blocks yet
484 blocksAgo = 0;
485 if (blocksAgo < 0) {
486 LogPrint(BCLog::ESTIMATEFEE, "Blockpolicy error, blocks ago is negative for mempool tx\n");
487 return; //This can't happen because we call this with our best seen height, no entries can have higher
490 if (blocksAgo >= (int)unconfTxs.size()) {
491 if (oldUnconfTxs[bucketindex] > 0) {
492 oldUnconfTxs[bucketindex]--;
493 } else {
494 LogPrint(BCLog::ESTIMATEFEE, "Blockpolicy error, mempool tx removed from >25 blocks,bucketIndex=%u already\n",
495 bucketindex);
498 else {
499 unsigned int blockIndex = entryHeight % unconfTxs.size();
500 if (unconfTxs[blockIndex][bucketindex] > 0) {
501 unconfTxs[blockIndex][bucketindex]--;
502 } else {
503 LogPrint(BCLog::ESTIMATEFEE, "Blockpolicy error, mempool tx removed from blockIndex=%u,bucketIndex=%u already\n",
504 blockIndex, bucketindex);
507 if (!inBlock && (unsigned int)blocksAgo >= scale) { // Only counts as a failure if not confirmed for entire period
508 assert(scale != 0);
509 unsigned int periodsAgo = blocksAgo / scale;
510 for (size_t i = 0; i < periodsAgo && i < failAvg.size(); i++) {
511 failAvg[i][bucketindex]++;
516 // This function is called from CTxMemPool::removeUnchecked to ensure
517 // txs removed from the mempool for any reason are no longer
518 // tracked. Txs that were part of a block have already been removed in
519 // processBlockTx to ensure they are never double tracked, but it is
520 // of no harm to try to remove them again.
521 bool CBlockPolicyEstimator::removeTx(uint256 hash, bool inBlock)
523 LOCK(cs_feeEstimator);
524 std::map<uint256, TxStatsInfo>::iterator pos = mapMemPoolTxs.find(hash);
525 if (pos != mapMemPoolTxs.end()) {
526 feeStats->removeTx(pos->second.blockHeight, nBestSeenHeight, pos->second.bucketIndex, inBlock);
527 shortStats->removeTx(pos->second.blockHeight, nBestSeenHeight, pos->second.bucketIndex, inBlock);
528 longStats->removeTx(pos->second.blockHeight, nBestSeenHeight, pos->second.bucketIndex, inBlock);
529 mapMemPoolTxs.erase(hash);
530 return true;
531 } else {
532 return false;
536 CBlockPolicyEstimator::CBlockPolicyEstimator()
537 : nBestSeenHeight(0), firstRecordedHeight(0), historicalFirst(0), historicalBest(0), trackedTxs(0), untrackedTxs(0)
539 static_assert(MIN_BUCKET_FEERATE > 0, "Min feerate must be nonzero");
540 size_t bucketIndex = 0;
541 for (double bucketBoundary = MIN_BUCKET_FEERATE; bucketBoundary <= MAX_BUCKET_FEERATE; bucketBoundary *= FEE_SPACING, bucketIndex++) {
542 buckets.push_back(bucketBoundary);
543 bucketMap[bucketBoundary] = bucketIndex;
545 buckets.push_back(INF_FEERATE);
546 bucketMap[INF_FEERATE] = bucketIndex;
547 assert(bucketMap.size() == buckets.size());
549 feeStats = std::unique_ptr<TxConfirmStats>(new TxConfirmStats(buckets, bucketMap, MED_BLOCK_PERIODS, MED_DECAY, MED_SCALE));
550 shortStats = std::unique_ptr<TxConfirmStats>(new TxConfirmStats(buckets, bucketMap, SHORT_BLOCK_PERIODS, SHORT_DECAY, SHORT_SCALE));
551 longStats = std::unique_ptr<TxConfirmStats>(new TxConfirmStats(buckets, bucketMap, LONG_BLOCK_PERIODS, LONG_DECAY, LONG_SCALE));
554 CBlockPolicyEstimator::~CBlockPolicyEstimator()
558 void CBlockPolicyEstimator::processTransaction(const CTxMemPoolEntry& entry, bool validFeeEstimate)
560 LOCK(cs_feeEstimator);
561 unsigned int txHeight = entry.GetHeight();
562 uint256 hash = entry.GetTx().GetHash();
563 if (mapMemPoolTxs.count(hash)) {
564 LogPrint(BCLog::ESTIMATEFEE, "Blockpolicy error mempool tx %s already being tracked\n",
565 hash.ToString().c_str());
566 return;
569 if (txHeight != nBestSeenHeight) {
570 // Ignore side chains and re-orgs; assuming they are random they don't
571 // affect the estimate. We'll potentially double count transactions in 1-block reorgs.
572 // Ignore txs if BlockPolicyEstimator is not in sync with chainActive.Tip().
573 // It will be synced next time a block is processed.
574 return;
577 // Only want to be updating estimates when our blockchain is synced,
578 // otherwise we'll miscalculate how many blocks its taking to get included.
579 if (!validFeeEstimate) {
580 untrackedTxs++;
581 return;
583 trackedTxs++;
585 // Feerates are stored and reported as BTC-per-kb:
586 CFeeRate feeRate(entry.GetFee(), entry.GetTxSize());
588 mapMemPoolTxs[hash].blockHeight = txHeight;
589 unsigned int bucketIndex = feeStats->NewTx(txHeight, (double)feeRate.GetFeePerK());
590 mapMemPoolTxs[hash].bucketIndex = bucketIndex;
591 unsigned int bucketIndex2 = shortStats->NewTx(txHeight, (double)feeRate.GetFeePerK());
592 assert(bucketIndex == bucketIndex2);
593 unsigned int bucketIndex3 = longStats->NewTx(txHeight, (double)feeRate.GetFeePerK());
594 assert(bucketIndex == bucketIndex3);
597 bool CBlockPolicyEstimator::processBlockTx(unsigned int nBlockHeight, const CTxMemPoolEntry* entry)
599 if (!removeTx(entry->GetTx().GetHash(), true)) {
600 // This transaction wasn't being tracked for fee estimation
601 return false;
604 // How many blocks did it take for miners to include this transaction?
605 // blocksToConfirm is 1-based, so a transaction included in the earliest
606 // possible block has confirmation count of 1
607 int blocksToConfirm = nBlockHeight - entry->GetHeight();
608 if (blocksToConfirm <= 0) {
609 // This can't happen because we don't process transactions from a block with a height
610 // lower than our greatest seen height
611 LogPrint(BCLog::ESTIMATEFEE, "Blockpolicy error Transaction had negative blocksToConfirm\n");
612 return false;
615 // Feerates are stored and reported as BTC-per-kb:
616 CFeeRate feeRate(entry->GetFee(), entry->GetTxSize());
618 feeStats->Record(blocksToConfirm, (double)feeRate.GetFeePerK());
619 shortStats->Record(blocksToConfirm, (double)feeRate.GetFeePerK());
620 longStats->Record(blocksToConfirm, (double)feeRate.GetFeePerK());
621 return true;
624 void CBlockPolicyEstimator::processBlock(unsigned int nBlockHeight,
625 std::vector<const CTxMemPoolEntry*>& entries)
627 LOCK(cs_feeEstimator);
628 if (nBlockHeight <= nBestSeenHeight) {
629 // Ignore side chains and re-orgs; assuming they are random
630 // they don't affect the estimate.
631 // And if an attacker can re-org the chain at will, then
632 // you've got much bigger problems than "attacker can influence
633 // transaction fees."
634 return;
637 // Must update nBestSeenHeight in sync with ClearCurrent so that
638 // calls to removeTx (via processBlockTx) correctly calculate age
639 // of unconfirmed txs to remove from tracking.
640 nBestSeenHeight = nBlockHeight;
642 // Update unconfirmed circular buffer
643 feeStats->ClearCurrent(nBlockHeight);
644 shortStats->ClearCurrent(nBlockHeight);
645 longStats->ClearCurrent(nBlockHeight);
647 // Decay all exponential averages
648 feeStats->UpdateMovingAverages();
649 shortStats->UpdateMovingAverages();
650 longStats->UpdateMovingAverages();
652 unsigned int countedTxs = 0;
653 // Update averages with data points from current block
654 for (const auto& entry : entries) {
655 if (processBlockTx(nBlockHeight, entry))
656 countedTxs++;
659 if (firstRecordedHeight == 0 && countedTxs > 0) {
660 firstRecordedHeight = nBestSeenHeight;
661 LogPrint(BCLog::ESTIMATEFEE, "Blockpolicy first recorded height %u\n", firstRecordedHeight);
665 LogPrint(BCLog::ESTIMATEFEE, "Blockpolicy estimates updated by %u of %u block txs, since last block %u of %u tracked, mempool map size %u, max target %u from %s\n",
666 countedTxs, entries.size(), trackedTxs, trackedTxs + untrackedTxs, mapMemPoolTxs.size(),
667 MaxUsableEstimate(), HistoricalBlockSpan() > BlockSpan() ? "historical" : "current");
669 trackedTxs = 0;
670 untrackedTxs = 0;
673 CFeeRate CBlockPolicyEstimator::estimateFee(int confTarget) const
675 // It's not possible to get reasonable estimates for confTarget of 1
676 if (confTarget <= 1)
677 return CFeeRate(0);
679 return estimateRawFee(confTarget, DOUBLE_SUCCESS_PCT, FeeEstimateHorizon::MED_HALFLIFE);
682 CFeeRate CBlockPolicyEstimator::estimateRawFee(int confTarget, double successThreshold, FeeEstimateHorizon horizon, EstimationResult* result) const
684 TxConfirmStats* stats;
685 double sufficientTxs = SUFFICIENT_FEETXS;
686 switch (horizon) {
687 case FeeEstimateHorizon::SHORT_HALFLIFE: {
688 stats = shortStats.get();
689 sufficientTxs = SUFFICIENT_TXS_SHORT;
690 break;
692 case FeeEstimateHorizon::MED_HALFLIFE: {
693 stats = feeStats.get();
694 break;
696 case FeeEstimateHorizon::LONG_HALFLIFE: {
697 stats = longStats.get();
698 break;
700 default: {
701 throw std::out_of_range("CBlockPolicyEstimator::estimateRawFee unknown FeeEstimateHorizon");
705 LOCK(cs_feeEstimator);
706 // Return failure if trying to analyze a target we're not tracking
707 if (confTarget <= 0 || (unsigned int)confTarget > stats->GetMaxConfirms())
708 return CFeeRate(0);
709 if (successThreshold > 1)
710 return CFeeRate(0);
712 double median = stats->EstimateMedianVal(confTarget, sufficientTxs, successThreshold, true, nBestSeenHeight, result);
714 if (median < 0)
715 return CFeeRate(0);
717 return CFeeRate(llround(median));
720 unsigned int CBlockPolicyEstimator::HighestTargetTracked(FeeEstimateHorizon horizon) const
722 switch (horizon) {
723 case FeeEstimateHorizon::SHORT_HALFLIFE: {
724 return shortStats->GetMaxConfirms();
726 case FeeEstimateHorizon::MED_HALFLIFE: {
727 return feeStats->GetMaxConfirms();
729 case FeeEstimateHorizon::LONG_HALFLIFE: {
730 return longStats->GetMaxConfirms();
732 default: {
733 throw std::out_of_range("CBlockPolicyEstimator::HighestTargetTracked unknown FeeEstimateHorizon");
738 unsigned int CBlockPolicyEstimator::BlockSpan() const
740 if (firstRecordedHeight == 0) return 0;
741 assert(nBestSeenHeight >= firstRecordedHeight);
743 return nBestSeenHeight - firstRecordedHeight;
746 unsigned int CBlockPolicyEstimator::HistoricalBlockSpan() const
748 if (historicalFirst == 0) return 0;
749 assert(historicalBest >= historicalFirst);
751 if (nBestSeenHeight - historicalBest > OLDEST_ESTIMATE_HISTORY) return 0;
753 return historicalBest - historicalFirst;
756 unsigned int CBlockPolicyEstimator::MaxUsableEstimate() const
758 // Block spans are divided by 2 to make sure there are enough potential failing data points for the estimate
759 return std::min(longStats->GetMaxConfirms(), std::max(BlockSpan(), HistoricalBlockSpan()) / 2);
762 /** Return a fee estimate at the required successThreshold from the shortest
763 * time horizon which tracks confirmations up to the desired target. If
764 * checkShorterHorizon is requested, also allow short time horizon estimates
765 * for a lower target to reduce the given answer */
766 double CBlockPolicyEstimator::estimateCombinedFee(unsigned int confTarget, double successThreshold, bool checkShorterHorizon, EstimationResult *result) const
768 double estimate = -1;
769 if (confTarget >= 1 && confTarget <= longStats->GetMaxConfirms()) {
770 // Find estimate from shortest time horizon possible
771 if (confTarget <= shortStats->GetMaxConfirms()) { // short horizon
772 estimate = shortStats->EstimateMedianVal(confTarget, SUFFICIENT_TXS_SHORT, successThreshold, true, nBestSeenHeight, result);
774 else if (confTarget <= feeStats->GetMaxConfirms()) { // medium horizon
775 estimate = feeStats->EstimateMedianVal(confTarget, SUFFICIENT_FEETXS, successThreshold, true, nBestSeenHeight, result);
777 else { // long horizon
778 estimate = longStats->EstimateMedianVal(confTarget, SUFFICIENT_FEETXS, successThreshold, true, nBestSeenHeight, result);
780 if (checkShorterHorizon) {
781 EstimationResult tempResult;
782 // If a lower confTarget from a more recent horizon returns a lower answer use it.
783 if (confTarget > feeStats->GetMaxConfirms()) {
784 double medMax = feeStats->EstimateMedianVal(feeStats->GetMaxConfirms(), SUFFICIENT_FEETXS, successThreshold, true, nBestSeenHeight, &tempResult);
785 if (medMax > 0 && (estimate == -1 || medMax < estimate)) {
786 estimate = medMax;
787 if (result) *result = tempResult;
790 if (confTarget > shortStats->GetMaxConfirms()) {
791 double shortMax = shortStats->EstimateMedianVal(shortStats->GetMaxConfirms(), SUFFICIENT_TXS_SHORT, successThreshold, true, nBestSeenHeight, &tempResult);
792 if (shortMax > 0 && (estimate == -1 || shortMax < estimate)) {
793 estimate = shortMax;
794 if (result) *result = tempResult;
799 return estimate;
802 /** Ensure that for a conservative estimate, the DOUBLE_SUCCESS_PCT is also met
803 * at 2 * target for any longer time horizons.
805 double CBlockPolicyEstimator::estimateConservativeFee(unsigned int doubleTarget, EstimationResult *result) const
807 double estimate = -1;
808 EstimationResult tempResult;
809 if (doubleTarget <= shortStats->GetMaxConfirms()) {
810 estimate = feeStats->EstimateMedianVal(doubleTarget, SUFFICIENT_FEETXS, DOUBLE_SUCCESS_PCT, true, nBestSeenHeight, result);
812 if (doubleTarget <= feeStats->GetMaxConfirms()) {
813 double longEstimate = longStats->EstimateMedianVal(doubleTarget, SUFFICIENT_FEETXS, DOUBLE_SUCCESS_PCT, true, nBestSeenHeight, &tempResult);
814 if (longEstimate > estimate) {
815 estimate = longEstimate;
816 if (result) *result = tempResult;
819 return estimate;
822 /** estimateSmartFee returns the max of the feerates calculated with a 60%
823 * threshold required at target / 2, an 85% threshold required at target and a
824 * 95% threshold required at 2 * target. Each calculation is performed at the
825 * shortest time horizon which tracks the required target. Conservative
826 * estimates, however, required the 95% threshold at 2 * target be met for any
827 * longer time horizons also.
829 CFeeRate CBlockPolicyEstimator::estimateSmartFee(int confTarget, FeeCalculation *feeCalc, bool conservative) const
831 LOCK(cs_feeEstimator);
833 if (feeCalc) {
834 feeCalc->desiredTarget = confTarget;
835 feeCalc->returnedTarget = confTarget;
838 double median = -1;
839 EstimationResult tempResult;
841 // Return failure if trying to analyze a target we're not tracking
842 if (confTarget <= 0 || (unsigned int)confTarget > longStats->GetMaxConfirms()) {
843 return CFeeRate(0); // error condition
846 // It's not possible to get reasonable estimates for confTarget of 1
847 if (confTarget == 1) confTarget = 2;
849 unsigned int maxUsableEstimate = MaxUsableEstimate();
850 if ((unsigned int)confTarget > maxUsableEstimate) {
851 confTarget = maxUsableEstimate;
853 if (feeCalc) feeCalc->returnedTarget = confTarget;
855 if (confTarget <= 1) return CFeeRate(0); // error condition
857 assert(confTarget > 0); //estimateCombinedFee and estimateConservativeFee take unsigned ints
858 /** true is passed to estimateCombined fee for target/2 and target so
859 * that we check the max confirms for shorter time horizons as well.
860 * This is necessary to preserve monotonically increasing estimates.
861 * For non-conservative estimates we do the same thing for 2*target, but
862 * for conservative estimates we want to skip these shorter horizons
863 * checks for 2*target because we are taking the max over all time
864 * horizons so we already have monotonically increasing estimates and
865 * the purpose of conservative estimates is not to let short term
866 * fluctuations lower our estimates by too much.
868 double halfEst = estimateCombinedFee(confTarget/2, HALF_SUCCESS_PCT, true, &tempResult);
869 if (feeCalc) {
870 feeCalc->est = tempResult;
871 feeCalc->reason = FeeReason::HALF_ESTIMATE;
873 median = halfEst;
874 double actualEst = estimateCombinedFee(confTarget, SUCCESS_PCT, true, &tempResult);
875 if (actualEst > median) {
876 median = actualEst;
877 if (feeCalc) {
878 feeCalc->est = tempResult;
879 feeCalc->reason = FeeReason::FULL_ESTIMATE;
882 double doubleEst = estimateCombinedFee(2 * confTarget, DOUBLE_SUCCESS_PCT, !conservative, &tempResult);
883 if (doubleEst > median) {
884 median = doubleEst;
885 if (feeCalc) {
886 feeCalc->est = tempResult;
887 feeCalc->reason = FeeReason::DOUBLE_ESTIMATE;
891 if (conservative || median == -1) {
892 double consEst = estimateConservativeFee(2 * confTarget, &tempResult);
893 if (consEst > median) {
894 median = consEst;
895 if (feeCalc) {
896 feeCalc->est = tempResult;
897 feeCalc->reason = FeeReason::CONSERVATIVE;
902 if (median < 0) return CFeeRate(0); // error condition
904 return CFeeRate(llround(median));
908 bool CBlockPolicyEstimator::Write(CAutoFile& fileout) const
910 try {
911 LOCK(cs_feeEstimator);
912 fileout << 149900; // version required to read: 0.14.99 or later
913 fileout << CLIENT_VERSION; // version that wrote the file
914 fileout << nBestSeenHeight;
915 if (BlockSpan() > HistoricalBlockSpan()/2) {
916 fileout << firstRecordedHeight << nBestSeenHeight;
918 else {
919 fileout << historicalFirst << historicalBest;
921 fileout << buckets;
922 feeStats->Write(fileout);
923 shortStats->Write(fileout);
924 longStats->Write(fileout);
926 catch (const std::exception&) {
927 LogPrintf("CBlockPolicyEstimator::Write(): unable to write policy estimator data (non-fatal)\n");
928 return false;
930 return true;
933 bool CBlockPolicyEstimator::Read(CAutoFile& filein)
935 try {
936 LOCK(cs_feeEstimator);
937 int nVersionRequired, nVersionThatWrote;
938 filein >> nVersionRequired >> nVersionThatWrote;
939 if (nVersionRequired > CLIENT_VERSION)
940 return error("CBlockPolicyEstimator::Read(): up-version (%d) fee estimate file", nVersionRequired);
942 // Read fee estimates file into temporary variables so existing data
943 // structures aren't corrupted if there is an exception.
944 unsigned int nFileBestSeenHeight;
945 filein >> nFileBestSeenHeight;
947 if (nVersionThatWrote < 149900) {
948 // Read the old fee estimates file for temporary use, but then discard. Will start collecting data from scratch.
949 // decay is stored before buckets in old versions, so pre-read decay and pass into TxConfirmStats constructor
950 double tempDecay;
951 filein >> tempDecay;
952 if (tempDecay <= 0 || tempDecay >= 1)
953 throw std::runtime_error("Corrupt estimates file. Decay must be between 0 and 1 (non-inclusive)");
955 std::vector<double> tempBuckets;
956 filein >> tempBuckets;
957 size_t tempNum = tempBuckets.size();
958 if (tempNum <= 1 || tempNum > 1000)
959 throw std::runtime_error("Corrupt estimates file. Must have between 2 and 1000 feerate buckets");
961 std::map<double, unsigned int> tempMap;
963 std::unique_ptr<TxConfirmStats> tempFeeStats(new TxConfirmStats(tempBuckets, tempMap, MED_BLOCK_PERIODS, tempDecay, 1));
964 tempFeeStats->Read(filein, nVersionThatWrote, tempNum);
965 // if nVersionThatWrote < 139900 then another TxConfirmStats (for priority) follows but can be ignored.
967 tempMap.clear();
968 for (unsigned int i = 0; i < tempBuckets.size(); i++) {
969 tempMap[tempBuckets[i]] = i;
972 else { // nVersionThatWrote >= 149900
973 unsigned int nFileHistoricalFirst, nFileHistoricalBest;
974 filein >> nFileHistoricalFirst >> nFileHistoricalBest;
975 if (nFileHistoricalFirst > nFileHistoricalBest || nFileHistoricalBest > nFileBestSeenHeight) {
976 throw std::runtime_error("Corrupt estimates file. Historical block range for estimates is invalid");
978 std::vector<double> fileBuckets;
979 filein >> fileBuckets;
980 size_t numBuckets = fileBuckets.size();
981 if (numBuckets <= 1 || numBuckets > 1000)
982 throw std::runtime_error("Corrupt estimates file. Must have between 2 and 1000 feerate buckets");
984 std::unique_ptr<TxConfirmStats> fileFeeStats(new TxConfirmStats(buckets, bucketMap, MED_BLOCK_PERIODS, MED_DECAY, MED_SCALE));
985 std::unique_ptr<TxConfirmStats> fileShortStats(new TxConfirmStats(buckets, bucketMap, SHORT_BLOCK_PERIODS, SHORT_DECAY, SHORT_SCALE));
986 std::unique_ptr<TxConfirmStats> fileLongStats(new TxConfirmStats(buckets, bucketMap, LONG_BLOCK_PERIODS, LONG_DECAY, LONG_SCALE));
987 fileFeeStats->Read(filein, nVersionThatWrote, numBuckets);
988 fileShortStats->Read(filein, nVersionThatWrote, numBuckets);
989 fileLongStats->Read(filein, nVersionThatWrote, numBuckets);
991 // Fee estimates file parsed correctly
992 // Copy buckets from file and refresh our bucketmap
993 buckets = fileBuckets;
994 bucketMap.clear();
995 for (unsigned int i = 0; i < buckets.size(); i++) {
996 bucketMap[buckets[i]] = i;
999 // Destroy old TxConfirmStats and point to new ones that already reference buckets and bucketMap
1000 feeStats = std::move(fileFeeStats);
1001 shortStats = std::move(fileShortStats);
1002 longStats = std::move(fileLongStats);
1004 nBestSeenHeight = nFileBestSeenHeight;
1005 historicalFirst = nFileHistoricalFirst;
1006 historicalBest = nFileHistoricalBest;
1009 catch (const std::exception& e) {
1010 LogPrintf("CBlockPolicyEstimator::Read(): unable to read policy estimator data (non-fatal): %s\n",e.what());
1011 return false;
1013 return true;
1016 void CBlockPolicyEstimator::FlushUnconfirmed(CTxMemPool& pool) {
1017 int64_t startclear = GetTimeMicros();
1018 std::vector<uint256> txids;
1019 pool.queryHashes(txids);
1020 LOCK(cs_feeEstimator);
1021 for (auto& txid : txids) {
1022 removeTx(txid, false);
1024 int64_t endclear = GetTimeMicros();
1025 LogPrint(BCLog::ESTIMATEFEE, "Recorded %u unconfirmed txs from mempool in %gs\n",txids.size(), (endclear - startclear)*0.000001);
1028 FeeFilterRounder::FeeFilterRounder(const CFeeRate& minIncrementalFee)
1030 CAmount minFeeLimit = std::max(CAmount(1), minIncrementalFee.GetFeePerK() / 2);
1031 feeset.insert(0);
1032 for (double bucketBoundary = minFeeLimit; bucketBoundary <= MAX_FILTER_FEERATE; bucketBoundary *= FEE_FILTER_SPACING) {
1033 feeset.insert(bucketBoundary);
1037 CAmount FeeFilterRounder::round(CAmount currentMinFee)
1039 std::set<double>::iterator it = feeset.lower_bound(currentMinFee);
1040 if ((it != feeset.begin() && insecure_rand.rand32() % 3 != 0) || it == feeset.end()) {
1041 it--;
1043 return static_cast<CAmount>(*it);