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