1use crate::{
22 standalone::SealVerificationError, AuthoritiesTracker, AuthorityId, CompatibilityMode, Error,
23 LOG_TARGET,
24};
25use codec::Codec;
26use log::{debug, info, trace};
27use prometheus_endpoint::Registry;
28use sc_client_api::{backend::AuxStore, BlockOf, UsageProvider};
29use sc_consensus::{
30 block_import::{BlockImport, BlockImportParams, ForkChoiceStrategy},
31 import_queue::{BasicQueue, BoxJustificationImport, DefaultImportQueue, Verifier},
32};
33use sc_consensus_slots::{check_equivocation, CheckedHeader, InherentDataProviderExt};
34use sc_telemetry::{telemetry, TelemetryHandle, CONSENSUS_DEBUG, CONSENSUS_TRACE};
35use sp_api::{ApiExt, ProvideRuntimeApi};
36use sp_block_builder::BlockBuilder as BlockBuilderApi;
37use sp_blockchain::{HeaderBackend, HeaderMetadata};
38use sp_consensus::Error as ConsensusError;
39use sp_consensus_aura::{inherents::AuraInherentData, AuraApi};
40use sp_consensus_slots::Slot;
41use sp_core::crypto::Pair;
42use sp_inherents::{CreateInherentDataProviders, InherentDataProvider as _};
43use sp_runtime::{
44 traits::{Block as BlockT, Header, NumberFor},
45 DigestItem,
46};
47use std::{fmt::Debug, sync::Arc};
48
49fn check_header<C, B: BlockT, P: Pair>(
55 client: &C,
56 slot_now: Slot,
57 header: B::Header,
58 hash: B::Hash,
59 authorities: &[AuthorityId<P>],
60 check_for_equivocation: CheckForEquivocation,
61) -> Result<CheckedHeader<B::Header, (Slot, DigestItem)>, Error<B>>
62where
63 P::Public: Codec,
64 P::Signature: Codec,
65 C: sc_client_api::backend::AuxStore,
66{
67 let check_result =
68 crate::standalone::check_header_slot_and_seal::<B, P>(slot_now, header, authorities);
69
70 match check_result {
71 Ok((header, slot, seal)) => {
72 let expected_author = crate::standalone::slot_author::<P>(slot, &authorities);
73 let should_equiv_check = check_for_equivocation.check_for_equivocation();
74 if let (true, Some(expected)) = (should_equiv_check, expected_author) {
75 if let Some(equivocation_proof) =
76 check_equivocation(client, slot_now, slot, &header, expected)
77 .map_err(Error::Client)?
78 {
79 info!(
80 target: LOG_TARGET,
81 "Slot author is equivocating at slot {} with headers {:?} and {:?}",
82 slot,
83 equivocation_proof.first_header.hash(),
84 equivocation_proof.second_header.hash(),
85 );
86 }
87 }
88
89 Ok(CheckedHeader::Checked(header, (slot, seal)))
90 },
91 Err(SealVerificationError::Deferred(header, slot)) =>
92 Ok(CheckedHeader::Deferred(header, slot)),
93 Err(SealVerificationError::Unsealed) => Err(Error::HeaderUnsealed(hash)),
94 Err(SealVerificationError::BadSeal) => Err(Error::HeaderBadSeal(hash)),
95 Err(SealVerificationError::BadSignature) => Err(Error::BadSignature(hash)),
96 Err(SealVerificationError::SlotAuthorNotFound) => Err(Error::SlotAuthorNotFound),
97 Err(SealVerificationError::InvalidPreDigest(e)) => Err(Error::from(e)),
98 }
99}
100
101pub struct AuraVerifier<C, P: Pair, CIDP, B: BlockT> {
103 client: Arc<C>,
104 create_inherent_data_providers: CIDP,
105 check_for_equivocation: CheckForEquivocation,
106 telemetry: Option<TelemetryHandle>,
107 compatibility_mode: CompatibilityMode<NumberFor<B>>,
108 authorities_tracker: AuthoritiesTracker<P, B, C>,
109}
110
111impl<C, P: Pair, CIDP, B: BlockT> AuraVerifier<C, P, CIDP, B> {
112 pub(crate) fn new(
113 client: Arc<C>,
114 create_inherent_data_providers: CIDP,
115 check_for_equivocation: CheckForEquivocation,
116 telemetry: Option<TelemetryHandle>,
117 compatibility_mode: CompatibilityMode<NumberFor<B>>,
118 ) -> Self {
119 Self {
120 client: client.clone(),
121 create_inherent_data_providers,
122 check_for_equivocation,
123 telemetry,
124 compatibility_mode,
125 authorities_tracker: AuthoritiesTracker::new(client),
126 }
127 }
128}
129
130#[async_trait::async_trait]
131impl<B, C, P, CIDP> Verifier<B> for AuraVerifier<C, P, CIDP, B>
132where
133 B: BlockT,
134 C: HeaderBackend<B>
135 + HeaderMetadata<B, Error = sp_blockchain::Error>
136 + ProvideRuntimeApi<B>
137 + Send
138 + Sync
139 + sc_client_api::backend::AuxStore,
140 C::Api: BlockBuilderApi<B> + AuraApi<B, AuthorityId<P>> + ApiExt<B>,
141 P: Pair,
142 P::Public: Codec + Debug,
143 P::Signature: Codec,
144 CIDP: CreateInherentDataProviders<B, ()> + Send + Sync,
145 CIDP::InherentDataProviders: InherentDataProviderExt + Send + Sync,
146{
147 async fn verify(
148 &self,
149 mut block: BlockImportParams<B>,
150 ) -> Result<BlockImportParams<B>, String> {
151 if block.with_state() || block.state_action.skip_execution_checks() {
157 block.fork_choice = Some(ForkChoiceStrategy::Custom(block.with_state()));
159
160 return Ok(block)
161 }
162
163 let hash = block.header.hash();
164 let number = *block.header.number();
165 let parent_hash = *block.header.parent_hash();
166
167 let authorities = self
168 .authorities_tracker
169 .fetch_or_update(&block.header, &self.compatibility_mode)
170 .map_err(|e| {
171 format!("Could not fetch authorities for block {hash:?} at number {number}: {e}")
172 })?;
173
174 let create_inherent_data_providers = self
175 .create_inherent_data_providers
176 .create_inherent_data_providers(parent_hash, ())
177 .await
178 .map_err(|e| Error::<B>::Client(sp_blockchain::Error::Application(e)))?;
179
180 let mut inherent_data = create_inherent_data_providers
181 .create_inherent_data()
182 .await
183 .map_err(Error::<B>::Inherent)?;
184
185 let slot_now = create_inherent_data_providers.slot();
186
187 let checked_header = check_header::<C, B, P>(
191 &self.client,
192 slot_now + 1,
193 block.header,
194 hash,
195 &authorities[..],
196 self.check_for_equivocation,
197 )
198 .map_err(|e| e.to_string())?;
199 match checked_header {
200 CheckedHeader::Checked(pre_header, (slot, seal)) => {
201 if let Some(inner_body) = block.body.take() {
205 let new_block = B::new(pre_header.clone(), inner_body);
206
207 inherent_data.aura_replace_inherent_data(slot);
208
209 if self
212 .client
213 .runtime_api()
214 .has_api_with::<dyn BlockBuilderApi<B>, _>(parent_hash, |v| v >= 2)
215 .map_err(|e| e.to_string())?
216 {
217 sp_block_builder::check_inherents_with_data(
218 self.client.clone(),
219 parent_hash,
220 new_block.clone(),
221 &create_inherent_data_providers,
222 inherent_data,
223 )
224 .await
225 .map_err(|e| format!("Error checking block inherents {:?}", e))?;
226 }
227
228 let (_, inner_body) = new_block.deconstruct();
229 block.body = Some(inner_body);
230 }
231
232 self.authorities_tracker.import(&pre_header).map_err(|e| {
233 format!(
234 "Could not import authorities for block {hash:?} at number {number}: {e}"
235 )
236 })?;
237
238 trace!(target: LOG_TARGET, "Checked {:?}; importing.", pre_header);
239 telemetry!(
240 self.telemetry;
241 CONSENSUS_TRACE;
242 "aura.checked_and_importing";
243 "pre_header" => ?pre_header,
244 );
245
246 block.header = pre_header;
247 block.post_digests.push(seal);
248 block.fork_choice = Some(ForkChoiceStrategy::LongestChain);
249 block.post_hash = Some(hash);
250
251 Ok(block)
252 },
253 CheckedHeader::Deferred(a, b) => {
254 debug!(target: LOG_TARGET, "Checking {:?} failed; {:?}, {:?}.", hash, a, b);
255 telemetry!(
256 self.telemetry;
257 CONSENSUS_DEBUG;
258 "aura.header_too_far_in_future";
259 "hash" => ?hash,
260 "a" => ?a,
261 "b" => ?b,
262 );
263 Err(format!("Header {:?} rejected: too far in the future", hash))
264 },
265 }
266 }
267}
268
269#[derive(Debug, Clone, Copy)]
271pub enum CheckForEquivocation {
272 Yes,
276 No,
278}
279
280impl CheckForEquivocation {
281 fn check_for_equivocation(self) -> bool {
283 matches!(self, Self::Yes)
284 }
285}
286
287impl Default for CheckForEquivocation {
288 fn default() -> Self {
289 Self::Yes
290 }
291}
292
293pub struct ImportQueueParams<'a, Block: BlockT, I, C, S, CIDP> {
295 pub block_import: I,
297 pub justification_import: Option<BoxJustificationImport<Block>>,
299 pub client: Arc<C>,
301 pub create_inherent_data_providers: CIDP,
303 pub spawner: &'a S,
305 pub registry: Option<&'a Registry>,
307 pub check_for_equivocation: CheckForEquivocation,
309 pub telemetry: Option<TelemetryHandle>,
311 pub compatibility_mode: CompatibilityMode<NumberFor<Block>>,
315}
316
317pub fn import_queue<P, Block, I, C, S, CIDP>(
319 ImportQueueParams {
320 block_import,
321 justification_import,
322 client,
323 create_inherent_data_providers,
324 spawner,
325 registry,
326 check_for_equivocation,
327 telemetry,
328 compatibility_mode,
329 }: ImportQueueParams<Block, I, C, S, CIDP>,
330) -> Result<DefaultImportQueue<Block>, sp_consensus::Error>
331where
332 Block: BlockT,
333 C::Api: BlockBuilderApi<Block> + AuraApi<Block, AuthorityId<P>> + ApiExt<Block>,
334 C: 'static
335 + ProvideRuntimeApi<Block>
336 + BlockOf
337 + Send
338 + Sync
339 + AuxStore
340 + UsageProvider<Block>
341 + HeaderBackend<Block>
342 + HeaderMetadata<Block, Error = sp_blockchain::Error>,
343 I: BlockImport<Block, Error = ConsensusError> + Send + Sync + 'static,
344 P: Pair + 'static,
345 P::Public: Codec + Debug,
346 P::Signature: Codec,
347 S: sp_core::traits::SpawnEssentialNamed,
348 CIDP: CreateInherentDataProviders<Block, ()> + Sync + Send + 'static,
349 CIDP::InherentDataProviders: InherentDataProviderExt + Send + Sync,
350{
351 let verifier = build_verifier::<P, _, _, _>(BuildVerifierParams {
352 client,
353 create_inherent_data_providers,
354 check_for_equivocation,
355 telemetry,
356 compatibility_mode,
357 });
358
359 Ok(BasicQueue::new(verifier, Box::new(block_import), justification_import, spawner, registry))
360}
361
362pub struct BuildVerifierParams<C, CIDP, N> {
364 pub client: Arc<C>,
366 pub create_inherent_data_providers: CIDP,
368 pub check_for_equivocation: CheckForEquivocation,
370 pub telemetry: Option<TelemetryHandle>,
372 pub compatibility_mode: CompatibilityMode<N>,
376}
377
378pub fn build_verifier<P: Pair, C, CIDP, B: BlockT>(
380 BuildVerifierParams {
381 client,
382 create_inherent_data_providers,
383 check_for_equivocation,
384 telemetry,
385 compatibility_mode,
386 }: BuildVerifierParams<C, CIDP, NumberFor<B>>,
387) -> AuraVerifier<C, P, CIDP, B> {
388 AuraVerifier::<_, P, _, _>::new(
389 client,
390 create_inherent_data_providers,
391 check_for_equivocation,
392 telemetry,
393 compatibility_mode,
394 )
395}