Remove signing local commitment transaction from ChannelMonitor
[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};
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_hashes::hash160::Hash as Hash160;
17
18 use secp256k1::key::{SecretKey, PublicKey};
19 use secp256k1::{Secp256k1, Signature, Signing};
20 use 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
30 use std::sync::Arc;
31 use std::sync::atomic::{AtomicUsize, Ordering};
32 use std::io::Error;
33 use ln::msgs::DecodeError;
34
35 /// When on-chain outputs are created by rust-lightning (which our counterparty is not able to
36 /// claim at any point in the future) an event is generated which you must track and be able to
37 /// spend on-chain. The information needed to do this is provided in this enum, including the
38 /// outpoint describing which txid and output index is available, the full output which exists at
39 /// that txid/index, and any keys or other information required to sign.
40 #[derive(Clone, PartialEq)]
41 pub enum SpendableOutputDescriptor {
42         /// An output to a script which was provided via KeysInterface, thus you should already know
43         /// how to spend it. No keys are provided as rust-lightning was never given any keys - only the
44         /// script_pubkey as it appears in the output.
45         /// These may include outputs from a transaction punishing our counterparty or claiming an HTLC
46         /// on-chain using the payment preimage or after it has timed out.
47         StaticOutput {
48                 /// The outpoint which is spendable
49                 outpoint: OutPoint,
50                 /// The output which is referenced by the given outpoint.
51                 output: TxOut,
52         },
53         /// An output to a P2WSH script which can be spent with a single signature after a CSV delay.
54         /// The private key which should be used to sign the transaction is provided, as well as the
55         /// full witness redeemScript which is hashed in the output script_pubkey.
56         /// The witness in the spending input should be:
57         /// <BIP 143 signature generated with the given key> <empty vector> (MINIMALIF standard rule)
58         /// <witness_script as provided>
59         /// Note that the nSequence field in the input must be set to_self_delay (which corresponds to
60         /// the transaction not being broadcastable until at least to_self_delay blocks after the input
61         /// confirms).
62         /// These are generally the result of a "revocable" output to us, spendable only by us unless
63         /// it is an output from us having broadcast an old state (which should never happen).
64         DynamicOutputP2WSH {
65                 /// The outpoint which is spendable
66                 outpoint: OutPoint,
67                 /// The secret key which must be used to sign the spending transaction
68                 key: SecretKey,
69                 /// The witness redeemScript which is hashed to create the script_pubkey in the given output
70                 witness_script: Script,
71                 /// The nSequence value which must be set in the spending input to satisfy the OP_CSV in
72                 /// the witness_script.
73                 to_self_delay: u16,
74                 /// The output which is referenced by the given outpoint
75                 output: TxOut,
76         },
77         /// An output to a P2WPKH, spendable exclusively by the given private key.
78         /// The witness in the spending input, is, thus, simply:
79         /// <BIP 143 signature generated with the given key> <public key derived from the given key>
80         /// These are generally the result of our counterparty having broadcast the current state,
81         /// allowing us to claim the non-HTLC-encumbered outputs immediately.
82         DynamicOutputP2WPKH {
83                 /// The outpoint which is spendable
84                 outpoint: OutPoint,
85                 /// The secret key which must be used to sign the spending transaction
86                 key: SecretKey,
87                 /// The output which is reference by the given outpoint
88                 output: TxOut,
89         }
90 }
91
92 impl Writeable for SpendableOutputDescriptor {
93         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
94                 match self {
95                         &SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output } => {
96                                 0u8.write(writer)?;
97                                 outpoint.write(writer)?;
98                                 output.write(writer)?;
99                         },
100                         &SpendableOutputDescriptor::DynamicOutputP2WSH { ref outpoint, ref key, ref witness_script, ref to_self_delay, ref output } => {
101                                 1u8.write(writer)?;
102                                 outpoint.write(writer)?;
103                                 key.write(writer)?;
104                                 witness_script.write(writer)?;
105                                 to_self_delay.write(writer)?;
106                                 output.write(writer)?;
107                         },
108                         &SpendableOutputDescriptor::DynamicOutputP2WPKH { ref outpoint, ref key, ref output } => {
109                                 2u8.write(writer)?;
110                                 outpoint.write(writer)?;
111                                 key.write(writer)?;
112                                 output.write(writer)?;
113                         },
114                 }
115                 Ok(())
116         }
117 }
118
119 impl Readable for SpendableOutputDescriptor {
120         fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
121                 match Readable::read(reader)? {
122                         0u8 => Ok(SpendableOutputDescriptor::StaticOutput {
123                                 outpoint: Readable::read(reader)?,
124                                 output: Readable::read(reader)?,
125                         }),
126                         1u8 => Ok(SpendableOutputDescriptor::DynamicOutputP2WSH {
127                                 outpoint: Readable::read(reader)?,
128                                 key: Readable::read(reader)?,
129                                 witness_script: Readable::read(reader)?,
130                                 to_self_delay: Readable::read(reader)?,
131                                 output: Readable::read(reader)?,
132                         }),
133                         2u8 => Ok(SpendableOutputDescriptor::DynamicOutputP2WPKH {
134                                 outpoint: Readable::read(reader)?,
135                                 key: Readable::read(reader)?,
136                                 output: Readable::read(reader)?,
137                         }),
138                         _ => Err(DecodeError::InvalidValue),
139                 }
140         }
141 }
142
143 /// A trait to describe an object which can get user secrets and key material.
144 pub trait KeysInterface: Send + Sync {
145         /// A type which implements ChannelKeys which will be returned by get_channel_keys.
146         type ChanKeySigner : ChannelKeys;
147
148         /// Get node secret key (aka node_id or network_key)
149         fn get_node_secret(&self) -> SecretKey;
150         /// Get destination redeemScript to encumber static protocol exit points.
151         fn get_destination_script(&self) -> Script;
152         /// Get shutdown_pubkey to use as PublicKey at channel closure
153         fn get_shutdown_pubkey(&self) -> PublicKey;
154         /// Get a new set of ChannelKeys for per-channel secrets. These MUST be unique even if you
155         /// restarted with some stale data!
156         fn get_channel_keys(&self, inbound: bool, channel_value_satoshis: u64) -> Self::ChanKeySigner;
157         /// Get a secret and PRNG seed for construting an onion packet
158         fn get_onion_rand(&self) -> (SecretKey, [u8; 32]);
159         /// Get a unique temporary channel id. Channels will be referred to by this until the funding
160         /// transaction is created, at which point they will use the outpoint in the funding
161         /// transaction.
162         fn get_channel_id(&self) -> [u8; 32];
163 }
164
165 /// Set of lightning keys needed to operate a channel as described in BOLT 3.
166 ///
167 /// Signing services could be implemented on a hardware wallet. In this case,
168 /// the current ChannelKeys would be a front-end on top of a communication
169 /// channel connected to your secure device and lightning key material wouldn't
170 /// reside on a hot server. Nevertheless, a this deployment would still need
171 /// to trust the ChannelManager to avoid loss of funds as this latest component
172 /// could ask to sign commitment transaction with HTLCs paying to attacker pubkeys.
173 ///
174 /// A more secure iteration would be to use hashlock (or payment points) to pair
175 /// invoice/incoming HTLCs with outgoing HTLCs to implement a no-trust-ChannelManager
176 /// at the price of more state and computation on the hardware wallet side. In the future,
177 /// we are looking forward to design such interface.
178 ///
179 /// In any case, ChannelMonitor or fallback watchtowers are always going to be trusted
180 /// to act, as liveness and breach reply correctness are always going to be hard requirements
181 /// of LN security model, orthogonal of key management issues.
182 ///
183 /// If you're implementing a custom signer, you almost certainly want to implement
184 /// Readable/Writable to serialize out a unique reference to this set of keys so
185 /// that you can serialize the full ChannelManager object.
186 ///
187 /// (TODO: We shouldn't require that, and should have an API to get them at deser time, due mostly
188 /// to the possibility of reentrancy issues by calling the user's code during our deserialization
189 /// routine).
190 /// TODO: We should remove Clone by instead requesting a new ChannelKeys copy when we create
191 /// ChannelMonitors instead of expecting to clone the one out of the Channel into the monitors.
192 pub trait ChannelKeys : Send+Clone {
193         /// Gets the private key for the anchor tx
194         fn funding_key<'a>(&'a self) -> &'a SecretKey;
195         /// Gets the local secret key for blinded revocation pubkey
196         fn revocation_base_key<'a>(&'a self) -> &'a SecretKey;
197         /// Gets the local secret key used in to_remote output of remote commitment tx
198         /// (and also as part of obscured commitment number)
199         fn payment_base_key<'a>(&'a self) -> &'a SecretKey;
200         /// Gets the local secret key used in HTLC-Success/HTLC-Timeout txn and to_local output
201         fn delayed_payment_base_key<'a>(&'a self) -> &'a SecretKey;
202         /// Gets the local htlc secret key used in commitment tx htlc outputs
203         fn htlc_base_key<'a>(&'a self) -> &'a SecretKey;
204         /// Gets the commitment seed
205         fn commitment_seed<'a>(&'a self) -> &'a [u8; 32];
206         /// Gets the local channel public keys and basepoints
207         fn pubkeys<'a>(&'a self) -> &'a ChannelPublicKeys;
208
209         /// Create a signature for a remote commitment transaction and associated HTLC transactions.
210         ///
211         /// Note that if signing fails or is rejected, the channel will be force-closed.
212         ///
213         /// TODO: Document the things someone using this interface should enforce before signing.
214         /// TODO: Add more input vars to enable better checking (preferably removing commitment_tx and
215         /// making the callee generate it via some util function we expose)!
216         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>), ()>;
217
218         /// Create a signature for a local commitment transaction
219         ///
220         /// TODO: Document the things someone using this interface should enforce before signing.
221         /// TODO: Add more input vars to enable better checking (preferably removing commitment_tx and
222         /// TODO: Ensure test-only version doesn't enforce uniqueness of signature when it's enforced in this method
223         /// making the callee generate it via some util function we expose)!
224         fn sign_local_commitment<T: secp256k1::Signing + secp256k1::Verification>(&self, local_commitment_tx: &mut LocalCommitmentTransaction, funding_redeemscript: &Script, channel_value_satoshis: u64, secp_ctx: &Secp256k1<T>);
225
226         /// Create a signature for a local commitment transaction without enforcing one-time signing.
227         ///
228         /// Testing revocation logic by our test framework needs to sign multiple local commitment
229         /// transactions. This unsafe test-only version doesn't enforce one-time signing security
230         /// requirement.
231         #[cfg(test)]
232         fn unsafe_sign_local_commitment<T: secp256k1::Signing + secp256k1::Verification>(&self, local_commitment_tx: &mut LocalCommitmentTransaction, funding_redeemscript: &Script, channel_value_satoshis: u64, secp_ctx: &Secp256k1<T>);
233
234         /// Create a signature for a (proposed) closing transaction.
235         ///
236         /// Note that, due to rounding, there may be one "missing" satoshi, and either party may have
237         /// chosen to forgo their output as dust.
238         fn sign_closing_transaction<T: secp256k1::Signing>(&self, closing_tx: &Transaction, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()>;
239
240         /// Signs a channel announcement message with our funding key, proving it comes from one
241         /// of the channel participants.
242         ///
243         /// Note that if this fails or is rejected, the channel will not be publicly announced and
244         /// our counterparty may (though likely will not) close the channel on us for violating the
245         /// protocol.
246         fn sign_channel_announcement<T: secp256k1::Signing>(&self, msg: &msgs::UnsignedChannelAnnouncement, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()>;
247
248         /// Set the remote channel basepoints.  This is done immediately on incoming channels
249         /// and as soon as the channel is accepted on outgoing channels.
250         ///
251         /// Will be called before any signatures are applied.
252         fn set_remote_channel_pubkeys(&mut self, channel_points: &ChannelPublicKeys);
253 }
254
255 #[derive(Clone)]
256 /// A simple implementation of ChannelKeys that just keeps the private keys in memory.
257 pub struct InMemoryChannelKeys {
258         /// Private key of anchor tx
259         funding_key: SecretKey,
260         /// Local secret key for blinded revocation pubkey
261         revocation_base_key: SecretKey,
262         /// Local secret key used in commitment tx htlc outputs
263         payment_base_key: SecretKey,
264         /// Local secret key used in HTLC tx
265         delayed_payment_base_key: SecretKey,
266         /// Local htlc secret key used in commitment tx htlc outputs
267         htlc_base_key: SecretKey,
268         /// Commitment seed
269         commitment_seed: [u8; 32],
270         /// Local public keys and basepoints
271         pub(crate) local_channel_pubkeys: ChannelPublicKeys,
272         /// Remote public keys and base points
273         pub(crate) remote_channel_pubkeys: Option<ChannelPublicKeys>,
274         /// The total value of this channel
275         channel_value_satoshis: u64,
276 }
277
278 impl InMemoryChannelKeys {
279         /// Create a new InMemoryChannelKeys
280         pub fn new<C: Signing>(
281                 secp_ctx: &Secp256k1<C>,
282                 funding_key: SecretKey,
283                 revocation_base_key: SecretKey,
284                 payment_base_key: SecretKey,
285                 delayed_payment_base_key: SecretKey,
286                 htlc_base_key: SecretKey,
287                 commitment_seed: [u8; 32],
288                 channel_value_satoshis: u64) -> InMemoryChannelKeys {
289                 let local_channel_pubkeys =
290                         InMemoryChannelKeys::make_local_keys(secp_ctx, &funding_key, &revocation_base_key,
291                                                              &payment_base_key, &delayed_payment_base_key,
292                                                              &htlc_base_key);
293                 InMemoryChannelKeys {
294                         funding_key,
295                         revocation_base_key,
296                         payment_base_key,
297                         delayed_payment_base_key,
298                         htlc_base_key,
299                         commitment_seed,
300                         channel_value_satoshis,
301                         local_channel_pubkeys,
302                         remote_channel_pubkeys: None,
303                 }
304         }
305
306         fn make_local_keys<C: Signing>(secp_ctx: &Secp256k1<C>,
307                                        funding_key: &SecretKey,
308                                        revocation_base_key: &SecretKey,
309                                        payment_base_key: &SecretKey,
310                                        delayed_payment_base_key: &SecretKey,
311                                        htlc_base_key: &SecretKey) -> ChannelPublicKeys {
312                 let from_secret = |s: &SecretKey| PublicKey::from_secret_key(secp_ctx, s);
313                 ChannelPublicKeys {
314                         funding_pubkey: from_secret(&funding_key),
315                         revocation_basepoint: from_secret(&revocation_base_key),
316                         payment_basepoint: from_secret(&payment_base_key),
317                         delayed_payment_basepoint: from_secret(&delayed_payment_base_key),
318                         htlc_basepoint: from_secret(&htlc_base_key),
319                 }
320         }
321 }
322
323 impl ChannelKeys for InMemoryChannelKeys {
324         fn funding_key(&self) -> &SecretKey { &self.funding_key }
325         fn revocation_base_key(&self) -> &SecretKey { &self.revocation_base_key }
326         fn payment_base_key(&self) -> &SecretKey { &self.payment_base_key }
327         fn delayed_payment_base_key(&self) -> &SecretKey { &self.delayed_payment_base_key }
328         fn htlc_base_key(&self) -> &SecretKey { &self.htlc_base_key }
329         fn commitment_seed(&self) -> &[u8; 32] { &self.commitment_seed }
330         fn pubkeys<'a>(&'a self) -> &'a ChannelPublicKeys { &self.local_channel_pubkeys }
331
332         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>), ()> {
333                 if commitment_tx.input.len() != 1 { return Err(()); }
334
335                 let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
336                 let remote_channel_pubkeys = self.remote_channel_pubkeys.as_ref().expect("must set remote channel pubkeys before signing");
337                 let channel_funding_redeemscript = make_funding_redeemscript(&funding_pubkey, &remote_channel_pubkeys.funding_pubkey);
338
339                 let commitment_sighash = hash_to_message!(&bip143::SighashComponents::new(&commitment_tx).sighash_all(&commitment_tx.input[0], &channel_funding_redeemscript, self.channel_value_satoshis)[..]);
340                 let commitment_sig = secp_ctx.sign(&commitment_sighash, &self.funding_key);
341
342                 let commitment_txid = commitment_tx.txid();
343
344                 let mut htlc_sigs = Vec::with_capacity(htlcs.len());
345                 for ref htlc in htlcs {
346                         if let Some(_) = htlc.transaction_output_index {
347                                 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);
348                                 let htlc_redeemscript = chan_utils::get_htlc_redeemscript(&htlc, &keys);
349                                 let htlc_sighash = hash_to_message!(&bip143::SighashComponents::new(&htlc_tx).sighash_all(&htlc_tx.input[0], &htlc_redeemscript, htlc.amount_msat / 1000)[..]);
350                                 let our_htlc_key = match chan_utils::derive_private_key(&secp_ctx, &keys.per_commitment_point, &self.htlc_base_key) {
351                                         Ok(s) => s,
352                                         Err(_) => return Err(()),
353                                 };
354                                 htlc_sigs.push(secp_ctx.sign(&htlc_sighash, &our_htlc_key));
355                         }
356                 }
357
358                 Ok((commitment_sig, htlc_sigs))
359         }
360
361         fn sign_local_commitment<T: secp256k1::Signing + secp256k1::Verification>(&self, local_commitment_tx: &mut LocalCommitmentTransaction, funding_redeemscript: &Script, channel_value_satoshis: u64, secp_ctx: &Secp256k1<T>) {
362                 local_commitment_tx.add_local_sig(&self.funding_key, funding_redeemscript, channel_value_satoshis, secp_ctx);
363         }
364
365         #[cfg(test)]
366         fn unsafe_sign_local_commitment<T: secp256k1::Signing + secp256k1::Verification>(&self, local_commitment_tx: &mut LocalCommitmentTransaction, funding_redeemscript: &Script, channel_value_satoshis: u64, secp_ctx: &Secp256k1<T>) {
367                 local_commitment_tx.add_local_sig(&self.funding_key, funding_redeemscript, channel_value_satoshis, secp_ctx);
368         }
369
370         fn sign_closing_transaction<T: secp256k1::Signing>(&self, closing_tx: &Transaction, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()> {
371                 if closing_tx.input.len() != 1 { return Err(()); }
372                 if closing_tx.input[0].witness.len() != 0 { return Err(()); }
373                 if closing_tx.output.len() > 2 { return Err(()); }
374
375                 let remote_channel_pubkeys = self.remote_channel_pubkeys.as_ref().expect("must set remote channel pubkeys before signing");
376                 let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
377                 let channel_funding_redeemscript = make_funding_redeemscript(&funding_pubkey, &remote_channel_pubkeys.funding_pubkey);
378
379                 let sighash = hash_to_message!(&bip143::SighashComponents::new(closing_tx)
380                         .sighash_all(&closing_tx.input[0], &channel_funding_redeemscript, self.channel_value_satoshis)[..]);
381                 Ok(secp_ctx.sign(&sighash, &self.funding_key))
382         }
383
384         fn sign_channel_announcement<T: secp256k1::Signing>(&self, msg: &msgs::UnsignedChannelAnnouncement, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()> {
385                 let msghash = hash_to_message!(&Sha256dHash::hash(&msg.encode()[..])[..]);
386                 Ok(secp_ctx.sign(&msghash, &self.funding_key))
387         }
388
389         fn set_remote_channel_pubkeys(&mut self, channel_pubkeys: &ChannelPublicKeys) {
390                 assert!(self.remote_channel_pubkeys.is_none(), "Already set remote channel pubkeys");
391                 self.remote_channel_pubkeys = Some(channel_pubkeys.clone());
392         }
393 }
394
395 impl Writeable for InMemoryChannelKeys {
396         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), Error> {
397                 self.funding_key.write(writer)?;
398                 self.revocation_base_key.write(writer)?;
399                 self.payment_base_key.write(writer)?;
400                 self.delayed_payment_base_key.write(writer)?;
401                 self.htlc_base_key.write(writer)?;
402                 self.commitment_seed.write(writer)?;
403                 self.remote_channel_pubkeys.write(writer)?;
404                 self.channel_value_satoshis.write(writer)?;
405
406                 Ok(())
407         }
408 }
409
410 impl Readable for InMemoryChannelKeys {
411         fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
412                 let funding_key = Readable::read(reader)?;
413                 let revocation_base_key = Readable::read(reader)?;
414                 let payment_base_key = Readable::read(reader)?;
415                 let delayed_payment_base_key = Readable::read(reader)?;
416                 let htlc_base_key = Readable::read(reader)?;
417                 let commitment_seed = Readable::read(reader)?;
418                 let remote_channel_pubkeys = Readable::read(reader)?;
419                 let channel_value_satoshis = Readable::read(reader)?;
420                 let secp_ctx = Secp256k1::signing_only();
421                 let local_channel_pubkeys =
422                         InMemoryChannelKeys::make_local_keys(&secp_ctx, &funding_key, &revocation_base_key,
423                                                              &payment_base_key, &delayed_payment_base_key,
424                                                              &htlc_base_key);
425
426                 Ok(InMemoryChannelKeys {
427                         funding_key,
428                         revocation_base_key,
429                         payment_base_key,
430                         delayed_payment_base_key,
431                         htlc_base_key,
432                         commitment_seed,
433                         channel_value_satoshis,
434                         local_channel_pubkeys,
435                         remote_channel_pubkeys
436                 })
437         }
438 }
439
440 /// Simple KeysInterface implementor that takes a 32-byte seed for use as a BIP 32 extended key
441 /// and derives keys from that.
442 ///
443 /// Your node_id is seed/0'
444 /// ChannelMonitor closes may use seed/1'
445 /// Cooperative closes may use seed/2'
446 /// The two close keys may be needed to claim on-chain funds!
447 pub struct KeysManager {
448         secp_ctx: Secp256k1<secp256k1::SignOnly>,
449         node_secret: SecretKey,
450         destination_script: Script,
451         shutdown_pubkey: PublicKey,
452         channel_master_key: ExtendedPrivKey,
453         channel_child_index: AtomicUsize,
454         session_master_key: ExtendedPrivKey,
455         session_child_index: AtomicUsize,
456         channel_id_master_key: ExtendedPrivKey,
457         channel_id_child_index: AtomicUsize,
458
459         unique_start: Sha256State,
460         logger: Arc<Logger>,
461 }
462
463 impl KeysManager {
464         /// Constructs a KeysManager from a 32-byte seed. If the seed is in some way biased (eg your
465         /// RNG is busted) this may panic (but more importantly, you will possibly lose funds).
466         /// starting_time isn't strictly required to actually be a time, but it must absolutely,
467         /// without a doubt, be unique to this instance. ie if you start multiple times with the same
468         /// seed, starting_time must be unique to each run. Thus, the easiest way to achieve this is to
469         /// simply use the current time (with very high precision).
470         ///
471         /// The seed MUST be backed up safely prior to use so that the keys can be re-created, however,
472         /// obviously, starting_time should be unique every time you reload the library - it is only
473         /// used to generate new ephemeral key data (which will be stored by the individual channel if
474         /// necessary).
475         ///
476         /// Note that the seed is required to recover certain on-chain funds independent of
477         /// ChannelMonitor data, though a current copy of ChannelMonitor data is also required for any
478         /// channel, and some on-chain during-closing funds.
479         ///
480         /// Note that until the 0.1 release there is no guarantee of backward compatibility between
481         /// versions. Once the library is more fully supported, the docs will be updated to include a
482         /// detailed description of the guarantee.
483         pub fn new(seed: &[u8; 32], network: Network, logger: Arc<Logger>, starting_time_secs: u64, starting_time_nanos: u32) -> KeysManager {
484                 let secp_ctx = Secp256k1::signing_only();
485                 match ExtendedPrivKey::new_master(network.clone(), seed) {
486                         Ok(master_key) => {
487                                 let node_secret = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(0).unwrap()).expect("Your RNG is busted").private_key.key;
488                                 let destination_script = match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(1).unwrap()) {
489                                         Ok(destination_key) => {
490                                                 let pubkey_hash160 = Hash160::hash(&ExtendedPubKey::from_private(&secp_ctx, &destination_key).public_key.key.serialize()[..]);
491                                                 Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0)
492                                                               .push_slice(&pubkey_hash160.into_inner())
493                                                               .into_script()
494                                         },
495                                         Err(_) => panic!("Your RNG is busted"),
496                                 };
497                                 let shutdown_pubkey = match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(2).unwrap()) {
498                                         Ok(shutdown_key) => ExtendedPubKey::from_private(&secp_ctx, &shutdown_key).public_key.key,
499                                         Err(_) => panic!("Your RNG is busted"),
500                                 };
501                                 let channel_master_key = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(3).unwrap()).expect("Your RNG is busted");
502                                 let session_master_key = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(4).unwrap()).expect("Your RNG is busted");
503                                 let channel_id_master_key = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(5).unwrap()).expect("Your RNG is busted");
504
505                                 let mut unique_start = Sha256::engine();
506                                 unique_start.input(&byte_utils::be64_to_array(starting_time_secs));
507                                 unique_start.input(&byte_utils::be32_to_array(starting_time_nanos));
508                                 unique_start.input(seed);
509
510                                 KeysManager {
511                                         secp_ctx,
512                                         node_secret,
513                                         destination_script,
514                                         shutdown_pubkey,
515                                         channel_master_key,
516                                         channel_child_index: AtomicUsize::new(0),
517                                         session_master_key,
518                                         session_child_index: AtomicUsize::new(0),
519                                         channel_id_master_key,
520                                         channel_id_child_index: AtomicUsize::new(0),
521
522                                         unique_start,
523                                         logger,
524                                 }
525                         },
526                         Err(_) => panic!("Your rng is busted"),
527                 }
528         }
529 }
530
531 impl KeysInterface for KeysManager {
532         type ChanKeySigner = InMemoryChannelKeys;
533
534         fn get_node_secret(&self) -> SecretKey {
535                 self.node_secret.clone()
536         }
537
538         fn get_destination_script(&self) -> Script {
539                 self.destination_script.clone()
540         }
541
542         fn get_shutdown_pubkey(&self) -> PublicKey {
543                 self.shutdown_pubkey.clone()
544         }
545
546         fn get_channel_keys(&self, _inbound: bool, channel_value_satoshis: u64) -> InMemoryChannelKeys {
547                 // We only seriously intend to rely on the channel_master_key for true secure
548                 // entropy, everything else just ensures uniqueness. We rely on the unique_start (ie
549                 // starting_time provided in the constructor) to be unique.
550                 let mut sha = self.unique_start.clone();
551
552                 let child_ix = self.channel_child_index.fetch_add(1, Ordering::AcqRel);
553                 let child_privkey = self.channel_master_key.ckd_priv(&self.secp_ctx, ChildNumber::from_hardened_idx(child_ix as u32).expect("key space exhausted")).expect("Your RNG is busted");
554                 sha.input(&child_privkey.private_key.key[..]);
555
556                 let seed = Sha256::from_engine(sha).into_inner();
557
558                 let commitment_seed = {
559                         let mut sha = Sha256::engine();
560                         sha.input(&seed);
561                         sha.input(&b"commitment seed"[..]);
562                         Sha256::from_engine(sha).into_inner()
563                 };
564                 macro_rules! key_step {
565                         ($info: expr, $prev_key: expr) => {{
566                                 let mut sha = Sha256::engine();
567                                 sha.input(&seed);
568                                 sha.input(&$prev_key[..]);
569                                 sha.input(&$info[..]);
570                                 SecretKey::from_slice(&Sha256::from_engine(sha).into_inner()).expect("SHA-256 is busted")
571                         }}
572                 }
573                 let funding_key = key_step!(b"funding key", commitment_seed);
574                 let revocation_base_key = key_step!(b"revocation base key", funding_key);
575                 let payment_base_key = key_step!(b"payment base key", revocation_base_key);
576                 let delayed_payment_base_key = key_step!(b"delayed payment base key", payment_base_key);
577                 let htlc_base_key = key_step!(b"HTLC base key", delayed_payment_base_key);
578
579                 InMemoryChannelKeys::new(
580                         &self.secp_ctx,
581                         funding_key,
582                         revocation_base_key,
583                         payment_base_key,
584                         delayed_payment_base_key,
585                         htlc_base_key,
586                         commitment_seed,
587                         channel_value_satoshis
588                 )
589         }
590
591         fn get_onion_rand(&self) -> (SecretKey, [u8; 32]) {
592                 let mut sha = self.unique_start.clone();
593
594                 let child_ix = self.session_child_index.fetch_add(1, Ordering::AcqRel);
595                 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");
596                 sha.input(&child_privkey.private_key.key[..]);
597
598                 let mut rng_seed = sha.clone();
599                 // Not exactly the most ideal construction, but the second value will get fed into
600                 // ChaCha so it is another step harder to break.
601                 rng_seed.input(b"RNG Seed Salt");
602                 sha.input(b"Session Key Salt");
603                 (SecretKey::from_slice(&Sha256::from_engine(sha).into_inner()).expect("Your RNG is busted"),
604                 Sha256::from_engine(rng_seed).into_inner())
605         }
606
607         fn get_channel_id(&self) -> [u8; 32] {
608                 let mut sha = self.unique_start.clone();
609
610                 let child_ix = self.channel_id_child_index.fetch_add(1, Ordering::AcqRel);
611                 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");
612                 sha.input(&child_privkey.private_key.key[..]);
613
614                 (Sha256::from_engine(sha).into_inner())
615         }
616 }