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