Skip to content

Commit 3f15d84

Browse files
committed
Add infra to block ChannelMonitorUpdates on forwarded claims
When we forward a payment and receive an `update_fulfill_htlc` message from the downstream channel, we immediately claim the HTLC on the upstream channel, before even doing a `commitment_signed` dance on the downstream channel. This implies that our `ChannelMonitorUpdate`s "go out" in the right order - first we ensure we'll get our money by writing the preimage down, then we write the update that resolves giving money on the downstream node. This is safe as long as `ChannelMonitorUpdate`s complete in the order in which they are generated, but of course looking forward we want to support asynchronous updates, which may complete in any order. Here we add infrastructure to handle downstream `ChannelMonitorUpdate`s which are blocked on an upstream preimage-containing one. We don't yet actually do the blocking which will come in a future commit.
1 parent bbf9e4e commit 3f15d84

File tree

1 file changed

+122
-23
lines changed

1 file changed

+122
-23
lines changed

lightning/src/ln/channelmanager.rs

+122-23
Original file line numberDiff line numberDiff line change
@@ -504,12 +504,24 @@ pub(crate) enum MonitorUpdateCompletionAction {
504504
/// event can be generated.
505505
PaymentClaimed { payment_hash: PaymentHash },
506506
/// Indicates an [`events::Event`] should be surfaced to the user.
507-
EmitEvent { event: events::Event },
507+
EmitEventAndFreeOtherChannel {
508+
event: events::Event,
509+
downstream_counterparty_and_funding_outpoint: Option<(PublicKey, OutPoint, RAAMonitorUpdateBlockingAction)>,
510+
},
508511
}
509512

510513
impl_writeable_tlv_based_enum_upgradable!(MonitorUpdateCompletionAction,
511514
(0, PaymentClaimed) => { (0, payment_hash, required) },
512-
(2, EmitEvent) => { (0, event, upgradable_required) },
515+
(2, EmitEventAndFreeOtherChannel) => {
516+
(0, event, upgradable_required),
517+
// LDK prior to 0.0.115 did not have this field as the monitor update application order was
518+
// required by clients. If we downgrade to something prior to 0.0.115 this may result in
519+
// monitor updates which aren't properly blocked or resumed, however that's fine - we don't
520+
// support async monitor updates even in LDK 0.0.115 and once we do we'll require no
521+
// downgrades to prior versions. Thus, while this would break on downgrade, we don't
522+
// support it even without downgrade, so if it breaks its not on us ¯\_(ツ)_/¯.
523+
(1, downstream_counterparty_and_funding_outpoint, option),
524+
},
513525
);
514526

515527
#[derive(Clone, Debug, PartialEq, Eq)]
@@ -526,6 +538,29 @@ impl_writeable_tlv_based_enum!(EventCompletionAction,
526538
};
527539
);
528540

541+
#[derive(Clone, PartialEq, Eq, Debug)]
542+
pub(crate) enum RAAMonitorUpdateBlockingAction {
543+
/// The inbound channel's channel_id
544+
ForwardedPaymentOtherChannelClaim {
545+
channel_id: [u8; 32],
546+
htlc_id: u64,
547+
},
548+
}
549+
550+
impl RAAMonitorUpdateBlockingAction {
551+
fn from_prev_hop_data(prev_hop: &HTLCPreviousHopData) -> Self {
552+
Self::ForwardedPaymentOtherChannelClaim {
553+
channel_id: prev_hop.outpoint.to_channel_id(),
554+
htlc_id: prev_hop.htlc_id,
555+
}
556+
}
557+
}
558+
559+
impl_writeable_tlv_based_enum!(RAAMonitorUpdateBlockingAction,
560+
(0, ForwardedPaymentOtherChannelClaim) => { (0, channel_id, required), (2, htlc_id, required) }
561+
;);
562+
563+
529564
/// State we hold per-peer.
530565
pub(super) struct PeerState<Signer: ChannelSigner> {
531566
/// `temporary_channel_id` or `channel_id` -> `channel`.
@@ -554,6 +589,11 @@ pub(super) struct PeerState<Signer: ChannelSigner> {
554589
/// to funding appearing on-chain), the downstream `ChannelMonitor` set is required to ensure
555590
/// duplicates do not occur, so such channels should fail without a monitor update completing.
556591
monitor_update_blocked_actions: BTreeMap<[u8; 32], Vec<MonitorUpdateCompletionAction>>,
592+
/// If another channel's [`ChannelMonitorUpdate`] needs to complete before a channel we have
593+
/// with this peer can complete an RAA [`ChannelMonitorUpdate`] (e.g. because the RAA update
594+
/// will remove a preimage that needs to be durably in an upstream channel first), we put an
595+
/// entry here to note that the channel with the key's ID is blocked on a set of actions.
596+
actions_blocking_raa_monitor_updates: BTreeMap<[u8; 32], Vec<RAAMonitorUpdateBlockingAction>>,
557597
/// The peer is currently connected (i.e. we've seen a
558598
/// [`ChannelMessageHandler::peer_connected`] and no corresponding
559599
/// [`ChannelMessageHandler::peer_disconnected`].
@@ -4397,20 +4437,24 @@ where
43974437
},
43984438
HTLCSource::PreviousHopData(hop_data) => {
43994439
let prev_outpoint = hop_data.outpoint;
4440+
let completed_blocker = RAAMonitorUpdateBlockingAction::from_prev_hop_data(&hop_data);
44004441
let res = self.claim_funds_from_hop(hop_data, payment_preimage,
44014442
|htlc_claim_value_msat| {
44024443
if let Some(forwarded_htlc_value) = forwarded_htlc_value_msat {
44034444
let fee_earned_msat = if let Some(claimed_htlc_value) = htlc_claim_value_msat {
44044445
Some(claimed_htlc_value - forwarded_htlc_value)
44054446
} else { None };
44064447

4407-
Some(MonitorUpdateCompletionAction::EmitEvent { event: events::Event::PaymentForwarded {
4408-
fee_earned_msat,
4409-
claim_from_onchain_tx: from_onchain,
4410-
prev_channel_id: Some(prev_outpoint.to_channel_id()),
4411-
next_channel_id: Some(next_channel_outpoint.to_channel_id()),
4412-
outbound_amount_forwarded_msat: forwarded_htlc_value_msat,
4413-
}})
4448+
Some(MonitorUpdateCompletionAction::EmitEventAndFreeOtherChannel {
4449+
event: events::Event::PaymentForwarded {
4450+
fee_earned_msat,
4451+
claim_from_onchain_tx: from_onchain,
4452+
prev_channel_id: Some(prev_outpoint.to_channel_id()),
4453+
next_channel_id: Some(next_channel_outpoint.to_channel_id()),
4454+
outbound_amount_forwarded_msat: forwarded_htlc_value_msat,
4455+
},
4456+
downstream_counterparty_and_funding_outpoint: None,
4457+
})
44144458
} else { None }
44154459
});
44164460
if let Err((pk, err)) = res {
@@ -4437,8 +4481,13 @@ where
44374481
}, None));
44384482
}
44394483
},
4440-
MonitorUpdateCompletionAction::EmitEvent { event } => {
4484+
MonitorUpdateCompletionAction::EmitEventAndFreeOtherChannel {
4485+
event, downstream_counterparty_and_funding_outpoint
4486+
} => {
44414487
self.pending_events.lock().unwrap().push_back((event, None));
4488+
if let Some((node_id, funding_outpoint, blocker)) = downstream_counterparty_and_funding_outpoint {
4489+
self.handle_monitor_update_release(node_id, funding_outpoint, Some(blocker));
4490+
}
44424491
},
44434492
}
44444493
}
@@ -5288,6 +5337,36 @@ where
52885337
}
52895338
}
52905339

5340+
fn raa_monitor_updates_held(&self,
5341+
actions_blocking_raa_monitor_updates: &BTreeMap<[u8; 32], Vec<RAAMonitorUpdateBlockingAction>>,
5342+
channel_funding_outpoint: OutPoint, counterparty_node_id: PublicKey
5343+
) -> bool {
5344+
actions_blocking_raa_monitor_updates
5345+
.get(&channel_funding_outpoint.to_channel_id()).map(|v| !v.is_empty()).unwrap_or(false)
5346+
|| self.pending_events.lock().unwrap().iter().any(|(_, action)| {
5347+
action == &Some(EventCompletionAction::ReleaseRAAChannelMonitorUpdate {
5348+
channel_funding_outpoint,
5349+
counterparty_node_id,
5350+
})
5351+
})
5352+
}
5353+
5354+
pub(crate) fn test_raa_monitor_updates_held(&self, counterparty_node_id: PublicKey,
5355+
channel_id: [u8; 32])
5356+
-> bool {
5357+
let per_peer_state = self.per_peer_state.read().unwrap();
5358+
if let Some(peer_state_mtx) = per_peer_state.get(&counterparty_node_id) {
5359+
let mut peer_state_lck = peer_state_mtx.lock().unwrap();
5360+
let peer_state = &mut *peer_state_lck;
5361+
5362+
if let Some(chan) = peer_state.channel_by_id.get(&channel_id) {
5363+
return self.raa_monitor_updates_held(&peer_state.actions_blocking_raa_monitor_updates,
5364+
chan.get_funding_txo().unwrap(), counterparty_node_id);
5365+
}
5366+
}
5367+
false
5368+
}
5369+
52915370
fn internal_revoke_and_ack(&self, counterparty_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), MsgHandleErrInternal> {
52925371
let (htlcs_to_fail, res) = {
52935372
let per_peer_state = self.per_peer_state.read().unwrap();
@@ -5957,24 +6036,28 @@ where
59576036
self.pending_outbound_payments.clear_pending_payments()
59586037
}
59596038

5960-
fn handle_monitor_update_release(&self, counterparty_node_id: PublicKey, channel_funding_outpoint: OutPoint) {
6039+
fn handle_monitor_update_release(&self, counterparty_node_id: PublicKey, channel_funding_outpoint: OutPoint, completed_blocker: Option<RAAMonitorUpdateBlockingAction>) {
59616040
loop {
59626041
let per_peer_state = self.per_peer_state.read().unwrap();
59636042
if let Some(peer_state_mtx) = per_peer_state.get(&counterparty_node_id) {
59646043
let mut peer_state_lck = peer_state_mtx.lock().unwrap();
59656044
let peer_state = &mut *peer_state_lck;
5966-
if self.pending_events.lock().unwrap().iter()
5967-
.any(|(_ev, action_opt)| action_opt == &Some(EventCompletionAction::ReleaseRAAChannelMonitorUpdate {
5968-
channel_funding_outpoint, counterparty_node_id
5969-
}))
5970-
{
5971-
// Check that, while holding the peer lock, we don't have another event
5972-
// blocking any monitor updates for this channel. If we do, let those
5973-
// events be the ones that ultimately release the monitor update(s).
5974-
log_trace!(self.logger, "Delaying monitor unlock for channel {} as another event is pending",
6045+
6046+
if let Some(blocker) = &completed_blocker {
6047+
if let Some(blockers) = peer_state.actions_blocking_raa_monitor_updates
6048+
.get_mut(&channel_funding_outpoint.to_channel_id())
6049+
{
6050+
blockers.retain(|iter| iter != blocker);
6051+
}
6052+
}
6053+
6054+
if self.raa_monitor_updates_held(&peer_state.actions_blocking_raa_monitor_updates,
6055+
channel_funding_outpoint, counterparty_node_id) {
6056+
log_trace!(self.logger, "Delaying monitor unlock for channel {} as another channel's mon update needs to complete first",
59756057
log_bytes!(&channel_funding_outpoint.to_channel_id()[..]));
59766058
return;
59776059
}
6060+
59786061
if let hash_map::Entry::Occupied(mut chan) = peer_state.channel_by_id.entry(channel_funding_outpoint.to_channel_id()) {
59796062
debug_assert_eq!(chan.get().get_funding_txo().unwrap(), channel_funding_outpoint);
59806063
if let Some((monitor_update, further_update_exists)) = chan.get_mut().unblock_next_blocked_monitor_update() {
@@ -6011,7 +6094,7 @@ where
60116094
EventCompletionAction::ReleaseRAAChannelMonitorUpdate {
60126095
channel_funding_outpoint, counterparty_node_id
60136096
} => {
6014-
self.handle_monitor_update_release(counterparty_node_id, channel_funding_outpoint);
6097+
self.handle_monitor_update_release(counterparty_node_id, channel_funding_outpoint, None);
60156098
}
60166099
}
60176100
}
@@ -6662,6 +6745,7 @@ where
66626745
latest_features: init_msg.features.clone(),
66636746
pending_msg_events: Vec::new(),
66646747
monitor_update_blocked_actions: BTreeMap::new(),
6748+
actions_blocking_raa_monitor_updates: BTreeMap::new(),
66656749
is_connected: true,
66666750
}));
66676751
},
@@ -7788,6 +7872,7 @@ where
77887872
latest_features: Readable::read(reader)?,
77897873
pending_msg_events: Vec::new(),
77907874
monitor_update_blocked_actions: BTreeMap::new(),
7875+
actions_blocking_raa_monitor_updates: BTreeMap::new(),
77917876
is_connected: false,
77927877
};
77937878
per_peer_state.insert(peer_pubkey, Mutex::new(peer_state));
@@ -7870,7 +7955,7 @@ where
78707955
let mut probing_cookie_secret: Option<[u8; 32]> = None;
78717956
let mut claimable_htlc_purposes = None;
78727957
let mut pending_claiming_payments = Some(HashMap::new());
7873-
let mut monitor_update_blocked_actions_per_peer = Some(Vec::new());
7958+
let mut monitor_update_blocked_actions_per_peer: Option<Vec<(_, BTreeMap<_, Vec<_>>)>> = Some(Vec::new());
78747959
let mut events_override = None;
78757960
read_tlv_fields!(reader, {
78767961
(1, pending_outbound_payments_no_retry, option),
@@ -8180,7 +8265,21 @@ where
81808265
}
81818266

81828267
for (node_id, monitor_update_blocked_actions) in monitor_update_blocked_actions_per_peer.unwrap() {
8183-
if let Some(peer_state) = per_peer_state.get_mut(&node_id) {
8268+
if let Some(peer_state) = per_peer_state.get(&node_id) {
8269+
for (_, actions) in monitor_update_blocked_actions.iter() {
8270+
for action in actions.iter() {
8271+
if let MonitorUpdateCompletionAction::EmitEventAndFreeOtherChannel {
8272+
downstream_counterparty_and_funding_outpoint:
8273+
Some((blocked_node_id, blocked_channel_outpoint, blocking_action)), ..
8274+
} = action {
8275+
if let Some(blocked_peer_state) = per_peer_state.get(&blocked_node_id) {
8276+
blocked_peer_state.lock().unwrap().actions_blocking_raa_monitor_updates
8277+
.entry(blocked_channel_outpoint.to_channel_id())
8278+
.or_insert_with(Vec::new).push(blocking_action.clone());
8279+
}
8280+
}
8281+
}
8282+
}
81848283
peer_state.lock().unwrap().monitor_update_blocked_actions = monitor_update_blocked_actions;
81858284
} else {
81868285
log_error!(args.logger, "Got blocked actions without a per-peer-state for {}", node_id);

0 commit comments

Comments
 (0)