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+ get_output_weight, calculate_change_output_value, 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};
@@ -2222,6 +2222,106 @@ impl<SP: Deref> InitialRemoteCommitmentReceiver<SP> for FundedChannel<SP> where
22222222}
22232223
22242224impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
2225+ #[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled
2226+ pub fn begin_interactive_funding_tx_construction<ES: Deref>(
2227+ &mut self, signer_provider: &SP, entropy_source: &ES, holder_node_id: PublicKey,
2228+ prev_funding_input: Option<(TxIn, TransactionU16LenLimited)>,
2229+ ) -> Result<Option<InteractiveTxMessageSend>, APIError>
2230+ where ES::Target: EntropySource
2231+ {
2232+ let mut funding_inputs = Vec::new();
2233+ mem::swap(&mut self.dual_funding_context.our_funding_inputs, &mut funding_inputs);
2234+
2235+ if let Some(prev_funding_input) = prev_funding_input {
2236+ funding_inputs.push(prev_funding_input);
2237+ }
2238+
2239+ let mut funding_inputs_prev_outputs: Vec<&TxOut> = Vec::with_capacity(funding_inputs.len());
2240+ // Check that vouts exist for each TxIn in provided transactions.
2241+ for (idx, (txin, tx)) in funding_inputs.iter().enumerate() {
2242+ if let Some(output) = tx.as_transaction().output.get(txin.previous_output.vout as usize) {
2243+ funding_inputs_prev_outputs.push(output);
2244+ } else {
2245+ return Err(APIError::APIMisuseError {
2246+ err: format!("Transaction with txid {} does not have an output with vout of {} corresponding to TxIn at funding_inputs[{}]",
2247+ tx.as_transaction().compute_txid(), txin.previous_output.vout, idx) });
2248+ }
2249+ }
2250+
2251+ let total_input_satoshis: u64 = funding_inputs.iter().map(
2252+ |(txin, tx)| tx.as_transaction().output.get(txin.previous_output.vout as usize).map(|out| out.value.to_sat()).unwrap_or(0)
2253+ ).sum();
2254+ if total_input_satoshis < self.dual_funding_context.our_funding_satoshis {
2255+ return Err(APIError::APIMisuseError {
2256+ err: format!("Total value of funding inputs must be at least funding amount. It was {} sats",
2257+ total_input_satoshis) });
2258+ }
2259+
2260+ // Add output for funding tx
2261+ let mut funding_outputs = Vec::new();
2262+ let funding_output_value_satoshis = self.funding.get_value_satoshis();
2263+ let funding_output_script_pubkey = self.funding.get_funding_redeemscript().to_p2wsh();
2264+ let expected_remote_shared_funding_output = if self.funding.is_outbound() {
2265+ let tx_out = TxOut {
2266+ value: Amount::from_sat(funding_output_value_satoshis),
2267+ script_pubkey: funding_output_script_pubkey,
2268+ };
2269+ funding_outputs.push(
2270+ if self.dual_funding_context.their_funding_satoshis.unwrap_or(0) == 0 {
2271+ OutputOwned::SharedControlFullyOwned(tx_out)
2272+ } else {
2273+ OutputOwned::Shared(SharedOwnedOutput::new(
2274+ tx_out, self.dual_funding_context.our_funding_satoshis
2275+ ))
2276+ }
2277+ );
2278+ None
2279+ } else {
2280+ Some((funding_output_script_pubkey, funding_output_value_satoshis))
2281+ };
2282+
2283+ // Optionally add change output
2284+ if let Some(change_value) = calculate_change_output_value(
2285+ self.funding.is_outbound(), self.dual_funding_context.our_funding_satoshis,
2286+ &funding_inputs_prev_outputs, &funding_outputs,
2287+ self.dual_funding_context.funding_feerate_sat_per_1000_weight,
2288+ self.context.holder_dust_limit_satoshis,
2289+ ) {
2290+ let change_script = signer_provider.get_destination_script(self.context.channel_keys_id).map_err(
2291+ |err| APIError::APIMisuseError {
2292+ err: format!("Failed to get change script as new destination script, {:?}", err),
2293+ })?;
2294+ let mut change_output = TxOut {
2295+ value: Amount::from_sat(change_value),
2296+ script_pubkey: change_script,
2297+ };
2298+ let change_output_weight = get_output_weight(&change_output.script_pubkey).to_wu();
2299+ let change_output_fee = fee_for_weight(self.dual_funding_context.funding_feerate_sat_per_1000_weight, change_output_weight);
2300+ change_output.value = Amount::from_sat(change_value.saturating_sub(change_output_fee));
2301+ funding_outputs.push(OutputOwned::Single(change_output));
2302+ }
2303+
2304+ let constructor_args = InteractiveTxConstructorArgs {
2305+ entropy_source,
2306+ holder_node_id,
2307+ counterparty_node_id: self.context.counterparty_node_id,
2308+ channel_id: self.context.channel_id(),
2309+ feerate_sat_per_kw: self.dual_funding_context.funding_feerate_sat_per_1000_weight,
2310+ is_initiator: self.funding.is_outbound(),
2311+ funding_tx_locktime: self.dual_funding_context.funding_tx_locktime,
2312+ inputs_to_contribute: funding_inputs,
2313+ outputs_to_contribute: funding_outputs,
2314+ expected_remote_shared_funding_output,
2315+ };
2316+ let mut tx_constructor = InteractiveTxConstructor::new(constructor_args)
2317+ .map_err(|_| APIError::APIMisuseError { err: "Incorrect shared output provided".into() })?;
2318+ let msg = tx_constructor.take_initiator_first_message();
2319+
2320+ self.interactive_tx_constructor = Some(tx_constructor);
2321+
2322+ Ok(msg)
2323+ }
2324+
22252325 pub fn tx_add_input(&mut self, msg: &msgs::TxAddInput) -> InteractiveTxMessageSendResult {
22262326 InteractiveTxMessageSendResult(match &mut self.interactive_tx_constructor {
22272327 Some(ref mut tx_constructor) => tx_constructor.handle_tx_add_input(msg).map_err(
@@ -4875,6 +4975,9 @@ fn check_v2_funding_inputs_sufficient(
48754975pub(super) struct DualFundingChannelContext {
48764976 /// The amount in satoshis we will be contributing to the channel.
48774977 pub our_funding_satoshis: u64,
4978+ /// The amount in satoshis our counterparty will be contributing to the channel.
4979+ #[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
4980+ pub their_funding_satoshis: Option<u64>,
48784981 /// The funding transaction locktime suggested by the initiator. If set by us, it is always set
48794982 /// to the current block height to align incentives against fee-sniping.
48804983 pub funding_tx_locktime: LockTime,
@@ -4886,6 +4989,8 @@ pub(super) struct DualFundingChannelContext {
48864989 /// Note that the `our_funding_satoshis` field is equal to the total value of `our_funding_inputs`
48874990 /// minus any fees paid for our contributed weight. This means that change will never be generated
48884991 /// and the maximum value possible will go towards funding the channel.
4992+ ///
4993+ /// Note that this field may be emptied once the interactive negotiation has been started.
48894994 #[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
48904995 pub our_funding_inputs: Vec<(TxIn, TransactionU16LenLimited)>,
48914996}
@@ -9857,6 +9962,7 @@ impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
98579962 unfunded_context,
98589963 dual_funding_context: DualFundingChannelContext {
98599964 our_funding_satoshis: funding_satoshis,
9965+ their_funding_satoshis: None,
98609966 funding_tx_locktime,
98619967 funding_feerate_sat_per_1000_weight,
98629968 our_funding_inputs: funding_inputs,
@@ -10002,6 +10108,7 @@ impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
1000210108
1000310109 let dual_funding_context = DualFundingChannelContext {
1000410110 our_funding_satoshis: our_funding_satoshis,
10111+ their_funding_satoshis: Some(msg.common_fields.funding_satoshis),
1000510112 funding_tx_locktime: LockTime::from_consensus(msg.locktime),
1000610113 funding_feerate_sat_per_1000_weight: msg.funding_feerate_sat_per_1000_weight,
1000710114 our_funding_inputs: our_funding_inputs.clone(),
0 commit comments