Bitcoin Core  0.20.99
P2P Digital Currency
fees.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2019 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 
8 #include <clientversion.h>
9 #include <streams.h>
10 #include <txmempool.h>
11 #include <util/system.h>
12 
13 static constexpr double INF_FEERATE = 1e99;
14 
16  static const std::map<FeeEstimateHorizon, std::string> horizon_strings = {
20  };
21  auto horizon_string = horizon_strings.find(horizon);
22 
23  if (horizon_string == horizon_strings.end()) return "unknown";
24 
25  return horizon_string->second;
26 }
27 
37 {
38 private:
39  //Define the buckets we will group transactions into
40  const std::vector<double>& buckets; // The upper-bound of the range for the bucket (inclusive)
41  const std::map<double, unsigned int>& bucketMap; // Map of bucket upper-bound to index into all vectors by bucket
42 
43  // For each bucket X:
44  // Count the total # of txs in each bucket
45  // Track the historical moving average of this total over blocks
46  std::vector<double> txCtAvg;
47 
48  // Count the total # of txs confirmed within Y blocks in each bucket
49  // Track the historical moving average of these totals over blocks
50  std::vector<std::vector<double>> confAvg; // confAvg[Y][X]
51 
52  // Track moving avg of txs which have been evicted from the mempool
53  // after failing to be confirmed within Y blocks
54  std::vector<std::vector<double>> failAvg; // failAvg[Y][X]
55 
56  // Sum the total feerate of all tx's in each bucket
57  // Track the historical moving average of this total over blocks
58  std::vector<double> m_feerate_avg;
59 
60  // Combine the conf counts with tx counts to calculate the confirmation % for each Y,X
61  // Combine the total value with the tx counts to calculate the avg feerate per bucket
62 
63  double decay;
64 
65  // Resolution (# of blocks) with which confirmations are tracked
66  unsigned int scale;
67 
68  // Mempool counts of outstanding transactions
69  // For each bucket X, track the number of transactions in the mempool
70  // that are unconfirmed for each possible confirmation value Y
71  std::vector<std::vector<int> > unconfTxs; //unconfTxs[Y][X]
72  // transactions still unconfirmed after GetMaxConfirms for each bucket
73  std::vector<int> oldUnconfTxs;
74 
75  void resizeInMemoryCounters(size_t newbuckets);
76 
77 public:
85  TxConfirmStats(const std::vector<double>& defaultBuckets, const std::map<double, unsigned int>& defaultBucketMap,
86  unsigned int maxPeriods, double decay, unsigned int scale);
87 
89  void ClearCurrent(unsigned int nBlockHeight);
90 
97  void Record(int blocksToConfirm, double val);
98 
100  unsigned int NewTx(unsigned int nBlockHeight, double val);
101 
103  void removeTx(unsigned int entryHeight, unsigned int nBestSeenHeight,
104  unsigned int bucketIndex, bool inBlock);
105 
108  void UpdateMovingAverages();
109 
119  double EstimateMedianVal(int confTarget, double sufficientTxVal,
120  double minSuccess, unsigned int nBlockHeight,
121  EstimationResult *result = nullptr) const;
122 
124  unsigned int GetMaxConfirms() const { return scale * confAvg.size(); }
125 
127  void Write(CAutoFile& fileout) const;
128 
133  void Read(CAutoFile& filein, int nFileVersion, size_t numBuckets);
134 };
135 
136 
137 TxConfirmStats::TxConfirmStats(const std::vector<double>& defaultBuckets,
138  const std::map<double, unsigned int>& defaultBucketMap,
139  unsigned int maxPeriods, double _decay, unsigned int _scale)
140  : buckets(defaultBuckets), bucketMap(defaultBucketMap), decay(_decay), scale(_scale)
141 {
142  assert(_scale != 0 && "_scale must be non-zero");
143  confAvg.resize(maxPeriods);
144  failAvg.resize(maxPeriods);
145  for (unsigned int i = 0; i < maxPeriods; i++) {
146  confAvg[i].resize(buckets.size());
147  failAvg[i].resize(buckets.size());
148  }
149 
150  txCtAvg.resize(buckets.size());
151  m_feerate_avg.resize(buckets.size());
152 
154 }
155 
156 void TxConfirmStats::resizeInMemoryCounters(size_t newbuckets) {
157  // newbuckets must be passed in because the buckets referred to during Read have not been updated yet.
158  unconfTxs.resize(GetMaxConfirms());
159  for (unsigned int i = 0; i < unconfTxs.size(); i++) {
160  unconfTxs[i].resize(newbuckets);
161  }
162  oldUnconfTxs.resize(newbuckets);
163 }
164 
165 // Roll the unconfirmed txs circular buffer
166 void TxConfirmStats::ClearCurrent(unsigned int nBlockHeight)
167 {
168  for (unsigned int j = 0; j < buckets.size(); j++) {
169  oldUnconfTxs[j] += unconfTxs[nBlockHeight % unconfTxs.size()][j];
170  unconfTxs[nBlockHeight%unconfTxs.size()][j] = 0;
171  }
172 }
173 
174 
175 void TxConfirmStats::Record(int blocksToConfirm, double feerate)
176 {
177  // blocksToConfirm is 1-based
178  if (blocksToConfirm < 1)
179  return;
180  int periodsToConfirm = (blocksToConfirm + scale - 1) / scale;
181  unsigned int bucketindex = bucketMap.lower_bound(feerate)->second;
182  for (size_t i = periodsToConfirm; i <= confAvg.size(); i++) {
183  confAvg[i - 1][bucketindex]++;
184  }
185  txCtAvg[bucketindex]++;
186  m_feerate_avg[bucketindex] += feerate;
187 }
188 
190 {
191  assert(confAvg.size() == failAvg.size());
192  for (unsigned int j = 0; j < buckets.size(); j++) {
193  for (unsigned int i = 0; i < confAvg.size(); i++) {
194  confAvg[i][j] *= decay;
195  failAvg[i][j] *= decay;
196  }
197  m_feerate_avg[j] *= decay;
198  txCtAvg[j] *= decay;
199  }
200 }
201 
202 // returns -1 on error conditions
203 double TxConfirmStats::EstimateMedianVal(int confTarget, double sufficientTxVal,
204  double successBreakPoint, unsigned int nBlockHeight,
205  EstimationResult *result) const
206 {
207  // Counters for a bucket (or range of buckets)
208  double nConf = 0; // Number of tx's confirmed within the confTarget
209  double totalNum = 0; // Total number of tx's that were ever confirmed
210  int extraNum = 0; // Number of tx's still in mempool for confTarget or longer
211  double failNum = 0; // Number of tx's that were never confirmed but removed from the mempool after confTarget
212  const int periodTarget = (confTarget + scale - 1) / scale;
213  const int maxbucketindex = buckets.size() - 1;
214 
215  // We'll combine buckets until we have enough samples.
216  // The near and far variables will define the range we've combined
217  // The best variables are the last range we saw which still had a high
218  // enough confirmation rate to count as success.
219  // The cur variables are the current range we're counting.
220  unsigned int curNearBucket = maxbucketindex;
221  unsigned int bestNearBucket = maxbucketindex;
222  unsigned int curFarBucket = maxbucketindex;
223  unsigned int bestFarBucket = maxbucketindex;
224 
225  bool foundAnswer = false;
226  unsigned int bins = unconfTxs.size();
227  bool newBucketRange = true;
228  bool passing = true;
229  EstimatorBucket passBucket;
230  EstimatorBucket failBucket;
231 
232  // Start counting from highest feerate transactions
233  for (int bucket = maxbucketindex; bucket >= 0; --bucket) {
234  if (newBucketRange) {
235  curNearBucket = bucket;
236  newBucketRange = false;
237  }
238  curFarBucket = bucket;
239  nConf += confAvg[periodTarget - 1][bucket];
240  totalNum += txCtAvg[bucket];
241  failNum += failAvg[periodTarget - 1][bucket];
242  for (unsigned int confct = confTarget; confct < GetMaxConfirms(); confct++)
243  extraNum += unconfTxs[(nBlockHeight - confct) % bins][bucket];
244  extraNum += oldUnconfTxs[bucket];
245  // If we have enough transaction data points in this range of buckets,
246  // we can test for success
247  // (Only count the confirmed data points, so that each confirmation count
248  // will be looking at the same amount of data and same bucket breaks)
249  if (totalNum >= sufficientTxVal / (1 - decay)) {
250  double curPct = nConf / (totalNum + failNum + extraNum);
251 
252  // Check to see if we are no longer getting confirmed at the success rate
253  if (curPct < successBreakPoint) {
254  if (passing == true) {
255  // First time we hit a failure record the failed bucket
256  unsigned int failMinBucket = std::min(curNearBucket, curFarBucket);
257  unsigned int failMaxBucket = std::max(curNearBucket, curFarBucket);
258  failBucket.start = failMinBucket ? buckets[failMinBucket - 1] : 0;
259  failBucket.end = buckets[failMaxBucket];
260  failBucket.withinTarget = nConf;
261  failBucket.totalConfirmed = totalNum;
262  failBucket.inMempool = extraNum;
263  failBucket.leftMempool = failNum;
264  passing = false;
265  }
266  continue;
267  }
268  // Otherwise update the cumulative stats, and the bucket variables
269  // and reset the counters
270  else {
271  failBucket = EstimatorBucket(); // Reset any failed bucket, currently passing
272  foundAnswer = true;
273  passing = true;
274  passBucket.withinTarget = nConf;
275  nConf = 0;
276  passBucket.totalConfirmed = totalNum;
277  totalNum = 0;
278  passBucket.inMempool = extraNum;
279  passBucket.leftMempool = failNum;
280  failNum = 0;
281  extraNum = 0;
282  bestNearBucket = curNearBucket;
283  bestFarBucket = curFarBucket;
284  newBucketRange = true;
285  }
286  }
287  }
288 
289  double median = -1;
290  double txSum = 0;
291 
292  // Calculate the "average" feerate of the best bucket range that met success conditions
293  // Find the bucket with the median transaction and then report the average feerate from that bucket
294  // This is a compromise between finding the median which we can't since we don't save all tx's
295  // and reporting the average which is less accurate
296  unsigned int minBucket = std::min(bestNearBucket, bestFarBucket);
297  unsigned int maxBucket = std::max(bestNearBucket, bestFarBucket);
298  for (unsigned int j = minBucket; j <= maxBucket; j++) {
299  txSum += txCtAvg[j];
300  }
301  if (foundAnswer && txSum != 0) {
302  txSum = txSum / 2;
303  for (unsigned int j = minBucket; j <= maxBucket; j++) {
304  if (txCtAvg[j] < txSum)
305  txSum -= txCtAvg[j];
306  else { // we're in the right bucket
307  median = m_feerate_avg[j] / txCtAvg[j];
308  break;
309  }
310  }
311 
312  passBucket.start = minBucket ? buckets[minBucket-1] : 0;
313  passBucket.end = buckets[maxBucket];
314  }
315 
316  // If we were passing until we reached last few buckets with insufficient data, then report those as failed
317  if (passing && !newBucketRange) {
318  unsigned int failMinBucket = std::min(curNearBucket, curFarBucket);
319  unsigned int failMaxBucket = std::max(curNearBucket, curFarBucket);
320  failBucket.start = failMinBucket ? buckets[failMinBucket - 1] : 0;
321  failBucket.end = buckets[failMaxBucket];
322  failBucket.withinTarget = nConf;
323  failBucket.totalConfirmed = totalNum;
324  failBucket.inMempool = extraNum;
325  failBucket.leftMempool = failNum;
326  }
327 
328  float passed_within_target_perc = 0.0;
329  float failed_within_target_perc = 0.0;
330  if ((passBucket.totalConfirmed + passBucket.inMempool + passBucket.leftMempool)) {
331  passed_within_target_perc = 100 * passBucket.withinTarget / (passBucket.totalConfirmed + passBucket.inMempool + passBucket.leftMempool);
332  }
333  if ((failBucket.totalConfirmed + failBucket.inMempool + failBucket.leftMempool)) {
334  failed_within_target_perc = 100 * failBucket.withinTarget / (failBucket.totalConfirmed + failBucket.inMempool + failBucket.leftMempool);
335  }
336 
337  LogPrint(BCLog::ESTIMATEFEE, "FeeEst: %d > %.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",
338  confTarget, 100.0 * successBreakPoint, decay,
339  median, passBucket.start, passBucket.end,
340  passed_within_target_perc,
341  passBucket.withinTarget, passBucket.totalConfirmed, passBucket.inMempool, passBucket.leftMempool,
342  failBucket.start, failBucket.end,
343  failed_within_target_perc,
344  failBucket.withinTarget, failBucket.totalConfirmed, failBucket.inMempool, failBucket.leftMempool);
345 
346 
347  if (result) {
348  result->pass = passBucket;
349  result->fail = failBucket;
350  result->decay = decay;
351  result->scale = scale;
352  }
353  return median;
354 }
355 
356 void TxConfirmStats::Write(CAutoFile& fileout) const
357 {
358  fileout << decay;
359  fileout << scale;
360  fileout << m_feerate_avg;
361  fileout << txCtAvg;
362  fileout << confAvg;
363  fileout << failAvg;
364 }
365 
366 void TxConfirmStats::Read(CAutoFile& filein, int nFileVersion, size_t numBuckets)
367 {
368  // Read data file and do some very basic sanity checking
369  // buckets and bucketMap are not updated yet, so don't access them
370  // If there is a read failure, we'll just discard this entire object anyway
371  size_t maxConfirms, maxPeriods;
372 
373  // The current version will store the decay with each individual TxConfirmStats and also keep a scale factor
374  filein >> decay;
375  if (decay <= 0 || decay >= 1) {
376  throw std::runtime_error("Corrupt estimates file. Decay must be between 0 and 1 (non-inclusive)");
377  }
378  filein >> scale;
379  if (scale == 0) {
380  throw std::runtime_error("Corrupt estimates file. Scale must be non-zero");
381  }
382 
383  filein >> m_feerate_avg;
384  if (m_feerate_avg.size() != numBuckets) {
385  throw std::runtime_error("Corrupt estimates file. Mismatch in feerate average bucket count");
386  }
387  filein >> txCtAvg;
388  if (txCtAvg.size() != numBuckets) {
389  throw std::runtime_error("Corrupt estimates file. Mismatch in tx count bucket count");
390  }
391  filein >> confAvg;
392  maxPeriods = confAvg.size();
393  maxConfirms = scale * maxPeriods;
394 
395  if (maxConfirms <= 0 || maxConfirms > 6 * 24 * 7) { // one week
396  throw std::runtime_error("Corrupt estimates file. Must maintain estimates for between 1 and 1008 (one week) confirms");
397  }
398  for (unsigned int i = 0; i < maxPeriods; i++) {
399  if (confAvg[i].size() != numBuckets) {
400  throw std::runtime_error("Corrupt estimates file. Mismatch in feerate conf average bucket count");
401  }
402  }
403 
404  filein >> failAvg;
405  if (maxPeriods != failAvg.size()) {
406  throw std::runtime_error("Corrupt estimates file. Mismatch in confirms tracked for failures");
407  }
408  for (unsigned int i = 0; i < maxPeriods; i++) {
409  if (failAvg[i].size() != numBuckets) {
410  throw std::runtime_error("Corrupt estimates file. Mismatch in one of failure average bucket counts");
411  }
412  }
413 
414  // Resize the current block variables which aren't stored in the data file
415  // to match the number of confirms and buckets
416  resizeInMemoryCounters(numBuckets);
417 
418  LogPrint(BCLog::ESTIMATEFEE, "Reading estimates: %u buckets counting confirms up to %u blocks\n",
419  numBuckets, maxConfirms);
420 }
421 
422 unsigned int TxConfirmStats::NewTx(unsigned int nBlockHeight, double val)
423 {
424  unsigned int bucketindex = bucketMap.lower_bound(val)->second;
425  unsigned int blockIndex = nBlockHeight % unconfTxs.size();
426  unconfTxs[blockIndex][bucketindex]++;
427  return bucketindex;
428 }
429 
430 void TxConfirmStats::removeTx(unsigned int entryHeight, unsigned int nBestSeenHeight, unsigned int bucketindex, bool inBlock)
431 {
432  //nBestSeenHeight is not updated yet for the new block
433  int blocksAgo = nBestSeenHeight - entryHeight;
434  if (nBestSeenHeight == 0) // the BlockPolicyEstimator hasn't seen any blocks yet
435  blocksAgo = 0;
436  if (blocksAgo < 0) {
437  LogPrint(BCLog::ESTIMATEFEE, "Blockpolicy error, blocks ago is negative for mempool tx\n");
438  return; //This can't happen because we call this with our best seen height, no entries can have higher
439  }
440 
441  if (blocksAgo >= (int)unconfTxs.size()) {
442  if (oldUnconfTxs[bucketindex] > 0) {
443  oldUnconfTxs[bucketindex]--;
444  } else {
445  LogPrint(BCLog::ESTIMATEFEE, "Blockpolicy error, mempool tx removed from >25 blocks,bucketIndex=%u already\n",
446  bucketindex);
447  }
448  }
449  else {
450  unsigned int blockIndex = entryHeight % unconfTxs.size();
451  if (unconfTxs[blockIndex][bucketindex] > 0) {
452  unconfTxs[blockIndex][bucketindex]--;
453  } else {
454  LogPrint(BCLog::ESTIMATEFEE, "Blockpolicy error, mempool tx removed from blockIndex=%u,bucketIndex=%u already\n",
455  blockIndex, bucketindex);
456  }
457  }
458  if (!inBlock && (unsigned int)blocksAgo >= scale) { // Only counts as a failure if not confirmed for entire period
459  assert(scale != 0);
460  unsigned int periodsAgo = blocksAgo / scale;
461  for (size_t i = 0; i < periodsAgo && i < failAvg.size(); i++) {
462  failAvg[i][bucketindex]++;
463  }
464  }
465 }
466 
467 // This function is called from CTxMemPool::removeUnchecked to ensure
468 // txs removed from the mempool for any reason are no longer
469 // tracked. Txs that were part of a block have already been removed in
470 // processBlockTx to ensure they are never double tracked, but it is
471 // of no harm to try to remove them again.
472 bool CBlockPolicyEstimator::removeTx(uint256 hash, bool inBlock)
473 {
474  LOCK(m_cs_fee_estimator);
475  std::map<uint256, TxStatsInfo>::iterator pos = mapMemPoolTxs.find(hash);
476  if (pos != mapMemPoolTxs.end()) {
477  feeStats->removeTx(pos->second.blockHeight, nBestSeenHeight, pos->second.bucketIndex, inBlock);
478  shortStats->removeTx(pos->second.blockHeight, nBestSeenHeight, pos->second.bucketIndex, inBlock);
479  longStats->removeTx(pos->second.blockHeight, nBestSeenHeight, pos->second.bucketIndex, inBlock);
480  mapMemPoolTxs.erase(hash);
481  return true;
482  } else {
483  return false;
484  }
485 }
486 
488  : nBestSeenHeight(0), firstRecordedHeight(0), historicalFirst(0), historicalBest(0), trackedTxs(0), untrackedTxs(0)
489 {
490  static_assert(MIN_BUCKET_FEERATE > 0, "Min feerate must be nonzero");
491  size_t bucketIndex = 0;
492  for (double bucketBoundary = MIN_BUCKET_FEERATE; bucketBoundary <= MAX_BUCKET_FEERATE; bucketBoundary *= FEE_SPACING, bucketIndex++) {
493  buckets.push_back(bucketBoundary);
494  bucketMap[bucketBoundary] = bucketIndex;
495  }
496  buckets.push_back(INF_FEERATE);
497  bucketMap[INF_FEERATE] = bucketIndex;
498  assert(bucketMap.size() == buckets.size());
499 
500  feeStats = std::unique_ptr<TxConfirmStats>(new TxConfirmStats(buckets, bucketMap, MED_BLOCK_PERIODS, MED_DECAY, MED_SCALE));
501  shortStats = std::unique_ptr<TxConfirmStats>(new TxConfirmStats(buckets, bucketMap, SHORT_BLOCK_PERIODS, SHORT_DECAY, SHORT_SCALE));
502  longStats = std::unique_ptr<TxConfirmStats>(new TxConfirmStats(buckets, bucketMap, LONG_BLOCK_PERIODS, LONG_DECAY, LONG_SCALE));
503 }
504 
506 {
507 }
508 
509 void CBlockPolicyEstimator::processTransaction(const CTxMemPoolEntry& entry, bool validFeeEstimate)
510 {
512  unsigned int txHeight = entry.GetHeight();
513  uint256 hash = entry.GetTx().GetHash();
514  if (mapMemPoolTxs.count(hash)) {
515  LogPrint(BCLog::ESTIMATEFEE, "Blockpolicy error mempool tx %s already being tracked\n",
516  hash.ToString());
517  return;
518  }
519 
520  if (txHeight != nBestSeenHeight) {
521  // Ignore side chains and re-orgs; assuming they are random they don't
522  // affect the estimate. We'll potentially double count transactions in 1-block reorgs.
523  // Ignore txs if BlockPolicyEstimator is not in sync with ::ChainActive().Tip().
524  // It will be synced next time a block is processed.
525  return;
526  }
527 
528  // Only want to be updating estimates when our blockchain is synced,
529  // otherwise we'll miscalculate how many blocks its taking to get included.
530  if (!validFeeEstimate) {
531  untrackedTxs++;
532  return;
533  }
534  trackedTxs++;
535 
536  // Feerates are stored and reported as BTC-per-kb:
537  CFeeRate feeRate(entry.GetFee(), entry.GetTxSize());
538 
539  mapMemPoolTxs[hash].blockHeight = txHeight;
540  unsigned int bucketIndex = feeStats->NewTx(txHeight, (double)feeRate.GetFeePerK());
541  mapMemPoolTxs[hash].bucketIndex = bucketIndex;
542  unsigned int bucketIndex2 = shortStats->NewTx(txHeight, (double)feeRate.GetFeePerK());
543  assert(bucketIndex == bucketIndex2);
544  unsigned int bucketIndex3 = longStats->NewTx(txHeight, (double)feeRate.GetFeePerK());
545  assert(bucketIndex == bucketIndex3);
546 }
547 
548 bool CBlockPolicyEstimator::processBlockTx(unsigned int nBlockHeight, const CTxMemPoolEntry* entry)
549 {
550  if (!removeTx(entry->GetTx().GetHash(), true)) {
551  // This transaction wasn't being tracked for fee estimation
552  return false;
553  }
554 
555  // How many blocks did it take for miners to include this transaction?
556  // blocksToConfirm is 1-based, so a transaction included in the earliest
557  // possible block has confirmation count of 1
558  int blocksToConfirm = nBlockHeight - entry->GetHeight();
559  if (blocksToConfirm <= 0) {
560  // This can't happen because we don't process transactions from a block with a height
561  // lower than our greatest seen height
562  LogPrint(BCLog::ESTIMATEFEE, "Blockpolicy error Transaction had negative blocksToConfirm\n");
563  return false;
564  }
565 
566  // Feerates are stored and reported as BTC-per-kb:
567  CFeeRate feeRate(entry->GetFee(), entry->GetTxSize());
568 
569  feeStats->Record(blocksToConfirm, (double)feeRate.GetFeePerK());
570  shortStats->Record(blocksToConfirm, (double)feeRate.GetFeePerK());
571  longStats->Record(blocksToConfirm, (double)feeRate.GetFeePerK());
572  return true;
573 }
574 
575 void CBlockPolicyEstimator::processBlock(unsigned int nBlockHeight,
576  std::vector<const CTxMemPoolEntry*>& entries)
577 {
579  if (nBlockHeight <= nBestSeenHeight) {
580  // Ignore side chains and re-orgs; assuming they are random
581  // they don't affect the estimate.
582  // And if an attacker can re-org the chain at will, then
583  // you've got much bigger problems than "attacker can influence
584  // transaction fees."
585  return;
586  }
587 
588  // Must update nBestSeenHeight in sync with ClearCurrent so that
589  // calls to removeTx (via processBlockTx) correctly calculate age
590  // of unconfirmed txs to remove from tracking.
591  nBestSeenHeight = nBlockHeight;
592 
593  // Update unconfirmed circular buffer
594  feeStats->ClearCurrent(nBlockHeight);
595  shortStats->ClearCurrent(nBlockHeight);
596  longStats->ClearCurrent(nBlockHeight);
597 
598  // Decay all exponential averages
599  feeStats->UpdateMovingAverages();
600  shortStats->UpdateMovingAverages();
601  longStats->UpdateMovingAverages();
602 
603  unsigned int countedTxs = 0;
604  // Update averages with data points from current block
605  for (const auto& entry : entries) {
606  if (processBlockTx(nBlockHeight, entry))
607  countedTxs++;
608  }
609 
610  if (firstRecordedHeight == 0 && countedTxs > 0) {
611  firstRecordedHeight = nBestSeenHeight;
612  LogPrint(BCLog::ESTIMATEFEE, "Blockpolicy first recorded height %u\n", firstRecordedHeight);
613  }
614 
615 
616  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",
617  countedTxs, entries.size(), trackedTxs, trackedTxs + untrackedTxs, mapMemPoolTxs.size(),
618  MaxUsableEstimate(), HistoricalBlockSpan() > BlockSpan() ? "historical" : "current");
619 
620  trackedTxs = 0;
621  untrackedTxs = 0;
622 }
623 
625 {
626  // It's not possible to get reasonable estimates for confTarget of 1
627  if (confTarget <= 1)
628  return CFeeRate(0);
629 
631 }
632 
633 CFeeRate CBlockPolicyEstimator::estimateRawFee(int confTarget, double successThreshold, FeeEstimateHorizon horizon, EstimationResult* result) const
634 {
635  TxConfirmStats* stats;
636  double sufficientTxs = SUFFICIENT_FEETXS;
637  switch (horizon) {
639  stats = shortStats.get();
640  sufficientTxs = SUFFICIENT_TXS_SHORT;
641  break;
642  }
644  stats = feeStats.get();
645  break;
646  }
648  stats = longStats.get();
649  break;
650  }
651  default: {
652  throw std::out_of_range("CBlockPolicyEstimator::estimateRawFee unknown FeeEstimateHorizon");
653  }
654  }
655 
657  // Return failure if trying to analyze a target we're not tracking
658  if (confTarget <= 0 || (unsigned int)confTarget > stats->GetMaxConfirms())
659  return CFeeRate(0);
660  if (successThreshold > 1)
661  return CFeeRate(0);
662 
663  double median = stats->EstimateMedianVal(confTarget, sufficientTxs, successThreshold, nBestSeenHeight, result);
664 
665  if (median < 0)
666  return CFeeRate(0);
667 
668  return CFeeRate(llround(median));
669 }
670 
672 {
674  switch (horizon) {
676  return shortStats->GetMaxConfirms();
677  }
679  return feeStats->GetMaxConfirms();
680  }
682  return longStats->GetMaxConfirms();
683  }
684  default: {
685  throw std::out_of_range("CBlockPolicyEstimator::HighestTargetTracked unknown FeeEstimateHorizon");
686  }
687  }
688 }
689 
691 {
692  if (firstRecordedHeight == 0) return 0;
693  assert(nBestSeenHeight >= firstRecordedHeight);
694 
695  return nBestSeenHeight - firstRecordedHeight;
696 }
697 
699 {
700  if (historicalFirst == 0) return 0;
701  assert(historicalBest >= historicalFirst);
702 
703  if (nBestSeenHeight - historicalBest > OLDEST_ESTIMATE_HISTORY) return 0;
704 
705  return historicalBest - historicalFirst;
706 }
707 
709 {
710  // Block spans are divided by 2 to make sure there are enough potential failing data points for the estimate
711  return std::min(longStats->GetMaxConfirms(), std::max(BlockSpan(), HistoricalBlockSpan()) / 2);
712 }
713 
718 double CBlockPolicyEstimator::estimateCombinedFee(unsigned int confTarget, double successThreshold, bool checkShorterHorizon, EstimationResult *result) const
719 {
720  double estimate = -1;
721  if (confTarget >= 1 && confTarget <= longStats->GetMaxConfirms()) {
722  // Find estimate from shortest time horizon possible
723  if (confTarget <= shortStats->GetMaxConfirms()) { // short horizon
724  estimate = shortStats->EstimateMedianVal(confTarget, SUFFICIENT_TXS_SHORT, successThreshold, nBestSeenHeight, result);
725  }
726  else if (confTarget <= feeStats->GetMaxConfirms()) { // medium horizon
727  estimate = feeStats->EstimateMedianVal(confTarget, SUFFICIENT_FEETXS, successThreshold, nBestSeenHeight, result);
728  }
729  else { // long horizon
730  estimate = longStats->EstimateMedianVal(confTarget, SUFFICIENT_FEETXS, successThreshold, nBestSeenHeight, result);
731  }
732  if (checkShorterHorizon) {
733  EstimationResult tempResult;
734  // If a lower confTarget from a more recent horizon returns a lower answer use it.
735  if (confTarget > feeStats->GetMaxConfirms()) {
736  double medMax = feeStats->EstimateMedianVal(feeStats->GetMaxConfirms(), SUFFICIENT_FEETXS, successThreshold, nBestSeenHeight, &tempResult);
737  if (medMax > 0 && (estimate == -1 || medMax < estimate)) {
738  estimate = medMax;
739  if (result) *result = tempResult;
740  }
741  }
742  if (confTarget > shortStats->GetMaxConfirms()) {
743  double shortMax = shortStats->EstimateMedianVal(shortStats->GetMaxConfirms(), SUFFICIENT_TXS_SHORT, successThreshold, nBestSeenHeight, &tempResult);
744  if (shortMax > 0 && (estimate == -1 || shortMax < estimate)) {
745  estimate = shortMax;
746  if (result) *result = tempResult;
747  }
748  }
749  }
750  }
751  return estimate;
752 }
753 
757 double CBlockPolicyEstimator::estimateConservativeFee(unsigned int doubleTarget, EstimationResult *result) const
758 {
759  double estimate = -1;
760  EstimationResult tempResult;
761  if (doubleTarget <= shortStats->GetMaxConfirms()) {
762  estimate = feeStats->EstimateMedianVal(doubleTarget, SUFFICIENT_FEETXS, DOUBLE_SUCCESS_PCT, nBestSeenHeight, result);
763  }
764  if (doubleTarget <= feeStats->GetMaxConfirms()) {
765  double longEstimate = longStats->EstimateMedianVal(doubleTarget, SUFFICIENT_FEETXS, DOUBLE_SUCCESS_PCT, nBestSeenHeight, &tempResult);
766  if (longEstimate > estimate) {
767  estimate = longEstimate;
768  if (result) *result = tempResult;
769  }
770  }
771  return estimate;
772 }
773 
781 CFeeRate CBlockPolicyEstimator::estimateSmartFee(int confTarget, FeeCalculation *feeCalc, bool conservative) const
782 {
784 
785  if (feeCalc) {
786  feeCalc->desiredTarget = confTarget;
787  feeCalc->returnedTarget = confTarget;
788  }
789 
790  double median = -1;
791  EstimationResult tempResult;
792 
793  // Return failure if trying to analyze a target we're not tracking
794  if (confTarget <= 0 || (unsigned int)confTarget > longStats->GetMaxConfirms()) {
795  return CFeeRate(0); // error condition
796  }
797 
798  // It's not possible to get reasonable estimates for confTarget of 1
799  if (confTarget == 1) confTarget = 2;
800 
801  unsigned int maxUsableEstimate = MaxUsableEstimate();
802  if ((unsigned int)confTarget > maxUsableEstimate) {
803  confTarget = maxUsableEstimate;
804  }
805  if (feeCalc) feeCalc->returnedTarget = confTarget;
806 
807  if (confTarget <= 1) return CFeeRate(0); // error condition
808 
809  assert(confTarget > 0); //estimateCombinedFee and estimateConservativeFee take unsigned ints
820  double halfEst = estimateCombinedFee(confTarget/2, HALF_SUCCESS_PCT, true, &tempResult);
821  if (feeCalc) {
822  feeCalc->est = tempResult;
823  feeCalc->reason = FeeReason::HALF_ESTIMATE;
824  }
825  median = halfEst;
826  double actualEst = estimateCombinedFee(confTarget, SUCCESS_PCT, true, &tempResult);
827  if (actualEst > median) {
828  median = actualEst;
829  if (feeCalc) {
830  feeCalc->est = tempResult;
831  feeCalc->reason = FeeReason::FULL_ESTIMATE;
832  }
833  }
834  double doubleEst = estimateCombinedFee(2 * confTarget, DOUBLE_SUCCESS_PCT, !conservative, &tempResult);
835  if (doubleEst > median) {
836  median = doubleEst;
837  if (feeCalc) {
838  feeCalc->est = tempResult;
840  }
841  }
842 
843  if (conservative || median == -1) {
844  double consEst = estimateConservativeFee(2 * confTarget, &tempResult);
845  if (consEst > median) {
846  median = consEst;
847  if (feeCalc) {
848  feeCalc->est = tempResult;
849  feeCalc->reason = FeeReason::CONSERVATIVE;
850  }
851  }
852  }
853 
854  if (median < 0) return CFeeRate(0); // error condition
855 
856  return CFeeRate(llround(median));
857 }
858 
859 
861 {
862  try {
864  fileout << 149900; // version required to read: 0.14.99 or later
865  fileout << CLIENT_VERSION; // version that wrote the file
866  fileout << nBestSeenHeight;
867  if (BlockSpan() > HistoricalBlockSpan()/2) {
868  fileout << firstRecordedHeight << nBestSeenHeight;
869  }
870  else {
871  fileout << historicalFirst << historicalBest;
872  }
873  fileout << buckets;
874  feeStats->Write(fileout);
875  shortStats->Write(fileout);
876  longStats->Write(fileout);
877  }
878  catch (const std::exception&) {
879  LogPrintf("CBlockPolicyEstimator::Write(): unable to write policy estimator data (non-fatal)\n");
880  return false;
881  }
882  return true;
883 }
884 
886 {
887  try {
889  int nVersionRequired, nVersionThatWrote;
890  filein >> nVersionRequired >> nVersionThatWrote;
891  if (nVersionRequired > CLIENT_VERSION)
892  return error("CBlockPolicyEstimator::Read(): up-version (%d) fee estimate file", nVersionRequired);
893 
894  // Read fee estimates file into temporary variables so existing data
895  // structures aren't corrupted if there is an exception.
896  unsigned int nFileBestSeenHeight;
897  filein >> nFileBestSeenHeight;
898 
899  if (nVersionRequired < 149900) {
900  LogPrintf("%s: incompatible old fee estimation data (non-fatal). Version: %d\n", __func__, nVersionRequired);
901  } else { // New format introduced in 149900
902  unsigned int nFileHistoricalFirst, nFileHistoricalBest;
903  filein >> nFileHistoricalFirst >> nFileHistoricalBest;
904  if (nFileHistoricalFirst > nFileHistoricalBest || nFileHistoricalBest > nFileBestSeenHeight) {
905  throw std::runtime_error("Corrupt estimates file. Historical block range for estimates is invalid");
906  }
907  std::vector<double> fileBuckets;
908  filein >> fileBuckets;
909  size_t numBuckets = fileBuckets.size();
910  if (numBuckets <= 1 || numBuckets > 1000)
911  throw std::runtime_error("Corrupt estimates file. Must have between 2 and 1000 feerate buckets");
912 
913  std::unique_ptr<TxConfirmStats> fileFeeStats(new TxConfirmStats(buckets, bucketMap, MED_BLOCK_PERIODS, MED_DECAY, MED_SCALE));
914  std::unique_ptr<TxConfirmStats> fileShortStats(new TxConfirmStats(buckets, bucketMap, SHORT_BLOCK_PERIODS, SHORT_DECAY, SHORT_SCALE));
915  std::unique_ptr<TxConfirmStats> fileLongStats(new TxConfirmStats(buckets, bucketMap, LONG_BLOCK_PERIODS, LONG_DECAY, LONG_SCALE));
916  fileFeeStats->Read(filein, nVersionThatWrote, numBuckets);
917  fileShortStats->Read(filein, nVersionThatWrote, numBuckets);
918  fileLongStats->Read(filein, nVersionThatWrote, numBuckets);
919 
920  // Fee estimates file parsed correctly
921  // Copy buckets from file and refresh our bucketmap
922  buckets = fileBuckets;
923  bucketMap.clear();
924  for (unsigned int i = 0; i < buckets.size(); i++) {
925  bucketMap[buckets[i]] = i;
926  }
927 
928  // Destroy old TxConfirmStats and point to new ones that already reference buckets and bucketMap
929  feeStats = std::move(fileFeeStats);
930  shortStats = std::move(fileShortStats);
931  longStats = std::move(fileLongStats);
932 
933  nBestSeenHeight = nFileBestSeenHeight;
934  historicalFirst = nFileHistoricalFirst;
935  historicalBest = nFileHistoricalBest;
936  }
937  }
938  catch (const std::exception& e) {
939  LogPrintf("CBlockPolicyEstimator::Read(): unable to read policy estimator data (non-fatal): %s\n",e.what());
940  return false;
941  }
942  return true;
943 }
944 
946  int64_t startclear = GetTimeMicros();
948  size_t num_entries = mapMemPoolTxs.size();
949  // Remove every entry in mapMemPoolTxs
950  while (!mapMemPoolTxs.empty()) {
951  auto mi = mapMemPoolTxs.begin();
952  removeTx(mi->first, false); // this calls erase() on mapMemPoolTxs
953  }
954  int64_t endclear = GetTimeMicros();
955  LogPrint(BCLog::ESTIMATEFEE, "Recorded %u unconfirmed txs from mempool in %gs\n", num_entries, (endclear - startclear)*0.000001);
956 }
957 
959 {
960  CAmount minFeeLimit = std::max(CAmount(1), minIncrementalFee.GetFeePerK() / 2);
961  feeset.insert(0);
962  for (double bucketBoundary = minFeeLimit; bucketBoundary <= MAX_FILTER_FEERATE; bucketBoundary *= FEE_FILTER_SPACING) {
963  feeset.insert(bucketBoundary);
964  }
965 }
966 
968 {
969  std::set<double>::iterator it = feeset.lower_bound(currentMinFee);
970  if ((it != feeset.begin() && insecure_rand.rand32() % 3 != 0) || it == feeset.end()) {
971  it--;
972  }
973  return static_cast<CAmount>(*it);
974 }
static constexpr double MED_DECAY
Decay of .9952 is a half-life of 144 blocks or about 1 day.
Definition: fees.h:142
EstimatorBucket pass
Definition: fees.h:62
std::vector< std::vector< double > > failAvg
Definition: fees.cpp:54
std::deque< CInv >::iterator it
EstimationResult est
Definition: fees.h:70
bool processBlockTx(unsigned int nBlockHeight, const CTxMemPoolEntry *entry) EXCLUSIVE_LOCKS_REQUIRED(m_cs_fee_estimator)
Process a transaction confirmed in a block.
Definition: fees.cpp:548
#define LogPrint(category,...)
Definition: logging.h:182
int returnedTarget
Definition: fees.h:73
static constexpr double MAX_BUCKET_FEERATE
Definition: fees.h:166
static constexpr double HALF_SUCCESS_PCT
Require greater than 60% of X feerate transactions to be confirmed within Y/2 blocks.
Definition: fees.h:147
size_t GetTxSize() const
Definition: txmempool.cpp:52
static constexpr unsigned int MED_BLOCK_PERIODS
Track confirm delays up to 48 blocks for medium horizon.
Definition: fees.h:131
double start
Definition: fees.h:51
bool removeTx(uint256 hash, bool inBlock)
Remove a transaction from the mempool tracking stats.
Definition: fees.cpp:472
CBlockPolicyEstimator()
Create new BlockPolicyEstimator and initialize stats tracking classes with default values...
Definition: fees.cpp:487
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:137
double estimateConservativeFee(unsigned int doubleTarget, EstimationResult *result) const EXCLUSIVE_LOCKS_REQUIRED(m_cs_fee_estimator)
Helper for estimateSmartFee.
Definition: fees.cpp:757
bool Write(CAutoFile &fileout) const
Write estimation data to a file.
Definition: fees.cpp:860
void FlushUnconfirmed()
Empty mempool transactions on shutdown to record failure to confirm for txs still in mempool...
Definition: fees.cpp:945
unsigned int HistoricalBlockSpan() const EXCLUSIVE_LOCKS_REQUIRED(m_cs_fee_estimator)
Number of blocks of recorded fee estimate data represented in saved data file.
Definition: fees.cpp:698
FeeReason reason
Definition: fees.h:71
We will instantiate an instance of this class to track transactions that were included in a block...
Definition: fees.cpp:36
static void LogPrintf(const char *fmt, const Args &... args)
Definition: logging.h:166
std::string StringForFeeEstimateHorizon(FeeEstimateHorizon horizon)
Definition: fees.cpp:15
static constexpr double DOUBLE_SUCCESS_PCT
Require greater than 95% of X feerate transactions to be confirmed within 2 * Y blocks.
Definition: fees.h:151
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:173
unsigned int MaxUsableEstimate() const EXCLUSIVE_LOCKS_REQUIRED(m_cs_fee_estimator)
Calculation of highest target that reasonable estimate can be provided for.
Definition: fees.cpp:708
double decay
Definition: fees.cpp:63
void Record(int blocksToConfirm, double val)
Record a new transaction data point in the current block stats.
Definition: fees.cpp:175
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:165
double withinTarget
Definition: fees.h:53
void resizeInMemoryCounters(size_t newbuckets)
Definition: fees.cpp:156
void ClearCurrent(unsigned int nBlockHeight)
Roll the circular buffer for unconfirmed txs.
Definition: fees.cpp:166
int desiredTarget
Definition: fees.h:72
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:156
CTxMemPoolEntry stores data about the corresponding transaction, as well as data about all in-mempool...
Definition: txmempool.h:78
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
static constexpr double SUCCESS_PCT
Require greater than 85% of X feerate transactions to be confirmed within Y blocks.
Definition: fees.h:149
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:366
double EstimateMedianVal(int confTarget, double sufficientTxVal, double minSuccess, unsigned int nBlockHeight, EstimationResult *result=nullptr) const
Calculate a feerate estimate.
Definition: fees.cpp:203
const std::map< double, unsigned int > & bucketMap
Definition: fees.cpp:41
static constexpr unsigned int SHORT_SCALE
Definition: fees.h:129
static constexpr double LONG_DECAY
Decay of .99931 is a half-life of 1008 blocks or about 1 week.
Definition: fees.h:144
std::vector< std::vector< double > > confAvg
Definition: fees.cpp:50
unsigned int NewTx(unsigned int nBlockHeight, double val)
Record a new transaction entering the mempool.
Definition: fees.cpp:422
unsigned int GetHeight() const
Definition: txmempool.h:125
double end
Definition: fees.h:52
EstimatorBucket fail
Definition: fees.h:63
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:633
#define LOCK(cs)
Definition: sync.h:230
void removeTx(unsigned int entryHeight, unsigned int nBestSeenHeight, unsigned int bucketIndex, bool inBlock)
Remove a transaction from mempool tracking stats.
Definition: fees.cpp:430
const uint256 & GetHash() const
Definition: transaction.h:311
const CAmount & GetFee() const
Definition: txmempool.h:121
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:781
unsigned int scale
Definition: fees.cpp:66
const std::vector< double > & buckets
Definition: fees.cpp:40
unsigned int BlockSpan() const EXCLUSIVE_LOCKS_REQUIRED(m_cs_fee_estimator)
Number of blocks of data recorded while fee estimates have been running.
Definition: fees.cpp:690
double inMempool
Definition: fees.h:55
double estimateCombinedFee(unsigned int confTarget, double successThreshold, bool checkShorterHorizon, EstimationResult *result) const EXCLUSIVE_LOCKS_REQUIRED(m_cs_fee_estimator)
Helper for estimateSmartFee.
Definition: fees.cpp:718
std::string ToString() const
Definition: uint256.cpp:64
FeeFilterRounder(const CFeeRate &minIncrementalFee)
Create new FeeFilterRounder.
Definition: fees.cpp:958
CFeeRate estimateFee(int confTarget) const
DEPRECATED.
Definition: fees.cpp:624
static constexpr unsigned int LONG_SCALE
Definition: fees.h:135
int64_t GetTimeMicros()
Returns the system time (not mockable)
Definition: time.cpp:65
FeeEstimateHorizon
Definition: fees.h:27
std::vector< std::vector< int > > unconfTxs
Definition: fees.cpp:71
unsigned int HighestTargetTracked(FeeEstimateHorizon horizon) const
Calculation of highest target that estimates are tracked for.
Definition: fees.cpp:671
256-bit opaque blob.
Definition: uint256.h:124
static constexpr unsigned int MED_SCALE
Definition: fees.h:132
static const unsigned int OLDEST_ESTIMATE_HISTORY
Historical estimates that are older than this aren&#39;t valid.
Definition: fees.h:137
std::vector< int > oldUnconfTxs
Definition: fees.cpp:73
void processBlock(unsigned int nBlockHeight, std::vector< const CTxMemPoolEntry *> &entries)
Process all the transactions that have been included in a block.
Definition: fees.cpp:575
const CTransaction & GetTx() const
Definition: txmempool.h:119
bool Read(CAutoFile &filein)
Read estimation data from a file.
Definition: fees.cpp:885
double leftMempool
Definition: fees.h:56
unsigned int GetMaxConfirms() const
Return the max number of confirms we&#39;re tracking.
Definition: fees.cpp:124
static constexpr unsigned int LONG_BLOCK_PERIODS
Track confirm delays up to 1008 blocks for long horizon.
Definition: fees.h:134
Fee rate in satoshis per kilobyte: CAmount / kB.
Definition: feerate.h:29
RecursiveMutex m_cs_fee_estimator
Definition: fees.h:219
static constexpr unsigned int SHORT_BLOCK_PERIODS
Track confirm delays up to 12 blocks for short horizon.
Definition: fees.h:128
static constexpr double INF_FEERATE
Definition: fees.cpp:13
double totalConfirmed
Definition: fees.h:54
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:154
std::vector< double > m_feerate_avg
Definition: fees.cpp:58
CAmount round(CAmount currentMinFee)
Quantize a minimum fee for privacy purpose before broadcast.
Definition: fees.cpp:967
static constexpr double SHORT_DECAY
Decay of .962 is a half-life of 18 blocks or about 3 hours.
Definition: fees.h:140
void Write(CAutoFile &fileout) const
Write state of estimation data to a file.
Definition: fees.cpp:356
std::vector< double > txCtAvg
Definition: fees.cpp:46
void UpdateMovingAverages()
Update our estimates by decaying our historical moving average and updating with the data gathered fr...
Definition: fees.cpp:189
static const int CLIENT_VERSION
bitcoind-res.rc includes this file, but it cannot cope with real c++ code.
Definition: clientversion.h:38
unsigned int scale
Definition: fees.h:65
bool error(const char *fmt, const Args &... args)
Definition: system.h:52
CAmount GetFeePerK() const
Return the fee in satoshis for a size of 1000 bytes.
Definition: feerate.h:51
Non-refcounted RAII wrapper for FILE*.
Definition: streams.h:602
void processTransaction(const CTxMemPoolEntry &entry, bool validFeeEstimate)
Process a transaction accepted to the mempool.
Definition: fees.cpp:509
double decay
Definition: fees.h:64