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