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};
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::hash_types::WPubkeyHash;
18 use bitcoin::secp256k1::key::{SecretKey, PublicKey};
19 use bitcoin::secp256k1::{Secp256k1, Signature, Signing};
20 use bitcoin::secp256k1;
23 use util::ser::{Writeable, Writer, Readable};
26 use ln::chan_utils::{TxCreationKeys, HTLCOutputInCommitment, make_funding_redeemscript, ChannelPublicKeys, LocalCommitmentTransaction};
29 use std::sync::atomic::{AtomicUsize, Ordering};
31 use ln::msgs::DecodeError;
33 /// When on-chain outputs are created by rust-lightning (which our counterparty is not able to
34 /// claim at any point in the future) an event is generated which you must track and be able to
35 /// spend on-chain. The information needed to do this is provided in this enum, including the
36 /// outpoint describing which txid and output index is available, the full output which exists at
37 /// that txid/index, and any keys or other information required to sign.
38 #[derive(Clone, PartialEq)]
39 pub enum SpendableOutputDescriptor {
40 /// An output to a script which was provided via KeysInterface, thus you should already know
41 /// how to spend it. No keys are provided as rust-lightning was never given any keys - only the
42 /// script_pubkey as it appears in the output.
43 /// These may include outputs from a transaction punishing our counterparty or claiming an HTLC
44 /// on-chain using the payment preimage or after it has timed out.
46 /// The outpoint which is spendable
48 /// The output which is referenced by the given outpoint.
51 /// An output to a P2WSH script which can be spent with a single signature after a CSV delay.
52 /// The private key which should be used to sign the transaction is provided, as well as the
53 /// full witness redeemScript which is hashed in the output script_pubkey.
54 /// The witness in the spending input should be:
55 /// <BIP 143 signature generated with the given key> <empty vector> (MINIMALIF standard rule)
56 /// <witness_script as provided>
57 /// Note that the nSequence field in the input must be set to_self_delay (which corresponds to
58 /// the transaction not being broadcastable until at least to_self_delay blocks after the input
60 /// These are generally the result of a "revocable" output to us, spendable only by us unless
61 /// it is an output from us having broadcast an old state (which should never happen).
63 /// The outpoint which is spendable
65 /// The secret key which must be used to sign the spending transaction
67 /// The witness redeemScript which is hashed to create the script_pubkey in the given output
68 witness_script: Script,
69 /// The nSequence value which must be set in the spending input to satisfy the OP_CSV in
70 /// the witness_script.
72 /// The output which is referenced by the given outpoint
75 // TODO: Note that because key is now static and exactly what is provided by us, we should drop
76 // this in favor of StaticOutput:
77 /// An output to a P2WPKH, spendable exclusively by the given private key.
78 /// The witness in the spending input, is, thus, simply:
79 /// <BIP 143 signature generated with the given key> <public key derived from the given key>
80 /// These are generally the result of our counterparty having broadcast the current state,
81 /// allowing us to claim the non-HTLC-encumbered outputs immediately.
83 /// The outpoint which is spendable
85 /// The secret key which must be used to sign the spending transaction
87 /// The output which is reference by the given outpoint
92 impl Writeable for SpendableOutputDescriptor {
93 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
95 &SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output } => {
97 outpoint.write(writer)?;
98 output.write(writer)?;
100 &SpendableOutputDescriptor::DynamicOutputP2WSH { ref outpoint, ref key, ref witness_script, ref to_self_delay, ref output } => {
102 outpoint.write(writer)?;
104 witness_script.write(writer)?;
105 to_self_delay.write(writer)?;
106 output.write(writer)?;
108 &SpendableOutputDescriptor::DynamicOutputP2WPKH { ref outpoint, ref key, ref output } => {
110 outpoint.write(writer)?;
112 output.write(writer)?;
119 impl Readable for SpendableOutputDescriptor {
120 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
121 match Readable::read(reader)? {
122 0u8 => Ok(SpendableOutputDescriptor::StaticOutput {
123 outpoint: Readable::read(reader)?,
124 output: Readable::read(reader)?,
126 1u8 => Ok(SpendableOutputDescriptor::DynamicOutputP2WSH {
127 outpoint: Readable::read(reader)?,
128 key: Readable::read(reader)?,
129 witness_script: Readable::read(reader)?,
130 to_self_delay: Readable::read(reader)?,
131 output: Readable::read(reader)?,
133 2u8 => Ok(SpendableOutputDescriptor::DynamicOutputP2WPKH {
134 outpoint: Readable::read(reader)?,
135 key: Readable::read(reader)?,
136 output: Readable::read(reader)?,
138 _ => Err(DecodeError::InvalidValue),
143 /// A trait to describe an object which can get user secrets and key material.
144 pub trait KeysInterface: Send + Sync {
145 /// A type which implements ChannelKeys which will be returned by get_channel_keys.
146 type ChanKeySigner : ChannelKeys;
148 /// Get node secret key (aka node_id or network_key)
149 fn get_node_secret(&self) -> SecretKey;
150 /// Get destination redeemScript to encumber static protocol exit points.
151 fn get_destination_script(&self) -> Script;
152 /// Get shutdown_pubkey to use as PublicKey at channel closure
153 fn get_shutdown_pubkey(&self) -> PublicKey;
154 /// Get a new set of ChannelKeys for per-channel secrets. These MUST be unique even if you
155 /// restarted with some stale data!
156 fn get_channel_keys(&self, inbound: bool, channel_value_satoshis: u64) -> Self::ChanKeySigner;
157 /// Get a secret and PRNG seed for construting an onion packet
158 fn get_onion_rand(&self) -> (SecretKey, [u8; 32]);
159 /// Get a unique temporary channel id. Channels will be referred to by this until the funding
160 /// transaction is created, at which point they will use the outpoint in the funding
162 fn get_channel_id(&self) -> [u8; 32];
165 /// Set of lightning keys needed to operate a channel as described in BOLT 3.
167 /// Signing services could be implemented on a hardware wallet. In this case,
168 /// the current ChannelKeys would be a front-end on top of a communication
169 /// channel connected to your secure device and lightning key material wouldn't
170 /// reside on a hot server. Nevertheless, a this deployment would still need
171 /// to trust the ChannelManager to avoid loss of funds as this latest component
172 /// could ask to sign commitment transaction with HTLCs paying to attacker pubkeys.
174 /// A more secure iteration would be to use hashlock (or payment points) to pair
175 /// invoice/incoming HTLCs with outgoing HTLCs to implement a no-trust-ChannelManager
176 /// at the price of more state and computation on the hardware wallet side. In the future,
177 /// we are looking forward to design such interface.
179 /// In any case, ChannelMonitor or fallback watchtowers are always going to be trusted
180 /// to act, as liveness and breach reply correctness are always going to be hard requirements
181 /// of LN security model, orthogonal of key management issues.
183 /// If you're implementing a custom signer, you almost certainly want to implement
184 /// Readable/Writable to serialize out a unique reference to this set of keys so
185 /// that you can serialize the full ChannelManager object.
187 // (TODO: We shouldn't require that, and should have an API to get them at deser time, due mostly
188 // to the possibility of reentrancy issues by calling the user's code during our deserialization
190 // TODO: We should remove Clone by instead requesting a new ChannelKeys copy when we create
191 // ChannelMonitors instead of expecting to clone the one out of the Channel into the monitors.
192 pub trait ChannelKeys : Send+Clone {
193 /// Gets the private key for the anchor tx
194 fn funding_key<'a>(&'a self) -> &'a SecretKey;
195 /// Gets the local secret key for blinded revocation pubkey
196 fn revocation_base_key<'a>(&'a self) -> &'a SecretKey;
197 /// Gets the local secret key used in the to_remote output of remote commitment tx (ie the
198 /// output to us in transactions our counterparty broadcasts).
199 /// Also as part of obscured commitment number.
200 fn payment_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. This will only ever be called with
220 /// the same local_commitment_tx (or a copy thereof), though there are currently no guarantees
221 /// that it will not be called multiple times.
223 // TODO: Document the things someone using this interface should enforce before signing.
224 // TODO: Add more input vars to enable better checking (preferably removing commitment_tx and
225 fn sign_local_commitment<T: secp256k1::Signing + secp256k1::Verification>(&self, local_commitment_tx: &LocalCommitmentTransaction, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()>;
227 /// Same as sign_local_commitment, but exists only for tests to get access to local commitment
228 /// transactions which will be broadcasted later, after the channel has moved on to a newer
229 /// state. Thus, needs its own method as sign_local_commitment may enforce that we only ever
232 fn unsafe_sign_local_commitment<T: secp256k1::Signing + secp256k1::Verification>(&self, local_commitment_tx: &LocalCommitmentTransaction, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()>;
234 /// Create a signature for each HTLC transaction spending a local commitment transaction.
236 /// Unlike sign_local_commitment, this may be called multiple times with *different*
237 /// local_commitment_tx values. While this will never be called with a revoked
238 /// local_commitment_tx, it is possible that it is called with the second-latest
239 /// local_commitment_tx (only if we haven't yet revoked it) if some watchtower/secondary
240 /// ChannelMonitor decided to broadcast before it had been updated to the latest.
242 /// Either an Err should be returned, or a Vec with one entry for each HTLC which exists in
243 /// local_commitment_tx. For those HTLCs which have transaction_output_index set to None
244 /// (implying they were considered dust at the time the commitment transaction was negotiated),
245 /// a corresponding None should be included in the return value. All other positions in the
246 /// return value must contain a signature.
247 fn sign_local_commitment_htlc_transactions<T: secp256k1::Signing + secp256k1::Verification>(&self, local_commitment_tx: &LocalCommitmentTransaction, local_csv: u16, secp_ctx: &Secp256k1<T>) -> Result<Vec<Option<Signature>>, ()>;
249 /// Create a signature for a transaction spending an HTLC or commitment transaction output
250 /// when our counterparty broadcast an old state.
252 /// Justice transaction may claim multiples outputs at same time if timelock are similar.
253 /// It may be called multiples time for same output(s) if a fee-bump is needed with regards
254 /// to an upcoming timelock expiration.
256 /// Witness_script is a revokable witness script as defined in BOLT3 for `to_local`/HTLC
259 /// Input index is a pointer towards outpoint spent, commited by sigs (BIP 143).
261 /// Amount is value of the output spent by this input, committed by sigs (BIP 143).
263 /// Per_commitment key is revocation secret such as provided by remote party while
264 /// revocating detected onchain transaction. It's not a _local_ secret key, therefore
265 /// it may cross interfaces, a node compromise won't allow to spend revoked output without
266 /// also compromissing revocation key.
267 //TODO: dry-up witness_script and pass pubkeys
268 fn sign_justice_transaction<T: secp256k1::Signing>(&self, justice_tx: &Transaction, input: usize, witness_script: &Script, amount: u64, per_commitment_key: &SecretKey, revocation_pubkey: &PublicKey, is_htlc: bool, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()>;
270 /// Create a signature for a (proposed) closing transaction.
272 /// Note that, due to rounding, there may be one "missing" satoshi, and either party may have
273 /// chosen to forgo their output as dust.
274 fn sign_closing_transaction<T: secp256k1::Signing>(&self, closing_tx: &Transaction, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()>;
276 /// Signs a channel announcement message with our funding key, proving it comes from one
277 /// of the channel participants.
279 /// Note that if this fails or is rejected, the channel will not be publicly announced and
280 /// our counterparty may (though likely will not) close the channel on us for violating the
282 fn sign_channel_announcement<T: secp256k1::Signing>(&self, msg: &msgs::UnsignedChannelAnnouncement, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()>;
284 /// Set the remote channel basepoints. This is done immediately on incoming channels
285 /// and as soon as the channel is accepted on outgoing channels.
287 /// Will be called before any signatures are applied.
288 fn set_remote_channel_pubkeys(&mut self, channel_points: &ChannelPublicKeys);
292 /// A simple implementation of ChannelKeys that just keeps the private keys in memory.
293 pub struct InMemoryChannelKeys {
294 /// Private key of anchor tx
295 funding_key: SecretKey,
296 /// Local secret key for blinded revocation pubkey
297 revocation_base_key: SecretKey,
298 /// Local secret key used for our balance in remote-broadcasted commitment transactions
299 payment_key: SecretKey,
300 /// Local secret key used in HTLC tx
301 delayed_payment_base_key: SecretKey,
302 /// Local htlc secret key used in commitment tx htlc outputs
303 htlc_base_key: SecretKey,
305 commitment_seed: [u8; 32],
306 /// Local public keys and basepoints
307 pub(crate) local_channel_pubkeys: ChannelPublicKeys,
308 /// Remote public keys and base points
309 pub(crate) remote_channel_pubkeys: Option<ChannelPublicKeys>,
310 /// The total value of this channel
311 channel_value_satoshis: u64,
314 impl InMemoryChannelKeys {
315 /// Create a new InMemoryChannelKeys
316 pub fn new<C: Signing>(
317 secp_ctx: &Secp256k1<C>,
318 funding_key: SecretKey,
319 revocation_base_key: SecretKey,
320 payment_key: SecretKey,
321 delayed_payment_base_key: SecretKey,
322 htlc_base_key: SecretKey,
323 commitment_seed: [u8; 32],
324 channel_value_satoshis: u64) -> InMemoryChannelKeys {
325 let local_channel_pubkeys =
326 InMemoryChannelKeys::make_local_keys(secp_ctx, &funding_key, &revocation_base_key,
327 &payment_key, &delayed_payment_base_key,
329 InMemoryChannelKeys {
333 delayed_payment_base_key,
336 channel_value_satoshis,
337 local_channel_pubkeys,
338 remote_channel_pubkeys: None,
342 fn make_local_keys<C: Signing>(secp_ctx: &Secp256k1<C>,
343 funding_key: &SecretKey,
344 revocation_base_key: &SecretKey,
345 payment_key: &SecretKey,
346 delayed_payment_base_key: &SecretKey,
347 htlc_base_key: &SecretKey) -> ChannelPublicKeys {
348 let from_secret = |s: &SecretKey| PublicKey::from_secret_key(secp_ctx, s);
350 funding_pubkey: from_secret(&funding_key),
351 revocation_basepoint: from_secret(&revocation_base_key),
352 payment_point: from_secret(&payment_key),
353 delayed_payment_basepoint: from_secret(&delayed_payment_base_key),
354 htlc_basepoint: from_secret(&htlc_base_key),
359 impl ChannelKeys for InMemoryChannelKeys {
360 fn funding_key(&self) -> &SecretKey { &self.funding_key }
361 fn revocation_base_key(&self) -> &SecretKey { &self.revocation_base_key }
362 fn payment_key(&self) -> &SecretKey { &self.payment_key }
363 fn delayed_payment_base_key(&self) -> &SecretKey { &self.delayed_payment_base_key }
364 fn htlc_base_key(&self) -> &SecretKey { &self.htlc_base_key }
365 fn commitment_seed(&self) -> &[u8; 32] { &self.commitment_seed }
366 fn pubkeys<'a>(&'a self) -> &'a ChannelPublicKeys { &self.local_channel_pubkeys }
368 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>), ()> {
369 if commitment_tx.input.len() != 1 { return Err(()); }
371 let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
372 let remote_channel_pubkeys = self.remote_channel_pubkeys.as_ref().expect("must set remote channel pubkeys before signing");
373 let channel_funding_redeemscript = make_funding_redeemscript(&funding_pubkey, &remote_channel_pubkeys.funding_pubkey);
375 let commitment_sighash = hash_to_message!(&bip143::SighashComponents::new(&commitment_tx).sighash_all(&commitment_tx.input[0], &channel_funding_redeemscript, self.channel_value_satoshis)[..]);
376 let commitment_sig = secp_ctx.sign(&commitment_sighash, &self.funding_key);
378 let commitment_txid = commitment_tx.txid();
380 let mut htlc_sigs = Vec::with_capacity(htlcs.len());
381 for ref htlc in htlcs {
382 if let Some(_) = htlc.transaction_output_index {
383 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);
384 let htlc_redeemscript = chan_utils::get_htlc_redeemscript(&htlc, &keys);
385 let htlc_sighash = hash_to_message!(&bip143::SighashComponents::new(&htlc_tx).sighash_all(&htlc_tx.input[0], &htlc_redeemscript, htlc.amount_msat / 1000)[..]);
386 let our_htlc_key = match chan_utils::derive_private_key(&secp_ctx, &keys.per_commitment_point, &self.htlc_base_key) {
388 Err(_) => return Err(()),
390 htlc_sigs.push(secp_ctx.sign(&htlc_sighash, &our_htlc_key));
394 Ok((commitment_sig, htlc_sigs))
397 fn sign_local_commitment<T: secp256k1::Signing + secp256k1::Verification>(&self, local_commitment_tx: &LocalCommitmentTransaction, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()> {
398 let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
399 let remote_channel_pubkeys = self.remote_channel_pubkeys.as_ref().expect("must set remote channel pubkeys before signing");
400 let channel_funding_redeemscript = make_funding_redeemscript(&funding_pubkey, &remote_channel_pubkeys.funding_pubkey);
402 Ok(local_commitment_tx.get_local_sig(&self.funding_key, &channel_funding_redeemscript, self.channel_value_satoshis, secp_ctx))
406 fn unsafe_sign_local_commitment<T: secp256k1::Signing + secp256k1::Verification>(&self, local_commitment_tx: &LocalCommitmentTransaction, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()> {
407 let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
408 let remote_channel_pubkeys = self.remote_channel_pubkeys.as_ref().expect("must set remote channel pubkeys before signing");
409 let channel_funding_redeemscript = make_funding_redeemscript(&funding_pubkey, &remote_channel_pubkeys.funding_pubkey);
411 Ok(local_commitment_tx.get_local_sig(&self.funding_key, &channel_funding_redeemscript, self.channel_value_satoshis, secp_ctx))
414 fn sign_local_commitment_htlc_transactions<T: secp256k1::Signing + secp256k1::Verification>(&self, local_commitment_tx: &LocalCommitmentTransaction, local_csv: u16, secp_ctx: &Secp256k1<T>) -> Result<Vec<Option<Signature>>, ()> {
415 local_commitment_tx.get_htlc_sigs(&self.htlc_base_key, local_csv, secp_ctx)
418 fn sign_justice_transaction<T: secp256k1::Signing>(&self, justice_tx: &Transaction, input: usize, witness_script: &Script, amount: u64, per_commitment_key: &SecretKey, revocation_pubkey: &PublicKey, is_htlc: bool, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()> {
419 if let Ok(revocation_key) = chan_utils::derive_private_revocation_key(&secp_ctx, &per_commitment_key, &self.revocation_base_key) {
420 let sighash_parts = bip143::SighashComponents::new(&justice_tx);
421 let sighash = hash_to_message!(&sighash_parts.sighash_all(&justice_tx.input[input], &witness_script, amount)[..]);
422 return Ok(secp_ctx.sign(&sighash, &revocation_key))
427 fn sign_closing_transaction<T: secp256k1::Signing>(&self, closing_tx: &Transaction, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()> {
428 if closing_tx.input.len() != 1 { return Err(()); }
429 if closing_tx.input[0].witness.len() != 0 { return Err(()); }
430 if closing_tx.output.len() > 2 { return Err(()); }
432 let remote_channel_pubkeys = self.remote_channel_pubkeys.as_ref().expect("must set remote channel pubkeys before signing");
433 let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
434 let channel_funding_redeemscript = make_funding_redeemscript(&funding_pubkey, &remote_channel_pubkeys.funding_pubkey);
436 let sighash = hash_to_message!(&bip143::SighashComponents::new(closing_tx)
437 .sighash_all(&closing_tx.input[0], &channel_funding_redeemscript, self.channel_value_satoshis)[..]);
438 Ok(secp_ctx.sign(&sighash, &self.funding_key))
441 fn sign_channel_announcement<T: secp256k1::Signing>(&self, msg: &msgs::UnsignedChannelAnnouncement, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()> {
442 let msghash = hash_to_message!(&Sha256dHash::hash(&msg.encode()[..])[..]);
443 Ok(secp_ctx.sign(&msghash, &self.funding_key))
446 fn set_remote_channel_pubkeys(&mut self, channel_pubkeys: &ChannelPublicKeys) {
447 assert!(self.remote_channel_pubkeys.is_none(), "Already set remote channel pubkeys");
448 self.remote_channel_pubkeys = Some(channel_pubkeys.clone());
452 impl Writeable for InMemoryChannelKeys {
453 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), Error> {
454 self.funding_key.write(writer)?;
455 self.revocation_base_key.write(writer)?;
456 self.payment_key.write(writer)?;
457 self.delayed_payment_base_key.write(writer)?;
458 self.htlc_base_key.write(writer)?;
459 self.commitment_seed.write(writer)?;
460 self.remote_channel_pubkeys.write(writer)?;
461 self.channel_value_satoshis.write(writer)?;
467 impl Readable for InMemoryChannelKeys {
468 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
469 let funding_key = Readable::read(reader)?;
470 let revocation_base_key = Readable::read(reader)?;
471 let payment_key = Readable::read(reader)?;
472 let delayed_payment_base_key = Readable::read(reader)?;
473 let htlc_base_key = Readable::read(reader)?;
474 let commitment_seed = Readable::read(reader)?;
475 let remote_channel_pubkeys = Readable::read(reader)?;
476 let channel_value_satoshis = Readable::read(reader)?;
477 let secp_ctx = Secp256k1::signing_only();
478 let local_channel_pubkeys =
479 InMemoryChannelKeys::make_local_keys(&secp_ctx, &funding_key, &revocation_base_key,
480 &payment_key, &delayed_payment_base_key,
483 Ok(InMemoryChannelKeys {
487 delayed_payment_base_key,
490 channel_value_satoshis,
491 local_channel_pubkeys,
492 remote_channel_pubkeys
497 /// Simple KeysInterface implementor that takes a 32-byte seed for use as a BIP 32 extended key
498 /// and derives keys from that.
500 /// Your node_id is seed/0'
501 /// ChannelMonitor closes may use seed/1'
502 /// Cooperative closes may use seed/2'
503 /// The two close keys may be needed to claim on-chain funds!
504 pub struct KeysManager {
505 secp_ctx: Secp256k1<secp256k1::SignOnly>,
506 node_secret: SecretKey,
507 destination_script: Script,
508 shutdown_pubkey: PublicKey,
509 channel_master_key: ExtendedPrivKey,
510 channel_child_index: AtomicUsize,
511 session_master_key: ExtendedPrivKey,
512 session_child_index: AtomicUsize,
513 channel_id_master_key: ExtendedPrivKey,
514 channel_id_child_index: AtomicUsize,
516 unique_start: Sha256State,
520 /// Constructs a KeysManager from a 32-byte seed. If the seed is in some way biased (eg your
521 /// RNG is busted) this may panic (but more importantly, you will possibly lose funds).
522 /// starting_time isn't strictly required to actually be a time, but it must absolutely,
523 /// without a doubt, be unique to this instance. ie if you start multiple times with the same
524 /// seed, starting_time must be unique to each run. Thus, the easiest way to achieve this is to
525 /// simply use the current time (with very high precision).
527 /// The seed MUST be backed up safely prior to use so that the keys can be re-created, however,
528 /// obviously, starting_time should be unique every time you reload the library - it is only
529 /// used to generate new ephemeral key data (which will be stored by the individual channel if
532 /// Note that the seed is required to recover certain on-chain funds independent of
533 /// ChannelMonitor data, though a current copy of ChannelMonitor data is also required for any
534 /// channel, and some on-chain during-closing funds.
536 /// Note that until the 0.1 release there is no guarantee of backward compatibility between
537 /// versions. Once the library is more fully supported, the docs will be updated to include a
538 /// detailed description of the guarantee.
539 pub fn new(seed: &[u8; 32], network: Network, starting_time_secs: u64, starting_time_nanos: u32) -> KeysManager {
540 let secp_ctx = Secp256k1::signing_only();
541 match ExtendedPrivKey::new_master(network.clone(), seed) {
543 let node_secret = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(0).unwrap()).expect("Your RNG is busted").private_key.key;
544 let destination_script = match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(1).unwrap()) {
545 Ok(destination_key) => {
546 let wpubkey_hash = WPubkeyHash::hash(&ExtendedPubKey::from_private(&secp_ctx, &destination_key).public_key.to_bytes());
547 Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0)
548 .push_slice(&wpubkey_hash.into_inner())
551 Err(_) => panic!("Your RNG is busted"),
553 let shutdown_pubkey = match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(2).unwrap()) {
554 Ok(shutdown_key) => ExtendedPubKey::from_private(&secp_ctx, &shutdown_key).public_key.key,
555 Err(_) => panic!("Your RNG is busted"),
557 let channel_master_key = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(3).unwrap()).expect("Your RNG is busted");
558 let session_master_key = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(4).unwrap()).expect("Your RNG is busted");
559 let channel_id_master_key = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(5).unwrap()).expect("Your RNG is busted");
561 let mut unique_start = Sha256::engine();
562 unique_start.input(&byte_utils::be64_to_array(starting_time_secs));
563 unique_start.input(&byte_utils::be32_to_array(starting_time_nanos));
564 unique_start.input(seed);
572 channel_child_index: AtomicUsize::new(0),
574 session_child_index: AtomicUsize::new(0),
575 channel_id_master_key,
576 channel_id_child_index: AtomicUsize::new(0),
581 Err(_) => panic!("Your rng is busted"),
586 impl KeysInterface for KeysManager {
587 type ChanKeySigner = InMemoryChannelKeys;
589 fn get_node_secret(&self) -> SecretKey {
590 self.node_secret.clone()
593 fn get_destination_script(&self) -> Script {
594 self.destination_script.clone()
597 fn get_shutdown_pubkey(&self) -> PublicKey {
598 self.shutdown_pubkey.clone()
601 fn get_channel_keys(&self, _inbound: bool, channel_value_satoshis: u64) -> InMemoryChannelKeys {
602 // We only seriously intend to rely on the channel_master_key for true secure
603 // entropy, everything else just ensures uniqueness. We rely on the unique_start (ie
604 // starting_time provided in the constructor) to be unique.
605 let mut sha = self.unique_start.clone();
607 let child_ix = self.channel_child_index.fetch_add(1, Ordering::AcqRel);
608 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");
609 sha.input(&child_privkey.private_key.key[..]);
611 let seed = Sha256::from_engine(sha).into_inner();
613 let commitment_seed = {
614 let mut sha = Sha256::engine();
616 sha.input(&b"commitment seed"[..]);
617 Sha256::from_engine(sha).into_inner()
619 macro_rules! key_step {
620 ($info: expr, $prev_key: expr) => {{
621 let mut sha = Sha256::engine();
623 sha.input(&$prev_key[..]);
624 sha.input(&$info[..]);
625 SecretKey::from_slice(&Sha256::from_engine(sha).into_inner()).expect("SHA-256 is busted")
628 let funding_key = key_step!(b"funding key", commitment_seed);
629 let revocation_base_key = key_step!(b"revocation base key", funding_key);
630 let payment_key = key_step!(b"payment key", revocation_base_key);
631 let delayed_payment_base_key = key_step!(b"delayed payment base key", payment_key);
632 let htlc_base_key = key_step!(b"HTLC base key", delayed_payment_base_key);
634 InMemoryChannelKeys::new(
639 delayed_payment_base_key,
642 channel_value_satoshis
646 fn get_onion_rand(&self) -> (SecretKey, [u8; 32]) {
647 let mut sha = self.unique_start.clone();
649 let child_ix = self.session_child_index.fetch_add(1, Ordering::AcqRel);
650 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");
651 sha.input(&child_privkey.private_key.key[..]);
653 let mut rng_seed = sha.clone();
654 // Not exactly the most ideal construction, but the second value will get fed into
655 // ChaCha so it is another step harder to break.
656 rng_seed.input(b"RNG Seed Salt");
657 sha.input(b"Session Key Salt");
658 (SecretKey::from_slice(&Sha256::from_engine(sha).into_inner()).expect("Your RNG is busted"),
659 Sha256::from_engine(rng_seed).into_inner())
662 fn get_channel_id(&self) -> [u8; 32] {
663 let mut sha = self.unique_start.clone();
665 let child_ix = self.channel_id_child_index.fetch_add(1, Ordering::AcqRel);
666 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");
667 sha.input(&child_privkey.private_key.key[..]);
669 Sha256::from_engine(sha).into_inner()