Bitcoin Core 28.99.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#include <validationinterface.h>
16
17#include <array>
18#include <chrono>
19#include <map>
20#include <memory>
21#include <set>
22#include <string>
23#include <vector>
24
25
26// How often to flush fee estimates to fee_estimates.dat.
27static constexpr std::chrono::hours FEE_FLUSH_INTERVAL{1};
28
33static constexpr std::chrono::hours MAX_FILE_AGE{60};
34
35// Whether we allow importing a fee_estimates file older than MAX_FILE_AGE.
36static constexpr bool DEFAULT_ACCEPT_STALE_FEE_ESTIMATES{false};
37
38class AutoFile;
39class TxConfirmStats;
42
43/* Identifier for each of the 3 different TxConfirmStats which will track
44 * history over different time horizons. */
49};
50
51static constexpr auto ALL_FEE_ESTIMATE_HORIZONS = std::array{
55};
56
58
59/* Enumeration of reason for returned fee estimate */
60enum class FeeReason {
61 NONE,
70};
71
72/* Used to return detailed information about a feerate bucket */
74{
75 double start = -1;
76 double end = -1;
77 double withinTarget = 0;
78 double totalConfirmed = 0;
79 double inMempool = 0;
80 double leftMempool = 0;
81};
82
83/* Used to return detailed information about a fee estimate calculation */
85{
88 double decay = 0;
89 unsigned int scale = 0;
90};
91
93{
98};
99
149{
150private:
152 static constexpr unsigned int SHORT_BLOCK_PERIODS = 12;
153 static constexpr unsigned int SHORT_SCALE = 1;
155 static constexpr unsigned int MED_BLOCK_PERIODS = 24;
156 static constexpr unsigned int MED_SCALE = 2;
158 static constexpr unsigned int LONG_BLOCK_PERIODS = 42;
159 static constexpr unsigned int LONG_SCALE = 24;
161 static const unsigned int OLDEST_ESTIMATE_HISTORY = 6 * 1008;
162
164 static constexpr double SHORT_DECAY = .962;
166 static constexpr double MED_DECAY = .9952;
168 static constexpr double LONG_DECAY = .99931;
169
171 static constexpr double HALF_SUCCESS_PCT = .6;
173 static constexpr double SUCCESS_PCT = .85;
175 static constexpr double DOUBLE_SUCCESS_PCT = .95;
176
178 static constexpr double SUFFICIENT_FEETXS = 0.1;
180 static constexpr double SUFFICIENT_TXS_SHORT = 0.5;
181
189 static constexpr double MIN_BUCKET_FEERATE = 1000;
190 static constexpr double MAX_BUCKET_FEERATE = 1e7;
191
197 static constexpr double FEE_SPACING = 1.05;
198
200public:
202 CBlockPolicyEstimator(const fs::path& estimation_filepath, const bool read_stale_estimates);
204
206 void processBlock(const std::vector<RemovedMempoolTransactionInfo>& txs_removed_for_block,
207 unsigned int nBlockHeight)
209
213
215 bool removeTx(uint256 hash)
217
219 CFeeRate estimateFee(int confTarget) const
221
227 CFeeRate estimateSmartFee(int confTarget, FeeCalculation *feeCalc, bool conservative) const
229
234 CFeeRate estimateRawFee(int confTarget, double successThreshold, FeeEstimateHorizon horizon,
235 EstimationResult* result = nullptr) const
237
239 bool Write(AutoFile& fileout) const
241
243 bool Read(AutoFile& filein)
245
247 void FlushUnconfirmed()
249
251 unsigned int HighestTargetTracked(FeeEstimateHorizon horizon) const
253
255 void Flush()
257
259 void FlushFeeEstimates()
261
263 std::chrono::hours GetFeeEstimatorFileAge();
264
265protected:
267 void TransactionAddedToMempool(const NewMempoolTransactionInfo& tx, uint64_t /*unused*/) override
269 void TransactionRemovedFromMempool(const CTransactionRef& tx, MemPoolRemovalReason /*unused*/, uint64_t /*unused*/) override
271 void MempoolTransactionsRemovedForBlock(const std::vector<RemovedMempoolTransactionInfo>& txs_removed_for_block, unsigned int nBlockHeight) override
273
274private:
276
277 unsigned int nBestSeenHeight GUARDED_BY(m_cs_fee_estimator){0};
278 unsigned int firstRecordedHeight GUARDED_BY(m_cs_fee_estimator){0};
279 unsigned int historicalFirst GUARDED_BY(m_cs_fee_estimator){0};
280 unsigned int historicalBest GUARDED_BY(m_cs_fee_estimator){0};
281
283 {
284 unsigned int blockHeight{0};
285 unsigned int bucketIndex{0};
286 TxStatsInfo() = default;
287 };
288
289 // map of txids to information about that transaction
290 std::map<uint256, TxStatsInfo> mapMemPoolTxs GUARDED_BY(m_cs_fee_estimator);
291
293 std::unique_ptr<TxConfirmStats> feeStats PT_GUARDED_BY(m_cs_fee_estimator);
294 std::unique_ptr<TxConfirmStats> shortStats PT_GUARDED_BY(m_cs_fee_estimator);
295 std::unique_ptr<TxConfirmStats> longStats PT_GUARDED_BY(m_cs_fee_estimator);
296
297 unsigned int trackedTxs GUARDED_BY(m_cs_fee_estimator){0};
298 unsigned int untrackedTxs GUARDED_BY(m_cs_fee_estimator){0};
299
300 std::vector<double> buckets GUARDED_BY(m_cs_fee_estimator); // The upper-bound of the range for the bucket (inclusive)
301 std::map<double, unsigned int> bucketMap GUARDED_BY(m_cs_fee_estimator); // Map of bucket upper-bound to index into all vectors by bucket
302
305
307 double estimateCombinedFee(unsigned int confTarget, double successThreshold, bool checkShorterHorizon, EstimationResult *result) const EXCLUSIVE_LOCKS_REQUIRED(m_cs_fee_estimator);
309 double estimateConservativeFee(unsigned int doubleTarget, EstimationResult *result) const EXCLUSIVE_LOCKS_REQUIRED(m_cs_fee_estimator);
316
318 bool _removeTx(const uint256& hash, bool inBlock)
320};
321
323{
324private:
325 static constexpr double MAX_FILTER_FEERATE = 1e7;
330 static constexpr double FEE_FILTER_SPACING = 1.1;
331
332public:
334 explicit FeeFilterRounder(const CFeeRate& min_incremental_fee, FastRandomContext& rng);
335
337 CAmount round(CAmount currentMinFee) EXCLUSIVE_LOCKS_REQUIRED(!m_insecure_rand_mutex);
338
339private:
340 const std::set<double> m_fee_set;
342 FastRandomContext& insecure_rand GUARDED_BY(m_insecure_rand_mutex);
343};
344
345#endif // BITCOIN_POLICY_FEES_H
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
Non-refcounted RAII wrapper for FILE*.
Definition: streams.h:392
The BlockPolicyEstimator is used for estimating the feerate needed for a transaction to be included i...
Definition: fees.h:149
void processTransaction(const NewMempoolTransactionInfo &tx) EXCLUSIVE_LOCKS_REQUIRED(!m_cs_fee_estimator)
Process a transaction accepted to the mempool.
Definition: fees.cpp:595
std::unique_ptr< TxConfirmStats > shortStats PT_GUARDED_BY(m_cs_fee_estimator)
std::unique_ptr< TxConfirmStats > feeStats PT_GUARDED_BY(m_cs_fee_estimator)
Classes to track historical data on transaction confirmations.
std::map< uint256, TxStatsInfo > mapMemPoolTxs GUARDED_BY(m_cs_fee_estimator)
static constexpr unsigned int LONG_SCALE
Definition: fees.h:159
unsigned int trackedTxs GUARDED_BY(m_cs_fee_estimator)
Definition: fees.h:297
static constexpr double SUCCESS_PCT
Require greater than 85% of X feerate transactions to be confirmed within Y blocks.
Definition: fees.h:173
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:189
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:807
static constexpr double FEE_SPACING
Spacing of FeeRate buckets We have to lump transactions into buckets based on feerate,...
Definition: fees.h:197
unsigned int nBestSeenHeight GUARDED_BY(m_cs_fee_estimator)
Definition: fees.h:277
static const unsigned int OLDEST_ESTIMATE_HISTORY
Historical estimates that are older than this aren't valid.
Definition: fees.h:161
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:948
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:178
static constexpr double MAX_BUCKET_FEERATE
Definition: fees.h:190
unsigned int historicalBest GUARDED_BY(m_cs_fee_estimator)
Definition: fees.h:280
void FlushFeeEstimates() EXCLUSIVE_LOCKS_REQUIRED(!m_cs_fee_estimator)
Record current fee estimations.
Definition: fees.cpp:953
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:870
static constexpr unsigned int LONG_BLOCK_PERIODS
Track confirm delays up to 1008 blocks for long horizon.
Definition: fees.h:158
bool Write(AutoFile &fileout) const EXCLUSIVE_LOCKS_REQUIRED(!m_cs_fee_estimator)
Write estimation data to a file.
Definition: fees.cpp:963
static constexpr double SHORT_DECAY
Decay of .962 is a half-life of 18 blocks or about 3 hours.
Definition: fees.h:164
std::chrono::hours GetFeeEstimatorFileAge()
Calculates the age of the file, since last modified.
Definition: fees.cpp:1064
Mutex m_cs_fee_estimator
Definition: fees.h:275
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:762
unsigned int firstRecordedHeight GUARDED_BY(m_cs_fee_estimator)
Definition: fees.h:278
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:527
static constexpr double LONG_DECAY
Decay of .99931 is a half-life of 1008 blocks or about 1 week.
Definition: fees.h:168
double estimateConservativeFee(unsigned int doubleTarget, EstimationResult *result) const EXCLUSIVE_LOCKS_REQUIRED(m_cs_fee_estimator)
Helper for estimateSmartFee.
Definition: fees.cpp:846
void TransactionRemovedFromMempool(const CTransactionRef &tx, MemPoolRemovalReason, uint64_t) override EXCLUSIVE_LOCKS_REQUIRED(!m_cs_fee_estimator)
Notifies listeners of a transaction leaving mempool.
Definition: fees.cpp:585
static constexpr double HALF_SUCCESS_PCT
Require greater than 60% of X feerate transactions to be confirmed within Y/2 blocks.
Definition: fees.h:171
static constexpr double MED_DECAY
Decay of .9952 is a half-life of 144 blocks or about 1 day.
Definition: fees.h:166
std::map< double, unsigned int > bucketMap GUARDED_BY(m_cs_fee_estimator)
unsigned int historicalFirst GUARDED_BY(m_cs_fee_estimator)
Definition: fees.h:279
CFeeRate estimateFee(int confTarget) const EXCLUSIVE_LOCKS_REQUIRED(!m_cs_fee_estimator)
DEPRECATED.
Definition: fees.cpp:717
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:542
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:797
static constexpr unsigned int SHORT_SCALE
Definition: fees.h:153
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:779
void MempoolTransactionsRemovedForBlock(const std::vector< RemovedMempoolTransactionInfo > &txs_removed_for_block, unsigned int nBlockHeight) override EXCLUSIVE_LOCKS_REQUIRED(!m_cs_fee_estimator)
Definition: fees.cpp:590
bool Read(AutoFile &filein) EXCLUSIVE_LOCKS_REQUIRED(!m_cs_fee_estimator)
Read estimation data from a file.
Definition: fees.cpp:988
static constexpr unsigned int SHORT_BLOCK_PERIODS
Track confirm delays up to 12 blocks for short horizon.
Definition: fees.h:152
static constexpr double DOUBLE_SUCCESS_PCT
Require greater than 95% of X feerate transactions to be confirmed within 2 * Y blocks.
Definition: fees.h:175
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:787
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:1050
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:726
unsigned int untrackedTxs GUARDED_BY(m_cs_fee_estimator)
Definition: fees.h:298
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:180
bool processBlockTx(unsigned int nBlockHeight, const RemovedMempoolTransactionInfo &tx) EXCLUSIVE_LOCKS_REQUIRED(m_cs_fee_estimator)
Process a transaction confirmed in a block.
Definition: fees.cpp:640
static constexpr unsigned int MED_SCALE
Definition: fees.h:156
std::unique_ptr< TxConfirmStats > longStats PT_GUARDED_BY(m_cs_fee_estimator)
static constexpr unsigned int MED_BLOCK_PERIODS
Track confirm delays up to 48 blocks for medium horizon.
Definition: fees.h:155
bool removeTx(uint256 hash) EXCLUSIVE_LOCKS_REQUIRED(!m_cs_fee_estimator)
Remove a transaction from the mempool tracking stats for non BLOCK removal reasons.
Definition: fees.cpp:521
const fs::path m_estimation_filepath
Definition: fees.h:199
std::vector< double > buckets GUARDED_BY(m_cs_fee_estimator)
virtual ~CBlockPolicyEstimator()
void TransactionAddedToMempool(const NewMempoolTransactionInfo &tx, uint64_t) override EXCLUSIVE_LOCKS_REQUIRED(!m_cs_fee_estimator)
Overridden from CValidationInterface.
Definition: fees.cpp:580
void processBlock(const std::vector< RemovedMempoolTransactionInfo > &txs_removed_for_block, unsigned int nBlockHeight) EXCLUSIVE_LOCKS_REQUIRED(!m_cs_fee_estimator)
Process all the transactions that have been included in a block.
Definition: fees.cpp:668
Fee rate in satoshis per kilovirtualbyte: CAmount / kvB.
Definition: feerate.h:33
Implement this to subscribe to events generated in validation and mempool.
Fast randomness source.
Definition: random.h:377
const std::set< double > m_fee_set
Definition: fees.h:340
FastRandomContext &insecure_rand GUARDED_BY(m_insecure_rand_mutex)
Mutex m_insecure_rand_mutex
Definition: fees.h:341
We will instantiate an instance of this class to track transactions that were included in a block.
Definition: fees.cpp:78
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
Definition: fs.h:33
256-bit opaque blob.
Definition: uint256.h:190
@ CONSERVATIVE
Force estimateSmartFee to use conservative estimates.
MemPoolRemovalReason
Reason why a transaction was removed from the mempool, this is passed to the notification signal.
static constexpr bool DEFAULT_ACCEPT_STALE_FEE_ESTIMATES
Definition: fees.h:36
static constexpr auto ALL_FEE_ESTIMATE_HORIZONS
Definition: fees.h:51
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:33
static constexpr std::chrono::hours FEE_FLUSH_INTERVAL
Definition: fees.h:27
FeeEstimateHorizon
Definition: fees.h:45
std::string StringForFeeEstimateHorizon(FeeEstimateHorizon horizon)
Definition: fees.cpp:40
FeeReason
Definition: fees.h:60
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:423
EstimatorBucket fail
Definition: fees.h:87
EstimatorBucket pass
Definition: fees.h:86
double decay
Definition: fees.h:88
unsigned int scale
Definition: fees.h:89
double totalConfirmed
Definition: fees.h:78
double end
Definition: fees.h:76
double leftMempool
Definition: fees.h:80
double start
Definition: fees.h:75
double withinTarget
Definition: fees.h:77
double inMempool
Definition: fees.h:79
int returnedTarget
Definition: fees.h:97
int desiredTarget
Definition: fees.h:96
FeeReason reason
Definition: fees.h:95
EstimationResult est
Definition: fees.h:94
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49