Implement KeysInterface for KeysManager util
[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
18 use util::sha2::Sha256;
19 use util::logger::Logger;
20
21 use std::sync::Arc;
22
23 /// When on-chain outputs are created by rust-lightning an event is generated which informs the
24 /// user thereof. This enum describes the format of the output and provides the OutPoint.
25 pub enum SpendableOutputDescriptor {
26         /// Outpoint with an output to a script which was provided via KeysInterface, thus you should
27         /// have stored somewhere how to spend script_pubkey!
28         /// Outputs from a justice tx, claim tx or preimage tx
29         StaticOutput {
30                 /// The outpoint spendable by user wallet
31                 outpoint: OutPoint,
32                 /// The output which is referenced by the given outpoint
33                 output: TxOut,
34         },
35         /// Outpoint commits to a P2WSH, should be spend by the following witness :
36         /// <local_delayedsig> 0 <witnessScript>
37         /// With input nSequence set to_self_delay.
38         /// Outputs from a HTLC-Success/Timeout tx
39         DynamicOutput {
40                 /// Outpoint spendable by user wallet
41                 outpoint: OutPoint,
42                 /// local_delayedkey = delayed_payment_basepoint_secret + SHA256(per_commitment_point || delayed_payment_basepoint
43                 local_delayedkey: SecretKey,
44                 /// witness redeemScript encumbering output
45                 witness_script: Script,
46                 /// nSequence input must commit to self_delay to satisfy script's OP_CSV
47                 to_self_delay: u16,
48         }
49 }
50
51 /// A trait to describe an object which can get user secrets and key material.
52 pub trait KeysInterface: Send + Sync {
53         /// Get node secret key (aka node_id or network_key)
54         fn get_node_secret(&self) -> SecretKey;
55         /// Get destination redeemScript to encumber static protocol exit points.
56         fn get_destination_script(&self) -> Script;
57         /// Get shutdown_pubkey to use as PublicKey at channel closure
58         fn get_shutdown_pubkey(&self) -> PublicKey;
59         /// Get a new set of ChannelKeys for per-channel secrets. These MUST be unique even if you
60         /// restarted with some stale data!
61         fn get_channel_keys(&self, inbound: bool) -> ChannelKeys;
62 }
63
64 /// Set of lightning keys needed to operate a channel as described in BOLT 3
65 pub struct ChannelKeys {
66         /// Private key of anchor tx
67         pub funding_key: SecretKey,
68         /// Local secret key for blinded revocation pubkey
69         pub revocation_base_key: SecretKey,
70         /// Local secret key used in commitment tx htlc outputs
71         pub payment_base_key: SecretKey,
72         /// Local secret key used in HTLC tx
73         pub delayed_payment_base_key: SecretKey,
74         /// Local htlc secret key used in commitment tx htlc outputs
75         pub htlc_base_key: SecretKey,
76         /// Local secret key used for closing tx
77         pub channel_close_key: SecretKey,
78         /// Local secret key used in justice tx, claim tx and preimage tx outputs
79         pub channel_monitor_claim_key: SecretKey,
80         /// Commitment seed
81         pub commitment_seed: [u8; 32],
82 }
83
84 impl ChannelKeys {
85         /// Generate a set of lightning keys needed to operate a channel by HKDF-expanding a given
86         /// random 32-byte seed
87         pub fn new_from_seed(seed: &[u8; 32]) -> ChannelKeys {
88                 let mut prk = [0; 32];
89                 hkdf_extract(Sha256::new(), b"rust-lightning key gen salt", seed, &mut prk);
90                 let secp_ctx = Secp256k1::without_caps();
91
92                 let mut okm = [0; 32];
93                 hkdf_expand(Sha256::new(), &prk, b"rust-lightning funding key info", &mut okm);
94                 let funding_key = SecretKey::from_slice(&secp_ctx, &okm).expect("Sha256 is broken");
95
96                 hkdf_expand(Sha256::new(), &prk, b"rust-lightning revocation base key info", &mut okm);
97                 let revocation_base_key = SecretKey::from_slice(&secp_ctx, &okm).expect("Sha256 is broken");
98
99                 hkdf_expand(Sha256::new(), &prk, b"rust-lightning payment base key info", &mut okm);
100                 let payment_base_key = SecretKey::from_slice(&secp_ctx, &okm).expect("Sha256 is broken");
101
102                 hkdf_expand(Sha256::new(), &prk, b"rust-lightning delayed payment base key info", &mut okm);
103                 let delayed_payment_base_key = SecretKey::from_slice(&secp_ctx, &okm).expect("Sha256 is broken");
104
105                 hkdf_expand(Sha256::new(), &prk, b"rust-lightning htlc base key info", &mut okm);
106                 let htlc_base_key = SecretKey::from_slice(&secp_ctx, &okm).expect("Sha256 is broken");
107
108                 hkdf_expand(Sha256::new(), &prk, b"rust-lightning channel close key info", &mut okm);
109                 let channel_close_key = SecretKey::from_slice(&secp_ctx, &okm).expect("Sha256 is broken");
110
111                 hkdf_expand(Sha256::new(), &prk, b"rust-lightning channel monitor claim key info", &mut okm);
112                 let channel_monitor_claim_key = SecretKey::from_slice(&secp_ctx, &okm).expect("Sha256 is broken");
113
114                 hkdf_expand(Sha256::new(), &prk, b"rust-lightning local commitment seed info", &mut okm);
115
116                 ChannelKeys {
117                         funding_key: funding_key,
118                         revocation_base_key: revocation_base_key,
119                         payment_base_key: payment_base_key,
120                         delayed_payment_base_key: delayed_payment_base_key,
121                         htlc_base_key: htlc_base_key,
122                         channel_close_key: channel_close_key,
123                         channel_monitor_claim_key: channel_monitor_claim_key,
124                         commitment_seed: okm
125                 }
126         }
127 }
128
129 /// Simple KeysInterface implementor that takes a 32-byte seed for use as a BIP 32 extended key
130 /// and derives keys from that.
131 ///
132 /// Your node_id is seed/0'
133 /// ChannelMonitor closes may use seed/1'
134 /// Cooperative closes may use seed/2'
135 /// The two close keys may be needed to claim on-chain funds!
136 pub struct KeysManager {
137         secp_ctx: Secp256k1<secp256k1::All>,
138         node_secret: SecretKey,
139         destination_script: Script,
140         shutdown_pubkey: PublicKey,
141         channel_master_key: ExtendedPrivKey,
142
143         logger: Arc<Logger>,
144 }
145
146 impl KeysManager {
147         /// Constructs a KeysManager from a 32-byte seed. If the seed is in some way biased (eg your
148         /// RNG is busted) this may panic.
149         pub fn new(seed: &[u8; 32], network: Network, logger: Arc<Logger>) -> KeysManager {
150                 let secp_ctx = Secp256k1::new();
151                 match ExtendedPrivKey::new_master(&secp_ctx, network.clone(), seed) {
152                         Ok(master_key) => {
153                                 let node_secret = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(0)).expect("Your RNG is busted").secret_key;
154                                 let destination_script = match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(1)) {
155                                         Ok(destination_key) => {
156                                                 let pubkey_hash160 = Hash160::from_data(&ExtendedPubKey::from_private(&secp_ctx, &destination_key).public_key.serialize()[..]);
157                                                 Builder::new().push_opcode(opcodes::All::OP_PUSHBYTES_0)
158                                                               .push_slice(pubkey_hash160.as_bytes())
159                                                               .into_script()
160                                         },
161                                         Err(_) => panic!("Your RNG is busted"),
162                                 };
163                                 let shutdown_pubkey = match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(2)) {
164                                         Ok(shutdown_key) => ExtendedPubKey::from_private(&secp_ctx, &shutdown_key).public_key,
165                                         Err(_) => panic!("Your RNG is busted"),
166                                 };
167                                 let channel_master_key = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(3)).expect("Your RNG is busted");
168                                 KeysManager {
169                                         secp_ctx,
170                                         node_secret,
171                                         destination_script,
172                                         shutdown_pubkey,
173                                         channel_master_key,
174
175                                         logger,
176                                 }
177                         },
178                         Err(_) => panic!("Your rng is busted"),
179                 }
180         }
181 }
182
183 impl KeysInterface for KeysManager {
184         fn get_node_secret(&self) -> SecretKey {
185                 self.node_secret.clone()
186         }
187
188         fn get_destination_script(&self) -> Script {
189                 self.destination_script.clone()
190         }
191
192         fn get_shutdown_pubkey(&self) -> PublicKey {
193                 self.shutdown_pubkey.clone()
194         }
195
196         fn get_channel_keys(&self, _inbound: bool) -> ChannelKeys {
197                 let channel_pubkey = ExtendedPubKey::from_private(&self.secp_ctx, &self. channel_master_key);
198                 let mut seed = [0; 32];
199                 for (arr, slice) in seed.iter_mut().zip((&channel_pubkey.public_key.serialize()[0..32]).iter()) {
200                         *arr = *slice;
201                 }
202                 ChannelKeys::new_from_seed(&seed)
203         }
204 }