Skip to content

Commit ba1207a

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 e13ff10 commit ba1207a

14 files changed

+326
-105
lines changed

lightning-invoice/src/utils.rs

+1-16
Original file line numberDiff line numberDiff line change
@@ -1373,22 +1373,7 @@ mod test {
13731373
assert_eq!(other_events.borrow().len(), 1);
13741374
check_payment_claimable(&other_events.borrow()[0], payment_hash, payment_secret, payment_amt, payment_preimage_opt, invoice.recover_payee_pub_key());
13751375
do_claim_payment_along_route(&nodes[0], &[&vec!(&nodes[fwd_idx])[..]], false, payment_preimage);
1376-
let events = nodes[0].node.get_and_clear_pending_events();
1377-
assert_eq!(events.len(), 2);
1378-
match events[0] {
1379-
Event::PaymentSent { payment_preimage: ref ev_preimage, payment_hash: ref ev_hash, ref fee_paid_msat, .. } => {
1380-
assert_eq!(payment_preimage, *ev_preimage);
1381-
assert_eq!(payment_hash, *ev_hash);
1382-
assert_eq!(fee_paid_msat, &Some(0));
1383-
},
1384-
_ => panic!("Unexpected event")
1385-
}
1386-
match events[1] {
1387-
Event::PaymentPathSuccessful { payment_hash: hash, .. } => {
1388-
assert_eq!(hash, Some(payment_hash));
1389-
},
1390-
_ => panic!("Unexpected event")
1391-
}
1376+
expect_payment_sent(&nodes[0], payment_preimage, None, true, true);
13921377
}
13931378

13941379
#[test]

lightning/src/chain/chainmonitor.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -806,7 +806,7 @@ impl<ChannelSigner: WriteableEcdsaChannelSigner, C: Deref, T: Deref, F: Deref, L
806806
#[cfg(test)]
807807
mod tests {
808808
use crate::{check_added_monitors, check_closed_broadcast, check_closed_event};
809-
use crate::{expect_payment_sent, expect_payment_claimed, expect_payment_sent_without_paths, expect_payment_path_successful, get_event_msg};
809+
use crate::{expect_payment_claimed, expect_payment_path_successful, get_event_msg};
810810
use crate::{get_htlc_update_msgs, get_local_commitment_txn, get_revoke_commit_msgs, get_route_and_payment_hash, unwrap_send_err};
811811
use crate::chain::{ChannelMonitorUpdateStatus, Confirm, Watch};
812812
use crate::chain::channelmonitor::LATENCY_GRACE_PERIOD_BLOCKS;
@@ -889,7 +889,7 @@ mod tests {
889889

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

904904
nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_updates.update_fulfill_htlcs[0]);
905-
expect_payment_sent_without_paths!(nodes[0], payment_preimage_2);
905+
expect_payment_sent(&nodes[0], payment_preimage_2, None, false, false);
906906
nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_updates.commitment_signed);
907907
check_added_monitors!(nodes[0], 1);
908908
nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
@@ -985,7 +985,7 @@ mod tests {
985985
}
986986
}
987987

988-
expect_payment_sent!(nodes[0], payment_preimage);
988+
expect_payment_sent(&nodes[0], payment_preimage, None, true, false);
989989
}
990990

991991
#[test]

lightning/src/events/mod.rs

+5
Original file line numberDiff line numberDiff line change
@@ -491,6 +491,11 @@ pub enum Event {
491491
/// payment is no longer retryable, due either to the [`Retry`] provided or
492492
/// [`ChannelManager::abandon_payment`] having been called for the corresponding payment.
493493
///
494+
/// In exceedingly rare cases, it is possible that an [`Event::PaymentFailed`] is generated for
495+
/// a payment after an [`Event::PaymentSent`] event for this same payment has already been
496+
/// received and processed. In this case, the [`Event::PaymentFailed`] event MUST be ignored,
497+
/// and the payment MUST be treated as having succeeded.
498+
///
494499
/// [`Retry`]: crate::ln::channelmanager::Retry
495500
/// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
496501
PaymentFailed {

lightning/src/ln/chanmon_update_fail_tests.rs

+72-7
Original file line numberDiff line numberDiff line change
@@ -1400,6 +1400,7 @@ fn claim_while_disconnected_monitor_update_fail() {
14001400
MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
14011401
assert_eq!(*node_id, nodes[0].node.get_our_node_id());
14021402
nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
1403+
expect_payment_sent(&nodes[0], payment_preimage_1, None, false, false);
14031404
nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &updates.commitment_signed);
14041405
check_added_monitors!(nodes[0], 1);
14051406

@@ -1437,7 +1438,7 @@ fn claim_while_disconnected_monitor_update_fail() {
14371438

14381439
nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
14391440
check_added_monitors!(nodes[0], 1);
1440-
expect_payment_sent!(nodes[0], payment_preimage_1);
1441+
expect_payment_path_successful!(nodes[0]);
14411442

14421443
claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
14431444
}
@@ -2191,7 +2192,7 @@ fn test_fail_htlc_on_broadcast_after_claim() {
21912192
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 }]);
21922193

21932194
nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
2194-
expect_payment_sent_without_paths!(nodes[0], payment_preimage);
2195+
expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
21952196
commitment_signed_dance!(nodes[0], nodes[1], bs_updates.commitment_signed, true, true);
21962197
expect_payment_path_successful!(nodes[0]);
21972198
}
@@ -2444,7 +2445,7 @@ fn do_channel_holding_cell_serialize(disconnect: bool, reload_a: bool) {
24442445
assert!(updates.update_fee.is_none());
24452446
assert_eq!(updates.update_fulfill_htlcs.len(), 1);
24462447
nodes[1].node.handle_update_fulfill_htlc(&nodes[0].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
2447-
expect_payment_sent_without_paths!(nodes[1], payment_preimage_0);
2448+
expect_payment_sent(&nodes[1], payment_preimage_0, None, false, false);
24482449
assert_eq!(updates.update_add_htlcs.len(), 1);
24492450
nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
24502451
updates.commitment_signed
@@ -2461,7 +2462,7 @@ fn do_channel_holding_cell_serialize(disconnect: bool, reload_a: bool) {
24612462
expect_payment_claimable!(nodes[1], payment_hash_1, payment_secret_1, 100000);
24622463
check_added_monitors!(nodes[1], 1);
24632464

2464-
commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false);
2465+
commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false, false);
24652466

24662467
let events = nodes[1].node.get_and_clear_pending_events();
24672468
assert_eq!(events.len(), 2);
@@ -2562,7 +2563,7 @@ fn do_test_reconnect_dup_htlc_claims(htlc_status: HTLCStatusAtDupClaim, second_f
25622563
bs_updates = Some(get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id()));
25632564
assert_eq!(bs_updates.as_ref().unwrap().update_fulfill_htlcs.len(), 1);
25642565
nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.as_ref().unwrap().update_fulfill_htlcs[0]);
2565-
expect_payment_sent_without_paths!(nodes[0], payment_preimage);
2566+
expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
25662567
if htlc_status == HTLCStatusAtDupClaim::Cleared {
25672568
commitment_signed_dance!(nodes[0], nodes[1], &bs_updates.as_ref().unwrap().commitment_signed, false);
25682569
expect_payment_path_successful!(nodes[0]);
@@ -2589,7 +2590,7 @@ fn do_test_reconnect_dup_htlc_claims(htlc_status: HTLCStatusAtDupClaim, second_f
25892590
bs_updates = Some(get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id()));
25902591
assert_eq!(bs_updates.as_ref().unwrap().update_fulfill_htlcs.len(), 1);
25912592
nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.as_ref().unwrap().update_fulfill_htlcs[0]);
2592-
expect_payment_sent_without_paths!(nodes[0], payment_preimage);
2593+
expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
25932594
}
25942595
if htlc_status != HTLCStatusAtDupClaim::Cleared {
25952596
commitment_signed_dance!(nodes[0], nodes[1], &bs_updates.as_ref().unwrap().commitment_signed, false);
@@ -2786,7 +2787,7 @@ fn double_temp_error() {
27862787
assert_eq!(node_id, nodes[0].node.get_our_node_id());
27872788
nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_1);
27882789
check_added_monitors!(nodes[0], 0);
2789-
expect_payment_sent_without_paths!(nodes[0], payment_preimage_1);
2790+
expect_payment_sent(&nodes[0], payment_preimage_1, None, false, false);
27902791
nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_b1);
27912792
check_added_monitors!(nodes[0], 1);
27922793
nodes[0].node.process_pending_htlc_forwards();
@@ -3011,3 +3012,67 @@ fn test_inbound_reload_without_init_mon() {
30113012
do_test_inbound_reload_without_init_mon(false, true);
30123013
do_test_inbound_reload_without_init_mon(false, false);
30133014
}
3015+
3016+
#[test]
3017+
fn test_blocked_chan_preimage_release() {
3018+
// Test that even if a channel's `ChannelMonitorUpdate` flow is blocked waiting on an event to
3019+
// be handled HTLC preimage `ChannelMonitorUpdate`s will still go out.
3020+
let chanmon_cfgs = create_chanmon_cfgs(3);
3021+
let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3022+
let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3023+
let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3024+
3025+
create_announced_chan_between_nodes(&nodes, 0, 1).2;
3026+
create_announced_chan_between_nodes(&nodes, 1, 2).2;
3027+
3028+
send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 5_000_000);
3029+
3030+
// Tee up two payments in opposite directions across nodes[1], one it sent to generate a
3031+
// PaymentSent event and one it forwards.
3032+
let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[1], &[&nodes[2]], 1_000_000);
3033+
let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[2], &[&nodes[1], &nodes[0]], 1_000_000);
3034+
3035+
// Claim the first payment to get a `PaymentSent` event (but don't handle it yet).
3036+
nodes[2].node.claim_funds(payment_preimage_1);
3037+
check_added_monitors(&nodes[2], 1);
3038+
expect_payment_claimed!(nodes[2], payment_hash_1, 1_000_000);
3039+
3040+
let cs_htlc_fulfill_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3041+
nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &cs_htlc_fulfill_updates.update_fulfill_htlcs[0]);
3042+
commitment_signed_dance!(nodes[1], nodes[2], cs_htlc_fulfill_updates.commitment_signed, false);
3043+
check_added_monitors(&nodes[1], 0);
3044+
3045+
// Now claim the second payment on nodes[0], which will ultimately result in nodes[1] trying to
3046+
// claim an HTLC on its channel with nodes[2], but that channel is blocked on the above
3047+
// `PaymentSent` event.
3048+
nodes[0].node.claim_funds(payment_preimage_2);
3049+
check_added_monitors(&nodes[0], 1);
3050+
expect_payment_claimed!(nodes[0], payment_hash_2, 1_000_000);
3051+
3052+
let as_htlc_fulfill_updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3053+
nodes[1].node.handle_update_fulfill_htlc(&nodes[0].node.get_our_node_id(), &as_htlc_fulfill_updates.update_fulfill_htlcs[0]);
3054+
check_added_monitors(&nodes[1], 1); // We generate only a preimage monitor update
3055+
assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3056+
3057+
// Finish the CS dance between nodes[0] and nodes[1].
3058+
commitment_signed_dance!(nodes[1], nodes[0], as_htlc_fulfill_updates.commitment_signed, false);
3059+
check_added_monitors(&nodes[1], 0);
3060+
3061+
let events = nodes[1].node.get_and_clear_pending_events();
3062+
assert_eq!(events.len(), 3);
3063+
if let Event::PaymentSent { .. } = events[0] {} else { panic!(); }
3064+
if let Event::PaymentPathSuccessful { .. } = events[2] {} else { panic!(); }
3065+
if let Event::PaymentForwarded { .. } = events[1] {} else { panic!(); }
3066+
3067+
// The event processing should release the last RAA update.
3068+
check_added_monitors(&nodes[1], 1);
3069+
3070+
// When we fetch the next update the message getter will generate the next update for nodes[2],
3071+
// generating a further monitor update.
3072+
let bs_htlc_fulfill_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
3073+
check_added_monitors(&nodes[1], 1);
3074+
3075+
nodes[2].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_htlc_fulfill_updates.update_fulfill_htlcs[0]);
3076+
commitment_signed_dance!(nodes[2], nodes[1], bs_htlc_fulfill_updates.commitment_signed, false);
3077+
expect_payment_sent(&nodes[2], payment_preimage_2, None, true, true);
3078+
}

lightning/src/ln/channel.rs

+32-8
Original file line numberDiff line numberDiff line change
@@ -3223,7 +3223,7 @@ impl<Signer: WriteableEcdsaChannelSigner> Channel<Signer> {
32233223
/// generating an appropriate error *after* the channel state has been updated based on the
32243224
/// revoke_and_ack message.
32253225
pub fn revoke_and_ack<F: Deref, L: Deref>(&mut self, msg: &msgs::RevokeAndACK,
3226-
fee_estimator: &LowerBoundedFeeEstimator<F>, logger: &L
3226+
fee_estimator: &LowerBoundedFeeEstimator<F>, logger: &L, hold_mon_update: bool,
32273227
) -> Result<(Vec<(HTLCSource, PaymentHash)>, Option<ChannelMonitorUpdate>), ChannelError>
32283228
where F::Target: FeeEstimator, L::Target: Logger,
32293229
{
@@ -3404,6 +3404,22 @@ impl<Signer: WriteableEcdsaChannelSigner> Channel<Signer> {
34043404
}
34053405
}
34063406

3407+
let release_monitor = self.context.blocked_monitor_updates.is_empty() && !hold_mon_update;
3408+
let release_state_str =
3409+
if hold_mon_update { "Holding" } else if release_monitor { "Releasing" } else { "Blocked" };
3410+
macro_rules! return_with_htlcs_to_fail {
3411+
($htlcs_to_fail: expr) => {
3412+
if !release_monitor {
3413+
self.context.blocked_monitor_updates.push(PendingChannelMonitorUpdate {
3414+
update: monitor_update,
3415+
});
3416+
return Ok(($htlcs_to_fail, None));
3417+
} else {
3418+
return Ok(($htlcs_to_fail, Some(monitor_update)));
3419+
}
3420+
}
3421+
}
3422+
34073423
if (self.context.channel_state & ChannelState::MonitorUpdateInProgress as u32) == ChannelState::MonitorUpdateInProgress as u32 {
34083424
// We can't actually generate a new commitment transaction (incl by freeing holding
34093425
// cells) while we can't update the monitor, so we just return what we have.
@@ -3422,7 +3438,7 @@ impl<Signer: WriteableEcdsaChannelSigner> Channel<Signer> {
34223438
self.context.monitor_pending_failures.append(&mut revoked_htlcs);
34233439
self.context.monitor_pending_finalized_fulfills.append(&mut finalized_claimed_htlcs);
34243440
log_debug!(logger, "Received a valid revoke_and_ack for channel {} but awaiting a monitor update resolution to reply.", log_bytes!(self.context.channel_id()));
3425-
return Ok((Vec::new(), self.push_ret_blockable_mon_update(monitor_update)));
3441+
return_with_htlcs_to_fail!(Vec::new());
34263442
}
34273443

34283444
match self.free_holding_cell_htlcs(fee_estimator, logger) {
@@ -3432,8 +3448,11 @@ impl<Signer: WriteableEcdsaChannelSigner> Channel<Signer> {
34323448
self.context.latest_monitor_update_id = monitor_update.update_id;
34333449
monitor_update.updates.append(&mut additional_update.updates);
34343450

3451+
log_debug!(logger, "Received a valid revoke_and_ack for channel {} with holding cell HTLCs freed. {} monitor update.",
3452+
log_bytes!(self.context.channel_id()), release_state_str);
3453+
34353454
self.monitor_updating_paused(false, true, false, to_forward_infos, revoked_htlcs, finalized_claimed_htlcs);
3436-
Ok((htlcs_to_fail, self.push_ret_blockable_mon_update(monitor_update)))
3455+
return_with_htlcs_to_fail!(htlcs_to_fail);
34373456
},
34383457
(None, htlcs_to_fail) => {
34393458
if require_commitment {
@@ -3444,14 +3463,19 @@ impl<Signer: WriteableEcdsaChannelSigner> Channel<Signer> {
34443463
self.context.latest_monitor_update_id = monitor_update.update_id;
34453464
monitor_update.updates.append(&mut additional_update.updates);
34463465

3447-
log_debug!(logger, "Received a valid revoke_and_ack for channel {}. Responding with a commitment update with {} HTLCs failed.",
3448-
log_bytes!(self.context.channel_id()), update_fail_htlcs.len() + update_fail_malformed_htlcs.len());
3466+
log_debug!(logger, "Received a valid revoke_and_ack for channel {}. Responding with a commitment update with {} HTLCs failed. {} monitor update.",
3467+
log_bytes!(self.context.channel_id()),
3468+
update_fail_htlcs.len() + update_fail_malformed_htlcs.len(),
3469+
release_state_str);
3470+
34493471
self.monitor_updating_paused(false, true, false, to_forward_infos, revoked_htlcs, finalized_claimed_htlcs);
3450-
Ok((htlcs_to_fail, self.push_ret_blockable_mon_update(monitor_update)))
3472+
return_with_htlcs_to_fail!(htlcs_to_fail);
34513473
} else {
3452-
log_debug!(logger, "Received a valid revoke_and_ack for channel {} with no reply necessary.", log_bytes!(self.context.channel_id()));
3474+
log_debug!(logger, "Received a valid revoke_and_ack for channel {} with no reply necessary. {} monitor update.",
3475+
log_bytes!(self.context.channel_id()), release_state_str);
3476+
34533477
self.monitor_updating_paused(false, false, false, to_forward_infos, revoked_htlcs, finalized_claimed_htlcs);
3454-
Ok((htlcs_to_fail, self.push_ret_blockable_mon_update(monitor_update)))
3478+
return_with_htlcs_to_fail!(htlcs_to_fail);
34553479
}
34563480
}
34573481
}

0 commit comments

Comments
 (0)