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