@@ -24,9 +24,9 @@ use bitcoin::hashes::Hash;
2424use bitcoin::secp256k1::constants::PUBLIC_KEY_SIZE;
2525use bitcoin::secp256k1::{ecdsa::Signature, Secp256k1};
2626use bitcoin::secp256k1::{PublicKey, SecretKey};
27- #[cfg(splicing)]
28- use bitcoin::Sequence;
2927use bitcoin::{secp256k1, sighash, TxIn};
28+ #[cfg(splicing)]
29+ use bitcoin::{FeeRate, Sequence};
3030
3131use crate::chain::chaininterface::{
3232 fee_for_weight, ConfirmationTarget, FeeEstimator, LowerBoundedFeeEstimator,
@@ -5878,20 +5878,53 @@ fn get_v2_channel_reserve_satoshis(channel_value_satoshis: u64, dust_limit_satos
58785878 cmp::min(channel_value_satoshis, cmp::max(q, dust_limit_satoshis))
58795879}
58805880
5881+ #[cfg(splicing)]
5882+ fn check_splice_contribution_sufficient(
5883+ channel_balance: Amount, contribution: &SpliceContribution, is_initiator: bool,
5884+ funding_feerate: FeeRate,
5885+ ) -> Result<Amount, ChannelError> {
5886+ let contribution_amount = contribution.value();
5887+ if contribution_amount < SignedAmount::ZERO {
5888+ let estimated_fee = Amount::from_sat(estimate_v2_funding_transaction_fee(
5889+ is_initiator,
5890+ 1, // spends the previous funding output
5891+ Weight::from_wu(FUNDING_TRANSACTION_WITNESS_WEIGHT),
5892+ contribution.outputs(),
5893+ funding_feerate.to_sat_per_kwu() as u32,
5894+ ));
5895+
5896+ if channel_balance > contribution_amount.unsigned_abs() + estimated_fee {
5897+ Ok(estimated_fee)
5898+ } else {
5899+ Err(ChannelError::Warn(format!(
5900+ "Available channel balance {} is lower than needed for splicing out {}, considering fees of {}",
5901+ channel_balance, contribution_amount.unsigned_abs(), estimated_fee,
5902+ )))
5903+ }
5904+ } else {
5905+ check_v2_funding_inputs_sufficient(
5906+ contribution_amount.to_sat(),
5907+ contribution.inputs(),
5908+ is_initiator,
5909+ true,
5910+ funding_feerate.to_sat_per_kwu() as u32,
5911+ )
5912+ .map(Amount::from_sat)
5913+ }
5914+ }
5915+
58815916/// Estimate our part of the fee of the new funding transaction.
58825917/// input_count: Number of contributed inputs.
58835918/// witness_weight: The witness weight for contributed inputs.
58845919#[allow(dead_code)] // TODO(dual_funding): TODO(splicing): Remove allow once used.
58855920#[rustfmt::skip]
58865921fn estimate_v2_funding_transaction_fee(
5887- is_initiator: bool, input_count: usize, witness_weight: Weight,
5922+ is_initiator: bool, input_count: usize, witness_weight: Weight, outputs: &[TxOut],
58885923 funding_feerate_sat_per_1000_weight: u32,
58895924) -> u64 {
5890- // Inputs
58915925 let mut weight = (input_count as u64) * BASE_INPUT_WEIGHT;
5892-
5893- // Witnesses
58945926 weight = weight.saturating_add(witness_weight.to_wu());
5927+ weight = weight.saturating_add(outputs.iter().map(|txout| txout.weight().to_wu()).sum());
58955928
58965929 // If we are the initiator, we must pay for weight of all common fields in the funding transaction.
58975930 if is_initiator {
@@ -5929,7 +5962,7 @@ fn check_v2_funding_inputs_sufficient(
59295962 funding_inputs_len += 1;
59305963 total_input_witness_weight += Weight::from_wu(FUNDING_TRANSACTION_WITNESS_WEIGHT);
59315964 }
5932- let estimated_fee = estimate_v2_funding_transaction_fee(is_initiator, funding_inputs_len, total_input_witness_weight, funding_feerate_sat_per_1000_weight);
5965+ let estimated_fee = estimate_v2_funding_transaction_fee(is_initiator, funding_inputs_len, total_input_witness_weight, &[], funding_feerate_sat_per_1000_weight);
59335966
59345967 let mut total_input_sats = 0u64;
59355968 for FundingTxInput { utxo, .. } in funding_inputs.iter() {
@@ -5976,6 +6009,9 @@ pub(super) struct FundingNegotiationContext {
59766009 /// The funding inputs we will be contributing to the channel.
59776010 #[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
59786011 pub our_funding_inputs: Vec<FundingTxInput>,
6012+ /// The funding outputs we will be contributing to the channel.
6013+ #[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
6014+ pub our_funding_outputs: Vec<TxOut>,
59796015 /// The change output script. This will be used if needed or -- if not set -- generated using
59806016 /// `SignerProvider::get_destination_script`.
59816017 #[allow(dead_code)] // TODO(splicing): Remove once splicing is enabled.
@@ -6005,45 +6041,46 @@ impl FundingNegotiationContext {
60056041 debug_assert!(matches!(context.channel_state, ChannelState::NegotiatingFunding(_)));
60066042 }
60076043
6008- // Add output for funding tx
60096044 // Note: For the error case when the inputs are insufficient, it will be handled after
60106045 // the `calculate_change_output_value` call below
6011- let mut funding_outputs = Vec::new();
60126046
60136047 let shared_funding_output = TxOut {
60146048 value: Amount::from_sat(funding.get_value_satoshis()),
60156049 script_pubkey: funding.get_funding_redeemscript().to_p2wsh(),
60166050 };
60176051
60186052 // Optionally add change output
6019- if self.our_funding_contribution > SignedAmount::ZERO {
6020- let change_value_opt = calculate_change_output_value(
6053+ let change_value_opt = if self.our_funding_contribution > SignedAmount::ZERO {
6054+ calculate_change_output_value(
60216055 &self,
60226056 self.shared_funding_input.is_some(),
60236057 &shared_funding_output.script_pubkey,
6024- &funding_outputs,
60256058 context.holder_dust_limit_satoshis,
6026- )?;
6027- if let Some(change_value) = change_value_opt {
6028- let change_script = if let Some(script) = self.change_script {
6029- script
6030- } else {
6031- signer_provider
6032- .get_destination_script(context.channel_keys_id)
6033- .map_err(|_err| AbortReason::InternalError("Error getting change script"))?
6034- };
6035- let mut change_output =
6036- TxOut { value: Amount::from_sat(change_value), script_pubkey: change_script };
6037- let change_output_weight = get_output_weight(&change_output.script_pubkey).to_wu();
6038- let change_output_fee =
6039- fee_for_weight(self.funding_feerate_sat_per_1000_weight, change_output_weight);
6040- let change_value_decreased_with_fee =
6041- change_value.saturating_sub(change_output_fee);
6042- // Check dust limit again
6043- if change_value_decreased_with_fee > context.holder_dust_limit_satoshis {
6044- change_output.value = Amount::from_sat(change_value_decreased_with_fee);
6045- funding_outputs.push(change_output);
6046- }
6059+ )?
6060+ } else {
6061+ None
6062+ };
6063+
6064+ let mut funding_outputs = self.our_funding_outputs;
6065+
6066+ if let Some(change_value) = change_value_opt {
6067+ let change_script = if let Some(script) = self.change_script {
6068+ script
6069+ } else {
6070+ signer_provider
6071+ .get_destination_script(context.channel_keys_id)
6072+ .map_err(|_err| AbortReason::InternalError("Error getting change script"))?
6073+ };
6074+ let mut change_output =
6075+ TxOut { value: Amount::from_sat(change_value), script_pubkey: change_script };
6076+ let change_output_weight = get_output_weight(&change_output.script_pubkey).to_wu();
6077+ let change_output_fee =
6078+ fee_for_weight(self.funding_feerate_sat_per_1000_weight, change_output_weight);
6079+ let change_value_decreased_with_fee = change_value.saturating_sub(change_output_fee);
6080+ // Check dust limit again
6081+ if change_value_decreased_with_fee > context.holder_dust_limit_satoshis {
6082+ change_output.value = Amount::from_sat(change_value_decreased_with_fee);
6083+ funding_outputs.push(change_output);
60476084 }
60486085 }
60496086
@@ -10634,44 +10671,66 @@ where
1063410671 if our_funding_contribution > SignedAmount::MAX_MONEY {
1063510672 return Err(APIError::APIMisuseError {
1063610673 err: format!(
10637- "Channel {} cannot be spliced; contribution exceeds total bitcoin supply: {}",
10674+ "Channel {} cannot be spliced in ; contribution exceeds total bitcoin supply: {}",
1063810675 self.context.channel_id(),
1063910676 our_funding_contribution,
1064010677 ),
1064110678 });
1064210679 }
1064310680
10644- if our_funding_contribution < SignedAmount::ZERO {
10681+ if our_funding_contribution < - SignedAmount::MAX_MONEY {
1064510682 return Err(APIError::APIMisuseError {
1064610683 err: format!(
10647- "TODO(splicing): Splice-out not supported, only splice in; channel ID {}, contribution {}",
10648- self.context.channel_id(), our_funding_contribution,
10649- ),
10684+ "Channel {} cannot be spliced out; contribution exhausts total bitcoin supply: {}",
10685+ self.context.channel_id(),
10686+ our_funding_contribution,
10687+ ),
1065010688 });
1065110689 }
1065210690
10653- // TODO(splicing): Once splice-out is supported, check that channel balance does not go below 0
10654- // (or below channel reserve)
10655-
1065610691 // Note: post-splice channel value is not yet known at this point, counterparty contribution is not known
1065710692 // (Cannot test for miminum required post-splice channel value)
1065810693
10659- // Check that inputs are sufficient to cover our contribution.
10660- let _fee = check_v2_funding_inputs_sufficient(
10661- our_funding_contribution.to_sat(),
10662- contribution.inputs(),
10663- true,
10664- true,
10665- funding_feerate_per_kw,
10694+ let channel_balance = Amount::from_sat(self.funding.get_value_to_self_msat() / 1000);
10695+ let fees = check_splice_contribution_sufficient(
10696+ channel_balance,
10697+ &contribution,
10698+ true, // is_initiator
10699+ FeeRate::from_sat_per_kwu(funding_feerate_per_kw as u64),
1066610700 )
10667- .map_err(|err| APIError::APIMisuseError {
10668- err: format!(
10669- "Insufficient inputs for splicing; channel ID {}, err {}",
10670- self.context.channel_id(),
10671- err,
10672- ),
10701+ .map_err(|e| {
10702+ let splice_type = if our_funding_contribution < SignedAmount::ZERO {
10703+ "spliced out"
10704+ } else {
10705+ "spliced in"
10706+ };
10707+ APIError::APIMisuseError {
10708+ err: format!(
10709+ "Channel {} cannot be {}; {}",
10710+ self.context.channel_id(),
10711+ splice_type,
10712+ e,
10713+ ),
10714+ }
1067310715 })?;
1067410716
10717+ // Fees for splice-out are paid from the channel balance whereas fees for splice-in are paid
10718+ // by the funding inputs.
10719+ let adjusted_funding_contribution = if our_funding_contribution < SignedAmount::ZERO {
10720+ let adjusted_funding_contribution = our_funding_contribution
10721+ - fees.to_signed().expect("fees should never exceed splice-out value");
10722+
10723+ // TODO(splicing): Check that channel balance does not go below the channel reserve
10724+ let _post_channel_balance = AddSigned::checked_add_signed(
10725+ channel_balance.to_sat(),
10726+ adjusted_funding_contribution.to_sat(),
10727+ );
10728+
10729+ adjusted_funding_contribution
10730+ } else {
10731+ our_funding_contribution
10732+ };
10733+
1067510734 for FundingTxInput { utxo, prevtx, .. } in contribution.inputs().iter() {
1067610735 const MESSAGE_TEMPLATE: msgs::TxAddInput = msgs::TxAddInput {
1067710736 channel_id: ChannelId([0; 32]),
@@ -10693,14 +10752,15 @@ where
1069310752 }
1069410753
1069510754 let prev_funding_input = self.funding.to_splice_funding_input();
10696- let (our_funding_inputs, change_script) = contribution.into_tx_parts();
10755+ let (our_funding_inputs, our_funding_outputs, change_script) = contribution.into_tx_parts();
1069710756 let funding_negotiation_context = FundingNegotiationContext {
1069810757 is_initiator: true,
10699- our_funding_contribution,
10758+ our_funding_contribution: adjusted_funding_contribution ,
1070010759 funding_tx_locktime: LockTime::from_consensus(locktime),
1070110760 funding_feerate_sat_per_1000_weight: funding_feerate_per_kw,
1070210761 shared_funding_input: Some(prev_funding_input),
1070310762 our_funding_inputs,
10763+ our_funding_outputs,
1070410764 change_script,
1070510765 };
1070610766
@@ -10716,7 +10776,7 @@ where
1071610776
1071710777 Ok(msgs::SpliceInit {
1071810778 channel_id: self.context.channel_id,
10719- funding_contribution_satoshis: our_funding_contribution .to_sat(),
10779+ funding_contribution_satoshis: adjusted_funding_contribution .to_sat(),
1072010780 funding_feerate_per_kw,
1072110781 locktime,
1072210782 funding_pubkey,
@@ -10825,6 +10885,7 @@ where
1082510885 funding_feerate_sat_per_1000_weight: msg.funding_feerate_per_kw,
1082610886 shared_funding_input: Some(prev_funding_input),
1082710887 our_funding_inputs: Vec::new(),
10888+ our_funding_outputs: Vec::new(),
1082810889 change_script: None,
1082910890 };
1083010891
@@ -12523,6 +12584,7 @@ where
1252312584 funding_feerate_sat_per_1000_weight,
1252412585 shared_funding_input: None,
1252512586 our_funding_inputs: funding_inputs,
12587+ our_funding_outputs: Vec::new(),
1252612588 change_script: None,
1252712589 };
1252812590 let chan = Self {
@@ -12677,6 +12739,7 @@ where
1267712739 funding_feerate_sat_per_1000_weight: msg.funding_feerate_sat_per_1000_weight,
1267812740 shared_funding_input: None,
1267912741 our_funding_inputs: our_funding_inputs.clone(),
12742+ our_funding_outputs: Vec::new(),
1268012743 change_script: None,
1268112744 };
1268212745 let shared_funding_output = TxOut {
@@ -12702,7 +12765,7 @@ where
1270212765 inputs_to_contribute,
1270312766 shared_funding_input: None,
1270412767 shared_funding_output: SharedOwnedOutput::new(shared_funding_output, our_funding_contribution_sats),
12705- outputs_to_contribute: Vec::new (),
12768+ outputs_to_contribute: funding_negotiation_context.our_funding_outputs.clone (),
1270612769 }
1270712770 ).map_err(|err| {
1270812771 let reason = ClosureReason::ProcessingError { err: err.to_string() };
@@ -15871,31 +15934,31 @@ mod tests {
1587115934
1587215935 // 2 inputs with weight 300, initiator, 2000 sat/kw feerate
1587315936 assert_eq!(
15874- estimate_v2_funding_transaction_fee(true, 2, Weight::from_wu(300), 2000),
15937+ estimate_v2_funding_transaction_fee(true, 2, Weight::from_wu(300), &[], 2000),
1587515938 1668
1587615939 );
1587715940
1587815941 // higher feerate
1587915942 assert_eq!(
15880- estimate_v2_funding_transaction_fee(true, 2, Weight::from_wu(300), 3000),
15943+ estimate_v2_funding_transaction_fee(true, 2, Weight::from_wu(300), &[], 3000),
1588115944 2502
1588215945 );
1588315946
1588415947 // only 1 input
1588515948 assert_eq!(
15886- estimate_v2_funding_transaction_fee(true, 1, Weight::from_wu(300), 2000),
15949+ estimate_v2_funding_transaction_fee(true, 1, Weight::from_wu(300), &[], 2000),
1588715950 1348
1588815951 );
1588915952
1589015953 // 0 input weight
1589115954 assert_eq!(
15892- estimate_v2_funding_transaction_fee(true, 1, Weight::from_wu(0), 2000),
15955+ estimate_v2_funding_transaction_fee(true, 1, Weight::from_wu(0), &[], 2000),
1589315956 748
1589415957 );
1589515958
1589615959 // not initiator
1589715960 assert_eq!(
15898- estimate_v2_funding_transaction_fee(false, 1, Weight::from_wu(0), 2000),
15961+ estimate_v2_funding_transaction_fee(false, 1, Weight::from_wu(0), &[], 2000),
1589915962 320
1590015963 );
1590115964 }
0 commit comments