X-Git-Url: http://git.bitcoin.ninja/index.cgi?a=blobdiff_plain;f=src%2Fln%2Fchannel.rs;h=ab8b3bcdf6cb0ca0bd8251ff8f474f939758df68;hb=90b545ffe3e6855e09156361ecb1d5384add1e46;hp=b2164696f25897c48536ec64692730a1a1eb1d38;hpb=1360fccd7143937278f880497634eb284da834ce;p=rust-lightning diff --git a/src/ln/channel.rs b/src/ln/channel.rs index b2164696..ab8b3bcd 100644 --- a/src/ln/channel.rs +++ b/src/ln/channel.rs @@ -16,14 +16,14 @@ use crypto::hkdf::{hkdf_extract,hkdf_expand}; use ln::msgs; use ln::msgs::{ErrorAction, HandleError, MsgEncodable}; use ln::channelmonitor::ChannelMonitor; -use ln::channelmanager::{PendingForwardHTLCInfo, HTLCFailReason}; +use ln::channelmanager::{PendingHTLCStatus, PendingForwardHTLCInfo, HTLCFailReason, HTLCFailureMsg}; use ln::chan_utils::{TxCreationKeys,HTLCOutputInCommitment,HTLC_SUCCESS_TX_WEIGHT,HTLC_TIMEOUT_TX_WEIGHT}; use ln::chan_utils; use chain::chaininterface::{FeeEstimator,ConfirmationTarget}; use chain::transaction::OutPoint; use util::{transaction_utils,rng}; use util::sha2::Sha256; -use util::logger::{Logger, Record}; +use util::logger::Logger; use util::errors::APIError; use std; @@ -138,18 +138,16 @@ enum HTLCState { AwaitingRemovedRemoteRevoke, /// Removed by us and a new commitment_signed was sent (if we were AwaitingRemoteRevoke when we /// created it we would have put it in the holding cell instead). When they next revoke_and_ack - /// we'll promote to LocalRemovedAwaitingCommitment if we fulfilled, otherwise we'll drop at - /// that point. + /// we'll drop it. /// Note that we have to keep an eye on the HTLC until we've received a broadcastable /// commitment transaction without it as otherwise we'll have to force-close the channel to /// claim it before the timeout (obviously doesn't apply to revoked HTLCs that we can't claim - /// anyway). + /// anyway). That said, ChannelMonitor does this for us (see + /// ChannelMonitor::would_broadcast_at_height) so we actually remove the HTLC from our own + /// local state before then, once we're sure that the next commitment_signed and + /// ChannelMonitor::provide_latest_local_commitment_tx_info will not include this HTLC. /// Implies HTLCOutput::outbound: false LocalRemoved, - /// Removed by us, sent a new commitment_signed and got a revoke_and_ack. Just waiting on an - /// updated local commitment transaction. Implies local_removed_fulfilled. - /// Implies HTLCOutput::outbound: false - LocalRemovedAwaitingCommitment, } struct HTLCOutput { //TODO: Refactor into Outbound/InboundHTLCOutput (will save memory and fewer panics) @@ -164,7 +162,7 @@ struct HTLCOutput { //TODO: Refactor into Outbound/InboundHTLCOutput (will save /// If we're in LocalRemoved*, set to true if we fulfilled the HTLC, and can claim money local_removed_fulfilled: bool, /// state pre-committed Remote* implies pending_forward_state, otherwise it must be None - pending_forward_state: Option, + pending_forward_state: Option, } impl HTLCOutput { @@ -251,7 +249,7 @@ pub struct Channel { channel_id: [u8; 32], channel_state: u32, channel_outbound: bool, - secp_ctx: Secp256k1, + secp_ctx: Secp256k1, announce_publicly: bool, channel_value_satoshis: u64, @@ -302,12 +300,12 @@ pub struct Channel { their_max_accepted_htlcs: u16, //implied by OUR_MAX_HTLCS: our_max_accepted_htlcs: u16, - their_funding_pubkey: PublicKey, - their_revocation_basepoint: PublicKey, - their_payment_basepoint: PublicKey, - their_delayed_payment_basepoint: PublicKey, - their_htlc_basepoint: PublicKey, - their_cur_commitment_point: PublicKey, + their_funding_pubkey: Option, + their_revocation_basepoint: Option, + their_payment_basepoint: Option, + their_delayed_payment_basepoint: Option, + their_htlc_basepoint: Option, + their_cur_commitment_point: Option, their_prev_commitment_point: Option, their_node_id: PublicKey, @@ -338,18 +336,17 @@ const B_OUTPUT_PLUS_SPENDING_INPUT_WEIGHT: u64 = 104; // prevout: 40, nSequence: pub const MAX_FUNDING_SATOSHIS: u64 = (1 << 24); macro_rules! secp_call { - ( $res: expr, $err: expr ) => { + ( $res: expr, $err: expr, $chan_id: expr ) => { match $res { Ok(key) => key, - //TODO: make the error a parameter - Err(_) => return Err(HandleError{err: $err, action: Some(msgs::ErrorAction::DisconnectPeer{ msg: None })}) + Err(_) => return Err(HandleError {err: $err, action: Some(msgs::ErrorAction::SendErrorMessage {msg: msgs::ErrorMessage {channel_id: $chan_id, data: $err.to_string()}})}) } }; } macro_rules! secp_derived_key { - ( $res: expr ) => { - secp_call!($res, "Derived invalid key, peer is maliciously selecting parameters") + ( $res: expr, $chan_id: expr ) => { + secp_call!($res, "Derived invalid key, peer is maliciously selecting parameters", $chan_id) } } impl Channel { @@ -373,6 +370,8 @@ impl Channel { } fn derive_minimum_depth(_channel_value_satoshis_msat: u64, _value_to_self_msat: u64) -> u32 { + // Note that in order to comply with BOLT 7 announcement_signatures requirements this must + // be at least 6. const CONF_TARGET: u32 = 12; //TODO: Should be much higher CONF_TARGET } @@ -401,10 +400,10 @@ impl Channel { let feerate = fee_estimator.get_est_sat_per_1000_weight(ConfirmationTarget::Normal); let secp_ctx = Secp256k1::new(); - let our_channel_monitor_claim_key_hash = Hash160::from_data(&PublicKey::from_secret_key(&secp_ctx, &chan_keys.channel_monitor_claim_key).unwrap().serialize()); + let our_channel_monitor_claim_key_hash = Hash160::from_data(&PublicKey::from_secret_key(&secp_ctx, &chan_keys.channel_monitor_claim_key).serialize()); let our_channel_monitor_claim_script = Builder::new().push_opcode(opcodes::All::OP_PUSHBYTES_0).push_slice(&our_channel_monitor_claim_key_hash[..]).into_script(); let channel_monitor = ChannelMonitor::new(&chan_keys.revocation_base_key, - &PublicKey::from_secret_key(&secp_ctx, &chan_keys.delayed_payment_base_key).unwrap(), + &PublicKey::from_secret_key(&secp_ctx, &chan_keys.delayed_payment_base_key), &chan_keys.htlc_base_key, BREAKDOWN_TIMEOUT, our_channel_monitor_claim_script); @@ -447,12 +446,12 @@ impl Channel { their_to_self_delay: 0, their_max_accepted_htlcs: 0, - their_funding_pubkey: PublicKey::new(), - their_revocation_basepoint: PublicKey::new(), - their_payment_basepoint: PublicKey::new(), - their_delayed_payment_basepoint: PublicKey::new(), - their_htlc_basepoint: PublicKey::new(), - their_cur_commitment_point: PublicKey::new(), + their_funding_pubkey: None, + their_revocation_basepoint: None, + their_payment_basepoint: None, + their_delayed_payment_basepoint: None, + their_htlc_basepoint: None, + their_cur_commitment_point: None, their_prev_commitment_point: None, their_node_id: their_node_id, @@ -523,10 +522,10 @@ impl Channel { let their_announce = if (msg.channel_flags & 1) == 1 { true } else { false }; if require_announce && !their_announce { - return Err(HandleError{err: "Peer tried to open unannounced channel, but we require public ones", action: Some(msgs::ErrorAction::IgnoreError) }); + return_error_message!("Peer tried to open unannounced channel, but we require public ones"); } if !allow_announce && their_announce { - return Err(HandleError{err: "Peer tried to open announced channel, but we require private ones", action: Some(msgs::ErrorAction::IgnoreError) }); + return_error_message!("Peer tried to open announced channel, but we require private ones"); } let background_feerate = fee_estimator.get_est_sat_per_1000_weight(ConfirmationTarget::Background); @@ -557,10 +556,10 @@ impl Channel { } let secp_ctx = Secp256k1::new(); - let our_channel_monitor_claim_key_hash = Hash160::from_data(&PublicKey::from_secret_key(&secp_ctx, &chan_keys.channel_monitor_claim_key).unwrap().serialize()); + let our_channel_monitor_claim_key_hash = Hash160::from_data(&PublicKey::from_secret_key(&secp_ctx, &chan_keys.channel_monitor_claim_key).serialize()); let our_channel_monitor_claim_script = Builder::new().push_opcode(opcodes::All::OP_PUSHBYTES_0).push_slice(&our_channel_monitor_claim_key_hash[..]).into_script(); let mut channel_monitor = ChannelMonitor::new(&chan_keys.revocation_base_key, - &PublicKey::from_secret_key(&secp_ctx, &chan_keys.delayed_payment_base_key).unwrap(), + &PublicKey::from_secret_key(&secp_ctx, &chan_keys.delayed_payment_base_key), &chan_keys.htlc_base_key, BREAKDOWN_TIMEOUT, our_channel_monitor_claim_script); channel_monitor.set_their_htlc_base_key(&msg.htlc_basepoint); @@ -605,12 +604,12 @@ impl Channel { their_to_self_delay: msg.to_self_delay, their_max_accepted_htlcs: msg.max_accepted_htlcs, - their_funding_pubkey: msg.funding_pubkey, - their_revocation_basepoint: msg.revocation_basepoint, - their_payment_basepoint: msg.payment_basepoint, - their_delayed_payment_basepoint: msg.delayed_payment_basepoint, - their_htlc_basepoint: msg.htlc_basepoint, - their_cur_commitment_point: msg.first_per_commitment_point, + their_funding_pubkey: Some(msg.funding_pubkey), + their_revocation_basepoint: Some(msg.revocation_basepoint), + their_payment_basepoint: Some(msg.payment_basepoint), + their_delayed_payment_basepoint: Some(msg.delayed_payment_basepoint), + their_htlc_basepoint: Some(msg.htlc_basepoint), + their_cur_commitment_point: Some(msg.first_per_commitment_point), their_prev_commitment_point: None, their_node_id: their_node_id, @@ -639,13 +638,13 @@ impl Channel { fn get_commitment_transaction_number_obscure_factor(&self) -> u64 { let mut sha = Sha256::new(); - let our_payment_basepoint = PublicKey::from_secret_key(&self.secp_ctx, &self.local_keys.payment_base_key).unwrap(); + let our_payment_basepoint = PublicKey::from_secret_key(&self.secp_ctx, &self.local_keys.payment_base_key); if self.channel_outbound { sha.input(&our_payment_basepoint.serialize()); - sha.input(&self.their_payment_basepoint.serialize()); + sha.input(&self.their_payment_basepoint.unwrap().serialize()); } else { - sha.input(&self.their_payment_basepoint.serialize()); + sha.input(&self.their_payment_basepoint.unwrap().serialize()); sha.input(&our_payment_basepoint.serialize()); } let mut res = [0; 32]; @@ -679,8 +678,7 @@ impl Channel { let txins = { let mut ins: Vec = Vec::new(); ins.push(TxIn { - prev_hash: self.channel_monitor.get_funding_txo().unwrap().txid, - prev_index: self.channel_monitor.get_funding_txo().unwrap().index as u32, + previous_output: self.channel_monitor.get_funding_txo().unwrap().into_bitcoin_outpoint(), script_sig: Script::new(), sequence: ((0x80 as u32) << 8*3) | ((obscured_commitment_transaction_number >> 3*8) as u32), witness: Vec::new(), @@ -706,7 +704,6 @@ impl Channel { HTLCState::AwaitingRemoteRevokeToRemove => generated_by_local, HTLCState::AwaitingRemovedRemoteRevoke => false, HTLCState::LocalRemoved => !generated_by_local, - HTLCState::LocalRemovedAwaitingCommitment => false, }; if include { @@ -749,10 +746,6 @@ impl Channel { value_to_self_msat_offset += htlc.amount_msat as i64; } }, - HTLCState::LocalRemovedAwaitingCommitment => { - assert!(htlc.local_removed_fulfilled); - value_to_self_msat_offset += htlc.amount_msat as i64; - }, _ => {}, } } @@ -805,7 +798,7 @@ impl Channel { #[inline] fn get_closing_scriptpubkey(&self) -> Script { - let our_channel_close_key_hash = Hash160::from_data(&PublicKey::from_secret_key(&self.secp_ctx, &self.local_keys.channel_close_key).unwrap().serialize()); + let our_channel_close_key_hash = Hash160::from_data(&PublicKey::from_secret_key(&self.secp_ctx, &self.local_keys.channel_close_key).serialize()); Builder::new().push_opcode(opcodes::All::OP_PUSHBYTES_0).push_slice(&our_channel_close_key_hash[..]).into_script() } @@ -819,8 +812,7 @@ impl Channel { let txins = { let mut ins: Vec = Vec::new(); ins.push(TxIn { - prev_hash: self.channel_monitor.get_funding_txo().unwrap().txid, - prev_index: self.channel_monitor.get_funding_txo().unwrap().index as u32, + previous_output: self.channel_monitor.get_funding_txo().unwrap().into_bitcoin_outpoint(), script_sig: Script::new(), sequence: 0xffffffff, witness: Vec::new(), @@ -879,11 +871,11 @@ impl Channel { /// The result is a transaction which we can revoke ownership of (ie a "local" transaction) /// TODO Some magic rust shit to compile-time check this? fn build_local_transaction_keys(&self, commitment_number: u64) -> Result { - let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &self.build_local_commitment_secret(commitment_number)).unwrap(); - let delayed_payment_base = PublicKey::from_secret_key(&self.secp_ctx, &self.local_keys.delayed_payment_base_key).unwrap(); - let htlc_basepoint = PublicKey::from_secret_key(&self.secp_ctx, &self.local_keys.htlc_base_key).unwrap(); + let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &self.build_local_commitment_secret(commitment_number)); + let delayed_payment_base = PublicKey::from_secret_key(&self.secp_ctx, &self.local_keys.delayed_payment_base_key); + let htlc_basepoint = PublicKey::from_secret_key(&self.secp_ctx, &self.local_keys.htlc_base_key); - Ok(secp_derived_key!(TxCreationKeys::new(&self.secp_ctx, &per_commitment_point, &delayed_payment_base, &htlc_basepoint, &self.their_revocation_basepoint, &self.their_payment_basepoint, &self.their_htlc_basepoint))) + 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())) } #[inline] @@ -892,19 +884,19 @@ impl Channel { fn build_remote_transaction_keys(&self) -> Result { //TODO: Ensure that the payment_key derived here ends up in the library users' wallet as we //may see payments to it! - let payment_basepoint = PublicKey::from_secret_key(&self.secp_ctx, &self.local_keys.payment_base_key).unwrap(); - let revocation_basepoint = PublicKey::from_secret_key(&self.secp_ctx, &self.local_keys.revocation_base_key).unwrap(); - let htlc_basepoint = PublicKey::from_secret_key(&self.secp_ctx, &self.local_keys.htlc_base_key).unwrap(); + let payment_basepoint = PublicKey::from_secret_key(&self.secp_ctx, &self.local_keys.payment_base_key); + let revocation_basepoint = PublicKey::from_secret_key(&self.secp_ctx, &self.local_keys.revocation_base_key); + let htlc_basepoint = PublicKey::from_secret_key(&self.secp_ctx, &self.local_keys.htlc_base_key); - Ok(secp_derived_key!(TxCreationKeys::new(&self.secp_ctx, &self.their_cur_commitment_point, &self.their_delayed_payment_basepoint, &self.their_htlc_basepoint, &revocation_basepoint, &payment_basepoint, &htlc_basepoint))) + 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())) } /// Gets the redeemscript for the funding transaction output (ie the funding transaction output /// pays to get_funding_redeemscript().to_v0_p2wsh()). pub fn get_funding_redeemscript(&self) -> Script { let builder = Builder::new().push_opcode(opcodes::All::OP_PUSHNUM_2); - let our_funding_key = PublicKey::from_secret_key(&self.secp_ctx, &self.local_keys.funding_key).unwrap().serialize(); - let their_funding_key = self.their_funding_pubkey.serialize(); + let our_funding_key = PublicKey::from_secret_key(&self.secp_ctx, &self.local_keys.funding_key).serialize(); + let their_funding_key = self.their_funding_pubkey.unwrap().serialize(); if our_funding_key[..] < their_funding_key[..] { builder.push_slice(&our_funding_key) .push_slice(&their_funding_key) @@ -925,12 +917,12 @@ impl Channel { let funding_redeemscript = self.get_funding_redeemscript(); let sighash = Message::from_slice(&bip143::SighashComponents::new(&tx).sighash_all(&tx.input[0], &funding_redeemscript, self.channel_value_satoshis)[..]).unwrap(); - let our_sig = self.secp_ctx.sign(&sighash, &self.local_keys.funding_key).unwrap(); + let our_sig = self.secp_ctx.sign(&sighash, &self.local_keys.funding_key); tx.input[0].witness.push(Vec::new()); // First is the multisig dummy - let our_funding_key = PublicKey::from_secret_key(&self.secp_ctx, &self.local_keys.funding_key).unwrap().serialize(); - let their_funding_key = self.their_funding_pubkey.serialize(); + let our_funding_key = PublicKey::from_secret_key(&self.secp_ctx, &self.local_keys.funding_key).serialize(); + let their_funding_key = self.their_funding_pubkey.unwrap().serialize(); if our_funding_key[..] < their_funding_key[..] { tx.input[0].witness.push(our_sig.serialize_der(&self.secp_ctx).to_vec()); tx.input[0].witness.push(their_sig.serialize_der(&self.secp_ctx).to_vec()); @@ -941,7 +933,7 @@ impl Channel { tx.input[0].witness[1].push(SigHashType::All as u8); tx.input[0].witness[2].push(SigHashType::All as u8); - tx.input[0].witness.push(funding_redeemscript.into_vec()); + tx.input[0].witness.push(funding_redeemscript.into_bytes()); our_sig } @@ -960,10 +952,10 @@ impl Channel { let htlc_redeemscript = chan_utils::get_htlc_redeemscript(&htlc, &keys); - 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)); + 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()); let sighash = Message::from_slice(&bip143::SighashComponents::new(&tx).sighash_all(&tx.input[0], &htlc_redeemscript, htlc.amount_msat / 1000)[..]).unwrap(); - let is_local_tx = PublicKey::from_secret_key(&self.secp_ctx, &our_htlc_key).unwrap() == keys.a_htlc_key; - Ok((htlc_redeemscript, self.secp_ctx.sign(&sighash, &our_htlc_key).unwrap(), is_local_tx)) + let is_local_tx = PublicKey::from_secret_key(&self.secp_ctx, &our_htlc_key) == keys.a_htlc_key; + Ok((htlc_redeemscript, self.secp_ctx.sign(&sighash, &our_htlc_key), is_local_tx)) } /// Signs a transaction created by build_htlc_transaction. If the transaction is an @@ -996,7 +988,7 @@ impl Channel { tx.input[0].witness.push(preimage.unwrap().to_vec()); } - tx.input[0].witness.push(htlc_redeemscript.into_vec()); + tx.input[0].witness.push(htlc_redeemscript.into_bytes()); Ok(our_sig) } @@ -1018,11 +1010,15 @@ impl Channel { let mut pending_idx = std::usize::MAX; for (idx, htlc) in self.pending_htlcs.iter().enumerate() { - if !htlc.outbound && htlc.payment_hash == payment_hash_calc { - if pending_idx != std::usize::MAX { - panic!("Duplicate HTLC payment_hash, ChannelManager should have prevented this!"); + if !htlc.outbound && htlc.payment_hash == payment_hash_calc && + htlc.state != HTLCState::LocalRemoved { + if let Some(PendingHTLCStatus::Fail(_)) = htlc.pending_forward_state { + } else { + if pending_idx != std::usize::MAX { + panic!("Duplicate HTLC payment_hash, ChannelManager should have prevented this!"); + } + pending_idx = idx; } - pending_idx = idx; } } if pending_idx == std::usize::MAX { @@ -1070,9 +1066,8 @@ impl Channel { // hopefully never happens. Instead, we make sure we get the preimage into the // channel_monitor and pretend we didn't just see the preimage. return Ok((None, Some(self.channel_monitor.clone()))); - } else if htlc.state == HTLCState::LocalRemoved || htlc.state == HTLCState::LocalRemovedAwaitingCommitment { - return Err(HandleError{err: "Unable to find a pending HTLC which matched the given payment preimage", action: None}); } else { + // LocalRemoved/LocalRemovedAwaitingCOmmitment handled in the search loop panic!("Have an inbound HTLC when not awaiting remote revoke that had a garbage state"); } htlc.htlc_id @@ -1130,20 +1125,27 @@ impl Channel { let mut htlc_amount_msat = 0; for htlc in self.pending_htlcs.iter_mut() { if !htlc.outbound && htlc.payment_hash == *payment_hash_arg { - if htlc_id != 0 { - panic!("Duplicate HTLC payment_hash, you probably re-used payment preimages, NEVER DO THIS!"); - } - htlc_id = htlc.htlc_id; - htlc_amount_msat += htlc.amount_msat; if htlc.state == HTLCState::Committed { htlc.state = HTLCState::LocalRemoved; } else if htlc.state == HTLCState::RemoteAnnounced { - panic!("Somehow forwarded HTLC prior to remote revocation!"); - } else if htlc.state == HTLCState::LocalRemoved || htlc.state == HTLCState::LocalRemovedAwaitingCommitment { + if let Some(PendingHTLCStatus::Forward(_)) = htlc.pending_forward_state { + panic!("Somehow forwarded HTLC prior to remote revocation!"); + } else { + // We have to pretend this isn't here - we're probably a duplicate with the + // same payment_hash as some other HTLC, and the other is getting failed, + // we'll fail this one as soon as remote commits to it. + continue; + } + } else if htlc.state == HTLCState::LocalRemoved { return Err(HandleError{err: "Unable to find a pending HTLC which matched the given payment preimage", action: None}); } else { panic!("Have an inbound HTLC when not awaiting remote revoke that had a garbage state"); } + if htlc_id != 0 { + panic!("Duplicate HTLC payment_hash, you probably re-used payment preimages, NEVER DO THIS!"); + } + htlc_id = htlc.htlc_id; + htlc_amount_msat += htlc.amount_msat; } } if htlc_amount_msat == 0 { @@ -1230,12 +1232,12 @@ impl Channel { self.their_htlc_minimum_msat = msg.htlc_minimum_msat; self.their_to_self_delay = msg.to_self_delay; self.their_max_accepted_htlcs = msg.max_accepted_htlcs; - self.their_funding_pubkey = msg.funding_pubkey; - self.their_revocation_basepoint = msg.revocation_basepoint; - self.their_payment_basepoint = msg.payment_basepoint; - self.their_delayed_payment_basepoint = msg.delayed_payment_basepoint; - self.their_htlc_basepoint = msg.htlc_basepoint; - self.their_cur_commitment_point = msg.first_per_commitment_point; + self.their_funding_pubkey = Some(msg.funding_pubkey); + self.their_revocation_basepoint = Some(msg.revocation_basepoint); + self.their_payment_basepoint = Some(msg.payment_basepoint); + self.their_delayed_payment_basepoint = Some(msg.delayed_payment_basepoint); + self.their_htlc_basepoint = Some(msg.htlc_basepoint); + self.their_cur_commitment_point = Some(msg.first_per_commitment_point); let obscure_factor = self.get_commitment_transaction_number_obscure_factor(); self.channel_monitor.set_commitment_obscure_factor(obscure_factor); @@ -1258,18 +1260,21 @@ impl Channel { 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(); // They sign the "local" commitment transaction, allowing us to broadcast the tx if we wish. - secp_call!(self.secp_ctx.verify(&local_sighash, &sig, &self.their_funding_pubkey), "Invalid funding_created signature from peer"); + secp_call!(self.secp_ctx.verify(&local_sighash, &sig, &self.their_funding_pubkey.unwrap()), "Invalid funding_created signature from peer", self.channel_id()); // We sign the "remote" commitment transaction, allowing them to broadcast the tx if they wish. - Ok((remote_initial_commitment_tx, self.secp_ctx.sign(&remote_sighash, &self.local_keys.funding_key).unwrap())) + Ok((remote_initial_commitment_tx, self.secp_ctx.sign(&remote_sighash, &self.local_keys.funding_key))) } pub fn funding_created(&mut self, msg: &msgs::FundingCreated) -> Result<(msgs::FundingSigned, ChannelMonitor), HandleError> { if self.channel_outbound { - return Err(HandleError{err: "Received funding_created for an outbound channel?", action: None}); + return Err(HandleError{err: "Received funding_created for an outbound channel?", action: Some(msgs::ErrorAction::SendErrorMessage {msg: msgs::ErrorMessage {channel_id: self.channel_id, data: "Received funding_created for an outbound channel?".to_string()}})}); } if self.channel_state != (ChannelState::OurInitSent as u32 | ChannelState::TheirInitSent as u32) { - return Err(HandleError{err: "Received funding_created after we got the channel!", action: None}); + // BOLT 2 says that if we disconnect before we send funding_signed we SHOULD NOT + // remember the channel, so its safe to just send an error_message here and drop the + // channel. + return Err(HandleError{err: "Received funding_created after we got the channel!", action: Some(msgs::ErrorAction::SendErrorMessage {msg: msgs::ErrorMessage {channel_id: self.channel_id, data: "Received funding_created after we got the channel!".to_string()}})}); } if self.channel_monitor.get_min_seen_secret() != (1 << 48) || self.cur_remote_commitment_transaction_number != (1 << 48) - 1 || self.cur_local_commitment_transaction_number != (1 << 48) - 1 { panic!("Should not have advanced channel commitment tx numbers prior to funding_created"); @@ -1321,7 +1326,7 @@ impl Channel { 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(); // They sign the "local" commitment transaction, allowing us to broadcast the tx if we wish. - secp_call!(self.secp_ctx.verify(&local_sighash, &msg.signature, &self.their_funding_pubkey), "Invalid funding_signed signature from peer"); + secp_call!(self.secp_ctx.verify(&local_sighash, &msg.signature, &self.their_funding_pubkey.unwrap()), "Invalid funding_signed signature from peer", self.channel_id()); self.sign_commitment_transaction(&mut local_initial_commitment_tx, &msg.signature); self.channel_monitor.provide_latest_local_commitment_tx_info(local_initial_commitment_tx.clone(), local_keys, self.feerate_per_kw, Vec::new()); @@ -1343,8 +1348,8 @@ impl Channel { return Err(HandleError{err: "Peer sent a funding_locked at a strange time", action: None}); } - self.their_prev_commitment_point = Some(self.their_cur_commitment_point); - self.their_cur_commitment_point = msg.next_per_commitment_point; + self.their_prev_commitment_point = self.their_cur_commitment_point; + self.their_cur_commitment_point = Some(msg.next_per_commitment_point); Ok(()) } @@ -1370,7 +1375,6 @@ impl Channel { HTLCState::AwaitingRemoteRevokeToRemove => { if for_remote_update_check { continue; } }, HTLCState::AwaitingRemovedRemoteRevoke => { if for_remote_update_check { continue; } }, HTLCState::LocalRemoved => {}, - HTLCState::LocalRemovedAwaitingCommitment => { if for_remote_update_check { continue; } }, } if !htlc.outbound { inbound_htlc_count += 1; @@ -1383,7 +1387,7 @@ impl Channel { (inbound_htlc_count, outbound_htlc_count, htlc_outbound_value_msat, htlc_inbound_value_msat) } - pub fn update_add_htlc(&mut self, msg: &msgs::UpdateAddHTLC, pending_forward_state: PendingForwardHTLCInfo) -> Result<(), HandleError> { + pub fn update_add_htlc(&mut self, msg: &msgs::UpdateAddHTLC, pending_forward_state: PendingHTLCStatus) -> Result<(), HandleError> { if (self.channel_state & (ChannelState::ChannelFunded as u32 | ChannelState::RemoteShutdownSent as u32)) != (ChannelState::ChannelFunded as u32) { return Err(HandleError{err: "Got add HTLC message when channel was not in an operational state", action: None}); } @@ -1505,7 +1509,7 @@ impl Channel { let mut local_commitment_tx = self.build_commitment_transaction(self.cur_local_commitment_transaction_number, &local_keys, true, false); let local_commitment_txid = local_commitment_tx.0.txid(); 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(); - secp_call!(self.secp_ctx.verify(&local_sighash, &msg.signature, &self.their_funding_pubkey), "Invalid commitment tx signature from peer"); + secp_call!(self.secp_ctx.verify(&local_sighash, &msg.signature, &self.their_funding_pubkey.unwrap()), "Invalid commitment tx signature from peer", self.channel_id()); if msg.htlc_signatures.len() != local_commitment_tx.1.len() { return Err(HandleError{err: "Got wrong number of HTLC signatures from remote", action: None}); @@ -1520,7 +1524,7 @@ impl Channel { let mut htlc_tx = self.build_htlc_transaction(&local_commitment_txid, htlc, true, &local_keys); let htlc_redeemscript = chan_utils::get_htlc_redeemscript(&htlc, &local_keys); let htlc_sighash = Message::from_slice(&bip143::SighashComponents::new(&htlc_tx).sighash_all(&htlc_tx.input[0], &htlc_redeemscript, htlc.amount_msat / 1000)[..]).unwrap(); - secp_call!(self.secp_ctx.verify(&htlc_sighash, &msg.htlc_signatures[idx], &local_keys.b_htlc_key), "Invalid HTLC tx siganture from peer"); + 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()); let htlc_sig = if htlc.offered { let htlc_sig = self.sign_htlc_transaction(&mut htlc_tx, &msg.htlc_signatures[idx], &None, htlc, &local_keys)?; new_local_commitment_txn.push(htlc_tx); @@ -1531,7 +1535,7 @@ impl Channel { htlcs_and_sigs.push(((*htlc).clone(), msg.htlc_signatures[idx], htlc_sig)); } - let next_per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &self.build_local_commitment_secret(self.cur_local_commitment_transaction_number - 1)).unwrap(); + let next_per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &self.build_local_commitment_secret(self.cur_local_commitment_transaction_number - 1)); let per_commitment_secret = chan_utils::build_commitment_secret(self.local_keys.commitment_seed, self.cur_local_commitment_transaction_number + 1); // Update state now that we've passed all the can-fail calls... @@ -1547,16 +1551,6 @@ impl Channel { need_our_commitment = true; } } - // Finally delete all the LocalRemovedAwaitingCommitment HTLCs - // We really shouldnt have two passes here, but retain gives a non-mutable ref (Rust bug) - let mut claimed_value_msat = 0; - self.pending_htlcs.retain(|htlc| { - if htlc.state == HTLCState::LocalRemovedAwaitingCommitment { - claimed_value_msat += htlc.amount_msat; - false - } else { true } - }); - self.value_to_self_msat += claimed_value_msat; self.cur_local_commitment_transaction_number -= 1; self.last_local_commitment_txn = new_local_commitment_txn; @@ -1635,6 +1629,7 @@ impl Channel { update_add_htlcs, update_fulfill_htlcs, update_fail_htlcs, + update_fail_malformed_htlcs: Vec::new(), commitment_signed, }, monitor_update))) }, @@ -1655,7 +1650,7 @@ impl Channel { return Err(HandleError{err: "Got revoke/ACK message when channel was not in an operational state", action: None}); } if let Some(their_prev_commitment_point) = self.their_prev_commitment_point { - 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")).unwrap() != their_prev_commitment_point { + 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 { return Err(HandleError{err: "Got a revoke commitment secret which didn't correspond to their current pubkey", action: None}); } } @@ -1666,18 +1661,23 @@ impl Channel { // OK, we step the channel here and *then* if the new generation fails we can fail the // channel based on that, but stepping stuff here should be safe either way. self.channel_state &= !(ChannelState::AwaitingRemoteRevoke as u32); - self.their_prev_commitment_point = Some(self.their_cur_commitment_point); - self.their_cur_commitment_point = msg.next_per_commitment_point; + self.their_prev_commitment_point = self.their_cur_commitment_point; + self.their_cur_commitment_point = Some(msg.next_per_commitment_point); self.cur_remote_commitment_transaction_number -= 1; let mut to_forward_infos = Vec::new(); let mut revoked_htlcs = Vec::new(); + let mut update_fail_htlcs = Vec::new(); + let mut update_fail_malformed_htlcs = Vec::new(); let mut require_commitment = false; let mut value_to_self_msat_diff: i64 = 0; // We really shouldnt have two passes here, but retain gives a non-mutable ref (Rust bug) self.pending_htlcs.retain(|htlc| { if htlc.state == HTLCState::LocalRemoved { - if htlc.local_removed_fulfilled { true } else { false } + if htlc.local_removed_fulfilled { + value_to_self_msat_diff += htlc.amount_msat as i64; + } + false } else if htlc.state == HTLCState::AwaitingRemovedRemoteRevoke { if let Some(reason) = htlc.fail_reason.clone() { // We really want take() here, but, again, non-mut ref :( revoked_htlcs.push((htlc.payment_hash, reason)); @@ -1695,20 +1695,37 @@ impl Channel { htlc.state = HTLCState::AwaitingAnnouncedRemoteRevoke; require_commitment = true; } else if htlc.state == HTLCState::AwaitingAnnouncedRemoteRevoke { - htlc.state = HTLCState::Committed; - to_forward_infos.push(htlc.pending_forward_state.take().unwrap()); + match htlc.pending_forward_state.take().unwrap() { + PendingHTLCStatus::Fail(fail_msg) => { + htlc.state = HTLCState::LocalRemoved; + require_commitment = true; + match fail_msg { + HTLCFailureMsg::Relay(msg) => update_fail_htlcs.push(msg), + HTLCFailureMsg::Malformed(msg) => update_fail_malformed_htlcs.push(msg), + } + }, + PendingHTLCStatus::Forward(forward_info) => { + to_forward_infos.push(forward_info); + htlc.state = HTLCState::Committed; + } + } } else if htlc.state == HTLCState::AwaitingRemoteRevokeToRemove { htlc.state = HTLCState::AwaitingRemovedRemoteRevoke; require_commitment = true; - } else if htlc.state == HTLCState::LocalRemoved { - assert!(htlc.local_removed_fulfilled); - htlc.state = HTLCState::LocalRemovedAwaitingCommitment; } } self.value_to_self_msat = (self.value_to_self_msat as i64 + value_to_self_msat_diff) as u64; match self.free_holding_cell_htlcs()? { - Some(commitment_update) => { + Some(mut commitment_update) => { + commitment_update.0.update_fail_htlcs.reserve(update_fail_htlcs.len()); + for fail_msg in update_fail_htlcs.drain(..) { + commitment_update.0.update_fail_htlcs.push(fail_msg); + } + commitment_update.0.update_fail_malformed_htlcs.reserve(update_fail_malformed_htlcs.len()); + for fail_msg in update_fail_malformed_htlcs.drain(..) { + commitment_update.0.update_fail_malformed_htlcs.push(fail_msg); + } Ok((Some(commitment_update.0), to_forward_infos, revoked_htlcs, commitment_update.1)) }, None => { @@ -1717,7 +1734,8 @@ impl Channel { Ok((Some(msgs::CommitmentUpdate { update_add_htlcs: Vec::new(), update_fulfill_htlcs: Vec::new(), - update_fail_htlcs: Vec::new(), + update_fail_htlcs, + update_fail_malformed_htlcs, commitment_signed }), to_forward_infos, revoked_htlcs, monitor_update)) } else { @@ -1782,7 +1800,7 @@ impl Channel { let funding_redeemscript = self.get_funding_redeemscript(); let sighash = Message::from_slice(&bip143::SighashComponents::new(&closing_tx).sighash_all(&closing_tx.input[0], &funding_redeemscript, self.channel_value_satoshis)[..]).unwrap(); - (Some(proposed_feerate), Some(total_fee_satoshis), Some(self.secp_ctx.sign(&sighash, &self.local_keys.funding_key).unwrap())) + (Some(proposed_feerate), Some(total_fee_satoshis), Some(self.secp_ctx.sign(&sighash, &self.local_keys.funding_key))) } else { (None, None, None) }; // From here on out, we may not fail! @@ -1852,14 +1870,14 @@ impl Channel { } let mut sighash = Message::from_slice(&bip143::SighashComponents::new(&closing_tx).sighash_all(&closing_tx.input[0], &funding_redeemscript, self.channel_value_satoshis)[..]).unwrap(); - match self.secp_ctx.verify(&sighash, &msg.signature, &self.their_funding_pubkey) { + match self.secp_ctx.verify(&sighash, &msg.signature, &self.their_funding_pubkey.unwrap()) { Ok(_) => {}, Err(_e) => { // The remote end may have decided to revoke their output due to inconsistent dust // limits, so check for that case by re-checking the signature here. closing_tx = self.build_closing_transaction(msg.fee_satoshis, true).0; sighash = Message::from_slice(&bip143::SighashComponents::new(&closing_tx).sighash_all(&closing_tx.input[0], &funding_redeemscript, self.channel_value_satoshis)[..]).unwrap(); - secp_call!(self.secp_ctx.verify(&sighash, &msg.signature, &self.their_funding_pubkey), "Invalid closing tx signature from peer"); + secp_call!(self.secp_ctx.verify(&sighash, &msg.signature, &self.their_funding_pubkey.unwrap()), "Invalid closing tx signature from peer", self.channel_id()); }, }; @@ -1877,7 +1895,7 @@ impl Channel { let closing_tx_max_weight = Self::get_closing_transaction_weight(&self.get_closing_scriptpubkey(), self.their_shutdown_scriptpubkey.as_ref().unwrap()); let (closing_tx, used_total_fee) = self.build_closing_transaction($new_feerate * closing_tx_max_weight / 1000, false); sighash = Message::from_slice(&bip143::SighashComponents::new(&closing_tx).sighash_all(&closing_tx.input[0], &funding_redeemscript, self.channel_value_satoshis)[..]).unwrap(); - let our_sig = self.secp_ctx.sign(&sighash, &self.local_keys.funding_key).unwrap(); + let our_sig = self.secp_ctx.sign(&sighash, &self.local_keys.funding_key); self.last_sent_closing_fee = Some(($new_feerate, used_total_fee)); return Ok((Some(msgs::ClosingSigned { channel_id: self.channel_id, @@ -1968,6 +1986,12 @@ impl Channel { self.channel_value_satoshis } + //TODO: Testing purpose only, should be changed in another way after #81 + #[cfg(test)] + pub fn get_local_keys(&self) -> &ChannelKeys { + &self.local_keys + } + /// Allowed in any state (including after shutdown) pub fn get_channel_update_count(&self) -> u32 { self.channel_update_count @@ -2065,7 +2089,7 @@ impl Channel { //a protocol oversight, but I assume I'm just missing something. if need_commitment_update { let next_per_commitment_secret = self.build_local_commitment_secret(self.cur_local_commitment_transaction_number); - let next_per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &next_per_commitment_secret).unwrap(); + let next_per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &next_per_commitment_secret); return Ok(Some(msgs::FundingLocked { channel_id: self.channel_id, next_per_commitment_point: next_per_commitment_point, @@ -2079,7 +2103,16 @@ impl Channel { if tx.txid() == self.channel_monitor.get_funding_txo().unwrap().txid { let txo_idx = self.channel_monitor.get_funding_txo().unwrap().index as usize; if txo_idx >= tx.output.len() || tx.output[txo_idx].script_pubkey != self.get_funding_redeemscript().to_v0_p2wsh() || - tx.output[txo_idx].value != self.channel_value_satoshis { + tx.output[txo_idx].value != self.channel_value_satoshis { + if self.channel_outbound { + // If we generated the funding transaction and it doesn't match what it + // should, the client is really broken and we should just panic and + // tell them off. That said, because hash collisions happen with high + // probability in fuzztarget mode, if we're fuzzing we just close the + // channel and move on. + #[cfg(not(feature = "fuzztarget"))] + panic!("Client called ChannelManager::funding_transaction_generated with bogus transaction!"); + } self.channel_state = ChannelState::ShutdownComplete as u32; self.channel_update_count += 1; return Err(HandleError{err: "funding tx had wrong script/value", action: Some(ErrorAction::DisconnectPeer{msg: None})}); @@ -2140,18 +2173,18 @@ impl Channel { feerate_per_kw: fee_estimator.get_est_sat_per_1000_weight(ConfirmationTarget::Background) as u32, to_self_delay: BREAKDOWN_TIMEOUT, max_accepted_htlcs: OUR_MAX_HTLCS, - funding_pubkey: PublicKey::from_secret_key(&self.secp_ctx, &self.local_keys.funding_key).unwrap(), - revocation_basepoint: PublicKey::from_secret_key(&self.secp_ctx, &self.local_keys.revocation_base_key).unwrap(), - payment_basepoint: PublicKey::from_secret_key(&self.secp_ctx, &self.local_keys.payment_base_key).unwrap(), - delayed_payment_basepoint: PublicKey::from_secret_key(&self.secp_ctx, &self.local_keys.delayed_payment_base_key).unwrap(), - htlc_basepoint: PublicKey::from_secret_key(&self.secp_ctx, &self.local_keys.htlc_base_key).unwrap(), - first_per_commitment_point: PublicKey::from_secret_key(&self.secp_ctx, &local_commitment_secret).unwrap(), + funding_pubkey: PublicKey::from_secret_key(&self.secp_ctx, &self.local_keys.funding_key), + revocation_basepoint: PublicKey::from_secret_key(&self.secp_ctx, &self.local_keys.revocation_base_key), + payment_basepoint: PublicKey::from_secret_key(&self.secp_ctx, &self.local_keys.payment_base_key), + delayed_payment_basepoint: PublicKey::from_secret_key(&self.secp_ctx, &self.local_keys.delayed_payment_base_key), + htlc_basepoint: PublicKey::from_secret_key(&self.secp_ctx, &self.local_keys.htlc_base_key), + first_per_commitment_point: PublicKey::from_secret_key(&self.secp_ctx, &local_commitment_secret), channel_flags: if self.announce_publicly {1} else {0}, shutdown_scriptpubkey: None, }) } - pub fn get_accept_channel(&self) -> Result { + pub fn get_accept_channel(&self) -> msgs::AcceptChannel { if self.channel_outbound { panic!("Tried to send accept_channel for an outbound channel?"); } @@ -2164,7 +2197,7 @@ impl Channel { let local_commitment_secret = self.build_local_commitment_secret(self.cur_local_commitment_transaction_number); - Ok(msgs::AcceptChannel { + msgs::AcceptChannel { temporary_channel_id: self.channel_id, dust_limit_satoshis: self.our_dust_limit_satoshis, max_htlc_value_in_flight_msat: Channel::get_our_max_htlc_value_in_flight_msat(self.channel_value_satoshis), @@ -2173,14 +2206,14 @@ impl Channel { minimum_depth: Channel::derive_minimum_depth(self.channel_value_satoshis*1000, self.value_to_self_msat), to_self_delay: BREAKDOWN_TIMEOUT, max_accepted_htlcs: OUR_MAX_HTLCS, - funding_pubkey: PublicKey::from_secret_key(&self.secp_ctx, &self.local_keys.funding_key).unwrap(), - revocation_basepoint: PublicKey::from_secret_key(&self.secp_ctx, &self.local_keys.revocation_base_key).unwrap(), - payment_basepoint: PublicKey::from_secret_key(&self.secp_ctx, &self.local_keys.payment_base_key).unwrap(), - delayed_payment_basepoint: PublicKey::from_secret_key(&self.secp_ctx, &self.local_keys.delayed_payment_base_key).unwrap(), - htlc_basepoint: PublicKey::from_secret_key(&self.secp_ctx, &self.local_keys.htlc_base_key).unwrap(), - first_per_commitment_point: PublicKey::from_secret_key(&self.secp_ctx, &local_commitment_secret).unwrap(), + funding_pubkey: PublicKey::from_secret_key(&self.secp_ctx, &self.local_keys.funding_key), + revocation_basepoint: PublicKey::from_secret_key(&self.secp_ctx, &self.local_keys.revocation_base_key), + payment_basepoint: PublicKey::from_secret_key(&self.secp_ctx, &self.local_keys.payment_base_key), + delayed_payment_basepoint: PublicKey::from_secret_key(&self.secp_ctx, &self.local_keys.delayed_payment_base_key), + htlc_basepoint: PublicKey::from_secret_key(&self.secp_ctx, &self.local_keys.htlc_base_key), + first_per_commitment_point: PublicKey::from_secret_key(&self.secp_ctx, &local_commitment_secret), shutdown_scriptpubkey: None, - }) + } } fn get_outbound_funding_created_signature(&mut self) -> Result<(Signature, Transaction), HandleError> { @@ -2191,7 +2224,7 @@ impl Channel { let remote_sighash = Message::from_slice(&bip143::SighashComponents::new(&remote_initial_commitment_tx).sighash_all(&remote_initial_commitment_tx.input[0], &funding_script, self.channel_value_satoshis)[..]).unwrap(); // We sign the "remote" commitment transaction, allowing them to broadcast the tx if they wish. - Ok((self.secp_ctx.sign(&remote_sighash, &self.local_keys.funding_key).unwrap(), remote_initial_commitment_tx)) + Ok((self.secp_ctx.sign(&remote_sighash, &self.local_keys.funding_key), remote_initial_commitment_tx)) } /// Updates channel state with knowledge of the funding transaction's txid/index, and generates @@ -2241,21 +2274,25 @@ impl Channel { /// Gets an UnsignedChannelAnnouncement, as well as a signature covering it using our /// bitcoin_key, if available, for this channel. The channel must be publicly announceable and - /// available for use (have exchanged FundingLocked messages in both directions. Should be used + /// available for use (have exchanged FundingLocked messages in both directions). Should be used /// for both loose and in response to an AnnouncementSignatures message from the remote peer. - /// Note that you can get an announcement for a channel which is closing, though you should - /// likely not announce such a thing. In case its already been announced, a channel_update - /// message can mark the channel disabled. + /// Will only fail if we're not in a state where channel_announcement may be sent (including + /// closing). + /// Note that the "channel must be funded" requirement is stricter than BOLT 7 requires - see + /// https://github.com/lightningnetwork/lightning-rfc/issues/468 pub fn get_channel_announcement(&self, our_node_id: PublicKey, chain_hash: Sha256dHash) -> Result<(msgs::UnsignedChannelAnnouncement, Signature), HandleError> { if !self.announce_publicly { - return Err(HandleError{err: "Channel is not available for public announcements", action: None}); + return Err(HandleError{err: "Channel is not available for public announcements", action: Some(msgs::ErrorAction::IgnoreError)}); + } + if self.channel_state & (ChannelState::ChannelFunded as u32) == 0 { + return Err(HandleError{err: "Cannot get a ChannelAnnouncement until the channel funding has been locked", action: Some(msgs::ErrorAction::IgnoreError)}); } - if self.channel_state & (ChannelState::ChannelFunded as u32) != (ChannelState::ChannelFunded as u32) { - return Err(HandleError{err: "Cannot get a ChannelAnnouncement until the channel funding has been locked", action: None}); + if (self.channel_state & (ChannelState::LocalShutdownSent as u32 | ChannelState::ShutdownComplete as u32)) != 0 { + return Err(HandleError{err: "Cannot get a ChannelAnnouncement once the channel is closing", action: Some(msgs::ErrorAction::IgnoreError)}); } let were_node_one = our_node_id.serialize()[..] < self.their_node_id.serialize()[..]; - let our_bitcoin_key = PublicKey::from_secret_key(&self.secp_ctx, &self.local_keys.funding_key).unwrap(); + let our_bitcoin_key = PublicKey::from_secret_key(&self.secp_ctx, &self.local_keys.funding_key); let msg = msgs::UnsignedChannelAnnouncement { features: msgs::GlobalFeatures::new(), @@ -2263,12 +2300,13 @@ impl Channel { short_channel_id: self.get_short_channel_id().unwrap(), node_id_1: if were_node_one { our_node_id } else { self.get_their_node_id() }, node_id_2: if were_node_one { self.get_their_node_id() } else { our_node_id }, - bitcoin_key_1: if were_node_one { our_bitcoin_key } else { self.their_funding_pubkey }, - bitcoin_key_2: if were_node_one { self.their_funding_pubkey } else { our_bitcoin_key }, + bitcoin_key_1: if were_node_one { our_bitcoin_key } else { self.their_funding_pubkey.unwrap() }, + bitcoin_key_2: if were_node_one { self.their_funding_pubkey.unwrap() } else { our_bitcoin_key }, + excess_data: Vec::new(), }; let msghash = Message::from_slice(&Sha256dHash::from_data(&msg.encode()[..])[..]).unwrap(); - let sig = self.secp_ctx.sign(&msghash, &self.local_keys.funding_key).unwrap(); + let sig = self.secp_ctx.sign(&msghash, &self.local_keys.funding_key); Ok((msg, sig)) } @@ -2281,6 +2319,7 @@ impl Channel { /// This returns an option instead of a pure UpdateAddHTLC as we may be in a state where we are /// waiting on the remote peer to send us a revoke_and_ack during which time we cannot add new /// HTLCs on the wire or we wouldn't be able to determine what they actually ACK'ed. + /// You MUST call send_commitment prior to any other calls on this Channel pub fn send_htlc(&mut self, amount_msat: u64, payment_hash: [u8; 32], cltv_expiry: u32, onion_routing_packet: msgs::OnionPacket) -> Result, HandleError> { if (self.channel_state & (ChannelState::ChannelFunded as u32 | BOTH_SIDES_SHUTDOWN_MASK)) != (ChannelState::ChannelFunded as u32) { return Err(HandleError{err: "Cannot send HTLC until channel is fully established and we haven't started shutting down", action: None}); @@ -2348,6 +2387,8 @@ impl Channel { } /// Creates a signed commitment transaction to send to the remote peer. + /// Always returns a Channel-failing HandleError::action if an immediately-preceding (read: the + /// last call to this Channel) send_htlc returned Ok(Some(_)) and there is an Err. pub fn send_commitment(&mut self) -> Result<(msgs::CommitmentSigned, ChannelMonitor), HandleError> { if (self.channel_state & (ChannelState::ChannelFunded as u32)) != (ChannelState::ChannelFunded as u32) { return Err(HandleError{err: "Cannot create commitment tx until channel is fully established", action: None}); @@ -2386,7 +2427,7 @@ impl Channel { let remote_commitment_tx = self.build_commitment_transaction(self.cur_remote_commitment_transaction_number, &remote_keys, false, true); let remote_commitment_txid = remote_commitment_tx.0.txid(); let remote_sighash = Message::from_slice(&bip143::SighashComponents::new(&remote_commitment_tx.0).sighash_all(&remote_commitment_tx.0.input[0], &funding_script, self.channel_value_satoshis)[..]).unwrap(); - let our_sig = self.secp_ctx.sign(&remote_sighash, &self.local_keys.funding_key).unwrap(); + let our_sig = self.secp_ctx.sign(&remote_sighash, &self.local_keys.funding_key); let mut htlc_sigs = Vec::new(); @@ -2394,8 +2435,8 @@ impl Channel { let htlc_tx = self.build_htlc_transaction(&remote_commitment_txid, htlc, false, &remote_keys); let htlc_redeemscript = chan_utils::get_htlc_redeemscript(&htlc, &remote_keys); let htlc_sighash = Message::from_slice(&bip143::SighashComponents::new(&htlc_tx).sighash_all(&htlc_tx.input[0], &htlc_redeemscript, htlc.amount_msat / 1000)[..]).unwrap(); - 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)); - htlc_sigs.push(self.secp_ctx.sign(&htlc_sighash, &our_htlc_key).unwrap()); + 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()); + htlc_sigs.push(self.secp_ctx.sign(&htlc_sighash, &our_htlc_key)); } // Update state now that we've passed all the can-fail calls... @@ -2558,38 +2599,39 @@ mod tests { channel_monitor_claim_key: SecretKey::from_slice(&secp_ctx, &hex::decode("0fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff").unwrap()[..]).unwrap(), commitment_seed: [0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff], }; - assert_eq!(PublicKey::from_secret_key(&secp_ctx, &chan_keys.funding_key).unwrap().serialize()[..], + assert_eq!(PublicKey::from_secret_key(&secp_ctx, &chan_keys.funding_key).serialize()[..], hex::decode("023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb").unwrap()[..]); - let mut chan = Channel::new_outbound(&feeest, chan_keys, PublicKey::new(), 10000000, 100000, false, 42, Arc::clone(&logger)).unwrap(); // Nothing uses their network key in this test + let their_node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap()); + let mut chan = Channel::new_outbound(&feeest, chan_keys, their_node_id, 10000000, 100000, false, 42, Arc::clone(&logger)).unwrap(); // Nothing uses their network key in this test chan.their_to_self_delay = 144; chan.our_dust_limit_satoshis = 546; let funding_info = OutPoint::new(Sha256dHash::from_hex("8984484a580b825b9972d7adb15050b3ab624ccd731946b3eeddb92f4e7ef6be").unwrap(), 0); chan.channel_monitor.set_funding_info((funding_info, Script::new())); - chan.their_payment_basepoint = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("4444444444444444444444444444444444444444444444444444444444444444").unwrap()[..]).unwrap()).unwrap(); - assert_eq!(chan.their_payment_basepoint.serialize()[..], + chan.their_payment_basepoint = Some(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("4444444444444444444444444444444444444444444444444444444444444444").unwrap()[..]).unwrap())); + assert_eq!(chan.their_payment_basepoint.unwrap().serialize()[..], hex::decode("032c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991").unwrap()[..]); - chan.their_funding_pubkey = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("1552dfba4f6cf29a62a0af13c8d6981d36d0ef8d61ba10fb0fe90da7634d7e13").unwrap()[..]).unwrap()).unwrap(); - assert_eq!(chan.their_funding_pubkey.serialize()[..], + chan.their_funding_pubkey = Some(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("1552dfba4f6cf29a62a0af13c8d6981d36d0ef8d61ba10fb0fe90da7634d7e13").unwrap()[..]).unwrap())); + assert_eq!(chan.their_funding_pubkey.unwrap().serialize()[..], hex::decode("030e9f7b623d2ccc7c9bd44d66d5ce21ce504c0acf6385a132cec6d3c39fa711c1").unwrap()[..]); - chan.their_htlc_basepoint = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("4444444444444444444444444444444444444444444444444444444444444444").unwrap()[..]).unwrap()).unwrap(); - assert_eq!(chan.their_htlc_basepoint.serialize()[..], + chan.their_htlc_basepoint = Some(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("4444444444444444444444444444444444444444444444444444444444444444").unwrap()[..]).unwrap())); + assert_eq!(chan.their_htlc_basepoint.unwrap().serialize()[..], hex::decode("032c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991").unwrap()[..]); - chan.their_revocation_basepoint = PublicKey::from_slice(&secp_ctx, &hex::decode("02466d7fcae563e5cb09a0d1870bb580344804617879a14949cf22285f1bae3f27").unwrap()[..]).unwrap(); + chan.their_revocation_basepoint = Some(PublicKey::from_slice(&secp_ctx, &hex::decode("02466d7fcae563e5cb09a0d1870bb580344804617879a14949cf22285f1bae3f27").unwrap()[..]).unwrap()); // We can't just use build_local_transaction_keys here as the per_commitment_secret is not // derived from a commitment_seed, so instead we copy it here and call // build_commitment_transaction. - let delayed_payment_base = PublicKey::from_secret_key(&secp_ctx, &chan.local_keys.delayed_payment_base_key).unwrap(); + let delayed_payment_base = PublicKey::from_secret_key(&secp_ctx, &chan.local_keys.delayed_payment_base_key); let per_commitment_secret = SecretKey::from_slice(&secp_ctx, &hex::decode("1f1e1d1c1b1a191817161514131211100f0e0d0c0b0a09080706050403020100").unwrap()[..]).unwrap(); - let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &per_commitment_secret).unwrap(); - let htlc_basepoint = PublicKey::from_secret_key(&secp_ctx, &chan.local_keys.htlc_base_key).unwrap(); - let keys = TxCreationKeys::new(&secp_ctx, &per_commitment_point, &delayed_payment_base, &htlc_basepoint, &chan.their_revocation_basepoint, &chan.their_payment_basepoint, &chan.their_htlc_basepoint).unwrap(); + let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &per_commitment_secret); + let htlc_basepoint = PublicKey::from_secret_key(&secp_ctx, &chan.local_keys.htlc_base_key); + let keys = TxCreationKeys::new(&secp_ctx, &per_commitment_point, &delayed_payment_base, &htlc_basepoint, &chan.their_revocation_basepoint.unwrap(), &chan.their_payment_basepoint.unwrap(), &chan.their_htlc_basepoint.unwrap()).unwrap(); let mut unsigned_tx: (Transaction, Vec); @@ -2598,7 +2640,7 @@ mod tests { unsigned_tx = chan.build_commitment_transaction(0xffffffffffff - 42, &keys, true, false); let their_signature = Signature::from_der(&secp_ctx, &hex::decode($their_sig_hex).unwrap()[..]).unwrap(); let sighash = Message::from_slice(&bip143::SighashComponents::new(&unsigned_tx.0).sighash_all(&unsigned_tx.0.input[0], &chan.get_funding_redeemscript(), chan.channel_value_satoshis)[..]).unwrap(); - secp_ctx.verify(&sighash, &their_signature, &chan.their_funding_pubkey).unwrap(); + secp_ctx.verify(&sighash, &their_signature, &chan.their_funding_pubkey.unwrap()).unwrap(); chan.sign_commitment_transaction(&mut unsigned_tx.0, &their_signature); @@ -3086,10 +3128,10 @@ mod tests { let base_secret = SecretKey::from_slice(&secp_ctx, &hex::decode("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f").unwrap()[..]).unwrap(); let per_commitment_secret = SecretKey::from_slice(&secp_ctx, &hex::decode("1f1e1d1c1b1a191817161514131211100f0e0d0c0b0a09080706050403020100").unwrap()[..]).unwrap(); - let base_point = PublicKey::from_secret_key(&secp_ctx, &base_secret).unwrap(); + let base_point = PublicKey::from_secret_key(&secp_ctx, &base_secret); assert_eq!(base_point.serialize()[..], hex::decode("036d6caac248af96f6afa7f904f550253a0f3ef3f5aa2fe6838a95b216691468e2").unwrap()[..]); - let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &per_commitment_secret).unwrap(); + let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &per_commitment_secret); assert_eq!(per_commitment_point.serialize()[..], hex::decode("025f7117a78150fe2ef97db7cfc83bd57b2e2c0d0dd25eaf467a4a1c2a45ce1486").unwrap()[..]); assert_eq!(chan_utils::derive_public_key(&secp_ctx, &per_commitment_point, &base_point).unwrap().serialize()[..],