556be6dc5bbaa4c881ca58f12be762c28598ff54
[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, 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
44         DynamicOutput {
45                 /// Outpoint spendable by user wallet
46                 outpoint: OutPoint,
47                 /// local_delayedkey = delayed_payment_basepoint_secret + SHA256(per_commitment_point || delayed_payment_basepoint)
48                 local_delayedkey: 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         }
54 }
55
56 /// A trait to describe an object which can get user secrets and key material.
57 pub trait KeysInterface: Send + Sync {
58         /// Get node secret key (aka node_id or network_key)
59         fn get_node_secret(&self) -> SecretKey;
60         /// Get destination redeemScript to encumber static protocol exit points.
61         fn get_destination_script(&self) -> Script;
62         /// Get shutdown_pubkey to use as PublicKey at channel closure
63         fn get_shutdown_pubkey(&self) -> PublicKey;
64         /// Get a new set of ChannelKeys for per-channel secrets. These MUST be unique even if you
65         /// restarted with some stale data!
66         fn get_channel_keys(&self, inbound: bool) -> ChannelKeys;
67 }
68
69 /// Set of lightning keys needed to operate a channel as described in BOLT 3
70 #[derive(Clone)]
71 pub struct ChannelKeys {
72         /// Private key of anchor tx
73         pub funding_key: SecretKey,
74         /// Local secret key for blinded revocation pubkey
75         pub revocation_base_key: SecretKey,
76         /// Local secret key used in commitment tx htlc outputs
77         pub payment_base_key: SecretKey,
78         /// Local secret key used in HTLC tx
79         pub delayed_payment_base_key: SecretKey,
80         /// Local htlc secret key used in commitment tx htlc outputs
81         pub htlc_base_key: SecretKey,
82         /// Commitment seed
83         pub commitment_seed: [u8; 32],
84 }
85
86 impl_writeable!(ChannelKeys, 0, {
87         funding_key,
88         revocation_base_key,
89         payment_base_key,
90         delayed_payment_base_key,
91         htlc_base_key,
92         commitment_seed
93 });
94
95 impl ChannelKeys {
96         /// Generate a set of lightning keys needed to operate a channel by HKDF-expanding a given
97         /// random 32-byte seed
98         pub fn new_from_seed(seed: &[u8; 32]) -> ChannelKeys {
99                 let mut prk = [0; 32];
100                 hkdf_extract(Sha256::new(), b"rust-lightning key gen salt", seed, &mut prk);
101                 let secp_ctx = Secp256k1::without_caps();
102
103                 let mut okm = [0; 32];
104                 hkdf_expand(Sha256::new(), &prk, b"rust-lightning funding key info", &mut okm);
105                 let funding_key = SecretKey::from_slice(&secp_ctx, &okm).expect("Sha256 is broken");
106
107                 hkdf_expand(Sha256::new(), &prk, b"rust-lightning revocation base key info", &mut okm);
108                 let revocation_base_key = SecretKey::from_slice(&secp_ctx, &okm).expect("Sha256 is broken");
109
110                 hkdf_expand(Sha256::new(), &prk, b"rust-lightning payment base key info", &mut okm);
111                 let payment_base_key = SecretKey::from_slice(&secp_ctx, &okm).expect("Sha256 is broken");
112
113                 hkdf_expand(Sha256::new(), &prk, b"rust-lightning delayed payment base key info", &mut okm);
114                 let delayed_payment_base_key = SecretKey::from_slice(&secp_ctx, &okm).expect("Sha256 is broken");
115
116                 hkdf_expand(Sha256::new(), &prk, b"rust-lightning htlc base key info", &mut okm);
117                 let htlc_base_key = SecretKey::from_slice(&secp_ctx, &okm).expect("Sha256 is broken");
118
119                 hkdf_expand(Sha256::new(), &prk, b"rust-lightning local commitment seed info", &mut okm);
120
121                 ChannelKeys {
122                         funding_key: funding_key,
123                         revocation_base_key: revocation_base_key,
124                         payment_base_key: payment_base_key,
125                         delayed_payment_base_key: delayed_payment_base_key,
126                         htlc_base_key: htlc_base_key,
127                         commitment_seed: okm
128                 }
129         }
130 }
131
132 /// Simple KeysInterface implementor that takes a 32-byte seed for use as a BIP 32 extended key
133 /// and derives keys from that.
134 ///
135 /// Your node_id is seed/0'
136 /// ChannelMonitor closes may use seed/1'
137 /// Cooperative closes may use seed/2'
138 /// The two close keys may be needed to claim on-chain funds!
139 pub struct KeysManager {
140         secp_ctx: Secp256k1<secp256k1::All>,
141         node_secret: SecretKey,
142         destination_script: Script,
143         shutdown_pubkey: PublicKey,
144         channel_master_key: ExtendedPrivKey,
145         channel_child_index: AtomicUsize,
146
147         logger: Arc<Logger>,
148 }
149
150 impl KeysManager {
151         /// Constructs a KeysManager from a 32-byte seed. If the seed is in some way biased (eg your
152         /// RNG is busted) this may panic.
153         pub fn new(seed: &[u8; 32], network: Network, logger: Arc<Logger>) -> KeysManager {
154                 let secp_ctx = Secp256k1::new();
155                 match ExtendedPrivKey::new_master(&secp_ctx, network.clone(), seed) {
156                         Ok(master_key) => {
157                                 let node_secret = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(0)).expect("Your RNG is busted").secret_key;
158                                 let destination_script = match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(1)) {
159                                         Ok(destination_key) => {
160                                                 let pubkey_hash160 = Hash160::from_data(&ExtendedPubKey::from_private(&secp_ctx, &destination_key).public_key.serialize()[..]);
161                                                 Builder::new().push_opcode(opcodes::All::OP_PUSHBYTES_0)
162                                                               .push_slice(pubkey_hash160.as_bytes())
163                                                               .into_script()
164                                         },
165                                         Err(_) => panic!("Your RNG is busted"),
166                                 };
167                                 let shutdown_pubkey = match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(2)) {
168                                         Ok(shutdown_key) => ExtendedPubKey::from_private(&secp_ctx, &shutdown_key).public_key,
169                                         Err(_) => panic!("Your RNG is busted"),
170                                 };
171                                 let channel_master_key = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(3)).expect("Your RNG is busted");
172                                 KeysManager {
173                                         secp_ctx,
174                                         node_secret,
175                                         destination_script,
176                                         shutdown_pubkey,
177                                         channel_master_key,
178                                         channel_child_index: AtomicUsize::new(0),
179
180                                         logger,
181                                 }
182                         },
183                         Err(_) => panic!("Your rng is busted"),
184                 }
185         }
186 }
187
188 impl KeysInterface for KeysManager {
189         fn get_node_secret(&self) -> SecretKey {
190                 self.node_secret.clone()
191         }
192
193         fn get_destination_script(&self) -> Script {
194                 self.destination_script.clone()
195         }
196
197         fn get_shutdown_pubkey(&self) -> PublicKey {
198                 self.shutdown_pubkey.clone()
199         }
200
201         fn get_channel_keys(&self, _inbound: bool) -> ChannelKeys {
202                 // We only seriously intend to rely on the channel_master_key for true secure
203                 // entropy, everything else just ensures uniqueness. We generally don't expect
204                 // all clients to have non-broken RNGs here, so we also include the current
205                 // time as a fallback to get uniqueness.
206                 let mut sha = Sha256::new();
207
208                 let mut seed = [0u8; 32];
209                 rng::fill_bytes(&mut seed[..]);
210                 sha.input(&seed);
211
212                 let now = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time went backwards");
213                 sha.input(&byte_utils::be32_to_array(now.subsec_nanos()));
214                 sha.input(&byte_utils::be64_to_array(now.as_secs()));
215
216                 let child_ix = self.channel_child_index.fetch_add(1, Ordering::AcqRel);
217                 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");
218                 sha.input(&child_privkey.secret_key[..]);
219
220                 sha.result(&mut seed);
221                 ChannelKeys::new_from_seed(&seed)
222         }
223 }