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};
@@ -2032,6 +2032,99 @@ impl<SP: Deref> InitialRemoteCommitmentReceiver<SP> for FundedChannel<SP> where
20322032}
20332033
20342034impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
2035+ #[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled
2036+ fn begin_interactive_funding_tx_construction<ES: Deref>(
2037+ &mut self, signer_provider: &SP, entropy_source: &ES, holder_node_id: PublicKey,
2038+ extra_input: Option<(TxIn, TransactionU16LenLimited)>,
2039+ ) -> Result<Option<InteractiveTxMessageSend>, APIError>
2040+ where ES::Target: EntropySource
2041+ {
2042+ let mut funding_inputs_with_extra = self.dual_funding_context.our_funding_inputs.take().unwrap_or_else(|| vec![]);
2043+
2044+ if let Some(extra_input) = extra_input {
2045+ funding_inputs_with_extra.push(extra_input);
2046+ }
2047+
2048+ let mut funding_inputs_prev_outputs: Vec<TxOut> = Vec::with_capacity(funding_inputs_with_extra.len());
2049+ // Check that vouts exist for each TxIn in provided transactions.
2050+ for (idx, input) in funding_inputs_with_extra.iter().enumerate() {
2051+ if let Some(output) = input.1.as_transaction().output.get(input.0.previous_output.vout as usize) {
2052+ funding_inputs_prev_outputs.push(output.clone());
2053+ } else {
2054+ return Err(APIError::APIMisuseError {
2055+ err: format!("Transaction with txid {} does not have an output with vout of {} corresponding to TxIn at funding_inputs_with_extra[{}]",
2056+ input.1.as_transaction().compute_txid(), input.0.previous_output.vout, idx) });
2057+ }
2058+ }
2059+
2060+ let total_input_satoshis: u64 = funding_inputs_with_extra.iter().map(
2061+ |input| input.1.as_transaction().output.get(input.0.previous_output.vout as usize).map(|out| out.value.to_sat()).unwrap_or(0)
2062+ ).sum();
2063+ if total_input_satoshis < self.dual_funding_context.our_funding_satoshis {
2064+ return Err(APIError::APIMisuseError {
2065+ err: format!("Total value of funding inputs must be at least funding amount. It was {} sats",
2066+ total_input_satoshis) });
2067+ }
2068+
2069+ // Add output for funding tx
2070+ let mut funding_outputs = Vec::new();
2071+ let funding_output_value_satoshis = self.context.get_value_satoshis();
2072+ let funding_output_script_pubkey = self.context.get_funding_redeemscript().to_p2wsh();
2073+ let expected_remote_shared_funding_output = if self.context.is_outbound() {
2074+ let tx_out = TxOut {
2075+ value: Amount::from_sat(funding_output_value_satoshis),
2076+ script_pubkey: funding_output_script_pubkey,
2077+ };
2078+ funding_outputs.push(
2079+ if self.dual_funding_context.their_funding_satoshis.unwrap_or(0) == 0 {
2080+ OutputOwned::SharedControlFullyOwned(tx_out)
2081+ } else {
2082+ OutputOwned::Shared(SharedOwnedOutput::new(
2083+ tx_out, self.dual_funding_context.our_funding_satoshis
2084+ ))
2085+ }
2086+ );
2087+ None
2088+ } else {
2089+ Some((funding_output_script_pubkey, funding_output_value_satoshis))
2090+ };
2091+
2092+ // Optionally add change output
2093+ if let Some(change_value) = need_to_add_funding_change_output(
2094+ self.context.is_outbound(), self.dual_funding_context.our_funding_satoshis,
2095+ &funding_inputs_prev_outputs, &funding_outputs,
2096+ self.dual_funding_context.funding_feerate_sat_per_1000_weight,
2097+ self.context.holder_dust_limit_satoshis,
2098+ ) {
2099+ let change_script = signer_provider.get_destination_script(self.context.channel_keys_id).map_err(
2100+ |err| APIError::APIMisuseError {
2101+ err: format!("Failed to get change script as new destination script, {:?}", err),
2102+ })?;
2103+ let _res = add_funding_change_output(
2104+ change_value, change_script, &mut funding_outputs, self.dual_funding_context.funding_feerate_sat_per_1000_weight);
2105+ }
2106+
2107+ let constructor_args = InteractiveTxConstructorArgs {
2108+ entropy_source,
2109+ holder_node_id,
2110+ counterparty_node_id: self.context.counterparty_node_id,
2111+ channel_id: self.context.channel_id(),
2112+ feerate_sat_per_kw: self.dual_funding_context.funding_feerate_sat_per_1000_weight,
2113+ is_initiator: self.context.is_outbound(),
2114+ funding_tx_locktime: self.dual_funding_context.funding_tx_locktime,
2115+ inputs_to_contribute: funding_inputs_with_extra,
2116+ outputs_to_contribute: funding_outputs,
2117+ expected_remote_shared_funding_output,
2118+ };
2119+ let mut tx_constructor = InteractiveTxConstructor::new(constructor_args)
2120+ .map_err(|_| APIError::APIMisuseError { err: "Incorrect shared output provided".into() })?;
2121+ let msg = tx_constructor.take_initiator_first_message();
2122+
2123+ self.interactive_tx_constructor.replace(tx_constructor);
2124+
2125+ Ok(msg)
2126+ }
2127+
20352128 pub fn tx_add_input(&mut self, msg: &msgs::TxAddInput) -> InteractiveTxMessageSendResult {
20362129 InteractiveTxMessageSendResult(match &mut self.interactive_tx_constructor {
20372130 Some(ref mut tx_constructor) => tx_constructor.handle_tx_add_input(msg).map_err(
@@ -4470,7 +4563,22 @@ fn get_v2_channel_reserve_satoshis(channel_value_satoshis: u64, dust_limit_satos
44704563 cmp::min(channel_value_satoshis, cmp::max(q, dust_limit_satoshis))
44714564}
44724565
4473- #[allow(dead_code)] // TODO(dual_funding): Remove once V2 channels is enabled.
4566+ #[allow(dead_code)] // TODO(dual_funding): Remove once begin_interactive_funding_tx_construction() is used
4567+ fn add_funding_change_output(
4568+ change_value: u64, change_script: ScriptBuf,
4569+ funding_outputs: &mut Vec<OutputOwned>, funding_feerate_sat_per_1000_weight: u32,
4570+ ) -> TxOut {
4571+ let mut change_output = TxOut {
4572+ value: Amount::from_sat(change_value),
4573+ script_pubkey: change_script,
4574+ };
4575+ let change_output_weight = get_output_weight(&change_output.script_pubkey).to_wu();
4576+ let change_output_fee = fee_for_weight(funding_feerate_sat_per_1000_weight, change_output_weight);
4577+ change_output.value = Amount::from_sat(change_value.saturating_sub(change_output_fee));
4578+ funding_outputs.push(OutputOwned::Single(change_output.clone()));
4579+ change_output
4580+ }
4581+
44744582pub(super) fn calculate_our_funding_satoshis(
44754583 is_initiator: bool, funding_inputs: &[(TxIn, TransactionU16LenLimited)],
44764584 total_witness_weight: Weight, funding_feerate_sat_per_1000_weight: u32,
@@ -4516,6 +4624,9 @@ pub(super) fn calculate_our_funding_satoshis(
45164624pub(super) struct DualFundingChannelContext {
45174625 /// The amount in satoshis we will be contributing to the channel.
45184626 pub our_funding_satoshis: u64,
4627+ /// The amount in satoshis our counterparty will be contributing to the channel.
4628+ #[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
4629+ pub their_funding_satoshis: Option<u64>,
45194630 /// The funding transaction locktime suggested by the initiator. If set by us, it is always set
45204631 /// to the current block height to align incentives against fee-sniping.
45214632 pub funding_tx_locktime: LockTime,
@@ -4528,7 +4639,7 @@ pub(super) struct DualFundingChannelContext {
45284639 /// minus any fees paid for our contributed weight. This means that change will never be generated
45294640 /// and the maximum value possible will go towards funding the channel.
45304641 #[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
4531- pub our_funding_inputs: Vec<(TxIn, TransactionU16LenLimited)>,
4642+ pub our_funding_inputs: Option< Vec<(TxIn, TransactionU16LenLimited)> >,
45324643}
45334644
45344645// Holder designates channel data owned for the benefit of the user client.
@@ -9169,9 +9280,10 @@ impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
91699280 unfunded_context,
91709281 dual_funding_context: DualFundingChannelContext {
91719282 our_funding_satoshis: funding_satoshis,
9283+ their_funding_satoshis: None,
91729284 funding_tx_locktime,
91739285 funding_feerate_sat_per_1000_weight,
9174- our_funding_inputs: funding_inputs,
9286+ our_funding_inputs: Some( funding_inputs) ,
91759287 },
91769288 interactive_tx_constructor: None,
91779289 };
@@ -9319,9 +9431,10 @@ impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
93199431
93209432 let dual_funding_context = DualFundingChannelContext {
93219433 our_funding_satoshis: funding_satoshis,
9434+ their_funding_satoshis: Some(msg.common_fields.funding_satoshis),
93229435 funding_tx_locktime: LockTime::from_consensus(msg.locktime),
93239436 funding_feerate_sat_per_1000_weight: msg.funding_feerate_sat_per_1000_weight,
9324- our_funding_inputs: funding_inputs.clone(),
9437+ our_funding_inputs: Some( funding_inputs.clone() ),
93259438 };
93269439
93279440 let interactive_tx_constructor = Some(InteractiveTxConstructor::new(
0 commit comments