LCOV - code coverage report
Current view: top level - src/policy/fees - block_policy_estimator.h Coverage Total Hit
Test: test_bitcoin_coverage.info Lines: 100.0 % 2 2
Test Date: 2026-08-25 06:16:57 Functions: - 0 0

            Line data    Source code
       1              : // Copyright (c) 2009-2010 Satoshi Nakamoto
       2              : // Copyright (c) 2009-present 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              : #ifndef BITCOIN_POLICY_FEES_BLOCK_POLICY_ESTIMATOR_H
       6              : #define BITCOIN_POLICY_FEES_BLOCK_POLICY_ESTIMATOR_H
       7              : 
       8              : #include <consensus/amount.h>
       9              : #include <policy/feerate.h>
      10              : #include <primitives/transaction_identifier.h>
      11              : #include <random.h>
      12              : #include <sync.h>
      13              : #include <uint256.h>
      14              : #include <util/expected.h>
      15              : #include <util/fees.h>
      16              : #include <util/fs.h>
      17              : 
      18              : #include <array>
      19              : #include <chrono>
      20              : #include <map>
      21              : #include <memory>
      22              : #include <set>
      23              : #include <string>
      24              : #include <vector>
      25              : 
      26              : 
      27              : /** Block policy estimate files that are more than 60 hours (2.5 days) old will not be read,
      28              :  * as fee estimates are based on historical data and may be inaccurate if
      29              :  * network activity has changed.
      30              :  */
      31              : inline constexpr std::chrono::hours MAX_FILE_AGE{60};
      32              : 
      33              : // Whether we allow importing a fee_estimates file older than MAX_FILE_AGE.
      34              : inline constexpr bool DEFAULT_ACCEPT_STALE_FEE_ESTIMATES{false};
      35              : 
      36              : class AutoFile;
      37              : class TxConfirmStats;
      38              : struct RemovedMempoolTransactionInfo;
      39              : struct NewMempoolTransactionInfo;
      40              : 
      41              : /* Identifier for each of the 3 different TxConfirmStats which will track
      42              :  * history over different time horizons. */
      43              : enum class FeeEstimateHorizon {
      44              :     SHORT_HALFLIFE,
      45              :     MED_HALFLIFE,
      46              :     LONG_HALFLIFE,
      47              : };
      48              : 
      49              : inline constexpr auto ALL_FEE_ESTIMATE_HORIZONS = std::array{
      50              :     FeeEstimateHorizon::SHORT_HALFLIFE,
      51              :     FeeEstimateHorizon::MED_HALFLIFE,
      52              :     FeeEstimateHorizon::LONG_HALFLIFE,
      53              : };
      54              : 
      55              : std::string StringForFeeEstimateHorizon(FeeEstimateHorizon horizon);
      56              : 
      57              : /* Enumeration of reason for returned fee estimate */
      58              : enum class BlockPolicyEstimateReason {
      59              :     NONE,
      60              :     HALF_ESTIMATE,
      61              :     FULL_ESTIMATE,
      62              :     DOUBLE_ESTIMATE,
      63              :     CONSERVATIVE,
      64              : };
      65              : 
      66              : std::string StringForBlockPolicyEstimateReason(BlockPolicyEstimateReason reason);
      67              : 
      68              : /* Used to return detailed information about a feerate bucket */
      69              : struct EstimatorBucket
      70              : {
      71              :     double start = -1;
      72              :     double end = -1;
      73              :     double withinTarget = 0;
      74              :     double totalConfirmed = 0;
      75              :     double inMempool = 0;
      76              :     double leftMempool = 0;
      77              : };
      78              : 
      79              : /* Used to return detailed information about a fee estimate calculation */
      80              : struct EstimationResult
      81              : {
      82              :     EstimatorBucket pass;
      83              :     EstimatorBucket fail;
      84              :     double decay = 0;
      85              :     unsigned int scale = 0;
      86              : };
      87              : 
      88              : struct FeeCalculation
      89              : {
      90              :     EstimationResult est;
      91              :     BlockPolicyEstimateReason reason = BlockPolicyEstimateReason::NONE;
      92              :     int desiredTarget = 0;
      93              :     int returnedTarget = 0;
      94              :     unsigned int best_height{0};
      95              : };
      96              : 
      97              : /** \class CBlockPolicyEstimator
      98              :  * The BlockPolicyEstimator is used for estimating the feerate needed
      99              :  * for a transaction to be included in a block within a certain number of
     100              :  * blocks.
     101              :  *
     102              :  * At a high level the algorithm works by grouping transactions into buckets
     103              :  * based on having similar feerates and then tracking how long it
     104              :  * takes transactions in the various buckets to be mined.  It operates under
     105              :  * the assumption that in general transactions of higher feerate will be
     106              :  * included in blocks before transactions of lower feerate.   So for
     107              :  * example if you wanted to know what feerate you should put on a transaction to
     108              :  * be included in a block within the next 5 blocks, you would start by looking
     109              :  * at the bucket with the highest feerate transactions and verifying that a
     110              :  * sufficiently high percentage of them were confirmed within 5 blocks and
     111              :  * then you would look at the next highest feerate bucket, and so on, stopping at
     112              :  * the last bucket to pass the test.   The average feerate of transactions in this
     113              :  * bucket will give you an indication of the lowest feerate you can put on a
     114              :  * transaction and still have a sufficiently high chance of being confirmed
     115              :  * within your desired 5 blocks.
     116              :  *
     117              :  * Here is a brief description of the implementation:
     118              :  * When a transaction enters the mempool, we track the height of the block chain
     119              :  * at entry.  All further calculations are conducted only on this set of "seen"
     120              :  * transactions. Whenever a block comes in, we count the number of transactions
     121              :  * in each bucket and the total amount of feerate paid in each bucket. Then we
     122              :  * calculate how many blocks Y it took each transaction to be mined.  We convert
     123              :  * from a number of blocks to a number of periods Y' each encompassing "scale"
     124              :  * blocks.  This is tracked in 3 different data sets each up to a maximum
     125              :  * number of periods. Within each data set we have an array of counters in each
     126              :  * feerate bucket and we increment all the counters from Y' up to max periods
     127              :  * representing that a tx was successfully confirmed in less than or equal to
     128              :  * that many periods. We want to save a history of this information, so at any
     129              :  * time we have a counter of the total number of transactions that happened in a
     130              :  * given feerate bucket and the total number that were confirmed in each of the
     131              :  * periods or less for any bucket.  We save this history by keeping an
     132              :  * exponentially decaying moving average of each one of these stats.  This is
     133              :  * done for a different decay in each of the 3 data sets to keep relevant data
     134              :  * from different time horizons.  Furthermore we also keep track of the number
     135              :  * unmined (in mempool or left mempool without being included in a block)
     136              :  * transactions in each bucket and for how many blocks they have been
     137              :  * outstanding and use both of these numbers to increase the number of transactions
     138              :  * we've seen in that feerate bucket when calculating an estimate for any number
     139              :  * of confirmations below the number of blocks they've been outstanding.
     140              :  *
     141              :  *  We want to be able to estimate feerates that are needed on tx's to be included in
     142              :  * a certain number of blocks.  Every time a block is added to the best chain, this class records
     143              :  * stats on the transactions included in that block
     144              :  */
     145              : class CBlockPolicyEstimator
     146              : {
     147              : private:
     148              :     /** Track confirm delays up to 12 blocks for short horizon */
     149              :     static constexpr unsigned int SHORT_BLOCK_PERIODS = 12;
     150              :     static constexpr unsigned int SHORT_SCALE = 1;
     151              :     /** Track confirm delays up to 48 blocks for medium horizon */
     152              :     static constexpr unsigned int MED_BLOCK_PERIODS = 24;
     153              :     static constexpr unsigned int MED_SCALE = 2;
     154              :     /** Track confirm delays up to 1008 blocks for long horizon */
     155              :     static constexpr unsigned int LONG_BLOCK_PERIODS = 42;
     156              :     static constexpr unsigned int LONG_SCALE = 24;
     157              :     /** Historical estimates that are older than this aren't valid */
     158              :     static constexpr unsigned int OLDEST_ESTIMATE_HISTORY{6 * 1008};
     159              : 
     160              :     /** Decay of .962 is a half-life of 18 blocks or about 3 hours */
     161              :     static constexpr double SHORT_DECAY = .962;
     162              :     /** Decay of .9952 is a half-life of 144 blocks or about 1 day */
     163              :     static constexpr double MED_DECAY = .9952;
     164              :     /** Decay of .99931 is a half-life of 1008 blocks or about 1 week */
     165              :     static constexpr double LONG_DECAY = .99931;
     166              : 
     167              :     /** Require greater than 60% of X feerate transactions to be confirmed within Y/2 blocks*/
     168              :     static constexpr double HALF_SUCCESS_PCT = .6;
     169              :     /** Require greater than 85% of X feerate transactions to be confirmed within Y blocks*/
     170              :     static constexpr double SUCCESS_PCT = .85;
     171              :     /** Require greater than 95% of X feerate transactions to be confirmed within 2 * Y blocks*/
     172              :     static constexpr double DOUBLE_SUCCESS_PCT = .95;
     173              : 
     174              :     /** Require an avg of 0.1 tx in the combined feerate bucket per block to have stat significance */
     175              :     static constexpr double SUFFICIENT_FEETXS = 0.1;
     176              :     /** Require an avg of 0.5 tx when using short decay since there are fewer blocks considered*/
     177              :     static constexpr double SUFFICIENT_TXS_SHORT = 0.5;
     178              : 
     179              :     /** Minimum and Maximum values for tracking feerates
     180              :      * The MIN_BUCKET_FEERATE should just be set to the lowest reasonable feerate.
     181              :      * MIN_BUCKET_FEERATE has historically inherited DEFAULT_MIN_RELAY_TX_FEE.
     182              :      * It is hardcoded because changing it is disruptive, as it invalidates existing fee
     183              :      * estimate files.
     184              :      *
     185              :      * Whenever DEFAULT_MIN_RELAY_TX_FEE changes, this value should be updated
     186              :      * accordingly. At the same time CURRENT_FEES_FILE_VERSION should be bumped.
     187              :      */
     188              :     static constexpr double MIN_BUCKET_FEERATE = 100;
     189              :     static constexpr double MAX_BUCKET_FEERATE = 1e7;
     190              : 
     191              :     /** Spacing of FeeRate buckets
     192              :      * We have to lump transactions into buckets based on feerate, but we want to be able
     193              :      * to give accurate estimates over a large range of potential feerates
     194              :      * Therefore it makes sense to exponentially space the buckets
     195              :      */
     196              :     static constexpr double FEE_SPACING = 1.05;
     197              : 
     198              :     const fs::path m_estimation_filepath;
     199              : public:
     200              :     /** Create new BlockPolicyEstimator and initialize stats tracking classes with default values */
     201              :     CBlockPolicyEstimator(const fs::path& estimation_filepath, bool read_stale_estimates);
     202              :     virtual ~CBlockPolicyEstimator();
     203              : 
     204              :     /** Process all the transactions that have been included in a block */
     205              :     void processBlock(const std::vector<RemovedMempoolTransactionInfo>& txs_removed_for_block,
     206              :                       unsigned int nBlockHeight)
     207              :         EXCLUSIVE_LOCKS_REQUIRED(!m_cs_fee_estimator);
     208              : 
     209              :     /** Process a transaction accepted to the mempool*/
     210              :     void processTransaction(const NewMempoolTransactionInfo& tx)
     211              :         EXCLUSIVE_LOCKS_REQUIRED(!m_cs_fee_estimator);
     212              : 
     213              :     /** Remove a transaction from the mempool tracking stats for non BLOCK removal reasons*/
     214              :     bool removeTx(Txid hash)
     215              :         EXCLUSIVE_LOCKS_REQUIRED(!m_cs_fee_estimator);
     216              : 
     217              :     /** DEPRECATED. Return a feerate estimate */
     218              :     CFeeRate estimateFee(int confTarget) const
     219              :         EXCLUSIVE_LOCKS_REQUIRED(!m_cs_fee_estimator);
     220              : 
     221              :     /** Estimate feerate needed to get be included in a block within confTarget
     222              :      *  blocks. If no answer can be given at confTarget, return an estimate at
     223              :      *  the closest target where one can be given.  'conservative' estimates are
     224              :      *  valid over longer time horizons also.
     225              :      */
     226              :     virtual CFeeRate estimateSmartFee(int confTarget, FeeCalculation *feeCalc, bool conservative) const
     227              :         EXCLUSIVE_LOCKS_REQUIRED(!m_cs_fee_estimator);
     228              : 
     229              :     /** Return a specific fee estimate calculation with a given success
     230              :      * threshold and time horizon, and optionally return detailed data about
     231              :      * calculation
     232              :      */
     233              :     CFeeRate estimateRawFee(int confTarget, double successThreshold, FeeEstimateHorizon horizon,
     234              :                             EstimationResult* result = nullptr) const
     235              :         EXCLUSIVE_LOCKS_REQUIRED(!m_cs_fee_estimator);
     236              : 
     237              :     /** Write estimation data to a file */
     238              :     bool Write(AutoFile& fileout) const
     239              :         EXCLUSIVE_LOCKS_REQUIRED(!m_cs_fee_estimator);
     240              : 
     241              :     /** Read estimation data from a file */
     242              :     bool Read(AutoFile& filein)
     243              :         EXCLUSIVE_LOCKS_REQUIRED(!m_cs_fee_estimator);
     244              : 
     245              :     /** Empty mempool transactions on shutdown to record failure to confirm for txs still in mempool */
     246              :     void FlushUnconfirmed()
     247              :         EXCLUSIVE_LOCKS_REQUIRED(!m_cs_fee_estimator);
     248              : 
     249              :     /** Calculation of highest target that estimates are tracked for */
     250              :     virtual unsigned int HighestTargetTracked(FeeEstimateHorizon horizon) const
     251              :         EXCLUSIVE_LOCKS_REQUIRED(!m_cs_fee_estimator);
     252              : 
     253              :     /** Drop still unconfirmed transactions and record current estimations, if the fee estimation file is present. */
     254              :     void Flush()
     255              :         EXCLUSIVE_LOCKS_REQUIRED(!m_cs_fee_estimator);
     256              : 
     257              :     /** Record current fee estimations. */
     258              :     void FlushFeeEstimates()
     259              :         EXCLUSIVE_LOCKS_REQUIRED(!m_cs_fee_estimator);
     260              : 
     261              :     /** Calculates the age of the file, since last modified */
     262              :     std::chrono::hours GetFeeEstimatorFileAge();
     263              : 
     264              :     /** Return the highest confirmation target for which an estimate can be provided. */
     265              :     unsigned int MaximumTarget() const
     266              :         EXCLUSIVE_LOCKS_REQUIRED(!m_cs_fee_estimator);
     267              : 
     268              :     /** Estimate the feerate needed to confirm within @p target blocks; wraps estimateSmartFee into a FeeRateEstimation. */
     269              :     util::Expected<FeeRateEstimation, FeeRateEstimationError> EstimateFeeRate(int target, bool conservative) const
     270              :         EXCLUSIVE_LOCKS_REQUIRED(!m_cs_fee_estimator);
     271              : 
     272              : 
     273              : private:
     274              :     mutable Mutex m_cs_fee_estimator;
     275              : 
     276              :     unsigned int nBestSeenHeight GUARDED_BY(m_cs_fee_estimator){0};
     277              :     unsigned int firstRecordedHeight GUARDED_BY(m_cs_fee_estimator){0};
     278              :     unsigned int historicalFirst GUARDED_BY(m_cs_fee_estimator){0};
     279              :     unsigned int historicalBest GUARDED_BY(m_cs_fee_estimator){0};
     280              : 
     281              :     struct TxStatsInfo
     282              :     {
     283              :         unsigned int blockHeight{0};
     284              :         unsigned int bucketIndex{0};
     285        24560 :         TxStatsInfo() = default;
     286              :     };
     287              : 
     288              :     // map of txids to information about that transaction
     289              :     std::map<Txid, TxStatsInfo> mapMemPoolTxs GUARDED_BY(m_cs_fee_estimator);
     290              : 
     291              :     /** Classes to track historical data on transaction confirmations */
     292              :     std::unique_ptr<TxConfirmStats> feeStats PT_GUARDED_BY(m_cs_fee_estimator);
     293              :     std::unique_ptr<TxConfirmStats> shortStats PT_GUARDED_BY(m_cs_fee_estimator);
     294              :     std::unique_ptr<TxConfirmStats> longStats PT_GUARDED_BY(m_cs_fee_estimator);
     295              : 
     296              :     unsigned int trackedTxs GUARDED_BY(m_cs_fee_estimator){0};
     297              :     unsigned int untrackedTxs GUARDED_BY(m_cs_fee_estimator){0};
     298              : 
     299              :     std::vector<double> buckets GUARDED_BY(m_cs_fee_estimator); // The upper-bound of the range for the bucket (inclusive)
     300              :     std::map<double, unsigned int> bucketMap GUARDED_BY(m_cs_fee_estimator); // Map of bucket upper-bound to index into all vectors by bucket
     301              : 
     302              :     /** Process a transaction confirmed in a block*/
     303              :     bool processBlockTx(unsigned int nBlockHeight, const RemovedMempoolTransactionInfo& tx) EXCLUSIVE_LOCKS_REQUIRED(m_cs_fee_estimator);
     304              : 
     305              :     /** Helper for estimateSmartFee */
     306              :     double estimateCombinedFee(unsigned int confTarget, double successThreshold, bool checkShorterHorizon, EstimationResult *result) const EXCLUSIVE_LOCKS_REQUIRED(m_cs_fee_estimator);
     307              :     /** Helper for estimateSmartFee */
     308              :     double estimateConservativeFee(unsigned int doubleTarget, EstimationResult *result) const EXCLUSIVE_LOCKS_REQUIRED(m_cs_fee_estimator);
     309              :     /** Number of blocks of data recorded while fee estimates have been running */
     310              :     unsigned int BlockSpan() const EXCLUSIVE_LOCKS_REQUIRED(m_cs_fee_estimator);
     311              :     /** Number of blocks of recorded fee estimate data represented in saved data file */
     312              :     unsigned int HistoricalBlockSpan() const EXCLUSIVE_LOCKS_REQUIRED(m_cs_fee_estimator);
     313              :     /** Calculation of highest target that reasonable estimate can be provided for */
     314              :     unsigned int MaxUsableEstimate() const EXCLUSIVE_LOCKS_REQUIRED(m_cs_fee_estimator);
     315              : 
     316              :     /** A non-thread-safe helper for the removeTx function */
     317              :     bool _removeTx(const Txid& hash, bool inBlock)
     318              :         EXCLUSIVE_LOCKS_REQUIRED(m_cs_fee_estimator);
     319              : };
     320              : 
     321            1 : class FeeFilterRounder
     322              : {
     323              : private:
     324              :     static constexpr double MAX_FILTER_FEERATE = 1e7;
     325              :     /** FEE_FILTER_SPACING is just used to provide some quantization of fee
     326              :      * filter results.  Historically it reused FEE_SPACING, but it is completely
     327              :      * unrelated, and was made a separate constant so the two concepts are not
     328              :      * tied together */
     329              :     static constexpr double FEE_FILTER_SPACING = 1.1;
     330              : 
     331              : public:
     332              :     /** Create new FeeFilterRounder */
     333              :     explicit FeeFilterRounder(const CFeeRate& min_incremental_fee, FastRandomContext& rng);
     334              : 
     335              :     /** Quantize a minimum fee for privacy purpose before broadcast. */
     336              :     CAmount round(CAmount currentMinFee) EXCLUSIVE_LOCKS_REQUIRED(!m_insecure_rand_mutex);
     337              : 
     338              : private:
     339              :     const std::set<double> m_fee_set;
     340              :     Mutex m_insecure_rand_mutex;
     341              :     FastRandomContext& insecure_rand GUARDED_BY(m_insecure_rand_mutex);
     342              : };
     343              : 
     344              : #endif // BITCOIN_POLICY_FEES_BLOCK_POLICY_ESTIMATOR_H
        

Generated by: LCOV version 2.0-1