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 //! Provides keys to LDK and defines some useful objects describing spendable on-chain outputs.
12 //! The provided output descriptors follow a custom LDK data format and are currently not fully
13 //! compatible with Bitcoin Core output descriptors.
15 use bitcoin::blockdata::locktime::absolute::LockTime;
16 use bitcoin::blockdata::transaction::{Transaction, TxOut, TxIn};
17 use bitcoin::blockdata::script::{Script, ScriptBuf, Builder};
18 use bitcoin::blockdata::opcodes;
19 use bitcoin::ecdsa::Signature as EcdsaSignature;
20 use bitcoin::network::constants::Network;
21 use bitcoin::psbt::PartiallySignedTransaction;
22 use bitcoin::bip32::{ExtendedPrivKey, ExtendedPubKey, ChildNumber};
24 use bitcoin::sighash::EcdsaSighashType;
26 use bitcoin::bech32::u5;
27 use bitcoin::hashes::{Hash, HashEngine};
28 use bitcoin::hashes::sha256::Hash as Sha256;
29 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
30 use bitcoin::hash_types::WPubkeyHash;
33 use bitcoin::secp256k1::All;
34 use bitcoin::secp256k1::{KeyPair, PublicKey, Scalar, Secp256k1, SecretKey, Signing};
35 use bitcoin::secp256k1::ecdh::SharedSecret;
36 use bitcoin::secp256k1::ecdsa::{RecoverableSignature, Signature};
37 use bitcoin::secp256k1::schnorr;
38 use bitcoin::{secp256k1, Sequence, Witness, Txid};
40 use crate::util::transaction_utils;
41 use crate::crypto::utils::{hkdf_extract_expand_twice, sign, sign_with_aux_rand};
42 use crate::util::ser::{Writeable, Writer, Readable, ReadableArgs};
43 use crate::chain::transaction::OutPoint;
44 use crate::ln::channel::ANCHOR_OUTPUT_VALUE_SATOSHI;
45 use crate::ln::{chan_utils, PaymentPreimage};
46 use crate::ln::chan_utils::{HTLCOutputInCommitment, make_funding_redeemscript, ChannelPublicKeys, HolderCommitmentTransaction, ChannelTransactionParameters, CommitmentTransaction, ClosingTransaction};
47 use crate::ln::channel_keys::{DelayedPaymentBasepoint, DelayedPaymentKey, HtlcKey, HtlcBasepoint, RevocationKey, RevocationBasepoint};
48 use crate::ln::msgs::{UnsignedChannelAnnouncement, UnsignedGossipMessage};
50 use crate::ln::msgs::PartialSignatureWithNonce;
51 use crate::ln::script::ShutdownScript;
52 use crate::offers::invoice::UnsignedBolt12Invoice;
53 use crate::offers::invoice_request::UnsignedInvoiceRequest;
55 use crate::prelude::*;
57 use core::sync::atomic::{AtomicUsize, Ordering};
59 use musig2::types::{PartialSignature, PublicNonce};
60 use crate::io::{self, Error};
61 use crate::ln::features::ChannelTypeFeatures;
62 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
63 use crate::sign::ecdsa::{EcdsaChannelSigner, WriteableEcdsaChannelSigner};
65 use crate::sign::taproot::TaprootChannelSigner;
66 use crate::util::atomic_counter::AtomicCounter;
67 use crate::crypto::chacha20::ChaCha20;
68 use crate::util::invoice::construct_invoice_preimage;
70 pub(crate) mod type_resolver;
76 /// Used as initial key material, to be expanded into multiple secret keys (but not to be used
77 /// directly). This is used within LDK to encrypt/decrypt inbound payment data.
79 /// This is not exported to bindings users as we just use `[u8; 32]` directly
80 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
81 pub struct KeyMaterial(pub [u8; 32]);
83 /// Information about a spendable output to a P2WSH script.
85 /// See [`SpendableOutputDescriptor::DelayedPaymentOutput`] for more details on how to spend this.
86 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
87 pub struct DelayedPaymentOutputDescriptor {
88 /// The outpoint which is spendable.
89 pub outpoint: OutPoint,
90 /// Per commitment point to derive the delayed payment key by key holder.
91 pub per_commitment_point: PublicKey,
92 /// The `nSequence` value which must be set in the spending input to satisfy the `OP_CSV` in
93 /// the witness_script.
94 pub to_self_delay: u16,
95 /// The output which is referenced by the given outpoint.
97 /// The revocation point specific to the commitment transaction which was broadcast. Used to
98 /// derive the witnessScript for this output.
99 pub revocation_pubkey: RevocationKey,
100 /// Arbitrary identification information returned by a call to [`ChannelSigner::channel_keys_id`].
101 /// This may be useful in re-deriving keys used in the channel to spend the output.
102 pub channel_keys_id: [u8; 32],
103 /// The value of the channel which this output originated from, possibly indirectly.
104 pub channel_value_satoshis: u64,
106 impl DelayedPaymentOutputDescriptor {
107 /// The maximum length a well-formed witness spending one of these should have.
108 /// Note: If you have the grind_signatures feature enabled, this will be at least 1 byte
110 // Calculated as 1 byte length + 73 byte signature, 1 byte empty vec push, 1 byte length plus
111 // redeemscript push length.
112 pub const MAX_WITNESS_LENGTH: u64 = 1 + 73 + 1 + chan_utils::REVOKEABLE_REDEEMSCRIPT_MAX_LENGTH as u64 + 1;
115 impl_writeable_tlv_based!(DelayedPaymentOutputDescriptor, {
116 (0, outpoint, required),
117 (2, per_commitment_point, required),
118 (4, to_self_delay, required),
119 (6, output, required),
120 (8, revocation_pubkey, required),
121 (10, channel_keys_id, required),
122 (12, channel_value_satoshis, required),
125 pub(crate) const P2WPKH_WITNESS_WEIGHT: u64 = 1 /* num stack items */ +
127 73 /* sig including sighash flag */ +
128 1 /* pubkey length */ +
131 /// Information about a spendable output to our "payment key".
133 /// See [`SpendableOutputDescriptor::StaticPaymentOutput`] for more details on how to spend this.
134 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
135 pub struct StaticPaymentOutputDescriptor {
136 /// The outpoint which is spendable.
137 pub outpoint: OutPoint,
138 /// The output which is referenced by the given outpoint.
140 /// Arbitrary identification information returned by a call to [`ChannelSigner::channel_keys_id`].
141 /// This may be useful in re-deriving keys used in the channel to spend the output.
142 pub channel_keys_id: [u8; 32],
143 /// The value of the channel which this transactions spends.
144 pub channel_value_satoshis: u64,
145 /// The necessary channel parameters that need to be provided to the re-derived signer through
146 /// [`ChannelSigner::provide_channel_parameters`].
148 /// Added as optional, but always `Some` if the descriptor was produced in v0.0.117 or later.
149 pub channel_transaction_parameters: Option<ChannelTransactionParameters>,
151 impl StaticPaymentOutputDescriptor {
152 /// Returns the `witness_script` of the spendable output.
154 /// Note that this will only return `Some` for [`StaticPaymentOutputDescriptor`]s that
155 /// originated from an anchor outputs channel, as they take the form of a P2WSH script.
156 pub fn witness_script(&self) -> Option<ScriptBuf> {
157 self.channel_transaction_parameters.as_ref()
158 .and_then(|channel_params|
159 if channel_params.supports_anchors() {
160 let payment_point = channel_params.holder_pubkeys.payment_point;
161 Some(chan_utils::get_to_countersignatory_with_anchors_redeemscript(&payment_point))
168 /// The maximum length a well-formed witness spending one of these should have.
169 /// Note: If you have the grind_signatures feature enabled, this will be at least 1 byte
171 pub fn max_witness_length(&self) -> u64 {
172 if self.channel_transaction_parameters.as_ref().map_or(false, |p| p.supports_anchors())
174 let witness_script_weight = 1 /* pubkey push */ + 33 /* pubkey */ +
175 1 /* OP_CHECKSIGVERIFY */ + 1 /* OP_1 */ + 1 /* OP_CHECKSEQUENCEVERIFY */;
176 1 /* num witness items */ + 1 /* sig push */ + 73 /* sig including sighash flag */ +
177 1 /* witness script push */ + witness_script_weight
179 P2WPKH_WITNESS_WEIGHT
183 impl_writeable_tlv_based!(StaticPaymentOutputDescriptor, {
184 (0, outpoint, required),
185 (2, output, required),
186 (4, channel_keys_id, required),
187 (6, channel_value_satoshis, required),
188 (7, channel_transaction_parameters, option),
191 /// Describes the necessary information to spend a spendable output.
193 /// When on-chain outputs are created by LDK (which our counterparty is not able to claim at any
194 /// point in the future) a [`SpendableOutputs`] event is generated which you must track and be able
195 /// to spend on-chain. The information needed to do this is provided in this enum, including the
196 /// outpoint describing which `txid` and output `index` is available, the full output which exists
197 /// at that `txid`/`index`, and any keys or other information required to sign.
199 /// [`SpendableOutputs`]: crate::events::Event::SpendableOutputs
200 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
201 pub enum SpendableOutputDescriptor {
202 /// An output to a script which was provided via [`SignerProvider`] directly, either from
203 /// [`get_destination_script`] or [`get_shutdown_scriptpubkey`], thus you should already
204 /// know how to spend it. No secret keys are provided as LDK was never given any key.
205 /// These may include outputs from a transaction punishing our counterparty or claiming an HTLC
206 /// on-chain using the payment preimage or after it has timed out.
208 /// [`get_shutdown_scriptpubkey`]: SignerProvider::get_shutdown_scriptpubkey
209 /// [`get_destination_script`]: SignerProvider::get_shutdown_scriptpubkey
211 /// The outpoint which is spendable.
213 /// The output which is referenced by the given outpoint.
215 /// The `channel_keys_id` for the channel which this output came from.
217 /// For channels which were generated on LDK 0.0.119 or later, this is the value which was
218 /// passed to the [`SignerProvider::get_destination_script`] call which provided this
221 /// For channels which were generated prior to LDK 0.0.119, no such argument existed,
222 /// however this field may still be filled in if such data is available.
223 channel_keys_id: Option<[u8; 32]>
225 /// An output to a P2WSH script which can be spent with a single signature after an `OP_CSV`
228 /// The witness in the spending input should be:
230 /// <BIP 143 signature> <empty vector> (MINIMALIF standard rule) <provided witnessScript>
233 /// Note that the `nSequence` field in the spending input must be set to
234 /// [`DelayedPaymentOutputDescriptor::to_self_delay`] (which means the transaction is not
235 /// broadcastable until at least [`DelayedPaymentOutputDescriptor::to_self_delay`] blocks after
236 /// the outpoint confirms, see [BIP
237 /// 68](https://github.com/bitcoin/bips/blob/master/bip-0068.mediawiki)). Also note that LDK
238 /// won't generate a [`SpendableOutputDescriptor`] until the corresponding block height
241 /// These are generally the result of a "revocable" output to us, spendable only by us unless
242 /// it is an output from an old state which we broadcast (which should never happen).
244 /// To derive the delayed payment key which is used to sign this input, you must pass the
245 /// holder [`InMemorySigner::delayed_payment_base_key`] (i.e., the private key which corresponds to the
246 /// [`ChannelPublicKeys::delayed_payment_basepoint`] in [`ChannelSigner::pubkeys`]) and the provided
247 /// [`DelayedPaymentOutputDescriptor::per_commitment_point`] to [`chan_utils::derive_private_key`]. The DelayedPaymentKey can be
248 /// generated without the secret key using [`DelayedPaymentKey::from_basepoint`] and only the
249 /// [`ChannelPublicKeys::delayed_payment_basepoint`] which appears in [`ChannelSigner::pubkeys`].
251 /// To derive the [`DelayedPaymentOutputDescriptor::revocation_pubkey`] provided here (which is
252 /// used in the witness script generation), you must pass the counterparty
253 /// [`ChannelPublicKeys::revocation_basepoint`] (which appears in the call to
254 /// [`ChannelSigner::provide_channel_parameters`]) and the provided
255 /// [`DelayedPaymentOutputDescriptor::per_commitment_point`] to
256 /// [`RevocationKey`].
258 /// The witness script which is hashed and included in the output `script_pubkey` may be
259 /// regenerated by passing the [`DelayedPaymentOutputDescriptor::revocation_pubkey`] (derived
260 /// as explained above), our delayed payment pubkey (derived as explained above), and the
261 /// [`DelayedPaymentOutputDescriptor::to_self_delay`] contained here to
262 /// [`chan_utils::get_revokeable_redeemscript`].
263 DelayedPaymentOutput(DelayedPaymentOutputDescriptor),
264 /// An output spendable exclusively by our payment key (i.e., the private key that corresponds
265 /// to the `payment_point` in [`ChannelSigner::pubkeys`]). The output type depends on the
266 /// channel type negotiated.
268 /// On an anchor outputs channel, the witness in the spending input is:
270 /// <BIP 143 signature> <witness script>
273 /// Otherwise, it is:
275 /// <BIP 143 signature> <payment key>
278 /// These are generally the result of our counterparty having broadcast the current state,
279 /// allowing us to claim the non-HTLC-encumbered outputs immediately, or after one confirmation
280 /// in the case of anchor outputs channels.
281 StaticPaymentOutput(StaticPaymentOutputDescriptor),
284 impl_writeable_tlv_based_enum!(SpendableOutputDescriptor,
285 (0, StaticOutput) => {
286 (0, outpoint, required),
287 (1, channel_keys_id, option),
288 (2, output, required),
291 (1, DelayedPaymentOutput),
292 (2, StaticPaymentOutput),
295 impl SpendableOutputDescriptor {
296 /// Turns this into a [`bitcoin::psbt::Input`] which can be used to create a
297 /// [`PartiallySignedTransaction`] which spends the given descriptor.
299 /// Note that this does not include any signatures, just the information required to
300 /// construct the transaction and sign it.
302 /// This is not exported to bindings users as there is no standard serialization for an input.
303 /// See [`Self::create_spendable_outputs_psbt`] instead.
304 pub fn to_psbt_input(&self) -> bitcoin::psbt::Input {
306 SpendableOutputDescriptor::StaticOutput { output, .. } => {
307 // Is a standard P2WPKH, no need for witness script
308 bitcoin::psbt::Input {
309 witness_utxo: Some(output.clone()),
313 SpendableOutputDescriptor::DelayedPaymentOutput(descriptor) => {
314 // TODO we could add the witness script as well
315 bitcoin::psbt::Input {
316 witness_utxo: Some(descriptor.output.clone()),
320 SpendableOutputDescriptor::StaticPaymentOutput(descriptor) => {
321 // TODO we could add the witness script as well
322 bitcoin::psbt::Input {
323 witness_utxo: Some(descriptor.output.clone()),
330 /// Creates an unsigned [`PartiallySignedTransaction`] which spends the given descriptors to
331 /// the given outputs, plus an output to the given change destination (if sufficient
332 /// change value remains). The PSBT will have a feerate, at least, of the given value.
334 /// The `locktime` argument is used to set the transaction's locktime. If `None`, the
335 /// transaction will have a locktime of 0. It it recommended to set this to the current block
336 /// height to avoid fee sniping, unless you have some specific reason to use a different
339 /// Returns the PSBT and expected max transaction weight.
341 /// Returns `Err(())` if the output value is greater than the input value minus required fee,
342 /// if a descriptor was duplicated, or if an output descriptor `script_pubkey`
343 /// does not match the one we can spend.
345 /// We do not enforce that outputs meet the dust limit or that any output scripts are standard.
346 pub fn create_spendable_outputs_psbt(descriptors: &[&SpendableOutputDescriptor], outputs: Vec<TxOut>, change_destination_script: ScriptBuf, feerate_sat_per_1000_weight: u32, locktime: Option<LockTime>) -> Result<(PartiallySignedTransaction, u64), ()> {
347 let mut input = Vec::with_capacity(descriptors.len());
348 let mut input_value = 0;
349 let mut witness_weight = 0;
350 let mut output_set = hash_set_with_capacity(descriptors.len());
351 for outp in descriptors {
353 SpendableOutputDescriptor::StaticPaymentOutput(descriptor) => {
354 if !output_set.insert(descriptor.outpoint) { return Err(()); }
356 if descriptor.channel_transaction_parameters.as_ref()
357 .map_or(false, |p| p.supports_anchors())
359 Sequence::from_consensus(1)
364 previous_output: descriptor.outpoint.into_bitcoin_outpoint(),
365 script_sig: ScriptBuf::new(),
367 witness: Witness::new(),
369 witness_weight += descriptor.max_witness_length();
370 #[cfg(feature = "grind_signatures")]
371 { witness_weight -= 1; } // Guarantees a low R signature
372 input_value += descriptor.output.value;
374 SpendableOutputDescriptor::DelayedPaymentOutput(descriptor) => {
375 if !output_set.insert(descriptor.outpoint) { return Err(()); }
377 previous_output: descriptor.outpoint.into_bitcoin_outpoint(),
378 script_sig: ScriptBuf::new(),
379 sequence: Sequence(descriptor.to_self_delay as u32),
380 witness: Witness::new(),
382 witness_weight += DelayedPaymentOutputDescriptor::MAX_WITNESS_LENGTH;
383 #[cfg(feature = "grind_signatures")]
384 { witness_weight -= 1; } // Guarantees a low R signature
385 input_value += descriptor.output.value;
387 SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output, .. } => {
388 if !output_set.insert(*outpoint) { return Err(()); }
390 previous_output: outpoint.into_bitcoin_outpoint(),
391 script_sig: ScriptBuf::new(),
392 sequence: Sequence::ZERO,
393 witness: Witness::new(),
395 witness_weight += 1 + 73 + 34;
396 #[cfg(feature = "grind_signatures")]
397 { witness_weight -= 1; } // Guarantees a low R signature
398 input_value += output.value;
401 if input_value > MAX_VALUE_MSAT / 1000 { return Err(()); }
403 let mut tx = Transaction {
405 lock_time: locktime.unwrap_or(LockTime::ZERO),
409 let expected_max_weight =
410 transaction_utils::maybe_add_change_output(&mut tx, input_value, witness_weight, feerate_sat_per_1000_weight, change_destination_script)?;
412 let psbt_inputs = descriptors.iter().map(|d| d.to_psbt_input()).collect::<Vec<_>>();
413 let psbt = PartiallySignedTransaction {
415 outputs: vec![Default::default(); tx.output.len()],
417 xpub: Default::default(),
419 proprietary: Default::default(),
420 unknown: Default::default(),
422 Ok((psbt, expected_max_weight))
426 /// The parameters required to derive a channel signer via [`SignerProvider`].
427 #[derive(Clone, Debug, PartialEq, Eq)]
428 pub struct ChannelDerivationParameters {
429 /// The value in satoshis of the channel we're attempting to spend the anchor output of.
430 pub value_satoshis: u64,
431 /// The unique identifier to re-derive the signer for the associated channel.
432 pub keys_id: [u8; 32],
433 /// The necessary channel parameters that need to be provided to the re-derived signer through
434 /// [`ChannelSigner::provide_channel_parameters`].
435 pub transaction_parameters: ChannelTransactionParameters,
438 impl_writeable_tlv_based!(ChannelDerivationParameters, {
439 (0, value_satoshis, required),
440 (2, keys_id, required),
441 (4, transaction_parameters, required),
444 /// A descriptor used to sign for a commitment transaction's HTLC output.
445 #[derive(Clone, Debug, PartialEq, Eq)]
446 pub struct HTLCDescriptor {
447 /// The parameters required to derive the signer for the HTLC input.
448 pub channel_derivation_parameters: ChannelDerivationParameters,
449 /// The txid of the commitment transaction in which the HTLC output lives.
450 pub commitment_txid: Txid,
451 /// The number of the commitment transaction in which the HTLC output lives.
452 pub per_commitment_number: u64,
453 /// The key tweak corresponding to the number of the commitment transaction in which the HTLC
454 /// output lives. This tweak is applied to all the basepoints for both parties in the channel to
455 /// arrive at unique keys per commitment.
457 /// See <https://github.com/lightning/bolts/blob/master/03-transactions.md#keys> for more info.
458 pub per_commitment_point: PublicKey,
459 /// The feerate to use on the HTLC claiming transaction. This is always `0` for HTLCs
460 /// originating from a channel supporting anchor outputs, otherwise it is the channel's
461 /// negotiated feerate at the time the commitment transaction was built.
462 pub feerate_per_kw: u32,
463 /// The details of the HTLC as it appears in the commitment transaction.
464 pub htlc: HTLCOutputInCommitment,
465 /// The preimage, if `Some`, to claim the HTLC output with. If `None`, the timeout path must be
467 pub preimage: Option<PaymentPreimage>,
468 /// The counterparty's signature required to spend the HTLC output.
469 pub counterparty_sig: Signature
472 impl_writeable_tlv_based!(HTLCDescriptor, {
473 (0, channel_derivation_parameters, required),
474 (1, feerate_per_kw, (default_value, 0)),
475 (2, commitment_txid, required),
476 (4, per_commitment_number, required),
477 (6, per_commitment_point, required),
479 (10, preimage, option),
480 (12, counterparty_sig, required),
483 impl HTLCDescriptor {
484 /// Returns the outpoint of the HTLC output in the commitment transaction. This is the outpoint
485 /// being spent by the HTLC input in the HTLC transaction.
486 pub fn outpoint(&self) -> bitcoin::OutPoint {
488 txid: self.commitment_txid,
489 vout: self.htlc.transaction_output_index.unwrap(),
493 /// Returns the UTXO to be spent by the HTLC input, which can be obtained via
494 /// [`Self::unsigned_tx_input`].
495 pub fn previous_utxo<C: secp256k1::Signing + secp256k1::Verification>(&self, secp: &Secp256k1<C>) -> TxOut {
497 script_pubkey: self.witness_script(secp).to_v0_p2wsh(),
498 value: self.htlc.amount_msat / 1000,
502 /// Returns the unsigned transaction input spending the HTLC output in the commitment
504 pub fn unsigned_tx_input(&self) -> TxIn {
505 chan_utils::build_htlc_input(
506 &self.commitment_txid, &self.htlc, &self.channel_derivation_parameters.transaction_parameters.channel_type_features
510 /// Returns the delayed output created as a result of spending the HTLC output in the commitment
512 pub fn tx_output<C: secp256k1::Signing + secp256k1::Verification>(&self, secp: &Secp256k1<C>) -> TxOut {
513 let channel_params = self.channel_derivation_parameters.transaction_parameters.as_holder_broadcastable();
514 let broadcaster_keys = channel_params.broadcaster_pubkeys();
515 let counterparty_keys = channel_params.countersignatory_pubkeys();
516 let broadcaster_delayed_key = DelayedPaymentKey::from_basepoint(
517 secp, &broadcaster_keys.delayed_payment_basepoint, &self.per_commitment_point
519 let counterparty_revocation_key = &RevocationKey::from_basepoint(&secp, &counterparty_keys.revocation_basepoint, &self.per_commitment_point);
520 chan_utils::build_htlc_output(
521 self.feerate_per_kw, channel_params.contest_delay(), &self.htlc,
522 channel_params.channel_type_features(), &broadcaster_delayed_key, &counterparty_revocation_key
526 /// Returns the witness script of the HTLC output in the commitment transaction.
527 pub fn witness_script<C: secp256k1::Signing + secp256k1::Verification>(&self, secp: &Secp256k1<C>) -> ScriptBuf {
528 let channel_params = self.channel_derivation_parameters.transaction_parameters.as_holder_broadcastable();
529 let broadcaster_keys = channel_params.broadcaster_pubkeys();
530 let counterparty_keys = channel_params.countersignatory_pubkeys();
531 let broadcaster_htlc_key = HtlcKey::from_basepoint(
532 secp, &broadcaster_keys.htlc_basepoint, &self.per_commitment_point
534 let counterparty_htlc_key = HtlcKey::from_basepoint(
535 secp, &counterparty_keys.htlc_basepoint, &self.per_commitment_point,
537 let counterparty_revocation_key = &RevocationKey::from_basepoint(&secp, &counterparty_keys.revocation_basepoint, &self.per_commitment_point);
538 chan_utils::get_htlc_redeemscript_with_explicit_keys(
539 &self.htlc, channel_params.channel_type_features(), &broadcaster_htlc_key, &counterparty_htlc_key,
540 &counterparty_revocation_key,
544 /// Returns the fully signed witness required to spend the HTLC output in the commitment
546 pub fn tx_input_witness(&self, signature: &Signature, witness_script: &Script) -> Witness {
547 chan_utils::build_htlc_input_witness(
548 signature, &self.counterparty_sig, &self.preimage, witness_script,
549 &self.channel_derivation_parameters.transaction_parameters.channel_type_features
553 /// Derives the channel signer required to sign the HTLC input.
554 pub fn derive_channel_signer<S: WriteableEcdsaChannelSigner, SP: Deref>(&self, signer_provider: &SP) -> S
556 SP::Target: SignerProvider<EcdsaSigner= S>
558 let mut signer = signer_provider.derive_channel_signer(
559 self.channel_derivation_parameters.value_satoshis,
560 self.channel_derivation_parameters.keys_id,
562 signer.provide_channel_parameters(&self.channel_derivation_parameters.transaction_parameters);
567 /// A trait to handle Lightning channel key material without concretizing the channel type or
568 /// the signature mechanism.
569 pub trait ChannelSigner {
570 /// Gets the per-commitment point for a specific commitment number
572 /// Note that the commitment number starts at `(1 << 48) - 1` and counts backwards.
573 fn get_per_commitment_point(&self, idx: u64, secp_ctx: &Secp256k1<secp256k1::All>) -> PublicKey;
575 /// Gets the commitment secret for a specific commitment number as part of the revocation process
577 /// An external signer implementation should error here if the commitment was already signed
578 /// and should refuse to sign it in the future.
580 /// May be called more than once for the same index.
582 /// Note that the commitment number starts at `(1 << 48) - 1` and counts backwards.
583 // TODO: return a Result so we can signal a validation error
584 fn release_commitment_secret(&self, idx: u64) -> [u8; 32];
586 /// Validate the counterparty's signatures on the holder commitment transaction and HTLCs.
588 /// This is required in order for the signer to make sure that releasing a commitment
589 /// secret won't leave us without a broadcastable holder transaction.
590 /// Policy checks should be implemented in this function, including checking the amount
591 /// sent to us and checking the HTLCs.
593 /// The preimages of outbound HTLCs that were fulfilled since the last commitment are provided.
594 /// A validating signer should ensure that an HTLC output is removed only when the matching
595 /// preimage is provided, or when the value to holder is restored.
597 /// Note that all the relevant preimages will be provided, but there may also be additional
598 /// irrelevant or duplicate preimages.
599 fn validate_holder_commitment(&self, holder_tx: &HolderCommitmentTransaction,
600 outbound_htlc_preimages: Vec<PaymentPreimage>) -> Result<(), ()>;
602 /// Validate the counterparty's revocation.
604 /// This is required in order for the signer to make sure that the state has moved
605 /// forward and it is safe to sign the next counterparty commitment.
606 fn validate_counterparty_revocation(&self, idx: u64, secret: &SecretKey) -> Result<(), ()>;
608 /// Returns the holder's channel public keys and basepoints.
609 fn pubkeys(&self) -> &ChannelPublicKeys;
611 /// Returns an arbitrary identifier describing the set of keys which are provided back to you in
612 /// some [`SpendableOutputDescriptor`] types. This should be sufficient to identify this
613 /// [`EcdsaChannelSigner`] object uniquely and lookup or re-derive its keys.
614 fn channel_keys_id(&self) -> [u8; 32];
616 /// Set the counterparty static channel data, including basepoints,
617 /// `counterparty_selected`/`holder_selected_contest_delay` and funding outpoint.
619 /// This data is static, and will never change for a channel once set. For a given [`ChannelSigner`]
620 /// instance, LDK will call this method exactly once - either immediately after construction
621 /// (not including if done via [`SignerProvider::read_chan_signer`]) or when the funding
622 /// information has been generated.
624 /// channel_parameters.is_populated() MUST be true.
625 fn provide_channel_parameters(&mut self, channel_parameters: &ChannelTransactionParameters);
628 /// Specifies the recipient of an invoice.
630 /// This indicates to [`NodeSigner::sign_invoice`] what node secret key should be used to sign
633 /// The invoice should be signed with the local node secret key.
635 /// The invoice should be signed with the phantom node secret key. This secret key must be the
636 /// same for all nodes participating in the [phantom node payment].
638 /// [phantom node payment]: PhantomKeysManager
642 /// A trait that describes a source of entropy.
643 pub trait EntropySource {
644 /// Gets a unique, cryptographically-secure, random 32-byte value. This method must return a
645 /// different value each time it is called.
646 fn get_secure_random_bytes(&self) -> [u8; 32];
649 /// A trait that can handle cryptographic operations at the scope level of a node.
650 pub trait NodeSigner {
651 /// Get secret key material as bytes for use in encrypting and decrypting inbound payment data.
653 /// If the implementor of this trait supports [phantom node payments], then every node that is
654 /// intended to be included in the phantom invoice route hints must return the same value from
656 // This is because LDK avoids storing inbound payment data by encrypting payment data in the
657 // payment hash and/or payment secret, therefore for a payment to be receivable by multiple
658 // nodes, they must share the key that encrypts this payment data.
660 /// This method must return the same value each time it is called.
662 /// [phantom node payments]: PhantomKeysManager
663 fn get_inbound_payment_key_material(&self) -> KeyMaterial;
665 /// Get node id based on the provided [`Recipient`].
667 /// This method must return the same value each time it is called with a given [`Recipient`]
670 /// Errors if the [`Recipient`] variant is not supported by the implementation.
671 fn get_node_id(&self, recipient: Recipient) -> Result<PublicKey, ()>;
673 /// Gets the ECDH shared secret of our node secret and `other_key`, multiplying by `tweak` if
674 /// one is provided. Note that this tweak can be applied to `other_key` instead of our node
675 /// secret, though this is less efficient.
677 /// Note that if this fails while attempting to forward an HTLC, LDK will panic. The error
678 /// should be resolved to allow LDK to resume forwarding HTLCs.
680 /// Errors if the [`Recipient`] variant is not supported by the implementation.
681 fn ecdh(&self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&Scalar>) -> Result<SharedSecret, ()>;
685 /// By parameterizing by the raw invoice bytes instead of the hash, we allow implementors of
686 /// this trait to parse the invoice and make sure they're signing what they expect, rather than
687 /// blindly signing the hash.
689 /// The `hrp_bytes` are ASCII bytes, while the `invoice_data` is base32.
691 /// The secret key used to sign the invoice is dependent on the [`Recipient`].
693 /// Errors if the [`Recipient`] variant is not supported by the implementation.
694 fn sign_invoice(&self, hrp_bytes: &[u8], invoice_data: &[u5], recipient: Recipient) -> Result<RecoverableSignature, ()>;
696 /// Signs the [`TaggedHash`] of a BOLT 12 invoice request.
698 /// May be called by a function passed to [`UnsignedInvoiceRequest::sign`] where
699 /// `invoice_request` is the callee.
701 /// Implementors may check that the `invoice_request` is expected rather than blindly signing
702 /// the tagged hash. An `Ok` result should sign `invoice_request.tagged_hash().as_digest()` with
703 /// the node's signing key or an ephemeral key to preserve privacy, whichever is associated with
704 /// [`UnsignedInvoiceRequest::payer_id`].
706 /// [`TaggedHash`]: crate::offers::merkle::TaggedHash
707 fn sign_bolt12_invoice_request(
708 &self, invoice_request: &UnsignedInvoiceRequest
709 ) -> Result<schnorr::Signature, ()>;
711 /// Signs the [`TaggedHash`] of a BOLT 12 invoice.
713 /// May be called by a function passed to [`UnsignedBolt12Invoice::sign`] where `invoice` is the
716 /// Implementors may check that the `invoice` is expected rather than blindly signing the tagged
717 /// hash. An `Ok` result should sign `invoice.tagged_hash().as_digest()` with the node's signing
718 /// key or an ephemeral key to preserve privacy, whichever is associated with
719 /// [`UnsignedBolt12Invoice::signing_pubkey`].
721 /// [`TaggedHash`]: crate::offers::merkle::TaggedHash
722 fn sign_bolt12_invoice(
723 &self, invoice: &UnsignedBolt12Invoice
724 ) -> Result<schnorr::Signature, ()>;
726 /// Sign a gossip message.
728 /// Note that if this fails, LDK may panic and the message will not be broadcast to the network
729 /// or a possible channel counterparty. If LDK panics, the error should be resolved to allow the
730 /// message to be broadcast, as otherwise it may prevent one from receiving funds over the
731 /// corresponding channel.
732 fn sign_gossip_message(&self, msg: UnsignedGossipMessage) -> Result<Signature, ()>;
735 // Primarily needed in doctests because of https://github.com/rust-lang/rust/issues/67295
736 /// A dynamic [`SignerProvider`] temporarily needed for doc tests.
739 #[deprecated(note = "Remove once taproot cfg is removed")]
740 pub type DynSignerProvider = dyn SignerProvider<EcdsaSigner = InMemorySigner, TaprootSigner = InMemorySigner>;
742 /// A dynamic [`SignerProvider`] temporarily needed for doc tests.
745 #[deprecated(note = "Remove once taproot cfg is removed")]
746 pub type DynSignerProvider = dyn SignerProvider<EcdsaSigner = InMemorySigner>;
748 /// A trait that can return signer instances for individual channels.
749 pub trait SignerProvider {
750 /// A type which implements [`WriteableEcdsaChannelSigner`] which will be returned by [`Self::derive_channel_signer`].
751 type EcdsaSigner: WriteableEcdsaChannelSigner;
753 /// A type which implements [`TaprootChannelSigner`]
754 type TaprootSigner: TaprootChannelSigner;
756 /// Generates a unique `channel_keys_id` that can be used to obtain a [`Self::EcdsaSigner`] through
757 /// [`SignerProvider::derive_channel_signer`]. The `user_channel_id` is provided to allow
758 /// implementations of [`SignerProvider`] to maintain a mapping between itself and the generated
759 /// `channel_keys_id`.
761 /// This method must return a different value each time it is called.
762 fn generate_channel_keys_id(&self, inbound: bool, channel_value_satoshis: u64, user_channel_id: u128) -> [u8; 32];
764 /// Derives the private key material backing a `Signer`.
766 /// To derive a new `Signer`, a fresh `channel_keys_id` should be obtained through
767 /// [`SignerProvider::generate_channel_keys_id`]. Otherwise, an existing `Signer` can be
768 /// re-derived from its `channel_keys_id`, which can be obtained through its trait method
769 /// [`ChannelSigner::channel_keys_id`].
770 fn derive_channel_signer(&self, channel_value_satoshis: u64, channel_keys_id: [u8; 32]) -> Self::EcdsaSigner;
772 /// Reads a [`Signer`] for this [`SignerProvider`] from the given input stream.
773 /// This is only called during deserialization of other objects which contain
774 /// [`WriteableEcdsaChannelSigner`]-implementing objects (i.e., [`ChannelMonitor`]s and [`ChannelManager`]s).
775 /// The bytes are exactly those which `<Self::Signer as Writeable>::write()` writes, and
776 /// contain no versioning scheme. You may wish to include your own version prefix and ensure
777 /// you've read all of the provided bytes to ensure no corruption occurred.
779 /// This method is slowly being phased out -- it will only be called when reading objects
780 /// written by LDK versions prior to 0.0.113.
782 /// [`Signer`]: Self::EcdsaSigner
783 /// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
784 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
785 fn read_chan_signer(&self, reader: &[u8]) -> Result<Self::EcdsaSigner, DecodeError>;
787 /// Get a script pubkey which we send funds to when claiming on-chain contestable outputs.
789 /// If this function returns an error, this will result in a channel failing to open.
791 /// This method should return a different value each time it is called, to avoid linking
792 /// on-chain funds across channels as controlled to the same user. `channel_keys_id` may be
793 /// used to derive a unique value for each channel.
794 fn get_destination_script(&self, channel_keys_id: [u8; 32]) -> Result<ScriptBuf, ()>;
796 /// Get a script pubkey which we will send funds to when closing a channel.
798 /// If this function returns an error, this will result in a channel failing to open or close.
799 /// In the event of a failure when the counterparty is initiating a close, this can result in a
800 /// channel force close.
802 /// This method should return a different value each time it is called, to avoid linking
803 /// on-chain funds across channels as controlled to the same user.
804 fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()>;
807 /// A simple implementation of [`WriteableEcdsaChannelSigner`] that just keeps the private keys in memory.
809 /// This implementation performs no policy checks and is insufficient by itself as
810 /// a secure external signer.
812 pub struct InMemorySigner {
813 /// Holder secret key in the 2-of-2 multisig script of a channel. This key also backs the
814 /// holder's anchor output in a commitment transaction, if one is present.
815 pub funding_key: SecretKey,
816 /// Holder secret key for blinded revocation pubkey.
817 pub revocation_base_key: SecretKey,
818 /// Holder secret key used for our balance in counterparty-broadcasted commitment transactions.
819 pub payment_key: SecretKey,
820 /// Holder secret key used in an HTLC transaction.
821 pub delayed_payment_base_key: SecretKey,
822 /// Holder HTLC secret key used in commitment transaction HTLC outputs.
823 pub htlc_base_key: SecretKey,
825 pub commitment_seed: [u8; 32],
826 /// Holder public keys and basepoints.
827 pub(crate) holder_channel_pubkeys: ChannelPublicKeys,
828 /// Counterparty public keys and counterparty/holder `selected_contest_delay`, populated on channel acceptance.
829 channel_parameters: Option<ChannelTransactionParameters>,
830 /// The total value of this channel.
831 channel_value_satoshis: u64,
832 /// Key derivation parameters.
833 channel_keys_id: [u8; 32],
834 /// A source of random bytes.
835 entropy_source: RandomBytes,
838 impl PartialEq for InMemorySigner {
839 fn eq(&self, other: &Self) -> bool {
840 self.funding_key == other.funding_key &&
841 self.revocation_base_key == other.revocation_base_key &&
842 self.payment_key == other.payment_key &&
843 self.delayed_payment_base_key == other.delayed_payment_base_key &&
844 self.htlc_base_key == other.htlc_base_key &&
845 self.commitment_seed == other.commitment_seed &&
846 self.holder_channel_pubkeys == other.holder_channel_pubkeys &&
847 self.channel_parameters == other.channel_parameters &&
848 self.channel_value_satoshis == other.channel_value_satoshis &&
849 self.channel_keys_id == other.channel_keys_id
853 impl Clone for InMemorySigner {
854 fn clone(&self) -> Self {
856 funding_key: self.funding_key.clone(),
857 revocation_base_key: self.revocation_base_key.clone(),
858 payment_key: self.payment_key.clone(),
859 delayed_payment_base_key: self.delayed_payment_base_key.clone(),
860 htlc_base_key: self.htlc_base_key.clone(),
861 commitment_seed: self.commitment_seed.clone(),
862 holder_channel_pubkeys: self.holder_channel_pubkeys.clone(),
863 channel_parameters: self.channel_parameters.clone(),
864 channel_value_satoshis: self.channel_value_satoshis,
865 channel_keys_id: self.channel_keys_id,
866 entropy_source: RandomBytes::new(self.get_secure_random_bytes()),
871 impl InMemorySigner {
872 /// Creates a new [`InMemorySigner`].
873 pub fn new<C: Signing>(
874 secp_ctx: &Secp256k1<C>,
875 funding_key: SecretKey,
876 revocation_base_key: SecretKey,
877 payment_key: SecretKey,
878 delayed_payment_base_key: SecretKey,
879 htlc_base_key: SecretKey,
880 commitment_seed: [u8; 32],
881 channel_value_satoshis: u64,
882 channel_keys_id: [u8; 32],
883 rand_bytes_unique_start: [u8; 32],
884 ) -> InMemorySigner {
885 let holder_channel_pubkeys =
886 InMemorySigner::make_holder_keys(secp_ctx, &funding_key, &revocation_base_key,
887 &payment_key, &delayed_payment_base_key,
893 delayed_payment_base_key,
896 channel_value_satoshis,
897 holder_channel_pubkeys,
898 channel_parameters: None,
900 entropy_source: RandomBytes::new(rand_bytes_unique_start),
904 fn make_holder_keys<C: Signing>(secp_ctx: &Secp256k1<C>,
905 funding_key: &SecretKey,
906 revocation_base_key: &SecretKey,
907 payment_key: &SecretKey,
908 delayed_payment_base_key: &SecretKey,
909 htlc_base_key: &SecretKey) -> ChannelPublicKeys {
910 let from_secret = |s: &SecretKey| PublicKey::from_secret_key(secp_ctx, s);
912 funding_pubkey: from_secret(&funding_key),
913 revocation_basepoint: RevocationBasepoint::from(from_secret(&revocation_base_key)),
914 payment_point: from_secret(&payment_key),
915 delayed_payment_basepoint: DelayedPaymentBasepoint::from(from_secret(&delayed_payment_base_key)),
916 htlc_basepoint: HtlcBasepoint::from(from_secret(&htlc_base_key)),
920 /// Returns the counterparty's pubkeys.
922 /// Will return `None` if [`ChannelSigner::provide_channel_parameters`] has not been called.
923 /// In general, this is safe to `unwrap` only in [`ChannelSigner`] implementation.
924 pub fn counterparty_pubkeys(&self) -> Option<&ChannelPublicKeys> {
925 self.get_channel_parameters()
926 .and_then(|params| params.counterparty_parameters.as_ref().map(|params| ¶ms.pubkeys))
929 /// Returns the `contest_delay` value specified by our counterparty and applied on holder-broadcastable
930 /// transactions, i.e., the amount of time that we have to wait to recover our funds if we
931 /// broadcast a transaction.
933 /// Will return `None` if [`ChannelSigner::provide_channel_parameters`] has not been called.
934 /// In general, this is safe to `unwrap` only in [`ChannelSigner`] implementation.
935 pub fn counterparty_selected_contest_delay(&self) -> Option<u16> {
936 self.get_channel_parameters()
937 .and_then(|params| params.counterparty_parameters.as_ref().map(|params| params.selected_contest_delay))
940 /// Returns the `contest_delay` value specified by us and applied on transactions broadcastable
941 /// by our counterparty, i.e., the amount of time that they have to wait to recover their funds
942 /// if they broadcast a transaction.
944 /// Will return `None` if [`ChannelSigner::provide_channel_parameters`] has not been called.
945 /// In general, this is safe to `unwrap` only in [`ChannelSigner`] implementation.
946 pub fn holder_selected_contest_delay(&self) -> Option<u16> {
947 self.get_channel_parameters().map(|params| params.holder_selected_contest_delay)
950 /// Returns whether the holder is the initiator.
952 /// Will return `None` if [`ChannelSigner::provide_channel_parameters`] has not been called.
953 /// In general, this is safe to `unwrap` only in [`ChannelSigner`] implementation.
954 pub fn is_outbound(&self) -> Option<bool> {
955 self.get_channel_parameters().map(|params| params.is_outbound_from_holder)
960 /// Will return `None` if [`ChannelSigner::provide_channel_parameters`] has not been called.
961 /// In general, this is safe to `unwrap` only in [`ChannelSigner`] implementation.
962 pub fn funding_outpoint(&self) -> Option<&OutPoint> {
963 self.get_channel_parameters().map(|params| params.funding_outpoint.as_ref()).flatten()
966 /// Returns a [`ChannelTransactionParameters`] for this channel, to be used when verifying or
967 /// building transactions.
969 /// Will return `None` if [`ChannelSigner::provide_channel_parameters`] has not been called.
970 /// In general, this is safe to `unwrap` only in [`ChannelSigner`] implementation.
971 pub fn get_channel_parameters(&self) -> Option<&ChannelTransactionParameters> {
972 self.channel_parameters.as_ref()
975 /// Returns the channel type features of the channel parameters. Should be helpful for
976 /// determining a channel's category, i. e. legacy/anchors/taproot/etc.
978 /// Will return `None` if [`ChannelSigner::provide_channel_parameters`] has not been called.
979 /// In general, this is safe to `unwrap` only in [`ChannelSigner`] implementation.
980 pub fn channel_type_features(&self) -> Option<&ChannelTypeFeatures> {
981 self.get_channel_parameters().map(|params| ¶ms.channel_type_features)
984 /// Sign the single input of `spend_tx` at index `input_idx`, which spends the output described
985 /// by `descriptor`, returning the witness stack for the input.
987 /// Returns an error if the input at `input_idx` does not exist, has a non-empty `script_sig`,
988 /// is not spending the outpoint described by [`descriptor.outpoint`],
989 /// or if an output descriptor `script_pubkey` does not match the one we can spend.
991 /// [`descriptor.outpoint`]: StaticPaymentOutputDescriptor::outpoint
992 pub fn sign_counterparty_payment_input<C: Signing>(&self, spend_tx: &Transaction, input_idx: usize, descriptor: &StaticPaymentOutputDescriptor, secp_ctx: &Secp256k1<C>) -> Result<Witness, ()> {
993 // TODO: We really should be taking the SigHashCache as a parameter here instead of
994 // spend_tx, but ideally the SigHashCache would expose the transaction's inputs read-only
995 // so that we can check them. This requires upstream rust-bitcoin changes (as well as
996 // bindings updates to support SigHashCache objects).
997 if spend_tx.input.len() <= input_idx { return Err(()); }
998 if !spend_tx.input[input_idx].script_sig.is_empty() { return Err(()); }
999 if spend_tx.input[input_idx].previous_output != descriptor.outpoint.into_bitcoin_outpoint() { return Err(()); }
1001 let remotepubkey = bitcoin::PublicKey::new(self.pubkeys().payment_point);
1002 // We cannot always assume that `channel_parameters` is set, so can't just call
1003 // `self.channel_parameters()` or anything that relies on it
1004 let supports_anchors_zero_fee_htlc_tx = self.channel_type_features()
1005 .map(|features| features.supports_anchors_zero_fee_htlc_tx())
1008 let witness_script = if supports_anchors_zero_fee_htlc_tx {
1009 chan_utils::get_to_countersignatory_with_anchors_redeemscript(&remotepubkey.inner)
1011 ScriptBuf::new_p2pkh(&remotepubkey.pubkey_hash())
1013 let sighash = hash_to_message!(&sighash::SighashCache::new(spend_tx).segwit_signature_hash(input_idx, &witness_script, descriptor.output.value, EcdsaSighashType::All).unwrap()[..]);
1014 let remotesig = sign_with_aux_rand(secp_ctx, &sighash, &self.payment_key, &self);
1015 let payment_script = if supports_anchors_zero_fee_htlc_tx {
1016 witness_script.to_v0_p2wsh()
1018 ScriptBuf::new_v0_p2wpkh(&remotepubkey.wpubkey_hash().unwrap())
1021 if payment_script != descriptor.output.script_pubkey { return Err(()); }
1023 let mut witness = Vec::with_capacity(2);
1024 witness.push(remotesig.serialize_der().to_vec());
1025 witness[0].push(EcdsaSighashType::All as u8);
1026 if supports_anchors_zero_fee_htlc_tx {
1027 witness.push(witness_script.to_bytes());
1029 witness.push(remotepubkey.to_bytes());
1034 /// Sign the single input of `spend_tx` at index `input_idx` which spends the output
1035 /// described by `descriptor`, returning the witness stack for the input.
1037 /// Returns an error if the input at `input_idx` does not exist, has a non-empty `script_sig`,
1038 /// is not spending the outpoint described by [`descriptor.outpoint`], does not have a
1039 /// sequence set to [`descriptor.to_self_delay`], or if an output descriptor
1040 /// `script_pubkey` does not match the one we can spend.
1042 /// [`descriptor.outpoint`]: DelayedPaymentOutputDescriptor::outpoint
1043 /// [`descriptor.to_self_delay`]: DelayedPaymentOutputDescriptor::to_self_delay
1044 pub fn sign_dynamic_p2wsh_input<C: Signing>(&self, spend_tx: &Transaction, input_idx: usize, descriptor: &DelayedPaymentOutputDescriptor, secp_ctx: &Secp256k1<C>) -> Result<Witness, ()> {
1045 // TODO: We really should be taking the SigHashCache as a parameter here instead of
1046 // spend_tx, but ideally the SigHashCache would expose the transaction's inputs read-only
1047 // so that we can check them. This requires upstream rust-bitcoin changes (as well as
1048 // bindings updates to support SigHashCache objects).
1049 if spend_tx.input.len() <= input_idx { return Err(()); }
1050 if !spend_tx.input[input_idx].script_sig.is_empty() { return Err(()); }
1051 if spend_tx.input[input_idx].previous_output != descriptor.outpoint.into_bitcoin_outpoint() { return Err(()); }
1052 if spend_tx.input[input_idx].sequence.0 != descriptor.to_self_delay as u32 { return Err(()); }
1054 let delayed_payment_key = chan_utils::derive_private_key(&secp_ctx, &descriptor.per_commitment_point, &self.delayed_payment_base_key);
1055 let delayed_payment_pubkey = DelayedPaymentKey::from_secret_key(&secp_ctx, &delayed_payment_key);
1056 let witness_script = chan_utils::get_revokeable_redeemscript(&descriptor.revocation_pubkey, descriptor.to_self_delay, &delayed_payment_pubkey);
1057 let sighash = hash_to_message!(&sighash::SighashCache::new(spend_tx).segwit_signature_hash(input_idx, &witness_script, descriptor.output.value, EcdsaSighashType::All).unwrap()[..]);
1058 let local_delayedsig = EcdsaSignature {
1059 sig: sign_with_aux_rand(secp_ctx, &sighash, &delayed_payment_key, &self),
1060 hash_ty: EcdsaSighashType::All,
1062 let payment_script = bitcoin::Address::p2wsh(&witness_script, Network::Bitcoin).script_pubkey();
1064 if descriptor.output.script_pubkey != payment_script { return Err(()); }
1066 Ok(Witness::from_slice(&[
1067 &local_delayedsig.serialize()[..],
1069 witness_script.as_bytes(),
1074 impl EntropySource for InMemorySigner {
1075 fn get_secure_random_bytes(&self) -> [u8; 32] {
1076 self.entropy_source.get_secure_random_bytes()
1080 impl ChannelSigner for InMemorySigner {
1081 fn get_per_commitment_point(&self, idx: u64, secp_ctx: &Secp256k1<secp256k1::All>) -> PublicKey {
1082 let commitment_secret = SecretKey::from_slice(&chan_utils::build_commitment_secret(&self.commitment_seed, idx)).unwrap();
1083 PublicKey::from_secret_key(secp_ctx, &commitment_secret)
1086 fn release_commitment_secret(&self, idx: u64) -> [u8; 32] {
1087 chan_utils::build_commitment_secret(&self.commitment_seed, idx)
1090 fn validate_holder_commitment(&self, _holder_tx: &HolderCommitmentTransaction, _outbound_htlc_preimages: Vec<PaymentPreimage>) -> Result<(), ()> {
1094 fn validate_counterparty_revocation(&self, _idx: u64, _secret: &SecretKey) -> Result<(), ()> {
1098 fn pubkeys(&self) -> &ChannelPublicKeys { &self.holder_channel_pubkeys }
1100 fn channel_keys_id(&self) -> [u8; 32] { self.channel_keys_id }
1102 fn provide_channel_parameters(&mut self, channel_parameters: &ChannelTransactionParameters) {
1103 assert!(self.channel_parameters.is_none() || self.channel_parameters.as_ref().unwrap() == channel_parameters);
1104 if self.channel_parameters.is_some() {
1105 // The channel parameters were already set and they match, return early.
1108 assert!(channel_parameters.is_populated(), "Channel parameters must be fully populated");
1109 self.channel_parameters = Some(channel_parameters.clone());
1113 const MISSING_PARAMS_ERR: &'static str = "ChannelSigner::provide_channel_parameters must be called before signing operations";
1115 impl EcdsaChannelSigner for InMemorySigner {
1116 fn sign_counterparty_commitment(&self, commitment_tx: &CommitmentTransaction, _inbound_htlc_preimages: Vec<PaymentPreimage>, _outbound_htlc_preimages: Vec<PaymentPreimage>, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<(Signature, Vec<Signature>), ()> {
1117 let trusted_tx = commitment_tx.trust();
1118 let keys = trusted_tx.keys();
1120 let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
1121 let counterparty_keys = self.counterparty_pubkeys().expect(MISSING_PARAMS_ERR);
1122 let channel_funding_redeemscript = make_funding_redeemscript(&funding_pubkey, &counterparty_keys.funding_pubkey);
1124 let built_tx = trusted_tx.built_transaction();
1125 let commitment_sig = built_tx.sign_counterparty_commitment(&self.funding_key, &channel_funding_redeemscript, self.channel_value_satoshis, secp_ctx);
1126 let commitment_txid = built_tx.txid;
1128 let mut htlc_sigs = Vec::with_capacity(commitment_tx.htlcs().len());
1129 for htlc in commitment_tx.htlcs() {
1130 let channel_parameters = self.get_channel_parameters().expect(MISSING_PARAMS_ERR);
1131 let holder_selected_contest_delay =
1132 self.holder_selected_contest_delay().expect(MISSING_PARAMS_ERR);
1133 let chan_type = &channel_parameters.channel_type_features;
1134 let htlc_tx = chan_utils::build_htlc_transaction(&commitment_txid, commitment_tx.feerate_per_kw(), holder_selected_contest_delay, htlc, chan_type, &keys.broadcaster_delayed_payment_key, &keys.revocation_key);
1135 let htlc_redeemscript = chan_utils::get_htlc_redeemscript(&htlc, chan_type, &keys);
1136 let htlc_sighashtype = if chan_type.supports_anchors_zero_fee_htlc_tx() { EcdsaSighashType::SinglePlusAnyoneCanPay } else { EcdsaSighashType::All };
1137 let htlc_sighash = hash_to_message!(&sighash::SighashCache::new(&htlc_tx).segwit_signature_hash(0, &htlc_redeemscript, htlc.amount_msat / 1000, htlc_sighashtype).unwrap()[..]);
1138 let holder_htlc_key = chan_utils::derive_private_key(&secp_ctx, &keys.per_commitment_point, &self.htlc_base_key);
1139 htlc_sigs.push(sign(secp_ctx, &htlc_sighash, &holder_htlc_key));
1142 Ok((commitment_sig, htlc_sigs))
1145 fn sign_holder_commitment(&self, commitment_tx: &HolderCommitmentTransaction, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<Signature, ()> {
1146 let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
1147 let counterparty_keys = self.counterparty_pubkeys().expect(MISSING_PARAMS_ERR);
1148 let funding_redeemscript = make_funding_redeemscript(&funding_pubkey, &counterparty_keys.funding_pubkey);
1149 let trusted_tx = commitment_tx.trust();
1150 Ok(trusted_tx.built_transaction().sign_holder_commitment(&self.funding_key, &funding_redeemscript, self.channel_value_satoshis, &self, secp_ctx))
1153 #[cfg(any(test,feature = "unsafe_revoked_tx_signing"))]
1154 fn unsafe_sign_holder_commitment(&self, commitment_tx: &HolderCommitmentTransaction, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<Signature, ()> {
1155 let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
1156 let counterparty_keys = self.counterparty_pubkeys().expect(MISSING_PARAMS_ERR);
1157 let funding_redeemscript = make_funding_redeemscript(&funding_pubkey, &counterparty_keys.funding_pubkey);
1158 let trusted_tx = commitment_tx.trust();
1159 Ok(trusted_tx.built_transaction().sign_holder_commitment(&self.funding_key, &funding_redeemscript, self.channel_value_satoshis, &self, secp_ctx))
1162 fn sign_justice_revoked_output(&self, justice_tx: &Transaction, input: usize, amount: u64, per_commitment_key: &SecretKey, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<Signature, ()> {
1163 let revocation_key = chan_utils::derive_private_revocation_key(&secp_ctx, &per_commitment_key, &self.revocation_base_key);
1164 let per_commitment_point = PublicKey::from_secret_key(secp_ctx, &per_commitment_key);
1165 let revocation_pubkey = RevocationKey::from_basepoint(
1166 &secp_ctx, &self.pubkeys().revocation_basepoint, &per_commitment_point,
1168 let witness_script = {
1169 let counterparty_keys = self.counterparty_pubkeys().expect(MISSING_PARAMS_ERR);
1170 let holder_selected_contest_delay =
1171 self.holder_selected_contest_delay().expect(MISSING_PARAMS_ERR);
1172 let counterparty_delayedpubkey = DelayedPaymentKey::from_basepoint(&secp_ctx, &counterparty_keys.delayed_payment_basepoint, &per_commitment_point);
1173 chan_utils::get_revokeable_redeemscript(&revocation_pubkey, holder_selected_contest_delay, &counterparty_delayedpubkey)
1175 let mut sighash_parts = sighash::SighashCache::new(justice_tx);
1176 let sighash = hash_to_message!(&sighash_parts.segwit_signature_hash(input, &witness_script, amount, EcdsaSighashType::All).unwrap()[..]);
1177 return Ok(sign_with_aux_rand(secp_ctx, &sighash, &revocation_key, &self))
1180 fn sign_justice_revoked_htlc(&self, justice_tx: &Transaction, input: usize, amount: u64, per_commitment_key: &SecretKey, htlc: &HTLCOutputInCommitment, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<Signature, ()> {
1181 let revocation_key = chan_utils::derive_private_revocation_key(&secp_ctx, &per_commitment_key, &self.revocation_base_key);
1182 let per_commitment_point = PublicKey::from_secret_key(secp_ctx, &per_commitment_key);
1183 let revocation_pubkey = RevocationKey::from_basepoint(
1184 &secp_ctx, &self.pubkeys().revocation_basepoint, &per_commitment_point,
1186 let witness_script = {
1187 let counterparty_keys = self.counterparty_pubkeys().expect(MISSING_PARAMS_ERR);
1188 let counterparty_htlcpubkey = HtlcKey::from_basepoint(
1189 &secp_ctx, &counterparty_keys.htlc_basepoint, &per_commitment_point,
1191 let holder_htlcpubkey = HtlcKey::from_basepoint(
1192 &secp_ctx, &self.pubkeys().htlc_basepoint, &per_commitment_point,
1194 let chan_type = self.channel_type_features().expect(MISSING_PARAMS_ERR);
1195 chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, chan_type, &counterparty_htlcpubkey, &holder_htlcpubkey, &revocation_pubkey)
1197 let mut sighash_parts = sighash::SighashCache::new(justice_tx);
1198 let sighash = hash_to_message!(&sighash_parts.segwit_signature_hash(input, &witness_script, amount, EcdsaSighashType::All).unwrap()[..]);
1199 return Ok(sign_with_aux_rand(secp_ctx, &sighash, &revocation_key, &self))
1202 fn sign_holder_htlc_transaction(
1203 &self, htlc_tx: &Transaction, input: usize, htlc_descriptor: &HTLCDescriptor,
1204 secp_ctx: &Secp256k1<secp256k1::All>
1205 ) -> Result<Signature, ()> {
1206 let witness_script = htlc_descriptor.witness_script(secp_ctx);
1207 let sighash = &sighash::SighashCache::new(&*htlc_tx).segwit_signature_hash(
1208 input, &witness_script, htlc_descriptor.htlc.amount_msat / 1000, EcdsaSighashType::All
1210 let our_htlc_private_key = chan_utils::derive_private_key(
1211 &secp_ctx, &htlc_descriptor.per_commitment_point, &self.htlc_base_key
1213 Ok(sign_with_aux_rand(&secp_ctx, &hash_to_message!(sighash.as_byte_array()), &our_htlc_private_key, &self))
1216 fn sign_counterparty_htlc_transaction(&self, htlc_tx: &Transaction, input: usize, amount: u64, per_commitment_point: &PublicKey, htlc: &HTLCOutputInCommitment, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<Signature, ()> {
1217 let htlc_key = chan_utils::derive_private_key(&secp_ctx, &per_commitment_point, &self.htlc_base_key);
1218 let revocation_pubkey = RevocationKey::from_basepoint(
1219 &secp_ctx, &self.pubkeys().revocation_basepoint, &per_commitment_point,
1221 let counterparty_keys = self.counterparty_pubkeys().expect(MISSING_PARAMS_ERR);
1222 let counterparty_htlcpubkey = HtlcKey::from_basepoint(
1223 &secp_ctx, &counterparty_keys.htlc_basepoint, &per_commitment_point,
1225 let htlcpubkey = HtlcKey::from_basepoint(&secp_ctx, &self.pubkeys().htlc_basepoint, &per_commitment_point);
1226 let chan_type = self.channel_type_features().expect(MISSING_PARAMS_ERR);
1227 let witness_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, chan_type, &counterparty_htlcpubkey, &htlcpubkey, &revocation_pubkey);
1228 let mut sighash_parts = sighash::SighashCache::new(htlc_tx);
1229 let sighash = hash_to_message!(&sighash_parts.segwit_signature_hash(input, &witness_script, amount, EcdsaSighashType::All).unwrap()[..]);
1230 Ok(sign_with_aux_rand(secp_ctx, &sighash, &htlc_key, &self))
1233 fn sign_closing_transaction(&self, closing_tx: &ClosingTransaction, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<Signature, ()> {
1234 let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
1235 let counterparty_funding_key = &self.counterparty_pubkeys().expect(MISSING_PARAMS_ERR).funding_pubkey;
1236 let channel_funding_redeemscript = make_funding_redeemscript(&funding_pubkey, counterparty_funding_key);
1237 Ok(closing_tx.trust().sign(&self.funding_key, &channel_funding_redeemscript, self.channel_value_satoshis, secp_ctx))
1240 fn sign_holder_anchor_input(
1241 &self, anchor_tx: &Transaction, input: usize, secp_ctx: &Secp256k1<secp256k1::All>,
1242 ) -> Result<Signature, ()> {
1243 let witness_script = chan_utils::get_anchor_redeemscript(&self.holder_channel_pubkeys.funding_pubkey);
1244 let sighash = sighash::SighashCache::new(&*anchor_tx).segwit_signature_hash(
1245 input, &witness_script, ANCHOR_OUTPUT_VALUE_SATOSHI, EcdsaSighashType::All,
1247 Ok(sign_with_aux_rand(secp_ctx, &hash_to_message!(&sighash[..]), &self.funding_key, &self))
1250 fn sign_channel_announcement_with_funding_key(
1251 &self, msg: &UnsignedChannelAnnouncement, secp_ctx: &Secp256k1<secp256k1::All>
1252 ) -> Result<Signature, ()> {
1253 let msghash = hash_to_message!(&Sha256dHash::hash(&msg.encode()[..])[..]);
1254 Ok(secp_ctx.sign_ecdsa(&msghash, &self.funding_key))
1259 impl TaprootChannelSigner for InMemorySigner {
1260 fn generate_local_nonce_pair(&self, commitment_number: u64, secp_ctx: &Secp256k1<All>) -> PublicNonce {
1264 fn partially_sign_counterparty_commitment(&self, counterparty_nonce: PublicNonce, commitment_tx: &CommitmentTransaction, inbound_htlc_preimages: Vec<PaymentPreimage>, outbound_htlc_preimages: Vec<PaymentPreimage>, secp_ctx: &Secp256k1<All>) -> Result<(PartialSignatureWithNonce, Vec<schnorr::Signature>), ()> {
1268 fn finalize_holder_commitment(&self, commitment_tx: &HolderCommitmentTransaction, counterparty_partial_signature: PartialSignatureWithNonce, secp_ctx: &Secp256k1<All>) -> Result<PartialSignature, ()> {
1272 fn sign_justice_revoked_output(&self, justice_tx: &Transaction, input: usize, amount: u64, per_commitment_key: &SecretKey, secp_ctx: &Secp256k1<All>) -> Result<schnorr::Signature, ()> {
1276 fn sign_justice_revoked_htlc(&self, justice_tx: &Transaction, input: usize, amount: u64, per_commitment_key: &SecretKey, htlc: &HTLCOutputInCommitment, secp_ctx: &Secp256k1<All>) -> Result<schnorr::Signature, ()> {
1280 fn sign_holder_htlc_transaction(&self, htlc_tx: &Transaction, input: usize, htlc_descriptor: &HTLCDescriptor, secp_ctx: &Secp256k1<All>) -> Result<schnorr::Signature, ()> {
1284 fn sign_counterparty_htlc_transaction(&self, htlc_tx: &Transaction, input: usize, amount: u64, per_commitment_point: &PublicKey, htlc: &HTLCOutputInCommitment, secp_ctx: &Secp256k1<All>) -> Result<schnorr::Signature, ()> {
1288 fn partially_sign_closing_transaction(&self, closing_tx: &ClosingTransaction, secp_ctx: &Secp256k1<All>) -> Result<PartialSignature, ()> {
1292 fn sign_holder_anchor_input(&self, anchor_tx: &Transaction, input: usize, secp_ctx: &Secp256k1<All>) -> Result<schnorr::Signature, ()> {
1297 const SERIALIZATION_VERSION: u8 = 1;
1299 const MIN_SERIALIZATION_VERSION: u8 = 1;
1301 impl WriteableEcdsaChannelSigner for InMemorySigner {}
1303 impl Writeable for InMemorySigner {
1304 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), Error> {
1305 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
1307 self.funding_key.write(writer)?;
1308 self.revocation_base_key.write(writer)?;
1309 self.payment_key.write(writer)?;
1310 self.delayed_payment_base_key.write(writer)?;
1311 self.htlc_base_key.write(writer)?;
1312 self.commitment_seed.write(writer)?;
1313 self.channel_parameters.write(writer)?;
1314 self.channel_value_satoshis.write(writer)?;
1315 self.channel_keys_id.write(writer)?;
1317 write_tlv_fields!(writer, {});
1323 impl<ES: Deref> ReadableArgs<ES> for InMemorySigner where ES::Target: EntropySource {
1324 fn read<R: io::Read>(reader: &mut R, entropy_source: ES) -> Result<Self, DecodeError> {
1325 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
1327 let funding_key = Readable::read(reader)?;
1328 let revocation_base_key = Readable::read(reader)?;
1329 let payment_key = Readable::read(reader)?;
1330 let delayed_payment_base_key = Readable::read(reader)?;
1331 let htlc_base_key = Readable::read(reader)?;
1332 let commitment_seed = Readable::read(reader)?;
1333 let counterparty_channel_data = Readable::read(reader)?;
1334 let channel_value_satoshis = Readable::read(reader)?;
1335 let secp_ctx = Secp256k1::signing_only();
1336 let holder_channel_pubkeys =
1337 InMemorySigner::make_holder_keys(&secp_ctx, &funding_key, &revocation_base_key,
1338 &payment_key, &delayed_payment_base_key, &htlc_base_key);
1339 let keys_id = Readable::read(reader)?;
1341 read_tlv_fields!(reader, {});
1345 revocation_base_key,
1347 delayed_payment_base_key,
1350 channel_value_satoshis,
1351 holder_channel_pubkeys,
1352 channel_parameters: counterparty_channel_data,
1353 channel_keys_id: keys_id,
1354 entropy_source: RandomBytes::new(entropy_source.get_secure_random_bytes()),
1359 /// Simple implementation of [`EntropySource`], [`NodeSigner`], and [`SignerProvider`] that takes a
1360 /// 32-byte seed for use as a BIP 32 extended key and derives keys from that.
1362 /// Your `node_id` is seed/0'.
1363 /// Unilateral closes may use seed/1'.
1364 /// Cooperative closes may use seed/2'.
1365 /// The two close keys may be needed to claim on-chain funds!
1367 /// This struct cannot be used for nodes that wish to support receiving phantom payments;
1368 /// [`PhantomKeysManager`] must be used instead.
1370 /// Note that switching between this struct and [`PhantomKeysManager`] will invalidate any
1371 /// previously issued invoices and attempts to pay previous invoices will fail.
1372 pub struct KeysManager {
1373 secp_ctx: Secp256k1<secp256k1::All>,
1374 node_secret: SecretKey,
1376 inbound_payment_key: KeyMaterial,
1377 destination_script: ScriptBuf,
1378 shutdown_pubkey: PublicKey,
1379 channel_master_key: ExtendedPrivKey,
1380 channel_child_index: AtomicUsize,
1382 entropy_source: RandomBytes,
1385 starting_time_secs: u64,
1386 starting_time_nanos: u32,
1390 /// Constructs a [`KeysManager`] from a 32-byte seed. If the seed is in some way biased (e.g.,
1391 /// your CSRNG is busted) this may panic (but more importantly, you will possibly lose funds).
1392 /// `starting_time` isn't strictly required to actually be a time, but it must absolutely,
1393 /// without a doubt, be unique to this instance. ie if you start multiple times with the same
1394 /// `seed`, `starting_time` must be unique to each run. Thus, the easiest way to achieve this
1395 /// is to simply use the current time (with very high precision).
1397 /// The `seed` MUST be backed up safely prior to use so that the keys can be re-created, however,
1398 /// obviously, `starting_time` should be unique every time you reload the library - it is only
1399 /// used to generate new ephemeral key data (which will be stored by the individual channel if
1402 /// Note that the seed is required to recover certain on-chain funds independent of
1403 /// [`ChannelMonitor`] data, though a current copy of [`ChannelMonitor`] data is also required
1404 /// for any channel, and some on-chain during-closing funds.
1406 /// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
1407 pub fn new(seed: &[u8; 32], starting_time_secs: u64, starting_time_nanos: u32) -> Self {
1408 let secp_ctx = Secp256k1::new();
1409 // Note that when we aren't serializing the key, network doesn't matter
1410 match ExtendedPrivKey::new_master(Network::Testnet, seed) {
1412 let node_secret = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(0).unwrap()).expect("Your RNG is busted").private_key;
1413 let node_id = PublicKey::from_secret_key(&secp_ctx, &node_secret);
1414 let destination_script = match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(1).unwrap()) {
1415 Ok(destination_key) => {
1416 let wpubkey_hash = WPubkeyHash::hash(&ExtendedPubKey::from_priv(&secp_ctx, &destination_key).to_pub().to_bytes());
1417 Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0)
1418 .push_slice(&wpubkey_hash.to_byte_array())
1421 Err(_) => panic!("Your RNG is busted"),
1423 let shutdown_pubkey = match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(2).unwrap()) {
1424 Ok(shutdown_key) => ExtendedPubKey::from_priv(&secp_ctx, &shutdown_key).public_key,
1425 Err(_) => panic!("Your RNG is busted"),
1427 let channel_master_key = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(3).unwrap()).expect("Your RNG is busted");
1428 let inbound_payment_key: SecretKey = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(5).unwrap()).expect("Your RNG is busted").private_key;
1429 let mut inbound_pmt_key_bytes = [0; 32];
1430 inbound_pmt_key_bytes.copy_from_slice(&inbound_payment_key[..]);
1432 let mut rand_bytes_engine = Sha256::engine();
1433 rand_bytes_engine.input(&starting_time_secs.to_be_bytes());
1434 rand_bytes_engine.input(&starting_time_nanos.to_be_bytes());
1435 rand_bytes_engine.input(seed);
1436 rand_bytes_engine.input(b"LDK PRNG Seed");
1437 let rand_bytes_unique_start = Sha256::from_engine(rand_bytes_engine).to_byte_array();
1439 let mut res = KeysManager {
1443 inbound_payment_key: KeyMaterial(inbound_pmt_key_bytes),
1449 channel_child_index: AtomicUsize::new(0),
1451 entropy_source: RandomBytes::new(rand_bytes_unique_start),
1455 starting_time_nanos,
1457 let secp_seed = res.get_secure_random_bytes();
1458 res.secp_ctx.seeded_randomize(&secp_seed);
1461 Err(_) => panic!("Your rng is busted"),
1465 /// Gets the "node_id" secret key used to sign gossip announcements, decode onion data, etc.
1466 pub fn get_node_secret_key(&self) -> SecretKey {
1470 /// Derive an old [`WriteableEcdsaChannelSigner`] containing per-channel secrets based on a key derivation parameters.
1471 pub fn derive_channel_keys(&self, channel_value_satoshis: u64, params: &[u8; 32]) -> InMemorySigner {
1472 let chan_id = u64::from_be_bytes(params[0..8].try_into().unwrap());
1473 let mut unique_start = Sha256::engine();
1474 unique_start.input(params);
1475 unique_start.input(&self.seed);
1477 // We only seriously intend to rely on the channel_master_key for true secure
1478 // entropy, everything else just ensures uniqueness. We rely on the unique_start (ie
1479 // starting_time provided in the constructor) to be unique.
1480 let child_privkey = self.channel_master_key.ckd_priv(&self.secp_ctx,
1481 ChildNumber::from_hardened_idx((chan_id as u32) % (1 << 31)).expect("key space exhausted")
1482 ).expect("Your RNG is busted");
1483 unique_start.input(&child_privkey.private_key[..]);
1485 let seed = Sha256::from_engine(unique_start).to_byte_array();
1487 let commitment_seed = {
1488 let mut sha = Sha256::engine();
1490 sha.input(&b"commitment seed"[..]);
1491 Sha256::from_engine(sha).to_byte_array()
1493 macro_rules! key_step {
1494 ($info: expr, $prev_key: expr) => {{
1495 let mut sha = Sha256::engine();
1497 sha.input(&$prev_key[..]);
1498 sha.input(&$info[..]);
1499 SecretKey::from_slice(&Sha256::from_engine(sha).to_byte_array()).expect("SHA-256 is busted")
1502 let funding_key = key_step!(b"funding key", commitment_seed);
1503 let revocation_base_key = key_step!(b"revocation base key", funding_key);
1504 let payment_key = key_step!(b"payment key", revocation_base_key);
1505 let delayed_payment_base_key = key_step!(b"delayed payment base key", payment_key);
1506 let htlc_base_key = key_step!(b"HTLC base key", delayed_payment_base_key);
1507 let prng_seed = self.get_secure_random_bytes();
1509 InMemorySigner::new(
1512 revocation_base_key,
1514 delayed_payment_base_key,
1517 channel_value_satoshis,
1523 /// Signs the given [`PartiallySignedTransaction`] which spends the given [`SpendableOutputDescriptor`]s.
1524 /// The resulting inputs will be finalized and the PSBT will be ready for broadcast if there
1525 /// are no other inputs that need signing.
1527 /// Returns `Err(())` if the PSBT is missing a descriptor or if we fail to sign.
1529 /// May panic if the [`SpendableOutputDescriptor`]s were not generated by channels which used
1530 /// this [`KeysManager`] or one of the [`InMemorySigner`] created by this [`KeysManager`].
1531 pub fn sign_spendable_outputs_psbt<C: Signing>(&self, descriptors: &[&SpendableOutputDescriptor], mut psbt: PartiallySignedTransaction, secp_ctx: &Secp256k1<C>) -> Result<PartiallySignedTransaction, ()> {
1532 let mut keys_cache: Option<(InMemorySigner, [u8; 32])> = None;
1533 for outp in descriptors {
1535 SpendableOutputDescriptor::StaticPaymentOutput(descriptor) => {
1536 let input_idx = psbt.unsigned_tx.input.iter().position(|i| i.previous_output == descriptor.outpoint.into_bitcoin_outpoint()).ok_or(())?;
1537 if keys_cache.is_none() || keys_cache.as_ref().unwrap().1 != descriptor.channel_keys_id {
1538 let mut signer = self.derive_channel_keys(descriptor.channel_value_satoshis, &descriptor.channel_keys_id);
1539 if let Some(channel_params) = descriptor.channel_transaction_parameters.as_ref() {
1540 signer.provide_channel_parameters(channel_params);
1542 keys_cache = Some((signer, descriptor.channel_keys_id));
1544 let witness = keys_cache.as_ref().unwrap().0.sign_counterparty_payment_input(&psbt.unsigned_tx, input_idx, &descriptor, &secp_ctx)?;
1545 psbt.inputs[input_idx].final_script_witness = Some(witness);
1547 SpendableOutputDescriptor::DelayedPaymentOutput(descriptor) => {
1548 let input_idx = psbt.unsigned_tx.input.iter().position(|i| i.previous_output == descriptor.outpoint.into_bitcoin_outpoint()).ok_or(())?;
1549 if keys_cache.is_none() || keys_cache.as_ref().unwrap().1 != descriptor.channel_keys_id {
1551 self.derive_channel_keys(descriptor.channel_value_satoshis, &descriptor.channel_keys_id),
1552 descriptor.channel_keys_id));
1554 let witness = keys_cache.as_ref().unwrap().0.sign_dynamic_p2wsh_input(&psbt.unsigned_tx, input_idx, &descriptor, &secp_ctx)?;
1555 psbt.inputs[input_idx].final_script_witness = Some(witness);
1557 SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output, .. } => {
1558 let input_idx = psbt.unsigned_tx.input.iter().position(|i| i.previous_output == outpoint.into_bitcoin_outpoint()).ok_or(())?;
1559 let derivation_idx = if output.script_pubkey == self.destination_script {
1565 // Note that when we aren't serializing the key, network doesn't matter
1566 match ExtendedPrivKey::new_master(Network::Testnet, &self.seed) {
1568 match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(derivation_idx).expect("key space exhausted")) {
1570 Err(_) => panic!("Your RNG is busted"),
1573 Err(_) => panic!("Your rng is busted"),
1576 let pubkey = ExtendedPubKey::from_priv(&secp_ctx, &secret).to_pub();
1577 if derivation_idx == 2 {
1578 assert_eq!(pubkey.inner, self.shutdown_pubkey);
1580 let witness_script = bitcoin::Address::p2pkh(&pubkey, Network::Testnet).script_pubkey();
1581 let payment_script = bitcoin::Address::p2wpkh(&pubkey, Network::Testnet).expect("uncompressed key found").script_pubkey();
1583 if payment_script != output.script_pubkey { return Err(()); };
1585 let sighash = hash_to_message!(&sighash::SighashCache::new(&psbt.unsigned_tx).segwit_signature_hash(input_idx, &witness_script, output.value, EcdsaSighashType::All).unwrap()[..]);
1586 let sig = sign_with_aux_rand(secp_ctx, &sighash, &secret.private_key, &self);
1587 let mut sig_ser = sig.serialize_der().to_vec();
1588 sig_ser.push(EcdsaSighashType::All as u8);
1589 let witness = Witness::from_slice(&[&sig_ser, &pubkey.inner.serialize().to_vec()]);
1590 psbt.inputs[input_idx].final_script_witness = Some(witness);
1598 /// Creates a [`Transaction`] which spends the given descriptors to the given outputs, plus an
1599 /// output to the given change destination (if sufficient change value remains). The
1600 /// transaction will have a feerate, at least, of the given value.
1602 /// The `locktime` argument is used to set the transaction's locktime. If `None`, the
1603 /// transaction will have a locktime of 0. It it recommended to set this to the current block
1604 /// height to avoid fee sniping, unless you have some specific reason to use a different
1607 /// Returns `Err(())` if the output value is greater than the input value minus required fee,
1608 /// if a descriptor was duplicated, or if an output descriptor `script_pubkey`
1609 /// does not match the one we can spend.
1611 /// We do not enforce that outputs meet the dust limit or that any output scripts are standard.
1613 /// May panic if the [`SpendableOutputDescriptor`]s were not generated by channels which used
1614 /// this [`KeysManager`] or one of the [`InMemorySigner`] created by this [`KeysManager`].
1615 pub fn spend_spendable_outputs<C: Signing>(&self, descriptors: &[&SpendableOutputDescriptor], outputs: Vec<TxOut>, change_destination_script: ScriptBuf, feerate_sat_per_1000_weight: u32, locktime: Option<LockTime>, secp_ctx: &Secp256k1<C>) -> Result<Transaction, ()> {
1616 let (mut psbt, expected_max_weight) = SpendableOutputDescriptor::create_spendable_outputs_psbt(descriptors, outputs, change_destination_script, feerate_sat_per_1000_weight, locktime)?;
1617 psbt = self.sign_spendable_outputs_psbt(descriptors, psbt, secp_ctx)?;
1619 let spend_tx = psbt.extract_tx();
1621 debug_assert!(expected_max_weight >= spend_tx.weight().to_wu());
1622 // Note that witnesses with a signature vary somewhat in size, so allow
1623 // `expected_max_weight` to overshoot by up to 3 bytes per input.
1624 debug_assert!(expected_max_weight <= spend_tx.weight().to_wu() + descriptors.len() as u64 * 3);
1630 impl EntropySource for KeysManager {
1631 fn get_secure_random_bytes(&self) -> [u8; 32] {
1632 self.entropy_source.get_secure_random_bytes()
1636 impl NodeSigner for KeysManager {
1637 fn get_node_id(&self, recipient: Recipient) -> Result<PublicKey, ()> {
1639 Recipient::Node => Ok(self.node_id.clone()),
1640 Recipient::PhantomNode => Err(())
1644 fn ecdh(&self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&Scalar>) -> Result<SharedSecret, ()> {
1645 let mut node_secret = match recipient {
1646 Recipient::Node => Ok(self.node_secret.clone()),
1647 Recipient::PhantomNode => Err(())
1649 if let Some(tweak) = tweak {
1650 node_secret = node_secret.mul_tweak(tweak).map_err(|_| ())?;
1652 Ok(SharedSecret::new(other_key, &node_secret))
1655 fn get_inbound_payment_key_material(&self) -> KeyMaterial {
1656 self.inbound_payment_key.clone()
1659 fn sign_invoice(&self, hrp_bytes: &[u8], invoice_data: &[u5], recipient: Recipient) -> Result<RecoverableSignature, ()> {
1660 let preimage = construct_invoice_preimage(&hrp_bytes, &invoice_data);
1661 let secret = match recipient {
1662 Recipient::Node => Ok(&self.node_secret),
1663 Recipient::PhantomNode => Err(())
1665 Ok(self.secp_ctx.sign_ecdsa_recoverable(&hash_to_message!(&Sha256::hash(&preimage).to_byte_array()), secret))
1668 fn sign_bolt12_invoice_request(
1669 &self, invoice_request: &UnsignedInvoiceRequest
1670 ) -> Result<schnorr::Signature, ()> {
1671 let message = invoice_request.tagged_hash().as_digest();
1672 let keys = KeyPair::from_secret_key(&self.secp_ctx, &self.node_secret);
1673 let aux_rand = self.get_secure_random_bytes();
1674 Ok(self.secp_ctx.sign_schnorr_with_aux_rand(message, &keys, &aux_rand))
1677 fn sign_bolt12_invoice(
1678 &self, invoice: &UnsignedBolt12Invoice
1679 ) -> Result<schnorr::Signature, ()> {
1680 let message = invoice.tagged_hash().as_digest();
1681 let keys = KeyPair::from_secret_key(&self.secp_ctx, &self.node_secret);
1682 let aux_rand = self.get_secure_random_bytes();
1683 Ok(self.secp_ctx.sign_schnorr_with_aux_rand(message, &keys, &aux_rand))
1686 fn sign_gossip_message(&self, msg: UnsignedGossipMessage) -> Result<Signature, ()> {
1687 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.encode()[..])[..]);
1688 Ok(self.secp_ctx.sign_ecdsa(&msg_hash, &self.node_secret))
1692 impl SignerProvider for KeysManager {
1693 type EcdsaSigner = InMemorySigner;
1695 type TaprootSigner = InMemorySigner;
1697 fn generate_channel_keys_id(&self, _inbound: bool, _channel_value_satoshis: u64, user_channel_id: u128) -> [u8; 32] {
1698 let child_idx = self.channel_child_index.fetch_add(1, Ordering::AcqRel);
1699 // `child_idx` is the only thing guaranteed to make each channel unique without a restart
1700 // (though `user_channel_id` should help, depending on user behavior). If it manages to
1701 // roll over, we may generate duplicate keys for two different channels, which could result
1702 // in loss of funds. Because we only support 32-bit+ systems, assert that our `AtomicUsize`
1703 // doesn't reach `u32::MAX`.
1704 assert!(child_idx < core::u32::MAX as usize, "2^32 channels opened without restart");
1705 let mut id = [0; 32];
1706 id[0..4].copy_from_slice(&(child_idx as u32).to_be_bytes());
1707 id[4..8].copy_from_slice(&self.starting_time_nanos.to_be_bytes());
1708 id[8..16].copy_from_slice(&self.starting_time_secs.to_be_bytes());
1709 id[16..32].copy_from_slice(&user_channel_id.to_be_bytes());
1713 fn derive_channel_signer(&self, channel_value_satoshis: u64, channel_keys_id: [u8; 32]) -> Self::EcdsaSigner {
1714 self.derive_channel_keys(channel_value_satoshis, &channel_keys_id)
1717 fn read_chan_signer(&self, reader: &[u8]) -> Result<Self::EcdsaSigner, DecodeError> {
1718 InMemorySigner::read(&mut io::Cursor::new(reader), self)
1721 fn get_destination_script(&self, _channel_keys_id: [u8; 32]) -> Result<ScriptBuf, ()> {
1722 Ok(self.destination_script.clone())
1725 fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()> {
1726 Ok(ShutdownScript::new_p2wpkh_from_pubkey(self.shutdown_pubkey.clone()))
1730 /// Similar to [`KeysManager`], but allows the node using this struct to receive phantom node
1733 /// A phantom node payment is a payment made to a phantom invoice, which is an invoice that can be
1734 /// paid to one of multiple nodes. This works because we encode the invoice route hints such that
1735 /// LDK will recognize an incoming payment as destined for a phantom node, and collect the payment
1736 /// itself without ever needing to forward to this fake node.
1738 /// Phantom node payments are useful for load balancing between multiple LDK nodes. They also
1739 /// provide some fault tolerance, because payers will automatically retry paying other provided
1740 /// nodes in the case that one node goes down.
1742 /// Note that multi-path payments are not supported in phantom invoices for security reasons.
1743 // In the hypothetical case that we did support MPP phantom payments, there would be no way for
1744 // nodes to know when the full payment has been received (and the preimage can be released) without
1745 // significantly compromising on our safety guarantees. I.e., if we expose the ability for the user
1746 // to tell LDK when the preimage can be released, we open ourselves to attacks where the preimage
1747 // is released too early.
1749 /// Switching between this struct and [`KeysManager`] will invalidate any previously issued
1750 /// invoices and attempts to pay previous invoices will fail.
1751 pub struct PhantomKeysManager {
1753 inbound_payment_key: KeyMaterial,
1754 phantom_secret: SecretKey,
1755 phantom_node_id: PublicKey,
1758 impl EntropySource for PhantomKeysManager {
1759 fn get_secure_random_bytes(&self) -> [u8; 32] {
1760 self.inner.get_secure_random_bytes()
1764 impl NodeSigner for PhantomKeysManager {
1765 fn get_node_id(&self, recipient: Recipient) -> Result<PublicKey, ()> {
1767 Recipient::Node => self.inner.get_node_id(Recipient::Node),
1768 Recipient::PhantomNode => Ok(self.phantom_node_id.clone()),
1772 fn ecdh(&self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&Scalar>) -> Result<SharedSecret, ()> {
1773 let mut node_secret = match recipient {
1774 Recipient::Node => self.inner.node_secret.clone(),
1775 Recipient::PhantomNode => self.phantom_secret.clone(),
1777 if let Some(tweak) = tweak {
1778 node_secret = node_secret.mul_tweak(tweak).map_err(|_| ())?;
1780 Ok(SharedSecret::new(other_key, &node_secret))
1783 fn get_inbound_payment_key_material(&self) -> KeyMaterial {
1784 self.inbound_payment_key.clone()
1787 fn sign_invoice(&self, hrp_bytes: &[u8], invoice_data: &[u5], recipient: Recipient) -> Result<RecoverableSignature, ()> {
1788 let preimage = construct_invoice_preimage(&hrp_bytes, &invoice_data);
1789 let secret = match recipient {
1790 Recipient::Node => &self.inner.node_secret,
1791 Recipient::PhantomNode => &self.phantom_secret,
1793 Ok(self.inner.secp_ctx.sign_ecdsa_recoverable(&hash_to_message!(&Sha256::hash(&preimage).to_byte_array()), secret))
1796 fn sign_bolt12_invoice_request(
1797 &self, invoice_request: &UnsignedInvoiceRequest
1798 ) -> Result<schnorr::Signature, ()> {
1799 self.inner.sign_bolt12_invoice_request(invoice_request)
1802 fn sign_bolt12_invoice(
1803 &self, invoice: &UnsignedBolt12Invoice
1804 ) -> Result<schnorr::Signature, ()> {
1805 self.inner.sign_bolt12_invoice(invoice)
1808 fn sign_gossip_message(&self, msg: UnsignedGossipMessage) -> Result<Signature, ()> {
1809 self.inner.sign_gossip_message(msg)
1813 impl SignerProvider for PhantomKeysManager {
1814 type EcdsaSigner = InMemorySigner;
1816 type TaprootSigner = InMemorySigner;
1818 fn generate_channel_keys_id(&self, inbound: bool, channel_value_satoshis: u64, user_channel_id: u128) -> [u8; 32] {
1819 self.inner.generate_channel_keys_id(inbound, channel_value_satoshis, user_channel_id)
1822 fn derive_channel_signer(&self, channel_value_satoshis: u64, channel_keys_id: [u8; 32]) -> Self::EcdsaSigner {
1823 self.inner.derive_channel_signer(channel_value_satoshis, channel_keys_id)
1826 fn read_chan_signer(&self, reader: &[u8]) -> Result<Self::EcdsaSigner, DecodeError> {
1827 self.inner.read_chan_signer(reader)
1830 fn get_destination_script(&self, channel_keys_id: [u8; 32]) -> Result<ScriptBuf, ()> {
1831 self.inner.get_destination_script(channel_keys_id)
1834 fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()> {
1835 self.inner.get_shutdown_scriptpubkey()
1839 impl PhantomKeysManager {
1840 /// Constructs a [`PhantomKeysManager`] given a 32-byte seed and an additional `cross_node_seed`
1841 /// that is shared across all nodes that intend to participate in [phantom node payments]
1844 /// See [`KeysManager::new`] for more information on `seed`, `starting_time_secs`, and
1845 /// `starting_time_nanos`.
1847 /// `cross_node_seed` must be the same across all phantom payment-receiving nodes and also the
1848 /// same across restarts, or else inbound payments may fail.
1850 /// [phantom node payments]: PhantomKeysManager
1851 pub fn new(seed: &[u8; 32], starting_time_secs: u64, starting_time_nanos: u32, cross_node_seed: &[u8; 32]) -> Self {
1852 let inner = KeysManager::new(seed, starting_time_secs, starting_time_nanos);
1853 let (inbound_key, phantom_key) = hkdf_extract_expand_twice(b"LDK Inbound and Phantom Payment Key Expansion", cross_node_seed);
1854 let phantom_secret = SecretKey::from_slice(&phantom_key).unwrap();
1855 let phantom_node_id = PublicKey::from_secret_key(&inner.secp_ctx, &phantom_secret);
1858 inbound_payment_key: KeyMaterial(inbound_key),
1864 /// See [`KeysManager::spend_spendable_outputs`] for documentation on this method.
1865 pub fn spend_spendable_outputs<C: Signing>(&self, descriptors: &[&SpendableOutputDescriptor], outputs: Vec<TxOut>, change_destination_script: ScriptBuf, feerate_sat_per_1000_weight: u32, locktime: Option<LockTime>, secp_ctx: &Secp256k1<C>) -> Result<Transaction, ()> {
1866 self.inner.spend_spendable_outputs(descriptors, outputs, change_destination_script, feerate_sat_per_1000_weight, locktime, secp_ctx)
1869 /// See [`KeysManager::derive_channel_keys`] for documentation on this method.
1870 pub fn derive_channel_keys(&self, channel_value_satoshis: u64, params: &[u8; 32]) -> InMemorySigner {
1871 self.inner.derive_channel_keys(channel_value_satoshis, params)
1874 /// Gets the "node_id" secret key used to sign gossip announcements, decode onion data, etc.
1875 pub fn get_node_secret_key(&self) -> SecretKey {
1876 self.inner.get_node_secret_key()
1879 /// Gets the "node_id" secret key of the phantom node used to sign invoices, decode the
1880 /// last-hop onion data, etc.
1881 pub fn get_phantom_node_secret_key(&self) -> SecretKey {
1886 /// An implementation of [`EntropySource`] using ChaCha20.
1888 pub struct RandomBytes {
1889 /// Seed from which all randomness produced is derived from.
1891 /// Tracks the number of times we've produced randomness to ensure we don't return the same
1893 index: AtomicCounter,
1897 /// Creates a new instance using the given seed.
1898 pub fn new(seed: [u8; 32]) -> Self {
1901 index: AtomicCounter::new(),
1906 impl EntropySource for RandomBytes {
1907 fn get_secure_random_bytes(&self) -> [u8; 32] {
1908 let index = self.index.get_increment();
1909 let mut nonce = [0u8; 16];
1910 nonce[..8].copy_from_slice(&index.to_be_bytes());
1911 ChaCha20::get_single_block(&self.seed, &nonce)
1915 // Ensure that EcdsaChannelSigner can have a vtable
1918 let _signer: Box<dyn EcdsaChannelSigner>;
1923 use std::sync::{Arc, mpsc};
1924 use std::sync::mpsc::TryRecvError;
1926 use std::time::Duration;
1927 use bitcoin::blockdata::constants::genesis_block;
1928 use bitcoin::Network;
1929 use crate::sign::{EntropySource, KeysManager};
1931 use criterion::Criterion;
1933 pub fn bench_get_secure_random_bytes(bench: &mut Criterion) {
1934 let seed = [0u8; 32];
1935 let now = Duration::from_secs(genesis_block(Network::Testnet).header.time as u64);
1936 let keys_manager = Arc::new(KeysManager::new(&seed, now.as_secs(), now.subsec_micros()));
1938 let mut handles = Vec::new();
1939 let mut stops = Vec::new();
1941 let keys_manager_clone = Arc::clone(&keys_manager);
1942 let (stop_sender, stop_receiver) = mpsc::channel();
1943 let handle = thread::spawn(move || {
1945 keys_manager_clone.get_secure_random_bytes();
1946 match stop_receiver.try_recv() {
1947 Ok(_) | Err(TryRecvError::Disconnected) => {
1948 println!("Terminating.");
1951 Err(TryRecvError::Empty) => {}
1955 handles.push(handle);
1956 stops.push(stop_sender);
1959 bench.bench_function("get_secure_random_bytes", |b| b.iter(||
1960 keys_manager.get_secure_random_bytes()));
1963 let _ = stop.send(());
1965 for handle in handles {
1966 handle.join().unwrap();