Skip to content
Open
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
116 changes: 87 additions & 29 deletions src/connection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<HashMap<PublicKey, Vec<tokio::sync::oneshot::Sender<Result<(), Error>>>>>;
struct PendingConnection {
addr: SocketAddress,
subscribers: Vec<tokio::sync::oneshot::Sender<Result<(), Error>>>,
}

type PendingConnections = Mutex<HashMap<PublicKey, PendingConnection>>;

struct PendingConnectionGuard<'a> {
pending_connections: &'a PendingConnections,
Expand All @@ -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<L: Deref + Clone + Sync + Send>
where
L::Target: LdkLogger,
Expand Down Expand Up @@ -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<ConnectPeerResult, Error> {
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) {
Expand All @@ -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<ConnectPeerResult, Error> {
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<ConnectPeerResult, Error> {
if self.disable_lightning_connections {
log_warn!(self.logger, "Lightning peer connections are disabled.");
return Err(Error::ConnectionFailed);
Expand Down Expand Up @@ -257,7 +295,7 @@ where

async fn await_connection<F, CF>(
&self, connection_future: F, node_id: PublicKey, addr: SocketAddress,
) -> Result<(), Error>
) -> Result<ConnectPeerResult, Error>
where
F: std::future::Future<Output = Option<CF>>,
CF: std::future::Future<Output = ()>,
Expand All @@ -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,
}
}
Expand All @@ -287,19 +328,32 @@ where
}
}

async fn recv_pending_connection(
&self, pending: tokio::sync::oneshot::Receiver<Result<(), Error>>,
) -> Result<Result<(), Error>, 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<tokio::sync::oneshot::Receiver<Result<(), Error>>> {
&self, node_id: &PublicKey, addr: &SocketAddress,
) -> Option<(SocketAddress, tokio::sync::oneshot::Receiver<Result<(), Error>>)> {
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
},
}
Expand All @@ -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,
Expand All @@ -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);
Expand Down
4 changes: 2 additions & 2 deletions src/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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) => {
Expand Down
55 changes: 31 additions & 24 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -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(
Expand All @@ -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<ConnectPeerResult, Error> {
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
Expand Down Expand Up @@ -1474,16 +1490,7 @@ impl Node {
disable_counterparty_reserve: bool,
) -> Result<UserChannelId, Error> {
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)
Expand Down Expand Up @@ -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) => {
Expand Down
4 changes: 2 additions & 2 deletions src/liquidity/client/lsps1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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);
Expand Down
31 changes: 31 additions & 0 deletions src/peer_store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down Expand Up @@ -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<DynStore> = 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));
}
}
Loading
Loading