Skip to content

Commit 031bd1b

Browse files
committed
Delay RAA-after-next processing until PaymentSent is are handled
In 0ad1f4c we fixed a nasty bug where a failure to persist a `ChannelManager` faster than a `ChannelMonitor` could result in the loss of a `PaymentSent` event, eventually resulting in a `PaymentFailed` instead! As noted in that commit, there's still some risk, though its been substantially reduced - if we receive an `update_fulfill_htlc` message for an outbound payment, and persist the initial removal `ChannelMonitorUpdate`, then respond with our own `commitment_signed` + `revoke_and_ack`, followed by receiving our peer's final `revoke_and_ack`, and then persist the `ChannelMonitorUpdate` generated from that, all prior to completing a `ChannelManager` persistence, we'll still forget the HTLC and eventually trigger a `PaymentFailed` rather than the correct `PaymentSent`. Here we fully fix the issue by delaying the final `ChannelMonitorUpdate` persistence until the `PaymentSent` event has been processed and document the fact that a spurious `PaymentFailed` event can still be generated for a sent payment. The original fix in 0ad1f4c is still incredibly useful here, allowing us to avoid blocking the first `ChannelMonitorUpdate` until the event processing completes, as this would cause us to add event-processing delay in our general commitment update latency. Instead, we ultimately race the user handling the `PaymentSent` event with how long it takes our `revoke_and_ack` + `commitment_signed` to make it to our counterparty and receive the response `revoke_and_ack`. This should give the user plenty of time to handle the event before we need to make progress. Sadly, because we change our `ChannelMonitorUpdate` semantics, this change requires a number of test changes, avoiding checking for a post-RAA `ChannelMonitorUpdate` until after we process a `PaymentSent` event. Note that this does not apply to payments we learned the preimage for on-chain - ensuring `PaymentSent` events from such resolutions will be addressed in a future PR. Thus, tests which resolve payments on-chain switch to a direct call to the `expect_payment_sent` function with the claim-expected flag unset.
1 parent d2d3036 commit 031bd1b

14 files changed

+305
-104
lines changed

lightning-invoice/src/utils.rs

+1-16
Original file line numberDiff line numberDiff line change
@@ -1175,22 +1175,7 @@ mod test {
11751175
let payment_preimage_opt = if user_generated_pmt_hash { None } else { Some(payment_preimage) };
11761176
expect_payment_claimable!(&nodes[fwd_idx], payment_hash, payment_secret, payment_amt, payment_preimage_opt, route.paths[0].last().unwrap().pubkey);
11771177
do_claim_payment_along_route(&nodes[0], &[&vec!(&nodes[fwd_idx])[..]], false, payment_preimage);
1178-
let events = nodes[0].node.get_and_clear_pending_events();
1179-
assert_eq!(events.len(), 2);
1180-
match events[0] {
1181-
Event::PaymentSent { payment_preimage: ref ev_preimage, payment_hash: ref ev_hash, ref fee_paid_msat, .. } => {
1182-
assert_eq!(payment_preimage, *ev_preimage);
1183-
assert_eq!(payment_hash, *ev_hash);
1184-
assert_eq!(fee_paid_msat, &Some(0));
1185-
},
1186-
_ => panic!("Unexpected event")
1187-
}
1188-
match events[1] {
1189-
Event::PaymentPathSuccessful { payment_hash: hash, .. } => {
1190-
assert_eq!(hash, Some(payment_hash));
1191-
},
1192-
_ => panic!("Unexpected event")
1193-
}
1178+
expect_payment_sent(&nodes[0], payment_preimage, None, true, true);
11941179
}
11951180

11961181
#[test]

lightning/src/chain/chainmonitor.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -807,7 +807,7 @@ mod tests {
807807
use bitcoin::{BlockHeader, TxMerkleNode};
808808
use bitcoin::hashes::Hash;
809809
use crate::{check_added_monitors, check_closed_broadcast, check_closed_event};
810-
use crate::{expect_payment_sent, expect_payment_claimed, expect_payment_sent_without_paths, expect_payment_path_successful, get_event_msg};
810+
use crate::{expect_payment_claimed, expect_payment_path_successful, get_event_msg};
811811
use crate::{get_htlc_update_msgs, get_local_commitment_txn, get_revoke_commit_msgs, get_route_and_payment_hash, unwrap_send_err};
812812
use crate::chain::{ChannelMonitorUpdateStatus, Confirm, Watch};
813813
use crate::chain::channelmonitor::LATENCY_GRACE_PERIOD_BLOCKS;
@@ -890,7 +890,7 @@ mod tests {
890890

891891
let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
892892
nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
893-
expect_payment_sent_without_paths!(nodes[0], payment_preimage_1);
893+
expect_payment_sent(&nodes[0], payment_preimage_1, None, false, false);
894894
nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &updates.commitment_signed);
895895
check_added_monitors!(nodes[0], 1);
896896
let (as_first_raa, as_first_update) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
@@ -903,7 +903,7 @@ mod tests {
903903
let bs_first_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
904904

905905
nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_updates.update_fulfill_htlcs[0]);
906-
expect_payment_sent_without_paths!(nodes[0], payment_preimage_2);
906+
expect_payment_sent(&nodes[0], payment_preimage_2, None, false, false);
907907
nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_updates.commitment_signed);
908908
check_added_monitors!(nodes[0], 1);
909909
nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
@@ -991,7 +991,7 @@ mod tests {
991991
}
992992
}
993993

994-
expect_payment_sent!(nodes[0], payment_preimage);
994+
expect_payment_sent(&nodes[0], payment_preimage, None, true, false);
995995
}
996996

997997
#[test]

lightning/src/events/mod.rs

+5
Original file line numberDiff line numberDiff line change
@@ -417,6 +417,11 @@ pub enum Event {
417417
/// payment is no longer retryable, due either to the [`Retry`] provided or
418418
/// [`ChannelManager::abandon_payment`] having been called for the corresponding payment.
419419
///
420+
/// In exceedingly rare cases, it is possible that an [`Event::PaymentFailed`] is generated for
421+
/// a payment after an [`Event::PaymentSent`] event for this same payment has already been
422+
/// received and processed. In this case, the [`Event::PaymentFailed`] event MUST be ignored,
423+
/// and the payment MUST be treated as having succeeded.
424+
///
420425
/// [`Retry`]: crate::ln::channelmanager::Retry
421426
/// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
422427
PaymentFailed {

lightning/src/ln/chanmon_update_fail_tests.rs

+72-7
Original file line numberDiff line numberDiff line change
@@ -1371,6 +1371,7 @@ fn claim_while_disconnected_monitor_update_fail() {
13711371
MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
13721372
assert_eq!(*node_id, nodes[0].node.get_our_node_id());
13731373
nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
1374+
expect_payment_sent(&nodes[0], payment_preimage_1, None, false, false);
13741375
nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &updates.commitment_signed);
13751376
check_added_monitors!(nodes[0], 1);
13761377

@@ -1408,7 +1409,7 @@ fn claim_while_disconnected_monitor_update_fail() {
14081409

14091410
nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
14101411
check_added_monitors!(nodes[0], 1);
1411-
expect_payment_sent!(nodes[0], payment_preimage_1);
1412+
expect_payment_path_successful!(nodes[0]);
14121413

14131414
claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
14141415
}
@@ -2144,7 +2145,7 @@ fn test_fail_htlc_on_broadcast_after_claim() {
21442145
expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_id_2 }]);
21452146

21462147
nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
2147-
expect_payment_sent_without_paths!(nodes[0], payment_preimage);
2148+
expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
21482149
commitment_signed_dance!(nodes[0], nodes[1], bs_updates.commitment_signed, true, true);
21492150
expect_payment_path_successful!(nodes[0]);
21502151
}
@@ -2380,7 +2381,7 @@ fn do_channel_holding_cell_serialize(disconnect: bool, reload_a: bool) {
23802381
assert!(updates.update_fee.is_none());
23812382
assert_eq!(updates.update_fulfill_htlcs.len(), 1);
23822383
nodes[1].node.handle_update_fulfill_htlc(&nodes[0].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
2383-
expect_payment_sent_without_paths!(nodes[1], payment_preimage_0);
2384+
expect_payment_sent(&nodes[1], payment_preimage_0, None, false, false);
23842385
assert_eq!(updates.update_add_htlcs.len(), 1);
23852386
nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
23862387
updates.commitment_signed
@@ -2397,7 +2398,7 @@ fn do_channel_holding_cell_serialize(disconnect: bool, reload_a: bool) {
23972398
expect_payment_claimable!(nodes[1], payment_hash_1, payment_secret_1, 100000);
23982399
check_added_monitors!(nodes[1], 1);
23992400

2400-
commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false);
2401+
commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false, false);
24012402

24022403
let events = nodes[1].node.get_and_clear_pending_events();
24032404
assert_eq!(events.len(), 2);
@@ -2497,7 +2498,7 @@ fn do_test_reconnect_dup_htlc_claims(htlc_status: HTLCStatusAtDupClaim, second_f
24972498
bs_updates = Some(get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id()));
24982499
assert_eq!(bs_updates.as_ref().unwrap().update_fulfill_htlcs.len(), 1);
24992500
nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.as_ref().unwrap().update_fulfill_htlcs[0]);
2500-
expect_payment_sent_without_paths!(nodes[0], payment_preimage);
2501+
expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
25012502
if htlc_status == HTLCStatusAtDupClaim::Cleared {
25022503
commitment_signed_dance!(nodes[0], nodes[1], &bs_updates.as_ref().unwrap().commitment_signed, false);
25032504
expect_payment_path_successful!(nodes[0]);
@@ -2524,7 +2525,7 @@ fn do_test_reconnect_dup_htlc_claims(htlc_status: HTLCStatusAtDupClaim, second_f
25242525
bs_updates = Some(get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id()));
25252526
assert_eq!(bs_updates.as_ref().unwrap().update_fulfill_htlcs.len(), 1);
25262527
nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.as_ref().unwrap().update_fulfill_htlcs[0]);
2527-
expect_payment_sent_without_paths!(nodes[0], payment_preimage);
2528+
expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
25282529
}
25292530
if htlc_status != HTLCStatusAtDupClaim::Cleared {
25302531
commitment_signed_dance!(nodes[0], nodes[1], &bs_updates.as_ref().unwrap().commitment_signed, false);
@@ -2721,7 +2722,7 @@ fn double_temp_error() {
27212722
assert_eq!(node_id, nodes[0].node.get_our_node_id());
27222723
nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_1);
27232724
check_added_monitors!(nodes[0], 0);
2724-
expect_payment_sent_without_paths!(nodes[0], payment_preimage_1);
2725+
expect_payment_sent(&nodes[0], payment_preimage_1, None, false, false);
27252726
nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_b1);
27262727
check_added_monitors!(nodes[0], 1);
27272728
nodes[0].node.process_pending_htlc_forwards();
@@ -2946,3 +2947,67 @@ fn test_inbound_reload_without_init_mon() {
29462947
do_test_inbound_reload_without_init_mon(false, true);
29472948
do_test_inbound_reload_without_init_mon(false, false);
29482949
}
2950+
2951+
#[test]
2952+
fn test_blocked_chan_preimage_release() {
2953+
// Test that even if a channel's `ChannelMonitorUpdate` flow is blocked waiting on an event to
2954+
// be handled HTLC preimage `ChannelMonitorUpdate`s will still go out.
2955+
let chanmon_cfgs = create_chanmon_cfgs(3);
2956+
let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2957+
let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2958+
let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2959+
2960+
create_announced_chan_between_nodes(&nodes, 0, 1).2;
2961+
create_announced_chan_between_nodes(&nodes, 1, 2).2;
2962+
2963+
send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 5_000_000);
2964+
2965+
// Tee up two payments in opposite directions across nodes[1], one it sent to generate a
2966+
// PaymentSent event and one it forwards.
2967+
let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[1], &[&nodes[2]], 1_000_000);
2968+
let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[2], &[&nodes[1], &nodes[0]], 1_000_000);
2969+
2970+
// Claim the first payment to get a `PaymentSent` event (but don't handle it yet).
2971+
nodes[2].node.claim_funds(payment_preimage_1);
2972+
check_added_monitors(&nodes[2], 1);
2973+
expect_payment_claimed!(nodes[2], payment_hash_1, 1_000_000);
2974+
2975+
let cs_htlc_fulfill_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2976+
nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &cs_htlc_fulfill_updates.update_fulfill_htlcs[0]);
2977+
commitment_signed_dance!(nodes[1], nodes[2], cs_htlc_fulfill_updates.commitment_signed, false);
2978+
check_added_monitors(&nodes[1], 0);
2979+
2980+
// Now claim the second payment on nodes[0], which will ultimately result in nodes[1] trying to
2981+
// claim an HTLC on its channel with nodes[2], but that channel is blocked on the above
2982+
// `PaymentSent` event.
2983+
nodes[0].node.claim_funds(payment_preimage_2);
2984+
check_added_monitors(&nodes[0], 1);
2985+
expect_payment_claimed!(nodes[0], payment_hash_2, 1_000_000);
2986+
2987+
let as_htlc_fulfill_updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2988+
nodes[1].node.handle_update_fulfill_htlc(&nodes[0].node.get_our_node_id(), &as_htlc_fulfill_updates.update_fulfill_htlcs[0]);
2989+
check_added_monitors(&nodes[1], 1); // We generate only a preimage monitor update
2990+
assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2991+
2992+
// Finish the CS dance between nodes[0] and nodes[1].
2993+
commitment_signed_dance!(nodes[1], nodes[0], as_htlc_fulfill_updates.commitment_signed, false);
2994+
check_added_monitors(&nodes[1], 0);
2995+
2996+
let events = nodes[1].node.get_and_clear_pending_events();
2997+
assert_eq!(events.len(), 3);
2998+
if let Event::PaymentSent { .. } = events[0] {} else { panic!(); }
2999+
if let Event::PaymentPathSuccessful { .. } = events[2] {} else { panic!(); }
3000+
if let Event::PaymentForwarded { .. } = events[1] {} else { panic!(); }
3001+
3002+
// The event processing should release the last RAA update.
3003+
check_added_monitors(&nodes[1], 1);
3004+
3005+
// When we fetch the next update the message getter will generate the next update for nodes[2],
3006+
// generating a further monitor update.
3007+
let bs_htlc_fulfill_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
3008+
check_added_monitors(&nodes[1], 1);
3009+
3010+
nodes[2].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_htlc_fulfill_updates.update_fulfill_htlcs[0]);
3011+
commitment_signed_dance!(nodes[2], nodes[1], bs_htlc_fulfill_updates.commitment_signed, false);
3012+
expect_payment_sent(&nodes[2], payment_preimage_2, None, true, true);
3013+
}

lightning/src/ln/channel.rs

+18-8
Original file line numberDiff line numberDiff line change
@@ -3438,7 +3438,8 @@ impl<Signer: WriteableEcdsaChannelSigner> Channel<Signer> {
34383438
/// waiting on this revoke_and_ack. The generation of this new commitment_signed may also fail,
34393439
/// generating an appropriate error *after* the channel state has been updated based on the
34403440
/// revoke_and_ack message.
3441-
pub fn revoke_and_ack<L: Deref>(&mut self, msg: &msgs::RevokeAndACK, logger: &L) -> Result<(Vec<(HTLCSource, PaymentHash)>, Option<&ChannelMonitorUpdate>), ChannelError>
3441+
pub fn revoke_and_ack<L: Deref>(&mut self, msg: &msgs::RevokeAndACK, logger: &L, hold_mon_update: bool)
3442+
-> Result<(Vec<(HTLCSource, PaymentHash)>, Option<&ChannelMonitorUpdate>), ChannelError>
34423443
where L::Target: Logger,
34433444
{
34443445
if (self.channel_state & (ChannelState::ChannelReady as u32)) != (ChannelState::ChannelReady as u32) {
@@ -3635,14 +3636,18 @@ impl<Signer: WriteableEcdsaChannelSigner> Channel<Signer> {
36353636
self.monitor_pending_failures.append(&mut revoked_htlcs);
36363637
self.monitor_pending_finalized_fulfills.append(&mut finalized_claimed_htlcs);
36373638
log_debug!(logger, "Received a valid revoke_and_ack for channel {} but awaiting a monitor update resolution to reply.", log_bytes!(self.channel_id()));
3638-
let release_monitor = self.pending_monitor_updates.iter().all(|upd| !upd.blocked);
3639+
let release_monitor = self.pending_monitor_updates.iter().all(|upd| !upd.blocked) && !hold_mon_update;
36393640
self.pending_monitor_updates.push(PendingChannelMonitorUpdate {
36403641
update: monitor_update, blocked: !release_monitor,
36413642
});
36423643
return Ok((Vec::new(),
36433644
if release_monitor { self.pending_monitor_updates.last().map(|upd| &upd.update) } else { None }));
36443645
}
36453646

3647+
let release_monitor = self.pending_monitor_updates.iter().all(|upd| !upd.blocked) && !hold_mon_update;
3648+
let release_state_str =
3649+
if hold_mon_update { "Holding" } else if release_monitor { "Releasing" } else { "Blocked" };
3650+
36463651
match self.free_holding_cell_htlcs(logger) {
36473652
(Some(_), htlcs_to_fail) => {
36483653
let mut additional_update = self.pending_monitor_updates.pop().unwrap().update;
@@ -3651,8 +3656,10 @@ impl<Signer: WriteableEcdsaChannelSigner> Channel<Signer> {
36513656
self.latest_monitor_update_id = monitor_update.update_id;
36523657
monitor_update.updates.append(&mut additional_update.updates);
36533658

3659+
log_debug!(logger, "Received a valid revoke_and_ack for channel {} with holding cell HTLCs freed. {} monitor update.",
3660+
log_bytes!(self.channel_id()), release_state_str);
3661+
36543662
self.monitor_updating_paused(false, true, false, to_forward_infos, revoked_htlcs, finalized_claimed_htlcs);
3655-
let release_monitor = self.pending_monitor_updates.iter().all(|upd| !upd.blocked);
36563663
self.pending_monitor_updates.push(PendingChannelMonitorUpdate {
36573664
update: monitor_update, blocked: !release_monitor,
36583665
});
@@ -3668,19 +3675,22 @@ impl<Signer: WriteableEcdsaChannelSigner> Channel<Signer> {
36683675
self.latest_monitor_update_id = monitor_update.update_id;
36693676
monitor_update.updates.append(&mut additional_update.updates);
36703677

3671-
log_debug!(logger, "Received a valid revoke_and_ack for channel {}. Responding with a commitment update with {} HTLCs failed.",
3672-
log_bytes!(self.channel_id()), update_fail_htlcs.len() + update_fail_malformed_htlcs.len());
3678+
log_debug!(logger, "Received a valid revoke_and_ack for channel {}. Responding with a commitment update with {} HTLCs failed. {} monitor update.",
3679+
log_bytes!(self.channel_id()),
3680+
update_fail_htlcs.len() + update_fail_malformed_htlcs.len(),
3681+
release_state_str);
3682+
36733683
self.monitor_updating_paused(false, true, false, to_forward_infos, revoked_htlcs, finalized_claimed_htlcs);
3674-
let release_monitor = self.pending_monitor_updates.iter().all(|upd| !upd.blocked);
36753684
self.pending_monitor_updates.push(PendingChannelMonitorUpdate {
36763685
update: monitor_update, blocked: !release_monitor,
36773686
});
36783687
Ok((htlcs_to_fail,
36793688
if release_monitor { self.pending_monitor_updates.last().map(|upd| &upd.update) } else { None }))
36803689
} else {
3681-
log_debug!(logger, "Received a valid revoke_and_ack for channel {} with no reply necessary.", log_bytes!(self.channel_id()));
3690+
log_debug!(logger, "Received a valid revoke_and_ack for channel {} with no reply necessary. {} monitor update.",
3691+
log_bytes!(self.channel_id()), release_state_str);
3692+
36823693
self.monitor_updating_paused(false, false, false, to_forward_infos, revoked_htlcs, finalized_claimed_htlcs);
3683-
let release_monitor = self.pending_monitor_updates.iter().all(|upd| !upd.blocked);
36843694
self.pending_monitor_updates.push(PendingChannelMonitorUpdate {
36853695
update: monitor_update, blocked: !release_monitor,
36863696
});

0 commit comments

Comments
 (0)