Skip to content

Commit e112a94

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 facf996 commit e112a94

File tree

3 files changed

+106
-3
lines changed

3 files changed

+106
-3
lines changed

lightning/src/ln/channelmanager.rs

Lines changed: 33 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@ enum PendingForwardReceiveHTLCInfo {
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

@@ -125,6 +126,7 @@ struct ClaimableHTLC {
125126
src: HTLCPreviousHopData,
126127
value: u64,
127128
payment_data: Option<msgs::FinalOnionHopData>,
129+
cltv_expiry: u32,
128130
}
129131

130132
/// Tracks the inbound corresponding to an outbound HTLC
@@ -1028,7 +1030,10 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref> ChannelMan
10281030
// delay) once they've send us a commitment_signed!
10291031

10301032
PendingHTLCStatus::Forward(PendingHTLCInfo {
1031-
type_data: PendingForwardReceiveHTLCInfo::Receive { payment_data },
1033+
type_data: PendingForwardReceiveHTLCInfo::Receive {
1034+
payment_data,
1035+
incoming_cltv_expiry: msg.cltv_expiry,
1036+
},
10321037
payment_hash: msg.payment_hash.clone(),
10331038
incoming_shared_secret: shared_secret,
10341039
amt_to_forward: next_hop_data.amt_to_forward,
@@ -1661,7 +1666,7 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref> ChannelMan
16611666
for forward_info in pending_forwards.drain(..) {
16621667
match forward_info {
16631668
HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_htlc_id, forward_info: PendingHTLCInfo {
1664-
type_data: PendingForwardReceiveHTLCInfo::Receive { payment_data },
1669+
type_data: PendingForwardReceiveHTLCInfo::Receive { payment_data, incoming_cltv_expiry },
16651670
incoming_shared_secret, payment_hash, amt_to_forward, .. }, } => {
16661671
let prev_hop_data = HTLCPreviousHopData {
16671672
short_channel_id: prev_short_channel_id,
@@ -1677,6 +1682,7 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref> ChannelMan
16771682
src: prev_hop_data,
16781683
value: amt_to_forward,
16791684
payment_data: payment_data.clone(),
1685+
cltv_expiry: incoming_cltv_expiry,
16801686
});
16811687
if let &Some(ref data) = &payment_data {
16821688
for htlc in htlcs.iter() {
@@ -2861,6 +2867,7 @@ impl<ChanSigner: ChannelKeys, M: Deref + Sync + Send, T: Deref + Sync + Send, K:
28612867
log_trace!(self, "Block {} at height {} connected with {} txn matched", header_hash, height, txn_matched.len());
28622868
let _ = self.total_consistency_lock.read().unwrap();
28632869
let mut failed_channels = Vec::new();
2870+
let mut timed_out_htlcs = Vec::new();
28642871
{
28652872
let mut channel_lock = self.channel_state.lock().unwrap();
28662873
let channel_state = &mut *channel_lock;
@@ -2930,10 +2937,29 @@ impl<ChanSigner: ChannelKeys, M: Deref + Sync + Send, T: Deref + Sync + Send, K:
29302937
}
29312938
true
29322939
});
2940+
2941+
channel_state.claimable_htlcs.retain(|&(ref payment_hash, _), htlcs| {
2942+
htlcs.retain(|htlc| {
2943+
if height >= htlc.cltv_expiry - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS {
2944+
timed_out_htlcs.push((HTLCSource::PreviousHopData(htlc.src.clone()), payment_hash.clone(), htlc.value));
2945+
false
2946+
} else { true }
2947+
});
2948+
!htlcs.is_empty()
2949+
});
29332950
}
29342951
for failure in failed_channels.drain(..) {
29352952
self.finish_force_close_channel(failure);
29362953
}
2954+
2955+
for (source, payment_hash, value) in timed_out_htlcs.drain(..) {
2956+
// Call it preimage_unknown as the issue, ultimately, is that the user failed to
2957+
// provide us a preimage within the cltv_expiry time window.
2958+
self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), source, &payment_hash, HTLCFailReason::Reason {
2959+
failure_code: 0x4000 | 15,
2960+
data: byte_utils::be64_to_array(value).to_vec()
2961+
});
2962+
}
29372963
self.latest_block_height.store(height as usize, Ordering::Release);
29382964
*self.last_block_hash.try_lock().expect("block_(dis)connected must not be called in parallel") = header_hash;
29392965
loop {
@@ -3288,9 +3314,10 @@ impl Writeable for PendingHTLCInfo {
32883314
onion_packet.write(writer)?;
32893315
short_channel_id.write(writer)?;
32903316
},
3291-
&PendingForwardReceiveHTLCInfo::Receive { ref payment_data } => {
3317+
&PendingForwardReceiveHTLCInfo::Receive { ref payment_data, ref incoming_cltv_expiry } => {
32923318
1u8.write(writer)?;
32933319
payment_data.write(writer)?;
3320+
incoming_cltv_expiry.write(writer)?;
32943321
},
32953322
}
32963323
self.incoming_shared_secret.write(writer)?;
@@ -3311,6 +3338,7 @@ impl Readable for PendingHTLCInfo {
33113338
},
33123339
1u8 => PendingForwardReceiveHTLCInfo::Receive {
33133340
payment_data: Readable::read(reader)?,
3341+
incoming_cltv_expiry: Readable::read(reader)?,
33143342
},
33153343
_ => return Err(DecodeError::InvalidValue),
33163344
},
@@ -3525,6 +3553,7 @@ impl<ChanSigner: ChannelKeys + Writeable, M: Deref, T: Deref, K: Deref, F: Deref
35253553
htlc.src.write(writer)?;
35263554
htlc.value.write(writer)?;
35273555
htlc.payment_data.write(writer)?;
3556+
htlc.cltv_expiry.write(writer)?;
35283557
}
35293558
}
35303559

@@ -3698,6 +3727,7 @@ impl<'a, ChanSigner: ChannelKeys + Readable, M: Deref, T: Deref, K: Deref, F: De
36983727
src: Readable::read(reader)?,
36993728
value: Readable::read(reader)?,
37003729
payment_data: Readable::read(reader)?,
3730+
cltv_expiry: Readable::read(reader)?,
37013731
});
37023732
}
37033733
claimable_htlcs.insert(payment_hash, previous_hops);

lightning/src/ln/functional_tests.rs

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2302,6 +2302,15 @@ fn claim_htlc_outputs_single_tx() {
23022302
let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
23032303
nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
23042304
nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
2305+
2306+
// Expect pending failures, but we don't bother trying to update the channel state with them.
2307+
let events = nodes[0].node.get_and_clear_pending_events();
2308+
assert_eq!(events.len(), 1);
2309+
match events[0] {
2310+
Event::PendingHTLCsForwardable { .. } => { },
2311+
_ => panic!("Unexpected event"),
2312+
};
2313+
23052314
connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 200, true, header.bitcoin_hash());
23062315

23072316
let events = nodes[1].node.get_and_clear_pending_events();
@@ -3572,6 +3581,49 @@ fn test_drop_messages_peer_disconnect_dual_htlc() {
35723581
claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
35733582
}
35743583

3584+
#[test]
3585+
fn test_htlc_timeout() {
3586+
// If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
3587+
// to avoid our counterparty failing the channel.
3588+
let chanmon_cfgs = create_chanmon_cfgs(2);
3589+
let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3590+
let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3591+
let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3592+
3593+
create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
3594+
let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 100000);
3595+
3596+
let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3597+
nodes[0].block_notifier.block_connected_checked(&header, 101, &[], &[]);
3598+
nodes[1].block_notifier.block_connected_checked(&header, 101, &[], &[]);
3599+
for i in 102..TEST_FINAL_CLTV + 100 + 1 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS {
3600+
header.prev_blockhash = header.bitcoin_hash();
3601+
nodes[0].block_notifier.block_connected_checked(&header, i, &[], &[]);
3602+
nodes[1].block_notifier.block_connected_checked(&header, i, &[], &[]);
3603+
}
3604+
3605+
expect_pending_htlcs_forwardable!(nodes[1]);
3606+
3607+
check_added_monitors!(nodes[1], 1);
3608+
let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3609+
assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
3610+
assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
3611+
assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
3612+
assert!(htlc_timeout_updates.update_fee.is_none());
3613+
3614+
nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
3615+
commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
3616+
let events = nodes[0].node.get_and_clear_pending_events();
3617+
match events[0] {
3618+
Event::PaymentFailed { payment_hash, rejected_by_dest, error_code } => {
3619+
assert_eq!(payment_hash, our_payment_hash);
3620+
assert!(rejected_by_dest);
3621+
assert_eq!(error_code.unwrap(), 0x4000 | 15);
3622+
},
3623+
_ => panic!("Unexpected event"),
3624+
}
3625+
}
3626+
35753627
#[test]
35763628
fn test_invalid_channel_announcement() {
35773629
//Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
@@ -6879,6 +6931,15 @@ fn test_bump_penalty_txn_on_revoked_htlcs() {
68796931

68806932
// Broadcast set of revoked txn on A
68816933
let header_128 = connect_blocks(&nodes[0].block_notifier, 128, 0, true, header.bitcoin_hash());
6934+
6935+
// Expect pending failures, but we don't bother trying to update the channel state with them.
6936+
let events = nodes[0].node.get_and_clear_pending_events();
6937+
assert_eq!(events.len(), 1);
6938+
match events[0] {
6939+
Event::PendingHTLCsForwardable { .. } => { },
6940+
_ => panic!("Unexpected event"),
6941+
};
6942+
68826943
let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
68836944
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);
68846945
let first;
@@ -7201,6 +7262,15 @@ fn test_bump_txn_sanitize_tracking_maps() {
72017262

72027263
// Broadcast set of revoked txn on A
72037264
let header_128 = connect_blocks(&nodes[0].block_notifier, 128, 0, false, Default::default());
7265+
7266+
// Expect pending failures, but we don't bother trying to update the channel state with them.
7267+
let events = nodes[0].node.get_and_clear_pending_events();
7268+
assert_eq!(events.len(), 1);
7269+
match events[0] {
7270+
Event::PendingHTLCsForwardable { .. } => { },
7271+
_ => panic!("Unexpected event"),
7272+
};
7273+
72047274
let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
72057275
nodes[0].block_notifier.block_connected(&Block { header: header_129, txdata: vec![revoked_local_txn[0].clone()] }, 129);
72067276
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 of
59+
/// ChannelManager::fail_htlc_backwards within the HTLC's timeout, the HTLC will be
60+
/// automatically failed with PaymentFailReason::PreimageUnknown.
5861
PaymentReceived {
5962
/// The hash for which the preimage should be handed to the ChannelManager.
6063
payment_hash: PaymentHash,

0 commit comments

Comments
 (0)