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