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