Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add sanity_check implementation for block headers #5863

Merged
merged 2 commits into from
Dec 27, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions crates/primitives/src/header.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,15 @@ use std::{
ops::{Deref, DerefMut},
};

/// Errors that can occur during header sanity checks.
#[derive(Debug, PartialEq)]
pub enum HeaderError {
/// Represents an error when the block difficulty is too large.
LargeDifficulty,
/// Represents an error when the block extradata is too large.
LargeExtraData,
}

/// Block header
#[main_codec]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
Expand Down Expand Up @@ -117,6 +126,44 @@ impl Default for Header {
}

impl Header {
/// Performs a sanity check on the extradata field of the header.
///
/// # Errors
///
/// Returns an error if the extradata size is larger than 100 KB.
pub fn ensure_extradata_valid(&self) -> Result<(), HeaderError> {
if self.extra_data.len() > 100 * 1024 {
return Err(HeaderError::LargeExtraData);
}
Ok(())
}

/// Performs a sanity check on the block difficulty field of the header.
///
/// # Errors
///
/// Returns an error if the block difficulty exceeds 80 bits.
pub fn ensure_difficulty_valid(&self) -> Result<(), HeaderError> {
if self.difficulty.bit_len() > 80 {
return Err(HeaderError::LargeDifficulty);
}
Ok(())
}

/// Performs combined sanity checks on multiple header fields.
///
/// This method combines checks for block difficulty and extradata sizes.
///
/// # Errors
///
/// Returns an error if either the block difficulty exceeds 80 bits
/// or if the extradata size is larger than 100 KB.
pub fn ensure_well_formed(&self) -> Result<(), HeaderError> {
self.ensure_difficulty_valid()?;
self.ensure_extradata_valid()?;
Ok(())
}

/// Returns the parent block's number and hash
pub fn parent_num_hash(&self) -> BlockNumHash {
BlockNumHash { number: self.number.saturating_sub(1), hash: self.parent_hash }
Expand Down
Loading