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