Skip to content

Commit 7809c55

Browse files
Automatically fail intercepts back on timeout
1 parent ddcd9b0 commit 7809c55

File tree

2 files changed

+73
-12
lines changed

2 files changed

+73
-12
lines changed

lightning/src/ln/channelmanager.rs

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3067,6 +3067,9 @@ impl<M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<M, T, K, F
30673067
/// Note that LDK does not enforce fee requirements in `amt_to_forward_msat`, and will not stop
30683068
/// you from forwarding more than you received.
30693069
///
3070+
/// Errors if the event was not handled in time, in which case the HTLC was automatically failed
3071+
/// backwards.
3072+
///
30703073
/// [`UserConfig::accept_intercept_htlcs`]: crate::util::config::UserConfig::accept_intercept_htlcs
30713074
/// [`HTLCIntercepted`]: events::Event::HTLCIntercepted
30723075
// TODO: when we move to deciding the best outbound channel at forward time, only take
@@ -3109,6 +3112,9 @@ impl<M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<M, T, K, F
31093112
/// Fails the intercepted HTLC indicated by intercept_id. Should only be called in response to
31103113
/// an [`HTLCIntercepted`] event. See [`ChannelManager::forward_intercepted_htlc`].
31113114
///
3115+
/// Errors if the event was not handled in time, in which case the HTLC was automatically failed
3116+
/// backwards.
3117+
///
31123118
/// [`HTLCIntercepted`]: events::Event::HTLCIntercepted
31133119
pub fn fail_intercepted_htlc(&self, intercept_id: InterceptId) -> Result<(), APIError> {
31143120
let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
@@ -6256,7 +6262,6 @@ where
62566262
if height >= htlc.cltv_expiry - HTLC_FAIL_BACK_BUFFER {
62576263
let mut htlc_msat_height_data = byte_utils::be64_to_array(htlc.value).to_vec();
62586264
htlc_msat_height_data.extend_from_slice(&byte_utils::be32_to_array(height));
6259-
62606265
timed_out_htlcs.push((HTLCSource::PreviousHopData(htlc.prev_hop.clone()), payment_hash.clone(), HTLCFailReason::Reason {
62616266
failure_code: 0x4000 | 15,
62626267
data: htlc_msat_height_data
@@ -6266,6 +6271,29 @@ where
62666271
});
62676272
!htlcs.is_empty() // Only retain this entry if htlcs has at least one entry.
62686273
});
6274+
6275+
let mut intercepted_htlcs = self.pending_intercepted_htlcs.lock().unwrap();
6276+
intercepted_htlcs.retain(|_, htlc| {
6277+
if height >= htlc.forward_info.outgoing_cltv_value - HTLC_FAIL_BACK_BUFFER {
6278+
let prev_hop_data = HTLCSource::PreviousHopData(HTLCPreviousHopData {
6279+
short_channel_id: htlc.prev_short_channel_id,
6280+
htlc_id: htlc.prev_htlc_id,
6281+
incoming_packet_shared_secret: htlc.forward_info.incoming_shared_secret,
6282+
phantom_shared_secret: None,
6283+
outpoint: htlc.prev_funding_outpoint,
6284+
});
6285+
6286+
let requested_forward_scid /* intercept scid */ = match htlc.forward_info.routing {
6287+
PendingHTLCRouting::Forward { short_channel_id, .. } => short_channel_id,
6288+
_ => unreachable!(),
6289+
};
6290+
timed_out_htlcs.push((prev_hop_data, htlc.forward_info.payment_hash,
6291+
HTLCFailReason::Reason { failure_code: 0x2000 | 2, data: Vec::new() },
6292+
HTLCDestination::InvalidForward { requested_forward_scid }));
6293+
log_trace!(self.logger, "Timing out intercepted HTLC with requested forward scid {}", requested_forward_scid);
6294+
false
6295+
} else { true }
6296+
});
62696297
}
62706298

62716299
self.handle_init_event_channel_failures(failed_channels);

lightning/src/ln/payment_tests.rs

Lines changed: 44 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ use crate::chain::channelmonitor::{ANTI_REORG_DELAY, LATENCY_GRACE_PERIOD_BLOCKS
1616
use crate::chain::transaction::OutPoint;
1717
use crate::chain::keysinterface::KeysInterface;
1818
use crate::ln::channel::EXPIRE_PREV_CONFIG_TICKS;
19-
use crate::ln::channelmanager::{self, BREAKDOWN_TIMEOUT, ChannelManager, InterceptId, MPP_TIMEOUT_TICKS, MIN_CLTV_EXPIRY_DELTA, PaymentId, PaymentSendFailure, IDEMPOTENCY_TIMEOUT_TICKS};
19+
use crate::ln::channelmanager::{self, BREAKDOWN_TIMEOUT, ChannelManager, MPP_TIMEOUT_TICKS, MIN_CLTV_EXPIRY_DELTA, PaymentId, PaymentSendFailure, IDEMPOTENCY_TIMEOUT_TICKS};
2020
use crate::ln::msgs;
2121
use crate::ln::msgs::ChannelMessageHandler;
2222
use crate::routing::gossip::RoutingFees;
@@ -1243,6 +1243,13 @@ fn abandoned_send_payment_idempotent() {
12431243
claim_payment(&nodes[0], &[&nodes[1]], second_payment_preimage);
12441244
}
12451245

1246+
#[derive(PartialEq)]
1247+
enum InterceptTest {
1248+
Forward,
1249+
Fail,
1250+
Timeout,
1251+
}
1252+
12461253
#[test]
12471254
fn test_trivial_inflight_htlc_tracking(){
12481255
// In this test, we test three scenarios:
@@ -1378,11 +1385,13 @@ fn intercepted_payment() {
13781385
// Test that detecting an intercept scid on payment forward will signal LDK to generate an
13791386
// intercept event, which the LSP can then use to either (a) open a JIT channel to forward the
13801387
// payment or (b) fail the payment.
1381-
do_test_intercepted_payment(false);
1382-
do_test_intercepted_payment(true);
1388+
do_test_intercepted_payment(InterceptTest::Forward);
1389+
do_test_intercepted_payment(InterceptTest::Fail);
1390+
// Make sure that intercepted payments will be automatically failed back if too many blocks pass.
1391+
do_test_intercepted_payment(InterceptTest::Timeout);
13831392
}
13841393

1385-
fn do_test_intercepted_payment(fail_intercept: bool) {
1394+
fn do_test_intercepted_payment(test: InterceptTest) {
13861395
let chanmon_cfgs = create_chanmon_cfgs(3);
13871396
let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
13881397

@@ -1459,7 +1468,7 @@ fn do_test_intercepted_payment(fail_intercept: bool) {
14591468
let unknown_chan_id_err = nodes[1].node.forward_intercepted_htlc(intercept_id, &[42; 32], nodes[2].node.get_our_node_id(), expected_outbound_amount_msat).unwrap_err();
14601469
assert_eq!(unknown_chan_id_err , APIError::APIMisuseError { err: format!("Channel with id {:?} not found", [42; 32]) });
14611470

1462-
if fail_intercept {
1471+
if test == InterceptTest::Fail {
14631472
// Ensure we can fail the intercepted payment back.
14641473
nodes[1].node.fail_intercepted_htlc(intercept_id).unwrap();
14651474
expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::UnknownNextHop { requested_forward_scid: intercept_scid }]);
@@ -1477,15 +1486,10 @@ fn do_test_intercepted_payment(fail_intercept: bool) {
14771486
.blamed_chan_closed(true)
14781487
.expected_htlc_error_data(0x4000 | 10, &[]);
14791488
expect_payment_failed_conditions(&nodes[0], payment_hash, false, fail_conditions);
1480-
} else {
1489+
} else if test == InterceptTest::Forward {
14811490
// Open the just-in-time channel so the payment can then be forwarded.
14821491
let (_, channel_id) = open_zero_conf_channel(&nodes[1], &nodes[2], None);
14831492

1484-
// Check for unknown intercept id error.
1485-
let unknown_intercept_id = InterceptId([42; 32]);
1486-
let unknown_intercept_id_err = nodes[1].node.forward_intercepted_htlc(unknown_intercept_id, &channel_id, nodes[2].node.get_our_node_id(), expected_outbound_amount_msat).unwrap_err();
1487-
assert_eq!(unknown_intercept_id_err , APIError::APIMisuseError { err: format!("Payment with intercept id {:?} not found", unknown_intercept_id.0) });
1488-
14891493
// Finally, forward the intercepted payment through and claim it.
14901494
nodes[1].node.forward_intercepted_htlc(intercept_id, &channel_id, nodes[2].node.get_our_node_id(), expected_outbound_amount_msat).unwrap();
14911495
expect_pending_htlcs_forwardable!(nodes[1]);
@@ -1523,5 +1527,34 @@ fn do_test_intercepted_payment(fail_intercept: bool) {
15231527
},
15241528
_ => panic!("Unexpected event")
15251529
}
1530+
} else if test == InterceptTest::Timeout {
1531+
let mut block = Block {
1532+
header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
1533+
txdata: vec![],
1534+
};
1535+
connect_block(&nodes[0], &block);
1536+
connect_block(&nodes[1], &block);
1537+
let block_count = 183; // find_route adds a random CLTV offset, so hardcode rather than summing consts
1538+
for _ in 0..block_count {
1539+
block.header.prev_blockhash = block.block_hash();
1540+
connect_block(&nodes[0], &block);
1541+
connect_block(&nodes[1], &block);
1542+
}
1543+
expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::InvalidForward { requested_forward_scid: intercept_scid }]);
1544+
check_added_monitors!(nodes[1], 1);
1545+
let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1546+
assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
1547+
assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
1548+
assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
1549+
assert!(htlc_timeout_updates.update_fee.is_none());
1550+
1551+
nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
1552+
commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
1553+
expect_payment_failed!(nodes[0], payment_hash, false, 0x2000 | 2, []);
1554+
1555+
// Check for unknown intercept id error.
1556+
let (_, channel_id) = open_zero_conf_channel(&nodes[1], &nodes[2], None);
1557+
let unknown_intercept_id_err = nodes[1].node.forward_intercepted_htlc(intercept_id, &channel_id, nodes[2].node.get_our_node_id(), expected_outbound_amount_msat).unwrap_err();
1558+
assert_eq!(unknown_intercept_id_err , APIError::APIMisuseError { err: format!("Payment with intercept id {:?} not found", intercept_id.0) });
15261559
}
15271560
}

0 commit comments

Comments
 (0)