Skip to content

Commit e634382

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 4054bc4 commit e634382

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))]
@@ -1977,28 +1987,52 @@ impl<Signer: WriteableEcdsaChannelSigner> Channel<Signer> {
19771987
}
19781988

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

3069-
pub fn commitment_signed<L: Deref>(&mut self, msg: &msgs::CommitmentSigned, logger: &L) -> Result<&ChannelMonitorUpdate, ChannelError>
3103+
pub fn commitment_signed<L: Deref>(&mut self, msg: &msgs::CommitmentSigned, logger: &L) -> Result<Option<&ChannelMonitorUpdate>, ChannelError>
30703104
where L::Target: Logger
30713105
{
30723106
if (self.channel_state & (ChannelState::ChannelReady as u32)) != (ChannelState::ChannelReady as u32) {
@@ -3266,8 +3300,11 @@ impl<Signer: WriteableEcdsaChannelSigner> Channel<Signer> {
32663300
}
32673301
log_debug!(logger, "Received valid commitment_signed from peer in channel {}, updated HTLC state but awaiting a monitor update resolution to reply.",
32683302
log_bytes!(self.channel_id));
3269-
self.pending_monitor_updates.push(monitor_update);
3270-
return Ok(self.pending_monitor_updates.last().unwrap());
3303+
let release_monitor = self.pending_monitor_updates.iter().all(|upd| !upd.blocked);
3304+
self.pending_monitor_updates.push(PendingChannelMonitorUpdate {
3305+
update: monitor_update, blocked: !release_monitor
3306+
});
3307+
return Ok(if release_monitor { self.pending_monitor_updates.last().map(|upd| &upd.update) } else { None });
32713308
}
32723309

32733310
let need_commitment_signed = if need_commitment && (self.channel_state & (ChannelState::AwaitingRemoteRevoke as u32)) == 0 {
@@ -3284,9 +3321,12 @@ impl<Signer: WriteableEcdsaChannelSigner> Channel<Signer> {
32843321

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

32923332
/// Public version of the below, checking relevant preconditions first.
@@ -3401,8 +3441,12 @@ impl<Signer: WriteableEcdsaChannelSigner> Channel<Signer> {
34013441
update_add_htlcs.len(), update_fulfill_htlcs.len(), update_fail_htlcs.len());
34023442

34033443
self.monitor_updating_paused(false, true, false, Vec::new(), Vec::new(), Vec::new());
3404-
self.pending_monitor_updates.push(monitor_update);
3405-
(Some(self.pending_monitor_updates.last().unwrap()), htlcs_to_fail)
3444+
let release_monitor = self.pending_monitor_updates.iter().all(|upd| !upd.blocked);
3445+
self.pending_monitor_updates.push(PendingChannelMonitorUpdate {
3446+
update: monitor_update, blocked: !release_monitor,
3447+
});
3448+
(if release_monitor { self.pending_monitor_updates.last().map(|upd| &upd.update) } else { None },
3449+
htlcs_to_fail)
34063450
} else {
34073451
(None, Vec::new())
34083452
}
@@ -3413,7 +3457,7 @@ impl<Signer: WriteableEcdsaChannelSigner> Channel<Signer> {
34133457
/// waiting on this revoke_and_ack. The generation of this new commitment_signed may also fail,
34143458
/// generating an appropriate error *after* the channel state has been updated based on the
34153459
/// revoke_and_ack message.
3416-
pub fn revoke_and_ack<L: Deref>(&mut self, msg: &msgs::RevokeAndACK, logger: &L) -> Result<(Vec<(HTLCSource, PaymentHash)>, &ChannelMonitorUpdate), ChannelError>
3460+
pub fn revoke_and_ack<L: Deref>(&mut self, msg: &msgs::RevokeAndACK, logger: &L) -> Result<(Vec<(HTLCSource, PaymentHash)>, Option<&ChannelMonitorUpdate>), ChannelError>
34173461
where L::Target: Logger,
34183462
{
34193463
if (self.channel_state & (ChannelState::ChannelReady as u32)) != (ChannelState::ChannelReady as u32) {
@@ -3610,21 +3654,29 @@ impl<Signer: WriteableEcdsaChannelSigner> Channel<Signer> {
36103654
self.monitor_pending_failures.append(&mut revoked_htlcs);
36113655
self.monitor_pending_finalized_fulfills.append(&mut finalized_claimed_htlcs);
36123656
log_debug!(logger, "Received a valid revoke_and_ack for channel {} but awaiting a monitor update resolution to reply.", log_bytes!(self.channel_id()));
3613-
self.pending_monitor_updates.push(monitor_update);
3614-
return Ok((Vec::new(), self.pending_monitor_updates.last().unwrap()));
3657+
let release_monitor = self.pending_monitor_updates.iter().all(|upd| !upd.blocked);
3658+
self.pending_monitor_updates.push(PendingChannelMonitorUpdate {
3659+
update: monitor_update, blocked: !release_monitor,
3660+
});
3661+
return Ok((Vec::new(),
3662+
if release_monitor { self.pending_monitor_updates.last().map(|upd| &upd.update) } else { None }));
36153663
}
36163664

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

36253673
self.monitor_updating_paused(false, true, false, to_forward_infos, revoked_htlcs, finalized_claimed_htlcs);
3626-
self.pending_monitor_updates.push(monitor_update);
3627-
Ok((htlcs_to_fail, self.pending_monitor_updates.last().unwrap()))
3674+
let release_monitor = self.pending_monitor_updates.iter().all(|upd| !upd.blocked);
3675+
self.pending_monitor_updates.push(PendingChannelMonitorUpdate {
3676+
update: monitor_update, blocked: !release_monitor,
3677+
});
3678+
Ok((htlcs_to_fail,
3679+
if release_monitor { self.pending_monitor_updates.last().map(|upd| &upd.update) } else { None }))
36283680
},
36293681
(None, htlcs_to_fail) => {
36303682
if require_commitment {
@@ -3638,13 +3690,21 @@ impl<Signer: WriteableEcdsaChannelSigner> Channel<Signer> {
36383690
log_debug!(logger, "Received a valid revoke_and_ack for channel {}. Responding with a commitment update with {} HTLCs failed.",
36393691
log_bytes!(self.channel_id()), update_fail_htlcs.len() + update_fail_malformed_htlcs.len());
36403692
self.monitor_updating_paused(false, true, false, to_forward_infos, revoked_htlcs, finalized_claimed_htlcs);
3641-
self.pending_monitor_updates.push(monitor_update);
3642-
Ok((htlcs_to_fail, self.pending_monitor_updates.last().unwrap()))
3693+
let release_monitor = self.pending_monitor_updates.iter().all(|upd| !upd.blocked);
3694+
self.pending_monitor_updates.push(PendingChannelMonitorUpdate {
3695+
update: monitor_update, blocked: !release_monitor,
3696+
});
3697+
Ok((htlcs_to_fail,
3698+
if release_monitor { self.pending_monitor_updates.last().map(|upd| &upd.update) } else { None }))
36433699
} else {
36443700
log_debug!(logger, "Received a valid revoke_and_ack for channel {} with no reply necessary.", log_bytes!(self.channel_id()));
36453701
self.monitor_updating_paused(false, false, false, to_forward_infos, revoked_htlcs, finalized_claimed_htlcs);
3646-
self.pending_monitor_updates.push(monitor_update);
3647-
Ok((htlcs_to_fail, self.pending_monitor_updates.last().unwrap()))
3702+
let release_monitor = self.pending_monitor_updates.iter().all(|upd| !upd.blocked);
3703+
self.pending_monitor_updates.push(PendingChannelMonitorUpdate {
3704+
update: monitor_update, blocked: !release_monitor,
3705+
});
3706+
Ok((htlcs_to_fail,
3707+
if release_monitor { self.pending_monitor_updates.last().map(|upd| &upd.update) } else { None }))
36483708
}
36493709
}
36503710
}
@@ -3833,7 +3893,12 @@ impl<Signer: WriteableEcdsaChannelSigner> Channel<Signer> {
38333893
{
38343894
assert_eq!(self.channel_state & ChannelState::MonitorUpdateInProgress as u32, ChannelState::MonitorUpdateInProgress as u32);
38353895
self.channel_state &= !(ChannelState::MonitorUpdateInProgress as u32);
3836-
self.pending_monitor_updates.clear();
3896+
let mut found_blocked = false;
3897+
self.pending_monitor_updates.retain(|upd| {
3898+
if found_blocked { debug_assert!(upd.blocked, "No mons may be unblocked after a blocked one"); }
3899+
if upd.blocked { found_blocked = true; }
3900+
upd.blocked
3901+
});
38373902

38383903
// If we're past (or at) the FundingSent stage on an outbound channel, try to
38393904
// (re-)broadcast the funding transaction as we may have declined to broadcast it when we
@@ -4376,8 +4441,11 @@ impl<Signer: WriteableEcdsaChannelSigner> Channel<Signer> {
43764441
}],
43774442
};
43784443
self.monitor_updating_paused(false, false, false, Vec::new(), Vec::new(), Vec::new());
4379-
self.pending_monitor_updates.push(monitor_update);
4380-
Some(self.pending_monitor_updates.last().unwrap())
4444+
let release_monitor = self.pending_monitor_updates.iter().all(|upd| !upd.blocked);
4445+
self.pending_monitor_updates.push(PendingChannelMonitorUpdate {
4446+
update: monitor_update, blocked: !release_monitor,
4447+
});
4448+
if release_monitor { self.pending_monitor_updates.last().map(|upd| &upd.update) } else { None }
43814449
} else { None };
43824450
let shutdown = if send_shutdown {
43834451
Some(msgs::Shutdown {
@@ -4949,8 +5017,25 @@ impl<Signer: WriteableEcdsaChannelSigner> Channel<Signer> {
49495017
(self.channel_state & ChannelState::MonitorUpdateInProgress as u32) != 0
49505018
}
49515019

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

49565041
/// Returns true if funding_created was sent/received.
@@ -5998,8 +6083,12 @@ impl<Signer: WriteableEcdsaChannelSigner> Channel<Signer> {
59986083
Some(_) => {
59996084
let monitor_update = self.build_commitment_no_status_check(logger);
60006085
self.monitor_updating_paused(false, true, false, Vec::new(), Vec::new(), Vec::new());
6001-
self.pending_monitor_updates.push(monitor_update);
6002-
Ok(Some(self.pending_monitor_updates.last().unwrap()))
6086+
6087+
let release_monitor = self.pending_monitor_updates.iter().all(|upd| !upd.blocked);
6088+
self.pending_monitor_updates.push(PendingChannelMonitorUpdate {
6089+
update: monitor_update, blocked: !release_monitor,
6090+
});
6091+
Ok(if release_monitor { self.pending_monitor_updates.last().map(|upd| &upd.update) } else { None })
60036092
},
60046093
None => Ok(None)
60056094
}
@@ -6088,8 +6177,11 @@ impl<Signer: WriteableEcdsaChannelSigner> Channel<Signer> {
60886177
}],
60896178
};
60906179
self.monitor_updating_paused(false, false, false, Vec::new(), Vec::new(), Vec::new());
6091-
self.pending_monitor_updates.push(monitor_update);
6092-
Some(self.pending_monitor_updates.last().unwrap())
6180+
let release_monitor = self.pending_monitor_updates.iter().all(|upd| !upd.blocked);
6181+
self.pending_monitor_updates.push(PendingChannelMonitorUpdate {
6182+
update: monitor_update, blocked: !release_monitor,
6183+
});
6184+
if release_monitor { self.pending_monitor_updates.last().map(|upd| &upd.update) } else { None }
60936185
} else { None };
60946186
let shutdown = msgs::Shutdown {
60956187
channel_id: self.channel_id,

0 commit comments

Comments
 (0)