Skip to content

Commit fe59961

Browse files
committed
Allow holding ChannelMonitorUpdates until later, completing one
In the coming commits, we need to delay `ChannelMonitorUpdate`s until future actions (specifically `Event` handling). However, because we should only notify users once of a given `ChannelMonitorUpdate` and they must be provided in-order, we need to track which ones have or have not been given to users and, once updating resumes, fly the ones that haven't already made it to users. To do this we simply add a `bool` in the `ChannelMonitorUpdate` set stored in the `Channel` which indicates if an update flew and decline to provide new updates back to the `ChannelManager` if any updates have their flown bit unset. Further, because we'll now by releasing `ChannelMonitorUpdate`s which were already stored in the pending list, we now need to support getting a `Completed` result for a monitor which isn't the only pending monitor (or even out of order), thus we also rewrite the way monitor updates are marked completed.
1 parent 88c63e9 commit fe59961

File tree

4 files changed

+155
-62
lines changed

4 files changed

+155
-62
lines changed

lightning/src/ln/chanmon_update_fail_tests.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,7 @@ fn test_monitor_and_persister_update_fail() {
146146
let mut node_0_per_peer_lock;
147147
let mut node_0_peer_state_lock;
148148
let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan.2);
149-
if let Ok(update) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
149+
if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
150150
// Check that even though the persister is returning a InProgress,
151151
// because the update is bogus, ultimately the error that's returned
152152
// should be a PermanentFailure.

lightning/src/ln/channel.rs

Lines changed: 136 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -479,6 +479,16 @@ pub(crate) const MIN_AFFORDABLE_HTLC_COUNT: usize = 4;
479479
/// * `EXPIRE_PREV_CONFIG_TICKS` = convergence_delay / tick_interval
480480
pub(crate) const EXPIRE_PREV_CONFIG_TICKS: usize = 5;
481481

482+
struct PendingChannelMonitorUpdate {
483+
update: ChannelMonitorUpdate,
484+
/// In some cases we need to delay letting the [`ChannelMonitorUpdate`] go until after an
485+
/// `Event` is processed by the user. This bool indicates the [`ChannelMonitorUpdate`] is
486+
/// blocked on some externl event and the [`ChannelManager`] will update us when we're ready.
487+
///
488+
/// [`ChannelManager`]: super::channelmanager::ChannelManager
489+
blocked: bool,
490+
}
491+
482492
// TODO: We should refactor this to be an Inbound/OutboundChannel until initial setup handshaking
483493
// has been completed, and then turn into a Channel to get compiler-time enforcement of things like
484494
// calling channel_id() before we're set up or things like get_outbound_funding_signed on an
@@ -744,7 +754,7 @@ pub(super) struct Channel<Signer: ChannelSigner> {
744754
/// If we then persist the [`channelmanager::ChannelManager`] and crash before the persistence
745755
/// completes we still need to be able to complete the persistence. Thus, we have to keep a
746756
/// copy of the [`ChannelMonitorUpdate`] here until it is complete.
747-
pending_monitor_updates: Vec<ChannelMonitorUpdate>,
757+
pending_monitor_updates: Vec<PendingChannelMonitorUpdate>,
748758
}
749759

750760
#[cfg(any(test, fuzzing))]
@@ -1979,28 +1989,52 @@ impl<Signer: WriteableEcdsaChannelSigner> Channel<Signer> {
19791989
}
19801990

19811991
pub fn get_update_fulfill_htlc_and_commit<L: Deref>(&mut self, htlc_id: u64, payment_preimage: PaymentPreimage, logger: &L) -> UpdateFulfillCommitFetch where L::Target: Logger {
1992+
let release_cs_monitor = self.pending_monitor_updates.iter().all(|upd| !upd.blocked);
19821993
match self.get_update_fulfill_htlc(htlc_id, payment_preimage, logger) {
1983-
UpdateFulfillFetch::NewClaim { mut monitor_update, htlc_value_msat, msg: Some(_) } => {
1984-
let mut additional_update = self.build_commitment_no_status_check(logger);
1985-
// build_commitment_no_status_check may bump latest_monitor_id but we want them to be
1986-
// strictly increasing by one, so decrement it here.
1987-
self.latest_monitor_update_id = monitor_update.update_id;
1988-
monitor_update.updates.append(&mut additional_update.updates);
1989-
self.monitor_updating_paused(false, true, false, Vec::new(), Vec::new(), Vec::new());
1990-
self.pending_monitor_updates.push(monitor_update);
1994+
UpdateFulfillFetch::NewClaim { mut monitor_update, htlc_value_msat, msg } => {
1995+
// Even if we aren't supposed to let new monitor updates with commitment state
1996+
// updates run, we still need to push the preimage ChannelMonitorUpdateStep no
1997+
// matter what. Sadly, to push a new monitor update which flies before others
1998+
// already queued, we have to insert it into the pending queue and update the
1999+
// update_ids of all the following monitors.
2000+
let unblocked_monitor_pos = if release_cs_monitor && msg.is_some() {
2001+
// build_commitment_no_status_check may bump latest_monitor_id but we want them to be
2002+
// strictly increasing by one, so decrement it here.
2003+
let mut additional_update = self.build_commitment_no_status_check(logger);
2004+
self.latest_monitor_update_id = monitor_update.update_id;
2005+
monitor_update.updates.append(&mut additional_update.updates);
2006+
self.pending_monitor_updates.push(PendingChannelMonitorUpdate {
2007+
update: monitor_update, blocked: false,
2008+
});
2009+
self.pending_monitor_updates.len() - 1
2010+
} else {
2011+
let insert_pos = self.pending_monitor_updates.iter().position(|upd| upd.blocked)
2012+
.unwrap_or(self.pending_monitor_updates.len());
2013+
let new_mon_id = self.pending_monitor_updates.get(insert_pos)
2014+
.map(|upd| upd.update.update_id).unwrap_or(monitor_update.update_id);
2015+
monitor_update.update_id = new_mon_id;
2016+
self.pending_monitor_updates.insert(insert_pos, PendingChannelMonitorUpdate {
2017+
update: monitor_update, blocked: false,
2018+
});
2019+
for held_update in self.pending_monitor_updates.iter_mut().skip(insert_pos + 1) {
2020+
held_update.update.update_id += 1;
2021+
}
2022+
if msg.is_some() {
2023+
debug_assert!(false, "If there is a pending blocked monitor we should have MonitorUpdateInProgress set");
2024+
let update = self.build_commitment_no_status_check(logger);
2025+
self.pending_monitor_updates.push(PendingChannelMonitorUpdate {
2026+
update, blocked: true,
2027+
});
2028+
}
2029+
insert_pos
2030+
};
2031+
self.monitor_updating_paused(false, msg.is_some(), false, Vec::new(), Vec::new(), Vec::new());
19912032
UpdateFulfillCommitFetch::NewClaim {
1992-
monitor_update: self.pending_monitor_updates.last().unwrap(),
2033+
monitor_update: &self.pending_monitor_updates.get(unblocked_monitor_pos)
2034+
.expect("We just pushed the monitor update").update,
19932035
htlc_value_msat,
19942036
}
19952037
},
1996-
UpdateFulfillFetch::NewClaim { monitor_update, htlc_value_msat, msg: None } => {
1997-
self.monitor_updating_paused(false, false, false, Vec::new(), Vec::new(), Vec::new());
1998-
self.pending_monitor_updates.push(monitor_update);
1999-
UpdateFulfillCommitFetch::NewClaim {
2000-
monitor_update: self.pending_monitor_updates.last().unwrap(),
2001-
htlc_value_msat,
2002-
}
2003-
}
20042038
UpdateFulfillFetch::DuplicateClaim {} => UpdateFulfillCommitFetch::DuplicateClaim {},
20052039
}
20062040
}
@@ -3068,7 +3102,7 @@ impl<Signer: WriteableEcdsaChannelSigner> Channel<Signer> {
30683102
Ok(())
30693103
}
30703104

3071-
pub fn commitment_signed<L: Deref>(&mut self, msg: &msgs::CommitmentSigned, logger: &L) -> Result<&ChannelMonitorUpdate, ChannelError>
3105+
pub fn commitment_signed<L: Deref>(&mut self, msg: &msgs::CommitmentSigned, logger: &L) -> Result<Option<&ChannelMonitorUpdate>, ChannelError>
30723106
where L::Target: Logger
30733107
{
30743108
if (self.channel_state & (ChannelState::ChannelReady as u32)) != (ChannelState::ChannelReady as u32) {
@@ -3268,8 +3302,11 @@ impl<Signer: WriteableEcdsaChannelSigner> Channel<Signer> {
32683302
}
32693303
log_debug!(logger, "Received valid commitment_signed from peer in channel {}, updated HTLC state but awaiting a monitor update resolution to reply.",
32703304
log_bytes!(self.channel_id));
3271-
self.pending_monitor_updates.push(monitor_update);
3272-
return Ok(self.pending_monitor_updates.last().unwrap());
3305+
let release_monitor = self.pending_monitor_updates.iter().all(|upd| !upd.blocked);
3306+
self.pending_monitor_updates.push(PendingChannelMonitorUpdate {
3307+
update: monitor_update, blocked: !release_monitor
3308+
});
3309+
return Ok(if release_monitor { self.pending_monitor_updates.last().map(|upd| &upd.update) } else { None });
32733310
}
32743311

32753312
let need_commitment_signed = if need_commitment && (self.channel_state & (ChannelState::AwaitingRemoteRevoke as u32)) == 0 {
@@ -3286,9 +3323,12 @@ impl<Signer: WriteableEcdsaChannelSigner> Channel<Signer> {
32863323

32873324
log_debug!(logger, "Received valid commitment_signed from peer in channel {}, updating HTLC state and responding with{} a revoke_and_ack.",
32883325
log_bytes!(self.channel_id()), if need_commitment_signed { " our own commitment_signed and" } else { "" });
3289-
self.pending_monitor_updates.push(monitor_update);
3326+
let release_monitor = self.pending_monitor_updates.iter().all(|upd| !upd.blocked);
3327+
self.pending_monitor_updates.push(PendingChannelMonitorUpdate {
3328+
update: monitor_update, blocked: !release_monitor,
3329+
});
32903330
self.monitor_updating_paused(true, need_commitment_signed, false, Vec::new(), Vec::new(), Vec::new());
3291-
return Ok(self.pending_monitor_updates.last().unwrap());
3331+
return Ok(if release_monitor { self.pending_monitor_updates.last().map(|upd| &upd.update) } else { None });
32923332
}
32933333

32943334
/// Public version of the below, checking relevant preconditions first.
@@ -3403,8 +3443,12 @@ impl<Signer: WriteableEcdsaChannelSigner> Channel<Signer> {
34033443
update_add_htlcs.len(), update_fulfill_htlcs.len(), update_fail_htlcs.len());
34043444

34053445
self.monitor_updating_paused(false, true, false, Vec::new(), Vec::new(), Vec::new());
3406-
self.pending_monitor_updates.push(monitor_update);
3407-
(Some(self.pending_monitor_updates.last().unwrap()), htlcs_to_fail)
3446+
let release_monitor = self.pending_monitor_updates.iter().all(|upd| !upd.blocked);
3447+
self.pending_monitor_updates.push(PendingChannelMonitorUpdate {
3448+
update: monitor_update, blocked: !release_monitor,
3449+
});
3450+
(if release_monitor { self.pending_monitor_updates.last().map(|upd| &upd.update) } else { None },
3451+
htlcs_to_fail)
34083452
} else {
34093453
(None, Vec::new())
34103454
}
@@ -3415,7 +3459,7 @@ impl<Signer: WriteableEcdsaChannelSigner> Channel<Signer> {
34153459
/// waiting on this revoke_and_ack. The generation of this new commitment_signed may also fail,
34163460
/// generating an appropriate error *after* the channel state has been updated based on the
34173461
/// revoke_and_ack message.
3418-
pub fn revoke_and_ack<L: Deref>(&mut self, msg: &msgs::RevokeAndACK, logger: &L) -> Result<(Vec<(HTLCSource, PaymentHash)>, &ChannelMonitorUpdate), ChannelError>
3462+
pub fn revoke_and_ack<L: Deref>(&mut self, msg: &msgs::RevokeAndACK, logger: &L) -> Result<(Vec<(HTLCSource, PaymentHash)>, Option<&ChannelMonitorUpdate>), ChannelError>
34193463
where L::Target: Logger,
34203464
{
34213465
if (self.channel_state & (ChannelState::ChannelReady as u32)) != (ChannelState::ChannelReady as u32) {
@@ -3612,21 +3656,29 @@ impl<Signer: WriteableEcdsaChannelSigner> Channel<Signer> {
36123656
self.monitor_pending_failures.append(&mut revoked_htlcs);
36133657
self.monitor_pending_finalized_fulfills.append(&mut finalized_claimed_htlcs);
36143658
log_debug!(logger, "Received a valid revoke_and_ack for channel {} but awaiting a monitor update resolution to reply.", log_bytes!(self.channel_id()));
3615-
self.pending_monitor_updates.push(monitor_update);
3616-
return Ok((Vec::new(), self.pending_monitor_updates.last().unwrap()));
3659+
let release_monitor = self.pending_monitor_updates.iter().all(|upd| !upd.blocked);
3660+
self.pending_monitor_updates.push(PendingChannelMonitorUpdate {
3661+
update: monitor_update, blocked: !release_monitor,
3662+
});
3663+
return Ok((Vec::new(),
3664+
if release_monitor { self.pending_monitor_updates.last().map(|upd| &upd.update) } else { None }));
36173665
}
36183666

36193667
match self.free_holding_cell_htlcs(logger) {
36203668
(Some(_), htlcs_to_fail) => {
3621-
let mut additional_update = self.pending_monitor_updates.pop().unwrap();
3669+
let mut additional_update = self.pending_monitor_updates.pop().unwrap().update;
36223670
// free_holding_cell_htlcs may bump latest_monitor_id multiple times but we want them to be
36233671
// strictly increasing by one, so decrement it here.
36243672
self.latest_monitor_update_id = monitor_update.update_id;
36253673
monitor_update.updates.append(&mut additional_update.updates);
36263674

36273675
self.monitor_updating_paused(false, true, false, to_forward_infos, revoked_htlcs, finalized_claimed_htlcs);
3628-
self.pending_monitor_updates.push(monitor_update);
3629-
Ok((htlcs_to_fail, self.pending_monitor_updates.last().unwrap()))
3676+
let release_monitor = self.pending_monitor_updates.iter().all(|upd| !upd.blocked);
3677+
self.pending_monitor_updates.push(PendingChannelMonitorUpdate {
3678+
update: monitor_update, blocked: !release_monitor,
3679+
});
3680+
Ok((htlcs_to_fail,
3681+
if release_monitor { self.pending_monitor_updates.last().map(|upd| &upd.update) } else { None }))
36303682
},
36313683
(None, htlcs_to_fail) => {
36323684
if require_commitment {
@@ -3640,13 +3692,21 @@ impl<Signer: WriteableEcdsaChannelSigner> Channel<Signer> {
36403692
log_debug!(logger, "Received a valid revoke_and_ack for channel {}. Responding with a commitment update with {} HTLCs failed.",
36413693
log_bytes!(self.channel_id()), update_fail_htlcs.len() + update_fail_malformed_htlcs.len());
36423694
self.monitor_updating_paused(false, true, false, to_forward_infos, revoked_htlcs, finalized_claimed_htlcs);
3643-
self.pending_monitor_updates.push(monitor_update);
3644-
Ok((htlcs_to_fail, self.pending_monitor_updates.last().unwrap()))
3695+
let release_monitor = self.pending_monitor_updates.iter().all(|upd| !upd.blocked);
3696+
self.pending_monitor_updates.push(PendingChannelMonitorUpdate {
3697+
update: monitor_update, blocked: !release_monitor,
3698+
});
3699+
Ok((htlcs_to_fail,
3700+
if release_monitor { self.pending_monitor_updates.last().map(|upd| &upd.update) } else { None }))
36453701
} else {
36463702
log_debug!(logger, "Received a valid revoke_and_ack for channel {} with no reply necessary.", log_bytes!(self.channel_id()));
36473703
self.monitor_updating_paused(false, false, false, to_forward_infos, revoked_htlcs, finalized_claimed_htlcs);
3648-
self.pending_monitor_updates.push(monitor_update);
3649-
Ok((htlcs_to_fail, self.pending_monitor_updates.last().unwrap()))
3704+
let release_monitor = self.pending_monitor_updates.iter().all(|upd| !upd.blocked);
3705+
self.pending_monitor_updates.push(PendingChannelMonitorUpdate {
3706+
update: monitor_update, blocked: !release_monitor,
3707+
});
3708+
Ok((htlcs_to_fail,
3709+
if release_monitor { self.pending_monitor_updates.last().map(|upd| &upd.update) } else { None }))
36503710
}
36513711
}
36523712
}
@@ -3835,7 +3895,12 @@ impl<Signer: WriteableEcdsaChannelSigner> Channel<Signer> {
38353895
{
38363896
assert_eq!(self.channel_state & ChannelState::MonitorUpdateInProgress as u32, ChannelState::MonitorUpdateInProgress as u32);
38373897
self.channel_state &= !(ChannelState::MonitorUpdateInProgress as u32);
3838-
self.pending_monitor_updates.clear();
3898+
let mut found_blocked = false;
3899+
self.pending_monitor_updates.retain(|upd| {
3900+
if found_blocked { debug_assert!(upd.blocked, "No mons may be unblocked after a blocked one"); }
3901+
if upd.blocked { found_blocked = true; }
3902+
upd.blocked
3903+
});
38393904

38403905
// If we're past (or at) the FundingSent stage on an outbound channel, try to
38413906
// (re-)broadcast the funding transaction as we may have declined to broadcast it when we
@@ -4378,8 +4443,11 @@ impl<Signer: WriteableEcdsaChannelSigner> Channel<Signer> {
43784443
}],
43794444
};
43804445
self.monitor_updating_paused(false, false, false, Vec::new(), Vec::new(), Vec::new());
4381-
self.pending_monitor_updates.push(monitor_update);
4382-
Some(self.pending_monitor_updates.last().unwrap())
4446+
let release_monitor = self.pending_monitor_updates.iter().all(|upd| !upd.blocked);
4447+
self.pending_monitor_updates.push(PendingChannelMonitorUpdate {
4448+
update: monitor_update, blocked: !release_monitor,
4449+
});
4450+
if release_monitor { self.pending_monitor_updates.last().map(|upd| &upd.update) } else { None }
43834451
} else { None };
43844452
let shutdown = if send_shutdown {
43854453
Some(msgs::Shutdown {
@@ -4951,8 +5019,25 @@ impl<Signer: WriteableEcdsaChannelSigner> Channel<Signer> {
49515019
(self.channel_state & ChannelState::MonitorUpdateInProgress as u32) != 0
49525020
}
49535021

4954-
pub fn get_next_monitor_update(&self) -> Option<&ChannelMonitorUpdate> {
4955-
self.pending_monitor_updates.first()
5022+
/// Returns the next blocked monitor update, if one exists, and a bool which indicates a
5023+
/// further blocked monitor update exists after the next.
5024+
pub fn unblock_next_blocked_monitor_update(&mut self) -> Option<(&ChannelMonitorUpdate, bool)> {
5025+
for i in 0..self.pending_monitor_updates.len() {
5026+
if self.pending_monitor_updates[i].blocked {
5027+
self.pending_monitor_updates[i].blocked = false;
5028+
return Some((&self.pending_monitor_updates[i].update,
5029+
self.pending_monitor_updates.len() > i + 1));
5030+
}
5031+
}
5032+
None
5033+
}
5034+
5035+
pub fn no_monitor_updates_pending(&self) -> bool {
5036+
self.pending_monitor_updates.is_empty()
5037+
}
5038+
5039+
pub fn complete_one_mon_update(&mut self, update_id: u64) {
5040+
self.pending_monitor_updates.retain(|upd| upd.update.update_id != update_id);
49565041
}
49575042

49585043
/// Returns true if funding_created was sent/received.
@@ -6000,8 +6085,12 @@ impl<Signer: WriteableEcdsaChannelSigner> Channel<Signer> {
60006085
Some(_) => {
60016086
let monitor_update = self.build_commitment_no_status_check(logger);
60026087
self.monitor_updating_paused(false, true, false, Vec::new(), Vec::new(), Vec::new());
6003-
self.pending_monitor_updates.push(monitor_update);
6004-
Ok(Some(self.pending_monitor_updates.last().unwrap()))
6088+
6089+
let release_monitor = self.pending_monitor_updates.iter().all(|upd| !upd.blocked);
6090+
self.pending_monitor_updates.push(PendingChannelMonitorUpdate {
6091+
update: monitor_update, blocked: !release_monitor,
6092+
});
6093+
Ok(if release_monitor { self.pending_monitor_updates.last().map(|upd| &upd.update) } else { None })
60056094
},
60066095
None => Ok(None)
60076096
}
@@ -6090,8 +6179,11 @@ impl<Signer: WriteableEcdsaChannelSigner> Channel<Signer> {
60906179
}],
60916180
};
60926181
self.monitor_updating_paused(false, false, false, Vec::new(), Vec::new(), Vec::new());
6093-
self.pending_monitor_updates.push(monitor_update);
6094-
Some(self.pending_monitor_updates.last().unwrap())
6182+
let release_monitor = self.pending_monitor_updates.iter().all(|upd| !upd.blocked);
6183+
self.pending_monitor_updates.push(PendingChannelMonitorUpdate {
6184+
update: monitor_update, blocked: !release_monitor,
6185+
});
6186+
if release_monitor { self.pending_monitor_updates.last().map(|upd| &upd.update) } else { None }
60956187
} else { None };
60966188
let shutdown = msgs::Shutdown {
60976189
channel_id: self.channel_id,

0 commit comments

Comments
 (0)