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};
@@ -2232,6 +2232,99 @@ impl<SP: Deref> InitialRemoteCommitmentReceiver<SP> for FundedChannel<SP> where
22322232}
22332233
22342234impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
2235+ #[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled
2236+ fn begin_interactive_funding_tx_construction<ES: Deref>(
2237+ &mut self, signer_provider: &SP, entropy_source: &ES, holder_node_id: PublicKey,
2238+ extra_input: Option<(TxIn, TransactionU16LenLimited)>,
2239+ ) -> Result<Option<InteractiveTxMessageSend>, APIError>
2240+ where ES::Target: EntropySource
2241+ {
2242+ let mut funding_inputs_with_extra = self.dual_funding_context.our_funding_inputs.take().unwrap_or_else(|| vec![]);
2243+
2244+ if let Some(extra_input) = extra_input {
2245+ funding_inputs_with_extra.push(extra_input);
2246+ }
2247+
2248+ let mut funding_inputs_prev_outputs: Vec<TxOut> = Vec::with_capacity(funding_inputs_with_extra.len());
2249+ // Check that vouts exist for each TxIn in provided transactions.
2250+ for (idx, input) in funding_inputs_with_extra.iter().enumerate() {
2251+ if let Some(output) = input.1.as_transaction().output.get(input.0.previous_output.vout as usize) {
2252+ funding_inputs_prev_outputs.push(output.clone());
2253+ } else {
2254+ return Err(APIError::APIMisuseError {
2255+ err: format!("Transaction with txid {} does not have an output with vout of {} corresponding to TxIn at funding_inputs_with_extra[{}]",
2256+ input.1.as_transaction().compute_txid(), input.0.previous_output.vout, idx) });
2257+ }
2258+ }
2259+
2260+ let total_input_satoshis: u64 = funding_inputs_with_extra.iter().map(
2261+ |input| input.1.as_transaction().output.get(input.0.previous_output.vout as usize).map(|out| out.value.to_sat()).unwrap_or(0)
2262+ ).sum();
2263+ if total_input_satoshis < self.dual_funding_context.our_funding_satoshis {
2264+ return Err(APIError::APIMisuseError {
2265+ err: format!("Total value of funding inputs must be at least funding amount. It was {} sats",
2266+ total_input_satoshis) });
2267+ }
2268+
2269+ // Add output for funding tx
2270+ let mut funding_outputs = Vec::new();
2271+ let funding_output_value_satoshis = self.funding.get_value_satoshis();
2272+ let funding_output_script_pubkey = self.funding.get_funding_redeemscript().to_p2wsh();
2273+ let expected_remote_shared_funding_output = if self.funding.is_outbound() {
2274+ let tx_out = TxOut {
2275+ value: Amount::from_sat(funding_output_value_satoshis),
2276+ script_pubkey: funding_output_script_pubkey,
2277+ };
2278+ funding_outputs.push(
2279+ if self.dual_funding_context.their_funding_satoshis.unwrap_or(0) == 0 {
2280+ OutputOwned::SharedControlFullyOwned(tx_out)
2281+ } else {
2282+ OutputOwned::Shared(SharedOwnedOutput::new(
2283+ tx_out, self.dual_funding_context.our_funding_satoshis
2284+ ))
2285+ }
2286+ );
2287+ None
2288+ } else {
2289+ Some((funding_output_script_pubkey, funding_output_value_satoshis))
2290+ };
2291+
2292+ // Optionally add change output
2293+ if let Some(change_value) = need_to_add_funding_change_output(
2294+ self.funding.is_outbound(), self.dual_funding_context.our_funding_satoshis,
2295+ &funding_inputs_prev_outputs, &funding_outputs,
2296+ self.dual_funding_context.funding_feerate_sat_per_1000_weight,
2297+ self.context.holder_dust_limit_satoshis,
2298+ ) {
2299+ let change_script = signer_provider.get_destination_script(self.context.channel_keys_id).map_err(
2300+ |err| APIError::APIMisuseError {
2301+ err: format!("Failed to get change script as new destination script, {:?}", err),
2302+ })?;
2303+ let _res = add_funding_change_output(
2304+ change_value, change_script, &mut funding_outputs, self.dual_funding_context.funding_feerate_sat_per_1000_weight);
2305+ }
2306+
2307+ let constructor_args = InteractiveTxConstructorArgs {
2308+ entropy_source,
2309+ holder_node_id,
2310+ counterparty_node_id: self.context.counterparty_node_id,
2311+ channel_id: self.context.channel_id(),
2312+ feerate_sat_per_kw: self.dual_funding_context.funding_feerate_sat_per_1000_weight,
2313+ is_initiator: self.funding.is_outbound(),
2314+ funding_tx_locktime: self.dual_funding_context.funding_tx_locktime,
2315+ inputs_to_contribute: funding_inputs_with_extra,
2316+ outputs_to_contribute: funding_outputs,
2317+ expected_remote_shared_funding_output,
2318+ };
2319+ let mut tx_constructor = InteractiveTxConstructor::new(constructor_args)
2320+ .map_err(|_| APIError::APIMisuseError { err: "Incorrect shared output provided".into() })?;
2321+ let msg = tx_constructor.take_initiator_first_message();
2322+
2323+ self.interactive_tx_constructor.replace(tx_constructor);
2324+
2325+ Ok(msg)
2326+ }
2327+
22352328 pub fn tx_add_input(&mut self, msg: &msgs::TxAddInput) -> InteractiveTxMessageSendResult {
22362329 InteractiveTxMessageSendResult(match &mut self.interactive_tx_constructor {
22372330 Some(ref mut tx_constructor) => tx_constructor.handle_tx_add_input(msg).map_err(
@@ -4911,10 +5004,29 @@ fn check_v2_funding_inputs_sufficient(
49115004 }
49125005}
49135006
5007+ #[allow(dead_code)] // TODO(dual_funding): Remove once begin_interactive_funding_tx_construction() is used
5008+ fn add_funding_change_output(
5009+ change_value: u64, change_script: ScriptBuf,
5010+ funding_outputs: &mut Vec<OutputOwned>, funding_feerate_sat_per_1000_weight: u32,
5011+ ) -> TxOut {
5012+ let mut change_output = TxOut {
5013+ value: Amount::from_sat(change_value),
5014+ script_pubkey: change_script,
5015+ };
5016+ let change_output_weight = get_output_weight(&change_output.script_pubkey).to_wu();
5017+ let change_output_fee = fee_for_weight(funding_feerate_sat_per_1000_weight, change_output_weight);
5018+ change_output.value = Amount::from_sat(change_value.saturating_sub(change_output_fee));
5019+ funding_outputs.push(OutputOwned::Single(change_output.clone()));
5020+ change_output
5021+ }
5022+
49145023/// Context for dual-funded channels.
49155024pub(super) struct DualFundingChannelContext {
49165025 /// The amount in satoshis we will be contributing to the channel.
49175026 pub our_funding_satoshis: u64,
5027+ /// The amount in satoshis our counterparty will be contributing to the channel.
5028+ #[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
5029+ pub their_funding_satoshis: Option<u64>,
49185030 /// The funding transaction locktime suggested by the initiator. If set by us, it is always set
49195031 /// to the current block height to align incentives against fee-sniping.
49205032 pub funding_tx_locktime: LockTime,
@@ -4927,7 +5039,7 @@ pub(super) struct DualFundingChannelContext {
49275039 /// minus any fees paid for our contributed weight. This means that change will never be generated
49285040 /// and the maximum value possible will go towards funding the channel.
49295041 #[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
4930- pub our_funding_inputs: Vec<(TxIn, TransactionU16LenLimited)>,
5042+ pub our_funding_inputs: Option< Vec<(TxIn, TransactionU16LenLimited)> >,
49315043}
49325044
49335045// Holder designates channel data owned for the benefit of the user client.
@@ -9915,9 +10027,10 @@ impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
991510027 unfunded_context,
991610028 dual_funding_context: DualFundingChannelContext {
991710029 our_funding_satoshis: funding_satoshis,
10030+ their_funding_satoshis: None,
991810031 funding_tx_locktime,
991910032 funding_feerate_sat_per_1000_weight,
9920- our_funding_inputs: funding_inputs,
10033+ our_funding_inputs: Some( funding_inputs) ,
992110034 },
992210035 interactive_tx_constructor: None,
992310036 interactive_tx_signing_session: None,
@@ -10060,9 +10173,10 @@ impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
1006010173
1006110174 let dual_funding_context = DualFundingChannelContext {
1006210175 our_funding_satoshis: our_funding_satoshis,
10176+ their_funding_satoshis: Some(msg.common_fields.funding_satoshis),
1006310177 funding_tx_locktime: LockTime::from_consensus(msg.locktime),
1006410178 funding_feerate_sat_per_1000_weight: msg.funding_feerate_sat_per_1000_weight,
10065- our_funding_inputs: our_funding_inputs.clone(),
10179+ our_funding_inputs: Some( our_funding_inputs.clone() ),
1006610180 };
1006710181
1006810182 let interactive_tx_constructor = Some(InteractiveTxConstructor::new(
0 commit comments