From 276d0d468aa6deeb1299816c1725cdacd92c4d51 Mon Sep 17 00:00:00 2001 From: cdecker Date: Wed, 18 Nov 2026 14:24:59 +0100 Subject: [PATCH 1/3] plugin: Reconnect peers without holding the shared RPC connection Every successful connection is recorded in the `greenlight/peerlist` datastore, and every entry is dialed again whenever a signer attaches. The reconnect held the shared RPC connection for the whole pass and dialed peers one after the other, so a single stale entry whose address no longer answers stalled it for minutes per pass, until the TCP connect timed out. Everything else on that connection, `lsp_invoice` in particular, queued behind it: invoice creation hung while the app polled on. Reconnecting is best effort, so take it off the critical path: collect the peers and dial each of them on their own RPC connection, with a 30s timeout, up to 8 at a time. Peerlist entries are still dialed, but a dead one now costs at most 30s in the background and blocks nobody. --- libs/gl-plugin/src/node/mod.rs | 56 +++++++++++++++++++++++++--------- 1 file changed, 42 insertions(+), 14 deletions(-) diff --git a/libs/gl-plugin/src/node/mod.rs b/libs/gl-plugin/src/node/mod.rs index fea0b4848..6b1f81d81 100644 --- a/libs/gl-plugin/src/node/mod.rs +++ b/libs/gl-plugin/src/node/mod.rs @@ -36,6 +36,12 @@ static LIMITER: OnceCell> = static RPC_CLIENT: OnceCell>> = OnceCell::const_new(); static RPC_POLL_INTERVAL: Duration = Duration::from_millis(500); +/// Bound on a single reconnect `connect` call. An unreachable address +/// otherwise blocks until the TCP connect times out (minutes). +const RECONNECT_TIMEOUT: Duration = Duration::from_secs(30); +/// How many peers to reconnect at the same time. +const RECONNECT_CONCURRENCY: usize = 8; + #[allow(unused)] const OPT_SUPPORTS_LSPS: usize = 729; @@ -950,19 +956,41 @@ impl PluginNodeServer { peers.iter().map(|p| p.id.clone()) ); - let rpc_arc = get_rpc(&self.rpc_path).await; - let mut rpc = rpc_arc.lock().await; - - for r in peers { - trace!("Calling connect: {:?} (plugin)", &r.id); - let res = rpc.call_typed(&r).await; - trace!("Connect returned: {:?} -> {:?} (plugin)", &r.id, res); + // Reconnecting is best effort and must never stall other + // operations: an unreachable peer (e.g. a stale peerlist entry) + // makes `connect` hang for minutes. So each attempt gets its own + // RPC connection instead of the shared one other calls (e.g. + // `lsp_invoice`) wait on, a timeout, and runs next to the others. + use futures::StreamExt; + futures::stream::iter(peers) + .for_each_concurrent(RECONNECT_CONCURRENCY, |r| { + let rpc_path = self.rpc_path.clone(); + async move { + trace!("Calling connect: {:?} (plugin)", &r.id); + let res = match cln_rpc::ClnRpc::new(&rpc_path).await { + Ok(mut rpc) => { + tokio::time::timeout(RECONNECT_TIMEOUT, rpc.call_typed(&r)).await + } + Err(e) => { + warn!("Could not open RPC to connect to {}: {:?} (plugin)", &r.id, e); + return; + } + }; + trace!("Connect returned: {:?} -> {:?} (plugin)", &r.id, res); - match res { - Ok(r) => info!("Connection to {} established: {:?} (plugin)", &r.id, r), - Err(e) => warn!("Could not connect to {}: {:?} (plugin)", &r.id, e), - } - } + match res { + Ok(Ok(c)) => { + info!("Connection to {} established: {:?} (plugin)", &c.id, c) + } + Ok(Err(e)) => warn!("Could not connect to {}: {:?} (plugin)", &r.id, e), + Err(_) => warn!( + "Connecting to {} timed out after {:?} (plugin)", + &r.id, RECONNECT_TIMEOUT + ), + } + } + }) + .await; return Ok(()); } @@ -1091,8 +1119,8 @@ impl PluginNodeServer { async fn get_reconnect_peers( &self, ) -> Result, Error> { - let rpc_arc = get_rpc(&self.rpc_path).await; - let mut rpc = rpc_arc.lock().await; + // Own connection: don't queue behind, or hold up, the shared one. + let mut rpc = cln_rpc::ClnRpc::new(&self.rpc_path).await?; let peers = self.list_peers(&mut rpc).await?; let mut requests: Vec = peers From 942dfead06e2df0a3ff033a3d4485a4b2868e794 Mon Sep 17 00:00:00 2001 From: cdecker Date: Wed, 18 Nov 2026 14:24:59 +0100 Subject: [PATCH 2/3] plugin: Give lsp_invoice its own RPC connection and a timeout `lsp_invoice` held the shared RPC connection across the whole LSPS2 negotiation, including the `lsps-lsps2-invoice` call that waits on the remote LSP and had no timeout. An LSP that never answers would hang the invoice, and every other caller of the shared connection, indefinitely. Use a dedicated connection and bound the negotiation to 30s. The timeout is only safe on a dedicated connection: `cln_rpc` reads the next frame off the socket without matching response ids, so abandoning a call on a shared connection would hand its late response to the next caller. --- libs/gl-plugin/src/node/mod.rs | 25 +++++++++++++++++++++---- 1 file changed, 21 insertions(+), 4 deletions(-) diff --git a/libs/gl-plugin/src/node/mod.rs b/libs/gl-plugin/src/node/mod.rs index 6b1f81d81..016238be6 100644 --- a/libs/gl-plugin/src/node/mod.rs +++ b/libs/gl-plugin/src/node/mod.rs @@ -41,6 +41,9 @@ static RPC_POLL_INTERVAL: Duration = Duration::from_millis(500); const RECONNECT_TIMEOUT: Duration = Duration::from_secs(30); /// How many peers to reconnect at the same time. const RECONNECT_CONCURRENCY: usize = 8; +/// Bound on the LSPS2 invoice negotiation with the LSP (`lsps2.buy` +/// round trip plus invoice creation). +const LSP_INVOICE_TIMEOUT: Duration = Duration::from_secs(30); #[allow(unused)] const OPT_SUPPORTS_LSPS: usize = 729; @@ -223,9 +226,15 @@ impl Node for PluginNodeServer { req: Request, ) -> Result, Status> { let req: pb::LspInvoiceRequest = req.into_inner(); - let rpc_arc = get_rpc(&self.rpc_path).await; - let mut rpc = rpc_arc.lock().await; + // Own connection rather than the shared one: the LSPS2 + // negotiation waits on a remote LSP, and must neither block nor + // be blocked by other calls. It also lets us time it out safely, + // as `cln_rpc` doesn't match responses to requests, so an + // abandoned call would desync a shared connection. + let mut rpc = cln_rpc::ClnRpc::new(&self.rpc_path) + .await + .map_err(|e| Status::unavailable(format!("Could not connect to lightningd: {e}")))?; // Check if we have sufficient incoming capacity to skip JIT channel negotiation. // We require capacity + 5% buffer to account for fees and routing. @@ -334,17 +343,25 @@ impl Node for PluginNodeServer { let invoice_label = req.label.clone(); // Use the new RPC method name for versions > v25.05gl1 + let timed_out = || { + Status::deadline_exceeded(format!( + "LSP {} did not complete the JIT channel negotiation within {:?}", + lsp_id, LSP_INVOICE_TIMEOUT + )) + }; let mut res = if *version > *"v25.05gl1" { let mut invreq: crate::requests::LspInvoiceRequestV2 = req.into(); invreq.lsp_id = lsp_id.to_owned(); - rpc.call_typed(&invreq) + tokio::time::timeout(LSP_INVOICE_TIMEOUT, rpc.call_typed(&invreq)) .await + .map_err(|_| timed_out())? .map_err(|e| Status::new(Code::Internal, e.to_string()))? } else { let mut invreq: crate::requests::LspInvoiceRequest = req.into(); invreq.lsp_id = lsp_id.to_owned(); - rpc.call_typed(&invreq) + tokio::time::timeout(LSP_INVOICE_TIMEOUT, rpc.call_typed(&invreq)) .await + .map_err(|_| timed_out())? .map_err(|e| Status::new(Code::Internal, e.to_string()))? }; From 5d52e80f3b34623dab9414817cad3704d3cd1d53 Mon Sep 17 00:00:00 2001 From: cdecker Date: Wed, 18 Nov 2026 14:24:59 +0100 Subject: [PATCH 3/3] plugin: Add a helper for the peers worth reconnecting to A reconnect only helps to bring channels back, so a peer is worth dialing if at least one of its channels is available by the existing rule in `is_channel_available`. One with only unavailable channels, e.g. an abandoned JIT channel the LSP server may have forgotten, is not. `reconnect_candidates` exposes that set so callers can skip such peers. --- libs/gl-plugin/src/channels.rs | 66 ++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) diff --git a/libs/gl-plugin/src/channels.rs b/libs/gl-plugin/src/channels.rs index 2ca03c62b..7f84d51b8 100644 --- a/libs/gl-plugin/src/channels.rs +++ b/libs/gl-plugin/src/channels.rs @@ -30,6 +30,9 @@ //! or come back online), while a never-funded zeroconf channel is not, //! even if it would momentarily show spendable capacity. +use std::collections::HashSet; +use std::hash::Hash; + /// Decide whether a channel is available for payments, awaiting and /// routehints. /// @@ -44,6 +47,51 @@ pub fn is_channel_available( state_is_normal && (max_to_us_msat_msat > 0 || has_scid) } +/// The peers worth reconnecting to: those with at least one available +/// channel. +/// +/// Reconnecting is only useful to bring channels back. A peer with no +/// channel at all, or with only unavailable ones (e.g. an abandoned JIT +/// channel the LSP server may have forgotten), is not worth dialing, and +/// an unreachable one can hold up the caller for minutes per `connect`. +/// +/// Each item is `(peer_id, state_is_normal, has_scid, max_to_us_msat)`, +/// see [`is_channel_available`]. +pub fn peers_with_available_channels(channels: I) -> HashSet +where + K: Eq + Hash, + I: IntoIterator, +{ + channels + .into_iter() + .filter(|(_, normal, scid, max_to_us)| is_channel_available(*normal, *scid, *max_to_us)) + .map(|(id, ..)| id) + .collect() +} + +/// Ask `lightningd` for the peers worth reconnecting to, as lowercase +/// hex node ids. See [`peers_with_available_channels`]. +pub async fn reconnect_candidates( + rpc: &mut cln_rpc::ClnRpc, +) -> Result, cln_rpc::RpcError> { + use cln_rpc::primitives::ChannelState; + + let res = rpc + .call_typed(&cln_rpc::model::requests::ListpeerchannelsRequest { id: None }) + .await?; + + Ok(peers_with_available_channels(res.channels.into_iter().map( + |c| { + ( + c.peer_id.to_string(), + c.state == ChannelState::CHANNELD_NORMAL, + c.short_channel_id.is_some(), + c.max_to_us_msat.map(|a| a.msat()).unwrap_or(0), + ) + }, + ))) +} + #[cfg(test)] mod tests { use super::*; @@ -70,4 +118,22 @@ mod tests { assert!(!is_channel_available(false, true, 0)); assert!(!is_channel_available(false, false, 0)); } + + #[test] + fn test_reconnect_needs_one_available_channel() { + let peers = peers_with_available_channels(vec![ + // Confirmed normal channel: reconnect. + ("good", true, true, 0), + // A stalled JIT channel next to a good one still reconnects. + ("mixed", true, false, 0), + ("mixed", true, true, 1), + // Only an abandoned JIT channel: skip. + ("stalled-jit", true, false, 0), + // Only a closing channel: skip. + ("closing", false, true, 1), + ]); + let mut peers: Vec<_> = peers.into_iter().collect(); + peers.sort(); + assert_eq!(peers, vec!["good", "mixed"]); + } }