Dash Core Source Documentation (0.16.0.1)

Find detailed information regarding the Dash Core source code.

fees.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2015 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.
5 
6 #include <policy/fees.h>
7 #include <policy/policy.h>
8 
9 #include <clientversion.h>
10 #include <primitives/transaction.h>
11 #include <streams.h>
12 #include <txmempool.h>
13 #include <util.h>
14 
15 static constexpr double INF_FEERATE = 1e99;
16 
18  static const std::map<FeeEstimateHorizon, std::string> horizon_strings = {
22  };
23  auto horizon_string = horizon_strings.find(horizon);
24 
25  if (horizon_string == horizon_strings.end()) return "unknown";
26 
27  return horizon_string->second;
28 }
29 
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"}
42  };
43  auto reason_string = fee_reason_strings.find(reason);
44 
45  if (reason_string == fee_reason_strings.end()) return "Unknown";
46 
47  return reason_string->second;
48 }
49 
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},
55  };
56  auto mode = fee_modes.find(mode_string);
57 
58  if (mode == fee_modes.end()) return false;
59 
60  fee_estimate_mode = mode->second;
61  return true;
62 }
63 
73 {
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
78 
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;
83 
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]
87 
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]
91 
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;
95 
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
98 
99  double decay;
100 
101  // Resolution (# of blocks) with which confirmations are tracked
102  unsigned int scale;
103 
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;
110 
111  void resizeInMemoryCounters(size_t newbuckets);
112 
113 public:
121  TxConfirmStats(const std::vector<double>& defaultBuckets, const std::map<double, unsigned int>& defaultBucketMap,
122  unsigned int maxPeriods, double decay, unsigned int scale);
123 
125  void ClearCurrent(unsigned int nBlockHeight);
126 
133  void Record(int blocksToConfirm, double val);
134 
136  unsigned int NewTx(unsigned int nBlockHeight, double val);
137 
139  void removeTx(unsigned int entryHeight, unsigned int nBestSeenHeight,
140  unsigned int bucketIndex, bool inBlock);
141 
144  void UpdateMovingAverages();
145 
157  double EstimateMedianVal(int confTarget, double sufficientTxVal,
158  double minSuccess, bool requireGreater, unsigned int nBlockHeight,
159  EstimationResult *result = nullptr) const;
160 
162  unsigned int GetMaxConfirms() const { return scale * confAvg.size(); }
163 
165  void Write(CAutoFile& fileout) const;
166 
171  void Read(CAutoFile& filein, int nFileVersion, size_t numBuckets);
172 };
173 
174 
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)
179 {
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());
186  }
187  failAvg.resize(maxPeriods);
188  for (unsigned int i = 0; i < maxPeriods; i++) {
189  failAvg[i].resize(buckets.size());
190  }
191 
192  txCtAvg.resize(buckets.size());
193  avg.resize(buckets.size());
194 
196 }
197 
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);
203  }
204  oldUnconfTxs.resize(newbuckets);
205 }
206 
207 // Roll the unconfirmed txs circular buffer
208 void TxConfirmStats::ClearCurrent(unsigned int nBlockHeight)
209 {
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;
213  }
214 }
215 
216 
217 void TxConfirmStats::Record(int blocksToConfirm, double val)
218 {
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]++;
226  }
227  txCtAvg[bucketindex]++;
228  avg[bucketindex] += val;
229 }
230 
232 {
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;
240  }
241 }
242 
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
247 {
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;
254 
255  int maxbucketindex = buckets.size() - 1;
256 
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;
263 
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;
273 
274  bool foundAnswer = false;
275  unsigned int bins = unconfTxs.size();
276  bool newBucketRange = true;
277  bool passing = true;
278  EstimatorBucket passBucket;
279  EstimatorBucket failBucket;
280 
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;
286  }
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);
300 
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;
314  }
315  continue;
316  }
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;
334  }
335  }
336  }
337 
338  double median = -1;
339  double txSum = 0;
340 
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];
349  }
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;
358  }
359  }
360 
361  passBucket.start = minBucket ? buckets[minBucket-1] : 0;
362  passBucket.end = buckets[maxBucket];
363  }
364 
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;
375  }
376 
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);
385 
386 
387  if (result) {
388  result->pass = passBucket;
389  result->fail = failBucket;
390  result->decay = decay;
391  result->scale = scale;
392  }
393  return median;
394 }
395 
397 {
398  fileout << decay;
399  fileout << scale;
400  fileout << avg;
401  fileout << txCtAvg;
402  fileout << confAvg;
403  fileout << failAvg;
404 }
405 
406 void TxConfirmStats::Read(CAutoFile& filein, int nFileVersion, size_t numBuckets)
407 {
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;
412 
413  // The current version will store the decay with each individual TxConfirmStats and also keep a scale factor
414  filein >> decay;
415  if (decay <= 0 || decay >= 1) {
416  throw std::runtime_error("Corrupt estimates file. Decay must be between 0 and 1 (non-inclusive)");
417  }
418  filein >> scale;
419  if (scale == 0) {
420  throw std::runtime_error("Corrupt estimates file. Scale must be non-zero");
421  }
422 
423  filein >> avg;
424  if (avg.size() != numBuckets) {
425  throw std::runtime_error("Corrupt estimates file. Mismatch in feerate average bucket count");
426  }
427  filein >> txCtAvg;
428  if (txCtAvg.size() != numBuckets) {
429  throw std::runtime_error("Corrupt estimates file. Mismatch in tx count bucket count");
430  }
431  filein >> confAvg;
432  maxPeriods = confAvg.size();
433  maxConfirms = scale * maxPeriods;
434 
435  if (maxConfirms <= 0 || maxConfirms > 6 * 24 * 7) { // one week
436  throw std::runtime_error("Corrupt estimates file. Must maintain estimates for between 1 and 1008 (one week) confirms");
437  }
438  for (unsigned int i = 0; i < maxPeriods; i++) {
439  if (confAvg[i].size() != numBuckets) {
440  throw std::runtime_error("Corrupt estimates file. Mismatch in feerate conf average bucket count");
441  }
442  }
443 
444  filein >> failAvg;
445  if (maxPeriods != failAvg.size()) {
446  throw std::runtime_error("Corrupt estimates file. Mismatch in confirms tracked for failures");
447  }
448  for (unsigned int i = 0; i < maxPeriods; i++) {
449  if (failAvg[i].size() != numBuckets) {
450  throw std::runtime_error("Corrupt estimates file. Mismatch in one of failure average bucket counts");
451  }
452  }
453 
454  // Resize the current block variables which aren't stored in the data file
455  // to match the number of confirms and buckets
456  resizeInMemoryCounters(numBuckets);
457 
458  LogPrint(BCLog::ESTIMATEFEE, "Reading estimates: %u buckets counting confirms up to %u blocks\n",
459  numBuckets, maxConfirms);
460 }
461 
462 unsigned int TxConfirmStats::NewTx(unsigned int nBlockHeight, double val)
463 {
464  unsigned int bucketindex = bucketMap.lower_bound(val)->second;
465  unsigned int blockIndex = nBlockHeight % unconfTxs.size();
466  unconfTxs[blockIndex][bucketindex]++;
467  return bucketindex;
468 }
469 
470 void TxConfirmStats::removeTx(unsigned int entryHeight, unsigned int nBestSeenHeight, unsigned int bucketindex, bool inBlock)
471 {
472  //nBestSeenHeight is not updated yet for the new block
473  int blocksAgo = nBestSeenHeight - entryHeight;
474  if (nBestSeenHeight == 0) // the BlockPolicyEstimator hasn't seen any blocks yet
475  blocksAgo = 0;
476  if (blocksAgo < 0) {
477  LogPrint(BCLog::ESTIMATEFEE, "Blockpolicy error, blocks ago is negative for mempool tx\n");
478  return; //This can't happen because we call this with our best seen height, no entries can have higher
479  }
480 
481  if (blocksAgo >= (int)unconfTxs.size()) {
482  if (oldUnconfTxs[bucketindex] > 0) {
483  oldUnconfTxs[bucketindex]--;
484  } else {
485  LogPrint(BCLog::ESTIMATEFEE, "Blockpolicy error, mempool tx removed from >25 blocks,bucketIndex=%u already\n",
486  bucketindex);
487  }
488  }
489  else {
490  unsigned int blockIndex = entryHeight % unconfTxs.size();
491  if (unconfTxs[blockIndex][bucketindex] > 0) {
492  unconfTxs[blockIndex][bucketindex]--;
493  } else {
494  LogPrint(BCLog::ESTIMATEFEE, "Blockpolicy error, mempool tx removed from blockIndex=%u,bucketIndex=%u already\n",
495  blockIndex, bucketindex);
496  }
497  }
498  if (!inBlock && (unsigned int)blocksAgo >= scale) { // Only counts as a failure if not confirmed for entire period
499  assert(scale != 0);
500  unsigned int periodsAgo = blocksAgo / scale;
501  for (size_t i = 0; i < periodsAgo && i < failAvg.size(); i++) {
502  failAvg[i][bucketindex]++;
503  }
504  }
505 }
506 
507 // This function is called from CTxMemPool::removeUnchecked to ensure
508 // txs removed from the mempool for any reason are no longer
509 // tracked. Txs that were part of a block have already been removed in
510 // processBlockTx to ensure they are never double tracked, but it is
511 // of no harm to try to remove them again.
512 bool CBlockPolicyEstimator::removeTx(uint256 hash, bool inBlock)
513 {
515  std::map<uint256, TxStatsInfo>::iterator pos = mapMemPoolTxs.find(hash);
516  if (pos != mapMemPoolTxs.end()) {
517  feeStats->removeTx(pos->second.blockHeight, nBestSeenHeight, pos->second.bucketIndex, inBlock);
518  shortStats->removeTx(pos->second.blockHeight, nBestSeenHeight, pos->second.bucketIndex, inBlock);
519  longStats->removeTx(pos->second.blockHeight, nBestSeenHeight, pos->second.bucketIndex, inBlock);
520  mapMemPoolTxs.erase(hash);
521  return true;
522  } else {
523  return false;
524  }
525 }
526 
528  : nBestSeenHeight(0), firstRecordedHeight(0), historicalFirst(0), historicalBest(0), trackedTxs(0), untrackedTxs(0)
529 {
530  static_assert(MIN_BUCKET_FEERATE > 0, "Min feerate must be nonzero");
531  size_t bucketIndex = 0;
532  for (double bucketBoundary = MIN_BUCKET_FEERATE; bucketBoundary <= MAX_BUCKET_FEERATE; bucketBoundary *= FEE_SPACING, bucketIndex++) {
533  buckets.push_back(bucketBoundary);
534  bucketMap[bucketBoundary] = bucketIndex;
535  }
536  buckets.push_back(INF_FEERATE);
537  bucketMap[INF_FEERATE] = bucketIndex;
538  assert(bucketMap.size() == buckets.size());
539 
540  feeStats = std::unique_ptr<TxConfirmStats>(new TxConfirmStats(buckets, bucketMap, MED_BLOCK_PERIODS, MED_DECAY, MED_SCALE));
541  shortStats = std::unique_ptr<TxConfirmStats>(new TxConfirmStats(buckets, bucketMap, SHORT_BLOCK_PERIODS, SHORT_DECAY, SHORT_SCALE));
542  longStats = std::unique_ptr<TxConfirmStats>(new TxConfirmStats(buckets, bucketMap, LONG_BLOCK_PERIODS, LONG_DECAY, LONG_SCALE));
543 }
544 
546 {
547 }
548 
549 void CBlockPolicyEstimator::processTransaction(const CTxMemPoolEntry& entry, bool validFeeEstimate)
550 {
552  unsigned int txHeight = entry.GetHeight();
553  uint256 hash = entry.GetTx().GetHash();
554  if (mapMemPoolTxs.count(hash)) {
555  LogPrint(BCLog::ESTIMATEFEE, "Blockpolicy error mempool tx %s already being tracked\n", hash.ToString());
556  return;
557  }
558 
559  if (txHeight != nBestSeenHeight) {
560  // Ignore side chains and re-orgs; assuming they are random they don't
561  // affect the estimate. We'll potentially double count transactions in 1-block reorgs.
562  // Ignore txs if BlockPolicyEstimator is not in sync with chainActive.Tip().
563  // It will be synced next time a block is processed.
564  return;
565  }
566 
567  // Only want to be updating estimates when our blockchain is synced,
568  // otherwise we'll miscalculate how many blocks its taking to get included.
569  if (!validFeeEstimate) {
570  untrackedTxs++;
571  return;
572  }
573  trackedTxs++;
574 
575  // Feerates are stored and reported as BTC-per-kb:
576  CFeeRate feeRate(entry.GetFee(), entry.GetTxSize());
577 
578  mapMemPoolTxs[hash].blockHeight = txHeight;
579  unsigned int bucketIndex = feeStats->NewTx(txHeight, (double)feeRate.GetFeePerK());
580  mapMemPoolTxs[hash].bucketIndex = bucketIndex;
581  unsigned int bucketIndex2 = shortStats->NewTx(txHeight, (double)feeRate.GetFeePerK());
582  assert(bucketIndex == bucketIndex2);
583  unsigned int bucketIndex3 = longStats->NewTx(txHeight, (double)feeRate.GetFeePerK());
584  assert(bucketIndex == bucketIndex3);
585 }
586 
587 bool CBlockPolicyEstimator::processBlockTx(unsigned int nBlockHeight, const CTxMemPoolEntry* entry)
588 {
589  if (!removeTx(entry->GetTx().GetHash(), true)) {
590  // This transaction wasn't being tracked for fee estimation
591  return false;
592  }
593 
594  // How many blocks did it take for miners to include this transaction?
595  // blocksToConfirm is 1-based, so a transaction included in the earliest
596  // possible block has confirmation count of 1
597  int blocksToConfirm = nBlockHeight - entry->GetHeight();
598  if (blocksToConfirm <= 0) {
599  // This can't happen because we don't process transactions from a block with a height
600  // lower than our greatest seen height
601  LogPrint(BCLog::ESTIMATEFEE, "Blockpolicy error Transaction had negative blocksToConfirm\n");
602  return false;
603  }
604 
605  // Feerates are stored and reported as BTC-per-kb:
606  CFeeRate feeRate(entry->GetFee(), entry->GetTxSize());
607 
608  feeStats->Record(blocksToConfirm, (double)feeRate.GetFeePerK());
609  shortStats->Record(blocksToConfirm, (double)feeRate.GetFeePerK());
610  longStats->Record(blocksToConfirm, (double)feeRate.GetFeePerK());
611  return true;
612 }
613 
614 void CBlockPolicyEstimator::processBlock(unsigned int nBlockHeight,
615  std::vector<const CTxMemPoolEntry*>& entries)
616 {
618  if (nBlockHeight <= nBestSeenHeight) {
619  // Ignore side chains and re-orgs; assuming they are random
620  // they don't affect the estimate.
621  // And if an attacker can re-org the chain at will, then
622  // you've got much bigger problems than "attacker can influence
623  // transaction fees."
624  return;
625  }
626 
627  // Must update nBestSeenHeight in sync with ClearCurrent so that
628  // calls to removeTx (via processBlockTx) correctly calculate age
629  // of unconfirmed txs to remove from tracking.
630  nBestSeenHeight = nBlockHeight;
631 
632  // Update unconfirmed circular buffer
633  feeStats->ClearCurrent(nBlockHeight);
634  shortStats->ClearCurrent(nBlockHeight);
635  longStats->ClearCurrent(nBlockHeight);
636 
637  // Decay all exponential averages
638  feeStats->UpdateMovingAverages();
639  shortStats->UpdateMovingAverages();
640  longStats->UpdateMovingAverages();
641 
642  unsigned int countedTxs = 0;
643  // Update averages with data points from current block
644  for (const auto& entry : entries) {
645  if (processBlockTx(nBlockHeight, entry))
646  countedTxs++;
647  }
648 
649  if (firstRecordedHeight == 0 && countedTxs > 0) {
651  LogPrint(BCLog::ESTIMATEFEE, "Blockpolicy first recorded height %u\n", firstRecordedHeight);
652  }
653 
654 
655  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",
656  countedTxs, entries.size(), trackedTxs, trackedTxs + untrackedTxs, mapMemPoolTxs.size(),
657  MaxUsableEstimate(), HistoricalBlockSpan() > BlockSpan() ? "historical" : "current");
658 
659  trackedTxs = 0;
660  untrackedTxs = 0;
661 }
662 
664 {
665  // It's not possible to get reasonable estimates for confTarget of 1
666  if (confTarget <= 1)
667  return CFeeRate(0);
668 
670 }
671 
672 CFeeRate CBlockPolicyEstimator::estimateRawFee(int confTarget, double successThreshold, FeeEstimateHorizon horizon, EstimationResult* result) const
673 {
674  TxConfirmStats* stats;
675  double sufficientTxs = SUFFICIENT_FEETXS;
676  switch (horizon) {
678  stats = shortStats.get();
679  sufficientTxs = SUFFICIENT_TXS_SHORT;
680  break;
681  }
683  stats = feeStats.get();
684  break;
685  }
687  stats = longStats.get();
688  break;
689  }
690  default: {
691  throw std::out_of_range("CBlockPolicyEstimator::estimateRawFee unknown FeeEstimateHorizon");
692  }
693  }
694 
696  // Return failure if trying to analyze a target we're not tracking
697  if (confTarget <= 0 || (unsigned int)confTarget > stats->GetMaxConfirms())
698  return CFeeRate(0);
699  if (successThreshold > 1)
700  return CFeeRate(0);
701 
702  double median = stats->EstimateMedianVal(confTarget, sufficientTxs, successThreshold, true, nBestSeenHeight, result);
703 
704  if (median < 0)
705  return CFeeRate(0);
706 
707  return CFeeRate(llround(median));
708 }
709 
711 {
712  switch (horizon) {
714  return shortStats->GetMaxConfirms();
715  }
717  return feeStats->GetMaxConfirms();
718  }
720  return longStats->GetMaxConfirms();
721  }
722  default: {
723  throw std::out_of_range("CBlockPolicyEstimator::HighestTargetTracked unknown FeeEstimateHorizon");
724  }
725  }
726 }
727 
729 {
730  if (firstRecordedHeight == 0) return 0;
732 
734 }
735 
737 {
738  if (historicalFirst == 0) return 0;
739  assert(historicalBest >= historicalFirst);
740 
742 
744 }
745 
747 {
748  // Block spans are divided by 2 to make sure there are enough potential failing data points for the estimate
749  return std::min(longStats->GetMaxConfirms(), std::max(BlockSpan(), HistoricalBlockSpan()) / 2);
750 }
751 
756 double CBlockPolicyEstimator::estimateCombinedFee(unsigned int confTarget, double successThreshold, bool checkShorterHorizon, EstimationResult *result) const
757 {
758  double estimate = -1;
759  if (confTarget >= 1 && confTarget <= longStats->GetMaxConfirms()) {
760  // Find estimate from shortest time horizon possible
761  if (confTarget <= shortStats->GetMaxConfirms()) { // short horizon
762  estimate = shortStats->EstimateMedianVal(confTarget, SUFFICIENT_TXS_SHORT, successThreshold, true, nBestSeenHeight, result);
763  }
764  else if (confTarget <= feeStats->GetMaxConfirms()) { // medium horizon
765  estimate = feeStats->EstimateMedianVal(confTarget, SUFFICIENT_FEETXS, successThreshold, true, nBestSeenHeight, result);
766  }
767  else { // long horizon
768  estimate = longStats->EstimateMedianVal(confTarget, SUFFICIENT_FEETXS, successThreshold, true, nBestSeenHeight, result);
769  }
770  if (checkShorterHorizon) {
771  EstimationResult tempResult;
772  // If a lower confTarget from a more recent horizon returns a lower answer use it.
773  if (confTarget > feeStats->GetMaxConfirms()) {
774  double medMax = feeStats->EstimateMedianVal(feeStats->GetMaxConfirms(), SUFFICIENT_FEETXS, successThreshold, true, nBestSeenHeight, &tempResult);
775  if (medMax > 0 && (estimate == -1 || medMax < estimate)) {
776  estimate = medMax;
777  if (result) *result = tempResult;
778  }
779  }
780  if (confTarget > shortStats->GetMaxConfirms()) {
781  double shortMax = shortStats->EstimateMedianVal(shortStats->GetMaxConfirms(), SUFFICIENT_TXS_SHORT, successThreshold, true, nBestSeenHeight, &tempResult);
782  if (shortMax > 0 && (estimate == -1 || shortMax < estimate)) {
783  estimate = shortMax;
784  if (result) *result = tempResult;
785  }
786  }
787  }
788  }
789  return estimate;
790 }
791 
795 double CBlockPolicyEstimator::estimateConservativeFee(unsigned int doubleTarget, EstimationResult *result) const
796 {
797  double estimate = -1;
798  EstimationResult tempResult;
799  if (doubleTarget <= shortStats->GetMaxConfirms()) {
800  estimate = feeStats->EstimateMedianVal(doubleTarget, SUFFICIENT_FEETXS, DOUBLE_SUCCESS_PCT, true, nBestSeenHeight, result);
801  }
802  if (doubleTarget <= feeStats->GetMaxConfirms()) {
803  double longEstimate = longStats->EstimateMedianVal(doubleTarget, SUFFICIENT_FEETXS, DOUBLE_SUCCESS_PCT, true, nBestSeenHeight, &tempResult);
804  if (longEstimate > estimate) {
805  estimate = longEstimate;
806  if (result) *result = tempResult;
807  }
808  }
809  return estimate;
810 }
811 
819 CFeeRate CBlockPolicyEstimator::estimateSmartFee(int confTarget, FeeCalculation *feeCalc, bool conservative) const
820 {
822 
823  if (feeCalc) {
824  feeCalc->desiredTarget = confTarget;
825  feeCalc->returnedTarget = confTarget;
826  }
827 
828  double median = -1;
829  EstimationResult tempResult;
830 
831  // Return failure if trying to analyze a target we're not tracking
832  if (confTarget <= 0 || (unsigned int)confTarget > longStats->GetMaxConfirms()) {
833  return CFeeRate(0); // error condition
834  }
835 
836  // It's not possible to get reasonable estimates for confTarget of 1
837  if (confTarget == 1) confTarget = 2;
838 
839  unsigned int maxUsableEstimate = MaxUsableEstimate();
840  if ((unsigned int)confTarget > maxUsableEstimate) {
841  confTarget = maxUsableEstimate;
842  }
843  if (feeCalc) feeCalc->returnedTarget = confTarget;
844 
845  if (confTarget <= 1) return CFeeRate(0); // error condition
846 
847  assert(confTarget > 0); //estimateCombinedFee and estimateConservativeFee take unsigned ints
858  double halfEst = estimateCombinedFee(confTarget/2, HALF_SUCCESS_PCT, true, &tempResult);
859  if (feeCalc) {
860  feeCalc->est = tempResult;
861  feeCalc->reason = FeeReason::HALF_ESTIMATE;
862  }
863  median = halfEst;
864  double actualEst = estimateCombinedFee(confTarget, SUCCESS_PCT, true, &tempResult);
865  if (actualEst > median) {
866  median = actualEst;
867  if (feeCalc) {
868  feeCalc->est = tempResult;
869  feeCalc->reason = FeeReason::FULL_ESTIMATE;
870  }
871  }
872  double doubleEst = estimateCombinedFee(2 * confTarget, DOUBLE_SUCCESS_PCT, !conservative, &tempResult);
873  if (doubleEst > median) {
874  median = doubleEst;
875  if (feeCalc) {
876  feeCalc->est = tempResult;
878  }
879  }
880 
881  if (conservative || median == -1) {
882  double consEst = estimateConservativeFee(2 * confTarget, &tempResult);
883  if (consEst > median) {
884  median = consEst;
885  if (feeCalc) {
886  feeCalc->est = tempResult;
887  feeCalc->reason = FeeReason::CONSERVATIVE;
888  }
889  }
890  }
891 
892  if (median < 0) return CFeeRate(0); // error condition
893 
894  return CFeeRate(llround(median));
895 }
896 
897 
899 {
900  try {
902  fileout << 140100; // version required to read: 0.14.1 or later
903  fileout << CLIENT_VERSION; // version that wrote the file
905  if (BlockSpan() > HistoricalBlockSpan()/2) {
907  }
908  else {
910  }
911  fileout << buckets;
912  feeStats->Write(fileout);
913  shortStats->Write(fileout);
914  longStats->Write(fileout);
915  }
916  catch (const std::exception&) {
917  LogPrintf("CBlockPolicyEstimator::Write(): unable to write policy estimator data (non-fatal)\n");
918  return false;
919  }
920  return true;
921 }
922 
924 {
925  try {
927  int nVersionRequired, nVersionThatWrote;
928  unsigned int nFileBestSeenHeight, nFileHistoricalFirst, nFileHistoricalBest;
929  filein >> nVersionRequired >> nVersionThatWrote;
930  if (nVersionRequired > CLIENT_VERSION)
931  return error("CBlockPolicyEstimator::Read(): up-version (%d) fee estimate file", nVersionRequired);
932 
933  // Read fee estimates file into temporary variables so existing data
934  // structures aren't corrupted if there is an exception.
935  filein >> nFileBestSeenHeight;
936 
937  if (nVersionRequired < 140100) {
938  LogPrintf("%s: incompatible old fee estimation data (non-fatal). Version: %d\n", __func__, nVersionRequired);
939  } else { // New format introduced in 140100
940  unsigned int nFileHistoricalFirst, nFileHistoricalBest;
941  filein >> nFileHistoricalFirst >> nFileHistoricalBest;
942  if (nFileHistoricalFirst > nFileHistoricalBest || nFileHistoricalBest > nFileBestSeenHeight) {
943  throw std::runtime_error("Corrupt estimates file. Historical block range for estimates is invalid");
944  }
945  std::vector<double> fileBuckets;
946  filein >> fileBuckets;
947  size_t numBuckets = fileBuckets.size();
948  if (numBuckets <= 1 || numBuckets > 1000)
949  throw std::runtime_error("Corrupt estimates file. Must have between 2 and 1000 feerate buckets");
950 
951  std::unique_ptr<TxConfirmStats> fileFeeStats(new TxConfirmStats(buckets, bucketMap, MED_BLOCK_PERIODS, MED_DECAY, MED_SCALE));
952  std::unique_ptr<TxConfirmStats> fileShortStats(new TxConfirmStats(buckets, bucketMap, SHORT_BLOCK_PERIODS, SHORT_DECAY, SHORT_SCALE));
953  std::unique_ptr<TxConfirmStats> fileLongStats(new TxConfirmStats(buckets, bucketMap, LONG_BLOCK_PERIODS, LONG_DECAY, LONG_SCALE));
954  fileFeeStats->Read(filein, nVersionThatWrote, numBuckets);
955  fileShortStats->Read(filein, nVersionThatWrote, numBuckets);
956  fileLongStats->Read(filein, nVersionThatWrote, numBuckets);
957 
958  // Fee estimates file parsed correctly
959  // Copy buckets from file and refresh our bucketmap
960  buckets = fileBuckets;
961  bucketMap.clear();
962  for (unsigned int i = 0; i < buckets.size(); i++) {
963  bucketMap[buckets[i]] = i;
964  }
965 
966  // Destroy old TxConfirmStats and point to new ones that already reference buckets and bucketMap
967  feeStats = std::move(fileFeeStats);
968  shortStats = std::move(fileShortStats);
969  longStats = std::move(fileLongStats);
970 
971  nBestSeenHeight = nFileBestSeenHeight;
972  historicalFirst = nFileHistoricalFirst;
973  historicalBest = nFileHistoricalBest;
974  }
975  }
976  catch (const std::exception& e) {
977  LogPrintf("CBlockPolicyEstimator::Read(): unable to read policy estimator data (non-fatal): %s\n",e.what());
978  return false;
979  }
980  return true;
981 }
982 
984  int64_t startclear = GetTimeMicros();
985  std::vector<uint256> txids;
986  pool.queryHashes(txids);
988  for (auto& txid : txids) {
989  removeTx(txid, false);
990  }
991  int64_t endclear = GetTimeMicros();
992  LogPrint(BCLog::ESTIMATEFEE, "Recorded %u unconfirmed txs from mempool in %ld micros\n",txids.size(), endclear - startclear);
993 }
static constexpr double MED_DECAY
Decay of .998 is a half-life of 144 blocks or about 6 hours.
Definition: fees.h:156
EstimatorBucket pass
Definition: fees.h:119
std::vector< std::vector< double > > failAvg
Definition: fees.cpp:90
EstimationResult est
Definition: fees.h:127
bool FeeModeFromString(const std::string &mode_string, FeeEstimateMode &fee_estimate_mode)
Definition: fees.cpp:50
int returnedTarget
Definition: fees.h:130
CCriticalSection cs_feeEstimator
Definition: fees.h:259
static constexpr double MAX_BUCKET_FEERATE
Definition: fees.h:180
static constexpr double HALF_SUCCESS_PCT
Require greater than 60% of X feerate transactions to be confirmed within Y/2 blocks.
Definition: fees.h:161
size_t GetTxSize() const
Definition: txmempool.h:105
unsigned int firstRecordedHeight
Definition: fees.h:234
static constexpr unsigned int MED_BLOCK_PERIODS
Track confirm delays up to 48 blocks for medium horizon.
Definition: fees.h:145
double start
Definition: fees.h:108
bool removeTx(uint256 hash, bool inBlock)
Remove a transaction from the mempool tracking stats.
Definition: fees.cpp:512
CBlockPolicyEstimator()
Create new BlockPolicyEstimator and initialize stats tracking classes with default values...
Definition: fees.cpp:527
TxConfirmStats(const std::vector< double > &defaultBuckets, const std::map< double, unsigned int > &defaultBucketMap, unsigned int maxPeriods, double decay, unsigned int scale)
Create new TxConfirmStats.
Definition: fees.cpp:175
static FILE * fileout
We use boost::call_once() to make sure mutexDebugLog and vMsgsBeforeOpenLog are initialized in a thre...
Definition: util.cpp:192
bool Write(CAutoFile &fileout) const
Write estimation data to a file.
Definition: fees.cpp:898
FeeEstimateMode
Definition: fees.h:97
std::vector< double > avg
Definition: fees.cpp:94
FeeReason reason
Definition: fees.h:128
We will instantiate an instance of this class to track transactions that were included in a block...
Definition: fees.cpp:72
std::map< double, unsigned int > bucketMap
Definition: fees.h:257
std::unique_ptr< TxConfirmStats > shortStats
Definition: fees.h:250
std::string StringForFeeReason(FeeReason reason)
Definition: fees.cpp:30
std::string StringForFeeEstimateHorizon(FeeEstimateHorizon horizon)
Definition: fees.cpp:17
std::unique_ptr< TxConfirmStats > longStats
Definition: fees.h:251
static constexpr double DOUBLE_SUCCESS_PCT
Require greater than 95% of X feerate transactions to be confirmed within 2 * Y blocks.
Definition: fees.h:165
void queryHashes(std::vector< uint256 > &vtxid)
Definition: txmempool.cpp:1180
static constexpr double FEE_SPACING
Spacing of FeeRate buckets We have to lump transactions into buckets based on feerate, but we want to be able to give accurate estimates over a large range of potential feerates Therefore it makes sense to exponentially space the buckets.
Definition: fees.h:187
int64_t GetTimeMicros()
Returns the system time (not mockable)
Definition: utiltime.cpp:63
unsigned int nBestSeenHeight
Definition: fees.h:233
double decay
Definition: fees.cpp:99
void Record(int blocksToConfirm, double val)
Record a new transaction data point in the current block stats.
Definition: fees.cpp:217
static constexpr double MIN_BUCKET_FEERATE
Minimum and Maximum values for tracking feerates The MIN_BUCKET_FEERATE should just be set to the low...
Definition: fees.h:179
double withinTarget
Definition: fees.h:110
void resizeInMemoryCounters(size_t newbuckets)
Definition: fees.cpp:198
unsigned int MaxUsableEstimate() const
Calculation of highest target that reasonable estimate can be provided for.
Definition: fees.cpp:746
void ClearCurrent(unsigned int nBlockHeight)
Roll the circular buffer for unconfirmed txs.
Definition: fees.cpp:208
int desiredTarget
Definition: fees.h:129
static constexpr double SUFFICIENT_TXS_SHORT
Require an avg of 0.5 tx when using short decay since there are fewer blocks considered.
Definition: fees.h:170
CTxMemPoolEntry stores data about the corresponding transaction, as well as data about all in-mempool...
Definition: txmempool.h:69
Force estimateSmartFee to use non-conservative estimates.
static constexpr double SUCCESS_PCT
Require greater than 85% of X feerate transactions to be confirmed within Y blocks.
Definition: fees.h:163
void Read(CAutoFile &filein, int nFileVersion, size_t numBuckets)
Read saved state of estimation data from a file and replace all internal data structures and variable...
Definition: fees.cpp:406
std::unique_ptr< TxConfirmStats > feeStats
Classes to track historical data on transaction confirmations.
Definition: fees.h:249
const std::map< double, unsigned int > & bucketMap
Definition: fees.cpp:77
static constexpr unsigned int SHORT_SCALE
Definition: fees.h:143
static constexpr double LONG_DECAY
Decay of .9995 is a half-life of 1008 blocks or about 2 days.
Definition: fees.h:158
#define LogPrintf(...)
Definition: util.h:203
std::vector< std::vector< double > > confAvg
Definition: fees.cpp:86
unsigned int NewTx(unsigned int nBlockHeight, double val)
Record a new transaction entering the mempool.
Definition: fees.cpp:462
unsigned int GetHeight() const
Definition: txmempool.h:107
unsigned int HistoricalBlockSpan() const
Number of blocks of recorded fee estimate data represented in saved data file.
Definition: fees.cpp:736
double end
Definition: fees.h:109
EstimatorBucket fail
Definition: fees.h:120
CFeeRate estimateRawFee(int confTarget, double successThreshold, FeeEstimateHorizon horizon, EstimationResult *result=nullptr) const
Return a specific fee estimate calculation with a given success threshold and time horizon...
Definition: fees.cpp:672
#define LOCK(cs)
Definition: sync.h:178
void removeTx(unsigned int entryHeight, unsigned int nBestSeenHeight, unsigned int bucketIndex, bool inBlock)
Remove a transaction from mempool tracking stats.
Definition: fees.cpp:470
const uint256 & GetHash() const
Definition: transaction.h:256
const CAmount & GetFee() const
Definition: txmempool.h:104
CFeeRate estimateSmartFee(int confTarget, FeeCalculation *feeCalc, bool conservative) const
Estimate feerate needed to get be included in a block within confTarget blocks.
Definition: fees.cpp:819
unsigned int scale
Definition: fees.cpp:102
unsigned int historicalFirst
Definition: fees.h:235
void FlushUnconfirmed(CTxMemPool &pool)
Empty mempool transactions on shutdown to record failure to confirm for txs still in mempool...
Definition: fees.cpp:983
double estimateConservativeFee(unsigned int doubleTarget, EstimationResult *result) const
Helper for estimateSmartFee.
Definition: fees.cpp:795
unsigned int trackedTxs
Definition: fees.h:253
const std::vector< double > & buckets
Definition: fees.cpp:76
double inMempool
Definition: fees.h:112
unsigned int BlockSpan() const
Number of blocks of data recorded while fee estimates have been running.
Definition: fees.cpp:728
FeeReason
Definition: fees.h:81
std::string ToString() const
Definition: uint256.cpp:62
std::map< uint256, TxStatsInfo > mapMemPoolTxs
Definition: fees.h:246
CFeeRate estimateFee(int confTarget) const
DEPRECATED.
Definition: fees.cpp:663
static constexpr unsigned int LONG_SCALE
Definition: fees.h:149
double estimateCombinedFee(unsigned int confTarget, double successThreshold, bool checkShorterHorizon, EstimationResult *result) const
Helper for estimateSmartFee.
Definition: fees.cpp:756
#define LogPrint(category,...)
Definition: util.h:214
FeeEstimateHorizon
Definition: fees.h:72
std::vector< std::vector< int > > unconfTxs
Definition: fees.cpp:107
unsigned int HighestTargetTracked(FeeEstimateHorizon horizon) const
Calculation of highest target that estimates are tracked for.
Definition: fees.cpp:710
256-bit opaque blob.
Definition: uint256.h:123
static constexpr unsigned int MED_SCALE
Definition: fees.h:146
static const unsigned int OLDEST_ESTIMATE_HISTORY
Historical estimates that are older than this aren&#39;t valid.
Definition: fees.h:151
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:442
std::vector< int > oldUnconfTxs
Definition: fees.cpp:109
void processBlock(unsigned int nBlockHeight, std::vector< const CTxMemPoolEntry *> &entries)
Process all the transactions that have been included in a block.
Definition: fees.cpp:614
const CTransaction & GetTx() const
Definition: txmempool.h:102
bool Read(CAutoFile &filein)
Read estimation data from a file.
Definition: fees.cpp:923
unsigned int historicalBest
Definition: fees.h:236
double leftMempool
Definition: fees.h:113
unsigned int GetMaxConfirms() const
Return the max number of confirms we&#39;re tracking.
Definition: fees.cpp:162
static constexpr unsigned int LONG_BLOCK_PERIODS
Track confirm delays up to 1008 blocks for long horizon.
Definition: fees.h:148
Fee rate in satoshis per kilobyte: CAmount / kB.
Definition: feerate.h:19
bool error(const char *fmt, const Args &... args)
Definition: util.h:222
std::vector< double > buckets
Definition: fees.h:256
static constexpr unsigned int SHORT_BLOCK_PERIODS
Track confirm delays up to 12 blocks for short horizon.
Definition: fees.h:142
static constexpr double INF_FEERATE
Definition: fees.cpp:15
double totalConfirmed
Definition: fees.h:111
static constexpr double SUFFICIENT_FEETXS
Require an avg of 0.1 tx in the combined feerate bucket per block to have stat significance.
Definition: fees.h:168
bool processBlockTx(unsigned int nBlockHeight, const CTxMemPoolEntry *entry)
Process a transaction confirmed in a block.
Definition: fees.cpp:587
Use default settings based on other criteria.
static constexpr double SHORT_DECAY
Decay of .962 is a half-life of 18 blocks or about 45 minutes.
Definition: fees.h:154
double EstimateMedianVal(int confTarget, double sufficientTxVal, double minSuccess, bool requireGreater, unsigned int nBlockHeight, EstimationResult *result=nullptr) const
Calculate a feerate estimate.
Definition: fees.cpp:244
void Write(CAutoFile &fileout) const
Write state of estimation data to a file.
Definition: fees.cpp:396
std::vector< double > txCtAvg
Definition: fees.cpp:82
unsigned int untrackedTxs
Definition: fees.h:254
void UpdateMovingAverages()
Update our estimates by decaying our historical moving average and updating with the data gathered fr...
Definition: fees.cpp:231
static const int CLIENT_VERSION
dashd-res.rc includes this file, but it cannot cope with real c++ code.
Definition: clientversion.h:38
unsigned int scale
Definition: fees.h:122
Non-refcounted RAII wrapper for FILE*.
Definition: streams.h:410
void processTransaction(const CTxMemPoolEntry &entry, bool validFeeEstimate)
Process a transaction accepted to the mempool.
Definition: fees.cpp:549
double decay
Definition: fees.h:121
Released under the MIT license