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