@@ -3452,6 +3452,132 @@ impl<SP: Deref> ChannelContext<SP> where SP::Target: SignerProvider {
34523452 !matches!(self.channel_state, ChannelState::AwaitingChannelReady(flags) if flags.is_set(AwaitingChannelReadyFlags::WAITING_FOR_BATCH))
34533453 }
34543454
3455+ fn validate_commitment_signed<L: Deref>(
3456+ &self, funding: &FundingScope, holder_commitment_point: &HolderCommitmentPoint,
3457+ msg: &msgs::CommitmentSigned, logger: &L,
3458+ ) -> Result<LatestHolderCommitmentTXInfo, ChannelError>
3459+ where
3460+ L::Target: Logger,
3461+ {
3462+ let funding_script = funding.get_funding_redeemscript();
3463+
3464+ let keys = self.build_holder_transaction_keys(funding, holder_commitment_point.current_point());
3465+
3466+ let commitment_stats = self.build_commitment_transaction(funding, holder_commitment_point.transaction_number(), &keys, true, false, logger);
3467+ let commitment_txid = {
3468+ let trusted_tx = commitment_stats.tx.trust();
3469+ let bitcoin_tx = trusted_tx.built_transaction();
3470+ let sighash = bitcoin_tx.get_sighash_all(&funding_script, funding.get_value_satoshis());
3471+
3472+ log_trace!(logger, "Checking commitment tx signature {} by key {} against tx {} (sighash {}) with redeemscript {} in channel {}",
3473+ log_bytes!(msg.signature.serialize_compact()[..]),
3474+ log_bytes!(funding.counterparty_funding_pubkey().serialize()), encode::serialize_hex(&bitcoin_tx.transaction),
3475+ log_bytes!(sighash[..]), encode::serialize_hex(&funding_script), &self.channel_id());
3476+ if let Err(_) = self.secp_ctx.verify_ecdsa(&sighash, &msg.signature, &funding.counterparty_funding_pubkey()) {
3477+ return Err(ChannelError::close("Invalid commitment tx signature from peer".to_owned()));
3478+ }
3479+ bitcoin_tx.txid
3480+ };
3481+ let mut htlcs_cloned: Vec<_> = commitment_stats.htlcs_included.iter().map(|htlc| (htlc.0.clone(), htlc.1.map(|h| h.clone()))).collect();
3482+
3483+ // If our counterparty updated the channel fee in this commitment transaction, check that
3484+ // they can actually afford the new fee now.
3485+ let update_fee = if let Some((_, update_state)) = self.pending_update_fee {
3486+ update_state == FeeUpdateState::RemoteAnnounced
3487+ } else { false };
3488+ if update_fee {
3489+ debug_assert!(!funding.is_outbound());
3490+ let counterparty_reserve_we_require_msat = funding.holder_selected_channel_reserve_satoshis * 1000;
3491+ if commitment_stats.remote_balance_msat < commitment_stats.total_fee_sat * 1000 + counterparty_reserve_we_require_msat {
3492+ return Err(ChannelError::close("Funding remote cannot afford proposed new fee".to_owned()));
3493+ }
3494+ }
3495+ #[cfg(any(test, fuzzing))]
3496+ {
3497+ if funding.is_outbound() {
3498+ let projected_commit_tx_info = funding.next_local_commitment_tx_fee_info_cached.lock().unwrap().take();
3499+ *funding.next_remote_commitment_tx_fee_info_cached.lock().unwrap() = None;
3500+ if let Some(info) = projected_commit_tx_info {
3501+ let total_pending_htlcs = self.pending_inbound_htlcs.len() + self.pending_outbound_htlcs.len()
3502+ + self.holding_cell_htlc_updates.len();
3503+ if info.total_pending_htlcs == total_pending_htlcs
3504+ && info.next_holder_htlc_id == self.next_holder_htlc_id
3505+ && info.next_counterparty_htlc_id == self.next_counterparty_htlc_id
3506+ && info.feerate == self.feerate_per_kw {
3507+ assert_eq!(commitment_stats.total_fee_sat, info.fee / 1000);
3508+ }
3509+ }
3510+ }
3511+ }
3512+
3513+ if msg.htlc_signatures.len() != commitment_stats.num_nondust_htlcs {
3514+ return Err(ChannelError::close(format!("Got wrong number of HTLC signatures ({}) from remote. It must be {}", msg.htlc_signatures.len(), commitment_stats.num_nondust_htlcs)));
3515+ }
3516+
3517+ // Up to LDK 0.0.115, HTLC information was required to be duplicated in the
3518+ // `htlcs_and_sigs` vec and in the `holder_commitment_tx` itself, both of which were passed
3519+ // in the `ChannelMonitorUpdate`. In 0.0.115, support for having a separate set of
3520+ // outbound-non-dust-HTLCSources in the `ChannelMonitorUpdate` was added, however for
3521+ // backwards compatibility, we never use it in production. To provide test coverage, here,
3522+ // we randomly decide (in test/fuzzing builds) to use the new vec sometimes.
3523+ #[allow(unused_assignments, unused_mut)]
3524+ let mut separate_nondust_htlc_sources = false;
3525+ #[cfg(all(feature = "std", any(test, fuzzing)))] {
3526+ use core::hash::{BuildHasher, Hasher};
3527+ // Get a random value using the only std API to do so - the DefaultHasher
3528+ let rand_val = std::collections::hash_map::RandomState::new().build_hasher().finish();
3529+ separate_nondust_htlc_sources = rand_val % 2 == 0;
3530+ }
3531+
3532+ let mut nondust_htlc_sources = Vec::with_capacity(htlcs_cloned.len());
3533+ let mut htlcs_and_sigs = Vec::with_capacity(htlcs_cloned.len());
3534+ for (idx, (htlc, mut source_opt)) in htlcs_cloned.drain(..).enumerate() {
3535+ if let Some(_) = htlc.transaction_output_index {
3536+ let htlc_tx = chan_utils::build_htlc_transaction(&commitment_txid, commitment_stats.feerate_per_kw,
3537+ funding.get_counterparty_selected_contest_delay().unwrap(), &htlc, &self.channel_type,
3538+ &keys.broadcaster_delayed_payment_key, &keys.revocation_key);
3539+
3540+ let htlc_redeemscript = chan_utils::get_htlc_redeemscript(&htlc, &self.channel_type, &keys);
3541+ let htlc_sighashtype = if self.channel_type.supports_anchors_zero_fee_htlc_tx() { EcdsaSighashType::SinglePlusAnyoneCanPay } else { EcdsaSighashType::All };
3542+ let htlc_sighash = hash_to_message!(&sighash::SighashCache::new(&htlc_tx).p2wsh_signature_hash(0, &htlc_redeemscript, htlc.to_bitcoin_amount(), htlc_sighashtype).unwrap()[..]);
3543+ log_trace!(logger, "Checking HTLC tx signature {} by key {} against tx {} (sighash {}) with redeemscript {} in channel {}.",
3544+ log_bytes!(msg.htlc_signatures[idx].serialize_compact()[..]), log_bytes!(keys.countersignatory_htlc_key.to_public_key().serialize()),
3545+ encode::serialize_hex(&htlc_tx), log_bytes!(htlc_sighash[..]), encode::serialize_hex(&htlc_redeemscript), &self.channel_id());
3546+ if let Err(_) = self.secp_ctx.verify_ecdsa(&htlc_sighash, &msg.htlc_signatures[idx], &keys.countersignatory_htlc_key.to_public_key()) {
3547+ return Err(ChannelError::close("Invalid HTLC tx signature from peer".to_owned()));
3548+ }
3549+ if !separate_nondust_htlc_sources {
3550+ htlcs_and_sigs.push((htlc, Some(msg.htlc_signatures[idx]), source_opt.take()));
3551+ }
3552+ } else {
3553+ htlcs_and_sigs.push((htlc, None, source_opt.take()));
3554+ }
3555+ if separate_nondust_htlc_sources {
3556+ if let Some(source) = source_opt.take() {
3557+ nondust_htlc_sources.push(source);
3558+ }
3559+ }
3560+ debug_assert!(source_opt.is_none(), "HTLCSource should have been put somewhere");
3561+ }
3562+
3563+ let holder_commitment_tx = HolderCommitmentTransaction::new(
3564+ commitment_stats.tx,
3565+ msg.signature,
3566+ msg.htlc_signatures.clone(),
3567+ &funding.get_holder_pubkeys().funding_pubkey,
3568+ funding.counterparty_funding_pubkey()
3569+ );
3570+
3571+ self.holder_signer.as_ref().validate_holder_commitment(&holder_commitment_tx, commitment_stats.outbound_htlc_preimages)
3572+ .map_err(|_| ChannelError::close("Failed to validate our commitment".to_owned()))?;
3573+
3574+ Ok(LatestHolderCommitmentTXInfo {
3575+ commitment_tx: holder_commitment_tx,
3576+ htlc_outputs: htlcs_and_sigs,
3577+ nondust_htlc_sources,
3578+ })
3579+ }
3580+
34553581 /// Transaction nomenclature is somewhat confusing here as there are many different cases - a
34563582 /// transaction is referred to as "a's transaction" implying that a will be able to broadcast
34573583 /// the transaction. Thus, b will generally be sending a signature over such a transaction to
@@ -4707,7 +4833,7 @@ struct CommitmentTxInfoCached {
47074833}
47084834
47094835/// Partial data from ChannelMonitorUpdateStep::LatestHolderCommitmentTXInfo used to simplify the
4710- /// return type of `FundedChannel ::validate_commitment_signed`.
4836+ /// return type of `ChannelContext ::validate_commitment_signed`.
47114837struct LatestHolderCommitmentTXInfo {
47124838 pub commitment_tx: HolderCommitmentTransaction,
47134839 pub htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>,
@@ -5502,128 +5628,6 @@ impl<SP: Deref> FundedChannel<SP> where
55025628 Ok(channel_monitor)
55035629 }
55045630
5505- fn validate_commitment_signed<L: Deref>(&self, msg: &msgs::CommitmentSigned, logger: &L) -> Result<LatestHolderCommitmentTXInfo, ChannelError>
5506- where L::Target: Logger
5507- {
5508- let funding_script = self.funding.get_funding_redeemscript();
5509-
5510- let keys = self.context.build_holder_transaction_keys(&self.funding, self.holder_commitment_point.current_point());
5511-
5512- let commitment_stats = self.context.build_commitment_transaction(&self.funding, self.holder_commitment_point.transaction_number(), &keys, true, false, logger);
5513- let commitment_txid = {
5514- let trusted_tx = commitment_stats.tx.trust();
5515- let bitcoin_tx = trusted_tx.built_transaction();
5516- let sighash = bitcoin_tx.get_sighash_all(&funding_script, self.funding.get_value_satoshis());
5517-
5518- log_trace!(logger, "Checking commitment tx signature {} by key {} against tx {} (sighash {}) with redeemscript {} in channel {}",
5519- log_bytes!(msg.signature.serialize_compact()[..]),
5520- log_bytes!(self.funding.counterparty_funding_pubkey().serialize()), encode::serialize_hex(&bitcoin_tx.transaction),
5521- log_bytes!(sighash[..]), encode::serialize_hex(&funding_script), &self.context.channel_id());
5522- if let Err(_) = self.context.secp_ctx.verify_ecdsa(&sighash, &msg.signature, &self.funding.counterparty_funding_pubkey()) {
5523- return Err(ChannelError::close("Invalid commitment tx signature from peer".to_owned()));
5524- }
5525- bitcoin_tx.txid
5526- };
5527- let mut htlcs_cloned: Vec<_> = commitment_stats.htlcs_included.iter().map(|htlc| (htlc.0.clone(), htlc.1.map(|h| h.clone()))).collect();
5528-
5529- // If our counterparty updated the channel fee in this commitment transaction, check that
5530- // they can actually afford the new fee now.
5531- let update_fee = if let Some((_, update_state)) = self.context.pending_update_fee {
5532- update_state == FeeUpdateState::RemoteAnnounced
5533- } else { false };
5534- if update_fee {
5535- debug_assert!(!self.funding.is_outbound());
5536- let counterparty_reserve_we_require_msat = self.funding.holder_selected_channel_reserve_satoshis * 1000;
5537- if commitment_stats.remote_balance_msat < commitment_stats.total_fee_sat * 1000 + counterparty_reserve_we_require_msat {
5538- return Err(ChannelError::close("Funding remote cannot afford proposed new fee".to_owned()));
5539- }
5540- }
5541- #[cfg(any(test, fuzzing))]
5542- {
5543- if self.funding.is_outbound() {
5544- let projected_commit_tx_info = self.funding.next_local_commitment_tx_fee_info_cached.lock().unwrap().take();
5545- *self.funding.next_remote_commitment_tx_fee_info_cached.lock().unwrap() = None;
5546- if let Some(info) = projected_commit_tx_info {
5547- let total_pending_htlcs = self.context.pending_inbound_htlcs.len() + self.context.pending_outbound_htlcs.len()
5548- + self.context.holding_cell_htlc_updates.len();
5549- if info.total_pending_htlcs == total_pending_htlcs
5550- && info.next_holder_htlc_id == self.context.next_holder_htlc_id
5551- && info.next_counterparty_htlc_id == self.context.next_counterparty_htlc_id
5552- && info.feerate == self.context.feerate_per_kw {
5553- assert_eq!(commitment_stats.total_fee_sat, info.fee / 1000);
5554- }
5555- }
5556- }
5557- }
5558-
5559- if msg.htlc_signatures.len() != commitment_stats.num_nondust_htlcs {
5560- return Err(ChannelError::close(format!("Got wrong number of HTLC signatures ({}) from remote. It must be {}", msg.htlc_signatures.len(), commitment_stats.num_nondust_htlcs)));
5561- }
5562-
5563- // Up to LDK 0.0.115, HTLC information was required to be duplicated in the
5564- // `htlcs_and_sigs` vec and in the `holder_commitment_tx` itself, both of which were passed
5565- // in the `ChannelMonitorUpdate`. In 0.0.115, support for having a separate set of
5566- // outbound-non-dust-HTLCSources in the `ChannelMonitorUpdate` was added, however for
5567- // backwards compatibility, we never use it in production. To provide test coverage, here,
5568- // we randomly decide (in test/fuzzing builds) to use the new vec sometimes.
5569- #[allow(unused_assignments, unused_mut)]
5570- let mut separate_nondust_htlc_sources = false;
5571- #[cfg(all(feature = "std", any(test, fuzzing)))] {
5572- use core::hash::{BuildHasher, Hasher};
5573- // Get a random value using the only std API to do so - the DefaultHasher
5574- let rand_val = std::collections::hash_map::RandomState::new().build_hasher().finish();
5575- separate_nondust_htlc_sources = rand_val % 2 == 0;
5576- }
5577-
5578- let mut nondust_htlc_sources = Vec::with_capacity(htlcs_cloned.len());
5579- let mut htlcs_and_sigs = Vec::with_capacity(htlcs_cloned.len());
5580- for (idx, (htlc, mut source_opt)) in htlcs_cloned.drain(..).enumerate() {
5581- if let Some(_) = htlc.transaction_output_index {
5582- let htlc_tx = chan_utils::build_htlc_transaction(&commitment_txid, commitment_stats.feerate_per_kw,
5583- self.funding.get_counterparty_selected_contest_delay().unwrap(), &htlc, &self.context.channel_type,
5584- &keys.broadcaster_delayed_payment_key, &keys.revocation_key);
5585-
5586- let htlc_redeemscript = chan_utils::get_htlc_redeemscript(&htlc, &self.context.channel_type, &keys);
5587- let htlc_sighashtype = if self.context.channel_type.supports_anchors_zero_fee_htlc_tx() { EcdsaSighashType::SinglePlusAnyoneCanPay } else { EcdsaSighashType::All };
5588- let htlc_sighash = hash_to_message!(&sighash::SighashCache::new(&htlc_tx).p2wsh_signature_hash(0, &htlc_redeemscript, htlc.to_bitcoin_amount(), htlc_sighashtype).unwrap()[..]);
5589- log_trace!(logger, "Checking HTLC tx signature {} by key {} against tx {} (sighash {}) with redeemscript {} in channel {}.",
5590- log_bytes!(msg.htlc_signatures[idx].serialize_compact()[..]), log_bytes!(keys.countersignatory_htlc_key.to_public_key().serialize()),
5591- encode::serialize_hex(&htlc_tx), log_bytes!(htlc_sighash[..]), encode::serialize_hex(&htlc_redeemscript), &self.context.channel_id());
5592- if let Err(_) = self.context.secp_ctx.verify_ecdsa(&htlc_sighash, &msg.htlc_signatures[idx], &keys.countersignatory_htlc_key.to_public_key()) {
5593- return Err(ChannelError::close("Invalid HTLC tx signature from peer".to_owned()));
5594- }
5595- if !separate_nondust_htlc_sources {
5596- htlcs_and_sigs.push((htlc, Some(msg.htlc_signatures[idx]), source_opt.take()));
5597- }
5598- } else {
5599- htlcs_and_sigs.push((htlc, None, source_opt.take()));
5600- }
5601- if separate_nondust_htlc_sources {
5602- if let Some(source) = source_opt.take() {
5603- nondust_htlc_sources.push(source);
5604- }
5605- }
5606- debug_assert!(source_opt.is_none(), "HTLCSource should have been put somewhere");
5607- }
5608-
5609- let holder_commitment_tx = HolderCommitmentTransaction::new(
5610- commitment_stats.tx,
5611- msg.signature,
5612- msg.htlc_signatures.clone(),
5613- &self.funding.get_holder_pubkeys().funding_pubkey,
5614- self.funding.counterparty_funding_pubkey()
5615- );
5616-
5617- self.context.holder_signer.as_ref().validate_holder_commitment(&holder_commitment_tx, commitment_stats.outbound_htlc_preimages)
5618- .map_err(|_| ChannelError::close("Failed to validate our commitment".to_owned()))?;
5619-
5620- Ok(LatestHolderCommitmentTXInfo {
5621- commitment_tx: holder_commitment_tx,
5622- htlc_outputs: htlcs_and_sigs,
5623- nondust_htlc_sources,
5624- })
5625- }
5626-
56275631 pub fn commitment_signed<L: Deref>(&mut self, msg: &msgs::CommitmentSigned, logger: &L) -> Result<Option<ChannelMonitorUpdate>, ChannelError>
56285632 where L::Target: Logger
56295633 {
@@ -5640,7 +5644,7 @@ impl<SP: Deref> FundedChannel<SP> where
56405644 return Err(ChannelError::close("Peer sent commitment_signed after we'd started exchanging closing_signeds".to_owned()));
56415645 }
56425646
5643- let commitment_tx_info = self.validate_commitment_signed(msg, logger)?;
5647+ let commitment_tx_info = self.context. validate_commitment_signed(&self.funding, &self.holder_commitment_point, msg, logger)?;
56445648
56455649 // Update state now that we've passed all the can-fail calls...
56465650 let mut need_commitment = false;
0 commit comments