Skip to content

Commit d203d91

Browse files
wpaulinojkczyz
andcommitted
Refactor FundingNegotiationContext and PendingSplice
FundingNegotiationContext and PendingSplice both hold the user's contribution to a splice, which doesn't need to be duplicated. Instead, only store this in FundingNegotiationContext, which then can be used to create an InteractiveTxConstructor when transitioning to FundingNegotiation::Pending. This commit updates that code to properly compute change outputs using the FundingNegotiationContext by not considering the shared input since it is accounted for in the shared output. Co-authored-by: Wilmer Paulino <[email protected]> Co-authored-by: Jeffrey Czyz <[email protected]>
1 parent 03aaec8 commit d203d91

File tree

3 files changed

+191
-218
lines changed

3 files changed

+191
-218
lines changed

lightning/src/ln/channel.rs

Lines changed: 108 additions & 106 deletions
Original file line numberDiff line numberDiff line change
@@ -57,9 +57,8 @@ use crate::ln::channelmanager::{
5757
};
5858
use crate::ln::interactivetxs::{
5959
calculate_change_output_value, get_output_weight, AbortReason, HandleTxCompleteResult,
60-
InteractiveTxConstructor, InteractiveTxConstructorArgs, InteractiveTxMessageSend,
61-
InteractiveTxMessageSendResult, InteractiveTxSigningSession, SharedOwnedOutput,
62-
TX_COMMON_FIELDS_WEIGHT,
60+
InteractiveTxConstructor, InteractiveTxConstructorArgs, InteractiveTxMessageSendResult,
61+
InteractiveTxSigningSession, SharedOwnedInput, SharedOwnedOutput, TX_COMMON_FIELDS_WEIGHT,
6362
};
6463
use crate::ln::msgs;
6564
use crate::ln::msgs::{ClosingSigned, ClosingSignedFeeRange, DecodeError, OnionErrorPacket};
@@ -2171,7 +2170,6 @@ impl FundingScope {
21712170
/// Info about a pending splice, used in the pre-splice channel
21722171
#[cfg(splicing)]
21732172
struct PendingSplice {
2174-
pub our_funding_contribution: i64,
21752173
funding_negotiation: Option<FundingNegotiation>,
21762174

21772175
/// The funding txid used in the `splice_locked` sent to the counterparty.
@@ -2775,86 +2773,6 @@ impl<SP: Deref> PendingV2Channel<SP>
27752773
where
27762774
SP::Target: SignerProvider,
27772775
{
2778-
/// Prepare and start interactive transaction negotiation.
2779-
/// `change_destination_opt` - Optional destination for optional change; if None,
2780-
/// default destination address is used.
2781-
/// If error occurs, it is caused by our side, not the counterparty.
2782-
#[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled
2783-
#[rustfmt::skip]
2784-
fn begin_interactive_funding_tx_construction<ES: Deref>(
2785-
&mut self, signer_provider: &SP, entropy_source: &ES, holder_node_id: PublicKey,
2786-
change_destination_opt: Option<ScriptBuf>,
2787-
) -> Result<Option<InteractiveTxMessageSend>, AbortReason>
2788-
where ES::Target: EntropySource
2789-
{
2790-
debug_assert!(matches!(self.context.channel_state, ChannelState::NegotiatingFunding(_)));
2791-
debug_assert!(self.interactive_tx_constructor.is_none());
2792-
2793-
let mut funding_inputs = Vec::new();
2794-
mem::swap(&mut self.funding_negotiation_context.our_funding_inputs, &mut funding_inputs);
2795-
2796-
// TODO(splicing): Add prev funding tx as input, must be provided as a parameter
2797-
2798-
// Add output for funding tx
2799-
// Note: For the error case when the inputs are insufficient, it will be handled after
2800-
// the `calculate_change_output_value` call below
2801-
let mut funding_outputs = Vec::new();
2802-
2803-
let shared_funding_output = TxOut {
2804-
value: Amount::from_sat(self.funding.get_value_satoshis()),
2805-
script_pubkey: self.funding.get_funding_redeemscript().to_p2wsh(),
2806-
};
2807-
2808-
// Optionally add change output
2809-
let change_script = if let Some(script) = change_destination_opt {
2810-
script
2811-
} else {
2812-
signer_provider.get_destination_script(self.context.channel_keys_id)
2813-
.map_err(|_err| AbortReason::InternalError("Error getting destination script"))?
2814-
};
2815-
let change_value_opt = calculate_change_output_value(
2816-
self.funding.is_outbound(), self.funding_negotiation_context.our_funding_satoshis,
2817-
&funding_inputs, None,
2818-
&shared_funding_output.script_pubkey, &funding_outputs,
2819-
self.funding_negotiation_context.funding_feerate_sat_per_1000_weight,
2820-
change_script.minimal_non_dust().to_sat(),
2821-
)?;
2822-
if let Some(change_value) = change_value_opt {
2823-
let mut change_output = TxOut {
2824-
value: Amount::from_sat(change_value),
2825-
script_pubkey: change_script,
2826-
};
2827-
let change_output_weight = get_output_weight(&change_output.script_pubkey).to_wu();
2828-
let change_output_fee = fee_for_weight(self.funding_negotiation_context.funding_feerate_sat_per_1000_weight, change_output_weight);
2829-
let change_value_decreased_with_fee = change_value.saturating_sub(change_output_fee);
2830-
// Check dust limit again
2831-
if change_value_decreased_with_fee > self.context.holder_dust_limit_satoshis {
2832-
change_output.value = Amount::from_sat(change_value_decreased_with_fee);
2833-
funding_outputs.push(change_output);
2834-
}
2835-
}
2836-
2837-
let constructor_args = InteractiveTxConstructorArgs {
2838-
entropy_source,
2839-
holder_node_id,
2840-
counterparty_node_id: self.context.counterparty_node_id,
2841-
channel_id: self.context.channel_id(),
2842-
feerate_sat_per_kw: self.funding_negotiation_context.funding_feerate_sat_per_1000_weight,
2843-
is_initiator: self.funding.is_outbound(),
2844-
funding_tx_locktime: self.funding_negotiation_context.funding_tx_locktime,
2845-
inputs_to_contribute: funding_inputs,
2846-
shared_funding_input: None,
2847-
shared_funding_output: SharedOwnedOutput::new(shared_funding_output, self.funding_negotiation_context.our_funding_satoshis),
2848-
outputs_to_contribute: funding_outputs,
2849-
};
2850-
let mut tx_constructor = InteractiveTxConstructor::new(constructor_args)?;
2851-
let msg = tx_constructor.take_initiator_first_message();
2852-
2853-
self.interactive_tx_constructor = Some(tx_constructor);
2854-
2855-
Ok(msg)
2856-
}
2857-
28582776
pub fn tx_add_input(&mut self, msg: &msgs::TxAddInput) -> InteractiveTxMessageSendResult {
28592777
InteractiveTxMessageSendResult(match &mut self.interactive_tx_constructor {
28602778
Some(ref mut tx_constructor) => tx_constructor
@@ -2934,7 +2852,7 @@ where
29342852
where
29352853
L::Target: Logger
29362854
{
2937-
let our_funding_satoshis = self.funding_negotiation_context.our_funding_satoshis;
2855+
let our_funding_satoshis = self.funding_negotiation_context.our_funding_contribution_satoshis;
29382856
let transaction_number = self.unfunded_context.transaction_number();
29392857

29402858
let mut output_index = None;
@@ -5874,28 +5792,107 @@ fn check_v2_funding_inputs_sufficient(
58745792

58755793
/// Context for negotiating channels (dual-funded V2 open, splicing)
58765794
pub(super) struct FundingNegotiationContext {
5795+
/// Whether we initiated the funding negotiation.
5796+
pub is_initiator: bool,
58775797
/// The amount in satoshis we will be contributing to the channel.
5878-
pub our_funding_satoshis: u64,
5798+
pub our_funding_contribution_satoshis: i64,
58795799
/// The amount in satoshis our counterparty will be contributing to the channel.
58805800
#[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
5881-
pub their_funding_satoshis: Option<u64>,
5801+
pub their_funding_contribution_satoshis: Option<i64>,
58825802
/// The funding transaction locktime suggested by the initiator. If set by us, it is always set
58835803
/// to the current block height to align incentives against fee-sniping.
58845804
pub funding_tx_locktime: LockTime,
58855805
/// The feerate set by the initiator to be used for the funding transaction.
58865806
#[allow(dead_code)] // TODO(dual_funding): Remove once V2 channels is enabled.
58875807
pub funding_feerate_sat_per_1000_weight: u32,
58885808
/// The funding inputs we will be contributing to the channel.
5889-
///
5890-
/// Note that the `our_funding_satoshis` field is equal to the total value of `our_funding_inputs`
5891-
/// minus any fees paid for our contributed weight. This means that change will never be generated
5892-
/// and the maximum value possible will go towards funding the channel.
5893-
///
5894-
/// Note that this field may be emptied once the interactive negotiation has been started.
58955809
#[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
58965810
pub our_funding_inputs: Vec<(TxIn, TransactionU16LenLimited)>,
58975811
}
58985812

5813+
impl FundingNegotiationContext {
5814+
/// Prepare and start interactive transaction negotiation.
5815+
/// `change_destination_opt` - Optional destination for optional change; if None,
5816+
/// default destination address is used.
5817+
/// If error occurs, it is caused by our side, not the counterparty.
5818+
#[cfg(splicing)]
5819+
fn into_interactive_tx_constructor<SP: Deref, ES: Deref>(
5820+
self, context: &ChannelContext<SP>, funding: &FundingScope, signer_provider: &SP,
5821+
entropy_source: &ES, holder_node_id: PublicKey, change_destination_opt: Option<ScriptBuf>,
5822+
shared_funding_input: Option<SharedOwnedInput>,
5823+
) -> Result<InteractiveTxConstructor, AbortReason>
5824+
where
5825+
SP::Target: SignerProvider,
5826+
ES::Target: EntropySource,
5827+
{
5828+
if shared_funding_input.is_some() {
5829+
debug_assert!(matches!(context.channel_state, ChannelState::ChannelReady(_)));
5830+
} else {
5831+
debug_assert!(matches!(context.channel_state, ChannelState::NegotiatingFunding(_)));
5832+
}
5833+
5834+
// Add output for funding tx
5835+
// Note: For the error case when the inputs are insufficient, it will be handled after
5836+
// the `calculate_change_output_value` call below
5837+
let mut funding_outputs = Vec::new();
5838+
5839+
let shared_funding_output = TxOut {
5840+
value: Amount::from_sat(funding.get_value_satoshis()),
5841+
script_pubkey: funding.get_funding_redeemscript().to_p2wsh(),
5842+
};
5843+
5844+
// Optionally add change output
5845+
if self.our_funding_contribution_satoshis > 0 {
5846+
let change_value_opt = calculate_change_output_value(
5847+
&self,
5848+
funding.channel_transaction_parameters.splice_parent_funding_txid.is_some(),
5849+
&shared_funding_output.script_pubkey,
5850+
&funding_outputs,
5851+
context.holder_dust_limit_satoshis,
5852+
)?;
5853+
if let Some(change_value) = change_value_opt {
5854+
let change_script = if let Some(script) = change_destination_opt {
5855+
script
5856+
} else {
5857+
signer_provider.get_destination_script(context.channel_keys_id).map_err(
5858+
|_err| AbortReason::InternalError("Error getting destination script"),
5859+
)?
5860+
};
5861+
let mut change_output =
5862+
TxOut { value: Amount::from_sat(change_value), script_pubkey: change_script };
5863+
let change_output_weight = get_output_weight(&change_output.script_pubkey).to_wu();
5864+
let change_output_fee =
5865+
fee_for_weight(self.funding_feerate_sat_per_1000_weight, change_output_weight);
5866+
let change_value_decreased_with_fee =
5867+
change_value.saturating_sub(change_output_fee);
5868+
// Check dust limit again
5869+
if change_value_decreased_with_fee > context.holder_dust_limit_satoshis {
5870+
change_output.value = Amount::from_sat(change_value_decreased_with_fee);
5871+
funding_outputs.push(change_output);
5872+
}
5873+
}
5874+
}
5875+
5876+
let constructor_args = InteractiveTxConstructorArgs {
5877+
entropy_source,
5878+
holder_node_id,
5879+
counterparty_node_id: context.counterparty_node_id,
5880+
channel_id: context.channel_id(),
5881+
feerate_sat_per_kw: self.funding_feerate_sat_per_1000_weight,
5882+
is_initiator: self.is_initiator,
5883+
funding_tx_locktime: self.funding_tx_locktime,
5884+
inputs_to_contribute: self.our_funding_inputs,
5885+
shared_funding_input,
5886+
shared_funding_output: SharedOwnedOutput::new(
5887+
shared_funding_output,
5888+
funding.value_to_self_msat / 1000,
5889+
),
5890+
outputs_to_contribute: funding_outputs,
5891+
};
5892+
InteractiveTxConstructor::new(constructor_args)
5893+
}
5894+
}
5895+
58995896
// Holder designates channel data owned for the benefit of the user client.
59005897
// Counterparty designates channel data owned by the another channel participant entity.
59015898
pub(super) struct FundedChannel<SP: Deref>
@@ -10418,11 +10415,13 @@ where
1041810415
) -> Result<msgs::SpliceInit, APIError> {
1041910416
// Check if a splice has been initiated already.
1042010417
// Note: only a single outstanding splice is supported (per spec)
10421-
if let Some(splice_info) = &self.pending_splice {
10422-
return Err(APIError::APIMisuseError { err: format!(
10423-
"Channel {} cannot be spliced, as it has already a splice pending (contribution {})",
10424-
self.context.channel_id(), splice_info.our_funding_contribution
10425-
)});
10418+
if self.pending_splice.is_some() {
10419+
return Err(APIError::APIMisuseError {
10420+
err: format!(
10421+
"Channel {} cannot be spliced, as it has already a splice pending",
10422+
self.context.channel_id(),
10423+
),
10424+
});
1042610425
}
1042710426

1042810427
if !self.context.is_live() {
@@ -10455,7 +10454,6 @@ where
1045510454
)})?;
1045610455

1045710456
self.pending_splice = Some(PendingSplice {
10458-
our_funding_contribution: our_funding_contribution_satoshis,
1045910457
funding_negotiation: None,
1046010458
sent_funding_txid: None,
1046110459
received_funding_txid: None,
@@ -10492,9 +10490,10 @@ where
1049210490
let our_funding_contribution_satoshis = 0i64;
1049310491

1049410492
// Check if a splice has been initiated already.
10495-
if let Some(splice_info) = &self.pending_splice {
10493+
if self.pending_splice.is_some() {
1049610494
return Err(ChannelError::Warn(format!(
10497-
"Channel has already a splice pending, contribution {}", splice_info.our_funding_contribution,
10495+
"Channel {} already has a splice pending",
10496+
self.context.channel_id(),
1049810497
)));
1049910498
}
1050010499

@@ -12105,9 +12104,10 @@ where
1210512104
holder_commitment_point: HolderCommitmentPoint::new(&context.holder_signer, &context.secp_ctx),
1210612105
};
1210712106
let funding_negotiation_context = FundingNegotiationContext {
12108-
our_funding_satoshis: funding_satoshis,
12107+
is_initiator: true,
12108+
our_funding_contribution_satoshis: funding_satoshis as i64,
1210912109
// TODO(dual_funding) TODO(splicing) Include counterparty contribution, once that's enabled
12110-
their_funding_satoshis: None,
12110+
their_funding_contribution_satoshis: None,
1211112111
funding_tx_locktime,
1211212112
funding_feerate_sat_per_1000_weight,
1211312113
our_funding_inputs: funding_inputs,
@@ -12259,8 +12259,9 @@ where
1225912259
context.channel_id = channel_id;
1226012260

1226112261
let funding_negotiation_context = FundingNegotiationContext {
12262-
our_funding_satoshis: our_funding_satoshis,
12263-
their_funding_satoshis: Some(msg.common_fields.funding_satoshis),
12262+
is_initiator: false,
12263+
our_funding_contribution_satoshis: our_funding_satoshis as i64,
12264+
their_funding_contribution_satoshis: Some(msg.common_fields.funding_satoshis as i64),
1226412265
funding_tx_locktime: LockTime::from_consensus(msg.locktime),
1226512266
funding_feerate_sat_per_1000_weight: msg.funding_feerate_sat_per_1000_weight,
1226612267
our_funding_inputs: our_funding_inputs.clone(),
@@ -12362,7 +12363,8 @@ where
1236212363
}),
1236312364
channel_type: Some(self.funding.get_channel_type().clone()),
1236412365
},
12365-
funding_satoshis: self.funding_negotiation_context.our_funding_satoshis,
12366+
funding_satoshis: self.funding_negotiation_context.our_funding_contribution_satoshis
12367+
as u64,
1236612368
second_per_commitment_point,
1236712369
require_confirmed_inputs: None,
1236812370
}

lightning/src/ln/channelmanager.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9190,7 +9190,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/
91909190

91919191
// Inbound V2 channels with contributed inputs are not considered unfunded.
91929192
if let Some(unfunded_chan) = chan.as_unfunded_v2() {
9193-
if unfunded_chan.funding_negotiation_context.our_funding_satoshis != 0 {
9193+
if unfunded_chan.funding_negotiation_context.our_funding_contribution_satoshis > 0 {
91949194
continue;
91959195
}
91969196
}

0 commit comments

Comments
 (0)