Update the `gossip` and `router` module docs which were out of date
[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, EcdsaSighashType};
16 use bitcoin::util::sighash;
17 use bitcoin::util::address::Payload;
18
19 use bitcoin::hashes::{Hash, HashEngine};
20 use bitcoin::hashes::sha256::Hash as Sha256;
21 use bitcoin::hashes::ripemd160::Hash as Ripemd160;
22 use bitcoin::hash_types::{Txid, PubkeyHash};
23
24 use crate::ln::{PaymentHash, PaymentPreimage};
25 use crate::ln::msgs::DecodeError;
26 use crate::routing::gossip::NodeId;
27 use crate::util::ser::{Readable, Writeable, Writer};
28 use crate::util::transaction_utils;
29
30 use bitcoin::secp256k1::{SecretKey, PublicKey, Scalar};
31 use bitcoin::secp256k1::{Secp256k1, ecdsa::Signature, Message};
32 use bitcoin::{PackedLockTime, secp256k1, Sequence, Witness};
33 use bitcoin::PublicKey as BitcoinPublicKey;
34
35 use crate::io;
36 use crate::prelude::*;
37 use core::cmp;
38 use crate::ln::chan_utils;
39 use crate::util::transaction_utils::sort_outputs;
40 use crate::ln::channel::{INITIAL_COMMITMENT_NUMBER, ANCHOR_OUTPUT_VALUE_SATOSHI};
41 use core::ops::Deref;
42 use crate::chain;
43 use crate::util::crypto::sign;
44
45 /// Maximum number of one-way in-flight HTLC (protocol-level value).
46 pub const MAX_HTLCS: u16 = 483;
47 /// The weight of a BIP141 witnessScript for a BOLT3's "offered HTLC output" on a commitment transaction, non-anchor variant.
48 pub const OFFERED_HTLC_SCRIPT_WEIGHT: usize = 133;
49 /// The weight of a BIP141 witnessScript for a BOLT3's "offered HTLC output" on a commitment transaction, anchor variant.
50 pub const OFFERED_HTLC_SCRIPT_WEIGHT_ANCHORS: usize = 136;
51
52 /// The weight of a BIP141 witnessScript for a BOLT3's "received HTLC output" can vary in function of its CLTV argument value.
53 /// We define a range that encompasses both its non-anchors and anchors variants.
54 pub(crate) const MIN_ACCEPTED_HTLC_SCRIPT_WEIGHT: usize = 136;
55 /// The weight of a BIP141 witnessScript for a BOLT3's "received HTLC output" can vary in function of its CLTV argument value.
56 /// We define a range that encompasses both its non-anchors and anchors variants.
57 /// This is the maximum post-anchor value.
58 pub const MAX_ACCEPTED_HTLC_SCRIPT_WEIGHT: usize = 143;
59
60 /// Gets the weight for an HTLC-Success transaction.
61 #[inline]
62 pub fn htlc_success_tx_weight(opt_anchors: bool) -> u64 {
63         const HTLC_SUCCESS_TX_WEIGHT: u64 = 703;
64         const HTLC_SUCCESS_ANCHOR_TX_WEIGHT: u64 = 706;
65         if opt_anchors { HTLC_SUCCESS_ANCHOR_TX_WEIGHT } else { HTLC_SUCCESS_TX_WEIGHT }
66 }
67
68 /// Gets the weight for an HTLC-Timeout transaction.
69 #[inline]
70 pub fn htlc_timeout_tx_weight(opt_anchors: bool) -> u64 {
71         const HTLC_TIMEOUT_TX_WEIGHT: u64 = 663;
72         const HTLC_TIMEOUT_ANCHOR_TX_WEIGHT: u64 = 666;
73         if opt_anchors { HTLC_TIMEOUT_ANCHOR_TX_WEIGHT } else { HTLC_TIMEOUT_TX_WEIGHT }
74 }
75
76 /// Describes the type of HTLC claim as determined by analyzing the witness.
77 #[derive(PartialEq, Eq)]
78 pub enum HTLCClaim {
79         /// Claims an offered output on a commitment transaction through the timeout path.
80         OfferedTimeout,
81         /// Claims an offered output on a commitment transaction through the success path.
82         OfferedPreimage,
83         /// Claims an accepted output on a commitment transaction through the timeout path.
84         AcceptedTimeout,
85         /// Claims an accepted output on a commitment transaction through the success path.
86         AcceptedPreimage,
87         /// Claims an offered/accepted output on a commitment transaction through the revocation path.
88         Revocation,
89 }
90
91 impl HTLCClaim {
92         /// Check if a given input witness attempts to claim a HTLC.
93         pub fn from_witness(witness: &Witness) -> Option<Self> {
94                 debug_assert_eq!(OFFERED_HTLC_SCRIPT_WEIGHT_ANCHORS, MIN_ACCEPTED_HTLC_SCRIPT_WEIGHT);
95                 if witness.len() < 2 {
96                         return None;
97                 }
98                 let witness_script = witness.last().unwrap();
99                 let second_to_last = witness.second_to_last().unwrap();
100                 if witness_script.len() == OFFERED_HTLC_SCRIPT_WEIGHT {
101                         if witness.len() == 3 && second_to_last.len() == 33 {
102                                 // <revocation sig> <revocationpubkey> <witness_script>
103                                 Some(Self::Revocation)
104                         } else if witness.len() == 3 && second_to_last.len() == 32 {
105                                 // <remotehtlcsig> <payment_preimage> <witness_script>
106                                 Some(Self::OfferedPreimage)
107                         } else if witness.len() == 5 && second_to_last.len() == 0 {
108                                 // 0 <remotehtlcsig> <localhtlcsig> <> <witness_script>
109                                 Some(Self::OfferedTimeout)
110                         } else {
111                                 None
112                         }
113                 } else if witness_script.len() == OFFERED_HTLC_SCRIPT_WEIGHT_ANCHORS {
114                         // It's possible for the weight of `offered_htlc_script` and `accepted_htlc_script` to
115                         // match so we check for both here.
116                         if witness.len() == 3 && second_to_last.len() == 33 {
117                                 // <revocation sig> <revocationpubkey> <witness_script>
118                                 Some(Self::Revocation)
119                         } else if witness.len() == 3 && second_to_last.len() == 32 {
120                                 // <remotehtlcsig> <payment_preimage> <witness_script>
121                                 Some(Self::OfferedPreimage)
122                         } else if witness.len() == 5 && second_to_last.len() == 0 {
123                                 // 0 <remotehtlcsig> <localhtlcsig> <> <witness_script>
124                                 Some(Self::OfferedTimeout)
125                         } else if witness.len() == 3 && second_to_last.len() == 0 {
126                                 // <remotehtlcsig> <> <witness_script>
127                                 Some(Self::AcceptedTimeout)
128                         } else if witness.len() == 5 && second_to_last.len() == 32 {
129                                 // 0 <remotehtlcsig> <localhtlcsig> <payment_preimage> <witness_script>
130                                 Some(Self::AcceptedPreimage)
131                         } else {
132                                 None
133                         }
134                 } else if witness_script.len() > MIN_ACCEPTED_HTLC_SCRIPT_WEIGHT &&
135                         witness_script.len() <= MAX_ACCEPTED_HTLC_SCRIPT_WEIGHT {
136                         // Handle remaining range of ACCEPTED_HTLC_SCRIPT_WEIGHT.
137                         if witness.len() == 3 && second_to_last.len() == 33 {
138                                 // <revocation sig> <revocationpubkey> <witness_script>
139                                 Some(Self::Revocation)
140                         } else if witness.len() == 3 && second_to_last.len() == 0 {
141                                 // <remotehtlcsig> <> <witness_script>
142                                 Some(Self::AcceptedTimeout)
143                         } else if witness.len() == 5 && second_to_last.len() == 32 {
144                                 // 0 <remotehtlcsig> <localhtlcsig> <payment_preimage> <witness_script>
145                                 Some(Self::AcceptedPreimage)
146                         } else {
147                                 None
148                         }
149                 } else {
150                         None
151                 }
152         }
153 }
154
155 // Various functions for key derivation and transaction creation for use within channels. Primarily
156 // used in Channel and ChannelMonitor.
157
158 /// Build the commitment secret from the seed and the commitment number
159 pub fn build_commitment_secret(commitment_seed: &[u8; 32], idx: u64) -> [u8; 32] {
160         let mut res: [u8; 32] = commitment_seed.clone();
161         for i in 0..48 {
162                 let bitpos = 47 - i;
163                 if idx & (1 << bitpos) == (1 << bitpos) {
164                         res[bitpos / 8] ^= 1 << (bitpos & 7);
165                         res = Sha256::hash(&res).into_inner();
166                 }
167         }
168         res
169 }
170
171 /// Build a closing transaction
172 pub fn build_closing_transaction(to_holder_value_sat: u64, to_counterparty_value_sat: u64, to_holder_script: Script, to_counterparty_script: Script, funding_outpoint: OutPoint) -> Transaction {
173         let txins = {
174                 let mut ins: Vec<TxIn> = Vec::new();
175                 ins.push(TxIn {
176                         previous_output: funding_outpoint,
177                         script_sig: Script::new(),
178                         sequence: Sequence::MAX,
179                         witness: Witness::new(),
180                 });
181                 ins
182         };
183
184         let mut txouts: Vec<(TxOut, ())> = Vec::new();
185
186         if to_counterparty_value_sat > 0 {
187                 txouts.push((TxOut {
188                         script_pubkey: to_counterparty_script,
189                         value: to_counterparty_value_sat
190                 }, ()));
191         }
192
193         if to_holder_value_sat > 0 {
194                 txouts.push((TxOut {
195                         script_pubkey: to_holder_script,
196                         value: to_holder_value_sat
197                 }, ()));
198         }
199
200         transaction_utils::sort_outputs(&mut txouts, |_, _| { cmp::Ordering::Equal }); // Ordering doesnt matter if they used our pubkey...
201
202         let mut outputs: Vec<TxOut> = Vec::new();
203         for out in txouts.drain(..) {
204                 outputs.push(out.0);
205         }
206
207         Transaction {
208                 version: 2,
209                 lock_time: PackedLockTime::ZERO,
210                 input: txins,
211                 output: outputs,
212         }
213 }
214
215 /// Implements the per-commitment secret storage scheme from
216 /// [BOLT 3](https://github.com/lightning/bolts/blob/dcbf8583976df087c79c3ce0b535311212e6812d/03-transactions.md#efficient-per-commitment-secret-storage).
217 ///
218 /// Allows us to keep track of all of the revocation secrets of our counterparty in just 50*32 bytes
219 /// or so.
220 #[derive(Clone)]
221 pub struct CounterpartyCommitmentSecrets {
222         old_secrets: [([u8; 32], u64); 49],
223 }
224
225 impl Eq for CounterpartyCommitmentSecrets {}
226 impl PartialEq for CounterpartyCommitmentSecrets {
227         fn eq(&self, other: &Self) -> bool {
228                 for (&(ref secret, ref idx), &(ref o_secret, ref o_idx)) in self.old_secrets.iter().zip(other.old_secrets.iter()) {
229                         if secret != o_secret || idx != o_idx {
230                                 return false
231                         }
232                 }
233                 true
234         }
235 }
236
237 impl CounterpartyCommitmentSecrets {
238         /// Creates a new empty `CounterpartyCommitmentSecrets` structure.
239         pub fn new() -> Self {
240                 Self { old_secrets: [([0; 32], 1 << 48); 49], }
241         }
242
243         #[inline]
244         fn place_secret(idx: u64) -> u8 {
245                 for i in 0..48 {
246                         if idx & (1 << i) == (1 << i) {
247                                 return i
248                         }
249                 }
250                 48
251         }
252
253         /// Returns the minimum index of all stored secrets. Note that indexes start
254         /// at 1 << 48 and get decremented by one for each new secret.
255         pub fn get_min_seen_secret(&self) -> u64 {
256                 //TODO This can be optimized?
257                 let mut min = 1 << 48;
258                 for &(_, idx) in self.old_secrets.iter() {
259                         if idx < min {
260                                 min = idx;
261                         }
262                 }
263                 min
264         }
265
266         #[inline]
267         fn derive_secret(secret: [u8; 32], bits: u8, idx: u64) -> [u8; 32] {
268                 let mut res: [u8; 32] = secret;
269                 for i in 0..bits {
270                         let bitpos = bits - 1 - i;
271                         if idx & (1 << bitpos) == (1 << bitpos) {
272                                 res[(bitpos / 8) as usize] ^= 1 << (bitpos & 7);
273                                 res = Sha256::hash(&res).into_inner();
274                         }
275                 }
276                 res
277         }
278
279         /// Inserts the `secret` at `idx`. Returns `Ok(())` if the secret
280         /// was generated in accordance with BOLT 3 and is consistent with previous secrets.
281         pub fn provide_secret(&mut self, idx: u64, secret: [u8; 32]) -> Result<(), ()> {
282                 let pos = Self::place_secret(idx);
283                 for i in 0..pos {
284                         let (old_secret, old_idx) = self.old_secrets[i as usize];
285                         if Self::derive_secret(secret, pos, old_idx) != old_secret {
286                                 return Err(());
287                         }
288                 }
289                 if self.get_min_seen_secret() <= idx {
290                         return Ok(());
291                 }
292                 self.old_secrets[pos as usize] = (secret, idx);
293                 Ok(())
294         }
295
296         /// Returns the secret at `idx`.
297         /// Returns `None` if `idx` is < [`CounterpartyCommitmentSecrets::get_min_seen_secret`].
298         pub fn get_secret(&self, idx: u64) -> Option<[u8; 32]> {
299                 for i in 0..self.old_secrets.len() {
300                         if (idx & (!((1 << i) - 1))) == self.old_secrets[i].1 {
301                                 return Some(Self::derive_secret(self.old_secrets[i].0, i as u8, idx))
302                         }
303                 }
304                 assert!(idx < self.get_min_seen_secret());
305                 None
306         }
307 }
308
309 impl Writeable for CounterpartyCommitmentSecrets {
310         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
311                 for &(ref secret, ref idx) in self.old_secrets.iter() {
312                         writer.write_all(secret)?;
313                         writer.write_all(&idx.to_be_bytes())?;
314                 }
315                 write_tlv_fields!(writer, {});
316                 Ok(())
317         }
318 }
319 impl Readable for CounterpartyCommitmentSecrets {
320         fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
321                 let mut old_secrets = [([0; 32], 1 << 48); 49];
322                 for &mut (ref mut secret, ref mut idx) in old_secrets.iter_mut() {
323                         *secret = Readable::read(reader)?;
324                         *idx = Readable::read(reader)?;
325                 }
326                 read_tlv_fields!(reader, {});
327                 Ok(Self { old_secrets })
328         }
329 }
330
331 /// Derives a per-commitment-transaction private key (eg an htlc key or delayed_payment key)
332 /// from the base secret and the per_commitment_point.
333 pub fn derive_private_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, base_secret: &SecretKey) -> SecretKey {
334         let mut sha = Sha256::engine();
335         sha.input(&per_commitment_point.serialize());
336         sha.input(&PublicKey::from_secret_key(&secp_ctx, &base_secret).serialize());
337         let res = Sha256::from_engine(sha).into_inner();
338
339         base_secret.clone().add_tweak(&Scalar::from_be_bytes(res).unwrap())
340                 .expect("Addition only fails if the tweak is the inverse of the key. This is not possible when the tweak contains the hash of the key.")
341 }
342
343 /// Derives a per-commitment-transaction public key (eg an htlc key or a delayed_payment key)
344 /// from the base point and the per_commitment_key. This is the public equivalent of
345 /// derive_private_key - using only public keys to derive a public key instead of private keys.
346 pub fn derive_public_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, base_point: &PublicKey) -> PublicKey {
347         let mut sha = Sha256::engine();
348         sha.input(&per_commitment_point.serialize());
349         sha.input(&base_point.serialize());
350         let res = Sha256::from_engine(sha).into_inner();
351
352         let hashkey = PublicKey::from_secret_key(&secp_ctx,
353                 &SecretKey::from_slice(&res).expect("Hashes should always be valid keys unless SHA-256 is broken"));
354         base_point.combine(&hashkey)
355                 .expect("Addition only fails if the tweak is the inverse of the key. This is not possible when the tweak contains the hash of the key.")
356 }
357
358 /// Derives a per-commitment-transaction revocation key from its constituent parts.
359 ///
360 /// Only the cheating participant owns a valid witness to propagate a revoked
361 /// commitment transaction, thus per_commitment_secret always come from cheater
362 /// and revocation_base_secret always come from punisher, which is the broadcaster
363 /// of the transaction spending with this key knowledge.
364 pub fn derive_private_revocation_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>,
365         per_commitment_secret: &SecretKey, countersignatory_revocation_base_secret: &SecretKey)
366 -> SecretKey {
367         let countersignatory_revocation_base_point = PublicKey::from_secret_key(&secp_ctx, &countersignatory_revocation_base_secret);
368         let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &per_commitment_secret);
369
370         let rev_append_commit_hash_key = {
371                 let mut sha = Sha256::engine();
372                 sha.input(&countersignatory_revocation_base_point.serialize());
373                 sha.input(&per_commitment_point.serialize());
374
375                 Sha256::from_engine(sha).into_inner()
376         };
377         let commit_append_rev_hash_key = {
378                 let mut sha = Sha256::engine();
379                 sha.input(&per_commitment_point.serialize());
380                 sha.input(&countersignatory_revocation_base_point.serialize());
381
382                 Sha256::from_engine(sha).into_inner()
383         };
384
385         let countersignatory_contrib = countersignatory_revocation_base_secret.clone().mul_tweak(&Scalar::from_be_bytes(rev_append_commit_hash_key).unwrap())
386                 .expect("Multiplying a secret key by a hash is expected to never fail per secp256k1 docs");
387         let broadcaster_contrib = per_commitment_secret.clone().mul_tweak(&Scalar::from_be_bytes(commit_append_rev_hash_key).unwrap())
388                 .expect("Multiplying a secret key by a hash is expected to never fail per secp256k1 docs");
389         countersignatory_contrib.add_tweak(&Scalar::from_be_bytes(broadcaster_contrib.secret_bytes()).unwrap())
390                 .expect("Addition only fails if the tweak is the inverse of the key. This is not possible when the tweak commits to the key.")
391 }
392
393 /// Derives a per-commitment-transaction revocation public key from its constituent parts. This is
394 /// the public equivalend of derive_private_revocation_key - using only public keys to derive a
395 /// public key instead of private keys.
396 ///
397 /// Only the cheating participant owns a valid witness to propagate a revoked
398 /// commitment transaction, thus per_commitment_point always come from cheater
399 /// and revocation_base_point always come from punisher, which is the broadcaster
400 /// of the transaction spending with this key knowledge.
401 ///
402 /// Note that this is infallible iff we trust that at least one of the two input keys are randomly
403 /// generated (ie our own).
404 pub fn derive_public_revocation_key<T: secp256k1::Verification>(secp_ctx: &Secp256k1<T>,
405         per_commitment_point: &PublicKey, countersignatory_revocation_base_point: &PublicKey)
406 -> PublicKey {
407         let rev_append_commit_hash_key = {
408                 let mut sha = Sha256::engine();
409                 sha.input(&countersignatory_revocation_base_point.serialize());
410                 sha.input(&per_commitment_point.serialize());
411
412                 Sha256::from_engine(sha).into_inner()
413         };
414         let commit_append_rev_hash_key = {
415                 let mut sha = Sha256::engine();
416                 sha.input(&per_commitment_point.serialize());
417                 sha.input(&countersignatory_revocation_base_point.serialize());
418
419                 Sha256::from_engine(sha).into_inner()
420         };
421
422         let countersignatory_contrib = countersignatory_revocation_base_point.clone().mul_tweak(&secp_ctx, &Scalar::from_be_bytes(rev_append_commit_hash_key).unwrap())
423                 .expect("Multiplying a valid public key by a hash is expected to never fail per secp256k1 docs");
424         let broadcaster_contrib = per_commitment_point.clone().mul_tweak(&secp_ctx, &Scalar::from_be_bytes(commit_append_rev_hash_key).unwrap())
425                 .expect("Multiplying a valid public key by a hash is expected to never fail per secp256k1 docs");
426         countersignatory_contrib.combine(&broadcaster_contrib)
427                 .expect("Addition only fails if the tweak is the inverse of the key. This is not possible when the tweak commits to the key.")
428 }
429
430 /// The set of public keys which are used in the creation of one commitment transaction.
431 /// These are derived from the channel base keys and per-commitment data.
432 ///
433 /// A broadcaster key is provided from potential broadcaster of the computed transaction.
434 /// A countersignatory key is coming from a protocol participant unable to broadcast the
435 /// transaction.
436 ///
437 /// These keys are assumed to be good, either because the code derived them from
438 /// channel basepoints via the new function, or they were obtained via
439 /// CommitmentTransaction.trust().keys() because we trusted the source of the
440 /// pre-calculated keys.
441 #[derive(PartialEq, Eq, Clone)]
442 pub struct TxCreationKeys {
443         /// The broadcaster's per-commitment public key which was used to derive the other keys.
444         pub per_commitment_point: PublicKey,
445         /// The revocation key which is used to allow the broadcaster of the commitment
446         /// transaction to provide their counterparty the ability to punish them if they broadcast
447         /// an old state.
448         pub revocation_key: PublicKey,
449         /// Broadcaster's HTLC Key
450         pub broadcaster_htlc_key: PublicKey,
451         /// Countersignatory's HTLC Key
452         pub countersignatory_htlc_key: PublicKey,
453         /// Broadcaster's Payment Key (which isn't allowed to be spent from for some delay)
454         pub broadcaster_delayed_payment_key: PublicKey,
455 }
456
457 impl_writeable_tlv_based!(TxCreationKeys, {
458         (0, per_commitment_point, required),
459         (2, revocation_key, required),
460         (4, broadcaster_htlc_key, required),
461         (6, countersignatory_htlc_key, required),
462         (8, broadcaster_delayed_payment_key, required),
463 });
464
465 /// One counterparty's public keys which do not change over the life of a channel.
466 #[derive(Clone, Debug, PartialEq, Eq)]
467 pub struct ChannelPublicKeys {
468         /// The public key which is used to sign all commitment transactions, as it appears in the
469         /// on-chain channel lock-in 2-of-2 multisig output.
470         pub funding_pubkey: PublicKey,
471         /// The base point which is used (with derive_public_revocation_key) to derive per-commitment
472         /// revocation keys. This is combined with the per-commitment-secret generated by the
473         /// counterparty to create a secret which the counterparty can reveal to revoke previous
474         /// states.
475         pub revocation_basepoint: PublicKey,
476         /// The public key on which the non-broadcaster (ie the countersignatory) receives an immediately
477         /// spendable primary channel balance on the broadcaster's commitment transaction. This key is
478         /// static across every commitment transaction.
479         pub payment_point: PublicKey,
480         /// The base point which is used (with derive_public_key) to derive a per-commitment payment
481         /// public key which receives non-HTLC-encumbered funds which are only available for spending
482         /// after some delay (or can be claimed via the revocation path).
483         pub delayed_payment_basepoint: PublicKey,
484         /// The base point which is used (with derive_public_key) to derive a per-commitment public key
485         /// which is used to encumber HTLC-in-flight outputs.
486         pub htlc_basepoint: PublicKey,
487 }
488
489 impl_writeable_tlv_based!(ChannelPublicKeys, {
490         (0, funding_pubkey, required),
491         (2, revocation_basepoint, required),
492         (4, payment_point, required),
493         (6, delayed_payment_basepoint, required),
494         (8, htlc_basepoint, required),
495 });
496
497 impl TxCreationKeys {
498         /// Create per-state keys from channel base points and the per-commitment point.
499         /// Key set is asymmetric and can't be used as part of counter-signatory set of transactions.
500         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) -> TxCreationKeys {
501                 TxCreationKeys {
502                         per_commitment_point: per_commitment_point.clone(),
503                         revocation_key: derive_public_revocation_key(&secp_ctx, &per_commitment_point, &countersignatory_revocation_base),
504                         broadcaster_htlc_key: derive_public_key(&secp_ctx, &per_commitment_point, &broadcaster_htlc_base),
505                         countersignatory_htlc_key: derive_public_key(&secp_ctx, &per_commitment_point, &countersignatory_htlc_base),
506                         broadcaster_delayed_payment_key: derive_public_key(&secp_ctx, &per_commitment_point, &broadcaster_delayed_payment_base),
507                 }
508         }
509
510         /// Generate per-state keys from channel static keys.
511         /// Key set is asymmetric and can't be used as part of counter-signatory set of transactions.
512         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>) -> TxCreationKeys {
513                 TxCreationKeys::derive_new(
514                         &secp_ctx,
515                         &per_commitment_point,
516                         &broadcaster_keys.delayed_payment_basepoint,
517                         &broadcaster_keys.htlc_basepoint,
518                         &countersignatory_keys.revocation_basepoint,
519                         &countersignatory_keys.htlc_basepoint,
520                 )
521         }
522 }
523
524 /// The maximum length of a script returned by get_revokeable_redeemscript.
525 // Calculated as 6 bytes of opcodes, 1 byte push plus 2 bytes for contest_delay, and two public
526 // keys of 33 bytes (+ 1 push).
527 pub const REVOKEABLE_REDEEMSCRIPT_MAX_LENGTH: usize = 6 + 3 + 34*2;
528
529 /// A script either spendable by the revocation
530 /// key or the broadcaster_delayed_payment_key and satisfying the relative-locktime OP_CSV constrain.
531 /// Encumbering a `to_holder` output on a commitment transaction or 2nd-stage HTLC transactions.
532 pub fn get_revokeable_redeemscript(revocation_key: &PublicKey, contest_delay: u16, broadcaster_delayed_payment_key: &PublicKey) -> Script {
533         let res = Builder::new().push_opcode(opcodes::all::OP_IF)
534                       .push_slice(&revocation_key.serialize())
535                       .push_opcode(opcodes::all::OP_ELSE)
536                       .push_int(contest_delay as i64)
537                       .push_opcode(opcodes::all::OP_CSV)
538                       .push_opcode(opcodes::all::OP_DROP)
539                       .push_slice(&broadcaster_delayed_payment_key.serialize())
540                       .push_opcode(opcodes::all::OP_ENDIF)
541                       .push_opcode(opcodes::all::OP_CHECKSIG)
542                       .into_script();
543         debug_assert!(res.len() <= REVOKEABLE_REDEEMSCRIPT_MAX_LENGTH);
544         res
545 }
546
547 /// Information about an HTLC as it appears in a commitment transaction
548 #[derive(Clone, Debug, PartialEq, Eq)]
549 pub struct HTLCOutputInCommitment {
550         /// Whether the HTLC was "offered" (ie outbound in relation to this commitment transaction).
551         /// Note that this is not the same as whether it is ountbound *from us*. To determine that you
552         /// need to compare this value to whether the commitment transaction in question is that of
553         /// the counterparty or our own.
554         pub offered: bool,
555         /// The value, in msat, of the HTLC. The value as it appears in the commitment transaction is
556         /// this divided by 1000.
557         pub amount_msat: u64,
558         /// The CLTV lock-time at which this HTLC expires.
559         pub cltv_expiry: u32,
560         /// The hash of the preimage which unlocks this HTLC.
561         pub payment_hash: PaymentHash,
562         /// The position within the commitment transactions' outputs. This may be None if the value is
563         /// below the dust limit (in which case no output appears in the commitment transaction and the
564         /// value is spent to additional transaction fees).
565         pub transaction_output_index: Option<u32>,
566 }
567
568 impl_writeable_tlv_based!(HTLCOutputInCommitment, {
569         (0, offered, required),
570         (2, amount_msat, required),
571         (4, cltv_expiry, required),
572         (6, payment_hash, required),
573         (8, transaction_output_index, option),
574 });
575
576 #[inline]
577 pub(crate) fn get_htlc_redeemscript_with_explicit_keys(htlc: &HTLCOutputInCommitment, opt_anchors: bool, broadcaster_htlc_key: &PublicKey, countersignatory_htlc_key: &PublicKey, revocation_key: &PublicKey) -> Script {
578         let payment_hash160 = Ripemd160::hash(&htlc.payment_hash.0[..]).into_inner();
579         if htlc.offered {
580                 let mut bldr = Builder::new().push_opcode(opcodes::all::OP_DUP)
581                               .push_opcode(opcodes::all::OP_HASH160)
582                               .push_slice(&PubkeyHash::hash(&revocation_key.serialize())[..])
583                               .push_opcode(opcodes::all::OP_EQUAL)
584                               .push_opcode(opcodes::all::OP_IF)
585                               .push_opcode(opcodes::all::OP_CHECKSIG)
586                               .push_opcode(opcodes::all::OP_ELSE)
587                               .push_slice(&countersignatory_htlc_key.serialize()[..])
588                               .push_opcode(opcodes::all::OP_SWAP)
589                               .push_opcode(opcodes::all::OP_SIZE)
590                               .push_int(32)
591                               .push_opcode(opcodes::all::OP_EQUAL)
592                               .push_opcode(opcodes::all::OP_NOTIF)
593                               .push_opcode(opcodes::all::OP_DROP)
594                               .push_int(2)
595                               .push_opcode(opcodes::all::OP_SWAP)
596                               .push_slice(&broadcaster_htlc_key.serialize()[..])
597                               .push_int(2)
598                               .push_opcode(opcodes::all::OP_CHECKMULTISIG)
599                               .push_opcode(opcodes::all::OP_ELSE)
600                               .push_opcode(opcodes::all::OP_HASH160)
601                               .push_slice(&payment_hash160)
602                               .push_opcode(opcodes::all::OP_EQUALVERIFY)
603                               .push_opcode(opcodes::all::OP_CHECKSIG)
604                               .push_opcode(opcodes::all::OP_ENDIF);
605                 if opt_anchors {
606                         bldr = bldr.push_opcode(opcodes::all::OP_PUSHNUM_1)
607                                 .push_opcode(opcodes::all::OP_CSV)
608                                 .push_opcode(opcodes::all::OP_DROP);
609                 }
610                 bldr.push_opcode(opcodes::all::OP_ENDIF)
611                         .into_script()
612         } else {
613                         let mut bldr = Builder::new().push_opcode(opcodes::all::OP_DUP)
614                               .push_opcode(opcodes::all::OP_HASH160)
615                               .push_slice(&PubkeyHash::hash(&revocation_key.serialize())[..])
616                               .push_opcode(opcodes::all::OP_EQUAL)
617                               .push_opcode(opcodes::all::OP_IF)
618                               .push_opcode(opcodes::all::OP_CHECKSIG)
619                               .push_opcode(opcodes::all::OP_ELSE)
620                               .push_slice(&countersignatory_htlc_key.serialize()[..])
621                               .push_opcode(opcodes::all::OP_SWAP)
622                               .push_opcode(opcodes::all::OP_SIZE)
623                               .push_int(32)
624                               .push_opcode(opcodes::all::OP_EQUAL)
625                               .push_opcode(opcodes::all::OP_IF)
626                               .push_opcode(opcodes::all::OP_HASH160)
627                               .push_slice(&payment_hash160)
628                               .push_opcode(opcodes::all::OP_EQUALVERIFY)
629                               .push_int(2)
630                               .push_opcode(opcodes::all::OP_SWAP)
631                               .push_slice(&broadcaster_htlc_key.serialize()[..])
632                               .push_int(2)
633                               .push_opcode(opcodes::all::OP_CHECKMULTISIG)
634                               .push_opcode(opcodes::all::OP_ELSE)
635                               .push_opcode(opcodes::all::OP_DROP)
636                               .push_int(htlc.cltv_expiry as i64)
637                               .push_opcode(opcodes::all::OP_CLTV)
638                               .push_opcode(opcodes::all::OP_DROP)
639                               .push_opcode(opcodes::all::OP_CHECKSIG)
640                               .push_opcode(opcodes::all::OP_ENDIF);
641                 if opt_anchors {
642                         bldr = bldr.push_opcode(opcodes::all::OP_PUSHNUM_1)
643                                 .push_opcode(opcodes::all::OP_CSV)
644                                 .push_opcode(opcodes::all::OP_DROP);
645                 }
646                 bldr.push_opcode(opcodes::all::OP_ENDIF)
647                         .into_script()
648         }
649 }
650
651 /// Gets the witness redeemscript for an HTLC output in a commitment transaction. Note that htlc
652 /// does not need to have its previous_output_index filled.
653 #[inline]
654 pub fn get_htlc_redeemscript(htlc: &HTLCOutputInCommitment, opt_anchors: bool, keys: &TxCreationKeys) -> Script {
655         get_htlc_redeemscript_with_explicit_keys(htlc, opt_anchors, &keys.broadcaster_htlc_key, &keys.countersignatory_htlc_key, &keys.revocation_key)
656 }
657
658 /// Gets the redeemscript for a funding output from the two funding public keys.
659 /// Note that the order of funding public keys does not matter.
660 pub fn make_funding_redeemscript(broadcaster: &PublicKey, countersignatory: &PublicKey) -> Script {
661         let broadcaster_funding_key = broadcaster.serialize();
662         let countersignatory_funding_key = countersignatory.serialize();
663
664         make_funding_redeemscript_from_slices(&broadcaster_funding_key, &countersignatory_funding_key)
665 }
666
667 pub(crate) fn make_funding_redeemscript_from_slices(broadcaster_funding_key: &[u8], countersignatory_funding_key: &[u8]) -> Script {
668         let builder = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2);
669         if broadcaster_funding_key[..] < countersignatory_funding_key[..] {
670                 builder.push_slice(broadcaster_funding_key)
671                         .push_slice(countersignatory_funding_key)
672         } else {
673                 builder.push_slice(countersignatory_funding_key)
674                         .push_slice(broadcaster_funding_key)
675         }.push_opcode(opcodes::all::OP_PUSHNUM_2).push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script()
676 }
677
678 /// Builds an unsigned HTLC-Success or HTLC-Timeout transaction from the given channel and HTLC
679 /// parameters. This is used by [`TrustedCommitmentTransaction::get_htlc_sigs`] to fetch the
680 /// transaction which needs signing, and can be used to construct an HTLC transaction which is
681 /// broadcastable given a counterparty HTLC signature.
682 ///
683 /// Panics if htlc.transaction_output_index.is_none() (as such HTLCs do not appear in the
684 /// commitment transaction).
685 pub fn build_htlc_transaction(commitment_txid: &Txid, feerate_per_kw: u32, contest_delay: u16, htlc: &HTLCOutputInCommitment, opt_anchors: bool, use_non_zero_fee_anchors: bool, broadcaster_delayed_payment_key: &PublicKey, revocation_key: &PublicKey) -> Transaction {
686         let mut txins: Vec<TxIn> = Vec::new();
687         txins.push(build_htlc_input(commitment_txid, htlc, opt_anchors));
688
689         let mut txouts: Vec<TxOut> = Vec::new();
690         txouts.push(build_htlc_output(
691                 feerate_per_kw, contest_delay, htlc, opt_anchors, use_non_zero_fee_anchors,
692                 broadcaster_delayed_payment_key, revocation_key
693         ));
694
695         Transaction {
696                 version: 2,
697                 lock_time: PackedLockTime(if htlc.offered { htlc.cltv_expiry } else { 0 }),
698                 input: txins,
699                 output: txouts,
700         }
701 }
702
703 pub(crate) fn build_htlc_input(commitment_txid: &Txid, htlc: &HTLCOutputInCommitment, opt_anchors: bool) -> TxIn {
704         TxIn {
705                 previous_output: OutPoint {
706                         txid: commitment_txid.clone(),
707                         vout: htlc.transaction_output_index.expect("Can't build an HTLC transaction for a dust output"),
708                 },
709                 script_sig: Script::new(),
710                 sequence: Sequence(if opt_anchors { 1 } else { 0 }),
711                 witness: Witness::new(),
712         }
713 }
714
715 pub(crate) fn build_htlc_output(
716         feerate_per_kw: u32, contest_delay: u16, htlc: &HTLCOutputInCommitment, opt_anchors: bool,
717         use_non_zero_fee_anchors: bool, broadcaster_delayed_payment_key: &PublicKey, revocation_key: &PublicKey
718 ) -> TxOut {
719         let weight = if htlc.offered {
720                 htlc_timeout_tx_weight(opt_anchors)
721         } else {
722                 htlc_success_tx_weight(opt_anchors)
723         };
724         let output_value = if opt_anchors && !use_non_zero_fee_anchors {
725                 htlc.amount_msat / 1000
726         } else {
727                 let total_fee = feerate_per_kw as u64 * weight / 1000;
728                 htlc.amount_msat / 1000 - total_fee
729         };
730
731         TxOut {
732                 script_pubkey: get_revokeable_redeemscript(revocation_key, contest_delay, broadcaster_delayed_payment_key).to_v0_p2wsh(),
733                 value: output_value,
734         }
735 }
736
737 /// Returns the witness required to satisfy and spend a HTLC input.
738 pub fn build_htlc_input_witness(
739         local_sig: &Signature, remote_sig: &Signature, preimage: &Option<PaymentPreimage>,
740         redeem_script: &Script, opt_anchors: bool,
741 ) -> Witness {
742         let remote_sighash_type = if opt_anchors {
743                 EcdsaSighashType::SinglePlusAnyoneCanPay
744         } else {
745                 EcdsaSighashType::All
746         };
747
748         let mut witness = Witness::new();
749         // First push the multisig dummy, note that due to BIP147 (NULLDUMMY) it must be a zero-length element.
750         witness.push(vec![]);
751         witness.push_bitcoin_signature(&remote_sig.serialize_der(), remote_sighash_type);
752         witness.push_bitcoin_signature(&local_sig.serialize_der(), EcdsaSighashType::All);
753         if let Some(preimage) = preimage {
754                 witness.push(preimage.0.to_vec());
755         } else {
756                 // Due to BIP146 (MINIMALIF) this must be a zero-length element to relay.
757                 witness.push(vec![]);
758         }
759         witness.push(redeem_script.to_bytes());
760         witness
761 }
762
763 /// Gets the witnessScript for the to_remote output when anchors are enabled.
764 #[inline]
765 pub fn get_to_countersignatory_with_anchors_redeemscript(payment_point: &PublicKey) -> Script {
766         Builder::new()
767                 .push_slice(&payment_point.serialize()[..])
768                 .push_opcode(opcodes::all::OP_CHECKSIGVERIFY)
769                 .push_int(1)
770                 .push_opcode(opcodes::all::OP_CSV)
771                 .into_script()
772 }
773
774 /// Gets the witnessScript for an anchor output from the funding public key.
775 /// The witness in the spending input must be:
776 /// <BIP 143 funding_signature>
777 /// After 16 blocks of confirmation, an alternative satisfying witness could be:
778 /// <>
779 /// (empty vector required to satisfy compliance with MINIMALIF-standard rule)
780 #[inline]
781 pub fn get_anchor_redeemscript(funding_pubkey: &PublicKey) -> Script {
782         Builder::new().push_slice(&funding_pubkey.serialize()[..])
783                 .push_opcode(opcodes::all::OP_CHECKSIG)
784                 .push_opcode(opcodes::all::OP_IFDUP)
785                 .push_opcode(opcodes::all::OP_NOTIF)
786                 .push_int(16)
787                 .push_opcode(opcodes::all::OP_CSV)
788                 .push_opcode(opcodes::all::OP_ENDIF)
789                 .into_script()
790 }
791
792 #[cfg(anchors)]
793 /// Locates the output with an anchor script paying to `funding_pubkey` within `commitment_tx`.
794 pub(crate) fn get_anchor_output<'a>(commitment_tx: &'a Transaction, funding_pubkey: &PublicKey) -> Option<(u32, &'a TxOut)> {
795         let anchor_script = chan_utils::get_anchor_redeemscript(funding_pubkey).to_v0_p2wsh();
796         commitment_tx.output.iter().enumerate()
797                 .find(|(_, txout)| txout.script_pubkey == anchor_script)
798                 .map(|(idx, txout)| (idx as u32, txout))
799 }
800
801 /// Returns the witness required to satisfy and spend an anchor input.
802 pub fn build_anchor_input_witness(funding_key: &PublicKey, funding_sig: &Signature) -> Witness {
803         let anchor_redeem_script = chan_utils::get_anchor_redeemscript(funding_key);
804         let mut ret = Witness::new();
805         ret.push_bitcoin_signature(&funding_sig.serialize_der(), EcdsaSighashType::All);
806         ret.push(anchor_redeem_script.as_bytes());
807         ret
808 }
809
810 /// Per-channel data used to build transactions in conjunction with the per-commitment data (CommitmentTransaction).
811 /// The fields are organized by holder/counterparty.
812 ///
813 /// Normally, this is converted to the broadcaster/countersignatory-organized DirectedChannelTransactionParameters
814 /// before use, via the as_holder_broadcastable and as_counterparty_broadcastable functions.
815 #[derive(Clone, Debug, PartialEq)]
816 pub struct ChannelTransactionParameters {
817         /// Holder public keys
818         pub holder_pubkeys: ChannelPublicKeys,
819         /// The contest delay selected by the holder, which applies to counterparty-broadcast transactions
820         pub holder_selected_contest_delay: u16,
821         /// Whether the holder is the initiator of this channel.
822         /// This is an input to the commitment number obscure factor computation.
823         pub is_outbound_from_holder: bool,
824         /// The late-bound counterparty channel transaction parameters.
825         /// These parameters are populated at the point in the protocol where the counterparty provides them.
826         pub counterparty_parameters: Option<CounterpartyChannelTransactionParameters>,
827         /// The late-bound funding outpoint
828         pub funding_outpoint: Option<chain::transaction::OutPoint>,
829         /// Are anchors (zero fee HTLC transaction variant) used for this channel. Boolean is
830         /// serialization backwards-compatible.
831         pub opt_anchors: Option<()>,
832         /// Are non-zero-fee anchors are enabled (used in conjuction with opt_anchors)
833         /// It is intended merely for backwards compatibility with signers that need it.
834         /// There is no support for this feature in LDK channel negotiation.
835         pub opt_non_zero_fee_anchors: Option<()>,
836 }
837
838 /// Late-bound per-channel counterparty data used to build transactions.
839 #[derive(Clone, Debug, PartialEq)]
840 pub struct CounterpartyChannelTransactionParameters {
841         /// Counter-party public keys
842         pub pubkeys: ChannelPublicKeys,
843         /// The contest delay selected by the counterparty, which applies to holder-broadcast transactions
844         pub selected_contest_delay: u16,
845 }
846
847 impl ChannelTransactionParameters {
848         /// Whether the late bound parameters are populated.
849         pub fn is_populated(&self) -> bool {
850                 self.counterparty_parameters.is_some() && self.funding_outpoint.is_some()
851         }
852
853         /// Convert the holder/counterparty parameters to broadcaster/countersignatory-organized parameters,
854         /// given that the holder is the broadcaster.
855         ///
856         /// self.is_populated() must be true before calling this function.
857         pub fn as_holder_broadcastable(&self) -> DirectedChannelTransactionParameters {
858                 assert!(self.is_populated(), "self.late_parameters must be set before using as_holder_broadcastable");
859                 DirectedChannelTransactionParameters {
860                         inner: self,
861                         holder_is_broadcaster: true
862                 }
863         }
864
865         /// Convert the holder/counterparty parameters to broadcaster/countersignatory-organized parameters,
866         /// given that the counterparty is the broadcaster.
867         ///
868         /// self.is_populated() must be true before calling this function.
869         pub fn as_counterparty_broadcastable(&self) -> DirectedChannelTransactionParameters {
870                 assert!(self.is_populated(), "self.late_parameters must be set before using as_counterparty_broadcastable");
871                 DirectedChannelTransactionParameters {
872                         inner: self,
873                         holder_is_broadcaster: false
874                 }
875         }
876 }
877
878 impl_writeable_tlv_based!(CounterpartyChannelTransactionParameters, {
879         (0, pubkeys, required),
880         (2, selected_contest_delay, required),
881 });
882
883 impl_writeable_tlv_based!(ChannelTransactionParameters, {
884         (0, holder_pubkeys, required),
885         (2, holder_selected_contest_delay, required),
886         (4, is_outbound_from_holder, required),
887         (6, counterparty_parameters, option),
888         (8, funding_outpoint, option),
889         (10, opt_anchors, option),
890         (12, opt_non_zero_fee_anchors, option),
891 });
892
893 /// Static channel fields used to build transactions given per-commitment fields, organized by
894 /// broadcaster/countersignatory.
895 ///
896 /// This is derived from the holder/counterparty-organized ChannelTransactionParameters via the
897 /// as_holder_broadcastable and as_counterparty_broadcastable functions.
898 pub struct DirectedChannelTransactionParameters<'a> {
899         /// The holder's channel static parameters
900         inner: &'a ChannelTransactionParameters,
901         /// Whether the holder is the broadcaster
902         holder_is_broadcaster: bool,
903 }
904
905 impl<'a> DirectedChannelTransactionParameters<'a> {
906         /// Get the channel pubkeys for the broadcaster
907         pub fn broadcaster_pubkeys(&self) -> &ChannelPublicKeys {
908                 if self.holder_is_broadcaster {
909                         &self.inner.holder_pubkeys
910                 } else {
911                         &self.inner.counterparty_parameters.as_ref().unwrap().pubkeys
912                 }
913         }
914
915         /// Get the channel pubkeys for the countersignatory
916         pub fn countersignatory_pubkeys(&self) -> &ChannelPublicKeys {
917                 if self.holder_is_broadcaster {
918                         &self.inner.counterparty_parameters.as_ref().unwrap().pubkeys
919                 } else {
920                         &self.inner.holder_pubkeys
921                 }
922         }
923
924         /// Get the contest delay applicable to the transactions.
925         /// Note that the contest delay was selected by the countersignatory.
926         pub fn contest_delay(&self) -> u16 {
927                 let counterparty_parameters = self.inner.counterparty_parameters.as_ref().unwrap();
928                 if self.holder_is_broadcaster { counterparty_parameters.selected_contest_delay } else { self.inner.holder_selected_contest_delay }
929         }
930
931         /// Whether the channel is outbound from the broadcaster.
932         ///
933         /// The boolean representing the side that initiated the channel is
934         /// an input to the commitment number obscure factor computation.
935         pub fn is_outbound(&self) -> bool {
936                 if self.holder_is_broadcaster { self.inner.is_outbound_from_holder } else { !self.inner.is_outbound_from_holder }
937         }
938
939         /// The funding outpoint
940         pub fn funding_outpoint(&self) -> OutPoint {
941                 self.inner.funding_outpoint.unwrap().into_bitcoin_outpoint()
942         }
943
944         /// Whether to use anchors for this channel
945         pub fn opt_anchors(&self) -> bool {
946                 self.inner.opt_anchors.is_some()
947         }
948 }
949
950 /// Information needed to build and sign a holder's commitment transaction.
951 ///
952 /// The transaction is only signed once we are ready to broadcast.
953 #[derive(Clone)]
954 pub struct HolderCommitmentTransaction {
955         inner: CommitmentTransaction,
956         /// Our counterparty's signature for the transaction
957         pub counterparty_sig: Signature,
958         /// All non-dust counterparty HTLC signatures, in the order they appear in the transaction
959         pub counterparty_htlc_sigs: Vec<Signature>,
960         // Which order the signatures should go in when constructing the final commitment tx witness.
961         // The user should be able to reconstruct this themselves, so we don't bother to expose it.
962         holder_sig_first: bool,
963 }
964
965 impl Deref for HolderCommitmentTransaction {
966         type Target = CommitmentTransaction;
967
968         fn deref(&self) -> &Self::Target { &self.inner }
969 }
970
971 impl Eq for HolderCommitmentTransaction {}
972 impl PartialEq for HolderCommitmentTransaction {
973         // We dont care whether we are signed in equality comparison
974         fn eq(&self, o: &Self) -> bool {
975                 self.inner == o.inner
976         }
977 }
978
979 impl_writeable_tlv_based!(HolderCommitmentTransaction, {
980         (0, inner, required),
981         (2, counterparty_sig, required),
982         (4, holder_sig_first, required),
983         (6, counterparty_htlc_sigs, vec_type),
984 });
985
986 impl HolderCommitmentTransaction {
987         #[cfg(test)]
988         pub fn dummy() -> Self {
989                 let secp_ctx = Secp256k1::new();
990                 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
991                 let dummy_sig = sign(&secp_ctx, &secp256k1::Message::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[42; 32]).unwrap());
992
993                 let keys = TxCreationKeys {
994                         per_commitment_point: dummy_key.clone(),
995                         revocation_key: dummy_key.clone(),
996                         broadcaster_htlc_key: dummy_key.clone(),
997                         countersignatory_htlc_key: dummy_key.clone(),
998                         broadcaster_delayed_payment_key: dummy_key.clone(),
999                 };
1000                 let channel_pubkeys = ChannelPublicKeys {
1001                         funding_pubkey: dummy_key.clone(),
1002                         revocation_basepoint: dummy_key.clone(),
1003                         payment_point: dummy_key.clone(),
1004                         delayed_payment_basepoint: dummy_key.clone(),
1005                         htlc_basepoint: dummy_key.clone()
1006                 };
1007                 let channel_parameters = ChannelTransactionParameters {
1008                         holder_pubkeys: channel_pubkeys.clone(),
1009                         holder_selected_contest_delay: 0,
1010                         is_outbound_from_holder: false,
1011                         counterparty_parameters: Some(CounterpartyChannelTransactionParameters { pubkeys: channel_pubkeys.clone(), selected_contest_delay: 0 }),
1012                         funding_outpoint: Some(chain::transaction::OutPoint { txid: Txid::all_zeros(), index: 0 }),
1013                         opt_anchors: None,
1014                         opt_non_zero_fee_anchors: None,
1015                 };
1016                 let mut htlcs_with_aux: Vec<(_, ())> = Vec::new();
1017                 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());
1018                 HolderCommitmentTransaction {
1019                         inner,
1020                         counterparty_sig: dummy_sig,
1021                         counterparty_htlc_sigs: Vec::new(),
1022                         holder_sig_first: false
1023                 }
1024         }
1025
1026         /// Create a new holder transaction with the given counterparty signatures.
1027         /// The funding keys are used to figure out which signature should go first when building the transaction for broadcast.
1028         pub fn new(commitment_tx: CommitmentTransaction, counterparty_sig: Signature, counterparty_htlc_sigs: Vec<Signature>, holder_funding_key: &PublicKey, counterparty_funding_key: &PublicKey) -> Self {
1029                 Self {
1030                         inner: commitment_tx,
1031                         counterparty_sig,
1032                         counterparty_htlc_sigs,
1033                         holder_sig_first: holder_funding_key.serialize()[..] < counterparty_funding_key.serialize()[..],
1034                 }
1035         }
1036
1037         pub(crate) fn add_holder_sig(&self, funding_redeemscript: &Script, holder_sig: Signature) -> Transaction {
1038                 // First push the multisig dummy, note that due to BIP147 (NULLDUMMY) it must be a zero-length element.
1039                 let mut tx = self.inner.built.transaction.clone();
1040                 tx.input[0].witness.push(Vec::new());
1041
1042                 if self.holder_sig_first {
1043                         tx.input[0].witness.push_bitcoin_signature(&holder_sig.serialize_der(), EcdsaSighashType::All);
1044                         tx.input[0].witness.push_bitcoin_signature(&self.counterparty_sig.serialize_der(), EcdsaSighashType::All);
1045                 } else {
1046                         tx.input[0].witness.push_bitcoin_signature(&self.counterparty_sig.serialize_der(), EcdsaSighashType::All);
1047                         tx.input[0].witness.push_bitcoin_signature(&holder_sig.serialize_der(), EcdsaSighashType::All);
1048                 }
1049
1050                 tx.input[0].witness.push(funding_redeemscript.as_bytes().to_vec());
1051                 tx
1052         }
1053 }
1054
1055 /// A pre-built Bitcoin commitment transaction and its txid.
1056 #[derive(Clone)]
1057 pub struct BuiltCommitmentTransaction {
1058         /// The commitment transaction
1059         pub transaction: Transaction,
1060         /// The txid for the commitment transaction.
1061         ///
1062         /// This is provided as a performance optimization, instead of calling transaction.txid()
1063         /// multiple times.
1064         pub txid: Txid,
1065 }
1066
1067 impl_writeable_tlv_based!(BuiltCommitmentTransaction, {
1068         (0, transaction, required),
1069         (2, txid, required),
1070 });
1071
1072 impl BuiltCommitmentTransaction {
1073         /// Get the SIGHASH_ALL sighash value of the transaction.
1074         ///
1075         /// This can be used to verify a signature.
1076         pub fn get_sighash_all(&self, funding_redeemscript: &Script, channel_value_satoshis: u64) -> Message {
1077                 let sighash = &sighash::SighashCache::new(&self.transaction).segwit_signature_hash(0, funding_redeemscript, channel_value_satoshis, EcdsaSighashType::All).unwrap()[..];
1078                 hash_to_message!(sighash)
1079         }
1080
1081         /// Sign a transaction, either because we are counter-signing the counterparty's transaction or
1082         /// because we are about to broadcast a holder transaction.
1083         pub fn sign<T: secp256k1::Signing>(&self, funding_key: &SecretKey, funding_redeemscript: &Script, channel_value_satoshis: u64, secp_ctx: &Secp256k1<T>) -> Signature {
1084                 let sighash = self.get_sighash_all(funding_redeemscript, channel_value_satoshis);
1085                 sign(secp_ctx, &sighash, funding_key)
1086         }
1087 }
1088
1089 /// This class tracks the per-transaction information needed to build a closing transaction and will
1090 /// actually build it and sign.
1091 ///
1092 /// This class can be used inside a signer implementation to generate a signature given the relevant
1093 /// secret key.
1094 #[derive(Clone, Hash, PartialEq, Eq)]
1095 pub struct ClosingTransaction {
1096         to_holder_value_sat: u64,
1097         to_counterparty_value_sat: u64,
1098         to_holder_script: Script,
1099         to_counterparty_script: Script,
1100         built: Transaction,
1101 }
1102
1103 impl ClosingTransaction {
1104         /// Construct an object of the class
1105         pub fn new(
1106                 to_holder_value_sat: u64,
1107                 to_counterparty_value_sat: u64,
1108                 to_holder_script: Script,
1109                 to_counterparty_script: Script,
1110                 funding_outpoint: OutPoint,
1111         ) -> Self {
1112                 let built = build_closing_transaction(
1113                         to_holder_value_sat, to_counterparty_value_sat,
1114                         to_holder_script.clone(), to_counterparty_script.clone(),
1115                         funding_outpoint
1116                 );
1117                 ClosingTransaction {
1118                         to_holder_value_sat,
1119                         to_counterparty_value_sat,
1120                         to_holder_script,
1121                         to_counterparty_script,
1122                         built
1123                 }
1124         }
1125
1126         /// Trust our pre-built transaction.
1127         ///
1128         /// Applies a wrapper which allows access to the transaction.
1129         ///
1130         /// This should only be used if you fully trust the builder of this object. It should not
1131         /// be used by an external signer - instead use the verify function.
1132         pub fn trust(&self) -> TrustedClosingTransaction {
1133                 TrustedClosingTransaction { inner: self }
1134         }
1135
1136         /// Verify our pre-built transaction.
1137         ///
1138         /// Applies a wrapper which allows access to the transaction.
1139         ///
1140         /// An external validating signer must call this method before signing
1141         /// or using the built transaction.
1142         pub fn verify(&self, funding_outpoint: OutPoint) -> Result<TrustedClosingTransaction, ()> {
1143                 let built = build_closing_transaction(
1144                         self.to_holder_value_sat, self.to_counterparty_value_sat,
1145                         self.to_holder_script.clone(), self.to_counterparty_script.clone(),
1146                         funding_outpoint
1147                 );
1148                 if self.built != built {
1149                         return Err(())
1150                 }
1151                 Ok(TrustedClosingTransaction { inner: self })
1152         }
1153
1154         /// The value to be sent to the holder, or zero if the output will be omitted
1155         pub fn to_holder_value_sat(&self) -> u64 {
1156                 self.to_holder_value_sat
1157         }
1158
1159         /// The value to be sent to the counterparty, or zero if the output will be omitted
1160         pub fn to_counterparty_value_sat(&self) -> u64 {
1161                 self.to_counterparty_value_sat
1162         }
1163
1164         /// The destination of the holder's output
1165         pub fn to_holder_script(&self) -> &Script {
1166                 &self.to_holder_script
1167         }
1168
1169         /// The destination of the counterparty's output
1170         pub fn to_counterparty_script(&self) -> &Script {
1171                 &self.to_counterparty_script
1172         }
1173 }
1174
1175 /// A wrapper on ClosingTransaction indicating that the built bitcoin
1176 /// transaction is trusted.
1177 ///
1178 /// See trust() and verify() functions on CommitmentTransaction.
1179 ///
1180 /// This structure implements Deref.
1181 pub struct TrustedClosingTransaction<'a> {
1182         inner: &'a ClosingTransaction,
1183 }
1184
1185 impl<'a> Deref for TrustedClosingTransaction<'a> {
1186         type Target = ClosingTransaction;
1187
1188         fn deref(&self) -> &Self::Target { self.inner }
1189 }
1190
1191 impl<'a> TrustedClosingTransaction<'a> {
1192         /// The pre-built Bitcoin commitment transaction
1193         pub fn built_transaction(&self) -> &Transaction {
1194                 &self.inner.built
1195         }
1196
1197         /// Get the SIGHASH_ALL sighash value of the transaction.
1198         ///
1199         /// This can be used to verify a signature.
1200         pub fn get_sighash_all(&self, funding_redeemscript: &Script, channel_value_satoshis: u64) -> Message {
1201                 let sighash = &sighash::SighashCache::new(&self.inner.built).segwit_signature_hash(0, funding_redeemscript, channel_value_satoshis, EcdsaSighashType::All).unwrap()[..];
1202                 hash_to_message!(sighash)
1203         }
1204
1205         /// Sign a transaction, either because we are counter-signing the counterparty's transaction or
1206         /// because we are about to broadcast a holder transaction.
1207         pub fn sign<T: secp256k1::Signing>(&self, funding_key: &SecretKey, funding_redeemscript: &Script, channel_value_satoshis: u64, secp_ctx: &Secp256k1<T>) -> Signature {
1208                 let sighash = self.get_sighash_all(funding_redeemscript, channel_value_satoshis);
1209                 sign(secp_ctx, &sighash, funding_key)
1210         }
1211 }
1212
1213 /// This class tracks the per-transaction information needed to build a commitment transaction and will
1214 /// actually build it and sign.  It is used for holder transactions that we sign only when needed
1215 /// and for transactions we sign for the counterparty.
1216 ///
1217 /// This class can be used inside a signer implementation to generate a signature given the relevant
1218 /// secret key.
1219 #[derive(Clone)]
1220 pub struct CommitmentTransaction {
1221         commitment_number: u64,
1222         to_broadcaster_value_sat: u64,
1223         to_countersignatory_value_sat: u64,
1224         feerate_per_kw: u32,
1225         htlcs: Vec<HTLCOutputInCommitment>,
1226         // A boolean that is serialization backwards-compatible
1227         opt_anchors: Option<()>,
1228         // Whether non-zero-fee anchors should be used
1229         opt_non_zero_fee_anchors: Option<()>,
1230         // A cache of the parties' pubkeys required to construct the transaction, see doc for trust()
1231         keys: TxCreationKeys,
1232         // For access to the pre-built transaction, see doc for trust()
1233         built: BuiltCommitmentTransaction,
1234 }
1235
1236 impl Eq for CommitmentTransaction {}
1237 impl PartialEq for CommitmentTransaction {
1238         fn eq(&self, o: &Self) -> bool {
1239                 let eq = self.commitment_number == o.commitment_number &&
1240                         self.to_broadcaster_value_sat == o.to_broadcaster_value_sat &&
1241                         self.to_countersignatory_value_sat == o.to_countersignatory_value_sat &&
1242                         self.feerate_per_kw == o.feerate_per_kw &&
1243                         self.htlcs == o.htlcs &&
1244                         self.opt_anchors == o.opt_anchors &&
1245                         self.keys == o.keys;
1246                 if eq {
1247                         debug_assert_eq!(self.built.transaction, o.built.transaction);
1248                         debug_assert_eq!(self.built.txid, o.built.txid);
1249                 }
1250                 eq
1251         }
1252 }
1253
1254 impl_writeable_tlv_based!(CommitmentTransaction, {
1255         (0, commitment_number, required),
1256         (2, to_broadcaster_value_sat, required),
1257         (4, to_countersignatory_value_sat, required),
1258         (6, feerate_per_kw, required),
1259         (8, keys, required),
1260         (10, built, required),
1261         (12, htlcs, vec_type),
1262         (14, opt_anchors, option),
1263         (16, opt_non_zero_fee_anchors, option),
1264 });
1265
1266 impl CommitmentTransaction {
1267         /// Construct an object of the class while assigning transaction output indices to HTLCs.
1268         ///
1269         /// Populates HTLCOutputInCommitment.transaction_output_index in htlcs_with_aux.
1270         ///
1271         /// The generic T allows the caller to match the HTLC output index with auxiliary data.
1272         /// This auxiliary data is not stored in this object.
1273         ///
1274         /// Only include HTLCs that are above the dust limit for the channel.
1275         ///
1276         /// (C-not exported) due to the generic though we likely should expose a version without
1277         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 {
1278                 // Sort outputs and populate output indices while keeping track of the auxiliary data
1279                 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();
1280
1281                 let (obscured_commitment_transaction_number, txins) = Self::internal_build_inputs(commitment_number, channel_parameters);
1282                 let transaction = Self::make_transaction(obscured_commitment_transaction_number, txins, outputs);
1283                 let txid = transaction.txid();
1284                 CommitmentTransaction {
1285                         commitment_number,
1286                         to_broadcaster_value_sat,
1287                         to_countersignatory_value_sat,
1288                         feerate_per_kw,
1289                         htlcs,
1290                         opt_anchors: if opt_anchors { Some(()) } else { None },
1291                         keys,
1292                         built: BuiltCommitmentTransaction {
1293                                 transaction,
1294                                 txid
1295                         },
1296                         opt_non_zero_fee_anchors: None,
1297                 }
1298         }
1299
1300         /// Use non-zero fee anchors
1301         ///
1302         /// (C-not exported) due to move, and also not likely to be useful for binding users
1303         pub fn with_non_zero_fee_anchors(mut self) -> Self {
1304                 self.opt_non_zero_fee_anchors = Some(());
1305                 self
1306         }
1307
1308         fn internal_rebuild_transaction(&self, keys: &TxCreationKeys, channel_parameters: &DirectedChannelTransactionParameters, broadcaster_funding_key: &PublicKey, countersignatory_funding_key: &PublicKey) -> Result<BuiltCommitmentTransaction, ()> {
1309                 let (obscured_commitment_transaction_number, txins) = Self::internal_build_inputs(self.commitment_number, channel_parameters);
1310
1311                 let mut htlcs_with_aux = self.htlcs.iter().map(|h| (h.clone(), ())).collect();
1312                 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)?;
1313
1314                 let transaction = Self::make_transaction(obscured_commitment_transaction_number, txins, outputs);
1315                 let txid = transaction.txid();
1316                 let built_transaction = BuiltCommitmentTransaction {
1317                         transaction,
1318                         txid
1319                 };
1320                 Ok(built_transaction)
1321         }
1322
1323         fn make_transaction(obscured_commitment_transaction_number: u64, txins: Vec<TxIn>, outputs: Vec<TxOut>) -> Transaction {
1324                 Transaction {
1325                         version: 2,
1326                         lock_time: PackedLockTime(((0x20 as u32) << 8 * 3) | ((obscured_commitment_transaction_number & 0xffffffu64) as u32)),
1327                         input: txins,
1328                         output: outputs,
1329                 }
1330         }
1331
1332         // This is used in two cases:
1333         // - initial sorting of outputs / HTLCs in the constructor, in which case T is auxiliary data the
1334         //   caller needs to have sorted together with the HTLCs so it can keep track of the output index
1335         // - building of a bitcoin transaction during a verify() call, in which case T is just ()
1336         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>), ()> {
1337                 let countersignatory_pubkeys = channel_parameters.countersignatory_pubkeys();
1338                 let contest_delay = channel_parameters.contest_delay();
1339
1340                 let mut txouts: Vec<(TxOut, Option<&mut HTLCOutputInCommitment>)> = Vec::new();
1341
1342                 if to_countersignatory_value_sat > 0 {
1343                         let script = if opt_anchors {
1344                             get_to_countersignatory_with_anchors_redeemscript(&countersignatory_pubkeys.payment_point).to_v0_p2wsh()
1345                         } else {
1346                             Payload::p2wpkh(&BitcoinPublicKey::new(countersignatory_pubkeys.payment_point)).unwrap().script_pubkey()
1347                         };
1348                         txouts.push((
1349                                 TxOut {
1350                                         script_pubkey: script.clone(),
1351                                         value: to_countersignatory_value_sat,
1352                                 },
1353                                 None,
1354                         ))
1355                 }
1356
1357                 if to_broadcaster_value_sat > 0 {
1358                         let redeem_script = get_revokeable_redeemscript(
1359                                 &keys.revocation_key,
1360                                 contest_delay,
1361                                 &keys.broadcaster_delayed_payment_key,
1362                         );
1363                         txouts.push((
1364                                 TxOut {
1365                                         script_pubkey: redeem_script.to_v0_p2wsh(),
1366                                         value: to_broadcaster_value_sat,
1367                                 },
1368                                 None,
1369                         ));
1370                 }
1371
1372                 if opt_anchors {
1373                         if to_broadcaster_value_sat > 0 || !htlcs_with_aux.is_empty() {
1374                                 let anchor_script = get_anchor_redeemscript(broadcaster_funding_key);
1375                                 txouts.push((
1376                                         TxOut {
1377                                                 script_pubkey: anchor_script.to_v0_p2wsh(),
1378                                                 value: ANCHOR_OUTPUT_VALUE_SATOSHI,
1379                                         },
1380                                         None,
1381                                 ));
1382                         }
1383
1384                         if to_countersignatory_value_sat > 0 || !htlcs_with_aux.is_empty() {
1385                                 let anchor_script = get_anchor_redeemscript(countersignatory_funding_key);
1386                                 txouts.push((
1387                                         TxOut {
1388                                                 script_pubkey: anchor_script.to_v0_p2wsh(),
1389                                                 value: ANCHOR_OUTPUT_VALUE_SATOSHI,
1390                                         },
1391                                         None,
1392                                 ));
1393                         }
1394                 }
1395
1396                 let mut htlcs = Vec::with_capacity(htlcs_with_aux.len());
1397                 for (htlc, _) in htlcs_with_aux {
1398                         let script = chan_utils::get_htlc_redeemscript(&htlc, opt_anchors, &keys);
1399                         let txout = TxOut {
1400                                 script_pubkey: script.to_v0_p2wsh(),
1401                                 value: htlc.amount_msat / 1000,
1402                         };
1403                         txouts.push((txout, Some(htlc)));
1404                 }
1405
1406                 // Sort output in BIP-69 order (amount, scriptPubkey).  Tie-breaks based on HTLC
1407                 // CLTV expiration height.
1408                 sort_outputs(&mut txouts, |a, b| {
1409                         if let &Some(ref a_htlcout) = a {
1410                                 if let &Some(ref b_htlcout) = b {
1411                                         a_htlcout.cltv_expiry.cmp(&b_htlcout.cltv_expiry)
1412                                                 // Note that due to hash collisions, we have to have a fallback comparison
1413                                                 // here for fuzzing mode (otherwise at least chanmon_fail_consistency
1414                                                 // may fail)!
1415                                                 .then(a_htlcout.payment_hash.0.cmp(&b_htlcout.payment_hash.0))
1416                                 // For non-HTLC outputs, if they're copying our SPK we don't really care if we
1417                                 // close the channel due to mismatches - they're doing something dumb:
1418                                 } else { cmp::Ordering::Equal }
1419                         } else { cmp::Ordering::Equal }
1420                 });
1421
1422                 let mut outputs = Vec::with_capacity(txouts.len());
1423                 for (idx, out) in txouts.drain(..).enumerate() {
1424                         if let Some(htlc) = out.1 {
1425                                 htlc.transaction_output_index = Some(idx as u32);
1426                                 htlcs.push(htlc.clone());
1427                         }
1428                         outputs.push(out.0);
1429                 }
1430                 Ok((outputs, htlcs))
1431         }
1432
1433         fn internal_build_inputs(commitment_number: u64, channel_parameters: &DirectedChannelTransactionParameters) -> (u64, Vec<TxIn>) {
1434                 let broadcaster_pubkeys = channel_parameters.broadcaster_pubkeys();
1435                 let countersignatory_pubkeys = channel_parameters.countersignatory_pubkeys();
1436                 let commitment_transaction_number_obscure_factor = get_commitment_transaction_number_obscure_factor(
1437                         &broadcaster_pubkeys.payment_point,
1438                         &countersignatory_pubkeys.payment_point,
1439                         channel_parameters.is_outbound(),
1440                 );
1441
1442                 let obscured_commitment_transaction_number =
1443                         commitment_transaction_number_obscure_factor ^ (INITIAL_COMMITMENT_NUMBER - commitment_number);
1444
1445                 let txins = {
1446                         let mut ins: Vec<TxIn> = Vec::new();
1447                         ins.push(TxIn {
1448                                 previous_output: channel_parameters.funding_outpoint(),
1449                                 script_sig: Script::new(),
1450                                 sequence: Sequence(((0x80 as u32) << 8 * 3)
1451                                         | ((obscured_commitment_transaction_number >> 3 * 8) as u32)),
1452                                 witness: Witness::new(),
1453                         });
1454                         ins
1455                 };
1456                 (obscured_commitment_transaction_number, txins)
1457         }
1458
1459         /// The backwards-counting commitment number
1460         pub fn commitment_number(&self) -> u64 {
1461                 self.commitment_number
1462         }
1463
1464         /// The value to be sent to the broadcaster
1465         pub fn to_broadcaster_value_sat(&self) -> u64 {
1466                 self.to_broadcaster_value_sat
1467         }
1468
1469         /// The value to be sent to the counterparty
1470         pub fn to_countersignatory_value_sat(&self) -> u64 {
1471                 self.to_countersignatory_value_sat
1472         }
1473
1474         /// The feerate paid per 1000-weight-unit in this commitment transaction.
1475         pub fn feerate_per_kw(&self) -> u32 {
1476                 self.feerate_per_kw
1477         }
1478
1479         /// The non-dust HTLCs (direction, amt, height expiration, hash, transaction output index)
1480         /// which were included in this commitment transaction in output order.
1481         /// The transaction index is always populated.
1482         ///
1483         /// (C-not exported) as we cannot currently convert Vec references to/from C, though we should
1484         /// expose a less effecient version which creates a Vec of references in the future.
1485         pub fn htlcs(&self) -> &Vec<HTLCOutputInCommitment> {
1486                 &self.htlcs
1487         }
1488
1489         /// Trust our pre-built transaction and derived transaction creation public keys.
1490         ///
1491         /// Applies a wrapper which allows access to these fields.
1492         ///
1493         /// This should only be used if you fully trust the builder of this object.  It should not
1494         /// be used by an external signer - instead use the verify function.
1495         pub fn trust(&self) -> TrustedCommitmentTransaction {
1496                 TrustedCommitmentTransaction { inner: self }
1497         }
1498
1499         /// Verify our pre-built transaction and derived transaction creation public keys.
1500         ///
1501         /// Applies a wrapper which allows access to these fields.
1502         ///
1503         /// An external validating signer must call this method before signing
1504         /// or using the built transaction.
1505         pub fn verify<T: secp256k1::Signing + secp256k1::Verification>(&self, channel_parameters: &DirectedChannelTransactionParameters, broadcaster_keys: &ChannelPublicKeys, countersignatory_keys: &ChannelPublicKeys, secp_ctx: &Secp256k1<T>) -> Result<TrustedCommitmentTransaction, ()> {
1506                 // This is the only field of the key cache that we trust
1507                 let per_commitment_point = self.keys.per_commitment_point;
1508                 let keys = TxCreationKeys::from_channel_static_keys(&per_commitment_point, broadcaster_keys, countersignatory_keys, secp_ctx);
1509                 if keys != self.keys {
1510                         return Err(());
1511                 }
1512                 let tx = self.internal_rebuild_transaction(&keys, channel_parameters, &broadcaster_keys.funding_pubkey, &countersignatory_keys.funding_pubkey)?;
1513                 if self.built.transaction != tx.transaction || self.built.txid != tx.txid {
1514                         return Err(());
1515                 }
1516                 Ok(TrustedCommitmentTransaction { inner: self })
1517         }
1518 }
1519
1520 /// A wrapper on CommitmentTransaction indicating that the derived fields (the built bitcoin
1521 /// transaction and the transaction creation keys) are trusted.
1522 ///
1523 /// See trust() and verify() functions on CommitmentTransaction.
1524 ///
1525 /// This structure implements Deref.
1526 pub struct TrustedCommitmentTransaction<'a> {
1527         inner: &'a CommitmentTransaction,
1528 }
1529
1530 impl<'a> Deref for TrustedCommitmentTransaction<'a> {
1531         type Target = CommitmentTransaction;
1532
1533         fn deref(&self) -> &Self::Target { self.inner }
1534 }
1535
1536 impl<'a> TrustedCommitmentTransaction<'a> {
1537         /// The transaction ID of the built Bitcoin transaction
1538         pub fn txid(&self) -> Txid {
1539                 self.inner.built.txid
1540         }
1541
1542         /// The pre-built Bitcoin commitment transaction
1543         pub fn built_transaction(&self) -> &BuiltCommitmentTransaction {
1544                 &self.inner.built
1545         }
1546
1547         /// The pre-calculated transaction creation public keys.
1548         pub fn keys(&self) -> &TxCreationKeys {
1549                 &self.inner.keys
1550         }
1551
1552         /// Should anchors be used.
1553         pub fn opt_anchors(&self) -> bool {
1554                 self.opt_anchors.is_some()
1555         }
1556
1557         /// Get a signature for each HTLC which was included in the commitment transaction (ie for
1558         /// which HTLCOutputInCommitment::transaction_output_index.is_some()).
1559         ///
1560         /// The returned Vec has one entry for each HTLC, and in the same order.
1561         ///
1562         /// This function is only valid in the holder commitment context, it always uses EcdsaSighashType::All.
1563         pub fn get_htlc_sigs<T: secp256k1::Signing>(&self, htlc_base_key: &SecretKey, channel_parameters: &DirectedChannelTransactionParameters, secp_ctx: &Secp256k1<T>) -> Result<Vec<Signature>, ()> {
1564                 let inner = self.inner;
1565                 let keys = &inner.keys;
1566                 let txid = inner.built.txid;
1567                 let mut ret = Vec::with_capacity(inner.htlcs.len());
1568                 let holder_htlc_key = derive_private_key(secp_ctx, &inner.keys.per_commitment_point, htlc_base_key);
1569
1570                 for this_htlc in inner.htlcs.iter() {
1571                         assert!(this_htlc.transaction_output_index.is_some());
1572                         let htlc_tx = build_htlc_transaction(&txid, inner.feerate_per_kw, channel_parameters.contest_delay(), &this_htlc, self.opt_anchors(), self.opt_non_zero_fee_anchors.is_some(), &keys.broadcaster_delayed_payment_key, &keys.revocation_key);
1573
1574                         let htlc_redeemscript = get_htlc_redeemscript_with_explicit_keys(&this_htlc, self.opt_anchors(), &keys.broadcaster_htlc_key, &keys.countersignatory_htlc_key, &keys.revocation_key);
1575
1576                         let sighash = hash_to_message!(&sighash::SighashCache::new(&htlc_tx).segwit_signature_hash(0, &htlc_redeemscript, this_htlc.amount_msat / 1000, EcdsaSighashType::All).unwrap()[..]);
1577                         ret.push(sign(secp_ctx, &sighash, &holder_htlc_key));
1578                 }
1579                 Ok(ret)
1580         }
1581
1582         /// Gets a signed HTLC transaction given a preimage (for !htlc.offered) and the holder HTLC transaction signature.
1583         pub(crate) fn get_signed_htlc_tx(&self, channel_parameters: &DirectedChannelTransactionParameters, htlc_index: usize, counterparty_signature: &Signature, signature: &Signature, preimage: &Option<PaymentPreimage>) -> Transaction {
1584                 let inner = self.inner;
1585                 let keys = &inner.keys;
1586                 let txid = inner.built.txid;
1587                 let this_htlc = &inner.htlcs[htlc_index];
1588                 assert!(this_htlc.transaction_output_index.is_some());
1589                 // if we don't have preimage for an HTLC-Success, we can't generate an HTLC transaction.
1590                 if !this_htlc.offered && preimage.is_none() { unreachable!(); }
1591                 // Further, we should never be provided the preimage for an HTLC-Timeout transaction.
1592                 if  this_htlc.offered && preimage.is_some() { unreachable!(); }
1593
1594                 let mut htlc_tx = build_htlc_transaction(&txid, inner.feerate_per_kw, channel_parameters.contest_delay(), &this_htlc, self.opt_anchors(), self.opt_non_zero_fee_anchors.is_some(), &keys.broadcaster_delayed_payment_key, &keys.revocation_key);
1595
1596                 let htlc_redeemscript = get_htlc_redeemscript_with_explicit_keys(&this_htlc, self.opt_anchors(), &keys.broadcaster_htlc_key, &keys.countersignatory_htlc_key, &keys.revocation_key);
1597
1598                 htlc_tx.input[0].witness = chan_utils::build_htlc_input_witness(
1599                         signature, counterparty_signature, preimage, &htlc_redeemscript, self.opt_anchors(),
1600                 );
1601                 htlc_tx
1602         }
1603 }
1604
1605 /// Commitment transaction numbers which appear in the transactions themselves are XOR'd with a
1606 /// shared secret first. This prevents on-chain observers from discovering how many commitment
1607 /// transactions occurred in a channel before it was closed.
1608 ///
1609 /// This function gets the shared secret from relevant channel public keys and can be used to
1610 /// "decrypt" the commitment transaction number given a commitment transaction on-chain.
1611 pub fn get_commitment_transaction_number_obscure_factor(
1612         broadcaster_payment_basepoint: &PublicKey,
1613         countersignatory_payment_basepoint: &PublicKey,
1614         outbound_from_broadcaster: bool,
1615 ) -> u64 {
1616         let mut sha = Sha256::engine();
1617
1618         if outbound_from_broadcaster {
1619                 sha.input(&broadcaster_payment_basepoint.serialize());
1620                 sha.input(&countersignatory_payment_basepoint.serialize());
1621         } else {
1622                 sha.input(&countersignatory_payment_basepoint.serialize());
1623                 sha.input(&broadcaster_payment_basepoint.serialize());
1624         }
1625         let res = Sha256::from_engine(sha).into_inner();
1626
1627         ((res[26] as u64) << 5 * 8)
1628                 | ((res[27] as u64) << 4 * 8)
1629                 | ((res[28] as u64) << 3 * 8)
1630                 | ((res[29] as u64) << 2 * 8)
1631                 | ((res[30] as u64) << 1 * 8)
1632                 | ((res[31] as u64) << 0 * 8)
1633 }
1634
1635 #[cfg(test)]
1636 mod tests {
1637         use super::CounterpartyCommitmentSecrets;
1638         use crate::{hex, chain};
1639         use crate::prelude::*;
1640         use crate::ln::chan_utils::{get_htlc_redeemscript, get_to_countersignatory_with_anchors_redeemscript, CommitmentTransaction, TxCreationKeys, ChannelTransactionParameters, CounterpartyChannelTransactionParameters, HTLCOutputInCommitment};
1641         use bitcoin::secp256k1::{PublicKey, SecretKey, Secp256k1};
1642         use crate::util::test_utils;
1643         use crate::chain::keysinterface::{ChannelSigner, SignerProvider};
1644         use bitcoin::{Network, Txid};
1645         use bitcoin::hashes::Hash;
1646         use crate::ln::PaymentHash;
1647         use bitcoin::hashes::hex::ToHex;
1648         use bitcoin::util::address::Payload;
1649         use bitcoin::PublicKey as BitcoinPublicKey;
1650
1651         #[test]
1652         fn test_anchors() {
1653                 let secp_ctx = Secp256k1::new();
1654
1655                 let seed = [42; 32];
1656                 let network = Network::Testnet;
1657                 let keys_provider = test_utils::TestKeysInterface::new(&seed, network);
1658                 let signer = keys_provider.derive_channel_signer(3000, keys_provider.generate_channel_keys_id(false, 1_000_000, 0));
1659                 let counterparty_signer = keys_provider.derive_channel_signer(3000, keys_provider.generate_channel_keys_id(true, 1_000_000, 1));
1660                 let delayed_payment_base = &signer.pubkeys().delayed_payment_basepoint;
1661                 let per_commitment_secret = SecretKey::from_slice(&hex::decode("1f1e1d1c1b1a191817161514131211100f0e0d0c0b0a09080706050403020100").unwrap()[..]).unwrap();
1662                 let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &per_commitment_secret);
1663                 let htlc_basepoint = &signer.pubkeys().htlc_basepoint;
1664                 let holder_pubkeys = signer.pubkeys();
1665                 let counterparty_pubkeys = counterparty_signer.pubkeys();
1666                 let keys = TxCreationKeys::derive_new(&secp_ctx, &per_commitment_point, delayed_payment_base, htlc_basepoint, &counterparty_pubkeys.revocation_basepoint, &counterparty_pubkeys.htlc_basepoint);
1667                 let mut channel_parameters = ChannelTransactionParameters {
1668                         holder_pubkeys: holder_pubkeys.clone(),
1669                         holder_selected_contest_delay: 0,
1670                         is_outbound_from_holder: false,
1671                         counterparty_parameters: Some(CounterpartyChannelTransactionParameters { pubkeys: counterparty_pubkeys.clone(), selected_contest_delay: 0 }),
1672                         funding_outpoint: Some(chain::transaction::OutPoint { txid: Txid::all_zeros(), index: 0 }),
1673                         opt_anchors: None,
1674                         opt_non_zero_fee_anchors: None,
1675                 };
1676
1677                 let mut htlcs_with_aux: Vec<(_, ())> = Vec::new();
1678
1679                 // Generate broadcaster and counterparty outputs
1680                 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1681                         0, 1000, 2000,
1682                         false,
1683                         holder_pubkeys.funding_pubkey,
1684                         counterparty_pubkeys.funding_pubkey,
1685                         keys.clone(), 1,
1686                         &mut htlcs_with_aux, &channel_parameters.as_holder_broadcastable()
1687                 );
1688                 assert_eq!(tx.built.transaction.output.len(), 2);
1689                 assert_eq!(tx.built.transaction.output[1].script_pubkey, Payload::p2wpkh(&BitcoinPublicKey::new(counterparty_pubkeys.payment_point)).unwrap().script_pubkey());
1690
1691                 // Generate broadcaster and counterparty outputs as well as two anchors
1692                 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1693                         0, 1000, 2000,
1694                         true,
1695                         holder_pubkeys.funding_pubkey,
1696                         counterparty_pubkeys.funding_pubkey,
1697                         keys.clone(), 1,
1698                         &mut htlcs_with_aux, &channel_parameters.as_holder_broadcastable()
1699                 );
1700                 assert_eq!(tx.built.transaction.output.len(), 4);
1701                 assert_eq!(tx.built.transaction.output[3].script_pubkey, get_to_countersignatory_with_anchors_redeemscript(&counterparty_pubkeys.payment_point).to_v0_p2wsh());
1702
1703                 // Generate broadcaster output and anchor
1704                 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1705                         0, 3000, 0,
1706                         true,
1707                         holder_pubkeys.funding_pubkey,
1708                         counterparty_pubkeys.funding_pubkey,
1709                         keys.clone(), 1,
1710                         &mut htlcs_with_aux, &channel_parameters.as_holder_broadcastable()
1711                 );
1712                 assert_eq!(tx.built.transaction.output.len(), 2);
1713
1714                 // Generate counterparty output and anchor
1715                 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1716                         0, 0, 3000,
1717                         true,
1718                         holder_pubkeys.funding_pubkey,
1719                         counterparty_pubkeys.funding_pubkey,
1720                         keys.clone(), 1,
1721                         &mut htlcs_with_aux, &channel_parameters.as_holder_broadcastable()
1722                 );
1723                 assert_eq!(tx.built.transaction.output.len(), 2);
1724
1725                 let received_htlc = HTLCOutputInCommitment {
1726                         offered: false,
1727                         amount_msat: 400000,
1728                         cltv_expiry: 100,
1729                         payment_hash: PaymentHash([42; 32]),
1730                         transaction_output_index: None,
1731                 };
1732
1733                 let offered_htlc = HTLCOutputInCommitment {
1734                         offered: true,
1735                         amount_msat: 600000,
1736                         cltv_expiry: 100,
1737                         payment_hash: PaymentHash([43; 32]),
1738                         transaction_output_index: None,
1739                 };
1740
1741                 // Generate broadcaster output and received and offered HTLC outputs,  w/o anchors
1742                 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1743                         0, 3000, 0,
1744                         false,
1745                         holder_pubkeys.funding_pubkey,
1746                         counterparty_pubkeys.funding_pubkey,
1747                         keys.clone(), 1,
1748                         &mut vec![(received_htlc.clone(), ()), (offered_htlc.clone(), ())],
1749                         &channel_parameters.as_holder_broadcastable()
1750                 );
1751                 assert_eq!(tx.built.transaction.output.len(), 3);
1752                 assert_eq!(tx.built.transaction.output[0].script_pubkey, get_htlc_redeemscript(&received_htlc, false, &keys).to_v0_p2wsh());
1753                 assert_eq!(tx.built.transaction.output[1].script_pubkey, get_htlc_redeemscript(&offered_htlc, false, &keys).to_v0_p2wsh());
1754                 assert_eq!(get_htlc_redeemscript(&received_htlc, false, &keys).to_v0_p2wsh().to_hex(),
1755                                    "0020e43a7c068553003fe68fcae424fb7b28ec5ce48cd8b6744b3945631389bad2fb");
1756                 assert_eq!(get_htlc_redeemscript(&offered_htlc, false, &keys).to_v0_p2wsh().to_hex(),
1757                                    "0020215d61bba56b19e9eadb6107f5a85d7f99c40f65992443f69229c290165bc00d");
1758
1759                 // Generate broadcaster output and received and offered HTLC outputs,  with anchors
1760                 channel_parameters.opt_anchors = Some(());
1761                 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1762                         0, 3000, 0,
1763                         true,
1764                         holder_pubkeys.funding_pubkey,
1765                         counterparty_pubkeys.funding_pubkey,
1766                         keys.clone(), 1,
1767                         &mut vec![(received_htlc.clone(), ()), (offered_htlc.clone(), ())],
1768                         &channel_parameters.as_holder_broadcastable()
1769                 );
1770                 assert_eq!(tx.built.transaction.output.len(), 5);
1771                 assert_eq!(tx.built.transaction.output[2].script_pubkey, get_htlc_redeemscript(&received_htlc, true, &keys).to_v0_p2wsh());
1772                 assert_eq!(tx.built.transaction.output[3].script_pubkey, get_htlc_redeemscript(&offered_htlc, true, &keys).to_v0_p2wsh());
1773                 assert_eq!(get_htlc_redeemscript(&received_htlc, true, &keys).to_v0_p2wsh().to_hex(),
1774                                    "0020b70d0649c72b38756885c7a30908d912a7898dd5d79457a7280b8e9a20f3f2bc");
1775                 assert_eq!(get_htlc_redeemscript(&offered_htlc, true, &keys).to_v0_p2wsh().to_hex(),
1776                                    "002087a3faeb1950a469c0e2db4a79b093a41b9526e5a6fc6ef5cb949bde3be379c7");
1777         }
1778
1779         #[test]
1780         fn test_per_commitment_storage() {
1781                 // Test vectors from BOLT 3:
1782                 let mut secrets: Vec<[u8; 32]> = Vec::new();
1783                 let mut monitor;
1784
1785                 macro_rules! test_secrets {
1786                         () => {
1787                                 let mut idx = 281474976710655;
1788                                 for secret in secrets.iter() {
1789                                         assert_eq!(monitor.get_secret(idx).unwrap(), *secret);
1790                                         idx -= 1;
1791                                 }
1792                                 assert_eq!(monitor.get_min_seen_secret(), idx + 1);
1793                                 assert!(monitor.get_secret(idx).is_none());
1794                         };
1795                 }
1796
1797                 {
1798                         // insert_secret correct sequence
1799                         monitor = CounterpartyCommitmentSecrets::new();
1800                         secrets.clear();
1801
1802                         secrets.push([0; 32]);
1803                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1804                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1805                         test_secrets!();
1806
1807                         secrets.push([0; 32]);
1808                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1809                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1810                         test_secrets!();
1811
1812                         secrets.push([0; 32]);
1813                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1814                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1815                         test_secrets!();
1816
1817                         secrets.push([0; 32]);
1818                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1819                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
1820                         test_secrets!();
1821
1822                         secrets.push([0; 32]);
1823                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1824                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
1825                         test_secrets!();
1826
1827                         secrets.push([0; 32]);
1828                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1829                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
1830                         test_secrets!();
1831
1832                         secrets.push([0; 32]);
1833                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1834                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
1835                         test_secrets!();
1836
1837                         secrets.push([0; 32]);
1838                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1839                         monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap();
1840                         test_secrets!();
1841                 }
1842
1843                 {
1844                         // insert_secret #1 incorrect
1845                         monitor = CounterpartyCommitmentSecrets::new();
1846                         secrets.clear();
1847
1848                         secrets.push([0; 32]);
1849                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
1850                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1851                         test_secrets!();
1852
1853                         secrets.push([0; 32]);
1854                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1855                         assert!(monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).is_err());
1856                 }
1857
1858                 {
1859                         // insert_secret #2 incorrect (#1 derived from incorrect)
1860                         monitor = CounterpartyCommitmentSecrets::new();
1861                         secrets.clear();
1862
1863                         secrets.push([0; 32]);
1864                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
1865                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1866                         test_secrets!();
1867
1868                         secrets.push([0; 32]);
1869                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
1870                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1871                         test_secrets!();
1872
1873                         secrets.push([0; 32]);
1874                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1875                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1876                         test_secrets!();
1877
1878                         secrets.push([0; 32]);
1879                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1880                         assert!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).is_err());
1881                 }
1882
1883                 {
1884                         // insert_secret #3 incorrect
1885                         monitor = CounterpartyCommitmentSecrets::new();
1886                         secrets.clear();
1887
1888                         secrets.push([0; 32]);
1889                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1890                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1891                         test_secrets!();
1892
1893                         secrets.push([0; 32]);
1894                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1895                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1896                         test_secrets!();
1897
1898                         secrets.push([0; 32]);
1899                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
1900                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1901                         test_secrets!();
1902
1903                         secrets.push([0; 32]);
1904                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1905                         assert!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).is_err());
1906                 }
1907
1908                 {
1909                         // insert_secret #4 incorrect (1,2,3 derived from incorrect)
1910                         monitor = CounterpartyCommitmentSecrets::new();
1911                         secrets.clear();
1912
1913                         secrets.push([0; 32]);
1914                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
1915                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1916                         test_secrets!();
1917
1918                         secrets.push([0; 32]);
1919                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
1920                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1921                         test_secrets!();
1922
1923                         secrets.push([0; 32]);
1924                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
1925                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1926                         test_secrets!();
1927
1928                         secrets.push([0; 32]);
1929                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("ba65d7b0ef55a3ba300d4e87af29868f394f8f138d78a7011669c79b37b936f4").unwrap());
1930                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
1931                         test_secrets!();
1932
1933                         secrets.push([0; 32]);
1934                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1935                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
1936                         test_secrets!();
1937
1938                         secrets.push([0; 32]);
1939                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1940                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
1941                         test_secrets!();
1942
1943                         secrets.push([0; 32]);
1944                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1945                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
1946                         test_secrets!();
1947
1948                         secrets.push([0; 32]);
1949                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1950                         assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
1951                 }
1952
1953                 {
1954                         // insert_secret #5 incorrect
1955                         monitor = CounterpartyCommitmentSecrets::new();
1956                         secrets.clear();
1957
1958                         secrets.push([0; 32]);
1959                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1960                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1961                         test_secrets!();
1962
1963                         secrets.push([0; 32]);
1964                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1965                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1966                         test_secrets!();
1967
1968                         secrets.push([0; 32]);
1969                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1970                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1971                         test_secrets!();
1972
1973                         secrets.push([0; 32]);
1974                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1975                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
1976                         test_secrets!();
1977
1978                         secrets.push([0; 32]);
1979                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
1980                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
1981                         test_secrets!();
1982
1983                         secrets.push([0; 32]);
1984                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1985                         assert!(monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).is_err());
1986                 }
1987
1988                 {
1989                         // insert_secret #6 incorrect (5 derived from incorrect)
1990                         monitor = CounterpartyCommitmentSecrets::new();
1991                         secrets.clear();
1992
1993                         secrets.push([0; 32]);
1994                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1995                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1996                         test_secrets!();
1997
1998                         secrets.push([0; 32]);
1999                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2000                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2001                         test_secrets!();
2002
2003                         secrets.push([0; 32]);
2004                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2005                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2006                         test_secrets!();
2007
2008                         secrets.push([0; 32]);
2009                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2010                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2011                         test_secrets!();
2012
2013                         secrets.push([0; 32]);
2014                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
2015                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2016                         test_secrets!();
2017
2018                         secrets.push([0; 32]);
2019                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("b7e76a83668bde38b373970155c868a653304308f9896692f904a23731224bb1").unwrap());
2020                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2021                         test_secrets!();
2022
2023                         secrets.push([0; 32]);
2024                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2025                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2026                         test_secrets!();
2027
2028                         secrets.push([0; 32]);
2029                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2030                         assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
2031                 }
2032
2033                 {
2034                         // insert_secret #7 incorrect
2035                         monitor = CounterpartyCommitmentSecrets::new();
2036                         secrets.clear();
2037
2038                         secrets.push([0; 32]);
2039                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2040                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2041                         test_secrets!();
2042
2043                         secrets.push([0; 32]);
2044                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2045                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2046                         test_secrets!();
2047
2048                         secrets.push([0; 32]);
2049                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2050                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2051                         test_secrets!();
2052
2053                         secrets.push([0; 32]);
2054                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2055                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2056                         test_secrets!();
2057
2058                         secrets.push([0; 32]);
2059                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2060                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2061                         test_secrets!();
2062
2063                         secrets.push([0; 32]);
2064                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2065                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2066                         test_secrets!();
2067
2068                         secrets.push([0; 32]);
2069                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("e7971de736e01da8ed58b94c2fc216cb1dca9e326f3a96e7194fe8ea8af6c0a3").unwrap());
2070                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2071                         test_secrets!();
2072
2073                         secrets.push([0; 32]);
2074                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2075                         assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
2076                 }
2077
2078                 {
2079                         // insert_secret #8 incorrect
2080                         monitor = CounterpartyCommitmentSecrets::new();
2081                         secrets.clear();
2082
2083                         secrets.push([0; 32]);
2084                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2085                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2086                         test_secrets!();
2087
2088                         secrets.push([0; 32]);
2089                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2090                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2091                         test_secrets!();
2092
2093                         secrets.push([0; 32]);
2094                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2095                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2096                         test_secrets!();
2097
2098                         secrets.push([0; 32]);
2099                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2100                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2101                         test_secrets!();
2102
2103                         secrets.push([0; 32]);
2104                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2105                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2106                         test_secrets!();
2107
2108                         secrets.push([0; 32]);
2109                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2110                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2111                         test_secrets!();
2112
2113                         secrets.push([0; 32]);
2114                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2115                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2116                         test_secrets!();
2117
2118                         secrets.push([0; 32]);
2119                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a7efbc61aac46d34f77778bac22c8a20c6a46ca460addc49009bda875ec88fa4").unwrap());
2120                         assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
2121                 }
2122         }
2123 }