Skip to content

Commit c276b0a

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 lightningdevkit#993
1 parent 9f4d907 commit c276b0a

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
@@ -5303,6 +5303,26 @@ impl<SP: Deref> Channel<SP> where
53035303
}
53045304
}
53055305

5306+
pub fn check_for_stale_feerate<L: Logger>(&mut self, logger: &L, min_feerate: u32) -> Result<(), ClosureReason> {
5307+
if self.context.is_outbound() {
5308+
// While its possible our fee is too low for an outbound channel because we've been
5309+
// unable to increase the fee, we don't try to force-close directly here.
5310+
return Ok(());
5311+
}
5312+
if self.context.feerate_per_kw < min_feerate {
5313+
log_info!(logger,
5314+
"Closing channel as feerate of {} is below required {} (the minimum required rate over the past day)",
5315+
self.context.feerate_per_kw, min_feerate
5316+
);
5317+
Err(ClosureReason::PeerFeerateTooLow {
5318+
peer_feerate_sat_per_kw: self.context.feerate_per_kw,
5319+
required_feerate_sat_per_kw: min_feerate,
5320+
})
5321+
} else {
5322+
Ok(())
5323+
}
5324+
}
5325+
53065326
pub fn update_fee<F: Deref, L: Deref>(&mut self, fee_estimator: &LowerBoundedFeeEstimator<F>, msg: &msgs::UpdateFee, logger: &L) -> Result<(), ChannelError>
53075327
where F::Target: FeeEstimator, L::Target: Logger
53085328
{

lightning/src/ln/channelmanager.rs

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

965+
/// The number of blocks of historical feerate estimates we keep around and consider when deciding
966+
/// to force-close a channel for having too-low fees. Also the number of blocks we have to see
967+
/// after startup before we consider force-closing channels for having too-low fees.
968+
const FEERATE_TRACKING_BLOCKS: usize = 144;
969+
965970
/// Stores a PaymentSecret and any other data we may need to validate an inbound payment is
966971
/// actually ours and not some duplicate HTLC sent to us by a node along the route.
967972
///
@@ -2096,6 +2101,21 @@ where
20962101
/// Tracks the message events that are to be broadcasted when we are connected to some peer.
20972102
pending_broadcast_messages: Mutex<Vec<MessageSendEvent>>,
20982103

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

3215+
last_days_feerates: Mutex::new(VecDeque::new()),
3216+
31953217
entropy_source,
31963218
node_signer,
31973219
signer_provider,
@@ -9414,7 +9436,38 @@ where
94149436
self, || -> NotifyOption { NotifyOption::DoPersist });
94159437
*self.best_block.write().unwrap() = BestBlock::new(block_hash, height);
94169438

9417-
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, None)));
9439+
let mut min_anchor_feerate = None;
9440+
let mut min_non_anchor_feerate = None;
9441+
if self.background_events_processed_since_startup.load(Ordering::Relaxed) {
9442+
// If we're past the startup phase, update our feerate cache
9443+
let mut last_days_feerates = self.last_days_feerates.lock().unwrap();
9444+
if last_days_feerates.len() >= FEERATE_TRACKING_BLOCKS {
9445+
last_days_feerates.pop_front();
9446+
}
9447+
let anchor_feerate = self.fee_estimator
9448+
.bounded_sat_per_1000_weight(ConfirmationTarget::MinAllowedAnchorChannelRemoteFee);
9449+
let non_anchor_feerate = self.fee_estimator
9450+
.bounded_sat_per_1000_weight(ConfirmationTarget::MinAllowedNonAnchorChannelRemoteFee);
9451+
last_days_feerates.push_back((anchor_feerate, non_anchor_feerate));
9452+
if last_days_feerates.len() >= FEERATE_TRACKING_BLOCKS {
9453+
min_anchor_feerate = last_days_feerates.iter().map(|(f, _)| f).min().copied();
9454+
min_non_anchor_feerate = last_days_feerates.iter().map(|(_, f)| f).min().copied();
9455+
}
9456+
}
9457+
9458+
self.do_chain_event(Some(height), |channel| {
9459+
let logger = WithChannelContext::from(&self.logger, &channel.context, None);
9460+
if channel.context.get_channel_type().supports_anchors_zero_fee_htlc_tx() {
9461+
if let Some(feerate) = min_anchor_feerate {
9462+
channel.check_for_stale_feerate(&logger, feerate)?;
9463+
}
9464+
} else {
9465+
if let Some(feerate) = min_non_anchor_feerate {
9466+
channel.check_for_stale_feerate(&logger, feerate)?;
9467+
}
9468+
}
9469+
channel.best_block_updated(height, header.time, self.chain_hash, &self.node_signer, &self.default_configuration, &&WithChannelContext::from(&self.logger, &channel.context, None))
9470+
});
94189471

94199472
macro_rules! max_time {
94209473
($timestamp: expr) => {
@@ -12375,6 +12428,8 @@ where
1237512428
node_signer: args.node_signer,
1237612429
signer_provider: args.signer_provider,
1237712430

12431+
last_days_feerates: Mutex::new(VecDeque::new()),
12432+
1237812433
logger: args.logger,
1237912434
default_configuration: args.default_config,
1238012435
};

0 commit comments

Comments
 (0)