Skip to content

Commit 9fcbd16

Browse files
committed
Block monitor updates to ensure preimages are in each MPP part
If we claim an MPP payment and only persist some of the `ChannelMonitorUpdate`s which include the preimage prior to shutting down, we may be in a state where some of our `ChannelMonitor`s have the preimage for a payment while others do not. This, it turns out, is actually mostly safe - on startup `ChanelManager` will detect there's a payment it has as unclaimed but there's a corresponding payment preimage in a `ChannelMonitor` and go claim the other MPP parts. This works so long as the `ChannelManager` has been persisted after the payment has been received but prior to the `PaymentClaimable` event being processed (and the claim itself occurring). This is not always true and certainly not required on our API, but our `lightning-background-processor` today does persist prior to event handling so is generally true subject to some race conditions. In order to address this we need to use copy payment preimages across channels irrespective of the `ChannelManager`'s payment state, but this introduces another wrinkle - if one channel makes substantial progress while other channel(s) are still waiting to get the payment preimage in `ChannelMonitor`(s) while the `ChannelManager` hasn't been persisted after the payment was received, we may end up without the preimage on disk. Here, we address this issue by using the new `RAAMonitorUpdateBlockingAction` variant for this specific case. We block persistence of an RAA `ChannelMonitorUpdate` which may remove the preimage from disk until all channels have had the preimage added to their `ChannelMonitor`. We do this only in-memory (and not on disk) as we can recreate this blocker during the startup re-claim logic. This will enable us to claim MPP parts without using the `ChannelManager`'s payment state in later work.
1 parent d6ff6ff commit 9fcbd16

File tree

1 file changed

+145
-15
lines changed

1 file changed

+145
-15
lines changed

lightning/src/ln/channelmanager.rs

Lines changed: 145 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -799,7 +799,13 @@ pub(crate) enum MonitorUpdateCompletionAction {
799799
/// [`events::Event::PaymentClaimed`] to the user if we haven't yet generated such an event for
800800
/// this payment. Note that this is only best-effort. On restart it's possible such a duplicate
801801
/// event can be generated.
802-
PaymentClaimed { payment_hash: PaymentHash },
802+
PaymentClaimed {
803+
payment_hash: PaymentHash,
804+
/// A pending MPP claim which hasn't yet completed.
805+
///
806+
/// Not written to disk.
807+
pending_mpp_claim: Option<(PublicKey, ChannelId, u64, PendingMPPClaimPointer)>,
808+
},
803809
/// Indicates an [`events::Event`] should be surfaced to the user and possibly resume the
804810
/// operation of another channel.
805811
///
@@ -833,7 +839,10 @@ pub(crate) enum MonitorUpdateCompletionAction {
833839
}
834840

835841
impl_writeable_tlv_based_enum_upgradable!(MonitorUpdateCompletionAction,
836-
(0, PaymentClaimed) => { (0, payment_hash, required) },
842+
(0, PaymentClaimed) => {
843+
(0, payment_hash, required),
844+
(9999999999, pending_mpp_claim, (static_value, None)),
845+
},
837846
// Note that FreeOtherChannelImmediately should never be written - we were supposed to free
838847
// *immediately*. However, for simplicity we implement read/write here.
839848
(1, FreeOtherChannelImmediately) => {
@@ -6295,12 +6304,43 @@ where
62956304
return;
62966305
}
62976306
if valid_mpp {
6298-
for htlc in sources.drain(..) {
6307+
let mut pending_claim_ptr_opt = None;
6308+
let mut source_claim_pairs = Vec::with_capacity(sources.len());
6309+
if sources.len() > 1 {
6310+
let mut pending_claims = PendingMPPClaim {
6311+
channels_without_preimage: Vec::new(),
6312+
channels_with_preimage: Vec::new(),
6313+
};
6314+
for htlc in sources.drain(..) {
6315+
if let Some(cp_id) = htlc.prev_hop.counterparty_node_id {
6316+
let htlc_id = htlc.prev_hop.htlc_id;
6317+
let chan_id = htlc.prev_hop.channel_id;
6318+
let chan_outpoint = htlc.prev_hop.outpoint;
6319+
pending_claims.channels_without_preimage.push((cp_id, chan_outpoint, chan_id, htlc_id));
6320+
source_claim_pairs.push((htlc, Some((cp_id, chan_id, htlc_id))));
6321+
}
6322+
}
6323+
pending_claim_ptr_opt = Some(Arc::new(Mutex::new(pending_claims)));
6324+
} else {
6325+
for htlc in sources.drain(..) {
6326+
source_claim_pairs.push((htlc, None));
6327+
}
6328+
}
6329+
for (htlc, mpp_claim) in source_claim_pairs.drain(..) {
6330+
let mut pending_mpp_claim = None;
6331+
let pending_claim_ptr = pending_claim_ptr_opt.as_ref().map(|pending_claim| {
6332+
pending_mpp_claim = mpp_claim.map(|(cp_id, chan_id, htlc_id)|
6333+
(cp_id, chan_id, htlc_id, PendingMPPClaimPointer(Arc::clone(pending_claim)))
6334+
);
6335+
RAAMonitorUpdateBlockingAction::ClaimedMPPPayment {
6336+
pending_claim: PendingMPPClaimPointer(Arc::clone(pending_claim)),
6337+
}
6338+
});
62996339
self.claim_funds_from_hop(
63006340
htlc.prev_hop, payment_preimage,
63016341
|_, definitely_duplicate| {
63026342
debug_assert!(!definitely_duplicate, "We shouldn't claim duplicatively from a payment");
6303-
Some(MonitorUpdateCompletionAction::PaymentClaimed { payment_hash })
6343+
(Some(MonitorUpdateCompletionAction::PaymentClaimed { payment_hash, pending_mpp_claim }), pending_claim_ptr)
63046344
}
63056345
);
63066346
}
@@ -6324,7 +6364,9 @@ where
63246364
}
63256365
}
63266366

6327-
fn claim_funds_from_hop<ComplFunc: FnOnce(Option<u64>, bool) -> Option<MonitorUpdateCompletionAction>>(
6367+
fn claim_funds_from_hop<
6368+
ComplFunc: FnOnce(Option<u64>, bool) -> (Option<MonitorUpdateCompletionAction>, Option<RAAMonitorUpdateBlockingAction>)
6369+
>(
63286370
&self, prev_hop: HTLCPreviousHopData, payment_preimage: PaymentPreimage,
63296371
completion_action: ComplFunc,
63306372
) {
@@ -6364,11 +6406,15 @@ where
63646406

63656407
match fulfill_res {
63666408
UpdateFulfillCommitFetch::NewClaim { htlc_value_msat, monitor_update } => {
6367-
if let Some(action) = completion_action(Some(htlc_value_msat), false) {
6409+
let (action_opt, raa_blocker_opt) = completion_action(Some(htlc_value_msat), false);
6410+
if let Some(action) = action_opt {
63686411
log_trace!(logger, "Tracking monitor update completion action for channel {}: {:?}",
63696412
chan_id, action);
63706413
peer_state.monitor_update_blocked_actions.entry(chan_id).or_insert(Vec::new()).push(action);
63716414
}
6415+
if let Some(raa_blocker) = raa_blocker_opt {
6416+
peer_state.actions_blocking_raa_monitor_updates.entry(chan_id).or_insert_with(Vec::new).push(raa_blocker);
6417+
}
63726418
if !during_init {
63736419
handle_new_monitor_update!(self, prev_hop.outpoint, monitor_update, peer_state_lock,
63746420
peer_state, per_peer_state, chan);
@@ -6386,11 +6432,16 @@ where
63866432
}
63876433
}
63886434
UpdateFulfillCommitFetch::DuplicateClaim {} => {
6389-
let action = if let Some(action) = completion_action(None, true) {
6435+
let (action_opt, raa_blocker_opt) = completion_action(None, true);
6436+
let action = if let Some(action) = action_opt {
63906437
action
63916438
} else {
63926439
return;
63936440
};
6441+
if let Some(raa_blocker) = raa_blocker_opt {
6442+
debug_assert!(peer_state.actions_blocking_raa_monitor_updates.get(&chan_id).unwrap().contains(&raa_blocker));
6443+
}
6444+
63946445
mem::drop(peer_state_lock);
63956446

63966447
log_trace!(logger, "Completing monitor update completion action for channel {} as claim was redundant: {:?}",
@@ -6477,7 +6528,47 @@ where
64776528
// `ChannelMonitor` we've provided the above update to. Instead, note that `Event`s are
64786529
// generally always allowed to be duplicative (and it's specifically noted in
64796530
// `PaymentForwarded`).
6480-
self.handle_monitor_update_completion_actions(completion_action(None, false));
6531+
let (action_opt, raa_blocker_opt) = completion_action(None, false);
6532+
6533+
if let Some(raa_blocker) = raa_blocker_opt {
6534+
let counterparty_node_id = prev_hop.counterparty_node_id.or_else(||
6535+
// prev_hop.counterparty_node_id is always available for payments received after
6536+
// LDK 0.0.123, but for those received on 0.0.123 and claimed later, we need to
6537+
// look up the counterparty in the `action_opt`, if possible.
6538+
if let Some(action) = &action_opt {
6539+
if let MonitorUpdateCompletionAction::PaymentClaimed { pending_mpp_claim, .. } = action {
6540+
if let Some((node_id, _, _, _)) = pending_mpp_claim {
6541+
Some(*node_id)
6542+
} else { None }
6543+
} else { None }
6544+
} else { None });
6545+
if let Some(counterparty_node_id) = counterparty_node_id {
6546+
// TODO: Avoid always blocking the world for the write lock here.
6547+
let mut per_peer_state = self.per_peer_state.write().unwrap();
6548+
let peer_state_mutex = per_peer_state.entry(counterparty_node_id).or_insert_with(||
6549+
Mutex::new(PeerState {
6550+
channel_by_id: new_hash_map(),
6551+
inbound_channel_request_by_id: new_hash_map(),
6552+
latest_features: InitFeatures::empty(),
6553+
pending_msg_events: Vec::new(),
6554+
in_flight_monitor_updates: BTreeMap::new(),
6555+
monitor_update_blocked_actions: BTreeMap::new(),
6556+
actions_blocking_raa_monitor_updates: BTreeMap::new(),
6557+
is_connected: false,
6558+
}));
6559+
let mut peer_state = peer_state_mutex.lock().unwrap();
6560+
6561+
peer_state.actions_blocking_raa_monitor_updates
6562+
.entry(prev_hop.channel_id)
6563+
.or_insert_with(Vec::new)
6564+
.push(raa_blocker);
6565+
} else {
6566+
debug_assert!(false,
6567+
"RAA ChannelMonitorUpdate blockers are only set with PaymentClaimed completion actions, so we should always have a counterparty node id");
6568+
}
6569+
}
6570+
6571+
self.handle_monitor_update_completion_actions(action_opt);
64816572
}
64826573

64836574
fn finalize_claims(&self, sources: Vec<HTLCSource>) {
@@ -6576,16 +6667,16 @@ where
65766667
}
65776668
}), "{:?}", *background_events);
65786669
}
6579-
None
6670+
(None, None)
65806671
} else if definitely_duplicate {
65816672
if let Some(other_chan) = chan_to_release {
6582-
Some(MonitorUpdateCompletionAction::FreeOtherChannelImmediately {
6673+
(Some(MonitorUpdateCompletionAction::FreeOtherChannelImmediately {
65836674
downstream_counterparty_node_id: other_chan.counterparty_node_id,
65846675
downstream_funding_outpoint: other_chan.funding_txo,
65856676
downstream_channel_id: other_chan.channel_id,
65866677
blocking_action: other_chan.blocking_action,
6587-
})
6588-
} else { None }
6678+
}), None)
6679+
} else { (None, None) }
65896680
} else {
65906681
let total_fee_earned_msat = if let Some(forwarded_htlc_value) = forwarded_htlc_value_msat {
65916682
if let Some(claimed_htlc_value) = htlc_claim_value_msat {
@@ -6594,7 +6685,7 @@ where
65946685
} else { None };
65956686
debug_assert!(skimmed_fee_msat <= total_fee_earned_msat,
65966687
"skimmed_fee_msat must always be included in total_fee_earned_msat");
6597-
Some(MonitorUpdateCompletionAction::EmitEventAndFreeOtherChannel {
6688+
(Some(MonitorUpdateCompletionAction::EmitEventAndFreeOtherChannel {
65986689
event: events::Event::PaymentForwarded {
65996690
prev_channel_id: Some(prev_channel_id),
66006691
next_channel_id: Some(next_channel_id),
@@ -6606,7 +6697,7 @@ where
66066697
outbound_amount_forwarded_msat: forwarded_htlc_value_msat,
66076698
},
66086699
downstream_counterparty_and_funding_outpoint: chan_to_release,
6609-
})
6700+
}), None)
66106701
}
66116702
});
66126703
},
@@ -6623,9 +6714,44 @@ where
66236714
debug_assert_ne!(self.claimable_payments.held_by_thread(), LockHeldState::HeldByThread);
66246715
debug_assert_ne!(self.per_peer_state.held_by_thread(), LockHeldState::HeldByThread);
66256716

6717+
let mut freed_channels = Vec::new();
6718+
66266719
for action in actions.into_iter() {
66276720
match action {
6628-
MonitorUpdateCompletionAction::PaymentClaimed { payment_hash } => {
6721+
MonitorUpdateCompletionAction::PaymentClaimed { payment_hash, pending_mpp_claim } => {
6722+
if let Some((counterparty_node_id, chan_id, htlc_id, claim_ptr)) = pending_mpp_claim {
6723+
let per_peer_state = self.per_peer_state.read().unwrap();
6724+
per_peer_state.get(&counterparty_node_id).map(|peer_state_mutex| {
6725+
let mut peer_state = peer_state_mutex.lock().unwrap();
6726+
let blockers_entry = peer_state.actions_blocking_raa_monitor_updates.entry(chan_id);
6727+
if let btree_map::Entry::Occupied(mut blockers) = blockers_entry {
6728+
blockers.get_mut().retain(|blocker|
6729+
if let &RAAMonitorUpdateBlockingAction::ClaimedMPPPayment { pending_claim } = &blocker {
6730+
if *pending_claim == claim_ptr {
6731+
let mut pending_claim_state_lock = pending_claim.0.lock().unwrap();
6732+
let pending_claim_state = &mut *pending_claim_state_lock;
6733+
pending_claim_state.channels_without_preimage.retain(|(cp, outp, cid, hid)| {
6734+
if *cp == counterparty_node_id && *cid == chan_id && *hid == htlc_id {
6735+
pending_claim_state.channels_with_preimage.push((*cp, *outp, *cid));
6736+
false
6737+
} else { true }
6738+
});
6739+
if pending_claim_state.channels_without_preimage.is_empty() {
6740+
for (cp, outp, cid) in pending_claim_state.channels_with_preimage.iter() {
6741+
freed_channels.push((*cp, *outp, *cid, blocker.clone()));
6742+
}
6743+
}
6744+
!pending_claim_state.channels_without_preimage.is_empty()
6745+
} else { true }
6746+
} else { true }
6747+
);
6748+
if blockers.get().is_empty() {
6749+
blockers.remove();
6750+
}
6751+
}
6752+
});
6753+
}
6754+
66296755
let payment = self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
66306756
if let Some(ClaimingPayment {
66316757
amount_msat,
@@ -6669,6 +6795,10 @@ where
66696795
},
66706796
}
66716797
}
6798+
6799+
for (node_id, funding_outpoint, channel_id, blocker) in freed_channels {
6800+
self.handle_monitor_update_release(node_id, funding_outpoint, channel_id, Some(blocker));
6801+
}
66726802
}
66736803

66746804
/// Handles a channel reentering a functional state, either due to reconnect or a monitor

0 commit comments

Comments
 (0)