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