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