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