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