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