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