Relicense as dual Apache-2.0 + MIT
[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(test)]
251         fn unsafe_sign_local_commitment<T: secp256k1::Signing + secp256k1::Verification>(&self, local_commitment_tx: &LocalCommitmentTransaction, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()>;
252
253         /// Create a signature for each HTLC transaction spending a local commitment transaction.
254         ///
255         /// Unlike sign_local_commitment, this may be called multiple times with *different*
256         /// local_commitment_tx values. While this will never be called with a revoked
257         /// local_commitment_tx, it is possible that it is called with the second-latest
258         /// local_commitment_tx (only if we haven't yet revoked it) if some watchtower/secondary
259         /// ChannelMonitor decided to broadcast before it had been updated to the latest.
260         ///
261         /// Either an Err should be returned, or a Vec with one entry for each HTLC which exists in
262         /// local_commitment_tx. For those HTLCs which have transaction_output_index set to None
263         /// (implying they were considered dust at the time the commitment transaction was negotiated),
264         /// a corresponding None should be included in the return value. All other positions in the
265         /// return value must contain a signature.
266         fn sign_local_commitment_htlc_transactions<T: secp256k1::Signing + secp256k1::Verification>(&self, local_commitment_tx: &LocalCommitmentTransaction, 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         /// Get a secret and PRNG seed for constructing an onion packet
345         fn get_onion_rand(&self) -> (SecretKey, [u8; 32]);
346         /// Get a unique temporary channel id. Channels will be referred to by this until the funding
347         /// transaction is created, at which point they will use the outpoint in the funding
348         /// transaction.
349         fn get_channel_id(&self) -> [u8; 32];
350 }
351
352 #[derive(Clone)]
353 /// Holds late-bound channel data.
354 /// This data is available after the channel is known to be accepted, either
355 /// when receiving an open_channel for an inbound channel or when
356 /// receiving accept_channel for an outbound channel.
357 struct AcceptedChannelData {
358         /// Remote public keys and base points
359         remote_channel_pubkeys: ChannelPublicKeys,
360         /// The to_self_delay value specified by our counterparty and applied on locally-broadcastable
361         /// transactions, ie the amount of time that we have to wait to recover our funds if we
362         /// broadcast a transaction. You'll likely want to pass this to the
363         /// ln::chan_utils::build*_transaction functions when signing local transactions.
364         remote_to_self_delay: u16,
365         /// The to_self_delay value specified by us and applied on transactions broadcastable
366         /// by our counterparty, ie the amount of time that they have to wait to recover their funds
367         /// if they broadcast a transaction.
368         local_to_self_delay: u16,
369 }
370
371 #[derive(Clone)]
372 /// A simple implementation of ChannelKeys that just keeps the private keys in memory.
373 pub struct InMemoryChannelKeys {
374         /// Private key of anchor tx
375         pub funding_key: SecretKey,
376         /// Local secret key for blinded revocation pubkey
377         pub revocation_base_key: SecretKey,
378         /// Local secret key used for our balance in remote-broadcasted commitment transactions
379         pub payment_key: SecretKey,
380         /// Local secret key used in HTLC tx
381         pub delayed_payment_base_key: SecretKey,
382         /// Local htlc secret key used in commitment tx htlc outputs
383         pub htlc_base_key: SecretKey,
384         /// Commitment seed
385         pub commitment_seed: [u8; 32],
386         /// Local public keys and basepoints
387         pub(crate) local_channel_pubkeys: ChannelPublicKeys,
388         /// Remote public keys and remote/local to_self_delay, populated on channel acceptance
389         accepted_channel_data: Option<AcceptedChannelData>,
390         /// The total value of this channel
391         channel_value_satoshis: u64,
392         /// Key derivation parameters
393         key_derivation_params: (u64, u64),
394 }
395
396 impl InMemoryChannelKeys {
397         /// Create a new InMemoryChannelKeys
398         pub fn new<C: Signing>(
399                 secp_ctx: &Secp256k1<C>,
400                 funding_key: SecretKey,
401                 revocation_base_key: SecretKey,
402                 payment_key: SecretKey,
403                 delayed_payment_base_key: SecretKey,
404                 htlc_base_key: SecretKey,
405                 commitment_seed: [u8; 32],
406                 channel_value_satoshis: u64,
407                 key_derivation_params: (u64, u64)) -> InMemoryChannelKeys {
408                 let local_channel_pubkeys =
409                         InMemoryChannelKeys::make_local_keys(secp_ctx, &funding_key, &revocation_base_key,
410                                                              &payment_key, &delayed_payment_base_key,
411                                                              &htlc_base_key);
412                 InMemoryChannelKeys {
413                         funding_key,
414                         revocation_base_key,
415                         payment_key,
416                         delayed_payment_base_key,
417                         htlc_base_key,
418                         commitment_seed,
419                         channel_value_satoshis,
420                         local_channel_pubkeys,
421                         accepted_channel_data: None,
422                         key_derivation_params,
423                 }
424         }
425
426         fn make_local_keys<C: Signing>(secp_ctx: &Secp256k1<C>,
427                                        funding_key: &SecretKey,
428                                        revocation_base_key: &SecretKey,
429                                        payment_key: &SecretKey,
430                                        delayed_payment_base_key: &SecretKey,
431                                        htlc_base_key: &SecretKey) -> ChannelPublicKeys {
432                 let from_secret = |s: &SecretKey| PublicKey::from_secret_key(secp_ctx, s);
433                 ChannelPublicKeys {
434                         funding_pubkey: from_secret(&funding_key),
435                         revocation_basepoint: from_secret(&revocation_base_key),
436                         payment_point: from_secret(&payment_key),
437                         delayed_payment_basepoint: from_secret(&delayed_payment_base_key),
438                         htlc_basepoint: from_secret(&htlc_base_key),
439                 }
440         }
441
442         /// Remote pubkeys.
443         /// Will panic if on_accept wasn't called.
444         pub fn remote_pubkeys(&self) -> &ChannelPublicKeys { &self.accepted_channel_data.as_ref().unwrap().remote_channel_pubkeys }
445
446         /// The to_self_delay value specified by our counterparty and applied on locally-broadcastable
447         /// transactions, ie the amount of time that we have to wait to recover our funds if we
448         /// broadcast a transaction. You'll likely want to pass this to the
449         /// ln::chan_utils::build*_transaction functions when signing local transactions.
450         /// Will panic if on_accept wasn't called.
451         pub fn remote_to_self_delay(&self) -> u16 { self.accepted_channel_data.as_ref().unwrap().remote_to_self_delay }
452
453         /// The to_self_delay value specified by us and applied on transactions broadcastable
454         /// by our counterparty, ie the amount of time that they have to wait to recover their funds
455         /// if they broadcast a transaction.
456         /// Will panic if on_accept wasn't called.
457         pub fn local_to_self_delay(&self) -> u16 { self.accepted_channel_data.as_ref().unwrap().local_to_self_delay }
458 }
459
460 impl ChannelKeys for InMemoryChannelKeys {
461         fn get_per_commitment_point<T: secp256k1::Signing + secp256k1::Verification>(&self, idx: u64, secp_ctx: &Secp256k1<T>) -> PublicKey {
462                 let commitment_secret = SecretKey::from_slice(&chan_utils::build_commitment_secret(&self.commitment_seed, idx)).unwrap();
463                 PublicKey::from_secret_key(secp_ctx, &commitment_secret)
464         }
465
466         fn release_commitment_secret(&self, idx: u64) -> [u8; 32] {
467                 chan_utils::build_commitment_secret(&self.commitment_seed, idx)
468         }
469
470         fn pubkeys(&self) -> &ChannelPublicKeys { &self.local_channel_pubkeys }
471         fn key_derivation_params(&self) -> (u64, u64) { self.key_derivation_params }
472
473         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>), ()> {
474                 if commitment_tx.input.len() != 1 { return Err(()); }
475                 let keys = pre_keys.trust_key_derivation();
476
477                 let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
478                 let accepted_data = self.accepted_channel_data.as_ref().expect("must accept before signing");
479                 let channel_funding_redeemscript = make_funding_redeemscript(&funding_pubkey, &accepted_data.remote_channel_pubkeys.funding_pubkey);
480
481                 let commitment_sighash = hash_to_message!(&bip143::SighashComponents::new(&commitment_tx).sighash_all(&commitment_tx.input[0], &channel_funding_redeemscript, self.channel_value_satoshis)[..]);
482                 let commitment_sig = secp_ctx.sign(&commitment_sighash, &self.funding_key);
483
484                 let commitment_txid = commitment_tx.txid();
485
486                 let mut htlc_sigs = Vec::with_capacity(htlcs.len());
487                 for ref htlc in htlcs {
488                         if let Some(_) = htlc.transaction_output_index {
489                                 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);
490                                 let htlc_redeemscript = chan_utils::get_htlc_redeemscript(&htlc, &keys);
491                                 let htlc_sighash = hash_to_message!(&bip143::SighashComponents::new(&htlc_tx).sighash_all(&htlc_tx.input[0], &htlc_redeemscript, htlc.amount_msat / 1000)[..]);
492                                 let our_htlc_key = match chan_utils::derive_private_key(&secp_ctx, &keys.per_commitment_point, &self.htlc_base_key) {
493                                         Ok(s) => s,
494                                         Err(_) => return Err(()),
495                                 };
496                                 htlc_sigs.push(secp_ctx.sign(&htlc_sighash, &our_htlc_key));
497                         }
498                 }
499
500                 Ok((commitment_sig, htlc_sigs))
501         }
502
503         fn sign_local_commitment<T: secp256k1::Signing + secp256k1::Verification>(&self, local_commitment_tx: &LocalCommitmentTransaction, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()> {
504                 let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
505                 let remote_channel_data = self.accepted_channel_data.as_ref().expect("must accept before signing");
506                 let channel_funding_redeemscript = make_funding_redeemscript(&funding_pubkey, &remote_channel_data.remote_channel_pubkeys.funding_pubkey);
507
508                 Ok(local_commitment_tx.get_local_sig(&self.funding_key, &channel_funding_redeemscript, self.channel_value_satoshis, secp_ctx))
509         }
510
511         #[cfg(test)]
512         fn unsafe_sign_local_commitment<T: secp256k1::Signing + secp256k1::Verification>(&self, local_commitment_tx: &LocalCommitmentTransaction, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()> {
513                 let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
514                 let remote_channel_pubkeys = &self.accepted_channel_data.as_ref().expect("must accept before signing").remote_channel_pubkeys;
515                 let channel_funding_redeemscript = make_funding_redeemscript(&funding_pubkey, &remote_channel_pubkeys.funding_pubkey);
516
517                 Ok(local_commitment_tx.get_local_sig(&self.funding_key, &channel_funding_redeemscript, self.channel_value_satoshis, secp_ctx))
518         }
519
520         fn sign_local_commitment_htlc_transactions<T: secp256k1::Signing + secp256k1::Verification>(&self, local_commitment_tx: &LocalCommitmentTransaction, secp_ctx: &Secp256k1<T>) -> Result<Vec<Option<Signature>>, ()> {
521                 let local_csv = self.accepted_channel_data.as_ref().unwrap().remote_to_self_delay;
522                 local_commitment_tx.get_htlc_sigs(&self.htlc_base_key, local_csv, secp_ctx)
523         }
524
525         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, ()> {
526                 let revocation_key = match chan_utils::derive_private_revocation_key(&secp_ctx, &per_commitment_key, &self.revocation_base_key) {
527                         Ok(revocation_key) => revocation_key,
528                         Err(_) => return Err(())
529                 };
530                 let per_commitment_point = PublicKey::from_secret_key(secp_ctx, &per_commitment_key);
531                 let revocation_pubkey = match chan_utils::derive_public_revocation_key(&secp_ctx, &per_commitment_point, &self.pubkeys().revocation_basepoint) {
532                         Ok(revocation_pubkey) => revocation_pubkey,
533                         Err(_) => return Err(())
534                 };
535                 let witness_script = if let &Some(ref htlc) = htlc {
536                         let remote_htlcpubkey = match chan_utils::derive_public_key(&secp_ctx, &per_commitment_point, &self.remote_pubkeys().htlc_basepoint) {
537                                 Ok(remote_htlcpubkey) => remote_htlcpubkey,
538                                 Err(_) => return Err(())
539                         };
540                         let local_htlcpubkey = match chan_utils::derive_public_key(&secp_ctx, &per_commitment_point, &self.pubkeys().htlc_basepoint) {
541                                 Ok(local_htlcpubkey) => local_htlcpubkey,
542                                 Err(_) => return Err(())
543                         };
544                         chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, &remote_htlcpubkey, &local_htlcpubkey, &revocation_pubkey)
545                 } else {
546                         let remote_delayedpubkey = match chan_utils::derive_public_key(&secp_ctx, &per_commitment_point, &self.remote_pubkeys().delayed_payment_basepoint) {
547                                 Ok(remote_delayedpubkey) => remote_delayedpubkey,
548                                 Err(_) => return Err(())
549                         };
550                         chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.local_to_self_delay(), &remote_delayedpubkey)
551                 };
552                 let sighash_parts = bip143::SighashComponents::new(&justice_tx);
553                 let sighash = hash_to_message!(&sighash_parts.sighash_all(&justice_tx.input[input], &witness_script, amount)[..]);
554                 return Ok(secp_ctx.sign(&sighash, &revocation_key))
555         }
556
557         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, ()> {
558                 if let Ok(htlc_key) = chan_utils::derive_private_key(&secp_ctx, &per_commitment_point, &self.htlc_base_key) {
559                         let witness_script = if let Ok(revocation_pubkey) = chan_utils::derive_public_revocation_key(&secp_ctx, &per_commitment_point, &self.pubkeys().revocation_basepoint) {
560                                 if let Ok(remote_htlcpubkey) = chan_utils::derive_public_key(&secp_ctx, &per_commitment_point, &self.remote_pubkeys().htlc_basepoint) {
561                                         if let Ok(local_htlcpubkey) = chan_utils::derive_public_key(&secp_ctx, &per_commitment_point, &self.pubkeys().htlc_basepoint) {
562                                                 chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, &remote_htlcpubkey, &local_htlcpubkey, &revocation_pubkey)
563                                         } else { return Err(()) }
564                                 } else { return Err(()) }
565                         } else { return Err(()) };
566                         let sighash_parts = bip143::SighashComponents::new(&htlc_tx);
567                         let sighash = hash_to_message!(&sighash_parts.sighash_all(&htlc_tx.input[input], &witness_script, amount)[..]);
568                         return Ok(secp_ctx.sign(&sighash, &htlc_key))
569                 }
570                 Err(())
571         }
572
573         fn sign_closing_transaction<T: secp256k1::Signing>(&self, closing_tx: &Transaction, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()> {
574                 if closing_tx.input.len() != 1 { return Err(()); }
575                 if closing_tx.input[0].witness.len() != 0 { return Err(()); }
576                 if closing_tx.output.len() > 2 { return Err(()); }
577
578                 let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
579                 let remote_channel_data = self.accepted_channel_data.as_ref().expect("must accept before signing");
580                 let channel_funding_redeemscript = make_funding_redeemscript(&funding_pubkey, &remote_channel_data.remote_channel_pubkeys.funding_pubkey);
581
582                 let sighash = hash_to_message!(&bip143::SighashComponents::new(closing_tx)
583                         .sighash_all(&closing_tx.input[0], &channel_funding_redeemscript, self.channel_value_satoshis)[..]);
584                 Ok(secp_ctx.sign(&sighash, &self.funding_key))
585         }
586
587         fn sign_channel_announcement<T: secp256k1::Signing>(&self, msg: &msgs::UnsignedChannelAnnouncement, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()> {
588                 let msghash = hash_to_message!(&Sha256dHash::hash(&msg.encode()[..])[..]);
589                 Ok(secp_ctx.sign(&msghash, &self.funding_key))
590         }
591
592         fn on_accept(&mut self, channel_pubkeys: &ChannelPublicKeys, remote_to_self_delay: u16, local_to_self_delay: u16) {
593                 assert!(self.accepted_channel_data.is_none(), "Already accepted");
594                 self.accepted_channel_data = Some(AcceptedChannelData {
595                         remote_channel_pubkeys: channel_pubkeys.clone(),
596                         remote_to_self_delay,
597                         local_to_self_delay,
598                 });
599         }
600 }
601
602 impl_writeable!(AcceptedChannelData, 0,
603  { remote_channel_pubkeys, remote_to_self_delay, local_to_self_delay });
604
605 impl Writeable for InMemoryChannelKeys {
606         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), Error> {
607                 self.funding_key.write(writer)?;
608                 self.revocation_base_key.write(writer)?;
609                 self.payment_key.write(writer)?;
610                 self.delayed_payment_base_key.write(writer)?;
611                 self.htlc_base_key.write(writer)?;
612                 self.commitment_seed.write(writer)?;
613                 self.accepted_channel_data.write(writer)?;
614                 self.channel_value_satoshis.write(writer)?;
615                 self.key_derivation_params.0.write(writer)?;
616                 self.key_derivation_params.1.write(writer)?;
617
618                 Ok(())
619         }
620 }
621
622 impl Readable for InMemoryChannelKeys {
623         fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
624                 let funding_key = Readable::read(reader)?;
625                 let revocation_base_key = Readable::read(reader)?;
626                 let payment_key = Readable::read(reader)?;
627                 let delayed_payment_base_key = Readable::read(reader)?;
628                 let htlc_base_key = Readable::read(reader)?;
629                 let commitment_seed = Readable::read(reader)?;
630                 let remote_channel_data = Readable::read(reader)?;
631                 let channel_value_satoshis = Readable::read(reader)?;
632                 let secp_ctx = Secp256k1::signing_only();
633                 let local_channel_pubkeys =
634                         InMemoryChannelKeys::make_local_keys(&secp_ctx, &funding_key, &revocation_base_key,
635                                                              &payment_key, &delayed_payment_base_key,
636                                                              &htlc_base_key);
637                 let params_1 = Readable::read(reader)?;
638                 let params_2 = Readable::read(reader)?;
639
640                 Ok(InMemoryChannelKeys {
641                         funding_key,
642                         revocation_base_key,
643                         payment_key,
644                         delayed_payment_base_key,
645                         htlc_base_key,
646                         commitment_seed,
647                         channel_value_satoshis,
648                         local_channel_pubkeys,
649                         accepted_channel_data: remote_channel_data,
650                         key_derivation_params: (params_1, params_2),
651                 })
652         }
653 }
654
655 /// Simple KeysInterface implementor that takes a 32-byte seed for use as a BIP 32 extended key
656 /// and derives keys from that.
657 ///
658 /// Your node_id is seed/0'
659 /// ChannelMonitor closes may use seed/1'
660 /// Cooperative closes may use seed/2'
661 /// The two close keys may be needed to claim on-chain funds!
662 pub struct KeysManager {
663         secp_ctx: Secp256k1<secp256k1::SignOnly>,
664         node_secret: SecretKey,
665         destination_script: Script,
666         shutdown_pubkey: PublicKey,
667         channel_master_key: ExtendedPrivKey,
668         channel_child_index: AtomicUsize,
669         session_master_key: ExtendedPrivKey,
670         session_child_index: AtomicUsize,
671         channel_id_master_key: ExtendedPrivKey,
672         channel_id_child_index: AtomicUsize,
673
674         seed: [u8; 32],
675         starting_time_secs: u64,
676         starting_time_nanos: u32,
677 }
678
679 impl KeysManager {
680         /// Constructs a KeysManager from a 32-byte seed. If the seed is in some way biased (eg your
681         /// RNG is busted) this may panic (but more importantly, you will possibly lose funds).
682         /// starting_time isn't strictly required to actually be a time, but it must absolutely,
683         /// without a doubt, be unique to this instance. ie if you start multiple times with the same
684         /// seed, starting_time must be unique to each run. Thus, the easiest way to achieve this is to
685         /// simply use the current time (with very high precision).
686         ///
687         /// The seed MUST be backed up safely prior to use so that the keys can be re-created, however,
688         /// obviously, starting_time should be unique every time you reload the library - it is only
689         /// used to generate new ephemeral key data (which will be stored by the individual channel if
690         /// necessary).
691         ///
692         /// Note that the seed is required to recover certain on-chain funds independent of
693         /// ChannelMonitor data, though a current copy of ChannelMonitor data is also required for any
694         /// channel, and some on-chain during-closing funds.
695         ///
696         /// Note that until the 0.1 release there is no guarantee of backward compatibility between
697         /// versions. Once the library is more fully supported, the docs will be updated to include a
698         /// detailed description of the guarantee.
699         pub fn new(seed: &[u8; 32], network: Network, starting_time_secs: u64, starting_time_nanos: u32) -> Self {
700                 let secp_ctx = Secp256k1::signing_only();
701                 match ExtendedPrivKey::new_master(network.clone(), seed) {
702                         Ok(master_key) => {
703                                 let node_secret = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(0).unwrap()).expect("Your RNG is busted").private_key.key;
704                                 let destination_script = match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(1).unwrap()) {
705                                         Ok(destination_key) => {
706                                                 let wpubkey_hash = WPubkeyHash::hash(&ExtendedPubKey::from_private(&secp_ctx, &destination_key).public_key.to_bytes());
707                                                 Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0)
708                                                               .push_slice(&wpubkey_hash.into_inner())
709                                                               .into_script()
710                                         },
711                                         Err(_) => panic!("Your RNG is busted"),
712                                 };
713                                 let shutdown_pubkey = match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(2).unwrap()) {
714                                         Ok(shutdown_key) => ExtendedPubKey::from_private(&secp_ctx, &shutdown_key).public_key.key,
715                                         Err(_) => panic!("Your RNG is busted"),
716                                 };
717                                 let channel_master_key = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(3).unwrap()).expect("Your RNG is busted");
718                                 let session_master_key = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(4).unwrap()).expect("Your RNG is busted");
719                                 let channel_id_master_key = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(5).unwrap()).expect("Your RNG is busted");
720
721                                 KeysManager {
722                                         secp_ctx,
723                                         node_secret,
724                                         destination_script,
725                                         shutdown_pubkey,
726                                         channel_master_key,
727                                         channel_child_index: AtomicUsize::new(0),
728                                         session_master_key,
729                                         session_child_index: AtomicUsize::new(0),
730                                         channel_id_master_key,
731                                         channel_id_child_index: AtomicUsize::new(0),
732
733                                         seed: *seed,
734                                         starting_time_secs,
735                                         starting_time_nanos,
736                                 }
737                         },
738                         Err(_) => panic!("Your rng is busted"),
739                 }
740         }
741         fn derive_unique_start(&self) -> Sha256State {
742                 let mut unique_start = Sha256::engine();
743                 unique_start.input(&byte_utils::be64_to_array(self.starting_time_secs));
744                 unique_start.input(&byte_utils::be32_to_array(self.starting_time_nanos));
745                 unique_start.input(&self.seed);
746                 unique_start
747         }
748         /// Derive an old set of ChannelKeys for per-channel secrets based on a key derivation
749         /// parameters.
750         /// Key derivation parameters are accessible through a per-channel secrets
751         /// ChannelKeys::key_derivation_params and is provided inside DynamicOuputP2WSH in case of
752         /// onchain output detection for which a corresponding delayed_payment_key must be derived.
753         pub fn derive_channel_keys(&self, channel_value_satoshis: u64, params_1: u64, params_2: u64) -> InMemoryChannelKeys {
754                 let chan_id = ((params_1 & 0xFFFF_FFFF_0000_0000) >> 32) as u32;
755                 let mut unique_start = Sha256::engine();
756                 unique_start.input(&byte_utils::be64_to_array(params_2));
757                 unique_start.input(&byte_utils::be32_to_array(params_1 as u32));
758                 unique_start.input(&self.seed);
759
760                 // We only seriously intend to rely on the channel_master_key for true secure
761                 // entropy, everything else just ensures uniqueness. We rely on the unique_start (ie
762                 // starting_time provided in the constructor) to be unique.
763                 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");
764                 unique_start.input(&child_privkey.private_key.key[..]);
765
766                 let seed = Sha256::from_engine(unique_start).into_inner();
767
768                 let commitment_seed = {
769                         let mut sha = Sha256::engine();
770                         sha.input(&seed);
771                         sha.input(&b"commitment seed"[..]);
772                         Sha256::from_engine(sha).into_inner()
773                 };
774                 macro_rules! key_step {
775                         ($info: expr, $prev_key: expr) => {{
776                                 let mut sha = Sha256::engine();
777                                 sha.input(&seed);
778                                 sha.input(&$prev_key[..]);
779                                 sha.input(&$info[..]);
780                                 SecretKey::from_slice(&Sha256::from_engine(sha).into_inner()).expect("SHA-256 is busted")
781                         }}
782                 }
783                 let funding_key = key_step!(b"funding key", commitment_seed);
784                 let revocation_base_key = key_step!(b"revocation base key", funding_key);
785                 let payment_key = key_step!(b"payment key", revocation_base_key);
786                 let delayed_payment_base_key = key_step!(b"delayed payment base key", payment_key);
787                 let htlc_base_key = key_step!(b"HTLC base key", delayed_payment_base_key);
788
789                 InMemoryChannelKeys::new(
790                         &self.secp_ctx,
791                         funding_key,
792                         revocation_base_key,
793                         payment_key,
794                         delayed_payment_base_key,
795                         htlc_base_key,
796                         commitment_seed,
797                         channel_value_satoshis,
798                         (params_1, params_2),
799                 )
800         }
801 }
802
803 impl KeysInterface for KeysManager {
804         type ChanKeySigner = InMemoryChannelKeys;
805
806         fn get_node_secret(&self) -> SecretKey {
807                 self.node_secret.clone()
808         }
809
810         fn get_destination_script(&self) -> Script {
811                 self.destination_script.clone()
812         }
813
814         fn get_shutdown_pubkey(&self) -> PublicKey {
815                 self.shutdown_pubkey.clone()
816         }
817
818         fn get_channel_keys(&self, _inbound: bool, channel_value_satoshis: u64) -> InMemoryChannelKeys {
819                 let child_ix = self.channel_child_index.fetch_add(1, Ordering::AcqRel);
820                 let ix_and_nanos: u64 = (child_ix as u64) << 32 | (self.starting_time_nanos as u64);
821                 self.derive_channel_keys(channel_value_satoshis, ix_and_nanos, self.starting_time_secs)
822         }
823
824         fn get_onion_rand(&self) -> (SecretKey, [u8; 32]) {
825                 let mut sha = self.derive_unique_start();
826
827                 let child_ix = self.session_child_index.fetch_add(1, Ordering::AcqRel);
828                 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");
829                 sha.input(&child_privkey.private_key.key[..]);
830
831                 let mut rng_seed = sha.clone();
832                 // Not exactly the most ideal construction, but the second value will get fed into
833                 // ChaCha so it is another step harder to break.
834                 rng_seed.input(b"RNG Seed Salt");
835                 sha.input(b"Session Key Salt");
836                 (SecretKey::from_slice(&Sha256::from_engine(sha).into_inner()).expect("Your RNG is busted"),
837                 Sha256::from_engine(rng_seed).into_inner())
838         }
839
840         fn get_channel_id(&self) -> [u8; 32] {
841                 let mut sha = self.derive_unique_start();
842
843                 let child_ix = self.channel_id_child_index.fetch_add(1, Ordering::AcqRel);
844                 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");
845                 sha.input(&child_privkey.private_key.key[..]);
846
847                 Sha256::from_engine(sha).into_inner()
848         }
849 }