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