Skip to content

Commit 371fad0

Browse files
committed
Free holding cell on monitor-updating-restored when there's no upd
If there is no pending channel update messages when monitor updating is restored (though there may be an RAA to send), and we're connected to our peer and not awaiting a remote RAA, we need to free anything in our holding cell. However, we don't want to immediately free the holding cell during channel_monitor_updated as it presents a somewhat bug-prone case of reentrancy: a) it would re-enter user code around a monitor update while being called from user code notifying us of the same monitor being updated, making deadlocs very likely (in fact, our fuzzers would have a bug here!), b) the re-entrancy only occurs in a very rare case, making it likely users will not hit it in testing, only deadlocking in production. Thus, we add a holding-cell-free pass over each channel in get_and_clear_pending_msg_events. This fits up nicely with the anticipated bug - users almost certainly need to process new network messages immediately after monitor updating has been restored to send messages which were not sent originally when the monitor updating was paused. Without this, chanmon_fail_consistency was able to find a stuck condition where we sit on an HTLC failure in our holding cell and don't ever handle it (at least until we have other actions to take which empty the holding cell).
1 parent e33012f commit 371fad0

File tree

2 files changed

+78
-11
lines changed

2 files changed

+78
-11
lines changed

lightning/src/ln/channel.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2294,6 +2294,14 @@ impl<Signer: Sign> Channel<Signer> {
22942294
}, commitment_signed, closing_signed, monitor_update))
22952295
}
22962296

2297+
/// Public version of the below, checking relevant preconditions first
2298+
pub fn maybe_free_holding_cell_htlcs<L: Deref>(&mut self, logger: &L) -> Result<(Option<(msgs::CommitmentUpdate, ChannelMonitorUpdate)>, Vec<(HTLCSource, PaymentHash)>), ChannelError> where L::Target: Logger {
2299+
if self.channel_state >= ChannelState::ChannelFunded as u32 &&
2300+
(self.channel_state & (ChannelState::AwaitingRemoteRevoke as u32 | ChannelState::PeerDisconnected as u32 | ChannelState::MonitorUpdateFailed as u32)) == 0 {
2301+
self.free_holding_cell_htlcs(logger)
2302+
} else { Ok((None, Vec::new())) }
2303+
}
2304+
22972305
/// Used to fulfill holding_cell_htlcs when we get a remote ack (or implicitly get it by them
22982306
/// fulfilling or failing the last pending HTLC)
22992307
fn free_holding_cell_htlcs<L: Deref>(&mut self, logger: &L) -> Result<(Option<(msgs::CommitmentUpdate, ChannelMonitorUpdate)>, Vec<(HTLCSource, PaymentHash)>), ChannelError> where L::Target: Logger {

lightning/src/ln/channelmanager.rs

Lines changed: 70 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -755,13 +755,12 @@ macro_rules! handle_monitor_err {
755755
($self: ident, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $resend_raa: expr, $resend_commitment: expr) => {
756756
handle_monitor_err!($self, $err, $channel_state, $entry, $action_type, $resend_raa, $resend_commitment, Vec::new(), Vec::new())
757757
};
758-
($self: ident, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $resend_raa: expr, $resend_commitment: expr, $failed_forwards: expr, $failed_fails: expr) => {
758+
($self: ident, $err: expr, $short_to_id: expr, $chan: expr, $action_type: path, $resend_raa: expr, $resend_commitment: expr, $failed_forwards: expr, $failed_fails: expr, $chan_id: expr) => {
759759
match $err {
760760
ChannelMonitorUpdateErr::PermanentFailure => {
761-
log_error!($self.logger, "Closing channel {} due to monitor update PermanentFailure", log_bytes!($entry.key()[..]));
762-
let (channel_id, mut chan) = $entry.remove_entry();
763-
if let Some(short_id) = chan.get_short_channel_id() {
764-
$channel_state.short_to_id.remove(&short_id);
761+
log_error!($self.logger, "Closing channel {} due to monitor update ChannelMonitorUpdateErr::PermanentFailure", log_bytes!($chan_id[..]));
762+
if let Some(short_id) = $chan.get_short_channel_id() {
763+
$short_to_id.remove(&short_id);
765764
}
766765
// TODO: $failed_fails is dropped here, which will cause other channels to hit the
767766
// chain in a confused state! We need to move them into the ChannelMonitor which
@@ -772,12 +771,12 @@ macro_rules! handle_monitor_err {
772771
// splitting hairs we'd prefer to claim payments that were to us, but we haven't
773772
// given up the preimage yet, so might as well just wait until the payment is
774773
// retried, avoiding the on-chain fees.
775-
let res: Result<(), _> = Err(MsgHandleErrInternal::from_finish_shutdown("ChannelMonitor storage failure".to_owned(), channel_id, chan.force_shutdown(true), $self.get_channel_update(&chan).ok()));
776-
res
774+
let res: Result<(), _> = Err(MsgHandleErrInternal::from_finish_shutdown("ChannelMonitor storage failure".to_owned(), *$chan_id, $chan.force_shutdown(true), $self.get_channel_update(&$chan).ok()));
775+
(res, true)
777776
},
778777
ChannelMonitorUpdateErr::TemporaryFailure => {
779778
log_info!($self.logger, "Disabling channel {} due to monitor update TemporaryFailure. On restore will send {} and process {} forwards and {} fails",
780-
log_bytes!($entry.key()[..]),
779+
log_bytes!($chan_id[..]),
781780
if $resend_commitment && $resend_raa {
782781
match $action_type {
783782
RAACommitmentOrder::CommitmentFirst => { "commitment then RAA" },
@@ -794,11 +793,18 @@ macro_rules! handle_monitor_err {
794793
if !$resend_raa {
795794
debug_assert!($action_type == RAACommitmentOrder::CommitmentFirst || !$resend_commitment);
796795
}
797-
$entry.get_mut().monitor_update_failed($resend_raa, $resend_commitment, $failed_forwards, $failed_fails);
798-
Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore("Failed to update ChannelMonitor".to_owned()), *$entry.key()))
796+
$chan.monitor_update_failed($resend_raa, $resend_commitment, $failed_forwards, $failed_fails);
797+
(Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore("Failed to update ChannelMonitor".to_owned()), *$chan_id)), false)
799798
},
800799
}
801-
}
800+
};
801+
($self: ident, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $resend_raa: expr, $resend_commitment: expr, $failed_forwards: expr, $failed_fails: expr) => { {
802+
let (res, drop) = handle_monitor_err!($self, $err, $channel_state.short_to_id, $entry.get_mut(), $action_type, $resend_raa, $resend_commitment, $failed_forwards, $failed_fails, $entry.key());
803+
if drop {
804+
$entry.remove_entry();
805+
}
806+
res
807+
} };
802808
}
803809

804810
macro_rules! return_monitor_err {
@@ -3319,6 +3325,57 @@ impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelMana
33193325
}
33203326
}
33213327

3328+
/// Check the holding cell in each channel and free any pending HTLCs in them if possible.
3329+
/// This should only apply to HTLCs which were added to the holding cell because we were
3330+
/// waiting on a monitor update to finish. In that case, we don't want to free the holding cell
3331+
/// directly in `channel_monitor_updated` as it may introduce deadlocks calling back into user
3332+
/// code to inform them of a channel monitor update.
3333+
fn check_free_holding_cells(&self) {
3334+
let mut forwarding_failed_htlcs = Vec::new();
3335+
let mut handle_errors = Vec::new();
3336+
{
3337+
let mut channel_state_lock = self.channel_state.lock().unwrap();
3338+
let channel_state = &mut *channel_state_lock;
3339+
let by_id = &mut channel_state.by_id;
3340+
let short_to_id = &mut channel_state.short_to_id;
3341+
let pending_msg_events = &mut channel_state.pending_msg_events;
3342+
3343+
by_id.retain(|channel_id, chan| {
3344+
match chan.maybe_free_holding_cell_htlcs(&self.logger) {
3345+
Ok((None, ref htlcs)) if htlcs.is_empty() => true,
3346+
Ok((commitment_opt, failed_htlcs)) => {
3347+
forwarding_failed_htlcs.push((failed_htlcs, *channel_id));
3348+
if let Some((commitment_update, monitor_update)) = commitment_opt {
3349+
if let Err(e) = self.chain_monitor.update_channel(chan.get_funding_txo().unwrap(), monitor_update) {
3350+
let (res, close_channel) = handle_monitor_err!(self, e, short_to_id, chan, RAACommitmentOrder::CommitmentFirst, false, true, Vec::new(), Vec::new(), channel_id);
3351+
handle_errors.push((chan.get_counterparty_node_id(), res));
3352+
if close_channel { return false; }
3353+
} else {
3354+
pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
3355+
node_id: chan.get_counterparty_node_id(),
3356+
updates: commitment_update,
3357+
});
3358+
}
3359+
}
3360+
true
3361+
},
3362+
Err(e) => {
3363+
let (close_channel, res) = convert_chan_err!(self, e, short_to_id, chan, channel_id);
3364+
handle_errors.push((chan.get_counterparty_node_id(), Err(res)));
3365+
!close_channel
3366+
}
3367+
}
3368+
});
3369+
}
3370+
for (failures, channel_id) in forwarding_failed_htlcs.drain(..) {
3371+
self.fail_holding_cell_htlcs(failures, channel_id);
3372+
}
3373+
3374+
for (counterparty_node_id, err) in handle_errors.drain(..) {
3375+
let _ = handle_error!(self, err, counterparty_node_id);
3376+
}
3377+
}
3378+
33223379
/// Handle a list of channel failures during a block_connected or block_disconnected call,
33233380
/// pushing the channel monitor update (if any) to the background events queue and removing the
33243381
/// Channel object.
@@ -3355,6 +3412,8 @@ impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> MessageSend
33553412
// ChannelMonitors when clearing other events.
33563413
self.process_pending_monitor_events();
33573414

3415+
self.check_free_holding_cells();
3416+
33583417
let mut ret = Vec::new();
33593418
let mut channel_state = self.channel_state.lock().unwrap();
33603419
mem::swap(&mut ret, &mut channel_state.pending_msg_events);

0 commit comments

Comments
 (0)