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