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