@@ -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,
@@ -5878,20 +5878,53 @@ fn get_v2_channel_reserve_satoshis(channel_value_satoshis: u64, dust_limit_satos
5878
5878
cmp::min(channel_value_satoshis, cmp::max(q, dust_limit_satoshis))
5879
5879
}
5880
5880
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
+
5881
5916
/// Estimate our part of the fee of the new funding transaction.
5882
5917
/// input_count: Number of contributed inputs.
5883
5918
/// witness_weight: The witness weight for contributed inputs.
5884
5919
#[allow(dead_code)] // TODO(dual_funding): TODO(splicing): Remove allow once used.
5885
5920
#[rustfmt::skip]
5886
5921
fn 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],
5888
5923
funding_feerate_sat_per_1000_weight: u32,
5889
5924
) -> u64 {
5890
- // Inputs
5891
5925
let mut weight = (input_count as u64) * BASE_INPUT_WEIGHT;
5892
-
5893
- // Witnesses
5894
5926
weight = weight.saturating_add(witness_weight.to_wu());
5927
+ weight = weight.saturating_add(outputs.iter().map(|txout| txout.weight().to_wu()).sum());
5895
5928
5896
5929
// If we are the initiator, we must pay for weight of all common fields in the funding transaction.
5897
5930
if is_initiator {
@@ -5929,7 +5962,7 @@ fn check_v2_funding_inputs_sufficient(
5929
5962
funding_inputs_len += 1;
5930
5963
total_input_witness_weight += Weight::from_wu(FUNDING_TRANSACTION_WITNESS_WEIGHT);
5931
5964
}
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);
5933
5966
5934
5967
let mut total_input_sats = 0u64;
5935
5968
for FundingTxInput { utxo, .. } in funding_inputs.iter() {
@@ -5976,6 +6009,9 @@ pub(super) struct FundingNegotiationContext {
5976
6009
/// The funding inputs we will be contributing to the channel.
5977
6010
#[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
5978
6011
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>,
5979
6015
/// The change output script. This will be used if needed or -- if not set -- generated using
5980
6016
/// `SignerProvider::get_destination_script`.
5981
6017
#[allow(dead_code)] // TODO(splicing): Remove once splicing is enabled.
@@ -6005,45 +6041,46 @@ impl FundingNegotiationContext {
6005
6041
debug_assert!(matches!(context.channel_state, ChannelState::NegotiatingFunding(_)));
6006
6042
}
6007
6043
6008
- // Add output for funding tx
6009
6044
// Note: For the error case when the inputs are insufficient, it will be handled after
6010
6045
// the `calculate_change_output_value` call below
6011
- let mut funding_outputs = Vec::new();
6012
6046
6013
6047
let shared_funding_output = TxOut {
6014
6048
value: Amount::from_sat(funding.get_value_satoshis()),
6015
6049
script_pubkey: funding.get_funding_redeemscript().to_p2wsh(),
6016
6050
};
6017
6051
6018
6052
// 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(
6021
6055
&self,
6022
6056
self.shared_funding_input.is_some(),
6023
6057
&shared_funding_output.script_pubkey,
6024
- &funding_outputs,
6025
6058
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);
6047
6084
}
6048
6085
}
6049
6086
@@ -10634,44 +10671,66 @@ where
10634
10671
if our_funding_contribution > SignedAmount::MAX_MONEY {
10635
10672
return Err(APIError::APIMisuseError {
10636
10673
err: format!(
10637
- "Channel {} cannot be spliced; contribution exceeds total bitcoin supply: {}",
10674
+ "Channel {} cannot be spliced in ; contribution exceeds total bitcoin supply: {}",
10638
10675
self.context.channel_id(),
10639
10676
our_funding_contribution,
10640
10677
),
10641
10678
});
10642
10679
}
10643
10680
10644
- if our_funding_contribution < SignedAmount::ZERO {
10681
+ if our_funding_contribution < - SignedAmount::MAX_MONEY {
10645
10682
return Err(APIError::APIMisuseError {
10646
10683
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
+ ),
10650
10688
});
10651
10689
}
10652
10690
10653
- // TODO(splicing): Once splice-out is supported, check that channel balance does not go below 0
10654
- // (or below channel reserve)
10655
-
10656
10691
// Note: post-splice channel value is not yet known at this point, counterparty contribution is not known
10657
10692
// (Cannot test for miminum required post-splice channel value)
10658
10693
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),
10666
10700
)
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
+ }
10673
10715
})?;
10674
10716
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
+
10675
10734
for FundingTxInput { utxo, prevtx, .. } in contribution.inputs().iter() {
10676
10735
const MESSAGE_TEMPLATE: msgs::TxAddInput = msgs::TxAddInput {
10677
10736
channel_id: ChannelId([0; 32]),
@@ -10693,14 +10752,15 @@ where
10693
10752
}
10694
10753
10695
10754
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();
10697
10756
let funding_negotiation_context = FundingNegotiationContext {
10698
10757
is_initiator: true,
10699
- our_funding_contribution,
10758
+ our_funding_contribution: adjusted_funding_contribution ,
10700
10759
funding_tx_locktime: LockTime::from_consensus(locktime),
10701
10760
funding_feerate_sat_per_1000_weight: funding_feerate_per_kw,
10702
10761
shared_funding_input: Some(prev_funding_input),
10703
10762
our_funding_inputs,
10763
+ our_funding_outputs,
10704
10764
change_script,
10705
10765
};
10706
10766
@@ -10716,7 +10776,7 @@ where
10716
10776
10717
10777
Ok(msgs::SpliceInit {
10718
10778
channel_id: self.context.channel_id,
10719
- funding_contribution_satoshis: our_funding_contribution .to_sat(),
10779
+ funding_contribution_satoshis: adjusted_funding_contribution .to_sat(),
10720
10780
funding_feerate_per_kw,
10721
10781
locktime,
10722
10782
funding_pubkey,
@@ -10825,6 +10885,7 @@ where
10825
10885
funding_feerate_sat_per_1000_weight: msg.funding_feerate_per_kw,
10826
10886
shared_funding_input: Some(prev_funding_input),
10827
10887
our_funding_inputs: Vec::new(),
10888
+ our_funding_outputs: Vec::new(),
10828
10889
change_script: None,
10829
10890
};
10830
10891
@@ -12523,6 +12584,7 @@ where
12523
12584
funding_feerate_sat_per_1000_weight,
12524
12585
shared_funding_input: None,
12525
12586
our_funding_inputs: funding_inputs,
12587
+ our_funding_outputs: Vec::new(),
12526
12588
change_script: None,
12527
12589
};
12528
12590
let chan = Self {
@@ -12677,6 +12739,7 @@ where
12677
12739
funding_feerate_sat_per_1000_weight: msg.funding_feerate_sat_per_1000_weight,
12678
12740
shared_funding_input: None,
12679
12741
our_funding_inputs: our_funding_inputs.clone(),
12742
+ our_funding_outputs: Vec::new(),
12680
12743
change_script: None,
12681
12744
};
12682
12745
let shared_funding_output = TxOut {
@@ -12702,7 +12765,7 @@ where
12702
12765
inputs_to_contribute,
12703
12766
shared_funding_input: None,
12704
12767
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 (),
12706
12769
}
12707
12770
).map_err(|err| {
12708
12771
let reason = ClosureReason::ProcessingError { err: err.to_string() };
@@ -15871,31 +15934,31 @@ mod tests {
15871
15934
15872
15935
// 2 inputs with weight 300, initiator, 2000 sat/kw feerate
15873
15936
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),
15875
15938
1668
15876
15939
);
15877
15940
15878
15941
// higher feerate
15879
15942
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),
15881
15944
2502
15882
15945
);
15883
15946
15884
15947
// only 1 input
15885
15948
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),
15887
15950
1348
15888
15951
);
15889
15952
15890
15953
// 0 input weight
15891
15954
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),
15893
15956
748
15894
15957
);
15895
15958
15896
15959
// not initiator
15897
15960
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),
15899
15962
320
15900
15963
);
15901
15964
}
0 commit comments