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