Bitcoin Core  26.1.0
P2P Digital Currency
fees.h
Go to the documentation of this file.
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 #ifndef BITCOIN_POLICY_FEES_H
6 #define BITCOIN_POLICY_FEES_H
7 
8 #include <consensus/amount.h>
9 #include <policy/feerate.h>
10 #include <random.h>
11 #include <sync.h>
12 #include <threadsafety.h>
13 #include <uint256.h>
14 #include <util/fs.h>
15 
16 #include <array>
17 #include <chrono>
18 #include <map>
19 #include <memory>
20 #include <set>
21 #include <string>
22 #include <vector>
23 
24 
25 // How often to flush fee estimates to fee_estimates.dat.
26 static constexpr std::chrono::hours FEE_FLUSH_INTERVAL{1};
27 
32 static constexpr std::chrono::hours MAX_FILE_AGE{60};
33 
34 // Whether we allow importing a fee_estimates file older than MAX_FILE_AGE.
35 static constexpr bool DEFAULT_ACCEPT_STALE_FEE_ESTIMATES{false};
36 
37 class AutoFile;
38 class CTxMemPoolEntry;
39 class TxConfirmStats;
40 
41 /* Identifier for each of the 3 different TxConfirmStats which will track
42  * history over different time horizons. */
43 enum class FeeEstimateHorizon {
47 };
48 
49 static constexpr auto ALL_FEE_ESTIMATE_HORIZONS = std::array{
53 };
54 
56 
57 /* Enumeration of reason for returned fee estimate */
58 enum class FeeReason {
59  NONE,
65  PAYTXFEE,
66  FALLBACK,
67  REQUIRED,
68 };
69 
70 /* Used to return detailed information about a feerate bucket */
72 {
73  double start = -1;
74  double end = -1;
75  double withinTarget = 0;
76  double totalConfirmed = 0;
77  double inMempool = 0;
78  double leftMempool = 0;
79 };
80 
81 /* Used to return detailed information about a fee estimate calculation */
83 {
86  double decay = 0;
87  unsigned int scale = 0;
88 };
89 
91 {
94  int desiredTarget = 0;
95  int returnedTarget = 0;
96 };
97 
147 {
148 private:
150  static constexpr unsigned int SHORT_BLOCK_PERIODS = 12;
151  static constexpr unsigned int SHORT_SCALE = 1;
153  static constexpr unsigned int MED_BLOCK_PERIODS = 24;
154  static constexpr unsigned int MED_SCALE = 2;
156  static constexpr unsigned int LONG_BLOCK_PERIODS = 42;
157  static constexpr unsigned int LONG_SCALE = 24;
159  static const unsigned int OLDEST_ESTIMATE_HISTORY = 6 * 1008;
160 
162  static constexpr double SHORT_DECAY = .962;
164  static constexpr double MED_DECAY = .9952;
166  static constexpr double LONG_DECAY = .99931;
167 
169  static constexpr double HALF_SUCCESS_PCT = .6;
171  static constexpr double SUCCESS_PCT = .85;
173  static constexpr double DOUBLE_SUCCESS_PCT = .95;
174 
176  static constexpr double SUFFICIENT_FEETXS = 0.1;
178  static constexpr double SUFFICIENT_TXS_SHORT = 0.5;
179 
187  static constexpr double MIN_BUCKET_FEERATE = 1000;
188  static constexpr double MAX_BUCKET_FEERATE = 1e7;
189 
195  static constexpr double FEE_SPACING = 1.05;
196 
198 public:
200  CBlockPolicyEstimator(const fs::path& estimation_filepath, const bool read_stale_estimates);
202 
204  void processBlock(unsigned int nBlockHeight,
205  std::vector<const CTxMemPoolEntry*>& entries)
207 
209  void processTransaction(const CTxMemPoolEntry& entry, bool validFeeEstimate)
211 
213  bool removeTx(uint256 hash, bool inBlock)
215 
217  CFeeRate estimateFee(int confTarget) const
219 
225  CFeeRate estimateSmartFee(int confTarget, FeeCalculation *feeCalc, bool conservative) const
227 
232  CFeeRate estimateRawFee(int confTarget, double successThreshold, FeeEstimateHorizon horizon,
233  EstimationResult* result = nullptr) const
235 
237  bool Write(AutoFile& fileout) const
239 
241  bool Read(AutoFile& filein)
243 
245  void FlushUnconfirmed()
247 
249  unsigned int HighestTargetTracked(FeeEstimateHorizon horizon) const
251 
253  void Flush()
255 
257  void FlushFeeEstimates()
259 
261  std::chrono::hours GetFeeEstimatorFileAge();
262 
263 private:
265 
266  unsigned int nBestSeenHeight GUARDED_BY(m_cs_fee_estimator){0};
267  unsigned int firstRecordedHeight GUARDED_BY(m_cs_fee_estimator){0};
268  unsigned int historicalFirst GUARDED_BY(m_cs_fee_estimator){0};
269  unsigned int historicalBest GUARDED_BY(m_cs_fee_estimator){0};
270 
271  struct TxStatsInfo
272  {
273  unsigned int blockHeight{0};
274  unsigned int bucketIndex{0};
276  };
277 
278  // map of txids to information about that transaction
279  std::map<uint256, TxStatsInfo> mapMemPoolTxs GUARDED_BY(m_cs_fee_estimator);
280 
282  std::unique_ptr<TxConfirmStats> feeStats PT_GUARDED_BY(m_cs_fee_estimator);
283  std::unique_ptr<TxConfirmStats> shortStats PT_GUARDED_BY(m_cs_fee_estimator);
284  std::unique_ptr<TxConfirmStats> longStats PT_GUARDED_BY(m_cs_fee_estimator);
285 
286  unsigned int trackedTxs GUARDED_BY(m_cs_fee_estimator){0};
287  unsigned int untrackedTxs GUARDED_BY(m_cs_fee_estimator){0};
288 
289  std::vector<double> buckets GUARDED_BY(m_cs_fee_estimator); // The upper-bound of the range for the bucket (inclusive)
290  std::map<double, unsigned int> bucketMap GUARDED_BY(m_cs_fee_estimator); // Map of bucket upper-bound to index into all vectors by bucket
291 
293  bool processBlockTx(unsigned int nBlockHeight, const CTxMemPoolEntry* entry) EXCLUSIVE_LOCKS_REQUIRED(m_cs_fee_estimator);
294 
296  double estimateCombinedFee(unsigned int confTarget, double successThreshold, bool checkShorterHorizon, EstimationResult *result) const EXCLUSIVE_LOCKS_REQUIRED(m_cs_fee_estimator);
298  double estimateConservativeFee(unsigned int doubleTarget, EstimationResult *result) const EXCLUSIVE_LOCKS_REQUIRED(m_cs_fee_estimator);
305 
307  bool _removeTx(const uint256& hash, bool inBlock)
309 };
310 
312 {
313 private:
314  static constexpr double MAX_FILTER_FEERATE = 1e7;
319  static constexpr double FEE_FILTER_SPACING = 1.1;
320 
321 public:
323  explicit FeeFilterRounder(const CFeeRate& min_incremental_fee, FastRandomContext& rng);
324 
326  CAmount round(CAmount currentMinFee) EXCLUSIVE_LOCKS_REQUIRED(!m_insecure_rand_mutex);
327 
328 private:
329  const std::set<double> m_fee_set;
331  FastRandomContext& insecure_rand GUARDED_BY(m_insecure_rand_mutex);
332 };
333 
334 #endif // BITCOIN_POLICY_FEES_H
static constexpr double MED_DECAY
Decay of .9952 is a half-life of 144 blocks or about 1 day.
Definition: fees.h:164
EstimatorBucket pass
Definition: fees.h:84
unsigned int trackedTxs GUARDED_BY(m_cs_fee_estimator)
Definition: fees.h:286
bool _removeTx(const uint256 &hash, bool inBlock) EXCLUSIVE_LOCKS_REQUIRED(m_cs_fee_estimator)
A non-thread-safe helper for the removeTx function.
Definition: fees.cpp:516
CFeeRate estimateFee(int confTarget) const EXCLUSIVE_LOCKS_REQUIRED(!m_cs_fee_estimator)
DEPRECATED.
Definition: fees.cpp:685
unsigned int firstRecordedHeight GUARDED_BY(m_cs_fee_estimator)
Definition: fees.h:267
unsigned int untrackedTxs GUARDED_BY(m_cs_fee_estimator)
Definition: fees.h:287
void processBlock(unsigned int nBlockHeight, std::vector< const CTxMemPoolEntry *> &entries) EXCLUSIVE_LOCKS_REQUIRED(!m_cs_fee_estimator)
Process all the transactions that have been included in a block.
Definition: fees.cpp:636
EstimationResult est
Definition: fees.h:92
bool processBlockTx(unsigned int nBlockHeight, const CTxMemPoolEntry *entry) EXCLUSIVE_LOCKS_REQUIRED(m_cs_fee_estimator)
Process a transaction confirmed in a block.
Definition: fees.cpp:608
int returnedTarget
Definition: fees.h:95
static constexpr double MAX_BUCKET_FEERATE
Definition: fees.h:188
static constexpr double HALF_SUCCESS_PCT
Require greater than 60% of X feerate transactions to be confirmed within Y/2 blocks.
Definition: fees.h:169
static constexpr bool DEFAULT_ACCEPT_STALE_FEE_ESTIMATES
Definition: fees.h:35
static constexpr unsigned int MED_BLOCK_PERIODS
Track confirm delays up to 48 blocks for medium horizon.
Definition: fees.h:153
double start
Definition: fees.h:73
double estimateConservativeFee(unsigned int doubleTarget, EstimationResult *result) const EXCLUSIVE_LOCKS_REQUIRED(m_cs_fee_estimator)
Helper for estimateSmartFee.
Definition: fees.cpp:814
static constexpr std::chrono::hours MAX_FILE_AGE
fee_estimates.dat that are more than 60 hours (2.5 days) old will not be read, as fee estimates are b...
Definition: fees.h:32
unsigned int HistoricalBlockSpan() const EXCLUSIVE_LOCKS_REQUIRED(m_cs_fee_estimator)
Number of blocks of recorded fee estimate data represented in saved data file.
Definition: fees.cpp:755
FeeReason reason
Definition: fees.h:93
We will instantiate an instance of this class to track transactions that were included in a block...
Definition: fees.cpp:74
static constexpr std::chrono::hours FEE_FLUSH_INTERVAL
Definition: fees.h:26
static constexpr double DOUBLE_SUCCESS_PCT
Require greater than 95% of X feerate transactions to be confirmed within 2 * Y blocks.
Definition: fees.h:173
static constexpr double FEE_SPACING
Spacing of FeeRate buckets We have to lump transactions into buckets based on feerate, but we want to be able to give accurate estimates over a large range of potential feerates Therefore it makes sense to exponentially space the buckets.
Definition: fees.h:195
unsigned int MaxUsableEstimate() const EXCLUSIVE_LOCKS_REQUIRED(m_cs_fee_estimator)
Calculation of highest target that reasonable estimate can be provided for.
Definition: fees.cpp:765
std::string StringForFeeEstimateHorizon(FeeEstimateHorizon horizon)
Definition: fees.cpp:37
static constexpr double MIN_BUCKET_FEERATE
Minimum and Maximum values for tracking feerates The MIN_BUCKET_FEERATE should just be set to the low...
Definition: fees.h:187
Mutex m_insecure_rand_mutex
Definition: fees.h:330
double withinTarget
Definition: fees.h:75
Non-refcounted RAII wrapper for FILE*.
Definition: streams.h:470
Force estimateSmartFee to use conservative estimates.
bool removeTx(uint256 hash, bool inBlock) EXCLUSIVE_LOCKS_REQUIRED(!m_cs_fee_estimator)
Remove a transaction from the mempool tracking stats.
Definition: fees.cpp:510
Mutex m_cs_fee_estimator
Definition: fees.h:264
int desiredTarget
Definition: fees.h:94
static constexpr double SUFFICIENT_TXS_SHORT
Require an avg of 0.5 tx when using short decay since there are fewer blocks considered.
Definition: fees.h:178
CTxMemPoolEntry stores data about the corresponding transaction, as well as data about all in-mempool...
Definition: mempool_entry.h:65
void FlushFeeEstimates() EXCLUSIVE_LOCKS_REQUIRED(!m_cs_fee_estimator)
Record current fee estimations.
Definition: fees.cpp:921
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
std::chrono::hours GetFeeEstimatorFileAge()
Calculates the age of the file, since last modified.
Definition: fees.cpp:1032
static constexpr double SUCCESS_PCT
Require greater than 85% of X feerate transactions to be confirmed within Y blocks.
Definition: fees.h:171
static constexpr unsigned int SHORT_SCALE
Definition: fees.h:151
static constexpr double LONG_DECAY
Decay of .99931 is a half-life of 1008 blocks or about 1 week.
Definition: fees.h:166
bool Write(AutoFile &fileout) const EXCLUSIVE_LOCKS_REQUIRED(!m_cs_fee_estimator)
Write estimation data to a file.
Definition: fees.cpp:931
static constexpr auto ALL_FEE_ESTIMATE_HORIZONS
Definition: fees.h:49
double end
Definition: fees.h:74
EstimatorBucket fail
Definition: fees.h:85
unsigned int historicalFirst GUARDED_BY(m_cs_fee_estimator)
Definition: fees.h:268
The BlockPolicyEstimator is used for estimating the feerate needed for a transaction to be included i...
Definition: fees.h:146
Fast randomness source.
Definition: random.h:143
unsigned int BlockSpan() const EXCLUSIVE_LOCKS_REQUIRED(m_cs_fee_estimator)
Number of blocks of data recorded while fee estimates have been running.
Definition: fees.cpp:747
double inMempool
Definition: fees.h:77
void Flush() EXCLUSIVE_LOCKS_REQUIRED(!m_cs_fee_estimator)
Drop still unconfirmed transactions and record current estimations, if the fee estimation file is pre...
Definition: fees.cpp:916
CFeeRate estimateSmartFee(int confTarget, FeeCalculation *feeCalc, bool conservative) const EXCLUSIVE_LOCKS_REQUIRED(!m_cs_fee_estimator)
Estimate feerate needed to get be included in a block within confTarget blocks.
Definition: fees.cpp:838
double estimateCombinedFee(unsigned int confTarget, double successThreshold, bool checkShorterHorizon, EstimationResult *result) const EXCLUSIVE_LOCKS_REQUIRED(m_cs_fee_estimator)
Helper for estimateSmartFee.
Definition: fees.cpp:775
FeeReason
Definition: fees.h:58
std::unique_ptr< TxConfirmStats > feeStats PT_GUARDED_BY(m_cs_fee_estimator)
Classes to track historical data on transaction confirmations.
void processTransaction(const CTxMemPoolEntry &entry, bool validFeeEstimate) EXCLUSIVE_LOCKS_REQUIRED(!m_cs_fee_estimator)
Process a transaction accepted to the mempool.
Definition: fees.cpp:569
unsigned int nBestSeenHeight GUARDED_BY(m_cs_fee_estimator)
Definition: fees.h:266
CBlockPolicyEstimator(const fs::path &estimation_filepath, const bool read_stale_estimates)
Create new BlockPolicyEstimator and initialize stats tracking classes with default values...
Definition: fees.cpp:531
static constexpr unsigned int LONG_SCALE
Definition: fees.h:157
FeeEstimateHorizon
Definition: fees.h:43
256-bit opaque blob.
Definition: uint256.h:106
static constexpr unsigned int MED_SCALE
Definition: fees.h:154
static const unsigned int OLDEST_ESTIMATE_HISTORY
Historical estimates that are older than this aren&#39;t valid.
Definition: fees.h:159
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
unsigned int historicalBest GUARDED_BY(m_cs_fee_estimator)
Definition: fees.h:269
bool Read(AutoFile &filein) EXCLUSIVE_LOCKS_REQUIRED(!m_cs_fee_estimator)
Read estimation data from a file.
Definition: fees.cpp:956
double leftMempool
Definition: fees.h:78
static constexpr unsigned int LONG_BLOCK_PERIODS
Track confirm delays up to 1008 blocks for long horizon.
Definition: fees.h:156
Fee rate in satoshis per kilovirtualbyte: CAmount / kvB.
Definition: feerate.h:32
static constexpr unsigned int SHORT_BLOCK_PERIODS
Track confirm delays up to 12 blocks for short horizon.
Definition: fees.h:150
double totalConfirmed
Definition: fees.h:76
static constexpr double SUFFICIENT_FEETXS
Require an avg of 0.1 tx in the combined feerate bucket per block to have stat significance.
Definition: fees.h:176
static constexpr double SHORT_DECAY
Decay of .962 is a half-life of 18 blocks or about 3 hours.
Definition: fees.h:162
CFeeRate estimateRawFee(int confTarget, double successThreshold, FeeEstimateHorizon horizon, EstimationResult *result=nullptr) const EXCLUSIVE_LOCKS_REQUIRED(!m_cs_fee_estimator)
Return a specific fee estimate calculation with a given success threshold and time horizon...
Definition: fees.cpp:694
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
Definition: fs.h:30
unsigned int scale
Definition: fees.h:87
const fs::path m_estimation_filepath
Definition: fees.h:197
void FlushUnconfirmed() EXCLUSIVE_LOCKS_REQUIRED(!m_cs_fee_estimator)
Empty mempool transactions on shutdown to record failure to confirm for txs still in mempool...
Definition: fees.cpp:1018
unsigned int HighestTargetTracked(FeeEstimateHorizon horizon) const EXCLUSIVE_LOCKS_REQUIRED(!m_cs_fee_estimator)
Calculation of highest target that estimates are tracked for.
Definition: fees.cpp:730
const std::set< double > m_fee_set
Definition: fees.h:329
double decay
Definition: fees.h:86