1 // This file is Copyright its original authors, visible in version control
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
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.
13 use bitcoin::blockdata::script::{Script,Builder};
14 use bitcoin::blockdata::opcodes;
15 use bitcoin::blockdata::transaction::{TxIn,TxOut,OutPoint,Transaction, SigHashType};
16 use bitcoin::util::bip143;
18 use bitcoin::hashes::{Hash, HashEngine};
19 use bitcoin::hashes::sha256::Hash as Sha256;
20 use bitcoin::hashes::ripemd160::Hash as Ripemd160;
21 use bitcoin::hash_types::{Txid, PubkeyHash};
23 use ln::{PaymentHash, PaymentPreimage};
24 use ln::msgs::DecodeError;
25 use util::ser::{Readable, Writeable, Writer};
26 use util::{byte_utils, transaction_utils};
28 use bitcoin::hash_types::WPubkeyHash;
29 use bitcoin::secp256k1::key::{SecretKey, PublicKey};
30 use bitcoin::secp256k1::{Secp256k1, Signature, Message};
31 use bitcoin::secp256k1::Error as SecpError;
32 use bitcoin::secp256k1;
38 use util::transaction_utils::sort_outputs;
39 use ln::channel::{INITIAL_COMMITMENT_NUMBER, ANCHOR_OUTPUT_VALUE_SATOSHI};
43 pub(crate) const MAX_HTLCS: u16 = 483;
45 pub(super) const HTLC_SUCCESS_TX_WEIGHT: u64 = 703;
46 pub(super) const HTLC_TIMEOUT_TX_WEIGHT: u64 = 663;
49 pub(crate) enum HTLCType {
55 /// Check if a given tx witnessScript len matchs one of a pre-signed HTLC
56 pub(crate) fn scriptlen_to_htlctype(witness_script_len: usize) -> Option<HTLCType> {
57 if witness_script_len == 133 {
58 Some(HTLCType::OfferedHTLC)
59 } else if witness_script_len >= 136 && witness_script_len <= 139 {
60 Some(HTLCType::AcceptedHTLC)
67 // Various functions for key derivation and transaction creation for use within channels. Primarily
68 // used in Channel and ChannelMonitor.
70 /// Build the commitment secret from the seed and the commitment number
71 pub fn build_commitment_secret(commitment_seed: &[u8; 32], idx: u64) -> [u8; 32] {
72 let mut res: [u8; 32] = commitment_seed.clone();
75 if idx & (1 << bitpos) == (1 << bitpos) {
76 res[bitpos / 8] ^= 1 << (bitpos & 7);
77 res = Sha256::hash(&res).into_inner();
83 /// Build a closing transaction
84 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 {
86 let mut ins: Vec<TxIn> = Vec::new();
88 previous_output: funding_outpoint,
89 script_sig: Script::new(),
96 let mut txouts: Vec<(TxOut, ())> = Vec::new();
98 if to_counterparty_value_sat > 0 {
100 script_pubkey: to_counterparty_script,
101 value: to_counterparty_value_sat
105 if to_holder_value_sat > 0 {
107 script_pubkey: to_holder_script,
108 value: to_holder_value_sat
112 transaction_utils::sort_outputs(&mut txouts, |_, _| { cmp::Ordering::Equal }); // Ordering doesnt matter if they used our pubkey...
114 let mut outputs: Vec<TxOut> = Vec::new();
115 for out in txouts.drain(..) {
127 /// Implements the per-commitment secret storage scheme from
128 /// [BOLT 3](https://github.com/lightningnetwork/lightning-rfc/blob/dcbf8583976df087c79c3ce0b535311212e6812d/03-transactions.md#efficient-per-commitment-secret-storage).
130 /// Allows us to keep track of all of the revocation secrets of counterarties in just 50*32 bytes
133 pub(crate) struct CounterpartyCommitmentSecrets {
134 old_secrets: [([u8; 32], u64); 49],
137 impl PartialEq for CounterpartyCommitmentSecrets {
138 fn eq(&self, other: &Self) -> bool {
139 for (&(ref secret, ref idx), &(ref o_secret, ref o_idx)) in self.old_secrets.iter().zip(other.old_secrets.iter()) {
140 if secret != o_secret || idx != o_idx {
148 impl CounterpartyCommitmentSecrets {
149 pub(crate) fn new() -> Self {
150 Self { old_secrets: [([0; 32], 1 << 48); 49], }
154 fn place_secret(idx: u64) -> u8 {
156 if idx & (1 << i) == (1 << i) {
163 pub(crate) fn get_min_seen_secret(&self) -> u64 {
164 //TODO This can be optimized?
165 let mut min = 1 << 48;
166 for &(_, idx) in self.old_secrets.iter() {
175 fn derive_secret(secret: [u8; 32], bits: u8, idx: u64) -> [u8; 32] {
176 let mut res: [u8; 32] = secret;
178 let bitpos = bits - 1 - i;
179 if idx & (1 << bitpos) == (1 << bitpos) {
180 res[(bitpos / 8) as usize] ^= 1 << (bitpos & 7);
181 res = Sha256::hash(&res).into_inner();
187 pub(crate) fn provide_secret(&mut self, idx: u64, secret: [u8; 32]) -> Result<(), ()> {
188 let pos = Self::place_secret(idx);
190 let (old_secret, old_idx) = self.old_secrets[i as usize];
191 if Self::derive_secret(secret, pos, old_idx) != old_secret {
195 if self.get_min_seen_secret() <= idx {
198 self.old_secrets[pos as usize] = (secret, idx);
202 /// Can only fail if idx is < get_min_seen_secret
203 pub(crate) fn get_secret(&self, idx: u64) -> Option<[u8; 32]> {
204 for i in 0..self.old_secrets.len() {
205 if (idx & (!((1 << i) - 1))) == self.old_secrets[i].1 {
206 return Some(Self::derive_secret(self.old_secrets[i].0, i as u8, idx))
209 assert!(idx < self.get_min_seen_secret());
214 impl Writeable for CounterpartyCommitmentSecrets {
215 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
216 for &(ref secret, ref idx) in self.old_secrets.iter() {
217 writer.write_all(secret)?;
218 writer.write_all(&byte_utils::be64_to_array(*idx))?;
220 write_tlv_fields!(writer, {});
224 impl Readable for CounterpartyCommitmentSecrets {
225 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
226 let mut old_secrets = [([0; 32], 1 << 48); 49];
227 for &mut (ref mut secret, ref mut idx) in old_secrets.iter_mut() {
228 *secret = Readable::read(reader)?;
229 *idx = Readable::read(reader)?;
231 read_tlv_fields!(reader, {});
232 Ok(Self { old_secrets })
236 /// Derives a per-commitment-transaction private key (eg an htlc key or delayed_payment key)
237 /// from the base secret and the per_commitment_point.
239 /// Note that this is infallible iff we trust that at least one of the two input keys are randomly
240 /// generated (ie our own).
241 pub fn derive_private_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, base_secret: &SecretKey) -> Result<SecretKey, SecpError> {
242 let mut sha = Sha256::engine();
243 sha.input(&per_commitment_point.serialize());
244 sha.input(&PublicKey::from_secret_key(&secp_ctx, &base_secret).serialize());
245 let res = Sha256::from_engine(sha).into_inner();
247 let mut key = base_secret.clone();
248 key.add_assign(&res)?;
252 /// Derives a per-commitment-transaction public key (eg an htlc key or a delayed_payment key)
253 /// from the base point and the per_commitment_key. This is the public equivalent of
254 /// derive_private_key - using only public keys to derive a public key instead of private keys.
256 /// Note that this is infallible iff we trust that at least one of the two input keys are randomly
257 /// generated (ie our own).
258 pub fn derive_public_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, base_point: &PublicKey) -> Result<PublicKey, SecpError> {
259 let mut sha = Sha256::engine();
260 sha.input(&per_commitment_point.serialize());
261 sha.input(&base_point.serialize());
262 let res = Sha256::from_engine(sha).into_inner();
264 let hashkey = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&res)?);
265 base_point.combine(&hashkey)
268 /// Derives a per-commitment-transaction revocation key from its constituent parts.
270 /// Only the cheating participant owns a valid witness to propagate a revoked
271 /// commitment transaction, thus per_commitment_secret always come from cheater
272 /// and revocation_base_secret always come from punisher, which is the broadcaster
273 /// of the transaction spending with this key knowledge.
275 /// Note that this is infallible iff we trust that at least one of the two input keys are randomly
276 /// generated (ie our own).
277 pub fn derive_private_revocation_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, per_commitment_secret: &SecretKey, countersignatory_revocation_base_secret: &SecretKey) -> Result<SecretKey, SecpError> {
278 let countersignatory_revocation_base_point = PublicKey::from_secret_key(&secp_ctx, &countersignatory_revocation_base_secret);
279 let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &per_commitment_secret);
281 let rev_append_commit_hash_key = {
282 let mut sha = Sha256::engine();
283 sha.input(&countersignatory_revocation_base_point.serialize());
284 sha.input(&per_commitment_point.serialize());
286 Sha256::from_engine(sha).into_inner()
288 let commit_append_rev_hash_key = {
289 let mut sha = Sha256::engine();
290 sha.input(&per_commitment_point.serialize());
291 sha.input(&countersignatory_revocation_base_point.serialize());
293 Sha256::from_engine(sha).into_inner()
296 let mut countersignatory_contrib = countersignatory_revocation_base_secret.clone();
297 countersignatory_contrib.mul_assign(&rev_append_commit_hash_key)?;
298 let mut broadcaster_contrib = per_commitment_secret.clone();
299 broadcaster_contrib.mul_assign(&commit_append_rev_hash_key)?;
300 countersignatory_contrib.add_assign(&broadcaster_contrib[..])?;
301 Ok(countersignatory_contrib)
304 /// Derives a per-commitment-transaction revocation public key from its constituent parts. This is
305 /// the public equivalend of derive_private_revocation_key - using only public keys to derive a
306 /// public key instead of private keys.
308 /// Only the cheating participant owns a valid witness to propagate a revoked
309 /// commitment transaction, thus per_commitment_point always come from cheater
310 /// and revocation_base_point always come from punisher, which is the broadcaster
311 /// of the transaction spending with this key knowledge.
313 /// Note that this is infallible iff we trust that at least one of the two input keys are randomly
314 /// generated (ie our own).
315 pub fn derive_public_revocation_key<T: secp256k1::Verification>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, countersignatory_revocation_base_point: &PublicKey) -> Result<PublicKey, SecpError> {
316 let rev_append_commit_hash_key = {
317 let mut sha = Sha256::engine();
318 sha.input(&countersignatory_revocation_base_point.serialize());
319 sha.input(&per_commitment_point.serialize());
321 Sha256::from_engine(sha).into_inner()
323 let commit_append_rev_hash_key = {
324 let mut sha = Sha256::engine();
325 sha.input(&per_commitment_point.serialize());
326 sha.input(&countersignatory_revocation_base_point.serialize());
328 Sha256::from_engine(sha).into_inner()
331 let mut countersignatory_contrib = countersignatory_revocation_base_point.clone();
332 countersignatory_contrib.mul_assign(&secp_ctx, &rev_append_commit_hash_key)?;
333 let mut broadcaster_contrib = per_commitment_point.clone();
334 broadcaster_contrib.mul_assign(&secp_ctx, &commit_append_rev_hash_key)?;
335 countersignatory_contrib.combine(&broadcaster_contrib)
338 /// The set of public keys which are used in the creation of one commitment transaction.
339 /// These are derived from the channel base keys and per-commitment data.
341 /// A broadcaster key is provided from potential broadcaster of the computed transaction.
342 /// A countersignatory key is coming from a protocol participant unable to broadcast the
345 /// These keys are assumed to be good, either because the code derived them from
346 /// channel basepoints via the new function, or they were obtained via
347 /// CommitmentTransaction.trust().keys() because we trusted the source of the
348 /// pre-calculated keys.
349 #[derive(PartialEq, Clone)]
350 pub struct TxCreationKeys {
351 /// The broadcaster's per-commitment public key which was used to derive the other keys.
352 pub per_commitment_point: PublicKey,
353 /// The revocation key which is used to allow the broadcaster of the commitment
354 /// transaction to provide their counterparty the ability to punish them if they broadcast
356 pub revocation_key: PublicKey,
357 /// Broadcaster's HTLC Key
358 pub broadcaster_htlc_key: PublicKey,
359 /// Countersignatory's HTLC Key
360 pub countersignatory_htlc_key: PublicKey,
361 /// Broadcaster's Payment Key (which isn't allowed to be spent from for some delay)
362 pub broadcaster_delayed_payment_key: PublicKey,
365 impl_writeable_tlv_based!(TxCreationKeys, {
366 (0, per_commitment_point, required),
367 (2, revocation_key, required),
368 (4, broadcaster_htlc_key, required),
369 (6, countersignatory_htlc_key, required),
370 (8, broadcaster_delayed_payment_key, required),
373 /// One counterparty's public keys which do not change over the life of a channel.
374 #[derive(Clone, PartialEq)]
375 pub struct ChannelPublicKeys {
376 /// The public key which is used to sign all commitment transactions, as it appears in the
377 /// on-chain channel lock-in 2-of-2 multisig output.
378 pub funding_pubkey: PublicKey,
379 /// The base point which is used (with derive_public_revocation_key) to derive per-commitment
380 /// revocation keys. This is combined with the per-commitment-secret generated by the
381 /// counterparty to create a secret which the counterparty can reveal to revoke previous
383 pub revocation_basepoint: PublicKey,
384 /// The public key on which the non-broadcaster (ie the countersignatory) receives an immediately
385 /// spendable primary channel balance on the broadcaster's commitment transaction. This key is
386 /// static across every commitment transaction.
387 pub payment_point: PublicKey,
388 /// The base point which is used (with derive_public_key) to derive a per-commitment payment
389 /// public key which receives non-HTLC-encumbered funds which are only available for spending
390 /// after some delay (or can be claimed via the revocation path).
391 pub delayed_payment_basepoint: PublicKey,
392 /// The base point which is used (with derive_public_key) to derive a per-commitment public key
393 /// which is used to encumber HTLC-in-flight outputs.
394 pub htlc_basepoint: PublicKey,
397 impl_writeable_tlv_based!(ChannelPublicKeys, {
398 (0, funding_pubkey, required),
399 (2, revocation_basepoint, required),
400 (4, payment_point, required),
401 (6, delayed_payment_basepoint, required),
402 (8, htlc_basepoint, required),
405 impl TxCreationKeys {
406 /// Create per-state keys from channel base points and the per-commitment point.
407 /// Key set is asymmetric and can't be used as part of counter-signatory set of transactions.
408 pub fn derive_new<T: secp256k1::Signing + secp256k1::Verification>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, broadcaster_delayed_payment_base: &PublicKey, broadcaster_htlc_base: &PublicKey, countersignatory_revocation_base: &PublicKey, countersignatory_htlc_base: &PublicKey) -> Result<TxCreationKeys, SecpError> {
410 per_commitment_point: per_commitment_point.clone(),
411 revocation_key: derive_public_revocation_key(&secp_ctx, &per_commitment_point, &countersignatory_revocation_base)?,
412 broadcaster_htlc_key: derive_public_key(&secp_ctx, &per_commitment_point, &broadcaster_htlc_base)?,
413 countersignatory_htlc_key: derive_public_key(&secp_ctx, &per_commitment_point, &countersignatory_htlc_base)?,
414 broadcaster_delayed_payment_key: derive_public_key(&secp_ctx, &per_commitment_point, &broadcaster_delayed_payment_base)?,
418 /// Generate per-state keys from channel static keys.
419 /// Key set is asymmetric and can't be used as part of counter-signatory set of transactions.
420 pub fn from_channel_static_keys<T: secp256k1::Signing + secp256k1::Verification>(per_commitment_point: &PublicKey, broadcaster_keys: &ChannelPublicKeys, countersignatory_keys: &ChannelPublicKeys, secp_ctx: &Secp256k1<T>) -> Result<TxCreationKeys, SecpError> {
421 TxCreationKeys::derive_new(
423 &per_commitment_point,
424 &broadcaster_keys.delayed_payment_basepoint,
425 &broadcaster_keys.htlc_basepoint,
426 &countersignatory_keys.revocation_basepoint,
427 &countersignatory_keys.htlc_basepoint,
432 /// The maximum length of a script returned by get_revokeable_redeemscript.
433 // Calculated as 6 bytes of opcodes, 1 byte push plus 2 bytes for contest_delay, and two public
434 // keys of 33 bytes (+ 1 push).
435 pub const REVOKEABLE_REDEEMSCRIPT_MAX_LENGTH: usize = 6 + 3 + 34*2;
437 /// A script either spendable by the revocation
438 /// key or the broadcaster_delayed_payment_key and satisfying the relative-locktime OP_CSV constrain.
439 /// Encumbering a `to_holder` output on a commitment transaction or 2nd-stage HTLC transactions.
440 pub fn get_revokeable_redeemscript(revocation_key: &PublicKey, contest_delay: u16, broadcaster_delayed_payment_key: &PublicKey) -> Script {
441 let res = Builder::new().push_opcode(opcodes::all::OP_IF)
442 .push_slice(&revocation_key.serialize())
443 .push_opcode(opcodes::all::OP_ELSE)
444 .push_int(contest_delay as i64)
445 .push_opcode(opcodes::all::OP_CSV)
446 .push_opcode(opcodes::all::OP_DROP)
447 .push_slice(&broadcaster_delayed_payment_key.serialize())
448 .push_opcode(opcodes::all::OP_ENDIF)
449 .push_opcode(opcodes::all::OP_CHECKSIG)
451 debug_assert!(res.len() <= REVOKEABLE_REDEEMSCRIPT_MAX_LENGTH);
455 #[derive(Clone, PartialEq)]
456 /// Information about an HTLC as it appears in a commitment transaction
457 pub struct HTLCOutputInCommitment {
458 /// Whether the HTLC was "offered" (ie outbound in relation to this commitment transaction).
459 /// Note that this is not the same as whether it is ountbound *from us*. To determine that you
460 /// need to compare this value to whether the commitment transaction in question is that of
461 /// the counterparty or our own.
463 /// The value, in msat, of the HTLC. The value as it appears in the commitment transaction is
464 /// this divided by 1000.
465 pub amount_msat: u64,
466 /// The CLTV lock-time at which this HTLC expires.
467 pub cltv_expiry: u32,
468 /// The hash of the preimage which unlocks this HTLC.
469 pub payment_hash: PaymentHash,
470 /// The position within the commitment transactions' outputs. This may be None if the value is
471 /// below the dust limit (in which case no output appears in the commitment transaction and the
472 /// value is spent to additional transaction fees).
473 pub transaction_output_index: Option<u32>,
476 impl_writeable_tlv_based!(HTLCOutputInCommitment, {
477 (0, offered, required),
478 (2, amount_msat, required),
479 (4, cltv_expiry, required),
480 (6, payment_hash, required),
481 (8, transaction_output_index, option),
485 pub(crate) fn get_htlc_redeemscript_with_explicit_keys(htlc: &HTLCOutputInCommitment, broadcaster_htlc_key: &PublicKey, countersignatory_htlc_key: &PublicKey, revocation_key: &PublicKey) -> Script {
486 let payment_hash160 = Ripemd160::hash(&htlc.payment_hash.0[..]).into_inner();
488 Builder::new().push_opcode(opcodes::all::OP_DUP)
489 .push_opcode(opcodes::all::OP_HASH160)
490 .push_slice(&PubkeyHash::hash(&revocation_key.serialize())[..])
491 .push_opcode(opcodes::all::OP_EQUAL)
492 .push_opcode(opcodes::all::OP_IF)
493 .push_opcode(opcodes::all::OP_CHECKSIG)
494 .push_opcode(opcodes::all::OP_ELSE)
495 .push_slice(&countersignatory_htlc_key.serialize()[..])
496 .push_opcode(opcodes::all::OP_SWAP)
497 .push_opcode(opcodes::all::OP_SIZE)
499 .push_opcode(opcodes::all::OP_EQUAL)
500 .push_opcode(opcodes::all::OP_NOTIF)
501 .push_opcode(opcodes::all::OP_DROP)
503 .push_opcode(opcodes::all::OP_SWAP)
504 .push_slice(&broadcaster_htlc_key.serialize()[..])
506 .push_opcode(opcodes::all::OP_CHECKMULTISIG)
507 .push_opcode(opcodes::all::OP_ELSE)
508 .push_opcode(opcodes::all::OP_HASH160)
509 .push_slice(&payment_hash160)
510 .push_opcode(opcodes::all::OP_EQUALVERIFY)
511 .push_opcode(opcodes::all::OP_CHECKSIG)
512 .push_opcode(opcodes::all::OP_ENDIF)
513 .push_opcode(opcodes::all::OP_ENDIF)
516 Builder::new().push_opcode(opcodes::all::OP_DUP)
517 .push_opcode(opcodes::all::OP_HASH160)
518 .push_slice(&PubkeyHash::hash(&revocation_key.serialize())[..])
519 .push_opcode(opcodes::all::OP_EQUAL)
520 .push_opcode(opcodes::all::OP_IF)
521 .push_opcode(opcodes::all::OP_CHECKSIG)
522 .push_opcode(opcodes::all::OP_ELSE)
523 .push_slice(&countersignatory_htlc_key.serialize()[..])
524 .push_opcode(opcodes::all::OP_SWAP)
525 .push_opcode(opcodes::all::OP_SIZE)
527 .push_opcode(opcodes::all::OP_EQUAL)
528 .push_opcode(opcodes::all::OP_IF)
529 .push_opcode(opcodes::all::OP_HASH160)
530 .push_slice(&payment_hash160)
531 .push_opcode(opcodes::all::OP_EQUALVERIFY)
533 .push_opcode(opcodes::all::OP_SWAP)
534 .push_slice(&broadcaster_htlc_key.serialize()[..])
536 .push_opcode(opcodes::all::OP_CHECKMULTISIG)
537 .push_opcode(opcodes::all::OP_ELSE)
538 .push_opcode(opcodes::all::OP_DROP)
539 .push_int(htlc.cltv_expiry as i64)
540 .push_opcode(opcodes::all::OP_CLTV)
541 .push_opcode(opcodes::all::OP_DROP)
542 .push_opcode(opcodes::all::OP_CHECKSIG)
543 .push_opcode(opcodes::all::OP_ENDIF)
544 .push_opcode(opcodes::all::OP_ENDIF)
549 /// Gets the witness redeemscript for an HTLC output in a commitment transaction. Note that htlc
550 /// does not need to have its previous_output_index filled.
552 pub fn get_htlc_redeemscript(htlc: &HTLCOutputInCommitment, keys: &TxCreationKeys) -> Script {
553 get_htlc_redeemscript_with_explicit_keys(htlc, &keys.broadcaster_htlc_key, &keys.countersignatory_htlc_key, &keys.revocation_key)
556 /// Gets the redeemscript for a funding output from the two funding public keys.
557 /// Note that the order of funding public keys does not matter.
558 pub fn make_funding_redeemscript(broadcaster: &PublicKey, countersignatory: &PublicKey) -> Script {
559 let broadcaster_funding_key = broadcaster.serialize();
560 let countersignatory_funding_key = countersignatory.serialize();
562 let builder = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2);
563 if broadcaster_funding_key[..] < countersignatory_funding_key[..] {
564 builder.push_slice(&broadcaster_funding_key)
565 .push_slice(&countersignatory_funding_key)
567 builder.push_slice(&countersignatory_funding_key)
568 .push_slice(&broadcaster_funding_key)
569 }.push_opcode(opcodes::all::OP_PUSHNUM_2).push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script()
572 /// Builds an unsigned HTLC-Success or HTLC-Timeout transaction from the given channel and HTLC
573 /// parameters. This is used by [`TrustedCommitmentTransaction::get_htlc_sigs`] to fetch the
574 /// transaction which needs signing, and can be used to construct an HTLC transaction which is
575 /// broadcastable given a counterparty HTLC signature.
577 /// Panics if htlc.transaction_output_index.is_none() (as such HTLCs do not appear in the
578 /// commitment transaction).
579 pub fn build_htlc_transaction(commitment_txid: &Txid, feerate_per_kw: u32, contest_delay: u16, htlc: &HTLCOutputInCommitment, broadcaster_delayed_payment_key: &PublicKey, revocation_key: &PublicKey) -> Transaction {
580 let mut txins: Vec<TxIn> = Vec::new();
582 previous_output: OutPoint {
583 txid: commitment_txid.clone(),
584 vout: htlc.transaction_output_index.expect("Can't build an HTLC transaction for a dust output"),
586 script_sig: Script::new(),
591 let total_fee = if htlc.offered {
592 feerate_per_kw as u64 * HTLC_TIMEOUT_TX_WEIGHT / 1000
594 feerate_per_kw as u64 * HTLC_SUCCESS_TX_WEIGHT / 1000
597 let mut txouts: Vec<TxOut> = Vec::new();
599 script_pubkey: get_revokeable_redeemscript(revocation_key, contest_delay, broadcaster_delayed_payment_key).to_v0_p2wsh(),
600 value: htlc.amount_msat / 1000 - total_fee //TODO: BOLT 3 does not specify if we should add amount_msat before dividing or if we should divide by 1000 before subtracting (as we do here)
605 lock_time: if htlc.offered { htlc.cltv_expiry } else { 0 },
611 /// Gets the witnessScript for an anchor output from the funding public key.
612 /// The witness in the spending input must be:
613 /// <BIP 143 funding_signature>
614 /// After 16 blocks of confirmation, an alternative satisfying witness could be:
616 /// (empty vector required to satisfy compliance with MINIMALIF-standard rule)
618 pub(crate) fn get_anchor_redeemscript(funding_pubkey: &PublicKey) -> Script {
619 Builder::new().push_slice(&funding_pubkey.serialize()[..])
620 .push_opcode(opcodes::all::OP_CHECKSIG)
621 .push_opcode(opcodes::all::OP_IFDUP)
622 .push_opcode(opcodes::all::OP_NOTIF)
624 .push_opcode(opcodes::all::OP_CSV)
625 .push_opcode(opcodes::all::OP_ENDIF)
629 /// Per-channel data used to build transactions in conjunction with the per-commitment data (CommitmentTransaction).
630 /// The fields are organized by holder/counterparty.
632 /// Normally, this is converted to the broadcaster/countersignatory-organized DirectedChannelTransactionParameters
633 /// before use, via the as_holder_broadcastable and as_counterparty_broadcastable functions.
635 pub struct ChannelTransactionParameters {
636 /// Holder public keys
637 pub holder_pubkeys: ChannelPublicKeys,
638 /// The contest delay selected by the holder, which applies to counterparty-broadcast transactions
639 pub holder_selected_contest_delay: u16,
640 /// Whether the holder is the initiator of this channel.
641 /// This is an input to the commitment number obscure factor computation.
642 pub is_outbound_from_holder: bool,
643 /// The late-bound counterparty channel transaction parameters.
644 /// These parameters are populated at the point in the protocol where the counterparty provides them.
645 pub counterparty_parameters: Option<CounterpartyChannelTransactionParameters>,
646 /// The late-bound funding outpoint
647 pub funding_outpoint: Option<chain::transaction::OutPoint>,
650 /// Late-bound per-channel counterparty data used to build transactions.
652 pub struct CounterpartyChannelTransactionParameters {
653 /// Counter-party public keys
654 pub pubkeys: ChannelPublicKeys,
655 /// The contest delay selected by the counterparty, which applies to holder-broadcast transactions
656 pub selected_contest_delay: u16,
659 impl ChannelTransactionParameters {
660 /// Whether the late bound parameters are populated.
661 pub fn is_populated(&self) -> bool {
662 self.counterparty_parameters.is_some() && self.funding_outpoint.is_some()
665 /// Convert the holder/counterparty parameters to broadcaster/countersignatory-organized parameters,
666 /// given that the holder is the broadcaster.
668 /// self.is_populated() must be true before calling this function.
669 pub fn as_holder_broadcastable(&self) -> DirectedChannelTransactionParameters {
670 assert!(self.is_populated(), "self.late_parameters must be set before using as_holder_broadcastable");
671 DirectedChannelTransactionParameters {
673 holder_is_broadcaster: true
677 /// Convert the holder/counterparty parameters to broadcaster/countersignatory-organized parameters,
678 /// given that the counterparty is the broadcaster.
680 /// self.is_populated() must be true before calling this function.
681 pub fn as_counterparty_broadcastable(&self) -> DirectedChannelTransactionParameters {
682 assert!(self.is_populated(), "self.late_parameters must be set before using as_counterparty_broadcastable");
683 DirectedChannelTransactionParameters {
685 holder_is_broadcaster: false
690 impl_writeable_tlv_based!(CounterpartyChannelTransactionParameters, {
691 (0, pubkeys, required),
692 (2, selected_contest_delay, required),
695 impl_writeable_tlv_based!(ChannelTransactionParameters, {
696 (0, holder_pubkeys, required),
697 (2, holder_selected_contest_delay, required),
698 (4, is_outbound_from_holder, required),
699 (6, counterparty_parameters, option),
700 (8, funding_outpoint, option),
703 /// Static channel fields used to build transactions given per-commitment fields, organized by
704 /// broadcaster/countersignatory.
706 /// This is derived from the holder/counterparty-organized ChannelTransactionParameters via the
707 /// as_holder_broadcastable and as_counterparty_broadcastable functions.
708 pub struct DirectedChannelTransactionParameters<'a> {
709 /// The holder's channel static parameters
710 inner: &'a ChannelTransactionParameters,
711 /// Whether the holder is the broadcaster
712 holder_is_broadcaster: bool,
715 impl<'a> DirectedChannelTransactionParameters<'a> {
716 /// Get the channel pubkeys for the broadcaster
717 pub fn broadcaster_pubkeys(&self) -> &ChannelPublicKeys {
718 if self.holder_is_broadcaster {
719 &self.inner.holder_pubkeys
721 &self.inner.counterparty_parameters.as_ref().unwrap().pubkeys
725 /// Get the channel pubkeys for the countersignatory
726 pub fn countersignatory_pubkeys(&self) -> &ChannelPublicKeys {
727 if self.holder_is_broadcaster {
728 &self.inner.counterparty_parameters.as_ref().unwrap().pubkeys
730 &self.inner.holder_pubkeys
734 /// Get the contest delay applicable to the transactions.
735 /// Note that the contest delay was selected by the countersignatory.
736 pub fn contest_delay(&self) -> u16 {
737 let counterparty_parameters = self.inner.counterparty_parameters.as_ref().unwrap();
738 if self.holder_is_broadcaster { counterparty_parameters.selected_contest_delay } else { self.inner.holder_selected_contest_delay }
741 /// Whether the channel is outbound from the broadcaster.
743 /// The boolean representing the side that initiated the channel is
744 /// an input to the commitment number obscure factor computation.
745 pub fn is_outbound(&self) -> bool {
746 if self.holder_is_broadcaster { self.inner.is_outbound_from_holder } else { !self.inner.is_outbound_from_holder }
749 /// The funding outpoint
750 pub fn funding_outpoint(&self) -> OutPoint {
751 self.inner.funding_outpoint.unwrap().into_bitcoin_outpoint()
755 /// Information needed to build and sign a holder's commitment transaction.
757 /// The transaction is only signed once we are ready to broadcast.
759 pub struct HolderCommitmentTransaction {
760 inner: CommitmentTransaction,
761 /// Our counterparty's signature for the transaction
762 pub counterparty_sig: Signature,
763 /// All non-dust counterparty HTLC signatures, in the order they appear in the transaction
764 pub counterparty_htlc_sigs: Vec<Signature>,
765 // Which order the signatures should go in when constructing the final commitment tx witness.
766 // The user should be able to reconstruct this themselves, so we don't bother to expose it.
767 holder_sig_first: bool,
770 impl Deref for HolderCommitmentTransaction {
771 type Target = CommitmentTransaction;
773 fn deref(&self) -> &Self::Target { &self.inner }
776 impl PartialEq for HolderCommitmentTransaction {
777 // We dont care whether we are signed in equality comparison
778 fn eq(&self, o: &Self) -> bool {
779 self.inner == o.inner
783 impl_writeable_tlv_based!(HolderCommitmentTransaction, {
784 (0, inner, required),
785 (2, counterparty_sig, required),
786 (4, holder_sig_first, required),
787 (6, counterparty_htlc_sigs, vec_type),
790 impl HolderCommitmentTransaction {
792 pub fn dummy() -> Self {
793 let secp_ctx = Secp256k1::new();
794 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
795 let dummy_sig = secp_ctx.sign(&secp256k1::Message::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[42; 32]).unwrap());
797 let keys = TxCreationKeys {
798 per_commitment_point: dummy_key.clone(),
799 revocation_key: dummy_key.clone(),
800 broadcaster_htlc_key: dummy_key.clone(),
801 countersignatory_htlc_key: dummy_key.clone(),
802 broadcaster_delayed_payment_key: dummy_key.clone(),
804 let channel_pubkeys = ChannelPublicKeys {
805 funding_pubkey: dummy_key.clone(),
806 revocation_basepoint: dummy_key.clone(),
807 payment_point: dummy_key.clone(),
808 delayed_payment_basepoint: dummy_key.clone(),
809 htlc_basepoint: dummy_key.clone()
811 let channel_parameters = ChannelTransactionParameters {
812 holder_pubkeys: channel_pubkeys.clone(),
813 holder_selected_contest_delay: 0,
814 is_outbound_from_holder: false,
815 counterparty_parameters: Some(CounterpartyChannelTransactionParameters { pubkeys: channel_pubkeys.clone(), selected_contest_delay: 0 }),
816 funding_outpoint: Some(chain::transaction::OutPoint { txid: Default::default(), index: 0 })
818 let mut htlcs_with_aux: Vec<(_, ())> = Vec::new();
819 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());
820 HolderCommitmentTransaction {
822 counterparty_sig: dummy_sig,
823 counterparty_htlc_sigs: Vec::new(),
824 holder_sig_first: false
828 /// Create a new holder transaction with the given counterparty signatures.
829 /// The funding keys are used to figure out which signature should go first when building the transaction for broadcast.
830 pub fn new(commitment_tx: CommitmentTransaction, counterparty_sig: Signature, counterparty_htlc_sigs: Vec<Signature>, holder_funding_key: &PublicKey, counterparty_funding_key: &PublicKey) -> Self {
832 inner: commitment_tx,
834 counterparty_htlc_sigs,
835 holder_sig_first: holder_funding_key.serialize()[..] < counterparty_funding_key.serialize()[..],
839 pub(crate) fn add_holder_sig(&self, funding_redeemscript: &Script, holder_sig: Signature) -> Transaction {
840 // First push the multisig dummy, note that due to BIP147 (NULLDUMMY) it must be a zero-length element.
841 let mut tx = self.inner.built.transaction.clone();
842 tx.input[0].witness.push(Vec::new());
844 if self.holder_sig_first {
845 tx.input[0].witness.push(holder_sig.serialize_der().to_vec());
846 tx.input[0].witness.push(self.counterparty_sig.serialize_der().to_vec());
848 tx.input[0].witness.push(self.counterparty_sig.serialize_der().to_vec());
849 tx.input[0].witness.push(holder_sig.serialize_der().to_vec());
851 tx.input[0].witness[1].push(SigHashType::All as u8);
852 tx.input[0].witness[2].push(SigHashType::All as u8);
854 tx.input[0].witness.push(funding_redeemscript.as_bytes().to_vec());
859 /// A pre-built Bitcoin commitment transaction and its txid.
861 pub struct BuiltCommitmentTransaction {
862 /// The commitment transaction
863 pub transaction: Transaction,
864 /// The txid for the commitment transaction.
866 /// This is provided as a performance optimization, instead of calling transaction.txid()
871 impl_writeable_tlv_based!(BuiltCommitmentTransaction, {
872 (0, transaction, required),
876 impl BuiltCommitmentTransaction {
877 /// Get the SIGHASH_ALL sighash value of the transaction.
879 /// This can be used to verify a signature.
880 pub fn get_sighash_all(&self, funding_redeemscript: &Script, channel_value_satoshis: u64) -> Message {
881 let sighash = &bip143::SigHashCache::new(&self.transaction).signature_hash(0, funding_redeemscript, channel_value_satoshis, SigHashType::All)[..];
882 hash_to_message!(sighash)
885 /// Sign a transaction, either because we are counter-signing the counterparty's transaction or
886 /// because we are about to broadcast a holder transaction.
887 pub fn sign<T: secp256k1::Signing>(&self, funding_key: &SecretKey, funding_redeemscript: &Script, channel_value_satoshis: u64, secp_ctx: &Secp256k1<T>) -> Signature {
888 let sighash = self.get_sighash_all(funding_redeemscript, channel_value_satoshis);
889 secp_ctx.sign(&sighash, funding_key)
893 /// This class tracks the per-transaction information needed to build a closing transaction and will
894 /// actually build it and sign.
896 /// This class can be used inside a signer implementation to generate a signature given the relevant
898 pub struct ClosingTransaction {
899 to_holder_value_sat: u64,
900 to_counterparty_value_sat: u64,
901 to_holder_script: Script,
902 to_counterparty_script: Script,
906 impl ClosingTransaction {
907 /// Construct an object of the class
909 to_holder_value_sat: u64,
910 to_counterparty_value_sat: u64,
911 to_holder_script: Script,
912 to_counterparty_script: Script,
913 funding_outpoint: OutPoint,
915 let built = build_closing_transaction(
916 to_holder_value_sat, to_counterparty_value_sat,
917 to_holder_script.clone(), to_counterparty_script.clone(),
922 to_counterparty_value_sat,
924 to_counterparty_script,
929 /// Trust our pre-built transaction.
931 /// Applies a wrapper which allows access to the transaction.
933 /// This should only be used if you fully trust the builder of this object. It should not
934 /// be used by an external signer - instead use the verify function.
935 pub fn trust(&self) -> TrustedClosingTransaction {
936 TrustedClosingTransaction { inner: self }
939 /// Verify our pre-built transaction.
941 /// Applies a wrapper which allows access to the transaction.
943 /// An external validating signer must call this method before signing
944 /// or using the built transaction.
945 pub fn verify(&self, funding_outpoint: OutPoint) -> Result<TrustedClosingTransaction, ()> {
946 let built = build_closing_transaction(
947 self.to_holder_value_sat, self.to_counterparty_value_sat,
948 self.to_holder_script.clone(), self.to_counterparty_script.clone(),
951 if self.built != built {
954 Ok(TrustedClosingTransaction { inner: self })
957 /// The value to be sent to the holder, or zero if the output will be omitted
958 pub fn to_holder_value_sat(&self) -> u64 {
959 self.to_holder_value_sat
962 /// The value to be sent to the counterparty, or zero if the output will be omitted
963 pub fn to_counterparty_value_sat(&self) -> u64 {
964 self.to_counterparty_value_sat
967 /// The destination of the holder's output
968 pub fn to_holder_script(&self) -> &Script {
969 &self.to_holder_script
972 /// The destination of the counterparty's output
973 pub fn to_counterparty_script(&self) -> &Script {
974 &self.to_counterparty_script
978 /// A wrapper on ClosingTransaction indicating that the built bitcoin
979 /// transaction is trusted.
981 /// See trust() and verify() functions on CommitmentTransaction.
983 /// This structure implements Deref.
984 pub struct TrustedClosingTransaction<'a> {
985 inner: &'a ClosingTransaction,
988 impl<'a> Deref for TrustedClosingTransaction<'a> {
989 type Target = ClosingTransaction;
991 fn deref(&self) -> &Self::Target { self.inner }
994 impl<'a> TrustedClosingTransaction<'a> {
995 /// The pre-built Bitcoin commitment transaction
996 pub fn built_transaction(&self) -> &Transaction {
1000 /// Get the SIGHASH_ALL sighash value of the transaction.
1002 /// This can be used to verify a signature.
1003 pub fn get_sighash_all(&self, funding_redeemscript: &Script, channel_value_satoshis: u64) -> Message {
1004 let sighash = &bip143::SigHashCache::new(&self.inner.built).signature_hash(0, funding_redeemscript, channel_value_satoshis, SigHashType::All)[..];
1005 hash_to_message!(sighash)
1008 /// Sign a transaction, either because we are counter-signing the counterparty's transaction or
1009 /// because we are about to broadcast a holder transaction.
1010 pub fn sign<T: secp256k1::Signing>(&self, funding_key: &SecretKey, funding_redeemscript: &Script, channel_value_satoshis: u64, secp_ctx: &Secp256k1<T>) -> Signature {
1011 let sighash = self.get_sighash_all(funding_redeemscript, channel_value_satoshis);
1012 secp_ctx.sign(&sighash, funding_key)
1016 /// This class tracks the per-transaction information needed to build a commitment transaction and will
1017 /// actually build it and sign. It is used for holder transactions that we sign only when needed
1018 /// and for transactions we sign for the counterparty.
1020 /// This class can be used inside a signer implementation to generate a signature given the relevant
1023 pub struct CommitmentTransaction {
1024 commitment_number: u64,
1025 to_broadcaster_value_sat: u64,
1026 to_countersignatory_value_sat: u64,
1027 feerate_per_kw: u32,
1028 htlcs: Vec<HTLCOutputInCommitment>,
1029 // A boolean that is serialization backwards-compatible
1030 opt_anchors: Option<()>,
1031 // A cache of the parties' pubkeys required to construct the transaction, see doc for trust()
1032 keys: TxCreationKeys,
1033 // For access to the pre-built transaction, see doc for trust()
1034 built: BuiltCommitmentTransaction,
1037 impl PartialEq for CommitmentTransaction {
1038 fn eq(&self, o: &Self) -> bool {
1039 let eq = self.commitment_number == o.commitment_number &&
1040 self.to_broadcaster_value_sat == o.to_broadcaster_value_sat &&
1041 self.to_countersignatory_value_sat == o.to_countersignatory_value_sat &&
1042 self.feerate_per_kw == o.feerate_per_kw &&
1043 self.htlcs == o.htlcs &&
1044 self.opt_anchors == o.opt_anchors &&
1045 self.keys == o.keys;
1047 debug_assert_eq!(self.built.transaction, o.built.transaction);
1048 debug_assert_eq!(self.built.txid, o.built.txid);
1054 impl_writeable_tlv_based!(CommitmentTransaction, {
1055 (0, commitment_number, required),
1056 (2, to_broadcaster_value_sat, required),
1057 (4, to_countersignatory_value_sat, required),
1058 (6, feerate_per_kw, required),
1059 (8, keys, required),
1060 (10, built, required),
1061 (12, htlcs, vec_type),
1062 (14, opt_anchors, option),
1065 impl CommitmentTransaction {
1066 /// Construct an object of the class while assigning transaction output indices to HTLCs.
1068 /// Populates HTLCOutputInCommitment.transaction_output_index in htlcs_with_aux.
1070 /// The generic T allows the caller to match the HTLC output index with auxiliary data.
1071 /// This auxiliary data is not stored in this object.
1073 /// Only include HTLCs that are above the dust limit for the channel.
1075 /// (C-not exported) due to the generic though we likely should expose a version without
1076 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 {
1077 // Sort outputs and populate output indices while keeping track of the auxiliary data
1078 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();
1080 let (obscured_commitment_transaction_number, txins) = Self::internal_build_inputs(commitment_number, channel_parameters);
1081 let transaction = Self::make_transaction(obscured_commitment_transaction_number, txins, outputs);
1082 let txid = transaction.txid();
1083 CommitmentTransaction {
1085 to_broadcaster_value_sat,
1086 to_countersignatory_value_sat,
1089 opt_anchors: if opt_anchors { Some(()) } else { None },
1091 built: BuiltCommitmentTransaction {
1098 fn internal_rebuild_transaction(&self, keys: &TxCreationKeys, channel_parameters: &DirectedChannelTransactionParameters, broadcaster_funding_key: &PublicKey, countersignatory_funding_key: &PublicKey) -> Result<BuiltCommitmentTransaction, ()> {
1099 let (obscured_commitment_transaction_number, txins) = Self::internal_build_inputs(self.commitment_number, channel_parameters);
1101 let mut htlcs_with_aux = self.htlcs.iter().map(|h| (h.clone(), ())).collect();
1102 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)?;
1104 let transaction = Self::make_transaction(obscured_commitment_transaction_number, txins, outputs);
1105 let txid = transaction.txid();
1106 let built_transaction = BuiltCommitmentTransaction {
1110 Ok(built_transaction)
1113 fn make_transaction(obscured_commitment_transaction_number: u64, txins: Vec<TxIn>, outputs: Vec<TxOut>) -> Transaction {
1116 lock_time: ((0x20 as u32) << 8 * 3) | ((obscured_commitment_transaction_number & 0xffffffu64) as u32),
1122 // This is used in two cases:
1123 // - initial sorting of outputs / HTLCs in the constructor, in which case T is auxiliary data the
1124 // caller needs to have sorted together with the HTLCs so it can keep track of the output index
1125 // - building of a bitcoin transaction during a verify() call, in which case T is just ()
1126 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>), ()> {
1127 let countersignatory_pubkeys = channel_parameters.countersignatory_pubkeys();
1128 let contest_delay = channel_parameters.contest_delay();
1130 let mut txouts: Vec<(TxOut, Option<&mut HTLCOutputInCommitment>)> = Vec::new();
1132 if to_countersignatory_value_sat > 0 {
1133 let script = script_for_p2wpkh(&countersignatory_pubkeys.payment_point);
1136 script_pubkey: script.clone(),
1137 value: to_countersignatory_value_sat,
1143 if to_broadcaster_value_sat > 0 {
1144 let redeem_script = get_revokeable_redeemscript(
1145 &keys.revocation_key,
1147 &keys.broadcaster_delayed_payment_key,
1151 script_pubkey: redeem_script.to_v0_p2wsh(),
1152 value: to_broadcaster_value_sat,
1159 if to_broadcaster_value_sat > 0 || !htlcs_with_aux.is_empty() {
1160 let anchor_script = get_anchor_redeemscript(broadcaster_funding_key);
1163 script_pubkey: anchor_script.to_v0_p2wsh(),
1164 value: ANCHOR_OUTPUT_VALUE_SATOSHI,
1170 if to_countersignatory_value_sat > 0 || !htlcs_with_aux.is_empty() {
1171 let anchor_script = get_anchor_redeemscript(countersignatory_funding_key);
1174 script_pubkey: anchor_script.to_v0_p2wsh(),
1175 value: ANCHOR_OUTPUT_VALUE_SATOSHI,
1182 let mut htlcs = Vec::with_capacity(htlcs_with_aux.len());
1183 for (htlc, _) in htlcs_with_aux {
1184 let script = chan_utils::get_htlc_redeemscript(&htlc, &keys);
1186 script_pubkey: script.to_v0_p2wsh(),
1187 value: htlc.amount_msat / 1000,
1189 txouts.push((txout, Some(htlc)));
1192 // Sort output in BIP-69 order (amount, scriptPubkey). Tie-breaks based on HTLC
1193 // CLTV expiration height.
1194 sort_outputs(&mut txouts, |a, b| {
1195 if let &Some(ref a_htlcout) = a {
1196 if let &Some(ref b_htlcout) = b {
1197 a_htlcout.cltv_expiry.cmp(&b_htlcout.cltv_expiry)
1198 // Note that due to hash collisions, we have to have a fallback comparison
1199 // here for fuzztarget mode (otherwise at least chanmon_fail_consistency
1201 .then(a_htlcout.payment_hash.0.cmp(&b_htlcout.payment_hash.0))
1202 // For non-HTLC outputs, if they're copying our SPK we don't really care if we
1203 // close the channel due to mismatches - they're doing something dumb:
1204 } else { cmp::Ordering::Equal }
1205 } else { cmp::Ordering::Equal }
1208 let mut outputs = Vec::with_capacity(txouts.len());
1209 for (idx, out) in txouts.drain(..).enumerate() {
1210 if let Some(htlc) = out.1 {
1211 htlc.transaction_output_index = Some(idx as u32);
1212 htlcs.push(htlc.clone());
1214 outputs.push(out.0);
1216 Ok((outputs, htlcs))
1219 fn internal_build_inputs(commitment_number: u64, channel_parameters: &DirectedChannelTransactionParameters) -> (u64, Vec<TxIn>) {
1220 let broadcaster_pubkeys = channel_parameters.broadcaster_pubkeys();
1221 let countersignatory_pubkeys = channel_parameters.countersignatory_pubkeys();
1222 let commitment_transaction_number_obscure_factor = get_commitment_transaction_number_obscure_factor(
1223 &broadcaster_pubkeys.payment_point,
1224 &countersignatory_pubkeys.payment_point,
1225 channel_parameters.is_outbound(),
1228 let obscured_commitment_transaction_number =
1229 commitment_transaction_number_obscure_factor ^ (INITIAL_COMMITMENT_NUMBER - commitment_number);
1232 let mut ins: Vec<TxIn> = Vec::new();
1234 previous_output: channel_parameters.funding_outpoint(),
1235 script_sig: Script::new(),
1236 sequence: ((0x80 as u32) << 8 * 3)
1237 | ((obscured_commitment_transaction_number >> 3 * 8) as u32),
1238 witness: Vec::new(),
1242 (obscured_commitment_transaction_number, txins)
1245 /// The backwards-counting commitment number
1246 pub fn commitment_number(&self) -> u64 {
1247 self.commitment_number
1250 /// The value to be sent to the broadcaster
1251 pub fn to_broadcaster_value_sat(&self) -> u64 {
1252 self.to_broadcaster_value_sat
1255 /// The value to be sent to the counterparty
1256 pub fn to_countersignatory_value_sat(&self) -> u64 {
1257 self.to_countersignatory_value_sat
1260 /// The feerate paid per 1000-weight-unit in this commitment transaction.
1261 pub fn feerate_per_kw(&self) -> u32 {
1265 /// The non-dust HTLCs (direction, amt, height expiration, hash, transaction output index)
1266 /// which were included in this commitment transaction in output order.
1267 /// The transaction index is always populated.
1269 /// (C-not exported) as we cannot currently convert Vec references to/from C, though we should
1270 /// expose a less effecient version which creates a Vec of references in the future.
1271 pub fn htlcs(&self) -> &Vec<HTLCOutputInCommitment> {
1275 /// Trust our pre-built transaction and derived transaction creation public keys.
1277 /// Applies a wrapper which allows access to these fields.
1279 /// This should only be used if you fully trust the builder of this object. It should not
1280 /// be used by an external signer - instead use the verify function.
1281 pub fn trust(&self) -> TrustedCommitmentTransaction {
1282 TrustedCommitmentTransaction { inner: self }
1285 /// Verify our pre-built transaction and derived transaction creation public keys.
1287 /// Applies a wrapper which allows access to these fields.
1289 /// An external validating signer must call this method before signing
1290 /// or using the built transaction.
1291 pub fn verify<T: secp256k1::Signing + secp256k1::Verification>(&self, channel_parameters: &DirectedChannelTransactionParameters, broadcaster_keys: &ChannelPublicKeys, countersignatory_keys: &ChannelPublicKeys, secp_ctx: &Secp256k1<T>) -> Result<TrustedCommitmentTransaction, ()> {
1292 // This is the only field of the key cache that we trust
1293 let per_commitment_point = self.keys.per_commitment_point;
1294 let keys = TxCreationKeys::from_channel_static_keys(&per_commitment_point, broadcaster_keys, countersignatory_keys, secp_ctx).unwrap();
1295 if keys != self.keys {
1298 let tx = self.internal_rebuild_transaction(&keys, channel_parameters, &broadcaster_keys.funding_pubkey, &countersignatory_keys.funding_pubkey)?;
1299 if self.built.transaction != tx.transaction || self.built.txid != tx.txid {
1302 Ok(TrustedCommitmentTransaction { inner: self })
1306 /// A wrapper on CommitmentTransaction indicating that the derived fields (the built bitcoin
1307 /// transaction and the transaction creation keys) are trusted.
1309 /// See trust() and verify() functions on CommitmentTransaction.
1311 /// This structure implements Deref.
1312 pub struct TrustedCommitmentTransaction<'a> {
1313 inner: &'a CommitmentTransaction,
1316 impl<'a> Deref for TrustedCommitmentTransaction<'a> {
1317 type Target = CommitmentTransaction;
1319 fn deref(&self) -> &Self::Target { self.inner }
1322 impl<'a> TrustedCommitmentTransaction<'a> {
1323 /// The transaction ID of the built Bitcoin transaction
1324 pub fn txid(&self) -> Txid {
1325 self.inner.built.txid
1328 /// The pre-built Bitcoin commitment transaction
1329 pub fn built_transaction(&self) -> &BuiltCommitmentTransaction {
1333 /// The pre-calculated transaction creation public keys.
1334 pub fn keys(&self) -> &TxCreationKeys {
1338 /// Get a signature for each HTLC which was included in the commitment transaction (ie for
1339 /// which HTLCOutputInCommitment::transaction_output_index.is_some()).
1341 /// The returned Vec has one entry for each HTLC, and in the same order.
1342 pub fn get_htlc_sigs<T: secp256k1::Signing>(&self, htlc_base_key: &SecretKey, channel_parameters: &DirectedChannelTransactionParameters, secp_ctx: &Secp256k1<T>) -> Result<Vec<Signature>, ()> {
1343 let inner = self.inner;
1344 let keys = &inner.keys;
1345 let txid = inner.built.txid;
1346 let mut ret = Vec::with_capacity(inner.htlcs.len());
1347 let holder_htlc_key = derive_private_key(secp_ctx, &inner.keys.per_commitment_point, htlc_base_key).map_err(|_| ())?;
1349 for this_htlc in inner.htlcs.iter() {
1350 assert!(this_htlc.transaction_output_index.is_some());
1351 let htlc_tx = build_htlc_transaction(&txid, inner.feerate_per_kw, channel_parameters.contest_delay(), &this_htlc, &keys.broadcaster_delayed_payment_key, &keys.revocation_key);
1353 let htlc_redeemscript = get_htlc_redeemscript_with_explicit_keys(&this_htlc, &keys.broadcaster_htlc_key, &keys.countersignatory_htlc_key, &keys.revocation_key);
1355 let sighash = hash_to_message!(&bip143::SigHashCache::new(&htlc_tx).signature_hash(0, &htlc_redeemscript, this_htlc.amount_msat / 1000, SigHashType::All)[..]);
1356 ret.push(secp_ctx.sign(&sighash, &holder_htlc_key));
1361 /// Gets a signed HTLC transaction given a preimage (for !htlc.offered) and the holder HTLC transaction signature.
1362 pub(crate) fn get_signed_htlc_tx(&self, channel_parameters: &DirectedChannelTransactionParameters, htlc_index: usize, counterparty_signature: &Signature, signature: &Signature, preimage: &Option<PaymentPreimage>) -> Transaction {
1363 let inner = self.inner;
1364 let keys = &inner.keys;
1365 let txid = inner.built.txid;
1366 let this_htlc = &inner.htlcs[htlc_index];
1367 assert!(this_htlc.transaction_output_index.is_some());
1368 // if we don't have preimage for an HTLC-Success, we can't generate an HTLC transaction.
1369 if !this_htlc.offered && preimage.is_none() { unreachable!(); }
1370 // Further, we should never be provided the preimage for an HTLC-Timeout transaction.
1371 if this_htlc.offered && preimage.is_some() { unreachable!(); }
1373 let mut htlc_tx = build_htlc_transaction(&txid, inner.feerate_per_kw, channel_parameters.contest_delay(), &this_htlc, &keys.broadcaster_delayed_payment_key, &keys.revocation_key);
1375 let htlc_redeemscript = get_htlc_redeemscript_with_explicit_keys(&this_htlc, &keys.broadcaster_htlc_key, &keys.countersignatory_htlc_key, &keys.revocation_key);
1377 // First push the multisig dummy, note that due to BIP147 (NULLDUMMY) it must be a zero-length element.
1378 htlc_tx.input[0].witness.push(Vec::new());
1380 htlc_tx.input[0].witness.push(counterparty_signature.serialize_der().to_vec());
1381 htlc_tx.input[0].witness.push(signature.serialize_der().to_vec());
1382 htlc_tx.input[0].witness[1].push(SigHashType::All as u8);
1383 htlc_tx.input[0].witness[2].push(SigHashType::All as u8);
1385 if this_htlc.offered {
1386 // Due to BIP146 (MINIMALIF) this must be a zero-length element to relay.
1387 htlc_tx.input[0].witness.push(Vec::new());
1389 htlc_tx.input[0].witness.push(preimage.unwrap().0.to_vec());
1392 htlc_tx.input[0].witness.push(htlc_redeemscript.as_bytes().to_vec());
1397 /// Commitment transaction numbers which appear in the transactions themselves are XOR'd with a
1398 /// shared secret first. This prevents on-chain observers from discovering how many commitment
1399 /// transactions occurred in a channel before it was closed.
1401 /// This function gets the shared secret from relevant channel public keys and can be used to
1402 /// "decrypt" the commitment transaction number given a commitment transaction on-chain.
1403 pub fn get_commitment_transaction_number_obscure_factor(
1404 broadcaster_payment_basepoint: &PublicKey,
1405 countersignatory_payment_basepoint: &PublicKey,
1406 outbound_from_broadcaster: bool,
1408 let mut sha = Sha256::engine();
1410 if outbound_from_broadcaster {
1411 sha.input(&broadcaster_payment_basepoint.serialize());
1412 sha.input(&countersignatory_payment_basepoint.serialize());
1414 sha.input(&countersignatory_payment_basepoint.serialize());
1415 sha.input(&broadcaster_payment_basepoint.serialize());
1417 let res = Sha256::from_engine(sha).into_inner();
1419 ((res[26] as u64) << 5 * 8)
1420 | ((res[27] as u64) << 4 * 8)
1421 | ((res[28] as u64) << 3 * 8)
1422 | ((res[29] as u64) << 2 * 8)
1423 | ((res[30] as u64) << 1 * 8)
1424 | ((res[31] as u64) << 0 * 8)
1427 fn script_for_p2wpkh(key: &PublicKey) -> Script {
1428 Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0)
1429 .push_slice(&WPubkeyHash::hash(&key.serialize())[..])
1435 use super::CounterpartyCommitmentSecrets;
1438 use ln::chan_utils::{CommitmentTransaction, TxCreationKeys, ChannelTransactionParameters, CounterpartyChannelTransactionParameters, HTLCOutputInCommitment};
1439 use bitcoin::secp256k1::{PublicKey, SecretKey, Secp256k1};
1440 use util::test_utils;
1441 use chain::keysinterface::{KeysInterface, BaseSign};
1442 use bitcoin::Network;
1443 use ln::PaymentHash;
1447 let secp_ctx = Secp256k1::new();
1449 let seed = [42; 32];
1450 let network = Network::Testnet;
1451 let keys_provider = test_utils::TestKeysInterface::new(&seed, network);
1452 let signer = keys_provider.get_channel_signer(false, 3000);
1453 let counterparty_signer = keys_provider.get_channel_signer(false, 3000);
1454 let delayed_payment_base = &signer.pubkeys().delayed_payment_basepoint;
1455 let per_commitment_secret = SecretKey::from_slice(&hex::decode("1f1e1d1c1b1a191817161514131211100f0e0d0c0b0a09080706050403020100").unwrap()[..]).unwrap();
1456 let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &per_commitment_secret);
1457 let htlc_basepoint = &signer.pubkeys().htlc_basepoint;
1458 let holder_pubkeys = signer.pubkeys();
1459 let counterparty_pubkeys = counterparty_signer.pubkeys();
1460 let keys = TxCreationKeys::derive_new(&secp_ctx, &per_commitment_point, delayed_payment_base, htlc_basepoint, &counterparty_pubkeys.revocation_basepoint, &counterparty_pubkeys.htlc_basepoint).unwrap();
1461 let channel_parameters = ChannelTransactionParameters {
1462 holder_pubkeys: holder_pubkeys.clone(),
1463 holder_selected_contest_delay: 0,
1464 is_outbound_from_holder: false,
1465 counterparty_parameters: Some(CounterpartyChannelTransactionParameters { pubkeys: counterparty_pubkeys.clone(), selected_contest_delay: 0 }),
1466 funding_outpoint: Some(chain::transaction::OutPoint { txid: Default::default(), index: 0 })
1469 let mut htlcs_with_aux: Vec<(_, ())> = Vec::new();
1471 // Generate broadcaster and counterparty outputs
1472 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1475 holder_pubkeys.funding_pubkey,
1476 counterparty_pubkeys.funding_pubkey,
1478 &mut htlcs_with_aux, &channel_parameters.as_holder_broadcastable()
1480 assert_eq!(tx.built.transaction.output.len(), 2);
1482 // Generate broadcaster and counterparty outputs as well as two anchors
1483 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1486 holder_pubkeys.funding_pubkey,
1487 counterparty_pubkeys.funding_pubkey,
1489 &mut htlcs_with_aux, &channel_parameters.as_holder_broadcastable()
1491 assert_eq!(tx.built.transaction.output.len(), 4);
1493 // Generate broadcaster output and anchor
1494 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1497 holder_pubkeys.funding_pubkey,
1498 counterparty_pubkeys.funding_pubkey,
1500 &mut htlcs_with_aux, &channel_parameters.as_holder_broadcastable()
1502 assert_eq!(tx.built.transaction.output.len(), 2);
1504 // Generate counterparty output and anchor
1505 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1508 holder_pubkeys.funding_pubkey,
1509 counterparty_pubkeys.funding_pubkey,
1511 &mut htlcs_with_aux, &channel_parameters.as_holder_broadcastable()
1513 assert_eq!(tx.built.transaction.output.len(), 2);
1515 // Generate broadcaster output, an HTLC output and two anchors
1516 let payment_hash = PaymentHash([42; 32]);
1517 let htlc_info = HTLCOutputInCommitment {
1519 amount_msat: 1000000,
1522 transaction_output_index: None,
1525 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1528 holder_pubkeys.funding_pubkey,
1529 counterparty_pubkeys.funding_pubkey,
1531 &mut vec![(htlc_info, ())], &channel_parameters.as_holder_broadcastable()
1533 assert_eq!(tx.built.transaction.output.len(), 4);
1537 fn test_per_commitment_storage() {
1538 // Test vectors from BOLT 3:
1539 let mut secrets: Vec<[u8; 32]> = Vec::new();
1542 macro_rules! test_secrets {
1544 let mut idx = 281474976710655;
1545 for secret in secrets.iter() {
1546 assert_eq!(monitor.get_secret(idx).unwrap(), *secret);
1549 assert_eq!(monitor.get_min_seen_secret(), idx + 1);
1550 assert!(monitor.get_secret(idx).is_none());
1555 // insert_secret correct sequence
1556 monitor = CounterpartyCommitmentSecrets::new();
1559 secrets.push([0; 32]);
1560 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1561 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1564 secrets.push([0; 32]);
1565 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1566 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1569 secrets.push([0; 32]);
1570 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1571 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1574 secrets.push([0; 32]);
1575 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1576 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
1579 secrets.push([0; 32]);
1580 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1581 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
1584 secrets.push([0; 32]);
1585 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1586 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
1589 secrets.push([0; 32]);
1590 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1591 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
1594 secrets.push([0; 32]);
1595 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1596 monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap();
1601 // insert_secret #1 incorrect
1602 monitor = CounterpartyCommitmentSecrets::new();
1605 secrets.push([0; 32]);
1606 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
1607 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1610 secrets.push([0; 32]);
1611 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1612 assert!(monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).is_err());
1616 // insert_secret #2 incorrect (#1 derived from incorrect)
1617 monitor = CounterpartyCommitmentSecrets::new();
1620 secrets.push([0; 32]);
1621 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
1622 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1625 secrets.push([0; 32]);
1626 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
1627 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1630 secrets.push([0; 32]);
1631 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1632 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1635 secrets.push([0; 32]);
1636 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1637 assert!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).is_err());
1641 // insert_secret #3 incorrect
1642 monitor = CounterpartyCommitmentSecrets::new();
1645 secrets.push([0; 32]);
1646 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1647 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1650 secrets.push([0; 32]);
1651 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1652 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1655 secrets.push([0; 32]);
1656 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
1657 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1660 secrets.push([0; 32]);
1661 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1662 assert!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).is_err());
1666 // insert_secret #4 incorrect (1,2,3 derived from incorrect)
1667 monitor = CounterpartyCommitmentSecrets::new();
1670 secrets.push([0; 32]);
1671 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
1672 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1675 secrets.push([0; 32]);
1676 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
1677 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1680 secrets.push([0; 32]);
1681 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
1682 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1685 secrets.push([0; 32]);
1686 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("ba65d7b0ef55a3ba300d4e87af29868f394f8f138d78a7011669c79b37b936f4").unwrap());
1687 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
1690 secrets.push([0; 32]);
1691 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1692 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
1695 secrets.push([0; 32]);
1696 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1697 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
1700 secrets.push([0; 32]);
1701 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1702 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
1705 secrets.push([0; 32]);
1706 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1707 assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
1711 // insert_secret #5 incorrect
1712 monitor = CounterpartyCommitmentSecrets::new();
1715 secrets.push([0; 32]);
1716 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1717 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1720 secrets.push([0; 32]);
1721 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1722 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1725 secrets.push([0; 32]);
1726 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1727 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1730 secrets.push([0; 32]);
1731 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1732 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
1735 secrets.push([0; 32]);
1736 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
1737 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
1740 secrets.push([0; 32]);
1741 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1742 assert!(monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).is_err());
1746 // insert_secret #6 incorrect (5 derived from incorrect)
1747 monitor = CounterpartyCommitmentSecrets::new();
1750 secrets.push([0; 32]);
1751 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1752 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1755 secrets.push([0; 32]);
1756 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1757 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1760 secrets.push([0; 32]);
1761 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1762 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1765 secrets.push([0; 32]);
1766 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1767 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
1770 secrets.push([0; 32]);
1771 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
1772 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
1775 secrets.push([0; 32]);
1776 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("b7e76a83668bde38b373970155c868a653304308f9896692f904a23731224bb1").unwrap());
1777 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
1780 secrets.push([0; 32]);
1781 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1782 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
1785 secrets.push([0; 32]);
1786 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1787 assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
1791 // insert_secret #7 incorrect
1792 monitor = CounterpartyCommitmentSecrets::new();
1795 secrets.push([0; 32]);
1796 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1797 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1800 secrets.push([0; 32]);
1801 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1802 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1805 secrets.push([0; 32]);
1806 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1807 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1810 secrets.push([0; 32]);
1811 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1812 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
1815 secrets.push([0; 32]);
1816 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1817 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
1820 secrets.push([0; 32]);
1821 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1822 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
1825 secrets.push([0; 32]);
1826 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("e7971de736e01da8ed58b94c2fc216cb1dca9e326f3a96e7194fe8ea8af6c0a3").unwrap());
1827 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
1830 secrets.push([0; 32]);
1831 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1832 assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
1836 // insert_secret #8 incorrect
1837 monitor = CounterpartyCommitmentSecrets::new();
1840 secrets.push([0; 32]);
1841 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1842 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1845 secrets.push([0; 32]);
1846 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1847 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1850 secrets.push([0; 32]);
1851 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1852 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1855 secrets.push([0; 32]);
1856 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1857 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
1860 secrets.push([0; 32]);
1861 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1862 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
1865 secrets.push([0; 32]);
1866 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1867 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
1870 secrets.push([0; 32]);
1871 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1872 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
1875 secrets.push([0; 32]);
1876 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a7efbc61aac46d34f77778bac22c8a20c6a46ca460addc49009bda875ec88fa4").unwrap());
1877 assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());