1#[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
37pub 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 const SHARD_KIND: RealShardKind;
49
50 #[cfg(feature = "alloc")]
52 type Owned: GenericOwnedBlockHeader<Header<'a> = Self>
53 where
54 Self: 'a;
55
56 #[cfg(feature = "alloc")]
58 fn to_owned(self) -> Self::Owned;
59
60 fn root(&self) -> impl Deref<Target = BlockRoot> + Send + Sync;
67
68 fn pre_seal_hash(&self) -> Blake3Hash;
70}
71
72#[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 pub number: BlockNumber,
83 pub shard_index: ShardIndex,
85 pub padding_0: [u8; 4],
87 pub timestamp: BlockTimestamp,
89 pub parent_root: BlockRoot,
91 pub mmr_root: Blake3Hash,
94}
95
96impl BlockHeaderPrefix {
97 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#[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 pub slot: SlotNumber,
118 pub proof_of_time: PotOutput,
120 pub future_proof_of_time: PotOutput,
122 pub solution: Solution,
124}
125
126impl BlockHeaderConsensusInfo {
127 pub fn hash(&self) -> Blake3Hash {
129 Blake3Hash::from(blake3::hash(self.as_bytes()))
130 }
131}
132
133#[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 pub number: BlockNumber,
142 pub root: BlockRoot,
144}
145
146impl BlockHeaderBeaconChainInfo {
147 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#[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 pub solution_range: SolutionRange,
167 pub slot_iterations: NonZeroU32,
172 pub num_shards: NumShards,
174}
175
176impl BlockHeaderFixedConsensusParameters {
177 #[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#[derive(Debug, Copy, Clone, Eq, PartialEq)]
215#[repr(C, packed)]
216pub struct BlockHeaderPotParametersChange {
217 slot: SlotNumber,
221 slot_iterations: NonZeroU32,
223 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 #[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 let pot_parameters_change = unsafe { pot_parameters_change_ptr.as_ref_unchecked() };
287
288 Some((pot_parameters_change, bytes))
289 }
290}
291
292#[derive(Debug, Copy, Clone, Eq, PartialEq)]
294pub struct OwnedBlockHeaderConsensusParameters {
295 pub fixed_parameters: BlockHeaderFixedConsensusParameters,
297 pub super_segment_root: Option<SuperSegmentRoot>,
299 pub next_solution_range: Option<SolutionRange>,
301 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#[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 pub mut(self) fixed_parameters: BlockHeaderFixedConsensusParameters,
334 pub mut(self) super_segment_root: Option<&'a SuperSegmentRoot>,
336 pub mut(self) next_solution_range: Option<SolutionRange>,
338 pub mut(self) pot_parameters_change: Option<&'a BlockHeaderPotParametersChange>,
340 bytes: &'a [u8],
342}
343
344impl<'a> BlockHeaderConsensusParameters<'a> {
345 pub const MAX_SIZE: u32 =
347 <SolutionRange as TrivialType>::SIZE
349 + u32::SIZE
351 + <NumShardsUnchecked as TrivialType>::SIZE
353 + u8::SIZE
355 + <SuperSegmentRoot as TrivialType>::SIZE
357 + <SolutionRange as TrivialType>::SIZE
359 + size_of::<BlockHeaderPotParametersChange>() as u32;
361 pub const SUPER_SEGMENT_ROOT_MASK: u8 = 0b0000_0001;
363 pub const NEXT_SOLUTION_RANGE_MASK: u8 = 0b0000_0010;
365 pub const POT_PARAMETERS_CHANGE_MASK: u8 = 0b0000_0100;
367 pub const MASK_ALL: u8 = Self::SUPER_SEGMENT_ROOT_MASK
369 | Self::NEXT_SOLUTION_RANGE_MASK
370 | Self::POT_PARAMETERS_CHANGE_MASK;
371
372 #[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 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 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 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#[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 pub body_root: Blake3Hash,
464 pub state_root: Blake3Hash,
467}
468
469impl BlockHeaderResult {
470 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#[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 #[cfg_attr(feature = "scale-codec", codec(index = 0))]
492 Ed25519 = 0,
493}
494
495impl BlockHeaderSealType {
496 #[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#[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 pub public_key: Ed25519PublicKey,
516 pub signature: Ed25519Signature,
518}
519
520#[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(BlockHeaderEd25519Seal),
529}
530
531impl OwnedBlockHeaderSeal {
532 #[inline(always)]
534 pub fn as_ref(&self) -> BlockHeaderSeal<'_> {
535 match self {
536 Self::Ed25519(seal) => BlockHeaderSeal::Ed25519(seal),
537 }
538 }
539}
540
541#[derive(Debug, Copy, Clone)]
543#[non_exhaustive]
544pub enum BlockHeaderSeal<'a> {
545 Ed25519(&'a BlockHeaderEd25519Seal),
547}
548
549impl<'a> BlockHeaderSeal<'a> {
550 pub const MAX_SIZE: u32 = 1 + BlockHeaderEd25519Seal::SIZE;
552 #[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 #[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 #[inline]
587 pub fn public_key_hash(&self) -> Blake3Hash {
588 match self {
589 BlockHeaderSeal::Ed25519(seal) => seal.public_key.hash(),
590 }
591 }
592
593 #[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#[derive(Debug, Copy, Clone, Eq, PartialEq, thiserror::Error)]
614pub enum BlockHeaderConsistencyError {
615 #[error("Prefix padding is not all zeroes")]
617 NonZeroPrefixPadding,
618 #[error("Shard index {shard_index} is not a valid {shard_kind:?} shard index")]
620 InvalidShardIndex {
621 shard_index: ShardIndex,
623 shard_kind: RealShardKind,
625 },
626 #[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 solution_public_key_hash: Blake3Hash,
634 seal_public_key_hash: Blake3Hash,
636 },
637}
638
639#[derive(Debug, Copy, Clone)]
641pub struct SharedBlockHeader<'a> {
642 pub prefix: &'a BlockHeaderPrefix,
644 pub result: &'a BlockHeaderResult,
646 pub consensus_info: &'a BlockHeaderConsensusInfo,
648 pub seal: BlockHeaderSeal<'a>,
650}
651
652#[derive(Debug, Clone, Yokeable)]
654#[non_exhaustive]
656pub struct BeaconChainHeader<'a> {
657 shared: SharedBlockHeader<'a>,
659 intermediate_shard_blocks_root: &'a Blake3Hash,
661 consensus_parameters: BlockHeaderConsensusParameters<'a>,
663 pre_seal_bytes: &'a [u8],
665 #[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 #[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 #[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 #[inline(always)]
773 pub fn shared(&self) -> &SharedBlockHeader<'a> {
774 &self.shared
775 }
776
777 #[inline(always)]
782 pub fn intermediate_shard_blocks_root(&self) -> &'a Blake3Hash {
783 self.intermediate_shard_blocks_root
784 }
785
786 #[inline(always)]
788 pub fn consensus_parameters(&self) -> &BlockHeaderConsensusParameters<'a> {
789 &self.consensus_parameters
790 }
791
792 #[inline]
794 pub fn pre_seal_hash(&self) -> Blake3Hash {
795 Blake3Hash::from(blake3::hash(self.pre_seal_bytes))
796 }
797
798 #[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 #[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#[derive(Debug, Clone, Yokeable)]
875#[non_exhaustive]
877pub struct IntermediateShardHeader<'a> {
878 shared: SharedBlockHeader<'a>,
880 beacon_chain_info: &'a BlockHeaderBeaconChainInfo,
882 leaf_shard_blocks_root: &'a Blake3Hash,
884 pre_seal_bytes: &'a [u8],
886 #[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 #[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 #[cfg(feature = "alloc")]
981 #[inline(always)]
982 pub(crate) fn bytes(&self) -> &'a [u8] {
983 self.bytes
984 }
985
986 #[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 #[inline(always)]
1000 pub fn shared(&self) -> &SharedBlockHeader<'a> {
1001 &self.shared
1002 }
1003
1004 #[inline(always)]
1006 pub fn beacon_chain_info(&self) -> &'a BlockHeaderBeaconChainInfo {
1007 self.beacon_chain_info
1008 }
1009
1010 #[inline(always)]
1016 pub fn leaf_shard_blocks_root(&self) -> &'a Blake3Hash {
1017 self.leaf_shard_blocks_root
1018 }
1019
1020 #[inline]
1022 pub fn pre_seal_hash(&self) -> Blake3Hash {
1023 Blake3Hash::from(blake3::hash(self.pre_seal_bytes))
1024 }
1025
1026 #[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 #[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#[derive(Debug, Clone, Yokeable)]
1103#[non_exhaustive]
1105pub struct LeafShardHeader<'a> {
1106 shared: SharedBlockHeader<'a>,
1108 beacon_chain_info: &'a BlockHeaderBeaconChainInfo,
1110 pre_seal_bytes: &'a [u8],
1112 #[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 #[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 #[cfg(feature = "alloc")]
1203 #[inline(always)]
1204 pub(crate) fn bytes(&self) -> &'a [u8] {
1205 self.bytes
1206 }
1207
1208 #[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 #[inline(always)]
1222 pub fn shared(&self) -> &SharedBlockHeader<'a> {
1223 &self.shared
1224 }
1225
1226 #[inline(always)]
1228 pub fn beacon_chain_info(&self) -> &'a BlockHeaderBeaconChainInfo {
1229 self.beacon_chain_info
1230 }
1231
1232 #[inline]
1234 pub fn pre_seal_hash(&self) -> Blake3Hash {
1235 Blake3Hash::from(blake3::hash(self.pre_seal_bytes))
1236 }
1237
1238 #[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 #[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#[derive(Debug, Clone, From)]
1316pub enum BlockHeader<'a> {
1317 BeaconChain(BeaconChainHeader<'a>),
1319 IntermediateShard(IntermediateShardHeader<'a>),
1321 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 #[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 #[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 #[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 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 #[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 #[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 #[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 #[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 #[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}