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