Skip to main content

sc_consensus_subspace/
verifier.rs

1//! Stateless and parallelized block verification that happens before block is imported (except for locally produced
2//! blocks that are imported directly).
3//!
4//! The goal of verifier is to check internal consistency of the block, which includes things like
5//! solution according to claimed inputs, signature, Proof of Time checkpoints in justifications,
6//! etc.
7//!
8//! This should be the majority of the block verification computation such that all that is left for
9//! [`block_import`](crate::block_import) to check is that information in the block corresponds to
10//! the state of the parent block, which for the most part is comparing bytes against known good
11//! values.
12//!
13//! This is a significant tradeoff in the protocol: having a smaller header vs being able to verify
14//! a lot of things stateless and in parallel.
15
16use futures::lock::Mutex;
17use rand::prelude::*;
18use rayon::prelude::*;
19use sc_client_api::backend::AuxStore;
20use sc_consensus::block_import::BlockImportParams;
21use sc_consensus::import_queue::Verifier;
22use sc_consensus_slots::check_equivocation;
23use sc_proof_of_time::verifier::PotVerifier;
24use sc_telemetry::{CONSENSUS_TRACE, TelemetryHandle, telemetry};
25use schnorrkel::context::SigningContext;
26use sp_api::ProvideRuntimeApi;
27use sp_block_builder::BlockBuilder as BlockBuilderApi;
28use sp_blockchain::HeaderBackend;
29use sp_consensus::BlockOrigin;
30use sp_consensus_slots::Slot;
31use sp_consensus_subspace::digests::{
32    CompatibleDigestItem, PreDigest, SubspaceDigestItems, extract_subspace_digest_items,
33};
34use sp_consensus_subspace::{ChainConstants, PotNextSlotInput, SubspaceApi, SubspaceJustification};
35use sp_runtime::traits::{Block as BlockT, Header as HeaderT, NumberFor};
36use sp_runtime::{DigestItem, Justifications};
37use std::iter;
38use std::marker::PhantomData;
39use std::num::NonZeroUsize;
40use std::sync::Arc;
41use std::sync::atomic::{AtomicU32, Ordering};
42use std::thread::available_parallelism;
43use subspace_core_primitives::{BlockNumber, PublicKey};
44use subspace_kzg::Kzg;
45use subspace_proof_of_space::Table;
46use subspace_verification::{VerifySolutionParams, check_reward_signature, verify_solution};
47use tokio::runtime::Handle;
48use tracing::{debug, info, trace, warn};
49
50/// Errors encountered by the Subspace verification task.
51#[derive(Debug, Eq, PartialEq, thiserror::Error)]
52pub enum VerificationError<Header: HeaderT> {
53    /// Header has a bad seal
54    #[error("Header {0:?} has a bad seal")]
55    HeaderBadSeal(Header::Hash),
56    /// Header is unsealed
57    #[error("Header {0:?} is unsealed")]
58    HeaderUnsealed(Header::Hash),
59    /// Bad reward signature
60    #[error("Bad reward signature on {0:?}")]
61    BadRewardSignature(Header::Hash),
62    /// Missing Subspace justification
63    #[error("Missing Subspace justification")]
64    MissingSubspaceJustification,
65    /// Invalid Subspace justification
66    #[error("Invalid Subspace justification: {0}")]
67    InvalidSubspaceJustification(parity_scale_codec::Error),
68    /// Invalid Subspace justification contents
69    #[error("Invalid Subspace justification contents")]
70    InvalidSubspaceJustificationContents,
71    /// Invalid proof of time
72    #[error("Invalid proof of time")]
73    InvalidProofOfTime,
74    /// Adding block authoring delay to the slot overflows
75    #[error("Future slot of slot {0} overflows")]
76    FutureSlotOverflow(Slot),
77    /// Verification error
78    #[error("Verification error on slot {0:?}: {1:?}")]
79    VerificationError(Slot, subspace_verification::Error),
80}
81
82/// A header which has been checked
83struct CheckedHeader<H> {
84    /// A header which is fully checked, including signature. This is the pre-header accompanied by
85    /// the seal components.
86    ///
87    /// Includes the digest item that encoded the seal.
88    pre_header: H,
89    /// Pre-digest
90    pre_digest: PreDigest<PublicKey>,
91    /// Seal (signature)
92    seal: DigestItem,
93}
94
95/// Subspace verification parameters
96struct VerificationParams<'a, Header>
97where
98    Header: HeaderT + 'a,
99{
100    /// The header being verified.
101    header: Header,
102    /// Parameters for solution verification
103    verify_solution_params: &'a VerifySolutionParams,
104}
105
106/// Options for Subspace block verifier
107pub struct SubspaceVerifierOptions<Client> {
108    /// Substrate client
109    pub client: Arc<Client>,
110    /// Subspace chain constants
111    pub chain_constants: ChainConstants,
112    /// Kzg instance
113    pub kzg: Kzg,
114    /// Telemetry
115    pub telemetry: Option<TelemetryHandle>,
116    /// Context for reward signing
117    pub reward_signing_context: SigningContext,
118    /// Approximate target block number for syncing purposes
119    pub sync_target_block_number: Arc<AtomicU32>,
120    /// Whether this node is authoring blocks
121    pub is_authoring_blocks: bool,
122    /// Proof of time verifier
123    pub pot_verifier: PotVerifier,
124}
125
126/// A verifier for Subspace blocks.
127struct Inner<PosTable, Block, Client>
128where
129    Block: BlockT,
130{
131    client: Arc<Client>,
132    kzg: Kzg,
133    telemetry: Option<TelemetryHandle>,
134    chain_constants: ChainConstants,
135    reward_signing_context: SigningContext,
136    sync_target_block_number: Arc<AtomicU32>,
137    is_authoring_blocks: bool,
138    pot_verifier: PotVerifier,
139    equivocation_mutex: Mutex<()>,
140    _pos_table: PhantomData<PosTable>,
141    _block: PhantomData<Block>,
142}
143
144impl<PosTable, Block, Client> Inner<PosTable, Block, Client>
145where
146    PosTable: Table,
147    Block: BlockT,
148    BlockNumber: From<NumberFor<Block>>,
149    Client: HeaderBackend<Block> + ProvideRuntimeApi<Block> + AuxStore + 'static,
150    Client::Api: BlockBuilderApi<Block> + SubspaceApi<Block, PublicKey>,
151{
152    /// Create new instance
153    fn new(options: SubspaceVerifierOptions<Client>) -> Self {
154        let SubspaceVerifierOptions {
155            client,
156            chain_constants,
157            kzg,
158            telemetry,
159            reward_signing_context,
160            sync_target_block_number,
161            is_authoring_blocks,
162            pot_verifier,
163        } = options;
164
165        Self {
166            client,
167            kzg,
168            telemetry,
169            chain_constants,
170            reward_signing_context,
171            sync_target_block_number,
172            is_authoring_blocks,
173            pot_verifier,
174            equivocation_mutex: Mutex::default(),
175            _pos_table: Default::default(),
176            _block: Default::default(),
177        }
178    }
179
180    /// Determine if full proof of time verification is needed for this block number
181    fn full_pot_verification(&self, block_number: NumberFor<Block>) -> bool {
182        let sync_target_block_number: BlockNumber =
183            self.sync_target_block_number.load(Ordering::Relaxed);
184        let Some(diff) = sync_target_block_number.checked_sub(BlockNumber::from(block_number))
185        else {
186            return true;
187        };
188
189        let sample_size = match diff {
190            ..=1_581 => {
191                return true;
192            }
193            1_582..=6_234 => 1_581,
194            6_235..=63_240 => 3_162 * (diff - 3_162) / (diff - 1),
195            63_241..=3_162_000 => 3_162,
196            _ => diff / 1_000,
197        };
198
199        let n = rand::rng().random_range(0..=diff);
200
201        n < sample_size
202    }
203
204    /// Check a header has been signed correctly and whether solution and PoT justification are
205    /// correct. If successful, returns the pre-header and the digest item containing the seal.
206    ///
207    /// The seal must be the last digest. Otherwise, the whole header is considered unsigned. This
208    /// is required for security and must not be changed.
209    ///
210    /// The returned seal digest item will always return `Some` when used with `as_subspace_seal`.
211    fn check_header(
212        &self,
213        params: VerificationParams<'_, Block::Header>,
214        subspace_digest_items: SubspaceDigestItems<PublicKey>,
215        full_pot_verification: bool,
216        justifications: &Option<Justifications>,
217    ) -> Result<CheckedHeader<Block::Header>, VerificationError<Block::Header>> {
218        let VerificationParams {
219            mut header,
220            verify_solution_params,
221        } = params;
222
223        let pre_digest = subspace_digest_items.pre_digest;
224        let slot = pre_digest.slot();
225
226        let seal = header
227            .digest_mut()
228            .pop()
229            .ok_or_else(|| VerificationError::HeaderUnsealed(header.hash()))?;
230
231        let signature = seal
232            .as_subspace_seal()
233            .ok_or_else(|| VerificationError::HeaderBadSeal(header.hash()))?;
234
235        // The pre-hash of the header doesn't include the seal and that's what we sign
236        let pre_hash = header.hash();
237
238        // With justifications we can verify PoT checkpoints quickly and efficiently, the only check
239        // that will remain is to ensure that seed and number of iterations (inputs) is correct
240        // during block import.
241        {
242            let Some(subspace_justification) = justifications
243                .as_ref()
244                .and_then(|justifications| {
245                    justifications
246                        .iter()
247                        .find_map(SubspaceJustification::try_from_justification)
248                })
249                .transpose()
250                .map_err(VerificationError::InvalidSubspaceJustification)?
251            else {
252                return Err(VerificationError::MissingSubspaceJustification);
253            };
254
255            let SubspaceJustification::PotCheckpoints { seed, checkpoints } =
256                subspace_justification;
257
258            // Last checkpoint must be our future proof of time, this is how we anchor the rest of
259            // checks together
260            if checkpoints.last().map(|checkpoints| checkpoints.output())
261                != Some(pre_digest.pot_info().future_proof_of_time())
262            {
263                return Err(VerificationError::InvalidSubspaceJustificationContents);
264            }
265
266            let future_slot = Slot::from(
267                slot.checked_add(*self.chain_constants.block_authoring_delay())
268                    .ok_or(VerificationError::FutureSlotOverflow(slot))?,
269            );
270            let first_slot_to_check = Slot::from(
271                future_slot
272                    .checked_sub(checkpoints.len() as u64 - 1)
273                    .ok_or(VerificationError::InvalidProofOfTime)?,
274            );
275            let slot_iterations = subspace_digest_items
276                .pot_parameters_change
277                .as_ref()
278                .and_then(|parameters_change| {
279                    (parameters_change.slot <= first_slot_to_check)
280                        .then_some(parameters_change.slot_iterations)
281                })
282                .unwrap_or(subspace_digest_items.pot_slot_iterations);
283
284            let mut pot_input = PotNextSlotInput {
285                slot: first_slot_to_check,
286                slot_iterations,
287                seed,
288            };
289            // Collect all the data we will use for verification so we can process it in parallel
290            let checkpoints_verification_input = iter::once((
291                pot_input,
292                *checkpoints
293                    .first()
294                    .expect("Not empty, contents was checked above; qed"),
295            ));
296            let checkpoints_verification_input = checkpoints_verification_input
297                .chain(checkpoints.windows(2).map(|checkpoints_pair| {
298                    pot_input = PotNextSlotInput::derive(
299                        pot_input.slot_iterations,
300                        pot_input.slot,
301                        checkpoints_pair[0].output(),
302                        &subspace_digest_items.pot_parameters_change,
303                    );
304
305                    (pot_input, checkpoints_pair[1])
306                }))
307                .collect::<Vec<_>>();
308
309            // All checkpoints must be valid, at least according to the seed included in
310            // justifications, search for the first error
311            let pot_verifier = &self.pot_verifier;
312            checkpoints_verification_input
313                .into_par_iter()
314                .find_map_first(|(pot_input, checkpoints)| {
315                    if full_pot_verification {
316                        // Try to find invalid checkpoints
317                        if !pot_verifier.verify_checkpoints(
318                            pot_input.seed,
319                            pot_input.slot_iterations,
320                            &checkpoints,
321                        ) {
322                            return Some(VerificationError::InvalidProofOfTime);
323                        }
324                    } else {
325                        // We inject verified checkpoints in order to avoid full proving when votes
326                        // included in the block will inevitably be verified during block execution
327                        pot_verifier.inject_verified_checkpoints(
328                            pot_input.seed,
329                            pot_input.slot_iterations,
330                            checkpoints,
331                        );
332                    }
333
334                    // We search for errors
335                    None
336                })
337                .map_or(Ok(()), Err)?;
338        }
339
340        // Verify that block is signed properly
341        if check_reward_signature(
342            pre_hash.as_ref(),
343            &signature,
344            &pre_digest.solution().public_key,
345            &self.reward_signing_context,
346        )
347        .is_err()
348        {
349            return Err(VerificationError::BadRewardSignature(pre_hash));
350        }
351
352        // Verify that solution is valid
353        verify_solution::<PosTable, _>(
354            pre_digest.solution(),
355            slot.into(),
356            verify_solution_params,
357            &self.kzg,
358        )
359        .map_err(|error| VerificationError::VerificationError(slot, error))?;
360
361        Ok(CheckedHeader {
362            pre_header: header,
363            pre_digest,
364            seal,
365        })
366    }
367
368    async fn check_and_report_equivocation(
369        &self,
370        slot_now: Slot,
371        slot: Slot,
372        header: &Block::Header,
373        author: &PublicKey,
374        origin: &BlockOrigin,
375    ) -> Result<(), String> {
376        // don't report any equivocations during initial sync
377        // as they are most likely stale.
378        if *origin == BlockOrigin::NetworkInitialSync {
379            return Ok(());
380        }
381
382        // Equivocation verification uses `AuxStore` in a way that is not safe from concurrency,
383        // this lock ensures that we process one header at a time
384        let _guard = self.equivocation_mutex.lock().await;
385
386        // check if authorship of this header is an equivocation and return a proof if so.
387        let equivocation_proof =
388            match check_equivocation(&*self.client, slot_now, slot, header, author)
389                .map_err(|error| error.to_string())?
390            {
391                Some(proof) => proof,
392                None => return Ok(()),
393            };
394
395        info!(
396            "Slot author {:?} is equivocating at slot {} with headers {:?} and {:?}",
397            author,
398            slot,
399            equivocation_proof.first_header.hash(),
400            equivocation_proof.second_header.hash(),
401        );
402
403        if self.is_authoring_blocks {
404            // TODO: Handle equivocation
405        } else {
406            info!("Not submitting equivocation report because node is not authoring blocks");
407        }
408
409        Ok(())
410    }
411
412    async fn verify(
413        &self,
414        mut block: BlockImportParams<Block>,
415    ) -> Result<BlockImportParams<Block>, String> {
416        trace!(
417            origin = ?block.origin,
418            header = ?block.header,
419            justifications = ?block.justifications,
420            body = ?block.body,
421            "Verifying",
422        );
423
424        let best_number = self.client.info().best_number;
425        // Reject block below archiving point, but only if we received it from the network
426        if *block.header.number() + self.chain_constants.confirmation_depth_k().into() < best_number
427            && matches!(block.origin, BlockOrigin::NetworkBroadcast)
428        {
429            debug!(
430                header = ?block.header,
431                %best_number,
432                "Rejecting block below archiving point"
433            );
434
435            return Err(format!(
436                "Rejecting block #{} below archiving point",
437                block.header.number()
438            ));
439        }
440
441        let hash = block.header.hash();
442
443        debug!(
444            "We have {:?} logs in this header",
445            block.header.digest().logs().len()
446        );
447
448        let subspace_digest_items =
449            extract_subspace_digest_items::<Block::Header, PublicKey>(&block.header)?;
450
451        let full_pot_verification = self.full_pot_verification(*block.header.number());
452
453        // Stateless header verification only. This means only check that header contains required
454        // contents, correct signature and valid Proof-of-Space, but because previous block is not
455        // guaranteed to be imported at this point, it is not possible to verify
456        // Proof-of-Archival-Storage. In order to verify PoAS randomness and solution range
457        // from the header are checked against expected correct values during block import as well
458        // as whether piece in the header corresponds to the actual archival history of the
459        // blockchain.
460        let checked_header = self
461            .check_header(
462                VerificationParams {
463                    header: block.header.clone(),
464                    verify_solution_params: &VerifySolutionParams {
465                        proof_of_time: subspace_digest_items.pre_digest.pot_info().proof_of_time(),
466                        solution_range: subspace_digest_items.solution_range,
467                        piece_check_params: None,
468                    },
469                },
470                subspace_digest_items,
471                full_pot_verification,
472                &block.justifications,
473            )
474            .map_err(|error| error.to_string())?;
475
476        let CheckedHeader {
477            pre_header,
478            pre_digest,
479            seal,
480        } = checked_header;
481
482        let slot = pre_digest.slot();
483        // Estimate what the "current" slot is according to sync target since we don't have other
484        // way to know it
485        let diff_in_blocks = self
486            .sync_target_block_number
487            .load(Ordering::Relaxed)
488            .saturating_sub(BlockNumber::from(*pre_header.number()));
489        let slot_now = if diff_in_blocks > 0 {
490            slot.saturating_add(
491                u64::from(diff_in_blocks) * self.chain_constants.slot_probability().1
492                    / self.chain_constants.slot_probability().0,
493            )
494        } else {
495            slot
496        };
497
498        // the header is valid but let's check if there was something else already proposed at the
499        // same slot by the given author. if there was, we will report the equivocation to the
500        // runtime.
501        if let Err(error) = self
502            .check_and_report_equivocation(
503                slot_now,
504                slot,
505                &block.header,
506                &pre_digest.solution().public_key,
507                &block.origin,
508            )
509            .await
510        {
511            warn!(
512                %error,
513                "Error checking/reporting Subspace equivocation"
514            );
515        }
516
517        trace!(?pre_header, "Checked header; importing");
518        telemetry!(
519            self.telemetry;
520            CONSENSUS_TRACE;
521            "subspace.checked_and_importing";
522            "pre_header" => ?pre_header,
523        );
524
525        block.header = pre_header;
526        block.post_digests.push(seal);
527        block.post_hash = Some(hash);
528
529        Ok(block)
530    }
531}
532
533/// A verifier for Subspace blocks.
534pub struct SubspaceVerifier<PosTable, Block, Client>
535where
536    Block: BlockT,
537{
538    inner: Arc<Inner<PosTable, Block, Client>>,
539}
540
541impl<PosTable, Block, Client> SubspaceVerifier<PosTable, Block, Client>
542where
543    PosTable: Table,
544    Block: BlockT,
545    BlockNumber: From<NumberFor<Block>>,
546    Client: HeaderBackend<Block> + ProvideRuntimeApi<Block> + AuxStore + 'static,
547    Client::Api: BlockBuilderApi<Block> + SubspaceApi<Block, PublicKey>,
548{
549    /// Create new instance
550    pub fn new(options: SubspaceVerifierOptions<Client>) -> Self {
551        Self {
552            inner: Arc::new(Inner::new(options)),
553        }
554    }
555}
556
557#[async_trait::async_trait]
558impl<PosTable, Block, Client> Verifier<Block> for SubspaceVerifier<PosTable, Block, Client>
559where
560    PosTable: Table,
561    Block: BlockT,
562    BlockNumber: From<NumberFor<Block>>,
563    Client: HeaderBackend<Block> + ProvideRuntimeApi<Block> + AuxStore + 'static,
564    Client::Api: BlockBuilderApi<Block> + SubspaceApi<Block, PublicKey>,
565{
566    fn verification_concurrency(&self) -> NonZeroUsize {
567        available_parallelism().unwrap_or(NonZeroUsize::new(1).expect("Not zero; qed"))
568    }
569
570    async fn verify(
571        &self,
572        block: BlockImportParams<Block>,
573    ) -> Result<BlockImportParams<Block>, String> {
574        let inner = Arc::clone(&self.inner);
575        tokio::task::spawn_blocking(move || Handle::current().block_on(inner.verify(block)))
576            .await
577            .map_err(|error| format!("Failed to join block verification task: {error}"))?
578    }
579}