Skip to content

Commit 6032099

Browse files
committed
Remove remaining uses of HandleError in Channel Err return values
This converts block_connected failures to returning the ErrorMessage that needs to be sent directly, since it always results in channel closure and never results in needing to call force_shutdown. It also converts update_add_htlc and closing_signed handlers to ChannelError as the rest of the message handlers.
1 parent dfbcacf commit 6032099

File tree

2 files changed

+32
-44
lines changed

2 files changed

+32
-44
lines changed

src/ln/channel.rs

Lines changed: 26 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ use secp256k1;
1313
use crypto::digest::Digest;
1414

1515
use ln::msgs;
16-
use ln::msgs::{DecodeError, ErrorAction, HandleError};
16+
use ln::msgs::DecodeError;
1717
use ln::channelmonitor::ChannelMonitor;
1818
use ln::channelmanager::{PendingHTLCStatus, HTLCSource, HTLCFailReason, HTLCFailureMsg, PendingForwardHTLCInfo, RAACommitmentOrder};
1919
use ln::chan_utils::{TxCreationKeys,HTLCOutputInCommitment,HTLC_SUCCESS_TX_WEIGHT,HTLC_TIMEOUT_TX_WEIGHT};
@@ -373,15 +373,6 @@ pub(super) enum ChannelError {
373373
Close(&'static str),
374374
}
375375

376-
macro_rules! secp_call {
377-
( $res: expr, $err: expr, $chan_id: expr ) => {
378-
match $res {
379-
Ok(key) => key,
380-
Err(_) => return Err(HandleError {err: $err, action: Some(msgs::ErrorAction::SendErrorMessage {msg: msgs::ErrorMessage {channel_id: $chan_id, data: $err.to_string()}})})
381-
}
382-
};
383-
}
384-
385376
macro_rules! secp_check {
386377
($res: expr, $err: expr) => {
387378
match $res {
@@ -1528,40 +1519,40 @@ impl Channel {
15281519
(self.pending_outbound_htlcs.len() as u32, htlc_outbound_value_msat)
15291520
}
15301521

1531-
pub fn update_add_htlc(&mut self, msg: &msgs::UpdateAddHTLC, pending_forward_state: PendingHTLCStatus) -> Result<(), HandleError> {
1522+
pub fn update_add_htlc(&mut self, msg: &msgs::UpdateAddHTLC, pending_forward_state: PendingHTLCStatus) -> Result<(), ChannelError> {
15321523
if (self.channel_state & (ChannelState::ChannelFunded as u32 | ChannelState::RemoteShutdownSent as u32)) != (ChannelState::ChannelFunded as u32) {
1533-
return Err(HandleError{err: "Got add HTLC message when channel was not in an operational state", action: None});
1524+
return Err(ChannelError::Close("Got add HTLC message when channel was not in an operational state"));
15341525
}
15351526
if self.channel_state & (ChannelState::PeerDisconnected as u32) == ChannelState::PeerDisconnected as u32 {
1536-
return Err(HandleError{err: "Peer sent update_add_htlc when we needed a channel_reestablish", action: Some(msgs::ErrorAction::SendErrorMessage{msg: msgs::ErrorMessage{data: "Peer sent update_add_htlc when we needed a channel_reestablish".to_string(), channel_id: msg.channel_id}})});
1527+
return Err(ChannelError::Close("Peer sent update_add_htlc when we needed a channel_reestablish"));
15371528
}
15381529
if msg.amount_msat > self.channel_value_satoshis * 1000 {
1539-
return Err(HandleError{err: "Remote side tried to send more than the total value of the channel", action: None});
1530+
return Err(ChannelError::Close("Remote side tried to send more than the total value of the channel"));
15401531
}
15411532
if msg.amount_msat < self.our_htlc_minimum_msat {
1542-
return Err(HandleError{err: "Remote side tried to send less than our minimum HTLC value", action: None});
1533+
return Err(ChannelError::Close("Remote side tried to send less than our minimum HTLC value"));
15431534
}
15441535

15451536
let (inbound_htlc_count, htlc_inbound_value_msat) = self.get_inbound_pending_htlc_stats();
15461537
if inbound_htlc_count + 1 > OUR_MAX_HTLCS as u32 {
1547-
return Err(HandleError{err: "Remote tried to push more than our max accepted HTLCs", action: None});
1538+
return Err(ChannelError::Close("Remote tried to push more than our max accepted HTLCs"));
15481539
}
15491540
//TODO: Spec is unclear if this is per-direction or in total (I assume per direction):
15501541
// Check our_max_htlc_value_in_flight_msat
15511542
if htlc_inbound_value_msat + msg.amount_msat > Channel::get_our_max_htlc_value_in_flight_msat(self.channel_value_satoshis) {
1552-
return Err(HandleError{err: "Remote HTLC add would put them over their max HTLC value in flight", action: None});
1543+
return Err(ChannelError::Close("Remote HTLC add would put them over their max HTLC value in flight"));
15531544
}
15541545
// Check our_channel_reserve_satoshis (we're getting paid, so they have to at least meet
15551546
// the reserve_satoshis we told them to always have as direct payment so that they lose
15561547
// something if we punish them for broadcasting an old state).
15571548
if htlc_inbound_value_msat + msg.amount_msat + self.value_to_self_msat > (self.channel_value_satoshis - Channel::get_our_channel_reserve_satoshis(self.channel_value_satoshis)) * 1000 {
1558-
return Err(HandleError{err: "Remote HTLC add would put them over their reserve value", action: None});
1549+
return Err(ChannelError::Close("Remote HTLC add would put them over their reserve value"));
15591550
}
15601551
if self.next_remote_htlc_id != msg.htlc_id {
1561-
return Err(HandleError{err: "Remote skipped HTLC ID", action: None});
1552+
return Err(ChannelError::Close("Remote skipped HTLC ID"));
15621553
}
15631554
if msg.cltv_expiry >= 500000000 {
1564-
return Err(HandleError{err: "Remote provided CLTV expiry in seconds instead of block height", action: None});
1555+
return Err(ChannelError::Close("Remote provided CLTV expiry in seconds instead of block height"));
15651556
}
15661557

15671558
//TODO: Check msg.cltv_expiry further? Do this in channel manager?
@@ -2508,24 +2499,24 @@ impl Channel {
25082499
Ok((our_shutdown, self.maybe_propose_first_closing_signed(fee_estimator), dropped_outbound_htlcs))
25092500
}
25102501

2511-
pub fn closing_signed(&mut self, fee_estimator: &FeeEstimator, msg: &msgs::ClosingSigned) -> Result<(Option<msgs::ClosingSigned>, Option<Transaction>), HandleError> {
2502+
pub fn closing_signed(&mut self, fee_estimator: &FeeEstimator, msg: &msgs::ClosingSigned) -> Result<(Option<msgs::ClosingSigned>, Option<Transaction>), ChannelError> {
25122503
if self.channel_state & BOTH_SIDES_SHUTDOWN_MASK != BOTH_SIDES_SHUTDOWN_MASK {
2513-
return Err(HandleError{err: "Remote end sent us a closing_signed before both sides provided a shutdown", action: None});
2504+
return Err(ChannelError::Close("Remote end sent us a closing_signed before both sides provided a shutdown"));
25142505
}
25152506
if self.channel_state & (ChannelState::PeerDisconnected as u32) == ChannelState::PeerDisconnected as u32 {
2516-
return Err(HandleError{err: "Peer sent closing_signed when we needed a channel_reestablish", action: Some(msgs::ErrorAction::SendErrorMessage{msg: msgs::ErrorMessage{data: "Peer sent closing_signed when we needed a channel_reestablish".to_string(), channel_id: msg.channel_id}})});
2507+
return Err(ChannelError::Close("Peer sent closing_signed when we needed a channel_reestablish"));
25172508
}
25182509
if !self.pending_inbound_htlcs.is_empty() || !self.pending_outbound_htlcs.is_empty() {
2519-
return Err(HandleError{err: "Remote end sent us a closing_signed while there were still pending HTLCs", action: None});
2510+
return Err(ChannelError::Close("Remote end sent us a closing_signed while there were still pending HTLCs"));
25202511
}
25212512
if msg.fee_satoshis > 21000000 * 10000000 { //this is required to stop potential overflow in build_closing_transaction
2522-
return Err(HandleError{err: "Remote tried to send us a closing tx with > 21 million BTC fee", action: None});
2513+
return Err(ChannelError::Close("Remote tried to send us a closing tx with > 21 million BTC fee"));
25232514
}
25242515

25252516
let funding_redeemscript = self.get_funding_redeemscript();
25262517
let (mut closing_tx, used_total_fee) = self.build_closing_transaction(msg.fee_satoshis, false);
25272518
if used_total_fee != msg.fee_satoshis {
2528-
return Err(HandleError{err: "Remote sent us a closing_signed with a fee greater than the value they can claim", action: None});
2519+
return Err(ChannelError::Close("Remote sent us a closing_signed with a fee greater than the value they can claim"));
25292520
}
25302521
let mut sighash = Message::from_slice(&bip143::SighashComponents::new(&closing_tx).sighash_all(&closing_tx.input[0], &funding_redeemscript, self.channel_value_satoshis)[..]).unwrap();
25312522

@@ -2536,7 +2527,7 @@ impl Channel {
25362527
// limits, so check for that case by re-checking the signature here.
25372528
closing_tx = self.build_closing_transaction(msg.fee_satoshis, true).0;
25382529
sighash = Message::from_slice(&bip143::SighashComponents::new(&closing_tx).sighash_all(&closing_tx.input[0], &funding_redeemscript, self.channel_value_satoshis)[..]).unwrap();
2539-
secp_call!(self.secp_ctx.verify(&sighash, &msg.signature, &self.their_funding_pubkey.unwrap()), "Invalid closing tx signature from peer", self.channel_id());
2530+
secp_check!(self.secp_ctx.verify(&sighash, &msg.signature, &self.their_funding_pubkey.unwrap()), "Invalid closing tx signature from peer");
25402531
},
25412532
};
25422533

@@ -2570,7 +2561,7 @@ impl Channel {
25702561
if proposed_sat_per_kw > our_max_feerate {
25712562
if let Some((last_feerate, _)) = self.last_sent_closing_fee {
25722563
if our_max_feerate <= last_feerate {
2573-
return Err(HandleError{err: "Unable to come to consensus about closing feerate, remote wanted something higher than our Normal feerate", action: None});
2564+
return Err(ChannelError::Close("Unable to come to consensus about closing feerate, remote wanted something higher than our Normal feerate"));
25742565
}
25752566
}
25762567
propose_new_feerate!(our_max_feerate);
@@ -2580,7 +2571,7 @@ impl Channel {
25802571
if proposed_sat_per_kw < our_min_feerate {
25812572
if let Some((last_feerate, _)) = self.last_sent_closing_fee {
25822573
if our_min_feerate >= last_feerate {
2583-
return Err(HandleError{err: "Unable to come to consensus about closing feerate, remote wanted something lower than our Background feerate", action: None});
2574+
return Err(ChannelError::Close("Unable to come to consensus about closing feerate, remote wanted something lower than our Background feerate"));
25842575
}
25852576
}
25862577
propose_new_feerate!(our_min_feerate);
@@ -2780,7 +2771,7 @@ impl Channel {
27802771
/// In case of Err, the channel may have been closed, at which point the standard requirements
27812772
/// apply - no calls may be made except those explicitly stated to be allowed post-shutdown.
27822773
/// Only returns an ErrorAction of DisconnectPeer, if Err.
2783-
pub fn block_connected(&mut self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]) -> Result<Option<msgs::FundingLocked>, HandleError> {
2774+
pub fn block_connected(&mut self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]) -> Result<Option<msgs::FundingLocked>, msgs::ErrorMessage> {
27842775
let non_shutdown_state = self.channel_state & (!MULTI_STATE_FLAGS);
27852776
if header.bitcoin_hash() != self.last_block_connected {
27862777
self.last_block_connected = header.bitcoin_hash();
@@ -2840,7 +2831,10 @@ impl Channel {
28402831
}
28412832
self.channel_state = ChannelState::ShutdownComplete as u32;
28422833
self.channel_update_count += 1;
2843-
return Err(HandleError{err: "funding tx had wrong script/value", action: Some(ErrorAction::DisconnectPeer{msg: None})});
2834+
return Err(msgs::ErrorMessage {
2835+
channel_id: self.channel_id(),
2836+
data: "funding tx had wrong script/value".to_owned()
2837+
});
28442838
} else {
28452839
if self.channel_outbound {
28462840
for input in tx.input.iter() {
@@ -3160,7 +3154,7 @@ impl Channel {
31603154
}
31613155

31623156
/// Creates a signed commitment transaction to send to the remote peer.
3163-
/// Always returns a Channel-failing HandleError::action if an immediately-preceding (read: the
3157+
/// Always returns a ChannelError::Close if an immediately-preceding (read: the
31643158
/// last call to this Channel) send_htlc returned Ok(Some(_)) and there is an Err.
31653159
/// May panic if called except immediately after a successful, Ok(Some(_))-returning send_htlc.
31663160
pub fn send_commitment(&mut self) -> Result<(msgs::CommitmentSigned, ChannelMonitor), ChannelError> {

src/ln/channelmanager.rs

Lines changed: 6 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -169,10 +169,6 @@ impl MsgHandleErrInternal {
169169
}
170170
}
171171
#[inline]
172-
fn from_maybe_close(err: msgs::HandleError) -> Self {
173-
Self { err, needs_channel_force_close: true }
174-
}
175-
#[inline]
176172
fn from_no_close(err: msgs::HandleError) -> Self {
177173
Self { err, needs_channel_force_close: false }
178174
}
@@ -1928,7 +1924,7 @@ impl ChannelManager {
19281924
//TODO: here and below MsgHandleErrInternal, #153 case
19291925
return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
19301926
}
1931-
let (closing_signed, tx) = chan_entry.get_mut().closing_signed(&*self.fee_estimator, &msg).map_err(|e| MsgHandleErrInternal::from_maybe_close(e))?;
1927+
let (closing_signed, tx) = chan_entry.get_mut().closing_signed(&*self.fee_estimator, &msg).map_err(|e| MsgHandleErrInternal::from_chan_maybe_close(e, msg.channel_id))?;
19321928
if let Some(msg) = closing_signed {
19331929
channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
19341930
node_id: their_node_id.clone(),
@@ -2005,7 +2001,7 @@ impl ChannelManager {
20052001
}));
20062002
}
20072003
}
2008-
chan.update_add_htlc(&msg, pending_forward_info).map_err(|e| MsgHandleErrInternal::from_maybe_close(e))
2004+
chan.update_add_htlc(&msg, pending_forward_info).map_err(|e| MsgHandleErrInternal::from_chan_maybe_close(e, msg.channel_id))
20092005
},
20102006
None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
20112007
}
@@ -2588,11 +2584,9 @@ impl ChainListener for ChannelManager {
25882584
} else if let Err(e) = chan_res {
25892585
pending_msg_events.push(events::MessageSendEvent::HandleError {
25902586
node_id: channel.get_their_node_id(),
2591-
action: e.action,
2587+
action: Some(msgs::ErrorAction::SendErrorMessage { msg: e }),
25922588
});
2593-
if channel.is_shutdown() {
2594-
return false;
2595-
}
2589+
return false;
25962590
}
25972591
if let Some(funding_txo) = channel.get_funding_txo() {
25982592
for tx in txn_matched {
@@ -5532,7 +5526,7 @@ mod tests {
55325526
HandleError{err, .. } => assert_eq!(err, "Remote HTLC add would put them over their reserve value"),
55335527
}
55345528
// If we send a garbage message, the channel should get closed, making the rest of this test case fail.
5535-
/*assert_eq!(nodes[1].node.list_channels().len(), 1);
5529+
assert_eq!(nodes[1].node.list_channels().len(), 1);
55365530
assert_eq!(nodes[1].node.list_channels().len(), 1);
55375531
let channel_close_broadcast = nodes[1].node.get_and_clear_pending_msg_events();
55385532
assert_eq!(channel_close_broadcast.len(), 1);
@@ -5541,7 +5535,7 @@ mod tests {
55415535
assert_eq!(msg.contents.flags & 2, 2);
55425536
},
55435537
_ => panic!("Unexpected event"),
5544-
}*/
5538+
}
55455539
return;
55465540
}
55475541
}

0 commit comments

Comments
 (0)