Skip to content

Commit 20b6809

Browse files
committed
Add splice-out support
Update SpliceContribution with a variant used to support splice-out (i.e., removing funds from a channel). The TxOut values must not exceed the users channel balance after accounting for fees and the reserve requirement.
1 parent 3e04691 commit 20b6809

4 files changed

Lines changed: 174 additions & 74 deletions

File tree

lightning/src/ln/channel.rs

Lines changed: 135 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -24,9 +24,9 @@ use bitcoin::hashes::Hash;
2424
use bitcoin::secp256k1::constants::PUBLIC_KEY_SIZE;
2525
use bitcoin::secp256k1::{ecdsa::Signature, Secp256k1};
2626
use bitcoin::secp256k1::{PublicKey, SecretKey};
27-
#[cfg(splicing)]
28-
use bitcoin::Sequence;
2927
use bitcoin::{secp256k1, sighash, TxIn};
28+
#[cfg(splicing)]
29+
use bitcoin::{FeeRate, Sequence};
3030

3131
use crate::chain::chaininterface::{
3232
fee_for_weight, ConfirmationTarget, FeeEstimator, LowerBoundedFeeEstimator,
@@ -5879,18 +5879,60 @@ fn get_v2_channel_reserve_satoshis(channel_value_satoshis: u64, dust_limit_satos
58795879
cmp::min(channel_value_satoshis, cmp::max(q, dust_limit_satoshis))
58805880
}
58815881

5882+
#[cfg(splicing)]
5883+
fn check_splice_contribution_sufficient(
5884+
channel_balance: Amount, contribution: &SpliceContribution, is_initiator: bool,
5885+
funding_feerate: FeeRate,
5886+
) -> Result<Amount, ChannelError> {
5887+
let contribution_amount = contribution.value();
5888+
if contribution_amount < SignedAmount::ZERO {
5889+
let estimated_fee = Amount::from_sat(estimate_v2_funding_transaction_fee(
5890+
contribution.inputs(),
5891+
contribution.outputs(),
5892+
is_initiator,
5893+
true, // is_splice
5894+
funding_feerate.to_sat_per_kwu() as u32,
5895+
));
5896+
5897+
if channel_balance >= contribution_amount.unsigned_abs() + estimated_fee {
5898+
Ok(estimated_fee)
5899+
} else {
5900+
Err(ChannelError::Warn(format!(
5901+
"Available channel balance {} is lower than needed for splicing out {}, considering fees of {}",
5902+
channel_balance, contribution_amount.unsigned_abs(), estimated_fee,
5903+
)))
5904+
}
5905+
} else {
5906+
check_v2_funding_inputs_sufficient(
5907+
contribution_amount.to_sat(),
5908+
contribution.inputs(),
5909+
is_initiator,
5910+
true,
5911+
funding_feerate.to_sat_per_kwu() as u32,
5912+
)
5913+
.map(Amount::from_sat)
5914+
}
5915+
}
5916+
58825917
/// Estimate our part of the fee of the new funding transaction.
58835918
#[allow(dead_code)] // TODO(dual_funding): TODO(splicing): Remove allow once used.
58845919
#[rustfmt::skip]
58855920
fn estimate_v2_funding_transaction_fee(
5886-
funding_inputs: &[FundingTxInput], is_initiator: bool, is_splice: bool,
5921+
funding_inputs: &[FundingTxInput], outputs: &[TxOut], is_initiator: bool, is_splice: bool,
58875922
funding_feerate_sat_per_1000_weight: u32,
58885923
) -> u64 {
5889-
let mut weight: u64 = funding_inputs
5924+
let input_weight: u64 = funding_inputs
58905925
.iter()
58915926
.map(|input| BASE_INPUT_WEIGHT.saturating_add(input.utxo.satisfaction_weight))
58925927
.fold(0, |total_weight, input_weight| total_weight.saturating_add(input_weight));
58935928

5929+
let output_weight: u64 = outputs
5930+
.iter()
5931+
.map(|txout| txout.weight().to_wu())
5932+
.fold(0, |total_weight, output_weight| total_weight.saturating_add(output_weight));
5933+
5934+
let mut weight = input_weight.saturating_add(output_weight);
5935+
58945936
// The initiator pays for all common fields and the shared output in the funding transaction.
58955937
if is_initiator {
58965938
weight = weight
@@ -5927,7 +5969,7 @@ fn check_v2_funding_inputs_sufficient(
59275969
is_splice: bool, funding_feerate_sat_per_1000_weight: u32,
59285970
) -> Result<u64, ChannelError> {
59295971
let estimated_fee = estimate_v2_funding_transaction_fee(
5930-
funding_inputs, is_initiator, is_splice, funding_feerate_sat_per_1000_weight,
5972+
funding_inputs, &[], is_initiator, is_splice, funding_feerate_sat_per_1000_weight,
59315973
);
59325974

59335975
let mut total_input_sats = 0u64;
@@ -5975,6 +6017,9 @@ pub(super) struct FundingNegotiationContext {
59756017
/// The funding inputs we will be contributing to the channel.
59766018
#[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
59776019
pub our_funding_inputs: Vec<FundingTxInput>,
6020+
/// The funding outputs we will be contributing to the channel.
6021+
#[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
6022+
pub our_funding_outputs: Vec<TxOut>,
59786023
/// The change output script. This will be used if needed or -- if not set -- generated using
59796024
/// `SignerProvider::get_destination_script`.
59806025
#[allow(dead_code)] // TODO(splicing): Remove once splicing is enabled.
@@ -6004,45 +6049,46 @@ impl FundingNegotiationContext {
60046049
debug_assert!(matches!(context.channel_state, ChannelState::NegotiatingFunding(_)));
60056050
}
60066051

6007-
// Add output for funding tx
60086052
// Note: For the error case when the inputs are insufficient, it will be handled after
60096053
// the `calculate_change_output_value` call below
6010-
let mut funding_outputs = Vec::new();
60116054

60126055
let shared_funding_output = TxOut {
60136056
value: Amount::from_sat(funding.get_value_satoshis()),
60146057
script_pubkey: funding.get_funding_redeemscript().to_p2wsh(),
60156058
};
60166059

60176060
// Optionally add change output
6018-
if self.our_funding_contribution > SignedAmount::ZERO {
6019-
let change_value_opt = calculate_change_output_value(
6061+
let change_value_opt = if self.our_funding_contribution > SignedAmount::ZERO {
6062+
calculate_change_output_value(
60206063
&self,
60216064
self.shared_funding_input.is_some(),
60226065
&shared_funding_output.script_pubkey,
6023-
&funding_outputs,
60246066
context.holder_dust_limit_satoshis,
6025-
)?;
6026-
if let Some(change_value) = change_value_opt {
6027-
let change_script = if let Some(script) = self.change_script {
6028-
script
6029-
} else {
6030-
signer_provider
6031-
.get_destination_script(context.channel_keys_id)
6032-
.map_err(|_err| AbortReason::InternalError("Error getting change script"))?
6033-
};
6034-
let mut change_output =
6035-
TxOut { value: Amount::from_sat(change_value), script_pubkey: change_script };
6036-
let change_output_weight = get_output_weight(&change_output.script_pubkey).to_wu();
6037-
let change_output_fee =
6038-
fee_for_weight(self.funding_feerate_sat_per_1000_weight, change_output_weight);
6039-
let change_value_decreased_with_fee =
6040-
change_value.saturating_sub(change_output_fee);
6041-
// Check dust limit again
6042-
if change_value_decreased_with_fee > context.holder_dust_limit_satoshis {
6043-
change_output.value = Amount::from_sat(change_value_decreased_with_fee);
6044-
funding_outputs.push(change_output);
6045-
}
6067+
)?
6068+
} else {
6069+
None
6070+
};
6071+
6072+
let mut funding_outputs = self.our_funding_outputs;
6073+
6074+
if let Some(change_value) = change_value_opt {
6075+
let change_script = if let Some(script) = self.change_script {
6076+
script
6077+
} else {
6078+
signer_provider
6079+
.get_destination_script(context.channel_keys_id)
6080+
.map_err(|_err| AbortReason::InternalError("Error getting change script"))?
6081+
};
6082+
let mut change_output =
6083+
TxOut { value: Amount::from_sat(change_value), script_pubkey: change_script };
6084+
let change_output_weight = get_output_weight(&change_output.script_pubkey).to_wu();
6085+
let change_output_fee =
6086+
fee_for_weight(self.funding_feerate_sat_per_1000_weight, change_output_weight);
6087+
let change_value_decreased_with_fee = change_value.saturating_sub(change_output_fee);
6088+
// Check dust limit again
6089+
if change_value_decreased_with_fee > context.holder_dust_limit_satoshis {
6090+
change_output.value = Amount::from_sat(change_value_decreased_with_fee);
6091+
funding_outputs.push(change_output);
60466092
}
60476093
}
60486094

@@ -10633,44 +10679,66 @@ where
1063310679
if our_funding_contribution > SignedAmount::MAX_MONEY {
1063410680
return Err(APIError::APIMisuseError {
1063510681
err: format!(
10636-
"Channel {} cannot be spliced; contribution exceeds total bitcoin supply: {}",
10682+
"Channel {} cannot be spliced in; contribution exceeds total bitcoin supply: {}",
1063710683
self.context.channel_id(),
1063810684
our_funding_contribution,
1063910685
),
1064010686
});
1064110687
}
1064210688

10643-
if our_funding_contribution < SignedAmount::ZERO {
10689+
if our_funding_contribution < -SignedAmount::MAX_MONEY {
1064410690
return Err(APIError::APIMisuseError {
1064510691
err: format!(
10646-
"TODO(splicing): Splice-out not supported, only splice in; channel ID {}, contribution {}",
10647-
self.context.channel_id(), our_funding_contribution,
10648-
),
10692+
"Channel {} cannot be spliced out; contribution exhausts total bitcoin supply: {}",
10693+
self.context.channel_id(),
10694+
our_funding_contribution,
10695+
),
1064910696
});
1065010697
}
1065110698

10652-
// TODO(splicing): Once splice-out is supported, check that channel balance does not go below 0
10653-
// (or below channel reserve)
10654-
1065510699
// Note: post-splice channel value is not yet known at this point, counterparty contribution is not known
1065610700
// (Cannot test for miminum required post-splice channel value)
1065710701

10658-
// Check that inputs are sufficient to cover our contribution.
10659-
let _fee = check_v2_funding_inputs_sufficient(
10660-
our_funding_contribution.to_sat(),
10661-
contribution.inputs(),
10662-
true,
10663-
true,
10664-
funding_feerate_per_kw,
10702+
let channel_balance = Amount::from_sat(self.funding.get_value_to_self_msat() / 1000);
10703+
let fees = check_splice_contribution_sufficient(
10704+
channel_balance,
10705+
&contribution,
10706+
true, // is_initiator
10707+
FeeRate::from_sat_per_kwu(funding_feerate_per_kw as u64),
1066510708
)
10666-
.map_err(|err| APIError::APIMisuseError {
10667-
err: format!(
10668-
"Insufficient inputs for splicing; channel ID {}, err {}",
10669-
self.context.channel_id(),
10670-
err,
10671-
),
10709+
.map_err(|e| {
10710+
let splice_type = if our_funding_contribution < SignedAmount::ZERO {
10711+
"spliced out"
10712+
} else {
10713+
"spliced in"
10714+
};
10715+
APIError::APIMisuseError {
10716+
err: format!(
10717+
"Channel {} cannot be {}; {}",
10718+
self.context.channel_id(),
10719+
splice_type,
10720+
e,
10721+
),
10722+
}
1067210723
})?;
1067310724

10725+
// Fees for splice-out are paid from the channel balance whereas fees for splice-in are paid
10726+
// by the funding inputs.
10727+
let adjusted_funding_contribution = if our_funding_contribution < SignedAmount::ZERO {
10728+
let adjusted_funding_contribution = our_funding_contribution
10729+
- fees.to_signed().expect("fees should never exceed Amount::MAX_MONEY");
10730+
10731+
// TODO(splicing): Check that channel balance does not go below the channel reserve
10732+
let _post_channel_balance = AddSigned::checked_add_signed(
10733+
channel_balance.to_sat(),
10734+
adjusted_funding_contribution.to_sat(),
10735+
);
10736+
10737+
adjusted_funding_contribution
10738+
} else {
10739+
our_funding_contribution
10740+
};
10741+
1067410742
for FundingTxInput { utxo, prevtx, .. } in contribution.inputs().iter() {
1067510743
const MESSAGE_TEMPLATE: msgs::TxAddInput = msgs::TxAddInput {
1067610744
channel_id: ChannelId([0; 32]),
@@ -10693,14 +10761,15 @@ where
1069310761
}
1069410762

1069510763
let prev_funding_input = self.funding.to_splice_funding_input();
10696-
let (our_funding_inputs, change_script) = contribution.into_tx_parts();
10764+
let (our_funding_inputs, our_funding_outputs, change_script) = contribution.into_tx_parts();
1069710765
let funding_negotiation_context = FundingNegotiationContext {
1069810766
is_initiator: true,
10699-
our_funding_contribution,
10767+
our_funding_contribution: adjusted_funding_contribution,
1070010768
funding_tx_locktime: LockTime::from_consensus(locktime),
1070110769
funding_feerate_sat_per_1000_weight: funding_feerate_per_kw,
1070210770
shared_funding_input: Some(prev_funding_input),
1070310771
our_funding_inputs,
10772+
our_funding_outputs,
1070410773
change_script,
1070510774
};
1070610775

@@ -10716,7 +10785,7 @@ where
1071610785

1071710786
Ok(msgs::SpliceInit {
1071810787
channel_id: self.context.channel_id,
10719-
funding_contribution_satoshis: our_funding_contribution.to_sat(),
10788+
funding_contribution_satoshis: adjusted_funding_contribution.to_sat(),
1072010789
funding_feerate_per_kw,
1072110790
locktime,
1072210791
funding_pubkey,
@@ -10825,6 +10894,7 @@ where
1082510894
funding_feerate_sat_per_1000_weight: msg.funding_feerate_per_kw,
1082610895
shared_funding_input: Some(prev_funding_input),
1082710896
our_funding_inputs: Vec::new(),
10897+
our_funding_outputs: Vec::new(),
1082810898
change_script: None,
1082910899
};
1083010900

@@ -12523,6 +12593,7 @@ where
1252312593
funding_feerate_sat_per_1000_weight,
1252412594
shared_funding_input: None,
1252512595
our_funding_inputs: funding_inputs,
12596+
our_funding_outputs: Vec::new(),
1252612597
change_script: None,
1252712598
};
1252812599
let chan = Self {
@@ -12677,6 +12748,7 @@ where
1267712748
funding_feerate_sat_per_1000_weight: msg.funding_feerate_sat_per_1000_weight,
1267812749
shared_funding_input: None,
1267912750
our_funding_inputs: our_funding_inputs.clone(),
12751+
our_funding_outputs: Vec::new(),
1268012752
change_script: None,
1268112753
};
1268212754
let shared_funding_output = TxOut {
@@ -12702,7 +12774,7 @@ where
1270212774
inputs_to_contribute,
1270312775
shared_funding_input: None,
1270412776
shared_funding_output: SharedOwnedOutput::new(shared_funding_output, our_funding_contribution_sats),
12705-
outputs_to_contribute: Vec::new(),
12777+
outputs_to_contribute: funding_negotiation_context.our_funding_outputs.clone(),
1270612778
}
1270712779
).map_err(|err| {
1270812780
let reason = ClosureReason::ProcessingError { err: err.to_string() };
@@ -15870,43 +15942,43 @@ mod tests {
1587015942

1587115943
// 2 inputs, initiator, 2000 sat/kw feerate
1587215944
assert_eq!(
15873-
estimate_v2_funding_transaction_fee(&two_inputs, true, false, 2000),
15945+
estimate_v2_funding_transaction_fee(&two_inputs, &[], true, false, 2000),
1587415946
1520,
1587515947
);
1587615948

1587715949
// higher feerate
1587815950
assert_eq!(
15879-
estimate_v2_funding_transaction_fee(&two_inputs, true, false, 3000),
15951+
estimate_v2_funding_transaction_fee(&two_inputs, &[], true, false, 3000),
1588015952
2280,
1588115953
);
1588215954

1588315955
// only 1 input
1588415956
assert_eq!(
15885-
estimate_v2_funding_transaction_fee(&one_input, true, false, 2000),
15957+
estimate_v2_funding_transaction_fee(&one_input, &[], true, false, 2000),
1588615958
974,
1588715959
);
1588815960

1588915961
// 0 inputs
1589015962
assert_eq!(
15891-
estimate_v2_funding_transaction_fee(&[], true, false, 2000),
15963+
estimate_v2_funding_transaction_fee(&[], &[], true, false, 2000),
1589215964
428,
1589315965
);
1589415966

1589515967
// not initiator
1589615968
assert_eq!(
15897-
estimate_v2_funding_transaction_fee(&[], false, false, 2000),
15969+
estimate_v2_funding_transaction_fee(&[], &[], false, false, 2000),
1589815970
0,
1589915971
);
1590015972

1590115973
// splice initiator
1590215974
assert_eq!(
15903-
estimate_v2_funding_transaction_fee(&one_input, true, true, 2000),
15975+
estimate_v2_funding_transaction_fee(&one_input, &[], true, true, 2000),
1590415976
1746,
1590515977
);
1590615978

1590715979
// splice acceptor
1590815980
assert_eq!(
15909-
estimate_v2_funding_transaction_fee(&one_input, false, true, 2000),
15981+
estimate_v2_funding_transaction_fee(&one_input, &[], false, true, 2000),
1591015982
546,
1591115983
);
1591215984
}

0 commit comments

Comments
 (0)