f5ba6bc3e8f7c85a56e7a1aeceb372fc703bb103
[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, SigHashType};
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::bip143;
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::key::{SecretKey, PublicKey};
29 use bitcoin::secp256k1::{Secp256k1, Signature, Signing};
30 use bitcoin::secp256k1::recovery::RecoverableSignature;
31 use bitcoin::secp256k1;
32
33 use util::{byte_utils, transaction_utils};
34 use util::crypto::hkdf_extract_expand_twice;
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 /// A trait to describe an object which can get user secrets and key material.
384 pub trait KeysInterface {
385         /// A type which implements Sign which will be returned by get_channel_signer.
386         type Signer : Sign;
387
388         /// Get node secret key (aka node_id or network_key).
389         ///
390         /// This method must return the same value each time it is called.
391         fn get_node_secret(&self) -> SecretKey;
392         /// Get a script pubkey which we send funds to when claiming on-chain contestable outputs.
393         ///
394         /// This method should return a different value each time it is called, to avoid linking
395         /// on-chain funds across channels as controlled to the same user.
396         fn get_destination_script(&self) -> Script;
397         /// Get a script pubkey which we will send funds to when closing a channel.
398         ///
399         /// This method should return a different value each time it is called, to avoid linking
400         /// on-chain funds across channels as controlled to the same user.
401         fn get_shutdown_scriptpubkey(&self) -> ShutdownScript;
402         /// Get a new set of Sign for per-channel secrets. These MUST be unique even if you
403         /// restarted with some stale data!
404         ///
405         /// This method must return a different value each time it is called.
406         fn get_channel_signer(&self, inbound: bool, channel_value_satoshis: u64) -> Self::Signer;
407         /// Gets a unique, cryptographically-secure, random 32 byte value. This is used for encrypting
408         /// onion packets and for temporary channel IDs. There is no requirement that these be
409         /// persisted anywhere, though they must be unique across restarts.
410         ///
411         /// This method must return a different value each time it is called.
412         fn get_secure_random_bytes(&self) -> [u8; 32];
413
414         /// Reads a `Signer` for this `KeysInterface` from the given input stream.
415         /// This is only called during deserialization of other objects which contain
416         /// `Sign`-implementing objects (ie `ChannelMonitor`s and `ChannelManager`s).
417         /// The bytes are exactly those which `<Self::Signer as Writeable>::write()` writes, and
418         /// contain no versioning scheme. You may wish to include your own version prefix and ensure
419         /// you've read all of the provided bytes to ensure no corruption occurred.
420         fn read_chan_signer(&self, reader: &[u8]) -> Result<Self::Signer, DecodeError>;
421
422         /// Sign an invoice.
423         /// By parameterizing by the raw invoice bytes instead of the hash, we allow implementors of
424         /// this trait to parse the invoice and make sure they're signing what they expect, rather than
425         /// blindly signing the hash.
426         /// The hrp is ascii bytes, while the invoice data is base32.
427         fn sign_invoice(&self, hrp_bytes: &[u8], invoice_data: &[u5]) -> Result<RecoverableSignature, ()>;
428
429         /// Get secret key material as bytes for use in encrypting and decrypting inbound payment data.
430         ///
431         /// If the implementor of this trait supports [phantom node payments], then every node that is
432         /// intended to be included in the phantom invoice route hints must return the same value from
433         /// this method.
434         //  This is because LDK avoids storing inbound payment data by encrypting payment data in the
435         //  payment hash and/or payment secret, therefore for a payment to be receivable by multiple
436         //  nodes, they must share the key that encrypts this payment data.
437         ///
438         /// This method must return the same value each time it is called.
439         ///
440         /// [phantom node payments]: PhantomKeysManager
441         fn get_inbound_payment_key_material(&self) -> KeyMaterial;
442 }
443
444 #[derive(Clone)]
445 /// A simple implementation of Sign that just keeps the private keys in memory.
446 ///
447 /// This implementation performs no policy checks and is insufficient by itself as
448 /// a secure external signer.
449 pub struct InMemorySigner {
450         /// Private key of anchor tx
451         pub funding_key: SecretKey,
452         /// Holder secret key for blinded revocation pubkey
453         pub revocation_base_key: SecretKey,
454         /// Holder secret key used for our balance in counterparty-broadcasted commitment transactions
455         pub payment_key: SecretKey,
456         /// Holder secret key used in HTLC tx
457         pub delayed_payment_base_key: SecretKey,
458         /// Holder htlc secret key used in commitment tx htlc outputs
459         pub htlc_base_key: SecretKey,
460         /// Commitment seed
461         pub commitment_seed: [u8; 32],
462         /// Holder public keys and basepoints
463         pub(crate) holder_channel_pubkeys: ChannelPublicKeys,
464         /// Private key of our node secret, used for signing channel announcements
465         node_secret: SecretKey,
466         /// Counterparty public keys and counterparty/holder selected_contest_delay, populated on channel acceptance
467         channel_parameters: Option<ChannelTransactionParameters>,
468         /// The total value of this channel
469         channel_value_satoshis: u64,
470         /// Key derivation parameters
471         channel_keys_id: [u8; 32],
472 }
473
474 impl InMemorySigner {
475         /// Create a new InMemorySigner
476         pub fn new<C: Signing>(
477                 secp_ctx: &Secp256k1<C>,
478                 node_secret: SecretKey,
479                 funding_key: SecretKey,
480                 revocation_base_key: SecretKey,
481                 payment_key: SecretKey,
482                 delayed_payment_base_key: SecretKey,
483                 htlc_base_key: SecretKey,
484                 commitment_seed: [u8; 32],
485                 channel_value_satoshis: u64,
486                 channel_keys_id: [u8; 32]) -> InMemorySigner {
487                 let holder_channel_pubkeys =
488                         InMemorySigner::make_holder_keys(secp_ctx, &funding_key, &revocation_base_key,
489                                                              &payment_key, &delayed_payment_base_key,
490                                                              &htlc_base_key);
491                 InMemorySigner {
492                         funding_key,
493                         revocation_base_key,
494                         payment_key,
495                         delayed_payment_base_key,
496                         htlc_base_key,
497                         commitment_seed,
498                         node_secret,
499                         channel_value_satoshis,
500                         holder_channel_pubkeys,
501                         channel_parameters: None,
502                         channel_keys_id,
503                 }
504         }
505
506         fn make_holder_keys<C: Signing>(secp_ctx: &Secp256k1<C>,
507                                        funding_key: &SecretKey,
508                                        revocation_base_key: &SecretKey,
509                                        payment_key: &SecretKey,
510                                        delayed_payment_base_key: &SecretKey,
511                                        htlc_base_key: &SecretKey) -> ChannelPublicKeys {
512                 let from_secret = |s: &SecretKey| PublicKey::from_secret_key(secp_ctx, s);
513                 ChannelPublicKeys {
514                         funding_pubkey: from_secret(&funding_key),
515                         revocation_basepoint: from_secret(&revocation_base_key),
516                         payment_point: from_secret(&payment_key),
517                         delayed_payment_basepoint: from_secret(&delayed_payment_base_key),
518                         htlc_basepoint: from_secret(&htlc_base_key),
519                 }
520         }
521
522         /// Counterparty pubkeys.
523         /// Will panic if ready_channel wasn't called.
524         pub fn counterparty_pubkeys(&self) -> &ChannelPublicKeys { &self.get_channel_parameters().counterparty_parameters.as_ref().unwrap().pubkeys }
525
526         /// The contest_delay value specified by our counterparty and applied on holder-broadcastable
527         /// transactions, ie the amount of time that we have to wait to recover our funds if we
528         /// broadcast a transaction.
529         /// Will panic if ready_channel wasn't called.
530         pub fn counterparty_selected_contest_delay(&self) -> u16 { self.get_channel_parameters().counterparty_parameters.as_ref().unwrap().selected_contest_delay }
531
532         /// The contest_delay value specified by us and applied on transactions broadcastable
533         /// by our counterparty, ie the amount of time that they have to wait to recover their funds
534         /// if they broadcast a transaction.
535         /// Will panic if ready_channel wasn't called.
536         pub fn holder_selected_contest_delay(&self) -> u16 { self.get_channel_parameters().holder_selected_contest_delay }
537
538         /// Whether the holder is the initiator
539         /// Will panic if ready_channel wasn't called.
540         pub fn is_outbound(&self) -> bool { self.get_channel_parameters().is_outbound_from_holder }
541
542         /// Funding outpoint
543         /// Will panic if ready_channel wasn't called.
544         pub fn funding_outpoint(&self) -> &OutPoint { self.get_channel_parameters().funding_outpoint.as_ref().unwrap() }
545
546         /// Obtain a ChannelTransactionParameters for this channel, to be used when verifying or
547         /// building transactions.
548         ///
549         /// Will panic if ready_channel wasn't called.
550         pub fn get_channel_parameters(&self) -> &ChannelTransactionParameters {
551                 self.channel_parameters.as_ref().unwrap()
552         }
553
554         /// Whether anchors should be used.
555         /// Will panic if ready_channel wasn't called.
556         pub fn opt_anchors(&self) -> bool {
557                 self.get_channel_parameters().opt_anchors.is_some()
558         }
559
560         /// Sign the single input of spend_tx at index `input_idx` which spends the output
561         /// described by descriptor, returning the witness stack for the input.
562         ///
563         /// Returns an Err if the input at input_idx does not exist, has a non-empty script_sig,
564         /// is not spending the outpoint described by `descriptor.outpoint`,
565         /// or if an output descriptor script_pubkey does not match the one we can spend.
566         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>>, ()> {
567                 // TODO: We really should be taking the SigHashCache as a parameter here instead of
568                 // spend_tx, but ideally the SigHashCache would expose the transaction's inputs read-only
569                 // so that we can check them. This requires upstream rust-bitcoin changes (as well as
570                 // bindings updates to support SigHashCache objects).
571                 if spend_tx.input.len() <= input_idx { return Err(()); }
572                 if !spend_tx.input[input_idx].script_sig.is_empty() { return Err(()); }
573                 if spend_tx.input[input_idx].previous_output != descriptor.outpoint.into_bitcoin_outpoint() { return Err(()); }
574
575                 let remotepubkey = self.pubkeys().payment_point;
576                 let witness_script = bitcoin::Address::p2pkh(&::bitcoin::PublicKey{compressed: true, key: remotepubkey}, Network::Testnet).script_pubkey();
577                 let sighash = hash_to_message!(&bip143::SigHashCache::new(spend_tx).signature_hash(input_idx, &witness_script, descriptor.output.value, SigHashType::All)[..]);
578                 let remotesig = secp_ctx.sign(&sighash, &self.payment_key);
579                 let payment_script = bitcoin::Address::p2wpkh(&::bitcoin::PublicKey{compressed: true, key: remotepubkey}, Network::Bitcoin).unwrap().script_pubkey();
580
581                 if payment_script != descriptor.output.script_pubkey  { return Err(()); }
582
583                 let mut witness = Vec::with_capacity(2);
584                 witness.push(remotesig.serialize_der().to_vec());
585                 witness[0].push(SigHashType::All as u8);
586                 witness.push(remotepubkey.serialize().to_vec());
587                 Ok(witness)
588         }
589
590         /// Sign the single input of spend_tx at index `input_idx` which spends the output
591         /// described by descriptor, returning the witness stack for the input.
592         ///
593         /// Returns an Err if the input at input_idx does not exist, has a non-empty script_sig,
594         /// is not spending the outpoint described by `descriptor.outpoint`, does not have a
595         /// sequence set to `descriptor.to_self_delay`, or if an output descriptor
596         /// script_pubkey does not match the one we can spend.
597         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>>, ()> {
598                 // TODO: We really should be taking the SigHashCache as a parameter here instead of
599                 // spend_tx, but ideally the SigHashCache would expose the transaction's inputs read-only
600                 // so that we can check them. This requires upstream rust-bitcoin changes (as well as
601                 // bindings updates to support SigHashCache objects).
602                 if spend_tx.input.len() <= input_idx { return Err(()); }
603                 if !spend_tx.input[input_idx].script_sig.is_empty() { return Err(()); }
604                 if spend_tx.input[input_idx].previous_output != descriptor.outpoint.into_bitcoin_outpoint() { return Err(()); }
605                 if spend_tx.input[input_idx].sequence != descriptor.to_self_delay as u32 { return Err(()); }
606
607                 let delayed_payment_key = chan_utils::derive_private_key(&secp_ctx, &descriptor.per_commitment_point, &self.delayed_payment_base_key)
608                         .expect("We constructed the payment_base_key, so we can only fail here if the RNG is busted.");
609                 let delayed_payment_pubkey = PublicKey::from_secret_key(&secp_ctx, &delayed_payment_key);
610                 let witness_script = chan_utils::get_revokeable_redeemscript(&descriptor.revocation_pubkey, descriptor.to_self_delay, &delayed_payment_pubkey);
611                 let sighash = hash_to_message!(&bip143::SigHashCache::new(spend_tx).signature_hash(input_idx, &witness_script, descriptor.output.value, SigHashType::All)[..]);
612                 let local_delayedsig = secp_ctx.sign(&sighash, &delayed_payment_key);
613                 let payment_script = bitcoin::Address::p2wsh(&witness_script, Network::Bitcoin).script_pubkey();
614
615                 if descriptor.output.script_pubkey != payment_script { return Err(()); }
616
617                 let mut witness = Vec::with_capacity(3);
618                 witness.push(local_delayedsig.serialize_der().to_vec());
619                 witness[0].push(SigHashType::All as u8);
620                 witness.push(vec!()); //MINIMALIF
621                 witness.push(witness_script.clone().into_bytes());
622                 Ok(witness)
623         }
624 }
625
626 impl BaseSign for InMemorySigner {
627         fn get_per_commitment_point(&self, idx: u64, secp_ctx: &Secp256k1<secp256k1::All>) -> PublicKey {
628                 let commitment_secret = SecretKey::from_slice(&chan_utils::build_commitment_secret(&self.commitment_seed, idx)).unwrap();
629                 PublicKey::from_secret_key(secp_ctx, &commitment_secret)
630         }
631
632         fn release_commitment_secret(&self, idx: u64) -> [u8; 32] {
633                 chan_utils::build_commitment_secret(&self.commitment_seed, idx)
634         }
635
636         fn validate_holder_commitment(&self, _holder_tx: &HolderCommitmentTransaction, _preimages: Vec<PaymentPreimage>) -> Result<(), ()> {
637                 Ok(())
638         }
639
640         fn pubkeys(&self) -> &ChannelPublicKeys { &self.holder_channel_pubkeys }
641         fn channel_keys_id(&self) -> [u8; 32] { self.channel_keys_id }
642
643         fn sign_counterparty_commitment(&self, commitment_tx: &CommitmentTransaction, _preimages: Vec<PaymentPreimage>, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<(Signature, Vec<Signature>), ()> {
644                 let trusted_tx = commitment_tx.trust();
645                 let keys = trusted_tx.keys();
646
647                 let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
648                 let channel_funding_redeemscript = make_funding_redeemscript(&funding_pubkey, &self.counterparty_pubkeys().funding_pubkey);
649
650                 let built_tx = trusted_tx.built_transaction();
651                 let commitment_sig = built_tx.sign(&self.funding_key, &channel_funding_redeemscript, self.channel_value_satoshis, secp_ctx);
652                 let commitment_txid = built_tx.txid;
653
654                 let mut htlc_sigs = Vec::with_capacity(commitment_tx.htlcs().len());
655                 for htlc in commitment_tx.htlcs() {
656                         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);
657                         let htlc_redeemscript = chan_utils::get_htlc_redeemscript(&htlc, self.opt_anchors(), &keys);
658                         let htlc_sighashtype = if self.opt_anchors() { SigHashType::SinglePlusAnyoneCanPay } else { SigHashType::All };
659                         let htlc_sighash = hash_to_message!(&bip143::SigHashCache::new(&htlc_tx).signature_hash(0, &htlc_redeemscript, htlc.amount_msat / 1000, htlc_sighashtype)[..]);
660                         let holder_htlc_key = chan_utils::derive_private_key(&secp_ctx, &keys.per_commitment_point, &self.htlc_base_key).map_err(|_| ())?;
661                         htlc_sigs.push(secp_ctx.sign(&htlc_sighash, &holder_htlc_key));
662                 }
663
664                 Ok((commitment_sig, htlc_sigs))
665         }
666
667         fn validate_counterparty_revocation(&self, _idx: u64, _secret: &SecretKey) -> Result<(), ()> {
668                 Ok(())
669         }
670
671         fn sign_holder_commitment_and_htlcs(&self, commitment_tx: &HolderCommitmentTransaction, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<(Signature, Vec<Signature>), ()> {
672                 let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
673                 let funding_redeemscript = make_funding_redeemscript(&funding_pubkey, &self.counterparty_pubkeys().funding_pubkey);
674                 let trusted_tx = commitment_tx.trust();
675                 let sig = trusted_tx.built_transaction().sign(&self.funding_key, &funding_redeemscript, self.channel_value_satoshis, secp_ctx);
676                 let channel_parameters = self.get_channel_parameters();
677                 let htlc_sigs = trusted_tx.get_htlc_sigs(&self.htlc_base_key, &channel_parameters.as_holder_broadcastable(), secp_ctx)?;
678                 Ok((sig, htlc_sigs))
679         }
680
681         #[cfg(any(test,feature = "unsafe_revoked_tx_signing"))]
682         fn unsafe_sign_holder_commitment_and_htlcs(&self, commitment_tx: &HolderCommitmentTransaction, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<(Signature, Vec<Signature>), ()> {
683                 let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
684                 let funding_redeemscript = make_funding_redeemscript(&funding_pubkey, &self.counterparty_pubkeys().funding_pubkey);
685                 let trusted_tx = commitment_tx.trust();
686                 let sig = trusted_tx.built_transaction().sign(&self.funding_key, &funding_redeemscript, self.channel_value_satoshis, secp_ctx);
687                 let channel_parameters = self.get_channel_parameters();
688                 let htlc_sigs = trusted_tx.get_htlc_sigs(&self.htlc_base_key, &channel_parameters.as_holder_broadcastable(), secp_ctx)?;
689                 Ok((sig, htlc_sigs))
690         }
691
692         fn sign_justice_revoked_output(&self, justice_tx: &Transaction, input: usize, amount: u64, per_commitment_key: &SecretKey, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<Signature, ()> {
693                 let revocation_key = chan_utils::derive_private_revocation_key(&secp_ctx, &per_commitment_key, &self.revocation_base_key).map_err(|_| ())?;
694                 let per_commitment_point = PublicKey::from_secret_key(secp_ctx, &per_commitment_key);
695                 let revocation_pubkey = chan_utils::derive_public_revocation_key(&secp_ctx, &per_commitment_point, &self.pubkeys().revocation_basepoint).map_err(|_| ())?;
696                 let witness_script = {
697                         let counterparty_delayedpubkey = chan_utils::derive_public_key(&secp_ctx, &per_commitment_point, &self.counterparty_pubkeys().delayed_payment_basepoint).map_err(|_| ())?;
698                         chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.holder_selected_contest_delay(), &counterparty_delayedpubkey)
699                 };
700                 let mut sighash_parts = bip143::SigHashCache::new(justice_tx);
701                 let sighash = hash_to_message!(&sighash_parts.signature_hash(input, &witness_script, amount, SigHashType::All)[..]);
702                 return Ok(secp_ctx.sign(&sighash, &revocation_key))
703         }
704
705         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, ()> {
706                 let revocation_key = chan_utils::derive_private_revocation_key(&secp_ctx, &per_commitment_key, &self.revocation_base_key).map_err(|_| ())?;
707                 let per_commitment_point = PublicKey::from_secret_key(secp_ctx, &per_commitment_key);
708                 let revocation_pubkey = chan_utils::derive_public_revocation_key(&secp_ctx, &per_commitment_point, &self.pubkeys().revocation_basepoint).map_err(|_| ())?;
709                 let witness_script = {
710                         let counterparty_htlcpubkey = chan_utils::derive_public_key(&secp_ctx, &per_commitment_point, &self.counterparty_pubkeys().htlc_basepoint).map_err(|_| ())?;
711                         let holder_htlcpubkey = chan_utils::derive_public_key(&secp_ctx, &per_commitment_point, &self.pubkeys().htlc_basepoint).map_err(|_| ())?;
712                         chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, self.opt_anchors(), &counterparty_htlcpubkey, &holder_htlcpubkey, &revocation_pubkey)
713                 };
714                 let mut sighash_parts = bip143::SigHashCache::new(justice_tx);
715                 let sighash = hash_to_message!(&sighash_parts.signature_hash(input, &witness_script, amount, SigHashType::All)[..]);
716                 return Ok(secp_ctx.sign(&sighash, &revocation_key))
717         }
718
719         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, ()> {
720                 if let Ok(htlc_key) = chan_utils::derive_private_key(&secp_ctx, &per_commitment_point, &self.htlc_base_key) {
721                         let witness_script = if let Ok(revocation_pubkey) = chan_utils::derive_public_revocation_key(&secp_ctx, &per_commitment_point, &self.pubkeys().revocation_basepoint) {
722                                 if let Ok(counterparty_htlcpubkey) = chan_utils::derive_public_key(&secp_ctx, &per_commitment_point, &self.counterparty_pubkeys().htlc_basepoint) {
723                                         if let Ok(htlcpubkey) = chan_utils::derive_public_key(&secp_ctx, &per_commitment_point, &self.pubkeys().htlc_basepoint) {
724                                                 chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, self.opt_anchors(), &counterparty_htlcpubkey, &htlcpubkey, &revocation_pubkey)
725                                         } else { return Err(()) }
726                                 } else { return Err(()) }
727                         } else { return Err(()) };
728                         let mut sighash_parts = bip143::SigHashCache::new(htlc_tx);
729                         let sighash = hash_to_message!(&sighash_parts.signature_hash(input, &witness_script, amount, SigHashType::All)[..]);
730                         return Ok(secp_ctx.sign(&sighash, &htlc_key))
731                 }
732                 Err(())
733         }
734
735         fn sign_closing_transaction(&self, closing_tx: &ClosingTransaction, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<Signature, ()> {
736                 let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
737                 let channel_funding_redeemscript = make_funding_redeemscript(&funding_pubkey, &self.counterparty_pubkeys().funding_pubkey);
738                 Ok(closing_tx.trust().sign(&self.funding_key, &channel_funding_redeemscript, self.channel_value_satoshis, secp_ctx))
739         }
740
741         fn sign_channel_announcement(&self, msg: &UnsignedChannelAnnouncement, secp_ctx: &Secp256k1<secp256k1::All>)
742         -> Result<(Signature, Signature), ()> {
743                 let msghash = hash_to_message!(&Sha256dHash::hash(&msg.encode()[..])[..]);
744                 Ok((secp_ctx.sign(&msghash, &self.node_secret), secp_ctx.sign(&msghash, &self.funding_key)))
745         }
746
747         fn ready_channel(&mut self, channel_parameters: &ChannelTransactionParameters) {
748                 assert!(self.channel_parameters.is_none(), "Acceptance already noted");
749                 assert!(channel_parameters.is_populated(), "Channel parameters must be fully populated");
750                 self.channel_parameters = Some(channel_parameters.clone());
751         }
752 }
753
754 const SERIALIZATION_VERSION: u8 = 1;
755 const MIN_SERIALIZATION_VERSION: u8 = 1;
756
757 impl Sign for InMemorySigner {}
758
759 impl Writeable for InMemorySigner {
760         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), Error> {
761                 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
762
763                 self.funding_key.write(writer)?;
764                 self.revocation_base_key.write(writer)?;
765                 self.payment_key.write(writer)?;
766                 self.delayed_payment_base_key.write(writer)?;
767                 self.htlc_base_key.write(writer)?;
768                 self.commitment_seed.write(writer)?;
769                 self.channel_parameters.write(writer)?;
770                 self.channel_value_satoshis.write(writer)?;
771                 self.channel_keys_id.write(writer)?;
772
773                 write_tlv_fields!(writer, {});
774
775                 Ok(())
776         }
777 }
778
779 impl ReadableArgs<SecretKey> for InMemorySigner {
780         fn read<R: io::Read>(reader: &mut R, node_secret: SecretKey) -> Result<Self, DecodeError> {
781                 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
782
783                 let funding_key = Readable::read(reader)?;
784                 let revocation_base_key = Readable::read(reader)?;
785                 let payment_key = Readable::read(reader)?;
786                 let delayed_payment_base_key = Readable::read(reader)?;
787                 let htlc_base_key = Readable::read(reader)?;
788                 let commitment_seed = Readable::read(reader)?;
789                 let counterparty_channel_data = Readable::read(reader)?;
790                 let channel_value_satoshis = Readable::read(reader)?;
791                 let secp_ctx = Secp256k1::signing_only();
792                 let holder_channel_pubkeys =
793                         InMemorySigner::make_holder_keys(&secp_ctx, &funding_key, &revocation_base_key,
794                                                              &payment_key, &delayed_payment_base_key,
795                                                              &htlc_base_key);
796                 let keys_id = Readable::read(reader)?;
797
798                 read_tlv_fields!(reader, {});
799
800                 Ok(InMemorySigner {
801                         funding_key,
802                         revocation_base_key,
803                         payment_key,
804                         delayed_payment_base_key,
805                         htlc_base_key,
806                         node_secret,
807                         commitment_seed,
808                         channel_value_satoshis,
809                         holder_channel_pubkeys,
810                         channel_parameters: counterparty_channel_data,
811                         channel_keys_id: keys_id,
812                 })
813         }
814 }
815
816 /// Simple KeysInterface implementor that takes a 32-byte seed for use as a BIP 32 extended key
817 /// and derives keys from that.
818 ///
819 /// Your node_id is seed/0'
820 /// ChannelMonitor closes may use seed/1'
821 /// Cooperative closes may use seed/2'
822 /// The two close keys may be needed to claim on-chain funds!
823 ///
824 /// This struct cannot be used for nodes that wish to support receiving phantom payments;
825 /// [`PhantomKeysManager`] must be used instead.
826 ///
827 /// Note that switching between this struct and [`PhantomKeysManager`] will invalidate any
828 /// previously issued invoices and attempts to pay previous invoices will fail.
829 pub struct KeysManager {
830         secp_ctx: Secp256k1<secp256k1::All>,
831         node_secret: SecretKey,
832         inbound_payment_key: KeyMaterial,
833         destination_script: Script,
834         shutdown_pubkey: PublicKey,
835         channel_master_key: ExtendedPrivKey,
836         channel_child_index: AtomicUsize,
837
838         rand_bytes_master_key: ExtendedPrivKey,
839         rand_bytes_child_index: AtomicUsize,
840         rand_bytes_unique_start: Sha256State,
841
842         seed: [u8; 32],
843         starting_time_secs: u64,
844         starting_time_nanos: u32,
845 }
846
847 impl KeysManager {
848         /// Constructs a KeysManager from a 32-byte seed. If the seed is in some way biased (eg your
849         /// CSRNG is busted) this may panic (but more importantly, you will possibly lose funds).
850         /// starting_time isn't strictly required to actually be a time, but it must absolutely,
851         /// without a doubt, be unique to this instance. ie if you start multiple times with the same
852         /// seed, starting_time must be unique to each run. Thus, the easiest way to achieve this is to
853         /// simply use the current time (with very high precision).
854         ///
855         /// The seed MUST be backed up safely prior to use so that the keys can be re-created, however,
856         /// obviously, starting_time should be unique every time you reload the library - it is only
857         /// used to generate new ephemeral key data (which will be stored by the individual channel if
858         /// necessary).
859         ///
860         /// Note that the seed is required to recover certain on-chain funds independent of
861         /// ChannelMonitor data, though a current copy of ChannelMonitor data is also required for any
862         /// channel, and some on-chain during-closing funds.
863         ///
864         /// Note that until the 0.1 release there is no guarantee of backward compatibility between
865         /// versions. Once the library is more fully supported, the docs will be updated to include a
866         /// detailed description of the guarantee.
867         pub fn new(seed: &[u8; 32], starting_time_secs: u64, starting_time_nanos: u32) -> Self {
868                 let secp_ctx = Secp256k1::new();
869                 // Note that when we aren't serializing the key, network doesn't matter
870                 match ExtendedPrivKey::new_master(Network::Testnet, seed) {
871                         Ok(master_key) => {
872                                 let node_secret = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(0).unwrap()).expect("Your RNG is busted").private_key.key;
873                                 let destination_script = match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(1).unwrap()) {
874                                         Ok(destination_key) => {
875                                                 let wpubkey_hash = WPubkeyHash::hash(&ExtendedPubKey::from_private(&secp_ctx, &destination_key).public_key.to_bytes());
876                                                 Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0)
877                                                               .push_slice(&wpubkey_hash.into_inner())
878                                                               .into_script()
879                                         },
880                                         Err(_) => panic!("Your RNG is busted"),
881                                 };
882                                 let shutdown_pubkey = match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(2).unwrap()) {
883                                         Ok(shutdown_key) => ExtendedPubKey::from_private(&secp_ctx, &shutdown_key).public_key.key,
884                                         Err(_) => panic!("Your RNG is busted"),
885                                 };
886                                 let channel_master_key = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(3).unwrap()).expect("Your RNG is busted");
887                                 let rand_bytes_master_key = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(4).unwrap()).expect("Your RNG is busted");
888                                 let inbound_payment_key: SecretKey = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(5).unwrap()).expect("Your RNG is busted").private_key.key;
889                                 let mut inbound_pmt_key_bytes = [0; 32];
890                                 inbound_pmt_key_bytes.copy_from_slice(&inbound_payment_key[..]);
891
892                                 let mut rand_bytes_unique_start = Sha256::engine();
893                                 rand_bytes_unique_start.input(&byte_utils::be64_to_array(starting_time_secs));
894                                 rand_bytes_unique_start.input(&byte_utils::be32_to_array(starting_time_nanos));
895                                 rand_bytes_unique_start.input(seed);
896
897                                 let mut res = KeysManager {
898                                         secp_ctx,
899                                         node_secret,
900                                         inbound_payment_key: KeyMaterial(inbound_pmt_key_bytes),
901
902                                         destination_script,
903                                         shutdown_pubkey,
904
905                                         channel_master_key,
906                                         channel_child_index: AtomicUsize::new(0),
907
908                                         rand_bytes_master_key,
909                                         rand_bytes_child_index: AtomicUsize::new(0),
910                                         rand_bytes_unique_start,
911
912                                         seed: *seed,
913                                         starting_time_secs,
914                                         starting_time_nanos,
915                                 };
916                                 let secp_seed = res.get_secure_random_bytes();
917                                 res.secp_ctx.seeded_randomize(&secp_seed);
918                                 res
919                         },
920                         Err(_) => panic!("Your rng is busted"),
921                 }
922         }
923         /// Derive an old Sign containing per-channel secrets based on a key derivation parameters.
924         ///
925         /// Key derivation parameters are accessible through a per-channel secrets
926         /// Sign::channel_keys_id and is provided inside DynamicOuputP2WSH in case of
927         /// onchain output detection for which a corresponding delayed_payment_key must be derived.
928         pub fn derive_channel_keys(&self, channel_value_satoshis: u64, params: &[u8; 32]) -> InMemorySigner {
929                 let chan_id = byte_utils::slice_to_be64(&params[0..8]);
930                 assert!(chan_id <= core::u32::MAX as u64); // Otherwise the params field wasn't created by us
931                 let mut unique_start = Sha256::engine();
932                 unique_start.input(params);
933                 unique_start.input(&self.seed);
934
935                 // We only seriously intend to rely on the channel_master_key for true secure
936                 // entropy, everything else just ensures uniqueness. We rely on the unique_start (ie
937                 // starting_time provided in the constructor) to be unique.
938                 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");
939                 unique_start.input(&child_privkey.private_key.key[..]);
940
941                 let seed = Sha256::from_engine(unique_start).into_inner();
942
943                 let commitment_seed = {
944                         let mut sha = Sha256::engine();
945                         sha.input(&seed);
946                         sha.input(&b"commitment seed"[..]);
947                         Sha256::from_engine(sha).into_inner()
948                 };
949                 macro_rules! key_step {
950                         ($info: expr, $prev_key: expr) => {{
951                                 let mut sha = Sha256::engine();
952                                 sha.input(&seed);
953                                 sha.input(&$prev_key[..]);
954                                 sha.input(&$info[..]);
955                                 SecretKey::from_slice(&Sha256::from_engine(sha).into_inner()).expect("SHA-256 is busted")
956                         }}
957                 }
958                 let funding_key = key_step!(b"funding key", commitment_seed);
959                 let revocation_base_key = key_step!(b"revocation base key", funding_key);
960                 let payment_key = key_step!(b"payment key", revocation_base_key);
961                 let delayed_payment_base_key = key_step!(b"delayed payment base key", payment_key);
962                 let htlc_base_key = key_step!(b"HTLC base key", delayed_payment_base_key);
963
964                 InMemorySigner::new(
965                         &self.secp_ctx,
966                         self.node_secret,
967                         funding_key,
968                         revocation_base_key,
969                         payment_key,
970                         delayed_payment_base_key,
971                         htlc_base_key,
972                         commitment_seed,
973                         channel_value_satoshis,
974                         params.clone()
975                 )
976         }
977
978         /// Creates a Transaction which spends the given descriptors to the given outputs, plus an
979         /// output to the given change destination (if sufficient change value remains). The
980         /// transaction will have a feerate, at least, of the given value.
981         ///
982         /// Returns `Err(())` if the output value is greater than the input value minus required fee,
983         /// if a descriptor was duplicated, or if an output descriptor `script_pubkey`
984         /// does not match the one we can spend.
985         ///
986         /// We do not enforce that outputs meet the dust limit or that any output scripts are standard.
987         ///
988         /// May panic if the `SpendableOutputDescriptor`s were not generated by Channels which used
989         /// this KeysManager or one of the `InMemorySigner` created by this KeysManager.
990         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, ()> {
991                 let mut input = Vec::new();
992                 let mut input_value = 0;
993                 let mut witness_weight = 0;
994                 let mut output_set = HashSet::with_capacity(descriptors.len());
995                 for outp in descriptors {
996                         match outp {
997                                 SpendableOutputDescriptor::StaticPaymentOutput(descriptor) => {
998                                         input.push(TxIn {
999                                                 previous_output: descriptor.outpoint.into_bitcoin_outpoint(),
1000                                                 script_sig: Script::new(),
1001                                                 sequence: 0,
1002                                                 witness: Vec::new(),
1003                                         });
1004                                         witness_weight += StaticPaymentOutputDescriptor::MAX_WITNESS_LENGTH;
1005                                         input_value += descriptor.output.value;
1006                                         if !output_set.insert(descriptor.outpoint) { return Err(()); }
1007                                 },
1008                                 SpendableOutputDescriptor::DelayedPaymentOutput(descriptor) => {
1009                                         input.push(TxIn {
1010                                                 previous_output: descriptor.outpoint.into_bitcoin_outpoint(),
1011                                                 script_sig: Script::new(),
1012                                                 sequence: descriptor.to_self_delay as u32,
1013                                                 witness: Vec::new(),
1014                                         });
1015                                         witness_weight += DelayedPaymentOutputDescriptor::MAX_WITNESS_LENGTH;
1016                                         input_value += descriptor.output.value;
1017                                         if !output_set.insert(descriptor.outpoint) { return Err(()); }
1018                                 },
1019                                 SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output } => {
1020                                         input.push(TxIn {
1021                                                 previous_output: outpoint.into_bitcoin_outpoint(),
1022                                                 script_sig: Script::new(),
1023                                                 sequence: 0,
1024                                                 witness: Vec::new(),
1025                                         });
1026                                         witness_weight += 1 + 73 + 34;
1027                                         input_value += output.value;
1028                                         if !output_set.insert(*outpoint) { return Err(()); }
1029                                 }
1030                         }
1031                         if input_value > MAX_VALUE_MSAT / 1000 { return Err(()); }
1032                 }
1033                 let mut spend_tx = Transaction {
1034                         version: 2,
1035                         lock_time: 0,
1036                         input,
1037                         output: outputs,
1038                 };
1039                 let expected_max_weight =
1040                         transaction_utils::maybe_add_change_output(&mut spend_tx, input_value, witness_weight, feerate_sat_per_1000_weight, change_destination_script)?;
1041
1042                 let mut keys_cache: Option<(InMemorySigner, [u8; 32])> = None;
1043                 let mut input_idx = 0;
1044                 for outp in descriptors {
1045                         match outp {
1046                                 SpendableOutputDescriptor::StaticPaymentOutput(descriptor) => {
1047                                         if keys_cache.is_none() || keys_cache.as_ref().unwrap().1 != descriptor.channel_keys_id {
1048                                                 keys_cache = Some((
1049                                                         self.derive_channel_keys(descriptor.channel_value_satoshis, &descriptor.channel_keys_id),
1050                                                         descriptor.channel_keys_id));
1051                                         }
1052                                         spend_tx.input[input_idx].witness = keys_cache.as_ref().unwrap().0.sign_counterparty_payment_input(&spend_tx, input_idx, &descriptor, &secp_ctx)?;
1053                                 },
1054                                 SpendableOutputDescriptor::DelayedPaymentOutput(descriptor) => {
1055                                         if keys_cache.is_none() || keys_cache.as_ref().unwrap().1 != descriptor.channel_keys_id {
1056                                                 keys_cache = Some((
1057                                                         self.derive_channel_keys(descriptor.channel_value_satoshis, &descriptor.channel_keys_id),
1058                                                         descriptor.channel_keys_id));
1059                                         }
1060                                         spend_tx.input[input_idx].witness = keys_cache.as_ref().unwrap().0.sign_dynamic_p2wsh_input(&spend_tx, input_idx, &descriptor, &secp_ctx)?;
1061                                 },
1062                                 SpendableOutputDescriptor::StaticOutput { ref output, .. } => {
1063                                         let derivation_idx = if output.script_pubkey == self.destination_script {
1064                                                 1
1065                                         } else {
1066                                                 2
1067                                         };
1068                                         let secret = {
1069                                                 // Note that when we aren't serializing the key, network doesn't matter
1070                                                 match ExtendedPrivKey::new_master(Network::Testnet, &self.seed) {
1071                                                         Ok(master_key) => {
1072                                                                 match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(derivation_idx).expect("key space exhausted")) {
1073                                                                         Ok(key) => key,
1074                                                                         Err(_) => panic!("Your RNG is busted"),
1075                                                                 }
1076                                                         }
1077                                                         Err(_) => panic!("Your rng is busted"),
1078                                                 }
1079                                         };
1080                                         let pubkey = ExtendedPubKey::from_private(&secp_ctx, &secret).public_key;
1081                                         if derivation_idx == 2 {
1082                                                 assert_eq!(pubkey.key, self.shutdown_pubkey);
1083                                         }
1084                                         let witness_script = bitcoin::Address::p2pkh(&pubkey, Network::Testnet).script_pubkey();
1085                                         let payment_script = bitcoin::Address::p2wpkh(&pubkey, Network::Testnet).expect("uncompressed key found").script_pubkey();
1086
1087                                         if payment_script != output.script_pubkey { return Err(()); };
1088
1089                                         let sighash = hash_to_message!(&bip143::SigHashCache::new(&spend_tx).signature_hash(input_idx, &witness_script, output.value, SigHashType::All)[..]);
1090                                         let sig = secp_ctx.sign(&sighash, &secret.private_key.key);
1091                                         spend_tx.input[input_idx].witness.push(sig.serialize_der().to_vec());
1092                                         spend_tx.input[input_idx].witness[0].push(SigHashType::All as u8);
1093                                         spend_tx.input[input_idx].witness.push(pubkey.key.serialize().to_vec());
1094                                 },
1095                         }
1096                         input_idx += 1;
1097                 }
1098
1099                 debug_assert!(expected_max_weight >= spend_tx.get_weight());
1100                 // Note that witnesses with a signature vary somewhat in size, so allow
1101                 // `expected_max_weight` to overshoot by up to 3 bytes per input.
1102                 debug_assert!(expected_max_weight <= spend_tx.get_weight() + descriptors.len() * 3);
1103
1104                 Ok(spend_tx)
1105         }
1106 }
1107
1108 impl KeysInterface for KeysManager {
1109         type Signer = InMemorySigner;
1110
1111         fn get_node_secret(&self) -> SecretKey {
1112                 self.node_secret.clone()
1113         }
1114
1115         fn get_inbound_payment_key_material(&self) -> KeyMaterial {
1116                 self.inbound_payment_key.clone()
1117         }
1118
1119         fn get_destination_script(&self) -> Script {
1120                 self.destination_script.clone()
1121         }
1122
1123         fn get_shutdown_scriptpubkey(&self) -> ShutdownScript {
1124                 ShutdownScript::new_p2wpkh_from_pubkey(self.shutdown_pubkey.clone())
1125         }
1126
1127         fn get_channel_signer(&self, _inbound: bool, channel_value_satoshis: u64) -> Self::Signer {
1128                 let child_ix = self.channel_child_index.fetch_add(1, Ordering::AcqRel);
1129                 assert!(child_ix <= core::u32::MAX as usize);
1130                 let mut id = [0; 32];
1131                 id[0..8].copy_from_slice(&byte_utils::be64_to_array(child_ix as u64));
1132                 id[8..16].copy_from_slice(&byte_utils::be64_to_array(self.starting_time_nanos as u64));
1133                 id[16..24].copy_from_slice(&byte_utils::be64_to_array(self.starting_time_secs));
1134                 self.derive_channel_keys(channel_value_satoshis, &id)
1135         }
1136
1137         fn get_secure_random_bytes(&self) -> [u8; 32] {
1138                 let mut sha = self.rand_bytes_unique_start.clone();
1139
1140                 let child_ix = self.rand_bytes_child_index.fetch_add(1, Ordering::AcqRel);
1141                 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");
1142                 sha.input(&child_privkey.private_key.key[..]);
1143
1144                 sha.input(b"Unique Secure Random Bytes Salt");
1145                 Sha256::from_engine(sha).into_inner()
1146         }
1147
1148         fn read_chan_signer(&self, reader: &[u8]) -> Result<Self::Signer, DecodeError> {
1149                 InMemorySigner::read(&mut io::Cursor::new(reader), self.get_node_secret())
1150         }
1151
1152         fn sign_invoice(&self, hrp_bytes: &[u8], invoice_data: &[u5]) -> Result<RecoverableSignature, ()> {
1153                 let preimage = construct_invoice_preimage(&hrp_bytes, &invoice_data);
1154                 Ok(self.secp_ctx.sign_recoverable(&hash_to_message!(&Sha256::hash(&preimage)), &self.get_node_secret()))
1155         }
1156 }
1157
1158 /// Similar to [`KeysManager`], but allows the node using this struct to receive phantom node
1159 /// payments.
1160 ///
1161 /// A phantom node payment is a payment made to a phantom invoice, which is an invoice that can be
1162 /// paid to one of multiple nodes. This works because we encode the invoice route hints such that
1163 /// LDK will recognize an incoming payment as destined for a phantom node, and collect the payment
1164 /// itself without ever needing to forward to this fake node.
1165 ///
1166 /// Phantom node payments are useful for load balancing between multiple LDK nodes. They also
1167 /// provide some fault tolerance, because payers will automatically retry paying other provided
1168 /// nodes in the case that one node goes down.
1169 ///
1170 /// Note that multi-path payments are not supported in phantom invoices for security reasons.
1171 //  In the hypothetical case that we did support MPP phantom payments, there would be no way for
1172 //  nodes to know when the full payment has been received (and the preimage can be released) without
1173 //  significantly compromising on our safety guarantees. I.e., if we expose the ability for the user
1174 //  to tell LDK when the preimage can be released, we open ourselves to attacks where the preimage
1175 //  is released too early.
1176 //
1177 /// Switching between this struct and [`KeysManager`] will invalidate any previously issued
1178 /// invoices and attempts to pay previous invoices will fail.
1179 pub struct PhantomKeysManager {
1180         inner: KeysManager,
1181         inbound_payment_key: KeyMaterial,
1182         phantom_secret: SecretKey,
1183 }
1184
1185 impl KeysInterface for PhantomKeysManager {
1186         type Signer = InMemorySigner;
1187
1188         fn get_node_secret(&self) -> SecretKey {
1189                 self.inner.get_node_secret()
1190         }
1191
1192         fn get_inbound_payment_key_material(&self) -> KeyMaterial {
1193                 self.inbound_payment_key.clone()
1194         }
1195
1196         fn get_destination_script(&self) -> Script {
1197                 self.inner.get_destination_script()
1198         }
1199
1200         fn get_shutdown_scriptpubkey(&self) -> ShutdownScript {
1201                 self.inner.get_shutdown_scriptpubkey()
1202         }
1203
1204         fn get_channel_signer(&self, inbound: bool, channel_value_satoshis: u64) -> Self::Signer {
1205                 self.inner.get_channel_signer(inbound, channel_value_satoshis)
1206         }
1207
1208         fn get_secure_random_bytes(&self) -> [u8; 32] {
1209                 self.inner.get_secure_random_bytes()
1210         }
1211
1212         fn read_chan_signer(&self, reader: &[u8]) -> Result<Self::Signer, DecodeError> {
1213                 self.inner.read_chan_signer(reader)
1214         }
1215
1216         fn sign_invoice(&self, hrp_bytes: &[u8], invoice_data: &[u5]) -> Result<RecoverableSignature, ()> {
1217                 let preimage = construct_invoice_preimage(&hrp_bytes, &invoice_data);
1218                 Ok(self.inner.secp_ctx.sign_recoverable(&hash_to_message!(&Sha256::hash(&preimage)), &self.get_node_secret()))
1219         }
1220 }
1221
1222 impl PhantomKeysManager {
1223         /// Constructs a `PhantomKeysManager` given a 32-byte seed and an additional `cross_node_seed`
1224         /// that is shared across all nodes that intend to participate in [phantom node payments] together.
1225         ///
1226         /// See [`KeysManager::new`] for more information on `seed`, `starting_time_secs`, and
1227         /// `starting_time_nanos`.
1228         ///
1229         /// `cross_node_seed` must be the same across all phantom payment-receiving nodes and also the
1230         /// same across restarts, or else inbound payments may fail.
1231         ///
1232         /// [phantom node payments]: PhantomKeysManager
1233         pub fn new(seed: &[u8; 32], starting_time_secs: u64, starting_time_nanos: u32, cross_node_seed: &[u8; 32]) -> Self {
1234                 let inner = KeysManager::new(seed, starting_time_secs, starting_time_nanos);
1235                 let (inbound_key, phantom_key) = hkdf_extract_expand_twice(b"LDK Inbound and Phantom Payment Key Expansion", cross_node_seed);
1236                 Self {
1237                         inner,
1238                         inbound_payment_key: KeyMaterial(inbound_key),
1239                         phantom_secret: SecretKey::from_slice(&phantom_key).unwrap(),
1240                 }
1241         }
1242
1243         /// See [`KeysManager::spend_spendable_outputs`] for documentation on this method.
1244         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, ()> {
1245                 self.inner.spend_spendable_outputs(descriptors, outputs, change_destination_script, feerate_sat_per_1000_weight, secp_ctx)
1246         }
1247
1248         /// See [`KeysManager::derive_channel_keys`] for documentation on this method.
1249         pub fn derive_channel_keys(&self, channel_value_satoshis: u64, params: &[u8; 32]) -> InMemorySigner {
1250                 self.inner.derive_channel_keys(channel_value_satoshis, params)
1251         }
1252 }
1253
1254 // Ensure that BaseSign can have a vtable
1255 #[test]
1256 pub fn dyn_sign() {
1257         let _signer: Box<dyn BaseSign>;
1258 }