1#[cfg(feature = "alloc")]
4pub mod owned;
5
6#[cfg(feature = "alloc")]
7use crate::block::body::owned::{
8 GenericOwnedBlockBody, OwnedBeaconChainBody, OwnedBlockBody, OwnedIntermediateShardBody,
9 OwnedLeafShardBody,
10};
11use crate::block::header::{IntermediateShardHeader, LeafShardHeader};
12use crate::block::{BlockNumber, align_to_and_ensure_zero_padding};
13use crate::hashes::Blake3Hash;
14use crate::pot::PotCheckpoints;
15use crate::segments::{LocalSegmentIndex, SegmentRoot};
16use crate::shard::{RealShardKind, ShardIndex};
17use crate::transaction::Transaction;
18use crate::trees::{
19 BeaconChainBodyMerkleTree, ChildIntermediateShardBlocksMerkleTree,
20 ChildLeafShardBlocksMerkleTree, IntermediateShardBodyMerkleTree,
21 IntermediateShardsSegmentsMerkleTree, LeafShardBodyMerkleTree, LeafShardsSegmentsMerkleTree,
22 OwnSegmentsMerkleTree, SegmentRootsMerkleTree, ShardOwnSegmentsMerkleTree,
23 TransactionsMerkleTree,
24};
25#[cfg(feature = "alloc")]
26use ab_aligned_buffer::SharedAlignedBuffer;
27use ab_blake3::{BLOCK_LEN, single_block_hash};
28use ab_io_type::alignment::Alignment;
29use ab_io_type::trivial_type::TrivialType;
30use ab_io_type::unaligned::Unaligned;
31use core::iter::{Step, TrustedLen};
32use core::num::NonZeroU8;
33use core::{cmp, fmt, iter};
34use derive_more::From;
35use yoke::Yokeable;
36
37pub trait GenericBlockBody<'a>
39where
40 Self: Copy + fmt::Debug + Into<BlockBody<'a>> + Send + Sync,
41{
42 const SHARD_KIND: RealShardKind;
44
45 #[cfg(feature = "alloc")]
47 type Owned: GenericOwnedBlockBody<Body<'a> = Self>
48 where
49 Self: 'a;
50
51 #[cfg(feature = "alloc")]
58 fn to_owned(self) -> Self::Owned;
59
60 fn root(&self) -> Blake3Hash;
62}
63
64#[inline]
66pub fn compute_segments_root<'a, const MAX_SEGMENTS: u64, Iter>(segment_roots: Iter) -> Blake3Hash
67where
68 Iter: IntoIterator<Item = &'a SegmentRoot, IntoIter: TrustedLen>,
69{
70 let root = SegmentRootsMerkleTree::compute_root_only::<MAX_SEGMENTS, _, _>(
71 segment_roots.into_iter().copied(),
72 );
73
74 Blake3Hash::new(root.unwrap_or_default())
75}
76
77#[derive(Debug, Copy, Clone)]
83pub struct OwnSegments<'a> {
84 pub mut(self) first_local_segment_index: LocalSegmentIndex,
86 pub mut(self) segment_roots: &'a [SegmentRoot],
88}
89
90impl<'a> OwnSegments<'a> {
91 #[inline]
96 pub fn new(
97 first_local_segment_index: LocalSegmentIndex,
98 segment_roots: &'a [SegmentRoot],
99 ) -> Option<Self> {
100 if segment_roots.is_empty()
101 || segment_roots.len() > usize::from(u8::MAX)
102 || LocalSegmentIndex::forward_checked(first_local_segment_index, segment_roots.len())
103 .is_none()
104 {
105 return None;
106 }
107
108 Some(Self::new_unchecked(
109 first_local_segment_index,
110 segment_roots,
111 ))
112 }
113
114 #[inline(always)]
121 const fn new_unchecked(
122 first_local_segment_index: LocalSegmentIndex,
123 segment_roots: &'a [SegmentRoot],
124 ) -> Self {
125 Self {
126 first_local_segment_index,
127 segment_roots,
128 }
129 }
130
131 #[inline(always)]
133 pub fn num_segment_roots(&self) -> NonZeroU8 {
134 u8::try_from(self.segment_roots.len())
135 .ok()
136 .and_then(NonZeroU8::new)
137 .expect("Constructors ensure between 1 and `u8::MAX` segment roots; qed")
138 }
139
140 #[inline]
142 pub fn iter(
143 &self,
144 ) -> impl ExactSizeIterator<Item = (LocalSegmentIndex, &'a SegmentRoot)> + TrustedLen + use<'a>
145 {
146 let first_local_segment_index = self.first_local_segment_index;
147
148 self.segment_roots
149 .iter()
150 .enumerate()
151 .map(move |(offset, segment_root)| {
152 let local_segment_index =
153 LocalSegmentIndex::forward_checked(first_local_segment_index, offset).expect(
154 "`Self::new()` and parsers check that the index after the last root fits \
155 into `u64`; qed",
156 );
157
158 (local_segment_index, segment_root)
159 })
160 }
161
162 #[inline]
164 pub fn root(&self) -> Blake3Hash {
165 let root = OwnSegmentsMerkleTree::compute_root_only(&[
166 single_block_hash(self.first_local_segment_index.as_bytes())
167 .expect("Less than a single block worth of bytes; qed"),
168 *compute_segments_root::<{ u64::from(u8::MAX) }, _>(self.segment_roots),
169 ]);
170
171 Blake3Hash::new(root)
172 }
173
174 #[inline]
180 pub fn root_with_shard_index(&self, shard_index: ShardIndex) -> Blake3Hash {
181 let root = ShardOwnSegmentsMerkleTree::compute_root_only(&[
182 {
183 const {
184 assert!((ShardIndex::SIZE + LocalSegmentIndex::SIZE) as usize <= BLOCK_LEN);
185 }
186 let mut pair = [0u8; (ShardIndex::SIZE + LocalSegmentIndex::SIZE) as usize];
187 pair[..ShardIndex::SIZE as usize].copy_from_slice(shard_index.as_bytes());
188 pair[ShardIndex::SIZE as usize..]
189 .copy_from_slice(self.first_local_segment_index.as_bytes());
190
191 single_block_hash(&pair).expect("Less than a single block worth of bytes; qed")
192 },
193 *compute_segments_root::<{ u64::from(u8::MAX) }, _>(self.segment_roots),
194 ]);
195
196 Blake3Hash::new(root)
197 }
198}
199
200fn compute_leaf_shards_segments_root<'a, Iter>(
206 num_leaf_shard_blocks: u16,
207 leaf_shard_blocks_segments: Iter,
208) -> Option<Blake3Hash>
209where
210 Iter: IntoIterator<Item = (u16, ShardIndex, OwnSegments<'a>)>,
211{
212 let mut leaves =
213 leaf_shard_blocks_segments
214 .into_iter()
215 .map(|(position, shard_index, own_segments)| {
216 (
217 u64::from(position),
218 *own_segments.root_with_shard_index(shard_index),
219 )
220 });
221
222 if num_leaf_shard_blocks == 0 {
223 return leaves.next().is_none().then_some(Blake3Hash::default());
224 }
225
226 LeafShardsSegmentsMerkleTree::compute_root_only_sparse::<{ u64::from(u16::MAX) }, _, _>(
227 u64::from(num_leaf_shard_blocks),
228 leaves,
229 )
230 .map(Blake3Hash::new)
231}
232
233fn intermediate_shard_body_root(
235 own_segments: Option<&OwnSegments<'_>>,
236 leaf_shards_segments_root: &Blake3Hash,
237 leaf_shard_blocks_root: &Blake3Hash,
238) -> Blake3Hash {
239 Blake3Hash::new(IntermediateShardBodyMerkleTree::compute_root_only_array(&[
240 *own_segments.map_or_default(OwnSegments::root),
241 **leaf_shards_segments_root,
242 **leaf_shard_blocks_root,
243 ]))
244}
245
246#[derive(Debug, Copy, Clone)]
249struct IntermediateShardBlockCounts {
250 num_own_segment_roots: u8,
251 num_leaf_shard_blocks: u16,
252 num_leaf_shard_blocks_with_segments: u16,
253}
254
255impl IntermediateShardBlockCounts {
256 const SIZE: usize = size_of::<u8>() + 2 * size_of::<u16>();
258
259 #[inline(always)]
266 fn from_bytes(bytes: [u8; Self::SIZE]) -> Self {
267 let [
268 num_own_segment_roots,
269 num_leaf_shard_blocks_0,
270 num_leaf_shard_blocks_1,
271 num_leaf_shard_blocks_with_segments_0,
272 num_leaf_shard_blocks_with_segments_1,
273 ] = bytes;
274
275 Self {
276 num_own_segment_roots,
277 num_leaf_shard_blocks: u16::from_le_bytes([
278 num_leaf_shard_blocks_0,
279 num_leaf_shard_blocks_1,
280 ]),
281 num_leaf_shard_blocks_with_segments: u16::from_le_bytes([
282 num_leaf_shard_blocks_with_segments_0,
283 num_leaf_shard_blocks_with_segments_1,
284 ]),
285 }
286 }
287
288 #[cfg(feature = "alloc")]
290 #[inline(always)]
291 fn to_bytes(self) -> [u8; Self::SIZE] {
292 let Self {
293 num_own_segment_roots,
294 num_leaf_shard_blocks,
295 num_leaf_shard_blocks_with_segments,
296 } = self;
297 let [num_leaf_shard_blocks_0, num_leaf_shard_blocks_1] =
298 num_leaf_shard_blocks.to_le_bytes();
299 let [
300 num_leaf_shard_blocks_with_segments_0,
301 num_leaf_shard_blocks_with_segments_1,
302 ] = num_leaf_shard_blocks_with_segments.to_le_bytes();
303
304 [
305 num_own_segment_roots,
306 num_leaf_shard_blocks_0,
307 num_leaf_shard_blocks_1,
308 num_leaf_shard_blocks_with_segments_0,
309 num_leaf_shard_blocks_with_segments_1,
310 ]
311 }
312}
313
314#[derive(Debug, Clone)]
316#[expect(
317 clippy::partial_pub_fields,
318 reason = "Intentionally exposing immediately decoded fields above and hiding the rest of the implementation"
319)]
320pub struct IntermediateShardBlockInfo<'a> {
321 pub mut(self) header: IntermediateShardHeader<'a>,
323 pub mut(self) own_segments: Option<OwnSegments<'a>>,
325 num_leaf_shard_blocks: u16,
326 num_leaf_shard_blocks_with_segments: u16,
327 leaf_shards_segments_bytes: &'a [u8],
328}
329
330impl<'a> IntermediateShardBlockInfo<'a> {
331 #[inline]
340 fn try_from_record(
341 counts: IntermediateShardBlockCounts,
342 mut bytes: &'a [u8],
343 ) -> Option<(Self, &'a [u8])> {
344 let IntermediateShardBlockCounts {
345 num_own_segment_roots,
346 num_leaf_shard_blocks,
347 num_leaf_shard_blocks_with_segments,
348 } = counts;
349
350 let header;
351 (header, bytes) = IntermediateShardHeader::try_from_bytes(bytes)?;
352
353 let own_segments = if num_own_segment_roots > 0 {
354 let first_local_segment_index;
355 (first_local_segment_index, bytes) = Unaligned::<LocalSegmentIndex>::from_bytes(bytes)?;
356
357 let own_segment_roots;
358 (own_segment_roots, bytes) =
359 SegmentRoot::slice_from_bytes(bytes, usize::from(num_own_segment_roots))?;
360
361 Some(OwnSegments::new(
362 first_local_segment_index.as_inner(),
363 own_segment_roots,
364 )?)
365 } else {
366 None
367 };
368
369 let leaf_shards_segments_start = bytes;
370
371 let leaf_shard_segment_roots_counts = bytes
372 .split_off(..usize::from(num_leaf_shard_blocks_with_segments) * size_of::<u8>())?;
373
374 let mut next_position = 0;
377 for &num_own_segment_roots in leaf_shard_segment_roots_counts {
378 let num_own_segment_roots = NonZeroU8::new(num_own_segment_roots)?;
379 let position;
380 (position, bytes) = bytes.split_first_chunk::<{ size_of::<u16>() }>()?;
381 let position = u16::from_le_bytes(*position);
382 if position < next_position || position >= num_leaf_shard_blocks {
383 return None;
384 }
385 next_position = position + 1;
386 (_, bytes) = Unaligned::<ShardIndex>::from_bytes(bytes)?;
387 let first_local_segment_index;
388 (first_local_segment_index, bytes) = Unaligned::<LocalSegmentIndex>::from_bytes(bytes)?;
389 let _next_local_segment_index = LocalSegmentIndex::forward_checked(
391 first_local_segment_index.as_inner(),
392 usize::from(num_own_segment_roots.get()),
393 )?;
394 (_, bytes) =
395 SegmentRoot::slice_from_bytes(bytes, usize::from(num_own_segment_roots.get()))?;
396 }
397
398 let leaf_shards_segments_bytes =
399 &leaf_shards_segments_start[..leaf_shards_segments_start.len() - bytes.len()];
400
401 let remainder = align_to_and_ensure_zero_padding(bytes, Alignment::of::<u64>())?;
402
403 let info = Self {
404 header,
405 own_segments,
406 num_leaf_shard_blocks,
407 num_leaf_shard_blocks_with_segments,
408 leaf_shards_segments_bytes,
409 };
410
411 Some((info, remainder))
412 }
413
414 #[cfg(feature = "alloc")]
430 #[inline]
431 fn try_from_standalone_bytes(mut bytes: &'a [u8]) -> Option<(Self, &'a [u8])> {
432 let counts;
433 (counts, bytes) = bytes.split_first_chunk::<{ IntermediateShardBlockCounts::SIZE }>()?;
434
435 let bytes = align_to_and_ensure_zero_padding(bytes, Alignment::of::<u64>())?;
436
437 let (info, remainder) =
438 Self::try_from_record(IntermediateShardBlockCounts::from_bytes(*counts), bytes)?;
439
440 if !info.is_internally_consistent() {
441 return None;
442 }
443
444 Some((info, remainder))
445 }
446
447 #[inline]
451 fn is_internally_consistent(&self) -> bool {
452 let shard_index = self.header.prefix.shard_index;
453 let mut last_leaf_shard_info = None::<(ShardIndex, LocalSegmentIndex)>;
454
455 if !self
457 .leaf_shards_segments()
458 .all(|(_position, leaf_shard_index, own_segments)| {
459 if !leaf_shard_index.is_child_of(shard_index) {
460 return false;
461 }
462
463 if let Some((last_leaf_shard_index, last_leaf_shard_first_local_segment_index)) =
464 last_leaf_shard_info
465 {
466 match last_leaf_shard_index.cmp(&leaf_shard_index) {
467 cmp::Ordering::Less => {
468 }
470 cmp::Ordering::Equal => {
471 if last_leaf_shard_first_local_segment_index
472 >= own_segments.first_local_segment_index
473 {
474 return false;
475 }
476 }
477 cmp::Ordering::Greater => {
478 return false;
479 }
480 }
481 }
482 last_leaf_shard_info
483 .replace((leaf_shard_index, own_segments.first_local_segment_index));
484
485 true
486 })
487 {
488 return false;
489 }
490
491 let body_root = intermediate_shard_body_root(
494 self.own_segments.as_ref(),
495 &self.leaf_shards_segments_root(),
496 self.header.leaf_shard_blocks_root(),
497 );
498 body_root == self.header.result.body_root
499 }
500
501 #[inline(always)]
503 pub const fn num_leaf_shard_blocks(&self) -> u16 {
504 self.num_leaf_shard_blocks
505 }
506
507 #[inline(always)]
509 pub const fn num_leaf_shard_blocks_with_segments(&self) -> u16 {
510 self.num_leaf_shard_blocks_with_segments
511 }
512
513 #[inline]
516 pub fn leaf_shards_segments(
517 &self,
518 ) -> impl ExactSizeIterator<Item = (u16, ShardIndex, OwnSegments<'a>)> + TrustedLen + use<'a>
519 {
520 let (counts, mut remainder) = self
521 .leaf_shards_segments_bytes
522 .split_at_checked(
523 usize::from(self.num_leaf_shard_blocks_with_segments) * size_of::<u8>(),
524 )
525 .expect("Already checked in constructor; qed");
526 counts.iter().map(move |&num_own_segment_roots| {
527 let num_own_segment_roots = usize::from(num_own_segment_roots);
528
529 let position;
530 (position, remainder) = remainder
531 .split_first_chunk::<{ size_of::<u16>() }>()
532 .expect("Already checked in constructor; qed");
533 let position = u16::from_le_bytes(*position);
534
535 let shard_index;
536 (shard_index, remainder) = Unaligned::<ShardIndex>::from_bytes(remainder)
537 .expect("Already checked in constructor; qed");
538 let shard_index = shard_index.as_inner();
539
540 let first_local_segment_index;
541 (first_local_segment_index, remainder) =
542 Unaligned::<LocalSegmentIndex>::from_bytes(remainder)
543 .expect("Already checked in constructor; qed");
544 let first_local_segment_index = first_local_segment_index.as_inner();
545
546 let own_segment_roots;
547 (own_segment_roots, remainder) =
548 SegmentRoot::slice_from_bytes(remainder, num_own_segment_roots)
549 .expect("Already checked in constructor; qed");
550
551 (
552 position,
553 shard_index,
554 OwnSegments::new_unchecked(first_local_segment_index, own_segment_roots),
555 )
556 })
557 }
558
559 #[inline]
561 fn leaf_shards_segments_root(&self) -> Blake3Hash {
562 compute_leaf_shards_segments_root(self.num_leaf_shard_blocks, self.leaf_shards_segments())
563 .expect("Positions are checked in constructor; qed")
564 }
565}
566
567#[derive(Debug, Copy, Clone)]
569pub struct IntermediateShardBlocksInfo<'a> {
570 num_blocks: usize,
571 bytes: &'a [u8],
572}
573
574impl<'a> IntermediateShardBlocksInfo<'a> {
575 #[inline]
608 pub fn try_from_bytes(mut bytes: &'a [u8]) -> Option<(Self, &'a [u8])> {
609 let num_blocks;
610 (num_blocks, bytes) = bytes.split_first_chunk::<{ size_of::<u16>() }>()?;
611 let num_blocks = usize::from(u16::from_le_bytes(*num_blocks));
612
613 let bytes_start = bytes;
614
615 let counts = bytes.split_off(..num_blocks * IntermediateShardBlockCounts::SIZE)?;
616 let (counts, _) = counts.as_chunks::<{ IntermediateShardBlockCounts::SIZE }>();
617
618 let mut remainder = align_to_and_ensure_zero_padding(bytes, Alignment::of::<u64>())?;
619
620 for block_counts in counts {
621 let intermediate_shard_block;
622 (intermediate_shard_block, remainder) = IntermediateShardBlockInfo::try_from_record(
623 IntermediateShardBlockCounts::from_bytes(*block_counts),
624 remainder,
625 )?;
626
627 if !intermediate_shard_block.is_internally_consistent() {
628 return None;
629 }
630 }
631
632 let info = Self {
633 num_blocks,
634 bytes: &bytes_start[..bytes_start.len() - remainder.len()],
635 };
636
637 if !info.is_internally_consistent() {
638 return None;
639 }
640
641 Some((info, remainder))
642 }
643
644 #[inline]
649 fn is_internally_consistent(&self) -> bool {
650 let mut last_intermediate_shard_info =
651 None::<(ShardIndex, BlockNumber, Option<LocalSegmentIndex>)>;
652
653 self.iter().all(|intermediate_shard_block| {
654 let shard_index = intermediate_shard_block.header.prefix.shard_index;
655
656 if let Some((
658 last_intermediate_shard_index,
659 last_intermediate_shard_block_number,
660 last_intermediate_shard_first_local_segment_index,
661 )) = last_intermediate_shard_info
662 {
663 match last_intermediate_shard_index.cmp(&shard_index) {
664 cmp::Ordering::Less => {
665 last_intermediate_shard_info.replace((
666 shard_index,
667 intermediate_shard_block.header.prefix.number,
668 intermediate_shard_block
669 .own_segments
670 .as_ref()
671 .map(|own_segments| own_segments.first_local_segment_index),
672 ));
673 }
674 cmp::Ordering::Equal => {
675 if last_intermediate_shard_block_number
676 >= intermediate_shard_block.header.prefix.number
677 {
678 return false;
679 }
680 if let Some(own_segments) = &intermediate_shard_block.own_segments {
681 if let Some(last_intermediate_shard_first_local_segment_index) =
682 last_intermediate_shard_first_local_segment_index
683 && last_intermediate_shard_first_local_segment_index
684 >= own_segments.first_local_segment_index
685 {
686 return false;
687 }
688
689 last_intermediate_shard_info.replace((
690 shard_index,
691 intermediate_shard_block.header.prefix.number,
692 Some(own_segments.first_local_segment_index),
693 ));
694 } else {
695 last_intermediate_shard_info.replace((
696 shard_index,
697 intermediate_shard_block.header.prefix.number,
698 last_intermediate_shard_first_local_segment_index,
699 ));
700 }
701 }
702 cmp::Ordering::Greater => {
703 return false;
704 }
705 }
706 } else {
707 last_intermediate_shard_info.replace((
708 shard_index,
709 intermediate_shard_block.header.prefix.number,
710 intermediate_shard_block
711 .own_segments
712 .as_ref()
713 .map(|own_segments| own_segments.first_local_segment_index),
714 ));
715 }
716
717 true
718 })
719 }
720
721 #[inline]
723 pub fn iter(
724 &self,
725 ) -> impl ExactSizeIterator<Item = IntermediateShardBlockInfo<'a>> + TrustedLen + use<'a> {
726 let (counts, remainder) = self
727 .bytes
728 .split_at_checked(self.num_blocks * IntermediateShardBlockCounts::SIZE)
729 .expect("Already checked in constructor; qed");
730 let (counts, _) = counts.as_chunks::<{ IntermediateShardBlockCounts::SIZE }>();
731 let mut remainder = align_to_and_ensure_zero_padding(remainder, Alignment::of::<u64>())
732 .expect("Already checked in constructor; qed");
733
734 counts.iter().map(move |block_counts| {
735 let intermediate_shard_block;
736 (intermediate_shard_block, remainder) = IntermediateShardBlockInfo::try_from_record(
737 IntermediateShardBlockCounts::from_bytes(*block_counts),
738 remainder,
739 )
740 .expect("Already checked in constructor; qed");
741
742 intermediate_shard_block
743 })
744 }
745
746 #[inline(always)]
748 pub const fn len(&self) -> usize {
749 self.num_blocks
750 }
751
752 #[inline(always)]
754 pub const fn is_empty(&self) -> bool {
755 self.num_blocks == 0
756 }
757
758 #[inline]
762 pub fn segments_root(&self) -> Blake3Hash {
763 let root = IntermediateShardsSegmentsMerkleTree::compute_root_only::<
764 { u64::from(u16::MAX) },
765 _,
766 _,
767 >(self.iter().map(|shard_block_info| {
768 IntermediateShardBodyMerkleTree::compute_root_only_array(&[
772 *shard_block_info
773 .own_segments
774 .as_ref()
775 .map_or_default(OwnSegments::root),
776 *shard_block_info.leaf_shards_segments_root(),
777 ])
778 }))
779 .unwrap_or_default();
780
781 Blake3Hash::new(root)
782 }
783
784 #[inline]
788 pub fn headers_root(&self) -> Blake3Hash {
789 let root = ChildIntermediateShardBlocksMerkleTree::compute_root_only::<
790 { u64::from(u16::MAX) },
791 _,
792 _,
793 >(
794 self.iter()
795 .map(|shard_block_info| **shard_block_info.header.root()),
796 )
797 .unwrap_or_default();
798
799 Blake3Hash::new(root)
800 }
801}
802
803#[derive(Debug, Copy, Clone, Yokeable)]
805#[non_exhaustive]
807pub struct BeaconChainBody<'a> {
808 own_segments: Option<OwnSegments<'a>>,
810 intermediate_shard_blocks: IntermediateShardBlocksInfo<'a>,
812 pot_checkpoints: &'a [PotCheckpoints],
815 #[cfg(feature = "alloc")]
817 bytes: &'a [u8],
818}
819
820impl<'a> GenericBlockBody<'a> for BeaconChainBody<'a> {
821 const SHARD_KIND: RealShardKind = RealShardKind::BeaconChain;
822
823 #[cfg(feature = "alloc")]
824 type Owned = OwnedBeaconChainBody;
825
826 #[cfg(feature = "alloc")]
827 #[inline(always)]
828 fn to_owned(self) -> Self::Owned {
829 self.to_owned()
830 }
831
832 #[inline(always)]
833 fn root(&self) -> Blake3Hash {
834 self.root()
835 }
836}
837
838impl<'a> BeaconChainBody<'a> {
839 #[inline]
855 pub fn try_from_bytes(mut bytes: &'a [u8]) -> Option<(Self, &'a [u8])> {
856 if !Alignment::MAX.is_slice_aligned(bytes) {
857 return None;
858 }
859
860 let bytes_start = bytes;
861
862 let num_pot_checkpoints;
863 (num_pot_checkpoints, bytes) = u32::from_bytes(bytes)?;
864 let num_pot_checkpoints = *num_pot_checkpoints as usize;
865
866 let num_own_segment_roots = usize::from(*bytes.split_off_first()?);
867
868 let own_segments = if num_own_segment_roots > 0 {
869 let first_local_segment_index;
870 (first_local_segment_index, bytes) = Unaligned::<LocalSegmentIndex>::from_bytes(bytes)?;
871
872 let own_segment_roots;
873 (own_segment_roots, bytes) =
874 SegmentRoot::slice_from_bytes(bytes, num_own_segment_roots)?;
875
876 Some(OwnSegments::new(
877 first_local_segment_index.as_inner(),
878 own_segment_roots,
879 )?)
880 } else {
881 None
882 };
883
884 let (intermediate_shard_blocks, remainder) =
885 IntermediateShardBlocksInfo::try_from_bytes(bytes)?;
886
887 let (pot_checkpoints, remainder) =
888 PotCheckpoints::slice_from_bytes(remainder, num_pot_checkpoints)?;
889
890 let bytes = &bytes_start[..bytes_start.len() - remainder.len()];
891 if u32::try_from(bytes.len()).is_err() {
896 return None;
897 }
898
899 let body = Self {
900 own_segments,
901 intermediate_shard_blocks,
902 pot_checkpoints,
903 #[cfg(feature = "alloc")]
904 bytes,
905 };
906
907 Some((body, remainder))
908 }
909
910 #[cfg(feature = "alloc")]
917 #[inline(always)]
918 pub fn to_owned(self) -> OwnedBeaconChainBody {
919 OwnedBeaconChainBody::from_buffer(SharedAlignedBuffer::from_bytes(self.bytes)).expect(
920 "The parser accepted these bytes at a 16-byte aligned address, as in the buffer; qed",
921 )
922 }
923
924 #[inline(always)]
926 pub fn own_segments(&self) -> Option<OwnSegments<'a>> {
927 self.own_segments
928 }
929
930 #[inline(always)]
932 pub fn intermediate_shard_blocks(&self) -> &IntermediateShardBlocksInfo<'a> {
933 &self.intermediate_shard_blocks
934 }
935
936 #[inline(always)]
939 pub fn pot_checkpoints(&self) -> &'a [PotCheckpoints] {
940 self.pot_checkpoints
941 }
942
943 #[inline]
945 pub fn root(&self) -> Blake3Hash {
946 self.root_with_intermediate_shard_blocks_root(
947 &self.intermediate_shard_blocks.headers_root(),
948 )
949 }
950
951 #[inline]
954 pub(crate) fn root_with_intermediate_shard_blocks_root(
955 &self,
956 intermediate_shard_blocks_root: &Blake3Hash,
957 ) -> Blake3Hash {
958 let root = BeaconChainBodyMerkleTree::compute_root_only(&[
959 *self.own_segments.as_ref().map_or_default(OwnSegments::root),
960 *self.intermediate_shard_blocks.segments_root(),
961 **intermediate_shard_blocks_root,
962 blake3::hash(PotCheckpoints::slice_as_bytes(self.pot_checkpoints)).into(),
963 ]);
964
965 Blake3Hash::new(root)
966 }
967}
968
969fn leaf_shard_body_root(
971 own_segments: Option<&OwnSegments<'_>>,
972 transactions_root: &Blake3Hash,
973) -> Blake3Hash {
974 Blake3Hash::new(LeafShardBodyMerkleTree::compute_root_only(&[
975 *own_segments.map_or_default(OwnSegments::root),
976 **transactions_root,
977 ]))
978}
979
980#[derive(Debug, Clone)]
982pub struct LeafShardBlockInfo<'a> {
983 pub mut(self) header: LeafShardHeader<'a>,
985 pub mut(self) transactions_root: &'a Blake3Hash,
987 pub mut(self) own_segments: Option<OwnSegments<'a>>,
989}
990
991impl<'a> LeafShardBlockInfo<'a> {
992 #[inline]
1001 fn try_from_record(num_own_segment_roots: u8, mut bytes: &'a [u8]) -> Option<(Self, &'a [u8])> {
1002 let header;
1003 (header, bytes) = LeafShardHeader::try_from_bytes(bytes)?;
1004
1005 bytes = align_to_and_ensure_zero_padding(bytes, Alignment::of::<u64>())?;
1006
1007 let transactions_root;
1008 (transactions_root, bytes) = Blake3Hash::from_bytes(bytes)?;
1009
1010 let own_segments = if num_own_segment_roots > 0 {
1011 let first_local_segment_index;
1012 (first_local_segment_index, bytes) = LocalSegmentIndex::from_bytes(bytes)?;
1013
1014 let own_segment_roots;
1015 (own_segment_roots, bytes) =
1016 SegmentRoot::slice_from_bytes(bytes, usize::from(num_own_segment_roots))?;
1017
1018 Some(OwnSegments::new(
1019 *first_local_segment_index,
1020 own_segment_roots,
1021 )?)
1022 } else {
1023 None
1024 };
1025
1026 let info = Self {
1027 header,
1028 transactions_root,
1029 own_segments,
1030 };
1031
1032 Some((info, bytes))
1033 }
1034
1035 #[cfg(feature = "alloc")]
1049 #[inline]
1050 fn try_from_standalone_bytes(mut bytes: &'a [u8]) -> Option<(Self, &'a [u8])> {
1051 let num_own_segment_roots = *bytes.split_off_first()?;
1052
1053 let bytes = align_to_and_ensure_zero_padding(bytes, Alignment::of::<u64>())?;
1054
1055 let (info, remainder) = Self::try_from_record(num_own_segment_roots, bytes)?;
1056
1057 if !info.is_internally_consistent() {
1058 return None;
1059 }
1060
1061 Some((info, remainder))
1062 }
1063
1064 #[inline]
1066 fn is_internally_consistent(&self) -> bool {
1067 leaf_shard_body_root(self.own_segments.as_ref(), self.transactions_root)
1069 == self.header.result.body_root
1070 }
1071}
1072
1073#[derive(Debug, Copy, Clone)]
1075pub struct LeafShardBlocksInfo<'a> {
1076 num_blocks: u16,
1077 bytes: &'a [u8],
1078}
1079
1080impl<'a> LeafShardBlocksInfo<'a> {
1081 #[inline]
1103 pub fn try_from_bytes(mut bytes: &'a [u8]) -> Option<(Self, &'a [u8])> {
1104 let num_blocks;
1105 (num_blocks, bytes) = bytes.split_first_chunk::<{ size_of::<u16>() }>()?;
1106 let num_blocks = u16::from_le_bytes(*num_blocks);
1107
1108 let bytes_start = bytes;
1109
1110 let counts = bytes.split_off(..usize::from(num_blocks) * size_of::<u8>())?;
1111
1112 let mut remainder = align_to_and_ensure_zero_padding(bytes, Alignment::of::<u64>())?;
1113
1114 for &num_own_segment_roots in counts {
1115 let leaf_shard_block;
1116 (leaf_shard_block, remainder) =
1117 LeafShardBlockInfo::try_from_record(num_own_segment_roots, remainder)?;
1118
1119 if !leaf_shard_block.is_internally_consistent() {
1120 return None;
1121 }
1122 }
1123
1124 let info = Self {
1125 num_blocks,
1126 bytes: &bytes_start[..bytes_start.len() - remainder.len()],
1127 };
1128
1129 if !info.is_internally_consistent() {
1130 return None;
1131 }
1132
1133 Some((info, remainder))
1134 }
1135
1136 #[inline]
1141 fn is_internally_consistent(&self) -> bool {
1142 let mut last_leaf_shard_info = None::<(ShardIndex, BlockNumber, Option<LocalSegmentIndex>)>;
1143
1144 self.iter().all(|leaf_shard_block| {
1145 let shard_index = leaf_shard_block.header.prefix.shard_index;
1146
1147 if let Some((
1149 last_leaf_shard_index,
1150 last_leaf_shard_block_number,
1151 last_leaf_shard_first_local_segment_index,
1152 )) = last_leaf_shard_info
1153 {
1154 match last_leaf_shard_index.cmp(&shard_index) {
1155 cmp::Ordering::Less => {
1156 last_leaf_shard_info.replace((
1157 shard_index,
1158 leaf_shard_block.header.prefix.number,
1159 leaf_shard_block
1160 .own_segments
1161 .as_ref()
1162 .map(|own_segments| own_segments.first_local_segment_index),
1163 ));
1164 }
1165 cmp::Ordering::Equal => {
1166 if last_leaf_shard_block_number >= leaf_shard_block.header.prefix.number {
1167 return false;
1168 }
1169 if let Some(own_segments) = &leaf_shard_block.own_segments {
1170 if let Some(last_leaf_shard_first_local_segment_index) =
1171 last_leaf_shard_first_local_segment_index
1172 && last_leaf_shard_first_local_segment_index
1173 >= own_segments.first_local_segment_index
1174 {
1175 return false;
1176 }
1177
1178 last_leaf_shard_info.replace((
1179 shard_index,
1180 leaf_shard_block.header.prefix.number,
1181 Some(own_segments.first_local_segment_index),
1182 ));
1183 } else {
1184 last_leaf_shard_info.replace((
1185 shard_index,
1186 leaf_shard_block.header.prefix.number,
1187 last_leaf_shard_first_local_segment_index,
1188 ));
1189 }
1190 }
1191 cmp::Ordering::Greater => {
1192 return false;
1193 }
1194 }
1195 } else {
1196 last_leaf_shard_info.replace((
1197 shard_index,
1198 leaf_shard_block.header.prefix.number,
1199 leaf_shard_block
1200 .own_segments
1201 .as_ref()
1202 .map(|own_segments| own_segments.first_local_segment_index),
1203 ));
1204 }
1205
1206 true
1207 })
1208 }
1209
1210 #[inline]
1212 pub fn iter(
1213 &self,
1214 ) -> impl ExactSizeIterator<Item = LeafShardBlockInfo<'a>> + TrustedLen + use<'a> {
1215 let (counts, remainder) = self
1216 .bytes
1217 .split_at_checked(usize::from(self.num_blocks) * size_of::<u8>())
1218 .expect("Already checked in constructor; qed");
1219 let mut remainder = align_to_and_ensure_zero_padding(remainder, Alignment::of::<u64>())
1220 .expect("Already checked in constructor; qed");
1221
1222 counts.iter().map(move |&num_own_segment_roots| {
1223 let leaf_shard_block;
1224 (leaf_shard_block, remainder) =
1225 LeafShardBlockInfo::try_from_record(num_own_segment_roots, remainder)
1226 .expect("Already checked in constructor; qed");
1227
1228 leaf_shard_block
1229 })
1230 }
1231
1232 #[inline(always)]
1234 pub const fn len(&self) -> usize {
1235 self.num_blocks as usize
1236 }
1237
1238 #[inline(always)]
1240 pub const fn is_empty(&self) -> bool {
1241 self.num_blocks == 0
1242 }
1243
1244 #[inline]
1247 fn leaf_shards_segments(
1248 &self,
1249 ) -> impl Iterator<Item = (u16, ShardIndex, OwnSegments<'a>)> + use<'a> {
1250 self.iter()
1252 .zip(0..)
1253 .filter_map(|(shard_block_info, position)| {
1254 shard_block_info.own_segments.map(|own_segments| {
1255 (
1256 position,
1257 shard_block_info.header.prefix.shard_index,
1258 own_segments,
1259 )
1260 })
1261 })
1262 }
1263
1264 #[inline]
1268 pub fn segments_root(&self) -> Blake3Hash {
1269 compute_leaf_shards_segments_root(self.num_blocks, self.leaf_shards_segments())
1270 .expect("Positions are strictly increasing and smaller than the number of blocks; qed")
1271 }
1272
1273 #[inline]
1277 pub fn headers_root(&self) -> Blake3Hash {
1278 let root =
1279 ChildLeafShardBlocksMerkleTree::compute_root_only::<{ u64::from(u16::MAX) }, _, _>(
1280 self.iter()
1281 .map(|shard_block_info| **shard_block_info.header.root()),
1282 )
1283 .unwrap_or_default();
1284
1285 Blake3Hash::new(root)
1286 }
1287}
1288
1289#[derive(Debug, Copy, Clone, Yokeable)]
1291#[non_exhaustive]
1293pub struct IntermediateShardBody<'a> {
1294 own_segments: Option<OwnSegments<'a>>,
1296 leaf_shard_blocks: LeafShardBlocksInfo<'a>,
1298 #[cfg(feature = "alloc")]
1300 bytes: &'a [u8],
1301}
1302
1303impl<'a> GenericBlockBody<'a> for IntermediateShardBody<'a> {
1304 const SHARD_KIND: RealShardKind = RealShardKind::IntermediateShard;
1305
1306 #[cfg(feature = "alloc")]
1307 type Owned = OwnedIntermediateShardBody;
1308
1309 #[cfg(feature = "alloc")]
1310 #[inline(always)]
1311 fn to_owned(self) -> Self::Owned {
1312 self.to_owned()
1313 }
1314
1315 #[inline(always)]
1316 fn root(&self) -> Blake3Hash {
1317 self.root()
1318 }
1319}
1320
1321impl<'a> IntermediateShardBody<'a> {
1322 #[inline]
1336 pub fn try_from_bytes(mut bytes: &'a [u8]) -> Option<(Self, &'a [u8])> {
1337 if !Alignment::MAX.is_slice_aligned(bytes) {
1338 return None;
1339 }
1340
1341 let bytes_start = bytes;
1342
1343 let num_own_segment_roots = usize::from(*bytes.split_off_first()?);
1344
1345 let own_segments = if num_own_segment_roots > 0 {
1346 let first_local_segment_index;
1347 (first_local_segment_index, bytes) = Unaligned::<LocalSegmentIndex>::from_bytes(bytes)?;
1348
1349 let own_segment_roots;
1350 (own_segment_roots, bytes) =
1351 SegmentRoot::slice_from_bytes(bytes, num_own_segment_roots)?;
1352
1353 Some(OwnSegments::new(
1354 first_local_segment_index.as_inner(),
1355 own_segment_roots,
1356 )?)
1357 } else {
1358 None
1359 };
1360
1361 let (leaf_shard_blocks, remainder) = LeafShardBlocksInfo::try_from_bytes(bytes)?;
1362
1363 let bytes = &bytes_start[..bytes_start.len() - remainder.len()];
1364 if u32::try_from(bytes.len()).is_err() {
1369 return None;
1370 }
1371
1372 let body = Self {
1373 own_segments,
1374 leaf_shard_blocks,
1375 #[cfg(feature = "alloc")]
1376 bytes,
1377 };
1378
1379 Some((body, remainder))
1380 }
1381
1382 #[inline(always)]
1384 pub fn own_segments(&self) -> Option<OwnSegments<'a>> {
1385 self.own_segments
1386 }
1387
1388 #[inline(always)]
1390 pub fn leaf_shard_blocks(&self) -> &LeafShardBlocksInfo<'a> {
1391 &self.leaf_shard_blocks
1392 }
1393
1394 #[cfg(feature = "alloc")]
1401 #[inline(always)]
1402 pub fn to_owned(self) -> OwnedIntermediateShardBody {
1403 OwnedIntermediateShardBody::from_buffer(SharedAlignedBuffer::from_bytes(self.bytes)).expect(
1404 "The parser accepted these bytes at a 16-byte aligned address, as in the buffer; qed",
1405 )
1406 }
1407
1408 #[inline]
1410 pub fn root(&self) -> Blake3Hash {
1411 self.root_with_leaf_shard_blocks_root(&self.leaf_shard_blocks.headers_root())
1412 }
1413
1414 #[inline]
1417 pub(crate) fn root_with_leaf_shard_blocks_root(
1418 &self,
1419 leaf_shard_blocks_root: &Blake3Hash,
1420 ) -> Blake3Hash {
1421 intermediate_shard_body_root(
1422 self.own_segments.as_ref(),
1423 &self.leaf_shard_blocks.segments_root(),
1424 leaf_shard_blocks_root,
1425 )
1426 }
1427}
1428
1429#[derive(Debug, Copy, Clone)]
1431pub struct Transactions<'a> {
1432 num_transactions: usize,
1433 bytes: &'a [u8],
1434}
1435
1436impl<'a> Transactions<'a> {
1437 #[inline]
1451 pub fn try_from_bytes(mut bytes: &'a [u8]) -> Option<(Self, &'a [u8])> {
1452 let num_transactions;
1453 (num_transactions, bytes) = bytes.split_first_chunk::<{ size_of::<u32>() }>()?;
1454 let num_transactions = u32::from_le_bytes(*num_transactions) as usize;
1455
1456 let mut remainder = align_to_and_ensure_zero_padding(bytes, Alignment::MAX)?;
1457 let bytes_start = remainder;
1458
1459 for _ in 0..num_transactions {
1460 (_, remainder) = Transaction::try_from_bytes(remainder)?;
1461 remainder = align_to_and_ensure_zero_padding(remainder, Alignment::MAX)?;
1462 }
1463
1464 Some((
1465 Self {
1466 num_transactions,
1467 bytes: &bytes_start[..bytes_start.len() - remainder.len()],
1468 },
1469 remainder,
1470 ))
1471 }
1472
1473 #[inline]
1475 pub fn iter(&self) -> impl ExactSizeIterator<Item = Transaction<'a>> + TrustedLen + use<'a> {
1476 let mut remainder = self.bytes;
1477
1478 iter::repeat_with(move || {
1479 let transaction;
1480 (transaction, remainder) = Transaction::try_from_bytes(remainder)
1481 .expect("Already checked in constructor; qed");
1482 remainder = align_to_and_ensure_zero_padding(remainder, Alignment::MAX)
1483 .expect("Already checked in constructor; qed");
1484
1485 transaction
1486 })
1487 .take(self.num_transactions)
1488 }
1489
1490 #[inline(always)]
1492 pub const fn len(&self) -> usize {
1493 self.num_transactions
1494 }
1495
1496 #[inline(always)]
1498 pub const fn is_empty(&self) -> bool {
1499 self.num_transactions == 0
1500 }
1501
1502 #[inline]
1506 pub fn root(&self) -> Blake3Hash {
1507 let root = TransactionsMerkleTree::compute_root_only::<{ u64::from(u32::MAX) }, _, _>(
1508 self.iter().map(|transaction| ***transaction.hash()),
1509 )
1510 .unwrap_or_default();
1511
1512 Blake3Hash::new(root)
1513 }
1514}
1515
1516#[derive(Debug, Copy, Clone, Yokeable)]
1518#[non_exhaustive]
1520pub struct LeafShardBody<'a> {
1521 own_segments: Option<OwnSegments<'a>>,
1523 transactions: Transactions<'a>,
1525 #[cfg(feature = "alloc")]
1527 bytes: &'a [u8],
1528}
1529
1530impl<'a> GenericBlockBody<'a> for LeafShardBody<'a> {
1531 const SHARD_KIND: RealShardKind = RealShardKind::LeafShard;
1532
1533 #[cfg(feature = "alloc")]
1534 type Owned = OwnedLeafShardBody;
1535
1536 #[cfg(feature = "alloc")]
1537 #[inline(always)]
1538 fn to_owned(self) -> Self::Owned {
1539 self.to_owned()
1540 }
1541
1542 #[inline(always)]
1543 fn root(&self) -> Blake3Hash {
1544 self.root()
1545 }
1546}
1547
1548impl<'a> LeafShardBody<'a> {
1549 #[inline]
1563 pub fn try_from_bytes(mut bytes: &'a [u8]) -> Option<(Self, &'a [u8])> {
1564 if !Alignment::MAX.is_slice_aligned(bytes) {
1565 return None;
1566 }
1567
1568 let bytes_start = bytes;
1569
1570 let num_own_segment_roots = usize::from(*bytes.split_off_first()?);
1571
1572 let own_segments = if num_own_segment_roots > 0 {
1573 let first_local_segment_index;
1574 (first_local_segment_index, bytes) = Unaligned::<LocalSegmentIndex>::from_bytes(bytes)?;
1575
1576 let own_segment_roots;
1577 (own_segment_roots, bytes) =
1578 SegmentRoot::slice_from_bytes(bytes, num_own_segment_roots)?;
1579
1580 Some(OwnSegments::new(
1581 first_local_segment_index.as_inner(),
1582 own_segment_roots,
1583 )?)
1584 } else {
1585 None
1586 };
1587
1588 let (transactions, remainder) = Transactions::try_from_bytes(bytes)?;
1589
1590 let bytes = &bytes_start[..bytes_start.len() - remainder.len()];
1591 if u32::try_from(bytes.len()).is_err() {
1596 return None;
1597 }
1598
1599 let body = Self {
1600 own_segments,
1601 transactions,
1602 #[cfg(feature = "alloc")]
1603 bytes,
1604 };
1605
1606 Some((body, remainder))
1607 }
1608
1609 #[inline(always)]
1611 pub fn own_segments(&self) -> Option<OwnSegments<'a>> {
1612 self.own_segments
1613 }
1614
1615 #[inline(always)]
1617 pub fn transactions(&self) -> &Transactions<'a> {
1618 &self.transactions
1619 }
1620
1621 #[cfg(feature = "alloc")]
1628 #[inline(always)]
1629 pub fn to_owned(self) -> OwnedLeafShardBody {
1630 OwnedLeafShardBody::from_buffer(SharedAlignedBuffer::from_bytes(self.bytes)).expect(
1631 "The parser accepted these bytes at a 16-byte aligned address, as in the buffer; qed",
1632 )
1633 }
1634
1635 #[inline]
1637 pub fn root(&self) -> Blake3Hash {
1638 leaf_shard_body_root(self.own_segments.as_ref(), &self.transactions.root())
1639 }
1640}
1641
1642#[derive(Debug, Copy, Clone, From)]
1647pub enum BlockBody<'a> {
1648 BeaconChain(BeaconChainBody<'a>),
1650 IntermediateShard(IntermediateShardBody<'a>),
1652 LeafShard(LeafShardBody<'a>),
1654}
1655
1656impl<'a> BlockBody<'a> {
1657 #[inline]
1664 pub fn try_from_bytes(bytes: &'a [u8], shard_kind: RealShardKind) -> Option<(Self, &'a [u8])> {
1665 match shard_kind {
1666 RealShardKind::BeaconChain => {
1667 let (body, remainder) = BeaconChainBody::try_from_bytes(bytes)?;
1668 Some((Self::BeaconChain(body), remainder))
1669 }
1670 RealShardKind::IntermediateShard => {
1671 let (body, remainder) = IntermediateShardBody::try_from_bytes(bytes)?;
1672 Some((Self::IntermediateShard(body), remainder))
1673 }
1674 RealShardKind::LeafShard => {
1675 let (body, remainder) = LeafShardBody::try_from_bytes(bytes)?;
1676 Some((Self::LeafShard(body), remainder))
1677 }
1678 }
1679 }
1680
1681 #[cfg(feature = "alloc")]
1688 #[inline(always)]
1689 pub fn to_owned(self) -> OwnedBlockBody {
1690 match self {
1691 Self::BeaconChain(body) => body.to_owned().into(),
1692 Self::IntermediateShard(body) => body.to_owned().into(),
1693 Self::LeafShard(body) => body.to_owned().into(),
1694 }
1695 }
1696
1697 #[inline]
1702 pub fn root(&self) -> Blake3Hash {
1703 match self {
1704 Self::BeaconChain(body) => body.root(),
1705 Self::IntermediateShard(body) => body.root(),
1706 Self::LeafShard(body) => body.root(),
1707 }
1708 }
1709}