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