Skip to content

Commit 411198f

Browse files
committed
New splice_channel() for initiating splicing, handle splice_init and splice_ack messages, but fail afterwards
1 parent 726dd5c commit 411198f

File tree

5 files changed

+779
-11
lines changed

5 files changed

+779
-11
lines changed

lightning/src/ln/channel.rs

Lines changed: 280 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@ use bitcoin::amount::Amount;
1111
use bitcoin::constants::ChainHash;
1212
use bitcoin::script::{Script, ScriptBuf, Builder, WScriptHash};
1313
use bitcoin::transaction::{Transaction, TxIn};
14-
use bitcoin::sighash;
1514
use bitcoin::sighash::EcdsaSighashType;
1615
use bitcoin::consensus::encode;
1716
use bitcoin::absolute::LockTime;
@@ -25,7 +24,7 @@ use bitcoin::hash_types::{Txid, BlockHash};
2524
use bitcoin::secp256k1::constants::PUBLIC_KEY_SIZE;
2625
use bitcoin::secp256k1::{PublicKey,SecretKey};
2726
use bitcoin::secp256k1::{Secp256k1,ecdsa::Signature};
28-
use bitcoin::secp256k1;
27+
use bitcoin::{secp256k1, sighash};
2928

3029
use crate::ln::types::ChannelId;
3130
use crate::types::payment::{PaymentPreimage, PaymentHash};
@@ -1182,6 +1181,30 @@ impl UnfundedChannelContext {
11821181
}
11831182
}
11841183

1184+
/// Info about a pending splice, used in the pre-splice channel
1185+
#[cfg(splicing)]
1186+
#[derive(Clone)]
1187+
struct PendingSpliceInfoPre {
1188+
pub our_funding_contribution: i64,
1189+
}
1190+
1191+
#[cfg(splicing)]
1192+
impl PendingSpliceInfoPre {
1193+
#[inline]
1194+
fn add_checked(base: u64, delta: i64) -> u64 {
1195+
if delta >= 0 {
1196+
base.saturating_add(delta as u64)
1197+
} else {
1198+
base.saturating_sub(delta.abs() as u64)
1199+
}
1200+
}
1201+
1202+
/// Compute the post-splice channel value from the pre-splice values and the peer contributions
1203+
pub fn compute_post_value(pre_channel_value: u64, our_funding_contribution: i64, their_funding_contribution: i64) -> u64 {
1204+
Self::add_checked(pre_channel_value, our_funding_contribution.saturating_add(their_funding_contribution))
1205+
}
1206+
}
1207+
11851208
/// Contains everything about the channel including state, and various flags.
11861209
pub(super) struct ChannelContext<SP: Deref> where SP::Target: SignerProvider {
11871210
config: LegacyChannelConfig,
@@ -1217,6 +1240,10 @@ pub(super) struct ChannelContext<SP: Deref> where SP::Target: SignerProvider {
12171240
secp_ctx: Secp256k1<secp256k1::All>,
12181241
channel_value_satoshis: u64,
12191242

1243+
/// Info about an in-progress, pending splice (if any), on the pre-splice channel
1244+
#[cfg(splicing)]
1245+
pending_splice_pre: Option<PendingSpliceInfoPre>,
1246+
12201247
latest_monitor_update_id: u64,
12211248

12221249
holder_signer: ChannelSignerType<SP>,
@@ -2207,6 +2234,9 @@ impl<SP: Deref> ChannelContext<SP> where SP::Target: SignerProvider {
22072234
is_manual_broadcast: false,
22082235

22092236
next_funding_txid: None,
2237+
2238+
#[cfg(splicing)]
2239+
pending_splice_pre: None,
22102240
};
22112241

22122242
Ok(channel_context)
@@ -2440,6 +2470,9 @@ impl<SP: Deref> ChannelContext<SP> where SP::Target: SignerProvider {
24402470
local_initiated_shutdown: None,
24412471
is_manual_broadcast: false,
24422472
next_funding_txid: None,
2473+
2474+
#[cfg(splicing)]
2475+
pending_splice_pre: None,
24432476
})
24442477
}
24452478

@@ -3623,6 +3656,33 @@ impl<SP: Deref> ChannelContext<SP> where SP::Target: SignerProvider {
36233656
(context.holder_selected_channel_reserve_satoshis, context.counterparty_selected_channel_reserve_satoshis)
36243657
}
36253658

3659+
/// Check that a balance value meets the channel reserve requirements or violates them (below reserve).
3660+
/// The channel value is an input as opposed to using from self, so that this can be used in case of splicing
3661+
/// to checks with new channel value (before being comitted to it).
3662+
#[cfg(splicing)]
3663+
pub fn check_balance_meets_reserve_requirements(&self, balance: u64, channel_value: u64) -> Result<(), ChannelError> {
3664+
if balance == 0 {
3665+
return Ok(());
3666+
}
3667+
let holder_selected_channel_reserve_satoshis = get_v2_channel_reserve_satoshis(
3668+
channel_value, self.holder_dust_limit_satoshis);
3669+
if balance < holder_selected_channel_reserve_satoshis {
3670+
return Err(ChannelError::Warn(format!(
3671+
"Balance below reserve mandated by holder, {} vs {}",
3672+
balance, holder_selected_channel_reserve_satoshis,
3673+
)));
3674+
}
3675+
let counterparty_selected_channel_reserve_satoshis = get_v2_channel_reserve_satoshis(
3676+
channel_value, self.counterparty_dust_limit_satoshis);
3677+
if balance < counterparty_selected_channel_reserve_satoshis {
3678+
return Err(ChannelError::Warn(format!(
3679+
"Balance below reserve mandated by counterparty, {} vs {}",
3680+
balance, counterparty_selected_channel_reserve_satoshis,
3681+
)));
3682+
}
3683+
Ok(())
3684+
}
3685+
36263686
/// Get the commitment tx fee for the local's (i.e. our) next commitment transaction based on the
36273687
/// number of pending HTLCs that are on track to be in our next commitment tx.
36283688
///
@@ -4093,6 +4153,38 @@ impl<SP: Deref> ChannelContext<SP> where SP::Target: SignerProvider {
40934153
self.channel_transaction_parameters = channel_transaction_parameters;
40944154
self.get_initial_counterparty_commitment_signature(logger)
40954155
}
4156+
4157+
/// Get the splice message that can be sent during splice initiation.
4158+
#[cfg(splicing)]
4159+
pub fn get_splice_init(&self, our_funding_contribution_satoshis: i64,
4160+
funding_feerate_perkw: u32, locktime: u32,
4161+
) -> msgs::SpliceInit {
4162+
// Reuse the existing funding pubkey, in spite of the channel value changing
4163+
// (though at this point we don't know the new value yet, due tue the optional counterparty contribution)
4164+
// Note that channel_keys_id is supposed NOT to change
4165+
let funding_pubkey = self.get_holder_pubkeys().funding_pubkey.clone();
4166+
msgs::SpliceInit {
4167+
channel_id: self.channel_id,
4168+
funding_contribution_satoshis: our_funding_contribution_satoshis,
4169+
funding_feerate_perkw,
4170+
locktime,
4171+
funding_pubkey,
4172+
require_confirmed_inputs: None,
4173+
}
4174+
}
4175+
4176+
/// Get the splice_ack message that can be sent in response to splice initiation.
4177+
#[cfg(splicing)]
4178+
pub fn get_splice_ack(&self, our_funding_contribution_satoshis: i64) -> msgs::SpliceAck {
4179+
// Reuse the existing funding pubkey, in spite of the channel value changing
4180+
let funding_pubkey = self.get_holder_pubkeys().funding_pubkey;
4181+
msgs::SpliceAck {
4182+
channel_id: self.channel_id,
4183+
funding_contribution_satoshis: our_funding_contribution_satoshis,
4184+
funding_pubkey,
4185+
require_confirmed_inputs: None,
4186+
}
4187+
}
40964188
}
40974189

40984190
// Internal utility functions for channels
@@ -7815,6 +7907,124 @@ impl<SP: Deref> Channel<SP> where
78157907
}
78167908
}
78177909

7910+
/// Initiate splicing
7911+
#[cfg(splicing)]
7912+
pub fn splice_channel(&mut self, our_funding_contribution_satoshis: i64,
7913+
funding_feerate_perkw: u32, locktime: u32,
7914+
) -> Result<msgs::SpliceInit, ChannelError> {
7915+
// Check if a splice has been initiated already.
7916+
// Note: this could be handled more nicely, and support multiple outstanding splice's, the incoming splice_ack matters anyways.
7917+
if let Some(splice_info) = &self.context.pending_splice_pre {
7918+
return Err(ChannelError::Warn(format!(
7919+
"Channel has already a splice pending, contribution {}", splice_info.our_funding_contribution
7920+
)));
7921+
}
7922+
7923+
if !matches!(self.context.channel_state, ChannelState::ChannelReady(_)) {
7924+
return Err(ChannelError::Warn(format!("Cannot initiate splicing, as channel is not Ready")));
7925+
}
7926+
7927+
let pre_channel_value = self.context.get_value_satoshis();
7928+
// Sanity check: capacity cannot decrease below 0
7929+
if (pre_channel_value as i64).saturating_add(our_funding_contribution_satoshis) < 0 {
7930+
return Err(ChannelError::Warn(format!(
7931+
"Post-splicing channel value cannot be negative. It was {} + {}",
7932+
pre_channel_value, our_funding_contribution_satoshis
7933+
)));
7934+
}
7935+
7936+
if our_funding_contribution_satoshis < 0 {
7937+
return Err(ChannelError::Warn(format!(
7938+
"TODO(splicing): Splice-out not supported, only splice in, contribution {}",
7939+
our_funding_contribution_satoshis,
7940+
)));
7941+
}
7942+
7943+
// Note: post-splice channel value is not yet known at this point, counterpary contribution is not known
7944+
// (Cannot test for miminum required post-splice channel value)
7945+
7946+
self.context.pending_splice_pre = Some(PendingSpliceInfoPre {
7947+
our_funding_contribution: our_funding_contribution_satoshis,
7948+
});
7949+
7950+
let msg = self.context.get_splice_init(our_funding_contribution_satoshis, funding_feerate_perkw, locktime);
7951+
Ok(msg)
7952+
}
7953+
7954+
/// Handle splice_init
7955+
#[cfg(splicing)]
7956+
pub fn splice_init(&mut self, msg: &msgs::SpliceInit) -> Result<msgs::SpliceAck, ChannelError> {
7957+
let their_funding_contribution_satoshis = msg.funding_contribution_satoshis;
7958+
// TODO(splicing): Currently not possible to contribute on the splicing-acceptor side
7959+
let our_funding_contribution_satoshis = 0i64;
7960+
7961+
// Check if a splice has been initiated already.
7962+
// Note: this could be handled more nicely, and support multiple outstanding splice's, the incoming splice_ack matters anyways.
7963+
if let Some(splice_info) = &self.context.pending_splice_pre {
7964+
return Err(ChannelError::Warn(format!(
7965+
"Channel has already a splice pending, contribution {}", splice_info.our_funding_contribution,
7966+
)));
7967+
}
7968+
7969+
if !matches!(self.context.channel_state, ChannelState::ChannelReady(_)) {
7970+
return Err(ChannelError::Warn(format!("Splicing requested on a channel that is not Ready")));
7971+
}
7972+
7973+
let pre_channel_value = self.context.get_value_satoshis();
7974+
// Sanity check: capacity cannot decrease below 0
7975+
if (pre_channel_value as i64)
7976+
.saturating_add(their_funding_contribution_satoshis)
7977+
.saturating_add(our_funding_contribution_satoshis) < 0
7978+
{
7979+
return Err(ChannelError::Warn(format!(
7980+
"Post-splicing channel value cannot be negative. It was {} + {} + {}",
7981+
pre_channel_value, their_funding_contribution_satoshis, our_funding_contribution_satoshis,
7982+
)));
7983+
}
7984+
7985+
if their_funding_contribution_satoshis.saturating_add(our_funding_contribution_satoshis) < 0 {
7986+
return Err(ChannelError::Warn(format!(
7987+
"Splice-out not supported, only splice in, relative {} + {}",
7988+
their_funding_contribution_satoshis, our_funding_contribution_satoshis,
7989+
)));
7990+
}
7991+
7992+
let post_channel_value = PendingSpliceInfoPre::compute_post_value(pre_channel_value, their_funding_contribution_satoshis, our_funding_contribution_satoshis);
7993+
let post_balance = PendingSpliceInfoPre::add_checked(self.context.value_to_self_msat, our_funding_contribution_satoshis);
7994+
// Early check for reserve requirement, assuming maximum balance of full channel value
7995+
// This will also be checked later at tx_complete
7996+
let _res = self.context.check_balance_meets_reserve_requirements(post_balance, post_channel_value)?;
7997+
7998+
// TODO(splicing): Store msg.funding_pubkey
7999+
// TODO(splicing): Apply start of splice (splice_start)
8000+
8001+
let splice_ack_msg = self.context.get_splice_ack(our_funding_contribution_satoshis);
8002+
// TODO(splicing): start interactive funding negotiation
8003+
Ok(splice_ack_msg)
8004+
}
8005+
8006+
/// Handle splice_ack
8007+
#[cfg(splicing)]
8008+
pub fn splice_ack(&mut self, msg: &msgs::SpliceAck) -> Result<(), ChannelError> {
8009+
let their_funding_contribution_satoshis = msg.funding_contribution_satoshis;
8010+
8011+
// check if splice is pending
8012+
let pending_splice = if let Some(pending_splice) = &self.context.pending_splice_pre {
8013+
pending_splice
8014+
} else {
8015+
return Err(ChannelError::Warn(format!("Channel is not in pending splice")));
8016+
};
8017+
8018+
let our_funding_contribution = pending_splice.our_funding_contribution;
8019+
8020+
let pre_channel_value = self.context.get_value_satoshis();
8021+
let post_channel_value = PendingSpliceInfoPre::compute_post_value(pre_channel_value, our_funding_contribution, their_funding_contribution_satoshis);
8022+
let post_balance = PendingSpliceInfoPre::add_checked(self.context.value_to_self_msat, our_funding_contribution);
8023+
// Early check for reserve requirement, assuming maximum balance of full channel value
8024+
// This will also be checked later at tx_complete
8025+
let _res = self.context.check_balance_meets_reserve_requirements(post_balance, post_channel_value)?;
8026+
Ok(())
8027+
}
78188028

78198029
// Send stuff to our remote peers:
78208030

@@ -10131,6 +10341,9 @@ impl<'a, 'b, 'c, ES: Deref, SP: Deref> ReadableArgs<(&'a ES, &'b SP, u32, &'c Ch
1013110341
// during a signing session, but have not received `tx_signatures` we MUST set `next_funding_txid`
1013210342
// to the txid of that interactive transaction, else we MUST NOT set it.
1013310343
next_funding_txid: None,
10344+
10345+
#[cfg(splicing)]
10346+
pending_splice_pre: None,
1013410347
},
1013510348
interactive_tx_signing_session: None,
1013610349
})
@@ -11915,4 +12128,69 @@ mod tests {
1191512128
assert_eq!(node_a_chan.context.channel_state, ChannelState::AwaitingChannelReady(AwaitingChannelReadyFlags::THEIR_CHANNEL_READY));
1191612129
assert!(node_a_chan.check_get_channel_ready(0, &&logger).is_some());
1191712130
}
12131+
12132+
#[cfg(all(test, splicing))]
12133+
fn get_pre_and_post(pre_channel_value: u64, our_funding_contribution: i64, their_funding_contribution: i64) -> (u64, u64) {
12134+
use crate::ln::channel::PendingSpliceInfoPre;
12135+
12136+
let post_channel_value = PendingSpliceInfoPre::compute_post_value(pre_channel_value, our_funding_contribution, their_funding_contribution);
12137+
(pre_channel_value, post_channel_value)
12138+
}
12139+
12140+
#[cfg(all(test, splicing))]
12141+
#[test]
12142+
fn test_splice_compute_post_value() {
12143+
{
12144+
// increase, small amounts
12145+
let (pre_channel_value, post_channel_value) = get_pre_and_post(9_000, 6_000, 0);
12146+
assert_eq!(pre_channel_value, 9_000);
12147+
assert_eq!(post_channel_value, 15_000);
12148+
}
12149+
{
12150+
// increase, small amounts
12151+
let (pre_channel_value, post_channel_value) = get_pre_and_post(9_000, 4_000, 2_000);
12152+
assert_eq!(pre_channel_value, 9_000);
12153+
assert_eq!(post_channel_value, 15_000);
12154+
}
12155+
{
12156+
// increase, small amounts
12157+
let (pre_channel_value, post_channel_value) = get_pre_and_post(9_000, 0, 6_000);
12158+
assert_eq!(pre_channel_value, 9_000);
12159+
assert_eq!(post_channel_value, 15_000);
12160+
}
12161+
{
12162+
// decrease, small amounts
12163+
let (pre_channel_value, post_channel_value) = get_pre_and_post(15_000, -6_000, 0);
12164+
assert_eq!(pre_channel_value, 15_000);
12165+
assert_eq!(post_channel_value, 9_000);
12166+
}
12167+
{
12168+
// decrease, small amounts
12169+
let (pre_channel_value, post_channel_value) = get_pre_and_post(15_000, -4_000, -2_000);
12170+
assert_eq!(pre_channel_value, 15_000);
12171+
assert_eq!(post_channel_value, 9_000);
12172+
}
12173+
{
12174+
// increase and decrease
12175+
let (pre_channel_value, post_channel_value) = get_pre_and_post(15_000, 4_000, -2_000);
12176+
assert_eq!(pre_channel_value, 15_000);
12177+
assert_eq!(post_channel_value, 17_000);
12178+
}
12179+
let base2: u64 = 2;
12180+
let huge63i3 = (base2.pow(63) - 3) as i64;
12181+
assert_eq!(huge63i3, 9223372036854775805);
12182+
assert_eq!(-huge63i3, -9223372036854775805);
12183+
{
12184+
// increase, large amount
12185+
let (pre_channel_value, post_channel_value) = get_pre_and_post(9_000, huge63i3, 3);
12186+
assert_eq!(pre_channel_value, 9_000);
12187+
assert_eq!(post_channel_value, 9223372036854784807);
12188+
}
12189+
{
12190+
// increase, large amounts
12191+
let (pre_channel_value, post_channel_value) = get_pre_and_post(9_000, huge63i3, huge63i3);
12192+
assert_eq!(pre_channel_value, 9_000);
12193+
assert_eq!(post_channel_value, 9223372036854784807);
12194+
}
12195+
}
1191812196
}

0 commit comments

Comments
 (0)