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