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