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