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