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