Integrate KeysInterface to ChannelManager with Arc
[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 #[derive(Clone)]
66 pub struct ChannelKeys {
67         /// Private key of anchor tx
68         pub funding_key: SecretKey,
69         /// Local secret key for blinded revocation pubkey
70         pub revocation_base_key: SecretKey,
71         /// Local secret key used in commitment tx htlc outputs
72         pub payment_base_key: SecretKey,
73         /// Local secret key used in HTLC tx
74         pub delayed_payment_base_key: SecretKey,
75         /// Local htlc secret key used in commitment tx htlc outputs
76         pub htlc_base_key: SecretKey,
77         /// Local secret key used for closing tx
78         pub channel_close_key: SecretKey,
79         /// Local secret key used in justice tx, claim tx and preimage tx outputs
80         pub channel_monitor_claim_key: SecretKey,
81         /// Commitment seed
82         pub commitment_seed: [u8; 32],
83 }
84
85 impl ChannelKeys {
86         /// Generate a set of lightning keys needed to operate a channel by HKDF-expanding a given
87         /// random 32-byte seed
88         pub fn new_from_seed(seed: &[u8; 32]) -> ChannelKeys {
89                 let mut prk = [0; 32];
90                 hkdf_extract(Sha256::new(), b"rust-lightning key gen salt", seed, &mut prk);
91                 let secp_ctx = Secp256k1::without_caps();
92
93                 let mut okm = [0; 32];
94                 hkdf_expand(Sha256::new(), &prk, b"rust-lightning funding key info", &mut okm);
95                 let funding_key = SecretKey::from_slice(&secp_ctx, &okm).expect("Sha256 is broken");
96
97                 hkdf_expand(Sha256::new(), &prk, b"rust-lightning revocation base key info", &mut okm);
98                 let revocation_base_key = SecretKey::from_slice(&secp_ctx, &okm).expect("Sha256 is broken");
99
100                 hkdf_expand(Sha256::new(), &prk, b"rust-lightning payment base key info", &mut okm);
101                 let payment_base_key = SecretKey::from_slice(&secp_ctx, &okm).expect("Sha256 is broken");
102
103                 hkdf_expand(Sha256::new(), &prk, b"rust-lightning delayed payment base key info", &mut okm);
104                 let delayed_payment_base_key = SecretKey::from_slice(&secp_ctx, &okm).expect("Sha256 is broken");
105
106                 hkdf_expand(Sha256::new(), &prk, b"rust-lightning htlc base key info", &mut okm);
107                 let htlc_base_key = SecretKey::from_slice(&secp_ctx, &okm).expect("Sha256 is broken");
108
109                 hkdf_expand(Sha256::new(), &prk, b"rust-lightning channel close key info", &mut okm);
110                 let channel_close_key = SecretKey::from_slice(&secp_ctx, &okm).expect("Sha256 is broken");
111
112                 hkdf_expand(Sha256::new(), &prk, b"rust-lightning channel monitor claim key info", &mut okm);
113                 let channel_monitor_claim_key = SecretKey::from_slice(&secp_ctx, &okm).expect("Sha256 is broken");
114
115                 hkdf_expand(Sha256::new(), &prk, b"rust-lightning local commitment seed info", &mut okm);
116
117                 ChannelKeys {
118                         funding_key: funding_key,
119                         revocation_base_key: revocation_base_key,
120                         payment_base_key: payment_base_key,
121                         delayed_payment_base_key: delayed_payment_base_key,
122                         htlc_base_key: htlc_base_key,
123                         channel_close_key: channel_close_key,
124                         channel_monitor_claim_key: channel_monitor_claim_key,
125                         commitment_seed: okm
126                 }
127         }
128 }
129
130 /// Simple KeysInterface implementor that takes a 32-byte seed for use as a BIP 32 extended key
131 /// and derives keys from that.
132 ///
133 /// Your node_id is seed/0'
134 /// ChannelMonitor closes may use seed/1'
135 /// Cooperative closes may use seed/2'
136 /// The two close keys may be needed to claim on-chain funds!
137 pub struct KeysManager {
138         secp_ctx: Secp256k1<secp256k1::All>,
139         node_secret: SecretKey,
140         destination_script: Script,
141         shutdown_pubkey: PublicKey,
142         channel_master_key: ExtendedPrivKey,
143
144         logger: Arc<Logger>,
145 }
146
147 impl KeysManager {
148         /// Constructs a KeysManager from a 32-byte seed. If the seed is in some way biased (eg your
149         /// RNG is busted) this may panic.
150         pub fn new(seed: &[u8; 32], network: Network, logger: Arc<Logger>) -> KeysManager {
151                 let secp_ctx = Secp256k1::new();
152                 match ExtendedPrivKey::new_master(&secp_ctx, network.clone(), seed) {
153                         Ok(master_key) => {
154                                 let node_secret = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(0)).expect("Your RNG is busted").secret_key;
155                                 let destination_script = match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(1)) {
156                                         Ok(destination_key) => {
157                                                 let pubkey_hash160 = Hash160::from_data(&ExtendedPubKey::from_private(&secp_ctx, &destination_key).public_key.serialize()[..]);
158                                                 Builder::new().push_opcode(opcodes::All::OP_PUSHBYTES_0)
159                                                               .push_slice(pubkey_hash160.as_bytes())
160                                                               .into_script()
161                                         },
162                                         Err(_) => panic!("Your RNG is busted"),
163                                 };
164                                 let shutdown_pubkey = match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(2)) {
165                                         Ok(shutdown_key) => ExtendedPubKey::from_private(&secp_ctx, &shutdown_key).public_key,
166                                         Err(_) => panic!("Your RNG is busted"),
167                                 };
168                                 let channel_master_key = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(3)).expect("Your RNG is busted");
169                                 KeysManager {
170                                         secp_ctx,
171                                         node_secret,
172                                         destination_script,
173                                         shutdown_pubkey,
174                                         channel_master_key,
175
176                                         logger,
177                                 }
178                         },
179                         Err(_) => panic!("Your rng is busted"),
180                 }
181         }
182 }
183
184 impl KeysInterface for KeysManager {
185         fn get_node_secret(&self) -> SecretKey {
186                 self.node_secret.clone()
187         }
188
189         fn get_destination_script(&self) -> Script {
190                 self.destination_script.clone()
191         }
192
193         fn get_shutdown_pubkey(&self) -> PublicKey {
194                 self.shutdown_pubkey.clone()
195         }
196
197         fn get_channel_keys(&self, _inbound: bool) -> ChannelKeys {
198                 let channel_pubkey = ExtendedPubKey::from_private(&self.secp_ctx, &self. channel_master_key);
199                 let mut seed = [0; 32];
200                 for (arr, slice) in seed.iter_mut().zip((&channel_pubkey.public_key.serialize()[0..32]).iter()) {
201                         *arr = *slice;
202                 }
203                 ChannelKeys::new_from_seed(&seed)
204         }
205 }