Skip to content

Commit 1812655

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 4267436 commit 1812655

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<(), ()> {
@@ -3618,6 +3619,44 @@ impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelMana
36183619
});
36193620
}
36203621

3622+
fn timeout_resolved_payments(&self) {
3623+
// If an outbound payment was completed, and no pending HTLCs remain, we should remove it
3624+
// from the map. However, if we did that immediately when the payment completes, this could
3625+
// race the user sending a duplicate payment (and relying on our idempotency guarantees on
3626+
// send_payment to avoid actually sending). Instead, we wait two timer ticks to do the
3627+
// actual removal. This should be more than sufficient to ensure and `send_payment` calls
3628+
// which were made at the same time the `PaymentSent` event was being processed complete.
3629+
let mut pending_outbound_payments = self.pending_outbound_payments.lock().unwrap();
3630+
let pending_events = self.pending_events.lock().unwrap();
3631+
pending_outbound_payments.retain(|payment_id, payment| {
3632+
if let PendingOutboundPayment::Fulfilled { session_privs, timer_ticks_without_htlcs, .. } = payment {
3633+
let mut no_remaining_entries = session_privs.is_empty();
3634+
if no_remaining_entries {
3635+
for ev in pending_events.iter() {
3636+
match ev {
3637+
events::Event::PaymentSent { payment_id: Some(ev_payment_id), .. }|
3638+
events::Event::PaymentPathSuccessful { payment_id: ev_payment_id, .. }|
3639+
events::Event::PaymentPathFailed { payment_id: Some(ev_payment_id), .. } => {
3640+
if payment_id == ev_payment_id {
3641+
no_remaining_entries = false;
3642+
break;
3643+
}
3644+
},
3645+
_ => {},
3646+
}
3647+
}
3648+
}
3649+
if no_remaining_entries {
3650+
*timer_ticks_without_htlcs += 1;
3651+
*timer_ticks_without_htlcs <= 3
3652+
} else {
3653+
*timer_ticks_without_htlcs = 0;
3654+
true
3655+
}
3656+
} else { true }
3657+
});
3658+
}
3659+
36213660
/// Performs actions which should happen on startup and roughly once per minute thereafter.
36223661
///
36233662
/// This currently includes:
@@ -3721,6 +3760,9 @@ impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelMana
37213760
for (err, counterparty_node_id) in handle_errors.drain(..) {
37223761
let _ = handle_error!(self, err, counterparty_node_id);
37233762
}
3763+
3764+
self.timeout_resolved_payments();
3765+
37243766
should_persist
37253767
});
37263768
}
@@ -4238,9 +4280,6 @@ impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelMana
42384280
}
42394281
);
42404282
}
4241-
if payment.get().remaining_parts() == 0 {
4242-
payment.remove();
4243-
}
42444283
}
42454284
}
42464285
}
@@ -4286,10 +4325,6 @@ impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelMana
42864325
}
42874326
);
42884327
}
4289-
4290-
if payment.get().remaining_parts() == 0 {
4291-
payment.remove();
4292-
}
42934328
}
42944329
} else {
42954330
log_trace!(self.logger, "Received duplicative fulfill for HTLC with payment_preimage {}", log_bytes!(payment_preimage.0));
@@ -6614,6 +6649,7 @@ impl_writeable_tlv_based_enum_upgradable!(PendingOutboundPayment,
66146649
(1, Fulfilled) => {
66156650
(0, session_privs, required),
66166651
(1, payment_hash, option),
6652+
(3, timer_ticks_without_htlcs, (default_value, 0)),
66176653
},
66186654
(2, Retryable) => {
66196655
(0, session_privs, required),

lightning/src/ln/payment_tests.rs

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

0 commit comments

Comments
 (0)