Skip to content

Commit cae07b8

Browse files
committed
Add begin_interactive_funding_tx_construction()
This method is needed by both V2 channel open and splicing. Auxiliary changes: - New method `calculate_change_output_value()` for determining if a change output is needed, and with what value. - In `interactivetxs.rs` adjust the visibility of `SharedOwnedOutput` and `OutputOwned` structs (were not used before). - In `DualFundingChannelContext` add a new field for the counterparty contribution, `their_funding_satoshis`.
1 parent 830ffa0 commit cae07b8

File tree

2 files changed

+296
-18
lines changed

2 files changed

+296
-18
lines changed

lightning/src/ln/channel.rs

+112-10
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
use bitcoin::amount::Amount;
1111
use bitcoin::constants::ChainHash;
1212
use bitcoin::script::{Script, ScriptBuf, Builder, WScriptHash};
13-
use bitcoin::transaction::{Transaction, TxIn};
13+
use bitcoin::transaction::{Transaction, TxIn, TxOut};
1414
use bitcoin::sighash::EcdsaSighashType;
1515
use bitcoin::consensus::encode;
1616
use bitcoin::absolute::LockTime;
@@ -30,9 +30,9 @@ use crate::ln::types::ChannelId;
3030
use crate::types::payment::{PaymentPreimage, PaymentHash};
3131
use crate::types::features::{ChannelTypeFeatures, InitFeatures};
3232
use crate::ln::interactivetxs::{
33-
get_output_weight, HandleTxCompleteValue, HandleTxCompleteResult, InteractiveTxConstructor,
34-
InteractiveTxConstructorArgs, InteractiveTxSigningSession, InteractiveTxMessageSendResult,
35-
TX_COMMON_FIELDS_WEIGHT,
33+
calculate_change_output_value, get_output_weight, AbortReason, HandleTxCompleteValue, HandleTxCompleteResult, InteractiveTxConstructor,
34+
InteractiveTxConstructorArgs, InteractiveTxMessageSend, InteractiveTxSigningSession, InteractiveTxMessageSendResult,
35+
OutputOwned, SharedOwnedOutput, TX_COMMON_FIELDS_WEIGHT,
3636
};
3737
use crate::ln::msgs;
3838
use crate::ln::msgs::{ClosingSigned, ClosingSignedFeeRange, DecodeError, OnionErrorPacket};
@@ -2220,6 +2220,99 @@ impl<SP: Deref> InitialRemoteCommitmentReceiver<SP> for FundedChannel<SP> where
22202220
}
22212221

22222222
impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
2223+
/// Prepare and start interactive transaction negotiation.
2224+
/// `change_destination_opt` - Optional destination for optional change; if None,
2225+
/// default destination address is used.
2226+
/// If error occurs, it is caused by our side, not the counterparty.
2227+
#[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled
2228+
fn begin_interactive_funding_tx_construction<ES: Deref>(
2229+
&mut self, signer_provider: &SP, entropy_source: &ES, holder_node_id: PublicKey,
2230+
change_destination_opt: Option<ScriptBuf>,
2231+
) -> Result<Option<InteractiveTxMessageSend>, AbortReason>
2232+
where ES::Target: EntropySource
2233+
{
2234+
debug_assert!(!matches!(self.context.channel_state, ChannelState::NegotiatingFunding(_)));
2235+
debug_assert!(self.interactive_tx_constructor.is_none());
2236+
2237+
let mut funding_inputs = Vec::new();
2238+
mem::swap(&mut self.dual_funding_context.our_funding_inputs, &mut funding_inputs);
2239+
2240+
// TODO(splicing): Add prev funding tx as input, must be provided as a parameter
2241+
2242+
// Add output for funding tx
2243+
// Note: For the error case when the inputs are insufficient, it will be handled after
2244+
// the `calculate_change_output_value` call below
2245+
let mut funding_outputs = Vec::new();
2246+
let mut expected_remote_shared_funding_output = None;
2247+
2248+
let shared_funding_output = TxOut {
2249+
value: Amount::from_sat(self.funding.get_value_satoshis()),
2250+
script_pubkey: self.funding.get_funding_redeemscript().to_p2wsh(),
2251+
};
2252+
2253+
if self.funding.is_outbound() {
2254+
if self.dual_funding_context.their_funding_satoshis.unwrap_or(0) == 0 {
2255+
funding_outputs.push(OutputOwned::SharedControlFullyOwned(shared_funding_output));
2256+
} else {
2257+
funding_outputs.push(
2258+
OutputOwned::Shared(SharedOwnedOutput::new(
2259+
shared_funding_output, self.dual_funding_context.our_funding_satoshis,
2260+
))
2261+
);
2262+
}
2263+
} else {
2264+
let TxOut { value, script_pubkey } = shared_funding_output;
2265+
expected_remote_shared_funding_output = Some((script_pubkey, value.to_sat()));
2266+
}
2267+
2268+
// Optionally add change output
2269+
let change_script = if let Some(script) = change_destination_opt {
2270+
script
2271+
} else {
2272+
signer_provider.get_destination_script(self.context.channel_keys_id)
2273+
.map_err(|_err| AbortReason::InternalErrorGettingDestinationScript)?
2274+
};
2275+
let change_value_opt = calculate_change_output_value(
2276+
self.funding.is_outbound(), self.dual_funding_context.our_funding_satoshis,
2277+
&funding_inputs, &funding_outputs,
2278+
self.dual_funding_context.funding_feerate_sat_per_1000_weight,
2279+
change_script.minimal_non_dust().to_sat(),
2280+
)?;
2281+
if let Some(change_value) = change_value_opt {
2282+
let mut change_output = TxOut {
2283+
value: Amount::from_sat(change_value),
2284+
script_pubkey: change_script,
2285+
};
2286+
let change_output_weight = get_output_weight(&change_output.script_pubkey).to_wu();
2287+
let change_output_fee = fee_for_weight(self.dual_funding_context.funding_feerate_sat_per_1000_weight, change_output_weight);
2288+
let change_value_decreased_with_fee = change_value.saturating_sub(change_output_fee);
2289+
// Check dust limit again
2290+
if change_value_decreased_with_fee > self.context.holder_dust_limit_satoshis {
2291+
change_output.value = Amount::from_sat(change_value_decreased_with_fee);
2292+
funding_outputs.push(OutputOwned::Single(change_output));
2293+
}
2294+
}
2295+
2296+
let constructor_args = InteractiveTxConstructorArgs {
2297+
entropy_source,
2298+
holder_node_id,
2299+
counterparty_node_id: self.context.counterparty_node_id,
2300+
channel_id: self.context.channel_id(),
2301+
feerate_sat_per_kw: self.dual_funding_context.funding_feerate_sat_per_1000_weight,
2302+
is_initiator: self.funding.is_outbound(),
2303+
funding_tx_locktime: self.dual_funding_context.funding_tx_locktime,
2304+
inputs_to_contribute: funding_inputs,
2305+
outputs_to_contribute: funding_outputs,
2306+
expected_remote_shared_funding_output,
2307+
};
2308+
let mut tx_constructor = InteractiveTxConstructor::new(constructor_args)?;
2309+
let msg = tx_constructor.take_initiator_first_message();
2310+
2311+
self.interactive_tx_constructor = Some(tx_constructor);
2312+
2313+
Ok(msg)
2314+
}
2315+
22232316
pub fn tx_add_input(&mut self, msg: &msgs::TxAddInput) -> InteractiveTxMessageSendResult {
22242317
InteractiveTxMessageSendResult(match &mut self.interactive_tx_constructor {
22252318
Some(ref mut tx_constructor) => tx_constructor.handle_tx_add_input(msg).map_err(
@@ -4849,6 +4942,9 @@ fn check_v2_funding_inputs_sufficient(
48494942
pub(super) struct DualFundingChannelContext {
48504943
/// The amount in satoshis we will be contributing to the channel.
48514944
pub our_funding_satoshis: u64,
4945+
/// The amount in satoshis our counterparty will be contributing to the channel.
4946+
#[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
4947+
pub their_funding_satoshis: Option<u64>,
48524948
/// The funding transaction locktime suggested by the initiator. If set by us, it is always set
48534949
/// to the current block height to align incentives against fee-sniping.
48544950
pub funding_tx_locktime: LockTime,
@@ -4860,6 +4956,8 @@ pub(super) struct DualFundingChannelContext {
48604956
/// Note that the `our_funding_satoshis` field is equal to the total value of `our_funding_inputs`
48614957
/// minus any fees paid for our contributed weight. This means that change will never be generated
48624958
/// and the maximum value possible will go towards funding the channel.
4959+
///
4960+
/// Note that this field may be emptied once the interactive negotiation has been started.
48634961
#[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
48644962
pub our_funding_inputs: Vec<(TxIn, TransactionU16LenLimited)>,
48654963
}
@@ -9829,16 +9927,19 @@ impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
98299927
unfunded_channel_age_ticks: 0,
98309928
holder_commitment_point: HolderCommitmentPoint::new(&context.holder_signer, &context.secp_ctx),
98319929
};
9930+
let dual_funding_context = DualFundingChannelContext {
9931+
our_funding_satoshis: funding_satoshis,
9932+
// TODO(dual_funding) TODO(splicing) Include counterparty contribution, once that's enabled
9933+
their_funding_satoshis: None,
9934+
funding_tx_locktime,
9935+
funding_feerate_sat_per_1000_weight,
9936+
our_funding_inputs: funding_inputs,
9937+
};
98329938
let chan = Self {
98339939
funding,
98349940
context,
98359941
unfunded_context,
9836-
dual_funding_context: DualFundingChannelContext {
9837-
our_funding_satoshis: funding_satoshis,
9838-
funding_tx_locktime,
9839-
funding_feerate_sat_per_1000_weight,
9840-
our_funding_inputs: funding_inputs,
9841-
},
9942+
dual_funding_context,
98429943
interactive_tx_constructor: None,
98439944
interactive_tx_signing_session: None,
98449945
};
@@ -9980,6 +10081,7 @@ impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
998010081

998110082
let dual_funding_context = DualFundingChannelContext {
998210083
our_funding_satoshis: our_funding_satoshis,
10084+
their_funding_satoshis: Some(msg.common_fields.funding_satoshis),
998310085
funding_tx_locktime: LockTime::from_consensus(msg.locktime),
998410086
funding_feerate_sat_per_1000_weight: msg.funding_feerate_sat_per_1000_weight,
998510087
our_funding_inputs: our_funding_inputs.clone(),

0 commit comments

Comments
 (0)