Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions src/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -610,6 +610,19 @@ impl NodeBuilder {
self
}

/// Sets whether to disable all Lightning peer-to-peer (P2P) connections.
///
/// Updates [`Config::disable_lightning_connections`].
///
/// Defaults to `false`. If `true`, automatic reconnections and explicit outbound connection
/// attempts are disabled for the built node. Inbound listening must also be disabled by
/// setting [`Config::listening_addresses`] to `None` or an empty list;
/// otherwise building fails with [`BuildError::InvalidListeningAddresses`].
pub fn set_disable_lightning_connections(&mut self, disable: bool) -> &mut Self {
self.config.disable_lightning_connections = disable;
self
}

/// Sets the IP address and TCP port on which [`Node`] will listen for incoming network connections.
pub fn set_listening_addresses(
&mut self, listening_addresses: Vec<SocketAddress>,
Expand Down Expand Up @@ -1259,6 +1272,18 @@ impl Builder {
self.inner.write().expect("lock").set_network(network);
}

/// Sets whether to disable all Lightning peer-to-peer (P2P) connections.
///
/// Updates [`Config::disable_lightning_connections`].
///
/// Defaults to `false`. If `true`, automatic reconnections and explicit outbound connection
/// attempts are disabled for the built node. Inbound listening must also be disabled by
/// setting [`Config::listening_addresses`] to `None` or an empty list;
/// otherwise building fails with [`BuildError::InvalidListeningAddresses`].
pub fn set_disable_lightning_connections(&self, disable: bool) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This probably also needs to be exposed in the Uniffi UDL file?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not needed because of these lines further above:

ldk-node/src/builder.rs

Lines 1224 to 1226 in 3bc8309

#[cfg(feature = "uniffi")]
#[uniffi::export]
impl Builder {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, nvm, I forgot that we switched the builder over to macros a while ago 😆

self.inner.write().expect("lock").set_disable_lightning_connections(disable);
}

/// Sets the IP address and TCP port on which [`Node`] will listen for incoming network connections.
pub fn set_listening_addresses(
&self, listening_addresses: Vec<SocketAddress>,
Expand Down Expand Up @@ -1531,6 +1556,16 @@ fn build_with_store_internal(
) -> Result<Node, BuildError> {
optionally_install_rustls_cryptoprovider();

if config.disable_lightning_connections
&& config.listening_addresses.as_ref().is_some_and(|addresses| !addresses.is_empty())
{
log_error!(
logger,
"Listening addresses must be unset or empty when Lightning connections are disabled."
);
return Err(BuildError::InvalidListeningAddresses);
}

if let Err(err) = may_announce_channel(&config) {
if config.announcement_addresses.is_some() {
log_error!(logger, "Announcement addresses were set but some required configuration options for node announcement are missing: {}", err);
Expand Down Expand Up @@ -2431,6 +2466,7 @@ fn build_with_store_internal(

let connection_manager = Arc::new(ConnectionManager::new(
Arc::clone(&peer_manager),
config.disable_lightning_connections,
config.tor_config.clone(),
Arc::clone(&keys_manager),
Arc::clone(&logger),
Expand Down
11 changes: 11 additions & 0 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,7 @@ impl Default for ForwardedPaymentTrackingMode {
/// | `storage_dir_path` | /tmp/ldk_node/ |
/// | `network` | Bitcoin |
/// | `listening_addresses` | None |
/// | `disable_lightning_connections` | false |
/// | `announcement_addresses` | None |
/// | `node_alias` | None |
/// | `trusted_peers_0conf` | [] |
Expand Down Expand Up @@ -286,6 +287,15 @@ pub struct Config {
/// `listening_addresses` are set. When both are set, we also accept payment forwards over
/// unannounced channels.
pub listening_addresses: Option<Vec<SocketAddress>>,
/// Whether to disable all Lightning peer-to-peer (P2P) connections.
///
/// If `true`, automatic reconnections and explicit outbound connection attempts are disabled.
/// [`Config::listening_addresses`] must also be `None` or an empty list; otherwise building
/// fails with [`BuildError::InvalidListeningAddresses`]. Chain synchronization and other
/// non-peer networking are unaffected.
///
/// [`BuildError::InvalidListeningAddresses`]: crate::BuildError::InvalidListeningAddresses
pub disable_lightning_connections: bool,
/// The addresses which the node will announce to the gossip network that it accepts connections on.
///
/// **Note**: If unset, the [`listening_addresses`] will be used as the list of addresses to announce.
Expand Down Expand Up @@ -358,6 +368,7 @@ impl Default for Config {
storage_dir_path: DEFAULT_STORAGE_DIR_PATH.to_string(),
network: DEFAULT_NETWORK,
listening_addresses: None,
disable_lightning_connections: false,
announcement_addresses: None,
trusted_peers_0conf: Vec::new(),
probing_liquidity_limit_multiplier: DEFAULT_PROBING_LIQUIDITY_LIMIT_MULTIPLIER,
Expand Down
21 changes: 17 additions & 4 deletions src/connection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use bitcoin::secp256k1::PublicKey;
use lightning::ln::msgs::SocketAddress;

use crate::config::TorConfig;
use crate::logger::{log_debug, log_error, log_info, LdkLogger};
use crate::logger::{log_debug, log_error, log_info, log_warn, LdkLogger};
use crate::types::{KeysManager, PeerManager};
use crate::Error;

Expand Down Expand Up @@ -57,6 +57,7 @@ where
{
pending_connections: PendingConnections,
peer_manager: Arc<PeerManager>,
disable_lightning_connections: bool,
tor_proxy_config: Option<TorConfig>,
keys_manager: Arc<KeysManager>,
logger: L,
Expand All @@ -67,12 +68,19 @@ where
L::Target: LdkLogger,
{
pub(crate) fn new(
peer_manager: Arc<PeerManager>, tor_proxy_config: Option<TorConfig>,
keys_manager: Arc<KeysManager>, logger: L,
peer_manager: Arc<PeerManager>, disable_lightning_connections: bool,
tor_proxy_config: Option<TorConfig>, keys_manager: Arc<KeysManager>, logger: L,
) -> Self {
let pending_connections = Mutex::new(HashMap::new());

Self { pending_connections, peer_manager, tor_proxy_config, keys_manager, logger }
Self {
pending_connections,
peer_manager,
disable_lightning_connections,
tor_proxy_config,
keys_manager,
logger,
}
}

pub(crate) async fn connect_peer_if_necessary(
Expand Down Expand Up @@ -115,6 +123,11 @@ where
async fn do_connect_peer_internal(
&self, node_id: PublicKey, addr: SocketAddress,
) -> Result<(), Error> {
if self.disable_lightning_connections {
log_warn!(self.logger, "Lightning peer connections are disabled.");

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rather than logging indefinitely, should we just disable the reconnection loop when the flag is enabled?

@tankyleo tankyleo Nov 17, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks done below, the goal is to remove sources of infinite logs, feel free to use --ignore--all-space for this commit.

return Err(Error::ConnectionFailed);
}

log_info!(self.logger, "Connecting to peer: {}@{}", node_id, addr);

match addr {
Expand Down
5 changes: 5 additions & 0 deletions src/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -630,6 +630,11 @@ where
}

fn remove_peer_after_reconnect(&self, peer_info: PeerInfo, closed_channel_id: ChannelId) {
if self.config.disable_lightning_connections {
// Retain the peer for recovery when Lightning connections are enabled again.
return;
}

let channel_manager = Arc::clone(&self.channel_manager);
let connection_manager = Arc::clone(&self.connection_manager);
let peer_store = Arc::clone(&self.peer_store);
Expand Down
152 changes: 83 additions & 69 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -560,41 +560,48 @@ impl Node {
}
}

// Regularly reconnect to persisted peers.
let connect_cm = Arc::clone(&self.connection_manager);
let connect_pm = Arc::clone(&self.peer_manager);
let connect_logger = Arc::clone(&self.logger);
let connect_peer_store = Arc::clone(&self.peer_store);
let mut stop_connect = self.stop_sender.subscribe();
self.runtime.spawn_cancellable_background_task(async move {
let mut interval = tokio::time::interval(PEER_RECONNECTION_INTERVAL);
interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
loop {
tokio::select! {
_ = stop_connect.changed() => {
log_debug!(
connect_logger,
"Stopping reconnecting known peers."
);
return;
}
_ = interval.tick() => {
let pm_peers = connect_pm
.list_peers()
.iter()
.map(|peer| peer.counterparty_node_id)
.collect::<Vec<_>>();

for peer_info in connect_peer_store.list_peers().iter().filter(|info| !pm_peers.contains(&info.node_id)) {
let _ = connect_cm.do_connect_peer(
peer_info.node_id,
peer_info.address.clone(),
).await;
if !self.config.disable_lightning_connections {
// Regularly reconnect to persisted peers.
let connect_cm = Arc::clone(&self.connection_manager);
let connect_pm = Arc::clone(&self.peer_manager);
let connect_logger = Arc::clone(&self.logger);
let connect_peer_store = Arc::clone(&self.peer_store);
let mut stop_connect = self.stop_sender.subscribe();
self.runtime.spawn_cancellable_background_task(async move {
let mut interval = tokio::time::interval(PEER_RECONNECTION_INTERVAL);
interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
loop {
tokio::select! {
_ = stop_connect.changed() => {
log_debug!(
connect_logger,
"Stopping reconnecting known peers."
);
return;
}
}
_ = interval.tick() => {
let pm_peers = connect_pm
.list_peers()
.iter()
.map(|peer| peer.counterparty_node_id)
.collect::<Vec<_>>();

for peer_info in connect_peer_store.list_peers().iter().filter(|info| !pm_peers.contains(&info.node_id)) {
let _ = connect_cm.do_connect_peer(
peer_info.node_id,
peer_info.address.clone(),
).await;
}
}
}
}
}
});
});
} else {
log_info!(
self.logger,
"Lightning peer networking is disabled for both inbound and outbound connections."
);
}

// Regularly broadcast node announcements.
let bcast_cm = Arc::clone(&self.channel_manager);
Expand Down Expand Up @@ -809,17 +816,20 @@ impl Node {
let liquidity_handler = Arc::clone(&self.liquidity_source);
let liquidity_logger = Arc::clone(&self.logger);
let discovery_cm = Arc::clone(&self.connection_manager);
let disable_lightning_connections = self.config.disable_lightning_connections;
self.runtime.spawn_background_task(async move {
// Spawn discovery for configured LSPs in parallel.
let discovery_logger = Arc::clone(&liquidity_logger);
let mut discovery_set = tokio::task::JoinSet::new();
for (node_id, address) in liquidity_handler.get_all_lsp_details() {
let cm = Arc::clone(&discovery_cm);
let logger = Arc::clone(&discovery_logger);
let ls = Arc::clone(&liquidity_handler);
discovery_set.spawn(async move {
connect_and_discover_lsp(&cm, &ls, &logger, node_id, address).await;
});
if !disable_lightning_connections {
for (node_id, address) in liquidity_handler.get_all_lsp_details() {
let cm = Arc::clone(&discovery_cm);
let logger = Arc::clone(&discovery_logger);
let ls = Arc::clone(&liquidity_handler);
discovery_set.spawn(async move {
connect_and_discover_lsp(&cm, &ls, &logger, node_id, address).await;
});
}
}

let mut discovery_done = false;
Expand Down Expand Up @@ -848,38 +858,40 @@ impl Node {
}
});

// Retry protocol discovery for any LSPs that failed the startup batch, backing off up to a
// cap and then retrying at that cap until every configured LSP has been discovered.
let mut stop_retry = self.stop_sender.subscribe();
let retry_ls = Arc::clone(&self.liquidity_source);
let retry_logger = Arc::clone(&self.logger);
let retry_cm = Arc::clone(&self.connection_manager);
self.runtime.spawn_cancellable_background_task(async move {
let mut backoff = LIQUIDITY_DISCOVERY_RETRY_INITIAL_DELAY;
loop {
tokio::select! {
_ = stop_retry.changed() => return,
_ = tokio::time::sleep(backoff) => {},
}
if !self.config.disable_lightning_connections {
// Retry protocol discovery for any LSPs that failed the startup batch, backing off up to a
// cap and then retrying at that cap until every configured LSP has been discovered.
let mut stop_retry = self.stop_sender.subscribe();
let retry_ls = Arc::clone(&self.liquidity_source);
let retry_logger = Arc::clone(&self.logger);
let retry_cm = Arc::clone(&self.connection_manager);
self.runtime.spawn_cancellable_background_task(async move {
let mut backoff = LIQUIDITY_DISCOVERY_RETRY_INITIAL_DELAY;
loop {
tokio::select! {
_ = stop_retry.changed() => return,
_ = tokio::time::sleep(backoff) => {},
}

let undiscovered_lsps = retry_ls.get_undiscovered_lsps();
if undiscovered_lsps.is_empty() {
break;
}
let undiscovered_lsps = retry_ls.get_undiscovered_lsps();
if undiscovered_lsps.is_empty() {
break;
}

let mut discovery_set = tokio::task::JoinSet::new();
for (node_id, address) in undiscovered_lsps {
let cm = Arc::clone(&retry_cm);
let ls = Arc::clone(&retry_ls);
let logger = Arc::clone(&retry_logger);
discovery_set.spawn(async move {
connect_and_discover_lsp(&cm, &ls, &logger, node_id, address).await;
});
let mut discovery_set = tokio::task::JoinSet::new();
for (node_id, address) in undiscovered_lsps {
let cm = Arc::clone(&retry_cm);
let ls = Arc::clone(&retry_ls);
let logger = Arc::clone(&retry_logger);
discovery_set.spawn(async move {
connect_and_discover_lsp(&cm, &ls, &logger, node_id, address).await;
});
}
discovery_set.join_all().await;
backoff = (backoff * 2).min(LIQUIDITY_DISCOVERY_RETRY_MAX_DELAY);
}
discovery_set.join_all().await;
backoff = (backoff * 2).min(LIQUIDITY_DISCOVERY_RETRY_MAX_DELAY);
}
});
});
}

log_info!(self.logger, "Startup complete.");
*is_running_lock = true;
Expand Down Expand Up @@ -1322,6 +1334,8 @@ impl Node {
/// Connect to a node on the peer-to-peer network.
///
/// If `persist` is set to `true`, we'll remember the peer and reconnect to it on restart.
/// Outbound connection attempts fail with [`Error::ConnectionFailed`] if
/// [`Config::disable_lightning_connections`] is set to `true`.
pub fn connect(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, wouldn't we still want to allow manual overrides? I.e. allow the user to selectively connect peers, e.g., to trigger the channel-reestablish recovery flow?

@tankyleo tankyleo Oct 22, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the node that reconnects to peers to trigger the force-closes must not have the stale database, it must be launched from the seed alone. That node will be launched with outbound connections enabled.

If the node with the stale database tries to reconnect with the peers, the channel-reestablish flow causes the node to panic in rust-lightning. That is why we would like to add this disable_outbound_lightning_connections flag here, and also disable manual overrides.

See the full procedure I have in mind here: lightningdevkit/ldk-server#257 (comment)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually I went further and now enforce that inbound connections are disabled as well, see the rationale in the commit message below.

&self, node_id: PublicKey, address: SocketAddress, persist: bool,
) -> Result<(), Error> {
Expand Down
Loading
Loading