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, calculate_change_output_value, 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,106 @@ 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+ pub fn begin_interactive_funding_tx_construction<ES: Deref>(
2218+ &mut self, signer_provider: &SP, entropy_source: &ES, holder_node_id: PublicKey,
2219+ prev_funding_input: Option<(TxIn, TransactionU16LenLimited)>,
2220+ ) -> Result<Option<InteractiveTxMessageSend>, APIError>
2221+ where ES::Target: EntropySource
2222+ {
2223+ let mut funding_inputs = Vec::new();
2224+ mem::swap(&mut self.dual_funding_context.our_funding_inputs, &mut funding_inputs);
2225+
2226+ if let Some(prev_funding_input) = prev_funding_input {
2227+ funding_inputs.push(prev_funding_input);
2228+ }
2229+
2230+ let mut funding_inputs_prev_outputs: Vec<&TxOut> = Vec::with_capacity(funding_inputs.len());
2231+ // Check that vouts exist for each TxIn in provided transactions.
2232+ for (idx, (txin, tx)) in funding_inputs.iter().enumerate() {
2233+ if let Some(output) = tx.as_transaction().output.get(txin.previous_output.vout as usize) {
2234+ funding_inputs_prev_outputs.push(output);
2235+ } else {
2236+ return Err(APIError::APIMisuseError {
2237+ err: format!("Transaction with txid {} does not have an output with vout of {} corresponding to TxIn at funding_inputs[{}]",
2238+ tx.as_transaction().compute_txid(), txin.previous_output.vout, idx) });
2239+ }
2240+ }
2241+
2242+ let total_input_satoshis: u64 = funding_inputs.iter().map(
2243+ |(txin, tx)| tx.as_transaction().output.get(txin.previous_output.vout as usize).map(|out| out.value.to_sat()).unwrap_or(0)
2244+ ).sum();
2245+ if total_input_satoshis < self.dual_funding_context.our_funding_satoshis {
2246+ return Err(APIError::APIMisuseError {
2247+ err: format!("Total value of funding inputs must be at least funding amount. It was {} sats",
2248+ total_input_satoshis) });
2249+ }
2250+
2251+ // Add output for funding tx
2252+ let mut funding_outputs = Vec::new();
2253+ let funding_output_value_satoshis = self.funding.get_value_satoshis();
2254+ let funding_output_script_pubkey = self.context.get_funding_redeemscript().to_p2wsh();
2255+ let expected_remote_shared_funding_output = if self.context.is_outbound() {
2256+ let tx_out = TxOut {
2257+ value: Amount::from_sat(funding_output_value_satoshis),
2258+ script_pubkey: funding_output_script_pubkey,
2259+ };
2260+ funding_outputs.push(
2261+ if self.dual_funding_context.their_funding_satoshis.unwrap_or(0) == 0 {
2262+ OutputOwned::SharedControlFullyOwned(tx_out)
2263+ } else {
2264+ OutputOwned::Shared(SharedOwnedOutput::new(
2265+ tx_out, self.dual_funding_context.our_funding_satoshis
2266+ ))
2267+ }
2268+ );
2269+ None
2270+ } else {
2271+ Some((funding_output_script_pubkey, funding_output_value_satoshis))
2272+ };
2273+
2274+ // Optionally add change output
2275+ if let Some(change_value) = calculate_change_output_value(
2276+ self.context.is_outbound(), self.dual_funding_context.our_funding_satoshis,
2277+ &funding_inputs_prev_outputs, &funding_outputs,
2278+ self.dual_funding_context.funding_feerate_sat_per_1000_weight,
2279+ self.context.holder_dust_limit_satoshis,
2280+ ) {
2281+ let change_script = signer_provider.get_destination_script(self.context.channel_keys_id).map_err(
2282+ |err| APIError::APIMisuseError {
2283+ err: format!("Failed to get change script as new destination script, {:?}", err),
2284+ })?;
2285+ let mut change_output = TxOut {
2286+ value: Amount::from_sat(change_value),
2287+ script_pubkey: change_script,
2288+ };
2289+ let change_output_weight = get_output_weight(&change_output.script_pubkey).to_wu();
2290+ let change_output_fee = fee_for_weight(self.dual_funding_context.funding_feerate_sat_per_1000_weight, change_output_weight);
2291+ change_output.value = Amount::from_sat(change_value.saturating_sub(change_output_fee));
2292+ funding_outputs.push(OutputOwned::Single(change_output));
2293+ }
2294+
2295+ let constructor_args = InteractiveTxConstructorArgs {
2296+ entropy_source,
2297+ holder_node_id,
2298+ counterparty_node_id: self.context.counterparty_node_id,
2299+ channel_id: self.context.channel_id(),
2300+ feerate_sat_per_kw: self.dual_funding_context.funding_feerate_sat_per_1000_weight,
2301+ is_initiator: self.context.is_outbound(),
2302+ funding_tx_locktime: self.dual_funding_context.funding_tx_locktime,
2303+ inputs_to_contribute: funding_inputs,
2304+ outputs_to_contribute: funding_outputs,
2305+ expected_remote_shared_funding_output,
2306+ };
2307+ let mut tx_constructor = InteractiveTxConstructor::new(constructor_args)
2308+ .map_err(|_| APIError::APIMisuseError { err: "Incorrect shared output provided".into() })?;
2309+ let msg = tx_constructor.take_initiator_first_message();
2310+
2311+ self.interactive_tx_constructor = Some(tx_constructor);
2312+
2313+ Ok(msg)
2314+ }
2315+
22162316 pub fn tx_add_input(&mut self, msg: &msgs::TxAddInput) -> InteractiveTxMessageSendResult {
22172317 InteractiveTxMessageSendResult(match &mut self.interactive_tx_constructor {
22182318 Some(ref mut tx_constructor) => tx_constructor.handle_tx_add_input(msg).map_err(
@@ -4671,6 +4771,9 @@ fn estimate_v2_funding_transaction_fee(
46714771pub(super) struct DualFundingChannelContext {
46724772 /// The amount in satoshis we will be contributing to the channel.
46734773 pub our_funding_satoshis: u64,
4774+ /// The amount in satoshis our counterparty will be contributing to the channel.
4775+ #[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
4776+ pub their_funding_satoshis: Option<u64>,
46744777 /// The funding transaction locktime suggested by the initiator. If set by us, it is always set
46754778 /// to the current block height to align incentives against fee-sniping.
46764779 pub funding_tx_locktime: LockTime,
@@ -4682,6 +4785,8 @@ pub(super) struct DualFundingChannelContext {
46824785 /// Note that the `our_funding_satoshis` field is equal to the total value of `our_funding_inputs`
46834786 /// minus any fees paid for our contributed weight. This means that change will never be generated
46844787 /// and the maximum value possible will go towards funding the channel.
4788+ ///
4789+ /// Note that this field may be emptied once the interactive negotiation has been started.
46854790 #[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
46864791 pub our_funding_inputs: Vec<(TxIn, TransactionU16LenLimited)>,
46874792}
@@ -9608,6 +9713,7 @@ impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
96089713 unfunded_context,
96099714 dual_funding_context: DualFundingChannelContext {
96109715 our_funding_satoshis: funding_satoshis,
9716+ their_funding_satoshis: None,
96119717 funding_tx_locktime,
96129718 funding_feerate_sat_per_1000_weight,
96139719 our_funding_inputs: funding_inputs,
@@ -9753,6 +9859,7 @@ impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
97539859
97549860 let dual_funding_context = DualFundingChannelContext {
97559861 our_funding_satoshis: our_funding_satoshis,
9862+ their_funding_satoshis: Some(msg.common_fields.funding_satoshis),
97569863 funding_tx_locktime: LockTime::from_consensus(msg.locktime),
97579864 funding_feerate_sat_per_1000_weight: msg.funding_feerate_sat_per_1000_weight,
97589865 our_funding_inputs: our_funding_inputs.clone(),
0 commit comments