1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! keysinterface provides keys into rust-lightning and defines some useful enums which describe
11 //! spendable on-chain outputs which the user owns and is responsible for using just as any other
12 //! on-chain output which is theirs.
14 use bitcoin::blockdata::transaction::{Transaction, TxOut, SigHashType};
15 use bitcoin::blockdata::script::{Script, Builder};
16 use bitcoin::blockdata::opcodes;
17 use bitcoin::network::constants::Network;
18 use bitcoin::util::bip32::{ExtendedPrivKey, ExtendedPubKey, ChildNumber};
19 use bitcoin::util::bip143;
21 use bitcoin::hashes::{Hash, HashEngine};
22 use bitcoin::hashes::sha256::HashEngine as Sha256State;
23 use bitcoin::hashes::sha256::Hash as Sha256;
24 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
25 use bitcoin::hash_types::WPubkeyHash;
27 use bitcoin::secp256k1::key::{SecretKey, PublicKey};
28 use bitcoin::secp256k1::{Secp256k1, Signature, Signing};
29 use bitcoin::secp256k1;
32 use util::ser::{Writeable, Writer, Readable};
34 use chain::transaction::OutPoint;
36 use ln::chan_utils::{HTLCOutputInCommitment, make_funding_redeemscript, ChannelPublicKeys, HolderCommitmentTransaction, ChannelTransactionParameters, CommitmentTransaction};
37 use ln::msgs::UnsignedChannelAnnouncement;
39 use std::sync::atomic::{AtomicUsize, Ordering};
41 use ln::msgs::DecodeError;
43 /// When on-chain outputs are created by rust-lightning (which our counterparty is not able to
44 /// claim at any point in the future) an event is generated which you must track and be able to
45 /// spend on-chain. The information needed to do this is provided in this enum, including the
46 /// outpoint describing which txid and output index is available, the full output which exists at
47 /// that txid/index, and any keys or other information required to sign.
48 #[derive(Clone, Debug, PartialEq)]
49 pub enum SpendableOutputDescriptor {
50 /// An output to a script which was provided via KeysInterface, thus you should already know
51 /// how to spend it. No keys are provided as rust-lightning was never given any keys - only the
52 /// script_pubkey as it appears in the output.
53 /// These may include outputs from a transaction punishing our counterparty or claiming an HTLC
54 /// on-chain using the payment preimage or after it has timed out.
56 /// The outpoint which is spendable
58 /// The output which is referenced by the given outpoint.
61 /// An output to a P2WSH script which can be spent with a single signature after a CSV delay.
63 /// The witness in the spending input should be:
64 /// <BIP 143 signature> <empty vector> (MINIMALIF standard rule) <provided witnessScript>
66 /// Note that the nSequence field in the spending input must be set to to_self_delay
67 /// (which means the transaction is not broadcastable until at least to_self_delay
68 /// blocks after the outpoint confirms).
70 /// These are generally the result of a "revocable" output to us, spendable only by us unless
71 /// it is an output from an old state which we broadcast (which should never happen).
73 /// To derive the delayed_payment key which is used to sign for this input, you must pass the
74 /// holder delayed_payment_base_key (ie the private key which corresponds to the pubkey in
75 /// ChannelKeys::pubkeys().delayed_payment_basepoint) and the provided per_commitment_point to
76 /// chan_utils::derive_private_key. The public key can be generated without the secret key
77 /// using chan_utils::derive_public_key and only the delayed_payment_basepoint which appears in
78 /// ChannelKeys::pubkeys().
80 /// To derive the revocation_pubkey provided here (which is used in the witness
81 /// script generation), you must pass the counterparty revocation_basepoint (which appears in the
82 /// call to ChannelKeys::ready_channel) and the provided per_commitment point
83 /// to chan_utils::derive_public_revocation_key.
85 /// The witness script which is hashed and included in the output script_pubkey may be
86 /// regenerated by passing the revocation_pubkey (derived as above), our delayed_payment pubkey
87 /// (derived as above), and the to_self_delay contained here to
88 /// chan_utils::get_revokeable_redeemscript.
90 // TODO: we need to expose utility methods in KeyManager to do all the relevant derivation.
92 /// The outpoint which is spendable
94 /// Per commitment point to derive delayed_payment_key by key holder
95 per_commitment_point: PublicKey,
96 /// The nSequence value which must be set in the spending input to satisfy the OP_CSV in
97 /// the witness_script.
99 /// The output which is referenced by the given outpoint
101 /// The channel keys state used to proceed to derivation of signing key. Must
102 /// be pass to KeysInterface::derive_channel_keys.
103 channel_keys_id: [u8; 32],
104 /// The revocation_pubkey used to derive witnessScript
105 revocation_pubkey: PublicKey
107 /// An output to a P2WPKH, spendable exclusively by our payment key (ie the private key which
108 /// corresponds to the public key in ChannelKeys::pubkeys().payment_point).
109 /// The witness in the spending input, is, thus, simply:
110 /// <BIP 143 signature> <payment key>
112 /// These are generally the result of our counterparty having broadcast the current state,
113 /// allowing us to claim the non-HTLC-encumbered outputs immediately.
114 StaticOutputCounterpartyPayment {
115 /// The outpoint which is spendable
117 /// The output which is reference by the given outpoint
119 /// The channel keys state used to proceed to derivation of signing key. Must
120 /// be pass to KeysInterface::derive_channel_keys.
121 channel_keys_id: [u8; 32],
125 impl Writeable for SpendableOutputDescriptor {
126 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
128 &SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output } => {
130 outpoint.write(writer)?;
131 output.write(writer)?;
133 &SpendableOutputDescriptor::DynamicOutputP2WSH { ref outpoint, ref per_commitment_point, ref to_self_delay, ref output, ref channel_keys_id, ref revocation_pubkey } => {
135 outpoint.write(writer)?;
136 per_commitment_point.write(writer)?;
137 to_self_delay.write(writer)?;
138 output.write(writer)?;
139 channel_keys_id.write(writer)?;
140 revocation_pubkey.write(writer)?;
142 &SpendableOutputDescriptor::StaticOutputCounterpartyPayment { ref outpoint, ref output, ref channel_keys_id } => {
144 outpoint.write(writer)?;
145 output.write(writer)?;
146 channel_keys_id.write(writer)?;
153 impl Readable for SpendableOutputDescriptor {
154 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
155 match Readable::read(reader)? {
156 0u8 => Ok(SpendableOutputDescriptor::StaticOutput {
157 outpoint: Readable::read(reader)?,
158 output: Readable::read(reader)?,
160 1u8 => Ok(SpendableOutputDescriptor::DynamicOutputP2WSH {
161 outpoint: Readable::read(reader)?,
162 per_commitment_point: Readable::read(reader)?,
163 to_self_delay: Readable::read(reader)?,
164 output: Readable::read(reader)?,
165 channel_keys_id: Readable::read(reader)?,
166 revocation_pubkey: Readable::read(reader)?,
168 2u8 => Ok(SpendableOutputDescriptor::StaticOutputCounterpartyPayment {
169 outpoint: Readable::read(reader)?,
170 output: Readable::read(reader)?,
171 channel_keys_id: Readable::read(reader)?,
173 _ => Err(DecodeError::InvalidValue),
178 /// Set of lightning keys needed to operate a channel as described in BOLT 3.
180 /// Signing services could be implemented on a hardware wallet. In this case,
181 /// the current ChannelKeys would be a front-end on top of a communication
182 /// channel connected to your secure device and lightning key material wouldn't
183 /// reside on a hot server. Nevertheless, a this deployment would still need
184 /// to trust the ChannelManager to avoid loss of funds as this latest component
185 /// could ask to sign commitment transaction with HTLCs paying to attacker pubkeys.
187 /// A more secure iteration would be to use hashlock (or payment points) to pair
188 /// invoice/incoming HTLCs with outgoing HTLCs to implement a no-trust-ChannelManager
189 /// at the price of more state and computation on the hardware wallet side. In the future,
190 /// we are looking forward to design such interface.
192 /// In any case, ChannelMonitor or fallback watchtowers are always going to be trusted
193 /// to act, as liveness and breach reply correctness are always going to be hard requirements
194 /// of LN security model, orthogonal of key management issues.
196 /// If you're implementing a custom signer, you almost certainly want to implement
197 /// Readable/Writable to serialize out a unique reference to this set of keys so
198 /// that you can serialize the full ChannelManager object.
200 // (TODO: We shouldn't require that, and should have an API to get them at deser time, due mostly
201 // to the possibility of reentrancy issues by calling the user's code during our deserialization
203 // TODO: We should remove Clone by instead requesting a new ChannelKeys copy when we create
204 // ChannelMonitors instead of expecting to clone the one out of the Channel into the monitors.
205 pub trait ChannelKeys : Send+Clone + Writeable {
206 /// Gets the per-commitment point for a specific commitment number
208 /// Note that the commitment number starts at (1 << 48) - 1 and counts backwards.
209 fn get_per_commitment_point<T: secp256k1::Signing + secp256k1::Verification>(&self, idx: u64, secp_ctx: &Secp256k1<T>) -> PublicKey;
210 /// Gets the commitment secret for a specific commitment number as part of the revocation process
212 /// An external signer implementation should error here if the commitment was already signed
213 /// and should refuse to sign it in the future.
215 /// May be called more than once for the same index.
217 /// Note that the commitment number starts at (1 << 48) - 1 and counts backwards.
218 /// TODO: return a Result so we can signal a validation error
219 fn release_commitment_secret(&self, idx: u64) -> [u8; 32];
220 /// Gets the holder's channel public keys and basepoints
221 fn pubkeys(&self) -> &ChannelPublicKeys;
222 /// Gets an arbitrary identifier describing the set of keys which are provided back to you in
223 /// some SpendableOutputDescriptor types. This should be sufficient to identify this
224 /// ChannelKeys object uniquely and lookup or re-derive its keys.
225 fn channel_keys_id(&self) -> [u8; 32];
227 /// Create a signature for a counterparty's commitment transaction and associated HTLC transactions.
229 /// Note that if signing fails or is rejected, the channel will be force-closed.
231 // TODO: Document the things someone using this interface should enforce before signing.
232 fn sign_counterparty_commitment<T: secp256k1::Signing + secp256k1::Verification>(&self, commitment_tx: &CommitmentTransaction, secp_ctx: &Secp256k1<T>) -> Result<(Signature, Vec<Signature>), ()>;
234 /// Create a signatures for a holder's commitment transaction and its claiming HTLC transactions.
235 /// This will only ever be called with a non-revoked commitment_tx. This will be called with the
236 /// latest commitment_tx when we initiate a force-close.
237 /// This will be called with the previous latest, just to get claiming HTLC signatures, if we are
238 /// reacting to a ChannelMonitor replica that decided to broadcast before it had been updated to
240 /// This may be called multiple times for the same transaction.
242 /// An external signer implementation should check that the commitment has not been revoked.
244 /// May return Err if key derivation fails. Callers, such as ChannelMonitor, will panic in such a case.
246 // TODO: Document the things someone using this interface should enforce before signing.
247 // TODO: Key derivation failure should panic rather than Err
248 fn sign_holder_commitment_and_htlcs<T: secp256k1::Signing + secp256k1::Verification>(&self, commitment_tx: &HolderCommitmentTransaction, secp_ctx: &Secp256k1<T>) -> Result<(Signature, Vec<Signature>), ()>;
250 /// Same as sign_holder_commitment, but exists only for tests to get access to holder commitment
251 /// transactions which will be broadcasted later, after the channel has moved on to a newer
252 /// state. Thus, needs its own method as sign_holder_commitment may enforce that we only ever
254 #[cfg(any(test,feature = "unsafe_revoked_tx_signing"))]
255 fn unsafe_sign_holder_commitment_and_htlcs<T: secp256k1::Signing + secp256k1::Verification>(&self, commitment_tx: &HolderCommitmentTransaction, secp_ctx: &Secp256k1<T>) -> Result<(Signature, Vec<Signature>), ()>;
257 /// Create a signature for the given input in a transaction spending an HTLC or commitment
258 /// transaction output when our counterparty broadcasts an old state.
260 /// A justice transaction may claim multiples outputs at the same time if timelocks are
261 /// similar, but only a signature for the input at index `input` should be signed for here.
262 /// It may be called multiples time for same output(s) if a fee-bump is needed with regards
263 /// to an upcoming timelock expiration.
265 /// Amount is value of the output spent by this input, committed to in the BIP 143 signature.
267 /// per_commitment_key is revocation secret which was provided by our counterparty when they
268 /// revoked the state which they eventually broadcast. It's not a _holder_ secret key and does
269 /// not allow the spending of any funds by itself (you need our holder revocation_secret to do
272 /// htlc holds HTLC elements (hash, timelock) if the output being spent is a HTLC output, thus
273 /// changing the format of the witness script (which is committed to in the BIP 143
275 fn sign_justice_transaction<T: secp256k1::Signing + secp256k1::Verification>(&self, justice_tx: &Transaction, input: usize, amount: u64, per_commitment_key: &SecretKey, htlc: &Option<HTLCOutputInCommitment>, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()>;
277 /// Create a signature for a claiming transaction for a HTLC output on a counterparty's commitment
278 /// transaction, either offered or received.
280 /// Such a transaction may claim multiples offered outputs at same time if we know the
281 /// preimage for each when we create it, but only the input at index `input` should be
282 /// signed for here. It may be called multiple times for same output(s) if a fee-bump is
283 /// needed with regards to an upcoming timelock expiration.
285 /// Witness_script is either a offered or received script as defined in BOLT3 for HTLC
288 /// Amount is value of the output spent by this input, committed to in the BIP 143 signature.
290 /// Per_commitment_point is the dynamic point corresponding to the channel state
291 /// detected onchain. It has been generated by our counterparty and is used to derive
292 /// channel state keys, which are then included in the witness script and committed to in the
293 /// BIP 143 signature.
294 fn sign_counterparty_htlc_transaction<T: secp256k1::Signing + secp256k1::Verification>(&self, htlc_tx: &Transaction, input: usize, amount: u64, per_commitment_point: &PublicKey, htlc: &HTLCOutputInCommitment, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()>;
296 /// Create a signature for a (proposed) closing transaction.
298 /// Note that, due to rounding, there may be one "missing" satoshi, and either party may have
299 /// chosen to forgo their output as dust.
300 fn sign_closing_transaction<T: secp256k1::Signing>(&self, closing_tx: &Transaction, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()>;
302 /// Signs a channel announcement message with our funding key, proving it comes from one
303 /// of the channel participants.
305 /// Note that if this fails or is rejected, the channel will not be publicly announced and
306 /// our counterparty may (though likely will not) close the channel on us for violating the
308 fn sign_channel_announcement<T: secp256k1::Signing>(&self, msg: &UnsignedChannelAnnouncement, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()>;
310 /// Set the counterparty static channel data, including basepoints,
311 /// counterparty_selected/holder_selected_contest_delay and funding outpoint.
312 /// This is done as soon as the funding outpoint is known. Since these are static channel data,
313 /// they MUST NOT be allowed to change to different values once set.
315 /// channel_parameters.is_populated() MUST be true.
317 /// We bind holder_selected_contest_delay late here for API convenience.
319 /// Will be called before any signatures are applied.
320 fn ready_channel(&mut self, channel_parameters: &ChannelTransactionParameters);
323 /// A trait to describe an object which can get user secrets and key material.
324 pub trait KeysInterface: Send + Sync {
325 /// A type which implements ChannelKeys which will be returned by get_channel_keys.
326 type ChanKeySigner : ChannelKeys;
328 /// Get node secret key (aka node_id or network_key)
329 fn get_node_secret(&self) -> SecretKey;
330 /// Get destination redeemScript to encumber static protocol exit points.
331 fn get_destination_script(&self) -> Script;
332 /// Get shutdown_pubkey to use as PublicKey at channel closure
333 fn get_shutdown_pubkey(&self) -> PublicKey;
334 /// Get a new set of ChannelKeys for per-channel secrets. These MUST be unique even if you
335 /// restarted with some stale data!
336 fn get_channel_keys(&self, inbound: bool, channel_value_satoshis: u64) -> Self::ChanKeySigner;
337 /// Gets a unique, cryptographically-secure, random 32 byte value. This is used for encrypting
338 /// onion packets and for temporary channel IDs. There is no requirement that these be
339 /// persisted anywhere, though they must be unique across restarts.
340 fn get_secure_random_bytes(&self) -> [u8; 32];
342 /// Reads a `ChanKeySigner` for this `KeysInterface` from the given input stream.
343 /// This is only called during deserialization of other objects which contain
344 /// `ChannelKeys`-implementing objects (ie `ChannelMonitor`s and `ChannelManager`s).
345 /// The bytes are exactly those which `<Self::ChanKeySigner as Writeable>::write()` writes, and
346 /// contain no versioning scheme. You may wish to include your own version prefix and ensure
347 /// you've read all of the provided bytes to ensure no corruption occurred.
348 fn read_chan_signer(&self, reader: &[u8]) -> Result<Self::ChanKeySigner, DecodeError>;
352 /// A simple implementation of ChannelKeys that just keeps the private keys in memory.
354 /// This implementation performs no policy checks and is insufficient by itself as
355 /// a secure external signer.
356 pub struct InMemoryChannelKeys {
357 /// Private key of anchor tx
358 pub funding_key: SecretKey,
359 /// Holder secret key for blinded revocation pubkey
360 pub revocation_base_key: SecretKey,
361 /// Holder secret key used for our balance in counterparty-broadcasted commitment transactions
362 pub payment_key: SecretKey,
363 /// Holder secret key used in HTLC tx
364 pub delayed_payment_base_key: SecretKey,
365 /// Holder htlc secret key used in commitment tx htlc outputs
366 pub htlc_base_key: SecretKey,
368 pub commitment_seed: [u8; 32],
369 /// Holder public keys and basepoints
370 pub(crate) holder_channel_pubkeys: ChannelPublicKeys,
371 /// Counterparty public keys and counterparty/holder selected_contest_delay, populated on channel acceptance
372 channel_parameters: Option<ChannelTransactionParameters>,
373 /// The total value of this channel
374 channel_value_satoshis: u64,
375 /// Key derivation parameters
376 channel_keys_id: [u8; 32],
379 impl InMemoryChannelKeys {
380 /// Create a new InMemoryChannelKeys
381 pub fn new<C: Signing>(
382 secp_ctx: &Secp256k1<C>,
383 funding_key: SecretKey,
384 revocation_base_key: SecretKey,
385 payment_key: SecretKey,
386 delayed_payment_base_key: SecretKey,
387 htlc_base_key: SecretKey,
388 commitment_seed: [u8; 32],
389 channel_value_satoshis: u64,
390 channel_keys_id: [u8; 32]) -> InMemoryChannelKeys {
391 let holder_channel_pubkeys =
392 InMemoryChannelKeys::make_holder_keys(secp_ctx, &funding_key, &revocation_base_key,
393 &payment_key, &delayed_payment_base_key,
395 InMemoryChannelKeys {
399 delayed_payment_base_key,
402 channel_value_satoshis,
403 holder_channel_pubkeys,
404 channel_parameters: None,
409 fn make_holder_keys<C: Signing>(secp_ctx: &Secp256k1<C>,
410 funding_key: &SecretKey,
411 revocation_base_key: &SecretKey,
412 payment_key: &SecretKey,
413 delayed_payment_base_key: &SecretKey,
414 htlc_base_key: &SecretKey) -> ChannelPublicKeys {
415 let from_secret = |s: &SecretKey| PublicKey::from_secret_key(secp_ctx, s);
417 funding_pubkey: from_secret(&funding_key),
418 revocation_basepoint: from_secret(&revocation_base_key),
419 payment_point: from_secret(&payment_key),
420 delayed_payment_basepoint: from_secret(&delayed_payment_base_key),
421 htlc_basepoint: from_secret(&htlc_base_key),
425 /// Counterparty pubkeys.
426 /// Will panic if ready_channel wasn't called.
427 pub fn counterparty_pubkeys(&self) -> &ChannelPublicKeys { &self.get_channel_parameters().counterparty_parameters.as_ref().unwrap().pubkeys }
429 /// The contest_delay value specified by our counterparty and applied on holder-broadcastable
430 /// transactions, ie the amount of time that we have to wait to recover our funds if we
431 /// broadcast a transaction.
432 /// Will panic if ready_channel wasn't called.
433 pub fn counterparty_selected_contest_delay(&self) -> u16 { self.get_channel_parameters().counterparty_parameters.as_ref().unwrap().selected_contest_delay }
435 /// The contest_delay value specified by us and applied on transactions broadcastable
436 /// by our counterparty, ie the amount of time that they have to wait to recover their funds
437 /// if they broadcast a transaction.
438 /// Will panic if ready_channel wasn't called.
439 pub fn holder_selected_contest_delay(&self) -> u16 { self.get_channel_parameters().holder_selected_contest_delay }
441 /// Whether the holder is the initiator
442 /// Will panic if ready_channel wasn't called.
443 pub fn is_outbound(&self) -> bool { self.get_channel_parameters().is_outbound_from_holder }
446 /// Will panic if ready_channel wasn't called.
447 pub fn funding_outpoint(&self) -> &OutPoint { self.get_channel_parameters().funding_outpoint.as_ref().unwrap() }
449 /// Obtain a ChannelTransactionParameters for this channel, to be used when verifying or
450 /// building transactions.
452 /// Will panic if ready_channel wasn't called.
453 pub fn get_channel_parameters(&self) -> &ChannelTransactionParameters {
454 self.channel_parameters.as_ref().unwrap()
458 impl ChannelKeys for InMemoryChannelKeys {
459 fn get_per_commitment_point<T: secp256k1::Signing + secp256k1::Verification>(&self, idx: u64, secp_ctx: &Secp256k1<T>) -> PublicKey {
460 let commitment_secret = SecretKey::from_slice(&chan_utils::build_commitment_secret(&self.commitment_seed, idx)).unwrap();
461 PublicKey::from_secret_key(secp_ctx, &commitment_secret)
464 fn release_commitment_secret(&self, idx: u64) -> [u8; 32] {
465 chan_utils::build_commitment_secret(&self.commitment_seed, idx)
468 fn pubkeys(&self) -> &ChannelPublicKeys { &self.holder_channel_pubkeys }
469 fn channel_keys_id(&self) -> [u8; 32] { self.channel_keys_id }
471 fn sign_counterparty_commitment<T: secp256k1::Signing + secp256k1::Verification>(&self, commitment_tx: &CommitmentTransaction, secp_ctx: &Secp256k1<T>) -> Result<(Signature, Vec<Signature>), ()> {
472 let trusted_tx = commitment_tx.trust();
473 let keys = trusted_tx.keys();
475 let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
476 let channel_funding_redeemscript = make_funding_redeemscript(&funding_pubkey, &self.counterparty_pubkeys().funding_pubkey);
478 let built_tx = trusted_tx.built_transaction();
479 let commitment_sig = built_tx.sign(&self.funding_key, &channel_funding_redeemscript, self.channel_value_satoshis, secp_ctx);
480 let commitment_txid = built_tx.txid;
482 let mut htlc_sigs = Vec::with_capacity(commitment_tx.htlcs().len());
483 for htlc in commitment_tx.htlcs() {
484 let htlc_tx = chan_utils::build_htlc_transaction(&commitment_txid, commitment_tx.feerate_per_kw(), self.holder_selected_contest_delay(), htlc, &keys.broadcaster_delayed_payment_key, &keys.revocation_key);
485 let htlc_redeemscript = chan_utils::get_htlc_redeemscript(&htlc, &keys);
486 let htlc_sighash = hash_to_message!(&bip143::SigHashCache::new(&htlc_tx).signature_hash(0, &htlc_redeemscript, htlc.amount_msat / 1000, SigHashType::All)[..]);
487 let holder_htlc_key = match chan_utils::derive_private_key(&secp_ctx, &keys.per_commitment_point, &self.htlc_base_key) {
489 Err(_) => return Err(()),
491 htlc_sigs.push(secp_ctx.sign(&htlc_sighash, &holder_htlc_key));
494 Ok((commitment_sig, htlc_sigs))
497 fn sign_holder_commitment_and_htlcs<T: secp256k1::Signing + secp256k1::Verification>(&self, commitment_tx: &HolderCommitmentTransaction, secp_ctx: &Secp256k1<T>) -> Result<(Signature, Vec<Signature>), ()> {
498 let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
499 let funding_redeemscript = make_funding_redeemscript(&funding_pubkey, &self.counterparty_pubkeys().funding_pubkey);
500 let trusted_tx = commitment_tx.trust();
501 let sig = trusted_tx.built_transaction().sign(&self.funding_key, &funding_redeemscript, self.channel_value_satoshis, secp_ctx);
502 let channel_parameters = self.get_channel_parameters();
503 let htlc_sigs = trusted_tx.get_htlc_sigs(&self.htlc_base_key, &channel_parameters.as_holder_broadcastable(), secp_ctx)?;
507 #[cfg(any(test,feature = "unsafe_revoked_tx_signing"))]
508 fn unsafe_sign_holder_commitment_and_htlcs<T: secp256k1::Signing + secp256k1::Verification>(&self, commitment_tx: &HolderCommitmentTransaction, secp_ctx: &Secp256k1<T>) -> Result<(Signature, Vec<Signature>), ()> {
509 let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
510 let funding_redeemscript = make_funding_redeemscript(&funding_pubkey, &self.counterparty_pubkeys().funding_pubkey);
511 let trusted_tx = commitment_tx.trust();
512 let sig = trusted_tx.built_transaction().sign(&self.funding_key, &funding_redeemscript, self.channel_value_satoshis, secp_ctx);
513 let channel_parameters = self.get_channel_parameters();
514 let htlc_sigs = trusted_tx.get_htlc_sigs(&self.htlc_base_key, &channel_parameters.as_holder_broadcastable(), secp_ctx)?;
518 fn sign_justice_transaction<T: secp256k1::Signing + secp256k1::Verification>(&self, justice_tx: &Transaction, input: usize, amount: u64, per_commitment_key: &SecretKey, htlc: &Option<HTLCOutputInCommitment>, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()> {
519 let revocation_key = match chan_utils::derive_private_revocation_key(&secp_ctx, &per_commitment_key, &self.revocation_base_key) {
520 Ok(revocation_key) => revocation_key,
521 Err(_) => return Err(())
523 let per_commitment_point = PublicKey::from_secret_key(secp_ctx, &per_commitment_key);
524 let revocation_pubkey = match chan_utils::derive_public_revocation_key(&secp_ctx, &per_commitment_point, &self.pubkeys().revocation_basepoint) {
525 Ok(revocation_pubkey) => revocation_pubkey,
526 Err(_) => return Err(())
528 let witness_script = if let &Some(ref htlc) = htlc {
529 let counterparty_htlcpubkey = match chan_utils::derive_public_key(&secp_ctx, &per_commitment_point, &self.counterparty_pubkeys().htlc_basepoint) {
530 Ok(counterparty_htlcpubkey) => counterparty_htlcpubkey,
531 Err(_) => return Err(())
533 let holder_htlcpubkey = match chan_utils::derive_public_key(&secp_ctx, &per_commitment_point, &self.pubkeys().htlc_basepoint) {
534 Ok(holder_htlcpubkey) => holder_htlcpubkey,
535 Err(_) => return Err(())
537 chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, &counterparty_htlcpubkey, &holder_htlcpubkey, &revocation_pubkey)
539 let counterparty_delayedpubkey = match chan_utils::derive_public_key(&secp_ctx, &per_commitment_point, &self.counterparty_pubkeys().delayed_payment_basepoint) {
540 Ok(counterparty_delayedpubkey) => counterparty_delayedpubkey,
541 Err(_) => return Err(())
543 chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.holder_selected_contest_delay(), &counterparty_delayedpubkey)
545 let mut sighash_parts = bip143::SigHashCache::new(justice_tx);
546 let sighash = hash_to_message!(&sighash_parts.signature_hash(input, &witness_script, amount, SigHashType::All)[..]);
547 return Ok(secp_ctx.sign(&sighash, &revocation_key))
550 fn sign_counterparty_htlc_transaction<T: secp256k1::Signing + secp256k1::Verification>(&self, htlc_tx: &Transaction, input: usize, amount: u64, per_commitment_point: &PublicKey, htlc: &HTLCOutputInCommitment, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()> {
551 if let Ok(htlc_key) = chan_utils::derive_private_key(&secp_ctx, &per_commitment_point, &self.htlc_base_key) {
552 let witness_script = if let Ok(revocation_pubkey) = chan_utils::derive_public_revocation_key(&secp_ctx, &per_commitment_point, &self.pubkeys().revocation_basepoint) {
553 if let Ok(counterparty_htlcpubkey) = chan_utils::derive_public_key(&secp_ctx, &per_commitment_point, &self.counterparty_pubkeys().htlc_basepoint) {
554 if let Ok(htlcpubkey) = chan_utils::derive_public_key(&secp_ctx, &per_commitment_point, &self.pubkeys().htlc_basepoint) {
555 chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, &counterparty_htlcpubkey, &htlcpubkey, &revocation_pubkey)
556 } else { return Err(()) }
557 } else { return Err(()) }
558 } else { return Err(()) };
559 let mut sighash_parts = bip143::SigHashCache::new(htlc_tx);
560 let sighash = hash_to_message!(&sighash_parts.signature_hash(input, &witness_script, amount, SigHashType::All)[..]);
561 return Ok(secp_ctx.sign(&sighash, &htlc_key))
566 fn sign_closing_transaction<T: secp256k1::Signing>(&self, closing_tx: &Transaction, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()> {
567 if closing_tx.input.len() != 1 { return Err(()); }
568 if closing_tx.input[0].witness.len() != 0 { return Err(()); }
569 if closing_tx.output.len() > 2 { return Err(()); }
571 let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
572 let channel_funding_redeemscript = make_funding_redeemscript(&funding_pubkey, &self.counterparty_pubkeys().funding_pubkey);
574 let sighash = hash_to_message!(&bip143::SigHashCache::new(closing_tx)
575 .signature_hash(0, &channel_funding_redeemscript, self.channel_value_satoshis, SigHashType::All)[..]);
576 Ok(secp_ctx.sign(&sighash, &self.funding_key))
579 fn sign_channel_announcement<T: secp256k1::Signing>(&self, msg: &UnsignedChannelAnnouncement, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()> {
580 let msghash = hash_to_message!(&Sha256dHash::hash(&msg.encode()[..])[..]);
581 Ok(secp_ctx.sign(&msghash, &self.funding_key))
584 fn ready_channel(&mut self, channel_parameters: &ChannelTransactionParameters) {
585 assert!(self.channel_parameters.is_none(), "Acceptance already noted");
586 assert!(channel_parameters.is_populated(), "Channel parameters must be fully populated");
587 self.channel_parameters = Some(channel_parameters.clone());
591 impl Writeable for InMemoryChannelKeys {
592 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), Error> {
593 self.funding_key.write(writer)?;
594 self.revocation_base_key.write(writer)?;
595 self.payment_key.write(writer)?;
596 self.delayed_payment_base_key.write(writer)?;
597 self.htlc_base_key.write(writer)?;
598 self.commitment_seed.write(writer)?;
599 self.channel_parameters.write(writer)?;
600 self.channel_value_satoshis.write(writer)?;
601 self.channel_keys_id.write(writer)?;
607 impl Readable for InMemoryChannelKeys {
608 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
609 let funding_key = Readable::read(reader)?;
610 let revocation_base_key = Readable::read(reader)?;
611 let payment_key = Readable::read(reader)?;
612 let delayed_payment_base_key = Readable::read(reader)?;
613 let htlc_base_key = Readable::read(reader)?;
614 let commitment_seed = Readable::read(reader)?;
615 let counterparty_channel_data = Readable::read(reader)?;
616 let channel_value_satoshis = Readable::read(reader)?;
617 let secp_ctx = Secp256k1::signing_only();
618 let holder_channel_pubkeys =
619 InMemoryChannelKeys::make_holder_keys(&secp_ctx, &funding_key, &revocation_base_key,
620 &payment_key, &delayed_payment_base_key,
622 let keys_id = Readable::read(reader)?;
624 Ok(InMemoryChannelKeys {
628 delayed_payment_base_key,
631 channel_value_satoshis,
632 holder_channel_pubkeys,
633 channel_parameters: counterparty_channel_data,
634 channel_keys_id: keys_id,
639 /// Simple KeysInterface implementor that takes a 32-byte seed for use as a BIP 32 extended key
640 /// and derives keys from that.
642 /// Your node_id is seed/0'
643 /// ChannelMonitor closes may use seed/1'
644 /// Cooperative closes may use seed/2'
645 /// The two close keys may be needed to claim on-chain funds!
646 pub struct KeysManager {
647 secp_ctx: Secp256k1<secp256k1::SignOnly>,
648 node_secret: SecretKey,
649 destination_script: Script,
650 shutdown_pubkey: PublicKey,
651 channel_master_key: ExtendedPrivKey,
652 channel_child_index: AtomicUsize,
653 rand_bytes_master_key: ExtendedPrivKey,
654 rand_bytes_child_index: AtomicUsize,
657 starting_time_secs: u64,
658 starting_time_nanos: u32,
662 /// Constructs a KeysManager from a 32-byte seed. If the seed is in some way biased (eg your
663 /// CSRNG is busted) this may panic (but more importantly, you will possibly lose funds).
664 /// starting_time isn't strictly required to actually be a time, but it must absolutely,
665 /// without a doubt, be unique to this instance. ie if you start multiple times with the same
666 /// seed, starting_time must be unique to each run. Thus, the easiest way to achieve this is to
667 /// simply use the current time (with very high precision).
669 /// The seed MUST be backed up safely prior to use so that the keys can be re-created, however,
670 /// obviously, starting_time should be unique every time you reload the library - it is only
671 /// used to generate new ephemeral key data (which will be stored by the individual channel if
674 /// Note that the seed is required to recover certain on-chain funds independent of
675 /// ChannelMonitor data, though a current copy of ChannelMonitor data is also required for any
676 /// channel, and some on-chain during-closing funds.
678 /// Note that until the 0.1 release there is no guarantee of backward compatibility between
679 /// versions. Once the library is more fully supported, the docs will be updated to include a
680 /// detailed description of the guarantee.
681 pub fn new(seed: &[u8; 32], network: Network, starting_time_secs: u64, starting_time_nanos: u32) -> Self {
682 let secp_ctx = Secp256k1::signing_only();
683 match ExtendedPrivKey::new_master(network.clone(), seed) {
685 let node_secret = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(0).unwrap()).expect("Your RNG is busted").private_key.key;
686 let destination_script = match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(1).unwrap()) {
687 Ok(destination_key) => {
688 let wpubkey_hash = WPubkeyHash::hash(&ExtendedPubKey::from_private(&secp_ctx, &destination_key).public_key.to_bytes());
689 Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0)
690 .push_slice(&wpubkey_hash.into_inner())
693 Err(_) => panic!("Your RNG is busted"),
695 let shutdown_pubkey = match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(2).unwrap()) {
696 Ok(shutdown_key) => ExtendedPubKey::from_private(&secp_ctx, &shutdown_key).public_key.key,
697 Err(_) => panic!("Your RNG is busted"),
699 let channel_master_key = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(3).unwrap()).expect("Your RNG is busted");
700 let rand_bytes_master_key = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(4).unwrap()).expect("Your RNG is busted");
708 channel_child_index: AtomicUsize::new(0),
709 rand_bytes_master_key,
710 rand_bytes_child_index: AtomicUsize::new(0),
717 Err(_) => panic!("Your rng is busted"),
720 fn derive_unique_start(&self) -> Sha256State {
721 let mut unique_start = Sha256::engine();
722 unique_start.input(&byte_utils::be64_to_array(self.starting_time_secs));
723 unique_start.input(&byte_utils::be32_to_array(self.starting_time_nanos));
724 unique_start.input(&self.seed);
727 /// Derive an old set of ChannelKeys for per-channel secrets based on a key derivation
729 /// Key derivation parameters are accessible through a per-channel secrets
730 /// ChannelKeys::channel_keys_id and is provided inside DynamicOuputP2WSH in case of
731 /// onchain output detection for which a corresponding delayed_payment_key must be derived.
732 pub fn derive_channel_keys(&self, channel_value_satoshis: u64, params: &[u8; 32]) -> InMemoryChannelKeys {
733 let chan_id = byte_utils::slice_to_be64(¶ms[0..8]);
734 assert!(chan_id <= std::u32::MAX as u64); // Otherwise the params field wasn't created by us
735 let mut unique_start = Sha256::engine();
736 unique_start.input(params);
737 unique_start.input(&self.seed);
739 // We only seriously intend to rely on the channel_master_key for true secure
740 // entropy, everything else just ensures uniqueness. We rely on the unique_start (ie
741 // starting_time provided in the constructor) to be unique.
742 let child_privkey = self.channel_master_key.ckd_priv(&self.secp_ctx, ChildNumber::from_hardened_idx(chan_id as u32).expect("key space exhausted")).expect("Your RNG is busted");
743 unique_start.input(&child_privkey.private_key.key[..]);
745 let seed = Sha256::from_engine(unique_start).into_inner();
747 let commitment_seed = {
748 let mut sha = Sha256::engine();
750 sha.input(&b"commitment seed"[..]);
751 Sha256::from_engine(sha).into_inner()
753 macro_rules! key_step {
754 ($info: expr, $prev_key: expr) => {{
755 let mut sha = Sha256::engine();
757 sha.input(&$prev_key[..]);
758 sha.input(&$info[..]);
759 SecretKey::from_slice(&Sha256::from_engine(sha).into_inner()).expect("SHA-256 is busted")
762 let funding_key = key_step!(b"funding key", commitment_seed);
763 let revocation_base_key = key_step!(b"revocation base key", funding_key);
764 let payment_key = key_step!(b"payment key", revocation_base_key);
765 let delayed_payment_base_key = key_step!(b"delayed payment base key", payment_key);
766 let htlc_base_key = key_step!(b"HTLC base key", delayed_payment_base_key);
768 InMemoryChannelKeys::new(
773 delayed_payment_base_key,
776 channel_value_satoshis,
782 impl KeysInterface for KeysManager {
783 type ChanKeySigner = InMemoryChannelKeys;
785 fn get_node_secret(&self) -> SecretKey {
786 self.node_secret.clone()
789 fn get_destination_script(&self) -> Script {
790 self.destination_script.clone()
793 fn get_shutdown_pubkey(&self) -> PublicKey {
794 self.shutdown_pubkey.clone()
797 fn get_channel_keys(&self, _inbound: bool, channel_value_satoshis: u64) -> Self::ChanKeySigner {
798 let child_ix = self.channel_child_index.fetch_add(1, Ordering::AcqRel);
799 assert!(child_ix <= std::u32::MAX as usize);
800 let mut id = [0; 32];
801 id[0..8].copy_from_slice(&byte_utils::be64_to_array(child_ix as u64));
802 id[8..16].copy_from_slice(&byte_utils::be64_to_array(self.starting_time_nanos as u64));
803 id[16..24].copy_from_slice(&byte_utils::be64_to_array(self.starting_time_secs));
804 self.derive_channel_keys(channel_value_satoshis, &id)
807 fn get_secure_random_bytes(&self) -> [u8; 32] {
808 let mut sha = self.derive_unique_start();
810 let child_ix = self.rand_bytes_child_index.fetch_add(1, Ordering::AcqRel);
811 let child_privkey = self.rand_bytes_master_key.ckd_priv(&self.secp_ctx, ChildNumber::from_hardened_idx(child_ix as u32).expect("key space exhausted")).expect("Your RNG is busted");
812 sha.input(&child_privkey.private_key.key[..]);
814 sha.input(b"Unique Secure Random Bytes Salt");
815 Sha256::from_engine(sha).into_inner()
818 fn read_chan_signer(&self, reader: &[u8]) -> Result<Self::ChanKeySigner, DecodeError> {
819 InMemoryChannelKeys::read(&mut std::io::Cursor::new(reader))