From 6d99f4d6382f7412bf0a19ee3dc16a8dd491d4f9 Mon Sep 17 00:00:00 2001 From: benthecarman Date: Wed, 11 Nov 2026 13:38:24 -0600 Subject: [PATCH] Bump LDK to v0.3.0-rc4 Pin every LDK crate to commit 3ed13ee3 on the 0.3 branch, i.e., the v0.3-rc4 tag plus the fix for the Esplora build of lightning-transaction-sync and the re-gating of inbound v2 channel opens. LSPS2 OpenChannel events now carry the client to_self_delay limit agreed upon in the selected opening fee parameters, which the service must enforce itself. We now cap the channel's their_to_self_delay handshake limit accordingly, falling back to our configured limit for events persisted before the field existed. LDK's ChannelConfig gained inbound and outbound splice minimum-depth knobs, which default to six confirmations and no longer follow the channel's own minimum depth. We adopt that default, so splices on zero-conf channels are no longer zero-conf. The test for superseded zero-conf splice rounds, which can no longer occur, is replaced by one covering the new behavior, and the test for a second splice on a zero-conf channel now waits for each splice to confirm. As we don't expose the knobs, our ChannelConfig is applied as a partial update so that it doesn't reset them. LDK now bounds the RBF adjustment of a prior splice contribution by the bump's own maximum feerate rather than the prior round's, so a bump above the prior maximum is paid from the existing inputs where they suffice. The tests relying on such a bump to pull in a new coin now size the first round so its inputs cannot pay the bump. bitcoin-payment-instructions is moved to a fork commit pinned to the same LDK revision so both resolve to a single copy of LDK. Developed with assistance from Claude Code. --- CHANGELOG.md | 9 + Cargo.toml | 30 +-- src/config.rs | 32 +++- src/lib.rs | 15 +- src/liquidity/service/lsps2.rs | 10 + tests/integration_tests_rust.rs | 313 +++++++++++++++++++++----------- 6 files changed, 269 insertions(+), 140 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ef50da0a28..e2f50de582 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -45,6 +45,15 @@ - `BalanceDetails::spendable_onchain_balance_sats` no longer includes wallet outputs selected as inputs of a channel funding transaction or splice that has yet to confirm. They remain part of `total_onchain_balance_sats` until the transaction is seen by a wallet sync. (#1037) +- Splices on zero-conf channels, e.g., with peers in `Config::trusted_peers_0conf` or LSPs + trusted for zero-conf, are no longer zero-conf themselves. Following LDK, a splice now + requires six confirmations before it locks, independent of the channel's own minimum depth. + This also applies to existing channels. +- An LSPS2 service now enforces the `max_client_to_self_delay` agreed upon in the selected + opening fee parameters when opening a JIT channel. If the client's `to_self_delay` exceeds it, + the channel open fails. LDK clients use a `to_self_delay` of 144 blocks by default, so a + service configured with a lower `LSPS2ServiceConfig::max_client_to_self_delay` will fail to + open JIT channels to them. ## Feature and API updates - `Node::splice_out_max` withdraws the maximum available channel balance to an on-chain address. diff --git a/Cargo.toml b/Cargo.toml index ba98aebdd6..eac7ff5c14 100755 --- a/Cargo.toml +++ b/Cargo.toml @@ -86,18 +86,18 @@ uniffi-default = [ #lightning-macros = { version = "0.2.0" } #lightning-dns-resolver = { version = "0.3.0" } -lightning = { git = "https://github.com/lightningdevkit/rust-lightning", rev = "d7a980641c6325ddda5072a0f470ef8392676cf5", features = ["std"] } -lightning-types = { git = "https://github.com/lightningdevkit/rust-lightning", rev = "d7a980641c6325ddda5072a0f470ef8392676cf5" } -lightning-invoice = { git = "https://github.com/lightningdevkit/rust-lightning", rev = "d7a980641c6325ddda5072a0f470ef8392676cf5", features = ["std"] } -lightning-net-tokio = { git = "https://github.com/lightningdevkit/rust-lightning", rev = "d7a980641c6325ddda5072a0f470ef8392676cf5" } -lightning-persister = { git = "https://github.com/lightningdevkit/rust-lightning", rev = "d7a980641c6325ddda5072a0f470ef8392676cf5", features = ["tokio"], optional = true } -lightning-background-processor = { git = "https://github.com/lightningdevkit/rust-lightning", rev = "d7a980641c6325ddda5072a0f470ef8392676cf5" } -lightning-rapid-gossip-sync = { git = "https://github.com/lightningdevkit/rust-lightning", rev = "d7a980641c6325ddda5072a0f470ef8392676cf5" } -lightning-block-sync = { git = "https://github.com/lightningdevkit/rust-lightning", rev = "d7a980641c6325ddda5072a0f470ef8392676cf5", features = ["rest-client", "rpc-client", "tokio"], optional = true } -lightning-transaction-sync = { git = "https://github.com/lightningdevkit/rust-lightning", rev = "d7a980641c6325ddda5072a0f470ef8392676cf5", optional = true } -lightning-liquidity = { git = "https://github.com/lightningdevkit/rust-lightning", rev = "d7a980641c6325ddda5072a0f470ef8392676cf5", features = ["std"] } -lightning-macros = { git = "https://github.com/lightningdevkit/rust-lightning", rev = "d7a980641c6325ddda5072a0f470ef8392676cf5" } -lightning-dns-resolver = { git = "https://github.com/lightningdevkit/rust-lightning", rev = "d7a980641c6325ddda5072a0f470ef8392676cf5", optional = true } +lightning = { git = "https://github.com/lightningdevkit/rust-lightning", rev = "3ed13ee320a10ca98f1bba919e1886b1fc959758", features = ["std"] } +lightning-types = { git = "https://github.com/lightningdevkit/rust-lightning", rev = "3ed13ee320a10ca98f1bba919e1886b1fc959758" } +lightning-invoice = { git = "https://github.com/lightningdevkit/rust-lightning", rev = "3ed13ee320a10ca98f1bba919e1886b1fc959758", features = ["std"] } +lightning-net-tokio = { git = "https://github.com/lightningdevkit/rust-lightning", rev = "3ed13ee320a10ca98f1bba919e1886b1fc959758" } +lightning-persister = { git = "https://github.com/lightningdevkit/rust-lightning", rev = "3ed13ee320a10ca98f1bba919e1886b1fc959758", features = ["tokio"], optional = true } +lightning-background-processor = { git = "https://github.com/lightningdevkit/rust-lightning", rev = "3ed13ee320a10ca98f1bba919e1886b1fc959758" } +lightning-rapid-gossip-sync = { git = "https://github.com/lightningdevkit/rust-lightning", rev = "3ed13ee320a10ca98f1bba919e1886b1fc959758" } +lightning-block-sync = { git = "https://github.com/lightningdevkit/rust-lightning", rev = "3ed13ee320a10ca98f1bba919e1886b1fc959758", features = ["rest-client", "rpc-client", "tokio"], optional = true } +lightning-transaction-sync = { git = "https://github.com/lightningdevkit/rust-lightning", rev = "3ed13ee320a10ca98f1bba919e1886b1fc959758", optional = true } +lightning-liquidity = { git = "https://github.com/lightningdevkit/rust-lightning", rev = "3ed13ee320a10ca98f1bba919e1886b1fc959758", features = ["std"] } +lightning-macros = { git = "https://github.com/lightningdevkit/rust-lightning", rev = "3ed13ee320a10ca98f1bba919e1886b1fc959758" } +lightning-dns-resolver = { git = "https://github.com/lightningdevkit/rust-lightning", rev = "3ed13ee320a10ca98f1bba919e1886b1fc959758", optional = true } bdk_chain = { version = "0.23.3", default-features = false, features = ["std"] } bdk_esplora = { version = "0.22.2", default-features = false, features = ["async-https-rustls", "tokio"], optional = true } @@ -133,14 +133,14 @@ postgres-native-tls = { version = "0.5", default-features = false, features = [" vss-client = { package = "vss-client-ng", version = "0.6", optional = true } prost = { version = "0.11.6", default-features = false, optional = true} #bitcoin-payment-instructions = { version = "0.6" } -bitcoin-payment-instructions = { git = "https://github.com/benthecarman/bitcoin-payment-instructions", rev = "3dbe11bdf8916639df42476501fb40f87b253e84", optional = true } +bitcoin-payment-instructions = { git = "https://github.com/benthecarman/bitcoin-payment-instructions", rev = "7b082636f8136fbc298c1c0a567245b0df7821d7", optional = true } [target.'cfg(windows)'.dependencies] winapi = { version = "0.3", features = ["winbase"] } [dev-dependencies] -lightning = { git = "https://github.com/lightningdevkit/rust-lightning", rev = "d7a980641c6325ddda5072a0f470ef8392676cf5", features = ["std", "_test_utils"] } -lightning-persister = { git = "https://github.com/lightningdevkit/rust-lightning", rev = "d7a980641c6325ddda5072a0f470ef8392676cf5", features = ["tokio"] } +lightning = { git = "https://github.com/lightningdevkit/rust-lightning", rev = "3ed13ee320a10ca98f1bba919e1886b1fc959758", features = ["std", "_test_utils"] } +lightning-persister = { git = "https://github.com/lightningdevkit/rust-lightning", rev = "3ed13ee320a10ca98f1bba919e1886b1fc959758", features = ["tokio"] } rand = { version = "0.9.2", default-features = false, features = ["std", "thread_rng", "os_rng"] } proptest = "1.0.0" regex = "1.5.6" diff --git a/src/config.rs b/src/config.rs index 31dfaafaa2..12640cb85b 100644 --- a/src/config.rs +++ b/src/config.rs @@ -18,7 +18,8 @@ use lightning::ln::msgs::SocketAddress; use lightning::routing::gossip::NodeAlias; use lightning::routing::router::{RouteParameters, RouteParametersConfig}; use lightning::util::config::{ - ChannelConfig as LdkChannelConfig, MaxDustHTLCExposure as LdkMaxDustHTLCExposure, UserConfig, + ChannelConfig as LdkChannelConfig, ChannelConfigUpdate, + MaxDustHTLCExposure as LdkMaxDustHTLCExposure, UserConfig, }; use crate::logger::LogLevel; @@ -862,19 +863,34 @@ impl From for ChannelConfig { } } -impl From for LdkChannelConfig { +/// Only sets the fields we expose, leaving any other settings of a channel's [`LdkChannelConfig`], +/// such as its splice minimum depths, untouched when applied. +impl From for ChannelConfigUpdate { fn from(value: ChannelConfig) -> Self { Self { - forwarding_fee_proportional_millionths: value.forwarding_fee_proportional_millionths, - forwarding_fee_base_msat: value.forwarding_fee_base_msat, - cltv_expiry_delta: value.cltv_expiry_delta, - max_dust_htlc_exposure: value.max_dust_htlc_exposure.into(), - force_close_avoidance_max_fee_satoshis: value.force_close_avoidance_max_fee_satoshis, - accept_underpaying_htlcs: value.accept_underpaying_htlcs, + forwarding_fee_proportional_millionths: Some( + value.forwarding_fee_proportional_millionths, + ), + forwarding_fee_base_msat: Some(value.forwarding_fee_base_msat), + cltv_expiry_delta: Some(value.cltv_expiry_delta), + max_dust_htlc_exposure_msat: Some(value.max_dust_htlc_exposure.into()), + force_close_avoidance_max_fee_satoshis: Some( + value.force_close_avoidance_max_fee_satoshis, + ), + accept_underpaying_htlcs: Some(value.accept_underpaying_htlcs), + ..Default::default() } } } +impl From for LdkChannelConfig { + fn from(value: ChannelConfig) -> Self { + let mut config = LdkChannelConfig::default(); + config.apply(&value.into()); + config + } +} + impl Default for ChannelConfig { fn default() -> Self { LdkChannelConfig::default().into() diff --git a/src/lib.rs b/src/lib.rs index 87dd434d51..d0ddfab3d3 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1507,7 +1507,7 @@ impl Node { let mut user_config = default_user_config(&self.config); user_config.channel_handshake_config.announce_for_forwarding = announce_for_forwarding; - user_config.channel_config = (channel_config.unwrap_or_default()).clone().into(); + user_config.channel_config.apply(&channel_config.unwrap_or_default().into()); // Unannounced channels rely on LDK's default of 100% inbound HTLC value-in-flight // to support large initial payments via LSPS2. @@ -2397,9 +2397,8 @@ impl Node { /// with [`Node::splice_out_max`]; the output is not reduced to cover the higher fee. /// /// A splice of all on-chain funds (see [`Node::splice_in_with_all`]) has no amount to preserve: - /// the bump is paid by adding less to the channel, or, if the pending splice's maximum feerate - /// does not allow that or less than dust would be left to add, the splice is rebuilt from all - /// confirmed funds, including any confirmed since. + /// the bump is paid by adding less to the channel, or, if that would leave less than dust to + /// add, the splice is rebuilt from all confirmed funds, including any confirmed since. /// /// If `min_fee_rate` is set, it will be used as the minimum feerate for the replacement instead /// of a feerate estimate retrieved from the configured chain source. As with the estimate, we @@ -2466,8 +2465,8 @@ impl Node { None }, Ok(contribution) => Some(contribution), - // LDK adjusts a contribution of manually selected inputs only up to its maximum - // feerate and never supplements it by coin selection. + // LDK adjusts a contribution of manually selected inputs only as far as its inputs + // can pay and never supplements it by coin selection. Err(FundingContributionError::ManuallySelectedInputsInsufficient) => None, Err(e) => { log_error!(self.logger, "Failed to RBF channel: {}", e); @@ -2667,10 +2666,10 @@ impl Node { open_channels.iter().find(|c| c.user_channel_id == user_channel_id.0) { self.channel_manager - .update_channel_config( + .update_partial_channel_config( &counterparty_node_id, &[channel_details.channel_id], - &(channel_config).clone().into(), + &channel_config.into(), ) .map_err(|_| Error::ChannelConfigUpdateFailed) } else { diff --git a/src/liquidity/service/lsps2.rs b/src/liquidity/service/lsps2.rs index 9357e6eb48..3dfe36e5c4 100644 --- a/src/liquidity/service/lsps2.rs +++ b/src/liquidity/service/lsps2.rs @@ -408,6 +408,7 @@ where opening_fee_msat: _, user_channel_id, intercept_scid: _, + max_client_to_self_delay, } => { if self.liquidity_manager.lsps2_service_handler().is_none() { log_error!(self.logger, "Failed to handle LSPS2ServiceEvent as LSPS2 liquidity service was not configured.",); @@ -524,6 +525,15 @@ where config.channel_config.forwarding_fee_base_msat = 0; config.channel_config.forwarding_fee_proportional_millionths = 0; + // Ensure the client's `to_self_delay` doesn't exceed the limit agreed upon in the + // selected opening fee parameters. Events persisted before the limit was carried + // in the event fall back to our currently configured limit. + let max_client_to_self_delay = + max_client_to_self_delay.unwrap_or(service_config.max_client_to_self_delay); + let their_to_self_delay = &mut config.channel_handshake_limits.their_to_self_delay; + *their_to_self_delay = + (*their_to_self_delay as u32).min(max_client_to_self_delay) as u16; + let result = if service_config.disable_client_reserve { self.channel_manager.create_channel_to_trusted_peer_0reserve( their_network_key, diff --git a/tests/integration_tests_rust.rs b/tests/integration_tests_rust.rs index 3a1aa73347..6aa177a3d6 100644 --- a/tests/integration_tests_rust.rs +++ b/tests/integration_tests_rust.rs @@ -3439,9 +3439,10 @@ async fn splice_channel() { ); } -/// Two splices of this node in flight on a zero-conf channel — the second submitted right after -/// the first locked — are two payments: the second splice's round is recorded under an id of its -/// own rather than under the first splice's record. +/// Two splices of this node on a zero-conf channel — the second submitted right after the first +/// locked — are two payments: the second splice's round is recorded under an id of its own rather +/// than under the first splice's record. The splices themselves are not zero-conf: each locks +/// once it reaches the default splice minimum depth. /// /// Pinned to Esplora, as the sibling below is: both wait for a record of a splice round that is /// still unconfirmed, and wallet sync creates it from what the wallet has seen. A bitcoind chain @@ -3450,7 +3451,7 @@ async fn splice_channel() { /// it confirms. #[cfg(feature = "chain-esplora")] #[tokio::test(flavor = "multi_thread", worker_threads = 1)] -async fn zero_conf_queued_splice_is_recorded_as_its_own_payment() { +async fn zero_conf_channel_second_splice_is_recorded_as_its_own_payment() { let (bitcoind, electrsd) = setup_bitcoind_and_electrsd(); let chain_source = TestChainSource::Esplora(&electrsd); @@ -3459,7 +3460,7 @@ async fn zero_conf_queued_splice_is_recorded_as_its_own_payment() { config_b.node_config.trusted_peers_0conf.push(node_a.node_id()); let node_b = setup_node(&chain_source, config_b); - // Two coins: the second splice-in below cannot spend the first one's unconfirmed change. + // Two coins, one for each splice-in. let address_a = node_a.onchain_payment().new_address().unwrap(); let second_address_a = node_a.onchain_payment().new_address().unwrap(); premine_and_distribute_funds( @@ -3481,14 +3482,21 @@ async fn zero_conf_queued_splice_is_recorded_as_its_own_payment() { node_a.splice_in(&user_channel_id_a, node_b.node_id(), 1_000_000, None).unwrap(); let first = expect_splice_negotiated_event!(node_a, node_b.node_id()); wait_for_classified_funding_payment(&node_a, first.txid).await; - // The zero-conf splice locks without confirmations, re-signaled as `ChannelReady`. + // The splice locks once confirmed, re-signaled as `ChannelReady`. + wait_for_tx(&electrsd.client, first.txid).await; + generate_blocks_and_wait(&bitcoind.client, &electrsd.client, 6).await; + node_a.sync_wallets().unwrap(); + node_b.sync_wallets().unwrap(); expect_channel_ready_event!(node_a, node_b.node_id()); expect_channel_ready_event!(node_b, node_a.node_id()); - node_a.sync_wallets().unwrap(); node_a.splice_in(&user_channel_id_a, node_b.node_id(), 1_000_000, None).unwrap(); let second = expect_splice_negotiated_event!(node_a, node_b.node_id()); wait_for_classified_funding_payment(&node_a, second.txid).await; + wait_for_tx(&electrsd.client, second.txid).await; + generate_blocks_and_wait(&bitcoind.client, &electrsd.client, 6).await; + node_a.sync_wallets().unwrap(); + node_b.sync_wallets().unwrap(); expect_channel_ready_event!(node_a, node_b.node_id()); expect_channel_ready_event!(node_b, node_a.node_id()); @@ -4218,33 +4226,55 @@ async fn run_splice_in_with_all_bump_fee_test(per_channel_reserve_sats: Option 0); + let balances = node_b.list_balances(); + assert_eq!(balances.total_onchain_balance_sats, first_coin_amount_sat); + assert_eq!(balances.total_anchor_channels_reserve_sats, anchor_reserve_sats); - // Well above the regtest estimate, so the bump below exceeds 1.5 times this feerate without - // the estimate having a say. - let fee_rate = FeeRate::from_sat_per_kwu(1_000); node_b.splice_in_with_all(&user_channel_id_b, node_a.node_id(), Some(fee_rate.into())).unwrap(); let original_txo = expect_splice_negotiated_event!(node_b, node_a.node_id()); @@ -4293,17 +4321,12 @@ async fn splice_in_with_all_bump_fee_above_max_feerate_adds_new_coins() { let original_fee_msat = original.fee_paid_msat.expect("splice payment has a fee"); assert_eq!( original_amount_msat + original_fee_msat, - (premine_amount_sat - anchor_reserve_sats) * 1000, + (first_coin_amount_sat - anchor_reserve_sats) * 1000, ); - // Above the first round's maximum feerate. - // TODO: Once the LDK pin includes - // https://git.rust-bitcoin.org/lightningdevkit/rust-lightning/pulls/5297, the adjustment is - // bounded by the bump's own maximum and succeeds in place, so the bump keeps the first round's - // inputs and the coin assertion below fails. Make the first round's inputs unable to cover the - // bump's fee instead, sized as in `splice_in_with_all_bump_fee_leaving_dust_fails`, so the - // rebuild is still what adds the coin. - let bump_fee_rate = FeeRate::from_sat_per_kwu(2_000); + // At the pending splice's maximum feerate, paying the bump from the same inputs would leave + // less than dust to add to the channel. + let bump_fee_rate = FeeRate::from_sat_per_kwu(3_000); node_b .bump_channel_funding_fee(&user_channel_id_b, node_a.node_id(), Some(bump_fee_rate.into())) .unwrap(); @@ -4329,7 +4352,7 @@ async fn splice_in_with_all_bump_fee_above_max_feerate_adds_new_coins() { assert!(bumped_amount_msat > original_amount_msat, "the new coin was not added"); assert_eq!( bumped_amount_msat + bumped_fee_msat, - (premine_amount_sat + coin_amount_sat - anchor_reserve_sats) * 1000, + (first_coin_amount_sat + coin_amount_sat - anchor_reserve_sats) * 1000, ); generate_blocks_and_wait(&bitcoind.client, &electrsd.client, 6).await; @@ -4974,9 +4997,6 @@ const RECLAIMED_ADDRESSES: &str = "Reclaiming unused wallet state from channel"; /// Unlike [`CLOSED_CHANNEL_PAYMENT_RESOLVED`], logged whatever was found, so also when no payment /// of the channel is left to resolve. const CLOSED_CHANNEL_ROUNDS_RESOLVED: &str = "round(s) its monitor watches"; -/// Logged by a node as it records that LDK promoted a splice round of ours to the channel's -/// funding. -const ROUND_LOCKED: &str = "locked as the funding of channel"; /// A splice round this node signed keeps its place in the channel's recorded splice history when /// the channel closes before the counterparty's `tx_signatures` arrive, if the channel's monitor @@ -5373,20 +5393,17 @@ async fn signed_splice_round_the_monitor_does_not_watch_is_dropped_at_close() { node_b.stop().unwrap(); } -/// A zero-conf splice round of ours stays recorded when the channel closes after a later splice -/// built on it. LDK promoted the round to the funding as `splice_locked` was exchanged, before its -/// transaction confirmed, and moved on again as the later splice locked, so at the close neither -/// the channel manager lists the round nor the monitor watches it — although it can still confirm, -/// the later round and the commitment transaction both descending from it. Node A splices into its -/// zero-conf channel with node B, then splices out of it, and force-closes before either round -/// confirms; the first round's payment is kept, and both graduate once the rounds confirm. Pinned -/// to Esplora so the wallet syncs only on demand. +/// Splices on a zero-conf channel are not zero-conf themselves: LDK requires the channel's +/// `inbound_splice_min_depth` and `outbound_splice_min_depth`, which default to six, independent of +/// the channel's own minimum depth. Node B accepts node A's channel as zero-conf, yet node A's +/// splice only locks once it has six confirmations. Pinned to Esplora so the wallet syncs only on +/// demand. #[cfg(feature = "chain-esplora")] #[tokio::test(flavor = "multi_thread", worker_threads = 1)] -async fn superseded_zero_conf_splice_round_keeps_its_payment_at_close() { +async fn splice_on_zero_conf_channel_requires_confirmations() { let (bitcoind, electrsd) = setup_bitcoind_and_electrsd(); let chain_source = TestChainSource::Esplora(&electrsd); - let (node_a, logs_a) = setup_logged_node(&chain_source, random_config()); + let node_a = setup_node(&chain_source, random_config()); let mut config_b = random_config(); config_b.node_config.trusted_peers_0conf.push(node_a.node_id()); let node_b = setup_node(&chain_source, config_b); @@ -5401,57 +5418,32 @@ async fn superseded_zero_conf_splice_round_keeps_its_payment_at_close() { .await; node_a.sync_wallets().unwrap(); + // The channel itself is zero-conf, so it is ready before its funding confirms. open_channel(&node_a, &node_b, 2_000_000, false, &electrsd).await; let user_channel_id_a = expect_channel_ready_event!(node_a, node_b.node_id()); expect_channel_ready_event!(node_b, node_a.node_id()); - // Confirm the original funding so the splices below are the only unconfirmed rounds and node - // A's change from the open is spendable for the splice-in. generate_blocks_and_wait(&bitcoind.client, &electrsd.client, 6).await; node_a.sync_wallets().unwrap(); node_b.sync_wallets().unwrap(); node_a.splice_in(&user_channel_id_a, node_b.node_id(), 1_000_000, None).unwrap(); - let first = expect_splice_negotiated_event!(node_a, node_b.node_id()); - wait_for_classified_funding_payment(&node_a, first.txid).await; - // The zero-conf splice locks without confirmations, re-signaled as `ChannelReady`, and node A - // records the promotion as it handles it. - expect_channel_ready_event!(node_a, node_b.node_id()); - expect_channel_ready_event!(node_b, node_a.node_id()); - assert_eq!(logs_a.count(ROUND_LOCKED), 1, "the promotion of the first round was not recorded"); + let splice = expect_splice_negotiated_event!(node_a, node_b.node_id()); + wait_for_classified_funding_payment(&node_a, splice.txid).await; + wait_for_tx(&electrsd.client, splice.txid).await; - let address = node_a.onchain_payment().new_address().unwrap(); - node_a.splice_out(&user_channel_id_a, node_b.node_id(), &address, 500_000, None).unwrap(); - let second = expect_splice_negotiated_event!(node_a, node_b.node_id()); - wait_for_classified_funding_payment(&node_a, second.txid).await; - expect_channel_ready_event!(node_a, node_b.node_id()); - expect_channel_ready_event!(node_b, node_a.node_id()); - assert_eq!(logs_a.count(ROUND_LOCKED), 2, "the promotion of the second round was not recorded"); - assert_eq!(funding_payment(&node_a, first.txid).status, PaymentStatus::Pending); - assert_eq!(funding_payment(&node_a, second.txid).status, PaymentStatus::Pending); - - node_a.force_close_channel(&user_channel_id_a, node_b.node_id(), None).unwrap(); - expect_event!(node_a, ChannelClosed); - assert!( - logs_a.wait_for_count(CLOSED_CHANNEL_PAYMENT_RESOLVED, 2).await, - "the close did not resolve both funding payments" - ); - assert!(!logs_a.contains(NO_ROUND_CAN_CONFIRM), "the superseded round's payment was failed"); - assert_eq!(funding_payment(&node_a, first.txid).status, PaymentStatus::Pending); - assert_eq!(funding_payment(&node_a, second.txid).status, PaymentStatus::Pending); + // One confirmation short of the default splice minimum depth, the splice does not lock. + generate_blocks_and_wait(&bitcoind.client, &electrsd.client, 5).await; + node_a.sync_wallets().unwrap(); + node_b.sync_wallets().unwrap(); + tokio::time::sleep(std::time::Duration::from_secs(2)).await; + assert_eq!(node_a.next_event(), None); + assert_eq!(node_b.next_event(), None); - // Both rounds confirm, the second spending the first, and the payments graduate. Six blocks are - // the exact minimum, so wait for the rounds to reach the chain source before mining them. - wait_for_tx(&electrsd.client, second.txid).await; - generate_blocks_and_wait(&bitcoind.client, &electrsd.client, 6).await; + generate_blocks_and_wait(&bitcoind.client, &electrsd.client, 1).await; node_a.sync_wallets().unwrap(); - for txid in [first.txid, second.txid] { - let payment = funding_payment(&node_a, txid); - assert_eq!(payment.status, PaymentStatus::Succeeded, "round {} did not graduate", txid); - assert!(matches!( - payment.kind, - PaymentKind::Onchain { status: ConfirmationStatus::Confirmed { .. }, .. } - )); - } + node_b.sync_wallets().unwrap(); + expect_channel_ready_event!(node_a, node_b.node_id()); + expect_channel_ready_event!(node_b, node_a.node_id()); node_a.stop().unwrap(); node_b.stop().unwrap(); @@ -5463,20 +5455,20 @@ async fn superseded_zero_conf_splice_round_keeps_its_payment_at_close() { /// pass and on peer traffic, and the monitor's own events are handled right after the manager's. /// Each event then finds the channel listed and, both rounds having been broadcast, only returns /// the round's contribution, leaving the payment to the `ChannelClosed` that follows, which fails -/// it, no round of ours being watched anymore. Node A splices into its channel with node B and, -/// once another coin has confirmed, bumps the round's fee past its maximum feerate, so the bump is -/// rebuilt with that coin and the two rounds are contributions of their own; node B closes while -/// node A's event handler sits in a blocked event-queue write — for a channel node C opened to it — -/// until the close and its maturity are synced. Pinned to Esplora so the wallet syncs only on -/// demand. +/// it, no round of ours being watched anymore. Node A splices into its channel with node B, +/// leaving no change, and, once another coin has confirmed, bumps the round's fee, which coin +/// selection draws from that coin, so the two rounds are contributions of their own; node B +/// closes while node A's event handler sits in a blocked event-queue write — for a channel node C +/// opened to it — until the close and its maturity are synced. Pinned to Esplora so the wallet +/// syncs only on demand. #[cfg(feature = "chain-esplora")] #[tokio::test(flavor = "multi_thread", worker_threads = 1)] async fn splice_rounds_discarded_while_the_channel_is_listed_fail_at_close() { let (bitcoind, electrsd) = setup_bitcoind_and_electrsd(); let chain_source = TestChainSource::Esplora(&electrsd); let node_b = setup_node(&chain_source, random_config()); - // Keeping no anchor reserve back from node B, node A's splice-in takes its whole balance into - // the funding, with no output of its own. + // Keeping no anchor reserve back from node B, node A's splice-in can take nearly its whole + // balance into the funding, with no output of its own. let mut config_a = random_config(); config_a.node_config.anchor_channels_config.trusted_peers_no_reserve.push(node_b.node_id()); let (node_a, store_a, logs_a) = @@ -5503,14 +5495,18 @@ async fn splice_rounds_discarded_while_the_channel_is_listed_fail_at_close() { let user_channel_id_a = expect_channel_ready_event!(node_a, node_b.node_id()); let user_channel_id_b = expect_channel_ready_event!(node_b, node_a.node_id()); - // Node B contributes nothing to either round, so only node A hears of them. - node_a.splice_in_with_all(&user_channel_id_a, node_b.node_id(), None).unwrap(); + // Node B contributes nothing to either round, so only node A hears of them. The splice-in + // spends node A's only coin, leaving less than dust over its fee of about 220 sats, which goes + // to the fee rather than to change. + let splice_amount_sat = node_a.list_balances().spendable_onchain_balance_sats - 400; + node_a.splice_in(&user_channel_id_a, node_b.node_id(), splice_amount_sat, None).unwrap(); let first_txo = expect_splice_negotiated_event!(node_a, node_b.node_id()); let first_round = wait_for_transaction(&bitcoind, &electrsd, first_txo.txid).await; wait_for_classified_funding_payment(&node_a, first_txo.txid).await; assert_eq!(first_round.output.len(), 1, "the splice-in left change"); - // The wallet learns the round from the sync and gets a fresh coin. The bump asks for more than - // the round's maximum feerate allows, so it is rebuilt from the round's inputs and the coin. + // The wallet learns the round from the sync and gets a fresh coin. With no change to pay the + // bump's higher fee from, coin selection runs again and funds the bump from the coin alone, the + // round's own input being spent by the round. node_a.sync_wallets().unwrap(); let coin_address = node_a.onchain_payment().new_address().unwrap(); let coin_txid = distribute_funds_unconfirmed( @@ -5523,12 +5519,6 @@ async fn splice_rounds_discarded_while_the_channel_is_listed_fail_at_close() { mine_block_with(&bitcoind, &electrsd, &[raw_transaction_hex(&bitcoind, coin_txid)]).await; node_a.sync_wallets().unwrap(); - // Past the first round's maximum feerate, so the bump is rebuilt with the coin. - // TODO: Once the LDK pin includes - // https://git.rust-bitcoin.org/lightningdevkit/rust-lightning/pulls/5297, the adjustment is - // bounded by the bump's own maximum and succeeds in place, so the bump keeps the first round's - // inputs and the input assertions below fail. Make the first round a fixed-amount `splice_in` - // that leaves no change instead, with coin selection then drawing the bump's fee from the coin. let bump_fee_rate = FeeRate::from_sat_per_kwu(1_000); node_a .bump_channel_funding_fee(&user_channel_id_a, node_b.node_id(), Some(bump_fee_rate.into())) @@ -5540,10 +5530,12 @@ async fn splice_rounds_discarded_while_the_channel_is_listed_fail_at_close() { let first_inputs: Vec<_> = first_round.input.iter().map(|input| input.previous_output).collect(); let bump_inputs: Vec<_> = bump_round.input.iter().map(|input| input.previous_output).collect(); - assert!( - first_inputs.iter().all(|outpoint| bump_inputs.contains(outpoint)), - "the bump did not reuse the first round's inputs" - ); + // Both rounds spend the channel's funding output; beyond it, the bump swaps the round's input + // for the coin. + assert!(bump_inputs.contains(&funding_txo), "the bump did not spend the funding output"); + let dropped_inputs: Vec<_> = + first_inputs.iter().filter(|outpoint| !bump_inputs.contains(outpoint)).collect(); + assert_eq!(dropped_inputs.len(), 1, "the bump kept the round's own input"); let added_inputs: Vec<_> = bump_inputs.iter().filter(|outpoint| !first_inputs.contains(outpoint)).collect(); assert_eq!(added_inputs.len(), 1, "the bump added more than the coin"); @@ -5595,7 +5587,7 @@ async fn splice_rounds_discarded_while_the_channel_is_listed_fail_at_close() { kept_before, "a discard while the channel was listed resolved the payment" ); - // The bump added the coin to the first round's inputs, so each round's discard carries a + // The bump spends the coin in place of the round's input, so each round's discard carries a // contribution of its own to return. assert_eq!( logs_a.count(RECLAIMED_ADDRESSES), @@ -7913,6 +7905,109 @@ async fn drop_in_async_context() { node.stop().unwrap(); } +/// The LSPS2 service only opens a JIT channel if the client's `to_self_delay` stays within the +/// `max_client_to_self_delay` agreed upon in the selected opening fee parameters. The client uses +/// LDK's default of `BREAKDOWN_TIMEOUT`, so a limit one block below it aborts the open, while a +/// limit equal to it lets the open go through. +#[tokio::test(flavor = "multi_thread", worker_threads = 1)] +async fn lsps2_service_enforces_max_client_to_self_delay() { + do_lsps2_service_enforces_max_client_to_self_delay(BREAKDOWN_TIMEOUT as u32 - 1, false).await; + do_lsps2_service_enforces_max_client_to_self_delay(BREAKDOWN_TIMEOUT as u32, true).await; +} + +async fn do_lsps2_service_enforces_max_client_to_self_delay( + max_client_to_self_delay: u32, expect_open: bool, +) { + let (bitcoind, electrsd) = setup_bitcoind_and_electrsd(); + let esplora_url = format!("http://{}", electrsd.esplora_url.as_ref().unwrap()); + + let mut sync_config = EsploraSyncConfig::default(); + sync_config.background_sync_config = None; + + let lsps2_service_config = LSPS2ServiceConfig { + require_token: None, + advertise_service: false, + channel_opening_fee_ppm: 10_000, + channel_over_provisioning_ppm: 100_000, + max_payment_size_msat: 1_000_000_000, + min_payment_size_msat: 0, + min_channel_lifetime: 100, + min_channel_opening_fee_msat: 1_000, + max_client_to_self_delay, + client_trusts_lsp: false, + disable_client_reserve: false, + }; + + let service_config = random_config(); + setup_builder!(service_builder, service_config.node_config); + service_builder.set_chain_source_esplora(esplora_url.clone(), Some(sync_config)); + service_builder.enable_liquidity_provider(lsps2_service_config); + let service_node = service_builder.build(service_config.node_entropy.into()).unwrap(); + service_node.start().unwrap(); + + let service_node_id = service_node.node_id(); + let service_addr = service_node.listening_addresses().unwrap().first().unwrap().clone(); + + let client_config = random_config(); + setup_builder!(client_builder, client_config.node_config); + client_builder.set_chain_source_esplora(esplora_url.clone(), Some(sync_config)); + client_builder.add_liquidity_source(service_node_id, service_addr, None, false); + let client_node = client_builder.build(client_config.node_entropy.into()).unwrap(); + client_node.start().unwrap(); + + let payer_config = random_config(); + setup_builder!(payer_builder, payer_config.node_config); + payer_builder.set_chain_source_esplora(esplora_url.clone(), Some(sync_config)); + let payer_node = payer_builder.build(payer_config.node_entropy.into()).unwrap(); + payer_node.start().unwrap(); + + let service_addr = service_node.onchain_payment().new_address().unwrap(); + let payer_addr = payer_node.onchain_payment().new_address().unwrap(); + premine_and_distribute_funds( + &bitcoind.client, + &electrsd.client, + vec![service_addr, payer_addr], + Amount::from_sat(10_000_000), + ) + .await; + service_node.sync_wallets().unwrap(); + payer_node.sync_wallets().unwrap(); + + open_channel(&payer_node, &service_node, 5_000_000, false, &electrsd).await; + generate_blocks_and_wait(&bitcoind.client, &electrsd.client, 6).await; + service_node.sync_wallets().unwrap(); + payer_node.sync_wallets().unwrap(); + expect_channel_ready_event!(payer_node, service_node.node_id()); + expect_channel_ready_event!(service_node, payer_node.node_id()); + + let invoice_description = + Bolt11InvoiceDescription::Direct(Description::new(String::from("asdf")).unwrap()); + let jit_invoice = client_node + .bolt11_payment() + .receive_via_jit_channel(100_000_000, &invoice_description.into(), 1024) + .unwrap(); + payer_node.bolt11_payment().send(&jit_invoice, None).unwrap(); + + if expect_open { + expect_channel_pending_event!(service_node, client_node.node_id()); + expect_channel_pending_event!(client_node, service_node.node_id()); + } else { + // The client's `accept_channel` exceeds our `to_self_delay` limit, so the channel is + // closed before it is ever funded. + expect_event!(service_node, ChannelClosed); + expect_event!(client_node, ChannelClosed); + assert!(service_node + .list_channels() + .iter() + .all(|c| c.counterparty.node_id != client_node.node_id())); + assert!(client_node.list_channels().is_empty()); + } + + service_node.stop().unwrap(); + client_node.stop().unwrap(); + payer_node.stop().unwrap(); +} + #[tokio::test(flavor = "multi_thread", worker_threads = 1)] async fn lsps2_client_trusts_lsp() { let (bitcoind, electrsd) = setup_bitcoind_and_electrsd();