From 358673c64a377eeb115691c5eba84a608af86aa3 Mon Sep 17 00:00:00 2001 From: Vincenzo Palazzo Date: Wed, 18 Nov 2026 18:39:06 +0100 Subject: [PATCH] fix(peer_store): upsert a peer address only after dialing it Node::connect(..., persist=true) and open_channel kept the first stored address, so a later working address was never used for reconnect (#700). upsert_peer replaces the address through the persist-first update_peers path from #1234. connect and open_channel call it only when this call dialed the requested address. An already-connected peer keeps add_peer, so an unverified address cannot overwrite a working one. The LSPS2 receive path stays add_peer (#1147). Co-authored-by: Bartok <259807879+Bartok9@users.noreply.github.com> Assisted-by: goose (AI) --- src/lib.rs | 23 +++++++++++++++++++++-- src/peer_store.rs | 31 +++++++++++++++++++++++++++++++ tests/integration_tests_rust.rs | 21 +++++++++++++++++++++ 3 files changed, 73 insertions(+), 2 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 97a179c95f..df22d9f575 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1405,6 +1405,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. + /// A later `connect` with `persist` set updates the stored address only when this call dialed + /// `address`. If the peer is already connected, the stored address is left unchanged. /// Outbound connection attempts fail with [`Error::ConnectionFailed`] if /// [`Config::disable_lightning_connections`] is set to `true`. pub fn connect( @@ -1416,6 +1418,10 @@ impl Node { let peer_info = PeerInfo { node_id, address }; + // `connect_peer_if_necessary` returns `Ok(())` without dialing when the peer is already + // up, so that success must not replace a stored address we never dialed. + let already_connected = self.peer_manager.peer_by_node_id(&peer_info.node_id).is_some(); + let con_node_id = peer_info.node_id; let con_addr = peer_info.address.clone(); let con_cm = Arc::clone(&self.connection_manager); @@ -1429,12 +1435,24 @@ impl Node { 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_dialed_peer(peer_info, !already_connected)?; } Ok(()) } + /// Persists `peer_info` after a connection attempt. + /// + /// `replace_address` is set only when this call dialed `peer_info.address`. Otherwise the peer + /// is inserted if missing, so an address we never dialed cannot overwrite a working one. + fn persist_dialed_peer(&self, peer_info: PeerInfo, replace_address: bool) -> Result<(), Error> { + if replace_address { + self.runtime.block_on(self.peer_store.upsert_peer(peer_info)) + } else { + 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 @@ -1468,6 +1486,7 @@ impl Node { disable_counterparty_reserve: bool, ) -> Result { let peer_info = PeerInfo { node_id, address }; + let already_connected = self.peer_manager.peer_by_node_id(&peer_info.node_id).is_some(); let con_node_id = peer_info.node_id; let con_addr = peer_info.address.clone(); @@ -1577,7 +1596,7 @@ impl Node { zero_reserve_string, peer_info.node_id ); - self.runtime.block_on(self.peer_store.add_peer(peer_info))?; + self.persist_dialed_peer(peer_info, !already_connected)?; Ok(UserChannelId(user_channel_id)) }, Err(e) => { diff --git a/src/peer_store.rs b/src/peer_store.rs index db5809f1f3..085ff77be3 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 } @@ -355,4 +371,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)); + } } diff --git a/tests/integration_tests_rust.rs b/tests/integration_tests_rust.rs index c831c98ade..3881bd12f9 100644 --- a/tests/integration_tests_rust.rs +++ b/tests/integration_tests_rust.rs @@ -3305,6 +3305,27 @@ 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 = + ldk_node::lightning::ln::msgs::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); +} + #[tokio::test(flavor = "multi_thread", worker_threads = 1)] async fn disconnect_reports_failure_to_remove_peer() { let (bitcoind, electrsd) = setup_bitcoind_and_electrsd();