Skip to content

Commit c9483c6

Browse files
committed
Time out incoming HTLCs when we reach cltv_expiry (+ test)
We only do this for incoming HTLCs directly as we rely on channel closure and HTLC-Timeout broadcast to fail any HTLCs which we relayed onwards where our next-hop doesn't update_fail in time.
1 parent f0e9524 commit c9483c6

File tree

4 files changed

+110
-8
lines changed

4 files changed

+110
-8
lines changed

lightning/src/ln/channelmanager.rs

Lines changed: 40 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ use secp256k1;
2828
use chain::chaininterface::{BroadcasterInterface,ChainListener,FeeEstimator};
2929
use chain::transaction::OutPoint;
3030
use ln::channel::{Channel, ChannelError};
31-
use ln::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateErr, ManyChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
31+
use ln::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateErr, ManyChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY, HTLC_FAIL_BACK_BUFFER};
3232
use ln::features::{InitFeatures, NodeFeatures};
3333
use ln::router::{Route, RouteHop};
3434
use ln::msgs;
@@ -76,6 +76,7 @@ enum PendingHTLCRouting {
7676
},
7777
Receive {
7878
payment_data: Option<msgs::FinalOnionHopData>,
79+
incoming_cltv_expiry: u32, // Used to track when we should expire pending HTLCs that go unclaimed
7980
},
8081
}
8182

@@ -129,6 +130,7 @@ struct ClaimableHTLC {
129130
/// payment_secret which prevents path-probing attacks and can associate different HTLCs which
130131
/// are part of the same payment.
131132
payment_data: Option<msgs::FinalOnionHopData>,
133+
cltv_expiry: u32,
132134
}
133135

134136
/// Tracks the inbound corresponding to an outbound HTLC
@@ -296,8 +298,6 @@ pub(super) struct ChannelHolder<ChanSigner: ChannelKeys> {
296298
/// Note that while this is held in the same mutex as the channels themselves, no consistency
297299
/// guarantees are made about the channels given here actually existing anymore by the time you
298300
/// go to read them!
299-
/// TODO: We need to time out HTLCs sitting here which are waiting on other AMP HTLCs to
300-
/// arrive.
301301
claimable_htlcs: HashMap<(PaymentHash, Option<PaymentSecret>), Vec<ClaimableHTLC>>,
302302
/// Messages to send to peers - pushed to in the same lock that they are generated in (except
303303
/// for broadcast messages, where ordering isn't as strict).
@@ -1063,7 +1063,10 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref> ChannelMan
10631063
// delay) once they've send us a commitment_signed!
10641064

10651065
PendingHTLCStatus::Forward(PendingHTLCInfo {
1066-
routing: PendingHTLCRouting::Receive { payment_data },
1066+
routing: PendingHTLCRouting::Receive {
1067+
payment_data,
1068+
incoming_cltv_expiry: msg.cltv_expiry,
1069+
},
10671070
payment_hash: msg.payment_hash.clone(),
10681071
incoming_shared_secret: shared_secret,
10691072
amt_to_forward: next_hop_data.amt_to_forward,
@@ -1686,7 +1689,7 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref> ChannelMan
16861689
for forward_info in pending_forwards.drain(..) {
16871690
match forward_info {
16881691
HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_htlc_id, forward_info: PendingHTLCInfo {
1689-
routing: PendingHTLCRouting::Receive { payment_data },
1692+
routing: PendingHTLCRouting::Receive { payment_data, incoming_cltv_expiry },
16901693
incoming_shared_secret, payment_hash, amt_to_forward, .. }, } => {
16911694
let prev_hop = HTLCPreviousHopData {
16921695
short_channel_id: prev_short_channel_id,
@@ -1703,6 +1706,7 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref> ChannelMan
17031706
prev_hop,
17041707
value: amt_to_forward,
17051708
payment_data: payment_data.clone(),
1709+
cltv_expiry: incoming_cltv_expiry,
17061710
});
17071711
if let &Some(ref data) = &payment_data {
17081712
for htlc in htlcs.iter() {
@@ -2958,6 +2962,7 @@ impl<ChanSigner: ChannelKeys, M: Deref + Sync + Send, T: Deref + Sync + Send, K:
29582962
log_trace!(self, "Block {} at height {} connected with {} txn matched", header_hash, height, txn_matched.len());
29592963
let _ = self.total_consistency_lock.read().unwrap();
29602964
let mut failed_channels = Vec::new();
2965+
let mut timed_out_htlcs = Vec::new();
29612966
{
29622967
let mut channel_lock = self.channel_state.lock().unwrap();
29632968
let channel_state = &mut *channel_lock;
@@ -3026,10 +3031,35 @@ impl<ChanSigner: ChannelKeys, M: Deref + Sync + Send, T: Deref + Sync + Send, K:
30263031
}
30273032
true
30283033
});
3034+
3035+
channel_state.claimable_htlcs.retain(|&(ref payment_hash, _), htlcs| {
3036+
htlcs.retain(|htlc| {
3037+
// If height is approaching the number of blocks we think it takes us to get
3038+
// our commitment transaction confirmed before the HTLC expires, plus the
3039+
// number of blocks we generally consider it to take to do a commitment update,
3040+
// just give up on it and fail the HTLC.
3041+
if height >= htlc.cltv_expiry - HTLC_FAIL_BACK_BUFFER {
3042+
let mut htlc_msat_height_data = byte_utils::be64_to_array(htlc.value).to_vec();
3043+
htlc_msat_height_data.extend_from_slice(&byte_utils::be32_to_array(height));
3044+
timed_out_htlcs.push((HTLCSource::PreviousHopData(htlc.prev_hop.clone()), payment_hash.clone(), HTLCFailReason::Reason {
3045+
failure_code: 0x4000 | 15,
3046+
data: htlc_msat_height_data
3047+
}));
3048+
false
3049+
} else { true }
3050+
});
3051+
!htlcs.is_empty() // Only retain this entry if htlcs has at least one entry.
3052+
});
30293053
}
30303054
for failure in failed_channels.drain(..) {
30313055
self.finish_force_close_channel(failure);
30323056
}
3057+
3058+
for (source, payment_hash, reason) in timed_out_htlcs.drain(..) {
3059+
// Call it incorrect_or_unknown_payment_details as the issue, ultimately, is that the
3060+
// user failed to provide us a preimage within the cltv_expiry time window.
3061+
self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), source, &payment_hash, reason);
3062+
}
30333063
self.latest_block_height.store(height as usize, Ordering::Release);
30343064
*self.last_block_hash.try_lock().expect("block_(dis)connected must not be called in parallel") = header_hash;
30353065
loop {
@@ -3320,9 +3350,10 @@ impl Writeable for PendingHTLCInfo {
33203350
onion_packet.write(writer)?;
33213351
short_channel_id.write(writer)?;
33223352
},
3323-
&PendingHTLCRouting::Receive { ref payment_data } => {
3353+
&PendingHTLCRouting::Receive { ref payment_data, ref incoming_cltv_expiry } => {
33243354
1u8.write(writer)?;
33253355
payment_data.write(writer)?;
3356+
incoming_cltv_expiry.write(writer)?;
33263357
},
33273358
}
33283359
self.incoming_shared_secret.write(writer)?;
@@ -3343,6 +3374,7 @@ impl Readable for PendingHTLCInfo {
33433374
},
33443375
1u8 => PendingHTLCRouting::Receive {
33453376
payment_data: Readable::read(reader)?,
3377+
incoming_cltv_expiry: Readable::read(reader)?,
33463378
},
33473379
_ => return Err(DecodeError::InvalidValue),
33483380
},
@@ -3415,7 +3447,8 @@ impl_writeable!(HTLCPreviousHopData, 0, {
34153447
impl_writeable!(ClaimableHTLC, 0, {
34163448
prev_hop,
34173449
value,
3418-
payment_data
3450+
payment_data,
3451+
cltv_expiry
34193452
});
34203453

34213454
impl Writeable for HTLCSource {

lightning/src/ln/functional_test_utils.rs

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -717,14 +717,20 @@ macro_rules! get_payment_preimage_hash {
717717
}
718718
}
719719

720-
macro_rules! expect_pending_htlcs_forwardable {
720+
macro_rules! expect_pending_htlcs_forwardable_ignore {
721721
($node: expr) => {{
722722
let events = $node.node.get_and_clear_pending_events();
723723
assert_eq!(events.len(), 1);
724724
match events[0] {
725725
Event::PendingHTLCsForwardable { .. } => { },
726726
_ => panic!("Unexpected event"),
727727
};
728+
}}
729+
}
730+
731+
macro_rules! expect_pending_htlcs_forwardable {
732+
($node: expr) => {{
733+
expect_pending_htlcs_forwardable_ignore!($node);
728734
$node.node.process_pending_htlc_forwards();
729735
}}
730736
}

lightning/src/ln/functional_tests.rs

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2320,6 +2320,8 @@ fn claim_htlc_outputs_single_tx() {
23202320
check_added_monitors!(nodes[0], 1);
23212321
nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
23222322
check_added_monitors!(nodes[1], 1);
2323+
expect_pending_htlcs_forwardable_ignore!(nodes[0]);
2324+
23232325
connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 200, true, header.bitcoin_hash());
23242326

23252327
let events = nodes[1].node.get_and_clear_pending_events();
@@ -3653,6 +3655,60 @@ fn test_drop_messages_peer_disconnect_dual_htlc() {
36533655
claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
36543656
}
36553657

3658+
#[test]
3659+
fn test_htlc_timeout() {
3660+
// If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
3661+
// to avoid our counterparty failing the channel.
3662+
let chanmon_cfgs = create_chanmon_cfgs(2);
3663+
let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3664+
let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3665+
let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3666+
3667+
create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
3668+
let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 100000);
3669+
3670+
let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3671+
nodes[0].block_notifier.block_connected_checked(&header, 101, &[], &[]);
3672+
nodes[1].block_notifier.block_connected_checked(&header, 101, &[], &[]);
3673+
for i in 102..TEST_FINAL_CLTV + 100 + 1 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS {
3674+
header.prev_blockhash = header.bitcoin_hash();
3675+
nodes[0].block_notifier.block_connected_checked(&header, i, &[], &[]);
3676+
nodes[1].block_notifier.block_connected_checked(&header, i, &[], &[]);
3677+
}
3678+
3679+
expect_pending_htlcs_forwardable!(nodes[1]);
3680+
3681+
check_added_monitors!(nodes[1], 1);
3682+
let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3683+
assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
3684+
assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
3685+
assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
3686+
assert!(htlc_timeout_updates.update_fee.is_none());
3687+
3688+
nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
3689+
commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
3690+
let events = nodes[0].node.get_and_clear_pending_events();
3691+
match &events[0] {
3692+
&Event::PaymentFailed { payment_hash, rejected_by_dest, error_code, ref error_data } => {
3693+
assert_eq!(payment_hash, our_payment_hash);
3694+
assert!(rejected_by_dest);
3695+
assert_eq!(error_code.unwrap(), 0x4000 | 15);
3696+
// 100_000 msat as u64, followed by a height of 123 as u32
3697+
assert_eq!(&error_data.as_ref().unwrap()[..], &[
3698+
((100_000u64 >> 7*8) & 0xff) as u8,
3699+
((100_000u64 >> 6*8) & 0xff) as u8,
3700+
((100_000u64 >> 5*8) & 0xff) as u8,
3701+
((100_000u64 >> 4*8) & 0xff) as u8,
3702+
((100_000u64 >> 3*8) & 0xff) as u8,
3703+
((100_000u64 >> 2*8) & 0xff) as u8,
3704+
((100_000u64 >> 1*8) & 0xff) as u8,
3705+
((100_000u64 >> 0*8) & 0xff) as u8,
3706+
0, 0, 0, 123]);
3707+
},
3708+
_ => panic!("Unexpected event"),
3709+
}
3710+
}
3711+
36563712
#[test]
36573713
fn test_invalid_channel_announcement() {
36583714
//Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
@@ -7140,6 +7196,8 @@ fn test_bump_penalty_txn_on_revoked_htlcs() {
71407196

71417197
// Broadcast set of revoked txn on A
71427198
let header_128 = connect_blocks(&nodes[0].block_notifier, 128, 0, true, header.bitcoin_hash());
7199+
expect_pending_htlcs_forwardable_ignore!(nodes[0]);
7200+
71437201
let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
71447202
nodes[0].block_notifier.block_connected(&Block { header: header_129, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()] }, 129);
71457203
let first;
@@ -7472,6 +7530,8 @@ fn test_bump_txn_sanitize_tracking_maps() {
74727530

74737531
// Broadcast set of revoked txn on A
74747532
let header_128 = connect_blocks(&nodes[0].block_notifier, 128, 0, false, Default::default());
7533+
expect_pending_htlcs_forwardable_ignore!(nodes[0]);
7534+
74757535
let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
74767536
nodes[0].block_notifier.block_connected(&Block { header: header_129, txdata: vec![revoked_local_txn[0].clone()] }, 129);
74777537
check_closed_broadcast!(nodes[0], false);

lightning/src/util/events.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,9 @@ pub enum Event {
5555
/// ChannelManager::fail_htlc_backwards to free up resources for this HTLC.
5656
/// The amount paid should be considered 'incorrect' when it is less than or more than twice
5757
/// the amount expected.
58+
/// If you fail to call either ChannelManager::claim_funds or
59+
/// ChannelManager::fail_htlc_backwards within the HTLC's timeout, the HTLC will be
60+
/// automatically failed.
5861
PaymentReceived {
5962
/// The hash for which the preimage should be handed to the ChannelManager.
6063
payment_hash: PaymentHash,

0 commit comments

Comments
 (0)