]> git.bitcoin.ninja Git - rust-lightning/blob - lightning/src/chain/keysinterface.rs
Persist scorer upon update based on event handling
[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         /// This method should return a different value each time it is called, to avoid linking
547         /// on-chain funds across channels as controlled to the same user.
548         fn get_destination_script(&self) -> Script;
549
550         /// Get a script pubkey which we will send funds to when closing a channel.
551         ///
552         /// This method should return a different value each time it is called, to avoid linking
553         /// on-chain funds across channels as controlled to the same user.
554         fn get_shutdown_scriptpubkey(&self) -> ShutdownScript;
555 }
556
557 /// A simple implementation of [`WriteableEcdsaChannelSigner`] that just keeps the private keys in memory.
558 ///
559 /// This implementation performs no policy checks and is insufficient by itself as
560 /// a secure external signer.
561 pub struct InMemorySigner {
562         /// Holder secret key in the 2-of-2 multisig script of a channel. This key also backs the
563         /// holder's anchor output in a commitment transaction, if one is present.
564         pub funding_key: SecretKey,
565         /// Holder secret key for blinded revocation pubkey.
566         pub revocation_base_key: SecretKey,
567         /// Holder secret key used for our balance in counterparty-broadcasted commitment transactions.
568         pub payment_key: SecretKey,
569         /// Holder secret key used in an HTLC transaction.
570         pub delayed_payment_base_key: SecretKey,
571         /// Holder HTLC secret key used in commitment transaction HTLC outputs.
572         pub htlc_base_key: SecretKey,
573         /// Commitment seed.
574         pub commitment_seed: [u8; 32],
575         /// Holder public keys and basepoints.
576         pub(crate) holder_channel_pubkeys: ChannelPublicKeys,
577         /// Counterparty public keys and counterparty/holder `selected_contest_delay`, populated on channel acceptance.
578         channel_parameters: Option<ChannelTransactionParameters>,
579         /// The total value of this channel.
580         channel_value_satoshis: u64,
581         /// Key derivation parameters.
582         channel_keys_id: [u8; 32],
583         /// Seed from which all randomness produced is derived from.
584         rand_bytes_unique_start: [u8; 32],
585         /// Tracks the number of times we've produced randomness to ensure we don't return the same
586         /// bytes twice.
587         rand_bytes_index: AtomicCounter,
588 }
589
590 impl Clone for InMemorySigner {
591         fn clone(&self) -> Self {
592                 Self {
593                         funding_key: self.funding_key.clone(),
594                         revocation_base_key: self.revocation_base_key.clone(),
595                         payment_key: self.payment_key.clone(),
596                         delayed_payment_base_key: self.delayed_payment_base_key.clone(),
597                         htlc_base_key: self.htlc_base_key.clone(),
598                         commitment_seed: self.commitment_seed.clone(),
599                         holder_channel_pubkeys: self.holder_channel_pubkeys.clone(),
600                         channel_parameters: self.channel_parameters.clone(),
601                         channel_value_satoshis: self.channel_value_satoshis,
602                         channel_keys_id: self.channel_keys_id,
603                         rand_bytes_unique_start: self.get_secure_random_bytes(),
604                         rand_bytes_index: AtomicCounter::new(),
605                 }
606         }
607 }
608
609 impl InMemorySigner {
610         /// Creates a new [`InMemorySigner`].
611         pub fn new<C: Signing>(
612                 secp_ctx: &Secp256k1<C>,
613                 funding_key: SecretKey,
614                 revocation_base_key: SecretKey,
615                 payment_key: SecretKey,
616                 delayed_payment_base_key: SecretKey,
617                 htlc_base_key: SecretKey,
618                 commitment_seed: [u8; 32],
619                 channel_value_satoshis: u64,
620                 channel_keys_id: [u8; 32],
621                 rand_bytes_unique_start: [u8; 32],
622         ) -> InMemorySigner {
623                 let holder_channel_pubkeys =
624                         InMemorySigner::make_holder_keys(secp_ctx, &funding_key, &revocation_base_key,
625                                 &payment_key, &delayed_payment_base_key,
626                                 &htlc_base_key);
627                 InMemorySigner {
628                         funding_key,
629                         revocation_base_key,
630                         payment_key,
631                         delayed_payment_base_key,
632                         htlc_base_key,
633                         commitment_seed,
634                         channel_value_satoshis,
635                         holder_channel_pubkeys,
636                         channel_parameters: None,
637                         channel_keys_id,
638                         rand_bytes_unique_start,
639                         rand_bytes_index: AtomicCounter::new(),
640                 }
641         }
642
643         fn make_holder_keys<C: Signing>(secp_ctx: &Secp256k1<C>,
644                         funding_key: &SecretKey,
645                         revocation_base_key: &SecretKey,
646                         payment_key: &SecretKey,
647                         delayed_payment_base_key: &SecretKey,
648                         htlc_base_key: &SecretKey) -> ChannelPublicKeys {
649                 let from_secret = |s: &SecretKey| PublicKey::from_secret_key(secp_ctx, s);
650                 ChannelPublicKeys {
651                         funding_pubkey: from_secret(&funding_key),
652                         revocation_basepoint: from_secret(&revocation_base_key),
653                         payment_point: from_secret(&payment_key),
654                         delayed_payment_basepoint: from_secret(&delayed_payment_base_key),
655                         htlc_basepoint: from_secret(&htlc_base_key),
656                 }
657         }
658
659         /// Returns the counterparty's pubkeys.
660         ///
661         /// Will panic if [`ChannelSigner::provide_channel_parameters`] has not been called before.
662         pub fn counterparty_pubkeys(&self) -> &ChannelPublicKeys { &self.get_channel_parameters().counterparty_parameters.as_ref().unwrap().pubkeys }
663         /// Returns the `contest_delay` value specified by our counterparty and applied on holder-broadcastable
664         /// transactions, i.e., the amount of time that we have to wait to recover our funds if we
665         /// broadcast a transaction.
666         ///
667         /// Will panic if [`ChannelSigner::provide_channel_parameters`] has not been called before.
668         pub fn counterparty_selected_contest_delay(&self) -> u16 { self.get_channel_parameters().counterparty_parameters.as_ref().unwrap().selected_contest_delay }
669         /// Returns the `contest_delay` value specified by us and applied on transactions broadcastable
670         /// by our counterparty, i.e., the amount of time that they have to wait to recover their funds
671         /// if they broadcast a transaction.
672         ///
673         /// Will panic if [`ChannelSigner::provide_channel_parameters`] has not been called before.
674         pub fn holder_selected_contest_delay(&self) -> u16 { self.get_channel_parameters().holder_selected_contest_delay }
675         /// Returns whether the holder is the initiator.
676         ///
677         /// Will panic if [`ChannelSigner::provide_channel_parameters`] has not been called before.
678         pub fn is_outbound(&self) -> bool { self.get_channel_parameters().is_outbound_from_holder }
679         /// Funding outpoint
680         ///
681         /// Will panic if [`ChannelSigner::provide_channel_parameters`] has not been called before.
682         pub fn funding_outpoint(&self) -> &OutPoint { self.get_channel_parameters().funding_outpoint.as_ref().unwrap() }
683         /// Returns a [`ChannelTransactionParameters`] for this channel, to be used when verifying or
684         /// building transactions.
685         ///
686         /// Will panic if [`ChannelSigner::provide_channel_parameters`] has not been called before.
687         pub fn get_channel_parameters(&self) -> &ChannelTransactionParameters {
688                 self.channel_parameters.as_ref().unwrap()
689         }
690         /// Returns whether anchors should be used.
691         ///
692         /// Will panic if [`ChannelSigner::provide_channel_parameters`] has not been called before.
693         pub fn opt_anchors(&self) -> bool {
694                 self.get_channel_parameters().opt_anchors.is_some()
695         }
696         /// Sign the single input of `spend_tx` at index `input_idx`, which spends the output described
697         /// by `descriptor`, returning the witness stack for the input.
698         ///
699         /// Returns an error if the input at `input_idx` does not exist, has a non-empty `script_sig`,
700         /// is not spending the outpoint described by [`descriptor.outpoint`],
701         /// or if an output descriptor `script_pubkey` does not match the one we can spend.
702         ///
703         /// [`descriptor.outpoint`]: StaticPaymentOutputDescriptor::outpoint
704         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>>, ()> {
705                 // TODO: We really should be taking the SigHashCache as a parameter here instead of
706                 // spend_tx, but ideally the SigHashCache would expose the transaction's inputs read-only
707                 // so that we can check them. This requires upstream rust-bitcoin changes (as well as
708                 // bindings updates to support SigHashCache objects).
709                 if spend_tx.input.len() <= input_idx { return Err(()); }
710                 if !spend_tx.input[input_idx].script_sig.is_empty() { return Err(()); }
711                 if spend_tx.input[input_idx].previous_output != descriptor.outpoint.into_bitcoin_outpoint() { return Err(()); }
712
713                 let remotepubkey = self.pubkeys().payment_point;
714                 let witness_script = bitcoin::Address::p2pkh(&::bitcoin::PublicKey{compressed: true, inner: remotepubkey}, Network::Testnet).script_pubkey();
715                 let sighash = hash_to_message!(&sighash::SighashCache::new(spend_tx).segwit_signature_hash(input_idx, &witness_script, descriptor.output.value, EcdsaSighashType::All).unwrap()[..]);
716                 let remotesig = sign_with_aux_rand(secp_ctx, &sighash, &self.payment_key, &self);
717                 let payment_script = bitcoin::Address::p2wpkh(&::bitcoin::PublicKey{compressed: true, inner: remotepubkey}, Network::Bitcoin).unwrap().script_pubkey();
718
719                 if payment_script != descriptor.output.script_pubkey { return Err(()); }
720
721                 let mut witness = Vec::with_capacity(2);
722                 witness.push(remotesig.serialize_der().to_vec());
723                 witness[0].push(EcdsaSighashType::All as u8);
724                 witness.push(remotepubkey.serialize().to_vec());
725                 Ok(witness)
726         }
727
728         /// Sign the single input of `spend_tx` at index `input_idx` which spends the output
729         /// described by `descriptor`, returning the witness stack for the input.
730         ///
731         /// Returns an error if the input at `input_idx` does not exist, has a non-empty `script_sig`,
732         /// is not spending the outpoint described by [`descriptor.outpoint`], does not have a
733         /// sequence set to [`descriptor.to_self_delay`], or if an output descriptor
734         /// `script_pubkey` does not match the one we can spend.
735         ///
736         /// [`descriptor.outpoint`]: DelayedPaymentOutputDescriptor::outpoint
737         /// [`descriptor.to_self_delay`]: DelayedPaymentOutputDescriptor::to_self_delay
738         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>>, ()> {
739                 // TODO: We really should be taking the SigHashCache as a parameter here instead of
740                 // spend_tx, but ideally the SigHashCache would expose the transaction's inputs read-only
741                 // so that we can check them. This requires upstream rust-bitcoin changes (as well as
742                 // bindings updates to support SigHashCache objects).
743                 if spend_tx.input.len() <= input_idx { return Err(()); }
744                 if !spend_tx.input[input_idx].script_sig.is_empty() { return Err(()); }
745                 if spend_tx.input[input_idx].previous_output != descriptor.outpoint.into_bitcoin_outpoint() { return Err(()); }
746                 if spend_tx.input[input_idx].sequence.0 != descriptor.to_self_delay as u32 { return Err(()); }
747
748                 let delayed_payment_key = chan_utils::derive_private_key(&secp_ctx, &descriptor.per_commitment_point, &self.delayed_payment_base_key);
749                 let delayed_payment_pubkey = PublicKey::from_secret_key(&secp_ctx, &delayed_payment_key);
750                 let witness_script = chan_utils::get_revokeable_redeemscript(&descriptor.revocation_pubkey, descriptor.to_self_delay, &delayed_payment_pubkey);
751                 let sighash = hash_to_message!(&sighash::SighashCache::new(spend_tx).segwit_signature_hash(input_idx, &witness_script, descriptor.output.value, EcdsaSighashType::All).unwrap()[..]);
752                 let local_delayedsig = sign_with_aux_rand(secp_ctx, &sighash, &delayed_payment_key, &self);
753                 let payment_script = bitcoin::Address::p2wsh(&witness_script, Network::Bitcoin).script_pubkey();
754
755                 if descriptor.output.script_pubkey != payment_script { return Err(()); }
756
757                 let mut witness = Vec::with_capacity(3);
758                 witness.push(local_delayedsig.serialize_der().to_vec());
759                 witness[0].push(EcdsaSighashType::All as u8);
760                 witness.push(vec!()); //MINIMALIF
761                 witness.push(witness_script.clone().into_bytes());
762                 Ok(witness)
763         }
764 }
765
766 impl EntropySource for InMemorySigner {
767         fn get_secure_random_bytes(&self) -> [u8; 32] {
768                 let index = self.rand_bytes_index.get_increment();
769                 let mut nonce = [0u8; 16];
770                 nonce[..8].copy_from_slice(&index.to_be_bytes());
771                 ChaCha20::get_single_block(&self.rand_bytes_unique_start, &nonce)
772         }
773 }
774
775 impl ChannelSigner for InMemorySigner {
776         fn get_per_commitment_point(&self, idx: u64, secp_ctx: &Secp256k1<secp256k1::All>) -> PublicKey {
777                 let commitment_secret = SecretKey::from_slice(&chan_utils::build_commitment_secret(&self.commitment_seed, idx)).unwrap();
778                 PublicKey::from_secret_key(secp_ctx, &commitment_secret)
779         }
780
781         fn release_commitment_secret(&self, idx: u64) -> [u8; 32] {
782                 chan_utils::build_commitment_secret(&self.commitment_seed, idx)
783         }
784
785         fn validate_holder_commitment(&self, _holder_tx: &HolderCommitmentTransaction, _preimages: Vec<PaymentPreimage>) -> Result<(), ()> {
786                 Ok(())
787         }
788
789         fn pubkeys(&self) -> &ChannelPublicKeys { &self.holder_channel_pubkeys }
790
791         fn channel_keys_id(&self) -> [u8; 32] { self.channel_keys_id }
792
793         fn provide_channel_parameters(&mut self, channel_parameters: &ChannelTransactionParameters) {
794                 assert!(self.channel_parameters.is_none() || self.channel_parameters.as_ref().unwrap() == channel_parameters);
795                 if self.channel_parameters.is_some() {
796                         // The channel parameters were already set and they match, return early.
797                         return;
798                 }
799                 assert!(channel_parameters.is_populated(), "Channel parameters must be fully populated");
800                 self.channel_parameters = Some(channel_parameters.clone());
801         }
802 }
803
804 impl EcdsaChannelSigner for InMemorySigner {
805         fn sign_counterparty_commitment(&self, commitment_tx: &CommitmentTransaction, _preimages: Vec<PaymentPreimage>, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<(Signature, Vec<Signature>), ()> {
806                 let trusted_tx = commitment_tx.trust();
807                 let keys = trusted_tx.keys();
808
809                 let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
810                 let channel_funding_redeemscript = make_funding_redeemscript(&funding_pubkey, &self.counterparty_pubkeys().funding_pubkey);
811
812                 let built_tx = trusted_tx.built_transaction();
813                 let commitment_sig = built_tx.sign_counterparty_commitment(&self.funding_key, &channel_funding_redeemscript, self.channel_value_satoshis, secp_ctx);
814                 let commitment_txid = built_tx.txid;
815
816                 let mut htlc_sigs = Vec::with_capacity(commitment_tx.htlcs().len());
817                 for htlc in commitment_tx.htlcs() {
818                         let channel_parameters = self.get_channel_parameters();
819                         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);
820                         let htlc_redeemscript = chan_utils::get_htlc_redeemscript(&htlc, self.opt_anchors(), &keys);
821                         let htlc_sighashtype = if self.opt_anchors() { EcdsaSighashType::SinglePlusAnyoneCanPay } else { EcdsaSighashType::All };
822                         let htlc_sighash = hash_to_message!(&sighash::SighashCache::new(&htlc_tx).segwit_signature_hash(0, &htlc_redeemscript, htlc.amount_msat / 1000, htlc_sighashtype).unwrap()[..]);
823                         let holder_htlc_key = chan_utils::derive_private_key(&secp_ctx, &keys.per_commitment_point, &self.htlc_base_key);
824                         htlc_sigs.push(sign(secp_ctx, &htlc_sighash, &holder_htlc_key));
825                 }
826
827                 Ok((commitment_sig, htlc_sigs))
828         }
829
830         fn validate_counterparty_revocation(&self, _idx: u64, _secret: &SecretKey) -> Result<(), ()> {
831                 Ok(())
832         }
833
834         fn sign_holder_commitment_and_htlcs(&self, commitment_tx: &HolderCommitmentTransaction, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<(Signature, Vec<Signature>), ()> {
835                 let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
836                 let funding_redeemscript = make_funding_redeemscript(&funding_pubkey, &self.counterparty_pubkeys().funding_pubkey);
837                 let trusted_tx = commitment_tx.trust();
838                 let sig = trusted_tx.built_transaction().sign_holder_commitment(&self.funding_key, &funding_redeemscript, self.channel_value_satoshis, &self, secp_ctx);
839                 let channel_parameters = self.get_channel_parameters();
840                 let htlc_sigs = trusted_tx.get_htlc_sigs(&self.htlc_base_key, &channel_parameters.as_holder_broadcastable(), &self, secp_ctx)?;
841                 Ok((sig, htlc_sigs))
842         }
843
844         #[cfg(any(test,feature = "unsafe_revoked_tx_signing"))]
845         fn unsafe_sign_holder_commitment_and_htlcs(&self, commitment_tx: &HolderCommitmentTransaction, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<(Signature, Vec<Signature>), ()> {
846                 let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
847                 let funding_redeemscript = make_funding_redeemscript(&funding_pubkey, &self.counterparty_pubkeys().funding_pubkey);
848                 let trusted_tx = commitment_tx.trust();
849                 let sig = trusted_tx.built_transaction().sign_holder_commitment(&self.funding_key, &funding_redeemscript, self.channel_value_satoshis, &self, secp_ctx);
850                 let channel_parameters = self.get_channel_parameters();
851                 let htlc_sigs = trusted_tx.get_htlc_sigs(&self.htlc_base_key, &channel_parameters.as_holder_broadcastable(), &self, secp_ctx)?;
852                 Ok((sig, htlc_sigs))
853         }
854
855         fn sign_justice_revoked_output(&self, justice_tx: &Transaction, input: usize, amount: u64, per_commitment_key: &SecretKey, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<Signature, ()> {
856                 let revocation_key = chan_utils::derive_private_revocation_key(&secp_ctx, &per_commitment_key, &self.revocation_base_key);
857                 let per_commitment_point = PublicKey::from_secret_key(secp_ctx, &per_commitment_key);
858                 let revocation_pubkey = chan_utils::derive_public_revocation_key(&secp_ctx, &per_commitment_point, &self.pubkeys().revocation_basepoint);
859                 let witness_script = {
860                         let counterparty_delayedpubkey = chan_utils::derive_public_key(&secp_ctx, &per_commitment_point, &self.counterparty_pubkeys().delayed_payment_basepoint);
861                         chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.holder_selected_contest_delay(), &counterparty_delayedpubkey)
862                 };
863                 let mut sighash_parts = sighash::SighashCache::new(justice_tx);
864                 let sighash = hash_to_message!(&sighash_parts.segwit_signature_hash(input, &witness_script, amount, EcdsaSighashType::All).unwrap()[..]);
865                 return Ok(sign_with_aux_rand(secp_ctx, &sighash, &revocation_key, &self))
866         }
867
868         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, ()> {
869                 let revocation_key = chan_utils::derive_private_revocation_key(&secp_ctx, &per_commitment_key, &self.revocation_base_key);
870                 let per_commitment_point = PublicKey::from_secret_key(secp_ctx, &per_commitment_key);
871                 let revocation_pubkey = chan_utils::derive_public_revocation_key(&secp_ctx, &per_commitment_point, &self.pubkeys().revocation_basepoint);
872                 let witness_script = {
873                         let counterparty_htlcpubkey = chan_utils::derive_public_key(&secp_ctx, &per_commitment_point, &self.counterparty_pubkeys().htlc_basepoint);
874                         let holder_htlcpubkey = chan_utils::derive_public_key(&secp_ctx, &per_commitment_point, &self.pubkeys().htlc_basepoint);
875                         chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, self.opt_anchors(), &counterparty_htlcpubkey, &holder_htlcpubkey, &revocation_pubkey)
876                 };
877                 let mut sighash_parts = sighash::SighashCache::new(justice_tx);
878                 let sighash = hash_to_message!(&sighash_parts.segwit_signature_hash(input, &witness_script, amount, EcdsaSighashType::All).unwrap()[..]);
879                 return Ok(sign_with_aux_rand(secp_ctx, &sighash, &revocation_key, &self))
880         }
881
882         #[cfg(anchors)]
883         fn sign_holder_htlc_transaction(
884                 &self, htlc_tx: &Transaction, input: usize, htlc_descriptor: &HTLCDescriptor,
885                 secp_ctx: &Secp256k1<secp256k1::All>
886         ) -> Result<Signature, ()> {
887                 let per_commitment_point = self.get_per_commitment_point(
888                         htlc_descriptor.per_commitment_number, &secp_ctx
889                 );
890                 let witness_script = htlc_descriptor.witness_script(&per_commitment_point, secp_ctx);
891                 let sighash = &sighash::SighashCache::new(&*htlc_tx).segwit_signature_hash(
892                         input, &witness_script, htlc_descriptor.htlc.amount_msat / 1000, EcdsaSighashType::All
893                 ).map_err(|_| ())?;
894                 let our_htlc_private_key = chan_utils::derive_private_key(
895                         &secp_ctx, &per_commitment_point, &self.htlc_base_key
896                 );
897                 Ok(sign_with_aux_rand(&secp_ctx, &hash_to_message!(sighash), &our_htlc_private_key, &self))
898         }
899
900         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, ()> {
901                 let htlc_key = chan_utils::derive_private_key(&secp_ctx, &per_commitment_point, &self.htlc_base_key);
902                 let revocation_pubkey = chan_utils::derive_public_revocation_key(&secp_ctx, &per_commitment_point, &self.pubkeys().revocation_basepoint);
903                 let counterparty_htlcpubkey = chan_utils::derive_public_key(&secp_ctx, &per_commitment_point, &self.counterparty_pubkeys().htlc_basepoint);
904                 let htlcpubkey = chan_utils::derive_public_key(&secp_ctx, &per_commitment_point, &self.pubkeys().htlc_basepoint);
905                 let witness_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, self.opt_anchors(), &counterparty_htlcpubkey, &htlcpubkey, &revocation_pubkey);
906                 let mut sighash_parts = sighash::SighashCache::new(htlc_tx);
907                 let sighash = hash_to_message!(&sighash_parts.segwit_signature_hash(input, &witness_script, amount, EcdsaSighashType::All).unwrap()[..]);
908                 Ok(sign_with_aux_rand(secp_ctx, &sighash, &htlc_key, &self))
909         }
910
911         fn sign_closing_transaction(&self, closing_tx: &ClosingTransaction, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<Signature, ()> {
912                 let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
913                 let channel_funding_redeemscript = make_funding_redeemscript(&funding_pubkey, &self.counterparty_pubkeys().funding_pubkey);
914                 Ok(closing_tx.trust().sign(&self.funding_key, &channel_funding_redeemscript, self.channel_value_satoshis, secp_ctx))
915         }
916
917         fn sign_holder_anchor_input(
918                 &self, anchor_tx: &Transaction, input: usize, secp_ctx: &Secp256k1<secp256k1::All>,
919         ) -> Result<Signature, ()> {
920                 let witness_script = chan_utils::get_anchor_redeemscript(&self.holder_channel_pubkeys.funding_pubkey);
921                 let sighash = sighash::SighashCache::new(&*anchor_tx).segwit_signature_hash(
922                         input, &witness_script, ANCHOR_OUTPUT_VALUE_SATOSHI, EcdsaSighashType::All,
923                 ).unwrap();
924                 Ok(sign_with_aux_rand(secp_ctx, &hash_to_message!(&sighash[..]), &self.funding_key, &self))
925         }
926
927         fn sign_channel_announcement_with_funding_key(
928                 &self, msg: &UnsignedChannelAnnouncement, secp_ctx: &Secp256k1<secp256k1::All>
929         ) -> Result<Signature, ()> {
930                 let msghash = hash_to_message!(&Sha256dHash::hash(&msg.encode()[..])[..]);
931                 Ok(secp_ctx.sign_ecdsa(&msghash, &self.funding_key))
932         }
933 }
934
935 const SERIALIZATION_VERSION: u8 = 1;
936
937 const MIN_SERIALIZATION_VERSION: u8 = 1;
938
939 impl WriteableEcdsaChannelSigner for InMemorySigner {}
940
941 impl Writeable for InMemorySigner {
942         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), Error> {
943                 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
944
945                 self.funding_key.write(writer)?;
946                 self.revocation_base_key.write(writer)?;
947                 self.payment_key.write(writer)?;
948                 self.delayed_payment_base_key.write(writer)?;
949                 self.htlc_base_key.write(writer)?;
950                 self.commitment_seed.write(writer)?;
951                 self.channel_parameters.write(writer)?;
952                 self.channel_value_satoshis.write(writer)?;
953                 self.channel_keys_id.write(writer)?;
954
955                 write_tlv_fields!(writer, {});
956
957                 Ok(())
958         }
959 }
960
961 impl<ES: Deref> ReadableArgs<ES> for InMemorySigner where ES::Target: EntropySource {
962         fn read<R: io::Read>(reader: &mut R, entropy_source: ES) -> Result<Self, DecodeError> {
963                 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
964
965                 let funding_key = Readable::read(reader)?;
966                 let revocation_base_key = Readable::read(reader)?;
967                 let payment_key = Readable::read(reader)?;
968                 let delayed_payment_base_key = Readable::read(reader)?;
969                 let htlc_base_key = Readable::read(reader)?;
970                 let commitment_seed = Readable::read(reader)?;
971                 let counterparty_channel_data = Readable::read(reader)?;
972                 let channel_value_satoshis = Readable::read(reader)?;
973                 let secp_ctx = Secp256k1::signing_only();
974                 let holder_channel_pubkeys =
975                         InMemorySigner::make_holder_keys(&secp_ctx, &funding_key, &revocation_base_key,
976                                  &payment_key, &delayed_payment_base_key, &htlc_base_key);
977                 let keys_id = Readable::read(reader)?;
978
979                 read_tlv_fields!(reader, {});
980
981                 Ok(InMemorySigner {
982                         funding_key,
983                         revocation_base_key,
984                         payment_key,
985                         delayed_payment_base_key,
986                         htlc_base_key,
987                         commitment_seed,
988                         channel_value_satoshis,
989                         holder_channel_pubkeys,
990                         channel_parameters: counterparty_channel_data,
991                         channel_keys_id: keys_id,
992                         rand_bytes_unique_start: entropy_source.get_secure_random_bytes(),
993                         rand_bytes_index: AtomicCounter::new(),
994                 })
995         }
996 }
997
998 /// Simple implementation of [`EntropySource`], [`NodeSigner`], and [`SignerProvider`] that takes a
999 /// 32-byte seed for use as a BIP 32 extended key and derives keys from that.
1000 ///
1001 /// Your `node_id` is seed/0'.
1002 /// Unilateral closes may use seed/1'.
1003 /// Cooperative closes may use seed/2'.
1004 /// The two close keys may be needed to claim on-chain funds!
1005 ///
1006 /// This struct cannot be used for nodes that wish to support receiving phantom payments;
1007 /// [`PhantomKeysManager`] must be used instead.
1008 ///
1009 /// Note that switching between this struct and [`PhantomKeysManager`] will invalidate any
1010 /// previously issued invoices and attempts to pay previous invoices will fail.
1011 pub struct KeysManager {
1012         secp_ctx: Secp256k1<secp256k1::All>,
1013         node_secret: SecretKey,
1014         node_id: PublicKey,
1015         inbound_payment_key: KeyMaterial,
1016         destination_script: Script,
1017         shutdown_pubkey: PublicKey,
1018         channel_master_key: ExtendedPrivKey,
1019         channel_child_index: AtomicUsize,
1020
1021         rand_bytes_unique_start: [u8; 32],
1022         rand_bytes_index: AtomicCounter,
1023
1024         seed: [u8; 32],
1025         starting_time_secs: u64,
1026         starting_time_nanos: u32,
1027 }
1028
1029 impl KeysManager {
1030         /// Constructs a [`KeysManager`] from a 32-byte seed. If the seed is in some way biased (e.g.,
1031         /// your CSRNG is busted) this may panic (but more importantly, you will possibly lose funds).
1032         /// `starting_time` isn't strictly required to actually be a time, but it must absolutely,
1033         /// without a doubt, be unique to this instance. ie if you start multiple times with the same
1034         /// `seed`, `starting_time` must be unique to each run. Thus, the easiest way to achieve this
1035         /// is to simply use the current time (with very high precision).
1036         ///
1037         /// The `seed` MUST be backed up safely prior to use so that the keys can be re-created, however,
1038         /// obviously, `starting_time` should be unique every time you reload the library - it is only
1039         /// used to generate new ephemeral key data (which will be stored by the individual channel if
1040         /// necessary).
1041         ///
1042         /// Note that the seed is required to recover certain on-chain funds independent of
1043         /// [`ChannelMonitor`] data, though a current copy of [`ChannelMonitor`] data is also required
1044         /// for any channel, and some on-chain during-closing funds.
1045         ///
1046         /// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
1047         pub fn new(seed: &[u8; 32], starting_time_secs: u64, starting_time_nanos: u32) -> Self {
1048                 let secp_ctx = Secp256k1::new();
1049                 // Note that when we aren't serializing the key, network doesn't matter
1050                 match ExtendedPrivKey::new_master(Network::Testnet, seed) {
1051                         Ok(master_key) => {
1052                                 let node_secret = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(0).unwrap()).expect("Your RNG is busted").private_key;
1053                                 let node_id = PublicKey::from_secret_key(&secp_ctx, &node_secret);
1054                                 let destination_script = match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(1).unwrap()) {
1055                                         Ok(destination_key) => {
1056                                                 let wpubkey_hash = WPubkeyHash::hash(&ExtendedPubKey::from_priv(&secp_ctx, &destination_key).to_pub().to_bytes());
1057                                                 Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0)
1058                                                         .push_slice(&wpubkey_hash.into_inner())
1059                                                         .into_script()
1060                                         },
1061                                         Err(_) => panic!("Your RNG is busted"),
1062                                 };
1063                                 let shutdown_pubkey = match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(2).unwrap()) {
1064                                         Ok(shutdown_key) => ExtendedPubKey::from_priv(&secp_ctx, &shutdown_key).public_key,
1065                                         Err(_) => panic!("Your RNG is busted"),
1066                                 };
1067                                 let channel_master_key = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(3).unwrap()).expect("Your RNG is busted");
1068                                 let inbound_payment_key: SecretKey = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(5).unwrap()).expect("Your RNG is busted").private_key;
1069                                 let mut inbound_pmt_key_bytes = [0; 32];
1070                                 inbound_pmt_key_bytes.copy_from_slice(&inbound_payment_key[..]);
1071
1072                                 let mut rand_bytes_engine = Sha256::engine();
1073                                 rand_bytes_engine.input(&starting_time_secs.to_be_bytes());
1074                                 rand_bytes_engine.input(&starting_time_nanos.to_be_bytes());
1075                                 rand_bytes_engine.input(seed);
1076                                 rand_bytes_engine.input(b"LDK PRNG Seed");
1077                                 let rand_bytes_unique_start = Sha256::from_engine(rand_bytes_engine).into_inner();
1078
1079                                 let mut res = KeysManager {
1080                                         secp_ctx,
1081                                         node_secret,
1082                                         node_id,
1083                                         inbound_payment_key: KeyMaterial(inbound_pmt_key_bytes),
1084
1085                                         destination_script,
1086                                         shutdown_pubkey,
1087
1088                                         channel_master_key,
1089                                         channel_child_index: AtomicUsize::new(0),
1090
1091                                         rand_bytes_unique_start,
1092                                         rand_bytes_index: AtomicCounter::new(),
1093
1094                                         seed: *seed,
1095                                         starting_time_secs,
1096                                         starting_time_nanos,
1097                                 };
1098                                 let secp_seed = res.get_secure_random_bytes();
1099                                 res.secp_ctx.seeded_randomize(&secp_seed);
1100                                 res
1101                         },
1102                         Err(_) => panic!("Your rng is busted"),
1103                 }
1104         }
1105
1106         /// Gets the "node_id" secret key used to sign gossip announcements, decode onion data, etc.
1107         pub fn get_node_secret_key(&self) -> SecretKey {
1108                 self.node_secret
1109         }
1110
1111         /// Derive an old [`WriteableEcdsaChannelSigner`] containing per-channel secrets based on a key derivation parameters.
1112         pub fn derive_channel_keys(&self, channel_value_satoshis: u64, params: &[u8; 32]) -> InMemorySigner {
1113                 let chan_id = u64::from_be_bytes(params[0..8].try_into().unwrap());
1114                 let mut unique_start = Sha256::engine();
1115                 unique_start.input(params);
1116                 unique_start.input(&self.seed);
1117
1118                 // We only seriously intend to rely on the channel_master_key for true secure
1119                 // entropy, everything else just ensures uniqueness. We rely on the unique_start (ie
1120                 // starting_time provided in the constructor) to be unique.
1121                 let child_privkey = self.channel_master_key.ckd_priv(&self.secp_ctx,
1122                                 ChildNumber::from_hardened_idx((chan_id as u32) % (1 << 31)).expect("key space exhausted")
1123                         ).expect("Your RNG is busted");
1124                 unique_start.input(&child_privkey.private_key[..]);
1125
1126                 let seed = Sha256::from_engine(unique_start).into_inner();
1127
1128                 let commitment_seed = {
1129                         let mut sha = Sha256::engine();
1130                         sha.input(&seed);
1131                         sha.input(&b"commitment seed"[..]);
1132                         Sha256::from_engine(sha).into_inner()
1133                 };
1134                 macro_rules! key_step {
1135                         ($info: expr, $prev_key: expr) => {{
1136                                 let mut sha = Sha256::engine();
1137                                 sha.input(&seed);
1138                                 sha.input(&$prev_key[..]);
1139                                 sha.input(&$info[..]);
1140                                 SecretKey::from_slice(&Sha256::from_engine(sha).into_inner()).expect("SHA-256 is busted")
1141                         }}
1142                 }
1143                 let funding_key = key_step!(b"funding key", commitment_seed);
1144                 let revocation_base_key = key_step!(b"revocation base key", funding_key);
1145                 let payment_key = key_step!(b"payment key", revocation_base_key);
1146                 let delayed_payment_base_key = key_step!(b"delayed payment base key", payment_key);
1147                 let htlc_base_key = key_step!(b"HTLC base key", delayed_payment_base_key);
1148                 let prng_seed = self.get_secure_random_bytes();
1149
1150                 InMemorySigner::new(
1151                         &self.secp_ctx,
1152                         funding_key,
1153                         revocation_base_key,
1154                         payment_key,
1155                         delayed_payment_base_key,
1156                         htlc_base_key,
1157                         commitment_seed,
1158                         channel_value_satoshis,
1159                         params.clone(),
1160                         prng_seed,
1161                 )
1162         }
1163
1164         /// Creates a [`Transaction`] which spends the given descriptors to the given outputs, plus an
1165         /// output to the given change destination (if sufficient change value remains). The
1166         /// transaction will have a feerate, at least, of the given value.
1167         ///
1168         /// Returns `Err(())` if the output value is greater than the input value minus required fee,
1169         /// if a descriptor was duplicated, or if an output descriptor `script_pubkey`
1170         /// does not match the one we can spend.
1171         ///
1172         /// We do not enforce that outputs meet the dust limit or that any output scripts are standard.
1173         ///
1174         /// May panic if the [`SpendableOutputDescriptor`]s were not generated by channels which used
1175         /// this [`KeysManager`] or one of the [`InMemorySigner`] created by this [`KeysManager`].
1176         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, ()> {
1177                 let mut input = Vec::new();
1178                 let mut input_value = 0;
1179                 let mut witness_weight = 0;
1180                 let mut output_set = HashSet::with_capacity(descriptors.len());
1181                 for outp in descriptors {
1182                         match outp {
1183                                 SpendableOutputDescriptor::StaticPaymentOutput(descriptor) => {
1184                                         input.push(TxIn {
1185                                                 previous_output: descriptor.outpoint.into_bitcoin_outpoint(),
1186                                                 script_sig: Script::new(),
1187                                                 sequence: Sequence::ZERO,
1188                                                 witness: Witness::new(),
1189                                         });
1190                                         witness_weight += StaticPaymentOutputDescriptor::MAX_WITNESS_LENGTH;
1191                                         input_value += descriptor.output.value;
1192                                         if !output_set.insert(descriptor.outpoint) { return Err(()); }
1193                                 },
1194                                 SpendableOutputDescriptor::DelayedPaymentOutput(descriptor) => {
1195                                         input.push(TxIn {
1196                                                 previous_output: descriptor.outpoint.into_bitcoin_outpoint(),
1197                                                 script_sig: Script::new(),
1198                                                 sequence: Sequence(descriptor.to_self_delay as u32),
1199                                                 witness: Witness::new(),
1200                                         });
1201                                         witness_weight += DelayedPaymentOutputDescriptor::MAX_WITNESS_LENGTH;
1202                                         input_value += descriptor.output.value;
1203                                         if !output_set.insert(descriptor.outpoint) { return Err(()); }
1204                                 },
1205                                 SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output } => {
1206                                         input.push(TxIn {
1207                                                 previous_output: outpoint.into_bitcoin_outpoint(),
1208                                                 script_sig: Script::new(),
1209                                                 sequence: Sequence::ZERO,
1210                                                 witness: Witness::new(),
1211                                         });
1212                                         witness_weight += 1 + 73 + 34;
1213                                         input_value += output.value;
1214                                         if !output_set.insert(*outpoint) { return Err(()); }
1215                                 }
1216                         }
1217                         if input_value > MAX_VALUE_MSAT / 1000 { return Err(()); }
1218                 }
1219                 let mut spend_tx = Transaction {
1220                         version: 2,
1221                         lock_time: PackedLockTime(0),
1222                         input,
1223                         output: outputs,
1224                 };
1225                 let expected_max_weight =
1226                         transaction_utils::maybe_add_change_output(&mut spend_tx, input_value, witness_weight, feerate_sat_per_1000_weight, change_destination_script)?;
1227
1228                 let mut keys_cache: Option<(InMemorySigner, [u8; 32])> = None;
1229                 let mut input_idx = 0;
1230                 for outp in descriptors {
1231                         match outp {
1232                                 SpendableOutputDescriptor::StaticPaymentOutput(descriptor) => {
1233                                         if keys_cache.is_none() || keys_cache.as_ref().unwrap().1 != descriptor.channel_keys_id {
1234                                                 keys_cache = Some((
1235                                                         self.derive_channel_keys(descriptor.channel_value_satoshis, &descriptor.channel_keys_id),
1236                                                         descriptor.channel_keys_id));
1237                                         }
1238                                         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)?);
1239                                 },
1240                                 SpendableOutputDescriptor::DelayedPaymentOutput(descriptor) => {
1241                                         if keys_cache.is_none() || keys_cache.as_ref().unwrap().1 != descriptor.channel_keys_id {
1242                                                 keys_cache = Some((
1243                                                         self.derive_channel_keys(descriptor.channel_value_satoshis, &descriptor.channel_keys_id),
1244                                                         descriptor.channel_keys_id));
1245                                         }
1246                                         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)?);
1247                                 },
1248                                 SpendableOutputDescriptor::StaticOutput { ref output, .. } => {
1249                                         let derivation_idx = if output.script_pubkey == self.destination_script {
1250                                                 1
1251                                         } else {
1252                                                 2
1253                                         };
1254                                         let secret = {
1255                                                 // Note that when we aren't serializing the key, network doesn't matter
1256                                                 match ExtendedPrivKey::new_master(Network::Testnet, &self.seed) {
1257                                                         Ok(master_key) => {
1258                                                                 match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(derivation_idx).expect("key space exhausted")) {
1259                                                                         Ok(key) => key,
1260                                                                         Err(_) => panic!("Your RNG is busted"),
1261                                                                 }
1262                                                         }
1263                                                         Err(_) => panic!("Your rng is busted"),
1264                                                 }
1265                                         };
1266                                         let pubkey = ExtendedPubKey::from_priv(&secp_ctx, &secret).to_pub();
1267                                         if derivation_idx == 2 {
1268                                                 assert_eq!(pubkey.inner, self.shutdown_pubkey);
1269                                         }
1270                                         let witness_script = bitcoin::Address::p2pkh(&pubkey, Network::Testnet).script_pubkey();
1271                                         let payment_script = bitcoin::Address::p2wpkh(&pubkey, Network::Testnet).expect("uncompressed key found").script_pubkey();
1272
1273                                         if payment_script != output.script_pubkey { return Err(()); };
1274
1275                                         let sighash = hash_to_message!(&sighash::SighashCache::new(&spend_tx).segwit_signature_hash(input_idx, &witness_script, output.value, EcdsaSighashType::All).unwrap()[..]);
1276                                         let sig = sign_with_aux_rand(secp_ctx, &sighash, &secret.private_key, &self);
1277                                         let mut sig_ser = sig.serialize_der().to_vec();
1278                                         sig_ser.push(EcdsaSighashType::All as u8);
1279                                         spend_tx.input[input_idx].witness.push(sig_ser);
1280                                         spend_tx.input[input_idx].witness.push(pubkey.inner.serialize().to_vec());
1281                                 },
1282                         }
1283                         input_idx += 1;
1284                 }
1285
1286                 debug_assert!(expected_max_weight >= spend_tx.weight());
1287                 // Note that witnesses with a signature vary somewhat in size, so allow
1288                 // `expected_max_weight` to overshoot by up to 3 bytes per input.
1289                 debug_assert!(expected_max_weight <= spend_tx.weight() + descriptors.len() * 3);
1290
1291                 Ok(spend_tx)
1292         }
1293 }
1294
1295 impl EntropySource for KeysManager {
1296         fn get_secure_random_bytes(&self) -> [u8; 32] {
1297                 let index = self.rand_bytes_index.get_increment();
1298                 let mut nonce = [0u8; 16];
1299                 nonce[..8].copy_from_slice(&index.to_be_bytes());
1300                 ChaCha20::get_single_block(&self.rand_bytes_unique_start, &nonce)
1301         }
1302 }
1303
1304 impl NodeSigner for KeysManager {
1305         fn get_node_id(&self, recipient: Recipient) -> Result<PublicKey, ()> {
1306                 match recipient {
1307                         Recipient::Node => Ok(self.node_id.clone()),
1308                         Recipient::PhantomNode => Err(())
1309                 }
1310         }
1311
1312         fn ecdh(&self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&Scalar>) -> Result<SharedSecret, ()> {
1313                 let mut node_secret = match recipient {
1314                         Recipient::Node => Ok(self.node_secret.clone()),
1315                         Recipient::PhantomNode => Err(())
1316                 }?;
1317                 if let Some(tweak) = tweak {
1318                         node_secret = node_secret.mul_tweak(tweak).map_err(|_| ())?;
1319                 }
1320                 Ok(SharedSecret::new(other_key, &node_secret))
1321         }
1322
1323         fn get_inbound_payment_key_material(&self) -> KeyMaterial {
1324                 self.inbound_payment_key.clone()
1325         }
1326
1327         fn sign_invoice(&self, hrp_bytes: &[u8], invoice_data: &[u5], recipient: Recipient) -> Result<RecoverableSignature, ()> {
1328                 let preimage = construct_invoice_preimage(&hrp_bytes, &invoice_data);
1329                 let secret = match recipient {
1330                         Recipient::Node => Ok(&self.node_secret),
1331                         Recipient::PhantomNode => Err(())
1332                 }?;
1333                 Ok(self.secp_ctx.sign_ecdsa_recoverable(&hash_to_message!(&Sha256::hash(&preimage)), secret))
1334         }
1335
1336         fn sign_gossip_message(&self, msg: UnsignedGossipMessage) -> Result<Signature, ()> {
1337                 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.encode()[..])[..]);
1338                 Ok(self.secp_ctx.sign_ecdsa(&msg_hash, &self.node_secret))
1339         }
1340 }
1341
1342 impl SignerProvider for KeysManager {
1343         type Signer = InMemorySigner;
1344
1345         fn generate_channel_keys_id(&self, _inbound: bool, _channel_value_satoshis: u64, user_channel_id: u128) -> [u8; 32] {
1346                 let child_idx = self.channel_child_index.fetch_add(1, Ordering::AcqRel);
1347                 // `child_idx` is the only thing guaranteed to make each channel unique without a restart
1348                 // (though `user_channel_id` should help, depending on user behavior). If it manages to
1349                 // roll over, we may generate duplicate keys for two different channels, which could result
1350                 // in loss of funds. Because we only support 32-bit+ systems, assert that our `AtomicUsize`
1351                 // doesn't reach `u32::MAX`.
1352                 assert!(child_idx < core::u32::MAX as usize, "2^32 channels opened without restart");
1353                 let mut id = [0; 32];
1354                 id[0..4].copy_from_slice(&(child_idx as u32).to_be_bytes());
1355                 id[4..8].copy_from_slice(&self.starting_time_nanos.to_be_bytes());
1356                 id[8..16].copy_from_slice(&self.starting_time_secs.to_be_bytes());
1357                 id[16..32].copy_from_slice(&user_channel_id.to_be_bytes());
1358                 id
1359         }
1360
1361         fn derive_channel_signer(&self, channel_value_satoshis: u64, channel_keys_id: [u8; 32]) -> Self::Signer {
1362                 self.derive_channel_keys(channel_value_satoshis, &channel_keys_id)
1363         }
1364
1365         fn read_chan_signer(&self, reader: &[u8]) -> Result<Self::Signer, DecodeError> {
1366                 InMemorySigner::read(&mut io::Cursor::new(reader), self)
1367         }
1368
1369         fn get_destination_script(&self) -> Script {
1370                 self.destination_script.clone()
1371         }
1372
1373         fn get_shutdown_scriptpubkey(&self) -> ShutdownScript {
1374                 ShutdownScript::new_p2wpkh_from_pubkey(self.shutdown_pubkey.clone())
1375         }
1376 }
1377
1378 /// Similar to [`KeysManager`], but allows the node using this struct to receive phantom node
1379 /// payments.
1380 ///
1381 /// A phantom node payment is a payment made to a phantom invoice, which is an invoice that can be
1382 /// paid to one of multiple nodes. This works because we encode the invoice route hints such that
1383 /// LDK will recognize an incoming payment as destined for a phantom node, and collect the payment
1384 /// itself without ever needing to forward to this fake node.
1385 ///
1386 /// Phantom node payments are useful for load balancing between multiple LDK nodes. They also
1387 /// provide some fault tolerance, because payers will automatically retry paying other provided
1388 /// nodes in the case that one node goes down.
1389 ///
1390 /// Note that multi-path payments are not supported in phantom invoices for security reasons.
1391 // In the hypothetical case that we did support MPP phantom payments, there would be no way for
1392 // nodes to know when the full payment has been received (and the preimage can be released) without
1393 // significantly compromising on our safety guarantees. I.e., if we expose the ability for the user
1394 // to tell LDK when the preimage can be released, we open ourselves to attacks where the preimage
1395 // is released too early.
1396 //
1397 /// Switching between this struct and [`KeysManager`] will invalidate any previously issued
1398 /// invoices and attempts to pay previous invoices will fail.
1399 pub struct PhantomKeysManager {
1400         inner: KeysManager,
1401         inbound_payment_key: KeyMaterial,
1402         phantom_secret: SecretKey,
1403         phantom_node_id: PublicKey,
1404 }
1405
1406 impl EntropySource for PhantomKeysManager {
1407         fn get_secure_random_bytes(&self) -> [u8; 32] {
1408                 self.inner.get_secure_random_bytes()
1409         }
1410 }
1411
1412 impl NodeSigner for PhantomKeysManager {
1413         fn get_node_id(&self, recipient: Recipient) -> Result<PublicKey, ()> {
1414                 match recipient {
1415                         Recipient::Node => self.inner.get_node_id(Recipient::Node),
1416                         Recipient::PhantomNode => Ok(self.phantom_node_id.clone()),
1417                 }
1418         }
1419
1420         fn ecdh(&self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&Scalar>) -> Result<SharedSecret, ()> {
1421                 let mut node_secret = match recipient {
1422                         Recipient::Node => self.inner.node_secret.clone(),
1423                         Recipient::PhantomNode => self.phantom_secret.clone(),
1424                 };
1425                 if let Some(tweak) = tweak {
1426                         node_secret = node_secret.mul_tweak(tweak).map_err(|_| ())?;
1427                 }
1428                 Ok(SharedSecret::new(other_key, &node_secret))
1429         }
1430
1431         fn get_inbound_payment_key_material(&self) -> KeyMaterial {
1432                 self.inbound_payment_key.clone()
1433         }
1434
1435         fn sign_invoice(&self, hrp_bytes: &[u8], invoice_data: &[u5], recipient: Recipient) -> Result<RecoverableSignature, ()> {
1436                 let preimage = construct_invoice_preimage(&hrp_bytes, &invoice_data);
1437                 let secret = match recipient {
1438                         Recipient::Node => &self.inner.node_secret,
1439                         Recipient::PhantomNode => &self.phantom_secret,
1440                 };
1441                 Ok(self.inner.secp_ctx.sign_ecdsa_recoverable(&hash_to_message!(&Sha256::hash(&preimage)), secret))
1442         }
1443
1444         fn sign_gossip_message(&self, msg: UnsignedGossipMessage) -> Result<Signature, ()> {
1445                 self.inner.sign_gossip_message(msg)
1446         }
1447 }
1448
1449 impl SignerProvider for PhantomKeysManager {
1450         type Signer = InMemorySigner;
1451
1452         fn generate_channel_keys_id(&self, inbound: bool, channel_value_satoshis: u64, user_channel_id: u128) -> [u8; 32] {
1453                 self.inner.generate_channel_keys_id(inbound, channel_value_satoshis, user_channel_id)
1454         }
1455
1456         fn derive_channel_signer(&self, channel_value_satoshis: u64, channel_keys_id: [u8; 32]) -> Self::Signer {
1457                 self.inner.derive_channel_signer(channel_value_satoshis, channel_keys_id)
1458         }
1459
1460         fn read_chan_signer(&self, reader: &[u8]) -> Result<Self::Signer, DecodeError> {
1461                 self.inner.read_chan_signer(reader)
1462         }
1463
1464         fn get_destination_script(&self) -> Script {
1465                 self.inner.get_destination_script()
1466         }
1467
1468         fn get_shutdown_scriptpubkey(&self) -> ShutdownScript {
1469                 self.inner.get_shutdown_scriptpubkey()
1470         }
1471 }
1472
1473 impl PhantomKeysManager {
1474         /// Constructs a [`PhantomKeysManager`] given a 32-byte seed and an additional `cross_node_seed`
1475         /// that is shared across all nodes that intend to participate in [phantom node payments]
1476         /// together.
1477         ///
1478         /// See [`KeysManager::new`] for more information on `seed`, `starting_time_secs`, and
1479         /// `starting_time_nanos`.
1480         ///
1481         /// `cross_node_seed` must be the same across all phantom payment-receiving nodes and also the
1482         /// same across restarts, or else inbound payments may fail.
1483         ///
1484         /// [phantom node payments]: PhantomKeysManager
1485         pub fn new(seed: &[u8; 32], starting_time_secs: u64, starting_time_nanos: u32, cross_node_seed: &[u8; 32]) -> Self {
1486                 let inner = KeysManager::new(seed, starting_time_secs, starting_time_nanos);
1487                 let (inbound_key, phantom_key) = hkdf_extract_expand_twice(b"LDK Inbound and Phantom Payment Key Expansion", cross_node_seed);
1488                 let phantom_secret = SecretKey::from_slice(&phantom_key).unwrap();
1489                 let phantom_node_id = PublicKey::from_secret_key(&inner.secp_ctx, &phantom_secret);
1490                 Self {
1491                         inner,
1492                         inbound_payment_key: KeyMaterial(inbound_key),
1493                         phantom_secret,
1494                         phantom_node_id,
1495                 }
1496         }
1497
1498         /// See [`KeysManager::spend_spendable_outputs`] for documentation on this method.
1499         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, ()> {
1500                 self.inner.spend_spendable_outputs(descriptors, outputs, change_destination_script, feerate_sat_per_1000_weight, secp_ctx)
1501         }
1502
1503         /// See [`KeysManager::derive_channel_keys`] for documentation on this method.
1504         pub fn derive_channel_keys(&self, channel_value_satoshis: u64, params: &[u8; 32]) -> InMemorySigner {
1505                 self.inner.derive_channel_keys(channel_value_satoshis, params)
1506         }
1507
1508         /// Gets the "node_id" secret key used to sign gossip announcements, decode onion data, etc.
1509         pub fn get_node_secret_key(&self) -> SecretKey {
1510                 self.inner.get_node_secret_key()
1511         }
1512
1513         /// Gets the "node_id" secret key of the phantom node used to sign invoices, decode the
1514         /// last-hop onion data, etc.
1515         pub fn get_phantom_node_secret_key(&self) -> SecretKey {
1516                 self.phantom_secret
1517         }
1518 }
1519
1520 // Ensure that EcdsaChannelSigner can have a vtable
1521 #[test]
1522 pub fn dyn_sign() {
1523         let _signer: Box<dyn EcdsaChannelSigner>;
1524 }
1525
1526 #[cfg(all(test, feature = "_bench_unstable", not(feature = "no-std")))]
1527 mod benches {
1528         use std::sync::{Arc, mpsc};
1529         use std::sync::mpsc::TryRecvError;
1530         use std::thread;
1531         use std::time::Duration;
1532         use bitcoin::blockdata::constants::genesis_block;
1533         use bitcoin::Network;
1534         use crate::chain::keysinterface::{EntropySource, KeysManager};
1535
1536         use test::Bencher;
1537
1538         #[bench]
1539         fn bench_get_secure_random_bytes(bench: &mut Bencher) {
1540                 let seed = [0u8; 32];
1541                 let now = Duration::from_secs(genesis_block(Network::Testnet).header.time as u64);
1542                 let keys_manager = Arc::new(KeysManager::new(&seed, now.as_secs(), now.subsec_micros()));
1543
1544                 let mut handles = Vec::new();
1545                 let mut stops = Vec::new();
1546                 for _ in 1..5 {
1547                         let keys_manager_clone = Arc::clone(&keys_manager);
1548                         let (stop_sender, stop_receiver) = mpsc::channel();
1549                         let handle = thread::spawn(move || {
1550                                 loop {
1551                                         keys_manager_clone.get_secure_random_bytes();
1552                                         match stop_receiver.try_recv() {
1553                                                 Ok(_) | Err(TryRecvError::Disconnected) => {
1554                                                         println!("Terminating.");
1555                                                         break;
1556                                                 }
1557                                                 Err(TryRecvError::Empty) => {}
1558                                         }
1559                                 }
1560                         });
1561                         handles.push(handle);
1562                         stops.push(stop_sender);
1563                 }
1564
1565                 bench.iter(|| {
1566                         for _ in 1..100 {
1567                                 keys_manager.get_secure_random_bytes();
1568                         }
1569                 });
1570
1571                 for stop in stops {
1572                         let _ = stop.send(());
1573                 }
1574                 for handle in handles {
1575                         handle.join().unwrap();
1576                 }
1577         }
1578
1579 }