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