1010use bitcoin::amount::Amount;
1111use bitcoin::constants::ChainHash;
1212use bitcoin::script::{Script, ScriptBuf, Builder, WScriptHash};
13- use bitcoin::transaction::{Transaction, TxIn};
13+ use bitcoin::transaction::{Transaction, TxIn, TxOut };
1414use bitcoin::sighash::EcdsaSighashType;
1515use bitcoin::consensus::encode;
1616use bitcoin::absolute::LockTime;
@@ -30,9 +30,9 @@ use crate::ln::types::ChannelId;
3030use crate::types::payment::{PaymentPreimage, PaymentHash};
3131use crate::types::features::{ChannelTypeFeatures, InitFeatures};
3232use 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};
3737use crate::ln::msgs;
3838use crate::ln::msgs::{ClosingSigned, ClosingSignedFeeRange, DecodeError, OnionErrorPacket};
@@ -2220,6 +2220,95 @@ impl<SP: Deref> InitialRemoteCommitmentReceiver<SP> for FundedChannel<SP> where
22202220}
22212221
22222222impl<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+ 			funding_outputs.push(
2255+ 				OutputOwned::Shared(SharedOwnedOutput::new(
2256+ 					shared_funding_output, self.dual_funding_context.our_funding_satoshis,
2257+ 				))
2258+ 			);
2259+ 		} else {
2260+ 			let TxOut { value, script_pubkey } = shared_funding_output;
2261+ 			expected_remote_shared_funding_output = Some((script_pubkey, value.to_sat()));
2262+ 		}
2263+ 
2264+ 		// Optionally add change output
2265+ 		let change_script = if let Some(script) = change_destination_opt {
2266+ 			script
2267+ 		} else {
2268+ 			signer_provider.get_destination_script(self.context.channel_keys_id)
2269+ 				.map_err(|_err| AbortReason::InternalError("Error getting destination script"))?
2270+ 		};
2271+ 		let change_value_opt = calculate_change_output_value(
2272+ 			self.funding.is_outbound(), self.dual_funding_context.our_funding_satoshis,
2273+ 			&funding_inputs, &funding_outputs,
2274+ 			self.dual_funding_context.funding_feerate_sat_per_1000_weight,
2275+ 			change_script.minimal_non_dust().to_sat(),
2276+ 		)?;
2277+ 		if let Some(change_value) = change_value_opt {
2278+ 			let mut change_output = TxOut {
2279+ 				value: Amount::from_sat(change_value),
2280+ 				script_pubkey: change_script,
2281+ 			};
2282+ 			let change_output_weight = get_output_weight(&change_output.script_pubkey).to_wu();
2283+ 			let change_output_fee = fee_for_weight(self.dual_funding_context.funding_feerate_sat_per_1000_weight, change_output_weight);
2284+ 			let change_value_decreased_with_fee = change_value.saturating_sub(change_output_fee);
2285+ 			// Check dust limit again
2286+ 			if change_value_decreased_with_fee > self.context.holder_dust_limit_satoshis {
2287+ 				change_output.value = Amount::from_sat(change_value_decreased_with_fee);
2288+ 				funding_outputs.push(OutputOwned::Single(change_output));
2289+ 			}
2290+ 		}
2291+ 
2292+ 		let constructor_args = InteractiveTxConstructorArgs {
2293+ 			entropy_source,
2294+ 			holder_node_id,
2295+ 			counterparty_node_id: self.context.counterparty_node_id,
2296+ 			channel_id: self.context.channel_id(),
2297+ 			feerate_sat_per_kw: self.dual_funding_context.funding_feerate_sat_per_1000_weight,
2298+ 			is_initiator: self.funding.is_outbound(),
2299+ 			funding_tx_locktime: self.dual_funding_context.funding_tx_locktime,
2300+ 			inputs_to_contribute: funding_inputs,
2301+ 			outputs_to_contribute: funding_outputs,
2302+ 			expected_remote_shared_funding_output,
2303+ 		};
2304+ 		let mut tx_constructor = InteractiveTxConstructor::new(constructor_args)?;
2305+ 		let msg = tx_constructor.take_initiator_first_message();
2306+ 
2307+ 		self.interactive_tx_constructor = Some(tx_constructor);
2308+ 
2309+ 		Ok(msg)
2310+ 	}
2311+ 
22232312	pub fn tx_add_input(&mut self, msg: &msgs::TxAddInput) -> InteractiveTxMessageSendResult {
22242313		InteractiveTxMessageSendResult(match &mut self.interactive_tx_constructor {
22252314			Some(ref mut tx_constructor) => tx_constructor.handle_tx_add_input(msg).map_err(
@@ -4833,6 +4922,9 @@ fn check_v2_funding_inputs_sufficient(
48334922pub(super) struct DualFundingChannelContext {
48344923	/// The amount in satoshis we will be contributing to the channel.
48354924	pub our_funding_satoshis: u64,
4925+ 	/// The amount in satoshis our counterparty will be contributing to the channel.
4926+ 	#[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
4927+ 	pub their_funding_satoshis: Option<u64>,
48364928	/// The funding transaction locktime suggested by the initiator. If set by us, it is always set
48374929	/// to the current block height to align incentives against fee-sniping.
48384930	pub funding_tx_locktime: LockTime,
@@ -4844,6 +4936,8 @@ pub(super) struct DualFundingChannelContext {
48444936	/// Note that the `our_funding_satoshis` field is equal to the total value of `our_funding_inputs`
48454937	/// minus any fees paid for our contributed weight. This means that change will never be generated
48464938	/// and the maximum value possible will go towards funding the channel.
4939+ 	///
4940+ 	/// Note that this field may be emptied once the interactive negotiation has been started.
48474941	#[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
48484942	pub our_funding_inputs: Vec<(TxIn, TransactionU16LenLimited)>,
48494943}
@@ -9813,16 +9907,19 @@ impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
98139907			unfunded_channel_age_ticks: 0,
98149908			holder_commitment_point: HolderCommitmentPoint::new(&context.holder_signer, &context.secp_ctx),
98159909		};
9910+ 		let dual_funding_context = DualFundingChannelContext {
9911+ 			our_funding_satoshis: funding_satoshis,
9912+ 			// TODO(dual_funding) TODO(splicing) Include counterparty contribution, once that's enabled
9913+ 			their_funding_satoshis: None,
9914+ 			funding_tx_locktime,
9915+ 			funding_feerate_sat_per_1000_weight,
9916+ 			our_funding_inputs: funding_inputs,
9917+ 		};
98169918		let chan = Self {
98179919			funding,
98189920			context,
98199921			unfunded_context,
9820- 			dual_funding_context: DualFundingChannelContext {
9821- 				our_funding_satoshis: funding_satoshis,
9822- 				funding_tx_locktime,
9823- 				funding_feerate_sat_per_1000_weight,
9824- 				our_funding_inputs: funding_inputs,
9825- 			},
9922+ 			dual_funding_context,
98269923			interactive_tx_constructor: None,
98279924			interactive_tx_signing_session: None,
98289925		};
@@ -9964,6 +10061,7 @@ impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
996410061
996510062		let dual_funding_context = DualFundingChannelContext {
996610063			our_funding_satoshis: our_funding_satoshis,
10064+ 			their_funding_satoshis: Some(msg.common_fields.funding_satoshis),
996710065			funding_tx_locktime: LockTime::from_consensus(msg.locktime),
996810066			funding_feerate_sat_per_1000_weight: msg.funding_feerate_sat_per_1000_weight,
996910067			our_funding_inputs: our_funding_inputs.clone(),
0 commit comments