Add intermediate `ConstructedTransaction`
[rust-lightning] / lightning / src / sign / mod.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
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
8 // licenses.
9
10 //! Provides keys to LDK and defines some useful objects describing spendable on-chain outputs.
11 //!
12 //! The provided output descriptors follow a custom LDK data format and are currently not fully
13 //! compatible with Bitcoin Core output descriptors.
14
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;
23 use bitcoin::sighash;
24 use bitcoin::sighash::EcdsaSighashType;
25
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};
31
32 use bitcoin::secp256k1::ecdh::SharedSecret;
33 use bitcoin::secp256k1::ecdsa::{RecoverableSignature, Signature};
34 use bitcoin::secp256k1::schnorr;
35 #[cfg(taproot)]
36 use bitcoin::secp256k1::All;
37 use bitcoin::secp256k1::{KeyPair, PublicKey, Scalar, Secp256k1, SecretKey, Signing};
38 use bitcoin::{secp256k1, Sequence, Txid, Witness};
39
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         make_funding_redeemscript, ChannelPublicKeys, ChannelTransactionParameters, ClosingTransaction,
44         CommitmentTransaction, HTLCOutputInCommitment, HolderCommitmentTransaction,
45 };
46 use crate::ln::channel::ANCHOR_OUTPUT_VALUE_SATOSHI;
47 use crate::ln::channel_keys::{
48         DelayedPaymentBasepoint, DelayedPaymentKey, HtlcBasepoint, HtlcKey, RevocationBasepoint,
49         RevocationKey,
50 };
51 #[cfg(taproot)]
52 use crate::ln::msgs::PartialSignatureWithNonce;
53 use crate::ln::msgs::{UnsignedChannelAnnouncement, UnsignedGossipMessage};
54 use crate::ln::script::ShutdownScript;
55 use crate::ln::{chan_utils, PaymentPreimage};
56 use crate::offers::invoice::UnsignedBolt12Invoice;
57 use crate::offers::invoice_request::UnsignedInvoiceRequest;
58 use crate::util::ser::{Readable, ReadableArgs, Writeable, Writer};
59 use crate::util::transaction_utils;
60
61 use crate::crypto::chacha20::ChaCha20;
62 use crate::io::{self, Error};
63 use crate::ln::features::ChannelTypeFeatures;
64 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
65 use crate::prelude::*;
66 use crate::sign::ecdsa::{EcdsaChannelSigner, WriteableEcdsaChannelSigner};
67 #[cfg(taproot)]
68 use crate::sign::taproot::TaprootChannelSigner;
69 use crate::util::atomic_counter::AtomicCounter;
70 use crate::util::invoice::construct_invoice_preimage;
71 use core::ops::Deref;
72 use core::sync::atomic::{AtomicUsize, Ordering};
73 #[cfg(taproot)]
74 use musig2::types::{PartialSignature, PublicNonce};
75
76 pub(crate) mod type_resolver;
77
78 pub mod ecdsa;
79 #[cfg(taproot)]
80 pub mod taproot;
81
82 /// Used as initial key material, to be expanded into multiple secret keys (but not to be used
83 /// directly). This is used within LDK to encrypt/decrypt inbound payment data.
84 ///
85 /// This is not exported to bindings users as we just use `[u8; 32]` directly
86 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
87 pub struct KeyMaterial(pub [u8; 32]);
88
89 /// Information about a spendable output to a P2WSH script.
90 ///
91 /// See [`SpendableOutputDescriptor::DelayedPaymentOutput`] for more details on how to spend this.
92 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
93 pub struct DelayedPaymentOutputDescriptor {
94         /// The outpoint which is spendable.
95         pub outpoint: OutPoint,
96         /// Per commitment point to derive the delayed payment key by key holder.
97         pub per_commitment_point: PublicKey,
98         /// The `nSequence` value which must be set in the spending input to satisfy the `OP_CSV` in
99         /// the witness_script.
100         pub to_self_delay: u16,
101         /// The output which is referenced by the given outpoint.
102         pub output: TxOut,
103         /// The revocation point specific to the commitment transaction which was broadcast. Used to
104         /// derive the witnessScript for this output.
105         pub revocation_pubkey: RevocationKey,
106         /// Arbitrary identification information returned by a call to [`ChannelSigner::channel_keys_id`].
107         /// This may be useful in re-deriving keys used in the channel to spend the output.
108         pub channel_keys_id: [u8; 32],
109         /// The value of the channel which this output originated from, possibly indirectly.
110         pub channel_value_satoshis: u64,
111 }
112 impl DelayedPaymentOutputDescriptor {
113         /// The maximum length a well-formed witness spending one of these should have.
114         /// Note: If you have the grind_signatures feature enabled, this will be at least 1 byte
115         /// shorter.
116         // Calculated as 1 byte length + 73 byte signature, 1 byte empty vec push, 1 byte length plus
117         // redeemscript push length.
118         pub const MAX_WITNESS_LENGTH: u64 =
119                 1 + 73 + 1 + chan_utils::REVOKEABLE_REDEEMSCRIPT_MAX_LENGTH as u64 + 1;
120 }
121
122 impl_writeable_tlv_based!(DelayedPaymentOutputDescriptor, {
123         (0, outpoint, required),
124         (2, per_commitment_point, required),
125         (4, to_self_delay, required),
126         (6, output, required),
127         (8, revocation_pubkey, required),
128         (10, channel_keys_id, required),
129         (12, channel_value_satoshis, required),
130 });
131
132 pub(crate) const P2WPKH_WITNESS_WEIGHT: u64 = 1 /* num stack items */ +
133         1 /* sig length */ +
134         73 /* sig including sighash flag */ +
135         1 /* pubkey length */ +
136         33 /* pubkey */;
137
138 /// Witness weight for satisying a P2TR key-path spend.
139 pub(crate) const P2TR_KEY_PATH_WITNESS_WEIGHT: u64 = 1 /* witness items */
140         + 1 /* schnorr sig len */ + 64 /* schnorr sig */;
141
142 /// Information about a spendable output to our "payment key".
143 ///
144 /// See [`SpendableOutputDescriptor::StaticPaymentOutput`] for more details on how to spend this.
145 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
146 pub struct StaticPaymentOutputDescriptor {
147         /// The outpoint which is spendable.
148         pub outpoint: OutPoint,
149         /// The output which is referenced by the given outpoint.
150         pub output: TxOut,
151         /// Arbitrary identification information returned by a call to [`ChannelSigner::channel_keys_id`].
152         /// This may be useful in re-deriving keys used in the channel to spend the output.
153         pub channel_keys_id: [u8; 32],
154         /// The value of the channel which this transactions spends.
155         pub channel_value_satoshis: u64,
156         /// The necessary channel parameters that need to be provided to the re-derived signer through
157         /// [`ChannelSigner::provide_channel_parameters`].
158         ///
159         /// Added as optional, but always `Some` if the descriptor was produced in v0.0.117 or later.
160         pub channel_transaction_parameters: Option<ChannelTransactionParameters>,
161 }
162 impl StaticPaymentOutputDescriptor {
163         /// Returns the `witness_script` of the spendable output.
164         ///
165         /// Note that this will only return `Some` for [`StaticPaymentOutputDescriptor`]s that
166         /// originated from an anchor outputs channel, as they take the form of a P2WSH script.
167         pub fn witness_script(&self) -> Option<ScriptBuf> {
168                 self.channel_transaction_parameters.as_ref().and_then(|channel_params| {
169                         if channel_params.supports_anchors() {
170                                 let payment_point = channel_params.holder_pubkeys.payment_point;
171                                 Some(chan_utils::get_to_countersignatory_with_anchors_redeemscript(&payment_point))
172                         } else {
173                                 None
174                         }
175                 })
176         }
177
178         /// The maximum length a well-formed witness spending one of these should have.
179         /// Note: If you have the grind_signatures feature enabled, this will be at least 1 byte
180         /// shorter.
181         pub fn max_witness_length(&self) -> u64 {
182                 if self.channel_transaction_parameters.as_ref().map_or(false, |p| p.supports_anchors()) {
183                         let witness_script_weight = 1 /* pubkey push */ + 33 /* pubkey */ +
184                                 1 /* OP_CHECKSIGVERIFY */ + 1 /* OP_1 */ + 1 /* OP_CHECKSEQUENCEVERIFY */;
185                         1 /* num witness items */ + 1 /* sig push */ + 73 /* sig including sighash flag */ +
186                                 1 /* witness script push */ + witness_script_weight
187                 } else {
188                         P2WPKH_WITNESS_WEIGHT
189                 }
190         }
191 }
192 impl_writeable_tlv_based!(StaticPaymentOutputDescriptor, {
193         (0, outpoint, required),
194         (2, output, required),
195         (4, channel_keys_id, required),
196         (6, channel_value_satoshis, required),
197         (7, channel_transaction_parameters, option),
198 });
199
200 /// Describes the necessary information to spend a spendable output.
201 ///
202 /// When on-chain outputs are created by LDK (which our counterparty is not able to claim at any
203 /// point in the future) a [`SpendableOutputs`] event is generated which you must track and be able
204 /// to spend on-chain. The information needed to do this is provided in this enum, including the
205 /// outpoint describing which `txid` and output `index` is available, the full output which exists
206 /// at that `txid`/`index`, and any keys or other information required to sign.
207 ///
208 /// [`SpendableOutputs`]: crate::events::Event::SpendableOutputs
209 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
210 pub enum SpendableOutputDescriptor {
211         /// An output to a script which was provided via [`SignerProvider`] directly, either from
212         /// [`get_destination_script`] or [`get_shutdown_scriptpubkey`], thus you should already
213         /// know how to spend it. No secret keys are provided as LDK was never given any key.
214         /// These may include outputs from a transaction punishing our counterparty or claiming an HTLC
215         /// on-chain using the payment preimage or after it has timed out.
216         ///
217         /// [`get_shutdown_scriptpubkey`]: SignerProvider::get_shutdown_scriptpubkey
218         /// [`get_destination_script`]: SignerProvider::get_shutdown_scriptpubkey
219         StaticOutput {
220                 /// The outpoint which is spendable.
221                 outpoint: OutPoint,
222                 /// The output which is referenced by the given outpoint.
223                 output: TxOut,
224                 /// The `channel_keys_id` for the channel which this output came from.
225                 ///
226                 /// For channels which were generated on LDK 0.0.119 or later, this is the value which was
227                 /// passed to the [`SignerProvider::get_destination_script`] call which provided this
228                 /// output script.
229                 ///
230                 /// For channels which were generated prior to LDK 0.0.119, no such argument existed,
231                 /// however this field may still be filled in if such data is available.
232                 channel_keys_id: Option<[u8; 32]>,
233         },
234         /// An output to a P2WSH script which can be spent with a single signature after an `OP_CSV`
235         /// delay.
236         ///
237         /// The witness in the spending input should be:
238         /// ```bitcoin
239         /// <BIP 143 signature> <empty vector> (MINIMALIF standard rule) <provided witnessScript>
240         /// ```
241         ///
242         /// Note that the `nSequence` field in the spending input must be set to
243         /// [`DelayedPaymentOutputDescriptor::to_self_delay`] (which means the transaction is not
244         /// broadcastable until at least [`DelayedPaymentOutputDescriptor::to_self_delay`] blocks after
245         /// the outpoint confirms, see [BIP
246         /// 68](https://github.com/bitcoin/bips/blob/master/bip-0068.mediawiki)). Also note that LDK
247         /// won't generate a [`SpendableOutputDescriptor`] until the corresponding block height
248         /// is reached.
249         ///
250         /// These are generally the result of a "revocable" output to us, spendable only by us unless
251         /// it is an output from an old state which we broadcast (which should never happen).
252         ///
253         /// To derive the delayed payment key which is used to sign this input, you must pass the
254         /// holder [`InMemorySigner::delayed_payment_base_key`] (i.e., the private key which corresponds to the
255         /// [`ChannelPublicKeys::delayed_payment_basepoint`] in [`ChannelSigner::pubkeys`]) and the provided
256         /// [`DelayedPaymentOutputDescriptor::per_commitment_point`] to [`chan_utils::derive_private_key`]. The DelayedPaymentKey can be
257         /// generated without the secret key using [`DelayedPaymentKey::from_basepoint`] and only the
258         /// [`ChannelPublicKeys::delayed_payment_basepoint`] which appears in [`ChannelSigner::pubkeys`].
259         ///
260         /// To derive the [`DelayedPaymentOutputDescriptor::revocation_pubkey`] provided here (which is
261         /// used in the witness script generation), you must pass the counterparty
262         /// [`ChannelPublicKeys::revocation_basepoint`] (which appears in the call to
263         /// [`ChannelSigner::provide_channel_parameters`]) and the provided
264         /// [`DelayedPaymentOutputDescriptor::per_commitment_point`] to
265         /// [`RevocationKey`].
266         ///
267         /// The witness script which is hashed and included in the output `script_pubkey` may be
268         /// regenerated by passing the [`DelayedPaymentOutputDescriptor::revocation_pubkey`] (derived
269         /// as explained above), our delayed payment pubkey (derived as explained above), and the
270         /// [`DelayedPaymentOutputDescriptor::to_self_delay`] contained here to
271         /// [`chan_utils::get_revokeable_redeemscript`].
272         DelayedPaymentOutput(DelayedPaymentOutputDescriptor),
273         /// An output spendable exclusively by our payment key (i.e., the private key that corresponds
274         /// to the `payment_point` in [`ChannelSigner::pubkeys`]). The output type depends on the
275         /// channel type negotiated.
276         ///
277         /// On an anchor outputs channel, the witness in the spending input is:
278         /// ```bitcoin
279         /// <BIP 143 signature> <witness script>
280         /// ```
281         ///
282         /// Otherwise, it is:
283         /// ```bitcoin
284         /// <BIP 143 signature> <payment key>
285         /// ```
286         ///
287         /// These are generally the result of our counterparty having broadcast the current state,
288         /// allowing us to claim the non-HTLC-encumbered outputs immediately, or after one confirmation
289         /// in the case of anchor outputs channels.
290         StaticPaymentOutput(StaticPaymentOutputDescriptor),
291 }
292
293 impl_writeable_tlv_based_enum!(SpendableOutputDescriptor,
294         (0, StaticOutput) => {
295                 (0, outpoint, required),
296                 (1, channel_keys_id, option),
297                 (2, output, required),
298         },
299 ;
300         (1, DelayedPaymentOutput),
301         (2, StaticPaymentOutput),
302 );
303
304 impl SpendableOutputDescriptor {
305         /// Turns this into a [`bitcoin::psbt::Input`] which can be used to create a
306         /// [`PartiallySignedTransaction`] which spends the given descriptor.
307         ///
308         /// Note that this does not include any signatures, just the information required to
309         /// construct the transaction and sign it.
310         ///
311         /// This is not exported to bindings users as there is no standard serialization for an input.
312         /// See [`Self::create_spendable_outputs_psbt`] instead.
313         pub fn to_psbt_input(&self) -> bitcoin::psbt::Input {
314                 match self {
315                         SpendableOutputDescriptor::StaticOutput { output, .. } => {
316                                 // Is a standard P2WPKH, no need for witness script
317                                 bitcoin::psbt::Input { witness_utxo: Some(output.clone()), ..Default::default() }
318                         },
319                         SpendableOutputDescriptor::DelayedPaymentOutput(descriptor) => {
320                                 // TODO we could add the witness script as well
321                                 bitcoin::psbt::Input {
322                                         witness_utxo: Some(descriptor.output.clone()),
323                                         ..Default::default()
324                                 }
325                         },
326                         SpendableOutputDescriptor::StaticPaymentOutput(descriptor) => {
327                                 // TODO we could add the witness script as well
328                                 bitcoin::psbt::Input {
329                                         witness_utxo: Some(descriptor.output.clone()),
330                                         ..Default::default()
331                                 }
332                         },
333                 }
334         }
335
336         /// Creates an unsigned [`PartiallySignedTransaction`] which spends the given descriptors to
337         /// the given outputs, plus an output to the given change destination (if sufficient
338         /// change value remains). The PSBT will have a feerate, at least, of the given value.
339         ///
340         /// The `locktime` argument is used to set the transaction's locktime. If `None`, the
341         /// transaction will have a locktime of 0. It it recommended to set this to the current block
342         /// height to avoid fee sniping, unless you have some specific reason to use a different
343         /// locktime.
344         ///
345         /// Returns the PSBT and expected max transaction weight.
346         ///
347         /// Returns `Err(())` if the output value is greater than the input value minus required fee,
348         /// if a descriptor was duplicated, or if an output descriptor `script_pubkey`
349         /// does not match the one we can spend.
350         ///
351         /// We do not enforce that outputs meet the dust limit or that any output scripts are standard.
352         pub fn create_spendable_outputs_psbt(
353                 descriptors: &[&SpendableOutputDescriptor], outputs: Vec<TxOut>,
354                 change_destination_script: ScriptBuf, feerate_sat_per_1000_weight: u32,
355                 locktime: Option<LockTime>,
356         ) -> Result<(PartiallySignedTransaction, u64), ()> {
357                 let mut input = Vec::with_capacity(descriptors.len());
358                 let mut input_value = 0;
359                 let mut witness_weight = 0;
360                 let mut output_set = hash_set_with_capacity(descriptors.len());
361                 for outp in descriptors {
362                         match outp {
363                                 SpendableOutputDescriptor::StaticPaymentOutput(descriptor) => {
364                                         if !output_set.insert(descriptor.outpoint) {
365                                                 return Err(());
366                                         }
367                                         let sequence = if descriptor
368                                                 .channel_transaction_parameters
369                                                 .as_ref()
370                                                 .map_or(false, |p| p.supports_anchors())
371                                         {
372                                                 Sequence::from_consensus(1)
373                                         } else {
374                                                 Sequence::ZERO
375                                         };
376                                         input.push(TxIn {
377                                                 previous_output: descriptor.outpoint.into_bitcoin_outpoint(),
378                                                 script_sig: ScriptBuf::new(),
379                                                 sequence,
380                                                 witness: Witness::new(),
381                                         });
382                                         witness_weight += descriptor.max_witness_length();
383                                         #[cfg(feature = "grind_signatures")]
384                                         {
385                                                 // Guarantees a low R signature
386                                                 witness_weight -= 1;
387                                         }
388                                         input_value += descriptor.output.value;
389                                 },
390                                 SpendableOutputDescriptor::DelayedPaymentOutput(descriptor) => {
391                                         if !output_set.insert(descriptor.outpoint) {
392                                                 return Err(());
393                                         }
394                                         input.push(TxIn {
395                                                 previous_output: descriptor.outpoint.into_bitcoin_outpoint(),
396                                                 script_sig: ScriptBuf::new(),
397                                                 sequence: Sequence(descriptor.to_self_delay as u32),
398                                                 witness: Witness::new(),
399                                         });
400                                         witness_weight += DelayedPaymentOutputDescriptor::MAX_WITNESS_LENGTH;
401                                         #[cfg(feature = "grind_signatures")]
402                                         {
403                                                 // Guarantees a low R signature
404                                                 witness_weight -= 1;
405                                         }
406                                         input_value += descriptor.output.value;
407                                 },
408                                 SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output, .. } => {
409                                         if !output_set.insert(*outpoint) {
410                                                 return Err(());
411                                         }
412                                         input.push(TxIn {
413                                                 previous_output: outpoint.into_bitcoin_outpoint(),
414                                                 script_sig: ScriptBuf::new(),
415                                                 sequence: Sequence::ZERO,
416                                                 witness: Witness::new(),
417                                         });
418                                         witness_weight += 1 + 73 + 34;
419                                         #[cfg(feature = "grind_signatures")]
420                                         {
421                                                 // Guarantees a low R signature
422                                                 witness_weight -= 1;
423                                         }
424                                         input_value += output.value;
425                                 },
426                         }
427                         if input_value > MAX_VALUE_MSAT / 1000 {
428                                 return Err(());
429                         }
430                 }
431                 let mut tx = Transaction {
432                         version: 2,
433                         lock_time: locktime.unwrap_or(LockTime::ZERO),
434                         input,
435                         output: outputs,
436                 };
437                 let expected_max_weight = transaction_utils::maybe_add_change_output(
438                         &mut tx,
439                         input_value,
440                         witness_weight,
441                         feerate_sat_per_1000_weight,
442                         change_destination_script,
443                 )?;
444
445                 let psbt_inputs = descriptors.iter().map(|d| d.to_psbt_input()).collect::<Vec<_>>();
446                 let psbt = PartiallySignedTransaction {
447                         inputs: psbt_inputs,
448                         outputs: vec![Default::default(); tx.output.len()],
449                         unsigned_tx: tx,
450                         xpub: Default::default(),
451                         version: 0,
452                         proprietary: Default::default(),
453                         unknown: Default::default(),
454                 };
455                 Ok((psbt, expected_max_weight))
456         }
457 }
458
459 /// The parameters required to derive a channel signer via [`SignerProvider`].
460 #[derive(Clone, Debug, PartialEq, Eq)]
461 pub struct ChannelDerivationParameters {
462         /// The value in satoshis of the channel we're attempting to spend the anchor output of.
463         pub value_satoshis: u64,
464         /// The unique identifier to re-derive the signer for the associated channel.
465         pub keys_id: [u8; 32],
466         /// The necessary channel parameters that need to be provided to the re-derived signer through
467         /// [`ChannelSigner::provide_channel_parameters`].
468         pub transaction_parameters: ChannelTransactionParameters,
469 }
470
471 impl_writeable_tlv_based!(ChannelDerivationParameters, {
472         (0, value_satoshis, required),
473         (2, keys_id, required),
474         (4, transaction_parameters, required),
475 });
476
477 /// A descriptor used to sign for a commitment transaction's HTLC output.
478 #[derive(Clone, Debug, PartialEq, Eq)]
479 pub struct HTLCDescriptor {
480         /// The parameters required to derive the signer for the HTLC input.
481         pub channel_derivation_parameters: ChannelDerivationParameters,
482         /// The txid of the commitment transaction in which the HTLC output lives.
483         pub commitment_txid: Txid,
484         /// The number of the commitment transaction in which the HTLC output lives.
485         pub per_commitment_number: u64,
486         /// The key tweak corresponding to the number of the commitment transaction in which the HTLC
487         /// output lives. This tweak is applied to all the basepoints for both parties in the channel to
488         /// arrive at unique keys per commitment.
489         ///
490         /// See <https://github.com/lightning/bolts/blob/master/03-transactions.md#keys> for more info.
491         pub per_commitment_point: PublicKey,
492         /// The feerate to use on the HTLC claiming transaction. This is always `0` for HTLCs
493         /// originating from a channel supporting anchor outputs, otherwise it is the channel's
494         /// negotiated feerate at the time the commitment transaction was built.
495         pub feerate_per_kw: u32,
496         /// The details of the HTLC as it appears in the commitment transaction.
497         pub htlc: HTLCOutputInCommitment,
498         /// The preimage, if `Some`, to claim the HTLC output with. If `None`, the timeout path must be
499         /// taken.
500         pub preimage: Option<PaymentPreimage>,
501         /// The counterparty's signature required to spend the HTLC output.
502         pub counterparty_sig: Signature,
503 }
504
505 impl_writeable_tlv_based!(HTLCDescriptor, {
506         (0, channel_derivation_parameters, required),
507         (1, feerate_per_kw, (default_value, 0)),
508         (2, commitment_txid, required),
509         (4, per_commitment_number, required),
510         (6, per_commitment_point, required),
511         (8, htlc, required),
512         (10, preimage, option),
513         (12, counterparty_sig, required),
514 });
515
516 impl HTLCDescriptor {
517         /// Returns the outpoint of the HTLC output in the commitment transaction. This is the outpoint
518         /// being spent by the HTLC input in the HTLC transaction.
519         pub fn outpoint(&self) -> bitcoin::OutPoint {
520                 bitcoin::OutPoint {
521                         txid: self.commitment_txid,
522                         vout: self.htlc.transaction_output_index.unwrap(),
523                 }
524         }
525
526         /// Returns the UTXO to be spent by the HTLC input, which can be obtained via
527         /// [`Self::unsigned_tx_input`].
528         pub fn previous_utxo<C: secp256k1::Signing + secp256k1::Verification>(
529                 &self, secp: &Secp256k1<C>,
530         ) -> TxOut {
531                 TxOut {
532                         script_pubkey: self.witness_script(secp).to_v0_p2wsh(),
533                         value: self.htlc.amount_msat / 1000,
534                 }
535         }
536
537         /// Returns the unsigned transaction input spending the HTLC output in the commitment
538         /// transaction.
539         pub fn unsigned_tx_input(&self) -> TxIn {
540                 chan_utils::build_htlc_input(
541                         &self.commitment_txid,
542                         &self.htlc,
543                         &self.channel_derivation_parameters.transaction_parameters.channel_type_features,
544                 )
545         }
546
547         /// Returns the delayed output created as a result of spending the HTLC output in the commitment
548         /// transaction.
549         pub fn tx_output<C: secp256k1::Signing + secp256k1::Verification>(
550                 &self, secp: &Secp256k1<C>,
551         ) -> TxOut {
552                 let channel_params =
553                         self.channel_derivation_parameters.transaction_parameters.as_holder_broadcastable();
554                 let broadcaster_keys = channel_params.broadcaster_pubkeys();
555                 let counterparty_keys = channel_params.countersignatory_pubkeys();
556                 let broadcaster_delayed_key = DelayedPaymentKey::from_basepoint(
557                         secp,
558                         &broadcaster_keys.delayed_payment_basepoint,
559                         &self.per_commitment_point,
560                 );
561                 let counterparty_revocation_key = &RevocationKey::from_basepoint(
562                         &secp,
563                         &counterparty_keys.revocation_basepoint,
564                         &self.per_commitment_point,
565                 );
566                 chan_utils::build_htlc_output(
567                         self.feerate_per_kw,
568                         channel_params.contest_delay(),
569                         &self.htlc,
570                         channel_params.channel_type_features(),
571                         &broadcaster_delayed_key,
572                         &counterparty_revocation_key,
573                 )
574         }
575
576         /// Returns the witness script of the HTLC output in the commitment transaction.
577         pub fn witness_script<C: secp256k1::Signing + secp256k1::Verification>(
578                 &self, secp: &Secp256k1<C>,
579         ) -> ScriptBuf {
580                 let channel_params =
581                         self.channel_derivation_parameters.transaction_parameters.as_holder_broadcastable();
582                 let broadcaster_keys = channel_params.broadcaster_pubkeys();
583                 let counterparty_keys = channel_params.countersignatory_pubkeys();
584                 let broadcaster_htlc_key = HtlcKey::from_basepoint(
585                         secp,
586                         &broadcaster_keys.htlc_basepoint,
587                         &self.per_commitment_point,
588                 );
589                 let counterparty_htlc_key = HtlcKey::from_basepoint(
590                         secp,
591                         &counterparty_keys.htlc_basepoint,
592                         &self.per_commitment_point,
593                 );
594                 let counterparty_revocation_key = &RevocationKey::from_basepoint(
595                         &secp,
596                         &counterparty_keys.revocation_basepoint,
597                         &self.per_commitment_point,
598                 );
599                 chan_utils::get_htlc_redeemscript_with_explicit_keys(
600                         &self.htlc,
601                         channel_params.channel_type_features(),
602                         &broadcaster_htlc_key,
603                         &counterparty_htlc_key,
604                         &counterparty_revocation_key,
605                 )
606         }
607
608         /// Returns the fully signed witness required to spend the HTLC output in the commitment
609         /// transaction.
610         pub fn tx_input_witness(&self, signature: &Signature, witness_script: &Script) -> Witness {
611                 chan_utils::build_htlc_input_witness(
612                         signature,
613                         &self.counterparty_sig,
614                         &self.preimage,
615                         witness_script,
616                         &self.channel_derivation_parameters.transaction_parameters.channel_type_features,
617                 )
618         }
619
620         /// Derives the channel signer required to sign the HTLC input.
621         pub fn derive_channel_signer<S: WriteableEcdsaChannelSigner, SP: Deref>(
622                 &self, signer_provider: &SP,
623         ) -> S
624         where
625                 SP::Target: SignerProvider<EcdsaSigner = S>,
626         {
627                 let mut signer = signer_provider.derive_channel_signer(
628                         self.channel_derivation_parameters.value_satoshis,
629                         self.channel_derivation_parameters.keys_id,
630                 );
631                 signer
632                         .provide_channel_parameters(&self.channel_derivation_parameters.transaction_parameters);
633                 signer
634         }
635 }
636
637 /// A trait to handle Lightning channel key material without concretizing the channel type or
638 /// the signature mechanism.
639 pub trait ChannelSigner {
640         /// Gets the per-commitment point for a specific commitment number
641         ///
642         /// Note that the commitment number starts at `(1 << 48) - 1` and counts backwards.
643         fn get_per_commitment_point(&self, idx: u64, secp_ctx: &Secp256k1<secp256k1::All>)
644                 -> PublicKey;
645
646         /// Gets the commitment secret for a specific commitment number as part of the revocation process
647         ///
648         /// An external signer implementation should error here if the commitment was already signed
649         /// and should refuse to sign it in the future.
650         ///
651         /// May be called more than once for the same index.
652         ///
653         /// Note that the commitment number starts at `(1 << 48) - 1` and counts backwards.
654         // TODO: return a Result so we can signal a validation error
655         fn release_commitment_secret(&self, idx: u64) -> [u8; 32];
656
657         /// Validate the counterparty's signatures on the holder commitment transaction and HTLCs.
658         ///
659         /// This is required in order for the signer to make sure that releasing a commitment
660         /// secret won't leave us without a broadcastable holder transaction.
661         /// Policy checks should be implemented in this function, including checking the amount
662         /// sent to us and checking the HTLCs.
663         ///
664         /// The preimages of outbound HTLCs that were fulfilled since the last commitment are provided.
665         /// A validating signer should ensure that an HTLC output is removed only when the matching
666         /// preimage is provided, or when the value to holder is restored.
667         ///
668         /// Note that all the relevant preimages will be provided, but there may also be additional
669         /// irrelevant or duplicate preimages.
670         fn validate_holder_commitment(
671                 &self, holder_tx: &HolderCommitmentTransaction,
672                 outbound_htlc_preimages: Vec<PaymentPreimage>,
673         ) -> Result<(), ()>;
674
675         /// Validate the counterparty's revocation.
676         ///
677         /// This is required in order for the signer to make sure that the state has moved
678         /// forward and it is safe to sign the next counterparty commitment.
679         fn validate_counterparty_revocation(&self, idx: u64, secret: &SecretKey) -> Result<(), ()>;
680
681         /// Returns the holder's channel public keys and basepoints.
682         fn pubkeys(&self) -> &ChannelPublicKeys;
683
684         /// Returns an arbitrary identifier describing the set of keys which are provided back to you in
685         /// some [`SpendableOutputDescriptor`] types. This should be sufficient to identify this
686         /// [`EcdsaChannelSigner`] object uniquely and lookup or re-derive its keys.
687         fn channel_keys_id(&self) -> [u8; 32];
688
689         /// Set the counterparty static channel data, including basepoints,
690         /// `counterparty_selected`/`holder_selected_contest_delay` and funding outpoint.
691         ///
692         /// This data is static, and will never change for a channel once set. For a given [`ChannelSigner`]
693         /// instance, LDK will call this method exactly once - either immediately after construction
694         /// (not including if done via [`SignerProvider::read_chan_signer`]) or when the funding
695         /// information has been generated.
696         ///
697         /// channel_parameters.is_populated() MUST be true.
698         fn provide_channel_parameters(&mut self, channel_parameters: &ChannelTransactionParameters);
699 }
700
701 /// Specifies the recipient of an invoice.
702 ///
703 /// This indicates to [`NodeSigner::sign_invoice`] what node secret key should be used to sign
704 /// the invoice.
705 pub enum Recipient {
706         /// The invoice should be signed with the local node secret key.
707         Node,
708         /// The invoice should be signed with the phantom node secret key. This secret key must be the
709         /// same for all nodes participating in the [phantom node payment].
710         ///
711         /// [phantom node payment]: PhantomKeysManager
712         PhantomNode,
713 }
714
715 /// A trait that describes a source of entropy.
716 pub trait EntropySource {
717         /// Gets a unique, cryptographically-secure, random 32-byte value. This method must return a
718         /// different value each time it is called.
719         fn get_secure_random_bytes(&self) -> [u8; 32];
720 }
721
722 /// A trait that can handle cryptographic operations at the scope level of a node.
723 pub trait NodeSigner {
724         /// Get secret key material as bytes for use in encrypting and decrypting inbound payment data.
725         ///
726         /// If the implementor of this trait supports [phantom node payments], then every node that is
727         /// intended to be included in the phantom invoice route hints must return the same value from
728         /// this method.
729         // This is because LDK avoids storing inbound payment data by encrypting payment data in the
730         // payment hash and/or payment secret, therefore for a payment to be receivable by multiple
731         // nodes, they must share the key that encrypts this payment data.
732         ///
733         /// This method must return the same value each time it is called.
734         ///
735         /// [phantom node payments]: PhantomKeysManager
736         fn get_inbound_payment_key_material(&self) -> KeyMaterial;
737
738         /// Get node id based on the provided [`Recipient`].
739         ///
740         /// This method must return the same value each time it is called with a given [`Recipient`]
741         /// parameter.
742         ///
743         /// Errors if the [`Recipient`] variant is not supported by the implementation.
744         fn get_node_id(&self, recipient: Recipient) -> Result<PublicKey, ()>;
745
746         /// Gets the ECDH shared secret of our node secret and `other_key`, multiplying by `tweak` if
747         /// one is provided. Note that this tweak can be applied to `other_key` instead of our node
748         /// secret, though this is less efficient.
749         ///
750         /// Note that if this fails while attempting to forward an HTLC, LDK will panic. The error
751         /// should be resolved to allow LDK to resume forwarding HTLCs.
752         ///
753         /// Errors if the [`Recipient`] variant is not supported by the implementation.
754         fn ecdh(
755                 &self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&Scalar>,
756         ) -> Result<SharedSecret, ()>;
757
758         /// Sign an invoice.
759         ///
760         /// By parameterizing by the raw invoice bytes instead of the hash, we allow implementors of
761         /// this trait to parse the invoice and make sure they're signing what they expect, rather than
762         /// blindly signing the hash.
763         ///
764         /// The `hrp_bytes` are ASCII bytes, while the `invoice_data` is base32.
765         ///
766         /// The secret key used to sign the invoice is dependent on the [`Recipient`].
767         ///
768         /// Errors if the [`Recipient`] variant is not supported by the implementation.
769         fn sign_invoice(
770                 &self, hrp_bytes: &[u8], invoice_data: &[u5], recipient: Recipient,
771         ) -> Result<RecoverableSignature, ()>;
772
773         /// Signs the [`TaggedHash`] of a BOLT 12 invoice request.
774         ///
775         /// May be called by a function passed to [`UnsignedInvoiceRequest::sign`] where
776         /// `invoice_request` is the callee.
777         ///
778         /// Implementors may check that the `invoice_request` is expected rather than blindly signing
779         /// the tagged hash. An `Ok` result should sign `invoice_request.tagged_hash().as_digest()` with
780         /// the node's signing key or an ephemeral key to preserve privacy, whichever is associated with
781         /// [`UnsignedInvoiceRequest::payer_id`].
782         ///
783         /// [`TaggedHash`]: crate::offers::merkle::TaggedHash
784         fn sign_bolt12_invoice_request(
785                 &self, invoice_request: &UnsignedInvoiceRequest,
786         ) -> Result<schnorr::Signature, ()>;
787
788         /// Signs the [`TaggedHash`] of a BOLT 12 invoice.
789         ///
790         /// May be called by a function passed to [`UnsignedBolt12Invoice::sign`] where `invoice` is the
791         /// callee.
792         ///
793         /// Implementors may check that the `invoice` is expected rather than blindly signing the tagged
794         /// hash. An `Ok` result should sign `invoice.tagged_hash().as_digest()` with the node's signing
795         /// key or an ephemeral key to preserve privacy, whichever is associated with
796         /// [`UnsignedBolt12Invoice::signing_pubkey`].
797         ///
798         /// [`TaggedHash`]: crate::offers::merkle::TaggedHash
799         fn sign_bolt12_invoice(
800                 &self, invoice: &UnsignedBolt12Invoice,
801         ) -> Result<schnorr::Signature, ()>;
802
803         /// Sign a gossip message.
804         ///
805         /// Note that if this fails, LDK may panic and the message will not be broadcast to the network
806         /// or a possible channel counterparty. If LDK panics, the error should be resolved to allow the
807         /// message to be broadcast, as otherwise it may prevent one from receiving funds over the
808         /// corresponding channel.
809         fn sign_gossip_message(&self, msg: UnsignedGossipMessage) -> Result<Signature, ()>;
810 }
811
812 // Primarily needed in doctests because of https://github.com/rust-lang/rust/issues/67295
813 /// A dynamic [`SignerProvider`] temporarily needed for doc tests.
814 #[cfg(taproot)]
815 #[doc(hidden)]
816 #[deprecated(note = "Remove once taproot cfg is removed")]
817 pub type DynSignerProvider =
818         dyn SignerProvider<EcdsaSigner = InMemorySigner, TaprootSigner = InMemorySigner>;
819
820 /// A dynamic [`SignerProvider`] temporarily needed for doc tests.
821 #[cfg(not(taproot))]
822 #[doc(hidden)]
823 #[deprecated(note = "Remove once taproot cfg is removed")]
824 pub type DynSignerProvider = dyn SignerProvider<EcdsaSigner = InMemorySigner>;
825
826 /// A trait that can return signer instances for individual channels.
827 pub trait SignerProvider {
828         /// A type which implements [`WriteableEcdsaChannelSigner`] which will be returned by [`Self::derive_channel_signer`].
829         type EcdsaSigner: WriteableEcdsaChannelSigner;
830         #[cfg(taproot)]
831         /// A type which implements [`TaprootChannelSigner`]
832         type TaprootSigner: TaprootChannelSigner;
833
834         /// Generates a unique `channel_keys_id` that can be used to obtain a [`Self::EcdsaSigner`] through
835         /// [`SignerProvider::derive_channel_signer`]. The `user_channel_id` is provided to allow
836         /// implementations of [`SignerProvider`] to maintain a mapping between itself and the generated
837         /// `channel_keys_id`.
838         ///
839         /// This method must return a different value each time it is called.
840         fn generate_channel_keys_id(
841                 &self, inbound: bool, channel_value_satoshis: u64, user_channel_id: u128,
842         ) -> [u8; 32];
843
844         /// Derives the private key material backing a `Signer`.
845         ///
846         /// To derive a new `Signer`, a fresh `channel_keys_id` should be obtained through
847         /// [`SignerProvider::generate_channel_keys_id`]. Otherwise, an existing `Signer` can be
848         /// re-derived from its `channel_keys_id`, which can be obtained through its trait method
849         /// [`ChannelSigner::channel_keys_id`].
850         fn derive_channel_signer(
851                 &self, channel_value_satoshis: u64, channel_keys_id: [u8; 32],
852         ) -> Self::EcdsaSigner;
853
854         /// Reads a [`Signer`] for this [`SignerProvider`] from the given input stream.
855         /// This is only called during deserialization of other objects which contain
856         /// [`WriteableEcdsaChannelSigner`]-implementing objects (i.e., [`ChannelMonitor`]s and [`ChannelManager`]s).
857         /// The bytes are exactly those which `<Self::Signer as Writeable>::write()` writes, and
858         /// contain no versioning scheme. You may wish to include your own version prefix and ensure
859         /// you've read all of the provided bytes to ensure no corruption occurred.
860         ///
861         /// This method is slowly being phased out -- it will only be called when reading objects
862         /// written by LDK versions prior to 0.0.113.
863         ///
864         /// [`Signer`]: Self::EcdsaSigner
865         /// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
866         /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
867         fn read_chan_signer(&self, reader: &[u8]) -> Result<Self::EcdsaSigner, DecodeError>;
868
869         /// Get a script pubkey which we send funds to when claiming on-chain contestable outputs.
870         ///
871         /// If this function returns an error, this will result in a channel failing to open.
872         ///
873         /// This method should return a different value each time it is called, to avoid linking
874         /// on-chain funds across channels as controlled to the same user. `channel_keys_id` may be
875         /// used to derive a unique value for each channel.
876         fn get_destination_script(&self, channel_keys_id: [u8; 32]) -> Result<ScriptBuf, ()>;
877
878         /// Get a script pubkey which we will send funds to when closing a channel.
879         ///
880         /// If this function returns an error, this will result in a channel failing to open or close.
881         /// In the event of a failure when the counterparty is initiating a close, this can result in a
882         /// channel force close.
883         ///
884         /// This method should return a different value each time it is called, to avoid linking
885         /// on-chain funds across channels as controlled to the same user.
886         fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()>;
887 }
888
889 /// A simple implementation of [`WriteableEcdsaChannelSigner`] that just keeps the private keys in memory.
890 ///
891 /// This implementation performs no policy checks and is insufficient by itself as
892 /// a secure external signer.
893 #[derive(Debug)]
894 pub struct InMemorySigner {
895         /// Holder secret key in the 2-of-2 multisig script of a channel. This key also backs the
896         /// holder's anchor output in a commitment transaction, if one is present.
897         pub funding_key: SecretKey,
898         /// Holder secret key for blinded revocation pubkey.
899         pub revocation_base_key: SecretKey,
900         /// Holder secret key used for our balance in counterparty-broadcasted commitment transactions.
901         pub payment_key: SecretKey,
902         /// Holder secret key used in an HTLC transaction.
903         pub delayed_payment_base_key: SecretKey,
904         /// Holder HTLC secret key used in commitment transaction HTLC outputs.
905         pub htlc_base_key: SecretKey,
906         /// Commitment seed.
907         pub commitment_seed: [u8; 32],
908         /// Holder public keys and basepoints.
909         pub(crate) holder_channel_pubkeys: ChannelPublicKeys,
910         /// Counterparty public keys and counterparty/holder `selected_contest_delay`, populated on channel acceptance.
911         channel_parameters: Option<ChannelTransactionParameters>,
912         /// The total value of this channel.
913         channel_value_satoshis: u64,
914         /// Key derivation parameters.
915         channel_keys_id: [u8; 32],
916         /// A source of random bytes.
917         entropy_source: RandomBytes,
918 }
919
920 impl PartialEq for InMemorySigner {
921         fn eq(&self, other: &Self) -> bool {
922                 self.funding_key == other.funding_key
923                         && self.revocation_base_key == other.revocation_base_key
924                         && self.payment_key == other.payment_key
925                         && self.delayed_payment_base_key == other.delayed_payment_base_key
926                         && self.htlc_base_key == other.htlc_base_key
927                         && self.commitment_seed == other.commitment_seed
928                         && self.holder_channel_pubkeys == other.holder_channel_pubkeys
929                         && self.channel_parameters == other.channel_parameters
930                         && self.channel_value_satoshis == other.channel_value_satoshis
931                         && self.channel_keys_id == other.channel_keys_id
932         }
933 }
934
935 impl Clone for InMemorySigner {
936         fn clone(&self) -> Self {
937                 Self {
938                         funding_key: self.funding_key.clone(),
939                         revocation_base_key: self.revocation_base_key.clone(),
940                         payment_key: self.payment_key.clone(),
941                         delayed_payment_base_key: self.delayed_payment_base_key.clone(),
942                         htlc_base_key: self.htlc_base_key.clone(),
943                         commitment_seed: self.commitment_seed.clone(),
944                         holder_channel_pubkeys: self.holder_channel_pubkeys.clone(),
945                         channel_parameters: self.channel_parameters.clone(),
946                         channel_value_satoshis: self.channel_value_satoshis,
947                         channel_keys_id: self.channel_keys_id,
948                         entropy_source: RandomBytes::new(self.get_secure_random_bytes()),
949                 }
950         }
951 }
952
953 impl InMemorySigner {
954         /// Creates a new [`InMemorySigner`].
955         pub fn new<C: Signing>(
956                 secp_ctx: &Secp256k1<C>, funding_key: SecretKey, revocation_base_key: SecretKey,
957                 payment_key: SecretKey, delayed_payment_base_key: SecretKey, htlc_base_key: SecretKey,
958                 commitment_seed: [u8; 32], channel_value_satoshis: u64, channel_keys_id: [u8; 32],
959                 rand_bytes_unique_start: [u8; 32],
960         ) -> InMemorySigner {
961                 let holder_channel_pubkeys = InMemorySigner::make_holder_keys(
962                         secp_ctx,
963                         &funding_key,
964                         &revocation_base_key,
965                         &payment_key,
966                         &delayed_payment_base_key,
967                         &htlc_base_key,
968                 );
969                 InMemorySigner {
970                         funding_key,
971                         revocation_base_key,
972                         payment_key,
973                         delayed_payment_base_key,
974                         htlc_base_key,
975                         commitment_seed,
976                         channel_value_satoshis,
977                         holder_channel_pubkeys,
978                         channel_parameters: None,
979                         channel_keys_id,
980                         entropy_source: RandomBytes::new(rand_bytes_unique_start),
981                 }
982         }
983
984         fn make_holder_keys<C: Signing>(
985                 secp_ctx: &Secp256k1<C>, funding_key: &SecretKey, revocation_base_key: &SecretKey,
986                 payment_key: &SecretKey, delayed_payment_base_key: &SecretKey, htlc_base_key: &SecretKey,
987         ) -> ChannelPublicKeys {
988                 let from_secret = |s: &SecretKey| PublicKey::from_secret_key(secp_ctx, s);
989                 ChannelPublicKeys {
990                         funding_pubkey: from_secret(&funding_key),
991                         revocation_basepoint: RevocationBasepoint::from(from_secret(&revocation_base_key)),
992                         payment_point: from_secret(&payment_key),
993                         delayed_payment_basepoint: DelayedPaymentBasepoint::from(from_secret(
994                                 &delayed_payment_base_key,
995                         )),
996                         htlc_basepoint: HtlcBasepoint::from(from_secret(&htlc_base_key)),
997                 }
998         }
999
1000         /// Returns the counterparty's pubkeys.
1001         ///
1002         /// Will return `None` if [`ChannelSigner::provide_channel_parameters`] has not been called.
1003         /// In general, this is safe to `unwrap` only in [`ChannelSigner`] implementation.
1004         pub fn counterparty_pubkeys(&self) -> Option<&ChannelPublicKeys> {
1005                 self.get_channel_parameters().and_then(|params| {
1006                         params.counterparty_parameters.as_ref().map(|params| &params.pubkeys)
1007                 })
1008         }
1009
1010         /// Returns the `contest_delay` value specified by our counterparty and applied on holder-broadcastable
1011         /// transactions, i.e., the amount of time that we have to wait to recover our funds if we
1012         /// broadcast a transaction.
1013         ///
1014         /// Will return `None` if [`ChannelSigner::provide_channel_parameters`] has not been called.
1015         /// In general, this is safe to `unwrap` only in [`ChannelSigner`] implementation.
1016         pub fn counterparty_selected_contest_delay(&self) -> Option<u16> {
1017                 self.get_channel_parameters().and_then(|params| {
1018                         params.counterparty_parameters.as_ref().map(|params| params.selected_contest_delay)
1019                 })
1020         }
1021
1022         /// Returns the `contest_delay` value specified by us and applied on transactions broadcastable
1023         /// by our counterparty, i.e., the amount of time that they have to wait to recover their funds
1024         /// if they broadcast a transaction.
1025         ///
1026         /// Will return `None` if [`ChannelSigner::provide_channel_parameters`] has not been called.
1027         /// In general, this is safe to `unwrap` only in [`ChannelSigner`] implementation.
1028         pub fn holder_selected_contest_delay(&self) -> Option<u16> {
1029                 self.get_channel_parameters().map(|params| params.holder_selected_contest_delay)
1030         }
1031
1032         /// Returns whether the holder is the initiator.
1033         ///
1034         /// Will return `None` if [`ChannelSigner::provide_channel_parameters`] has not been called.
1035         /// In general, this is safe to `unwrap` only in [`ChannelSigner`] implementation.
1036         pub fn is_outbound(&self) -> Option<bool> {
1037                 self.get_channel_parameters().map(|params| params.is_outbound_from_holder)
1038         }
1039
1040         /// Funding outpoint
1041         ///
1042         /// Will return `None` if [`ChannelSigner::provide_channel_parameters`] has not been called.
1043         /// In general, this is safe to `unwrap` only in [`ChannelSigner`] implementation.
1044         pub fn funding_outpoint(&self) -> Option<&OutPoint> {
1045                 self.get_channel_parameters().map(|params| params.funding_outpoint.as_ref()).flatten()
1046         }
1047
1048         /// Returns a [`ChannelTransactionParameters`] for this channel, to be used when verifying or
1049         /// building transactions.
1050         ///
1051         /// Will return `None` if [`ChannelSigner::provide_channel_parameters`] has not been called.
1052         /// In general, this is safe to `unwrap` only in [`ChannelSigner`] implementation.
1053         pub fn get_channel_parameters(&self) -> Option<&ChannelTransactionParameters> {
1054                 self.channel_parameters.as_ref()
1055         }
1056
1057         /// Returns the channel type features of the channel parameters. Should be helpful for
1058         /// determining a channel's category, i. e. legacy/anchors/taproot/etc.
1059         ///
1060         /// Will return `None` if [`ChannelSigner::provide_channel_parameters`] has not been called.
1061         /// In general, this is safe to `unwrap` only in [`ChannelSigner`] implementation.
1062         pub fn channel_type_features(&self) -> Option<&ChannelTypeFeatures> {
1063                 self.get_channel_parameters().map(|params| &params.channel_type_features)
1064         }
1065
1066         /// Sign the single input of `spend_tx` at index `input_idx`, which spends the output described
1067         /// by `descriptor`, returning the witness stack for the input.
1068         ///
1069         /// Returns an error if the input at `input_idx` does not exist, has a non-empty `script_sig`,
1070         /// is not spending the outpoint described by [`descriptor.outpoint`],
1071         /// or if an output descriptor `script_pubkey` does not match the one we can spend.
1072         ///
1073         /// [`descriptor.outpoint`]: StaticPaymentOutputDescriptor::outpoint
1074         pub fn sign_counterparty_payment_input<C: Signing>(
1075                 &self, spend_tx: &Transaction, input_idx: usize,
1076                 descriptor: &StaticPaymentOutputDescriptor, secp_ctx: &Secp256k1<C>,
1077         ) -> Result<Witness, ()> {
1078                 // TODO: We really should be taking the SigHashCache as a parameter here instead of
1079                 // spend_tx, but ideally the SigHashCache would expose the transaction's inputs read-only
1080                 // so that we can check them. This requires upstream rust-bitcoin changes (as well as
1081                 // bindings updates to support SigHashCache objects).
1082                 if spend_tx.input.len() <= input_idx {
1083                         return Err(());
1084                 }
1085                 if !spend_tx.input[input_idx].script_sig.is_empty() {
1086                         return Err(());
1087                 }
1088                 if spend_tx.input[input_idx].previous_output != descriptor.outpoint.into_bitcoin_outpoint()
1089                 {
1090                         return Err(());
1091                 }
1092
1093                 let remotepubkey = bitcoin::PublicKey::new(self.pubkeys().payment_point);
1094                 // We cannot always assume that `channel_parameters` is set, so can't just call
1095                 // `self.channel_parameters()` or anything that relies on it
1096                 let supports_anchors_zero_fee_htlc_tx = self
1097                         .channel_type_features()
1098                         .map(|features| features.supports_anchors_zero_fee_htlc_tx())
1099                         .unwrap_or(false);
1100
1101                 let witness_script = if supports_anchors_zero_fee_htlc_tx {
1102                         chan_utils::get_to_countersignatory_with_anchors_redeemscript(&remotepubkey.inner)
1103                 } else {
1104                         ScriptBuf::new_p2pkh(&remotepubkey.pubkey_hash())
1105                 };
1106                 let sighash = hash_to_message!(
1107                         &sighash::SighashCache::new(spend_tx)
1108                                 .segwit_signature_hash(
1109                                         input_idx,
1110                                         &witness_script,
1111                                         descriptor.output.value,
1112                                         EcdsaSighashType::All
1113                                 )
1114                                 .unwrap()[..]
1115                 );
1116                 let remotesig = sign_with_aux_rand(secp_ctx, &sighash, &self.payment_key, &self);
1117                 let payment_script = if supports_anchors_zero_fee_htlc_tx {
1118                         witness_script.to_v0_p2wsh()
1119                 } else {
1120                         ScriptBuf::new_v0_p2wpkh(&remotepubkey.wpubkey_hash().unwrap())
1121                 };
1122
1123                 if payment_script != descriptor.output.script_pubkey {
1124                         return Err(());
1125                 }
1126
1127                 let mut witness = Vec::with_capacity(2);
1128                 witness.push(remotesig.serialize_der().to_vec());
1129                 witness[0].push(EcdsaSighashType::All as u8);
1130                 if supports_anchors_zero_fee_htlc_tx {
1131                         witness.push(witness_script.to_bytes());
1132                 } else {
1133                         witness.push(remotepubkey.to_bytes());
1134                 }
1135                 Ok(witness.into())
1136         }
1137
1138         /// Sign the single input of `spend_tx` at index `input_idx` which spends the output
1139         /// described by `descriptor`, returning the witness stack for the input.
1140         ///
1141         /// Returns an error if the input at `input_idx` does not exist, has a non-empty `script_sig`,
1142         /// is not spending the outpoint described by [`descriptor.outpoint`], does not have a
1143         /// sequence set to [`descriptor.to_self_delay`], or if an output descriptor
1144         /// `script_pubkey` does not match the one we can spend.
1145         ///
1146         /// [`descriptor.outpoint`]: DelayedPaymentOutputDescriptor::outpoint
1147         /// [`descriptor.to_self_delay`]: DelayedPaymentOutputDescriptor::to_self_delay
1148         pub fn sign_dynamic_p2wsh_input<C: Signing>(
1149                 &self, spend_tx: &Transaction, input_idx: usize,
1150                 descriptor: &DelayedPaymentOutputDescriptor, secp_ctx: &Secp256k1<C>,
1151         ) -> Result<Witness, ()> {
1152                 // TODO: We really should be taking the SigHashCache as a parameter here instead of
1153                 // spend_tx, but ideally the SigHashCache would expose the transaction's inputs read-only
1154                 // so that we can check them. This requires upstream rust-bitcoin changes (as well as
1155                 // bindings updates to support SigHashCache objects).
1156                 if spend_tx.input.len() <= input_idx {
1157                         return Err(());
1158                 }
1159                 if !spend_tx.input[input_idx].script_sig.is_empty() {
1160                         return Err(());
1161                 }
1162                 if spend_tx.input[input_idx].previous_output != descriptor.outpoint.into_bitcoin_outpoint()
1163                 {
1164                         return Err(());
1165                 }
1166                 if spend_tx.input[input_idx].sequence.0 != descriptor.to_self_delay as u32 {
1167                         return Err(());
1168                 }
1169
1170                 let delayed_payment_key = chan_utils::derive_private_key(
1171                         &secp_ctx,
1172                         &descriptor.per_commitment_point,
1173                         &self.delayed_payment_base_key,
1174                 );
1175                 let delayed_payment_pubkey =
1176                         DelayedPaymentKey::from_secret_key(&secp_ctx, &delayed_payment_key);
1177                 let witness_script = chan_utils::get_revokeable_redeemscript(
1178                         &descriptor.revocation_pubkey,
1179                         descriptor.to_self_delay,
1180                         &delayed_payment_pubkey,
1181                 );
1182                 let sighash = hash_to_message!(
1183                         &sighash::SighashCache::new(spend_tx)
1184                                 .segwit_signature_hash(
1185                                         input_idx,
1186                                         &witness_script,
1187                                         descriptor.output.value,
1188                                         EcdsaSighashType::All
1189                                 )
1190                                 .unwrap()[..]
1191                 );
1192                 let local_delayedsig = EcdsaSignature {
1193                         sig: sign_with_aux_rand(secp_ctx, &sighash, &delayed_payment_key, &self),
1194                         hash_ty: EcdsaSighashType::All,
1195                 };
1196                 let payment_script =
1197                         bitcoin::Address::p2wsh(&witness_script, Network::Bitcoin).script_pubkey();
1198
1199                 if descriptor.output.script_pubkey != payment_script {
1200                         return Err(());
1201                 }
1202
1203                 Ok(Witness::from_slice(&[
1204                         &local_delayedsig.serialize()[..],
1205                         &[], // MINIMALIF
1206                         witness_script.as_bytes(),
1207                 ]))
1208         }
1209 }
1210
1211 impl EntropySource for InMemorySigner {
1212         fn get_secure_random_bytes(&self) -> [u8; 32] {
1213                 self.entropy_source.get_secure_random_bytes()
1214         }
1215 }
1216
1217 impl ChannelSigner for InMemorySigner {
1218         fn get_per_commitment_point(
1219                 &self, idx: u64, secp_ctx: &Secp256k1<secp256k1::All>,
1220         ) -> PublicKey {
1221                 let commitment_secret =
1222                         SecretKey::from_slice(&chan_utils::build_commitment_secret(&self.commitment_seed, idx))
1223                                 .unwrap();
1224                 PublicKey::from_secret_key(secp_ctx, &commitment_secret)
1225         }
1226
1227         fn release_commitment_secret(&self, idx: u64) -> [u8; 32] {
1228                 chan_utils::build_commitment_secret(&self.commitment_seed, idx)
1229         }
1230
1231         fn validate_holder_commitment(
1232                 &self, _holder_tx: &HolderCommitmentTransaction,
1233                 _outbound_htlc_preimages: Vec<PaymentPreimage>,
1234         ) -> Result<(), ()> {
1235                 Ok(())
1236         }
1237
1238         fn validate_counterparty_revocation(&self, _idx: u64, _secret: &SecretKey) -> Result<(), ()> {
1239                 Ok(())
1240         }
1241
1242         fn pubkeys(&self) -> &ChannelPublicKeys {
1243                 &self.holder_channel_pubkeys
1244         }
1245
1246         fn channel_keys_id(&self) -> [u8; 32] {
1247                 self.channel_keys_id
1248         }
1249
1250         fn provide_channel_parameters(&mut self, channel_parameters: &ChannelTransactionParameters) {
1251                 assert!(
1252                         self.channel_parameters.is_none()
1253                                 || self.channel_parameters.as_ref().unwrap() == channel_parameters
1254                 );
1255                 if self.channel_parameters.is_some() {
1256                         // The channel parameters were already set and they match, return early.
1257                         return;
1258                 }
1259                 assert!(channel_parameters.is_populated(), "Channel parameters must be fully populated");
1260                 self.channel_parameters = Some(channel_parameters.clone());
1261         }
1262 }
1263
1264 const MISSING_PARAMS_ERR: &'static str =
1265         "ChannelSigner::provide_channel_parameters must be called before signing operations";
1266
1267 impl EcdsaChannelSigner for InMemorySigner {
1268         fn sign_counterparty_commitment(
1269                 &self, commitment_tx: &CommitmentTransaction,
1270                 _inbound_htlc_preimages: Vec<PaymentPreimage>,
1271                 _outbound_htlc_preimages: Vec<PaymentPreimage>, secp_ctx: &Secp256k1<secp256k1::All>,
1272         ) -> Result<(Signature, Vec<Signature>), ()> {
1273                 let trusted_tx = commitment_tx.trust();
1274                 let keys = trusted_tx.keys();
1275
1276                 let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
1277                 let counterparty_keys = self.counterparty_pubkeys().expect(MISSING_PARAMS_ERR);
1278                 let channel_funding_redeemscript =
1279                         make_funding_redeemscript(&funding_pubkey, &counterparty_keys.funding_pubkey);
1280
1281                 let built_tx = trusted_tx.built_transaction();
1282                 let commitment_sig = built_tx.sign_counterparty_commitment(
1283                         &self.funding_key,
1284                         &channel_funding_redeemscript,
1285                         self.channel_value_satoshis,
1286                         secp_ctx,
1287                 );
1288                 let commitment_txid = built_tx.txid;
1289
1290                 let mut htlc_sigs = Vec::with_capacity(commitment_tx.htlcs().len());
1291                 for htlc in commitment_tx.htlcs() {
1292                         let channel_parameters = self.get_channel_parameters().expect(MISSING_PARAMS_ERR);
1293                         let holder_selected_contest_delay =
1294                                 self.holder_selected_contest_delay().expect(MISSING_PARAMS_ERR);
1295                         let chan_type = &channel_parameters.channel_type_features;
1296                         let htlc_tx = chan_utils::build_htlc_transaction(
1297                                 &commitment_txid,
1298                                 commitment_tx.feerate_per_kw(),
1299                                 holder_selected_contest_delay,
1300                                 htlc,
1301                                 chan_type,
1302                                 &keys.broadcaster_delayed_payment_key,
1303                                 &keys.revocation_key,
1304                         );
1305                         let htlc_redeemscript = chan_utils::get_htlc_redeemscript(&htlc, chan_type, &keys);
1306                         let htlc_sighashtype = if chan_type.supports_anchors_zero_fee_htlc_tx() {
1307                                 EcdsaSighashType::SinglePlusAnyoneCanPay
1308                         } else {
1309                                 EcdsaSighashType::All
1310                         };
1311                         let htlc_sighash = hash_to_message!(
1312                                 &sighash::SighashCache::new(&htlc_tx)
1313                                         .segwit_signature_hash(
1314                                                 0,
1315                                                 &htlc_redeemscript,
1316                                                 htlc.amount_msat / 1000,
1317                                                 htlc_sighashtype
1318                                         )
1319                                         .unwrap()[..]
1320                         );
1321                         let holder_htlc_key = chan_utils::derive_private_key(
1322                                 &secp_ctx,
1323                                 &keys.per_commitment_point,
1324                                 &self.htlc_base_key,
1325                         );
1326                         htlc_sigs.push(sign(secp_ctx, &htlc_sighash, &holder_htlc_key));
1327                 }
1328
1329                 Ok((commitment_sig, htlc_sigs))
1330         }
1331
1332         fn sign_holder_commitment(
1333                 &self, commitment_tx: &HolderCommitmentTransaction, secp_ctx: &Secp256k1<secp256k1::All>,
1334         ) -> Result<Signature, ()> {
1335                 let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
1336                 let counterparty_keys = self.counterparty_pubkeys().expect(MISSING_PARAMS_ERR);
1337                 let funding_redeemscript =
1338                         make_funding_redeemscript(&funding_pubkey, &counterparty_keys.funding_pubkey);
1339                 let trusted_tx = commitment_tx.trust();
1340                 Ok(trusted_tx.built_transaction().sign_holder_commitment(
1341                         &self.funding_key,
1342                         &funding_redeemscript,
1343                         self.channel_value_satoshis,
1344                         &self,
1345                         secp_ctx,
1346                 ))
1347         }
1348
1349         #[cfg(any(test, feature = "unsafe_revoked_tx_signing"))]
1350         fn unsafe_sign_holder_commitment(
1351                 &self, commitment_tx: &HolderCommitmentTransaction, secp_ctx: &Secp256k1<secp256k1::All>,
1352         ) -> Result<Signature, ()> {
1353                 let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
1354                 let counterparty_keys = self.counterparty_pubkeys().expect(MISSING_PARAMS_ERR);
1355                 let funding_redeemscript =
1356                         make_funding_redeemscript(&funding_pubkey, &counterparty_keys.funding_pubkey);
1357                 let trusted_tx = commitment_tx.trust();
1358                 Ok(trusted_tx.built_transaction().sign_holder_commitment(
1359                         &self.funding_key,
1360                         &funding_redeemscript,
1361                         self.channel_value_satoshis,
1362                         &self,
1363                         secp_ctx,
1364                 ))
1365         }
1366
1367         fn sign_justice_revoked_output(
1368                 &self, justice_tx: &Transaction, input: usize, amount: u64, per_commitment_key: &SecretKey,
1369                 secp_ctx: &Secp256k1<secp256k1::All>,
1370         ) -> Result<Signature, ()> {
1371                 let revocation_key = chan_utils::derive_private_revocation_key(
1372                         &secp_ctx,
1373                         &per_commitment_key,
1374                         &self.revocation_base_key,
1375                 );
1376                 let per_commitment_point = PublicKey::from_secret_key(secp_ctx, &per_commitment_key);
1377                 let revocation_pubkey = RevocationKey::from_basepoint(
1378                         &secp_ctx,
1379                         &self.pubkeys().revocation_basepoint,
1380                         &per_commitment_point,
1381                 );
1382                 let witness_script = {
1383                         let counterparty_keys = self.counterparty_pubkeys().expect(MISSING_PARAMS_ERR);
1384                         let holder_selected_contest_delay =
1385                                 self.holder_selected_contest_delay().expect(MISSING_PARAMS_ERR);
1386                         let counterparty_delayedpubkey = DelayedPaymentKey::from_basepoint(
1387                                 &secp_ctx,
1388                                 &counterparty_keys.delayed_payment_basepoint,
1389                                 &per_commitment_point,
1390                         );
1391                         chan_utils::get_revokeable_redeemscript(
1392                                 &revocation_pubkey,
1393                                 holder_selected_contest_delay,
1394                                 &counterparty_delayedpubkey,
1395                         )
1396                 };
1397                 let mut sighash_parts = sighash::SighashCache::new(justice_tx);
1398                 let sighash = hash_to_message!(
1399                         &sighash_parts
1400                                 .segwit_signature_hash(input, &witness_script, amount, EcdsaSighashType::All)
1401                                 .unwrap()[..]
1402                 );
1403                 return Ok(sign_with_aux_rand(secp_ctx, &sighash, &revocation_key, &self));
1404         }
1405
1406         fn sign_justice_revoked_htlc(
1407                 &self, justice_tx: &Transaction, input: usize, amount: u64, per_commitment_key: &SecretKey,
1408                 htlc: &HTLCOutputInCommitment, secp_ctx: &Secp256k1<secp256k1::All>,
1409         ) -> Result<Signature, ()> {
1410                 let revocation_key = chan_utils::derive_private_revocation_key(
1411                         &secp_ctx,
1412                         &per_commitment_key,
1413                         &self.revocation_base_key,
1414                 );
1415                 let per_commitment_point = PublicKey::from_secret_key(secp_ctx, &per_commitment_key);
1416                 let revocation_pubkey = RevocationKey::from_basepoint(
1417                         &secp_ctx,
1418                         &self.pubkeys().revocation_basepoint,
1419                         &per_commitment_point,
1420                 );
1421                 let witness_script = {
1422                         let counterparty_keys = self.counterparty_pubkeys().expect(MISSING_PARAMS_ERR);
1423                         let counterparty_htlcpubkey = HtlcKey::from_basepoint(
1424                                 &secp_ctx,
1425                                 &counterparty_keys.htlc_basepoint,
1426                                 &per_commitment_point,
1427                         );
1428                         let holder_htlcpubkey = HtlcKey::from_basepoint(
1429                                 &secp_ctx,
1430                                 &self.pubkeys().htlc_basepoint,
1431                                 &per_commitment_point,
1432                         );
1433                         let chan_type = self.channel_type_features().expect(MISSING_PARAMS_ERR);
1434                         chan_utils::get_htlc_redeemscript_with_explicit_keys(
1435                                 &htlc,
1436                                 chan_type,
1437                                 &counterparty_htlcpubkey,
1438                                 &holder_htlcpubkey,
1439                                 &revocation_pubkey,
1440                         )
1441                 };
1442                 let mut sighash_parts = sighash::SighashCache::new(justice_tx);
1443                 let sighash = hash_to_message!(
1444                         &sighash_parts
1445                                 .segwit_signature_hash(input, &witness_script, amount, EcdsaSighashType::All)
1446                                 .unwrap()[..]
1447                 );
1448                 return Ok(sign_with_aux_rand(secp_ctx, &sighash, &revocation_key, &self));
1449         }
1450
1451         fn sign_holder_htlc_transaction(
1452                 &self, htlc_tx: &Transaction, input: usize, htlc_descriptor: &HTLCDescriptor,
1453                 secp_ctx: &Secp256k1<secp256k1::All>,
1454         ) -> Result<Signature, ()> {
1455                 let witness_script = htlc_descriptor.witness_script(secp_ctx);
1456                 let sighash = &sighash::SighashCache::new(&*htlc_tx)
1457                         .segwit_signature_hash(
1458                                 input,
1459                                 &witness_script,
1460                                 htlc_descriptor.htlc.amount_msat / 1000,
1461                                 EcdsaSighashType::All,
1462                         )
1463                         .map_err(|_| ())?;
1464                 let our_htlc_private_key = chan_utils::derive_private_key(
1465                         &secp_ctx,
1466                         &htlc_descriptor.per_commitment_point,
1467                         &self.htlc_base_key,
1468                 );
1469                 let sighash = hash_to_message!(sighash.as_byte_array());
1470                 Ok(sign_with_aux_rand(&secp_ctx, &sighash, &our_htlc_private_key, &self))
1471         }
1472
1473         fn sign_counterparty_htlc_transaction(
1474                 &self, htlc_tx: &Transaction, input: usize, amount: u64, per_commitment_point: &PublicKey,
1475                 htlc: &HTLCOutputInCommitment, secp_ctx: &Secp256k1<secp256k1::All>,
1476         ) -> Result<Signature, ()> {
1477                 let htlc_key =
1478                         chan_utils::derive_private_key(&secp_ctx, &per_commitment_point, &self.htlc_base_key);
1479                 let revocation_pubkey = RevocationKey::from_basepoint(
1480                         &secp_ctx,
1481                         &self.pubkeys().revocation_basepoint,
1482                         &per_commitment_point,
1483                 );
1484                 let counterparty_keys = self.counterparty_pubkeys().expect(MISSING_PARAMS_ERR);
1485                 let counterparty_htlcpubkey = HtlcKey::from_basepoint(
1486                         &secp_ctx,
1487                         &counterparty_keys.htlc_basepoint,
1488                         &per_commitment_point,
1489                 );
1490                 let htlc_basepoint = self.pubkeys().htlc_basepoint;
1491                 let htlcpubkey = HtlcKey::from_basepoint(&secp_ctx, &htlc_basepoint, &per_commitment_point);
1492                 let chan_type = self.channel_type_features().expect(MISSING_PARAMS_ERR);
1493                 let witness_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(
1494                         &htlc,
1495                         chan_type,
1496                         &counterparty_htlcpubkey,
1497                         &htlcpubkey,
1498                         &revocation_pubkey,
1499                 );
1500                 let mut sighash_parts = sighash::SighashCache::new(htlc_tx);
1501                 let sighash = hash_to_message!(
1502                         &sighash_parts
1503                                 .segwit_signature_hash(input, &witness_script, amount, EcdsaSighashType::All)
1504                                 .unwrap()[..]
1505                 );
1506                 Ok(sign_with_aux_rand(secp_ctx, &sighash, &htlc_key, &self))
1507         }
1508
1509         fn sign_closing_transaction(
1510                 &self, closing_tx: &ClosingTransaction, secp_ctx: &Secp256k1<secp256k1::All>,
1511         ) -> Result<Signature, ()> {
1512                 let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
1513                 let counterparty_funding_key =
1514                         &self.counterparty_pubkeys().expect(MISSING_PARAMS_ERR).funding_pubkey;
1515                 let channel_funding_redeemscript =
1516                         make_funding_redeemscript(&funding_pubkey, counterparty_funding_key);
1517                 Ok(closing_tx.trust().sign(
1518                         &self.funding_key,
1519                         &channel_funding_redeemscript,
1520                         self.channel_value_satoshis,
1521                         secp_ctx,
1522                 ))
1523         }
1524
1525         fn sign_holder_anchor_input(
1526                 &self, anchor_tx: &Transaction, input: usize, secp_ctx: &Secp256k1<secp256k1::All>,
1527         ) -> Result<Signature, ()> {
1528                 let witness_script =
1529                         chan_utils::get_anchor_redeemscript(&self.holder_channel_pubkeys.funding_pubkey);
1530                 let sighash = sighash::SighashCache::new(&*anchor_tx)
1531                         .segwit_signature_hash(
1532                                 input,
1533                                 &witness_script,
1534                                 ANCHOR_OUTPUT_VALUE_SATOSHI,
1535                                 EcdsaSighashType::All,
1536                         )
1537                         .unwrap();
1538                 Ok(sign_with_aux_rand(secp_ctx, &hash_to_message!(&sighash[..]), &self.funding_key, &self))
1539         }
1540
1541         fn sign_channel_announcement_with_funding_key(
1542                 &self, msg: &UnsignedChannelAnnouncement, secp_ctx: &Secp256k1<secp256k1::All>,
1543         ) -> Result<Signature, ()> {
1544                 let msghash = hash_to_message!(&Sha256dHash::hash(&msg.encode()[..])[..]);
1545                 Ok(secp_ctx.sign_ecdsa(&msghash, &self.funding_key))
1546         }
1547 }
1548
1549 #[cfg(taproot)]
1550 impl TaprootChannelSigner for InMemorySigner {
1551         fn generate_local_nonce_pair(
1552                 &self, commitment_number: u64, secp_ctx: &Secp256k1<All>,
1553         ) -> PublicNonce {
1554                 todo!()
1555         }
1556
1557         fn partially_sign_counterparty_commitment(
1558                 &self, counterparty_nonce: PublicNonce, commitment_tx: &CommitmentTransaction,
1559                 inbound_htlc_preimages: Vec<PaymentPreimage>,
1560                 outbound_htlc_preimages: Vec<PaymentPreimage>, secp_ctx: &Secp256k1<All>,
1561         ) -> Result<(PartialSignatureWithNonce, Vec<schnorr::Signature>), ()> {
1562                 todo!()
1563         }
1564
1565         fn finalize_holder_commitment(
1566                 &self, commitment_tx: &HolderCommitmentTransaction,
1567                 counterparty_partial_signature: PartialSignatureWithNonce, secp_ctx: &Secp256k1<All>,
1568         ) -> Result<PartialSignature, ()> {
1569                 todo!()
1570         }
1571
1572         fn sign_justice_revoked_output(
1573                 &self, justice_tx: &Transaction, input: usize, amount: u64, per_commitment_key: &SecretKey,
1574                 secp_ctx: &Secp256k1<All>,
1575         ) -> Result<schnorr::Signature, ()> {
1576                 todo!()
1577         }
1578
1579         fn sign_justice_revoked_htlc(
1580                 &self, justice_tx: &Transaction, input: usize, amount: u64, per_commitment_key: &SecretKey,
1581                 htlc: &HTLCOutputInCommitment, secp_ctx: &Secp256k1<All>,
1582         ) -> Result<schnorr::Signature, ()> {
1583                 todo!()
1584         }
1585
1586         fn sign_holder_htlc_transaction(
1587                 &self, htlc_tx: &Transaction, input: usize, htlc_descriptor: &HTLCDescriptor,
1588                 secp_ctx: &Secp256k1<All>,
1589         ) -> Result<schnorr::Signature, ()> {
1590                 todo!()
1591         }
1592
1593         fn sign_counterparty_htlc_transaction(
1594                 &self, htlc_tx: &Transaction, input: usize, amount: u64, per_commitment_point: &PublicKey,
1595                 htlc: &HTLCOutputInCommitment, secp_ctx: &Secp256k1<All>,
1596         ) -> Result<schnorr::Signature, ()> {
1597                 todo!()
1598         }
1599
1600         fn partially_sign_closing_transaction(
1601                 &self, closing_tx: &ClosingTransaction, secp_ctx: &Secp256k1<All>,
1602         ) -> Result<PartialSignature, ()> {
1603                 todo!()
1604         }
1605
1606         fn sign_holder_anchor_input(
1607                 &self, anchor_tx: &Transaction, input: usize, secp_ctx: &Secp256k1<All>,
1608         ) -> Result<schnorr::Signature, ()> {
1609                 todo!()
1610         }
1611 }
1612
1613 const SERIALIZATION_VERSION: u8 = 1;
1614
1615 const MIN_SERIALIZATION_VERSION: u8 = 1;
1616
1617 impl WriteableEcdsaChannelSigner for InMemorySigner {}
1618
1619 impl Writeable for InMemorySigner {
1620         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), Error> {
1621                 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
1622
1623                 self.funding_key.write(writer)?;
1624                 self.revocation_base_key.write(writer)?;
1625                 self.payment_key.write(writer)?;
1626                 self.delayed_payment_base_key.write(writer)?;
1627                 self.htlc_base_key.write(writer)?;
1628                 self.commitment_seed.write(writer)?;
1629                 self.channel_parameters.write(writer)?;
1630                 self.channel_value_satoshis.write(writer)?;
1631                 self.channel_keys_id.write(writer)?;
1632
1633                 write_tlv_fields!(writer, {});
1634
1635                 Ok(())
1636         }
1637 }
1638
1639 impl<ES: Deref> ReadableArgs<ES> for InMemorySigner
1640 where
1641         ES::Target: EntropySource,
1642 {
1643         fn read<R: io::Read>(reader: &mut R, entropy_source: ES) -> Result<Self, DecodeError> {
1644                 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
1645
1646                 let funding_key = Readable::read(reader)?;
1647                 let revocation_base_key = Readable::read(reader)?;
1648                 let payment_key = Readable::read(reader)?;
1649                 let delayed_payment_base_key = Readable::read(reader)?;
1650                 let htlc_base_key = Readable::read(reader)?;
1651                 let commitment_seed = Readable::read(reader)?;
1652                 let counterparty_channel_data = Readable::read(reader)?;
1653                 let channel_value_satoshis = Readable::read(reader)?;
1654                 let secp_ctx = Secp256k1::signing_only();
1655                 let holder_channel_pubkeys = InMemorySigner::make_holder_keys(
1656                         &secp_ctx,
1657                         &funding_key,
1658                         &revocation_base_key,
1659                         &payment_key,
1660                         &delayed_payment_base_key,
1661                         &htlc_base_key,
1662                 );
1663                 let keys_id = Readable::read(reader)?;
1664
1665                 read_tlv_fields!(reader, {});
1666
1667                 Ok(InMemorySigner {
1668                         funding_key,
1669                         revocation_base_key,
1670                         payment_key,
1671                         delayed_payment_base_key,
1672                         htlc_base_key,
1673                         commitment_seed,
1674                         channel_value_satoshis,
1675                         holder_channel_pubkeys,
1676                         channel_parameters: counterparty_channel_data,
1677                         channel_keys_id: keys_id,
1678                         entropy_source: RandomBytes::new(entropy_source.get_secure_random_bytes()),
1679                 })
1680         }
1681 }
1682
1683 /// Simple implementation of [`EntropySource`], [`NodeSigner`], and [`SignerProvider`] that takes a
1684 /// 32-byte seed for use as a BIP 32 extended key and derives keys from that.
1685 ///
1686 /// Your `node_id` is seed/0'.
1687 /// Unilateral closes may use seed/1'.
1688 /// Cooperative closes may use seed/2'.
1689 /// The two close keys may be needed to claim on-chain funds!
1690 ///
1691 /// This struct cannot be used for nodes that wish to support receiving phantom payments;
1692 /// [`PhantomKeysManager`] must be used instead.
1693 ///
1694 /// Note that switching between this struct and [`PhantomKeysManager`] will invalidate any
1695 /// previously issued invoices and attempts to pay previous invoices will fail.
1696 pub struct KeysManager {
1697         secp_ctx: Secp256k1<secp256k1::All>,
1698         node_secret: SecretKey,
1699         node_id: PublicKey,
1700         inbound_payment_key: KeyMaterial,
1701         destination_script: ScriptBuf,
1702         shutdown_pubkey: PublicKey,
1703         channel_master_key: ExtendedPrivKey,
1704         channel_child_index: AtomicUsize,
1705
1706         entropy_source: RandomBytes,
1707
1708         seed: [u8; 32],
1709         starting_time_secs: u64,
1710         starting_time_nanos: u32,
1711 }
1712
1713 impl KeysManager {
1714         /// Constructs a [`KeysManager`] from a 32-byte seed. If the seed is in some way biased (e.g.,
1715         /// your CSRNG is busted) this may panic (but more importantly, you will possibly lose funds).
1716         /// `starting_time` isn't strictly required to actually be a time, but it must absolutely,
1717         /// without a doubt, be unique to this instance. ie if you start multiple times with the same
1718         /// `seed`, `starting_time` must be unique to each run. Thus, the easiest way to achieve this
1719         /// is to simply use the current time (with very high precision).
1720         ///
1721         /// The `seed` MUST be backed up safely prior to use so that the keys can be re-created, however,
1722         /// obviously, `starting_time` should be unique every time you reload the library - it is only
1723         /// used to generate new ephemeral key data (which will be stored by the individual channel if
1724         /// necessary).
1725         ///
1726         /// Note that the seed is required to recover certain on-chain funds independent of
1727         /// [`ChannelMonitor`] data, though a current copy of [`ChannelMonitor`] data is also required
1728         /// for any channel, and some on-chain during-closing funds.
1729         ///
1730         /// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
1731         pub fn new(seed: &[u8; 32], starting_time_secs: u64, starting_time_nanos: u32) -> Self {
1732                 let secp_ctx = Secp256k1::new();
1733                 // Note that when we aren't serializing the key, network doesn't matter
1734                 match ExtendedPrivKey::new_master(Network::Testnet, seed) {
1735                         Ok(master_key) => {
1736                                 let node_secret = master_key
1737                                         .ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(0).unwrap())
1738                                         .expect("Your RNG is busted")
1739                                         .private_key;
1740                                 let node_id = PublicKey::from_secret_key(&secp_ctx, &node_secret);
1741                                 let destination_script = match master_key
1742                                         .ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(1).unwrap())
1743                                 {
1744                                         Ok(destination_key) => {
1745                                                 let wpubkey_hash = WPubkeyHash::hash(
1746                                                         &ExtendedPubKey::from_priv(&secp_ctx, &destination_key)
1747                                                                 .to_pub()
1748                                                                 .to_bytes(),
1749                                                 );
1750                                                 Builder::new()
1751                                                         .push_opcode(opcodes::all::OP_PUSHBYTES_0)
1752                                                         .push_slice(&wpubkey_hash.to_byte_array())
1753                                                         .into_script()
1754                                         },
1755                                         Err(_) => panic!("Your RNG is busted"),
1756                                 };
1757                                 let shutdown_pubkey = match master_key
1758                                         .ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(2).unwrap())
1759                                 {
1760                                         Ok(shutdown_key) => {
1761                                                 ExtendedPubKey::from_priv(&secp_ctx, &shutdown_key).public_key
1762                                         },
1763                                         Err(_) => panic!("Your RNG is busted"),
1764                                 };
1765                                 let channel_master_key = master_key
1766                                         .ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(3).unwrap())
1767                                         .expect("Your RNG is busted");
1768                                 let inbound_payment_key: SecretKey = master_key
1769                                         .ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(5).unwrap())
1770                                         .expect("Your RNG is busted")
1771                                         .private_key;
1772                                 let mut inbound_pmt_key_bytes = [0; 32];
1773                                 inbound_pmt_key_bytes.copy_from_slice(&inbound_payment_key[..]);
1774
1775                                 let mut rand_bytes_engine = Sha256::engine();
1776                                 rand_bytes_engine.input(&starting_time_secs.to_be_bytes());
1777                                 rand_bytes_engine.input(&starting_time_nanos.to_be_bytes());
1778                                 rand_bytes_engine.input(seed);
1779                                 rand_bytes_engine.input(b"LDK PRNG Seed");
1780                                 let rand_bytes_unique_start =
1781                                         Sha256::from_engine(rand_bytes_engine).to_byte_array();
1782
1783                                 let mut res = KeysManager {
1784                                         secp_ctx,
1785                                         node_secret,
1786                                         node_id,
1787                                         inbound_payment_key: KeyMaterial(inbound_pmt_key_bytes),
1788
1789                                         destination_script,
1790                                         shutdown_pubkey,
1791
1792                                         channel_master_key,
1793                                         channel_child_index: AtomicUsize::new(0),
1794
1795                                         entropy_source: RandomBytes::new(rand_bytes_unique_start),
1796
1797                                         seed: *seed,
1798                                         starting_time_secs,
1799                                         starting_time_nanos,
1800                                 };
1801                                 let secp_seed = res.get_secure_random_bytes();
1802                                 res.secp_ctx.seeded_randomize(&secp_seed);
1803                                 res
1804                         },
1805                         Err(_) => panic!("Your rng is busted"),
1806                 }
1807         }
1808
1809         /// Gets the "node_id" secret key used to sign gossip announcements, decode onion data, etc.
1810         pub fn get_node_secret_key(&self) -> SecretKey {
1811                 self.node_secret
1812         }
1813
1814         /// Derive an old [`WriteableEcdsaChannelSigner`] containing per-channel secrets based on a key derivation parameters.
1815         pub fn derive_channel_keys(
1816                 &self, channel_value_satoshis: u64, params: &[u8; 32],
1817         ) -> InMemorySigner {
1818                 let chan_id = u64::from_be_bytes(params[0..8].try_into().unwrap());
1819                 let mut unique_start = Sha256::engine();
1820                 unique_start.input(params);
1821                 unique_start.input(&self.seed);
1822
1823                 // We only seriously intend to rely on the channel_master_key for true secure
1824                 // entropy, everything else just ensures uniqueness. We rely on the unique_start (ie
1825                 // starting_time provided in the constructor) to be unique.
1826                 let child_privkey = self
1827                         .channel_master_key
1828                         .ckd_priv(
1829                                 &self.secp_ctx,
1830                                 ChildNumber::from_hardened_idx((chan_id as u32) % (1 << 31))
1831                                         .expect("key space exhausted"),
1832                         )
1833                         .expect("Your RNG is busted");
1834                 unique_start.input(&child_privkey.private_key[..]);
1835
1836                 let seed = Sha256::from_engine(unique_start).to_byte_array();
1837
1838                 let commitment_seed = {
1839                         let mut sha = Sha256::engine();
1840                         sha.input(&seed);
1841                         sha.input(&b"commitment seed"[..]);
1842                         Sha256::from_engine(sha).to_byte_array()
1843                 };
1844                 macro_rules! key_step {
1845                         ($info: expr, $prev_key: expr) => {{
1846                                 let mut sha = Sha256::engine();
1847                                 sha.input(&seed);
1848                                 sha.input(&$prev_key[..]);
1849                                 sha.input(&$info[..]);
1850                                 SecretKey::from_slice(&Sha256::from_engine(sha).to_byte_array())
1851                                         .expect("SHA-256 is busted")
1852                         }};
1853                 }
1854                 let funding_key = key_step!(b"funding key", commitment_seed);
1855                 let revocation_base_key = key_step!(b"revocation base key", funding_key);
1856                 let payment_key = key_step!(b"payment key", revocation_base_key);
1857                 let delayed_payment_base_key = key_step!(b"delayed payment base key", payment_key);
1858                 let htlc_base_key = key_step!(b"HTLC base key", delayed_payment_base_key);
1859                 let prng_seed = self.get_secure_random_bytes();
1860
1861                 InMemorySigner::new(
1862                         &self.secp_ctx,
1863                         funding_key,
1864                         revocation_base_key,
1865                         payment_key,
1866                         delayed_payment_base_key,
1867                         htlc_base_key,
1868                         commitment_seed,
1869                         channel_value_satoshis,
1870                         params.clone(),
1871                         prng_seed,
1872                 )
1873         }
1874
1875         /// Signs the given [`PartiallySignedTransaction`] which spends the given [`SpendableOutputDescriptor`]s.
1876         /// The resulting inputs will be finalized and the PSBT will be ready for broadcast if there
1877         /// are no other inputs that need signing.
1878         ///
1879         /// Returns `Err(())` if the PSBT is missing a descriptor or if we fail to sign.
1880         ///
1881         /// May panic if the [`SpendableOutputDescriptor`]s were not generated by channels which used
1882         /// this [`KeysManager`] or one of the [`InMemorySigner`] created by this [`KeysManager`].
1883         pub fn sign_spendable_outputs_psbt<C: Signing>(
1884                 &self, descriptors: &[&SpendableOutputDescriptor], mut psbt: PartiallySignedTransaction,
1885                 secp_ctx: &Secp256k1<C>,
1886         ) -> Result<PartiallySignedTransaction, ()> {
1887                 let mut keys_cache: Option<(InMemorySigner, [u8; 32])> = None;
1888                 for outp in descriptors {
1889                         let get_input_idx = |outpoint: &OutPoint| {
1890                                 psbt.unsigned_tx
1891                                         .input
1892                                         .iter()
1893                                         .position(|i| i.previous_output == outpoint.into_bitcoin_outpoint())
1894                                         .ok_or(())
1895                         };
1896                         match outp {
1897                                 SpendableOutputDescriptor::StaticPaymentOutput(descriptor) => {
1898                                         let input_idx = get_input_idx(&descriptor.outpoint)?;
1899                                         if keys_cache.is_none()
1900                                                 || keys_cache.as_ref().unwrap().1 != descriptor.channel_keys_id
1901                                         {
1902                                                 let mut signer = self.derive_channel_keys(
1903                                                         descriptor.channel_value_satoshis,
1904                                                         &descriptor.channel_keys_id,
1905                                                 );
1906                                                 if let Some(channel_params) =
1907                                                         descriptor.channel_transaction_parameters.as_ref()
1908                                                 {
1909                                                         signer.provide_channel_parameters(channel_params);
1910                                                 }
1911                                                 keys_cache = Some((signer, descriptor.channel_keys_id));
1912                                         }
1913                                         let witness = keys_cache.as_ref().unwrap().0.sign_counterparty_payment_input(
1914                                                 &psbt.unsigned_tx,
1915                                                 input_idx,
1916                                                 &descriptor,
1917                                                 &secp_ctx,
1918                                         )?;
1919                                         psbt.inputs[input_idx].final_script_witness = Some(witness);
1920                                 },
1921                                 SpendableOutputDescriptor::DelayedPaymentOutput(descriptor) => {
1922                                         let input_idx = get_input_idx(&descriptor.outpoint)?;
1923                                         if keys_cache.is_none()
1924                                                 || keys_cache.as_ref().unwrap().1 != descriptor.channel_keys_id
1925                                         {
1926                                                 keys_cache = Some((
1927                                                         self.derive_channel_keys(
1928                                                                 descriptor.channel_value_satoshis,
1929                                                                 &descriptor.channel_keys_id,
1930                                                         ),
1931                                                         descriptor.channel_keys_id,
1932                                                 ));
1933                                         }
1934                                         let witness = keys_cache.as_ref().unwrap().0.sign_dynamic_p2wsh_input(
1935                                                 &psbt.unsigned_tx,
1936                                                 input_idx,
1937                                                 &descriptor,
1938                                                 &secp_ctx,
1939                                         )?;
1940                                         psbt.inputs[input_idx].final_script_witness = Some(witness);
1941                                 },
1942                                 SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output, .. } => {
1943                                         let input_idx = get_input_idx(outpoint)?;
1944                                         let derivation_idx =
1945                                                 if output.script_pubkey == self.destination_script { 1 } else { 2 };
1946                                         let secret = {
1947                                                 // Note that when we aren't serializing the key, network doesn't matter
1948                                                 match ExtendedPrivKey::new_master(Network::Testnet, &self.seed) {
1949                                                         Ok(master_key) => {
1950                                                                 match master_key.ckd_priv(
1951                                                                         &secp_ctx,
1952                                                                         ChildNumber::from_hardened_idx(derivation_idx)
1953                                                                                 .expect("key space exhausted"),
1954                                                                 ) {
1955                                                                         Ok(key) => key,
1956                                                                         Err(_) => panic!("Your RNG is busted"),
1957                                                                 }
1958                                                         },
1959                                                         Err(_) => panic!("Your rng is busted"),
1960                                                 }
1961                                         };
1962                                         let pubkey = ExtendedPubKey::from_priv(&secp_ctx, &secret).to_pub();
1963                                         if derivation_idx == 2 {
1964                                                 assert_eq!(pubkey.inner, self.shutdown_pubkey);
1965                                         }
1966                                         let witness_script =
1967                                                 bitcoin::Address::p2pkh(&pubkey, Network::Testnet).script_pubkey();
1968                                         let payment_script = bitcoin::Address::p2wpkh(&pubkey, Network::Testnet)
1969                                                 .expect("uncompressed key found")
1970                                                 .script_pubkey();
1971
1972                                         if payment_script != output.script_pubkey {
1973                                                 return Err(());
1974                                         };
1975
1976                                         let sighash = hash_to_message!(
1977                                                 &sighash::SighashCache::new(&psbt.unsigned_tx)
1978                                                         .segwit_signature_hash(
1979                                                                 input_idx,
1980                                                                 &witness_script,
1981                                                                 output.value,
1982                                                                 EcdsaSighashType::All
1983                                                         )
1984                                                         .unwrap()[..]
1985                                         );
1986                                         let sig = sign_with_aux_rand(secp_ctx, &sighash, &secret.private_key, &self);
1987                                         let mut sig_ser = sig.serialize_der().to_vec();
1988                                         sig_ser.push(EcdsaSighashType::All as u8);
1989                                         let witness =
1990                                                 Witness::from_slice(&[&sig_ser, &pubkey.inner.serialize().to_vec()]);
1991                                         psbt.inputs[input_idx].final_script_witness = Some(witness);
1992                                 },
1993                         }
1994                 }
1995
1996                 Ok(psbt)
1997         }
1998
1999         /// Creates a [`Transaction`] which spends the given descriptors to the given outputs, plus an
2000         /// output to the given change destination (if sufficient change value remains). The
2001         /// transaction will have a feerate, at least, of the given value.
2002         ///
2003         /// The `locktime` argument is used to set the transaction's locktime. If `None`, the
2004         /// transaction will have a locktime of 0. It it recommended to set this to the current block
2005         /// height to avoid fee sniping, unless you have some specific reason to use a different
2006         /// locktime.
2007         ///
2008         /// Returns `Err(())` if the output value is greater than the input value minus required fee,
2009         /// if a descriptor was duplicated, or if an output descriptor `script_pubkey`
2010         /// does not match the one we can spend.
2011         ///
2012         /// We do not enforce that outputs meet the dust limit or that any output scripts are standard.
2013         ///
2014         /// May panic if the [`SpendableOutputDescriptor`]s were not generated by channels which used
2015         /// this [`KeysManager`] or one of the [`InMemorySigner`] created by this [`KeysManager`].
2016         pub fn spend_spendable_outputs<C: Signing>(
2017                 &self, descriptors: &[&SpendableOutputDescriptor], outputs: Vec<TxOut>,
2018                 change_destination_script: ScriptBuf, feerate_sat_per_1000_weight: u32,
2019                 locktime: Option<LockTime>, secp_ctx: &Secp256k1<C>,
2020         ) -> Result<Transaction, ()> {
2021                 let (mut psbt, expected_max_weight) =
2022                         SpendableOutputDescriptor::create_spendable_outputs_psbt(
2023                                 descriptors,
2024                                 outputs,
2025                                 change_destination_script,
2026                                 feerate_sat_per_1000_weight,
2027                                 locktime,
2028                         )?;
2029                 psbt = self.sign_spendable_outputs_psbt(descriptors, psbt, secp_ctx)?;
2030
2031                 let spend_tx = psbt.extract_tx();
2032
2033                 debug_assert!(expected_max_weight >= spend_tx.weight().to_wu());
2034                 // Note that witnesses with a signature vary somewhat in size, so allow
2035                 // `expected_max_weight` to overshoot by up to 3 bytes per input.
2036                 debug_assert!(
2037                         expected_max_weight <= spend_tx.weight().to_wu() + descriptors.len() as u64 * 3
2038                 );
2039
2040                 Ok(spend_tx)
2041         }
2042 }
2043
2044 impl EntropySource for KeysManager {
2045         fn get_secure_random_bytes(&self) -> [u8; 32] {
2046                 self.entropy_source.get_secure_random_bytes()
2047         }
2048 }
2049
2050 impl NodeSigner for KeysManager {
2051         fn get_node_id(&self, recipient: Recipient) -> Result<PublicKey, ()> {
2052                 match recipient {
2053                         Recipient::Node => Ok(self.node_id.clone()),
2054                         Recipient::PhantomNode => Err(()),
2055                 }
2056         }
2057
2058         fn ecdh(
2059                 &self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&Scalar>,
2060         ) -> Result<SharedSecret, ()> {
2061                 let mut node_secret = match recipient {
2062                         Recipient::Node => Ok(self.node_secret.clone()),
2063                         Recipient::PhantomNode => Err(()),
2064                 }?;
2065                 if let Some(tweak) = tweak {
2066                         node_secret = node_secret.mul_tweak(tweak).map_err(|_| ())?;
2067                 }
2068                 Ok(SharedSecret::new(other_key, &node_secret))
2069         }
2070
2071         fn get_inbound_payment_key_material(&self) -> KeyMaterial {
2072                 self.inbound_payment_key.clone()
2073         }
2074
2075         fn sign_invoice(
2076                 &self, hrp_bytes: &[u8], invoice_data: &[u5], recipient: Recipient,
2077         ) -> Result<RecoverableSignature, ()> {
2078                 let preimage = construct_invoice_preimage(&hrp_bytes, &invoice_data);
2079                 let secret = match recipient {
2080                         Recipient::Node => Ok(&self.node_secret),
2081                         Recipient::PhantomNode => Err(()),
2082                 }?;
2083                 Ok(self.secp_ctx.sign_ecdsa_recoverable(
2084                         &hash_to_message!(&Sha256::hash(&preimage).to_byte_array()),
2085                         secret,
2086                 ))
2087         }
2088
2089         fn sign_bolt12_invoice_request(
2090                 &self, invoice_request: &UnsignedInvoiceRequest,
2091         ) -> Result<schnorr::Signature, ()> {
2092                 let message = invoice_request.tagged_hash().as_digest();
2093                 let keys = KeyPair::from_secret_key(&self.secp_ctx, &self.node_secret);
2094                 let aux_rand = self.get_secure_random_bytes();
2095                 Ok(self.secp_ctx.sign_schnorr_with_aux_rand(message, &keys, &aux_rand))
2096         }
2097
2098         fn sign_bolt12_invoice(
2099                 &self, invoice: &UnsignedBolt12Invoice,
2100         ) -> Result<schnorr::Signature, ()> {
2101                 let message = invoice.tagged_hash().as_digest();
2102                 let keys = KeyPair::from_secret_key(&self.secp_ctx, &self.node_secret);
2103                 let aux_rand = self.get_secure_random_bytes();
2104                 Ok(self.secp_ctx.sign_schnorr_with_aux_rand(message, &keys, &aux_rand))
2105         }
2106
2107         fn sign_gossip_message(&self, msg: UnsignedGossipMessage) -> Result<Signature, ()> {
2108                 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.encode()[..])[..]);
2109                 Ok(self.secp_ctx.sign_ecdsa(&msg_hash, &self.node_secret))
2110         }
2111 }
2112
2113 impl SignerProvider for KeysManager {
2114         type EcdsaSigner = InMemorySigner;
2115         #[cfg(taproot)]
2116         type TaprootSigner = InMemorySigner;
2117
2118         fn generate_channel_keys_id(
2119                 &self, _inbound: bool, _channel_value_satoshis: u64, user_channel_id: u128,
2120         ) -> [u8; 32] {
2121                 let child_idx = self.channel_child_index.fetch_add(1, Ordering::AcqRel);
2122                 // `child_idx` is the only thing guaranteed to make each channel unique without a restart
2123                 // (though `user_channel_id` should help, depending on user behavior). If it manages to
2124                 // roll over, we may generate duplicate keys for two different channels, which could result
2125                 // in loss of funds. Because we only support 32-bit+ systems, assert that our `AtomicUsize`
2126                 // doesn't reach `u32::MAX`.
2127                 assert!(child_idx < core::u32::MAX as usize, "2^32 channels opened without restart");
2128                 let mut id = [0; 32];
2129                 id[0..4].copy_from_slice(&(child_idx as u32).to_be_bytes());
2130                 id[4..8].copy_from_slice(&self.starting_time_nanos.to_be_bytes());
2131                 id[8..16].copy_from_slice(&self.starting_time_secs.to_be_bytes());
2132                 id[16..32].copy_from_slice(&user_channel_id.to_be_bytes());
2133                 id
2134         }
2135
2136         fn derive_channel_signer(
2137                 &self, channel_value_satoshis: u64, channel_keys_id: [u8; 32],
2138         ) -> Self::EcdsaSigner {
2139                 self.derive_channel_keys(channel_value_satoshis, &channel_keys_id)
2140         }
2141
2142         fn read_chan_signer(&self, reader: &[u8]) -> Result<Self::EcdsaSigner, DecodeError> {
2143                 InMemorySigner::read(&mut io::Cursor::new(reader), self)
2144         }
2145
2146         fn get_destination_script(&self, _channel_keys_id: [u8; 32]) -> Result<ScriptBuf, ()> {
2147                 Ok(self.destination_script.clone())
2148         }
2149
2150         fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()> {
2151                 Ok(ShutdownScript::new_p2wpkh_from_pubkey(self.shutdown_pubkey.clone()))
2152         }
2153 }
2154
2155 /// Similar to [`KeysManager`], but allows the node using this struct to receive phantom node
2156 /// payments.
2157 ///
2158 /// A phantom node payment is a payment made to a phantom invoice, which is an invoice that can be
2159 /// paid to one of multiple nodes. This works because we encode the invoice route hints such that
2160 /// LDK will recognize an incoming payment as destined for a phantom node, and collect the payment
2161 /// itself without ever needing to forward to this fake node.
2162 ///
2163 /// Phantom node payments are useful for load balancing between multiple LDK nodes. They also
2164 /// provide some fault tolerance, because payers will automatically retry paying other provided
2165 /// nodes in the case that one node goes down.
2166 ///
2167 /// Note that multi-path payments are not supported in phantom invoices for security reasons.
2168 // In the hypothetical case that we did support MPP phantom payments, there would be no way for
2169 // nodes to know when the full payment has been received (and the preimage can be released) without
2170 // significantly compromising on our safety guarantees. I.e., if we expose the ability for the user
2171 // to tell LDK when the preimage can be released, we open ourselves to attacks where the preimage
2172 // is released too early.
2173 //
2174 /// Switching between this struct and [`KeysManager`] will invalidate any previously issued
2175 /// invoices and attempts to pay previous invoices will fail.
2176 pub struct PhantomKeysManager {
2177         inner: KeysManager,
2178         inbound_payment_key: KeyMaterial,
2179         phantom_secret: SecretKey,
2180         phantom_node_id: PublicKey,
2181 }
2182
2183 impl EntropySource for PhantomKeysManager {
2184         fn get_secure_random_bytes(&self) -> [u8; 32] {
2185                 self.inner.get_secure_random_bytes()
2186         }
2187 }
2188
2189 impl NodeSigner for PhantomKeysManager {
2190         fn get_node_id(&self, recipient: Recipient) -> Result<PublicKey, ()> {
2191                 match recipient {
2192                         Recipient::Node => self.inner.get_node_id(Recipient::Node),
2193                         Recipient::PhantomNode => Ok(self.phantom_node_id.clone()),
2194                 }
2195         }
2196
2197         fn ecdh(
2198                 &self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&Scalar>,
2199         ) -> Result<SharedSecret, ()> {
2200                 let mut node_secret = match recipient {
2201                         Recipient::Node => self.inner.node_secret.clone(),
2202                         Recipient::PhantomNode => self.phantom_secret.clone(),
2203                 };
2204                 if let Some(tweak) = tweak {
2205                         node_secret = node_secret.mul_tweak(tweak).map_err(|_| ())?;
2206                 }
2207                 Ok(SharedSecret::new(other_key, &node_secret))
2208         }
2209
2210         fn get_inbound_payment_key_material(&self) -> KeyMaterial {
2211                 self.inbound_payment_key.clone()
2212         }
2213
2214         fn sign_invoice(
2215                 &self, hrp_bytes: &[u8], invoice_data: &[u5], recipient: Recipient,
2216         ) -> Result<RecoverableSignature, ()> {
2217                 let preimage = construct_invoice_preimage(&hrp_bytes, &invoice_data);
2218                 let secret = match recipient {
2219                         Recipient::Node => &self.inner.node_secret,
2220                         Recipient::PhantomNode => &self.phantom_secret,
2221                 };
2222                 Ok(self.inner.secp_ctx.sign_ecdsa_recoverable(
2223                         &hash_to_message!(&Sha256::hash(&preimage).to_byte_array()),
2224                         secret,
2225                 ))
2226         }
2227
2228         fn sign_bolt12_invoice_request(
2229                 &self, invoice_request: &UnsignedInvoiceRequest,
2230         ) -> Result<schnorr::Signature, ()> {
2231                 self.inner.sign_bolt12_invoice_request(invoice_request)
2232         }
2233
2234         fn sign_bolt12_invoice(
2235                 &self, invoice: &UnsignedBolt12Invoice,
2236         ) -> Result<schnorr::Signature, ()> {
2237                 self.inner.sign_bolt12_invoice(invoice)
2238         }
2239
2240         fn sign_gossip_message(&self, msg: UnsignedGossipMessage) -> Result<Signature, ()> {
2241                 self.inner.sign_gossip_message(msg)
2242         }
2243 }
2244
2245 impl SignerProvider for PhantomKeysManager {
2246         type EcdsaSigner = InMemorySigner;
2247         #[cfg(taproot)]
2248         type TaprootSigner = InMemorySigner;
2249
2250         fn generate_channel_keys_id(
2251                 &self, inbound: bool, channel_value_satoshis: u64, user_channel_id: u128,
2252         ) -> [u8; 32] {
2253                 self.inner.generate_channel_keys_id(inbound, channel_value_satoshis, user_channel_id)
2254         }
2255
2256         fn derive_channel_signer(
2257                 &self, channel_value_satoshis: u64, channel_keys_id: [u8; 32],
2258         ) -> Self::EcdsaSigner {
2259                 self.inner.derive_channel_signer(channel_value_satoshis, channel_keys_id)
2260         }
2261
2262         fn read_chan_signer(&self, reader: &[u8]) -> Result<Self::EcdsaSigner, DecodeError> {
2263                 self.inner.read_chan_signer(reader)
2264         }
2265
2266         fn get_destination_script(&self, channel_keys_id: [u8; 32]) -> Result<ScriptBuf, ()> {
2267                 self.inner.get_destination_script(channel_keys_id)
2268         }
2269
2270         fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()> {
2271                 self.inner.get_shutdown_scriptpubkey()
2272         }
2273 }
2274
2275 impl PhantomKeysManager {
2276         /// Constructs a [`PhantomKeysManager`] given a 32-byte seed and an additional `cross_node_seed`
2277         /// that is shared across all nodes that intend to participate in [phantom node payments]
2278         /// together.
2279         ///
2280         /// See [`KeysManager::new`] for more information on `seed`, `starting_time_secs`, and
2281         /// `starting_time_nanos`.
2282         ///
2283         /// `cross_node_seed` must be the same across all phantom payment-receiving nodes and also the
2284         /// same across restarts, or else inbound payments may fail.
2285         ///
2286         /// [phantom node payments]: PhantomKeysManager
2287         pub fn new(
2288                 seed: &[u8; 32], starting_time_secs: u64, starting_time_nanos: u32,
2289                 cross_node_seed: &[u8; 32],
2290         ) -> Self {
2291                 let inner = KeysManager::new(seed, starting_time_secs, starting_time_nanos);
2292                 let (inbound_key, phantom_key) = hkdf_extract_expand_twice(
2293                         b"LDK Inbound and Phantom Payment Key Expansion",
2294                         cross_node_seed,
2295                 );
2296                 let phantom_secret = SecretKey::from_slice(&phantom_key).unwrap();
2297                 let phantom_node_id = PublicKey::from_secret_key(&inner.secp_ctx, &phantom_secret);
2298                 Self {
2299                         inner,
2300                         inbound_payment_key: KeyMaterial(inbound_key),
2301                         phantom_secret,
2302                         phantom_node_id,
2303                 }
2304         }
2305
2306         /// See [`KeysManager::spend_spendable_outputs`] for documentation on this method.
2307         pub fn spend_spendable_outputs<C: Signing>(
2308                 &self, descriptors: &[&SpendableOutputDescriptor], outputs: Vec<TxOut>,
2309                 change_destination_script: ScriptBuf, feerate_sat_per_1000_weight: u32,
2310                 locktime: Option<LockTime>, secp_ctx: &Secp256k1<C>,
2311         ) -> Result<Transaction, ()> {
2312                 self.inner.spend_spendable_outputs(
2313                         descriptors,
2314                         outputs,
2315                         change_destination_script,
2316                         feerate_sat_per_1000_weight,
2317                         locktime,
2318                         secp_ctx,
2319                 )
2320         }
2321
2322         /// See [`KeysManager::derive_channel_keys`] for documentation on this method.
2323         pub fn derive_channel_keys(
2324                 &self, channel_value_satoshis: u64, params: &[u8; 32],
2325         ) -> InMemorySigner {
2326                 self.inner.derive_channel_keys(channel_value_satoshis, params)
2327         }
2328
2329         /// Gets the "node_id" secret key used to sign gossip announcements, decode onion data, etc.
2330         pub fn get_node_secret_key(&self) -> SecretKey {
2331                 self.inner.get_node_secret_key()
2332         }
2333
2334         /// Gets the "node_id" secret key of the phantom node used to sign invoices, decode the
2335         /// last-hop onion data, etc.
2336         pub fn get_phantom_node_secret_key(&self) -> SecretKey {
2337                 self.phantom_secret
2338         }
2339 }
2340
2341 /// An implementation of [`EntropySource`] using ChaCha20.
2342 #[derive(Debug)]
2343 pub struct RandomBytes {
2344         /// Seed from which all randomness produced is derived from.
2345         seed: [u8; 32],
2346         /// Tracks the number of times we've produced randomness to ensure we don't return the same
2347         /// bytes twice.
2348         index: AtomicCounter,
2349 }
2350
2351 impl RandomBytes {
2352         /// Creates a new instance using the given seed.
2353         pub fn new(seed: [u8; 32]) -> Self {
2354                 Self { seed, index: AtomicCounter::new() }
2355         }
2356 }
2357
2358 impl EntropySource for RandomBytes {
2359         fn get_secure_random_bytes(&self) -> [u8; 32] {
2360                 let index = self.index.get_increment();
2361                 let mut nonce = [0u8; 16];
2362                 nonce[..8].copy_from_slice(&index.to_be_bytes());
2363                 ChaCha20::get_single_block(&self.seed, &nonce)
2364         }
2365 }
2366
2367 // Ensure that EcdsaChannelSigner can have a vtable
2368 #[test]
2369 pub fn dyn_sign() {
2370         let _signer: Box<dyn EcdsaChannelSigner>;
2371 }
2372
2373 #[cfg(ldk_bench)]
2374 pub mod benches {
2375         use crate::sign::{EntropySource, KeysManager};
2376         use bitcoin::blockdata::constants::genesis_block;
2377         use bitcoin::Network;
2378         use std::sync::mpsc::TryRecvError;
2379         use std::sync::{mpsc, Arc};
2380         use std::thread;
2381         use std::time::Duration;
2382
2383         use criterion::Criterion;
2384
2385         pub fn bench_get_secure_random_bytes(bench: &mut Criterion) {
2386                 let seed = [0u8; 32];
2387                 let now = Duration::from_secs(genesis_block(Network::Testnet).header.time as u64);
2388                 let keys_manager = Arc::new(KeysManager::new(&seed, now.as_secs(), now.subsec_micros()));
2389
2390                 let mut handles = Vec::new();
2391                 let mut stops = Vec::new();
2392                 for _ in 1..5 {
2393                         let keys_manager_clone = Arc::clone(&keys_manager);
2394                         let (stop_sender, stop_receiver) = mpsc::channel();
2395                         let handle = thread::spawn(move || loop {
2396                                 keys_manager_clone.get_secure_random_bytes();
2397                                 match stop_receiver.try_recv() {
2398                                         Ok(_) | Err(TryRecvError::Disconnected) => {
2399                                                 println!("Terminating.");
2400                                                 break;
2401                                         },
2402                                         Err(TryRecvError::Empty) => {},
2403                                 }
2404                         });
2405                         handles.push(handle);
2406                         stops.push(stop_sender);
2407                 }
2408
2409                 bench.bench_function("get_secure_random_bytes", |b| {
2410                         b.iter(|| keys_manager.get_secure_random_bytes())
2411                 });
2412
2413                 for stop in stops {
2414                         let _ = stop.send(());
2415                 }
2416                 for handle in handles {
2417                         handle.join().unwrap();
2418                 }
2419         }
2420 }