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