Skip to content

Commit 0204741

Browse files
committed
Delay removal of fulfilled outbound payments for three timer ticks
Previously, once a fulfilled outbound payment completed and all associated HTLCs were resolved, we'd immediately remove the payment entry from the `pending_outbound_payments` map. Now that we're using the `pending_outbound_payments` map for send idempotency, this presents a race condition - if the user makes a redundant `send_payment` call at the same time that the original payment's last HTLC is resolved, the user would reasonably expect the `send_payment` call to fail due to our idempotency guarantees. However, because the `pending_outbound_payments` entry is being removed, if it completes first the `send_payment` call will succeed even though the user has not had a chance to see the corresponding `Event::PaymentSent`. Instead, here, we delay removal of `Fulfilled` `pending_outbound_payments` entries until several timer ticks have passed without any corresponding event or HTLC pending.
1 parent df8aa67 commit 0204741

File tree

2 files changed

+115
-8
lines changed

2 files changed

+115
-8
lines changed

lightning/src/ln/channelmanager.rs

Lines changed: 44 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -473,6 +473,7 @@ pub(crate) enum PendingOutboundPayment {
473473
Fulfilled {
474474
session_privs: HashSet<[u8; 32]>,
475475
payment_hash: Option<PaymentHash>,
476+
timer_ticks_without_htlcs: u8,
476477
},
477478
/// When a payer gives up trying to retry a payment, they inform us, letting us generate a
478479
/// `PaymentFailed` event when all HTLCs have irrevocably failed. This avoids a number of race
@@ -532,7 +533,7 @@ impl PendingOutboundPayment {
532533
=> session_privs,
533534
});
534535
let payment_hash = self.payment_hash();
535-
*self = PendingOutboundPayment::Fulfilled { session_privs, payment_hash };
536+
*self = PendingOutboundPayment::Fulfilled { session_privs, payment_hash, timer_ticks_without_htlcs: 0 };
536537
}
537538

538539
fn mark_abandoned(&mut self) -> Result<(), ()> {
@@ -3601,6 +3602,44 @@ impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelMana
36013602
});
36023603
}
36033604

3605+
fn timeout_resolved_payments(&self) {
3606+
// If an outbound payment was completed, and no pending HTLCs remain, we should remove it
3607+
// from the map. However, if we did that immediately when the payment completes, this could
3608+
// race the user sending a duplicate payment (and relying on our idempotency guarantees on
3609+
// send_payment to avoid actually sending). Instead, we wait two timer ticks to do the
3610+
// actual removal. This should be more than sufficient to ensure and `send_payment` calls
3611+
// which were made at the same time the `PaymentSent` event was being processed complete.
3612+
let mut pending_outbound_payments = self.pending_outbound_payments.lock().unwrap();
3613+
let pending_events = self.pending_events.lock().unwrap();
3614+
pending_outbound_payments.retain(|payment_id, payment| {
3615+
if let PendingOutboundPayment::Fulfilled { session_privs, timer_ticks_without_htlcs, .. } = payment {
3616+
let mut no_remaining_entries = session_privs.is_empty();
3617+
if no_remaining_entries {
3618+
for ev in pending_events.iter() {
3619+
match ev {
3620+
events::Event::PaymentSent { payment_id: Some(ev_payment_id), .. }|
3621+
events::Event::PaymentPathSuccessful { payment_id: ev_payment_id, .. }|
3622+
events::Event::PaymentPathFailed { payment_id: Some(ev_payment_id), .. } => {
3623+
if payment_id == ev_payment_id {
3624+
no_remaining_entries = false;
3625+
break;
3626+
}
3627+
},
3628+
_ => {},
3629+
}
3630+
}
3631+
}
3632+
if no_remaining_entries {
3633+
*timer_ticks_without_htlcs += 1;
3634+
*timer_ticks_without_htlcs <= 3
3635+
} else {
3636+
*timer_ticks_without_htlcs = 0;
3637+
true
3638+
}
3639+
} else { true }
3640+
});
3641+
}
3642+
36043643
/// Performs actions which should happen on startup and roughly once per minute thereafter.
36053644
///
36063645
/// This currently includes:
@@ -3704,6 +3743,9 @@ impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelMana
37043743
for (err, counterparty_node_id) in handle_errors.drain(..) {
37053744
let _ = handle_error!(self, err, counterparty_node_id);
37063745
}
3746+
3747+
self.timeout_resolved_payments();
3748+
37073749
should_persist
37083750
});
37093751
}
@@ -4221,9 +4263,6 @@ impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelMana
42214263
}
42224264
);
42234265
}
4224-
if payment.get().remaining_parts() == 0 {
4225-
payment.remove();
4226-
}
42274266
}
42284267
}
42294268
}
@@ -4269,10 +4308,6 @@ impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelMana
42694308
}
42704309
);
42714310
}
4272-
4273-
if payment.get().remaining_parts() == 0 {
4274-
payment.remove();
4275-
}
42764311
}
42774312
} else {
42784313
log_trace!(self.logger, "Received duplicative fulfill for HTLC with payment_preimage {}", log_bytes!(payment_preimage.0));
@@ -6597,6 +6632,7 @@ impl_writeable_tlv_based_enum_upgradable!(PendingOutboundPayment,
65976632
(1, Fulfilled) => {
65986633
(0, session_privs, required),
65996634
(1, payment_hash, option),
6635+
(3, timer_ticks_without_htlcs, (default_value, 0)),
66006636
},
66016637
(2, Retryable) => {
66026638
(0, session_privs, required),

lightning/src/ln/payment_tests.rs

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1255,3 +1255,74 @@ fn onchain_failed_probe_yields_event() {
12551255
}
12561256
assert!(found_probe_failed);
12571257
}
1258+
1259+
#[test]
1260+
fn claimed_send_payment_idempotent() {
1261+
// Tests that `send_payment` (and friends) are (reasonably) idempotent.
1262+
let chanmon_cfgs = create_chanmon_cfgs(2);
1263+
let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1264+
let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1265+
let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1266+
1267+
create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
1268+
1269+
let (route, second_payment_hash, second_payment_preimage, second_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
1270+
let (first_payment_preimage, _, _, payment_id) = send_along_route(&nodes[0], route.clone(), &[&nodes[1]], 100_000);
1271+
1272+
macro_rules! check_send_rejected {
1273+
() => {
1274+
// If we try to resend a new payment with a different payment_hash but with the same
1275+
// payment_id, it should be rejected.
1276+
let send_result = nodes[0].node.send_payment(&route, second_payment_hash, &Some(second_payment_secret), payment_id);
1277+
match send_result {
1278+
Err(PaymentSendFailure::ParameterError(APIError::RouteError { err: "Payment already in progress" })) => {},
1279+
_ => panic!("Unexpected send result: {:?}", send_result),
1280+
}
1281+
1282+
// Further, if we try to send a spontaneous payment with the same payment_id it should
1283+
// also be rejected.
1284+
let send_result = nodes[0].node.send_spontaneous_payment(&route, None, payment_id);
1285+
match send_result {
1286+
Err(PaymentSendFailure::ParameterError(APIError::RouteError { err: "Payment already in progress" })) => {},
1287+
_ => panic!("Unexpected send result: {:?}", send_result),
1288+
}
1289+
}
1290+
}
1291+
1292+
check_send_rejected!();
1293+
1294+
// Claim the payment backwards, but note that the PaymentSent event is still pending and has
1295+
// not been seen by the user. At this point, from the user perspective nothing has changed, so
1296+
// we must remain just as idempotent as we were before.
1297+
do_claim_payment_along_route(&nodes[0], &[&[&nodes[1]]], false, first_payment_preimage);
1298+
1299+
nodes[0].node.timer_tick_occurred();
1300+
nodes[0].node.timer_tick_occurred();
1301+
nodes[0].node.timer_tick_occurred();
1302+
nodes[0].node.timer_tick_occurred();
1303+
1304+
check_send_rejected!();
1305+
1306+
// Once the user sees and handles the `PaymentSent` event, we expect them to no longer call
1307+
// `send_payment`, and our idempotency guarantees are off - they should have atomically marked
1308+
// the payment complete. However, they could have called `send_payment` while the event was
1309+
// being processed, leading to a race in our idempotency guarantees. Thus, even immediately
1310+
// after the event is handled a duplicate payment should sitll be rejected.
1311+
expect_payment_sent!(&nodes[0], first_payment_preimage, Some(0));
1312+
check_send_rejected!();
1313+
1314+
// However, after some time has passed (at least more than one timer tick), a duplicate payment
1315+
// should go through, as ChannelManager should no longer have any remaining references to the
1316+
// old payment data.
1317+
nodes[0].node.timer_tick_occurred();
1318+
check_send_rejected!();
1319+
1320+
nodes[0].node.timer_tick_occurred();
1321+
nodes[0].node.timer_tick_occurred();
1322+
nodes[0].node.timer_tick_occurred();
1323+
1324+
nodes[0].node.send_payment(&route, second_payment_hash, &Some(second_payment_secret), payment_id).unwrap();
1325+
check_added_monitors!(nodes[0], 1);
1326+
pass_along_route(&nodes[0], &[&[&nodes[1]]], 100_000, second_payment_hash, second_payment_secret);
1327+
claim_payment(&nodes[0], &[&nodes[1]], second_payment_preimage);
1328+
}

0 commit comments

Comments
 (0)