referrerpolicy=no-referrer-when-downgrade

sc_consensus_babe/
lib.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
19//! # BABE (Blind Assignment for Blockchain Extension)
20//!
21//! BABE is a slot-based block production mechanism which uses a VRF PRNG to
22//! randomly perform the slot allocation. On every slot, all the authorities
23//! generate a new random number with the VRF function and if it is lower than a
24//! given threshold (which is proportional to their weight/stake) they have a
25//! right to produce a block. The proof of the VRF function execution will be
26//! used by other peer to validate the legitimacy of the slot claim.
27//!
28//! The engine is also responsible for collecting entropy on-chain which will be
29//! used to seed the given VRF PRNG. An epoch is a contiguous number of slots
30//! under which we will be using the same authority set. During an epoch all VRF
31//! outputs produced as a result of block production will be collected on an
32//! on-chain randomness pool. Epoch changes are announced one epoch in advance,
33//! i.e. when ending epoch N, we announce the parameters (randomness,
34//! authorities, etc.) for epoch N+2.
35//!
36//! Since the slot assignment is randomized, it is possible that a slot is
37//! assigned to multiple validators in which case we will have a temporary fork,
38//! or that a slot is assigned to no validator in which case no block is
39//! produced. Which means that block times are not deterministic.
40//!
41//! The protocol has a parameter `c` [0, 1] for which `1 - c` is the probability
42//! of a slot being empty. The choice of this parameter affects the security of
43//! the protocol relating to maximum tolerable network delays.
44//!
45//! In addition to the VRF-based slot assignment described above, which we will
46//! call primary slots, the engine also supports a deterministic secondary slot
47//! assignment. Primary slots take precedence over secondary slots, when
48//! authoring the node starts by trying to claim a primary slot and falls back
49//! to a secondary slot claim attempt. The secondary slot assignment is done
50//! by picking the authority at index:
51//!
52//! `blake2_256(epoch_randomness ++ slot_number) % authorities_len`.
53//!
54//! The secondary slots supports either a `SecondaryPlain` or `SecondaryVRF`
55//! variant. Comparing with `SecondaryPlain` variant, the `SecondaryVRF` variant
56//! generates an additional VRF output. The output is not included in beacon
57//! randomness, but can be consumed by parachains.
58//!
59//! The fork choice rule is weight-based, where weight equals the number of
60//! primary blocks in the chain. We will pick the heaviest chain (more primary
61//! blocks) and will go with the longest one in case of a tie.
62//!
63//! An in-depth description and analysis of the protocol can be found here:
64//! <https://research.web3.foundation/Polkadot/protocols/block-production/Babe>
65
66#![forbid(unsafe_code)]
67#![warn(missing_docs)]
68
69use std::{
70	collections::HashSet,
71	future::Future,
72	ops::{Deref, DerefMut},
73	pin::Pin,
74	sync::Arc,
75	task::{Context, Poll},
76	time::Duration,
77};
78
79use codec::{Decode, Encode};
80use futures::{
81	channel::{
82		mpsc::{channel, Receiver, Sender},
83		oneshot,
84	},
85	prelude::*,
86};
87use log::{debug, info, log, trace, warn};
88use parking_lot::Mutex;
89use prometheus_endpoint::Registry;
90
91use sc_client_api::{
92	backend::AuxStore, AuxDataOperations, Backend as BackendT, FinalityNotification,
93	PreCommitActions, UsageProvider,
94};
95use sc_consensus::{
96	block_import::{
97		BlockCheckParams, BlockImport, BlockImportParams, ForkChoiceStrategy, ImportResult,
98		StateAction,
99	},
100	import_queue::{BasicQueue, BoxJustificationImport, DefaultImportQueue, Verifier},
101};
102use sc_consensus_epochs::{
103	descendent_query, Epoch as EpochT, EpochChangesFor, SharedEpochChanges, ViableEpoch,
104	ViableEpochDescriptor,
105};
106use sc_consensus_slots::{
107	check_equivocation, BackoffAuthoringBlocksStrategy, CheckedHeader, InherentDataProviderExt,
108	SlotInfo, StorageChanges,
109};
110use sc_telemetry::{telemetry, TelemetryHandle, CONSENSUS_DEBUG, CONSENSUS_TRACE};
111use sc_transaction_pool_api::OffchainTransactionPoolFactory;
112use sp_api::{ApiExt, ProvideRuntimeApi};
113use sp_application_crypto::AppCrypto;
114use sp_block_builder::BlockBuilder as BlockBuilderApi;
115use sp_blockchain::{
116	Backend as _, BlockStatus, Error as ClientError, HeaderBackend, HeaderMetadata,
117	Result as ClientResult,
118};
119use sp_consensus::{BlockOrigin, Environment, Error as ConsensusError, Proposer, SelectChain};
120use sp_consensus_babe::{inherents::BabeInherentData, SlotDuration};
121use sp_consensus_slots::Slot;
122use sp_core::traits::SpawnEssentialNamed;
123use sp_inherents::{CreateInherentDataProviders, InherentDataProvider};
124use sp_keystore::KeystorePtr;
125use sp_runtime::{
126	generic::OpaqueDigestItemId,
127	traits::{Block as BlockT, Header, NumberFor, SaturatedConversion, Zero},
128	DigestItem,
129};
130
131pub use sc_consensus_slots::SlotProportion;
132pub use sp_consensus::SyncOracle;
133pub use sp_consensus_babe::{
134	digests::{
135		CompatibleDigestItem, NextConfigDescriptor, NextEpochDescriptor, PreDigest,
136		PrimaryPreDigest, SecondaryPlainPreDigest,
137	},
138	AuthorityId, AuthorityPair, AuthoritySignature, BabeApi, BabeAuthorityWeight, BabeBlockWeight,
139	BabeConfiguration, BabeEpochConfiguration, ConsensusLog, Randomness, BABE_ENGINE_ID,
140};
141
142pub use aux_schema::load_block_weight as block_weight;
143use sp_timestamp::Timestamp;
144
145mod migration;
146mod verification;
147
148pub mod authorship;
149pub mod aux_schema;
150#[cfg(test)]
151mod tests;
152
153const LOG_TARGET: &str = "babe";
154
155/// VRF context used for slots claiming lottery.
156const AUTHORING_SCORE_VRF_CONTEXT: &[u8] = b"substrate-babe-vrf";
157
158/// VRF output length for slots claiming lottery.
159const AUTHORING_SCORE_LENGTH: usize = 16;
160
161/// BABE epoch information
162#[derive(Clone, Debug, PartialEq, Eq, Encode, Decode)]
163pub struct Epoch(sp_consensus_babe::Epoch);
164
165impl Deref for Epoch {
166	type Target = sp_consensus_babe::Epoch;
167
168	fn deref(&self) -> &Self::Target {
169		&self.0
170	}
171}
172
173impl DerefMut for Epoch {
174	fn deref_mut(&mut self) -> &mut Self::Target {
175		&mut self.0
176	}
177}
178
179impl From<sp_consensus_babe::Epoch> for Epoch {
180	fn from(epoch: sp_consensus_babe::Epoch) -> Self {
181		Epoch(epoch)
182	}
183}
184
185impl EpochT for Epoch {
186	type NextEpochDescriptor = (NextEpochDescriptor, BabeEpochConfiguration);
187	type Slot = Slot;
188
189	fn increment(
190		&self,
191		(descriptor, config): (NextEpochDescriptor, BabeEpochConfiguration),
192	) -> Epoch {
193		sp_consensus_babe::Epoch {
194			epoch_index: self.epoch_index + 1,
195			start_slot: self.start_slot + self.duration,
196			duration: self.duration,
197			authorities: descriptor.authorities,
198			randomness: descriptor.randomness,
199			config,
200		}
201		.into()
202	}
203
204	fn start_slot(&self) -> Slot {
205		self.start_slot
206	}
207
208	fn end_slot(&self) -> Slot {
209		self.start_slot + self.duration
210	}
211}
212
213impl Epoch {
214	/// Create the genesis epoch (epoch #0).
215	///
216	/// This is defined to start at the slot of the first block, so that has to be provided.
217	pub fn genesis(genesis_config: &BabeConfiguration, slot: Slot) -> Epoch {
218		sp_consensus_babe::Epoch {
219			epoch_index: 0,
220			start_slot: slot,
221			duration: genesis_config.epoch_length,
222			authorities: genesis_config.authorities.clone(),
223			randomness: genesis_config.randomness,
224			config: BabeEpochConfiguration {
225				c: genesis_config.c,
226				allowed_slots: genesis_config.allowed_slots,
227			},
228		}
229		.into()
230	}
231
232	/// Clone and tweak epoch information to refer to the specified slot.
233	///
234	/// All the information which depends on the slot value is recomputed and assigned
235	/// to the returned epoch instance.
236	///
237	/// The `slot` must be greater than or equal the original epoch start slot,
238	/// if is less this operation is equivalent to a simple clone.
239	pub fn clone_for_slot(&self, slot: Slot) -> Epoch {
240		let mut epoch = self.clone();
241
242		let skipped_epochs = *slot.saturating_sub(self.start_slot) / self.duration;
243
244		let epoch_index = epoch.epoch_index.checked_add(skipped_epochs).expect(
245			"epoch number is u64; it should be strictly smaller than number of slots; \
246				slots relate in some way to wall clock time; \
247				if u64 is not enough we should crash for safety; qed.",
248		);
249
250		let start_slot = skipped_epochs
251			.checked_mul(epoch.duration)
252			.and_then(|skipped_slots| epoch.start_slot.checked_add(skipped_slots))
253			.expect(
254				"slot number is u64; it should relate in some way to wall clock time; \
255				 if u64 is not enough we should crash for safety; qed.",
256			);
257
258		epoch.epoch_index = epoch_index;
259		epoch.start_slot = Slot::from(start_slot);
260
261		epoch
262	}
263}
264
265/// Errors encountered by the babe authorship task.
266#[derive(Debug, thiserror::Error)]
267pub enum Error<B: BlockT> {
268	/// Multiple BABE pre-runtime digests
269	#[error("Multiple BABE pre-runtime digests, rejecting!")]
270	MultiplePreRuntimeDigests,
271	/// No BABE pre-runtime digest found
272	#[error("No BABE pre-runtime digest found")]
273	NoPreRuntimeDigest,
274	/// Multiple BABE epoch change digests
275	#[error("Multiple BABE epoch change digests, rejecting!")]
276	MultipleEpochChangeDigests,
277	/// Multiple BABE config change digests
278	#[error("Multiple BABE config change digests, rejecting!")]
279	MultipleConfigChangeDigests,
280	/// Could not extract timestamp and slot
281	#[error("Could not extract timestamp and slot: {0}")]
282	Extraction(ConsensusError),
283	/// Could not fetch epoch
284	#[error("Could not fetch epoch at {0:?}")]
285	FetchEpoch(B::Hash),
286	/// Header rejected: too far in the future
287	#[error("Header {0:?} rejected: too far in the future")]
288	TooFarInFuture(B::Hash),
289	/// Parent unavailable. Cannot import
290	#[error("Parent ({0}) of {1} unavailable. Cannot import")]
291	ParentUnavailable(B::Hash, B::Hash),
292	/// Slot number must increase
293	#[error("Slot number must increase: parent slot: {0}, this slot: {1}")]
294	SlotMustIncrease(Slot, Slot),
295	/// Header has a bad seal
296	#[error("Header {0:?} has a bad seal")]
297	HeaderBadSeal(B::Hash),
298	/// Header is unsealed
299	#[error("Header {0:?} is unsealed")]
300	HeaderUnsealed(B::Hash),
301	/// Slot author not found
302	#[error("Slot author not found")]
303	SlotAuthorNotFound,
304	/// Secondary slot assignments are disabled for the current epoch.
305	#[error("Secondary slot assignments are disabled for the current epoch.")]
306	SecondarySlotAssignmentsDisabled,
307	/// Bad signature
308	#[error("Bad signature on {0:?}")]
309	BadSignature(B::Hash),
310	/// Invalid author: Expected secondary author
311	#[error("Invalid author: Expected secondary author: {0:?}, got: {1:?}.")]
312	InvalidAuthor(AuthorityId, AuthorityId),
313	/// No secondary author expected.
314	#[error("No secondary author expected.")]
315	NoSecondaryAuthorExpected,
316	/// VRF verification failed
317	#[error("VRF verification failed")]
318	VrfVerificationFailed,
319	/// Primary slot threshold too low
320	#[error("VRF output rejected, threshold {0} exceeded")]
321	VrfThresholdExceeded(u128),
322	/// Could not fetch parent header
323	#[error("Could not fetch parent header: {0}")]
324	FetchParentHeader(sp_blockchain::Error),
325	/// Expected epoch change to happen.
326	#[error("Expected epoch change to happen at {0:?}, s{1}")]
327	ExpectedEpochChange(B::Hash, Slot),
328	/// Unexpected config change.
329	#[error("Unexpected config change")]
330	UnexpectedConfigChange,
331	/// Unexpected epoch change
332	#[error("Unexpected epoch change")]
333	UnexpectedEpochChange,
334	/// Parent block has no associated weight
335	#[error("Parent block of {0} has no associated weight")]
336	ParentBlockNoAssociatedWeight(B::Hash),
337	/// Check inherents error
338	#[error("Checking inherents failed: {0}")]
339	CheckInherents(sp_inherents::Error),
340	/// Unhandled check inherents error
341	#[error("Checking inherents unhandled error: {}", String::from_utf8_lossy(.0))]
342	CheckInherentsUnhandled(sp_inherents::InherentIdentifier),
343	/// Create inherents error.
344	#[error("Creating inherents failed: {0}")]
345	CreateInherents(sp_inherents::Error),
346	/// Background worker is not running and therefore requests cannot be answered.
347	#[error("Background worker is not running")]
348	BackgroundWorkerTerminated,
349	/// Client error
350	#[error(transparent)]
351	Client(sp_blockchain::Error),
352	/// Runtime Api error.
353	#[error(transparent)]
354	RuntimeApi(sp_api::ApiError),
355	/// Fork tree error
356	#[error(transparent)]
357	ForkTree(Box<fork_tree::Error<sp_blockchain::Error>>),
358}
359
360impl<B: BlockT> From<Error<B>> for String {
361	fn from(error: Error<B>) -> String {
362		error.to_string()
363	}
364}
365
366fn babe_err<B: BlockT>(error: Error<B>) -> Error<B> {
367	debug!(target: LOG_TARGET, "{}", error);
368	error
369}
370
371/// Intermediate value passed to block importer.
372pub struct BabeIntermediate<B: BlockT> {
373	/// The epoch descriptor.
374	pub epoch_descriptor: ViableEpochDescriptor<B::Hash, NumberFor<B>, Epoch>,
375}
376
377/// Intermediate key for Babe engine.
378pub static INTERMEDIATE_KEY: &[u8] = b"babe1";
379
380/// Read configuration from the runtime state at current best block.
381pub fn configuration<B: BlockT, C>(client: &C) -> ClientResult<BabeConfiguration>
382where
383	C: AuxStore + ProvideRuntimeApi<B> + UsageProvider<B>,
384	C::Api: BabeApi<B>,
385{
386	let at_hash = if client.usage_info().chain.finalized_state.is_some() {
387		client.usage_info().chain.best_hash
388	} else {
389		debug!(target: LOG_TARGET, "No finalized state is available. Reading config from genesis");
390		client.usage_info().chain.genesis_hash
391	};
392
393	let runtime_api = client.runtime_api();
394	let version = runtime_api.api_version::<dyn BabeApi<B>>(at_hash)?;
395
396	let config = match version {
397		Some(1) => {
398			#[allow(deprecated)]
399			{
400				runtime_api.configuration_before_version_2(at_hash)?.into()
401			}
402		},
403		Some(2) => runtime_api.configuration(at_hash)?,
404		_ => {
405			return Err(sp_blockchain::Error::VersionInvalid(
406				"Unsupported or invalid BabeApi version".to_string(),
407			))
408		},
409	};
410	Ok(config)
411}
412
413/// Parameters for BABE.
414pub struct BabeParams<B: BlockT, C, SC, E, I, SO, L, CIDP, BS> {
415	/// The keystore that manages the keys of the node.
416	pub keystore: KeystorePtr,
417
418	/// The client to use
419	pub client: Arc<C>,
420
421	/// The SelectChain Strategy
422	pub select_chain: SC,
423
424	/// The environment we are producing blocks for.
425	pub env: E,
426
427	/// The underlying block-import object to supply our produced blocks to.
428	/// This must be a `BabeBlockImport` or a wrapper of it, otherwise
429	/// critical consensus logic will be omitted.
430	pub block_import: I,
431
432	/// A sync oracle
433	pub sync_oracle: SO,
434
435	/// Hook into the sync module to control the justification sync process.
436	pub justification_sync_link: L,
437
438	/// Something that can create the inherent data providers.
439	pub create_inherent_data_providers: CIDP,
440
441	/// Force authoring of blocks even if we are offline
442	pub force_authoring: bool,
443
444	/// Strategy and parameters for backing off block production.
445	pub backoff_authoring_blocks: Option<BS>,
446
447	/// The source of timestamps for relative slots
448	pub babe_link: BabeLink<B>,
449
450	/// The proportion of the slot dedicated to proposing.
451	///
452	/// The block proposing will be limited to this proportion of the slot from the starting of the
453	/// slot. However, the proposing can still take longer when there is some lenience factor
454	/// applied, because there were no blocks produced for some slots.
455	pub block_proposal_slot_portion: SlotProportion,
456
457	/// The maximum proportion of the slot dedicated to proposing with any lenience factor applied
458	/// due to no blocks being produced.
459	pub max_block_proposal_slot_portion: Option<SlotProportion>,
460
461	/// Handle use to report telemetries.
462	pub telemetry: Option<TelemetryHandle>,
463}
464
465/// Start the babe worker.
466pub fn start_babe<B, C, SC, E, I, SO, CIDP, BS, L, Error>(
467	BabeParams {
468		keystore,
469		client,
470		select_chain,
471		env,
472		block_import,
473		sync_oracle,
474		justification_sync_link,
475		create_inherent_data_providers,
476		force_authoring,
477		backoff_authoring_blocks,
478		babe_link,
479		block_proposal_slot_portion,
480		max_block_proposal_slot_portion,
481		telemetry,
482	}: BabeParams<B, C, SC, E, I, SO, L, CIDP, BS>,
483) -> Result<BabeWorker<B>, ConsensusError>
484where
485	B: BlockT,
486	C: ProvideRuntimeApi<B>
487		+ HeaderBackend<B>
488		+ HeaderMetadata<B, Error = ClientError>
489		+ Send
490		+ Sync
491		+ 'static,
492	C::Api: BabeApi<B>,
493	SC: SelectChain<B> + 'static,
494	E: Environment<B, Error = Error> + Send + Sync + 'static,
495	E::Proposer: Proposer<B, Error = Error>,
496	I: BlockImport<B, Error = ConsensusError> + Send + Sync + 'static,
497	SO: SyncOracle + Send + Sync + Clone + 'static,
498	L: sc_consensus::JustificationSyncLink<B> + 'static,
499	CIDP: CreateInherentDataProviders<B, ()> + Send + Sync + 'static,
500	CIDP::InherentDataProviders: InherentDataProviderExt + Send,
501	BS: BackoffAuthoringBlocksStrategy<NumberFor<B>> + Send + Sync + 'static,
502	Error: std::error::Error + Send + From<ConsensusError> + From<I::Error> + 'static,
503{
504	let slot_notification_sinks = Arc::new(Mutex::new(Vec::new()));
505
506	let worker = BabeSlotWorker {
507		client: client.clone(),
508		block_import,
509		env,
510		sync_oracle: sync_oracle.clone(),
511		justification_sync_link,
512		force_authoring,
513		backoff_authoring_blocks,
514		keystore,
515		epoch_changes: babe_link.epoch_changes.clone(),
516		slot_notification_sinks: slot_notification_sinks.clone(),
517		config: babe_link.config.clone(),
518		block_proposal_slot_portion,
519		max_block_proposal_slot_portion,
520		telemetry,
521	};
522
523	info!(target: LOG_TARGET, "๐Ÿ‘ถ Starting BABE Authorship worker");
524
525	let slot_worker = sc_consensus_slots::start_slot_worker(
526		babe_link.config.slot_duration(),
527		select_chain,
528		sc_consensus_slots::SimpleSlotWorkerToSlotWorker(worker),
529		sync_oracle,
530		create_inherent_data_providers,
531	);
532
533	Ok(BabeWorker { inner: Box::pin(slot_worker), slot_notification_sinks })
534}
535
536// Remove obsolete block's weight data by leveraging finality notifications.
537// This includes data for all finalized blocks (excluding the most recent one)
538// and all stale branches.
539fn aux_storage_cleanup<C: HeaderMetadata<Block> + HeaderBackend<Block>, Block: BlockT>(
540	client: &C,
541	notification: &FinalityNotification<Block>,
542) -> AuxDataOperations {
543	let mut hashes = HashSet::new();
544
545	let first = notification.tree_route.first().unwrap_or(&notification.hash);
546	match client.header_metadata(*first) {
547		Ok(meta) => {
548			hashes.insert(meta.parent);
549		},
550		Err(err) => {
551			warn!(target: LOG_TARGET, "Failed to lookup metadata for block `{:?}`: {}", first, err,)
552		},
553	}
554
555	// Cleans data for finalized block's ancestors
556	hashes.extend(
557		notification
558			.tree_route
559			.iter()
560			// Ensure we don't prune latest finalized block.
561			// This should not happen, but better be safe than sorry!
562			.filter(|h| **h != notification.hash),
563	);
564
565	hashes.extend(notification.stale_blocks.iter().map(|b| b.hash));
566
567	hashes
568		.into_iter()
569		.map(|val| (aux_schema::block_weight_key(val), None))
570		.collect()
571}
572
573async fn answer_requests<B: BlockT, C>(
574	mut request_rx: Receiver<BabeRequest<B>>,
575	config: BabeConfiguration,
576	client: Arc<C>,
577	epoch_changes: SharedEpochChanges<B, Epoch>,
578) where
579	C: HeaderBackend<B> + HeaderMetadata<B, Error = ClientError>,
580{
581	while let Some(request) = request_rx.next().await {
582		match request {
583			BabeRequest::EpochData(response) => {
584				let _ = response.send(epoch_changes.shared_data().clone());
585			},
586			BabeRequest::EpochDataForChildOf(parent_hash, parent_number, slot, response) => {
587				let lookup = || {
588					let epoch_changes = epoch_changes.shared_data();
589					epoch_changes
590						.epoch_data_for_child_of(
591							descendent_query(&*client),
592							&parent_hash,
593							parent_number,
594							slot,
595							|slot| Epoch::genesis(&config, slot),
596						)
597						.map_err(|e| Error::<B>::ForkTree(Box::new(e)))?
598						.ok_or(Error::<B>::FetchEpoch(parent_hash))
599				};
600
601				let _ = response.send(lookup());
602			},
603		}
604	}
605}
606
607/// Requests to the BABE service.
608enum BabeRequest<B: BlockT> {
609	/// Request all available epoch data.
610	EpochData(oneshot::Sender<EpochChangesFor<B, Epoch>>),
611	/// Request the epoch that a child of the given block, with the given slot number would have.
612	///
613	/// The parent block is identified by its hash and number.
614	EpochDataForChildOf(B::Hash, NumberFor<B>, Slot, oneshot::Sender<Result<Epoch, Error<B>>>),
615}
616
617/// A handle to the BABE worker for issuing requests.
618#[derive(Clone)]
619pub struct BabeWorkerHandle<B: BlockT>(Sender<BabeRequest<B>>);
620
621impl<B: BlockT> BabeWorkerHandle<B> {
622	async fn send_request(&self, request: BabeRequest<B>) -> Result<(), Error<B>> {
623		match self.0.clone().send(request).await {
624			Err(err) if err.is_disconnected() => return Err(Error::BackgroundWorkerTerminated),
625			Err(err) => warn!(
626				target: LOG_TARGET,
627				"Unhandled error when sending request to worker: {:?}", err
628			),
629			_ => {},
630		}
631
632		Ok(())
633	}
634
635	/// Fetch all available epoch data.
636	pub async fn epoch_data(&self) -> Result<EpochChangesFor<B, Epoch>, Error<B>> {
637		let (tx, rx) = oneshot::channel();
638		self.send_request(BabeRequest::EpochData(tx)).await?;
639
640		rx.await.or(Err(Error::BackgroundWorkerTerminated))
641	}
642
643	/// Fetch the epoch that a child of the given block, with the given slot number would have.
644	///
645	/// The parent block is identified by its hash and number.
646	pub async fn epoch_data_for_child_of(
647		&self,
648		parent_hash: B::Hash,
649		parent_number: NumberFor<B>,
650		slot: Slot,
651	) -> Result<Epoch, Error<B>> {
652		let (tx, rx) = oneshot::channel();
653		self.send_request(BabeRequest::EpochDataForChildOf(parent_hash, parent_number, slot, tx))
654			.await?;
655
656		rx.await.or(Err(Error::BackgroundWorkerTerminated))?
657	}
658}
659
660/// Worker for Babe which implements `Future<Output=()>`. This must be polled.
661#[must_use]
662pub struct BabeWorker<B: BlockT> {
663	inner: Pin<Box<dyn Future<Output = ()> + Send + 'static>>,
664	slot_notification_sinks: SlotNotificationSinks<B>,
665}
666
667impl<B: BlockT> BabeWorker<B> {
668	/// Return an event stream of notifications for when new slot happens, and the corresponding
669	/// epoch descriptor.
670	pub fn slot_notification_stream(
671		&self,
672	) -> Receiver<(Slot, ViableEpochDescriptor<B::Hash, NumberFor<B>, Epoch>)> {
673		const CHANNEL_BUFFER_SIZE: usize = 1024;
674
675		let (sink, stream) = channel(CHANNEL_BUFFER_SIZE);
676		self.slot_notification_sinks.lock().push(sink);
677		stream
678	}
679}
680
681impl<B: BlockT> Future for BabeWorker<B> {
682	type Output = ();
683
684	fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
685		self.inner.as_mut().poll(cx)
686	}
687}
688
689/// Slot notification sinks.
690type SlotNotificationSinks<B> = Arc<
691	Mutex<Vec<Sender<(Slot, ViableEpochDescriptor<<B as BlockT>::Hash, NumberFor<B>, Epoch>)>>>,
692>;
693
694struct BabeSlotWorker<B: BlockT, C, E, I, SO, L, BS> {
695	client: Arc<C>,
696	block_import: I,
697	env: E,
698	sync_oracle: SO,
699	justification_sync_link: L,
700	force_authoring: bool,
701	backoff_authoring_blocks: Option<BS>,
702	keystore: KeystorePtr,
703	epoch_changes: SharedEpochChanges<B, Epoch>,
704	slot_notification_sinks: SlotNotificationSinks<B>,
705	config: BabeConfiguration,
706	block_proposal_slot_portion: SlotProportion,
707	max_block_proposal_slot_portion: Option<SlotProportion>,
708	telemetry: Option<TelemetryHandle>,
709}
710
711#[async_trait::async_trait]
712impl<B, C, E, I, Error, SO, L, BS> sc_consensus_slots::SimpleSlotWorker<B>
713	for BabeSlotWorker<B, C, E, I, SO, L, BS>
714where
715	B: BlockT,
716	C: ProvideRuntimeApi<B> + HeaderBackend<B> + HeaderMetadata<B, Error = ClientError>,
717	C::Api: BabeApi<B>,
718	E: Environment<B, Error = Error> + Send + Sync,
719	E::Proposer: Proposer<B, Error = Error>,
720	I: BlockImport<B> + Send + Sync + 'static,
721	SO: SyncOracle + Send + Clone + Sync,
722	L: sc_consensus::JustificationSyncLink<B>,
723	BS: BackoffAuthoringBlocksStrategy<NumberFor<B>> + Send + Sync,
724	Error: std::error::Error + Send + From<ConsensusError> + From<I::Error> + 'static,
725{
726	type Claim = (PreDigest, AuthorityId);
727	type SyncOracle = SO;
728	type JustificationSyncLink = L;
729	type CreateProposer =
730		Pin<Box<dyn Future<Output = Result<E::Proposer, ConsensusError>> + Send + 'static>>;
731	type Proposer = E::Proposer;
732	type BlockImport = I;
733	type AuxData = ViableEpochDescriptor<B::Hash, NumberFor<B>, Epoch>;
734
735	fn logging_target(&self) -> &'static str {
736		LOG_TARGET
737	}
738
739	fn block_import(&mut self) -> &mut Self::BlockImport {
740		&mut self.block_import
741	}
742
743	fn aux_data(&self, parent: &B::Header, slot: Slot) -> Result<Self::AuxData, ConsensusError> {
744		self.epoch_changes
745			.shared_data()
746			.epoch_descriptor_for_child_of(
747				descendent_query(&*self.client),
748				&parent.hash(),
749				*parent.number(),
750				slot,
751			)
752			.map_err(|e| ConsensusError::ChainLookup(e.to_string()))?
753			.ok_or(ConsensusError::InvalidAuthoritiesSet)
754	}
755
756	fn authorities_len(&self, epoch_descriptor: &Self::AuxData) -> Option<usize> {
757		self.epoch_changes
758			.shared_data()
759			.viable_epoch(epoch_descriptor, |slot| Epoch::genesis(&self.config, slot))
760			.map(|epoch| epoch.as_ref().authorities.len())
761	}
762
763	async fn claim_slot(
764		&mut self,
765		_parent_header: &B::Header,
766		slot: Slot,
767		epoch_descriptor: &ViableEpochDescriptor<B::Hash, NumberFor<B>, Epoch>,
768	) -> Option<Self::Claim> {
769		debug!(target: LOG_TARGET, "Attempting to claim slot {}", slot);
770		let s = authorship::claim_slot(
771			slot,
772			self.epoch_changes
773				.shared_data()
774				.viable_epoch(epoch_descriptor, |slot| Epoch::genesis(&self.config, slot))?
775				.as_ref(),
776			&self.keystore,
777		);
778
779		if s.is_some() {
780			debug!(target: LOG_TARGET, "Claimed slot {}", slot);
781		}
782
783		s
784	}
785
786	fn notify_slot(
787		&self,
788		_parent_header: &B::Header,
789		slot: Slot,
790		epoch_descriptor: &ViableEpochDescriptor<B::Hash, NumberFor<B>, Epoch>,
791	) {
792		let sinks = &mut self.slot_notification_sinks.lock();
793		sinks.retain_mut(|sink| match sink.try_send((slot, epoch_descriptor.clone())) {
794			Ok(()) => true,
795			Err(e) => {
796				if e.is_full() {
797					warn!(target: LOG_TARGET, "Trying to notify a slot but the channel is full");
798					true
799				} else {
800					false
801				}
802			},
803		});
804	}
805
806	fn pre_digest_data(&self, _slot: Slot, claim: &Self::Claim) -> Vec<sp_runtime::DigestItem> {
807		vec![<DigestItem as CompatibleDigestItem>::babe_pre_digest(claim.0.clone())]
808	}
809
810	async fn block_import_params(
811		&self,
812		header: B::Header,
813		header_hash: &B::Hash,
814		body: Vec<B::Extrinsic>,
815		storage_changes: StorageChanges<B>,
816		(_, public): Self::Claim,
817		epoch_descriptor: Self::AuxData,
818	) -> Result<BlockImportParams<B>, ConsensusError> {
819		let signature = self
820			.keystore
821			.sr25519_sign(<AuthorityId as AppCrypto>::ID, public.as_ref(), header_hash.as_ref())
822			.map_err(|e| ConsensusError::CannotSign(format!("{}. Key: {:?}", e, public)))?
823			.ok_or_else(|| {
824				ConsensusError::CannotSign(format!(
825					"Could not find key in keystore. Key: {:?}",
826					public
827				))
828			})?;
829
830		let digest_item = <DigestItem as CompatibleDigestItem>::babe_seal(signature.into());
831
832		let mut import_block = BlockImportParams::new(BlockOrigin::Own, header);
833		import_block.post_digests.push(digest_item);
834		import_block.body = Some(body);
835		import_block.state_action =
836			StateAction::ApplyChanges(sc_consensus::StorageChanges::Changes(storage_changes));
837		import_block
838			.insert_intermediate(INTERMEDIATE_KEY, BabeIntermediate::<B> { epoch_descriptor });
839
840		Ok(import_block)
841	}
842
843	fn force_authoring(&self) -> bool {
844		self.force_authoring
845	}
846
847	fn should_backoff(&self, slot: Slot, chain_head: &B::Header) -> bool {
848		if let Some(ref strategy) = self.backoff_authoring_blocks {
849			if let Ok(chain_head_slot) =
850				find_pre_digest::<B>(chain_head).map(|digest| digest.slot())
851			{
852				return strategy.should_backoff(
853					*chain_head.number(),
854					chain_head_slot,
855					self.client.info().finalized_number,
856					slot,
857					self.logging_target(),
858				);
859			}
860		}
861		false
862	}
863
864	fn sync_oracle(&mut self) -> &mut Self::SyncOracle {
865		&mut self.sync_oracle
866	}
867
868	fn justification_sync_link(&mut self) -> &mut Self::JustificationSyncLink {
869		&mut self.justification_sync_link
870	}
871
872	fn proposer(&mut self, block: &B::Header) -> Self::CreateProposer {
873		Box::pin(self.env.init(block).map_err(|e| ConsensusError::ClientImport(e.to_string())))
874	}
875
876	fn telemetry(&self) -> Option<TelemetryHandle> {
877		self.telemetry.clone()
878	}
879
880	fn proposing_remaining_duration(&self, slot_info: &SlotInfo<B>) -> Duration {
881		let parent_slot = find_pre_digest::<B>(&slot_info.chain_head).ok().map(|d| d.slot());
882
883		sc_consensus_slots::proposing_remaining_duration(
884			parent_slot,
885			slot_info,
886			&self.block_proposal_slot_portion,
887			self.max_block_proposal_slot_portion.as_ref(),
888			sc_consensus_slots::SlotLenienceType::Exponential,
889			self.logging_target(),
890		)
891	}
892}
893
894/// Extract the BABE pre digest from the given header. Pre-runtime digests are
895/// mandatory, the function will return `Err` if none is found.
896pub fn find_pre_digest<B: BlockT>(header: &B::Header) -> Result<PreDigest, Error<B>> {
897	// genesis block doesn't contain a pre digest so let's generate a
898	// dummy one to not break any invariants in the rest of the code
899	if header.number().is_zero() {
900		return Ok(PreDigest::SecondaryPlain(SecondaryPlainPreDigest {
901			slot: 0.into(),
902			authority_index: 0,
903		}));
904	}
905
906	let mut pre_digest: Option<_> = None;
907	for log in header.digest().logs() {
908		trace!(target: LOG_TARGET, "Checking log {:?}, looking for pre runtime digest", log);
909		match (log.as_babe_pre_digest(), pre_digest.is_some()) {
910			(Some(_), true) => return Err(babe_err(Error::MultiplePreRuntimeDigests)),
911			(None, _) => trace!(target: LOG_TARGET, "Ignoring digest not meant for us"),
912			(s, false) => pre_digest = s,
913		}
914	}
915	pre_digest.ok_or_else(|| babe_err(Error::NoPreRuntimeDigest))
916}
917
918/// Check whether the given header contains a BABE epoch change digest.
919pub fn contains_epoch_change<B: BlockT>(header: &B::Header) -> bool {
920	find_next_epoch_digest::<B>(header).ok().flatten().is_some()
921}
922
923/// Extract the BABE epoch change digest from the given header, if it exists.
924pub fn find_next_epoch_digest<B: BlockT>(
925	header: &B::Header,
926) -> Result<Option<NextEpochDescriptor>, Error<B>> {
927	let mut epoch_digest: Option<_> = None;
928	for log in header.digest().logs() {
929		trace!(target: LOG_TARGET, "Checking log {:?}, looking for epoch change digest.", log);
930		let log = log.try_to::<ConsensusLog>(OpaqueDigestItemId::Consensus(&BABE_ENGINE_ID));
931		match (log, epoch_digest.is_some()) {
932			(Some(ConsensusLog::NextEpochData(_)), true) => {
933				return Err(babe_err(Error::MultipleEpochChangeDigests))
934			},
935			(Some(ConsensusLog::NextEpochData(epoch)), false) => epoch_digest = Some(epoch),
936			_ => trace!(target: LOG_TARGET, "Ignoring digest not meant for us"),
937		}
938	}
939
940	Ok(epoch_digest)
941}
942
943/// Extract the BABE config change digest from the given header, if it exists.
944fn find_next_config_digest<B: BlockT>(
945	header: &B::Header,
946) -> Result<Option<NextConfigDescriptor>, Error<B>> {
947	let mut config_digest: Option<_> = None;
948	for log in header.digest().logs() {
949		trace!(target: LOG_TARGET, "Checking log {:?}, looking for epoch change digest.", log);
950		let log = log.try_to::<ConsensusLog>(OpaqueDigestItemId::Consensus(&BABE_ENGINE_ID));
951		match (log, config_digest.is_some()) {
952			(Some(ConsensusLog::NextConfigData(_)), true) => {
953				return Err(babe_err(Error::MultipleConfigChangeDigests))
954			},
955			(Some(ConsensusLog::NextConfigData(config)), false) => config_digest = Some(config),
956			_ => trace!(target: LOG_TARGET, "Ignoring digest not meant for us"),
957		}
958	}
959
960	Ok(config_digest)
961}
962
963/// State that must be shared between the import queue and the authoring logic.
964#[derive(Clone)]
965pub struct BabeLink<Block: BlockT> {
966	epoch_changes: SharedEpochChanges<Block, Epoch>,
967	config: BabeConfiguration,
968}
969
970impl<Block: BlockT> BabeLink<Block> {
971	/// Get the epoch changes of this link.
972	pub fn epoch_changes(&self) -> &SharedEpochChanges<Block, Epoch> {
973		&self.epoch_changes
974	}
975
976	/// Get the config of this link.
977	pub fn config(&self) -> &BabeConfiguration {
978		&self.config
979	}
980}
981
982/// A verifier for Babe blocks.
983pub struct BabeVerifier<Block: BlockT, Client> {
984	client: Arc<Client>,
985	slot_duration: SlotDuration,
986	config: BabeConfiguration,
987	epoch_changes: SharedEpochChanges<Block, Epoch>,
988	telemetry: Option<TelemetryHandle>,
989}
990
991impl<Block: BlockT, Client> BabeVerifier<Block, Client> {
992	pub(crate) fn new(
993		client: Arc<Client>,
994		slot_duration: SlotDuration,
995		config: BabeConfiguration,
996		epoch_changes: SharedEpochChanges<Block, Epoch>,
997		telemetry: Option<TelemetryHandle>,
998	) -> Self {
999		Self { client, slot_duration, config, epoch_changes, telemetry }
1000	}
1001}
1002
1003#[async_trait::async_trait]
1004impl<Block, Client> Verifier<Block> for BabeVerifier<Block, Client>
1005where
1006	Block: BlockT,
1007	Client: HeaderMetadata<Block, Error = sp_blockchain::Error>
1008		+ HeaderBackend<Block>
1009		+ ProvideRuntimeApi<Block>
1010		+ Send
1011		+ Sync
1012		+ AuxStore,
1013	Client::Api: BlockBuilderApi<Block> + BabeApi<Block>,
1014{
1015	async fn verify(
1016		&self,
1017		mut block: BlockImportParams<Block>,
1018	) -> Result<BlockImportParams<Block>, String> {
1019		trace!(
1020			target: LOG_TARGET,
1021			"Verifying origin: {:?} header: {:?} justification(s): {:?} body: {:?}",
1022			block.origin,
1023			block.header,
1024			block.justifications,
1025			block.body,
1026		);
1027
1028		let hash = block.header.hash();
1029		let parent_hash = *block.header.parent_hash();
1030
1031		let number = block.header.number();
1032
1033		if should_skip_verification(&*self.client, &block) {
1034			return Ok(block);
1035		}
1036
1037		debug!(
1038			target: LOG_TARGET,
1039			"We have {:?} logs in this header",
1040			block.header.digest().logs().len()
1041		);
1042
1043		let slot_now = Slot::from_timestamp(Timestamp::current(), self.slot_duration);
1044
1045		let pre_digest = find_pre_digest::<Block>(&block.header)?;
1046		let (check_header, epoch_descriptor) = {
1047			let (epoch_descriptor, viable_epoch) = query_epoch_changes(
1048				&self.epoch_changes,
1049				self.client.as_ref(),
1050				&self.config,
1051				*number,
1052				pre_digest.slot(),
1053				parent_hash,
1054			)?;
1055
1056			// We add one to the current slot to allow for some small drift.
1057			// FIXME #1019 in the future, alter this queue to allow deferring of headers
1058			let v_params = verification::VerificationParams {
1059				header: block.header.clone(),
1060				pre_digest: Some(pre_digest),
1061				slot_now: slot_now + 1,
1062				epoch: viable_epoch.as_ref(),
1063			};
1064
1065			(verification::check_header::<Block>(v_params)?, epoch_descriptor)
1066		};
1067
1068		match check_header {
1069			CheckedHeader::Checked(pre_header, verified_info) => {
1070				trace!(target: LOG_TARGET, "Checked {:?}; importing.", pre_header);
1071				telemetry!(
1072					self.telemetry;
1073					CONSENSUS_TRACE;
1074					"babe.checked_and_importing";
1075					"pre_header" => ?pre_header,
1076				);
1077
1078				block.header = pre_header;
1079				block.post_digests.push(verified_info.seal);
1080				block.insert_intermediate(
1081					INTERMEDIATE_KEY,
1082					BabeIntermediate::<Block> { epoch_descriptor },
1083				);
1084				block.post_hash = Some(hash);
1085
1086				Ok(block)
1087			},
1088			CheckedHeader::Deferred(a, b) => {
1089				debug!(target: LOG_TARGET, "Checking {:?} failed; {:?}, {:?}.", hash, a, b);
1090				telemetry!(
1091					self.telemetry;
1092					CONSENSUS_DEBUG;
1093					"babe.header_too_far_in_future";
1094					"hash" => ?hash, "a" => ?a, "b" => ?b
1095				);
1096				Err(Error::<Block>::TooFarInFuture(hash).into())
1097			},
1098		}
1099	}
1100}
1101
1102/// Verification for imported blocks is skipped in three cases:
1103/// 1. When importing blocks below the last finalized block during network initial synchronization.
1104/// 2. When importing whole state we don't calculate epoch descriptor, but rather read it from the
1105///    state after import. We also skip all verifications because there's no parent state and we
1106///    trust the sync module to verify that the state is correct and finalized.
1107/// 3. When importing warp sync blocks that have already been verified via warp sync proof.
1108fn should_skip_verification<B: BlockT>(
1109	client: &impl HeaderBackend<B>,
1110	block: &BlockImportParams<B>,
1111) -> bool {
1112	block.origin == BlockOrigin::WarpSync || block.with_state() || {
1113		let number = *block.header.number();
1114		let info = client.info();
1115		info.block_gap.map_or(false, |gap| gap.start <= number && number <= gap.end)
1116	}
1117}
1118
1119/// A block-import handler for BABE.
1120///
1121/// This scans each imported block for epoch change signals. The signals are
1122/// tracked in a tree (of all forks), and the import logic validates all epoch
1123/// change transitions, i.e. whether a given epoch change is expected or whether
1124/// it is missing.
1125///
1126/// The epoch change tree should be pruned as blocks are finalized.
1127pub struct BabeBlockImport<Block: BlockT, Client, I, CIDP, SC> {
1128	inner: I,
1129	client: Arc<Client>,
1130	epoch_changes: SharedEpochChanges<Block, Epoch>,
1131	create_inherent_data_providers: CIDP,
1132	config: BabeConfiguration,
1133	// A [`SelectChain`] implementation.
1134	//
1135	// Used to determine the best block that should be used as basis when sending an equivocation
1136	// report.
1137	select_chain: SC,
1138	// The offchain transaction pool factory.
1139	//
1140	// Will be used when sending equivocation reports.
1141	offchain_tx_pool_factory: OffchainTransactionPoolFactory<Block>,
1142}
1143
1144impl<Block: BlockT, I: Clone, Client, CIDP: Clone, SC: Clone> Clone
1145	for BabeBlockImport<Block, Client, I, CIDP, SC>
1146{
1147	fn clone(&self) -> Self {
1148		BabeBlockImport {
1149			inner: self.inner.clone(),
1150			client: self.client.clone(),
1151			epoch_changes: self.epoch_changes.clone(),
1152			config: self.config.clone(),
1153			create_inherent_data_providers: self.create_inherent_data_providers.clone(),
1154			select_chain: self.select_chain.clone(),
1155			offchain_tx_pool_factory: self.offchain_tx_pool_factory.clone(),
1156		}
1157	}
1158}
1159
1160impl<Block: BlockT, Client, I, CIDP, SC> BabeBlockImport<Block, Client, I, CIDP, SC> {
1161	fn new(
1162		client: Arc<Client>,
1163		epoch_changes: SharedEpochChanges<Block, Epoch>,
1164		block_import: I,
1165		config: BabeConfiguration,
1166		create_inherent_data_providers: CIDP,
1167		select_chain: SC,
1168		offchain_tx_pool_factory: OffchainTransactionPoolFactory<Block>,
1169	) -> Self {
1170		BabeBlockImport {
1171			client,
1172			inner: block_import,
1173			epoch_changes,
1174			config,
1175			create_inherent_data_providers,
1176			select_chain,
1177			offchain_tx_pool_factory,
1178		}
1179	}
1180}
1181
1182impl<Block, Client, Inner, CIDP, SC> BabeBlockImport<Block, Client, Inner, CIDP, SC>
1183where
1184	Block: BlockT,
1185	Inner: BlockImport<Block> + Send + Sync,
1186	Inner::Error: Into<ConsensusError>,
1187	Client: HeaderBackend<Block>
1188		+ HeaderMetadata<Block, Error = sp_blockchain::Error>
1189		+ AuxStore
1190		+ ProvideRuntimeApi<Block>
1191		+ Send
1192		+ Sync,
1193	Client::Api: BlockBuilderApi<Block> + BabeApi<Block> + ApiExt<Block>,
1194	CIDP: CreateInherentDataProviders<Block, ()>,
1195	CIDP::InherentDataProviders: InherentDataProviderExt + Send,
1196	SC: sp_consensus::SelectChain<Block> + 'static,
1197{
1198	/// Import whole state after warp sync.
1199	// This function makes multiple transactions to the DB. If one of them fails we may
1200	// end up in an inconsistent state and have to resync.
1201	async fn import_state(
1202		&self,
1203		mut block: BlockImportParams<Block>,
1204	) -> Result<ImportResult, ConsensusError> {
1205		let hash = block.post_hash();
1206		let parent_hash = *block.header.parent_hash();
1207		let number = *block.header.number();
1208
1209		block.fork_choice = Some(ForkChoiceStrategy::Custom(true));
1210		// Reset block weight.
1211		aux_schema::write_block_weight(hash, 0, |values| {
1212			block
1213				.auxiliary
1214				.extend(values.iter().map(|(k, v)| (k.to_vec(), Some(v.to_vec()))))
1215		});
1216
1217		// First make the client import the state.
1218		let import_result = self.inner.import_block(block).await;
1219		let aux = match import_result {
1220			Ok(ImportResult::Imported(aux)) => aux,
1221			Ok(r) => {
1222				return Err(ConsensusError::ClientImport(format!(
1223					"Unexpected import result: {:?}",
1224					r
1225				)))
1226			},
1227			Err(r) => return Err(r.into()),
1228		};
1229
1230		// Read epoch info from the imported state.
1231		let current_epoch = self.client.runtime_api().current_epoch(hash).map_err(|e| {
1232			ConsensusError::ClientImport(babe_err::<Block>(Error::RuntimeApi(e)).into())
1233		})?;
1234		let next_epoch = self.client.runtime_api().next_epoch(hash).map_err(|e| {
1235			ConsensusError::ClientImport(babe_err::<Block>(Error::RuntimeApi(e)).into())
1236		})?;
1237
1238		let mut epoch_changes = self.epoch_changes.shared_data_locked();
1239		epoch_changes.reset(parent_hash, hash, number, current_epoch.into(), next_epoch.into());
1240		aux_schema::write_epoch_changes::<Block, _, _>(&*epoch_changes, |insert| {
1241			self.client.insert_aux(insert, [])
1242		})
1243		.map_err(|e| ConsensusError::ClientImport(e.to_string()))?;
1244
1245		Ok(ImportResult::Imported(aux))
1246	}
1247
1248	/// Check the inherents and equivocations.
1249	async fn check_inherents_and_equivocations(
1250		&self,
1251		block: &mut BlockImportParams<Block>,
1252	) -> Result<(), ConsensusError> {
1253		if should_skip_verification(&*self.client, block) {
1254			return Ok(());
1255		}
1256
1257		let parent_hash = *block.header.parent_hash();
1258		let number = *block.header.number();
1259
1260		let create_inherent_data_providers = self
1261			.create_inherent_data_providers
1262			.create_inherent_data_providers(parent_hash, ())
1263			.await?;
1264
1265		let slot_now = create_inherent_data_providers.slot();
1266
1267		let babe_pre_digest = find_pre_digest::<Block>(&block.header)
1268			.map_err(|e| ConsensusError::Other(Box::new(e)))?;
1269		let slot = babe_pre_digest.slot();
1270
1271		// Check inherents.
1272		self.check_inherents(block, parent_hash, slot, create_inherent_data_providers)
1273			.await?;
1274
1275		// Check for equivocation and report it to the runtime if needed.
1276		let author = {
1277			let viable_epoch = query_epoch_changes(
1278				&self.epoch_changes,
1279				self.client.as_ref(),
1280				&self.config,
1281				number,
1282				slot,
1283				parent_hash,
1284			)
1285			.map_err(|e| ConsensusError::Other(babe_err(e).into()))?
1286			.1;
1287			match viable_epoch
1288				.as_ref()
1289				.authorities
1290				.get(babe_pre_digest.authority_index() as usize)
1291			{
1292				Some(author) => author.0.clone(),
1293				None => {
1294					return Err(ConsensusError::Other(Error::<Block>::SlotAuthorNotFound.into()))
1295				},
1296			}
1297		};
1298		if let Err(err) = self
1299			.check_and_report_equivocation(slot_now, slot, &block.header, &author, &block.origin)
1300			.await
1301		{
1302			warn!(
1303				target: LOG_TARGET,
1304				"Error checking/reporting BABE equivocation: {}", err
1305			);
1306		}
1307		Ok(())
1308	}
1309
1310	async fn check_inherents(
1311		&self,
1312		block: &mut BlockImportParams<Block>,
1313		at_hash: Block::Hash,
1314		slot: Slot,
1315		create_inherent_data_providers: CIDP::InherentDataProviders,
1316	) -> Result<(), ConsensusError> {
1317		if block.state_action.skip_execution_checks() {
1318			return Ok(());
1319		}
1320
1321		if let Some(inner_body) = block.body.take() {
1322			let new_block = Block::new(block.header.clone(), inner_body);
1323			// if the body is passed through and the block was executed,
1324			// we need to use the runtime to check that the internally-set
1325			// timestamp in the inherents actually matches the slot set in the seal.
1326			let mut inherent_data = create_inherent_data_providers
1327				.create_inherent_data()
1328				.await
1329				.map_err(|e| ConsensusError::Other(Box::new(e)))?;
1330			inherent_data.babe_replace_inherent_data(slot);
1331
1332			use sp_block_builder::CheckInherentsError;
1333
1334			sp_block_builder::check_inherents_with_data(
1335				self.client.clone(),
1336				at_hash,
1337				new_block.clone(),
1338				&create_inherent_data_providers,
1339				inherent_data,
1340			)
1341			.await
1342			.map_err(|e| {
1343				ConsensusError::Other(Box::new(match e {
1344					CheckInherentsError::CreateInherentData(e) => {
1345						Error::<Block>::CreateInherents(e)
1346					},
1347					CheckInherentsError::Client(e) => Error::RuntimeApi(e),
1348					CheckInherentsError::CheckInherents(e) => Error::CheckInherents(e),
1349					CheckInherentsError::CheckInherentsUnknownError(id) => {
1350						Error::CheckInherentsUnhandled(id)
1351					},
1352				}))
1353			})?;
1354			let (_, inner_body) = new_block.deconstruct();
1355			block.body = Some(inner_body);
1356		}
1357
1358		Ok(())
1359	}
1360
1361	async fn check_and_report_equivocation(
1362		&self,
1363		slot_now: Slot,
1364		slot: Slot,
1365		header: &Block::Header,
1366		author: &AuthorityId,
1367		origin: &BlockOrigin,
1368	) -> Result<(), Error<Block>> {
1369		// don't report any equivocations during initial sync
1370		// as they are most likely stale.
1371		if *origin == BlockOrigin::NetworkInitialSync {
1372			return Ok(());
1373		}
1374
1375		// check if authorship of this header is an equivocation and return a proof if so.
1376		let Some(equivocation_proof) =
1377			check_equivocation(&*self.client, slot_now, slot, header, author)
1378				.map_err(Error::Client)?
1379		else {
1380			return Ok(());
1381		};
1382
1383		info!(
1384			target: LOG_TARGET,
1385			"Slot author {:?} is equivocating at slot {} with headers {:?} and {:?}",
1386			author,
1387			slot,
1388			equivocation_proof.first_header.hash(),
1389			equivocation_proof.second_header.hash(),
1390		);
1391
1392		// get the best block on which we will build and send the equivocation report.
1393		let best_hash = self
1394			.select_chain
1395			.best_chain()
1396			.await
1397			.map(|h| h.hash())
1398			.map_err(|e| Error::Client(e.into()))?;
1399
1400		// generate a key ownership proof. we start by trying to generate the
1401		// key ownership proof at the parent of the equivocating header, this
1402		// will make sure that proof generation is successful since it happens
1403		// during the on-going session (i.e. session keys are available in the
1404		// state to be able to generate the proof). this might fail if the
1405		// equivocation happens on the first block of the session, in which case
1406		// its parent would be on the previous session. if generation on the
1407		// parent header fails we try with best block as well.
1408		let generate_key_owner_proof = |at_hash: Block::Hash| {
1409			self.client
1410				.runtime_api()
1411				.generate_key_ownership_proof(at_hash, slot, equivocation_proof.offender.clone())
1412				.map_err(Error::RuntimeApi)
1413		};
1414
1415		let parent_hash = *header.parent_hash();
1416		let key_owner_proof = match generate_key_owner_proof(parent_hash)? {
1417			Some(proof) => proof,
1418			None => match generate_key_owner_proof(best_hash)? {
1419				Some(proof) => proof,
1420				None => {
1421					debug!(
1422						target: LOG_TARGET,
1423						"Equivocation offender is not part of the authority set."
1424					);
1425					return Ok(());
1426				},
1427			},
1428		};
1429
1430		// submit equivocation report at best block.
1431		let mut runtime_api = self.client.runtime_api();
1432
1433		// Register the offchain tx pool to be able to use it from the runtime.
1434		runtime_api
1435			.register_extension(self.offchain_tx_pool_factory.offchain_transaction_pool(best_hash));
1436
1437		runtime_api
1438			.submit_report_equivocation_unsigned_extrinsic(
1439				best_hash,
1440				equivocation_proof,
1441				key_owner_proof,
1442			)
1443			.map_err(Error::RuntimeApi)?;
1444
1445		info!(target: LOG_TARGET, "Submitted equivocation report for author {:?}", author);
1446
1447		Ok(())
1448	}
1449}
1450
1451#[async_trait::async_trait]
1452impl<Block, Client, Inner, CIDP, SC> BlockImport<Block>
1453	for BabeBlockImport<Block, Client, Inner, CIDP, SC>
1454where
1455	Block: BlockT,
1456	Inner: BlockImport<Block> + Send + Sync,
1457	Inner::Error: Into<ConsensusError>,
1458	Client: HeaderBackend<Block>
1459		+ HeaderMetadata<Block, Error = sp_blockchain::Error>
1460		+ AuxStore
1461		+ ProvideRuntimeApi<Block>
1462		+ Send
1463		+ Sync,
1464	Client::Api: BlockBuilderApi<Block> + BabeApi<Block> + ApiExt<Block>,
1465	CIDP: CreateInherentDataProviders<Block, ()>,
1466	CIDP::InherentDataProviders: InherentDataProviderExt + Send + Sync,
1467	SC: SelectChain<Block> + 'static,
1468{
1469	type Error = ConsensusError;
1470
1471	async fn import_block(
1472		&self,
1473		mut block: BlockImportParams<Block>,
1474	) -> Result<ImportResult, Self::Error> {
1475		let hash = block.post_hash();
1476		let parent_hash = *block.header.parent_hash();
1477		let number = *block.header.number();
1478		let info = self.client.info();
1479
1480		self.check_inherents_and_equivocations(&mut block).await?;
1481
1482		let block_status = self
1483			.client
1484			.status(hash)
1485			.map_err(|e| ConsensusError::ClientImport(e.to_string()))?;
1486
1487		// Skip babe logic if block already in chain or importing blocks during initial sync,
1488		// otherwise the check for epoch changes will error because trying to re-import an
1489		// epoch change or because of missing epoch data in the tree, respectively.
1490		if info.block_gap.map_or(false, |gap| gap.start <= number && number <= gap.end) ||
1491			block_status == BlockStatus::InChain
1492		{
1493			// When re-importing existing block strip away intermediates.
1494			// In case of initial sync intermediates should not be present...
1495			let _ = block.remove_intermediate::<BabeIntermediate<Block>>(INTERMEDIATE_KEY);
1496			block.fork_choice = Some(ForkChoiceStrategy::Custom(false));
1497			return self.inner.import_block(block).await.map_err(Into::into);
1498		}
1499
1500		if block.with_state() {
1501			return self.import_state(block).await;
1502		}
1503
1504		let pre_digest = find_pre_digest::<Block>(&block.header).expect(
1505			"valid babe headers must contain a predigest; header has been already verified; qed",
1506		);
1507		let slot = pre_digest.slot();
1508
1509		// If there's a pending epoch we'll save the previous epoch changes here
1510		// this way we can revert it if there's any error.
1511		let mut old_epoch_changes = None;
1512
1513		// Skip epoch change processing for warp synced blocks
1514		let epoch_changes = if block.origin != BlockOrigin::WarpSync {
1515			let parent_header = self
1516				.client
1517				.header(parent_hash)
1518				.map_err(|e| ConsensusError::ChainLookup(e.to_string()))?
1519				.ok_or_else(|| {
1520					ConsensusError::ChainLookup(
1521						babe_err(Error::<Block>::ParentUnavailable(parent_hash, hash)).into(),
1522					)
1523				})?;
1524
1525			let parent_slot = find_pre_digest::<Block>(&parent_header).map(|d| d.slot()).expect(
1526				"parent is non-genesis; valid BABE headers contain a pre-digest; header has already \
1527				 been verified; qed",
1528			);
1529
1530			// make sure that slot number is strictly increasing
1531			if slot <= parent_slot {
1532				return Err(ConsensusError::ClientImport(
1533					babe_err(Error::<Block>::SlotMustIncrease(parent_slot, slot)).into(),
1534				));
1535			}
1536
1537			let mut epoch_changes = self.epoch_changes.shared_data_locked();
1538
1539			// check if there's any epoch change expected to happen at this slot.
1540			// `epoch` is the epoch to verify the block under, and `first_in_epoch` is true
1541			// if this is the first block in its chain for that epoch.
1542			//
1543			// also provides the total weight of the chain, including the imported block.
1544			let (epoch_descriptor, first_in_epoch, parent_weight) = {
1545				let parent_weight = if *parent_header.number() == Zero::zero() {
1546					0
1547				} else {
1548					aux_schema::load_block_weight(&*self.client, parent_hash)
1549						.map_err(|e| ConsensusError::ClientImport(e.to_string()))?
1550						.ok_or_else(|| {
1551							ConsensusError::ClientImport(
1552								babe_err(Error::<Block>::ParentBlockNoAssociatedWeight(hash))
1553									.into(),
1554							)
1555						})?
1556				};
1557
1558				let intermediate =
1559					block.remove_intermediate::<BabeIntermediate<Block>>(INTERMEDIATE_KEY)?;
1560
1561				let epoch_descriptor = intermediate.epoch_descriptor;
1562				let first_in_epoch = parent_slot < epoch_descriptor.start_slot();
1563				(epoch_descriptor, first_in_epoch, parent_weight)
1564			};
1565
1566			let total_weight = parent_weight + pre_digest.added_weight();
1567
1568			// search for this all the time so we can reject unexpected announcements.
1569			let next_epoch_digest = find_next_epoch_digest::<Block>(&block.header)
1570				.map_err(|e| ConsensusError::ClientImport(e.to_string()))?;
1571			let next_config_digest = find_next_config_digest::<Block>(&block.header)
1572				.map_err(|e| ConsensusError::ClientImport(e.to_string()))?;
1573
1574			match (first_in_epoch, next_epoch_digest.is_some(), next_config_digest.is_some()) {
1575				(true, true, _) => {},
1576				(false, false, false) => {},
1577				(false, false, true) => {
1578					return Err(ConsensusError::ClientImport(
1579						babe_err(Error::<Block>::UnexpectedConfigChange).into(),
1580					))
1581				},
1582				(true, false, _) => {
1583					return Err(ConsensusError::ClientImport(
1584						babe_err(Error::<Block>::ExpectedEpochChange(hash, slot)).into(),
1585					))
1586				},
1587				(false, true, _) => {
1588					return Err(ConsensusError::ClientImport(
1589						babe_err(Error::<Block>::UnexpectedEpochChange).into(),
1590					))
1591				},
1592			}
1593
1594			if let Some(next_epoch_descriptor) = next_epoch_digest {
1595				old_epoch_changes = Some((*epoch_changes).clone());
1596
1597				let mut viable_epoch = epoch_changes
1598					.viable_epoch(&epoch_descriptor, |slot| Epoch::genesis(&self.config, slot))
1599					.ok_or_else(|| {
1600						ConsensusError::ClientImport(Error::<Block>::FetchEpoch(parent_hash).into())
1601					})?
1602					.into_cloned();
1603
1604				let epoch_config = next_config_digest
1605					.map(Into::into)
1606					.unwrap_or_else(|| viable_epoch.as_ref().config.clone());
1607
1608				// restrict info logging during initial sync to avoid spam
1609				let log_level = if block.origin == BlockOrigin::NetworkInitialSync {
1610					log::Level::Debug
1611				} else {
1612					log::Level::Info
1613				};
1614
1615				if viable_epoch.as_ref().end_slot() <= slot {
1616					// Some epochs must have been skipped as our current slot fits outside the
1617					// current epoch. We will figure out which epoch it belongs to and we will
1618					// re-use the same data for that epoch.
1619					// Notice that we are only updating a local copy of the `Epoch`, this
1620					// makes it so that when we insert the next epoch into `EpochChanges` below
1621					// (after incrementing it), it will use the correct epoch index and start
1622					// slot. We do not update the original epoch that will be re-used
1623					// because there might be other forks (that we haven't imported) where
1624					// the epoch isn't skipped, and to import those forks we want to keep
1625					// the original epoch data. Not updating the original epoch works
1626					// because when we search the tree for which epoch to use for a given
1627					// slot, we will search in-depth with the predicate `epoch.start_slot
1628					// <= slot` which will still match correctly without updating
1629					// `start_slot` to the correct value as below.
1630					let epoch = viable_epoch.as_mut();
1631					let prev_index = epoch.epoch_index;
1632					*epoch = epoch.clone_for_slot(slot);
1633
1634					warn!(
1635						target: LOG_TARGET,
1636						"๐Ÿ‘ถ Epoch(s) skipped: from {} to {}", prev_index, epoch.epoch_index,
1637					);
1638				}
1639
1640				log!(
1641					target: LOG_TARGET,
1642					log_level,
1643					"๐Ÿ‘ถ New epoch {} launching at block {} (block slot {} >= start slot {}).",
1644					viable_epoch.as_ref().epoch_index,
1645					hash,
1646					slot,
1647					viable_epoch.as_ref().start_slot,
1648				);
1649
1650				let next_epoch = viable_epoch.increment((next_epoch_descriptor, epoch_config));
1651
1652				log!(
1653					target: LOG_TARGET,
1654					log_level,
1655					"๐Ÿ‘ถ Next epoch starts at slot {}",
1656					next_epoch.as_ref().start_slot,
1657				);
1658
1659				// prune the tree of epochs not part of the finalized chain or
1660				// that are not live anymore, and then track the given epoch change
1661				// in the tree.
1662				// NOTE: it is important that these operations are done in this
1663				// order, otherwise if pruning after import the `is_descendent_of`
1664				// used by pruning may not know about the block that is being
1665				// imported.
1666				let prune_and_import = || {
1667					prune_finalized(self.client.clone(), &mut epoch_changes)?;
1668
1669					epoch_changes
1670						.import(
1671							descendent_query(&*self.client),
1672							hash,
1673							number,
1674							*block.header.parent_hash(),
1675							next_epoch,
1676						)
1677						.map_err(|e| {
1678							ConsensusError::ClientImport(format!(
1679								"Error importing epoch changes: {}",
1680								e
1681							))
1682						})?;
1683					Ok(())
1684				};
1685
1686				if let Err(e) = prune_and_import() {
1687					debug!(target: LOG_TARGET, "Failed to launch next epoch: {}", e);
1688					*epoch_changes =
1689						old_epoch_changes.expect("set `Some` above and not taken; qed");
1690					return Err(e);
1691				}
1692
1693				crate::aux_schema::write_epoch_changes::<Block, _, _>(&*epoch_changes, |insert| {
1694					block
1695						.auxiliary
1696						.extend(insert.iter().map(|(k, v)| (k.to_vec(), Some(v.to_vec()))))
1697				});
1698			}
1699
1700			aux_schema::write_block_weight(hash, total_weight, |values| {
1701				block
1702					.auxiliary
1703					.extend(values.iter().map(|(k, v)| (k.to_vec(), Some(v.to_vec()))))
1704			});
1705
1706			// The fork choice rule is that we pick the heaviest chain (i.e.
1707			// more primary blocks), if there's a tie we go with the longest
1708			// chain.
1709			block.fork_choice = {
1710				let (last_best, last_best_number) = (info.best_hash, info.best_number);
1711
1712				let last_best_weight = if &last_best == block.header.parent_hash() {
1713					// the parent=genesis case is already covered for loading parent weight,
1714					// so we don't need to cover again here.
1715					parent_weight
1716				} else {
1717					aux_schema::load_block_weight(&*self.client, last_best)
1718						.map_err(|e| ConsensusError::ChainLookup(e.to_string()))?
1719						.ok_or_else(|| {
1720							ConsensusError::ChainLookup(
1721								"No block weight for parent header.".to_string(),
1722							)
1723						})?
1724				};
1725
1726				Some(ForkChoiceStrategy::Custom(if total_weight > last_best_weight {
1727					true
1728				} else if total_weight == last_best_weight {
1729					number > last_best_number
1730				} else {
1731					false
1732				}))
1733			};
1734
1735			// Release the mutex, but it stays locked
1736			Some(epoch_changes.release_mutex())
1737		} else {
1738			block.fork_choice = Some(ForkChoiceStrategy::Custom(false));
1739			None
1740		};
1741
1742		let import_result = self.inner.import_block(block).await;
1743
1744		// revert to the original epoch changes in case there's an error
1745		// importing the block
1746		if import_result.is_err() {
1747			if let (Some(mut epoch_changes), Some(old_epoch_changes)) =
1748				(epoch_changes, old_epoch_changes)
1749			{
1750				*epoch_changes.upgrade() = old_epoch_changes;
1751			}
1752		}
1753
1754		import_result.map_err(Into::into)
1755	}
1756
1757	async fn check_block(
1758		&self,
1759		block: BlockCheckParams<Block>,
1760	) -> Result<ImportResult, Self::Error> {
1761		self.inner.check_block(block).await.map_err(Into::into)
1762	}
1763}
1764
1765/// Gets the best finalized block and its slot, and prunes the given epoch tree.
1766///
1767/// Skips pruning when the finalized header has no BABE pre-digest โ€” not all finalized blocks
1768/// have to be BABE-authored.
1769fn prune_finalized<Block, Client>(
1770	client: Arc<Client>,
1771	epoch_changes: &mut EpochChangesFor<Block, Epoch>,
1772) -> Result<(), ConsensusError>
1773where
1774	Block: BlockT,
1775	Client: HeaderBackend<Block> + HeaderMetadata<Block, Error = sp_blockchain::Error>,
1776{
1777	let info = client.info();
1778
1779	let finalized_header = client
1780		.header(info.finalized_hash)
1781		.map_err(|e| ConsensusError::ClientImport(e.to_string()))?
1782		.expect("best finalized hash was given by client; finalized headers must exist in db; qed");
1783
1784	let finalized_slot = match find_pre_digest::<Block>(&finalized_header) {
1785		Ok(pre_digest) => pre_digest.slot(),
1786		Err(e) => {
1787			debug!(
1788				target: LOG_TARGET,
1789				"Skipping epoch-tree pruning: finalized header {:?} has no BABE pre-digest ({e:?})",
1790				info.finalized_hash,
1791			);
1792			return Ok(());
1793		},
1794	};
1795
1796	epoch_changes
1797		.prune_finalized(
1798			descendent_query(&*client),
1799			&info.finalized_hash,
1800			info.finalized_number,
1801			finalized_slot,
1802		)
1803		.map_err(|e| ConsensusError::ClientImport(e.to_string()))?;
1804
1805	Ok(())
1806}
1807
1808/// Produce a BABE block-import object to be used later on in the construction of
1809/// an import-queue.
1810///
1811/// Also returns a link object used to correctly instantiate the import queue
1812/// and background worker.
1813pub fn block_import<Client, Block: BlockT, I, CIDP, SC>(
1814	config: BabeConfiguration,
1815	wrapped_block_import: I,
1816	client: Arc<Client>,
1817	create_inherent_data_providers: CIDP,
1818	select_chain: SC,
1819	offchain_tx_pool_factory: OffchainTransactionPoolFactory<Block>,
1820) -> ClientResult<(BabeBlockImport<Block, Client, I, CIDP, SC>, BabeLink<Block>)>
1821where
1822	Client: AuxStore
1823		+ HeaderBackend<Block>
1824		+ HeaderMetadata<Block, Error = sp_blockchain::Error>
1825		+ PreCommitActions<Block>
1826		+ 'static,
1827{
1828	let epoch_changes = aux_schema::load_epoch_changes::<Block, _>(&*client, &config)?;
1829	let link = BabeLink { epoch_changes: epoch_changes.clone(), config: config.clone() };
1830
1831	// NOTE: this isn't entirely necessary, but since we didn't use to prune the
1832	// epoch tree it is useful as a migration, so that nodes prune long trees on
1833	// startup rather than waiting until importing the next epoch change block.
1834	prune_finalized(client.clone(), &mut epoch_changes.shared_data())?;
1835
1836	let client_weak = Arc::downgrade(&client);
1837	let on_finality = move |summary: &FinalityNotification<Block>| {
1838		if let Some(client) = client_weak.upgrade() {
1839			aux_storage_cleanup(client.as_ref(), summary)
1840		} else {
1841			Default::default()
1842		}
1843	};
1844	client.register_finality_action(Box::new(on_finality));
1845
1846	let import = BabeBlockImport::new(
1847		client,
1848		epoch_changes,
1849		wrapped_block_import,
1850		config,
1851		create_inherent_data_providers,
1852		select_chain,
1853		offchain_tx_pool_factory,
1854	);
1855
1856	Ok((import, link))
1857}
1858
1859/// Parameters of [`build_verifier`].
1860pub struct BuildVerifierParams<Block: BlockT, Client> {
1861	/// The client to interact with the internals of the node.
1862	pub client: Arc<Client>,
1863	/// Slot duration.
1864	pub slot_duration: SlotDuration,
1865	/// BABE configuration for this chain.
1866	pub config: BabeConfiguration,
1867	/// Shared epoch-changes tree.
1868	pub epoch_changes: SharedEpochChanges<Block, Epoch>,
1869	/// Optional telemetry handle to report telemetry events.
1870	pub telemetry: Option<TelemetryHandle>,
1871}
1872
1873/// Build the [`BabeVerifier`]
1874pub fn build_verifier<Block: BlockT, Client>(
1875	BuildVerifierParams { client, slot_duration, config, epoch_changes, telemetry }: BuildVerifierParams<
1876		Block,
1877		Client,
1878	>,
1879) -> BabeVerifier<Block, Client> {
1880	BabeVerifier::new(client, slot_duration, config, epoch_changes, telemetry)
1881}
1882
1883/// Parameters passed to [`import_queue`].
1884pub struct ImportQueueParams<'a, Block: BlockT, BI, Client, Spawn> {
1885	/// The BABE link that is created by [`block_import`].
1886	pub link: BabeLink<Block>,
1887	/// The block import that should be wrapped.
1888	pub block_import: BI,
1889	/// Optional justification import.
1890	pub justification_import: Option<BoxJustificationImport<Block>>,
1891	/// The client to interact with the internals of the node.
1892	pub client: Arc<Client>,
1893	/// Slot duration.
1894	pub slot_duration: SlotDuration,
1895	/// Spawner for spawning futures.
1896	pub spawner: &'a Spawn,
1897	/// Registry for prometheus metrics.
1898	pub registry: Option<&'a Registry>,
1899	/// Optional telemetry handle to report telemetry events.
1900	pub telemetry: Option<TelemetryHandle>,
1901}
1902
1903/// Start an import queue for the BABE consensus algorithm.
1904///
1905/// This method returns the import queue, some data that needs to be passed to the block authoring
1906/// logic (`BabeLink`), and a future that must be run to
1907/// completion and is responsible for listening to finality notifications and
1908/// pruning the epoch changes tree.
1909///
1910/// The block import object provided must be the `BabeBlockImport` or a wrapper
1911/// of it, otherwise crucial import logic will be omitted.
1912pub fn import_queue<Block: BlockT, Client, BI, Spawn>(
1913	ImportQueueParams {
1914		link: babe_link,
1915		block_import,
1916		justification_import,
1917		client,
1918		slot_duration,
1919		spawner,
1920		registry,
1921		telemetry,
1922	}: ImportQueueParams<'_, Block, BI, Client, Spawn>,
1923) -> ClientResult<(DefaultImportQueue<Block>, BabeWorkerHandle<Block>)>
1924where
1925	BI: BlockImport<Block, Error = ConsensusError> + Send + Sync + 'static,
1926	Client: ProvideRuntimeApi<Block>
1927		+ HeaderBackend<Block>
1928		+ HeaderMetadata<Block, Error = sp_blockchain::Error>
1929		+ AuxStore
1930		+ Send
1931		+ Sync
1932		+ 'static,
1933	Client::Api: BlockBuilderApi<Block> + BabeApi<Block> + ApiExt<Block>,
1934	Spawn: SpawnEssentialNamed,
1935{
1936	const HANDLE_BUFFER_SIZE: usize = 1024;
1937
1938	let verifier = build_verifier(BuildVerifierParams {
1939		client: client.clone(),
1940		slot_duration,
1941		config: babe_link.config.clone(),
1942		epoch_changes: babe_link.epoch_changes.clone(),
1943		telemetry,
1944	});
1945
1946	let (worker_tx, worker_rx) = channel(HANDLE_BUFFER_SIZE);
1947
1948	let answer_requests =
1949		answer_requests(worker_rx, babe_link.config, client, babe_link.epoch_changes);
1950
1951	spawner.spawn_essential("babe-worker", Some("babe"), answer_requests.boxed());
1952
1953	Ok((
1954		BasicQueue::new(verifier, Box::new(block_import), justification_import, spawner, registry),
1955		BabeWorkerHandle(worker_tx),
1956	))
1957}
1958
1959/// Reverts protocol aux data to at most the last finalized block.
1960/// In particular, epoch-changes and block weights announced after the revert
1961/// point are removed.
1962pub fn revert<Block, Client, Backend>(
1963	client: Arc<Client>,
1964	backend: Arc<Backend>,
1965	blocks: NumberFor<Block>,
1966) -> ClientResult<()>
1967where
1968	Block: BlockT,
1969	Client: AuxStore
1970		+ HeaderMetadata<Block, Error = sp_blockchain::Error>
1971		+ HeaderBackend<Block>
1972		+ ProvideRuntimeApi<Block>
1973		+ UsageProvider<Block>,
1974	Client::Api: BabeApi<Block>,
1975	Backend: BackendT<Block>,
1976{
1977	let best_number = client.info().best_number;
1978	let finalized = client.info().finalized_number;
1979
1980	let revertible = blocks.min(best_number - finalized);
1981	if revertible == Zero::zero() {
1982		return Ok(());
1983	}
1984
1985	let revert_up_to_number = best_number - revertible;
1986	let revert_up_to_hash = client.hash(revert_up_to_number)?.ok_or(ClientError::Backend(
1987		format!("Unexpected hash lookup failure for block number: {}", revert_up_to_number),
1988	))?;
1989
1990	// Revert epoch changes tree.
1991
1992	// This config is only used on-genesis.
1993	let config = configuration(&*client)?;
1994	let epoch_changes = aux_schema::load_epoch_changes::<Block, Client>(&*client, &config)?;
1995	let mut epoch_changes = epoch_changes.shared_data();
1996
1997	if revert_up_to_number == Zero::zero() {
1998		// Special case, no epoch changes data were present on genesis.
1999		*epoch_changes = EpochChangesFor::<Block, Epoch>::default();
2000	} else {
2001		epoch_changes.revert(descendent_query(&*client), revert_up_to_hash, revert_up_to_number);
2002	}
2003
2004	// Remove block weights added after the revert point.
2005
2006	let mut weight_keys = HashSet::with_capacity(revertible.saturated_into());
2007
2008	let leaves = backend.blockchain().leaves()?.into_iter().filter(|&leaf| {
2009		sp_blockchain::tree_route(&*client, revert_up_to_hash, leaf)
2010			.map(|route| route.retracted().is_empty())
2011			.unwrap_or_default()
2012	});
2013
2014	for leaf in leaves {
2015		let mut hash = leaf;
2016		loop {
2017			let meta = client.header_metadata(hash)?;
2018			if meta.number <= revert_up_to_number ||
2019				!weight_keys.insert(aux_schema::block_weight_key(hash))
2020			{
2021				// We've reached the revert point or an already processed branch, stop here.
2022				break;
2023			}
2024			hash = meta.parent;
2025		}
2026	}
2027
2028	let weight_keys: Vec<_> = weight_keys.iter().map(|val| val.as_slice()).collect();
2029
2030	// Write epoch changes and remove weights in one shot.
2031	aux_schema::write_epoch_changes::<Block, _, _>(&epoch_changes, |values| {
2032		client.insert_aux(values, weight_keys.iter())
2033	})
2034}
2035
2036fn query_epoch_changes<Block, Client>(
2037	epoch_changes: &SharedEpochChanges<Block, Epoch>,
2038	client: &Client,
2039	config: &BabeConfiguration,
2040	block_number: NumberFor<Block>,
2041	slot: Slot,
2042	parent_hash: Block::Hash,
2043) -> Result<
2044	(ViableEpochDescriptor<Block::Hash, NumberFor<Block>, Epoch>, ViableEpoch<Epoch>),
2045	Error<Block>,
2046>
2047where
2048	Block: BlockT,
2049	Client: HeaderBackend<Block> + HeaderMetadata<Block, Error = sp_blockchain::Error>,
2050{
2051	let epoch_changes = epoch_changes.shared_data();
2052	let epoch_descriptor = epoch_changes
2053		.epoch_descriptor_for_child_of(
2054			descendent_query(client),
2055			&parent_hash,
2056			block_number - 1u32.into(),
2057			slot,
2058		)
2059		.map_err(|e| Error::<Block>::ForkTree(Box::new(e)))?
2060		.ok_or(Error::<Block>::FetchEpoch(parent_hash))?;
2061	let viable_epoch = epoch_changes
2062		.viable_epoch(&epoch_descriptor, |slot| Epoch::genesis(&config, slot))
2063		.ok_or(Error::<Block>::FetchEpoch(parent_hash))?;
2064	Ok((epoch_descriptor, viable_epoch.into_cloned()))
2065}