From 39c2926919332064f8dc60e38121ff6fb2c0bf99 Mon Sep 17 00:00:00 2001 From: jolah1 Date: Wed, 14 Oct 2026 08:01:47 +0100 Subject: [PATCH 1/4] Fall back to per-target defaults for missing fee estimates Esplora may return a non-empty estimate map that still has no usable entry for some of our confirmation targets, as `convert_fee_rate` only yields a value if the map holds a block count at or below the requested one. We'd then substitute 1 sat/vb, which is well below the default we'd otherwise use for urgent targets: `UrgentOnChainSweep` would end up at 250 sats/kwu instead of 5000. Note this isn't a case of a missing fallback, but of an actively harmful one: `OnchainFeeEstimator::estimate_fee_rate` already falls back to `get_fallback_rate_for_target` whenever it misses the cache, so inserting 1 sat/vb only serves to shadow the value we'd have used anyway. Here we therefore fall back to the target's own default. We deliberately skip the post-estimation adjustments for it, as there is no estimate to adjust, and so that we land on the same rate the cache-miss path would have given us. A non-positive entry is treated as no entry at all, as it is no more usable than a missing one and must not pin the target to the floor either. The defaults are sized for a chain that has a fee market, though, and `regtest`/`signet` don't have one: regtest Esplora serves an empty map, as `estimatesmartfee` has nothing to go on there, so the fallback would decide every rate rather than the odd sparse-map target. We therefore stand in the 1 sat/vb we have always used on those two networks, which is the same split `BitcoindChainSource` already makes, and adjust that stand-in exactly as we would an estimate, because that is what those networks have always cached: `MaximumFeeEstimate` stays at 2775 sats/kwu rather than dropping to the raw 250, which matters as LDK sizes a channel's dust exposure limit off it. `get_fallback_fee_rate_for_network` holds that decision so the remaining chain sources can share it. Finally, we log the targets we had to fall back to a default for. On `regtest`/`signet` that is every target on every update, so we keep quiet there, but anywhere else it means we're pricing transactions off defaults rather than off the chain, which shouldn't pass silently. To allow testing this without an Esplora server, we move the cache construction to `build_fee_rate_cache` and add coverage for sparse maps, for empty maps on and off Mainnet, for non-positive entries, for the network-dependent fallback, and for the unchanged complete-map behavior. This change was written with the assistance of Claude Code. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_016RDZbFbxkpNupzvTFDsL43 --- src/chain/esplora.rs | 279 +++++++++++++++++++++++++++++++++++++------ src/fee_estimator.rs | 79 +++++++++++- 2 files changed, 322 insertions(+), 36 deletions(-) diff --git a/src/chain/esplora.rs b/src/chain/esplora.rs index e87d075d1f..72dc236f97 100644 --- a/src/chain/esplora.rs +++ b/src/chain/esplora.rs @@ -24,8 +24,9 @@ use crate::config::{ MAX_FULL_SCAN_STOP_GAP, MIN_FULL_SCAN_STOP_GAP, }; use crate::fee_estimator::{ - apply_post_estimation_adjustments, get_all_conf_targets, get_num_block_defaults_for_target, - OnchainFeeEstimator, + apply_post_estimation_adjustments, get_all_conf_targets, get_fallback_fee_rate_for_network, + get_num_block_defaults_for_target, ConfirmationTarget, OnchainFeeEstimator, + ONE_SAT_PER_VB_SATS_PER_KWU, }; use crate::io::utils::update_and_persist_node_metrics; use crate::logger::{log_bytes, log_debug, log_error, log_trace, log_warn, LdkLogger, Logger}; @@ -377,44 +378,41 @@ impl EsploraChainSource { Error::FeerateEstimationUpdateFailed })?; - if estimates.is_empty() && self.config.network == Network::Bitcoin { - // Ensure we fail if we didn't receive any estimates. - log_error!( - self.logger, - "Failed to retrieve fee rate estimates: empty fee estimates are dissallowed on Mainnet.", - ); - return Err(Error::FeerateEstimationUpdateFailed); - } - - let confirmation_targets = get_all_conf_targets(); - - let mut new_fee_rate_cache = HashMap::with_capacity(10); - for target in confirmation_targets { - let num_blocks = get_num_block_defaults_for_target(target); - - // Convert the retrieved fee rate and fall back to 1 sat/vb if we fail or it - // yields less than that. This is mostly necessary to continue on - // `signet`/`regtest` where we might not get estimates (or bogus values). - let converted_estimate_sat_vb = - esplora_client::convert_fee_rate(num_blocks, estimates.clone()) - .map_or(1.0, |converted| converted.max(1.0)); - - let fee_rate = FeeRate::from_sat_per_kwu((converted_estimate_sat_vb * 250.0) as u64); - - // LDK 0.0.118 introduced changes to the `ConfirmationTarget` semantics that - // require some post-estimation adjustments to the fee rates, which we do here. - let adjusted_fee_rate = apply_post_estimation_adjustments(target, fee_rate); - - new_fee_rate_cache.insert(target, adjusted_fee_rate); + let (new_fee_rate_cache, fell_back_targets) = + build_fee_rate_cache(estimates, self.config.network).map_err(|e| { + log_error!( + self.logger, + "Failed to retrieve fee rate estimates: empty fee estimates are dissallowed on Mainnet.", + ); + e + })?; - log_trace!( + // On `regtest`/`signet` we expect to fall back for every target, as the backends serve no + // estimates there, so a warning would be pure noise. Elsewhere it means we're pricing + // transactions off defaults rather than off the chain, which is worth knowing about. + if !fell_back_targets.is_empty() + && !matches!(self.config.network, Network::Regtest | Network::Signet) + { + log_warn!( self.logger, - "Fee rate estimation updated for {:?}: {} sats/kwu", - target, - adjusted_fee_rate.to_sat_per_kwu(), + "Received no usable fee rate estimate for {:?}, falling back to their defaults.", + fell_back_targets, ); } + // Note we iterate the targets rather than the cache, as a `HashMap`'s order varies from + // run to run and we'd rather these lines stay comparable across restarts. + for target in get_all_conf_targets() { + if let Some(fee_rate) = new_fee_rate_cache.get(&target) { + log_trace!( + self.logger, + "Fee rate estimation updated for {:?}: {} sats/kwu", + target, + fee_rate.to_sat_per_kwu(), + ); + } + } + self.fee_estimator.set_fee_rate_cache(new_fee_rate_cache); log_debug!( @@ -549,3 +547,214 @@ impl Filter for EsploraChainSource { self.tx_sync.register_output(output); } } + +// Builds the fee rate cache from the estimates Esplora returned for us. +// +// Note that Esplora may hand us a sparse map that has no usable estimate for some of our +// confirmation targets. Rather than putting those on 1 sat/vb, which would silently downgrade +// urgent targets such as `UrgentOnChainSweep`, we fall back to what +// `get_fallback_fee_rate_for_network` gives us, just as the Electrum and Bitcoin Core sources do. +fn build_fee_rate_cache( + estimates: HashMap, network: Network, +) -> Result<(HashMap, Vec), Error> { + if estimates.is_empty() && network == Network::Bitcoin { + // Ensure we fail if we didn't receive any estimates. + return Err(Error::FeerateEstimationUpdateFailed); + } + + let confirmation_targets = get_all_conf_targets(); + + let mut new_fee_rate_cache = HashMap::with_capacity(10); + let mut fell_back_targets = Vec::new(); + for target in confirmation_targets { + let num_blocks = get_num_block_defaults_for_target(target); + + // Note a non-positive value is no more usable than a missing one, so we treat it as + // missing rather than letting it pin the target to 1 sat/vb. + let converted = esplora_client::convert_fee_rate(num_blocks, estimates.clone()) + .filter(|converted| *converted > 0.0); + + let fee_rate = match converted { + Some(converted) => { + // Enforce a lower bound of 1 sat/vb on the converted estimate. This is mostly + // necessary to continue on `signet`/`regtest` where we might get bogus values. + let estimate_sats_kwu = + ((converted * 250.0) as u64).max(ONE_SAT_PER_VB_SATS_PER_KWU); + let estimate = FeeRate::from_sat_per_kwu(estimate_sats_kwu); + + // LDK 0.0.118 introduced changes to the `ConfirmationTarget` semantics that + // require some post-estimation adjustments to the fee rates, which we do here. + apply_post_estimation_adjustments(target, estimate) + }, + // We have no estimate to adjust, so we fall back. + None => { + fell_back_targets.push(target); + get_fallback_fee_rate_for_network(target, network) + }, + }; + + new_fee_rate_cache.insert(target, fee_rate); + } + + Ok((new_fee_rate_cache, fell_back_targets)) +} + +#[cfg(test)] +mod tests { + use lightning::chain::chaininterface::ConfirmationTarget as LdkConfirmationTarget; + + use super::*; + use crate::fee_estimator::get_fallback_rate_for_target; + + // Esplora only gives us an estimate for a target if it knows a block count at or below the + // requested one, so a map holding nothing but high block counts starves our urgent targets. + fn sparse_estimates() -> HashMap { + HashMap::from([(144, 2.0), (1008, 1.0)]) + } + + #[test] + fn sparse_estimates_fall_back_to_target_defaults() { + let (cache, _) = build_fee_rate_cache(sparse_estimates(), Network::Bitcoin).unwrap(); + + // These have no estimate at or below their block count, so they have to end up on their + // own defaults rather than on the 1 sat/vb (i.e., 250 sats/kwu) relay floor. + for (target, expected) in [ + (ConfirmationTarget::Lightning(LdkConfirmationTarget::UrgentOnChainSweep), 5000), + (ConfirmationTarget::Lightning(LdkConfirmationTarget::MaximumFeeEstimate), 8000), + (ConfirmationTarget::OnchainPayment, 5000), + (ConfirmationTarget::ChannelFunding, 1000), + ] { + assert_eq!(cache.get(&target).unwrap().to_sat_per_kwu(), expected, "{:?}", target); + } + + // While the targets that do have an estimate keep using it. + assert_eq!( + cache + .get(&ConfirmationTarget::Lightning(LdkConfirmationTarget::ChannelCloseMinimum)) + .unwrap() + .to_sat_per_kwu(), + 500 + ); + } + + #[test] + fn empty_estimates_are_rejected_on_mainnet_only() { + assert!(matches!( + build_fee_rate_cache(HashMap::new(), Network::Bitcoin), + Err(Error::FeerateEstimationUpdateFailed) + )); + + // On testnet we carry on, with every target on its own default, and report all of them + // as fallen back so the caller can say so in the logs. + let (cache, fell_back) = build_fee_rate_cache(HashMap::new(), Network::Testnet).unwrap(); + assert_eq!(cache.len(), get_all_conf_targets().len()); + assert_eq!(fell_back.len(), get_all_conf_targets().len()); + for target in get_all_conf_targets() { + assert_eq!( + cache.get(&target).unwrap().to_sat_per_kwu(), + get_fallback_rate_for_target(target) as u64, + "{:?}", + target + ); + } + } + + #[test] + fn non_positive_estimates_fall_back_rather_than_pinning_the_floor() { + // A bogus entry is no more usable than a missing one, so it must not pin the target to + // 1 sat/vb. + for bogus in [0.0, -1.0] { + let estimates = HashMap::from([(6, bogus), (144, 2.0)]); + let (cache, fell_back) = build_fee_rate_cache(estimates, Network::Bitcoin).unwrap(); + + let urgent = ConfirmationTarget::Lightning(LdkConfirmationTarget::UrgentOnChainSweep); + assert_eq!( + cache.get(&urgent).unwrap().to_sat_per_kwu(), + get_fallback_rate_for_target(urgent) as u64, + "{}", + bogus + ); + assert!(fell_back.contains(&urgent), "{}", bogus); + } + } + + #[test] + fn no_estimates_stay_on_one_sat_per_vb_on_regtest_and_signet() { + // `regtest`/`signet` have no fee market at all. Regtest Esplora serves an empty map, as + // `estimatesmartfee` has nothing to go on, so the defaults would decide every rate + // there. We keep the 1 sat/vb we've always used instead, adjusted as an estimate would + // be, which is exactly what those networks cached before this change. + for network in [Network::Regtest, Network::Signet] { + for estimates in [HashMap::new(), sparse_estimates()] { + let (cache, _) = build_fee_rate_cache(estimates, network).unwrap(); + + assert_eq!( + cache + .get(&ConfirmationTarget::Lightning( + LdkConfirmationTarget::UrgentOnChainSweep + )) + .unwrap() + .to_sat_per_kwu(), + ONE_SAT_PER_VB_SATS_PER_KWU, + "{}", + network + ); + assert_eq!( + cache.get(&ConfirmationTarget::ChannelFunding).unwrap().to_sat_per_kwu(), + ONE_SAT_PER_VB_SATS_PER_KWU, + "{}", + network + ); + + // The one target the adjustment moves: LDK sizes its per-channel dust exposure + // limit off this, so caching the raw 250 here would cut that limit ~11x. + assert_eq!( + cache + .get(&ConfirmationTarget::Lightning( + LdkConfirmationTarget::MaximumFeeEstimate + )) + .unwrap() + .to_sat_per_kwu(), + 2775, + "{}", + network + ); + } + } + } + + #[test] + fn complete_estimates_are_used_and_adjusted() { + let estimates = HashMap::from([(1, 10.0), (6, 5.0), (12, 4.0), (144, 2.0), (1008, 1.0)]); + let (cache, _) = build_fee_rate_cache(estimates, Network::Bitcoin).unwrap(); + + // 5 sat/vb, no post-estimation adjustment. + assert_eq!( + cache + .get(&ConfirmationTarget::Lightning(LdkConfirmationTarget::UrgentOnChainSweep)) + .unwrap() + .to_sat_per_kwu(), + 1250 + ); + + // 10 sat/vb, bumped by `x * 1.1 + 2500`. + assert_eq!( + cache + .get(&ConfirmationTarget::Lightning(LdkConfirmationTarget::MaximumFeeEstimate)) + .unwrap() + .to_sat_per_kwu(), + 5250 + ); + + // 2 sat/vb, less 250 sats/kwu, but clamped back up to the relay floor. + assert_eq!( + cache + .get(&ConfirmationTarget::Lightning( + LdkConfirmationTarget::MinAllowedNonAnchorChannelRemoteFee + )) + .unwrap() + .to_sat_per_kwu(), + 253 + ); + } +} diff --git a/src/fee_estimator.rs b/src/fee_estimator.rs index 78a3d37ab3..4b10f5e239 100644 --- a/src/fee_estimator.rs +++ b/src/fee_estimator.rs @@ -8,7 +8,7 @@ use std::collections::HashMap; use std::sync::RwLock; -use bitcoin::FeeRate; +use bitcoin::{FeeRate, Network}; use lightning::chain::chaininterface::{ ConfirmationTarget as LdkConfirmationTarget, FeeEstimator as LdkFeeEstimator, FEERATE_FLOOR_SATS_PER_KW, @@ -134,6 +134,36 @@ pub(crate) fn get_fallback_rate_for_ldk_target(target: LdkConfirmationTarget) -> } } +/// 1 sat/vb in sats/kwu, i.e. the lowest rate we'd ever consider using. Note this sits just +/// below LDK's `FEERATE_FLOOR_SATS_PER_KW`, which `estimate_fee_rate` clamps reads to. +pub(crate) const ONE_SAT_PER_VB_SATS_PER_KWU: u64 = 250; + +/// Returns the fee rate to use for `target` when the chain source handed us no usable estimate +/// for it. +/// +/// Off `regtest`/`signet` we use the target's own default, as falling back to 1 sat/vb would +/// silently downgrade urgent targets such as `UrgentOnChainSweep`. We deliberately +/// don't run that default through `apply_post_estimation_adjustments`, mirroring what +/// `OnchainFeeEstimator::estimate_fee_rate` returns on a cache miss. +/// +/// On `regtest`/`signet` there is no fee market to speak of, and the backends commonly serve no +/// estimates there at all, so pulling every target up to a mainnet-sized default would be wrong. +/// We stand in the 1 sat/vb we have always used there, and adjust it exactly as we would an +/// estimate, because that is what these networks have always cached: `MaximumFeeEstimate` ends up +/// at 2775 sats/kwu rather than the raw 250, and LDK derives its per-channel dust exposure limit +/// from that value. +pub(crate) fn get_fallback_fee_rate_for_network( + target: ConfirmationTarget, network: Network, +) -> FeeRate { + match network { + Network::Regtest | Network::Signet => apply_post_estimation_adjustments( + target, + FeeRate::from_sat_per_kwu(ONE_SAT_PER_VB_SATS_PER_KWU), + ), + _ => FeeRate::from_sat_per_kwu(get_fallback_rate_for_target(target) as u64), + } +} + pub(crate) fn get_all_conf_targets() -> [ConfirmationTarget; 10] { [ ConfirmationTarget::OnchainPayment, @@ -204,6 +234,53 @@ pub(crate) fn rbf_splice_feerates( mod tests { use super::*; + #[test] + fn fallback_fee_rates_are_network_aware() { + // Mainnet and testnet have a fee market, so a target with no usable estimate gets its own + // default rather than the relay floor. + for network in [Network::Bitcoin, Network::Testnet, Network::Testnet4] { + for target in get_all_conf_targets() { + assert_eq!( + get_fallback_fee_rate_for_network(target, network).to_sat_per_kwu(), + get_fallback_rate_for_target(target) as u64, + "{:?} on {}", + target, + network + ); + } + } + + // Regtest and signet don't, so we stand in 1 sat/vb there and avoid pulling every target + // up to a mainnet-sized default. The stand-in is adjusted as an estimate would be, which + // is what those networks have always cached. + for network in [Network::Regtest, Network::Signet] { + for target in get_all_conf_targets() { + let one_sat_per_vb = FeeRate::from_sat_per_kwu(ONE_SAT_PER_VB_SATS_PER_KWU); + assert_eq!( + get_fallback_fee_rate_for_network(target, network), + apply_post_estimation_adjustments(target, one_sat_per_vb), + "{:?} on {}", + target, + network + ); + } + + // Spelled out for the one target where the adjustment matters, as LDK derives its + // per-channel dust exposure limit from it: dropping this to the raw 250 would cut + // that limit ~11x on every regtest/signet node. + assert_eq!( + get_fallback_fee_rate_for_network( + ConfirmationTarget::Lightning(LdkConfirmationTarget::MaximumFeeEstimate), + network + ) + .to_sat_per_kwu(), + 2775, + "{}", + network + ); + } + } + #[test] fn rbf_splice_feerates_target_and_max() { let kwu = FeeRate::from_sat_per_kwu; From ed6886236792c3a9f8f07b9080250d5acc9dd5d8 Mon Sep 17 00:00:00 2001 From: jolah1 Date: Wed, 14 Oct 2026 08:01:55 +0100 Subject: [PATCH 2/4] Use the same fee estimate fallback for Electrum and Bitcoin Core A missing estimate should mean the same thing no matter which backend we happen to be on, so have the remaining two chain sources fall back through `get_fallback_fee_rate_for_network` as well. For Electrum that covers the results we can't use: a server that has no estimate for the requested block count answers `-1`, and a result may not be a number at all. Both used to be floored to 1 sat/vb, so the silent downgrade of urgent targets this series removes from the Esplora source was reachable here too, mainnet included. We report the targets we had to fall back for, as the Esplora source now does, and index into the batch results rather than zipping them with the targets, so that a short response could never silently drop the trailing targets from the cache. Note `batch_call` returns one result per request or an error, so that isn't a case we can hit today. For Bitcoin Core it means we no longer abandon the whole update when a single `estimatesmartfee` call fails off mainnet, which kept none of the estimates we did get, and that the fallback no longer runs through the post-estimation adjustments. The regtest/signet rates are unchanged, and mainnet still fails hard. This change was written with the assistance of Claude Code. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_016RDZbFbxkpNupzvTFDsL43 --- src/chain/bitcoind.rs | 42 +++++----- src/chain/electrum.rs | 183 ++++++++++++++++++++++++++++++++++++------ 2 files changed, 177 insertions(+), 48 deletions(-) diff --git a/src/chain/bitcoind.rs b/src/chain/bitcoind.rs index fe0047e6a7..2c7189e841 100644 --- a/src/chain/bitcoind.rs +++ b/src/chain/bitcoind.rs @@ -39,8 +39,8 @@ use crate::config::{ DEFAULT_TX_BROADCAST_TIMEOUT_SECS, }; use crate::fee_estimator::{ - apply_post_estimation_adjustments, get_all_conf_targets, get_num_block_defaults_for_target, - ConfirmationTarget, OnchainFeeEstimator, + apply_post_estimation_adjustments, get_all_conf_targets, get_fallback_fee_rate_for_network, + get_num_block_defaults_for_target, ConfirmationTarget, OnchainFeeEstimator, }; use crate::io::utils::update_and_persist_node_metrics; use crate::logger::{log_bytes, log_debug, log_error, log_info, log_trace, LdkLogger, Logger}; @@ -637,45 +637,39 @@ impl BitcoindChainSource { }; let fee_rate = match (fee_rate_update_res, self.config.network) { - (Ok(rate), _) => rate, + (Ok(rate), _) => { + // LDK 0.0.118 introduced changes to the `ConfirmationTarget` semantics that + // require some post-estimation adjustments to the fee rates, which we do here. + apply_post_estimation_adjustments(target, rate) + }, (Err(e), Network::Bitcoin) => { // Strictly fail on mainnet. log_error!(self.logger, "Failed to retrieve fee rate estimates: {}", e); return Err(Error::FeerateEstimationUpdateFailed); }, - (Err(e), n) if n == Network::Regtest || n == Network::Signet => { - // On regtest/signet we just fall back to the usual 1 sat/vb == 250 - // sat/kwu default. - log_error!( - self.logger, - "Failed to retrieve fee rate estimates: {}. Falling back to default of 1 sat/vb.", - e, - ); - FeeRate::from_sat_per_kwu(250) - }, - (Err(e), _) => { - // On testnet `estimatesmartfee` can be unreliable so we just skip in - // case of a failure, which will have us falling back to defaults. + (Err(e), network) => { + // Off mainnet we carry on with this target's fallback: on regtest/signet + // there is no fee market to begin with, and on testnet `estimatesmartfee` + // can simply be unreliable. Note this keeps whatever estimates we did get + // for the remaining targets. + let fallback_fee_rate = get_fallback_fee_rate_for_network(target, network); log_error!( self.logger, - "Failed to retrieve fee rate estimates: {}. Falling back to defaults.", + "Failed to retrieve fee rate estimates: {}. Falling back to {} sats/kwu.", e, + fallback_fee_rate.to_sat_per_kwu(), ); - return Ok(()); + fallback_fee_rate }, }; - // LDK 0.0.118 introduced changes to the `ConfirmationTarget` semantics that - // require some post-estimation adjustments to the fee rates, which we do here. - let adjusted_fee_rate = apply_post_estimation_adjustments(target, fee_rate); - - new_fee_rate_cache.insert(target, adjusted_fee_rate); + new_fee_rate_cache.insert(target, fee_rate); log_trace!( self.logger, "Fee rate estimation updated for {:?}: {} sats/kwu", target, - adjusted_fee_rate.to_sat_per_kwu(), + fee_rate.to_sat_per_kwu(), ); } diff --git a/src/chain/electrum.rs b/src/chain/electrum.rs index 7be8656b58..c6b0946371 100644 --- a/src/chain/electrum.rs +++ b/src/chain/electrum.rs @@ -32,8 +32,9 @@ use crate::config::{ }; use crate::error::Error; use crate::fee_estimator::{ - apply_post_estimation_adjustments, get_all_conf_targets, get_num_block_defaults_for_target, - ConfirmationTarget, OnchainFeeEstimator, + apply_post_estimation_adjustments, get_all_conf_targets, get_fallback_fee_rate_for_network, + get_num_block_defaults_for_target, ConfirmationTarget, OnchainFeeEstimator, + ONE_SAT_PER_VB_SATS_PER_KWU, }; use crate::io::utils::update_and_persist_node_metrics; use crate::logger::{log_bytes, log_debug, log_error, log_trace, log_warn, LdkLogger, Logger}; @@ -814,40 +815,77 @@ pub(crate) async fn get_electrum_fee_rate_cache_update( } let mut new_fee_rate_cache = HashMap::with_capacity(10); - for (target, raw_fee_rate_btc_per_kvb) in - confirmation_targets.into_iter().zip(raw_estimates_btc_kvb.into_iter()) - { - // Parse the retrieved serde_json::Value and fall back to 1 sat/vb (10^3 / 10^8 = 10^-5 - // = 0.00001 btc/kvb) if we fail or it yields less than that. This is mostly necessary - // to continue on `signet`/`regtest` where we might not get estimates (or bogus - // values). - let fee_rate_btc_per_kvb = - raw_fee_rate_btc_per_kvb.as_f64().map_or(0.00001, |converted| converted.max(0.00001)); - - // Electrum, just like Bitcoin Core, gives us a feerate in BTC/KvB. - // Thus, we multiply by 25_000_000 (10^8 / 4) to get satoshis/kwu. - let fee_rate = { - let fee_rate_sat_per_kwu = (fee_rate_btc_per_kvb * 25_000_000.0).round() as u64; - FeeRate::from_sat_per_kwu(fee_rate_sat_per_kwu) - }; - - // LDK 0.0.118 introduced changes to the `ConfirmationTarget` semantics that - // require some post-estimation adjustments to the fee rates, which we do here. - let adjusted_fee_rate = apply_post_estimation_adjustments(target, fee_rate); + let mut fell_back_targets = Vec::new(); + for (index, target) in confirmation_targets.into_iter().enumerate() { + // `batch_call` gives us one result per request or an error, and the check above + // rejects anything else on mainnet. We still index rather than zip so that a short + // response could never silently drop the trailing targets from the cache. + let raw_fee_rate_btc_per_kvb = + raw_estimates_btc_kvb.get(index).and_then(|raw| raw.as_f64()); + + let (fee_rate, fell_back) = + fee_rate_from_estimate(target, raw_fee_rate_btc_per_kvb, network); + + if fell_back { + fell_back_targets.push(target); + } - new_fee_rate_cache.insert(target, adjusted_fee_rate); + new_fee_rate_cache.insert(target, fee_rate); log_trace!( logger, "Fee rate estimation updated for {:?}: {} sats/kwu", target, - adjusted_fee_rate.to_sat_per_kwu(), + fee_rate.to_sat_per_kwu(), + ); + } + + // On `regtest`/`signet` we expect to fall back for every target, so a warning would be + // pure noise there. Elsewhere it means we're pricing transactions off defaults rather + // than off the chain, which shouldn't pass silently. + if !fell_back_targets.is_empty() && !matches!(network, Network::Regtest | Network::Signet) { + log_warn!( + logger, + "Received no usable fee rate estimate for {:?}, falling back to their defaults.", + fell_back_targets, ); } Ok(new_fee_rate_cache) } +// Converts a raw `estimatefee` result, as returned by the Electrum server for `target`, into the +// fee rate we'll cache for it, and whether we had to fall back for it. +// +// Note that Electrum serves `-1` when it has no estimate for the requested block count, and that a +// result may not be a number at all. In either case we have no usable estimate and fall back rather +// than putting the target on 1 sat/vb, which would silently downgrade urgent targets such as +// `UrgentOnChainSweep`. +fn fee_rate_from_estimate( + target: ConfirmationTarget, estimate_btc_per_kvb: Option, network: Network, +) -> (FeeRate, bool) { + // Electrum, just like Bitcoin Core, gives us a feerate in BTC/KvB. Thus, we multiply by + // 25_000_000 (10^8 / 4) to get satoshis/kwu. + let estimate_sats_kwu = estimate_btc_per_kvb + .filter(|converted| *converted > 0.0) + .map(|converted| (converted * 25_000_000.0).round() as u64); + + match estimate_sats_kwu { + Some(estimate_sats_kwu) => { + // Enforce a lower bound of 1 sat/vb on the converted estimate. This is mostly + // necessary to continue on `signet`/`regtest` where we might get bogus values. + let estimate = + FeeRate::from_sat_per_kwu(estimate_sats_kwu.max(ONE_SAT_PER_VB_SATS_PER_KWU)); + + // LDK 0.0.118 introduced changes to the `ConfirmationTarget` semantics that + // require some post-estimation adjustments to the fee rates, which we do here. + (apply_post_estimation_adjustments(target, estimate), false) + }, + // We have no estimate to adjust, so we fall back. + None => (get_fallback_fee_rate_for_network(target, network), true), + } +} + struct ConfirmGate { active: Mutex, } @@ -949,6 +987,7 @@ mod tests { use std::thread; use bitcoin::blockdata::constants::genesis_block; + use lightning::chain::chaininterface::ConfirmationTarget as LdkConfirmationTarget; use super::*; @@ -1036,6 +1075,102 @@ mod tests { server.join().unwrap(); } + #[test] + fn missing_estimates_fall_back_per_network() { + // `-1` is what Electrum serves when it has no estimate for the requested block count, + // and a short batch response leaves us without a value at all. Neither is a usable + // estimate. + for raw in [None, Some(-1.0)] { + // On mainnet/testnet the target's own default decides, rather than the relay floor + // silently downgrading urgent targets to 1 sat/vb. + for network in [Network::Bitcoin, Network::Testnet] { + let (fee_rate, fell_back) = fee_rate_from_estimate( + ConfirmationTarget::Lightning(LdkConfirmationTarget::UrgentOnChainSweep), + raw, + network, + ); + assert_eq!(fee_rate.to_sat_per_kwu(), 5000, "{:?} on {}", raw, network); + assert!(fell_back, "{:?} on {}", raw, network); + + let (fee_rate, fell_back) = + fee_rate_from_estimate(ConfirmationTarget::ChannelFunding, raw, network); + assert_eq!(fee_rate.to_sat_per_kwu(), 1000, "{:?} on {}", raw, network); + assert!(fell_back, "{:?} on {}", raw, network); + } + + // While on regtest/signet we stay on the 1 sat/vb stand-in, adjusted as an estimate + // would be. `MaximumFeeEstimate` therefore has to come out at 2775 here too, as LDK + // sizes a channel's dust exposure limit off it. + for network in [Network::Regtest, Network::Signet] { + assert_eq!( + fee_rate_from_estimate( + ConfirmationTarget::Lightning(LdkConfirmationTarget::MaximumFeeEstimate), + raw, + network + ) + .0 + .to_sat_per_kwu(), + 2775, + "{:?} on {}", + raw, + network + ); + assert_eq!( + fee_rate_from_estimate( + ConfirmationTarget::Lightning(LdkConfirmationTarget::UrgentOnChainSweep), + raw, + network + ) + .0 + .to_sat_per_kwu(), + ONE_SAT_PER_VB_SATS_PER_KWU, + "{:?} on {}", + raw, + network + ); + } + } + } + + #[test] + fn estimates_are_converted_floored_and_adjusted() { + // 0.00002 btc/kvb == 2 sat/vb == 500 sats/kwu, no post-estimation adjustment. + assert_eq!( + fee_rate_from_estimate( + ConfirmationTarget::Lightning(LdkConfirmationTarget::UrgentOnChainSweep), + Some(0.00002), + Network::Bitcoin + ) + .0 + .to_sat_per_kwu(), + 500 + ); + + // The same estimate bumped by `x * 1.1 + 2500` for `MaximumFeeEstimate`. + assert_eq!( + fee_rate_from_estimate( + ConfirmationTarget::Lightning(LdkConfirmationTarget::MaximumFeeEstimate), + Some(0.00002), + Network::Bitcoin + ) + .0 + .to_sat_per_kwu(), + 3050 + ); + + // A dust-but-positive estimate is floored at 1 sat/vb, not taken at face value. + assert_eq!( + fee_rate_from_estimate( + ConfirmationTarget::OnchainPayment, + Some(0.000001), + Network::Bitcoin + ) + .0 + .to_sat_per_kwu(), + ONE_SAT_PER_VB_SATS_PER_KWU + ); + } + struct RecordingConfirm { calls: AtomicUsize, relevant_txid: Txid, From cee0fd4e1325284f152c8a098331b4eb70bbaa25 Mon Sep 17 00:00:00 2001 From: jolah1 Date: Mon, 16 Nov 2026 11:51:19 +0100 Subject: [PATCH 3/4] Don't let unusable fee estimates shadow or stand in for usable ones A few follow-ups to the fee estimate fallback handling. For Esplora, we previously filtered non-positive values only after `convert_fee_rate` had picked an entry. As it settles on the closest block count at or below the requested one, a bogus entry there would shadow a usable one further down and send the target to its fallback even though we had an estimate for it. We now drop non-positive entries upfront, which also means a map holding nothing usable is rejected on mainnet just as an empty one is. For Electrum, a server answering `-1` for every block count, or handing us nothing we could parse, left us with no usable estimate at all, yet we'd happily cache the fallback for every target on mainnet. We now reject such an update there, matching what we do for an empty Esplora response. A single usable estimate is still enough to carry on, with the remaining targets falling back individually. To allow testing this without an Electrum server, we move the cache construction to `build_fee_rate_cache`. For Bitcoin Core, we expect `estimatesmartfee` to fail for every target on `regtest`/`signet`, so logging the per-target fallback at error level there is pure noise. We log it at trace level on those two networks instead. This change was written with the assistance of Claude Code. Co-Authored-By: Claude Fable 5.2 --- src/chain/bitcoind.rs | 23 ++++++--- src/chain/electrum.rs | 107 ++++++++++++++++++++++++++++++++---------- src/chain/esplora.rs | 41 +++++++++++++--- 3 files changed, 134 insertions(+), 37 deletions(-) diff --git a/src/chain/bitcoind.rs b/src/chain/bitcoind.rs index 2c7189e841..671dabeb68 100644 --- a/src/chain/bitcoind.rs +++ b/src/chain/bitcoind.rs @@ -653,12 +653,23 @@ impl BitcoindChainSource { // can simply be unreliable. Note this keeps whatever estimates we did get // for the remaining targets. let fallback_fee_rate = get_fallback_fee_rate_for_network(target, network); - log_error!( - self.logger, - "Failed to retrieve fee rate estimates: {}. Falling back to {} sats/kwu.", - e, - fallback_fee_rate.to_sat_per_kwu(), - ); + // On `regtest`/`signet` we expect to end up here for every target, so an + // error would be pure noise there. + if matches!(network, Network::Regtest | Network::Signet) { + log_trace!( + self.logger, + "Failed to retrieve fee rate estimates: {}. Falling back to {} sats/kwu.", + e, + fallback_fee_rate.to_sat_per_kwu(), + ); + } else { + log_error!( + self.logger, + "Failed to retrieve fee rate estimates: {}. Falling back to {} sats/kwu.", + e, + fallback_fee_rate.to_sat_per_kwu(), + ); + } fallback_fee_rate }, }; diff --git a/src/chain/electrum.rs b/src/chain/electrum.rs index c6b0946371..08d1895c3a 100644 --- a/src/chain/electrum.rs +++ b/src/chain/electrum.rs @@ -814,30 +814,27 @@ pub(crate) async fn get_electrum_fee_rate_cache_update( return Err(Error::FeerateEstimationUpdateFailed); } - let mut new_fee_rate_cache = HashMap::with_capacity(10); - let mut fell_back_targets = Vec::new(); - for (index, target) in confirmation_targets.into_iter().enumerate() { - // `batch_call` gives us one result per request or an error, and the check above - // rejects anything else on mainnet. We still index rather than zip so that a short - // response could never silently drop the trailing targets from the cache. - let raw_fee_rate_btc_per_kvb = - raw_estimates_btc_kvb.get(index).and_then(|raw| raw.as_f64()); - - let (fee_rate, fell_back) = - fee_rate_from_estimate(target, raw_fee_rate_btc_per_kvb, network); + let estimates_btc_per_kvb = + raw_estimates_btc_kvb.iter().map(|raw| raw.as_f64()).collect::>(); + + let (new_fee_rate_cache, fell_back_targets) = + build_fee_rate_cache(&estimates_btc_per_kvb, network).map_err(|e| { + log_error!( + logger, + "Failed to retrieve fee rate estimates: Electrum server didn't return any usable estimates. This is disallowed on Mainnet." + ); + e + })?; - if fell_back { - fell_back_targets.push(target); + for target in confirmation_targets { + if let Some(fee_rate) = new_fee_rate_cache.get(&target) { + log_trace!( + logger, + "Fee rate estimation updated for {:?}: {} sats/kwu", + target, + fee_rate.to_sat_per_kwu(), + ); } - - new_fee_rate_cache.insert(target, fee_rate); - - log_trace!( - logger, - "Fee rate estimation updated for {:?}: {} sats/kwu", - target, - fee_rate.to_sat_per_kwu(), - ); } // On `regtest`/`signet` we expect to fall back for every target, so a warning would be @@ -854,6 +851,37 @@ pub(crate) async fn get_electrum_fee_rate_cache_update( Ok(new_fee_rate_cache) } +// Builds the fee rate cache from the raw `estimatefee` results the Electrum server returned for +// our confirmation targets, in the order of `get_all_conf_targets`. +// +// Targets without a usable estimate fall back individually, but, just as for an empty Esplora +// response, we reject the update on mainnet if the server gave us no usable estimate at all. +fn build_fee_rate_cache( + estimates_btc_per_kvb: &[Option], network: Network, +) -> Result<(HashMap, Vec), Error> { + let confirmation_targets = get_all_conf_targets(); + + let mut new_fee_rate_cache = HashMap::with_capacity(10); + let mut fell_back_targets = Vec::new(); + for (index, target) in confirmation_targets.into_iter().enumerate() { + let estimate_btc_per_kvb = estimates_btc_per_kvb.get(index).copied().flatten(); + let (fee_rate, fell_back) = fee_rate_from_estimate(target, estimate_btc_per_kvb, network); + + if fell_back { + fell_back_targets.push(target); + } + + new_fee_rate_cache.insert(target, fee_rate); + } + + if fell_back_targets.len() == confirmation_targets.len() && network == Network::Bitcoin { + // Ensure we fail if we didn't receive any usable estimates. + return Err(Error::FeerateEstimationUpdateFailed); + } + + Ok((new_fee_rate_cache, fell_back_targets)) +} + // Converts a raw `estimatefee` result, as returned by the Electrum server for `target`, into the // fee rate we'll cache for it, and whether we had to fall back for it. // @@ -1078,8 +1106,8 @@ mod tests { #[test] fn missing_estimates_fall_back_per_network() { // `-1` is what Electrum serves when it has no estimate for the requested block count, - // and a short batch response leaves us without a value at all. Neither is a usable - // estimate. + // and a result that isn't a number leaves us without a value at all. Neither is a + // usable estimate. for raw in [None, Some(-1.0)] { // On mainnet/testnet the target's own default decides, rather than the relay floor // silently downgrading urgent targets to 1 sat/vb. @@ -1132,6 +1160,37 @@ mod tests { } } + #[test] + fn all_unusable_estimates_are_rejected_on_mainnet_only() { + let target_count = get_all_conf_targets().len(); + + // Whether the server answers `-1` for every block count or hands us nothing we could + // parse, we have no usable estimate at all, which we reject on mainnet just as we do an + // empty Esplora response. + for estimates in [vec![Some(-1.0); target_count], vec![None; target_count], Vec::new()] { + assert!(matches!( + build_fee_rate_cache(&estimates, Network::Bitcoin), + Err(Error::FeerateEstimationUpdateFailed) + )); + + // Off mainnet we carry on with every target on its fallback. + for network in [Network::Testnet, Network::Signet, Network::Regtest] { + let (cache, fell_back) = build_fee_rate_cache(&estimates, network).unwrap(); + assert_eq!(cache.len(), target_count, "{}", network); + assert_eq!(fell_back.len(), target_count, "{}", network); + } + } + + // A single usable estimate is enough to carry on on mainnet, with only the remaining + // targets falling back. + let mut estimates = vec![Some(-1.0); target_count]; + estimates[0] = Some(0.00002); + let (cache, fell_back) = build_fee_rate_cache(&estimates, Network::Bitcoin).unwrap(); + assert_eq!(cache.len(), target_count); + assert_eq!(fell_back.len(), target_count - 1); + assert_eq!(cache.get(&get_all_conf_targets()[0]).unwrap().to_sat_per_kwu(), 500); + } + #[test] fn estimates_are_converted_floored_and_adjusted() { // 0.00002 btc/kvb == 2 sat/vb == 500 sats/kwu, no post-estimation adjustment. diff --git a/src/chain/esplora.rs b/src/chain/esplora.rs index 72dc236f97..23a1c2254b 100644 --- a/src/chain/esplora.rs +++ b/src/chain/esplora.rs @@ -382,7 +382,7 @@ impl EsploraChainSource { build_fee_rate_cache(estimates, self.config.network).map_err(|e| { log_error!( self.logger, - "Failed to retrieve fee rate estimates: empty fee estimates are dissallowed on Mainnet.", + "Failed to retrieve fee rate estimates: Esplora server didn't return any usable estimates. This is disallowed on Mainnet.", ); e })?; @@ -555,10 +555,16 @@ impl Filter for EsploraChainSource { // urgent targets such as `UrgentOnChainSweep`, we fall back to what // `get_fallback_fee_rate_for_network` gives us, just as the Electrum and Bitcoin Core sources do. fn build_fee_rate_cache( - estimates: HashMap, network: Network, + mut estimates: HashMap, network: Network, ) -> Result<(HashMap, Vec), Error> { + // Note a non-positive value is no more usable than a missing one, so we drop these upfront + // rather than letting them pin a target to 1 sat/vb. We need to do this before picking an + // estimate, as `convert_fee_rate` settles on the closest block count at or below the + // requested one, and a bogus entry there would otherwise shadow a usable one further down. + estimates.retain(|_, estimate| *estimate > 0.0); + if estimates.is_empty() && network == Network::Bitcoin { - // Ensure we fail if we didn't receive any estimates. + // Ensure we fail if we didn't receive any usable estimates. return Err(Error::FeerateEstimationUpdateFailed); } @@ -569,10 +575,7 @@ fn build_fee_rate_cache( for target in confirmation_targets { let num_blocks = get_num_block_defaults_for_target(target); - // Note a non-positive value is no more usable than a missing one, so we treat it as - // missing rather than letting it pin the target to 1 sat/vb. - let converted = esplora_client::convert_fee_rate(num_blocks, estimates.clone()) - .filter(|converted| *converted > 0.0); + let converted = esplora_client::convert_fee_rate(num_blocks, estimates.clone()); let fee_rate = match converted { Some(converted) => { @@ -678,6 +681,30 @@ mod tests { } } + #[test] + fn non_positive_estimates_dont_shadow_usable_ones() { + // `convert_fee_rate` picks the closest block count at or below the requested one, so a + // bogus entry at 6 blocks must not keep us from using the estimate we have for 1 block. + for bogus in [0.0, -1.0] { + let estimates = HashMap::from([(1, 5.0), (6, bogus), (144, 2.0)]); + let (cache, fell_back) = build_fee_rate_cache(estimates, Network::Bitcoin).unwrap(); + + let urgent = ConfirmationTarget::Lightning(LdkConfirmationTarget::UrgentOnChainSweep); + assert_eq!(cache.get(&urgent).unwrap().to_sat_per_kwu(), 1250, "{}", bogus); + assert!(!fell_back.contains(&urgent), "{}", bogus); + } + } + + #[test] + fn all_non_positive_estimates_are_rejected_on_mainnet() { + // A map holding nothing usable is no better than an empty one. + let estimates = HashMap::from([(1, 0.0), (6, -1.0)]); + assert!(matches!( + build_fee_rate_cache(estimates, Network::Bitcoin), + Err(Error::FeerateEstimationUpdateFailed) + )); + } + #[test] fn no_estimates_stay_on_one_sat_per_vb_on_regtest_and_signet() { // `regtest`/`signet` have no fee market at all. Regtest Esplora serves an empty map, as From 715950e93ed12801cd4e27d7d384edc0a59c3e70 Mon Sep 17 00:00:00 2001 From: jolah1 Date: Mon, 23 Nov 2026 08:04:23 +0100 Subject: [PATCH 4/4] Only give up on Bitcoin Core fee estimates if none are usable The Esplora and Electrum sources fall back to a target's default when they have no usable estimate for it, and on mainnet only reject the update if they got no usable estimate at all. Bitcoin Core however still failed the whole update on mainnet as soon as a single `estimatesmartfee` call errored, e.g., as it lacks the data for one of our block counts, discarding the estimates it did give us. Here we bring it in line, moving the cache construction to a `build_fee_rate_cache` that, just as for the other two sources, falls back per target and rejects the update on mainnet only if we didn't get a single usable estimate. Note we don't count the mempool minimum fee towards that, as Bitcoin Core reports it even when it has no fee estimates at all, e.g., while still syncing, which is exactly when we want to keep failing. As for the other sources, we now log the targets we fell back for in a single warning, staying quiet on `regtest`/`signet` where that is every target, and log the per-target errors at debug level, or at trace level on `regtest`/`signet`. This change was written with the assistance of Claude Code. Co-Authored-By: Claude Opus 5.5 --- src/chain/bitcoind.rs | 211 ++++++++++++++++++++++++++++++++++-------- 1 file changed, 174 insertions(+), 37 deletions(-) diff --git a/src/chain/bitcoind.rs b/src/chain/bitcoind.rs index 671dabeb68..2449fdaf2e 100644 --- a/src/chain/bitcoind.rs +++ b/src/chain/bitcoind.rs @@ -43,7 +43,9 @@ use crate::fee_estimator::{ get_num_block_defaults_for_target, ConfirmationTarget, OnchainFeeEstimator, }; use crate::io::utils::update_and_persist_node_metrics; -use crate::logger::{log_bytes, log_debug, log_error, log_info, log_trace, LdkLogger, Logger}; +use crate::logger::{ + log_bytes, log_debug, log_error, log_info, log_trace, log_warn, LdkLogger, Logger, +}; use crate::payment::NodeOffersMessageHandler; use crate::tx_broadcaster::SortedTransactions; use crate::types::{Broadcaster, ChainMonitor, ChannelManager, DynStore, Sweeper, Wallet}; @@ -602,7 +604,7 @@ impl BitcoindChainSource { } let confirmation_targets = get_all_conf_targets(); - let mut new_fee_rate_cache = HashMap::with_capacity(10); + let mut estimates = Vec::with_capacity(confirmation_targets.len()); let now = Instant::now(); for target in confirmation_targets { let fee_rate_update_res = match target { @@ -636,54 +638,66 @@ impl BitcoindChainSource { }, }; - let fee_rate = match (fee_rate_update_res, self.config.network) { - (Ok(rate), _) => { - // LDK 0.0.118 introduced changes to the `ConfirmationTarget` semantics that - // require some post-estimation adjustments to the fee rates, which we do here. - apply_post_estimation_adjustments(target, rate) - }, - (Err(e), Network::Bitcoin) => { - // Strictly fail on mainnet. - log_error!(self.logger, "Failed to retrieve fee rate estimates: {}", e); - return Err(Error::FeerateEstimationUpdateFailed); - }, - (Err(e), network) => { - // Off mainnet we carry on with this target's fallback: on regtest/signet - // there is no fee market to begin with, and on testnet `estimatesmartfee` - // can simply be unreliable. Note this keeps whatever estimates we did get - // for the remaining targets. - let fallback_fee_rate = get_fallback_fee_rate_for_network(target, network); - // On `regtest`/`signet` we expect to end up here for every target, so an - // error would be pure noise there. - if matches!(network, Network::Regtest | Network::Signet) { + let estimate = match fee_rate_update_res { + Ok(rate) => Some(rate), + Err(e) => { + // Note `estimatesmartfee` errors out if it has no estimate for the requested + // block count, which on `regtest`/`signet` is the case for every target, so + // we keep quiet there. + if matches!(self.config.network, Network::Regtest | Network::Signet) { log_trace!( self.logger, - "Failed to retrieve fee rate estimates: {}. Falling back to {} sats/kwu.", + "Failed to retrieve fee rate estimate for {:?}: {}", + target, e, - fallback_fee_rate.to_sat_per_kwu(), ); } else { - log_error!( + log_debug!( self.logger, - "Failed to retrieve fee rate estimates: {}. Falling back to {} sats/kwu.", + "Failed to retrieve fee rate estimate for {:?}: {}", + target, e, - fallback_fee_rate.to_sat_per_kwu(), ); } - fallback_fee_rate + None }, }; + estimates.push((target, estimate)); + } - new_fee_rate_cache.insert(target, fee_rate); + let (new_fee_rate_cache, fell_back_targets) = + build_fee_rate_cache(&estimates, self.config.network).map_err(|e| { + log_error!( + self.logger, + "Failed to retrieve fee rate estimates: Bitcoin Core didn't return any usable estimates. This is disallowed on Mainnet.", + ); + e + })?; - log_trace!( + // On `regtest`/`signet` we expect to fall back for every target, so a warning would be + // pure noise there. Elsewhere it means we're pricing transactions off defaults rather + // than off the chain, which shouldn't pass silently. + if !fell_back_targets.is_empty() + && !matches!(self.config.network, Network::Regtest | Network::Signet) + { + log_warn!( self.logger, - "Fee rate estimation updated for {:?}: {} sats/kwu", - target, - fee_rate.to_sat_per_kwu(), + "Received no usable fee rate estimate for {:?}, falling back to their defaults.", + fell_back_targets, ); } + for target in confirmation_targets { + if let Some(fee_rate) = new_fee_rate_cache.get(&target) { + log_trace!( + self.logger, + "Fee rate estimation updated for {:?}: {} sats/kwu", + target, + fee_rate.to_sat_per_kwu(), + ); + } + } + if self.fee_estimator.set_fee_rate_cache(new_fee_rate_cache) { // We only log if the values changed, as it might be very spammy otherwise. log_debug!( @@ -1643,6 +1657,47 @@ impl fmt::Display for BitcoindClientError { impl std::error::Error for BitcoindClientError {} +// Builds the fee rate cache from the estimates Bitcoin Core gave us for our confirmation targets. +// +// Targets without an estimate fall back individually, but, just as the Esplora and Electrum +// sources do, we reject the update on mainnet if we didn't get a single usable estimate. +// +// Note we don't count the mempool minimum fee towards that, which we use for +// `MinAllowedAnchorChannelRemoteFee`, as Bitcoin Core reports it even when it has no fee +// estimates at all, e.g., while still syncing. +fn build_fee_rate_cache( + estimates: &[(ConfirmationTarget, Option)], network: Network, +) -> Result<(HashMap, Vec), Error> { + let mut new_fee_rate_cache = HashMap::with_capacity(estimates.len()); + let mut fell_back_targets = Vec::new(); + for &(target, estimate) in estimates { + let fee_rate = match estimate { + // LDK 0.0.118 introduced changes to the `ConfirmationTarget` semantics that + // require some post-estimation adjustments to the fee rates, which we do here. + Some(estimate) => apply_post_estimation_adjustments(target, estimate), + // We have no estimate to adjust, so we fall back. + None => { + fell_back_targets.push(target); + get_fallback_fee_rate_for_network(target, network) + }, + }; + + new_fee_rate_cache.insert(target, fee_rate); + } + + let mempool_min_fee_target = + ConfirmationTarget::Lightning(LdkConfirmationTarget::MinAllowedAnchorChannelRemoteFee); + let received_any_estimate = estimates + .iter() + .any(|(target, estimate)| *target != mempool_min_fee_target && estimate.is_some()); + if !received_any_estimate && network == Network::Bitcoin { + // Ensure we fail if we didn't receive any usable estimates. + return Err(Error::FeerateEstimationUpdateFailed); + } + + Ok((new_fee_rate_cache, fell_back_targets)) +} + #[cfg(test)] mod tests { use std::collections::{HashMap, HashSet}; @@ -1652,7 +1707,8 @@ mod tests { use bitcoin::absolute::LockTime; use bitcoin::hashes::Hash; use bitcoin::transaction::Version; - use bitcoin::{FeeRate, OutPoint, ScriptBuf, Transaction, TxIn, TxOut, Txid, Witness}; + use bitcoin::{FeeRate, Network, OutPoint, ScriptBuf, Transaction, TxIn, TxOut, Txid, Witness}; + use lightning::chain::chaininterface::ConfirmationTarget as LdkConfirmationTarget; use lightning_block_sync::http::JsonResponse; use proptest::arbitrary::any; use proptest::collection::vec; @@ -1660,11 +1716,14 @@ mod tests { use serde_json::json; use crate::chain::bitcoind::{ - acquire_initial_wallet_sync_guard, emit_new_mempool_txs, CachedMempoolEntry, FeeResponse, - GetMempoolEntryResponse, GetRawMempoolResponse, GetRawTransactionResponse, MempoolEntry, - MempoolMinFeeResponse, + acquire_initial_wallet_sync_guard, build_fee_rate_cache, emit_new_mempool_txs, + CachedMempoolEntry, FeeResponse, GetMempoolEntryResponse, GetRawMempoolResponse, + GetRawTransactionResponse, MempoolEntry, MempoolMinFeeResponse, }; use crate::chain::{WalletSyncGuard, WalletSyncStatus}; + use crate::fee_estimator::{ + get_all_conf_targets, get_fallback_rate_for_target, ConfirmationTarget, + }; use crate::Error; fn insert_mempool_entry( @@ -1825,6 +1884,84 @@ mod tests { } } + #[test] + fn failed_estimates_fall_back_per_target() { + // Bitcoin Core only failed to estimate the urgent target, e.g., as it lacks the data for + // it, so the remaining targets keep their estimates rather than the update being dropped. + let urgent = ConfirmationTarget::Lightning(LdkConfirmationTarget::UrgentOnChainSweep); + let max = ConfirmationTarget::Lightning(LdkConfirmationTarget::MaximumFeeEstimate); + let estimates = get_all_conf_targets() + .into_iter() + .map(|target| { + let estimate = (target != urgent).then(|| FeeRate::from_sat_per_kwu(500)); + (target, estimate) + }) + .collect::>(); + + for network in [Network::Bitcoin, Network::Testnet] { + let (cache, fell_back) = build_fee_rate_cache(&estimates, network).unwrap(); + assert_eq!(cache.len(), get_all_conf_targets().len(), "{}", network); + assert_eq!(fell_back, vec![urgent], "{}", network); + + // The failed target gets its own default rather than the 1 sat/vb floor. + assert_eq!( + cache.get(&urgent).unwrap().to_sat_per_kwu(), + get_fallback_rate_for_target(urgent) as u64, + "{}", + network + ); + + // While the estimates we did get are adjusted as usual, i.e., `x * 1.1 + 2500` here. + assert_eq!(cache.get(&max).unwrap().to_sat_per_kwu(), 3050, "{}", network); + } + } + + #[test] + fn all_failed_estimates_are_rejected_on_mainnet_only() { + let estimates = + get_all_conf_targets().into_iter().map(|target| (target, None)).collect::>(); + + assert!(matches!( + build_fee_rate_cache(&estimates, Network::Bitcoin), + Err(Error::FeerateEstimationUpdateFailed) + )); + + // Off mainnet we carry on with every target on its fallback, which on regtest/signet is + // the adjusted 1 sat/vb stand-in, i.e., 2775 sats/kwu for `MaximumFeeEstimate`. + for network in [Network::Testnet, Network::Signet, Network::Regtest] { + let (cache, fell_back) = build_fee_rate_cache(&estimates, network).unwrap(); + assert_eq!(cache.len(), get_all_conf_targets().len(), "{}", network); + assert_eq!(fell_back.len(), get_all_conf_targets().len(), "{}", network); + } + for network in [Network::Signet, Network::Regtest] { + let (cache, _) = build_fee_rate_cache(&estimates, network).unwrap(); + let max = ConfirmationTarget::Lightning(LdkConfirmationTarget::MaximumFeeEstimate); + assert_eq!(cache.get(&max).unwrap().to_sat_per_kwu(), 2775, "{}", network); + } + } + + #[test] + fn mempool_min_fee_alone_is_rejected_on_mainnet() { + // Bitcoin Core reports its mempool minimum fee even if it has no fee estimates at all, so + // that alone mustn't be enough to carry on with every other target on its default. + let mempool_min_fee_target = + ConfirmationTarget::Lightning(LdkConfirmationTarget::MinAllowedAnchorChannelRemoteFee); + let estimates = get_all_conf_targets() + .into_iter() + .map(|target| { + let estimate = + (target == mempool_min_fee_target).then(|| FeeRate::from_sat_per_kwu(253)); + (target, estimate) + }) + .collect::>(); + + assert!(matches!( + build_fee_rate_cache(&estimates, Network::Bitcoin), + Err(Error::FeerateEstimationUpdateFailed) + )); + assert!(build_fee_rate_cache(&estimates, Network::Testnet).is_ok()); + } + proptest! { #![proptest_config(proptest::test_runner::Config::with_cases(20))]