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