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.channel_type_features.supports_anchors_zero_fee_htlc_tx() {
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()
173 .map(|channel_params| channel_params.channel_type_features.supports_anchors_zero_fee_htlc_tx())
176 let witness_script_weight = 1 /* pubkey push */ + 33 /* pubkey */ +
177 1 /* OP_CHECKSIGVERIFY */ + 1 /* OP_1 */ + 1 /* OP_CHECKSEQUENCEVERIFY */;
178 1 /* num witness items */ + 1 /* sig push */ + 73 /* sig including sighash flag */ +
179 1 /* witness script push */ + witness_script_weight
181 P2WPKH_WITNESS_WEIGHT
185 impl_writeable_tlv_based!(StaticPaymentOutputDescriptor, {
186 (0, outpoint, required),
187 (2, output, required),
188 (4, channel_keys_id, required),
189 (6, channel_value_satoshis, required),
190 (7, channel_transaction_parameters, option),
193 /// Describes the necessary information to spend a spendable output.
195 /// When on-chain outputs are created by LDK (which our counterparty is not able to claim at any
196 /// point in the future) a [`SpendableOutputs`] event is generated which you must track and be able
197 /// to spend on-chain. The information needed to do this is provided in this enum, including the
198 /// outpoint describing which `txid` and output `index` is available, the full output which exists
199 /// at that `txid`/`index`, and any keys or other information required to sign.
201 /// [`SpendableOutputs`]: crate::events::Event::SpendableOutputs
202 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
203 pub enum SpendableOutputDescriptor {
204 /// An output to a script which was provided via [`SignerProvider`] directly, either from
205 /// [`get_destination_script`] or [`get_shutdown_scriptpubkey`], thus you should already
206 /// know how to spend it. No secret keys are provided as LDK was never given any key.
207 /// These may include outputs from a transaction punishing our counterparty or claiming an HTLC
208 /// on-chain using the payment preimage or after it has timed out.
210 /// [`get_shutdown_scriptpubkey`]: SignerProvider::get_shutdown_scriptpubkey
211 /// [`get_destination_script`]: SignerProvider::get_shutdown_scriptpubkey
213 /// The outpoint which is spendable.
215 /// The output which is referenced by the given outpoint.
217 /// The `channel_keys_id` for the channel which this output came from.
219 /// For channels which were generated on LDK 0.0.119 or later, this is the value which was
220 /// passed to the [`SignerProvider::get_destination_script`] call which provided this
223 /// For channels which were generated prior to LDK 0.0.119, no such argument existed,
224 /// however this field may still be filled in if such data is available.
225 channel_keys_id: Option<[u8; 32]>
227 /// An output to a P2WSH script which can be spent with a single signature after an `OP_CSV`
230 /// The witness in the spending input should be:
232 /// <BIP 143 signature> <empty vector> (MINIMALIF standard rule) <provided witnessScript>
235 /// Note that the `nSequence` field in the spending input must be set to
236 /// [`DelayedPaymentOutputDescriptor::to_self_delay`] (which means the transaction is not
237 /// broadcastable until at least [`DelayedPaymentOutputDescriptor::to_self_delay`] blocks after
238 /// the outpoint confirms, see [BIP
239 /// 68](https://github.com/bitcoin/bips/blob/master/bip-0068.mediawiki)). Also note that LDK
240 /// won't generate a [`SpendableOutputDescriptor`] until the corresponding block height
243 /// These are generally the result of a "revocable" output to us, spendable only by us unless
244 /// it is an output from an old state which we broadcast (which should never happen).
246 /// To derive the delayed payment key which is used to sign this input, you must pass the
247 /// holder [`InMemorySigner::delayed_payment_base_key`] (i.e., the private key which corresponds to the
248 /// [`ChannelPublicKeys::delayed_payment_basepoint`] in [`ChannelSigner::pubkeys`]) and the provided
249 /// [`DelayedPaymentOutputDescriptor::per_commitment_point`] to [`chan_utils::derive_private_key`]. The DelayedPaymentKey can be
250 /// generated without the secret key using [`DelayedPaymentKey::from_basepoint`] and only the
251 /// [`ChannelPublicKeys::delayed_payment_basepoint`] which appears in [`ChannelSigner::pubkeys`].
253 /// To derive the [`DelayedPaymentOutputDescriptor::revocation_pubkey`] provided here (which is
254 /// used in the witness script generation), you must pass the counterparty
255 /// [`ChannelPublicKeys::revocation_basepoint`] (which appears in the call to
256 /// [`ChannelSigner::provide_channel_parameters`]) and the provided
257 /// [`DelayedPaymentOutputDescriptor::per_commitment_point`] to
258 /// [`RevocationKey`].
260 /// The witness script which is hashed and included in the output `script_pubkey` may be
261 /// regenerated by passing the [`DelayedPaymentOutputDescriptor::revocation_pubkey`] (derived
262 /// as explained above), our delayed payment pubkey (derived as explained above), and the
263 /// [`DelayedPaymentOutputDescriptor::to_self_delay`] contained here to
264 /// [`chan_utils::get_revokeable_redeemscript`].
265 DelayedPaymentOutput(DelayedPaymentOutputDescriptor),
266 /// An output spendable exclusively by our payment key (i.e., the private key that corresponds
267 /// to the `payment_point` in [`ChannelSigner::pubkeys`]). The output type depends on the
268 /// channel type negotiated.
270 /// On an anchor outputs channel, the witness in the spending input is:
272 /// <BIP 143 signature> <witness script>
275 /// Otherwise, it is:
277 /// <BIP 143 signature> <payment key>
280 /// These are generally the result of our counterparty having broadcast the current state,
281 /// allowing us to claim the non-HTLC-encumbered outputs immediately, or after one confirmation
282 /// in the case of anchor outputs channels.
283 StaticPaymentOutput(StaticPaymentOutputDescriptor),
286 impl_writeable_tlv_based_enum!(SpendableOutputDescriptor,
287 (0, StaticOutput) => {
288 (0, outpoint, required),
289 (1, channel_keys_id, option),
290 (2, output, required),
293 (1, DelayedPaymentOutput),
294 (2, StaticPaymentOutput),
297 impl SpendableOutputDescriptor {
298 /// Turns this into a [`bitcoin::psbt::Input`] which can be used to create a
299 /// [`PartiallySignedTransaction`] which spends the given descriptor.
301 /// Note that this does not include any signatures, just the information required to
302 /// construct the transaction and sign it.
304 /// This is not exported to bindings users as there is no standard serialization for an input.
305 /// See [`Self::create_spendable_outputs_psbt`] instead.
306 pub fn to_psbt_input(&self) -> bitcoin::psbt::Input {
308 SpendableOutputDescriptor::StaticOutput { output, .. } => {
309 // Is a standard P2WPKH, no need for witness script
310 bitcoin::psbt::Input {
311 witness_utxo: Some(output.clone()),
315 SpendableOutputDescriptor::DelayedPaymentOutput(descriptor) => {
316 // TODO we could add the witness script as well
317 bitcoin::psbt::Input {
318 witness_utxo: Some(descriptor.output.clone()),
322 SpendableOutputDescriptor::StaticPaymentOutput(descriptor) => {
323 // TODO we could add the witness script as well
324 bitcoin::psbt::Input {
325 witness_utxo: Some(descriptor.output.clone()),
332 /// Creates an unsigned [`PartiallySignedTransaction`] which spends the given descriptors to
333 /// the given outputs, plus an output to the given change destination (if sufficient
334 /// change value remains). The PSBT will have a feerate, at least, of the given value.
336 /// The `locktime` argument is used to set the transaction's locktime. If `None`, the
337 /// transaction will have a locktime of 0. It it recommended to set this to the current block
338 /// height to avoid fee sniping, unless you have some specific reason to use a different
341 /// Returns the PSBT and expected max transaction weight.
343 /// Returns `Err(())` if the output value is greater than the input value minus required fee,
344 /// if a descriptor was duplicated, or if an output descriptor `script_pubkey`
345 /// does not match the one we can spend.
347 /// We do not enforce that outputs meet the dust limit or that any output scripts are standard.
348 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), ()> {
349 let mut input = Vec::with_capacity(descriptors.len());
350 let mut input_value = 0;
351 let mut witness_weight = 0;
352 let mut output_set = hash_set_with_capacity(descriptors.len());
353 for outp in descriptors {
355 SpendableOutputDescriptor::StaticPaymentOutput(descriptor) => {
356 if !output_set.insert(descriptor.outpoint) { return Err(()); }
358 if descriptor.channel_transaction_parameters.as_ref()
359 .map(|channel_params| channel_params.channel_type_features.supports_anchors_zero_fee_htlc_tx())
362 Sequence::from_consensus(1)
367 previous_output: descriptor.outpoint.into_bitcoin_outpoint(),
368 script_sig: ScriptBuf::new(),
370 witness: Witness::new(),
372 witness_weight += descriptor.max_witness_length();
373 #[cfg(feature = "grind_signatures")]
374 { witness_weight -= 1; } // Guarantees a low R signature
375 input_value += descriptor.output.value;
377 SpendableOutputDescriptor::DelayedPaymentOutput(descriptor) => {
378 if !output_set.insert(descriptor.outpoint) { return Err(()); }
380 previous_output: descriptor.outpoint.into_bitcoin_outpoint(),
381 script_sig: ScriptBuf::new(),
382 sequence: Sequence(descriptor.to_self_delay as u32),
383 witness: Witness::new(),
385 witness_weight += DelayedPaymentOutputDescriptor::MAX_WITNESS_LENGTH;
386 #[cfg(feature = "grind_signatures")]
387 { witness_weight -= 1; } // Guarantees a low R signature
388 input_value += descriptor.output.value;
390 SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output, .. } => {
391 if !output_set.insert(*outpoint) { return Err(()); }
393 previous_output: outpoint.into_bitcoin_outpoint(),
394 script_sig: ScriptBuf::new(),
395 sequence: Sequence::ZERO,
396 witness: Witness::new(),
398 witness_weight += 1 + 73 + 34;
399 #[cfg(feature = "grind_signatures")]
400 { witness_weight -= 1; } // Guarantees a low R signature
401 input_value += output.value;
404 if input_value > MAX_VALUE_MSAT / 1000 { return Err(()); }
406 let mut tx = Transaction {
408 lock_time: locktime.unwrap_or(LockTime::ZERO),
412 let expected_max_weight =
413 transaction_utils::maybe_add_change_output(&mut tx, input_value, witness_weight, feerate_sat_per_1000_weight, change_destination_script)?;
415 let psbt_inputs = descriptors.iter().map(|d| d.to_psbt_input()).collect::<Vec<_>>();
416 let psbt = PartiallySignedTransaction {
418 outputs: vec![Default::default(); tx.output.len()],
420 xpub: Default::default(),
422 proprietary: Default::default(),
423 unknown: Default::default(),
425 Ok((psbt, expected_max_weight))
429 /// The parameters required to derive a channel signer via [`SignerProvider`].
430 #[derive(Clone, Debug, PartialEq, Eq)]
431 pub struct ChannelDerivationParameters {
432 /// The value in satoshis of the channel we're attempting to spend the anchor output of.
433 pub value_satoshis: u64,
434 /// The unique identifier to re-derive the signer for the associated channel.
435 pub keys_id: [u8; 32],
436 /// The necessary channel parameters that need to be provided to the re-derived signer through
437 /// [`ChannelSigner::provide_channel_parameters`].
438 pub transaction_parameters: ChannelTransactionParameters,
441 impl_writeable_tlv_based!(ChannelDerivationParameters, {
442 (0, value_satoshis, required),
443 (2, keys_id, required),
444 (4, transaction_parameters, required),
447 /// A descriptor used to sign for a commitment transaction's HTLC output.
448 #[derive(Clone, Debug, PartialEq, Eq)]
449 pub struct HTLCDescriptor {
450 /// The parameters required to derive the signer for the HTLC input.
451 pub channel_derivation_parameters: ChannelDerivationParameters,
452 /// The txid of the commitment transaction in which the HTLC output lives.
453 pub commitment_txid: Txid,
454 /// The number of the commitment transaction in which the HTLC output lives.
455 pub per_commitment_number: u64,
456 /// The key tweak corresponding to the number of the commitment transaction in which the HTLC
457 /// output lives. This tweak is applied to all the basepoints for both parties in the channel to
458 /// arrive at unique keys per commitment.
460 /// See <https://github.com/lightning/bolts/blob/master/03-transactions.md#keys> for more info.
461 pub per_commitment_point: PublicKey,
462 /// The feerate to use on the HTLC claiming transaction. This is always `0` for HTLCs
463 /// originating from a channel supporting anchor outputs, otherwise it is the channel's
464 /// negotiated feerate at the time the commitment transaction was built.
465 pub feerate_per_kw: u32,
466 /// The details of the HTLC as it appears in the commitment transaction.
467 pub htlc: HTLCOutputInCommitment,
468 /// The preimage, if `Some`, to claim the HTLC output with. If `None`, the timeout path must be
470 pub preimage: Option<PaymentPreimage>,
471 /// The counterparty's signature required to spend the HTLC output.
472 pub counterparty_sig: Signature
475 impl_writeable_tlv_based!(HTLCDescriptor, {
476 (0, channel_derivation_parameters, required),
477 (1, feerate_per_kw, (default_value, 0)),
478 (2, commitment_txid, required),
479 (4, per_commitment_number, required),
480 (6, per_commitment_point, required),
482 (10, preimage, option),
483 (12, counterparty_sig, required),
486 impl HTLCDescriptor {
487 /// Returns the outpoint of the HTLC output in the commitment transaction. This is the outpoint
488 /// being spent by the HTLC input in the HTLC transaction.
489 pub fn outpoint(&self) -> bitcoin::OutPoint {
491 txid: self.commitment_txid,
492 vout: self.htlc.transaction_output_index.unwrap(),
496 /// Returns the UTXO to be spent by the HTLC input, which can be obtained via
497 /// [`Self::unsigned_tx_input`].
498 pub fn previous_utxo<C: secp256k1::Signing + secp256k1::Verification>(&self, secp: &Secp256k1<C>) -> TxOut {
500 script_pubkey: self.witness_script(secp).to_v0_p2wsh(),
501 value: self.htlc.amount_msat / 1000,
505 /// Returns the unsigned transaction input spending the HTLC output in the commitment
507 pub fn unsigned_tx_input(&self) -> TxIn {
508 chan_utils::build_htlc_input(
509 &self.commitment_txid, &self.htlc, &self.channel_derivation_parameters.transaction_parameters.channel_type_features
513 /// Returns the delayed output created as a result of spending the HTLC output in the commitment
515 pub fn tx_output<C: secp256k1::Signing + secp256k1::Verification>(&self, secp: &Secp256k1<C>) -> TxOut {
516 let channel_params = self.channel_derivation_parameters.transaction_parameters.as_holder_broadcastable();
517 let broadcaster_keys = channel_params.broadcaster_pubkeys();
518 let counterparty_keys = channel_params.countersignatory_pubkeys();
519 let broadcaster_delayed_key = DelayedPaymentKey::from_basepoint(
520 secp, &broadcaster_keys.delayed_payment_basepoint, &self.per_commitment_point
522 let counterparty_revocation_key = &RevocationKey::from_basepoint(&secp, &counterparty_keys.revocation_basepoint, &self.per_commitment_point);
523 chan_utils::build_htlc_output(
524 self.feerate_per_kw, channel_params.contest_delay(), &self.htlc,
525 channel_params.channel_type_features(), &broadcaster_delayed_key, &counterparty_revocation_key
529 /// Returns the witness script of the HTLC output in the commitment transaction.
530 pub fn witness_script<C: secp256k1::Signing + secp256k1::Verification>(&self, secp: &Secp256k1<C>) -> ScriptBuf {
531 let channel_params = self.channel_derivation_parameters.transaction_parameters.as_holder_broadcastable();
532 let broadcaster_keys = channel_params.broadcaster_pubkeys();
533 let counterparty_keys = channel_params.countersignatory_pubkeys();
534 let broadcaster_htlc_key = HtlcKey::from_basepoint(
535 secp, &broadcaster_keys.htlc_basepoint, &self.per_commitment_point
537 let counterparty_htlc_key = HtlcKey::from_basepoint(
538 secp, &counterparty_keys.htlc_basepoint, &self.per_commitment_point,
540 let counterparty_revocation_key = &RevocationKey::from_basepoint(&secp, &counterparty_keys.revocation_basepoint, &self.per_commitment_point);
541 chan_utils::get_htlc_redeemscript_with_explicit_keys(
542 &self.htlc, channel_params.channel_type_features(), &broadcaster_htlc_key, &counterparty_htlc_key,
543 &counterparty_revocation_key,
547 /// Returns the fully signed witness required to spend the HTLC output in the commitment
549 pub fn tx_input_witness(&self, signature: &Signature, witness_script: &Script) -> Witness {
550 chan_utils::build_htlc_input_witness(
551 signature, &self.counterparty_sig, &self.preimage, witness_script,
552 &self.channel_derivation_parameters.transaction_parameters.channel_type_features
556 /// Derives the channel signer required to sign the HTLC input.
557 pub fn derive_channel_signer<S: WriteableEcdsaChannelSigner, SP: Deref>(&self, signer_provider: &SP) -> S
559 SP::Target: SignerProvider<EcdsaSigner= S>
561 let mut signer = signer_provider.derive_channel_signer(
562 self.channel_derivation_parameters.value_satoshis,
563 self.channel_derivation_parameters.keys_id,
565 signer.provide_channel_parameters(&self.channel_derivation_parameters.transaction_parameters);
570 /// A trait to handle Lightning channel key material without concretizing the channel type or
571 /// the signature mechanism.
572 pub trait ChannelSigner {
573 /// Gets the per-commitment point for a specific commitment number
575 /// Note that the commitment number starts at `(1 << 48) - 1` and counts backwards.
576 fn get_per_commitment_point(&self, idx: u64, secp_ctx: &Secp256k1<secp256k1::All>) -> PublicKey;
578 /// Gets the commitment secret for a specific commitment number as part of the revocation process
580 /// An external signer implementation should error here if the commitment was already signed
581 /// and should refuse to sign it in the future.
583 /// May be called more than once for the same index.
585 /// Note that the commitment number starts at `(1 << 48) - 1` and counts backwards.
586 // TODO: return a Result so we can signal a validation error
587 fn release_commitment_secret(&self, idx: u64) -> [u8; 32];
589 /// Validate the counterparty's signatures on the holder commitment transaction and HTLCs.
591 /// This is required in order for the signer to make sure that releasing a commitment
592 /// secret won't leave us without a broadcastable holder transaction.
593 /// Policy checks should be implemented in this function, including checking the amount
594 /// sent to us and checking the HTLCs.
596 /// The preimages of outbound HTLCs that were fulfilled since the last commitment are provided.
597 /// A validating signer should ensure that an HTLC output is removed only when the matching
598 /// preimage is provided, or when the value to holder is restored.
600 /// Note that all the relevant preimages will be provided, but there may also be additional
601 /// irrelevant or duplicate preimages.
602 fn validate_holder_commitment(&self, holder_tx: &HolderCommitmentTransaction,
603 outbound_htlc_preimages: Vec<PaymentPreimage>) -> Result<(), ()>;
605 /// Validate the counterparty's revocation.
607 /// This is required in order for the signer to make sure that the state has moved
608 /// forward and it is safe to sign the next counterparty commitment.
609 fn validate_counterparty_revocation(&self, idx: u64, secret: &SecretKey) -> Result<(), ()>;
611 /// Returns the holder's channel public keys and basepoints.
612 fn pubkeys(&self) -> &ChannelPublicKeys;
614 /// Returns an arbitrary identifier describing the set of keys which are provided back to you in
615 /// some [`SpendableOutputDescriptor`] types. This should be sufficient to identify this
616 /// [`EcdsaChannelSigner`] object uniquely and lookup or re-derive its keys.
617 fn channel_keys_id(&self) -> [u8; 32];
619 /// Set the counterparty static channel data, including basepoints,
620 /// `counterparty_selected`/`holder_selected_contest_delay` and funding outpoint.
622 /// This data is static, and will never change for a channel once set. For a given [`ChannelSigner`]
623 /// instance, LDK will call this method exactly once - either immediately after construction
624 /// (not including if done via [`SignerProvider::read_chan_signer`]) or when the funding
625 /// information has been generated.
627 /// channel_parameters.is_populated() MUST be true.
628 fn provide_channel_parameters(&mut self, channel_parameters: &ChannelTransactionParameters);
631 /// Specifies the recipient of an invoice.
633 /// This indicates to [`NodeSigner::sign_invoice`] what node secret key should be used to sign
636 /// The invoice should be signed with the local node secret key.
638 /// The invoice should be signed with the phantom node secret key. This secret key must be the
639 /// same for all nodes participating in the [phantom node payment].
641 /// [phantom node payment]: PhantomKeysManager
645 /// A trait that describes a source of entropy.
646 pub trait EntropySource {
647 /// Gets a unique, cryptographically-secure, random 32-byte value. This method must return a
648 /// different value each time it is called.
649 fn get_secure_random_bytes(&self) -> [u8; 32];
652 /// A trait that can handle cryptographic operations at the scope level of a node.
653 pub trait NodeSigner {
654 /// Get secret key material as bytes for use in encrypting and decrypting inbound payment data.
656 /// If the implementor of this trait supports [phantom node payments], then every node that is
657 /// intended to be included in the phantom invoice route hints must return the same value from
659 // This is because LDK avoids storing inbound payment data by encrypting payment data in the
660 // payment hash and/or payment secret, therefore for a payment to be receivable by multiple
661 // nodes, they must share the key that encrypts this payment data.
663 /// This method must return the same value each time it is called.
665 /// [phantom node payments]: PhantomKeysManager
666 fn get_inbound_payment_key_material(&self) -> KeyMaterial;
668 /// Get node id based on the provided [`Recipient`].
670 /// This method must return the same value each time it is called with a given [`Recipient`]
673 /// Errors if the [`Recipient`] variant is not supported by the implementation.
674 fn get_node_id(&self, recipient: Recipient) -> Result<PublicKey, ()>;
676 /// Gets the ECDH shared secret of our node secret and `other_key`, multiplying by `tweak` if
677 /// one is provided. Note that this tweak can be applied to `other_key` instead of our node
678 /// secret, though this is less efficient.
680 /// Note that if this fails while attempting to forward an HTLC, LDK will panic. The error
681 /// should be resolved to allow LDK to resume forwarding HTLCs.
683 /// Errors if the [`Recipient`] variant is not supported by the implementation.
684 fn ecdh(&self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&Scalar>) -> Result<SharedSecret, ()>;
688 /// By parameterizing by the raw invoice bytes instead of the hash, we allow implementors of
689 /// this trait to parse the invoice and make sure they're signing what they expect, rather than
690 /// blindly signing the hash.
692 /// The `hrp_bytes` are ASCII bytes, while the `invoice_data` is base32.
694 /// The secret key used to sign the invoice is dependent on the [`Recipient`].
696 /// Errors if the [`Recipient`] variant is not supported by the implementation.
697 fn sign_invoice(&self, hrp_bytes: &[u8], invoice_data: &[u5], recipient: Recipient) -> Result<RecoverableSignature, ()>;
699 /// Signs the [`TaggedHash`] of a BOLT 12 invoice request.
701 /// May be called by a function passed to [`UnsignedInvoiceRequest::sign`] where
702 /// `invoice_request` is the callee.
704 /// Implementors may check that the `invoice_request` is expected rather than blindly signing
705 /// the tagged hash. An `Ok` result should sign `invoice_request.tagged_hash().as_digest()` with
706 /// the node's signing key or an ephemeral key to preserve privacy, whichever is associated with
707 /// [`UnsignedInvoiceRequest::payer_id`].
709 /// [`TaggedHash`]: crate::offers::merkle::TaggedHash
710 fn sign_bolt12_invoice_request(
711 &self, invoice_request: &UnsignedInvoiceRequest
712 ) -> Result<schnorr::Signature, ()>;
714 /// Signs the [`TaggedHash`] of a BOLT 12 invoice.
716 /// May be called by a function passed to [`UnsignedBolt12Invoice::sign`] where `invoice` is the
719 /// Implementors may check that the `invoice` is expected rather than blindly signing the tagged
720 /// hash. An `Ok` result should sign `invoice.tagged_hash().as_digest()` with the node's signing
721 /// key or an ephemeral key to preserve privacy, whichever is associated with
722 /// [`UnsignedBolt12Invoice::signing_pubkey`].
724 /// [`TaggedHash`]: crate::offers::merkle::TaggedHash
725 fn sign_bolt12_invoice(
726 &self, invoice: &UnsignedBolt12Invoice
727 ) -> Result<schnorr::Signature, ()>;
729 /// Sign a gossip message.
731 /// Note that if this fails, LDK may panic and the message will not be broadcast to the network
732 /// or a possible channel counterparty. If LDK panics, the error should be resolved to allow the
733 /// message to be broadcast, as otherwise it may prevent one from receiving funds over the
734 /// corresponding channel.
735 fn sign_gossip_message(&self, msg: UnsignedGossipMessage) -> Result<Signature, ()>;
738 // Primarily needed in doctests because of https://github.com/rust-lang/rust/issues/67295
739 /// A dynamic [`SignerProvider`] temporarily needed for doc tests.
742 #[deprecated(note = "Remove once taproot cfg is removed")]
743 pub type DynSignerProvider = dyn SignerProvider<EcdsaSigner = InMemorySigner, TaprootSigner = InMemorySigner>;
745 /// A dynamic [`SignerProvider`] temporarily needed for doc tests.
748 #[deprecated(note = "Remove once taproot cfg is removed")]
749 pub type DynSignerProvider = dyn SignerProvider<EcdsaSigner = InMemorySigner>;
751 /// A trait that can return signer instances for individual channels.
752 pub trait SignerProvider {
753 /// A type which implements [`WriteableEcdsaChannelSigner`] which will be returned by [`Self::derive_channel_signer`].
754 type EcdsaSigner: WriteableEcdsaChannelSigner;
756 /// A type which implements [`TaprootChannelSigner`]
757 type TaprootSigner: TaprootChannelSigner;
759 /// Generates a unique `channel_keys_id` that can be used to obtain a [`Self::EcdsaSigner`] through
760 /// [`SignerProvider::derive_channel_signer`]. The `user_channel_id` is provided to allow
761 /// implementations of [`SignerProvider`] to maintain a mapping between itself and the generated
762 /// `channel_keys_id`.
764 /// This method must return a different value each time it is called.
765 fn generate_channel_keys_id(&self, inbound: bool, channel_value_satoshis: u64, user_channel_id: u128) -> [u8; 32];
767 /// Derives the private key material backing a `Signer`.
769 /// To derive a new `Signer`, a fresh `channel_keys_id` should be obtained through
770 /// [`SignerProvider::generate_channel_keys_id`]. Otherwise, an existing `Signer` can be
771 /// re-derived from its `channel_keys_id`, which can be obtained through its trait method
772 /// [`ChannelSigner::channel_keys_id`].
773 fn derive_channel_signer(&self, channel_value_satoshis: u64, channel_keys_id: [u8; 32]) -> Self::EcdsaSigner;
775 /// Reads a [`Signer`] for this [`SignerProvider`] from the given input stream.
776 /// This is only called during deserialization of other objects which contain
777 /// [`WriteableEcdsaChannelSigner`]-implementing objects (i.e., [`ChannelMonitor`]s and [`ChannelManager`]s).
778 /// The bytes are exactly those which `<Self::Signer as Writeable>::write()` writes, and
779 /// contain no versioning scheme. You may wish to include your own version prefix and ensure
780 /// you've read all of the provided bytes to ensure no corruption occurred.
782 /// This method is slowly being phased out -- it will only be called when reading objects
783 /// written by LDK versions prior to 0.0.113.
785 /// [`Signer`]: Self::EcdsaSigner
786 /// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
787 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
788 fn read_chan_signer(&self, reader: &[u8]) -> Result<Self::EcdsaSigner, DecodeError>;
790 /// Get a script pubkey which we send funds to when claiming on-chain contestable outputs.
792 /// If this function returns an error, this will result in a channel failing to open.
794 /// This method should return a different value each time it is called, to avoid linking
795 /// on-chain funds across channels as controlled to the same user. `channel_keys_id` may be
796 /// used to derive a unique value for each channel.
797 fn get_destination_script(&self, channel_keys_id: [u8; 32]) -> Result<ScriptBuf, ()>;
799 /// Get a script pubkey which we will send funds to when closing a channel.
801 /// If this function returns an error, this will result in a channel failing to open or close.
802 /// In the event of a failure when the counterparty is initiating a close, this can result in a
803 /// channel force close.
805 /// This method should return a different value each time it is called, to avoid linking
806 /// on-chain funds across channels as controlled to the same user.
807 fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()>;
810 /// A simple implementation of [`WriteableEcdsaChannelSigner`] that just keeps the private keys in memory.
812 /// This implementation performs no policy checks and is insufficient by itself as
813 /// a secure external signer.
815 pub struct InMemorySigner {
816 /// Holder secret key in the 2-of-2 multisig script of a channel. This key also backs the
817 /// holder's anchor output in a commitment transaction, if one is present.
818 pub funding_key: SecretKey,
819 /// Holder secret key for blinded revocation pubkey.
820 pub revocation_base_key: SecretKey,
821 /// Holder secret key used for our balance in counterparty-broadcasted commitment transactions.
822 pub payment_key: SecretKey,
823 /// Holder secret key used in an HTLC transaction.
824 pub delayed_payment_base_key: SecretKey,
825 /// Holder HTLC secret key used in commitment transaction HTLC outputs.
826 pub htlc_base_key: SecretKey,
828 pub commitment_seed: [u8; 32],
829 /// Holder public keys and basepoints.
830 pub(crate) holder_channel_pubkeys: ChannelPublicKeys,
831 /// Counterparty public keys and counterparty/holder `selected_contest_delay`, populated on channel acceptance.
832 channel_parameters: Option<ChannelTransactionParameters>,
833 /// The total value of this channel.
834 channel_value_satoshis: u64,
835 /// Key derivation parameters.
836 channel_keys_id: [u8; 32],
837 /// A source of random bytes.
838 entropy_source: RandomBytes,
841 impl PartialEq for InMemorySigner {
842 fn eq(&self, other: &Self) -> bool {
843 self.funding_key == other.funding_key &&
844 self.revocation_base_key == other.revocation_base_key &&
845 self.payment_key == other.payment_key &&
846 self.delayed_payment_base_key == other.delayed_payment_base_key &&
847 self.htlc_base_key == other.htlc_base_key &&
848 self.commitment_seed == other.commitment_seed &&
849 self.holder_channel_pubkeys == other.holder_channel_pubkeys &&
850 self.channel_parameters == other.channel_parameters &&
851 self.channel_value_satoshis == other.channel_value_satoshis &&
852 self.channel_keys_id == other.channel_keys_id
856 impl Clone for InMemorySigner {
857 fn clone(&self) -> Self {
859 funding_key: self.funding_key.clone(),
860 revocation_base_key: self.revocation_base_key.clone(),
861 payment_key: self.payment_key.clone(),
862 delayed_payment_base_key: self.delayed_payment_base_key.clone(),
863 htlc_base_key: self.htlc_base_key.clone(),
864 commitment_seed: self.commitment_seed.clone(),
865 holder_channel_pubkeys: self.holder_channel_pubkeys.clone(),
866 channel_parameters: self.channel_parameters.clone(),
867 channel_value_satoshis: self.channel_value_satoshis,
868 channel_keys_id: self.channel_keys_id,
869 entropy_source: RandomBytes::new(self.get_secure_random_bytes()),
874 impl InMemorySigner {
875 /// Creates a new [`InMemorySigner`].
876 pub fn new<C: Signing>(
877 secp_ctx: &Secp256k1<C>,
878 funding_key: SecretKey,
879 revocation_base_key: SecretKey,
880 payment_key: SecretKey,
881 delayed_payment_base_key: SecretKey,
882 htlc_base_key: SecretKey,
883 commitment_seed: [u8; 32],
884 channel_value_satoshis: u64,
885 channel_keys_id: [u8; 32],
886 rand_bytes_unique_start: [u8; 32],
887 ) -> InMemorySigner {
888 let holder_channel_pubkeys =
889 InMemorySigner::make_holder_keys(secp_ctx, &funding_key, &revocation_base_key,
890 &payment_key, &delayed_payment_base_key,
896 delayed_payment_base_key,
899 channel_value_satoshis,
900 holder_channel_pubkeys,
901 channel_parameters: None,
903 entropy_source: RandomBytes::new(rand_bytes_unique_start),
907 fn make_holder_keys<C: Signing>(secp_ctx: &Secp256k1<C>,
908 funding_key: &SecretKey,
909 revocation_base_key: &SecretKey,
910 payment_key: &SecretKey,
911 delayed_payment_base_key: &SecretKey,
912 htlc_base_key: &SecretKey) -> ChannelPublicKeys {
913 let from_secret = |s: &SecretKey| PublicKey::from_secret_key(secp_ctx, s);
915 funding_pubkey: from_secret(&funding_key),
916 revocation_basepoint: RevocationBasepoint::from(from_secret(&revocation_base_key)),
917 payment_point: from_secret(&payment_key),
918 delayed_payment_basepoint: DelayedPaymentBasepoint::from(from_secret(&delayed_payment_base_key)),
919 htlc_basepoint: HtlcBasepoint::from(from_secret(&htlc_base_key)),
923 /// Returns the counterparty's pubkeys.
925 /// Will return `None` if [`ChannelSigner::provide_channel_parameters`] has not been called.
926 /// In general, this is safe to `unwrap` only in [`ChannelSigner`] implementation.
927 pub fn counterparty_pubkeys(&self) -> Option<&ChannelPublicKeys> {
928 self.get_channel_parameters()
929 .and_then(|params| params.counterparty_parameters.as_ref().map(|params| ¶ms.pubkeys))
932 /// Returns the `contest_delay` value specified by our counterparty and applied on holder-broadcastable
933 /// transactions, i.e., the amount of time that we have to wait to recover our funds if we
934 /// broadcast a transaction.
936 /// Will return `None` if [`ChannelSigner::provide_channel_parameters`] has not been called.
937 /// In general, this is safe to `unwrap` only in [`ChannelSigner`] implementation.
938 pub fn counterparty_selected_contest_delay(&self) -> Option<u16> {
939 self.get_channel_parameters()
940 .and_then(|params| params.counterparty_parameters.as_ref().map(|params| params.selected_contest_delay))
943 /// Returns the `contest_delay` value specified by us and applied on transactions broadcastable
944 /// by our counterparty, i.e., the amount of time that they have to wait to recover their funds
945 /// if they broadcast a transaction.
947 /// Will return `None` if [`ChannelSigner::provide_channel_parameters`] has not been called.
948 /// In general, this is safe to `unwrap` only in [`ChannelSigner`] implementation.
949 pub fn holder_selected_contest_delay(&self) -> Option<u16> {
950 self.get_channel_parameters().map(|params| params.holder_selected_contest_delay)
953 /// Returns whether the holder is the initiator.
955 /// Will return `None` if [`ChannelSigner::provide_channel_parameters`] has not been called.
956 /// In general, this is safe to `unwrap` only in [`ChannelSigner`] implementation.
957 pub fn is_outbound(&self) -> Option<bool> {
958 self.get_channel_parameters().map(|params| params.is_outbound_from_holder)
963 /// Will return `None` if [`ChannelSigner::provide_channel_parameters`] has not been called.
964 /// In general, this is safe to `unwrap` only in [`ChannelSigner`] implementation.
965 pub fn funding_outpoint(&self) -> Option<&OutPoint> {
966 self.get_channel_parameters().map(|params| params.funding_outpoint.as_ref()).flatten()
969 /// Returns a [`ChannelTransactionParameters`] for this channel, to be used when verifying or
970 /// building transactions.
972 /// Will return `None` if [`ChannelSigner::provide_channel_parameters`] has not been called.
973 /// In general, this is safe to `unwrap` only in [`ChannelSigner`] implementation.
974 pub fn get_channel_parameters(&self) -> Option<&ChannelTransactionParameters> {
975 self.channel_parameters.as_ref()
978 /// Returns the channel type features of the channel parameters. Should be helpful for
979 /// determining a channel's category, i. e. legacy/anchors/taproot/etc.
981 /// Will return `None` if [`ChannelSigner::provide_channel_parameters`] has not been called.
982 /// In general, this is safe to `unwrap` only in [`ChannelSigner`] implementation.
983 pub fn channel_type_features(&self) -> Option<&ChannelTypeFeatures> {
984 self.get_channel_parameters().map(|params| ¶ms.channel_type_features)
987 /// Sign the single input of `spend_tx` at index `input_idx`, which spends the output described
988 /// by `descriptor`, returning the witness stack for the input.
990 /// Returns an error if the input at `input_idx` does not exist, has a non-empty `script_sig`,
991 /// is not spending the outpoint described by [`descriptor.outpoint`],
992 /// or if an output descriptor `script_pubkey` does not match the one we can spend.
994 /// [`descriptor.outpoint`]: StaticPaymentOutputDescriptor::outpoint
995 pub fn sign_counterparty_payment_input<C: Signing>(&self, spend_tx: &Transaction, input_idx: usize, descriptor: &StaticPaymentOutputDescriptor, secp_ctx: &Secp256k1<C>) -> Result<Witness, ()> {
996 // TODO: We really should be taking the SigHashCache as a parameter here instead of
997 // spend_tx, but ideally the SigHashCache would expose the transaction's inputs read-only
998 // so that we can check them. This requires upstream rust-bitcoin changes (as well as
999 // bindings updates to support SigHashCache objects).
1000 if spend_tx.input.len() <= input_idx { return Err(()); }
1001 if !spend_tx.input[input_idx].script_sig.is_empty() { return Err(()); }
1002 if spend_tx.input[input_idx].previous_output != descriptor.outpoint.into_bitcoin_outpoint() { return Err(()); }
1004 let remotepubkey = bitcoin::PublicKey::new(self.pubkeys().payment_point);
1005 // We cannot always assume that `channel_parameters` is set, so can't just call
1006 // `self.channel_parameters()` or anything that relies on it
1007 let supports_anchors_zero_fee_htlc_tx = self.channel_type_features()
1008 .map(|features| features.supports_anchors_zero_fee_htlc_tx())
1011 let witness_script = if supports_anchors_zero_fee_htlc_tx {
1012 chan_utils::get_to_countersignatory_with_anchors_redeemscript(&remotepubkey.inner)
1014 ScriptBuf::new_p2pkh(&remotepubkey.pubkey_hash())
1016 let sighash = hash_to_message!(&sighash::SighashCache::new(spend_tx).segwit_signature_hash(input_idx, &witness_script, descriptor.output.value, EcdsaSighashType::All).unwrap()[..]);
1017 let remotesig = sign_with_aux_rand(secp_ctx, &sighash, &self.payment_key, &self);
1018 let payment_script = if supports_anchors_zero_fee_htlc_tx {
1019 witness_script.to_v0_p2wsh()
1021 ScriptBuf::new_v0_p2wpkh(&remotepubkey.wpubkey_hash().unwrap())
1024 if payment_script != descriptor.output.script_pubkey { return Err(()); }
1026 let mut witness = Vec::with_capacity(2);
1027 witness.push(remotesig.serialize_der().to_vec());
1028 witness[0].push(EcdsaSighashType::All as u8);
1029 if supports_anchors_zero_fee_htlc_tx {
1030 witness.push(witness_script.to_bytes());
1032 witness.push(remotepubkey.to_bytes());
1037 /// Sign the single input of `spend_tx` at index `input_idx` which spends the output
1038 /// described by `descriptor`, returning the witness stack for the input.
1040 /// Returns an error if the input at `input_idx` does not exist, has a non-empty `script_sig`,
1041 /// is not spending the outpoint described by [`descriptor.outpoint`], does not have a
1042 /// sequence set to [`descriptor.to_self_delay`], or if an output descriptor
1043 /// `script_pubkey` does not match the one we can spend.
1045 /// [`descriptor.outpoint`]: DelayedPaymentOutputDescriptor::outpoint
1046 /// [`descriptor.to_self_delay`]: DelayedPaymentOutputDescriptor::to_self_delay
1047 pub fn sign_dynamic_p2wsh_input<C: Signing>(&self, spend_tx: &Transaction, input_idx: usize, descriptor: &DelayedPaymentOutputDescriptor, secp_ctx: &Secp256k1<C>) -> Result<Witness, ()> {
1048 // TODO: We really should be taking the SigHashCache as a parameter here instead of
1049 // spend_tx, but ideally the SigHashCache would expose the transaction's inputs read-only
1050 // so that we can check them. This requires upstream rust-bitcoin changes (as well as
1051 // bindings updates to support SigHashCache objects).
1052 if spend_tx.input.len() <= input_idx { return Err(()); }
1053 if !spend_tx.input[input_idx].script_sig.is_empty() { return Err(()); }
1054 if spend_tx.input[input_idx].previous_output != descriptor.outpoint.into_bitcoin_outpoint() { return Err(()); }
1055 if spend_tx.input[input_idx].sequence.0 != descriptor.to_self_delay as u32 { return Err(()); }
1057 let delayed_payment_key = chan_utils::derive_private_key(&secp_ctx, &descriptor.per_commitment_point, &self.delayed_payment_base_key);
1058 let delayed_payment_pubkey = DelayedPaymentKey::from_secret_key(&secp_ctx, &delayed_payment_key);
1059 let witness_script = chan_utils::get_revokeable_redeemscript(&descriptor.revocation_pubkey, descriptor.to_self_delay, &delayed_payment_pubkey);
1060 let sighash = hash_to_message!(&sighash::SighashCache::new(spend_tx).segwit_signature_hash(input_idx, &witness_script, descriptor.output.value, EcdsaSighashType::All).unwrap()[..]);
1061 let local_delayedsig = EcdsaSignature {
1062 sig: sign_with_aux_rand(secp_ctx, &sighash, &delayed_payment_key, &self),
1063 hash_ty: EcdsaSighashType::All,
1065 let payment_script = bitcoin::Address::p2wsh(&witness_script, Network::Bitcoin).script_pubkey();
1067 if descriptor.output.script_pubkey != payment_script { return Err(()); }
1069 Ok(Witness::from_slice(&[
1070 &local_delayedsig.serialize()[..],
1072 witness_script.as_bytes(),
1077 impl EntropySource for InMemorySigner {
1078 fn get_secure_random_bytes(&self) -> [u8; 32] {
1079 self.entropy_source.get_secure_random_bytes()
1083 impl ChannelSigner for InMemorySigner {
1084 fn get_per_commitment_point(&self, idx: u64, secp_ctx: &Secp256k1<secp256k1::All>) -> PublicKey {
1085 let commitment_secret = SecretKey::from_slice(&chan_utils::build_commitment_secret(&self.commitment_seed, idx)).unwrap();
1086 PublicKey::from_secret_key(secp_ctx, &commitment_secret)
1089 fn release_commitment_secret(&self, idx: u64) -> [u8; 32] {
1090 chan_utils::build_commitment_secret(&self.commitment_seed, idx)
1093 fn validate_holder_commitment(&self, _holder_tx: &HolderCommitmentTransaction, _outbound_htlc_preimages: Vec<PaymentPreimage>) -> Result<(), ()> {
1097 fn validate_counterparty_revocation(&self, _idx: u64, _secret: &SecretKey) -> Result<(), ()> {
1101 fn pubkeys(&self) -> &ChannelPublicKeys { &self.holder_channel_pubkeys }
1103 fn channel_keys_id(&self) -> [u8; 32] { self.channel_keys_id }
1105 fn provide_channel_parameters(&mut self, channel_parameters: &ChannelTransactionParameters) {
1106 assert!(self.channel_parameters.is_none() || self.channel_parameters.as_ref().unwrap() == channel_parameters);
1107 if self.channel_parameters.is_some() {
1108 // The channel parameters were already set and they match, return early.
1111 assert!(channel_parameters.is_populated(), "Channel parameters must be fully populated");
1112 self.channel_parameters = Some(channel_parameters.clone());
1116 const MISSING_PARAMS_ERR: &'static str = "ChannelSigner::provide_channel_parameters must be called before signing operations";
1118 impl EcdsaChannelSigner for InMemorySigner {
1119 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>), ()> {
1120 let trusted_tx = commitment_tx.trust();
1121 let keys = trusted_tx.keys();
1123 let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
1124 let counterparty_keys = self.counterparty_pubkeys().expect(MISSING_PARAMS_ERR);
1125 let channel_funding_redeemscript = make_funding_redeemscript(&funding_pubkey, &counterparty_keys.funding_pubkey);
1127 let built_tx = trusted_tx.built_transaction();
1128 let commitment_sig = built_tx.sign_counterparty_commitment(&self.funding_key, &channel_funding_redeemscript, self.channel_value_satoshis, secp_ctx);
1129 let commitment_txid = built_tx.txid;
1131 let mut htlc_sigs = Vec::with_capacity(commitment_tx.htlcs().len());
1132 for htlc in commitment_tx.htlcs() {
1133 let channel_parameters = self.get_channel_parameters().expect(MISSING_PARAMS_ERR);
1134 let holder_selected_contest_delay =
1135 self.holder_selected_contest_delay().expect(MISSING_PARAMS_ERR);
1136 let chan_type = &channel_parameters.channel_type_features;
1137 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);
1138 let htlc_redeemscript = chan_utils::get_htlc_redeemscript(&htlc, chan_type, &keys);
1139 let htlc_sighashtype = if chan_type.supports_anchors_zero_fee_htlc_tx() { EcdsaSighashType::SinglePlusAnyoneCanPay } else { EcdsaSighashType::All };
1140 let htlc_sighash = hash_to_message!(&sighash::SighashCache::new(&htlc_tx).segwit_signature_hash(0, &htlc_redeemscript, htlc.amount_msat / 1000, htlc_sighashtype).unwrap()[..]);
1141 let holder_htlc_key = chan_utils::derive_private_key(&secp_ctx, &keys.per_commitment_point, &self.htlc_base_key);
1142 htlc_sigs.push(sign(secp_ctx, &htlc_sighash, &holder_htlc_key));
1145 Ok((commitment_sig, htlc_sigs))
1148 fn sign_holder_commitment(&self, commitment_tx: &HolderCommitmentTransaction, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<Signature, ()> {
1149 let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
1150 let counterparty_keys = self.counterparty_pubkeys().expect(MISSING_PARAMS_ERR);
1151 let funding_redeemscript = make_funding_redeemscript(&funding_pubkey, &counterparty_keys.funding_pubkey);
1152 let trusted_tx = commitment_tx.trust();
1153 Ok(trusted_tx.built_transaction().sign_holder_commitment(&self.funding_key, &funding_redeemscript, self.channel_value_satoshis, &self, secp_ctx))
1156 #[cfg(any(test,feature = "unsafe_revoked_tx_signing"))]
1157 fn unsafe_sign_holder_commitment(&self, commitment_tx: &HolderCommitmentTransaction, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<Signature, ()> {
1158 let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
1159 let counterparty_keys = self.counterparty_pubkeys().expect(MISSING_PARAMS_ERR);
1160 let funding_redeemscript = make_funding_redeemscript(&funding_pubkey, &counterparty_keys.funding_pubkey);
1161 let trusted_tx = commitment_tx.trust();
1162 Ok(trusted_tx.built_transaction().sign_holder_commitment(&self.funding_key, &funding_redeemscript, self.channel_value_satoshis, &self, secp_ctx))
1165 fn sign_justice_revoked_output(&self, justice_tx: &Transaction, input: usize, amount: u64, per_commitment_key: &SecretKey, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<Signature, ()> {
1166 let revocation_key = chan_utils::derive_private_revocation_key(&secp_ctx, &per_commitment_key, &self.revocation_base_key);
1167 let per_commitment_point = PublicKey::from_secret_key(secp_ctx, &per_commitment_key);
1168 let revocation_pubkey = RevocationKey::from_basepoint(
1169 &secp_ctx, &self.pubkeys().revocation_basepoint, &per_commitment_point,
1171 let witness_script = {
1172 let counterparty_keys = self.counterparty_pubkeys().expect(MISSING_PARAMS_ERR);
1173 let holder_selected_contest_delay =
1174 self.holder_selected_contest_delay().expect(MISSING_PARAMS_ERR);
1175 let counterparty_delayedpubkey = DelayedPaymentKey::from_basepoint(&secp_ctx, &counterparty_keys.delayed_payment_basepoint, &per_commitment_point);
1176 chan_utils::get_revokeable_redeemscript(&revocation_pubkey, holder_selected_contest_delay, &counterparty_delayedpubkey)
1178 let mut sighash_parts = sighash::SighashCache::new(justice_tx);
1179 let sighash = hash_to_message!(&sighash_parts.segwit_signature_hash(input, &witness_script, amount, EcdsaSighashType::All).unwrap()[..]);
1180 return Ok(sign_with_aux_rand(secp_ctx, &sighash, &revocation_key, &self))
1183 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, ()> {
1184 let revocation_key = chan_utils::derive_private_revocation_key(&secp_ctx, &per_commitment_key, &self.revocation_base_key);
1185 let per_commitment_point = PublicKey::from_secret_key(secp_ctx, &per_commitment_key);
1186 let revocation_pubkey = RevocationKey::from_basepoint(
1187 &secp_ctx, &self.pubkeys().revocation_basepoint, &per_commitment_point,
1189 let witness_script = {
1190 let counterparty_keys = self.counterparty_pubkeys().expect(MISSING_PARAMS_ERR);
1191 let counterparty_htlcpubkey = HtlcKey::from_basepoint(
1192 &secp_ctx, &counterparty_keys.htlc_basepoint, &per_commitment_point,
1194 let holder_htlcpubkey = HtlcKey::from_basepoint(
1195 &secp_ctx, &self.pubkeys().htlc_basepoint, &per_commitment_point,
1197 let chan_type = self.channel_type_features().expect(MISSING_PARAMS_ERR);
1198 chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, chan_type, &counterparty_htlcpubkey, &holder_htlcpubkey, &revocation_pubkey)
1200 let mut sighash_parts = sighash::SighashCache::new(justice_tx);
1201 let sighash = hash_to_message!(&sighash_parts.segwit_signature_hash(input, &witness_script, amount, EcdsaSighashType::All).unwrap()[..]);
1202 return Ok(sign_with_aux_rand(secp_ctx, &sighash, &revocation_key, &self))
1205 fn sign_holder_htlc_transaction(
1206 &self, htlc_tx: &Transaction, input: usize, htlc_descriptor: &HTLCDescriptor,
1207 secp_ctx: &Secp256k1<secp256k1::All>
1208 ) -> Result<Signature, ()> {
1209 let witness_script = htlc_descriptor.witness_script(secp_ctx);
1210 let sighash = &sighash::SighashCache::new(&*htlc_tx).segwit_signature_hash(
1211 input, &witness_script, htlc_descriptor.htlc.amount_msat / 1000, EcdsaSighashType::All
1213 let our_htlc_private_key = chan_utils::derive_private_key(
1214 &secp_ctx, &htlc_descriptor.per_commitment_point, &self.htlc_base_key
1216 Ok(sign_with_aux_rand(&secp_ctx, &hash_to_message!(sighash.as_byte_array()), &our_htlc_private_key, &self))
1219 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, ()> {
1220 let htlc_key = chan_utils::derive_private_key(&secp_ctx, &per_commitment_point, &self.htlc_base_key);
1221 let revocation_pubkey = RevocationKey::from_basepoint(
1222 &secp_ctx, &self.pubkeys().revocation_basepoint, &per_commitment_point,
1224 let counterparty_keys = self.counterparty_pubkeys().expect(MISSING_PARAMS_ERR);
1225 let counterparty_htlcpubkey = HtlcKey::from_basepoint(
1226 &secp_ctx, &counterparty_keys.htlc_basepoint, &per_commitment_point,
1228 let htlcpubkey = HtlcKey::from_basepoint(&secp_ctx, &self.pubkeys().htlc_basepoint, &per_commitment_point);
1229 let chan_type = self.channel_type_features().expect(MISSING_PARAMS_ERR);
1230 let witness_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, chan_type, &counterparty_htlcpubkey, &htlcpubkey, &revocation_pubkey);
1231 let mut sighash_parts = sighash::SighashCache::new(htlc_tx);
1232 let sighash = hash_to_message!(&sighash_parts.segwit_signature_hash(input, &witness_script, amount, EcdsaSighashType::All).unwrap()[..]);
1233 Ok(sign_with_aux_rand(secp_ctx, &sighash, &htlc_key, &self))
1236 fn sign_closing_transaction(&self, closing_tx: &ClosingTransaction, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<Signature, ()> {
1237 let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
1238 let counterparty_funding_key = &self.counterparty_pubkeys().expect(MISSING_PARAMS_ERR).funding_pubkey;
1239 let channel_funding_redeemscript = make_funding_redeemscript(&funding_pubkey, counterparty_funding_key);
1240 Ok(closing_tx.trust().sign(&self.funding_key, &channel_funding_redeemscript, self.channel_value_satoshis, secp_ctx))
1243 fn sign_holder_anchor_input(
1244 &self, anchor_tx: &Transaction, input: usize, secp_ctx: &Secp256k1<secp256k1::All>,
1245 ) -> Result<Signature, ()> {
1246 let witness_script = chan_utils::get_anchor_redeemscript(&self.holder_channel_pubkeys.funding_pubkey);
1247 let sighash = sighash::SighashCache::new(&*anchor_tx).segwit_signature_hash(
1248 input, &witness_script, ANCHOR_OUTPUT_VALUE_SATOSHI, EcdsaSighashType::All,
1250 Ok(sign_with_aux_rand(secp_ctx, &hash_to_message!(&sighash[..]), &self.funding_key, &self))
1253 fn sign_channel_announcement_with_funding_key(
1254 &self, msg: &UnsignedChannelAnnouncement, secp_ctx: &Secp256k1<secp256k1::All>
1255 ) -> Result<Signature, ()> {
1256 let msghash = hash_to_message!(&Sha256dHash::hash(&msg.encode()[..])[..]);
1257 Ok(secp_ctx.sign_ecdsa(&msghash, &self.funding_key))
1262 impl TaprootChannelSigner for InMemorySigner {
1263 fn generate_local_nonce_pair(&self, commitment_number: u64, secp_ctx: &Secp256k1<All>) -> PublicNonce {
1267 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>), ()> {
1271 fn finalize_holder_commitment(&self, commitment_tx: &HolderCommitmentTransaction, counterparty_partial_signature: PartialSignatureWithNonce, secp_ctx: &Secp256k1<All>) -> Result<PartialSignature, ()> {
1275 fn sign_justice_revoked_output(&self, justice_tx: &Transaction, input: usize, amount: u64, per_commitment_key: &SecretKey, secp_ctx: &Secp256k1<All>) -> Result<schnorr::Signature, ()> {
1279 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, ()> {
1283 fn sign_holder_htlc_transaction(&self, htlc_tx: &Transaction, input: usize, htlc_descriptor: &HTLCDescriptor, secp_ctx: &Secp256k1<All>) -> Result<schnorr::Signature, ()> {
1287 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, ()> {
1291 fn partially_sign_closing_transaction(&self, closing_tx: &ClosingTransaction, secp_ctx: &Secp256k1<All>) -> Result<PartialSignature, ()> {
1295 fn sign_holder_anchor_input(&self, anchor_tx: &Transaction, input: usize, secp_ctx: &Secp256k1<All>) -> Result<schnorr::Signature, ()> {
1300 const SERIALIZATION_VERSION: u8 = 1;
1302 const MIN_SERIALIZATION_VERSION: u8 = 1;
1304 impl WriteableEcdsaChannelSigner for InMemorySigner {}
1306 impl Writeable for InMemorySigner {
1307 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), Error> {
1308 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
1310 self.funding_key.write(writer)?;
1311 self.revocation_base_key.write(writer)?;
1312 self.payment_key.write(writer)?;
1313 self.delayed_payment_base_key.write(writer)?;
1314 self.htlc_base_key.write(writer)?;
1315 self.commitment_seed.write(writer)?;
1316 self.channel_parameters.write(writer)?;
1317 self.channel_value_satoshis.write(writer)?;
1318 self.channel_keys_id.write(writer)?;
1320 write_tlv_fields!(writer, {});
1326 impl<ES: Deref> ReadableArgs<ES> for InMemorySigner where ES::Target: EntropySource {
1327 fn read<R: io::Read>(reader: &mut R, entropy_source: ES) -> Result<Self, DecodeError> {
1328 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
1330 let funding_key = Readable::read(reader)?;
1331 let revocation_base_key = Readable::read(reader)?;
1332 let payment_key = Readable::read(reader)?;
1333 let delayed_payment_base_key = Readable::read(reader)?;
1334 let htlc_base_key = Readable::read(reader)?;
1335 let commitment_seed = Readable::read(reader)?;
1336 let counterparty_channel_data = Readable::read(reader)?;
1337 let channel_value_satoshis = Readable::read(reader)?;
1338 let secp_ctx = Secp256k1::signing_only();
1339 let holder_channel_pubkeys =
1340 InMemorySigner::make_holder_keys(&secp_ctx, &funding_key, &revocation_base_key,
1341 &payment_key, &delayed_payment_base_key, &htlc_base_key);
1342 let keys_id = Readable::read(reader)?;
1344 read_tlv_fields!(reader, {});
1348 revocation_base_key,
1350 delayed_payment_base_key,
1353 channel_value_satoshis,
1354 holder_channel_pubkeys,
1355 channel_parameters: counterparty_channel_data,
1356 channel_keys_id: keys_id,
1357 entropy_source: RandomBytes::new(entropy_source.get_secure_random_bytes()),
1362 /// Simple implementation of [`EntropySource`], [`NodeSigner`], and [`SignerProvider`] that takes a
1363 /// 32-byte seed for use as a BIP 32 extended key and derives keys from that.
1365 /// Your `node_id` is seed/0'.
1366 /// Unilateral closes may use seed/1'.
1367 /// Cooperative closes may use seed/2'.
1368 /// The two close keys may be needed to claim on-chain funds!
1370 /// This struct cannot be used for nodes that wish to support receiving phantom payments;
1371 /// [`PhantomKeysManager`] must be used instead.
1373 /// Note that switching between this struct and [`PhantomKeysManager`] will invalidate any
1374 /// previously issued invoices and attempts to pay previous invoices will fail.
1375 pub struct KeysManager {
1376 secp_ctx: Secp256k1<secp256k1::All>,
1377 node_secret: SecretKey,
1379 inbound_payment_key: KeyMaterial,
1380 destination_script: ScriptBuf,
1381 shutdown_pubkey: PublicKey,
1382 channel_master_key: ExtendedPrivKey,
1383 channel_child_index: AtomicUsize,
1385 entropy_source: RandomBytes,
1388 starting_time_secs: u64,
1389 starting_time_nanos: u32,
1393 /// Constructs a [`KeysManager`] from a 32-byte seed. If the seed is in some way biased (e.g.,
1394 /// your CSRNG is busted) this may panic (but more importantly, you will possibly lose funds).
1395 /// `starting_time` isn't strictly required to actually be a time, but it must absolutely,
1396 /// without a doubt, be unique to this instance. ie if you start multiple times with the same
1397 /// `seed`, `starting_time` must be unique to each run. Thus, the easiest way to achieve this
1398 /// is to simply use the current time (with very high precision).
1400 /// The `seed` MUST be backed up safely prior to use so that the keys can be re-created, however,
1401 /// obviously, `starting_time` should be unique every time you reload the library - it is only
1402 /// used to generate new ephemeral key data (which will be stored by the individual channel if
1405 /// Note that the seed is required to recover certain on-chain funds independent of
1406 /// [`ChannelMonitor`] data, though a current copy of [`ChannelMonitor`] data is also required
1407 /// for any channel, and some on-chain during-closing funds.
1409 /// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
1410 pub fn new(seed: &[u8; 32], starting_time_secs: u64, starting_time_nanos: u32) -> Self {
1411 let secp_ctx = Secp256k1::new();
1412 // Note that when we aren't serializing the key, network doesn't matter
1413 match ExtendedPrivKey::new_master(Network::Testnet, seed) {
1415 let node_secret = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(0).unwrap()).expect("Your RNG is busted").private_key;
1416 let node_id = PublicKey::from_secret_key(&secp_ctx, &node_secret);
1417 let destination_script = match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(1).unwrap()) {
1418 Ok(destination_key) => {
1419 let wpubkey_hash = WPubkeyHash::hash(&ExtendedPubKey::from_priv(&secp_ctx, &destination_key).to_pub().to_bytes());
1420 Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0)
1421 .push_slice(&wpubkey_hash.to_byte_array())
1424 Err(_) => panic!("Your RNG is busted"),
1426 let shutdown_pubkey = match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(2).unwrap()) {
1427 Ok(shutdown_key) => ExtendedPubKey::from_priv(&secp_ctx, &shutdown_key).public_key,
1428 Err(_) => panic!("Your RNG is busted"),
1430 let channel_master_key = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(3).unwrap()).expect("Your RNG is busted");
1431 let inbound_payment_key: SecretKey = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(5).unwrap()).expect("Your RNG is busted").private_key;
1432 let mut inbound_pmt_key_bytes = [0; 32];
1433 inbound_pmt_key_bytes.copy_from_slice(&inbound_payment_key[..]);
1435 let mut rand_bytes_engine = Sha256::engine();
1436 rand_bytes_engine.input(&starting_time_secs.to_be_bytes());
1437 rand_bytes_engine.input(&starting_time_nanos.to_be_bytes());
1438 rand_bytes_engine.input(seed);
1439 rand_bytes_engine.input(b"LDK PRNG Seed");
1440 let rand_bytes_unique_start = Sha256::from_engine(rand_bytes_engine).to_byte_array();
1442 let mut res = KeysManager {
1446 inbound_payment_key: KeyMaterial(inbound_pmt_key_bytes),
1452 channel_child_index: AtomicUsize::new(0),
1454 entropy_source: RandomBytes::new(rand_bytes_unique_start),
1458 starting_time_nanos,
1460 let secp_seed = res.get_secure_random_bytes();
1461 res.secp_ctx.seeded_randomize(&secp_seed);
1464 Err(_) => panic!("Your rng is busted"),
1468 /// Gets the "node_id" secret key used to sign gossip announcements, decode onion data, etc.
1469 pub fn get_node_secret_key(&self) -> SecretKey {
1473 /// Derive an old [`WriteableEcdsaChannelSigner`] containing per-channel secrets based on a key derivation parameters.
1474 pub fn derive_channel_keys(&self, channel_value_satoshis: u64, params: &[u8; 32]) -> InMemorySigner {
1475 let chan_id = u64::from_be_bytes(params[0..8].try_into().unwrap());
1476 let mut unique_start = Sha256::engine();
1477 unique_start.input(params);
1478 unique_start.input(&self.seed);
1480 // We only seriously intend to rely on the channel_master_key for true secure
1481 // entropy, everything else just ensures uniqueness. We rely on the unique_start (ie
1482 // starting_time provided in the constructor) to be unique.
1483 let child_privkey = self.channel_master_key.ckd_priv(&self.secp_ctx,
1484 ChildNumber::from_hardened_idx((chan_id as u32) % (1 << 31)).expect("key space exhausted")
1485 ).expect("Your RNG is busted");
1486 unique_start.input(&child_privkey.private_key[..]);
1488 let seed = Sha256::from_engine(unique_start).to_byte_array();
1490 let commitment_seed = {
1491 let mut sha = Sha256::engine();
1493 sha.input(&b"commitment seed"[..]);
1494 Sha256::from_engine(sha).to_byte_array()
1496 macro_rules! key_step {
1497 ($info: expr, $prev_key: expr) => {{
1498 let mut sha = Sha256::engine();
1500 sha.input(&$prev_key[..]);
1501 sha.input(&$info[..]);
1502 SecretKey::from_slice(&Sha256::from_engine(sha).to_byte_array()).expect("SHA-256 is busted")
1505 let funding_key = key_step!(b"funding key", commitment_seed);
1506 let revocation_base_key = key_step!(b"revocation base key", funding_key);
1507 let payment_key = key_step!(b"payment key", revocation_base_key);
1508 let delayed_payment_base_key = key_step!(b"delayed payment base key", payment_key);
1509 let htlc_base_key = key_step!(b"HTLC base key", delayed_payment_base_key);
1510 let prng_seed = self.get_secure_random_bytes();
1512 InMemorySigner::new(
1515 revocation_base_key,
1517 delayed_payment_base_key,
1520 channel_value_satoshis,
1526 /// Signs the given [`PartiallySignedTransaction`] which spends the given [`SpendableOutputDescriptor`]s.
1527 /// The resulting inputs will be finalized and the PSBT will be ready for broadcast if there
1528 /// are no other inputs that need signing.
1530 /// Returns `Err(())` if the PSBT is missing a descriptor or if we fail to sign.
1532 /// May panic if the [`SpendableOutputDescriptor`]s were not generated by channels which used
1533 /// this [`KeysManager`] or one of the [`InMemorySigner`] created by this [`KeysManager`].
1534 pub fn sign_spendable_outputs_psbt<C: Signing>(&self, descriptors: &[&SpendableOutputDescriptor], mut psbt: PartiallySignedTransaction, secp_ctx: &Secp256k1<C>) -> Result<PartiallySignedTransaction, ()> {
1535 let mut keys_cache: Option<(InMemorySigner, [u8; 32])> = None;
1536 for outp in descriptors {
1538 SpendableOutputDescriptor::StaticPaymentOutput(descriptor) => {
1539 let input_idx = psbt.unsigned_tx.input.iter().position(|i| i.previous_output == descriptor.outpoint.into_bitcoin_outpoint()).ok_or(())?;
1540 if keys_cache.is_none() || keys_cache.as_ref().unwrap().1 != descriptor.channel_keys_id {
1541 let mut signer = self.derive_channel_keys(descriptor.channel_value_satoshis, &descriptor.channel_keys_id);
1542 if let Some(channel_params) = descriptor.channel_transaction_parameters.as_ref() {
1543 signer.provide_channel_parameters(channel_params);
1545 keys_cache = Some((signer, descriptor.channel_keys_id));
1547 let witness = keys_cache.as_ref().unwrap().0.sign_counterparty_payment_input(&psbt.unsigned_tx, input_idx, &descriptor, &secp_ctx)?;
1548 psbt.inputs[input_idx].final_script_witness = Some(witness);
1550 SpendableOutputDescriptor::DelayedPaymentOutput(descriptor) => {
1551 let input_idx = psbt.unsigned_tx.input.iter().position(|i| i.previous_output == descriptor.outpoint.into_bitcoin_outpoint()).ok_or(())?;
1552 if keys_cache.is_none() || keys_cache.as_ref().unwrap().1 != descriptor.channel_keys_id {
1554 self.derive_channel_keys(descriptor.channel_value_satoshis, &descriptor.channel_keys_id),
1555 descriptor.channel_keys_id));
1557 let witness = keys_cache.as_ref().unwrap().0.sign_dynamic_p2wsh_input(&psbt.unsigned_tx, input_idx, &descriptor, &secp_ctx)?;
1558 psbt.inputs[input_idx].final_script_witness = Some(witness);
1560 SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output, .. } => {
1561 let input_idx = psbt.unsigned_tx.input.iter().position(|i| i.previous_output == outpoint.into_bitcoin_outpoint()).ok_or(())?;
1562 let derivation_idx = if output.script_pubkey == self.destination_script {
1568 // Note that when we aren't serializing the key, network doesn't matter
1569 match ExtendedPrivKey::new_master(Network::Testnet, &self.seed) {
1571 match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(derivation_idx).expect("key space exhausted")) {
1573 Err(_) => panic!("Your RNG is busted"),
1576 Err(_) => panic!("Your rng is busted"),
1579 let pubkey = ExtendedPubKey::from_priv(&secp_ctx, &secret).to_pub();
1580 if derivation_idx == 2 {
1581 assert_eq!(pubkey.inner, self.shutdown_pubkey);
1583 let witness_script = bitcoin::Address::p2pkh(&pubkey, Network::Testnet).script_pubkey();
1584 let payment_script = bitcoin::Address::p2wpkh(&pubkey, Network::Testnet).expect("uncompressed key found").script_pubkey();
1586 if payment_script != output.script_pubkey { return Err(()); };
1588 let sighash = hash_to_message!(&sighash::SighashCache::new(&psbt.unsigned_tx).segwit_signature_hash(input_idx, &witness_script, output.value, EcdsaSighashType::All).unwrap()[..]);
1589 let sig = sign_with_aux_rand(secp_ctx, &sighash, &secret.private_key, &self);
1590 let mut sig_ser = sig.serialize_der().to_vec();
1591 sig_ser.push(EcdsaSighashType::All as u8);
1592 let witness = Witness::from_slice(&[&sig_ser, &pubkey.inner.serialize().to_vec()]);
1593 psbt.inputs[input_idx].final_script_witness = Some(witness);
1601 /// Creates a [`Transaction`] which spends the given descriptors to the given outputs, plus an
1602 /// output to the given change destination (if sufficient change value remains). The
1603 /// transaction will have a feerate, at least, of the given value.
1605 /// The `locktime` argument is used to set the transaction's locktime. If `None`, the
1606 /// transaction will have a locktime of 0. It it recommended to set this to the current block
1607 /// height to avoid fee sniping, unless you have some specific reason to use a different
1610 /// Returns `Err(())` if the output value is greater than the input value minus required fee,
1611 /// if a descriptor was duplicated, or if an output descriptor `script_pubkey`
1612 /// does not match the one we can spend.
1614 /// We do not enforce that outputs meet the dust limit or that any output scripts are standard.
1616 /// May panic if the [`SpendableOutputDescriptor`]s were not generated by channels which used
1617 /// this [`KeysManager`] or one of the [`InMemorySigner`] created by this [`KeysManager`].
1618 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, ()> {
1619 let (mut psbt, expected_max_weight) = SpendableOutputDescriptor::create_spendable_outputs_psbt(descriptors, outputs, change_destination_script, feerate_sat_per_1000_weight, locktime)?;
1620 psbt = self.sign_spendable_outputs_psbt(descriptors, psbt, secp_ctx)?;
1622 let spend_tx = psbt.extract_tx();
1624 debug_assert!(expected_max_weight >= spend_tx.weight().to_wu());
1625 // Note that witnesses with a signature vary somewhat in size, so allow
1626 // `expected_max_weight` to overshoot by up to 3 bytes per input.
1627 debug_assert!(expected_max_weight <= spend_tx.weight().to_wu() + descriptors.len() as u64 * 3);
1633 impl EntropySource for KeysManager {
1634 fn get_secure_random_bytes(&self) -> [u8; 32] {
1635 self.entropy_source.get_secure_random_bytes()
1639 impl NodeSigner for KeysManager {
1640 fn get_node_id(&self, recipient: Recipient) -> Result<PublicKey, ()> {
1642 Recipient::Node => Ok(self.node_id.clone()),
1643 Recipient::PhantomNode => Err(())
1647 fn ecdh(&self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&Scalar>) -> Result<SharedSecret, ()> {
1648 let mut node_secret = match recipient {
1649 Recipient::Node => Ok(self.node_secret.clone()),
1650 Recipient::PhantomNode => Err(())
1652 if let Some(tweak) = tweak {
1653 node_secret = node_secret.mul_tweak(tweak).map_err(|_| ())?;
1655 Ok(SharedSecret::new(other_key, &node_secret))
1658 fn get_inbound_payment_key_material(&self) -> KeyMaterial {
1659 self.inbound_payment_key.clone()
1662 fn sign_invoice(&self, hrp_bytes: &[u8], invoice_data: &[u5], recipient: Recipient) -> Result<RecoverableSignature, ()> {
1663 let preimage = construct_invoice_preimage(&hrp_bytes, &invoice_data);
1664 let secret = match recipient {
1665 Recipient::Node => Ok(&self.node_secret),
1666 Recipient::PhantomNode => Err(())
1668 Ok(self.secp_ctx.sign_ecdsa_recoverable(&hash_to_message!(&Sha256::hash(&preimage).to_byte_array()), secret))
1671 fn sign_bolt12_invoice_request(
1672 &self, invoice_request: &UnsignedInvoiceRequest
1673 ) -> Result<schnorr::Signature, ()> {
1674 let message = invoice_request.tagged_hash().as_digest();
1675 let keys = KeyPair::from_secret_key(&self.secp_ctx, &self.node_secret);
1676 let aux_rand = self.get_secure_random_bytes();
1677 Ok(self.secp_ctx.sign_schnorr_with_aux_rand(message, &keys, &aux_rand))
1680 fn sign_bolt12_invoice(
1681 &self, invoice: &UnsignedBolt12Invoice
1682 ) -> Result<schnorr::Signature, ()> {
1683 let message = invoice.tagged_hash().as_digest();
1684 let keys = KeyPair::from_secret_key(&self.secp_ctx, &self.node_secret);
1685 let aux_rand = self.get_secure_random_bytes();
1686 Ok(self.secp_ctx.sign_schnorr_with_aux_rand(message, &keys, &aux_rand))
1689 fn sign_gossip_message(&self, msg: UnsignedGossipMessage) -> Result<Signature, ()> {
1690 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.encode()[..])[..]);
1691 Ok(self.secp_ctx.sign_ecdsa(&msg_hash, &self.node_secret))
1695 impl SignerProvider for KeysManager {
1696 type EcdsaSigner = InMemorySigner;
1698 type TaprootSigner = InMemorySigner;
1700 fn generate_channel_keys_id(&self, _inbound: bool, _channel_value_satoshis: u64, user_channel_id: u128) -> [u8; 32] {
1701 let child_idx = self.channel_child_index.fetch_add(1, Ordering::AcqRel);
1702 // `child_idx` is the only thing guaranteed to make each channel unique without a restart
1703 // (though `user_channel_id` should help, depending on user behavior). If it manages to
1704 // roll over, we may generate duplicate keys for two different channels, which could result
1705 // in loss of funds. Because we only support 32-bit+ systems, assert that our `AtomicUsize`
1706 // doesn't reach `u32::MAX`.
1707 assert!(child_idx < core::u32::MAX as usize, "2^32 channels opened without restart");
1708 let mut id = [0; 32];
1709 id[0..4].copy_from_slice(&(child_idx as u32).to_be_bytes());
1710 id[4..8].copy_from_slice(&self.starting_time_nanos.to_be_bytes());
1711 id[8..16].copy_from_slice(&self.starting_time_secs.to_be_bytes());
1712 id[16..32].copy_from_slice(&user_channel_id.to_be_bytes());
1716 fn derive_channel_signer(&self, channel_value_satoshis: u64, channel_keys_id: [u8; 32]) -> Self::EcdsaSigner {
1717 self.derive_channel_keys(channel_value_satoshis, &channel_keys_id)
1720 fn read_chan_signer(&self, reader: &[u8]) -> Result<Self::EcdsaSigner, DecodeError> {
1721 InMemorySigner::read(&mut io::Cursor::new(reader), self)
1724 fn get_destination_script(&self, _channel_keys_id: [u8; 32]) -> Result<ScriptBuf, ()> {
1725 Ok(self.destination_script.clone())
1728 fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()> {
1729 Ok(ShutdownScript::new_p2wpkh_from_pubkey(self.shutdown_pubkey.clone()))
1733 /// Similar to [`KeysManager`], but allows the node using this struct to receive phantom node
1736 /// A phantom node payment is a payment made to a phantom invoice, which is an invoice that can be
1737 /// paid to one of multiple nodes. This works because we encode the invoice route hints such that
1738 /// LDK will recognize an incoming payment as destined for a phantom node, and collect the payment
1739 /// itself without ever needing to forward to this fake node.
1741 /// Phantom node payments are useful for load balancing between multiple LDK nodes. They also
1742 /// provide some fault tolerance, because payers will automatically retry paying other provided
1743 /// nodes in the case that one node goes down.
1745 /// Note that multi-path payments are not supported in phantom invoices for security reasons.
1746 // In the hypothetical case that we did support MPP phantom payments, there would be no way for
1747 // nodes to know when the full payment has been received (and the preimage can be released) without
1748 // significantly compromising on our safety guarantees. I.e., if we expose the ability for the user
1749 // to tell LDK when the preimage can be released, we open ourselves to attacks where the preimage
1750 // is released too early.
1752 /// Switching between this struct and [`KeysManager`] will invalidate any previously issued
1753 /// invoices and attempts to pay previous invoices will fail.
1754 pub struct PhantomKeysManager {
1756 inbound_payment_key: KeyMaterial,
1757 phantom_secret: SecretKey,
1758 phantom_node_id: PublicKey,
1761 impl EntropySource for PhantomKeysManager {
1762 fn get_secure_random_bytes(&self) -> [u8; 32] {
1763 self.inner.get_secure_random_bytes()
1767 impl NodeSigner for PhantomKeysManager {
1768 fn get_node_id(&self, recipient: Recipient) -> Result<PublicKey, ()> {
1770 Recipient::Node => self.inner.get_node_id(Recipient::Node),
1771 Recipient::PhantomNode => Ok(self.phantom_node_id.clone()),
1775 fn ecdh(&self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&Scalar>) -> Result<SharedSecret, ()> {
1776 let mut node_secret = match recipient {
1777 Recipient::Node => self.inner.node_secret.clone(),
1778 Recipient::PhantomNode => self.phantom_secret.clone(),
1780 if let Some(tweak) = tweak {
1781 node_secret = node_secret.mul_tweak(tweak).map_err(|_| ())?;
1783 Ok(SharedSecret::new(other_key, &node_secret))
1786 fn get_inbound_payment_key_material(&self) -> KeyMaterial {
1787 self.inbound_payment_key.clone()
1790 fn sign_invoice(&self, hrp_bytes: &[u8], invoice_data: &[u5], recipient: Recipient) -> Result<RecoverableSignature, ()> {
1791 let preimage = construct_invoice_preimage(&hrp_bytes, &invoice_data);
1792 let secret = match recipient {
1793 Recipient::Node => &self.inner.node_secret,
1794 Recipient::PhantomNode => &self.phantom_secret,
1796 Ok(self.inner.secp_ctx.sign_ecdsa_recoverable(&hash_to_message!(&Sha256::hash(&preimage).to_byte_array()), secret))
1799 fn sign_bolt12_invoice_request(
1800 &self, invoice_request: &UnsignedInvoiceRequest
1801 ) -> Result<schnorr::Signature, ()> {
1802 self.inner.sign_bolt12_invoice_request(invoice_request)
1805 fn sign_bolt12_invoice(
1806 &self, invoice: &UnsignedBolt12Invoice
1807 ) -> Result<schnorr::Signature, ()> {
1808 self.inner.sign_bolt12_invoice(invoice)
1811 fn sign_gossip_message(&self, msg: UnsignedGossipMessage) -> Result<Signature, ()> {
1812 self.inner.sign_gossip_message(msg)
1816 impl SignerProvider for PhantomKeysManager {
1817 type EcdsaSigner = InMemorySigner;
1819 type TaprootSigner = InMemorySigner;
1821 fn generate_channel_keys_id(&self, inbound: bool, channel_value_satoshis: u64, user_channel_id: u128) -> [u8; 32] {
1822 self.inner.generate_channel_keys_id(inbound, channel_value_satoshis, user_channel_id)
1825 fn derive_channel_signer(&self, channel_value_satoshis: u64, channel_keys_id: [u8; 32]) -> Self::EcdsaSigner {
1826 self.inner.derive_channel_signer(channel_value_satoshis, channel_keys_id)
1829 fn read_chan_signer(&self, reader: &[u8]) -> Result<Self::EcdsaSigner, DecodeError> {
1830 self.inner.read_chan_signer(reader)
1833 fn get_destination_script(&self, channel_keys_id: [u8; 32]) -> Result<ScriptBuf, ()> {
1834 self.inner.get_destination_script(channel_keys_id)
1837 fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()> {
1838 self.inner.get_shutdown_scriptpubkey()
1842 impl PhantomKeysManager {
1843 /// Constructs a [`PhantomKeysManager`] given a 32-byte seed and an additional `cross_node_seed`
1844 /// that is shared across all nodes that intend to participate in [phantom node payments]
1847 /// See [`KeysManager::new`] for more information on `seed`, `starting_time_secs`, and
1848 /// `starting_time_nanos`.
1850 /// `cross_node_seed` must be the same across all phantom payment-receiving nodes and also the
1851 /// same across restarts, or else inbound payments may fail.
1853 /// [phantom node payments]: PhantomKeysManager
1854 pub fn new(seed: &[u8; 32], starting_time_secs: u64, starting_time_nanos: u32, cross_node_seed: &[u8; 32]) -> Self {
1855 let inner = KeysManager::new(seed, starting_time_secs, starting_time_nanos);
1856 let (inbound_key, phantom_key) = hkdf_extract_expand_twice(b"LDK Inbound and Phantom Payment Key Expansion", cross_node_seed);
1857 let phantom_secret = SecretKey::from_slice(&phantom_key).unwrap();
1858 let phantom_node_id = PublicKey::from_secret_key(&inner.secp_ctx, &phantom_secret);
1861 inbound_payment_key: KeyMaterial(inbound_key),
1867 /// See [`KeysManager::spend_spendable_outputs`] for documentation on this method.
1868 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, ()> {
1869 self.inner.spend_spendable_outputs(descriptors, outputs, change_destination_script, feerate_sat_per_1000_weight, locktime, secp_ctx)
1872 /// See [`KeysManager::derive_channel_keys`] for documentation on this method.
1873 pub fn derive_channel_keys(&self, channel_value_satoshis: u64, params: &[u8; 32]) -> InMemorySigner {
1874 self.inner.derive_channel_keys(channel_value_satoshis, params)
1877 /// Gets the "node_id" secret key used to sign gossip announcements, decode onion data, etc.
1878 pub fn get_node_secret_key(&self) -> SecretKey {
1879 self.inner.get_node_secret_key()
1882 /// Gets the "node_id" secret key of the phantom node used to sign invoices, decode the
1883 /// last-hop onion data, etc.
1884 pub fn get_phantom_node_secret_key(&self) -> SecretKey {
1889 /// An implementation of [`EntropySource`] using ChaCha20.
1891 pub struct RandomBytes {
1892 /// Seed from which all randomness produced is derived from.
1894 /// Tracks the number of times we've produced randomness to ensure we don't return the same
1896 index: AtomicCounter,
1900 /// Creates a new instance using the given seed.
1901 pub fn new(seed: [u8; 32]) -> Self {
1904 index: AtomicCounter::new(),
1909 impl EntropySource for RandomBytes {
1910 fn get_secure_random_bytes(&self) -> [u8; 32] {
1911 let index = self.index.get_increment();
1912 let mut nonce = [0u8; 16];
1913 nonce[..8].copy_from_slice(&index.to_be_bytes());
1914 ChaCha20::get_single_block(&self.seed, &nonce)
1918 // Ensure that EcdsaChannelSigner can have a vtable
1921 let _signer: Box<dyn EcdsaChannelSigner>;
1926 use std::sync::{Arc, mpsc};
1927 use std::sync::mpsc::TryRecvError;
1929 use std::time::Duration;
1930 use bitcoin::blockdata::constants::genesis_block;
1931 use bitcoin::Network;
1932 use crate::sign::{EntropySource, KeysManager};
1934 use criterion::Criterion;
1936 pub fn bench_get_secure_random_bytes(bench: &mut Criterion) {
1937 let seed = [0u8; 32];
1938 let now = Duration::from_secs(genesis_block(Network::Testnet).header.time as u64);
1939 let keys_manager = Arc::new(KeysManager::new(&seed, now.as_secs(), now.subsec_micros()));
1941 let mut handles = Vec::new();
1942 let mut stops = Vec::new();
1944 let keys_manager_clone = Arc::clone(&keys_manager);
1945 let (stop_sender, stop_receiver) = mpsc::channel();
1946 let handle = thread::spawn(move || {
1948 keys_manager_clone.get_secure_random_bytes();
1949 match stop_receiver.try_recv() {
1950 Ok(_) | Err(TryRecvError::Disconnected) => {
1951 println!("Terminating.");
1954 Err(TryRecvError::Empty) => {}
1958 handles.push(handle);
1959 stops.push(stop_sender);
1962 bench.bench_function("get_secure_random_bytes", |b| b.iter(||
1963 keys_manager.get_secure_random_bytes()));
1966 let _ = stop.send(());
1968 for handle in handles {
1969 handle.join().unwrap();