Skip to content

Commit b288a27

Browse files
committed
Return ClosureReason from Channel chain update methods
This fixes a few `ClosureReason`s and allows us to have finer-grained user-visible errors when a channel closes due to an on-chain event.
1 parent 4a3139d commit b288a27

File tree

6 files changed

+55
-33
lines changed

6 files changed

+55
-33
lines changed

lightning/src/ln/channel.rs

Lines changed: 10 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ use chain::chaininterface::{FeeEstimator,ConfirmationTarget};
3535
use chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateStep, LATENCY_GRACE_PERIOD_BLOCKS};
3636
use chain::transaction::{OutPoint, TransactionData};
3737
use chain::keysinterface::{Sign, KeysInterface};
38+
use util::events::ClosureReason;
3839
use util::ser::{Readable, ReadableArgs, Writeable, Writer, VecWriter};
3940
use util::logger::Logger;
4041
use util::errors::APIError;
@@ -4117,7 +4118,7 @@ impl<Signer: Sign> Channel<Signer> {
41174118
/// In the first case, we store the confirmation height and calculating the short channel id.
41184119
/// In the second, we simply return an Err indicating we need to be force-closed now.
41194120
pub fn transactions_confirmed<L: Deref>(&mut self, block_hash: &BlockHash, height: u32, txdata: &TransactionData, logger: &L)
4120-
-> Result<Option<msgs::FundingLocked>, msgs::ErrorMessage> where L::Target: Logger {
4121+
-> Result<Option<msgs::FundingLocked>, ClosureReason> where L::Target: Logger {
41214122
let non_shutdown_state = self.channel_state & (!MULTI_STATE_FLAGS);
41224123
for &(index_in_block, tx) in txdata.iter() {
41234124
if let Some(funding_txo) = self.get_funding_txo() {
@@ -4138,10 +4139,8 @@ impl<Signer: Sign> Channel<Signer> {
41384139
panic!("Client called ChannelManager::funding_transaction_generated with bogus transaction!");
41394140
}
41404141
self.update_time_counter += 1;
4141-
return Err(msgs::ErrorMessage {
4142-
channel_id: self.channel_id(),
4143-
data: "funding tx had wrong script/value or output index".to_owned()
4144-
});
4142+
let err_reason = "funding tx had wrong script/value or output index";
4143+
return Err(ClosureReason::ProcessingError { err: err_reason.to_owned() });
41454144
} else {
41464145
if self.is_outbound() {
41474146
for input in tx.input.iter() {
@@ -4172,10 +4171,7 @@ impl<Signer: Sign> Channel<Signer> {
41724171
for inp in tx.input.iter() {
41734172
if inp.previous_output == funding_txo.into_bitcoin_outpoint() {
41744173
log_info!(logger, "Detected channel-closing tx {} spending {}:{}, closing channel {}", tx.txid(), inp.previous_output.txid, inp.previous_output.vout, log_bytes!(self.channel_id()));
4175-
return Err(msgs::ErrorMessage {
4176-
channel_id: self.channel_id(),
4177-
data: "Commitment or closing transaction was confirmed on chain.".to_owned()
4178-
});
4174+
return Err(ClosureReason::CommitmentTxConfirmed);
41794175
}
41804176
}
41814177
}
@@ -4195,7 +4191,7 @@ impl<Signer: Sign> Channel<Signer> {
41954191
/// May return some HTLCs (and their payment_hash) which have timed out and should be failed
41964192
/// back.
41974193
pub fn best_block_updated<L: Deref>(&mut self, height: u32, highest_header_time: u32, logger: &L)
4198-
-> Result<(Option<msgs::FundingLocked>, Vec<(HTLCSource, PaymentHash)>), msgs::ErrorMessage> where L::Target: Logger {
4194+
-> Result<(Option<msgs::FundingLocked>, Vec<(HTLCSource, PaymentHash)>), ClosureReason> where L::Target: Logger {
41994195
let mut timed_out_htlcs = Vec::new();
42004196
// This mirrors the check in ChannelManager::decode_update_add_htlc_onion, refusing to
42014197
// forward an HTLC when our counterparty should almost certainly just fail it for expiring
@@ -4236,10 +4232,9 @@ impl<Signer: Sign> Channel<Signer> {
42364232
// close the channel and hope we can get the latest state on chain (because presumably
42374233
// the funding transaction is at least still in the mempool of most nodes).
42384234
if funding_tx_confirmations < self.minimum_depth.unwrap() as i64 / 2 {
4239-
return Err(msgs::ErrorMessage {
4240-
channel_id: self.channel_id(),
4241-
data: format!("Funding transaction was un-confirmed. Locked at {} confs, now have {} confs.", self.minimum_depth.unwrap(), funding_tx_confirmations),
4242-
});
4235+
let err_reason = format!("Funding transaction was un-confirmed. Locked at {} confs, now have {} confs.",
4236+
self.minimum_depth.unwrap(), funding_tx_confirmations);
4237+
return Err(ClosureReason::ProcessingError { err: err_reason });
42434238
}
42444239
}
42454240

@@ -4249,7 +4244,7 @@ impl<Signer: Sign> Channel<Signer> {
42494244
/// Indicates the funding transaction is no longer confirmed in the main chain. This may
42504245
/// force-close the channel, but may also indicate a harmless reorganization of a block or two
42514246
/// before the channel has reached funding_locked and we can just wait for more blocks.
4252-
pub fn funding_transaction_unconfirmed<L: Deref>(&mut self, logger: &L) -> Result<(), msgs::ErrorMessage> where L::Target: Logger {
4247+
pub fn funding_transaction_unconfirmed<L: Deref>(&mut self, logger: &L) -> Result<(), ClosureReason> where L::Target: Logger {
42534248
if self.funding_tx_confirmation_height != 0 {
42544249
// We handle the funding disconnection by calling best_block_updated with a height one
42554250
// below where our funding was connected, implying a reorg back to conf_height - 1.

lightning/src/ln/channelmanager.rs

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4850,7 +4850,7 @@ where
48504850
/// Calls a function which handles an on-chain event (blocks dis/connected, transactions
48514851
/// un/confirmed, etc) on each channel, handling any resulting errors or messages generated by
48524852
/// the function.
4853-
fn do_chain_event<FN: Fn(&mut Channel<Signer>) -> Result<(Option<msgs::FundingLocked>, Vec<(HTLCSource, PaymentHash)>), msgs::ErrorMessage>>
4853+
fn do_chain_event<FN: Fn(&mut Channel<Signer>) -> Result<(Option<msgs::FundingLocked>, Vec<(HTLCSource, PaymentHash)>), ClosureReason>>
48544854
(&self, height_opt: Option<u32>, f: FN) {
48554855
// Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
48564856
// during initialization prior to the chain_monitor being fully configured in some cases.
@@ -4895,7 +4895,7 @@ where
48954895
}
48964896
short_to_id.insert(channel.get_short_channel_id().unwrap(), channel.channel_id());
48974897
}
4898-
} else if let Err(e) = res {
4898+
} else if let Err(reason) = res {
48994899
if let Some(short_id) = channel.get_short_channel_id() {
49004900
short_to_id.remove(&short_id);
49014901
}
@@ -4907,10 +4907,14 @@ where
49074907
msg: update
49084908
});
49094909
}
4910-
self.issue_channel_close_events(channel, ClosureReason::CommitmentTxConfirmed);
4910+
let reason_message = format!("{}", reason);
4911+
self.issue_channel_close_events(channel, reason);
49114912
pending_msg_events.push(events::MessageSendEvent::HandleError {
49124913
node_id: channel.get_counterparty_node_id(),
4913-
action: msgs::ErrorAction::SendErrorMessage { msg: e },
4914+
action: msgs::ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage {
4915+
channel_id: channel.channel_id(),
4916+
data: reason_message,
4917+
} },
49144918
});
49154919
return false;
49164920
}

lightning/src/ln/functional_test_utils.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1737,7 +1737,7 @@ pub fn handle_announce_close_broadcast_events<'a, 'b, 'c>(nodes: &Vec<Node<'a, '
17371737
}
17381738

17391739
pub fn get_announce_close_broadcast_events<'a, 'b, 'c>(nodes: &Vec<Node<'a, 'b, 'c>>, a: usize, b: usize) {
1740-
handle_announce_close_broadcast_events(nodes, a, b, false, "Commitment or closing transaction was confirmed on chain.");
1740+
handle_announce_close_broadcast_events(nodes, a, b, false, "Channel closed because commitment or closing transaction was confirmed on chain.");
17411741
}
17421742

17431743
#[cfg(test)]

lightning/src/ln/functional_tests.rs

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1207,7 +1207,7 @@ fn test_duplicate_htlc_different_direction_onchain() {
12071207
MessageSendEvent::BroadcastChannelUpdate { .. } => {},
12081208
MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
12091209
assert_eq!(node_id, nodes[1].node.get_our_node_id());
1210-
assert_eq!(msg.data, "Commitment or closing transaction was confirmed on chain.");
1210+
assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
12111211
},
12121212
MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, .. } } => {
12131213
assert!(update_add_htlcs.is_empty());
@@ -3017,7 +3017,7 @@ fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use
30173017
match events[if deliver_bs_raa { 2 } else { 1 }] {
30183018
MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
30193019
assert_eq!(channel_id, chan_2.2);
3020-
assert_eq!(data.as_str(), "Commitment or closing transaction was confirmed on chain.");
3020+
assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
30213021
},
30223022
_ => panic!("Unexpected event"),
30233023
}
@@ -8831,15 +8831,16 @@ fn test_invalid_funding_tx() {
88318831
assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
88328832
nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
88338833

8834+
let expected_err = "funding tx had wrong script/value or output index";
88348835
confirm_transaction_at(&nodes[1], &tx, 1);
8835-
check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8836+
check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
88368837
check_added_monitors!(nodes[1], 1);
88378838
let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
88388839
assert_eq!(events_2.len(), 1);
88398840
if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
88408841
assert_eq!(*node_id, nodes[0].node.get_our_node_id());
88418842
if let msgs::ErrorAction::SendErrorMessage { msg } = action {
8842-
assert_eq!(msg.data, "funding tx had wrong script/value or output index");
8843+
assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
88438844
} else { panic!(); }
88448845
} else { panic!(); }
88458846
assert_eq!(nodes[1].node.list_channels().len(), 0);

lightning/src/ln/reorg_tests.rs

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -219,9 +219,9 @@ fn do_test_unconf_chan(reload_node: bool, reorg_after_reload: bool, use_funding_
219219
disconnect_all_blocks(&nodes[0]);
220220
}
221221
if connect_style == ConnectStyle::FullBlockViaListen && !use_funding_unconfirmed {
222-
handle_announce_close_broadcast_events(&nodes, 0, 1, true, "Funding transaction was un-confirmed. Locked at 6 confs, now have 2 confs.");
222+
handle_announce_close_broadcast_events(&nodes, 0, 1, true, "Channel closed because of an exception: Funding transaction was un-confirmed. Locked at 6 confs, now have 2 confs.");
223223
} else {
224-
handle_announce_close_broadcast_events(&nodes, 0, 1, true, "Funding transaction was un-confirmed. Locked at 6 confs, now have 0 confs.");
224+
handle_announce_close_broadcast_events(&nodes, 0, 1, true, "Channel closed because of an exception: Funding transaction was un-confirmed. Locked at 6 confs, now have 0 confs.");
225225
}
226226
check_added_monitors!(nodes[1], 1);
227227
{
@@ -287,9 +287,9 @@ fn do_test_unconf_chan(reload_node: bool, reorg_after_reload: bool, use_funding_
287287
disconnect_all_blocks(&nodes[0]);
288288
}
289289
if connect_style == ConnectStyle::FullBlockViaListen && !use_funding_unconfirmed {
290-
handle_announce_close_broadcast_events(&nodes, 0, 1, true, "Funding transaction was un-confirmed. Locked at 6 confs, now have 2 confs.");
290+
handle_announce_close_broadcast_events(&nodes, 0, 1, true, "Channel closed because of an exception: Funding transaction was un-confirmed. Locked at 6 confs, now have 2 confs.");
291291
} else {
292-
handle_announce_close_broadcast_events(&nodes, 0, 1, true, "Funding transaction was un-confirmed. Locked at 6 confs, now have 0 confs.");
292+
handle_announce_close_broadcast_events(&nodes, 0, 1, true, "Channel closed because of an exception: Funding transaction was un-confirmed. Locked at 6 confs, now have 0 confs.");
293293
}
294294
check_added_monitors!(nodes[1], 1);
295295
{
@@ -303,12 +303,13 @@ fn do_test_unconf_chan(reload_node: bool, reorg_after_reload: bool, use_funding_
303303
*nodes[0].chain_monitor.expect_channel_force_closed.lock().unwrap() = Some((chan.2, true));
304304
nodes[0].node.test_process_background_events(); // Required to free the pending background monitor update
305305
check_added_monitors!(nodes[0], 1);
306-
check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
307-
if connect_style == ConnectStyle::FullBlockViaListen && !use_funding_unconfirmed {
308-
check_closed_event!(nodes[1], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "Funding transaction was un-confirmed. Locked at 6 confs, now have 2 confs.".to_string() });
306+
let expected_err = if connect_style == ConnectStyle::FullBlockViaListen && !use_funding_unconfirmed {
307+
"Funding transaction was un-confirmed. Locked at 6 confs, now have 2 confs."
309308
} else {
310-
check_closed_event!(nodes[1], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "Funding transaction was un-confirmed. Locked at 6 confs, now have 0 confs.".to_string() });
311-
}
309+
"Funding transaction was un-confirmed. Locked at 6 confs, now have 0 confs."
310+
};
311+
check_closed_event!(nodes[1], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "Channel closed because of an exception: ".to_owned() + expected_err });
312+
check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: expected_err.to_owned() });
312313
assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
313314
nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
314315

lightning/src/util/events.rs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,27 @@ pub enum ClosureReason {
118118
OutdatedChannelManager
119119
}
120120

121+
impl core::fmt::Display for ClosureReason {
122+
fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
123+
f.write_str("Channel closed because ")?;
124+
match self {
125+
ClosureReason::CounterpartyForceClosed { peer_msg } => {
126+
f.write_str("counterparty force-closed with message ")?;
127+
f.write_str(&peer_msg)
128+
},
129+
ClosureReason::HolderForceClosed => f.write_str("user manually force-closed the channel"),
130+
ClosureReason::CooperativeClosure => f.write_str("the channel was cooperatively closed"),
131+
ClosureReason::CommitmentTxConfirmed => f.write_str("commitment or closing transaction was confirmed on chain."),
132+
ClosureReason::ProcessingError { err } => {
133+
f.write_str("of an exception: ")?;
134+
f.write_str(&err)
135+
},
136+
ClosureReason::DisconnectedPeer => f.write_str("the peer disconnected prior to the channel being funded"),
137+
ClosureReason::OutdatedChannelManager => f.write_str("the ChannelManager read from disk was stale compared to ChannelMonitor(s)"),
138+
}
139+
}
140+
}
141+
121142
impl_writeable_tlv_based_enum_upgradable!(ClosureReason,
122143
(0, CounterpartyForceClosed) => { (1, peer_msg, required) },
123144
(2, HolderForceClosed) => {},

0 commit comments

Comments
 (0)