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::ChannelKeys message signing
14 use bitcoin::blockdata::script::{Script,Builder};
15 use bitcoin::blockdata::opcodes;
16 use bitcoin::blockdata::transaction::{TxIn,TxOut,OutPoint,Transaction, SigHashType};
17 use bitcoin::util::bip143;
19 use bitcoin::hashes::{Hash, HashEngine};
20 use bitcoin::hashes::sha256::Hash as Sha256;
21 use bitcoin::hashes::ripemd160::Hash as Ripemd160;
22 use bitcoin::hash_types::{Txid, PubkeyHash};
24 use ln::channelmanager::{PaymentHash, PaymentPreimage};
25 use ln::msgs::DecodeError;
26 use util::ser::{Readable, Writeable, Writer, MAX_BUF_SIZE};
29 use bitcoin::hash_types::WPubkeyHash;
30 use bitcoin::secp256k1::key::{SecretKey, PublicKey};
31 use bitcoin::secp256k1::{Secp256k1, Signature, Message};
32 use bitcoin::secp256k1::Error as SecpError;
33 use bitcoin::secp256k1;
37 use util::transaction_utils::sort_outputs;
38 use ln::channel::INITIAL_COMMITMENT_NUMBER;
43 const HTLC_OUTPUT_IN_COMMITMENT_SIZE: usize = 1 + 8 + 4 + 32 + 5;
45 pub(crate) const MAX_HTLCS: u16 = 483;
47 // This checks that the buffer size is greater than the maximum possible size for serialized HTLCS
48 const _EXCESS_BUFFER_SIZE: usize = MAX_BUF_SIZE - MAX_HTLCS as usize * HTLC_OUTPUT_IN_COMMITMENT_SIZE;
50 pub(super) const HTLC_SUCCESS_TX_WEIGHT: u64 = 703;
51 pub(super) const HTLC_TIMEOUT_TX_WEIGHT: u64 = 663;
54 pub(crate) enum HTLCType {
60 /// Check if a given tx witnessScript len matchs one of a pre-signed HTLC
61 pub(crate) fn scriptlen_to_htlctype(witness_script_len: usize) -> Option<HTLCType> {
62 if witness_script_len == 133 {
63 Some(HTLCType::OfferedHTLC)
64 } else if witness_script_len >= 136 && witness_script_len <= 139 {
65 Some(HTLCType::AcceptedHTLC)
72 // Various functions for key derivation and transaction creation for use within channels. Primarily
73 // used in Channel and ChannelMonitor.
75 /// Build the commitment secret from the seed and the commitment number
76 pub fn build_commitment_secret(commitment_seed: &[u8; 32], idx: u64) -> [u8; 32] {
77 let mut res: [u8; 32] = commitment_seed.clone();
80 if idx & (1 << bitpos) == (1 << bitpos) {
81 res[bitpos / 8] ^= 1 << (bitpos & 7);
82 res = Sha256::hash(&res).into_inner();
88 /// Implements the per-commitment secret storage scheme from
89 /// [BOLT 3](https://github.com/lightningnetwork/lightning-rfc/blob/dcbf8583976df087c79c3ce0b535311212e6812d/03-transactions.md#efficient-per-commitment-secret-storage).
91 /// Allows us to keep track of all of the revocation secrets of counterarties in just 50*32 bytes
94 pub(crate) struct CounterpartyCommitmentSecrets {
95 old_secrets: [([u8; 32], u64); 49],
98 impl PartialEq for CounterpartyCommitmentSecrets {
99 fn eq(&self, other: &Self) -> bool {
100 for (&(ref secret, ref idx), &(ref o_secret, ref o_idx)) in self.old_secrets.iter().zip(other.old_secrets.iter()) {
101 if secret != o_secret || idx != o_idx {
109 impl CounterpartyCommitmentSecrets {
110 pub(crate) fn new() -> Self {
111 Self { old_secrets: [([0; 32], 1 << 48); 49], }
115 fn place_secret(idx: u64) -> u8 {
117 if idx & (1 << i) == (1 << i) {
124 pub(crate) fn get_min_seen_secret(&self) -> u64 {
125 //TODO This can be optimized?
126 let mut min = 1 << 48;
127 for &(_, idx) in self.old_secrets.iter() {
136 fn derive_secret(secret: [u8; 32], bits: u8, idx: u64) -> [u8; 32] {
137 let mut res: [u8; 32] = secret;
139 let bitpos = bits - 1 - i;
140 if idx & (1 << bitpos) == (1 << bitpos) {
141 res[(bitpos / 8) as usize] ^= 1 << (bitpos & 7);
142 res = Sha256::hash(&res).into_inner();
148 pub(crate) fn provide_secret(&mut self, idx: u64, secret: [u8; 32]) -> Result<(), ()> {
149 let pos = Self::place_secret(idx);
151 let (old_secret, old_idx) = self.old_secrets[i as usize];
152 if Self::derive_secret(secret, pos, old_idx) != old_secret {
156 if self.get_min_seen_secret() <= idx {
159 self.old_secrets[pos as usize] = (secret, idx);
163 /// Can only fail if idx is < get_min_seen_secret
164 pub(crate) fn get_secret(&self, idx: u64) -> Option<[u8; 32]> {
165 for i in 0..self.old_secrets.len() {
166 if (idx & (!((1 << i) - 1))) == self.old_secrets[i].1 {
167 return Some(Self::derive_secret(self.old_secrets[i].0, i as u8, idx))
170 assert!(idx < self.get_min_seen_secret());
175 impl Writeable for CounterpartyCommitmentSecrets {
176 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
177 for &(ref secret, ref idx) in self.old_secrets.iter() {
178 writer.write_all(secret)?;
179 writer.write_all(&byte_utils::be64_to_array(*idx))?;
184 impl Readable for CounterpartyCommitmentSecrets {
185 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
186 let mut old_secrets = [([0; 32], 1 << 48); 49];
187 for &mut (ref mut secret, ref mut idx) in old_secrets.iter_mut() {
188 *secret = Readable::read(reader)?;
189 *idx = Readable::read(reader)?;
192 Ok(Self { old_secrets })
196 /// Derives a per-commitment-transaction private key (eg an htlc key or delayed_payment key)
197 /// from the base secret and the per_commitment_point.
199 /// Note that this is infallible iff we trust that at least one of the two input keys are randomly
200 /// generated (ie our own).
201 pub fn derive_private_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, base_secret: &SecretKey) -> Result<SecretKey, SecpError> {
202 let mut sha = Sha256::engine();
203 sha.input(&per_commitment_point.serialize());
204 sha.input(&PublicKey::from_secret_key(&secp_ctx, &base_secret).serialize());
205 let res = Sha256::from_engine(sha).into_inner();
207 let mut key = base_secret.clone();
208 key.add_assign(&res)?;
212 /// Derives a per-commitment-transaction public key (eg an htlc key or a delayed_payment key)
213 /// from the base point and the per_commitment_key. This is the public equivalent of
214 /// derive_private_key - using only public keys to derive a public key instead of private keys.
216 /// Note that this is infallible iff we trust that at least one of the two input keys are randomly
217 /// generated (ie our own).
218 pub fn derive_public_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, base_point: &PublicKey) -> Result<PublicKey, SecpError> {
219 let mut sha = Sha256::engine();
220 sha.input(&per_commitment_point.serialize());
221 sha.input(&base_point.serialize());
222 let res = Sha256::from_engine(sha).into_inner();
224 let hashkey = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&res)?);
225 base_point.combine(&hashkey)
228 /// Derives a per-commitment-transaction revocation key from its constituent parts.
230 /// Only the cheating participant owns a valid witness to propagate a revoked
231 /// commitment transaction, thus per_commitment_secret always come from cheater
232 /// and revocation_base_secret always come from punisher, which is the broadcaster
233 /// of the transaction spending with this key knowledge.
235 /// Note that this is infallible iff we trust that at least one of the two input keys are randomly
236 /// generated (ie our own).
237 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> {
238 let countersignatory_revocation_base_point = PublicKey::from_secret_key(&secp_ctx, &countersignatory_revocation_base_secret);
239 let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &per_commitment_secret);
241 let rev_append_commit_hash_key = {
242 let mut sha = Sha256::engine();
243 sha.input(&countersignatory_revocation_base_point.serialize());
244 sha.input(&per_commitment_point.serialize());
246 Sha256::from_engine(sha).into_inner()
248 let commit_append_rev_hash_key = {
249 let mut sha = Sha256::engine();
250 sha.input(&per_commitment_point.serialize());
251 sha.input(&countersignatory_revocation_base_point.serialize());
253 Sha256::from_engine(sha).into_inner()
256 let mut countersignatory_contrib = countersignatory_revocation_base_secret.clone();
257 countersignatory_contrib.mul_assign(&rev_append_commit_hash_key)?;
258 let mut broadcaster_contrib = per_commitment_secret.clone();
259 broadcaster_contrib.mul_assign(&commit_append_rev_hash_key)?;
260 countersignatory_contrib.add_assign(&broadcaster_contrib[..])?;
261 Ok(countersignatory_contrib)
264 /// Derives a per-commitment-transaction revocation public key from its constituent parts. This is
265 /// the public equivalend of derive_private_revocation_key - using only public keys to derive a
266 /// public key instead of private keys.
268 /// Only the cheating participant owns a valid witness to propagate a revoked
269 /// commitment transaction, thus per_commitment_point always come from cheater
270 /// and revocation_base_point always come from punisher, which is the broadcaster
271 /// of the transaction spending with this key knowledge.
273 /// Note that this is infallible iff we trust that at least one of the two input keys are randomly
274 /// generated (ie our own).
275 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> {
276 let rev_append_commit_hash_key = {
277 let mut sha = Sha256::engine();
278 sha.input(&countersignatory_revocation_base_point.serialize());
279 sha.input(&per_commitment_point.serialize());
281 Sha256::from_engine(sha).into_inner()
283 let commit_append_rev_hash_key = {
284 let mut sha = Sha256::engine();
285 sha.input(&per_commitment_point.serialize());
286 sha.input(&countersignatory_revocation_base_point.serialize());
288 Sha256::from_engine(sha).into_inner()
291 let mut countersignatory_contrib = countersignatory_revocation_base_point.clone();
292 countersignatory_contrib.mul_assign(&secp_ctx, &rev_append_commit_hash_key)?;
293 let mut broadcaster_contrib = per_commitment_point.clone();
294 broadcaster_contrib.mul_assign(&secp_ctx, &commit_append_rev_hash_key)?;
295 countersignatory_contrib.combine(&broadcaster_contrib)
298 /// The set of public keys which are used in the creation of one commitment transaction.
299 /// These are derived from the channel base keys and per-commitment data.
301 /// A broadcaster key is provided from potential broadcaster of the computed transaction.
302 /// A countersignatory key is coming from a protocol participant unable to broadcast the
305 /// These keys are assumed to be good, either because the code derived them from
306 /// channel basepoints via the new function, or they were obtained via
307 /// CommitmentTransaction.trust().keys() because we trusted the source of the
308 /// pre-calculated keys.
309 #[derive(PartialEq, Clone)]
310 pub struct TxCreationKeys {
311 /// The broadcaster's per-commitment public key which was used to derive the other keys.
312 pub per_commitment_point: PublicKey,
313 /// The revocation key which is used to allow the broadcaster of the commitment
314 /// transaction to provide their counterparty the ability to punish them if they broadcast
316 pub revocation_key: PublicKey,
317 /// Broadcaster's HTLC Key
318 pub broadcaster_htlc_key: PublicKey,
319 /// Countersignatory's HTLC Key
320 pub countersignatory_htlc_key: PublicKey,
321 /// Broadcaster's Payment Key (which isn't allowed to be spent from for some delay)
322 pub broadcaster_delayed_payment_key: PublicKey,
324 impl_writeable!(TxCreationKeys, 33*6,
325 { per_commitment_point, revocation_key, broadcaster_htlc_key, countersignatory_htlc_key, broadcaster_delayed_payment_key });
327 /// One counterparty's public keys which do not change over the life of a channel.
328 #[derive(Clone, PartialEq)]
329 pub struct ChannelPublicKeys {
330 /// The public key which is used to sign all commitment transactions, as it appears in the
331 /// on-chain channel lock-in 2-of-2 multisig output.
332 pub funding_pubkey: PublicKey,
333 /// The base point which is used (with derive_public_revocation_key) to derive per-commitment
334 /// revocation keys. This is combined with the per-commitment-secret generated by the
335 /// counterparty to create a secret which the counterparty can reveal to revoke previous
337 pub revocation_basepoint: PublicKey,
338 /// The public key on which the non-broadcaster (ie the countersignatory) receives an immediately
339 /// spendable primary channel balance on the broadcaster's commitment transaction. This key is
340 /// static across every commitment transaction.
341 pub payment_point: PublicKey,
342 /// The base point which is used (with derive_public_key) to derive a per-commitment payment
343 /// public key which receives non-HTLC-encumbered funds which are only available for spending
344 /// after some delay (or can be claimed via the revocation path).
345 pub delayed_payment_basepoint: PublicKey,
346 /// The base point which is used (with derive_public_key) to derive a per-commitment public key
347 /// which is used to encumber HTLC-in-flight outputs.
348 pub htlc_basepoint: PublicKey,
351 impl_writeable!(ChannelPublicKeys, 33*5, {
353 revocation_basepoint,
355 delayed_payment_basepoint,
360 impl TxCreationKeys {
361 /// Create per-state keys from channel base points and the per-commitment point.
362 /// Key set is asymmetric and can't be used as part of counter-signatory set of transactions.
363 pub fn derive_new<T: secp256k1::Signing + secp256k1::Verification>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, broadcaster_delayed_payment_base: &PublicKey, broadcaster_htlc_base: &PublicKey, countersignatory_revocation_base: &PublicKey, countersignatory_htlc_base: &PublicKey) -> Result<TxCreationKeys, SecpError> {
365 per_commitment_point: per_commitment_point.clone(),
366 revocation_key: derive_public_revocation_key(&secp_ctx, &per_commitment_point, &countersignatory_revocation_base)?,
367 broadcaster_htlc_key: derive_public_key(&secp_ctx, &per_commitment_point, &broadcaster_htlc_base)?,
368 countersignatory_htlc_key: derive_public_key(&secp_ctx, &per_commitment_point, &countersignatory_htlc_base)?,
369 broadcaster_delayed_payment_key: derive_public_key(&secp_ctx, &per_commitment_point, &broadcaster_delayed_payment_base)?,
373 /// Generate per-state keys from channel static keys.
374 /// Key set is asymmetric and can't be used as part of counter-signatory set of transactions.
375 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> {
376 TxCreationKeys::derive_new(
378 &per_commitment_point,
379 &broadcaster_keys.delayed_payment_basepoint,
380 &broadcaster_keys.htlc_basepoint,
381 &countersignatory_keys.revocation_basepoint,
382 &countersignatory_keys.htlc_basepoint,
387 /// The maximum length of a script returned by get_revokeable_redeemscript.
388 // Calculated as 6 bytes of opcodes, 1 byte push plus 2 bytes for contest_delay, and two public
389 // keys of 33 bytes (+ 1 push).
390 pub const REVOKEABLE_REDEEMSCRIPT_MAX_LENGTH: usize = 6 + 3 + 34*2;
392 /// A script either spendable by the revocation
393 /// key or the broadcaster_delayed_payment_key and satisfying the relative-locktime OP_CSV constrain.
394 /// Encumbering a `to_holder` output on a commitment transaction or 2nd-stage HTLC transactions.
395 pub fn get_revokeable_redeemscript(revocation_key: &PublicKey, contest_delay: u16, broadcaster_delayed_payment_key: &PublicKey) -> Script {
396 let res = Builder::new().push_opcode(opcodes::all::OP_IF)
397 .push_slice(&revocation_key.serialize())
398 .push_opcode(opcodes::all::OP_ELSE)
399 .push_int(contest_delay as i64)
400 .push_opcode(opcodes::all::OP_CSV)
401 .push_opcode(opcodes::all::OP_DROP)
402 .push_slice(&broadcaster_delayed_payment_key.serialize())
403 .push_opcode(opcodes::all::OP_ENDIF)
404 .push_opcode(opcodes::all::OP_CHECKSIG)
406 debug_assert!(res.len() <= REVOKEABLE_REDEEMSCRIPT_MAX_LENGTH);
410 #[derive(Clone, PartialEq)]
411 /// Information about an HTLC as it appears in a commitment transaction
412 pub struct HTLCOutputInCommitment {
413 /// Whether the HTLC was "offered" (ie outbound in relation to this commitment transaction).
414 /// Note that this is not the same as whether it is ountbound *from us*. To determine that you
415 /// need to compare this value to whether the commitment transaction in question is that of
416 /// the counterparty or our own.
418 /// The value, in msat, of the HTLC. The value as it appears in the commitment transaction is
419 /// this divided by 1000.
420 pub amount_msat: u64,
421 /// The CLTV lock-time at which this HTLC expires.
422 pub cltv_expiry: u32,
423 /// The hash of the preimage which unlocks this HTLC.
424 pub payment_hash: PaymentHash,
425 /// The position within the commitment transactions' outputs. This may be None if the value is
426 /// below the dust limit (in which case no output appears in the commitment transaction and the
427 /// value is spent to additional transaction fees).
428 pub transaction_output_index: Option<u32>,
431 impl_writeable!(HTLCOutputInCommitment, HTLC_OUTPUT_IN_COMMITMENT_SIZE, {
436 transaction_output_index
440 pub(crate) fn get_htlc_redeemscript_with_explicit_keys(htlc: &HTLCOutputInCommitment, broadcaster_htlc_key: &PublicKey, countersignatory_htlc_key: &PublicKey, revocation_key: &PublicKey) -> Script {
441 let payment_hash160 = Ripemd160::hash(&htlc.payment_hash.0[..]).into_inner();
443 Builder::new().push_opcode(opcodes::all::OP_DUP)
444 .push_opcode(opcodes::all::OP_HASH160)
445 .push_slice(&PubkeyHash::hash(&revocation_key.serialize())[..])
446 .push_opcode(opcodes::all::OP_EQUAL)
447 .push_opcode(opcodes::all::OP_IF)
448 .push_opcode(opcodes::all::OP_CHECKSIG)
449 .push_opcode(opcodes::all::OP_ELSE)
450 .push_slice(&countersignatory_htlc_key.serialize()[..])
451 .push_opcode(opcodes::all::OP_SWAP)
452 .push_opcode(opcodes::all::OP_SIZE)
454 .push_opcode(opcodes::all::OP_EQUAL)
455 .push_opcode(opcodes::all::OP_NOTIF)
456 .push_opcode(opcodes::all::OP_DROP)
458 .push_opcode(opcodes::all::OP_SWAP)
459 .push_slice(&broadcaster_htlc_key.serialize()[..])
461 .push_opcode(opcodes::all::OP_CHECKMULTISIG)
462 .push_opcode(opcodes::all::OP_ELSE)
463 .push_opcode(opcodes::all::OP_HASH160)
464 .push_slice(&payment_hash160)
465 .push_opcode(opcodes::all::OP_EQUALVERIFY)
466 .push_opcode(opcodes::all::OP_CHECKSIG)
467 .push_opcode(opcodes::all::OP_ENDIF)
468 .push_opcode(opcodes::all::OP_ENDIF)
471 Builder::new().push_opcode(opcodes::all::OP_DUP)
472 .push_opcode(opcodes::all::OP_HASH160)
473 .push_slice(&PubkeyHash::hash(&revocation_key.serialize())[..])
474 .push_opcode(opcodes::all::OP_EQUAL)
475 .push_opcode(opcodes::all::OP_IF)
476 .push_opcode(opcodes::all::OP_CHECKSIG)
477 .push_opcode(opcodes::all::OP_ELSE)
478 .push_slice(&countersignatory_htlc_key.serialize()[..])
479 .push_opcode(opcodes::all::OP_SWAP)
480 .push_opcode(opcodes::all::OP_SIZE)
482 .push_opcode(opcodes::all::OP_EQUAL)
483 .push_opcode(opcodes::all::OP_IF)
484 .push_opcode(opcodes::all::OP_HASH160)
485 .push_slice(&payment_hash160)
486 .push_opcode(opcodes::all::OP_EQUALVERIFY)
488 .push_opcode(opcodes::all::OP_SWAP)
489 .push_slice(&broadcaster_htlc_key.serialize()[..])
491 .push_opcode(opcodes::all::OP_CHECKMULTISIG)
492 .push_opcode(opcodes::all::OP_ELSE)
493 .push_opcode(opcodes::all::OP_DROP)
494 .push_int(htlc.cltv_expiry as i64)
495 .push_opcode(opcodes::all::OP_CLTV)
496 .push_opcode(opcodes::all::OP_DROP)
497 .push_opcode(opcodes::all::OP_CHECKSIG)
498 .push_opcode(opcodes::all::OP_ENDIF)
499 .push_opcode(opcodes::all::OP_ENDIF)
504 /// Gets the witness redeemscript for an HTLC output in a commitment transaction. Note that htlc
505 /// does not need to have its previous_output_index filled.
507 pub fn get_htlc_redeemscript(htlc: &HTLCOutputInCommitment, keys: &TxCreationKeys) -> Script {
508 get_htlc_redeemscript_with_explicit_keys(htlc, &keys.broadcaster_htlc_key, &keys.countersignatory_htlc_key, &keys.revocation_key)
511 /// Gets the redeemscript for a funding output from the two funding public keys.
512 /// Note that the order of funding public keys does not matter.
513 pub fn make_funding_redeemscript(broadcaster: &PublicKey, countersignatory: &PublicKey) -> Script {
514 let broadcaster_funding_key = broadcaster.serialize();
515 let countersignatory_funding_key = countersignatory.serialize();
517 let builder = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2);
518 if broadcaster_funding_key[..] < countersignatory_funding_key[..] {
519 builder.push_slice(&broadcaster_funding_key)
520 .push_slice(&countersignatory_funding_key)
522 builder.push_slice(&countersignatory_funding_key)
523 .push_slice(&broadcaster_funding_key)
524 }.push_opcode(opcodes::all::OP_PUSHNUM_2).push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script()
527 /// panics if htlc.transaction_output_index.is_none()!
528 pub fn build_htlc_transaction(prev_hash: &Txid, feerate_per_kw: u32, contest_delay: u16, htlc: &HTLCOutputInCommitment, broadcaster_delayed_payment_key: &PublicKey, revocation_key: &PublicKey) -> Transaction {
529 let mut txins: Vec<TxIn> = Vec::new();
531 previous_output: OutPoint {
532 txid: prev_hash.clone(),
533 vout: htlc.transaction_output_index.expect("Can't build an HTLC transaction for a dust output"),
535 script_sig: Script::new(),
540 let total_fee = if htlc.offered {
541 feerate_per_kw as u64 * HTLC_TIMEOUT_TX_WEIGHT / 1000
543 feerate_per_kw as u64 * HTLC_SUCCESS_TX_WEIGHT / 1000
546 let mut txouts: Vec<TxOut> = Vec::new();
548 script_pubkey: get_revokeable_redeemscript(revocation_key, contest_delay, broadcaster_delayed_payment_key).to_v0_p2wsh(),
549 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)
554 lock_time: if htlc.offered { htlc.cltv_expiry } else { 0 },
560 /// Per-channel data used to build transactions in conjunction with the per-commitment data (CommitmentTransaction).
561 /// The fields are organized by holder/counterparty.
563 /// Normally, this is converted to the broadcaster/countersignatory-organized DirectedChannelTransactionParameters
564 /// before use, via the as_holder_broadcastable and as_counterparty_broadcastable functions.
566 pub struct ChannelTransactionParameters {
567 /// Holder public keys
568 pub holder_pubkeys: ChannelPublicKeys,
569 /// The contest delay selected by the holder, which applies to counterparty-broadcast transactions
570 pub holder_selected_contest_delay: u16,
571 /// Whether the holder is the initiator of this channel.
572 /// This is an input to the commitment number obscure factor computation.
573 pub is_outbound_from_holder: bool,
574 /// The late-bound counterparty channel transaction parameters.
575 /// These parameters are populated at the point in the protocol where the counterparty provides them.
576 pub counterparty_parameters: Option<CounterpartyChannelTransactionParameters>,
577 /// The late-bound funding outpoint
578 pub funding_outpoint: Option<chain::transaction::OutPoint>,
581 /// Late-bound per-channel counterparty data used to build transactions.
583 pub struct CounterpartyChannelTransactionParameters {
584 /// Counter-party public keys
585 pub pubkeys: ChannelPublicKeys,
586 /// The contest delay selected by the counterparty, which applies to holder-broadcast transactions
587 pub selected_contest_delay: u16,
590 impl ChannelTransactionParameters {
591 /// Whether the late bound parameters are populated.
592 pub fn is_populated(&self) -> bool {
593 self.counterparty_parameters.is_some() && self.funding_outpoint.is_some()
596 /// Convert the holder/counterparty parameters to broadcaster/countersignatory-organized parameters,
597 /// given that the holder is the broadcaster.
599 /// self.is_populated() must be true before calling this function.
600 pub fn as_holder_broadcastable(&self) -> DirectedChannelTransactionParameters {
601 assert!(self.is_populated(), "self.late_parameters must be set before using as_holder_broadcastable");
602 DirectedChannelTransactionParameters {
604 holder_is_broadcaster: true
608 /// Convert the holder/counterparty parameters to broadcaster/countersignatory-organized parameters,
609 /// given that the counterparty is the broadcaster.
611 /// self.is_populated() must be true before calling this function.
612 pub fn as_counterparty_broadcastable(&self) -> DirectedChannelTransactionParameters {
613 assert!(self.is_populated(), "self.late_parameters must be set before using as_counterparty_broadcastable");
614 DirectedChannelTransactionParameters {
616 holder_is_broadcaster: false
621 impl_writeable!(CounterpartyChannelTransactionParameters, 0, {
623 selected_contest_delay
626 impl_writeable!(ChannelTransactionParameters, 0, {
628 holder_selected_contest_delay,
629 is_outbound_from_holder,
630 counterparty_parameters,
634 /// Static channel fields used to build transactions given per-commitment fields, organized by
635 /// broadcaster/countersignatory.
637 /// This is derived from the holder/counterparty-organized ChannelTransactionParameters via the
638 /// as_holder_broadcastable and as_counterparty_broadcastable functions.
639 pub struct DirectedChannelTransactionParameters<'a> {
640 /// The holder's channel static parameters
641 inner: &'a ChannelTransactionParameters,
642 /// Whether the holder is the broadcaster
643 holder_is_broadcaster: bool,
646 impl<'a> DirectedChannelTransactionParameters<'a> {
647 /// Get the channel pubkeys for the broadcaster
648 pub fn broadcaster_pubkeys(&self) -> &ChannelPublicKeys {
649 if self.holder_is_broadcaster {
650 &self.inner.holder_pubkeys
652 &self.inner.counterparty_parameters.as_ref().unwrap().pubkeys
656 /// Get the channel pubkeys for the countersignatory
657 pub fn countersignatory_pubkeys(&self) -> &ChannelPublicKeys {
658 if self.holder_is_broadcaster {
659 &self.inner.counterparty_parameters.as_ref().unwrap().pubkeys
661 &self.inner.holder_pubkeys
665 /// Get the contest delay applicable to the transactions.
666 /// Note that the contest delay was selected by the countersignatory.
667 pub fn contest_delay(&self) -> u16 {
668 let counterparty_parameters = self.inner.counterparty_parameters.as_ref().unwrap();
669 if self.holder_is_broadcaster { counterparty_parameters.selected_contest_delay } else { self.inner.holder_selected_contest_delay }
672 /// Whether the channel is outbound from the broadcaster.
674 /// The boolean representing the side that initiated the channel is
675 /// an input to the commitment number obscure factor computation.
676 pub fn is_outbound(&self) -> bool {
677 if self.holder_is_broadcaster { self.inner.is_outbound_from_holder } else { !self.inner.is_outbound_from_holder }
680 /// The funding outpoint
681 pub fn funding_outpoint(&self) -> OutPoint {
682 self.inner.funding_outpoint.unwrap().into_bitcoin_outpoint()
686 /// Information needed to build and sign a holder's commitment transaction.
688 /// The transaction is only signed once we are ready to broadcast.
690 pub struct HolderCommitmentTransaction {
691 inner: CommitmentTransaction,
692 /// Our counterparty's signature for the transaction
693 pub counterparty_sig: Signature,
694 /// All non-dust counterparty HTLC signatures, in the order they appear in the transaction
695 pub counterparty_htlc_sigs: Vec<Signature>,
696 // Which order the signatures should go in when constructing the final commitment tx witness.
697 // The user should be able to reconstruct this themselves, so we don't bother to expose it.
698 holder_sig_first: bool,
701 impl Deref for HolderCommitmentTransaction {
702 type Target = CommitmentTransaction;
704 fn deref(&self) -> &Self::Target { &self.inner }
707 impl PartialEq for HolderCommitmentTransaction {
708 // We dont care whether we are signed in equality comparison
709 fn eq(&self, o: &Self) -> bool {
710 self.inner == o.inner
714 impl_writeable!(HolderCommitmentTransaction, 0, {
715 inner, counterparty_sig, counterparty_htlc_sigs, holder_sig_first
718 impl HolderCommitmentTransaction {
720 pub fn dummy() -> Self {
721 let secp_ctx = Secp256k1::new();
722 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
723 let dummy_sig = secp_ctx.sign(&secp256k1::Message::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[42; 32]).unwrap());
725 let keys = TxCreationKeys {
726 per_commitment_point: dummy_key.clone(),
727 revocation_key: dummy_key.clone(),
728 broadcaster_htlc_key: dummy_key.clone(),
729 countersignatory_htlc_key: dummy_key.clone(),
730 broadcaster_delayed_payment_key: dummy_key.clone(),
732 let channel_pubkeys = ChannelPublicKeys {
733 funding_pubkey: dummy_key.clone(),
734 revocation_basepoint: dummy_key.clone(),
735 payment_point: dummy_key.clone(),
736 delayed_payment_basepoint: dummy_key.clone(),
737 htlc_basepoint: dummy_key.clone()
739 let channel_parameters = ChannelTransactionParameters {
740 holder_pubkeys: channel_pubkeys.clone(),
741 holder_selected_contest_delay: 0,
742 is_outbound_from_holder: false,
743 counterparty_parameters: Some(CounterpartyChannelTransactionParameters { pubkeys: channel_pubkeys.clone(), selected_contest_delay: 0 }),
744 funding_outpoint: Some(chain::transaction::OutPoint { txid: Default::default(), index: 0 })
746 let mut htlcs_with_aux: Vec<(_, ())> = Vec::new();
747 let inner = CommitmentTransaction::new_with_auxiliary_htlc_data(0, 0, 0, keys, 0, &mut htlcs_with_aux, &channel_parameters.as_counterparty_broadcastable());
748 HolderCommitmentTransaction {
750 counterparty_sig: dummy_sig,
751 counterparty_htlc_sigs: Vec::new(),
752 holder_sig_first: false
756 /// Create a new holder transaction with the given counterparty signatures.
757 /// The funding keys are used to figure out which signature should go first when building the transaction for broadcast.
758 pub fn new(commitment_tx: CommitmentTransaction, counterparty_sig: Signature, counterparty_htlc_sigs: Vec<Signature>, holder_funding_key: &PublicKey, counterparty_funding_key: &PublicKey) -> Self {
760 inner: commitment_tx,
762 counterparty_htlc_sigs,
763 holder_sig_first: holder_funding_key.serialize()[..] < counterparty_funding_key.serialize()[..],
767 pub(crate) fn add_holder_sig(&self, funding_redeemscript: &Script, holder_sig: Signature) -> Transaction {
768 // First push the multisig dummy, note that due to BIP147 (NULLDUMMY) it must be a zero-length element.
769 let mut tx = self.inner.built.transaction.clone();
770 tx.input[0].witness.push(Vec::new());
772 if self.holder_sig_first {
773 tx.input[0].witness.push(holder_sig.serialize_der().to_vec());
774 tx.input[0].witness.push(self.counterparty_sig.serialize_der().to_vec());
776 tx.input[0].witness.push(self.counterparty_sig.serialize_der().to_vec());
777 tx.input[0].witness.push(holder_sig.serialize_der().to_vec());
779 tx.input[0].witness[1].push(SigHashType::All as u8);
780 tx.input[0].witness[2].push(SigHashType::All as u8);
782 tx.input[0].witness.push(funding_redeemscript.as_bytes().to_vec());
787 /// A pre-built Bitcoin commitment transaction and its txid.
789 pub struct BuiltCommitmentTransaction {
790 /// The commitment transaction
791 pub transaction: Transaction,
792 /// The txid for the commitment transaction.
794 /// This is provided as a performance optimization, instead of calling transaction.txid()
799 impl_writeable!(BuiltCommitmentTransaction, 0, { transaction, txid });
801 impl BuiltCommitmentTransaction {
802 /// Get the SIGHASH_ALL sighash value of the transaction.
804 /// This can be used to verify a signature.
805 pub fn get_sighash_all(&self, funding_redeemscript: &Script, channel_value_satoshis: u64) -> Message {
806 let sighash = &bip143::SigHashCache::new(&self.transaction).signature_hash(0, funding_redeemscript, channel_value_satoshis, SigHashType::All)[..];
807 hash_to_message!(sighash)
810 /// Sign a transaction, either because we are counter-signing the counterparty's transaction or
811 /// because we are about to broadcast a holder transaction.
812 pub fn sign<T: secp256k1::Signing>(&self, funding_key: &SecretKey, funding_redeemscript: &Script, channel_value_satoshis: u64, secp_ctx: &Secp256k1<T>) -> Signature {
813 let sighash = self.get_sighash_all(funding_redeemscript, channel_value_satoshis);
814 secp_ctx.sign(&sighash, funding_key)
818 /// This class tracks the per-transaction information needed to build a commitment transaction and to
819 /// actually build it and sign. It is used for holder transactions that we sign only when needed
820 /// and for transactions we sign for the counterparty.
822 /// This class can be used inside a signer implementation to generate a signature given the relevant
825 pub struct CommitmentTransaction {
826 commitment_number: u64,
827 to_broadcaster_value_sat: u64,
828 to_countersignatory_value_sat: u64,
830 htlcs: Vec<HTLCOutputInCommitment>,
831 // A cache of the parties' pubkeys required to construct the transaction, see doc for trust()
832 keys: TxCreationKeys,
833 // For access to the pre-built transaction, see doc for trust()
834 built: BuiltCommitmentTransaction,
837 impl PartialEq for CommitmentTransaction {
838 fn eq(&self, o: &Self) -> bool {
839 let eq = self.commitment_number == o.commitment_number &&
840 self.to_broadcaster_value_sat == o.to_broadcaster_value_sat &&
841 self.to_countersignatory_value_sat == o.to_countersignatory_value_sat &&
842 self.feerate_per_kw == o.feerate_per_kw &&
843 self.htlcs == o.htlcs &&
846 debug_assert_eq!(self.built.transaction, o.built.transaction);
847 debug_assert_eq!(self.built.txid, o.built.txid);
853 /// (C-not exported) as users never need to call this directly
854 impl Writeable for Vec<HTLCOutputInCommitment> {
856 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
857 (self.len() as u16).write(w)?;
858 for e in self.iter() {
865 /// (C-not exported) as users never need to call this directly
866 impl Readable for Vec<HTLCOutputInCommitment> {
868 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
869 let len: u16 = Readable::read(r)?;
870 let byte_size = (len as usize)
871 .checked_mul(HTLC_OUTPUT_IN_COMMITMENT_SIZE)
872 .ok_or(DecodeError::BadLengthDescriptor)?;
873 if byte_size > MAX_BUF_SIZE {
874 return Err(DecodeError::BadLengthDescriptor);
876 let mut ret = Vec::with_capacity(len as usize);
877 for _ in 0..len { ret.push(HTLCOutputInCommitment::read(r)?); }
882 impl_writeable!(CommitmentTransaction, 0, {
884 to_broadcaster_value_sat,
885 to_countersignatory_value_sat,
892 impl CommitmentTransaction {
893 /// Construct an object of the class while assigning transaction output indices to HTLCs.
895 /// Populates HTLCOutputInCommitment.transaction_output_index in htlcs_with_aux.
897 /// The generic T allows the caller to match the HTLC output index with auxiliary data.
898 /// This auxiliary data is not stored in this object.
900 /// Only include HTLCs that are above the dust limit for the channel.
902 /// (C-not exported) due to the generic though we likely should expose a version without
903 pub fn new_with_auxiliary_htlc_data<T>(commitment_number: u64, to_broadcaster_value_sat: u64, to_countersignatory_value_sat: u64, keys: TxCreationKeys, feerate_per_kw: u32, htlcs_with_aux: &mut Vec<(HTLCOutputInCommitment, T)>, channel_parameters: &DirectedChannelTransactionParameters) -> CommitmentTransaction {
904 // Sort outputs and populate output indices while keeping track of the auxiliary data
905 let (outputs, htlcs) = Self::internal_build_outputs(&keys, to_broadcaster_value_sat, to_countersignatory_value_sat, htlcs_with_aux, channel_parameters).unwrap();
907 let (obscured_commitment_transaction_number, txins) = Self::internal_build_inputs(commitment_number, channel_parameters);
908 let transaction = Self::make_transaction(obscured_commitment_transaction_number, txins, outputs);
909 let txid = transaction.txid();
910 CommitmentTransaction {
912 to_broadcaster_value_sat,
913 to_countersignatory_value_sat,
917 built: BuiltCommitmentTransaction {
924 fn internal_rebuild_transaction(&self, keys: &TxCreationKeys, channel_parameters: &DirectedChannelTransactionParameters) -> Result<BuiltCommitmentTransaction, ()> {
925 let (obscured_commitment_transaction_number, txins) = Self::internal_build_inputs(self.commitment_number, channel_parameters);
927 let mut htlcs_with_aux = self.htlcs.iter().map(|h| (h.clone(), ())).collect();
928 let (outputs, _) = Self::internal_build_outputs(keys, self.to_broadcaster_value_sat, self.to_countersignatory_value_sat, &mut htlcs_with_aux, channel_parameters)?;
930 let transaction = Self::make_transaction(obscured_commitment_transaction_number, txins, outputs);
931 let txid = transaction.txid();
932 let built_transaction = BuiltCommitmentTransaction {
936 Ok(built_transaction)
939 fn make_transaction(obscured_commitment_transaction_number: u64, txins: Vec<TxIn>, outputs: Vec<TxOut>) -> Transaction {
942 lock_time: ((0x20 as u32) << 8 * 3) | ((obscured_commitment_transaction_number & 0xffffffu64) as u32),
948 // This is used in two cases:
949 // - initial sorting of outputs / HTLCs in the constructor, in which case T is auxiliary data the
950 // caller needs to have sorted together with the HTLCs so it can keep track of the output index
951 // - building of a bitcoin transaction during a verify() call, in which case T is just ()
952 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) -> Result<(Vec<TxOut>, Vec<HTLCOutputInCommitment>), ()> {
953 let countersignatory_pubkeys = channel_parameters.countersignatory_pubkeys();
954 let contest_delay = channel_parameters.contest_delay();
956 let mut txouts: Vec<(TxOut, Option<&mut HTLCOutputInCommitment>)> = Vec::new();
958 if to_countersignatory_value_sat > 0 {
959 let script = script_for_p2wpkh(&countersignatory_pubkeys.payment_point);
962 script_pubkey: script.clone(),
963 value: to_countersignatory_value_sat,
969 if to_broadcaster_value_sat > 0 {
970 let redeem_script = get_revokeable_redeemscript(
971 &keys.revocation_key,
973 &keys.broadcaster_delayed_payment_key,
977 script_pubkey: redeem_script.to_v0_p2wsh(),
978 value: to_broadcaster_value_sat,
984 let mut htlcs = Vec::with_capacity(htlcs_with_aux.len());
985 for (htlc, _) in htlcs_with_aux {
986 let script = chan_utils::get_htlc_redeemscript(&htlc, &keys);
988 script_pubkey: script.to_v0_p2wsh(),
989 value: htlc.amount_msat / 1000,
991 txouts.push((txout, Some(htlc)));
994 // Sort output in BIP-69 order (amount, scriptPubkey). Tie-breaks based on HTLC
995 // CLTV expiration height.
996 sort_outputs(&mut txouts, |a, b| {
997 if let &Some(ref a_htlcout) = a {
998 if let &Some(ref b_htlcout) = b {
999 a_htlcout.cltv_expiry.cmp(&b_htlcout.cltv_expiry)
1000 // Note that due to hash collisions, we have to have a fallback comparison
1001 // here for fuzztarget mode (otherwise at least chanmon_fail_consistency
1003 .then(a_htlcout.payment_hash.0.cmp(&b_htlcout.payment_hash.0))
1004 // For non-HTLC outputs, if they're copying our SPK we don't really care if we
1005 // close the channel due to mismatches - they're doing something dumb:
1006 } else { cmp::Ordering::Equal }
1007 } else { cmp::Ordering::Equal }
1010 let mut outputs = Vec::with_capacity(txouts.len());
1011 for (idx, out) in txouts.drain(..).enumerate() {
1012 if let Some(htlc) = out.1 {
1013 htlc.transaction_output_index = Some(idx as u32);
1014 htlcs.push(htlc.clone());
1016 outputs.push(out.0);
1018 Ok((outputs, htlcs))
1021 fn internal_build_inputs(commitment_number: u64, channel_parameters: &DirectedChannelTransactionParameters) -> (u64, Vec<TxIn>) {
1022 let broadcaster_pubkeys = channel_parameters.broadcaster_pubkeys();
1023 let countersignatory_pubkeys = channel_parameters.countersignatory_pubkeys();
1024 let commitment_transaction_number_obscure_factor = get_commitment_transaction_number_obscure_factor(
1025 &broadcaster_pubkeys.payment_point,
1026 &countersignatory_pubkeys.payment_point,
1027 channel_parameters.is_outbound(),
1030 let obscured_commitment_transaction_number =
1031 commitment_transaction_number_obscure_factor ^ (INITIAL_COMMITMENT_NUMBER - commitment_number);
1034 let mut ins: Vec<TxIn> = Vec::new();
1036 previous_output: channel_parameters.funding_outpoint(),
1037 script_sig: Script::new(),
1038 sequence: ((0x80 as u32) << 8 * 3)
1039 | ((obscured_commitment_transaction_number >> 3 * 8) as u32),
1040 witness: Vec::new(),
1044 (obscured_commitment_transaction_number, txins)
1047 /// The backwards-counting commitment number
1048 pub fn commitment_number(&self) -> u64 {
1049 self.commitment_number
1052 /// The value to be sent to the broadcaster
1053 pub fn to_broadcaster_value_sat(&self) -> u64 {
1054 self.to_broadcaster_value_sat
1057 /// The value to be sent to the counterparty
1058 pub fn to_countersignatory_value_sat(&self) -> u64 {
1059 self.to_countersignatory_value_sat
1062 /// The feerate paid per 1000-weight-unit in this commitment transaction.
1063 pub fn feerate_per_kw(&self) -> u32 {
1067 /// The non-dust HTLCs (direction, amt, height expiration, hash, transaction output index)
1068 /// which were included in this commitment transaction in output order.
1069 /// The transaction index is always populated.
1071 /// (C-not exported) as we cannot currently convert Vec references to/from C, though we should
1072 /// expose a less effecient version which creates a Vec of references in the future.
1073 pub fn htlcs(&self) -> &Vec<HTLCOutputInCommitment> {
1077 /// Trust our pre-built transaction and derived transaction creation public keys.
1079 /// Applies a wrapper which allows access to these fields.
1081 /// This should only be used if you fully trust the builder of this object. It should not
1082 /// be used by an external signer - instead use the verify function.
1083 pub fn trust(&self) -> TrustedCommitmentTransaction {
1084 TrustedCommitmentTransaction { inner: self }
1087 /// Verify our pre-built transaction and derived transaction creation public keys.
1089 /// Applies a wrapper which allows access to these fields.
1091 /// An external validating signer must call this method before signing
1092 /// or using the built transaction.
1093 pub fn verify<T: secp256k1::Signing + secp256k1::Verification>(&self, channel_parameters: &DirectedChannelTransactionParameters, broadcaster_keys: &ChannelPublicKeys, countersignatory_keys: &ChannelPublicKeys, secp_ctx: &Secp256k1<T>) -> Result<TrustedCommitmentTransaction, ()> {
1094 // This is the only field of the key cache that we trust
1095 let per_commitment_point = self.keys.per_commitment_point;
1096 let keys = TxCreationKeys::from_channel_static_keys(&per_commitment_point, broadcaster_keys, countersignatory_keys, secp_ctx).unwrap();
1097 if keys != self.keys {
1100 let tx = self.internal_rebuild_transaction(&keys, channel_parameters)?;
1101 if self.built.transaction != tx.transaction || self.built.txid != tx.txid {
1104 Ok(TrustedCommitmentTransaction { inner: self })
1108 /// A wrapper on CommitmentTransaction indicating that the derived fields (the built bitcoin
1109 /// transaction and the transaction creation keys) are trusted.
1111 /// See trust() and verify() functions on CommitmentTransaction.
1113 /// This structure implements Deref.
1114 pub struct TrustedCommitmentTransaction<'a> {
1115 inner: &'a CommitmentTransaction,
1118 impl<'a> Deref for TrustedCommitmentTransaction<'a> {
1119 type Target = CommitmentTransaction;
1121 fn deref(&self) -> &Self::Target { self.inner }
1124 impl<'a> TrustedCommitmentTransaction<'a> {
1125 /// The transaction ID of the built Bitcoin transaction
1126 pub fn txid(&self) -> Txid {
1127 self.inner.built.txid
1130 /// The pre-built Bitcoin commitment transaction
1131 pub fn built_transaction(&self) -> &BuiltCommitmentTransaction {
1135 /// The pre-calculated transaction creation public keys.
1136 pub fn keys(&self) -> &TxCreationKeys {
1140 /// Get a signature for each HTLC which was included in the commitment transaction (ie for
1141 /// which HTLCOutputInCommitment::transaction_output_index.is_some()).
1143 /// The returned Vec has one entry for each HTLC, and in the same order.
1144 pub fn get_htlc_sigs<T: secp256k1::Signing>(&self, htlc_base_key: &SecretKey, channel_parameters: &DirectedChannelTransactionParameters, secp_ctx: &Secp256k1<T>) -> Result<Vec<Signature>, ()> {
1145 let inner = self.inner;
1146 let keys = &inner.keys;
1147 let txid = inner.built.txid;
1148 let mut ret = Vec::with_capacity(inner.htlcs.len());
1149 let holder_htlc_key = derive_private_key(secp_ctx, &inner.keys.per_commitment_point, htlc_base_key).map_err(|_| ())?;
1151 for this_htlc in inner.htlcs.iter() {
1152 assert!(this_htlc.transaction_output_index.is_some());
1153 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);
1155 let htlc_redeemscript = get_htlc_redeemscript_with_explicit_keys(&this_htlc, &keys.broadcaster_htlc_key, &keys.countersignatory_htlc_key, &keys.revocation_key);
1157 let sighash = hash_to_message!(&bip143::SigHashCache::new(&htlc_tx).signature_hash(0, &htlc_redeemscript, this_htlc.amount_msat / 1000, SigHashType::All)[..]);
1158 ret.push(secp_ctx.sign(&sighash, &holder_htlc_key));
1163 /// Gets a signed HTLC transaction given a preimage (for !htlc.offered) and the holder HTLC transaction signature.
1164 pub(crate) fn get_signed_htlc_tx(&self, channel_parameters: &DirectedChannelTransactionParameters, htlc_index: usize, counterparty_signature: &Signature, signature: &Signature, preimage: &Option<PaymentPreimage>) -> Transaction {
1165 let inner = self.inner;
1166 let keys = &inner.keys;
1167 let txid = inner.built.txid;
1168 let this_htlc = &inner.htlcs[htlc_index];
1169 assert!(this_htlc.transaction_output_index.is_some());
1170 // if we don't have preimage for an HTLC-Success, we can't generate an HTLC transaction.
1171 if !this_htlc.offered && preimage.is_none() { unreachable!(); }
1172 // Further, we should never be provided the preimage for an HTLC-Timeout transaction.
1173 if this_htlc.offered && preimage.is_some() { unreachable!(); }
1175 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);
1177 let htlc_redeemscript = get_htlc_redeemscript_with_explicit_keys(&this_htlc, &keys.broadcaster_htlc_key, &keys.countersignatory_htlc_key, &keys.revocation_key);
1179 // First push the multisig dummy, note that due to BIP147 (NULLDUMMY) it must be a zero-length element.
1180 htlc_tx.input[0].witness.push(Vec::new());
1182 htlc_tx.input[0].witness.push(counterparty_signature.serialize_der().to_vec());
1183 htlc_tx.input[0].witness.push(signature.serialize_der().to_vec());
1184 htlc_tx.input[0].witness[1].push(SigHashType::All as u8);
1185 htlc_tx.input[0].witness[2].push(SigHashType::All as u8);
1187 if this_htlc.offered {
1188 // Due to BIP146 (MINIMALIF) this must be a zero-length element to relay.
1189 htlc_tx.input[0].witness.push(Vec::new());
1191 htlc_tx.input[0].witness.push(preimage.unwrap().0.to_vec());
1194 htlc_tx.input[0].witness.push(htlc_redeemscript.as_bytes().to_vec());
1199 /// Get the transaction number obscure factor
1200 pub fn get_commitment_transaction_number_obscure_factor(
1201 broadcaster_payment_basepoint: &PublicKey,
1202 countersignatory_payment_basepoint: &PublicKey,
1203 outbound_from_broadcaster: bool,
1205 let mut sha = Sha256::engine();
1207 if outbound_from_broadcaster {
1208 sha.input(&broadcaster_payment_basepoint.serialize());
1209 sha.input(&countersignatory_payment_basepoint.serialize());
1211 sha.input(&countersignatory_payment_basepoint.serialize());
1212 sha.input(&broadcaster_payment_basepoint.serialize());
1214 let res = Sha256::from_engine(sha).into_inner();
1216 ((res[26] as u64) << 5 * 8)
1217 | ((res[27] as u64) << 4 * 8)
1218 | ((res[28] as u64) << 3 * 8)
1219 | ((res[29] as u64) << 2 * 8)
1220 | ((res[30] as u64) << 1 * 8)
1221 | ((res[31] as u64) << 0 * 8)
1224 fn script_for_p2wpkh(key: &PublicKey) -> Script {
1225 Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0)
1226 .push_slice(&WPubkeyHash::hash(&key.serialize())[..])
1232 use super::CounterpartyCommitmentSecrets;
1236 fn test_per_commitment_storage() {
1237 // Test vectors from BOLT 3:
1238 let mut secrets: Vec<[u8; 32]> = Vec::new();
1241 macro_rules! test_secrets {
1243 let mut idx = 281474976710655;
1244 for secret in secrets.iter() {
1245 assert_eq!(monitor.get_secret(idx).unwrap(), *secret);
1248 assert_eq!(monitor.get_min_seen_secret(), idx + 1);
1249 assert!(monitor.get_secret(idx).is_none());
1254 // insert_secret correct sequence
1255 monitor = CounterpartyCommitmentSecrets::new();
1258 secrets.push([0; 32]);
1259 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1260 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1263 secrets.push([0; 32]);
1264 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1265 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1268 secrets.push([0; 32]);
1269 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1270 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1273 secrets.push([0; 32]);
1274 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1275 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
1278 secrets.push([0; 32]);
1279 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1280 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
1283 secrets.push([0; 32]);
1284 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1285 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
1288 secrets.push([0; 32]);
1289 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1290 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
1293 secrets.push([0; 32]);
1294 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1295 monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap();
1300 // insert_secret #1 incorrect
1301 monitor = CounterpartyCommitmentSecrets::new();
1304 secrets.push([0; 32]);
1305 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
1306 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1309 secrets.push([0; 32]);
1310 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1311 assert!(monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).is_err());
1315 // insert_secret #2 incorrect (#1 derived from incorrect)
1316 monitor = CounterpartyCommitmentSecrets::new();
1319 secrets.push([0; 32]);
1320 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
1321 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1324 secrets.push([0; 32]);
1325 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
1326 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1329 secrets.push([0; 32]);
1330 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1331 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1334 secrets.push([0; 32]);
1335 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1336 assert!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).is_err());
1340 // insert_secret #3 incorrect
1341 monitor = CounterpartyCommitmentSecrets::new();
1344 secrets.push([0; 32]);
1345 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1346 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1349 secrets.push([0; 32]);
1350 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1351 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1354 secrets.push([0; 32]);
1355 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
1356 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1359 secrets.push([0; 32]);
1360 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1361 assert!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).is_err());
1365 // insert_secret #4 incorrect (1,2,3 derived from incorrect)
1366 monitor = CounterpartyCommitmentSecrets::new();
1369 secrets.push([0; 32]);
1370 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
1371 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1374 secrets.push([0; 32]);
1375 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
1376 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1379 secrets.push([0; 32]);
1380 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
1381 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1384 secrets.push([0; 32]);
1385 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("ba65d7b0ef55a3ba300d4e87af29868f394f8f138d78a7011669c79b37b936f4").unwrap());
1386 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
1389 secrets.push([0; 32]);
1390 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1391 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
1394 secrets.push([0; 32]);
1395 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1396 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
1399 secrets.push([0; 32]);
1400 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1401 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
1404 secrets.push([0; 32]);
1405 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1406 assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
1410 // insert_secret #5 incorrect
1411 monitor = CounterpartyCommitmentSecrets::new();
1414 secrets.push([0; 32]);
1415 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1416 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1419 secrets.push([0; 32]);
1420 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1421 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1424 secrets.push([0; 32]);
1425 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1426 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1429 secrets.push([0; 32]);
1430 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1431 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
1434 secrets.push([0; 32]);
1435 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
1436 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
1439 secrets.push([0; 32]);
1440 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1441 assert!(monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).is_err());
1445 // insert_secret #6 incorrect (5 derived from incorrect)
1446 monitor = CounterpartyCommitmentSecrets::new();
1449 secrets.push([0; 32]);
1450 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1451 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1454 secrets.push([0; 32]);
1455 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1456 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1459 secrets.push([0; 32]);
1460 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1461 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1464 secrets.push([0; 32]);
1465 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1466 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
1469 secrets.push([0; 32]);
1470 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
1471 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
1474 secrets.push([0; 32]);
1475 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("b7e76a83668bde38b373970155c868a653304308f9896692f904a23731224bb1").unwrap());
1476 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
1479 secrets.push([0; 32]);
1480 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1481 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
1484 secrets.push([0; 32]);
1485 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1486 assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
1490 // insert_secret #7 incorrect
1491 monitor = CounterpartyCommitmentSecrets::new();
1494 secrets.push([0; 32]);
1495 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1496 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1499 secrets.push([0; 32]);
1500 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1501 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1504 secrets.push([0; 32]);
1505 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1506 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1509 secrets.push([0; 32]);
1510 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1511 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
1514 secrets.push([0; 32]);
1515 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1516 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
1519 secrets.push([0; 32]);
1520 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1521 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
1524 secrets.push([0; 32]);
1525 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("e7971de736e01da8ed58b94c2fc216cb1dca9e326f3a96e7194fe8ea8af6c0a3").unwrap());
1526 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
1529 secrets.push([0; 32]);
1530 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1531 assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
1535 // insert_secret #8 incorrect
1536 monitor = CounterpartyCommitmentSecrets::new();
1539 secrets.push([0; 32]);
1540 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1541 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1544 secrets.push([0; 32]);
1545 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1546 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1549 secrets.push([0; 32]);
1550 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1551 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1554 secrets.push([0; 32]);
1555 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1556 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
1559 secrets.push([0; 32]);
1560 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1561 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
1564 secrets.push([0; 32]);
1565 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1566 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
1569 secrets.push([0; 32]);
1570 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1571 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
1574 secrets.push([0; 32]);
1575 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a7efbc61aac46d34f77778bac22c8a20c6a46ca460addc49009bda875ec88fa4").unwrap());
1576 assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());