Merged
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
30 changes: 24 additions & 6 deletions src/ln/channel.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,7 +14,7 @@ use crypto::digest::Digest;
use crypto::hkdf::{hkdf_extract,hkdf_expand};

use ln::msgs;
use ln::msgs::{ErrorAction, HandleError};
use ln::msgs::{ErrorAction, HandleError, RAACommitmentOrder};
use ln::channelmonitor::ChannelMonitor;
use ln::channelmanager::{PendingHTLCStatus, HTLCSource, PendingForwardHTLCInfo, HTLCFailReason, HTLCFailureMsg};
use ln::chan_utils::{TxCreationKeys,HTLCOutputInCommitment,HTLC_SUCCESS_TX_WEIGHT,HTLC_TIMEOUT_TX_WEIGHT};
Expand DownExpand Up@@ -296,6 +296,12 @@ pub(super) struct Channel {
cur_local_commitment_transaction_number: u64,
cur_remote_commitment_transaction_number: u64,
value_to_self_msat: u64, // Excluding all pending_htlcs, excluding fees
/// Upon receipt of a channel_reestablish we have to figure out whether to send a
/// revoke_and_ack first or a commitment update first. Generally, we prefer to send
/// revoke_and_ack first, but if we had a pending commitment update of our own waiting on a
/// remote revoke when we received the latest commitment update from the remote we have to make
/// sure that commitment update gets resent first.
received_commitment_while_awaiting_raa: bool,
pending_inbound_htlcs: Vec<InboundHTLCOutput>,
pending_outbound_htlcs: Vec<OutboundHTLCOutput>,
holding_cell_htlc_updates: Vec<HTLCUpdateAwaitingACK>,
Expand DownExpand Up@@ -492,6 +498,8 @@ impl Channel {
cur_local_commitment_transaction_number: INITIAL_COMMITMENT_NUMBER,
cur_remote_commitment_transaction_number: INITIAL_COMMITMENT_NUMBER,
value_to_self_msat: channel_value_satoshis * 1000 - push_msat,
received_commitment_while_awaiting_raa: false,

pending_inbound_htlcs: Vec::new(),
pending_outbound_htlcs: Vec::new(),
holding_cell_htlc_updates: Vec::new(),
Expand DownExpand Up@@ -647,6 +655,8 @@ impl Channel {
cur_local_commitment_transaction_number: INITIAL_COMMITMENT_NUMBER,
cur_remote_commitment_transaction_number: INITIAL_COMMITMENT_NUMBER,
value_to_self_msat: msg.push_msat,
received_commitment_while_awaiting_raa: false,

pending_inbound_htlcs: Vec::new(),
pending_outbound_htlcs: Vec::new(),
holding_cell_htlc_updates: Vec::new(),
Expand DownExpand Up@@ -1696,6 +1706,7 @@ impl Channel {

self.cur_local_commitment_transaction_number -= 1;
self.last_local_commitment_txn = new_local_commitment_txn;
self.received_commitment_while_awaiting_raa = (self.channel_state & (ChannelState::AwaitingRemoteRevoke as u32)) != 0;

let (our_commitment_signed, monitor_update) = if need_our_commitment && (self.channel_state & (ChannelState::AwaitingRemoteRevoke as u32)) == 0 {
// If we're AwaitingRemoteRevoke we can't send a new commitment here, but that's ok -
Expand DownExpand Up@@ -1831,6 +1842,7 @@ impl Channel {
self.their_prev_commitment_point = self.their_cur_commitment_point;
self.their_cur_commitment_point = Some(msg.next_per_commitment_point);
self.cur_remote_commitment_transaction_number -= 1;
self.received_commitment_while_awaiting_raa = false;

let mut to_forward_infos = Vec::new();
let mut revoked_htlcs = Vec::new();
Expand DownExpand Up@@ -2072,7 +2084,7 @@ impl Channel {

/// May panic if some calls other than message-handling calls (which will all Err immediately)
/// have been called between remove_uncommitted_htlcs_and_mark_paused and this call.
pub fn channel_reestablish(&mut self, msg: &msgs::ChannelReestablish) -> Result<(Option<msgs::FundingLocked>, Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>, Option<ChannelMonitor>), ChannelError> {
pub fn channel_reestablish(&mut self, msg: &msgs::ChannelReestablish) -> Result<(Option<msgs::FundingLocked>, Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>, Option<ChannelMonitor>, RAACommitmentOrder), ChannelError> {
if self.channel_state & (ChannelState::PeerDisconnected as u32) == 0 {
// While BOLT 2 doesn't indicate explicitly we should error this channel here, it
// almost certainly indicates we are going to end up out-of-sync in some way, so we
Expand DownExpand Up@@ -2120,6 +2132,12 @@ impl Channel {
})
} else { None };

let order = if self.received_commitment_while_awaiting_raa {
RAACommitmentOrder::CommitmentFirst
} else {
RAACommitmentOrder::RevokeAndACKFirst
};

if msg.next_local_commitment_number == our_next_remote_commitment_number {
if required_revoke.is_some() {
log_debug!(self, "Reconnected channel {} with only lost outbound RAA", log_bytes!(self.channel_id()));
Expand All@@ -2142,11 +2160,11 @@ impl Channel {
panic!("Got non-channel-failing result from free_holding_cell_htlcs");
}
},
Ok(Some((commitment_update, channel_monitor))) => return Ok((resend_funding_locked, required_revoke, Some(commitment_update), Some(channel_monitor))),
Ok(None) => return Ok((resend_funding_locked, required_revoke, None, None)),
Ok(Some((commitment_update, channel_monitor))) => return Ok((resend_funding_locked, required_revoke, Some(commitment_update), Some(channel_monitor), order)),
Ok(None) => return Ok((resend_funding_locked, required_revoke, None, None, order)),
}
} else {
return Ok((resend_funding_locked, required_revoke, None, None));
return Ok((resend_funding_locked, required_revoke, None, None, order));
}
} else if msg.next_local_commitment_number == our_next_remote_commitment_number - 1 {
if required_revoke.is_some() {
Expand DownExpand Up@@ -2206,7 +2224,7 @@ impl Channel {
update_add_htlcs, update_fulfill_htlcs, update_fail_htlcs, update_fail_malformed_htlcs,
update_fee: None, //TODO: We need to support re-generating any update_fees in the last commitment_signed!
commitment_signed: self.send_commitment_no_state_update().expect("It looks like we failed to re-generate a commitment_signed we had previously sent?").0,
}), None));
}), None, order));
} else {
return Err(ChannelError::Close("Peer attempted to reestablish channel with a very old remote commitment transaction"));
}
Expand Down
147 changes: 142 additions & 5 deletions src/ln/channelmanager.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -26,7 +26,7 @@ use ln::channel::{Channel, ChannelError, ChannelKeys};
use ln::channelmonitor::{ManyChannelMonitor, CLTV_CLAIM_BUFFER, HTLC_FAIL_TIMEOUT_BLOCKS};
use ln::router::{Route,RouteHop};
use ln::msgs;
use ln::msgs::{HandleError,ChannelMessageHandler};
use ln::msgs::{ChannelMessageHandler, HandleError, RAACommitmentOrder};
use util::{byte_utils, events, internal_traits, rng};
use util::sha2::Sha256;
use util::ser::{Readable, Writeable};
Expand DownExpand Up@@ -2168,17 +2168,17 @@ impl ChannelManager {
Ok(())
}

fn internal_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(Option<msgs::FundingLocked>, Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>), MsgHandleErrInternal> {
fn internal_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(Option<msgs::FundingLocked>, Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>, RAACommitmentOrder), MsgHandleErrInternal> {
let (res, chan_monitor) = {
let mut channel_state = self.channel_state.lock().unwrap();
match channel_state.by_id.get_mut(&msg.channel_id) {
Some(chan) => {
if chan.get_their_node_id() != *their_node_id {
return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
}
let (funding_locked, revoke_and_ack, commitment_update, channel_monitor) = chan.channel_reestablish(msg)
let (funding_locked, revoke_and_ack, commitment_update, channel_monitor, order) = chan.channel_reestablish(msg)
.map_err(|e| MsgHandleErrInternal::from_chan_maybe_close(e, msg.channel_id))?;
(Ok((funding_locked, revoke_and_ack, commitment_update)), channel_monitor)
(Ok((funding_locked, revoke_and_ack, commitment_update, order)), channel_monitor)
},
None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
}
Expand DownExpand Up@@ -2448,7 +2448,7 @@ impl ChannelMessageHandler for ChannelManager {
handle_error!(self, self.internal_announcement_signatures(their_node_id, msg), their_node_id)
}

fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(Option<msgs::FundingLocked>, Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>), HandleError> {
fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(Option<msgs::FundingLocked>, Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>, RAACommitmentOrder), HandleError> {
handle_error!(self, self.internal_channel_reestablish(their_node_id, msg), their_node_id)
}

Expand DownExpand Up@@ -4938,6 +4938,7 @@ mod tests {
assert!(chan_msgs.0.is_none());
}
if pending_raa.0 {
assert!(chan_msgs.3 == msgs::RAACommitmentOrder::RevokeAndACKFirst);
assert!(node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap().is_none());
check_added_monitors!(node_a, 1);
} else {
Expand DownExpand Up@@ -4985,6 +4986,7 @@ mod tests {
assert!(chan_msgs.0.is_none());
}
if pending_raa.1 {
assert!(chan_msgs.3 == msgs::RAACommitmentOrder::RevokeAndACKFirst);
assert!(node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap().is_none());
check_added_monitors!(node_b, 1);
} else {
Expand DownExpand Up@@ -5316,6 +5318,141 @@ mod tests {
claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
}

#[test]
fn test_drop_messages_peer_disconnect_dual_htlc() {
// Test that we can handle reconnecting when both sides of a channel have pending
// commitment_updates when we disconnect.
let mut nodes = create_network(2);
create_announced_chan_between_nodes(&nodes, 0, 1);

let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);

// Now try to send a second payment which will fail to send
let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);

nodes[0].node.send_payment(route.clone(), payment_hash_2).unwrap();
check_added_monitors!(nodes[0], 1);

let events_1 = nodes[0].node.get_and_clear_pending_events();
assert_eq!(events_1.len(), 1);
match events_1[0] {
Event::UpdateHTLCs { .. } => {},
_ => panic!("Unexpected event"),
}

assert!(nodes[1].node.claim_funds(payment_preimage_1));
check_added_monitors!(nodes[1], 1);

let events_2 = nodes[1].node.get_and_clear_pending_events();
assert_eq!(events_2.len(), 1);
match events_2[0] {
Event::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, ref commitment_signed } } => {
assert_eq!(*node_id, nodes[0].node.get_our_node_id());
assert!(update_add_htlcs.is_empty());
assert_eq!(update_fulfill_htlcs.len(), 1);
assert!(update_fail_htlcs.is_empty());
assert!(update_fail_malformed_htlcs.is_empty());
assert!(update_fee.is_none());

nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]).unwrap();
let events_3 = nodes[0].node.get_and_clear_pending_events();
assert_eq!(events_3.len(), 1);
match events_3[0] {
Event::PaymentSent { ref payment_preimage } => {
assert_eq!(*payment_preimage, payment_preimage_1);
},
_ => panic!("Unexpected event"),
}

let (_, commitment_update) = nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed).unwrap();
assert!(commitment_update.is_none());
check_added_monitors!(nodes[0], 1);
},
_ => panic!("Unexpected event"),
}

nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);

let reestablish_1 = nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
assert_eq!(reestablish_1.len(), 1);
let reestablish_2 = nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
assert_eq!(reestablish_2.len(), 1);

let as_resp = nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
let bs_resp = nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();

assert!(as_resp.0.is_none());
assert!(bs_resp.0.is_none());

assert!(bs_resp.1.is_none());
assert!(bs_resp.2.is_none());

assert!(as_resp.3 == msgs::RAACommitmentOrder::CommitmentFirst);

assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]).unwrap();
let (bs_revoke_and_ack, bs_commitment_signed) = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed).unwrap();
assert!(bs_commitment_signed.is_none());
check_added_monitors!(nodes[1], 1);

let bs_second_commitment_signed = nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap()).unwrap().unwrap();
assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
assert!(bs_second_commitment_signed.update_fee.is_none());
check_added_monitors!(nodes[1], 1);

let as_commitment_signed = nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap().unwrap();
assert!(as_commitment_signed.update_add_htlcs.is_empty());
assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
assert!(as_commitment_signed.update_fail_htlcs.is_empty());
assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
assert!(as_commitment_signed.update_fee.is_none());
check_added_monitors!(nodes[0], 1);

let (as_revoke_and_ack, as_second_commitment_signed) = nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed).unwrap();
assert!(as_second_commitment_signed.is_none());
check_added_monitors!(nodes[0], 1);

let (bs_second_revoke_and_ack, bs_third_commitment_signed) = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed).unwrap();
assert!(bs_third_commitment_signed.is_none());
check_added_monitors!(nodes[1], 1);

assert!(nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap().is_none());
check_added_monitors!(nodes[1], 1);

let events_4 = nodes[1].node.get_and_clear_pending_events();
assert_eq!(events_4.len(), 1);
match events_4[0] {
Event::PendingHTLCsForwardable { .. } => { },
_ => panic!("Unexpected event"),
};

nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
nodes[1].node.process_pending_htlc_forwards();

let events_5 = nodes[1].node.get_and_clear_pending_events();
assert_eq!(events_5.len(), 1);
match events_5[0] {
Event::PaymentReceived { ref payment_hash, amt: _ } => {
assert_eq!(payment_hash_2, *payment_hash);
},
_ => panic!("Unexpected event"),
}

assert!(nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack).unwrap().is_none());
check_added_monitors!(nodes[0], 1);

claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
}

#[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
14 changes: 13 additions & 1 deletion src/ln/msgs.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -500,6 +500,18 @@ pub enum HTLCFailChannelUpdate {
}
}

/// For events which result in both a RevokeAndACK and a CommitmentUpdate, by default they should
/// be sent in the order they appear in the return value, however sometimes the order needs to be
/// variable at runtime (eg handle_channel_reestablish needs to re-send messages in the order they
/// were originally sent). In those cases, this enum is also returned.
#[derive(Clone, PartialEq)]
pub enum RAACommitmentOrder {
/// Send the CommitmentUpdate messages first
CommitmentFirst,
/// Send the RevokeAndACK message first
RevokeAndACKFirst,
}

/// A trait to describe an object which can receive channel messages.
///
/// Messages MAY be called in parallel when they originate from different their_node_ids, however
Expand DownExpand Up@@ -554,7 +566,7 @@ pub trait ChannelMessageHandler : events::EventsProvider + Send + Sync {
/// Handle a peer reconnecting, possibly generating channel_reestablish message(s).
fn peer_connected(&self, their_node_id: &PublicKey) -> Vec<ChannelReestablish>;
/// Handle an incoming channel_reestablish message from the given peer.
fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &ChannelReestablish) -> Result<(Option<FundingLocked>, Option<RevokeAndACK>, Option<CommitmentUpdate>), HandleError>;
fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &ChannelReestablish) -> Result<(Option<FundingLocked>, Option<RevokeAndACK>, Option<CommitmentUpdate>, RAACommitmentOrder), HandleError>;

// Error:
/// Handle an incoming error message from the given peer.
Expand Down
Loading
, '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
Merged
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
30 changes: 24 additions & 6 deletions src/ln/channel.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,7 +14,7 @@ use crypto::digest::Digest;
use crypto::hkdf::{hkdf_extract,hkdf_expand};

use ln::msgs;
use ln::msgs::{ErrorAction, HandleError};
use ln::msgs::{ErrorAction, HandleError, RAACommitmentOrder};
use ln::channelmonitor::ChannelMonitor;
use ln::channelmanager::{PendingHTLCStatus, HTLCSource, PendingForwardHTLCInfo, HTLCFailReason, HTLCFailureMsg};
use ln::chan_utils::{TxCreationKeys,HTLCOutputInCommitment,HTLC_SUCCESS_TX_WEIGHT,HTLC_TIMEOUT_TX_WEIGHT};
Expand DownExpand Up@@ -296,6 +296,12 @@ pub(super) struct Channel {
cur_local_commitment_transaction_number: u64,
cur_remote_commitment_transaction_number: u64,
value_to_self_msat: u64, // Excluding all pending_htlcs, excluding fees
/// Upon receipt of a channel_reestablish we have to figure out whether to send a
/// revoke_and_ack first or a commitment update first. Generally, we prefer to send
/// revoke_and_ack first, but if we had a pending commitment update of our own waiting on a
/// remote revoke when we received the latest commitment update from the remote we have to make
/// sure that commitment update gets resent first.
received_commitment_while_awaiting_raa: bool,
pending_inbound_htlcs: Vec<InboundHTLCOutput>,
pending_outbound_htlcs: Vec<OutboundHTLCOutput>,
holding_cell_htlc_updates: Vec<HTLCUpdateAwaitingACK>,
Expand DownExpand Up@@ -492,6 +498,8 @@ impl Channel {
cur_local_commitment_transaction_number: INITIAL_COMMITMENT_NUMBER,
cur_remote_commitment_transaction_number: INITIAL_COMMITMENT_NUMBER,
value_to_self_msat: channel_value_satoshis * 1000 - push_msat,
received_commitment_while_awaiting_raa: false,

pending_inbound_htlcs: Vec::new(),
pending_outbound_htlcs: Vec::new(),
holding_cell_htlc_updates: Vec::new(),
Expand DownExpand Up@@ -647,6 +655,8 @@ impl Channel {
cur_local_commitment_transaction_number: INITIAL_COMMITMENT_NUMBER,
cur_remote_commitment_transaction_number: INITIAL_COMMITMENT_NUMBER,
value_to_self_msat: msg.push_msat,
received_commitment_while_awaiting_raa: false,

pending_inbound_htlcs: Vec::new(),
pending_outbound_htlcs: Vec::new(),
holding_cell_htlc_updates: Vec::new(),
Expand DownExpand Up@@ -1696,6 +1706,7 @@ impl Channel {

self.cur_local_commitment_transaction_number -= 1;
self.last_local_commitment_txn = new_local_commitment_txn;
self.received_commitment_while_awaiting_raa = (self.channel_state & (ChannelState::AwaitingRemoteRevoke as u32)) != 0;

let (our_commitment_signed, monitor_update) = if need_our_commitment && (self.channel_state & (ChannelState::AwaitingRemoteRevoke as u32)) == 0 {
// If we're AwaitingRemoteRevoke we can't send a new commitment here, but that's ok -
Expand DownExpand Up@@ -1831,6 +1842,7 @@ impl Channel {
self.their_prev_commitment_point = self.their_cur_commitment_point;
self.their_cur_commitment_point = Some(msg.next_per_commitment_point);
self.cur_remote_commitment_transaction_number -= 1;
self.received_commitment_while_awaiting_raa = false;

let mut to_forward_infos = Vec::new();
let mut revoked_htlcs = Vec::new();
Expand DownExpand Up@@ -2072,7 +2084,7 @@ impl Channel {

/// May panic if some calls other than message-handling calls (which will all Err immediately)
/// have been called between remove_uncommitted_htlcs_and_mark_paused and this call.
pub fn channel_reestablish(&mut self, msg: &msgs::ChannelReestablish) -> Result<(Option<msgs::FundingLocked>, Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>, Option<ChannelMonitor>), ChannelError> {
pub fn channel_reestablish(&mut self, msg: &msgs::ChannelReestablish) -> Result<(Option<msgs::FundingLocked>, Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>, Option<ChannelMonitor>, RAACommitmentOrder), ChannelError> {
if self.channel_state & (ChannelState::PeerDisconnected as u32) == 0 {
// While BOLT 2 doesn't indicate explicitly we should error this channel here, it
// almost certainly indicates we are going to end up out-of-sync in some way, so we
Expand DownExpand Up@@ -2120,6 +2132,12 @@ impl Channel {
})
} else { None };

let order = if self.received_commitment_while_awaiting_raa {
RAACommitmentOrder::CommitmentFirst
} else {
RAACommitmentOrder::RevokeAndACKFirst
};

if msg.next_local_commitment_number == our_next_remote_commitment_number {
if required_revoke.is_some() {
log_debug!(self, "Reconnected channel {} with only lost outbound RAA", log_bytes!(self.channel_id()));
Expand All@@ -2142,11 +2160,11 @@ impl Channel {
panic!("Got non-channel-failing result from free_holding_cell_htlcs");
}
},
Ok(Some((commitment_update, channel_monitor))) => return Ok((resend_funding_locked, required_revoke, Some(commitment_update), Some(channel_monitor))),
Ok(None) => return Ok((resend_funding_locked, required_revoke, None, None)),
Ok(Some((commitment_update, channel_monitor))) => return Ok((resend_funding_locked, required_revoke, Some(commitment_update), Some(channel_monitor), order)),
Ok(None) => return Ok((resend_funding_locked, required_revoke, None, None, order)),
}
} else {
return Ok((resend_funding_locked, required_revoke, None, None));
return Ok((resend_funding_locked, required_revoke, None, None, order));
}
} else if msg.next_local_commitment_number == our_next_remote_commitment_number - 1 {
if required_revoke.is_some() {
Expand DownExpand Up@@ -2206,7 +2224,7 @@ impl Channel {
update_add_htlcs, update_fulfill_htlcs, update_fail_htlcs, update_fail_malformed_htlcs,
update_fee: None, //TODO: We need to support re-generating any update_fees in the last commitment_signed!
commitment_signed: self.send_commitment_no_state_update().expect("It looks like we failed to re-generate a commitment_signed we had previously sent?").0,
}), None));
}), None, order));
} else {
return Err(ChannelError::Close("Peer attempted to reestablish channel with a very old remote commitment transaction"));
}
Expand Down
147 changes: 142 additions & 5 deletions src/ln/channelmanager.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -26,7 +26,7 @@ use ln::channel::{Channel, ChannelError, ChannelKeys};
use ln::channelmonitor::{ManyChannelMonitor, CLTV_CLAIM_BUFFER, HTLC_FAIL_TIMEOUT_BLOCKS};
use ln::router::{Route,RouteHop};
use ln::msgs;
use ln::msgs::{HandleError,ChannelMessageHandler};
use ln::msgs::{ChannelMessageHandler, HandleError, RAACommitmentOrder};
use util::{byte_utils, events, internal_traits, rng};
use util::sha2::Sha256;
use util::ser::{Readable, Writeable};
Expand DownExpand Up@@ -2168,17 +2168,17 @@ impl ChannelManager {
Ok(())
}

fn internal_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(Option<msgs::FundingLocked>, Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>), MsgHandleErrInternal> {
fn internal_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(Option<msgs::FundingLocked>, Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>, RAACommitmentOrder), MsgHandleErrInternal> {
let (res, chan_monitor) = {
let mut channel_state = self.channel_state.lock().unwrap();
match channel_state.by_id.get_mut(&msg.channel_id) {
Some(chan) => {
if chan.get_their_node_id() != *their_node_id {
return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
}
let (funding_locked, revoke_and_ack, commitment_update, channel_monitor) = chan.channel_reestablish(msg)
let (funding_locked, revoke_and_ack, commitment_update, channel_monitor, order) = chan.channel_reestablish(msg)
.map_err(|e| MsgHandleErrInternal::from_chan_maybe_close(e, msg.channel_id))?;
(Ok((funding_locked, revoke_and_ack, commitment_update)), channel_monitor)
(Ok((funding_locked, revoke_and_ack, commitment_update, order)), channel_monitor)
},
None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
}
Expand DownExpand Up@@ -2448,7 +2448,7 @@ impl ChannelMessageHandler for ChannelManager {
handle_error!(self, self.internal_announcement_signatures(their_node_id, msg), their_node_id)
}

fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(Option<msgs::FundingLocked>, Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>), HandleError> {
fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(Option<msgs::FundingLocked>, Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>, RAACommitmentOrder), HandleError> {
handle_error!(self, self.internal_channel_reestablish(their_node_id, msg), their_node_id)
}

Expand DownExpand Up@@ -4938,6 +4938,7 @@ mod tests {
assert!(chan_msgs.0.is_none());
}
if pending_raa.0 {
assert!(chan_msgs.3 == msgs::RAACommitmentOrder::RevokeAndACKFirst);
assert!(node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap().is_none());
check_added_monitors!(node_a, 1);
} else {
Expand DownExpand Up@@ -4985,6 +4986,7 @@ mod tests {
assert!(chan_msgs.0.is_none());
}
if pending_raa.1 {
assert!(chan_msgs.3 == msgs::RAACommitmentOrder::RevokeAndACKFirst);
assert!(node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap().is_none());
check_added_monitors!(node_b, 1);
} else {
Expand DownExpand Up@@ -5316,6 +5318,141 @@ mod tests {
claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
}

#[test]
fn test_drop_messages_peer_disconnect_dual_htlc() {
// Test that we can handle reconnecting when both sides of a channel have pending
// commitment_updates when we disconnect.
let mut nodes = create_network(2);
create_announced_chan_between_nodes(&nodes, 0, 1);

let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);

// Now try to send a second payment which will fail to send
let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);

nodes[0].node.send_payment(route.clone(), payment_hash_2).unwrap();
check_added_monitors!(nodes[0], 1);

let events_1 = nodes[0].node.get_and_clear_pending_events();
assert_eq!(events_1.len(), 1);
match events_1[0] {
Event::UpdateHTLCs { .. } => {},
_ => panic!("Unexpected event"),
}

assert!(nodes[1].node.claim_funds(payment_preimage_1));
check_added_monitors!(nodes[1], 1);

let events_2 = nodes[1].node.get_and_clear_pending_events();
assert_eq!(events_2.len(), 1);
match events_2[0] {
Event::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, ref commitment_signed } } => {
assert_eq!(*node_id, nodes[0].node.get_our_node_id());
assert!(update_add_htlcs.is_empty());
assert_eq!(update_fulfill_htlcs.len(), 1);
assert!(update_fail_htlcs.is_empty());
assert!(update_fail_malformed_htlcs.is_empty());
assert!(update_fee.is_none());

nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]).unwrap();
let events_3 = nodes[0].node.get_and_clear_pending_events();
assert_eq!(events_3.len(), 1);
match events_3[0] {
Event::PaymentSent { ref payment_preimage } => {
assert_eq!(*payment_preimage, payment_preimage_1);
},
_ => panic!("Unexpected event"),
}

let (_, commitment_update) = nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed).unwrap();
assert!(commitment_update.is_none());
check_added_monitors!(nodes[0], 1);
},
_ => panic!("Unexpected event"),
}

nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);

let reestablish_1 = nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
assert_eq!(reestablish_1.len(), 1);
let reestablish_2 = nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
assert_eq!(reestablish_2.len(), 1);

let as_resp = nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
let bs_resp = nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();

assert!(as_resp.0.is_none());
assert!(bs_resp.0.is_none());

assert!(bs_resp.1.is_none());
assert!(bs_resp.2.is_none());

assert!(as_resp.3 == msgs::RAACommitmentOrder::CommitmentFirst);

assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]).unwrap();
let (bs_revoke_and_ack, bs_commitment_signed) = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed).unwrap();
assert!(bs_commitment_signed.is_none());
check_added_monitors!(nodes[1], 1);

let bs_second_commitment_signed = nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap()).unwrap().unwrap();
assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
assert!(bs_second_commitment_signed.update_fee.is_none());
check_added_monitors!(nodes[1], 1);

let as_commitment_signed = nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap().unwrap();
assert!(as_commitment_signed.update_add_htlcs.is_empty());
assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
assert!(as_commitment_signed.update_fail_htlcs.is_empty());
assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
assert!(as_commitment_signed.update_fee.is_none());
check_added_monitors!(nodes[0], 1);

let (as_revoke_and_ack, as_second_commitment_signed) = nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed).unwrap();
assert!(as_second_commitment_signed.is_none());
check_added_monitors!(nodes[0], 1);

let (bs_second_revoke_and_ack, bs_third_commitment_signed) = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed).unwrap();
assert!(bs_third_commitment_signed.is_none());
check_added_monitors!(nodes[1], 1);

assert!(nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap().is_none());
check_added_monitors!(nodes[1], 1);

let events_4 = nodes[1].node.get_and_clear_pending_events();
assert_eq!(events_4.len(), 1);
match events_4[0] {
Event::PendingHTLCsForwardable { .. } => { },
_ => panic!("Unexpected event"),
};

nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
nodes[1].node.process_pending_htlc_forwards();

let events_5 = nodes[1].node.get_and_clear_pending_events();
assert_eq!(events_5.len(), 1);
match events_5[0] {
Event::PaymentReceived { ref payment_hash, amt: _ } => {
assert_eq!(payment_hash_2, *payment_hash);
},
_ => panic!("Unexpected event"),
}

assert!(nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack).unwrap().is_none());
check_added_monitors!(nodes[0], 1);

claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
}

#[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
14 changes: 13 additions & 1 deletion src/ln/msgs.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -500,6 +500,18 @@ pub enum HTLCFailChannelUpdate {
}
}

/// For events which result in both a RevokeAndACK and a CommitmentUpdate, by default they should
/// be sent in the order they appear in the return value, however sometimes the order needs to be
/// variable at runtime (eg handle_channel_reestablish needs to re-send messages in the order they
/// were originally sent). In those cases, this enum is also returned.
#[derive(Clone, PartialEq)]
pub enum RAACommitmentOrder {
/// Send the CommitmentUpdate messages first
CommitmentFirst,
/// Send the RevokeAndACK message first
RevokeAndACKFirst,
}

/// A trait to describe an object which can receive channel messages.
///
/// Messages MAY be called in parallel when they originate from different their_node_ids, however
Expand DownExpand Up@@ -554,7 +566,7 @@ pub trait ChannelMessageHandler : events::EventsProvider + Send + Sync {
/// Handle a peer reconnecting, possibly generating channel_reestablish message(s).
fn peer_connected(&self, their_node_id: &PublicKey) -> Vec<ChannelReestablish>;
/// Handle an incoming channel_reestablish message from the given peer.
fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &ChannelReestablish) -> Result<(Option<FundingLocked>, Option<RevokeAndACK>, Option<CommitmentUpdate>), HandleError>;
fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &ChannelReestablish) -> Result<(Option<FundingLocked>, Option<RevokeAndACK>, Option<CommitmentUpdate>, RAACommitmentOrder), HandleError>;

// Error:
/// Handle an incoming error message from the given peer.
Expand Down
Loading
, '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
Merged
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
30 changes: 24 additions & 6 deletions src/ln/channel.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,7 +14,7 @@ use crypto::digest::Digest;
use crypto::hkdf::{hkdf_extract,hkdf_expand};

use ln::msgs;
use ln::msgs::{ErrorAction, HandleError};
use ln::msgs::{ErrorAction, HandleError, RAACommitmentOrder};
use ln::channelmonitor::ChannelMonitor;
use ln::channelmanager::{PendingHTLCStatus, HTLCSource, PendingForwardHTLCInfo, HTLCFailReason, HTLCFailureMsg};
use ln::chan_utils::{TxCreationKeys,HTLCOutputInCommitment,HTLC_SUCCESS_TX_WEIGHT,HTLC_TIMEOUT_TX_WEIGHT};
Expand DownExpand Up@@ -296,6 +296,12 @@ pub(super) struct Channel {
cur_local_commitment_transaction_number: u64,
cur_remote_commitment_transaction_number: u64,
value_to_self_msat: u64, // Excluding all pending_htlcs, excluding fees
/// Upon receipt of a channel_reestablish we have to figure out whether to send a
/// revoke_and_ack first or a commitment update first. Generally, we prefer to send
/// revoke_and_ack first, but if we had a pending commitment update of our own waiting on a
/// remote revoke when we received the latest commitment update from the remote we have to make
/// sure that commitment update gets resent first.
received_commitment_while_awaiting_raa: bool,
pending_inbound_htlcs: Vec<InboundHTLCOutput>,
pending_outbound_htlcs: Vec<OutboundHTLCOutput>,
holding_cell_htlc_updates: Vec<HTLCUpdateAwaitingACK>,
Expand DownExpand Up@@ -492,6 +498,8 @@ impl Channel {
cur_local_commitment_transaction_number: INITIAL_COMMITMENT_NUMBER,
cur_remote_commitment_transaction_number: INITIAL_COMMITMENT_NUMBER,
value_to_self_msat: channel_value_satoshis * 1000 - push_msat,
received_commitment_while_awaiting_raa: false,

pending_inbound_htlcs: Vec::new(),
pending_outbound_htlcs: Vec::new(),
holding_cell_htlc_updates: Vec::new(),
Expand DownExpand Up@@ -647,6 +655,8 @@ impl Channel {
cur_local_commitment_transaction_number: INITIAL_COMMITMENT_NUMBER,
cur_remote_commitment_transaction_number: INITIAL_COMMITMENT_NUMBER,
value_to_self_msat: msg.push_msat,
received_commitment_while_awaiting_raa: false,

pending_inbound_htlcs: Vec::new(),
pending_outbound_htlcs: Vec::new(),
holding_cell_htlc_updates: Vec::new(),
Expand DownExpand Up@@ -1696,6 +1706,7 @@ impl Channel {

self.cur_local_commitment_transaction_number -= 1;
self.last_local_commitment_txn = new_local_commitment_txn;
self.received_commitment_while_awaiting_raa = (self.channel_state & (ChannelState::AwaitingRemoteRevoke as u32)) != 0;

let (our_commitment_signed, monitor_update) = if need_our_commitment && (self.channel_state & (ChannelState::AwaitingRemoteRevoke as u32)) == 0 {
// If we're AwaitingRemoteRevoke we can't send a new commitment here, but that's ok -
Expand DownExpand Up@@ -1831,6 +1842,7 @@ impl Channel {
self.their_prev_commitment_point = self.their_cur_commitment_point;
self.their_cur_commitment_point = Some(msg.next_per_commitment_point);
self.cur_remote_commitment_transaction_number -= 1;
self.received_commitment_while_awaiting_raa = false;

let mut to_forward_infos = Vec::new();
let mut revoked_htlcs = Vec::new();
Expand DownExpand Up@@ -2072,7 +2084,7 @@ impl Channel {

/// May panic if some calls other than message-handling calls (which will all Err immediately)
/// have been called between remove_uncommitted_htlcs_and_mark_paused and this call.
pub fn channel_reestablish(&mut self, msg: &msgs::ChannelReestablish) -> Result<(Option<msgs::FundingLocked>, Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>, Option<ChannelMonitor>), ChannelError> {
pub fn channel_reestablish(&mut self, msg: &msgs::ChannelReestablish) -> Result<(Option<msgs::FundingLocked>, Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>, Option<ChannelMonitor>, RAACommitmentOrder), ChannelError> {
if self.channel_state & (ChannelState::PeerDisconnected as u32) == 0 {
// While BOLT 2 doesn't indicate explicitly we should error this channel here, it
// almost certainly indicates we are going to end up out-of-sync in some way, so we
Expand DownExpand Up@@ -2120,6 +2132,12 @@ impl Channel {
})
} else { None };

let order = if self.received_commitment_while_awaiting_raa {
RAACommitmentOrder::CommitmentFirst
} else {
RAACommitmentOrder::RevokeAndACKFirst
};

if msg.next_local_commitment_number == our_next_remote_commitment_number {
if required_revoke.is_some() {
log_debug!(self, "Reconnected channel {} with only lost outbound RAA", log_bytes!(self.channel_id()));
Expand All@@ -2142,11 +2160,11 @@ impl Channel {
panic!("Got non-channel-failing result from free_holding_cell_htlcs");
}
},
Ok(Some((commitment_update, channel_monitor))) => return Ok((resend_funding_locked, required_revoke, Some(commitment_update), Some(channel_monitor))),
Ok(None) => return Ok((resend_funding_locked, required_revoke, None, None)),
Ok(Some((commitment_update, channel_monitor))) => return Ok((resend_funding_locked, required_revoke, Some(commitment_update), Some(channel_monitor), order)),
Ok(None) => return Ok((resend_funding_locked, required_revoke, None, None, order)),
}
} else {
return Ok((resend_funding_locked, required_revoke, None, None));
return Ok((resend_funding_locked, required_revoke, None, None, order));
}
} else if msg.next_local_commitment_number == our_next_remote_commitment_number - 1 {
if required_revoke.is_some() {
Expand DownExpand Up@@ -2206,7 +2224,7 @@ impl Channel {
update_add_htlcs, update_fulfill_htlcs, update_fail_htlcs, update_fail_malformed_htlcs,
update_fee: None, //TODO: We need to support re-generating any update_fees in the last commitment_signed!
commitment_signed: self.send_commitment_no_state_update().expect("It looks like we failed to re-generate a commitment_signed we had previously sent?").0,
}), None));
}), None, order));
} else {
return Err(ChannelError::Close("Peer attempted to reestablish channel with a very old remote commitment transaction"));
}
Expand Down
147 changes: 142 additions & 5 deletions src/ln/channelmanager.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -26,7 +26,7 @@ use ln::channel::{Channel, ChannelError, ChannelKeys};
use ln::channelmonitor::{ManyChannelMonitor, CLTV_CLAIM_BUFFER, HTLC_FAIL_TIMEOUT_BLOCKS};
use ln::router::{Route,RouteHop};
use ln::msgs;
use ln::msgs::{HandleError,ChannelMessageHandler};
use ln::msgs::{ChannelMessageHandler, HandleError, RAACommitmentOrder};
use util::{byte_utils, events, internal_traits, rng};
use util::sha2::Sha256;
use util::ser::{Readable, Writeable};
Expand DownExpand Up@@ -2168,17 +2168,17 @@ impl ChannelManager {
Ok(())
}

fn internal_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(Option<msgs::FundingLocked>, Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>), MsgHandleErrInternal> {
fn internal_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(Option<msgs::FundingLocked>, Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>, RAACommitmentOrder), MsgHandleErrInternal> {
let (res, chan_monitor) = {
let mut channel_state = self.channel_state.lock().unwrap();
match channel_state.by_id.get_mut(&msg.channel_id) {
Some(chan) => {
if chan.get_their_node_id() != *their_node_id {
return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
}
let (funding_locked, revoke_and_ack, commitment_update, channel_monitor) = chan.channel_reestablish(msg)
let (funding_locked, revoke_and_ack, commitment_update, channel_monitor, order) = chan.channel_reestablish(msg)
.map_err(|e| MsgHandleErrInternal::from_chan_maybe_close(e, msg.channel_id))?;
(Ok((funding_locked, revoke_and_ack, commitment_update)), channel_monitor)
(Ok((funding_locked, revoke_and_ack, commitment_update, order)), channel_monitor)
},
None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
}
Expand DownExpand Up@@ -2448,7 +2448,7 @@ impl ChannelMessageHandler for ChannelManager {
handle_error!(self, self.internal_announcement_signatures(their_node_id, msg), their_node_id)
}

fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(Option<msgs::FundingLocked>, Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>), HandleError> {
fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(Option<msgs::FundingLocked>, Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>, RAACommitmentOrder), HandleError> {
handle_error!(self, self.internal_channel_reestablish(their_node_id, msg), their_node_id)
}

Expand DownExpand Up@@ -4938,6 +4938,7 @@ mod tests {
assert!(chan_msgs.0.is_none());
}
if pending_raa.0 {
assert!(chan_msgs.3 == msgs::RAACommitmentOrder::RevokeAndACKFirst);
assert!(node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap().is_none());
check_added_monitors!(node_a, 1);
} else {
Expand DownExpand Up@@ -4985,6 +4986,7 @@ mod tests {
assert!(chan_msgs.0.is_none());
}
if pending_raa.1 {
assert!(chan_msgs.3 == msgs::RAACommitmentOrder::RevokeAndACKFirst);
assert!(node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap().is_none());
check_added_monitors!(node_b, 1);
} else {
Expand DownExpand Up@@ -5316,6 +5318,141 @@ mod tests {
claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
}

#[test]
fn test_drop_messages_peer_disconnect_dual_htlc() {
// Test that we can handle reconnecting when both sides of a channel have pending
// commitment_updates when we disconnect.
let mut nodes = create_network(2);
create_announced_chan_between_nodes(&nodes, 0, 1);

let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);

// Now try to send a second payment which will fail to send
let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);

nodes[0].node.send_payment(route.clone(), payment_hash_2).unwrap();
check_added_monitors!(nodes[0], 1);

let events_1 = nodes[0].node.get_and_clear_pending_events();
assert_eq!(events_1.len(), 1);
match events_1[0] {
Event::UpdateHTLCs { .. } => {},
_ => panic!("Unexpected event"),
}

assert!(nodes[1].node.claim_funds(payment_preimage_1));
check_added_monitors!(nodes[1], 1);

let events_2 = nodes[1].node.get_and_clear_pending_events();
assert_eq!(events_2.len(), 1);
match events_2[0] {
Event::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, ref commitment_signed } } => {
assert_eq!(*node_id, nodes[0].node.get_our_node_id());
assert!(update_add_htlcs.is_empty());
assert_eq!(update_fulfill_htlcs.len(), 1);
assert!(update_fail_htlcs.is_empty());
assert!(update_fail_malformed_htlcs.is_empty());
assert!(update_fee.is_none());

nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]).unwrap();
let events_3 = nodes[0].node.get_and_clear_pending_events();
assert_eq!(events_3.len(), 1);
match events_3[0] {
Event::PaymentSent { ref payment_preimage } => {
assert_eq!(*payment_preimage, payment_preimage_1);
},
_ => panic!("Unexpected event"),
}

let (_, commitment_update) = nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed).unwrap();
assert!(commitment_update.is_none());
check_added_monitors!(nodes[0], 1);
},
_ => panic!("Unexpected event"),
}

nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);

let reestablish_1 = nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
assert_eq!(reestablish_1.len(), 1);
let reestablish_2 = nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
assert_eq!(reestablish_2.len(), 1);

let as_resp = nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
let bs_resp = nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();

assert!(as_resp.0.is_none());
assert!(bs_resp.0.is_none());

assert!(bs_resp.1.is_none());
assert!(bs_resp.2.is_none());

assert!(as_resp.3 == msgs::RAACommitmentOrder::CommitmentFirst);

assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]).unwrap();
let (bs_revoke_and_ack, bs_commitment_signed) = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed).unwrap();
assert!(bs_commitment_signed.is_none());
check_added_monitors!(nodes[1], 1);

let bs_second_commitment_signed = nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap()).unwrap().unwrap();
assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
assert!(bs_second_commitment_signed.update_fee.is_none());
check_added_monitors!(nodes[1], 1);

let as_commitment_signed = nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap().unwrap();
assert!(as_commitment_signed.update_add_htlcs.is_empty());
assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
assert!(as_commitment_signed.update_fail_htlcs.is_empty());
assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
assert!(as_commitment_signed.update_fee.is_none());
check_added_monitors!(nodes[0], 1);

let (as_revoke_and_ack, as_second_commitment_signed) = nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed).unwrap();
assert!(as_second_commitment_signed.is_none());
check_added_monitors!(nodes[0], 1);

let (bs_second_revoke_and_ack, bs_third_commitment_signed) = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed).unwrap();
assert!(bs_third_commitment_signed.is_none());
check_added_monitors!(nodes[1], 1);

assert!(nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap().is_none());
check_added_monitors!(nodes[1], 1);

let events_4 = nodes[1].node.get_and_clear_pending_events();
assert_eq!(events_4.len(), 1);
match events_4[0] {
Event::PendingHTLCsForwardable { .. } => { },
_ => panic!("Unexpected event"),
};

nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
nodes[1].node.process_pending_htlc_forwards();

let events_5 = nodes[1].node.get_and_clear_pending_events();
assert_eq!(events_5.len(), 1);
match events_5[0] {
Event::PaymentReceived { ref payment_hash, amt: _ } => {
assert_eq!(payment_hash_2, *payment_hash);
},
_ => panic!("Unexpected event"),
}

assert!(nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack).unwrap().is_none());
check_added_monitors!(nodes[0], 1);

claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
}

#[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
14 changes: 13 additions & 1 deletion src/ln/msgs.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -500,6 +500,18 @@ pub enum HTLCFailChannelUpdate {
}
}

/// For events which result in both a RevokeAndACK and a CommitmentUpdate, by default they should
/// be sent in the order they appear in the return value, however sometimes the order needs to be
/// variable at runtime (eg handle_channel_reestablish needs to re-send messages in the order they
/// were originally sent). In those cases, this enum is also returned.
#[derive(Clone, PartialEq)]
pub enum RAACommitmentOrder {
/// Send the CommitmentUpdate messages first
CommitmentFirst,
/// Send the RevokeAndACK message first
RevokeAndACKFirst,
}

/// A trait to describe an object which can receive channel messages.
///
/// Messages MAY be called in parallel when they originate from different their_node_ids, however
Expand DownExpand Up@@ -554,7 +566,7 @@ pub trait ChannelMessageHandler : events::EventsProvider + Send + Sync {
/// Handle a peer reconnecting, possibly generating channel_reestablish message(s).
fn peer_connected(&self, their_node_id: &PublicKey) -> Vec<ChannelReestablish>;
/// Handle an incoming channel_reestablish message from the given peer.
fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &ChannelReestablish) -> Result<(Option<FundingLocked>, Option<RevokeAndACK>, Option<CommitmentUpdate>), HandleError>;
fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &ChannelReestablish) -> Result<(Option<FundingLocked>, Option<RevokeAndACK>, Option<CommitmentUpdate>, RAACommitmentOrder), HandleError>;

// Error:
/// Handle an incoming error message from the given peer.
Expand Down
Loading
, '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
Merged
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
30 changes: 24 additions & 6 deletions src/ln/channel.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,7 +14,7 @@ use crypto::digest::Digest;
use crypto::hkdf::{hkdf_extract,hkdf_expand};

use ln::msgs;
use ln::msgs::{ErrorAction, HandleError};
use ln::msgs::{ErrorAction, HandleError, RAACommitmentOrder};
use ln::channelmonitor::ChannelMonitor;
use ln::channelmanager::{PendingHTLCStatus, HTLCSource, PendingForwardHTLCInfo, HTLCFailReason, HTLCFailureMsg};
use ln::chan_utils::{TxCreationKeys,HTLCOutputInCommitment,HTLC_SUCCESS_TX_WEIGHT,HTLC_TIMEOUT_TX_WEIGHT};
Expand DownExpand Up@@ -296,6 +296,12 @@ pub(super) struct Channel {
cur_local_commitment_transaction_number: u64,
cur_remote_commitment_transaction_number: u64,
value_to_self_msat: u64, // Excluding all pending_htlcs, excluding fees
/// Upon receipt of a channel_reestablish we have to figure out whether to send a
/// revoke_and_ack first or a commitment update first. Generally, we prefer to send
/// revoke_and_ack first, but if we had a pending commitment update of our own waiting on a
/// remote revoke when we received the latest commitment update from the remote we have to make
/// sure that commitment update gets resent first.
received_commitment_while_awaiting_raa: bool,
pending_inbound_htlcs: Vec<InboundHTLCOutput>,
pending_outbound_htlcs: Vec<OutboundHTLCOutput>,
holding_cell_htlc_updates: Vec<HTLCUpdateAwaitingACK>,
Expand DownExpand Up@@ -492,6 +498,8 @@ impl Channel {
cur_local_commitment_transaction_number: INITIAL_COMMITMENT_NUMBER,
cur_remote_commitment_transaction_number: INITIAL_COMMITMENT_NUMBER,
value_to_self_msat: channel_value_satoshis * 1000 - push_msat,
received_commitment_while_awaiting_raa: false,

pending_inbound_htlcs: Vec::new(),
pending_outbound_htlcs: Vec::new(),
holding_cell_htlc_updates: Vec::new(),
Expand DownExpand Up@@ -647,6 +655,8 @@ impl Channel {
cur_local_commitment_transaction_number: INITIAL_COMMITMENT_NUMBER,
cur_remote_commitment_transaction_number: INITIAL_COMMITMENT_NUMBER,
value_to_self_msat: msg.push_msat,
received_commitment_while_awaiting_raa: false,

pending_inbound_htlcs: Vec::new(),
pending_outbound_htlcs: Vec::new(),
holding_cell_htlc_updates: Vec::new(),
Expand DownExpand Up@@ -1696,6 +1706,7 @@ impl Channel {

self.cur_local_commitment_transaction_number -= 1;
self.last_local_commitment_txn = new_local_commitment_txn;
self.received_commitment_while_awaiting_raa = (self.channel_state & (ChannelState::AwaitingRemoteRevoke as u32)) != 0;

let (our_commitment_signed, monitor_update) = if need_our_commitment && (self.channel_state & (ChannelState::AwaitingRemoteRevoke as u32)) == 0 {
// If we're AwaitingRemoteRevoke we can't send a new commitment here, but that's ok -
Expand DownExpand Up@@ -1831,6 +1842,7 @@ impl Channel {
self.their_prev_commitment_point = self.their_cur_commitment_point;
self.their_cur_commitment_point = Some(msg.next_per_commitment_point);
self.cur_remote_commitment_transaction_number -= 1;
self.received_commitment_while_awaiting_raa = false;

let mut to_forward_infos = Vec::new();
let mut revoked_htlcs = Vec::new();
Expand DownExpand Up@@ -2072,7 +2084,7 @@ impl Channel {

/// May panic if some calls other than message-handling calls (which will all Err immediately)
/// have been called between remove_uncommitted_htlcs_and_mark_paused and this call.
pub fn channel_reestablish(&mut self, msg: &msgs::ChannelReestablish) -> Result<(Option<msgs::FundingLocked>, Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>, Option<ChannelMonitor>), ChannelError> {
pub fn channel_reestablish(&mut self, msg: &msgs::ChannelReestablish) -> Result<(Option<msgs::FundingLocked>, Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>, Option<ChannelMonitor>, RAACommitmentOrder), ChannelError> {
if self.channel_state & (ChannelState::PeerDisconnected as u32) == 0 {
// While BOLT 2 doesn't indicate explicitly we should error this channel here, it
// almost certainly indicates we are going to end up out-of-sync in some way, so we
Expand DownExpand Up@@ -2120,6 +2132,12 @@ impl Channel {
})
} else { None };

let order = if self.received_commitment_while_awaiting_raa {
RAACommitmentOrder::CommitmentFirst
} else {
RAACommitmentOrder::RevokeAndACKFirst
};

if msg.next_local_commitment_number == our_next_remote_commitment_number {
if required_revoke.is_some() {
log_debug!(self, "Reconnected channel {} with only lost outbound RAA", log_bytes!(self.channel_id()));
Expand All@@ -2142,11 +2160,11 @@ impl Channel {
panic!("Got non-channel-failing result from free_holding_cell_htlcs");
}
},
Ok(Some((commitment_update, channel_monitor))) => return Ok((resend_funding_locked, required_revoke, Some(commitment_update), Some(channel_monitor))),
Ok(None) => return Ok((resend_funding_locked, required_revoke, None, None)),
Ok(Some((commitment_update, channel_monitor))) => return Ok((resend_funding_locked, required_revoke, Some(commitment_update), Some(channel_monitor), order)),
Ok(None) => return Ok((resend_funding_locked, required_revoke, None, None, order)),
}
} else {
return Ok((resend_funding_locked, required_revoke, None, None));
return Ok((resend_funding_locked, required_revoke, None, None, order));
}
} else if msg.next_local_commitment_number == our_next_remote_commitment_number - 1 {
if required_revoke.is_some() {
Expand DownExpand Up@@ -2206,7 +2224,7 @@ impl Channel {
update_add_htlcs, update_fulfill_htlcs, update_fail_htlcs, update_fail_malformed_htlcs,
update_fee: None, //TODO: We need to support re-generating any update_fees in the last commitment_signed!
commitment_signed: self.send_commitment_no_state_update().expect("It looks like we failed to re-generate a commitment_signed we had previously sent?").0,
}), None));
}), None, order));
} else {
return Err(ChannelError::Close("Peer attempted to reestablish channel with a very old remote commitment transaction"));
}
Expand Down
147 changes: 142 additions & 5 deletions src/ln/channelmanager.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -26,7 +26,7 @@ use ln::channel::{Channel, ChannelError, ChannelKeys};
use ln::channelmonitor::{ManyChannelMonitor, CLTV_CLAIM_BUFFER, HTLC_FAIL_TIMEOUT_BLOCKS};
use ln::router::{Route,RouteHop};
use ln::msgs;
use ln::msgs::{HandleError,ChannelMessageHandler};
use ln::msgs::{ChannelMessageHandler, HandleError, RAACommitmentOrder};
use util::{byte_utils, events, internal_traits, rng};
use util::sha2::Sha256;
use util::ser::{Readable, Writeable};
Expand DownExpand Up@@ -2168,17 +2168,17 @@ impl ChannelManager {
Ok(())
}

fn internal_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(Option<msgs::FundingLocked>, Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>), MsgHandleErrInternal> {
fn internal_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(Option<msgs::FundingLocked>, Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>, RAACommitmentOrder), MsgHandleErrInternal> {
let (res, chan_monitor) = {
let mut channel_state = self.channel_state.lock().unwrap();
match channel_state.by_id.get_mut(&msg.channel_id) {
Some(chan) => {
if chan.get_their_node_id() != *their_node_id {
return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
}
let (funding_locked, revoke_and_ack, commitment_update, channel_monitor) = chan.channel_reestablish(msg)
let (funding_locked, revoke_and_ack, commitment_update, channel_monitor, order) = chan.channel_reestablish(msg)
.map_err(|e| MsgHandleErrInternal::from_chan_maybe_close(e, msg.channel_id))?;
(Ok((funding_locked, revoke_and_ack, commitment_update)), channel_monitor)
(Ok((funding_locked, revoke_and_ack, commitment_update, order)), channel_monitor)
},
None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
}
Expand DownExpand Up@@ -2448,7 +2448,7 @@ impl ChannelMessageHandler for ChannelManager {
handle_error!(self, self.internal_announcement_signatures(their_node_id, msg), their_node_id)
}

fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(Option<msgs::FundingLocked>, Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>), HandleError> {
fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(Option<msgs::FundingLocked>, Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>, RAACommitmentOrder), HandleError> {
handle_error!(self, self.internal_channel_reestablish(their_node_id, msg), their_node_id)
}

Expand DownExpand Up@@ -4938,6 +4938,7 @@ mod tests {
assert!(chan_msgs.0.is_none());
}
if pending_raa.0 {
assert!(chan_msgs.3 == msgs::RAACommitmentOrder::RevokeAndACKFirst);
assert!(node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap().is_none());
check_added_monitors!(node_a, 1);
} else {
Expand DownExpand Up@@ -4985,6 +4986,7 @@ mod tests {
assert!(chan_msgs.0.is_none());
}
if pending_raa.1 {
assert!(chan_msgs.3 == msgs::RAACommitmentOrder::RevokeAndACKFirst);
assert!(node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap().is_none());
check_added_monitors!(node_b, 1);
} else {
Expand DownExpand Up@@ -5316,6 +5318,141 @@ mod tests {
claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
}

#[test]
fn test_drop_messages_peer_disconnect_dual_htlc() {
// Test that we can handle reconnecting when both sides of a channel have pending
// commitment_updates when we disconnect.
let mut nodes = create_network(2);
create_announced_chan_between_nodes(&nodes, 0, 1);

let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);

// Now try to send a second payment which will fail to send
let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);

nodes[0].node.send_payment(route.clone(), payment_hash_2).unwrap();
check_added_monitors!(nodes[0], 1);

let events_1 = nodes[0].node.get_and_clear_pending_events();
assert_eq!(events_1.len(), 1);
match events_1[0] {
Event::UpdateHTLCs { .. } => {},
_ => panic!("Unexpected event"),
}

assert!(nodes[1].node.claim_funds(payment_preimage_1));
check_added_monitors!(nodes[1], 1);

let events_2 = nodes[1].node.get_and_clear_pending_events();
assert_eq!(events_2.len(), 1);
match events_2[0] {
Event::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, ref commitment_signed } } => {
assert_eq!(*node_id, nodes[0].node.get_our_node_id());
assert!(update_add_htlcs.is_empty());
assert_eq!(update_fulfill_htlcs.len(), 1);
assert!(update_fail_htlcs.is_empty());
assert!(update_fail_malformed_htlcs.is_empty());
assert!(update_fee.is_none());

nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]).unwrap();
let events_3 = nodes[0].node.get_and_clear_pending_events();
assert_eq!(events_3.len(), 1);
match events_3[0] {
Event::PaymentSent { ref payment_preimage } => {
assert_eq!(*payment_preimage, payment_preimage_1);
},
_ => panic!("Unexpected event"),
}

let (_, commitment_update) = nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed).unwrap();
assert!(commitment_update.is_none());
check_added_monitors!(nodes[0], 1);
},
_ => panic!("Unexpected event"),
}

nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);

let reestablish_1 = nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
assert_eq!(reestablish_1.len(), 1);
let reestablish_2 = nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
assert_eq!(reestablish_2.len(), 1);

let as_resp = nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
let bs_resp = nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();

assert!(as_resp.0.is_none());
assert!(bs_resp.0.is_none());

assert!(bs_resp.1.is_none());
assert!(bs_resp.2.is_none());

assert!(as_resp.3 == msgs::RAACommitmentOrder::CommitmentFirst);

assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]).unwrap();
let (bs_revoke_and_ack, bs_commitment_signed) = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed).unwrap();
assert!(bs_commitment_signed.is_none());
check_added_monitors!(nodes[1], 1);

let bs_second_commitment_signed = nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap()).unwrap().unwrap();
assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
assert!(bs_second_commitment_signed.update_fee.is_none());
check_added_monitors!(nodes[1], 1);

let as_commitment_signed = nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap().unwrap();
assert!(as_commitment_signed.update_add_htlcs.is_empty());
assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
assert!(as_commitment_signed.update_fail_htlcs.is_empty());
assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
assert!(as_commitment_signed.update_fee.is_none());
check_added_monitors!(nodes[0], 1);

let (as_revoke_and_ack, as_second_commitment_signed) = nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed).unwrap();
assert!(as_second_commitment_signed.is_none());
check_added_monitors!(nodes[0], 1);

let (bs_second_revoke_and_ack, bs_third_commitment_signed) = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed).unwrap();
assert!(bs_third_commitment_signed.is_none());
check_added_monitors!(nodes[1], 1);

assert!(nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap().is_none());
check_added_monitors!(nodes[1], 1);

let events_4 = nodes[1].node.get_and_clear_pending_events();
assert_eq!(events_4.len(), 1);
match events_4[0] {
Event::PendingHTLCsForwardable { .. } => { },
_ => panic!("Unexpected event"),
};

nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
nodes[1].node.process_pending_htlc_forwards();

let events_5 = nodes[1].node.get_and_clear_pending_events();
assert_eq!(events_5.len(), 1);
match events_5[0] {
Event::PaymentReceived { ref payment_hash, amt: _ } => {
assert_eq!(payment_hash_2, *payment_hash);
},
_ => panic!("Unexpected event"),
}

assert!(nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack).unwrap().is_none());
check_added_monitors!(nodes[0], 1);

claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
}

#[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
14 changes: 13 additions & 1 deletion src/ln/msgs.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -500,6 +500,18 @@ pub enum HTLCFailChannelUpdate {
}
}

/// For events which result in both a RevokeAndACK and a CommitmentUpdate, by default they should
/// be sent in the order they appear in the return value, however sometimes the order needs to be
/// variable at runtime (eg handle_channel_reestablish needs to re-send messages in the order they
/// were originally sent). In those cases, this enum is also returned.
#[derive(Clone, PartialEq)]
pub enum RAACommitmentOrder {
/// Send the CommitmentUpdate messages first
CommitmentFirst,
/// Send the RevokeAndACK message first
RevokeAndACKFirst,
}

/// A trait to describe an object which can receive channel messages.
///
/// Messages MAY be called in parallel when they originate from different their_node_ids, however
Expand DownExpand Up@@ -554,7 +566,7 @@ pub trait ChannelMessageHandler : events::EventsProvider + Send + Sync {
/// Handle a peer reconnecting, possibly generating channel_reestablish message(s).
fn peer_connected(&self, their_node_id: &PublicKey) -> Vec<ChannelReestablish>;
/// Handle an incoming channel_reestablish message from the given peer.
fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &ChannelReestablish) -> Result<(Option<FundingLocked>, Option<RevokeAndACK>, Option<CommitmentUpdate>), HandleError>;
fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &ChannelReestablish) -> Result<(Option<FundingLocked>, Option<RevokeAndACK>, Option<CommitmentUpdate>, RAACommitmentOrder), HandleError>;

// Error:
/// Handle an incoming error message from the given peer.
Expand Down
Loading
, '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
Merged
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
30 changes: 24 additions & 6 deletions src/ln/channel.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,7 +14,7 @@ use crypto::digest::Digest;
use crypto::hkdf::{hkdf_extract,hkdf_expand};

use ln::msgs;
use ln::msgs::{ErrorAction, HandleError};
use ln::msgs::{ErrorAction, HandleError, RAACommitmentOrder};
use ln::channelmonitor::ChannelMonitor;
use ln::channelmanager::{PendingHTLCStatus, HTLCSource, PendingForwardHTLCInfo, HTLCFailReason, HTLCFailureMsg};
use ln::chan_utils::{TxCreationKeys,HTLCOutputInCommitment,HTLC_SUCCESS_TX_WEIGHT,HTLC_TIMEOUT_TX_WEIGHT};
Expand DownExpand Up@@ -296,6 +296,12 @@ pub(super) struct Channel {
cur_local_commitment_transaction_number: u64,
cur_remote_commitment_transaction_number: u64,
value_to_self_msat: u64, // Excluding all pending_htlcs, excluding fees
/// Upon receipt of a channel_reestablish we have to figure out whether to send a
/// revoke_and_ack first or a commitment update first. Generally, we prefer to send
/// revoke_and_ack first, but if we had a pending commitment update of our own waiting on a
/// remote revoke when we received the latest commitment update from the remote we have to make
/// sure that commitment update gets resent first.
received_commitment_while_awaiting_raa: bool,
pending_inbound_htlcs: Vec<InboundHTLCOutput>,
pending_outbound_htlcs: Vec<OutboundHTLCOutput>,
holding_cell_htlc_updates: Vec<HTLCUpdateAwaitingACK>,
Expand DownExpand Up@@ -492,6 +498,8 @@ impl Channel {
cur_local_commitment_transaction_number: INITIAL_COMMITMENT_NUMBER,
cur_remote_commitment_transaction_number: INITIAL_COMMITMENT_NUMBER,
value_to_self_msat: channel_value_satoshis * 1000 - push_msat,
received_commitment_while_awaiting_raa: false,

pending_inbound_htlcs: Vec::new(),
pending_outbound_htlcs: Vec::new(),
holding_cell_htlc_updates: Vec::new(),
Expand DownExpand Up@@ -647,6 +655,8 @@ impl Channel {
cur_local_commitment_transaction_number: INITIAL_COMMITMENT_NUMBER,
cur_remote_commitment_transaction_number: INITIAL_COMMITMENT_NUMBER,
value_to_self_msat: msg.push_msat,
received_commitment_while_awaiting_raa: false,

pending_inbound_htlcs: Vec::new(),
pending_outbound_htlcs: Vec::new(),
holding_cell_htlc_updates: Vec::new(),
Expand DownExpand Up@@ -1696,6 +1706,7 @@ impl Channel {

self.cur_local_commitment_transaction_number -= 1;
self.last_local_commitment_txn = new_local_commitment_txn;
self.received_commitment_while_awaiting_raa = (self.channel_state & (ChannelState::AwaitingRemoteRevoke as u32)) != 0;

let (our_commitment_signed, monitor_update) = if need_our_commitment && (self.channel_state & (ChannelState::AwaitingRemoteRevoke as u32)) == 0 {
// If we're AwaitingRemoteRevoke we can't send a new commitment here, but that's ok -
Expand DownExpand Up@@ -1831,6 +1842,7 @@ impl Channel {
self.their_prev_commitment_point = self.their_cur_commitment_point;
self.their_cur_commitment_point = Some(msg.next_per_commitment_point);
self.cur_remote_commitment_transaction_number -= 1;
self.received_commitment_while_awaiting_raa = false;

let mut to_forward_infos = Vec::new();
let mut revoked_htlcs = Vec::new();
Expand DownExpand Up@@ -2072,7 +2084,7 @@ impl Channel {

/// May panic if some calls other than message-handling calls (which will all Err immediately)
/// have been called between remove_uncommitted_htlcs_and_mark_paused and this call.
pub fn channel_reestablish(&mut self, msg: &msgs::ChannelReestablish) -> Result<(Option<msgs::FundingLocked>, Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>, Option<ChannelMonitor>), ChannelError> {
pub fn channel_reestablish(&mut self, msg: &msgs::ChannelReestablish) -> Result<(Option<msgs::FundingLocked>, Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>, Option<ChannelMonitor>, RAACommitmentOrder), ChannelError> {
if self.channel_state & (ChannelState::PeerDisconnected as u32) == 0 {
// While BOLT 2 doesn't indicate explicitly we should error this channel here, it
// almost certainly indicates we are going to end up out-of-sync in some way, so we
Expand DownExpand Up@@ -2120,6 +2132,12 @@ impl Channel {
})
} else { None };

let order = if self.received_commitment_while_awaiting_raa {
RAACommitmentOrder::CommitmentFirst
} else {
RAACommitmentOrder::RevokeAndACKFirst
};

if msg.next_local_commitment_number == our_next_remote_commitment_number {
if required_revoke.is_some() {
log_debug!(self, "Reconnected channel {} with only lost outbound RAA", log_bytes!(self.channel_id()));
Expand All@@ -2142,11 +2160,11 @@ impl Channel {
panic!("Got non-channel-failing result from free_holding_cell_htlcs");
}
},
Ok(Some((commitment_update, channel_monitor))) => return Ok((resend_funding_locked, required_revoke, Some(commitment_update), Some(channel_monitor))),
Ok(None) => return Ok((resend_funding_locked, required_revoke, None, None)),
Ok(Some((commitment_update, channel_monitor))) => return Ok((resend_funding_locked, required_revoke, Some(commitment_update), Some(channel_monitor), order)),
Ok(None) => return Ok((resend_funding_locked, required_revoke, None, None, order)),
}
} else {
return Ok((resend_funding_locked, required_revoke, None, None));
return Ok((resend_funding_locked, required_revoke, None, None, order));
}
} else if msg.next_local_commitment_number == our_next_remote_commitment_number - 1 {
if required_revoke.is_some() {
Expand DownExpand Up@@ -2206,7 +2224,7 @@ impl Channel {
update_add_htlcs, update_fulfill_htlcs, update_fail_htlcs, update_fail_malformed_htlcs,
update_fee: None, //TODO: We need to support re-generating any update_fees in the last commitment_signed!
commitment_signed: self.send_commitment_no_state_update().expect("It looks like we failed to re-generate a commitment_signed we had previously sent?").0,
}), None));
}), None, order));
} else {
return Err(ChannelError::Close("Peer attempted to reestablish channel with a very old remote commitment transaction"));
}
Expand Down
147 changes: 142 additions & 5 deletions src/ln/channelmanager.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -26,7 +26,7 @@ use ln::channel::{Channel, ChannelError, ChannelKeys};
use ln::channelmonitor::{ManyChannelMonitor, CLTV_CLAIM_BUFFER, HTLC_FAIL_TIMEOUT_BLOCKS};
use ln::router::{Route,RouteHop};
use ln::msgs;
use ln::msgs::{HandleError,ChannelMessageHandler};
use ln::msgs::{ChannelMessageHandler, HandleError, RAACommitmentOrder};
use util::{byte_utils, events, internal_traits, rng};
use util::sha2::Sha256;
use util::ser::{Readable, Writeable};
Expand DownExpand Up@@ -2168,17 +2168,17 @@ impl ChannelManager {
Ok(())
}

fn internal_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(Option<msgs::FundingLocked>, Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>), MsgHandleErrInternal> {
fn internal_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(Option<msgs::FundingLocked>, Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>, RAACommitmentOrder), MsgHandleErrInternal> {
let (res, chan_monitor) = {
let mut channel_state = self.channel_state.lock().unwrap();
match channel_state.by_id.get_mut(&msg.channel_id) {
Some(chan) => {
if chan.get_their_node_id() != *their_node_id {
return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
}
let (funding_locked, revoke_and_ack, commitment_update, channel_monitor) = chan.channel_reestablish(msg)
let (funding_locked, revoke_and_ack, commitment_update, channel_monitor, order) = chan.channel_reestablish(msg)
.map_err(|e| MsgHandleErrInternal::from_chan_maybe_close(e, msg.channel_id))?;
(Ok((funding_locked, revoke_and_ack, commitment_update)), channel_monitor)
(Ok((funding_locked, revoke_and_ack, commitment_update, order)), channel_monitor)
},
None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
}
Expand DownExpand Up@@ -2448,7 +2448,7 @@ impl ChannelMessageHandler for ChannelManager {
handle_error!(self, self.internal_announcement_signatures(their_node_id, msg), their_node_id)
}

fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(Option<msgs::FundingLocked>, Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>), HandleError> {
fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(Option<msgs::FundingLocked>, Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>, RAACommitmentOrder), HandleError> {
handle_error!(self, self.internal_channel_reestablish(their_node_id, msg), their_node_id)
}

Expand DownExpand Up@@ -4938,6 +4938,7 @@ mod tests {
assert!(chan_msgs.0.is_none());
}
if pending_raa.0 {
assert!(chan_msgs.3 == msgs::RAACommitmentOrder::RevokeAndACKFirst);
assert!(node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap().is_none());
check_added_monitors!(node_a, 1);
} else {
Expand DownExpand Up@@ -4985,6 +4986,7 @@ mod tests {
assert!(chan_msgs.0.is_none());
}
if pending_raa.1 {
assert!(chan_msgs.3 == msgs::RAACommitmentOrder::RevokeAndACKFirst);
assert!(node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap().is_none());
check_added_monitors!(node_b, 1);
} else {
Expand DownExpand Up@@ -5316,6 +5318,141 @@ mod tests {
claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
}

#[test]
fn test_drop_messages_peer_disconnect_dual_htlc() {
// Test that we can handle reconnecting when both sides of a channel have pending
// commitment_updates when we disconnect.
let mut nodes = create_network(2);
create_announced_chan_between_nodes(&nodes, 0, 1);

let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);

// Now try to send a second payment which will fail to send
let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);

nodes[0].node.send_payment(route.clone(), payment_hash_2).unwrap();
check_added_monitors!(nodes[0], 1);

let events_1 = nodes[0].node.get_and_clear_pending_events();
assert_eq!(events_1.len(), 1);
match events_1[0] {
Event::UpdateHTLCs { .. } => {},
_ => panic!("Unexpected event"),
}

assert!(nodes[1].node.claim_funds(payment_preimage_1));
check_added_monitors!(nodes[1], 1);

let events_2 = nodes[1].node.get_and_clear_pending_events();
assert_eq!(events_2.len(), 1);
match events_2[0] {
Event::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, ref commitment_signed } } => {
assert_eq!(*node_id, nodes[0].node.get_our_node_id());
assert!(update_add_htlcs.is_empty());
assert_eq!(update_fulfill_htlcs.len(), 1);
assert!(update_fail_htlcs.is_empty());
assert!(update_fail_malformed_htlcs.is_empty());
assert!(update_fee.is_none());

nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]).unwrap();
let events_3 = nodes[0].node.get_and_clear_pending_events();
assert_eq!(events_3.len(), 1);
match events_3[0] {
Event::PaymentSent { ref payment_preimage } => {
assert_eq!(*payment_preimage, payment_preimage_1);
},
_ => panic!("Unexpected event"),
}

let (_, commitment_update) = nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed).unwrap();
assert!(commitment_update.is_none());
check_added_monitors!(nodes[0], 1);
},
_ => panic!("Unexpected event"),
}

nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);

let reestablish_1 = nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
assert_eq!(reestablish_1.len(), 1);
let reestablish_2 = nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
assert_eq!(reestablish_2.len(), 1);

let as_resp = nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
let bs_resp = nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();

assert!(as_resp.0.is_none());
assert!(bs_resp.0.is_none());

assert!(bs_resp.1.is_none());
assert!(bs_resp.2.is_none());

assert!(as_resp.3 == msgs::RAACommitmentOrder::CommitmentFirst);

assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]).unwrap();
let (bs_revoke_and_ack, bs_commitment_signed) = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed).unwrap();
assert!(bs_commitment_signed.is_none());
check_added_monitors!(nodes[1], 1);

let bs_second_commitment_signed = nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap()).unwrap().unwrap();
assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
assert!(bs_second_commitment_signed.update_fee.is_none());
check_added_monitors!(nodes[1], 1);

let as_commitment_signed = nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap().unwrap();
assert!(as_commitment_signed.update_add_htlcs.is_empty());
assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
assert!(as_commitment_signed.update_fail_htlcs.is_empty());
assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
assert!(as_commitment_signed.update_fee.is_none());
check_added_monitors!(nodes[0], 1);

let (as_revoke_and_ack, as_second_commitment_signed) = nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed).unwrap();
assert!(as_second_commitment_signed.is_none());
check_added_monitors!(nodes[0], 1);

let (bs_second_revoke_and_ack, bs_third_commitment_signed) = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed).unwrap();
assert!(bs_third_commitment_signed.is_none());
check_added_monitors!(nodes[1], 1);

assert!(nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap().is_none());
check_added_monitors!(nodes[1], 1);

let events_4 = nodes[1].node.get_and_clear_pending_events();
assert_eq!(events_4.len(), 1);
match events_4[0] {
Event::PendingHTLCsForwardable { .. } => { },
_ => panic!("Unexpected event"),
};

nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
nodes[1].node.process_pending_htlc_forwards();

let events_5 = nodes[1].node.get_and_clear_pending_events();
assert_eq!(events_5.len(), 1);
match events_5[0] {
Event::PaymentReceived { ref payment_hash, amt: _ } => {
assert_eq!(payment_hash_2, *payment_hash);
},
_ => panic!("Unexpected event"),
}

assert!(nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack).unwrap().is_none());
check_added_monitors!(nodes[0], 1);

claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
}

#[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
14 changes: 13 additions & 1 deletion src/ln/msgs.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -500,6 +500,18 @@ pub enum HTLCFailChannelUpdate {
}
}

/// For events which result in both a RevokeAndACK and a CommitmentUpdate, by default they should
/// be sent in the order they appear in the return value, however sometimes the order needs to be
/// variable at runtime (eg handle_channel_reestablish needs to re-send messages in the order they
/// were originally sent). In those cases, this enum is also returned.
#[derive(Clone, PartialEq)]
pub enum RAACommitmentOrder {
/// Send the CommitmentUpdate messages first
CommitmentFirst,
/// Send the RevokeAndACK message first
RevokeAndACKFirst,
}

/// A trait to describe an object which can receive channel messages.
///
/// Messages MAY be called in parallel when they originate from different their_node_ids, however
Expand DownExpand Up@@ -554,7 +566,7 @@ pub trait ChannelMessageHandler : events::EventsProvider + Send + Sync {
/// Handle a peer reconnecting, possibly generating channel_reestablish message(s).
fn peer_connected(&self, their_node_id: &PublicKey) -> Vec<ChannelReestablish>;
/// Handle an incoming channel_reestablish message from the given peer.
fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &ChannelReestablish) -> Result<(Option<FundingLocked>, Option<RevokeAndACK>, Option<CommitmentUpdate>), HandleError>;
fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &ChannelReestablish) -> Result<(Option<FundingLocked>, Option<RevokeAndACK>, Option<CommitmentUpdate>, RAACommitmentOrder), HandleError>;

// Error:
/// Handle an incoming error message from the given peer.
Expand Down
Loading
, '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
Merged
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
30 changes: 24 additions & 6 deletions src/ln/channel.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,7 +14,7 @@ use crypto::digest::Digest;
use crypto::hkdf::{hkdf_extract,hkdf_expand};

use ln::msgs;
use ln::msgs::{ErrorAction, HandleError};
use ln::msgs::{ErrorAction, HandleError, RAACommitmentOrder};
use ln::channelmonitor::ChannelMonitor;
use ln::channelmanager::{PendingHTLCStatus, HTLCSource, PendingForwardHTLCInfo, HTLCFailReason, HTLCFailureMsg};
use ln::chan_utils::{TxCreationKeys,HTLCOutputInCommitment,HTLC_SUCCESS_TX_WEIGHT,HTLC_TIMEOUT_TX_WEIGHT};
Expand DownExpand Up@@ -296,6 +296,12 @@ pub(super) struct Channel {
cur_local_commitment_transaction_number: u64,
cur_remote_commitment_transaction_number: u64,
value_to_self_msat: u64, // Excluding all pending_htlcs, excluding fees
/// Upon receipt of a channel_reestablish we have to figure out whether to send a
/// revoke_and_ack first or a commitment update first. Generally, we prefer to send
/// revoke_and_ack first, but if we had a pending commitment update of our own waiting on a
/// remote revoke when we received the latest commitment update from the remote we have to make
/// sure that commitment update gets resent first.
received_commitment_while_awaiting_raa: bool,
pending_inbound_htlcs: Vec<InboundHTLCOutput>,
pending_outbound_htlcs: Vec<OutboundHTLCOutput>,
holding_cell_htlc_updates: Vec<HTLCUpdateAwaitingACK>,
Expand DownExpand Up@@ -492,6 +498,8 @@ impl Channel {
cur_local_commitment_transaction_number: INITIAL_COMMITMENT_NUMBER,
cur_remote_commitment_transaction_number: INITIAL_COMMITMENT_NUMBER,
value_to_self_msat: channel_value_satoshis * 1000 - push_msat,
received_commitment_while_awaiting_raa: false,

pending_inbound_htlcs: Vec::new(),
pending_outbound_htlcs: Vec::new(),
holding_cell_htlc_updates: Vec::new(),
Expand DownExpand Up@@ -647,6 +655,8 @@ impl Channel {
cur_local_commitment_transaction_number: INITIAL_COMMITMENT_NUMBER,
cur_remote_commitment_transaction_number: INITIAL_COMMITMENT_NUMBER,
value_to_self_msat: msg.push_msat,
received_commitment_while_awaiting_raa: false,

pending_inbound_htlcs: Vec::new(),
pending_outbound_htlcs: Vec::new(),
holding_cell_htlc_updates: Vec::new(),
Expand DownExpand Up@@ -1696,6 +1706,7 @@ impl Channel {

self.cur_local_commitment_transaction_number -= 1;
self.last_local_commitment_txn = new_local_commitment_txn;
self.received_commitment_while_awaiting_raa = (self.channel_state & (ChannelState::AwaitingRemoteRevoke as u32)) != 0;

let (our_commitment_signed, monitor_update) = if need_our_commitment && (self.channel_state & (ChannelState::AwaitingRemoteRevoke as u32)) == 0 {
// If we're AwaitingRemoteRevoke we can't send a new commitment here, but that's ok -
Expand DownExpand Up@@ -1831,6 +1842,7 @@ impl Channel {
self.their_prev_commitment_point = self.their_cur_commitment_point;
self.their_cur_commitment_point = Some(msg.next_per_commitment_point);
self.cur_remote_commitment_transaction_number -= 1;
self.received_commitment_while_awaiting_raa = false;

let mut to_forward_infos = Vec::new();
let mut revoked_htlcs = Vec::new();
Expand DownExpand Up@@ -2072,7 +2084,7 @@ impl Channel {

/// May panic if some calls other than message-handling calls (which will all Err immediately)
/// have been called between remove_uncommitted_htlcs_and_mark_paused and this call.
pub fn channel_reestablish(&mut self, msg: &msgs::ChannelReestablish) -> Result<(Option<msgs::FundingLocked>, Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>, Option<ChannelMonitor>), ChannelError> {
pub fn channel_reestablish(&mut self, msg: &msgs::ChannelReestablish) -> Result<(Option<msgs::FundingLocked>, Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>, Option<ChannelMonitor>, RAACommitmentOrder), ChannelError> {
if self.channel_state & (ChannelState::PeerDisconnected as u32) == 0 {
// While BOLT 2 doesn't indicate explicitly we should error this channel here, it
// almost certainly indicates we are going to end up out-of-sync in some way, so we
Expand DownExpand Up@@ -2120,6 +2132,12 @@ impl Channel {
})
} else { None };

let order = if self.received_commitment_while_awaiting_raa {
RAACommitmentOrder::CommitmentFirst
} else {
RAACommitmentOrder::RevokeAndACKFirst
};

if msg.next_local_commitment_number == our_next_remote_commitment_number {
if required_revoke.is_some() {
log_debug!(self, "Reconnected channel {} with only lost outbound RAA", log_bytes!(self.channel_id()));
Expand All@@ -2142,11 +2160,11 @@ impl Channel {
panic!("Got non-channel-failing result from free_holding_cell_htlcs");
}
},
Ok(Some((commitment_update, channel_monitor))) => return Ok((resend_funding_locked, required_revoke, Some(commitment_update), Some(channel_monitor))),
Ok(None) => return Ok((resend_funding_locked, required_revoke, None, None)),
Ok(Some((commitment_update, channel_monitor))) => return Ok((resend_funding_locked, required_revoke, Some(commitment_update), Some(channel_monitor), order)),
Ok(None) => return Ok((resend_funding_locked, required_revoke, None, None, order)),
}
} else {
return Ok((resend_funding_locked, required_revoke, None, None));
return Ok((resend_funding_locked, required_revoke, None, None, order));
}
} else if msg.next_local_commitment_number == our_next_remote_commitment_number - 1 {
if required_revoke.is_some() {
Expand DownExpand Up@@ -2206,7 +2224,7 @@ impl Channel {
update_add_htlcs, update_fulfill_htlcs, update_fail_htlcs, update_fail_malformed_htlcs,
update_fee: None, //TODO: We need to support re-generating any update_fees in the last commitment_signed!
commitment_signed: self.send_commitment_no_state_update().expect("It looks like we failed to re-generate a commitment_signed we had previously sent?").0,
}), None));
}), None, order));
} else {
return Err(ChannelError::Close("Peer attempted to reestablish channel with a very old remote commitment transaction"));
}
Expand Down
147 changes: 142 additions & 5 deletions src/ln/channelmanager.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -26,7 +26,7 @@ use ln::channel::{Channel, ChannelError, ChannelKeys};
use ln::channelmonitor::{ManyChannelMonitor, CLTV_CLAIM_BUFFER, HTLC_FAIL_TIMEOUT_BLOCKS};
use ln::router::{Route,RouteHop};
use ln::msgs;
use ln::msgs::{HandleError,ChannelMessageHandler};
use ln::msgs::{ChannelMessageHandler, HandleError, RAACommitmentOrder};
use util::{byte_utils, events, internal_traits, rng};
use util::sha2::Sha256;
use util::ser::{Readable, Writeable};
Expand DownExpand Up@@ -2168,17 +2168,17 @@ impl ChannelManager {
Ok(())
}

fn internal_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(Option<msgs::FundingLocked>, Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>), MsgHandleErrInternal> {
fn internal_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(Option<msgs::FundingLocked>, Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>, RAACommitmentOrder), MsgHandleErrInternal> {
let (res, chan_monitor) = {
let mut channel_state = self.channel_state.lock().unwrap();
match channel_state.by_id.get_mut(&msg.channel_id) {
Some(chan) => {
if chan.get_their_node_id() != *their_node_id {
return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
}
let (funding_locked, revoke_and_ack, commitment_update, channel_monitor) = chan.channel_reestablish(msg)
let (funding_locked, revoke_and_ack, commitment_update, channel_monitor, order) = chan.channel_reestablish(msg)
.map_err(|e| MsgHandleErrInternal::from_chan_maybe_close(e, msg.channel_id))?;
(Ok((funding_locked, revoke_and_ack, commitment_update)), channel_monitor)
(Ok((funding_locked, revoke_and_ack, commitment_update, order)), channel_monitor)
},
None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
}
Expand DownExpand Up@@ -2448,7 +2448,7 @@ impl ChannelMessageHandler for ChannelManager {
handle_error!(self, self.internal_announcement_signatures(their_node_id, msg), their_node_id)
}

fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(Option<msgs::FundingLocked>, Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>), HandleError> {
fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(Option<msgs::FundingLocked>, Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>, RAACommitmentOrder), HandleError> {
handle_error!(self, self.internal_channel_reestablish(their_node_id, msg), their_node_id)
}

Expand DownExpand Up@@ -4938,6 +4938,7 @@ mod tests {
assert!(chan_msgs.0.is_none());
}
if pending_raa.0 {
assert!(chan_msgs.3 == msgs::RAACommitmentOrder::RevokeAndACKFirst);
assert!(node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap().is_none());
check_added_monitors!(node_a, 1);
} else {
Expand DownExpand Up@@ -4985,6 +4986,7 @@ mod tests {
assert!(chan_msgs.0.is_none());
}
if pending_raa.1 {
assert!(chan_msgs.3 == msgs::RAACommitmentOrder::RevokeAndACKFirst);
assert!(node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap().is_none());
check_added_monitors!(node_b, 1);
} else {
Expand DownExpand Up@@ -5316,6 +5318,141 @@ mod tests {
claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
}

#[test]
fn test_drop_messages_peer_disconnect_dual_htlc() {
// Test that we can handle reconnecting when both sides of a channel have pending
// commitment_updates when we disconnect.
let mut nodes = create_network(2);
create_announced_chan_between_nodes(&nodes, 0, 1);

let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);

// Now try to send a second payment which will fail to send
let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);

nodes[0].node.send_payment(route.clone(), payment_hash_2).unwrap();
check_added_monitors!(nodes[0], 1);

let events_1 = nodes[0].node.get_and_clear_pending_events();
assert_eq!(events_1.len(), 1);
match events_1[0] {
Event::UpdateHTLCs { .. } => {},
_ => panic!("Unexpected event"),
}

assert!(nodes[1].node.claim_funds(payment_preimage_1));
check_added_monitors!(nodes[1], 1);

let events_2 = nodes[1].node.get_and_clear_pending_events();
assert_eq!(events_2.len(), 1);
match events_2[0] {
Event::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, ref commitment_signed } } => {
assert_eq!(*node_id, nodes[0].node.get_our_node_id());
assert!(update_add_htlcs.is_empty());
assert_eq!(update_fulfill_htlcs.len(), 1);
assert!(update_fail_htlcs.is_empty());
assert!(update_fail_malformed_htlcs.is_empty());
assert!(update_fee.is_none());

nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]).unwrap();
let events_3 = nodes[0].node.get_and_clear_pending_events();
assert_eq!(events_3.len(), 1);
match events_3[0] {
Event::PaymentSent { ref payment_preimage } => {
assert_eq!(*payment_preimage, payment_preimage_1);
},
_ => panic!("Unexpected event"),
}

let (_, commitment_update) = nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed).unwrap();
assert!(commitment_update.is_none());
check_added_monitors!(nodes[0], 1);
},
_ => panic!("Unexpected event"),
}

nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);

let reestablish_1 = nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
assert_eq!(reestablish_1.len(), 1);
let reestablish_2 = nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
assert_eq!(reestablish_2.len(), 1);

let as_resp = nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
let bs_resp = nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();

assert!(as_resp.0.is_none());
assert!(bs_resp.0.is_none());

assert!(bs_resp.1.is_none());
assert!(bs_resp.2.is_none());

assert!(as_resp.3 == msgs::RAACommitmentOrder::CommitmentFirst);

assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]).unwrap();
let (bs_revoke_and_ack, bs_commitment_signed) = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed).unwrap();
assert!(bs_commitment_signed.is_none());
check_added_monitors!(nodes[1], 1);

let bs_second_commitment_signed = nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap()).unwrap().unwrap();
assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
assert!(bs_second_commitment_signed.update_fee.is_none());
check_added_monitors!(nodes[1], 1);

let as_commitment_signed = nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap().unwrap();
assert!(as_commitment_signed.update_add_htlcs.is_empty());
assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
assert!(as_commitment_signed.update_fail_htlcs.is_empty());
assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
assert!(as_commitment_signed.update_fee.is_none());
check_added_monitors!(nodes[0], 1);

let (as_revoke_and_ack, as_second_commitment_signed) = nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed).unwrap();
assert!(as_second_commitment_signed.is_none());
check_added_monitors!(nodes[0], 1);

let (bs_second_revoke_and_ack, bs_third_commitment_signed) = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed).unwrap();
assert!(bs_third_commitment_signed.is_none());
check_added_monitors!(nodes[1], 1);

assert!(nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap().is_none());
check_added_monitors!(nodes[1], 1);

let events_4 = nodes[1].node.get_and_clear_pending_events();
assert_eq!(events_4.len(), 1);
match events_4[0] {
Event::PendingHTLCsForwardable { .. } => { },
_ => panic!("Unexpected event"),
};

nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
nodes[1].node.process_pending_htlc_forwards();

let events_5 = nodes[1].node.get_and_clear_pending_events();
assert_eq!(events_5.len(), 1);
match events_5[0] {
Event::PaymentReceived { ref payment_hash, amt: _ } => {
assert_eq!(payment_hash_2, *payment_hash);
},
_ => panic!("Unexpected event"),
}

assert!(nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack).unwrap().is_none());
check_added_monitors!(nodes[0], 1);

claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
}

#[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
14 changes: 13 additions & 1 deletion src/ln/msgs.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -500,6 +500,18 @@ pub enum HTLCFailChannelUpdate {
}
}

/// For events which result in both a RevokeAndACK and a CommitmentUpdate, by default they should
/// be sent in the order they appear in the return value, however sometimes the order needs to be
/// variable at runtime (eg handle_channel_reestablish needs to re-send messages in the order they
/// were originally sent). In those cases, this enum is also returned.
#[derive(Clone, PartialEq)]
pub enum RAACommitmentOrder {
/// Send the CommitmentUpdate messages first
CommitmentFirst,
/// Send the RevokeAndACK message first
RevokeAndACKFirst,
}

/// A trait to describe an object which can receive channel messages.
///
/// Messages MAY be called in parallel when they originate from different their_node_ids, however
Expand DownExpand Up@@ -554,7 +566,7 @@ pub trait ChannelMessageHandler : events::EventsProvider + Send + Sync {
/// Handle a peer reconnecting, possibly generating channel_reestablish message(s).
fn peer_connected(&self, their_node_id: &PublicKey) -> Vec<ChannelReestablish>;
/// Handle an incoming channel_reestablish message from the given peer.
fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &ChannelReestablish) -> Result<(Option<FundingLocked>, Option<RevokeAndACK>, Option<CommitmentUpdate>), HandleError>;
fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &ChannelReestablish) -> Result<(Option<FundingLocked>, Option<RevokeAndACK>, Option<CommitmentUpdate>, RAACommitmentOrder), HandleError>;

// Error:
/// Handle an incoming error message from the given peer.
Expand Down
Loading
, '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
Merged
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
30 changes: 24 additions & 6 deletions src/ln/channel.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,7 +14,7 @@ use crypto::digest::Digest;
use crypto::hkdf::{hkdf_extract,hkdf_expand};

use ln::msgs;
use ln::msgs::{ErrorAction, HandleError};
use ln::msgs::{ErrorAction, HandleError, RAACommitmentOrder};
use ln::channelmonitor::ChannelMonitor;
use ln::channelmanager::{PendingHTLCStatus, HTLCSource, PendingForwardHTLCInfo, HTLCFailReason, HTLCFailureMsg};
use ln::chan_utils::{TxCreationKeys,HTLCOutputInCommitment,HTLC_SUCCESS_TX_WEIGHT,HTLC_TIMEOUT_TX_WEIGHT};
Expand DownExpand Up@@ -296,6 +296,12 @@ pub(super) struct Channel {
cur_local_commitment_transaction_number: u64,
cur_remote_commitment_transaction_number: u64,
value_to_self_msat: u64, // Excluding all pending_htlcs, excluding fees
/// Upon receipt of a channel_reestablish we have to figure out whether to send a
/// revoke_and_ack first or a commitment update first. Generally, we prefer to send
/// revoke_and_ack first, but if we had a pending commitment update of our own waiting on a
/// remote revoke when we received the latest commitment update from the remote we have to make
/// sure that commitment update gets resent first.
received_commitment_while_awaiting_raa: bool,
pending_inbound_htlcs: Vec<InboundHTLCOutput>,
pending_outbound_htlcs: Vec<OutboundHTLCOutput>,
holding_cell_htlc_updates: Vec<HTLCUpdateAwaitingACK>,
Expand DownExpand Up@@ -492,6 +498,8 @@ impl Channel {
cur_local_commitment_transaction_number: INITIAL_COMMITMENT_NUMBER,
cur_remote_commitment_transaction_number: INITIAL_COMMITMENT_NUMBER,
value_to_self_msat: channel_value_satoshis * 1000 - push_msat,
received_commitment_while_awaiting_raa: false,

pending_inbound_htlcs: Vec::new(),
pending_outbound_htlcs: Vec::new(),
holding_cell_htlc_updates: Vec::new(),
Expand DownExpand Up@@ -647,6 +655,8 @@ impl Channel {
cur_local_commitment_transaction_number: INITIAL_COMMITMENT_NUMBER,
cur_remote_commitment_transaction_number: INITIAL_COMMITMENT_NUMBER,
value_to_self_msat: msg.push_msat,
received_commitment_while_awaiting_raa: false,

pending_inbound_htlcs: Vec::new(),
pending_outbound_htlcs: Vec::new(),
holding_cell_htlc_updates: Vec::new(),
Expand DownExpand Up@@ -1696,6 +1706,7 @@ impl Channel {

self.cur_local_commitment_transaction_number -= 1;
self.last_local_commitment_txn = new_local_commitment_txn;
self.received_commitment_while_awaiting_raa = (self.channel_state & (ChannelState::AwaitingRemoteRevoke as u32)) != 0;

let (our_commitment_signed, monitor_update) = if need_our_commitment && (self.channel_state & (ChannelState::AwaitingRemoteRevoke as u32)) == 0 {
// If we're AwaitingRemoteRevoke we can't send a new commitment here, but that's ok -
Expand DownExpand Up@@ -1831,6 +1842,7 @@ impl Channel {
self.their_prev_commitment_point = self.their_cur_commitment_point;
self.their_cur_commitment_point = Some(msg.next_per_commitment_point);
self.cur_remote_commitment_transaction_number -= 1;
self.received_commitment_while_awaiting_raa = false;

let mut to_forward_infos = Vec::new();
let mut revoked_htlcs = Vec::new();
Expand DownExpand Up@@ -2072,7 +2084,7 @@ impl Channel {

/// May panic if some calls other than message-handling calls (which will all Err immediately)
/// have been called between remove_uncommitted_htlcs_and_mark_paused and this call.
pub fn channel_reestablish(&mut self, msg: &msgs::ChannelReestablish) -> Result<(Option<msgs::FundingLocked>, Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>, Option<ChannelMonitor>), ChannelError> {
pub fn channel_reestablish(&mut self, msg: &msgs::ChannelReestablish) -> Result<(Option<msgs::FundingLocked>, Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>, Option<ChannelMonitor>, RAACommitmentOrder), ChannelError> {
if self.channel_state & (ChannelState::PeerDisconnected as u32) == 0 {
// While BOLT 2 doesn't indicate explicitly we should error this channel here, it
// almost certainly indicates we are going to end up out-of-sync in some way, so we
Expand DownExpand Up@@ -2120,6 +2132,12 @@ impl Channel {
})
} else { None };

let order = if self.received_commitment_while_awaiting_raa {
RAACommitmentOrder::CommitmentFirst
} else {
RAACommitmentOrder::RevokeAndACKFirst
};

if msg.next_local_commitment_number == our_next_remote_commitment_number {
if required_revoke.is_some() {
log_debug!(self, "Reconnected channel {} with only lost outbound RAA", log_bytes!(self.channel_id()));
Expand All@@ -2142,11 +2160,11 @@ impl Channel {
panic!("Got non-channel-failing result from free_holding_cell_htlcs");
}
},
Ok(Some((commitment_update, channel_monitor))) => return Ok((resend_funding_locked, required_revoke, Some(commitment_update), Some(channel_monitor))),
Ok(None) => return Ok((resend_funding_locked, required_revoke, None, None)),
Ok(Some((commitment_update, channel_monitor))) => return Ok((resend_funding_locked, required_revoke, Some(commitment_update), Some(channel_monitor), order)),
Ok(None) => return Ok((resend_funding_locked, required_revoke, None, None, order)),
}
} else {
return Ok((resend_funding_locked, required_revoke, None, None));
return Ok((resend_funding_locked, required_revoke, None, None, order));
}
} else if msg.next_local_commitment_number == our_next_remote_commitment_number - 1 {
if required_revoke.is_some() {
Expand DownExpand Up@@ -2206,7 +2224,7 @@ impl Channel {
update_add_htlcs, update_fulfill_htlcs, update_fail_htlcs, update_fail_malformed_htlcs,
update_fee: None, //TODO: We need to support re-generating any update_fees in the last commitment_signed!
commitment_signed: self.send_commitment_no_state_update().expect("It looks like we failed to re-generate a commitment_signed we had previously sent?").0,
}), None));
}), None, order));
} else {
return Err(ChannelError::Close("Peer attempted to reestablish channel with a very old remote commitment transaction"));
}
Expand Down
147 changes: 142 additions & 5 deletions src/ln/channelmanager.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -26,7 +26,7 @@ use ln::channel::{Channel, ChannelError, ChannelKeys};
use ln::channelmonitor::{ManyChannelMonitor, CLTV_CLAIM_BUFFER, HTLC_FAIL_TIMEOUT_BLOCKS};
use ln::router::{Route,RouteHop};
use ln::msgs;
use ln::msgs::{HandleError,ChannelMessageHandler};
use ln::msgs::{ChannelMessageHandler, HandleError, RAACommitmentOrder};
use util::{byte_utils, events, internal_traits, rng};
use util::sha2::Sha256;
use util::ser::{Readable, Writeable};
Expand DownExpand Up@@ -2168,17 +2168,17 @@ impl ChannelManager {
Ok(())
}

fn internal_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(Option<msgs::FundingLocked>, Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>), MsgHandleErrInternal> {
fn internal_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(Option<msgs::FundingLocked>, Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>, RAACommitmentOrder), MsgHandleErrInternal> {
let (res, chan_monitor) = {
let mut channel_state = self.channel_state.lock().unwrap();
match channel_state.by_id.get_mut(&msg.channel_id) {
Some(chan) => {
if chan.get_their_node_id() != *their_node_id {
return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
}
let (funding_locked, revoke_and_ack, commitment_update, channel_monitor) = chan.channel_reestablish(msg)
let (funding_locked, revoke_and_ack, commitment_update, channel_monitor, order) = chan.channel_reestablish(msg)
.map_err(|e| MsgHandleErrInternal::from_chan_maybe_close(e, msg.channel_id))?;
(Ok((funding_locked, revoke_and_ack, commitment_update)), channel_monitor)
(Ok((funding_locked, revoke_and_ack, commitment_update, order)), channel_monitor)
},
None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
}
Expand DownExpand Up@@ -2448,7 +2448,7 @@ impl ChannelMessageHandler for ChannelManager {
handle_error!(self, self.internal_announcement_signatures(their_node_id, msg), their_node_id)
}

fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(Option<msgs::FundingLocked>, Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>), HandleError> {
fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(Option<msgs::FundingLocked>, Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>, RAACommitmentOrder), HandleError> {
handle_error!(self, self.internal_channel_reestablish(their_node_id, msg), their_node_id)
}

Expand DownExpand Up@@ -4938,6 +4938,7 @@ mod tests {
assert!(chan_msgs.0.is_none());
}
if pending_raa.0 {
assert!(chan_msgs.3 == msgs::RAACommitmentOrder::RevokeAndACKFirst);
assert!(node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap().is_none());
check_added_monitors!(node_a, 1);
} else {
Expand DownExpand Up@@ -4985,6 +4986,7 @@ mod tests {
assert!(chan_msgs.0.is_none());
}
if pending_raa.1 {
assert!(chan_msgs.3 == msgs::RAACommitmentOrder::RevokeAndACKFirst);
assert!(node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap().is_none());
check_added_monitors!(node_b, 1);
} else {
Expand DownExpand Up@@ -5316,6 +5318,141 @@ mod tests {
claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
}

#[test]
fn test_drop_messages_peer_disconnect_dual_htlc() {
// Test that we can handle reconnecting when both sides of a channel have pending
// commitment_updates when we disconnect.
let mut nodes = create_network(2);
create_announced_chan_between_nodes(&nodes, 0, 1);

let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);

// Now try to send a second payment which will fail to send
let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);

nodes[0].node.send_payment(route.clone(), payment_hash_2).unwrap();
check_added_monitors!(nodes[0], 1);

let events_1 = nodes[0].node.get_and_clear_pending_events();
assert_eq!(events_1.len(), 1);
match events_1[0] {
Event::UpdateHTLCs { .. } => {},
_ => panic!("Unexpected event"),
}

assert!(nodes[1].node.claim_funds(payment_preimage_1));
check_added_monitors!(nodes[1], 1);

let events_2 = nodes[1].node.get_and_clear_pending_events();
assert_eq!(events_2.len(), 1);
match events_2[0] {
Event::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, ref commitment_signed } } => {
assert_eq!(*node_id, nodes[0].node.get_our_node_id());
assert!(update_add_htlcs.is_empty());
assert_eq!(update_fulfill_htlcs.len(), 1);
assert!(update_fail_htlcs.is_empty());
assert!(update_fail_malformed_htlcs.is_empty());
assert!(update_fee.is_none());

nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]).unwrap();
let events_3 = nodes[0].node.get_and_clear_pending_events();
assert_eq!(events_3.len(), 1);
match events_3[0] {
Event::PaymentSent { ref payment_preimage } => {
assert_eq!(*payment_preimage, payment_preimage_1);
},
_ => panic!("Unexpected event"),
}

let (_, commitment_update) = nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed).unwrap();
assert!(commitment_update.is_none());
check_added_monitors!(nodes[0], 1);
},
_ => panic!("Unexpected event"),
}

nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);

let reestablish_1 = nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
assert_eq!(reestablish_1.len(), 1);
let reestablish_2 = nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
assert_eq!(reestablish_2.len(), 1);

let as_resp = nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
let bs_resp = nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();

assert!(as_resp.0.is_none());
assert!(bs_resp.0.is_none());

assert!(bs_resp.1.is_none());
assert!(bs_resp.2.is_none());

assert!(as_resp.3 == msgs::RAACommitmentOrder::CommitmentFirst);

assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]).unwrap();
let (bs_revoke_and_ack, bs_commitment_signed) = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed).unwrap();
assert!(bs_commitment_signed.is_none());
check_added_monitors!(nodes[1], 1);

let bs_second_commitment_signed = nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap()).unwrap().unwrap();
assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
assert!(bs_second_commitment_signed.update_fee.is_none());
check_added_monitors!(nodes[1], 1);

let as_commitment_signed = nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap().unwrap();
assert!(as_commitment_signed.update_add_htlcs.is_empty());
assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
assert!(as_commitment_signed.update_fail_htlcs.is_empty());
assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
assert!(as_commitment_signed.update_fee.is_none());
check_added_monitors!(nodes[0], 1);

let (as_revoke_and_ack, as_second_commitment_signed) = nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed).unwrap();
assert!(as_second_commitment_signed.is_none());
check_added_monitors!(nodes[0], 1);

let (bs_second_revoke_and_ack, bs_third_commitment_signed) = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed).unwrap();
assert!(bs_third_commitment_signed.is_none());
check_added_monitors!(nodes[1], 1);

assert!(nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap().is_none());
check_added_monitors!(nodes[1], 1);

let events_4 = nodes[1].node.get_and_clear_pending_events();
assert_eq!(events_4.len(), 1);
match events_4[0] {
Event::PendingHTLCsForwardable { .. } => { },
_ => panic!("Unexpected event"),
};

nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
nodes[1].node.process_pending_htlc_forwards();

let events_5 = nodes[1].node.get_and_clear_pending_events();
assert_eq!(events_5.len(), 1);
match events_5[0] {
Event::PaymentReceived { ref payment_hash, amt: _ } => {
assert_eq!(payment_hash_2, *payment_hash);
},
_ => panic!("Unexpected event"),
}

assert!(nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack).unwrap().is_none());
check_added_monitors!(nodes[0], 1);

claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
}

#[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
14 changes: 13 additions & 1 deletion src/ln/msgs.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -500,6 +500,18 @@ pub enum HTLCFailChannelUpdate {
}
}

/// For events which result in both a RevokeAndACK and a CommitmentUpdate, by default they should
/// be sent in the order they appear in the return value, however sometimes the order needs to be
/// variable at runtime (eg handle_channel_reestablish needs to re-send messages in the order they
/// were originally sent). In those cases, this enum is also returned.
#[derive(Clone, PartialEq)]
pub enum RAACommitmentOrder {
/// Send the CommitmentUpdate messages first
CommitmentFirst,
/// Send the RevokeAndACK message first
RevokeAndACKFirst,
}

/// A trait to describe an object which can receive channel messages.
///
/// Messages MAY be called in parallel when they originate from different their_node_ids, however
Expand DownExpand Up@@ -554,7 +566,7 @@ pub trait ChannelMessageHandler : events::EventsProvider + Send + Sync {
/// Handle a peer reconnecting, possibly generating channel_reestablish message(s).
fn peer_connected(&self, their_node_id: &PublicKey) -> Vec<ChannelReestablish>;
/// Handle an incoming channel_reestablish message from the given peer.
fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &ChannelReestablish) -> Result<(Option<FundingLocked>, Option<RevokeAndACK>, Option<CommitmentUpdate>), HandleError>;
fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &ChannelReestablish) -> Result<(Option<FundingLocked>, Option<RevokeAndACK>, Option<CommitmentUpdate>, RAACommitmentOrder), HandleError>;

// Error:
/// Handle an incoming error message from the given peer.
Expand Down
Loading
, '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
Merged
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
30 changes: 24 additions & 6 deletions src/ln/channel.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,7 +14,7 @@ use crypto::digest::Digest;
use crypto::hkdf::{hkdf_extract,hkdf_expand};

use ln::msgs;
use ln::msgs::{ErrorAction, HandleError};
use ln::msgs::{ErrorAction, HandleError, RAACommitmentOrder};
use ln::channelmonitor::ChannelMonitor;
use ln::channelmanager::{PendingHTLCStatus, HTLCSource, PendingForwardHTLCInfo, HTLCFailReason, HTLCFailureMsg};
use ln::chan_utils::{TxCreationKeys,HTLCOutputInCommitment,HTLC_SUCCESS_TX_WEIGHT,HTLC_TIMEOUT_TX_WEIGHT};
Expand DownExpand Up@@ -296,6 +296,12 @@ pub(super) struct Channel {
cur_local_commitment_transaction_number: u64,
cur_remote_commitment_transaction_number: u64,
value_to_self_msat: u64, // Excluding all pending_htlcs, excluding fees
/// Upon receipt of a channel_reestablish we have to figure out whether to send a
/// revoke_and_ack first or a commitment update first. Generally, we prefer to send
/// revoke_and_ack first, but if we had a pending commitment update of our own waiting on a
/// remote revoke when we received the latest commitment update from the remote we have to make
/// sure that commitment update gets resent first.
received_commitment_while_awaiting_raa: bool,
pending_inbound_htlcs: Vec<InboundHTLCOutput>,
pending_outbound_htlcs: Vec<OutboundHTLCOutput>,
holding_cell_htlc_updates: Vec<HTLCUpdateAwaitingACK>,
Expand DownExpand Up@@ -492,6 +498,8 @@ impl Channel {
cur_local_commitment_transaction_number: INITIAL_COMMITMENT_NUMBER,
cur_remote_commitment_transaction_number: INITIAL_COMMITMENT_NUMBER,
value_to_self_msat: channel_value_satoshis * 1000 - push_msat,
received_commitment_while_awaiting_raa: false,

pending_inbound_htlcs: Vec::new(),
pending_outbound_htlcs: Vec::new(),
holding_cell_htlc_updates: Vec::new(),
Expand DownExpand Up@@ -647,6 +655,8 @@ impl Channel {
cur_local_commitment_transaction_number: INITIAL_COMMITMENT_NUMBER,
cur_remote_commitment_transaction_number: INITIAL_COMMITMENT_NUMBER,
value_to_self_msat: msg.push_msat,
received_commitment_while_awaiting_raa: false,

pending_inbound_htlcs: Vec::new(),
pending_outbound_htlcs: Vec::new(),
holding_cell_htlc_updates: Vec::new(),
Expand DownExpand Up@@ -1696,6 +1706,7 @@ impl Channel {

self.cur_local_commitment_transaction_number -= 1;
self.last_local_commitment_txn = new_local_commitment_txn;
self.received_commitment_while_awaiting_raa = (self.channel_state & (ChannelState::AwaitingRemoteRevoke as u32)) != 0;

let (our_commitment_signed, monitor_update) = if need_our_commitment && (self.channel_state & (ChannelState::AwaitingRemoteRevoke as u32)) == 0 {
// If we're AwaitingRemoteRevoke we can't send a new commitment here, but that's ok -
Expand DownExpand Up@@ -1831,6 +1842,7 @@ impl Channel {
self.their_prev_commitment_point = self.their_cur_commitment_point;
self.their_cur_commitment_point = Some(msg.next_per_commitment_point);
self.cur_remote_commitment_transaction_number -= 1;
self.received_commitment_while_awaiting_raa = false;

let mut to_forward_infos = Vec::new();
let mut revoked_htlcs = Vec::new();
Expand DownExpand Up@@ -2072,7 +2084,7 @@ impl Channel {

/// May panic if some calls other than message-handling calls (which will all Err immediately)
/// have been called between remove_uncommitted_htlcs_and_mark_paused and this call.
pub fn channel_reestablish(&mut self, msg: &msgs::ChannelReestablish) -> Result<(Option<msgs::FundingLocked>, Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>, Option<ChannelMonitor>), ChannelError> {
pub fn channel_reestablish(&mut self, msg: &msgs::ChannelReestablish) -> Result<(Option<msgs::FundingLocked>, Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>, Option<ChannelMonitor>, RAACommitmentOrder), ChannelError> {
if self.channel_state & (ChannelState::PeerDisconnected as u32) == 0 {
// While BOLT 2 doesn't indicate explicitly we should error this channel here, it
// almost certainly indicates we are going to end up out-of-sync in some way, so we
Expand DownExpand Up@@ -2120,6 +2132,12 @@ impl Channel {
})
} else { None };

let order = if self.received_commitment_while_awaiting_raa {
RAACommitmentOrder::CommitmentFirst
} else {
RAACommitmentOrder::RevokeAndACKFirst
};

if msg.next_local_commitment_number == our_next_remote_commitment_number {
if required_revoke.is_some() {
log_debug!(self, "Reconnected channel {} with only lost outbound RAA", log_bytes!(self.channel_id()));
Expand All@@ -2142,11 +2160,11 @@ impl Channel {
panic!("Got non-channel-failing result from free_holding_cell_htlcs");
}
},
Ok(Some((commitment_update, channel_monitor))) => return Ok((resend_funding_locked, required_revoke, Some(commitment_update), Some(channel_monitor))),
Ok(None) => return Ok((resend_funding_locked, required_revoke, None, None)),
Ok(Some((commitment_update, channel_monitor))) => return Ok((resend_funding_locked, required_revoke, Some(commitment_update), Some(channel_monitor), order)),
Ok(None) => return Ok((resend_funding_locked, required_revoke, None, None, order)),
}
} else {
return Ok((resend_funding_locked, required_revoke, None, None));
return Ok((resend_funding_locked, required_revoke, None, None, order));
}
} else if msg.next_local_commitment_number == our_next_remote_commitment_number - 1 {
if required_revoke.is_some() {
Expand DownExpand Up@@ -2206,7 +2224,7 @@ impl Channel {
update_add_htlcs, update_fulfill_htlcs, update_fail_htlcs, update_fail_malformed_htlcs,
update_fee: None, //TODO: We need to support re-generating any update_fees in the last commitment_signed!
commitment_signed: self.send_commitment_no_state_update().expect("It looks like we failed to re-generate a commitment_signed we had previously sent?").0,
}), None));
}), None, order));
} else {
return Err(ChannelError::Close("Peer attempted to reestablish channel with a very old remote commitment transaction"));
}
Expand Down
147 changes: 142 additions & 5 deletions src/ln/channelmanager.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -26,7 +26,7 @@ use ln::channel::{Channel, ChannelError, ChannelKeys};
use ln::channelmonitor::{ManyChannelMonitor, CLTV_CLAIM_BUFFER, HTLC_FAIL_TIMEOUT_BLOCKS};
use ln::router::{Route,RouteHop};
use ln::msgs;
use ln::msgs::{HandleError,ChannelMessageHandler};
use ln::msgs::{ChannelMessageHandler, HandleError, RAACommitmentOrder};
use util::{byte_utils, events, internal_traits, rng};
use util::sha2::Sha256;
use util::ser::{Readable, Writeable};
Expand DownExpand Up@@ -2168,17 +2168,17 @@ impl ChannelManager {
Ok(())
}

fn internal_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(Option<msgs::FundingLocked>, Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>), MsgHandleErrInternal> {
fn internal_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(Option<msgs::FundingLocked>, Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>, RAACommitmentOrder), MsgHandleErrInternal> {
let (res, chan_monitor) = {
let mut channel_state = self.channel_state.lock().unwrap();
match channel_state.by_id.get_mut(&msg.channel_id) {
Some(chan) => {
if chan.get_their_node_id() != *their_node_id {
return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
}
let (funding_locked, revoke_and_ack, commitment_update, channel_monitor) = chan.channel_reestablish(msg)
let (funding_locked, revoke_and_ack, commitment_update, channel_monitor, order) = chan.channel_reestablish(msg)
.map_err(|e| MsgHandleErrInternal::from_chan_maybe_close(e, msg.channel_id))?;
(Ok((funding_locked, revoke_and_ack, commitment_update)), channel_monitor)
(Ok((funding_locked, revoke_and_ack, commitment_update, order)), channel_monitor)
},
None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
}
Expand DownExpand Up@@ -2448,7 +2448,7 @@ impl ChannelMessageHandler for ChannelManager {
handle_error!(self, self.internal_announcement_signatures(their_node_id, msg), their_node_id)
}

fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(Option<msgs::FundingLocked>, Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>), HandleError> {
fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(Option<msgs::FundingLocked>, Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>, RAACommitmentOrder), HandleError> {
handle_error!(self, self.internal_channel_reestablish(their_node_id, msg), their_node_id)
}

Expand DownExpand Up@@ -4938,6 +4938,7 @@ mod tests {
assert!(chan_msgs.0.is_none());
}
if pending_raa.0 {
assert!(chan_msgs.3 == msgs::RAACommitmentOrder::RevokeAndACKFirst);
assert!(node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap().is_none());
check_added_monitors!(node_a, 1);
} else {
Expand DownExpand Up@@ -4985,6 +4986,7 @@ mod tests {
assert!(chan_msgs.0.is_none());
}
if pending_raa.1 {
assert!(chan_msgs.3 == msgs::RAACommitmentOrder::RevokeAndACKFirst);
assert!(node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap().is_none());
check_added_monitors!(node_b, 1);
} else {
Expand DownExpand Up@@ -5316,6 +5318,141 @@ mod tests {
claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
}

#[test]
fn test_drop_messages_peer_disconnect_dual_htlc() {
// Test that we can handle reconnecting when both sides of a channel have pending
// commitment_updates when we disconnect.
let mut nodes = create_network(2);
create_announced_chan_between_nodes(&nodes, 0, 1);

let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);

// Now try to send a second payment which will fail to send
let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);

nodes[0].node.send_payment(route.clone(), payment_hash_2).unwrap();
check_added_monitors!(nodes[0], 1);

let events_1 = nodes[0].node.get_and_clear_pending_events();
assert_eq!(events_1.len(), 1);
match events_1[0] {
Event::UpdateHTLCs { .. } => {},
_ => panic!("Unexpected event"),
}

assert!(nodes[1].node.claim_funds(payment_preimage_1));
check_added_monitors!(nodes[1], 1);

let events_2 = nodes[1].node.get_and_clear_pending_events();
assert_eq!(events_2.len(), 1);
match events_2[0] {
Event::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, ref commitment_signed } } => {
assert_eq!(*node_id, nodes[0].node.get_our_node_id());
assert!(update_add_htlcs.is_empty());
assert_eq!(update_fulfill_htlcs.len(), 1);
assert!(update_fail_htlcs.is_empty());
assert!(update_fail_malformed_htlcs.is_empty());
assert!(update_fee.is_none());

nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]).unwrap();
let events_3 = nodes[0].node.get_and_clear_pending_events();
assert_eq!(events_3.len(), 1);
match events_3[0] {
Event::PaymentSent { ref payment_preimage } => {
assert_eq!(*payment_preimage, payment_preimage_1);
},
_ => panic!("Unexpected event"),
}

let (_, commitment_update) = nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed).unwrap();
assert!(commitment_update.is_none());
check_added_monitors!(nodes[0], 1);
},
_ => panic!("Unexpected event"),
}

nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);

let reestablish_1 = nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
assert_eq!(reestablish_1.len(), 1);
let reestablish_2 = nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
assert_eq!(reestablish_2.len(), 1);

let as_resp = nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
let bs_resp = nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();

assert!(as_resp.0.is_none());
assert!(bs_resp.0.is_none());

assert!(bs_resp.1.is_none());
assert!(bs_resp.2.is_none());

assert!(as_resp.3 == msgs::RAACommitmentOrder::CommitmentFirst);

assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]).unwrap();
let (bs_revoke_and_ack, bs_commitment_signed) = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed).unwrap();
assert!(bs_commitment_signed.is_none());
check_added_monitors!(nodes[1], 1);

let bs_second_commitment_signed = nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap()).unwrap().unwrap();
assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
assert!(bs_second_commitment_signed.update_fee.is_none());
check_added_monitors!(nodes[1], 1);

let as_commitment_signed = nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap().unwrap();
assert!(as_commitment_signed.update_add_htlcs.is_empty());
assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
assert!(as_commitment_signed.update_fail_htlcs.is_empty());
assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
assert!(as_commitment_signed.update_fee.is_none());
check_added_monitors!(nodes[0], 1);

let (as_revoke_and_ack, as_second_commitment_signed) = nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed).unwrap();
assert!(as_second_commitment_signed.is_none());
check_added_monitors!(nodes[0], 1);

let (bs_second_revoke_and_ack, bs_third_commitment_signed) = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed).unwrap();
assert!(bs_third_commitment_signed.is_none());
check_added_monitors!(nodes[1], 1);

assert!(nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap().is_none());
check_added_monitors!(nodes[1], 1);

let events_4 = nodes[1].node.get_and_clear_pending_events();
assert_eq!(events_4.len(), 1);
match events_4[0] {
Event::PendingHTLCsForwardable { .. } => { },
_ => panic!("Unexpected event"),
};

nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
nodes[1].node.process_pending_htlc_forwards();

let events_5 = nodes[1].node.get_and_clear_pending_events();
assert_eq!(events_5.len(), 1);
match events_5[0] {
Event::PaymentReceived { ref payment_hash, amt: _ } => {
assert_eq!(payment_hash_2, *payment_hash);
},
_ => panic!("Unexpected event"),
}

assert!(nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack).unwrap().is_none());
check_added_monitors!(nodes[0], 1);

claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
}

#[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
14 changes: 13 additions & 1 deletion src/ln/msgs.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -500,6 +500,18 @@ pub enum HTLCFailChannelUpdate {
}
}

/// For events which result in both a RevokeAndACK and a CommitmentUpdate, by default they should
/// be sent in the order they appear in the return value, however sometimes the order needs to be
/// variable at runtime (eg handle_channel_reestablish needs to re-send messages in the order they
/// were originally sent). In those cases, this enum is also returned.
#[derive(Clone, PartialEq)]
pub enum RAACommitmentOrder {
/// Send the CommitmentUpdate messages first
CommitmentFirst,
/// Send the RevokeAndACK message first
RevokeAndACKFirst,
}

/// A trait to describe an object which can receive channel messages.
///
/// Messages MAY be called in parallel when they originate from different their_node_ids, however
Expand DownExpand Up@@ -554,7 +566,7 @@ pub trait ChannelMessageHandler : events::EventsProvider + Send + Sync {
/// Handle a peer reconnecting, possibly generating channel_reestablish message(s).
fn peer_connected(&self, their_node_id: &PublicKey) -> Vec<ChannelReestablish>;
/// Handle an incoming channel_reestablish message from the given peer.
fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &ChannelReestablish) -> Result<(Option<FundingLocked>, Option<RevokeAndACK>, Option<CommitmentUpdate>), HandleError>;
fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &ChannelReestablish) -> Result<(Option<FundingLocked>, Option<RevokeAndACK>, Option<CommitmentUpdate>, RAACommitmentOrder), HandleError>;

// Error:
/// Handle an incoming error message from the given peer.
Expand Down
Loading