Skip to main content

subspace_networking/
node.rs

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