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