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;
1515use bitcoin::sighash::EcdsaSighashType;
1616use bitcoin::consensus::encode;
@@ -31,9 +31,9 @@ use crate::ln::types::ChannelId;
3131use crate::types::payment::{PaymentPreimage, PaymentHash};
3232use crate::types::features::{ChannelTypeFeatures, InitFeatures};
3333use crate::ln::interactivetxs::{
34- get_output_weight, HandleTxCompleteValue, HandleTxCompleteResult, InteractiveTxConstructor,
35- InteractiveTxConstructorArgs, InteractiveTxSigningSession, InteractiveTxMessageSendResult,
36- TX_COMMON_FIELDS_WEIGHT,
34+ get_output_weight, need_to_add_funding_change_output, HandleTxCompleteValue, HandleTxCompleteResult, InteractiveTxConstructor,
35+ InteractiveTxConstructorArgs, InteractiveTxMessageSend, InteractiveTxSigningSession, InteractiveTxMessageSendResult,
36+ OutputOwned, SharedOwnedOutput, TX_COMMON_FIELDS_WEIGHT,
3737};
3838use crate::ln::msgs;
3939use crate::ln::msgs::{ClosingSigned, ClosingSignedFeeRange, DecodeError};
@@ -2213,6 +2213,99 @@ impl<SP: Deref> InitialRemoteCommitmentReceiver<SP> for FundedChannel<SP> where
22132213}
22142214
22152215impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
2216+ #[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled
2217+ fn begin_interactive_funding_tx_construction<ES: Deref>(
2218+ &mut self, signer_provider: &SP, entropy_source: &ES, holder_node_id: PublicKey,
2219+ extra_input: Option<(TxIn, TransactionU16LenLimited)>,
2220+ ) -> Result<Option<InteractiveTxMessageSend>, APIError>
2221+ where ES::Target: EntropySource
2222+ {
2223+ let mut funding_inputs_with_extra = self.dual_funding_context.our_funding_inputs.take().unwrap_or_else(|| vec![]);
2224+
2225+ if let Some(extra_input) = extra_input {
2226+ funding_inputs_with_extra.push(extra_input);
2227+ }
2228+
2229+ let mut funding_inputs_prev_outputs: Vec<TxOut> = Vec::with_capacity(funding_inputs_with_extra.len());
2230+ // Check that vouts exist for each TxIn in provided transactions.
2231+ for (idx, input) in funding_inputs_with_extra.iter().enumerate() {
2232+ if let Some(output) = input.1.as_transaction().output.get(input.0.previous_output.vout as usize) {
2233+ funding_inputs_prev_outputs.push(output.clone());
2234+ } else {
2235+ return Err(APIError::APIMisuseError {
2236+ err: format!("Transaction with txid {} does not have an output with vout of {} corresponding to TxIn at funding_inputs_with_extra[{}]",
2237+ input.1.as_transaction().compute_txid(), input.0.previous_output.vout, idx) });
2238+ }
2239+ }
2240+
2241+ let total_input_satoshis: u64 = funding_inputs_with_extra.iter().map(
2242+ |input| input.1.as_transaction().output.get(input.0.previous_output.vout as usize).map(|out| out.value.to_sat()).unwrap_or(0)
2243+ ).sum();
2244+ if total_input_satoshis < self.dual_funding_context.our_funding_satoshis {
2245+ return Err(APIError::APIMisuseError {
2246+ err: format!("Total value of funding inputs must be at least funding amount. It was {} sats",
2247+ total_input_satoshis) });
2248+ }
2249+
2250+ // Add output for funding tx
2251+ let mut funding_outputs = Vec::new();
2252+ let funding_output_value_satoshis = self.funding.get_value_satoshis();
2253+ let funding_output_script_pubkey = self.funding.get_funding_redeemscript().to_p2wsh();
2254+ let expected_remote_shared_funding_output = if self.funding.is_outbound() {
2255+ let tx_out = TxOut {
2256+ value: Amount::from_sat(funding_output_value_satoshis),
2257+ script_pubkey: funding_output_script_pubkey,
2258+ };
2259+ funding_outputs.push(
2260+ if self.dual_funding_context.their_funding_satoshis.unwrap_or(0) == 0 {
2261+ OutputOwned::SharedControlFullyOwned(tx_out)
2262+ } else {
2263+ OutputOwned::Shared(SharedOwnedOutput::new(
2264+ tx_out, self.dual_funding_context.our_funding_satoshis
2265+ ))
2266+ }
2267+ );
2268+ None
2269+ } else {
2270+ Some((funding_output_script_pubkey, funding_output_value_satoshis))
2271+ };
2272+
2273+ // Optionally add change output
2274+ if let Some(change_value) = need_to_add_funding_change_output(
2275+ self.funding.is_outbound(), self.dual_funding_context.our_funding_satoshis,
2276+ &funding_inputs_prev_outputs, &funding_outputs,
2277+ self.dual_funding_context.funding_feerate_sat_per_1000_weight,
2278+ self.context.holder_dust_limit_satoshis,
2279+ ) {
2280+ let change_script = signer_provider.get_destination_script(self.context.channel_keys_id).map_err(
2281+ |err| APIError::APIMisuseError {
2282+ err: format!("Failed to get change script as new destination script, {:?}", err),
2283+ })?;
2284+ let _res = add_funding_change_output(
2285+ change_value, change_script, &mut funding_outputs, self.dual_funding_context.funding_feerate_sat_per_1000_weight);
2286+ }
2287+
2288+ let constructor_args = InteractiveTxConstructorArgs {
2289+ entropy_source,
2290+ holder_node_id,
2291+ counterparty_node_id: self.context.counterparty_node_id,
2292+ channel_id: self.context.channel_id(),
2293+ feerate_sat_per_kw: self.dual_funding_context.funding_feerate_sat_per_1000_weight,
2294+ is_initiator: self.funding.is_outbound(),
2295+ funding_tx_locktime: self.dual_funding_context.funding_tx_locktime,
2296+ inputs_to_contribute: funding_inputs_with_extra,
2297+ outputs_to_contribute: funding_outputs,
2298+ expected_remote_shared_funding_output,
2299+ };
2300+ let mut tx_constructor = InteractiveTxConstructor::new(constructor_args)
2301+ .map_err(|_| APIError::APIMisuseError { err: "Incorrect shared output provided".into() })?;
2302+ let msg = tx_constructor.take_initiator_first_message();
2303+
2304+ self.interactive_tx_constructor.replace(tx_constructor);
2305+
2306+ Ok(msg)
2307+ }
2308+
22162309 pub fn tx_add_input(&mut self, msg: &msgs::TxAddInput) -> InteractiveTxMessageSendResult {
22172310 InteractiveTxMessageSendResult(match &mut self.interactive_tx_constructor {
22182311 Some(ref mut tx_constructor) => tx_constructor.handle_tx_add_input(msg).map_err(
@@ -4667,10 +4760,29 @@ fn estimate_v2_funding_transaction_fee(
46674760 fee_for_weight(funding_feerate_sat_per_1000_weight, weight)
46684761}
46694762
4763+ #[allow(dead_code)] // TODO(dual_funding): Remove once begin_interactive_funding_tx_construction() is used
4764+ fn add_funding_change_output(
4765+ change_value: u64, change_script: ScriptBuf,
4766+ funding_outputs: &mut Vec<OutputOwned>, funding_feerate_sat_per_1000_weight: u32,
4767+ ) -> TxOut {
4768+ let mut change_output = TxOut {
4769+ value: Amount::from_sat(change_value),
4770+ script_pubkey: change_script,
4771+ };
4772+ let change_output_weight = get_output_weight(&change_output.script_pubkey).to_wu();
4773+ let change_output_fee = fee_for_weight(funding_feerate_sat_per_1000_weight, change_output_weight);
4774+ change_output.value = Amount::from_sat(change_value.saturating_sub(change_output_fee));
4775+ funding_outputs.push(OutputOwned::Single(change_output.clone()));
4776+ change_output
4777+ }
4778+
46704779/// Context for dual-funded channels.
46714780pub(super) struct DualFundingChannelContext {
46724781 /// The amount in satoshis we will be contributing to the channel.
46734782 pub our_funding_satoshis: u64,
4783+ /// The amount in satoshis our counterparty will be contributing to the channel.
4784+ #[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
4785+ pub their_funding_satoshis: Option<u64>,
46744786 /// The funding transaction locktime suggested by the initiator. If set by us, it is always set
46754787 /// to the current block height to align incentives against fee-sniping.
46764788 pub funding_tx_locktime: LockTime,
@@ -4683,7 +4795,7 @@ pub(super) struct DualFundingChannelContext {
46834795 /// minus any fees paid for our contributed weight. This means that change will never be generated
46844796 /// and the maximum value possible will go towards funding the channel.
46854797 #[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
4686- pub our_funding_inputs: Vec<(TxIn, TransactionU16LenLimited)>,
4798+ pub our_funding_inputs: Option< Vec<(TxIn, TransactionU16LenLimited)> >,
46874799}
46884800
46894801// Holder designates channel data owned for the benefit of the user client.
@@ -9608,9 +9720,10 @@ impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
96089720 unfunded_context,
96099721 dual_funding_context: DualFundingChannelContext {
96109722 our_funding_satoshis: funding_satoshis,
9723+ their_funding_satoshis: None,
96119724 funding_tx_locktime,
96129725 funding_feerate_sat_per_1000_weight,
9613- our_funding_inputs: funding_inputs,
9726+ our_funding_inputs: Some( funding_inputs) ,
96149727 },
96159728 interactive_tx_constructor: None,
96169729 interactive_tx_signing_session: None,
@@ -9753,9 +9866,10 @@ impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
97539866
97549867 let dual_funding_context = DualFundingChannelContext {
97559868 our_funding_satoshis: our_funding_satoshis,
9869+ their_funding_satoshis: Some(msg.common_fields.funding_satoshis),
97569870 funding_tx_locktime: LockTime::from_consensus(msg.locktime),
97579871 funding_feerate_sat_per_1000_weight: msg.funding_feerate_sat_per_1000_weight,
9758- our_funding_inputs: our_funding_inputs.clone(),
9872+ our_funding_inputs: Some( our_funding_inputs.clone() ),
97599873 };
97609874
97619875 let interactive_tx_constructor = Some(InteractiveTxConstructor::new(
0 commit comments