LCOV - code coverage report
Current view: top level - src/policy - fees.cpp (source / functions) Coverage Total Hit
Test: test_bitcoin_coverage.info Lines: 51.4 % 552 284
Test Date: 2024-08-28 04:44:32 Functions: 59.5 % 42 25
Branches: 26.9 % 562 151

             Branch data     Line data    Source code
       1                 :             : // Copyright (c) 2009-2010 Satoshi Nakamoto
       2                 :             : // Copyright (c) 2009-2022 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 <common/system.h>
      10                 :             : #include <consensus/amount.h>
      11                 :             : #include <kernel/mempool_entry.h>
      12                 :             : #include <logging.h>
      13                 :             : #include <policy/feerate.h>
      14                 :             : #include <primitives/transaction.h>
      15                 :             : #include <random.h>
      16                 :             : #include <serialize.h>
      17                 :             : #include <streams.h>
      18                 :             : #include <sync.h>
      19                 :             : #include <tinyformat.h>
      20                 :             : #include <uint256.h>
      21                 :             : #include <util/fs.h>
      22                 :             : #include <util/serfloat.h>
      23                 :             : #include <util/time.h>
      24                 :             : 
      25                 :             : #include <algorithm>
      26                 :             : #include <cassert>
      27                 :             : #include <chrono>
      28                 :             : #include <cmath>
      29                 :             : #include <cstddef>
      30                 :             : #include <cstdint>
      31                 :             : #include <exception>
      32                 :             : #include <stdexcept>
      33                 :             : #include <utility>
      34                 :             : 
      35                 :             : static constexpr double INF_FEERATE = 1e99;
      36                 :             : 
      37                 :           0 : std::string StringForFeeEstimateHorizon(FeeEstimateHorizon horizon)
      38                 :             : {
      39   [ #  #  #  # ]:           0 :     switch (horizon) {
      40                 :           0 :     case FeeEstimateHorizon::SHORT_HALFLIFE: return "short";
      41                 :           0 :     case FeeEstimateHorizon::MED_HALFLIFE: return "medium";
      42                 :           0 :     case FeeEstimateHorizon::LONG_HALFLIFE: return "long";
      43                 :             :     } // no default case, so the compiler can warn about missing cases
      44                 :           0 :     assert(false);
      45                 :             : }
      46                 :             : 
      47                 :             : namespace {
      48                 :             : 
      49                 :             : struct EncodedDoubleFormatter
      50                 :             : {
      51                 :           0 :     template<typename Stream> void Ser(Stream &s, double v)
      52                 :             :     {
      53                 :           0 :         s << EncodeDouble(v);
      54                 :             :     }
      55                 :             : 
      56                 :           0 :     template<typename Stream> void Unser(Stream& s, double& v)
      57                 :             :     {
      58                 :             :         uint64_t encoded;
      59                 :           0 :         s >> encoded;
      60                 :           0 :         v = DecodeDouble(encoded);
      61                 :           0 :     }
      62                 :             : };
      63                 :             : 
      64                 :             : } // namespace
      65                 :             : 
      66                 :             : /**
      67                 :             :  * We will instantiate an instance of this class to track transactions that were
      68                 :             :  * included in a block. We will lump transactions into a bucket according to their
      69                 :             :  * approximate feerate and then track how long it took for those txs to be included in a block
      70                 :             :  *
      71                 :             :  * The tracking of unconfirmed (mempool) transactions is completely independent of the
      72                 :             :  * historical tracking of transactions that have been confirmed in a block.
      73                 :             :  */
      74                 :             : class TxConfirmStats
      75                 :             : {
      76                 :             : private:
      77                 :             :     //Define the buckets we will group transactions into
      78                 :             :     const std::vector<double>& buckets;              // The upper-bound of the range for the bucket (inclusive)
      79                 :             :     const std::map<double, unsigned int>& bucketMap; // Map of bucket upper-bound to index into all vectors by bucket
      80                 :             : 
      81                 :             :     // For each bucket X:
      82                 :             :     // Count the total # of txs in each bucket
      83                 :             :     // Track the historical moving average of this total over blocks
      84                 :             :     std::vector<double> txCtAvg;
      85                 :             : 
      86                 :             :     // Count the total # of txs confirmed within Y blocks in each bucket
      87                 :             :     // Track the historical moving average of these totals over blocks
      88                 :             :     std::vector<std::vector<double>> confAvg; // confAvg[Y][X]
      89                 :             : 
      90                 :             :     // Track moving avg of txs which have been evicted from the mempool
      91                 :             :     // after failing to be confirmed within Y blocks
      92                 :             :     std::vector<std::vector<double>> failAvg; // failAvg[Y][X]
      93                 :             : 
      94                 :             :     // Sum the total feerate of all tx's in each bucket
      95                 :             :     // Track the historical moving average of this total over blocks
      96                 :             :     std::vector<double> m_feerate_avg;
      97                 :             : 
      98                 :             :     // Combine the conf counts with tx counts to calculate the confirmation % for each Y,X
      99                 :             :     // Combine the total value with the tx counts to calculate the avg feerate per bucket
     100                 :             : 
     101                 :             :     double decay;
     102                 :             : 
     103                 :             :     // Resolution (# of blocks) with which confirmations are tracked
     104                 :             :     unsigned int scale;
     105                 :             : 
     106                 :             :     // Mempool counts of outstanding transactions
     107                 :             :     // For each bucket X, track the number of transactions in the mempool
     108                 :             :     // that are unconfirmed for each possible confirmation value Y
     109                 :             :     std::vector<std::vector<int> > unconfTxs;  //unconfTxs[Y][X]
     110                 :             :     // transactions still unconfirmed after GetMaxConfirms for each bucket
     111                 :             :     std::vector<int> oldUnconfTxs;
     112                 :             : 
     113                 :             :     void resizeInMemoryCounters(size_t newbuckets);
     114                 :             : 
     115                 :             : public:
     116                 :             :     /**
     117                 :             :      * Create new TxConfirmStats. This is called by BlockPolicyEstimator's
     118                 :             :      * constructor with default values.
     119                 :             :      * @param defaultBuckets contains the upper limits for the bucket boundaries
     120                 :             :      * @param maxPeriods max number of periods to track
     121                 :             :      * @param decay how much to decay the historical moving average per block
     122                 :             :      */
     123                 :             :     TxConfirmStats(const std::vector<double>& defaultBuckets, const std::map<double, unsigned int>& defaultBucketMap,
     124                 :             :                    unsigned int maxPeriods, double decay, unsigned int scale);
     125                 :             : 
     126                 :             :     /** Roll the circular buffer for unconfirmed txs*/
     127                 :             :     void ClearCurrent(unsigned int nBlockHeight);
     128                 :             : 
     129                 :             :     /**
     130                 :             :      * Record a new transaction data point in the current block stats
     131                 :             :      * @param blocksToConfirm the number of blocks it took this transaction to confirm
     132                 :             :      * @param val the feerate of the transaction
     133                 :             :      * @warning blocksToConfirm is 1-based and has to be >= 1
     134                 :             :      */
     135                 :             :     void Record(int blocksToConfirm, double val);
     136                 :             : 
     137                 :             :     /** Record a new transaction entering the mempool*/
     138                 :             :     unsigned int NewTx(unsigned int nBlockHeight, double val);
     139                 :             : 
     140                 :             :     /** Remove a transaction from mempool tracking stats*/
     141                 :             :     void removeTx(unsigned int entryHeight, unsigned int nBestSeenHeight,
     142                 :             :                   unsigned int bucketIndex, bool inBlock);
     143                 :             : 
     144                 :             :     /** Update our estimates by decaying our historical moving average and updating
     145                 :             :         with the data gathered from the current block */
     146                 :             :     void UpdateMovingAverages();
     147                 :             : 
     148                 :             :     /**
     149                 :             :      * Calculate a feerate estimate.  Find the lowest value bucket (or range of buckets
     150                 :             :      * to make sure we have enough data points) whose transactions still have sufficient likelihood
     151                 :             :      * of being confirmed within the target number of confirmations
     152                 :             :      * @param confTarget target number of confirmations
     153                 :             :      * @param sufficientTxVal required average number of transactions per block in a bucket range
     154                 :             :      * @param minSuccess the success probability we require
     155                 :             :      * @param nBlockHeight the current block height
     156                 :             :      */
     157                 :             :     double EstimateMedianVal(int confTarget, double sufficientTxVal,
     158                 :             :                              double minSuccess, unsigned int nBlockHeight,
     159                 :             :                              EstimationResult *result = nullptr) const;
     160                 :             : 
     161                 :             :     /** Return the max number of confirms we're tracking */
     162   [ -  -  -  -  :         753 :     unsigned int GetMaxConfirms() const { return scale * confAvg.size(); }
          -  -  -  -  -  
          -  -  -  -  -  
          -  -  -  +  +  
                      - ]
     163                 :             : 
     164                 :             :     /** Write state of estimation data to a file*/
     165                 :             :     void Write(AutoFile& fileout) const;
     166                 :             : 
     167                 :             :     /**
     168                 :             :      * Read saved state of estimation data from a file and replace all internal data structures and
     169                 :             :      * variables with this state.
     170                 :             :      */
     171                 :             :     void Read(AutoFile& filein, int nFileVersion, size_t numBuckets);
     172                 :             : };
     173                 :             : 
     174                 :             : 
     175                 :           3 : TxConfirmStats::TxConfirmStats(const std::vector<double>& defaultBuckets,
     176                 :             :                                 const std::map<double, unsigned int>& defaultBucketMap,
     177                 :           3 :                                unsigned int maxPeriods, double _decay, unsigned int _scale)
     178         [ -  + ]:           3 :     : buckets(defaultBuckets), bucketMap(defaultBucketMap), decay(_decay), scale(_scale)
     179                 :             : {
     180         [ -  + ]:           3 :     assert(_scale != 0 && "_scale must be non-zero");
     181         [ +  - ]:           3 :     confAvg.resize(maxPeriods);
     182         [ +  - ]:           3 :     failAvg.resize(maxPeriods);
     183         [ +  + ]:          81 :     for (unsigned int i = 0; i < maxPeriods; i++) {
     184         [ +  - ]:          78 :         confAvg[i].resize(buckets.size());
     185         [ +  - ]:          78 :         failAvg[i].resize(buckets.size());
     186                 :             :     }
     187                 :             : 
     188         [ +  - ]:           3 :     txCtAvg.resize(buckets.size());
     189         [ +  - ]:           3 :     m_feerate_avg.resize(buckets.size());
     190                 :             : 
     191         [ +  - ]:           3 :     resizeInMemoryCounters(buckets.size());
     192                 :           3 : }
     193                 :             : 
     194                 :           3 : void TxConfirmStats::resizeInMemoryCounters(size_t newbuckets) {
     195                 :             :     // newbuckets must be passed in because the buckets referred to during Read have not been updated yet.
     196                 :           3 :     unconfTxs.resize(GetMaxConfirms());
     197         [ +  + ]:        1071 :     for (unsigned int i = 0; i < unconfTxs.size(); i++) {
     198                 :        1068 :         unconfTxs[i].resize(newbuckets);
     199                 :             :     }
     200                 :           3 :     oldUnconfTxs.resize(newbuckets);
     201                 :           3 : }
     202                 :             : 
     203                 :             : // Roll the unconfirmed txs circular buffer
     204                 :        1995 : void TxConfirmStats::ClearCurrent(unsigned int nBlockHeight)
     205                 :             : {
     206         [ +  + ]:      381045 :     for (unsigned int j = 0; j < buckets.size(); j++) {
     207                 :      379050 :         oldUnconfTxs[j] += unconfTxs[nBlockHeight % unconfTxs.size()][j];
     208                 :      379050 :         unconfTxs[nBlockHeight%unconfTxs.size()][j] = 0;
     209                 :             :     }
     210                 :        1995 : }
     211                 :             : 
     212                 :             : 
     213                 :       73680 : void TxConfirmStats::Record(int blocksToConfirm, double feerate)
     214                 :             : {
     215                 :             :     // blocksToConfirm is 1-based
     216         [ +  - ]:       73680 :     if (blocksToConfirm < 1)
     217                 :             :         return;
     218                 :       73680 :     int periodsToConfirm = (blocksToConfirm + scale - 1) / scale;
     219                 :       73680 :     unsigned int bucketindex = bucketMap.lower_bound(feerate)->second;
     220         [ +  + ]:     1963760 :     for (size_t i = periodsToConfirm; i <= confAvg.size(); i++) {
     221                 :     1890080 :         confAvg[i - 1][bucketindex]++;
     222                 :             :     }
     223                 :       73680 :     txCtAvg[bucketindex]++;
     224                 :       73680 :     m_feerate_avg[bucketindex] += feerate;
     225                 :             : }
     226                 :             : 
     227                 :        1995 : void TxConfirmStats::UpdateMovingAverages()
     228                 :             : {
     229         [ +  - ]:        1995 :     assert(confAvg.size() == failAvg.size());
     230         [ +  + ]:      381045 :     for (unsigned int j = 0; j < buckets.size(); j++) {
     231         [ +  + ]:    10234350 :         for (unsigned int i = 0; i < confAvg.size(); i++) {
     232                 :     9855300 :             confAvg[i][j] *= decay;
     233                 :     9855300 :             failAvg[i][j] *= decay;
     234                 :             :         }
     235                 :      379050 :         m_feerate_avg[j] *= decay;
     236                 :      379050 :         txCtAvg[j] *= decay;
     237                 :             :     }
     238                 :        1995 : }
     239                 :             : 
     240                 :             : // returns -1 on error conditions
     241                 :          88 : double TxConfirmStats::EstimateMedianVal(int confTarget, double sufficientTxVal,
     242                 :             :                                          double successBreakPoint, unsigned int nBlockHeight,
     243                 :             :                                          EstimationResult *result) const
     244                 :             : {
     245                 :             :     // Counters for a bucket (or range of buckets)
     246                 :          88 :     double nConf = 0; // Number of tx's confirmed within the confTarget
     247                 :          88 :     double totalNum = 0; // Total number of tx's that were ever confirmed
     248                 :          88 :     int extraNum = 0;  // Number of tx's still in mempool for confTarget or longer
     249                 :          88 :     double failNum = 0; // Number of tx's that were never confirmed but removed from the mempool after confTarget
     250                 :          88 :     const int periodTarget = (confTarget + scale - 1) / scale;
     251                 :          88 :     const int maxbucketindex = buckets.size() - 1;
     252                 :             : 
     253                 :             :     // We'll combine buckets until we have enough samples.
     254                 :             :     // The near and far variables will define the range we've combined
     255                 :             :     // The best variables are the last range we saw which still had a high
     256                 :             :     // enough confirmation rate to count as success.
     257                 :             :     // The cur variables are the current range we're counting.
     258                 :          88 :     unsigned int curNearBucket = maxbucketindex;
     259                 :          88 :     unsigned int bestNearBucket = maxbucketindex;
     260                 :          88 :     unsigned int curFarBucket = maxbucketindex;
     261                 :          88 :     unsigned int bestFarBucket = maxbucketindex;
     262                 :             : 
     263                 :             :     // We'll always group buckets into sets that meet sufficientTxVal --
     264                 :             :     // this ensures that we're using consistent groups between different
     265                 :             :     // confirmation targets.
     266                 :          88 :     double partialNum = 0;
     267                 :             : 
     268                 :          88 :     bool foundAnswer = false;
     269                 :          88 :     unsigned int bins = unconfTxs.size();
     270                 :          88 :     bool newBucketRange = true;
     271                 :          88 :     bool passing = true;
     272                 :          88 :     EstimatorBucket passBucket;
     273                 :          88 :     EstimatorBucket failBucket;
     274                 :             : 
     275                 :             :     // Start counting from highest feerate transactions
     276         [ +  + ]:       16808 :     for (int bucket = maxbucketindex; bucket >= 0; --bucket) {
     277         [ +  + ]:       16720 :         if (newBucketRange) {
     278                 :         689 :             curNearBucket = bucket;
     279                 :         689 :             newBucketRange = false;
     280                 :             :         }
     281                 :       16720 :         curFarBucket = bucket;
     282                 :       16720 :         nConf += confAvg[periodTarget - 1][bucket];
     283                 :       16720 :         partialNum += txCtAvg[bucket];
     284                 :       16720 :         totalNum += txCtAvg[bucket];
     285                 :       16720 :         failNum += failAvg[periodTarget - 1][bucket];
     286         [ +  + ]:      555180 :         for (unsigned int confct = confTarget; confct < GetMaxConfirms(); confct++)
     287                 :      538460 :             extraNum += unconfTxs[(nBlockHeight - confct) % bins][bucket];
     288         [ +  + ]:       16720 :         extraNum += oldUnconfTxs[bucket];
     289                 :             :         // If we have enough transaction data points in this range of buckets,
     290                 :             :         // we can test for success
     291                 :             :         // (Only count the confirmed data points, so that each confirmation count
     292                 :             :         // will be looking at the same amount of data and same bucket breaks)
     293                 :             : 
     294         [ +  + ]:       16720 :         if (partialNum < sufficientTxVal / (1 - decay)) {
     295                 :             :             // the buckets we've added in this round aren't sufficient
     296                 :             :             // so keep adding
     297                 :       15858 :             continue;
     298                 :             :         } else {
     299                 :         862 :             partialNum = 0; // reset for the next range we'll add
     300                 :             : 
     301                 :         862 :             double curPct = nConf / (totalNum + failNum + extraNum);
     302                 :             : 
     303                 :             :             // Check to see if we are no longer getting confirmed at the success rate
     304         [ +  + ]:         862 :             if (curPct < successBreakPoint) {
     305         [ +  + ]:         261 :                 if (passing == true) {
     306                 :             :                     // First time we hit a failure record the failed bucket
     307         [ -  + ]:          40 :                     unsigned int failMinBucket = std::min(curNearBucket, curFarBucket);
     308         [ +  - ]:          40 :                     unsigned int failMaxBucket = std::max(curNearBucket, curFarBucket);
     309         [ +  - ]:          40 :                     failBucket.start = failMinBucket ? buckets[failMinBucket - 1] : 0;
     310                 :          40 :                     failBucket.end = buckets[failMaxBucket];
     311                 :          40 :                     failBucket.withinTarget = nConf;
     312                 :          40 :                     failBucket.totalConfirmed = totalNum;
     313                 :          40 :                     failBucket.inMempool = extraNum;
     314                 :          40 :                     failBucket.leftMempool = failNum;
     315                 :          40 :                     passing = false;
     316                 :             :                 }
     317                 :         261 :                 continue;
     318                 :         261 :             }
     319                 :             :             // Otherwise update the cumulative stats, and the bucket variables
     320                 :             :             // and reset the counters
     321                 :             :             else {
     322                 :         601 :                 failBucket = EstimatorBucket(); // Reset any failed bucket, currently passing
     323                 :         601 :                 foundAnswer = true;
     324                 :         601 :                 passing = true;
     325                 :         601 :                 passBucket.withinTarget = nConf;
     326                 :         601 :                 nConf = 0;
     327                 :         601 :                 passBucket.totalConfirmed = totalNum;
     328                 :         601 :                 totalNum = 0;
     329                 :         601 :                 passBucket.inMempool = extraNum;
     330                 :         601 :                 passBucket.leftMempool = failNum;
     331                 :         601 :                 failNum = 0;
     332                 :         601 :                 extraNum = 0;
     333                 :         601 :                 bestNearBucket = curNearBucket;
     334                 :         601 :                 bestFarBucket = curFarBucket;
     335                 :         601 :                 newBucketRange = true;
     336                 :             :             }
     337                 :             :         }
     338                 :             :     }
     339                 :             : 
     340                 :          88 :     double median = -1;
     341                 :          88 :     double txSum = 0;
     342                 :             : 
     343                 :             :     // Calculate the "average" feerate of the best bucket range that met success conditions
     344                 :             :     // Find the bucket with the median transaction and then report the average feerate from that bucket
     345                 :             :     // This is a compromise between finding the median which we can't since we don't save all tx's
     346                 :             :     // and reporting the average which is less accurate
     347         [ +  + ]:          88 :     unsigned int minBucket = std::min(bestNearBucket, bestFarBucket);
     348         [ +  - ]:          88 :     unsigned int maxBucket = std::max(bestNearBucket, bestFarBucket);
     349         [ +  + ]:        1045 :     for (unsigned int j = minBucket; j <= maxBucket; j++) {
     350                 :         957 :         txSum += txCtAvg[j];
     351                 :             :     }
     352         [ +  + ]:          88 :     if (foundAnswer && txSum != 0) {
     353                 :          72 :         txSum = txSum / 2;
     354         [ +  - ]:          72 :         for (unsigned int j = minBucket; j <= maxBucket; j++) {
     355         [ -  + ]:          72 :             if (txCtAvg[j] < txSum)
     356                 :           0 :                 txSum -= txCtAvg[j];
     357                 :             :             else { // we're in the right bucket
     358                 :          72 :                 median = m_feerate_avg[j] / txCtAvg[j];
     359                 :          72 :                 break;
     360                 :             :             }
     361                 :             :         }
     362                 :             : 
     363         [ +  - ]:          72 :         passBucket.start = minBucket ? buckets[minBucket-1] : 0;
     364                 :          72 :         passBucket.end = buckets[maxBucket];
     365                 :             :     }
     366                 :             : 
     367                 :             :     // If we were passing until we reached last few buckets with insufficient data, then report those as failed
     368         [ +  + ]:          88 :     if (passing && !newBucketRange) {
     369         [ -  + ]:          48 :         unsigned int failMinBucket = std::min(curNearBucket, curFarBucket);
     370         [ +  - ]:          48 :         unsigned int failMaxBucket = std::max(curNearBucket, curFarBucket);
     371         [ -  + ]:          48 :         failBucket.start = failMinBucket ? buckets[failMinBucket - 1] : 0;
     372                 :          48 :         failBucket.end = buckets[failMaxBucket];
     373                 :          48 :         failBucket.withinTarget = nConf;
     374                 :          48 :         failBucket.totalConfirmed = totalNum;
     375                 :          48 :         failBucket.inMempool = extraNum;
     376                 :          48 :         failBucket.leftMempool = failNum;
     377                 :             :     }
     378                 :             : 
     379                 :          88 :     float passed_within_target_perc = 0.0;
     380                 :          88 :     float failed_within_target_perc = 0.0;
     381         [ +  + ]:          88 :     if ((passBucket.totalConfirmed + passBucket.inMempool + passBucket.leftMempool)) {
     382                 :          72 :         passed_within_target_perc = 100 * passBucket.withinTarget / (passBucket.totalConfirmed + passBucket.inMempool + passBucket.leftMempool);
     383                 :             :     }
     384         [ +  + ]:          88 :     if ((failBucket.totalConfirmed + failBucket.inMempool + failBucket.leftMempool)) {
     385                 :          42 :         failed_within_target_perc = 100 * failBucket.withinTarget / (failBucket.totalConfirmed + failBucket.inMempool + failBucket.leftMempool);
     386                 :             :     }
     387                 :             : 
     388         [ +  - ]:          88 :     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",
     389                 :             :              confTarget, 100.0 * successBreakPoint, decay,
     390                 :             :              median, passBucket.start, passBucket.end,
     391                 :             :              passed_within_target_perc,
     392                 :             :              passBucket.withinTarget, passBucket.totalConfirmed, passBucket.inMempool, passBucket.leftMempool,
     393                 :             :              failBucket.start, failBucket.end,
     394                 :             :              failed_within_target_perc,
     395                 :             :              failBucket.withinTarget, failBucket.totalConfirmed, failBucket.inMempool, failBucket.leftMempool);
     396                 :             : 
     397                 :             : 
     398         [ -  + ]:          88 :     if (result) {
     399                 :           0 :         result->pass = passBucket;
     400                 :           0 :         result->fail = failBucket;
     401                 :           0 :         result->decay = decay;
     402                 :           0 :         result->scale = scale;
     403                 :             :     }
     404                 :          88 :     return median;
     405                 :             : }
     406                 :             : 
     407                 :           0 : void TxConfirmStats::Write(AutoFile& fileout) const
     408                 :             : {
     409                 :           0 :     fileout << Using<EncodedDoubleFormatter>(decay);
     410                 :           0 :     fileout << scale;
     411                 :           0 :     fileout << Using<VectorFormatter<EncodedDoubleFormatter>>(m_feerate_avg);
     412                 :           0 :     fileout << Using<VectorFormatter<EncodedDoubleFormatter>>(txCtAvg);
     413                 :           0 :     fileout << Using<VectorFormatter<VectorFormatter<EncodedDoubleFormatter>>>(confAvg);
     414                 :           0 :     fileout << Using<VectorFormatter<VectorFormatter<EncodedDoubleFormatter>>>(failAvg);
     415                 :           0 : }
     416                 :             : 
     417                 :           0 : void TxConfirmStats::Read(AutoFile& filein, int nFileVersion, size_t numBuckets)
     418                 :             : {
     419                 :             :     // Read data file and do some very basic sanity checking
     420                 :             :     // buckets and bucketMap are not updated yet, so don't access them
     421                 :             :     // If there is a read failure, we'll just discard this entire object anyway
     422                 :           0 :     size_t maxConfirms, maxPeriods;
     423                 :             : 
     424                 :             :     // The current version will store the decay with each individual TxConfirmStats and also keep a scale factor
     425                 :           0 :     filein >> Using<EncodedDoubleFormatter>(decay);
     426   [ #  #  #  # ]:           0 :     if (decay <= 0 || decay >= 1) {
     427         [ #  # ]:           0 :         throw std::runtime_error("Corrupt estimates file. Decay must be between 0 and 1 (non-inclusive)");
     428                 :             :     }
     429                 :           0 :     filein >> scale;
     430         [ #  # ]:           0 :     if (scale == 0) {
     431         [ #  # ]:           0 :         throw std::runtime_error("Corrupt estimates file. Scale must be non-zero");
     432                 :             :     }
     433                 :             : 
     434                 :           0 :     filein >> Using<VectorFormatter<EncodedDoubleFormatter>>(m_feerate_avg);
     435         [ #  # ]:           0 :     if (m_feerate_avg.size() != numBuckets) {
     436         [ #  # ]:           0 :         throw std::runtime_error("Corrupt estimates file. Mismatch in feerate average bucket count");
     437                 :             :     }
     438                 :           0 :     filein >> Using<VectorFormatter<EncodedDoubleFormatter>>(txCtAvg);
     439         [ #  # ]:           0 :     if (txCtAvg.size() != numBuckets) {
     440         [ #  # ]:           0 :         throw std::runtime_error("Corrupt estimates file. Mismatch in tx count bucket count");
     441                 :             :     }
     442                 :           0 :     filein >> Using<VectorFormatter<VectorFormatter<EncodedDoubleFormatter>>>(confAvg);
     443         [ #  # ]:           0 :     maxPeriods = confAvg.size();
     444                 :           0 :     maxConfirms = scale * maxPeriods;
     445                 :             : 
     446         [ #  # ]:           0 :     if (maxConfirms <= 0 || maxConfirms > 6 * 24 * 7) { // one week
     447         [ #  # ]:           0 :         throw std::runtime_error("Corrupt estimates file.  Must maintain estimates for between 1 and 1008 (one week) confirms");
     448                 :             :     }
     449         [ #  # ]:           0 :     for (unsigned int i = 0; i < maxPeriods; i++) {
     450         [ #  # ]:           0 :         if (confAvg[i].size() != numBuckets) {
     451         [ #  # ]:           0 :             throw std::runtime_error("Corrupt estimates file. Mismatch in feerate conf average bucket count");
     452                 :             :         }
     453                 :             :     }
     454                 :             : 
     455                 :           0 :     filein >> Using<VectorFormatter<VectorFormatter<EncodedDoubleFormatter>>>(failAvg);
     456         [ #  # ]:           0 :     if (maxPeriods != failAvg.size()) {
     457         [ #  # ]:           0 :         throw std::runtime_error("Corrupt estimates file. Mismatch in confirms tracked for failures");
     458                 :             :     }
     459         [ #  # ]:           0 :     for (unsigned int i = 0; i < maxPeriods; i++) {
     460         [ #  # ]:           0 :         if (failAvg[i].size() != numBuckets) {
     461         [ #  # ]:           0 :             throw std::runtime_error("Corrupt estimates file. Mismatch in one of failure average bucket counts");
     462                 :             :         }
     463                 :             :     }
     464                 :             : 
     465                 :             :     // Resize the current block variables which aren't stored in the data file
     466                 :             :     // to match the number of confirms and buckets
     467                 :           0 :     resizeInMemoryCounters(numBuckets);
     468                 :             : 
     469         [ #  # ]:           0 :     LogPrint(BCLog::ESTIMATEFEE, "Reading estimates: %u buckets counting confirms up to %u blocks\n",
     470                 :             :              numBuckets, maxConfirms);
     471                 :           0 : }
     472                 :             : 
     473                 :       73680 : unsigned int TxConfirmStats::NewTx(unsigned int nBlockHeight, double val)
     474                 :             : {
     475                 :       73680 :     unsigned int bucketindex = bucketMap.lower_bound(val)->second;
     476                 :       73680 :     unsigned int blockIndex = nBlockHeight % unconfTxs.size();
     477                 :       73680 :     unconfTxs[blockIndex][bucketindex]++;
     478                 :       73680 :     return bucketindex;
     479                 :             : }
     480                 :             : 
     481                 :       73680 : void TxConfirmStats::removeTx(unsigned int entryHeight, unsigned int nBestSeenHeight, unsigned int bucketindex, bool inBlock)
     482                 :             : {
     483                 :             :     //nBestSeenHeight is not updated yet for the new block
     484                 :       73680 :     int blocksAgo = nBestSeenHeight - entryHeight;
     485         [ +  - ]:       73680 :     if (nBestSeenHeight == 0)  // the BlockPolicyEstimator hasn't seen any blocks yet
     486                 :             :         blocksAgo = 0;
     487         [ -  + ]:       73680 :     if (blocksAgo < 0) {
     488         [ #  # ]:           0 :         LogPrint(BCLog::ESTIMATEFEE, "Blockpolicy error, blocks ago is negative for mempool tx\n");
     489                 :           0 :         return;  //This can't happen because we call this with our best seen height, no entries can have higher
     490                 :             :     }
     491                 :             : 
     492         [ +  + ]:       73680 :     if (blocksAgo >= (int)unconfTxs.size()) {
     493         [ +  - ]:         200 :         if (oldUnconfTxs[bucketindex] > 0) {
     494                 :         200 :             oldUnconfTxs[bucketindex]--;
     495                 :             :         } else {
     496         [ #  # ]:           0 :             LogPrint(BCLog::ESTIMATEFEE, "Blockpolicy error, mempool tx removed from >25 blocks,bucketIndex=%u already\n",
     497                 :             :                      bucketindex);
     498                 :             :         }
     499                 :             :     }
     500                 :             :     else {
     501         [ +  - ]:       73480 :         unsigned int blockIndex = entryHeight % unconfTxs.size();
     502         [ +  - ]:       73480 :         if (unconfTxs[blockIndex][bucketindex] > 0) {
     503                 :       73480 :             unconfTxs[blockIndex][bucketindex]--;
     504                 :             :         } else {
     505         [ #  # ]:           0 :             LogPrint(BCLog::ESTIMATEFEE, "Blockpolicy error, mempool tx removed from blockIndex=%u,bucketIndex=%u already\n",
     506                 :             :                      blockIndex, bucketindex);
     507                 :             :         }
     508                 :             :     }
     509   [ -  +  -  - ]:       73680 :     if (!inBlock && (unsigned int)blocksAgo >= scale) { // Only counts as a failure if not confirmed for entire period
     510         [ #  # ]:           0 :         assert(scale != 0);
     511                 :           0 :         unsigned int periodsAgo = blocksAgo / scale;
     512   [ #  #  #  # ]:           0 :         for (size_t i = 0; i < periodsAgo && i < failAvg.size(); i++) {
     513                 :           0 :             failAvg[i][bucketindex]++;
     514                 :             :         }
     515                 :             :     }
     516                 :             : }
     517                 :             : 
     518                 :           0 : bool CBlockPolicyEstimator::removeTx(uint256 hash)
     519                 :             : {
     520                 :           0 :     LOCK(m_cs_fee_estimator);
     521   [ #  #  #  # ]:           0 :     return _removeTx(hash, /*inBlock=*/false);
     522                 :           0 : }
     523                 :             : 
     524                 :       24560 : bool CBlockPolicyEstimator::_removeTx(const uint256& hash, bool inBlock)
     525                 :             : {
     526                 :       24560 :     AssertLockHeld(m_cs_fee_estimator);
     527                 :       24560 :     std::map<uint256, TxStatsInfo>::iterator pos = mapMemPoolTxs.find(hash);
     528         [ +  - ]:       24560 :     if (pos != mapMemPoolTxs.end()) {
     529                 :       24560 :         feeStats->removeTx(pos->second.blockHeight, nBestSeenHeight, pos->second.bucketIndex, inBlock);
     530                 :       24560 :         shortStats->removeTx(pos->second.blockHeight, nBestSeenHeight, pos->second.bucketIndex, inBlock);
     531                 :       24560 :         longStats->removeTx(pos->second.blockHeight, nBestSeenHeight, pos->second.bucketIndex, inBlock);
     532                 :       24560 :         mapMemPoolTxs.erase(hash);
     533                 :       24560 :         return true;
     534                 :             :     } else {
     535                 :             :         return false;
     536                 :             :     }
     537                 :             : }
     538                 :             : 
     539                 :           1 : CBlockPolicyEstimator::CBlockPolicyEstimator(const fs::path& estimation_filepath, const bool read_stale_estimates)
     540                 :           1 :     : m_estimation_filepath{estimation_filepath}
     541                 :             : {
     542                 :           1 :     static_assert(MIN_BUCKET_FEERATE > 0, "Min feerate must be nonzero");
     543                 :           1 :     size_t bucketIndex = 0;
     544                 :             : 
     545         [ +  + ]:         190 :     for (double bucketBoundary = MIN_BUCKET_FEERATE; bucketBoundary <= MAX_BUCKET_FEERATE; bucketBoundary *= FEE_SPACING, bucketIndex++) {
     546         [ +  - ]:         189 :         buckets.push_back(bucketBoundary);
     547         [ +  - ]:         189 :         bucketMap[bucketBoundary] = bucketIndex;
     548                 :             :     }
     549         [ +  - ]:           1 :     buckets.push_back(INF_FEERATE);
     550         [ +  - ]:           1 :     bucketMap[INF_FEERATE] = bucketIndex;
     551         [ -  + ]:           1 :     assert(bucketMap.size() == buckets.size());
     552                 :             : 
     553   [ +  -  +  - ]:           1 :     feeStats = std::unique_ptr<TxConfirmStats>(new TxConfirmStats(buckets, bucketMap, MED_BLOCK_PERIODS, MED_DECAY, MED_SCALE));
     554   [ +  -  +  - ]:           1 :     shortStats = std::unique_ptr<TxConfirmStats>(new TxConfirmStats(buckets, bucketMap, SHORT_BLOCK_PERIODS, SHORT_DECAY, SHORT_SCALE));
     555   [ +  -  +  - ]:           1 :     longStats = std::unique_ptr<TxConfirmStats>(new TxConfirmStats(buckets, bucketMap, LONG_BLOCK_PERIODS, LONG_DECAY, LONG_SCALE));
     556                 :             : 
     557         [ +  - ]:           1 :     AutoFile est_file{fsbridge::fopen(m_estimation_filepath, "rb")};
     558                 :             : 
     559         [ +  - ]:           1 :     if (est_file.IsNull()) {
     560   [ +  -  +  - ]:           2 :         LogPrintf("%s is not found. Continue anyway.\n", fs::PathToString(m_estimation_filepath));
     561                 :           1 :         return;
     562                 :             :     }
     563                 :             : 
     564         [ #  # ]:           0 :     std::chrono::hours file_age = GetFeeEstimatorFileAge();
     565   [ #  #  #  # ]:           0 :     if (file_age > MAX_FILE_AGE && !read_stale_estimates) {
     566   [ #  #  #  # ]:           0 :         LogPrintf("Fee estimation file %s too old (age=%lld > %lld hours) and will not be used to avoid serving stale estimates.\n", fs::PathToString(m_estimation_filepath), Ticks<std::chrono::hours>(file_age), Ticks<std::chrono::hours>(MAX_FILE_AGE));
     567                 :           0 :         return;
     568                 :             :     }
     569                 :             : 
     570   [ #  #  #  # ]:           0 :     if (!Read(est_file)) {
     571   [ #  #  #  # ]:           0 :         LogPrintf("Failed to read fee estimates from %s. Continue anyway.\n", fs::PathToString(m_estimation_filepath));
     572                 :             :     }
     573                 :           1 : }
     574                 :             : 
     575                 :           1 : CBlockPolicyEstimator::~CBlockPolicyEstimator() = default;
     576                 :             : 
     577                 :       24600 : void CBlockPolicyEstimator::TransactionAddedToMempool(const NewMempoolTransactionInfo& tx, uint64_t /*unused*/)
     578                 :             : {
     579                 :       24600 :     processTransaction(tx);
     580                 :       24600 : }
     581                 :             : 
     582                 :           0 : void CBlockPolicyEstimator::TransactionRemovedFromMempool(const CTransactionRef& tx, MemPoolRemovalReason /*unused*/, uint64_t /*unused*/)
     583                 :             : {
     584                 :           0 :     removeTx(tx->GetHash());
     585                 :           0 : }
     586                 :             : 
     587                 :         666 : void CBlockPolicyEstimator::MempoolTransactionsRemovedForBlock(const std::vector<RemovedMempoolTransactionInfo>& txs_removed_for_block, unsigned int nBlockHeight)
     588                 :             : {
     589                 :         666 :     processBlock(txs_removed_for_block, nBlockHeight);
     590                 :         666 : }
     591                 :             : 
     592                 :       24600 : void CBlockPolicyEstimator::processTransaction(const NewMempoolTransactionInfo& tx)
     593                 :             : {
     594                 :       24600 :     LOCK(m_cs_fee_estimator);
     595                 :       24600 :     const unsigned int txHeight = tx.info.txHeight;
     596                 :       24600 :     const auto& hash = tx.info.m_tx->GetHash();
     597         [ -  + ]:       24600 :     if (mapMemPoolTxs.count(hash)) {
     598   [ #  #  #  #  :           0 :         LogPrint(BCLog::ESTIMATEFEE, "Blockpolicy error mempool tx %s already being tracked\n",
             #  #  #  # ]
     599                 :             :                  hash.ToString());
     600                 :           0 :         return;
     601                 :             :     }
     602                 :             : 
     603         [ +  + ]:       24600 :     if (txHeight != nBestSeenHeight) {
     604                 :             :         // Ignore side chains and re-orgs; assuming they are random they don't
     605                 :             :         // affect the estimate.  We'll potentially double count transactions in 1-block reorgs.
     606                 :             :         // Ignore txs if BlockPolicyEstimator is not in sync with ActiveChain().Tip().
     607                 :             :         // It will be synced next time a block is processed.
     608                 :             :         return;
     609                 :             :     }
     610                 :             :     // This transaction should only count for fee estimation if:
     611                 :             :     // - it's not being re-added during a reorg which bypasses typical mempool fee limits
     612                 :             :     // - the node is not behind
     613                 :             :     // - the transaction is not dependent on any other transactions in the mempool
     614                 :             :     // - it's not part of a package.
     615   [ +  -  +  -  :       24560 :     const bool validForFeeEstimation = !tx.m_mempool_limit_bypassed && !tx.m_submitted_in_package && tx.m_chainstate_is_current && tx.m_has_no_mempool_parents;
             +  -  +  - ]
     616                 :             : 
     617                 :             :     // Only want to be updating estimates when our blockchain is synced,
     618                 :             :     // otherwise we'll miscalculate how many blocks its taking to get included.
     619                 :       24560 :     if (!validForFeeEstimation) {
     620                 :           0 :         untrackedTxs++;
     621                 :           0 :         return;
     622                 :             :     }
     623                 :       24560 :     trackedTxs++;
     624                 :             : 
     625                 :             :     // Feerates are stored and reported as BTC-per-kb:
     626         [ +  - ]:       24560 :     const CFeeRate feeRate(tx.info.m_fee, tx.info.m_virtual_transaction_size);
     627                 :             : 
     628         [ +  - ]:       24560 :     mapMemPoolTxs[hash].blockHeight = txHeight;
     629                 :       24560 :     unsigned int bucketIndex = feeStats->NewTx(txHeight, static_cast<double>(feeRate.GetFeePerK()));
     630         [ +  - ]:       24560 :     mapMemPoolTxs[hash].bucketIndex = bucketIndex;
     631                 :       24560 :     unsigned int bucketIndex2 = shortStats->NewTx(txHeight, static_cast<double>(feeRate.GetFeePerK()));
     632         [ -  + ]:       24560 :     assert(bucketIndex == bucketIndex2);
     633                 :       24560 :     unsigned int bucketIndex3 = longStats->NewTx(txHeight, static_cast<double>(feeRate.GetFeePerK()));
     634         [ -  + ]:       24560 :     assert(bucketIndex == bucketIndex3);
     635                 :       24600 : }
     636                 :             : 
     637                 :       24560 : bool CBlockPolicyEstimator::processBlockTx(unsigned int nBlockHeight, const RemovedMempoolTransactionInfo& tx)
     638                 :             : {
     639                 :       24560 :     AssertLockHeld(m_cs_fee_estimator);
     640         [ +  - ]:       24560 :     if (!_removeTx(tx.info.m_tx->GetHash(), true)) {
     641                 :             :         // This transaction wasn't being tracked for fee estimation
     642                 :             :         return false;
     643                 :             :     }
     644                 :             : 
     645                 :             :     // How many blocks did it take for miners to include this transaction?
     646                 :             :     // blocksToConfirm is 1-based, so a transaction included in the earliest
     647                 :             :     // possible block has confirmation count of 1
     648                 :       24560 :     int blocksToConfirm = nBlockHeight - tx.info.txHeight;
     649         [ -  + ]:       24560 :     if (blocksToConfirm <= 0) {
     650                 :             :         // This can't happen because we don't process transactions from a block with a height
     651                 :             :         // lower than our greatest seen height
     652         [ #  # ]:           0 :         LogPrint(BCLog::ESTIMATEFEE, "Blockpolicy error Transaction had negative blocksToConfirm\n");
     653                 :           0 :         return false;
     654                 :             :     }
     655                 :             : 
     656                 :             :     // Feerates are stored and reported as BTC-per-kb:
     657                 :       24560 :     CFeeRate feeRate(tx.info.m_fee, tx.info.m_virtual_transaction_size);
     658                 :             : 
     659                 :       24560 :     feeStats->Record(blocksToConfirm, static_cast<double>(feeRate.GetFeePerK()));
     660                 :       24560 :     shortStats->Record(blocksToConfirm, static_cast<double>(feeRate.GetFeePerK()));
     661                 :       24560 :     longStats->Record(blocksToConfirm, static_cast<double>(feeRate.GetFeePerK()));
     662                 :       24560 :     return true;
     663                 :             : }
     664                 :             : 
     665                 :         666 : void CBlockPolicyEstimator::processBlock(const std::vector<RemovedMempoolTransactionInfo>& txs_removed_for_block,
     666                 :             :                                          unsigned int nBlockHeight)
     667                 :             : {
     668                 :         666 :     LOCK(m_cs_fee_estimator);
     669         [ +  + ]:         666 :     if (nBlockHeight <= nBestSeenHeight) {
     670                 :             :         // Ignore side chains and re-orgs; assuming they are random
     671                 :             :         // they don't affect the estimate.
     672                 :             :         // And if an attacker can re-org the chain at will, then
     673                 :             :         // you've got much bigger problems than "attacker can influence
     674                 :             :         // transaction fees."
     675         [ +  - ]:           1 :         return;
     676                 :             :     }
     677                 :             : 
     678                 :             :     // Must update nBestSeenHeight in sync with ClearCurrent so that
     679                 :             :     // calls to removeTx (via processBlockTx) correctly calculate age
     680                 :             :     // of unconfirmed txs to remove from tracking.
     681                 :         665 :     nBestSeenHeight = nBlockHeight;
     682                 :             : 
     683                 :             :     // Update unconfirmed circular buffer
     684                 :         665 :     feeStats->ClearCurrent(nBlockHeight);
     685                 :         665 :     shortStats->ClearCurrent(nBlockHeight);
     686                 :         665 :     longStats->ClearCurrent(nBlockHeight);
     687                 :             : 
     688                 :             :     // Decay all exponential averages
     689                 :         665 :     feeStats->UpdateMovingAverages();
     690                 :         665 :     shortStats->UpdateMovingAverages();
     691                 :         665 :     longStats->UpdateMovingAverages();
     692                 :             : 
     693                 :         665 :     unsigned int countedTxs = 0;
     694                 :             :     // Update averages with data points from current block
     695         [ +  + ]:       25225 :     for (const auto& tx : txs_removed_for_block) {
     696   [ +  -  +  - ]:       24560 :         if (processBlockTx(nBlockHeight, tx))
     697                 :       24560 :             countedTxs++;
     698                 :             :     }
     699                 :             : 
     700   [ +  +  +  - ]:         665 :     if (firstRecordedHeight == 0 && countedTxs > 0) {
     701                 :           1 :         firstRecordedHeight = nBestSeenHeight;
     702   [ +  -  +  -  :           1 :         LogPrint(BCLog::ESTIMATEFEE, "Blockpolicy first recorded height %u\n", firstRecordedHeight);
                   +  - ]
     703                 :             :     }
     704                 :             : 
     705                 :             : 
     706   [ +  -  +  -  :        1330 :     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",
             +  -  +  - ]
     707                 :             :              countedTxs, txs_removed_for_block.size(), trackedTxs, trackedTxs + untrackedTxs, mapMemPoolTxs.size(),
     708                 :             :              MaxUsableEstimate(), HistoricalBlockSpan() > BlockSpan() ? "historical" : "current");
     709                 :             : 
     710                 :         665 :     trackedTxs = 0;
     711         [ +  - ]:         665 :     untrackedTxs = 0;
     712                 :         666 : }
     713                 :             : 
     714                 :          94 : CFeeRate CBlockPolicyEstimator::estimateFee(int confTarget) const
     715                 :             : {
     716                 :             :     // It's not possible to get reasonable estimates for confTarget of 1
     717         [ +  + ]:          94 :     if (confTarget <= 1)
     718                 :           6 :         return CFeeRate(0);
     719                 :             : 
     720                 :          88 :     return estimateRawFee(confTarget, DOUBLE_SUCCESS_PCT, FeeEstimateHorizon::MED_HALFLIFE);
     721                 :             : }
     722                 :             : 
     723                 :          88 : CFeeRate CBlockPolicyEstimator::estimateRawFee(int confTarget, double successThreshold, FeeEstimateHorizon horizon, EstimationResult* result) const
     724                 :             : {
     725                 :          88 :     TxConfirmStats* stats = nullptr;
     726                 :          88 :     double sufficientTxs = SUFFICIENT_FEETXS;
     727   [ -  +  -  - ]:          88 :     switch (horizon) {
     728                 :           0 :     case FeeEstimateHorizon::SHORT_HALFLIFE: {
     729                 :           0 :         stats = shortStats.get();
     730                 :           0 :         sufficientTxs = SUFFICIENT_TXS_SHORT;
     731                 :           0 :         break;
     732                 :             :     }
     733                 :          88 :     case FeeEstimateHorizon::MED_HALFLIFE: {
     734                 :          88 :         stats = feeStats.get();
     735                 :          88 :         break;
     736                 :             :     }
     737                 :           0 :     case FeeEstimateHorizon::LONG_HALFLIFE: {
     738                 :           0 :         stats = longStats.get();
     739                 :           0 :         break;
     740                 :             :     }
     741                 :             :     } // no default case, so the compiler can warn about missing cases
     742         [ -  + ]:          88 :     assert(stats);
     743                 :             : 
     744                 :          88 :     LOCK(m_cs_fee_estimator);
     745                 :             :     // Return failure if trying to analyze a target we're not tracking
     746   [ +  -  +  - ]:          88 :     if (confTarget <= 0 || (unsigned int)confTarget > stats->GetMaxConfirms())
     747                 :           0 :         return CFeeRate(0);
     748         [ -  + ]:          88 :     if (successThreshold > 1)
     749                 :           0 :         return CFeeRate(0);
     750                 :             : 
     751         [ +  - ]:          88 :     double median = stats->EstimateMedianVal(confTarget, sufficientTxs, successThreshold, nBestSeenHeight, result);
     752                 :             : 
     753         [ +  + ]:          88 :     if (median < 0)
     754                 :          16 :         return CFeeRate(0);
     755                 :             : 
     756                 :          72 :     return CFeeRate(llround(median));
     757                 :          88 : }
     758                 :             : 
     759                 :           0 : unsigned int CBlockPolicyEstimator::HighestTargetTracked(FeeEstimateHorizon horizon) const
     760                 :             : {
     761                 :           0 :     LOCK(m_cs_fee_estimator);
     762   [ #  #  #  # ]:           0 :     switch (horizon) {
     763                 :           0 :     case FeeEstimateHorizon::SHORT_HALFLIFE: {
     764                 :           0 :         return shortStats->GetMaxConfirms();
     765                 :             :     }
     766                 :           0 :     case FeeEstimateHorizon::MED_HALFLIFE: {
     767                 :           0 :         return feeStats->GetMaxConfirms();
     768                 :             :     }
     769                 :           0 :     case FeeEstimateHorizon::LONG_HALFLIFE: {
     770                 :           0 :         return longStats->GetMaxConfirms();
     771                 :             :     }
     772                 :             :     } // no default case, so the compiler can warn about missing cases
     773                 :           0 :     assert(false);
     774                 :           0 : }
     775                 :             : 
     776                 :        1330 : unsigned int CBlockPolicyEstimator::BlockSpan() const
     777                 :             : {
     778         [ +  - ]:        1330 :     if (firstRecordedHeight == 0) return 0;
     779         [ -  + ]:        1330 :     assert(nBestSeenHeight >= firstRecordedHeight);
     780                 :             : 
     781                 :        1330 :     return nBestSeenHeight - firstRecordedHeight;
     782                 :             : }
     783                 :             : 
     784                 :        1330 : unsigned int CBlockPolicyEstimator::HistoricalBlockSpan() const
     785                 :             : {
     786         [ -  + ]:        1330 :     if (historicalFirst == 0) return 0;
     787         [ #  # ]:           0 :     assert(historicalBest >= historicalFirst);
     788                 :             : 
     789         [ #  # ]:           0 :     if (nBestSeenHeight - historicalBest > OLDEST_ESTIMATE_HISTORY) return 0;
     790                 :             : 
     791                 :           0 :     return historicalBest - historicalFirst;
     792                 :             : }
     793                 :             : 
     794                 :         665 : unsigned int CBlockPolicyEstimator::MaxUsableEstimate() const
     795                 :             : {
     796                 :             :     // Block spans are divided by 2 to make sure there are enough potential failing data points for the estimate
     797   [ +  -  -  + ]:        1330 :     return std::min(longStats->GetMaxConfirms(), std::max(BlockSpan(), HistoricalBlockSpan()) / 2);
     798                 :             : }
     799                 :             : 
     800                 :             : /** Return a fee estimate at the required successThreshold from the shortest
     801                 :             :  * time horizon which tracks confirmations up to the desired target.  If
     802                 :             :  * checkShorterHorizon is requested, also allow short time horizon estimates
     803                 :             :  * for a lower target to reduce the given answer */
     804                 :           0 : double CBlockPolicyEstimator::estimateCombinedFee(unsigned int confTarget, double successThreshold, bool checkShorterHorizon, EstimationResult *result) const
     805                 :             : {
     806                 :           0 :     double estimate = -1;
     807   [ #  #  #  # ]:           0 :     if (confTarget >= 1 && confTarget <= longStats->GetMaxConfirms()) {
     808                 :             :         // Find estimate from shortest time horizon possible
     809         [ #  # ]:           0 :         if (confTarget <= shortStats->GetMaxConfirms()) { // short horizon
     810                 :           0 :             estimate = shortStats->EstimateMedianVal(confTarget, SUFFICIENT_TXS_SHORT, successThreshold, nBestSeenHeight, result);
     811                 :             :         }
     812         [ #  # ]:           0 :         else if (confTarget <= feeStats->GetMaxConfirms()) { // medium horizon
     813                 :           0 :             estimate = feeStats->EstimateMedianVal(confTarget, SUFFICIENT_FEETXS, successThreshold, nBestSeenHeight, result);
     814                 :             :         }
     815                 :             :         else { // long horizon
     816                 :           0 :             estimate = longStats->EstimateMedianVal(confTarget, SUFFICIENT_FEETXS, successThreshold, nBestSeenHeight, result);
     817                 :             :         }
     818         [ #  # ]:           0 :         if (checkShorterHorizon) {
     819                 :           0 :             EstimationResult tempResult;
     820                 :             :             // If a lower confTarget from a more recent horizon returns a lower answer use it.
     821         [ #  # ]:           0 :             if (confTarget > feeStats->GetMaxConfirms()) {
     822                 :           0 :                 double medMax = feeStats->EstimateMedianVal(feeStats->GetMaxConfirms(), SUFFICIENT_FEETXS, successThreshold, nBestSeenHeight, &tempResult);
     823   [ #  #  #  #  :           0 :                 if (medMax > 0 && (estimate == -1 || medMax < estimate)) {
                   #  # ]
     824                 :           0 :                     estimate = medMax;
     825         [ #  # ]:           0 :                     if (result) *result = tempResult;
     826                 :             :                 }
     827                 :             :             }
     828         [ #  # ]:           0 :             if (confTarget > shortStats->GetMaxConfirms()) {
     829                 :           0 :                 double shortMax = shortStats->EstimateMedianVal(shortStats->GetMaxConfirms(), SUFFICIENT_TXS_SHORT, successThreshold, nBestSeenHeight, &tempResult);
     830   [ #  #  #  #  :           0 :                 if (shortMax > 0 && (estimate == -1 || shortMax < estimate)) {
                   #  # ]
     831                 :           0 :                     estimate = shortMax;
     832         [ #  # ]:           0 :                     if (result) *result = tempResult;
     833                 :             :                 }
     834                 :             :             }
     835                 :             :         }
     836                 :             :     }
     837                 :           0 :     return estimate;
     838                 :             : }
     839                 :             : 
     840                 :             : /** Ensure that for a conservative estimate, the DOUBLE_SUCCESS_PCT is also met
     841                 :             :  * at 2 * target for any longer time horizons.
     842                 :             :  */
     843                 :           0 : double CBlockPolicyEstimator::estimateConservativeFee(unsigned int doubleTarget, EstimationResult *result) const
     844                 :             : {
     845                 :           0 :     double estimate = -1;
     846                 :           0 :     EstimationResult tempResult;
     847         [ #  # ]:           0 :     if (doubleTarget <= shortStats->GetMaxConfirms()) {
     848                 :           0 :         estimate = feeStats->EstimateMedianVal(doubleTarget, SUFFICIENT_FEETXS, DOUBLE_SUCCESS_PCT, nBestSeenHeight, result);
     849                 :             :     }
     850         [ #  # ]:           0 :     if (doubleTarget <= feeStats->GetMaxConfirms()) {
     851                 :           0 :         double longEstimate = longStats->EstimateMedianVal(doubleTarget, SUFFICIENT_FEETXS, DOUBLE_SUCCESS_PCT, nBestSeenHeight, &tempResult);
     852         [ #  # ]:           0 :         if (longEstimate > estimate) {
     853                 :           0 :             estimate = longEstimate;
     854         [ #  # ]:           0 :             if (result) *result = tempResult;
     855                 :             :         }
     856                 :             :     }
     857                 :           0 :     return estimate;
     858                 :             : }
     859                 :             : 
     860                 :             : /** estimateSmartFee returns the max of the feerates calculated with a 60%
     861                 :             :  * threshold required at target / 2, an 85% threshold required at target and a
     862                 :             :  * 95% threshold required at 2 * target.  Each calculation is performed at the
     863                 :             :  * shortest time horizon which tracks the required target.  Conservative
     864                 :             :  * estimates, however, required the 95% threshold at 2 * target be met for any
     865                 :             :  * longer time horizons also.
     866                 :             :  */
     867                 :           0 : CFeeRate CBlockPolicyEstimator::estimateSmartFee(int confTarget, FeeCalculation *feeCalc, bool conservative) const
     868                 :             : {
     869                 :           0 :     LOCK(m_cs_fee_estimator);
     870                 :             : 
     871         [ #  # ]:           0 :     if (feeCalc) {
     872                 :           0 :         feeCalc->desiredTarget = confTarget;
     873                 :           0 :         feeCalc->returnedTarget = confTarget;
     874                 :             :     }
     875                 :             : 
     876                 :           0 :     double median = -1;
     877                 :           0 :     EstimationResult tempResult;
     878                 :             : 
     879                 :             :     // Return failure if trying to analyze a target we're not tracking
     880   [ #  #  #  # ]:           0 :     if (confTarget <= 0 || (unsigned int)confTarget > longStats->GetMaxConfirms()) {
     881                 :           0 :         return CFeeRate(0);  // error condition
     882                 :             :     }
     883                 :             : 
     884                 :             :     // It's not possible to get reasonable estimates for confTarget of 1
     885         [ #  # ]:           0 :     if (confTarget == 1) confTarget = 2;
     886                 :             : 
     887                 :           0 :     unsigned int maxUsableEstimate = MaxUsableEstimate();
     888         [ #  # ]:           0 :     if ((unsigned int)confTarget > maxUsableEstimate) {
     889                 :           0 :         confTarget = maxUsableEstimate;
     890                 :             :     }
     891         [ #  # ]:           0 :     if (feeCalc) feeCalc->returnedTarget = confTarget;
     892                 :             : 
     893         [ #  # ]:           0 :     if (confTarget <= 1) return CFeeRate(0); // error condition
     894                 :             : 
     895                 :           0 :     assert(confTarget > 0); //estimateCombinedFee and estimateConservativeFee take unsigned ints
     896                 :             :     /** true is passed to estimateCombined fee for target/2 and target so
     897                 :             :      * that we check the max confirms for shorter time horizons as well.
     898                 :             :      * This is necessary to preserve monotonically increasing estimates.
     899                 :             :      * For non-conservative estimates we do the same thing for 2*target, but
     900                 :             :      * for conservative estimates we want to skip these shorter horizons
     901                 :             :      * checks for 2*target because we are taking the max over all time
     902                 :             :      * horizons so we already have monotonically increasing estimates and
     903                 :             :      * the purpose of conservative estimates is not to let short term
     904                 :             :      * fluctuations lower our estimates by too much.
     905                 :             :      */
     906         [ #  # ]:           0 :     double halfEst = estimateCombinedFee(confTarget/2, HALF_SUCCESS_PCT, true, &tempResult);
     907         [ #  # ]:           0 :     if (feeCalc) {
     908                 :           0 :         feeCalc->est = tempResult;
     909                 :           0 :         feeCalc->reason = FeeReason::HALF_ESTIMATE;
     910                 :             :     }
     911                 :           0 :     median = halfEst;
     912         [ #  # ]:           0 :     double actualEst = estimateCombinedFee(confTarget, SUCCESS_PCT, true, &tempResult);
     913         [ #  # ]:           0 :     if (actualEst > median) {
     914                 :           0 :         median = actualEst;
     915         [ #  # ]:           0 :         if (feeCalc) {
     916                 :           0 :             feeCalc->est = tempResult;
     917                 :           0 :             feeCalc->reason = FeeReason::FULL_ESTIMATE;
     918                 :             :         }
     919                 :             :     }
     920         [ #  # ]:           0 :     double doubleEst = estimateCombinedFee(2 * confTarget, DOUBLE_SUCCESS_PCT, !conservative, &tempResult);
     921         [ #  # ]:           0 :     if (doubleEst > median) {
     922                 :           0 :         median = doubleEst;
     923         [ #  # ]:           0 :         if (feeCalc) {
     924                 :           0 :             feeCalc->est = tempResult;
     925                 :           0 :             feeCalc->reason = FeeReason::DOUBLE_ESTIMATE;
     926                 :             :         }
     927                 :             :     }
     928                 :             : 
     929         [ #  # ]:           0 :     if (conservative || median == -1) {
     930         [ #  # ]:           0 :         double consEst =  estimateConservativeFee(2 * confTarget, &tempResult);
     931         [ #  # ]:           0 :         if (consEst > median) {
     932                 :           0 :             median = consEst;
     933         [ #  # ]:           0 :             if (feeCalc) {
     934                 :           0 :                 feeCalc->est = tempResult;
     935                 :           0 :                 feeCalc->reason = FeeReason::CONSERVATIVE;
     936                 :             :             }
     937                 :             :         }
     938                 :             :     }
     939                 :             : 
     940         [ #  # ]:           0 :     if (median < 0) return CFeeRate(0); // error condition
     941                 :             : 
     942                 :           0 :     return CFeeRate(llround(median));
     943                 :           0 : }
     944                 :             : 
     945                 :           0 : void CBlockPolicyEstimator::Flush() {
     946                 :           0 :     FlushUnconfirmed();
     947                 :           0 :     FlushFeeEstimates();
     948                 :           0 : }
     949                 :             : 
     950                 :           0 : void CBlockPolicyEstimator::FlushFeeEstimates()
     951                 :             : {
     952                 :           0 :     AutoFile est_file{fsbridge::fopen(m_estimation_filepath, "wb")};
     953   [ #  #  #  #  :           0 :     if (est_file.IsNull() || !Write(est_file)) {
                   #  # ]
     954   [ #  #  #  # ]:           0 :         LogPrintf("Failed to write fee estimates to %s. Continue anyway.\n", fs::PathToString(m_estimation_filepath));
     955                 :             :     } else {
     956   [ #  #  #  # ]:           0 :         LogPrintf("Flushed fee estimates to %s.\n", fs::PathToString(m_estimation_filepath.filename()));
     957                 :             :     }
     958                 :           0 : }
     959                 :             : 
     960                 :           0 : bool CBlockPolicyEstimator::Write(AutoFile& fileout) const
     961                 :             : {
     962                 :           0 :     try {
     963         [ #  # ]:           0 :         LOCK(m_cs_fee_estimator);
     964         [ #  # ]:           0 :         fileout << 149900; // version required to read: 0.14.99 or later
     965         [ #  # ]:           0 :         fileout << CLIENT_VERSION; // version that wrote the file
     966         [ #  # ]:           0 :         fileout << nBestSeenHeight;
     967         [ #  # ]:           0 :         if (BlockSpan() > HistoricalBlockSpan()/2) {
     968   [ #  #  #  # ]:           0 :             fileout << firstRecordedHeight << nBestSeenHeight;
     969                 :             :         }
     970                 :             :         else {
     971   [ #  #  #  # ]:           0 :             fileout << historicalFirst << historicalBest;
     972                 :             :         }
     973         [ #  # ]:           0 :         fileout << Using<VectorFormatter<EncodedDoubleFormatter>>(buckets);
     974         [ #  # ]:           0 :         feeStats->Write(fileout);
     975         [ #  # ]:           0 :         shortStats->Write(fileout);
     976         [ #  # ]:           0 :         longStats->Write(fileout);
     977                 :           0 :     }
     978         [ -  - ]:           0 :     catch (const std::exception&) {
     979         [ -  - ]:           0 :         LogPrintf("CBlockPolicyEstimator::Write(): unable to write policy estimator data (non-fatal)\n");
     980                 :           0 :         return false;
     981                 :           0 :     }
     982                 :           0 :     return true;
     983                 :             : }
     984                 :             : 
     985                 :           0 : bool CBlockPolicyEstimator::Read(AutoFile& filein)
     986                 :             : {
     987                 :           0 :     try {
     988         [ #  # ]:           0 :         LOCK(m_cs_fee_estimator);
     989                 :           0 :         int nVersionRequired, nVersionThatWrote;
     990   [ #  #  #  # ]:           0 :         filein >> nVersionRequired >> nVersionThatWrote;
     991         [ #  # ]:           0 :         if (nVersionRequired > CLIENT_VERSION) {
     992   [ #  #  #  # ]:           0 :             throw std::runtime_error(strprintf("up-version (%d) fee estimate file", nVersionRequired));
     993                 :             :         }
     994                 :             : 
     995                 :             :         // Read fee estimates file into temporary variables so existing data
     996                 :             :         // structures aren't corrupted if there is an exception.
     997                 :           0 :         unsigned int nFileBestSeenHeight;
     998         [ #  # ]:           0 :         filein >> nFileBestSeenHeight;
     999                 :             : 
    1000         [ #  # ]:           0 :         if (nVersionRequired < 149900) {
    1001         [ #  # ]:           0 :             LogPrintf("%s: incompatible old fee estimation data (non-fatal). Version: %d\n", __func__, nVersionRequired);
    1002                 :             :         } else { // New format introduced in 149900
    1003                 :           0 :             unsigned int nFileHistoricalFirst, nFileHistoricalBest;
    1004   [ #  #  #  # ]:           0 :             filein >> nFileHistoricalFirst >> nFileHistoricalBest;
    1005   [ #  #  #  # ]:           0 :             if (nFileHistoricalFirst > nFileHistoricalBest || nFileHistoricalBest > nFileBestSeenHeight) {
    1006         [ #  # ]:           0 :                 throw std::runtime_error("Corrupt estimates file. Historical block range for estimates is invalid");
    1007                 :             :             }
    1008                 :           0 :             std::vector<double> fileBuckets;
    1009         [ #  # ]:           0 :             filein >> Using<VectorFormatter<EncodedDoubleFormatter>>(fileBuckets);
    1010         [ #  # ]:           0 :             size_t numBuckets = fileBuckets.size();
    1011         [ #  # ]:           0 :             if (numBuckets <= 1 || numBuckets > 1000) {
    1012         [ #  # ]:           0 :                 throw std::runtime_error("Corrupt estimates file. Must have between 2 and 1000 feerate buckets");
    1013                 :             :             }
    1014                 :             : 
    1015   [ #  #  #  #  :           0 :             std::unique_ptr<TxConfirmStats> fileFeeStats(new TxConfirmStats(buckets, bucketMap, MED_BLOCK_PERIODS, MED_DECAY, MED_SCALE));
                   #  # ]
    1016   [ #  #  #  #  :           0 :             std::unique_ptr<TxConfirmStats> fileShortStats(new TxConfirmStats(buckets, bucketMap, SHORT_BLOCK_PERIODS, SHORT_DECAY, SHORT_SCALE));
                   #  # ]
    1017   [ #  #  #  #  :           0 :             std::unique_ptr<TxConfirmStats> fileLongStats(new TxConfirmStats(buckets, bucketMap, LONG_BLOCK_PERIODS, LONG_DECAY, LONG_SCALE));
                   #  # ]
    1018         [ #  # ]:           0 :             fileFeeStats->Read(filein, nVersionThatWrote, numBuckets);
    1019         [ #  # ]:           0 :             fileShortStats->Read(filein, nVersionThatWrote, numBuckets);
    1020         [ #  # ]:           0 :             fileLongStats->Read(filein, nVersionThatWrote, numBuckets);
    1021                 :             : 
    1022                 :             :             // Fee estimates file parsed correctly
    1023                 :             :             // Copy buckets from file and refresh our bucketmap
    1024         [ #  # ]:           0 :             buckets = fileBuckets;
    1025                 :           0 :             bucketMap.clear();
    1026         [ #  # ]:           0 :             for (unsigned int i = 0; i < buckets.size(); i++) {
    1027         [ #  # ]:           0 :                 bucketMap[buckets[i]] = i;
    1028                 :             :             }
    1029                 :             : 
    1030                 :             :             // Destroy old TxConfirmStats and point to new ones that already reference buckets and bucketMap
    1031                 :           0 :             feeStats = std::move(fileFeeStats);
    1032                 :           0 :             shortStats = std::move(fileShortStats);
    1033                 :           0 :             longStats = std::move(fileLongStats);
    1034                 :             : 
    1035                 :           0 :             nBestSeenHeight = nFileBestSeenHeight;
    1036                 :           0 :             historicalFirst = nFileHistoricalFirst;
    1037                 :           0 :             historicalBest = nFileHistoricalBest;
    1038                 :           0 :         }
    1039                 :           0 :     }
    1040         [ -  - ]:           0 :     catch (const std::exception& e) {
    1041         [ -  - ]:           0 :         LogPrintf("CBlockPolicyEstimator::Read(): unable to read policy estimator data (non-fatal): %s\n",e.what());
    1042                 :           0 :         return false;
    1043                 :           0 :     }
    1044                 :           0 :     return true;
    1045                 :             : }
    1046                 :             : 
    1047                 :           0 : void CBlockPolicyEstimator::FlushUnconfirmed()
    1048                 :             : {
    1049                 :           0 :     const auto startclear{SteadyClock::now()};
    1050                 :           0 :     LOCK(m_cs_fee_estimator);
    1051                 :           0 :     size_t num_entries = mapMemPoolTxs.size();
    1052                 :             :     // Remove every entry in mapMemPoolTxs
    1053         [ #  # ]:           0 :     while (!mapMemPoolTxs.empty()) {
    1054         [ #  # ]:           0 :         auto mi = mapMemPoolTxs.begin();
    1055         [ #  # ]:           0 :         _removeTx(mi->first, false); // this calls erase() on mapMemPoolTxs
    1056                 :             :     }
    1057                 :           0 :     const auto endclear{SteadyClock::now()};
    1058   [ #  #  #  #  :           0 :     LogPrint(BCLog::ESTIMATEFEE, "Recorded %u unconfirmed txs from mempool in %.3fs\n", num_entries, Ticks<SecondsDouble>(endclear - startclear));
             #  #  #  # ]
    1059                 :           0 : }
    1060                 :             : 
    1061                 :           0 : std::chrono::hours CBlockPolicyEstimator::GetFeeEstimatorFileAge()
    1062                 :             : {
    1063                 :           0 :     auto file_time{fs::last_write_time(m_estimation_filepath)};
    1064                 :           0 :     auto now{fs::file_time_type::clock::now()};
    1065                 :           0 :     return std::chrono::duration_cast<std::chrono::hours>(now - file_time);
    1066                 :             : }
    1067                 :             : 
    1068                 :         169 : static std::set<double> MakeFeeSet(const CFeeRate& min_incremental_fee,
    1069                 :             :                                    double max_filter_fee_rate,
    1070                 :             :                                    double fee_filter_spacing)
    1071                 :             : {
    1072         [ -  + ]:         169 :     std::set<double> fee_set;
    1073                 :             : 
    1074         [ -  + ]:         169 :     const CAmount min_fee_limit{std::max(CAmount(1), min_incremental_fee.GetFeePerK() / 2)};
    1075         [ +  - ]:         169 :     fee_set.insert(0);
    1076                 :         169 :     for (double bucket_boundary = min_fee_limit;
    1077         [ +  + ]:       17745 :          bucket_boundary <= max_filter_fee_rate;
    1078                 :       17576 :          bucket_boundary *= fee_filter_spacing) {
    1079                 :             : 
    1080         [ +  - ]:       17576 :         fee_set.insert(bucket_boundary);
    1081                 :             :     }
    1082                 :             : 
    1083                 :         169 :     return fee_set;
    1084                 :           0 : }
    1085                 :             : 
    1086                 :         169 : FeeFilterRounder::FeeFilterRounder(const CFeeRate& minIncrementalFee, FastRandomContext& rng)
    1087                 :         169 :     : m_fee_set{MakeFeeSet(minIncrementalFee, MAX_FILTER_FEERATE, FEE_FILTER_SPACING)},
    1088                 :         169 :       insecure_rand{rng}
    1089                 :             : {
    1090                 :         169 : }
    1091                 :             : 
    1092                 :          13 : CAmount FeeFilterRounder::round(CAmount currentMinFee)
    1093                 :             : {
    1094                 :          13 :     AssertLockNotHeld(m_insecure_rand_mutex);
    1095                 :          13 :     std::set<double>::iterator it = m_fee_set.lower_bound(currentMinFee);
    1096   [ +  +  +  + ]:          13 :     if (it == m_fee_set.end() ||
    1097         [ +  + ]:           7 :         (it != m_fee_set.begin() &&
    1098   [ +  +  +  - ]:           8 :          WITH_LOCK(m_insecure_rand_mutex, return insecure_rand.rand32()) % 3 != 0)) {
    1099                 :           7 :         --it;
    1100                 :             :     }
    1101                 :          13 :     return static_cast<CAmount>(*it);
    1102                 :             : }
        

Generated by: LCOV version 2.0-1