Don't underpay htlc_min due to path contribution
[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::ChannelKeys message signing
12 //! by hand.
13
14 use bitcoin::blockdata::script::{Script,Builder};
15 use bitcoin::blockdata::opcodes;
16 use bitcoin::blockdata::transaction::{TxIn,TxOut,OutPoint,Transaction, SigHashType};
17 use bitcoin::consensus::encode::{Decodable, Encodable};
18 use bitcoin::consensus::encode;
19 use bitcoin::util::bip143;
20
21 use bitcoin::hashes::{Hash, HashEngine};
22 use bitcoin::hashes::sha256::Hash as Sha256;
23 use bitcoin::hashes::ripemd160::Hash as Ripemd160;
24 use bitcoin::hash_types::{Txid, PubkeyHash};
25
26 use ln::channelmanager::{PaymentHash, PaymentPreimage};
27 use ln::msgs::DecodeError;
28 use util::ser::{Readable, Writeable, Writer, WriterWriteAdaptor};
29 use util::byte_utils;
30
31 use bitcoin::secp256k1::key::{SecretKey, PublicKey};
32 use bitcoin::secp256k1::{Secp256k1, Signature};
33 use bitcoin::secp256k1::Error as SecpError;
34 use bitcoin::secp256k1;
35
36 use std::{cmp, mem};
37
38 const MAX_ALLOC_SIZE: usize = 64*1024;
39
40 pub(super) const HTLC_SUCCESS_TX_WEIGHT: u64 = 703;
41 pub(super) const HTLC_TIMEOUT_TX_WEIGHT: u64 = 663;
42
43 #[derive(PartialEq)]
44 pub(crate) enum HTLCType {
45         AcceptedHTLC,
46         OfferedHTLC
47 }
48
49 impl HTLCType {
50         /// Check if a given tx witnessScript len matchs one of a pre-signed HTLC
51         pub(crate) fn scriptlen_to_htlctype(witness_script_len: usize) ->  Option<HTLCType> {
52                 if witness_script_len == 133 {
53                         Some(HTLCType::OfferedHTLC)
54                 } else if witness_script_len >= 136 && witness_script_len <= 139 {
55                         Some(HTLCType::AcceptedHTLC)
56                 } else {
57                         None
58                 }
59         }
60 }
61
62 // Various functions for key derivation and transaction creation for use within channels. Primarily
63 // used in Channel and ChannelMonitor.
64
65 /// Build the commitment secret from the seed and the commitment number
66 pub fn build_commitment_secret(commitment_seed: &[u8; 32], idx: u64) -> [u8; 32] {
67         let mut res: [u8; 32] = commitment_seed.clone();
68         for i in 0..48 {
69                 let bitpos = 47 - i;
70                 if idx & (1 << bitpos) == (1 << bitpos) {
71                         res[bitpos / 8] ^= 1 << (bitpos & 7);
72                         res = Sha256::hash(&res).into_inner();
73                 }
74         }
75         res
76 }
77
78 /// Implements the per-commitment secret storage scheme from
79 /// [BOLT 3](https://github.com/lightningnetwork/lightning-rfc/blob/dcbf8583976df087c79c3ce0b535311212e6812d/03-transactions.md#efficient-per-commitment-secret-storage).
80 ///
81 /// Allows us to keep track of all of the revocation secrets of counterarties in just 50*32 bytes
82 /// or so.
83 #[derive(Clone)]
84 pub(crate) struct CounterpartyCommitmentSecrets {
85         old_secrets: [([u8; 32], u64); 49],
86 }
87
88 impl PartialEq for CounterpartyCommitmentSecrets {
89         fn eq(&self, other: &Self) -> bool {
90                 for (&(ref secret, ref idx), &(ref o_secret, ref o_idx)) in self.old_secrets.iter().zip(other.old_secrets.iter()) {
91                         if secret != o_secret || idx != o_idx {
92                                 return false
93                         }
94                 }
95                 true
96         }
97 }
98
99 impl CounterpartyCommitmentSecrets {
100         pub(crate) fn new() -> Self {
101                 Self { old_secrets: [([0; 32], 1 << 48); 49], }
102         }
103
104         #[inline]
105         fn place_secret(idx: u64) -> u8 {
106                 for i in 0..48 {
107                         if idx & (1 << i) == (1 << i) {
108                                 return i
109                         }
110                 }
111                 48
112         }
113
114         pub(crate) fn get_min_seen_secret(&self) -> u64 {
115                 //TODO This can be optimized?
116                 let mut min = 1 << 48;
117                 for &(_, idx) in self.old_secrets.iter() {
118                         if idx < min {
119                                 min = idx;
120                         }
121                 }
122                 min
123         }
124
125         #[inline]
126         fn derive_secret(secret: [u8; 32], bits: u8, idx: u64) -> [u8; 32] {
127                 let mut res: [u8; 32] = secret;
128                 for i in 0..bits {
129                         let bitpos = bits - 1 - i;
130                         if idx & (1 << bitpos) == (1 << bitpos) {
131                                 res[(bitpos / 8) as usize] ^= 1 << (bitpos & 7);
132                                 res = Sha256::hash(&res).into_inner();
133                         }
134                 }
135                 res
136         }
137
138         pub(crate) fn provide_secret(&mut self, idx: u64, secret: [u8; 32]) -> Result<(), ()> {
139                 let pos = Self::place_secret(idx);
140                 for i in 0..pos {
141                         let (old_secret, old_idx) = self.old_secrets[i as usize];
142                         if Self::derive_secret(secret, pos, old_idx) != old_secret {
143                                 return Err(());
144                         }
145                 }
146                 if self.get_min_seen_secret() <= idx {
147                         return Ok(());
148                 }
149                 self.old_secrets[pos as usize] = (secret, idx);
150                 Ok(())
151         }
152
153         /// Can only fail if idx is < get_min_seen_secret
154         pub(crate) fn get_secret(&self, idx: u64) -> Option<[u8; 32]> {
155                 for i in 0..self.old_secrets.len() {
156                         if (idx & (!((1 << i) - 1))) == self.old_secrets[i].1 {
157                                 return Some(Self::derive_secret(self.old_secrets[i].0, i as u8, idx))
158                         }
159                 }
160                 assert!(idx < self.get_min_seen_secret());
161                 None
162         }
163 }
164
165 impl Writeable for CounterpartyCommitmentSecrets {
166         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
167                 for &(ref secret, ref idx) in self.old_secrets.iter() {
168                         writer.write_all(secret)?;
169                         writer.write_all(&byte_utils::be64_to_array(*idx))?;
170                 }
171                 Ok(())
172         }
173 }
174 impl Readable for CounterpartyCommitmentSecrets {
175         fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
176                 let mut old_secrets = [([0; 32], 1 << 48); 49];
177                 for &mut (ref mut secret, ref mut idx) in old_secrets.iter_mut() {
178                         *secret = Readable::read(reader)?;
179                         *idx = Readable::read(reader)?;
180                 }
181
182                 Ok(Self { old_secrets })
183         }
184 }
185
186 /// Derives a per-commitment-transaction private key (eg an htlc key or delayed_payment key)
187 /// from the base secret and the per_commitment_point.
188 ///
189 /// Note that this is infallible iff we trust that at least one of the two input keys are randomly
190 /// generated (ie our own).
191 pub fn derive_private_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, base_secret: &SecretKey) -> Result<SecretKey, SecpError> {
192         let mut sha = Sha256::engine();
193         sha.input(&per_commitment_point.serialize());
194         sha.input(&PublicKey::from_secret_key(&secp_ctx, &base_secret).serialize());
195         let res = Sha256::from_engine(sha).into_inner();
196
197         let mut key = base_secret.clone();
198         key.add_assign(&res)?;
199         Ok(key)
200 }
201
202 /// Derives a per-commitment-transaction public key (eg an htlc key or a delayed_payment key)
203 /// from the base point and the per_commitment_key. This is the public equivalent of
204 /// derive_private_key - using only public keys to derive a public key instead of private keys.
205 ///
206 /// Note that this is infallible iff we trust that at least one of the two input keys are randomly
207 /// generated (ie our own).
208 pub fn derive_public_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, base_point: &PublicKey) -> Result<PublicKey, SecpError> {
209         let mut sha = Sha256::engine();
210         sha.input(&per_commitment_point.serialize());
211         sha.input(&base_point.serialize());
212         let res = Sha256::from_engine(sha).into_inner();
213
214         let hashkey = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&res)?);
215         base_point.combine(&hashkey)
216 }
217
218 /// Derives a per-commitment-transaction revocation key from its constituent parts.
219 ///
220 /// Only the cheating participant owns a valid witness to propagate a revoked 
221 /// commitment transaction, thus per_commitment_secret always come from cheater
222 /// and revocation_base_secret always come from punisher, which is the broadcaster
223 /// of the transaction spending with this key knowledge.
224 ///
225 /// Note that this is infallible iff we trust that at least one of the two input keys are randomly
226 /// generated (ie our own).
227 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> {
228         let countersignatory_revocation_base_point = PublicKey::from_secret_key(&secp_ctx, &countersignatory_revocation_base_secret);
229         let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &per_commitment_secret);
230
231         let rev_append_commit_hash_key = {
232                 let mut sha = Sha256::engine();
233                 sha.input(&countersignatory_revocation_base_point.serialize());
234                 sha.input(&per_commitment_point.serialize());
235
236                 Sha256::from_engine(sha).into_inner()
237         };
238         let commit_append_rev_hash_key = {
239                 let mut sha = Sha256::engine();
240                 sha.input(&per_commitment_point.serialize());
241                 sha.input(&countersignatory_revocation_base_point.serialize());
242
243                 Sha256::from_engine(sha).into_inner()
244         };
245
246         let mut countersignatory_contrib = countersignatory_revocation_base_secret.clone();
247         countersignatory_contrib.mul_assign(&rev_append_commit_hash_key)?;
248         let mut broadcaster_contrib = per_commitment_secret.clone();
249         broadcaster_contrib.mul_assign(&commit_append_rev_hash_key)?;
250         countersignatory_contrib.add_assign(&broadcaster_contrib[..])?;
251         Ok(countersignatory_contrib)
252 }
253
254 /// Derives a per-commitment-transaction revocation public key from its constituent parts. This is
255 /// the public equivalend of derive_private_revocation_key - using only public keys to derive a
256 /// public key instead of private keys.
257 ///
258 /// Only the cheating participant owns a valid witness to propagate a revoked 
259 /// commitment transaction, thus per_commitment_point always come from cheater
260 /// and revocation_base_point always come from punisher, which is the broadcaster
261 /// of the transaction spending with this key knowledge.
262 ///
263 /// Note that this is infallible iff we trust that at least one of the two input keys are randomly
264 /// generated (ie our own).
265 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> {
266         let rev_append_commit_hash_key = {
267                 let mut sha = Sha256::engine();
268                 sha.input(&countersignatory_revocation_base_point.serialize());
269                 sha.input(&per_commitment_point.serialize());
270
271                 Sha256::from_engine(sha).into_inner()
272         };
273         let commit_append_rev_hash_key = {
274                 let mut sha = Sha256::engine();
275                 sha.input(&per_commitment_point.serialize());
276                 sha.input(&countersignatory_revocation_base_point.serialize());
277
278                 Sha256::from_engine(sha).into_inner()
279         };
280
281         let mut countersignatory_contrib = countersignatory_revocation_base_point.clone();
282         countersignatory_contrib.mul_assign(&secp_ctx, &rev_append_commit_hash_key)?;
283         let mut broadcaster_contrib = per_commitment_point.clone();
284         broadcaster_contrib.mul_assign(&secp_ctx, &commit_append_rev_hash_key)?;
285         countersignatory_contrib.combine(&broadcaster_contrib)
286 }
287
288 /// The set of public keys which are used in the creation of one commitment transaction.
289 /// These are derived from the channel base keys and per-commitment data.
290 ///
291 /// A broadcaster key is provided from potential broadcaster of the computed transaction.
292 /// A countersignatory key is coming from a protocol participant unable to broadcast the
293 /// transaction.
294 ///
295 /// These keys are assumed to be good, either because the code derived them from
296 /// channel basepoints via the new function, or they were obtained via
297 /// PreCalculatedTxCreationKeys.trust_key_derivation because we trusted the source of the
298 /// pre-calculated keys.
299 #[derive(PartialEq, Clone)]
300 pub struct TxCreationKeys {
301         /// The broadcaster's per-commitment public key which was used to derive the other keys.
302         pub per_commitment_point: PublicKey,
303         /// The revocation key which is used to allow the broadcaster of the commitment
304         /// transaction to provide their counterparty the ability to punish them if they broadcast
305         /// an old state.
306         pub revocation_key: PublicKey,
307         /// Broadcaster's HTLC Key
308         pub broadcaster_htlc_key: PublicKey,
309         /// Countersignatory's HTLC Key
310         pub countersignatory_htlc_key: PublicKey,
311         /// Broadcaster's Payment Key (which isn't allowed to be spent from for some delay)
312         pub broadcaster_delayed_payment_key: PublicKey,
313 }
314 impl_writeable!(TxCreationKeys, 33*6,
315         { per_commitment_point, revocation_key, broadcaster_htlc_key, countersignatory_htlc_key, broadcaster_delayed_payment_key });
316
317 /// The per-commitment point and a set of pre-calculated public keys used for transaction creation
318 /// in the signer.
319 /// The pre-calculated keys are an optimization, because ChannelKeys has enough
320 /// information to re-derive them.
321 #[derive(PartialEq, Clone)]
322 pub struct PreCalculatedTxCreationKeys(TxCreationKeys);
323
324 impl PreCalculatedTxCreationKeys {
325         /// Create a new PreCalculatedTxCreationKeys from TxCreationKeys
326         pub fn new(keys: TxCreationKeys) -> Self {
327                 PreCalculatedTxCreationKeys(keys)
328         }
329
330         /// The pre-calculated transaction creation public keys.
331         /// An external validating signer should not trust these keys.
332         pub fn trust_key_derivation(&self) -> &TxCreationKeys {
333                 &self.0
334         }
335
336         /// The transaction per-commitment point
337         pub fn per_commitment_point(&self) -> &PublicKey {
338                 &self.0.per_commitment_point
339         }
340 }
341
342 /// One counterparty's public keys which do not change over the life of a channel.
343 #[derive(Clone, PartialEq)]
344 pub struct ChannelPublicKeys {
345         /// The public key which is used to sign all commitment transactions, as it appears in the
346         /// on-chain channel lock-in 2-of-2 multisig output.
347         pub funding_pubkey: PublicKey,
348         /// The base point which is used (with derive_public_revocation_key) to derive per-commitment
349         /// revocation keys. This is combined with the per-commitment-secret generated by the
350         /// counterparty to create a secret which the counterparty can reveal to revoke previous
351         /// states.
352         pub revocation_basepoint: PublicKey,
353         /// The public key on which the non-broadcaster (ie the countersignatory) receives an immediately
354         /// spendable primary channel balance on the broadcaster's commitment transaction. This key is
355         /// static across every commitment transaction.
356         pub payment_point: PublicKey,
357         /// The base point which is used (with derive_public_key) to derive a per-commitment payment
358         /// public key which receives non-HTLC-encumbered funds which are only available for spending
359         /// after some delay (or can be claimed via the revocation path).
360         pub delayed_payment_basepoint: PublicKey,
361         /// The base point which is used (with derive_public_key) to derive a per-commitment public key
362         /// which is used to encumber HTLC-in-flight outputs.
363         pub htlc_basepoint: PublicKey,
364 }
365
366 impl_writeable!(ChannelPublicKeys, 33*5, {
367         funding_pubkey,
368         revocation_basepoint,
369         payment_point,
370         delayed_payment_basepoint,
371         htlc_basepoint
372 });
373
374
375 impl TxCreationKeys {
376         /// Create a new TxCreationKeys from channel base points and the per-commitment point
377         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> {
378                 Ok(TxCreationKeys {
379                         per_commitment_point: per_commitment_point.clone(),
380                         revocation_key: derive_public_revocation_key(&secp_ctx, &per_commitment_point, &countersignatory_revocation_base)?,
381                         broadcaster_htlc_key: derive_public_key(&secp_ctx, &per_commitment_point, &broadcaster_htlc_base)?,
382                         countersignatory_htlc_key: derive_public_key(&secp_ctx, &per_commitment_point, &countersignatory_htlc_base)?,
383                         broadcaster_delayed_payment_key: derive_public_key(&secp_ctx, &per_commitment_point, &broadcaster_delayed_payment_base)?,
384                 })
385         }
386 }
387
388 /// A script either spendable by the revocation
389 /// key or the broadcaster_delayed_payment_key and satisfying the relative-locktime OP_CSV constrain.
390 /// Encumbering a `to_holder` output on a commitment transaction or 2nd-stage HTLC transactions.
391 pub fn get_revokeable_redeemscript(revocation_key: &PublicKey, contest_delay: u16, broadcaster_delayed_payment_key: &PublicKey) -> Script {
392         Builder::new().push_opcode(opcodes::all::OP_IF)
393                       .push_slice(&revocation_key.serialize())
394                       .push_opcode(opcodes::all::OP_ELSE)
395                       .push_int(contest_delay as i64)
396                       .push_opcode(opcodes::all::OP_CSV)
397                       .push_opcode(opcodes::all::OP_DROP)
398                       .push_slice(&broadcaster_delayed_payment_key.serialize())
399                       .push_opcode(opcodes::all::OP_ENDIF)
400                       .push_opcode(opcodes::all::OP_CHECKSIG)
401                       .into_script()
402 }
403
404 #[derive(Clone, PartialEq)]
405 /// Information about an HTLC as it appears in a commitment transaction
406 pub struct HTLCOutputInCommitment {
407         /// Whether the HTLC was "offered" (ie outbound in relation to this commitment transaction).
408         /// Note that this is not the same as whether it is ountbound *from us*. To determine that you
409         /// need to compare this value to whether the commitment transaction in question is that of
410         /// the counterparty or our own.
411         pub offered: bool,
412         /// The value, in msat, of the HTLC. The value as it appears in the commitment transaction is
413         /// this divided by 1000.
414         pub amount_msat: u64,
415         /// The CLTV lock-time at which this HTLC expires.
416         pub cltv_expiry: u32,
417         /// The hash of the preimage which unlocks this HTLC.
418         pub payment_hash: PaymentHash,
419         /// The position within the commitment transactions' outputs. This may be None if the value is
420         /// below the dust limit (in which case no output appears in the commitment transaction and the
421         /// value is spent to additional transaction fees).
422         pub transaction_output_index: Option<u32>,
423 }
424
425 impl_writeable!(HTLCOutputInCommitment, 1 + 8 + 4 + 32 + 5, {
426         offered,
427         amount_msat,
428         cltv_expiry,
429         payment_hash,
430         transaction_output_index
431 });
432
433 #[inline]
434 pub(crate) fn get_htlc_redeemscript_with_explicit_keys(htlc: &HTLCOutputInCommitment, broadcaster_htlc_key: &PublicKey, countersignatory_htlc_key: &PublicKey, revocation_key: &PublicKey) -> Script {
435         let payment_hash160 = Ripemd160::hash(&htlc.payment_hash.0[..]).into_inner();
436         if htlc.offered {
437                 Builder::new().push_opcode(opcodes::all::OP_DUP)
438                               .push_opcode(opcodes::all::OP_HASH160)
439                               .push_slice(&PubkeyHash::hash(&revocation_key.serialize())[..])
440                               .push_opcode(opcodes::all::OP_EQUAL)
441                               .push_opcode(opcodes::all::OP_IF)
442                               .push_opcode(opcodes::all::OP_CHECKSIG)
443                               .push_opcode(opcodes::all::OP_ELSE)
444                               .push_slice(&countersignatory_htlc_key.serialize()[..])
445                               .push_opcode(opcodes::all::OP_SWAP)
446                               .push_opcode(opcodes::all::OP_SIZE)
447                               .push_int(32)
448                               .push_opcode(opcodes::all::OP_EQUAL)
449                               .push_opcode(opcodes::all::OP_NOTIF)
450                               .push_opcode(opcodes::all::OP_DROP)
451                               .push_int(2)
452                               .push_opcode(opcodes::all::OP_SWAP)
453                               .push_slice(&broadcaster_htlc_key.serialize()[..])
454                               .push_int(2)
455                               .push_opcode(opcodes::all::OP_CHECKMULTISIG)
456                               .push_opcode(opcodes::all::OP_ELSE)
457                               .push_opcode(opcodes::all::OP_HASH160)
458                               .push_slice(&payment_hash160)
459                               .push_opcode(opcodes::all::OP_EQUALVERIFY)
460                               .push_opcode(opcodes::all::OP_CHECKSIG)
461                               .push_opcode(opcodes::all::OP_ENDIF)
462                               .push_opcode(opcodes::all::OP_ENDIF)
463                               .into_script()
464         } else {
465                 Builder::new().push_opcode(opcodes::all::OP_DUP)
466                               .push_opcode(opcodes::all::OP_HASH160)
467                               .push_slice(&PubkeyHash::hash(&revocation_key.serialize())[..])
468                               .push_opcode(opcodes::all::OP_EQUAL)
469                               .push_opcode(opcodes::all::OP_IF)
470                               .push_opcode(opcodes::all::OP_CHECKSIG)
471                               .push_opcode(opcodes::all::OP_ELSE)
472                               .push_slice(&countersignatory_htlc_key.serialize()[..])
473                               .push_opcode(opcodes::all::OP_SWAP)
474                               .push_opcode(opcodes::all::OP_SIZE)
475                               .push_int(32)
476                               .push_opcode(opcodes::all::OP_EQUAL)
477                               .push_opcode(opcodes::all::OP_IF)
478                               .push_opcode(opcodes::all::OP_HASH160)
479                               .push_slice(&payment_hash160)
480                               .push_opcode(opcodes::all::OP_EQUALVERIFY)
481                               .push_int(2)
482                               .push_opcode(opcodes::all::OP_SWAP)
483                               .push_slice(&broadcaster_htlc_key.serialize()[..])
484                               .push_int(2)
485                               .push_opcode(opcodes::all::OP_CHECKMULTISIG)
486                               .push_opcode(opcodes::all::OP_ELSE)
487                               .push_opcode(opcodes::all::OP_DROP)
488                               .push_int(htlc.cltv_expiry as i64)
489                               .push_opcode(opcodes::all::OP_CLTV)
490                               .push_opcode(opcodes::all::OP_DROP)
491                               .push_opcode(opcodes::all::OP_CHECKSIG)
492                               .push_opcode(opcodes::all::OP_ENDIF)
493                               .push_opcode(opcodes::all::OP_ENDIF)
494                               .into_script()
495         }
496 }
497
498 /// Gets the witness redeemscript for an HTLC output in a commitment transaction. Note that htlc
499 /// does not need to have its previous_output_index filled.
500 #[inline]
501 pub fn get_htlc_redeemscript(htlc: &HTLCOutputInCommitment, keys: &TxCreationKeys) -> Script {
502         get_htlc_redeemscript_with_explicit_keys(htlc, &keys.broadcaster_htlc_key, &keys.countersignatory_htlc_key, &keys.revocation_key)
503 }
504
505 /// Gets the redeemscript for a funding output from the two funding public keys.
506 /// Note that the order of funding public keys does not matter.
507 pub fn make_funding_redeemscript(broadcaster: &PublicKey, countersignatory: &PublicKey) -> Script {
508         let broadcaster_funding_key = broadcaster.serialize();
509         let countersignatory_funding_key = countersignatory.serialize();
510
511         let builder = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2);
512         if broadcaster_funding_key[..] < countersignatory_funding_key[..] {
513                 builder.push_slice(&broadcaster_funding_key)
514                         .push_slice(&countersignatory_funding_key)
515         } else {
516                 builder.push_slice(&countersignatory_funding_key)
517                         .push_slice(&broadcaster_funding_key)
518         }.push_opcode(opcodes::all::OP_PUSHNUM_2).push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script()
519 }
520
521 /// panics if htlc.transaction_output_index.is_none()!
522 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 {
523         let mut txins: Vec<TxIn> = Vec::new();
524         txins.push(TxIn {
525                 previous_output: OutPoint {
526                         txid: prev_hash.clone(),
527                         vout: htlc.transaction_output_index.expect("Can't build an HTLC transaction for a dust output"),
528                 },
529                 script_sig: Script::new(),
530                 sequence: 0,
531                 witness: Vec::new(),
532         });
533
534         let total_fee = if htlc.offered {
535                         feerate_per_kw as u64 * HTLC_TIMEOUT_TX_WEIGHT / 1000
536                 } else {
537                         feerate_per_kw as u64 * HTLC_SUCCESS_TX_WEIGHT / 1000
538                 };
539
540         let mut txouts: Vec<TxOut> = Vec::new();
541         txouts.push(TxOut {
542                 script_pubkey: get_revokeable_redeemscript(revocation_key, contest_delay, broadcaster_delayed_payment_key).to_v0_p2wsh(),
543                 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)
544         });
545
546         Transaction {
547                 version: 2,
548                 lock_time: if htlc.offered { htlc.cltv_expiry } else { 0 },
549                 input: txins,
550                 output: txouts,
551         }
552 }
553
554 #[derive(Clone)]
555 /// We use this to track holder commitment transactions and put off signing them until we are ready
556 /// to broadcast. This class can be used inside a signer implementation to generate a signature
557 /// given the relevant secret key.
558 pub struct HolderCommitmentTransaction {
559         // TODO: We should migrate away from providing the transaction, instead providing enough to
560         // allow the ChannelKeys to construct it from scratch. Luckily we already have HTLC data here,
561         // so we're probably most of the way there.
562         /// The commitment transaction itself, in unsigned form.
563         pub unsigned_tx: Transaction,
564         /// Our counterparty's signature for the transaction, above.
565         pub counterparty_sig: Signature,
566         // Which order the signatures should go in when constructing the final commitment tx witness.
567         // The user should be able to reconstruc this themselves, so we don't bother to expose it.
568         holder_sig_first: bool,
569         pub(crate) keys: TxCreationKeys,
570         /// The feerate paid per 1000-weight-unit in this commitment transaction. This value is
571         /// controlled by the channel initiator.
572         pub feerate_per_kw: u32,
573         /// The HTLCs and counterparty htlc signatures which were included in this commitment transaction.
574         ///
575         /// Note that this includes all HTLCs, including ones which were considered dust and not
576         /// actually included in the transaction as it appears on-chain, but who's value is burned as
577         /// fees and not included in the to_holder or to_counterparty outputs.
578         ///
579         /// The counterparty HTLC signatures in the second element will always be set for non-dust HTLCs, ie
580         /// those for which transaction_output_index.is_some().
581         pub per_htlc: Vec<(HTLCOutputInCommitment, Option<Signature>)>,
582 }
583 impl HolderCommitmentTransaction {
584         #[cfg(test)]
585         pub fn dummy() -> Self {
586                 let dummy_input = TxIn {
587                         previous_output: OutPoint {
588                                 txid: Default::default(),
589                                 vout: 0,
590                         },
591                         script_sig: Default::default(),
592                         sequence: 0,
593                         witness: vec![]
594                 };
595                 let dummy_key = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&[42; 32]).unwrap());
596                 let dummy_sig = Secp256k1::new().sign(&secp256k1::Message::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[42; 32]).unwrap());
597                 Self {
598                         unsigned_tx: Transaction {
599                                 version: 2,
600                                 input: vec![dummy_input],
601                                 output: Vec::new(),
602                                 lock_time: 0,
603                         },
604                         counterparty_sig: dummy_sig,
605                         holder_sig_first: false,
606                         keys: TxCreationKeys {
607                                         per_commitment_point: dummy_key.clone(),
608                                         revocation_key: dummy_key.clone(),
609                                         broadcaster_htlc_key: dummy_key.clone(),
610                                         countersignatory_htlc_key: dummy_key.clone(),
611                                         broadcaster_delayed_payment_key: dummy_key.clone(),
612                                 },
613                         feerate_per_kw: 0,
614                         per_htlc: Vec::new()
615                 }
616         }
617
618         /// Generate a new HolderCommitmentTransaction based on a raw commitment transaction,
619         /// counterparty signature and both parties keys.
620         ///
621         /// The unsigned transaction outputs must be consistent with htlc_data.  This function
622         /// only checks that the shape and amounts are consistent, but does not check the scriptPubkey.
623         pub fn new_missing_holder_sig(unsigned_tx: Transaction, counterparty_sig: Signature, holder_funding_key: &PublicKey, counterparty_funding_key: &PublicKey, keys: TxCreationKeys, feerate_per_kw: u32, htlc_data: Vec<(HTLCOutputInCommitment, Option<Signature>)>) -> HolderCommitmentTransaction {
624                 if unsigned_tx.input.len() != 1 { panic!("Tried to store a commitment transaction that had input count != 1!"); }
625                 if unsigned_tx.input[0].witness.len() != 0 { panic!("Tried to store a signed commitment transaction?"); }
626
627                 for htlc in &htlc_data {
628                         if let Some(index) = htlc.0.transaction_output_index {
629                                 let out = &unsigned_tx.output[index as usize];
630                                 if out.value != htlc.0.amount_msat / 1000 {
631                                         panic!("HTLC at index {} has incorrect amount", index);
632                                 }
633                                 if !out.script_pubkey.is_v0_p2wsh() {
634                                         panic!("HTLC at index {} doesn't have p2wsh scriptPubkey", index);
635                                 }
636                         }
637                 }
638
639                 Self {
640                         unsigned_tx,
641                         counterparty_sig,
642                         holder_sig_first: holder_funding_key.serialize()[..] < counterparty_funding_key.serialize()[..],
643                         keys,
644                         feerate_per_kw,
645                         per_htlc: htlc_data,
646                 }
647         }
648
649         /// The pre-calculated transaction creation public keys.
650         /// An external validating signer should not trust these keys.
651         pub fn trust_key_derivation(&self) -> &TxCreationKeys {
652                 &self.keys
653         }
654
655         /// Get the txid of the holder commitment transaction contained in this
656         /// HolderCommitmentTransaction
657         pub fn txid(&self) -> Txid {
658                 self.unsigned_tx.txid()
659         }
660
661         /// Gets holder signature for the contained commitment transaction given holder funding private key.
662         ///
663         /// Funding key is your key included in the 2-2 funding_outpoint lock. Should be provided
664         /// by your ChannelKeys.
665         /// Funding redeemscript is script locking funding_outpoint. This is the mutlsig script
666         /// between your own funding key and your counterparty's. Currently, this is provided in
667         /// ChannelKeys::sign_holder_commitment() calls directly.
668         /// Channel value is amount locked in funding_outpoint.
669         pub fn get_holder_sig<T: secp256k1::Signing>(&self, funding_key: &SecretKey, funding_redeemscript: &Script, channel_value_satoshis: u64, secp_ctx: &Secp256k1<T>) -> Signature {
670                 let sighash = hash_to_message!(&bip143::SigHashCache::new(&self.unsigned_tx)
671                         .signature_hash(0, funding_redeemscript, channel_value_satoshis, SigHashType::All)[..]);
672                 secp_ctx.sign(&sighash, funding_key)
673         }
674
675         pub(crate) fn add_holder_sig(&self, funding_redeemscript: &Script, holder_sig: Signature) -> Transaction {
676                 let mut tx = self.unsigned_tx.clone();
677                 // First push the multisig dummy, note that due to BIP147 (NULLDUMMY) it must be a zero-length element.
678                 tx.input[0].witness.push(Vec::new());
679
680                 if self.holder_sig_first {
681                         tx.input[0].witness.push(holder_sig.serialize_der().to_vec());
682                         tx.input[0].witness.push(self.counterparty_sig.serialize_der().to_vec());
683                 } else {
684                         tx.input[0].witness.push(self.counterparty_sig.serialize_der().to_vec());
685                         tx.input[0].witness.push(holder_sig.serialize_der().to_vec());
686                 }
687                 tx.input[0].witness[1].push(SigHashType::All as u8);
688                 tx.input[0].witness[2].push(SigHashType::All as u8);
689
690                 tx.input[0].witness.push(funding_redeemscript.as_bytes().to_vec());
691                 tx
692         }
693
694         /// Get a signature for each HTLC which was included in the commitment transaction (ie for
695         /// which HTLCOutputInCommitment::transaction_output_index.is_some()).
696         ///
697         /// The returned Vec has one entry for each HTLC, and in the same order. For HTLCs which were
698         /// considered dust and not included, a None entry exists, for all others a signature is
699         /// included.
700         pub fn get_htlc_sigs<T: secp256k1::Signing + secp256k1::Verification>(&self, htlc_base_key: &SecretKey, counterparty_selected_contest_delay: u16, secp_ctx: &Secp256k1<T>) -> Result<Vec<Option<Signature>>, ()> {
701                 let txid = self.txid();
702                 let mut ret = Vec::with_capacity(self.per_htlc.len());
703                 let holder_htlc_key = derive_private_key(secp_ctx, &self.keys.per_commitment_point, htlc_base_key).map_err(|_| ())?;
704
705                 for this_htlc in self.per_htlc.iter() {
706                         if this_htlc.0.transaction_output_index.is_some() {
707                                 let htlc_tx = build_htlc_transaction(&txid, self.feerate_per_kw, counterparty_selected_contest_delay, &this_htlc.0, &self.keys.broadcaster_delayed_payment_key, &self.keys.revocation_key);
708
709                                 let htlc_redeemscript = get_htlc_redeemscript_with_explicit_keys(&this_htlc.0, &self.keys.broadcaster_htlc_key, &self.keys.countersignatory_htlc_key, &self.keys.revocation_key);
710
711                                 let sighash = hash_to_message!(&bip143::SigHashCache::new(&htlc_tx).signature_hash(0, &htlc_redeemscript, this_htlc.0.amount_msat / 1000, SigHashType::All)[..]);
712                                 ret.push(Some(secp_ctx.sign(&sighash, &holder_htlc_key)));
713                         } else {
714                                 ret.push(None);
715                         }
716                 }
717                 Ok(ret)
718         }
719
720         /// Gets a signed HTLC transaction given a preimage (for !htlc.offered) and the holder HTLC transaction signature.
721         pub(crate) fn get_signed_htlc_tx(&self, htlc_index: usize, signature: &Signature, preimage: &Option<PaymentPreimage>, counterparty_selected_contest_delay: u16) -> Transaction {
722                 let txid = self.txid();
723                 let this_htlc = &self.per_htlc[htlc_index];
724                 assert!(this_htlc.0.transaction_output_index.is_some());
725                 // if we don't have preimage for an HTLC-Success, we can't generate an HTLC transaction.
726                 if !this_htlc.0.offered && preimage.is_none() { unreachable!(); }
727                 // Further, we should never be provided the preimage for an HTLC-Timeout transaction.
728                 if  this_htlc.0.offered && preimage.is_some() { unreachable!(); }
729
730                 let mut htlc_tx = build_htlc_transaction(&txid, self.feerate_per_kw, counterparty_selected_contest_delay, &this_htlc.0, &self.keys.broadcaster_delayed_payment_key, &self.keys.revocation_key);
731                 // Channel should have checked that we have a counterparty signature for this HTLC at
732                 // creation, and we should have a sensible htlc transaction:
733                 assert!(this_htlc.1.is_some());
734
735                 let htlc_redeemscript = get_htlc_redeemscript_with_explicit_keys(&this_htlc.0, &self.keys.broadcaster_htlc_key, &self.keys.countersignatory_htlc_key, &self.keys.revocation_key);
736
737                 // First push the multisig dummy, note that due to BIP147 (NULLDUMMY) it must be a zero-length element.
738                 htlc_tx.input[0].witness.push(Vec::new());
739
740                 htlc_tx.input[0].witness.push(this_htlc.1.unwrap().serialize_der().to_vec());
741                 htlc_tx.input[0].witness.push(signature.serialize_der().to_vec());
742                 htlc_tx.input[0].witness[1].push(SigHashType::All as u8);
743                 htlc_tx.input[0].witness[2].push(SigHashType::All as u8);
744
745                 if this_htlc.0.offered {
746                         // Due to BIP146 (MINIMALIF) this must be a zero-length element to relay.
747                         htlc_tx.input[0].witness.push(Vec::new());
748                 } else {
749                         htlc_tx.input[0].witness.push(preimage.unwrap().0.to_vec());
750                 }
751
752                 htlc_tx.input[0].witness.push(htlc_redeemscript.as_bytes().to_vec());
753                 htlc_tx
754         }
755 }
756 impl PartialEq for HolderCommitmentTransaction {
757         // We dont care whether we are signed in equality comparison
758         fn eq(&self, o: &Self) -> bool {
759                 self.txid() == o.txid()
760         }
761 }
762 impl Writeable for HolderCommitmentTransaction {
763         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
764                 if let Err(e) = self.unsigned_tx.consensus_encode(&mut WriterWriteAdaptor(writer)) {
765                         match e {
766                                 encode::Error::Io(e) => return Err(e),
767                                 _ => panic!("holder tx must have been well-formed!"),
768                         }
769                 }
770                 self.counterparty_sig.write(writer)?;
771                 self.holder_sig_first.write(writer)?;
772                 self.keys.write(writer)?;
773                 self.feerate_per_kw.write(writer)?;
774                 writer.write_all(&byte_utils::be64_to_array(self.per_htlc.len() as u64))?;
775                 for &(ref htlc, ref sig) in self.per_htlc.iter() {
776                         htlc.write(writer)?;
777                         sig.write(writer)?;
778                 }
779                 Ok(())
780         }
781 }
782 impl Readable for HolderCommitmentTransaction {
783         fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
784                 let unsigned_tx = match Transaction::consensus_decode(reader.by_ref()) {
785                         Ok(tx) => tx,
786                         Err(e) => match e {
787                                 encode::Error::Io(ioe) => return Err(DecodeError::Io(ioe)),
788                                 _ => return Err(DecodeError::InvalidValue),
789                         },
790                 };
791                 let counterparty_sig = Readable::read(reader)?;
792                 let holder_sig_first = Readable::read(reader)?;
793                 let keys = Readable::read(reader)?;
794                 let feerate_per_kw = Readable::read(reader)?;
795                 let htlcs_count: u64 = Readable::read(reader)?;
796                 let mut per_htlc = Vec::with_capacity(cmp::min(htlcs_count as usize, MAX_ALLOC_SIZE / mem::size_of::<(HTLCOutputInCommitment, Option<Signature>)>()));
797                 for _ in 0..htlcs_count {
798                         let htlc: HTLCOutputInCommitment = Readable::read(reader)?;
799                         let sigs = Readable::read(reader)?;
800                         per_htlc.push((htlc, sigs));
801                 }
802
803                 if unsigned_tx.input.len() != 1 {
804                         // Ensure tx didn't hit the 0-input ambiguity case.
805                         return Err(DecodeError::InvalidValue);
806                 }
807                 Ok(Self {
808                         unsigned_tx,
809                         counterparty_sig,
810                         holder_sig_first,
811                         keys,
812                         feerate_per_kw,
813                         per_htlc,
814                 })
815         }
816 }
817
818 #[cfg(test)]
819 mod tests {
820         use super::CounterpartyCommitmentSecrets;
821         use hex;
822
823         #[test]
824         fn test_per_commitment_storage() {
825                 // Test vectors from BOLT 3:
826                 let mut secrets: Vec<[u8; 32]> = Vec::new();
827                 let mut monitor;
828
829                 macro_rules! test_secrets {
830                         () => {
831                                 let mut idx = 281474976710655;
832                                 for secret in secrets.iter() {
833                                         assert_eq!(monitor.get_secret(idx).unwrap(), *secret);
834                                         idx -= 1;
835                                 }
836                                 assert_eq!(monitor.get_min_seen_secret(), idx + 1);
837                                 assert!(monitor.get_secret(idx).is_none());
838                         };
839                 }
840
841                 {
842                         // insert_secret correct sequence
843                         monitor = CounterpartyCommitmentSecrets::new();
844                         secrets.clear();
845
846                         secrets.push([0; 32]);
847                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
848                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
849                         test_secrets!();
850
851                         secrets.push([0; 32]);
852                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
853                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
854                         test_secrets!();
855
856                         secrets.push([0; 32]);
857                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
858                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
859                         test_secrets!();
860
861                         secrets.push([0; 32]);
862                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
863                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
864                         test_secrets!();
865
866                         secrets.push([0; 32]);
867                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
868                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
869                         test_secrets!();
870
871                         secrets.push([0; 32]);
872                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
873                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
874                         test_secrets!();
875
876                         secrets.push([0; 32]);
877                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
878                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
879                         test_secrets!();
880
881                         secrets.push([0; 32]);
882                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
883                         monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap();
884                         test_secrets!();
885                 }
886
887                 {
888                         // insert_secret #1 incorrect
889                         monitor = CounterpartyCommitmentSecrets::new();
890                         secrets.clear();
891
892                         secrets.push([0; 32]);
893                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
894                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
895                         test_secrets!();
896
897                         secrets.push([0; 32]);
898                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
899                         assert!(monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).is_err());
900                 }
901
902                 {
903                         // insert_secret #2 incorrect (#1 derived from incorrect)
904                         monitor = CounterpartyCommitmentSecrets::new();
905                         secrets.clear();
906
907                         secrets.push([0; 32]);
908                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
909                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
910                         test_secrets!();
911
912                         secrets.push([0; 32]);
913                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
914                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
915                         test_secrets!();
916
917                         secrets.push([0; 32]);
918                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
919                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
920                         test_secrets!();
921
922                         secrets.push([0; 32]);
923                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
924                         assert!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).is_err());
925                 }
926
927                 {
928                         // insert_secret #3 incorrect
929                         monitor = CounterpartyCommitmentSecrets::new();
930                         secrets.clear();
931
932                         secrets.push([0; 32]);
933                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
934                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
935                         test_secrets!();
936
937                         secrets.push([0; 32]);
938                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
939                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
940                         test_secrets!();
941
942                         secrets.push([0; 32]);
943                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
944                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
945                         test_secrets!();
946
947                         secrets.push([0; 32]);
948                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
949                         assert!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).is_err());
950                 }
951
952                 {
953                         // insert_secret #4 incorrect (1,2,3 derived from incorrect)
954                         monitor = CounterpartyCommitmentSecrets::new();
955                         secrets.clear();
956
957                         secrets.push([0; 32]);
958                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
959                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
960                         test_secrets!();
961
962                         secrets.push([0; 32]);
963                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
964                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
965                         test_secrets!();
966
967                         secrets.push([0; 32]);
968                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
969                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
970                         test_secrets!();
971
972                         secrets.push([0; 32]);
973                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("ba65d7b0ef55a3ba300d4e87af29868f394f8f138d78a7011669c79b37b936f4").unwrap());
974                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
975                         test_secrets!();
976
977                         secrets.push([0; 32]);
978                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
979                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
980                         test_secrets!();
981
982                         secrets.push([0; 32]);
983                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
984                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
985                         test_secrets!();
986
987                         secrets.push([0; 32]);
988                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
989                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
990                         test_secrets!();
991
992                         secrets.push([0; 32]);
993                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
994                         assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
995                 }
996
997                 {
998                         // insert_secret #5 incorrect
999                         monitor = CounterpartyCommitmentSecrets::new();
1000                         secrets.clear();
1001
1002                         secrets.push([0; 32]);
1003                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1004                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1005                         test_secrets!();
1006
1007                         secrets.push([0; 32]);
1008                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1009                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1010                         test_secrets!();
1011
1012                         secrets.push([0; 32]);
1013                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1014                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1015                         test_secrets!();
1016
1017                         secrets.push([0; 32]);
1018                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1019                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
1020                         test_secrets!();
1021
1022                         secrets.push([0; 32]);
1023                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
1024                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
1025                         test_secrets!();
1026
1027                         secrets.push([0; 32]);
1028                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1029                         assert!(monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).is_err());
1030                 }
1031
1032                 {
1033                         // insert_secret #6 incorrect (5 derived from incorrect)
1034                         monitor = CounterpartyCommitmentSecrets::new();
1035                         secrets.clear();
1036
1037                         secrets.push([0; 32]);
1038                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1039                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1040                         test_secrets!();
1041
1042                         secrets.push([0; 32]);
1043                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1044                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1045                         test_secrets!();
1046
1047                         secrets.push([0; 32]);
1048                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1049                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1050                         test_secrets!();
1051
1052                         secrets.push([0; 32]);
1053                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1054                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
1055                         test_secrets!();
1056
1057                         secrets.push([0; 32]);
1058                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
1059                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
1060                         test_secrets!();
1061
1062                         secrets.push([0; 32]);
1063                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("b7e76a83668bde38b373970155c868a653304308f9896692f904a23731224bb1").unwrap());
1064                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
1065                         test_secrets!();
1066
1067                         secrets.push([0; 32]);
1068                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1069                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
1070                         test_secrets!();
1071
1072                         secrets.push([0; 32]);
1073                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1074                         assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
1075                 }
1076
1077                 {
1078                         // insert_secret #7 incorrect
1079                         monitor = CounterpartyCommitmentSecrets::new();
1080                         secrets.clear();
1081
1082                         secrets.push([0; 32]);
1083                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1084                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1085                         test_secrets!();
1086
1087                         secrets.push([0; 32]);
1088                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1089                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1090                         test_secrets!();
1091
1092                         secrets.push([0; 32]);
1093                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1094                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1095                         test_secrets!();
1096
1097                         secrets.push([0; 32]);
1098                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1099                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
1100                         test_secrets!();
1101
1102                         secrets.push([0; 32]);
1103                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1104                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
1105                         test_secrets!();
1106
1107                         secrets.push([0; 32]);
1108                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1109                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
1110                         test_secrets!();
1111
1112                         secrets.push([0; 32]);
1113                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("e7971de736e01da8ed58b94c2fc216cb1dca9e326f3a96e7194fe8ea8af6c0a3").unwrap());
1114                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
1115                         test_secrets!();
1116
1117                         secrets.push([0; 32]);
1118                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1119                         assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
1120                 }
1121
1122                 {
1123                         // insert_secret #8 incorrect
1124                         monitor = CounterpartyCommitmentSecrets::new();
1125                         secrets.clear();
1126
1127                         secrets.push([0; 32]);
1128                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1129                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1130                         test_secrets!();
1131
1132                         secrets.push([0; 32]);
1133                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1134                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1135                         test_secrets!();
1136
1137                         secrets.push([0; 32]);
1138                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1139                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1140                         test_secrets!();
1141
1142                         secrets.push([0; 32]);
1143                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1144                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
1145                         test_secrets!();
1146
1147                         secrets.push([0; 32]);
1148                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1149                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
1150                         test_secrets!();
1151
1152                         secrets.push([0; 32]);
1153                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1154                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
1155                         test_secrets!();
1156
1157                         secrets.push([0; 32]);
1158                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1159                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
1160                         test_secrets!();
1161
1162                         secrets.push([0; 32]);
1163                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a7efbc61aac46d34f77778bac22c8a20c6a46ca460addc49009bda875ec88fa4").unwrap());
1164                         assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
1165                 }
1166         }
1167 }