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