Skip to content

Commit a468c35

Browse files
committed
Add data_loss_protect support
1 parent 26a7192 commit a468c35

File tree

4 files changed

+107
-28
lines changed

4 files changed

+107
-28
lines changed

src/ln/channel.rs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -371,6 +371,7 @@ pub const MAX_FUNDING_SATOSHIS: u64 = (1 << 24);
371371
pub(super) enum ChannelError {
372372
Ignore(&'static str),
373373
Close(&'static str),
374+
CloseNoPublish(&'static str),
374375
}
375376

376377
macro_rules! secp_check {
@@ -383,6 +384,11 @@ macro_rules! secp_check {
383384
}
384385

385386
impl Channel {
387+
// get functions
388+
pub fn get_channel_id(&self) -> [u8; 32] {
389+
self.channel_id
390+
}
391+
386392
// Convert constants + channel value to limits:
387393
fn get_our_max_htlc_value_in_flight_msat(channel_value_satoshis: u64) -> u64 {
388394
channel_value_satoshis * 1000 / 10 //TODO
@@ -2293,6 +2299,21 @@ impl Channel {
22932299
return Err(ChannelError::Close("Peer sent a garbage channel_reestablish"));
22942300
}
22952301

2302+
//Check for dataloss fields and fail channel
2303+
if msg.next_remote_commitment_number > 0 {
2304+
if let Some(ref data_loss) = msg.data_loss_protect {
2305+
//check if provided signature is a valid signature from us
2306+
if chan_utils::build_commitment_secret(self.local_keys.commitment_seed, msg.next_remote_commitment_number-1) != data_loss.your_last_per_commitment_secret{
2307+
return Err(ChannelError::Close("Peer sent a garbage channel_reestablish with secret key not matching the commitment height provided"));
2308+
}
2309+
//check if we have fallen beind
2310+
//We should not broadcast commitment transaction or continue
2311+
if msg.next_remote_commitment_number > self.cur_local_commitment_transaction_number{
2312+
return Err(ChannelError::CloseNoPublish("We have fallen behind and we cannot catch up, need to close channel but not publish commitment"));
2313+
}
2314+
}
2315+
}
2316+
22962317
// Go ahead and unmark PeerDisconnected as various calls we may make check for it (and all
22972318
// remaining cases either succeed or ErrorMessage-fail).
22982319
self.channel_state &= !(ChannelState::PeerDisconnected as u32);
@@ -2374,6 +2395,7 @@ impl Channel {
23742395
// now!
23752396
match self.free_holding_cell_htlcs() {
23762397
Err(ChannelError::Close(msg)) => return Err(ChannelError::Close(msg)),
2398+
Err(ChannelError::CloseNoPublish(msg)) => return Err(ChannelError::CloseNoPublish(msg)),
23772399
Err(ChannelError::Ignore(_)) => panic!("Got non-channel-failing result from free_holding_cell_htlcs"),
23782400
Ok(Some((commitment_update, channel_monitor))) => return Ok((resend_funding_locked, required_revoke, Some(commitment_update), Some(channel_monitor), order, shutdown_msg)),
23792401
Ok(None) => return Ok((resend_funding_locked, required_revoke, None, None, order, shutdown_msg)),

src/ln/channelmanager.rs

Lines changed: 56 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,15 @@ impl MsgHandleErrInternal {
196196
},
197197
}),
198198
},
199+
ChannelError::CloseNoPublish(msg) => HandleError {
200+
err: msg,
201+
action: Some(msgs::ErrorAction::SendErrorMessage {
202+
msg: msgs::ErrorMessage {
203+
channel_id,
204+
data: msg.to_string()
205+
},
206+
}),
207+
},
199208
},
200209
shutdown_finish: None,
201210
}
@@ -323,6 +332,7 @@ pub struct ChannelManager {
323332
total_consistency_lock: RwLock<()>,
324333

325334
keys_manager: Arc<KeysInterface>,
335+
channels_awaiting_claiming : HashMap<[u8; 32], Vec<bitcoin::Transaction>>,
326336

327337
logger: Arc<Logger>,
328338
}
@@ -392,7 +402,7 @@ macro_rules! handle_error {
392402
Ok(msg) => Ok(msg),
393403
Err(MsgHandleErrInternal { err, shutdown_finish }) => {
394404
if let Some((shutdown_res, update_option)) = shutdown_finish {
395-
$self.finish_force_close_channel(shutdown_res);
405+
$self.finish_force_close_channel(shutdown_res,None);
396406
if let Some(update) = update_option {
397407
let mut channel_state = $self.channel_state.lock().unwrap();
398408
channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
@@ -420,6 +430,13 @@ macro_rules! break_chan_entry {
420430
}
421431
break Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
422432
},
433+
Err(ChannelError::CloseNoPublish(msg)) => {
434+
let (channel_id, mut chan) = $entry.remove_entry();
435+
if let Some(short_id) = chan.get_short_channel_id() {
436+
$channel_state.short_to_id.remove(&short_id);
437+
}
438+
break Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
439+
},
423440
}
424441
}
425442
}
@@ -438,6 +455,13 @@ macro_rules! try_chan_entry {
438455
}
439456
return Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
440457
},
458+
Err(ChannelError::CloseNoPublish(msg)) => {
459+
let (channel_id, mut chan) = $entry.remove_entry();
460+
if let Some(short_id) = chan.get_short_channel_id() {
461+
$channel_state.short_to_id.remove(&short_id);
462+
}
463+
return Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
464+
},
441465
}
442466
}
443467
}
@@ -478,7 +502,7 @@ impl ChannelManager {
478502

479503
pending_events: Mutex::new(Vec::new()),
480504
total_consistency_lock: RwLock::new(()),
481-
505+
channels_awaiting_claiming : HashMap::new(),
482506
keys_manager,
483507

484508
logger,
@@ -615,14 +639,18 @@ impl ChannelManager {
615639
}
616640

617641
#[inline]
618-
fn finish_force_close_channel(&self, shutdown_res: ShutdownResult) {
642+
fn finish_force_close_channel(&mut self, shutdown_res: ShutdownResult,dont_claim_from_chain : Option<[u8; 32]>) {
619643
let (local_txn, mut failed_htlcs) = shutdown_res;
620644
for htlc_source in failed_htlcs.drain(..) {
621645
// unknown_next_peer...I dunno who that is anymore....
622646
self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source.0, &htlc_source.1, HTLCFailReason::Reason { failure_code: 0x4000 | 10, data: Vec::new() });
623647
}
624-
for tx in local_txn {
625-
self.tx_broadcaster.broadcast_transaction(&tx);
648+
if dont_claim_from_chain == None{
649+
for tx in local_txn {
650+
self.tx_broadcaster.broadcast_transaction(&tx);
651+
}
652+
} else {
653+
self.channels_awaiting_claiming.insert(dont_claim_from_chain.unwrap(), local_txn);
626654
}
627655
//TODO: We need to have a way where outbound HTLC claims can result in us claiming the
628656
//now-on-chain HTLC output for ourselves (and, thereafter, passing the HTLC backwards).
@@ -635,7 +663,7 @@ impl ChannelManager {
635663

636664
/// Force closes a channel, immediately broadcasting the latest local commitment transaction to
637665
/// the chain and rejecting new HTLCs on the given channel.
638-
pub fn force_close_channel(&self, channel_id: &[u8; 32]) {
666+
pub fn force_close_channel(&mut self, channel_id: &[u8; 32], store_closed : bool) {
639667
let _ = self.total_consistency_lock.read().unwrap();
640668

641669
let mut chan = {
@@ -650,7 +678,12 @@ impl ChannelManager {
650678
return;
651679
}
652680
};
653-
self.finish_force_close_channel(chan.force_shutdown());
681+
if store_closed{
682+
self.finish_force_close_channel(chan.force_shutdown(),Some(chan.get_channel_id()));
683+
} else
684+
{
685+
self.finish_force_close_channel(chan.force_shutdown(),None);
686+
}
654687
if let Ok(update) = self.get_channel_update(&chan) {
655688
let mut channel_state = self.channel_state.lock().unwrap();
656689
channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
@@ -661,13 +694,13 @@ impl ChannelManager {
661694

662695
/// Force close all channels, immediately broadcasting the latest local commitment transaction
663696
/// for each to the chain and rejecting new HTLCs on each.
664-
pub fn force_close_all_channels(&self) {
697+
pub fn force_close_all_channels(&mut self) {
665698
for chan in self.list_channels() {
666-
self.force_close_channel(&chan.channel_id);
699+
self.force_close_channel(&chan.channel_id, false);
667700
}
668701
}
669702

670-
fn handle_monitor_update_fail(&self, mut channel_state_lock: MutexGuard<ChannelHolder>, channel_id: &[u8; 32], err: ChannelMonitorUpdateErr, reason: RAACommitmentOrder) {
703+
fn handle_monitor_update_fail(&mut self, mut channel_state_lock: MutexGuard<ChannelHolder>, channel_id: &[u8; 32], err: ChannelMonitorUpdateErr, reason: RAACommitmentOrder) {
671704
match err {
672705
ChannelMonitorUpdateErr::PermanentFailure => {
673706
let mut chan = {
@@ -679,7 +712,7 @@ impl ChannelManager {
679712
chan
680713
};
681714
mem::drop(channel_state_lock);
682-
self.finish_force_close_channel(chan.force_shutdown());
715+
self.finish_force_close_channel(chan.force_shutdown(), None);
683716
if let Ok(update) = self.get_channel_update(&chan) {
684717
let mut channel_state = self.channel_state.lock().unwrap();
685718
channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
@@ -1194,7 +1227,7 @@ impl ChannelManager {
11941227
///
11951228
/// Raises APIError::RoutError when invalid route or forward parameter
11961229
/// (cltv_delta, fee, node public key) is specified
1197-
pub fn send_payment(&self, route: Route, payment_hash: [u8; 32]) -> Result<(), APIError> {
1230+
pub fn send_payment(&mut self, route: Route, payment_hash: [u8; 32]) -> Result<(), APIError> {
11981231
if route.hops.len() < 1 || route.hops.len() > 20 {
11991232
return Err(APIError::RouteError{err: "Route didn't go anywhere/had bogus size"});
12001233
}
@@ -1737,7 +1770,7 @@ impl ChannelManager {
17371770
self.forward_htlcs(&mut htlc_forwards[..]);
17381771

17391772
for res in close_results.drain(..) {
1740-
self.finish_force_close_channel(res);
1773+
self.finish_force_close_channel(res, None);
17411774
}
17421775
}
17431776

@@ -2659,7 +2692,7 @@ impl ChainListener for ChannelManager {
26592692
});
26602693
}
26612694
for failure in failed_channels.drain(..) {
2662-
self.finish_force_close_channel(failure);
2695+
self.finish_force_close_channel(failure, None);
26632696
}
26642697
self.latest_block_height.store(height as usize, Ordering::Release);
26652698
*self.last_block_hash.try_lock().expect("block_(dis)connected must not be called in parallel") = header.bitcoin_hash();
@@ -2692,7 +2725,7 @@ impl ChainListener for ChannelManager {
26922725
});
26932726
}
26942727
for failure in failed_channels.drain(..) {
2695-
self.finish_force_close_channel(failure);
2728+
self.finish_force_close_channel(failure, None);
26962729
}
26972730
self.latest_block_height.fetch_sub(1, Ordering::AcqRel);
26982731
*self.last_block_hash.try_lock().expect("block_(dis)connected must not be called in parallel") = header.bitcoin_hash();
@@ -2781,7 +2814,7 @@ impl ChannelMessageHandler for ChannelManager {
27812814
handle_error!(self, self.internal_channel_reestablish(their_node_id, msg), their_node_id)
27822815
}
27832816

2784-
fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool) {
2817+
fn peer_disconnected(&mut self, their_node_id: &PublicKey, no_connection_possible: bool) {
27852818
let _ = self.total_consistency_lock.read().unwrap();
27862819
let mut failed_channels = Vec::new();
27872820
let mut failed_payments = Vec::new();
@@ -2830,7 +2863,7 @@ impl ChannelMessageHandler for ChannelManager {
28302863
}
28312864
}
28322865
for failure in failed_channels.drain(..) {
2833-
self.finish_force_close_channel(failure);
2866+
self.finish_force_close_channel(failure, None);
28342867
}
28352868
for (chan_update, mut htlc_sources) in failed_payments {
28362869
for (htlc_source, payment_hash) in htlc_sources.drain(..) {
@@ -2866,17 +2899,17 @@ impl ChannelMessageHandler for ChannelManager {
28662899
//TODO: Also re-broadcast announcement_signatures
28672900
}
28682901

2869-
fn handle_error(&self, their_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
2902+
fn handle_error(&mut self, their_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
28702903
let _ = self.total_consistency_lock.read().unwrap();
28712904

28722905
if msg.channel_id == [0; 32] {
28732906
for chan in self.list_channels() {
28742907
if chan.remote_network_id == *their_node_id {
2875-
self.force_close_channel(&chan.channel_id);
2908+
self.force_close_channel(&chan.channel_id, false);
28762909
}
28772910
}
28782911
} else {
2879-
self.force_close_channel(&msg.channel_id);
2912+
self.force_close_channel(&msg.channel_id, false);
28802913
}
28812914
}
28822915
}
@@ -3225,7 +3258,7 @@ impl<'a, R : ::std::io::Read> ReadableArgs<R, ChannelManagerReadArgs<'a>> for (S
32253258
claimable_htlcs.insert(payment_hash, previous_hops);
32263259
}
32273260

3228-
let channel_manager = ChannelManager {
3261+
let mut channel_manager = ChannelManager {
32293262
genesis_hash,
32303263
fee_estimator: args.fee_estimator,
32313264
monitor: args.monitor,
@@ -3250,11 +3283,12 @@ impl<'a, R : ::std::io::Read> ReadableArgs<R, ChannelManagerReadArgs<'a>> for (S
32503283
total_consistency_lock: RwLock::new(()),
32513284
keys_manager: args.keys_manager,
32523285
logger: args.logger,
3286+
channels_awaiting_claiming : HashMap::new(),
32533287
default_configuration: args.default_config,
32543288
};
32553289

32563290
for close_res in closed_channels.drain(..) {
3257-
channel_manager.finish_force_close_channel(close_res);
3291+
channel_manager.finish_force_close_channel(close_res, None);
32583292
//TODO: Broadcast channel update for closed channels, but only after we've made a
32593293
//connection or two.
32603294
}

src/ln/msgs.rs

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,13 @@ impl LocalFeatures {
7070
pub(crate) fn requires_data_loss_protect(&self) -> bool {
7171
self.flags.len() > 0 && (self.flags[0] & 1) != 0
7272
}
73+
pub(crate) fn set_supports_data_loss_protect(&mut self) {
74+
if self.flags.len() == 0 {
75+
self.flags.resize(1, 3);
76+
} else {
77+
self.flags[0] |= 3;
78+
}
79+
}
7380

7481
pub(crate) fn initial_routing_sync(&self) -> bool {
7582
self.flags.len() > 0 && (self.flags[0] & (1 << 3)) != 0
@@ -465,6 +472,11 @@ pub enum ErrorAction {
465472
/// The message to send.
466473
msg: ErrorMessage
467474
},
475+
///We encountered a state where we cannot recover from we should drop the channel without redeeming as we might loose all channel funds.
476+
DropChannel {
477+
/// The message to log.
478+
msg: ErrorMessage
479+
},
468480
}
469481

470482
/// An Err type for failure to process messages.
@@ -565,7 +577,7 @@ pub trait ChannelMessageHandler : events::MessageSendEventsProvider + Send + Syn
565577
/// is believed to be possible in the future (eg they're sending us messages we don't
566578
/// understand or indicate they require unknown feature bits), no_connection_possible is set
567579
/// and any outstanding channels should be failed.
568-
fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool);
580+
fn peer_disconnected(&mut self, their_node_id: &PublicKey, no_connection_possible: bool);
569581

570582
/// Handle a peer reconnecting, possibly generating channel_reestablish message(s).
571583
fn peer_connected(&self, their_node_id: &PublicKey);
@@ -574,7 +586,7 @@ pub trait ChannelMessageHandler : events::MessageSendEventsProvider + Send + Syn
574586

575587
// Error:
576588
/// Handle an incoming error message from the given peer.
577-
fn handle_error(&self, their_node_id: &PublicKey, msg: &ErrorMessage);
589+
fn handle_error(&mut self, their_node_id: &PublicKey, msg: &ErrorMessage);
578590
}
579591

580592
/// A trait to describe an object which can receive routing messages.

0 commit comments

Comments
 (0)