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