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