1use bitcoin::blockdata::script::{Script,Builder};
14use bitcoin::blockdata::opcodes;
15use bitcoin::blockdata::transaction::{TxIn,TxOut,OutPoint,Transaction, EcdsaSighashType};
16use bitcoin::util::sighash;
17use bitcoin::util::address::Payload;
18
19use bitcoin::hashes::{Hash, HashEngine};
20use bitcoin::hashes::sha256::Hash as Sha256;
21use bitcoin::hashes::ripemd160::Hash as Ripemd160;
22use bitcoin::hash_types::{Txid, PubkeyHash};
23
24use crate::ln::{PaymentHash, PaymentPreimage};
25use crate::ln::msgs::DecodeError;
26use crate::util::ser::{Readable, Writeable, Writer};
27use crate::util::transaction_utils;
28
29use bitcoin::secp256k1::{SecretKey, PublicKey, Scalar};
30use bitcoin::secp256k1::{Secp256k1, ecdsa::Signature, Message};
31use bitcoin::{PackedLockTime, secp256k1, Sequence, Witness};
32use bitcoin::PublicKey as BitcoinPublicKey;
33
34use crate::io;
35use crate::prelude::*;
36use core::cmp;
37use crate::ln::chan_utils;
38use crate::util::transaction_utils::sort_outputs;
39use crate::ln::channel::{INITIAL_COMMITMENT_NUMBER, ANCHOR_OUTPUT_VALUE_SATOSHI};
40use core::ops::Deref;
41use crate::chain;
42use crate::util::crypto::sign;
43
44pub const MAX_HTLCS: u16 = 483;
46pub const OFFERED_HTLC_SCRIPT_WEIGHT: usize = 133;
48pub const OFFERED_HTLC_SCRIPT_WEIGHT_ANCHORS: usize = 136;
50
51pub(crate) const MIN_ACCEPTED_HTLC_SCRIPT_WEIGHT: usize = 136;
54pub const MAX_ACCEPTED_HTLC_SCRIPT_WEIGHT: usize = 143;
58
59#[inline]
61pub fn htlc_success_tx_weight(opt_anchors: bool) -> u64 {
62 const HTLC_SUCCESS_TX_WEIGHT: u64 = 703;
63 const HTLC_SUCCESS_ANCHOR_TX_WEIGHT: u64 = 706;
64 if opt_anchors { HTLC_SUCCESS_ANCHOR_TX_WEIGHT } else { HTLC_SUCCESS_TX_WEIGHT }
65}
66
67#[inline]
69pub fn htlc_timeout_tx_weight(opt_anchors: bool) -> u64 {
70 const HTLC_TIMEOUT_TX_WEIGHT: u64 = 663;
71 const HTLC_TIMEOUT_ANCHOR_TX_WEIGHT: u64 = 666;
72 if opt_anchors { HTLC_TIMEOUT_ANCHOR_TX_WEIGHT } else { HTLC_TIMEOUT_TX_WEIGHT }
73}
74
75#[derive(PartialEq, Eq)]
77pub enum HTLCClaim {
78 OfferedTimeout,
80 OfferedPreimage,
82 AcceptedTimeout,
84 AcceptedPreimage,
86 Revocation,
88}
89
90impl HTLCClaim {
91 pub fn from_witness(witness: &Witness) -> Option<Self> {
93 debug_assert_eq!(OFFERED_HTLC_SCRIPT_WEIGHT_ANCHORS, MIN_ACCEPTED_HTLC_SCRIPT_WEIGHT);
94 if witness.len() < 2 {
95 return None;
96 }
97 let witness_script = witness.last().unwrap();
98 let second_to_last = witness.second_to_last().unwrap();
99 if witness_script.len() == OFFERED_HTLC_SCRIPT_WEIGHT {
100 if witness.len() == 3 && second_to_last.len() == 33 {
101 Some(Self::Revocation)
103 } else if witness.len() == 3 && second_to_last.len() == 32 {
104 Some(Self::OfferedPreimage)
106 } else if witness.len() == 5 && second_to_last.len() == 0 {
107 Some(Self::OfferedTimeout)
109 } else {
110 None
111 }
112 } else if witness_script.len() == OFFERED_HTLC_SCRIPT_WEIGHT_ANCHORS {
113 if witness.len() == 3 && second_to_last.len() == 33 {
116 Some(Self::Revocation)
118 } else if witness.len() == 3 && second_to_last.len() == 32 {
119 Some(Self::OfferedPreimage)
121 } else if witness.len() == 5 && second_to_last.len() == 0 {
122 Some(Self::OfferedTimeout)
124 } else if witness.len() == 3 && second_to_last.len() == 0 {
125 Some(Self::AcceptedTimeout)
127 } else if witness.len() == 5 && second_to_last.len() == 32 {
128 Some(Self::AcceptedPreimage)
130 } else {
131 None
132 }
133 } else if witness_script.len() > MIN_ACCEPTED_HTLC_SCRIPT_WEIGHT &&
134 witness_script.len() <= MAX_ACCEPTED_HTLC_SCRIPT_WEIGHT {
135 if witness.len() == 3 && second_to_last.len() == 33 {
137 Some(Self::Revocation)
139 } else if witness.len() == 3 && second_to_last.len() == 0 {
140 Some(Self::AcceptedTimeout)
142 } else if witness.len() == 5 && second_to_last.len() == 32 {
143 Some(Self::AcceptedPreimage)
145 } else {
146 None
147 }
148 } else {
149 None
150 }
151 }
152}
153
154pub fn build_commitment_secret(commitment_seed: &[u8; 32], idx: u64) -> [u8; 32] {
159 let mut res: [u8; 32] = commitment_seed.clone();
160 for i in 0..48 {
161 let bitpos = 47 - i;
162 if idx & (1 << bitpos) == (1 << bitpos) {
163 res[bitpos / 8] ^= 1 << (bitpos & 7);
164 res = Sha256::hash(&res).into_inner();
165 }
166 }
167 res
168}
169
170pub 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 {
172 let txins = {
173 let mut ins: Vec<TxIn> = Vec::new();
174 ins.push(TxIn {
175 previous_output: funding_outpoint,
176 script_sig: Script::new(),
177 sequence: Sequence::MAX,
178 witness: Witness::new(),
179 });
180 ins
181 };
182
183 let mut txouts: Vec<(TxOut, ())> = Vec::new();
184
185 if to_counterparty_value_sat > 0 {
186 txouts.push((TxOut {
187 script_pubkey: to_counterparty_script,
188 value: to_counterparty_value_sat
189 }, ()));
190 }
191
192 if to_holder_value_sat > 0 {
193 txouts.push((TxOut {
194 script_pubkey: to_holder_script,
195 value: to_holder_value_sat
196 }, ()));
197 }
198
199 transaction_utils::sort_outputs(&mut txouts, |_, _| { cmp::Ordering::Equal }); let mut outputs: Vec<TxOut> = Vec::new();
202 for out in txouts.drain(..) {
203 outputs.push(out.0);
204 }
205
206 Transaction {
207 version: 2,
208 lock_time: PackedLockTime::ZERO,
209 input: txins,
210 output: outputs,
211 }
212}
213
214#[derive(Clone)]
220pub struct CounterpartyCommitmentSecrets {
221 old_secrets: [([u8; 32], u64); 49],
222}
223
224impl Eq for CounterpartyCommitmentSecrets {}
225impl PartialEq for CounterpartyCommitmentSecrets {
226 fn eq(&self, other: &Self) -> bool {
227 for (&(ref secret, ref idx), &(ref o_secret, ref o_idx)) in self.old_secrets.iter().zip(other.old_secrets.iter()) {
228 if secret != o_secret || idx != o_idx {
229 return false
230 }
231 }
232 true
233 }
234}
235
236impl CounterpartyCommitmentSecrets {
237 pub fn new() -> Self {
239 Self { old_secrets: [([0; 32], 1 << 48); 49], }
240 }
241
242 #[inline]
243 fn place_secret(idx: u64) -> u8 {
244 for i in 0..48 {
245 if idx & (1 << i) == (1 << i) {
246 return i
247 }
248 }
249 48
250 }
251
252 pub fn get_min_seen_secret(&self) -> u64 {
255 let mut min = 1 << 48;
257 for &(_, idx) in self.old_secrets.iter() {
258 if idx < min {
259 min = idx;
260 }
261 }
262 min
263 }
264
265 #[inline]
266 fn derive_secret(secret: [u8; 32], bits: u8, idx: u64) -> [u8; 32] {
267 let mut res: [u8; 32] = secret;
268 for i in 0..bits {
269 let bitpos = bits - 1 - i;
270 if idx & (1 << bitpos) == (1 << bitpos) {
271 res[(bitpos / 8) as usize] ^= 1 << (bitpos & 7);
272 res = Sha256::hash(&res).into_inner();
273 }
274 }
275 res
276 }
277
278 pub fn provide_secret(&mut self, idx: u64, secret: [u8; 32]) -> Result<(), ()> {
281 let pos = Self::place_secret(idx);
282 for i in 0..pos {
283 let (old_secret, old_idx) = self.old_secrets[i as usize];
284 if Self::derive_secret(secret, pos, old_idx) != old_secret {
285 return Err(());
286 }
287 }
288 if self.get_min_seen_secret() <= idx {
289 return Ok(());
290 }
291 self.old_secrets[pos as usize] = (secret, idx);
292 Ok(())
293 }
294
295 pub fn get_secret(&self, idx: u64) -> Option<[u8; 32]> {
298 for i in 0..self.old_secrets.len() {
299 if (idx & (!((1 << i) - 1))) == self.old_secrets[i].1 {
300 return Some(Self::derive_secret(self.old_secrets[i].0, i as u8, idx))
301 }
302 }
303 assert!(idx < self.get_min_seen_secret());
304 None
305 }
306}
307
308impl Writeable for CounterpartyCommitmentSecrets {
309 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
310 for &(ref secret, ref idx) in self.old_secrets.iter() {
311 writer.write_all(secret)?;
312 writer.write_all(&idx.to_be_bytes())?;
313 }
314 write_tlv_fields!(writer, {});
315 Ok(())
316 }
317}
318impl Readable for CounterpartyCommitmentSecrets {
319 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
320 let mut old_secrets = [([0; 32], 1 << 48); 49];
321 for &mut (ref mut secret, ref mut idx) in old_secrets.iter_mut() {
322 *secret = Readable::read(reader)?;
323 *idx = Readable::read(reader)?;
324 }
325 read_tlv_fields!(reader, {});
326 Ok(Self { old_secrets })
327 }
328}
329
330pub fn derive_private_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, base_secret: &SecretKey) -> SecretKey {
333 let mut sha = Sha256::engine();
334 sha.input(&per_commitment_point.serialize());
335 sha.input(&PublicKey::from_secret_key(&secp_ctx, &base_secret).serialize());
336 let res = Sha256::from_engine(sha).into_inner();
337
338 base_secret.clone().add_tweak(&Scalar::from_be_bytes(res).unwrap())
339 .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.")
340}
341
342pub fn derive_public_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, base_point: &PublicKey) -> PublicKey {
346 let mut sha = Sha256::engine();
347 sha.input(&per_commitment_point.serialize());
348 sha.input(&base_point.serialize());
349 let res = Sha256::from_engine(sha).into_inner();
350
351 let hashkey = PublicKey::from_secret_key(&secp_ctx,
352 &SecretKey::from_slice(&res).expect("Hashes should always be valid keys unless SHA-256 is broken"));
353 base_point.combine(&hashkey)
354 .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.")
355}
356
357pub fn derive_private_revocation_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>,
364 per_commitment_secret: &SecretKey, countersignatory_revocation_base_secret: &SecretKey)
365-> SecretKey {
366 let countersignatory_revocation_base_point = PublicKey::from_secret_key(&secp_ctx, &countersignatory_revocation_base_secret);
367 let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &per_commitment_secret);
368
369 let rev_append_commit_hash_key = {
370 let mut sha = Sha256::engine();
371 sha.input(&countersignatory_revocation_base_point.serialize());
372 sha.input(&per_commitment_point.serialize());
373
374 Sha256::from_engine(sha).into_inner()
375 };
376 let commit_append_rev_hash_key = {
377 let mut sha = Sha256::engine();
378 sha.input(&per_commitment_point.serialize());
379 sha.input(&countersignatory_revocation_base_point.serialize());
380
381 Sha256::from_engine(sha).into_inner()
382 };
383
384 let countersignatory_contrib = countersignatory_revocation_base_secret.clone().mul_tweak(&Scalar::from_be_bytes(rev_append_commit_hash_key).unwrap())
385 .expect("Multiplying a secret key by a hash is expected to never fail per secp256k1 docs");
386 let broadcaster_contrib = per_commitment_secret.clone().mul_tweak(&Scalar::from_be_bytes(commit_append_rev_hash_key).unwrap())
387 .expect("Multiplying a secret key by a hash is expected to never fail per secp256k1 docs");
388 countersignatory_contrib.add_tweak(&Scalar::from_be_bytes(broadcaster_contrib.secret_bytes()).unwrap())
389 .expect("Addition only fails if the tweak is the inverse of the key. This is not possible when the tweak commits to the key.")
390}
391
392pub fn derive_public_revocation_key<T: secp256k1::Verification>(secp_ctx: &Secp256k1<T>,
404 per_commitment_point: &PublicKey, countersignatory_revocation_base_point: &PublicKey)
405-> PublicKey {
406 let rev_append_commit_hash_key = {
407 let mut sha = Sha256::engine();
408 sha.input(&countersignatory_revocation_base_point.serialize());
409 sha.input(&per_commitment_point.serialize());
410
411 Sha256::from_engine(sha).into_inner()
412 };
413 let commit_append_rev_hash_key = {
414 let mut sha = Sha256::engine();
415 sha.input(&per_commitment_point.serialize());
416 sha.input(&countersignatory_revocation_base_point.serialize());
417
418 Sha256::from_engine(sha).into_inner()
419 };
420
421 let countersignatory_contrib = countersignatory_revocation_base_point.clone().mul_tweak(&secp_ctx, &Scalar::from_be_bytes(rev_append_commit_hash_key).unwrap())
422 .expect("Multiplying a valid public key by a hash is expected to never fail per secp256k1 docs");
423 let broadcaster_contrib = per_commitment_point.clone().mul_tweak(&secp_ctx, &Scalar::from_be_bytes(commit_append_rev_hash_key).unwrap())
424 .expect("Multiplying a valid public key by a hash is expected to never fail per secp256k1 docs");
425 countersignatory_contrib.combine(&broadcaster_contrib)
426 .expect("Addition only fails if the tweak is the inverse of the key. This is not possible when the tweak commits to the key.")
427}
428
429#[derive(PartialEq, Eq, Clone)]
441pub struct TxCreationKeys {
442 pub per_commitment_point: PublicKey,
444 pub revocation_key: PublicKey,
448 pub broadcaster_htlc_key: PublicKey,
450 pub countersignatory_htlc_key: PublicKey,
452 pub broadcaster_delayed_payment_key: PublicKey,
454}
455
456impl_writeable_tlv_based!(TxCreationKeys, {
457 (0, per_commitment_point, required),
458 (2, revocation_key, required),
459 (4, broadcaster_htlc_key, required),
460 (6, countersignatory_htlc_key, required),
461 (8, broadcaster_delayed_payment_key, required),
462});
463
464#[derive(Clone, Debug, PartialEq, Eq)]
466pub struct ChannelPublicKeys {
467 pub funding_pubkey: PublicKey,
470 pub revocation_basepoint: PublicKey,
475 pub payment_point: PublicKey,
479 pub delayed_payment_basepoint: PublicKey,
483 pub htlc_basepoint: PublicKey,
486}
487
488impl_writeable_tlv_based!(ChannelPublicKeys, {
489 (0, funding_pubkey, required),
490 (2, revocation_basepoint, required),
491 (4, payment_point, required),
492 (6, delayed_payment_basepoint, required),
493 (8, htlc_basepoint, required),
494});
495
496impl TxCreationKeys {
497 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 {
500 TxCreationKeys {
501 per_commitment_point: per_commitment_point.clone(),
502 revocation_key: derive_public_revocation_key(&secp_ctx, &per_commitment_point, &countersignatory_revocation_base),
503 broadcaster_htlc_key: derive_public_key(&secp_ctx, &per_commitment_point, &broadcaster_htlc_base),
504 countersignatory_htlc_key: derive_public_key(&secp_ctx, &per_commitment_point, &countersignatory_htlc_base),
505 broadcaster_delayed_payment_key: derive_public_key(&secp_ctx, &per_commitment_point, &broadcaster_delayed_payment_base),
506 }
507 }
508
509 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 {
512 TxCreationKeys::derive_new(
513 &secp_ctx,
514 &per_commitment_point,
515 &broadcaster_keys.delayed_payment_basepoint,
516 &broadcaster_keys.htlc_basepoint,
517 &countersignatory_keys.revocation_basepoint,
518 &countersignatory_keys.htlc_basepoint,
519 )
520 }
521}
522
523pub const REVOKEABLE_REDEEMSCRIPT_MAX_LENGTH: usize = 6 + 3 + 34*2;
527
528pub fn get_revokeable_redeemscript(revocation_key: &PublicKey, contest_delay: u16, broadcaster_delayed_payment_key: &PublicKey) -> Script {
532 let res = Builder::new().push_opcode(opcodes::all::OP_IF)
533 .push_slice(&revocation_key.serialize())
534 .push_opcode(opcodes::all::OP_ELSE)
535 .push_int(contest_delay as i64)
536 .push_opcode(opcodes::all::OP_CSV)
537 .push_opcode(opcodes::all::OP_DROP)
538 .push_slice(&broadcaster_delayed_payment_key.serialize())
539 .push_opcode(opcodes::all::OP_ENDIF)
540 .push_opcode(opcodes::all::OP_CHECKSIG)
541 .into_script();
542 debug_assert!(res.len() <= REVOKEABLE_REDEEMSCRIPT_MAX_LENGTH);
543 res
544}
545
546#[derive(Clone, Debug, PartialEq, Eq)]
548pub struct HTLCOutputInCommitment {
549 pub offered: bool,
554 pub amount_msat: u64,
557 pub cltv_expiry: u32,
559 pub payment_hash: PaymentHash,
561 pub transaction_output_index: Option<u32>,
565}
566
567impl_writeable_tlv_based!(HTLCOutputInCommitment, {
568 (0, offered, required),
569 (2, amount_msat, required),
570 (4, cltv_expiry, required),
571 (6, payment_hash, required),
572 (8, transaction_output_index, option),
573});
574
575#[inline]
576pub(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 {
577 let payment_hash160 = Ripemd160::hash(&htlc.payment_hash.0[..]).into_inner();
578 if htlc.offered {
579 let mut bldr = Builder::new().push_opcode(opcodes::all::OP_DUP)
580 .push_opcode(opcodes::all::OP_HASH160)
581 .push_slice(&PubkeyHash::hash(&revocation_key.serialize())[..])
582 .push_opcode(opcodes::all::OP_EQUAL)
583 .push_opcode(opcodes::all::OP_IF)
584 .push_opcode(opcodes::all::OP_CHECKSIG)
585 .push_opcode(opcodes::all::OP_ELSE)
586 .push_slice(&countersignatory_htlc_key.serialize()[..])
587 .push_opcode(opcodes::all::OP_SWAP)
588 .push_opcode(opcodes::all::OP_SIZE)
589 .push_int(32)
590 .push_opcode(opcodes::all::OP_EQUAL)
591 .push_opcode(opcodes::all::OP_NOTIF)
592 .push_opcode(opcodes::all::OP_DROP)
593 .push_int(2)
594 .push_opcode(opcodes::all::OP_SWAP)
595 .push_slice(&broadcaster_htlc_key.serialize()[..])
596 .push_int(2)
597 .push_opcode(opcodes::all::OP_CHECKMULTISIG)
598 .push_opcode(opcodes::all::OP_ELSE)
599 .push_opcode(opcodes::all::OP_HASH160)
600 .push_slice(&payment_hash160)
601 .push_opcode(opcodes::all::OP_EQUALVERIFY)
602 .push_opcode(opcodes::all::OP_CHECKSIG)
603 .push_opcode(opcodes::all::OP_ENDIF);
604 if opt_anchors {
605 bldr = bldr.push_opcode(opcodes::all::OP_PUSHNUM_1)
606 .push_opcode(opcodes::all::OP_CSV)
607 .push_opcode(opcodes::all::OP_DROP);
608 }
609 bldr.push_opcode(opcodes::all::OP_ENDIF)
610 .into_script()
611 } else {
612 let mut bldr = Builder::new().push_opcode(opcodes::all::OP_DUP)
613 .push_opcode(opcodes::all::OP_HASH160)
614 .push_slice(&PubkeyHash::hash(&revocation_key.serialize())[..])
615 .push_opcode(opcodes::all::OP_EQUAL)
616 .push_opcode(opcodes::all::OP_IF)
617 .push_opcode(opcodes::all::OP_CHECKSIG)
618 .push_opcode(opcodes::all::OP_ELSE)
619 .push_slice(&countersignatory_htlc_key.serialize()[..])
620 .push_opcode(opcodes::all::OP_SWAP)
621 .push_opcode(opcodes::all::OP_SIZE)
622 .push_int(32)
623 .push_opcode(opcodes::all::OP_EQUAL)
624 .push_opcode(opcodes::all::OP_IF)
625 .push_opcode(opcodes::all::OP_HASH160)
626 .push_slice(&payment_hash160)
627 .push_opcode(opcodes::all::OP_EQUALVERIFY)
628 .push_int(2)
629 .push_opcode(opcodes::all::OP_SWAP)
630 .push_slice(&broadcaster_htlc_key.serialize()[..])
631 .push_int(2)
632 .push_opcode(opcodes::all::OP_CHECKMULTISIG)
633 .push_opcode(opcodes::all::OP_ELSE)
634 .push_opcode(opcodes::all::OP_DROP)
635 .push_int(htlc.cltv_expiry as i64)
636 .push_opcode(opcodes::all::OP_CLTV)
637 .push_opcode(opcodes::all::OP_DROP)
638 .push_opcode(opcodes::all::OP_CHECKSIG)
639 .push_opcode(opcodes::all::OP_ENDIF);
640 if opt_anchors {
641 bldr = bldr.push_opcode(opcodes::all::OP_PUSHNUM_1)
642 .push_opcode(opcodes::all::OP_CSV)
643 .push_opcode(opcodes::all::OP_DROP);
644 }
645 bldr.push_opcode(opcodes::all::OP_ENDIF)
646 .into_script()
647 }
648}
649
650#[inline]
653pub fn get_htlc_redeemscript(htlc: &HTLCOutputInCommitment, opt_anchors: bool, keys: &TxCreationKeys) -> Script {
654 get_htlc_redeemscript_with_explicit_keys(htlc, opt_anchors, &keys.broadcaster_htlc_key, &keys.countersignatory_htlc_key, &keys.revocation_key)
655}
656
657pub fn make_funding_redeemscript(broadcaster: &PublicKey, countersignatory: &PublicKey) -> Script {
660 let broadcaster_funding_key = broadcaster.serialize();
661 let countersignatory_funding_key = countersignatory.serialize();
662
663 let builder = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2);
664 if broadcaster_funding_key[..] < countersignatory_funding_key[..] {
665 builder.push_slice(&broadcaster_funding_key)
666 .push_slice(&countersignatory_funding_key)
667 } else {
668 builder.push_slice(&countersignatory_funding_key)
669 .push_slice(&broadcaster_funding_key)
670 }.push_opcode(opcodes::all::OP_PUSHNUM_2).push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script()
671}
672
673pub 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 {
681 let mut txins: Vec<TxIn> = Vec::new();
682 txins.push(build_htlc_input(commitment_txid, htlc, opt_anchors));
683
684 let mut txouts: Vec<TxOut> = Vec::new();
685 txouts.push(build_htlc_output(
686 feerate_per_kw, contest_delay, htlc, opt_anchors, use_non_zero_fee_anchors,
687 broadcaster_delayed_payment_key, revocation_key
688 ));
689
690 Transaction {
691 version: 2,
692 lock_time: PackedLockTime(if htlc.offered { htlc.cltv_expiry } else { 0 }),
693 input: txins,
694 output: txouts,
695 }
696}
697
698pub(crate) fn build_htlc_input(commitment_txid: &Txid, htlc: &HTLCOutputInCommitment, opt_anchors: bool) -> TxIn {
699 TxIn {
700 previous_output: OutPoint {
701 txid: commitment_txid.clone(),
702 vout: htlc.transaction_output_index.expect("Can't build an HTLC transaction for a dust output"),
703 },
704 script_sig: Script::new(),
705 sequence: Sequence(if opt_anchors { 1 } else { 0 }),
706 witness: Witness::new(),
707 }
708}
709
710pub(crate) fn build_htlc_output(
711 feerate_per_kw: u32, contest_delay: u16, htlc: &HTLCOutputInCommitment, opt_anchors: bool,
712 use_non_zero_fee_anchors: bool, broadcaster_delayed_payment_key: &PublicKey, revocation_key: &PublicKey
713) -> TxOut {
714 let weight = if htlc.offered {
715 htlc_timeout_tx_weight(opt_anchors)
716 } else {
717 htlc_success_tx_weight(opt_anchors)
718 };
719 let output_value = if opt_anchors && !use_non_zero_fee_anchors {
720 htlc.amount_msat / 1000
721 } else {
722 let total_fee = feerate_per_kw as u64 * weight / 1000;
723 htlc.amount_msat / 1000 - total_fee
724 };
725
726 TxOut {
727 script_pubkey: get_revokeable_redeemscript(revocation_key, contest_delay, broadcaster_delayed_payment_key).to_v0_p2wsh(),
728 value: output_value,
729 }
730}
731
732pub fn build_htlc_input_witness(
734 local_sig: &Signature, remote_sig: &Signature, preimage: &Option<PaymentPreimage>,
735 redeem_script: &Script, opt_anchors: bool,
736) -> Witness {
737 let remote_sighash_type = if opt_anchors {
738 EcdsaSighashType::SinglePlusAnyoneCanPay
739 } else {
740 EcdsaSighashType::All
741 };
742
743 let mut witness = Witness::new();
744 witness.push(vec![]);
746 witness.push_bitcoin_signature(&remote_sig.serialize_der(), remote_sighash_type);
747 witness.push_bitcoin_signature(&local_sig.serialize_der(), EcdsaSighashType::All);
748 if let Some(preimage) = preimage {
749 witness.push(preimage.0.to_vec());
750 } else {
751 witness.push(vec![]);
753 }
754 witness.push(redeem_script.to_bytes());
755 witness
756}
757
758#[inline]
760pub fn get_to_countersignatory_with_anchors_redeemscript(payment_point: &PublicKey) -> Script {
761 Builder::new()
762 .push_slice(&payment_point.serialize()[..])
763 .push_opcode(opcodes::all::OP_CHECKSIGVERIFY)
764 .push_int(1)
765 .push_opcode(opcodes::all::OP_CSV)
766 .into_script()
767}
768
769#[inline]
776pub fn get_anchor_redeemscript(funding_pubkey: &PublicKey) -> Script {
777 Builder::new().push_slice(&funding_pubkey.serialize()[..])
778 .push_opcode(opcodes::all::OP_CHECKSIG)
779 .push_opcode(opcodes::all::OP_IFDUP)
780 .push_opcode(opcodes::all::OP_NOTIF)
781 .push_int(16)
782 .push_opcode(opcodes::all::OP_CSV)
783 .push_opcode(opcodes::all::OP_ENDIF)
784 .into_script()
785}
786
787#[cfg(anchors)]
788pub(crate) fn get_anchor_output<'a>(commitment_tx: &'a Transaction, funding_pubkey: &PublicKey) -> Option<(u32, &'a TxOut)> {
790 let anchor_script = chan_utils::get_anchor_redeemscript(funding_pubkey).to_v0_p2wsh();
791 commitment_tx.output.iter().enumerate()
792 .find(|(_, txout)| txout.script_pubkey == anchor_script)
793 .map(|(idx, txout)| (idx as u32, txout))
794}
795
796pub fn build_anchor_input_witness(funding_key: &PublicKey, funding_sig: &Signature) -> Witness {
798 let anchor_redeem_script = chan_utils::get_anchor_redeemscript(funding_key);
799 let mut ret = Witness::new();
800 ret.push_bitcoin_signature(&funding_sig.serialize_der(), EcdsaSighashType::All);
801 ret.push(anchor_redeem_script.as_bytes());
802 ret
803}
804
805#[derive(Clone, Debug, PartialEq)]
811pub struct ChannelTransactionParameters {
812 pub holder_pubkeys: ChannelPublicKeys,
814 pub holder_selected_contest_delay: u16,
816 pub is_outbound_from_holder: bool,
819 pub counterparty_parameters: Option<CounterpartyChannelTransactionParameters>,
822 pub funding_outpoint: Option<chain::transaction::OutPoint>,
824 pub opt_anchors: Option<()>,
827 pub opt_non_zero_fee_anchors: Option<()>,
831}
832
833#[derive(Clone, Debug, PartialEq)]
835pub struct CounterpartyChannelTransactionParameters {
836 pub pubkeys: ChannelPublicKeys,
838 pub selected_contest_delay: u16,
840}
841
842impl ChannelTransactionParameters {
843 pub fn is_populated(&self) -> bool {
845 self.counterparty_parameters.is_some() && self.funding_outpoint.is_some()
846 }
847
848 pub fn as_holder_broadcastable(&self) -> DirectedChannelTransactionParameters {
853 assert!(self.is_populated(), "self.late_parameters must be set before using as_holder_broadcastable");
854 DirectedChannelTransactionParameters {
855 inner: self,
856 holder_is_broadcaster: true
857 }
858 }
859
860 pub fn as_counterparty_broadcastable(&self) -> DirectedChannelTransactionParameters {
865 assert!(self.is_populated(), "self.late_parameters must be set before using as_counterparty_broadcastable");
866 DirectedChannelTransactionParameters {
867 inner: self,
868 holder_is_broadcaster: false
869 }
870 }
871}
872
873impl_writeable_tlv_based!(CounterpartyChannelTransactionParameters, {
874 (0, pubkeys, required),
875 (2, selected_contest_delay, required),
876});
877
878impl_writeable_tlv_based!(ChannelTransactionParameters, {
879 (0, holder_pubkeys, required),
880 (2, holder_selected_contest_delay, required),
881 (4, is_outbound_from_holder, required),
882 (6, counterparty_parameters, option),
883 (8, funding_outpoint, option),
884 (10, opt_anchors, option),
885 (12, opt_non_zero_fee_anchors, option),
886});
887
888pub struct DirectedChannelTransactionParameters<'a> {
894 inner: &'a ChannelTransactionParameters,
896 holder_is_broadcaster: bool,
898}
899
900impl<'a> DirectedChannelTransactionParameters<'a> {
901 pub fn broadcaster_pubkeys(&self) -> &ChannelPublicKeys {
903 if self.holder_is_broadcaster {
904 &self.inner.holder_pubkeys
905 } else {
906 &self.inner.counterparty_parameters.as_ref().unwrap().pubkeys
907 }
908 }
909
910 pub fn countersignatory_pubkeys(&self) -> &ChannelPublicKeys {
912 if self.holder_is_broadcaster {
913 &self.inner.counterparty_parameters.as_ref().unwrap().pubkeys
914 } else {
915 &self.inner.holder_pubkeys
916 }
917 }
918
919 pub fn contest_delay(&self) -> u16 {
922 let counterparty_parameters = self.inner.counterparty_parameters.as_ref().unwrap();
923 if self.holder_is_broadcaster { counterparty_parameters.selected_contest_delay } else { self.inner.holder_selected_contest_delay }
924 }
925
926 pub fn is_outbound(&self) -> bool {
931 if self.holder_is_broadcaster { self.inner.is_outbound_from_holder } else { !self.inner.is_outbound_from_holder }
932 }
933
934 pub fn funding_outpoint(&self) -> OutPoint {
936 self.inner.funding_outpoint.unwrap().into_bitcoin_outpoint()
937 }
938
939 pub fn opt_anchors(&self) -> bool {
941 self.inner.opt_anchors.is_some()
942 }
943}
944
945#[derive(Clone)]
949pub struct HolderCommitmentTransaction {
950 inner: CommitmentTransaction,
951 pub counterparty_sig: Signature,
953 pub counterparty_htlc_sigs: Vec<Signature>,
955 holder_sig_first: bool,
958}
959
960impl Deref for HolderCommitmentTransaction {
961 type Target = CommitmentTransaction;
962
963 fn deref(&self) -> &Self::Target { &self.inner }
964}
965
966impl Eq for HolderCommitmentTransaction {}
967impl PartialEq for HolderCommitmentTransaction {
968 fn eq(&self, o: &Self) -> bool {
970 self.inner == o.inner
971 }
972}
973
974impl_writeable_tlv_based!(HolderCommitmentTransaction, {
975 (0, inner, required),
976 (2, counterparty_sig, required),
977 (4, holder_sig_first, required),
978 (6, counterparty_htlc_sigs, vec_type),
979});
980
981impl HolderCommitmentTransaction {
982 #[cfg(test)]
983 pub fn dummy() -> Self {
984 let secp_ctx = Secp256k1::new();
985 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
986 let dummy_sig = sign(&secp_ctx, &secp256k1::Message::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[42; 32]).unwrap());
987
988 let keys = TxCreationKeys {
989 per_commitment_point: dummy_key.clone(),
990 revocation_key: dummy_key.clone(),
991 broadcaster_htlc_key: dummy_key.clone(),
992 countersignatory_htlc_key: dummy_key.clone(),
993 broadcaster_delayed_payment_key: dummy_key.clone(),
994 };
995 let channel_pubkeys = ChannelPublicKeys {
996 funding_pubkey: dummy_key.clone(),
997 revocation_basepoint: dummy_key.clone(),
998 payment_point: dummy_key.clone(),
999 delayed_payment_basepoint: dummy_key.clone(),
1000 htlc_basepoint: dummy_key.clone()
1001 };
1002 let channel_parameters = ChannelTransactionParameters {
1003 holder_pubkeys: channel_pubkeys.clone(),
1004 holder_selected_contest_delay: 0,
1005 is_outbound_from_holder: false,
1006 counterparty_parameters: Some(CounterpartyChannelTransactionParameters { pubkeys: channel_pubkeys.clone(), selected_contest_delay: 0 }),
1007 funding_outpoint: Some(chain::transaction::OutPoint { txid: Txid::all_zeros(), index: 0 }),
1008 opt_anchors: None,
1009 opt_non_zero_fee_anchors: None,
1010 };
1011 let mut htlcs_with_aux: Vec<(_, ())> = Vec::new();
1012 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());
1013 HolderCommitmentTransaction {
1014 inner,
1015 counterparty_sig: dummy_sig,
1016 counterparty_htlc_sigs: Vec::new(),
1017 holder_sig_first: false
1018 }
1019 }
1020
1021 pub fn new(commitment_tx: CommitmentTransaction, counterparty_sig: Signature, counterparty_htlc_sigs: Vec<Signature>, holder_funding_key: &PublicKey, counterparty_funding_key: &PublicKey) -> Self {
1024 Self {
1025 inner: commitment_tx,
1026 counterparty_sig,
1027 counterparty_htlc_sigs,
1028 holder_sig_first: holder_funding_key.serialize()[..] < counterparty_funding_key.serialize()[..],
1029 }
1030 }
1031
1032 pub(crate) fn add_holder_sig(&self, funding_redeemscript: &Script, holder_sig: Signature) -> Transaction {
1033 let mut tx = self.inner.built.transaction.clone();
1035 tx.input[0].witness.push(Vec::new());
1036
1037 if self.holder_sig_first {
1038 tx.input[0].witness.push_bitcoin_signature(&holder_sig.serialize_der(), EcdsaSighashType::All);
1039 tx.input[0].witness.push_bitcoin_signature(&self.counterparty_sig.serialize_der(), EcdsaSighashType::All);
1040 } else {
1041 tx.input[0].witness.push_bitcoin_signature(&self.counterparty_sig.serialize_der(), EcdsaSighashType::All);
1042 tx.input[0].witness.push_bitcoin_signature(&holder_sig.serialize_der(), EcdsaSighashType::All);
1043 }
1044
1045 tx.input[0].witness.push(funding_redeemscript.as_bytes().to_vec());
1046 tx
1047 }
1048}
1049
1050#[derive(Clone)]
1052pub struct BuiltCommitmentTransaction {
1053 pub transaction: Transaction,
1055 pub txid: Txid,
1060}
1061
1062impl_writeable_tlv_based!(BuiltCommitmentTransaction, {
1063 (0, transaction, required),
1064 (2, txid, required),
1065});
1066
1067impl BuiltCommitmentTransaction {
1068 pub fn get_sighash_all(&self, funding_redeemscript: &Script, channel_value_satoshis: u64) -> Message {
1072 let sighash = &sighash::SighashCache::new(&self.transaction).segwit_signature_hash(0, funding_redeemscript, channel_value_satoshis, EcdsaSighashType::All).unwrap()[..];
1073 hash_to_message!(sighash)
1074 }
1075
1076 pub fn sign<T: secp256k1::Signing>(&self, funding_key: &SecretKey, funding_redeemscript: &Script, channel_value_satoshis: u64, secp_ctx: &Secp256k1<T>) -> Signature {
1079 let sighash = self.get_sighash_all(funding_redeemscript, channel_value_satoshis);
1080 sign(secp_ctx, &sighash, funding_key)
1081 }
1082}
1083
1084#[derive(Clone, Hash, PartialEq, Eq)]
1090pub struct ClosingTransaction {
1091 to_holder_value_sat: u64,
1092 to_counterparty_value_sat: u64,
1093 to_holder_script: Script,
1094 to_counterparty_script: Script,
1095 built: Transaction,
1096}
1097
1098impl ClosingTransaction {
1099 pub fn new(
1101 to_holder_value_sat: u64,
1102 to_counterparty_value_sat: u64,
1103 to_holder_script: Script,
1104 to_counterparty_script: Script,
1105 funding_outpoint: OutPoint,
1106 ) -> Self {
1107 let built = build_closing_transaction(
1108 to_holder_value_sat, to_counterparty_value_sat,
1109 to_holder_script.clone(), to_counterparty_script.clone(),
1110 funding_outpoint
1111 );
1112 ClosingTransaction {
1113 to_holder_value_sat,
1114 to_counterparty_value_sat,
1115 to_holder_script,
1116 to_counterparty_script,
1117 built
1118 }
1119 }
1120
1121 pub fn trust(&self) -> TrustedClosingTransaction {
1128 TrustedClosingTransaction { inner: self }
1129 }
1130
1131 pub fn verify(&self, funding_outpoint: OutPoint) -> Result<TrustedClosingTransaction, ()> {
1138 let built = build_closing_transaction(
1139 self.to_holder_value_sat, self.to_counterparty_value_sat,
1140 self.to_holder_script.clone(), self.to_counterparty_script.clone(),
1141 funding_outpoint
1142 );
1143 if self.built != built {
1144 return Err(())
1145 }
1146 Ok(TrustedClosingTransaction { inner: self })
1147 }
1148
1149 pub fn to_holder_value_sat(&self) -> u64 {
1151 self.to_holder_value_sat
1152 }
1153
1154 pub fn to_counterparty_value_sat(&self) -> u64 {
1156 self.to_counterparty_value_sat
1157 }
1158
1159 pub fn to_holder_script(&self) -> &Script {
1161 &self.to_holder_script
1162 }
1163
1164 pub fn to_counterparty_script(&self) -> &Script {
1166 &self.to_counterparty_script
1167 }
1168}
1169
1170pub struct TrustedClosingTransaction<'a> {
1177 inner: &'a ClosingTransaction,
1178}
1179
1180impl<'a> Deref for TrustedClosingTransaction<'a> {
1181 type Target = ClosingTransaction;
1182
1183 fn deref(&self) -> &Self::Target { self.inner }
1184}
1185
1186impl<'a> TrustedClosingTransaction<'a> {
1187 pub fn built_transaction(&self) -> &Transaction {
1189 &self.inner.built
1190 }
1191
1192 pub fn get_sighash_all(&self, funding_redeemscript: &Script, channel_value_satoshis: u64) -> Message {
1196 let sighash = &sighash::SighashCache::new(&self.inner.built).segwit_signature_hash(0, funding_redeemscript, channel_value_satoshis, EcdsaSighashType::All).unwrap()[..];
1197 hash_to_message!(sighash)
1198 }
1199
1200 pub fn sign<T: secp256k1::Signing>(&self, funding_key: &SecretKey, funding_redeemscript: &Script, channel_value_satoshis: u64, secp_ctx: &Secp256k1<T>) -> Signature {
1203 let sighash = self.get_sighash_all(funding_redeemscript, channel_value_satoshis);
1204 sign(secp_ctx, &sighash, funding_key)
1205 }
1206}
1207
1208#[derive(Clone)]
1215pub struct CommitmentTransaction {
1216 commitment_number: u64,
1217 to_broadcaster_value_sat: u64,
1218 to_countersignatory_value_sat: u64,
1219 feerate_per_kw: u32,
1220 htlcs: Vec<HTLCOutputInCommitment>,
1221 opt_anchors: Option<()>,
1223 opt_non_zero_fee_anchors: Option<()>,
1225 keys: TxCreationKeys,
1227 built: BuiltCommitmentTransaction,
1229}
1230
1231impl Eq for CommitmentTransaction {}
1232impl PartialEq for CommitmentTransaction {
1233 fn eq(&self, o: &Self) -> bool {
1234 let eq = self.commitment_number == o.commitment_number &&
1235 self.to_broadcaster_value_sat == o.to_broadcaster_value_sat &&
1236 self.to_countersignatory_value_sat == o.to_countersignatory_value_sat &&
1237 self.feerate_per_kw == o.feerate_per_kw &&
1238 self.htlcs == o.htlcs &&
1239 self.opt_anchors == o.opt_anchors &&
1240 self.keys == o.keys;
1241 if eq {
1242 debug_assert_eq!(self.built.transaction, o.built.transaction);
1243 debug_assert_eq!(self.built.txid, o.built.txid);
1244 }
1245 eq
1246 }
1247}
1248
1249impl_writeable_tlv_based!(CommitmentTransaction, {
1250 (0, commitment_number, required),
1251 (2, to_broadcaster_value_sat, required),
1252 (4, to_countersignatory_value_sat, required),
1253 (6, feerate_per_kw, required),
1254 (8, keys, required),
1255 (10, built, required),
1256 (12, htlcs, vec_type),
1257 (14, opt_anchors, option),
1258 (16, opt_non_zero_fee_anchors, option),
1259});
1260
1261impl CommitmentTransaction {
1262 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 {
1273 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();
1275
1276 let (obscured_commitment_transaction_number, txins) = Self::internal_build_inputs(commitment_number, channel_parameters);
1277 let transaction = Self::make_transaction(obscured_commitment_transaction_number, txins, outputs);
1278 let txid = transaction.txid();
1279 CommitmentTransaction {
1280 commitment_number,
1281 to_broadcaster_value_sat,
1282 to_countersignatory_value_sat,
1283 feerate_per_kw,
1284 htlcs,
1285 opt_anchors: if opt_anchors { Some(()) } else { None },
1286 keys,
1287 built: BuiltCommitmentTransaction {
1288 transaction,
1289 txid
1290 },
1291 opt_non_zero_fee_anchors: None,
1292 }
1293 }
1294
1295 pub fn with_non_zero_fee_anchors(mut self) -> Self {
1299 self.opt_non_zero_fee_anchors = Some(());
1300 self
1301 }
1302
1303 fn internal_rebuild_transaction(&self, keys: &TxCreationKeys, channel_parameters: &DirectedChannelTransactionParameters, broadcaster_funding_key: &PublicKey, countersignatory_funding_key: &PublicKey) -> Result<BuiltCommitmentTransaction, ()> {
1304 let (obscured_commitment_transaction_number, txins) = Self::internal_build_inputs(self.commitment_number, channel_parameters);
1305
1306 let mut htlcs_with_aux = self.htlcs.iter().map(|h| (h.clone(), ())).collect();
1307 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)?;
1308
1309 let transaction = Self::make_transaction(obscured_commitment_transaction_number, txins, outputs);
1310 let txid = transaction.txid();
1311 let built_transaction = BuiltCommitmentTransaction {
1312 transaction,
1313 txid
1314 };
1315 Ok(built_transaction)
1316 }
1317
1318 fn make_transaction(obscured_commitment_transaction_number: u64, txins: Vec<TxIn>, outputs: Vec<TxOut>) -> Transaction {
1319 Transaction {
1320 version: 2,
1321 lock_time: PackedLockTime(((0x20 as u32) << 8 * 3) | ((obscured_commitment_transaction_number & 0xffffffu64) as u32)),
1322 input: txins,
1323 output: outputs,
1324 }
1325 }
1326
1327 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>), ()> {
1332 let countersignatory_pubkeys = channel_parameters.countersignatory_pubkeys();
1333 let contest_delay = channel_parameters.contest_delay();
1334
1335 let mut txouts: Vec<(TxOut, Option<&mut HTLCOutputInCommitment>)> = Vec::new();
1336
1337 if to_countersignatory_value_sat > 0 {
1338 let script = if opt_anchors {
1339 get_to_countersignatory_with_anchors_redeemscript(&countersignatory_pubkeys.payment_point).to_v0_p2wsh()
1340 } else {
1341 Payload::p2wpkh(&BitcoinPublicKey::new(countersignatory_pubkeys.payment_point)).unwrap().script_pubkey()
1342 };
1343 txouts.push((
1344 TxOut {
1345 script_pubkey: script.clone(),
1346 value: to_countersignatory_value_sat,
1347 },
1348 None,
1349 ))
1350 }
1351
1352 if to_broadcaster_value_sat > 0 {
1353 let redeem_script = get_revokeable_redeemscript(
1354 &keys.revocation_key,
1355 contest_delay,
1356 &keys.broadcaster_delayed_payment_key,
1357 );
1358 txouts.push((
1359 TxOut {
1360 script_pubkey: redeem_script.to_v0_p2wsh(),
1361 value: to_broadcaster_value_sat,
1362 },
1363 None,
1364 ));
1365 }
1366
1367 if opt_anchors {
1368 if to_broadcaster_value_sat > 0 || !htlcs_with_aux.is_empty() {
1369 let anchor_script = get_anchor_redeemscript(broadcaster_funding_key);
1370 txouts.push((
1371 TxOut {
1372 script_pubkey: anchor_script.to_v0_p2wsh(),
1373 value: ANCHOR_OUTPUT_VALUE_SATOSHI,
1374 },
1375 None,
1376 ));
1377 }
1378
1379 if to_countersignatory_value_sat > 0 || !htlcs_with_aux.is_empty() {
1380 let anchor_script = get_anchor_redeemscript(countersignatory_funding_key);
1381 txouts.push((
1382 TxOut {
1383 script_pubkey: anchor_script.to_v0_p2wsh(),
1384 value: ANCHOR_OUTPUT_VALUE_SATOSHI,
1385 },
1386 None,
1387 ));
1388 }
1389 }
1390
1391 let mut htlcs = Vec::with_capacity(htlcs_with_aux.len());
1392 for (htlc, _) in htlcs_with_aux {
1393 let script = chan_utils::get_htlc_redeemscript(&htlc, opt_anchors, &keys);
1394 let txout = TxOut {
1395 script_pubkey: script.to_v0_p2wsh(),
1396 value: htlc.amount_msat / 1000,
1397 };
1398 txouts.push((txout, Some(htlc)));
1399 }
1400
1401 sort_outputs(&mut txouts, |a, b| {
1404 if let &Some(ref a_htlcout) = a {
1405 if let &Some(ref b_htlcout) = b {
1406 a_htlcout.cltv_expiry.cmp(&b_htlcout.cltv_expiry)
1407 .then(a_htlcout.payment_hash.0.cmp(&b_htlcout.payment_hash.0))
1411 } else { cmp::Ordering::Equal }
1414 } else { cmp::Ordering::Equal }
1415 });
1416
1417 let mut outputs = Vec::with_capacity(txouts.len());
1418 for (idx, out) in txouts.drain(..).enumerate() {
1419 if let Some(htlc) = out.1 {
1420 htlc.transaction_output_index = Some(idx as u32);
1421 htlcs.push(htlc.clone());
1422 }
1423 outputs.push(out.0);
1424 }
1425 Ok((outputs, htlcs))
1426 }
1427
1428 fn internal_build_inputs(commitment_number: u64, channel_parameters: &DirectedChannelTransactionParameters) -> (u64, Vec<TxIn>) {
1429 let broadcaster_pubkeys = channel_parameters.broadcaster_pubkeys();
1430 let countersignatory_pubkeys = channel_parameters.countersignatory_pubkeys();
1431 let commitment_transaction_number_obscure_factor = get_commitment_transaction_number_obscure_factor(
1432 &broadcaster_pubkeys.payment_point,
1433 &countersignatory_pubkeys.payment_point,
1434 channel_parameters.is_outbound(),
1435 );
1436
1437 let obscured_commitment_transaction_number =
1438 commitment_transaction_number_obscure_factor ^ (INITIAL_COMMITMENT_NUMBER - commitment_number);
1439
1440 let txins = {
1441 let mut ins: Vec<TxIn> = Vec::new();
1442 ins.push(TxIn {
1443 previous_output: channel_parameters.funding_outpoint(),
1444 script_sig: Script::new(),
1445 sequence: Sequence(((0x80 as u32) << 8 * 3)
1446 | ((obscured_commitment_transaction_number >> 3 * 8) as u32)),
1447 witness: Witness::new(),
1448 });
1449 ins
1450 };
1451 (obscured_commitment_transaction_number, txins)
1452 }
1453
1454 pub fn commitment_number(&self) -> u64 {
1456 self.commitment_number
1457 }
1458
1459 pub fn to_broadcaster_value_sat(&self) -> u64 {
1461 self.to_broadcaster_value_sat
1462 }
1463
1464 pub fn to_countersignatory_value_sat(&self) -> u64 {
1466 self.to_countersignatory_value_sat
1467 }
1468
1469 pub fn feerate_per_kw(&self) -> u32 {
1471 self.feerate_per_kw
1472 }
1473
1474 pub fn htlcs(&self) -> &Vec<HTLCOutputInCommitment> {
1481 &self.htlcs
1482 }
1483
1484 pub fn trust(&self) -> TrustedCommitmentTransaction {
1491 TrustedCommitmentTransaction { inner: self }
1492 }
1493
1494 pub fn verify<T: secp256k1::Signing + secp256k1::Verification>(&self, channel_parameters: &DirectedChannelTransactionParameters, broadcaster_keys: &ChannelPublicKeys, countersignatory_keys: &ChannelPublicKeys, secp_ctx: &Secp256k1<T>) -> Result<TrustedCommitmentTransaction, ()> {
1501 let per_commitment_point = self.keys.per_commitment_point;
1503 let keys = TxCreationKeys::from_channel_static_keys(&per_commitment_point, broadcaster_keys, countersignatory_keys, secp_ctx);
1504 if keys != self.keys {
1505 return Err(());
1506 }
1507 let tx = self.internal_rebuild_transaction(&keys, channel_parameters, &broadcaster_keys.funding_pubkey, &countersignatory_keys.funding_pubkey)?;
1508 if self.built.transaction != tx.transaction || self.built.txid != tx.txid {
1509 return Err(());
1510 }
1511 Ok(TrustedCommitmentTransaction { inner: self })
1512 }
1513}
1514
1515pub struct TrustedCommitmentTransaction<'a> {
1522 inner: &'a CommitmentTransaction,
1523}
1524
1525impl<'a> Deref for TrustedCommitmentTransaction<'a> {
1526 type Target = CommitmentTransaction;
1527
1528 fn deref(&self) -> &Self::Target { self.inner }
1529}
1530
1531impl<'a> TrustedCommitmentTransaction<'a> {
1532 pub fn txid(&self) -> Txid {
1534 self.inner.built.txid
1535 }
1536
1537 pub fn built_transaction(&self) -> &BuiltCommitmentTransaction {
1539 &self.inner.built
1540 }
1541
1542 pub fn keys(&self) -> &TxCreationKeys {
1544 &self.inner.keys
1545 }
1546
1547 pub fn opt_anchors(&self) -> bool {
1549 self.opt_anchors.is_some()
1550 }
1551
1552 pub fn get_htlc_sigs<T: secp256k1::Signing>(&self, htlc_base_key: &SecretKey, channel_parameters: &DirectedChannelTransactionParameters, secp_ctx: &Secp256k1<T>) -> Result<Vec<Signature>, ()> {
1559 let inner = self.inner;
1560 let keys = &inner.keys;
1561 let txid = inner.built.txid;
1562 let mut ret = Vec::with_capacity(inner.htlcs.len());
1563 let holder_htlc_key = derive_private_key(secp_ctx, &inner.keys.per_commitment_point, htlc_base_key);
1564
1565 for this_htlc in inner.htlcs.iter() {
1566 assert!(this_htlc.transaction_output_index.is_some());
1567 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);
1568
1569 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);
1570
1571 let sighash = hash_to_message!(&sighash::SighashCache::new(&htlc_tx).segwit_signature_hash(0, &htlc_redeemscript, this_htlc.amount_msat / 1000, EcdsaSighashType::All).unwrap()[..]);
1572 ret.push(sign(secp_ctx, &sighash, &holder_htlc_key));
1573 }
1574 Ok(ret)
1575 }
1576
1577 pub(crate) fn get_signed_htlc_tx(&self, channel_parameters: &DirectedChannelTransactionParameters, htlc_index: usize, counterparty_signature: &Signature, signature: &Signature, preimage: &Option<PaymentPreimage>) -> Transaction {
1579 let inner = self.inner;
1580 let keys = &inner.keys;
1581 let txid = inner.built.txid;
1582 let this_htlc = &inner.htlcs[htlc_index];
1583 assert!(this_htlc.transaction_output_index.is_some());
1584 if !this_htlc.offered && preimage.is_none() { unreachable!(); }
1586 if this_htlc.offered && preimage.is_some() { unreachable!(); }
1588
1589 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);
1590
1591 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);
1592
1593 htlc_tx.input[0].witness = chan_utils::build_htlc_input_witness(
1594 signature, counterparty_signature, preimage, &htlc_redeemscript, self.opt_anchors(),
1595 );
1596 htlc_tx
1597 }
1598}
1599
1600pub fn get_commitment_transaction_number_obscure_factor(
1607 broadcaster_payment_basepoint: &PublicKey,
1608 countersignatory_payment_basepoint: &PublicKey,
1609 outbound_from_broadcaster: bool,
1610) -> u64 {
1611 let mut sha = Sha256::engine();
1612
1613 if outbound_from_broadcaster {
1614 sha.input(&broadcaster_payment_basepoint.serialize());
1615 sha.input(&countersignatory_payment_basepoint.serialize());
1616 } else {
1617 sha.input(&countersignatory_payment_basepoint.serialize());
1618 sha.input(&broadcaster_payment_basepoint.serialize());
1619 }
1620 let res = Sha256::from_engine(sha).into_inner();
1621
1622 ((res[26] as u64) << 5 * 8)
1623 | ((res[27] as u64) << 4 * 8)
1624 | ((res[28] as u64) << 3 * 8)
1625 | ((res[29] as u64) << 2 * 8)
1626 | ((res[30] as u64) << 1 * 8)
1627 | ((res[31] as u64) << 0 * 8)
1628}
1629
1630#[cfg(test)]
1631mod tests {
1632 use super::CounterpartyCommitmentSecrets;
1633 use crate::{hex, chain};
1634 use crate::prelude::*;
1635 use crate::ln::chan_utils::{get_htlc_redeemscript, get_to_countersignatory_with_anchors_redeemscript, CommitmentTransaction, TxCreationKeys, ChannelTransactionParameters, CounterpartyChannelTransactionParameters, HTLCOutputInCommitment};
1636 use bitcoin::secp256k1::{PublicKey, SecretKey, Secp256k1};
1637 use crate::util::test_utils;
1638 use crate::chain::keysinterface::{KeysInterface, BaseSign};
1639 use bitcoin::{Network, Txid};
1640 use bitcoin::hashes::Hash;
1641 use crate::ln::PaymentHash;
1642 use bitcoin::hashes::hex::ToHex;
1643 use bitcoin::util::address::Payload;
1644 use bitcoin::PublicKey as BitcoinPublicKey;
1645
1646 #[test]
1647 fn test_anchors() {
1648 let secp_ctx = Secp256k1::new();
1649
1650 let seed = [42; 32];
1651 let network = Network::Testnet;
1652 let keys_provider = test_utils::TestKeysInterface::new(&seed, network);
1653 let signer = keys_provider.derive_channel_signer(3000, keys_provider.generate_channel_keys_id(false, 1_000_000, 0));
1654 let counterparty_signer = keys_provider.derive_channel_signer(3000, keys_provider.generate_channel_keys_id(true, 1_000_000, 1));
1655 let delayed_payment_base = &signer.pubkeys().delayed_payment_basepoint;
1656 let per_commitment_secret = SecretKey::from_slice(&hex::decode("1f1e1d1c1b1a191817161514131211100f0e0d0c0b0a09080706050403020100").unwrap()[..]).unwrap();
1657 let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &per_commitment_secret);
1658 let htlc_basepoint = &signer.pubkeys().htlc_basepoint;
1659 let holder_pubkeys = signer.pubkeys();
1660 let counterparty_pubkeys = counterparty_signer.pubkeys();
1661 let keys = TxCreationKeys::derive_new(&secp_ctx, &per_commitment_point, delayed_payment_base, htlc_basepoint, &counterparty_pubkeys.revocation_basepoint, &counterparty_pubkeys.htlc_basepoint);
1662 let mut channel_parameters = ChannelTransactionParameters {
1663 holder_pubkeys: holder_pubkeys.clone(),
1664 holder_selected_contest_delay: 0,
1665 is_outbound_from_holder: false,
1666 counterparty_parameters: Some(CounterpartyChannelTransactionParameters { pubkeys: counterparty_pubkeys.clone(), selected_contest_delay: 0 }),
1667 funding_outpoint: Some(chain::transaction::OutPoint { txid: Txid::all_zeros(), index: 0 }),
1668 opt_anchors: None,
1669 opt_non_zero_fee_anchors: None,
1670 };
1671
1672 let mut htlcs_with_aux: Vec<(_, ())> = Vec::new();
1673
1674 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1676 0, 1000, 2000,
1677 false,
1678 holder_pubkeys.funding_pubkey,
1679 counterparty_pubkeys.funding_pubkey,
1680 keys.clone(), 1,
1681 &mut htlcs_with_aux, &channel_parameters.as_holder_broadcastable()
1682 );
1683 assert_eq!(tx.built.transaction.output.len(), 2);
1684 assert_eq!(tx.built.transaction.output[1].script_pubkey, Payload::p2wpkh(&BitcoinPublicKey::new(counterparty_pubkeys.payment_point)).unwrap().script_pubkey());
1685
1686 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1688 0, 1000, 2000,
1689 true,
1690 holder_pubkeys.funding_pubkey,
1691 counterparty_pubkeys.funding_pubkey,
1692 keys.clone(), 1,
1693 &mut htlcs_with_aux, &channel_parameters.as_holder_broadcastable()
1694 );
1695 assert_eq!(tx.built.transaction.output.len(), 4);
1696 assert_eq!(tx.built.transaction.output[3].script_pubkey, get_to_countersignatory_with_anchors_redeemscript(&counterparty_pubkeys.payment_point).to_v0_p2wsh());
1697
1698 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1700 0, 3000, 0,
1701 true,
1702 holder_pubkeys.funding_pubkey,
1703 counterparty_pubkeys.funding_pubkey,
1704 keys.clone(), 1,
1705 &mut htlcs_with_aux, &channel_parameters.as_holder_broadcastable()
1706 );
1707 assert_eq!(tx.built.transaction.output.len(), 2);
1708
1709 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1711 0, 0, 3000,
1712 true,
1713 holder_pubkeys.funding_pubkey,
1714 counterparty_pubkeys.funding_pubkey,
1715 keys.clone(), 1,
1716 &mut htlcs_with_aux, &channel_parameters.as_holder_broadcastable()
1717 );
1718 assert_eq!(tx.built.transaction.output.len(), 2);
1719
1720 let received_htlc = HTLCOutputInCommitment {
1721 offered: false,
1722 amount_msat: 400000,
1723 cltv_expiry: 100,
1724 payment_hash: PaymentHash([42; 32]),
1725 transaction_output_index: None,
1726 };
1727
1728 let offered_htlc = HTLCOutputInCommitment {
1729 offered: true,
1730 amount_msat: 600000,
1731 cltv_expiry: 100,
1732 payment_hash: PaymentHash([43; 32]),
1733 transaction_output_index: None,
1734 };
1735
1736 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1738 0, 3000, 0,
1739 false,
1740 holder_pubkeys.funding_pubkey,
1741 counterparty_pubkeys.funding_pubkey,
1742 keys.clone(), 1,
1743 &mut vec![(received_htlc.clone(), ()), (offered_htlc.clone(), ())],
1744 &channel_parameters.as_holder_broadcastable()
1745 );
1746 assert_eq!(tx.built.transaction.output.len(), 3);
1747 assert_eq!(tx.built.transaction.output[0].script_pubkey, get_htlc_redeemscript(&received_htlc, false, &keys).to_v0_p2wsh());
1748 assert_eq!(tx.built.transaction.output[1].script_pubkey, get_htlc_redeemscript(&offered_htlc, false, &keys).to_v0_p2wsh());
1749 assert_eq!(get_htlc_redeemscript(&received_htlc, false, &keys).to_v0_p2wsh().to_hex(),
1750 "0020e43a7c068553003fe68fcae424fb7b28ec5ce48cd8b6744b3945631389bad2fb");
1751 assert_eq!(get_htlc_redeemscript(&offered_htlc, false, &keys).to_v0_p2wsh().to_hex(),
1752 "0020215d61bba56b19e9eadb6107f5a85d7f99c40f65992443f69229c290165bc00d");
1753
1754 channel_parameters.opt_anchors = Some(());
1756 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1757 0, 3000, 0,
1758 true,
1759 holder_pubkeys.funding_pubkey,
1760 counterparty_pubkeys.funding_pubkey,
1761 keys.clone(), 1,
1762 &mut vec![(received_htlc.clone(), ()), (offered_htlc.clone(), ())],
1763 &channel_parameters.as_holder_broadcastable()
1764 );
1765 assert_eq!(tx.built.transaction.output.len(), 5);
1766 assert_eq!(tx.built.transaction.output[2].script_pubkey, get_htlc_redeemscript(&received_htlc, true, &keys).to_v0_p2wsh());
1767 assert_eq!(tx.built.transaction.output[3].script_pubkey, get_htlc_redeemscript(&offered_htlc, true, &keys).to_v0_p2wsh());
1768 assert_eq!(get_htlc_redeemscript(&received_htlc, true, &keys).to_v0_p2wsh().to_hex(),
1769 "0020b70d0649c72b38756885c7a30908d912a7898dd5d79457a7280b8e9a20f3f2bc");
1770 assert_eq!(get_htlc_redeemscript(&offered_htlc, true, &keys).to_v0_p2wsh().to_hex(),
1771 "002087a3faeb1950a469c0e2db4a79b093a41b9526e5a6fc6ef5cb949bde3be379c7");
1772 }
1773
1774 #[test]
1775 fn test_per_commitment_storage() {
1776 let mut secrets: Vec<[u8; 32]> = Vec::new();
1778 let mut monitor;
1779
1780 macro_rules! test_secrets {
1781 () => {
1782 let mut idx = 281474976710655;
1783 for secret in secrets.iter() {
1784 assert_eq!(monitor.get_secret(idx).unwrap(), *secret);
1785 idx -= 1;
1786 }
1787 assert_eq!(monitor.get_min_seen_secret(), idx + 1);
1788 assert!(monitor.get_secret(idx).is_none());
1789 };
1790 }
1791
1792 {
1793 monitor = CounterpartyCommitmentSecrets::new();
1795 secrets.clear();
1796
1797 secrets.push([0; 32]);
1798 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1799 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1800 test_secrets!();
1801
1802 secrets.push([0; 32]);
1803 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1804 monitor.provide_secret(281474976710654, 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("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1809 monitor.provide_secret(281474976710653, 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("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1814 monitor.provide_secret(281474976710652, 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("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1819 monitor.provide_secret(281474976710651, 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("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1824 monitor.provide_secret(281474976710650, 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("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1829 monitor.provide_secret(281474976710649, 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("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1834 monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap();
1835 test_secrets!();
1836 }
1837
1838 {
1839 monitor = CounterpartyCommitmentSecrets::new();
1841 secrets.clear();
1842
1843 secrets.push([0; 32]);
1844 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
1845 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1846 test_secrets!();
1847
1848 secrets.push([0; 32]);
1849 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1850 assert!(monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).is_err());
1851 }
1852
1853 {
1854 monitor = CounterpartyCommitmentSecrets::new();
1856 secrets.clear();
1857
1858 secrets.push([0; 32]);
1859 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
1860 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1861 test_secrets!();
1862
1863 secrets.push([0; 32]);
1864 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
1865 monitor.provide_secret(281474976710654, 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("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1870 monitor.provide_secret(281474976710653, 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("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1875 assert!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).is_err());
1876 }
1877
1878 {
1879 monitor = CounterpartyCommitmentSecrets::new();
1881 secrets.clear();
1882
1883 secrets.push([0; 32]);
1884 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1885 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1886 test_secrets!();
1887
1888 secrets.push([0; 32]);
1889 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1890 monitor.provide_secret(281474976710654, 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("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
1895 monitor.provide_secret(281474976710653, 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("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1900 assert!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).is_err());
1901 }
1902
1903 {
1904 monitor = CounterpartyCommitmentSecrets::new();
1906 secrets.clear();
1907
1908 secrets.push([0; 32]);
1909 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
1910 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1911 test_secrets!();
1912
1913 secrets.push([0; 32]);
1914 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
1915 monitor.provide_secret(281474976710654, 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("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
1920 monitor.provide_secret(281474976710653, 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("ba65d7b0ef55a3ba300d4e87af29868f394f8f138d78a7011669c79b37b936f4").unwrap());
1925 monitor.provide_secret(281474976710652, 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("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1930 monitor.provide_secret(281474976710651, 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("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1935 monitor.provide_secret(281474976710650, 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("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1940 monitor.provide_secret(281474976710649, 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("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1945 assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
1946 }
1947
1948 {
1949 monitor = CounterpartyCommitmentSecrets::new();
1951 secrets.clear();
1952
1953 secrets.push([0; 32]);
1954 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1955 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1956 test_secrets!();
1957
1958 secrets.push([0; 32]);
1959 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1960 monitor.provide_secret(281474976710654, 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("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1965 monitor.provide_secret(281474976710653, 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("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1970 monitor.provide_secret(281474976710652, 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("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
1975 monitor.provide_secret(281474976710651, 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("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1980 assert!(monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).is_err());
1981 }
1982
1983 {
1984 monitor = CounterpartyCommitmentSecrets::new();
1986 secrets.clear();
1987
1988 secrets.push([0; 32]);
1989 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1990 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1991 test_secrets!();
1992
1993 secrets.push([0; 32]);
1994 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1995 monitor.provide_secret(281474976710654, 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("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2000 monitor.provide_secret(281474976710653, 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("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2005 monitor.provide_secret(281474976710652, 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("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
2010 monitor.provide_secret(281474976710651, 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("b7e76a83668bde38b373970155c868a653304308f9896692f904a23731224bb1").unwrap());
2015 monitor.provide_secret(281474976710650, 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("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2020 monitor.provide_secret(281474976710649, 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("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2025 assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
2026 }
2027
2028 {
2029 monitor = CounterpartyCommitmentSecrets::new();
2031 secrets.clear();
2032
2033 secrets.push([0; 32]);
2034 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2035 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2036 test_secrets!();
2037
2038 secrets.push([0; 32]);
2039 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2040 monitor.provide_secret(281474976710654, 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("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2045 monitor.provide_secret(281474976710653, 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("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2050 monitor.provide_secret(281474976710652, 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("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2055 monitor.provide_secret(281474976710651, 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("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2060 monitor.provide_secret(281474976710650, 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("e7971de736e01da8ed58b94c2fc216cb1dca9e326f3a96e7194fe8ea8af6c0a3").unwrap());
2065 monitor.provide_secret(281474976710649, 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("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2070 assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
2071 }
2072
2073 {
2074 monitor = CounterpartyCommitmentSecrets::new();
2076 secrets.clear();
2077
2078 secrets.push([0; 32]);
2079 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2080 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2081 test_secrets!();
2082
2083 secrets.push([0; 32]);
2084 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2085 monitor.provide_secret(281474976710654, 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("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2090 monitor.provide_secret(281474976710653, 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("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2095 monitor.provide_secret(281474976710652, 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("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2100 monitor.provide_secret(281474976710651, 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("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2105 monitor.provide_secret(281474976710650, 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("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2110 monitor.provide_secret(281474976710649, 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("a7efbc61aac46d34f77778bac22c8a20c6a46ca460addc49009bda875ec88fa4").unwrap());
2115 assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
2116 }
2117 }
2118}