Drop Clone requirement from Sign
[rust-lightning] / lightning / src / ln / channel.rs
index debd4dfcf15297023e0fe88b9b04637cc6d43bcb..81372ee3da862cb35908da437e2a2fe578ef75f2 100644 (file)
@@ -34,7 +34,7 @@ use crate::chain::BestBlock;
 use crate::chain::chaininterface::{FeeEstimator, ConfirmationTarget, LowerBoundedFeeEstimator};
 use crate::chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateStep, LATENCY_GRACE_PERIOD_BLOCKS};
 use crate::chain::transaction::{OutPoint, TransactionData};
-use crate::chain::keysinterface::{Sign, KeysInterface};
+use crate::chain::keysinterface::{Sign, KeysInterface, BaseSign};
 use crate::util::events::ClosureReason;
 use crate::util::ser::{Readable, ReadableArgs, Writeable, Writer, VecWriter};
 use crate::util::logger::Logger;
@@ -737,6 +737,10 @@ pub(super) struct Channel<Signer: Sign> {
 
        // We track whether we already emitted a `ChannelReady` event.
        channel_ready_event_emitted: bool,
+
+       /// The unique identifier used to re-derive the private key material for the channel through
+       /// [`KeysInterface::derive_channel_signer`].
+       channel_keys_id: [u8; 32],
 }
 
 #[cfg(any(test, fuzzing))]
@@ -1072,6 +1076,7 @@ impl<Signer: Sign> Channel<Signer> {
                        historical_inbound_htlc_fulfills: HashSet::new(),
 
                        channel_type: Self::get_initial_channel_type(&config),
+                       channel_keys_id,
                })
        }
 
@@ -1419,6 +1424,7 @@ impl<Signer: Sign> Channel<Signer> {
                        historical_inbound_htlc_fulfills: HashSet::new(),
 
                        channel_type,
+                       channel_keys_id,
                };
 
                Ok(chan)
@@ -2192,7 +2198,13 @@ impl<Signer: Sign> Channel<Signer> {
                &self.get_counterparty_pubkeys().funding_pubkey
        }
 
-       pub fn funding_created<L: Deref>(&mut self, msg: &msgs::FundingCreated, best_block: BestBlock, logger: &L) -> Result<(msgs::FundingSigned, ChannelMonitor<Signer>, Option<msgs::ChannelReady>), ChannelError> where L::Target: Logger {
+       pub fn funding_created<K: Deref, L: Deref>(
+               &mut self, msg: &msgs::FundingCreated, best_block: BestBlock, keys_source: &K, logger: &L
+       ) -> Result<(msgs::FundingSigned, ChannelMonitor<<K::Target as KeysInterface>::Signer>, Option<msgs::ChannelReady>), ChannelError>
+       where
+               K::Target: KeysInterface,
+               L::Target: Logger
+       {
                if self.is_outbound() {
                        return Err(ChannelError::Close("Received funding_created for an outbound channel?".to_owned()));
                }
@@ -2247,7 +2259,9 @@ impl<Signer: Sign> Channel<Signer> {
                let funding_txo_script = funding_redeemscript.to_v0_p2wsh();
                let obscure_factor = get_commitment_transaction_number_obscure_factor(&self.get_holder_pubkeys().payment_point, &self.get_counterparty_pubkeys().payment_point, self.is_outbound());
                let shutdown_script = self.shutdown_scriptpubkey.clone().map(|script| script.into_inner());
-               let channel_monitor = ChannelMonitor::new(self.secp_ctx.clone(), self.holder_signer.clone(),
+               let mut monitor_signer = keys_source.derive_channel_signer(self.channel_value_satoshis, self.channel_keys_id);
+               monitor_signer.provide_channel_parameters(&self.channel_transaction_parameters);
+               let channel_monitor = ChannelMonitor::new(self.secp_ctx.clone(), monitor_signer,
                                                          shutdown_script, self.get_holder_selected_contest_delay(),
                                                          &self.destination_script, (funding_txo, funding_txo_script.clone()),
                                                          &self.channel_transaction_parameters,
@@ -2272,7 +2286,13 @@ impl<Signer: Sign> Channel<Signer> {
 
        /// Handles a funding_signed message from the remote end.
        /// If this call is successful, broadcast the funding transaction (and not before!)
-       pub fn funding_signed<L: Deref>(&mut self, msg: &msgs::FundingSigned, best_block: BestBlock, logger: &L) -> Result<(ChannelMonitor<Signer>, Transaction, Option<msgs::ChannelReady>), ChannelError> where L::Target: Logger {
+       pub fn funding_signed<K: Deref, L: Deref>(
+               &mut self, msg: &msgs::FundingSigned, best_block: BestBlock, keys_source: &K, logger: &L
+       ) -> Result<(ChannelMonitor<<K::Target as KeysInterface>::Signer>, Transaction, Option<msgs::ChannelReady>), ChannelError>
+       where
+               K::Target: KeysInterface,
+               L::Target: Logger
+       {
                if !self.is_outbound() {
                        return Err(ChannelError::Close("Received funding_signed for an inbound channel?".to_owned()));
                }
@@ -2324,7 +2344,9 @@ impl<Signer: Sign> Channel<Signer> {
                let funding_txo_script = funding_redeemscript.to_v0_p2wsh();
                let obscure_factor = get_commitment_transaction_number_obscure_factor(&self.get_holder_pubkeys().payment_point, &self.get_counterparty_pubkeys().payment_point, self.is_outbound());
                let shutdown_script = self.shutdown_scriptpubkey.clone().map(|script| script.into_inner());
-               let channel_monitor = ChannelMonitor::new(self.secp_ctx.clone(), self.holder_signer.clone(),
+               let mut monitor_signer = keys_source.derive_channel_signer(self.channel_value_satoshis, self.channel_keys_id);
+               monitor_signer.provide_channel_parameters(&self.channel_transaction_parameters);
+               let channel_monitor = ChannelMonitor::new(self.secp_ctx.clone(), monitor_signer,
                                                          shutdown_script, self.get_holder_selected_contest_delay(),
                                                          &self.destination_script, (funding_txo, funding_txo_script),
                                                          &self.channel_transaction_parameters,
@@ -5936,7 +5958,7 @@ impl<Signer: Sign> Channel<Signer> {
        }
 }
 
-const SERIALIZATION_VERSION: u8 = 2;
+const SERIALIZATION_VERSION: u8 = 3;
 const MIN_SERIALIZATION_VERSION: u8 = 2;
 
 impl_writeable_tlv_based_enum!(InboundHTLCRemovalReason,;
@@ -5998,7 +6020,7 @@ impl<Signer: Sign> Writeable for Channel<Signer> {
                // Note that we write out as if remove_uncommitted_htlcs_and_mark_paused had just been
                // called.
 
-               write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
+               write_ver_prefix!(writer, MIN_SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
 
                // `user_id` used to be a single u64 value. In order to remain backwards compatible with
                // versions prior to 0.0.113, the u128 is serialized as two separate u64 values. We write
@@ -6280,6 +6302,7 @@ impl<Signer: Sign> Writeable for Channel<Signer> {
                        (21, self.outbound_scid_alias, required),
                        (23, channel_ready_event_emitted, option),
                        (25, user_id_high_opt, option),
+                       (27, self.channel_keys_id, required),
                });
 
                Ok(())
@@ -6316,16 +6339,20 @@ impl<'a, K: Deref> ReadableArgs<(&'a K, u32)> for Channel<<K::Target as KeysInte
 
                let latest_monitor_update_id = Readable::read(reader)?;
 
-               let keys_len: u32 = Readable::read(reader)?;
-               let mut keys_data = Vec::with_capacity(cmp::min(keys_len as usize, MAX_ALLOC_SIZE));
-               while keys_data.len() != keys_len as usize {
-                       // Read 1KB at a time to avoid accidentally allocating 4GB on corrupted channel keys
-                       let mut data = [0; 1024];
-                       let read_slice = &mut data[0..cmp::min(1024, keys_len as usize - keys_data.len())];
-                       reader.read_exact(read_slice)?;
-                       keys_data.extend_from_slice(read_slice);
+               let mut keys_data = None;
+               if ver <= 2 {
+                       // Read the serialize signer bytes. We'll choose to deserialize them or not based on whether
+                       // the `channel_keys_id` TLV is present below.
+                       let keys_len: u32 = Readable::read(reader)?;
+                       keys_data = Some(Vec::with_capacity(cmp::min(keys_len as usize, MAX_ALLOC_SIZE)));
+                       while keys_data.as_ref().unwrap().len() != keys_len as usize {
+                               // Read 1KB at a time to avoid accidentally allocating 4GB on corrupted channel keys
+                               let mut data = [0; 1024];
+                               let read_slice = &mut data[0..cmp::min(1024, keys_len as usize - keys_data.as_ref().unwrap().len())];
+                               reader.read_exact(read_slice)?;
+                               keys_data.as_mut().unwrap().extend_from_slice(read_slice);
+                       }
                }
-               let holder_signer = keys_source.read_chan_signer(&keys_data)?;
 
                // Read the old serialization for shutdown_pubkey, preferring the TLV field later if set.
                let mut shutdown_scriptpubkey = match <PublicKey as Readable>::read(reader) {
@@ -6543,6 +6570,7 @@ impl<'a, K: Deref> ReadableArgs<(&'a K, u32)> for Channel<<K::Target as KeysInte
                let mut channel_ready_event_emitted = None;
 
                let mut user_id_high_opt: Option<u64> = None;
+               let mut channel_keys_id: Option<[u8; 32]> = None;
 
                read_tlv_fields!(reader, {
                        (0, announcement_sigs, option),
@@ -6562,8 +6590,25 @@ impl<'a, K: Deref> ReadableArgs<(&'a K, u32)> for Channel<<K::Target as KeysInte
                        (21, outbound_scid_alias, option),
                        (23, channel_ready_event_emitted, option),
                        (25, user_id_high_opt, option),
+                       (27, channel_keys_id, option),
                });
 
+               let (channel_keys_id, holder_signer) = if let Some(channel_keys_id) = channel_keys_id {
+                       let mut holder_signer = keys_source.derive_channel_signer(channel_value_satoshis, channel_keys_id);
+                       // If we've gotten to the funding stage of the channel, populate the signer with its
+                       // required channel parameters.
+                       let non_shutdown_state = channel_state & (!MULTI_STATE_FLAGS);
+                       if non_shutdown_state >= (ChannelState::FundingCreated as u32) {
+                               holder_signer.provide_channel_parameters(&channel_parameters);
+                       }
+                       (channel_keys_id, holder_signer)
+               } else {
+                       // `keys_data` can be `None` if we had corrupted data.
+                       let keys_data = keys_data.ok_or(DecodeError::InvalidValue)?;
+                       let holder_signer = keys_source.read_chan_signer(&keys_data)?;
+                       (holder_signer.channel_keys_id(), holder_signer)
+               };
+
                if let Some(preimages) = preimages_opt {
                        let mut iter = preimages.into_iter();
                        for htlc in pending_outbound_htlcs.iter_mut() {
@@ -6713,6 +6758,7 @@ impl<'a, K: Deref> ReadableArgs<(&'a K, u32)> for Channel<<K::Target as KeysInte
                        historical_inbound_htlc_fulfills,
 
                        channel_type: channel_type.unwrap(),
+                       channel_keys_id,
                })
        }
 }
@@ -7023,10 +7069,10 @@ mod tests {
                }]};
                let funding_outpoint = OutPoint{ txid: tx.txid(), index: 0 };
                let funding_created_msg = node_a_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap();
-               let (funding_signed_msg, _, _) = node_b_chan.funding_created(&funding_created_msg, best_block, &&logger).unwrap();
+               let (funding_signed_msg, _, _) = node_b_chan.funding_created(&funding_created_msg, best_block, &&keys_provider, &&logger).unwrap();
 
                // Node B --> Node A: funding signed
-               let _ = node_a_chan.funding_signed(&funding_signed_msg, best_block, &&logger);
+               let _ = node_a_chan.funding_signed(&funding_signed_msg, best_block, &&keys_provider, &&logger);
 
                // Now disconnect the two nodes and check that the commitment point in
                // Node B's channel_reestablish message is sane.