Merge pull request #1867 from wpaulino/remove-signer-persistence
[rust-lightning] / lightning / src / ln / chan_utils.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 //! Various utilities for building scripts and deriving keys related to channels. These are
11 //! largely of interest for those implementing chain::keysinterface::Sign message signing by hand.
12
13 use bitcoin::blockdata::script::{Script,Builder};
14 use bitcoin::blockdata::opcodes;
15 use bitcoin::blockdata::transaction::{TxIn,TxOut,OutPoint,Transaction, EcdsaSighashType};
16 use bitcoin::util::sighash;
17 use bitcoin::util::address::Payload;
18
19 use bitcoin::hashes::{Hash, HashEngine};
20 use bitcoin::hashes::sha256::Hash as Sha256;
21 use bitcoin::hashes::ripemd160::Hash as Ripemd160;
22 use bitcoin::hash_types::{Txid, PubkeyHash};
23
24 use crate::ln::{PaymentHash, PaymentPreimage};
25 use crate::ln::msgs::DecodeError;
26 use crate::util::ser::{Readable, Writeable, Writer};
27 use crate::util::transaction_utils;
28
29 use bitcoin::secp256k1::{SecretKey, PublicKey, Scalar};
30 use bitcoin::secp256k1::{Secp256k1, ecdsa::Signature, Message};
31 use bitcoin::{PackedLockTime, secp256k1, Sequence, Witness};
32 use bitcoin::PublicKey as BitcoinPublicKey;
33
34 use crate::io;
35 use crate::prelude::*;
36 use core::cmp;
37 use crate::ln::chan_utils;
38 use crate::util::transaction_utils::sort_outputs;
39 use crate::ln::channel::{INITIAL_COMMITMENT_NUMBER, ANCHOR_OUTPUT_VALUE_SATOSHI};
40 use core::ops::Deref;
41 use crate::chain;
42 use crate::util::crypto::sign;
43
44 /// Maximum number of one-way in-flight HTLC (protocol-level value).
45 pub const MAX_HTLCS: u16 = 483;
46 /// The weight of a BIP141 witnessScript for a BOLT3's "offered HTLC output" on a commitment transaction, non-anchor variant.
47 pub const OFFERED_HTLC_SCRIPT_WEIGHT: usize = 133;
48 /// The weight of a BIP141 witnessScript for a BOLT3's "offered HTLC output" on a commitment transaction, anchor variant.
49 pub const OFFERED_HTLC_SCRIPT_WEIGHT_ANCHORS: usize = 136;
50
51 /// The weight of a BIP141 witnessScript for a BOLT3's "received HTLC output" can vary in function of its CLTV argument value.
52 /// We define a range that encompasses both its non-anchors and anchors variants.
53 pub(crate) const MIN_ACCEPTED_HTLC_SCRIPT_WEIGHT: usize = 136;
54 /// The weight of a BIP141 witnessScript for a BOLT3's "received HTLC output" can vary in function of its CLTV argument value.
55 /// We define a range that encompasses both its non-anchors and anchors variants.
56 /// This is the maximum post-anchor value.
57 pub const MAX_ACCEPTED_HTLC_SCRIPT_WEIGHT: usize = 143;
58
59 /// Gets the weight for an HTLC-Success transaction.
60 #[inline]
61 pub fn htlc_success_tx_weight(opt_anchors: bool) -> u64 {
62         const HTLC_SUCCESS_TX_WEIGHT: u64 = 703;
63         const HTLC_SUCCESS_ANCHOR_TX_WEIGHT: u64 = 706;
64         if opt_anchors { HTLC_SUCCESS_ANCHOR_TX_WEIGHT } else { HTLC_SUCCESS_TX_WEIGHT }
65 }
66
67 /// Gets the weight for an HTLC-Timeout transaction.
68 #[inline]
69 pub fn htlc_timeout_tx_weight(opt_anchors: bool) -> u64 {
70         const HTLC_TIMEOUT_TX_WEIGHT: u64 = 663;
71         const HTLC_TIMEOUT_ANCHOR_TX_WEIGHT: u64 = 666;
72         if opt_anchors { HTLC_TIMEOUT_ANCHOR_TX_WEIGHT } else { HTLC_TIMEOUT_TX_WEIGHT }
73 }
74
75 /// Describes the type of HTLC claim as determined by analyzing the witness.
76 #[derive(PartialEq, Eq)]
77 pub enum HTLCClaim {
78         /// Claims an offered output on a commitment transaction through the timeout path.
79         OfferedTimeout,
80         /// Claims an offered output on a commitment transaction through the success path.
81         OfferedPreimage,
82         /// Claims an accepted output on a commitment transaction through the timeout path.
83         AcceptedTimeout,
84         /// Claims an accepted output on a commitment transaction through the success path.
85         AcceptedPreimage,
86         /// Claims an offered/accepted output on a commitment transaction through the revocation path.
87         Revocation,
88 }
89
90 impl HTLCClaim {
91         /// Check if a given input witness attempts to claim a HTLC.
92         pub fn from_witness(witness: &Witness) -> Option<Self> {
93                 debug_assert_eq!(OFFERED_HTLC_SCRIPT_WEIGHT_ANCHORS, MIN_ACCEPTED_HTLC_SCRIPT_WEIGHT);
94                 if witness.len() < 2 {
95                         return None;
96                 }
97                 let witness_script = witness.last().unwrap();
98                 let second_to_last = witness.second_to_last().unwrap();
99                 if witness_script.len() == OFFERED_HTLC_SCRIPT_WEIGHT {
100                         if witness.len() == 3 && second_to_last.len() == 33 {
101                                 // <revocation sig> <revocationpubkey> <witness_script>
102                                 Some(Self::Revocation)
103                         } else if witness.len() == 3 && second_to_last.len() == 32 {
104                                 // <remotehtlcsig> <payment_preimage> <witness_script>
105                                 Some(Self::OfferedPreimage)
106                         } else if witness.len() == 5 && second_to_last.len() == 0 {
107                                 // 0 <remotehtlcsig> <localhtlcsig> <> <witness_script>
108                                 Some(Self::OfferedTimeout)
109                         } else {
110                                 None
111                         }
112                 } else if witness_script.len() == OFFERED_HTLC_SCRIPT_WEIGHT_ANCHORS {
113                         // It's possible for the weight of `offered_htlc_script` and `accepted_htlc_script` to
114                         // match so we check for both here.
115                         if witness.len() == 3 && second_to_last.len() == 33 {
116                                 // <revocation sig> <revocationpubkey> <witness_script>
117                                 Some(Self::Revocation)
118                         } else if witness.len() == 3 && second_to_last.len() == 32 {
119                                 // <remotehtlcsig> <payment_preimage> <witness_script>
120                                 Some(Self::OfferedPreimage)
121                         } else if witness.len() == 5 && second_to_last.len() == 0 {
122                                 // 0 <remotehtlcsig> <localhtlcsig> <> <witness_script>
123                                 Some(Self::OfferedTimeout)
124                         } else if witness.len() == 3 && second_to_last.len() == 0 {
125                                 // <remotehtlcsig> <> <witness_script>
126                                 Some(Self::AcceptedTimeout)
127                         } else if witness.len() == 5 && second_to_last.len() == 32 {
128                                 // 0 <remotehtlcsig> <localhtlcsig> <payment_preimage> <witness_script>
129                                 Some(Self::AcceptedPreimage)
130                         } else {
131                                 None
132                         }
133                 } else if witness_script.len() > MIN_ACCEPTED_HTLC_SCRIPT_WEIGHT &&
134                         witness_script.len() <= MAX_ACCEPTED_HTLC_SCRIPT_WEIGHT {
135                         // Handle remaining range of ACCEPTED_HTLC_SCRIPT_WEIGHT.
136                         if witness.len() == 3 && second_to_last.len() == 33 {
137                                 // <revocation sig> <revocationpubkey> <witness_script>
138                                 Some(Self::Revocation)
139                         } else if witness.len() == 3 && second_to_last.len() == 0 {
140                                 // <remotehtlcsig> <> <witness_script>
141                                 Some(Self::AcceptedTimeout)
142                         } else if witness.len() == 5 && second_to_last.len() == 32 {
143                                 // 0 <remotehtlcsig> <localhtlcsig> <payment_preimage> <witness_script>
144                                 Some(Self::AcceptedPreimage)
145                         } else {
146                                 None
147                         }
148                 } else {
149                         None
150                 }
151         }
152 }
153
154 // Various functions for key derivation and transaction creation for use within channels. Primarily
155 // used in Channel and ChannelMonitor.
156
157 /// Build the commitment secret from the seed and the commitment number
158 pub fn build_commitment_secret(commitment_seed: &[u8; 32], idx: u64) -> [u8; 32] {
159         let mut res: [u8; 32] = commitment_seed.clone();
160         for i in 0..48 {
161                 let bitpos = 47 - i;
162                 if idx & (1 << bitpos) == (1 << bitpos) {
163                         res[bitpos / 8] ^= 1 << (bitpos & 7);
164                         res = Sha256::hash(&res).into_inner();
165                 }
166         }
167         res
168 }
169
170 /// Build a closing transaction
171 pub fn build_closing_transaction(to_holder_value_sat: u64, to_counterparty_value_sat: u64, to_holder_script: Script, to_counterparty_script: Script, funding_outpoint: OutPoint) -> Transaction {
172         let txins = {
173                 let mut ins: Vec<TxIn> = Vec::new();
174                 ins.push(TxIn {
175                         previous_output: funding_outpoint,
176                         script_sig: Script::new(),
177                         sequence: Sequence::MAX,
178                         witness: Witness::new(),
179                 });
180                 ins
181         };
182
183         let mut txouts: Vec<(TxOut, ())> = Vec::new();
184
185         if to_counterparty_value_sat > 0 {
186                 txouts.push((TxOut {
187                         script_pubkey: to_counterparty_script,
188                         value: to_counterparty_value_sat
189                 }, ()));
190         }
191
192         if to_holder_value_sat > 0 {
193                 txouts.push((TxOut {
194                         script_pubkey: to_holder_script,
195                         value: to_holder_value_sat
196                 }, ()));
197         }
198
199         transaction_utils::sort_outputs(&mut txouts, |_, _| { cmp::Ordering::Equal }); // Ordering doesnt matter if they used our pubkey...
200
201         let mut outputs: Vec<TxOut> = Vec::new();
202         for out in txouts.drain(..) {
203                 outputs.push(out.0);
204         }
205
206         Transaction {
207                 version: 2,
208                 lock_time: PackedLockTime::ZERO,
209                 input: txins,
210                 output: outputs,
211         }
212 }
213
214 /// Implements the per-commitment secret storage scheme from
215 /// [BOLT 3](https://github.com/lightning/bolts/blob/dcbf8583976df087c79c3ce0b535311212e6812d/03-transactions.md#efficient-per-commitment-secret-storage).
216 ///
217 /// Allows us to keep track of all of the revocation secrets of our counterparty in just 50*32 bytes
218 /// or so.
219 #[derive(Clone)]
220 pub struct CounterpartyCommitmentSecrets {
221         old_secrets: [([u8; 32], u64); 49],
222 }
223
224 impl Eq for CounterpartyCommitmentSecrets {}
225 impl PartialEq for CounterpartyCommitmentSecrets {
226         fn eq(&self, other: &Self) -> bool {
227                 for (&(ref secret, ref idx), &(ref o_secret, ref o_idx)) in self.old_secrets.iter().zip(other.old_secrets.iter()) {
228                         if secret != o_secret || idx != o_idx {
229                                 return false
230                         }
231                 }
232                 true
233         }
234 }
235
236 impl CounterpartyCommitmentSecrets {
237         /// Creates a new empty `CounterpartyCommitmentSecrets` structure.
238         pub fn new() -> Self {
239                 Self { old_secrets: [([0; 32], 1 << 48); 49], }
240         }
241
242         #[inline]
243         fn place_secret(idx: u64) -> u8 {
244                 for i in 0..48 {
245                         if idx & (1 << i) == (1 << i) {
246                                 return i
247                         }
248                 }
249                 48
250         }
251
252         /// Returns the minimum index of all stored secrets. Note that indexes start
253         /// at 1 << 48 and get decremented by one for each new secret.
254         pub fn get_min_seen_secret(&self) -> u64 {
255                 //TODO This can be optimized?
256                 let mut min = 1 << 48;
257                 for &(_, idx) in self.old_secrets.iter() {
258                         if idx < min {
259                                 min = idx;
260                         }
261                 }
262                 min
263         }
264
265         #[inline]
266         fn derive_secret(secret: [u8; 32], bits: u8, idx: u64) -> [u8; 32] {
267                 let mut res: [u8; 32] = secret;
268                 for i in 0..bits {
269                         let bitpos = bits - 1 - i;
270                         if idx & (1 << bitpos) == (1 << bitpos) {
271                                 res[(bitpos / 8) as usize] ^= 1 << (bitpos & 7);
272                                 res = Sha256::hash(&res).into_inner();
273                         }
274                 }
275                 res
276         }
277
278         /// Inserts the `secret` at `idx`. Returns `Ok(())` if the secret
279         /// was generated in accordance with BOLT 3 and is consistent with previous secrets.
280         pub fn provide_secret(&mut self, idx: u64, secret: [u8; 32]) -> Result<(), ()> {
281                 let pos = Self::place_secret(idx);
282                 for i in 0..pos {
283                         let (old_secret, old_idx) = self.old_secrets[i as usize];
284                         if Self::derive_secret(secret, pos, old_idx) != old_secret {
285                                 return Err(());
286                         }
287                 }
288                 if self.get_min_seen_secret() <= idx {
289                         return Ok(());
290                 }
291                 self.old_secrets[pos as usize] = (secret, idx);
292                 Ok(())
293         }
294
295         /// Returns the secret at `idx`.
296         /// Returns `None` if `idx` is < [`CounterpartyCommitmentSecrets::get_min_seen_secret`].
297         pub fn get_secret(&self, idx: u64) -> Option<[u8; 32]> {
298                 for i in 0..self.old_secrets.len() {
299                         if (idx & (!((1 << i) - 1))) == self.old_secrets[i].1 {
300                                 return Some(Self::derive_secret(self.old_secrets[i].0, i as u8, idx))
301                         }
302                 }
303                 assert!(idx < self.get_min_seen_secret());
304                 None
305         }
306 }
307
308 impl Writeable for CounterpartyCommitmentSecrets {
309         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
310                 for &(ref secret, ref idx) in self.old_secrets.iter() {
311                         writer.write_all(secret)?;
312                         writer.write_all(&idx.to_be_bytes())?;
313                 }
314                 write_tlv_fields!(writer, {});
315                 Ok(())
316         }
317 }
318 impl Readable for CounterpartyCommitmentSecrets {
319         fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
320                 let mut old_secrets = [([0; 32], 1 << 48); 49];
321                 for &mut (ref mut secret, ref mut idx) in old_secrets.iter_mut() {
322                         *secret = Readable::read(reader)?;
323                         *idx = Readable::read(reader)?;
324                 }
325                 read_tlv_fields!(reader, {});
326                 Ok(Self { old_secrets })
327         }
328 }
329
330 /// Derives a per-commitment-transaction private key (eg an htlc key or delayed_payment key)
331 /// from the base secret and the per_commitment_point.
332 pub fn derive_private_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, base_secret: &SecretKey) -> SecretKey {
333         let mut sha = Sha256::engine();
334         sha.input(&per_commitment_point.serialize());
335         sha.input(&PublicKey::from_secret_key(&secp_ctx, &base_secret).serialize());
336         let res = Sha256::from_engine(sha).into_inner();
337
338         base_secret.clone().add_tweak(&Scalar::from_be_bytes(res).unwrap())
339                 .expect("Addition only fails if the tweak is the inverse of the key. This is not possible when the tweak contains the hash of the key.")
340 }
341
342 /// Derives a per-commitment-transaction public key (eg an htlc key or a delayed_payment key)
343 /// from the base point and the per_commitment_key. This is the public equivalent of
344 /// derive_private_key - using only public keys to derive a public key instead of private keys.
345 pub fn derive_public_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, base_point: &PublicKey) -> PublicKey {
346         let mut sha = Sha256::engine();
347         sha.input(&per_commitment_point.serialize());
348         sha.input(&base_point.serialize());
349         let res = Sha256::from_engine(sha).into_inner();
350
351         let hashkey = PublicKey::from_secret_key(&secp_ctx,
352                 &SecretKey::from_slice(&res).expect("Hashes should always be valid keys unless SHA-256 is broken"));
353         base_point.combine(&hashkey)
354                 .expect("Addition only fails if the tweak is the inverse of the key. This is not possible when the tweak contains the hash of the key.")
355 }
356
357 /// Derives a per-commitment-transaction revocation key from its constituent parts.
358 ///
359 /// Only the cheating participant owns a valid witness to propagate a revoked
360 /// commitment transaction, thus per_commitment_secret always come from cheater
361 /// and revocation_base_secret always come from punisher, which is the broadcaster
362 /// of the transaction spending with this key knowledge.
363 pub fn derive_private_revocation_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>,
364         per_commitment_secret: &SecretKey, countersignatory_revocation_base_secret: &SecretKey)
365 -> SecretKey {
366         let countersignatory_revocation_base_point = PublicKey::from_secret_key(&secp_ctx, &countersignatory_revocation_base_secret);
367         let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &per_commitment_secret);
368
369         let rev_append_commit_hash_key = {
370                 let mut sha = Sha256::engine();
371                 sha.input(&countersignatory_revocation_base_point.serialize());
372                 sha.input(&per_commitment_point.serialize());
373
374                 Sha256::from_engine(sha).into_inner()
375         };
376         let commit_append_rev_hash_key = {
377                 let mut sha = Sha256::engine();
378                 sha.input(&per_commitment_point.serialize());
379                 sha.input(&countersignatory_revocation_base_point.serialize());
380
381                 Sha256::from_engine(sha).into_inner()
382         };
383
384         let countersignatory_contrib = countersignatory_revocation_base_secret.clone().mul_tweak(&Scalar::from_be_bytes(rev_append_commit_hash_key).unwrap())
385                 .expect("Multiplying a secret key by a hash is expected to never fail per secp256k1 docs");
386         let broadcaster_contrib = per_commitment_secret.clone().mul_tweak(&Scalar::from_be_bytes(commit_append_rev_hash_key).unwrap())
387                 .expect("Multiplying a secret key by a hash is expected to never fail per secp256k1 docs");
388         countersignatory_contrib.add_tweak(&Scalar::from_be_bytes(broadcaster_contrib.secret_bytes()).unwrap())
389                 .expect("Addition only fails if the tweak is the inverse of the key. This is not possible when the tweak commits to the key.")
390 }
391
392 /// Derives a per-commitment-transaction revocation public key from its constituent parts. This is
393 /// the public equivalend of derive_private_revocation_key - using only public keys to derive a
394 /// public key instead of private keys.
395 ///
396 /// Only the cheating participant owns a valid witness to propagate a revoked
397 /// commitment transaction, thus per_commitment_point always come from cheater
398 /// and revocation_base_point always come from punisher, which is the broadcaster
399 /// of the transaction spending with this key knowledge.
400 ///
401 /// Note that this is infallible iff we trust that at least one of the two input keys are randomly
402 /// generated (ie our own).
403 pub fn derive_public_revocation_key<T: secp256k1::Verification>(secp_ctx: &Secp256k1<T>,
404         per_commitment_point: &PublicKey, countersignatory_revocation_base_point: &PublicKey)
405 -> PublicKey {
406         let rev_append_commit_hash_key = {
407                 let mut sha = Sha256::engine();
408                 sha.input(&countersignatory_revocation_base_point.serialize());
409                 sha.input(&per_commitment_point.serialize());
410
411                 Sha256::from_engine(sha).into_inner()
412         };
413         let commit_append_rev_hash_key = {
414                 let mut sha = Sha256::engine();
415                 sha.input(&per_commitment_point.serialize());
416                 sha.input(&countersignatory_revocation_base_point.serialize());
417
418                 Sha256::from_engine(sha).into_inner()
419         };
420
421         let countersignatory_contrib = countersignatory_revocation_base_point.clone().mul_tweak(&secp_ctx, &Scalar::from_be_bytes(rev_append_commit_hash_key).unwrap())
422                 .expect("Multiplying a valid public key by a hash is expected to never fail per secp256k1 docs");
423         let broadcaster_contrib = per_commitment_point.clone().mul_tweak(&secp_ctx, &Scalar::from_be_bytes(commit_append_rev_hash_key).unwrap())
424                 .expect("Multiplying a valid public key by a hash is expected to never fail per secp256k1 docs");
425         countersignatory_contrib.combine(&broadcaster_contrib)
426                 .expect("Addition only fails if the tweak is the inverse of the key. This is not possible when the tweak commits to the key.")
427 }
428
429 /// The set of public keys which are used in the creation of one commitment transaction.
430 /// These are derived from the channel base keys and per-commitment data.
431 ///
432 /// A broadcaster key is provided from potential broadcaster of the computed transaction.
433 /// A countersignatory key is coming from a protocol participant unable to broadcast the
434 /// transaction.
435 ///
436 /// These keys are assumed to be good, either because the code derived them from
437 /// channel basepoints via the new function, or they were obtained via
438 /// CommitmentTransaction.trust().keys() because we trusted the source of the
439 /// pre-calculated keys.
440 #[derive(PartialEq, Eq, Clone)]
441 pub struct TxCreationKeys {
442         /// The broadcaster's per-commitment public key which was used to derive the other keys.
443         pub per_commitment_point: PublicKey,
444         /// The revocation key which is used to allow the broadcaster of the commitment
445         /// transaction to provide their counterparty the ability to punish them if they broadcast
446         /// an old state.
447         pub revocation_key: PublicKey,
448         /// Broadcaster's HTLC Key
449         pub broadcaster_htlc_key: PublicKey,
450         /// Countersignatory's HTLC Key
451         pub countersignatory_htlc_key: PublicKey,
452         /// Broadcaster's Payment Key (which isn't allowed to be spent from for some delay)
453         pub broadcaster_delayed_payment_key: PublicKey,
454 }
455
456 impl_writeable_tlv_based!(TxCreationKeys, {
457         (0, per_commitment_point, required),
458         (2, revocation_key, required),
459         (4, broadcaster_htlc_key, required),
460         (6, countersignatory_htlc_key, required),
461         (8, broadcaster_delayed_payment_key, required),
462 });
463
464 /// One counterparty's public keys which do not change over the life of a channel.
465 #[derive(Clone, PartialEq, Eq)]
466 pub struct ChannelPublicKeys {
467         /// The public key which is used to sign all commitment transactions, as it appears in the
468         /// on-chain channel lock-in 2-of-2 multisig output.
469         pub funding_pubkey: PublicKey,
470         /// The base point which is used (with derive_public_revocation_key) to derive per-commitment
471         /// revocation keys. This is combined with the per-commitment-secret generated by the
472         /// counterparty to create a secret which the counterparty can reveal to revoke previous
473         /// states.
474         pub revocation_basepoint: PublicKey,
475         /// The public key on which the non-broadcaster (ie the countersignatory) receives an immediately
476         /// spendable primary channel balance on the broadcaster's commitment transaction. This key is
477         /// static across every commitment transaction.
478         pub payment_point: PublicKey,
479         /// The base point which is used (with derive_public_key) to derive a per-commitment payment
480         /// public key which receives non-HTLC-encumbered funds which are only available for spending
481         /// after some delay (or can be claimed via the revocation path).
482         pub delayed_payment_basepoint: PublicKey,
483         /// The base point which is used (with derive_public_key) to derive a per-commitment public key
484         /// which is used to encumber HTLC-in-flight outputs.
485         pub htlc_basepoint: PublicKey,
486 }
487
488 impl_writeable_tlv_based!(ChannelPublicKeys, {
489         (0, funding_pubkey, required),
490         (2, revocation_basepoint, required),
491         (4, payment_point, required),
492         (6, delayed_payment_basepoint, required),
493         (8, htlc_basepoint, required),
494 });
495
496 impl TxCreationKeys {
497         /// Create per-state keys from channel base points and the per-commitment point.
498         /// Key set is asymmetric and can't be used as part of counter-signatory set of transactions.
499         pub fn derive_new<T: secp256k1::Signing + secp256k1::Verification>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, broadcaster_delayed_payment_base: &PublicKey, broadcaster_htlc_base: &PublicKey, countersignatory_revocation_base: &PublicKey, countersignatory_htlc_base: &PublicKey) -> TxCreationKeys {
500                 TxCreationKeys {
501                         per_commitment_point: per_commitment_point.clone(),
502                         revocation_key: derive_public_revocation_key(&secp_ctx, &per_commitment_point, &countersignatory_revocation_base),
503                         broadcaster_htlc_key: derive_public_key(&secp_ctx, &per_commitment_point, &broadcaster_htlc_base),
504                         countersignatory_htlc_key: derive_public_key(&secp_ctx, &per_commitment_point, &countersignatory_htlc_base),
505                         broadcaster_delayed_payment_key: derive_public_key(&secp_ctx, &per_commitment_point, &broadcaster_delayed_payment_base),
506                 }
507         }
508
509         /// Generate per-state keys from channel static keys.
510         /// Key set is asymmetric and can't be used as part of counter-signatory set of transactions.
511         pub fn from_channel_static_keys<T: secp256k1::Signing + secp256k1::Verification>(per_commitment_point: &PublicKey, broadcaster_keys: &ChannelPublicKeys, countersignatory_keys: &ChannelPublicKeys, secp_ctx: &Secp256k1<T>) -> TxCreationKeys {
512                 TxCreationKeys::derive_new(
513                         &secp_ctx,
514                         &per_commitment_point,
515                         &broadcaster_keys.delayed_payment_basepoint,
516                         &broadcaster_keys.htlc_basepoint,
517                         &countersignatory_keys.revocation_basepoint,
518                         &countersignatory_keys.htlc_basepoint,
519                 )
520         }
521 }
522
523 /// The maximum length of a script returned by get_revokeable_redeemscript.
524 // Calculated as 6 bytes of opcodes, 1 byte push plus 2 bytes for contest_delay, and two public
525 // keys of 33 bytes (+ 1 push).
526 pub const REVOKEABLE_REDEEMSCRIPT_MAX_LENGTH: usize = 6 + 3 + 34*2;
527
528 /// A script either spendable by the revocation
529 /// key or the broadcaster_delayed_payment_key and satisfying the relative-locktime OP_CSV constrain.
530 /// Encumbering a `to_holder` output on a commitment transaction or 2nd-stage HTLC transactions.
531 pub fn get_revokeable_redeemscript(revocation_key: &PublicKey, contest_delay: u16, broadcaster_delayed_payment_key: &PublicKey) -> Script {
532         let res = Builder::new().push_opcode(opcodes::all::OP_IF)
533                       .push_slice(&revocation_key.serialize())
534                       .push_opcode(opcodes::all::OP_ELSE)
535                       .push_int(contest_delay as i64)
536                       .push_opcode(opcodes::all::OP_CSV)
537                       .push_opcode(opcodes::all::OP_DROP)
538                       .push_slice(&broadcaster_delayed_payment_key.serialize())
539                       .push_opcode(opcodes::all::OP_ENDIF)
540                       .push_opcode(opcodes::all::OP_CHECKSIG)
541                       .into_script();
542         debug_assert!(res.len() <= REVOKEABLE_REDEEMSCRIPT_MAX_LENGTH);
543         res
544 }
545
546 /// Information about an HTLC as it appears in a commitment transaction
547 #[derive(Clone, Debug, PartialEq, Eq)]
548 pub struct HTLCOutputInCommitment {
549         /// Whether the HTLC was "offered" (ie outbound in relation to this commitment transaction).
550         /// Note that this is not the same as whether it is ountbound *from us*. To determine that you
551         /// need to compare this value to whether the commitment transaction in question is that of
552         /// the counterparty or our own.
553         pub offered: bool,
554         /// The value, in msat, of the HTLC. The value as it appears in the commitment transaction is
555         /// this divided by 1000.
556         pub amount_msat: u64,
557         /// The CLTV lock-time at which this HTLC expires.
558         pub cltv_expiry: u32,
559         /// The hash of the preimage which unlocks this HTLC.
560         pub payment_hash: PaymentHash,
561         /// The position within the commitment transactions' outputs. This may be None if the value is
562         /// below the dust limit (in which case no output appears in the commitment transaction and the
563         /// value is spent to additional transaction fees).
564         pub transaction_output_index: Option<u32>,
565 }
566
567 impl_writeable_tlv_based!(HTLCOutputInCommitment, {
568         (0, offered, required),
569         (2, amount_msat, required),
570         (4, cltv_expiry, required),
571         (6, payment_hash, required),
572         (8, transaction_output_index, option),
573 });
574
575 #[inline]
576 pub(crate) fn get_htlc_redeemscript_with_explicit_keys(htlc: &HTLCOutputInCommitment, opt_anchors: bool, broadcaster_htlc_key: &PublicKey, countersignatory_htlc_key: &PublicKey, revocation_key: &PublicKey) -> Script {
577         let payment_hash160 = Ripemd160::hash(&htlc.payment_hash.0[..]).into_inner();
578         if htlc.offered {
579                 let mut bldr = Builder::new().push_opcode(opcodes::all::OP_DUP)
580                               .push_opcode(opcodes::all::OP_HASH160)
581                               .push_slice(&PubkeyHash::hash(&revocation_key.serialize())[..])
582                               .push_opcode(opcodes::all::OP_EQUAL)
583                               .push_opcode(opcodes::all::OP_IF)
584                               .push_opcode(opcodes::all::OP_CHECKSIG)
585                               .push_opcode(opcodes::all::OP_ELSE)
586                               .push_slice(&countersignatory_htlc_key.serialize()[..])
587                               .push_opcode(opcodes::all::OP_SWAP)
588                               .push_opcode(opcodes::all::OP_SIZE)
589                               .push_int(32)
590                               .push_opcode(opcodes::all::OP_EQUAL)
591                               .push_opcode(opcodes::all::OP_NOTIF)
592                               .push_opcode(opcodes::all::OP_DROP)
593                               .push_int(2)
594                               .push_opcode(opcodes::all::OP_SWAP)
595                               .push_slice(&broadcaster_htlc_key.serialize()[..])
596                               .push_int(2)
597                               .push_opcode(opcodes::all::OP_CHECKMULTISIG)
598                               .push_opcode(opcodes::all::OP_ELSE)
599                               .push_opcode(opcodes::all::OP_HASH160)
600                               .push_slice(&payment_hash160)
601                               .push_opcode(opcodes::all::OP_EQUALVERIFY)
602                               .push_opcode(opcodes::all::OP_CHECKSIG)
603                               .push_opcode(opcodes::all::OP_ENDIF);
604                 if opt_anchors {
605                         bldr = bldr.push_opcode(opcodes::all::OP_PUSHNUM_1)
606                                 .push_opcode(opcodes::all::OP_CSV)
607                                 .push_opcode(opcodes::all::OP_DROP);
608                 }
609                 bldr.push_opcode(opcodes::all::OP_ENDIF)
610                         .into_script()
611         } else {
612                         let mut bldr = Builder::new().push_opcode(opcodes::all::OP_DUP)
613                               .push_opcode(opcodes::all::OP_HASH160)
614                               .push_slice(&PubkeyHash::hash(&revocation_key.serialize())[..])
615                               .push_opcode(opcodes::all::OP_EQUAL)
616                               .push_opcode(opcodes::all::OP_IF)
617                               .push_opcode(opcodes::all::OP_CHECKSIG)
618                               .push_opcode(opcodes::all::OP_ELSE)
619                               .push_slice(&countersignatory_htlc_key.serialize()[..])
620                               .push_opcode(opcodes::all::OP_SWAP)
621                               .push_opcode(opcodes::all::OP_SIZE)
622                               .push_int(32)
623                               .push_opcode(opcodes::all::OP_EQUAL)
624                               .push_opcode(opcodes::all::OP_IF)
625                               .push_opcode(opcodes::all::OP_HASH160)
626                               .push_slice(&payment_hash160)
627                               .push_opcode(opcodes::all::OP_EQUALVERIFY)
628                               .push_int(2)
629                               .push_opcode(opcodes::all::OP_SWAP)
630                               .push_slice(&broadcaster_htlc_key.serialize()[..])
631                               .push_int(2)
632                               .push_opcode(opcodes::all::OP_CHECKMULTISIG)
633                               .push_opcode(opcodes::all::OP_ELSE)
634                               .push_opcode(opcodes::all::OP_DROP)
635                               .push_int(htlc.cltv_expiry as i64)
636                               .push_opcode(opcodes::all::OP_CLTV)
637                               .push_opcode(opcodes::all::OP_DROP)
638                               .push_opcode(opcodes::all::OP_CHECKSIG)
639                               .push_opcode(opcodes::all::OP_ENDIF);
640                 if opt_anchors {
641                         bldr = bldr.push_opcode(opcodes::all::OP_PUSHNUM_1)
642                                 .push_opcode(opcodes::all::OP_CSV)
643                                 .push_opcode(opcodes::all::OP_DROP);
644                 }
645                 bldr.push_opcode(opcodes::all::OP_ENDIF)
646                         .into_script()
647         }
648 }
649
650 /// Gets the witness redeemscript for an HTLC output in a commitment transaction. Note that htlc
651 /// does not need to have its previous_output_index filled.
652 #[inline]
653 pub fn get_htlc_redeemscript(htlc: &HTLCOutputInCommitment, opt_anchors: bool, keys: &TxCreationKeys) -> Script {
654         get_htlc_redeemscript_with_explicit_keys(htlc, opt_anchors, &keys.broadcaster_htlc_key, &keys.countersignatory_htlc_key, &keys.revocation_key)
655 }
656
657 /// Gets the redeemscript for a funding output from the two funding public keys.
658 /// Note that the order of funding public keys does not matter.
659 pub fn make_funding_redeemscript(broadcaster: &PublicKey, countersignatory: &PublicKey) -> Script {
660         let broadcaster_funding_key = broadcaster.serialize();
661         let countersignatory_funding_key = countersignatory.serialize();
662
663         let builder = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2);
664         if broadcaster_funding_key[..] < countersignatory_funding_key[..] {
665                 builder.push_slice(&broadcaster_funding_key)
666                         .push_slice(&countersignatory_funding_key)
667         } else {
668                 builder.push_slice(&countersignatory_funding_key)
669                         .push_slice(&broadcaster_funding_key)
670         }.push_opcode(opcodes::all::OP_PUSHNUM_2).push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script()
671 }
672
673 /// Builds an unsigned HTLC-Success or HTLC-Timeout transaction from the given channel and HTLC
674 /// parameters. This is used by [`TrustedCommitmentTransaction::get_htlc_sigs`] to fetch the
675 /// transaction which needs signing, and can be used to construct an HTLC transaction which is
676 /// broadcastable given a counterparty HTLC signature.
677 ///
678 /// Panics if htlc.transaction_output_index.is_none() (as such HTLCs do not appear in the
679 /// commitment transaction).
680 pub fn build_htlc_transaction(commitment_txid: &Txid, feerate_per_kw: u32, contest_delay: u16, htlc: &HTLCOutputInCommitment, opt_anchors: bool, use_non_zero_fee_anchors: bool, broadcaster_delayed_payment_key: &PublicKey, revocation_key: &PublicKey) -> Transaction {
681         let mut txins: Vec<TxIn> = Vec::new();
682         txins.push(TxIn {
683                 previous_output: OutPoint {
684                         txid: commitment_txid.clone(),
685                         vout: htlc.transaction_output_index.expect("Can't build an HTLC transaction for a dust output"),
686                 },
687                 script_sig: Script::new(),
688                 sequence: Sequence(if opt_anchors { 1 } else { 0 }),
689                 witness: Witness::new(),
690         });
691
692         let weight = if htlc.offered {
693                 htlc_timeout_tx_weight(opt_anchors)
694         } else {
695                 htlc_success_tx_weight(opt_anchors)
696         };
697         let output_value = if opt_anchors && !use_non_zero_fee_anchors {
698                 htlc.amount_msat / 1000
699         } else {
700                 let total_fee = feerate_per_kw as u64 * weight / 1000;
701                 htlc.amount_msat / 1000 - total_fee
702         };
703
704         let mut txouts: Vec<TxOut> = Vec::new();
705         txouts.push(TxOut {
706                 script_pubkey: get_revokeable_redeemscript(revocation_key, contest_delay, broadcaster_delayed_payment_key).to_v0_p2wsh(),
707                 value: output_value,
708         });
709
710         Transaction {
711                 version: 2,
712                 lock_time: PackedLockTime(if htlc.offered { htlc.cltv_expiry } else { 0 }),
713                 input: txins,
714                 output: txouts,
715         }
716 }
717
718 /// Gets the witnessScript for the to_remote output when anchors are enabled.
719 #[inline]
720 pub fn get_to_countersignatory_with_anchors_redeemscript(payment_point: &PublicKey) -> Script {
721         Builder::new()
722                 .push_slice(&payment_point.serialize()[..])
723                 .push_opcode(opcodes::all::OP_CHECKSIGVERIFY)
724                 .push_int(1)
725                 .push_opcode(opcodes::all::OP_CSV)
726                 .into_script()
727 }
728
729 /// Gets the witnessScript for an anchor output from the funding public key.
730 /// The witness in the spending input must be:
731 /// <BIP 143 funding_signature>
732 /// After 16 blocks of confirmation, an alternative satisfying witness could be:
733 /// <>
734 /// (empty vector required to satisfy compliance with MINIMALIF-standard rule)
735 #[inline]
736 pub fn get_anchor_redeemscript(funding_pubkey: &PublicKey) -> Script {
737         Builder::new().push_slice(&funding_pubkey.serialize()[..])
738                 .push_opcode(opcodes::all::OP_CHECKSIG)
739                 .push_opcode(opcodes::all::OP_IFDUP)
740                 .push_opcode(opcodes::all::OP_NOTIF)
741                 .push_int(16)
742                 .push_opcode(opcodes::all::OP_CSV)
743                 .push_opcode(opcodes::all::OP_ENDIF)
744                 .into_script()
745 }
746
747 #[cfg(anchors)]
748 /// Locates the output with an anchor script paying to `funding_pubkey` within `commitment_tx`.
749 pub(crate) fn get_anchor_output<'a>(commitment_tx: &'a Transaction, funding_pubkey: &PublicKey) -> Option<(u32, &'a TxOut)> {
750         let anchor_script = chan_utils::get_anchor_redeemscript(funding_pubkey).to_v0_p2wsh();
751         commitment_tx.output.iter().enumerate()
752                 .find(|(_, txout)| txout.script_pubkey == anchor_script)
753                 .map(|(idx, txout)| (idx as u32, txout))
754 }
755
756 /// Returns the witness required to satisfy and spend an anchor input.
757 pub fn build_anchor_input_witness(funding_key: &PublicKey, funding_sig: &Signature) -> Witness {
758         let anchor_redeem_script = chan_utils::get_anchor_redeemscript(funding_key);
759         let mut funding_sig = funding_sig.serialize_der().to_vec();
760         funding_sig.push(EcdsaSighashType::All as u8);
761         Witness::from_vec(vec![funding_sig, anchor_redeem_script.to_bytes()])
762 }
763
764 /// Per-channel data used to build transactions in conjunction with the per-commitment data (CommitmentTransaction).
765 /// The fields are organized by holder/counterparty.
766 ///
767 /// Normally, this is converted to the broadcaster/countersignatory-organized DirectedChannelTransactionParameters
768 /// before use, via the as_holder_broadcastable and as_counterparty_broadcastable functions.
769 #[derive(Clone, PartialEq)]
770 pub struct ChannelTransactionParameters {
771         /// Holder public keys
772         pub holder_pubkeys: ChannelPublicKeys,
773         /// The contest delay selected by the holder, which applies to counterparty-broadcast transactions
774         pub holder_selected_contest_delay: u16,
775         /// Whether the holder is the initiator of this channel.
776         /// This is an input to the commitment number obscure factor computation.
777         pub is_outbound_from_holder: bool,
778         /// The late-bound counterparty channel transaction parameters.
779         /// These parameters are populated at the point in the protocol where the counterparty provides them.
780         pub counterparty_parameters: Option<CounterpartyChannelTransactionParameters>,
781         /// The late-bound funding outpoint
782         pub funding_outpoint: Option<chain::transaction::OutPoint>,
783         /// Are anchors (zero fee HTLC transaction variant) used for this channel. Boolean is
784         /// serialization backwards-compatible.
785         pub opt_anchors: Option<()>,
786         /// Are non-zero-fee anchors are enabled (used in conjuction with opt_anchors)
787         /// It is intended merely for backwards compatibility with signers that need it.
788         /// There is no support for this feature in LDK channel negotiation.
789         pub opt_non_zero_fee_anchors: Option<()>,
790 }
791
792 /// Late-bound per-channel counterparty data used to build transactions.
793 #[derive(Clone, PartialEq)]
794 pub struct CounterpartyChannelTransactionParameters {
795         /// Counter-party public keys
796         pub pubkeys: ChannelPublicKeys,
797         /// The contest delay selected by the counterparty, which applies to holder-broadcast transactions
798         pub selected_contest_delay: u16,
799 }
800
801 impl ChannelTransactionParameters {
802         /// Whether the late bound parameters are populated.
803         pub fn is_populated(&self) -> bool {
804                 self.counterparty_parameters.is_some() && self.funding_outpoint.is_some()
805         }
806
807         /// Convert the holder/counterparty parameters to broadcaster/countersignatory-organized parameters,
808         /// given that the holder is the broadcaster.
809         ///
810         /// self.is_populated() must be true before calling this function.
811         pub fn as_holder_broadcastable(&self) -> DirectedChannelTransactionParameters {
812                 assert!(self.is_populated(), "self.late_parameters must be set before using as_holder_broadcastable");
813                 DirectedChannelTransactionParameters {
814                         inner: self,
815                         holder_is_broadcaster: true
816                 }
817         }
818
819         /// Convert the holder/counterparty parameters to broadcaster/countersignatory-organized parameters,
820         /// given that the counterparty is the broadcaster.
821         ///
822         /// self.is_populated() must be true before calling this function.
823         pub fn as_counterparty_broadcastable(&self) -> DirectedChannelTransactionParameters {
824                 assert!(self.is_populated(), "self.late_parameters must be set before using as_counterparty_broadcastable");
825                 DirectedChannelTransactionParameters {
826                         inner: self,
827                         holder_is_broadcaster: false
828                 }
829         }
830 }
831
832 impl_writeable_tlv_based!(CounterpartyChannelTransactionParameters, {
833         (0, pubkeys, required),
834         (2, selected_contest_delay, required),
835 });
836
837 impl_writeable_tlv_based!(ChannelTransactionParameters, {
838         (0, holder_pubkeys, required),
839         (2, holder_selected_contest_delay, required),
840         (4, is_outbound_from_holder, required),
841         (6, counterparty_parameters, option),
842         (8, funding_outpoint, option),
843         (10, opt_anchors, option),
844         (12, opt_non_zero_fee_anchors, option),
845 });
846
847 /// Static channel fields used to build transactions given per-commitment fields, organized by
848 /// broadcaster/countersignatory.
849 ///
850 /// This is derived from the holder/counterparty-organized ChannelTransactionParameters via the
851 /// as_holder_broadcastable and as_counterparty_broadcastable functions.
852 pub struct DirectedChannelTransactionParameters<'a> {
853         /// The holder's channel static parameters
854         inner: &'a ChannelTransactionParameters,
855         /// Whether the holder is the broadcaster
856         holder_is_broadcaster: bool,
857 }
858
859 impl<'a> DirectedChannelTransactionParameters<'a> {
860         /// Get the channel pubkeys for the broadcaster
861         pub fn broadcaster_pubkeys(&self) -> &ChannelPublicKeys {
862                 if self.holder_is_broadcaster {
863                         &self.inner.holder_pubkeys
864                 } else {
865                         &self.inner.counterparty_parameters.as_ref().unwrap().pubkeys
866                 }
867         }
868
869         /// Get the channel pubkeys for the countersignatory
870         pub fn countersignatory_pubkeys(&self) -> &ChannelPublicKeys {
871                 if self.holder_is_broadcaster {
872                         &self.inner.counterparty_parameters.as_ref().unwrap().pubkeys
873                 } else {
874                         &self.inner.holder_pubkeys
875                 }
876         }
877
878         /// Get the contest delay applicable to the transactions.
879         /// Note that the contest delay was selected by the countersignatory.
880         pub fn contest_delay(&self) -> u16 {
881                 let counterparty_parameters = self.inner.counterparty_parameters.as_ref().unwrap();
882                 if self.holder_is_broadcaster { counterparty_parameters.selected_contest_delay } else { self.inner.holder_selected_contest_delay }
883         }
884
885         /// Whether the channel is outbound from the broadcaster.
886         ///
887         /// The boolean representing the side that initiated the channel is
888         /// an input to the commitment number obscure factor computation.
889         pub fn is_outbound(&self) -> bool {
890                 if self.holder_is_broadcaster { self.inner.is_outbound_from_holder } else { !self.inner.is_outbound_from_holder }
891         }
892
893         /// The funding outpoint
894         pub fn funding_outpoint(&self) -> OutPoint {
895                 self.inner.funding_outpoint.unwrap().into_bitcoin_outpoint()
896         }
897
898         /// Whether to use anchors for this channel
899         pub fn opt_anchors(&self) -> bool {
900                 self.inner.opt_anchors.is_some()
901         }
902 }
903
904 /// Information needed to build and sign a holder's commitment transaction.
905 ///
906 /// The transaction is only signed once we are ready to broadcast.
907 #[derive(Clone)]
908 pub struct HolderCommitmentTransaction {
909         inner: CommitmentTransaction,
910         /// Our counterparty's signature for the transaction
911         pub counterparty_sig: Signature,
912         /// All non-dust counterparty HTLC signatures, in the order they appear in the transaction
913         pub counterparty_htlc_sigs: Vec<Signature>,
914         // Which order the signatures should go in when constructing the final commitment tx witness.
915         // The user should be able to reconstruct this themselves, so we don't bother to expose it.
916         holder_sig_first: bool,
917 }
918
919 impl Deref for HolderCommitmentTransaction {
920         type Target = CommitmentTransaction;
921
922         fn deref(&self) -> &Self::Target { &self.inner }
923 }
924
925 impl Eq for HolderCommitmentTransaction {}
926 impl PartialEq for HolderCommitmentTransaction {
927         // We dont care whether we are signed in equality comparison
928         fn eq(&self, o: &Self) -> bool {
929                 self.inner == o.inner
930         }
931 }
932
933 impl_writeable_tlv_based!(HolderCommitmentTransaction, {
934         (0, inner, required),
935         (2, counterparty_sig, required),
936         (4, holder_sig_first, required),
937         (6, counterparty_htlc_sigs, vec_type),
938 });
939
940 impl HolderCommitmentTransaction {
941         #[cfg(test)]
942         pub fn dummy() -> Self {
943                 let secp_ctx = Secp256k1::new();
944                 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
945                 let dummy_sig = sign(&secp_ctx, &secp256k1::Message::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[42; 32]).unwrap());
946
947                 let keys = TxCreationKeys {
948                         per_commitment_point: dummy_key.clone(),
949                         revocation_key: dummy_key.clone(),
950                         broadcaster_htlc_key: dummy_key.clone(),
951                         countersignatory_htlc_key: dummy_key.clone(),
952                         broadcaster_delayed_payment_key: dummy_key.clone(),
953                 };
954                 let channel_pubkeys = ChannelPublicKeys {
955                         funding_pubkey: dummy_key.clone(),
956                         revocation_basepoint: dummy_key.clone(),
957                         payment_point: dummy_key.clone(),
958                         delayed_payment_basepoint: dummy_key.clone(),
959                         htlc_basepoint: dummy_key.clone()
960                 };
961                 let channel_parameters = ChannelTransactionParameters {
962                         holder_pubkeys: channel_pubkeys.clone(),
963                         holder_selected_contest_delay: 0,
964                         is_outbound_from_holder: false,
965                         counterparty_parameters: Some(CounterpartyChannelTransactionParameters { pubkeys: channel_pubkeys.clone(), selected_contest_delay: 0 }),
966                         funding_outpoint: Some(chain::transaction::OutPoint { txid: Txid::all_zeros(), index: 0 }),
967                         opt_anchors: None,
968                         opt_non_zero_fee_anchors: None,
969                 };
970                 let mut htlcs_with_aux: Vec<(_, ())> = Vec::new();
971                 let inner = CommitmentTransaction::new_with_auxiliary_htlc_data(0, 0, 0, false, dummy_key.clone(), dummy_key.clone(), keys, 0, &mut htlcs_with_aux, &channel_parameters.as_counterparty_broadcastable());
972                 HolderCommitmentTransaction {
973                         inner,
974                         counterparty_sig: dummy_sig,
975                         counterparty_htlc_sigs: Vec::new(),
976                         holder_sig_first: false
977                 }
978         }
979
980         /// Create a new holder transaction with the given counterparty signatures.
981         /// The funding keys are used to figure out which signature should go first when building the transaction for broadcast.
982         pub fn new(commitment_tx: CommitmentTransaction, counterparty_sig: Signature, counterparty_htlc_sigs: Vec<Signature>, holder_funding_key: &PublicKey, counterparty_funding_key: &PublicKey) -> Self {
983                 Self {
984                         inner: commitment_tx,
985                         counterparty_sig,
986                         counterparty_htlc_sigs,
987                         holder_sig_first: holder_funding_key.serialize()[..] < counterparty_funding_key.serialize()[..],
988                 }
989         }
990
991         pub(crate) fn add_holder_sig(&self, funding_redeemscript: &Script, holder_sig: Signature) -> Transaction {
992                 // First push the multisig dummy, note that due to BIP147 (NULLDUMMY) it must be a zero-length element.
993                 let mut tx = self.inner.built.transaction.clone();
994                 tx.input[0].witness.push(Vec::new());
995                 let mut ser_holder_sig = holder_sig.serialize_der().to_vec();
996                 ser_holder_sig.push(EcdsaSighashType::All as u8);
997                 let mut ser_cp_sig = self.counterparty_sig.serialize_der().to_vec();
998                 ser_cp_sig.push(EcdsaSighashType::All as u8);
999
1000                 if self.holder_sig_first {
1001                         tx.input[0].witness.push(ser_holder_sig);
1002                         tx.input[0].witness.push(ser_cp_sig);
1003                 } else {
1004                         tx.input[0].witness.push(ser_cp_sig);
1005                         tx.input[0].witness.push(ser_holder_sig);
1006                 }
1007
1008                 tx.input[0].witness.push(funding_redeemscript.as_bytes().to_vec());
1009                 tx
1010         }
1011 }
1012
1013 /// A pre-built Bitcoin commitment transaction and its txid.
1014 #[derive(Clone)]
1015 pub struct BuiltCommitmentTransaction {
1016         /// The commitment transaction
1017         pub transaction: Transaction,
1018         /// The txid for the commitment transaction.
1019         ///
1020         /// This is provided as a performance optimization, instead of calling transaction.txid()
1021         /// multiple times.
1022         pub txid: Txid,
1023 }
1024
1025 impl_writeable_tlv_based!(BuiltCommitmentTransaction, {
1026         (0, transaction, required),
1027         (2, txid, required),
1028 });
1029
1030 impl BuiltCommitmentTransaction {
1031         /// Get the SIGHASH_ALL sighash value of the transaction.
1032         ///
1033         /// This can be used to verify a signature.
1034         pub fn get_sighash_all(&self, funding_redeemscript: &Script, channel_value_satoshis: u64) -> Message {
1035                 let sighash = &sighash::SighashCache::new(&self.transaction).segwit_signature_hash(0, funding_redeemscript, channel_value_satoshis, EcdsaSighashType::All).unwrap()[..];
1036                 hash_to_message!(sighash)
1037         }
1038
1039         /// Sign a transaction, either because we are counter-signing the counterparty's transaction or
1040         /// because we are about to broadcast a holder transaction.
1041         pub fn sign<T: secp256k1::Signing>(&self, funding_key: &SecretKey, funding_redeemscript: &Script, channel_value_satoshis: u64, secp_ctx: &Secp256k1<T>) -> Signature {
1042                 let sighash = self.get_sighash_all(funding_redeemscript, channel_value_satoshis);
1043                 sign(secp_ctx, &sighash, funding_key)
1044         }
1045 }
1046
1047 /// This class tracks the per-transaction information needed to build a closing transaction and will
1048 /// actually build it and sign.
1049 ///
1050 /// This class can be used inside a signer implementation to generate a signature given the relevant
1051 /// secret key.
1052 #[derive(Clone, Hash, PartialEq, Eq)]
1053 pub struct ClosingTransaction {
1054         to_holder_value_sat: u64,
1055         to_counterparty_value_sat: u64,
1056         to_holder_script: Script,
1057         to_counterparty_script: Script,
1058         built: Transaction,
1059 }
1060
1061 impl ClosingTransaction {
1062         /// Construct an object of the class
1063         pub fn new(
1064                 to_holder_value_sat: u64,
1065                 to_counterparty_value_sat: u64,
1066                 to_holder_script: Script,
1067                 to_counterparty_script: Script,
1068                 funding_outpoint: OutPoint,
1069         ) -> Self {
1070                 let built = build_closing_transaction(
1071                         to_holder_value_sat, to_counterparty_value_sat,
1072                         to_holder_script.clone(), to_counterparty_script.clone(),
1073                         funding_outpoint
1074                 );
1075                 ClosingTransaction {
1076                         to_holder_value_sat,
1077                         to_counterparty_value_sat,
1078                         to_holder_script,
1079                         to_counterparty_script,
1080                         built
1081                 }
1082         }
1083
1084         /// Trust our pre-built transaction.
1085         ///
1086         /// Applies a wrapper which allows access to the transaction.
1087         ///
1088         /// This should only be used if you fully trust the builder of this object. It should not
1089         /// be used by an external signer - instead use the verify function.
1090         pub fn trust(&self) -> TrustedClosingTransaction {
1091                 TrustedClosingTransaction { inner: self }
1092         }
1093
1094         /// Verify our pre-built transaction.
1095         ///
1096         /// Applies a wrapper which allows access to the transaction.
1097         ///
1098         /// An external validating signer must call this method before signing
1099         /// or using the built transaction.
1100         pub fn verify(&self, funding_outpoint: OutPoint) -> Result<TrustedClosingTransaction, ()> {
1101                 let built = build_closing_transaction(
1102                         self.to_holder_value_sat, self.to_counterparty_value_sat,
1103                         self.to_holder_script.clone(), self.to_counterparty_script.clone(),
1104                         funding_outpoint
1105                 );
1106                 if self.built != built {
1107                         return Err(())
1108                 }
1109                 Ok(TrustedClosingTransaction { inner: self })
1110         }
1111
1112         /// The value to be sent to the holder, or zero if the output will be omitted
1113         pub fn to_holder_value_sat(&self) -> u64 {
1114                 self.to_holder_value_sat
1115         }
1116
1117         /// The value to be sent to the counterparty, or zero if the output will be omitted
1118         pub fn to_counterparty_value_sat(&self) -> u64 {
1119                 self.to_counterparty_value_sat
1120         }
1121
1122         /// The destination of the holder's output
1123         pub fn to_holder_script(&self) -> &Script {
1124                 &self.to_holder_script
1125         }
1126
1127         /// The destination of the counterparty's output
1128         pub fn to_counterparty_script(&self) -> &Script {
1129                 &self.to_counterparty_script
1130         }
1131 }
1132
1133 /// A wrapper on ClosingTransaction indicating that the built bitcoin
1134 /// transaction is trusted.
1135 ///
1136 /// See trust() and verify() functions on CommitmentTransaction.
1137 ///
1138 /// This structure implements Deref.
1139 pub struct TrustedClosingTransaction<'a> {
1140         inner: &'a ClosingTransaction,
1141 }
1142
1143 impl<'a> Deref for TrustedClosingTransaction<'a> {
1144         type Target = ClosingTransaction;
1145
1146         fn deref(&self) -> &Self::Target { self.inner }
1147 }
1148
1149 impl<'a> TrustedClosingTransaction<'a> {
1150         /// The pre-built Bitcoin commitment transaction
1151         pub fn built_transaction(&self) -> &Transaction {
1152                 &self.inner.built
1153         }
1154
1155         /// Get the SIGHASH_ALL sighash value of the transaction.
1156         ///
1157         /// This can be used to verify a signature.
1158         pub fn get_sighash_all(&self, funding_redeemscript: &Script, channel_value_satoshis: u64) -> Message {
1159                 let sighash = &sighash::SighashCache::new(&self.inner.built).segwit_signature_hash(0, funding_redeemscript, channel_value_satoshis, EcdsaSighashType::All).unwrap()[..];
1160                 hash_to_message!(sighash)
1161         }
1162
1163         /// Sign a transaction, either because we are counter-signing the counterparty's transaction or
1164         /// because we are about to broadcast a holder transaction.
1165         pub fn sign<T: secp256k1::Signing>(&self, funding_key: &SecretKey, funding_redeemscript: &Script, channel_value_satoshis: u64, secp_ctx: &Secp256k1<T>) -> Signature {
1166                 let sighash = self.get_sighash_all(funding_redeemscript, channel_value_satoshis);
1167                 sign(secp_ctx, &sighash, funding_key)
1168         }
1169 }
1170
1171 /// This class tracks the per-transaction information needed to build a commitment transaction and will
1172 /// actually build it and sign.  It is used for holder transactions that we sign only when needed
1173 /// and for transactions we sign for the counterparty.
1174 ///
1175 /// This class can be used inside a signer implementation to generate a signature given the relevant
1176 /// secret key.
1177 #[derive(Clone)]
1178 pub struct CommitmentTransaction {
1179         commitment_number: u64,
1180         to_broadcaster_value_sat: u64,
1181         to_countersignatory_value_sat: u64,
1182         feerate_per_kw: u32,
1183         htlcs: Vec<HTLCOutputInCommitment>,
1184         // A boolean that is serialization backwards-compatible
1185         opt_anchors: Option<()>,
1186         // Whether non-zero-fee anchors should be used
1187         opt_non_zero_fee_anchors: Option<()>,
1188         // A cache of the parties' pubkeys required to construct the transaction, see doc for trust()
1189         keys: TxCreationKeys,
1190         // For access to the pre-built transaction, see doc for trust()
1191         built: BuiltCommitmentTransaction,
1192 }
1193
1194 impl Eq for CommitmentTransaction {}
1195 impl PartialEq for CommitmentTransaction {
1196         fn eq(&self, o: &Self) -> bool {
1197                 let eq = self.commitment_number == o.commitment_number &&
1198                         self.to_broadcaster_value_sat == o.to_broadcaster_value_sat &&
1199                         self.to_countersignatory_value_sat == o.to_countersignatory_value_sat &&
1200                         self.feerate_per_kw == o.feerate_per_kw &&
1201                         self.htlcs == o.htlcs &&
1202                         self.opt_anchors == o.opt_anchors &&
1203                         self.keys == o.keys;
1204                 if eq {
1205                         debug_assert_eq!(self.built.transaction, o.built.transaction);
1206                         debug_assert_eq!(self.built.txid, o.built.txid);
1207                 }
1208                 eq
1209         }
1210 }
1211
1212 impl_writeable_tlv_based!(CommitmentTransaction, {
1213         (0, commitment_number, required),
1214         (2, to_broadcaster_value_sat, required),
1215         (4, to_countersignatory_value_sat, required),
1216         (6, feerate_per_kw, required),
1217         (8, keys, required),
1218         (10, built, required),
1219         (12, htlcs, vec_type),
1220         (14, opt_anchors, option),
1221         (16, opt_non_zero_fee_anchors, option),
1222 });
1223
1224 impl CommitmentTransaction {
1225         /// Construct an object of the class while assigning transaction output indices to HTLCs.
1226         ///
1227         /// Populates HTLCOutputInCommitment.transaction_output_index in htlcs_with_aux.
1228         ///
1229         /// The generic T allows the caller to match the HTLC output index with auxiliary data.
1230         /// This auxiliary data is not stored in this object.
1231         ///
1232         /// Only include HTLCs that are above the dust limit for the channel.
1233         ///
1234         /// (C-not exported) due to the generic though we likely should expose a version without
1235         pub fn new_with_auxiliary_htlc_data<T>(commitment_number: u64, to_broadcaster_value_sat: u64, to_countersignatory_value_sat: u64, opt_anchors: bool, broadcaster_funding_key: PublicKey, countersignatory_funding_key: PublicKey, keys: TxCreationKeys, feerate_per_kw: u32, htlcs_with_aux: &mut Vec<(HTLCOutputInCommitment, T)>, channel_parameters: &DirectedChannelTransactionParameters) -> CommitmentTransaction {
1236                 // Sort outputs and populate output indices while keeping track of the auxiliary data
1237                 let (outputs, htlcs) = Self::internal_build_outputs(&keys, to_broadcaster_value_sat, to_countersignatory_value_sat, htlcs_with_aux, channel_parameters, opt_anchors, &broadcaster_funding_key, &countersignatory_funding_key).unwrap();
1238
1239                 let (obscured_commitment_transaction_number, txins) = Self::internal_build_inputs(commitment_number, channel_parameters);
1240                 let transaction = Self::make_transaction(obscured_commitment_transaction_number, txins, outputs);
1241                 let txid = transaction.txid();
1242                 CommitmentTransaction {
1243                         commitment_number,
1244                         to_broadcaster_value_sat,
1245                         to_countersignatory_value_sat,
1246                         feerate_per_kw,
1247                         htlcs,
1248                         opt_anchors: if opt_anchors { Some(()) } else { None },
1249                         keys,
1250                         built: BuiltCommitmentTransaction {
1251                                 transaction,
1252                                 txid
1253                         },
1254                         opt_non_zero_fee_anchors: None,
1255                 }
1256         }
1257
1258         /// Use non-zero fee anchors
1259         ///
1260         /// (C-not exported) due to move, and also not likely to be useful for binding users
1261         pub fn with_non_zero_fee_anchors(mut self) -> Self {
1262                 self.opt_non_zero_fee_anchors = Some(());
1263                 self
1264         }
1265
1266         fn internal_rebuild_transaction(&self, keys: &TxCreationKeys, channel_parameters: &DirectedChannelTransactionParameters, broadcaster_funding_key: &PublicKey, countersignatory_funding_key: &PublicKey) -> Result<BuiltCommitmentTransaction, ()> {
1267                 let (obscured_commitment_transaction_number, txins) = Self::internal_build_inputs(self.commitment_number, channel_parameters);
1268
1269                 let mut htlcs_with_aux = self.htlcs.iter().map(|h| (h.clone(), ())).collect();
1270                 let (outputs, _) = Self::internal_build_outputs(keys, self.to_broadcaster_value_sat, self.to_countersignatory_value_sat, &mut htlcs_with_aux, channel_parameters, self.opt_anchors.is_some(), broadcaster_funding_key, countersignatory_funding_key)?;
1271
1272                 let transaction = Self::make_transaction(obscured_commitment_transaction_number, txins, outputs);
1273                 let txid = transaction.txid();
1274                 let built_transaction = BuiltCommitmentTransaction {
1275                         transaction,
1276                         txid
1277                 };
1278                 Ok(built_transaction)
1279         }
1280
1281         fn make_transaction(obscured_commitment_transaction_number: u64, txins: Vec<TxIn>, outputs: Vec<TxOut>) -> Transaction {
1282                 Transaction {
1283                         version: 2,
1284                         lock_time: PackedLockTime(((0x20 as u32) << 8 * 3) | ((obscured_commitment_transaction_number & 0xffffffu64) as u32)),
1285                         input: txins,
1286                         output: outputs,
1287                 }
1288         }
1289
1290         // This is used in two cases:
1291         // - initial sorting of outputs / HTLCs in the constructor, in which case T is auxiliary data the
1292         //   caller needs to have sorted together with the HTLCs so it can keep track of the output index
1293         // - building of a bitcoin transaction during a verify() call, in which case T is just ()
1294         fn internal_build_outputs<T>(keys: &TxCreationKeys, to_broadcaster_value_sat: u64, to_countersignatory_value_sat: u64, htlcs_with_aux: &mut Vec<(HTLCOutputInCommitment, T)>, channel_parameters: &DirectedChannelTransactionParameters, opt_anchors: bool, broadcaster_funding_key: &PublicKey, countersignatory_funding_key: &PublicKey) -> Result<(Vec<TxOut>, Vec<HTLCOutputInCommitment>), ()> {
1295                 let countersignatory_pubkeys = channel_parameters.countersignatory_pubkeys();
1296                 let contest_delay = channel_parameters.contest_delay();
1297
1298                 let mut txouts: Vec<(TxOut, Option<&mut HTLCOutputInCommitment>)> = Vec::new();
1299
1300                 if to_countersignatory_value_sat > 0 {
1301                         let script = if opt_anchors {
1302                             get_to_countersignatory_with_anchors_redeemscript(&countersignatory_pubkeys.payment_point).to_v0_p2wsh()
1303                         } else {
1304                             Payload::p2wpkh(&BitcoinPublicKey::new(countersignatory_pubkeys.payment_point)).unwrap().script_pubkey()
1305                         };
1306                         txouts.push((
1307                                 TxOut {
1308                                         script_pubkey: script.clone(),
1309                                         value: to_countersignatory_value_sat,
1310                                 },
1311                                 None,
1312                         ))
1313                 }
1314
1315                 if to_broadcaster_value_sat > 0 {
1316                         let redeem_script = get_revokeable_redeemscript(
1317                                 &keys.revocation_key,
1318                                 contest_delay,
1319                                 &keys.broadcaster_delayed_payment_key,
1320                         );
1321                         txouts.push((
1322                                 TxOut {
1323                                         script_pubkey: redeem_script.to_v0_p2wsh(),
1324                                         value: to_broadcaster_value_sat,
1325                                 },
1326                                 None,
1327                         ));
1328                 }
1329
1330                 if opt_anchors {
1331                         if to_broadcaster_value_sat > 0 || !htlcs_with_aux.is_empty() {
1332                                 let anchor_script = get_anchor_redeemscript(broadcaster_funding_key);
1333                                 txouts.push((
1334                                         TxOut {
1335                                                 script_pubkey: anchor_script.to_v0_p2wsh(),
1336                                                 value: ANCHOR_OUTPUT_VALUE_SATOSHI,
1337                                         },
1338                                         None,
1339                                 ));
1340                         }
1341
1342                         if to_countersignatory_value_sat > 0 || !htlcs_with_aux.is_empty() {
1343                                 let anchor_script = get_anchor_redeemscript(countersignatory_funding_key);
1344                                 txouts.push((
1345                                         TxOut {
1346                                                 script_pubkey: anchor_script.to_v0_p2wsh(),
1347                                                 value: ANCHOR_OUTPUT_VALUE_SATOSHI,
1348                                         },
1349                                         None,
1350                                 ));
1351                         }
1352                 }
1353
1354                 let mut htlcs = Vec::with_capacity(htlcs_with_aux.len());
1355                 for (htlc, _) in htlcs_with_aux {
1356                         let script = chan_utils::get_htlc_redeemscript(&htlc, opt_anchors, &keys);
1357                         let txout = TxOut {
1358                                 script_pubkey: script.to_v0_p2wsh(),
1359                                 value: htlc.amount_msat / 1000,
1360                         };
1361                         txouts.push((txout, Some(htlc)));
1362                 }
1363
1364                 // Sort output in BIP-69 order (amount, scriptPubkey).  Tie-breaks based on HTLC
1365                 // CLTV expiration height.
1366                 sort_outputs(&mut txouts, |a, b| {
1367                         if let &Some(ref a_htlcout) = a {
1368                                 if let &Some(ref b_htlcout) = b {
1369                                         a_htlcout.cltv_expiry.cmp(&b_htlcout.cltv_expiry)
1370                                                 // Note that due to hash collisions, we have to have a fallback comparison
1371                                                 // here for fuzzing mode (otherwise at least chanmon_fail_consistency
1372                                                 // may fail)!
1373                                                 .then(a_htlcout.payment_hash.0.cmp(&b_htlcout.payment_hash.0))
1374                                 // For non-HTLC outputs, if they're copying our SPK we don't really care if we
1375                                 // close the channel due to mismatches - they're doing something dumb:
1376                                 } else { cmp::Ordering::Equal }
1377                         } else { cmp::Ordering::Equal }
1378                 });
1379
1380                 let mut outputs = Vec::with_capacity(txouts.len());
1381                 for (idx, out) in txouts.drain(..).enumerate() {
1382                         if let Some(htlc) = out.1 {
1383                                 htlc.transaction_output_index = Some(idx as u32);
1384                                 htlcs.push(htlc.clone());
1385                         }
1386                         outputs.push(out.0);
1387                 }
1388                 Ok((outputs, htlcs))
1389         }
1390
1391         fn internal_build_inputs(commitment_number: u64, channel_parameters: &DirectedChannelTransactionParameters) -> (u64, Vec<TxIn>) {
1392                 let broadcaster_pubkeys = channel_parameters.broadcaster_pubkeys();
1393                 let countersignatory_pubkeys = channel_parameters.countersignatory_pubkeys();
1394                 let commitment_transaction_number_obscure_factor = get_commitment_transaction_number_obscure_factor(
1395                         &broadcaster_pubkeys.payment_point,
1396                         &countersignatory_pubkeys.payment_point,
1397                         channel_parameters.is_outbound(),
1398                 );
1399
1400                 let obscured_commitment_transaction_number =
1401                         commitment_transaction_number_obscure_factor ^ (INITIAL_COMMITMENT_NUMBER - commitment_number);
1402
1403                 let txins = {
1404                         let mut ins: Vec<TxIn> = Vec::new();
1405                         ins.push(TxIn {
1406                                 previous_output: channel_parameters.funding_outpoint(),
1407                                 script_sig: Script::new(),
1408                                 sequence: Sequence(((0x80 as u32) << 8 * 3)
1409                                         | ((obscured_commitment_transaction_number >> 3 * 8) as u32)),
1410                                 witness: Witness::new(),
1411                         });
1412                         ins
1413                 };
1414                 (obscured_commitment_transaction_number, txins)
1415         }
1416
1417         /// The backwards-counting commitment number
1418         pub fn commitment_number(&self) -> u64 {
1419                 self.commitment_number
1420         }
1421
1422         /// The value to be sent to the broadcaster
1423         pub fn to_broadcaster_value_sat(&self) -> u64 {
1424                 self.to_broadcaster_value_sat
1425         }
1426
1427         /// The value to be sent to the counterparty
1428         pub fn to_countersignatory_value_sat(&self) -> u64 {
1429                 self.to_countersignatory_value_sat
1430         }
1431
1432         /// The feerate paid per 1000-weight-unit in this commitment transaction.
1433         pub fn feerate_per_kw(&self) -> u32 {
1434                 self.feerate_per_kw
1435         }
1436
1437         /// The non-dust HTLCs (direction, amt, height expiration, hash, transaction output index)
1438         /// which were included in this commitment transaction in output order.
1439         /// The transaction index is always populated.
1440         ///
1441         /// (C-not exported) as we cannot currently convert Vec references to/from C, though we should
1442         /// expose a less effecient version which creates a Vec of references in the future.
1443         pub fn htlcs(&self) -> &Vec<HTLCOutputInCommitment> {
1444                 &self.htlcs
1445         }
1446
1447         /// Trust our pre-built transaction and derived transaction creation public keys.
1448         ///
1449         /// Applies a wrapper which allows access to these fields.
1450         ///
1451         /// This should only be used if you fully trust the builder of this object.  It should not
1452         /// be used by an external signer - instead use the verify function.
1453         pub fn trust(&self) -> TrustedCommitmentTransaction {
1454                 TrustedCommitmentTransaction { inner: self }
1455         }
1456
1457         /// Verify our pre-built transaction and derived transaction creation public keys.
1458         ///
1459         /// Applies a wrapper which allows access to these fields.
1460         ///
1461         /// An external validating signer must call this method before signing
1462         /// or using the built transaction.
1463         pub fn verify<T: secp256k1::Signing + secp256k1::Verification>(&self, channel_parameters: &DirectedChannelTransactionParameters, broadcaster_keys: &ChannelPublicKeys, countersignatory_keys: &ChannelPublicKeys, secp_ctx: &Secp256k1<T>) -> Result<TrustedCommitmentTransaction, ()> {
1464                 // This is the only field of the key cache that we trust
1465                 let per_commitment_point = self.keys.per_commitment_point;
1466                 let keys = TxCreationKeys::from_channel_static_keys(&per_commitment_point, broadcaster_keys, countersignatory_keys, secp_ctx);
1467                 if keys != self.keys {
1468                         return Err(());
1469                 }
1470                 let tx = self.internal_rebuild_transaction(&keys, channel_parameters, &broadcaster_keys.funding_pubkey, &countersignatory_keys.funding_pubkey)?;
1471                 if self.built.transaction != tx.transaction || self.built.txid != tx.txid {
1472                         return Err(());
1473                 }
1474                 Ok(TrustedCommitmentTransaction { inner: self })
1475         }
1476 }
1477
1478 /// A wrapper on CommitmentTransaction indicating that the derived fields (the built bitcoin
1479 /// transaction and the transaction creation keys) are trusted.
1480 ///
1481 /// See trust() and verify() functions on CommitmentTransaction.
1482 ///
1483 /// This structure implements Deref.
1484 pub struct TrustedCommitmentTransaction<'a> {
1485         inner: &'a CommitmentTransaction,
1486 }
1487
1488 impl<'a> Deref for TrustedCommitmentTransaction<'a> {
1489         type Target = CommitmentTransaction;
1490
1491         fn deref(&self) -> &Self::Target { self.inner }
1492 }
1493
1494 impl<'a> TrustedCommitmentTransaction<'a> {
1495         /// The transaction ID of the built Bitcoin transaction
1496         pub fn txid(&self) -> Txid {
1497                 self.inner.built.txid
1498         }
1499
1500         /// The pre-built Bitcoin commitment transaction
1501         pub fn built_transaction(&self) -> &BuiltCommitmentTransaction {
1502                 &self.inner.built
1503         }
1504
1505         /// The pre-calculated transaction creation public keys.
1506         pub fn keys(&self) -> &TxCreationKeys {
1507                 &self.inner.keys
1508         }
1509
1510         /// Should anchors be used.
1511         pub fn opt_anchors(&self) -> bool {
1512                 self.opt_anchors.is_some()
1513         }
1514
1515         /// Get a signature for each HTLC which was included in the commitment transaction (ie for
1516         /// which HTLCOutputInCommitment::transaction_output_index.is_some()).
1517         ///
1518         /// The returned Vec has one entry for each HTLC, and in the same order.
1519         ///
1520         /// This function is only valid in the holder commitment context, it always uses EcdsaSighashType::All.
1521         pub fn get_htlc_sigs<T: secp256k1::Signing>(&self, htlc_base_key: &SecretKey, channel_parameters: &DirectedChannelTransactionParameters, secp_ctx: &Secp256k1<T>) -> Result<Vec<Signature>, ()> {
1522                 let inner = self.inner;
1523                 let keys = &inner.keys;
1524                 let txid = inner.built.txid;
1525                 let mut ret = Vec::with_capacity(inner.htlcs.len());
1526                 let holder_htlc_key = derive_private_key(secp_ctx, &inner.keys.per_commitment_point, htlc_base_key);
1527
1528                 for this_htlc in inner.htlcs.iter() {
1529                         assert!(this_htlc.transaction_output_index.is_some());
1530                         let htlc_tx = build_htlc_transaction(&txid, inner.feerate_per_kw, channel_parameters.contest_delay(), &this_htlc, self.opt_anchors(), self.opt_non_zero_fee_anchors.is_some(), &keys.broadcaster_delayed_payment_key, &keys.revocation_key);
1531
1532                         let htlc_redeemscript = get_htlc_redeemscript_with_explicit_keys(&this_htlc, self.opt_anchors(), &keys.broadcaster_htlc_key, &keys.countersignatory_htlc_key, &keys.revocation_key);
1533
1534                         let sighash = hash_to_message!(&sighash::SighashCache::new(&htlc_tx).segwit_signature_hash(0, &htlc_redeemscript, this_htlc.amount_msat / 1000, EcdsaSighashType::All).unwrap()[..]);
1535                         ret.push(sign(secp_ctx, &sighash, &holder_htlc_key));
1536                 }
1537                 Ok(ret)
1538         }
1539
1540         /// Gets a signed HTLC transaction given a preimage (for !htlc.offered) and the holder HTLC transaction signature.
1541         pub(crate) fn get_signed_htlc_tx(&self, channel_parameters: &DirectedChannelTransactionParameters, htlc_index: usize, counterparty_signature: &Signature, signature: &Signature, preimage: &Option<PaymentPreimage>) -> Transaction {
1542                 let inner = self.inner;
1543                 let keys = &inner.keys;
1544                 let txid = inner.built.txid;
1545                 let this_htlc = &inner.htlcs[htlc_index];
1546                 assert!(this_htlc.transaction_output_index.is_some());
1547                 // if we don't have preimage for an HTLC-Success, we can't generate an HTLC transaction.
1548                 if !this_htlc.offered && preimage.is_none() { unreachable!(); }
1549                 // Further, we should never be provided the preimage for an HTLC-Timeout transaction.
1550                 if  this_htlc.offered && preimage.is_some() { unreachable!(); }
1551
1552                 let mut htlc_tx = build_htlc_transaction(&txid, inner.feerate_per_kw, channel_parameters.contest_delay(), &this_htlc, self.opt_anchors(), self.opt_non_zero_fee_anchors.is_some(), &keys.broadcaster_delayed_payment_key, &keys.revocation_key);
1553
1554                 let htlc_redeemscript = get_htlc_redeemscript_with_explicit_keys(&this_htlc, self.opt_anchors(), &keys.broadcaster_htlc_key, &keys.countersignatory_htlc_key, &keys.revocation_key);
1555
1556                 let sighashtype = if self.opt_anchors() { EcdsaSighashType::SinglePlusAnyoneCanPay } else { EcdsaSighashType::All };
1557
1558                 // First push the multisig dummy, note that due to BIP147 (NULLDUMMY) it must be a zero-length element.
1559                 htlc_tx.input[0].witness.push(Vec::new());
1560
1561                 let mut cp_sig_ser = counterparty_signature.serialize_der().to_vec();
1562                 cp_sig_ser.push(sighashtype as u8);
1563                 htlc_tx.input[0].witness.push(cp_sig_ser);
1564                 let mut holder_sig_ser = signature.serialize_der().to_vec();
1565                 holder_sig_ser.push(EcdsaSighashType::All as u8);
1566                 htlc_tx.input[0].witness.push(holder_sig_ser);
1567
1568                 if this_htlc.offered {
1569                         // Due to BIP146 (MINIMALIF) this must be a zero-length element to relay.
1570                         htlc_tx.input[0].witness.push(Vec::new());
1571                 } else {
1572                         htlc_tx.input[0].witness.push(preimage.unwrap().0.to_vec());
1573                 }
1574
1575                 htlc_tx.input[0].witness.push(htlc_redeemscript.as_bytes().to_vec());
1576                 htlc_tx
1577         }
1578 }
1579
1580 /// Commitment transaction numbers which appear in the transactions themselves are XOR'd with a
1581 /// shared secret first. This prevents on-chain observers from discovering how many commitment
1582 /// transactions occurred in a channel before it was closed.
1583 ///
1584 /// This function gets the shared secret from relevant channel public keys and can be used to
1585 /// "decrypt" the commitment transaction number given a commitment transaction on-chain.
1586 pub fn get_commitment_transaction_number_obscure_factor(
1587         broadcaster_payment_basepoint: &PublicKey,
1588         countersignatory_payment_basepoint: &PublicKey,
1589         outbound_from_broadcaster: bool,
1590 ) -> u64 {
1591         let mut sha = Sha256::engine();
1592
1593         if outbound_from_broadcaster {
1594                 sha.input(&broadcaster_payment_basepoint.serialize());
1595                 sha.input(&countersignatory_payment_basepoint.serialize());
1596         } else {
1597                 sha.input(&countersignatory_payment_basepoint.serialize());
1598                 sha.input(&broadcaster_payment_basepoint.serialize());
1599         }
1600         let res = Sha256::from_engine(sha).into_inner();
1601
1602         ((res[26] as u64) << 5 * 8)
1603                 | ((res[27] as u64) << 4 * 8)
1604                 | ((res[28] as u64) << 3 * 8)
1605                 | ((res[29] as u64) << 2 * 8)
1606                 | ((res[30] as u64) << 1 * 8)
1607                 | ((res[31] as u64) << 0 * 8)
1608 }
1609
1610 #[cfg(test)]
1611 mod tests {
1612         use super::CounterpartyCommitmentSecrets;
1613         use crate::{hex, chain};
1614         use crate::prelude::*;
1615         use crate::ln::chan_utils::{get_htlc_redeemscript, get_to_countersignatory_with_anchors_redeemscript, CommitmentTransaction, TxCreationKeys, ChannelTransactionParameters, CounterpartyChannelTransactionParameters, HTLCOutputInCommitment};
1616         use bitcoin::secp256k1::{PublicKey, SecretKey, Secp256k1};
1617         use crate::util::test_utils;
1618         use crate::chain::keysinterface::{KeysInterface, BaseSign};
1619         use bitcoin::{Network, Txid};
1620         use bitcoin::hashes::Hash;
1621         use crate::ln::PaymentHash;
1622         use bitcoin::hashes::hex::ToHex;
1623         use bitcoin::util::address::Payload;
1624         use bitcoin::PublicKey as BitcoinPublicKey;
1625
1626         #[test]
1627         fn test_anchors() {
1628                 let secp_ctx = Secp256k1::new();
1629
1630                 let seed = [42; 32];
1631                 let network = Network::Testnet;
1632                 let keys_provider = test_utils::TestKeysInterface::new(&seed, network);
1633                 let signer = keys_provider.derive_channel_signer(3000, keys_provider.generate_channel_keys_id(false, 1_000_000, 0));
1634                 let counterparty_signer = keys_provider.derive_channel_signer(3000, keys_provider.generate_channel_keys_id(true, 1_000_000, 1));
1635                 let delayed_payment_base = &signer.pubkeys().delayed_payment_basepoint;
1636                 let per_commitment_secret = SecretKey::from_slice(&hex::decode("1f1e1d1c1b1a191817161514131211100f0e0d0c0b0a09080706050403020100").unwrap()[..]).unwrap();
1637                 let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &per_commitment_secret);
1638                 let htlc_basepoint = &signer.pubkeys().htlc_basepoint;
1639                 let holder_pubkeys = signer.pubkeys();
1640                 let counterparty_pubkeys = counterparty_signer.pubkeys();
1641                 let keys = TxCreationKeys::derive_new(&secp_ctx, &per_commitment_point, delayed_payment_base, htlc_basepoint, &counterparty_pubkeys.revocation_basepoint, &counterparty_pubkeys.htlc_basepoint);
1642                 let mut channel_parameters = ChannelTransactionParameters {
1643                         holder_pubkeys: holder_pubkeys.clone(),
1644                         holder_selected_contest_delay: 0,
1645                         is_outbound_from_holder: false,
1646                         counterparty_parameters: Some(CounterpartyChannelTransactionParameters { pubkeys: counterparty_pubkeys.clone(), selected_contest_delay: 0 }),
1647                         funding_outpoint: Some(chain::transaction::OutPoint { txid: Txid::all_zeros(), index: 0 }),
1648                         opt_anchors: None,
1649                         opt_non_zero_fee_anchors: None,
1650                 };
1651
1652                 let mut htlcs_with_aux: Vec<(_, ())> = Vec::new();
1653
1654                 // Generate broadcaster and counterparty outputs
1655                 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1656                         0, 1000, 2000,
1657                         false,
1658                         holder_pubkeys.funding_pubkey,
1659                         counterparty_pubkeys.funding_pubkey,
1660                         keys.clone(), 1,
1661                         &mut htlcs_with_aux, &channel_parameters.as_holder_broadcastable()
1662                 );
1663                 assert_eq!(tx.built.transaction.output.len(), 2);
1664                 assert_eq!(tx.built.transaction.output[1].script_pubkey, Payload::p2wpkh(&BitcoinPublicKey::new(counterparty_pubkeys.payment_point)).unwrap().script_pubkey());
1665
1666                 // Generate broadcaster and counterparty outputs as well as two anchors
1667                 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1668                         0, 1000, 2000,
1669                         true,
1670                         holder_pubkeys.funding_pubkey,
1671                         counterparty_pubkeys.funding_pubkey,
1672                         keys.clone(), 1,
1673                         &mut htlcs_with_aux, &channel_parameters.as_holder_broadcastable()
1674                 );
1675                 assert_eq!(tx.built.transaction.output.len(), 4);
1676                 assert_eq!(tx.built.transaction.output[3].script_pubkey, get_to_countersignatory_with_anchors_redeemscript(&counterparty_pubkeys.payment_point).to_v0_p2wsh());
1677
1678                 // Generate broadcaster output and anchor
1679                 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1680                         0, 3000, 0,
1681                         true,
1682                         holder_pubkeys.funding_pubkey,
1683                         counterparty_pubkeys.funding_pubkey,
1684                         keys.clone(), 1,
1685                         &mut htlcs_with_aux, &channel_parameters.as_holder_broadcastable()
1686                 );
1687                 assert_eq!(tx.built.transaction.output.len(), 2);
1688
1689                 // Generate counterparty output and anchor
1690                 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1691                         0, 0, 3000,
1692                         true,
1693                         holder_pubkeys.funding_pubkey,
1694                         counterparty_pubkeys.funding_pubkey,
1695                         keys.clone(), 1,
1696                         &mut htlcs_with_aux, &channel_parameters.as_holder_broadcastable()
1697                 );
1698                 assert_eq!(tx.built.transaction.output.len(), 2);
1699
1700                 let received_htlc = HTLCOutputInCommitment {
1701                         offered: false,
1702                         amount_msat: 400000,
1703                         cltv_expiry: 100,
1704                         payment_hash: PaymentHash([42; 32]),
1705                         transaction_output_index: None,
1706                 };
1707
1708                 let offered_htlc = HTLCOutputInCommitment {
1709                         offered: true,
1710                         amount_msat: 600000,
1711                         cltv_expiry: 100,
1712                         payment_hash: PaymentHash([43; 32]),
1713                         transaction_output_index: None,
1714                 };
1715
1716                 // Generate broadcaster output and received and offered HTLC outputs,  w/o anchors
1717                 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1718                         0, 3000, 0,
1719                         false,
1720                         holder_pubkeys.funding_pubkey,
1721                         counterparty_pubkeys.funding_pubkey,
1722                         keys.clone(), 1,
1723                         &mut vec![(received_htlc.clone(), ()), (offered_htlc.clone(), ())],
1724                         &channel_parameters.as_holder_broadcastable()
1725                 );
1726                 assert_eq!(tx.built.transaction.output.len(), 3);
1727                 assert_eq!(tx.built.transaction.output[0].script_pubkey, get_htlc_redeemscript(&received_htlc, false, &keys).to_v0_p2wsh());
1728                 assert_eq!(tx.built.transaction.output[1].script_pubkey, get_htlc_redeemscript(&offered_htlc, false, &keys).to_v0_p2wsh());
1729                 assert_eq!(get_htlc_redeemscript(&received_htlc, false, &keys).to_v0_p2wsh().to_hex(),
1730                                    "0020e43a7c068553003fe68fcae424fb7b28ec5ce48cd8b6744b3945631389bad2fb");
1731                 assert_eq!(get_htlc_redeemscript(&offered_htlc, false, &keys).to_v0_p2wsh().to_hex(),
1732                                    "0020215d61bba56b19e9eadb6107f5a85d7f99c40f65992443f69229c290165bc00d");
1733
1734                 // Generate broadcaster output and received and offered HTLC outputs,  with anchors
1735                 channel_parameters.opt_anchors = Some(());
1736                 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1737                         0, 3000, 0,
1738                         true,
1739                         holder_pubkeys.funding_pubkey,
1740                         counterparty_pubkeys.funding_pubkey,
1741                         keys.clone(), 1,
1742                         &mut vec![(received_htlc.clone(), ()), (offered_htlc.clone(), ())],
1743                         &channel_parameters.as_holder_broadcastable()
1744                 );
1745                 assert_eq!(tx.built.transaction.output.len(), 5);
1746                 assert_eq!(tx.built.transaction.output[2].script_pubkey, get_htlc_redeemscript(&received_htlc, true, &keys).to_v0_p2wsh());
1747                 assert_eq!(tx.built.transaction.output[3].script_pubkey, get_htlc_redeemscript(&offered_htlc, true, &keys).to_v0_p2wsh());
1748                 assert_eq!(get_htlc_redeemscript(&received_htlc, true, &keys).to_v0_p2wsh().to_hex(),
1749                                    "0020b70d0649c72b38756885c7a30908d912a7898dd5d79457a7280b8e9a20f3f2bc");
1750                 assert_eq!(get_htlc_redeemscript(&offered_htlc, true, &keys).to_v0_p2wsh().to_hex(),
1751                                    "002087a3faeb1950a469c0e2db4a79b093a41b9526e5a6fc6ef5cb949bde3be379c7");
1752         }
1753
1754         #[test]
1755         fn test_per_commitment_storage() {
1756                 // Test vectors from BOLT 3:
1757                 let mut secrets: Vec<[u8; 32]> = Vec::new();
1758                 let mut monitor;
1759
1760                 macro_rules! test_secrets {
1761                         () => {
1762                                 let mut idx = 281474976710655;
1763                                 for secret in secrets.iter() {
1764                                         assert_eq!(monitor.get_secret(idx).unwrap(), *secret);
1765                                         idx -= 1;
1766                                 }
1767                                 assert_eq!(monitor.get_min_seen_secret(), idx + 1);
1768                                 assert!(monitor.get_secret(idx).is_none());
1769                         };
1770                 }
1771
1772                 {
1773                         // insert_secret correct sequence
1774                         monitor = CounterpartyCommitmentSecrets::new();
1775                         secrets.clear();
1776
1777                         secrets.push([0; 32]);
1778                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1779                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1780                         test_secrets!();
1781
1782                         secrets.push([0; 32]);
1783                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1784                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1785                         test_secrets!();
1786
1787                         secrets.push([0; 32]);
1788                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1789                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1790                         test_secrets!();
1791
1792                         secrets.push([0; 32]);
1793                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1794                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
1795                         test_secrets!();
1796
1797                         secrets.push([0; 32]);
1798                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1799                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
1800                         test_secrets!();
1801
1802                         secrets.push([0; 32]);
1803                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1804                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
1805                         test_secrets!();
1806
1807                         secrets.push([0; 32]);
1808                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1809                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
1810                         test_secrets!();
1811
1812                         secrets.push([0; 32]);
1813                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1814                         monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap();
1815                         test_secrets!();
1816                 }
1817
1818                 {
1819                         // insert_secret #1 incorrect
1820                         monitor = CounterpartyCommitmentSecrets::new();
1821                         secrets.clear();
1822
1823                         secrets.push([0; 32]);
1824                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
1825                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1826                         test_secrets!();
1827
1828                         secrets.push([0; 32]);
1829                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1830                         assert!(monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).is_err());
1831                 }
1832
1833                 {
1834                         // insert_secret #2 incorrect (#1 derived from incorrect)
1835                         monitor = CounterpartyCommitmentSecrets::new();
1836                         secrets.clear();
1837
1838                         secrets.push([0; 32]);
1839                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
1840                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1841                         test_secrets!();
1842
1843                         secrets.push([0; 32]);
1844                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
1845                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1846                         test_secrets!();
1847
1848                         secrets.push([0; 32]);
1849                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1850                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1851                         test_secrets!();
1852
1853                         secrets.push([0; 32]);
1854                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1855                         assert!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).is_err());
1856                 }
1857
1858                 {
1859                         // insert_secret #3 incorrect
1860                         monitor = CounterpartyCommitmentSecrets::new();
1861                         secrets.clear();
1862
1863                         secrets.push([0; 32]);
1864                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1865                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1866                         test_secrets!();
1867
1868                         secrets.push([0; 32]);
1869                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1870                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1871                         test_secrets!();
1872
1873                         secrets.push([0; 32]);
1874                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
1875                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1876                         test_secrets!();
1877
1878                         secrets.push([0; 32]);
1879                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1880                         assert!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).is_err());
1881                 }
1882
1883                 {
1884                         // insert_secret #4 incorrect (1,2,3 derived from incorrect)
1885                         monitor = CounterpartyCommitmentSecrets::new();
1886                         secrets.clear();
1887
1888                         secrets.push([0; 32]);
1889                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
1890                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1891                         test_secrets!();
1892
1893                         secrets.push([0; 32]);
1894                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
1895                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1896                         test_secrets!();
1897
1898                         secrets.push([0; 32]);
1899                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
1900                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1901                         test_secrets!();
1902
1903                         secrets.push([0; 32]);
1904                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("ba65d7b0ef55a3ba300d4e87af29868f394f8f138d78a7011669c79b37b936f4").unwrap());
1905                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
1906                         test_secrets!();
1907
1908                         secrets.push([0; 32]);
1909                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1910                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
1911                         test_secrets!();
1912
1913                         secrets.push([0; 32]);
1914                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1915                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
1916                         test_secrets!();
1917
1918                         secrets.push([0; 32]);
1919                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1920                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
1921                         test_secrets!();
1922
1923                         secrets.push([0; 32]);
1924                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1925                         assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
1926                 }
1927
1928                 {
1929                         // insert_secret #5 incorrect
1930                         monitor = CounterpartyCommitmentSecrets::new();
1931                         secrets.clear();
1932
1933                         secrets.push([0; 32]);
1934                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1935                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1936                         test_secrets!();
1937
1938                         secrets.push([0; 32]);
1939                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1940                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1941                         test_secrets!();
1942
1943                         secrets.push([0; 32]);
1944                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1945                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1946                         test_secrets!();
1947
1948                         secrets.push([0; 32]);
1949                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1950                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
1951                         test_secrets!();
1952
1953                         secrets.push([0; 32]);
1954                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
1955                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
1956                         test_secrets!();
1957
1958                         secrets.push([0; 32]);
1959                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1960                         assert!(monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).is_err());
1961                 }
1962
1963                 {
1964                         // insert_secret #6 incorrect (5 derived from incorrect)
1965                         monitor = CounterpartyCommitmentSecrets::new();
1966                         secrets.clear();
1967
1968                         secrets.push([0; 32]);
1969                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1970                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1971                         test_secrets!();
1972
1973                         secrets.push([0; 32]);
1974                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1975                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1976                         test_secrets!();
1977
1978                         secrets.push([0; 32]);
1979                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1980                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1981                         test_secrets!();
1982
1983                         secrets.push([0; 32]);
1984                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1985                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
1986                         test_secrets!();
1987
1988                         secrets.push([0; 32]);
1989                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
1990                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
1991                         test_secrets!();
1992
1993                         secrets.push([0; 32]);
1994                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("b7e76a83668bde38b373970155c868a653304308f9896692f904a23731224bb1").unwrap());
1995                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
1996                         test_secrets!();
1997
1998                         secrets.push([0; 32]);
1999                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2000                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2001                         test_secrets!();
2002
2003                         secrets.push([0; 32]);
2004                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2005                         assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
2006                 }
2007
2008                 {
2009                         // insert_secret #7 incorrect
2010                         monitor = CounterpartyCommitmentSecrets::new();
2011                         secrets.clear();
2012
2013                         secrets.push([0; 32]);
2014                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2015                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2016                         test_secrets!();
2017
2018                         secrets.push([0; 32]);
2019                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2020                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2021                         test_secrets!();
2022
2023                         secrets.push([0; 32]);
2024                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2025                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2026                         test_secrets!();
2027
2028                         secrets.push([0; 32]);
2029                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2030                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2031                         test_secrets!();
2032
2033                         secrets.push([0; 32]);
2034                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2035                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2036                         test_secrets!();
2037
2038                         secrets.push([0; 32]);
2039                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2040                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2041                         test_secrets!();
2042
2043                         secrets.push([0; 32]);
2044                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("e7971de736e01da8ed58b94c2fc216cb1dca9e326f3a96e7194fe8ea8af6c0a3").unwrap());
2045                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2046                         test_secrets!();
2047
2048                         secrets.push([0; 32]);
2049                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2050                         assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
2051                 }
2052
2053                 {
2054                         // insert_secret #8 incorrect
2055                         monitor = CounterpartyCommitmentSecrets::new();
2056                         secrets.clear();
2057
2058                         secrets.push([0; 32]);
2059                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2060                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2061                         test_secrets!();
2062
2063                         secrets.push([0; 32]);
2064                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2065                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2066                         test_secrets!();
2067
2068                         secrets.push([0; 32]);
2069                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2070                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2071                         test_secrets!();
2072
2073                         secrets.push([0; 32]);
2074                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2075                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2076                         test_secrets!();
2077
2078                         secrets.push([0; 32]);
2079                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2080                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2081                         test_secrets!();
2082
2083                         secrets.push([0; 32]);
2084                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2085                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2086                         test_secrets!();
2087
2088                         secrets.push([0; 32]);
2089                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2090                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2091                         test_secrets!();
2092
2093                         secrets.push([0; 32]);
2094                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a7efbc61aac46d34f77778bac22c8a20c6a46ca460addc49009bda875ec88fa4").unwrap());
2095                         assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
2096                 }
2097         }
2098 }