Skip to main content

ab_networking/
node.rs

1#[cfg(all(test, not(miri)))]
2mod tests;
3
4use crate::protocols::request_response::handlers::generic_request_handler::GenericRequest;
5use crate::protocols::request_response::request_response_factory;
6use crate::shared::{Command, PeerDiscovered, Shared};
7use crate::utils::HandlerFn;
8use crate::utils::multihash::Multihash;
9use event_listener_primitives::HandlerId;
10use futures::channel::{mpsc, oneshot};
11use futures::{SinkExt, Stream, StreamExt};
12use libp2p::{Multiaddr, PeerId};
13use std::sync::{Arc, Weak};
14use thiserror::Error;
15use tokio::sync::OwnedSemaphorePermit;
16use tracing::{debug, trace};
17
18/// Defines errors for `get-closest-peers` operation.
19#[derive(Debug, Error)]
20pub enum GetClosestPeersError {
21    /// Failed to send command to the node runner
22    #[error("Failed to send command to the node runner: {0}")]
23    SendCommand(#[from] mpsc::SendError),
24    /// Node runner was dropped
25    #[error("Node runner was dropped")]
26    NodeRunnerDropped,
27}
28
29impl From<oneshot::Canceled> for GetClosestPeersError {
30    #[inline]
31    fn from(oneshot::Canceled: oneshot::Canceled) -> Self {
32        Self::NodeRunnerDropped
33    }
34}
35
36/// Defines errors for `get-closest-peers` operation.
37#[derive(Debug, Error)]
38pub enum GetClosestLocalPeersError {
39    /// Failed to send command to the node runner
40    #[error("Failed to send command to the node runner: {0}")]
41    SendCommand(#[from] mpsc::SendError),
42    /// Node runner was dropped
43    #[error("Node runner was dropped")]
44    NodeRunnerDropped,
45}
46
47impl From<oneshot::Canceled> for GetClosestLocalPeersError {
48    #[inline]
49    fn from(oneshot::Canceled: oneshot::Canceled) -> Self {
50        Self::NodeRunnerDropped
51    }
52}
53
54/// Defines errors for `send-request` operation.
55#[derive(Debug, Error)]
56pub enum SendRequestError {
57    /// Failed to send command to the node runner
58    #[error("Failed to send command to the node runner: {0}")]
59    SendCommand(#[from] mpsc::SendError),
60    /// Node runner was dropped
61    #[error("Node runner was dropped")]
62    NodeRunnerDropped,
63    /// Underlying protocol returned an error, impossible to get response.
64    #[error("Underlying protocol returned an error: {0}")]
65    ProtocolFailure(#[from] request_response_factory::RequestFailure),
66    /// Underlying protocol returned an incorrect format, impossible to get response.
67    #[error("Received incorrectly formatted response: {0}")]
68    IncorrectResponseFormat(#[from] parity_scale_codec::Error),
69}
70
71impl From<oneshot::Canceled> for SendRequestError {
72    #[inline]
73    fn from(oneshot::Canceled: oneshot::Canceled) -> Self {
74        Self::NodeRunnerDropped
75    }
76}
77
78#[derive(Debug, Error)]
79pub enum ConnectedPeersError {
80    /// Failed to send command to the node runner
81    #[error("Failed to send command to the node runner: {0}")]
82    SendCommand(#[from] mpsc::SendError),
83    /// Node runner was dropped
84    #[error("Node runner was dropped")]
85    NodeRunnerDropped,
86    /// Failed to get connected peers.
87    #[error("Failed to get connected peers.")]
88    ConnectedPeers,
89}
90
91impl From<oneshot::Canceled> for ConnectedPeersError {
92    #[inline]
93    fn from(oneshot::Canceled: oneshot::Canceled) -> Self {
94        Self::NodeRunnerDropped
95    }
96}
97
98#[derive(Debug, Error)]
99pub enum BootstrapError {
100    /// Failed to send command to the node runner
101    #[error("Failed to send command to the node runner: {0}")]
102    SendCommand(#[from] mpsc::SendError),
103    /// Node runner was dropped
104    #[error("Node runner was dropped")]
105    NodeRunnerDropped,
106    /// Failed to bootstrap a peer.
107    #[error("Failed to bootstrap a peer.")]
108    Bootstrap,
109}
110
111impl From<oneshot::Canceled> for BootstrapError {
112    #[inline]
113    fn from(oneshot::Canceled: oneshot::Canceled) -> Self {
114        Self::NodeRunnerDropped
115    }
116}
117
118/// Implementation of a network node on Subspace Network.
119#[derive(Debug, Clone)]
120#[must_use = "Node doesn't do anything if dropped"]
121pub struct Node {
122    shared: Arc<Shared>,
123}
124
125impl Node {
126    pub(crate) fn new(shared: Arc<Shared>) -> Self {
127        Self { shared }
128    }
129
130    /// Node's own local ID.
131    pub fn id(&self) -> PeerId {
132        self.shared.id
133    }
134
135    async fn send_generic_request_internal<Request>(
136        &self,
137        peer_id: PeerId,
138        addresses: Vec<Multiaddr>,
139        request: Request,
140        acquire_permit: bool,
141    ) -> Result<Request::Response, SendRequestError>
142    where
143        Request: GenericRequest,
144    {
145        let _permit = if acquire_permit {
146            Some(self.shared.rate_limiter.acquire_permit().await)
147        } else {
148            None
149        };
150
151        let (result_sender, result_receiver) = oneshot::channel();
152        let command = Command::GenericRequest {
153            peer_id,
154            addresses,
155            protocol_name: Request::PROTOCOL_NAME,
156            request: request.encode(),
157            result_sender,
158        };
159
160        self.shared.command_sender.clone().send(command).await?;
161
162        let result = result_receiver.await??;
163
164        Request::decode_response(result).map_err(Into::into)
165    }
166
167    /// Sends the generic request to the peer and awaits the result.
168    ///
169    /// Optional addresses will be used for dialing if connection to peer isn't established yet.
170    pub async fn send_generic_request<Request>(
171        &self,
172        peer_id: PeerId,
173        addresses: Vec<Multiaddr>,
174        request: Request,
175    ) -> Result<Request::Response, SendRequestError>
176    where
177        Request: GenericRequest,
178    {
179        self.send_generic_request_internal(peer_id, addresses, request, true)
180            .await
181    }
182
183    /// Get closest peers by multihash key using Kademlia DHT.
184    pub async fn get_closest_peers(
185        &self,
186        key: Multihash,
187    ) -> Result<impl Stream<Item = PeerId>, GetClosestPeersError> {
188        self.get_closest_peers_internal(key, true).await
189    }
190
191    /// Get closest peers by multihash key using Kademlia DHT's local view without any network
192    /// requests.
193    ///
194    /// Optional `source` is peer for which results will be sent as a response. Defaults to local
195    /// peer ID.
196    pub async fn get_closest_local_peers(
197        &self,
198        key: Multihash,
199        source: Option<PeerId>,
200    ) -> Result<Vec<(PeerId, Vec<Multiaddr>)>, GetClosestLocalPeersError> {
201        let (result_sender, result_receiver) = oneshot::channel();
202
203        self.shared
204            .command_sender
205            .clone()
206            .send(Command::GetClosestLocalPeers {
207                key,
208                source,
209                result_sender,
210            })
211            .await?;
212
213        Ok(result_receiver.await?)
214    }
215
216    /// Get closest peers by multihash key using Kademlia DHT.
217    async fn get_closest_peers_internal(
218        &self,
219        key: Multihash,
220        acquire_permit: bool,
221    ) -> Result<impl Stream<Item = PeerId> + use<>, GetClosestPeersError> {
222        let permit = if acquire_permit {
223            Some(self.shared.rate_limiter.acquire_permit().await)
224        } else {
225            None
226        };
227
228        trace!(?key, "Starting 'GetClosestPeers' request.");
229
230        let (result_sender, result_receiver) = mpsc::unbounded();
231
232        self.shared
233            .command_sender
234            .clone()
235            .send(Command::GetClosestPeers {
236                key,
237                result_sender,
238                permit,
239            })
240            .await?;
241
242        // TODO: A wrapper that'll immediately cancel query on drop
243        Ok(result_receiver)
244    }
245
246    /// Ban peer with specified peer ID.
247    pub async fn ban_peer(&self, peer_id: PeerId) -> Result<(), mpsc::SendError> {
248        self.shared
249            .command_sender
250            .clone()
251            .send(Command::BanPeer { peer_id })
252            .await
253    }
254
255    /// Dial multiaddress.
256    /// It could be used to test libp2p transports bypassing protocol checks for bootstrap
257    /// or listen-on addresses.
258    #[doc(hidden)]
259    pub async fn dial(&self, address: Multiaddr) -> Result<(), mpsc::SendError> {
260        self.shared
261            .command_sender
262            .clone()
263            .send(Command::Dial { address })
264            .await
265    }
266
267    /// Node's own addresses where it listens for incoming requests.
268    pub fn listeners(&self) -> Vec<Multiaddr> {
269        self.shared.listeners.lock().clone()
270    }
271
272    /// Node's own addresses observed remotely.
273    pub fn external_addresses(&self) -> Vec<Multiaddr> {
274        self.shared.external_addresses.lock().clone()
275    }
276
277    /// Callback is called when node starts listening on new address.
278    pub fn on_new_listener(&self, callback: HandlerFn<Multiaddr>) -> HandlerId {
279        self.shared.handlers.new_listener.add(callback)
280    }
281
282    /// Callback is called when number of established peer connections changes.
283    pub fn on_num_established_peer_connections_change(
284        &self,
285        callback: HandlerFn<usize>,
286    ) -> HandlerId {
287        self.shared
288            .handlers
289            .num_established_peer_connections_change
290            .add(callback)
291    }
292
293    /// Returns a collection of currently connected peers.
294    pub async fn connected_peers(&self) -> Result<Vec<PeerId>, ConnectedPeersError> {
295        let (result_sender, result_receiver) = oneshot::channel();
296
297        trace!("Starting `connected_peers` request");
298
299        self.shared
300            .command_sender
301            .clone()
302            .send(Command::ConnectedPeers { result_sender })
303            .await?;
304
305        result_receiver
306            .await
307            .map_err(|_cancelled| ConnectedPeersError::ConnectedPeers)
308    }
309
310    /// Returns a collection of currently connected servers (typically farmers).
311    pub async fn connected_servers(&self) -> Result<Vec<PeerId>, ConnectedPeersError> {
312        let (result_sender, result_receiver) = oneshot::channel();
313
314        trace!("Starting `connected_servers` request.");
315
316        self.shared
317            .command_sender
318            .clone()
319            .send(Command::ConnectedServers { result_sender })
320            .await?;
321
322        result_receiver
323            .await
324            .map_err(|_cancelled| ConnectedPeersError::ConnectedPeers)
325    }
326
327    /// Bootstraps Kademlia network
328    pub async fn bootstrap(&self) -> Result<(), BootstrapError> {
329        let (result_sender, mut result_receiver) = mpsc::unbounded();
330
331        debug!("Starting `bootstrap` request");
332
333        self.shared
334            .command_sender
335            .clone()
336            .send(Command::Bootstrap {
337                result_sender: Some(result_sender),
338            })
339            .await?;
340
341        for step in 0usize.. {
342            let result = result_receiver.next().await;
343
344            if result.is_some() {
345                debug!(%step, "Kademlia bootstrapping...");
346            } else {
347                break;
348            }
349        }
350
351        Ok(())
352    }
353
354    /// Callback is called when a peer is connected.
355    pub fn on_connected_peer(&self, callback: HandlerFn<PeerId>) -> HandlerId {
356        self.shared.handlers.connected_peer.add(callback)
357    }
358
359    /// Callback is called when a peer is disconnected.
360    pub fn on_disconnected_peer(&self, callback: HandlerFn<PeerId>) -> HandlerId {
361        self.shared.handlers.disconnected_peer.add(callback)
362    }
363
364    /// Callback is called when a routable or unraoutable peer is discovered.
365    pub fn on_discovered_peer(&self, callback: HandlerFn<PeerDiscovered>) -> HandlerId {
366        self.shared.handlers.peer_discovered.add(callback)
367    }
368
369    /// Returns the request batch handle with common "connection permit" slot from the shared pool.
370    pub async fn get_requests_batch_handle(&self) -> NodeRequestsBatchHandle {
371        let permit = self.shared.rate_limiter.acquire_permit().await;
372
373        NodeRequestsBatchHandle {
374            node: self.clone(),
375            _permit: permit,
376        }
377    }
378
379    /// Downgrade to [`WeakNode`]
380    pub fn downgrade(&self) -> WeakNode {
381        WeakNode {
382            shared: Arc::downgrade(&self.shared),
383        }
384    }
385}
386
387/// Weak counterpart of [`Node`]
388#[derive(Debug, Clone)]
389pub struct WeakNode {
390    shared: Weak<Shared>,
391}
392
393impl WeakNode {
394    /// Try to upgrade to [`Node`]
395    pub fn upgrade(&self) -> Option<Node> {
396        self.shared.upgrade().map(|shared| Node { shared })
397    }
398}
399
400/// Requests handle for node operations. These operations share the same semaphore permit for
401/// connection and substream limits. It generally serves for the case when we have
402/// `get-closest-peers` operation followed by request-responses. This way we likely share the same
403/// connection and we don't need to obtain separate semaphore permits for the operations.
404#[derive(Debug)]
405pub struct NodeRequestsBatchHandle {
406    node: Node,
407    _permit: OwnedSemaphorePermit,
408}
409
410impl NodeRequestsBatchHandle {
411    /// Get closest peers by key. Initiate 'find_node' Kademlia operation.
412    pub async fn get_closest_peers(
413        &self,
414        key: Multihash,
415    ) -> Result<impl Stream<Item = PeerId> + use<>, GetClosestPeersError> {
416        self.node.get_closest_peers_internal(key, false).await
417    }
418    /// Sends the generic request to the peer and awaits the result.
419    ///
420    /// Optional addresses will be used for dialing if connection to peer isn't established yet.
421    pub async fn send_generic_request<Request>(
422        &self,
423        peer_id: PeerId,
424        addresses: Vec<Multiaddr>,
425        request: Request,
426    ) -> Result<Request::Response, SendRequestError>
427    where
428        Request: GenericRequest,
429    {
430        self.node
431            .send_generic_request_internal(peer_id, addresses, request, false)
432            .await
433    }
434}