referrerpolicy=no-referrer-when-downgrade

sc_consensus_grandpa/
import.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 std::{collections::HashMap, marker::PhantomData, sync::Arc};
20
21use codec::Decode;
22use log::debug;
23use parking_lot::Mutex;
24
25use sc_client_api::{backend::Backend, utils::is_descendent_of};
26use sc_consensus::{
27	shared_data::{SharedDataLocked, SharedDataLockedUpgradable},
28	BlockCheckParams, BlockImport, BlockImportParams, ImportResult, JustificationImport,
29};
30use sc_telemetry::TelemetryHandle;
31use sc_utils::mpsc::TracingUnboundedSender;
32use sp_api::{Core, RuntimeApiInfo};
33use sp_blockchain::BlockStatus;
34use sp_consensus::{BlockOrigin, Error as ConsensusError, SelectChain};
35use sp_consensus_grandpa::{ConsensusLog, GrandpaApi, ScheduledChange, SetId, GRANDPA_ENGINE_ID};
36use sp_runtime::{
37	generic::OpaqueDigestItemId,
38	traits::{Block as BlockT, Header as HeaderT, NumberFor, Zero},
39	Justification,
40};
41
42use crate::{
43	authorities::{AuthoritySet, DelayKind, PendingChange, SharedAuthoritySet},
44	environment,
45	justification::GrandpaJustification,
46	notification::GrandpaJustificationSender,
47	AuthoritySetChanges, ClientForGrandpa, CommandOrError, Error, NewAuthoritySet, VoterCommand,
48	LOG_TARGET,
49};
50
51/// A block-import handler for GRANDPA.
52///
53/// This scans each imported block for signals of changing authority set.
54/// If the block being imported enacts an authority set change then:
55/// - If the current authority set is still live: we import the block
56/// - Otherwise, the block must include a valid justification.
57///
58/// When using GRANDPA, the block import worker should be using this block import
59/// object.
60pub struct GrandpaBlockImport<Backend, Block: BlockT, Client, SC> {
61	inner: Arc<Client>,
62	justification_import_period: u32,
63	select_chain: SC,
64	authority_set: SharedAuthoritySet<Block::Hash, NumberFor<Block>>,
65	send_voter_commands: TracingUnboundedSender<VoterCommand<Block::Hash, NumberFor<Block>>>,
66	authority_set_hard_forks:
67		Mutex<HashMap<Block::Hash, PendingChange<Block::Hash, NumberFor<Block>>>>,
68	justification_sender: GrandpaJustificationSender<Block>,
69	telemetry: Option<TelemetryHandle>,
70	_phantom: PhantomData<Backend>,
71}
72
73impl<Backend, Block: BlockT, Client, SC: Clone> Clone
74	for GrandpaBlockImport<Backend, Block, Client, SC>
75{
76	fn clone(&self) -> Self {
77		GrandpaBlockImport {
78			inner: self.inner.clone(),
79			justification_import_period: self.justification_import_period,
80			select_chain: self.select_chain.clone(),
81			authority_set: self.authority_set.clone(),
82			send_voter_commands: self.send_voter_commands.clone(),
83			authority_set_hard_forks: Mutex::new(self.authority_set_hard_forks.lock().clone()),
84			justification_sender: self.justification_sender.clone(),
85			telemetry: self.telemetry.clone(),
86			_phantom: PhantomData,
87		}
88	}
89}
90
91#[async_trait::async_trait]
92impl<BE, Block: BlockT, Client, SC> JustificationImport<Block>
93	for GrandpaBlockImport<BE, Block, Client, SC>
94where
95	NumberFor<Block>: finality_grandpa::BlockNumberOps,
96	BE: Backend<Block>,
97	Client: ClientForGrandpa<Block, BE>,
98	SC: SelectChain<Block>,
99{
100	type Error = ConsensusError;
101
102	async fn on_start(&mut self) -> Vec<(Block::Hash, NumberFor<Block>)> {
103		let mut out = Vec::new();
104		let chain_info = self.inner.info();
105
106		// Request justifications for stored effective blocks, which may be above the best block
107		// during header-only sync.
108		let pending_changes: Vec<_> =
109			self.authority_set.inner().pending_changes().cloned().collect();
110
111		for pending_change in pending_changes {
112			if pending_change.delay_kind == DelayKind::Finalized &&
113				pending_change.effective_number() > chain_info.finalized_number
114			{
115				let effective_block_hash = if !pending_change.delay.is_zero() {
116					self.select_chain
117						.finality_target(
118							pending_change.canon_hash,
119							Some(pending_change.effective_number()),
120						)
121						.await
122				} else {
123					Ok(pending_change.canon_hash)
124				};
125
126				if let Ok(hash) = effective_block_hash {
127					if let Ok(Some(header)) = self.inner.header(hash) {
128						if *header.number() == pending_change.effective_number() {
129							out.push((header.hash(), *header.number()));
130						}
131					}
132				}
133			}
134		}
135
136		out
137	}
138
139	async fn import_justification(
140		&mut self,
141		hash: Block::Hash,
142		number: NumberFor<Block>,
143		justification: Justification,
144	) -> Result<(), Self::Error> {
145		// this justification was requested by the sync service, therefore we
146		// are not sure if it should enact a change or not. it could have been a
147		// request made as part of initial sync but that means the justification
148		// wasn't part of the block and was requested asynchronously, probably
149		// makes sense to log in that case.
150		GrandpaBlockImport::import_justification(self, hash, number, justification, false, false)
151	}
152}
153
154enum AppliedChanges<H, N> {
155	Standard(bool), // true if the change is ready to be applied (i.e. it's a root)
156	Forced(NewAuthoritySet<H, N>),
157	None,
158}
159
160impl<H, N> AppliedChanges<H, N> {
161	fn needs_justification(&self) -> bool {
162		match *self {
163			AppliedChanges::Standard(_) => true,
164			AppliedChanges::Forced(_) | AppliedChanges::None => false,
165		}
166	}
167}
168
169struct PendingSetChanges<Block: BlockT> {
170	just_in_case: Option<(
171		AuthoritySet<Block::Hash, NumberFor<Block>>,
172		SharedDataLockedUpgradable<AuthoritySet<Block::Hash, NumberFor<Block>>>,
173	)>,
174	applied_changes: AppliedChanges<Block::Hash, NumberFor<Block>>,
175	do_pause: bool,
176}
177
178impl<Block: BlockT> PendingSetChanges<Block> {
179	// revert the pending set change explicitly.
180	fn revert(self) {}
181
182	fn defuse(mut self) -> (AppliedChanges<Block::Hash, NumberFor<Block>>, bool) {
183		self.just_in_case = None;
184		let applied_changes = std::mem::replace(&mut self.applied_changes, AppliedChanges::None);
185		(applied_changes, self.do_pause)
186	}
187}
188
189impl<Block: BlockT> Drop for PendingSetChanges<Block> {
190	fn drop(&mut self) {
191		if let Some((old_set, mut authorities)) = self.just_in_case.take() {
192			*authorities.upgrade() = old_set;
193		}
194	}
195}
196
197/// Checks the given header for a consensus digest signalling a **standard** scheduled change and
198/// extracts it.
199pub fn find_scheduled_change<B: BlockT>(
200	header: &B::Header,
201) -> Option<ScheduledChange<NumberFor<B>>> {
202	let id = OpaqueDigestItemId::Consensus(&GRANDPA_ENGINE_ID);
203
204	let filter_log = |log: ConsensusLog<NumberFor<B>>| match log {
205		ConsensusLog::ScheduledChange(change) => Some(change),
206		_ => None,
207	};
208
209	// find the first consensus digest with the right ID which converts to
210	// the right kind of consensus log.
211	header.digest().convert_first(|l| l.try_to(id).and_then(filter_log))
212}
213
214/// Checks the given header for a consensus digest signalling a **forced** scheduled change and
215/// extracts it.
216pub fn find_forced_change<B: BlockT>(
217	header: &B::Header,
218) -> Option<(NumberFor<B>, ScheduledChange<NumberFor<B>>)> {
219	let id = OpaqueDigestItemId::Consensus(&GRANDPA_ENGINE_ID);
220
221	let filter_log = |log: ConsensusLog<NumberFor<B>>| match log {
222		ConsensusLog::ForcedChange(delay, change) => Some((delay, change)),
223		_ => None,
224	};
225
226	// find the first consensus digest with the right ID which converts to
227	// the right kind of consensus log.
228	header.digest().convert_first(|l| l.try_to(id).and_then(filter_log))
229}
230
231impl<BE, Block: BlockT, Client, SC> GrandpaBlockImport<BE, Block, Client, SC>
232where
233	NumberFor<Block>: finality_grandpa::BlockNumberOps,
234	BE: Backend<Block>,
235	Client: ClientForGrandpa<Block, BE>,
236	Client::Api: GrandpaApi<Block>,
237	for<'a> &'a Client: BlockImport<Block, Error = ConsensusError>,
238{
239	// check for a new authority set change.
240	fn check_new_change(
241		&self,
242		header: &Block::Header,
243		hash: Block::Hash,
244	) -> Option<PendingChange<Block::Hash, NumberFor<Block>>> {
245		// check for forced authority set hard forks
246		if let Some(change) = self.authority_set_hard_forks.lock().get(&hash) {
247			return Some(change.clone());
248		}
249
250		// check for forced change.
251		if let Some((median_last_finalized, change)) = find_forced_change::<Block>(header) {
252			return Some(PendingChange {
253				next_authorities: change.next_authorities,
254				delay: change.delay,
255				canon_height: *header.number(),
256				canon_hash: hash,
257				delay_kind: DelayKind::Best { median_last_finalized },
258			});
259		}
260
261		// check normal scheduled change.
262		let change = find_scheduled_change::<Block>(header)?;
263		Some(PendingChange {
264			next_authorities: change.next_authorities,
265			delay: change.delay,
266			canon_height: *header.number(),
267			canon_hash: hash,
268			delay_kind: DelayKind::Finalized,
269		})
270	}
271
272	fn make_authorities_changes(
273		&self,
274		block: &mut BlockImportParams<Block>,
275		hash: Block::Hash,
276		initial_sync: bool,
277	) -> Result<PendingSetChanges<Block>, ConsensusError> {
278		// For warp synced block we can skip authority set change tracking for warp synced blocks,
279		// because authority sets will be reconstructed after sync completes from the finalized
280		// state.
281		if block.origin == BlockOrigin::WarpSync {
282			return Ok(PendingSetChanges {
283				just_in_case: None,
284				applied_changes: AppliedChanges::None,
285				do_pause: false,
286			});
287		}
288
289		// when we update the authorities, we need to hold the lock
290		// until the block is written to prevent a race if we need to restore
291		// the old authority set on error or panic.
292		struct InnerGuard<'a, H, N> {
293			old: Option<AuthoritySet<H, N>>,
294			guard: Option<SharedDataLocked<'a, AuthoritySet<H, N>>>,
295		}
296
297		impl<'a, H, N> InnerGuard<'a, H, N> {
298			fn as_mut(&mut self) -> &mut AuthoritySet<H, N> {
299				self.guard.as_mut().expect("only taken on deconstruction; qed")
300			}
301
302			fn set_old(&mut self, old: AuthoritySet<H, N>) {
303				if self.old.is_none() {
304					// ignore "newer" old changes.
305					self.old = Some(old);
306				}
307			}
308
309			fn consume(
310				mut self,
311			) -> Option<(AuthoritySet<H, N>, SharedDataLocked<'a, AuthoritySet<H, N>>)> {
312				self.old
313					.take()
314					.map(|old| (old, self.guard.take().expect("only taken on deconstruction; qed")))
315			}
316		}
317
318		impl<'a, H, N> Drop for InnerGuard<'a, H, N> {
319			fn drop(&mut self) {
320				if let (Some(mut guard), Some(old)) = (self.guard.take(), self.old.take()) {
321					*guard = old;
322				}
323			}
324		}
325
326		let number = *(block.header.number());
327		let maybe_change = self.check_new_change(&block.header, hash);
328
329		// returns a function for checking whether a block is a descendent of another
330		// consistent with querying client directly after importing the block.
331		let parent_hash = *block.header.parent_hash();
332		let is_descendent_of = is_descendent_of(&*self.inner, Some((hash, parent_hash)));
333
334		let mut guard = InnerGuard { guard: Some(self.authority_set.inner_locked()), old: None };
335
336		// whether to pause the old authority set -- happens after import
337		// of a forced change block.
338		let mut do_pause = false;
339
340		// add any pending changes.
341		if let Some(change) = maybe_change {
342			let old = guard.as_mut().clone();
343			guard.set_old(old);
344
345			if let DelayKind::Best { .. } = change.delay_kind {
346				do_pause = true;
347			}
348
349			guard
350				.as_mut()
351				.add_pending_change(change, &is_descendent_of)
352				.map_err(|e| ConsensusError::ClientImport(e.to_string()))?;
353		}
354
355		let applied_changes = {
356			let forced_change_set = guard
357				.as_mut()
358				.apply_forced_changes(
359					hash,
360					number,
361					&is_descendent_of,
362					initial_sync,
363					self.telemetry.clone(),
364				)
365				.map_err(|e| ConsensusError::ClientImport(e.to_string()))
366				.map_err(ConsensusError::from)?;
367
368			if let Some((median_last_finalized_number, new_set)) = forced_change_set {
369				let new_authorities = {
370					let (set_id, new_authorities) = new_set.current();
371
372					// we will use the median last finalized number as a hint
373					// for the canon block the new authority set should start
374					// with. we use the minimum between the median and the local
375					// best finalized block.
376					let best_finalized_number = self.inner.info().finalized_number;
377					let canon_number = best_finalized_number.min(median_last_finalized_number);
378					let canon_hash = self.inner.hash(canon_number)
379							.map_err(|e| ConsensusError::ClientImport(e.to_string()))?
380							.expect(
381								"the given block number is less or equal than the current best finalized number; \
382								 current best finalized number must exist in chain; qed."
383							);
384
385					NewAuthoritySet {
386						canon_number,
387						canon_hash,
388						set_id,
389						authorities: new_authorities.to_vec(),
390					}
391				};
392				let old = ::std::mem::replace(guard.as_mut(), new_set);
393				guard.set_old(old);
394
395				AppliedChanges::Forced(new_authorities)
396			} else {
397				let did_standard = guard
398					.as_mut()
399					.enacts_standard_change(hash, number, &is_descendent_of)
400					.map_err(|e| ConsensusError::ClientImport(e.to_string()))
401					.map_err(ConsensusError::from)?;
402
403				if let Some(root) = did_standard {
404					AppliedChanges::Standard(root)
405				} else {
406					AppliedChanges::None
407				}
408			}
409		};
410
411		// consume the guard safely and write necessary changes.
412		let just_in_case = guard.consume();
413		if let Some((_, ref authorities)) = just_in_case {
414			let authorities_change = match applied_changes {
415				AppliedChanges::Forced(ref new) => Some(new),
416				AppliedChanges::Standard(_) => None, // the change isn't actually applied yet.
417				AppliedChanges::None => None,
418			};
419
420			crate::aux_schema::update_authority_set::<Block, _, _>(
421				authorities,
422				authorities_change,
423				|insert| {
424					block
425						.auxiliary
426						.extend(insert.iter().map(|(k, v)| (k.to_vec(), Some(v.to_vec()))))
427				},
428			);
429		}
430
431		let just_in_case = just_in_case.map(|(o, i)| (o, i.release_mutex()));
432
433		Ok(PendingSetChanges { just_in_case, applied_changes, do_pause })
434	}
435
436	/// Read current set id form a given state.
437	fn current_set_id(&self, hash: Block::Hash) -> Result<SetId, ConsensusError> {
438		let runtime_version = self.inner.runtime_api().version(hash).map_err(|e| {
439			ConsensusError::ClientImport(format!(
440				"Unable to retrieve current runtime version. {}",
441				e
442			))
443		})?;
444
445		if runtime_version
446			.api_version(&<dyn GrandpaApi<Block>>::ID)
447			.map_or(false, |v| v < 3)
448		{
449			// The new API is not supported in this runtime. Try reading directly from storage.
450			// This code may be removed once warp sync to an old runtime is no longer needed.
451			for prefix in ["GrandpaFinality", "Grandpa"] {
452				let k = [
453					sp_crypto_hashing::twox_128(prefix.as_bytes()),
454					sp_crypto_hashing::twox_128(b"CurrentSetId"),
455				]
456				.concat();
457				if let Ok(Some(id)) =
458					self.inner.storage(hash, &sc_client_api::StorageKey(k.to_vec()))
459				{
460					if let Ok(id) = SetId::decode(&mut id.0.as_ref()) {
461						return Ok(id);
462					}
463				}
464			}
465			Err(ConsensusError::ClientImport("Unable to retrieve current set id.".into()))
466		} else {
467			self.inner
468				.runtime_api()
469				.current_set_id(hash)
470				.map_err(|e| ConsensusError::ClientImport(e.to_string()))
471		}
472	}
473
474	/// Import whole new state and reset authority set.
475	async fn import_state(
476		&self,
477		mut block: BlockImportParams<Block>,
478	) -> Result<ImportResult, ConsensusError> {
479		let hash = block.post_hash();
480		let number = *block.header.number();
481		// Force imported state finality.
482		block.finalized = true;
483		let import_result = (&*self.inner).import_block(block).await;
484		match import_result {
485			Ok(ImportResult::Imported(aux)) => {
486				// We've just imported a new state. We trust the sync module has verified
487				// finality proofs and that the state is correct and final.
488				// So we can read the authority list and set id from the state.
489				self.authority_set_hard_forks.lock().clear();
490				let authorities = self
491					.inner
492					.runtime_api()
493					.grandpa_authorities(hash)
494					.map_err(|e| ConsensusError::ClientImport(e.to_string()))?;
495				let set_id = self.current_set_id(hash)?;
496				let authority_set = AuthoritySet::new(
497					authorities.clone(),
498					set_id,
499					fork_tree::ForkTree::new(),
500					Vec::new(),
501					AuthoritySetChanges::empty(),
502				)
503				.ok_or_else(|| ConsensusError::ClientImport("Invalid authority list".into()))?;
504				*self.authority_set.inner_locked() = authority_set.clone();
505
506				crate::aux_schema::update_authority_set::<Block, _, _>(
507					&authority_set,
508					None,
509					|insert| self.inner.insert_aux(insert, []),
510				)
511				.map_err(|e| ConsensusError::ClientImport(e.to_string()))?;
512				let new_set =
513					NewAuthoritySet { canon_number: number, canon_hash: hash, set_id, authorities };
514				let _ = self
515					.send_voter_commands
516					.unbounded_send(VoterCommand::ChangeAuthorities(new_set));
517				Ok(ImportResult::Imported(aux))
518			},
519			Ok(r) => Ok(r),
520			Err(e) => Err(ConsensusError::ClientImport(e.to_string())),
521		}
522	}
523}
524
525#[async_trait::async_trait]
526impl<BE, Block: BlockT, Client, SC> BlockImport<Block> for GrandpaBlockImport<BE, Block, Client, SC>
527where
528	NumberFor<Block>: finality_grandpa::BlockNumberOps,
529	BE: Backend<Block>,
530	Client: ClientForGrandpa<Block, BE>,
531	Client::Api: GrandpaApi<Block>,
532	for<'a> &'a Client: BlockImport<Block, Error = ConsensusError>,
533	SC: Send + Sync,
534{
535	type Error = ConsensusError;
536
537	async fn import_block(
538		&self,
539		mut block: BlockImportParams<Block>,
540	) -> Result<ImportResult, Self::Error> {
541		let hash = block.post_hash();
542		let number = *block.header.number();
543
544		// early exit if block already in chain, otherwise the check for
545		// authority changes will error when trying to re-import a change block
546		match self.inner.status(hash) {
547			Ok(BlockStatus::InChain) => {
548				// Strip justifications when re-importing an existing block.
549				let _justifications = block.justifications.take();
550				return (&*self.inner).import_block(block).await;
551			},
552			Ok(BlockStatus::Unknown) => {},
553			Err(e) => return Err(ConsensusError::ClientImport(e.to_string())),
554		}
555
556		if block.with_state() {
557			return self.import_state(block).await;
558		}
559
560		if number <= self.inner.info().finalized_number {
561			// Importing an old block. Just save justifications and authority set changes
562			let mut pending_changes = None;
563
564			if self.check_new_change(&block.header, hash).is_some() {
565				if block.justifications.is_none() {
566					return Err(ConsensusError::ClientImport(
567						"Justification required when importing \
568							an old block with authority set change."
569							.into(),
570					));
571				}
572				let mut authority_set = self.authority_set.inner_locked();
573				let old_set = authority_set.clone();
574				authority_set
575					.authority_set_changes
576					.insert(number)
577					.map_err(|e| ConsensusError::ClientImport(e.to_string()))?;
578
579				crate::aux_schema::update_authority_set::<Block, _, _>(
580					&authority_set,
581					None,
582					|insert| {
583						block
584							.auxiliary
585							.extend(insert.iter().map(|(k, v)| (k.to_vec(), Some(v.to_vec()))))
586					},
587				);
588
589				// The authority set remains locked until the block is imported.
590				// This ensures the in memory authority set cannot diverge from the DB one.
591				// If the block import fails, the authority set is not committed on the DB.
592				pending_changes = Some(PendingSetChanges::<Block> {
593					just_in_case: Some((old_set, authority_set.release_mutex())),
594					applied_changes: AppliedChanges::None,
595					do_pause: false,
596				});
597			}
598
599			let import_result = self.inner.import_block(block).await;
600			if let Some(pending_changes) = pending_changes {
601				match &import_result {
602					Ok(ImportResult::Imported(_)) => {
603						pending_changes.defuse();
604					},
605					other => {
606						debug!(
607							target: LOG_TARGET,
608							"Restoring old authority set after unsuccessful block import: {other:?}"
609						);
610						pending_changes.revert();
611					},
612				}
613			}
614
615			return import_result;
616		}
617
618		// on initial sync we will restrict logging under info to avoid spam.
619		let initial_sync = block.origin == BlockOrigin::NetworkInitialSync;
620
621		let pending_changes = self.make_authorities_changes(&mut block, hash, initial_sync)?;
622
623		// we don't want to finalize on `inner.import_block`
624		let mut justifications = block.justifications.take();
625		let import_result = (&*self.inner).import_block(block).await;
626
627		let mut imported_aux = {
628			match import_result {
629				Ok(ImportResult::Imported(aux)) => aux,
630				Ok(r) => {
631					debug!(
632						target: LOG_TARGET,
633						"Restoring old authority set after block import result: {:?}", r,
634					);
635					pending_changes.revert();
636					return Ok(r);
637				},
638				Err(e) => {
639					debug!(
640						target: LOG_TARGET,
641						"Restoring old authority set after block import error: {}", e,
642					);
643					pending_changes.revert();
644					return Err(ConsensusError::ClientImport(e.to_string()));
645				},
646			}
647		};
648
649		let (applied_changes, do_pause) = pending_changes.defuse();
650
651		// Send the pause signal after import but BEFORE sending a `ChangeAuthorities` message.
652		if do_pause {
653			let _ = self.send_voter_commands.unbounded_send(VoterCommand::Pause(
654				"Forced change scheduled after inactivity".to_string(),
655			));
656		}
657
658		let needs_justification = applied_changes.needs_justification();
659
660		match applied_changes {
661			AppliedChanges::Forced(new) => {
662				// NOTE: when we do a force change we are "discrediting" the old set so we
663				// ignore any justifications from them. this block may contain a justification
664				// which should be checked and imported below against the new authority
665				// triggered by this forced change. the new grandpa voter will start at the
666				// last median finalized block (which is before the block that enacts the
667				// change), full nodes syncing the chain will not be able to successfully
668				// import justifications for those blocks since their local authority set view
669				// is still of the set before the forced change was enacted, still after #1867
670				// they should import the block and discard the justification, and they will
671				// then request a justification from sync if it's necessary (which they should
672				// then be able to successfully validate).
673				let _ =
674					self.send_voter_commands.unbounded_send(VoterCommand::ChangeAuthorities(new));
675
676				// we must clear all pending justifications requests, presumably they won't be
677				// finalized hence why this forced changes was triggered
678				imported_aux.clear_justification_requests = true;
679			},
680			AppliedChanges::Standard(false) => {
681				// we can't apply this change yet since there are other dependent changes that we
682				// need to apply first, drop any justification that might have been provided with
683				// the block to make sure we request them from `sync` which will ensure they'll be
684				// applied in-order.
685				justifications.take();
686			},
687			_ => {},
688		}
689
690		let grandpa_justification =
691			justifications.and_then(|just| just.into_justification(GRANDPA_ENGINE_ID));
692
693		match grandpa_justification {
694			Some(justification) => {
695				if environment::should_process_justification(
696					&*self.inner,
697					self.justification_import_period,
698					number,
699					needs_justification,
700				) {
701					let import_res = self.import_justification(
702						hash,
703						number,
704						(GRANDPA_ENGINE_ID, justification),
705						needs_justification,
706						initial_sync,
707					);
708
709					import_res.unwrap_or_else(|err| {
710						if needs_justification {
711							debug!(
712								target: LOG_TARGET,
713								"Requesting justification from peers due to imported block #{} that enacts authority set change with invalid justification: {}",
714								number,
715								err
716							);
717							imported_aux.bad_justification = true;
718							imported_aux.needs_justification = true;
719						}
720					});
721				} else {
722					debug!(
723						target: LOG_TARGET,
724						"Ignoring unnecessary justification for block #{}",
725						number,
726					);
727				}
728			},
729			None => {
730				if needs_justification {
731					debug!(
732						target: LOG_TARGET,
733						"Imported unjustified block #{} that enacts authority set change, waiting for finality for enactment.",
734						number,
735					);
736
737					imported_aux.needs_justification = true;
738				}
739			},
740		}
741
742		Ok(ImportResult::Imported(imported_aux))
743	}
744
745	async fn check_block(
746		&self,
747		block: BlockCheckParams<Block>,
748	) -> Result<ImportResult, Self::Error> {
749		self.inner.check_block(block).await
750	}
751}
752
753impl<Backend, Block: BlockT, Client, SC> GrandpaBlockImport<Backend, Block, Client, SC> {
754	pub(crate) fn new(
755		inner: Arc<Client>,
756		justification_import_period: u32,
757		select_chain: SC,
758		authority_set: SharedAuthoritySet<Block::Hash, NumberFor<Block>>,
759		send_voter_commands: TracingUnboundedSender<VoterCommand<Block::Hash, NumberFor<Block>>>,
760		authority_set_hard_forks: Vec<(SetId, PendingChange<Block::Hash, NumberFor<Block>>)>,
761		justification_sender: GrandpaJustificationSender<Block>,
762		telemetry: Option<TelemetryHandle>,
763	) -> GrandpaBlockImport<Backend, Block, Client, SC> {
764		// check for and apply any forced authority set hard fork that applies
765		// to the *current* authority set.
766		if let Some((_, change)) = authority_set_hard_forks
767			.iter()
768			.find(|(set_id, _)| *set_id == authority_set.set_id())
769		{
770			authority_set.inner().current_authorities = change.next_authorities.clone();
771		}
772
773		// index authority set hard forks by block hash so that they can be used
774		// by any node syncing the chain and importing a block hard fork
775		// authority set changes.
776		let authority_set_hard_forks = authority_set_hard_forks
777			.into_iter()
778			.map(|(_, change)| (change.canon_hash, change))
779			.collect::<HashMap<_, _>>();
780
781		// check for and apply any forced authority set hard fork that apply to
782		// any *pending* standard changes, checking by the block hash at which
783		// they were announced.
784		{
785			let mut authority_set = authority_set.inner();
786
787			authority_set.pending_standard_changes =
788				authority_set.pending_standard_changes.clone().map(&mut |hash, _, original| {
789					authority_set_hard_forks.get(hash).cloned().unwrap_or(original)
790				});
791		}
792
793		GrandpaBlockImport {
794			inner,
795			justification_import_period,
796			select_chain,
797			authority_set,
798			send_voter_commands,
799			authority_set_hard_forks: Mutex::new(authority_set_hard_forks),
800			justification_sender,
801			telemetry,
802			_phantom: PhantomData,
803		}
804	}
805}
806
807impl<BE, Block: BlockT, Client, SC> GrandpaBlockImport<BE, Block, Client, SC>
808where
809	BE: Backend<Block>,
810	Client: ClientForGrandpa<Block, BE>,
811	NumberFor<Block>: finality_grandpa::BlockNumberOps,
812{
813	/// Import a block justification and finalize the block.
814	///
815	/// If `enacts_change` is set to true, then finalizing this block *must*
816	/// enact an authority set change, the function will panic otherwise.
817	pub(crate) fn import_justification(
818		&self,
819		hash: Block::Hash,
820		number: NumberFor<Block>,
821		justification: Justification,
822		enacts_change: bool,
823		initial_sync: bool,
824	) -> Result<(), ConsensusError> {
825		if justification.0 != GRANDPA_ENGINE_ID {
826			// TODO: the import queue needs to be refactored to be able dispatch to the correct
827			// `JustificationImport` instance based on `ConsensusEngineId`, or we need to build a
828			// justification import pipeline similar to what we do for `BlockImport`. In the
829			// meantime we'll just drop the justification, since this is only used for BEEFY which
830			// is still WIP.
831			return Ok(());
832		}
833
834		// Decode without holding the authority-set lock; verification must happen
835		// under the lock so it is atomic with the finalization below.
836		let justification = GrandpaJustification::decode(&justification.1)
837			.map_err(|e| ConsensusError::ClientImport(e.to_string()))?;
838
839		let authority_set = self.authority_set.inner();
840
841		justification
842			.verify_finalizes(
843				(hash, number),
844				authority_set.set_id,
845				&authority_set.current_voter_set(),
846			)
847			.map_err(|e| match e {
848				sp_blockchain::Error::OutdatedJustification => {
849					ConsensusError::OutdatedJustification
850				},
851				_ => ConsensusError::ClientImport(e.to_string()),
852			})?;
853
854		let result = environment::finalize_block(
855			self.inner.clone(),
856			authority_set,
857			None,
858			hash,
859			number,
860			justification.into(),
861			initial_sync,
862			Some(&self.justification_sender),
863			self.telemetry.clone(),
864		);
865
866		match result {
867			Err(CommandOrError::VoterCommand(command)) => {
868				grandpa_log!(
869					initial_sync,
870					"👴 Imported justification for block #{} that triggers \
871					command {}, signaling voter.",
872					number,
873					command,
874				);
875
876				// send the command to the voter
877				let _ = self.send_voter_commands.unbounded_send(command);
878			},
879			Err(CommandOrError::Error(e)) => {
880				return Err(match e {
881					Error::Grandpa(error) => ConsensusError::ClientImport(error.to_string()),
882					Error::Network(error) => ConsensusError::ClientImport(error),
883					Error::Blockchain(error) => ConsensusError::ClientImport(error),
884					Error::Client(error) => ConsensusError::ClientImport(error.to_string()),
885					Error::Safety(error) => ConsensusError::ClientImport(error),
886					Error::Signing(error) => ConsensusError::ClientImport(error),
887					Error::Timer(error) => ConsensusError::ClientImport(error.to_string()),
888					Error::RuntimeApi(error) => ConsensusError::ClientImport(error.to_string()),
889				})
890			},
891			Ok(_) => {
892				// Verification above and finalization below share the same authority-set
893				// lock, so a competing finalizer cannot advance the set in between.
894				// Reaching this arm with `enacts_change` set would be a genuine bug.
895				assert!(
896					!enacts_change,
897					"returns Ok when no authority set change should be enacted; qed;"
898				);
899			},
900		}
901
902		Ok(())
903	}
904}