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, need_to_add_funding_change_output, 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};
@@ -2237,6 +2237,99 @@ impl<SP: Deref> InitialRemoteCommitmentReceiver<SP> for FundedChannel<SP> where
22372237}
22382238
22392239impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
2240+ #[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled
2241+ fn begin_interactive_funding_tx_construction<ES: Deref>(
2242+ &mut self, signer_provider: &SP, entropy_source: &ES, holder_node_id: PublicKey,
2243+ extra_input: Option<(TxIn, TransactionU16LenLimited)>,
2244+ ) -> Result<Option<InteractiveTxMessageSend>, APIError>
2245+ where ES::Target: EntropySource
2246+ {
2247+ let mut funding_inputs_with_extra = self.dual_funding_context.our_funding_inputs.take().unwrap_or_else(|| vec![]);
2248+
2249+ if let Some(extra_input) = extra_input {
2250+ funding_inputs_with_extra.push(extra_input);
2251+ }
2252+
2253+ let mut funding_inputs_prev_outputs: Vec<TxOut> = Vec::with_capacity(funding_inputs_with_extra.len());
2254+ // Check that vouts exist for each TxIn in provided transactions.
2255+ for (idx, input) in funding_inputs_with_extra.iter().enumerate() {
2256+ if let Some(output) = input.1.as_transaction().output.get(input.0.previous_output.vout as usize) {
2257+ funding_inputs_prev_outputs.push(output.clone());
2258+ } else {
2259+ return Err(APIError::APIMisuseError {
2260+ err: format!("Transaction with txid {} does not have an output with vout of {} corresponding to TxIn at funding_inputs_with_extra[{}]",
2261+ input.1.as_transaction().compute_txid(), input.0.previous_output.vout, idx) });
2262+ }
2263+ }
2264+
2265+ let total_input_satoshis: u64 = funding_inputs_with_extra.iter().map(
2266+ |input| input.1.as_transaction().output.get(input.0.previous_output.vout as usize).map(|out| out.value.to_sat()).unwrap_or(0)
2267+ ).sum();
2268+ if total_input_satoshis < self.dual_funding_context.our_funding_satoshis {
2269+ return Err(APIError::APIMisuseError {
2270+ err: format!("Total value of funding inputs must be at least funding amount. It was {} sats",
2271+ total_input_satoshis) });
2272+ }
2273+
2274+ // Add output for funding tx
2275+ let mut funding_outputs = Vec::new();
2276+ let funding_output_value_satoshis = self.funding.get_value_satoshis();
2277+ let funding_output_script_pubkey = self.funding.get_funding_redeemscript().to_p2wsh();
2278+ let expected_remote_shared_funding_output = if self.funding.is_outbound() {
2279+ let tx_out = TxOut {
2280+ value: Amount::from_sat(funding_output_value_satoshis),
2281+ script_pubkey: funding_output_script_pubkey,
2282+ };
2283+ funding_outputs.push(
2284+ if self.dual_funding_context.their_funding_satoshis.unwrap_or(0) == 0 {
2285+ OutputOwned::SharedControlFullyOwned(tx_out)
2286+ } else {
2287+ OutputOwned::Shared(SharedOwnedOutput::new(
2288+ tx_out, self.dual_funding_context.our_funding_satoshis
2289+ ))
2290+ }
2291+ );
2292+ None
2293+ } else {
2294+ Some((funding_output_script_pubkey, funding_output_value_satoshis))
2295+ };
2296+
2297+ // Optionally add change output
2298+ if let Some(change_value) = need_to_add_funding_change_output(
2299+ self.funding.is_outbound(), self.dual_funding_context.our_funding_satoshis,
2300+ &funding_inputs_prev_outputs, &funding_outputs,
2301+ self.dual_funding_context.funding_feerate_sat_per_1000_weight,
2302+ self.context.holder_dust_limit_satoshis,
2303+ ) {
2304+ let change_script = signer_provider.get_destination_script(self.context.channel_keys_id).map_err(
2305+ |err| APIError::APIMisuseError {
2306+ err: format!("Failed to get change script as new destination script, {:?}", err),
2307+ })?;
2308+ let _res = add_funding_change_output(
2309+ change_value, change_script, &mut funding_outputs, self.dual_funding_context.funding_feerate_sat_per_1000_weight);
2310+ }
2311+
2312+ let constructor_args = InteractiveTxConstructorArgs {
2313+ entropy_source,
2314+ holder_node_id,
2315+ counterparty_node_id: self.context.counterparty_node_id,
2316+ channel_id: self.context.channel_id(),
2317+ feerate_sat_per_kw: self.dual_funding_context.funding_feerate_sat_per_1000_weight,
2318+ is_initiator: self.funding.is_outbound(),
2319+ funding_tx_locktime: self.dual_funding_context.funding_tx_locktime,
2320+ inputs_to_contribute: funding_inputs_with_extra,
2321+ outputs_to_contribute: funding_outputs,
2322+ expected_remote_shared_funding_output,
2323+ };
2324+ let mut tx_constructor = InteractiveTxConstructor::new(constructor_args)
2325+ .map_err(|_| APIError::APIMisuseError { err: "Incorrect shared output provided".into() })?;
2326+ let msg = tx_constructor.take_initiator_first_message();
2327+
2328+ self.interactive_tx_constructor.replace(tx_constructor);
2329+
2330+ Ok(msg)
2331+ }
2332+
22402333 pub fn tx_add_input(&mut self, msg: &msgs::TxAddInput) -> InteractiveTxMessageSendResult {
22412334 InteractiveTxMessageSendResult(match &mut self.interactive_tx_constructor {
22422335 Some(ref mut tx_constructor) => tx_constructor.handle_tx_add_input(msg).map_err(
@@ -4873,10 +4966,29 @@ fn check_v2_funding_inputs_sufficient(
48734966 }
48744967}
48754968
4969+ #[allow(dead_code)] // TODO(dual_funding): Remove once begin_interactive_funding_tx_construction() is used
4970+ fn add_funding_change_output(
4971+ change_value: u64, change_script: ScriptBuf,
4972+ funding_outputs: &mut Vec<OutputOwned>, funding_feerate_sat_per_1000_weight: u32,
4973+ ) -> TxOut {
4974+ let mut change_output = TxOut {
4975+ value: Amount::from_sat(change_value),
4976+ script_pubkey: change_script,
4977+ };
4978+ let change_output_weight = get_output_weight(&change_output.script_pubkey).to_wu();
4979+ let change_output_fee = fee_for_weight(funding_feerate_sat_per_1000_weight, change_output_weight);
4980+ change_output.value = Amount::from_sat(change_value.saturating_sub(change_output_fee));
4981+ funding_outputs.push(OutputOwned::Single(change_output.clone()));
4982+ change_output
4983+ }
4984+
48764985/// Context for dual-funded channels.
48774986pub(super) struct DualFundingChannelContext {
48784987 /// The amount in satoshis we will be contributing to the channel.
48794988 pub our_funding_satoshis: u64,
4989+ /// The amount in satoshis our counterparty will be contributing to the channel.
4990+ #[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
4991+ pub their_funding_satoshis: Option<u64>,
48804992 /// The funding transaction locktime suggested by the initiator. If set by us, it is always set
48814993 /// to the current block height to align incentives against fee-sniping.
48824994 pub funding_tx_locktime: LockTime,
@@ -4889,7 +5001,7 @@ pub(super) struct DualFundingChannelContext {
48895001 /// minus any fees paid for our contributed weight. This means that change will never be generated
48905002 /// and the maximum value possible will go towards funding the channel.
48915003 #[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
4892- pub our_funding_inputs: Vec<(TxIn, TransactionU16LenLimited)>,
5004+ pub our_funding_inputs: Option< Vec<(TxIn, TransactionU16LenLimited)> >,
48935005}
48945006
48955007// Holder designates channel data owned for the benefit of the user client.
@@ -9882,9 +9994,10 @@ impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
98829994 unfunded_context,
98839995 dual_funding_context: DualFundingChannelContext {
98849996 our_funding_satoshis: funding_satoshis,
9997+ their_funding_satoshis: None,
98859998 funding_tx_locktime,
98869999 funding_feerate_sat_per_1000_weight,
9887- our_funding_inputs: funding_inputs,
10000+ our_funding_inputs: Some( funding_inputs) ,
988810001 },
988910002 interactive_tx_constructor: None,
989010003 interactive_tx_signing_session: None,
@@ -10027,9 +10140,10 @@ impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
1002710140
1002810141 let dual_funding_context = DualFundingChannelContext {
1002910142 our_funding_satoshis: our_funding_satoshis,
10143+ their_funding_satoshis: Some(msg.common_fields.funding_satoshis),
1003010144 funding_tx_locktime: LockTime::from_consensus(msg.locktime),
1003110145 funding_feerate_sat_per_1000_weight: msg.funding_feerate_sat_per_1000_weight,
10032- our_funding_inputs: our_funding_inputs.clone(),
10146+ our_funding_inputs: Some( our_funding_inputs.clone() ),
1003310147 };
1003410148
1003510149 let interactive_tx_constructor = Some(InteractiveTxConstructor::new(
0 commit comments