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