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