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