Skip to content

Commit 60e0ab1

Browse files
authored
Merge pull request #152 from TheBlueMatt/2018-09-chan-cleanups
Channel cleanups
2 parents 2a93f98 + 3f5f3de commit 60e0ab1

File tree

2 files changed

+36
-45
lines changed

2 files changed

+36
-45
lines changed

src/ln/channel.rs

Lines changed: 28 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -138,18 +138,16 @@ enum HTLCState {
138138
AwaitingRemovedRemoteRevoke,
139139
/// Removed by us and a new commitment_signed was sent (if we were AwaitingRemoteRevoke when we
140140
/// created it we would have put it in the holding cell instead). When they next revoke_and_ack
141-
/// we'll promote to LocalRemovedAwaitingCommitment if we fulfilled, otherwise we'll drop at
142-
/// that point.
141+
/// we'll drop it.
143142
/// Note that we have to keep an eye on the HTLC until we've received a broadcastable
144143
/// commitment transaction without it as otherwise we'll have to force-close the channel to
145144
/// claim it before the timeout (obviously doesn't apply to revoked HTLCs that we can't claim
146-
/// anyway).
145+
/// anyway). That said, ChannelMonitor does this for us (see
146+
/// ChannelMonitor::would_broadcast_at_height) so we actually remove the HTLC from our own
147+
/// local state before then, once we're sure that the next commitment_signed and
148+
/// ChannelMonitor::provide_latest_local_commitment_tx_info will not include this HTLC.
147149
/// Implies HTLCOutput::outbound: false
148150
LocalRemoved,
149-
/// Removed by us, sent a new commitment_signed and got a revoke_and_ack. Just waiting on an
150-
/// updated local commitment transaction. Implies local_removed_fulfilled.
151-
/// Implies HTLCOutput::outbound: false
152-
LocalRemovedAwaitingCommitment,
153151
}
154152

155153
struct HTLCOutput { //TODO: Refactor into Outbound/InboundHTLCOutput (will save memory and fewer panics)
@@ -338,18 +336,17 @@ const B_OUTPUT_PLUS_SPENDING_INPUT_WEIGHT: u64 = 104; // prevout: 40, nSequence:
338336
pub const MAX_FUNDING_SATOSHIS: u64 = (1 << 24);
339337

340338
macro_rules! secp_call {
341-
( $res: expr, $err: expr ) => {
339+
( $res: expr, $err: expr, $chan_id: expr ) => {
342340
match $res {
343341
Ok(key) => key,
344-
//TODO: make the error a parameter
345-
Err(_) => return Err(HandleError{err: $err, action: Some(msgs::ErrorAction::DisconnectPeer{ msg: None })})
342+
Err(_) => return Err(HandleError {err: $err, action: Some(msgs::ErrorAction::SendErrorMessage {msg: msgs::ErrorMessage {channel_id: $chan_id, data: $err.to_string()}})})
346343
}
347344
};
348345
}
349346

350347
macro_rules! secp_derived_key {
351-
( $res: expr ) => {
352-
secp_call!($res, "Derived invalid key, peer is maliciously selecting parameters")
348+
( $res: expr, $chan_id: expr ) => {
349+
secp_call!($res, "Derived invalid key, peer is maliciously selecting parameters", $chan_id)
353350
}
354351
}
355352
impl Channel {
@@ -707,7 +704,6 @@ impl Channel {
707704
HTLCState::AwaitingRemoteRevokeToRemove => generated_by_local,
708705
HTLCState::AwaitingRemovedRemoteRevoke => false,
709706
HTLCState::LocalRemoved => !generated_by_local,
710-
HTLCState::LocalRemovedAwaitingCommitment => false,
711707
};
712708

713709
if include {
@@ -750,10 +746,6 @@ impl Channel {
750746
value_to_self_msat_offset += htlc.amount_msat as i64;
751747
}
752748
},
753-
HTLCState::LocalRemovedAwaitingCommitment => {
754-
assert!(htlc.local_removed_fulfilled);
755-
value_to_self_msat_offset += htlc.amount_msat as i64;
756-
},
757749
_ => {},
758750
}
759751
}
@@ -883,7 +875,7 @@ impl Channel {
883875
let delayed_payment_base = PublicKey::from_secret_key(&self.secp_ctx, &self.local_keys.delayed_payment_base_key);
884876
let htlc_basepoint = PublicKey::from_secret_key(&self.secp_ctx, &self.local_keys.htlc_base_key);
885877

886-
Ok(secp_derived_key!(TxCreationKeys::new(&self.secp_ctx, &per_commitment_point, &delayed_payment_base, &htlc_basepoint, &self.their_revocation_basepoint.unwrap(), &self.their_payment_basepoint.unwrap(), &self.their_htlc_basepoint.unwrap())))
878+
Ok(secp_derived_key!(TxCreationKeys::new(&self.secp_ctx, &per_commitment_point, &delayed_payment_base, &htlc_basepoint, &self.their_revocation_basepoint.unwrap(), &self.their_payment_basepoint.unwrap(), &self.their_htlc_basepoint.unwrap()), self.channel_id()))
887879
}
888880

889881
#[inline]
@@ -896,7 +888,7 @@ impl Channel {
896888
let revocation_basepoint = PublicKey::from_secret_key(&self.secp_ctx, &self.local_keys.revocation_base_key);
897889
let htlc_basepoint = PublicKey::from_secret_key(&self.secp_ctx, &self.local_keys.htlc_base_key);
898890

899-
Ok(secp_derived_key!(TxCreationKeys::new(&self.secp_ctx, &self.their_cur_commitment_point.unwrap(), &self.their_delayed_payment_basepoint.unwrap(), &self.their_htlc_basepoint.unwrap(), &revocation_basepoint, &payment_basepoint, &htlc_basepoint)))
891+
Ok(secp_derived_key!(TxCreationKeys::new(&self.secp_ctx, &self.their_cur_commitment_point.unwrap(), &self.their_delayed_payment_basepoint.unwrap(), &self.their_htlc_basepoint.unwrap(), &revocation_basepoint, &payment_basepoint, &htlc_basepoint), self.channel_id()))
900892
}
901893

902894
/// Gets the redeemscript for the funding transaction output (ie the funding transaction output
@@ -960,7 +952,7 @@ impl Channel {
960952

961953
let htlc_redeemscript = chan_utils::get_htlc_redeemscript(&htlc, &keys);
962954

963-
let our_htlc_key = secp_derived_key!(chan_utils::derive_private_key(&self.secp_ctx, &keys.per_commitment_point, &self.local_keys.htlc_base_key));
955+
let our_htlc_key = secp_derived_key!(chan_utils::derive_private_key(&self.secp_ctx, &keys.per_commitment_point, &self.local_keys.htlc_base_key), self.channel_id());
964956
let sighash = Message::from_slice(&bip143::SighashComponents::new(&tx).sighash_all(&tx.input[0], &htlc_redeemscript, htlc.amount_msat / 1000)[..]).unwrap();
965957
let is_local_tx = PublicKey::from_secret_key(&self.secp_ctx, &our_htlc_key) == keys.a_htlc_key;
966958
Ok((htlc_redeemscript, self.secp_ctx.sign(&sighash, &our_htlc_key), is_local_tx))
@@ -1019,7 +1011,7 @@ impl Channel {
10191011
let mut pending_idx = std::usize::MAX;
10201012
for (idx, htlc) in self.pending_htlcs.iter().enumerate() {
10211013
if !htlc.outbound && htlc.payment_hash == payment_hash_calc &&
1022-
htlc.state != HTLCState::LocalRemoved && htlc.state != HTLCState::LocalRemovedAwaitingCommitment {
1014+
htlc.state != HTLCState::LocalRemoved {
10231015
if let Some(PendingHTLCStatus::Fail(_)) = htlc.pending_forward_state {
10241016
} else {
10251017
if pending_idx != std::usize::MAX {
@@ -1144,7 +1136,7 @@ impl Channel {
11441136
// we'll fail this one as soon as remote commits to it.
11451137
continue;
11461138
}
1147-
} else if htlc.state == HTLCState::LocalRemoved || htlc.state == HTLCState::LocalRemovedAwaitingCommitment {
1139+
} else if htlc.state == HTLCState::LocalRemoved {
11481140
return Err(HandleError{err: "Unable to find a pending HTLC which matched the given payment preimage", action: None});
11491141
} else {
11501142
panic!("Have an inbound HTLC when not awaiting remote revoke that had a garbage state");
@@ -1268,7 +1260,7 @@ impl Channel {
12681260
let local_sighash = Message::from_slice(&bip143::SighashComponents::new(&local_initial_commitment_tx).sighash_all(&local_initial_commitment_tx.input[0], &funding_script, self.channel_value_satoshis)[..]).unwrap();
12691261

12701262
// They sign the "local" commitment transaction, allowing us to broadcast the tx if we wish.
1271-
secp_call!(self.secp_ctx.verify(&local_sighash, &sig, &self.their_funding_pubkey.unwrap()), "Invalid funding_created signature from peer");
1263+
secp_call!(self.secp_ctx.verify(&local_sighash, &sig, &self.their_funding_pubkey.unwrap()), "Invalid funding_created signature from peer", self.channel_id());
12721264

12731265
// We sign the "remote" commitment transaction, allowing them to broadcast the tx if they wish.
12741266
Ok((remote_initial_commitment_tx, self.secp_ctx.sign(&remote_sighash, &self.local_keys.funding_key)))
@@ -1331,7 +1323,7 @@ impl Channel {
13311323
let local_sighash = Message::from_slice(&bip143::SighashComponents::new(&local_initial_commitment_tx).sighash_all(&local_initial_commitment_tx.input[0], &funding_script, self.channel_value_satoshis)[..]).unwrap();
13321324

13331325
// They sign the "local" commitment transaction, allowing us to broadcast the tx if we wish.
1334-
secp_call!(self.secp_ctx.verify(&local_sighash, &msg.signature, &self.their_funding_pubkey.unwrap()), "Invalid funding_signed signature from peer");
1326+
secp_call!(self.secp_ctx.verify(&local_sighash, &msg.signature, &self.their_funding_pubkey.unwrap()), "Invalid funding_signed signature from peer", self.channel_id());
13351327

13361328
self.sign_commitment_transaction(&mut local_initial_commitment_tx, &msg.signature);
13371329
self.channel_monitor.provide_latest_local_commitment_tx_info(local_initial_commitment_tx.clone(), local_keys, self.feerate_per_kw, Vec::new());
@@ -1380,7 +1372,6 @@ impl Channel {
13801372
HTLCState::AwaitingRemoteRevokeToRemove => { if for_remote_update_check { continue; } },
13811373
HTLCState::AwaitingRemovedRemoteRevoke => { if for_remote_update_check { continue; } },
13821374
HTLCState::LocalRemoved => {},
1383-
HTLCState::LocalRemovedAwaitingCommitment => { if for_remote_update_check { continue; } },
13841375
}
13851376
if !htlc.outbound {
13861377
inbound_htlc_count += 1;
@@ -1515,7 +1506,7 @@ impl Channel {
15151506
let mut local_commitment_tx = self.build_commitment_transaction(self.cur_local_commitment_transaction_number, &local_keys, true, false);
15161507
let local_commitment_txid = local_commitment_tx.0.txid();
15171508
let local_sighash = Message::from_slice(&bip143::SighashComponents::new(&local_commitment_tx.0).sighash_all(&local_commitment_tx.0.input[0], &funding_script, self.channel_value_satoshis)[..]).unwrap();
1518-
secp_call!(self.secp_ctx.verify(&local_sighash, &msg.signature, &self.their_funding_pubkey.unwrap()), "Invalid commitment tx signature from peer");
1509+
secp_call!(self.secp_ctx.verify(&local_sighash, &msg.signature, &self.their_funding_pubkey.unwrap()), "Invalid commitment tx signature from peer", self.channel_id());
15191510

15201511
if msg.htlc_signatures.len() != local_commitment_tx.1.len() {
15211512
return Err(HandleError{err: "Got wrong number of HTLC signatures from remote", action: None});
@@ -1530,7 +1521,7 @@ impl Channel {
15301521
let mut htlc_tx = self.build_htlc_transaction(&local_commitment_txid, htlc, true, &local_keys);
15311522
let htlc_redeemscript = chan_utils::get_htlc_redeemscript(&htlc, &local_keys);
15321523
let htlc_sighash = Message::from_slice(&bip143::SighashComponents::new(&htlc_tx).sighash_all(&htlc_tx.input[0], &htlc_redeemscript, htlc.amount_msat / 1000)[..]).unwrap();
1533-
secp_call!(self.secp_ctx.verify(&htlc_sighash, &msg.htlc_signatures[idx], &local_keys.b_htlc_key), "Invalid HTLC tx siganture from peer");
1524+
secp_call!(self.secp_ctx.verify(&htlc_sighash, &msg.htlc_signatures[idx], &local_keys.b_htlc_key), "Invalid HTLC tx siganture from peer", self.channel_id());
15341525
let htlc_sig = if htlc.offered {
15351526
let htlc_sig = self.sign_htlc_transaction(&mut htlc_tx, &msg.htlc_signatures[idx], &None, htlc, &local_keys)?;
15361527
new_local_commitment_txn.push(htlc_tx);
@@ -1557,16 +1548,6 @@ impl Channel {
15571548
need_our_commitment = true;
15581549
}
15591550
}
1560-
// Finally delete all the LocalRemovedAwaitingCommitment HTLCs
1561-
// We really shouldnt have two passes here, but retain gives a non-mutable ref (Rust bug)
1562-
let mut claimed_value_msat = 0;
1563-
self.pending_htlcs.retain(|htlc| {
1564-
if htlc.state == HTLCState::LocalRemovedAwaitingCommitment {
1565-
claimed_value_msat += htlc.amount_msat;
1566-
false
1567-
} else { true }
1568-
});
1569-
self.value_to_self_msat += claimed_value_msat;
15701551

15711552
self.cur_local_commitment_transaction_number -= 1;
15721553
self.last_local_commitment_txn = new_local_commitment_txn;
@@ -1666,7 +1647,7 @@ impl Channel {
16661647
return Err(HandleError{err: "Got revoke/ACK message when channel was not in an operational state", action: None});
16671648
}
16681649
if let Some(their_prev_commitment_point) = self.their_prev_commitment_point {
1669-
if PublicKey::from_secret_key(&self.secp_ctx, &secp_call!(SecretKey::from_slice(&self.secp_ctx, &msg.per_commitment_secret), "Peer provided an invalid per_commitment_secret")) != their_prev_commitment_point {
1650+
if PublicKey::from_secret_key(&self.secp_ctx, &secp_call!(SecretKey::from_slice(&self.secp_ctx, &msg.per_commitment_secret), "Peer provided an invalid per_commitment_secret", self.channel_id())) != their_prev_commitment_point {
16701651
return Err(HandleError{err: "Got a revoke commitment secret which didn't correspond to their current pubkey", action: None});
16711652
}
16721653
}
@@ -1690,7 +1671,10 @@ impl Channel {
16901671
// We really shouldnt have two passes here, but retain gives a non-mutable ref (Rust bug)
16911672
self.pending_htlcs.retain(|htlc| {
16921673
if htlc.state == HTLCState::LocalRemoved {
1693-
if htlc.local_removed_fulfilled { true } else { false }
1674+
if htlc.local_removed_fulfilled {
1675+
value_to_self_msat_diff += htlc.amount_msat as i64;
1676+
}
1677+
false
16941678
} else if htlc.state == HTLCState::AwaitingRemovedRemoteRevoke {
16951679
if let Some(reason) = htlc.fail_reason.clone() { // We really want take() here, but, again, non-mut ref :(
16961680
revoked_htlcs.push((htlc.payment_hash, reason));
@@ -1725,9 +1709,6 @@ impl Channel {
17251709
} else if htlc.state == HTLCState::AwaitingRemoteRevokeToRemove {
17261710
htlc.state = HTLCState::AwaitingRemovedRemoteRevoke;
17271711
require_commitment = true;
1728-
} else if htlc.state == HTLCState::LocalRemoved {
1729-
assert!(htlc.local_removed_fulfilled);
1730-
htlc.state = HTLCState::LocalRemovedAwaitingCommitment;
17311712
}
17321713
}
17331714
self.value_to_self_msat = (self.value_to_self_msat as i64 + value_to_self_msat_diff) as u64;
@@ -1893,7 +1874,7 @@ impl Channel {
18931874
// limits, so check for that case by re-checking the signature here.
18941875
closing_tx = self.build_closing_transaction(msg.fee_satoshis, true).0;
18951876
sighash = Message::from_slice(&bip143::SighashComponents::new(&closing_tx).sighash_all(&closing_tx.input[0], &funding_redeemscript, self.channel_value_satoshis)[..]).unwrap();
1896-
secp_call!(self.secp_ctx.verify(&sighash, &msg.signature, &self.their_funding_pubkey.unwrap()), "Invalid closing tx signature from peer");
1877+
secp_call!(self.secp_ctx.verify(&sighash, &msg.signature, &self.their_funding_pubkey.unwrap()), "Invalid closing tx signature from peer", self.channel_id());
18971878
},
18981879
};
18991880

@@ -2335,6 +2316,7 @@ impl Channel {
23352316
/// This returns an option instead of a pure UpdateAddHTLC as we may be in a state where we are
23362317
/// waiting on the remote peer to send us a revoke_and_ack during which time we cannot add new
23372318
/// HTLCs on the wire or we wouldn't be able to determine what they actually ACK'ed.
2319+
/// You MUST call send_commitment prior to any other calls on this Channel
23382320
pub fn send_htlc(&mut self, amount_msat: u64, payment_hash: [u8; 32], cltv_expiry: u32, onion_routing_packet: msgs::OnionPacket) -> Result<Option<msgs::UpdateAddHTLC>, HandleError> {
23392321
if (self.channel_state & (ChannelState::ChannelFunded as u32 | BOTH_SIDES_SHUTDOWN_MASK)) != (ChannelState::ChannelFunded as u32) {
23402322
return Err(HandleError{err: "Cannot send HTLC until channel is fully established and we haven't started shutting down", action: None});
@@ -2402,6 +2384,8 @@ impl Channel {
24022384
}
24032385

24042386
/// Creates a signed commitment transaction to send to the remote peer.
2387+
/// Always returns a Channel-failing HandleError::action if an immediately-preceding (read: the
2388+
/// last call to this Channel) send_htlc returned Ok(Some(_)) and there is an Err.
24052389
pub fn send_commitment(&mut self) -> Result<(msgs::CommitmentSigned, ChannelMonitor), HandleError> {
24062390
if (self.channel_state & (ChannelState::ChannelFunded as u32)) != (ChannelState::ChannelFunded as u32) {
24072391
return Err(HandleError{err: "Cannot create commitment tx until channel is fully established", action: None});
@@ -2448,7 +2432,7 @@ impl Channel {
24482432
let htlc_tx = self.build_htlc_transaction(&remote_commitment_txid, htlc, false, &remote_keys);
24492433
let htlc_redeemscript = chan_utils::get_htlc_redeemscript(&htlc, &remote_keys);
24502434
let htlc_sighash = Message::from_slice(&bip143::SighashComponents::new(&htlc_tx).sighash_all(&htlc_tx.input[0], &htlc_redeemscript, htlc.amount_msat / 1000)[..]).unwrap();
2451-
let our_htlc_key = secp_derived_key!(chan_utils::derive_private_key(&self.secp_ctx, &remote_keys.per_commitment_point, &self.local_keys.htlc_base_key));
2435+
let our_htlc_key = secp_derived_key!(chan_utils::derive_private_key(&self.secp_ctx, &remote_keys.per_commitment_point, &self.local_keys.htlc_base_key), self.channel_id());
24522436
htlc_sigs.push(self.secp_ctx.sign(&htlc_sighash, &our_htlc_key));
24532437
}
24542438

src/ln/channelmanager.rs

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -447,6 +447,8 @@ impl ChannelManager {
447447
//TODO: We need to handle monitoring of pending offered HTLCs which just hit the chain and
448448
//may be claimed, resulting in us claiming the inbound HTLCs (and back-failing after
449449
//timeouts are hit and our claims confirm).
450+
//TODO: In any case, we need to make sure we remove any pending htlc tracking (via
451+
//fail_backwards or claim_funds) eventually for all HTLCs that were in the channel
450452
}
451453

452454
/// Force closes a channel, immediately broadcasting the latest local commitment transaction to
@@ -1147,7 +1149,12 @@ impl ChannelManager {
11471149
if !add_htlc_msgs.is_empty() {
11481150
let (commitment_msg, monitor) = match forward_chan.send_commitment() {
11491151
Ok(res) => res,
1150-
Err(_e) => {
1152+
Err(e) => {
1153+
if let &Some(msgs::ErrorAction::DisconnectPeer{msg: Some(ref _err_msg)}) = &e.action {
1154+
} else if let &Some(msgs::ErrorAction::SendErrorMessage{msg: ref _err_msg}) = &e.action {
1155+
} else {
1156+
panic!("Stated return value requirements in send_commitment() were not met");
1157+
}
11511158
//TODO: Handle...this is bad!
11521159
continue;
11531160
},

0 commit comments

Comments
 (0)