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