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::bip32::{ChildNumber, ExtendedPrivKey, ExtendedPubKey};
16 use bitcoin::blockdata::locktime::absolute::LockTime;
17 use bitcoin::blockdata::opcodes;
18 use bitcoin::blockdata::script::{Builder, Script, ScriptBuf};
19 use bitcoin::blockdata::transaction::{Transaction, TxIn, TxOut};
20 use bitcoin::ecdsa::Signature as EcdsaSignature;
21 use bitcoin::network::constants::Network;
22 use bitcoin::psbt::PartiallySignedTransaction;
24 use bitcoin::sighash::EcdsaSighashType;
26 use bitcoin::bech32::u5;
27 use bitcoin::hash_types::WPubkeyHash;
28 use bitcoin::hashes::sha256::Hash as Sha256;
29 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
30 use bitcoin::hashes::{Hash, HashEngine};
32 use bitcoin::secp256k1::ecdh::SharedSecret;
33 use bitcoin::secp256k1::ecdsa::{RecoverableSignature, Signature};
34 use bitcoin::secp256k1::schnorr;
36 use bitcoin::secp256k1::All;
37 use bitcoin::secp256k1::{KeyPair, PublicKey, Scalar, Secp256k1, SecretKey, Signing};
38 use bitcoin::{secp256k1, Sequence, Txid, Witness};
40 use crate::chain::transaction::OutPoint;
41 use crate::crypto::utils::{hkdf_extract_expand_twice, sign, sign_with_aux_rand};
42 use crate::ln::chan_utils::{
43 get_revokeable_redeemscript, make_funding_redeemscript, ChannelPublicKeys,
44 ChannelTransactionParameters, ClosingTransaction, CommitmentTransaction,
45 HTLCOutputInCommitment, HolderCommitmentTransaction,
47 use crate::ln::channel::ANCHOR_OUTPUT_VALUE_SATOSHI;
48 use crate::ln::channel_keys::{
49 add_public_key_tweak, DelayedPaymentBasepoint, DelayedPaymentKey, HtlcBasepoint, HtlcKey,
50 RevocationBasepoint, RevocationKey,
53 use crate::ln::msgs::PartialSignatureWithNonce;
54 use crate::ln::msgs::{UnsignedChannelAnnouncement, UnsignedGossipMessage};
55 use crate::ln::script::ShutdownScript;
56 use crate::ln::{chan_utils, PaymentPreimage};
57 use crate::offers::invoice::UnsignedBolt12Invoice;
58 use crate::offers::invoice_request::UnsignedInvoiceRequest;
59 use crate::util::ser::{Readable, ReadableArgs, Writeable, Writer};
60 use crate::util::transaction_utils;
62 use crate::crypto::chacha20::ChaCha20;
63 use crate::io::{self, Error};
64 use crate::ln::features::ChannelTypeFeatures;
65 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
66 use crate::prelude::*;
67 use crate::sign::ecdsa::{EcdsaChannelSigner, WriteableEcdsaChannelSigner};
69 use crate::sign::taproot::TaprootChannelSigner;
70 use crate::util::atomic_counter::AtomicCounter;
71 use crate::util::invoice::construct_invoice_preimage;
72 use core::convert::TryInto;
74 use core::sync::atomic::{AtomicUsize, Ordering};
76 use musig2::types::{PartialSignature, PublicNonce};
78 pub(crate) mod type_resolver;
84 /// Used as initial key material, to be expanded into multiple secret keys (but not to be used
85 /// directly). This is used within LDK to encrypt/decrypt inbound payment data.
87 /// This is not exported to bindings users as we just use `[u8; 32]` directly
88 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
89 pub struct KeyMaterial(pub [u8; 32]);
91 /// Information about a spendable output to a P2WSH script.
93 /// See [`SpendableOutputDescriptor::DelayedPaymentOutput`] for more details on how to spend this.
94 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
95 pub struct DelayedPaymentOutputDescriptor {
96 /// The outpoint which is spendable.
97 pub outpoint: OutPoint,
98 /// Per commitment point to derive the delayed payment key by key holder.
99 pub per_commitment_point: PublicKey,
100 /// The `nSequence` value which must be set in the spending input to satisfy the `OP_CSV` in
101 /// the witness_script.
102 pub to_self_delay: u16,
103 /// The output which is referenced by the given outpoint.
105 /// The revocation point specific to the commitment transaction which was broadcast. Used to
106 /// derive the witnessScript for this output.
107 pub revocation_pubkey: RevocationKey,
108 /// Arbitrary identification information returned by a call to [`ChannelSigner::channel_keys_id`].
109 /// This may be useful in re-deriving keys used in the channel to spend the output.
110 pub channel_keys_id: [u8; 32],
111 /// The value of the channel which this output originated from, possibly indirectly.
112 pub channel_value_satoshis: u64,
113 /// The channel public keys and other parameters needed to generate a spending transaction or to provide to a re-derived signer through
114 /// [`ChannelSigner::provide_channel_parameters`].
116 /// Added as optional, but always `Some` if the descriptor was produced in v0.0.123 or later.
117 pub channel_transaction_parameters: Option<ChannelTransactionParameters>,
120 impl DelayedPaymentOutputDescriptor {
121 /// The maximum length a well-formed witness spending one of these should have.
122 /// Note: If you have the grind_signatures feature enabled, this will be at least 1 byte
124 // Calculated as 1 byte length + 73 byte signature, 1 byte empty vec push, 1 byte length plus
125 // redeemscript push length.
126 pub const MAX_WITNESS_LENGTH: u64 =
127 1 + 73 + 1 + chan_utils::REVOKEABLE_REDEEMSCRIPT_MAX_LENGTH as u64 + 1;
130 impl_writeable_tlv_based!(DelayedPaymentOutputDescriptor, {
131 (0, outpoint, required),
132 (2, per_commitment_point, required),
133 (4, to_self_delay, required),
134 (6, output, required),
135 (8, revocation_pubkey, required),
136 (10, channel_keys_id, required),
137 (12, channel_value_satoshis, required),
138 (13, channel_transaction_parameters, option),
141 pub(crate) const P2WPKH_WITNESS_WEIGHT: u64 = 1 /* num stack items */ +
143 73 /* sig including sighash flag */ +
144 1 /* pubkey length */ +
147 /// Witness weight for satisying a P2TR key-path spend.
148 pub(crate) const P2TR_KEY_PATH_WITNESS_WEIGHT: u64 = 1 /* witness items */
149 + 1 /* schnorr sig len */ + 64 /* schnorr sig */;
151 /// Information about a spendable output to our "payment key".
153 /// See [`SpendableOutputDescriptor::StaticPaymentOutput`] for more details on how to spend this.
154 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
155 pub struct StaticPaymentOutputDescriptor {
156 /// The outpoint which is spendable.
157 pub outpoint: OutPoint,
158 /// The output which is referenced by the given outpoint.
160 /// Arbitrary identification information returned by a call to [`ChannelSigner::channel_keys_id`].
161 /// This may be useful in re-deriving keys used in the channel to spend the output.
162 pub channel_keys_id: [u8; 32],
163 /// The value of the channel which this transactions spends.
164 pub channel_value_satoshis: u64,
165 /// The necessary channel parameters that need to be provided to the re-derived signer through
166 /// [`ChannelSigner::provide_channel_parameters`].
168 /// Added as optional, but always `Some` if the descriptor was produced in v0.0.117 or later.
169 pub channel_transaction_parameters: Option<ChannelTransactionParameters>,
172 impl StaticPaymentOutputDescriptor {
173 /// Returns the `witness_script` of the spendable output.
175 /// Note that this will only return `Some` for [`StaticPaymentOutputDescriptor`]s that
176 /// originated from an anchor outputs channel, as they take the form of a P2WSH script.
177 pub fn witness_script(&self) -> Option<ScriptBuf> {
178 self.channel_transaction_parameters.as_ref().and_then(|channel_params| {
179 if channel_params.supports_anchors() {
180 let payment_point = channel_params.holder_pubkeys.payment_point;
181 Some(chan_utils::get_to_countersignatory_with_anchors_redeemscript(&payment_point))
188 /// The maximum length a well-formed witness spending one of these should have.
189 /// Note: If you have the grind_signatures feature enabled, this will be at least 1 byte
191 pub fn max_witness_length(&self) -> u64 {
192 if self.channel_transaction_parameters.as_ref().map_or(false, |p| p.supports_anchors()) {
193 let witness_script_weight = 1 /* pubkey push */ + 33 /* pubkey */ +
194 1 /* OP_CHECKSIGVERIFY */ + 1 /* OP_1 */ + 1 /* OP_CHECKSEQUENCEVERIFY */;
195 1 /* num witness items */ + 1 /* sig push */ + 73 /* sig including sighash flag */ +
196 1 /* witness script push */ + witness_script_weight
198 P2WPKH_WITNESS_WEIGHT
202 impl_writeable_tlv_based!(StaticPaymentOutputDescriptor, {
203 (0, outpoint, required),
204 (2, output, required),
205 (4, channel_keys_id, required),
206 (6, channel_value_satoshis, required),
207 (7, channel_transaction_parameters, option),
210 /// Describes the necessary information to spend a spendable output.
212 /// When on-chain outputs are created by LDK (which our counterparty is not able to claim at any
213 /// point in the future) a [`SpendableOutputs`] event is generated which you must track and be able
214 /// to spend on-chain. The information needed to do this is provided in this enum, including the
215 /// outpoint describing which `txid` and output `index` is available, the full output which exists
216 /// at that `txid`/`index`, and any keys or other information required to sign.
218 /// [`SpendableOutputs`]: crate::events::Event::SpendableOutputs
219 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
220 pub enum SpendableOutputDescriptor {
221 /// An output to a script which was provided via [`SignerProvider`] directly, either from
222 /// [`get_destination_script`] or [`get_shutdown_scriptpubkey`], thus you should already
223 /// know how to spend it. No secret keys are provided as LDK was never given any key.
224 /// These may include outputs from a transaction punishing our counterparty or claiming an HTLC
225 /// on-chain using the payment preimage or after it has timed out.
227 /// [`get_shutdown_scriptpubkey`]: SignerProvider::get_shutdown_scriptpubkey
228 /// [`get_destination_script`]: SignerProvider::get_shutdown_scriptpubkey
230 /// The outpoint which is spendable.
232 /// The output which is referenced by the given outpoint.
234 /// The `channel_keys_id` for the channel which this output came from.
236 /// For channels which were generated on LDK 0.0.119 or later, this is the value which was
237 /// passed to the [`SignerProvider::get_destination_script`] call which provided this
240 /// For channels which were generated prior to LDK 0.0.119, no such argument existed,
241 /// however this field may still be filled in if such data is available.
242 channel_keys_id: Option<[u8; 32]>,
244 /// An output to a P2WSH script which can be spent with a single signature after an `OP_CSV`
247 /// The witness in the spending input should be:
249 /// <BIP 143 signature> <empty vector> (MINIMALIF standard rule) <provided witnessScript>
252 /// Note that the `nSequence` field in the spending input must be set to
253 /// [`DelayedPaymentOutputDescriptor::to_self_delay`] (which means the transaction is not
254 /// broadcastable until at least [`DelayedPaymentOutputDescriptor::to_self_delay`] blocks after
255 /// the outpoint confirms, see [BIP
256 /// 68](https://github.com/bitcoin/bips/blob/master/bip-0068.mediawiki)). Also note that LDK
257 /// won't generate a [`SpendableOutputDescriptor`] until the corresponding block height
260 /// These are generally the result of a "revocable" output to us, spendable only by us unless
261 /// it is an output from an old state which we broadcast (which should never happen).
263 /// To derive the delayed payment key which is used to sign this input, you must pass the
264 /// holder [`InMemorySigner::delayed_payment_base_key`] (i.e., the private key which corresponds to the
265 /// [`ChannelPublicKeys::delayed_payment_basepoint`] in [`ChannelSigner::pubkeys`]) and the provided
266 /// [`DelayedPaymentOutputDescriptor::per_commitment_point`] to [`chan_utils::derive_private_key`]. The DelayedPaymentKey can be
267 /// generated without the secret key using [`DelayedPaymentKey::from_basepoint`] and only the
268 /// [`ChannelPublicKeys::delayed_payment_basepoint`] which appears in [`ChannelSigner::pubkeys`].
270 /// To derive the [`DelayedPaymentOutputDescriptor::revocation_pubkey`] provided here (which is
271 /// used in the witness script generation), you must pass the counterparty
272 /// [`ChannelPublicKeys::revocation_basepoint`] (which appears in the call to
273 /// [`ChannelSigner::provide_channel_parameters`]) and the provided
274 /// [`DelayedPaymentOutputDescriptor::per_commitment_point`] to
275 /// [`RevocationKey`].
277 /// The witness script which is hashed and included in the output `script_pubkey` may be
278 /// regenerated by passing the [`DelayedPaymentOutputDescriptor::revocation_pubkey`] (derived
279 /// as explained above), our delayed payment pubkey (derived as explained above), and the
280 /// [`DelayedPaymentOutputDescriptor::to_self_delay`] contained here to
281 /// [`chan_utils::get_revokeable_redeemscript`].
282 DelayedPaymentOutput(DelayedPaymentOutputDescriptor),
283 /// An output spendable exclusively by our payment key (i.e., the private key that corresponds
284 /// to the `payment_point` in [`ChannelSigner::pubkeys`]). The output type depends on the
285 /// channel type negotiated.
287 /// On an anchor outputs channel, the witness in the spending input is:
289 /// <BIP 143 signature> <witness script>
292 /// Otherwise, it is:
294 /// <BIP 143 signature> <payment key>
297 /// These are generally the result of our counterparty having broadcast the current state,
298 /// allowing us to claim the non-HTLC-encumbered outputs immediately, or after one confirmation
299 /// in the case of anchor outputs channels.
300 StaticPaymentOutput(StaticPaymentOutputDescriptor),
303 impl_writeable_tlv_based_enum!(SpendableOutputDescriptor,
304 (0, StaticOutput) => {
305 (0, outpoint, required),
306 (1, channel_keys_id, option),
307 (2, output, required),
310 (1, DelayedPaymentOutput),
311 (2, StaticPaymentOutput),
314 impl SpendableOutputDescriptor {
315 /// Turns this into a [`bitcoin::psbt::Input`] which can be used to create a
316 /// [`PartiallySignedTransaction`] which spends the given descriptor.
318 /// Note that this does not include any signatures, just the information required to
319 /// construct the transaction and sign it.
321 /// This is not exported to bindings users as there is no standard serialization for an input.
322 /// See [`Self::create_spendable_outputs_psbt`] instead.
324 /// The proprietary field is used to store add tweak for the signing key of this transaction.
325 /// See the [`DelayedPaymentBasepoint::derive_add_tweak`] docs for more info on add tweak and how to use it.
327 /// To get the proprietary field use:
329 /// use bitcoin::psbt::{PartiallySignedTransaction};
330 /// use bitcoin::hashes::hex::FromHex;
332 /// # let s = "70736274ff0100520200000001dee978529ab3e61a2987bea5183713d0e6d5ceb5ac81100fdb54a1a2\
333 /// # 69cef505000000000090000000011f26000000000000160014abb3ab63280d4ccc5c11d6b50fd427a8\
334 /// # e19d6470000000000001012b10270000000000002200200afe4736760d814a2651bae63b572d935d9a\
335 /// # b74a1a16c01774e341a32afa763601054d63210394a27a700617f5b7aee72bd4f8076b5770a582b7fb\
336 /// # d1d4ee2ea3802cd3cfbe2067029000b27521034629b1c8fdebfaeb58a74cd181f485e2c462e594cb30\
337 /// # 34dee655875f69f6c7c968ac20fc144c444b5f7370656e6461626c655f6f7574707574006164645f74\
338 /// # 7765616b20a86534f38ad61dc580ef41c3886204adf0911b81619c1ad7a2f5b5de39a2ba600000";
339 /// # let psbt = PartiallySignedTransaction::deserialize(<Vec<u8> as FromHex>::from_hex(s).unwrap().as_slice()).unwrap();
340 /// let key = bitcoin::psbt::raw::ProprietaryKey {
341 /// prefix: "LDK_spendable_output".as_bytes().to_vec(),
343 /// key: "add_tweak".as_bytes().to_vec(),
348 /// .expect("Unable to get add tweak as there are no inputs")
351 /// .map(|x| x.to_owned());
353 pub fn to_psbt_input<T: secp256k1::Signing>(
354 &self, secp_ctx: &Secp256k1<T>,
355 ) -> bitcoin::psbt::Input {
357 SpendableOutputDescriptor::StaticOutput { output, .. } => {
358 // Is a standard P2WPKH, no need for witness script
359 bitcoin::psbt::Input { witness_utxo: Some(output.clone()), ..Default::default() }
361 SpendableOutputDescriptor::DelayedPaymentOutput(DelayedPaymentOutputDescriptor {
362 channel_transaction_parameters,
363 per_commitment_point,
369 let delayed_payment_basepoint = channel_transaction_parameters
371 .map(|params| params.holder_pubkeys.delayed_payment_basepoint);
373 let (witness_script, add_tweak) =
374 if let Some(basepoint) = delayed_payment_basepoint.as_ref() {
375 // Required to derive signing key: privkey = basepoint_secret + SHA256(per_commitment_point || basepoint)
376 let add_tweak = basepoint.derive_add_tweak(&per_commitment_point);
377 let payment_key = DelayedPaymentKey(add_public_key_tweak(
379 &basepoint.to_public_key(),
384 Some(get_revokeable_redeemscript(
395 bitcoin::psbt::Input {
396 witness_utxo: Some(output.clone()),
398 proprietary: add_tweak
401 bitcoin::psbt::raw::ProprietaryKey {
402 // A non standard namespace for spendable outputs, used to store the tweak needed
403 // to derive the private key
404 prefix: "LDK_spendable_output".as_bytes().to_vec(),
406 key: "add_tweak".as_bytes().to_vec(),
413 .unwrap_or_default(),
417 SpendableOutputDescriptor::StaticPaymentOutput(descriptor) => bitcoin::psbt::Input {
418 witness_utxo: Some(descriptor.output.clone()),
419 witness_script: descriptor.witness_script(),
425 /// Creates an unsigned [`PartiallySignedTransaction`] which spends the given descriptors to
426 /// the given outputs, plus an output to the given change destination (if sufficient
427 /// change value remains). The PSBT will have a feerate, at least, of the given value.
429 /// The `locktime` argument is used to set the transaction's locktime. If `None`, the
430 /// transaction will have a locktime of 0. It it recommended to set this to the current block
431 /// height to avoid fee sniping, unless you have some specific reason to use a different
434 /// Returns the PSBT and expected max transaction weight.
436 /// Returns `Err(())` if the output value is greater than the input value minus required fee,
437 /// if a descriptor was duplicated, or if an output descriptor `script_pubkey`
438 /// does not match the one we can spend.
440 /// We do not enforce that outputs meet the dust limit or that any output scripts are standard.
441 pub fn create_spendable_outputs_psbt<T: secp256k1::Signing>(
442 secp_ctx: &Secp256k1<T>, descriptors: &[&SpendableOutputDescriptor], outputs: Vec<TxOut>,
443 change_destination_script: ScriptBuf, feerate_sat_per_1000_weight: u32,
444 locktime: Option<LockTime>,
445 ) -> Result<(PartiallySignedTransaction, u64), ()> {
446 let mut input = Vec::with_capacity(descriptors.len());
447 let mut input_value = 0;
448 let mut witness_weight = 0;
449 let mut output_set = hash_set_with_capacity(descriptors.len());
450 for outp in descriptors {
452 SpendableOutputDescriptor::StaticPaymentOutput(descriptor) => {
453 if !output_set.insert(descriptor.outpoint) {
456 let sequence = if descriptor
457 .channel_transaction_parameters
459 .map_or(false, |p| p.supports_anchors())
461 Sequence::from_consensus(1)
466 previous_output: descriptor.outpoint.into_bitcoin_outpoint(),
467 script_sig: ScriptBuf::new(),
469 witness: Witness::new(),
471 witness_weight += descriptor.max_witness_length();
472 #[cfg(feature = "grind_signatures")]
474 // Guarantees a low R signature
477 input_value += descriptor.output.value;
479 SpendableOutputDescriptor::DelayedPaymentOutput(descriptor) => {
480 if !output_set.insert(descriptor.outpoint) {
484 previous_output: descriptor.outpoint.into_bitcoin_outpoint(),
485 script_sig: ScriptBuf::new(),
486 sequence: Sequence(descriptor.to_self_delay as u32),
487 witness: Witness::new(),
489 witness_weight += DelayedPaymentOutputDescriptor::MAX_WITNESS_LENGTH;
490 #[cfg(feature = "grind_signatures")]
492 // Guarantees a low R signature
495 input_value += descriptor.output.value;
497 SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output, .. } => {
498 if !output_set.insert(*outpoint) {
502 previous_output: outpoint.into_bitcoin_outpoint(),
503 script_sig: ScriptBuf::new(),
504 sequence: Sequence::ZERO,
505 witness: Witness::new(),
507 witness_weight += 1 + 73 + 34;
508 #[cfg(feature = "grind_signatures")]
510 // Guarantees a low R signature
513 input_value += output.value;
516 if input_value > MAX_VALUE_MSAT / 1000 {
520 let mut tx = Transaction {
522 lock_time: locktime.unwrap_or(LockTime::ZERO),
526 let expected_max_weight = transaction_utils::maybe_add_change_output(
530 feerate_sat_per_1000_weight,
531 change_destination_script,
535 descriptors.iter().map(|d| d.to_psbt_input(&secp_ctx)).collect::<Vec<_>>();
536 let psbt = PartiallySignedTransaction {
538 outputs: vec![Default::default(); tx.output.len()],
540 xpub: Default::default(),
542 proprietary: Default::default(),
543 unknown: Default::default(),
545 Ok((psbt, expected_max_weight))
549 /// The parameters required to derive a channel signer via [`SignerProvider`].
550 #[derive(Clone, Debug, PartialEq, Eq)]
551 pub struct ChannelDerivationParameters {
552 /// The value in satoshis of the channel we're attempting to spend the anchor output of.
553 pub value_satoshis: u64,
554 /// The unique identifier to re-derive the signer for the associated channel.
555 pub keys_id: [u8; 32],
556 /// The necessary channel parameters that need to be provided to the re-derived signer through
557 /// [`ChannelSigner::provide_channel_parameters`].
558 pub transaction_parameters: ChannelTransactionParameters,
561 impl_writeable_tlv_based!(ChannelDerivationParameters, {
562 (0, value_satoshis, required),
563 (2, keys_id, required),
564 (4, transaction_parameters, required),
567 /// A descriptor used to sign for a commitment transaction's HTLC output.
568 #[derive(Clone, Debug, PartialEq, Eq)]
569 pub struct HTLCDescriptor {
570 /// The parameters required to derive the signer for the HTLC input.
571 pub channel_derivation_parameters: ChannelDerivationParameters,
572 /// The txid of the commitment transaction in which the HTLC output lives.
573 pub commitment_txid: Txid,
574 /// The number of the commitment transaction in which the HTLC output lives.
575 pub per_commitment_number: u64,
576 /// The key tweak corresponding to the number of the commitment transaction in which the HTLC
577 /// output lives. This tweak is applied to all the basepoints for both parties in the channel to
578 /// arrive at unique keys per commitment.
580 /// See <https://github.com/lightning/bolts/blob/master/03-transactions.md#keys> for more info.
581 pub per_commitment_point: PublicKey,
582 /// The feerate to use on the HTLC claiming transaction. This is always `0` for HTLCs
583 /// originating from a channel supporting anchor outputs, otherwise it is the channel's
584 /// negotiated feerate at the time the commitment transaction was built.
585 pub feerate_per_kw: u32,
586 /// The details of the HTLC as it appears in the commitment transaction.
587 pub htlc: HTLCOutputInCommitment,
588 /// The preimage, if `Some`, to claim the HTLC output with. If `None`, the timeout path must be
590 pub preimage: Option<PaymentPreimage>,
591 /// The counterparty's signature required to spend the HTLC output.
592 pub counterparty_sig: Signature,
595 impl_writeable_tlv_based!(HTLCDescriptor, {
596 (0, channel_derivation_parameters, required),
597 (1, feerate_per_kw, (default_value, 0)),
598 (2, commitment_txid, required),
599 (4, per_commitment_number, required),
600 (6, per_commitment_point, required),
602 (10, preimage, option),
603 (12, counterparty_sig, required),
606 impl HTLCDescriptor {
607 /// Returns the outpoint of the HTLC output in the commitment transaction. This is the outpoint
608 /// being spent by the HTLC input in the HTLC transaction.
609 pub fn outpoint(&self) -> bitcoin::OutPoint {
611 txid: self.commitment_txid,
612 vout: self.htlc.transaction_output_index.unwrap(),
616 /// Returns the UTXO to be spent by the HTLC input, which can be obtained via
617 /// [`Self::unsigned_tx_input`].
618 pub fn previous_utxo<C: secp256k1::Signing + secp256k1::Verification>(
619 &self, secp: &Secp256k1<C>,
622 script_pubkey: self.witness_script(secp).to_v0_p2wsh(),
623 value: self.htlc.amount_msat / 1000,
627 /// Returns the unsigned transaction input spending the HTLC output in the commitment
629 pub fn unsigned_tx_input(&self) -> TxIn {
630 chan_utils::build_htlc_input(
631 &self.commitment_txid,
633 &self.channel_derivation_parameters.transaction_parameters.channel_type_features,
637 /// Returns the delayed output created as a result of spending the HTLC output in the commitment
639 pub fn tx_output<C: secp256k1::Signing + secp256k1::Verification>(
640 &self, secp: &Secp256k1<C>,
643 self.channel_derivation_parameters.transaction_parameters.as_holder_broadcastable();
644 let broadcaster_keys = channel_params.broadcaster_pubkeys();
645 let counterparty_keys = channel_params.countersignatory_pubkeys();
646 let broadcaster_delayed_key = DelayedPaymentKey::from_basepoint(
648 &broadcaster_keys.delayed_payment_basepoint,
649 &self.per_commitment_point,
651 let counterparty_revocation_key = &RevocationKey::from_basepoint(
653 &counterparty_keys.revocation_basepoint,
654 &self.per_commitment_point,
656 chan_utils::build_htlc_output(
658 channel_params.contest_delay(),
660 channel_params.channel_type_features(),
661 &broadcaster_delayed_key,
662 &counterparty_revocation_key,
666 /// Returns the witness script of the HTLC output in the commitment transaction.
667 pub fn witness_script<C: secp256k1::Signing + secp256k1::Verification>(
668 &self, secp: &Secp256k1<C>,
671 self.channel_derivation_parameters.transaction_parameters.as_holder_broadcastable();
672 let broadcaster_keys = channel_params.broadcaster_pubkeys();
673 let counterparty_keys = channel_params.countersignatory_pubkeys();
674 let broadcaster_htlc_key = HtlcKey::from_basepoint(
676 &broadcaster_keys.htlc_basepoint,
677 &self.per_commitment_point,
679 let counterparty_htlc_key = HtlcKey::from_basepoint(
681 &counterparty_keys.htlc_basepoint,
682 &self.per_commitment_point,
684 let counterparty_revocation_key = &RevocationKey::from_basepoint(
686 &counterparty_keys.revocation_basepoint,
687 &self.per_commitment_point,
689 chan_utils::get_htlc_redeemscript_with_explicit_keys(
691 channel_params.channel_type_features(),
692 &broadcaster_htlc_key,
693 &counterparty_htlc_key,
694 &counterparty_revocation_key,
698 /// Returns the fully signed witness required to spend the HTLC output in the commitment
700 pub fn tx_input_witness(&self, signature: &Signature, witness_script: &Script) -> Witness {
701 chan_utils::build_htlc_input_witness(
703 &self.counterparty_sig,
706 &self.channel_derivation_parameters.transaction_parameters.channel_type_features,
710 /// Derives the channel signer required to sign the HTLC input.
711 pub fn derive_channel_signer<S: WriteableEcdsaChannelSigner, SP: Deref>(
712 &self, signer_provider: &SP,
715 SP::Target: SignerProvider<EcdsaSigner = S>,
717 let mut signer = signer_provider.derive_channel_signer(
718 self.channel_derivation_parameters.value_satoshis,
719 self.channel_derivation_parameters.keys_id,
722 .provide_channel_parameters(&self.channel_derivation_parameters.transaction_parameters);
727 /// A trait to handle Lightning channel key material without concretizing the channel type or
728 /// the signature mechanism.
729 pub trait ChannelSigner {
730 /// Gets the per-commitment point for a specific commitment number
732 /// Note that the commitment number starts at `(1 << 48) - 1` and counts backwards.
733 fn get_per_commitment_point(&self, idx: u64, secp_ctx: &Secp256k1<secp256k1::All>)
736 /// Gets the commitment secret for a specific commitment number as part of the revocation process
738 /// An external signer implementation should error here if the commitment was already signed
739 /// and should refuse to sign it in the future.
741 /// May be called more than once for the same index.
743 /// Note that the commitment number starts at `(1 << 48) - 1` and counts backwards.
744 // TODO: return a Result so we can signal a validation error
745 fn release_commitment_secret(&self, idx: u64) -> [u8; 32];
747 /// Validate the counterparty's signatures on the holder commitment transaction and HTLCs.
749 /// This is required in order for the signer to make sure that releasing a commitment
750 /// secret won't leave us without a broadcastable holder transaction.
751 /// Policy checks should be implemented in this function, including checking the amount
752 /// sent to us and checking the HTLCs.
754 /// The preimages of outbound HTLCs that were fulfilled since the last commitment are provided.
755 /// A validating signer should ensure that an HTLC output is removed only when the matching
756 /// preimage is provided, or when the value to holder is restored.
758 /// Note that all the relevant preimages will be provided, but there may also be additional
759 /// irrelevant or duplicate preimages.
760 fn validate_holder_commitment(
761 &self, holder_tx: &HolderCommitmentTransaction,
762 outbound_htlc_preimages: Vec<PaymentPreimage>,
765 /// Validate the counterparty's revocation.
767 /// This is required in order for the signer to make sure that the state has moved
768 /// forward and it is safe to sign the next counterparty commitment.
769 fn validate_counterparty_revocation(&self, idx: u64, secret: &SecretKey) -> Result<(), ()>;
771 /// Returns the holder's channel public keys and basepoints.
772 fn pubkeys(&self) -> &ChannelPublicKeys;
774 /// Returns an arbitrary identifier describing the set of keys which are provided back to you in
775 /// some [`SpendableOutputDescriptor`] types. This should be sufficient to identify this
776 /// [`EcdsaChannelSigner`] object uniquely and lookup or re-derive its keys.
777 fn channel_keys_id(&self) -> [u8; 32];
779 /// Set the counterparty static channel data, including basepoints,
780 /// `counterparty_selected`/`holder_selected_contest_delay` and funding outpoint.
782 /// This data is static, and will never change for a channel once set. For a given [`ChannelSigner`]
783 /// instance, LDK will call this method exactly once - either immediately after construction
784 /// (not including if done via [`SignerProvider::read_chan_signer`]) or when the funding
785 /// information has been generated.
787 /// channel_parameters.is_populated() MUST be true.
788 fn provide_channel_parameters(&mut self, channel_parameters: &ChannelTransactionParameters);
791 /// Specifies the recipient of an invoice.
793 /// This indicates to [`NodeSigner::sign_invoice`] what node secret key should be used to sign
796 /// The invoice should be signed with the local node secret key.
798 /// The invoice should be signed with the phantom node secret key. This secret key must be the
799 /// same for all nodes participating in the [phantom node payment].
801 /// [phantom node payment]: PhantomKeysManager
805 /// A trait that describes a source of entropy.
806 pub trait EntropySource {
807 /// Gets a unique, cryptographically-secure, random 32-byte value. This method must return a
808 /// different value each time it is called.
809 fn get_secure_random_bytes(&self) -> [u8; 32];
812 /// A trait that can handle cryptographic operations at the scope level of a node.
813 pub trait NodeSigner {
814 /// Get secret key material as bytes for use in encrypting and decrypting inbound payment data.
816 /// If the implementor of this trait supports [phantom node payments], then every node that is
817 /// intended to be included in the phantom invoice route hints must return the same value from
819 // This is because LDK avoids storing inbound payment data by encrypting payment data in the
820 // payment hash and/or payment secret, therefore for a payment to be receivable by multiple
821 // nodes, they must share the key that encrypts this payment data.
823 /// This method must return the same value each time it is called.
825 /// [phantom node payments]: PhantomKeysManager
826 fn get_inbound_payment_key_material(&self) -> KeyMaterial;
828 /// Get node id based on the provided [`Recipient`].
830 /// This method must return the same value each time it is called with a given [`Recipient`]
833 /// Errors if the [`Recipient`] variant is not supported by the implementation.
834 fn get_node_id(&self, recipient: Recipient) -> Result<PublicKey, ()>;
836 /// Gets the ECDH shared secret of our node secret and `other_key`, multiplying by `tweak` if
837 /// one is provided. Note that this tweak can be applied to `other_key` instead of our node
838 /// secret, though this is less efficient.
840 /// Note that if this fails while attempting to forward an HTLC, LDK will panic. The error
841 /// should be resolved to allow LDK to resume forwarding HTLCs.
843 /// Errors if the [`Recipient`] variant is not supported by the implementation.
845 &self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&Scalar>,
846 ) -> Result<SharedSecret, ()>;
850 /// By parameterizing by the raw invoice bytes instead of the hash, we allow implementors of
851 /// this trait to parse the invoice and make sure they're signing what they expect, rather than
852 /// blindly signing the hash.
854 /// The `hrp_bytes` are ASCII bytes, while the `invoice_data` is base32.
856 /// The secret key used to sign the invoice is dependent on the [`Recipient`].
858 /// Errors if the [`Recipient`] variant is not supported by the implementation.
860 &self, hrp_bytes: &[u8], invoice_data: &[u5], recipient: Recipient,
861 ) -> Result<RecoverableSignature, ()>;
863 /// Signs the [`TaggedHash`] of a BOLT 12 invoice request.
865 /// May be called by a function passed to [`UnsignedInvoiceRequest::sign`] where
866 /// `invoice_request` is the callee.
868 /// Implementors may check that the `invoice_request` is expected rather than blindly signing
869 /// the tagged hash. An `Ok` result should sign `invoice_request.tagged_hash().as_digest()` with
870 /// the node's signing key or an ephemeral key to preserve privacy, whichever is associated with
871 /// [`UnsignedInvoiceRequest::payer_id`].
873 /// [`TaggedHash`]: crate::offers::merkle::TaggedHash
874 fn sign_bolt12_invoice_request(
875 &self, invoice_request: &UnsignedInvoiceRequest,
876 ) -> Result<schnorr::Signature, ()>;
878 /// Signs the [`TaggedHash`] of a BOLT 12 invoice.
880 /// May be called by a function passed to [`UnsignedBolt12Invoice::sign`] where `invoice` is the
883 /// Implementors may check that the `invoice` is expected rather than blindly signing the tagged
884 /// hash. An `Ok` result should sign `invoice.tagged_hash().as_digest()` with the node's signing
885 /// key or an ephemeral key to preserve privacy, whichever is associated with
886 /// [`UnsignedBolt12Invoice::signing_pubkey`].
888 /// [`TaggedHash`]: crate::offers::merkle::TaggedHash
889 fn sign_bolt12_invoice(
890 &self, invoice: &UnsignedBolt12Invoice,
891 ) -> Result<schnorr::Signature, ()>;
893 /// Sign a gossip message.
895 /// Note that if this fails, LDK may panic and the message will not be broadcast to the network
896 /// or a possible channel counterparty. If LDK panics, the error should be resolved to allow the
897 /// message to be broadcast, as otherwise it may prevent one from receiving funds over the
898 /// corresponding channel.
899 fn sign_gossip_message(&self, msg: UnsignedGossipMessage) -> Result<Signature, ()>;
902 /// A trait that describes a wallet capable of creating a spending [`Transaction`] from a set of
903 /// [`SpendableOutputDescriptor`]s.
904 pub trait OutputSpender {
905 /// Creates a [`Transaction`] which spends the given descriptors to the given outputs, plus an
906 /// output to the given change destination (if sufficient change value remains). The
907 /// transaction will have a feerate, at least, of the given value.
909 /// The `locktime` argument is used to set the transaction's locktime. If `None`, the
910 /// transaction will have a locktime of 0. It it recommended to set this to the current block
911 /// height to avoid fee sniping, unless you have some specific reason to use a different
914 /// Returns `Err(())` if the output value is greater than the input value minus required fee,
915 /// if a descriptor was duplicated, or if an output descriptor `script_pubkey`
916 /// does not match the one we can spend.
917 fn spend_spendable_outputs<C: Signing>(
918 &self, descriptors: &[&SpendableOutputDescriptor], outputs: Vec<TxOut>,
919 change_destination_script: ScriptBuf, feerate_sat_per_1000_weight: u32,
920 locktime: Option<LockTime>, secp_ctx: &Secp256k1<C>,
921 ) -> Result<Transaction, ()>;
924 // Primarily needed in doctests because of https://github.com/rust-lang/rust/issues/67295
925 /// A dynamic [`SignerProvider`] temporarily needed for doc tests.
928 #[deprecated(note = "Remove once taproot cfg is removed")]
929 pub type DynSignerProvider =
930 dyn SignerProvider<EcdsaSigner = InMemorySigner, TaprootSigner = InMemorySigner>;
932 /// A dynamic [`SignerProvider`] temporarily needed for doc tests.
935 #[deprecated(note = "Remove once taproot cfg is removed")]
936 pub type DynSignerProvider = dyn SignerProvider<EcdsaSigner = InMemorySigner>;
938 /// A trait that can return signer instances for individual channels.
939 pub trait SignerProvider {
940 /// A type which implements [`WriteableEcdsaChannelSigner`] which will be returned by [`Self::derive_channel_signer`].
941 type EcdsaSigner: WriteableEcdsaChannelSigner;
943 /// A type which implements [`TaprootChannelSigner`]
944 type TaprootSigner: TaprootChannelSigner;
946 /// Generates a unique `channel_keys_id` that can be used to obtain a [`Self::EcdsaSigner`] through
947 /// [`SignerProvider::derive_channel_signer`]. The `user_channel_id` is provided to allow
948 /// implementations of [`SignerProvider`] to maintain a mapping between itself and the generated
949 /// `channel_keys_id`.
951 /// This method must return a different value each time it is called.
952 fn generate_channel_keys_id(
953 &self, inbound: bool, channel_value_satoshis: u64, user_channel_id: u128,
956 /// Derives the private key material backing a `Signer`.
958 /// To derive a new `Signer`, a fresh `channel_keys_id` should be obtained through
959 /// [`SignerProvider::generate_channel_keys_id`]. Otherwise, an existing `Signer` can be
960 /// re-derived from its `channel_keys_id`, which can be obtained through its trait method
961 /// [`ChannelSigner::channel_keys_id`].
962 fn derive_channel_signer(
963 &self, channel_value_satoshis: u64, channel_keys_id: [u8; 32],
964 ) -> Self::EcdsaSigner;
966 /// Reads a [`Signer`] for this [`SignerProvider`] from the given input stream.
967 /// This is only called during deserialization of other objects which contain
968 /// [`WriteableEcdsaChannelSigner`]-implementing objects (i.e., [`ChannelMonitor`]s and [`ChannelManager`]s).
969 /// The bytes are exactly those which `<Self::Signer as Writeable>::write()` writes, and
970 /// contain no versioning scheme. You may wish to include your own version prefix and ensure
971 /// you've read all of the provided bytes to ensure no corruption occurred.
973 /// This method is slowly being phased out -- it will only be called when reading objects
974 /// written by LDK versions prior to 0.0.113.
976 /// [`Signer`]: Self::EcdsaSigner
977 /// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
978 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
979 fn read_chan_signer(&self, reader: &[u8]) -> Result<Self::EcdsaSigner, DecodeError>;
981 /// Get a script pubkey which we send funds to when claiming on-chain contestable outputs.
983 /// If this function returns an error, this will result in a channel failing to open.
985 /// This method should return a different value each time it is called, to avoid linking
986 /// on-chain funds across channels as controlled to the same user. `channel_keys_id` may be
987 /// used to derive a unique value for each channel.
988 fn get_destination_script(&self, channel_keys_id: [u8; 32]) -> Result<ScriptBuf, ()>;
990 /// Get a script pubkey which we will send funds to when closing a channel.
992 /// If this function returns an error, this will result in a channel failing to open or close.
993 /// In the event of a failure when the counterparty is initiating a close, this can result in a
994 /// channel force close.
996 /// This method should return a different value each time it is called, to avoid linking
997 /// on-chain funds across channels as controlled to the same user.
998 fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()>;
1001 /// A helper trait that describes an on-chain wallet capable of returning a (change) destination
1003 pub trait ChangeDestinationSource {
1004 /// Returns a script pubkey which can be used as a change destination for
1005 /// [`OutputSpender::spend_spendable_outputs`].
1007 /// This method should return a different value each time it is called, to avoid linking
1008 /// on-chain funds controlled to the same user.
1009 fn get_change_destination_script(&self) -> Result<ScriptBuf, ()>;
1012 /// A simple implementation of [`WriteableEcdsaChannelSigner`] that just keeps the private keys in memory.
1014 /// This implementation performs no policy checks and is insufficient by itself as
1015 /// a secure external signer.
1017 pub struct InMemorySigner {
1018 /// Holder secret key in the 2-of-2 multisig script of a channel. This key also backs the
1019 /// holder's anchor output in a commitment transaction, if one is present.
1020 pub funding_key: SecretKey,
1021 /// Holder secret key for blinded revocation pubkey.
1022 pub revocation_base_key: SecretKey,
1023 /// Holder secret key used for our balance in counterparty-broadcasted commitment transactions.
1024 pub payment_key: SecretKey,
1025 /// Holder secret key used in an HTLC transaction.
1026 pub delayed_payment_base_key: SecretKey,
1027 /// Holder HTLC secret key used in commitment transaction HTLC outputs.
1028 pub htlc_base_key: SecretKey,
1029 /// Commitment seed.
1030 pub commitment_seed: [u8; 32],
1031 /// Holder public keys and basepoints.
1032 pub(crate) holder_channel_pubkeys: ChannelPublicKeys,
1033 /// Counterparty public keys and counterparty/holder `selected_contest_delay`, populated on channel acceptance.
1034 channel_parameters: Option<ChannelTransactionParameters>,
1035 /// The total value of this channel.
1036 channel_value_satoshis: u64,
1037 /// Key derivation parameters.
1038 channel_keys_id: [u8; 32],
1039 /// A source of random bytes.
1040 entropy_source: RandomBytes,
1043 impl PartialEq for InMemorySigner {
1044 fn eq(&self, other: &Self) -> bool {
1045 self.funding_key == other.funding_key
1046 && self.revocation_base_key == other.revocation_base_key
1047 && self.payment_key == other.payment_key
1048 && self.delayed_payment_base_key == other.delayed_payment_base_key
1049 && self.htlc_base_key == other.htlc_base_key
1050 && self.commitment_seed == other.commitment_seed
1051 && self.holder_channel_pubkeys == other.holder_channel_pubkeys
1052 && self.channel_parameters == other.channel_parameters
1053 && self.channel_value_satoshis == other.channel_value_satoshis
1054 && self.channel_keys_id == other.channel_keys_id
1058 impl Clone for InMemorySigner {
1059 fn clone(&self) -> Self {
1061 funding_key: self.funding_key.clone(),
1062 revocation_base_key: self.revocation_base_key.clone(),
1063 payment_key: self.payment_key.clone(),
1064 delayed_payment_base_key: self.delayed_payment_base_key.clone(),
1065 htlc_base_key: self.htlc_base_key.clone(),
1066 commitment_seed: self.commitment_seed.clone(),
1067 holder_channel_pubkeys: self.holder_channel_pubkeys.clone(),
1068 channel_parameters: self.channel_parameters.clone(),
1069 channel_value_satoshis: self.channel_value_satoshis,
1070 channel_keys_id: self.channel_keys_id,
1071 entropy_source: RandomBytes::new(self.get_secure_random_bytes()),
1076 impl InMemorySigner {
1077 /// Creates a new [`InMemorySigner`].
1078 pub fn new<C: Signing>(
1079 secp_ctx: &Secp256k1<C>, funding_key: SecretKey, revocation_base_key: SecretKey,
1080 payment_key: SecretKey, delayed_payment_base_key: SecretKey, htlc_base_key: SecretKey,
1081 commitment_seed: [u8; 32], channel_value_satoshis: u64, channel_keys_id: [u8; 32],
1082 rand_bytes_unique_start: [u8; 32],
1083 ) -> InMemorySigner {
1084 let holder_channel_pubkeys = InMemorySigner::make_holder_keys(
1087 &revocation_base_key,
1089 &delayed_payment_base_key,
1094 revocation_base_key,
1096 delayed_payment_base_key,
1099 channel_value_satoshis,
1100 holder_channel_pubkeys,
1101 channel_parameters: None,
1103 entropy_source: RandomBytes::new(rand_bytes_unique_start),
1107 fn make_holder_keys<C: Signing>(
1108 secp_ctx: &Secp256k1<C>, funding_key: &SecretKey, revocation_base_key: &SecretKey,
1109 payment_key: &SecretKey, delayed_payment_base_key: &SecretKey, htlc_base_key: &SecretKey,
1110 ) -> ChannelPublicKeys {
1111 let from_secret = |s: &SecretKey| PublicKey::from_secret_key(secp_ctx, s);
1113 funding_pubkey: from_secret(&funding_key),
1114 revocation_basepoint: RevocationBasepoint::from(from_secret(&revocation_base_key)),
1115 payment_point: from_secret(&payment_key),
1116 delayed_payment_basepoint: DelayedPaymentBasepoint::from(from_secret(
1117 &delayed_payment_base_key,
1119 htlc_basepoint: HtlcBasepoint::from(from_secret(&htlc_base_key)),
1123 /// Returns the counterparty's pubkeys.
1125 /// Will return `None` if [`ChannelSigner::provide_channel_parameters`] has not been called.
1126 /// In general, this is safe to `unwrap` only in [`ChannelSigner`] implementation.
1127 pub fn counterparty_pubkeys(&self) -> Option<&ChannelPublicKeys> {
1128 self.get_channel_parameters().and_then(|params| {
1129 params.counterparty_parameters.as_ref().map(|params| ¶ms.pubkeys)
1133 /// Returns the `contest_delay` value specified by our counterparty and applied on holder-broadcastable
1134 /// transactions, i.e., the amount of time that we have to wait to recover our funds if we
1135 /// broadcast a transaction.
1137 /// Will return `None` if [`ChannelSigner::provide_channel_parameters`] has not been called.
1138 /// In general, this is safe to `unwrap` only in [`ChannelSigner`] implementation.
1139 pub fn counterparty_selected_contest_delay(&self) -> Option<u16> {
1140 self.get_channel_parameters().and_then(|params| {
1141 params.counterparty_parameters.as_ref().map(|params| params.selected_contest_delay)
1145 /// Returns the `contest_delay` value specified by us and applied on transactions broadcastable
1146 /// by our counterparty, i.e., the amount of time that they have to wait to recover their funds
1147 /// if they broadcast a transaction.
1149 /// Will return `None` if [`ChannelSigner::provide_channel_parameters`] has not been called.
1150 /// In general, this is safe to `unwrap` only in [`ChannelSigner`] implementation.
1151 pub fn holder_selected_contest_delay(&self) -> Option<u16> {
1152 self.get_channel_parameters().map(|params| params.holder_selected_contest_delay)
1155 /// Returns whether the holder is the initiator.
1157 /// Will return `None` if [`ChannelSigner::provide_channel_parameters`] has not been called.
1158 /// In general, this is safe to `unwrap` only in [`ChannelSigner`] implementation.
1159 pub fn is_outbound(&self) -> Option<bool> {
1160 self.get_channel_parameters().map(|params| params.is_outbound_from_holder)
1163 /// Funding outpoint
1165 /// Will return `None` if [`ChannelSigner::provide_channel_parameters`] has not been called.
1166 /// In general, this is safe to `unwrap` only in [`ChannelSigner`] implementation.
1167 pub fn funding_outpoint(&self) -> Option<&OutPoint> {
1168 self.get_channel_parameters().map(|params| params.funding_outpoint.as_ref()).flatten()
1171 /// Returns a [`ChannelTransactionParameters`] for this channel, to be used when verifying or
1172 /// building transactions.
1174 /// Will return `None` if [`ChannelSigner::provide_channel_parameters`] has not been called.
1175 /// In general, this is safe to `unwrap` only in [`ChannelSigner`] implementation.
1176 pub fn get_channel_parameters(&self) -> Option<&ChannelTransactionParameters> {
1177 self.channel_parameters.as_ref()
1180 /// Returns the channel type features of the channel parameters. Should be helpful for
1181 /// determining a channel's category, i. e. legacy/anchors/taproot/etc.
1183 /// Will return `None` if [`ChannelSigner::provide_channel_parameters`] has not been called.
1184 /// In general, this is safe to `unwrap` only in [`ChannelSigner`] implementation.
1185 pub fn channel_type_features(&self) -> Option<&ChannelTypeFeatures> {
1186 self.get_channel_parameters().map(|params| ¶ms.channel_type_features)
1189 /// Sign the single input of `spend_tx` at index `input_idx`, which spends the output described
1190 /// by `descriptor`, returning the witness stack for the input.
1192 /// Returns an error if the input at `input_idx` does not exist, has a non-empty `script_sig`,
1193 /// is not spending the outpoint described by [`descriptor.outpoint`],
1194 /// or if an output descriptor `script_pubkey` does not match the one we can spend.
1196 /// [`descriptor.outpoint`]: StaticPaymentOutputDescriptor::outpoint
1197 pub fn sign_counterparty_payment_input<C: Signing>(
1198 &self, spend_tx: &Transaction, input_idx: usize,
1199 descriptor: &StaticPaymentOutputDescriptor, secp_ctx: &Secp256k1<C>,
1200 ) -> Result<Witness, ()> {
1201 // TODO: We really should be taking the SigHashCache as a parameter here instead of
1202 // spend_tx, but ideally the SigHashCache would expose the transaction's inputs read-only
1203 // so that we can check them. This requires upstream rust-bitcoin changes (as well as
1204 // bindings updates to support SigHashCache objects).
1205 if spend_tx.input.len() <= input_idx {
1208 if !spend_tx.input[input_idx].script_sig.is_empty() {
1211 if spend_tx.input[input_idx].previous_output != descriptor.outpoint.into_bitcoin_outpoint()
1216 let remotepubkey = bitcoin::PublicKey::new(self.pubkeys().payment_point);
1217 // We cannot always assume that `channel_parameters` is set, so can't just call
1218 // `self.channel_parameters()` or anything that relies on it
1219 let supports_anchors_zero_fee_htlc_tx = self
1220 .channel_type_features()
1221 .map(|features| features.supports_anchors_zero_fee_htlc_tx())
1224 let witness_script = if supports_anchors_zero_fee_htlc_tx {
1225 chan_utils::get_to_countersignatory_with_anchors_redeemscript(&remotepubkey.inner)
1227 ScriptBuf::new_p2pkh(&remotepubkey.pubkey_hash())
1229 let sighash = hash_to_message!(
1230 &sighash::SighashCache::new(spend_tx)
1231 .segwit_signature_hash(
1234 descriptor.output.value,
1235 EcdsaSighashType::All
1239 let remotesig = sign_with_aux_rand(secp_ctx, &sighash, &self.payment_key, &self);
1240 let payment_script = if supports_anchors_zero_fee_htlc_tx {
1241 witness_script.to_v0_p2wsh()
1243 ScriptBuf::new_v0_p2wpkh(&remotepubkey.wpubkey_hash().unwrap())
1246 if payment_script != descriptor.output.script_pubkey {
1250 let mut witness = Vec::with_capacity(2);
1251 witness.push(remotesig.serialize_der().to_vec());
1252 witness[0].push(EcdsaSighashType::All as u8);
1253 if supports_anchors_zero_fee_htlc_tx {
1254 witness.push(witness_script.to_bytes());
1256 witness.push(remotepubkey.to_bytes());
1261 /// Sign the single input of `spend_tx` at index `input_idx` which spends the output
1262 /// described by `descriptor`, returning the witness stack for the input.
1264 /// Returns an error if the input at `input_idx` does not exist, has a non-empty `script_sig`,
1265 /// is not spending the outpoint described by [`descriptor.outpoint`], does not have a
1266 /// sequence set to [`descriptor.to_self_delay`], or if an output descriptor
1267 /// `script_pubkey` does not match the one we can spend.
1269 /// [`descriptor.outpoint`]: DelayedPaymentOutputDescriptor::outpoint
1270 /// [`descriptor.to_self_delay`]: DelayedPaymentOutputDescriptor::to_self_delay
1271 pub fn sign_dynamic_p2wsh_input<C: Signing>(
1272 &self, spend_tx: &Transaction, input_idx: usize,
1273 descriptor: &DelayedPaymentOutputDescriptor, secp_ctx: &Secp256k1<C>,
1274 ) -> Result<Witness, ()> {
1275 // TODO: We really should be taking the SigHashCache as a parameter here instead of
1276 // spend_tx, but ideally the SigHashCache would expose the transaction's inputs read-only
1277 // so that we can check them. This requires upstream rust-bitcoin changes (as well as
1278 // bindings updates to support SigHashCache objects).
1279 if spend_tx.input.len() <= input_idx {
1282 if !spend_tx.input[input_idx].script_sig.is_empty() {
1285 if spend_tx.input[input_idx].previous_output != descriptor.outpoint.into_bitcoin_outpoint()
1289 if spend_tx.input[input_idx].sequence.0 != descriptor.to_self_delay as u32 {
1293 let delayed_payment_key = chan_utils::derive_private_key(
1295 &descriptor.per_commitment_point,
1296 &self.delayed_payment_base_key,
1298 let delayed_payment_pubkey =
1299 DelayedPaymentKey::from_secret_key(&secp_ctx, &delayed_payment_key);
1300 let witness_script = chan_utils::get_revokeable_redeemscript(
1301 &descriptor.revocation_pubkey,
1302 descriptor.to_self_delay,
1303 &delayed_payment_pubkey,
1305 let sighash = hash_to_message!(
1306 &sighash::SighashCache::new(spend_tx)
1307 .segwit_signature_hash(
1310 descriptor.output.value,
1311 EcdsaSighashType::All
1315 let local_delayedsig = EcdsaSignature {
1316 sig: sign_with_aux_rand(secp_ctx, &sighash, &delayed_payment_key, &self),
1317 hash_ty: EcdsaSighashType::All,
1319 let payment_script =
1320 bitcoin::Address::p2wsh(&witness_script, Network::Bitcoin).script_pubkey();
1322 if descriptor.output.script_pubkey != payment_script {
1326 Ok(Witness::from_slice(&[
1327 &local_delayedsig.serialize()[..],
1329 witness_script.as_bytes(),
1334 impl EntropySource for InMemorySigner {
1335 fn get_secure_random_bytes(&self) -> [u8; 32] {
1336 self.entropy_source.get_secure_random_bytes()
1340 impl ChannelSigner for InMemorySigner {
1341 fn get_per_commitment_point(
1342 &self, idx: u64, secp_ctx: &Secp256k1<secp256k1::All>,
1344 let commitment_secret =
1345 SecretKey::from_slice(&chan_utils::build_commitment_secret(&self.commitment_seed, idx))
1347 PublicKey::from_secret_key(secp_ctx, &commitment_secret)
1350 fn release_commitment_secret(&self, idx: u64) -> [u8; 32] {
1351 chan_utils::build_commitment_secret(&self.commitment_seed, idx)
1354 fn validate_holder_commitment(
1355 &self, _holder_tx: &HolderCommitmentTransaction,
1356 _outbound_htlc_preimages: Vec<PaymentPreimage>,
1357 ) -> Result<(), ()> {
1361 fn validate_counterparty_revocation(&self, _idx: u64, _secret: &SecretKey) -> Result<(), ()> {
1365 fn pubkeys(&self) -> &ChannelPublicKeys {
1366 &self.holder_channel_pubkeys
1369 fn channel_keys_id(&self) -> [u8; 32] {
1370 self.channel_keys_id
1373 fn provide_channel_parameters(&mut self, channel_parameters: &ChannelTransactionParameters) {
1375 self.channel_parameters.is_none()
1376 || self.channel_parameters.as_ref().unwrap() == channel_parameters
1378 if self.channel_parameters.is_some() {
1379 // The channel parameters were already set and they match, return early.
1382 assert!(channel_parameters.is_populated(), "Channel parameters must be fully populated");
1383 self.channel_parameters = Some(channel_parameters.clone());
1387 const MISSING_PARAMS_ERR: &'static str =
1388 "ChannelSigner::provide_channel_parameters must be called before signing operations";
1390 impl EcdsaChannelSigner for InMemorySigner {
1391 fn sign_counterparty_commitment(
1392 &self, commitment_tx: &CommitmentTransaction,
1393 _inbound_htlc_preimages: Vec<PaymentPreimage>,
1394 _outbound_htlc_preimages: Vec<PaymentPreimage>, secp_ctx: &Secp256k1<secp256k1::All>,
1395 ) -> Result<(Signature, Vec<Signature>), ()> {
1396 let trusted_tx = commitment_tx.trust();
1397 let keys = trusted_tx.keys();
1399 let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
1400 let counterparty_keys = self.counterparty_pubkeys().expect(MISSING_PARAMS_ERR);
1401 let channel_funding_redeemscript =
1402 make_funding_redeemscript(&funding_pubkey, &counterparty_keys.funding_pubkey);
1404 let built_tx = trusted_tx.built_transaction();
1405 let commitment_sig = built_tx.sign_counterparty_commitment(
1407 &channel_funding_redeemscript,
1408 self.channel_value_satoshis,
1411 let commitment_txid = built_tx.txid;
1413 let mut htlc_sigs = Vec::with_capacity(commitment_tx.htlcs().len());
1414 for htlc in commitment_tx.htlcs() {
1415 let channel_parameters = self.get_channel_parameters().expect(MISSING_PARAMS_ERR);
1416 let holder_selected_contest_delay =
1417 self.holder_selected_contest_delay().expect(MISSING_PARAMS_ERR);
1418 let chan_type = &channel_parameters.channel_type_features;
1419 let htlc_tx = chan_utils::build_htlc_transaction(
1421 commitment_tx.feerate_per_kw(),
1422 holder_selected_contest_delay,
1425 &keys.broadcaster_delayed_payment_key,
1426 &keys.revocation_key,
1428 let htlc_redeemscript = chan_utils::get_htlc_redeemscript(&htlc, chan_type, &keys);
1429 let htlc_sighashtype = if chan_type.supports_anchors_zero_fee_htlc_tx() {
1430 EcdsaSighashType::SinglePlusAnyoneCanPay
1432 EcdsaSighashType::All
1434 let htlc_sighash = hash_to_message!(
1435 &sighash::SighashCache::new(&htlc_tx)
1436 .segwit_signature_hash(
1439 htlc.amount_msat / 1000,
1444 let holder_htlc_key = chan_utils::derive_private_key(
1446 &keys.per_commitment_point,
1447 &self.htlc_base_key,
1449 htlc_sigs.push(sign(secp_ctx, &htlc_sighash, &holder_htlc_key));
1452 Ok((commitment_sig, htlc_sigs))
1455 fn sign_holder_commitment(
1456 &self, commitment_tx: &HolderCommitmentTransaction, secp_ctx: &Secp256k1<secp256k1::All>,
1457 ) -> Result<Signature, ()> {
1458 let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
1459 let counterparty_keys = self.counterparty_pubkeys().expect(MISSING_PARAMS_ERR);
1460 let funding_redeemscript =
1461 make_funding_redeemscript(&funding_pubkey, &counterparty_keys.funding_pubkey);
1462 let trusted_tx = commitment_tx.trust();
1463 Ok(trusted_tx.built_transaction().sign_holder_commitment(
1465 &funding_redeemscript,
1466 self.channel_value_satoshis,
1472 #[cfg(any(test, feature = "unsafe_revoked_tx_signing"))]
1473 fn unsafe_sign_holder_commitment(
1474 &self, commitment_tx: &HolderCommitmentTransaction, secp_ctx: &Secp256k1<secp256k1::All>,
1475 ) -> Result<Signature, ()> {
1476 let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
1477 let counterparty_keys = self.counterparty_pubkeys().expect(MISSING_PARAMS_ERR);
1478 let funding_redeemscript =
1479 make_funding_redeemscript(&funding_pubkey, &counterparty_keys.funding_pubkey);
1480 let trusted_tx = commitment_tx.trust();
1481 Ok(trusted_tx.built_transaction().sign_holder_commitment(
1483 &funding_redeemscript,
1484 self.channel_value_satoshis,
1490 fn sign_justice_revoked_output(
1491 &self, justice_tx: &Transaction, input: usize, amount: u64, per_commitment_key: &SecretKey,
1492 secp_ctx: &Secp256k1<secp256k1::All>,
1493 ) -> Result<Signature, ()> {
1494 let revocation_key = chan_utils::derive_private_revocation_key(
1496 &per_commitment_key,
1497 &self.revocation_base_key,
1499 let per_commitment_point = PublicKey::from_secret_key(secp_ctx, &per_commitment_key);
1500 let revocation_pubkey = RevocationKey::from_basepoint(
1502 &self.pubkeys().revocation_basepoint,
1503 &per_commitment_point,
1505 let witness_script = {
1506 let counterparty_keys = self.counterparty_pubkeys().expect(MISSING_PARAMS_ERR);
1507 let holder_selected_contest_delay =
1508 self.holder_selected_contest_delay().expect(MISSING_PARAMS_ERR);
1509 let counterparty_delayedpubkey = DelayedPaymentKey::from_basepoint(
1511 &counterparty_keys.delayed_payment_basepoint,
1512 &per_commitment_point,
1514 chan_utils::get_revokeable_redeemscript(
1516 holder_selected_contest_delay,
1517 &counterparty_delayedpubkey,
1520 let mut sighash_parts = sighash::SighashCache::new(justice_tx);
1521 let sighash = hash_to_message!(
1523 .segwit_signature_hash(input, &witness_script, amount, EcdsaSighashType::All)
1526 return Ok(sign_with_aux_rand(secp_ctx, &sighash, &revocation_key, &self));
1529 fn sign_justice_revoked_htlc(
1530 &self, justice_tx: &Transaction, input: usize, amount: u64, per_commitment_key: &SecretKey,
1531 htlc: &HTLCOutputInCommitment, secp_ctx: &Secp256k1<secp256k1::All>,
1532 ) -> Result<Signature, ()> {
1533 let revocation_key = chan_utils::derive_private_revocation_key(
1535 &per_commitment_key,
1536 &self.revocation_base_key,
1538 let per_commitment_point = PublicKey::from_secret_key(secp_ctx, &per_commitment_key);
1539 let revocation_pubkey = RevocationKey::from_basepoint(
1541 &self.pubkeys().revocation_basepoint,
1542 &per_commitment_point,
1544 let witness_script = {
1545 let counterparty_keys = self.counterparty_pubkeys().expect(MISSING_PARAMS_ERR);
1546 let counterparty_htlcpubkey = HtlcKey::from_basepoint(
1548 &counterparty_keys.htlc_basepoint,
1549 &per_commitment_point,
1551 let holder_htlcpubkey = HtlcKey::from_basepoint(
1553 &self.pubkeys().htlc_basepoint,
1554 &per_commitment_point,
1556 let chan_type = self.channel_type_features().expect(MISSING_PARAMS_ERR);
1557 chan_utils::get_htlc_redeemscript_with_explicit_keys(
1560 &counterparty_htlcpubkey,
1565 let mut sighash_parts = sighash::SighashCache::new(justice_tx);
1566 let sighash = hash_to_message!(
1568 .segwit_signature_hash(input, &witness_script, amount, EcdsaSighashType::All)
1571 return Ok(sign_with_aux_rand(secp_ctx, &sighash, &revocation_key, &self));
1574 fn sign_holder_htlc_transaction(
1575 &self, htlc_tx: &Transaction, input: usize, htlc_descriptor: &HTLCDescriptor,
1576 secp_ctx: &Secp256k1<secp256k1::All>,
1577 ) -> Result<Signature, ()> {
1578 let witness_script = htlc_descriptor.witness_script(secp_ctx);
1579 let sighash = &sighash::SighashCache::new(&*htlc_tx)
1580 .segwit_signature_hash(
1583 htlc_descriptor.htlc.amount_msat / 1000,
1584 EcdsaSighashType::All,
1587 let our_htlc_private_key = chan_utils::derive_private_key(
1589 &htlc_descriptor.per_commitment_point,
1590 &self.htlc_base_key,
1592 let sighash = hash_to_message!(sighash.as_byte_array());
1593 Ok(sign_with_aux_rand(&secp_ctx, &sighash, &our_htlc_private_key, &self))
1596 fn sign_counterparty_htlc_transaction(
1597 &self, htlc_tx: &Transaction, input: usize, amount: u64, per_commitment_point: &PublicKey,
1598 htlc: &HTLCOutputInCommitment, secp_ctx: &Secp256k1<secp256k1::All>,
1599 ) -> Result<Signature, ()> {
1601 chan_utils::derive_private_key(&secp_ctx, &per_commitment_point, &self.htlc_base_key);
1602 let revocation_pubkey = RevocationKey::from_basepoint(
1604 &self.pubkeys().revocation_basepoint,
1605 &per_commitment_point,
1607 let counterparty_keys = self.counterparty_pubkeys().expect(MISSING_PARAMS_ERR);
1608 let counterparty_htlcpubkey = HtlcKey::from_basepoint(
1610 &counterparty_keys.htlc_basepoint,
1611 &per_commitment_point,
1613 let htlc_basepoint = self.pubkeys().htlc_basepoint;
1614 let htlcpubkey = HtlcKey::from_basepoint(&secp_ctx, &htlc_basepoint, &per_commitment_point);
1615 let chan_type = self.channel_type_features().expect(MISSING_PARAMS_ERR);
1616 let witness_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(
1619 &counterparty_htlcpubkey,
1623 let mut sighash_parts = sighash::SighashCache::new(htlc_tx);
1624 let sighash = hash_to_message!(
1626 .segwit_signature_hash(input, &witness_script, amount, EcdsaSighashType::All)
1629 Ok(sign_with_aux_rand(secp_ctx, &sighash, &htlc_key, &self))
1632 fn sign_closing_transaction(
1633 &self, closing_tx: &ClosingTransaction, secp_ctx: &Secp256k1<secp256k1::All>,
1634 ) -> Result<Signature, ()> {
1635 let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
1636 let counterparty_funding_key =
1637 &self.counterparty_pubkeys().expect(MISSING_PARAMS_ERR).funding_pubkey;
1638 let channel_funding_redeemscript =
1639 make_funding_redeemscript(&funding_pubkey, counterparty_funding_key);
1640 Ok(closing_tx.trust().sign(
1642 &channel_funding_redeemscript,
1643 self.channel_value_satoshis,
1648 fn sign_holder_anchor_input(
1649 &self, anchor_tx: &Transaction, input: usize, secp_ctx: &Secp256k1<secp256k1::All>,
1650 ) -> Result<Signature, ()> {
1651 let witness_script =
1652 chan_utils::get_anchor_redeemscript(&self.holder_channel_pubkeys.funding_pubkey);
1653 let sighash = sighash::SighashCache::new(&*anchor_tx)
1654 .segwit_signature_hash(
1657 ANCHOR_OUTPUT_VALUE_SATOSHI,
1658 EcdsaSighashType::All,
1661 Ok(sign_with_aux_rand(secp_ctx, &hash_to_message!(&sighash[..]), &self.funding_key, &self))
1664 fn sign_channel_announcement_with_funding_key(
1665 &self, msg: &UnsignedChannelAnnouncement, secp_ctx: &Secp256k1<secp256k1::All>,
1666 ) -> Result<Signature, ()> {
1667 let msghash = hash_to_message!(&Sha256dHash::hash(&msg.encode()[..])[..]);
1668 Ok(secp_ctx.sign_ecdsa(&msghash, &self.funding_key))
1673 impl TaprootChannelSigner for InMemorySigner {
1674 fn generate_local_nonce_pair(
1675 &self, commitment_number: u64, secp_ctx: &Secp256k1<All>,
1680 fn partially_sign_counterparty_commitment(
1681 &self, counterparty_nonce: PublicNonce, commitment_tx: &CommitmentTransaction,
1682 inbound_htlc_preimages: Vec<PaymentPreimage>,
1683 outbound_htlc_preimages: Vec<PaymentPreimage>, secp_ctx: &Secp256k1<All>,
1684 ) -> Result<(PartialSignatureWithNonce, Vec<schnorr::Signature>), ()> {
1688 fn finalize_holder_commitment(
1689 &self, commitment_tx: &HolderCommitmentTransaction,
1690 counterparty_partial_signature: PartialSignatureWithNonce, secp_ctx: &Secp256k1<All>,
1691 ) -> Result<PartialSignature, ()> {
1695 fn sign_justice_revoked_output(
1696 &self, justice_tx: &Transaction, input: usize, amount: u64, per_commitment_key: &SecretKey,
1697 secp_ctx: &Secp256k1<All>,
1698 ) -> Result<schnorr::Signature, ()> {
1702 fn sign_justice_revoked_htlc(
1703 &self, justice_tx: &Transaction, input: usize, amount: u64, per_commitment_key: &SecretKey,
1704 htlc: &HTLCOutputInCommitment, secp_ctx: &Secp256k1<All>,
1705 ) -> Result<schnorr::Signature, ()> {
1709 fn sign_holder_htlc_transaction(
1710 &self, htlc_tx: &Transaction, input: usize, htlc_descriptor: &HTLCDescriptor,
1711 secp_ctx: &Secp256k1<All>,
1712 ) -> Result<schnorr::Signature, ()> {
1716 fn sign_counterparty_htlc_transaction(
1717 &self, htlc_tx: &Transaction, input: usize, amount: u64, per_commitment_point: &PublicKey,
1718 htlc: &HTLCOutputInCommitment, secp_ctx: &Secp256k1<All>,
1719 ) -> Result<schnorr::Signature, ()> {
1723 fn partially_sign_closing_transaction(
1724 &self, closing_tx: &ClosingTransaction, secp_ctx: &Secp256k1<All>,
1725 ) -> Result<PartialSignature, ()> {
1729 fn sign_holder_anchor_input(
1730 &self, anchor_tx: &Transaction, input: usize, secp_ctx: &Secp256k1<All>,
1731 ) -> Result<schnorr::Signature, ()> {
1736 const SERIALIZATION_VERSION: u8 = 1;
1738 const MIN_SERIALIZATION_VERSION: u8 = 1;
1740 impl WriteableEcdsaChannelSigner for InMemorySigner {}
1742 impl Writeable for InMemorySigner {
1743 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), Error> {
1744 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
1746 self.funding_key.write(writer)?;
1747 self.revocation_base_key.write(writer)?;
1748 self.payment_key.write(writer)?;
1749 self.delayed_payment_base_key.write(writer)?;
1750 self.htlc_base_key.write(writer)?;
1751 self.commitment_seed.write(writer)?;
1752 self.channel_parameters.write(writer)?;
1753 self.channel_value_satoshis.write(writer)?;
1754 self.channel_keys_id.write(writer)?;
1756 write_tlv_fields!(writer, {});
1762 impl<ES: Deref> ReadableArgs<ES> for InMemorySigner
1764 ES::Target: EntropySource,
1766 fn read<R: io::Read>(reader: &mut R, entropy_source: ES) -> Result<Self, DecodeError> {
1767 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
1769 let funding_key = Readable::read(reader)?;
1770 let revocation_base_key = Readable::read(reader)?;
1771 let payment_key = Readable::read(reader)?;
1772 let delayed_payment_base_key = Readable::read(reader)?;
1773 let htlc_base_key = Readable::read(reader)?;
1774 let commitment_seed = Readable::read(reader)?;
1775 let counterparty_channel_data = Readable::read(reader)?;
1776 let channel_value_satoshis = Readable::read(reader)?;
1777 let secp_ctx = Secp256k1::signing_only();
1778 let holder_channel_pubkeys = InMemorySigner::make_holder_keys(
1781 &revocation_base_key,
1783 &delayed_payment_base_key,
1786 let keys_id = Readable::read(reader)?;
1788 read_tlv_fields!(reader, {});
1792 revocation_base_key,
1794 delayed_payment_base_key,
1797 channel_value_satoshis,
1798 holder_channel_pubkeys,
1799 channel_parameters: counterparty_channel_data,
1800 channel_keys_id: keys_id,
1801 entropy_source: RandomBytes::new(entropy_source.get_secure_random_bytes()),
1806 /// Simple implementation of [`EntropySource`], [`NodeSigner`], and [`SignerProvider`] that takes a
1807 /// 32-byte seed for use as a BIP 32 extended key and derives keys from that.
1809 /// Your `node_id` is seed/0'.
1810 /// Unilateral closes may use seed/1'.
1811 /// Cooperative closes may use seed/2'.
1812 /// The two close keys may be needed to claim on-chain funds!
1814 /// This struct cannot be used for nodes that wish to support receiving phantom payments;
1815 /// [`PhantomKeysManager`] must be used instead.
1817 /// Note that switching between this struct and [`PhantomKeysManager`] will invalidate any
1818 /// previously issued invoices and attempts to pay previous invoices will fail.
1819 pub struct KeysManager {
1820 secp_ctx: Secp256k1<secp256k1::All>,
1821 node_secret: SecretKey,
1823 inbound_payment_key: KeyMaterial,
1824 destination_script: ScriptBuf,
1825 shutdown_pubkey: PublicKey,
1826 channel_master_key: ExtendedPrivKey,
1827 channel_child_index: AtomicUsize,
1829 entropy_source: RandomBytes,
1832 starting_time_secs: u64,
1833 starting_time_nanos: u32,
1837 /// Constructs a [`KeysManager`] from a 32-byte seed. If the seed is in some way biased (e.g.,
1838 /// your CSRNG is busted) this may panic (but more importantly, you will possibly lose funds).
1839 /// `starting_time` isn't strictly required to actually be a time, but it must absolutely,
1840 /// without a doubt, be unique to this instance. ie if you start multiple times with the same
1841 /// `seed`, `starting_time` must be unique to each run. Thus, the easiest way to achieve this
1842 /// is to simply use the current time (with very high precision).
1844 /// The `seed` MUST be backed up safely prior to use so that the keys can be re-created, however,
1845 /// obviously, `starting_time` should be unique every time you reload the library - it is only
1846 /// used to generate new ephemeral key data (which will be stored by the individual channel if
1849 /// Note that the seed is required to recover certain on-chain funds independent of
1850 /// [`ChannelMonitor`] data, though a current copy of [`ChannelMonitor`] data is also required
1851 /// for any channel, and some on-chain during-closing funds.
1853 /// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
1854 pub fn new(seed: &[u8; 32], starting_time_secs: u64, starting_time_nanos: u32) -> Self {
1855 let secp_ctx = Secp256k1::new();
1856 // Note that when we aren't serializing the key, network doesn't matter
1857 match ExtendedPrivKey::new_master(Network::Testnet, seed) {
1859 let node_secret = master_key
1860 .ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(0).unwrap())
1861 .expect("Your RNG is busted")
1863 let node_id = PublicKey::from_secret_key(&secp_ctx, &node_secret);
1864 let destination_script = match master_key
1865 .ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(1).unwrap())
1867 Ok(destination_key) => {
1868 let wpubkey_hash = WPubkeyHash::hash(
1869 &ExtendedPubKey::from_priv(&secp_ctx, &destination_key)
1874 .push_opcode(opcodes::all::OP_PUSHBYTES_0)
1875 .push_slice(&wpubkey_hash.to_byte_array())
1878 Err(_) => panic!("Your RNG is busted"),
1880 let shutdown_pubkey = match master_key
1881 .ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(2).unwrap())
1883 Ok(shutdown_key) => {
1884 ExtendedPubKey::from_priv(&secp_ctx, &shutdown_key).public_key
1886 Err(_) => panic!("Your RNG is busted"),
1888 let channel_master_key = master_key
1889 .ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(3).unwrap())
1890 .expect("Your RNG is busted");
1891 let inbound_payment_key: SecretKey = master_key
1892 .ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(5).unwrap())
1893 .expect("Your RNG is busted")
1895 let mut inbound_pmt_key_bytes = [0; 32];
1896 inbound_pmt_key_bytes.copy_from_slice(&inbound_payment_key[..]);
1898 let mut rand_bytes_engine = Sha256::engine();
1899 rand_bytes_engine.input(&starting_time_secs.to_be_bytes());
1900 rand_bytes_engine.input(&starting_time_nanos.to_be_bytes());
1901 rand_bytes_engine.input(seed);
1902 rand_bytes_engine.input(b"LDK PRNG Seed");
1903 let rand_bytes_unique_start =
1904 Sha256::from_engine(rand_bytes_engine).to_byte_array();
1906 let mut res = KeysManager {
1910 inbound_payment_key: KeyMaterial(inbound_pmt_key_bytes),
1916 channel_child_index: AtomicUsize::new(0),
1918 entropy_source: RandomBytes::new(rand_bytes_unique_start),
1922 starting_time_nanos,
1924 let secp_seed = res.get_secure_random_bytes();
1925 res.secp_ctx.seeded_randomize(&secp_seed);
1928 Err(_) => panic!("Your rng is busted"),
1932 /// Gets the "node_id" secret key used to sign gossip announcements, decode onion data, etc.
1933 pub fn get_node_secret_key(&self) -> SecretKey {
1937 /// Derive an old [`WriteableEcdsaChannelSigner`] containing per-channel secrets based on a key derivation parameters.
1938 pub fn derive_channel_keys(
1939 &self, channel_value_satoshis: u64, params: &[u8; 32],
1940 ) -> InMemorySigner {
1941 let chan_id = u64::from_be_bytes(params[0..8].try_into().unwrap());
1942 let mut unique_start = Sha256::engine();
1943 unique_start.input(params);
1944 unique_start.input(&self.seed);
1946 // We only seriously intend to rely on the channel_master_key for true secure
1947 // entropy, everything else just ensures uniqueness. We rely on the unique_start (ie
1948 // starting_time provided in the constructor) to be unique.
1949 let child_privkey = self
1953 ChildNumber::from_hardened_idx((chan_id as u32) % (1 << 31))
1954 .expect("key space exhausted"),
1956 .expect("Your RNG is busted");
1957 unique_start.input(&child_privkey.private_key[..]);
1959 let seed = Sha256::from_engine(unique_start).to_byte_array();
1961 let commitment_seed = {
1962 let mut sha = Sha256::engine();
1964 sha.input(&b"commitment seed"[..]);
1965 Sha256::from_engine(sha).to_byte_array()
1967 macro_rules! key_step {
1968 ($info: expr, $prev_key: expr) => {{
1969 let mut sha = Sha256::engine();
1971 sha.input(&$prev_key[..]);
1972 sha.input(&$info[..]);
1973 SecretKey::from_slice(&Sha256::from_engine(sha).to_byte_array())
1974 .expect("SHA-256 is busted")
1977 let funding_key = key_step!(b"funding key", commitment_seed);
1978 let revocation_base_key = key_step!(b"revocation base key", funding_key);
1979 let payment_key = key_step!(b"payment key", revocation_base_key);
1980 let delayed_payment_base_key = key_step!(b"delayed payment base key", payment_key);
1981 let htlc_base_key = key_step!(b"HTLC base key", delayed_payment_base_key);
1982 let prng_seed = self.get_secure_random_bytes();
1984 InMemorySigner::new(
1987 revocation_base_key,
1989 delayed_payment_base_key,
1992 channel_value_satoshis,
1998 /// Signs the given [`PartiallySignedTransaction`] which spends the given [`SpendableOutputDescriptor`]s.
1999 /// The resulting inputs will be finalized and the PSBT will be ready for broadcast if there
2000 /// are no other inputs that need signing.
2002 /// Returns `Err(())` if the PSBT is missing a descriptor or if we fail to sign.
2004 /// May panic if the [`SpendableOutputDescriptor`]s were not generated by channels which used
2005 /// this [`KeysManager`] or one of the [`InMemorySigner`] created by this [`KeysManager`].
2006 pub fn sign_spendable_outputs_psbt<C: Signing>(
2007 &self, descriptors: &[&SpendableOutputDescriptor], mut psbt: PartiallySignedTransaction,
2008 secp_ctx: &Secp256k1<C>,
2009 ) -> Result<PartiallySignedTransaction, ()> {
2010 let mut keys_cache: Option<(InMemorySigner, [u8; 32])> = None;
2011 for outp in descriptors {
2012 let get_input_idx = |outpoint: &OutPoint| {
2016 .position(|i| i.previous_output == outpoint.into_bitcoin_outpoint())
2020 SpendableOutputDescriptor::StaticPaymentOutput(descriptor) => {
2021 let input_idx = get_input_idx(&descriptor.outpoint)?;
2022 if keys_cache.is_none()
2023 || keys_cache.as_ref().unwrap().1 != descriptor.channel_keys_id
2025 let mut signer = self.derive_channel_keys(
2026 descriptor.channel_value_satoshis,
2027 &descriptor.channel_keys_id,
2029 if let Some(channel_params) =
2030 descriptor.channel_transaction_parameters.as_ref()
2032 signer.provide_channel_parameters(channel_params);
2034 keys_cache = Some((signer, descriptor.channel_keys_id));
2036 let witness = keys_cache.as_ref().unwrap().0.sign_counterparty_payment_input(
2042 psbt.inputs[input_idx].final_script_witness = Some(witness);
2044 SpendableOutputDescriptor::DelayedPaymentOutput(descriptor) => {
2045 let input_idx = get_input_idx(&descriptor.outpoint)?;
2046 if keys_cache.is_none()
2047 || keys_cache.as_ref().unwrap().1 != descriptor.channel_keys_id
2050 self.derive_channel_keys(
2051 descriptor.channel_value_satoshis,
2052 &descriptor.channel_keys_id,
2054 descriptor.channel_keys_id,
2057 let witness = keys_cache.as_ref().unwrap().0.sign_dynamic_p2wsh_input(
2063 psbt.inputs[input_idx].final_script_witness = Some(witness);
2065 SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output, .. } => {
2066 let input_idx = get_input_idx(outpoint)?;
2067 let derivation_idx =
2068 if output.script_pubkey == self.destination_script { 1 } else { 2 };
2070 // Note that when we aren't serializing the key, network doesn't matter
2071 match ExtendedPrivKey::new_master(Network::Testnet, &self.seed) {
2073 match master_key.ckd_priv(
2075 ChildNumber::from_hardened_idx(derivation_idx)
2076 .expect("key space exhausted"),
2079 Err(_) => panic!("Your RNG is busted"),
2082 Err(_) => panic!("Your rng is busted"),
2085 let pubkey = ExtendedPubKey::from_priv(&secp_ctx, &secret).to_pub();
2086 if derivation_idx == 2 {
2087 assert_eq!(pubkey.inner, self.shutdown_pubkey);
2089 let witness_script =
2090 bitcoin::Address::p2pkh(&pubkey, Network::Testnet).script_pubkey();
2091 let payment_script = bitcoin::Address::p2wpkh(&pubkey, Network::Testnet)
2092 .expect("uncompressed key found")
2095 if payment_script != output.script_pubkey {
2099 let sighash = hash_to_message!(
2100 &sighash::SighashCache::new(&psbt.unsigned_tx)
2101 .segwit_signature_hash(
2105 EcdsaSighashType::All
2109 let sig = sign_with_aux_rand(secp_ctx, &sighash, &secret.private_key, &self);
2110 let mut sig_ser = sig.serialize_der().to_vec();
2111 sig_ser.push(EcdsaSighashType::All as u8);
2113 Witness::from_slice(&[&sig_ser, &pubkey.inner.serialize().to_vec()]);
2114 psbt.inputs[input_idx].final_script_witness = Some(witness);
2123 impl EntropySource for KeysManager {
2124 fn get_secure_random_bytes(&self) -> [u8; 32] {
2125 self.entropy_source.get_secure_random_bytes()
2129 impl NodeSigner for KeysManager {
2130 fn get_node_id(&self, recipient: Recipient) -> Result<PublicKey, ()> {
2132 Recipient::Node => Ok(self.node_id.clone()),
2133 Recipient::PhantomNode => Err(()),
2138 &self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&Scalar>,
2139 ) -> Result<SharedSecret, ()> {
2140 let mut node_secret = match recipient {
2141 Recipient::Node => Ok(self.node_secret.clone()),
2142 Recipient::PhantomNode => Err(()),
2144 if let Some(tweak) = tweak {
2145 node_secret = node_secret.mul_tweak(tweak).map_err(|_| ())?;
2147 Ok(SharedSecret::new(other_key, &node_secret))
2150 fn get_inbound_payment_key_material(&self) -> KeyMaterial {
2151 self.inbound_payment_key.clone()
2155 &self, hrp_bytes: &[u8], invoice_data: &[u5], recipient: Recipient,
2156 ) -> Result<RecoverableSignature, ()> {
2157 let preimage = construct_invoice_preimage(&hrp_bytes, &invoice_data);
2158 let secret = match recipient {
2159 Recipient::Node => Ok(&self.node_secret),
2160 Recipient::PhantomNode => Err(()),
2162 Ok(self.secp_ctx.sign_ecdsa_recoverable(
2163 &hash_to_message!(&Sha256::hash(&preimage).to_byte_array()),
2168 fn sign_bolt12_invoice_request(
2169 &self, invoice_request: &UnsignedInvoiceRequest,
2170 ) -> Result<schnorr::Signature, ()> {
2171 let message = invoice_request.tagged_hash().as_digest();
2172 let keys = KeyPair::from_secret_key(&self.secp_ctx, &self.node_secret);
2173 let aux_rand = self.get_secure_random_bytes();
2174 Ok(self.secp_ctx.sign_schnorr_with_aux_rand(message, &keys, &aux_rand))
2177 fn sign_bolt12_invoice(
2178 &self, invoice: &UnsignedBolt12Invoice,
2179 ) -> Result<schnorr::Signature, ()> {
2180 let message = invoice.tagged_hash().as_digest();
2181 let keys = KeyPair::from_secret_key(&self.secp_ctx, &self.node_secret);
2182 let aux_rand = self.get_secure_random_bytes();
2183 Ok(self.secp_ctx.sign_schnorr_with_aux_rand(message, &keys, &aux_rand))
2186 fn sign_gossip_message(&self, msg: UnsignedGossipMessage) -> Result<Signature, ()> {
2187 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.encode()[..])[..]);
2188 Ok(self.secp_ctx.sign_ecdsa(&msg_hash, &self.node_secret))
2192 impl OutputSpender for KeysManager {
2193 /// Creates a [`Transaction`] which spends the given descriptors to the given outputs, plus an
2194 /// output to the given change destination (if sufficient change value remains).
2196 /// See [`OutputSpender::spend_spendable_outputs`] documentation for more information.
2198 /// We do not enforce that outputs meet the dust limit or that any output scripts are standard.
2200 /// May panic if the [`SpendableOutputDescriptor`]s were not generated by channels which used
2201 /// this [`KeysManager`] or one of the [`InMemorySigner`] created by this [`KeysManager`].
2202 fn spend_spendable_outputs<C: Signing>(
2203 &self, descriptors: &[&SpendableOutputDescriptor], outputs: Vec<TxOut>,
2204 change_destination_script: ScriptBuf, feerate_sat_per_1000_weight: u32,
2205 locktime: Option<LockTime>, secp_ctx: &Secp256k1<C>,
2206 ) -> Result<Transaction, ()> {
2207 let (mut psbt, expected_max_weight) =
2208 SpendableOutputDescriptor::create_spendable_outputs_psbt(
2212 change_destination_script,
2213 feerate_sat_per_1000_weight,
2216 psbt = self.sign_spendable_outputs_psbt(descriptors, psbt, secp_ctx)?;
2218 let spend_tx = psbt.extract_tx();
2220 debug_assert!(expected_max_weight >= spend_tx.weight().to_wu());
2221 // Note that witnesses with a signature vary somewhat in size, so allow
2222 // `expected_max_weight` to overshoot by up to 3 bytes per input.
2224 expected_max_weight <= spend_tx.weight().to_wu() + descriptors.len() as u64 * 3
2231 impl SignerProvider for KeysManager {
2232 type EcdsaSigner = InMemorySigner;
2234 type TaprootSigner = InMemorySigner;
2236 fn generate_channel_keys_id(
2237 &self, _inbound: bool, _channel_value_satoshis: u64, user_channel_id: u128,
2239 let child_idx = self.channel_child_index.fetch_add(1, Ordering::AcqRel);
2240 // `child_idx` is the only thing guaranteed to make each channel unique without a restart
2241 // (though `user_channel_id` should help, depending on user behavior). If it manages to
2242 // roll over, we may generate duplicate keys for two different channels, which could result
2243 // in loss of funds. Because we only support 32-bit+ systems, assert that our `AtomicUsize`
2244 // doesn't reach `u32::MAX`.
2245 assert!(child_idx < core::u32::MAX as usize, "2^32 channels opened without restart");
2246 let mut id = [0; 32];
2247 id[0..4].copy_from_slice(&(child_idx as u32).to_be_bytes());
2248 id[4..8].copy_from_slice(&self.starting_time_nanos.to_be_bytes());
2249 id[8..16].copy_from_slice(&self.starting_time_secs.to_be_bytes());
2250 id[16..32].copy_from_slice(&user_channel_id.to_be_bytes());
2254 fn derive_channel_signer(
2255 &self, channel_value_satoshis: u64, channel_keys_id: [u8; 32],
2256 ) -> Self::EcdsaSigner {
2257 self.derive_channel_keys(channel_value_satoshis, &channel_keys_id)
2260 fn read_chan_signer(&self, reader: &[u8]) -> Result<Self::EcdsaSigner, DecodeError> {
2261 InMemorySigner::read(&mut io::Cursor::new(reader), self)
2264 fn get_destination_script(&self, _channel_keys_id: [u8; 32]) -> Result<ScriptBuf, ()> {
2265 Ok(self.destination_script.clone())
2268 fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()> {
2269 Ok(ShutdownScript::new_p2wpkh_from_pubkey(self.shutdown_pubkey.clone()))
2273 /// Similar to [`KeysManager`], but allows the node using this struct to receive phantom node
2276 /// A phantom node payment is a payment made to a phantom invoice, which is an invoice that can be
2277 /// paid to one of multiple nodes. This works because we encode the invoice route hints such that
2278 /// LDK will recognize an incoming payment as destined for a phantom node, and collect the payment
2279 /// itself without ever needing to forward to this fake node.
2281 /// Phantom node payments are useful for load balancing between multiple LDK nodes. They also
2282 /// provide some fault tolerance, because payers will automatically retry paying other provided
2283 /// nodes in the case that one node goes down.
2285 /// Note that multi-path payments are not supported in phantom invoices for security reasons.
2286 // In the hypothetical case that we did support MPP phantom payments, there would be no way for
2287 // nodes to know when the full payment has been received (and the preimage can be released) without
2288 // significantly compromising on our safety guarantees. I.e., if we expose the ability for the user
2289 // to tell LDK when the preimage can be released, we open ourselves to attacks where the preimage
2290 // is released too early.
2292 /// Switching between this struct and [`KeysManager`] will invalidate any previously issued
2293 /// invoices and attempts to pay previous invoices will fail.
2294 pub struct PhantomKeysManager {
2296 inbound_payment_key: KeyMaterial,
2297 phantom_secret: SecretKey,
2298 phantom_node_id: PublicKey,
2301 impl EntropySource for PhantomKeysManager {
2302 fn get_secure_random_bytes(&self) -> [u8; 32] {
2303 self.inner.get_secure_random_bytes()
2307 impl NodeSigner for PhantomKeysManager {
2308 fn get_node_id(&self, recipient: Recipient) -> Result<PublicKey, ()> {
2310 Recipient::Node => self.inner.get_node_id(Recipient::Node),
2311 Recipient::PhantomNode => Ok(self.phantom_node_id.clone()),
2316 &self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&Scalar>,
2317 ) -> Result<SharedSecret, ()> {
2318 let mut node_secret = match recipient {
2319 Recipient::Node => self.inner.node_secret.clone(),
2320 Recipient::PhantomNode => self.phantom_secret.clone(),
2322 if let Some(tweak) = tweak {
2323 node_secret = node_secret.mul_tweak(tweak).map_err(|_| ())?;
2325 Ok(SharedSecret::new(other_key, &node_secret))
2328 fn get_inbound_payment_key_material(&self) -> KeyMaterial {
2329 self.inbound_payment_key.clone()
2333 &self, hrp_bytes: &[u8], invoice_data: &[u5], recipient: Recipient,
2334 ) -> Result<RecoverableSignature, ()> {
2335 let preimage = construct_invoice_preimage(&hrp_bytes, &invoice_data);
2336 let secret = match recipient {
2337 Recipient::Node => &self.inner.node_secret,
2338 Recipient::PhantomNode => &self.phantom_secret,
2340 Ok(self.inner.secp_ctx.sign_ecdsa_recoverable(
2341 &hash_to_message!(&Sha256::hash(&preimage).to_byte_array()),
2346 fn sign_bolt12_invoice_request(
2347 &self, invoice_request: &UnsignedInvoiceRequest,
2348 ) -> Result<schnorr::Signature, ()> {
2349 self.inner.sign_bolt12_invoice_request(invoice_request)
2352 fn sign_bolt12_invoice(
2353 &self, invoice: &UnsignedBolt12Invoice,
2354 ) -> Result<schnorr::Signature, ()> {
2355 self.inner.sign_bolt12_invoice(invoice)
2358 fn sign_gossip_message(&self, msg: UnsignedGossipMessage) -> Result<Signature, ()> {
2359 self.inner.sign_gossip_message(msg)
2363 impl OutputSpender for PhantomKeysManager {
2364 /// See [`OutputSpender::spend_spendable_outputs`] and [`KeysManager::spend_spendable_outputs`]
2365 /// for documentation on this method.
2366 fn spend_spendable_outputs<C: Signing>(
2367 &self, descriptors: &[&SpendableOutputDescriptor], outputs: Vec<TxOut>,
2368 change_destination_script: ScriptBuf, feerate_sat_per_1000_weight: u32,
2369 locktime: Option<LockTime>, secp_ctx: &Secp256k1<C>,
2370 ) -> Result<Transaction, ()> {
2371 self.inner.spend_spendable_outputs(
2374 change_destination_script,
2375 feerate_sat_per_1000_weight,
2382 impl SignerProvider for PhantomKeysManager {
2383 type EcdsaSigner = InMemorySigner;
2385 type TaprootSigner = InMemorySigner;
2387 fn generate_channel_keys_id(
2388 &self, inbound: bool, channel_value_satoshis: u64, user_channel_id: u128,
2390 self.inner.generate_channel_keys_id(inbound, channel_value_satoshis, user_channel_id)
2393 fn derive_channel_signer(
2394 &self, channel_value_satoshis: u64, channel_keys_id: [u8; 32],
2395 ) -> Self::EcdsaSigner {
2396 self.inner.derive_channel_signer(channel_value_satoshis, channel_keys_id)
2399 fn read_chan_signer(&self, reader: &[u8]) -> Result<Self::EcdsaSigner, DecodeError> {
2400 self.inner.read_chan_signer(reader)
2403 fn get_destination_script(&self, channel_keys_id: [u8; 32]) -> Result<ScriptBuf, ()> {
2404 self.inner.get_destination_script(channel_keys_id)
2407 fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()> {
2408 self.inner.get_shutdown_scriptpubkey()
2412 impl PhantomKeysManager {
2413 /// Constructs a [`PhantomKeysManager`] given a 32-byte seed and an additional `cross_node_seed`
2414 /// that is shared across all nodes that intend to participate in [phantom node payments]
2417 /// See [`KeysManager::new`] for more information on `seed`, `starting_time_secs`, and
2418 /// `starting_time_nanos`.
2420 /// `cross_node_seed` must be the same across all phantom payment-receiving nodes and also the
2421 /// same across restarts, or else inbound payments may fail.
2423 /// [phantom node payments]: PhantomKeysManager
2425 seed: &[u8; 32], starting_time_secs: u64, starting_time_nanos: u32,
2426 cross_node_seed: &[u8; 32],
2428 let inner = KeysManager::new(seed, starting_time_secs, starting_time_nanos);
2429 let (inbound_key, phantom_key) = hkdf_extract_expand_twice(
2430 b"LDK Inbound and Phantom Payment Key Expansion",
2433 let phantom_secret = SecretKey::from_slice(&phantom_key).unwrap();
2434 let phantom_node_id = PublicKey::from_secret_key(&inner.secp_ctx, &phantom_secret);
2437 inbound_payment_key: KeyMaterial(inbound_key),
2443 /// See [`KeysManager::derive_channel_keys`] for documentation on this method.
2444 pub fn derive_channel_keys(
2445 &self, channel_value_satoshis: u64, params: &[u8; 32],
2446 ) -> InMemorySigner {
2447 self.inner.derive_channel_keys(channel_value_satoshis, params)
2450 /// Gets the "node_id" secret key used to sign gossip announcements, decode onion data, etc.
2451 pub fn get_node_secret_key(&self) -> SecretKey {
2452 self.inner.get_node_secret_key()
2455 /// Gets the "node_id" secret key of the phantom node used to sign invoices, decode the
2456 /// last-hop onion data, etc.
2457 pub fn get_phantom_node_secret_key(&self) -> SecretKey {
2462 /// An implementation of [`EntropySource`] using ChaCha20.
2464 pub struct RandomBytes {
2465 /// Seed from which all randomness produced is derived from.
2467 /// Tracks the number of times we've produced randomness to ensure we don't return the same
2469 index: AtomicCounter,
2473 /// Creates a new instance using the given seed.
2474 pub fn new(seed: [u8; 32]) -> Self {
2475 Self { seed, index: AtomicCounter::new() }
2479 impl EntropySource for RandomBytes {
2480 fn get_secure_random_bytes(&self) -> [u8; 32] {
2481 let index = self.index.get_increment();
2482 let mut nonce = [0u8; 16];
2483 nonce[..8].copy_from_slice(&index.to_be_bytes());
2484 ChaCha20::get_single_block(&self.seed, &nonce)
2488 // Ensure that EcdsaChannelSigner can have a vtable
2491 let _signer: Box<dyn EcdsaChannelSigner>;
2496 use crate::sign::{EntropySource, KeysManager};
2497 use bitcoin::blockdata::constants::genesis_block;
2498 use bitcoin::Network;
2499 use std::sync::mpsc::TryRecvError;
2500 use std::sync::{mpsc, Arc};
2502 use std::time::Duration;
2504 use criterion::Criterion;
2506 pub fn bench_get_secure_random_bytes(bench: &mut Criterion) {
2507 let seed = [0u8; 32];
2508 let now = Duration::from_secs(genesis_block(Network::Testnet).header.time as u64);
2509 let keys_manager = Arc::new(KeysManager::new(&seed, now.as_secs(), now.subsec_micros()));
2511 let mut handles = Vec::new();
2512 let mut stops = Vec::new();
2514 let keys_manager_clone = Arc::clone(&keys_manager);
2515 let (stop_sender, stop_receiver) = mpsc::channel();
2516 let handle = thread::spawn(move || loop {
2517 keys_manager_clone.get_secure_random_bytes();
2518 match stop_receiver.try_recv() {
2519 Ok(_) | Err(TryRecvError::Disconnected) => {
2520 println!("Terminating.");
2523 Err(TryRecvError::Empty) => {},
2526 handles.push(handle);
2527 stops.push(stop_sender);
2530 bench.bench_function("get_secure_random_bytes", |b| {
2531 b.iter(|| keys_manager.get_secure_random_bytes())
2535 let _ = stop.send(());
2537 for handle in handles {
2538 handle.join().unwrap();