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