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