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