Extend KeysInterface with derive_channel_keys
[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::ser::{Writeable, Writer, Readable};
24
25 use ln::chan_utils;
26 use ln::chan_utils::{TxCreationKeys, HTLCOutputInCommitment, make_funding_redeemscript, ChannelPublicKeys, LocalCommitmentTransaction};
27 use ln::msgs;
28 use ln::channelmanager::PaymentPreimage;
29
30 use std::sync::atomic::{AtomicUsize, Ordering};
31 use std::io::Error;
32 use ln::msgs::DecodeError;
33
34 /// When on-chain outputs are created by rust-lightning (which our counterparty is not able to
35 /// claim at any point in the future) an event is generated which you must track and be able to
36 /// spend on-chain. The information needed to do this is provided in this enum, including the
37 /// outpoint describing which txid and output index is available, the full output which exists at
38 /// that txid/index, and any keys or other information required to sign.
39 #[derive(Clone, PartialEq)]
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> <empty vector> (MINIMALIF standard rule)
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         // TODO: Note that because key is now static and exactly what is provided by us, we should drop
77         // this in favor of StaticOutput:
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 the to_remote output of remote commitment tx (ie the
199         /// output to us in transactions our counterparty broadcasts).
200         /// Also as part of obscured commitment number.
201         fn payment_key<'a>(&'a self) -> &'a SecretKey;
202         /// Gets the local secret key used in HTLC-Success/HTLC-Timeout txn and to_local output
203         fn delayed_payment_base_key<'a>(&'a self) -> &'a SecretKey;
204         /// Gets the local htlc secret key used in commitment tx htlc outputs
205         fn htlc_base_key<'a>(&'a self) -> &'a SecretKey;
206         /// Gets the commitment seed
207         fn commitment_seed<'a>(&'a self) -> &'a [u8; 32];
208         /// Gets the local channel public keys and basepoints
209         fn pubkeys<'a>(&'a self) -> &'a ChannelPublicKeys;
210         /// Gets arbitrary identifiers describing the set of keys which are provided back to you in
211         /// some SpendableOutputDescriptor types. These should be sufficient to identify this
212         /// ChannelKeys object uniquely and lookup or re-derive its keys.
213         fn key_derivation_params(&self) -> (u64, u64);
214
215         /// Create a signature for a remote commitment transaction and associated HTLC transactions.
216         ///
217         /// Note that if signing fails or is rejected, the channel will be force-closed.
218         //
219         // TODO: Document the things someone using this interface should enforce before signing.
220         // TODO: Add more input vars to enable better checking (preferably removing commitment_tx and
221         // making the callee generate it via some util function we expose)!
222         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>), ()>;
223
224         /// Create a signature for a local commitment transaction. This will only ever be called with
225         /// the same local_commitment_tx (or a copy thereof), though there are currently no guarantees
226         /// that it will not be called multiple times.
227         //
228         // TODO: Document the things someone using this interface should enforce before signing.
229         // TODO: Add more input vars to enable better checking (preferably removing commitment_tx and
230         fn sign_local_commitment<T: secp256k1::Signing + secp256k1::Verification>(&self, local_commitment_tx: &LocalCommitmentTransaction, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()>;
231
232         /// Same as sign_local_commitment, but exists only for tests to get access to local commitment
233         /// transactions which will be broadcasted later, after the channel has moved on to a newer
234         /// state. Thus, needs its own method as sign_local_commitment may enforce that we only ever
235         /// get called once.
236         #[cfg(test)]
237         fn unsafe_sign_local_commitment<T: secp256k1::Signing + secp256k1::Verification>(&self, local_commitment_tx: &LocalCommitmentTransaction, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()>;
238
239         /// Create a signature for each HTLC transaction spending a local commitment transaction.
240         ///
241         /// Unlike sign_local_commitment, this may be called multiple times with *different*
242         /// local_commitment_tx values. While this will never be called with a revoked
243         /// local_commitment_tx, it is possible that it is called with the second-latest
244         /// local_commitment_tx (only if we haven't yet revoked it) if some watchtower/secondary
245         /// ChannelMonitor decided to broadcast before it had been updated to the latest.
246         ///
247         /// Either an Err should be returned, or a Vec with one entry for each HTLC which exists in
248         /// local_commitment_tx. For those HTLCs which have transaction_output_index set to None
249         /// (implying they were considered dust at the time the commitment transaction was negotiated),
250         /// a corresponding None should be included in the return value. All other positions in the
251         /// return value must contain a signature.
252         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>>, ()>;
253
254         /// Create a signature for a transaction spending an HTLC or commitment transaction output
255         /// when our counterparty broadcast an old state.
256         ///
257         /// Justice transaction may claim multiples outputs at same time if timelock are similar.
258         /// It may be called multiples time for same output(s) if a fee-bump is needed with regards
259         /// to an upcoming timelock expiration.
260         ///
261         /// Witness_script is a revokable witness script as defined in BOLT3 for `to_local`/HTLC
262         /// outputs.
263         ///
264         /// Input index is a pointer towards outpoint spent, commited by sigs (BIP 143).
265         ///
266         /// Amount is value of the output spent by this input, committed by sigs (BIP 143).
267         ///
268         /// Per_commitment key is revocation secret such as provided by remote party while
269         /// revocating detected onchain transaction. It's not a _local_ secret key, therefore
270         /// it may cross interfaces, a node compromise won't allow to spend revoked output without
271         /// also compromissing revocation key.
272         //TODO: dry-up witness_script and pass pubkeys
273         fn sign_justice_transaction<T: secp256k1::Signing>(&self, justice_tx: &Transaction, input: usize, witness_script: &Script, amount: u64, per_commitment_key: &SecretKey, revocation_pubkey: &PublicKey, is_htlc: bool, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()>;
274
275         /// Create a signature for a claiming transaction for a HTLC output on a remote commitment
276         /// transaction, either offered or received.
277         ///
278         /// HTLC transaction may claim multiples offered outputs at same time if we know preimage
279         /// for each at detection. It may be called multtiples time for same output(s) if a fee-bump
280         /// is needed with regards to an upcoming timelock expiration.
281         ///
282         /// Witness_script is either a offered or received script as defined in BOLT3 for HTLC
283         /// outputs.
284         ///
285         /// Input index is a pointer towards outpoint spent, commited by sigs (BIP 143).
286         ///
287         /// Amount is value of the output spent by this input, committed by sigs (BIP 143).
288         ///
289         /// Preimage is solution for an offered HTLC haslock. A preimage sets to None hints this
290         /// htlc_tx as timing-out funds back to us on a received output.
291         //TODO: dry-up witness_script and pass pubkeys
292         fn sign_remote_htlc_transaction<T: secp256k1::Signing>(&self, htlc_tx: &Transaction, input: usize, witness_script: &Script, amount: u64, per_commitment_point: &PublicKey, preimage: &Option<PaymentPreimage>, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()>;
293
294         /// Create a signature for a (proposed) closing transaction.
295         ///
296         /// Note that, due to rounding, there may be one "missing" satoshi, and either party may have
297         /// chosen to forgo their output as dust.
298         fn sign_closing_transaction<T: secp256k1::Signing>(&self, closing_tx: &Transaction, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()>;
299
300         /// Signs a channel announcement message with our funding key, proving it comes from one
301         /// of the channel participants.
302         ///
303         /// Note that if this fails or is rejected, the channel will not be publicly announced and
304         /// our counterparty may (though likely will not) close the channel on us for violating the
305         /// protocol.
306         fn sign_channel_announcement<T: secp256k1::Signing>(&self, msg: &msgs::UnsignedChannelAnnouncement, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()>;
307
308         /// Set the remote channel basepoints.  This is done immediately on incoming channels
309         /// and as soon as the channel is accepted on outgoing channels.
310         ///
311         /// Will be called before any signatures are applied.
312         fn set_remote_channel_pubkeys(&mut self, channel_points: &ChannelPublicKeys);
313 }
314
315 #[derive(Clone)]
316 /// A simple implementation of ChannelKeys that just keeps the private keys in memory.
317 pub struct InMemoryChannelKeys {
318         /// Private key of anchor tx
319         funding_key: SecretKey,
320         /// Local secret key for blinded revocation pubkey
321         revocation_base_key: SecretKey,
322         /// Local secret key used for our balance in remote-broadcasted commitment transactions
323         payment_key: SecretKey,
324         /// Local secret key used in HTLC tx
325         delayed_payment_base_key: SecretKey,
326         /// Local htlc secret key used in commitment tx htlc outputs
327         htlc_base_key: SecretKey,
328         /// Commitment seed
329         commitment_seed: [u8; 32],
330         /// Local public keys and basepoints
331         pub(crate) local_channel_pubkeys: ChannelPublicKeys,
332         /// Remote public keys and base points
333         pub(crate) remote_channel_pubkeys: Option<ChannelPublicKeys>,
334         /// The total value of this channel
335         channel_value_satoshis: u64,
336         /// Key derivation parameters
337         key_derivation_params: (u64, u64),
338 }
339
340 impl InMemoryChannelKeys {
341         /// Create a new InMemoryChannelKeys
342         pub fn new<C: Signing>(
343                 secp_ctx: &Secp256k1<C>,
344                 funding_key: SecretKey,
345                 revocation_base_key: SecretKey,
346                 payment_key: SecretKey,
347                 delayed_payment_base_key: SecretKey,
348                 htlc_base_key: SecretKey,
349                 commitment_seed: [u8; 32],
350                 channel_value_satoshis: u64,
351                 key_derivation_params: (u64, u64)) -> InMemoryChannelKeys {
352                 let local_channel_pubkeys =
353                         InMemoryChannelKeys::make_local_keys(secp_ctx, &funding_key, &revocation_base_key,
354                                                              &payment_key, &delayed_payment_base_key,
355                                                              &htlc_base_key);
356                 InMemoryChannelKeys {
357                         funding_key,
358                         revocation_base_key,
359                         payment_key,
360                         delayed_payment_base_key,
361                         htlc_base_key,
362                         commitment_seed,
363                         channel_value_satoshis,
364                         local_channel_pubkeys,
365                         remote_channel_pubkeys: None,
366                         key_derivation_params,
367                 }
368         }
369
370         fn make_local_keys<C: Signing>(secp_ctx: &Secp256k1<C>,
371                                        funding_key: &SecretKey,
372                                        revocation_base_key: &SecretKey,
373                                        payment_key: &SecretKey,
374                                        delayed_payment_base_key: &SecretKey,
375                                        htlc_base_key: &SecretKey) -> ChannelPublicKeys {
376                 let from_secret = |s: &SecretKey| PublicKey::from_secret_key(secp_ctx, s);
377                 ChannelPublicKeys {
378                         funding_pubkey: from_secret(&funding_key),
379                         revocation_basepoint: from_secret(&revocation_base_key),
380                         payment_point: from_secret(&payment_key),
381                         delayed_payment_basepoint: from_secret(&delayed_payment_base_key),
382                         htlc_basepoint: from_secret(&htlc_base_key),
383                 }
384         }
385 }
386
387 impl ChannelKeys for InMemoryChannelKeys {
388         fn funding_key(&self) -> &SecretKey { &self.funding_key }
389         fn revocation_base_key(&self) -> &SecretKey { &self.revocation_base_key }
390         fn payment_key(&self) -> &SecretKey { &self.payment_key }
391         fn delayed_payment_base_key(&self) -> &SecretKey { &self.delayed_payment_base_key }
392         fn htlc_base_key(&self) -> &SecretKey { &self.htlc_base_key }
393         fn commitment_seed(&self) -> &[u8; 32] { &self.commitment_seed }
394         fn pubkeys<'a>(&'a self) -> &'a ChannelPublicKeys { &self.local_channel_pubkeys }
395         fn key_derivation_params(&self) -> (u64, u64) { self.key_derivation_params }
396
397         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>), ()> {
398                 if commitment_tx.input.len() != 1 { return Err(()); }
399
400                 let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
401                 let remote_channel_pubkeys = self.remote_channel_pubkeys.as_ref().expect("must set remote channel pubkeys before signing");
402                 let channel_funding_redeemscript = make_funding_redeemscript(&funding_pubkey, &remote_channel_pubkeys.funding_pubkey);
403
404                 let commitment_sighash = hash_to_message!(&bip143::SighashComponents::new(&commitment_tx).sighash_all(&commitment_tx.input[0], &channel_funding_redeemscript, self.channel_value_satoshis)[..]);
405                 let commitment_sig = secp_ctx.sign(&commitment_sighash, &self.funding_key);
406
407                 let commitment_txid = commitment_tx.txid();
408
409                 let mut htlc_sigs = Vec::with_capacity(htlcs.len());
410                 for ref htlc in htlcs {
411                         if let Some(_) = htlc.transaction_output_index {
412                                 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);
413                                 let htlc_redeemscript = chan_utils::get_htlc_redeemscript(&htlc, &keys);
414                                 let htlc_sighash = hash_to_message!(&bip143::SighashComponents::new(&htlc_tx).sighash_all(&htlc_tx.input[0], &htlc_redeemscript, htlc.amount_msat / 1000)[..]);
415                                 let our_htlc_key = match chan_utils::derive_private_key(&secp_ctx, &keys.per_commitment_point, &self.htlc_base_key) {
416                                         Ok(s) => s,
417                                         Err(_) => return Err(()),
418                                 };
419                                 htlc_sigs.push(secp_ctx.sign(&htlc_sighash, &our_htlc_key));
420                         }
421                 }
422
423                 Ok((commitment_sig, htlc_sigs))
424         }
425
426         fn sign_local_commitment<T: secp256k1::Signing + secp256k1::Verification>(&self, local_commitment_tx: &LocalCommitmentTransaction, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()> {
427                 let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
428                 let remote_channel_pubkeys = self.remote_channel_pubkeys.as_ref().expect("must set remote channel pubkeys before signing");
429                 let channel_funding_redeemscript = make_funding_redeemscript(&funding_pubkey, &remote_channel_pubkeys.funding_pubkey);
430
431                 Ok(local_commitment_tx.get_local_sig(&self.funding_key, &channel_funding_redeemscript, self.channel_value_satoshis, secp_ctx))
432         }
433
434         #[cfg(test)]
435         fn unsafe_sign_local_commitment<T: secp256k1::Signing + secp256k1::Verification>(&self, local_commitment_tx: &LocalCommitmentTransaction, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()> {
436                 let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
437                 let remote_channel_pubkeys = self.remote_channel_pubkeys.as_ref().expect("must set remote channel pubkeys before signing");
438                 let channel_funding_redeemscript = make_funding_redeemscript(&funding_pubkey, &remote_channel_pubkeys.funding_pubkey);
439
440                 Ok(local_commitment_tx.get_local_sig(&self.funding_key, &channel_funding_redeemscript, self.channel_value_satoshis, secp_ctx))
441         }
442
443         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>>, ()> {
444                 local_commitment_tx.get_htlc_sigs(&self.htlc_base_key, local_csv, secp_ctx)
445         }
446
447         fn sign_justice_transaction<T: secp256k1::Signing>(&self, justice_tx: &Transaction, input: usize, witness_script: &Script, amount: u64, per_commitment_key: &SecretKey, revocation_pubkey: &PublicKey, is_htlc: bool, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()> {
448                 if let Ok(revocation_key) = chan_utils::derive_private_revocation_key(&secp_ctx, &per_commitment_key, &self.revocation_base_key) {
449                         let sighash_parts = bip143::SighashComponents::new(&justice_tx);
450                         let sighash = hash_to_message!(&sighash_parts.sighash_all(&justice_tx.input[input], &witness_script, amount)[..]);
451                         return Ok(secp_ctx.sign(&sighash, &revocation_key))
452                 }
453                 Err(())
454         }
455
456         fn sign_remote_htlc_transaction<T: secp256k1::Signing>(&self, htlc_tx: &Transaction, input: usize, witness_script: &Script, amount: u64, per_commitment_point: &PublicKey, preimage: &Option<PaymentPreimage>, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()> {
457                 if let Ok(htlc_key) = chan_utils::derive_private_key(&secp_ctx, &per_commitment_point, &self.htlc_base_key) {
458                         let sighash_parts = bip143::SighashComponents::new(&htlc_tx);
459                         let sighash = hash_to_message!(&sighash_parts.sighash_all(&htlc_tx.input[input], &witness_script, amount)[..]);
460                         return Ok(secp_ctx.sign(&sighash, &htlc_key))
461                 }
462                 Err(())
463         }
464
465         fn sign_closing_transaction<T: secp256k1::Signing>(&self, closing_tx: &Transaction, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()> {
466                 if closing_tx.input.len() != 1 { return Err(()); }
467                 if closing_tx.input[0].witness.len() != 0 { return Err(()); }
468                 if closing_tx.output.len() > 2 { return Err(()); }
469
470                 let remote_channel_pubkeys = self.remote_channel_pubkeys.as_ref().expect("must set remote channel pubkeys before signing");
471                 let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
472                 let channel_funding_redeemscript = make_funding_redeemscript(&funding_pubkey, &remote_channel_pubkeys.funding_pubkey);
473
474                 let sighash = hash_to_message!(&bip143::SighashComponents::new(closing_tx)
475                         .sighash_all(&closing_tx.input[0], &channel_funding_redeemscript, self.channel_value_satoshis)[..]);
476                 Ok(secp_ctx.sign(&sighash, &self.funding_key))
477         }
478
479         fn sign_channel_announcement<T: secp256k1::Signing>(&self, msg: &msgs::UnsignedChannelAnnouncement, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()> {
480                 let msghash = hash_to_message!(&Sha256dHash::hash(&msg.encode()[..])[..]);
481                 Ok(secp_ctx.sign(&msghash, &self.funding_key))
482         }
483
484         fn set_remote_channel_pubkeys(&mut self, channel_pubkeys: &ChannelPublicKeys) {
485                 assert!(self.remote_channel_pubkeys.is_none(), "Already set remote channel pubkeys");
486                 self.remote_channel_pubkeys = Some(channel_pubkeys.clone());
487         }
488 }
489
490 impl Writeable for InMemoryChannelKeys {
491         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), Error> {
492                 self.funding_key.write(writer)?;
493                 self.revocation_base_key.write(writer)?;
494                 self.payment_key.write(writer)?;
495                 self.delayed_payment_base_key.write(writer)?;
496                 self.htlc_base_key.write(writer)?;
497                 self.commitment_seed.write(writer)?;
498                 self.remote_channel_pubkeys.write(writer)?;
499                 self.channel_value_satoshis.write(writer)?;
500                 self.key_derivation_params.0.write(writer)?;
501                 self.key_derivation_params.1.write(writer)?;
502
503                 Ok(())
504         }
505 }
506
507 impl Readable for InMemoryChannelKeys {
508         fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
509                 let funding_key = Readable::read(reader)?;
510                 let revocation_base_key = Readable::read(reader)?;
511                 let payment_key = Readable::read(reader)?;
512                 let delayed_payment_base_key = Readable::read(reader)?;
513                 let htlc_base_key = Readable::read(reader)?;
514                 let commitment_seed = Readable::read(reader)?;
515                 let remote_channel_pubkeys = Readable::read(reader)?;
516                 let channel_value_satoshis = Readable::read(reader)?;
517                 let secp_ctx = Secp256k1::signing_only();
518                 let local_channel_pubkeys =
519                         InMemoryChannelKeys::make_local_keys(&secp_ctx, &funding_key, &revocation_base_key,
520                                                              &payment_key, &delayed_payment_base_key,
521                                                              &htlc_base_key);
522                 let params_1 = Readable::read(reader)?;
523                 let params_2 = Readable::read(reader)?;
524
525                 Ok(InMemoryChannelKeys {
526                         funding_key,
527                         revocation_base_key,
528                         payment_key,
529                         delayed_payment_base_key,
530                         htlc_base_key,
531                         commitment_seed,
532                         channel_value_satoshis,
533                         local_channel_pubkeys,
534                         remote_channel_pubkeys,
535                         key_derivation_params: (params_1, params_2),
536                 })
537         }
538 }
539
540 /// Simple KeysInterface implementor that takes a 32-byte seed for use as a BIP 32 extended key
541 /// and derives keys from that.
542 ///
543 /// Your node_id is seed/0'
544 /// ChannelMonitor closes may use seed/1'
545 /// Cooperative closes may use seed/2'
546 /// The two close keys may be needed to claim on-chain funds!
547 pub struct KeysManager {
548         secp_ctx: Secp256k1<secp256k1::SignOnly>,
549         node_secret: SecretKey,
550         destination_script: Script,
551         shutdown_pubkey: PublicKey,
552         channel_master_key: ExtendedPrivKey,
553         channel_child_index: AtomicUsize,
554         session_master_key: ExtendedPrivKey,
555         session_child_index: AtomicUsize,
556         channel_id_master_key: ExtendedPrivKey,
557         channel_id_child_index: AtomicUsize,
558
559         seed: [u8; 32],
560         starting_time_secs: u64,
561         starting_time_nanos: u32,
562 }
563
564 impl KeysManager {
565         /// Constructs a KeysManager from a 32-byte seed. If the seed is in some way biased (eg your
566         /// RNG is busted) this may panic (but more importantly, you will possibly lose funds).
567         /// starting_time isn't strictly required to actually be a time, but it must absolutely,
568         /// without a doubt, be unique to this instance. ie if you start multiple times with the same
569         /// seed, starting_time must be unique to each run. Thus, the easiest way to achieve this is to
570         /// simply use the current time (with very high precision).
571         ///
572         /// The seed MUST be backed up safely prior to use so that the keys can be re-created, however,
573         /// obviously, starting_time should be unique every time you reload the library - it is only
574         /// used to generate new ephemeral key data (which will be stored by the individual channel if
575         /// necessary).
576         ///
577         /// Note that the seed is required to recover certain on-chain funds independent of
578         /// ChannelMonitor data, though a current copy of ChannelMonitor data is also required for any
579         /// channel, and some on-chain during-closing funds.
580         ///
581         /// Note that until the 0.1 release there is no guarantee of backward compatibility between
582         /// versions. Once the library is more fully supported, the docs will be updated to include a
583         /// detailed description of the guarantee.
584         pub fn new(seed: &[u8; 32], network: Network, starting_time_secs: u64, starting_time_nanos: u32) -> KeysManager {
585                 let secp_ctx = Secp256k1::signing_only();
586                 match ExtendedPrivKey::new_master(network.clone(), seed) {
587                         Ok(master_key) => {
588                                 let node_secret = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(0).unwrap()).expect("Your RNG is busted").private_key.key;
589                                 let destination_script = match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(1).unwrap()) {
590                                         Ok(destination_key) => {
591                                                 let wpubkey_hash = WPubkeyHash::hash(&ExtendedPubKey::from_private(&secp_ctx, &destination_key).public_key.to_bytes());
592                                                 Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0)
593                                                               .push_slice(&wpubkey_hash.into_inner())
594                                                               .into_script()
595                                         },
596                                         Err(_) => panic!("Your RNG is busted"),
597                                 };
598                                 let shutdown_pubkey = match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(2).unwrap()) {
599                                         Ok(shutdown_key) => ExtendedPubKey::from_private(&secp_ctx, &shutdown_key).public_key.key,
600                                         Err(_) => panic!("Your RNG is busted"),
601                                 };
602                                 let channel_master_key = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(3).unwrap()).expect("Your RNG is busted");
603                                 let session_master_key = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(4).unwrap()).expect("Your RNG is busted");
604                                 let channel_id_master_key = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(5).unwrap()).expect("Your RNG is busted");
605
606                                 KeysManager {
607                                         secp_ctx,
608                                         node_secret,
609                                         destination_script,
610                                         shutdown_pubkey,
611                                         channel_master_key,
612                                         channel_child_index: AtomicUsize::new(0),
613                                         session_master_key,
614                                         session_child_index: AtomicUsize::new(0),
615                                         channel_id_master_key,
616                                         channel_id_child_index: AtomicUsize::new(0),
617
618                                         seed: *seed,
619                                         starting_time_secs,
620                                         starting_time_nanos,
621                                 }
622                         },
623                         Err(_) => panic!("Your rng is busted"),
624                 }
625         }
626         fn derive_unique_start(&self) -> Sha256State {
627                 let mut unique_start = Sha256::engine();
628                 unique_start.input(&byte_utils::be64_to_array(self.starting_time_secs));
629                 unique_start.input(&byte_utils::be32_to_array(self.starting_time_nanos));
630                 unique_start.input(&self.seed);
631                 unique_start
632         }
633         /// Derive an old set of ChannelKeys for per-channel secrets based on a key derivation
634         /// parameters.
635         /// Key derivation parameters are accessible through a per-channel secrets
636         /// ChannelKeys::key_derivation_params and is provided inside DynamicOuputP2WSH in case of
637         /// onchain output detection for which a corresponding delayed_payment_key must be derived.
638         pub fn derive_channel_keys(&self, channel_value_satoshis: u64, params_1: u64, params_2: u64) -> InMemoryChannelKeys {
639                 let chan_id = ((params_1 & 0xFFFF_FFFF_0000_0000) >> 32) as u32;
640                 let mut unique_start = Sha256::engine();
641                 unique_start.input(&byte_utils::be64_to_array(params_2));
642                 unique_start.input(&byte_utils::be32_to_array(params_1 as u32));
643                 unique_start.input(&self.seed);
644
645                 // We only seriously intend to rely on the channel_master_key for true secure
646                 // entropy, everything else just ensures uniqueness. We rely on the unique_start (ie
647                 // starting_time provided in the constructor) to be unique.
648                 let child_privkey = self.channel_master_key.ckd_priv(&self.secp_ctx, ChildNumber::from_hardened_idx(chan_id).expect("key space exhausted")).expect("Your RNG is busted");
649                 unique_start.input(&child_privkey.private_key.key[..]);
650
651                 let seed = Sha256::from_engine(unique_start).into_inner();
652
653                 let commitment_seed = {
654                         let mut sha = Sha256::engine();
655                         sha.input(&seed);
656                         sha.input(&b"commitment seed"[..]);
657                         Sha256::from_engine(sha).into_inner()
658                 };
659                 macro_rules! key_step {
660                         ($info: expr, $prev_key: expr) => {{
661                                 let mut sha = Sha256::engine();
662                                 sha.input(&seed);
663                                 sha.input(&$prev_key[..]);
664                                 sha.input(&$info[..]);
665                                 SecretKey::from_slice(&Sha256::from_engine(sha).into_inner()).expect("SHA-256 is busted")
666                         }}
667                 }
668                 let funding_key = key_step!(b"funding key", commitment_seed);
669                 let revocation_base_key = key_step!(b"revocation base key", funding_key);
670                 let payment_key = key_step!(b"payment key", revocation_base_key);
671                 let delayed_payment_base_key = key_step!(b"delayed payment base key", payment_key);
672                 let htlc_base_key = key_step!(b"HTLC base key", delayed_payment_base_key);
673
674                 InMemoryChannelKeys::new(
675                         &self.secp_ctx,
676                         funding_key,
677                         revocation_base_key,
678                         payment_key,
679                         delayed_payment_base_key,
680                         htlc_base_key,
681                         commitment_seed,
682                         channel_value_satoshis,
683                         (params_1, params_2),
684                 )
685         }
686 }
687
688 impl KeysInterface for KeysManager {
689         type ChanKeySigner = InMemoryChannelKeys;
690
691         fn get_node_secret(&self) -> SecretKey {
692                 self.node_secret.clone()
693         }
694
695         fn get_destination_script(&self) -> Script {
696                 self.destination_script.clone()
697         }
698
699         fn get_shutdown_pubkey(&self) -> PublicKey {
700                 self.shutdown_pubkey.clone()
701         }
702
703         fn get_channel_keys(&self, _inbound: bool, channel_value_satoshis: u64) -> InMemoryChannelKeys {
704                 let child_ix = self.channel_child_index.fetch_add(1, Ordering::AcqRel);
705                 let ix_and_nanos: u64 = (child_ix as u64) << 32 | (self.starting_time_nanos as u64);
706                 self.derive_channel_keys(channel_value_satoshis, ix_and_nanos, self.starting_time_secs)
707         }
708
709         fn get_onion_rand(&self) -> (SecretKey, [u8; 32]) {
710                 let mut sha = self.derive_unique_start();
711
712                 let child_ix = self.session_child_index.fetch_add(1, Ordering::AcqRel);
713                 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");
714                 sha.input(&child_privkey.private_key.key[..]);
715
716                 let mut rng_seed = sha.clone();
717                 // Not exactly the most ideal construction, but the second value will get fed into
718                 // ChaCha so it is another step harder to break.
719                 rng_seed.input(b"RNG Seed Salt");
720                 sha.input(b"Session Key Salt");
721                 (SecretKey::from_slice(&Sha256::from_engine(sha).into_inner()).expect("Your RNG is busted"),
722                 Sha256::from_engine(rng_seed).into_inner())
723         }
724
725         fn get_channel_id(&self) -> [u8; 32] {
726                 let mut sha = self.derive_unique_start();
727
728                 let child_ix = self.channel_id_child_index.fetch_add(1, Ordering::AcqRel);
729                 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");
730                 sha.input(&child_privkey.private_key.key[..]);
731
732                 Sha256::from_engine(sha).into_inner()
733         }
734 }