Skip to content

Commit c8ebee5

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 bbe8179 commit c8ebee5

File tree

4 files changed

+165
-74
lines changed

4 files changed

+165
-74
lines changed

lightning/src/ln/channel.rs

Lines changed: 126 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,
@@ -5880,20 +5880,53 @@ fn get_v2_channel_reserve_satoshis(channel_value_satoshis: u64, dust_limit_satos
58805880
cmp::min(channel_value_satoshis, cmp::max(q, dust_limit_satoshis))
58815881
}
58825882

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+
58835918
/// Estimate our part of the fee of the new funding transaction.
58845919
/// input_count: Number of contributed inputs.
58855920
/// witness_weight: The witness weight for contributed inputs.
58865921
#[allow(dead_code)] // TODO(dual_funding): TODO(splicing): Remove allow once used.
58875922
#[rustfmt::skip]
58885923
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],
58905925
funding_feerate_sat_per_1000_weight: u32,
58915926
) -> u64 {
5892-
// Inputs
58935927
let mut weight = (input_count as u64) * BASE_INPUT_WEIGHT;
5894-
5895-
// Witnesses
58965928
weight = weight.saturating_add(witness_weight.to_wu());
5929+
weight = weight.saturating_add(outputs.iter().map(|txout| txout.weight().to_wu()).sum());
58975930

58985931
// If we are the initiator, we must pay for weight of all common fields in the funding transaction.
58995932
if is_initiator {
@@ -5931,7 +5964,7 @@ fn check_v2_funding_inputs_sufficient(
59315964
funding_inputs_len += 1;
59325965
total_input_satisfaction_weight += Weight::from_wu(FUNDING_TRANSACTION_WITNESS_WEIGHT);
59335966
}
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);
59355968

59365969
let mut total_input_sats = 0u64;
59375970
for FundingTxInput { utxo, .. } in funding_inputs.iter() {
@@ -5978,6 +6011,9 @@ pub(super) struct FundingNegotiationContext {
59786011
/// The funding inputs we will be contributing to the channel.
59796012
#[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
59806013
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>,
59816017
/// The change output script. This will be used if needed or -- if not set -- generated using
59826018
/// `SignerProvider::get_destination_script`.
59836019
#[allow(dead_code)] // TODO(splicing): Remove once splicing is enabled.
@@ -6007,45 +6043,46 @@ impl FundingNegotiationContext {
60076043
debug_assert!(matches!(context.channel_state, ChannelState::NegotiatingFunding(_)));
60086044
}
60096045

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

60156049
let shared_funding_output = TxOut {
60166050
value: Amount::from_sat(funding.get_value_satoshis()),
60176051
script_pubkey: funding.get_funding_redeemscript().to_p2wsh(),
60186052
};
60196053

60206054
// 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(
60236057
&self,
60246058
self.shared_funding_input.is_some(),
60256059
&shared_funding_output.script_pubkey,
6026-
&funding_outputs,
60276060
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);
60496086
}
60506087
}
60516088

@@ -10636,44 +10673,66 @@ where
1063610673
if our_funding_contribution > SignedAmount::MAX_MONEY {
1063710674
return Err(APIError::APIMisuseError {
1063810675
err: format!(
10639-
"Channel {} cannot be spliced; contribution exceeds total bitcoin supply: {}",
10676+
"Channel {} cannot be spliced in; contribution exceeds total bitcoin supply: {}",
1064010677
self.context.channel_id(),
1064110678
our_funding_contribution,
1064210679
),
1064310680
});
1064410681
}
1064510682

10646-
if our_funding_contribution < SignedAmount::ZERO {
10683+
if our_funding_contribution < -SignedAmount::MAX_MONEY {
1064710684
return Err(APIError::APIMisuseError {
1064810685
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+
),
1065210690
});
1065310691
}
1065410692

10655-
// TODO(splicing): Once splice-out is supported, check that channel balance does not go below 0
10656-
// (or below channel reserve)
10657-
1065810693
// Note: post-splice channel value is not yet known at this point, counterparty contribution is not known
1065910694
// (Cannot test for miminum required post-splice channel value)
1066010695

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),
1066810702
)
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+
}
1067510717
})?;
1067610718

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+
1067710736
for FundingTxInput { utxo, prevtx, .. } in contribution.inputs().iter() {
1067810737
const MESSAGE_TEMPLATE: msgs::TxAddInput = msgs::TxAddInput {
1067910738
channel_id: ChannelId([0; 32]),
@@ -10696,14 +10755,15 @@ where
1069610755
}
1069710756

1069810757
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();
1070010759
let funding_negotiation_context = FundingNegotiationContext {
1070110760
is_initiator: true,
10702-
our_funding_contribution,
10761+
our_funding_contribution: adjusted_funding_contribution,
1070310762
funding_tx_locktime: LockTime::from_consensus(locktime),
1070410763
funding_feerate_sat_per_1000_weight: funding_feerate_per_kw,
1070510764
shared_funding_input: Some(prev_funding_input),
1070610765
our_funding_inputs,
10766+
our_funding_outputs,
1070710767
change_script,
1070810768
};
1070910769

@@ -10719,7 +10779,7 @@ where
1071910779

1072010780
Ok(msgs::SpliceInit {
1072110781
channel_id: self.context.channel_id,
10722-
funding_contribution_satoshis: our_funding_contribution.to_sat(),
10782+
funding_contribution_satoshis: adjusted_funding_contribution.to_sat(),
1072310783
funding_feerate_per_kw,
1072410784
locktime,
1072510785
funding_pubkey,
@@ -10828,6 +10888,7 @@ where
1082810888
funding_feerate_sat_per_1000_weight: msg.funding_feerate_per_kw,
1082910889
shared_funding_input: Some(prev_funding_input),
1083010890
our_funding_inputs: Vec::new(),
10891+
our_funding_outputs: Vec::new(),
1083110892
change_script: None,
1083210893
};
1083310894

@@ -12526,6 +12587,7 @@ where
1252612587
funding_feerate_sat_per_1000_weight,
1252712588
shared_funding_input: None,
1252812589
our_funding_inputs: funding_inputs,
12590+
our_funding_outputs: Vec::new(),
1252912591
change_script: None,
1253012592
};
1253112593
let chan = Self {
@@ -12680,6 +12742,7 @@ where
1268012742
funding_feerate_sat_per_1000_weight: msg.funding_feerate_sat_per_1000_weight,
1268112743
shared_funding_input: None,
1268212744
our_funding_inputs: our_funding_inputs.clone(),
12745+
our_funding_outputs: Vec::new(),
1268312746
change_script: None,
1268412747
};
1268512748
let shared_funding_output = TxOut {
@@ -12705,7 +12768,7 @@ where
1270512768
inputs_to_contribute,
1270612769
shared_funding_input: None,
1270712770
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(),
1270912772
}
1271012773
).map_err(|err| {
1271112774
let reason = ClosureReason::ProcessingError { err: err.to_string() };
@@ -15874,31 +15937,31 @@ mod tests {
1587415937

1587515938
// 2 inputs with weight 300, initiator, 2000 sat/kw feerate
1587615939
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),
1587815941
1668
1587915942
);
1588015943

1588115944
// higher feerate
1588215945
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),
1588415947
2502
1588515948
);
1588615949

1588715950
// only 1 input
1588815951
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),
1589015953
1348
1589115954
);
1589215955

1589315956
// 0 input weight
1589415957
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),
1589615959
748
1589715960
);
1589815961

1589915962
// not initiator
1590015963
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),
1590215965
320
1590315966
);
1590415967
}

0 commit comments

Comments
 (0)