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