1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2017 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.
6 #include <policy/fees.h>
7 #include <policy/policy.h>
9 #include <clientversion.h>
10 #include <primitives/transaction.h>
12 #include <txmempool.h>
15 static constexpr double INF_FEERATE
= 1e99
;
17 std::string
StringForFeeEstimateHorizon(FeeEstimateHorizon horizon
) {
18 static const std::map
<FeeEstimateHorizon
, std::string
> horizon_strings
= {
19 {FeeEstimateHorizon::SHORT_HALFLIFE
, "short"},
20 {FeeEstimateHorizon::MED_HALFLIFE
, "medium"},
21 {FeeEstimateHorizon::LONG_HALFLIFE
, "long"},
23 auto horizon_string
= horizon_strings
.find(horizon
);
25 if (horizon_string
== horizon_strings
.end()) return "unknown";
27 return horizon_string
->second
;
30 std::string
StringForFeeReason(FeeReason reason
) {
31 static const std::map
<FeeReason
, std::string
> fee_reason_strings
= {
32 {FeeReason::NONE
, "None"},
33 {FeeReason::HALF_ESTIMATE
, "Half Target 60% Threshold"},
34 {FeeReason::FULL_ESTIMATE
, "Target 85% Threshold"},
35 {FeeReason::DOUBLE_ESTIMATE
, "Double Target 95% Threshold"},
36 {FeeReason::CONSERVATIVE
, "Conservative Double Target longer horizon"},
37 {FeeReason::MEMPOOL_MIN
, "Mempool Min Fee"},
38 {FeeReason::PAYTXFEE
, "PayTxFee set"},
39 {FeeReason::FALLBACK
, "Fallback fee"},
40 {FeeReason::REQUIRED
, "Minimum Required Fee"},
41 {FeeReason::MAXTXFEE
, "MaxTxFee limit"}
43 auto reason_string
= fee_reason_strings
.find(reason
);
45 if (reason_string
== fee_reason_strings
.end()) return "Unknown";
47 return reason_string
->second
;
50 bool FeeModeFromString(const std::string
& mode_string
, FeeEstimateMode
& fee_estimate_mode
) {
51 static const std::map
<std::string
, FeeEstimateMode
> fee_modes
= {
52 {"UNSET", FeeEstimateMode::UNSET
},
53 {"ECONOMICAL", FeeEstimateMode::ECONOMICAL
},
54 {"CONSERVATIVE", FeeEstimateMode::CONSERVATIVE
},
56 auto mode
= fee_modes
.find(mode_string
);
58 if (mode
== fee_modes
.end()) return false;
60 fee_estimate_mode
= mode
->second
;
65 * We will instantiate an instance of this class to track transactions that were
66 * included in a block. We will lump transactions into a bucket according to their
67 * approximate feerate and then track how long it took for those txs to be included in a block
69 * The tracking of unconfirmed (mempool) transactions is completely independent of the
70 * historical tracking of transactions that have been confirmed in a block.
75 //Define the buckets we will group transactions into
76 const std::vector
<double>& buckets
; // The upper-bound of the range for the bucket (inclusive)
77 const std::map
<double, unsigned int>& bucketMap
; // Map of bucket upper-bound to index into all vectors by bucket
80 // Count the total # of txs in each bucket
81 // Track the historical moving average of this total over blocks
82 std::vector
<double> txCtAvg
;
84 // Count the total # of txs confirmed within Y blocks in each bucket
85 // Track the historical moving average of theses totals over blocks
86 std::vector
<std::vector
<double>> confAvg
; // confAvg[Y][X]
88 // Track moving avg of txs which have been evicted from the mempool
89 // after failing to be confirmed within Y blocks
90 std::vector
<std::vector
<double>> failAvg
; // failAvg[Y][X]
92 // Sum the total feerate of all tx's in each bucket
93 // Track the historical moving average of this total over blocks
94 std::vector
<double> avg
;
96 // Combine the conf counts with tx counts to calculate the confirmation % for each Y,X
97 // Combine the total value with the tx counts to calculate the avg feerate per bucket
101 // Resolution (# of blocks) with which confirmations are tracked
104 // Mempool counts of outstanding transactions
105 // For each bucket X, track the number of transactions in the mempool
106 // that are unconfirmed for each possible confirmation value Y
107 std::vector
<std::vector
<int> > unconfTxs
; //unconfTxs[Y][X]
108 // transactions still unconfirmed after GetMaxConfirms for each bucket
109 std::vector
<int> oldUnconfTxs
;
111 void resizeInMemoryCounters(size_t newbuckets
);
115 * Create new TxConfirmStats. This is called by BlockPolicyEstimator's
116 * constructor with default values.
117 * @param defaultBuckets contains the upper limits for the bucket boundaries
118 * @param maxPeriods max number of periods to track
119 * @param decay how much to decay the historical moving average per block
121 TxConfirmStats(const std::vector
<double>& defaultBuckets
, const std::map
<double, unsigned int>& defaultBucketMap
,
122 unsigned int maxPeriods
, double decay
, unsigned int scale
);
124 /** Roll the circular buffer for unconfirmed txs*/
125 void ClearCurrent(unsigned int nBlockHeight
);
128 * Record a new transaction data point in the current block stats
129 * @param blocksToConfirm the number of blocks it took this transaction to confirm
130 * @param val the feerate of the transaction
131 * @warning blocksToConfirm is 1-based and has to be >= 1
133 void Record(int blocksToConfirm
, double val
);
135 /** Record a new transaction entering the mempool*/
136 unsigned int NewTx(unsigned int nBlockHeight
, double val
);
138 /** Remove a transaction from mempool tracking stats*/
139 void removeTx(unsigned int entryHeight
, unsigned int nBestSeenHeight
,
140 unsigned int bucketIndex
, bool inBlock
);
142 /** Update our estimates by decaying our historical moving average and updating
143 with the data gathered from the current block */
144 void UpdateMovingAverages();
147 * Calculate a feerate estimate. Find the lowest value bucket (or range of buckets
148 * to make sure we have enough data points) whose transactions still have sufficient likelihood
149 * of being confirmed within the target number of confirmations
150 * @param confTarget target number of confirmations
151 * @param sufficientTxVal required average number of transactions per block in a bucket range
152 * @param minSuccess the success probability we require
153 * @param requireGreater return the lowest feerate such that all higher values pass minSuccess OR
154 * return the highest feerate such that all lower values fail minSuccess
155 * @param nBlockHeight the current block height
157 double EstimateMedianVal(int confTarget
, double sufficientTxVal
,
158 double minSuccess
, bool requireGreater
, unsigned int nBlockHeight
,
159 EstimationResult
*result
= nullptr) const;
161 /** Return the max number of confirms we're tracking */
162 unsigned int GetMaxConfirms() const { return scale
* confAvg
.size(); }
164 /** Write state of estimation data to a file*/
165 void Write(CAutoFile
& fileout
) const;
168 * Read saved state of estimation data from a file and replace all internal data structures and
169 * variables with this state.
171 void Read(CAutoFile
& filein
, int nFileVersion
, size_t numBuckets
);
175 TxConfirmStats::TxConfirmStats(const std::vector
<double>& defaultBuckets
,
176 const std::map
<double, unsigned int>& defaultBucketMap
,
177 unsigned int maxPeriods
, double _decay
, unsigned int _scale
)
178 : buckets(defaultBuckets
), bucketMap(defaultBucketMap
)
181 assert(_scale
!= 0 && "_scale must be non-zero");
183 confAvg
.resize(maxPeriods
);
184 for (unsigned int i
= 0; i
< maxPeriods
; i
++) {
185 confAvg
[i
].resize(buckets
.size());
187 failAvg
.resize(maxPeriods
);
188 for (unsigned int i
= 0; i
< maxPeriods
; i
++) {
189 failAvg
[i
].resize(buckets
.size());
192 txCtAvg
.resize(buckets
.size());
193 avg
.resize(buckets
.size());
195 resizeInMemoryCounters(buckets
.size());
198 void TxConfirmStats::resizeInMemoryCounters(size_t newbuckets
) {
199 // newbuckets must be passed in because the buckets referred to during Read have not been updated yet.
200 unconfTxs
.resize(GetMaxConfirms());
201 for (unsigned int i
= 0; i
< unconfTxs
.size(); i
++) {
202 unconfTxs
[i
].resize(newbuckets
);
204 oldUnconfTxs
.resize(newbuckets
);
207 // Roll the unconfirmed txs circular buffer
208 void TxConfirmStats::ClearCurrent(unsigned int nBlockHeight
)
210 for (unsigned int j
= 0; j
< buckets
.size(); j
++) {
211 oldUnconfTxs
[j
] += unconfTxs
[nBlockHeight
%unconfTxs
.size()][j
];
212 unconfTxs
[nBlockHeight
%unconfTxs
.size()][j
] = 0;
217 void TxConfirmStats::Record(int blocksToConfirm
, double val
)
219 // blocksToConfirm is 1-based
220 if (blocksToConfirm
< 1)
222 int periodsToConfirm
= (blocksToConfirm
+ scale
- 1)/scale
;
223 unsigned int bucketindex
= bucketMap
.lower_bound(val
)->second
;
224 for (size_t i
= periodsToConfirm
; i
<= confAvg
.size(); i
++) {
225 confAvg
[i
- 1][bucketindex
]++;
227 txCtAvg
[bucketindex
]++;
228 avg
[bucketindex
] += val
;
231 void TxConfirmStats::UpdateMovingAverages()
233 for (unsigned int j
= 0; j
< buckets
.size(); j
++) {
234 for (unsigned int i
= 0; i
< confAvg
.size(); i
++)
235 confAvg
[i
][j
] = confAvg
[i
][j
] * decay
;
236 for (unsigned int i
= 0; i
< failAvg
.size(); i
++)
237 failAvg
[i
][j
] = failAvg
[i
][j
] * decay
;
238 avg
[j
] = avg
[j
] * decay
;
239 txCtAvg
[j
] = txCtAvg
[j
] * decay
;
243 // returns -1 on error conditions
244 double TxConfirmStats::EstimateMedianVal(int confTarget
, double sufficientTxVal
,
245 double successBreakPoint
, bool requireGreater
,
246 unsigned int nBlockHeight
, EstimationResult
*result
) const
248 // Counters for a bucket (or range of buckets)
249 double nConf
= 0; // Number of tx's confirmed within the confTarget
250 double totalNum
= 0; // Total number of tx's that were ever confirmed
251 int extraNum
= 0; // Number of tx's still in mempool for confTarget or longer
252 double failNum
= 0; // Number of tx's that were never confirmed but removed from the mempool after confTarget
253 int periodTarget
= (confTarget
+ scale
- 1)/scale
;
255 int maxbucketindex
= buckets
.size() - 1;
257 // requireGreater means we are looking for the lowest feerate such that all higher
258 // values pass, so we start at maxbucketindex (highest feerate) and look at successively
259 // smaller buckets until we reach failure. Otherwise, we are looking for the highest
260 // feerate such that all lower values fail, and we go in the opposite direction.
261 unsigned int startbucket
= requireGreater
? maxbucketindex
: 0;
262 int step
= requireGreater
? -1 : 1;
264 // We'll combine buckets until we have enough samples.
265 // The near and far variables will define the range we've combined
266 // The best variables are the last range we saw which still had a high
267 // enough confirmation rate to count as success.
268 // The cur variables are the current range we're counting.
269 unsigned int curNearBucket
= startbucket
;
270 unsigned int bestNearBucket
= startbucket
;
271 unsigned int curFarBucket
= startbucket
;
272 unsigned int bestFarBucket
= startbucket
;
274 bool foundAnswer
= false;
275 unsigned int bins
= unconfTxs
.size();
276 bool newBucketRange
= true;
278 EstimatorBucket passBucket
;
279 EstimatorBucket failBucket
;
281 // Start counting from highest(default) or lowest feerate transactions
282 for (int bucket
= startbucket
; bucket
>= 0 && bucket
<= maxbucketindex
; bucket
+= step
) {
283 if (newBucketRange
) {
284 curNearBucket
= bucket
;
285 newBucketRange
= false;
287 curFarBucket
= bucket
;
288 nConf
+= confAvg
[periodTarget
- 1][bucket
];
289 totalNum
+= txCtAvg
[bucket
];
290 failNum
+= failAvg
[periodTarget
- 1][bucket
];
291 for (unsigned int confct
= confTarget
; confct
< GetMaxConfirms(); confct
++)
292 extraNum
+= unconfTxs
[(nBlockHeight
- confct
)%bins
][bucket
];
293 extraNum
+= oldUnconfTxs
[bucket
];
294 // If we have enough transaction data points in this range of buckets,
295 // we can test for success
296 // (Only count the confirmed data points, so that each confirmation count
297 // will be looking at the same amount of data and same bucket breaks)
298 if (totalNum
>= sufficientTxVal
/ (1 - decay
)) {
299 double curPct
= nConf
/ (totalNum
+ failNum
+ extraNum
);
301 // Check to see if we are no longer getting confirmed at the success rate
302 if ((requireGreater
&& curPct
< successBreakPoint
) || (!requireGreater
&& curPct
> successBreakPoint
)) {
303 if (passing
== true) {
304 // First time we hit a failure record the failed bucket
305 unsigned int failMinBucket
= std::min(curNearBucket
, curFarBucket
);
306 unsigned int failMaxBucket
= std::max(curNearBucket
, curFarBucket
);
307 failBucket
.start
= failMinBucket
? buckets
[failMinBucket
- 1] : 0;
308 failBucket
.end
= buckets
[failMaxBucket
];
309 failBucket
.withinTarget
= nConf
;
310 failBucket
.totalConfirmed
= totalNum
;
311 failBucket
.inMempool
= extraNum
;
312 failBucket
.leftMempool
= failNum
;
317 // Otherwise update the cumulative stats, and the bucket variables
318 // and reset the counters
320 failBucket
= EstimatorBucket(); // Reset any failed bucket, currently passing
323 passBucket
.withinTarget
= nConf
;
325 passBucket
.totalConfirmed
= totalNum
;
327 passBucket
.inMempool
= extraNum
;
328 passBucket
.leftMempool
= failNum
;
331 bestNearBucket
= curNearBucket
;
332 bestFarBucket
= curFarBucket
;
333 newBucketRange
= true;
341 // Calculate the "average" feerate of the best bucket range that met success conditions
342 // Find the bucket with the median transaction and then report the average feerate from that bucket
343 // This is a compromise between finding the median which we can't since we don't save all tx's
344 // and reporting the average which is less accurate
345 unsigned int minBucket
= std::min(bestNearBucket
, bestFarBucket
);
346 unsigned int maxBucket
= std::max(bestNearBucket
, bestFarBucket
);
347 for (unsigned int j
= minBucket
; j
<= maxBucket
; j
++) {
350 if (foundAnswer
&& txSum
!= 0) {
352 for (unsigned int j
= minBucket
; j
<= maxBucket
; j
++) {
353 if (txCtAvg
[j
] < txSum
)
355 else { // we're in the right bucket
356 median
= avg
[j
] / txCtAvg
[j
];
361 passBucket
.start
= minBucket
? buckets
[minBucket
-1] : 0;
362 passBucket
.end
= buckets
[maxBucket
];
365 // If we were passing until we reached last few buckets with insufficient data, then report those as failed
366 if (passing
&& !newBucketRange
) {
367 unsigned int failMinBucket
= std::min(curNearBucket
, curFarBucket
);
368 unsigned int failMaxBucket
= std::max(curNearBucket
, curFarBucket
);
369 failBucket
.start
= failMinBucket
? buckets
[failMinBucket
- 1] : 0;
370 failBucket
.end
= buckets
[failMaxBucket
];
371 failBucket
.withinTarget
= nConf
;
372 failBucket
.totalConfirmed
= totalNum
;
373 failBucket
.inMempool
= extraNum
;
374 failBucket
.leftMempool
= failNum
;
377 LogPrint(BCLog::ESTIMATEFEE
, "FeeEst: %d %s%.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",
378 confTarget
, requireGreater
? ">" : "<", 100.0 * successBreakPoint
, decay
,
379 median
, passBucket
.start
, passBucket
.end
,
380 100 * passBucket
.withinTarget
/ (passBucket
.totalConfirmed
+ passBucket
.inMempool
+ passBucket
.leftMempool
),
381 passBucket
.withinTarget
, passBucket
.totalConfirmed
, passBucket
.inMempool
, passBucket
.leftMempool
,
382 failBucket
.start
, failBucket
.end
,
383 100 * failBucket
.withinTarget
/ (failBucket
.totalConfirmed
+ failBucket
.inMempool
+ failBucket
.leftMempool
),
384 failBucket
.withinTarget
, failBucket
.totalConfirmed
, failBucket
.inMempool
, failBucket
.leftMempool
);
388 result
->pass
= passBucket
;
389 result
->fail
= failBucket
;
390 result
->decay
= decay
;
391 result
->scale
= scale
;
396 void TxConfirmStats::Write(CAutoFile
& fileout
) const
406 void TxConfirmStats::Read(CAutoFile
& filein
, int nFileVersion
, size_t numBuckets
)
408 // Read data file and do some very basic sanity checking
409 // buckets and bucketMap are not updated yet, so don't access them
410 // If there is a read failure, we'll just discard this entire object anyway
411 size_t maxConfirms
, maxPeriods
;
413 // The current version will store the decay with each individual TxConfirmStats and also keep a scale factor
415 if (decay
<= 0 || decay
>= 1) {
416 throw std::runtime_error("Corrupt estimates file. Decay must be between 0 and 1 (non-inclusive)");
420 throw std::runtime_error("Corrupt estimates file. Scale must be non-zero");
424 if (avg
.size() != numBuckets
) {
425 throw std::runtime_error("Corrupt estimates file. Mismatch in feerate average bucket count");
428 if (txCtAvg
.size() != numBuckets
) {
429 throw std::runtime_error("Corrupt estimates file. Mismatch in tx count bucket count");
432 maxPeriods
= confAvg
.size();
433 maxConfirms
= scale
* maxPeriods
;
435 if (maxConfirms
<= 0 || maxConfirms
> 6 * 24 * 7) { // one week
436 throw std::runtime_error("Corrupt estimates file. Must maintain estimates for between 1 and 1008 (one week) confirms");
438 for (unsigned int i
= 0; i
< maxPeriods
; i
++) {
439 if (confAvg
[i
].size() != numBuckets
) {
440 throw std::runtime_error("Corrupt estimates file. Mismatch in feerate conf average bucket count");
445 if (maxPeriods
!= failAvg
.size()) {
446 throw std::runtime_error("Corrupt estimates file. Mismatch in confirms tracked for failures");
448 for (unsigned int i
= 0; i
< maxPeriods
; i
++) {
449 if (failAvg
[i
].size() != numBuckets
) {
450 throw std::runtime_error("Corrupt estimates file. Mismatch in one of failure average bucket counts");
454 // Resize the current block variables which aren't stored in the data file
455 // to match the number of confirms and buckets
456 resizeInMemoryCounters(numBuckets
);
458 LogPrint(BCLog::ESTIMATEFEE
, "Reading estimates: %u buckets counting confirms up to %u blocks\n",
459 numBuckets
, maxConfirms
);
462 unsigned int TxConfirmStats::NewTx(unsigned int nBlockHeight
, double val
)
464 unsigned int bucketindex
= bucketMap
.lower_bound(val
)->second
;
465 unsigned int blockIndex
= nBlockHeight
% unconfTxs
.size();
466 unconfTxs
[blockIndex
][bucketindex
]++;
470 void TxConfirmStats::removeTx(unsigned int entryHeight
, unsigned int nBestSeenHeight
, unsigned int bucketindex
, bool inBlock
)
472 //nBestSeenHeight is not updated yet for the new block
473 int blocksAgo
= nBestSeenHeight
- entryHeight
;
474 if (nBestSeenHeight
== 0) // the BlockPolicyEstimator hasn't seen any blocks yet
477 LogPrint(BCLog::ESTIMATEFEE
, "Blockpolicy error, blocks ago is negative for mempool tx\n");
478 return; //This can't happen because we call this with our best seen height, no entries can have higher
481 if (blocksAgo
>= (int)unconfTxs
.size()) {
482 if (oldUnconfTxs
[bucketindex
] > 0) {
483 oldUnconfTxs
[bucketindex
]--;
485 LogPrint(BCLog::ESTIMATEFEE
, "Blockpolicy error, mempool tx removed from >25 blocks,bucketIndex=%u already\n",
490 unsigned int blockIndex
= entryHeight
% unconfTxs
.size();
491 if (unconfTxs
[blockIndex
][bucketindex
] > 0) {
492 unconfTxs
[blockIndex
][bucketindex
]--;
494 LogPrint(BCLog::ESTIMATEFEE
, "Blockpolicy error, mempool tx removed from blockIndex=%u,bucketIndex=%u already\n",
495 blockIndex
, bucketindex
);
498 if (!inBlock
&& (unsigned int)blocksAgo
>= scale
) { // Only counts as a failure if not confirmed for entire period
500 unsigned int periodsAgo
= blocksAgo
/ scale
;
501 for (size_t i
= 0; i
< periodsAgo
&& i
< failAvg
.size(); i
++) {
502 failAvg
[i
][bucketindex
]++;
507 // This function is called from CTxMemPool::removeUnchecked to ensure
508 // txs removed from the mempool for any reason are no longer
509 // tracked. Txs that were part of a block have already been removed in
510 // processBlockTx to ensure they are never double tracked, but it is
511 // of no harm to try to remove them again.
512 bool CBlockPolicyEstimator::removeTx(uint256 hash
, bool inBlock
)
514 LOCK(cs_feeEstimator
);
515 std::map
<uint256
, TxStatsInfo
>::iterator pos
= mapMemPoolTxs
.find(hash
);
516 if (pos
!= mapMemPoolTxs
.end()) {
517 feeStats
->removeTx(pos
->second
.blockHeight
, nBestSeenHeight
, pos
->second
.bucketIndex
, inBlock
);
518 shortStats
->removeTx(pos
->second
.blockHeight
, nBestSeenHeight
, pos
->second
.bucketIndex
, inBlock
);
519 longStats
->removeTx(pos
->second
.blockHeight
, nBestSeenHeight
, pos
->second
.bucketIndex
, inBlock
);
520 mapMemPoolTxs
.erase(hash
);
527 CBlockPolicyEstimator::CBlockPolicyEstimator()
528 : nBestSeenHeight(0), firstRecordedHeight(0), historicalFirst(0), historicalBest(0), trackedTxs(0), untrackedTxs(0)
530 static_assert(MIN_BUCKET_FEERATE
> 0, "Min feerate must be nonzero");
531 size_t bucketIndex
= 0;
532 for (double bucketBoundary
= MIN_BUCKET_FEERATE
; bucketBoundary
<= MAX_BUCKET_FEERATE
; bucketBoundary
*= FEE_SPACING
, bucketIndex
++) {
533 buckets
.push_back(bucketBoundary
);
534 bucketMap
[bucketBoundary
] = bucketIndex
;
536 buckets
.push_back(INF_FEERATE
);
537 bucketMap
[INF_FEERATE
] = bucketIndex
;
538 assert(bucketMap
.size() == buckets
.size());
540 feeStats
= std::unique_ptr
<TxConfirmStats
>(new TxConfirmStats(buckets
, bucketMap
, MED_BLOCK_PERIODS
, MED_DECAY
, MED_SCALE
));
541 shortStats
= std::unique_ptr
<TxConfirmStats
>(new TxConfirmStats(buckets
, bucketMap
, SHORT_BLOCK_PERIODS
, SHORT_DECAY
, SHORT_SCALE
));
542 longStats
= std::unique_ptr
<TxConfirmStats
>(new TxConfirmStats(buckets
, bucketMap
, LONG_BLOCK_PERIODS
, LONG_DECAY
, LONG_SCALE
));
545 CBlockPolicyEstimator::~CBlockPolicyEstimator()
549 void CBlockPolicyEstimator::processTransaction(const CTxMemPoolEntry
& entry
, bool validFeeEstimate
)
551 LOCK(cs_feeEstimator
);
552 unsigned int txHeight
= entry
.GetHeight();
553 uint256 hash
= entry
.GetTx().GetHash();
554 if (mapMemPoolTxs
.count(hash
)) {
555 LogPrint(BCLog::ESTIMATEFEE
, "Blockpolicy error mempool tx %s already being tracked\n",
556 hash
.ToString().c_str());
560 if (txHeight
!= nBestSeenHeight
) {
561 // Ignore side chains and re-orgs; assuming they are random they don't
562 // affect the estimate. We'll potentially double count transactions in 1-block reorgs.
563 // Ignore txs if BlockPolicyEstimator is not in sync with chainActive.Tip().
564 // It will be synced next time a block is processed.
568 // Only want to be updating estimates when our blockchain is synced,
569 // otherwise we'll miscalculate how many blocks its taking to get included.
570 if (!validFeeEstimate
) {
576 // Feerates are stored and reported as BTC-per-kb:
577 CFeeRate
feeRate(entry
.GetFee(), entry
.GetTxSize());
579 mapMemPoolTxs
[hash
].blockHeight
= txHeight
;
580 unsigned int bucketIndex
= feeStats
->NewTx(txHeight
, (double)feeRate
.GetFeePerK());
581 mapMemPoolTxs
[hash
].bucketIndex
= bucketIndex
;
582 unsigned int bucketIndex2
= shortStats
->NewTx(txHeight
, (double)feeRate
.GetFeePerK());
583 assert(bucketIndex
== bucketIndex2
);
584 unsigned int bucketIndex3
= longStats
->NewTx(txHeight
, (double)feeRate
.GetFeePerK());
585 assert(bucketIndex
== bucketIndex3
);
588 bool CBlockPolicyEstimator::processBlockTx(unsigned int nBlockHeight
, const CTxMemPoolEntry
* entry
)
590 if (!removeTx(entry
->GetTx().GetHash(), true)) {
591 // This transaction wasn't being tracked for fee estimation
595 // How many blocks did it take for miners to include this transaction?
596 // blocksToConfirm is 1-based, so a transaction included in the earliest
597 // possible block has confirmation count of 1
598 int blocksToConfirm
= nBlockHeight
- entry
->GetHeight();
599 if (blocksToConfirm
<= 0) {
600 // This can't happen because we don't process transactions from a block with a height
601 // lower than our greatest seen height
602 LogPrint(BCLog::ESTIMATEFEE
, "Blockpolicy error Transaction had negative blocksToConfirm\n");
606 // Feerates are stored and reported as BTC-per-kb:
607 CFeeRate
feeRate(entry
->GetFee(), entry
->GetTxSize());
609 feeStats
->Record(blocksToConfirm
, (double)feeRate
.GetFeePerK());
610 shortStats
->Record(blocksToConfirm
, (double)feeRate
.GetFeePerK());
611 longStats
->Record(blocksToConfirm
, (double)feeRate
.GetFeePerK());
615 void CBlockPolicyEstimator::processBlock(unsigned int nBlockHeight
,
616 std::vector
<const CTxMemPoolEntry
*>& entries
)
618 LOCK(cs_feeEstimator
);
619 if (nBlockHeight
<= nBestSeenHeight
) {
620 // Ignore side chains and re-orgs; assuming they are random
621 // they don't affect the estimate.
622 // And if an attacker can re-org the chain at will, then
623 // you've got much bigger problems than "attacker can influence
624 // transaction fees."
628 // Must update nBestSeenHeight in sync with ClearCurrent so that
629 // calls to removeTx (via processBlockTx) correctly calculate age
630 // of unconfirmed txs to remove from tracking.
631 nBestSeenHeight
= nBlockHeight
;
633 // Update unconfirmed circular buffer
634 feeStats
->ClearCurrent(nBlockHeight
);
635 shortStats
->ClearCurrent(nBlockHeight
);
636 longStats
->ClearCurrent(nBlockHeight
);
638 // Decay all exponential averages
639 feeStats
->UpdateMovingAverages();
640 shortStats
->UpdateMovingAverages();
641 longStats
->UpdateMovingAverages();
643 unsigned int countedTxs
= 0;
644 // Update averages with data points from current block
645 for (const auto& entry
: entries
) {
646 if (processBlockTx(nBlockHeight
, entry
))
650 if (firstRecordedHeight
== 0 && countedTxs
> 0) {
651 firstRecordedHeight
= nBestSeenHeight
;
652 LogPrint(BCLog::ESTIMATEFEE
, "Blockpolicy first recorded height %u\n", firstRecordedHeight
);
656 LogPrint(BCLog::ESTIMATEFEE
, "Blockpolicy estimates updated by %u of %u block txs, since last block %u of %u tracked, mempool map size %u, max target %u from %s\n",
657 countedTxs
, entries
.size(), trackedTxs
, trackedTxs
+ untrackedTxs
, mapMemPoolTxs
.size(),
658 MaxUsableEstimate(), HistoricalBlockSpan() > BlockSpan() ? "historical" : "current");
664 CFeeRate
CBlockPolicyEstimator::estimateFee(int confTarget
) const
666 // It's not possible to get reasonable estimates for confTarget of 1
670 return estimateRawFee(confTarget
, DOUBLE_SUCCESS_PCT
, FeeEstimateHorizon::MED_HALFLIFE
);
673 CFeeRate
CBlockPolicyEstimator::estimateRawFee(int confTarget
, double successThreshold
, FeeEstimateHorizon horizon
, EstimationResult
* result
) const
675 TxConfirmStats
* stats
;
676 double sufficientTxs
= SUFFICIENT_FEETXS
;
678 case FeeEstimateHorizon::SHORT_HALFLIFE
: {
679 stats
= shortStats
.get();
680 sufficientTxs
= SUFFICIENT_TXS_SHORT
;
683 case FeeEstimateHorizon::MED_HALFLIFE
: {
684 stats
= feeStats
.get();
687 case FeeEstimateHorizon::LONG_HALFLIFE
: {
688 stats
= longStats
.get();
692 throw std::out_of_range("CBlockPolicyEstimator::estimateRawFee unknown FeeEstimateHorizon");
696 LOCK(cs_feeEstimator
);
697 // Return failure if trying to analyze a target we're not tracking
698 if (confTarget
<= 0 || (unsigned int)confTarget
> stats
->GetMaxConfirms())
700 if (successThreshold
> 1)
703 double median
= stats
->EstimateMedianVal(confTarget
, sufficientTxs
, successThreshold
, true, nBestSeenHeight
, result
);
708 return CFeeRate(llround(median
));
711 unsigned int CBlockPolicyEstimator::HighestTargetTracked(FeeEstimateHorizon horizon
) const
714 case FeeEstimateHorizon::SHORT_HALFLIFE
: {
715 return shortStats
->GetMaxConfirms();
717 case FeeEstimateHorizon::MED_HALFLIFE
: {
718 return feeStats
->GetMaxConfirms();
720 case FeeEstimateHorizon::LONG_HALFLIFE
: {
721 return longStats
->GetMaxConfirms();
724 throw std::out_of_range("CBlockPolicyEstimator::HighestTargetTracked unknown FeeEstimateHorizon");
729 unsigned int CBlockPolicyEstimator::BlockSpan() const
731 if (firstRecordedHeight
== 0) return 0;
732 assert(nBestSeenHeight
>= firstRecordedHeight
);
734 return nBestSeenHeight
- firstRecordedHeight
;
737 unsigned int CBlockPolicyEstimator::HistoricalBlockSpan() const
739 if (historicalFirst
== 0) return 0;
740 assert(historicalBest
>= historicalFirst
);
742 if (nBestSeenHeight
- historicalBest
> OLDEST_ESTIMATE_HISTORY
) return 0;
744 return historicalBest
- historicalFirst
;
747 unsigned int CBlockPolicyEstimator::MaxUsableEstimate() const
749 // Block spans are divided by 2 to make sure there are enough potential failing data points for the estimate
750 return std::min(longStats
->GetMaxConfirms(), std::max(BlockSpan(), HistoricalBlockSpan()) / 2);
753 /** Return a fee estimate at the required successThreshold from the shortest
754 * time horizon which tracks confirmations up to the desired target. If
755 * checkShorterHorizon is requested, also allow short time horizon estimates
756 * for a lower target to reduce the given answer */
757 double CBlockPolicyEstimator::estimateCombinedFee(unsigned int confTarget
, double successThreshold
, bool checkShorterHorizon
, EstimationResult
*result
) const
759 double estimate
= -1;
760 if (confTarget
>= 1 && confTarget
<= longStats
->GetMaxConfirms()) {
761 // Find estimate from shortest time horizon possible
762 if (confTarget
<= shortStats
->GetMaxConfirms()) { // short horizon
763 estimate
= shortStats
->EstimateMedianVal(confTarget
, SUFFICIENT_TXS_SHORT
, successThreshold
, true, nBestSeenHeight
, result
);
765 else if (confTarget
<= feeStats
->GetMaxConfirms()) { // medium horizon
766 estimate
= feeStats
->EstimateMedianVal(confTarget
, SUFFICIENT_FEETXS
, successThreshold
, true, nBestSeenHeight
, result
);
768 else { // long horizon
769 estimate
= longStats
->EstimateMedianVal(confTarget
, SUFFICIENT_FEETXS
, successThreshold
, true, nBestSeenHeight
, result
);
771 if (checkShorterHorizon
) {
772 EstimationResult tempResult
;
773 // If a lower confTarget from a more recent horizon returns a lower answer use it.
774 if (confTarget
> feeStats
->GetMaxConfirms()) {
775 double medMax
= feeStats
->EstimateMedianVal(feeStats
->GetMaxConfirms(), SUFFICIENT_FEETXS
, successThreshold
, true, nBestSeenHeight
, &tempResult
);
776 if (medMax
> 0 && (estimate
== -1 || medMax
< estimate
)) {
778 if (result
) *result
= tempResult
;
781 if (confTarget
> shortStats
->GetMaxConfirms()) {
782 double shortMax
= shortStats
->EstimateMedianVal(shortStats
->GetMaxConfirms(), SUFFICIENT_TXS_SHORT
, successThreshold
, true, nBestSeenHeight
, &tempResult
);
783 if (shortMax
> 0 && (estimate
== -1 || shortMax
< estimate
)) {
785 if (result
) *result
= tempResult
;
793 /** Ensure that for a conservative estimate, the DOUBLE_SUCCESS_PCT is also met
794 * at 2 * target for any longer time horizons.
796 double CBlockPolicyEstimator::estimateConservativeFee(unsigned int doubleTarget
, EstimationResult
*result
) const
798 double estimate
= -1;
799 EstimationResult tempResult
;
800 if (doubleTarget
<= shortStats
->GetMaxConfirms()) {
801 estimate
= feeStats
->EstimateMedianVal(doubleTarget
, SUFFICIENT_FEETXS
, DOUBLE_SUCCESS_PCT
, true, nBestSeenHeight
, result
);
803 if (doubleTarget
<= feeStats
->GetMaxConfirms()) {
804 double longEstimate
= longStats
->EstimateMedianVal(doubleTarget
, SUFFICIENT_FEETXS
, DOUBLE_SUCCESS_PCT
, true, nBestSeenHeight
, &tempResult
);
805 if (longEstimate
> estimate
) {
806 estimate
= longEstimate
;
807 if (result
) *result
= tempResult
;
813 /** estimateSmartFee returns the max of the feerates calculated with a 60%
814 * threshold required at target / 2, an 85% threshold required at target and a
815 * 95% threshold required at 2 * target. Each calculation is performed at the
816 * shortest time horizon which tracks the required target. Conservative
817 * estimates, however, required the 95% threshold at 2 * target be met for any
818 * longer time horizons also.
820 CFeeRate
CBlockPolicyEstimator::estimateSmartFee(int confTarget
, FeeCalculation
*feeCalc
, bool conservative
) const
822 LOCK(cs_feeEstimator
);
825 feeCalc
->desiredTarget
= confTarget
;
826 feeCalc
->returnedTarget
= confTarget
;
830 EstimationResult tempResult
;
832 // Return failure if trying to analyze a target we're not tracking
833 if (confTarget
<= 0 || (unsigned int)confTarget
> longStats
->GetMaxConfirms()) {
834 return CFeeRate(0); // error condition
837 // It's not possible to get reasonable estimates for confTarget of 1
838 if (confTarget
== 1) confTarget
= 2;
840 unsigned int maxUsableEstimate
= MaxUsableEstimate();
841 if ((unsigned int)confTarget
> maxUsableEstimate
) {
842 confTarget
= maxUsableEstimate
;
844 if (feeCalc
) feeCalc
->returnedTarget
= confTarget
;
846 if (confTarget
<= 1) return CFeeRate(0); // error condition
848 assert(confTarget
> 0); //estimateCombinedFee and estimateConservativeFee take unsigned ints
849 /** true is passed to estimateCombined fee for target/2 and target so
850 * that we check the max confirms for shorter time horizons as well.
851 * This is necessary to preserve monotonically increasing estimates.
852 * For non-conservative estimates we do the same thing for 2*target, but
853 * for conservative estimates we want to skip these shorter horizons
854 * checks for 2*target because we are taking the max over all time
855 * horizons so we already have monotonically increasing estimates and
856 * the purpose of conservative estimates is not to let short term
857 * fluctuations lower our estimates by too much.
859 double halfEst
= estimateCombinedFee(confTarget
/2, HALF_SUCCESS_PCT
, true, &tempResult
);
861 feeCalc
->est
= tempResult
;
862 feeCalc
->reason
= FeeReason::HALF_ESTIMATE
;
865 double actualEst
= estimateCombinedFee(confTarget
, SUCCESS_PCT
, true, &tempResult
);
866 if (actualEst
> median
) {
869 feeCalc
->est
= tempResult
;
870 feeCalc
->reason
= FeeReason::FULL_ESTIMATE
;
873 double doubleEst
= estimateCombinedFee(2 * confTarget
, DOUBLE_SUCCESS_PCT
, !conservative
, &tempResult
);
874 if (doubleEst
> median
) {
877 feeCalc
->est
= tempResult
;
878 feeCalc
->reason
= FeeReason::DOUBLE_ESTIMATE
;
882 if (conservative
|| median
== -1) {
883 double consEst
= estimateConservativeFee(2 * confTarget
, &tempResult
);
884 if (consEst
> median
) {
887 feeCalc
->est
= tempResult
;
888 feeCalc
->reason
= FeeReason::CONSERVATIVE
;
893 if (median
< 0) return CFeeRate(0); // error condition
895 return CFeeRate(llround(median
));
899 bool CBlockPolicyEstimator::Write(CAutoFile
& fileout
) const
902 LOCK(cs_feeEstimator
);
903 fileout
<< 149900; // version required to read: 0.14.99 or later
904 fileout
<< CLIENT_VERSION
; // version that wrote the file
905 fileout
<< nBestSeenHeight
;
906 if (BlockSpan() > HistoricalBlockSpan()/2) {
907 fileout
<< firstRecordedHeight
<< nBestSeenHeight
;
910 fileout
<< historicalFirst
<< historicalBest
;
913 feeStats
->Write(fileout
);
914 shortStats
->Write(fileout
);
915 longStats
->Write(fileout
);
917 catch (const std::exception
&) {
918 LogPrintf("CBlockPolicyEstimator::Write(): unable to write policy estimator data (non-fatal)\n");
924 bool CBlockPolicyEstimator::Read(CAutoFile
& filein
)
927 LOCK(cs_feeEstimator
);
928 int nVersionRequired
, nVersionThatWrote
;
929 filein
>> nVersionRequired
>> nVersionThatWrote
;
930 if (nVersionRequired
> CLIENT_VERSION
)
931 return error("CBlockPolicyEstimator::Read(): up-version (%d) fee estimate file", nVersionRequired
);
933 // Read fee estimates file into temporary variables so existing data
934 // structures aren't corrupted if there is an exception.
935 unsigned int nFileBestSeenHeight
;
936 filein
>> nFileBestSeenHeight
;
938 if (nVersionRequired
< 149900) {
939 LogPrintf("%s: incompatible old fee estimation data (non-fatal). Version: %d\n", __func__
, nVersionRequired
);
940 } else { // New format introduced in 149900
941 unsigned int nFileHistoricalFirst
, nFileHistoricalBest
;
942 filein
>> nFileHistoricalFirst
>> nFileHistoricalBest
;
943 if (nFileHistoricalFirst
> nFileHistoricalBest
|| nFileHistoricalBest
> nFileBestSeenHeight
) {
944 throw std::runtime_error("Corrupt estimates file. Historical block range for estimates is invalid");
946 std::vector
<double> fileBuckets
;
947 filein
>> fileBuckets
;
948 size_t numBuckets
= fileBuckets
.size();
949 if (numBuckets
<= 1 || numBuckets
> 1000)
950 throw std::runtime_error("Corrupt estimates file. Must have between 2 and 1000 feerate buckets");
952 std::unique_ptr
<TxConfirmStats
> fileFeeStats(new TxConfirmStats(buckets
, bucketMap
, MED_BLOCK_PERIODS
, MED_DECAY
, MED_SCALE
));
953 std::unique_ptr
<TxConfirmStats
> fileShortStats(new TxConfirmStats(buckets
, bucketMap
, SHORT_BLOCK_PERIODS
, SHORT_DECAY
, SHORT_SCALE
));
954 std::unique_ptr
<TxConfirmStats
> fileLongStats(new TxConfirmStats(buckets
, bucketMap
, LONG_BLOCK_PERIODS
, LONG_DECAY
, LONG_SCALE
));
955 fileFeeStats
->Read(filein
, nVersionThatWrote
, numBuckets
);
956 fileShortStats
->Read(filein
, nVersionThatWrote
, numBuckets
);
957 fileLongStats
->Read(filein
, nVersionThatWrote
, numBuckets
);
959 // Fee estimates file parsed correctly
960 // Copy buckets from file and refresh our bucketmap
961 buckets
= fileBuckets
;
963 for (unsigned int i
= 0; i
< buckets
.size(); i
++) {
964 bucketMap
[buckets
[i
]] = i
;
967 // Destroy old TxConfirmStats and point to new ones that already reference buckets and bucketMap
968 feeStats
= std::move(fileFeeStats
);
969 shortStats
= std::move(fileShortStats
);
970 longStats
= std::move(fileLongStats
);
972 nBestSeenHeight
= nFileBestSeenHeight
;
973 historicalFirst
= nFileHistoricalFirst
;
974 historicalBest
= nFileHistoricalBest
;
977 catch (const std::exception
& e
) {
978 LogPrintf("CBlockPolicyEstimator::Read(): unable to read policy estimator data (non-fatal): %s\n",e
.what());
984 void CBlockPolicyEstimator::FlushUnconfirmed(CTxMemPool
& pool
) {
985 int64_t startclear
= GetTimeMicros();
986 std::vector
<uint256
> txids
;
987 pool
.queryHashes(txids
);
988 LOCK(cs_feeEstimator
);
989 for (auto& txid
: txids
) {
990 removeTx(txid
, false);
992 int64_t endclear
= GetTimeMicros();
993 LogPrint(BCLog::ESTIMATEFEE
, "Recorded %u unconfirmed txs from mempool in %gs\n",txids
.size(), (endclear
- startclear
)*0.000001);
996 FeeFilterRounder::FeeFilterRounder(const CFeeRate
& minIncrementalFee
)
998 CAmount minFeeLimit
= std::max(CAmount(1), minIncrementalFee
.GetFeePerK() / 2);
1000 for (double bucketBoundary
= minFeeLimit
; bucketBoundary
<= MAX_FILTER_FEERATE
; bucketBoundary
*= FEE_FILTER_SPACING
) {
1001 feeset
.insert(bucketBoundary
);
1005 CAmount
FeeFilterRounder::round(CAmount currentMinFee
)
1007 std::set
<double>::iterator it
= feeset
.lower_bound(currentMinFee
);
1008 if ((it
!= feeset
.begin() && insecure_rand
.rand32() % 3 != 0) || it
== feeset
.end()) {
1011 return static_cast<CAmount
>(*it
);