Overhaul LocalCommitmentTx to new nomenclature
[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(super) 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(super) 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(super) 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         pub(super) 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(super) 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(super) 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 pub struct PreCalculatedTxCreationKeys(TxCreationKeys);
322
323 impl PreCalculatedTxCreationKeys {
324         /// Create a new PreCalculatedTxCreationKeys from TxCreationKeys
325         pub fn new(keys: TxCreationKeys) -> Self {
326                 PreCalculatedTxCreationKeys(keys)
327         }
328
329         /// The pre-calculated transaction creation public keys.
330         /// An external validating signer should not trust these keys.
331         pub fn trust_key_derivation(&self) -> &TxCreationKeys {
332                 &self.0
333         }
334
335         /// The transaction per-commitment point
336         pub fn per_commitment_point(&self) -> &PublicKey {
337                 &self.0.per_commitment_point
338         }
339 }
340
341 /// One counterparty's public keys which do not change over the life of a channel.
342 #[derive(Clone, PartialEq)]
343 pub struct ChannelPublicKeys {
344         /// The public key which is used to sign all commitment transactions, as it appears in the
345         /// on-chain channel lock-in 2-of-2 multisig output.
346         pub funding_pubkey: PublicKey,
347         /// The base point which is used (with derive_public_revocation_key) to derive per-commitment
348         /// revocation keys. This is combined with the per-commitment-secret generated by the
349         /// counterparty to create a secret which the counterparty can reveal to revoke previous
350         /// states.
351         pub revocation_basepoint: PublicKey,
352         /// The public key which receives our immediately spendable primary channel balance in
353         /// counterparty-broadcasted commitment transactions. This key is static across every commitment
354         /// transaction.
355         pub payment_point: PublicKey,
356         /// The base point which is used (with derive_public_key) to derive a per-commitment payment
357         /// public key which receives non-HTLC-encumbered funds which are only available for spending
358         /// after some delay (or can be claimed via the revocation path).
359         pub delayed_payment_basepoint: PublicKey,
360         /// The base point which is used (with derive_public_key) to derive a per-commitment public key
361         /// which is used to encumber HTLC-in-flight outputs.
362         pub htlc_basepoint: PublicKey,
363 }
364
365 impl_writeable!(ChannelPublicKeys, 33*5, {
366         funding_pubkey,
367         revocation_basepoint,
368         payment_point,
369         delayed_payment_basepoint,
370         htlc_basepoint
371 });
372
373
374 impl TxCreationKeys {
375         /// Create a new TxCreationKeys from channel base points and the per-commitment point
376         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> {
377                 Ok(TxCreationKeys {
378                         per_commitment_point: per_commitment_point.clone(),
379                         revocation_key: derive_public_revocation_key(&secp_ctx, &per_commitment_point, &countersignatory_revocation_base)?,
380                         broadcaster_htlc_key: derive_public_key(&secp_ctx, &per_commitment_point, &broadcaster_htlc_base)?,
381                         countersignatory_htlc_key: derive_public_key(&secp_ctx, &per_commitment_point, &countersignatory_htlc_base)?,
382                         broadcaster_delayed_payment_key: derive_public_key(&secp_ctx, &per_commitment_point, &broadcaster_delayed_payment_base)?,
383                 })
384         }
385 }
386
387 /// A script either spendable by the revocation
388 /// key or the broadcaster_delayed_payment_key and satisfying the relative-locktime OP_CSV constrain.
389 /// Encumbering a `to_local` output on a commitment transaction or 2nd-stage HTLC transactions.
390 pub fn get_revokeable_redeemscript(revocation_key: &PublicKey, contest_delay: u16, broadcaster_delayed_payment_key: &PublicKey) -> Script {
391         Builder::new().push_opcode(opcodes::all::OP_IF)
392                       .push_slice(&revocation_key.serialize())
393                       .push_opcode(opcodes::all::OP_ELSE)
394                       .push_int(contest_delay as i64)
395                       .push_opcode(opcodes::all::OP_CSV)
396                       .push_opcode(opcodes::all::OP_DROP)
397                       .push_slice(&broadcaster_delayed_payment_key.serialize())
398                       .push_opcode(opcodes::all::OP_ENDIF)
399                       .push_opcode(opcodes::all::OP_CHECKSIG)
400                       .into_script()
401 }
402
403 #[derive(Clone, PartialEq)]
404 /// Information about an HTLC as it appears in a commitment transaction
405 pub struct HTLCOutputInCommitment {
406         /// Whether the HTLC was "offered" (ie outbound in relation to this commitment transaction).
407         /// Note that this is not the same as whether it is ountbound *from us*. To determine that you
408         /// need to compare this value to whether the commitment transaction in question is that of
409         /// the counterparty or our own.
410         pub offered: bool,
411         /// The value, in msat, of the HTLC. The value as it appears in the commitment transaction is
412         /// this divided by 1000.
413         pub amount_msat: u64,
414         /// The CLTV lock-time at which this HTLC expires.
415         pub cltv_expiry: u32,
416         /// The hash of the preimage which unlocks this HTLC.
417         pub payment_hash: PaymentHash,
418         /// The position within the commitment transactions' outputs. This may be None if the value is
419         /// below the dust limit (in which case no output appears in the commitment transaction and the
420         /// value is spent to additional transaction fees).
421         pub transaction_output_index: Option<u32>,
422 }
423
424 impl_writeable!(HTLCOutputInCommitment, 1 + 8 + 4 + 32 + 5, {
425         offered,
426         amount_msat,
427         cltv_expiry,
428         payment_hash,
429         transaction_output_index
430 });
431
432 #[inline]
433 pub(crate) fn get_htlc_redeemscript_with_explicit_keys(htlc: &HTLCOutputInCommitment, broadcaster_htlc_key: &PublicKey, countersignatory_htlc_key: &PublicKey, revocation_key: &PublicKey) -> Script {
434         let payment_hash160 = Ripemd160::hash(&htlc.payment_hash.0[..]).into_inner();
435         if htlc.offered {
436                 Builder::new().push_opcode(opcodes::all::OP_DUP)
437                               .push_opcode(opcodes::all::OP_HASH160)
438                               .push_slice(&PubkeyHash::hash(&revocation_key.serialize())[..])
439                               .push_opcode(opcodes::all::OP_EQUAL)
440                               .push_opcode(opcodes::all::OP_IF)
441                               .push_opcode(opcodes::all::OP_CHECKSIG)
442                               .push_opcode(opcodes::all::OP_ELSE)
443                               .push_slice(&countersignatory_htlc_key.serialize()[..])
444                               .push_opcode(opcodes::all::OP_SWAP)
445                               .push_opcode(opcodes::all::OP_SIZE)
446                               .push_int(32)
447                               .push_opcode(opcodes::all::OP_EQUAL)
448                               .push_opcode(opcodes::all::OP_NOTIF)
449                               .push_opcode(opcodes::all::OP_DROP)
450                               .push_int(2)
451                               .push_opcode(opcodes::all::OP_SWAP)
452                               .push_slice(&broadcaster_htlc_key.serialize()[..])
453                               .push_int(2)
454                               .push_opcode(opcodes::all::OP_CHECKMULTISIG)
455                               .push_opcode(opcodes::all::OP_ELSE)
456                               .push_opcode(opcodes::all::OP_HASH160)
457                               .push_slice(&payment_hash160)
458                               .push_opcode(opcodes::all::OP_EQUALVERIFY)
459                               .push_opcode(opcodes::all::OP_CHECKSIG)
460                               .push_opcode(opcodes::all::OP_ENDIF)
461                               .push_opcode(opcodes::all::OP_ENDIF)
462                               .into_script()
463         } else {
464                 Builder::new().push_opcode(opcodes::all::OP_DUP)
465                               .push_opcode(opcodes::all::OP_HASH160)
466                               .push_slice(&PubkeyHash::hash(&revocation_key.serialize())[..])
467                               .push_opcode(opcodes::all::OP_EQUAL)
468                               .push_opcode(opcodes::all::OP_IF)
469                               .push_opcode(opcodes::all::OP_CHECKSIG)
470                               .push_opcode(opcodes::all::OP_ELSE)
471                               .push_slice(&countersignatory_htlc_key.serialize()[..])
472                               .push_opcode(opcodes::all::OP_SWAP)
473                               .push_opcode(opcodes::all::OP_SIZE)
474                               .push_int(32)
475                               .push_opcode(opcodes::all::OP_EQUAL)
476                               .push_opcode(opcodes::all::OP_IF)
477                               .push_opcode(opcodes::all::OP_HASH160)
478                               .push_slice(&payment_hash160)
479                               .push_opcode(opcodes::all::OP_EQUALVERIFY)
480                               .push_int(2)
481                               .push_opcode(opcodes::all::OP_SWAP)
482                               .push_slice(&broadcaster_htlc_key.serialize()[..])
483                               .push_int(2)
484                               .push_opcode(opcodes::all::OP_CHECKMULTISIG)
485                               .push_opcode(opcodes::all::OP_ELSE)
486                               .push_opcode(opcodes::all::OP_DROP)
487                               .push_int(htlc.cltv_expiry as i64)
488                               .push_opcode(opcodes::all::OP_CLTV)
489                               .push_opcode(opcodes::all::OP_DROP)
490                               .push_opcode(opcodes::all::OP_CHECKSIG)
491                               .push_opcode(opcodes::all::OP_ENDIF)
492                               .push_opcode(opcodes::all::OP_ENDIF)
493                               .into_script()
494         }
495 }
496
497 /// note here that 'revocation_key' is generated using countersignatory_revocation_basepoint and broadcaster's
498 /// commitment secret. 'htlc' does *not* need to have its previous_output_index filled.
499 #[inline]
500 pub fn get_htlc_redeemscript(htlc: &HTLCOutputInCommitment, keys: &TxCreationKeys) -> Script {
501         get_htlc_redeemscript_with_explicit_keys(htlc, &keys.broadcaster_htlc_key, &keys.countersignatory_htlc_key, &keys.revocation_key)
502 }
503
504 /// Gets the redeemscript for a funding output from the two funding public keys.
505 /// Note that the order of funding public keys does not matter.
506 pub fn make_funding_redeemscript(broadcaster: &PublicKey, countersignatory: &PublicKey) -> Script {
507         let broadcaster_funding_key = broadcaster.serialize();
508         let countersignatory_funding_key = countersignatory.serialize();
509
510         let builder = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2);
511         if broadcaster_funding_key[..] < countersignatory_funding_key[..] {
512                 builder.push_slice(&broadcaster_funding_key)
513                         .push_slice(&countersignatory_funding_key)
514         } else {
515                 builder.push_slice(&countersignatory_funding_key)
516                         .push_slice(&broadcaster_funding_key)
517         }.push_opcode(opcodes::all::OP_PUSHNUM_2).push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script()
518 }
519
520 /// panics if htlc.transaction_output_index.is_none()!
521 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 {
522         let mut txins: Vec<TxIn> = Vec::new();
523         txins.push(TxIn {
524                 previous_output: OutPoint {
525                         txid: prev_hash.clone(),
526                         vout: htlc.transaction_output_index.expect("Can't build an HTLC transaction for a dust output"),
527                 },
528                 script_sig: Script::new(),
529                 sequence: 0,
530                 witness: Vec::new(),
531         });
532
533         let total_fee = if htlc.offered {
534                         feerate_per_kw as u64 * HTLC_TIMEOUT_TX_WEIGHT / 1000
535                 } else {
536                         feerate_per_kw as u64 * HTLC_SUCCESS_TX_WEIGHT / 1000
537                 };
538
539         let mut txouts: Vec<TxOut> = Vec::new();
540         txouts.push(TxOut {
541                 script_pubkey: get_revokeable_redeemscript(revocation_key, contest_delay, broadcaster_delayed_payment_key).to_v0_p2wsh(),
542                 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)
543         });
544
545         Transaction {
546                 version: 2,
547                 lock_time: if htlc.offered { htlc.cltv_expiry } else { 0 },
548                 input: txins,
549                 output: txouts,
550         }
551 }
552
553 #[derive(Clone)]
554 /// We use this to track holder commitment transactions and put off signing them until we are ready
555 /// to broadcast. This class can be used inside a signer implementation to generate a signature
556 /// given the relevant secret key.
557 pub struct HolderCommitmentTransaction {
558         // TODO: We should migrate away from providing the transaction, instead providing enough to
559         // allow the ChannelKeys to construct it from scratch. Luckily we already have HTLC data here,
560         // so we're probably most of the way there.
561         /// The commitment transaction itself, in unsigned form.
562         pub unsigned_tx: Transaction,
563         /// Our counterparty's signature for the transaction, above.
564         pub counterparty_sig: Signature,
565         // Which order the signatures should go in when constructing the final commitment tx witness.
566         // The user should be able to reconstruc this themselves, so we don't bother to expose it.
567         holder_sig_first: bool,
568         pub(crate) keys: TxCreationKeys,
569         /// The feerate paid per 1000-weight-unit in this commitment transaction. This value is
570         /// controlled by the channel initiator.
571         pub feerate_per_kw: u32,
572         /// The HTLCs and counterparty htlc signatures which were included in this commitment transaction.
573         ///
574         /// Note that this includes all HTLCs, including ones which were considered dust and not
575         /// actually included in the transaction as it appears on-chain, but who's value is burned as
576         /// fees and not included in the to_holder or to_counterparty outputs.
577         ///
578         /// The counterparty HTLC signatures in the second element will always be set for non-dust HTLCs, ie
579         /// those for which transaction_output_index.is_some().
580         pub per_htlc: Vec<(HTLCOutputInCommitment, Option<Signature>)>,
581 }
582 impl HolderCommitmentTransaction {
583         #[cfg(test)]
584         pub fn dummy() -> Self {
585                 let dummy_input = TxIn {
586                         previous_output: OutPoint {
587                                 txid: Default::default(),
588                                 vout: 0,
589                         },
590                         script_sig: Default::default(),
591                         sequence: 0,
592                         witness: vec![]
593                 };
594                 let dummy_key = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&[42; 32]).unwrap());
595                 let dummy_sig = Secp256k1::new().sign(&secp256k1::Message::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[42; 32]).unwrap());
596                 Self {
597                         unsigned_tx: Transaction {
598                                 version: 2,
599                                 input: vec![dummy_input],
600                                 output: Vec::new(),
601                                 lock_time: 0,
602                         },
603                         counterparty_sig: dummy_sig,
604                         holder_sig_first: false,
605                         keys: TxCreationKeys {
606                                         per_commitment_point: dummy_key.clone(),
607                                         revocation_key: dummy_key.clone(),
608                                         broadcaster_htlc_key: dummy_key.clone(),
609                                         countersignatory_htlc_key: dummy_key.clone(),
610                                         broadcaster_delayed_payment_key: dummy_key.clone(),
611                                 },
612                         feerate_per_kw: 0,
613                         per_htlc: Vec::new()
614                 }
615         }
616
617         /// Generate a new HolderCommitmentTransaction based on a raw commitment transaction,
618         /// counterparty signature and both parties keys.
619         ///
620         /// The unsigned transaction outputs must be consistent with htlc_data.  This function
621         /// only checks that the shape and amounts are consistent, but does not check the scriptPubkey.
622         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 {
623                 if unsigned_tx.input.len() != 1 { panic!("Tried to store a commitment transaction that had input count != 1!"); }
624                 if unsigned_tx.input[0].witness.len() != 0 { panic!("Tried to store a signed commitment transaction?"); }
625
626                 for htlc in &htlc_data {
627                         if let Some(index) = htlc.0.transaction_output_index {
628                                 let out = &unsigned_tx.output[index as usize];
629                                 if out.value != htlc.0.amount_msat / 1000 {
630                                         panic!("HTLC at index {} has incorrect amount", index);
631                                 }
632                                 if !out.script_pubkey.is_v0_p2wsh() {
633                                         panic!("HTLC at index {} doesn't have p2wsh scriptPubkey", index);
634                                 }
635                         }
636                 }
637
638                 Self {
639                         unsigned_tx,
640                         counterparty_sig,
641                         holder_sig_first: holder_funding_key.serialize()[..] < counterparty_funding_key.serialize()[..],
642                         keys,
643                         feerate_per_kw,
644                         per_htlc: htlc_data,
645                 }
646         }
647
648         /// The pre-calculated transaction creation public keys.
649         /// An external validating signer should not trust these keys.
650         pub fn trust_key_derivation(&self) -> &TxCreationKeys {
651                 &self.keys
652         }
653
654         /// Get the txid of the holder commitment transaction contained in this
655         /// HolderCommitmentTransaction
656         pub fn txid(&self) -> Txid {
657                 self.unsigned_tx.txid()
658         }
659
660         /// Gets holder signature for the contained commitment transaction given holder funding private key.
661         ///
662         /// Funding key is your key included in the 2-2 funding_outpoint lock. Should be provided
663         /// by your ChannelKeys.
664         /// Funding redeemscript is script locking funding_outpoint. This is the mutlsig script
665         /// between your own funding key and your counterparty's. Currently, this is provided in
666         /// ChannelKeys::sign_holder_commitment() calls directly.
667         /// Channel value is amount locked in funding_outpoint.
668         pub fn get_holder_sig<T: secp256k1::Signing>(&self, funding_key: &SecretKey, funding_redeemscript: &Script, channel_value_satoshis: u64, secp_ctx: &Secp256k1<T>) -> Signature {
669                 let sighash = hash_to_message!(&bip143::SigHashCache::new(&self.unsigned_tx)
670                         .signature_hash(0, funding_redeemscript, channel_value_satoshis, SigHashType::All)[..]);
671                 secp_ctx.sign(&sighash, funding_key)
672         }
673
674         pub(crate) fn add_holder_sig(&self, funding_redeemscript: &Script, holder_sig: Signature) -> Transaction {
675                 let mut tx = self.unsigned_tx.clone();
676                 // First push the multisig dummy, note that due to BIP147 (NULLDUMMY) it must be a zero-length element.
677                 tx.input[0].witness.push(Vec::new());
678
679                 if self.holder_sig_first {
680                         tx.input[0].witness.push(holder_sig.serialize_der().to_vec());
681                         tx.input[0].witness.push(self.counterparty_sig.serialize_der().to_vec());
682                 } else {
683                         tx.input[0].witness.push(self.counterparty_sig.serialize_der().to_vec());
684                         tx.input[0].witness.push(holder_sig.serialize_der().to_vec());
685                 }
686                 tx.input[0].witness[1].push(SigHashType::All as u8);
687                 tx.input[0].witness[2].push(SigHashType::All as u8);
688
689                 tx.input[0].witness.push(funding_redeemscript.as_bytes().to_vec());
690                 tx
691         }
692
693         /// Get a signature for each HTLC which was included in the commitment transaction (ie for
694         /// which HTLCOutputInCommitment::transaction_output_index.is_some()).
695         ///
696         /// The returned Vec has one entry for each HTLC, and in the same order. For HTLCs which were
697         /// considered dust and not included, a None entry exists, for all others a signature is
698         /// included.
699         pub fn get_htlc_sigs<T: secp256k1::Signing + secp256k1::Verification>(&self, htlc_base_key: &SecretKey, holder_selected_contest_delay: u16, secp_ctx: &Secp256k1<T>) -> Result<Vec<Option<Signature>>, ()> {
700                 let txid = self.txid();
701                 let mut ret = Vec::with_capacity(self.per_htlc.len());
702                 let holder_htlc_key = derive_private_key(secp_ctx, &self.keys.per_commitment_point, htlc_base_key).map_err(|_| ())?;
703
704                 for this_htlc in self.per_htlc.iter() {
705                         if this_htlc.0.transaction_output_index.is_some() {
706                                 let htlc_tx = build_htlc_transaction(&txid, self.feerate_per_kw, holder_selected_contest_delay, &this_htlc.0, &self.keys.broadcaster_delayed_payment_key, &self.keys.revocation_key);
707
708                                 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);
709
710                                 let sighash = hash_to_message!(&bip143::SigHashCache::new(&htlc_tx).signature_hash(0, &htlc_redeemscript, this_htlc.0.amount_msat / 1000, SigHashType::All)[..]);
711                                 ret.push(Some(secp_ctx.sign(&sighash, &holder_htlc_key)));
712                         } else {
713                                 ret.push(None);
714                         }
715                 }
716                 Ok(ret)
717         }
718
719         /// Gets a signed HTLC transaction given a preimage (for !htlc.offered) and the holder HTLC transaction signature.
720         pub(crate) fn get_signed_htlc_tx(&self, htlc_index: usize, signature: &Signature, preimage: &Option<PaymentPreimage>, holder_selected_contest_delay: u16) -> Transaction {
721                 let txid = self.txid();
722                 let this_htlc = &self.per_htlc[htlc_index];
723                 assert!(this_htlc.0.transaction_output_index.is_some());
724                 // if we don't have preimage for an HTLC-Success, we can't generate an HTLC transaction.
725                 if !this_htlc.0.offered && preimage.is_none() { unreachable!(); }
726                 // Further, we should never be provided the preimage for an HTLC-Timeout transaction.
727                 if  this_htlc.0.offered && preimage.is_some() { unreachable!(); }
728
729                 let mut htlc_tx = build_htlc_transaction(&txid, self.feerate_per_kw, holder_selected_contest_delay, &this_htlc.0, &self.keys.broadcaster_delayed_payment_key, &self.keys.revocation_key);
730                 // Channel should have checked that we have a counterparty signature for this HTLC at
731                 // creation, and we should have a sensible htlc transaction:
732                 assert!(this_htlc.1.is_some());
733
734                 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);
735
736                 // First push the multisig dummy, note that due to BIP147 (NULLDUMMY) it must be a zero-length element.
737                 htlc_tx.input[0].witness.push(Vec::new());
738
739                 htlc_tx.input[0].witness.push(this_htlc.1.unwrap().serialize_der().to_vec());
740                 htlc_tx.input[0].witness.push(signature.serialize_der().to_vec());
741                 htlc_tx.input[0].witness[1].push(SigHashType::All as u8);
742                 htlc_tx.input[0].witness[2].push(SigHashType::All as u8);
743
744                 if this_htlc.0.offered {
745                         // Due to BIP146 (MINIMALIF) this must be a zero-length element to relay.
746                         htlc_tx.input[0].witness.push(Vec::new());
747                 } else {
748                         htlc_tx.input[0].witness.push(preimage.unwrap().0.to_vec());
749                 }
750
751                 htlc_tx.input[0].witness.push(htlc_redeemscript.as_bytes().to_vec());
752                 htlc_tx
753         }
754 }
755 impl PartialEq for HolderCommitmentTransaction {
756         // We dont care whether we are signed in equality comparison
757         fn eq(&self, o: &Self) -> bool {
758                 self.txid() == o.txid()
759         }
760 }
761 impl Writeable for HolderCommitmentTransaction {
762         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
763                 if let Err(e) = self.unsigned_tx.consensus_encode(&mut WriterWriteAdaptor(writer)) {
764                         match e {
765                                 encode::Error::Io(e) => return Err(e),
766                                 _ => panic!("holder tx must have been well-formed!"),
767                         }
768                 }
769                 self.counterparty_sig.write(writer)?;
770                 self.holder_sig_first.write(writer)?;
771                 self.keys.write(writer)?;
772                 self.feerate_per_kw.write(writer)?;
773                 writer.write_all(&byte_utils::be64_to_array(self.per_htlc.len() as u64))?;
774                 for &(ref htlc, ref sig) in self.per_htlc.iter() {
775                         htlc.write(writer)?;
776                         sig.write(writer)?;
777                 }
778                 Ok(())
779         }
780 }
781 impl Readable for HolderCommitmentTransaction {
782         fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
783                 let unsigned_tx = match Transaction::consensus_decode(reader.by_ref()) {
784                         Ok(tx) => tx,
785                         Err(e) => match e {
786                                 encode::Error::Io(ioe) => return Err(DecodeError::Io(ioe)),
787                                 _ => return Err(DecodeError::InvalidValue),
788                         },
789                 };
790                 let counterparty_sig = Readable::read(reader)?;
791                 let holder_sig_first = Readable::read(reader)?;
792                 let keys = Readable::read(reader)?;
793                 let feerate_per_kw = Readable::read(reader)?;
794                 let htlcs_count: u64 = Readable::read(reader)?;
795                 let mut per_htlc = Vec::with_capacity(cmp::min(htlcs_count as usize, MAX_ALLOC_SIZE / mem::size_of::<(HTLCOutputInCommitment, Option<Signature>)>()));
796                 for _ in 0..htlcs_count {
797                         let htlc: HTLCOutputInCommitment = Readable::read(reader)?;
798                         let sigs = Readable::read(reader)?;
799                         per_htlc.push((htlc, sigs));
800                 }
801
802                 if unsigned_tx.input.len() != 1 {
803                         // Ensure tx didn't hit the 0-input ambiguity case.
804                         return Err(DecodeError::InvalidValue);
805                 }
806                 Ok(Self {
807                         unsigned_tx,
808                         counterparty_sig,
809                         holder_sig_first,
810                         keys,
811                         feerate_per_kw,
812                         per_htlc,
813                 })
814         }
815 }
816
817 #[cfg(test)]
818 mod tests {
819         use super::CounterpartyCommitmentSecrets;
820         use hex;
821
822         #[test]
823         fn test_per_commitment_storage() {
824                 // Test vectors from BOLT 3:
825                 let mut secrets: Vec<[u8; 32]> = Vec::new();
826                 let mut monitor;
827
828                 macro_rules! test_secrets {
829                         () => {
830                                 let mut idx = 281474976710655;
831                                 for secret in secrets.iter() {
832                                         assert_eq!(monitor.get_secret(idx).unwrap(), *secret);
833                                         idx -= 1;
834                                 }
835                                 assert_eq!(monitor.get_min_seen_secret(), idx + 1);
836                                 assert!(monitor.get_secret(idx).is_none());
837                         };
838                 }
839
840                 {
841                         // insert_secret correct sequence
842                         monitor = CounterpartyCommitmentSecrets::new();
843                         secrets.clear();
844
845                         secrets.push([0; 32]);
846                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
847                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
848                         test_secrets!();
849
850                         secrets.push([0; 32]);
851                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
852                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
853                         test_secrets!();
854
855                         secrets.push([0; 32]);
856                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
857                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
858                         test_secrets!();
859
860                         secrets.push([0; 32]);
861                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
862                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
863                         test_secrets!();
864
865                         secrets.push([0; 32]);
866                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
867                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
868                         test_secrets!();
869
870                         secrets.push([0; 32]);
871                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
872                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
873                         test_secrets!();
874
875                         secrets.push([0; 32]);
876                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
877                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
878                         test_secrets!();
879
880                         secrets.push([0; 32]);
881                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
882                         monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap();
883                         test_secrets!();
884                 }
885
886                 {
887                         // insert_secret #1 incorrect
888                         monitor = CounterpartyCommitmentSecrets::new();
889                         secrets.clear();
890
891                         secrets.push([0; 32]);
892                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
893                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
894                         test_secrets!();
895
896                         secrets.push([0; 32]);
897                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
898                         assert!(monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).is_err());
899                 }
900
901                 {
902                         // insert_secret #2 incorrect (#1 derived from incorrect)
903                         monitor = CounterpartyCommitmentSecrets::new();
904                         secrets.clear();
905
906                         secrets.push([0; 32]);
907                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
908                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
909                         test_secrets!();
910
911                         secrets.push([0; 32]);
912                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
913                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
914                         test_secrets!();
915
916                         secrets.push([0; 32]);
917                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
918                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
919                         test_secrets!();
920
921                         secrets.push([0; 32]);
922                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
923                         assert!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).is_err());
924                 }
925
926                 {
927                         // insert_secret #3 incorrect
928                         monitor = CounterpartyCommitmentSecrets::new();
929                         secrets.clear();
930
931                         secrets.push([0; 32]);
932                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
933                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
934                         test_secrets!();
935
936                         secrets.push([0; 32]);
937                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
938                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
939                         test_secrets!();
940
941                         secrets.push([0; 32]);
942                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
943                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
944                         test_secrets!();
945
946                         secrets.push([0; 32]);
947                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
948                         assert!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).is_err());
949                 }
950
951                 {
952                         // insert_secret #4 incorrect (1,2,3 derived from incorrect)
953                         monitor = CounterpartyCommitmentSecrets::new();
954                         secrets.clear();
955
956                         secrets.push([0; 32]);
957                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
958                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
959                         test_secrets!();
960
961                         secrets.push([0; 32]);
962                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
963                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
964                         test_secrets!();
965
966                         secrets.push([0; 32]);
967                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
968                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
969                         test_secrets!();
970
971                         secrets.push([0; 32]);
972                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("ba65d7b0ef55a3ba300d4e87af29868f394f8f138d78a7011669c79b37b936f4").unwrap());
973                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
974                         test_secrets!();
975
976                         secrets.push([0; 32]);
977                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
978                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
979                         test_secrets!();
980
981                         secrets.push([0; 32]);
982                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
983                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
984                         test_secrets!();
985
986                         secrets.push([0; 32]);
987                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
988                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
989                         test_secrets!();
990
991                         secrets.push([0; 32]);
992                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
993                         assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
994                 }
995
996                 {
997                         // insert_secret #5 incorrect
998                         monitor = CounterpartyCommitmentSecrets::new();
999                         secrets.clear();
1000
1001                         secrets.push([0; 32]);
1002                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1003                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1004                         test_secrets!();
1005
1006                         secrets.push([0; 32]);
1007                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1008                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1009                         test_secrets!();
1010
1011                         secrets.push([0; 32]);
1012                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1013                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1014                         test_secrets!();
1015
1016                         secrets.push([0; 32]);
1017                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1018                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
1019                         test_secrets!();
1020
1021                         secrets.push([0; 32]);
1022                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
1023                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
1024                         test_secrets!();
1025
1026                         secrets.push([0; 32]);
1027                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1028                         assert!(monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).is_err());
1029                 }
1030
1031                 {
1032                         // insert_secret #6 incorrect (5 derived from incorrect)
1033                         monitor = CounterpartyCommitmentSecrets::new();
1034                         secrets.clear();
1035
1036                         secrets.push([0; 32]);
1037                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1038                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1039                         test_secrets!();
1040
1041                         secrets.push([0; 32]);
1042                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1043                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1044                         test_secrets!();
1045
1046                         secrets.push([0; 32]);
1047                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1048                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1049                         test_secrets!();
1050
1051                         secrets.push([0; 32]);
1052                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1053                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
1054                         test_secrets!();
1055
1056                         secrets.push([0; 32]);
1057                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
1058                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
1059                         test_secrets!();
1060
1061                         secrets.push([0; 32]);
1062                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("b7e76a83668bde38b373970155c868a653304308f9896692f904a23731224bb1").unwrap());
1063                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
1064                         test_secrets!();
1065
1066                         secrets.push([0; 32]);
1067                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1068                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
1069                         test_secrets!();
1070
1071                         secrets.push([0; 32]);
1072                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1073                         assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
1074                 }
1075
1076                 {
1077                         // insert_secret #7 incorrect
1078                         monitor = CounterpartyCommitmentSecrets::new();
1079                         secrets.clear();
1080
1081                         secrets.push([0; 32]);
1082                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1083                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1084                         test_secrets!();
1085
1086                         secrets.push([0; 32]);
1087                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1088                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1089                         test_secrets!();
1090
1091                         secrets.push([0; 32]);
1092                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1093                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1094                         test_secrets!();
1095
1096                         secrets.push([0; 32]);
1097                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1098                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
1099                         test_secrets!();
1100
1101                         secrets.push([0; 32]);
1102                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1103                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
1104                         test_secrets!();
1105
1106                         secrets.push([0; 32]);
1107                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1108                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
1109                         test_secrets!();
1110
1111                         secrets.push([0; 32]);
1112                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("e7971de736e01da8ed58b94c2fc216cb1dca9e326f3a96e7194fe8ea8af6c0a3").unwrap());
1113                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
1114                         test_secrets!();
1115
1116                         secrets.push([0; 32]);
1117                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1118                         assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
1119                 }
1120
1121                 {
1122                         // insert_secret #8 incorrect
1123                         monitor = CounterpartyCommitmentSecrets::new();
1124                         secrets.clear();
1125
1126                         secrets.push([0; 32]);
1127                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1128                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1129                         test_secrets!();
1130
1131                         secrets.push([0; 32]);
1132                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1133                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1134                         test_secrets!();
1135
1136                         secrets.push([0; 32]);
1137                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1138                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1139                         test_secrets!();
1140
1141                         secrets.push([0; 32]);
1142                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1143                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
1144                         test_secrets!();
1145
1146                         secrets.push([0; 32]);
1147                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1148                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
1149                         test_secrets!();
1150
1151                         secrets.push([0; 32]);
1152                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1153                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
1154                         test_secrets!();
1155
1156                         secrets.push([0; 32]);
1157                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1158                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
1159                         test_secrets!();
1160
1161                         secrets.push([0; 32]);
1162                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a7efbc61aac46d34f77778bac22c8a20c6a46ca460addc49009bda875ec88fa4").unwrap());
1163                         assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
1164                 }
1165         }
1166 }