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