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.
53 /// The witness in the spending input should be:
54 /// <BIP 143 signature> <empty vector> (MINIMALIF standard rule) <provided witnessScript>
56 /// Note that the nSequence field in the spending input must be set to to_self_delay
57 /// (which means the transaction is not broadcastable until at least to_self_delay
58 /// blocks after the outpoint confirms).
60 /// These are generally the result of a "revocable" output to us, spendable only by us unless
61 /// it is an output from an old state which we broadcast (which should never happen).
63 /// To derive the delayed_payment key which is used to sign for this input, you must pass the
64 /// local delayed_payment_base_key (ie the private key which corresponds to the pubkey in
65 /// ChannelKeys::pubkeys().delayed_payment_basepoint) and the provided per_commitment_point to
66 /// chan_utils::derive_private_key. The public key can be generated without the secret key
67 /// using chan_utils::derive_public_key and only the delayed_payment_basepoint which appears in
68 /// ChannelKeys::pubkeys().
70 /// To derive the remote_revocation_pubkey provided here (which is used in the witness
71 /// script generation), you must pass the remote revocation_basepoint (which appears in the
72 /// call to ChannelKeys::on_accept) and the provided per_commitment point
73 /// to chan_utils::derive_public_revocation_key.
75 /// The witness script which is hashed and included in the output script_pubkey may be
76 /// regenerated by passing the revocation_pubkey (derived as above), our delayed_payment pubkey
77 /// (derived as above), and the to_self_delay contained here to
78 /// chan_utils::get_revokeable_redeemscript.
80 // TODO: we need to expose utility methods in KeyManager to do all the relevant derivation.
82 /// The outpoint which is spendable
84 /// Per commitment point to derive delayed_payment_key by key holder
85 per_commitment_point: PublicKey,
86 /// The nSequence value which must be set in the spending input to satisfy the OP_CSV in
87 /// the witness_script.
89 /// The output which is referenced by the given outpoint
91 /// The channel keys state used to proceed to derivation of signing key. Must
92 /// be pass to KeysInterface::derive_channel_keys.
93 key_derivation_params: (u64, u64),
94 /// The remote_revocation_pubkey used to derive witnessScript
95 remote_revocation_pubkey: PublicKey
97 /// An output to a P2WPKH, spendable exclusively by our payment key (ie the private key which
98 /// corresponds to the public key in ChannelKeys::pubkeys().payment_point).
99 /// The witness in the spending input, is, thus, simply:
100 /// <BIP 143 signature> <payment key>
102 /// These are generally the result of our counterparty having broadcast the current state,
103 /// allowing us to claim the non-HTLC-encumbered outputs immediately.
104 StaticOutputRemotePayment {
105 /// The outpoint which is spendable
107 /// The output which is reference by the given outpoint
109 /// The channel keys state used to proceed to derivation of signing key. Must
110 /// be pass to KeysInterface::derive_channel_keys.
111 key_derivation_params: (u64, u64),
115 impl Writeable for SpendableOutputDescriptor {
116 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
118 &SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output } => {
120 outpoint.write(writer)?;
121 output.write(writer)?;
123 &SpendableOutputDescriptor::DynamicOutputP2WSH { ref outpoint, ref per_commitment_point, ref to_self_delay, ref output, ref key_derivation_params, ref remote_revocation_pubkey } => {
125 outpoint.write(writer)?;
126 per_commitment_point.write(writer)?;
127 to_self_delay.write(writer)?;
128 output.write(writer)?;
129 key_derivation_params.0.write(writer)?;
130 key_derivation_params.1.write(writer)?;
131 remote_revocation_pubkey.write(writer)?;
133 &SpendableOutputDescriptor::StaticOutputRemotePayment { ref outpoint, ref output, ref key_derivation_params } => {
135 outpoint.write(writer)?;
136 output.write(writer)?;
137 key_derivation_params.0.write(writer)?;
138 key_derivation_params.1.write(writer)?;
145 impl Readable for SpendableOutputDescriptor {
146 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
147 match Readable::read(reader)? {
148 0u8 => Ok(SpendableOutputDescriptor::StaticOutput {
149 outpoint: Readable::read(reader)?,
150 output: Readable::read(reader)?,
152 1u8 => Ok(SpendableOutputDescriptor::DynamicOutputP2WSH {
153 outpoint: Readable::read(reader)?,
154 per_commitment_point: Readable::read(reader)?,
155 to_self_delay: Readable::read(reader)?,
156 output: Readable::read(reader)?,
157 key_derivation_params: (Readable::read(reader)?, Readable::read(reader)?),
158 remote_revocation_pubkey: Readable::read(reader)?,
160 2u8 => Ok(SpendableOutputDescriptor::StaticOutputRemotePayment {
161 outpoint: Readable::read(reader)?,
162 output: Readable::read(reader)?,
163 key_derivation_params: (Readable::read(reader)?, Readable::read(reader)?),
165 _ => Err(DecodeError::InvalidValue),
170 /// Set of lightning keys needed to operate a channel as described in BOLT 3.
172 /// Signing services could be implemented on a hardware wallet. In this case,
173 /// the current ChannelKeys would be a front-end on top of a communication
174 /// channel connected to your secure device and lightning key material wouldn't
175 /// reside on a hot server. Nevertheless, a this deployment would still need
176 /// to trust the ChannelManager to avoid loss of funds as this latest component
177 /// could ask to sign commitment transaction with HTLCs paying to attacker pubkeys.
179 /// A more secure iteration would be to use hashlock (or payment points) to pair
180 /// invoice/incoming HTLCs with outgoing HTLCs to implement a no-trust-ChannelManager
181 /// at the price of more state and computation on the hardware wallet side. In the future,
182 /// we are looking forward to design such interface.
184 /// In any case, ChannelMonitor or fallback watchtowers are always going to be trusted
185 /// to act, as liveness and breach reply correctness are always going to be hard requirements
186 /// of LN security model, orthogonal of key management issues.
188 /// If you're implementing a custom signer, you almost certainly want to implement
189 /// Readable/Writable to serialize out a unique reference to this set of keys so
190 /// that you can serialize the full ChannelManager object.
192 // (TODO: We shouldn't require that, and should have an API to get them at deser time, due mostly
193 // to the possibility of reentrancy issues by calling the user's code during our deserialization
195 // TODO: We should remove Clone by instead requesting a new ChannelKeys copy when we create
196 // ChannelMonitors instead of expecting to clone the one out of the Channel into the monitors.
197 pub trait ChannelKeys : Send+Clone {
198 /// Gets the per-commitment point for a specific commitment number
200 /// Note that the commitment number starts at (1 << 48) - 1 and counts backwards.
201 fn get_per_commitment_point<T: secp256k1::Signing + secp256k1::Verification>(&self, idx: u64, secp_ctx: &Secp256k1<T>) -> PublicKey;
202 /// Gets the commitment secret for a specific commitment number as part of the revocation process
204 /// An external signer implementation should error here if the commitment was already signed
205 /// and should refuse to sign it in the future.
207 /// May be called more than once for the same index.
209 /// Note that the commitment number starts at (1 << 48) - 1 and counts backwards.
210 /// TODO: return a Result so we can signal a validation error
211 fn release_commitment_secret(&self, idx: u64) -> [u8; 32];
212 /// Gets the local channel public keys and basepoints
213 fn pubkeys(&self) -> &ChannelPublicKeys;
214 /// Gets arbitrary identifiers describing the set of keys which are provided back to you in
215 /// some SpendableOutputDescriptor types. These should be sufficient to identify this
216 /// ChannelKeys object uniquely and lookup or re-derive its keys.
217 fn key_derivation_params(&self) -> (u64, u64);
219 /// Create a signature for a remote commitment transaction and associated HTLC transactions.
221 /// Note that if signing fails or is rejected, the channel will be force-closed.
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 // making the callee generate it via some util function we expose)!
226 fn sign_remote_commitment<T: secp256k1::Signing + secp256k1::Verification>(&self, feerate_per_kw: u32, commitment_tx: &Transaction, keys: &TxCreationKeys, htlcs: &[&HTLCOutputInCommitment], secp_ctx: &Secp256k1<T>) -> Result<(Signature, Vec<Signature>), ()>;
228 /// Create a signature for a local commitment transaction. This will only ever be called with
229 /// the same local_commitment_tx (or a copy thereof), though there are currently no guarantees
230 /// that it will not be called multiple times.
231 /// An external signer implementation should check that the commitment has not been revoked.
233 // TODO: Document the things someone using this interface should enforce before signing.
234 // TODO: Add more input vars to enable better checking (preferably removing commitment_tx and
235 fn sign_local_commitment<T: secp256k1::Signing + secp256k1::Verification>(&self, local_commitment_tx: &LocalCommitmentTransaction, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()>;
237 /// Same as sign_local_commitment, but exists only for tests to get access to local commitment
238 /// transactions which will be broadcasted later, after the channel has moved on to a newer
239 /// state. Thus, needs its own method as sign_local_commitment may enforce that we only ever
242 fn unsafe_sign_local_commitment<T: secp256k1::Signing + secp256k1::Verification>(&self, local_commitment_tx: &LocalCommitmentTransaction, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()>;
244 /// Create a signature for each HTLC transaction spending a local commitment transaction.
246 /// Unlike sign_local_commitment, this may be called multiple times with *different*
247 /// local_commitment_tx values. While this will never be called with a revoked
248 /// local_commitment_tx, it is possible that it is called with the second-latest
249 /// local_commitment_tx (only if we haven't yet revoked it) if some watchtower/secondary
250 /// ChannelMonitor decided to broadcast before it had been updated to the latest.
252 /// Either an Err should be returned, or a Vec with one entry for each HTLC which exists in
253 /// local_commitment_tx. For those HTLCs which have transaction_output_index set to None
254 /// (implying they were considered dust at the time the commitment transaction was negotiated),
255 /// a corresponding None should be included in the return value. All other positions in the
256 /// return value must contain a signature.
257 fn sign_local_commitment_htlc_transactions<T: secp256k1::Signing + secp256k1::Verification>(&self, local_commitment_tx: &LocalCommitmentTransaction, secp_ctx: &Secp256k1<T>) -> Result<Vec<Option<Signature>>, ()>;
259 /// Create a signature for the given input in a transaction spending an HTLC or commitment
260 /// transaction output when our counterparty broadcasts an old state.
262 /// A justice transaction may claim multiples outputs at the same time if timelocks are
263 /// similar, but only a signature for the input at index `input` should be signed for here.
264 /// It may be called multiples time for same output(s) if a fee-bump is needed with regards
265 /// to an upcoming timelock expiration.
267 /// Amount is value of the output spent by this input, committed to in the BIP 143 signature.
269 /// per_commitment_key is revocation secret which was provided by our counterparty when they
270 /// revoked the state which they eventually broadcast. It's not a _local_ secret key and does
271 /// not allow the spending of any funds by itself (you need our local revocation_secret to do
274 /// htlc holds HTLC elements (hash, timelock) if the output being spent is a HTLC output, thus
275 /// changing the format of the witness script (which is committed to in the BIP 143
277 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, ()>;
279 /// Create a signature for a claiming transaction for a HTLC output on a remote commitment
280 /// transaction, either offered or received.
282 /// Such a transaction may claim multiples offered outputs at same time if we know the
283 /// preimage for each when we create it, but only the input at index `input` should be
284 /// signed for here. It may be called multiple times for same output(s) if a fee-bump is
285 /// needed with regards to an upcoming timelock expiration.
287 /// Witness_script is either a offered or received script as defined in BOLT3 for HTLC
290 /// Amount is value of the output spent by this input, committed to in the BIP 143 signature.
292 /// Per_commitment_point is the dynamic point corresponding to the channel state
293 /// detected onchain. It has been generated by our counterparty and is used to derive
294 /// channel state keys, which are then included in the witness script and committed to in the
295 /// BIP 143 signature.
296 fn sign_remote_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, ()>;
298 /// Create a signature for a (proposed) closing transaction.
300 /// Note that, due to rounding, there may be one "missing" satoshi, and either party may have
301 /// chosen to forgo their output as dust.
302 fn sign_closing_transaction<T: secp256k1::Signing>(&self, closing_tx: &Transaction, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()>;
304 /// Signs a channel announcement message with our funding key, proving it comes from one
305 /// of the channel participants.
307 /// Note that if this fails or is rejected, the channel will not be publicly announced and
308 /// our counterparty may (though likely will not) close the channel on us for violating the
310 fn sign_channel_announcement<T: secp256k1::Signing>(&self, msg: &msgs::UnsignedChannelAnnouncement, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()>;
312 /// Set the remote channel basepoints and remote/local to_self_delay.
313 /// This is done immediately on incoming channels and as soon as the channel is accepted on outgoing channels.
315 /// We bind local_to_self_delay late here for API convenience.
317 /// Will be called before any signatures are applied.
318 fn on_accept(&mut self, channel_points: &ChannelPublicKeys, remote_to_self_delay: u16, local_to_self_delay: u16);
321 /// A trait to describe an object which can get user secrets and key material.
322 pub trait KeysInterface: Send + Sync {
323 /// A type which implements ChannelKeys which will be returned by get_channel_keys.
324 type ChanKeySigner : ChannelKeys;
326 /// Get node secret key (aka node_id or network_key)
327 fn get_node_secret(&self) -> SecretKey;
328 /// Get destination redeemScript to encumber static protocol exit points.
329 fn get_destination_script(&self) -> Script;
330 /// Get shutdown_pubkey to use as PublicKey at channel closure
331 fn get_shutdown_pubkey(&self) -> PublicKey;
332 /// Get a new set of ChannelKeys for per-channel secrets. These MUST be unique even if you
333 /// restarted with some stale data!
334 fn get_channel_keys(&self, inbound: bool, channel_value_satoshis: u64) -> Self::ChanKeySigner;
335 /// Get a secret and PRNG seed for constructing an onion packet
336 fn get_onion_rand(&self) -> (SecretKey, [u8; 32]);
337 /// Get a unique temporary channel id. Channels will be referred to by this until the funding
338 /// transaction is created, at which point they will use the outpoint in the funding
340 fn get_channel_id(&self) -> [u8; 32];
344 /// Holds late-bound channel data.
345 /// This data is available after the channel is known to be accepted, either
346 /// when receiving an open_channel for an inbound channel or when
347 /// receiving accept_channel for an outbound channel.
348 struct AcceptedChannelData {
349 /// Remote public keys and base points
350 remote_channel_pubkeys: ChannelPublicKeys,
351 /// The to_self_delay value specified by our counterparty and applied on locally-broadcastable
352 /// transactions, ie the amount of time that we have to wait to recover our funds if we
353 /// broadcast a transaction. You'll likely want to pass this to the
354 /// ln::chan_utils::build*_transaction functions when signing local transactions.
355 remote_to_self_delay: u16,
356 /// The to_self_delay value specified by us and applied on transactions broadcastable
357 /// by our counterparty, ie the amount of time that they have to wait to recover their funds
358 /// if they broadcast a transaction.
359 local_to_self_delay: u16,
363 /// A simple implementation of ChannelKeys that just keeps the private keys in memory.
364 pub struct InMemoryChannelKeys {
365 /// Private key of anchor tx
366 pub funding_key: SecretKey,
367 /// Local secret key for blinded revocation pubkey
368 pub revocation_base_key: SecretKey,
369 /// Local secret key used for our balance in remote-broadcasted commitment transactions
370 pub payment_key: SecretKey,
371 /// Local secret key used in HTLC tx
372 pub delayed_payment_base_key: SecretKey,
373 /// Local htlc secret key used in commitment tx htlc outputs
374 pub htlc_base_key: SecretKey,
376 pub commitment_seed: [u8; 32],
377 /// Local public keys and basepoints
378 pub(crate) local_channel_pubkeys: ChannelPublicKeys,
379 /// Remote public keys and remote/local to_self_delay, populated on channel acceptance
380 accepted_channel_data: Option<AcceptedChannelData>,
381 /// The total value of this channel
382 channel_value_satoshis: u64,
383 /// Key derivation parameters
384 key_derivation_params: (u64, u64),
387 impl InMemoryChannelKeys {
388 /// Create a new InMemoryChannelKeys
389 pub fn new<C: Signing>(
390 secp_ctx: &Secp256k1<C>,
391 funding_key: SecretKey,
392 revocation_base_key: SecretKey,
393 payment_key: SecretKey,
394 delayed_payment_base_key: SecretKey,
395 htlc_base_key: SecretKey,
396 commitment_seed: [u8; 32],
397 channel_value_satoshis: u64,
398 key_derivation_params: (u64, u64)) -> InMemoryChannelKeys {
399 let local_channel_pubkeys =
400 InMemoryChannelKeys::make_local_keys(secp_ctx, &funding_key, &revocation_base_key,
401 &payment_key, &delayed_payment_base_key,
403 InMemoryChannelKeys {
407 delayed_payment_base_key,
410 channel_value_satoshis,
411 local_channel_pubkeys,
412 accepted_channel_data: None,
413 key_derivation_params,
417 fn make_local_keys<C: Signing>(secp_ctx: &Secp256k1<C>,
418 funding_key: &SecretKey,
419 revocation_base_key: &SecretKey,
420 payment_key: &SecretKey,
421 delayed_payment_base_key: &SecretKey,
422 htlc_base_key: &SecretKey) -> ChannelPublicKeys {
423 let from_secret = |s: &SecretKey| PublicKey::from_secret_key(secp_ctx, s);
425 funding_pubkey: from_secret(&funding_key),
426 revocation_basepoint: from_secret(&revocation_base_key),
427 payment_point: from_secret(&payment_key),
428 delayed_payment_basepoint: from_secret(&delayed_payment_base_key),
429 htlc_basepoint: from_secret(&htlc_base_key),
434 /// Will panic if on_accept wasn't called.
435 pub fn remote_pubkeys(&self) -> &ChannelPublicKeys { &self.accepted_channel_data.as_ref().unwrap().remote_channel_pubkeys }
437 /// The to_self_delay value specified by our counterparty and applied on locally-broadcastable
438 /// transactions, ie the amount of time that we have to wait to recover our funds if we
439 /// broadcast a transaction. You'll likely want to pass this to the
440 /// ln::chan_utils::build*_transaction functions when signing local transactions.
441 /// Will panic if on_accept wasn't called.
442 pub fn remote_to_self_delay(&self) -> u16 { self.accepted_channel_data.as_ref().unwrap().remote_to_self_delay }
444 /// The to_self_delay value specified by us and applied on transactions broadcastable
445 /// by our counterparty, ie the amount of time that they have to wait to recover their funds
446 /// if they broadcast a transaction.
447 /// Will panic if on_accept wasn't called.
448 pub fn local_to_self_delay(&self) -> u16 { self.accepted_channel_data.as_ref().unwrap().local_to_self_delay }
451 impl ChannelKeys for InMemoryChannelKeys {
452 fn get_per_commitment_point<T: secp256k1::Signing + secp256k1::Verification>(&self, idx: u64, secp_ctx: &Secp256k1<T>) -> PublicKey {
453 let commitment_secret = SecretKey::from_slice(&chan_utils::build_commitment_secret(&self.commitment_seed, idx)).unwrap();
454 PublicKey::from_secret_key(secp_ctx, &commitment_secret)
457 fn release_commitment_secret(&self, idx: u64) -> [u8; 32] {
458 chan_utils::build_commitment_secret(&self.commitment_seed, idx)
461 fn pubkeys(&self) -> &ChannelPublicKeys { &self.local_channel_pubkeys }
462 fn key_derivation_params(&self) -> (u64, u64) { self.key_derivation_params }
464 fn sign_remote_commitment<T: secp256k1::Signing + secp256k1::Verification>(&self, feerate_per_kw: u32, commitment_tx: &Transaction, keys: &TxCreationKeys, htlcs: &[&HTLCOutputInCommitment], secp_ctx: &Secp256k1<T>) -> Result<(Signature, Vec<Signature>), ()> {
465 if commitment_tx.input.len() != 1 { return Err(()); }
467 let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
468 let accepted_data = self.accepted_channel_data.as_ref().expect("must accept before signing");
469 let channel_funding_redeemscript = make_funding_redeemscript(&funding_pubkey, &accepted_data.remote_channel_pubkeys.funding_pubkey);
471 let commitment_sighash = hash_to_message!(&bip143::SighashComponents::new(&commitment_tx).sighash_all(&commitment_tx.input[0], &channel_funding_redeemscript, self.channel_value_satoshis)[..]);
472 let commitment_sig = secp_ctx.sign(&commitment_sighash, &self.funding_key);
474 let commitment_txid = commitment_tx.txid();
476 let mut htlc_sigs = Vec::with_capacity(htlcs.len());
477 for ref htlc in htlcs {
478 if let Some(_) = htlc.transaction_output_index {
479 let htlc_tx = chan_utils::build_htlc_transaction(&commitment_txid, feerate_per_kw, accepted_data.local_to_self_delay, htlc, &keys.a_delayed_payment_key, &keys.revocation_key);
480 let htlc_redeemscript = chan_utils::get_htlc_redeemscript(&htlc, &keys);
481 let htlc_sighash = hash_to_message!(&bip143::SighashComponents::new(&htlc_tx).sighash_all(&htlc_tx.input[0], &htlc_redeemscript, htlc.amount_msat / 1000)[..]);
482 let our_htlc_key = match chan_utils::derive_private_key(&secp_ctx, &keys.per_commitment_point, &self.htlc_base_key) {
484 Err(_) => return Err(()),
486 htlc_sigs.push(secp_ctx.sign(&htlc_sighash, &our_htlc_key));
490 Ok((commitment_sig, htlc_sigs))
493 fn sign_local_commitment<T: secp256k1::Signing + secp256k1::Verification>(&self, local_commitment_tx: &LocalCommitmentTransaction, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()> {
494 let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
495 let remote_channel_data = self.accepted_channel_data.as_ref().expect("must accept before signing");
496 let channel_funding_redeemscript = make_funding_redeemscript(&funding_pubkey, &remote_channel_data.remote_channel_pubkeys.funding_pubkey);
498 Ok(local_commitment_tx.get_local_sig(&self.funding_key, &channel_funding_redeemscript, self.channel_value_satoshis, secp_ctx))
502 fn unsafe_sign_local_commitment<T: secp256k1::Signing + secp256k1::Verification>(&self, local_commitment_tx: &LocalCommitmentTransaction, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()> {
503 let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
504 let remote_channel_pubkeys = &self.accepted_channel_data.as_ref().expect("must accept before signing").remote_channel_pubkeys;
505 let channel_funding_redeemscript = make_funding_redeemscript(&funding_pubkey, &remote_channel_pubkeys.funding_pubkey);
507 Ok(local_commitment_tx.get_local_sig(&self.funding_key, &channel_funding_redeemscript, self.channel_value_satoshis, secp_ctx))
510 fn sign_local_commitment_htlc_transactions<T: secp256k1::Signing + secp256k1::Verification>(&self, local_commitment_tx: &LocalCommitmentTransaction, secp_ctx: &Secp256k1<T>) -> Result<Vec<Option<Signature>>, ()> {
511 let local_csv = self.accepted_channel_data.as_ref().unwrap().remote_to_self_delay;
512 local_commitment_tx.get_htlc_sigs(&self.htlc_base_key, local_csv, secp_ctx)
515 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, ()> {
516 let revocation_key = match chan_utils::derive_private_revocation_key(&secp_ctx, &per_commitment_key, &self.revocation_base_key) {
517 Ok(revocation_key) => revocation_key,
518 Err(_) => return Err(())
520 let per_commitment_point = PublicKey::from_secret_key(secp_ctx, &per_commitment_key);
521 let revocation_pubkey = match chan_utils::derive_public_revocation_key(&secp_ctx, &per_commitment_point, &self.pubkeys().revocation_basepoint) {
522 Ok(revocation_pubkey) => revocation_pubkey,
523 Err(_) => return Err(())
525 let witness_script = if let &Some(ref htlc) = htlc {
526 let remote_htlcpubkey = match chan_utils::derive_public_key(&secp_ctx, &per_commitment_point, &self.remote_pubkeys().htlc_basepoint) {
527 Ok(remote_htlcpubkey) => remote_htlcpubkey,
528 Err(_) => return Err(())
530 let local_htlcpubkey = match chan_utils::derive_public_key(&secp_ctx, &per_commitment_point, &self.pubkeys().htlc_basepoint) {
531 Ok(local_htlcpubkey) => local_htlcpubkey,
532 Err(_) => return Err(())
534 chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, &remote_htlcpubkey, &local_htlcpubkey, &revocation_pubkey)
536 let remote_delayedpubkey = match chan_utils::derive_public_key(&secp_ctx, &per_commitment_point, &self.remote_pubkeys().delayed_payment_basepoint) {
537 Ok(remote_delayedpubkey) => remote_delayedpubkey,
538 Err(_) => return Err(())
540 chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.local_to_self_delay(), &remote_delayedpubkey)
542 let sighash_parts = bip143::SighashComponents::new(&justice_tx);
543 let sighash = hash_to_message!(&sighash_parts.sighash_all(&justice_tx.input[input], &witness_script, amount)[..]);
544 return Ok(secp_ctx.sign(&sighash, &revocation_key))
547 fn sign_remote_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, ()> {
548 if let Ok(htlc_key) = chan_utils::derive_private_key(&secp_ctx, &per_commitment_point, &self.htlc_base_key) {
549 let witness_script = if let Ok(revocation_pubkey) = chan_utils::derive_public_revocation_key(&secp_ctx, &per_commitment_point, &self.pubkeys().revocation_basepoint) {
550 if let Ok(remote_htlcpubkey) = chan_utils::derive_public_key(&secp_ctx, &per_commitment_point, &self.remote_pubkeys().htlc_basepoint) {
551 if let Ok(local_htlcpubkey) = chan_utils::derive_public_key(&secp_ctx, &per_commitment_point, &self.pubkeys().htlc_basepoint) {
552 chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, &remote_htlcpubkey, &local_htlcpubkey, &revocation_pubkey)
553 } else { return Err(()) }
554 } else { return Err(()) }
555 } else { return Err(()) };
556 let sighash_parts = bip143::SighashComponents::new(&htlc_tx);
557 let sighash = hash_to_message!(&sighash_parts.sighash_all(&htlc_tx.input[input], &witness_script, amount)[..]);
558 return Ok(secp_ctx.sign(&sighash, &htlc_key))
563 fn sign_closing_transaction<T: secp256k1::Signing>(&self, closing_tx: &Transaction, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()> {
564 if closing_tx.input.len() != 1 { return Err(()); }
565 if closing_tx.input[0].witness.len() != 0 { return Err(()); }
566 if closing_tx.output.len() > 2 { return Err(()); }
568 let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
569 let remote_channel_data = self.accepted_channel_data.as_ref().expect("must accept before signing");
570 let channel_funding_redeemscript = make_funding_redeemscript(&funding_pubkey, &remote_channel_data.remote_channel_pubkeys.funding_pubkey);
572 let sighash = hash_to_message!(&bip143::SighashComponents::new(closing_tx)
573 .sighash_all(&closing_tx.input[0], &channel_funding_redeemscript, self.channel_value_satoshis)[..]);
574 Ok(secp_ctx.sign(&sighash, &self.funding_key))
577 fn sign_channel_announcement<T: secp256k1::Signing>(&self, msg: &msgs::UnsignedChannelAnnouncement, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()> {
578 let msghash = hash_to_message!(&Sha256dHash::hash(&msg.encode()[..])[..]);
579 Ok(secp_ctx.sign(&msghash, &self.funding_key))
582 fn on_accept(&mut self, channel_pubkeys: &ChannelPublicKeys, remote_to_self_delay: u16, local_to_self_delay: u16) {
583 assert!(self.accepted_channel_data.is_none(), "Already accepted");
584 self.accepted_channel_data = Some(AcceptedChannelData {
585 remote_channel_pubkeys: channel_pubkeys.clone(),
586 remote_to_self_delay,
592 impl_writeable!(AcceptedChannelData, 0,
593 { remote_channel_pubkeys, remote_to_self_delay, local_to_self_delay });
595 impl Writeable for InMemoryChannelKeys {
596 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), Error> {
597 self.funding_key.write(writer)?;
598 self.revocation_base_key.write(writer)?;
599 self.payment_key.write(writer)?;
600 self.delayed_payment_base_key.write(writer)?;
601 self.htlc_base_key.write(writer)?;
602 self.commitment_seed.write(writer)?;
603 self.accepted_channel_data.write(writer)?;
604 self.channel_value_satoshis.write(writer)?;
605 self.key_derivation_params.0.write(writer)?;
606 self.key_derivation_params.1.write(writer)?;
612 impl Readable for InMemoryChannelKeys {
613 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
614 let funding_key = Readable::read(reader)?;
615 let revocation_base_key = Readable::read(reader)?;
616 let payment_key = Readable::read(reader)?;
617 let delayed_payment_base_key = Readable::read(reader)?;
618 let htlc_base_key = Readable::read(reader)?;
619 let commitment_seed = Readable::read(reader)?;
620 let remote_channel_data = Readable::read(reader)?;
621 let channel_value_satoshis = Readable::read(reader)?;
622 let secp_ctx = Secp256k1::signing_only();
623 let local_channel_pubkeys =
624 InMemoryChannelKeys::make_local_keys(&secp_ctx, &funding_key, &revocation_base_key,
625 &payment_key, &delayed_payment_base_key,
627 let params_1 = Readable::read(reader)?;
628 let params_2 = Readable::read(reader)?;
630 Ok(InMemoryChannelKeys {
634 delayed_payment_base_key,
637 channel_value_satoshis,
638 local_channel_pubkeys,
639 accepted_channel_data: remote_channel_data,
640 key_derivation_params: (params_1, params_2),
645 /// Simple KeysInterface implementor that takes a 32-byte seed for use as a BIP 32 extended key
646 /// and derives keys from that.
648 /// Your node_id is seed/0'
649 /// ChannelMonitor closes may use seed/1'
650 /// Cooperative closes may use seed/2'
651 /// The two close keys may be needed to claim on-chain funds!
652 pub struct KeysManager {
653 secp_ctx: Secp256k1<secp256k1::SignOnly>,
654 node_secret: SecretKey,
655 destination_script: Script,
656 shutdown_pubkey: PublicKey,
657 channel_master_key: ExtendedPrivKey,
658 channel_child_index: AtomicUsize,
659 session_master_key: ExtendedPrivKey,
660 session_child_index: AtomicUsize,
661 channel_id_master_key: ExtendedPrivKey,
662 channel_id_child_index: AtomicUsize,
665 starting_time_secs: u64,
666 starting_time_nanos: u32,
670 /// Constructs a KeysManager from a 32-byte seed. If the seed is in some way biased (eg your
671 /// RNG is busted) this may panic (but more importantly, you will possibly lose funds).
672 /// starting_time isn't strictly required to actually be a time, but it must absolutely,
673 /// without a doubt, be unique to this instance. ie if you start multiple times with the same
674 /// seed, starting_time must be unique to each run. Thus, the easiest way to achieve this is to
675 /// simply use the current time (with very high precision).
677 /// The seed MUST be backed up safely prior to use so that the keys can be re-created, however,
678 /// obviously, starting_time should be unique every time you reload the library - it is only
679 /// used to generate new ephemeral key data (which will be stored by the individual channel if
682 /// Note that the seed is required to recover certain on-chain funds independent of
683 /// ChannelMonitor data, though a current copy of ChannelMonitor data is also required for any
684 /// channel, and some on-chain during-closing funds.
686 /// Note that until the 0.1 release there is no guarantee of backward compatibility between
687 /// versions. Once the library is more fully supported, the docs will be updated to include a
688 /// detailed description of the guarantee.
689 pub fn new(seed: &[u8; 32], network: Network, starting_time_secs: u64, starting_time_nanos: u32) -> Self {
690 let secp_ctx = Secp256k1::signing_only();
691 match ExtendedPrivKey::new_master(network.clone(), seed) {
693 let node_secret = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(0).unwrap()).expect("Your RNG is busted").private_key.key;
694 let destination_script = match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(1).unwrap()) {
695 Ok(destination_key) => {
696 let wpubkey_hash = WPubkeyHash::hash(&ExtendedPubKey::from_private(&secp_ctx, &destination_key).public_key.to_bytes());
697 Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0)
698 .push_slice(&wpubkey_hash.into_inner())
701 Err(_) => panic!("Your RNG is busted"),
703 let shutdown_pubkey = match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(2).unwrap()) {
704 Ok(shutdown_key) => ExtendedPubKey::from_private(&secp_ctx, &shutdown_key).public_key.key,
705 Err(_) => panic!("Your RNG is busted"),
707 let channel_master_key = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(3).unwrap()).expect("Your RNG is busted");
708 let session_master_key = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(4).unwrap()).expect("Your RNG is busted");
709 let channel_id_master_key = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(5).unwrap()).expect("Your RNG is busted");
717 channel_child_index: AtomicUsize::new(0),
719 session_child_index: AtomicUsize::new(0),
720 channel_id_master_key,
721 channel_id_child_index: AtomicUsize::new(0),
728 Err(_) => panic!("Your rng is busted"),
731 fn derive_unique_start(&self) -> Sha256State {
732 let mut unique_start = Sha256::engine();
733 unique_start.input(&byte_utils::be64_to_array(self.starting_time_secs));
734 unique_start.input(&byte_utils::be32_to_array(self.starting_time_nanos));
735 unique_start.input(&self.seed);
738 /// Derive an old set of ChannelKeys for per-channel secrets based on a key derivation
740 /// Key derivation parameters are accessible through a per-channel secrets
741 /// ChannelKeys::key_derivation_params and is provided inside DynamicOuputP2WSH in case of
742 /// onchain output detection for which a corresponding delayed_payment_key must be derived.
743 pub fn derive_channel_keys(&self, channel_value_satoshis: u64, params_1: u64, params_2: u64) -> InMemoryChannelKeys {
744 let chan_id = ((params_1 & 0xFFFF_FFFF_0000_0000) >> 32) as u32;
745 let mut unique_start = Sha256::engine();
746 unique_start.input(&byte_utils::be64_to_array(params_2));
747 unique_start.input(&byte_utils::be32_to_array(params_1 as u32));
748 unique_start.input(&self.seed);
750 // We only seriously intend to rely on the channel_master_key for true secure
751 // entropy, everything else just ensures uniqueness. We rely on the unique_start (ie
752 // starting_time provided in the constructor) to be unique.
753 let child_privkey = self.channel_master_key.ckd_priv(&self.secp_ctx, ChildNumber::from_hardened_idx(chan_id).expect("key space exhausted")).expect("Your RNG is busted");
754 unique_start.input(&child_privkey.private_key.key[..]);
756 let seed = Sha256::from_engine(unique_start).into_inner();
758 let commitment_seed = {
759 let mut sha = Sha256::engine();
761 sha.input(&b"commitment seed"[..]);
762 Sha256::from_engine(sha).into_inner()
764 macro_rules! key_step {
765 ($info: expr, $prev_key: expr) => {{
766 let mut sha = Sha256::engine();
768 sha.input(&$prev_key[..]);
769 sha.input(&$info[..]);
770 SecretKey::from_slice(&Sha256::from_engine(sha).into_inner()).expect("SHA-256 is busted")
773 let funding_key = key_step!(b"funding key", commitment_seed);
774 let revocation_base_key = key_step!(b"revocation base key", funding_key);
775 let payment_key = key_step!(b"payment key", revocation_base_key);
776 let delayed_payment_base_key = key_step!(b"delayed payment base key", payment_key);
777 let htlc_base_key = key_step!(b"HTLC base key", delayed_payment_base_key);
779 InMemoryChannelKeys::new(
784 delayed_payment_base_key,
787 channel_value_satoshis,
788 (params_1, params_2),
793 impl KeysInterface for KeysManager {
794 type ChanKeySigner = InMemoryChannelKeys;
796 fn get_node_secret(&self) -> SecretKey {
797 self.node_secret.clone()
800 fn get_destination_script(&self) -> Script {
801 self.destination_script.clone()
804 fn get_shutdown_pubkey(&self) -> PublicKey {
805 self.shutdown_pubkey.clone()
808 fn get_channel_keys(&self, _inbound: bool, channel_value_satoshis: u64) -> InMemoryChannelKeys {
809 let child_ix = self.channel_child_index.fetch_add(1, Ordering::AcqRel);
810 let ix_and_nanos: u64 = (child_ix as u64) << 32 | (self.starting_time_nanos as u64);
811 self.derive_channel_keys(channel_value_satoshis, ix_and_nanos, self.starting_time_secs)
814 fn get_onion_rand(&self) -> (SecretKey, [u8; 32]) {
815 let mut sha = self.derive_unique_start();
817 let child_ix = self.session_child_index.fetch_add(1, Ordering::AcqRel);
818 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");
819 sha.input(&child_privkey.private_key.key[..]);
821 let mut rng_seed = sha.clone();
822 // Not exactly the most ideal construction, but the second value will get fed into
823 // ChaCha so it is another step harder to break.
824 rng_seed.input(b"RNG Seed Salt");
825 sha.input(b"Session Key Salt");
826 (SecretKey::from_slice(&Sha256::from_engine(sha).into_inner()).expect("Your RNG is busted"),
827 Sha256::from_engine(rng_seed).into_inner())
830 fn get_channel_id(&self) -> [u8; 32] {
831 let mut sha = self.derive_unique_start();
833 let child_ix = self.channel_id_child_index.fetch_add(1, Ordering::AcqRel);
834 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");
835 sha.input(&child_privkey.private_key.key[..]);
837 Sha256::from_engine(sha).into_inner()