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