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::{Transaction, OutPoint, TxOut, SigHashType};
6 use bitcoin::blockdata::script::{Script, Builder};
7 use bitcoin::blockdata::opcodes;
8 use bitcoin::network::constants::Network;
9 use bitcoin::util::bip32::{ExtendedPrivKey, ExtendedPubKey, ChildNumber};
10 use bitcoin::util::bip143;
12 use bitcoin_hashes::{Hash, HashEngine};
13 use bitcoin_hashes::sha256::HashEngine as Sha256State;
14 use bitcoin_hashes::sha256::Hash as Sha256;
15 use bitcoin_hashes::sha256d::Hash as Sha256dHash;
16 use bitcoin_hashes::hash160::Hash as Hash160;
18 use secp256k1::key::{SecretKey, PublicKey};
19 use secp256k1::{Secp256k1, Signature, Signing};
23 use util::logger::Logger;
24 use util::ser::{Writeable, Writer, Readable};
27 use ln::chan_utils::{TxCreationKeys, HTLCOutputInCommitment, make_funding_redeemscript, ChannelPublicKeys, LocalCommitmentTransaction};
28 use ln::channelmanager::PaymentPreimage;
32 use std::sync::atomic::{AtomicUsize, Ordering};
34 use ln::msgs::DecodeError;
36 /// When on-chain outputs are created by rust-lightning (which our counterparty is not able to
37 /// claim at any point in the future) an event is generated which you must track and be able to
38 /// spend on-chain. The information needed to do this is provided in this enum, including the
39 /// outpoint describing which txid and output index is available, the full output which exists at
40 /// that txid/index, and any keys or other information required to sign.
41 #[derive(Clone, PartialEq)]
42 pub enum SpendableOutputDescriptor {
43 /// An output to a script which was provided via KeysInterface, thus you should already know
44 /// how to spend it. No keys are provided as rust-lightning was never given any keys - only the
45 /// script_pubkey as it appears in the output.
46 /// These may include outputs from a transaction punishing our counterparty or claiming an HTLC
47 /// on-chain using the payment preimage or after it has timed out.
49 /// The outpoint which is spendable
51 /// The output which is referenced by the given outpoint.
54 /// An output to a P2WSH script which can be spent with a single signature after a CSV delay.
55 /// The private key which should be used to sign the transaction is provided, as well as the
56 /// full witness redeemScript which is hashed in the output script_pubkey.
57 /// The witness in the spending input should be:
58 /// <BIP 143 signature generated with the given key> <empty vector> (MINIMALIF standard rule)
59 /// <witness_script as provided>
60 /// Note that the nSequence field in the input must be set to_self_delay (which corresponds to
61 /// the transaction not being broadcastable until at least to_self_delay blocks after the input
63 /// These are generally the result of a "revocable" output to us, spendable only by us unless
64 /// it is an output from us having broadcast an old state (which should never happen).
66 /// The outpoint which is spendable
68 /// The secret key which must be used to sign the spending transaction
70 /// The witness redeemScript which is hashed to create the script_pubkey in the given output
71 witness_script: Script,
72 /// The nSequence value which must be set in the spending input to satisfy the OP_CSV in
73 /// the witness_script.
75 /// The output which is referenced by the given outpoint
78 /// An output to a P2WPKH, spendable exclusively by the given private key.
79 /// The witness in the spending input, is, thus, simply:
80 /// <BIP 143 signature generated with the given key> <public key derived from the given key>
81 /// These are generally the result of our counterparty having broadcast the current state,
82 /// allowing us to claim the non-HTLC-encumbered outputs immediately.
84 /// The outpoint which is spendable
86 /// The secret key which must be used to sign the spending transaction
88 /// The output which is reference by the given outpoint
93 impl Writeable for SpendableOutputDescriptor {
94 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
96 &SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output } => {
98 outpoint.write(writer)?;
99 output.write(writer)?;
101 &SpendableOutputDescriptor::DynamicOutputP2WSH { ref outpoint, ref key, ref witness_script, ref to_self_delay, ref output } => {
103 outpoint.write(writer)?;
105 witness_script.write(writer)?;
106 to_self_delay.write(writer)?;
107 output.write(writer)?;
109 &SpendableOutputDescriptor::DynamicOutputP2WPKH { ref outpoint, ref key, ref output } => {
111 outpoint.write(writer)?;
113 output.write(writer)?;
120 impl Readable for SpendableOutputDescriptor {
121 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
122 match Readable::read(reader)? {
123 0u8 => Ok(SpendableOutputDescriptor::StaticOutput {
124 outpoint: Readable::read(reader)?,
125 output: Readable::read(reader)?,
127 1u8 => Ok(SpendableOutputDescriptor::DynamicOutputP2WSH {
128 outpoint: Readable::read(reader)?,
129 key: Readable::read(reader)?,
130 witness_script: Readable::read(reader)?,
131 to_self_delay: Readable::read(reader)?,
132 output: Readable::read(reader)?,
134 2u8 => Ok(SpendableOutputDescriptor::DynamicOutputP2WPKH {
135 outpoint: Readable::read(reader)?,
136 key: Readable::read(reader)?,
137 output: Readable::read(reader)?,
139 _ => Err(DecodeError::InvalidValue),
144 /// A trait to describe an object which can get user secrets and key material.
145 pub trait KeysInterface: Send + Sync {
146 /// A type which implements ChannelKeys which will be returned by get_channel_keys.
147 type ChanKeySigner : ChannelKeys;
149 /// Get node secret key (aka node_id or network_key)
150 fn get_node_secret(&self) -> SecretKey;
151 /// Get destination redeemScript to encumber static protocol exit points.
152 fn get_destination_script(&self) -> Script;
153 /// Get shutdown_pubkey to use as PublicKey at channel closure
154 fn get_shutdown_pubkey(&self) -> PublicKey;
155 /// Get a new set of ChannelKeys for per-channel secrets. These MUST be unique even if you
156 /// restarted with some stale data!
157 fn get_channel_keys(&self, inbound: bool, channel_value_satoshis: u64) -> Self::ChanKeySigner;
158 /// Get a secret and PRNG seed for construting an onion packet
159 fn get_onion_rand(&self) -> (SecretKey, [u8; 32]);
160 /// Get a unique temporary channel id. Channels will be referred to by this until the funding
161 /// transaction is created, at which point they will use the outpoint in the funding
163 fn get_channel_id(&self) -> [u8; 32];
166 /// Set of lightning keys needed to operate a channel as described in BOLT 3.
168 /// Signing services could be implemented on a hardware wallet. In this case,
169 /// the current ChannelKeys would be a front-end on top of a communication
170 /// channel connected to your secure device and lightning key material wouldn't
171 /// reside on a hot server. Nevertheless, a this deployment would still need
172 /// to trust the ChannelManager to avoid loss of funds as this latest component
173 /// could ask to sign commitment transaction with HTLCs paying to attacker pubkeys.
175 /// A more secure iteration would be to use hashlock (or payment points) to pair
176 /// invoice/incoming HTLCs with outgoing HTLCs to implement a no-trust-ChannelManager
177 /// at the price of more state and computation on the hardware wallet side. In the future,
178 /// we are looking forward to design such interface.
180 /// In any case, ChannelMonitor or fallback watchtowers are always going to be trusted
181 /// to act, as liveness and breach reply correctness are always going to be hard requirements
182 /// of LN security model, orthogonal of key management issues.
184 /// If you're implementing a custom signer, you almost certainly want to implement
185 /// Readable/Writable to serialize out a unique reference to this set of keys so
186 /// that you can serialize the full ChannelManager object.
188 /// (TODO: We shouldn't require that, and should have an API to get them at deser time, due mostly
189 /// to the possibility of reentrancy issues by calling the user's code during our deserialization
191 /// TODO: We should remove Clone by instead requesting a new ChannelKeys copy when we create
192 /// ChannelMonitors instead of expecting to clone the one out of the Channel into the monitors.
193 pub trait ChannelKeys : Send+Clone {
194 /// Gets the private key for the anchor tx
195 fn funding_key<'a>(&'a self) -> &'a SecretKey;
196 /// Gets the local secret key for blinded revocation pubkey
197 fn revocation_base_key<'a>(&'a self) -> &'a SecretKey;
198 /// Gets the local secret key used in to_remote output of remote commitment tx
199 /// (and also as part of obscured commitment number)
200 fn payment_base_key<'a>(&'a self) -> &'a SecretKey;
201 /// Gets the local secret key used in HTLC-Success/HTLC-Timeout txn and to_local output
202 fn delayed_payment_base_key<'a>(&'a self) -> &'a SecretKey;
203 /// Gets the local htlc secret key used in commitment tx htlc outputs
204 fn htlc_base_key<'a>(&'a self) -> &'a SecretKey;
205 /// Gets the commitment seed
206 fn commitment_seed<'a>(&'a self) -> &'a [u8; 32];
207 /// Gets the local channel public keys and basepoints
208 fn pubkeys<'a>(&'a self) -> &'a ChannelPublicKeys;
210 /// Create a signature for a remote commitment transaction and associated HTLC transactions.
212 /// Note that if signing fails or is rejected, the channel will be force-closed.
214 /// TODO: Document the things someone using this interface should enforce before signing.
215 /// TODO: Add more input vars to enable better checking (preferably removing commitment_tx and
216 /// making the callee generate it via some util function we expose)!
217 fn sign_remote_commitment<T: secp256k1::Signing + secp256k1::Verification>(&self, feerate_per_kw: u64, commitment_tx: &Transaction, keys: &TxCreationKeys, htlcs: &[&HTLCOutputInCommitment], to_self_delay: u16, secp_ctx: &Secp256k1<T>) -> Result<(Signature, Vec<Signature>), ()>;
219 /// Create a signature for a local commitment transaction
221 /// TODO: Document the things someone using this interface should enforce before signing.
222 /// TODO: Add more input vars to enable better checking (preferably removing commitment_tx and
223 /// TODO: Ensure test-only version doesn't enforce uniqueness of signature when it's enforced in this method
224 /// making the callee generate it via some util function we expose)!
225 fn sign_local_commitment<T: secp256k1::Signing + secp256k1::Verification>(&self, local_commitment_tx: &mut LocalCommitmentTransaction, funding_redeemscript: &Script, channel_value_satoshis: u64, secp_ctx: &Secp256k1<T>);
227 /// Create a signature for a local commitment transaction without enforcing one-time signing.
229 /// Testing revocation logic by our test framework needs to sign multiple local commitment
230 /// transactions. This unsafe test-only version doesn't enforce one-time signing security
233 fn unsafe_sign_local_commitment<T: secp256k1::Signing + secp256k1::Verification>(&self, local_commitment_tx: &mut LocalCommitmentTransaction, funding_redeemscript: &Script, channel_value_satoshis: u64, secp_ctx: &Secp256k1<T>);
235 /// Signs a transaction created by build_htlc_transaction. If the transaction is an
236 /// HTLC-Success transaction, preimage must be set!
237 /// TODO: should be merged with sign_local_commitment as a slice of HTLC transactions to sign
238 fn sign_htlc_transaction<T: secp256k1::Signing>(&self, htlc_tx: &mut Transaction, their_sig: &Signature, preimage: &Option<PaymentPreimage>, htlc: &HTLCOutputInCommitment, a_htlc_key: &PublicKey, b_htlc_key: &PublicKey, revocation_key: &PublicKey, per_commitment_point: &PublicKey, secp_ctx: &Secp256k1<T>);
240 /// Create a signature for a (proposed) closing transaction.
242 /// Note that, due to rounding, there may be one "missing" satoshi, and either party may have
243 /// chosen to forgo their output as dust.
244 fn sign_closing_transaction<T: secp256k1::Signing>(&self, closing_tx: &Transaction, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()>;
246 /// Signs a channel announcement message with our funding key, proving it comes from one
247 /// of the channel participants.
249 /// Note that if this fails or is rejected, the channel will not be publicly announced and
250 /// our counterparty may (though likely will not) close the channel on us for violating the
252 fn sign_channel_announcement<T: secp256k1::Signing>(&self, msg: &msgs::UnsignedChannelAnnouncement, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()>;
254 /// Set the remote channel basepoints. This is done immediately on incoming channels
255 /// and as soon as the channel is accepted on outgoing channels.
257 /// Will be called before any signatures are applied.
258 fn set_remote_channel_pubkeys(&mut self, channel_points: &ChannelPublicKeys);
262 /// A simple implementation of ChannelKeys that just keeps the private keys in memory.
263 pub struct InMemoryChannelKeys {
264 /// Private key of anchor tx
265 funding_key: SecretKey,
266 /// Local secret key for blinded revocation pubkey
267 revocation_base_key: SecretKey,
268 /// Local secret key used in commitment tx htlc outputs
269 payment_base_key: SecretKey,
270 /// Local secret key used in HTLC tx
271 delayed_payment_base_key: SecretKey,
272 /// Local htlc secret key used in commitment tx htlc outputs
273 htlc_base_key: SecretKey,
275 commitment_seed: [u8; 32],
276 /// Local public keys and basepoints
277 pub(crate) local_channel_pubkeys: ChannelPublicKeys,
278 /// Remote public keys and base points
279 pub(crate) remote_channel_pubkeys: Option<ChannelPublicKeys>,
280 /// The total value of this channel
281 channel_value_satoshis: u64,
284 impl InMemoryChannelKeys {
285 /// Create a new InMemoryChannelKeys
286 pub fn new<C: Signing>(
287 secp_ctx: &Secp256k1<C>,
288 funding_key: SecretKey,
289 revocation_base_key: SecretKey,
290 payment_base_key: SecretKey,
291 delayed_payment_base_key: SecretKey,
292 htlc_base_key: SecretKey,
293 commitment_seed: [u8; 32],
294 channel_value_satoshis: u64) -> InMemoryChannelKeys {
295 let local_channel_pubkeys =
296 InMemoryChannelKeys::make_local_keys(secp_ctx, &funding_key, &revocation_base_key,
297 &payment_base_key, &delayed_payment_base_key,
299 InMemoryChannelKeys {
303 delayed_payment_base_key,
306 channel_value_satoshis,
307 local_channel_pubkeys,
308 remote_channel_pubkeys: None,
312 fn make_local_keys<C: Signing>(secp_ctx: &Secp256k1<C>,
313 funding_key: &SecretKey,
314 revocation_base_key: &SecretKey,
315 payment_base_key: &SecretKey,
316 delayed_payment_base_key: &SecretKey,
317 htlc_base_key: &SecretKey) -> ChannelPublicKeys {
318 let from_secret = |s: &SecretKey| PublicKey::from_secret_key(secp_ctx, s);
320 funding_pubkey: from_secret(&funding_key),
321 revocation_basepoint: from_secret(&revocation_base_key),
322 payment_basepoint: from_secret(&payment_base_key),
323 delayed_payment_basepoint: from_secret(&delayed_payment_base_key),
324 htlc_basepoint: from_secret(&htlc_base_key),
329 impl ChannelKeys for InMemoryChannelKeys {
330 fn funding_key(&self) -> &SecretKey { &self.funding_key }
331 fn revocation_base_key(&self) -> &SecretKey { &self.revocation_base_key }
332 fn payment_base_key(&self) -> &SecretKey { &self.payment_base_key }
333 fn delayed_payment_base_key(&self) -> &SecretKey { &self.delayed_payment_base_key }
334 fn htlc_base_key(&self) -> &SecretKey { &self.htlc_base_key }
335 fn commitment_seed(&self) -> &[u8; 32] { &self.commitment_seed }
336 fn pubkeys<'a>(&'a self) -> &'a ChannelPublicKeys { &self.local_channel_pubkeys }
338 fn sign_remote_commitment<T: secp256k1::Signing + secp256k1::Verification>(&self, feerate_per_kw: u64, commitment_tx: &Transaction, keys: &TxCreationKeys, htlcs: &[&HTLCOutputInCommitment], to_self_delay: u16, secp_ctx: &Secp256k1<T>) -> Result<(Signature, Vec<Signature>), ()> {
339 if commitment_tx.input.len() != 1 { return Err(()); }
341 let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
342 let remote_channel_pubkeys = self.remote_channel_pubkeys.as_ref().expect("must set remote channel pubkeys before signing");
343 let channel_funding_redeemscript = make_funding_redeemscript(&funding_pubkey, &remote_channel_pubkeys.funding_pubkey);
345 let commitment_sighash = hash_to_message!(&bip143::SighashComponents::new(&commitment_tx).sighash_all(&commitment_tx.input[0], &channel_funding_redeemscript, self.channel_value_satoshis)[..]);
346 let commitment_sig = secp_ctx.sign(&commitment_sighash, &self.funding_key);
348 let commitment_txid = commitment_tx.txid();
350 let mut htlc_sigs = Vec::with_capacity(htlcs.len());
351 for ref htlc in htlcs {
352 if let Some(_) = htlc.transaction_output_index {
353 let htlc_tx = chan_utils::build_htlc_transaction(&commitment_txid, feerate_per_kw, to_self_delay, htlc, &keys.a_delayed_payment_key, &keys.revocation_key);
354 let htlc_redeemscript = chan_utils::get_htlc_redeemscript(&htlc, &keys);
355 let htlc_sighash = hash_to_message!(&bip143::SighashComponents::new(&htlc_tx).sighash_all(&htlc_tx.input[0], &htlc_redeemscript, htlc.amount_msat / 1000)[..]);
356 let our_htlc_key = match chan_utils::derive_private_key(&secp_ctx, &keys.per_commitment_point, &self.htlc_base_key) {
358 Err(_) => return Err(()),
360 htlc_sigs.push(secp_ctx.sign(&htlc_sighash, &our_htlc_key));
364 Ok((commitment_sig, htlc_sigs))
367 fn sign_local_commitment<T: secp256k1::Signing + secp256k1::Verification>(&self, local_commitment_tx: &mut LocalCommitmentTransaction, funding_redeemscript: &Script, channel_value_satoshis: u64, secp_ctx: &Secp256k1<T>) {
368 local_commitment_tx.add_local_sig(&self.funding_key, funding_redeemscript, channel_value_satoshis, secp_ctx);
372 fn unsafe_sign_local_commitment<T: secp256k1::Signing + secp256k1::Verification>(&self, local_commitment_tx: &mut LocalCommitmentTransaction, funding_redeemscript: &Script, channel_value_satoshis: u64, secp_ctx: &Secp256k1<T>) {
373 local_commitment_tx.add_local_sig(&self.funding_key, funding_redeemscript, channel_value_satoshis, secp_ctx);
376 fn sign_htlc_transaction<T: secp256k1::Signing>(&self, htlc_tx: &mut Transaction, their_sig: &Signature, preimage: &Option<PaymentPreimage>, htlc: &HTLCOutputInCommitment, a_htlc_key: &PublicKey, b_htlc_key: &PublicKey, revocation_key: &PublicKey, per_commitment_point: &PublicKey, secp_ctx: &Secp256k1<T>) {
377 if htlc_tx.input.len() != 1 { return; }
378 if htlc_tx.input[0].witness.len() != 0 { return; }
380 let htlc_redeemscript = chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, a_htlc_key, b_htlc_key, revocation_key);
382 if let Ok(our_htlc_key) = chan_utils::derive_private_key(secp_ctx, per_commitment_point, &self.htlc_base_key) {
383 let sighash = hash_to_message!(&bip143::SighashComponents::new(&htlc_tx).sighash_all(&htlc_tx.input[0], &htlc_redeemscript, htlc.amount_msat / 1000)[..]);
384 let local_tx = PublicKey::from_secret_key(&secp_ctx, &our_htlc_key) == *a_htlc_key;
385 let our_sig = secp_ctx.sign(&sighash, &our_htlc_key);
387 htlc_tx.input[0].witness.push(Vec::new()); // First is the multisig dummy
389 if local_tx { // b, then a
390 htlc_tx.input[0].witness.push(their_sig.serialize_der().to_vec());
391 htlc_tx.input[0].witness.push(our_sig.serialize_der().to_vec());
393 htlc_tx.input[0].witness.push(our_sig.serialize_der().to_vec());
394 htlc_tx.input[0].witness.push(their_sig.serialize_der().to_vec());
396 htlc_tx.input[0].witness[1].push(SigHashType::All as u8);
397 htlc_tx.input[0].witness[2].push(SigHashType::All as u8);
400 htlc_tx.input[0].witness.push(Vec::new());
401 assert!(preimage.is_none());
403 htlc_tx.input[0].witness.push(preimage.unwrap().0.to_vec());
406 htlc_tx.input[0].witness.push(htlc_redeemscript.as_bytes().to_vec());
410 fn sign_closing_transaction<T: secp256k1::Signing>(&self, closing_tx: &Transaction, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()> {
411 if closing_tx.input.len() != 1 { return Err(()); }
412 if closing_tx.input[0].witness.len() != 0 { return Err(()); }
413 if closing_tx.output.len() > 2 { return Err(()); }
415 let remote_channel_pubkeys = self.remote_channel_pubkeys.as_ref().expect("must set remote channel pubkeys before signing");
416 let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
417 let channel_funding_redeemscript = make_funding_redeemscript(&funding_pubkey, &remote_channel_pubkeys.funding_pubkey);
419 let sighash = hash_to_message!(&bip143::SighashComponents::new(closing_tx)
420 .sighash_all(&closing_tx.input[0], &channel_funding_redeemscript, self.channel_value_satoshis)[..]);
421 Ok(secp_ctx.sign(&sighash, &self.funding_key))
424 fn sign_channel_announcement<T: secp256k1::Signing>(&self, msg: &msgs::UnsignedChannelAnnouncement, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()> {
425 let msghash = hash_to_message!(&Sha256dHash::hash(&msg.encode()[..])[..]);
426 Ok(secp_ctx.sign(&msghash, &self.funding_key))
429 fn set_remote_channel_pubkeys(&mut self, channel_pubkeys: &ChannelPublicKeys) {
430 assert!(self.remote_channel_pubkeys.is_none(), "Already set remote channel pubkeys");
431 self.remote_channel_pubkeys = Some(channel_pubkeys.clone());
435 impl Writeable for InMemoryChannelKeys {
436 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), Error> {
437 self.funding_key.write(writer)?;
438 self.revocation_base_key.write(writer)?;
439 self.payment_base_key.write(writer)?;
440 self.delayed_payment_base_key.write(writer)?;
441 self.htlc_base_key.write(writer)?;
442 self.commitment_seed.write(writer)?;
443 self.remote_channel_pubkeys.write(writer)?;
444 self.channel_value_satoshis.write(writer)?;
450 impl Readable for InMemoryChannelKeys {
451 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
452 let funding_key = Readable::read(reader)?;
453 let revocation_base_key = Readable::read(reader)?;
454 let payment_base_key = Readable::read(reader)?;
455 let delayed_payment_base_key = Readable::read(reader)?;
456 let htlc_base_key = Readable::read(reader)?;
457 let commitment_seed = Readable::read(reader)?;
458 let remote_channel_pubkeys = Readable::read(reader)?;
459 let channel_value_satoshis = Readable::read(reader)?;
460 let secp_ctx = Secp256k1::signing_only();
461 let local_channel_pubkeys =
462 InMemoryChannelKeys::make_local_keys(&secp_ctx, &funding_key, &revocation_base_key,
463 &payment_base_key, &delayed_payment_base_key,
466 Ok(InMemoryChannelKeys {
470 delayed_payment_base_key,
473 channel_value_satoshis,
474 local_channel_pubkeys,
475 remote_channel_pubkeys
480 /// Simple KeysInterface implementor that takes a 32-byte seed for use as a BIP 32 extended key
481 /// and derives keys from that.
483 /// Your node_id is seed/0'
484 /// ChannelMonitor closes may use seed/1'
485 /// Cooperative closes may use seed/2'
486 /// The two close keys may be needed to claim on-chain funds!
487 pub struct KeysManager {
488 secp_ctx: Secp256k1<secp256k1::SignOnly>,
489 node_secret: SecretKey,
490 destination_script: Script,
491 shutdown_pubkey: PublicKey,
492 channel_master_key: ExtendedPrivKey,
493 channel_child_index: AtomicUsize,
494 session_master_key: ExtendedPrivKey,
495 session_child_index: AtomicUsize,
496 channel_id_master_key: ExtendedPrivKey,
497 channel_id_child_index: AtomicUsize,
499 unique_start: Sha256State,
504 /// Constructs a KeysManager from a 32-byte seed. If the seed is in some way biased (eg your
505 /// RNG is busted) this may panic (but more importantly, you will possibly lose funds).
506 /// starting_time isn't strictly required to actually be a time, but it must absolutely,
507 /// without a doubt, be unique to this instance. ie if you start multiple times with the same
508 /// seed, starting_time must be unique to each run. Thus, the easiest way to achieve this is to
509 /// simply use the current time (with very high precision).
511 /// The seed MUST be backed up safely prior to use so that the keys can be re-created, however,
512 /// obviously, starting_time should be unique every time you reload the library - it is only
513 /// used to generate new ephemeral key data (which will be stored by the individual channel if
516 /// Note that the seed is required to recover certain on-chain funds independent of
517 /// ChannelMonitor data, though a current copy of ChannelMonitor data is also required for any
518 /// channel, and some on-chain during-closing funds.
520 /// Note that until the 0.1 release there is no guarantee of backward compatibility between
521 /// versions. Once the library is more fully supported, the docs will be updated to include a
522 /// detailed description of the guarantee.
523 pub fn new(seed: &[u8; 32], network: Network, logger: Arc<Logger>, starting_time_secs: u64, starting_time_nanos: u32) -> KeysManager {
524 let secp_ctx = Secp256k1::signing_only();
525 match ExtendedPrivKey::new_master(network.clone(), seed) {
527 let node_secret = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(0).unwrap()).expect("Your RNG is busted").private_key.key;
528 let destination_script = match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(1).unwrap()) {
529 Ok(destination_key) => {
530 let pubkey_hash160 = Hash160::hash(&ExtendedPubKey::from_private(&secp_ctx, &destination_key).public_key.key.serialize()[..]);
531 Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0)
532 .push_slice(&pubkey_hash160.into_inner())
535 Err(_) => panic!("Your RNG is busted"),
537 let shutdown_pubkey = match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(2).unwrap()) {
538 Ok(shutdown_key) => ExtendedPubKey::from_private(&secp_ctx, &shutdown_key).public_key.key,
539 Err(_) => panic!("Your RNG is busted"),
541 let channel_master_key = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(3).unwrap()).expect("Your RNG is busted");
542 let session_master_key = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(4).unwrap()).expect("Your RNG is busted");
543 let channel_id_master_key = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(5).unwrap()).expect("Your RNG is busted");
545 let mut unique_start = Sha256::engine();
546 unique_start.input(&byte_utils::be64_to_array(starting_time_secs));
547 unique_start.input(&byte_utils::be32_to_array(starting_time_nanos));
548 unique_start.input(seed);
556 channel_child_index: AtomicUsize::new(0),
558 session_child_index: AtomicUsize::new(0),
559 channel_id_master_key,
560 channel_id_child_index: AtomicUsize::new(0),
566 Err(_) => panic!("Your rng is busted"),
571 impl KeysInterface for KeysManager {
572 type ChanKeySigner = InMemoryChannelKeys;
574 fn get_node_secret(&self) -> SecretKey {
575 self.node_secret.clone()
578 fn get_destination_script(&self) -> Script {
579 self.destination_script.clone()
582 fn get_shutdown_pubkey(&self) -> PublicKey {
583 self.shutdown_pubkey.clone()
586 fn get_channel_keys(&self, _inbound: bool, channel_value_satoshis: u64) -> InMemoryChannelKeys {
587 // We only seriously intend to rely on the channel_master_key for true secure
588 // entropy, everything else just ensures uniqueness. We rely on the unique_start (ie
589 // starting_time provided in the constructor) to be unique.
590 let mut sha = self.unique_start.clone();
592 let child_ix = self.channel_child_index.fetch_add(1, Ordering::AcqRel);
593 let child_privkey = self.channel_master_key.ckd_priv(&self.secp_ctx, ChildNumber::from_hardened_idx(child_ix as u32).expect("key space exhausted")).expect("Your RNG is busted");
594 sha.input(&child_privkey.private_key.key[..]);
596 let seed = Sha256::from_engine(sha).into_inner();
598 let commitment_seed = {
599 let mut sha = Sha256::engine();
601 sha.input(&b"commitment seed"[..]);
602 Sha256::from_engine(sha).into_inner()
604 macro_rules! key_step {
605 ($info: expr, $prev_key: expr) => {{
606 let mut sha = Sha256::engine();
608 sha.input(&$prev_key[..]);
609 sha.input(&$info[..]);
610 SecretKey::from_slice(&Sha256::from_engine(sha).into_inner()).expect("SHA-256 is busted")
613 let funding_key = key_step!(b"funding key", commitment_seed);
614 let revocation_base_key = key_step!(b"revocation base key", funding_key);
615 let payment_base_key = key_step!(b"payment base key", revocation_base_key);
616 let delayed_payment_base_key = key_step!(b"delayed payment base key", payment_base_key);
617 let htlc_base_key = key_step!(b"HTLC base key", delayed_payment_base_key);
619 InMemoryChannelKeys::new(
624 delayed_payment_base_key,
627 channel_value_satoshis
631 fn get_onion_rand(&self) -> (SecretKey, [u8; 32]) {
632 let mut sha = self.unique_start.clone();
634 let child_ix = self.session_child_index.fetch_add(1, Ordering::AcqRel);
635 let child_privkey = self.session_master_key.ckd_priv(&self.secp_ctx, ChildNumber::from_hardened_idx(child_ix as u32).expect("key space exhausted")).expect("Your RNG is busted");
636 sha.input(&child_privkey.private_key.key[..]);
638 let mut rng_seed = sha.clone();
639 // Not exactly the most ideal construction, but the second value will get fed into
640 // ChaCha so it is another step harder to break.
641 rng_seed.input(b"RNG Seed Salt");
642 sha.input(b"Session Key Salt");
643 (SecretKey::from_slice(&Sha256::from_engine(sha).into_inner()).expect("Your RNG is busted"),
644 Sha256::from_engine(rng_seed).into_inner())
647 fn get_channel_id(&self) -> [u8; 32] {
648 let mut sha = self.unique_start.clone();
650 let child_ix = self.channel_id_child_index.fetch_add(1, Ordering::AcqRel);
651 let child_privkey = self.channel_id_master_key.ckd_priv(&self.secp_ctx, ChildNumber::from_hardened_idx(child_ix as u32).expect("key space exhausted")).expect("Your RNG is busted");
652 sha.input(&child_privkey.private_key.key[..]);
654 (Sha256::from_engine(sha).into_inner())