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