Raven Core  3.0.0
P2P Digital Currency
fees.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 The Bitcoin Core developers
3 // Copyright (c) 2017-2019 The Raven Core developers
4 // Distributed under the MIT software license, see the accompanying
5 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 
7 #include "policy/fees.h"
8 #include "policy/policy.h"
9 
10 #include "amount.h"
11 #include "clientversion.h"
12 #include "primitives/transaction.h"
13 #include "random.h"
14 #include "streams.h"
15 #include "txmempool.h"
16 #include "util.h"
17 
18 static constexpr double INF_FEERATE = 1e99;
19 
21  static const std::map<FeeEstimateHorizon, std::string> horizon_strings = {
25  };
26  auto horizon_string = horizon_strings.find(horizon);
27 
28  if (horizon_string == horizon_strings.end()) return "unknown";
29 
30  return horizon_string->second;
31 }
32 
33 std::string StringForFeeReason(FeeReason reason) {
34  static const std::map<FeeReason, std::string> fee_reason_strings = {
35  {FeeReason::NONE, "None"},
36  {FeeReason::HALF_ESTIMATE, "Half Target 60% Threshold"},
37  {FeeReason::FULL_ESTIMATE, "Target 85% Threshold"},
38  {FeeReason::DOUBLE_ESTIMATE, "Double Target 95% Threshold"},
39  {FeeReason::CONSERVATIVE, "Conservative Double Target longer horizon"},
40  {FeeReason::MEMPOOL_MIN, "Mempool Min Fee"},
41  {FeeReason::PAYTXFEE, "PayTxFee set"},
42  {FeeReason::FALLBACK, "Fallback fee"},
43  {FeeReason::REQUIRED, "Minimum Required Fee"},
44  {FeeReason::MAXTXFEE, "MaxTxFee limit"}
45  };
46  auto reason_string = fee_reason_strings.find(reason);
47 
48  if (reason_string == fee_reason_strings.end()) return "Unknown";
49 
50  return reason_string->second;
51 }
52 
53 bool FeeModeFromString(const std::string& mode_string, FeeEstimateMode& fee_estimate_mode) {
54  static const std::map<std::string, FeeEstimateMode> fee_modes = {
55  {"UNSET", FeeEstimateMode::UNSET},
56  {"ECONOMICAL", FeeEstimateMode::ECONOMICAL},
57  {"CONSERVATIVE", FeeEstimateMode::CONSERVATIVE},
58  };
59  auto mode = fee_modes.find(mode_string);
60 
61  if (mode == fee_modes.end()) return false;
62 
63  fee_estimate_mode = mode->second;
64  return true;
65 }
66 
76 {
77 private:
78  //Define the buckets we will group transactions into
79  const std::vector<double>& buckets; // The upper-bound of the range for the bucket (inclusive)
80  const std::map<double, unsigned int>& bucketMap; // Map of bucket upper-bound to index into all vectors by bucket
81 
82  // For each bucket X:
83  // Count the total # of txs in each bucket
84  // Track the historical moving average of this total over blocks
85  std::vector<double> txCtAvg;
86 
87  // Count the total # of txs confirmed within Y blocks in each bucket
88  // Track the historical moving average of theses totals over blocks
89  std::vector<std::vector<double>> confAvg; // confAvg[Y][X]
90 
91  // Track moving avg of txs which have been evicted from the mempool
92  // after failing to be confirmed within Y blocks
93  std::vector<std::vector<double>> failAvg; // failAvg[Y][X]
94 
95  // Sum the total feerate of all tx's in each bucket
96  // Track the historical moving average of this total over blocks
97  std::vector<double> avg;
98 
99  // Combine the conf counts with tx counts to calculate the confirmation % for each Y,X
100  // Combine the total value with the tx counts to calculate the avg feerate per bucket
101 
102  double decay;
103 
104  // Resolution (# of blocks) with which confirmations are tracked
105  unsigned int scale;
106 
107  // Mempool counts of outstanding transactions
108  // For each bucket X, track the number of transactions in the mempool
109  // that are unconfirmed for each possible confirmation value Y
110  std::vector<std::vector<int> > unconfTxs; //unconfTxs[Y][X]
111  // transactions still unconfirmed after GetMaxConfirms for each bucket
112  std::vector<int> oldUnconfTxs;
113 
114  void resizeInMemoryCounters(size_t newbuckets);
115 
116 public:
124  TxConfirmStats(const std::vector<double>& defaultBuckets, const std::map<double, unsigned int>& defaultBucketMap,
125  unsigned int maxPeriods, double decay, unsigned int scale);
126 
128  void ClearCurrent(unsigned int nBlockHeight);
129 
136  void Record(int blocksToConfirm, double val);
137 
139  unsigned int NewTx(unsigned int nBlockHeight, double val);
140 
142  void removeTx(unsigned int entryHeight, unsigned int nBestSeenHeight,
143  unsigned int bucketIndex, bool inBlock);
144 
147  void UpdateMovingAverages();
148 
160  double EstimateMedianVal(int confTarget, double sufficientTxVal,
161  double minSuccess, bool requireGreater, unsigned int nBlockHeight,
162  EstimationResult *result = nullptr) const;
163 
165  unsigned int GetMaxConfirms() const { return scale * confAvg.size(); }
166 
168  void Write(CAutoFile& fileout) const;
169 
174  void Read(CAutoFile& filein, int nFileVersion, size_t numBuckets);
175 };
176 
177 
178 TxConfirmStats::TxConfirmStats(const std::vector<double>& defaultBuckets,
179  const std::map<double, unsigned int>& defaultBucketMap,
180  unsigned int maxPeriods, double _decay, unsigned int _scale)
181  : buckets(defaultBuckets), bucketMap(defaultBucketMap)
182 {
183  decay = _decay;
184  assert(_scale != 0 && "_scale must be non-zero");
185  scale = _scale;
186  confAvg.resize(maxPeriods);
187  for (unsigned int i = 0; i < maxPeriods; i++) {
188  confAvg[i].resize(buckets.size());
189  }
190  failAvg.resize(maxPeriods);
191  for (unsigned int i = 0; i < maxPeriods; i++) {
192  failAvg[i].resize(buckets.size());
193  }
194 
195  txCtAvg.resize(buckets.size());
196  avg.resize(buckets.size());
197 
199 }
200 
201 void TxConfirmStats::resizeInMemoryCounters(size_t newbuckets) {
202  // newbuckets must be passed in because the buckets referred to during Read have not been updated yet.
203  unconfTxs.resize(GetMaxConfirms());
204  for (unsigned int i = 0; i < unconfTxs.size(); i++) {
205  unconfTxs[i].resize(newbuckets);
206  }
207  oldUnconfTxs.resize(newbuckets);
208 }
209 
210 // Roll the unconfirmed txs circular buffer
211 void TxConfirmStats::ClearCurrent(unsigned int nBlockHeight)
212 {
213  for (unsigned int j = 0; j < buckets.size(); j++) {
214  oldUnconfTxs[j] += unconfTxs[nBlockHeight%unconfTxs.size()][j];
215  unconfTxs[nBlockHeight%unconfTxs.size()][j] = 0;
216  }
217 }
218 
219 
220 void TxConfirmStats::Record(int blocksToConfirm, double val)
221 {
222  // blocksToConfirm is 1-based
223  if (blocksToConfirm < 1)
224  return;
225  int periodsToConfirm = (blocksToConfirm + scale - 1)/scale;
226  unsigned int bucketindex = bucketMap.lower_bound(val)->second;
227  for (size_t i = periodsToConfirm; i <= confAvg.size(); i++) {
228  confAvg[i - 1][bucketindex]++;
229  }
230  txCtAvg[bucketindex]++;
231  avg[bucketindex] += val;
232 }
233 
235 {
236  for (unsigned int j = 0; j < buckets.size(); j++) {
237  for (unsigned int i = 0; i < confAvg.size(); i++)
238  confAvg[i][j] = confAvg[i][j] * decay;
239  for (unsigned int i = 0; i < failAvg.size(); i++)
240  failAvg[i][j] = failAvg[i][j] * decay;
241  avg[j] = avg[j] * decay;
242  txCtAvg[j] = txCtAvg[j] * decay;
243  }
244 }
245 
246 // returns -1 on error conditions
247 double TxConfirmStats::EstimateMedianVal(int confTarget, double sufficientTxVal,
248  double successBreakPoint, bool requireGreater,
249  unsigned int nBlockHeight, EstimationResult *result) const
250 {
251  // Counters for a bucket (or range of buckets)
252  double nConf = 0; // Number of tx's confirmed within the confTarget
253  double totalNum = 0; // Total number of tx's that were ever confirmed
254  int extraNum = 0; // Number of tx's still in mempool for confTarget or longer
255  double failNum = 0; // Number of tx's that were never confirmed but removed from the mempool after confTarget
256  int periodTarget = (confTarget + scale - 1)/scale;
257 
258  int maxbucketindex = buckets.size() - 1;
259 
260  // requireGreater means we are looking for the lowest feerate such that all higher
261  // values pass, so we start at maxbucketindex (highest feerate) and look at successively
262  // smaller buckets until we reach failure. Otherwise, we are looking for the highest
263  // feerate such that all lower values fail, and we go in the opposite direction.
264  unsigned int startbucket = requireGreater ? maxbucketindex : 0;
265  int step = requireGreater ? -1 : 1;
266 
267  // We'll combine buckets until we have enough samples.
268  // The near and far variables will define the range we've combined
269  // The best variables are the last range we saw which still had a high
270  // enough confirmation rate to count as success.
271  // The cur variables are the current range we're counting.
272  unsigned int curNearBucket = startbucket;
273  unsigned int bestNearBucket = startbucket;
274  unsigned int curFarBucket = startbucket;
275  unsigned int bestFarBucket = startbucket;
276 
277  bool foundAnswer = false;
278  unsigned int bins = unconfTxs.size();
279  bool newBucketRange = true;
280  bool passing = true;
281  EstimatorBucket passBucket;
282  EstimatorBucket failBucket;
283 
284  // Start counting from highest(default) or lowest feerate transactions
285  for (int bucket = startbucket; bucket >= 0 && bucket <= maxbucketindex; bucket += step) {
286  if (newBucketRange) {
287  curNearBucket = bucket;
288  newBucketRange = false;
289  }
290  curFarBucket = bucket;
291  nConf += confAvg[periodTarget - 1][bucket];
292  totalNum += txCtAvg[bucket];
293  failNum += failAvg[periodTarget - 1][bucket];
294  for (unsigned int confct = confTarget; confct < GetMaxConfirms(); confct++)
295  extraNum += unconfTxs[(nBlockHeight - confct)%bins][bucket];
296  extraNum += oldUnconfTxs[bucket];
297  // If we have enough transaction data points in this range of buckets,
298  // we can test for success
299  // (Only count the confirmed data points, so that each confirmation count
300  // will be looking at the same amount of data and same bucket breaks)
301  if (totalNum >= sufficientTxVal / (1 - decay)) {
302  double curPct = nConf / (totalNum + failNum + extraNum);
303 
304  // Check to see if we are no longer getting confirmed at the success rate
305  if ((requireGreater && curPct < successBreakPoint) || (!requireGreater && curPct > successBreakPoint)) {
306  if (passing == true) {
307  // First time we hit a failure record the failed bucket
308  unsigned int failMinBucket = std::min(curNearBucket, curFarBucket);
309  unsigned int failMaxBucket = std::max(curNearBucket, curFarBucket);
310  failBucket.start = failMinBucket ? buckets[failMinBucket - 1] : 0;
311  failBucket.end = buckets[failMaxBucket];
312  failBucket.withinTarget = nConf;
313  failBucket.totalConfirmed = totalNum;
314  failBucket.inMempool = extraNum;
315  failBucket.leftMempool = failNum;
316  passing = false;
317  }
318  continue;
319  }
320  // Otherwise update the cumulative stats, and the bucket variables
321  // and reset the counters
322  else {
323  failBucket = EstimatorBucket(); // Reset any failed bucket, currently passing
324  foundAnswer = true;
325  passing = true;
326  passBucket.withinTarget = nConf;
327  nConf = 0;
328  passBucket.totalConfirmed = totalNum;
329  totalNum = 0;
330  passBucket.inMempool = extraNum;
331  passBucket.leftMempool = failNum;
332  failNum = 0;
333  extraNum = 0;
334  bestNearBucket = curNearBucket;
335  bestFarBucket = curFarBucket;
336  newBucketRange = true;
337  }
338  }
339  }
340 
341  double median = -1;
342  double txSum = 0;
343 
344  // Calculate the "average" feerate of the best bucket range that met success conditions
345  // Find the bucket with the median transaction and then report the average feerate from that bucket
346  // This is a compromise between finding the median which we can't since we don't save all tx's
347  // and reporting the average which is less accurate
348  unsigned int minBucket = std::min(bestNearBucket, bestFarBucket);
349  unsigned int maxBucket = std::max(bestNearBucket, bestFarBucket);
350  for (unsigned int j = minBucket; j <= maxBucket; j++) {
351  txSum += txCtAvg[j];
352  }
353  if (foundAnswer && txSum != 0) {
354  txSum = txSum / 2;
355  for (unsigned int j = minBucket; j <= maxBucket; j++) {
356  if (txCtAvg[j] < txSum)
357  txSum -= txCtAvg[j];
358  else { // we're in the right bucket
359  median = avg[j] / txCtAvg[j];
360  break;
361  }
362  }
363 
364  passBucket.start = minBucket ? buckets[minBucket-1] : 0;
365  passBucket.end = buckets[maxBucket];
366  }
367 
368  // If we were passing until we reached last few buckets with insufficient data, then report those as failed
369  if (passing && !newBucketRange) {
370  unsigned int failMinBucket = std::min(curNearBucket, curFarBucket);
371  unsigned int failMaxBucket = std::max(curNearBucket, curFarBucket);
372  failBucket.start = failMinBucket ? buckets[failMinBucket - 1] : 0;
373  failBucket.end = buckets[failMaxBucket];
374  failBucket.withinTarget = nConf;
375  failBucket.totalConfirmed = totalNum;
376  failBucket.inMempool = extraNum;
377  failBucket.leftMempool = failNum;
378  }
379 
380  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",
381  confTarget, requireGreater ? ">" : "<", 100.0 * successBreakPoint, decay,
382  median, passBucket.start, passBucket.end,
383  100 * passBucket.withinTarget / (passBucket.totalConfirmed + passBucket.inMempool + passBucket.leftMempool),
384  passBucket.withinTarget, passBucket.totalConfirmed, passBucket.inMempool, passBucket.leftMempool,
385  failBucket.start, failBucket.end,
386  100 * failBucket.withinTarget / (failBucket.totalConfirmed + failBucket.inMempool + failBucket.leftMempool),
387  failBucket.withinTarget, failBucket.totalConfirmed, failBucket.inMempool, failBucket.leftMempool);
388 
389 
390  if (result) {
391  result->pass = passBucket;
392  result->fail = failBucket;
393  result->decay = decay;
394  result->scale = scale;
395  }
396  return median;
397 }
398 
399 void TxConfirmStats::Write(CAutoFile& fileout) const
400 {
401  fileout << decay;
402  fileout << scale;
403  fileout << avg;
404  fileout << txCtAvg;
405  fileout << confAvg;
406  fileout << failAvg;
407 }
408 
409 void TxConfirmStats::Read(CAutoFile& filein, int nFileVersion, size_t numBuckets)
410 {
411  // Read data file and do some very basic sanity checking
412  // buckets and bucketMap are not updated yet, so don't access them
413  // If there is a read failure, we'll just discard this entire object anyway
414  size_t maxConfirms, maxPeriods;
415 
416  // The current version will store the decay with each individual TxConfirmStats and also keep a scale factor
417  if (nFileVersion >= 149900) {
418  filein >> decay;
419  if (decay <= 0 || decay >= 1) {
420  throw std::runtime_error("Corrupt estimates file. Decay must be between 0 and 1 (non-inclusive)");
421  }
422  filein >> scale;
423  if (scale == 0) {
424  throw std::runtime_error("Corrupt estimates file. Scale must be non-zero");
425  }
426  }
427 
428  filein >> avg;
429  if (avg.size() != numBuckets) {
430  throw std::runtime_error("Corrupt estimates file. Mismatch in feerate average bucket count");
431  }
432  filein >> txCtAvg;
433  if (txCtAvg.size() != numBuckets) {
434  throw std::runtime_error("Corrupt estimates file. Mismatch in tx count bucket count");
435  }
436  filein >> confAvg;
437  maxPeriods = confAvg.size();
438  maxConfirms = scale * maxPeriods;
439 
440  if (maxConfirms <= 0 || maxConfirms > 6 * 24 * 7) { // one week
441  throw std::runtime_error("Corrupt estimates file. Must maintain estimates for between 1 and 1008 (one week) confirms");
442  }
443  for (unsigned int i = 0; i < maxPeriods; i++) {
444  if (confAvg[i].size() != numBuckets) {
445  throw std::runtime_error("Corrupt estimates file. Mismatch in feerate conf average bucket count");
446  }
447  }
448 
449  if (nFileVersion >= 149900) {
450  filein >> failAvg;
451  if (maxPeriods != failAvg.size()) {
452  throw std::runtime_error("Corrupt estimates file. Mismatch in confirms tracked for failures");
453  }
454  for (unsigned int i = 0; i < maxPeriods; i++) {
455  if (failAvg[i].size() != numBuckets) {
456  throw std::runtime_error("Corrupt estimates file. Mismatch in one of failure average bucket counts");
457  }
458  }
459  } else {
460  failAvg.resize(confAvg.size());
461  for (unsigned int i = 0; i < failAvg.size(); i++) {
462  failAvg[i].resize(numBuckets);
463  }
464  }
465 
466  // Resize the current block variables which aren't stored in the data file
467  // to match the number of confirms and buckets
468  resizeInMemoryCounters(numBuckets);
469 
470  LogPrint(BCLog::ESTIMATEFEE, "Reading estimates: %u buckets counting confirms up to %u blocks\n",
471  numBuckets, maxConfirms);
472 }
473 
474 unsigned int TxConfirmStats::NewTx(unsigned int nBlockHeight, double val)
475 {
476  unsigned int bucketindex = bucketMap.lower_bound(val)->second;
477  unsigned int blockIndex = nBlockHeight % unconfTxs.size();
478  unconfTxs[blockIndex][bucketindex]++;
479  return bucketindex;
480 }
481 
482 void TxConfirmStats::removeTx(unsigned int entryHeight, unsigned int nBestSeenHeight, unsigned int bucketindex, bool inBlock)
483 {
484  //nBestSeenHeight is not updated yet for the new block
485  int blocksAgo = nBestSeenHeight - entryHeight;
486  if (nBestSeenHeight == 0) // the BlockPolicyEstimator hasn't seen any blocks yet
487  blocksAgo = 0;
488  if (blocksAgo < 0) {
489  LogPrint(BCLog::ESTIMATEFEE, "Blockpolicy error, blocks ago is negative for mempool tx\n");
490  return; //This can't happen because we call this with our best seen height, no entries can have higher
491  }
492 
493  if (blocksAgo >= (int)unconfTxs.size()) {
494  if (oldUnconfTxs[bucketindex] > 0) {
495  oldUnconfTxs[bucketindex]--;
496  } else {
497  LogPrint(BCLog::ESTIMATEFEE, "Blockpolicy error, mempool tx removed from >25 blocks,bucketIndex=%u already\n",
498  bucketindex);
499  }
500  }
501  else {
502  unsigned int blockIndex = entryHeight % unconfTxs.size();
503  if (unconfTxs[blockIndex][bucketindex] > 0) {
504  unconfTxs[blockIndex][bucketindex]--;
505  } else {
506  LogPrint(BCLog::ESTIMATEFEE, "Blockpolicy error, mempool tx removed from blockIndex=%u,bucketIndex=%u already\n",
507  blockIndex, bucketindex);
508  }
509  }
510  if (!inBlock && (unsigned int)blocksAgo >= scale) { // Only counts as a failure if not confirmed for entire period
511  assert(scale != 0);
512  unsigned int periodsAgo = blocksAgo / scale;
513  for (size_t i = 0; i < periodsAgo && i < failAvg.size(); i++) {
514  failAvg[i][bucketindex]++;
515  }
516  }
517 }
518 
519 // This function is called from CTxMemPool::removeUnchecked to ensure
520 // txs removed from the mempool for any reason are no longer
521 // tracked. Txs that were part of a block have already been removed in
522 // processBlockTx to ensure they are never double tracked, but it is
523 // of no harm to try to remove them again.
524 bool CBlockPolicyEstimator::removeTx(uint256 hash, bool inBlock)
525 {
526  LOCK(cs_feeEstimator);
527  std::map<uint256, TxStatsInfo>::iterator pos = mapMemPoolTxs.find(hash);
528  if (pos != mapMemPoolTxs.end()) {
529  feeStats->removeTx(pos->second.blockHeight, nBestSeenHeight, pos->second.bucketIndex, inBlock);
530  shortStats->removeTx(pos->second.blockHeight, nBestSeenHeight, pos->second.bucketIndex, inBlock);
531  longStats->removeTx(pos->second.blockHeight, nBestSeenHeight, pos->second.bucketIndex, inBlock);
532  mapMemPoolTxs.erase(hash);
533  return true;
534  } else {
535  return false;
536  }
537 }
538 
540  : nBestSeenHeight(0), firstRecordedHeight(0), historicalFirst(0), historicalBest(0), trackedTxs(0), untrackedTxs(0)
541 {
542  static_assert(MIN_BUCKET_FEERATE > 0, "Min feerate must be nonzero");
543  size_t bucketIndex = 0;
544  for (double bucketBoundary = MIN_BUCKET_FEERATE; bucketBoundary <= MAX_BUCKET_FEERATE; bucketBoundary *= FEE_SPACING, bucketIndex++) {
545  buckets.push_back(bucketBoundary);
546  bucketMap[bucketBoundary] = bucketIndex;
547  }
548  buckets.push_back(INF_FEERATE);
549  bucketMap[INF_FEERATE] = bucketIndex;
550  assert(bucketMap.size() == buckets.size());
551 
555 }
556 
558 {
559  delete feeStats;
560  delete shortStats;
561  delete longStats;
562 }
563 
564 void CBlockPolicyEstimator::processTransaction(const CTxMemPoolEntry& entry, bool validFeeEstimate)
565 {
567  unsigned int txHeight = entry.GetHeight();
568  uint256 hash = entry.GetTx().GetHash();
569  if (mapMemPoolTxs.count(hash)) {
570  LogPrint(BCLog::ESTIMATEFEE, "Blockpolicy error mempool tx %s already being tracked\n",
571  hash.ToString().c_str());
572  return;
573  }
574 
575  if (txHeight != nBestSeenHeight) {
576  // Ignore side chains and re-orgs; assuming they are random they don't
577  // affect the estimate. We'll potentially double count transactions in 1-block reorgs.
578  // Ignore txs if BlockPolicyEstimator is not in sync with chainActive.Tip().
579  // It will be synced next time a block is processed.
580  return;
581  }
582 
583  // Only want to be updating estimates when our blockchain is synced,
584  // otherwise we'll miscalculate how many blocks its taking to get included.
585  if (!validFeeEstimate) {
586  untrackedTxs++;
587  return;
588  }
589  trackedTxs++;
590 
591  // Feerates are stored and reported as RVN-per-kb:
592  CFeeRate feeRate(entry.GetFee(), entry.GetTxSize());
593 
594  mapMemPoolTxs[hash].blockHeight = txHeight;
595  unsigned int bucketIndex = feeStats->NewTx(txHeight, (double)feeRate.GetFeePerK());
596  mapMemPoolTxs[hash].bucketIndex = bucketIndex;
597  unsigned int bucketIndex2 = shortStats->NewTx(txHeight, (double)feeRate.GetFeePerK());
598  assert(bucketIndex == bucketIndex2);
599  unsigned int bucketIndex3 = longStats->NewTx(txHeight, (double)feeRate.GetFeePerK());
600  assert(bucketIndex == bucketIndex3);
601 }
602 
603 bool CBlockPolicyEstimator::processBlockTx(unsigned int nBlockHeight, const CTxMemPoolEntry* entry)
604 {
605  if (!removeTx(entry->GetTx().GetHash(), true)) {
606  // This transaction wasn't being tracked for fee estimation
607  return false;
608  }
609 
610  // How many blocks did it take for miners to include this transaction?
611  // blocksToConfirm is 1-based, so a transaction included in the earliest
612  // possible block has confirmation count of 1
613  int blocksToConfirm = nBlockHeight - entry->GetHeight();
614  if (blocksToConfirm <= 0) {
615  // This can't happen because we don't process transactions from a block with a height
616  // lower than our greatest seen height
617  LogPrint(BCLog::ESTIMATEFEE, "Blockpolicy error Transaction had negative blocksToConfirm\n");
618  return false;
619  }
620 
621  // Feerates are stored and reported as RVN-per-kb:
622  CFeeRate feeRate(entry->GetFee(), entry->GetTxSize());
623 
624  feeStats->Record(blocksToConfirm, (double)feeRate.GetFeePerK());
625  shortStats->Record(blocksToConfirm, (double)feeRate.GetFeePerK());
626  longStats->Record(blocksToConfirm, (double)feeRate.GetFeePerK());
627  return true;
628 }
629 
630 void CBlockPolicyEstimator::processBlock(unsigned int nBlockHeight,
631  std::vector<const CTxMemPoolEntry*>& entries)
632 {
634  if (nBlockHeight <= nBestSeenHeight) {
635  // Ignore side chains and re-orgs; assuming they are random
636  // they don't affect the estimate.
637  // And if an attacker can re-org the chain at will, then
638  // you've got much bigger problems than "attacker can influence
639  // transaction fees."
640  return;
641  }
642 
643  // Must update nBestSeenHeight in sync with ClearCurrent so that
644  // calls to removeTx (via processBlockTx) correctly calculate age
645  // of unconfirmed txs to remove from tracking.
646  nBestSeenHeight = nBlockHeight;
647 
648  // Update unconfirmed circular buffer
649  feeStats->ClearCurrent(nBlockHeight);
650  shortStats->ClearCurrent(nBlockHeight);
651  longStats->ClearCurrent(nBlockHeight);
652 
653  // Decay all exponential averages
657 
658  unsigned int countedTxs = 0;
659  // Update averages with data points from current block
660  for (const auto& entry : entries) {
661  if (processBlockTx(nBlockHeight, entry))
662  countedTxs++;
663  }
664 
665  if (firstRecordedHeight == 0 && countedTxs > 0) {
667  LogPrint(BCLog::ESTIMATEFEE, "Blockpolicy first recorded height %u\n", firstRecordedHeight);
668  }
669 
670 
671  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",
672  countedTxs, entries.size(), trackedTxs, trackedTxs + untrackedTxs, mapMemPoolTxs.size(),
673  MaxUsableEstimate(), HistoricalBlockSpan() > BlockSpan() ? "historical" : "current");
674 
675  trackedTxs = 0;
676  untrackedTxs = 0;
677 }
678 
680 {
681  // It's not possible to get reasonable estimates for confTarget of 1
682  if (confTarget <= 1)
683  return CFeeRate(0);
684 
686 }
687 
688 CFeeRate CBlockPolicyEstimator::estimateRawFee(int confTarget, double successThreshold, FeeEstimateHorizon horizon, EstimationResult* result) const
689 {
690  TxConfirmStats* stats;
691  double sufficientTxs = SUFFICIENT_FEETXS;
692  switch (horizon) {
694  stats = shortStats;
695  sufficientTxs = SUFFICIENT_TXS_SHORT;
696  break;
697  }
699  stats = feeStats;
700  break;
701  }
703  stats = longStats;
704  break;
705  }
706  default: {
707  throw std::out_of_range("CBlockPolicyEstimator::estimateRawFee unknown FeeEstimateHorizon");
708  }
709  }
710 
712  // Return failure if trying to analyze a target we're not tracking
713  if (confTarget <= 0 || (unsigned int)confTarget > stats->GetMaxConfirms())
714  return CFeeRate(0);
715  if (successThreshold > 1)
716  return CFeeRate(0);
717 
718  double median = stats->EstimateMedianVal(confTarget, sufficientTxs, successThreshold, true, nBestSeenHeight, result);
719 
720  if (median < 0)
721  return CFeeRate(0);
722 
723  return CFeeRate(llround(median));
724 }
725 
727 {
728  switch (horizon) {
730  return shortStats->GetMaxConfirms();
731  }
733  return feeStats->GetMaxConfirms();
734  }
736  return longStats->GetMaxConfirms();
737  }
738  default: {
739  throw std::out_of_range("CBlockPolicyEstimator::HighestTargetTracked unknown FeeEstimateHorizon");
740  }
741  }
742 }
743 
745 {
746  if (firstRecordedHeight == 0) return 0;
748 
750 }
751 
753 {
754  if (historicalFirst == 0) return 0;
755  assert(historicalBest >= historicalFirst);
756 
758 
760 }
761 
763 {
764  // Block spans are divided by 2 to make sure there are enough potential failing data points for the estimate
765  return std::min(longStats->GetMaxConfirms(), std::max(BlockSpan(), HistoricalBlockSpan()) / 2);
766 }
767 
772 double CBlockPolicyEstimator::estimateCombinedFee(unsigned int confTarget, double successThreshold, bool checkShorterHorizon, EstimationResult *result) const
773 {
774  double estimate = -1;
775  if (confTarget >= 1 && confTarget <= longStats->GetMaxConfirms()) {
776  // Find estimate from shortest time horizon possible
777  if (confTarget <= shortStats->GetMaxConfirms()) { // short horizon
778  estimate = shortStats->EstimateMedianVal(confTarget, SUFFICIENT_TXS_SHORT, successThreshold, true, nBestSeenHeight, result);
779  }
780  else if (confTarget <= feeStats->GetMaxConfirms()) { // medium horizon
781  estimate = feeStats->EstimateMedianVal(confTarget, SUFFICIENT_FEETXS, successThreshold, true, nBestSeenHeight, result);
782  }
783  else { // long horizon
784  estimate = longStats->EstimateMedianVal(confTarget, SUFFICIENT_FEETXS, successThreshold, true, nBestSeenHeight, result);
785  }
786  if (checkShorterHorizon) {
787  EstimationResult tempResult;
788  // If a lower confTarget from a more recent horizon returns a lower answer use it.
789  if (confTarget > feeStats->GetMaxConfirms()) {
790  double medMax = feeStats->EstimateMedianVal(feeStats->GetMaxConfirms(), SUFFICIENT_FEETXS, successThreshold, true, nBestSeenHeight, &tempResult);
791  if (medMax > 0 && (estimate == -1 || medMax < estimate)) {
792  estimate = medMax;
793  if (result) *result = tempResult;
794  }
795  }
796  if (confTarget > shortStats->GetMaxConfirms()) {
797  double shortMax = shortStats->EstimateMedianVal(shortStats->GetMaxConfirms(), SUFFICIENT_TXS_SHORT, successThreshold, true, nBestSeenHeight, &tempResult);
798  if (shortMax > 0 && (estimate == -1 || shortMax < estimate)) {
799  estimate = shortMax;
800  if (result) *result = tempResult;
801  }
802  }
803  }
804  }
805  return estimate;
806 }
807 
811 double CBlockPolicyEstimator::estimateConservativeFee(unsigned int doubleTarget, EstimationResult *result) const
812 {
813  double estimate = -1;
814  EstimationResult tempResult;
815  if (doubleTarget <= shortStats->GetMaxConfirms()) {
816  estimate = feeStats->EstimateMedianVal(doubleTarget, SUFFICIENT_FEETXS, DOUBLE_SUCCESS_PCT, true, nBestSeenHeight, result);
817  }
818  if (doubleTarget <= feeStats->GetMaxConfirms()) {
819  double longEstimate = longStats->EstimateMedianVal(doubleTarget, SUFFICIENT_FEETXS, DOUBLE_SUCCESS_PCT, true, nBestSeenHeight, &tempResult);
820  if (longEstimate > estimate) {
821  estimate = longEstimate;
822  if (result) *result = tempResult;
823  }
824  }
825  return estimate;
826 }
827 
835 CFeeRate CBlockPolicyEstimator::estimateSmartFee(int confTarget, FeeCalculation *feeCalc, bool conservative) const
836 {
838 
839  if (feeCalc) {
840  feeCalc->desiredTarget = confTarget;
841  feeCalc->returnedTarget = confTarget;
842  }
843 
844  double median = -1;
845  EstimationResult tempResult;
846 
847  // Return failure if trying to analyze a target we're not tracking
848  if (confTarget <= 0 || (unsigned int)confTarget > longStats->GetMaxConfirms()) {
849  return CFeeRate(0); // error condition
850  }
851 
852  // It's not possible to get reasonable estimates for confTarget of 1
853  if (confTarget == 1) confTarget = 2;
854 
855  unsigned int maxUsableEstimate = MaxUsableEstimate();
856  if ((unsigned int)confTarget > maxUsableEstimate) {
857  confTarget = maxUsableEstimate;
858  }
859  if (feeCalc) feeCalc->returnedTarget = confTarget;
860 
861  if (confTarget <= 1) return CFeeRate(0); // error condition
862 
863  assert(confTarget > 0); //estimateCombinedFee and estimateConservativeFee take unsigned ints
874  double halfEst = estimateCombinedFee(confTarget/2, HALF_SUCCESS_PCT, true, &tempResult);
875  if (feeCalc) {
876  feeCalc->est = tempResult;
877  feeCalc->reason = FeeReason::HALF_ESTIMATE;
878  }
879  median = halfEst;
880  double actualEst = estimateCombinedFee(confTarget, SUCCESS_PCT, true, &tempResult);
881  if (actualEst > median) {
882  median = actualEst;
883  if (feeCalc) {
884  feeCalc->est = tempResult;
885  feeCalc->reason = FeeReason::FULL_ESTIMATE;
886  }
887  }
888  double doubleEst = estimateCombinedFee(2 * confTarget, DOUBLE_SUCCESS_PCT, !conservative, &tempResult);
889  if (doubleEst > median) {
890  median = doubleEst;
891  if (feeCalc) {
892  feeCalc->est = tempResult;
894  }
895  }
896 
897  if (conservative || median == -1) {
898  double consEst = estimateConservativeFee(2 * confTarget, &tempResult);
899  if (consEst > median) {
900  median = consEst;
901  if (feeCalc) {
902  feeCalc->est = tempResult;
903  feeCalc->reason = FeeReason::CONSERVATIVE;
904  }
905  }
906  }
907 
908  if (median < 0) return CFeeRate(0); // error condition
909 
910  return CFeeRate(llround(median));
911 }
912 
913 
915 {
916  try {
918  fileout << 149900; // version required to read: 0.14.99 or later
919  fileout << CLIENT_VERSION; // version that wrote the file
920  fileout << nBestSeenHeight;
921  if (BlockSpan() > HistoricalBlockSpan()/2) {
922  fileout << firstRecordedHeight << nBestSeenHeight;
923  }
924  else {
925  fileout << historicalFirst << historicalBest;
926  }
927  fileout << buckets;
928  feeStats->Write(fileout);
929  shortStats->Write(fileout);
930  longStats->Write(fileout);
931  }
932  catch (const std::exception&) {
933  LogPrintf("CBlockPolicyEstimator::Write(): unable to write policy estimator data (non-fatal)\n");
934  return false;
935  }
936  return true;
937 }
938 
940 {
941  try {
943  int nVersionRequired, nVersionThatWrote;
944  filein >> nVersionRequired >> nVersionThatWrote;
945  if (nVersionRequired > CLIENT_VERSION)
946  return error("CBlockPolicyEstimator::Read(): up-version (%d) fee estimate file", nVersionRequired);
947 
948  // Read fee estimates file into temporary variables so existing data
949  // structures aren't corrupted if there is an exception.
950  unsigned int nFileBestSeenHeight;
951  filein >> nFileBestSeenHeight;
952 
953  if (nVersionThatWrote < 149900) {
954  // Read the old fee estimates file for temporary use, but then discard. Will start collecting data from scratch.
955  // decay is stored before buckets in old versions, so pre-read decay and pass into TxConfirmStats constructor
956  double tempDecay;
957  filein >> tempDecay;
958  if (tempDecay <= 0 || tempDecay >= 1)
959  throw std::runtime_error("Corrupt estimates file. Decay must be between 0 and 1 (non-inclusive)");
960 
961  std::vector<double> tempBuckets;
962  filein >> tempBuckets;
963  size_t tempNum = tempBuckets.size();
964  if (tempNum <= 1 || tempNum > 1000)
965  throw std::runtime_error("Corrupt estimates file. Must have between 2 and 1000 feerate buckets");
966 
967  std::map<double, unsigned int> tempMap;
968 
969  std::unique_ptr<TxConfirmStats> tempFeeStats(new TxConfirmStats(tempBuckets, tempMap, MED_BLOCK_PERIODS, tempDecay, 1));
970  tempFeeStats->Read(filein, nVersionThatWrote, tempNum);
971  // if nVersionThatWrote < 139900 then another TxConfirmStats (for priority) follows but can be ignored.
972 
973  tempMap.clear();
974  for (unsigned int i = 0; i < tempBuckets.size(); i++) {
975  tempMap[tempBuckets[i]] = i;
976  }
977  }
978  else { // nVersionThatWrote >= 149900
979  unsigned int nFileHistoricalFirst, nFileHistoricalBest;
980  filein >> nFileHistoricalFirst >> nFileHistoricalBest;
981  if (nFileHistoricalFirst > nFileHistoricalBest || nFileHistoricalBest > nFileBestSeenHeight) {
982  throw std::runtime_error("Corrupt estimates file. Historical block range for estimates is invalid");
983  }
984  std::vector<double> fileBuckets;
985  filein >> fileBuckets;
986  size_t numBuckets = fileBuckets.size();
987  if (numBuckets <= 1 || numBuckets > 1000)
988  throw std::runtime_error("Corrupt estimates file. Must have between 2 and 1000 feerate buckets");
989 
990  std::unique_ptr<TxConfirmStats> fileFeeStats(new TxConfirmStats(buckets, bucketMap, MED_BLOCK_PERIODS, MED_DECAY, MED_SCALE));
991  std::unique_ptr<TxConfirmStats> fileShortStats(new TxConfirmStats(buckets, bucketMap, SHORT_BLOCK_PERIODS, SHORT_DECAY, SHORT_SCALE));
992  std::unique_ptr<TxConfirmStats> fileLongStats(new TxConfirmStats(buckets, bucketMap, LONG_BLOCK_PERIODS, LONG_DECAY, LONG_SCALE));
993  fileFeeStats->Read(filein, nVersionThatWrote, numBuckets);
994  fileShortStats->Read(filein, nVersionThatWrote, numBuckets);
995  fileLongStats->Read(filein, nVersionThatWrote, numBuckets);
996 
997  // Fee estimates file parsed correctly
998  // Copy buckets from file and refresh our bucketmap
999  buckets = fileBuckets;
1000  bucketMap.clear();
1001  for (unsigned int i = 0; i < buckets.size(); i++) {
1002  bucketMap[buckets[i]] = i;
1003  }
1004 
1005  // Destroy old TxConfirmStats and point to new ones that already reference buckets and bucketMap
1006  delete feeStats;
1007  delete shortStats;
1008  delete longStats;
1009  feeStats = fileFeeStats.release();
1010  shortStats = fileShortStats.release();
1011  longStats = fileLongStats.release();
1012 
1013  nBestSeenHeight = nFileBestSeenHeight;
1014  historicalFirst = nFileHistoricalFirst;
1015  historicalBest = nFileHistoricalBest;
1016  }
1017  }
1018  catch (const std::exception& e) {
1019  LogPrintf("CBlockPolicyEstimator::Read(): unable to read policy estimator data (non-fatal): %s\n",e.what());
1020  return false;
1021  }
1022  return true;
1023 }
1024 
1026  int64_t startclear = GetTimeMicros();
1027  std::vector<uint256> txids;
1028  pool.queryHashes(txids);
1030  for (auto& txid : txids) {
1031  removeTx(txid, false);
1032  }
1033  int64_t endclear = GetTimeMicros();
1034  LogPrint(BCLog::ESTIMATEFEE, "Recorded %u unconfirmed txs from mempool in %gs\n",txids.size(), (endclear - startclear)*0.000001);
1035 }
1036 
1038 {
1039  CAmount minFeeLimit = std::max(CAmount(1), minIncrementalFee.GetFeePerK() / 2);
1040  feeset.insert(0);
1041  for (double bucketBoundary = minFeeLimit; bucketBoundary <= MAX_FILTER_FEERATE; bucketBoundary *= FEE_FILTER_SPACING) {
1042  feeset.insert(bucketBoundary);
1043  }
1044 }
1045 
1047 {
1048  std::set<double>::iterator it = feeset.lower_bound(currentMinFee);
1049  if ((it != feeset.begin() && insecure_rand.rand32() % 3 != 0) || it == feeset.end()) {
1050  it--;
1051  }
1052  return static_cast<CAmount>(*it);
1053 }
1054 
1055 
1056 int getConfTargetForIndex(int index) {
1057  if (index+1 > static_cast<int>(confTargets.size())) {
1058  return confTargets.back();
1059  }
1060  if (index < 0) {
1061  return confTargets[0];
1062  }
1063  return confTargets[index];
1064 }
1065 
1066 int getIndexForConfTarget(int target) {
1067  for (unsigned int i = 0; i < confTargets.size(); i++) {
1068  if (confTargets[i] >= target) {
1069  return i;
1070  }
1071  }
1072  return confTargets.size() - 1;
1073 }
static constexpr double MED_DECAY
Decay of .998 is a half-life of 144 blocks or about 1 day.
Definition: fees.h:157
EstimatorBucket pass
Definition: fees.h:120
std::vector< std::vector< double > > failAvg
Definition: fees.cpp:93
EstimationResult est
Definition: fees.h:128
bool FeeModeFromString(const std::string &mode_string, FeeEstimateMode &fee_estimate_mode)
Definition: fees.cpp:53
int returnedTarget
Definition: fees.h:131
CCriticalSection cs_feeEstimator
Definition: fees.h:260
static constexpr double MAX_BUCKET_FEERATE
Definition: fees.h:181
static constexpr double HALF_SUCCESS_PCT
Require greater than 60% of X feerate transactions to be confirmed within Y/2 blocks.
Definition: fees.h:162
size_t GetTxSize() const
Definition: txmempool.cpp:56
unsigned int firstRecordedHeight
Definition: fees.h:235
static constexpr unsigned int MED_BLOCK_PERIODS
Track confirm delays up to 48 blocks for medium horizon.
Definition: fees.h:146
double start
Definition: fees.h:109
bool removeTx(uint256 hash, bool inBlock)
Remove a transaction from the mempool tracking stats.
Definition: fees.cpp:524
CBlockPolicyEstimator()
Create new BlockPolicyEstimator and initialize stats tracking classes with default values...
Definition: fees.cpp:539
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:178
bool Write(CAutoFile &fileout) const
Write estimation data to a file.
Definition: fees.cpp:914
FeeEstimateMode
Definition: fees.h:98
std::vector< double > avg
Definition: fees.cpp:97
FeeReason reason
Definition: fees.h:129
We will instantiate an instance of this class to track transactions that were included in a block...
Definition: fees.cpp:75
std::map< double, unsigned int > bucketMap
Definition: fees.h:258
std::string StringForFeeReason(FeeReason reason)
Definition: fees.cpp:33
std::string StringForFeeEstimateHorizon(FeeEstimateHorizon horizon)
Definition: fees.cpp:20
static constexpr double DOUBLE_SUCCESS_PCT
Require greater than 95% of X feerate transactions to be confirmed within 2 * Y blocks.
Definition: fees.h:166
void queryHashes(std::vector< uint256 > &vtxid)
Definition: txmempool.cpp:1160
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:188
int64_t GetTimeMicros()
Definition: utiltime.cpp:48
unsigned int nBestSeenHeight
Definition: fees.h:234
double decay
Definition: fees.cpp:102
void Record(int blocksToConfirm, double val)
Record a new transaction data point in the current block stats.
Definition: fees.cpp:220
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:180
double withinTarget
Definition: fees.h:111
void resizeInMemoryCounters(size_t newbuckets)
Definition: fees.cpp:201
unsigned int MaxUsableEstimate() const
Calculation of highest target that reasonable estimate can be provided for.
Definition: fees.cpp:762
void ClearCurrent(unsigned int nBlockHeight)
Roll the circular buffer for unconfirmed txs.
Definition: fees.cpp:211
int desiredTarget
Definition: fees.h:130
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:171
CTxMemPoolEntry stores data about the corresponding transaction, as well as data about all in-mempool...
Definition: txmempool.h:68
TxConfirmStats * longStats
Definition: fees.h:252
int64_t CAmount
Amount in corbies (Can be negative)
Definition: amount.h:13
Force estimateSmartFee to use non-conservative estimates.
int getConfTargetForIndex(int index)
Definition: fees.cpp:1056
static constexpr double SUCCESS_PCT
Require greater than 85% of X feerate transactions to be confirmed within Y blocks.
Definition: fees.h:164
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:409
const std::map< double, unsigned int > & bucketMap
Definition: fees.cpp:80
static constexpr unsigned int SHORT_SCALE
Definition: fees.h:144
static constexpr double LONG_DECAY
Decay of .9995 is a half-life of 1008 blocks or about 1 week.
Definition: fees.h:159
#define LogPrintf(...)
Definition: util.h:149
std::vector< std::vector< double > > confAvg
Definition: fees.cpp:89
unsigned int NewTx(unsigned int nBlockHeight, double val)
Record a new transaction entering the mempool.
Definition: fees.cpp:474
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:752
double end
Definition: fees.h:110
EstimatorBucket fail
Definition: fees.h:121
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:688
TxConfirmStats * feeStats
Classes to track historical data on transaction confirmations.
Definition: fees.h:250
#define LOCK(cs)
Definition: sync.h:176
void removeTx(unsigned int entryHeight, unsigned int nBestSeenHeight, unsigned int bucketIndex, bool inBlock)
Remove a transaction from mempool tracking stats.
Definition: fees.cpp:482
const uint256 & GetHash() const
Definition: transaction.h:320
const CAmount & GetFee() const
Definition: txmempool.h:103
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:835
unsigned int scale
Definition: fees.cpp:105
unsigned int historicalFirst
Definition: fees.h:236
void FlushUnconfirmed(CTxMemPool &pool)
Empty mempool transactions on shutdown to record failure to confirm for txs still in mempool...
Definition: fees.cpp:1025
double estimateConservativeFee(unsigned int doubleTarget, EstimationResult *result) const
Helper for estimateSmartFee.
Definition: fees.cpp:811
unsigned int trackedTxs
Definition: fees.h:254
const std::vector< double > & buckets
Definition: fees.cpp:79
double inMempool
Definition: fees.h:113
unsigned int BlockSpan() const
Number of blocks of data recorded while fee estimates have been running.
Definition: fees.cpp:744
FeeReason
Definition: fees.h:82
std::string ToString() const
Definition: uint256.cpp:63
int getIndexForConfTarget(int target)
Definition: fees.cpp:1066
FeeFilterRounder(const CFeeRate &minIncrementalFee)
Create new FeeFilterRounder.
Definition: fees.cpp:1037
std::map< uint256, TxStatsInfo > mapMemPoolTxs
Definition: fees.h:247
CFeeRate estimateFee(int confTarget) const
DEPRECATED.
Definition: fees.cpp:679
static constexpr unsigned int LONG_SCALE
Definition: fees.h:150
double estimateCombinedFee(unsigned int confTarget, double successThreshold, bool checkShorterHorizon, EstimationResult *result) const
Helper for estimateSmartFee.
Definition: fees.cpp:772
#define LogPrint(category,...)
Definition: util.h:160
FeeEstimateHorizon
Definition: fees.h:73
std::vector< std::vector< int > > unconfTxs
Definition: fees.cpp:110
unsigned int HighestTargetTracked(FeeEstimateHorizon horizon) const
Calculation of highest target that estimates are tracked for.
Definition: fees.cpp:726
256-bit opaque blob.
Definition: uint256.h:123
static constexpr unsigned int MED_SCALE
Definition: fees.h:147
static const unsigned int OLDEST_ESTIMATE_HISTORY
Historical estimates that are older than this aren&#39;t valid.
Definition: fees.h:152
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:416
std::vector< int > oldUnconfTxs
Definition: fees.cpp:112
void processBlock(unsigned int nBlockHeight, std::vector< const CTxMemPoolEntry *> &entries)
Process all the transactions that have been included in a block.
Definition: fees.cpp:630
const CTransaction & GetTx() const
Definition: txmempool.h:101
bool Read(CAutoFile &filein)
Read estimation data from a file.
Definition: fees.cpp:939
unsigned int historicalBest
Definition: fees.h:237
double leftMempool
Definition: fees.h:114
unsigned int GetMaxConfirms() const
Return the max number of confirms we&#39;re tracking.
Definition: fees.cpp:165
static constexpr unsigned int LONG_BLOCK_PERIODS
Track confirm delays up to 1008 blocks for long horizon.
Definition: fees.h:149
Fee rate in satoshis per kilobyte: CAmount / kB.
Definition: feerate.h:20
bool error(const char *fmt, const Args &... args)
Definition: util.h:168
std::vector< double > buckets
Definition: fees.h:257
static constexpr unsigned int SHORT_BLOCK_PERIODS
Track confirm delays up to 12 blocks for short horizon.
Definition: fees.h:143
double totalConfirmed
Definition: fees.h:112
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:169
bool processBlockTx(unsigned int nBlockHeight, const CTxMemPoolEntry *entry)
Process a transaction confirmed in a block.
Definition: fees.cpp:603
Use default settings based on other criteria.
TxConfirmStats * shortStats
Definition: fees.h:251
CAmount round(CAmount currentMinFee)
Quantize a minimum fee for privacy purpose before broadcast.
Definition: fees.cpp:1046
static constexpr double SHORT_DECAY
Decay of .962 is a half-life of 18 blocks or about 3 hours.
Definition: fees.h:155
double EstimateMedianVal(int confTarget, double sufficientTxVal, double minSuccess, bool requireGreater, unsigned int nBlockHeight, EstimationResult *result=nullptr) const
Calculate a feerate estimate.
Definition: fees.cpp:247
void Write(CAutoFile &fileout) const
Write state of estimation data to a file.
Definition: fees.cpp:399
std::vector< double > txCtAvg
Definition: fees.cpp:85
unsigned int untrackedTxs
Definition: fees.h:255
void UpdateMovingAverages()
Update our estimates by decaying our historical moving average and updating with the data gathered fr...
Definition: fees.cpp:234
unsigned int scale
Definition: fees.h:123
CAmount GetFeePerK() const
Return the fee in satoshis for a size of 1000 bytes.
Definition: feerate.h:42
Non-refcounted RAII wrapper for FILE*.
Definition: streams.h:456
void processTransaction(const CTxMemPoolEntry &entry, bool validFeeEstimate)
Process a transaction accepted to the mempool.
Definition: fees.cpp:564
double decay
Definition: fees.h:122