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