Skip to main content

sc_consensus_subspace/
block_import.rs

1//! Block import for Subspace, which includes stateful verification and corresponding notifications.
2//!
3//! In most cases block import happens after stateless block verification using [`verifier`](crate::verifier),
4//! the only exception to that is locally authored blocks.
5//!
6//! Since [`verifier`](crate::verifier) is stateless, the remaining checks in block import are those
7//! that require presence of the parent block or its state in the database. Specifically for Proof
8//! of Time individual checkpoints are assumed to be checked already and only PoT inputs need to be
9//! checked to correspond to the state of the parent block.
10//!
11//! After all checks and right before importing the block notification ([`SubspaceLink::block_importing_notification_stream`])
12//! will be sent that [`archiver`](crate::archiver) among other things is subscribed to.
13
14use crate::archiver::SegmentHeadersStore;
15use crate::verifier::VerificationError;
16use crate::{SubspaceLink, aux_schema, slot_worker};
17use futures::StreamExt;
18use futures::channel::mpsc;
19use sc_client_api::BlockBackend;
20use sc_client_api::backend::AuxStore;
21use sc_consensus::StateAction;
22use sc_consensus::block_import::{
23    BlockCheckParams, BlockImport, BlockImportParams, ForkChoiceStrategy, ImportResult,
24};
25use sc_proof_of_time::source::pot_next_slot_input;
26use sc_proof_of_time::verifier::PotVerifier;
27use sp_api::{ApiError, ApiExt, ProvideRuntimeApi};
28use sp_block_builder::BlockBuilder as BlockBuilderApi;
29use sp_blockchain::HeaderBackend;
30use sp_consensus_slots::Slot;
31use sp_consensus_subspace::digests::{
32    SubspaceDigestItems, extract_pre_digest, extract_subspace_digest_items,
33};
34use sp_consensus_subspace::{PotNextSlotInput, SubspaceApi, SubspaceJustification};
35use sp_inherents::{CreateInherentDataProviders, InherentDataProvider};
36use sp_runtime::Justifications;
37use sp_runtime::traits::{Block as BlockT, Header as HeaderT, NumberFor, One, Zero};
38use sp_weights::constants::WEIGHT_REF_TIME_PER_MILLIS;
39use std::marker::PhantomData;
40use std::sync::Arc;
41use std::time::Instant;
42use subspace_core_primitives::sectors::SectorId;
43use subspace_core_primitives::segments::{HistorySize, SegmentHeader, SegmentIndex};
44use subspace_core_primitives::solutions::SolutionRange;
45use subspace_core_primitives::{BlockNumber, PublicKey};
46use subspace_proof_of_space::Table;
47use subspace_verification::{PieceCheckParams, VerifySolutionParams, calculate_block_fork_weight};
48use tracing::warn;
49
50/// Maximum number of canonical heights to tombstone per block import.
51const BLOCK_WEIGHT_SWEEP_BATCH: u32 = 10_000;
52
53/// Notification with number of the block that is about to be imported and acknowledgement sender
54/// that can be used to pause block production if desired.
55#[derive(Debug, Clone)]
56pub struct BlockImportingNotification<Block>
57where
58    Block: BlockT,
59{
60    /// Block number
61    pub block_number: NumberFor<Block>,
62    /// Sender for pausing the block import when operator is not fast enough to process
63    /// the consensus block.
64    pub acknowledgement_sender: mpsc::Sender<()>,
65}
66use subspace_verification::Error as VerificationPrimitiveError;
67
68/// Errors encountered by the Subspace authorship task.
69#[derive(Debug, thiserror::Error)]
70pub enum Error<Header: HeaderT> {
71    /// Inner block import error
72    #[error("Inner block import error: {0}")]
73    InnerBlockImportError(#[from] sp_consensus::Error),
74    /// Error during digest item extraction
75    #[error("Digest item error: {0}")]
76    DigestItemError(#[from] sp_consensus_subspace::digests::Error),
77    /// Parent unavailable. Cannot import
78    #[error("Parent ({0}) of {1} unavailable. Cannot import")]
79    ParentUnavailable(Header::Hash, Header::Hash),
80    /// Genesis block unavailable. Cannot import
81    #[error("Genesis block unavailable. Cannot import")]
82    GenesisUnavailable,
83    /// Slot number must increase
84    #[error("Slot number must increase: parent slot: {0}, this slot: {1}")]
85    SlotMustIncrease(Slot, Slot),
86    /// Header has a bad seal
87    #[error("Header {0:?} has a bad seal")]
88    HeaderBadSeal(Header::Hash),
89    /// Header is unsealed
90    #[error("Header {0:?} is unsealed")]
91    HeaderUnsealed(Header::Hash),
92    /// Bad reward signature
93    #[error("Bad reward signature on {0:?}")]
94    BadRewardSignature(Header::Hash),
95    /// Missing Subspace justification
96    #[error("Missing Subspace justification")]
97    MissingSubspaceJustification,
98    /// Invalid Subspace justification
99    #[error("Invalid Subspace justification: {0}")]
100    InvalidSubspaceJustification(parity_scale_codec::Error),
101    /// Invalid Subspace justification contents
102    #[error("Invalid Subspace justification contents")]
103    InvalidSubspaceJustificationContents,
104    /// Invalid proof of time
105    #[error("Invalid proof of time")]
106    InvalidProofOfTime,
107    /// Adding block authoring delay to the slot overflows
108    #[error("Future slot of slot {0} overflows")]
109    FutureSlotOverflow(Slot),
110    /// Solution is outside of solution range
111    #[error(
112        "Solution distance {solution_distance} is outside of solution range \
113        {half_solution_range} (half of actual solution range) for slot {slot}"
114    )]
115    OutsideOfSolutionRange {
116        /// Time slot
117        slot: Slot,
118        /// Half of solution range
119        half_solution_range: SolutionRange,
120        /// Solution distance
121        solution_distance: SolutionRange,
122    },
123    /// Invalid proof of space
124    #[error("Invalid proof of space")]
125    InvalidProofOfSpace,
126    /// Invalid audit chunk offset
127    #[error("Invalid audit chunk offset")]
128    InvalidAuditChunkOffset,
129    /// Invalid chunk
130    #[error("Invalid chunk: {0}")]
131    InvalidChunk(String),
132    /// Invalid chunk witness
133    #[error("Invalid chunk witness")]
134    InvalidChunkWitness,
135    /// Piece verification failed
136    #[error("Piece verification failed")]
137    InvalidPieceOffset {
138        /// Time slot
139        slot: Slot,
140        /// Index of the piece that failed verification
141        piece_offset: u16,
142        /// How many pieces one sector is supposed to contain (max)
143        max_pieces_in_sector: u16,
144    },
145    /// History size is in the future
146    #[error("History size {solution} is in the future, current is {current}")]
147    FutureHistorySize {
148        /// Current history size
149        current: HistorySize,
150        /// History size solution was created for
151        solution: HistorySize,
152    },
153    /// Piece verification failed
154    #[error("Piece verification failed for slot {0}")]
155    InvalidPiece(Slot),
156    /// Block has invalid associated solution range
157    #[error("Invalid solution range for block {0}")]
158    InvalidSolutionRange(Header::Hash),
159    /// Invalid set of segment headers
160    #[error("Invalid set of segment headers")]
161    InvalidSetOfSegmentHeaders,
162    /// Stored segment header extrinsic was not found
163    #[error("Stored segment header extrinsic was not found: {0:?}")]
164    SegmentHeadersExtrinsicNotFound(Vec<SegmentHeader>),
165    /// Segment header not found
166    #[error("Segment header for index {0} not found")]
167    SegmentHeaderNotFound(SegmentIndex),
168    /// Different segment commitment found
169    #[error(
170        "Different segment commitment for segment index {0} was found in storage, likely fork \
171        below archiving point"
172    )]
173    DifferentSegmentCommitment(SegmentIndex),
174    /// Segment commitment not found
175    #[error("Segment commitment for segment index {0} not found")]
176    SegmentCommitmentNotFound(SegmentIndex),
177    /// Sector expired
178    #[error("Sector expired")]
179    SectorExpired {
180        /// Expiration history size
181        expiration_history_size: HistorySize,
182        /// Current history size
183        current_history_size: HistorySize,
184    },
185    /// Invalid history size
186    #[error("Invalid history size")]
187    InvalidHistorySize,
188    /// Only root plot public key is allowed
189    #[error("Only root plot public key is allowed")]
190    OnlyRootPlotPublicKeyAllowed,
191    /// Check inherents error
192    #[error("Checking inherents failed: {0}")]
193    CheckInherents(sp_inherents::Error),
194    /// Unhandled check inherents error
195    #[error("Checking inherents unhandled error: {}", String::from_utf8_lossy(.0))]
196    CheckInherentsUnhandled(sp_inherents::InherentIdentifier),
197    /// Create inherents error.
198    #[error("Creating inherents failed: {0}")]
199    CreateInherents(sp_inherents::Error),
200    /// Client error
201    #[error(transparent)]
202    Client(#[from] sp_blockchain::Error),
203    /// Runtime Api error.
204    #[error(transparent)]
205    RuntimeApi(#[from] ApiError),
206}
207
208impl<Header> From<VerificationError<Header>> for Error<Header>
209where
210    Header: HeaderT,
211{
212    #[inline]
213    fn from(error: VerificationError<Header>) -> Self {
214        match error {
215            VerificationError::HeaderBadSeal(block_hash) => Error::HeaderBadSeal(block_hash),
216            VerificationError::HeaderUnsealed(block_hash) => Error::HeaderUnsealed(block_hash),
217            VerificationError::BadRewardSignature(block_hash) => {
218                Error::BadRewardSignature(block_hash)
219            }
220            VerificationError::MissingSubspaceJustification => Error::MissingSubspaceJustification,
221            VerificationError::InvalidSubspaceJustification(error) => {
222                Error::InvalidSubspaceJustification(error)
223            }
224            VerificationError::InvalidSubspaceJustificationContents => {
225                Error::InvalidSubspaceJustificationContents
226            }
227            VerificationError::InvalidProofOfTime => Error::InvalidProofOfTime,
228            VerificationError::FutureSlotOverflow(slot) => Error::FutureSlotOverflow(slot),
229            VerificationError::VerificationError(slot, error) => match error {
230                VerificationPrimitiveError::InvalidPieceOffset {
231                    piece_offset,
232                    max_pieces_in_sector,
233                } => Error::InvalidPieceOffset {
234                    slot,
235                    piece_offset,
236                    max_pieces_in_sector,
237                },
238                VerificationPrimitiveError::FutureHistorySize { current, solution } => {
239                    Error::FutureHistorySize { current, solution }
240                }
241                VerificationPrimitiveError::InvalidPiece => Error::InvalidPiece(slot),
242                VerificationPrimitiveError::OutsideSolutionRange {
243                    half_solution_range,
244                    solution_distance,
245                } => Error::OutsideOfSolutionRange {
246                    slot,
247                    half_solution_range,
248                    solution_distance,
249                },
250                VerificationPrimitiveError::InvalidProofOfSpace => Error::InvalidProofOfSpace,
251                VerificationPrimitiveError::InvalidAuditChunkOffset => {
252                    Error::InvalidAuditChunkOffset
253                }
254                VerificationPrimitiveError::InvalidChunk(error) => Error::InvalidChunk(error),
255                VerificationPrimitiveError::InvalidChunkWitness => Error::InvalidChunkWitness,
256                VerificationPrimitiveError::SectorExpired {
257                    expiration_history_size,
258                    current_history_size,
259                } => Error::SectorExpired {
260                    expiration_history_size,
261                    current_history_size,
262                },
263                VerificationPrimitiveError::InvalidHistorySize => Error::InvalidHistorySize,
264            },
265        }
266    }
267}
268
269impl<Header> From<Error<Header>> for String
270where
271    Header: HeaderT,
272{
273    #[inline]
274    fn from(error: Error<Header>) -> String {
275        error.to_string()
276    }
277}
278
279/// A block-import handler for Subspace.
280pub struct SubspaceBlockImport<PosTable, Block, Client, I, CIDP, AS>
281where
282    Block: BlockT,
283{
284    inner: I,
285    client: Arc<Client>,
286    subspace_link: SubspaceLink<Block>,
287    create_inherent_data_providers: CIDP,
288    segment_headers_store: SegmentHeadersStore<AS>,
289    pot_verifier: PotVerifier,
290    _pos_table: PhantomData<PosTable>,
291}
292
293impl<PosTable, Block, I, Client, CIDP, AS> Clone
294    for SubspaceBlockImport<PosTable, Block, Client, I, CIDP, AS>
295where
296    Block: BlockT,
297    I: Clone,
298    CIDP: Clone,
299{
300    fn clone(&self) -> Self {
301        SubspaceBlockImport {
302            inner: self.inner.clone(),
303            client: self.client.clone(),
304            subspace_link: self.subspace_link.clone(),
305            create_inherent_data_providers: self.create_inherent_data_providers.clone(),
306            segment_headers_store: self.segment_headers_store.clone(),
307            pot_verifier: self.pot_verifier.clone(),
308            _pos_table: PhantomData,
309        }
310    }
311}
312
313impl<PosTable, Block, Client, I, CIDP, AS> SubspaceBlockImport<PosTable, Block, Client, I, CIDP, AS>
314where
315    PosTable: Table,
316    Block: BlockT,
317    Client: ProvideRuntimeApi<Block> + BlockBackend<Block> + HeaderBackend<Block> + AuxStore,
318    Client::Api: BlockBuilderApi<Block> + SubspaceApi<Block, PublicKey> + ApiExt<Block>,
319    CIDP: CreateInherentDataProviders<Block, ()> + Send + Sync + 'static,
320    AS: AuxStore + Send + Sync + 'static,
321    BlockNumber: From<NumberFor<Block>>,
322{
323    /// Produce a Subspace block-import object to be used later on in the construction of an import-queue.
324    pub fn new(
325        client: Arc<Client>,
326        block_import: I,
327        subspace_link: SubspaceLink<Block>,
328        create_inherent_data_providers: CIDP,
329        segment_headers_store: SegmentHeadersStore<AS>,
330        pot_verifier: PotVerifier,
331    ) -> Self {
332        Self {
333            client,
334            inner: block_import,
335            subspace_link,
336            create_inherent_data_providers,
337            segment_headers_store,
338            pot_verifier,
339            _pos_table: PhantomData,
340        }
341    }
342
343    async fn block_import_verification(
344        &self,
345        block_hash: Block::Hash,
346        header: Block::Header,
347        extrinsics: Option<Vec<Block::Extrinsic>>,
348        root_plot_public_key: &Option<PublicKey>,
349        subspace_digest_items: &SubspaceDigestItems<PublicKey>,
350        justifications: &Option<Justifications>,
351    ) -> Result<(), Error<Block::Header>> {
352        let block_number = *header.number();
353        let parent_hash = *header.parent_hash();
354
355        let pre_digest = &subspace_digest_items.pre_digest;
356        if let Some(root_plot_public_key) = root_plot_public_key
357            && &pre_digest.solution().public_key != root_plot_public_key
358        {
359            // Only root plot public key is allowed.
360            return Err(Error::OnlyRootPlotPublicKeyAllowed);
361        }
362
363        let parent_header = self
364            .client
365            .header(parent_hash)?
366            .ok_or(Error::ParentUnavailable(parent_hash, block_hash))?;
367
368        let parent_pre_digest = extract_pre_digest(&parent_header)?;
369        let parent_slot = parent_pre_digest.slot();
370
371        // Make sure that slot number is strictly increasing
372        if pre_digest.slot() <= parent_slot {
373            return Err(Error::SlotMustIncrease(parent_slot, pre_digest.slot()));
374        }
375
376        let parent_subspace_digest_items = if block_number.is_one() {
377            None
378        } else {
379            Some(extract_subspace_digest_items::<_, PublicKey>(
380                &parent_header,
381            )?)
382        };
383
384        let correct_solution_range = if block_number.is_one() {
385            slot_worker::extract_solution_ranges_for_block(self.client.as_ref(), parent_hash)?.0
386        } else {
387            let parent_subspace_digest_items = parent_subspace_digest_items
388                .as_ref()
389                .expect("Always Some for non-first block; qed");
390
391            match parent_subspace_digest_items.next_solution_range {
392                Some(solution_range) => solution_range,
393                None => parent_subspace_digest_items.solution_range,
394            }
395        };
396
397        if subspace_digest_items.solution_range != correct_solution_range {
398            return Err(Error::InvalidSolutionRange(block_hash));
399        }
400
401        let chain_constants = self.subspace_link.chain_constants();
402
403        // For PoT justifications we only need to check the seed and number of checkpoints, the rest
404        // was already checked during stateless block verification.
405        {
406            let Some(subspace_justification) = justifications
407                .as_ref()
408                .and_then(|justifications| {
409                    justifications
410                        .iter()
411                        .find_map(SubspaceJustification::try_from_justification)
412                })
413                .transpose()
414                .map_err(Error::InvalidSubspaceJustification)?
415            else {
416                return Err(Error::MissingSubspaceJustification);
417            };
418
419            let SubspaceJustification::PotCheckpoints { seed, checkpoints } =
420                subspace_justification;
421
422            let future_slot = Slot::from(
423                pre_digest
424                    .slot()
425                    .checked_add(*chain_constants.block_authoring_delay())
426                    .ok_or(Error::FutureSlotOverflow(pre_digest.slot()))?,
427            );
428
429            if block_number.is_one() {
430                // In case of first block seed must match genesis seed
431                if seed != self.pot_verifier.genesis_seed() {
432                    return Err(Error::InvalidSubspaceJustificationContents);
433                }
434
435                // Number of checkpoints must match future slot number
436                if checkpoints.len() as u64 != *future_slot {
437                    return Err(Error::InvalidSubspaceJustificationContents);
438                }
439            } else {
440                let parent_subspace_digest_items = parent_subspace_digest_items
441                    .as_ref()
442                    .expect("Always Some for non-first block; qed");
443
444                // Can't overflow since parent slot is below this block's slot, whose future slot
445                // was checked above
446                let parent_future_slot = parent_slot + chain_constants.block_authoring_delay();
447
448                let correct_input_parameters = PotNextSlotInput::derive(
449                    subspace_digest_items.pot_slot_iterations,
450                    parent_future_slot,
451                    parent_subspace_digest_items
452                        .pre_digest
453                        .pot_info()
454                        .future_proof_of_time(),
455                    &subspace_digest_items.pot_parameters_change,
456                );
457
458                if seed != correct_input_parameters.seed {
459                    return Err(Error::InvalidSubspaceJustificationContents);
460                }
461
462                // Number of checkpoints must match number of proofs that were not yet seen on chain
463                if checkpoints.len() as u64 != (*future_slot - *parent_future_slot) {
464                    return Err(Error::InvalidSubspaceJustificationContents);
465                }
466            }
467
468            // This is checked last, since it walks over all slots between the parent and this
469            // block, whose number is bounded by the number of checkpoints checked above
470            let runtime_api = self.client.runtime_api();
471            let parent_pot_parameters = runtime_api
472                .pot_parameters(parent_hash)
473                .map_err(|_| Error::ParentUnavailable(parent_hash, block_hash))?;
474
475            let pot_input = pot_next_slot_input::<Block>(
476                parent_header.number(),
477                parent_slot,
478                &parent_pot_parameters,
479                self.pot_verifier.genesis_seed(),
480                parent_pre_digest.pot_info().proof_of_time(),
481            );
482
483            // Ensure proof of time is valid according to parent block
484            if !self.pot_verifier.is_output_valid(
485                pot_input,
486                pre_digest.slot() - parent_slot,
487                pre_digest.pot_info().proof_of_time(),
488                parent_pot_parameters.next_parameters_change(),
489            ) {
490                return Err(Error::InvalidProofOfTime);
491            }
492        }
493
494        let sector_id = SectorId::new(
495            pre_digest.solution().public_key.hash(),
496            pre_digest.solution().sector_index,
497            pre_digest.solution().history_size,
498        );
499
500        let max_pieces_in_sector = self
501            .client
502            .runtime_api()
503            .max_pieces_in_sector(parent_hash)?;
504        let piece_index = sector_id.derive_piece_index(
505            pre_digest.solution().piece_offset,
506            pre_digest.solution().history_size,
507            max_pieces_in_sector,
508            chain_constants.recent_segments(),
509            chain_constants.recent_history_fraction(),
510        );
511        let segment_index = piece_index.segment_index();
512
513        let segment_commitment = self
514            .segment_headers_store
515            .get_segment_header(segment_index)
516            .map(|segment_header| segment_header.segment_commitment())
517            .ok_or(Error::SegmentCommitmentNotFound(segment_index))?;
518
519        let sector_expiration_check_segment_commitment = self
520            .segment_headers_store
521            .get_segment_header(
522                subspace_digest_items
523                    .pre_digest
524                    .solution()
525                    .history_size
526                    .sector_expiration_check(chain_constants.min_sector_lifetime())
527                    .ok_or(Error::InvalidHistorySize)?
528                    .segment_index(),
529            )
530            .map(|segment_header| segment_header.segment_commitment());
531
532        // Piece is not checked during initial block verification because it requires access to
533        // segment header and runtime, check it now.
534        subspace_verification::verify_solution::<PosTable, _>(
535            pre_digest.solution(),
536            // Slot was already checked during initial block verification
537            pre_digest.slot().into(),
538            &VerifySolutionParams {
539                proof_of_time: subspace_digest_items.pre_digest.pot_info().proof_of_time(),
540                solution_range: subspace_digest_items.solution_range,
541                piece_check_params: Some(PieceCheckParams {
542                    max_pieces_in_sector,
543                    segment_commitment,
544                    recent_segments: chain_constants.recent_segments(),
545                    recent_history_fraction: chain_constants.recent_history_fraction(),
546                    min_sector_lifetime: chain_constants.min_sector_lifetime(),
547                    current_history_size: self.client.runtime_api().history_size(parent_hash)?,
548                    sector_expiration_check_segment_commitment,
549                }),
550            },
551            &self.subspace_link.kzg,
552        )
553        .map_err(|error| VerificationError::VerificationError(pre_digest.slot(), error))?;
554
555        // If the body is passed through, we need to use the runtime to check that the
556        // internally-set timestamp in the inherents actually matches the slot set in the seal
557        // and segment headers in the inherents are set correctly.
558        if let Some(extrinsics) = extrinsics {
559            let create_inherent_data_providers = self
560                .create_inherent_data_providers
561                .create_inherent_data_providers(parent_hash, ())
562                .await
563                .map_err(|error| Error::Client(sp_blockchain::Error::from(error)))?;
564
565            let inherent_data = create_inherent_data_providers
566                .create_inherent_data()
567                .await
568                .map_err(Error::CreateInherents)?;
569
570            let inherent_res = self.client.runtime_api().check_inherents(
571                parent_hash,
572                Block::new(header, extrinsics).into(),
573                inherent_data,
574            )?;
575
576            if !inherent_res.ok() {
577                for (i, e) in inherent_res.into_errors() {
578                    match create_inherent_data_providers
579                        .try_handle_error(&i, &e)
580                        .await
581                    {
582                        Some(res) => res.map_err(Error::CheckInherents)?,
583                        None => return Err(Error::CheckInherentsUnhandled(i)),
584                    }
585                }
586            }
587        }
588
589        Ok(())
590    }
591}
592
593#[async_trait::async_trait]
594impl<PosTable, Block, Client, Inner, CIDP, AS> BlockImport<Block>
595    for SubspaceBlockImport<PosTable, Block, Client, Inner, CIDP, AS>
596where
597    PosTable: Table,
598    Block: BlockT,
599    Inner: BlockImport<Block, Error = sp_consensus::Error> + Send + Sync,
600    Client: ProvideRuntimeApi<Block>
601        + BlockBackend<Block>
602        + HeaderBackend<Block>
603        + AuxStore
604        + Send
605        + Sync,
606    Client::Api: BlockBuilderApi<Block> + SubspaceApi<Block, PublicKey> + ApiExt<Block>,
607    CIDP: CreateInherentDataProviders<Block, ()> + Send + Sync + 'static,
608    AS: AuxStore + Send + Sync + 'static,
609    BlockNumber: From<NumberFor<Block>>,
610{
611    type Error = Error<Block::Header>;
612
613    async fn import_block(
614        &self,
615        mut block: BlockImportParams<Block>,
616    ) -> Result<ImportResult, Self::Error> {
617        let block_hash = block.post_hash();
618        let block_number = *block.header.number();
619
620        // Early exit if the block is already in the chain, and never treat it as the best block.
621        match self.client.status(block_hash)? {
622            sp_blockchain::BlockStatus::InChain => {
623                block.fork_choice = Some(ForkChoiceStrategy::Custom(false));
624                return self
625                    .inner
626                    .import_block(block)
627                    .await
628                    .map_err(Error::InnerBlockImportError);
629            }
630            sp_blockchain::BlockStatus::Unknown => {}
631        }
632
633        let subspace_digest_items = extract_subspace_digest_items(&block.header)?;
634
635        // Only do import verification if we do not have the state already. If state needs to be
636        // applied this means verification and execution already happened before and doesn't need to
637        // be done again here (often can't because parent block would be missing in special sync
638        // modes).
639        if !matches!(block.state_action, StateAction::ApplyChanges(_)) {
640            let root_plot_public_key = self
641                .client
642                .runtime_api()
643                .root_plot_public_key(*block.header.parent_hash())?;
644
645            self.block_import_verification(
646                block_hash,
647                block.header.clone(),
648                block.body.clone(),
649                &root_plot_public_key,
650                &subspace_digest_items,
651                &block.justifications,
652            )
653            .await?;
654        }
655
656        // Find the solution range weight of the chain with the parent block at its tip.
657        let parent_weight = if block_number.is_one() {
658            // The genesis block is given a zero fork weight.
659            0
660        } else {
661            // Parent block fork weight might be missing in special sync modes where the block is
662            // imported in the middle of the blockchain history directly. For forks off the same
663            // parent, this doesn't change the comparison outcome.
664            //
665            // For forks off different parents, this only changes the outcome if the fork is over an
666            // era transition. (Solution ranges are fixed within the same era.) In this case, the
667            // rest of the connected nodes will quickly converge, because they have weights starting
668            // further back. This convergence will overwhelm the inconsistent fork choices of any
669            // nodes that are currently snap syncing.
670            aux_schema::load_block_weight(self.client.as_ref(), block.header.parent_hash())?
671                .unwrap_or_default()
672        };
673
674        // We prioritise narrower (numerically smaller) solution ranges, using an inverse
675        // calculation.
676        let added_weight = calculate_block_fork_weight(subspace_digest_items.solution_range);
677        let total_weight = parent_weight.saturating_add(added_weight);
678
679        aux_schema::write_block_weight(block_hash, total_weight, |values| {
680            block
681                .auxiliary
682                .extend(values.iter().map(|(k, v)| (k.to_vec(), Some(v.to_vec()))))
683        });
684
685        {
686            let cleaned_to = aux_schema::load_block_weight_cleaned_to::<NumberFor<Block>, _>(
687                self.client.as_ref(),
688            )?
689            .unwrap_or_else(Zero::zero);
690            let finalized = self.client.info().finalized_number;
691            let batch: NumberFor<Block> = BLOCK_WEIGHT_SWEEP_BATCH.into();
692            let entries = aux_schema::build_canonical_sweep_entries(
693                cleaned_to,
694                finalized,
695                batch,
696                |height| self.client.hash(height),
697            )?;
698            block.auxiliary.extend(entries);
699        }
700
701        for (&segment_index, segment_commitment) in &subspace_digest_items.segment_commitments {
702            let found_segment_commitment = self
703                .segment_headers_store
704                .get_segment_header(segment_index)
705                .ok_or_else(|| Error::SegmentHeaderNotFound(segment_index))?
706                .segment_commitment();
707
708            if &found_segment_commitment != segment_commitment {
709                warn!(
710                    "Different segment commitment for segment index {} was found in storage, \
711                    likely fork below archiving point. expected {:?}, found {:?}",
712                    segment_index, segment_commitment, found_segment_commitment
713                );
714                return Err(Error::DifferentSegmentCommitment(segment_index));
715            }
716        }
717
718        // The fork choice rule is the largest fork solution range weight.
719        //
720        // This almost always prioritises:
721        // - the longest chain (the largest number of solutions), and if there is a tie
722        // - the strictest solutions (the numerically smallest solution ranges).
723        //
724        // If these totals are equal:
725        // - each node keeps the block it already chose (the one that it processed first).
726        //
727        // If there is no previous best block, or the old best block is missing a weight, or has a
728        // zero weight:
729        // - the new block is chosen as the best block, as long as it has a non-zero weight.
730        // (The only blocks with zero weights are in the test runtime.)
731        //
732        // Solution ranges only change at the end of each era, where different block times can make
733        // the range in each fork different. This can lead to some edge cases:
734        // - one fork accepts a solution as within its range, but another with a narrower range
735        //   does not, or
736        // - a fork with a narrower range outweighs a fork with a wider range, leading to a reorg
737        //   to a fork with fewer blocks.
738        //
739        // But these will be resolved with very high probability after a few blocks, assuming the
740        // network is well-connected.
741        let fork_choice = {
742            let info = self.client.info();
743
744            let last_best_weight = if &info.best_hash == block.header.parent_hash() {
745                // The "parent is genesis" case is already covered when loading parent weight, so we don't
746                // need to cover it again here.
747                parent_weight
748            } else {
749                // The best block weight might be missing in special sync modes where the block is
750                // imported in the middle of the blockchain history, right after importing genesis.
751                aux_schema::load_block_weight(&*self.client, info.best_hash)?.unwrap_or_default()
752            };
753
754            ForkChoiceStrategy::Custom(total_weight > last_best_weight)
755        };
756        block.fork_choice = Some(fork_choice);
757
758        let (acknowledgement_sender, mut acknowledgement_receiver) = mpsc::channel(0);
759
760        self.subspace_link
761            .block_importing_notification_sender
762            .notify(move || BlockImportingNotification {
763                block_number,
764                acknowledgement_sender,
765            });
766
767        while acknowledgement_receiver.next().await.is_some() {
768            // Wait for all the acknowledgements to finish.
769        }
770
771        let start = Instant::now();
772
773        let result = self
774            .inner
775            .import_block(block)
776            .await
777            .map_err(Error::InnerBlockImportError)?;
778
779        let actual_execution_time_ms = start.elapsed().as_millis();
780
781        let runtime_api = self.client.runtime_api();
782        let best_hash = self.client.info().best_hash;
783        let subspace_api_version = runtime_api
784            .api_version::<dyn SubspaceApi<Block, PublicKey>>(best_hash)
785            .ok()
786            .flatten()
787            // It is safe to return a default version of 1, since there will always be version 1.
788            .unwrap_or(1);
789
790        if subspace_api_version < 2 {
791            return Ok(result);
792        }
793
794        // this is the actual reference execution time for the given block weight.
795        // but we need add some buffer here to allow for block import processing
796        // apart from the actual execution. A 200ms should be good enough.
797        let reference_execution_time_ms =
798            (runtime_api.block_weight(best_hash)?.ref_time() / WEIGHT_REF_TIME_PER_MILLIS) + 200;
799
800        if actual_execution_time_ms > reference_execution_time_ms as u128 {
801            warn!(
802                ?best_hash,
803                ?reference_execution_time_ms,
804                "Slow Consensus block execution, took {actual_execution_time_ms} ms"
805            );
806        }
807
808        Ok(result)
809    }
810
811    async fn check_block(
812        &self,
813        block: BlockCheckParams<Block>,
814    ) -> Result<ImportResult, Self::Error> {
815        self.inner.check_block(block).await.map_err(Into::into)
816    }
817}