@@ -31,7 +31,7 @@ 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, need_to_add_funding_change_output , HandleTxCompleteValue, HandleTxCompleteResult, InteractiveTxConstructor,
34+ get_output_weight, calculate_change_output_value , HandleTxCompleteValue, HandleTxCompleteResult, InteractiveTxConstructor,
3535 InteractiveTxConstructorArgs, InteractiveTxMessageSend, InteractiveTxSigningSession, InteractiveTxMessageSendResult,
3636 OutputOwned, SharedOwnedOutput, TX_COMMON_FIELDS_WEIGHT,
3737};
@@ -2213,34 +2213,22 @@ impl<SP: Deref> InitialRemoteCommitmentReceiver<SP> for FundedChannel<SP> where
22132213}
22142214
22152215impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
2216+ /// Prepare and start interactive transaction negotiation.
2217+ /// `change_destination_opt` - Optional destination for optional change; if None, default destination address is used.
22162218 #[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled
22172219 fn begin_interactive_funding_tx_construction<ES: Deref>(
22182220 &mut self, signer_provider: &SP, entropy_source: &ES, holder_node_id: PublicKey,
2219- extra_input : Option<(TxIn, TransactionU16LenLimited) >,
2221+ change_destination_opt : Option<ScriptBuf >,
22202222 ) -> Result<Option<InteractiveTxMessageSend>, APIError>
22212223 where ES::Target: EntropySource
22222224 {
2223- let mut funding_inputs_with_extra = self.dual_funding_context.our_funding_inputs.take().unwrap_or_else(|| vec![]);
2225+ let mut funding_inputs = Vec::new();
2226+ mem::swap(&mut self.dual_funding_context.our_funding_inputs, &mut funding_inputs);
22242227
2225- if let Some(extra_input) = extra_input {
2226- funding_inputs_with_extra.push(extra_input);
2227- }
2228-
2229- let mut funding_inputs_prev_outputs: Vec<TxOut> = Vec::with_capacity(funding_inputs_with_extra.len());
2230- // Check that vouts exist for each TxIn in provided transactions.
2231- for (idx, input) in funding_inputs_with_extra.iter().enumerate() {
2232- if let Some(output) = input.1.as_transaction().output.get(input.0.previous_output.vout as usize) {
2233- funding_inputs_prev_outputs.push(output.clone());
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_with_extra[{}]",
2237- input.1.as_transaction().compute_txid(), input.0.previous_output.vout, idx) });
2238- }
2239- }
2228+ let funding_inputs_prev_outputs = DualFundingChannelContext::txouts_from_input_prev_txs(&funding_inputs)
2229+ .map_err(|err| APIError::APIMisuseError { err: err.to_string() })?;
22402230
2241- let total_input_satoshis: u64 = funding_inputs_with_extra.iter().map(
2242- |input| input.1.as_transaction().output.get(input.0.previous_output.vout as usize).map(|out| out.value.to_sat()).unwrap_or(0)
2243- ).sum();
2231+ let total_input_satoshis: u64 = funding_inputs_prev_outputs.iter().map(|txout| txout.value.to_sat()).sum();
22442232 if total_input_satoshis < self.dual_funding_context.our_funding_satoshis {
22452233 return Err(APIError::APIMisuseError {
22462234 err: format!("Total value of funding inputs must be at least funding amount. It was {} sats",
@@ -2271,18 +2259,38 @@ impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
22712259 };
22722260
22732261 // Optionally add change output
2274- if let Some(change_value) = need_to_add_funding_change_output (
2262+ let change_value_opt = calculate_change_output_value (
22752263 self.funding.is_outbound(), self.dual_funding_context.our_funding_satoshis,
22762264 &funding_inputs_prev_outputs, &funding_outputs,
22772265 self.dual_funding_context.funding_feerate_sat_per_1000_weight,
22782266 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 _res = add_funding_change_output(
2285- change_value, change_script, &mut funding_outputs, self.dual_funding_context.funding_feerate_sat_per_1000_weight);
2267+ ).map_err(|err| APIError::APIMisuseError {
2268+ err: format!("Insufficient inputs, cannot cover intended contribution of {} and fees; {}",
2269+ self.dual_funding_context.our_funding_satoshis, err
2270+ ),
2271+ })?;
2272+ if let Some(change_value) = change_value_opt {
2273+ let change_script = match change_destination_opt {
2274+ Some(script) => script,
2275+ None => {
2276+ signer_provider.get_destination_script(self.context.channel_keys_id).map_err(
2277+ |err| APIError::APIMisuseError {
2278+ err: format!("Failed to get change script as new destination script, {:?}", err),
2279+ })?
2280+ }
2281+ };
2282+ let mut change_output = TxOut {
2283+ value: Amount::from_sat(change_value),
2284+ script_pubkey: change_script,
2285+ };
2286+ let change_output_weight = get_output_weight(&change_output.script_pubkey).to_wu();
2287+ let change_output_fee = fee_for_weight(self.dual_funding_context.funding_feerate_sat_per_1000_weight, change_output_weight);
2288+ let change_value_decreased_with_fee = change_value.saturating_sub(change_output_fee);
2289+ // Check dust limit again
2290+ if change_value_decreased_with_fee > self.context.holder_dust_limit_satoshis {
2291+ change_output.value = Amount::from_sat(change_value_decreased_with_fee);
2292+ funding_outputs.push(OutputOwned::Single(change_output));
2293+ }
22862294 }
22872295
22882296 let constructor_args = InteractiveTxConstructorArgs {
@@ -2293,15 +2301,15 @@ impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
22932301 feerate_sat_per_kw: self.dual_funding_context.funding_feerate_sat_per_1000_weight,
22942302 is_initiator: self.funding.is_outbound(),
22952303 funding_tx_locktime: self.dual_funding_context.funding_tx_locktime,
2296- inputs_to_contribute: funding_inputs_with_extra ,
2304+ inputs_to_contribute: funding_inputs ,
22972305 outputs_to_contribute: funding_outputs,
22982306 expected_remote_shared_funding_output,
22992307 };
23002308 let mut tx_constructor = InteractiveTxConstructor::new(constructor_args)
23012309 .map_err(|_| APIError::APIMisuseError { err: "Incorrect shared output provided".into() })?;
23022310 let msg = tx_constructor.take_initiator_first_message();
23032311
2304- self.interactive_tx_constructor.replace (tx_constructor);
2312+ self.interactive_tx_constructor = Some (tx_constructor);
23052313
23062314 Ok(msg)
23072315 }
@@ -4764,7 +4772,7 @@ fn estimate_v2_funding_transaction_fee(
47644772fn add_funding_change_output(
47654773 change_value: u64, change_script: ScriptBuf,
47664774 funding_outputs: &mut Vec<OutputOwned>, funding_feerate_sat_per_1000_weight: u32,
4767- ) -> TxOut {
4775+ ) {
47684776 let mut change_output = TxOut {
47694777 value: Amount::from_sat(change_value),
47704778 script_pubkey: change_script,
@@ -4773,7 +4781,6 @@ fn add_funding_change_output(
47734781 let change_output_fee = fee_for_weight(funding_feerate_sat_per_1000_weight, change_output_weight);
47744782 change_output.value = Amount::from_sat(change_value.saturating_sub(change_output_fee));
47754783 funding_outputs.push(OutputOwned::Single(change_output.clone()));
4776- change_output
47774784}
47784785
47794786/// Context for dual-funded channels.
@@ -4794,8 +4801,37 @@ pub(super) struct DualFundingChannelContext {
47944801 /// Note that the `our_funding_satoshis` field is equal to the total value of `our_funding_inputs`
47954802 /// minus any fees paid for our contributed weight. This means that change will never be generated
47964803 /// and the maximum value possible will go towards funding the channel.
4804+ ///
4805+ /// Note that this field may be emptied once the interactive negotiation has been started.
47974806 #[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
4798- pub our_funding_inputs: Option<Vec<(TxIn, TransactionU16LenLimited)>>,
4807+ pub our_funding_inputs: Vec<(TxIn, TransactionU16LenLimited)>,
4808+ }
4809+
4810+ impl DualFundingChannelContext {
4811+ /// Obtain prev outputs for each supplied input and matching transaction.
4812+ /// Will error when a prev tx does not have an output for the specified vout.
4813+ /// Also checks for matching of transaction IDs.
4814+ fn txouts_from_input_prev_txs(inputs: &Vec<(TxIn, TransactionU16LenLimited)>) -> Result<Vec<&TxOut>, ChannelError> {
4815+ let mut prev_outputs: Vec<&TxOut> = Vec::with_capacity(inputs.len());
4816+ // Check that vouts exist for each TxIn in provided transactions.
4817+ for (idx, (txin, tx)) in inputs.iter().enumerate() {
4818+ let txid = tx.as_transaction().compute_txid();
4819+ if txin.previous_output.txid != txid {
4820+ return Err(ChannelError::Warn(
4821+ format!("Transaction input txid mismatch, {} vs. {}, at index {}", txin.previous_output.txid, txid, idx)
4822+ ));
4823+ }
4824+ if let Some(output) = tx.as_transaction().output.get(txin.previous_output.vout as usize) {
4825+ prev_outputs.push(output);
4826+ } else {
4827+ return Err(ChannelError::Warn(
4828+ format!("Transaction with txid {} does not have an output with vout of {} corresponding to TxIn, at index {}",
4829+ txid, txin.previous_output.vout, idx)
4830+ ));
4831+ }
4832+ }
4833+ Ok(prev_outputs)
4834+ }
47994835}
48004836
48014837// Holder designates channel data owned for the benefit of the user client.
@@ -9714,17 +9750,18 @@ impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
97149750 unfunded_channel_age_ticks: 0,
97159751 holder_commitment_point: HolderCommitmentPoint::new(&context.holder_signer, &context.secp_ctx),
97169752 };
9753+ let dual_funding_context = DualFundingChannelContext {
9754+ our_funding_satoshis: funding_satoshis,
9755+ their_funding_satoshis: None,
9756+ funding_tx_locktime,
9757+ funding_feerate_sat_per_1000_weight,
9758+ our_funding_inputs: funding_inputs,
9759+ };
97179760 let chan = Self {
97189761 funding,
97199762 context,
97209763 unfunded_context,
9721- dual_funding_context: DualFundingChannelContext {
9722- our_funding_satoshis: funding_satoshis,
9723- their_funding_satoshis: None,
9724- funding_tx_locktime,
9725- funding_feerate_sat_per_1000_weight,
9726- our_funding_inputs: Some(funding_inputs),
9727- },
9764+ dual_funding_context,
97289765 interactive_tx_constructor: None,
97299766 interactive_tx_signing_session: None,
97309767 };
@@ -9869,7 +9906,7 @@ impl<SP: Deref> PendingV2Channel<SP> where SP::Target: SignerProvider {
98699906 their_funding_satoshis: Some(msg.common_fields.funding_satoshis),
98709907 funding_tx_locktime: LockTime::from_consensus(msg.locktime),
98719908 funding_feerate_sat_per_1000_weight: msg.funding_feerate_sat_per_1000_weight,
9872- our_funding_inputs: Some( our_funding_inputs.clone() ),
9909+ our_funding_inputs: our_funding_inputs.clone(),
98739910 };
98749911
98759912 let interactive_tx_constructor = Some(InteractiveTxConstructor::new(
0 commit comments