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#[derive(Debug, Error)]
21pub enum GetClosestPeersError {
22 #[error("Failed to send command to the node runner: {0}")]
24 SendCommand(#[from] mpsc::SendError),
25 #[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#[derive(Debug, Error)]
39pub enum GetClosestLocalPeersError {
40 #[error("Failed to send command to the node runner: {0}")]
42 SendCommand(#[from] mpsc::SendError),
43 #[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#[derive(Debug, Error)]
57pub enum SendRequestError {
58 #[error("Failed to send command to the node runner: {0}")]
60 SendCommand(#[from] mpsc::SendError),
61 #[error("Node runner was dropped")]
63 NodeRunnerDropped,
64 #[error("Underlying protocol returned an error: {0}")]
66 ProtocolFailure(#[from] request_response_factory::RequestFailure),
67 #[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 #[error("Failed to send command to the node runner: {0}")]
83 SendCommand(#[from] mpsc::SendError),
84 #[error("Node runner was dropped")]
86 NodeRunnerDropped,
87 #[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 #[error("Failed to send command to the node runner: {0}")]
103 SendCommand(#[from] mpsc::SendError),
104 #[error("Node runner was dropped")]
106 NodeRunnerDropped,
107 #[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#[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 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 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 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 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 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 Ok(result_receiver)
245 }
246
247 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 #[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 pub fn listeners(&self) -> Vec<Multiaddr> {
270 self.shared.listeners.lock().clone()
271 }
272
273 pub fn external_addresses(&self) -> Vec<Multiaddr> {
275 self.shared.external_addresses.lock().clone()
276 }
277
278 pub fn on_new_listener(&self, callback: HandlerFn<Multiaddr>) -> HandlerId {
280 self.shared.handlers.new_listener.add(callback)
281 }
282
283 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 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 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 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 pub fn on_connected_peer(&self, callback: HandlerFn<PeerId>) -> HandlerId {
357 self.shared.handlers.connected_peer.add(callback)
358 }
359
360 pub fn on_disconnected_peer(&self, callback: HandlerFn<PeerId>) -> HandlerId {
362 self.shared.handlers.disconnected_peer.add(callback)
363 }
364
365 pub fn on_discovered_peer(&self, callback: HandlerFn<PeerDiscovered>) -> HandlerId {
367 self.shared.handlers.peer_discovered.add(callback)
368 }
369
370 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 pub fn downgrade(&self) -> WeakNode {
382 WeakNode {
383 shared: Arc::downgrade(&self.shared),
384 }
385 }
386}
387
388#[derive(Debug, Clone)]
390pub struct WeakNode {
391 shared: Weak<Shared>,
392}
393
394impl WeakNode {
395 pub fn upgrade(&self) -> Option<Node> {
397 self.shared.upgrade().map(|shared| Node { shared })
398 }
399}
400
401pub struct NodeRequestsBatchHandle {
406 node: Node,
407 _permit: OwnedSemaphorePermit,
408}
409
410impl NodeRequestsBatchHandle {
411 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 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}