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