@@ -24,9 +24,9 @@ use bitcoin::hashes::Hash;
24
24
use bitcoin::secp256k1::constants::PUBLIC_KEY_SIZE;
25
25
use bitcoin::secp256k1::{ecdsa::Signature, Secp256k1};
26
26
use bitcoin::secp256k1::{PublicKey, SecretKey};
27
- #[cfg(splicing)]
28
- use bitcoin::Sequence;
29
27
use bitcoin::{secp256k1, sighash, TxIn};
28
+ #[cfg(splicing)]
29
+ use bitcoin::{FeeRate, Sequence};
30
30
31
31
use crate::chain::chaininterface::{
32
32
fee_for_weight, ConfirmationTarget, FeeEstimator, LowerBoundedFeeEstimator,
@@ -5880,20 +5880,53 @@ fn get_v2_channel_reserve_satoshis(channel_value_satoshis: u64, dust_limit_satos
5880
5880
cmp::min(channel_value_satoshis, cmp::max(q, dust_limit_satoshis))
5881
5881
}
5882
5882
5883
+ #[cfg(splicing)]
5884
+ fn check_splice_contribution_sufficient(
5885
+ channel_balance: Amount, contribution: &SpliceContribution, is_initiator: bool,
5886
+ funding_feerate: FeeRate,
5887
+ ) -> Result<Amount, ChannelError> {
5888
+ let contribution_amount = contribution.value();
5889
+ if contribution_amount < SignedAmount::ZERO {
5890
+ let estimated_fee = Amount::from_sat(estimate_v2_funding_transaction_fee(
5891
+ is_initiator,
5892
+ 1, // spends the previous funding output
5893
+ Weight::from_wu(FUNDING_TRANSACTION_WITNESS_WEIGHT),
5894
+ contribution.outputs(),
5895
+ funding_feerate.to_sat_per_kwu() as u32,
5896
+ ));
5897
+
5898
+ if channel_balance > contribution_amount.unsigned_abs() + estimated_fee {
5899
+ Ok(estimated_fee)
5900
+ } else {
5901
+ Err(ChannelError::Warn(format!(
5902
+ "Available channel balance {} is lower than needed for splicing out {}, considering fees of {}",
5903
+ channel_balance, contribution_amount.unsigned_abs(), estimated_fee,
5904
+ )))
5905
+ }
5906
+ } else {
5907
+ check_v2_funding_inputs_sufficient(
5908
+ contribution_amount.to_sat(),
5909
+ contribution.inputs(),
5910
+ is_initiator,
5911
+ true,
5912
+ funding_feerate.to_sat_per_kwu() as u32,
5913
+ )
5914
+ .map(Amount::from_sat)
5915
+ }
5916
+ }
5917
+
5883
5918
/// Estimate our part of the fee of the new funding transaction.
5884
5919
/// input_count: Number of contributed inputs.
5885
5920
/// witness_weight: The witness weight for contributed inputs.
5886
5921
#[allow(dead_code)] // TODO(dual_funding): TODO(splicing): Remove allow once used.
5887
5922
#[rustfmt::skip]
5888
5923
fn estimate_v2_funding_transaction_fee(
5889
- is_initiator: bool, input_count: usize, witness_weight: Weight,
5924
+ is_initiator: bool, input_count: usize, witness_weight: Weight, outputs: &[TxOut],
5890
5925
funding_feerate_sat_per_1000_weight: u32,
5891
5926
) -> u64 {
5892
- // Inputs
5893
5927
let mut weight = (input_count as u64) * BASE_INPUT_WEIGHT;
5894
-
5895
- // Witnesses
5896
5928
weight = weight.saturating_add(witness_weight.to_wu());
5929
+ weight = weight.saturating_add(outputs.iter().map(|txout| txout.weight().to_wu()).sum());
5897
5930
5898
5931
// If we are the initiator, we must pay for weight of all common fields in the funding transaction.
5899
5932
if is_initiator {
@@ -5931,7 +5964,7 @@ fn check_v2_funding_inputs_sufficient(
5931
5964
funding_inputs_len += 1;
5932
5965
total_input_satisfaction_weight += Weight::from_wu(FUNDING_TRANSACTION_WITNESS_WEIGHT);
5933
5966
}
5934
- let estimated_fee = estimate_v2_funding_transaction_fee(is_initiator, funding_inputs_len, total_input_satisfaction_weight, funding_feerate_sat_per_1000_weight);
5967
+ let estimated_fee = estimate_v2_funding_transaction_fee(is_initiator, funding_inputs_len, total_input_satisfaction_weight, &[], funding_feerate_sat_per_1000_weight);
5935
5968
5936
5969
let mut total_input_sats = 0u64;
5937
5970
for FundingTxInput { utxo, .. } in funding_inputs.iter() {
@@ -5978,6 +6011,9 @@ pub(super) struct FundingNegotiationContext {
5978
6011
/// The funding inputs we will be contributing to the channel.
5979
6012
#[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
5980
6013
pub our_funding_inputs: Vec<FundingTxInput>,
6014
+ /// The funding outputs we will be contributing to the channel.
6015
+ #[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
6016
+ pub our_funding_outputs: Vec<TxOut>,
5981
6017
/// The change output script. This will be used if needed or -- if not set -- generated using
5982
6018
/// `SignerProvider::get_destination_script`.
5983
6019
#[allow(dead_code)] // TODO(splicing): Remove once splicing is enabled.
@@ -6007,45 +6043,46 @@ impl FundingNegotiationContext {
6007
6043
debug_assert!(matches!(context.channel_state, ChannelState::NegotiatingFunding(_)));
6008
6044
}
6009
6045
6010
- // Add output for funding tx
6011
6046
// Note: For the error case when the inputs are insufficient, it will be handled after
6012
6047
// the `calculate_change_output_value` call below
6013
- let mut funding_outputs = Vec::new();
6014
6048
6015
6049
let shared_funding_output = TxOut {
6016
6050
value: Amount::from_sat(funding.get_value_satoshis()),
6017
6051
script_pubkey: funding.get_funding_redeemscript().to_p2wsh(),
6018
6052
};
6019
6053
6020
6054
// Optionally add change output
6021
- if self.our_funding_contribution > SignedAmount::ZERO {
6022
- let change_value_opt = calculate_change_output_value(
6055
+ let change_value_opt = if self.our_funding_contribution > SignedAmount::ZERO {
6056
+ calculate_change_output_value(
6023
6057
&self,
6024
6058
self.shared_funding_input.is_some(),
6025
6059
&shared_funding_output.script_pubkey,
6026
- &funding_outputs,
6027
6060
context.holder_dust_limit_satoshis,
6028
- )?;
6029
- if let Some(change_value) = change_value_opt {
6030
- let change_script = if let Some(script) = self.change_script {
6031
- script
6032
- } else {
6033
- signer_provider
6034
- .get_destination_script(context.channel_keys_id)
6035
- .map_err(|_err| AbortReason::InternalError("Error getting change script"))?
6036
- };
6037
- let mut change_output =
6038
- TxOut { value: Amount::from_sat(change_value), script_pubkey: change_script };
6039
- let change_output_weight = get_output_weight(&change_output.script_pubkey).to_wu();
6040
- let change_output_fee =
6041
- fee_for_weight(self.funding_feerate_sat_per_1000_weight, change_output_weight);
6042
- let change_value_decreased_with_fee =
6043
- change_value.saturating_sub(change_output_fee);
6044
- // Check dust limit again
6045
- if change_value_decreased_with_fee > context.holder_dust_limit_satoshis {
6046
- change_output.value = Amount::from_sat(change_value_decreased_with_fee);
6047
- funding_outputs.push(change_output);
6048
- }
6061
+ )?
6062
+ } else {
6063
+ None
6064
+ };
6065
+
6066
+ let mut funding_outputs = self.our_funding_outputs;
6067
+
6068
+ if let Some(change_value) = change_value_opt {
6069
+ let change_script = if let Some(script) = self.change_script {
6070
+ script
6071
+ } else {
6072
+ signer_provider
6073
+ .get_destination_script(context.channel_keys_id)
6074
+ .map_err(|_err| AbortReason::InternalError("Error getting change script"))?
6075
+ };
6076
+ let mut change_output =
6077
+ TxOut { value: Amount::from_sat(change_value), script_pubkey: change_script };
6078
+ let change_output_weight = get_output_weight(&change_output.script_pubkey).to_wu();
6079
+ let change_output_fee =
6080
+ fee_for_weight(self.funding_feerate_sat_per_1000_weight, change_output_weight);
6081
+ let change_value_decreased_with_fee = change_value.saturating_sub(change_output_fee);
6082
+ // Check dust limit again
6083
+ if change_value_decreased_with_fee > context.holder_dust_limit_satoshis {
6084
+ change_output.value = Amount::from_sat(change_value_decreased_with_fee);
6085
+ funding_outputs.push(change_output);
6049
6086
}
6050
6087
}
6051
6088
@@ -10636,44 +10673,66 @@ where
10636
10673
if our_funding_contribution > SignedAmount::MAX_MONEY {
10637
10674
return Err(APIError::APIMisuseError {
10638
10675
err: format!(
10639
- "Channel {} cannot be spliced; contribution exceeds total bitcoin supply: {}",
10676
+ "Channel {} cannot be spliced in ; contribution exceeds total bitcoin supply: {}",
10640
10677
self.context.channel_id(),
10641
10678
our_funding_contribution,
10642
10679
),
10643
10680
});
10644
10681
}
10645
10682
10646
- if our_funding_contribution < SignedAmount::ZERO {
10683
+ if our_funding_contribution < - SignedAmount::MAX_MONEY {
10647
10684
return Err(APIError::APIMisuseError {
10648
10685
err: format!(
10649
- "TODO(splicing): Splice-out not supported, only splice in; channel ID {}, contribution {}",
10650
- self.context.channel_id(), our_funding_contribution,
10651
- ),
10686
+ "Channel {} cannot be spliced out; contribution exhausts total bitcoin supply: {}",
10687
+ self.context.channel_id(),
10688
+ our_funding_contribution,
10689
+ ),
10652
10690
});
10653
10691
}
10654
10692
10655
- // TODO(splicing): Once splice-out is supported, check that channel balance does not go below 0
10656
- // (or below channel reserve)
10657
-
10658
10693
// Note: post-splice channel value is not yet known at this point, counterparty contribution is not known
10659
10694
// (Cannot test for miminum required post-splice channel value)
10660
10695
10661
- // Check that inputs are sufficient to cover our contribution.
10662
- let _fee = check_v2_funding_inputs_sufficient(
10663
- our_funding_contribution.to_sat(),
10664
- contribution.inputs(),
10665
- true,
10666
- true,
10667
- funding_feerate_per_kw,
10696
+ let channel_balance = Amount::from_sat(self.funding.get_value_to_self_msat() / 1000);
10697
+ let fees = check_splice_contribution_sufficient(
10698
+ channel_balance,
10699
+ &contribution,
10700
+ true, // is_initiator
10701
+ FeeRate::from_sat_per_kwu(funding_feerate_per_kw as u64),
10668
10702
)
10669
- .map_err(|err| APIError::APIMisuseError {
10670
- err: format!(
10671
- "Insufficient inputs for splicing; channel ID {}, err {}",
10672
- self.context.channel_id(),
10673
- err,
10674
- ),
10703
+ .map_err(|e| {
10704
+ let splice_type = if our_funding_contribution < SignedAmount::ZERO {
10705
+ "spliced out"
10706
+ } else {
10707
+ "spliced in"
10708
+ };
10709
+ APIError::APIMisuseError {
10710
+ err: format!(
10711
+ "Channel {} cannot be {}; {}",
10712
+ self.context.channel_id(),
10713
+ splice_type,
10714
+ e,
10715
+ ),
10716
+ }
10675
10717
})?;
10676
10718
10719
+ // Fees for splice-out are paid from the channel balance whereas fees for splice-in are paid
10720
+ // by the funding inputs.
10721
+ let adjusted_funding_contribution = if our_funding_contribution < SignedAmount::ZERO {
10722
+ let adjusted_funding_contribution = our_funding_contribution
10723
+ - fees.to_signed().expect("fees should never exceed splice-out value");
10724
+
10725
+ // TODO(splicing): Check that channel balance does not go below the channel reserve
10726
+ let _post_channel_balance = AddSigned::checked_add_signed(
10727
+ channel_balance.to_sat(),
10728
+ adjusted_funding_contribution.to_sat(),
10729
+ );
10730
+
10731
+ adjusted_funding_contribution
10732
+ } else {
10733
+ our_funding_contribution
10734
+ };
10735
+
10677
10736
for FundingTxInput { utxo, prevtx, .. } in contribution.inputs().iter() {
10678
10737
const MESSAGE_TEMPLATE: msgs::TxAddInput = msgs::TxAddInput {
10679
10738
channel_id: ChannelId([0; 32]),
@@ -10696,14 +10755,15 @@ where
10696
10755
}
10697
10756
10698
10757
let prev_funding_input = self.funding.to_splice_funding_input();
10699
- let (our_funding_inputs, change_script) = contribution.into_tx_parts();
10758
+ let (our_funding_inputs, our_funding_outputs, change_script) = contribution.into_tx_parts();
10700
10759
let funding_negotiation_context = FundingNegotiationContext {
10701
10760
is_initiator: true,
10702
- our_funding_contribution,
10761
+ our_funding_contribution: adjusted_funding_contribution ,
10703
10762
funding_tx_locktime: LockTime::from_consensus(locktime),
10704
10763
funding_feerate_sat_per_1000_weight: funding_feerate_per_kw,
10705
10764
shared_funding_input: Some(prev_funding_input),
10706
10765
our_funding_inputs,
10766
+ our_funding_outputs,
10707
10767
change_script,
10708
10768
};
10709
10769
@@ -10719,7 +10779,7 @@ where
10719
10779
10720
10780
Ok(msgs::SpliceInit {
10721
10781
channel_id: self.context.channel_id,
10722
- funding_contribution_satoshis: our_funding_contribution .to_sat(),
10782
+ funding_contribution_satoshis: adjusted_funding_contribution .to_sat(),
10723
10783
funding_feerate_per_kw,
10724
10784
locktime,
10725
10785
funding_pubkey,
@@ -10828,6 +10888,7 @@ where
10828
10888
funding_feerate_sat_per_1000_weight: msg.funding_feerate_per_kw,
10829
10889
shared_funding_input: Some(prev_funding_input),
10830
10890
our_funding_inputs: Vec::new(),
10891
+ our_funding_outputs: Vec::new(),
10831
10892
change_script: None,
10832
10893
};
10833
10894
@@ -12526,6 +12587,7 @@ where
12526
12587
funding_feerate_sat_per_1000_weight,
12527
12588
shared_funding_input: None,
12528
12589
our_funding_inputs: funding_inputs,
12590
+ our_funding_outputs: Vec::new(),
12529
12591
change_script: None,
12530
12592
};
12531
12593
let chan = Self {
@@ -12680,6 +12742,7 @@ where
12680
12742
funding_feerate_sat_per_1000_weight: msg.funding_feerate_sat_per_1000_weight,
12681
12743
shared_funding_input: None,
12682
12744
our_funding_inputs: our_funding_inputs.clone(),
12745
+ our_funding_outputs: Vec::new(),
12683
12746
change_script: None,
12684
12747
};
12685
12748
let shared_funding_output = TxOut {
@@ -12705,7 +12768,7 @@ where
12705
12768
inputs_to_contribute,
12706
12769
shared_funding_input: None,
12707
12770
shared_funding_output: SharedOwnedOutput::new(shared_funding_output, our_funding_contribution_sats),
12708
- outputs_to_contribute: Vec::new (),
12771
+ outputs_to_contribute: funding_negotiation_context.our_funding_outputs.clone (),
12709
12772
}
12710
12773
).map_err(|err| {
12711
12774
let reason = ClosureReason::ProcessingError { err: err.to_string() };
@@ -15874,31 +15937,31 @@ mod tests {
15874
15937
15875
15938
// 2 inputs with weight 300, initiator, 2000 sat/kw feerate
15876
15939
assert_eq!(
15877
- estimate_v2_funding_transaction_fee(true, 2, Weight::from_wu(300), 2000),
15940
+ estimate_v2_funding_transaction_fee(true, 2, Weight::from_wu(300), &[], 2000),
15878
15941
1668
15879
15942
);
15880
15943
15881
15944
// higher feerate
15882
15945
assert_eq!(
15883
- estimate_v2_funding_transaction_fee(true, 2, Weight::from_wu(300), 3000),
15946
+ estimate_v2_funding_transaction_fee(true, 2, Weight::from_wu(300), &[], 3000),
15884
15947
2502
15885
15948
);
15886
15949
15887
15950
// only 1 input
15888
15951
assert_eq!(
15889
- estimate_v2_funding_transaction_fee(true, 1, Weight::from_wu(300), 2000),
15952
+ estimate_v2_funding_transaction_fee(true, 1, Weight::from_wu(300), &[], 2000),
15890
15953
1348
15891
15954
);
15892
15955
15893
15956
// 0 input weight
15894
15957
assert_eq!(
15895
- estimate_v2_funding_transaction_fee(true, 1, Weight::from_wu(0), 2000),
15958
+ estimate_v2_funding_transaction_fee(true, 1, Weight::from_wu(0), &[], 2000),
15896
15959
748
15897
15960
);
15898
15961
15899
15962
// not initiator
15900
15963
assert_eq!(
15901
- estimate_v2_funding_transaction_fee(false, 1, Weight::from_wu(0), 2000),
15964
+ estimate_v2_funding_transaction_fee(false, 1, Weight::from_wu(0), &[], 2000),
15902
15965
320
15903
15966
);
15904
15967
}
0 commit comments