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