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