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