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