referrerpolicy=no-referrer-when-downgrade

sc_service/chain_ops/
import_blocks.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
5
6// This program is free software: you can redistribute it and/or modify
7// it under the terms of the GNU General Public License as published by
8// the Free Software Foundation, either version 3 of the License, or
9// (at your option) any later version.
10
11// This program is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14// GNU General Public License for more details.
15
16// You should have received a copy of the GNU General Public License
17// along with this program. If not, see <https://www.gnu.org/licenses/>.
18
19use crate::{error, error::Error};
20use codec::{Decode, IoReader as CodecIoReader};
21use futures::{future, prelude::*};
22use futures_timer::Delay;
23use log::{info, warn};
24use sc_chain_spec::ChainSpec;
25use sc_client_api::HeaderBackend;
26use sc_consensus::import_queue::{
27	BlockImportError, BlockImportStatus, ImportQueue, IncomingBlock, Link,
28};
29use serde_json::{de::IoRead as JsonIoRead, Deserializer, StreamDeserializer};
30use sp_consensus::BlockOrigin;
31use sp_runtime::{
32	generic::SignedBlock,
33	traits::{
34		Block as BlockT, CheckedDiv, Header, MaybeSerializeDeserialize, NumberFor, Saturating, Zero,
35	},
36};
37use std::{
38	io::Read,
39	pin::Pin,
40	sync::{
41		atomic::{AtomicBool, AtomicU64, Ordering},
42		Arc,
43	},
44	task::Poll,
45	time::{Duration, Instant},
46};
47
48/// Number of blocks we will add to the queue before waiting for the queue to catch up.
49const MAX_PENDING_BLOCKS: u64 = 10_000;
50
51/// Number of milliseconds to wait until next poll.
52const DELAY_TIME: u64 = 200;
53
54/// Number of milliseconds that must have passed between two updates.
55const TIME_BETWEEN_UPDATES: u64 = 3_000;
56
57/// Build a chain spec json
58pub fn build_spec(spec: &dyn ChainSpec, raw: bool) -> error::Result<String> {
59	spec.as_json(raw).map_err(Into::into)
60}
61
62/// Helper enum that wraps either a binary decoder (from parity-scale-codec), or a JSON decoder
63/// (from serde_json). Implements the Iterator Trait, calling `next()` will decode the next
64/// SignedBlock and return it.
65enum BlockIter<R, B>
66where
67	R: std::io::Read,
68{
69	Binary {
70		// Total number of blocks we are expecting to decode.
71		num_expected_blocks: u64,
72		// Number of blocks we have decoded thus far.
73		read_block_count: u64,
74		// Reader to the data, used for decoding new blocks.
75		reader: CodecIoReader<R>,
76	},
77	Json {
78		// Number of blocks we have decoded thus far.
79		read_block_count: u64,
80		// Stream to the data, used for decoding new blocks.
81		reader: StreamDeserializer<'static, JsonIoRead<R>, SignedBlock<B>>,
82	},
83}
84
85impl<R, B> BlockIter<R, B>
86where
87	R: Read + 'static,
88	B: BlockT + MaybeSerializeDeserialize,
89{
90	fn new(input: R, binary: bool) -> Result<Self, String> {
91		if binary {
92			let mut reader = CodecIoReader(input);
93			// If the file is encoded in binary format, it is expected to first specify the number
94			// of blocks that are going to be decoded. We read it and add it to our enum struct.
95			let num_expected_blocks: u64 = Decode::decode(&mut reader)
96				.map_err(|e| format!("Failed to decode the number of blocks: {:?}", e))?;
97			Ok(BlockIter::Binary { num_expected_blocks, read_block_count: 0, reader })
98		} else {
99			let stream_deser = Deserializer::from_reader(input).into_iter::<SignedBlock<B>>();
100			Ok(BlockIter::Json { reader: stream_deser, read_block_count: 0 })
101		}
102	}
103
104	/// Returns the number of blocks read thus far.
105	fn read_block_count(&self) -> u64 {
106		match self {
107			BlockIter::Binary { read_block_count, .. } |
108			BlockIter::Json { read_block_count, .. } => *read_block_count,
109		}
110	}
111
112	/// Returns the total number of blocks to be imported, if possible.
113	fn num_expected_blocks(&self) -> Option<u64> {
114		match self {
115			BlockIter::Binary { num_expected_blocks, .. } => Some(*num_expected_blocks),
116			BlockIter::Json { .. } => None,
117		}
118	}
119}
120
121impl<R, B> Iterator for BlockIter<R, B>
122where
123	R: Read + 'static,
124	B: BlockT + MaybeSerializeDeserialize,
125{
126	type Item = Result<SignedBlock<B>, String>;
127
128	fn next(&mut self) -> Option<Self::Item> {
129		match self {
130			BlockIter::Binary { num_expected_blocks, read_block_count, reader } => {
131				if read_block_count < num_expected_blocks {
132					let block_result: Result<SignedBlock<B>, _> =
133						SignedBlock::<B>::decode(reader).map_err(|e| e.to_string());
134					*read_block_count += 1;
135					Some(block_result)
136				} else {
137					// `read_block_count` == `num_expected_blocks` so we've read enough blocks.
138					None
139				}
140			},
141			BlockIter::Json { reader, read_block_count } => {
142				let res = Some(reader.next()?.map_err(|e| e.to_string()));
143				*read_block_count += 1;
144				res
145			},
146		}
147	}
148}
149
150/// Imports the SignedBlock to the queue.
151fn import_block_to_queue<TBl, TImpQu>(
152	signed_block: SignedBlock<TBl>,
153	queue: &mut TImpQu,
154	force: bool,
155) where
156	TBl: BlockT + MaybeSerializeDeserialize,
157	TImpQu: 'static + ImportQueue<TBl>,
158{
159	let (header, extrinsics) = signed_block.block.deconstruct();
160	let hash = header.hash();
161	// import queue handles verification and importing it into the client.
162	queue.service_ref().import_blocks(
163		BlockOrigin::File,
164		vec![IncomingBlock::<TBl> {
165			hash,
166			header: Some(header),
167			body: Some(extrinsics),
168			justifications: signed_block.justifications,
169			origin: None,
170			allow_missing_state: false,
171			import_existing: force,
172			state: None,
173			skip_execution: false,
174		}],
175	);
176}
177
178/// Returns true if we have imported every block we were supposed to import, else returns false.
179fn importing_is_done(
180	num_expected_blocks: Option<u64>,
181	read_block_count: u64,
182	imported_blocks: u64,
183) -> bool {
184	if let Some(num_expected_blocks) = num_expected_blocks {
185		imported_blocks >= num_expected_blocks
186	} else {
187		imported_blocks >= read_block_count
188	}
189}
190
191/// Structure used to log the block importing speed.
192struct Speedometer<B: BlockT> {
193	best_number: NumberFor<B>,
194	last_number: Option<NumberFor<B>>,
195	last_update: Instant,
196}
197
198impl<B: BlockT> Speedometer<B> {
199	/// Creates a fresh Speedometer.
200	fn new() -> Self {
201		Self {
202			best_number: NumberFor::<B>::from(0u32),
203			last_number: None,
204			last_update: Instant::now(),
205		}
206	}
207
208	/// Calculates `(best_number - last_number) / (now - last_update)` and
209	/// logs the speed of import.
210	fn display_speed(&self) {
211		// Number of milliseconds elapsed since last time.
212		let elapsed_ms = {
213			let elapsed = self.last_update.elapsed();
214			let since_last_millis = elapsed.as_secs() * 1000;
215			let since_last_subsec_millis = elapsed.subsec_millis() as u64;
216			since_last_millis + since_last_subsec_millis
217		};
218
219		// Number of blocks that have been imported since last time.
220		let diff = match self.last_number {
221			None => return,
222			Some(n) => self.best_number.saturating_sub(n),
223		};
224
225		if let Ok(diff) = TryInto::<u128>::try_into(diff) {
226			// If the number of blocks can be converted to a regular integer, then it's easy: just
227			// do the math and turn it into a `f64`.
228			let speed = diff
229				.saturating_mul(10_000)
230				.checked_div(u128::from(elapsed_ms))
231				.map_or(0.0, |s| s as f64) /
232				10.0;
233			info!("๐Ÿ“ฆ Current best block: {} ({:4.1} bps)", self.best_number, speed);
234		} else {
235			// If the number of blocks can't be converted to a regular integer, then we need a more
236			// algebraic approach and we stay within the realm of integers.
237			let one_thousand = NumberFor::<B>::from(1_000u32);
238			let elapsed =
239				NumberFor::<B>::from(<u32 as TryFrom<_>>::try_from(elapsed_ms).unwrap_or(u32::MAX));
240
241			let speed = diff
242				.saturating_mul(one_thousand)
243				.checked_div(&elapsed)
244				.unwrap_or_else(Zero::zero);
245			info!("๐Ÿ“ฆ Current best block: {} ({} bps)", self.best_number, speed)
246		}
247	}
248
249	/// Updates the Speedometer.
250	fn update(&mut self, best_number: NumberFor<B>) {
251		self.last_number = Some(self.best_number);
252		self.best_number = best_number;
253		self.last_update = Instant::now();
254	}
255
256	// If more than TIME_BETWEEN_UPDATES has elapsed since last update,
257	// then print and update the speedometer.
258	fn notify_user(&mut self, best_number: NumberFor<B>) {
259		let delta = Duration::from_millis(TIME_BETWEEN_UPDATES);
260		if Instant::now().duration_since(self.last_update) >= delta {
261			self.display_speed();
262			self.update(best_number);
263		}
264	}
265}
266
267/// Different State that the `import_blocks` future could be in.
268enum ImportState<R, B>
269where
270	R: Read + 'static,
271	B: BlockT + MaybeSerializeDeserialize,
272{
273	/// We are reading from the [`BlockIter`] structure, adding those blocks to the queue if
274	/// possible.
275	Reading { block_iter: BlockIter<R, B> },
276	/// The queue is full (contains at least MAX_PENDING_BLOCKS blocks) and we are waiting for it
277	/// to catch up.
278	WaitingForImportQueueToCatchUp {
279		block_iter: BlockIter<R, B>,
280		delay: Delay,
281		block: SignedBlock<B>,
282	},
283	// We have added all the blocks to the queue but they are still being processed.
284	WaitingForImportQueueToFinish {
285		num_expected_blocks: Option<u64>,
286		read_block_count: u64,
287		delay: Delay,
288	},
289}
290
291/// Starts the process of importing blocks.
292pub fn import_blocks<B, IQ, C>(
293	client: Arc<C>,
294	mut import_queue: IQ,
295	input: impl Read + Send + 'static,
296	force: bool,
297	binary: bool,
298) -> Pin<Box<dyn Future<Output = Result<(), Error>> + Send>>
299where
300	C: HeaderBackend<B> + Send + Sync + 'static,
301	B: BlockT + for<'de> serde::Deserialize<'de>,
302	IQ: ImportQueue<B> + 'static,
303{
304	struct WaitLink {
305		imported_blocks: AtomicU64,
306		has_error: AtomicBool,
307	}
308
309	impl WaitLink {
310		fn new() -> WaitLink {
311			WaitLink { imported_blocks: AtomicU64::new(0), has_error: AtomicBool::new(false) }
312		}
313	}
314
315	impl<B: BlockT> Link<B> for WaitLink {
316		fn blocks_processed(
317			&self,
318			imported: usize,
319			_num_expected_blocks: usize,
320			results: Vec<(Result<BlockImportStatus<NumberFor<B>>, BlockImportError>, B::Hash)>,
321		) {
322			self.imported_blocks.fetch_add(imported as u64, Ordering::AcqRel);
323
324			for result in results {
325				if let (Err(err), hash) = result {
326					warn!("There was an error importing block with hash {:?}: {}", hash, err);
327					self.has_error.store(true, Ordering::Release);
328					break;
329				}
330			}
331		}
332	}
333
334	let mut link = WaitLink::new();
335	let block_iter_res: Result<BlockIter<_, B>, String> = BlockIter::new(input, binary);
336
337	let block_iter = match block_iter_res {
338		Ok(block_iter) => block_iter,
339		Err(e) => {
340			// We've encountered an error while creating the block iterator
341			// so we can just return a future that returns an error.
342			return future::ready(Err(Error::Other(e))).boxed();
343		},
344	};
345
346	let mut state = Some(ImportState::Reading { block_iter });
347	let mut speedometer = Speedometer::<B>::new();
348
349	// Importing blocks is implemented as a future, because we want the operation to be
350	// interruptible.
351	//
352	// Every time we read a block from the input or import a bunch of blocks from the import
353	// queue, the `Future` re-schedules itself and returns `Poll::Pending`.
354	// This makes it possible either to interleave other operations in-between the block imports,
355	// or to stop the operation completely.
356	let import = future::poll_fn(move |cx| {
357		let client = &client;
358		let queue = &mut import_queue;
359		match state.take().expect("state should never be None; qed") {
360			ImportState::Reading { mut block_iter } => {
361				match block_iter.next() {
362					None => {
363						// The iterator is over: we now need to wait for the import queue to finish.
364						let num_expected_blocks = block_iter.num_expected_blocks();
365						let read_block_count = block_iter.read_block_count();
366						let delay = Delay::new(Duration::from_millis(DELAY_TIME));
367						state = Some(ImportState::WaitingForImportQueueToFinish {
368							num_expected_blocks,
369							read_block_count,
370							delay,
371						});
372					},
373					Some(block_result) => {
374						let read_block_count = block_iter.read_block_count();
375						match block_result {
376							Ok(block) => {
377								if read_block_count - link.imported_blocks.load(Ordering::Acquire) >=
378									MAX_PENDING_BLOCKS
379								{
380									// The queue is full, so do not add this block and simply wait
381									// until the queue has made some progress.
382									let delay = Delay::new(Duration::from_millis(DELAY_TIME));
383									state = Some(ImportState::WaitingForImportQueueToCatchUp {
384										block_iter,
385										delay,
386										block,
387									});
388								} else {
389									// Queue is not full, we can keep on adding blocks to the queue.
390									import_block_to_queue(block, queue, force);
391									state = Some(ImportState::Reading { block_iter });
392								}
393							},
394							Err(e) => {
395								return Poll::Ready(Err(Error::Other(format!(
396									"Error reading block #{}: {}",
397									read_block_count, e
398								))))
399							},
400						}
401					},
402				}
403			},
404			ImportState::WaitingForImportQueueToCatchUp { block_iter, mut delay, block } => {
405				let read_block_count = block_iter.read_block_count();
406				if read_block_count - link.imported_blocks.load(Ordering::Acquire) >=
407					MAX_PENDING_BLOCKS
408				{
409					// Queue is still full, so wait until there is room to insert our block.
410					match Pin::new(&mut delay).poll(cx) {
411						Poll::Pending => {
412							state = Some(ImportState::WaitingForImportQueueToCatchUp {
413								block_iter,
414								delay,
415								block,
416							});
417							return Poll::Pending;
418						},
419						Poll::Ready(_) => {
420							delay.reset(Duration::from_millis(DELAY_TIME));
421						},
422					}
423					state = Some(ImportState::WaitingForImportQueueToCatchUp {
424						block_iter,
425						delay,
426						block,
427					});
428				} else {
429					// Queue is no longer full, so we can add our block to the queue.
430					import_block_to_queue(block, queue, force);
431					// Switch back to Reading state.
432					state = Some(ImportState::Reading { block_iter });
433				}
434			},
435			ImportState::WaitingForImportQueueToFinish {
436				num_expected_blocks,
437				read_block_count,
438				mut delay,
439			} => {
440				// All the blocks have been added to the queue, which doesn't mean they
441				// have all been properly imported.
442				if importing_is_done(
443					num_expected_blocks,
444					read_block_count,
445					link.imported_blocks.load(Ordering::Acquire),
446				) {
447					// Importing is done, we can log the result and return.
448					info!(
449						"๐ŸŽ‰ Imported {} blocks. Best: #{}",
450						read_block_count,
451						client.info().best_number
452					);
453					return Poll::Ready(Ok(()));
454				} else {
455					// Importing is not done, we still have to wait for the queue to finish.
456					// Wait for the delay, because we know the queue is lagging behind.
457					match Pin::new(&mut delay).poll(cx) {
458						Poll::Pending => {
459							state = Some(ImportState::WaitingForImportQueueToFinish {
460								num_expected_blocks,
461								read_block_count,
462								delay,
463							});
464							return Poll::Pending;
465						},
466						Poll::Ready(_) => {
467							delay.reset(Duration::from_millis(DELAY_TIME));
468						},
469					}
470
471					state = Some(ImportState::WaitingForImportQueueToFinish {
472						num_expected_blocks,
473						read_block_count,
474						delay,
475					});
476				}
477			},
478		}
479
480		queue.poll_actions(cx, &mut link);
481
482		let best_number = client.info().best_number;
483		speedometer.notify_user(best_number);
484
485		if link.has_error.load(Ordering::Acquire) {
486			return Poll::Ready(Err(Error::Other(format!(
487				"Stopping after #{} blocks because of an error",
488				link.imported_blocks.load(Ordering::Acquire)
489			))));
490		}
491
492		cx.waker().wake_by_ref();
493		Poll::Pending
494	});
495	Box::pin(import)
496}