X-Git-Url: http://git.bitcoin.ninja/index.cgi?a=blobdiff_plain;f=lightning%2Fsrc%2Fln%2Fchannel.rs;h=64f7e4f0b682d78db36cecd00d3cdaa0251cf387;hb=4f06d7a83c04d3f99131175aec9a30ec0c55df5d;hp=d0db1d85613f217cbca040191207a60fcb5d2bfa;hpb=6caed7df7cf21de837d4b31443699a933164b9cd;p=rust-lightning diff --git a/lightning/src/ln/channel.rs b/lightning/src/ln/channel.rs index d0db1d85..64f7e4f0 100644 --- a/lightning/src/ln/channel.rs +++ b/lightning/src/ln/channel.rs @@ -35,6 +35,7 @@ use std; use std::default::Default; use std::{cmp,mem,fmt}; use std::sync::{Arc}; +use std::ops::Deref; #[cfg(test)] pub struct ChannelValueStat { @@ -437,7 +438,10 @@ impl Channel { } // Constructors: - pub fn new_outbound(fee_estimator: &FeeEstimator, keys_provider: &Arc>, their_node_id: PublicKey, channel_value_satoshis: u64, push_msat: u64, user_id: u64, logger: Arc, config: &UserConfig) -> Result, APIError> { + pub fn new_outbound(fee_estimator: &F, keys_provider: &K, their_node_id: PublicKey, channel_value_satoshis: u64, push_msat: u64, user_id: u64, logger: Arc, config: &UserConfig) -> Result, APIError> + where K::Target: KeysInterface, + F::Target: FeeEstimator, + { let chan_keys = keys_provider.get_channel_keys(false, channel_value_satoshis); if channel_value_satoshis >= MAX_FUNDING_SATOSHIS { @@ -538,7 +542,9 @@ impl Channel { }) } - fn check_remote_fee(fee_estimator: &FeeEstimator, feerate_per_kw: u32) -> Result<(), ChannelError> { + fn check_remote_fee(fee_estimator: &F, feerate_per_kw: u32) -> Result<(), ChannelError> + where F::Target: FeeEstimator + { if (feerate_per_kw as u64) < fee_estimator.get_est_sat_per_1000_weight(ConfirmationTarget::Background) { return Err(ChannelError::Close("Peer's feerate much too low")); } @@ -550,7 +556,10 @@ impl Channel { /// Creates a new channel from a remote sides' request for one. /// Assumes chain_hash has already been checked and corresponds with what we expect! - pub fn new_from_req(fee_estimator: &FeeEstimator, keys_provider: &Arc>, their_node_id: PublicKey, their_features: InitFeatures, msg: &msgs::OpenChannel, user_id: u64, logger: Arc, config: &UserConfig) -> Result, ChannelError> { + pub fn new_from_req(fee_estimator: &F, keys_provider: &K, their_node_id: PublicKey, their_features: InitFeatures, msg: &msgs::OpenChannel, user_id: u64, logger: Arc, config: &UserConfig) -> Result, ChannelError> + where K::Target: KeysInterface, + F::Target: FeeEstimator + { let mut chan_keys = keys_provider.get_channel_keys(true, msg.funding_satoshis); let their_pubkeys = ChannelPublicKeys { funding_pubkey: msg.funding_pubkey, @@ -1488,16 +1497,25 @@ impl Channel { let their_pubkeys = self.their_pubkeys.as_ref().unwrap(); let funding_redeemscript = self.get_funding_redeemscript(); let funding_txo_script = funding_redeemscript.to_v0_p2wsh(); - self.channel_monitor = Some(ChannelMonitor::new(self.local_keys.clone(), - &self.shutdown_pubkey, self.our_to_self_delay, - &self.destination_script, (funding_txo, funding_txo_script), - &their_pubkeys.htlc_basepoint, &their_pubkeys.delayed_payment_basepoint, - self.their_to_self_delay, funding_redeemscript, self.channel_value_satoshis, - self.get_commitment_transaction_number_obscure_factor(), - self.logger.clone())); - - self.channel_monitor.as_mut().unwrap().provide_latest_remote_commitment_tx_info(&remote_initial_commitment_tx, Vec::new(), self.cur_remote_commitment_transaction_number, self.their_cur_commitment_point.unwrap()); - self.channel_monitor.as_mut().unwrap().provide_latest_local_commitment_tx_info(local_initial_commitment_tx, local_keys, self.feerate_per_kw, Vec::new()).unwrap(); + macro_rules! create_monitor { + () => { { + let mut channel_monitor = ChannelMonitor::new(self.local_keys.clone(), + &self.shutdown_pubkey, self.our_to_self_delay, + &self.destination_script, (funding_txo, funding_txo_script.clone()), + &their_pubkeys.htlc_basepoint, &their_pubkeys.delayed_payment_basepoint, + self.their_to_self_delay, funding_redeemscript.clone(), self.channel_value_satoshis, + self.get_commitment_transaction_number_obscure_factor(), + self.logger.clone()); + + channel_monitor.provide_latest_remote_commitment_tx_info(&remote_initial_commitment_tx, Vec::new(), self.cur_remote_commitment_transaction_number, self.their_cur_commitment_point.unwrap()); + channel_monitor.provide_latest_local_commitment_tx_info(local_initial_commitment_tx.clone(), local_keys.clone(), self.feerate_per_kw, Vec::new()).unwrap(); + channel_monitor + } } + } + + self.channel_monitor = Some(create_monitor!()); + let channel_monitor = create_monitor!(); + self.channel_state = ChannelState::FundingSent as u32; self.channel_id = funding_txo.to_channel_id(); self.cur_remote_commitment_transaction_number -= 1; @@ -1506,7 +1524,7 @@ impl Channel { Ok((msgs::FundingSigned { channel_id: self.channel_id, signature: our_signature - }, self.channel_monitor.as_ref().unwrap().clone())) + }, channel_monitor)) } /// Handles a funding_signed message from the remote end. @@ -1763,7 +1781,7 @@ impl Channel { Ok(()) } - pub fn commitment_signed(&mut self, msg: &msgs::CommitmentSigned, fee_estimator: &FeeEstimator) -> Result<(msgs::RevokeAndACK, Option, Option, ChannelMonitorUpdate), (Option, ChannelError)> { + pub fn commitment_signed(&mut self, msg: &msgs::CommitmentSigned, fee_estimator: &F) -> Result<(msgs::RevokeAndACK, Option, Option, ChannelMonitorUpdate), (Option, ChannelError)> where F::Target: FeeEstimator { if (self.channel_state & (ChannelState::ChannelFunded as u32)) != (ChannelState::ChannelFunded as u32) { return Err((None, ChannelError::Close("Got commitment signed message when channel was not in an operational state"))); } @@ -2051,7 +2069,9 @@ impl Channel { /// waiting on this revoke_and_ack. The generation of this new commitment_signed may also fail, /// generating an appropriate error *after* the channel state has been updated based on the /// revoke_and_ack message. - pub fn revoke_and_ack(&mut self, msg: &msgs::RevokeAndACK, fee_estimator: &FeeEstimator) -> Result<(Option, Vec<(PendingHTLCInfo, u64)>, Vec<(HTLCSource, PaymentHash, HTLCFailReason)>, Option, ChannelMonitorUpdate), ChannelError> { + pub fn revoke_and_ack(&mut self, msg: &msgs::RevokeAndACK, fee_estimator: &F) -> Result<(Option, Vec<(PendingHTLCInfo, u64)>, Vec<(HTLCSource, PaymentHash, HTLCFailReason)>, Option, ChannelMonitorUpdate), ChannelError> + where F::Target: FeeEstimator + { if (self.channel_state & (ChannelState::ChannelFunded as u32)) != (ChannelState::ChannelFunded as u32) { return Err(ChannelError::Close("Got revoke/ACK message when channel was not in an operational state")); } @@ -2449,7 +2469,9 @@ impl Channel { (raa, commitment_update, order, forwards, failures, needs_broadcast_safe, funding_locked) } - pub fn update_fee(&mut self, fee_estimator: &FeeEstimator, msg: &msgs::UpdateFee) -> Result<(), ChannelError> { + pub fn update_fee(&mut self, fee_estimator: &F, msg: &msgs::UpdateFee) -> Result<(), ChannelError> + where F::Target: FeeEstimator + { if self.channel_outbound { return Err(ChannelError::Close("Non-funding remote tried to update channel fee")); } @@ -2670,7 +2692,9 @@ impl Channel { } } - fn maybe_propose_first_closing_signed(&mut self, fee_estimator: &FeeEstimator) -> Option { + fn maybe_propose_first_closing_signed(&mut self, fee_estimator: &F) -> Option + where F::Target: FeeEstimator + { if !self.channel_outbound || !self.pending_inbound_htlcs.is_empty() || !self.pending_outbound_htlcs.is_empty() || self.channel_state & (BOTH_SIDES_SHUTDOWN_MASK | ChannelState::AwaitingRemoteRevoke as u32) != BOTH_SIDES_SHUTDOWN_MASK || self.last_sent_closing_fee.is_some() || self.pending_update_fee.is_some() { @@ -2698,7 +2722,9 @@ impl Channel { }) } - pub fn shutdown(&mut self, fee_estimator: &FeeEstimator, msg: &msgs::Shutdown) -> Result<(Option, Option, Vec<(HTLCSource, PaymentHash)>), ChannelError> { + pub fn shutdown(&mut self, fee_estimator: &F, msg: &msgs::Shutdown) -> Result<(Option, Option, Vec<(HTLCSource, PaymentHash)>), ChannelError> + where F::Target: FeeEstimator + { if self.channel_state & (ChannelState::PeerDisconnected as u32) == ChannelState::PeerDisconnected as u32 { return Err(ChannelError::Close("Peer sent shutdown when we needed a channel_reestablish")); } @@ -2794,7 +2820,9 @@ impl Channel { tx.input[0].witness.push(self.get_funding_redeemscript().into_bytes()); } - pub fn closing_signed(&mut self, fee_estimator: &FeeEstimator, msg: &msgs::ClosingSigned) -> Result<(Option, Option), ChannelError> { + pub fn closing_signed(&mut self, fee_estimator: &F, msg: &msgs::ClosingSigned) -> Result<(Option, Option), ChannelError> + where F::Target: FeeEstimator + { if self.channel_state & BOTH_SIDES_SHUTDOWN_MASK != BOTH_SIDES_SHUTDOWN_MASK { return Err(ChannelError::Close("Remote end sent us a closing_signed before both sides provided a shutdown")); } @@ -3012,7 +3040,9 @@ impl Channel { /// Gets the fee we'd want to charge for adding an HTLC output to this Channel /// Allowed in any state (including after shutdown) - pub fn get_our_fee_base_msat(&self, fee_estimator: &FeeEstimator) -> u32 { + pub fn get_our_fee_base_msat(&self, fee_estimator: &F) -> u32 + where F::Target: FeeEstimator + { // For lack of a better metric, we calculate what it would cost to consolidate the new HTLC // output value back into a transaction with the regular channel output: @@ -3216,7 +3246,9 @@ impl Channel { // Methods to get unprompted messages to send to the remote end (or where we already returned // something in the handler for the message that prompted this message): - pub fn get_open_channel(&self, chain_hash: Sha256dHash, fee_estimator: &FeeEstimator) -> msgs::OpenChannel { + pub fn get_open_channel(&self, chain_hash: Sha256dHash, fee_estimator: &F) -> msgs::OpenChannel + where F::Target: FeeEstimator + { if !self.channel_outbound { panic!("Tried to open a channel for an inbound channel?"); } @@ -3330,15 +3362,24 @@ impl Channel { let their_pubkeys = self.their_pubkeys.as_ref().unwrap(); let funding_redeemscript = self.get_funding_redeemscript(); let funding_txo_script = funding_redeemscript.to_v0_p2wsh(); - self.channel_monitor = Some(ChannelMonitor::new(self.local_keys.clone(), - &self.shutdown_pubkey, self.our_to_self_delay, - &self.destination_script, (funding_txo, funding_txo_script), - &their_pubkeys.htlc_basepoint, &their_pubkeys.delayed_payment_basepoint, - self.their_to_self_delay, funding_redeemscript, self.channel_value_satoshis, - self.get_commitment_transaction_number_obscure_factor(), - self.logger.clone())); - - self.channel_monitor.as_mut().unwrap().provide_latest_remote_commitment_tx_info(&commitment_tx, Vec::new(), self.cur_remote_commitment_transaction_number, self.their_cur_commitment_point.unwrap()); + macro_rules! create_monitor { + () => { { + let mut channel_monitor = ChannelMonitor::new(self.local_keys.clone(), + &self.shutdown_pubkey, self.our_to_self_delay, + &self.destination_script, (funding_txo, funding_txo_script.clone()), + &their_pubkeys.htlc_basepoint, &their_pubkeys.delayed_payment_basepoint, + self.their_to_self_delay, funding_redeemscript.clone(), self.channel_value_satoshis, + self.get_commitment_transaction_number_obscure_factor(), + self.logger.clone()); + + channel_monitor.provide_latest_remote_commitment_tx_info(&commitment_tx, Vec::new(), self.cur_remote_commitment_transaction_number, self.their_cur_commitment_point.unwrap()); + channel_monitor + } } + } + + self.channel_monitor = Some(create_monitor!()); + let channel_monitor = create_monitor!(); + self.channel_state = ChannelState::FundingCreated as u32; self.channel_id = funding_txo.to_channel_id(); self.cur_remote_commitment_transaction_number -= 1; @@ -3348,7 +3389,7 @@ impl Channel { funding_txid: funding_txo.txid, funding_output_index: funding_txo.index, signature: our_signature - }, self.channel_monitor.as_ref().unwrap().clone())) + }, channel_monitor)) } /// Gets an UnsignedChannelAnnouncement, as well as a signature covering it using our @@ -3403,10 +3444,10 @@ impl Channel { my_current_per_commitment_point: PublicKey::from_secret_key(&self.secp_ctx, &self.build_local_commitment_secret(self.cur_local_commitment_transaction_number + 1)) }) } else { - 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"); + log_info!(self, "Sending a data_loss_protect with no previous remote per_commitment_secret"); 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)) + my_current_per_commitment_point: PublicKey::from_secret_key(&self.secp_ctx, &self.build_local_commitment_secret(self.cur_local_commitment_transaction_number + 1)) }) }; msgs::ChannelReestablish { @@ -3770,9 +3811,9 @@ impl Writeable for InboundHTLCRemovalReason { } } -impl Readable for InboundHTLCRemovalReason { - fn read(reader: &mut R) -> Result { - Ok(match >::read(reader)? { +impl Readable for InboundHTLCRemovalReason { + fn read(reader: &mut R) -> Result { + Ok(match ::read(reader)? { 0 => InboundHTLCRemovalReason::FailRelay(Readable::read(reader)?), 1 => InboundHTLCRemovalReason::FailMalformed((Readable::read(reader)?, Readable::read(reader)?)), 2 => InboundHTLCRemovalReason::Fulfill(Readable::read(reader)?), @@ -3842,18 +3883,6 @@ impl Writeable for Channel { } } - macro_rules! write_option { - ($thing: expr) => { - match &$thing { - &None => 0u8.write(writer)?, - &Some(ref v) => { - 1u8.write(writer)?; - v.write(writer)?; - }, - } - } - } - (self.pending_outbound_htlcs.len() as u64).write(writer)?; for htlc in self.pending_outbound_htlcs.iter() { htlc.htlc_id.write(writer)?; @@ -3871,15 +3900,15 @@ impl Writeable for Channel { }, &OutboundHTLCState::RemoteRemoved(ref fail_reason) => { 2u8.write(writer)?; - write_option!(*fail_reason); + fail_reason.write(writer)?; }, &OutboundHTLCState::AwaitingRemoteRevokeToRemove(ref fail_reason) => { 3u8.write(writer)?; - write_option!(*fail_reason); + fail_reason.write(writer)?; }, &OutboundHTLCState::AwaitingRemovedRemoteRevoke(ref fail_reason) => { 4u8.write(writer)?; - write_option!(*fail_reason); + fail_reason.write(writer)?; }, } } @@ -3930,8 +3959,8 @@ impl Writeable for Channel { fail_reason.write(writer)?; } - write_option!(self.pending_update_fee); - write_option!(self.holding_cell_update_fee); + self.pending_update_fee.write(writer)?; + self.holding_cell_update_fee.write(writer)?; self.next_local_htlc_id.write(writer)?; (self.next_remote_htlc_id - dropped_inbound_htlcs).write(writer)?; @@ -3948,9 +3977,9 @@ impl Writeable for Channel { None => 0u8.write(writer)?, } - write_option!(self.funding_txo); - write_option!(self.funding_tx_confirmed_in); - write_option!(self.short_channel_id); + self.funding_txo.write(writer)?; + self.funding_tx_confirmed_in.write(writer)?; + self.short_channel_id.write(writer)?; self.last_block_connected.write(writer)?; self.funding_tx_confirmations.write(writer)?; @@ -3966,13 +3995,13 @@ impl Writeable for Channel { self.their_max_accepted_htlcs.write(writer)?; self.minimum_depth.write(writer)?; - write_option!(self.their_pubkeys); - write_option!(self.their_cur_commitment_point); + self.their_pubkeys.write(writer)?; + self.their_cur_commitment_point.write(writer)?; - write_option!(self.their_prev_commitment_point); + self.their_prev_commitment_point.write(writer)?; self.their_node_id.write(writer)?; - write_option!(self.their_shutdown_scriptpubkey); + self.their_shutdown_scriptpubkey.write(writer)?; self.commitment_secrets.write(writer)?; @@ -3981,8 +4010,8 @@ impl Writeable for Channel { } } -impl> ReadableArgs> for Channel { - fn read(reader: &mut R, logger: Arc) -> Result { +impl ReadableArgs> for Channel { + fn read(reader: &mut R, logger: Arc) -> Result { let _ver: u8 = Readable::read(reader)?; let min_ver: u8 = Readable::read(reader)?; if min_ver > SERIALIZATION_VERSION { @@ -4015,7 +4044,7 @@ impl> ReadableArgs>::read(reader)? { + state: match ::read(reader)? { 1 => InboundHTLCState::AwaitingRemoteRevokeToAnnounce(Readable::read(reader)?), 2 => InboundHTLCState::AwaitingAnnouncedRemoteRevoke(Readable::read(reader)?), 3 => InboundHTLCState::Committed, @@ -4034,7 +4063,7 @@ impl> ReadableArgs>::read(reader)? { + state: match ::read(reader)? { 0 => OutboundHTLCState::LocalAnnounced(Box::new(Readable::read(reader)?)), 1 => OutboundHTLCState::Committed, 2 => OutboundHTLCState::RemoteRemoved(Readable::read(reader)?), @@ -4048,7 +4077,7 @@ impl> ReadableArgs>::read(reader)? { + holding_cell_htlc_updates.push(match ::read(reader)? { 0 => HTLCUpdateAwaitingACK::AddHTLC { amount_msat: Readable::read(reader)?, cltv_expiry: Readable::read(reader)?, @@ -4068,7 +4097,7 @@ impl> ReadableArgs>::read(reader)? { + let resend_order = match ::read(reader)? { 0 => RAACommitmentOrder::CommitmentFirst, 1 => RAACommitmentOrder::RevokeAndACKFirst, _ => return Err(DecodeError::InvalidValue), @@ -4098,7 +4127,7 @@ impl> ReadableArgs>::read(reader)? { + let last_sent_closing_fee = match ::read(reader)? { 0 => None, 1 => Some((Readable::read(reader)?, Readable::read(reader)?, Readable::read(reader)?)), _ => return Err(DecodeError::InvalidValue), @@ -4315,12 +4344,12 @@ mod tests { assert_eq!(PublicKey::from_secret_key(&secp_ctx, chan_keys.funding_key()).serialize()[..], hex::decode("023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb").unwrap()[..]); - let keys_provider: Arc> = Arc::new(Keys { chan_keys }); + let keys_provider = Keys { chan_keys }; let their_node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()); let mut config = UserConfig::default(); config.channel_options.announced_channel = false; - let mut chan = Channel::::new_outbound(&feeest, &keys_provider, their_node_id, 10000000, 100000, 42, Arc::clone(&logger), &config).unwrap(); // Nothing uses their network key in this test + let mut chan = Channel::::new_outbound(&&feeest, &&keys_provider, their_node_id, 10000000, 100000, 42, Arc::clone(&logger), &config).unwrap(); // Nothing uses their network key in this test chan.their_to_self_delay = 144; chan.our_dust_limit_satoshis = 546;