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