Skip to content

Commit 1b5bcb0

Browse files
committed
Reorg return values of ChannelContext::build_commitment_transaction
We choose to include in `CommitmentStats` only fields that will be calculated or constructed by transaction builders. The other fields are created by channel, and placed in a new struct we call `CommitmentData`.
1 parent a983014 commit 1b5bcb0

File tree

1 file changed

+77
-44
lines changed

1 file changed

+77
-44
lines changed

lightning/src/ln/channel.rs

Lines changed: 77 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -877,15 +877,20 @@ struct HTLCStats {
877877
on_holder_tx_outbound_holding_cell_htlcs_count: u32, // dust HTLCs *non*-included
878878
}
879879

880-
/// An enum gathering stats on commitment transaction, either local or remote.
881-
struct CommitmentStats<'a> {
880+
/// A struct gathering data on a commitment, either local or remote.
881+
struct CommitmentData<'a> {
882+
stats: CommitmentStats,
883+
htlcs_included: Vec<(HTLCOutputInCommitment, Option<&'a HTLCSource>)>, // the list of HTLCs (dust HTLCs *included*) which were not ignored when building the transaction
884+
outbound_htlc_preimages: Vec<PaymentPreimage>, // preimages for successful offered HTLCs since last commitment
885+
inbound_htlc_preimages: Vec<PaymentPreimage>, // preimages for successful received HTLCs since last commitment
886+
}
887+
888+
/// A struct gathering stats on a commitment transaction, either local or remote.
889+
struct CommitmentStats {
882890
tx: CommitmentTransaction, // the transaction info
883891
total_fee_sat: u64, // the total fee included in the transaction
884-
htlcs_included: Vec<(HTLCOutputInCommitment, Option<&'a HTLCSource>)>, // the list of HTLCs (dust HTLCs *included*) which were not ignored when building the transaction
885892
local_balance_msat: u64, // local balance before fees *not* considering dust limits
886893
remote_balance_msat: u64, // remote balance before fees *not* considering dust limits
887-
outbound_htlc_preimages: Vec<PaymentPreimage>, // preimages for successful offered HTLCs since last commitment
888-
inbound_htlc_preimages: Vec<PaymentPreimage>, // preimages for successful received HTLCs since last commitment
889894
}
890895

891896
/// Used when calculating whether we or the remote can afford an additional HTLC.
@@ -2043,7 +2048,10 @@ trait InitialRemoteCommitmentReceiver<SP: Deref> where SP::Target: SignerProvide
20432048
) -> Result<CommitmentTransaction, ChannelError> where L::Target: Logger {
20442049
let funding_script = self.funding().get_funding_redeemscript();
20452050

2046-
let initial_commitment_tx = self.context().build_commitment_transaction(self.funding(), holder_commitment_point.transaction_number(), &holder_commitment_point.current_point(), true, false, logger).tx;
2051+
let commitment_data = self.context().build_commitment_transaction(self.funding(),
2052+
holder_commitment_point.transaction_number(), &holder_commitment_point.current_point(),
2053+
true, false, logger);
2054+
let initial_commitment_tx = commitment_data.stats.tx;
20472055
let trusted_tx = initial_commitment_tx.trust();
20482056
let initial_commitment_bitcoin_tx = trusted_tx.built_transaction();
20492057
let sighash = initial_commitment_bitcoin_tx.get_sighash_all(&funding_script, self.funding().get_value_satoshis());
@@ -2080,7 +2088,10 @@ trait InitialRemoteCommitmentReceiver<SP: Deref> where SP::Target: SignerProvide
20802088
}
20812089
};
20822090
let context = self.context();
2083-
let counterparty_initial_commitment_tx = context.build_commitment_transaction(self.funding(), context.cur_counterparty_commitment_transaction_number, &context.counterparty_cur_commitment_point.unwrap(), false, false, logger).tx;
2091+
let commitment_data = context.build_commitment_transaction(self.funding(),
2092+
context.cur_counterparty_commitment_transaction_number,
2093+
&context.counterparty_cur_commitment_point.unwrap(), false, false, logger);
2094+
let counterparty_initial_commitment_tx = commitment_data.stats.tx;
20842095
let counterparty_trusted_tx = counterparty_initial_commitment_tx.trust();
20852096
let counterparty_initial_bitcoin_tx = counterparty_trusted_tx.built_transaction();
20862097

@@ -3483,9 +3494,11 @@ impl<SP: Deref> ChannelContext<SP> where SP::Target: SignerProvider {
34833494
{
34843495
let funding_script = funding.get_funding_redeemscript();
34853496

3486-
let commitment_stats = self.build_commitment_transaction(funding, holder_commitment_point.transaction_number(), &holder_commitment_point.current_point(), true, false, logger);
3497+
let commitment_data = self.build_commitment_transaction(funding,
3498+
holder_commitment_point.transaction_number(), &holder_commitment_point.current_point(),
3499+
true, false, logger);
34873500
let commitment_txid = {
3488-
let trusted_tx = commitment_stats.tx.trust();
3501+
let trusted_tx = commitment_data.stats.tx.trust();
34893502
let bitcoin_tx = trusted_tx.built_transaction();
34903503
let sighash = bitcoin_tx.get_sighash_all(&funding_script, funding.get_value_satoshis());
34913504

@@ -3498,7 +3511,7 @@ impl<SP: Deref> ChannelContext<SP> where SP::Target: SignerProvider {
34983511
}
34993512
bitcoin_tx.txid
35003513
};
3501-
let mut htlcs_cloned: Vec<_> = commitment_stats.htlcs_included.iter().map(|htlc| (htlc.0.clone(), htlc.1.map(|h| h.clone()))).collect();
3514+
let mut htlcs_cloned: Vec<_> = commitment_data.htlcs_included.iter().map(|htlc| (htlc.0.clone(), htlc.1.map(|h| h.clone()))).collect();
35023515

35033516
// If our counterparty updated the channel fee in this commitment transaction, check that
35043517
// they can actually afford the new fee now.
@@ -3508,7 +3521,7 @@ impl<SP: Deref> ChannelContext<SP> where SP::Target: SignerProvider {
35083521
if update_fee {
35093522
debug_assert!(!funding.is_outbound());
35103523
let counterparty_reserve_we_require_msat = funding.holder_selected_channel_reserve_satoshis * 1000;
3511-
if commitment_stats.remote_balance_msat < commitment_stats.total_fee_sat * 1000 + counterparty_reserve_we_require_msat {
3524+
if commitment_data.stats.remote_balance_msat < commitment_data.stats.total_fee_sat * 1000 + counterparty_reserve_we_require_msat {
35123525
return Err(ChannelError::close("Funding remote cannot afford proposed new fee".to_owned()));
35133526
}
35143527
}
@@ -3524,14 +3537,14 @@ impl<SP: Deref> ChannelContext<SP> where SP::Target: SignerProvider {
35243537
&& info.next_holder_htlc_id == self.next_holder_htlc_id
35253538
&& info.next_counterparty_htlc_id == self.next_counterparty_htlc_id
35263539
&& info.feerate == self.feerate_per_kw {
3527-
assert_eq!(commitment_stats.total_fee_sat, info.fee / 1000);
3540+
assert_eq!(commitment_data.stats.total_fee_sat, info.fee / 1000);
35283541
}
35293542
}
35303543
}
35313544
}
35323545

3533-
if msg.htlc_signatures.len() != commitment_stats.tx.htlcs().len() {
3534-
return Err(ChannelError::close(format!("Got wrong number of HTLC signatures ({}) from remote. It must be {}", msg.htlc_signatures.len(), commitment_stats.tx.htlcs().len())));
3546+
if msg.htlc_signatures.len() != commitment_data.stats.tx.htlcs().len() {
3547+
return Err(ChannelError::close(format!("Got wrong number of HTLC signatures ({}) from remote. It must be {}", msg.htlc_signatures.len(), commitment_data.stats.tx.htlcs().len())));
35353548
}
35363549

35373550
// Up to LDK 0.0.115, HTLC information was required to be duplicated in the
@@ -3551,10 +3564,10 @@ impl<SP: Deref> ChannelContext<SP> where SP::Target: SignerProvider {
35513564

35523565
let mut nondust_htlc_sources = Vec::with_capacity(htlcs_cloned.len());
35533566
let mut htlcs_and_sigs = Vec::with_capacity(htlcs_cloned.len());
3554-
let holder_keys = commitment_stats.tx.trust().keys();
3567+
let holder_keys = commitment_data.stats.tx.trust().keys();
35553568
for (idx, (htlc, mut source_opt)) in htlcs_cloned.drain(..).enumerate() {
35563569
if let Some(_) = htlc.transaction_output_index {
3557-
let htlc_tx = chan_utils::build_htlc_transaction(&commitment_txid, commitment_stats.tx.feerate_per_kw(),
3570+
let htlc_tx = chan_utils::build_htlc_transaction(&commitment_txid, commitment_data.stats.tx.feerate_per_kw(),
35583571
funding.get_counterparty_selected_contest_delay().unwrap(), &htlc, &self.channel_type,
35593572
&holder_keys.broadcaster_delayed_payment_key, &holder_keys.revocation_key);
35603573

@@ -3582,14 +3595,14 @@ impl<SP: Deref> ChannelContext<SP> where SP::Target: SignerProvider {
35823595
}
35833596

35843597
let holder_commitment_tx = HolderCommitmentTransaction::new(
3585-
commitment_stats.tx,
3598+
commitment_data.stats.tx,
35863599
msg.signature,
35873600
msg.htlc_signatures.clone(),
35883601
&funding.get_holder_pubkeys().funding_pubkey,
35893602
funding.counterparty_funding_pubkey()
35903603
);
35913604

3592-
self.holder_signer.as_ref().validate_holder_commitment(&holder_commitment_tx, commitment_stats.outbound_htlc_preimages)
3605+
self.holder_signer.as_ref().validate_holder_commitment(&holder_commitment_tx, commitment_data.outbound_htlc_preimages)
35933606
.map_err(|_| ChannelError::close("Failed to validate our commitment".to_owned()))?;
35943607

35953608
Ok(LatestHolderCommitmentTXInfo {
@@ -3613,7 +3626,7 @@ impl<SP: Deref> ChannelContext<SP> where SP::Target: SignerProvider {
36133626
/// generated by the peer which proposed adding the HTLCs, and thus we need to understand both
36143627
/// which peer generated this transaction and "to whom" this transaction flows.
36153628
#[inline]
3616-
fn build_commitment_transaction<L: Deref>(&self, funding: &FundingScope, commitment_number: u64, per_commitment_point: &PublicKey, local: bool, generated_by_local: bool, logger: &L) -> CommitmentStats
3629+
fn build_commitment_transaction<L: Deref>(&self, funding: &FundingScope, commitment_number: u64, per_commitment_point: &PublicKey, local: bool, generated_by_local: bool, logger: &L) -> CommitmentData
36173630
where L::Target: Logger
36183631
{
36193632
let mut included_dust_htlcs: Vec<(HTLCOutputInCommitment, Option<&HTLCSource>)> = Vec::new();
@@ -3820,12 +3833,16 @@ impl<SP: Deref> ChannelContext<SP> where SP::Target: SignerProvider {
38203833
htlcs_included.sort_unstable_by_key(|h| h.0.transaction_output_index.unwrap());
38213834
htlcs_included.append(&mut included_dust_htlcs);
38223835

3823-
CommitmentStats {
3836+
let stats = CommitmentStats {
38243837
tx,
38253838
total_fee_sat,
3826-
htlcs_included,
38273839
local_balance_msat: value_to_self_msat,
38283840
remote_balance_msat: value_to_remote_msat,
3841+
};
3842+
3843+
CommitmentData {
3844+
stats,
3845+
htlcs_included,
38293846
inbound_htlc_preimages,
38303847
outbound_htlc_preimages,
38313848
}
@@ -4613,8 +4630,10 @@ impl<SP: Deref> ChannelContext<SP> where SP::Target: SignerProvider {
46134630
SP::Target: SignerProvider,
46144631
L::Target: Logger
46154632
{
4616-
let counterparty_initial_commitment_tx = self.build_commitment_transaction(
4617-
funding, self.cur_counterparty_commitment_transaction_number, &self.counterparty_cur_commitment_point.unwrap(), false, false, logger).tx;
4633+
let commitment_data = self.build_commitment_transaction(funding,
4634+
self.cur_counterparty_commitment_transaction_number,
4635+
&self.counterparty_cur_commitment_point.unwrap(), false, false, logger);
4636+
let counterparty_initial_commitment_tx = commitment_data.stats.tx;
46184637
match self.holder_signer {
46194638
// TODO (taproot|arik): move match into calling method for Taproot
46204639
ChannelSignerType::Ecdsa(ref ecdsa) => {
@@ -6328,9 +6347,11 @@ impl<SP: Deref> FundedChannel<SP> where
63286347
// Before proposing a feerate update, check that we can actually afford the new fee.
63296348
let dust_exposure_limiting_feerate = self.context.get_dust_exposure_limiting_feerate(&fee_estimator);
63306349
let htlc_stats = self.context.get_pending_htlc_stats(Some(feerate_per_kw), dust_exposure_limiting_feerate);
6331-
let commitment_stats = self.context.build_commitment_transaction(&self.funding, self.holder_commitment_point.transaction_number(), &self.holder_commitment_point.current_point(), true, true, logger);
6332-
let buffer_fee_msat = commit_tx_fee_sat(feerate_per_kw, commitment_stats.tx.htlcs().len() + htlc_stats.on_holder_tx_outbound_holding_cell_htlcs_count as usize + CONCURRENT_INBOUND_HTLC_FEE_BUFFER as usize, self.context.get_channel_type()) * 1000;
6333-
let holder_balance_msat = commitment_stats.local_balance_msat - htlc_stats.outbound_holding_cell_msat;
6350+
let commitment_data = self.context.build_commitment_transaction(&self.funding,
6351+
self.holder_commitment_point.transaction_number(),
6352+
&self.holder_commitment_point.current_point(), true, true, logger);
6353+
let buffer_fee_msat = commit_tx_fee_sat(feerate_per_kw, commitment_data.stats.tx.htlcs().len() + htlc_stats.on_holder_tx_outbound_holding_cell_htlcs_count as usize + CONCURRENT_INBOUND_HTLC_FEE_BUFFER as usize, self.context.get_channel_type()) * 1000;
6354+
let holder_balance_msat = commitment_data.stats.local_balance_msat - htlc_stats.outbound_holding_cell_msat;
63346355
if holder_balance_msat < buffer_fee_msat + self.funding.counterparty_selected_channel_reserve_satoshis.unwrap() * 1000 {
63356356
//TODO: auto-close after a number of failures?
63366357
log_debug!(logger, "Cannot afford to send new feerate at {}", feerate_per_kw);
@@ -6641,7 +6662,10 @@ impl<SP: Deref> FundedChannel<SP> where
66416662
self.holder_commitment_point.try_resolve_pending(&self.context.holder_signer, &self.context.secp_ctx, logger);
66426663
}
66436664
let funding_signed = if self.context.signer_pending_funding && !self.funding.is_outbound() {
6644-
let counterparty_initial_commitment_tx = self.context.build_commitment_transaction(&self.funding, self.context.cur_counterparty_commitment_transaction_number + 1, &self.context.counterparty_cur_commitment_point.unwrap(), false, false, logger).tx;
6665+
let commitment_data = self.context.build_commitment_transaction(&self.funding,
6666+
self.context.cur_counterparty_commitment_transaction_number + 1,
6667+
&self.context.counterparty_cur_commitment_point.unwrap(), false, false, logger);
6668+
let counterparty_initial_commitment_tx = commitment_data.stats.tx;
66456669
self.context.get_funding_signed_msg(&self.funding.channel_transaction_parameters, logger, counterparty_initial_commitment_tx)
66466670
} else { None };
66476671
// Provide a `channel_ready` message if we need to, but only if we're _not_ still pending
@@ -8712,8 +8736,10 @@ impl<SP: Deref> FundedChannel<SP> where
87128736
-> (Vec<(HTLCOutputInCommitment, Option<&HTLCSource>)>, CommitmentTransaction)
87138737
where L::Target: Logger
87148738
{
8715-
let commitment_stats = self.context.build_commitment_transaction(&self.funding, self.context.cur_counterparty_commitment_transaction_number, &self.context.counterparty_cur_commitment_point.unwrap(), false, true, logger);
8716-
let counterparty_commitment_tx = commitment_stats.tx;
8739+
let commitment_data = self.context.build_commitment_transaction(&self.funding,
8740+
self.context.cur_counterparty_commitment_transaction_number,
8741+
&self.context.counterparty_cur_commitment_point.unwrap(), false, true, logger);
8742+
let counterparty_commitment_tx = commitment_data.stats.tx;
87178743

87188744
#[cfg(any(test, fuzzing))]
87198745
{
@@ -8733,7 +8759,7 @@ impl<SP: Deref> FundedChannel<SP> where
87338759
}
87348760
}
87358761

8736-
(commitment_stats.htlcs_included, counterparty_commitment_tx)
8762+
(commitment_data.htlcs_included, counterparty_commitment_tx)
87378763
}
87388764

87398765
/// Only fails in case of signer rejection. Used for channel_reestablish commitment_signed
@@ -8743,8 +8769,10 @@ impl<SP: Deref> FundedChannel<SP> where
87438769
#[cfg(any(test, fuzzing))]
87448770
self.build_commitment_no_state_update(logger);
87458771

8746-
let commitment_stats = self.context.build_commitment_transaction(&self.funding, self.context.cur_counterparty_commitment_transaction_number, &self.context.counterparty_cur_commitment_point.unwrap(), false, true, logger);
8747-
let counterparty_commitment_txid = commitment_stats.tx.trust().txid();
8772+
let commitment_data = self.context.build_commitment_transaction(&self.funding,
8773+
self.context.cur_counterparty_commitment_transaction_number,
8774+
&self.context.counterparty_cur_commitment_point.unwrap(), false, true, logger);
8775+
let counterparty_commitment_tx = commitment_data.stats.tx;
87488776

87498777
match &self.context.holder_signer {
87508778
ChannelSignerType::Ecdsa(ecdsa) => {
@@ -8753,24 +8781,25 @@ impl<SP: Deref> FundedChannel<SP> where
87538781
{
87548782
let res = ecdsa.sign_counterparty_commitment(
87558783
&self.funding.channel_transaction_parameters,
8756-
&commitment_stats.tx,
8757-
commitment_stats.inbound_htlc_preimages,
8758-
commitment_stats.outbound_htlc_preimages,
8784+
&counterparty_commitment_tx,
8785+
commitment_data.inbound_htlc_preimages,
8786+
commitment_data.outbound_htlc_preimages,
87598787
&self.context.secp_ctx,
87608788
).map_err(|_| ChannelError::Ignore("Failed to get signatures for new commitment_signed".to_owned()))?;
87618789
signature = res.0;
87628790
htlc_signatures = res.1;
87638791

8792+
let trusted_tx = counterparty_commitment_tx.trust();
87648793
log_trace!(logger, "Signed remote commitment tx {} (txid {}) with redeemscript {} -> {} in channel {}",
8765-
encode::serialize_hex(&commitment_stats.tx.trust().built_transaction().transaction),
8766-
&counterparty_commitment_txid, encode::serialize_hex(&self.funding.get_funding_redeemscript()),
8794+
encode::serialize_hex(&trusted_tx.built_transaction().transaction),
8795+
&trusted_tx.txid(), encode::serialize_hex(&self.funding.get_funding_redeemscript()),
87678796
log_bytes!(signature.serialize_compact()[..]), &self.context.channel_id());
87688797

8769-
let counterparty_keys = commitment_stats.tx.trust().keys();
8770-
debug_assert_eq!(htlc_signatures.len(), commitment_stats.tx.htlcs().len());
8771-
for (ref htlc_sig, ref htlc) in htlc_signatures.iter().zip(commitment_stats.tx.htlcs()) {
8798+
let counterparty_keys = trusted_tx.keys();
8799+
debug_assert_eq!(htlc_signatures.len(), trusted_tx.htlcs().len());
8800+
for (ref htlc_sig, ref htlc) in htlc_signatures.iter().zip(trusted_tx.htlcs()) {
87728801
log_trace!(logger, "Signed remote HTLC tx {} with redeemscript {} with pubkey {} -> {} in channel {}",
8773-
encode::serialize_hex(&chan_utils::build_htlc_transaction(&counterparty_commitment_txid, commitment_stats.tx.feerate_per_kw(), self.funding.get_holder_selected_contest_delay(), htlc, &self.context.channel_type, &counterparty_keys.broadcaster_delayed_payment_key, &counterparty_keys.revocation_key)),
8802+
encode::serialize_hex(&chan_utils::build_htlc_transaction(&trusted_tx.txid(), trusted_tx.feerate_per_kw(), self.funding.get_holder_selected_contest_delay(), htlc, &self.context.channel_type, &counterparty_keys.broadcaster_delayed_payment_key, &counterparty_keys.revocation_key)),
87748803
encode::serialize_hex(&chan_utils::get_htlc_redeemscript(&htlc, &self.context.channel_type, &counterparty_keys)),
87758804
log_bytes!(counterparty_keys.broadcaster_htlc_key.to_public_key().serialize()),
87768805
log_bytes!(htlc_sig.serialize_compact()[..]), &self.context.channel_id());
@@ -9224,7 +9253,10 @@ impl<SP: Deref> OutboundV1Channel<SP> where SP::Target: SignerProvider {
92249253

92259254
/// Only allowed after [`FundingScope::channel_transaction_parameters`] is set.
92269255
fn get_funding_created_msg<L: Deref>(&mut self, logger: &L) -> Option<msgs::FundingCreated> where L::Target: Logger {
9227-
let counterparty_initial_commitment_tx = self.context.build_commitment_transaction(&self.funding, self.context.cur_counterparty_commitment_transaction_number, &self.context.counterparty_cur_commitment_point.unwrap(), false, false, logger).tx;
9256+
let commitment_data = self.context.build_commitment_transaction(&self.funding,
9257+
self.context.cur_counterparty_commitment_transaction_number,
9258+
&self.context.counterparty_cur_commitment_point.unwrap(), false, false, logger);
9259+
let counterparty_initial_commitment_tx = commitment_data.stats.tx;
92289260
let signature = match &self.context.holder_signer {
92299261
// TODO (taproot|arik): move match into calling method for Taproot
92309262
ChannelSignerType::Ecdsa(ecdsa) => {
@@ -11857,8 +11889,9 @@ mod tests {
1185711889
( $counterparty_sig_hex: expr, $sig_hex: expr, $tx_hex: expr, $opt_anchors: expr, {
1185811890
$( { $htlc_idx: expr, $counterparty_htlc_sig_hex: expr, $htlc_sig_hex: expr, $htlc_tx_hex: expr } ), *
1185911891
} ) => { {
11860-
let commitment_stats = chan.context.build_commitment_transaction(&chan.funding, 0xffffffffffff - 42, &per_commitment_point, true, false, &logger);
11861-
let commitment_tx = commitment_stats.tx;
11892+
let commitment_data = chan.context.build_commitment_transaction(&chan.funding,
11893+
0xffffffffffff - 42, &per_commitment_point, true, false, &logger);
11894+
let commitment_tx = commitment_data.stats.tx;
1186211895
let trusted_tx = commitment_tx.trust();
1186311896
let unsigned_tx = trusted_tx.built_transaction();
1186411897
let redeemscript = chan.funding.get_funding_redeemscript();

0 commit comments

Comments
 (0)