Skip to content

Commit 09e7ca8

Browse files
author
Antoine Riard
committed
Merge build_commitment_transaction local/generated_by_local
We observe the only case where these parameters use to diverge was at funding signature, at which point we shouldn't have any pending HTLCs. We can merge them as a `local` commitment transaction is always generated at the request of your counterparty and vice-versa.
1 parent 012eb8f commit 09e7ca8

File tree

1 file changed

+33
-33
lines changed

1 file changed

+33
-33
lines changed

lightning/src/ln/channel.rs

Lines changed: 33 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -833,7 +833,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
833833
/// Note that below-dust HTLCs are included in the third return value, but not the second, and
834834
/// sources are provided only for outbound HTLCs in the third return value.
835835
#[inline]
836-
fn build_commitment_transaction<L: Deref>(&self, commitment_number: u64, keys: &TxCreationKeys, local: bool, generated_by_local: bool, feerate_per_kw: u32, logger: &L) -> (Transaction, usize, Vec<(HTLCOutputInCommitment, Option<&HTLCSource>)>) where L::Target: Logger {
836+
fn build_commitment_transaction<L: Deref>(&self, commitment_number: u64, keys: &TxCreationKeys, building_for_counterparty: bool, feerate_per_kw: u32, logger: &L) -> (Transaction, usize, Vec<(HTLCOutputInCommitment, Option<&HTLCSource>)>) where L::Target: Logger {
837837
let obscured_commitment_transaction_number = self.get_commitment_transaction_number_obscure_factor() ^ (INITIAL_COMMITMENT_NUMBER - commitment_number);
838838

839839
let txins = {
@@ -850,12 +850,12 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
850850
let mut txouts: Vec<(TxOut, Option<(HTLCOutputInCommitment, Option<&HTLCSource>)>)> = Vec::with_capacity(self.pending_inbound_htlcs.len() + self.pending_outbound_htlcs.len() + 2);
851851
let mut included_dust_htlcs: Vec<(HTLCOutputInCommitment, Option<&HTLCSource>)> = Vec::new();
852852

853-
let broadcaster_dust_limit_satoshis = if local { self.holder_dust_limit_satoshis } else { self.counterparty_dust_limit_satoshis };
853+
let broadcaster_dust_limit_satoshis = if !building_for_counterparty { self.holder_dust_limit_satoshis } else { self.counterparty_dust_limit_satoshis };
854854
let mut counterparty_htlc_total_msat = 0;
855855
let mut holder_htlc_total_msat = 0;
856856
let mut holder_value_msat_offset = 0;
857857

858-
log_trace!(logger, "Building commitment transaction number {} (really {} xor {}) for {}, generated by {} with fee {}...", commitment_number, (INITIAL_COMMITMENT_NUMBER - commitment_number), self.get_commitment_transaction_number_obscure_factor(), if local { "us" } else { "remote" }, if generated_by_local { "us" } else { "remote" }, feerate_per_kw);
858+
log_trace!(logger, "Building commitment transaction number {} (really {} xor {}) for {}, generated by {} with fee {}...", commitment_number, (INITIAL_COMMITMENT_NUMBER - commitment_number), self.get_commitment_transaction_number_obscure_factor(), if !building_for_counterparty { "us" } else { "remote" }, if !building_for_counterparty { "us" } else { "remote" }, feerate_per_kw);
859859

860860
macro_rules! get_htlc_in_commitment {
861861
($htlc: expr, $offered: expr) => {
@@ -871,7 +871,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
871871

872872
macro_rules! add_htlc_output {
873873
($htlc: expr, $outbound: expr, $source: expr, $state_name: expr) => {
874-
if $outbound == local { // "offered HTLC output"
874+
if $outbound == !building_for_counterparty { // "offered HTLC output"
875875
let htlc_in_tx = get_htlc_in_commitment!($htlc, true);
876876
if $htlc.amount_msat / 1000 >= broadcaster_dust_limit_satoshis + (feerate_per_kw as u64 * HTLC_TIMEOUT_TX_WEIGHT / 1000) {
877877
log_trace!(logger, " ...including {} {} HTLC {} (hash {}) with value {}", if $outbound { "outbound" } else { "inbound" }, $state_name, $htlc.htlc_id, log_bytes!($htlc.payment_hash.0), $htlc.amount_msat);
@@ -899,13 +899,15 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
899899
}
900900
}
901901

902+
// If we initiate the commitment update, inbound HTLC flowing from our counterparty
903+
// to us
902904
for ref htlc in self.pending_inbound_htlcs.iter() {
903905
let (include, state_name) = match htlc.state {
904-
InboundHTLCState::RemoteAnnounced(_) => (!generated_by_local, "RemoteAnnounced"),
905-
InboundHTLCState::AwaitingRemoteRevokeToAnnounce(_) => (!generated_by_local, "AwaitingRemoteRevokeToAnnounce"),
906+
InboundHTLCState::RemoteAnnounced(_) => (!building_for_counterparty, "RemoteAnnounced"),
907+
InboundHTLCState::AwaitingRemoteRevokeToAnnounce(_) => (!building_for_counterparty, "AwaitingRemoteRevokeToAnnounce"),
906908
InboundHTLCState::AwaitingAnnouncedRemoteRevoke(_) => (true, "AwaitingAnnouncedRemoteRevoke"),
907909
InboundHTLCState::Committed => (true, "Committed"),
908-
InboundHTLCState::LocalRemoved(_) => (!generated_by_local, "LocalRemoved"),
910+
InboundHTLCState::LocalRemoved(_) => (!building_for_counterparty, "LocalRemoved"),
909911
};
910912

911913
if include {
@@ -915,7 +917,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
915917
log_trace!(logger, " ...not including inbound HTLC {} (hash {}) with value {} due to state ({})", htlc.htlc_id, log_bytes!(htlc.payment_hash.0), htlc.amount_msat, state_name);
916918
match &htlc.state {
917919
&InboundHTLCState::LocalRemoved(ref reason) => {
918-
if generated_by_local {
920+
if building_for_counterparty {
919921
if let &InboundHTLCRemovalReason::Fulfill(_) = reason {
920922
holder_value_msat_offset += htlc.amount_msat as i64;
921923
}
@@ -928,10 +930,10 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
928930

929931
for ref htlc in self.pending_outbound_htlcs.iter() {
930932
let (include, state_name) = match htlc.state {
931-
OutboundHTLCState::LocalAnnounced(_) => (generated_by_local, "LocalAnnounced"),
933+
OutboundHTLCState::LocalAnnounced(_) => (building_for_counterparty, "LocalAnnounced"),
932934
OutboundHTLCState::Committed => (true, "Committed"),
933-
OutboundHTLCState::RemoteRemoved(_) => (generated_by_local, "RemoteRemoved"),
934-
OutboundHTLCState::AwaitingRemoteRevokeToRemove(_) => (generated_by_local, "AwaitingRemoteRevokeToRemove"),
935+
OutboundHTLCState::RemoteRemoved(_) => (building_for_counterparty, "RemoteRemoved"),
936+
OutboundHTLCState::AwaitingRemoteRevokeToRemove(_) => (building_for_counterparty, "AwaitingRemoteRevokeToRemove"),
935937
OutboundHTLCState::AwaitingRemovedRemoteRevoke(_) => (false, "AwaitingRemovedRemoteRevoke"),
936938
};
937939

@@ -945,7 +947,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
945947
holder_value_msat_offset -= htlc.amount_msat as i64;
946948
},
947949
OutboundHTLCState::RemoteRemoved(None) => {
948-
if !generated_by_local {
950+
if !building_for_counterparty {
949951
holder_value_msat_offset -= htlc.amount_msat as i64;
950952
}
951953
},
@@ -967,7 +969,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
967969
{
968970
// Make sure that the to_self/to_remote is always either past the appropriate
969971
// channel_reserve *or* it is making progress towards it.
970-
let mut broadcaster_max_commitment_tx_output = if generated_by_local {
972+
let mut broadcaster_max_commitment_tx_output = if !building_for_counterparty {
971973
self.holder_max_commitment_tx_output.lock().unwrap()
972974
} else {
973975
self.counterparty_max_commitment_tx_output.lock().unwrap()
@@ -985,21 +987,21 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
985987
(holder_value_msat / 1000, counterparty_value_msat / 1000 - total_fee as i64)
986988
};
987989

988-
let (value_to_a, value_to_b) = if local { (holder_value, counterparty_value) } else { (counterparty_value, holder_value) };
990+
let (value_to_a, value_to_b) = if !building_for_counterparty { (holder_value, counterparty_value) } else { (counterparty_value, holder_value) };
989991

990992
if value_to_a >= (broadcaster_dust_limit_satoshis as i64) {
991-
log_trace!(logger, " ...including {} output with value {}", if local { "to_local" } else { "to_remote" }, value_to_a);
993+
log_trace!(logger, " ...including {} output with value {}", if !building_for_counterparty { "to_local" } else { "to_remote" }, value_to_a);
992994
txouts.push((TxOut {
993995
script_pubkey: chan_utils::get_revokeable_redeemscript(&keys.revocation_key,
994-
if local { self.counterparty_selected_contest_delay } else { self.holder_selected_contest_delay },
996+
if !building_for_counterparty { self.counterparty_selected_contest_delay } else { self.holder_selected_contest_delay },
995997
&keys.broadcaster_delayed_payment_key).to_v0_p2wsh(),
996998
value: value_to_a as u64
997999
}, None));
9981000
}
9991001

10001002
if value_to_b >= (broadcaster_dust_limit_satoshis as i64) {
1001-
log_trace!(logger, " ...including {} output with value {}", if local { "to_remote" } else { "to_local" }, value_to_b);
1002-
let static_payment_pk = if local {
1003+
log_trace!(logger, " ...including {} output with value {}", if !building_for_counterparty { "to_remote" } else { "to_local" }, value_to_b);
1004+
let static_payment_pk = if !building_for_counterparty {
10031005
self.counterparty_pubkeys.as_ref().unwrap().payment_point
10041006
} else {
10051007
self.holder_keys.pubkeys().payment_point
@@ -1477,7 +1479,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
14771479
let funding_script = self.get_funding_redeemscript();
14781480

14791481
let keys = self.build_holder_transaction_keys(self.cur_holder_commitment_transaction_number)?;
1480-
let initial_commitment_tx = self.build_commitment_transaction(self.cur_holder_commitment_transaction_number, &keys, true, false, self.feerate_per_kw, logger).0;
1482+
let initial_commitment_tx = self.build_commitment_transaction(self.cur_holder_commitment_transaction_number, &keys, false, self.feerate_per_kw, logger).0;
14811483
let sighash = hash_to_message!(&bip143::SigHashCache::new(&initial_commitment_tx).signature_hash(0, &funding_script, self.channel_value_satoshis, SigHashType::All)[..]);
14821484

14831485
// They sign the "our" commitment transaction...
@@ -1487,9 +1489,9 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
14871489
let tx = HolderCommitmentTransaction::new_missing_holder_sig(initial_commitment_tx, sig.clone(), &self.holder_keys.pubkeys().funding_pubkey, self.counterparty_funding_pubkey(), keys, self.feerate_per_kw, Vec::new());
14881490

14891491
let counterparty_keys = self.build_remote_transaction_keys()?;
1490-
let counterparty_initial_commitment_tx = self.build_commitment_transaction(self.cur_counterparty_commitment_transaction_number, &counterparty_keys, false, false, self.feerate_per_kw, logger).0;
1491-
let pre_remote_keys = PreCalculatedTxCreationKeys::new(counterparty_keys);
1492-
let counterparty_signature = self.holder_keys.sign_counterparty_commitment(self.feerate_per_kw, &counterparty_initial_commitment_tx, &pre_remote_keys, &Vec::new(), &self.secp_ctx)
1492+
let counterparty_initial_commitment_tx = self.build_commitment_transaction(self.cur_counterparty_commitment_transaction_number, &counterparty_keys, true, self.feerate_per_kw, logger).0;
1493+
let pre_counterparty_keys = PreCalculatedTxCreationKeys::new(counterparty_keys);
1494+
let counterparty_signature = self.holder_keys.sign_counterparty_commitment(self.feerate_per_kw, &counterparty_initial_commitment_tx, &pre_counterparty_keys, &Vec::new(), &self.secp_ctx)
14931495
.map_err(|_| ChannelError::Close("Failed to get signatures for new commitment_signed".to_owned()))?.0;
14941496

14951497
// We sign "counterparty" commitment transaction, allowing them to broadcast the tx if they wish.
@@ -1578,10 +1580,10 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
15781580
let funding_script = self.get_funding_redeemscript();
15791581

15801582
let counterparty_keys = self.build_remote_transaction_keys()?;
1581-
let counterparty_initial_commitment_tx = self.build_commitment_transaction(self.cur_counterparty_commitment_transaction_number, &counterparty_keys, false, false, self.feerate_per_kw, logger).0;
1583+
let counterparty_initial_commitment_tx = self.build_commitment_transaction(self.cur_counterparty_commitment_transaction_number, &counterparty_keys, true, self.feerate_per_kw, logger).0;
15821584

15831585
let holder_keys = self.build_holder_transaction_keys(self.cur_holder_commitment_transaction_number)?;
1584-
let initial_commitment_tx = self.build_commitment_transaction(self.cur_holder_commitment_transaction_number, &holder_keys, true, false, self.feerate_per_kw, logger).0;
1586+
let initial_commitment_tx = self.build_commitment_transaction(self.cur_holder_commitment_transaction_number, &holder_keys, false, self.feerate_per_kw, logger).0;
15851587
let sighash = hash_to_message!(&bip143::SigHashCache::new(&initial_commitment_tx).signature_hash(0, &funding_script, self.channel_value_satoshis, SigHashType::All)[..]);
15861588

15871589
let counterparty_funding_pubkey = &self.counterparty_pubkeys.as_ref().unwrap().funding_pubkey;
@@ -1977,7 +1979,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
19771979
};
19781980

19791981
let mut commitment_tx = {
1980-
let mut commitment_tx = self.build_commitment_transaction(self.cur_holder_commitment_transaction_number, &keys, true, false, feerate_per_kw, logger);
1982+
let mut commitment_tx = self.build_commitment_transaction(self.cur_holder_commitment_transaction_number, &keys, false, feerate_per_kw, logger);
19811983
let htlcs_cloned: Vec<_> = commitment_tx.2.drain(..).map(|htlc| (htlc.0, htlc.1.map(|h| h.clone()))).collect();
19821984
(commitment_tx.0, commitment_tx.1, htlcs_cloned)
19831985
};
@@ -2063,9 +2065,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
20632065
}
20642066
}
20652067
for htlc in self.pending_outbound_htlcs.iter_mut() {
2066-
if let Some(fail_reason) = if let &mut OutboundHTLCState::RemoteRemoved(ref mut fail_reason) = &mut htlc.state {
2067-
Some(fail_reason.take())
2068-
} else { None } {
2068+
if let Some(fail_reason) = if let &mut OutboundHTLCState::RemoteRemoved(ref mut fail_reason) = &mut htlc.state { Some(fail_reason.take())} else { None } {
20692069
htlc.state = OutboundHTLCState::AwaitingRemoteRevokeToRemove(fail_reason);
20702070
need_commitment = true;
20712071
}
@@ -3518,9 +3518,9 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
35183518
/// If an Err is returned, it is a ChannelError::Close (for get_outbound_funding_created)
35193519
fn get_outbound_funding_created_signature<L: Deref>(&mut self, logger: &L) -> Result<Signature, ChannelError> where L::Target: Logger {
35203520
let counterparty_keys = self.build_remote_transaction_keys()?;
3521-
let counterparty_initial_commitment_tx = self.build_commitment_transaction(self.cur_counterparty_commitment_transaction_number, &counterparty_keys, false, false, self.feerate_per_kw, logger).0;
3522-
let pre_remote_keys = PreCalculatedTxCreationKeys::new(counterparty_keys);
3523-
Ok(self.holder_keys.sign_counterparty_commitment(self.feerate_per_kw, &counterparty_initial_commitment_tx, &pre_remote_keys, &Vec::new(), &self.secp_ctx)
3521+
let counterparty_initial_commitment_tx = self.build_commitment_transaction(self.cur_counterparty_commitment_transaction_number, &counterparty_keys, true, self.feerate_per_kw, logger).0;
3522+
let pre_counterparty_keys = PreCalculatedTxCreationKeys::new(counterparty_keys);
3523+
Ok(self.holder_keys.sign_counterparty_commitment(self.feerate_per_kw, &counterparty_initial_commitment_tx, &pre_counterparty_keys, &Vec::new(), &self.secp_ctx)
35243524
.map_err(|_| ChannelError::Close("Failed to get signatures for new commitment_signed".to_owned()))?.0)
35253525
}
35263526

@@ -3863,7 +3863,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
38633863
}
38643864

38653865
let counterparty_keys = self.build_remote_transaction_keys()?;
3866-
let counterparty_commitment_tx = self.build_commitment_transaction(self.cur_counterparty_commitment_transaction_number, &counterparty_keys, false, true, feerate_per_kw, logger);
3866+
let counterparty_commitment_tx = self.build_commitment_transaction(self.cur_counterparty_commitment_transaction_number, &counterparty_keys, true, feerate_per_kw, logger);
38673867
let (signature, htlc_signatures);
38683868

38693869
{
@@ -4685,7 +4685,7 @@ mod tests {
46854685
$( { $htlc_idx: expr, $counterparty_htlc_sig_hex: expr, $htlc_sig_hex: expr, $htlc_tx_hex: expr } ), *
46864686
} ) => { {
46874687
unsigned_tx = {
4688-
let mut res = chan.build_commitment_transaction(0xffffffffffff - 42, &keys, true, false, chan.feerate_per_kw, &logger);
4688+
let mut res = chan.build_commitment_transaction(0xffffffffffff - 42, &keys, false, chan.feerate_per_kw, &logger);
46894689
let htlcs = res.2.drain(..)
46904690
.filter_map(|(htlc, _)| if htlc.transaction_output_index.is_some() { Some(htlc) } else { None })
46914691
.collect();

0 commit comments

Comments
 (0)