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