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