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