From 87dd7e490525a72c410a5b34a32113bb25186a79 Mon Sep 17 00:00:00 2001 From: Vincenzo Palazzo Date: Thu, 3 Dec 2026 12:42:15 +0100 Subject: [PATCH 1/2] Add PeerStore::upsert_peer for replacing a stored address Replaces the stored address through the persist-first update_peers path from #1234. No-ops when the peer is already stored at the same address. Co-authored-by: Bartok <259807879+Bartok9@users.noreply.github.com> Assisted-by: Cursor Grok (AI) Co-authored-by: Cursor --- src/peer_store.rs | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/src/peer_store.rs b/src/peer_store.rs index 6856730893..d5725c3aca 100644 --- a/src/peer_store.rs +++ b/src/peer_store.rs @@ -55,6 +55,22 @@ where .await } + /// Stores `peer_info`, replacing the address when it differs. + /// + /// No-ops when the peer is already stored at the same address. Callers must only pass an + /// address that was just dialed successfully: an unverified address must not overwrite a + /// working one. Use [`Self::add_peer`] when the address may not have been dialed. + pub(crate) async fn upsert_peer(&self, peer_info: PeerInfo) -> Result<(), Error> { + self.update_peers(|peers| match peers.get(&peer_info.node_id) { + Some(existing) if existing == &peer_info => false, + _ => { + peers.insert(peer_info.node_id, peer_info); + true + }, + }) + .await + } + pub(crate) async fn remove_peer(&self, node_id: &PublicKey) -> Result<(), Error> { self.update_peers(|peers| peers.remove(node_id).is_some()).await } @@ -357,4 +373,19 @@ mod tests { // store holds, it has to be written regardless. assert_eq!(Err(Error::PersistenceFailed), peer_store.remove_peer(&peer_info.node_id).await); } + + #[tokio::test] + async fn upsert_peer_replaces_stored_address() { + let store: Arc = Arc::new(DynStoreWrapper(InMemoryStore::new())); + let peer_store = PeerStore::new(store, Arc::new(TestLogger::new())); + + let old = test_peer_info(); + let new = PeerInfo { + node_id: old.node_id, + address: SocketAddress::from_str("127.0.0.1:9739").unwrap(), + }; + peer_store.add_peer(old).await.unwrap(); + peer_store.upsert_peer(new.clone()).await.unwrap(); + assert_eq!(peer_store.get_peer(&new.node_id), Some(new)); + } } From 98e0d6c6f902641f131fc826cd63058e85dfd8ed Mon Sep 17 00:00:00 2001 From: Vincenzo Palazzo Date: Thu, 3 Dec 2026 12:42:16 +0100 Subject: [PATCH 2/2] Upsert a peer address only when this call dialed it connect_peer_if_necessary reports Dialed only for its own outbound dial. Joining another attempt or an inbound connection is NotDialed, so an unverified address cannot overwrite a working one. Pending attempts store their address. A connect that joins a failed attempt to the same address returns that error; to a different address it logs and retries, so a reconnect stuck on a stale address cannot swallow a new one (#700). Assisted-by: Cursor Grok (AI) Co-authored-by: Cursor --- src/connection.rs | 116 +++++++++++++++----- src/event.rs | 4 +- src/lib.rs | 55 ++++++---- src/liquidity/client/lsps1.rs | 4 +- tests/integration_tests_rust.rs | 188 +++++++++++++++++++++++++++++++- 5 files changed, 308 insertions(+), 59 deletions(-) diff --git a/src/connection.rs b/src/connection.rs index 70013cbb29..39d364cd5a 100644 --- a/src/connection.rs +++ b/src/connection.rs @@ -18,8 +18,12 @@ use crate::logger::{log_debug, log_error, log_info, log_warn, LdkLogger}; use crate::types::{KeysManager, PeerManager}; use crate::Error; -type PendingConnections = - Mutex>>>>; +struct PendingConnection { + addr: SocketAddress, + subscribers: Vec>>, +} + +type PendingConnections = Mutex>; struct PendingConnectionGuard<'a> { pending_connections: &'a PendingConnections, @@ -43,14 +47,22 @@ impl Drop for PendingConnectionGuard<'_> { return; } let mut pending_connections = self.pending_connections.lock().expect("lock"); - if let Some(subscribers) = pending_connections.remove(&self.node_id) { - for subscriber in subscribers { + if let Some(pending_connection) = pending_connections.remove(&self.node_id) { + for subscriber in pending_connection.subscribers { let _ = subscriber.send(Err(Error::ConnectionFailed)); } } } } +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum ConnectPeerResult { + /// We established an outbound connection to the given address. + Dialed, + /// The peer is connected, but not via an outbound connection to the given address. + NotDialed, +} + pub(crate) struct ConnectionManager where L::Target: LdkLogger, @@ -83,14 +95,38 @@ where } } + /// Connects to the peer unless it is already connected. + /// + /// If an attempt to a different address is already in flight and fails, we retry with `addr`. pub(crate) async fn connect_peer_if_necessary( &self, node_id: PublicKey, addr: SocketAddress, - ) -> Result<(), Error> { - if self.peer_manager.peer_by_node_id(&node_id).is_some() { - return Ok(()); - } + ) -> Result { + loop { + if self.peer_manager.peer_by_node_id(&node_id).is_some() { + return Ok(ConnectPeerResult::NotDialed); + } + + let (pending_addr, pending_connection_ready_receiver) = + match self.register_or_subscribe_pending_connection(&node_id, &addr) { + Some(pending) => pending, + None => return self.do_connect_peer_as_pending_owner(node_id, addr).await, + }; - self.do_connect_peer(node_id, addr).await + match self.recv_pending_connection(pending_connection_ready_receiver).await? { + Ok(()) => return Ok(ConnectPeerResult::NotDialed), + Err(e) if pending_addr == addr => return Err(e), + Err(e) => { + log_debug!( + self.logger, + "Failed to connect to peer {}@{}, retrying via {}: {}", + node_id, + pending_addr, + addr, + e + ); + }, + } + } } pub(crate) fn disconnect_peer(&self, node_id: PublicKey) { @@ -102,27 +138,29 @@ where ) -> Result<(), Error> { // If another task is already connecting, subscribe to its result instead of starting a // duplicate attempt. - if let Some(pending_connection_ready_receiver) = - self.register_or_subscribe_pending_connection(&node_id) + if let Some((_, pending_connection_ready_receiver)) = + self.register_or_subscribe_pending_connection(&node_id, &addr) { - return pending_connection_ready_receiver.await.map_err(|e| { - debug_assert!(false, "Failed to receive connection result: {:?}", e); - log_error!(self.logger, "Failed to receive connection result: {:?}", e); - Error::ConnectionFailed - })?; + return self.recv_pending_connection(pending_connection_ready_receiver).await?; } + self.do_connect_peer_as_pending_owner(node_id, addr).await.map(|_| ()) + } + + async fn do_connect_peer_as_pending_owner( + &self, node_id: PublicKey, addr: SocketAddress, + ) -> Result { let mut pending_connection = PendingConnectionGuard::new(&self.pending_connections, node_id); let res = self.do_connect_peer_internal(node_id, addr).await; - self.propagate_result_to_subscribers(&node_id, res); + self.propagate_result_to_subscribers(&node_id, res.map(|_| ())); pending_connection.disarm(); res } async fn do_connect_peer_internal( &self, node_id: PublicKey, addr: SocketAddress, - ) -> Result<(), Error> { + ) -> Result { if self.disable_lightning_connections { log_warn!(self.logger, "Lightning peer connections are disabled."); return Err(Error::ConnectionFailed); @@ -257,7 +295,7 @@ where async fn await_connection( &self, connection_future: F, node_id: PublicKey, addr: SocketAddress, - ) -> Result<(), Error> + ) -> Result where F: std::future::Future>, CF: std::future::Future, @@ -275,7 +313,10 @@ where }; match self.peer_manager.peer_by_node_id(&node_id) { - Some(_) => break Ok(()), + Some(peer) if peer.is_inbound_connection => { + break Ok(ConnectPeerResult::NotDialed) + }, + Some(_) => break Ok(ConnectPeerResult::Dialed), None => continue, } } @@ -287,19 +328,32 @@ where } } + async fn recv_pending_connection( + &self, pending: tokio::sync::oneshot::Receiver>, + ) -> Result, Error> { + pending.await.map_err(|e| { + debug_assert!(false, "Failed to receive connection result: {:?}", e); + log_error!(self.logger, "Failed to receive connection result: {:?}", e); + Error::ConnectionFailed + }) + } + + /// Returns the address of the attempt already in flight, if any, along with a receiver for + /// its result. Otherwise, registers an attempt to `addr` and returns `None`. fn register_or_subscribe_pending_connection( - &self, node_id: &PublicKey, - ) -> Option>> { + &self, node_id: &PublicKey, addr: &SocketAddress, + ) -> Option<(SocketAddress, tokio::sync::oneshot::Receiver>)> { let mut pending_connections_lock = self.pending_connections.lock().expect("lock"); match pending_connections_lock.entry(*node_id) { hash_map::Entry::Occupied(mut entry) => { let (tx, rx) = tokio::sync::oneshot::channel(); - entry.get_mut().retain(|subscriber| !subscriber.is_closed()); - entry.get_mut().push(tx); - Some(rx) + let pending_connection = entry.get_mut(); + pending_connection.subscribers.retain(|subscriber| !subscriber.is_closed()); + pending_connection.subscribers.push(tx); + Some((pending_connection.addr.clone(), rx)) }, hash_map::Entry::Vacant(entry) => { - entry.insert(Vec::new()); + entry.insert(PendingConnection { addr: addr.clone(), subscribers: Vec::new() }); None }, } @@ -308,8 +362,8 @@ where fn propagate_result_to_subscribers(&self, node_id: &PublicKey, res: Result<(), Error>) { // Send the result to any other tasks that might be waiting on it by now. let mut pending_connections_lock = self.pending_connections.lock().expect("lock"); - if let Some(connection_ready_senders) = pending_connections_lock.remove(node_id) { - for sender in connection_ready_senders { + if let Some(pending_connection) = pending_connections_lock.remove(node_id) { + for sender in pending_connection.subscribers { let _ = sender.send(res).map_err(|e| { log_error!( self.logger, @@ -332,7 +386,11 @@ mod tests { "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798".parse().unwrap(); let pending_connections = Mutex::new(HashMap::new()); let (sender, mut receiver) = tokio::sync::oneshot::channel(); - pending_connections.lock().expect("lock").insert(node_id, vec![sender]); + let addr = SocketAddress::TcpIpV4 { addr: [127, 0, 0, 1], port: 9735 }; + pending_connections + .lock() + .expect("lock") + .insert(node_id, PendingConnection { addr, subscribers: vec![sender] }); let connection_guard = PendingConnectionGuard::new(&pending_connections, node_id); drop(connection_guard); diff --git a/src/event.rs b/src/event.rs index ed6a8e738f..8e5751fae3 100644 --- a/src/event.rs +++ b/src/event.rs @@ -848,7 +848,7 @@ where .connect_peer_if_necessary(peer_info.node_id, peer_info.address.clone()) .await { - Ok(()) => { + Ok(_) => { if peer_store.get_peer(&peer_info.node_id).is_none() || has_other_channels() { return; @@ -2677,7 +2677,7 @@ where let future = async move { for addr in &addresses { match spawn_cm.connect_peer_if_necessary(node_id, addr.clone()).await { - Ok(()) => { + Ok(_) => { return; }, Err(e) => { diff --git a/src/lib.rs b/src/lib.rs index 26f04298c8..3c1ea592ba 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -137,7 +137,7 @@ use config::{ LNURL_AUTH_TIMEOUT_SECS, NODE_ANN_BCAST_INTERVAL, PEER_RECONNECTION_INTERVAL, RGS_SYNC_INTERVAL, }; -use connection::ConnectionManager; +use connection::{ConnectPeerResult, ConnectionManager}; pub use error::Error as NodeError; use error::Error; pub use event::{Event, SpliceFailureReason, SpliceOutput, SpliceParameters}; @@ -1410,7 +1410,9 @@ 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. + /// If `persist` is set to `true`, we'll remember the peer and reconnect to it on restart. The + /// address of an already persisted peer is only updated if we establish a new outbound + /// connection to `address`. /// Outbound connection attempts fail with [`Error::ConnectionFailed`] if /// [`Config::disable_lightning_connections`] is set to `true`. pub fn connect( @@ -1421,26 +1423,40 @@ impl Node { } let peer_info = PeerInfo { node_id, address }; - - let con_node_id = peer_info.node_id; - let con_addr = peer_info.address.clone(); - let con_cm = Arc::clone(&self.connection_manager); - - // We need to use our main runtime here as a local runtime might not be around to poll - // connection futures going forward. - self.runtime.block_on(async move { - con_cm.connect_peer_if_necessary(con_node_id, con_addr).await - })?; + let connect_result = self.connect_peer(peer_info.node_id, peer_info.address.clone())?; log_info!(self.logger, "Connected to peer {}@{}. ", peer_info.node_id, peer_info.address); if persist { - self.runtime.block_on(self.peer_store.add_peer(peer_info))?; + self.persist_peer(peer_info, connect_result)?; } Ok(()) } + fn connect_peer( + &self, node_id: PublicKey, address: SocketAddress, + ) -> Result { + let con_cm = Arc::clone(&self.connection_manager); + // We need to use our main runtime here as a local runtime might not be around to poll + // connection futures going forward. + self.runtime + .block_on(async move { con_cm.connect_peer_if_necessary(node_id, address).await }) + } + + fn persist_peer( + &self, peer_info: PeerInfo, connect_result: ConnectPeerResult, + ) -> Result<(), Error> { + match connect_result { + ConnectPeerResult::Dialed => { + self.runtime.block_on(self.peer_store.upsert_peer(peer_info)) + }, + ConnectPeerResult::NotDialed => { + self.runtime.block_on(self.peer_store.add_peer(peer_info)) + }, + } + } + /// Disconnects the peer with the given node id. /// /// Will also remove the peer from the peer store, i.e., after this has been called we won't @@ -1474,16 +1490,7 @@ impl Node { disable_counterparty_reserve: bool, ) -> Result { let peer_info = PeerInfo { node_id, address }; - - let con_node_id = peer_info.node_id; - let con_addr = peer_info.address.clone(); - let con_cm = Arc::clone(&self.connection_manager); - - // We need to use our main runtime here as a local runtime might not be around to poll - // connection futures going forward. - self.runtime.block_on(async move { - con_cm.connect_peer_if_necessary(con_node_id, con_addr).await - })?; + let connect_result = self.connect_peer(peer_info.node_id, peer_info.address.clone())?; let funding_fee_rate = fee_rate.unwrap_or_else(|| { self.fee_estimator.estimate_fee_rate(ConfirmationTarget::ChannelFunding) @@ -1583,7 +1590,7 @@ impl Node { zero_reserve_string, peer_info.node_id ); - self.runtime.block_on(self.peer_store.add_peer(peer_info))?; + self.persist_peer(peer_info, connect_result)?; Ok(UserChannelId(user_channel_id)) }, Err(e) => { diff --git a/src/liquidity/client/lsps1.rs b/src/liquidity/client/lsps1.rs index 12965ac17f..c07cdd5d15 100644 --- a/src/liquidity/client/lsps1.rs +++ b/src/liquidity/client/lsps1.rs @@ -506,7 +506,7 @@ impl LSPS1Liquidity { // We need to use our main runtime here as a local runtime might not be around to poll // connection futures going forward. self.runtime.block_on(async move { - con_cm.connect_peer_if_necessary(con_node_id, con_addr).await + con_cm.connect_peer_if_necessary(con_node_id, con_addr).await.map(|_| ()) })?; log_info!(self.logger, "Connected to LSP {}@{}. ", lsps1_node.node_id, lsps1_node.address); @@ -549,7 +549,7 @@ impl LSPS1Liquidity { // We need to use our main runtime here as a local runtime might not be around to poll // connection futures going forward. self.runtime.block_on(async move { - con_cm.connect_peer_if_necessary(con_node_id, con_addr).await + con_cm.connect_peer_if_necessary(con_node_id, con_addr).await.map(|_| ()) })?; let liquidity_source = Arc::clone(&self.liquidity_source); diff --git a/tests/integration_tests_rust.rs b/tests/integration_tests_rust.rs index c307d02b4e..43b58b1e38 100644 --- a/tests/integration_tests_rust.rs +++ b/tests/integration_tests_rust.rs @@ -3315,6 +3315,191 @@ async fn connection_build_rejects_inbound_when_lightning_connections_disabled() } } +#[tokio::test(flavor = "multi_thread", worker_threads = 1)] +async fn connect_persist_does_not_overwrite_address_while_connected() { + let (bitcoind, electrsd) = setup_bitcoind_and_electrsd(); + let chain_source = random_chain_source(&bitcoind, &electrsd); + let (node_a, node_b) = setup_two_nodes(&chain_source, false, false); + + let node_id_b = node_b.node_id(); + let good_addr = node_b.listening_addresses().unwrap().into_iter().next().unwrap(); + node_a.connect(node_id_b, good_addr.clone(), true).unwrap(); + + // Already connected, so this does not dial. A typo must not replace the working address. + let typo = SocketAddress::TcpIpV4 { addr: [127, 0, 0, 1], port: 1 }; + node_a.connect(node_id_b, typo, true).unwrap(); + + // `list_peers` prefers the live socket address, so stop first and read the stored one. + node_a.stop().unwrap(); + let stored = node_a.list_peers().into_iter().find(|p| p.node_id == node_id_b).unwrap(); + assert_eq!(stored.address, good_addr); + + node_b.stop().unwrap(); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 1)] +async fn connect_persist_replaces_address_after_peer_restart() { + let (bitcoind, electrsd) = setup_bitcoind_and_electrsd(); + let chain_source = random_chain_source(&bitcoind, &electrsd); + let node_a = setup_node(&chain_source, random_config()); + + let mut config_b = random_config(); + let listening = config_b.node_config.listening_addresses.clone().unwrap(); + assert!(listening.len() >= 2, "node_b must listen on two addresses"); + let first = listening[0].clone(); + let second = listening[1].clone(); + let node_b = setup_node(&chain_source, config_b.clone()); + let node_id_b = node_b.node_id(); + + node_a.connect(node_id_b, first, true).unwrap(); + + node_b.stop().unwrap(); + drop(node_b); + let deadline = std::time::Instant::now() + Duration::from_secs(15); + loop { + let still_connected = + node_a.list_peers().iter().any(|peer| peer.node_id == node_id_b && peer.is_connected); + if !still_connected { + break; + } + assert!(deadline > std::time::Instant::now(), "peer stayed connected after node_b stopped"); + tokio::time::sleep(Duration::from_millis(50)).await; + } + + // The peer moved: same identity, fresh store, only the second listening address. + config_b.node_config.listening_addresses = Some(vec![second.clone()]); + config_b.node_config.storage_dir_path = + common::random_storage_path().to_str().unwrap().to_owned(); + let node_b = setup_node(&chain_source, config_b); + assert_eq!(node_b.node_id(), node_id_b); + node_a.connect(node_id_b, second.clone(), true).unwrap(); + + // `list_peers` prefers the live socket address, so stop first and read the stored one. + node_a.stop().unwrap(); + let stored = node_a.list_peers().into_iter().find(|peer| peer.node_id == node_id_b).unwrap(); + assert_eq!(stored.address, second); + + node_b.stop().unwrap(); +} + +/// Accepts TCP connections without completing the Lightning handshake, and closes each after +/// `hold`. The pending-connection slot is registered before this listener accepts, so +/// [`Self::wait_for_accept`] means a dial of `addr` is already in flight. +struct StallingListener { + addr: SocketAddress, + port: u16, + accepted: Arc, + shutdown: Arc, +} + +impl StallingListener { + fn spawn(hold: Duration) -> Self { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + let accepted = Arc::new(AtomicUsize::new(0)); + let shutdown = Arc::new(AtomicBool::new(false)); + let thread_accepted = Arc::clone(&accepted); + let thread_shutdown = Arc::clone(&shutdown); + std::thread::spawn(move || loop { + if thread_shutdown.load(Ordering::SeqCst) { + break; + } + match listener.accept() { + Ok((stream, _)) => { + if thread_shutdown.load(Ordering::SeqCst) { + break; + } + thread_accepted.fetch_add(1, Ordering::SeqCst); + std::thread::spawn(move || { + std::thread::sleep(hold); + drop(stream); + }); + }, + Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue, + Err(_) => break, + } + }); + Self { + addr: SocketAddress::TcpIpV4 { addr: [127, 0, 0, 1], port }, + port, + accepted, + shutdown, + } + } + + async fn wait_for_accept(&self) { + let deadline = std::time::Instant::now() + Duration::from_secs(10); + while self.accepted.load(Ordering::SeqCst) == 0 { + assert!( + deadline > std::time::Instant::now(), + "stalling listener accepted no connection" + ); + tokio::time::sleep(Duration::from_millis(20)).await; + } + } +} + +impl Drop for StallingListener { + fn drop(&mut self) { + self.shutdown.store(true, Ordering::SeqCst); + let _ = std::net::TcpStream::connect_timeout( + &std::net::SocketAddr::from(([127, 0, 0, 1], self.port)), + Duration::from_millis(200), + ); + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 1)] +async fn connect_dials_own_address_after_joined_attempt_fails() { + let (bitcoind, electrsd) = setup_bitcoind_and_electrsd(); + let chain_source = random_chain_source(&bitcoind, &electrsd); + let (node_a, node_b) = setup_two_nodes(&chain_source, false, false); + let node_a = Arc::new(node_a); + let node_id_b = node_b.node_id(); + let node_addr_b = node_b.listening_addresses().unwrap().first().unwrap().clone(); + let listener = StallingListener::spawn(Duration::from_secs(2)); + + let stalled_node = Arc::clone(&node_a); + let stalling_addr = listener.addr.clone(); + let stalled = std::thread::spawn(move || stalled_node.connect(node_id_b, stalling_addr, false)); + listener.wait_for_accept().await; + + node_a.connect(node_id_b, node_addr_b.clone(), true).unwrap(); + assert_eq!(stalled.join().unwrap(), Err(NodeError::ConnectionFailed)); + + // `list_peers` prefers the live socket address, so stop first and read the stored one. + node_a.stop().unwrap(); + let stored = node_a.list_peers().into_iter().find(|peer| peer.node_id == node_id_b).unwrap(); + assert_eq!(stored.address, node_addr_b); + + node_b.stop().unwrap(); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 1)] +async fn connect_does_not_redial_address_of_failed_joined_attempt() { + let (bitcoind, electrsd) = setup_bitcoind_and_electrsd(); + let chain_source = random_chain_source(&bitcoind, &electrsd); + let (node_a, node_b) = setup_two_nodes(&chain_source, false, false); + let node_a = Arc::new(node_a); + let node_id_b = node_b.node_id(); + let listener = StallingListener::spawn(Duration::from_secs(2)); + + let stalled_node = Arc::clone(&node_a); + let stalling_addr = listener.addr.clone(); + let stalled = std::thread::spawn(move || stalled_node.connect(node_id_b, stalling_addr, false)); + listener.wait_for_accept().await; + + assert_eq!( + node_a.connect(node_id_b, listener.addr.clone(), false), + Err(NodeError::ConnectionFailed) + ); + assert_eq!(stalled.join().unwrap(), Err(NodeError::ConnectionFailed)); + assert_eq!(listener.accepted.load(Ordering::SeqCst), 1); + + node_a.stop().unwrap(); + node_b.stop().unwrap(); +} + #[tokio::test(flavor = "multi_thread", worker_threads = 1)] async fn disconnect_reports_failure_to_remove_peer() { let (bitcoind, electrsd) = setup_bitcoind_and_electrsd(); @@ -7108,8 +7293,7 @@ async fn async_payment() { .filter(|n| { node.network_graph().node(n).map_or(false, |info| info.announcement_info.is_some()) }) - .count() - >= 2 + .count() >= 2 }; // Wait for everyone to see all channels and node announcements.