1use futures::{
19 prelude::*,
20 task::{Context, Poll},
21};
22use log::{debug, trace};
23use prometheus_endpoint::Registry;
24use sc_utils::mpsc::{tracing_unbounded, TracingUnboundedReceiver, TracingUnboundedSender};
25use sp_consensus::BlockOrigin;
26use sp_runtime::{
27 traits::{Block as BlockT, Header as HeaderT, NumberFor},
28 Justification, Justifications,
29};
30use std::pin::Pin;
31
32use crate::{
33 import_queue::{
34 buffered_link::{self, BufferedLinkReceiver, BufferedLinkSender},
35 import_single_block_metered, verify_single_block_metered, BlockImportError,
36 BlockImportStatus, BoxBlockImport, BoxJustificationImport, ImportQueue, ImportQueueService,
37 IncomingBlock, Link, RuntimeOrigin, SingleBlockVerificationOutcome, Verifier, LOG_TARGET,
38 },
39 metrics::Metrics,
40};
41
42pub struct BasicQueue<B: BlockT> {
45 handle: BasicQueueHandle<B>,
47 result_port: BufferedLinkReceiver<B>,
49}
50
51impl<B: BlockT> Drop for BasicQueue<B> {
52 fn drop(&mut self) {
53 self.handle.close();
55 self.result_port.close();
56 }
57}
58
59impl<B: BlockT> BasicQueue<B> {
60 pub fn new<V>(
64 verifier: V,
65 block_import: BoxBlockImport<B>,
66 justification_import: Option<BoxJustificationImport<B>>,
67 spawner: &impl sp_core::traits::SpawnEssentialNamed,
68 prometheus_registry: Option<&Registry>,
69 ) -> Self
70 where
71 V: Verifier<B> + 'static,
72 {
73 let (result_sender, result_port) = buffered_link::buffered_link(100_000);
74
75 let metrics = prometheus_registry.and_then(|r| {
76 Metrics::register(r)
77 .map_err(|err| {
78 log::warn!("Failed to register Prometheus metrics: {}", err);
79 })
80 .ok()
81 });
82
83 let (future, justification_sender, block_import_sender) = BlockImportWorker::new(
84 result_sender,
85 verifier,
86 block_import,
87 justification_import,
88 metrics,
89 );
90
91 spawner.spawn_essential_blocking(
92 "basic-block-import-worker",
93 Some("block-import"),
94 future.boxed(),
95 );
96
97 Self {
98 handle: BasicQueueHandle::new(justification_sender, block_import_sender),
99 result_port,
100 }
101 }
102}
103
104#[derive(Clone)]
105struct BasicQueueHandle<B: BlockT> {
106 justification_sender: TracingUnboundedSender<worker_messages::ImportJustification<B>>,
108 block_import_sender: TracingUnboundedSender<worker_messages::ImportBlocks<B>>,
110}
111
112impl<B: BlockT> BasicQueueHandle<B> {
113 pub fn new(
114 justification_sender: TracingUnboundedSender<worker_messages::ImportJustification<B>>,
115 block_import_sender: TracingUnboundedSender<worker_messages::ImportBlocks<B>>,
116 ) -> Self {
117 Self { justification_sender, block_import_sender }
118 }
119
120 pub fn close(&mut self) {
121 self.justification_sender.close();
122 self.block_import_sender.close();
123 }
124}
125
126impl<B: BlockT> ImportQueueService<B> for BasicQueueHandle<B> {
127 fn import_blocks(&mut self, origin: BlockOrigin, blocks: Vec<IncomingBlock<B>>) {
128 if blocks.is_empty() {
129 return
130 }
131
132 trace!(target: LOG_TARGET, "Scheduling {} blocks for import", blocks.len());
133 let res = self
134 .block_import_sender
135 .unbounded_send(worker_messages::ImportBlocks(origin, blocks));
136
137 if res.is_err() {
138 log::error!(
139 target: LOG_TARGET,
140 "import_blocks: Background import task is no longer alive"
141 );
142 }
143 }
144
145 fn import_justifications(
146 &mut self,
147 who: RuntimeOrigin,
148 hash: B::Hash,
149 number: NumberFor<B>,
150 justifications: Justifications,
151 ) {
152 for justification in justifications {
153 let res = self.justification_sender.unbounded_send(
154 worker_messages::ImportJustification(who, hash, number, justification),
155 );
156
157 if res.is_err() {
158 log::error!(
159 target: LOG_TARGET,
160 "import_justification: Background import task is no longer alive"
161 );
162 }
163 }
164 }
165}
166
167#[async_trait::async_trait]
168impl<B: BlockT> ImportQueue<B> for BasicQueue<B> {
169 fn service(&self) -> Box<dyn ImportQueueService<B>> {
171 Box::new(self.handle.clone())
172 }
173
174 fn service_ref(&mut self) -> &mut dyn ImportQueueService<B> {
176 &mut self.handle
177 }
178
179 fn poll_actions(&mut self, cx: &mut Context, link: &dyn Link<B>) {
181 if self.result_port.poll_actions(cx, link).is_err() {
182 log::error!(
183 target: LOG_TARGET,
184 "poll_actions: Background import task is no longer alive"
185 );
186 }
187 }
188
189 async fn run(mut self, link: &dyn Link<B>) {
194 loop {
195 if let Err(_) = self.result_port.next_action(link).await {
196 log::error!(target: "sync", "poll_actions: Background import task is no longer alive");
197 return
198 }
199 }
200 }
201}
202
203mod worker_messages {
205 use super::*;
206
207 pub struct ImportBlocks<B: BlockT>(pub BlockOrigin, pub Vec<IncomingBlock<B>>);
208 pub struct ImportJustification<B: BlockT>(
209 pub RuntimeOrigin,
210 pub B::Hash,
211 pub NumberFor<B>,
212 pub Justification,
213 );
214}
215
216async fn block_import_process<B: BlockT>(
224 mut block_import: BoxBlockImport<B>,
225 verifier: impl Verifier<B>,
226 result_sender: BufferedLinkSender<B>,
227 mut block_import_receiver: TracingUnboundedReceiver<worker_messages::ImportBlocks<B>>,
228 metrics: Option<Metrics>,
229) {
230 loop {
231 let worker_messages::ImportBlocks(origin, blocks) = match block_import_receiver.next().await
232 {
233 Some(blocks) => blocks,
234 None => {
235 log::debug!(
236 target: LOG_TARGET,
237 "Stopping block import because the import channel was closed!",
238 );
239 return
240 },
241 };
242
243 let res =
244 import_many_blocks(&mut block_import, origin, blocks, &verifier, metrics.clone()).await;
245
246 result_sender.blocks_processed(res.imported, res.block_count, res.results);
247 }
248}
249
250struct BlockImportWorker<B: BlockT> {
251 result_sender: BufferedLinkSender<B>,
252 justification_import: Option<BoxJustificationImport<B>>,
253 metrics: Option<Metrics>,
254}
255
256impl<B: BlockT> BlockImportWorker<B> {
257 fn new<V>(
258 result_sender: BufferedLinkSender<B>,
259 verifier: V,
260 block_import: BoxBlockImport<B>,
261 justification_import: Option<BoxJustificationImport<B>>,
262 metrics: Option<Metrics>,
263 ) -> (
264 impl Future<Output = ()> + Send,
265 TracingUnboundedSender<worker_messages::ImportJustification<B>>,
266 TracingUnboundedSender<worker_messages::ImportBlocks<B>>,
267 )
268 where
269 V: Verifier<B> + 'static,
270 {
271 use worker_messages::*;
272
273 let (justification_sender, mut justification_port) =
274 tracing_unbounded("mpsc_import_queue_worker_justification", 100_000);
275
276 let (block_import_sender, block_import_receiver) =
277 tracing_unbounded("mpsc_import_queue_worker_blocks", 100_000);
278
279 let mut worker = BlockImportWorker { result_sender, justification_import, metrics };
280
281 let future = async move {
282 if let Some(justification_import) = worker.justification_import.as_mut() {
284 for (hash, number) in justification_import.on_start().await {
285 worker.result_sender.request_justification(&hash, number);
286 }
287 }
288
289 let block_import_process = block_import_process(
290 block_import,
291 verifier,
292 worker.result_sender.clone(),
293 block_import_receiver,
294 worker.metrics.clone(),
295 );
296 futures::pin_mut!(block_import_process);
297
298 loop {
299 if worker.result_sender.is_closed() {
302 log::debug!(
303 target: LOG_TARGET,
304 "Stopping block import because result channel was closed!",
305 );
306 return
307 }
308
309 while let Poll::Ready(justification) = futures::poll!(justification_port.next()) {
311 match justification {
312 Some(ImportJustification(who, hash, number, justification)) =>
313 worker.import_justification(who, hash, number, justification).await,
314 None => {
315 log::debug!(
316 target: LOG_TARGET,
317 "Stopping block import because justification channel was closed!",
318 );
319 return
320 },
321 }
322 }
323
324 if let Poll::Ready(()) = futures::poll!(&mut block_import_process) {
325 return
326 }
327
328 futures::pending!()
330 }
331 };
332
333 (future, justification_sender, block_import_sender)
334 }
335
336 async fn import_justification(
337 &mut self,
338 who: RuntimeOrigin,
339 hash: B::Hash,
340 number: NumberFor<B>,
341 justification: Justification,
342 ) {
343 let started = std::time::Instant::now();
344
345 let success = match self.justification_import.as_mut() {
346 Some(justification_import) => justification_import
347 .import_justification(hash, number, justification)
348 .await
349 .map_err(|e| {
350 debug!(
351 target: LOG_TARGET,
352 "Justification import failed for hash = {:?} with number = {:?} coming from node = {:?} with error: {}",
353 hash,
354 number,
355 who,
356 e,
357 );
358 e
359 })
360 .is_ok(),
361 None => false,
362 };
363
364 if let Some(metrics) = self.metrics.as_ref() {
365 metrics.justification_import_time.observe(started.elapsed().as_secs_f64());
366 }
367
368 self.result_sender.justification_imported(who, &hash, number, success);
369 }
370}
371
372struct ImportManyBlocksResult<B: BlockT> {
374 imported: usize,
376 block_count: usize,
378 results: Vec<(Result<BlockImportStatus<NumberFor<B>>, BlockImportError>, B::Hash)>,
380}
381
382async fn import_many_blocks<B: BlockT, V: Verifier<B>>(
387 import_handle: &mut BoxBlockImport<B>,
388 blocks_origin: BlockOrigin,
389 blocks: Vec<IncomingBlock<B>>,
390 verifier: &V,
391 metrics: Option<Metrics>,
392) -> ImportManyBlocksResult<B> {
393 let count = blocks.len();
394
395 let blocks_range = match (
396 blocks.first().and_then(|b| b.header.as_ref().map(|h| h.number())),
397 blocks.last().and_then(|b| b.header.as_ref().map(|h| h.number())),
398 ) {
399 (Some(first), Some(last)) if first != last => format!(" ({}..{})", first, last),
400 (Some(first), Some(_)) => format!(" ({})", first),
401 _ => Default::default(),
402 };
403
404 trace!(target: LOG_TARGET, "Starting import of {} blocks {}", count, blocks_range);
405
406 let mut imported = 0;
407 let mut results = vec![];
408 let mut has_error = false;
409 let mut blocks = blocks.into_iter();
410
411 loop {
413 let block = match blocks.next() {
415 Some(b) => b,
416 None => {
417 return ImportManyBlocksResult { block_count: count, imported, results }
419 },
420 };
421
422 let block_number = block.header.as_ref().map(|h| *h.number());
423 let block_hash = block.hash;
424 let import_result = if has_error {
425 Err(BlockImportError::Cancelled)
426 } else {
427 let verification_fut = verify_single_block_metered(
428 import_handle,
429 blocks_origin,
430 block,
431 verifier,
432 metrics.as_ref(),
433 );
434 match verification_fut.await {
435 Ok(SingleBlockVerificationOutcome::Imported(import_status)) => Ok(import_status),
436 Ok(SingleBlockVerificationOutcome::Verified(import_parameters)) => {
437 import_single_block_metered(import_handle, import_parameters, metrics.as_ref())
439 .await
440 },
441 Err(e) => Err(e),
442 }
443 };
444
445 if let Some(metrics) = metrics.as_ref() {
446 metrics.report_import::<B>(&import_result);
447 }
448
449 if import_result.is_ok() {
450 trace!(
451 target: LOG_TARGET,
452 "Block imported successfully {:?} ({})",
453 block_number,
454 block_hash,
455 );
456 imported += 1;
457 } else {
458 has_error = true;
459 }
460
461 results.push((import_result, block_hash));
462
463 Yield::new().await
464 }
465}
466
467struct Yield(bool);
473
474impl Yield {
475 fn new() -> Self {
476 Self(false)
477 }
478}
479
480impl Future for Yield {
481 type Output = ();
482
483 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
484 if !self.0 {
485 self.0 = true;
486 cx.waker().wake_by_ref();
487 Poll::Pending
488 } else {
489 Poll::Ready(())
490 }
491 }
492}
493
494#[cfg(test)]
495mod tests {
496 use super::*;
497 use crate::{
498 block_import::{
499 BlockCheckParams, BlockImport, BlockImportParams, ImportResult, JustificationImport,
500 },
501 import_queue::Verifier,
502 };
503 use futures::{executor::block_on, Future};
504 use parking_lot::Mutex;
505 use sp_test_primitives::{Block, BlockNumber, Hash, Header};
506
507 #[async_trait::async_trait]
508 impl Verifier<Block> for () {
509 async fn verify(
510 &self,
511 block: BlockImportParams<Block>,
512 ) -> Result<BlockImportParams<Block>, String> {
513 Ok(BlockImportParams::new(block.origin, block.header))
514 }
515 }
516
517 #[async_trait::async_trait]
518 impl BlockImport<Block> for () {
519 type Error = sp_consensus::Error;
520
521 async fn check_block(
522 &self,
523 _block: BlockCheckParams<Block>,
524 ) -> Result<ImportResult, Self::Error> {
525 Ok(ImportResult::imported(false))
526 }
527
528 async fn import_block(
529 &self,
530 _block: BlockImportParams<Block>,
531 ) -> Result<ImportResult, Self::Error> {
532 Ok(ImportResult::imported(true))
533 }
534 }
535
536 #[async_trait::async_trait]
537 impl JustificationImport<Block> for () {
538 type Error = sp_consensus::Error;
539
540 async fn on_start(&mut self) -> Vec<(Hash, BlockNumber)> {
541 Vec::new()
542 }
543
544 async fn import_justification(
545 &mut self,
546 _hash: Hash,
547 _number: BlockNumber,
548 _justification: Justification,
549 ) -> Result<(), Self::Error> {
550 Ok(())
551 }
552 }
553
554 #[derive(Debug, PartialEq)]
555 enum Event {
556 JustificationImported(Hash),
557 BlockImported(Hash),
558 }
559
560 #[derive(Default)]
561 struct TestLink {
562 events: Mutex<Vec<Event>>,
563 }
564
565 impl Link<Block> for TestLink {
566 fn blocks_processed(
567 &self,
568 _imported: usize,
569 _count: usize,
570 results: Vec<(Result<BlockImportStatus<BlockNumber>, BlockImportError>, Hash)>,
571 ) {
572 if let Some(hash) = results.into_iter().find_map(|(r, h)| r.ok().map(|_| h)) {
573 self.events.lock().push(Event::BlockImported(hash));
574 }
575 }
576
577 fn justification_imported(
578 &self,
579 _who: RuntimeOrigin,
580 hash: &Hash,
581 _number: BlockNumber,
582 _success: bool,
583 ) {
584 self.events.lock().push(Event::JustificationImported(*hash))
585 }
586 }
587
588 #[test]
589 fn prioritizes_finality_work_over_block_import() {
590 let (result_sender, mut result_port) = buffered_link::buffered_link(100_000);
591
592 let (worker, finality_sender, block_import_sender) =
593 BlockImportWorker::new(result_sender, (), Box::new(()), Some(Box::new(())), None);
594 futures::pin_mut!(worker);
595
596 let import_block = |n| {
597 let header = Header {
598 parent_hash: Hash::random(),
599 number: n,
600 extrinsics_root: Hash::random(),
601 state_root: Default::default(),
602 digest: Default::default(),
603 };
604
605 let hash = header.hash();
606
607 block_import_sender
608 .unbounded_send(worker_messages::ImportBlocks(
609 BlockOrigin::Own,
610 vec![IncomingBlock {
611 hash,
612 header: Some(header),
613 body: None,
614 indexed_body: None,
615 justifications: None,
616 origin: None,
617 allow_missing_state: false,
618 import_existing: false,
619 state: None,
620 skip_execution: false,
621 }],
622 ))
623 .unwrap();
624
625 hash
626 };
627
628 let import_justification = || {
629 let hash = Hash::random();
630 finality_sender
631 .unbounded_send(worker_messages::ImportJustification(
632 sc_network_types::PeerId::random(),
633 hash,
634 1,
635 (*b"TEST", Vec::new()),
636 ))
637 .unwrap();
638
639 hash
640 };
641
642 let link = TestLink::default();
643
644 let block1 = import_block(1);
646 let block2 = import_block(2);
647 let block3 = import_block(3);
648 let justification1 = import_justification();
649 let justification2 = import_justification();
650 let block4 = import_block(4);
651 let block5 = import_block(5);
652 let block6 = import_block(6);
653 let justification3 = import_justification();
654
655 block_on(futures::future::poll_fn(|cx| {
657 while link.events.lock().len() < 9 {
658 match Future::poll(Pin::new(&mut worker), cx) {
659 Poll::Pending => {},
660 Poll::Ready(()) => panic!("import queue worker should not conclude."),
661 }
662
663 result_port.poll_actions(cx, &link).unwrap();
664 }
665
666 Poll::Ready(())
667 }));
668
669 assert_eq!(
671 &*link.events.lock(),
672 &[
673 Event::JustificationImported(justification1),
674 Event::JustificationImported(justification2),
675 Event::JustificationImported(justification3),
676 Event::BlockImported(block1),
677 Event::BlockImported(block2),
678 Event::BlockImported(block3),
679 Event::BlockImported(block4),
680 Event::BlockImported(block5),
681 Event::BlockImported(block6),
682 ]
683 );
684 }
685}