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};
@@ -2240,6 +2240,99 @@ impl<SP: Deref> InitialRemoteCommitmentReceiver<SP> for FundedChannel<SP> where
22402240}
22412241
22422242impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
2243+ #[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled
2244+ fn begin_interactive_funding_tx_construction<ES: Deref>(
2245+ &mut self, signer_provider: &SP, entropy_source: &ES, holder_node_id: PublicKey,
2246+ extra_input: Option<(TxIn, TransactionU16LenLimited)>,
2247+ ) -> Result<Option<InteractiveTxMessageSend>, APIError>
2248+ where ES::Target: EntropySource
2249+ {
2250+ let mut funding_inputs_with_extra = self.dual_funding_context.our_funding_inputs.take().unwrap_or_else(|| vec![]);
2251+
2252+ if let Some(extra_input) = extra_input {
2253+ funding_inputs_with_extra.push(extra_input);
2254+ }
2255+
2256+ let mut funding_inputs_prev_outputs: Vec<TxOut> = Vec::with_capacity(funding_inputs_with_extra.len());
2257+ // Check that vouts exist for each TxIn in provided transactions.
2258+ for (idx, input) in funding_inputs_with_extra.iter().enumerate() {
2259+ if let Some(output) = input.1.as_transaction().output.get(input.0.previous_output.vout as usize) {
2260+ funding_inputs_prev_outputs.push(output.clone());
2261+ } else {
2262+ return Err(APIError::APIMisuseError {
2263+ err: format!("Transaction with txid {} does not have an output with vout of {} corresponding to TxIn at funding_inputs_with_extra[{}]",
2264+ input.1.as_transaction().compute_txid(), input.0.previous_output.vout, idx) });
2265+ }
2266+ }
2267+
2268+ let total_input_satoshis: u64 = funding_inputs_with_extra.iter().map(
2269+ |input| input.1.as_transaction().output.get(input.0.previous_output.vout as usize).map(|out| out.value.to_sat()).unwrap_or(0)
2270+ ).sum();
2271+ if total_input_satoshis < self.dual_funding_context.our_funding_satoshis {
2272+ return Err(APIError::APIMisuseError {
2273+ err: format!("Total value of funding inputs must be at least funding amount. It was {} sats",
2274+ total_input_satoshis) });
2275+ }
2276+
2277+ // Add output for funding tx
2278+ let mut funding_outputs = Vec::new();
2279+ let funding_output_value_satoshis = self.funding.get_value_satoshis();
2280+ let funding_output_script_pubkey = self.funding.get_funding_redeemscript().to_p2wsh();
2281+ let expected_remote_shared_funding_output = if self.funding.is_outbound() {
2282+ let tx_out = TxOut {
2283+ value: Amount::from_sat(funding_output_value_satoshis),
2284+ script_pubkey: funding_output_script_pubkey,
2285+ };
2286+ funding_outputs.push(
2287+ if self.dual_funding_context.their_funding_satoshis.unwrap_or(0) == 0 {
2288+ OutputOwned::SharedControlFullyOwned(tx_out)
2289+ } else {
2290+ OutputOwned::Shared(SharedOwnedOutput::new(
2291+ tx_out, self.dual_funding_context.our_funding_satoshis
2292+ ))
2293+ }
2294+ );
2295+ None
2296+ } else {
2297+ Some((funding_output_script_pubkey, funding_output_value_satoshis))
2298+ };
2299+
2300+ // Optionally add change output
2301+ if let Some(change_value) = need_to_add_funding_change_output(
2302+ self.funding.is_outbound(), self.dual_funding_context.our_funding_satoshis,
2303+ &funding_inputs_prev_outputs, &funding_outputs,
2304+ self.dual_funding_context.funding_feerate_sat_per_1000_weight,
2305+ self.context.holder_dust_limit_satoshis,
2306+ ) {
2307+ let change_script = signer_provider.get_destination_script(self.context.channel_keys_id).map_err(
2308+ |err| APIError::APIMisuseError {
2309+ err: format!("Failed to get change script as new destination script, {:?}", err),
2310+ })?;
2311+ let _res = add_funding_change_output(
2312+ change_value, change_script, &mut funding_outputs, self.dual_funding_context.funding_feerate_sat_per_1000_weight);
2313+ }
2314+
2315+ let constructor_args = InteractiveTxConstructorArgs {
2316+ entropy_source,
2317+ holder_node_id,
2318+ counterparty_node_id: self.context.counterparty_node_id,
2319+ channel_id: self.context.channel_id(),
2320+ feerate_sat_per_kw: self.dual_funding_context.funding_feerate_sat_per_1000_weight,
2321+ is_initiator: self.funding.is_outbound(),
2322+ funding_tx_locktime: self.dual_funding_context.funding_tx_locktime,
2323+ inputs_to_contribute: funding_inputs_with_extra,
2324+ outputs_to_contribute: funding_outputs,
2325+ expected_remote_shared_funding_output,
2326+ };
2327+ let mut tx_constructor = InteractiveTxConstructor::new(constructor_args)
2328+ .map_err(|_| APIError::APIMisuseError { err: "Incorrect shared output provided".into() })?;
2329+ let msg = tx_constructor.take_initiator_first_message();
2330+
2331+ self.interactive_tx_constructor.replace(tx_constructor);
2332+
2333+ Ok(msg)
2334+ }
2335+
22432336 pub fn tx_add_input(&mut self, msg: &msgs::TxAddInput) -> InteractiveTxMessageSendResult {
22442337 InteractiveTxMessageSendResult(match &mut self.interactive_tx_constructor {
22452338 Some(ref mut tx_constructor) => tx_constructor.handle_tx_add_input(msg).map_err(
@@ -4774,10 +4867,29 @@ pub(super) fn check_v2_funding_inputs_sufficient(
47744867 }
47754868}
47764869
4870+ #[allow(dead_code)] // TODO(dual_funding): Remove once begin_interactive_funding_tx_construction() is used
4871+ fn add_funding_change_output(
4872+ change_value: u64, change_script: ScriptBuf,
4873+ funding_outputs: &mut Vec<OutputOwned>, funding_feerate_sat_per_1000_weight: u32,
4874+ ) -> TxOut {
4875+ let mut change_output = TxOut {
4876+ value: Amount::from_sat(change_value),
4877+ script_pubkey: change_script,
4878+ };
4879+ let change_output_weight = get_output_weight(&change_output.script_pubkey).to_wu();
4880+ let change_output_fee = fee_for_weight(funding_feerate_sat_per_1000_weight, change_output_weight);
4881+ change_output.value = Amount::from_sat(change_value.saturating_sub(change_output_fee));
4882+ funding_outputs.push(OutputOwned::Single(change_output.clone()));
4883+ change_output
4884+ }
4885+
47774886/// Context for dual-funded channels.
47784887pub(super) struct DualFundingChannelContext {
47794888 /// The amount in satoshis we will be contributing to the channel.
47804889 pub our_funding_satoshis: u64,
4890+ /// The amount in satoshis our counterparty will be contributing to the channel.
4891+ #[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
4892+ pub their_funding_satoshis: Option<u64>,
47814893 /// The funding transaction locktime suggested by the initiator. If set by us, it is always set
47824894 /// to the current block height to align incentives against fee-sniping.
47834895 pub funding_tx_locktime: LockTime,
@@ -4790,7 +4902,7 @@ pub(super) struct DualFundingChannelContext {
47904902 /// minus any fees paid for our contributed weight. This means that change will never be generated
47914903 /// and the maximum value possible will go towards funding the channel.
47924904 #[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
4793- pub our_funding_inputs: Vec<(TxIn, TransactionU16LenLimited)>,
4905+ pub our_funding_inputs: Option< Vec<(TxIn, TransactionU16LenLimited)> >,
47944906}
47954907
47964908// Holder designates channel data owned for the benefit of the user client.
@@ -9876,9 +9988,10 @@ impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
98769988 unfunded_context,
98779989 dual_funding_context: DualFundingChannelContext {
98789990 our_funding_satoshis: funding_satoshis,
9991+ their_funding_satoshis: None,
98799992 funding_tx_locktime,
98809993 funding_feerate_sat_per_1000_weight,
9881- our_funding_inputs: funding_inputs,
9994+ our_funding_inputs: Some( funding_inputs) ,
98829995 },
98839996 interactive_tx_constructor: None,
98849997 interactive_tx_signing_session: None,
@@ -10021,9 +10134,10 @@ impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
1002110134
1002210135 let dual_funding_context = DualFundingChannelContext {
1002310136 our_funding_satoshis: our_funding_satoshis,
10137+ their_funding_satoshis: Some(msg.common_fields.funding_satoshis),
1002410138 funding_tx_locktime: LockTime::from_consensus(msg.locktime),
1002510139 funding_feerate_sat_per_1000_weight: msg.funding_feerate_sat_per_1000_weight,
10026- our_funding_inputs: our_funding_inputs.clone(),
10140+ our_funding_inputs: Some( our_funding_inputs.clone() ),
1002710141 };
1002810142
1002910143 let interactive_tx_constructor = Some(InteractiveTxConstructor::new(
0 commit comments