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, calculate_change_output_value, 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};
@@ -2158,6 +2158,107 @@ impl<SP: Deref> InitialRemoteCommitmentReceiver<SP> for FundedChannel<SP> where
21582158}
21592159
21602160impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
2161+ /// Prepare and start interactive transaction negotiation.
2162+ /// `change_destination_opt` - Optional destination for optional change; if None, default destination address is used.
2163+ #[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled
2164+ fn begin_interactive_funding_tx_construction<ES: Deref>(
2165+ &mut self, signer_provider: &SP, entropy_source: &ES, holder_node_id: PublicKey,
2166+ change_destination_opt: Option<ScriptBuf>,
2167+ ) -> Result<Option<InteractiveTxMessageSend>, APIError>
2168+ where ES::Target: EntropySource
2169+ {
2170+ let mut funding_inputs = Vec::new();
2171+ mem::swap(&mut self.dual_funding_context.our_funding_inputs, &mut funding_inputs);
2172+
2173+ let funding_inputs_prev_outputs = DualFundingChannelContext::txouts_from_input_prev_txs(&funding_inputs)
2174+ .map_err(|err| APIError::APIMisuseError { err: err.to_string() })?;
2175+
2176+ let total_input_satoshis: u64 = funding_inputs_prev_outputs.iter().map(|txout| txout.value.to_sat()).sum();
2177+ if total_input_satoshis < self.dual_funding_context.our_funding_satoshis {
2178+ return Err(APIError::APIMisuseError {
2179+ err: format!("Total value of funding inputs must be at least funding amount. It was {} sats",
2180+ total_input_satoshis) });
2181+ }
2182+
2183+ // Add output for funding tx
2184+ let mut funding_outputs = Vec::new();
2185+ let funding_output_value_satoshis = self.funding.get_value_satoshis();
2186+ let funding_output_script_pubkey = self.context.get_funding_redeemscript().to_p2wsh();
2187+ let expected_remote_shared_funding_output = if self.context.is_outbound() {
2188+ let tx_out = TxOut {
2189+ value: Amount::from_sat(funding_output_value_satoshis),
2190+ script_pubkey: funding_output_script_pubkey,
2191+ };
2192+ funding_outputs.push(
2193+ if self.dual_funding_context.their_funding_satoshis.unwrap_or(0) == 0 {
2194+ OutputOwned::SharedControlFullyOwned(tx_out)
2195+ } else {
2196+ OutputOwned::Shared(SharedOwnedOutput::new(
2197+ tx_out, self.dual_funding_context.our_funding_satoshis
2198+ ))
2199+ }
2200+ );
2201+ None
2202+ } else {
2203+ Some((funding_output_script_pubkey, funding_output_value_satoshis))
2204+ };
2205+
2206+ // Optionally add change output
2207+ let change_value_opt = calculate_change_output_value(
2208+ self.context.is_outbound(), self.dual_funding_context.our_funding_satoshis,
2209+ &funding_inputs_prev_outputs, &funding_outputs,
2210+ self.dual_funding_context.funding_feerate_sat_per_1000_weight,
2211+ self.context.holder_dust_limit_satoshis,
2212+ ).map_err(|err| APIError::APIMisuseError {
2213+ err: format!("Insufficient inputs, cannot cover intended contribution of {} and fees; {}",
2214+ self.dual_funding_context.our_funding_satoshis, err
2215+ ),
2216+ })?;
2217+ if let Some(change_value) = change_value_opt {
2218+ let change_script = match change_destination_opt {
2219+ Some(script) => script,
2220+ None => {
2221+ signer_provider.get_destination_script(self.context.channel_keys_id).map_err(
2222+ |err| APIError::APIMisuseError {
2223+ err: format!("Failed to get change script as new destination script, {:?}", err),
2224+ })?
2225+ }
2226+ };
2227+ let mut change_output = TxOut {
2228+ value: Amount::from_sat(change_value),
2229+ script_pubkey: change_script,
2230+ };
2231+ let change_output_weight = get_output_weight(&change_output.script_pubkey).to_wu();
2232+ let change_output_fee = fee_for_weight(self.dual_funding_context.funding_feerate_sat_per_1000_weight, change_output_weight);
2233+ let change_value_decreased_with_fee = change_value.saturating_sub(change_output_fee);
2234+ // Check dust limit again
2235+ if change_value_decreased_with_fee > self.context.holder_dust_limit_satoshis {
2236+ change_output.value = Amount::from_sat(change_value_decreased_with_fee);
2237+ funding_outputs.push(OutputOwned::Single(change_output));
2238+ }
2239+ }
2240+
2241+ let constructor_args = InteractiveTxConstructorArgs {
2242+ entropy_source,
2243+ holder_node_id,
2244+ counterparty_node_id: self.context.counterparty_node_id,
2245+ channel_id: self.context.channel_id(),
2246+ feerate_sat_per_kw: self.dual_funding_context.funding_feerate_sat_per_1000_weight,
2247+ is_initiator: self.context.is_outbound(),
2248+ funding_tx_locktime: self.dual_funding_context.funding_tx_locktime,
2249+ inputs_to_contribute: funding_inputs,
2250+ outputs_to_contribute: funding_outputs,
2251+ expected_remote_shared_funding_output,
2252+ };
2253+ let mut tx_constructor = InteractiveTxConstructor::new(constructor_args)
2254+ .map_err(|_| APIError::APIMisuseError { err: "Incorrect shared output provided".into() })?;
2255+ let msg = tx_constructor.take_initiator_first_message();
2256+
2257+ self.interactive_tx_constructor = Some(tx_constructor);
2258+
2259+ Ok(msg)
2260+ }
2261+
21612262 pub fn tx_add_input(&mut self, msg: &msgs::TxAddInput) -> InteractiveTxMessageSendResult {
21622263 InteractiveTxMessageSendResult(match &mut self.interactive_tx_constructor {
21632264 Some(ref mut tx_constructor) => tx_constructor.handle_tx_add_input(msg).map_err(
@@ -4731,10 +4832,28 @@ pub(super) fn check_v2_funding_inputs_sufficient(
47314832 }
47324833}
47334834
4835+ #[allow(dead_code)] // TODO(dual_funding): Remove once begin_interactive_funding_tx_construction() is used
4836+ fn add_funding_change_output(
4837+ change_value: u64, change_script: ScriptBuf,
4838+ funding_outputs: &mut Vec<OutputOwned>, funding_feerate_sat_per_1000_weight: u32,
4839+ ) {
4840+ let mut change_output = TxOut {
4841+ value: Amount::from_sat(change_value),
4842+ script_pubkey: change_script,
4843+ };
4844+ let change_output_weight = get_output_weight(&change_output.script_pubkey).to_wu();
4845+ let change_output_fee = fee_for_weight(funding_feerate_sat_per_1000_weight, change_output_weight);
4846+ change_output.value = Amount::from_sat(change_value.saturating_sub(change_output_fee));
4847+ funding_outputs.push(OutputOwned::Single(change_output.clone()));
4848+ }
4849+
47344850/// Context for dual-funded channels.
47354851pub(super) struct DualFundingChannelContext {
47364852 /// The amount in satoshis we will be contributing to the channel.
47374853 pub our_funding_satoshis: u64,
4854+ /// The amount in satoshis our counterparty will be contributing to the channel.
4855+ #[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
4856+ pub their_funding_satoshis: Option<u64>,
47384857 /// The funding transaction locktime suggested by the initiator. If set by us, it is always set
47394858 /// to the current block height to align incentives against fee-sniping.
47404859 pub funding_tx_locktime: LockTime,
@@ -4746,10 +4865,39 @@ pub(super) struct DualFundingChannelContext {
47464865 /// Note that the `our_funding_satoshis` field is equal to the total value of `our_funding_inputs`
47474866 /// minus any fees paid for our contributed weight. This means that change will never be generated
47484867 /// and the maximum value possible will go towards funding the channel.
4868+ ///
4869+ /// Note that this field may be emptied once the interactive negotiation has been started.
47494870 #[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
47504871 pub our_funding_inputs: Vec<(TxIn, TransactionU16LenLimited)>,
47514872}
47524873
4874+ impl DualFundingChannelContext {
4875+ /// Obtain prev outputs for each supplied input and matching transaction.
4876+ /// Can error when there a prev tx does not have an output for the specified vout number.
4877+ /// Also checks for matching of transaction IDs.
4878+ fn txouts_from_input_prev_txs(inputs: &Vec<(TxIn, TransactionU16LenLimited)>) -> Result<Vec<&TxOut>, ChannelError> {
4879+ let mut prev_outputs: Vec<&TxOut> = Vec::with_capacity(inputs.len());
4880+ // Check that vouts exist for each TxIn in provided transactions.
4881+ for (idx, (txin, tx)) in inputs.iter().enumerate() {
4882+ let txid = tx.as_transaction().compute_txid();
4883+ if txin.previous_output.txid != txid {
4884+ return Err(ChannelError::Warn(
4885+ format!("Transaction input txid mismatch, {} vs. {}, at index {}", txin.previous_output.txid, txid, idx)
4886+ ));
4887+ }
4888+ if let Some(output) = tx.as_transaction().output.get(txin.previous_output.vout as usize) {
4889+ prev_outputs.push(output);
4890+ } else {
4891+ return Err(ChannelError::Warn(
4892+ format!("Transaction with txid {} does not have an output with vout of {} corresponding to TxIn, at index {}",
4893+ txid, txin.previous_output.vout, idx)
4894+ ));
4895+ }
4896+ }
4897+ Ok(prev_outputs)
4898+ }
4899+ }
4900+
47534901// Holder designates channel data owned for the benefit of the user client.
47544902// Counterparty designates channel data owned by the another channel participant entity.
47554903pub(super) struct FundedChannel<SP: Deref> where SP::Target: SignerProvider {
@@ -9816,16 +9964,18 @@ impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
98169964 unfunded_channel_age_ticks: 0,
98179965 holder_commitment_point: HolderCommitmentPoint::new(&context.holder_signer, &context.secp_ctx),
98189966 };
9967+ let dual_funding_context = DualFundingChannelContext {
9968+ our_funding_satoshis: funding_satoshis,
9969+ their_funding_satoshis: None,
9970+ funding_tx_locktime,
9971+ funding_feerate_sat_per_1000_weight,
9972+ our_funding_inputs: funding_inputs,
9973+ };
98199974 let chan = Self {
98209975 funding,
98219976 context,
98229977 unfunded_context,
9823- dual_funding_context: DualFundingChannelContext {
9824- our_funding_satoshis: funding_satoshis,
9825- funding_tx_locktime,
9826- funding_feerate_sat_per_1000_weight,
9827- our_funding_inputs: funding_inputs,
9828- },
9978+ dual_funding_context,
98299979 interactive_tx_constructor: None,
98309980 };
98319981 Ok(chan)
@@ -9968,6 +10118,7 @@ impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
996810118
996910119 let dual_funding_context = DualFundingChannelContext {
997010120 our_funding_satoshis: our_funding_satoshis,
10121+ their_funding_satoshis: Some(msg.common_fields.funding_satoshis),
997110122 funding_tx_locktime: LockTime::from_consensus(msg.locktime),
997210123 funding_feerate_sat_per_1000_weight: msg.funding_feerate_sat_per_1000_weight,
997310124 our_funding_inputs: our_funding_inputs.clone(),
0 commit comments