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, EcdsaSighashType};
16 use bitcoin::util::sighash;
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::{SecretKey, PublicKey, Scalar};
30 use bitcoin::secp256k1::{Secp256k1, ecdsa::Signature, Message};
31 use bitcoin::secp256k1::Error as SecpError;
32 use bitcoin::{PackedLockTime, secp256k1, Sequence, Witness};
38 use util::transaction_utils::sort_outputs;
39 use ln::channel::{INITIAL_COMMITMENT_NUMBER, ANCHOR_OUTPUT_VALUE_SATOSHI};
42 use util::crypto::sign;
44 pub(crate) const MAX_HTLCS: u16 = 483;
45 pub(crate) const OFFERED_HTLC_SCRIPT_WEIGHT: usize = 133;
46 pub(crate) const OFFERED_HTLC_SCRIPT_WEIGHT_ANCHORS: usize = 136;
47 // The weight of `accepted_htlc_script` can vary in function of its CLTV argument value. We define a
48 // range that encompasses both its non-anchors and anchors variants.
49 pub(crate) const MIN_ACCEPTED_HTLC_SCRIPT_WEIGHT: usize = 136;
50 pub(crate) const MAX_ACCEPTED_HTLC_SCRIPT_WEIGHT: usize = 143;
52 /// Gets the weight for an HTLC-Success transaction.
54 pub fn htlc_success_tx_weight(opt_anchors: bool) -> u64 {
55 const HTLC_SUCCESS_TX_WEIGHT: u64 = 703;
56 const HTLC_SUCCESS_ANCHOR_TX_WEIGHT: u64 = 706;
57 if opt_anchors { HTLC_SUCCESS_ANCHOR_TX_WEIGHT } else { HTLC_SUCCESS_TX_WEIGHT }
60 /// Gets the weight for an HTLC-Timeout transaction.
62 pub fn htlc_timeout_tx_weight(opt_anchors: bool) -> u64 {
63 const HTLC_TIMEOUT_TX_WEIGHT: u64 = 663;
64 const HTLC_TIMEOUT_ANCHOR_TX_WEIGHT: u64 = 666;
65 if opt_anchors { HTLC_TIMEOUT_ANCHOR_TX_WEIGHT } else { HTLC_TIMEOUT_TX_WEIGHT }
68 #[derive(PartialEq, Eq)]
69 pub(crate) enum HTLCClaim {
78 /// Check if a given input witness attempts to claim a HTLC.
79 pub(crate) fn from_witness(witness: &Witness) -> Option<Self> {
80 debug_assert_eq!(OFFERED_HTLC_SCRIPT_WEIGHT_ANCHORS, MIN_ACCEPTED_HTLC_SCRIPT_WEIGHT);
81 if witness.len() < 2 {
84 let witness_script = witness.last().unwrap();
85 let second_to_last = witness.second_to_last().unwrap();
86 if witness_script.len() == OFFERED_HTLC_SCRIPT_WEIGHT {
87 if witness.len() == 3 && second_to_last.len() == 33 {
88 // <revocation sig> <revocationpubkey> <witness_script>
89 Some(Self::Revocation)
90 } else if witness.len() == 3 && second_to_last.len() == 32 {
91 // <remotehtlcsig> <payment_preimage> <witness_script>
92 Some(Self::OfferedPreimage)
93 } else if witness.len() == 5 && second_to_last.len() == 0 {
94 // 0 <remotehtlcsig> <localhtlcsig> <> <witness_script>
95 Some(Self::OfferedTimeout)
99 } else if witness_script.len() == OFFERED_HTLC_SCRIPT_WEIGHT_ANCHORS {
100 // It's possible for the weight of `offered_htlc_script` and `accepted_htlc_script` to
101 // match so we check for both here.
102 if witness.len() == 3 && second_to_last.len() == 33 {
103 // <revocation sig> <revocationpubkey> <witness_script>
104 Some(Self::Revocation)
105 } else if witness.len() == 3 && second_to_last.len() == 32 {
106 // <remotehtlcsig> <payment_preimage> <witness_script>
107 Some(Self::OfferedPreimage)
108 } else if witness.len() == 5 && second_to_last.len() == 0 {
109 // 0 <remotehtlcsig> <localhtlcsig> <> <witness_script>
110 Some(Self::OfferedTimeout)
111 } else if witness.len() == 3 && second_to_last.len() == 0 {
112 // <remotehtlcsig> <> <witness_script>
113 Some(Self::AcceptedTimeout)
114 } else if witness.len() == 5 && second_to_last.len() == 32 {
115 // 0 <remotehtlcsig> <localhtlcsig> <payment_preimage> <witness_script>
116 Some(Self::AcceptedPreimage)
120 } else if witness_script.len() > MIN_ACCEPTED_HTLC_SCRIPT_WEIGHT &&
121 witness_script.len() <= MAX_ACCEPTED_HTLC_SCRIPT_WEIGHT {
122 // Handle remaining range of ACCEPTED_HTLC_SCRIPT_WEIGHT.
123 if witness.len() == 3 && second_to_last.len() == 33 {
124 // <revocation sig> <revocationpubkey> <witness_script>
125 Some(Self::Revocation)
126 } else if witness.len() == 3 && second_to_last.len() == 0 {
127 // <remotehtlcsig> <> <witness_script>
128 Some(Self::AcceptedTimeout)
129 } else if witness.len() == 5 && second_to_last.len() == 32 {
130 // 0 <remotehtlcsig> <localhtlcsig> <payment_preimage> <witness_script>
131 Some(Self::AcceptedPreimage)
141 // Various functions for key derivation and transaction creation for use within channels. Primarily
142 // used in Channel and ChannelMonitor.
144 /// Build the commitment secret from the seed and the commitment number
145 pub fn build_commitment_secret(commitment_seed: &[u8; 32], idx: u64) -> [u8; 32] {
146 let mut res: [u8; 32] = commitment_seed.clone();
149 if idx & (1 << bitpos) == (1 << bitpos) {
150 res[bitpos / 8] ^= 1 << (bitpos & 7);
151 res = Sha256::hash(&res).into_inner();
157 /// Build a closing transaction
158 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 {
160 let mut ins: Vec<TxIn> = Vec::new();
162 previous_output: funding_outpoint,
163 script_sig: Script::new(),
164 sequence: Sequence::MAX,
165 witness: Witness::new(),
170 let mut txouts: Vec<(TxOut, ())> = Vec::new();
172 if to_counterparty_value_sat > 0 {
174 script_pubkey: to_counterparty_script,
175 value: to_counterparty_value_sat
179 if to_holder_value_sat > 0 {
181 script_pubkey: to_holder_script,
182 value: to_holder_value_sat
186 transaction_utils::sort_outputs(&mut txouts, |_, _| { cmp::Ordering::Equal }); // Ordering doesnt matter if they used our pubkey...
188 let mut outputs: Vec<TxOut> = Vec::new();
189 for out in txouts.drain(..) {
195 lock_time: PackedLockTime::ZERO,
201 /// Implements the per-commitment secret storage scheme from
202 /// [BOLT 3](https://github.com/lightning/bolts/blob/dcbf8583976df087c79c3ce0b535311212e6812d/03-transactions.md#efficient-per-commitment-secret-storage).
204 /// Allows us to keep track of all of the revocation secrets of our counterparty in just 50*32 bytes
207 pub struct CounterpartyCommitmentSecrets {
208 old_secrets: [([u8; 32], u64); 49],
211 impl Eq for CounterpartyCommitmentSecrets {}
212 impl PartialEq for CounterpartyCommitmentSecrets {
213 fn eq(&self, other: &Self) -> bool {
214 for (&(ref secret, ref idx), &(ref o_secret, ref o_idx)) in self.old_secrets.iter().zip(other.old_secrets.iter()) {
215 if secret != o_secret || idx != o_idx {
223 impl CounterpartyCommitmentSecrets {
224 /// Creates a new empty `CounterpartyCommitmentSecrets` structure.
225 pub fn new() -> Self {
226 Self { old_secrets: [([0; 32], 1 << 48); 49], }
230 fn place_secret(idx: u64) -> u8 {
232 if idx & (1 << i) == (1 << i) {
239 /// Returns the minimum index of all stored secrets. Note that indexes start
240 /// at 1 << 48 and get decremented by one for each new secret.
241 pub fn get_min_seen_secret(&self) -> u64 {
242 //TODO This can be optimized?
243 let mut min = 1 << 48;
244 for &(_, idx) in self.old_secrets.iter() {
253 fn derive_secret(secret: [u8; 32], bits: u8, idx: u64) -> [u8; 32] {
254 let mut res: [u8; 32] = secret;
256 let bitpos = bits - 1 - i;
257 if idx & (1 << bitpos) == (1 << bitpos) {
258 res[(bitpos / 8) as usize] ^= 1 << (bitpos & 7);
259 res = Sha256::hash(&res).into_inner();
265 /// Inserts the `secret` at `idx`. Returns `Ok(())` if the secret
266 /// was generated in accordance with BOLT 3 and is consistent with previous secrets.
267 pub fn provide_secret(&mut self, idx: u64, secret: [u8; 32]) -> Result<(), ()> {
268 let pos = Self::place_secret(idx);
270 let (old_secret, old_idx) = self.old_secrets[i as usize];
271 if Self::derive_secret(secret, pos, old_idx) != old_secret {
275 if self.get_min_seen_secret() <= idx {
278 self.old_secrets[pos as usize] = (secret, idx);
282 /// Returns the secret at `idx`.
283 /// Returns `None` if `idx` is < [`CounterpartyCommitmentSecrets::get_min_seen_secret`].
284 pub fn get_secret(&self, idx: u64) -> Option<[u8; 32]> {
285 for i in 0..self.old_secrets.len() {
286 if (idx & (!((1 << i) - 1))) == self.old_secrets[i].1 {
287 return Some(Self::derive_secret(self.old_secrets[i].0, i as u8, idx))
290 assert!(idx < self.get_min_seen_secret());
295 impl Writeable for CounterpartyCommitmentSecrets {
296 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
297 for &(ref secret, ref idx) in self.old_secrets.iter() {
298 writer.write_all(secret)?;
299 writer.write_all(&byte_utils::be64_to_array(*idx))?;
301 write_tlv_fields!(writer, {});
305 impl Readable for CounterpartyCommitmentSecrets {
306 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
307 let mut old_secrets = [([0; 32], 1 << 48); 49];
308 for &mut (ref mut secret, ref mut idx) in old_secrets.iter_mut() {
309 *secret = Readable::read(reader)?;
310 *idx = Readable::read(reader)?;
312 read_tlv_fields!(reader, {});
313 Ok(Self { old_secrets })
317 /// Derives a per-commitment-transaction private key (eg an htlc key or delayed_payment key)
318 /// from the base secret and the per_commitment_point.
320 /// Note that this is infallible iff we trust that at least one of the two input keys are randomly
321 /// generated (ie our own).
322 pub fn derive_private_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, base_secret: &SecretKey) -> Result<SecretKey, SecpError> {
323 let mut sha = Sha256::engine();
324 sha.input(&per_commitment_point.serialize());
325 sha.input(&PublicKey::from_secret_key(&secp_ctx, &base_secret).serialize());
326 let res = Sha256::from_engine(sha).into_inner();
328 base_secret.clone().add_tweak(&Scalar::from_be_bytes(res).unwrap())
331 /// Derives a per-commitment-transaction public key (eg an htlc key or a delayed_payment key)
332 /// from the base point and the per_commitment_key. This is the public equivalent of
333 /// derive_private_key - using only public keys to derive a public key instead of private keys.
335 /// Note that this is infallible iff we trust that at least one of the two input keys are randomly
336 /// generated (ie our own).
337 pub fn derive_public_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, base_point: &PublicKey) -> Result<PublicKey, SecpError> {
338 let mut sha = Sha256::engine();
339 sha.input(&per_commitment_point.serialize());
340 sha.input(&base_point.serialize());
341 let res = Sha256::from_engine(sha).into_inner();
343 let hashkey = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&res)?);
344 base_point.combine(&hashkey)
347 /// Derives a per-commitment-transaction revocation key from its constituent parts.
349 /// Only the cheating participant owns a valid witness to propagate a revoked
350 /// commitment transaction, thus per_commitment_secret always come from cheater
351 /// and revocation_base_secret always come from punisher, which is the broadcaster
352 /// of the transaction spending with this key knowledge.
354 /// Note that this is infallible iff we trust that at least one of the two input keys are randomly
355 /// generated (ie our own).
356 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> {
357 let countersignatory_revocation_base_point = PublicKey::from_secret_key(&secp_ctx, &countersignatory_revocation_base_secret);
358 let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &per_commitment_secret);
360 let rev_append_commit_hash_key = {
361 let mut sha = Sha256::engine();
362 sha.input(&countersignatory_revocation_base_point.serialize());
363 sha.input(&per_commitment_point.serialize());
365 Sha256::from_engine(sha).into_inner()
367 let commit_append_rev_hash_key = {
368 let mut sha = Sha256::engine();
369 sha.input(&per_commitment_point.serialize());
370 sha.input(&countersignatory_revocation_base_point.serialize());
372 Sha256::from_engine(sha).into_inner()
375 let countersignatory_contrib = countersignatory_revocation_base_secret.clone().mul_tweak(&Scalar::from_be_bytes(rev_append_commit_hash_key).unwrap())?;
376 let broadcaster_contrib = per_commitment_secret.clone().mul_tweak(&Scalar::from_be_bytes(commit_append_rev_hash_key).unwrap())?;
377 countersignatory_contrib.add_tweak(&Scalar::from_be_bytes(broadcaster_contrib.secret_bytes()).unwrap())
380 /// Derives a per-commitment-transaction revocation public key from its constituent parts. This is
381 /// the public equivalend of derive_private_revocation_key - using only public keys to derive a
382 /// public key instead of private keys.
384 /// Only the cheating participant owns a valid witness to propagate a revoked
385 /// commitment transaction, thus per_commitment_point always come from cheater
386 /// and revocation_base_point always come from punisher, which is the broadcaster
387 /// of the transaction spending with this key knowledge.
389 /// Note that this is infallible iff we trust that at least one of the two input keys are randomly
390 /// generated (ie our own).
391 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> {
392 let rev_append_commit_hash_key = {
393 let mut sha = Sha256::engine();
394 sha.input(&countersignatory_revocation_base_point.serialize());
395 sha.input(&per_commitment_point.serialize());
397 Sha256::from_engine(sha).into_inner()
399 let commit_append_rev_hash_key = {
400 let mut sha = Sha256::engine();
401 sha.input(&per_commitment_point.serialize());
402 sha.input(&countersignatory_revocation_base_point.serialize());
404 Sha256::from_engine(sha).into_inner()
407 let countersignatory_contrib = countersignatory_revocation_base_point.clone().mul_tweak(&secp_ctx, &Scalar::from_be_bytes(rev_append_commit_hash_key).unwrap())?;
408 let broadcaster_contrib = per_commitment_point.clone().mul_tweak(&secp_ctx, &Scalar::from_be_bytes(commit_append_rev_hash_key).unwrap())?;
409 countersignatory_contrib.combine(&broadcaster_contrib)
412 /// The set of public keys which are used in the creation of one commitment transaction.
413 /// These are derived from the channel base keys and per-commitment data.
415 /// A broadcaster key is provided from potential broadcaster of the computed transaction.
416 /// A countersignatory key is coming from a protocol participant unable to broadcast the
419 /// These keys are assumed to be good, either because the code derived them from
420 /// channel basepoints via the new function, or they were obtained via
421 /// CommitmentTransaction.trust().keys() because we trusted the source of the
422 /// pre-calculated keys.
423 #[derive(PartialEq, Eq, Clone)]
424 pub struct TxCreationKeys {
425 /// The broadcaster's per-commitment public key which was used to derive the other keys.
426 pub per_commitment_point: PublicKey,
427 /// The revocation key which is used to allow the broadcaster of the commitment
428 /// transaction to provide their counterparty the ability to punish them if they broadcast
430 pub revocation_key: PublicKey,
431 /// Broadcaster's HTLC Key
432 pub broadcaster_htlc_key: PublicKey,
433 /// Countersignatory's HTLC Key
434 pub countersignatory_htlc_key: PublicKey,
435 /// Broadcaster's Payment Key (which isn't allowed to be spent from for some delay)
436 pub broadcaster_delayed_payment_key: PublicKey,
439 impl_writeable_tlv_based!(TxCreationKeys, {
440 (0, per_commitment_point, required),
441 (2, revocation_key, required),
442 (4, broadcaster_htlc_key, required),
443 (6, countersignatory_htlc_key, required),
444 (8, broadcaster_delayed_payment_key, required),
447 /// One counterparty's public keys which do not change over the life of a channel.
448 #[derive(Clone, PartialEq, Eq)]
449 pub struct ChannelPublicKeys {
450 /// The public key which is used to sign all commitment transactions, as it appears in the
451 /// on-chain channel lock-in 2-of-2 multisig output.
452 pub funding_pubkey: PublicKey,
453 /// The base point which is used (with derive_public_revocation_key) to derive per-commitment
454 /// revocation keys. This is combined with the per-commitment-secret generated by the
455 /// counterparty to create a secret which the counterparty can reveal to revoke previous
457 pub revocation_basepoint: PublicKey,
458 /// The public key on which the non-broadcaster (ie the countersignatory) receives an immediately
459 /// spendable primary channel balance on the broadcaster's commitment transaction. This key is
460 /// static across every commitment transaction.
461 pub payment_point: PublicKey,
462 /// The base point which is used (with derive_public_key) to derive a per-commitment payment
463 /// public key which receives non-HTLC-encumbered funds which are only available for spending
464 /// after some delay (or can be claimed via the revocation path).
465 pub delayed_payment_basepoint: PublicKey,
466 /// The base point which is used (with derive_public_key) to derive a per-commitment public key
467 /// which is used to encumber HTLC-in-flight outputs.
468 pub htlc_basepoint: PublicKey,
471 impl_writeable_tlv_based!(ChannelPublicKeys, {
472 (0, funding_pubkey, required),
473 (2, revocation_basepoint, required),
474 (4, payment_point, required),
475 (6, delayed_payment_basepoint, required),
476 (8, htlc_basepoint, required),
479 impl TxCreationKeys {
480 /// Create per-state keys from channel base points and the per-commitment point.
481 /// Key set is asymmetric and can't be used as part of counter-signatory set of transactions.
482 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> {
484 per_commitment_point: per_commitment_point.clone(),
485 revocation_key: derive_public_revocation_key(&secp_ctx, &per_commitment_point, &countersignatory_revocation_base)?,
486 broadcaster_htlc_key: derive_public_key(&secp_ctx, &per_commitment_point, &broadcaster_htlc_base)?,
487 countersignatory_htlc_key: derive_public_key(&secp_ctx, &per_commitment_point, &countersignatory_htlc_base)?,
488 broadcaster_delayed_payment_key: derive_public_key(&secp_ctx, &per_commitment_point, &broadcaster_delayed_payment_base)?,
492 /// Generate per-state keys from channel static keys.
493 /// Key set is asymmetric and can't be used as part of counter-signatory set of transactions.
494 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> {
495 TxCreationKeys::derive_new(
497 &per_commitment_point,
498 &broadcaster_keys.delayed_payment_basepoint,
499 &broadcaster_keys.htlc_basepoint,
500 &countersignatory_keys.revocation_basepoint,
501 &countersignatory_keys.htlc_basepoint,
506 /// The maximum length of a script returned by get_revokeable_redeemscript.
507 // Calculated as 6 bytes of opcodes, 1 byte push plus 2 bytes for contest_delay, and two public
508 // keys of 33 bytes (+ 1 push).
509 pub const REVOKEABLE_REDEEMSCRIPT_MAX_LENGTH: usize = 6 + 3 + 34*2;
511 /// A script either spendable by the revocation
512 /// key or the broadcaster_delayed_payment_key and satisfying the relative-locktime OP_CSV constrain.
513 /// Encumbering a `to_holder` output on a commitment transaction or 2nd-stage HTLC transactions.
514 pub fn get_revokeable_redeemscript(revocation_key: &PublicKey, contest_delay: u16, broadcaster_delayed_payment_key: &PublicKey) -> Script {
515 let res = Builder::new().push_opcode(opcodes::all::OP_IF)
516 .push_slice(&revocation_key.serialize())
517 .push_opcode(opcodes::all::OP_ELSE)
518 .push_int(contest_delay as i64)
519 .push_opcode(opcodes::all::OP_CSV)
520 .push_opcode(opcodes::all::OP_DROP)
521 .push_slice(&broadcaster_delayed_payment_key.serialize())
522 .push_opcode(opcodes::all::OP_ENDIF)
523 .push_opcode(opcodes::all::OP_CHECKSIG)
525 debug_assert!(res.len() <= REVOKEABLE_REDEEMSCRIPT_MAX_LENGTH);
529 /// Information about an HTLC as it appears in a commitment transaction
530 #[derive(Clone, Debug, PartialEq, Eq)]
531 pub struct HTLCOutputInCommitment {
532 /// Whether the HTLC was "offered" (ie outbound in relation to this commitment transaction).
533 /// Note that this is not the same as whether it is ountbound *from us*. To determine that you
534 /// need to compare this value to whether the commitment transaction in question is that of
535 /// the counterparty or our own.
537 /// The value, in msat, of the HTLC. The value as it appears in the commitment transaction is
538 /// this divided by 1000.
539 pub amount_msat: u64,
540 /// The CLTV lock-time at which this HTLC expires.
541 pub cltv_expiry: u32,
542 /// The hash of the preimage which unlocks this HTLC.
543 pub payment_hash: PaymentHash,
544 /// The position within the commitment transactions' outputs. This may be None if the value is
545 /// below the dust limit (in which case no output appears in the commitment transaction and the
546 /// value is spent to additional transaction fees).
547 pub transaction_output_index: Option<u32>,
550 impl_writeable_tlv_based!(HTLCOutputInCommitment, {
551 (0, offered, required),
552 (2, amount_msat, required),
553 (4, cltv_expiry, required),
554 (6, payment_hash, required),
555 (8, transaction_output_index, option),
559 pub(crate) fn get_htlc_redeemscript_with_explicit_keys(htlc: &HTLCOutputInCommitment, opt_anchors: bool, broadcaster_htlc_key: &PublicKey, countersignatory_htlc_key: &PublicKey, revocation_key: &PublicKey) -> Script {
560 let payment_hash160 = Ripemd160::hash(&htlc.payment_hash.0[..]).into_inner();
562 let mut bldr = Builder::new().push_opcode(opcodes::all::OP_DUP)
563 .push_opcode(opcodes::all::OP_HASH160)
564 .push_slice(&PubkeyHash::hash(&revocation_key.serialize())[..])
565 .push_opcode(opcodes::all::OP_EQUAL)
566 .push_opcode(opcodes::all::OP_IF)
567 .push_opcode(opcodes::all::OP_CHECKSIG)
568 .push_opcode(opcodes::all::OP_ELSE)
569 .push_slice(&countersignatory_htlc_key.serialize()[..])
570 .push_opcode(opcodes::all::OP_SWAP)
571 .push_opcode(opcodes::all::OP_SIZE)
573 .push_opcode(opcodes::all::OP_EQUAL)
574 .push_opcode(opcodes::all::OP_NOTIF)
575 .push_opcode(opcodes::all::OP_DROP)
577 .push_opcode(opcodes::all::OP_SWAP)
578 .push_slice(&broadcaster_htlc_key.serialize()[..])
580 .push_opcode(opcodes::all::OP_CHECKMULTISIG)
581 .push_opcode(opcodes::all::OP_ELSE)
582 .push_opcode(opcodes::all::OP_HASH160)
583 .push_slice(&payment_hash160)
584 .push_opcode(opcodes::all::OP_EQUALVERIFY)
585 .push_opcode(opcodes::all::OP_CHECKSIG)
586 .push_opcode(opcodes::all::OP_ENDIF);
588 bldr = bldr.push_opcode(opcodes::all::OP_PUSHNUM_1)
589 .push_opcode(opcodes::all::OP_CSV)
590 .push_opcode(opcodes::all::OP_DROP);
592 bldr.push_opcode(opcodes::all::OP_ENDIF)
595 let mut bldr = Builder::new().push_opcode(opcodes::all::OP_DUP)
596 .push_opcode(opcodes::all::OP_HASH160)
597 .push_slice(&PubkeyHash::hash(&revocation_key.serialize())[..])
598 .push_opcode(opcodes::all::OP_EQUAL)
599 .push_opcode(opcodes::all::OP_IF)
600 .push_opcode(opcodes::all::OP_CHECKSIG)
601 .push_opcode(opcodes::all::OP_ELSE)
602 .push_slice(&countersignatory_htlc_key.serialize()[..])
603 .push_opcode(opcodes::all::OP_SWAP)
604 .push_opcode(opcodes::all::OP_SIZE)
606 .push_opcode(opcodes::all::OP_EQUAL)
607 .push_opcode(opcodes::all::OP_IF)
608 .push_opcode(opcodes::all::OP_HASH160)
609 .push_slice(&payment_hash160)
610 .push_opcode(opcodes::all::OP_EQUALVERIFY)
612 .push_opcode(opcodes::all::OP_SWAP)
613 .push_slice(&broadcaster_htlc_key.serialize()[..])
615 .push_opcode(opcodes::all::OP_CHECKMULTISIG)
616 .push_opcode(opcodes::all::OP_ELSE)
617 .push_opcode(opcodes::all::OP_DROP)
618 .push_int(htlc.cltv_expiry as i64)
619 .push_opcode(opcodes::all::OP_CLTV)
620 .push_opcode(opcodes::all::OP_DROP)
621 .push_opcode(opcodes::all::OP_CHECKSIG)
622 .push_opcode(opcodes::all::OP_ENDIF);
624 bldr = bldr.push_opcode(opcodes::all::OP_PUSHNUM_1)
625 .push_opcode(opcodes::all::OP_CSV)
626 .push_opcode(opcodes::all::OP_DROP);
628 bldr.push_opcode(opcodes::all::OP_ENDIF)
633 /// Gets the witness redeemscript for an HTLC output in a commitment transaction. Note that htlc
634 /// does not need to have its previous_output_index filled.
636 pub fn get_htlc_redeemscript(htlc: &HTLCOutputInCommitment, opt_anchors: bool, keys: &TxCreationKeys) -> Script {
637 get_htlc_redeemscript_with_explicit_keys(htlc, opt_anchors, &keys.broadcaster_htlc_key, &keys.countersignatory_htlc_key, &keys.revocation_key)
640 /// Gets the redeemscript for a funding output from the two funding public keys.
641 /// Note that the order of funding public keys does not matter.
642 pub fn make_funding_redeemscript(broadcaster: &PublicKey, countersignatory: &PublicKey) -> Script {
643 let broadcaster_funding_key = broadcaster.serialize();
644 let countersignatory_funding_key = countersignatory.serialize();
646 let builder = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2);
647 if broadcaster_funding_key[..] < countersignatory_funding_key[..] {
648 builder.push_slice(&broadcaster_funding_key)
649 .push_slice(&countersignatory_funding_key)
651 builder.push_slice(&countersignatory_funding_key)
652 .push_slice(&broadcaster_funding_key)
653 }.push_opcode(opcodes::all::OP_PUSHNUM_2).push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script()
656 /// Builds an unsigned HTLC-Success or HTLC-Timeout transaction from the given channel and HTLC
657 /// parameters. This is used by [`TrustedCommitmentTransaction::get_htlc_sigs`] to fetch the
658 /// transaction which needs signing, and can be used to construct an HTLC transaction which is
659 /// broadcastable given a counterparty HTLC signature.
661 /// Panics if htlc.transaction_output_index.is_none() (as such HTLCs do not appear in the
662 /// commitment transaction).
663 pub fn build_htlc_transaction(commitment_txid: &Txid, feerate_per_kw: u32, contest_delay: u16, htlc: &HTLCOutputInCommitment, opt_anchors: bool, broadcaster_delayed_payment_key: &PublicKey, revocation_key: &PublicKey) -> Transaction {
664 let mut txins: Vec<TxIn> = Vec::new();
666 previous_output: OutPoint {
667 txid: commitment_txid.clone(),
668 vout: htlc.transaction_output_index.expect("Can't build an HTLC transaction for a dust output"),
670 script_sig: Script::new(),
671 sequence: Sequence(if opt_anchors { 1 } else { 0 }),
672 witness: Witness::new(),
675 let weight = if htlc.offered {
676 htlc_timeout_tx_weight(opt_anchors)
678 htlc_success_tx_weight(opt_anchors)
680 let output_value = if opt_anchors {
681 htlc.amount_msat / 1000
683 let total_fee = feerate_per_kw as u64 * weight / 1000;
684 htlc.amount_msat / 1000 - total_fee
687 let mut txouts: Vec<TxOut> = Vec::new();
689 script_pubkey: get_revokeable_redeemscript(revocation_key, contest_delay, broadcaster_delayed_payment_key).to_v0_p2wsh(),
695 lock_time: PackedLockTime(if htlc.offered { htlc.cltv_expiry } else { 0 }),
701 /// Gets the witnessScript for the to_remote output when anchors are enabled.
703 pub(crate) fn get_to_countersignatory_with_anchors_redeemscript(payment_point: &PublicKey) -> Script {
705 .push_slice(&payment_point.serialize()[..])
706 .push_opcode(opcodes::all::OP_CHECKSIGVERIFY)
708 .push_opcode(opcodes::all::OP_CSV)
712 /// Gets the witnessScript for an anchor output from the funding public key.
713 /// The witness in the spending input must be:
714 /// <BIP 143 funding_signature>
715 /// After 16 blocks of confirmation, an alternative satisfying witness could be:
717 /// (empty vector required to satisfy compliance with MINIMALIF-standard rule)
719 pub fn get_anchor_redeemscript(funding_pubkey: &PublicKey) -> Script {
720 Builder::new().push_slice(&funding_pubkey.serialize()[..])
721 .push_opcode(opcodes::all::OP_CHECKSIG)
722 .push_opcode(opcodes::all::OP_IFDUP)
723 .push_opcode(opcodes::all::OP_NOTIF)
725 .push_opcode(opcodes::all::OP_CSV)
726 .push_opcode(opcodes::all::OP_ENDIF)
731 /// Locates the output with an anchor script paying to `funding_pubkey` within `commitment_tx`.
732 pub(crate) fn get_anchor_output<'a>(commitment_tx: &'a Transaction, funding_pubkey: &PublicKey) -> Option<(u32, &'a TxOut)> {
733 let anchor_script = chan_utils::get_anchor_redeemscript(funding_pubkey).to_v0_p2wsh();
734 commitment_tx.output.iter().enumerate()
735 .find(|(_, txout)| txout.script_pubkey == anchor_script)
736 .map(|(idx, txout)| (idx as u32, txout))
739 /// Per-channel data used to build transactions in conjunction with the per-commitment data (CommitmentTransaction).
740 /// The fields are organized by holder/counterparty.
742 /// Normally, this is converted to the broadcaster/countersignatory-organized DirectedChannelTransactionParameters
743 /// before use, via the as_holder_broadcastable and as_counterparty_broadcastable functions.
745 pub struct ChannelTransactionParameters {
746 /// Holder public keys
747 pub holder_pubkeys: ChannelPublicKeys,
748 /// The contest delay selected by the holder, which applies to counterparty-broadcast transactions
749 pub holder_selected_contest_delay: u16,
750 /// Whether the holder is the initiator of this channel.
751 /// This is an input to the commitment number obscure factor computation.
752 pub is_outbound_from_holder: bool,
753 /// The late-bound counterparty channel transaction parameters.
754 /// These parameters are populated at the point in the protocol where the counterparty provides them.
755 pub counterparty_parameters: Option<CounterpartyChannelTransactionParameters>,
756 /// The late-bound funding outpoint
757 pub funding_outpoint: Option<chain::transaction::OutPoint>,
758 /// Are anchors (zero fee HTLC transaction variant) used for this channel. Boolean is
759 /// serialization backwards-compatible.
760 pub opt_anchors: Option<()>
763 /// Late-bound per-channel counterparty data used to build transactions.
765 pub struct CounterpartyChannelTransactionParameters {
766 /// Counter-party public keys
767 pub pubkeys: ChannelPublicKeys,
768 /// The contest delay selected by the counterparty, which applies to holder-broadcast transactions
769 pub selected_contest_delay: u16,
772 impl ChannelTransactionParameters {
773 /// Whether the late bound parameters are populated.
774 pub fn is_populated(&self) -> bool {
775 self.counterparty_parameters.is_some() && self.funding_outpoint.is_some()
778 /// Convert the holder/counterparty parameters to broadcaster/countersignatory-organized parameters,
779 /// given that the holder is the broadcaster.
781 /// self.is_populated() must be true before calling this function.
782 pub fn as_holder_broadcastable(&self) -> DirectedChannelTransactionParameters {
783 assert!(self.is_populated(), "self.late_parameters must be set before using as_holder_broadcastable");
784 DirectedChannelTransactionParameters {
786 holder_is_broadcaster: true
790 /// Convert the holder/counterparty parameters to broadcaster/countersignatory-organized parameters,
791 /// given that the counterparty is the broadcaster.
793 /// self.is_populated() must be true before calling this function.
794 pub fn as_counterparty_broadcastable(&self) -> DirectedChannelTransactionParameters {
795 assert!(self.is_populated(), "self.late_parameters must be set before using as_counterparty_broadcastable");
796 DirectedChannelTransactionParameters {
798 holder_is_broadcaster: false
803 impl_writeable_tlv_based!(CounterpartyChannelTransactionParameters, {
804 (0, pubkeys, required),
805 (2, selected_contest_delay, required),
808 impl_writeable_tlv_based!(ChannelTransactionParameters, {
809 (0, holder_pubkeys, required),
810 (2, holder_selected_contest_delay, required),
811 (4, is_outbound_from_holder, required),
812 (6, counterparty_parameters, option),
813 (8, funding_outpoint, option),
814 (10, opt_anchors, option),
817 /// Static channel fields used to build transactions given per-commitment fields, organized by
818 /// broadcaster/countersignatory.
820 /// This is derived from the holder/counterparty-organized ChannelTransactionParameters via the
821 /// as_holder_broadcastable and as_counterparty_broadcastable functions.
822 pub struct DirectedChannelTransactionParameters<'a> {
823 /// The holder's channel static parameters
824 inner: &'a ChannelTransactionParameters,
825 /// Whether the holder is the broadcaster
826 holder_is_broadcaster: bool,
829 impl<'a> DirectedChannelTransactionParameters<'a> {
830 /// Get the channel pubkeys for the broadcaster
831 pub fn broadcaster_pubkeys(&self) -> &ChannelPublicKeys {
832 if self.holder_is_broadcaster {
833 &self.inner.holder_pubkeys
835 &self.inner.counterparty_parameters.as_ref().unwrap().pubkeys
839 /// Get the channel pubkeys for the countersignatory
840 pub fn countersignatory_pubkeys(&self) -> &ChannelPublicKeys {
841 if self.holder_is_broadcaster {
842 &self.inner.counterparty_parameters.as_ref().unwrap().pubkeys
844 &self.inner.holder_pubkeys
848 /// Get the contest delay applicable to the transactions.
849 /// Note that the contest delay was selected by the countersignatory.
850 pub fn contest_delay(&self) -> u16 {
851 let counterparty_parameters = self.inner.counterparty_parameters.as_ref().unwrap();
852 if self.holder_is_broadcaster { counterparty_parameters.selected_contest_delay } else { self.inner.holder_selected_contest_delay }
855 /// Whether the channel is outbound from the broadcaster.
857 /// The boolean representing the side that initiated the channel is
858 /// an input to the commitment number obscure factor computation.
859 pub fn is_outbound(&self) -> bool {
860 if self.holder_is_broadcaster { self.inner.is_outbound_from_holder } else { !self.inner.is_outbound_from_holder }
863 /// The funding outpoint
864 pub fn funding_outpoint(&self) -> OutPoint {
865 self.inner.funding_outpoint.unwrap().into_bitcoin_outpoint()
868 /// Whether to use anchors for this channel
869 pub fn opt_anchors(&self) -> bool {
870 self.inner.opt_anchors.is_some()
874 /// Information needed to build and sign a holder's commitment transaction.
876 /// The transaction is only signed once we are ready to broadcast.
878 pub struct HolderCommitmentTransaction {
879 inner: CommitmentTransaction,
880 /// Our counterparty's signature for the transaction
881 pub counterparty_sig: Signature,
882 /// All non-dust counterparty HTLC signatures, in the order they appear in the transaction
883 pub counterparty_htlc_sigs: Vec<Signature>,
884 // Which order the signatures should go in when constructing the final commitment tx witness.
885 // The user should be able to reconstruct this themselves, so we don't bother to expose it.
886 holder_sig_first: bool,
889 impl Deref for HolderCommitmentTransaction {
890 type Target = CommitmentTransaction;
892 fn deref(&self) -> &Self::Target { &self.inner }
895 impl Eq for HolderCommitmentTransaction {}
896 impl PartialEq for HolderCommitmentTransaction {
897 // We dont care whether we are signed in equality comparison
898 fn eq(&self, o: &Self) -> bool {
899 self.inner == o.inner
903 impl_writeable_tlv_based!(HolderCommitmentTransaction, {
904 (0, inner, required),
905 (2, counterparty_sig, required),
906 (4, holder_sig_first, required),
907 (6, counterparty_htlc_sigs, vec_type),
910 impl HolderCommitmentTransaction {
912 pub fn dummy() -> Self {
913 let secp_ctx = Secp256k1::new();
914 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
915 let dummy_sig = sign(&secp_ctx, &secp256k1::Message::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[42; 32]).unwrap());
917 let keys = TxCreationKeys {
918 per_commitment_point: dummy_key.clone(),
919 revocation_key: dummy_key.clone(),
920 broadcaster_htlc_key: dummy_key.clone(),
921 countersignatory_htlc_key: dummy_key.clone(),
922 broadcaster_delayed_payment_key: dummy_key.clone(),
924 let channel_pubkeys = ChannelPublicKeys {
925 funding_pubkey: dummy_key.clone(),
926 revocation_basepoint: dummy_key.clone(),
927 payment_point: dummy_key.clone(),
928 delayed_payment_basepoint: dummy_key.clone(),
929 htlc_basepoint: dummy_key.clone()
931 let channel_parameters = ChannelTransactionParameters {
932 holder_pubkeys: channel_pubkeys.clone(),
933 holder_selected_contest_delay: 0,
934 is_outbound_from_holder: false,
935 counterparty_parameters: Some(CounterpartyChannelTransactionParameters { pubkeys: channel_pubkeys.clone(), selected_contest_delay: 0 }),
936 funding_outpoint: Some(chain::transaction::OutPoint { txid: Txid::all_zeros(), index: 0 }),
939 let mut htlcs_with_aux: Vec<(_, ())> = Vec::new();
940 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());
941 HolderCommitmentTransaction {
943 counterparty_sig: dummy_sig,
944 counterparty_htlc_sigs: Vec::new(),
945 holder_sig_first: false
949 /// Create a new holder transaction with the given counterparty signatures.
950 /// The funding keys are used to figure out which signature should go first when building the transaction for broadcast.
951 pub fn new(commitment_tx: CommitmentTransaction, counterparty_sig: Signature, counterparty_htlc_sigs: Vec<Signature>, holder_funding_key: &PublicKey, counterparty_funding_key: &PublicKey) -> Self {
953 inner: commitment_tx,
955 counterparty_htlc_sigs,
956 holder_sig_first: holder_funding_key.serialize()[..] < counterparty_funding_key.serialize()[..],
960 pub(crate) fn add_holder_sig(&self, funding_redeemscript: &Script, holder_sig: Signature) -> Transaction {
961 // First push the multisig dummy, note that due to BIP147 (NULLDUMMY) it must be a zero-length element.
962 let mut tx = self.inner.built.transaction.clone();
963 tx.input[0].witness.push(Vec::new());
964 let mut ser_holder_sig = holder_sig.serialize_der().to_vec();
965 ser_holder_sig.push(EcdsaSighashType::All as u8);
966 let mut ser_cp_sig = self.counterparty_sig.serialize_der().to_vec();
967 ser_cp_sig.push(EcdsaSighashType::All as u8);
969 if self.holder_sig_first {
970 tx.input[0].witness.push(ser_holder_sig);
971 tx.input[0].witness.push(ser_cp_sig);
973 tx.input[0].witness.push(ser_cp_sig);
974 tx.input[0].witness.push(ser_holder_sig);
977 tx.input[0].witness.push(funding_redeemscript.as_bytes().to_vec());
982 /// A pre-built Bitcoin commitment transaction and its txid.
984 pub struct BuiltCommitmentTransaction {
985 /// The commitment transaction
986 pub transaction: Transaction,
987 /// The txid for the commitment transaction.
989 /// This is provided as a performance optimization, instead of calling transaction.txid()
994 impl_writeable_tlv_based!(BuiltCommitmentTransaction, {
995 (0, transaction, required),
999 impl BuiltCommitmentTransaction {
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 = &sighash::SighashCache::new(&self.transaction).segwit_signature_hash(0, funding_redeemscript, channel_value_satoshis, EcdsaSighashType::All).unwrap()[..];
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 sign(secp_ctx, &sighash, funding_key)
1016 /// This class tracks the per-transaction information needed to build a closing transaction and will
1017 /// actually build it and sign.
1019 /// This class can be used inside a signer implementation to generate a signature given the relevant
1021 #[derive(Clone, Hash, PartialEq, Eq)]
1022 pub struct ClosingTransaction {
1023 to_holder_value_sat: u64,
1024 to_counterparty_value_sat: u64,
1025 to_holder_script: Script,
1026 to_counterparty_script: Script,
1030 impl ClosingTransaction {
1031 /// Construct an object of the class
1033 to_holder_value_sat: u64,
1034 to_counterparty_value_sat: u64,
1035 to_holder_script: Script,
1036 to_counterparty_script: Script,
1037 funding_outpoint: OutPoint,
1039 let built = build_closing_transaction(
1040 to_holder_value_sat, to_counterparty_value_sat,
1041 to_holder_script.clone(), to_counterparty_script.clone(),
1044 ClosingTransaction {
1045 to_holder_value_sat,
1046 to_counterparty_value_sat,
1048 to_counterparty_script,
1053 /// Trust our pre-built transaction.
1055 /// Applies a wrapper which allows access to the transaction.
1057 /// This should only be used if you fully trust the builder of this object. It should not
1058 /// be used by an external signer - instead use the verify function.
1059 pub fn trust(&self) -> TrustedClosingTransaction {
1060 TrustedClosingTransaction { inner: self }
1063 /// Verify our pre-built transaction.
1065 /// Applies a wrapper which allows access to the transaction.
1067 /// An external validating signer must call this method before signing
1068 /// or using the built transaction.
1069 pub fn verify(&self, funding_outpoint: OutPoint) -> Result<TrustedClosingTransaction, ()> {
1070 let built = build_closing_transaction(
1071 self.to_holder_value_sat, self.to_counterparty_value_sat,
1072 self.to_holder_script.clone(), self.to_counterparty_script.clone(),
1075 if self.built != built {
1078 Ok(TrustedClosingTransaction { inner: self })
1081 /// The value to be sent to the holder, or zero if the output will be omitted
1082 pub fn to_holder_value_sat(&self) -> u64 {
1083 self.to_holder_value_sat
1086 /// The value to be sent to the counterparty, or zero if the output will be omitted
1087 pub fn to_counterparty_value_sat(&self) -> u64 {
1088 self.to_counterparty_value_sat
1091 /// The destination of the holder's output
1092 pub fn to_holder_script(&self) -> &Script {
1093 &self.to_holder_script
1096 /// The destination of the counterparty's output
1097 pub fn to_counterparty_script(&self) -> &Script {
1098 &self.to_counterparty_script
1102 /// A wrapper on ClosingTransaction indicating that the built bitcoin
1103 /// transaction is trusted.
1105 /// See trust() and verify() functions on CommitmentTransaction.
1107 /// This structure implements Deref.
1108 pub struct TrustedClosingTransaction<'a> {
1109 inner: &'a ClosingTransaction,
1112 impl<'a> Deref for TrustedClosingTransaction<'a> {
1113 type Target = ClosingTransaction;
1115 fn deref(&self) -> &Self::Target { self.inner }
1118 impl<'a> TrustedClosingTransaction<'a> {
1119 /// The pre-built Bitcoin commitment transaction
1120 pub fn built_transaction(&self) -> &Transaction {
1124 /// Get the SIGHASH_ALL sighash value of the transaction.
1126 /// This can be used to verify a signature.
1127 pub fn get_sighash_all(&self, funding_redeemscript: &Script, channel_value_satoshis: u64) -> Message {
1128 let sighash = &sighash::SighashCache::new(&self.inner.built).segwit_signature_hash(0, funding_redeemscript, channel_value_satoshis, EcdsaSighashType::All).unwrap()[..];
1129 hash_to_message!(sighash)
1132 /// Sign a transaction, either because we are counter-signing the counterparty's transaction or
1133 /// because we are about to broadcast a holder transaction.
1134 pub fn sign<T: secp256k1::Signing>(&self, funding_key: &SecretKey, funding_redeemscript: &Script, channel_value_satoshis: u64, secp_ctx: &Secp256k1<T>) -> Signature {
1135 let sighash = self.get_sighash_all(funding_redeemscript, channel_value_satoshis);
1136 sign(secp_ctx, &sighash, funding_key)
1140 /// This class tracks the per-transaction information needed to build a commitment transaction and will
1141 /// actually build it and sign. It is used for holder transactions that we sign only when needed
1142 /// and for transactions we sign for the counterparty.
1144 /// This class can be used inside a signer implementation to generate a signature given the relevant
1147 pub struct CommitmentTransaction {
1148 commitment_number: u64,
1149 to_broadcaster_value_sat: u64,
1150 to_countersignatory_value_sat: u64,
1151 feerate_per_kw: u32,
1152 htlcs: Vec<HTLCOutputInCommitment>,
1153 // A boolean that is serialization backwards-compatible
1154 opt_anchors: Option<()>,
1155 // A cache of the parties' pubkeys required to construct the transaction, see doc for trust()
1156 keys: TxCreationKeys,
1157 // For access to the pre-built transaction, see doc for trust()
1158 built: BuiltCommitmentTransaction,
1161 impl Eq for CommitmentTransaction {}
1162 impl PartialEq for CommitmentTransaction {
1163 fn eq(&self, o: &Self) -> bool {
1164 let eq = self.commitment_number == o.commitment_number &&
1165 self.to_broadcaster_value_sat == o.to_broadcaster_value_sat &&
1166 self.to_countersignatory_value_sat == o.to_countersignatory_value_sat &&
1167 self.feerate_per_kw == o.feerate_per_kw &&
1168 self.htlcs == o.htlcs &&
1169 self.opt_anchors == o.opt_anchors &&
1170 self.keys == o.keys;
1172 debug_assert_eq!(self.built.transaction, o.built.transaction);
1173 debug_assert_eq!(self.built.txid, o.built.txid);
1179 impl_writeable_tlv_based!(CommitmentTransaction, {
1180 (0, commitment_number, required),
1181 (2, to_broadcaster_value_sat, required),
1182 (4, to_countersignatory_value_sat, required),
1183 (6, feerate_per_kw, required),
1184 (8, keys, required),
1185 (10, built, required),
1186 (12, htlcs, vec_type),
1187 (14, opt_anchors, option),
1190 impl CommitmentTransaction {
1191 /// Construct an object of the class while assigning transaction output indices to HTLCs.
1193 /// Populates HTLCOutputInCommitment.transaction_output_index in htlcs_with_aux.
1195 /// The generic T allows the caller to match the HTLC output index with auxiliary data.
1196 /// This auxiliary data is not stored in this object.
1198 /// Only include HTLCs that are above the dust limit for the channel.
1200 /// (C-not exported) due to the generic though we likely should expose a version without
1201 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 {
1202 // Sort outputs and populate output indices while keeping track of the auxiliary data
1203 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();
1205 let (obscured_commitment_transaction_number, txins) = Self::internal_build_inputs(commitment_number, channel_parameters);
1206 let transaction = Self::make_transaction(obscured_commitment_transaction_number, txins, outputs);
1207 let txid = transaction.txid();
1208 CommitmentTransaction {
1210 to_broadcaster_value_sat,
1211 to_countersignatory_value_sat,
1214 opt_anchors: if opt_anchors { Some(()) } else { None },
1216 built: BuiltCommitmentTransaction {
1223 fn internal_rebuild_transaction(&self, keys: &TxCreationKeys, channel_parameters: &DirectedChannelTransactionParameters, broadcaster_funding_key: &PublicKey, countersignatory_funding_key: &PublicKey) -> Result<BuiltCommitmentTransaction, ()> {
1224 let (obscured_commitment_transaction_number, txins) = Self::internal_build_inputs(self.commitment_number, channel_parameters);
1226 let mut htlcs_with_aux = self.htlcs.iter().map(|h| (h.clone(), ())).collect();
1227 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)?;
1229 let transaction = Self::make_transaction(obscured_commitment_transaction_number, txins, outputs);
1230 let txid = transaction.txid();
1231 let built_transaction = BuiltCommitmentTransaction {
1235 Ok(built_transaction)
1238 fn make_transaction(obscured_commitment_transaction_number: u64, txins: Vec<TxIn>, outputs: Vec<TxOut>) -> Transaction {
1241 lock_time: PackedLockTime(((0x20 as u32) << 8 * 3) | ((obscured_commitment_transaction_number & 0xffffffu64) as u32)),
1247 // This is used in two cases:
1248 // - initial sorting of outputs / HTLCs in the constructor, in which case T is auxiliary data the
1249 // caller needs to have sorted together with the HTLCs so it can keep track of the output index
1250 // - building of a bitcoin transaction during a verify() call, in which case T is just ()
1251 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>), ()> {
1252 let countersignatory_pubkeys = channel_parameters.countersignatory_pubkeys();
1253 let contest_delay = channel_parameters.contest_delay();
1255 let mut txouts: Vec<(TxOut, Option<&mut HTLCOutputInCommitment>)> = Vec::new();
1257 if to_countersignatory_value_sat > 0 {
1258 let script = if opt_anchors {
1259 get_to_countersignatory_with_anchors_redeemscript(&countersignatory_pubkeys.payment_point).to_v0_p2wsh()
1261 get_p2wpkh_redeemscript(&countersignatory_pubkeys.payment_point)
1265 script_pubkey: script.clone(),
1266 value: to_countersignatory_value_sat,
1272 if to_broadcaster_value_sat > 0 {
1273 let redeem_script = get_revokeable_redeemscript(
1274 &keys.revocation_key,
1276 &keys.broadcaster_delayed_payment_key,
1280 script_pubkey: redeem_script.to_v0_p2wsh(),
1281 value: to_broadcaster_value_sat,
1288 if to_broadcaster_value_sat > 0 || !htlcs_with_aux.is_empty() {
1289 let anchor_script = get_anchor_redeemscript(broadcaster_funding_key);
1292 script_pubkey: anchor_script.to_v0_p2wsh(),
1293 value: ANCHOR_OUTPUT_VALUE_SATOSHI,
1299 if to_countersignatory_value_sat > 0 || !htlcs_with_aux.is_empty() {
1300 let anchor_script = get_anchor_redeemscript(countersignatory_funding_key);
1303 script_pubkey: anchor_script.to_v0_p2wsh(),
1304 value: ANCHOR_OUTPUT_VALUE_SATOSHI,
1311 let mut htlcs = Vec::with_capacity(htlcs_with_aux.len());
1312 for (htlc, _) in htlcs_with_aux {
1313 let script = chan_utils::get_htlc_redeemscript(&htlc, opt_anchors, &keys);
1315 script_pubkey: script.to_v0_p2wsh(),
1316 value: htlc.amount_msat / 1000,
1318 txouts.push((txout, Some(htlc)));
1321 // Sort output in BIP-69 order (amount, scriptPubkey). Tie-breaks based on HTLC
1322 // CLTV expiration height.
1323 sort_outputs(&mut txouts, |a, b| {
1324 if let &Some(ref a_htlcout) = a {
1325 if let &Some(ref b_htlcout) = b {
1326 a_htlcout.cltv_expiry.cmp(&b_htlcout.cltv_expiry)
1327 // Note that due to hash collisions, we have to have a fallback comparison
1328 // here for fuzzing mode (otherwise at least chanmon_fail_consistency
1330 .then(a_htlcout.payment_hash.0.cmp(&b_htlcout.payment_hash.0))
1331 // For non-HTLC outputs, if they're copying our SPK we don't really care if we
1332 // close the channel due to mismatches - they're doing something dumb:
1333 } else { cmp::Ordering::Equal }
1334 } else { cmp::Ordering::Equal }
1337 let mut outputs = Vec::with_capacity(txouts.len());
1338 for (idx, out) in txouts.drain(..).enumerate() {
1339 if let Some(htlc) = out.1 {
1340 htlc.transaction_output_index = Some(idx as u32);
1341 htlcs.push(htlc.clone());
1343 outputs.push(out.0);
1345 Ok((outputs, htlcs))
1348 fn internal_build_inputs(commitment_number: u64, channel_parameters: &DirectedChannelTransactionParameters) -> (u64, Vec<TxIn>) {
1349 let broadcaster_pubkeys = channel_parameters.broadcaster_pubkeys();
1350 let countersignatory_pubkeys = channel_parameters.countersignatory_pubkeys();
1351 let commitment_transaction_number_obscure_factor = get_commitment_transaction_number_obscure_factor(
1352 &broadcaster_pubkeys.payment_point,
1353 &countersignatory_pubkeys.payment_point,
1354 channel_parameters.is_outbound(),
1357 let obscured_commitment_transaction_number =
1358 commitment_transaction_number_obscure_factor ^ (INITIAL_COMMITMENT_NUMBER - commitment_number);
1361 let mut ins: Vec<TxIn> = Vec::new();
1363 previous_output: channel_parameters.funding_outpoint(),
1364 script_sig: Script::new(),
1365 sequence: Sequence(((0x80 as u32) << 8 * 3)
1366 | ((obscured_commitment_transaction_number >> 3 * 8) as u32)),
1367 witness: Witness::new(),
1371 (obscured_commitment_transaction_number, txins)
1374 /// The backwards-counting commitment number
1375 pub fn commitment_number(&self) -> u64 {
1376 self.commitment_number
1379 /// The value to be sent to the broadcaster
1380 pub fn to_broadcaster_value_sat(&self) -> u64 {
1381 self.to_broadcaster_value_sat
1384 /// The value to be sent to the counterparty
1385 pub fn to_countersignatory_value_sat(&self) -> u64 {
1386 self.to_countersignatory_value_sat
1389 /// The feerate paid per 1000-weight-unit in this commitment transaction.
1390 pub fn feerate_per_kw(&self) -> u32 {
1394 /// The non-dust HTLCs (direction, amt, height expiration, hash, transaction output index)
1395 /// which were included in this commitment transaction in output order.
1396 /// The transaction index is always populated.
1398 /// (C-not exported) as we cannot currently convert Vec references to/from C, though we should
1399 /// expose a less effecient version which creates a Vec of references in the future.
1400 pub fn htlcs(&self) -> &Vec<HTLCOutputInCommitment> {
1404 /// Trust our pre-built transaction and derived transaction creation public keys.
1406 /// Applies a wrapper which allows access to these fields.
1408 /// This should only be used if you fully trust the builder of this object. It should not
1409 /// be used by an external signer - instead use the verify function.
1410 pub fn trust(&self) -> TrustedCommitmentTransaction {
1411 TrustedCommitmentTransaction { inner: self }
1414 /// Verify our pre-built transaction and derived transaction creation public keys.
1416 /// Applies a wrapper which allows access to these fields.
1418 /// An external validating signer must call this method before signing
1419 /// or using the built transaction.
1420 pub fn verify<T: secp256k1::Signing + secp256k1::Verification>(&self, channel_parameters: &DirectedChannelTransactionParameters, broadcaster_keys: &ChannelPublicKeys, countersignatory_keys: &ChannelPublicKeys, secp_ctx: &Secp256k1<T>) -> Result<TrustedCommitmentTransaction, ()> {
1421 // This is the only field of the key cache that we trust
1422 let per_commitment_point = self.keys.per_commitment_point;
1423 let keys = TxCreationKeys::from_channel_static_keys(&per_commitment_point, broadcaster_keys, countersignatory_keys, secp_ctx).unwrap();
1424 if keys != self.keys {
1427 let tx = self.internal_rebuild_transaction(&keys, channel_parameters, &broadcaster_keys.funding_pubkey, &countersignatory_keys.funding_pubkey)?;
1428 if self.built.transaction != tx.transaction || self.built.txid != tx.txid {
1431 Ok(TrustedCommitmentTransaction { inner: self })
1435 /// A wrapper on CommitmentTransaction indicating that the derived fields (the built bitcoin
1436 /// transaction and the transaction creation keys) are trusted.
1438 /// See trust() and verify() functions on CommitmentTransaction.
1440 /// This structure implements Deref.
1441 pub struct TrustedCommitmentTransaction<'a> {
1442 inner: &'a CommitmentTransaction,
1445 impl<'a> Deref for TrustedCommitmentTransaction<'a> {
1446 type Target = CommitmentTransaction;
1448 fn deref(&self) -> &Self::Target { self.inner }
1451 impl<'a> TrustedCommitmentTransaction<'a> {
1452 /// The transaction ID of the built Bitcoin transaction
1453 pub fn txid(&self) -> Txid {
1454 self.inner.built.txid
1457 /// The pre-built Bitcoin commitment transaction
1458 pub fn built_transaction(&self) -> &BuiltCommitmentTransaction {
1462 /// The pre-calculated transaction creation public keys.
1463 pub fn keys(&self) -> &TxCreationKeys {
1467 /// Should anchors be used.
1468 pub fn opt_anchors(&self) -> bool {
1469 self.opt_anchors.is_some()
1472 /// Get a signature for each HTLC which was included in the commitment transaction (ie for
1473 /// which HTLCOutputInCommitment::transaction_output_index.is_some()).
1475 /// The returned Vec has one entry for each HTLC, and in the same order.
1477 /// This function is only valid in the holder commitment context, it always uses EcdsaSighashType::All.
1478 pub fn get_htlc_sigs<T: secp256k1::Signing>(&self, htlc_base_key: &SecretKey, channel_parameters: &DirectedChannelTransactionParameters, secp_ctx: &Secp256k1<T>) -> Result<Vec<Signature>, ()> {
1479 let inner = self.inner;
1480 let keys = &inner.keys;
1481 let txid = inner.built.txid;
1482 let mut ret = Vec::with_capacity(inner.htlcs.len());
1483 let holder_htlc_key = derive_private_key(secp_ctx, &inner.keys.per_commitment_point, htlc_base_key).map_err(|_| ())?;
1485 for this_htlc in inner.htlcs.iter() {
1486 assert!(this_htlc.transaction_output_index.is_some());
1487 let htlc_tx = build_htlc_transaction(&txid, inner.feerate_per_kw, channel_parameters.contest_delay(), &this_htlc, self.opt_anchors(), &keys.broadcaster_delayed_payment_key, &keys.revocation_key);
1489 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);
1491 let sighash = hash_to_message!(&sighash::SighashCache::new(&htlc_tx).segwit_signature_hash(0, &htlc_redeemscript, this_htlc.amount_msat / 1000, EcdsaSighashType::All).unwrap()[..]);
1492 ret.push(sign(secp_ctx, &sighash, &holder_htlc_key));
1497 /// Gets a signed HTLC transaction given a preimage (for !htlc.offered) and the holder HTLC transaction signature.
1498 pub(crate) fn get_signed_htlc_tx(&self, channel_parameters: &DirectedChannelTransactionParameters, htlc_index: usize, counterparty_signature: &Signature, signature: &Signature, preimage: &Option<PaymentPreimage>) -> Transaction {
1499 let inner = self.inner;
1500 let keys = &inner.keys;
1501 let txid = inner.built.txid;
1502 let this_htlc = &inner.htlcs[htlc_index];
1503 assert!(this_htlc.transaction_output_index.is_some());
1504 // if we don't have preimage for an HTLC-Success, we can't generate an HTLC transaction.
1505 if !this_htlc.offered && preimage.is_none() { unreachable!(); }
1506 // Further, we should never be provided the preimage for an HTLC-Timeout transaction.
1507 if this_htlc.offered && preimage.is_some() { unreachable!(); }
1509 let mut htlc_tx = build_htlc_transaction(&txid, inner.feerate_per_kw, channel_parameters.contest_delay(), &this_htlc, self.opt_anchors(), &keys.broadcaster_delayed_payment_key, &keys.revocation_key);
1511 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);
1513 let sighashtype = if self.opt_anchors() { EcdsaSighashType::SinglePlusAnyoneCanPay } else { EcdsaSighashType::All };
1515 // First push the multisig dummy, note that due to BIP147 (NULLDUMMY) it must be a zero-length element.
1516 htlc_tx.input[0].witness.push(Vec::new());
1518 let mut cp_sig_ser = counterparty_signature.serialize_der().to_vec();
1519 cp_sig_ser.push(sighashtype as u8);
1520 htlc_tx.input[0].witness.push(cp_sig_ser);
1521 let mut holder_sig_ser = signature.serialize_der().to_vec();
1522 holder_sig_ser.push(EcdsaSighashType::All as u8);
1523 htlc_tx.input[0].witness.push(holder_sig_ser);
1525 if this_htlc.offered {
1526 // Due to BIP146 (MINIMALIF) this must be a zero-length element to relay.
1527 htlc_tx.input[0].witness.push(Vec::new());
1529 htlc_tx.input[0].witness.push(preimage.unwrap().0.to_vec());
1532 htlc_tx.input[0].witness.push(htlc_redeemscript.as_bytes().to_vec());
1537 /// Commitment transaction numbers which appear in the transactions themselves are XOR'd with a
1538 /// shared secret first. This prevents on-chain observers from discovering how many commitment
1539 /// transactions occurred in a channel before it was closed.
1541 /// This function gets the shared secret from relevant channel public keys and can be used to
1542 /// "decrypt" the commitment transaction number given a commitment transaction on-chain.
1543 pub fn get_commitment_transaction_number_obscure_factor(
1544 broadcaster_payment_basepoint: &PublicKey,
1545 countersignatory_payment_basepoint: &PublicKey,
1546 outbound_from_broadcaster: bool,
1548 let mut sha = Sha256::engine();
1550 if outbound_from_broadcaster {
1551 sha.input(&broadcaster_payment_basepoint.serialize());
1552 sha.input(&countersignatory_payment_basepoint.serialize());
1554 sha.input(&countersignatory_payment_basepoint.serialize());
1555 sha.input(&broadcaster_payment_basepoint.serialize());
1557 let res = Sha256::from_engine(sha).into_inner();
1559 ((res[26] as u64) << 5 * 8)
1560 | ((res[27] as u64) << 4 * 8)
1561 | ((res[28] as u64) << 3 * 8)
1562 | ((res[29] as u64) << 2 * 8)
1563 | ((res[30] as u64) << 1 * 8)
1564 | ((res[31] as u64) << 0 * 8)
1567 fn get_p2wpkh_redeemscript(key: &PublicKey) -> Script {
1568 Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0)
1569 .push_slice(&WPubkeyHash::hash(&key.serialize())[..])
1575 use super::CounterpartyCommitmentSecrets;
1578 use ln::chan_utils::{get_htlc_redeemscript, get_to_countersignatory_with_anchors_redeemscript, get_p2wpkh_redeemscript, CommitmentTransaction, TxCreationKeys, ChannelTransactionParameters, CounterpartyChannelTransactionParameters, HTLCOutputInCommitment};
1579 use bitcoin::secp256k1::{PublicKey, SecretKey, Secp256k1};
1580 use util::test_utils;
1581 use chain::keysinterface::{KeysInterface, BaseSign};
1582 use bitcoin::{Network, Txid};
1583 use bitcoin::hashes::Hash;
1584 use ln::PaymentHash;
1585 use bitcoin::hashes::hex::ToHex;
1589 let secp_ctx = Secp256k1::new();
1591 let seed = [42; 32];
1592 let network = Network::Testnet;
1593 let keys_provider = test_utils::TestKeysInterface::new(&seed, network);
1594 let signer = keys_provider.get_channel_signer(false, 3000);
1595 let counterparty_signer = keys_provider.get_channel_signer(false, 3000);
1596 let delayed_payment_base = &signer.pubkeys().delayed_payment_basepoint;
1597 let per_commitment_secret = SecretKey::from_slice(&hex::decode("1f1e1d1c1b1a191817161514131211100f0e0d0c0b0a09080706050403020100").unwrap()[..]).unwrap();
1598 let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &per_commitment_secret);
1599 let htlc_basepoint = &signer.pubkeys().htlc_basepoint;
1600 let holder_pubkeys = signer.pubkeys();
1601 let counterparty_pubkeys = counterparty_signer.pubkeys();
1602 let keys = TxCreationKeys::derive_new(&secp_ctx, &per_commitment_point, delayed_payment_base, htlc_basepoint, &counterparty_pubkeys.revocation_basepoint, &counterparty_pubkeys.htlc_basepoint).unwrap();
1603 let mut channel_parameters = ChannelTransactionParameters {
1604 holder_pubkeys: holder_pubkeys.clone(),
1605 holder_selected_contest_delay: 0,
1606 is_outbound_from_holder: false,
1607 counterparty_parameters: Some(CounterpartyChannelTransactionParameters { pubkeys: counterparty_pubkeys.clone(), selected_contest_delay: 0 }),
1608 funding_outpoint: Some(chain::transaction::OutPoint { txid: Txid::all_zeros(), index: 0 }),
1612 let mut htlcs_with_aux: Vec<(_, ())> = Vec::new();
1614 // Generate broadcaster and counterparty outputs
1615 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1618 holder_pubkeys.funding_pubkey,
1619 counterparty_pubkeys.funding_pubkey,
1621 &mut htlcs_with_aux, &channel_parameters.as_holder_broadcastable()
1623 assert_eq!(tx.built.transaction.output.len(), 2);
1624 assert_eq!(tx.built.transaction.output[1].script_pubkey, get_p2wpkh_redeemscript(&counterparty_pubkeys.payment_point));
1626 // Generate broadcaster and counterparty outputs as well as two anchors
1627 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1630 holder_pubkeys.funding_pubkey,
1631 counterparty_pubkeys.funding_pubkey,
1633 &mut htlcs_with_aux, &channel_parameters.as_holder_broadcastable()
1635 assert_eq!(tx.built.transaction.output.len(), 4);
1636 assert_eq!(tx.built.transaction.output[3].script_pubkey, get_to_countersignatory_with_anchors_redeemscript(&counterparty_pubkeys.payment_point).to_v0_p2wsh());
1638 // Generate broadcaster output and anchor
1639 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1642 holder_pubkeys.funding_pubkey,
1643 counterparty_pubkeys.funding_pubkey,
1645 &mut htlcs_with_aux, &channel_parameters.as_holder_broadcastable()
1647 assert_eq!(tx.built.transaction.output.len(), 2);
1649 // Generate counterparty output and anchor
1650 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1653 holder_pubkeys.funding_pubkey,
1654 counterparty_pubkeys.funding_pubkey,
1656 &mut htlcs_with_aux, &channel_parameters.as_holder_broadcastable()
1658 assert_eq!(tx.built.transaction.output.len(), 2);
1660 let received_htlc = HTLCOutputInCommitment {
1662 amount_msat: 400000,
1664 payment_hash: PaymentHash([42; 32]),
1665 transaction_output_index: None,
1668 let offered_htlc = HTLCOutputInCommitment {
1670 amount_msat: 600000,
1672 payment_hash: PaymentHash([43; 32]),
1673 transaction_output_index: None,
1676 // Generate broadcaster output and received and offered HTLC outputs, w/o anchors
1677 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1680 holder_pubkeys.funding_pubkey,
1681 counterparty_pubkeys.funding_pubkey,
1683 &mut vec![(received_htlc.clone(), ()), (offered_htlc.clone(), ())],
1684 &channel_parameters.as_holder_broadcastable()
1686 assert_eq!(tx.built.transaction.output.len(), 3);
1687 assert_eq!(tx.built.transaction.output[0].script_pubkey, get_htlc_redeemscript(&received_htlc, false, &keys).to_v0_p2wsh());
1688 assert_eq!(tx.built.transaction.output[1].script_pubkey, get_htlc_redeemscript(&offered_htlc, false, &keys).to_v0_p2wsh());
1689 assert_eq!(get_htlc_redeemscript(&received_htlc, false, &keys).to_v0_p2wsh().to_hex(),
1690 "002085cf52e41ba7c099a39df504e7b61f6de122971ceb53b06731876eaeb85e8dc5");
1691 assert_eq!(get_htlc_redeemscript(&offered_htlc, false, &keys).to_v0_p2wsh().to_hex(),
1692 "002049f0736bb335c61a04d2623a24df878a7592a3c51fa7258d41b2c85318265e73");
1694 // Generate broadcaster output and received and offered HTLC outputs, with anchors
1695 channel_parameters.opt_anchors = Some(());
1696 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1699 holder_pubkeys.funding_pubkey,
1700 counterparty_pubkeys.funding_pubkey,
1702 &mut vec![(received_htlc.clone(), ()), (offered_htlc.clone(), ())],
1703 &channel_parameters.as_holder_broadcastable()
1705 assert_eq!(tx.built.transaction.output.len(), 5);
1706 assert_eq!(tx.built.transaction.output[2].script_pubkey, get_htlc_redeemscript(&received_htlc, true, &keys).to_v0_p2wsh());
1707 assert_eq!(tx.built.transaction.output[3].script_pubkey, get_htlc_redeemscript(&offered_htlc, true, &keys).to_v0_p2wsh());
1708 assert_eq!(get_htlc_redeemscript(&received_htlc, true, &keys).to_v0_p2wsh().to_hex(),
1709 "002067114123af3f95405bae4fd930fc95de03e3c86baaee8b2dd29b43dd26cf613c");
1710 assert_eq!(get_htlc_redeemscript(&offered_htlc, true, &keys).to_v0_p2wsh().to_hex(),
1711 "0020a06e3b0d4fcf704f2b9c41e16a70099e39989466c3142b8573a1154542f28f57");
1715 fn test_per_commitment_storage() {
1716 // Test vectors from BOLT 3:
1717 let mut secrets: Vec<[u8; 32]> = Vec::new();
1720 macro_rules! test_secrets {
1722 let mut idx = 281474976710655;
1723 for secret in secrets.iter() {
1724 assert_eq!(monitor.get_secret(idx).unwrap(), *secret);
1727 assert_eq!(monitor.get_min_seen_secret(), idx + 1);
1728 assert!(monitor.get_secret(idx).is_none());
1733 // insert_secret correct sequence
1734 monitor = CounterpartyCommitmentSecrets::new();
1737 secrets.push([0; 32]);
1738 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1739 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1742 secrets.push([0; 32]);
1743 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1744 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1747 secrets.push([0; 32]);
1748 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1749 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1752 secrets.push([0; 32]);
1753 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1754 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
1757 secrets.push([0; 32]);
1758 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1759 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
1762 secrets.push([0; 32]);
1763 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1764 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
1767 secrets.push([0; 32]);
1768 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1769 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
1772 secrets.push([0; 32]);
1773 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1774 monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap();
1779 // insert_secret #1 incorrect
1780 monitor = CounterpartyCommitmentSecrets::new();
1783 secrets.push([0; 32]);
1784 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
1785 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1788 secrets.push([0; 32]);
1789 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1790 assert!(monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).is_err());
1794 // insert_secret #2 incorrect (#1 derived from incorrect)
1795 monitor = CounterpartyCommitmentSecrets::new();
1798 secrets.push([0; 32]);
1799 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
1800 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1803 secrets.push([0; 32]);
1804 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
1805 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1808 secrets.push([0; 32]);
1809 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1810 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1813 secrets.push([0; 32]);
1814 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1815 assert!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).is_err());
1819 // insert_secret #3 incorrect
1820 monitor = CounterpartyCommitmentSecrets::new();
1823 secrets.push([0; 32]);
1824 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1825 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1828 secrets.push([0; 32]);
1829 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1830 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1833 secrets.push([0; 32]);
1834 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
1835 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1838 secrets.push([0; 32]);
1839 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1840 assert!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).is_err());
1844 // insert_secret #4 incorrect (1,2,3 derived from incorrect)
1845 monitor = CounterpartyCommitmentSecrets::new();
1848 secrets.push([0; 32]);
1849 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
1850 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1853 secrets.push([0; 32]);
1854 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
1855 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1858 secrets.push([0; 32]);
1859 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
1860 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1863 secrets.push([0; 32]);
1864 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("ba65d7b0ef55a3ba300d4e87af29868f394f8f138d78a7011669c79b37b936f4").unwrap());
1865 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
1868 secrets.push([0; 32]);
1869 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1870 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
1873 secrets.push([0; 32]);
1874 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1875 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
1878 secrets.push([0; 32]);
1879 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1880 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
1883 secrets.push([0; 32]);
1884 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1885 assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
1889 // insert_secret #5 incorrect
1890 monitor = CounterpartyCommitmentSecrets::new();
1893 secrets.push([0; 32]);
1894 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1895 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1898 secrets.push([0; 32]);
1899 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1900 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1903 secrets.push([0; 32]);
1904 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1905 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1908 secrets.push([0; 32]);
1909 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1910 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
1913 secrets.push([0; 32]);
1914 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
1915 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
1918 secrets.push([0; 32]);
1919 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1920 assert!(monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).is_err());
1924 // insert_secret #6 incorrect (5 derived from incorrect)
1925 monitor = CounterpartyCommitmentSecrets::new();
1928 secrets.push([0; 32]);
1929 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1930 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1933 secrets.push([0; 32]);
1934 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1935 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1938 secrets.push([0; 32]);
1939 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1940 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1943 secrets.push([0; 32]);
1944 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1945 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
1948 secrets.push([0; 32]);
1949 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
1950 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
1953 secrets.push([0; 32]);
1954 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("b7e76a83668bde38b373970155c868a653304308f9896692f904a23731224bb1").unwrap());
1955 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
1958 secrets.push([0; 32]);
1959 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1960 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
1963 secrets.push([0; 32]);
1964 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1965 assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
1969 // insert_secret #7 incorrect
1970 monitor = CounterpartyCommitmentSecrets::new();
1973 secrets.push([0; 32]);
1974 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1975 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1978 secrets.push([0; 32]);
1979 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1980 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1983 secrets.push([0; 32]);
1984 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1985 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1988 secrets.push([0; 32]);
1989 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1990 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
1993 secrets.push([0; 32]);
1994 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1995 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
1998 secrets.push([0; 32]);
1999 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2000 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2003 secrets.push([0; 32]);
2004 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("e7971de736e01da8ed58b94c2fc216cb1dca9e326f3a96e7194fe8ea8af6c0a3").unwrap());
2005 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2008 secrets.push([0; 32]);
2009 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2010 assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
2014 // insert_secret #8 incorrect
2015 monitor = CounterpartyCommitmentSecrets::new();
2018 secrets.push([0; 32]);
2019 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2020 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2023 secrets.push([0; 32]);
2024 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2025 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2028 secrets.push([0; 32]);
2029 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2030 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2033 secrets.push([0; 32]);
2034 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2035 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2038 secrets.push([0; 32]);
2039 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2040 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2043 secrets.push([0; 32]);
2044 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2045 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2048 secrets.push([0; 32]);
2049 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2050 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2053 secrets.push([0; 32]);
2054 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a7efbc61aac46d34f77778bac22c8a20c6a46ca460addc49009bda875ec88fa4").unwrap());
2055 assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());