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.
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};
12 use secp256k1::key::{SecretKey, PublicKey};
13 use secp256k1::Secp256k1;
16 use crypto::digest::Digest;
18 use util::sha2::Sha256;
19 use util::logger::Logger;
23 use std::time::{SystemTime, UNIX_EPOCH};
25 use std::sync::atomic::{AtomicUsize, Ordering};
27 /// When on-chain outputs are created by rust-lightning an event is generated which informs the
28 /// user thereof. This enum describes the format of the output and provides the OutPoint.
29 pub enum SpendableOutputDescriptor {
30 /// Outpoint with an output to a script which was provided via KeysInterface, thus you should
31 /// have stored somewhere how to spend script_pubkey!
32 /// Outputs from a justice tx, claim tx or preimage tx
34 /// The outpoint spendable by user wallet
36 /// The output which is referenced by the given outpoint
39 /// Outpoint commits to a P2WSH
40 /// 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/commitment tx
45 /// Outpoint spendable by user wallet
47 /// local_delayedkey = delayed_payment_basepoint_secret + SHA256(per_commitment_point || delayed_payment_basepoint) OR
49 /// witness redeemScript encumbering output.
50 witness_script: Script,
51 /// nSequence input must commit to self_delay to satisfy script's OP_CSV
53 /// The output which is referenced by the given outpoint
56 /// Outpoint commits to a P2WPKH
57 /// P2WPKH should be spend by the following witness :
58 /// <local_sig> <local_pubkey>
59 /// Outputs to_remote from a commitment tx
61 /// Outpoint spendable by user wallet
63 /// localkey = payment_basepoint_secret + SHA256(per_commitment_point || payment_basepoint
65 /// The output which is reference by the given outpoint
70 /// A trait to describe an object which can get user secrets and key material.
71 pub trait KeysInterface: Send + Sync {
72 /// Get node secret key (aka node_id or network_key)
73 fn get_node_secret(&self) -> SecretKey;
74 /// Get destination redeemScript to encumber static protocol exit points.
75 fn get_destination_script(&self) -> Script;
76 /// Get shutdown_pubkey to use as PublicKey at channel closure
77 fn get_shutdown_pubkey(&self) -> PublicKey;
78 /// Get a new set of ChannelKeys for per-channel secrets. These MUST be unique even if you
79 /// restarted with some stale data!
80 fn get_channel_keys(&self, inbound: bool) -> ChannelKeys;
81 /// Get a secret for construting an onion packet
82 fn get_session_key(&self) -> SecretKey;
85 /// Set of lightning keys needed to operate a channel as described in BOLT 3
87 pub struct ChannelKeys {
88 /// Private key of anchor tx
89 pub funding_key: SecretKey,
90 /// Local secret key for blinded revocation pubkey
91 pub revocation_base_key: SecretKey,
92 /// Local secret key used in commitment tx htlc outputs
93 pub payment_base_key: SecretKey,
94 /// Local secret key used in HTLC tx
95 pub delayed_payment_base_key: SecretKey,
96 /// Local htlc secret key used in commitment tx htlc outputs
97 pub htlc_base_key: SecretKey,
99 pub commitment_seed: [u8; 32],
102 impl_writeable!(ChannelKeys, 0, {
106 delayed_payment_base_key,
111 /// Simple KeysInterface implementor that takes a 32-byte seed for use as a BIP 32 extended key
112 /// and derives keys from that.
114 /// Your node_id is seed/0'
115 /// ChannelMonitor closes may use seed/1'
116 /// Cooperative closes may use seed/2'
117 /// The two close keys may be needed to claim on-chain funds!
118 pub struct KeysManager {
119 secp_ctx: Secp256k1<secp256k1::All>,
120 node_secret: SecretKey,
121 destination_script: Script,
122 shutdown_pubkey: PublicKey,
123 channel_master_key: ExtendedPrivKey,
124 channel_child_index: AtomicUsize,
125 session_master_key: ExtendedPrivKey,
126 session_child_index: AtomicUsize,
132 /// Constructs a KeysManager from a 32-byte seed. If the seed is in some way biased (eg your
133 /// RNG is busted) this may panic.
134 pub fn new(seed: &[u8; 32], network: Network, logger: Arc<Logger>) -> KeysManager {
135 let secp_ctx = Secp256k1::new();
136 match ExtendedPrivKey::new_master(&secp_ctx, network.clone(), seed) {
138 let node_secret = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(0)).expect("Your RNG is busted").secret_key;
139 let destination_script = match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(1)) {
140 Ok(destination_key) => {
141 let pubkey_hash160 = Hash160::from_data(&ExtendedPubKey::from_private(&secp_ctx, &destination_key).public_key.serialize()[..]);
142 Builder::new().push_opcode(opcodes::All::OP_PUSHBYTES_0)
143 .push_slice(pubkey_hash160.as_bytes())
146 Err(_) => panic!("Your RNG is busted"),
148 let shutdown_pubkey = match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(2)) {
149 Ok(shutdown_key) => ExtendedPubKey::from_private(&secp_ctx, &shutdown_key).public_key,
150 Err(_) => panic!("Your RNG is busted"),
152 let channel_master_key = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(3)).expect("Your RNG is busted");
153 let session_master_key = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(4)).expect("Your RNG is busted");
160 channel_child_index: AtomicUsize::new(0),
162 session_child_index: AtomicUsize::new(0),
167 Err(_) => panic!("Your rng is busted"),
172 impl KeysInterface for KeysManager {
173 fn get_node_secret(&self) -> SecretKey {
174 self.node_secret.clone()
177 fn get_destination_script(&self) -> Script {
178 self.destination_script.clone()
181 fn get_shutdown_pubkey(&self) -> PublicKey {
182 self.shutdown_pubkey.clone()
185 fn get_channel_keys(&self, _inbound: bool) -> ChannelKeys {
186 // We only seriously intend to rely on the channel_master_key for true secure
187 // entropy, everything else just ensures uniqueness. We generally don't expect
188 // all clients to have non-broken RNGs here, so we also include the current
189 // time as a fallback to get uniqueness.
190 let mut sha = Sha256::new();
192 let mut seed = [0u8; 32];
193 rng::fill_bytes(&mut seed[..]);
196 let now = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time went backwards");
197 sha.input(&byte_utils::be32_to_array(now.subsec_nanos()));
198 sha.input(&byte_utils::be64_to_array(now.as_secs()));
200 let child_ix = self.channel_child_index.fetch_add(1, Ordering::AcqRel);
201 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");
202 sha.input(&child_privkey.secret_key[..]);
204 sha.result(&mut seed);
206 let commitment_seed = {
207 let mut sha = Sha256::new();
209 sha.input(&b"commitment seed"[..]);
210 let mut res = [0; 32];
211 sha.result(&mut res);
214 macro_rules! key_step {
215 ($info: expr, $prev_key: expr) => {{
216 let mut sha = Sha256::new();
218 sha.input(&$prev_key[..]);
219 sha.input(&$info[..]);
220 let mut res = [0; 32];
221 sha.result(&mut res);
222 SecretKey::from_slice(&self.secp_ctx, &res).expect("SHA-256 is busted")
225 let funding_key = key_step!(b"funding key", commitment_seed);
226 let revocation_base_key = key_step!(b"revocation base key", funding_key);
227 let payment_base_key = key_step!(b"payment base key", revocation_base_key);
228 let delayed_payment_base_key = key_step!(b"delayed payment base key", payment_base_key);
229 let htlc_base_key = key_step!(b"HTLC base key", delayed_payment_base_key);
235 delayed_payment_base_key,
241 fn get_session_key(&self) -> SecretKey {
242 let mut sha = Sha256::new();
243 let mut res = [0u8; 32];
245 let now = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time went backwards");
246 sha.input(&byte_utils::be32_to_array(now.subsec_nanos()));
247 sha.input(&byte_utils::be64_to_array(now.as_secs()));
249 let child_ix = self.session_child_index.fetch_add(1, Ordering::AcqRel);
250 let child_privkey = self.session_master_key.ckd_priv(&self.secp_ctx, ChildNumber::from_hardened_idx(child_ix as u32)).expect("Your RNG is busted");
251 sha.input(&child_privkey.secret_key[..]);
252 sha.result(&mut res);
253 SecretKey::from_slice(&self.secp_ctx, &res).expect("Your RNG is busted")