Skip to main content

ab_core_primitives/
block.rs

1//! Block-related primitives
2
3pub mod body;
4pub mod header;
5#[cfg(feature = "alloc")]
6pub mod owned;
7
8use crate::block::body::{
9    BeaconChainBody, BlockBody, GenericBlockBody, IntermediateShardBody, LeafShardBlocksInfo,
10    LeafShardBody,
11};
12use crate::block::header::{
13    BeaconChainHeader, BlockHeader, GenericBlockHeader, IntermediateShardHeader, LeafShardHeader,
14};
15#[cfg(feature = "alloc")]
16use crate::block::owned::{
17    GenericOwnedBlock, OwnedBeaconChainBlock, OwnedBlock, OwnedIntermediateShardBlock,
18    OwnedLeafShardBlock,
19};
20use crate::hashes::Blake3Hash;
21use crate::shard::{RealShardKind, ShardIndex};
22use crate::solutions::SolutionRange;
23#[cfg(feature = "serde")]
24use ::serde::{Deserialize, Serialize};
25use ab_io_type::alignment::Alignment;
26use ab_io_type::trivial_type::TrivialType;
27use core::fmt;
28use core::iter::Step;
29use derive_more::{
30    Add, AddAssign, AsMut, AsRef, Deref, DerefMut, Display, From, Into, Sub, SubAssign,
31};
32#[cfg(feature = "scale-codec")]
33use parity_scale_codec::{Decode, Encode, MaxEncodedLen};
34use transparent_wrapper::TransparentWrapper;
35
36/// Block number
37#[derive(
38    Debug,
39    Display,
40    Default,
41    Copy,
42    Clone,
43    Ord,
44    PartialOrd,
45    Eq,
46    PartialEq,
47    Hash,
48    Add,
49    AddAssign,
50    Sub,
51    SubAssign,
52    TrivialType,
53)]
54#[cfg_attr(feature = "scale-codec", derive(Encode, Decode, MaxEncodedLen))]
55#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
56#[cfg_attr(feature = "serde", serde(transparent))]
57#[repr(C)]
58pub struct BlockNumber(u64);
59
60impl Step for BlockNumber {
61    #[inline(always)]
62    fn steps_between(start: &Self, end: &Self) -> (usize, Option<usize>) {
63        u64::steps_between(&start.0, &end.0)
64    }
65
66    #[inline(always)]
67    fn forward_checked(start: Self, count: usize) -> Option<Self> {
68        u64::forward_checked(start.0, count).map(Self)
69    }
70
71    #[inline(always)]
72    fn forward_overflowing(start: Self, count: usize) -> (Self, bool) {
73        let (n, overflowing) = u64::forward_overflowing(start.0, count);
74        (Self(n), overflowing)
75    }
76
77    #[inline(always)]
78    fn backward_checked(start: Self, count: usize) -> Option<Self> {
79        u64::backward_checked(start.0, count).map(Self)
80    }
81
82    #[inline(always)]
83    fn backward_overflowing(start: Self, count: usize) -> (Self, bool) {
84        let (n, overflowing) = u64::backward_overflowing(start.0, count);
85        (Self(n), overflowing)
86    }
87}
88
89const impl From<u64> for BlockNumber {
90    #[inline(always)]
91    fn from(value: u64) -> Self {
92        Self(value)
93    }
94}
95
96const impl From<BlockNumber> for u64 {
97    #[inline(always)]
98    fn from(value: BlockNumber) -> Self {
99        value.0
100    }
101}
102
103impl BlockNumber {
104    /// Size in bytes
105    pub const SIZE: usize = size_of::<u64>();
106    /// Genesis block number
107    pub const ZERO: BlockNumber = BlockNumber(0);
108    /// First block number
109    pub const ONE: BlockNumber = BlockNumber(1);
110    /// Max block number
111    pub const MAX: BlockNumber = BlockNumber(u64::MAX);
112
113    /// Create block number from bytes
114    #[inline(always)]
115    pub const fn from_bytes(bytes: [u8; Self::SIZE]) -> Self {
116        Self(u64::from_le_bytes(bytes))
117    }
118
119    /// Convert block number to bytes
120    #[inline(always)]
121    pub const fn to_bytes(self) -> [u8; Self::SIZE] {
122        self.0.to_le_bytes()
123    }
124
125    /// Checked addition, returns `None` on overflow
126    #[inline(always)]
127    pub const fn checked_add(self, rhs: Self) -> Option<Self> {
128        if let Some(n) = self.0.checked_add(rhs.0) {
129            Some(Self(n))
130        } else {
131            None
132        }
133    }
134
135    /// Saturating addition
136    #[inline(always)]
137    pub const fn saturating_add(self, rhs: Self) -> Self {
138        Self(self.0.saturating_add(rhs.0))
139    }
140
141    /// Checked subtraction, returns `None` on underflow
142    #[inline(always)]
143    pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
144        if let Some(n) = self.0.checked_sub(rhs.0) {
145            Some(Self(n))
146        } else {
147            None
148        }
149    }
150
151    /// Saturating subtraction
152    #[inline(always)]
153    pub const fn saturating_sub(self, rhs: Self) -> Self {
154        Self(self.0.saturating_sub(rhs.0))
155    }
156}
157
158/// Block timestamp as Unix time in milliseconds
159#[derive(
160    Debug,
161    Display,
162    Default,
163    Copy,
164    Clone,
165    Ord,
166    PartialOrd,
167    Eq,
168    PartialEq,
169    Hash,
170    From,
171    Into,
172    Add,
173    AddAssign,
174    Sub,
175    SubAssign,
176    TrivialType,
177)]
178#[cfg_attr(feature = "scale-codec", derive(Encode, Decode, MaxEncodedLen))]
179#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
180#[cfg_attr(feature = "serde", serde(transparent))]
181#[repr(C)]
182pub struct BlockTimestamp(u64);
183
184impl BlockTimestamp {
185    /// Size in bytes
186    pub const SIZE: usize = size_of::<u64>();
187
188    /// Create a new instance
189    #[inline(always)]
190    pub const fn from_millis(ms: u64) -> Self {
191        Self(ms)
192    }
193
194    /// Get internal representation
195    #[inline(always)]
196    pub const fn as_millis(self) -> u64 {
197        self.0
198    }
199
200    /// Checked addition, returns `None` on overflow
201    #[inline(always)]
202    pub const fn checked_add(self, rhs: Self) -> Option<Self> {
203        if let Some(n) = self.0.checked_add(rhs.0) {
204            Some(Self(n))
205        } else {
206            None
207        }
208    }
209
210    /// Saturating addition
211    #[inline(always)]
212    pub const fn saturating_add(self, rhs: Self) -> Self {
213        Self(self.0.saturating_add(rhs.0))
214    }
215
216    /// Checked subtraction, returns `None` on underflow
217    #[inline(always)]
218    pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
219        if let Some(n) = self.0.checked_sub(rhs.0) {
220            Some(Self(n))
221        } else {
222            None
223        }
224    }
225
226    /// Saturating subtraction
227    #[inline(always)]
228    pub const fn saturating_sub(self, rhs: Self) -> Self {
229        Self(self.0.saturating_sub(rhs.0))
230    }
231}
232
233/// Block root.
234///
235/// This is typically called block hash in other blockchains, but here it represents Merkle Tree
236/// root of the header rather than a single hash of its contents.
237#[derive(
238    Debug,
239    Display,
240    Default,
241    Copy,
242    Clone,
243    Eq,
244    PartialEq,
245    Ord,
246    PartialOrd,
247    Hash,
248    From,
249    Into,
250    AsRef,
251    AsMut,
252    Deref,
253    DerefMut,
254    TrivialType,
255    TransparentWrapper,
256)]
257#[cfg_attr(feature = "scale-codec", derive(Encode, Decode, MaxEncodedLen))]
258#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
259#[cfg_attr(feature = "serde", serde(transparent))]
260#[repr(C)]
261pub struct BlockRoot(Blake3Hash);
262
263impl AsRef<[u8]> for BlockRoot {
264    #[inline(always)]
265    fn as_ref(&self) -> &[u8] {
266        self.0.as_ref()
267    }
268}
269
270impl AsMut<[u8]> for BlockRoot {
271    #[inline(always)]
272    fn as_mut(&mut self) -> &mut [u8] {
273        self.0.as_mut()
274    }
275}
276
277impl BlockRoot {
278    /// Size in bytes
279    pub const SIZE: usize = Blake3Hash::SIZE;
280
281    /// Create a new instance
282    #[inline(always)]
283    pub const fn new(hash: Blake3Hash) -> Self {
284        Self(hash)
285    }
286}
287
288/// Generic block.
289///
290/// Can't be implemented outside of this module, so that code generic over blocks can rely on the
291/// header corresponding to the body, like with concrete blocks.
292pub impl(self) trait GenericBlock<'a>
293where
294    Self: Clone + fmt::Debug + Send + Sync,
295{
296    /// Shard kind
297    const SHARD_KIND: RealShardKind;
298
299    /// Block header type
300    type Header: GenericBlockHeader<'a>;
301    /// Block body type
302    type Body: GenericBlockBody<'a>;
303    /// Owned block
304    #[cfg(feature = "alloc")]
305    type Owned: GenericOwnedBlock<Block<'a> = Self>
306    where
307        Self: 'a;
308
309    /// Get block header
310    fn header(&self) -> &Self::Header;
311
312    /// Get block body
313    fn body(&self) -> &Self::Body;
314
315    /// Turn into an owned version.
316    ///
317    /// # Panics
318    /// Where `usize` is 32-bit, if the body is longer than [`OwnedAlignedBuffer::MAX_CAPACITY`]
319    ///
320    /// [`OwnedAlignedBuffer::MAX_CAPACITY`]: ab_aligned_buffer::OwnedAlignedBuffer::MAX_CAPACITY
321    #[cfg(feature = "alloc")]
322    fn to_owned(self) -> Self::Owned;
323}
324
325/// Block that corresponds to the beacon chain.
326///
327/// Fields can't be modified after creation, so that the header always corresponds to the body,
328/// which constructors ensure.
329#[derive(Debug, Clone)]
330pub struct BeaconChainBlock<'a> {
331    /// Block header
332    pub mut(self) header: BeaconChainHeader<'a>,
333    /// Block body
334    pub mut(self) body: BeaconChainBody<'a>,
335}
336
337impl<'a> BeaconChainBlock<'a> {
338    /// Try to create a new instance from provided bytes.
339    ///
340    /// `bytes` should be 16-bytes aligned.
341    ///
342    /// Checks internal consistency of header, body, and block, but no consensus verification is
343    /// done.
344    ///
345    /// Returns an instance and remaining bytes on success, `None` if too few bytes were given,
346    /// bytes are not properly aligned or input is otherwise invalid.
347    #[inline]
348    pub fn try_from_bytes(bytes: &'a [u8]) -> Option<(Self, &'a [u8])> {
349        if !Alignment::MAX.is_slice_aligned(bytes) {
350            return None;
351        }
352
353        let (header, remainder) = BeaconChainHeader::try_from_bytes(bytes)?;
354        let remainder = align_to_and_ensure_zero_padding(remainder, Alignment::MAX)?;
355        let (body, remainder) = BeaconChainBody::try_from_bytes(remainder)?;
356
357        let block = Self { header, body };
358
359        // Check internal consistency
360        if !block.is_internally_consistent() {
361            return None;
362        }
363
364        Some((block, remainder))
365    }
366
367    /// Check that the header corresponds to the body.
368    ///
369    /// Internal consistency of the header and body is checked by their parsers.
370    #[inline]
371    fn is_internally_consistent(&self) -> bool {
372        // Header roots of intermediate shard blocks are expensive to compute, so they are only
373        // computed once for both the header field and the body root
374        let intermediate_shard_blocks_root = self.body.intermediate_shard_blocks().headers_root();
375
376        // Intermediate shard blocks are always children of the beacon chain: header parsing ensures
377        // that their shard indices are those of intermediate shards
378        self.body
379            .root_with_intermediate_shard_blocks_root(&intermediate_shard_blocks_root)
380            == self.header.result.body_root
381            && *self.header.intermediate_shard_blocks_root() == intermediate_shard_blocks_root
382    }
383
384    /// Create an owned version of this block.
385    ///
386    /// # Panics
387    /// Where `usize` is 32-bit, if the body is longer than [`OwnedAlignedBuffer::MAX_CAPACITY`]
388    ///
389    /// [`OwnedAlignedBuffer::MAX_CAPACITY`]: ab_aligned_buffer::OwnedAlignedBuffer::MAX_CAPACITY
390    #[cfg(feature = "alloc")]
391    #[inline(always)]
392    pub fn to_owned(self) -> OwnedBeaconChainBlock {
393        OwnedBeaconChainBlock::from_block(self)
394    }
395}
396
397impl<'a> GenericBlock<'a> for BeaconChainBlock<'a> {
398    const SHARD_KIND: RealShardKind = RealShardKind::BeaconChain;
399
400    type Header = BeaconChainHeader<'a>;
401    type Body = BeaconChainBody<'a>;
402    #[cfg(feature = "alloc")]
403    type Owned = OwnedBeaconChainBlock;
404
405    #[inline(always)]
406    fn header(&self) -> &Self::Header {
407        &self.header
408    }
409
410    #[inline(always)]
411    fn body(&self) -> &Self::Body {
412        &self.body
413    }
414
415    #[cfg(feature = "alloc")]
416    #[inline(always)]
417    fn to_owned(self) -> Self::Owned {
418        self.to_owned()
419    }
420}
421
422/// Block that corresponds to an intermediate shard.
423///
424/// Fields can't be modified after creation, so that the header always corresponds to the body,
425/// which constructors ensure.
426#[derive(Debug, Clone)]
427pub struct IntermediateShardBlock<'a> {
428    /// Block header
429    pub mut(self) header: IntermediateShardHeader<'a>,
430    /// Block body
431    pub mut(self) body: IntermediateShardBody<'a>,
432}
433
434impl<'a> IntermediateShardBlock<'a> {
435    /// Try to create a new instance from provided bytes.
436    ///
437    /// `bytes` should be 16-bytes aligned.
438    ///
439    /// Checks internal consistency of header, body, and block, but no consensus verification is
440    /// done.
441    ///
442    /// Returns an instance and remaining bytes on success, `None` if too few bytes were given,
443    /// bytes are not properly aligned or input is otherwise invalid.
444    #[inline]
445    pub fn try_from_bytes(bytes: &'a [u8]) -> Option<(Self, &'a [u8])> {
446        if !Alignment::MAX.is_slice_aligned(bytes) {
447            return None;
448        }
449
450        let (header, remainder) = IntermediateShardHeader::try_from_bytes(bytes)?;
451        let remainder = align_to_and_ensure_zero_padding(remainder, Alignment::MAX)?;
452        let (body, remainder) = IntermediateShardBody::try_from_bytes(remainder)?;
453
454        let block = Self { header, body };
455
456        // Check internal consistency
457        if !block.is_internally_consistent() {
458            return None;
459        }
460
461        Some((block, remainder))
462    }
463
464    /// Check that the header corresponds to the body.
465    ///
466    /// Internal consistency of the header and body is checked by their parsers.
467    #[inline]
468    fn is_internally_consistent(&self) -> bool {
469        // Header roots of leaf shard blocks are expensive to compute, so they are only computed
470        // once for both the header field and the body root
471        let leaf_shard_blocks_root = self.body.leaf_shard_blocks().headers_root();
472
473        self.body
474            .root_with_leaf_shard_blocks_root(&leaf_shard_blocks_root)
475            == self.header.result.body_root
476            && *self.header.leaf_shard_blocks_root() == leaf_shard_blocks_root
477            && Self::find_leaf_shard_block_of_another_shard(
478                self.body.leaf_shard_blocks(),
479                self.header.prefix.shard_index,
480            )
481            .is_none()
482    }
483
484    /// Find a leaf shard block that is not a child of the shard with `shard_index`.
485    ///
486    /// Returns the shard index of the first such leaf shard block. The intermediate shard block
487    /// builder uses it too, so it accepts the same leaf shard blocks as the parser.
488    #[inline]
489    fn find_leaf_shard_block_of_another_shard(
490        leaf_shard_blocks: &LeafShardBlocksInfo<'_>,
491        shard_index: ShardIndex,
492    ) -> Option<ShardIndex> {
493        leaf_shard_blocks
494            .iter()
495            .map(|leaf_shard_block| leaf_shard_block.header.prefix.shard_index)
496            .find(|leaf_shard_index| !leaf_shard_index.is_child_of(shard_index))
497    }
498
499    /// Create an owned version of this block.
500    ///
501    /// # Panics
502    /// Where `usize` is 32-bit, if the body is longer than [`OwnedAlignedBuffer::MAX_CAPACITY`]
503    ///
504    /// [`OwnedAlignedBuffer::MAX_CAPACITY`]: ab_aligned_buffer::OwnedAlignedBuffer::MAX_CAPACITY
505    #[cfg(feature = "alloc")]
506    #[inline(always)]
507    pub fn to_owned(self) -> OwnedIntermediateShardBlock {
508        OwnedIntermediateShardBlock::from_block(self)
509    }
510}
511
512impl<'a> GenericBlock<'a> for IntermediateShardBlock<'a> {
513    const SHARD_KIND: RealShardKind = RealShardKind::IntermediateShard;
514
515    type Header = IntermediateShardHeader<'a>;
516    type Body = IntermediateShardBody<'a>;
517    #[cfg(feature = "alloc")]
518    type Owned = OwnedIntermediateShardBlock;
519
520    #[inline(always)]
521    fn header(&self) -> &Self::Header {
522        &self.header
523    }
524
525    #[inline(always)]
526    fn body(&self) -> &Self::Body {
527        &self.body
528    }
529
530    #[cfg(feature = "alloc")]
531    #[inline(always)]
532    fn to_owned(self) -> Self::Owned {
533        self.to_owned()
534    }
535}
536
537/// Block that corresponds to a leaf shard.
538///
539/// Fields can't be modified after creation, so that the header always corresponds to the body,
540/// which constructors ensure.
541#[derive(Debug, Clone)]
542pub struct LeafShardBlock<'a> {
543    /// Block header
544    pub mut(self) header: LeafShardHeader<'a>,
545    /// Block body
546    pub mut(self) body: LeafShardBody<'a>,
547}
548
549impl<'a> LeafShardBlock<'a> {
550    /// Try to create a new instance from provided bytes.
551    ///
552    /// `bytes` should be 16-bytes aligned.
553    ///
554    /// Checks internal consistency of header, body, and block, but no consensus verification is
555    /// done.
556    ///
557    /// Returns an instance and remaining bytes on success, `None` if too few bytes were given,
558    /// bytes are not properly aligned or input is otherwise invalid.
559    #[inline]
560    pub fn try_from_bytes(bytes: &'a [u8]) -> Option<(Self, &'a [u8])> {
561        if !Alignment::MAX.is_slice_aligned(bytes) {
562            return None;
563        }
564
565        let (header, remainder) = LeafShardHeader::try_from_bytes(bytes)?;
566        let remainder = align_to_and_ensure_zero_padding(remainder, Alignment::MAX)?;
567        let (body, remainder) = LeafShardBody::try_from_bytes(remainder)?;
568
569        let block = Self { header, body };
570
571        // Check internal consistency
572        if !block.is_internally_consistent() {
573            return None;
574        }
575
576        Some((block, remainder))
577    }
578
579    /// Check that the header corresponds to the body.
580    ///
581    /// Internal consistency of the header and body is checked by their parsers.
582    #[inline]
583    fn is_internally_consistent(&self) -> bool {
584        self.body.root() == self.header.result.body_root
585    }
586
587    /// Create an owned version of this block.
588    ///
589    /// # Panics
590    /// Where `usize` is 32-bit, if the body is longer than [`OwnedAlignedBuffer::MAX_CAPACITY`]
591    ///
592    /// [`OwnedAlignedBuffer::MAX_CAPACITY`]: ab_aligned_buffer::OwnedAlignedBuffer::MAX_CAPACITY
593    #[cfg(feature = "alloc")]
594    #[inline(always)]
595    pub fn to_owned(self) -> OwnedLeafShardBlock {
596        OwnedLeafShardBlock::from_block(self)
597    }
598}
599
600impl<'a> GenericBlock<'a> for LeafShardBlock<'a> {
601    const SHARD_KIND: RealShardKind = RealShardKind::LeafShard;
602
603    type Header = LeafShardHeader<'a>;
604    type Body = LeafShardBody<'a>;
605    #[cfg(feature = "alloc")]
606    type Owned = OwnedLeafShardBlock;
607
608    #[inline(always)]
609    fn header(&self) -> &Self::Header {
610        &self.header
611    }
612
613    #[inline(always)]
614    fn body(&self) -> &Self::Body {
615        &self.body
616    }
617
618    #[cfg(feature = "alloc")]
619    #[inline(always)]
620    fn to_owned(self) -> Self::Owned {
621        self.to_owned()
622    }
623}
624
625/// Block that contains [`BlockHeader`] and [`BlockBody`]
626#[derive(Debug, Clone, From)]
627pub enum Block<'a> {
628    /// Block corresponds to the beacon chain
629    BeaconChain(BeaconChainBlock<'a>),
630    /// Block corresponds to an intermediate shard
631    IntermediateShard(IntermediateShardBlock<'a>),
632    /// Block corresponds to a leaf shard
633    LeafShard(LeafShardBlock<'a>),
634}
635
636impl<'a> Block<'a> {
637    /// Try to create a new instance from provided bytes.
638    ///
639    /// `bytes` should be 16-byte aligned. The shard kind of the block is that of the shard index in
640    /// the prefix of its header, see [`BlockHeader::shard_kind_from_bytes()`].
641    ///
642    /// Checks internal consistency of header, body, and block, but no consensus verification is
643    /// done.
644    ///
645    /// Returns an instance and remaining bytes on success, `None` if too few bytes were given,
646    /// bytes are not properly aligned or input is otherwise invalid.
647    #[inline]
648    pub fn try_from_bytes(bytes: &'a [u8]) -> Option<(Self, &'a [u8])> {
649        match BlockHeader::shard_kind_from_bytes(bytes)? {
650            RealShardKind::BeaconChain => {
651                let (block_header, remainder) = BeaconChainBlock::try_from_bytes(bytes)?;
652                Some((Self::BeaconChain(block_header), remainder))
653            }
654            RealShardKind::IntermediateShard => {
655                let (block_header, remainder) = IntermediateShardBlock::try_from_bytes(bytes)?;
656                Some((Self::IntermediateShard(block_header), remainder))
657            }
658            RealShardKind::LeafShard => {
659                let (block_header, remainder) = LeafShardBlock::try_from_bytes(bytes)?;
660                Some((Self::LeafShard(block_header), remainder))
661            }
662        }
663    }
664
665    /// Block header
666    #[inline(always)]
667    pub fn header(&self) -> BlockHeader<'a> {
668        match self {
669            Self::BeaconChain(block) => BlockHeader::BeaconChain(block.header.clone()),
670            Self::IntermediateShard(block) => BlockHeader::IntermediateShard(block.header.clone()),
671            Self::LeafShard(block) => BlockHeader::LeafShard(block.header.clone()),
672        }
673    }
674
675    /// Block body
676    #[inline(always)]
677    pub fn body(&self) -> BlockBody<'a> {
678        match self {
679            Self::BeaconChain(block) => BlockBody::BeaconChain(block.body),
680            Self::IntermediateShard(block) => BlockBody::IntermediateShard(block.body),
681            Self::LeafShard(block) => BlockBody::LeafShard(block.body),
682        }
683    }
684
685    /// Create an owned version of this block.
686    ///
687    /// # Panics
688    /// Where `usize` is 32-bit, if the body is longer than [`OwnedAlignedBuffer::MAX_CAPACITY`]
689    ///
690    /// [`OwnedAlignedBuffer::MAX_CAPACITY`]: ab_aligned_buffer::OwnedAlignedBuffer::MAX_CAPACITY
691    #[cfg(feature = "alloc")]
692    #[inline(always)]
693    pub fn to_owned(self) -> OwnedBlock {
694        match self {
695            Self::BeaconChain(block) => block.to_owned().into(),
696            Self::IntermediateShard(block) => block.to_owned().into(),
697            Self::LeafShard(block) => block.to_owned().into(),
698        }
699    }
700}
701
702/// BlockWeight type for fork choice rule.
703///
704/// The smaller the solution range is, the heavier is the block.
705#[derive(
706    Debug,
707    Display,
708    Default,
709    Copy,
710    Clone,
711    Ord,
712    PartialOrd,
713    Eq,
714    PartialEq,
715    Hash,
716    Add,
717    AddAssign,
718    Sub,
719    SubAssign,
720)]
721#[cfg_attr(feature = "scale-codec", derive(Encode, Decode, MaxEncodedLen))]
722#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
723#[repr(C)]
724pub struct BlockWeight(u128);
725
726const impl From<u128> for BlockWeight {
727    #[inline(always)]
728    fn from(value: u128) -> Self {
729        Self(value)
730    }
731}
732
733const impl From<BlockWeight> for u128 {
734    #[inline(always)]
735    fn from(value: BlockWeight) -> Self {
736        value.0
737    }
738}
739
740impl BlockWeight {
741    /// Size in bytes
742    pub const SIZE: usize = size_of::<u128>();
743    /// Zero block weight
744    pub const ZERO: BlockWeight = BlockWeight(0);
745    /// Max block wright
746    pub const MAX: BlockWeight = BlockWeight(u128::MAX);
747
748    /// Derive block weight from provided solution range
749    pub const fn from_solution_range(solution_range: SolutionRange) -> Self {
750        Self::from(u128::from(
751            u64::from(SolutionRange::MAX) - u64::from(solution_range),
752        ))
753    }
754}
755
756/// Aligns bytes to `alignment` and ensures that all padding bytes (if any) are zero.
757///
758/// Returns `None` if there are fewer bytes than padding or padding is not zero.
759fn align_to_and_ensure_zero_padding(bytes: &[u8], alignment: Alignment) -> Option<&[u8]> {
760    let padding_len = bytes.as_ptr().align_offset(usize::from(alignment.get()));
761    let (padding, remainder) = bytes.split_at_checked(padding_len)?;
762
763    // Padding must be zero
764    if padding.iter().any(|&byte| byte != 0) {
765        return None;
766    }
767
768    Some(remainder)
769}