Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 7 additions & 6 deletions src/ln/channel.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -264,7 +264,7 @@ pub(super) struct Channel {
monitor_pending_revoke_and_ack: bool,
monitor_pending_commitment_signed: bool,
monitor_pending_order: Option<RAACommitmentOrder>,
monitor_pending_forwards: Vec<(PendingForwardHTLCInfo, u64)>,
monitor_pending_forwards: Vec<(PendingForwardHTLCInfo, u64, u32)>,
monitor_pending_failures: Vec<(HTLCSource, [u8; 32], HTLCFailReason)>,

// pending_update_fee is filled when sending and receiving update_fee
Expand DownExpand Up@@ -1854,7 +1854,7 @@ impl Channel {
/// waiting on this revoke_and_ack. The generation of this new commitment_signed may also fail,
/// generating an appropriate error *after* the channel state has been updated based on the
/// revoke_and_ack message.
pub fn revoke_and_ack(&mut self, msg: &msgs::RevokeAndACK, fee_estimator: &FeeEstimator) -> Result<(Option<msgs::CommitmentUpdate>, Vec<(PendingForwardHTLCInfo, u64)>, Vec<(HTLCSource, [u8; 32], HTLCFailReason)>, Option<msgs::ClosingSigned>, ChannelMonitor), HandleError> {
pub fn revoke_and_ack(&mut self, msg: &msgs::RevokeAndACK, fee_estimator: &FeeEstimator) -> Result<(Option<msgs::CommitmentUpdate>, Vec<(PendingForwardHTLCInfo, u64, u32)>, Vec<(HTLCSource, [u8; 32], HTLCFailReason)>, Option<msgs::ClosingSigned>, ChannelMonitor), HandleError> {
if (self.channel_state & (ChannelState::ChannelFunded as u32)) != (ChannelState::ChannelFunded as u32) {
return Err(HandleError{err: "Got revoke/ACK message when channel was not in an operational state", action: None});
}
Expand DownExpand Up@@ -1942,7 +1942,7 @@ impl Channel {
}
},
PendingHTLCStatus::Forward(forward_info) => {
to_forward_infos.push((forward_info, htlc.htlc_id));
to_forward_infos.push((forward_info, htlc.htlc_id, htlc.cltv_expiry));
htlc.state = InboundHTLCState::Committed;
}
}
Expand DownExpand Up@@ -2152,7 +2152,7 @@ impl Channel {
/// Indicates that the latest ChannelMonitor update has been committed by the client
/// successfully and we should restore normal operation. Returns messages which should be sent
/// to the remote side.
pub fn monitor_updating_restored(&mut self) -> (Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>, RAACommitmentOrder, Vec<(PendingForwardHTLCInfo, u64)>, Vec<(HTLCSource, [u8; 32], HTLCFailReason)>) {
pub fn monitor_updating_restored(&mut self) -> (Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>, RAACommitmentOrder, Vec<(PendingForwardHTLCInfo, u64, u32)>, Vec<(HTLCSource, [u8; 32], HTLCFailReason)>) {
assert_eq!(self.channel_state & ChannelState::MonitorUpdateFailed as u32, ChannelState::MonitorUpdateFailed as u32);
self.channel_state &= !(ChannelState::MonitorUpdateFailed as u32);

Expand DownExpand Up@@ -3489,9 +3489,10 @@ impl Writeable for Channel {
}

(self.monitor_pending_forwards.len() as u64).write(writer)?;
for &(ref pending_forward, ref htlc_id) in self.monitor_pending_forwards.iter() {
for &(ref pending_forward, ref htlc_id, ref cltv_expiry) in self.monitor_pending_forwards.iter() {
pending_forward.write(writer)?;
htlc_id.write(writer)?;
cltv_expiry.write(writer)?;
}

(self.monitor_pending_failures.len() as u64).write(writer)?;
Expand DownExpand Up@@ -3670,7 +3671,7 @@ impl<R : ::std::io::Read> ReadableArgs<R, Arc<Logger>> for Channel {
let monitor_pending_forwards_count: u64 = Readable::read(reader)?;
let mut monitor_pending_forwards = Vec::with_capacity(cmp::min(monitor_pending_forwards_count as usize, OUR_MAX_HTLCS as usize));
for _ in 0..monitor_pending_forwards_count {
monitor_pending_forwards.push((Readable::read(reader)?, Readable::read(reader)?));
monitor_pending_forwards.push((Readable::read(reader)?, Readable::read(reader)?, Readable::read(reader)?));
}

let monitor_pending_failures_count: u64 = Readable::read(reader)?;
Expand Down
82 changes: 73 additions & 9 deletions src/ln/channelmanager.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -96,6 +96,8 @@ mod channel_held_info {
pub(super) short_channel_id: u64,
pub(super) htlc_id: u64,
pub(super) incoming_packet_shared_secret: [u8; 32],
/// Only used to track expiry of claimable_htlcs and fail them backwards
pub(super) cltv_expiry: u32,
}

/// Tracks the inbound corresponding to an outbound HTLC
Expand DownExpand Up@@ -240,6 +242,7 @@ const MIN_HTLC_RELAY_HOLDING_CELL_MILLIS: u32 = 50;
struct HTLCForwardInfo {
prev_short_channel_id: u64,
prev_htlc_id: u64,
prev_cltv_expiry: u32,
forward_info: PendingForwardHTLCInfo,
}

Expand DownExpand Up@@ -1326,11 +1329,12 @@ impl ChannelManager {
Some(chan_id) => chan_id.clone(),
None => {
failed_forwards.reserve(pending_forwards.len());
for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info, prev_cltv_expiry } in pending_forwards.drain(..) {
let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
short_channel_id: prev_short_channel_id,
htlc_id: prev_htlc_id,
incoming_packet_shared_secret: forward_info.incoming_shared_secret,
cltv_expiry: prev_cltv_expiry,
});
failed_forwards.push((htlc_source, forward_info.payment_hash, 0x4000 | 10, None));
}
Expand All@@ -1340,11 +1344,12 @@ impl ChannelManager {
let forward_chan = &mut channel_state.by_id.get_mut(&forward_chan_id).unwrap();

let mut add_htlc_msgs = Vec::new();
for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, prev_cltv_expiry, forward_info } in pending_forwards.drain(..) {
let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
short_channel_id: prev_short_channel_id,
htlc_id: prev_htlc_id,
incoming_packet_shared_secret: forward_info.incoming_shared_secret,
cltv_expiry: prev_cltv_expiry,
});
match forward_chan.send_htlc(forward_info.amt_to_forward, forward_info.payment_hash, forward_info.outgoing_cltv_value, htlc_source.clone(), forward_info.onion_packet.unwrap()) {
Err(_e) => {
Expand DownExpand Up@@ -1398,11 +1403,12 @@ impl ChannelManager {
});
}
} else {
for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, prev_cltv_expiry, forward_info } in pending_forwards.drain(..) {
let prev_hop_data = HTLCPreviousHopData {
short_channel_id: prev_short_channel_id,
htlc_id: prev_htlc_id,
incoming_packet_shared_secret: forward_info.incoming_shared_secret,
cltv_expiry: prev_cltv_expiry,
};
match channel_state.claimable_htlcs.entry(forward_info.payment_hash) {
hash_map::Entry::Occupied(mut entry) => entry.get_mut().push(prev_hop_data),
Expand DownExpand Up@@ -1471,7 +1477,7 @@ impl ChannelManager {
panic!("should have onion error packet here");
}
},
HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, incoming_packet_shared_secret }) => {
HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, incoming_packet_shared_secret, .. }) => {
let err_packet = match onion_error {
HTLCFailReason::Reason { failure_code, data } => {
let packet = ChannelManager::build_failure_packet(&incoming_packet_shared_secret, failure_code, &data[..]).encode();
Expand DownExpand Up@@ -2248,7 +2254,7 @@ impl ChannelManager {
}

#[inline]
fn forward_htlcs(&self, per_source_pending_forwards: &mut [(u64, Vec<(PendingForwardHTLCInfo, u64)>)]) {
fn forward_htlcs(&self, per_source_pending_forwards: &mut [(u64, Vec<(PendingForwardHTLCInfo, u64, u32)>)]) {
for &mut (prev_short_channel_id, ref mut pending_forwards) in per_source_pending_forwards {
let mut forward_event = None;
if !pending_forwards.is_empty() {
Expand All@@ -2257,13 +2263,13 @@ impl ChannelManager {
forward_event = Some(Instant::now() + Duration::from_millis(((rng::rand_f32() * 4.0 + 1.0) * MIN_HTLC_RELAY_HOLDING_CELL_MILLIS as f32) as u64));
channel_state.next_forward = forward_event.unwrap();
}
for (forward_info, prev_htlc_id) in pending_forwards.drain(..) {
for (forward_info, prev_htlc_id, prev_cltv_expiry) in pending_forwards.drain(..) {
match channel_state.forward_htlcs.entry(forward_info.short_channel_id) {
hash_map::Entry::Occupied(mut entry) => {
entry.get_mut().push(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info });
entry.get_mut().push(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, prev_cltv_expiry, forward_info });
},
hash_map::Entry::Vacant(entry) => {
entry.insert(vec!(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info }));
entry.insert(vec!(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, prev_cltv_expiry, forward_info }));
}
}
}
Expand DownExpand Up@@ -2500,6 +2506,7 @@ impl ChainListener for ChannelManager {
fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]) {
let _ = self.total_consistency_lock.read().unwrap();
let mut failed_channels = Vec::new();
let mut timed_out_htlcs = Vec::new();
{
let mut channel_lock = self.channel_state.lock().unwrap();
let channel_state = channel_lock.borrow_parts();
Expand DownExpand Up@@ -2567,10 +2574,27 @@ impl ChainListener for ChannelManager {
}
true
});
channel_state.claimable_htlcs.retain(|payment_hash, htlcs| {
htlcs.retain(|htlc| {
if htlc.cltv_expiry <= height { // XXX: Or <?

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry what means "XXX: or <?" ? You want to substract a safe delay to height ?

@TheBlueMattTheBlueMattNov 16, 2018

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oops, lol, ffs, I really need to double-check my own commits before opening PRs, I blame sleep deprivation after 16 hours of being in a plane, thanks for reviewing...That was a note to myself that I'm not sure if the comparison was supposed to be <= or <, I'll double check and fix the PR.

timed_out_htlcs.push((HTLCSource::PreviousHopData(htlc.clone()), payment_hash.clone()));
false
} else { true }
});
!htlcs.is_empty()
});
}
for failure in failed_channels.drain(..) {
self.finish_force_close_channel(failure);
}
for (source, payment_hash) in timed_out_htlcs.drain(..) {
// Call it preimage_unknown as the issue, ultimately, is that the user failed to
// provide us a preimage within the cltv_expiry time window.
self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), source, &payment_hash, HTLCFailReason::Reason {
failure_code: 0x4000 | 15,
data: Vec::new()
});
}
self.latest_block_height.store(height as usize, Ordering::Release);
*self.last_block_hash.try_lock().expect("block_(dis)connected must not be called in parallel") = header.bitcoin_hash();
}
Expand DownExpand Up@@ -2916,7 +2940,8 @@ impl<R: ::std::io::Read> Readable<R> for PendingHTLCStatus {
impl_writeable!(HTLCPreviousHopData, 0, {
short_channel_id,
htlc_id,
incoming_packet_shared_secret
incoming_packet_shared_secret,
cltv_expiry
});

impl Writeable for HTLCSource {
Expand DownExpand Up@@ -2984,6 +3009,7 @@ impl<R: ::std::io::Read> Readable<R> for HTLCFailReason {
impl_writeable!(HTLCForwardInfo, 0, {
prev_short_channel_id,
prev_htlc_id,
prev_cltv_expiry,
forward_info
});

Expand DownExpand Up@@ -7263,6 +7289,44 @@ mod tests {
do_test_monitor_temporary_update_fail(3 | 8 | 16);
}

#[test]
fn test_htlc_timeout() {
// If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
// to avoid our counterparty failing the channel.
let secp_ctx = Secp256k1::new();
let nodes = create_network(2);

create_announced_chan_between_nodes(&nodes, 0, 1);
let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 100000);

let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
nodes[0].chain_monitor.block_connected_checked(&header, 101, &[], &[]);
nodes[1].chain_monitor.block_connected_checked(&header, 101, &[], &[]);
for i in 102..TEST_FINAL_CLTV + 100 + 1 {
header.prev_blockhash = header.bitcoin_hash();
nodes[0].chain_monitor.block_connected_checked(&header, i, &[], &[]);
nodes[1].chain_monitor.block_connected_checked(&header, i, &[], &[]);
}

check_added_monitors!(nodes[1], 1);
let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
assert!(htlc_timeout_updates.update_fee.is_none());

nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]).unwrap();
commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
let events = nodes[0].node.get_and_clear_pending_events();
match events[0] {
Event::PaymentFailed { payment_hash, rejected_by_dest } => {
assert_eq!(payment_hash, our_payment_hash);
assert!(rejected_by_dest);
},
_ => panic!("Unexpected event"),
}
}

#[test]
fn test_invalid_channel_announcement() {
//Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
Expand Down
3 changes: 3 additions & 0 deletions src/util/events.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -57,6 +57,9 @@ pub enum Event {
/// PaymentFailReason::AmountMismatch, respectively, to free up resources for this HTLC.
/// The amount paid should be considered 'incorrect' when it is less than or more than twice
/// the amount expected.
/// If you fail to call either ChannelManager::claim_funds of
/// ChannelManager::fail_htlc_backwards within the HTLC's timeout, the HTLC will be
/// automatically failed with PaymentFailReason::PreimageUnknown.
PaymentReceived {
/// The hash for which the preimage should be handed to the ChannelManager.
payment_hash: [u8; 32],
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 7 additions & 6 deletions src/ln/channel.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -264,7 +264,7 @@ pub(super) struct Channel {
monitor_pending_revoke_and_ack: bool,
monitor_pending_commitment_signed: bool,
monitor_pending_order: Option<RAACommitmentOrder>,
monitor_pending_forwards: Vec<(PendingForwardHTLCInfo, u64)>,
monitor_pending_forwards: Vec<(PendingForwardHTLCInfo, u64, u32)>,
monitor_pending_failures: Vec<(HTLCSource, [u8; 32], HTLCFailReason)>,

// pending_update_fee is filled when sending and receiving update_fee
Expand DownExpand Up@@ -1854,7 +1854,7 @@ impl Channel {
/// waiting on this revoke_and_ack. The generation of this new commitment_signed may also fail,
/// generating an appropriate error *after* the channel state has been updated based on the
/// revoke_and_ack message.
pub fn revoke_and_ack(&mut self, msg: &msgs::RevokeAndACK, fee_estimator: &FeeEstimator) -> Result<(Option<msgs::CommitmentUpdate>, Vec<(PendingForwardHTLCInfo, u64)>, Vec<(HTLCSource, [u8; 32], HTLCFailReason)>, Option<msgs::ClosingSigned>, ChannelMonitor), HandleError> {
pub fn revoke_and_ack(&mut self, msg: &msgs::RevokeAndACK, fee_estimator: &FeeEstimator) -> Result<(Option<msgs::CommitmentUpdate>, Vec<(PendingForwardHTLCInfo, u64, u32)>, Vec<(HTLCSource, [u8; 32], HTLCFailReason)>, Option<msgs::ClosingSigned>, ChannelMonitor), HandleError> {
if (self.channel_state & (ChannelState::ChannelFunded as u32)) != (ChannelState::ChannelFunded as u32) {
return Err(HandleError{err: "Got revoke/ACK message when channel was not in an operational state", action: None});
}
Expand DownExpand Up@@ -1942,7 +1942,7 @@ impl Channel {
}
},
PendingHTLCStatus::Forward(forward_info) => {
to_forward_infos.push((forward_info, htlc.htlc_id));
to_forward_infos.push((forward_info, htlc.htlc_id, htlc.cltv_expiry));
htlc.state = InboundHTLCState::Committed;
}
}
Expand DownExpand Up@@ -2152,7 +2152,7 @@ impl Channel {
/// Indicates that the latest ChannelMonitor update has been committed by the client
/// successfully and we should restore normal operation. Returns messages which should be sent
/// to the remote side.
pub fn monitor_updating_restored(&mut self) -> (Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>, RAACommitmentOrder, Vec<(PendingForwardHTLCInfo, u64)>, Vec<(HTLCSource, [u8; 32], HTLCFailReason)>) {
pub fn monitor_updating_restored(&mut self) -> (Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>, RAACommitmentOrder, Vec<(PendingForwardHTLCInfo, u64, u32)>, Vec<(HTLCSource, [u8; 32], HTLCFailReason)>) {
assert_eq!(self.channel_state & ChannelState::MonitorUpdateFailed as u32, ChannelState::MonitorUpdateFailed as u32);
self.channel_state &= !(ChannelState::MonitorUpdateFailed as u32);

Expand DownExpand Up@@ -3489,9 +3489,10 @@ impl Writeable for Channel {
}

(self.monitor_pending_forwards.len() as u64).write(writer)?;
for &(ref pending_forward, ref htlc_id) in self.monitor_pending_forwards.iter() {
for &(ref pending_forward, ref htlc_id, ref cltv_expiry) in self.monitor_pending_forwards.iter() {
pending_forward.write(writer)?;
htlc_id.write(writer)?;
cltv_expiry.write(writer)?;
}

(self.monitor_pending_failures.len() as u64).write(writer)?;
Expand DownExpand Up@@ -3670,7 +3671,7 @@ impl<R : ::std::io::Read> ReadableArgs<R, Arc<Logger>> for Channel {
let monitor_pending_forwards_count: u64 = Readable::read(reader)?;
let mut monitor_pending_forwards = Vec::with_capacity(cmp::min(monitor_pending_forwards_count as usize, OUR_MAX_HTLCS as usize));
for _ in 0..monitor_pending_forwards_count {
monitor_pending_forwards.push((Readable::read(reader)?, Readable::read(reader)?));
monitor_pending_forwards.push((Readable::read(reader)?, Readable::read(reader)?, Readable::read(reader)?));
}

let monitor_pending_failures_count: u64 = Readable::read(reader)?;
Expand Down
82 changes: 73 additions & 9 deletions src/ln/channelmanager.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -96,6 +96,8 @@ mod channel_held_info {
pub(super) short_channel_id: u64,
pub(super) htlc_id: u64,
pub(super) incoming_packet_shared_secret: [u8; 32],
/// Only used to track expiry of claimable_htlcs and fail them backwards
pub(super) cltv_expiry: u32,
}

/// Tracks the inbound corresponding to an outbound HTLC
Expand DownExpand Up@@ -240,6 +242,7 @@ const MIN_HTLC_RELAY_HOLDING_CELL_MILLIS: u32 = 50;
struct HTLCForwardInfo {
prev_short_channel_id: u64,
prev_htlc_id: u64,
prev_cltv_expiry: u32,
forward_info: PendingForwardHTLCInfo,
}

Expand DownExpand Up@@ -1326,11 +1329,12 @@ impl ChannelManager {
Some(chan_id) => chan_id.clone(),
None => {
failed_forwards.reserve(pending_forwards.len());
for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info, prev_cltv_expiry } in pending_forwards.drain(..) {
let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
short_channel_id: prev_short_channel_id,
htlc_id: prev_htlc_id,
incoming_packet_shared_secret: forward_info.incoming_shared_secret,
cltv_expiry: prev_cltv_expiry,
});
failed_forwards.push((htlc_source, forward_info.payment_hash, 0x4000 | 10, None));
}
Expand All@@ -1340,11 +1344,12 @@ impl ChannelManager {
let forward_chan = &mut channel_state.by_id.get_mut(&forward_chan_id).unwrap();

let mut add_htlc_msgs = Vec::new();
for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, prev_cltv_expiry, forward_info } in pending_forwards.drain(..) {
let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
short_channel_id: prev_short_channel_id,
htlc_id: prev_htlc_id,
incoming_packet_shared_secret: forward_info.incoming_shared_secret,
cltv_expiry: prev_cltv_expiry,
});
match forward_chan.send_htlc(forward_info.amt_to_forward, forward_info.payment_hash, forward_info.outgoing_cltv_value, htlc_source.clone(), forward_info.onion_packet.unwrap()) {
Err(_e) => {
Expand DownExpand Up@@ -1398,11 +1403,12 @@ impl ChannelManager {
});
}
} else {
for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, prev_cltv_expiry, forward_info } in pending_forwards.drain(..) {
let prev_hop_data = HTLCPreviousHopData {
short_channel_id: prev_short_channel_id,
htlc_id: prev_htlc_id,
incoming_packet_shared_secret: forward_info.incoming_shared_secret,
cltv_expiry: prev_cltv_expiry,
};
match channel_state.claimable_htlcs.entry(forward_info.payment_hash) {
hash_map::Entry::Occupied(mut entry) => entry.get_mut().push(prev_hop_data),
Expand DownExpand Up@@ -1471,7 +1477,7 @@ impl ChannelManager {
panic!("should have onion error packet here");
}
},
HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, incoming_packet_shared_secret }) => {
HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, incoming_packet_shared_secret, .. }) => {
let err_packet = match onion_error {
HTLCFailReason::Reason { failure_code, data } => {
let packet = ChannelManager::build_failure_packet(&incoming_packet_shared_secret, failure_code, &data[..]).encode();
Expand DownExpand Up@@ -2248,7 +2254,7 @@ impl ChannelManager {
}

#[inline]
fn forward_htlcs(&self, per_source_pending_forwards: &mut [(u64, Vec<(PendingForwardHTLCInfo, u64)>)]) {
fn forward_htlcs(&self, per_source_pending_forwards: &mut [(u64, Vec<(PendingForwardHTLCInfo, u64, u32)>)]) {
for &mut (prev_short_channel_id, ref mut pending_forwards) in per_source_pending_forwards {
let mut forward_event = None;
if !pending_forwards.is_empty() {
Expand All@@ -2257,13 +2263,13 @@ impl ChannelManager {
forward_event = Some(Instant::now() + Duration::from_millis(((rng::rand_f32() * 4.0 + 1.0) * MIN_HTLC_RELAY_HOLDING_CELL_MILLIS as f32) as u64));
channel_state.next_forward = forward_event.unwrap();
}
for (forward_info, prev_htlc_id) in pending_forwards.drain(..) {
for (forward_info, prev_htlc_id, prev_cltv_expiry) in pending_forwards.drain(..) {
match channel_state.forward_htlcs.entry(forward_info.short_channel_id) {
hash_map::Entry::Occupied(mut entry) => {
entry.get_mut().push(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info });
entry.get_mut().push(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, prev_cltv_expiry, forward_info });
},
hash_map::Entry::Vacant(entry) => {
entry.insert(vec!(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info }));
entry.insert(vec!(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, prev_cltv_expiry, forward_info }));
}
}
}
Expand DownExpand Up@@ -2500,6 +2506,7 @@ impl ChainListener for ChannelManager {
fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]) {
let _ = self.total_consistency_lock.read().unwrap();
let mut failed_channels = Vec::new();
let mut timed_out_htlcs = Vec::new();
{
let mut channel_lock = self.channel_state.lock().unwrap();
let channel_state = channel_lock.borrow_parts();
Expand DownExpand Up@@ -2567,10 +2574,27 @@ impl ChainListener for ChannelManager {
}
true
});
channel_state.claimable_htlcs.retain(|payment_hash, htlcs| {
htlcs.retain(|htlc| {
if htlc.cltv_expiry <= height { // XXX: Or <?

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry what means "XXX: or <?" ? You want to substract a safe delay to height ?

@TheBlueMattTheBlueMattNov 16, 2018

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oops, lol, ffs, I really need to double-check my own commits before opening PRs, I blame sleep deprivation after 16 hours of being in a plane, thanks for reviewing...That was a note to myself that I'm not sure if the comparison was supposed to be <= or <, I'll double check and fix the PR.

timed_out_htlcs.push((HTLCSource::PreviousHopData(htlc.clone()), payment_hash.clone()));
false
} else { true }
});
!htlcs.is_empty()
});
}
for failure in failed_channels.drain(..) {
self.finish_force_close_channel(failure);
}
for (source, payment_hash) in timed_out_htlcs.drain(..) {
// Call it preimage_unknown as the issue, ultimately, is that the user failed to
// provide us a preimage within the cltv_expiry time window.
self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), source, &payment_hash, HTLCFailReason::Reason {
failure_code: 0x4000 | 15,
data: Vec::new()
});
}
self.latest_block_height.store(height as usize, Ordering::Release);
*self.last_block_hash.try_lock().expect("block_(dis)connected must not be called in parallel") = header.bitcoin_hash();
}
Expand DownExpand Up@@ -2916,7 +2940,8 @@ impl<R: ::std::io::Read> Readable<R> for PendingHTLCStatus {
impl_writeable!(HTLCPreviousHopData, 0, {
short_channel_id,
htlc_id,
incoming_packet_shared_secret
incoming_packet_shared_secret,
cltv_expiry
});

impl Writeable for HTLCSource {
Expand DownExpand Up@@ -2984,6 +3009,7 @@ impl<R: ::std::io::Read> Readable<R> for HTLCFailReason {
impl_writeable!(HTLCForwardInfo, 0, {
prev_short_channel_id,
prev_htlc_id,
prev_cltv_expiry,
forward_info
});

Expand DownExpand Up@@ -7263,6 +7289,44 @@ mod tests {
do_test_monitor_temporary_update_fail(3 | 8 | 16);
}

#[test]
fn test_htlc_timeout() {
// If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
// to avoid our counterparty failing the channel.
let secp_ctx = Secp256k1::new();
let nodes = create_network(2);

create_announced_chan_between_nodes(&nodes, 0, 1);
let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 100000);

let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
nodes[0].chain_monitor.block_connected_checked(&header, 101, &[], &[]);
nodes[1].chain_monitor.block_connected_checked(&header, 101, &[], &[]);
for i in 102..TEST_FINAL_CLTV + 100 + 1 {
header.prev_blockhash = header.bitcoin_hash();
nodes[0].chain_monitor.block_connected_checked(&header, i, &[], &[]);
nodes[1].chain_monitor.block_connected_checked(&header, i, &[], &[]);
}

check_added_monitors!(nodes[1], 1);
let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
assert!(htlc_timeout_updates.update_fee.is_none());

nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]).unwrap();
commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
let events = nodes[0].node.get_and_clear_pending_events();
match events[0] {
Event::PaymentFailed { payment_hash, rejected_by_dest } => {
assert_eq!(payment_hash, our_payment_hash);
assert!(rejected_by_dest);
},
_ => panic!("Unexpected event"),
}
}

#[test]
fn test_invalid_channel_announcement() {
//Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
Expand Down
3 changes: 3 additions & 0 deletions src/util/events.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -57,6 +57,9 @@ pub enum Event {
/// PaymentFailReason::AmountMismatch, respectively, to free up resources for this HTLC.
/// The amount paid should be considered 'incorrect' when it is less than or more than twice
/// the amount expected.
/// If you fail to call either ChannelManager::claim_funds of
/// ChannelManager::fail_htlc_backwards within the HTLC's timeout, the HTLC will be
/// automatically failed with PaymentFailReason::PreimageUnknown.
PaymentReceived {
/// The hash for which the preimage should be handed to the ChannelManager.
payment_hash: [u8; 32],
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 7 additions & 6 deletions src/ln/channel.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -264,7 +264,7 @@ pub(super) struct Channel {
monitor_pending_revoke_and_ack: bool,
monitor_pending_commitment_signed: bool,
monitor_pending_order: Option<RAACommitmentOrder>,
monitor_pending_forwards: Vec<(PendingForwardHTLCInfo, u64)>,
monitor_pending_forwards: Vec<(PendingForwardHTLCInfo, u64, u32)>,
monitor_pending_failures: Vec<(HTLCSource, [u8; 32], HTLCFailReason)>,

// pending_update_fee is filled when sending and receiving update_fee
Expand DownExpand Up@@ -1854,7 +1854,7 @@ impl Channel {
/// waiting on this revoke_and_ack. The generation of this new commitment_signed may also fail,
/// generating an appropriate error *after* the channel state has been updated based on the
/// revoke_and_ack message.
pub fn revoke_and_ack(&mut self, msg: &msgs::RevokeAndACK, fee_estimator: &FeeEstimator) -> Result<(Option<msgs::CommitmentUpdate>, Vec<(PendingForwardHTLCInfo, u64)>, Vec<(HTLCSource, [u8; 32], HTLCFailReason)>, Option<msgs::ClosingSigned>, ChannelMonitor), HandleError> {
pub fn revoke_and_ack(&mut self, msg: &msgs::RevokeAndACK, fee_estimator: &FeeEstimator) -> Result<(Option<msgs::CommitmentUpdate>, Vec<(PendingForwardHTLCInfo, u64, u32)>, Vec<(HTLCSource, [u8; 32], HTLCFailReason)>, Option<msgs::ClosingSigned>, ChannelMonitor), HandleError> {
if (self.channel_state & (ChannelState::ChannelFunded as u32)) != (ChannelState::ChannelFunded as u32) {
return Err(HandleError{err: "Got revoke/ACK message when channel was not in an operational state", action: None});
}
Expand DownExpand Up@@ -1942,7 +1942,7 @@ impl Channel {
}
},
PendingHTLCStatus::Forward(forward_info) => {
to_forward_infos.push((forward_info, htlc.htlc_id));
to_forward_infos.push((forward_info, htlc.htlc_id, htlc.cltv_expiry));
htlc.state = InboundHTLCState::Committed;
}
}
Expand DownExpand Up@@ -2152,7 +2152,7 @@ impl Channel {
/// Indicates that the latest ChannelMonitor update has been committed by the client
/// successfully and we should restore normal operation. Returns messages which should be sent
/// to the remote side.
pub fn monitor_updating_restored(&mut self) -> (Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>, RAACommitmentOrder, Vec<(PendingForwardHTLCInfo, u64)>, Vec<(HTLCSource, [u8; 32], HTLCFailReason)>) {
pub fn monitor_updating_restored(&mut self) -> (Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>, RAACommitmentOrder, Vec<(PendingForwardHTLCInfo, u64, u32)>, Vec<(HTLCSource, [u8; 32], HTLCFailReason)>) {
assert_eq!(self.channel_state & ChannelState::MonitorUpdateFailed as u32, ChannelState::MonitorUpdateFailed as u32);
self.channel_state &= !(ChannelState::MonitorUpdateFailed as u32);

Expand DownExpand Up@@ -3489,9 +3489,10 @@ impl Writeable for Channel {
}

(self.monitor_pending_forwards.len() as u64).write(writer)?;
for &(ref pending_forward, ref htlc_id) in self.monitor_pending_forwards.iter() {
for &(ref pending_forward, ref htlc_id, ref cltv_expiry) in self.monitor_pending_forwards.iter() {
pending_forward.write(writer)?;
htlc_id.write(writer)?;
cltv_expiry.write(writer)?;
}

(self.monitor_pending_failures.len() as u64).write(writer)?;
Expand DownExpand Up@@ -3670,7 +3671,7 @@ impl<R : ::std::io::Read> ReadableArgs<R, Arc<Logger>> for Channel {
let monitor_pending_forwards_count: u64 = Readable::read(reader)?;
let mut monitor_pending_forwards = Vec::with_capacity(cmp::min(monitor_pending_forwards_count as usize, OUR_MAX_HTLCS as usize));
for _ in 0..monitor_pending_forwards_count {
monitor_pending_forwards.push((Readable::read(reader)?, Readable::read(reader)?));
monitor_pending_forwards.push((Readable::read(reader)?, Readable::read(reader)?, Readable::read(reader)?));
}

let monitor_pending_failures_count: u64 = Readable::read(reader)?;
Expand Down
82 changes: 73 additions & 9 deletions src/ln/channelmanager.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -96,6 +96,8 @@ mod channel_held_info {
pub(super) short_channel_id: u64,
pub(super) htlc_id: u64,
pub(super) incoming_packet_shared_secret: [u8; 32],
/// Only used to track expiry of claimable_htlcs and fail them backwards
pub(super) cltv_expiry: u32,
}

/// Tracks the inbound corresponding to an outbound HTLC
Expand DownExpand Up@@ -240,6 +242,7 @@ const MIN_HTLC_RELAY_HOLDING_CELL_MILLIS: u32 = 50;
struct HTLCForwardInfo {
prev_short_channel_id: u64,
prev_htlc_id: u64,
prev_cltv_expiry: u32,
forward_info: PendingForwardHTLCInfo,
}

Expand DownExpand Up@@ -1326,11 +1329,12 @@ impl ChannelManager {
Some(chan_id) => chan_id.clone(),
None => {
failed_forwards.reserve(pending_forwards.len());
for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info, prev_cltv_expiry } in pending_forwards.drain(..) {
let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
short_channel_id: prev_short_channel_id,
htlc_id: prev_htlc_id,
incoming_packet_shared_secret: forward_info.incoming_shared_secret,
cltv_expiry: prev_cltv_expiry,
});
failed_forwards.push((htlc_source, forward_info.payment_hash, 0x4000 | 10, None));
}
Expand All@@ -1340,11 +1344,12 @@ impl ChannelManager {
let forward_chan = &mut channel_state.by_id.get_mut(&forward_chan_id).unwrap();

let mut add_htlc_msgs = Vec::new();
for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, prev_cltv_expiry, forward_info } in pending_forwards.drain(..) {
let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
short_channel_id: prev_short_channel_id,
htlc_id: prev_htlc_id,
incoming_packet_shared_secret: forward_info.incoming_shared_secret,
cltv_expiry: prev_cltv_expiry,
});
match forward_chan.send_htlc(forward_info.amt_to_forward, forward_info.payment_hash, forward_info.outgoing_cltv_value, htlc_source.clone(), forward_info.onion_packet.unwrap()) {
Err(_e) => {
Expand DownExpand Up@@ -1398,11 +1403,12 @@ impl ChannelManager {
});
}
} else {
for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, prev_cltv_expiry, forward_info } in pending_forwards.drain(..) {
let prev_hop_data = HTLCPreviousHopData {
short_channel_id: prev_short_channel_id,
htlc_id: prev_htlc_id,
incoming_packet_shared_secret: forward_info.incoming_shared_secret,
cltv_expiry: prev_cltv_expiry,
};
match channel_state.claimable_htlcs.entry(forward_info.payment_hash) {
hash_map::Entry::Occupied(mut entry) => entry.get_mut().push(prev_hop_data),
Expand DownExpand Up@@ -1471,7 +1477,7 @@ impl ChannelManager {
panic!("should have onion error packet here");
}
},
HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, incoming_packet_shared_secret }) => {
HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, incoming_packet_shared_secret, .. }) => {
let err_packet = match onion_error {
HTLCFailReason::Reason { failure_code, data } => {
let packet = ChannelManager::build_failure_packet(&incoming_packet_shared_secret, failure_code, &data[..]).encode();
Expand DownExpand Up@@ -2248,7 +2254,7 @@ impl ChannelManager {
}

#[inline]
fn forward_htlcs(&self, per_source_pending_forwards: &mut [(u64, Vec<(PendingForwardHTLCInfo, u64)>)]) {
fn forward_htlcs(&self, per_source_pending_forwards: &mut [(u64, Vec<(PendingForwardHTLCInfo, u64, u32)>)]) {
for &mut (prev_short_channel_id, ref mut pending_forwards) in per_source_pending_forwards {
let mut forward_event = None;
if !pending_forwards.is_empty() {
Expand All@@ -2257,13 +2263,13 @@ impl ChannelManager {
forward_event = Some(Instant::now() + Duration::from_millis(((rng::rand_f32() * 4.0 + 1.0) * MIN_HTLC_RELAY_HOLDING_CELL_MILLIS as f32) as u64));
channel_state.next_forward = forward_event.unwrap();
}
for (forward_info, prev_htlc_id) in pending_forwards.drain(..) {
for (forward_info, prev_htlc_id, prev_cltv_expiry) in pending_forwards.drain(..) {
match channel_state.forward_htlcs.entry(forward_info.short_channel_id) {
hash_map::Entry::Occupied(mut entry) => {
entry.get_mut().push(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info });
entry.get_mut().push(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, prev_cltv_expiry, forward_info });
},
hash_map::Entry::Vacant(entry) => {
entry.insert(vec!(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info }));
entry.insert(vec!(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, prev_cltv_expiry, forward_info }));
}
}
}
Expand DownExpand Up@@ -2500,6 +2506,7 @@ impl ChainListener for ChannelManager {
fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]) {
let _ = self.total_consistency_lock.read().unwrap();
let mut failed_channels = Vec::new();
let mut timed_out_htlcs = Vec::new();
{
let mut channel_lock = self.channel_state.lock().unwrap();
let channel_state = channel_lock.borrow_parts();
Expand DownExpand Up@@ -2567,10 +2574,27 @@ impl ChainListener for ChannelManager {
}
true
});
channel_state.claimable_htlcs.retain(|payment_hash, htlcs| {
htlcs.retain(|htlc| {
if htlc.cltv_expiry <= height { // XXX: Or <?

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry what means "XXX: or <?" ? You want to substract a safe delay to height ?

@TheBlueMattTheBlueMattNov 16, 2018

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oops, lol, ffs, I really need to double-check my own commits before opening PRs, I blame sleep deprivation after 16 hours of being in a plane, thanks for reviewing...That was a note to myself that I'm not sure if the comparison was supposed to be <= or <, I'll double check and fix the PR.

timed_out_htlcs.push((HTLCSource::PreviousHopData(htlc.clone()), payment_hash.clone()));
false
} else { true }
});
!htlcs.is_empty()
});
}
for failure in failed_channels.drain(..) {
self.finish_force_close_channel(failure);
}
for (source, payment_hash) in timed_out_htlcs.drain(..) {
// Call it preimage_unknown as the issue, ultimately, is that the user failed to
// provide us a preimage within the cltv_expiry time window.
self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), source, &payment_hash, HTLCFailReason::Reason {
failure_code: 0x4000 | 15,
data: Vec::new()
});
}
self.latest_block_height.store(height as usize, Ordering::Release);
*self.last_block_hash.try_lock().expect("block_(dis)connected must not be called in parallel") = header.bitcoin_hash();
}
Expand DownExpand Up@@ -2916,7 +2940,8 @@ impl<R: ::std::io::Read> Readable<R> for PendingHTLCStatus {
impl_writeable!(HTLCPreviousHopData, 0, {
short_channel_id,
htlc_id,
incoming_packet_shared_secret
incoming_packet_shared_secret,
cltv_expiry
});

impl Writeable for HTLCSource {
Expand DownExpand Up@@ -2984,6 +3009,7 @@ impl<R: ::std::io::Read> Readable<R> for HTLCFailReason {
impl_writeable!(HTLCForwardInfo, 0, {
prev_short_channel_id,
prev_htlc_id,
prev_cltv_expiry,
forward_info
});

Expand DownExpand Up@@ -7263,6 +7289,44 @@ mod tests {
do_test_monitor_temporary_update_fail(3 | 8 | 16);
}

#[test]
fn test_htlc_timeout() {
// If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
// to avoid our counterparty failing the channel.
let secp_ctx = Secp256k1::new();
let nodes = create_network(2);

create_announced_chan_between_nodes(&nodes, 0, 1);
let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 100000);

let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
nodes[0].chain_monitor.block_connected_checked(&header, 101, &[], &[]);
nodes[1].chain_monitor.block_connected_checked(&header, 101, &[], &[]);
for i in 102..TEST_FINAL_CLTV + 100 + 1 {
header.prev_blockhash = header.bitcoin_hash();
nodes[0].chain_monitor.block_connected_checked(&header, i, &[], &[]);
nodes[1].chain_monitor.block_connected_checked(&header, i, &[], &[]);
}

check_added_monitors!(nodes[1], 1);
let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
assert!(htlc_timeout_updates.update_fee.is_none());

nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]).unwrap();
commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
let events = nodes[0].node.get_and_clear_pending_events();
match events[0] {
Event::PaymentFailed { payment_hash, rejected_by_dest } => {
assert_eq!(payment_hash, our_payment_hash);
assert!(rejected_by_dest);
},
_ => panic!("Unexpected event"),
}
}

#[test]
fn test_invalid_channel_announcement() {
//Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
Expand Down
3 changes: 3 additions & 0 deletions src/util/events.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -57,6 +57,9 @@ pub enum Event {
/// PaymentFailReason::AmountMismatch, respectively, to free up resources for this HTLC.
/// The amount paid should be considered 'incorrect' when it is less than or more than twice
/// the amount expected.
/// If you fail to call either ChannelManager::claim_funds of
/// ChannelManager::fail_htlc_backwards within the HTLC's timeout, the HTLC will be
/// automatically failed with PaymentFailReason::PreimageUnknown.
PaymentReceived {
/// The hash for which the preimage should be handed to the ChannelManager.
payment_hash: [u8; 32],
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 7 additions & 6 deletions src/ln/channel.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -264,7 +264,7 @@ pub(super) struct Channel {
monitor_pending_revoke_and_ack: bool,
monitor_pending_commitment_signed: bool,
monitor_pending_order: Option<RAACommitmentOrder>,
monitor_pending_forwards: Vec<(PendingForwardHTLCInfo, u64)>,
monitor_pending_forwards: Vec<(PendingForwardHTLCInfo, u64, u32)>,
monitor_pending_failures: Vec<(HTLCSource, [u8; 32], HTLCFailReason)>,

// pending_update_fee is filled when sending and receiving update_fee
Expand DownExpand Up@@ -1854,7 +1854,7 @@ impl Channel {
/// waiting on this revoke_and_ack. The generation of this new commitment_signed may also fail,
/// generating an appropriate error *after* the channel state has been updated based on the
/// revoke_and_ack message.
pub fn revoke_and_ack(&mut self, msg: &msgs::RevokeAndACK, fee_estimator: &FeeEstimator) -> Result<(Option<msgs::CommitmentUpdate>, Vec<(PendingForwardHTLCInfo, u64)>, Vec<(HTLCSource, [u8; 32], HTLCFailReason)>, Option<msgs::ClosingSigned>, ChannelMonitor), HandleError> {
pub fn revoke_and_ack(&mut self, msg: &msgs::RevokeAndACK, fee_estimator: &FeeEstimator) -> Result<(Option<msgs::CommitmentUpdate>, Vec<(PendingForwardHTLCInfo, u64, u32)>, Vec<(HTLCSource, [u8; 32], HTLCFailReason)>, Option<msgs::ClosingSigned>, ChannelMonitor), HandleError> {
if (self.channel_state & (ChannelState::ChannelFunded as u32)) != (ChannelState::ChannelFunded as u32) {
return Err(HandleError{err: "Got revoke/ACK message when channel was not in an operational state", action: None});
}
Expand DownExpand Up@@ -1942,7 +1942,7 @@ impl Channel {
}
},
PendingHTLCStatus::Forward(forward_info) => {
to_forward_infos.push((forward_info, htlc.htlc_id));
to_forward_infos.push((forward_info, htlc.htlc_id, htlc.cltv_expiry));
htlc.state = InboundHTLCState::Committed;
}
}
Expand DownExpand Up@@ -2152,7 +2152,7 @@ impl Channel {
/// Indicates that the latest ChannelMonitor update has been committed by the client
/// successfully and we should restore normal operation. Returns messages which should be sent
/// to the remote side.
pub fn monitor_updating_restored(&mut self) -> (Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>, RAACommitmentOrder, Vec<(PendingForwardHTLCInfo, u64)>, Vec<(HTLCSource, [u8; 32], HTLCFailReason)>) {
pub fn monitor_updating_restored(&mut self) -> (Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>, RAACommitmentOrder, Vec<(PendingForwardHTLCInfo, u64, u32)>, Vec<(HTLCSource, [u8; 32], HTLCFailReason)>) {
assert_eq!(self.channel_state & ChannelState::MonitorUpdateFailed as u32, ChannelState::MonitorUpdateFailed as u32);
self.channel_state &= !(ChannelState::MonitorUpdateFailed as u32);

Expand DownExpand Up@@ -3489,9 +3489,10 @@ impl Writeable for Channel {
}

(self.monitor_pending_forwards.len() as u64).write(writer)?;
for &(ref pending_forward, ref htlc_id) in self.monitor_pending_forwards.iter() {
for &(ref pending_forward, ref htlc_id, ref cltv_expiry) in self.monitor_pending_forwards.iter() {
pending_forward.write(writer)?;
htlc_id.write(writer)?;
cltv_expiry.write(writer)?;
}

(self.monitor_pending_failures.len() as u64).write(writer)?;
Expand DownExpand Up@@ -3670,7 +3671,7 @@ impl<R : ::std::io::Read> ReadableArgs<R, Arc<Logger>> for Channel {
let monitor_pending_forwards_count: u64 = Readable::read(reader)?;
let mut monitor_pending_forwards = Vec::with_capacity(cmp::min(monitor_pending_forwards_count as usize, OUR_MAX_HTLCS as usize));
for _ in 0..monitor_pending_forwards_count {
monitor_pending_forwards.push((Readable::read(reader)?, Readable::read(reader)?));
monitor_pending_forwards.push((Readable::read(reader)?, Readable::read(reader)?, Readable::read(reader)?));
}

let monitor_pending_failures_count: u64 = Readable::read(reader)?;
Expand Down
82 changes: 73 additions & 9 deletions src/ln/channelmanager.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -96,6 +96,8 @@ mod channel_held_info {
pub(super) short_channel_id: u64,
pub(super) htlc_id: u64,
pub(super) incoming_packet_shared_secret: [u8; 32],
/// Only used to track expiry of claimable_htlcs and fail them backwards
pub(super) cltv_expiry: u32,
}

/// Tracks the inbound corresponding to an outbound HTLC
Expand DownExpand Up@@ -240,6 +242,7 @@ const MIN_HTLC_RELAY_HOLDING_CELL_MILLIS: u32 = 50;
struct HTLCForwardInfo {
prev_short_channel_id: u64,
prev_htlc_id: u64,
prev_cltv_expiry: u32,
forward_info: PendingForwardHTLCInfo,
}

Expand DownExpand Up@@ -1326,11 +1329,12 @@ impl ChannelManager {
Some(chan_id) => chan_id.clone(),
None => {
failed_forwards.reserve(pending_forwards.len());
for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info, prev_cltv_expiry } in pending_forwards.drain(..) {
let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
short_channel_id: prev_short_channel_id,
htlc_id: prev_htlc_id,
incoming_packet_shared_secret: forward_info.incoming_shared_secret,
cltv_expiry: prev_cltv_expiry,
});
failed_forwards.push((htlc_source, forward_info.payment_hash, 0x4000 | 10, None));
}
Expand All@@ -1340,11 +1344,12 @@ impl ChannelManager {
let forward_chan = &mut channel_state.by_id.get_mut(&forward_chan_id).unwrap();

let mut add_htlc_msgs = Vec::new();
for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, prev_cltv_expiry, forward_info } in pending_forwards.drain(..) {
let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
short_channel_id: prev_short_channel_id,
htlc_id: prev_htlc_id,
incoming_packet_shared_secret: forward_info.incoming_shared_secret,
cltv_expiry: prev_cltv_expiry,
});
match forward_chan.send_htlc(forward_info.amt_to_forward, forward_info.payment_hash, forward_info.outgoing_cltv_value, htlc_source.clone(), forward_info.onion_packet.unwrap()) {
Err(_e) => {
Expand DownExpand Up@@ -1398,11 +1403,12 @@ impl ChannelManager {
});
}
} else {
for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, prev_cltv_expiry, forward_info } in pending_forwards.drain(..) {
let prev_hop_data = HTLCPreviousHopData {
short_channel_id: prev_short_channel_id,
htlc_id: prev_htlc_id,
incoming_packet_shared_secret: forward_info.incoming_shared_secret,
cltv_expiry: prev_cltv_expiry,
};
match channel_state.claimable_htlcs.entry(forward_info.payment_hash) {
hash_map::Entry::Occupied(mut entry) => entry.get_mut().push(prev_hop_data),
Expand DownExpand Up@@ -1471,7 +1477,7 @@ impl ChannelManager {
panic!("should have onion error packet here");
}
},
HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, incoming_packet_shared_secret }) => {
HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, incoming_packet_shared_secret, .. }) => {
let err_packet = match onion_error {
HTLCFailReason::Reason { failure_code, data } => {
let packet = ChannelManager::build_failure_packet(&incoming_packet_shared_secret, failure_code, &data[..]).encode();
Expand DownExpand Up@@ -2248,7 +2254,7 @@ impl ChannelManager {
}

#[inline]
fn forward_htlcs(&self, per_source_pending_forwards: &mut [(u64, Vec<(PendingForwardHTLCInfo, u64)>)]) {
fn forward_htlcs(&self, per_source_pending_forwards: &mut [(u64, Vec<(PendingForwardHTLCInfo, u64, u32)>)]) {
for &mut (prev_short_channel_id, ref mut pending_forwards) in per_source_pending_forwards {
let mut forward_event = None;
if !pending_forwards.is_empty() {
Expand All@@ -2257,13 +2263,13 @@ impl ChannelManager {
forward_event = Some(Instant::now() + Duration::from_millis(((rng::rand_f32() * 4.0 + 1.0) * MIN_HTLC_RELAY_HOLDING_CELL_MILLIS as f32) as u64));
channel_state.next_forward = forward_event.unwrap();
}
for (forward_info, prev_htlc_id) in pending_forwards.drain(..) {
for (forward_info, prev_htlc_id, prev_cltv_expiry) in pending_forwards.drain(..) {
match channel_state.forward_htlcs.entry(forward_info.short_channel_id) {
hash_map::Entry::Occupied(mut entry) => {
entry.get_mut().push(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info });
entry.get_mut().push(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, prev_cltv_expiry, forward_info });
},
hash_map::Entry::Vacant(entry) => {
entry.insert(vec!(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info }));
entry.insert(vec!(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, prev_cltv_expiry, forward_info }));
}
}
}
Expand DownExpand Up@@ -2500,6 +2506,7 @@ impl ChainListener for ChannelManager {
fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]) {
let _ = self.total_consistency_lock.read().unwrap();
let mut failed_channels = Vec::new();
let mut timed_out_htlcs = Vec::new();
{
let mut channel_lock = self.channel_state.lock().unwrap();
let channel_state = channel_lock.borrow_parts();
Expand DownExpand Up@@ -2567,10 +2574,27 @@ impl ChainListener for ChannelManager {
}
true
});
channel_state.claimable_htlcs.retain(|payment_hash, htlcs| {
htlcs.retain(|htlc| {
if htlc.cltv_expiry <= height { // XXX: Or <?

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry what means "XXX: or <?" ? You want to substract a safe delay to height ?

@TheBlueMattTheBlueMattNov 16, 2018

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oops, lol, ffs, I really need to double-check my own commits before opening PRs, I blame sleep deprivation after 16 hours of being in a plane, thanks for reviewing...That was a note to myself that I'm not sure if the comparison was supposed to be <= or <, I'll double check and fix the PR.

timed_out_htlcs.push((HTLCSource::PreviousHopData(htlc.clone()), payment_hash.clone()));
false
} else { true }
});
!htlcs.is_empty()
});
}
for failure in failed_channels.drain(..) {
self.finish_force_close_channel(failure);
}
for (source, payment_hash) in timed_out_htlcs.drain(..) {
// Call it preimage_unknown as the issue, ultimately, is that the user failed to
// provide us a preimage within the cltv_expiry time window.
self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), source, &payment_hash, HTLCFailReason::Reason {
failure_code: 0x4000 | 15,
data: Vec::new()
});
}
self.latest_block_height.store(height as usize, Ordering::Release);
*self.last_block_hash.try_lock().expect("block_(dis)connected must not be called in parallel") = header.bitcoin_hash();
}
Expand DownExpand Up@@ -2916,7 +2940,8 @@ impl<R: ::std::io::Read> Readable<R> for PendingHTLCStatus {
impl_writeable!(HTLCPreviousHopData, 0, {
short_channel_id,
htlc_id,
incoming_packet_shared_secret
incoming_packet_shared_secret,
cltv_expiry
});

impl Writeable for HTLCSource {
Expand DownExpand Up@@ -2984,6 +3009,7 @@ impl<R: ::std::io::Read> Readable<R> for HTLCFailReason {
impl_writeable!(HTLCForwardInfo, 0, {
prev_short_channel_id,
prev_htlc_id,
prev_cltv_expiry,
forward_info
});

Expand DownExpand Up@@ -7263,6 +7289,44 @@ mod tests {
do_test_monitor_temporary_update_fail(3 | 8 | 16);
}

#[test]
fn test_htlc_timeout() {
// If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
// to avoid our counterparty failing the channel.
let secp_ctx = Secp256k1::new();
let nodes = create_network(2);

create_announced_chan_between_nodes(&nodes, 0, 1);
let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 100000);

let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
nodes[0].chain_monitor.block_connected_checked(&header, 101, &[], &[]);
nodes[1].chain_monitor.block_connected_checked(&header, 101, &[], &[]);
for i in 102..TEST_FINAL_CLTV + 100 + 1 {
header.prev_blockhash = header.bitcoin_hash();
nodes[0].chain_monitor.block_connected_checked(&header, i, &[], &[]);
nodes[1].chain_monitor.block_connected_checked(&header, i, &[], &[]);
}

check_added_monitors!(nodes[1], 1);
let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
assert!(htlc_timeout_updates.update_fee.is_none());

nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]).unwrap();
commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
let events = nodes[0].node.get_and_clear_pending_events();
match events[0] {
Event::PaymentFailed { payment_hash, rejected_by_dest } => {
assert_eq!(payment_hash, our_payment_hash);
assert!(rejected_by_dest);
},
_ => panic!("Unexpected event"),
}
}

#[test]
fn test_invalid_channel_announcement() {
//Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
Expand Down
3 changes: 3 additions & 0 deletions src/util/events.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -57,6 +57,9 @@ pub enum Event {
/// PaymentFailReason::AmountMismatch, respectively, to free up resources for this HTLC.
/// The amount paid should be considered 'incorrect' when it is less than or more than twice
/// the amount expected.
/// If you fail to call either ChannelManager::claim_funds of
/// ChannelManager::fail_htlc_backwards within the HTLC's timeout, the HTLC will be
/// automatically failed with PaymentFailReason::PreimageUnknown.
PaymentReceived {
/// The hash for which the preimage should be handed to the ChannelManager.
payment_hash: [u8; 32],
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 7 additions & 6 deletions src/ln/channel.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -264,7 +264,7 @@ pub(super) struct Channel {
monitor_pending_revoke_and_ack: bool,
monitor_pending_commitment_signed: bool,
monitor_pending_order: Option<RAACommitmentOrder>,
monitor_pending_forwards: Vec<(PendingForwardHTLCInfo, u64)>,
monitor_pending_forwards: Vec<(PendingForwardHTLCInfo, u64, u32)>,
monitor_pending_failures: Vec<(HTLCSource, [u8; 32], HTLCFailReason)>,

// pending_update_fee is filled when sending and receiving update_fee
Expand DownExpand Up@@ -1854,7 +1854,7 @@ impl Channel {
/// waiting on this revoke_and_ack. The generation of this new commitment_signed may also fail,
/// generating an appropriate error *after* the channel state has been updated based on the
/// revoke_and_ack message.
pub fn revoke_and_ack(&mut self, msg: &msgs::RevokeAndACK, fee_estimator: &FeeEstimator) -> Result<(Option<msgs::CommitmentUpdate>, Vec<(PendingForwardHTLCInfo, u64)>, Vec<(HTLCSource, [u8; 32], HTLCFailReason)>, Option<msgs::ClosingSigned>, ChannelMonitor), HandleError> {
pub fn revoke_and_ack(&mut self, msg: &msgs::RevokeAndACK, fee_estimator: &FeeEstimator) -> Result<(Option<msgs::CommitmentUpdate>, Vec<(PendingForwardHTLCInfo, u64, u32)>, Vec<(HTLCSource, [u8; 32], HTLCFailReason)>, Option<msgs::ClosingSigned>, ChannelMonitor), HandleError> {
if (self.channel_state & (ChannelState::ChannelFunded as u32)) != (ChannelState::ChannelFunded as u32) {
return Err(HandleError{err: "Got revoke/ACK message when channel was not in an operational state", action: None});
}
Expand DownExpand Up@@ -1942,7 +1942,7 @@ impl Channel {
}
},
PendingHTLCStatus::Forward(forward_info) => {
to_forward_infos.push((forward_info, htlc.htlc_id));
to_forward_infos.push((forward_info, htlc.htlc_id, htlc.cltv_expiry));
htlc.state = InboundHTLCState::Committed;
}
}
Expand DownExpand Up@@ -2152,7 +2152,7 @@ impl Channel {
/// Indicates that the latest ChannelMonitor update has been committed by the client
/// successfully and we should restore normal operation. Returns messages which should be sent
/// to the remote side.
pub fn monitor_updating_restored(&mut self) -> (Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>, RAACommitmentOrder, Vec<(PendingForwardHTLCInfo, u64)>, Vec<(HTLCSource, [u8; 32], HTLCFailReason)>) {
pub fn monitor_updating_restored(&mut self) -> (Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>, RAACommitmentOrder, Vec<(PendingForwardHTLCInfo, u64, u32)>, Vec<(HTLCSource, [u8; 32], HTLCFailReason)>) {
assert_eq!(self.channel_state & ChannelState::MonitorUpdateFailed as u32, ChannelState::MonitorUpdateFailed as u32);
self.channel_state &= !(ChannelState::MonitorUpdateFailed as u32);

Expand DownExpand Up@@ -3489,9 +3489,10 @@ impl Writeable for Channel {
}

(self.monitor_pending_forwards.len() as u64).write(writer)?;
for &(ref pending_forward, ref htlc_id) in self.monitor_pending_forwards.iter() {
for &(ref pending_forward, ref htlc_id, ref cltv_expiry) in self.monitor_pending_forwards.iter() {
pending_forward.write(writer)?;
htlc_id.write(writer)?;
cltv_expiry.write(writer)?;
}

(self.monitor_pending_failures.len() as u64).write(writer)?;
Expand DownExpand Up@@ -3670,7 +3671,7 @@ impl<R : ::std::io::Read> ReadableArgs<R, Arc<Logger>> for Channel {
let monitor_pending_forwards_count: u64 = Readable::read(reader)?;
let mut monitor_pending_forwards = Vec::with_capacity(cmp::min(monitor_pending_forwards_count as usize, OUR_MAX_HTLCS as usize));
for _ in 0..monitor_pending_forwards_count {
monitor_pending_forwards.push((Readable::read(reader)?, Readable::read(reader)?));
monitor_pending_forwards.push((Readable::read(reader)?, Readable::read(reader)?, Readable::read(reader)?));
}

let monitor_pending_failures_count: u64 = Readable::read(reader)?;
Expand Down
82 changes: 73 additions & 9 deletions src/ln/channelmanager.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -96,6 +96,8 @@ mod channel_held_info {
pub(super) short_channel_id: u64,
pub(super) htlc_id: u64,
pub(super) incoming_packet_shared_secret: [u8; 32],
/// Only used to track expiry of claimable_htlcs and fail them backwards
pub(super) cltv_expiry: u32,
}

/// Tracks the inbound corresponding to an outbound HTLC
Expand DownExpand Up@@ -240,6 +242,7 @@ const MIN_HTLC_RELAY_HOLDING_CELL_MILLIS: u32 = 50;
struct HTLCForwardInfo {
prev_short_channel_id: u64,
prev_htlc_id: u64,
prev_cltv_expiry: u32,
forward_info: PendingForwardHTLCInfo,
}

Expand DownExpand Up@@ -1326,11 +1329,12 @@ impl ChannelManager {
Some(chan_id) => chan_id.clone(),
None => {
failed_forwards.reserve(pending_forwards.len());
for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info, prev_cltv_expiry } in pending_forwards.drain(..) {
let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
short_channel_id: prev_short_channel_id,
htlc_id: prev_htlc_id,
incoming_packet_shared_secret: forward_info.incoming_shared_secret,
cltv_expiry: prev_cltv_expiry,
});
failed_forwards.push((htlc_source, forward_info.payment_hash, 0x4000 | 10, None));
}
Expand All@@ -1340,11 +1344,12 @@ impl ChannelManager {
let forward_chan = &mut channel_state.by_id.get_mut(&forward_chan_id).unwrap();

let mut add_htlc_msgs = Vec::new();
for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, prev_cltv_expiry, forward_info } in pending_forwards.drain(..) {
let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
short_channel_id: prev_short_channel_id,
htlc_id: prev_htlc_id,
incoming_packet_shared_secret: forward_info.incoming_shared_secret,
cltv_expiry: prev_cltv_expiry,
});
match forward_chan.send_htlc(forward_info.amt_to_forward, forward_info.payment_hash, forward_info.outgoing_cltv_value, htlc_source.clone(), forward_info.onion_packet.unwrap()) {
Err(_e) => {
Expand DownExpand Up@@ -1398,11 +1403,12 @@ impl ChannelManager {
});
}
} else {
for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, prev_cltv_expiry, forward_info } in pending_forwards.drain(..) {
let prev_hop_data = HTLCPreviousHopData {
short_channel_id: prev_short_channel_id,
htlc_id: prev_htlc_id,
incoming_packet_shared_secret: forward_info.incoming_shared_secret,
cltv_expiry: prev_cltv_expiry,
};
match channel_state.claimable_htlcs.entry(forward_info.payment_hash) {
hash_map::Entry::Occupied(mut entry) => entry.get_mut().push(prev_hop_data),
Expand DownExpand Up@@ -1471,7 +1477,7 @@ impl ChannelManager {
panic!("should have onion error packet here");
}
},
HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, incoming_packet_shared_secret }) => {
HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, incoming_packet_shared_secret, .. }) => {
let err_packet = match onion_error {
HTLCFailReason::Reason { failure_code, data } => {
let packet = ChannelManager::build_failure_packet(&incoming_packet_shared_secret, failure_code, &data[..]).encode();
Expand DownExpand Up@@ -2248,7 +2254,7 @@ impl ChannelManager {
}

#[inline]
fn forward_htlcs(&self, per_source_pending_forwards: &mut [(u64, Vec<(PendingForwardHTLCInfo, u64)>)]) {
fn forward_htlcs(&self, per_source_pending_forwards: &mut [(u64, Vec<(PendingForwardHTLCInfo, u64, u32)>)]) {
for &mut (prev_short_channel_id, ref mut pending_forwards) in per_source_pending_forwards {
let mut forward_event = None;
if !pending_forwards.is_empty() {
Expand All@@ -2257,13 +2263,13 @@ impl ChannelManager {
forward_event = Some(Instant::now() + Duration::from_millis(((rng::rand_f32() * 4.0 + 1.0) * MIN_HTLC_RELAY_HOLDING_CELL_MILLIS as f32) as u64));
channel_state.next_forward = forward_event.unwrap();
}
for (forward_info, prev_htlc_id) in pending_forwards.drain(..) {
for (forward_info, prev_htlc_id, prev_cltv_expiry) in pending_forwards.drain(..) {
match channel_state.forward_htlcs.entry(forward_info.short_channel_id) {
hash_map::Entry::Occupied(mut entry) => {
entry.get_mut().push(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info });
entry.get_mut().push(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, prev_cltv_expiry, forward_info });
},
hash_map::Entry::Vacant(entry) => {
entry.insert(vec!(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info }));
entry.insert(vec!(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, prev_cltv_expiry, forward_info }));
}
}
}
Expand DownExpand Up@@ -2500,6 +2506,7 @@ impl ChainListener for ChannelManager {
fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]) {
let _ = self.total_consistency_lock.read().unwrap();
let mut failed_channels = Vec::new();
let mut timed_out_htlcs = Vec::new();
{
let mut channel_lock = self.channel_state.lock().unwrap();
let channel_state = channel_lock.borrow_parts();
Expand DownExpand Up@@ -2567,10 +2574,27 @@ impl ChainListener for ChannelManager {
}
true
});
channel_state.claimable_htlcs.retain(|payment_hash, htlcs| {
htlcs.retain(|htlc| {
if htlc.cltv_expiry <= height { // XXX: Or <?

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry what means "XXX: or <?" ? You want to substract a safe delay to height ?

@TheBlueMattTheBlueMattNov 16, 2018

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oops, lol, ffs, I really need to double-check my own commits before opening PRs, I blame sleep deprivation after 16 hours of being in a plane, thanks for reviewing...That was a note to myself that I'm not sure if the comparison was supposed to be <= or <, I'll double check and fix the PR.

timed_out_htlcs.push((HTLCSource::PreviousHopData(htlc.clone()), payment_hash.clone()));
false
} else { true }
});
!htlcs.is_empty()
});
}
for failure in failed_channels.drain(..) {
self.finish_force_close_channel(failure);
}
for (source, payment_hash) in timed_out_htlcs.drain(..) {
// Call it preimage_unknown as the issue, ultimately, is that the user failed to
// provide us a preimage within the cltv_expiry time window.
self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), source, &payment_hash, HTLCFailReason::Reason {
failure_code: 0x4000 | 15,
data: Vec::new()
});
}
self.latest_block_height.store(height as usize, Ordering::Release);
*self.last_block_hash.try_lock().expect("block_(dis)connected must not be called in parallel") = header.bitcoin_hash();
}
Expand DownExpand Up@@ -2916,7 +2940,8 @@ impl<R: ::std::io::Read> Readable<R> for PendingHTLCStatus {
impl_writeable!(HTLCPreviousHopData, 0, {
short_channel_id,
htlc_id,
incoming_packet_shared_secret
incoming_packet_shared_secret,
cltv_expiry
});

impl Writeable for HTLCSource {
Expand DownExpand Up@@ -2984,6 +3009,7 @@ impl<R: ::std::io::Read> Readable<R> for HTLCFailReason {
impl_writeable!(HTLCForwardInfo, 0, {
prev_short_channel_id,
prev_htlc_id,
prev_cltv_expiry,
forward_info
});

Expand DownExpand Up@@ -7263,6 +7289,44 @@ mod tests {
do_test_monitor_temporary_update_fail(3 | 8 | 16);
}

#[test]
fn test_htlc_timeout() {
// If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
// to avoid our counterparty failing the channel.
let secp_ctx = Secp256k1::new();
let nodes = create_network(2);

create_announced_chan_between_nodes(&nodes, 0, 1);
let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 100000);

let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
nodes[0].chain_monitor.block_connected_checked(&header, 101, &[], &[]);
nodes[1].chain_monitor.block_connected_checked(&header, 101, &[], &[]);
for i in 102..TEST_FINAL_CLTV + 100 + 1 {
header.prev_blockhash = header.bitcoin_hash();
nodes[0].chain_monitor.block_connected_checked(&header, i, &[], &[]);
nodes[1].chain_monitor.block_connected_checked(&header, i, &[], &[]);
}

check_added_monitors!(nodes[1], 1);
let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
assert!(htlc_timeout_updates.update_fee.is_none());

nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]).unwrap();
commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
let events = nodes[0].node.get_and_clear_pending_events();
match events[0] {
Event::PaymentFailed { payment_hash, rejected_by_dest } => {
assert_eq!(payment_hash, our_payment_hash);
assert!(rejected_by_dest);
},
_ => panic!("Unexpected event"),
}
}

#[test]
fn test_invalid_channel_announcement() {
//Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
Expand Down
3 changes: 3 additions & 0 deletions src/util/events.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -57,6 +57,9 @@ pub enum Event {
/// PaymentFailReason::AmountMismatch, respectively, to free up resources for this HTLC.
/// The amount paid should be considered 'incorrect' when it is less than or more than twice
/// the amount expected.
/// If you fail to call either ChannelManager::claim_funds of
/// ChannelManager::fail_htlc_backwards within the HTLC's timeout, the HTLC will be
/// automatically failed with PaymentFailReason::PreimageUnknown.
PaymentReceived {
/// The hash for which the preimage should be handed to the ChannelManager.
payment_hash: [u8; 32],
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 7 additions & 6 deletions src/ln/channel.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -264,7 +264,7 @@ pub(super) struct Channel {
monitor_pending_revoke_and_ack: bool,
monitor_pending_commitment_signed: bool,
monitor_pending_order: Option<RAACommitmentOrder>,
monitor_pending_forwards: Vec<(PendingForwardHTLCInfo, u64)>,
monitor_pending_forwards: Vec<(PendingForwardHTLCInfo, u64, u32)>,
monitor_pending_failures: Vec<(HTLCSource, [u8; 32], HTLCFailReason)>,

// pending_update_fee is filled when sending and receiving update_fee
Expand DownExpand Up@@ -1854,7 +1854,7 @@ impl Channel {
/// waiting on this revoke_and_ack. The generation of this new commitment_signed may also fail,
/// generating an appropriate error *after* the channel state has been updated based on the
/// revoke_and_ack message.
pub fn revoke_and_ack(&mut self, msg: &msgs::RevokeAndACK, fee_estimator: &FeeEstimator) -> Result<(Option<msgs::CommitmentUpdate>, Vec<(PendingForwardHTLCInfo, u64)>, Vec<(HTLCSource, [u8; 32], HTLCFailReason)>, Option<msgs::ClosingSigned>, ChannelMonitor), HandleError> {
pub fn revoke_and_ack(&mut self, msg: &msgs::RevokeAndACK, fee_estimator: &FeeEstimator) -> Result<(Option<msgs::CommitmentUpdate>, Vec<(PendingForwardHTLCInfo, u64, u32)>, Vec<(HTLCSource, [u8; 32], HTLCFailReason)>, Option<msgs::ClosingSigned>, ChannelMonitor), HandleError> {
if (self.channel_state & (ChannelState::ChannelFunded as u32)) != (ChannelState::ChannelFunded as u32) {
return Err(HandleError{err: "Got revoke/ACK message when channel was not in an operational state", action: None});
}
Expand DownExpand Up@@ -1942,7 +1942,7 @@ impl Channel {
}
},
PendingHTLCStatus::Forward(forward_info) => {
to_forward_infos.push((forward_info, htlc.htlc_id));
to_forward_infos.push((forward_info, htlc.htlc_id, htlc.cltv_expiry));
htlc.state = InboundHTLCState::Committed;
}
}
Expand DownExpand Up@@ -2152,7 +2152,7 @@ impl Channel {
/// Indicates that the latest ChannelMonitor update has been committed by the client
/// successfully and we should restore normal operation. Returns messages which should be sent
/// to the remote side.
pub fn monitor_updating_restored(&mut self) -> (Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>, RAACommitmentOrder, Vec<(PendingForwardHTLCInfo, u64)>, Vec<(HTLCSource, [u8; 32], HTLCFailReason)>) {
pub fn monitor_updating_restored(&mut self) -> (Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>, RAACommitmentOrder, Vec<(PendingForwardHTLCInfo, u64, u32)>, Vec<(HTLCSource, [u8; 32], HTLCFailReason)>) {
assert_eq!(self.channel_state & ChannelState::MonitorUpdateFailed as u32, ChannelState::MonitorUpdateFailed as u32);
self.channel_state &= !(ChannelState::MonitorUpdateFailed as u32);

Expand DownExpand Up@@ -3489,9 +3489,10 @@ impl Writeable for Channel {
}

(self.monitor_pending_forwards.len() as u64).write(writer)?;
for &(ref pending_forward, ref htlc_id) in self.monitor_pending_forwards.iter() {
for &(ref pending_forward, ref htlc_id, ref cltv_expiry) in self.monitor_pending_forwards.iter() {
pending_forward.write(writer)?;
htlc_id.write(writer)?;
cltv_expiry.write(writer)?;
}

(self.monitor_pending_failures.len() as u64).write(writer)?;
Expand DownExpand Up@@ -3670,7 +3671,7 @@ impl<R : ::std::io::Read> ReadableArgs<R, Arc<Logger>> for Channel {
let monitor_pending_forwards_count: u64 = Readable::read(reader)?;
let mut monitor_pending_forwards = Vec::with_capacity(cmp::min(monitor_pending_forwards_count as usize, OUR_MAX_HTLCS as usize));
for _ in 0..monitor_pending_forwards_count {
monitor_pending_forwards.push((Readable::read(reader)?, Readable::read(reader)?));
monitor_pending_forwards.push((Readable::read(reader)?, Readable::read(reader)?, Readable::read(reader)?));
}

let monitor_pending_failures_count: u64 = Readable::read(reader)?;
Expand Down
82 changes: 73 additions & 9 deletions src/ln/channelmanager.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -96,6 +96,8 @@ mod channel_held_info {
pub(super) short_channel_id: u64,
pub(super) htlc_id: u64,
pub(super) incoming_packet_shared_secret: [u8; 32],
/// Only used to track expiry of claimable_htlcs and fail them backwards
pub(super) cltv_expiry: u32,
}

/// Tracks the inbound corresponding to an outbound HTLC
Expand DownExpand Up@@ -240,6 +242,7 @@ const MIN_HTLC_RELAY_HOLDING_CELL_MILLIS: u32 = 50;
struct HTLCForwardInfo {
prev_short_channel_id: u64,
prev_htlc_id: u64,
prev_cltv_expiry: u32,
forward_info: PendingForwardHTLCInfo,
}

Expand DownExpand Up@@ -1326,11 +1329,12 @@ impl ChannelManager {
Some(chan_id) => chan_id.clone(),
None => {
failed_forwards.reserve(pending_forwards.len());
for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info, prev_cltv_expiry } in pending_forwards.drain(..) {
let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
short_channel_id: prev_short_channel_id,
htlc_id: prev_htlc_id,
incoming_packet_shared_secret: forward_info.incoming_shared_secret,
cltv_expiry: prev_cltv_expiry,
});
failed_forwards.push((htlc_source, forward_info.payment_hash, 0x4000 | 10, None));
}
Expand All@@ -1340,11 +1344,12 @@ impl ChannelManager {
let forward_chan = &mut channel_state.by_id.get_mut(&forward_chan_id).unwrap();

let mut add_htlc_msgs = Vec::new();
for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, prev_cltv_expiry, forward_info } in pending_forwards.drain(..) {
let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
short_channel_id: prev_short_channel_id,
htlc_id: prev_htlc_id,
incoming_packet_shared_secret: forward_info.incoming_shared_secret,
cltv_expiry: prev_cltv_expiry,
});
match forward_chan.send_htlc(forward_info.amt_to_forward, forward_info.payment_hash, forward_info.outgoing_cltv_value, htlc_source.clone(), forward_info.onion_packet.unwrap()) {
Err(_e) => {
Expand DownExpand Up@@ -1398,11 +1403,12 @@ impl ChannelManager {
});
}
} else {
for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, prev_cltv_expiry, forward_info } in pending_forwards.drain(..) {
let prev_hop_data = HTLCPreviousHopData {
short_channel_id: prev_short_channel_id,
htlc_id: prev_htlc_id,
incoming_packet_shared_secret: forward_info.incoming_shared_secret,
cltv_expiry: prev_cltv_expiry,
};
match channel_state.claimable_htlcs.entry(forward_info.payment_hash) {
hash_map::Entry::Occupied(mut entry) => entry.get_mut().push(prev_hop_data),
Expand DownExpand Up@@ -1471,7 +1477,7 @@ impl ChannelManager {
panic!("should have onion error packet here");
}
},
HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, incoming_packet_shared_secret }) => {
HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, incoming_packet_shared_secret, .. }) => {
let err_packet = match onion_error {
HTLCFailReason::Reason { failure_code, data } => {
let packet = ChannelManager::build_failure_packet(&incoming_packet_shared_secret, failure_code, &data[..]).encode();
Expand DownExpand Up@@ -2248,7 +2254,7 @@ impl ChannelManager {
}

#[inline]
fn forward_htlcs(&self, per_source_pending_forwards: &mut [(u64, Vec<(PendingForwardHTLCInfo, u64)>)]) {
fn forward_htlcs(&self, per_source_pending_forwards: &mut [(u64, Vec<(PendingForwardHTLCInfo, u64, u32)>)]) {
for &mut (prev_short_channel_id, ref mut pending_forwards) in per_source_pending_forwards {
let mut forward_event = None;
if !pending_forwards.is_empty() {
Expand All@@ -2257,13 +2263,13 @@ impl ChannelManager {
forward_event = Some(Instant::now() + Duration::from_millis(((rng::rand_f32() * 4.0 + 1.0) * MIN_HTLC_RELAY_HOLDING_CELL_MILLIS as f32) as u64));
channel_state.next_forward = forward_event.unwrap();
}
for (forward_info, prev_htlc_id) in pending_forwards.drain(..) {
for (forward_info, prev_htlc_id, prev_cltv_expiry) in pending_forwards.drain(..) {
match channel_state.forward_htlcs.entry(forward_info.short_channel_id) {
hash_map::Entry::Occupied(mut entry) => {
entry.get_mut().push(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info });
entry.get_mut().push(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, prev_cltv_expiry, forward_info });
},
hash_map::Entry::Vacant(entry) => {
entry.insert(vec!(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info }));
entry.insert(vec!(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, prev_cltv_expiry, forward_info }));
}
}
}
Expand DownExpand Up@@ -2500,6 +2506,7 @@ impl ChainListener for ChannelManager {
fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]) {
let _ = self.total_consistency_lock.read().unwrap();
let mut failed_channels = Vec::new();
let mut timed_out_htlcs = Vec::new();
{
let mut channel_lock = self.channel_state.lock().unwrap();
let channel_state = channel_lock.borrow_parts();
Expand DownExpand Up@@ -2567,10 +2574,27 @@ impl ChainListener for ChannelManager {
}
true
});
channel_state.claimable_htlcs.retain(|payment_hash, htlcs| {
htlcs.retain(|htlc| {
if htlc.cltv_expiry <= height { // XXX: Or <?

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry what means "XXX: or <?" ? You want to substract a safe delay to height ?

@TheBlueMattTheBlueMattNov 16, 2018

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oops, lol, ffs, I really need to double-check my own commits before opening PRs, I blame sleep deprivation after 16 hours of being in a plane, thanks for reviewing...That was a note to myself that I'm not sure if the comparison was supposed to be <= or <, I'll double check and fix the PR.

timed_out_htlcs.push((HTLCSource::PreviousHopData(htlc.clone()), payment_hash.clone()));
false
} else { true }
});
!htlcs.is_empty()
});
}
for failure in failed_channels.drain(..) {
self.finish_force_close_channel(failure);
}
for (source, payment_hash) in timed_out_htlcs.drain(..) {
// Call it preimage_unknown as the issue, ultimately, is that the user failed to
// provide us a preimage within the cltv_expiry time window.
self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), source, &payment_hash, HTLCFailReason::Reason {
failure_code: 0x4000 | 15,
data: Vec::new()
});
}
self.latest_block_height.store(height as usize, Ordering::Release);
*self.last_block_hash.try_lock().expect("block_(dis)connected must not be called in parallel") = header.bitcoin_hash();
}
Expand DownExpand Up@@ -2916,7 +2940,8 @@ impl<R: ::std::io::Read> Readable<R> for PendingHTLCStatus {
impl_writeable!(HTLCPreviousHopData, 0, {
short_channel_id,
htlc_id,
incoming_packet_shared_secret
incoming_packet_shared_secret,
cltv_expiry
});

impl Writeable for HTLCSource {
Expand DownExpand Up@@ -2984,6 +3009,7 @@ impl<R: ::std::io::Read> Readable<R> for HTLCFailReason {
impl_writeable!(HTLCForwardInfo, 0, {
prev_short_channel_id,
prev_htlc_id,
prev_cltv_expiry,
forward_info
});

Expand DownExpand Up@@ -7263,6 +7289,44 @@ mod tests {
do_test_monitor_temporary_update_fail(3 | 8 | 16);
}

#[test]
fn test_htlc_timeout() {
// If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
// to avoid our counterparty failing the channel.
let secp_ctx = Secp256k1::new();
let nodes = create_network(2);

create_announced_chan_between_nodes(&nodes, 0, 1);
let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 100000);

let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
nodes[0].chain_monitor.block_connected_checked(&header, 101, &[], &[]);
nodes[1].chain_monitor.block_connected_checked(&header, 101, &[], &[]);
for i in 102..TEST_FINAL_CLTV + 100 + 1 {
header.prev_blockhash = header.bitcoin_hash();
nodes[0].chain_monitor.block_connected_checked(&header, i, &[], &[]);
nodes[1].chain_monitor.block_connected_checked(&header, i, &[], &[]);
}

check_added_monitors!(nodes[1], 1);
let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
assert!(htlc_timeout_updates.update_fee.is_none());

nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]).unwrap();
commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
let events = nodes[0].node.get_and_clear_pending_events();
match events[0] {
Event::PaymentFailed { payment_hash, rejected_by_dest } => {
assert_eq!(payment_hash, our_payment_hash);
assert!(rejected_by_dest);
},
_ => panic!("Unexpected event"),
}
}

#[test]
fn test_invalid_channel_announcement() {
//Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
Expand Down
3 changes: 3 additions & 0 deletions src/util/events.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -57,6 +57,9 @@ pub enum Event {
/// PaymentFailReason::AmountMismatch, respectively, to free up resources for this HTLC.
/// The amount paid should be considered 'incorrect' when it is less than or more than twice
/// the amount expected.
/// If you fail to call either ChannelManager::claim_funds of
/// ChannelManager::fail_htlc_backwards within the HTLC's timeout, the HTLC will be
/// automatically failed with PaymentFailReason::PreimageUnknown.
PaymentReceived {
/// The hash for which the preimage should be handed to the ChannelManager.
payment_hash: [u8; 32],
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 7 additions & 6 deletions src/ln/channel.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -264,7 +264,7 @@ pub(super) struct Channel {
monitor_pending_revoke_and_ack: bool,
monitor_pending_commitment_signed: bool,
monitor_pending_order: Option<RAACommitmentOrder>,
monitor_pending_forwards: Vec<(PendingForwardHTLCInfo, u64)>,
monitor_pending_forwards: Vec<(PendingForwardHTLCInfo, u64, u32)>,
monitor_pending_failures: Vec<(HTLCSource, [u8; 32], HTLCFailReason)>,

// pending_update_fee is filled when sending and receiving update_fee
Expand DownExpand Up@@ -1854,7 +1854,7 @@ impl Channel {
/// waiting on this revoke_and_ack. The generation of this new commitment_signed may also fail,
/// generating an appropriate error *after* the channel state has been updated based on the
/// revoke_and_ack message.
pub fn revoke_and_ack(&mut self, msg: &msgs::RevokeAndACK, fee_estimator: &FeeEstimator) -> Result<(Option<msgs::CommitmentUpdate>, Vec<(PendingForwardHTLCInfo, u64)>, Vec<(HTLCSource, [u8; 32], HTLCFailReason)>, Option<msgs::ClosingSigned>, ChannelMonitor), HandleError> {
pub fn revoke_and_ack(&mut self, msg: &msgs::RevokeAndACK, fee_estimator: &FeeEstimator) -> Result<(Option<msgs::CommitmentUpdate>, Vec<(PendingForwardHTLCInfo, u64, u32)>, Vec<(HTLCSource, [u8; 32], HTLCFailReason)>, Option<msgs::ClosingSigned>, ChannelMonitor), HandleError> {
if (self.channel_state & (ChannelState::ChannelFunded as u32)) != (ChannelState::ChannelFunded as u32) {
return Err(HandleError{err: "Got revoke/ACK message when channel was not in an operational state", action: None});
}
Expand DownExpand Up@@ -1942,7 +1942,7 @@ impl Channel {
}
},
PendingHTLCStatus::Forward(forward_info) => {
to_forward_infos.push((forward_info, htlc.htlc_id));
to_forward_infos.push((forward_info, htlc.htlc_id, htlc.cltv_expiry));
htlc.state = InboundHTLCState::Committed;
}
}
Expand DownExpand Up@@ -2152,7 +2152,7 @@ impl Channel {
/// Indicates that the latest ChannelMonitor update has been committed by the client
/// successfully and we should restore normal operation. Returns messages which should be sent
/// to the remote side.
pub fn monitor_updating_restored(&mut self) -> (Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>, RAACommitmentOrder, Vec<(PendingForwardHTLCInfo, u64)>, Vec<(HTLCSource, [u8; 32], HTLCFailReason)>) {
pub fn monitor_updating_restored(&mut self) -> (Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>, RAACommitmentOrder, Vec<(PendingForwardHTLCInfo, u64, u32)>, Vec<(HTLCSource, [u8; 32], HTLCFailReason)>) {
assert_eq!(self.channel_state & ChannelState::MonitorUpdateFailed as u32, ChannelState::MonitorUpdateFailed as u32);
self.channel_state &= !(ChannelState::MonitorUpdateFailed as u32);

Expand DownExpand Up@@ -3489,9 +3489,10 @@ impl Writeable for Channel {
}

(self.monitor_pending_forwards.len() as u64).write(writer)?;
for &(ref pending_forward, ref htlc_id) in self.monitor_pending_forwards.iter() {
for &(ref pending_forward, ref htlc_id, ref cltv_expiry) in self.monitor_pending_forwards.iter() {
pending_forward.write(writer)?;
htlc_id.write(writer)?;
cltv_expiry.write(writer)?;
}

(self.monitor_pending_failures.len() as u64).write(writer)?;
Expand DownExpand Up@@ -3670,7 +3671,7 @@ impl<R : ::std::io::Read> ReadableArgs<R, Arc<Logger>> for Channel {
let monitor_pending_forwards_count: u64 = Readable::read(reader)?;
let mut monitor_pending_forwards = Vec::with_capacity(cmp::min(monitor_pending_forwards_count as usize, OUR_MAX_HTLCS as usize));
for _ in 0..monitor_pending_forwards_count {
monitor_pending_forwards.push((Readable::read(reader)?, Readable::read(reader)?));
monitor_pending_forwards.push((Readable::read(reader)?, Readable::read(reader)?, Readable::read(reader)?));
}

let monitor_pending_failures_count: u64 = Readable::read(reader)?;
Expand Down
82 changes: 73 additions & 9 deletions src/ln/channelmanager.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -96,6 +96,8 @@ mod channel_held_info {
pub(super) short_channel_id: u64,
pub(super) htlc_id: u64,
pub(super) incoming_packet_shared_secret: [u8; 32],
/// Only used to track expiry of claimable_htlcs and fail them backwards
pub(super) cltv_expiry: u32,
}

/// Tracks the inbound corresponding to an outbound HTLC
Expand DownExpand Up@@ -240,6 +242,7 @@ const MIN_HTLC_RELAY_HOLDING_CELL_MILLIS: u32 = 50;
struct HTLCForwardInfo {
prev_short_channel_id: u64,
prev_htlc_id: u64,
prev_cltv_expiry: u32,
forward_info: PendingForwardHTLCInfo,
}

Expand DownExpand Up@@ -1326,11 +1329,12 @@ impl ChannelManager {
Some(chan_id) => chan_id.clone(),
None => {
failed_forwards.reserve(pending_forwards.len());
for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info, prev_cltv_expiry } in pending_forwards.drain(..) {
let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
short_channel_id: prev_short_channel_id,
htlc_id: prev_htlc_id,
incoming_packet_shared_secret: forward_info.incoming_shared_secret,
cltv_expiry: prev_cltv_expiry,
});
failed_forwards.push((htlc_source, forward_info.payment_hash, 0x4000 | 10, None));
}
Expand All@@ -1340,11 +1344,12 @@ impl ChannelManager {
let forward_chan = &mut channel_state.by_id.get_mut(&forward_chan_id).unwrap();

let mut add_htlc_msgs = Vec::new();
for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, prev_cltv_expiry, forward_info } in pending_forwards.drain(..) {
let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
short_channel_id: prev_short_channel_id,
htlc_id: prev_htlc_id,
incoming_packet_shared_secret: forward_info.incoming_shared_secret,
cltv_expiry: prev_cltv_expiry,
});
match forward_chan.send_htlc(forward_info.amt_to_forward, forward_info.payment_hash, forward_info.outgoing_cltv_value, htlc_source.clone(), forward_info.onion_packet.unwrap()) {
Err(_e) => {
Expand DownExpand Up@@ -1398,11 +1403,12 @@ impl ChannelManager {
});
}
} else {
for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, prev_cltv_expiry, forward_info } in pending_forwards.drain(..) {
let prev_hop_data = HTLCPreviousHopData {
short_channel_id: prev_short_channel_id,
htlc_id: prev_htlc_id,
incoming_packet_shared_secret: forward_info.incoming_shared_secret,
cltv_expiry: prev_cltv_expiry,
};
match channel_state.claimable_htlcs.entry(forward_info.payment_hash) {
hash_map::Entry::Occupied(mut entry) => entry.get_mut().push(prev_hop_data),
Expand DownExpand Up@@ -1471,7 +1477,7 @@ impl ChannelManager {
panic!("should have onion error packet here");
}
},
HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, incoming_packet_shared_secret }) => {
HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, incoming_packet_shared_secret, .. }) => {
let err_packet = match onion_error {
HTLCFailReason::Reason { failure_code, data } => {
let packet = ChannelManager::build_failure_packet(&incoming_packet_shared_secret, failure_code, &data[..]).encode();
Expand DownExpand Up@@ -2248,7 +2254,7 @@ impl ChannelManager {
}

#[inline]
fn forward_htlcs(&self, per_source_pending_forwards: &mut [(u64, Vec<(PendingForwardHTLCInfo, u64)>)]) {
fn forward_htlcs(&self, per_source_pending_forwards: &mut [(u64, Vec<(PendingForwardHTLCInfo, u64, u32)>)]) {
for &mut (prev_short_channel_id, ref mut pending_forwards) in per_source_pending_forwards {
let mut forward_event = None;
if !pending_forwards.is_empty() {
Expand All@@ -2257,13 +2263,13 @@ impl ChannelManager {
forward_event = Some(Instant::now() + Duration::from_millis(((rng::rand_f32() * 4.0 + 1.0) * MIN_HTLC_RELAY_HOLDING_CELL_MILLIS as f32) as u64));
channel_state.next_forward = forward_event.unwrap();
}
for (forward_info, prev_htlc_id) in pending_forwards.drain(..) {
for (forward_info, prev_htlc_id, prev_cltv_expiry) in pending_forwards.drain(..) {
match channel_state.forward_htlcs.entry(forward_info.short_channel_id) {
hash_map::Entry::Occupied(mut entry) => {
entry.get_mut().push(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info });
entry.get_mut().push(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, prev_cltv_expiry, forward_info });
},
hash_map::Entry::Vacant(entry) => {
entry.insert(vec!(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info }));
entry.insert(vec!(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, prev_cltv_expiry, forward_info }));
}
}
}
Expand DownExpand Up@@ -2500,6 +2506,7 @@ impl ChainListener for ChannelManager {
fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]) {
let _ = self.total_consistency_lock.read().unwrap();
let mut failed_channels = Vec::new();
let mut timed_out_htlcs = Vec::new();
{
let mut channel_lock = self.channel_state.lock().unwrap();
let channel_state = channel_lock.borrow_parts();
Expand DownExpand Up@@ -2567,10 +2574,27 @@ impl ChainListener for ChannelManager {
}
true
});
channel_state.claimable_htlcs.retain(|payment_hash, htlcs| {
htlcs.retain(|htlc| {
if htlc.cltv_expiry <= height { // XXX: Or <?

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry what means "XXX: or <?" ? You want to substract a safe delay to height ?

@TheBlueMattTheBlueMattNov 16, 2018

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oops, lol, ffs, I really need to double-check my own commits before opening PRs, I blame sleep deprivation after 16 hours of being in a plane, thanks for reviewing...That was a note to myself that I'm not sure if the comparison was supposed to be <= or <, I'll double check and fix the PR.

timed_out_htlcs.push((HTLCSource::PreviousHopData(htlc.clone()), payment_hash.clone()));
false
} else { true }
});
!htlcs.is_empty()
});
}
for failure in failed_channels.drain(..) {
self.finish_force_close_channel(failure);
}
for (source, payment_hash) in timed_out_htlcs.drain(..) {
// Call it preimage_unknown as the issue, ultimately, is that the user failed to
// provide us a preimage within the cltv_expiry time window.
self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), source, &payment_hash, HTLCFailReason::Reason {
failure_code: 0x4000 | 15,
data: Vec::new()
});
}
self.latest_block_height.store(height as usize, Ordering::Release);
*self.last_block_hash.try_lock().expect("block_(dis)connected must not be called in parallel") = header.bitcoin_hash();
}
Expand DownExpand Up@@ -2916,7 +2940,8 @@ impl<R: ::std::io::Read> Readable<R> for PendingHTLCStatus {
impl_writeable!(HTLCPreviousHopData, 0, {
short_channel_id,
htlc_id,
incoming_packet_shared_secret
incoming_packet_shared_secret,
cltv_expiry
});

impl Writeable for HTLCSource {
Expand DownExpand Up@@ -2984,6 +3009,7 @@ impl<R: ::std::io::Read> Readable<R> for HTLCFailReason {
impl_writeable!(HTLCForwardInfo, 0, {
prev_short_channel_id,
prev_htlc_id,
prev_cltv_expiry,
forward_info
});

Expand DownExpand Up@@ -7263,6 +7289,44 @@ mod tests {
do_test_monitor_temporary_update_fail(3 | 8 | 16);
}

#[test]
fn test_htlc_timeout() {
// If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
// to avoid our counterparty failing the channel.
let secp_ctx = Secp256k1::new();
let nodes = create_network(2);

create_announced_chan_between_nodes(&nodes, 0, 1);
let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 100000);

let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
nodes[0].chain_monitor.block_connected_checked(&header, 101, &[], &[]);
nodes[1].chain_monitor.block_connected_checked(&header, 101, &[], &[]);
for i in 102..TEST_FINAL_CLTV + 100 + 1 {
header.prev_blockhash = header.bitcoin_hash();
nodes[0].chain_monitor.block_connected_checked(&header, i, &[], &[]);
nodes[1].chain_monitor.block_connected_checked(&header, i, &[], &[]);
}

check_added_monitors!(nodes[1], 1);
let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
assert!(htlc_timeout_updates.update_fee.is_none());

nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]).unwrap();
commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
let events = nodes[0].node.get_and_clear_pending_events();
match events[0] {
Event::PaymentFailed { payment_hash, rejected_by_dest } => {
assert_eq!(payment_hash, our_payment_hash);
assert!(rejected_by_dest);
},
_ => panic!("Unexpected event"),
}
}

#[test]
fn test_invalid_channel_announcement() {
//Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
Expand Down
3 changes: 3 additions & 0 deletions src/util/events.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -57,6 +57,9 @@ pub enum Event {
/// PaymentFailReason::AmountMismatch, respectively, to free up resources for this HTLC.
/// The amount paid should be considered 'incorrect' when it is less than or more than twice
/// the amount expected.
/// If you fail to call either ChannelManager::claim_funds of
/// ChannelManager::fail_htlc_backwards within the HTLC's timeout, the HTLC will be
/// automatically failed with PaymentFailReason::PreimageUnknown.
PaymentReceived {
/// The hash for which the preimage should be handed to the ChannelManager.
payment_hash: [u8; 32],
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 7 additions & 6 deletions src/ln/channel.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -264,7 +264,7 @@ pub(super) struct Channel {
monitor_pending_revoke_and_ack: bool,
monitor_pending_commitment_signed: bool,
monitor_pending_order: Option<RAACommitmentOrder>,
monitor_pending_forwards: Vec<(PendingForwardHTLCInfo, u64)>,
monitor_pending_forwards: Vec<(PendingForwardHTLCInfo, u64, u32)>,
monitor_pending_failures: Vec<(HTLCSource, [u8; 32], HTLCFailReason)>,

// pending_update_fee is filled when sending and receiving update_fee
Expand DownExpand Up@@ -1854,7 +1854,7 @@ impl Channel {
/// waiting on this revoke_and_ack. The generation of this new commitment_signed may also fail,
/// generating an appropriate error *after* the channel state has been updated based on the
/// revoke_and_ack message.
pub fn revoke_and_ack(&mut self, msg: &msgs::RevokeAndACK, fee_estimator: &FeeEstimator) -> Result<(Option<msgs::CommitmentUpdate>, Vec<(PendingForwardHTLCInfo, u64)>, Vec<(HTLCSource, [u8; 32], HTLCFailReason)>, Option<msgs::ClosingSigned>, ChannelMonitor), HandleError> {
pub fn revoke_and_ack(&mut self, msg: &msgs::RevokeAndACK, fee_estimator: &FeeEstimator) -> Result<(Option<msgs::CommitmentUpdate>, Vec<(PendingForwardHTLCInfo, u64, u32)>, Vec<(HTLCSource, [u8; 32], HTLCFailReason)>, Option<msgs::ClosingSigned>, ChannelMonitor), HandleError> {
if (self.channel_state & (ChannelState::ChannelFunded as u32)) != (ChannelState::ChannelFunded as u32) {
return Err(HandleError{err: "Got revoke/ACK message when channel was not in an operational state", action: None});
}
Expand DownExpand Up@@ -1942,7 +1942,7 @@ impl Channel {
}
},
PendingHTLCStatus::Forward(forward_info) => {
to_forward_infos.push((forward_info, htlc.htlc_id));
to_forward_infos.push((forward_info, htlc.htlc_id, htlc.cltv_expiry));
htlc.state = InboundHTLCState::Committed;
}
}
Expand DownExpand Up@@ -2152,7 +2152,7 @@ impl Channel {
/// Indicates that the latest ChannelMonitor update has been committed by the client
/// successfully and we should restore normal operation. Returns messages which should be sent
/// to the remote side.
pub fn monitor_updating_restored(&mut self) -> (Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>, RAACommitmentOrder, Vec<(PendingForwardHTLCInfo, u64)>, Vec<(HTLCSource, [u8; 32], HTLCFailReason)>) {
pub fn monitor_updating_restored(&mut self) -> (Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>, RAACommitmentOrder, Vec<(PendingForwardHTLCInfo, u64, u32)>, Vec<(HTLCSource, [u8; 32], HTLCFailReason)>) {
assert_eq!(self.channel_state & ChannelState::MonitorUpdateFailed as u32, ChannelState::MonitorUpdateFailed as u32);
self.channel_state &= !(ChannelState::MonitorUpdateFailed as u32);

Expand DownExpand Up@@ -3489,9 +3489,10 @@ impl Writeable for Channel {
}

(self.monitor_pending_forwards.len() as u64).write(writer)?;
for &(ref pending_forward, ref htlc_id) in self.monitor_pending_forwards.iter() {
for &(ref pending_forward, ref htlc_id, ref cltv_expiry) in self.monitor_pending_forwards.iter() {
pending_forward.write(writer)?;
htlc_id.write(writer)?;
cltv_expiry.write(writer)?;
}

(self.monitor_pending_failures.len() as u64).write(writer)?;
Expand DownExpand Up@@ -3670,7 +3671,7 @@ impl<R : ::std::io::Read> ReadableArgs<R, Arc<Logger>> for Channel {
let monitor_pending_forwards_count: u64 = Readable::read(reader)?;
let mut monitor_pending_forwards = Vec::with_capacity(cmp::min(monitor_pending_forwards_count as usize, OUR_MAX_HTLCS as usize));
for _ in 0..monitor_pending_forwards_count {
monitor_pending_forwards.push((Readable::read(reader)?, Readable::read(reader)?));
monitor_pending_forwards.push((Readable::read(reader)?, Readable::read(reader)?, Readable::read(reader)?));
}

let monitor_pending_failures_count: u64 = Readable::read(reader)?;
Expand Down
82 changes: 73 additions & 9 deletions src/ln/channelmanager.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -96,6 +96,8 @@ mod channel_held_info {
pub(super) short_channel_id: u64,
pub(super) htlc_id: u64,
pub(super) incoming_packet_shared_secret: [u8; 32],
/// Only used to track expiry of claimable_htlcs and fail them backwards
pub(super) cltv_expiry: u32,
}

/// Tracks the inbound corresponding to an outbound HTLC
Expand DownExpand Up@@ -240,6 +242,7 @@ const MIN_HTLC_RELAY_HOLDING_CELL_MILLIS: u32 = 50;
struct HTLCForwardInfo {
prev_short_channel_id: u64,
prev_htlc_id: u64,
prev_cltv_expiry: u32,
forward_info: PendingForwardHTLCInfo,
}

Expand DownExpand Up@@ -1326,11 +1329,12 @@ impl ChannelManager {
Some(chan_id) => chan_id.clone(),
None => {
failed_forwards.reserve(pending_forwards.len());
for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info, prev_cltv_expiry } in pending_forwards.drain(..) {
let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
short_channel_id: prev_short_channel_id,
htlc_id: prev_htlc_id,
incoming_packet_shared_secret: forward_info.incoming_shared_secret,
cltv_expiry: prev_cltv_expiry,
});
failed_forwards.push((htlc_source, forward_info.payment_hash, 0x4000 | 10, None));
}
Expand All@@ -1340,11 +1344,12 @@ impl ChannelManager {
let forward_chan = &mut channel_state.by_id.get_mut(&forward_chan_id).unwrap();

let mut add_htlc_msgs = Vec::new();
for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, prev_cltv_expiry, forward_info } in pending_forwards.drain(..) {
let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
short_channel_id: prev_short_channel_id,
htlc_id: prev_htlc_id,
incoming_packet_shared_secret: forward_info.incoming_shared_secret,
cltv_expiry: prev_cltv_expiry,
});
match forward_chan.send_htlc(forward_info.amt_to_forward, forward_info.payment_hash, forward_info.outgoing_cltv_value, htlc_source.clone(), forward_info.onion_packet.unwrap()) {
Err(_e) => {
Expand DownExpand Up@@ -1398,11 +1403,12 @@ impl ChannelManager {
});
}
} else {
for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, prev_cltv_expiry, forward_info } in pending_forwards.drain(..) {
let prev_hop_data = HTLCPreviousHopData {
short_channel_id: prev_short_channel_id,
htlc_id: prev_htlc_id,
incoming_packet_shared_secret: forward_info.incoming_shared_secret,
cltv_expiry: prev_cltv_expiry,
};
match channel_state.claimable_htlcs.entry(forward_info.payment_hash) {
hash_map::Entry::Occupied(mut entry) => entry.get_mut().push(prev_hop_data),
Expand DownExpand Up@@ -1471,7 +1477,7 @@ impl ChannelManager {
panic!("should have onion error packet here");
}
},
HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, incoming_packet_shared_secret }) => {
HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, incoming_packet_shared_secret, .. }) => {
let err_packet = match onion_error {
HTLCFailReason::Reason { failure_code, data } => {
let packet = ChannelManager::build_failure_packet(&incoming_packet_shared_secret, failure_code, &data[..]).encode();
Expand DownExpand Up@@ -2248,7 +2254,7 @@ impl ChannelManager {
}

#[inline]
fn forward_htlcs(&self, per_source_pending_forwards: &mut [(u64, Vec<(PendingForwardHTLCInfo, u64)>)]) {
fn forward_htlcs(&self, per_source_pending_forwards: &mut [(u64, Vec<(PendingForwardHTLCInfo, u64, u32)>)]) {
for &mut (prev_short_channel_id, ref mut pending_forwards) in per_source_pending_forwards {
let mut forward_event = None;
if !pending_forwards.is_empty() {
Expand All@@ -2257,13 +2263,13 @@ impl ChannelManager {
forward_event = Some(Instant::now() + Duration::from_millis(((rng::rand_f32() * 4.0 + 1.0) * MIN_HTLC_RELAY_HOLDING_CELL_MILLIS as f32) as u64));
channel_state.next_forward = forward_event.unwrap();
}
for (forward_info, prev_htlc_id) in pending_forwards.drain(..) {
for (forward_info, prev_htlc_id, prev_cltv_expiry) in pending_forwards.drain(..) {
match channel_state.forward_htlcs.entry(forward_info.short_channel_id) {
hash_map::Entry::Occupied(mut entry) => {
entry.get_mut().push(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info });
entry.get_mut().push(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, prev_cltv_expiry, forward_info });
},
hash_map::Entry::Vacant(entry) => {
entry.insert(vec!(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info }));
entry.insert(vec!(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, prev_cltv_expiry, forward_info }));
}
}
}
Expand DownExpand Up@@ -2500,6 +2506,7 @@ impl ChainListener for ChannelManager {
fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]) {
let _ = self.total_consistency_lock.read().unwrap();
let mut failed_channels = Vec::new();
let mut timed_out_htlcs = Vec::new();
{
let mut channel_lock = self.channel_state.lock().unwrap();
let channel_state = channel_lock.borrow_parts();
Expand DownExpand Up@@ -2567,10 +2574,27 @@ impl ChainListener for ChannelManager {
}
true
});
channel_state.claimable_htlcs.retain(|payment_hash, htlcs| {
htlcs.retain(|htlc| {
if htlc.cltv_expiry <= height { // XXX: Or <?

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry what means "XXX: or <?" ? You want to substract a safe delay to height ?

@TheBlueMattTheBlueMattNov 16, 2018

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oops, lol, ffs, I really need to double-check my own commits before opening PRs, I blame sleep deprivation after 16 hours of being in a plane, thanks for reviewing...That was a note to myself that I'm not sure if the comparison was supposed to be <= or <, I'll double check and fix the PR.

timed_out_htlcs.push((HTLCSource::PreviousHopData(htlc.clone()), payment_hash.clone()));
false
} else { true }
});
!htlcs.is_empty()
});
}
for failure in failed_channels.drain(..) {
self.finish_force_close_channel(failure);
}
for (source, payment_hash) in timed_out_htlcs.drain(..) {
// Call it preimage_unknown as the issue, ultimately, is that the user failed to
// provide us a preimage within the cltv_expiry time window.
self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), source, &payment_hash, HTLCFailReason::Reason {
failure_code: 0x4000 | 15,
data: Vec::new()
});
}
self.latest_block_height.store(height as usize, Ordering::Release);
*self.last_block_hash.try_lock().expect("block_(dis)connected must not be called in parallel") = header.bitcoin_hash();
}
Expand DownExpand Up@@ -2916,7 +2940,8 @@ impl<R: ::std::io::Read> Readable<R> for PendingHTLCStatus {
impl_writeable!(HTLCPreviousHopData, 0, {
short_channel_id,
htlc_id,
incoming_packet_shared_secret
incoming_packet_shared_secret,
cltv_expiry
});

impl Writeable for HTLCSource {
Expand DownExpand Up@@ -2984,6 +3009,7 @@ impl<R: ::std::io::Read> Readable<R> for HTLCFailReason {
impl_writeable!(HTLCForwardInfo, 0, {
prev_short_channel_id,
prev_htlc_id,
prev_cltv_expiry,
forward_info
});

Expand DownExpand Up@@ -7263,6 +7289,44 @@ mod tests {
do_test_monitor_temporary_update_fail(3 | 8 | 16);
}

#[test]
fn test_htlc_timeout() {
// If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
// to avoid our counterparty failing the channel.
let secp_ctx = Secp256k1::new();
let nodes = create_network(2);

create_announced_chan_between_nodes(&nodes, 0, 1);
let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 100000);

let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
nodes[0].chain_monitor.block_connected_checked(&header, 101, &[], &[]);
nodes[1].chain_monitor.block_connected_checked(&header, 101, &[], &[]);
for i in 102..TEST_FINAL_CLTV + 100 + 1 {
header.prev_blockhash = header.bitcoin_hash();
nodes[0].chain_monitor.block_connected_checked(&header, i, &[], &[]);
nodes[1].chain_monitor.block_connected_checked(&header, i, &[], &[]);
}

check_added_monitors!(nodes[1], 1);
let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
assert!(htlc_timeout_updates.update_fee.is_none());

nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]).unwrap();
commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
let events = nodes[0].node.get_and_clear_pending_events();
match events[0] {
Event::PaymentFailed { payment_hash, rejected_by_dest } => {
assert_eq!(payment_hash, our_payment_hash);
assert!(rejected_by_dest);
},
_ => panic!("Unexpected event"),
}
}

#[test]
fn test_invalid_channel_announcement() {
//Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
Expand Down
3 changes: 3 additions & 0 deletions src/util/events.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -57,6 +57,9 @@ pub enum Event {
/// PaymentFailReason::AmountMismatch, respectively, to free up resources for this HTLC.
/// The amount paid should be considered 'incorrect' when it is less than or more than twice
/// the amount expected.
/// If you fail to call either ChannelManager::claim_funds of
/// ChannelManager::fail_htlc_backwards within the HTLC's timeout, the HTLC will be
/// automatically failed with PaymentFailReason::PreimageUnknown.
PaymentReceived {
/// The hash for which the preimage should be handed to the ChannelManager.
payment_hash: [u8; 32],
Expand Down