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