From c61d73a26683bd8bd97f772c064ebef3f090d12e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20A=2EP?= <53834183+Jossec101@users.noreply.github.com> Date: Tue, 30 Jun 2026 10:49:04 +0200 Subject: [PATCH] Fix check peer connection before connecting Add a ListPeers check at the start of ConnectToPeer to short-circuit when the peer is already connected, avoiding unnecessary ConnectPeer RPC calls and noisy errors. Also throw PeerNotOnlineException early when no TCP address is available for the peer, and reuse the macaroon metadata across both RPC calls. stack-info: PR: https://github.com/Elenpay/NodeGuard/pull/525, branch: Jossec101/stack/11 --- src/Services/LightningClientService.cs | 27 ++++++++++++++++++++++---- 1 file changed, 23 insertions(+), 4 deletions(-) diff --git a/src/Services/LightningClientService.cs b/src/Services/LightningClientService.cs index f7b6621c..93eb9d92 100644 --- a/src/Services/LightningClientService.cs +++ b/src/Services/LightningClientService.cs @@ -274,8 +274,24 @@ public AsyncServerStreamingCall SubscribeChannelEvents(Node public async Task ConnectToPeer(Node node, string peerPubKey, Lightning.LightningClient? client = null) { client ??= GetLightningClient(node.Endpoint); + var metadata = new Metadata { { "macaroon", node.ChannelAdminMacaroon } }; var isPeerAlreadyConnected = false; + // If we're already connected to the peer there's nothing to do. + try + { + var peers = await client.ListPeersAsync(new ListPeersRequest(), metadata); + if (peers.Peers.Any(p => p.PubKey == peerPubKey)) + { + _logger.LogInformation("Peer: {Pubkey} already connected", peerPubKey); + return; + } + } + catch (Exception e) + { + _logger.LogWarning(e, "Could not list peers on node {NodeId} before connecting to {Pubkey}", node.Id, peerPubKey); + } + ConnectPeerResponse connectPeerResponse = null; try { @@ -284,14 +300,17 @@ public async Task ConnectToPeer(Node node, string peerPubKey, Lightning.Lightnin //For now, we only rely on pure tcp IPV4 connections var addr = nodeInfo?.Addresses.FirstOrDefault(x => x.Network == "tcp")?.Addr; + if (string.IsNullOrEmpty(addr)) + { + throw new PeerNotOnlineException( + $"peer {peerPubKey} has no known address to connect to and is not already connected"); + } + connectPeerResponse = await client.ConnectPeerAsync(new ConnectPeerRequest { Addr = new LightningAddress { Host = addr, Pubkey = nodeInfo.PubKey }, Perm = true - }, new Metadata - { - { "macaroon", node.ChannelAdminMacaroon } - }); + }, metadata); } //We avoid to stop the method if the peer is already connected catch (RpcException e)