1use crate::{
11 sync::{
12 block_relay_protocol::{
13 BlockDownloader, BlockRelayParams, BlockResponseError, BlockServer,
14 },
15 schema::v1::{
16 block_request::FromBlock as FromBlockSchema, BlockRequest as BlockRequestSchema,
17 BlockResponse as BlockResponseSchema, BlockResponse, Direction,
18 },
19 service::network::NetworkServiceHandle,
20 },
21 LOG_TARGET,
22};
23
24use codec::{Decode, DecodeAll, Encode};
25use futures::{channel::oneshot, stream::StreamExt};
26use log::debug;
27use prost::Message;
28use schnellru::{ByLength, LruMap};
29
30use soil_client::blockchain::HeaderBackend;
31use soil_client::client_api::BlockBackend;
32use soil_network::common::sync::message::{BlockAttributes, BlockData, BlockRequest, FromBlock};
33use soil_network::types::PeerId;
34use soil_network::{
35 config::ProtocolId,
36 request_responses::{IfDisconnected, IncomingRequest, OutgoingResponse, RequestFailure},
37 service::traits::RequestResponseConfig,
38 types::ProtocolName,
39 NetworkBackend, MAX_RESPONSE_SIZE,
40};
41use subsoil::runtime::{
42 generic::BlockId,
43 traits::{Block as BlockT, Header, One, Zero},
44};
45
46use std::{
47 cmp::min,
48 hash::{Hash, Hasher},
49 sync::Arc,
50 time::Duration,
51};
52
53pub(crate) const MAX_BLOCKS_IN_RESPONSE: usize = 128;
55
56const MAX_NUMBER_OF_SAME_REQUESTS_PER_PEER: usize = 2;
57
58mod rep {
59 use soil_network::ReputationChange as Rep;
60
61 pub const SAME_REQUEST: Rep = Rep::new_fatal("Same block request multiple times");
63
64 pub const SAME_SMALL_REQUEST: Rep =
66 Rep::new(-(1 << 10), "same small block request multiple times");
67}
68
69pub fn generate_protocol_config<
72 Hash: AsRef<[u8]>,
73 B: BlockT,
74 N: NetworkBackend<B, <B as BlockT>::Hash>,
75>(
76 protocol_id: &ProtocolId,
77 genesis_hash: Hash,
78 fork_id: Option<&str>,
79 inbound_queue: async_channel::Sender<IncomingRequest>,
80) -> N::RequestResponseProtocolConfig {
81 N::request_response_config(
82 generate_protocol_name(genesis_hash, fork_id).into(),
83 std::iter::once(generate_legacy_protocol_name(protocol_id).into()).collect(),
84 1024 * 1024,
85 MAX_RESPONSE_SIZE,
86 Duration::from_secs(20),
87 Some(inbound_queue),
88 )
89}
90
91fn generate_protocol_name<Hash: AsRef<[u8]>>(genesis_hash: Hash, fork_id: Option<&str>) -> String {
93 let genesis_hash = genesis_hash.as_ref();
94 if let Some(fork_id) = fork_id {
95 format!("/{}/{}/sync/2", array_bytes::bytes2hex("", genesis_hash), fork_id)
96 } else {
97 format!("/{}/sync/2", array_bytes::bytes2hex("", genesis_hash))
98 }
99}
100
101fn generate_legacy_protocol_name(protocol_id: &ProtocolId) -> String {
103 format!("/{}/sync/2", protocol_id.as_ref())
104}
105
106#[derive(Eq, PartialEq, Clone)]
108struct SeenRequestsKey<B: BlockT> {
109 peer: PeerId,
110 from: BlockId<B>,
111 max_blocks: usize,
112 direction: Direction,
113 attributes: BlockAttributes,
114 support_multiple_justifications: bool,
115}
116
117#[allow(clippy::derived_hash_with_manual_eq)]
118impl<B: BlockT> Hash for SeenRequestsKey<B> {
119 fn hash<H: Hasher>(&self, state: &mut H) {
120 self.peer.hash(state);
121 self.max_blocks.hash(state);
122 self.direction.hash(state);
123 self.attributes.hash(state);
124 self.support_multiple_justifications.hash(state);
125 match self.from {
126 BlockId::Hash(h) => h.hash(state),
127 BlockId::Number(n) => n.hash(state),
128 }
129 }
130}
131
132enum SeenRequestsValue {
134 First,
136 Fulfilled(usize),
138}
139
140pub struct BlockRequestHandler<B: BlockT, Client> {
143 client: Arc<Client>,
144 request_receiver: async_channel::Receiver<IncomingRequest>,
145 seen_requests: LruMap<SeenRequestsKey<B>, SeenRequestsValue>,
149}
150
151impl<B, Client> BlockRequestHandler<B, Client>
152where
153 B: BlockT,
154 Client: HeaderBackend<B> + BlockBackend<B> + Send + Sync + 'static,
155{
156 pub fn new<N: NetworkBackend<B, <B as BlockT>::Hash>>(
158 network: NetworkServiceHandle,
159 protocol_id: &ProtocolId,
160 fork_id: Option<&str>,
161 client: Arc<Client>,
162 num_peer_hint: usize,
163 ) -> BlockRelayParams<B, N> {
164 let capacity = std::cmp::max(num_peer_hint, 1);
167 let (tx, request_receiver) = async_channel::bounded(capacity);
168
169 let protocol_config = generate_protocol_config::<_, B, N>(
170 protocol_id,
171 client
172 .block_hash(0u32.into())
173 .ok()
174 .flatten()
175 .expect("Genesis block exists; qed"),
176 fork_id,
177 tx,
178 );
179
180 let capacity = ByLength::new(num_peer_hint.max(1) as u32 * 2);
181 let seen_requests = LruMap::new(capacity);
182
183 BlockRelayParams {
184 server: Box::new(Self { client, request_receiver, seen_requests }),
185 downloader: Arc::new(FullBlockDownloader::new(
186 protocol_config.protocol_name().clone(),
187 network,
188 )),
189 request_response_config: protocol_config,
190 }
191 }
192
193 async fn process_requests(&mut self) {
195 while let Some(request) = self.request_receiver.next().await {
196 let IncomingRequest { peer, payload, pending_response } = request;
197
198 match self.handle_request(payload, pending_response, &peer) {
199 Ok(()) => debug!(target: LOG_TARGET, "Handled block request from {}.", peer),
200 Err(e) => debug!(
201 target: LOG_TARGET,
202 "Failed to handle block request from {}: {}", peer, e,
203 ),
204 }
205 }
206 }
207
208 fn handle_request(
209 &mut self,
210 payload: Vec<u8>,
211 pending_response: oneshot::Sender<OutgoingResponse>,
212 peer: &PeerId,
213 ) -> Result<(), HandleRequestError> {
214 let request = crate::sync::schema::v1::BlockRequest::decode(&payload[..])?;
215
216 let from_block_id = match request.from_block.ok_or(HandleRequestError::MissingFromField)? {
217 FromBlockSchema::Hash(ref h) => {
218 let h = Decode::decode(&mut h.as_ref())?;
219 BlockId::<B>::Hash(h)
220 },
221 FromBlockSchema::Number(ref n) => {
222 let n = Decode::decode(&mut n.as_ref())?;
223 BlockId::<B>::Number(n)
224 },
225 };
226
227 let max_blocks = if request.max_blocks == 0 {
228 MAX_BLOCKS_IN_RESPONSE
229 } else {
230 min(request.max_blocks as usize, MAX_BLOCKS_IN_RESPONSE)
231 };
232
233 let direction =
234 i32::try_into(request.direction).map_err(|_| HandleRequestError::ParseDirection)?;
235
236 let attributes = BlockAttributes::from_be_u32(request.fields)?;
237
238 let support_multiple_justifications = request.support_multiple_justifications;
239
240 let key = SeenRequestsKey {
241 peer: *peer,
242 max_blocks,
243 direction,
244 from: from_block_id,
245 attributes,
246 support_multiple_justifications,
247 };
248
249 let mut reputation_change = None;
250
251 let small_request = attributes
252 .difference(BlockAttributes::HEADER | BlockAttributes::JUSTIFICATION)
253 .is_empty();
254
255 match self.seen_requests.get(&key) {
256 Some(SeenRequestsValue::First) => {},
257 Some(SeenRequestsValue::Fulfilled(ref mut requests)) => {
258 *requests = requests.saturating_add(1);
259
260 if *requests > MAX_NUMBER_OF_SAME_REQUESTS_PER_PEER {
261 reputation_change = Some(if small_request {
262 rep::SAME_SMALL_REQUEST
263 } else {
264 rep::SAME_REQUEST
265 });
266 }
267 },
268 None => {
269 self.seen_requests.insert(key.clone(), SeenRequestsValue::First);
270 },
271 }
272
273 debug!(
274 target: LOG_TARGET,
275 "Handling block request from {peer}: Starting at `{from_block_id:?}` with \
276 maximum blocks of `{max_blocks}`, reputation_change: `{reputation_change:?}`, \
277 small_request `{small_request:?}`, direction `{direction:?}` and \
278 attributes `{attributes:?}`.",
279 );
280
281 let maybe_block_response = if reputation_change.is_none() || small_request {
282 let block_response = self.get_block_response(
283 attributes,
284 from_block_id,
285 direction,
286 max_blocks,
287 support_multiple_justifications,
288 )?;
289
290 if block_response
292 .blocks
293 .iter()
294 .any(|b| !b.header.is_empty() || !b.body.is_empty() || b.is_empty_justification)
295 {
296 if let Some(value) = self.seen_requests.get(&key) {
297 if let SeenRequestsValue::First = value {
300 *value = SeenRequestsValue::Fulfilled(1);
301 }
302 }
303 }
304
305 Some(block_response)
306 } else {
307 None
308 };
309
310 debug!(
311 target: LOG_TARGET,
312 "Sending result of block request from {peer} starting at `{from_block_id:?}`: \
313 blocks: {:?}, data: {:?}",
314 maybe_block_response.as_ref().map(|res| res.blocks.len()),
315 maybe_block_response.as_ref().map(|res| res.encoded_len()),
316 );
317
318 let result = if let Some(block_response) = maybe_block_response {
319 let mut data = Vec::with_capacity(block_response.encoded_len());
320 block_response.encode(&mut data)?;
321 Ok(data)
322 } else {
323 Err(())
324 };
325
326 pending_response
327 .send(OutgoingResponse {
328 result,
329 reputation_changes: reputation_change.into_iter().collect(),
330 sent_feedback: None,
331 })
332 .map_err(|_| HandleRequestError::SendResponse)
333 }
334
335 fn get_block_response(
336 &self,
337 attributes: BlockAttributes,
338 mut block_id: BlockId<B>,
339 direction: Direction,
340 max_blocks: usize,
341 support_multiple_justifications: bool,
342 ) -> Result<BlockResponse, HandleRequestError> {
343 let get_header = attributes.contains(BlockAttributes::HEADER);
344 let get_body = attributes.contains(BlockAttributes::BODY);
345 let get_indexed_body = attributes.contains(BlockAttributes::INDEXED_BODY);
346 let get_justification = attributes.contains(BlockAttributes::JUSTIFICATION);
347
348 let mut blocks = Vec::new();
349
350 let mut total_size: usize = 0;
351
352 let client_header_from_block_id =
353 |block_id: BlockId<B>| -> Result<Option<B::Header>, HandleRequestError> {
354 if let Some(hash) = self.client.block_hash_from_id(&block_id)? {
355 return self.client.header(hash).map_err(Into::into);
356 }
357 Ok(None)
358 };
359
360 while let Some(header) = client_header_from_block_id(block_id).unwrap_or_default() {
361 let number = *header.number();
362 let hash = header.hash();
363 let parent_hash = *header.parent_hash();
364 let justifications =
365 if get_justification { self.client.justifications(hash)? } else { None };
366
367 let (justifications, justification, is_empty_justification) =
368 if support_multiple_justifications {
369 let justifications = match justifications {
370 Some(v) => v.encode(),
371 None => Vec::new(),
372 };
373 (justifications, Vec::new(), false)
374 } else {
375 let justification =
383 justifications.and_then(|just| just.into_justification(*b"FRNK"));
384
385 let is_empty_justification =
386 justification.as_ref().map(|j| j.is_empty()).unwrap_or(false);
387
388 let justification = justification.unwrap_or_default();
389
390 (Vec::new(), justification, is_empty_justification)
391 };
392
393 let body = if get_body {
394 match self.client.block_body(hash)? {
395 Some(mut extrinsics) => {
396 extrinsics.iter_mut().map(|extrinsic| extrinsic.encode()).collect()
397 },
398 None => {
399 log::trace!(target: LOG_TARGET, "Missing data for block request.");
400 break;
401 },
402 }
403 } else {
404 Vec::new()
405 };
406
407 let indexed_body = if get_indexed_body {
408 match self.client.block_indexed_body(hash)? {
409 Some(transactions) => transactions,
410 None => {
411 log::trace!(
412 target: LOG_TARGET,
413 "Missing indexed block data for block request."
414 );
415 Vec::new()
419 },
420 }
421 } else {
422 Vec::new()
423 };
424
425 let block_data = crate::sync::schema::v1::BlockData {
426 hash: hash.encode(),
427 header: if get_header { header.encode() } else { Vec::new() },
428 body,
429 receipt: Vec::new(),
430 message_queue: Vec::new(),
431 justification,
432 is_empty_justification,
433 justifications,
434 indexed_body,
435 };
436
437 let new_total_size = total_size + block_data.encoded_len();
438
439 if new_total_size > (MAX_RESPONSE_SIZE as usize - 20 * 1024) {
442 if blocks.is_empty() {
443 log::error!(
444 target: LOG_TARGET,
445 "Single block response is bigger than the max allowed response size! This is a bug!"
446 );
447 }
448
449 break;
450 }
451
452 total_size = new_total_size;
453
454 blocks.push(block_data);
455
456 if blocks.len() >= max_blocks as usize {
457 break;
458 }
459
460 match direction {
461 Direction::Ascending => block_id = BlockId::Number(number + One::one()),
462 Direction::Descending => {
463 if number.is_zero() {
464 break;
465 }
466 block_id = BlockId::Hash(parent_hash)
467 },
468 }
469 }
470
471 Ok(BlockResponse { blocks })
472 }
473}
474
475#[async_trait::async_trait]
476impl<B, Client> BlockServer<B> for BlockRequestHandler<B, Client>
477where
478 B: BlockT,
479 Client: HeaderBackend<B> + BlockBackend<B> + Send + Sync + 'static,
480{
481 async fn run(&mut self) {
482 self.process_requests().await;
483 }
484}
485
486#[derive(Debug, thiserror::Error)]
487enum HandleRequestError {
488 #[error("Failed to decode request: {0}.")]
489 DecodeProto(#[from] prost::DecodeError),
490 #[error("Failed to encode response: {0}.")]
491 EncodeProto(#[from] prost::EncodeError),
492 #[error("Failed to decode block hash: {0}.")]
493 DecodeScale(#[from] codec::Error),
494 #[error("Missing `BlockRequest::from_block` field.")]
495 MissingFromField,
496 #[error("Failed to parse BlockRequest::direction.")]
497 ParseDirection,
498 #[error(transparent)]
499 Client(#[from] soil_client::blockchain::Error),
500 #[error("Failed to send response.")]
501 SendResponse,
502}
503
504#[derive(Debug)]
506pub struct FullBlockDownloader {
507 protocol_name: ProtocolName,
508 network: NetworkServiceHandle,
509}
510
511impl FullBlockDownloader {
512 fn new(protocol_name: ProtocolName, network: NetworkServiceHandle) -> Self {
513 Self { protocol_name, network }
514 }
515
516 fn blocks_from_schema<B: BlockT>(
518 &self,
519 request: &BlockRequest<B>,
520 response: BlockResponseSchema,
521 ) -> Result<Vec<BlockData<B>>, String> {
522 response
523 .blocks
524 .into_iter()
525 .map(|block_data| {
526 Ok(BlockData::<B> {
527 hash: Decode::decode(&mut block_data.hash.as_ref())?,
528 header: if !block_data.header.is_empty() {
529 Some(Decode::decode(&mut block_data.header.as_ref())?)
530 } else {
531 None
532 },
533 body: if request.fields.contains(BlockAttributes::BODY) {
534 Some(
535 block_data
536 .body
537 .iter()
538 .map(|body| Decode::decode(&mut body.as_ref()))
539 .collect::<Result<Vec<_>, _>>()?,
540 )
541 } else {
542 None
543 },
544 indexed_body: if request.fields.contains(BlockAttributes::INDEXED_BODY) {
545 Some(block_data.indexed_body)
546 } else {
547 None
548 },
549 receipt: if !block_data.receipt.is_empty() {
550 Some(block_data.receipt)
551 } else {
552 None
553 },
554 message_queue: if !block_data.message_queue.is_empty() {
555 Some(block_data.message_queue)
556 } else {
557 None
558 },
559 justification: if !block_data.justification.is_empty() {
560 Some(block_data.justification)
561 } else if block_data.is_empty_justification {
562 Some(Vec::new())
563 } else {
564 None
565 },
566 justifications: if !block_data.justifications.is_empty() {
567 Some(DecodeAll::decode_all(&mut block_data.justifications.as_ref())?)
568 } else {
569 None
570 },
571 })
572 })
573 .collect::<Result<_, _>>()
574 .map_err(|error: codec::Error| error.to_string())
575 }
576}
577
578#[async_trait::async_trait]
579impl<B: BlockT> BlockDownloader<B> for FullBlockDownloader {
580 fn protocol_name(&self) -> &ProtocolName {
581 &self.protocol_name
582 }
583
584 async fn download_blocks(
585 &self,
586 who: PeerId,
587 request: BlockRequest<B>,
588 ) -> Result<Result<(Vec<u8>, ProtocolName), RequestFailure>, oneshot::Canceled> {
589 let bytes = BlockRequestSchema {
591 fields: request.fields.to_be_u32(),
592 from_block: match request.from {
593 FromBlock::Hash(h) => Some(FromBlockSchema::Hash(h.encode())),
594 FromBlock::Number(n) => Some(FromBlockSchema::Number(n.encode())),
595 },
596 direction: request.direction as i32,
597 max_blocks: request.max.unwrap_or(0),
598 support_multiple_justifications: true,
599 }
600 .encode_to_vec();
601
602 let (tx, rx) = oneshot::channel();
603 self.network.start_request(
604 who,
605 self.protocol_name.clone(),
606 bytes,
607 tx,
608 IfDisconnected::ImmediateError,
609 );
610 rx.await
611 }
612
613 fn block_response_into_blocks(
614 &self,
615 request: &BlockRequest<B>,
616 response: Vec<u8>,
617 ) -> Result<Vec<BlockData<B>>, BlockResponseError> {
618 let response_schema = BlockResponseSchema::decode(response.as_slice())
620 .map_err(|error| BlockResponseError::DecodeFailed(error.to_string()))?;
621
622 self.blocks_from_schema::<B>(request, response_schema)
624 .map_err(|error| BlockResponseError::ExtractionFailed(error.to_string()))
625 }
626}