Skip to content

Commit 57a4288

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 4e99025 commit 57a4288

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<(), ()> {
@@ -3603,6 +3604,44 @@ impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelMana
36033604
});
36043605
}
36053606

3607+
fn timeout_resolved_payments(&self) {
3608+
// If an outbound payment was completed, and no pending HTLCs remain, we should remove it
3609+
// from the map. However, if we did that immediately when the payment completes, this could
3610+
// race the user sending a duplicate payment (and relying on our idempotency guarantees on
3611+
// send_payment to avoid actually sending). Instead, we wait two timer ticks to do the
3612+
// actual removal. This should be more than sufficient to ensure and `send_payment` calls
3613+
// which were made at the same time the `PaymentSent` event was being processed complete.
3614+
let mut pending_outbound_payments = self.pending_outbound_payments.lock().unwrap();
3615+
let pending_events = self.pending_events.lock().unwrap();
3616+
pending_outbound_payments.retain(|payment_id, payment| {
3617+
if let PendingOutboundPayment::Fulfilled { session_privs, timer_ticks_without_htlcs, .. } = payment {
3618+
let mut no_remaining_entries = session_privs.is_empty();
3619+
if no_remaining_entries {
3620+
for ev in pending_events.iter() {
3621+
match ev {
3622+
events::Event::PaymentSent { payment_id: Some(ev_payment_id), .. }|
3623+
events::Event::PaymentPathSuccessful { payment_id: ev_payment_id, .. }|
3624+
events::Event::PaymentPathFailed { payment_id: Some(ev_payment_id), .. } => {
3625+
if payment_id == ev_payment_id {
3626+
no_remaining_entries = false;
3627+
break;
3628+
}
3629+
},
3630+
_ => {},
3631+
}
3632+
}
3633+
}
3634+
if no_remaining_entries {
3635+
*timer_ticks_without_htlcs += 1;
3636+
*timer_ticks_without_htlcs <= 3
3637+
} else {
3638+
*timer_ticks_without_htlcs = 0;
3639+
true
3640+
}
3641+
} else { true }
3642+
});
3643+
}
3644+
36063645
/// Performs actions which should happen on startup and roughly once per minute thereafter.
36073646
///
36083647
/// This currently includes:
@@ -3706,6 +3745,9 @@ impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelMana
37063745
for (err, counterparty_node_id) in handle_errors.drain(..) {
37073746
let _ = handle_error!(self, err, counterparty_node_id);
37083747
}
3748+
3749+
self.timeout_resolved_payments();
3750+
37093751
should_persist
37103752
});
37113753
}
@@ -4223,9 +4265,6 @@ impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelMana
42234265
}
42244266
);
42254267
}
4226-
if payment.get().remaining_parts() == 0 {
4227-
payment.remove();
4228-
}
42294268
}
42304269
}
42314270
}
@@ -4271,10 +4310,6 @@ impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelMana
42714310
}
42724311
);
42734312
}
4274-
4275-
if payment.get().remaining_parts() == 0 {
4276-
payment.remove();
4277-
}
42784313
}
42794314
} else {
42804315
log_trace!(self.logger, "Received duplicative fulfill for HTLC with payment_preimage {}", log_bytes!(payment_preimage.0));
@@ -6599,6 +6634,7 @@ impl_writeable_tlv_based_enum_upgradable!(PendingOutboundPayment,
65996634
(1, Fulfilled) => {
66006635
(0, session_privs, required),
66016636
(1, payment_hash, option),
6637+
(3, timer_ticks_without_htlcs, (default_value, 0)),
66026638
},
66036639
(2, Retryable) => {
66046640
(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)