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