Skip to main content

ab_core_primitives/block/
header.rs

1//! Block header primitives
2
3#[cfg(feature = "alloc")]
4pub mod owned;
5
6#[cfg(feature = "alloc")]
7use crate::block::header::owned::{
8    GenericOwnedBlockHeader, OwnedBeaconChainHeader, OwnedBlockHeader,
9    OwnedIntermediateShardHeader, OwnedLeafShardHeader,
10};
11use crate::block::{BlockNumber, BlockRoot, BlockTimestamp};
12use crate::ed25519::{Ed25519PublicKey, Ed25519Signature};
13use crate::hashes::Blake3Hash;
14use crate::pot::{PotOutput, PotParametersChange, SlotNumber};
15use crate::segments::SuperSegmentRoot;
16use crate::shard::{NumShards, NumShardsUnchecked, RealShardKind, ShardIndex, ShardKind};
17use crate::solutions::{Solution, SolutionRange};
18use crate::trees::{
19    BeaconChainHeaderMerkleTree, IntermediateShardHeaderMerkleTree, LeafShardHeaderMerkleTree,
20};
21#[cfg(feature = "alloc")]
22use ab_aligned_buffer::SharedAlignedBuffer;
23use ab_blake3::{BLOCK_LEN, single_block_hash, single_chunk_hash};
24use ab_io_type::trivial_type::TrivialType;
25use ab_io_type::unaligned::Unaligned;
26use blake3::CHUNK_LEN;
27use core::fmt;
28use core::num::NonZeroU32;
29use core::ops::Deref;
30use derive_more::From;
31#[cfg(feature = "scale-codec")]
32use parity_scale_codec::{Decode, Encode, MaxEncodedLen};
33#[cfg(feature = "serde")]
34use serde::{Deserialize, Serialize};
35use yoke::Yokeable;
36
37/// Generic block header
38pub trait GenericBlockHeader<'a>
39where
40    Self: Clone
41        + fmt::Debug
42        + Deref<Target = SharedBlockHeader<'a>>
43        + Into<BlockHeader<'a>>
44        + Send
45        + Sync,
46{
47    /// Shard kind
48    const SHARD_KIND: RealShardKind;
49
50    /// Owned block header
51    #[cfg(feature = "alloc")]
52    type Owned: GenericOwnedBlockHeader<Header<'a> = Self>
53    where
54        Self: 'a;
55
56    /// Turn into an owned version
57    #[cfg(feature = "alloc")]
58    fn to_owned(self) -> Self::Owned;
59
60    /// Compute block root out of this header.
61    ///
62    /// Block root is a Merkle Tree Root. The leaves are derived from individual fields in
63    /// [`SharedBlockHeader`] and other fields of this enum in the declaration order.
64    ///
65    /// Note that this method does a bunch of hashing and if root is often needed, should be cached.
66    fn root(&self) -> impl Deref<Target = BlockRoot> + Send + Sync;
67
68    /// Hash of the block before seal is applied to it
69    fn pre_seal_hash(&self) -> Blake3Hash;
70}
71
72/// Block header prefix.
73///
74/// The prefix contains generic information known about the block before block creation starts.
75#[derive(Debug, Copy, Clone, Eq, PartialEq, TrivialType)]
76#[cfg_attr(feature = "scale-codec", derive(Encode, Decode, MaxEncodedLen))]
77#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
78#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
79#[repr(C)]
80pub struct BlockHeaderPrefix {
81    /// Block number
82    pub number: BlockNumber,
83    /// Shard index
84    pub shard_index: ShardIndex,
85    /// Padding for data structure alignment, contents must be all zeroes
86    pub padding_0: [u8; 4],
87    /// Block timestamp
88    pub timestamp: BlockTimestamp,
89    /// Root of the parent block
90    pub parent_root: BlockRoot,
91    /// MMR root of all block roots, including `parent_root`
92    // TODO: New type?
93    pub mmr_root: Blake3Hash,
94}
95
96impl BlockHeaderPrefix {
97    /// Hash of the block header prefix, part of the eventual block root
98    pub fn hash(&self) -> Blake3Hash {
99        const {
100            assert!(size_of::<Self>() <= CHUNK_LEN);
101        }
102        Blake3Hash::new(
103            single_chunk_hash(self.as_bytes())
104                .expect("Less than a single chunk worth of bytes; qed"),
105        )
106    }
107}
108
109/// Consensus information in the block header
110#[derive(Debug, Copy, Clone, Eq, PartialEq, TrivialType)]
111#[cfg_attr(feature = "scale-codec", derive(Encode, Decode, MaxEncodedLen))]
112#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
113#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
114#[repr(C)]
115pub struct BlockHeaderConsensusInfo {
116    /// Slot number
117    pub slot: SlotNumber,
118    /// Proof of time for this slot
119    pub proof_of_time: PotOutput,
120    /// Future proof of time
121    pub future_proof_of_time: PotOutput,
122    /// Solution
123    pub solution: Solution,
124}
125
126impl BlockHeaderConsensusInfo {
127    /// Hash of the consensus info, part of the eventual block root
128    pub fn hash(&self) -> Blake3Hash {
129        Blake3Hash::from(blake3::hash(self.as_bytes()))
130    }
131}
132
133/// Beacon chain info
134#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, TrivialType)]
135#[cfg_attr(feature = "scale-codec", derive(Encode, Decode, MaxEncodedLen))]
136#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
137#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
138#[repr(C)]
139pub struct BlockHeaderBeaconChainInfo {
140    /// Beacon chain block number
141    pub number: BlockNumber,
142    /// Beacon chain block root
143    pub root: BlockRoot,
144}
145
146impl BlockHeaderBeaconChainInfo {
147    /// Hash of the beacon chain info, part of the eventual block root
148    pub fn hash(&self) -> Blake3Hash {
149        const {
150            assert!(size_of::<Self>() <= BLOCK_LEN);
151        }
152        Blake3Hash::new(
153            single_block_hash(self.as_bytes())
154                .expect("Less than a single block worth of bytes; qed"),
155        )
156    }
157}
158
159/// Consensus parameters (on the beacon chain)
160#[derive(Debug, Copy, Clone, Eq, PartialEq)]
161#[cfg_attr(feature = "scale-codec", derive(Encode, Decode, MaxEncodedLen))]
162#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
163#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
164pub struct BlockHeaderFixedConsensusParameters {
165    /// Solution range for this block/interval
166    pub solution_range: SolutionRange,
167    /// The number of iterations for proof of time per slot.
168    ///
169    /// Corresponds to the slot that is right after the parent block's slot.
170    /// It can change before the slot of this block (see [`PotParametersChange`]).
171    pub slot_iterations: NonZeroU32,
172    /// Number of shards in the network
173    pub num_shards: NumShards,
174}
175
176impl BlockHeaderFixedConsensusParameters {
177    /// Create an instance from provided bytes.
178    ///
179    /// `bytes` do not need to be aligned.
180    ///
181    /// The layout is as follows:
182    /// * solution range: SolutionRange as unaligned bytes
183    /// * PoT slot iterations: NonZeroU32 as unaligned little-endian bytes
184    /// * number of shards: NumShards as unaligned little-endian bytes
185    ///
186    /// Returns an instance and remaining bytes on success.
187    #[inline]
188    pub fn try_from_bytes(mut bytes: &[u8]) -> Option<(Self, &[u8])> {
189        let solution_range;
190        (solution_range, bytes) = bytes.split_first_chunk::<{ size_of::<SolutionRange>() }>()?;
191        let solution_range = SolutionRange::from_bytes(*solution_range);
192
193        let slot_iterations;
194        (slot_iterations, bytes) = bytes.split_first_chunk::<{ size_of::<u32>() }>()?;
195        let slot_iterations = NonZeroU32::new(u32::from_le_bytes(*slot_iterations))?;
196        let num_shards;
197        (num_shards, bytes) = Unaligned::<NumShardsUnchecked>::from_bytes(bytes)?;
198        let num_shards = NumShards::try_from(num_shards.as_inner()).ok()?;
199
200        Some((
201            Self {
202                solution_range,
203                slot_iterations,
204                num_shards,
205            },
206            bytes,
207        ))
208    }
209}
210
211/// A mirror of [`PotParametersChange`] for block header purposes.
212///
213/// Use [`From`] or [`Into`] for converting into [`PotParametersChange`] before use.
214#[derive(Debug, Copy, Clone, Eq, PartialEq)]
215#[repr(C, packed)]
216pub struct BlockHeaderPotParametersChange {
217    // TODO: Reduce this to `u16` or even `u8` since it is always an offset relatively to current
218    //  block's slot number
219    /// At which slot change of parameters takes effect
220    slot: SlotNumber,
221    /// New number of slot iterations
222    slot_iterations: NonZeroU32,
223    /// Entropy that should be injected at this time
224    entropy: Blake3Hash,
225}
226
227impl From<BlockHeaderPotParametersChange> for PotParametersChange {
228    #[inline(always)]
229    fn from(value: BlockHeaderPotParametersChange) -> Self {
230        let BlockHeaderPotParametersChange {
231            slot,
232            slot_iterations,
233            entropy,
234        } = value;
235
236        PotParametersChange {
237            slot,
238            slot_iterations,
239            entropy,
240        }
241    }
242}
243
244impl From<PotParametersChange> for BlockHeaderPotParametersChange {
245    #[inline(always)]
246    fn from(value: PotParametersChange) -> Self {
247        let PotParametersChange {
248            slot,
249            slot_iterations,
250            entropy,
251        } = value;
252
253        BlockHeaderPotParametersChange {
254            slot,
255            slot_iterations,
256            entropy,
257        }
258    }
259}
260
261impl BlockHeaderPotParametersChange {
262    /// Get instance reference from provided bytes.
263    ///
264    /// `bytes` do not need to be aligned.
265    ///
266    /// The layout is as follows:
267    /// * slot number: SlotNumber as unaligned bytes
268    /// * slot iterations: NonZeroU32 as unaligned little-endian bytes
269    /// * entropy: Blake3Hash
270    ///
271    /// Returns an instance and remaining bytes on success.
272    #[inline]
273    pub fn try_from_bytes(mut bytes: &[u8]) -> Option<(&Self, &[u8])> {
274        let pot_parameters_change_ptr = bytes.as_ptr().cast::<Self>();
275
276        (_, bytes) = bytes.split_first_chunk::<{ size_of::<SlotNumber>() }>()?;
277
278        let slot_iterations;
279        (slot_iterations, bytes) = bytes.split_first_chunk::<{ size_of::<u32>() }>()?;
280        if *slot_iterations == [0, 0, 0, 0] {
281            return None;
282        }
283        (_, bytes) = bytes.split_first_chunk::<{ size_of::<Blake3Hash>() }>()?;
284
285        // SAFETY: Not null, packed, bit pattern for `NonZeroU32` checked above
286        let pot_parameters_change = unsafe { pot_parameters_change_ptr.as_ref_unchecked() };
287
288        Some((pot_parameters_change, bytes))
289    }
290}
291
292/// Owned version of [`BlockHeaderConsensusParameters`]
293#[derive(Debug, Copy, Clone, Eq, PartialEq)]
294pub struct OwnedBlockHeaderConsensusParameters {
295    /// Consensus parameters that are always present
296    pub fixed_parameters: BlockHeaderFixedConsensusParameters,
297    /// Super segment root
298    pub super_segment_root: Option<SuperSegmentRoot>,
299    /// Solution range for the next block/interval (if any)
300    pub next_solution_range: Option<SolutionRange>,
301    /// Change of parameters to apply to the proof of time chain (if any)
302    pub pot_parameters_change: Option<BlockHeaderPotParametersChange>,
303}
304
305impl From<&BlockHeaderConsensusParameters<'_>> for OwnedBlockHeaderConsensusParameters {
306    #[inline]
307    fn from(value: &BlockHeaderConsensusParameters<'_>) -> Self {
308        let BlockHeaderConsensusParameters {
309            fixed_parameters,
310            super_segment_root,
311            next_solution_range,
312            pot_parameters_change,
313            bytes: _,
314        } = value;
315
316        Self {
317            fixed_parameters: *fixed_parameters,
318            super_segment_root: super_segment_root.copied(),
319            next_solution_range: *next_solution_range,
320            pot_parameters_change: pot_parameters_change.copied(),
321        }
322    }
323}
324
325/// Consensus parameters (on the beacon chain)
326#[derive(Debug, Copy, Clone, Eq, PartialEq)]
327#[expect(
328    clippy::partial_pub_fields,
329    reason = "Intentionally exposing decoded fields and hiding the bytes they were decoded from"
330)]
331pub struct BlockHeaderConsensusParameters<'a> {
332    /// Consensus parameters that are always present
333    pub mut(self) fixed_parameters: BlockHeaderFixedConsensusParameters,
334    /// Super segment root
335    pub mut(self) super_segment_root: Option<&'a SuperSegmentRoot>,
336    /// Solution range for the next block/interval (if any)
337    pub mut(self) next_solution_range: Option<SolutionRange>,
338    /// Change of parameters to apply to the proof of time chain (if any)
339    pub mut(self) pot_parameters_change: Option<&'a BlockHeaderPotParametersChange>,
340    /// Encoded consensus parameters the fields above were parsed from
341    bytes: &'a [u8],
342}
343
344impl<'a> BlockHeaderConsensusParameters<'a> {
345    /// Max size of the allocation necessary for this data structure
346    pub const MAX_SIZE: u32 =
347        // Solution range of fixed parameters
348        <SolutionRange as TrivialType>::SIZE
349        // PoT slot iterations of fixed parameters
350        + u32::SIZE
351        // Number of shards of fixed parameters
352        + <NumShardsUnchecked as TrivialType>::SIZE
353        // Bitflags
354        + u8::SIZE
355        // Super segment root
356        + <SuperSegmentRoot as TrivialType>::SIZE
357        // Next solution range
358        + <SolutionRange as TrivialType>::SIZE
359        // PoT parameters change
360        + size_of::<BlockHeaderPotParametersChange>() as u32;
361    /// Bitmask for presence of `super_segment_root` field
362    pub const SUPER_SEGMENT_ROOT_MASK: u8 = 0b0000_0001;
363    /// Bitmask for presence of `next_solution_range` field
364    pub const NEXT_SOLUTION_RANGE_MASK: u8 = 0b0000_0010;
365    /// Bitmask for presence of `pot_parameters_change` field
366    pub const POT_PARAMETERS_CHANGE_MASK: u8 = 0b0000_0100;
367    /// All supported bitmask variants
368    pub const MASK_ALL: u8 = Self::SUPER_SEGMENT_ROOT_MASK
369        | Self::NEXT_SOLUTION_RANGE_MASK
370        | Self::POT_PARAMETERS_CHANGE_MASK;
371
372    /// Create an instance from provided bytes.
373    ///
374    /// `bytes` do not need to be aligned.
375    ///
376    /// The layout is as follows:
377    /// * fixed parameters: BlockHeaderFixedConsensusParameters
378    /// * bitflags: u8
379    /// * (optional, depends on bitflags) super segment root: SuperSegmentRoot
380    /// * (optional, depends on bitflags) next solution range: SolutionRange as unaligned bytes
381    /// * (optional, depends on bitflags) PoT parameters change: BlockHeaderPotParametersChange
382    ///
383    /// Returns an instance and remaining bytes on success.
384    #[inline]
385    pub fn try_from_bytes(bytes: &'a [u8]) -> Option<(Self, &'a [u8])> {
386        let (fixed_parameters, mut remainder) =
387            BlockHeaderFixedConsensusParameters::try_from_bytes(bytes)?;
388
389        let bitflags = *remainder.split_off_first()?;
390
391        if (bitflags & Self::MASK_ALL) != bitflags {
392            // Unexpected bitflags were set
393            return None;
394        }
395
396        let super_segment_root = if bitflags & Self::SUPER_SEGMENT_ROOT_MASK != 0 {
397            let super_segment_root;
398            (super_segment_root, remainder) = SuperSegmentRoot::from_bytes(remainder)?;
399
400            Some(super_segment_root)
401        } else {
402            None
403        };
404
405        let next_solution_range = if bitflags & Self::NEXT_SOLUTION_RANGE_MASK != 0 {
406            let next_solution_range;
407            (next_solution_range, remainder) =
408                remainder.split_first_chunk::<{ size_of::<SolutionRange>() }>()?;
409            // Not guaranteed to be aligned
410            let next_solution_range = SolutionRange::from_bytes(*next_solution_range);
411
412            Some(next_solution_range)
413        } else {
414            None
415        };
416
417        let pot_parameters_change = if bitflags & Self::POT_PARAMETERS_CHANGE_MASK != 0 {
418            let pot_parameters_change;
419            (pot_parameters_change, remainder) =
420                BlockHeaderPotParametersChange::try_from_bytes(remainder)?;
421
422            Some(pot_parameters_change)
423        } else {
424            None
425        };
426
427        Some((
428            Self {
429                fixed_parameters,
430                super_segment_root,
431                next_solution_range,
432                pot_parameters_change,
433                bytes: &bytes[..bytes.len() - remainder.len()],
434            },
435            remainder,
436        ))
437    }
438
439    /// Hash of the block consensus parameters, part of the eventual block root
440    pub fn hash(&self) -> Blake3Hash {
441        const {
442            assert!(Self::MAX_SIZE as usize <= CHUNK_LEN);
443        }
444        Blake3Hash::new(
445            single_chunk_hash(self.bytes).expect(
446                "Parser stores at most `MAX_SIZE` bytes, which fit into a single chunk; qed",
447            ),
448        )
449    }
450}
451
452/// Block header result.
453///
454/// The result contains information that can only be computed after the block was created.
455#[derive(Debug, Copy, Clone, Eq, PartialEq, TrivialType)]
456#[cfg_attr(feature = "scale-codec", derive(Encode, Decode, MaxEncodedLen))]
457#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
458#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
459#[repr(C)]
460pub struct BlockHeaderResult {
461    /// Root of the block body
462    // TODO: New type
463    pub body_root: Blake3Hash,
464    /// Root of the state tree
465    // TODO: New type?
466    pub state_root: Blake3Hash,
467}
468
469impl BlockHeaderResult {
470    /// Hash of the block header result, part of the eventual block root
471    pub fn hash(&self) -> Blake3Hash {
472        const {
473            assert!(size_of::<Self>() <= BLOCK_LEN);
474        }
475        Blake3Hash::new(
476            single_block_hash(self.as_bytes())
477                .expect("Less than a single block worth of bytes; qed"),
478        )
479    }
480}
481
482/// Block header seal type
483#[derive(Debug, Copy, Clone, Eq, PartialEq, TrivialType)]
484#[cfg_attr(feature = "scale-codec", derive(Encode, Decode, MaxEncodedLen))]
485#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
486#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
487#[repr(u8)]
488#[non_exhaustive]
489pub enum BlockHeaderSealType {
490    /// Ed25519 signature
491    #[cfg_attr(feature = "scale-codec", codec(index = 0))]
492    Ed25519 = 0,
493}
494
495impl BlockHeaderSealType {
496    /// Create an instance from bytes if valid
497    #[inline(always)]
498    pub const fn try_from_byte(byte: u8) -> Option<Self> {
499        if byte == Self::Ed25519 as u8 {
500            Some(Self::Ed25519)
501        } else {
502            None
503        }
504    }
505}
506
507/// Ed25519 seal
508#[derive(Debug, Copy, Clone, Eq, PartialEq, TrivialType)]
509#[cfg_attr(feature = "scale-codec", derive(Encode, Decode, MaxEncodedLen))]
510#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
511#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
512#[repr(C)]
513pub struct BlockHeaderEd25519Seal {
514    /// Ed25519 public key
515    pub public_key: Ed25519PublicKey,
516    /// Ed25519 signature
517    pub signature: Ed25519Signature,
518}
519
520/// Owned version of [`BlockHeaderSeal`]
521#[derive(Debug, Copy, Clone)]
522#[cfg_attr(feature = "scale-codec", derive(Encode, Decode, MaxEncodedLen))]
523#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
524#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
525#[non_exhaustive]
526pub enum OwnedBlockHeaderSeal {
527    /// Ed25519 seal
528    Ed25519(BlockHeaderEd25519Seal),
529}
530
531impl OwnedBlockHeaderSeal {
532    /// Get a reference out of owned version
533    #[inline(always)]
534    pub fn as_ref(&self) -> BlockHeaderSeal<'_> {
535        match self {
536            Self::Ed25519(seal) => BlockHeaderSeal::Ed25519(seal),
537        }
538    }
539}
540
541/// Block header seal
542#[derive(Debug, Copy, Clone)]
543#[non_exhaustive]
544pub enum BlockHeaderSeal<'a> {
545    /// Ed25519 seal
546    Ed25519(&'a BlockHeaderEd25519Seal),
547}
548
549impl<'a> BlockHeaderSeal<'a> {
550    /// Max size of the allocation necessary for this data structure
551    pub const MAX_SIZE: u32 = 1 + BlockHeaderEd25519Seal::SIZE;
552    /// Create an instance from provided bytes.
553    ///
554    /// `bytes` do not need to be aligned.
555    ///
556    /// The layout is as follows:
557    /// * seal type: u8
558    /// * seal (depends on a seal type): BlockHeaderEd25519Seal
559    ///
560    /// Returns an instance and remaining bytes on success.
561    #[inline]
562    pub fn try_from_bytes(mut bytes: &'a [u8]) -> Option<(Self, &'a [u8])> {
563        let seal_type = BlockHeaderSealType::try_from_byte(*bytes.split_off_first()?)?;
564
565        match seal_type {
566            BlockHeaderSealType::Ed25519 => {
567                let (seal, bytes) = BlockHeaderEd25519Seal::from_bytes(bytes)?;
568                Some((Self::Ed25519(seal), bytes))
569            }
570        }
571    }
572
573    /// Verify seal against [`BlockHeader::pre_seal_hash()`]
574    #[cfg(feature = "ed25519")]
575    #[inline]
576    pub fn is_seal_valid(&self, pre_seal_hash: &Blake3Hash) -> bool {
577        match self {
578            BlockHeaderSeal::Ed25519(seal) => seal
579                .public_key
580                .verify(&seal.signature, pre_seal_hash.as_bytes())
581                .is_ok(),
582        }
583    }
584
585    /// Derive public key hash from this seal
586    #[inline]
587    pub fn public_key_hash(&self) -> Blake3Hash {
588        match self {
589            BlockHeaderSeal::Ed25519(seal) => seal.public_key.hash(),
590        }
591    }
592
593    /// Hash of the block header seal, part of the eventual block root
594    #[inline]
595    pub fn hash(&self) -> Blake3Hash {
596        match self {
597            BlockHeaderSeal::Ed25519(seal) => {
598                let mut hasher = blake3::Hasher::new();
599                hasher.update(&[BlockHeaderSealType::Ed25519 as u8]);
600                hasher.update(seal.as_bytes());
601
602                Blake3Hash::from(hasher.finalize())
603            }
604        }
605    }
606}
607
608/// Error for block header parts that are not consistent with each other or with the shard kind of
609/// the header.
610///
611/// Headers with such parts are rejected by parsing, and can't be created from parts, whether as
612/// owned headers or written into a buffer.
613#[derive(Debug, Copy, Clone, Eq, PartialEq, thiserror::Error)]
614pub enum BlockHeaderConsistencyError {
615    /// Prefix padding is not all zeroes
616    #[error("Prefix padding is not all zeroes")]
617    NonZeroPrefixPadding,
618    /// Shard index is out of range or doesn't correspond to the shard kind of the header
619    #[error("Shard index {shard_index} is not a valid {shard_kind:?} shard index")]
620    InvalidShardIndex {
621        /// Shard index
622        shard_index: ShardIndex,
623        /// Shard kind of the header
624        shard_kind: RealShardKind,
625    },
626    /// Public key hash of the seal doesn't match the solution
627    #[error(
628        "Seal public key hash {seal_public_key_hash} doesn't match solution public key hash \
629        {solution_public_key_hash}"
630    )]
631    SealPublicKeyHashMismatch {
632        /// Public key hash of the solution
633        solution_public_key_hash: Blake3Hash,
634        /// Public key hash of the seal
635        seal_public_key_hash: Blake3Hash,
636    },
637}
638
639/// Part of the block header, shared for different kinds of shards
640#[derive(Debug, Copy, Clone)]
641pub struct SharedBlockHeader<'a> {
642    /// Block header prefix
643    pub prefix: &'a BlockHeaderPrefix,
644    /// Block header result
645    pub result: &'a BlockHeaderResult,
646    /// Consensus information
647    pub consensus_info: &'a BlockHeaderConsensusInfo,
648    /// Block header seal
649    pub seal: BlockHeaderSeal<'a>,
650}
651
652/// Block header that corresponds to the beacon chain
653#[derive(Debug, Clone, Yokeable)]
654// Prevent creation of potentially broken invariants externally
655#[non_exhaustive]
656pub struct BeaconChainHeader<'a> {
657    /// Shared block header
658    shared: SharedBlockHeader<'a>,
659    /// Root of intermediate shard block roots
660    intermediate_shard_blocks_root: &'a Blake3Hash,
661    /// Consensus parameters (on the beacon chain)
662    consensus_parameters: BlockHeaderConsensusParameters<'a>,
663    /// All bytes of the header except the seal
664    pre_seal_bytes: &'a [u8],
665    /// All bytes of the header, which owned versions are created from
666    #[cfg(feature = "alloc")]
667    bytes: &'a [u8],
668    #[cfg(all(feature = "alloc", any(target_os = "none", target_os = "unknown")))]
669    cached_block_root: once_cell::race::OnceBox<BlockRoot>,
670    #[cfg(not(any(target_os = "none", target_os = "unknown")))]
671    cached_block_root: std::sync::OnceLock<BlockRoot>,
672}
673
674impl<'a> Deref for BeaconChainHeader<'a> {
675    type Target = SharedBlockHeader<'a>;
676
677    #[inline(always)]
678    fn deref(&self) -> &Self::Target {
679        &self.shared
680    }
681}
682
683impl<'a> GenericBlockHeader<'a> for BeaconChainHeader<'a> {
684    const SHARD_KIND: RealShardKind = RealShardKind::BeaconChain;
685
686    #[cfg(feature = "alloc")]
687    type Owned = OwnedBeaconChainHeader;
688
689    #[cfg(feature = "alloc")]
690    #[inline(always)]
691    fn to_owned(self) -> Self::Owned {
692        self.to_owned()
693    }
694
695    #[inline(always)]
696    fn root(&self) -> impl Deref<Target = BlockRoot> + Send + Sync {
697        self.root()
698    }
699
700    #[inline(always)]
701    fn pre_seal_hash(&self) -> Blake3Hash {
702        self.pre_seal_hash()
703    }
704}
705
706impl<'a> BeaconChainHeader<'a> {
707    /// Try to create a new instance from provided bytes.
708    ///
709    /// `bytes` should be 8-bytes aligned.
710    ///
711    /// The layout is as follows:
712    /// * block header prefix: BlockHeaderPrefix
713    /// * block header result: BlockHeaderResult
714    /// * consensus info: BlockHeaderConsensusInfo
715    /// * root of intermediate shard block roots: Blake3Hash
716    /// * consensus parameters: BlockHeaderConsensusParameters
717    /// * block header seal: BlockHeaderSeal
718    ///
719    /// Returns an instance and remaining bytes on success, `None` if too few bytes were given,
720    /// bytes are not properly aligned or input is otherwise invalid.
721    #[inline]
722    pub fn try_from_bytes(bytes: &'a [u8]) -> Option<(Self, &'a [u8])> {
723        let (prefix, consensus_info, result, remainder) =
724            BlockHeader::try_from_bytes_shared(bytes, RealShardKind::BeaconChain)?;
725
726        let (intermediate_shard_blocks_root, remainder) = Blake3Hash::from_bytes(remainder)?;
727
728        let (consensus_parameters, remainder) =
729            BlockHeaderConsensusParameters::try_from_bytes(remainder)?;
730
731        let pre_seal_bytes = &bytes[..bytes.len() - remainder.len()];
732
733        let (seal, remainder) = BlockHeaderSeal::try_from_bytes(remainder)?;
734        BlockHeader::check_seal(&consensus_info.solution.public_key_hash, seal).ok()?;
735
736        let shared = SharedBlockHeader {
737            prefix,
738            result,
739            consensus_info,
740            seal,
741        };
742
743        let header = Self {
744            shared,
745            intermediate_shard_blocks_root,
746            consensus_parameters,
747            pre_seal_bytes,
748            #[cfg(feature = "alloc")]
749            bytes: &bytes[..bytes.len() - remainder.len()],
750            #[cfg(all(feature = "alloc", any(target_os = "none", target_os = "unknown")))]
751            cached_block_root: once_cell::race::OnceBox::new(),
752            #[cfg(not(any(target_os = "none", target_os = "unknown")))]
753            cached_block_root: std::sync::OnceLock::new(),
754        };
755
756        Some((header, remainder))
757    }
758
759    /// Create an owned version of this header
760    #[cfg(feature = "alloc")]
761    #[inline(always)]
762    pub fn to_owned(self) -> OwnedBeaconChainHeader {
763        let buffer = SharedAlignedBuffer::from_bytes(self.bytes);
764        OwnedBeaconChainHeader::from_buffer(buffer).expect(
765            "The same bytes were already parsed with all checks, which only depend on the address \
766            being 8-byte aligned, and owned buffers are 16-byte aligned and hold headers, which \
767            are far smaller than `u32::MAX` bytes; qed",
768        )
769    }
770
771    /// Shared block header
772    #[inline(always)]
773    pub fn shared(&self) -> &SharedBlockHeader<'a> {
774        &self.shared
775    }
776
777    /// Root of intermediate shard block roots.
778    ///
779    /// It duplicates `headers_root()` of intermediate shard blocks in the body on purpose, to keep
780    /// proofs through the header short.
781    #[inline(always)]
782    pub fn intermediate_shard_blocks_root(&self) -> &'a Blake3Hash {
783        self.intermediate_shard_blocks_root
784    }
785
786    /// Consensus parameters (on the beacon chain)
787    #[inline(always)]
788    pub fn consensus_parameters(&self) -> &BlockHeaderConsensusParameters<'a> {
789        &self.consensus_parameters
790    }
791
792    /// Hash of the block before seal is applied to it
793    #[inline]
794    pub fn pre_seal_hash(&self) -> Blake3Hash {
795        Blake3Hash::from(blake3::hash(self.pre_seal_bytes))
796    }
797
798    /// Verify seal against [`BeaconChainHeader::pre_seal_hash()`] and check that its public key
799    /// hash corresponds to the solution
800    #[cfg(feature = "ed25519")]
801    #[inline]
802    pub fn is_sealed_correctly(&self) -> bool {
803        self.consensus_info.solution.public_key_hash == self.seal.public_key_hash()
804            && self.seal.is_seal_valid(&self.pre_seal_hash())
805    }
806
807    /// Compute block root out of this header.
808    ///
809    /// Block root is a Merkle Tree Root. The leaves are derived from individual fields in
810    /// [`SharedBlockHeader`] and other fields of this enum in the declaration order.
811    ///
812    /// Note that this method computes root by doing a bunch of hashing. The result is then cached
813    /// if `alloc` feature is enabled or when compiled for OS target that is not `none`.
814    #[inline]
815    pub fn root(&self) -> impl Deref<Target = BlockRoot> + Send + Sync {
816        let Self {
817            shared,
818            intermediate_shard_blocks_root,
819            consensus_parameters,
820            pre_seal_bytes: _,
821            #[cfg(feature = "alloc")]
822                bytes: _,
823            #[cfg(any(feature = "alloc", not(any(target_os = "none", target_os = "unknown"))))]
824            cached_block_root,
825        } = self;
826
827        let compute_root = || {
828            let SharedBlockHeader {
829                prefix,
830                result,
831                consensus_info,
832                seal,
833            } = shared;
834
835            let block_root = BeaconChainHeaderMerkleTree::compute_root_only_array(&[
836                prefix.hash(),
837                result.hash(),
838                consensus_info.hash(),
839                seal.hash(),
840                **intermediate_shard_blocks_root,
841                consensus_parameters.hash(),
842            ]);
843
844            BlockRoot::new(Blake3Hash::new(block_root))
845        };
846
847        #[cfg(not(any(target_os = "none", target_os = "unknown")))]
848        {
849            cached_block_root.get_or_init(compute_root)
850        }
851        #[cfg(all(feature = "alloc", any(target_os = "none", target_os = "unknown")))]
852        {
853            cached_block_root.get_or_init(|| alloc::boxed::Box::new(compute_root()))
854        }
855        #[cfg(all(not(feature = "alloc"), any(target_os = "none", target_os = "unknown")))]
856        {
857            struct Wrapper(BlockRoot);
858
859            impl Deref for Wrapper {
860                type Target = BlockRoot;
861
862                #[inline(always)]
863                fn deref(&self) -> &Self::Target {
864                    &self.0
865                }
866            }
867
868            Wrapper(compute_root())
869        }
870    }
871}
872
873/// Block header that corresponds to an intermediate shard
874#[derive(Debug, Clone, Yokeable)]
875// Prevent creation of potentially broken invariants externally
876#[non_exhaustive]
877pub struct IntermediateShardHeader<'a> {
878    /// Shared block header
879    shared: SharedBlockHeader<'a>,
880    /// Beacon chain info
881    beacon_chain_info: &'a BlockHeaderBeaconChainInfo,
882    /// Root of leaf shard block roots
883    leaf_shard_blocks_root: &'a Blake3Hash,
884    /// All bytes of the header except the seal
885    pre_seal_bytes: &'a [u8],
886    /// All bytes of the header, which owned versions are created from
887    #[cfg(feature = "alloc")]
888    bytes: &'a [u8],
889    #[cfg(all(feature = "alloc", any(target_os = "none", target_os = "unknown")))]
890    cached_block_root: once_cell::race::OnceBox<BlockRoot>,
891    #[cfg(not(any(target_os = "none", target_os = "unknown")))]
892    cached_block_root: std::sync::OnceLock<BlockRoot>,
893}
894
895impl<'a> Deref for IntermediateShardHeader<'a> {
896    type Target = SharedBlockHeader<'a>;
897
898    #[inline(always)]
899    fn deref(&self) -> &Self::Target {
900        &self.shared
901    }
902}
903
904impl<'a> GenericBlockHeader<'a> for IntermediateShardHeader<'a> {
905    const SHARD_KIND: RealShardKind = RealShardKind::IntermediateShard;
906
907    #[cfg(feature = "alloc")]
908    type Owned = OwnedIntermediateShardHeader;
909
910    #[cfg(feature = "alloc")]
911    #[inline(always)]
912    fn to_owned(self) -> Self::Owned {
913        self.to_owned()
914    }
915
916    #[inline(always)]
917    fn root(&self) -> impl Deref<Target = BlockRoot> + Send + Sync {
918        self.root()
919    }
920
921    #[inline(always)]
922    fn pre_seal_hash(&self) -> Blake3Hash {
923        self.pre_seal_hash()
924    }
925}
926
927impl<'a> IntermediateShardHeader<'a> {
928    /// Try to create a new instance from provided bytes.
929    ///
930    /// `bytes` should be 8-bytes aligned.
931    ///
932    /// The layout is as follows:
933    /// * block header prefix: BlockHeaderPrefix
934    /// * block header result: BlockHeaderResult
935    /// * consensus info: BlockHeaderConsensusInfo
936    /// * beacon chain: BlockHeaderBeaconChainInfo
937    /// * root of leaf shard block roots: Blake3Hash
938    /// * block header seal: BlockHeaderSeal
939    ///
940    /// Returns an instance and remaining bytes on success, `None` if too few bytes were given,
941    /// bytes are not properly aligned or input is otherwise invalid.
942    #[inline]
943    pub fn try_from_bytes(bytes: &'a [u8]) -> Option<(Self, &'a [u8])> {
944        let (prefix, consensus_info, result, remainder) =
945            BlockHeader::try_from_bytes_shared(bytes, RealShardKind::IntermediateShard)?;
946
947        let (beacon_chain_info, remainder) = BlockHeaderBeaconChainInfo::from_bytes(remainder)?;
948
949        let (leaf_shard_blocks_root, remainder) = Blake3Hash::from_bytes(remainder)?;
950
951        let pre_seal_bytes = &bytes[..bytes.len() - remainder.len()];
952
953        let (seal, remainder) = BlockHeaderSeal::try_from_bytes(remainder)?;
954        BlockHeader::check_seal(&consensus_info.solution.public_key_hash, seal).ok()?;
955
956        let shared = SharedBlockHeader {
957            prefix,
958            result,
959            consensus_info,
960            seal,
961        };
962
963        let header = Self {
964            shared,
965            beacon_chain_info,
966            leaf_shard_blocks_root,
967            pre_seal_bytes,
968            #[cfg(feature = "alloc")]
969            bytes: &bytes[..bytes.len() - remainder.len()],
970            #[cfg(all(feature = "alloc", any(target_os = "none", target_os = "unknown")))]
971            cached_block_root: once_cell::race::OnceBox::new(),
972            #[cfg(not(any(target_os = "none", target_os = "unknown")))]
973            cached_block_root: std::sync::OnceLock::new(),
974        };
975
976        Some((header, remainder))
977    }
978
979    /// All bytes of the header, which are copied as they are into other data structures
980    #[cfg(feature = "alloc")]
981    #[inline(always)]
982    pub(crate) fn bytes(&self) -> &'a [u8] {
983        self.bytes
984    }
985
986    /// Create an owned version of this header
987    #[cfg(feature = "alloc")]
988    #[inline(always)]
989    pub fn to_owned(self) -> OwnedIntermediateShardHeader {
990        let buffer = SharedAlignedBuffer::from_bytes(self.bytes);
991        OwnedIntermediateShardHeader::from_buffer(buffer).expect(
992            "The same bytes were already parsed with all checks, which only depend on the address \
993            being 8-byte aligned, and owned buffers are 16-byte aligned and hold headers, which \
994            are far smaller than `u32::MAX` bytes; qed",
995        )
996    }
997
998    /// Shared block header
999    #[inline(always)]
1000    pub fn shared(&self) -> &SharedBlockHeader<'a> {
1001        &self.shared
1002    }
1003
1004    /// Beacon chain info
1005    #[inline(always)]
1006    pub fn beacon_chain_info(&self) -> &'a BlockHeaderBeaconChainInfo {
1007        self.beacon_chain_info
1008    }
1009
1010    /// Root of leaf shard block roots.
1011    ///
1012    /// It duplicates `headers_root()` of leaf shard blocks in the body on purpose, to keep proofs
1013    /// through the header short and so that the beacon chain can verify segments of intermediate
1014    /// shard blocks without storing a sibling for each of them.
1015    #[inline(always)]
1016    pub fn leaf_shard_blocks_root(&self) -> &'a Blake3Hash {
1017        self.leaf_shard_blocks_root
1018    }
1019
1020    /// Hash of the block before seal is applied to it
1021    #[inline]
1022    pub fn pre_seal_hash(&self) -> Blake3Hash {
1023        Blake3Hash::from(blake3::hash(self.pre_seal_bytes))
1024    }
1025
1026    /// Verify seal against [`IntermediateShardHeader::pre_seal_hash()`] and check that its public
1027    /// key hash corresponds to the solution
1028    #[cfg(feature = "ed25519")]
1029    #[inline]
1030    pub fn is_sealed_correctly(&self) -> bool {
1031        self.consensus_info.solution.public_key_hash == self.seal.public_key_hash()
1032            && self.seal.is_seal_valid(&self.pre_seal_hash())
1033    }
1034
1035    /// Compute block root out of this header.
1036    ///
1037    /// Block root is a Merkle Tree Root. The leaves are derived from individual fields in
1038    /// [`SharedBlockHeader`] and other fields of this enum in the declaration order.
1039    ///
1040    /// Note that this method computes root by doing a bunch of hashing. The result is then cached
1041    /// if `alloc` feature is enabled or when compiled for OS target that is not `none`.
1042    #[inline]
1043    pub fn root(&self) -> impl Deref<Target = BlockRoot> + Send + Sync {
1044        let Self {
1045            shared,
1046            beacon_chain_info,
1047            leaf_shard_blocks_root,
1048            pre_seal_bytes: _,
1049            #[cfg(feature = "alloc")]
1050                bytes: _,
1051            #[cfg(any(feature = "alloc", not(any(target_os = "none", target_os = "unknown"))))]
1052            cached_block_root,
1053        } = self;
1054
1055        let compute_root = || {
1056            let SharedBlockHeader {
1057                prefix,
1058                result,
1059                consensus_info,
1060                seal,
1061            } = shared;
1062
1063            let block_root = IntermediateShardHeaderMerkleTree::compute_root_only_array(&[
1064                prefix.hash(),
1065                result.hash(),
1066                consensus_info.hash(),
1067                seal.hash(),
1068                beacon_chain_info.hash(),
1069                **leaf_shard_blocks_root,
1070            ]);
1071
1072            BlockRoot::new(Blake3Hash::new(block_root))
1073        };
1074
1075        #[cfg(not(any(target_os = "none", target_os = "unknown")))]
1076        {
1077            cached_block_root.get_or_init(compute_root)
1078        }
1079        #[cfg(all(feature = "alloc", any(target_os = "none", target_os = "unknown")))]
1080        {
1081            cached_block_root.get_or_init(|| alloc::boxed::Box::new(compute_root()))
1082        }
1083        #[cfg(all(not(feature = "alloc"), any(target_os = "none", target_os = "unknown")))]
1084        {
1085            struct Wrapper(BlockRoot);
1086
1087            impl Deref for Wrapper {
1088                type Target = BlockRoot;
1089
1090                #[inline(always)]
1091                fn deref(&self) -> &Self::Target {
1092                    &self.0
1093                }
1094            }
1095
1096            Wrapper(compute_root())
1097        }
1098    }
1099}
1100
1101/// Block header that corresponds to a leaf shard
1102#[derive(Debug, Clone, Yokeable)]
1103// Prevent creation of potentially broken invariants externally
1104#[non_exhaustive]
1105pub struct LeafShardHeader<'a> {
1106    /// Shared block header
1107    shared: SharedBlockHeader<'a>,
1108    /// Beacon chain info
1109    beacon_chain_info: &'a BlockHeaderBeaconChainInfo,
1110    /// All bytes of the header except the seal
1111    pre_seal_bytes: &'a [u8],
1112    /// All bytes of the header, which owned versions are created from
1113    #[cfg(feature = "alloc")]
1114    bytes: &'a [u8],
1115    #[cfg(all(feature = "alloc", any(target_os = "none", target_os = "unknown")))]
1116    cached_block_root: once_cell::race::OnceBox<BlockRoot>,
1117    #[cfg(not(any(target_os = "none", target_os = "unknown")))]
1118    cached_block_root: std::sync::OnceLock<BlockRoot>,
1119}
1120
1121impl<'a> Deref for LeafShardHeader<'a> {
1122    type Target = SharedBlockHeader<'a>;
1123
1124    #[inline(always)]
1125    fn deref(&self) -> &Self::Target {
1126        &self.shared
1127    }
1128}
1129
1130impl<'a> GenericBlockHeader<'a> for LeafShardHeader<'a> {
1131    const SHARD_KIND: RealShardKind = RealShardKind::LeafShard;
1132
1133    #[cfg(feature = "alloc")]
1134    type Owned = OwnedLeafShardHeader;
1135
1136    #[cfg(feature = "alloc")]
1137    #[inline(always)]
1138    fn to_owned(self) -> Self::Owned {
1139        self.to_owned()
1140    }
1141
1142    #[inline(always)]
1143    fn root(&self) -> impl Deref<Target = BlockRoot> + Send + Sync {
1144        self.root()
1145    }
1146
1147    #[inline(always)]
1148    fn pre_seal_hash(&self) -> Blake3Hash {
1149        self.pre_seal_hash()
1150    }
1151}
1152
1153impl<'a> LeafShardHeader<'a> {
1154    /// Try to create a new instance from provided bytes.
1155    ///
1156    /// `bytes` should be 8-bytes aligned.
1157    ///
1158    /// The layout is as follows:
1159    /// * block header prefix: BlockHeaderPrefix
1160    /// * block header result: BlockHeaderResult
1161    /// * consensus info: BlockHeaderConsensusInfo
1162    /// * beacon chain: BlockHeaderBeaconChainInfo
1163    /// * block header seal: BlockHeaderSeal
1164    ///
1165    /// Returns an instance and remaining bytes on success, `None` if too few bytes were given,
1166    /// bytes are not properly aligned or input is otherwise invalid.
1167    #[inline]
1168    pub fn try_from_bytes(bytes: &'a [u8]) -> Option<(Self, &'a [u8])> {
1169        let (prefix, consensus_info, result, remainder) =
1170            BlockHeader::try_from_bytes_shared(bytes, RealShardKind::LeafShard)?;
1171
1172        let (beacon_chain_info, remainder) = BlockHeaderBeaconChainInfo::from_bytes(remainder)?;
1173
1174        let pre_seal_bytes = &bytes[..bytes.len() - remainder.len()];
1175
1176        let (seal, remainder) = BlockHeaderSeal::try_from_bytes(remainder)?;
1177        BlockHeader::check_seal(&consensus_info.solution.public_key_hash, seal).ok()?;
1178
1179        let shared = SharedBlockHeader {
1180            prefix,
1181            result,
1182            consensus_info,
1183            seal,
1184        };
1185
1186        let header = Self {
1187            shared,
1188            beacon_chain_info,
1189            pre_seal_bytes,
1190            #[cfg(feature = "alloc")]
1191            bytes: &bytes[..bytes.len() - remainder.len()],
1192            #[cfg(all(feature = "alloc", any(target_os = "none", target_os = "unknown")))]
1193            cached_block_root: once_cell::race::OnceBox::new(),
1194            #[cfg(not(any(target_os = "none", target_os = "unknown")))]
1195            cached_block_root: std::sync::OnceLock::new(),
1196        };
1197
1198        Some((header, remainder))
1199    }
1200
1201    /// All bytes of the header, which are copied as they are into other data structures
1202    #[cfg(feature = "alloc")]
1203    #[inline(always)]
1204    pub(crate) fn bytes(&self) -> &'a [u8] {
1205        self.bytes
1206    }
1207
1208    /// Create an owned version of this header
1209    #[cfg(feature = "alloc")]
1210    #[inline(always)]
1211    pub fn to_owned(self) -> OwnedLeafShardHeader {
1212        let buffer = SharedAlignedBuffer::from_bytes(self.bytes);
1213        OwnedLeafShardHeader::from_buffer(buffer).expect(
1214            "The same bytes were already parsed with all checks, which only depend on the address \
1215            being 8-byte aligned, and owned buffers are 16-byte aligned and hold headers, which \
1216            are far smaller than `u32::MAX` bytes; qed",
1217        )
1218    }
1219
1220    /// Shared block header
1221    #[inline(always)]
1222    pub fn shared(&self) -> &SharedBlockHeader<'a> {
1223        &self.shared
1224    }
1225
1226    /// Beacon chain info
1227    #[inline(always)]
1228    pub fn beacon_chain_info(&self) -> &'a BlockHeaderBeaconChainInfo {
1229        self.beacon_chain_info
1230    }
1231
1232    /// Hash of the block before seal is applied to it
1233    #[inline]
1234    pub fn pre_seal_hash(&self) -> Blake3Hash {
1235        Blake3Hash::from(blake3::hash(self.pre_seal_bytes))
1236    }
1237
1238    /// Verify seal against [`LeafShardHeader::pre_seal_hash()`] and check that its public key hash
1239    /// corresponds to the solution
1240    #[cfg(feature = "ed25519")]
1241    #[inline]
1242    pub fn is_sealed_correctly(&self) -> bool {
1243        self.consensus_info.solution.public_key_hash == self.seal.public_key_hash()
1244            && self.seal.is_seal_valid(&self.pre_seal_hash())
1245    }
1246
1247    /// Compute block root out of this header.
1248    ///
1249    /// Block root is a Merkle Tree Root. The leaves are derived from individual fields in
1250    /// [`SharedBlockHeader`] and other fields of this enum in the declaration order.
1251    ///
1252    /// Note that this method computes root by doing a bunch of hashing. The result is then cached
1253    /// if `alloc` feature is enabled or when compiled for OS target that is not `none`.
1254    #[inline]
1255    pub fn root(&self) -> impl Deref<Target = BlockRoot> + Send + Sync {
1256        let Self {
1257            shared,
1258            beacon_chain_info,
1259            pre_seal_bytes: _,
1260            #[cfg(feature = "alloc")]
1261                bytes: _,
1262            #[cfg(any(feature = "alloc", not(any(target_os = "none", target_os = "unknown"))))]
1263            cached_block_root,
1264        } = self;
1265
1266        let compute_root = || {
1267            let SharedBlockHeader {
1268                prefix,
1269                result,
1270                consensus_info,
1271                seal,
1272            } = shared;
1273
1274            let block_root = LeafShardHeaderMerkleTree::compute_root_only_array(&[
1275                prefix.hash(),
1276                result.hash(),
1277                consensus_info.hash(),
1278                seal.hash(),
1279                beacon_chain_info.hash(),
1280            ]);
1281
1282            BlockRoot::new(Blake3Hash::new(block_root))
1283        };
1284
1285        #[cfg(not(any(target_os = "none", target_os = "unknown")))]
1286        {
1287            cached_block_root.get_or_init(compute_root)
1288        }
1289        #[cfg(all(feature = "alloc", any(target_os = "none", target_os = "unknown")))]
1290        {
1291            cached_block_root.get_or_init(|| alloc::boxed::Box::new(compute_root()))
1292        }
1293        #[cfg(all(not(feature = "alloc"), any(target_os = "none", target_os = "unknown")))]
1294        {
1295            struct Wrapper(BlockRoot);
1296
1297            impl Deref for Wrapper {
1298                type Target = BlockRoot;
1299
1300                #[inline(always)]
1301                fn deref(&self) -> &Self::Target {
1302                    &self.0
1303                }
1304            }
1305
1306            Wrapper(compute_root())
1307        }
1308    }
1309}
1310
1311/// Block header that together with [`BlockBody`] form a [`Block`]
1312///
1313/// [`BlockBody`]: crate::block::body::BlockBody
1314/// [`Block`]: crate::block::Block
1315#[derive(Debug, Clone, From)]
1316pub enum BlockHeader<'a> {
1317    /// Block header corresponds to the beacon chain
1318    BeaconChain(BeaconChainHeader<'a>),
1319    /// Block header corresponds to an intermediate shard
1320    IntermediateShard(IntermediateShardHeader<'a>),
1321    /// Block header corresponds to a leaf shard
1322    LeafShard(LeafShardHeader<'a>),
1323}
1324
1325impl<'a> Deref for BlockHeader<'a> {
1326    type Target = SharedBlockHeader<'a>;
1327
1328    #[inline(always)]
1329    fn deref(&self) -> &Self::Target {
1330        match self {
1331            Self::BeaconChain(header) => header,
1332            Self::IntermediateShard(header) => header,
1333            Self::LeafShard(header) => header,
1334        }
1335    }
1336}
1337
1338impl<'a> BlockHeader<'a> {
1339    /// Try to create a new instance from provided bytes.
1340    ///
1341    /// `bytes` should be 8-bytes aligned. The shard kind of the header is that of the shard index
1342    /// in its prefix, see [`Self::shard_kind_from_bytes()`].
1343    ///
1344    /// Returns an instance and remaining bytes on success, `None` if too few bytes were given,
1345    /// bytes are not properly aligned or input is otherwise invalid.
1346    #[inline]
1347    pub fn try_from_bytes(bytes: &'a [u8]) -> Option<(Self, &'a [u8])> {
1348        match Self::shard_kind_from_bytes(bytes)? {
1349            RealShardKind::BeaconChain => {
1350                let (header, remainder) = BeaconChainHeader::try_from_bytes(bytes)?;
1351                Some((Self::BeaconChain(header), remainder))
1352            }
1353            RealShardKind::IntermediateShard => {
1354                let (header, remainder) = IntermediateShardHeader::try_from_bytes(bytes)?;
1355                Some((Self::IntermediateShard(header), remainder))
1356            }
1357            RealShardKind::LeafShard => {
1358                let (header, remainder) = LeafShardHeader::try_from_bytes(bytes)?;
1359                Some((Self::LeafShard(header), remainder))
1360            }
1361        }
1362    }
1363
1364    /// Shard kind of the header that `bytes` start with.
1365    ///
1366    /// Headers of all shard kinds start with [`BlockHeaderPrefix`], so the shard kind is that of
1367    /// its shard index. Returns `None` if there are too few bytes for the prefix, they are not
1368    /// 8-bytes aligned or the shard index doesn't correspond to a real shard.
1369    #[inline]
1370    pub fn shard_kind_from_bytes(bytes: &[u8]) -> Option<RealShardKind> {
1371        let (prefix, _remainder) = BlockHeaderPrefix::from_bytes(bytes)?;
1372        prefix.shard_index.shard_kind()?.to_real()
1373    }
1374
1375    #[inline]
1376    fn try_from_bytes_shared(
1377        mut bytes: &'a [u8],
1378        shard_kind: RealShardKind,
1379    ) -> Option<(
1380        &'a BlockHeaderPrefix,
1381        &'a BlockHeaderConsensusInfo,
1382        &'a BlockHeaderResult,
1383        &'a [u8],
1384    )> {
1385        let prefix;
1386        (prefix, bytes) = BlockHeaderPrefix::from_bytes(bytes)?;
1387
1388        let result;
1389        (result, bytes) = BlockHeaderResult::from_bytes(bytes)?;
1390
1391        let consensus_info;
1392        (consensus_info, bytes) = BlockHeaderConsensusInfo::from_bytes(bytes)?;
1393
1394        Self::check_shared_parts(prefix, shard_kind).ok()?;
1395
1396        Some((prefix, consensus_info, result, bytes))
1397    }
1398
1399    /// Check the parts shared by headers of all shard kinds.
1400    ///
1401    /// Both the parser and headers created from parts use it, so they accept the same parts.
1402    #[inline]
1403    fn check_shared_parts(
1404        prefix: &BlockHeaderPrefix,
1405        shard_kind: RealShardKind,
1406    ) -> Result<(), BlockHeaderConsistencyError> {
1407        if prefix.padding_0 != [0; _] {
1408            return Err(BlockHeaderConsistencyError::NonZeroPrefixPadding);
1409        }
1410
1411        // Shard indices that are out of range have no shard kind
1412        if prefix.shard_index.shard_kind() != Some(ShardKind::from(shard_kind)) {
1413            return Err(BlockHeaderConsistencyError::InvalidShardIndex {
1414                shard_index: prefix.shard_index,
1415                shard_kind,
1416            });
1417        }
1418
1419        Ok(())
1420    }
1421
1422    /// Check that the seal was created by the solution's public key.
1423    ///
1424    /// Both the parser and headers created from parts use it, so they accept the same seals.
1425    #[inline]
1426    fn check_seal(
1427        solution_public_key_hash: &Blake3Hash,
1428        seal: BlockHeaderSeal<'_>,
1429    ) -> Result<(), BlockHeaderConsistencyError> {
1430        let seal_public_key_hash = seal.public_key_hash();
1431
1432        if seal_public_key_hash != *solution_public_key_hash {
1433            return Err(BlockHeaderConsistencyError::SealPublicKeyHashMismatch {
1434                solution_public_key_hash: *solution_public_key_hash,
1435                seal_public_key_hash,
1436            });
1437        }
1438
1439        Ok(())
1440    }
1441
1442    /// Create an owned version of this header
1443    #[cfg(feature = "alloc")]
1444    #[inline(always)]
1445    pub fn to_owned(self) -> OwnedBlockHeader {
1446        match self {
1447            Self::BeaconChain(header) => header.to_owned().into(),
1448            Self::IntermediateShard(header) => header.to_owned().into(),
1449            Self::LeafShard(header) => header.to_owned().into(),
1450        }
1451    }
1452
1453    /// Hash of the block before seal is applied to it
1454    #[inline]
1455    pub fn pre_seal_hash(&self) -> Blake3Hash {
1456        match self {
1457            Self::BeaconChain(header) => header.pre_seal_hash(),
1458            Self::IntermediateShard(header) => header.pre_seal_hash(),
1459            Self::LeafShard(header) => header.pre_seal_hash(),
1460        }
1461    }
1462
1463    /// Verify seal against [`BlockHeader::pre_seal_hash()`] and check that its public key hash
1464    /// corresponds to the solution
1465    #[cfg(feature = "ed25519")]
1466    #[inline]
1467    pub fn is_sealed_correctly(&self) -> bool {
1468        match self {
1469            Self::BeaconChain(header) => header.is_sealed_correctly(),
1470            Self::IntermediateShard(header) => header.is_sealed_correctly(),
1471            Self::LeafShard(header) => header.is_sealed_correctly(),
1472        }
1473    }
1474
1475    /// Compute block root out of this header.
1476    ///
1477    /// Block root is a Merkle Tree Root. The leaves are derived from individual fields in
1478    /// [`SharedBlockHeader`] and other fields of this enum in the declaration order.
1479    ///
1480    /// Note that this method computes root by doing a bunch of hashing. The result is then cached
1481    /// if `alloc` feature is enabled.
1482    #[inline]
1483    pub fn root(&self) -> impl Deref<Target = BlockRoot> + Send + Sync {
1484        enum Wrapper<B, I, L> {
1485            BeaconChain(B),
1486            IntermediateShard(I),
1487            LeafShard(L),
1488        }
1489
1490        impl<B, I, L> Deref for Wrapper<B, I, L>
1491        where
1492            B: Deref<Target = BlockRoot>,
1493            I: Deref<Target = BlockRoot>,
1494            L: Deref<Target = BlockRoot>,
1495        {
1496            type Target = BlockRoot;
1497
1498            #[inline(always)]
1499            fn deref(&self) -> &Self::Target {
1500                match self {
1501                    Wrapper::BeaconChain(block_root) => block_root,
1502                    Wrapper::IntermediateShard(block_root) => block_root,
1503                    Wrapper::LeafShard(block_root) => block_root,
1504                }
1505            }
1506        }
1507
1508        match self {
1509            Self::BeaconChain(header) => Wrapper::BeaconChain(header.root()),
1510            Self::IntermediateShard(header) => Wrapper::IntermediateShard(header.root()),
1511            Self::LeafShard(header) => Wrapper::LeafShard(header.root()),
1512        }
1513    }
1514}