Skip to main content

ab_networking/protocols/request_response/handlers/
cached_piece_by_index.rs

1//! Helper for incoming cached piece requests.
2//!
3//! Request handler can be created with [`CachedPieceByIndexRequestHandler`].
4
5#[cfg(test)]
6mod tests;
7
8use crate::protocols::request_response::handlers::generic_request_handler::{
9    GenericRequest, GenericRequestHandler, encode_to_buffer,
10};
11use crate::protocols::request_response::handlers::{decode_piece, encode_piece};
12use crate::protocols::request_response::request_response_factory::ResponsePayload;
13use ab_aligned_buffer::SharedAlignedBuffer;
14use ab_aligned_buffer::alignment::Align1;
15use ab_core_primitives::pieces::{Piece, PieceIndex};
16use derive_more::{Deref, DerefMut, From, Into};
17use libp2p::kad::K_VALUE;
18use libp2p::multiaddr::Protocol;
19use libp2p::{Multiaddr, PeerId};
20use multihash::Multihash;
21use parity_scale_codec::{
22    Compact, CompactLen, Decode, DecodeAll, Encode, EncodeLike, Input, Output,
23};
24use std::sync::Arc;
25
26/// Cached-piece-by-index request.
27///
28/// This is similar to `PieceByIndexRequest`, but will only respond with cached pieces.
29#[derive(Debug, Clone, Eq, PartialEq, Encode, Decode)]
30pub struct CachedPieceByIndexRequest {
31    /// Request key - piece index
32    pub piece_index: PieceIndex,
33    /// Additional pieces that requester is interested in if they are cached locally
34    // TODO: Use `Arc<[PieceIndex]>` once
35    //  https://github.com/paritytech/parity-scale-codec/issues/633 is resolved
36    pub cached_pieces: Arc<Vec<PieceIndex>>,
37}
38
39impl GenericRequest for CachedPieceByIndexRequest {
40    const PROTOCOL_NAME: &'static str = "/subspace/cached-piece-by-index/0.1.0";
41    const LOG_TARGET: &'static str = "cached-piece-by-index-request-response-handler";
42    type Response = CachedPieceByIndexResponse;
43
44    /// Piece is not copied into the payload
45    fn encode_response(response: &Self::Response) -> Option<ResponsePayload> {
46        let CachedPieceByIndexResponse {
47            result,
48            cached_pieces,
49        } = response;
50
51        let mut payload = ResponsePayload::default();
52        match result {
53            PieceResult::Piece(piece) => {
54                // `PieceResult::Piece` variant
55                encode_piece(&mut payload, &0u8, piece)?;
56            }
57            PieceResult::ClosestPeers(_closest_peers) => {
58                payload.push(encode_to_buffer(result)?);
59            }
60        }
61        payload.push(encode_to_buffer(cached_pieces)?);
62
63        Some(payload)
64    }
65
66    /// Piece references the payload without copying it
67    fn decode_response(
68        payload: SharedAlignedBuffer<Align1>,
69    ) -> Result<Self::Response, parity_scale_codec::Error> {
70        let mut input = payload.as_slice();
71        let result = match u8::decode(&mut input)? {
72            0 => PieceResult::Piece(decode_piece(&payload, &mut input)?),
73            1 => PieceResult::ClosestPeers(ClosestPeers::decode(&mut input)?),
74            _ => {
75                return Err("Invalid `PieceResult` variant".into());
76            }
77        };
78        // This is the last field, so it must consume the rest of the payload
79        let cached_pieces = Vec::decode_all(&mut input)?;
80
81        Ok(CachedPieceByIndexResponse {
82            result,
83            cached_pieces,
84        })
85    }
86}
87
88impl CachedPieceByIndexRequest {
89    /// Max number of cached piece indexes to accept per request, equals to the number of source
90    /// shards in a sector and fits nicely into a single TCP packet
91    pub const RECOMMENDED_LIMIT: usize = 128;
92}
93
94/// Closest peers
95#[derive(Debug, Default, PartialEq, Eq, Clone, From, Into, Deref, DerefMut)]
96pub struct ClosestPeers(Vec<(PeerId, Vec<Multiaddr>)>);
97
98impl Encode for ClosestPeers {
99    fn size_hint(&self) -> usize {
100        let mut size = Compact::compact_len(&(self.0.len() as u32));
101
102        for (peer_id, addresses) in &self.0 {
103            size += peer_id.as_ref().encoded_size();
104            size += Compact::compact_len(&(addresses.len() as u32));
105
106            for address in addresses {
107                size += address.as_ref().encoded_size();
108            }
109        }
110
111        size
112    }
113
114    fn encode_to<T>(&self, dest: &mut T)
115    where
116        T: Output + ?Sized,
117    {
118        Compact::from(self.0.len() as u32).encode_to(dest);
119
120        for (peer_id, addresses) in &self.0 {
121            peer_id.as_ref().encode_to(dest);
122            Compact::from(addresses.len() as u32).encode_to(dest);
123
124            for address in addresses {
125                address.as_ref().encode_to(dest);
126            }
127        }
128    }
129}
130
131impl EncodeLike for ClosestPeers {}
132
133impl Decode for ClosestPeers {
134    fn decode<I>(input: &mut I) -> Result<Self, parity_scale_codec::Error>
135    where
136        I: Input,
137    {
138        let mut closest_peers = Vec::with_capacity(K_VALUE.get());
139
140        let closest_peers_count = Compact::<u32>::decode(input)?.0 as usize;
141        for _ in 0..closest_peers_count {
142            let peer_id =
143                PeerId::from_multihash(Multihash::decode(input)?).map_err(|multihash| {
144                    parity_scale_codec::Error::from("Can't create `PeerId` from `Multihash`")
145                        .chain(format!("Code: {}", multihash.code()))
146                })?;
147            let p2p = Multiaddr::from(Protocol::P2p(peer_id));
148            let mut addresses = Vec::new();
149
150            let addresses_count = Compact::<u32>::decode(input)?.0 as usize;
151
152            if addresses_count == 0 {
153                return Err(parity_scale_codec::Error::from(
154                    "List of addresses must not be empty",
155                ));
156            }
157
158            for _ in 0..addresses_count {
159                let address = Multiaddr::try_from(Vec::<u8>::decode(input)?).map_err(|error| {
160                    parity_scale_codec::Error::from("Failed to decode `Multiaddr`")
161                        .chain(error.to_string())
162                })?;
163
164                if !address.ends_with(&p2p) {
165                    return Err(parity_scale_codec::Error::from(
166                        "`Multiaddr` doesn't end with correct p2p suffix",
167                    )
168                    .chain(format!("Address {address}, PeerId {p2p}")));
169                }
170
171                addresses.push(address);
172            }
173
174            closest_peers.push((peer_id, addresses));
175        }
176
177        Ok(Self(closest_peers))
178    }
179}
180
181/// Piece result contains either piece itself or the closest known peers to the piece index
182#[derive(Debug, PartialEq, Eq, Clone, Encode, Decode)]
183pub enum PieceResult {
184    /// Piece was cached locally
185    Piece(Piece),
186    /// Piece was not cached locally, but these are the closest known peers to the piece index
187    ClosestPeers(ClosestPeers),
188}
189
190/// Cached-piece-by-index response, may be cached piece or stored in one of the farms
191#[derive(Debug, PartialEq, Eq, Clone, Encode, Decode)]
192pub struct CachedPieceByIndexResponse {
193    /// Piece result
194    pub result: PieceResult,
195    /// Additional pieces that requester is interested in and are cached locally, order from
196    /// request is not preserved
197    pub cached_pieces: Vec<PieceIndex>,
198}
199
200/// Cached-piece-by-index request handler
201pub type CachedPieceByIndexRequestHandler = GenericRequestHandler<CachedPieceByIndexRequest>;