1#[cfg(test)]
4mod tests;
5
6use crate::constructor::DummyRecordStore;
7use crate::protocols::request_response::handlers::cached_piece_by_index::{
8 CachedPieceByIndexRequest, CachedPieceByIndexResponse, PieceResult,
9};
10use crate::protocols::request_response::handlers::piece_by_index::{
11 PieceByIndexRequest, PieceByIndexResponse,
12};
13use crate::utils::multihash::ToMultihash;
14use crate::{Multihash, Node};
15use async_lock::{Semaphore, SemaphoreGuard};
16use async_trait::async_trait;
17use futures::channel::mpsc;
18use futures::future::FusedFuture;
19use futures::stream::FuturesUnordered;
20use futures::task::noop_waker_ref;
21use futures::{FutureExt, Stream, StreamExt, stream};
22use libp2p::kad::{Behaviour as Kademlia, KBucketKey};
23use libp2p::swarm::NetworkBehaviour;
24use libp2p::{Multiaddr, PeerId};
25use rand::prelude::*;
26use std::any::type_name;
27use std::collections::{HashMap, HashSet};
28use std::pin::Pin;
29use std::sync::Arc;
30use std::task::{Context, Poll};
31use std::{fmt, iter};
32use subspace_core_primitives::pieces::{Piece, PieceIndex};
33use tokio_stream::StreamMap;
34use tracing::{Instrument, debug, trace, warn};
35
36#[async_trait]
38pub trait PieceValidator: Sync + Send {
39 async fn validate_piece(
41 &self,
42 source_peer_id: PeerId,
43 piece_index: PieceIndex,
44 piece: Piece,
45 ) -> Option<Piece>;
46}
47
48#[derive(Debug, Clone, Copy)]
50pub struct NoPieceValidator;
51
52#[async_trait]
53impl PieceValidator for NoPieceValidator {
54 async fn validate_piece(&self, _: PeerId, _: PieceIndex, piece: Piece) -> Option<Piece> {
55 Some(piece)
56 }
57}
58
59#[derive(Clone)]
62pub struct PieceProvider<PV> {
63 node: Node,
64 piece_validator: PV,
65 piece_downloading_semaphore: Arc<Semaphore>,
66}
67
68impl<PV> fmt::Debug for PieceProvider<PV> {
69 #[inline]
70 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
71 f.debug_struct(&format!("PieceProvider<{}>", type_name::<PV>()))
72 .finish_non_exhaustive()
73 }
74}
75
76impl<PV> PieceProvider<PV>
77where
78 PV: PieceValidator,
79{
80 pub fn new(
82 node: Node,
83 piece_validator: PV,
84 piece_downloading_semaphore: Arc<Semaphore>,
85 ) -> Self {
86 Self {
87 node,
88 piece_validator,
89 piece_downloading_semaphore,
90 }
91 }
92
93 pub async fn get_from_cache<'a, PieceIndices>(
97 &'a self,
98 piece_indices: PieceIndices,
99 ) -> impl Stream<Item = (PieceIndex, Option<Piece>)> + Unpin + 'a
100 where
101 PieceIndices: IntoIterator<Item = PieceIndex> + 'a,
102 {
103 let download_id = rand::random::<u64>();
104 let (tx, mut rx) = mpsc::unbounded();
105 let fut = async move {
106 let not_downloaded_pieces = download_cached_pieces(
107 piece_indices,
108 &self.node,
109 &self.piece_validator,
110 &tx,
111 &self.piece_downloading_semaphore,
112 )
113 .await;
114
115 if not_downloaded_pieces.is_empty() {
116 debug!("Done");
117 return;
118 }
119
120 for piece_index in not_downloaded_pieces {
121 tx.unbounded_send((piece_index, None))
122 .expect("This future isn't polled after receiver is dropped; qed");
123 }
124
125 debug!("Done #2");
126 };
127
128 let mut fut = Box::pin(fut.instrument(tracing::info_span!("", %download_id)).fuse());
129
130 stream::poll_fn(move |cx| {
132 if !fut.is_terminated() {
133 let _ = fut.poll_unpin(cx);
135 }
136
137 if let Poll::Ready(maybe_result) = rx.poll_next_unpin(cx) {
138 return Poll::Ready(maybe_result);
139 }
140
141 Poll::Pending
143 })
144 }
145
146 pub async fn get_piece_from_cache(&self, piece_index: PieceIndex) -> Option<Piece> {
150 self.get_from_cache(iter::once(piece_index))
151 .await
152 .next()
153 .await
154 .and_then(|(_piece_index, maybe_piece)| maybe_piece)
155 }
156
157 pub async fn get_piece_from_peer(
159 &self,
160 peer_id: PeerId,
161 piece_index: PieceIndex,
162 ) -> Option<Piece> {
163 let PieceByIndexResponse {
165 piece,
166 cached_pieces: _,
167 } = self
168 .node
169 .send_generic_request(
170 peer_id,
171 Vec::new(),
172 PieceByIndexRequest {
173 piece_index,
174 cached_pieces: Arc::default(),
175 },
176 )
177 .await
178 .inspect_err(|error| debug!(%peer_id, %piece_index, ?error, "Piece request failed"))
179 .ok()?;
180
181 if let Some(piece) = piece {
182 trace!(%peer_id, %piece_index, "Piece request succeeded");
183
184 return self
185 .piece_validator
186 .validate_piece(peer_id, piece_index, piece)
187 .await;
188 } else {
189 debug!(%peer_id, %piece_index, "Piece request returned empty piece");
190 }
191
192 None
193 }
194
195 pub async fn get_piece_from_archival_storage(
198 &self,
199 piece_index: PieceIndex,
200 max_random_walking_rounds: usize,
201 ) -> Option<Piece> {
202 trace!(%piece_index, "Getting piece from archival storage..");
204
205 let connected_servers = {
206 let connected_servers = match self.node.connected_servers().await {
207 Ok(connected_servers) => connected_servers,
208 Err(err) => {
209 debug!(%piece_index, ?err, "Cannot get connected peers (DSN L1 lookup)");
210
211 Default::default()
212 }
213 };
214
215 HashSet::<PeerId>::from_iter(connected_servers)
216 };
217
218 if connected_servers.is_empty() {
219 debug!(%piece_index, "Cannot acquire piece from no connected peers (DSN L1 lookup)");
220 } else {
221 for peer_id in connected_servers.iter() {
222 let maybe_piece = self.get_piece_from_peer(*peer_id, piece_index).await;
223
224 if maybe_piece.is_some() {
225 trace!(%piece_index, %peer_id, "DSN L1 lookup from connected peers succeeded");
226
227 return maybe_piece;
228 }
229 }
230 }
231
232 trace!(%piece_index, "Getting piece from DSN L1 using random walk.");
233 let random_walk_result = self
234 .get_piece_by_random_walking(piece_index, max_random_walking_rounds)
235 .await;
236
237 if random_walk_result.is_some() {
238 trace!(%piece_index, "DSN L1 lookup via random walk succeeded");
239
240 return random_walk_result;
241 } else {
242 debug!(
243 %piece_index,
244 %max_random_walking_rounds,
245 "Cannot acquire piece from DSN L1: random walk failed"
246 );
247 }
248
249 None
250 }
251
252 async fn get_piece_by_random_walking(
254 &self,
255 piece_index: PieceIndex,
256 walking_rounds: usize,
257 ) -> Option<Piece> {
258 for round in 0..walking_rounds {
259 debug!(%piece_index, round, "Random walk round");
260
261 let result = self
262 .get_piece_by_random_walking_from_single_round(piece_index, round)
263 .await;
264
265 if result.is_some() {
266 return result;
267 }
268 }
269
270 debug!(%piece_index, "Random walking piece retrieval failed.");
271
272 None
273 }
274
275 async fn get_piece_by_random_walking_from_single_round(
277 &self,
278 piece_index: PieceIndex,
279 round: usize,
280 ) -> Option<Piece> {
281 trace!(%piece_index, "get_piece_by_random_walking round");
283
284 let key = PeerId::random();
286
287 let request_batch = self.node.get_requests_batch_handle().await;
288 let mut get_closest_peers_stream = request_batch
289 .get_closest_peers(key.into())
290 .await
291 .inspect_err(|err| warn!(%piece_index, ?key, ?err, %round, "get_closest_peers returned an error"))
292 .ok()?;
293
294 while let Some(peer_id) = get_closest_peers_stream.next().await {
295 trace!(%piece_index, %peer_id, %round, "get_closest_peers returned an item");
296
297 let Ok(PieceByIndexResponse {
298 piece,
299 cached_pieces: _,
300 }) = request_batch
301 .send_generic_request(
302 peer_id,
303 Vec::new(),
304 PieceByIndexRequest {
305 piece_index,
306 cached_pieces: Arc::default(),
307 },
308 )
309 .await
310 .inspect_err(
311 |error| debug!(%peer_id, %piece_index, ?key, %round, ?error, "Piece request failed."),
312 )
313 else {
314 continue;
315 };
316
317 if let Some(piece) = piece {
318 trace!(%peer_id, %piece_index, ?key, %round, "Piece request succeeded.");
319
320 return self
321 .piece_validator
322 .validate_piece(peer_id, piece_index, piece)
323 .await;
324 } else {
325 debug!(%peer_id, %piece_index, ?key, %round, "Piece request returned empty piece.");
326 }
327 }
328
329 None
330 }
331}
332
333struct KademliaWrapper {
335 local_peer_id: PeerId,
336 kademlia: Kademlia<DummyRecordStore>,
337}
338
339impl KademliaWrapper {
340 fn new(local_peer_id: PeerId) -> Self {
341 Self {
342 local_peer_id,
343 kademlia: Kademlia::new(local_peer_id, DummyRecordStore),
344 }
345 }
346
347 fn add_peer(&mut self, peer_id: &PeerId, addresses: Vec<Multiaddr>) {
348 for address in addresses {
349 self.kademlia.add_address(peer_id, address);
350 }
351 while self
352 .kademlia
353 .poll(&mut Context::from_waker(noop_waker_ref()))
354 .is_ready()
355 {
356 }
358 }
359
360 fn closest_peers(
362 &mut self,
363 key: &KBucketKey<Multihash>,
364 ) -> impl Iterator<Item = (PeerId, Vec<Multiaddr>)> + 'static {
365 let mut closest_peers = self
366 .kademlia
367 .find_closest_local_peers(key, &self.local_peer_id)
368 .map(|peer| {
369 (
370 KBucketKey::from(peer.node_id).distance(key),
371 peer.node_id,
372 peer.multiaddrs,
373 )
374 })
375 .collect::<Vec<_>>();
376
377 closest_peers.sort_unstable_by_key(|a| a.0);
378 closest_peers
379 .into_iter()
380 .map(|(_distance, peer_id, addresses)| (peer_id, addresses))
381 }
382}
383
384async fn download_cached_pieces<PV, PieceIndices>(
387 piece_indices: PieceIndices,
388 node: &Node,
389 piece_validator: &PV,
390 results: &mpsc::UnboundedSender<(PieceIndex, Option<Piece>)>,
391 semaphore: &Semaphore,
392) -> impl ExactSizeIterator<Item = PieceIndex>
393where
394 PV: PieceValidator,
395 PieceIndices: IntoIterator<Item = PieceIndex>,
396{
397 let mut pieces_to_download = piece_indices
403 .into_iter()
404 .map(|piece_index| async move {
405 let mut kademlia = KademliaWrapper::new(node.id());
406 let key = piece_index.to_multihash();
407
408 let local_closest_peers = node
409 .get_closest_local_peers(key, None)
410 .await
411 .unwrap_or_default();
412
413 for (peer_id, addresses) in local_closest_peers {
415 kademlia.add_peer(&peer_id, addresses);
416 }
417
418 (piece_index, kademlia)
419 })
420 .collect::<FuturesUnordered<_>>()
421 .collect::<HashMap<_, _>>()
422 .await;
423
424 let num_pieces = pieces_to_download.len();
425 debug!(%num_pieces, "Starting");
426
427 let mut checked_peers = HashSet::new();
428
429 let Ok(connected_servers) = node.connected_servers().await else {
430 trace!("Connected servers error");
431 return pieces_to_download.into_keys();
432 };
433
434 let num_connected_servers = connected_servers.len();
435 debug!(
436 %num_connected_servers,
437 %num_pieces,
438 "Starting downloading"
439 );
440
441 let mut downloading_stream = connected_servers
443 .into_iter()
444 .take(num_pieces)
445 .enumerate()
446 .map(|(peer_index, peer_id)| {
447 checked_peers.insert(peer_id);
448
449 let step = num_pieces / num_connected_servers.min(num_pieces);
451
452 let mut check_cached_pieces = pieces_to_download
455 .keys()
456 .cycle()
457 .skip(step * peer_index)
458 .take(num_pieces.min(CachedPieceByIndexRequest::RECOMMENDED_LIMIT + 1))
460 .copied()
461 .collect::<Vec<_>>();
462 let piece_index = check_cached_pieces.swap_remove(0);
464
465 trace!(%peer_id, %piece_index, "Downloading piece from initially connected peer");
466
467 let permit = semaphore.try_acquire();
468
469 let fut = async move {
470 let permit = match permit {
471 Some(permit) => permit,
472 None => semaphore.acquire().await,
473 };
474
475 download_cached_piece_from_peer(
476 node,
477 piece_validator,
478 peer_id,
479 Vec::new(),
480 Arc::new(check_cached_pieces),
481 piece_index,
482 HashSet::new(),
483 HashSet::new(),
484 permit,
485 )
486 .await
487 };
488
489 (piece_index, Box::pin(fut.into_stream()) as _)
490 })
491 .collect::<StreamMap<_, _>>();
492
493 loop {
494 let mut additional_pieces_to_download = (num_pieces / 2)
497 .max(1)
498 .saturating_sub(downloading_stream.len());
499 if additional_pieces_to_download > 0 {
500 trace!(
501 %additional_pieces_to_download,
502 num_pieces,
503 currently_downloading = %downloading_stream.len(),
504 "Downloading additional pieces from closest peers"
505 );
506 'outer: for peer_id in node
508 .connected_servers()
509 .await
510 .unwrap_or_default()
511 .into_iter()
512 .filter(|peer_id| checked_peers.insert(*peer_id))
513 .take(additional_pieces_to_download)
514 {
515 let permit = if downloading_stream.is_empty() {
516 semaphore.acquire().await
517 } else if let Some(permit) = semaphore.try_acquire() {
518 permit
519 } else {
520 break;
521 };
522
523 for &piece_index in pieces_to_download.keys() {
524 if downloading_stream.contains_key(&piece_index) {
525 continue;
526 }
527
528 trace!(%peer_id, %piece_index, "Downloading piece from newly connected peer");
529
530 let check_cached_pieces = sample_cached_piece_indices(
531 pieces_to_download.keys(),
532 &HashSet::new(),
533 &HashSet::new(),
534 piece_index,
535 );
536 let fut = download_cached_piece_from_peer(
537 node,
538 piece_validator,
539 peer_id,
540 Vec::new(),
541 Arc::new(check_cached_pieces),
542 piece_index,
543 HashSet::new(),
544 HashSet::new(),
545 permit,
546 );
547
548 downloading_stream.insert(piece_index, Box::pin(fut.into_stream()) as _);
549 additional_pieces_to_download -= 1;
550
551 continue 'outer;
552 }
553
554 break;
555 }
556
557 let pieces_indices_to_download = pieces_to_download.keys().copied().collect::<Vec<_>>();
561 for piece_index in pieces_indices_to_download {
562 if additional_pieces_to_download == 0 {
563 break;
564 }
565 if downloading_stream.contains_key(&piece_index) {
566 continue;
567 }
568 let permit = if downloading_stream.is_empty() {
569 semaphore.acquire().await
570 } else if let Some(permit) = semaphore.try_acquire() {
571 permit
572 } else {
573 break;
574 };
575
576 let kbucket_key = KBucketKey::from(piece_index.to_multihash());
577 let closest_peers_to_check = pieces_to_download
578 .get_mut(&piece_index)
579 .expect("Entries are not removed here; qed")
580 .closest_peers(&kbucket_key);
581 for (peer_id, addresses) in closest_peers_to_check {
582 if !checked_peers.insert(peer_id) {
583 continue;
584 }
585
586 trace!(%peer_id, %piece_index, "Downloading piece from closest peer");
587
588 let check_cached_pieces = sample_cached_piece_indices(
589 pieces_to_download.keys(),
590 &HashSet::new(),
591 &HashSet::new(),
592 piece_index,
593 );
594 let fut = download_cached_piece_from_peer(
595 node,
596 piece_validator,
597 peer_id,
598 addresses,
599 Arc::new(check_cached_pieces),
600 piece_index,
601 HashSet::new(),
602 HashSet::new(),
603 permit,
604 );
605
606 downloading_stream.insert(piece_index, Box::pin(fut.into_stream()) as _);
607 additional_pieces_to_download -= 1;
608 break;
609 }
610 }
611
612 trace!(
613 pieces_left = %additional_pieces_to_download,
614 "Initiated downloading additional pieces from closest peers"
615 );
616 }
617
618 let Some((piece_index, result)) = downloading_stream.next().await else {
619 if !pieces_to_download.is_empty() {
620 debug!(
621 %num_pieces,
622 to_download = %pieces_to_download.len(),
623 "Finished downloading early"
624 );
625 break;
627 }
628 break;
629 };
630 downloading_stream.remove(&piece_index);
633 process_downloading_result(
634 piece_index,
635 result,
636 &mut pieces_to_download,
637 &mut downloading_stream,
638 node,
639 piece_validator,
640 results,
641 );
642
643 if pieces_to_download.is_empty() {
644 break;
645 }
646 }
647
648 pieces_to_download.into_keys()
649}
650
651fn process_downloading_result<'a, 'b, PV>(
652 piece_index: PieceIndex,
653 result: DownloadedPieceFromPeer<'a>,
654 pieces_to_download: &'b mut HashMap<PieceIndex, KademliaWrapper>,
655 downloading_stream: &'b mut StreamMap<
656 PieceIndex,
657 Pin<Box<dyn Stream<Item = DownloadedPieceFromPeer<'a>> + Send + 'a>>,
658 >,
659 node: &'a Node,
660 piece_validator: &'a PV,
661 results: &'a mpsc::UnboundedSender<(PieceIndex, Option<Piece>)>,
662) where
663 PV: PieceValidator,
664{
665 let DownloadedPieceFromPeer {
666 peer_id,
667 result,
668 mut cached_pieces,
669 not_cached_pieces,
670 permit,
671 } = result;
672 trace!(%piece_index, %peer_id, result = %result.is_some(), "Piece response");
673
674 let Some(result) = result else {
675 return;
677 };
678
679 match result {
680 PieceResult::Piece(piece) => {
681 trace!(%piece_index, %peer_id, "Got piece");
682
683 pieces_to_download.remove(&piece_index);
685
686 results
687 .unbounded_send((piece_index, Some(piece)))
688 .expect("This future isn't polled after receiver is dropped; qed");
689
690 if pieces_to_download.is_empty() {
691 return;
692 }
693
694 cached_pieces.remove(&piece_index);
695 }
696 PieceResult::ClosestPeers(closest_peers) => {
697 trace!(%piece_index, %peer_id, "Got closest peers");
698
699 if let Some(kademlia) = pieces_to_download.get_mut(&piece_index) {
701 for (peer_id, addresses) in Vec::from(closest_peers) {
702 kademlia.add_peer(&peer_id, addresses);
703 }
704 }
705
706 if cached_pieces.remove(&piece_index) {
708 return;
709 }
710 }
711 }
712
713 let mut maybe_piece_index_to_download_next = None;
714 cached_pieces.retain(|piece_index| {
716 if !pieces_to_download.contains_key(piece_index) {
718 return false;
719 }
720
721 if maybe_piece_index_to_download_next.is_none()
723 && !downloading_stream.contains_key(piece_index)
724 {
725 maybe_piece_index_to_download_next.replace(*piece_index);
726 return true;
728 }
729
730 true
732 });
733
734 let piece_index_to_download_next = if let Some(piece_index) = maybe_piece_index_to_download_next
735 {
736 trace!(%piece_index, %peer_id, "Next piece to download from peer");
737 piece_index
738 } else {
739 trace!(%peer_id, "Peer doesn't have anything else");
740 return;
742 };
743
744 let fut = download_cached_piece_from_peer(
745 node,
746 piece_validator,
747 peer_id,
748 Vec::new(),
749 Arc::new(sample_cached_piece_indices(
752 pieces_to_download.keys(),
753 &cached_pieces,
754 ¬_cached_pieces,
755 piece_index_to_download_next,
756 )),
757 piece_index_to_download_next,
758 cached_pieces,
759 not_cached_pieces,
760 permit,
761 );
762 downloading_stream.insert(piece_index_to_download_next, Box::pin(fut.into_stream()));
763}
764
765fn sample_cached_piece_indices<'a, I>(
766 pieces_to_download: I,
767 cached_pieces: &HashSet<PieceIndex>,
768 not_cached_pieces: &HashSet<PieceIndex>,
769 piece_index_to_download_next: PieceIndex,
770) -> Vec<PieceIndex>
771where
772 I: Iterator<Item = &'a PieceIndex>,
773{
774 pieces_to_download
775 .filter_map(|piece_index| {
778 if piece_index == &piece_index_to_download_next
779 || cached_pieces.contains(piece_index)
780 || not_cached_pieces.contains(piece_index)
781 {
782 None
783 } else {
784 Some(*piece_index)
785 }
786 })
787 .sample(
788 &mut rand::rng(),
789 CachedPieceByIndexRequest::RECOMMENDED_LIMIT,
790 )
791}
792
793struct DownloadedPieceFromPeer<'a> {
794 peer_id: PeerId,
795 result: Option<PieceResult>,
796 cached_pieces: HashSet<PieceIndex>,
797 not_cached_pieces: HashSet<PieceIndex>,
798 permit: SemaphoreGuard<'a>,
799}
800
801#[allow(clippy::too_many_arguments)]
805async fn download_cached_piece_from_peer<'a, PV>(
806 node: &'a Node,
807 piece_validator: &'a PV,
808 peer_id: PeerId,
809 addresses: Vec<Multiaddr>,
810 check_cached_pieces: Arc<Vec<PieceIndex>>,
811 piece_index: PieceIndex,
812 mut cached_pieces: HashSet<PieceIndex>,
813 mut not_cached_pieces: HashSet<PieceIndex>,
814 permit: SemaphoreGuard<'a>,
815) -> DownloadedPieceFromPeer<'a>
816where
817 PV: PieceValidator,
818{
819 let result = match node
820 .send_generic_request(
821 peer_id,
822 addresses,
823 CachedPieceByIndexRequest {
824 piece_index,
825 cached_pieces: Arc::clone(&check_cached_pieces),
826 },
827 )
828 .await
829 {
830 Ok(response) => {
831 let CachedPieceByIndexResponse {
832 result,
833 cached_pieces,
834 } = response;
835
836 match result {
837 PieceResult::Piece(piece) => piece_validator
838 .validate_piece(peer_id, piece_index, piece)
839 .await
840 .map(|piece| CachedPieceByIndexResponse {
841 result: PieceResult::Piece(piece),
842 cached_pieces,
843 }),
844 PieceResult::ClosestPeers(closest_peers) => Some(CachedPieceByIndexResponse {
845 result: PieceResult::ClosestPeers(closest_peers),
846 cached_pieces,
847 }),
848 }
849 }
850 Err(error) => {
851 debug!(%error, %peer_id, %piece_index, "Failed to download cached piece from peer");
852
853 None
854 }
855 };
856
857 match result {
858 Some(result) => {
859 cached_pieces.extend(result.cached_pieces);
860 not_cached_pieces.extend(
861 check_cached_pieces
862 .iter()
863 .filter(|piece_index| !cached_pieces.contains(piece_index))
864 .copied(),
865 );
866
867 DownloadedPieceFromPeer {
868 peer_id,
869 result: Some(result.result),
870 cached_pieces: { cached_pieces },
871 not_cached_pieces,
872 permit,
873 }
874 }
875 None => DownloadedPieceFromPeer {
876 peer_id,
877 result: None,
878 cached_pieces,
879 not_cached_pieces,
880 permit,
881 },
882 }
883}