Skip to content

Commit f4442be

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 5a2ed03 commit f4442be

File tree

3 files changed

+106
-4
lines changed

3 files changed

+106
-4
lines changed

lightning/src/ln/channelmanager.rs

Lines changed: 33 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -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
@@ -1063,7 +1065,10 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref> ChannelMan
10631065
// delay) once they've send us a commitment_signed!
10641066

10651067
PendingHTLCStatus::Forward(PendingHTLCInfo {
1066-
routing: PendingHTLCRouting::Receive { payment_data },
1068+
routing: PendingHTLCRouting::Receive {
1069+
payment_data,
1070+
incoming_cltv_expiry: msg.cltv_expiry,
1071+
},
10671072
payment_hash: msg.payment_hash.clone(),
10681073
incoming_shared_secret: shared_secret,
10691074
amt_to_forward: next_hop_data.amt_to_forward,
@@ -1705,7 +1710,7 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref> ChannelMan
17051710
for forward_info in pending_forwards.drain(..) {
17061711
match forward_info {
17071712
HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_htlc_id, forward_info: PendingHTLCInfo {
1708-
routing: PendingHTLCRouting::Receive { payment_data },
1713+
routing: PendingHTLCRouting::Receive { payment_data, incoming_cltv_expiry },
17091714
incoming_shared_secret, payment_hash, amt_to_forward, .. }, } => {
17101715
let prev_hop = HTLCPreviousHopData {
17111716
short_channel_id: prev_short_channel_id,
@@ -1722,6 +1727,7 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref> ChannelMan
17221727
prev_hop,
17231728
value: amt_to_forward,
17241729
payment_data: payment_data.clone(),
1730+
cltv_expiry: incoming_cltv_expiry,
17251731
});
17261732
if let &Some(ref data) = &payment_data {
17271733
for htlc in htlcs.iter() {
@@ -2983,6 +2989,7 @@ impl<ChanSigner: ChannelKeys, M: Deref + Sync + Send, T: Deref + Sync + Send, K:
29832989
log_trace!(self, "Block {} at height {} connected with {} txn matched", header_hash, height, txn_matched.len());
29842990
let _ = self.total_consistency_lock.read().unwrap();
29852991
let mut failed_channels = Vec::new();
2992+
let mut timed_out_htlcs = Vec::new();
29862993
{
29872994
let mut channel_lock = self.channel_state.lock().unwrap();
29882995
let channel_state = &mut *channel_lock;
@@ -3051,10 +3058,29 @@ impl<ChanSigner: ChannelKeys, M: Deref + Sync + Send, T: Deref + Sync + Send, K:
30513058
}
30523059
true
30533060
});
3061+
3062+
channel_state.claimable_htlcs.retain(|&(ref payment_hash, _), htlcs| {
3063+
htlcs.retain(|htlc| {
3064+
if height >= htlc.cltv_expiry - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS {
3065+
timed_out_htlcs.push((HTLCSource::PreviousHopData(htlc.prev_hop.clone()), payment_hash.clone(), htlc.value));
3066+
false
3067+
} else { true }
3068+
});
3069+
!htlcs.is_empty()
3070+
});
30543071
}
30553072
for failure in failed_channels.drain(..) {
30563073
self.finish_force_close_channel(failure);
30573074
}
3075+
3076+
for (source, payment_hash, value) in timed_out_htlcs.drain(..) {
3077+
// Call it preimage_unknown as the issue, ultimately, is that the user failed to
3078+
// provide us a preimage within the cltv_expiry time window.
3079+
self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), source, &payment_hash, HTLCFailReason::Reason {
3080+
failure_code: 0x4000 | 15,
3081+
data: byte_utils::be64_to_array(value).to_vec()
3082+
});
3083+
}
30583084
self.latest_block_height.store(height as usize, Ordering::Release);
30593085
*self.last_block_hash.try_lock().expect("block_(dis)connected must not be called in parallel") = header_hash;
30603086
loop {
@@ -3345,9 +3371,10 @@ impl Writeable for PendingHTLCInfo {
33453371
onion_packet.write(writer)?;
33463372
short_channel_id.write(writer)?;
33473373
},
3348-
&PendingHTLCRouting::Receive { ref payment_data } => {
3374+
&PendingHTLCRouting::Receive { ref payment_data, ref incoming_cltv_expiry } => {
33493375
1u8.write(writer)?;
33503376
payment_data.write(writer)?;
3377+
incoming_cltv_expiry.write(writer)?;
33513378
},
33523379
}
33533380
self.incoming_shared_secret.write(writer)?;
@@ -3368,6 +3395,7 @@ impl Readable for PendingHTLCInfo {
33683395
},
33693396
1u8 => PendingHTLCRouting::Receive {
33703397
payment_data: Readable::read(reader)?,
3398+
incoming_cltv_expiry: Readable::read(reader)?,
33713399
},
33723400
_ => return Err(DecodeError::InvalidValue),
33733401
},
@@ -3440,7 +3468,8 @@ impl_writeable!(HTLCPreviousHopData, 0, {
34403468
impl_writeable!(ClaimableHTLC, 0, {
34413469
prev_hop,
34423470
value,
3443-
payment_data
3471+
payment_data,
3472+
cltv_expiry
34443473
});
34453474

34463475
impl Writeable for HTLCSource {

lightning/src/ln/functional_tests.rs

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2325,6 +2325,15 @@ fn claim_htlc_outputs_single_tx() {
23252325
check_added_monitors!(nodes[0], 1);
23262326
nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
23272327
check_added_monitors!(nodes[1], 1);
2328+
2329+
// Expect pending failures, but we don't bother trying to update the channel state with them.
2330+
let events = nodes[0].node.get_and_clear_pending_events();
2331+
assert_eq!(events.len(), 1);
2332+
match events[0] {
2333+
Event::PendingHTLCsForwardable { .. } => { },
2334+
_ => panic!("Unexpected event"),
2335+
};
2336+
23282337
connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 200, true, header.bitcoin_hash());
23292338

23302339
let events = nodes[1].node.get_and_clear_pending_events();
@@ -3658,6 +3667,49 @@ fn test_drop_messages_peer_disconnect_dual_htlc() {
36583667
claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
36593668
}
36603669

3670+
#[test]
3671+
fn test_htlc_timeout() {
3672+
// If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
3673+
// to avoid our counterparty failing the channel.
3674+
let chanmon_cfgs = create_chanmon_cfgs(2);
3675+
let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3676+
let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3677+
let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3678+
3679+
create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
3680+
let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 100000);
3681+
3682+
let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3683+
nodes[0].block_notifier.block_connected_checked(&header, 101, &[], &[]);
3684+
nodes[1].block_notifier.block_connected_checked(&header, 101, &[], &[]);
3685+
for i in 102..TEST_FINAL_CLTV + 100 + 1 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS {
3686+
header.prev_blockhash = header.bitcoin_hash();
3687+
nodes[0].block_notifier.block_connected_checked(&header, i, &[], &[]);
3688+
nodes[1].block_notifier.block_connected_checked(&header, i, &[], &[]);
3689+
}
3690+
3691+
expect_pending_htlcs_forwardable!(nodes[1]);
3692+
3693+
check_added_monitors!(nodes[1], 1);
3694+
let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3695+
assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
3696+
assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
3697+
assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
3698+
assert!(htlc_timeout_updates.update_fee.is_none());
3699+
3700+
nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
3701+
commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
3702+
let events = nodes[0].node.get_and_clear_pending_events();
3703+
match events[0] {
3704+
Event::PaymentFailed { payment_hash, rejected_by_dest, error_code } => {
3705+
assert_eq!(payment_hash, our_payment_hash);
3706+
assert!(rejected_by_dest);
3707+
assert_eq!(error_code.unwrap(), 0x4000 | 15);
3708+
},
3709+
_ => panic!("Unexpected event"),
3710+
}
3711+
}
3712+
36613713
#[test]
36623714
fn test_invalid_channel_announcement() {
36633715
//Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
@@ -7145,6 +7197,15 @@ fn test_bump_penalty_txn_on_revoked_htlcs() {
71457197

71467198
// Broadcast set of revoked txn on A
71477199
let header_128 = connect_blocks(&nodes[0].block_notifier, 128, 0, true, header.bitcoin_hash());
7200+
7201+
// Expect pending failures, but we don't bother trying to update the channel state with them.
7202+
let events = nodes[0].node.get_and_clear_pending_events();
7203+
assert_eq!(events.len(), 1);
7204+
match events[0] {
7205+
Event::PendingHTLCsForwardable { .. } => { },
7206+
_ => panic!("Unexpected event"),
7207+
};
7208+
71487209
let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
71497210
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);
71507211
let first;
@@ -7477,6 +7538,15 @@ fn test_bump_txn_sanitize_tracking_maps() {
74777538

74787539
// Broadcast set of revoked txn on A
74797540
let header_128 = connect_blocks(&nodes[0].block_notifier, 128, 0, false, Default::default());
7541+
7542+
// Expect pending failures, but we don't bother trying to update the channel state with them.
7543+
let events = nodes[0].node.get_and_clear_pending_events();
7544+
assert_eq!(events.len(), 1);
7545+
match events[0] {
7546+
Event::PendingHTLCsForwardable { .. } => { },
7547+
_ => panic!("Unexpected event"),
7548+
};
7549+
74807550
let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
74817551
nodes[0].block_notifier.block_connected(&Block { header: header_129, txdata: vec![revoked_local_txn[0].clone()] }, 129);
74827552
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)