Skip to content

Commit 986bc4a

Browse files
committed
Force-close channels if their feerate gets stale without any update
For quite some time, LDK has force-closed channels if the peer sends us a feerate update which is below our `FeeEstimator`'s concept of a channel lower-bound. This is intended to ensure that channel feerates are always sufficient to get our commitment transaction confirmed on-chain if we do need to force-close. However, we've never checked our channel feerate regularly - if a peer is offline (or just uninterested in updating the channel feerate) and the prevailing feerates on-chain go up, we'll simply ignore it and allow our commitment transaction to sit around with a feerate too low to get confirmed. Here we rectify this oversight by force-closing channels with stale feerates, checking after each block. However, because fee estimators are often buggy and force-closures piss off users, we only do so rather conservatively. Specifically, we only force-close if a channel's feerate is below the minimum `FeeEstimator`-provided minimum across the last day. Further, because fee estimators are often especially buggy on startup (and because peers haven't had a chance to update the channel feerates yet), we don't force-close channels until we have a full day of feerate lower-bound history. This should reduce the incidence of force-closures substantially, but it is expected this will still increase force-closures somewhat substantially depending on the users' `FeeEstimator`. Fixes #993
1 parent fee7a9a commit 986bc4a

File tree

2 files changed

+76
-1
lines changed

2 files changed

+76
-1
lines changed

lightning/src/ln/channel.rs

+20
Original file line numberDiff line numberDiff line change
@@ -5245,6 +5245,26 @@ impl<SP: Deref> Channel<SP> where
52455245
}
52465246
}
52475247

5248+
pub fn check_for_stale_feerate<L: Logger>(&mut self, logger: &L, min_feerate: u32) -> Result<(), ClosureReason> {
5249+
if self.context.is_outbound() {
5250+
// While its possible our fee is too low for an outbound channel because we've been
5251+
// unable to increase the fee, we don't try to force-close directly here.
5252+
return Ok(());
5253+
}
5254+
if self.context.feerate_per_kw < min_feerate {
5255+
log_info!(logger,
5256+
"Closing channel as feerate of {} is below required {} (the minimum required rate over the past day)",
5257+
self.context.feerate_per_kw, min_feerate
5258+
);
5259+
Err(ClosureReason::PeerFeerateTooLow {
5260+
peer_feerate_sat_per_kw: self.context.feerate_per_kw,
5261+
required_feerate_sat_per_kw: min_feerate,
5262+
})
5263+
} else {
5264+
Ok(())
5265+
}
5266+
}
5267+
52485268
pub fn update_fee<F: Deref, L: Deref>(&mut self, fee_estimator: &LowerBoundedFeeEstimator<F>, msg: &msgs::UpdateFee, logger: &L) -> Result<(), ChannelError>
52495269
where F::Target: FeeEstimator, L::Target: Logger
52505270
{

lightning/src/ln/channelmanager.rs

+56-1
Original file line numberDiff line numberDiff line change
@@ -958,6 +958,11 @@ pub(super) struct InboundChannelRequest {
958958
/// accepted. An unaccepted channel that exceeds this limit will be abandoned.
959959
const UNACCEPTED_INBOUND_CHANNEL_AGE_LIMIT_TICKS: i32 = 2;
960960

961+
/// The number of blocks of historical feerate estimates we keep around and consider when deciding
962+
/// to force-close a channel for having too-low fees. Also the number of blocks we have to see
963+
/// after startup before we consider force-closing channels for having too-low fees.
964+
const FEERATE_TRACKING_BLOCKS: usize = 144;
965+
961966
/// Stores a PaymentSecret and any other data we may need to validate an inbound payment is
962967
/// actually ours and not some duplicate HTLC sent to us by a node along the route.
963968
///
@@ -2092,6 +2097,21 @@ where
20922097
/// Tracks the message events that are to be broadcasted when we are connected to some peer.
20932098
pending_broadcast_messages: Mutex<Vec<MessageSendEvent>>,
20942099

2100+
/// We only want to force-close our channels on peers based on stale feerates when we're
2101+
/// confident the feerate on the channel is *really* stale, not just became stale recently.
2102+
/// Thus, we store the fee estimates we had as of the last [`FEERATE_TRACKING_BLOCKS`] blocks
2103+
/// (after startup completed) here, and only force-close when channels have a lower feerate
2104+
/// than we predicted any time in the last [`FEERATE_TRACKING_BLOCKS`] blocks.
2105+
///
2106+
/// We only keep this in memory as we assume any feerates we receive immediately after startup
2107+
/// may be bunk (as they often are if Bitcoin Core crashes) and want to delay taking any
2108+
/// actions for a day anyway.
2109+
///
2110+
/// The first element in the pair is the
2111+
/// [`ConfirmationTarget::MinAllowedAnchorChannelRemoteFee`] estimate, the second the
2112+
/// [`ConfirmationTarget::MinAllowedNonAnchorChannelRemoteFee`] estimate.
2113+
last_days_feerates: Mutex<VecDeque<(u32, u32)>>,
2114+
20952115
entropy_source: ES,
20962116
node_signer: NS,
20972117
signer_provider: SP,
@@ -3188,6 +3208,8 @@ where
31883208
pending_offers_messages: Mutex::new(Vec::new()),
31893209
pending_broadcast_messages: Mutex::new(Vec::new()),
31903210

3211+
last_days_feerates: Mutex::new(VecDeque::new()),
3212+
31913213
entropy_source,
31923214
node_signer,
31933215
signer_provider,
@@ -9394,7 +9416,38 @@ where
93949416
self, || -> NotifyOption { NotifyOption::DoPersist });
93959417
*self.best_block.write().unwrap() = BestBlock::new(block_hash, height);
93969418

9397-
self.do_chain_event(Some(height), |channel| channel.best_block_updated(height, header.time, self.chain_hash, &self.node_signer, &self.default_configuration, &&WithChannelContext::from(&self.logger, &channel.context)));
9419+
let mut min_anchor_feerate = None;
9420+
let mut min_non_anchor_feerate = None;
9421+
if self.background_events_processed_since_startup.load(Ordering::Relaxed) {
9422+
// If we're past the startup phase, update our feerate cache
9423+
let mut last_days_feerates = self.last_days_feerates.lock().unwrap();
9424+
if last_days_feerates.len() >= FEERATE_TRACKING_BLOCKS {
9425+
last_days_feerates.pop_front();
9426+
}
9427+
let anchor_feerate = self.fee_estimator
9428+
.bounded_sat_per_1000_weight(ConfirmationTarget::MinAllowedAnchorChannelRemoteFee);
9429+
let non_anchor_feerate = self.fee_estimator
9430+
.bounded_sat_per_1000_weight(ConfirmationTarget::MinAllowedNonAnchorChannelRemoteFee);
9431+
last_days_feerates.push_back((anchor_feerate, non_anchor_feerate));
9432+
if last_days_feerates.len() >= FEERATE_TRACKING_BLOCKS {
9433+
min_anchor_feerate = last_days_feerates.iter().map(|(f, _)| f).min().copied();
9434+
min_non_anchor_feerate = last_days_feerates.iter().map(|(_, f)| f).min().copied();
9435+
}
9436+
}
9437+
9438+
self.do_chain_event(Some(height), |channel| {
9439+
let logger = WithChannelContext::from(&self.logger, &channel.context);
9440+
if channel.context.get_channel_type().supports_anchors_zero_fee_htlc_tx() {
9441+
if let Some(feerate) = min_anchor_feerate {
9442+
channel.check_for_stale_feerate(&logger, feerate)?;
9443+
}
9444+
} else {
9445+
if let Some(feerate) = min_non_anchor_feerate {
9446+
channel.check_for_stale_feerate(&logger, feerate)?;
9447+
}
9448+
}
9449+
channel.best_block_updated(height, header.time, self.chain_hash, &self.node_signer, &self.default_configuration, &&logger)
9450+
});
93989451

93999452
macro_rules! max_time {
94009453
($timestamp: expr) => {
@@ -12338,6 +12391,8 @@ where
1233812391
node_signer: args.node_signer,
1233912392
signer_provider: args.signer_provider,
1234012393

12394+
last_days_feerates: Mutex::new(VecDeque::new()),
12395+
1234112396
logger: args.logger,
1234212397
default_configuration: args.default_config,
1234312398
};

0 commit comments

Comments
 (0)