Remove SecretKey from DynamicOutputP2WSH descriptor
[rust-lightning] / lightning / src / chain / keysinterface.rs
1 //! keysinterface provides keys into rust-lightning and defines some useful enums which describe
2 //! spendable on-chain outputs which the user owns and is responsible for using just as any other
3 //! on-chain output which is theirs.
4
5 use bitcoin::blockdata::transaction::{Transaction, OutPoint, TxOut, SigHashType};
6 use bitcoin::blockdata::script::{Script, Builder};
7 use bitcoin::blockdata::opcodes;
8 use bitcoin::network::constants::Network;
9 use bitcoin::util::bip32::{ExtendedPrivKey, ExtendedPubKey, ChildNumber};
10 use bitcoin::util::bip143;
11
12 use bitcoin::hashes::{Hash, HashEngine};
13 use bitcoin::hashes::sha256::HashEngine as Sha256State;
14 use bitcoin::hashes::sha256::Hash as Sha256;
15 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
16 use bitcoin::hash_types::WPubkeyHash;
17
18 use bitcoin::secp256k1::key::{SecretKey, PublicKey};
19 use bitcoin::secp256k1::{Secp256k1, Signature, Signing};
20 use bitcoin::secp256k1;
21
22 use util::byte_utils;
23 use util::logger::Logger;
24 use util::ser::{Writeable, Writer, Readable};
25
26 use ln::chan_utils;
27 use ln::chan_utils::{TxCreationKeys, HTLCOutputInCommitment, make_funding_redeemscript, ChannelPublicKeys, LocalCommitmentTransaction};
28 use ln::msgs;
29 use ln::channelmanager::PaymentPreimage;
30
31 use std::sync::Arc;
32 use std::sync::atomic::{AtomicUsize, Ordering};
33 use std::io::Error;
34 use ln::msgs::DecodeError;
35
36 /// When on-chain outputs are created by rust-lightning (which our counterparty is not able to
37 /// claim at any point in the future) an event is generated which you must track and be able to
38 /// spend on-chain. The information needed to do this is provided in this enum, including the
39 /// outpoint describing which txid and output index is available, the full output which exists at
40 /// that txid/index, and any keys or other information required to sign.
41 #[derive(Clone, PartialEq)]
42 pub enum SpendableOutputDescriptor {
43         /// An output to a script which was provided via KeysInterface, thus you should already know
44         /// how to spend it. No keys are provided as rust-lightning was never given any keys - only the
45         /// script_pubkey as it appears in the output.
46         /// These may include outputs from a transaction punishing our counterparty or claiming an HTLC
47         /// on-chain using the payment preimage or after it has timed out.
48         StaticOutput {
49                 /// The outpoint which is spendable
50                 outpoint: OutPoint,
51                 /// The output which is referenced by the given outpoint.
52                 output: TxOut,
53         },
54         /// An output to a P2WSH script which can be spent with a single signature after a CSV delay.
55         ///
56         /// The witness in the spending input should be:
57         /// <BIP 143 signature> <empty vector> (MINIMALIF standard rule) <provided witnessScript>
58         ///
59         /// Note that the nSequence field in the spending input must be set to to_self_delay
60         /// (which means the transaction not being broadcastable until at least to_self_delay
61         /// blocks after the outpoint confirms).
62         ///
63         /// These are generally the result of a "revocable" output to us, spendable only by us unless
64         /// it is an output from us having broadcast an old state (which should never happen).
65         ///
66         /// WitnessScript may be regenerated by passing the revocation_pubkey, to_self_delay and
67         /// delayed_payment_pubkey to chan_utils::get_revokeable_redeemscript.
68         ///
69         /// To derive the delayed_payment key corresponding to the channel state, you must pass the
70         /// channel's delayed_payment_key and the provided per_commitment_point to
71         /// chan_utils::derive_private_key. The resulting key should be used to sign the spending
72         /// transaction.
73         DynamicOutputP2WSH {
74                 /// The outpoint which is spendable
75                 outpoint: OutPoint,
76                 /// Per commitment point to derive delayed_payment_key by key holder
77                 per_commitment_point: PublicKey,
78                 /// The nSequence value which must be set in the spending input to satisfy the OP_CSV in
79                 /// the witness_script.
80                 to_self_delay: u16,
81                 /// The output which is referenced by the given outpoint
82                 output: TxOut,
83                 /// The channel keys state used to proceed to derivation of signing key. Must
84                 /// be pass to KeysInterface::derive_channel_keys.
85                 key_derivation_params: (u64, u64),
86                 /// The remote_revocation_pubkey used to derive witnessScript
87                 remote_revocation_pubkey: PublicKey
88         },
89         // TODO: Note that because key is now static and exactly what is provided by us, we should drop
90         // this in favor of StaticOutput:
91         /// An output to a P2WPKH, spendable exclusively by the given private key.
92         /// The witness in the spending input, is, thus, simply:
93         /// <BIP 143 signature generated with the given key> <public key derived from the given key>
94         /// These are generally the result of our counterparty having broadcast the current state,
95         /// allowing us to claim the non-HTLC-encumbered outputs immediately.
96         DynamicOutputP2WPKH {
97                 /// The outpoint which is spendable
98                 outpoint: OutPoint,
99                 /// The secret key which must be used to sign the spending transaction
100                 key: SecretKey,
101                 /// The output which is reference by the given outpoint
102                 output: TxOut,
103         }
104 }
105
106 impl Writeable for SpendableOutputDescriptor {
107         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
108                 match self {
109                         &SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output } => {
110                                 0u8.write(writer)?;
111                                 outpoint.write(writer)?;
112                                 output.write(writer)?;
113                         },
114                         &SpendableOutputDescriptor::DynamicOutputP2WSH { ref outpoint, ref per_commitment_point, ref to_self_delay, ref output, ref key_derivation_params, ref remote_revocation_pubkey } => {
115                                 1u8.write(writer)?;
116                                 outpoint.write(writer)?;
117                                 per_commitment_point.write(writer)?;
118                                 to_self_delay.write(writer)?;
119                                 output.write(writer)?;
120                                 key_derivation_params.0.write(writer)?;
121                                 key_derivation_params.1.write(writer)?;
122                                 remote_revocation_pubkey.write(writer)?;
123                         },
124                         &SpendableOutputDescriptor::DynamicOutputP2WPKH { ref outpoint, ref key, ref output } => {
125                                 2u8.write(writer)?;
126                                 outpoint.write(writer)?;
127                                 key.write(writer)?;
128                                 output.write(writer)?;
129                         },
130                 }
131                 Ok(())
132         }
133 }
134
135 impl Readable for SpendableOutputDescriptor {
136         fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
137                 match Readable::read(reader)? {
138                         0u8 => Ok(SpendableOutputDescriptor::StaticOutput {
139                                 outpoint: Readable::read(reader)?,
140                                 output: Readable::read(reader)?,
141                         }),
142                         1u8 => Ok(SpendableOutputDescriptor::DynamicOutputP2WSH {
143                                 outpoint: Readable::read(reader)?,
144                                 per_commitment_point: Readable::read(reader)?,
145                                 to_self_delay: Readable::read(reader)?,
146                                 output: Readable::read(reader)?,
147                                 key_derivation_params: (Readable::read(reader)?, Readable::read(reader)?),
148                                 remote_revocation_pubkey: Readable::read(reader)?,
149                         }),
150                         2u8 => Ok(SpendableOutputDescriptor::DynamicOutputP2WPKH {
151                                 outpoint: Readable::read(reader)?,
152                                 key: Readable::read(reader)?,
153                                 output: Readable::read(reader)?,
154                         }),
155                         _ => Err(DecodeError::InvalidValue),
156                 }
157         }
158 }
159
160 /// A trait to describe an object which can get user secrets and key material.
161 pub trait KeysInterface: Send + Sync {
162         /// A type which implements ChannelKeys which will be returned by get_channel_keys.
163         type ChanKeySigner : ChannelKeys;
164
165         /// Get node secret key (aka node_id or network_key)
166         fn get_node_secret(&self) -> SecretKey;
167         /// Get destination redeemScript to encumber static protocol exit points.
168         fn get_destination_script(&self) -> Script;
169         /// Get shutdown_pubkey to use as PublicKey at channel closure
170         fn get_shutdown_pubkey(&self) -> PublicKey;
171         /// Get a new set of ChannelKeys for per-channel secrets. These MUST be unique even if you
172         /// restarted with some stale data!
173         fn get_channel_keys(&self, inbound: bool, channel_value_satoshis: u64) -> Self::ChanKeySigner;
174         /// Get a secret and PRNG seed for construting an onion packet
175         fn get_onion_rand(&self) -> (SecretKey, [u8; 32]);
176         /// Get a unique temporary channel id. Channels will be referred to by this until the funding
177         /// transaction is created, at which point they will use the outpoint in the funding
178         /// transaction.
179         fn get_channel_id(&self) -> [u8; 32];
180 }
181
182 /// Set of lightning keys needed to operate a channel as described in BOLT 3.
183 ///
184 /// Signing services could be implemented on a hardware wallet. In this case,
185 /// the current ChannelKeys would be a front-end on top of a communication
186 /// channel connected to your secure device and lightning key material wouldn't
187 /// reside on a hot server. Nevertheless, a this deployment would still need
188 /// to trust the ChannelManager to avoid loss of funds as this latest component
189 /// could ask to sign commitment transaction with HTLCs paying to attacker pubkeys.
190 ///
191 /// A more secure iteration would be to use hashlock (or payment points) to pair
192 /// invoice/incoming HTLCs with outgoing HTLCs to implement a no-trust-ChannelManager
193 /// at the price of more state and computation on the hardware wallet side. In the future,
194 /// we are looking forward to design such interface.
195 ///
196 /// In any case, ChannelMonitor or fallback watchtowers are always going to be trusted
197 /// to act, as liveness and breach reply correctness are always going to be hard requirements
198 /// of LN security model, orthogonal of key management issues.
199 ///
200 /// If you're implementing a custom signer, you almost certainly want to implement
201 /// Readable/Writable to serialize out a unique reference to this set of keys so
202 /// that you can serialize the full ChannelManager object.
203 ///
204 // (TODO: We shouldn't require that, and should have an API to get them at deser time, due mostly
205 // to the possibility of reentrancy issues by calling the user's code during our deserialization
206 // routine).
207 // TODO: We should remove Clone by instead requesting a new ChannelKeys copy when we create
208 // ChannelMonitors instead of expecting to clone the one out of the Channel into the monitors.
209 pub trait ChannelKeys : Send+Clone {
210         /// Gets the private key for the anchor tx
211         fn funding_key<'a>(&'a self) -> &'a SecretKey;
212         /// Gets the local secret key for blinded revocation pubkey
213         fn revocation_base_key<'a>(&'a self) -> &'a SecretKey;
214         /// Gets the local secret key used in the to_remote output of remote commitment tx (ie the
215         /// output to us in transactions our counterparty broadcasts).
216         /// Also as part of obscured commitment number.
217         fn payment_key<'a>(&'a self) -> &'a SecretKey;
218         /// Gets the local secret key used in HTLC-Success/HTLC-Timeout txn and to_local output
219         fn delayed_payment_base_key<'a>(&'a self) -> &'a SecretKey;
220         /// Gets the local htlc secret key used in commitment tx htlc outputs
221         fn htlc_base_key<'a>(&'a self) -> &'a SecretKey;
222         /// Gets the commitment seed
223         fn commitment_seed<'a>(&'a self) -> &'a [u8; 32];
224         /// Gets the local channel public keys and basepoints
225         fn pubkeys<'a>(&'a self) -> &'a ChannelPublicKeys;
226         /// Gets the key derivation parameters in case of new derivation.
227         fn key_derivation_params(&self) -> (u64, u64);
228
229         /// Create a signature for a remote commitment transaction and associated HTLC transactions.
230         ///
231         /// Note that if signing fails or is rejected, the channel will be force-closed.
232         //
233         // TODO: Document the things someone using this interface should enforce before signing.
234         // TODO: Add more input vars to enable better checking (preferably removing commitment_tx and
235         // making the callee generate it via some util function we expose)!
236         fn sign_remote_commitment<T: secp256k1::Signing + secp256k1::Verification>(&self, feerate_per_kw: u64, commitment_tx: &Transaction, keys: &TxCreationKeys, htlcs: &[&HTLCOutputInCommitment], to_self_delay: u16, secp_ctx: &Secp256k1<T>) -> Result<(Signature, Vec<Signature>), ()>;
237
238         /// Create a signature for a local commitment transaction. This will only ever be called with
239         /// the same local_commitment_tx (or a copy thereof), though there are currently no guarantees
240         /// that it will not be called multiple times.
241         //
242         // TODO: Document the things someone using this interface should enforce before signing.
243         // TODO: Add more input vars to enable better checking (preferably removing commitment_tx and
244         fn sign_local_commitment<T: secp256k1::Signing + secp256k1::Verification>(&self, local_commitment_tx: &LocalCommitmentTransaction, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()>;
245
246         /// Same as sign_local_commitment, but exists only for tests to get access to local commitment
247         /// transactions which will be broadcasted later, after the channel has moved on to a newer
248         /// state. Thus, needs its own method as sign_local_commitment may enforce that we only ever
249         /// get called once.
250         #[cfg(test)]
251         fn unsafe_sign_local_commitment<T: secp256k1::Signing + secp256k1::Verification>(&self, local_commitment_tx: &LocalCommitmentTransaction, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()>;
252
253         /// Create a signature for each HTLC transaction spending a local commitment transaction.
254         ///
255         /// Unlike sign_local_commitment, this may be called multiple times with *different*
256         /// local_commitment_tx values. While this will never be called with a revoked
257         /// local_commitment_tx, it is possible that it is called with the second-latest
258         /// local_commitment_tx (only if we haven't yet revoked it) if some watchtower/secondary
259         /// ChannelMonitor decided to broadcast before it had been updated to the latest.
260         ///
261         /// Either an Err should be returned, or a Vec with one entry for each HTLC which exists in
262         /// local_commitment_tx. For those HTLCs which have transaction_output_index set to None
263         /// (implying they were considered dust at the time the commitment transaction was negotiated),
264         /// a corresponding None should be included in the return value. All other positions in the
265         /// return value must contain a signature.
266         fn sign_local_commitment_htlc_transactions<T: secp256k1::Signing + secp256k1::Verification>(&self, local_commitment_tx: &LocalCommitmentTransaction, local_csv: u16, secp_ctx: &Secp256k1<T>) -> Result<Vec<Option<Signature>>, ()>;
267
268         /// Create a signature for a transaction spending an HTLC or commitment transaction output
269         /// when our counterparty broadcast an old state.
270         ///
271         /// Justice transaction may claim multiples outputs at same time if timelock are similar.
272         /// It may be called multiples time for same output(s) if a fee-bump is needed with regards
273         /// to an upcoming timelock expiration.
274         ///
275         /// Witness_script is a revokable witness script as defined in BOLT3 for `to_local`/HTLC
276         /// outputs.
277         ///
278         /// Input index is a pointer towards outpoint spent, commited by sigs (BIP 143).
279         ///
280         /// Amount is value of the output spent by this input, committed by sigs (BIP 143).
281         ///
282         /// Per_commitment key is revocation secret such as provided by remote party while
283         /// revocating detected onchain transaction. It's not a _local_ secret key, therefore
284         /// it may cross interfaces, a node compromise won't allow to spend revoked output without
285         /// also compromissing revocation key.
286         //TODO: dry-up witness_script and pass pubkeys
287         fn sign_justice_transaction<T: secp256k1::Signing>(&self, justice_tx: &Transaction, input: usize, witness_script: &Script, amount: u64, per_commitment_key: &SecretKey, revocation_pubkey: &PublicKey, is_htlc: bool, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()>;
288
289         /// Create a signature for a claiming transaction for a HTLC output on a remote commitment
290         /// transaction, either offered or received.
291         ///
292         /// HTLC transaction may claim multiples offered outputs at same time if we know preimage
293         /// for each at detection. It may be called multtiples time for same output(s) if a fee-bump
294         /// is needed with regards to an upcoming timelock expiration.
295         ///
296         /// Witness_script is either a offered or received script as defined in BOLT3 for HTLC
297         /// outputs.
298         ///
299         /// Input index is a pointer towards outpoint spent, commited by sigs (BIP 143).
300         ///
301         /// Amount is value of the output spent by this input, committed by sigs (BIP 143).
302         ///
303         /// Preimage is solution for an offered HTLC haslock. A preimage sets to None hints this
304         /// htlc_tx as timing-out funds back to us on a received output.
305         //TODO: dry-up witness_script and pass pubkeys
306         fn sign_remote_htlc_transaction<T: secp256k1::Signing>(&self, htlc_tx: &Transaction, input: usize, witness_script: &Script, amount: u64, per_commitment_point: &PublicKey, preimage: &Option<PaymentPreimage>, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()>;
307
308         /// Create a signature for a (proposed) closing transaction.
309         ///
310         /// Note that, due to rounding, there may be one "missing" satoshi, and either party may have
311         /// chosen to forgo their output as dust.
312         fn sign_closing_transaction<T: secp256k1::Signing>(&self, closing_tx: &Transaction, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()>;
313
314         /// Signs a channel announcement message with our funding key, proving it comes from one
315         /// of the channel participants.
316         ///
317         /// Note that if this fails or is rejected, the channel will not be publicly announced and
318         /// our counterparty may (though likely will not) close the channel on us for violating the
319         /// protocol.
320         fn sign_channel_announcement<T: secp256k1::Signing>(&self, msg: &msgs::UnsignedChannelAnnouncement, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()>;
321
322         /// Set the remote channel basepoints.  This is done immediately on incoming channels
323         /// and as soon as the channel is accepted on outgoing channels.
324         ///
325         /// Will be called before any signatures are applied.
326         fn set_remote_channel_pubkeys(&mut self, channel_points: &ChannelPublicKeys);
327 }
328
329 #[derive(Clone)]
330 /// A simple implementation of ChannelKeys that just keeps the private keys in memory.
331 pub struct InMemoryChannelKeys {
332         /// Private key of anchor tx
333         funding_key: SecretKey,
334         /// Local secret key for blinded revocation pubkey
335         revocation_base_key: SecretKey,
336         /// Local secret key used for our balance in remote-broadcasted commitment transactions
337         payment_key: SecretKey,
338         /// Local secret key used in HTLC tx
339         delayed_payment_base_key: SecretKey,
340         /// Local htlc secret key used in commitment tx htlc outputs
341         htlc_base_key: SecretKey,
342         /// Commitment seed
343         commitment_seed: [u8; 32],
344         /// Local public keys and basepoints
345         pub(crate) local_channel_pubkeys: ChannelPublicKeys,
346         /// Remote public keys and base points
347         pub(crate) remote_channel_pubkeys: Option<ChannelPublicKeys>,
348         /// The total value of this channel
349         channel_value_satoshis: u64,
350         /// Key derivation parameters
351         key_derivation_params: (u64, u64),
352 }
353
354 impl InMemoryChannelKeys {
355         /// Create a new InMemoryChannelKeys
356         pub fn new<C: Signing>(
357                 secp_ctx: &Secp256k1<C>,
358                 funding_key: SecretKey,
359                 revocation_base_key: SecretKey,
360                 payment_key: SecretKey,
361                 delayed_payment_base_key: SecretKey,
362                 htlc_base_key: SecretKey,
363                 commitment_seed: [u8; 32],
364                 channel_value_satoshis: u64,
365                 key_derivation_params: (u64, u64)) -> InMemoryChannelKeys {
366                 let local_channel_pubkeys =
367                         InMemoryChannelKeys::make_local_keys(secp_ctx, &funding_key, &revocation_base_key,
368                                                              &payment_key, &delayed_payment_base_key,
369                                                              &htlc_base_key);
370                 InMemoryChannelKeys {
371                         funding_key,
372                         revocation_base_key,
373                         payment_key,
374                         delayed_payment_base_key,
375                         htlc_base_key,
376                         commitment_seed,
377                         channel_value_satoshis,
378                         local_channel_pubkeys,
379                         remote_channel_pubkeys: None,
380                         key_derivation_params,
381                 }
382         }
383
384         fn make_local_keys<C: Signing>(secp_ctx: &Secp256k1<C>,
385                                        funding_key: &SecretKey,
386                                        revocation_base_key: &SecretKey,
387                                        payment_key: &SecretKey,
388                                        delayed_payment_base_key: &SecretKey,
389                                        htlc_base_key: &SecretKey) -> ChannelPublicKeys {
390                 let from_secret = |s: &SecretKey| PublicKey::from_secret_key(secp_ctx, s);
391                 ChannelPublicKeys {
392                         funding_pubkey: from_secret(&funding_key),
393                         revocation_basepoint: from_secret(&revocation_base_key),
394                         payment_point: from_secret(&payment_key),
395                         delayed_payment_basepoint: from_secret(&delayed_payment_base_key),
396                         htlc_basepoint: from_secret(&htlc_base_key),
397                 }
398         }
399 }
400
401 impl ChannelKeys for InMemoryChannelKeys {
402         fn funding_key(&self) -> &SecretKey { &self.funding_key }
403         fn revocation_base_key(&self) -> &SecretKey { &self.revocation_base_key }
404         fn payment_key(&self) -> &SecretKey { &self.payment_key }
405         fn delayed_payment_base_key(&self) -> &SecretKey { &self.delayed_payment_base_key }
406         fn htlc_base_key(&self) -> &SecretKey { &self.htlc_base_key }
407         fn commitment_seed(&self) -> &[u8; 32] { &self.commitment_seed }
408         fn pubkeys<'a>(&'a self) -> &'a ChannelPublicKeys { &self.local_channel_pubkeys }
409         fn key_derivation_params(&self) -> (u64, u64) { self.key_derivation_params }
410
411         fn sign_remote_commitment<T: secp256k1::Signing + secp256k1::Verification>(&self, feerate_per_kw: u64, commitment_tx: &Transaction, keys: &TxCreationKeys, htlcs: &[&HTLCOutputInCommitment], to_self_delay: u16, secp_ctx: &Secp256k1<T>) -> Result<(Signature, Vec<Signature>), ()> {
412                 if commitment_tx.input.len() != 1 { return Err(()); }
413
414                 let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
415                 let remote_channel_pubkeys = self.remote_channel_pubkeys.as_ref().expect("must set remote channel pubkeys before signing");
416                 let channel_funding_redeemscript = make_funding_redeemscript(&funding_pubkey, &remote_channel_pubkeys.funding_pubkey);
417
418                 let commitment_sighash = hash_to_message!(&bip143::SighashComponents::new(&commitment_tx).sighash_all(&commitment_tx.input[0], &channel_funding_redeemscript, self.channel_value_satoshis)[..]);
419                 let commitment_sig = secp_ctx.sign(&commitment_sighash, &self.funding_key);
420
421                 let commitment_txid = commitment_tx.txid();
422
423                 let mut htlc_sigs = Vec::with_capacity(htlcs.len());
424                 for ref htlc in htlcs {
425                         if let Some(_) = htlc.transaction_output_index {
426                                 let htlc_tx = chan_utils::build_htlc_transaction(&commitment_txid, feerate_per_kw, to_self_delay, htlc, &keys.a_delayed_payment_key, &keys.revocation_key);
427                                 let htlc_redeemscript = chan_utils::get_htlc_redeemscript(&htlc, &keys);
428                                 let htlc_sighash = hash_to_message!(&bip143::SighashComponents::new(&htlc_tx).sighash_all(&htlc_tx.input[0], &htlc_redeemscript, htlc.amount_msat / 1000)[..]);
429                                 let our_htlc_key = match chan_utils::derive_private_key(&secp_ctx, &keys.per_commitment_point, &self.htlc_base_key) {
430                                         Ok(s) => s,
431                                         Err(_) => return Err(()),
432                                 };
433                                 htlc_sigs.push(secp_ctx.sign(&htlc_sighash, &our_htlc_key));
434                         }
435                 }
436
437                 Ok((commitment_sig, htlc_sigs))
438         }
439
440         fn sign_local_commitment<T: secp256k1::Signing + secp256k1::Verification>(&self, local_commitment_tx: &LocalCommitmentTransaction, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()> {
441                 let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
442                 let remote_channel_pubkeys = self.remote_channel_pubkeys.as_ref().expect("must set remote channel pubkeys before signing");
443                 let channel_funding_redeemscript = make_funding_redeemscript(&funding_pubkey, &remote_channel_pubkeys.funding_pubkey);
444
445                 Ok(local_commitment_tx.get_local_sig(&self.funding_key, &channel_funding_redeemscript, self.channel_value_satoshis, secp_ctx))
446         }
447
448         #[cfg(test)]
449         fn unsafe_sign_local_commitment<T: secp256k1::Signing + secp256k1::Verification>(&self, local_commitment_tx: &LocalCommitmentTransaction, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()> {
450                 let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
451                 let remote_channel_pubkeys = self.remote_channel_pubkeys.as_ref().expect("must set remote channel pubkeys before signing");
452                 let channel_funding_redeemscript = make_funding_redeemscript(&funding_pubkey, &remote_channel_pubkeys.funding_pubkey);
453
454                 Ok(local_commitment_tx.get_local_sig(&self.funding_key, &channel_funding_redeemscript, self.channel_value_satoshis, secp_ctx))
455         }
456
457         fn sign_local_commitment_htlc_transactions<T: secp256k1::Signing + secp256k1::Verification>(&self, local_commitment_tx: &LocalCommitmentTransaction, local_csv: u16, secp_ctx: &Secp256k1<T>) -> Result<Vec<Option<Signature>>, ()> {
458                 local_commitment_tx.get_htlc_sigs(&self.htlc_base_key, local_csv, secp_ctx)
459         }
460
461         fn sign_justice_transaction<T: secp256k1::Signing>(&self, justice_tx: &Transaction, input: usize, witness_script: &Script, amount: u64, per_commitment_key: &SecretKey, revocation_pubkey: &PublicKey, is_htlc: bool, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()> {
462                 if let Ok(revocation_key) = chan_utils::derive_private_revocation_key(&secp_ctx, &per_commitment_key, &self.revocation_base_key) {
463                         let sighash_parts = bip143::SighashComponents::new(&justice_tx);
464                         let sighash = hash_to_message!(&sighash_parts.sighash_all(&justice_tx.input[input], &witness_script, amount)[..]);
465                         return Ok(secp_ctx.sign(&sighash, &revocation_key))
466                 }
467                 Err(())
468         }
469
470         fn sign_remote_htlc_transaction<T: secp256k1::Signing>(&self, htlc_tx: &Transaction, input: usize, witness_script: &Script, amount: u64, per_commitment_point: &PublicKey, preimage: &Option<PaymentPreimage>, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()> {
471                 if let Ok(htlc_key) = chan_utils::derive_private_key(&secp_ctx, &per_commitment_point, &self.htlc_base_key) {
472                         let sighash_parts = bip143::SighashComponents::new(&htlc_tx);
473                         let sighash = hash_to_message!(&sighash_parts.sighash_all(&htlc_tx.input[input], &witness_script, amount)[..]);
474                         return Ok(secp_ctx.sign(&sighash, &htlc_key))
475                 }
476                 Err(())
477         }
478
479         fn sign_closing_transaction<T: secp256k1::Signing>(&self, closing_tx: &Transaction, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()> {
480                 if closing_tx.input.len() != 1 { return Err(()); }
481                 if closing_tx.input[0].witness.len() != 0 { return Err(()); }
482                 if closing_tx.output.len() > 2 { return Err(()); }
483
484                 let remote_channel_pubkeys = self.remote_channel_pubkeys.as_ref().expect("must set remote channel pubkeys before signing");
485                 let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
486                 let channel_funding_redeemscript = make_funding_redeemscript(&funding_pubkey, &remote_channel_pubkeys.funding_pubkey);
487
488                 let sighash = hash_to_message!(&bip143::SighashComponents::new(closing_tx)
489                         .sighash_all(&closing_tx.input[0], &channel_funding_redeemscript, self.channel_value_satoshis)[..]);
490                 Ok(secp_ctx.sign(&sighash, &self.funding_key))
491         }
492
493         fn sign_channel_announcement<T: secp256k1::Signing>(&self, msg: &msgs::UnsignedChannelAnnouncement, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()> {
494                 let msghash = hash_to_message!(&Sha256dHash::hash(&msg.encode()[..])[..]);
495                 Ok(secp_ctx.sign(&msghash, &self.funding_key))
496         }
497
498         fn set_remote_channel_pubkeys(&mut self, channel_pubkeys: &ChannelPublicKeys) {
499                 assert!(self.remote_channel_pubkeys.is_none(), "Already set remote channel pubkeys");
500                 self.remote_channel_pubkeys = Some(channel_pubkeys.clone());
501         }
502 }
503
504 impl Writeable for InMemoryChannelKeys {
505         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), Error> {
506                 self.funding_key.write(writer)?;
507                 self.revocation_base_key.write(writer)?;
508                 self.payment_key.write(writer)?;
509                 self.delayed_payment_base_key.write(writer)?;
510                 self.htlc_base_key.write(writer)?;
511                 self.commitment_seed.write(writer)?;
512                 self.remote_channel_pubkeys.write(writer)?;
513                 self.channel_value_satoshis.write(writer)?;
514                 self.key_derivation_params.0.write(writer)?;
515                 self.key_derivation_params.1.write(writer)?;
516
517                 Ok(())
518         }
519 }
520
521 impl Readable for InMemoryChannelKeys {
522         fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
523                 let funding_key = Readable::read(reader)?;
524                 let revocation_base_key = Readable::read(reader)?;
525                 let payment_key = Readable::read(reader)?;
526                 let delayed_payment_base_key = Readable::read(reader)?;
527                 let htlc_base_key = Readable::read(reader)?;
528                 let commitment_seed = Readable::read(reader)?;
529                 let remote_channel_pubkeys = Readable::read(reader)?;
530                 let channel_value_satoshis = Readable::read(reader)?;
531                 let secp_ctx = Secp256k1::signing_only();
532                 let local_channel_pubkeys =
533                         InMemoryChannelKeys::make_local_keys(&secp_ctx, &funding_key, &revocation_base_key,
534                                                              &payment_key, &delayed_payment_base_key,
535                                                              &htlc_base_key);
536                 let user_id_1 = Readable::read(reader)?;
537                 let user_id_2 = Readable::read(reader)?;
538
539                 Ok(InMemoryChannelKeys {
540                         funding_key,
541                         revocation_base_key,
542                         payment_key,
543                         delayed_payment_base_key,
544                         htlc_base_key,
545                         commitment_seed,
546                         channel_value_satoshis,
547                         local_channel_pubkeys,
548                         remote_channel_pubkeys,
549                         key_derivation_params: (user_id_1, user_id_2),
550                 })
551         }
552 }
553
554 /// Simple KeysInterface implementor that takes a 32-byte seed for use as a BIP 32 extended key
555 /// and derives keys from that.
556 ///
557 /// Your node_id is seed/0'
558 /// ChannelMonitor closes may use seed/1'
559 /// Cooperative closes may use seed/2'
560 /// The two close keys may be needed to claim on-chain funds!
561 pub struct KeysManager {
562         secp_ctx: Secp256k1<secp256k1::SignOnly>,
563         node_secret: SecretKey,
564         destination_script: Script,
565         shutdown_pubkey: PublicKey,
566         channel_master_key: ExtendedPrivKey,
567         channel_child_index: AtomicUsize,
568         session_master_key: ExtendedPrivKey,
569         session_child_index: AtomicUsize,
570         channel_id_master_key: ExtendedPrivKey,
571         channel_id_child_index: AtomicUsize,
572
573         seed: [u8; 32],
574         starting_time_secs: u64,
575         starting_time_nanos: u32,
576         logger: Arc<Logger>,
577 }
578
579 impl KeysManager {
580         /// Constructs a KeysManager from a 32-byte seed. If the seed is in some way biased (eg your
581         /// RNG is busted) this may panic (but more importantly, you will possibly lose funds).
582         /// starting_time isn't strictly required to actually be a time, but it must absolutely,
583         /// without a doubt, be unique to this instance. ie if you start multiple times with the same
584         /// seed, starting_time must be unique to each run. Thus, the easiest way to achieve this is to
585         /// simply use the current time (with very high precision).
586         ///
587         /// The seed MUST be backed up safely prior to use so that the keys can be re-created, however,
588         /// obviously, starting_time should be unique every time you reload the library - it is only
589         /// used to generate new ephemeral key data (which will be stored by the individual channel if
590         /// necessary).
591         ///
592         /// Note that the seed is required to recover certain on-chain funds independent of
593         /// ChannelMonitor data, though a current copy of ChannelMonitor data is also required for any
594         /// channel, and some on-chain during-closing funds.
595         ///
596         /// Note that until the 0.1 release there is no guarantee of backward compatibility between
597         /// versions. Once the library is more fully supported, the docs will be updated to include a
598         /// detailed description of the guarantee.
599         pub fn new(seed: &[u8; 32], network: Network, logger: Arc<Logger>, starting_time_secs: u64, starting_time_nanos: u32) -> KeysManager {
600                 let secp_ctx = Secp256k1::signing_only();
601                 match ExtendedPrivKey::new_master(network.clone(), seed) {
602                         Ok(master_key) => {
603                                 let node_secret = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(0).unwrap()).expect("Your RNG is busted").private_key.key;
604                                 let destination_script = match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(1).unwrap()) {
605                                         Ok(destination_key) => {
606                                                 let wpubkey_hash = WPubkeyHash::hash(&ExtendedPubKey::from_private(&secp_ctx, &destination_key).public_key.to_bytes());
607                                                 Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0)
608                                                               .push_slice(&wpubkey_hash.into_inner())
609                                                               .into_script()
610                                         },
611                                         Err(_) => panic!("Your RNG is busted"),
612                                 };
613                                 let shutdown_pubkey = match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(2).unwrap()) {
614                                         Ok(shutdown_key) => ExtendedPubKey::from_private(&secp_ctx, &shutdown_key).public_key.key,
615                                         Err(_) => panic!("Your RNG is busted"),
616                                 };
617                                 let channel_master_key = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(3).unwrap()).expect("Your RNG is busted");
618                                 let session_master_key = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(4).unwrap()).expect("Your RNG is busted");
619                                 let channel_id_master_key = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(5).unwrap()).expect("Your RNG is busted");
620
621                                 KeysManager {
622                                         secp_ctx,
623                                         node_secret,
624                                         destination_script,
625                                         shutdown_pubkey,
626                                         channel_master_key,
627                                         channel_child_index: AtomicUsize::new(0),
628                                         session_master_key,
629                                         session_child_index: AtomicUsize::new(0),
630                                         channel_id_master_key,
631                                         channel_id_child_index: AtomicUsize::new(0),
632
633                                         seed: *seed,
634                                         starting_time_secs,
635                                         starting_time_nanos,
636                                         logger,
637                                 }
638                         },
639                         Err(_) => panic!("Your rng is busted"),
640                 }
641         }
642         fn derive_unique_start(&self) -> Sha256State {
643                 let mut unique_start = Sha256::engine();
644                 unique_start.input(&byte_utils::be64_to_array(self.starting_time_secs));
645                 unique_start.input(&byte_utils::be32_to_array(self.starting_time_nanos));
646                 unique_start.input(&self.seed);
647                 unique_start
648         }
649         /// Derive an old set of ChannelKeys for per-channel secrets based on a key derivation
650         /// parameters.
651         /// Key derivation parameters are accessible through a per-channel secrets
652         /// ChannelKeys::key_derivation_params and is provided inside DynamicOuputP2WSH in case of
653         /// onchain output detection for which a corresponding delayed_payment_key must be derived.
654         pub fn derive_channel_keys(&self, channel_value_satoshis: u64, user_id_1: u64, user_id_2: u64) -> InMemoryChannelKeys {
655                 let chan_id = ((user_id_1 & 0xFFFF0000) >> 32) as u32;
656                 let mut unique_start = Sha256::engine();
657                 unique_start.input(&byte_utils::be64_to_array(user_id_2));
658                 unique_start.input(&byte_utils::be32_to_array(user_id_1 as u32));
659                 unique_start.input(&self.seed);
660
661                 // We only seriously intend to rely on the channel_master_key for true secure
662                 // entropy, everything else just ensures uniqueness. We rely on the unique_start (ie
663                 // starting_time provided in the constructor) to be unique.
664                 let mut sha = self.derive_unique_start();
665
666                 let child_privkey = self.channel_master_key.ckd_priv(&self.secp_ctx, ChildNumber::from_hardened_idx(chan_id).expect("key space exhausted")).expect("Your RNG is busted");
667                 sha.input(&child_privkey.private_key.key[..]);
668
669                 let seed = Sha256::from_engine(sha).into_inner();
670
671                 let commitment_seed = {
672                         let mut sha = Sha256::engine();
673                         sha.input(&seed);
674                         sha.input(&b"commitment seed"[..]);
675                         Sha256::from_engine(sha).into_inner()
676                 };
677                 macro_rules! key_step {
678                         ($info: expr, $prev_key: expr) => {{
679                                 let mut sha = Sha256::engine();
680                                 sha.input(&seed);
681                                 sha.input(&$prev_key[..]);
682                                 sha.input(&$info[..]);
683                                 SecretKey::from_slice(&Sha256::from_engine(sha).into_inner()).expect("SHA-256 is busted")
684                         }}
685                 }
686                 let funding_key = key_step!(b"funding key", commitment_seed);
687                 let revocation_base_key = key_step!(b"revocation base key", funding_key);
688                 let payment_key = key_step!(b"payment key", revocation_base_key);
689                 let delayed_payment_base_key = key_step!(b"delayed payment base key", payment_key);
690                 let htlc_base_key = key_step!(b"HTLC base key", delayed_payment_base_key);
691
692                 InMemoryChannelKeys::new(
693                         &self.secp_ctx,
694                         funding_key,
695                         revocation_base_key,
696                         payment_key,
697                         delayed_payment_base_key,
698                         htlc_base_key,
699                         commitment_seed,
700                         channel_value_satoshis,
701                         (user_id_1, user_id_2),
702                 )
703         }
704 }
705
706 impl KeysInterface for KeysManager {
707         type ChanKeySigner = InMemoryChannelKeys;
708
709         fn get_node_secret(&self) -> SecretKey {
710                 self.node_secret.clone()
711         }
712
713         fn get_destination_script(&self) -> Script {
714                 self.destination_script.clone()
715         }
716
717         fn get_shutdown_pubkey(&self) -> PublicKey {
718                 self.shutdown_pubkey.clone()
719         }
720
721         fn get_channel_keys(&self, _inbound: bool, channel_value_satoshis: u64) -> InMemoryChannelKeys {
722                 let child_ix = self.channel_child_index.fetch_add(1, Ordering::AcqRel);
723                 let ix_and_nanos: u64 = (child_ix as u64) << 32 | (self.starting_time_nanos as u64);
724                 self.derive_channel_keys(channel_value_satoshis, ix_and_nanos, self.starting_time_secs)
725         }
726
727         fn get_onion_rand(&self) -> (SecretKey, [u8; 32]) {
728                 let mut sha = self.derive_unique_start();
729
730                 let child_ix = self.session_child_index.fetch_add(1, Ordering::AcqRel);
731                 let child_privkey = self.session_master_key.ckd_priv(&self.secp_ctx, ChildNumber::from_hardened_idx(child_ix as u32).expect("key space exhausted")).expect("Your RNG is busted");
732                 sha.input(&child_privkey.private_key.key[..]);
733
734                 let mut rng_seed = sha.clone();
735                 // Not exactly the most ideal construction, but the second value will get fed into
736                 // ChaCha so it is another step harder to break.
737                 rng_seed.input(b"RNG Seed Salt");
738                 sha.input(b"Session Key Salt");
739                 (SecretKey::from_slice(&Sha256::from_engine(sha).into_inner()).expect("Your RNG is busted"),
740                 Sha256::from_engine(rng_seed).into_inner())
741         }
742
743         fn get_channel_id(&self) -> [u8; 32] {
744                 let mut sha = self.derive_unique_start();
745
746                 let child_ix = self.channel_id_child_index.fetch_add(1, Ordering::AcqRel);
747                 let child_privkey = self.channel_id_master_key.ckd_priv(&self.secp_ctx, ChildNumber::from_hardened_idx(child_ix as u32).expect("key space exhausted")).expect("Your RNG is busted");
748                 sha.input(&child_privkey.private_key.key[..]);
749
750                 Sha256::from_engine(sha).into_inner()
751         }
752 }