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