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