Merge pull request #379 from rrybarczyk/use-workspaces
[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         /// Get node secret key (aka node_id or network_key)
72         fn get_node_secret(&self) -> SecretKey;
73         /// Get destination redeemScript to encumber static protocol exit points.
74         fn get_destination_script(&self) -> Script;
75         /// Get shutdown_pubkey to use as PublicKey at channel closure
76         fn get_shutdown_pubkey(&self) -> PublicKey;
77         /// Get a new set of ChannelKeys for per-channel secrets. These MUST be unique even if you
78         /// restarted with some stale data!
79         fn get_channel_keys(&self, inbound: bool) -> ChannelKeys;
80         /// Get a secret for construting an onion packet
81         fn get_session_key(&self) -> SecretKey;
82         /// Get a unique temporary channel id. Channels will be referred to by this until the funding
83         /// transaction is created, at which point they will use the outpoint in the funding
84         /// transaction.
85         fn get_channel_id(&self) -> [u8; 32];
86 }
87
88 /// Set of lightning keys needed to operate a channel as described in BOLT 3
89 #[derive(Clone)]
90 pub struct ChannelKeys {
91         /// Private key of anchor tx
92         pub funding_key: SecretKey,
93         /// Local secret key for blinded revocation pubkey
94         pub revocation_base_key: SecretKey,
95         /// Local secret key used in commitment tx htlc outputs
96         pub payment_base_key: SecretKey,
97         /// Local secret key used in HTLC tx
98         pub delayed_payment_base_key: SecretKey,
99         /// Local htlc secret key used in commitment tx htlc outputs
100         pub htlc_base_key: SecretKey,
101         /// Commitment seed
102         pub commitment_seed: [u8; 32],
103 }
104
105 impl_writeable!(ChannelKeys, 0, {
106         funding_key,
107         revocation_base_key,
108         payment_base_key,
109         delayed_payment_base_key,
110         htlc_base_key,
111         commitment_seed
112 });
113
114 /// Simple KeysInterface implementor that takes a 32-byte seed for use as a BIP 32 extended key
115 /// and derives keys from that.
116 ///
117 /// Your node_id is seed/0'
118 /// ChannelMonitor closes may use seed/1'
119 /// Cooperative closes may use seed/2'
120 /// The two close keys may be needed to claim on-chain funds!
121 pub struct KeysManager {
122         secp_ctx: Secp256k1<secp256k1::SignOnly>,
123         node_secret: SecretKey,
124         destination_script: Script,
125         shutdown_pubkey: PublicKey,
126         channel_master_key: ExtendedPrivKey,
127         channel_child_index: AtomicUsize,
128         session_master_key: ExtendedPrivKey,
129         session_child_index: AtomicUsize,
130         channel_id_master_key: ExtendedPrivKey,
131         channel_id_child_index: AtomicUsize,
132
133         unique_start: Sha256State,
134         logger: Arc<Logger>,
135 }
136
137 impl KeysManager {
138         /// Constructs a KeysManager from a 32-byte seed. If the seed is in some way biased (eg your
139         /// RNG is busted) this may panic (but more importantly, you will possibly lose funds).
140         /// starting_time isn't strictly required to actually be a time, but it must absolutely,
141         /// without a doubt, be unique to this instance. ie if you start multiple times with the same
142         /// seed, starting_time must be unique to each run. Thus, the easiest way to achieve this is to
143         /// simply use the current time (with very high precision).
144         ///
145         /// The seed MUST be backed up safely prior to use so that the keys can be re-created, however,
146         /// obviously, starting_time should be unique every time you reload the library - it is only
147         /// used to generate new ephemeral key data (which will be stored by the individual channel if
148         /// necessary).
149         ///
150         /// Note that the seed is required to recover certain on-chain funds independent of
151         /// ChannelMonitor data, though a current copy of ChannelMonitor data is also required for any
152         /// channel, and some on-chain during-closing funds.
153         ///
154         /// Note that until the 0.1 release there is no guarantee of backward compatibility between
155         /// versions. Once the library is more fully supported, the docs will be updated to include a
156         /// detailed description of the guarantee.
157         pub fn new(seed: &[u8; 32], network: Network, logger: Arc<Logger>, starting_time_secs: u64, starting_time_nanos: u32) -> KeysManager {
158                 let secp_ctx = Secp256k1::signing_only();
159                 match ExtendedPrivKey::new_master(network.clone(), seed) {
160                         Ok(master_key) => {
161                                 let node_secret = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(0).unwrap()).expect("Your RNG is busted").private_key.key;
162                                 let destination_script = match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(1).unwrap()) {
163                                         Ok(destination_key) => {
164                                                 let pubkey_hash160 = Hash160::hash(&ExtendedPubKey::from_private(&secp_ctx, &destination_key).public_key.key.serialize()[..]);
165                                                 Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0)
166                                                               .push_slice(&pubkey_hash160.into_inner())
167                                                               .into_script()
168                                         },
169                                         Err(_) => panic!("Your RNG is busted"),
170                                 };
171                                 let shutdown_pubkey = match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(2).unwrap()) {
172                                         Ok(shutdown_key) => ExtendedPubKey::from_private(&secp_ctx, &shutdown_key).public_key.key,
173                                         Err(_) => panic!("Your RNG is busted"),
174                                 };
175                                 let channel_master_key = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(3).unwrap()).expect("Your RNG is busted");
176                                 let session_master_key = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(4).unwrap()).expect("Your RNG is busted");
177                                 let channel_id_master_key = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(5).unwrap()).expect("Your RNG is busted");
178
179                                 let mut unique_start = Sha256::engine();
180                                 unique_start.input(&byte_utils::be64_to_array(starting_time_secs));
181                                 unique_start.input(&byte_utils::be32_to_array(starting_time_nanos));
182                                 unique_start.input(seed);
183
184                                 KeysManager {
185                                         secp_ctx,
186                                         node_secret,
187                                         destination_script,
188                                         shutdown_pubkey,
189                                         channel_master_key,
190                                         channel_child_index: AtomicUsize::new(0),
191                                         session_master_key,
192                                         session_child_index: AtomicUsize::new(0),
193                                         channel_id_master_key,
194                                         channel_id_child_index: AtomicUsize::new(0),
195
196                                         unique_start,
197                                         logger,
198                                 }
199                         },
200                         Err(_) => panic!("Your rng is busted"),
201                 }
202         }
203 }
204
205 impl KeysInterface for KeysManager {
206         fn get_node_secret(&self) -> SecretKey {
207                 self.node_secret.clone()
208         }
209
210         fn get_destination_script(&self) -> Script {
211                 self.destination_script.clone()
212         }
213
214         fn get_shutdown_pubkey(&self) -> PublicKey {
215                 self.shutdown_pubkey.clone()
216         }
217
218         fn get_channel_keys(&self, _inbound: bool) -> ChannelKeys {
219                 // We only seriously intend to rely on the channel_master_key for true secure
220                 // entropy, everything else just ensures uniqueness. We rely on the unique_start (ie
221                 // starting_time provided in the constructor) to be unique.
222                 let mut sha = self.unique_start.clone();
223
224                 let child_ix = self.channel_child_index.fetch_add(1, Ordering::AcqRel);
225                 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");
226                 sha.input(&child_privkey.private_key.key[..]);
227
228                 let seed = Sha256::from_engine(sha).into_inner();
229
230                 let commitment_seed = {
231                         let mut sha = Sha256::engine();
232                         sha.input(&seed);
233                         sha.input(&b"commitment seed"[..]);
234                         Sha256::from_engine(sha).into_inner()
235                 };
236                 macro_rules! key_step {
237                         ($info: expr, $prev_key: expr) => {{
238                                 let mut sha = Sha256::engine();
239                                 sha.input(&seed);
240                                 sha.input(&$prev_key[..]);
241                                 sha.input(&$info[..]);
242                                 SecretKey::from_slice(&Sha256::from_engine(sha).into_inner()).expect("SHA-256 is busted")
243                         }}
244                 }
245                 let funding_key = key_step!(b"funding key", commitment_seed);
246                 let revocation_base_key = key_step!(b"revocation base key", funding_key);
247                 let payment_base_key = key_step!(b"payment base key", revocation_base_key);
248                 let delayed_payment_base_key = key_step!(b"delayed payment base key", payment_base_key);
249                 let htlc_base_key = key_step!(b"HTLC base key", delayed_payment_base_key);
250
251                 ChannelKeys {
252                         funding_key,
253                         revocation_base_key,
254                         payment_base_key,
255                         delayed_payment_base_key,
256                         htlc_base_key,
257                         commitment_seed,
258                 }
259         }
260
261         fn get_session_key(&self) -> SecretKey {
262                 let mut sha = self.unique_start.clone();
263
264                 let child_ix = self.session_child_index.fetch_add(1, Ordering::AcqRel);
265                 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");
266                 sha.input(&child_privkey.private_key.key[..]);
267                 SecretKey::from_slice(&Sha256::from_engine(sha).into_inner()).expect("Your RNG is busted")
268         }
269
270         fn get_channel_id(&self) -> [u8; 32] {
271                 let mut sha = self.unique_start.clone();
272
273                 let child_ix = self.channel_id_child_index.fetch_add(1, Ordering::AcqRel);
274                 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");
275                 sha.input(&child_privkey.private_key.key[..]);
276
277                 (Sha256::from_engine(sha).into_inner())
278         }
279 }