Skip to content

Commit 8624570

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 2aa91ff commit 8624570

File tree

1 file changed

+122
-26
lines changed

1 file changed

+122
-26
lines changed

lightning/src/ln/channelmanager.rs

+122-26
Original file line numberDiff line numberDiff line change
@@ -520,12 +520,24 @@ pub(crate) enum MonitorUpdateCompletionAction {
520520
/// event can be generated.
521521
PaymentClaimed { payment_hash: PaymentHash },
522522
/// Indicates an [`events::Event`] should be surfaced to the user.
523-
EmitEvent { event: events::Event },
523+
EmitEventAndFreeOtherChannel {
524+
event: events::Event,
525+
downstream_counterparty_and_funding_outpoint: Option<(PublicKey, OutPoint, RAAMonitorUpdateBlockingAction)>,
526+
},
524527
}
525528

526529
impl_writeable_tlv_based_enum_upgradable!(MonitorUpdateCompletionAction,
527530
(0, PaymentClaimed) => { (0, payment_hash, required) },
528-
(2, EmitEvent) => { (0, event, upgradable_required) },
531+
(2, EmitEventAndFreeOtherChannel) => {
532+
(0, event, upgradable_required),
533+
// LDK prior to 0.0.115 did not have this field as the monitor update application order was
534+
// required by clients. If we downgrade to something prior to 0.0.115 this may result in
535+
// monitor updates which aren't properly blocked or resumed, however that's fine - we don't
536+
// support async monitor updates even in LDK 0.0.115 and once we do we'll require no
537+
// downgrades to prior versions. Thus, while this would break on downgrade, we don't
538+
// support it even without downgrade, so if it breaks its not on us ¯\_(ツ)_/¯.
539+
(1, downstream_counterparty_and_funding_outpoint, option),
540+
},
529541
);
530542

531543
#[derive(Clone, Debug, PartialEq, Eq)]
@@ -542,6 +554,29 @@ impl_writeable_tlv_based_enum!(EventCompletionAction,
542554
};
543555
);
544556

557+
#[derive(Clone, PartialEq, Eq, Debug)]
558+
pub(crate) enum RAAMonitorUpdateBlockingAction {
559+
/// The inbound channel's channel_id
560+
ForwardedPaymentOtherChannelClaim {
561+
channel_id: [u8; 32],
562+
htlc_id: u64,
563+
},
564+
}
565+
566+
impl RAAMonitorUpdateBlockingAction {
567+
fn from_prev_hop_data(prev_hop: &HTLCPreviousHopData) -> Self {
568+
Self::ForwardedPaymentOtherChannelClaim {
569+
channel_id: prev_hop.outpoint.to_channel_id(),
570+
htlc_id: prev_hop.htlc_id,
571+
}
572+
}
573+
}
574+
575+
impl_writeable_tlv_based_enum!(RAAMonitorUpdateBlockingAction,
576+
(0, ForwardedPaymentOtherChannelClaim) => { (0, channel_id, required), (2, htlc_id, required) }
577+
;);
578+
579+
545580
/// State we hold per-peer.
546581
pub(super) struct PeerState<Signer: ChannelSigner> {
547582
/// `temporary_channel_id` or `channel_id` -> `channel`.
@@ -570,6 +605,11 @@ pub(super) struct PeerState<Signer: ChannelSigner> {
570605
/// to funding appearing on-chain), the downstream `ChannelMonitor` set is required to ensure
571606
/// duplicates do not occur, so such channels should fail without a monitor update completing.
572607
monitor_update_blocked_actions: BTreeMap<[u8; 32], Vec<MonitorUpdateCompletionAction>>,
608+
/// If another channel's [`ChannelMonitorUpdate`] needs to complete before a channel we have
609+
/// with this peer can complete an RAA [`ChannelMonitorUpdate`] (e.g. because the RAA update
610+
/// will remove a preimage that needs to be durably in an upstream channel first), we put an
611+
/// entry here to note that the channel with the key's ID is blocked on a set of actions.
612+
actions_blocking_raa_monitor_updates: BTreeMap<[u8; 32], Vec<RAAMonitorUpdateBlockingAction>>,
573613
/// The peer is currently connected (i.e. we've seen a
574614
/// [`ChannelMessageHandler::peer_connected`] and no corresponding
575615
/// [`ChannelMessageHandler::peer_disconnected`].
@@ -4466,23 +4506,24 @@ where
44664506
},
44674507
HTLCSource::PreviousHopData(hop_data) => {
44684508
let prev_outpoint = hop_data.outpoint;
4509+
let completed_blocker = RAAMonitorUpdateBlockingAction::from_prev_hop_data(&hop_data);
44694510
let res = self.claim_funds_from_hop(hop_data, payment_preimage,
44704511
|htlc_claim_value_msat| {
44714512
if let Some(forwarded_htlc_value) = forwarded_htlc_value_msat {
44724513
let fee_earned_msat = if let Some(claimed_htlc_value) = htlc_claim_value_msat {
44734514
Some(claimed_htlc_value - forwarded_htlc_value)
44744515
} else { None };
44754516

4476-
let prev_channel_id = Some(prev_outpoint.to_channel_id());
4477-
let next_channel_id = Some(next_channel_id);
4478-
4479-
Some(MonitorUpdateCompletionAction::EmitEvent { event: events::Event::PaymentForwarded {
4480-
fee_earned_msat,
4481-
claim_from_onchain_tx: from_onchain,
4482-
prev_channel_id,
4483-
next_channel_id,
4484-
outbound_amount_forwarded_msat: forwarded_htlc_value_msat,
4485-
}})
4517+
Some(MonitorUpdateCompletionAction::EmitEventAndFreeOtherChannel {
4518+
event: events::Event::PaymentForwarded {
4519+
fee_earned_msat,
4520+
claim_from_onchain_tx: from_onchain,
4521+
prev_channel_id: Some(prev_outpoint.to_channel_id()),
4522+
next_channel_id: Some(next_channel_outpoint.to_channel_id()),
4523+
outbound_amount_forwarded_msat: forwarded_htlc_value_msat,
4524+
},
4525+
downstream_counterparty_and_funding_outpoint: None,
4526+
})
44864527
} else { None }
44874528
});
44884529
if let Err((pk, err)) = res {
@@ -4509,8 +4550,13 @@ where
45094550
}, None));
45104551
}
45114552
},
4512-
MonitorUpdateCompletionAction::EmitEvent { event } => {
4553+
MonitorUpdateCompletionAction::EmitEventAndFreeOtherChannel {
4554+
event, downstream_counterparty_and_funding_outpoint
4555+
} => {
45134556
self.pending_events.lock().unwrap().push_back((event, None));
4557+
if let Some((node_id, funding_outpoint, blocker)) = downstream_counterparty_and_funding_outpoint {
4558+
self.handle_monitor_update_release(node_id, funding_outpoint, Some(blocker));
4559+
}
45144560
},
45154561
}
45164562
}
@@ -5357,6 +5403,36 @@ where
53575403
}
53585404
}
53595405

5406+
fn raa_monitor_updates_held(&self,
5407+
actions_blocking_raa_monitor_updates: &BTreeMap<[u8; 32], Vec<RAAMonitorUpdateBlockingAction>>,
5408+
channel_funding_outpoint: OutPoint, counterparty_node_id: PublicKey
5409+
) -> bool {
5410+
actions_blocking_raa_monitor_updates
5411+
.get(&channel_funding_outpoint.to_channel_id()).map(|v| !v.is_empty()).unwrap_or(false)
5412+
|| self.pending_events.lock().unwrap().iter().any(|(_, action)| {
5413+
action == &Some(EventCompletionAction::ReleaseRAAChannelMonitorUpdate {
5414+
channel_funding_outpoint,
5415+
counterparty_node_id,
5416+
})
5417+
})
5418+
}
5419+
5420+
pub(crate) fn test_raa_monitor_updates_held(&self, counterparty_node_id: PublicKey,
5421+
channel_id: [u8; 32])
5422+
-> bool {
5423+
let per_peer_state = self.per_peer_state.read().unwrap();
5424+
if let Some(peer_state_mtx) = per_peer_state.get(&counterparty_node_id) {
5425+
let mut peer_state_lck = peer_state_mtx.lock().unwrap();
5426+
let peer_state = &mut *peer_state_lck;
5427+
5428+
if let Some(chan) = peer_state.channel_by_id.get(&channel_id) {
5429+
return self.raa_monitor_updates_held(&peer_state.actions_blocking_raa_monitor_updates,
5430+
chan.get_funding_txo().unwrap(), counterparty_node_id);
5431+
}
5432+
}
5433+
false
5434+
}
5435+
53605436
fn internal_revoke_and_ack(&self, counterparty_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), MsgHandleErrInternal> {
53615437
let (htlcs_to_fail, res) = {
53625438
let per_peer_state = self.per_peer_state.read().unwrap();
@@ -6018,25 +6094,29 @@ where
60186094
self.pending_outbound_payments.clear_pending_payments()
60196095
}
60206096

6021-
fn handle_monitor_update_release(&self, counterparty_node_id: PublicKey, channel_funding_outpoint: OutPoint) {
6097+
fn handle_monitor_update_release(&self, counterparty_node_id: PublicKey, channel_funding_outpoint: OutPoint, completed_blocker: Option<RAAMonitorUpdateBlockingAction>) {
60226098
let mut errors = Vec::new();
60236099
loop {
60246100
let per_peer_state = self.per_peer_state.read().unwrap();
60256101
if let Some(peer_state_mtx) = per_peer_state.get(&counterparty_node_id) {
60266102
let mut peer_state_lck = peer_state_mtx.lock().unwrap();
60276103
let peer_state = &mut *peer_state_lck;
6028-
if self.pending_events.lock().unwrap().iter()
6029-
.any(|(_ev, action_opt)| action_opt == &Some(EventCompletionAction::ReleaseRAAChannelMonitorUpdate {
6030-
channel_funding_outpoint, counterparty_node_id
6031-
}))
6032-
{
6033-
// Check that, while holding the peer lock, we don't have another event
6034-
// blocking any monitor updates for this channel. If we do, let those
6035-
// events be the ones that ultimately release the monitor update(s).
6036-
log_trace!(self.logger, "Delaying monitor unlock for channel {} as another event is pending",
6104+
6105+
if let Some(blocker) = &completed_blocker {
6106+
if let Some(blockers) = peer_state.actions_blocking_raa_monitor_updates
6107+
.get_mut(&channel_funding_outpoint.to_channel_id())
6108+
{
6109+
blockers.retain(|iter| iter != blocker);
6110+
}
6111+
}
6112+
6113+
if self.raa_monitor_updates_held(&peer_state.actions_blocking_raa_monitor_updates,
6114+
channel_funding_outpoint, counterparty_node_id) {
6115+
log_trace!(self.logger, "Delaying monitor unlock for channel {} as another channel's mon update needs to complete first",
60376116
log_bytes!(&channel_funding_outpoint.to_channel_id()[..]));
60386117
break;
60396118
}
6119+
60406120
if let hash_map::Entry::Occupied(mut chan) = peer_state.channel_by_id.entry(channel_funding_outpoint.to_channel_id()) {
60416121
debug_assert_eq!(chan.get().get_funding_txo().unwrap(), channel_funding_outpoint);
60426122
if let Some((monitor_update, further_update_exists)) = chan.get_mut().unblock_next_blocked_monitor_update() {
@@ -6078,7 +6158,7 @@ where
60786158
EventCompletionAction::ReleaseRAAChannelMonitorUpdate {
60796159
channel_funding_outpoint, counterparty_node_id
60806160
} => {
6081-
self.handle_monitor_update_release(counterparty_node_id, channel_funding_outpoint);
6161+
self.handle_monitor_update_release(counterparty_node_id, channel_funding_outpoint, None);
60826162
}
60836163
}
60846164
}
@@ -6729,6 +6809,7 @@ where
67296809
latest_features: init_msg.features.clone(),
67306810
pending_msg_events: Vec::new(),
67316811
monitor_update_blocked_actions: BTreeMap::new(),
6812+
actions_blocking_raa_monitor_updates: BTreeMap::new(),
67326813
is_connected: true,
67336814
}));
67346815
},
@@ -7874,6 +7955,7 @@ where
78747955
latest_features: Readable::read(reader)?,
78757956
pending_msg_events: Vec::new(),
78767957
monitor_update_blocked_actions: BTreeMap::new(),
7958+
actions_blocking_raa_monitor_updates: BTreeMap::new(),
78777959
is_connected: false,
78787960
};
78797961
per_peer_state.insert(peer_pubkey, Mutex::new(peer_state));
@@ -7957,7 +8039,7 @@ where
79578039
let mut claimable_htlc_purposes = None;
79588040
let mut claimable_htlc_onion_fields = None;
79598041
let mut pending_claiming_payments = Some(HashMap::new());
7960-
let mut monitor_update_blocked_actions_per_peer = Some(Vec::new());
8042+
let mut monitor_update_blocked_actions_per_peer: Option<Vec<(_, BTreeMap<_, Vec<_>>)>> = Some(Vec::new());
79618043
let mut events_override = None;
79628044
read_tlv_fields!(reader, {
79638045
(1, pending_outbound_payments_no_retry, option),
@@ -8282,7 +8364,21 @@ where
82828364
}
82838365

82848366
for (node_id, monitor_update_blocked_actions) in monitor_update_blocked_actions_per_peer.unwrap() {
8285-
if let Some(peer_state) = per_peer_state.get_mut(&node_id) {
8367+
if let Some(peer_state) = per_peer_state.get(&node_id) {
8368+
for (_, actions) in monitor_update_blocked_actions.iter() {
8369+
for action in actions.iter() {
8370+
if let MonitorUpdateCompletionAction::EmitEventAndFreeOtherChannel {
8371+
downstream_counterparty_and_funding_outpoint:
8372+
Some((blocked_node_id, blocked_channel_outpoint, blocking_action)), ..
8373+
} = action {
8374+
if let Some(blocked_peer_state) = per_peer_state.get(&blocked_node_id) {
8375+
blocked_peer_state.lock().unwrap().actions_blocking_raa_monitor_updates
8376+
.entry(blocked_channel_outpoint.to_channel_id())
8377+
.or_insert_with(Vec::new).push(blocking_action.clone());
8378+
}
8379+
}
8380+
}
8381+
}
82868382
peer_state.lock().unwrap().monitor_update_blocked_actions = monitor_update_blocked_actions;
82878383
} else {
82888384
log_error!(args.logger, "Got blocked actions without a per-peer-state for {}", node_id);

0 commit comments

Comments
 (0)