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