LCOV - code coverage report
Current view: top level - src/policy - fees.cpp (source / functions) Coverage Total Hit
Test: total_coverage.info Lines: 92.4 % 552 510
Test Date: 2024-11-04 05:10:19 Functions: 100.0 % 42 42
Branches: 60.7 % 596 362

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

Generated by: LCOV version 2.0-1