Merge pull request #318 from tamasblummer/rbitcoin017
[rust-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::Hash as Sha256;
13 use bitcoin_hashes::hash160::Hash as Hash160;
14
15 use secp256k1::key::{SecretKey, PublicKey};
16 use secp256k1::Secp256k1;
17 use secp256k1;
18
19 use util::logger::Logger;
20 use util::rng;
21 use util::byte_utils;
22
23 use std::time::{SystemTime, UNIX_EPOCH};
24 use std::sync::Arc;
25 use std::sync::atomic::{AtomicUsize, Ordering};
26
27 /// When on-chain outputs are created by rust-lightning an event is generated which informs the
28 /// user thereof. This enum describes the format of the output and provides the OutPoint.
29 pub enum SpendableOutputDescriptor {
30         /// Outpoint with an output to a script which was provided via KeysInterface, thus you should
31         /// have stored somewhere how to spend script_pubkey!
32         /// Outputs from a justice tx, claim tx or preimage tx
33         StaticOutput {
34                 /// The outpoint spendable by user wallet
35                 outpoint: OutPoint,
36                 /// The output which is referenced by the given outpoint
37                 output: TxOut,
38         },
39         /// Outpoint commits to a P2WSH
40         /// P2WSH should be spend by the following witness :
41         /// <local_delayedsig> 0 <witnessScript>
42         /// With input nSequence set to_self_delay.
43         /// Outputs from a HTLC-Success/Timeout tx/commitment tx
44         DynamicOutputP2WSH {
45                 /// Outpoint spendable by user wallet
46                 outpoint: OutPoint,
47                 /// local_delayedkey = delayed_payment_basepoint_secret + SHA256(per_commitment_point || delayed_payment_basepoint) OR
48                 key: SecretKey,
49                 /// witness redeemScript encumbering output.
50                 witness_script: Script,
51                 /// nSequence input must commit to self_delay to satisfy script's OP_CSV
52                 to_self_delay: u16,
53                 /// The output which is referenced by the given outpoint
54                 output: TxOut,
55         },
56         /// Outpoint commits to a P2WPKH
57         /// P2WPKH should be spend by the following witness :
58         /// <local_sig> <local_pubkey>
59         /// Outputs to_remote from a commitment tx
60         DynamicOutputP2WPKH {
61                 /// Outpoint spendable by user wallet
62                 outpoint: OutPoint,
63                 /// localkey = payment_basepoint_secret + SHA256(per_commitment_point || payment_basepoint
64                 key: SecretKey,
65                 /// The output which is reference by the given outpoint
66                 output: TxOut,
67         }
68 }
69
70 /// A trait to describe an object which can get user secrets and key material.
71 pub trait KeysInterface: Send + Sync {
72         /// Get node secret key (aka node_id or network_key)
73         fn get_node_secret(&self) -> SecretKey;
74         /// Get destination redeemScript to encumber static protocol exit points.
75         fn get_destination_script(&self) -> Script;
76         /// Get shutdown_pubkey to use as PublicKey at channel closure
77         fn get_shutdown_pubkey(&self) -> PublicKey;
78         /// Get a new set of ChannelKeys for per-channel secrets. These MUST be unique even if you
79         /// restarted with some stale data!
80         fn get_channel_keys(&self, inbound: bool) -> ChannelKeys;
81         /// Get a secret for construting an onion packet
82         fn get_session_key(&self) -> SecretKey;
83         /// Get a unique temporary channel id. Channels will be referred to by this until the funding
84         /// transaction is created, at which point they will use the outpoint in the funding
85         /// transaction.
86         fn get_channel_id(&self) -> [u8; 32];
87 }
88
89 /// Set of lightning keys needed to operate a channel as described in BOLT 3
90 #[derive(Clone)]
91 pub struct ChannelKeys {
92         /// Private key of anchor tx
93         pub funding_key: SecretKey,
94         /// Local secret key for blinded revocation pubkey
95         pub revocation_base_key: SecretKey,
96         /// Local secret key used in commitment tx htlc outputs
97         pub payment_base_key: SecretKey,
98         /// Local secret key used in HTLC tx
99         pub delayed_payment_base_key: SecretKey,
100         /// Local htlc secret key used in commitment tx htlc outputs
101         pub htlc_base_key: SecretKey,
102         /// Commitment seed
103         pub commitment_seed: [u8; 32],
104 }
105
106 impl_writeable!(ChannelKeys, 0, {
107         funding_key,
108         revocation_base_key,
109         payment_base_key,
110         delayed_payment_base_key,
111         htlc_base_key,
112         commitment_seed
113 });
114
115 /// Simple KeysInterface implementor that takes a 32-byte seed for use as a BIP 32 extended key
116 /// and derives keys from that.
117 ///
118 /// Your node_id is seed/0'
119 /// ChannelMonitor closes may use seed/1'
120 /// Cooperative closes may use seed/2'
121 /// The two close keys may be needed to claim on-chain funds!
122 pub struct KeysManager {
123         secp_ctx: Secp256k1<secp256k1::SignOnly>,
124         node_secret: SecretKey,
125         destination_script: Script,
126         shutdown_pubkey: PublicKey,
127         channel_master_key: ExtendedPrivKey,
128         channel_child_index: AtomicUsize,
129         session_master_key: ExtendedPrivKey,
130         session_child_index: AtomicUsize,
131         channel_id_master_key: ExtendedPrivKey,
132         channel_id_child_index: AtomicUsize,
133
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.
140         pub fn new(seed: &[u8; 32], network: Network, logger: Arc<Logger>) -> KeysManager {
141                 let secp_ctx = Secp256k1::signing_only();
142                 match ExtendedPrivKey::new_master(network.clone(), seed) {
143                         Ok(master_key) => {
144                                 let node_secret = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(0).unwrap()).expect("Your RNG is busted").private_key.key;
145                                 let destination_script = match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(1).unwrap()) {
146                                         Ok(destination_key) => {
147                                                 let pubkey_hash160 = Hash160::hash(&ExtendedPubKey::from_private(&secp_ctx, &destination_key).public_key.key.serialize()[..]);
148                                                 Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0)
149                                                               .push_slice(&pubkey_hash160.into_inner())
150                                                               .into_script()
151                                         },
152                                         Err(_) => panic!("Your RNG is busted"),
153                                 };
154                                 let shutdown_pubkey = match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(2).unwrap()) {
155                                         Ok(shutdown_key) => ExtendedPubKey::from_private(&secp_ctx, &shutdown_key).public_key.key,
156                                         Err(_) => panic!("Your RNG is busted"),
157                                 };
158                                 let channel_master_key = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(3).unwrap()).expect("Your RNG is busted");
159                                 let session_master_key = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(4).unwrap()).expect("Your RNG is busted");
160                                 let channel_id_master_key = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(5).unwrap()).expect("Your RNG is busted");
161                                 KeysManager {
162                                         secp_ctx,
163                                         node_secret,
164                                         destination_script,
165                                         shutdown_pubkey,
166                                         channel_master_key,
167                                         channel_child_index: AtomicUsize::new(0),
168                                         session_master_key,
169                                         session_child_index: AtomicUsize::new(0),
170                                         channel_id_master_key,
171                                         channel_id_child_index: AtomicUsize::new(0),
172
173                                         logger,
174                                 }
175                         },
176                         Err(_) => panic!("Your rng is busted"),
177                 }
178         }
179 }
180
181 impl KeysInterface for KeysManager {
182         fn get_node_secret(&self) -> SecretKey {
183                 self.node_secret.clone()
184         }
185
186         fn get_destination_script(&self) -> Script {
187                 self.destination_script.clone()
188         }
189
190         fn get_shutdown_pubkey(&self) -> PublicKey {
191                 self.shutdown_pubkey.clone()
192         }
193
194         fn get_channel_keys(&self, _inbound: bool) -> ChannelKeys {
195                 // We only seriously intend to rely on the channel_master_key for true secure
196                 // entropy, everything else just ensures uniqueness. We generally don't expect
197                 // all clients to have non-broken RNGs here, so we also include the current
198                 // time as a fallback to get uniqueness.
199                 let mut sha = Sha256::engine();
200
201                 let mut seed = [0u8; 32];
202                 rng::fill_bytes(&mut seed[..]);
203                 sha.input(&seed);
204
205                 let now = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time went backwards");
206                 sha.input(&byte_utils::be32_to_array(now.subsec_nanos()));
207                 sha.input(&byte_utils::be64_to_array(now.as_secs()));
208
209                 let child_ix = self.channel_child_index.fetch_add(1, Ordering::AcqRel);
210                 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");
211                 sha.input(&child_privkey.private_key.key[..]);
212
213                 seed = Sha256::from_engine(sha).into_inner();
214
215                 let commitment_seed = {
216                         let mut sha = Sha256::engine();
217                         sha.input(&seed);
218                         sha.input(&b"commitment seed"[..]);
219                         Sha256::from_engine(sha).into_inner()
220                 };
221                 macro_rules! key_step {
222                         ($info: expr, $prev_key: expr) => {{
223                                 let mut sha = Sha256::engine();
224                                 sha.input(&seed);
225                                 sha.input(&$prev_key[..]);
226                                 sha.input(&$info[..]);
227                                 SecretKey::from_slice(&Sha256::from_engine(sha).into_inner()).expect("SHA-256 is busted")
228                         }}
229                 }
230                 let funding_key = key_step!(b"funding key", commitment_seed);
231                 let revocation_base_key = key_step!(b"revocation base key", funding_key);
232                 let payment_base_key = key_step!(b"payment base key", revocation_base_key);
233                 let delayed_payment_base_key = key_step!(b"delayed payment base key", payment_base_key);
234                 let htlc_base_key = key_step!(b"HTLC base key", delayed_payment_base_key);
235
236                 ChannelKeys {
237                         funding_key,
238                         revocation_base_key,
239                         payment_base_key,
240                         delayed_payment_base_key,
241                         htlc_base_key,
242                         commitment_seed,
243                 }
244         }
245
246         fn get_session_key(&self) -> SecretKey {
247                 let mut sha = Sha256::engine();
248
249                 let now = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time went backwards");
250                 sha.input(&byte_utils::be32_to_array(now.subsec_nanos()));
251                 sha.input(&byte_utils::be64_to_array(now.as_secs()));
252
253                 let child_ix = self.session_child_index.fetch_add(1, Ordering::AcqRel);
254                 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");
255                 sha.input(&child_privkey.private_key.key[..]);
256                 SecretKey::from_slice(&Sha256::from_engine(sha).into_inner()).expect("Your RNG is busted")
257         }
258
259         fn get_channel_id(&self) -> [u8; 32] {
260                 let mut sha = Sha256::engine();
261
262                 let now = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time went backwards");
263                 sha.input(&byte_utils::be32_to_array(now.subsec_nanos()));
264                 sha.input(&byte_utils::be64_to_array(now.as_secs()));
265
266                 let child_ix = self.channel_id_child_index.fetch_add(1, Ordering::AcqRel);
267                 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");
268                 sha.input(&child_privkey.private_key.key[..]);
269
270                 (Sha256::from_engine(sha).into_inner())
271         }
272 }