Skip to content

Implement option_data_loss_protect on both sides - #349

Merged
TheBlueMatt merged 5 commits into
lightningdevkit:masterfrom
ariard:2019-07-data_loss
Aug 6, 2019
Merged

TheBlueMatt merged 5 commits into
lightningdevkit:masterfrom
ariard:2019-07-data_loss

Conversation

@ariard

@ariard ariard commented Jul 10, 2019 •

Copy link
Copy Markdown

Data Loss Protection could be a bit tricky to get right, as your_last_per_commitment_secret is there to let remote peer prove to you it knows at least a revocation at next_remote_commitment_number - 1 but it can lie by omission.

It's a simpler version than #244 I expect but we may pick tests from there, we want to verify:

  • we don't broadcast our Local Commitment Tx in case of fallen behind
  • we are able to claim our own outputs thanks to remote my_current_per_commitment_point
  • we close channel in case of Bob cheating with erroneous last_per_commitment_secret

Comment thread src/ln/msgs.rs Resolved
Comment thread src/ln/channel.rs Resolved
Comment thread src/ln/channel.rs
log_debug!(self, "We don't seen yet any revoked secret, if this channnel has already been updated it means we are fallen-behind, you should wait for other peer closing");
OptionalField::Present(DataLossProtect {
your_last_per_commitment_secret: [0;32],
my_current_per_commitment_point: PublicKey::from_secret_key(&self.secp_ctx, &self.build_local_commitment_secret(self.cur_local_commitment_transaction_number))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Hmm, have you tested this against a live c-lightning+lnd node?

Comment thread src/ln/channel.rs Resolved
Comment thread src/ln/channel.rs Outdated
}
if INITIAL_COMMITMENT_NUMBER - msg.next_remote_commitment_number < self.cur_local_commitment_transaction_number {
self.channel_monitor.provide_latest_remote_commitment_tx_info(&Transaction { version: 2, lock_time: 0, input: Vec::new(), output: Vec::new(), }, Vec::new(), INITIAL_COMMITMENT_NUMBER - msg.next_remote_commitment_number, data_loss.my_current_per_commitment_point);
return Err(ChannelError::Stale { msg: "FALLEN-BEHIND: we need to stale this channel and wait than our up-to-date non-malicious peer broadcast its own commitment transaction on chain", update: Some(self.channel_monitor.clone())

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

"stale" is not a verb. Maybe "We have fallen behind - we need to close the channel and give our peer some time to (hopefully) broadcast the latest commitment transaction is has, but should give up at some point and broadcast our own."
Also, I don't think we need to capitalize FALLEN-BEHIND, I don't think there's anything else like that in the codebase.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Corrected, but there is not that much place in our codebase where we learn something is completely wrong and user should be careful.

Comment thread src/ln/channel.rs Resolved
Comment thread src/ln/channelmanager.rs Outdated
Err(ChannelError::Stale { msg, update}) => {
if let Some(update) = update {
if let Err(_e) = $self.monitor.add_update_monitor(update.get_funding_txo().unwrap(), update) {
unimplemented!();

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Ugh, please don't add more unimplemented!()s in monitor updating. If nothing else this almost certainly results in the chanmon_fail_consistency fuzzer failing.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Ok, replace by a panic the break_chan_entry as it should never be taken. If permanent failure, IMO we can close the channel as we have no more any monitors to watch the chain for us..

Comment thread src/ln/channelmanager.rs Resolved
Comment thread src/ln/channelmanager.rs Outdated
},
ChannelError::Stale { msg, .. } => HandleError {
err: msg,
action: Some(msgs::ErrorAction::IgnoreError),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Huh? Shouldn't this return an error message to tell the peer to close on us?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Corrected after talks on should we disclose our failures or not to our remote peer

Comment thread src/ln/channelmanager.rs Outdated
}
}
log_error!($self, "Channel {} need to stale due to {}", log_bytes!($entry.key()[..]), msg);
break Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Stale { msg, update: None }, $entry.key().clone()))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Huh? Shouldn't the channel get removed? Right now it just continues like its no problem?

@ariard ariard Jul 30, 2019 •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Panic now on this branch which should never be taken

In case of sending channel_reestablish message, we join
our current per_commitment_point and their highest revocation
secret we know about

We set data_loss_protect by default and adjust encoding_init
test in consequence
@ariard

ariard commented Jul 30, 2019 •

Copy link
Copy Markdown
Author

Should I have corrected everything at 055a359 minus live tests todo

@codecov

codecov Bot commented Jul 30, 2019 •

Copy link
Copy Markdown

Codecov Report

Merging #349 into master will increase coverage by 0.04%.
The diff coverage is 87.97%.

Impacted file tree graph

@@            Coverage Diff             @@
##           master     #349      +/-   ##
==========================================
+ Coverage   87.34%   87.39%   +0.04%     
==========================================
  Files          29       29              
  Lines       15605    15751     +146     
==========================================
+ Hits        13630    13765     +135     
- Misses       1975     1986      +11
Impacted Files Coverage Δ
src/ln/peer_handler.rs 31.81% <ø> (ø) ⬆️
src/ln/channelmanager.rs 81.22% <0%> (-0.1%) ⬇️
src/ln/msgs.rs 82.37% <100%> (+0.53%) ⬆️
src/ln/channel.rs 84.37% <70.83%> (-0.12%) ⬇️
src/ln/functional_tests.rs 96.32% <94.87%> (-0.06%) ⬇️
src/ln/channelmonitor.rs 85.35% <95.74%> (+0.2%) ⬆️
... and 1 more

Continue to review full report at Codecov.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 127ce29...41def65. Read the comment docs.

@TheBlueMatt TheBlueMatt left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Didn't get to the last two commits, just theory of how this should work first.

Comment thread src/ln/channel.rs Resolved
Comment thread src/ln/channel.rs Resolved
Comment thread src/ln/channelmanager.rs Resolved
Comment thread src/ln/channelmanager.rs Outdated
}
}
}
chan.force_shutdown();

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Hmmmmmm....what to do with this result is...pretty unclear. We can't just blindly drop the HTLCs we may need to fail back, but probably shouldn't immediately fail them back. Any ideas?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Assuming we have lost data to reconstruct offered HTLC script, it's lost money anyway given we can't timeout them so best it to avoid break backward channel (if state is correct for this one, which is also unlikely, I don't see doing backup per-channel granularity). See https://github.com/lightningnetwork/lightning-rfc/blob/master/05-onchain.md#rationale-4.
Yes best seem to fail HTLCs backward ?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Add 16c285f for what we were talking yesterday

Comment thread src/ln/channelmanager.rs Outdated
// to watchtowers to retrieve our funds from remote commitment transaction.
// We close channnel as there is no hope to get back something..
ChannelMonitorUpdateErr::PermanentFailure => {
return Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I dont think you should handle the force_shutdown result differently here?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Okay because we may still use our fresh in-memory ChannelMonitor with remote per_commitment_point to get back the to_remote output ?

@TheBlueMatt TheBlueMatt added this to the 0.0.10 milestone Aug 1, 2019

@TheBlueMatt TheBlueMatt left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

ACK otherwise.

Comment thread src/ln/channelmanager.rs Outdated
for htlc_source in failed_htlcs.drain(..) {
$self.fail_htlc_backwards_internal($self.channel_state.lock().unwrap(), htlc_source.0, &htlc_source.1, HTLCFailReason::Reason { failure_code: 0x4000 | 8, data: Vec::new() });
}
return Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::CloseDelayBroadcast { msg, update: None }, channel_id))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Hmm, wouldn't it be a little more DRY to just do a let mut shutdown_res = chan.force_shutdown(); shutdown_res.0.clear(); and then return a from_finish_shutdown() here? Means we don't have the failure code duplicated everywhere, and also would generate the appropriate channel announcement which you're missing here.

Comment thread src/ln/channel.rs Outdated
}
if msg.next_remote_commitment_number > INITIAL_COMMITMENT_NUMBER - self.cur_local_commitment_transaction_number {
self.channel_monitor.provide_rescue_remote_commitment_tx_info(INITIAL_COMMITMENT_NUMBER - msg.next_remote_commitment_number, data_loss.my_current_per_commitment_point);
return Err(ChannelError::CloseDelayBroadcast { msg: "We have fallen behind - we need to close the channel and give our peer some time to (hopefully) broadcast the latest commitment transaction is has, but should give up at some point and broadcast our own", update: Some(self.channel_monitor.clone())

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

nit: text out of date - need to note that we have received proof that if we announce they'll steal our money - we can't do any automated announcements, period.

@ariard

ariard commented Aug 2, 2019

Copy link
Copy Markdown
Author

Incorporated suggested changes at 01142a3, biggest diff should be updating test in consequence

@TheBlueMatt TheBlueMatt left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Oops, a few obvious ones left in the monitor changes.

Comment thread src/ln/channelmonitor.rs Outdated
// already processed the block, resulting in the remote_commitment_txn_on_chain entry
// not being generated by the above conditional. Thus, to be safe, we go ahead and
// insert it here.
watch_outputs.append(&mut tx.output.clone());

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Huh? Now we just watch everything? This still needs to be filtered.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Yes right we don't care to watch how to_remote output is spent and others outputs only if they are htlcs on remote valid commitment transaction. Moved it beyond Some(per_commitment_data) = per_commitment_option branch

Comment thread src/ln/channelmonitor.rs Outdated
if outp.script_pubkey.is_v0_p2wpkh() {
match self.key_storage {
Storage::Local { ref payment_base_key, .. } => {
if let Ok(local_key) = chan_utils::derive_private_key(&self.secp_ctx, &revocation_point, &payment_base_key) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I dont think we want to do crypto operations in a loop over every output in every tx in a block that matched. Not entirely your fault, but this used to be in the match for it being definitely a commitment tx.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Yes I know, that's why I've added another filter in block_connected based on nSequence. I've improved it, it should only match commitment txn with the lightning pattern (0x20 in nlocktime, 0x80 in nSequence). Could this be a DoS vector for watchtower ? Can we do better than just saying "we want to match this commitment transaction with the given output" ? Cache the script?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Ok cached the script and strained filters.

@TheBlueMatt TheBlueMatt left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Nice! Latest changes are much easier to review :). One note, then I promise I'll merge :p.

Comment thread src/ln/channelmonitor.rs Outdated
}

pub(super) fn provide_rescue_remote_commitment_tx_info(&mut self, commitment_number: u64, their_revocation_point: PublicKey) {
self.their_cur_revocation_points = Some((commitment_number, their_revocation_point, None));

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Hmm, this seems redundant now (and easier to remove this than worry about whether its right in every case, no :p).

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Derive private key at this point too, diff should be even smaller in check_spend_remote :)

Comment thread src/ln/channelmonitor.rs Resolved
Antoine Riard added 4 commits August 5, 2019 15:47
If we remote peer provide us a revocation secret which doesn't
match with next_remote_revocation_number we close the channel
If we learn that we are fallen-behind, we send back a CloseDelayBroadcast
error, special take care will be take to log error and channel should
stale, i.e we expect our honest peer to unilateral close to claim
on it our balance

Add ChannelError::CloseDelayBroadcast to signal that you need to close
the channel but not to broadcast it while however update ChannelMonitor
with remote per_commitment_point thanks to our peer being a gentleman
You may use it to get a broadcastable local toxic tx in case of fallen-behind,
i.e when receiving a channel_reestablish with a proof that our remote side
knows a higher revocation secret than the local commitment number we are aware
of. Broadcasting these transactions are UNSAFE, as they allow remote side to punish
you. Nevertheless you may want to broadcast them if remote don't close channel with his
higher commitment transaction after a substantial amount of time (a month or even a year)
to get back funds. Best may be to contact out-of-band the other node operator to coordinate
with him if option is available to you. In any-case, choice is up to the user.

Also, log toxic commitment tx id in channel_reestablish sending back
ChannelError::CloseDelayBroadcast
Also, restrict commitment transaction filters in ChannelMonitor::
block_connected
@TheBlueMatt
TheBlueMatt merged commit 56f16ea into lightningdevkit:master Aug 6, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants