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