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
66 changes: 66 additions & 0 deletions libs/gl-plugin/src/channels.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
///
Expand All @@ -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<K, I>(channels: I) -> HashSet<K>
where
K: Eq + Hash,
I: IntoIterator<Item = (K, bool, bool, u64)>,
{
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<HashSet<String>, 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::*;
Expand All @@ -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"]);
}
}
81 changes: 63 additions & 18 deletions libs/gl-plugin/src/node/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,15 @@ static LIMITER: OnceCell<RateLimiter<NotKeyed, InMemoryState, MonotonicClock>> =
static RPC_CLIENT: OnceCell<Arc<Mutex<cln_rpc::ClnRpc>>> = 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;
/// 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;

Expand Down Expand Up @@ -217,9 +226,15 @@ impl Node for PluginNodeServer {
req: Request<pb::LspInvoiceRequest>,
) -> Result<Response<pb::LspInvoiceResponse>, 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.
Expand Down Expand Up @@ -328,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()))?
};

Expand Down Expand Up @@ -950,19 +973,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(());
}

Expand Down Expand Up @@ -1091,8 +1136,8 @@ impl PluginNodeServer {
async fn get_reconnect_peers(
&self,
) -> Result<Vec<cln_rpc::model::requests::ConnectRequest>, 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<cln_rpc::model::requests::ConnectRequest> = peers
Expand Down
Loading