Merge pull request #404 from TheBlueMatt/2019-11-signer-api
[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::hash160::Hash as Hash160;
16
17 use secp256k1::key::{SecretKey, PublicKey};
18 use secp256k1::{Secp256k1, Signature};
19 use secp256k1;
20
21 use util::byte_utils;
22 use util::logger::Logger;
23
24 use ln::chan_utils;
25 use ln::chan_utils::{TxCreationKeys, HTLCOutputInCommitment};
26
27 use std::sync::Arc;
28 use std::sync::atomic::{AtomicUsize, Ordering};
29
30 /// When on-chain outputs are created by rust-lightning an event is generated which informs the
31 /// user thereof. This enum describes the format of the output and provides the OutPoint.
32 pub enum SpendableOutputDescriptor {
33         /// Outpoint with an output to a script which was provided via KeysInterface, thus you should
34         /// have stored somewhere how to spend script_pubkey!
35         /// Outputs from a justice tx, claim tx or preimage tx
36         StaticOutput {
37                 /// The outpoint spendable by user wallet
38                 outpoint: OutPoint,
39                 /// The output which is referenced by the given outpoint
40                 output: TxOut,
41         },
42         /// Outpoint commits to a P2WSH
43         /// P2WSH should be spend by the following witness :
44         /// <local_delayedsig> 0 <witnessScript>
45         /// With input nSequence set to_self_delay.
46         /// Outputs from a HTLC-Success/Timeout tx/commitment tx
47         DynamicOutputP2WSH {
48                 /// Outpoint spendable by user wallet
49                 outpoint: OutPoint,
50                 /// local_delayedkey = delayed_payment_basepoint_secret + SHA256(per_commitment_point || delayed_payment_basepoint) OR
51                 key: SecretKey,
52                 /// witness redeemScript encumbering output.
53                 witness_script: Script,
54                 /// nSequence input must commit to self_delay to satisfy script's OP_CSV
55                 to_self_delay: u16,
56                 /// The output which is referenced by the given outpoint
57                 output: TxOut,
58         },
59         /// Outpoint commits to a P2WPKH
60         /// P2WPKH should be spend by the following witness :
61         /// <local_sig> <local_pubkey>
62         /// Outputs to_remote from a commitment tx
63         DynamicOutputP2WPKH {
64                 /// Outpoint spendable by user wallet
65                 outpoint: OutPoint,
66                 /// localkey = payment_basepoint_secret + SHA256(per_commitment_point || payment_basepoint
67                 key: SecretKey,
68                 /// The output which is reference by the given outpoint
69                 output: TxOut,
70         }
71 }
72
73 /// A trait to describe an object which can get user secrets and key material.
74 pub trait KeysInterface: Send + Sync {
75         /// A type which implements ChannelKeys which will be returned by get_channel_keys.
76         type ChanKeySigner : ChannelKeys;
77
78         /// Get node secret key (aka node_id or network_key)
79         fn get_node_secret(&self) -> SecretKey;
80         /// Get destination redeemScript to encumber static protocol exit points.
81         fn get_destination_script(&self) -> Script;
82         /// Get shutdown_pubkey to use as PublicKey at channel closure
83         fn get_shutdown_pubkey(&self) -> PublicKey;
84         /// Get a new set of ChannelKeys for per-channel secrets. These MUST be unique even if you
85         /// restarted with some stale data!
86         fn get_channel_keys(&self, inbound: bool) -> Self::ChanKeySigner;
87         /// Get a secret and PRNG seed for construting an onion packet
88         fn get_onion_rand(&self) -> (SecretKey, [u8; 32]);
89         /// Get a unique temporary channel id. Channels will be referred to by this until the funding
90         /// transaction is created, at which point they will use the outpoint in the funding
91         /// transaction.
92         fn get_channel_id(&self) -> [u8; 32];
93 }
94
95 /// Set of lightning keys needed to operate a channel as described in BOLT 3.
96 ///
97 /// Signing services could be implemented on a hardware wallet. In this case,
98 /// the current ChannelKeys would be a front-end on top of a communication
99 /// channel connected to your secure device and lightning key material wouldn't
100 /// reside on a hot server. Nevertheless, a this deployment would still need
101 /// to trust the ChannelManager to avoid loss of funds as this latest component
102 /// could ask to sign commitment transaction with HTLCs paying to attacker pubkeys.
103 ///
104 /// A more secure iteration would be to use hashlock (or payment points) to pair
105 /// invoice/incoming HTLCs with outgoing HTLCs to implement a no-trust-ChannelManager
106 /// at the price of more state and computation on the hardware wallet side. In the future,
107 /// we are looking forward to design such interface.
108 ///
109 /// In any case, ChannelMonitor or fallback watchtowers are always going to be trusted
110 /// to act, as liveness and breach reply correctness are always going to be hard requirements
111 /// of LN security model, orthogonal of key management issues.
112 ///
113 /// If you're implementing a custom signer, you almost certainly want to implement
114 /// Readable/Writable to serialize out a unique reference to this set of keys so
115 /// that you can serialize the full ChannelManager object.
116 ///
117 /// (TODO: We shouldn't require that, and should have an API to get them at deser time, due mostly
118 /// to the possibility of reentrancy issues by calling the user's code during our deserialization
119 /// routine).
120 pub trait ChannelKeys : Send {
121         /// Gets the private key for the anchor tx
122         fn funding_key<'a>(&'a self) -> &'a SecretKey;
123         /// Gets the local secret key for blinded revocation pubkey
124         fn revocation_base_key<'a>(&'a self) -> &'a SecretKey;
125         /// Gets the local secret key used in to_remote output of remote commitment tx
126         /// (and also as part of obscured commitment number)
127         fn payment_base_key<'a>(&'a self) -> &'a SecretKey;
128         /// Gets the local secret key used in HTLC-Success/HTLC-Timeout txn and to_local output
129         fn delayed_payment_base_key<'a>(&'a self) -> &'a SecretKey;
130         /// Gets the local htlc secret key used in commitment tx htlc outputs
131         fn htlc_base_key<'a>(&'a self) -> &'a SecretKey;
132         /// Gets the commitment seed
133         fn commitment_seed<'a>(&'a self) -> &'a [u8; 32];
134
135         /// Create a signature for a remote commitment transaction and associated HTLC transactions.
136         ///
137         /// Note that if signing fails or is rejected, the channel will be force-closed.
138         ///
139         /// TODO: Document the things someone using this interface should enforce before signing.
140         /// TODO: Add more input vars to enable better checking (preferably removing commitment_tx and
141         /// making the callee generate it via some util function we expose)!
142         fn sign_remote_commitment<T: secp256k1::Signing>(&self, channel_value_satoshis: u64, channel_funding_script: &Script, feerate_per_kw: u64, commitment_tx: &Transaction, keys: &TxCreationKeys, htlcs: &[&HTLCOutputInCommitment], to_self_delay: u16, secp_ctx: &Secp256k1<T>) -> Result<(Signature, Vec<Signature>), ()>;
143 }
144
145 #[derive(Clone)]
146 /// A simple implementation of ChannelKeys that just keeps the private keys in memory.
147 pub struct InMemoryChannelKeys {
148         /// Private key of anchor tx
149         pub funding_key: SecretKey,
150         /// Local secret key for blinded revocation pubkey
151         pub revocation_base_key: SecretKey,
152         /// Local secret key used in commitment tx htlc outputs
153         pub payment_base_key: SecretKey,
154         /// Local secret key used in HTLC tx
155         pub delayed_payment_base_key: SecretKey,
156         /// Local htlc secret key used in commitment tx htlc outputs
157         pub htlc_base_key: SecretKey,
158         /// Commitment seed
159         pub commitment_seed: [u8; 32],
160 }
161
162 impl ChannelKeys for InMemoryChannelKeys {
163         fn funding_key(&self) -> &SecretKey { &self.funding_key }
164         fn revocation_base_key(&self) -> &SecretKey { &self.revocation_base_key }
165         fn payment_base_key(&self) -> &SecretKey { &self.payment_base_key }
166         fn delayed_payment_base_key(&self) -> &SecretKey { &self.delayed_payment_base_key }
167         fn htlc_base_key(&self) -> &SecretKey { &self.htlc_base_key }
168         fn commitment_seed(&self) -> &[u8; 32] { &self.commitment_seed }
169
170
171         fn sign_remote_commitment<T: secp256k1::Signing>(&self, channel_value_satoshis: u64, channel_funding_script: &Script, feerate_per_kw: u64, commitment_tx: &Transaction, keys: &TxCreationKeys, htlcs: &[&HTLCOutputInCommitment], to_self_delay: u16, secp_ctx: &Secp256k1<T>) -> Result<(Signature, Vec<Signature>), ()> {
172                 if commitment_tx.input.len() != 1 { return Err(()); }
173                 let commitment_sighash = hash_to_message!(&bip143::SighashComponents::new(&commitment_tx).sighash_all(&commitment_tx.input[0], &channel_funding_script, channel_value_satoshis)[..]);
174                 let commitment_sig = secp_ctx.sign(&commitment_sighash, &self.funding_key);
175
176                 let commitment_txid = commitment_tx.txid();
177
178                 let mut htlc_sigs = Vec::with_capacity(htlcs.len());
179                 for ref htlc in htlcs {
180                         if let Some(_) = htlc.transaction_output_index {
181                                 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);
182                                 let htlc_redeemscript = chan_utils::get_htlc_redeemscript(&htlc, &keys);
183                                 let htlc_sighash = hash_to_message!(&bip143::SighashComponents::new(&htlc_tx).sighash_all(&htlc_tx.input[0], &htlc_redeemscript, htlc.amount_msat / 1000)[..]);
184                                 let our_htlc_key = match chan_utils::derive_private_key(&secp_ctx, &keys.per_commitment_point, &self.htlc_base_key) {
185                                         Ok(s) => s,
186                                         Err(_) => return Err(()),
187                                 };
188                                 htlc_sigs.push(secp_ctx.sign(&htlc_sighash, &our_htlc_key));
189                         }
190                 }
191
192                 Ok((commitment_sig, htlc_sigs))
193         }
194 }
195
196 impl_writeable!(InMemoryChannelKeys, 0, {
197         funding_key,
198         revocation_base_key,
199         payment_base_key,
200         delayed_payment_base_key,
201         htlc_base_key,
202         commitment_seed
203 });
204
205 /// Simple KeysInterface implementor that takes a 32-byte seed for use as a BIP 32 extended key
206 /// and derives keys from that.
207 ///
208 /// Your node_id is seed/0'
209 /// ChannelMonitor closes may use seed/1'
210 /// Cooperative closes may use seed/2'
211 /// The two close keys may be needed to claim on-chain funds!
212 pub struct KeysManager {
213         secp_ctx: Secp256k1<secp256k1::SignOnly>,
214         node_secret: SecretKey,
215         destination_script: Script,
216         shutdown_pubkey: PublicKey,
217         channel_master_key: ExtendedPrivKey,
218         channel_child_index: AtomicUsize,
219         session_master_key: ExtendedPrivKey,
220         session_child_index: AtomicUsize,
221         channel_id_master_key: ExtendedPrivKey,
222         channel_id_child_index: AtomicUsize,
223
224         unique_start: Sha256State,
225         logger: Arc<Logger>,
226 }
227
228 impl KeysManager {
229         /// Constructs a KeysManager from a 32-byte seed. If the seed is in some way biased (eg your
230         /// RNG is busted) this may panic (but more importantly, you will possibly lose funds).
231         /// starting_time isn't strictly required to actually be a time, but it must absolutely,
232         /// without a doubt, be unique to this instance. ie if you start multiple times with the same
233         /// seed, starting_time must be unique to each run. Thus, the easiest way to achieve this is to
234         /// simply use the current time (with very high precision).
235         ///
236         /// The seed MUST be backed up safely prior to use so that the keys can be re-created, however,
237         /// obviously, starting_time should be unique every time you reload the library - it is only
238         /// used to generate new ephemeral key data (which will be stored by the individual channel if
239         /// necessary).
240         ///
241         /// Note that the seed is required to recover certain on-chain funds independent of
242         /// ChannelMonitor data, though a current copy of ChannelMonitor data is also required for any
243         /// channel, and some on-chain during-closing funds.
244         ///
245         /// Note that until the 0.1 release there is no guarantee of backward compatibility between
246         /// versions. Once the library is more fully supported, the docs will be updated to include a
247         /// detailed description of the guarantee.
248         pub fn new(seed: &[u8; 32], network: Network, logger: Arc<Logger>, starting_time_secs: u64, starting_time_nanos: u32) -> KeysManager {
249                 let secp_ctx = Secp256k1::signing_only();
250                 match ExtendedPrivKey::new_master(network.clone(), seed) {
251                         Ok(master_key) => {
252                                 let node_secret = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(0).unwrap()).expect("Your RNG is busted").private_key.key;
253                                 let destination_script = match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(1).unwrap()) {
254                                         Ok(destination_key) => {
255                                                 let pubkey_hash160 = Hash160::hash(&ExtendedPubKey::from_private(&secp_ctx, &destination_key).public_key.key.serialize()[..]);
256                                                 Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0)
257                                                               .push_slice(&pubkey_hash160.into_inner())
258                                                               .into_script()
259                                         },
260                                         Err(_) => panic!("Your RNG is busted"),
261                                 };
262                                 let shutdown_pubkey = match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(2).unwrap()) {
263                                         Ok(shutdown_key) => ExtendedPubKey::from_private(&secp_ctx, &shutdown_key).public_key.key,
264                                         Err(_) => panic!("Your RNG is busted"),
265                                 };
266                                 let channel_master_key = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(3).unwrap()).expect("Your RNG is busted");
267                                 let session_master_key = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(4).unwrap()).expect("Your RNG is busted");
268                                 let channel_id_master_key = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(5).unwrap()).expect("Your RNG is busted");
269
270                                 let mut unique_start = Sha256::engine();
271                                 unique_start.input(&byte_utils::be64_to_array(starting_time_secs));
272                                 unique_start.input(&byte_utils::be32_to_array(starting_time_nanos));
273                                 unique_start.input(seed);
274
275                                 KeysManager {
276                                         secp_ctx,
277                                         node_secret,
278                                         destination_script,
279                                         shutdown_pubkey,
280                                         channel_master_key,
281                                         channel_child_index: AtomicUsize::new(0),
282                                         session_master_key,
283                                         session_child_index: AtomicUsize::new(0),
284                                         channel_id_master_key,
285                                         channel_id_child_index: AtomicUsize::new(0),
286
287                                         unique_start,
288                                         logger,
289                                 }
290                         },
291                         Err(_) => panic!("Your rng is busted"),
292                 }
293         }
294 }
295
296 impl KeysInterface for KeysManager {
297         type ChanKeySigner = InMemoryChannelKeys;
298
299         fn get_node_secret(&self) -> SecretKey {
300                 self.node_secret.clone()
301         }
302
303         fn get_destination_script(&self) -> Script {
304                 self.destination_script.clone()
305         }
306
307         fn get_shutdown_pubkey(&self) -> PublicKey {
308                 self.shutdown_pubkey.clone()
309         }
310
311         fn get_channel_keys(&self, _inbound: bool) -> InMemoryChannelKeys {
312                 // We only seriously intend to rely on the channel_master_key for true secure
313                 // entropy, everything else just ensures uniqueness. We rely on the unique_start (ie
314                 // starting_time provided in the constructor) to be unique.
315                 let mut sha = self.unique_start.clone();
316
317                 let child_ix = self.channel_child_index.fetch_add(1, Ordering::AcqRel);
318                 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");
319                 sha.input(&child_privkey.private_key.key[..]);
320
321                 let seed = Sha256::from_engine(sha).into_inner();
322
323                 let commitment_seed = {
324                         let mut sha = Sha256::engine();
325                         sha.input(&seed);
326                         sha.input(&b"commitment seed"[..]);
327                         Sha256::from_engine(sha).into_inner()
328                 };
329                 macro_rules! key_step {
330                         ($info: expr, $prev_key: expr) => {{
331                                 let mut sha = Sha256::engine();
332                                 sha.input(&seed);
333                                 sha.input(&$prev_key[..]);
334                                 sha.input(&$info[..]);
335                                 SecretKey::from_slice(&Sha256::from_engine(sha).into_inner()).expect("SHA-256 is busted")
336                         }}
337                 }
338                 let funding_key = key_step!(b"funding key", commitment_seed);
339                 let revocation_base_key = key_step!(b"revocation base key", funding_key);
340                 let payment_base_key = key_step!(b"payment base key", revocation_base_key);
341                 let delayed_payment_base_key = key_step!(b"delayed payment base key", payment_base_key);
342                 let htlc_base_key = key_step!(b"HTLC base key", delayed_payment_base_key);
343
344                 InMemoryChannelKeys {
345                         funding_key,
346                         revocation_base_key,
347                         payment_base_key,
348                         delayed_payment_base_key,
349                         htlc_base_key,
350                         commitment_seed,
351                 }
352         }
353
354         fn get_onion_rand(&self) -> (SecretKey, [u8; 32]) {
355                 let mut sha = self.unique_start.clone();
356
357                 let child_ix = self.session_child_index.fetch_add(1, Ordering::AcqRel);
358                 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");
359                 sha.input(&child_privkey.private_key.key[..]);
360
361                 let mut rng_seed = sha.clone();
362                 // Not exactly the most ideal construction, but the second value will get fed into
363                 // ChaCha so it is another step harder to break.
364                 rng_seed.input(b"RNG Seed Salt");
365                 sha.input(b"Session Key Salt");
366                 (SecretKey::from_slice(&Sha256::from_engine(sha).into_inner()).expect("Your RNG is busted"),
367                 Sha256::from_engine(rng_seed).into_inner())
368         }
369
370         fn get_channel_id(&self) -> [u8; 32] {
371                 let mut sha = self.unique_start.clone();
372
373                 let child_ix = self.channel_id_child_index.fetch_add(1, Ordering::AcqRel);
374                 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");
375                 sha.input(&child_privkey.private_key.key[..]);
376
377                 (Sha256::from_engine(sha).into_inner())
378         }
379 }