Make ChannelKeys an API and template Channel with it.
[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::{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
11 use bitcoin_hashes::{Hash, HashEngine};
12 use bitcoin_hashes::sha256::HashEngine as Sha256State;
13 use bitcoin_hashes::sha256::Hash as Sha256;
14 use bitcoin_hashes::hash160::Hash as Hash160;
15
16 use secp256k1::key::{SecretKey, PublicKey};
17 use secp256k1::Secp256k1;
18 use secp256k1;
19
20 use util::byte_utils;
21 use util::logger::Logger;
22
23 use std::sync::Arc;
24 use std::sync::atomic::{AtomicUsize, Ordering};
25
26 /// When on-chain outputs are created by rust-lightning an event is generated which informs the
27 /// user thereof. This enum describes the format of the output and provides the OutPoint.
28 pub enum SpendableOutputDescriptor {
29         /// Outpoint with an output to a script which was provided via KeysInterface, thus you should
30         /// have stored somewhere how to spend script_pubkey!
31         /// Outputs from a justice tx, claim tx or preimage tx
32         StaticOutput {
33                 /// The outpoint spendable by user wallet
34                 outpoint: OutPoint,
35                 /// The output which is referenced by the given outpoint
36                 output: TxOut,
37         },
38         /// Outpoint commits to a P2WSH
39         /// P2WSH should be spend by the following witness :
40         /// <local_delayedsig> 0 <witnessScript>
41         /// With input nSequence set to_self_delay.
42         /// Outputs from a HTLC-Success/Timeout tx/commitment tx
43         DynamicOutputP2WSH {
44                 /// Outpoint spendable by user wallet
45                 outpoint: OutPoint,
46                 /// local_delayedkey = delayed_payment_basepoint_secret + SHA256(per_commitment_point || delayed_payment_basepoint) OR
47                 key: SecretKey,
48                 /// witness redeemScript encumbering output.
49                 witness_script: Script,
50                 /// nSequence input must commit to self_delay to satisfy script's OP_CSV
51                 to_self_delay: u16,
52                 /// The output which is referenced by the given outpoint
53                 output: TxOut,
54         },
55         /// Outpoint commits to a P2WPKH
56         /// P2WPKH should be spend by the following witness :
57         /// <local_sig> <local_pubkey>
58         /// Outputs to_remote from a commitment tx
59         DynamicOutputP2WPKH {
60                 /// Outpoint spendable by user wallet
61                 outpoint: OutPoint,
62                 /// localkey = payment_basepoint_secret + SHA256(per_commitment_point || payment_basepoint
63                 key: SecretKey,
64                 /// The output which is reference by the given outpoint
65                 output: TxOut,
66         }
67 }
68
69 /// A trait to describe an object which can get user secrets and key material.
70 pub trait KeysInterface: Send + Sync {
71         /// A type which implements ChannelKeys which will be returned by get_channel_keys.
72         type ChanKeySigner : ChannelKeys;
73
74         /// Get node secret key (aka node_id or network_key)
75         fn get_node_secret(&self) -> SecretKey;
76         /// Get destination redeemScript to encumber static protocol exit points.
77         fn get_destination_script(&self) -> Script;
78         /// Get shutdown_pubkey to use as PublicKey at channel closure
79         fn get_shutdown_pubkey(&self) -> PublicKey;
80         /// Get a new set of ChannelKeys for per-channel secrets. These MUST be unique even if you
81         /// restarted with some stale data!
82         fn get_channel_keys(&self, inbound: bool) -> Self::ChanKeySigner;
83         /// Get a secret and PRNG seed for construting an onion packet
84         fn get_onion_rand(&self) -> (SecretKey, [u8; 32]);
85         /// Get a unique temporary channel id. Channels will be referred to by this until the funding
86         /// transaction is created, at which point they will use the outpoint in the funding
87         /// transaction.
88         fn get_channel_id(&self) -> [u8; 32];
89 }
90
91 /// Set of lightning keys needed to operate a channel as described in BOLT 3.
92 ///
93 /// If you're implementing a custom signer, you almost certainly want to implement
94 /// Readable/Writable to serialize out a unique reference to this set of keys so
95 /// that you can serialize the full ChannelManager object.
96 ///
97 /// (TODO: We shouldn't require that, and should have an API to get them at deser time, due mostly
98 /// to the possibility of reentrancy issues by calling the user's code during our deserialization
99 /// routine).
100 pub trait ChannelKeys : Send {
101         /// Gets the private key for the anchor tx
102         fn funding_key<'a>(&'a self) -> &'a SecretKey;
103         /// Gets the local secret key for blinded revocation pubkey
104         fn revocation_base_key<'a>(&'a self) -> &'a SecretKey;
105         /// Gets the local secret key used in commitment tx htlc outputs
106         fn payment_base_key<'a>(&'a self) -> &'a SecretKey;
107         /// Gets the local secret key used in HTLC tx
108         fn delayed_payment_base_key<'a>(&'a self) -> &'a SecretKey;
109         /// Gets the local htlc secret key used in commitment tx htlc outputs
110         fn htlc_base_key<'a>(&'a self) -> &'a SecretKey;
111         /// Gets the commitment seed
112         fn commitment_seed<'a>(&'a self) -> &'a [u8; 32];
113 }
114
115 #[derive(Clone)]
116 /// A simple implementation of ChannelKeys that just keeps the private keys in memory.
117 pub struct InMemoryChannelKeys {
118         /// Private key of anchor tx
119         pub funding_key: SecretKey,
120         /// Local secret key for blinded revocation pubkey
121         pub revocation_base_key: SecretKey,
122         /// Local secret key used in commitment tx htlc outputs
123         pub payment_base_key: SecretKey,
124         /// Local secret key used in HTLC tx
125         pub delayed_payment_base_key: SecretKey,
126         /// Local htlc secret key used in commitment tx htlc outputs
127         pub htlc_base_key: SecretKey,
128         /// Commitment seed
129         pub commitment_seed: [u8; 32],
130 }
131
132 impl ChannelKeys for InMemoryChannelKeys {
133         fn funding_key(&self) -> &SecretKey { &self.funding_key }
134         fn revocation_base_key(&self) -> &SecretKey { &self.revocation_base_key }
135         fn payment_base_key(&self) -> &SecretKey { &self.payment_base_key }
136         fn delayed_payment_base_key(&self) -> &SecretKey { &self.delayed_payment_base_key }
137         fn htlc_base_key(&self) -> &SecretKey { &self.htlc_base_key }
138         fn commitment_seed(&self) -> &[u8; 32] { &self.commitment_seed }
139 }
140
141 impl_writeable!(InMemoryChannelKeys, 0, {
142         funding_key,
143         revocation_base_key,
144         payment_base_key,
145         delayed_payment_base_key,
146         htlc_base_key,
147         commitment_seed
148 });
149
150 /// Simple KeysInterface implementor that takes a 32-byte seed for use as a BIP 32 extended key
151 /// and derives keys from that.
152 ///
153 /// Your node_id is seed/0'
154 /// ChannelMonitor closes may use seed/1'
155 /// Cooperative closes may use seed/2'
156 /// The two close keys may be needed to claim on-chain funds!
157 pub struct KeysManager {
158         secp_ctx: Secp256k1<secp256k1::SignOnly>,
159         node_secret: SecretKey,
160         destination_script: Script,
161         shutdown_pubkey: PublicKey,
162         channel_master_key: ExtendedPrivKey,
163         channel_child_index: AtomicUsize,
164         session_master_key: ExtendedPrivKey,
165         session_child_index: AtomicUsize,
166         channel_id_master_key: ExtendedPrivKey,
167         channel_id_child_index: AtomicUsize,
168
169         unique_start: Sha256State,
170         logger: Arc<Logger>,
171 }
172
173 impl KeysManager {
174         /// Constructs a KeysManager from a 32-byte seed. If the seed is in some way biased (eg your
175         /// RNG is busted) this may panic (but more importantly, you will possibly lose funds).
176         /// starting_time isn't strictly required to actually be a time, but it must absolutely,
177         /// without a doubt, be unique to this instance. ie if you start multiple times with the same
178         /// seed, starting_time must be unique to each run. Thus, the easiest way to achieve this is to
179         /// simply use the current time (with very high precision).
180         ///
181         /// The seed MUST be backed up safely prior to use so that the keys can be re-created, however,
182         /// obviously, starting_time should be unique every time you reload the library - it is only
183         /// used to generate new ephemeral key data (which will be stored by the individual channel if
184         /// necessary).
185         ///
186         /// Note that the seed is required to recover certain on-chain funds independent of
187         /// ChannelMonitor data, though a current copy of ChannelMonitor data is also required for any
188         /// channel, and some on-chain during-closing funds.
189         ///
190         /// Note that until the 0.1 release there is no guarantee of backward compatibility between
191         /// versions. Once the library is more fully supported, the docs will be updated to include a
192         /// detailed description of the guarantee.
193         pub fn new(seed: &[u8; 32], network: Network, logger: Arc<Logger>, starting_time_secs: u64, starting_time_nanos: u32) -> KeysManager {
194                 let secp_ctx = Secp256k1::signing_only();
195                 match ExtendedPrivKey::new_master(network.clone(), seed) {
196                         Ok(master_key) => {
197                                 let node_secret = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(0).unwrap()).expect("Your RNG is busted").private_key.key;
198                                 let destination_script = match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(1).unwrap()) {
199                                         Ok(destination_key) => {
200                                                 let pubkey_hash160 = Hash160::hash(&ExtendedPubKey::from_private(&secp_ctx, &destination_key).public_key.key.serialize()[..]);
201                                                 Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0)
202                                                               .push_slice(&pubkey_hash160.into_inner())
203                                                               .into_script()
204                                         },
205                                         Err(_) => panic!("Your RNG is busted"),
206                                 };
207                                 let shutdown_pubkey = match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(2).unwrap()) {
208                                         Ok(shutdown_key) => ExtendedPubKey::from_private(&secp_ctx, &shutdown_key).public_key.key,
209                                         Err(_) => panic!("Your RNG is busted"),
210                                 };
211                                 let channel_master_key = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(3).unwrap()).expect("Your RNG is busted");
212                                 let session_master_key = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(4).unwrap()).expect("Your RNG is busted");
213                                 let channel_id_master_key = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(5).unwrap()).expect("Your RNG is busted");
214
215                                 let mut unique_start = Sha256::engine();
216                                 unique_start.input(&byte_utils::be64_to_array(starting_time_secs));
217                                 unique_start.input(&byte_utils::be32_to_array(starting_time_nanos));
218                                 unique_start.input(seed);
219
220                                 KeysManager {
221                                         secp_ctx,
222                                         node_secret,
223                                         destination_script,
224                                         shutdown_pubkey,
225                                         channel_master_key,
226                                         channel_child_index: AtomicUsize::new(0),
227                                         session_master_key,
228                                         session_child_index: AtomicUsize::new(0),
229                                         channel_id_master_key,
230                                         channel_id_child_index: AtomicUsize::new(0),
231
232                                         unique_start,
233                                         logger,
234                                 }
235                         },
236                         Err(_) => panic!("Your rng is busted"),
237                 }
238         }
239 }
240
241 impl KeysInterface for KeysManager {
242         type ChanKeySigner = InMemoryChannelKeys;
243
244         fn get_node_secret(&self) -> SecretKey {
245                 self.node_secret.clone()
246         }
247
248         fn get_destination_script(&self) -> Script {
249                 self.destination_script.clone()
250         }
251
252         fn get_shutdown_pubkey(&self) -> PublicKey {
253                 self.shutdown_pubkey.clone()
254         }
255
256         fn get_channel_keys(&self, _inbound: bool) -> InMemoryChannelKeys {
257                 // We only seriously intend to rely on the channel_master_key for true secure
258                 // entropy, everything else just ensures uniqueness. We rely on the unique_start (ie
259                 // starting_time provided in the constructor) to be unique.
260                 let mut sha = self.unique_start.clone();
261
262                 let child_ix = self.channel_child_index.fetch_add(1, Ordering::AcqRel);
263                 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");
264                 sha.input(&child_privkey.private_key.key[..]);
265
266                 let seed = Sha256::from_engine(sha).into_inner();
267
268                 let commitment_seed = {
269                         let mut sha = Sha256::engine();
270                         sha.input(&seed);
271                         sha.input(&b"commitment seed"[..]);
272                         Sha256::from_engine(sha).into_inner()
273                 };
274                 macro_rules! key_step {
275                         ($info: expr, $prev_key: expr) => {{
276                                 let mut sha = Sha256::engine();
277                                 sha.input(&seed);
278                                 sha.input(&$prev_key[..]);
279                                 sha.input(&$info[..]);
280                                 SecretKey::from_slice(&Sha256::from_engine(sha).into_inner()).expect("SHA-256 is busted")
281                         }}
282                 }
283                 let funding_key = key_step!(b"funding key", commitment_seed);
284                 let revocation_base_key = key_step!(b"revocation base key", funding_key);
285                 let payment_base_key = key_step!(b"payment base key", revocation_base_key);
286                 let delayed_payment_base_key = key_step!(b"delayed payment base key", payment_base_key);
287                 let htlc_base_key = key_step!(b"HTLC base key", delayed_payment_base_key);
288
289                 InMemoryChannelKeys {
290                         funding_key,
291                         revocation_base_key,
292                         payment_base_key,
293                         delayed_payment_base_key,
294                         htlc_base_key,
295                         commitment_seed,
296                 }
297         }
298
299         fn get_onion_rand(&self) -> (SecretKey, [u8; 32]) {
300                 let mut sha = self.unique_start.clone();
301
302                 let child_ix = self.session_child_index.fetch_add(1, Ordering::AcqRel);
303                 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");
304                 sha.input(&child_privkey.private_key.key[..]);
305
306                 let mut rng_seed = sha.clone();
307                 // Not exactly the most ideal construction, but the second value will get fed into
308                 // ChaCha so it is another step harder to break.
309                 rng_seed.input(b"RNG Seed Salt");
310                 sha.input(b"Session Key Salt");
311                 (SecretKey::from_slice(&Sha256::from_engine(sha).into_inner()).expect("Your RNG is busted"),
312                 Sha256::from_engine(rng_seed).into_inner())
313         }
314
315         fn get_channel_id(&self) -> [u8; 32] {
316                 let mut sha = self.unique_start.clone();
317
318                 let child_ix = self.channel_id_child_index.fetch_add(1, Ordering::AcqRel);
319                 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");
320                 sha.input(&child_privkey.private_key.key[..]);
321
322                 (Sha256::from_engine(sha).into_inner())
323         }
324 }