Skip to main content

ab_core_primitives/block/
body.rs

1//! Block body primitives
2
3#[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
37/// Generic block body
38pub trait GenericBlockBody<'a>
39where
40    Self: Copy + fmt::Debug + Into<BlockBody<'a>> + Send + Sync,
41{
42    /// Shard kind
43    const SHARD_KIND: RealShardKind;
44
45    /// Owned block body
46    #[cfg(feature = "alloc")]
47    type Owned: GenericOwnedBlockBody<Body<'a> = Self>
48    where
49        Self: 'a;
50
51    /// Turn into an owned version.
52    ///
53    /// # Panics
54    /// Where `usize` is 32-bit, if the body is longer than [`OwnedAlignedBuffer::MAX_CAPACITY`]
55    ///
56    /// [`OwnedAlignedBuffer::MAX_CAPACITY`]: ab_aligned_buffer::OwnedAlignedBuffer::MAX_CAPACITY
57    #[cfg(feature = "alloc")]
58    fn to_owned(self) -> Self::Owned;
59
60    /// Compute block body root
61    fn root(&self) -> Blake3Hash;
62}
63
64/// Calculates a Merkle Tree root for a provided list of segment roots
65#[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/// Own segments produced by a shard.
78///
79/// They have between 1 and `u8::MAX` segment roots, which is how many a body can store. The local
80/// segment index after the last segment root fits into `u64`, because that is where the next
81/// segment of the shard starts. Local segment indices never get close to `u64::MAX` in practice.
82#[derive(Debug, Copy, Clone)]
83pub struct OwnSegments<'a> {
84    /// Local segment index of the first own segment root
85    pub mut(self) first_local_segment_index: LocalSegmentIndex,
86    /// Segment roots produced by a shard
87    pub mut(self) segment_roots: &'a [SegmentRoot],
88}
89
90impl<'a> OwnSegments<'a> {
91    /// Create own segments from the local segment index of the first segment root and the roots.
92    ///
93    /// Returns `None` if there are no segment roots, more than `u8::MAX` of them, or the local
94    /// segment index after the last one doesn't fit into `u64`.
95    #[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    /// Create own segments without checking them.
115    ///
116    /// The iterator over segments of leaf shards of an intermediate shard block info uses it for
117    /// own segments that its parser has already checked: the layout only allows between 1 and
118    /// `u8::MAX` segment roots, and the parser checks that the local segment index after the last
119    /// one fits into `u64`.
120    #[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    /// Number of segment roots
132    #[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    /// Iterator over segment roots with their local segment indices
141    #[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    /// Compute the root of own segments
163    #[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    /// Compute the root of own segments while mixing in shard index.
175    ///
176    /// This method is useful for deriving roots on intermediate shard that can be verified by the
177    /// beacon chain later (which will have just shard index available rather than the whole leaf
178    /// shard block header).
179    #[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
200/// Compute the root of segments of leaf shard blocks.
201///
202/// Takes positions of leaf shard blocks with segments among `num_leaf_shard_blocks` blocks, their
203/// shard indices and segments. Returns `None` if positions aren't strictly increasing or not
204/// smaller than `num_leaf_shard_blocks`.
205fn 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
233/// Compute the body root of an intermediate shard block
234fn 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/// Counts of an intermediate shard block, which a beacon chain body stores in a table separate from
247/// the rest of the information about the block
248#[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    /// Size of counts in bytes
257    const SIZE: usize = size_of::<u8>() + 2 * size_of::<u16>();
258
259    /// Create an instance from provided bytes.
260    ///
261    /// The layout is as follows:
262    /// * number of own segment roots: u8
263    /// * number of leaf shard blocks: u16 as unaligned little-endian bytes
264    /// * number of leaf shard blocks with segments: u16 as unaligned little-endian bytes
265    #[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    /// Convert counts into bytes, the inverse of [`Self::from_bytes()`]
289    #[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/// Information about intermediate shard block
315#[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    /// A block header that corresponds to an intermediate shard
322    pub mut(self) header: IntermediateShardHeader<'a>,
323    /// Segments in the corresponding block
324    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    /// Create an instance from the record of a block in [`IntermediateShardBlocksInfo`] with its
332    /// `counts`, see [`IntermediateShardBlocksInfo::try_from_bytes()`] for the layout.
333    ///
334    /// `bytes` must start at an 8-bytes boundary like in the collection, because padding at the end
335    /// of the record depends on their address. Only the structure is checked here, the rest is
336    /// checked by [`Self::is_internally_consistent()`].
337    ///
338    /// Returns an instance and remaining bytes after the padding on success.
339    #[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        // Positions of leaf shard blocks with segments must be strictly increasing and smaller
375        // than the number of leaf shard blocks, the root of their segments relies on it
376        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            // The local segment index after the last segment root must fit into `u64`
390            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    /// Create an instance from the bytes of an info, which an owned info stores.
415    ///
416    /// `bytes` do not need to be aligned, but padding in the layout depends on their address and
417    /// must be present in full. The info is checked the same way as each block in
418    /// [`IntermediateShardBlocksInfo::try_from_bytes()`].
419    ///
420    /// The layout is as follows:
421    /// * number of own segment roots: u8
422    /// * number of leaf shard blocks: u16 as unaligned little-endian bytes
423    /// * number of leaf shard blocks with segments: u16 as unaligned little-endian bytes
424    /// * padding to 8-bytes boundary with zeroes
425    /// * block header, own segments, segments of leaf shards and padding, exactly as for each block
426    ///   in `IntermediateShardBlocksInfo`
427    ///
428    /// Returns an instance and remaining bytes on success.
429    #[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    /// Check intermediate shard block info's internal consistency: leaf shards with segments must
448    /// be children of the shard of the block, ordered by shard index, and segments of the same
449    /// leaf shard by local segment index. The body root must match the header.
450    #[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        // Ensure increasing order of shard indices and local segment indices
456        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                            // Expected
469                        }
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        // Also checks blocks without segments, positions and the number of leaf shard blocks, the
492        // root of segments of leaf shards commits to them
493        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    /// Number of leaf shard blocks in the corresponding intermediate shard block
502    #[inline(always)]
503    pub const fn num_leaf_shard_blocks(&self) -> u16 {
504        self.num_leaf_shard_blocks
505    }
506
507    /// Number of leaf shard blocks with segments in the corresponding intermediate shard block
508    #[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    /// Segments of leaf shards in the corresponding intermediate shard block, with positions of
514    /// their blocks among leaf shard blocks of the intermediate shard block
515    #[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    /// Compute the root of segments of leaf shards in the corresponding intermediate shard block
560    #[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/// Information about a collection of intermediate shard blocks
568#[derive(Debug, Copy, Clone)]
569pub struct IntermediateShardBlocksInfo<'a> {
570    num_blocks: usize,
571    bytes: &'a [u8],
572}
573
574impl<'a> IntermediateShardBlocksInfo<'a> {
575    /// Create an instance from provided bytes.
576    ///
577    /// `bytes` do not need to be aligned, but padding in the layout depends on their address and
578    /// must be present in full.
579    ///
580    /// Blocks must be ordered by shard index, and blocks of the same shard by block number and by
581    /// local segment index of own segments. Leaf shards with segments in a block must be children
582    /// of its shard, ordered by shard index, and segments of the same leaf shard by local segment
583    /// index. The body root of each block must match its header.
584    ///
585    /// The layout is as follows:
586    /// * number of blocks: u16 as unaligned little-endian bytes
587    /// * for each block:
588    ///   * number of own segment roots: u8
589    ///   * number of leaf shard blocks: u16 as unaligned little-endian bytes
590    ///   * number of leaf shard blocks with segments: u16 as unaligned little-endian bytes
591    /// * padding to 8-bytes boundary with zeroes
592    /// * for each block:
593    ///   * block header: IntermediateShardHeader
594    ///   * local segment index of the first segment root (if any): unaligned `LocalSegmentIndex`
595    ///   * concatenated own segment roots
596    ///   * for each leaf shard block with segments:
597    ///     * number of own segment roots: NonZeroU8
598    ///   * for each leaf shard block with segments:
599    ///     * position among leaf shard blocks, strictly increasing: u16 as unaligned little-endian
600    ///       bytes
601    ///     * shard index: u32 as unaligned little-endian bytes
602    ///     * local segment index of the first segment root: unaligned `LocalSegmentIndex`
603    ///     * concatenated own segment roots
604    ///   * padding to 8-bytes boundary with zeroes
605    ///
606    /// Returns an instance and remaining bytes on success.
607    #[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    /// Check the order of intermediate shard blocks, see [`Self::try_from_bytes()`].
645    ///
646    /// Internal consistency of each block is checked by
647    /// [`IntermediateShardBlockInfo::is_internally_consistent()`].
648    #[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            // Ensure increasing order of shard indices, block numbers and local segment indices
657            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    /// Iterator over intermediate shard blocks in a collection
722    #[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    /// Number of intermediate shard blocks
747    #[inline(always)]
748    pub const fn len(&self) -> usize {
749        self.num_blocks
750    }
751
752    /// Returns `true` if there are no intermediate shard blocks
753    #[inline(always)]
754    pub const fn is_empty(&self) -> bool {
755        self.num_blocks == 0
756    }
757
758    /// Compute the root of segments of the intermediate shard blocks info.
759    ///
760    /// Returns the default value for an empty collection of shard blocks.
761    #[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            // The hasher doesn't depend on the number of leaves, so this is the inner node over the
769            // first two leaves of the body tree of the intermediate shard block, which commits to
770            // the same segments
771            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    /// Compute the root of child block roots, which the header stores.
785    ///
786    /// Returns the default value for an empty collection of shard blocks.
787    #[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/// Block body that corresponds to the beacon chain
804#[derive(Debug, Copy, Clone, Yokeable)]
805// Prevent creation of potentially broken invariants externally
806#[non_exhaustive]
807pub struct BeaconChainBody<'a> {
808    /// Segments produced by this shard
809    own_segments: Option<OwnSegments<'a>>,
810    /// Intermediate shard blocks
811    intermediate_shard_blocks: IntermediateShardBlocksInfo<'a>,
812    /// Proof of time checkpoints from after future proof of time of the parent block to the
813    /// current block's future proof of time (inclusive)
814    pot_checkpoints: &'a [PotCheckpoints],
815    /// All bytes of the body, which owned versions are created from
816    #[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    /// Create an instance from provided correctly aligned bytes.
840    ///
841    /// `bytes` must be 16-bytes aligned, as in owned bodies, because padding in the layout depends
842    /// on the address of the bytes. Bodies longer than `u32::MAX` bytes are rejected, since owned
843    /// bodies can't hold them.
844    ///
845    /// The layout is as follows:
846    /// * number of PoT checkpoints: u32 as aligned little-endian bytes
847    /// * number of own segment roots: u8
848    /// * local segment index of the first segment root (if any): unaligned `LocalSegmentIndex`
849    /// * concatenated own segment roots
850    /// * intermediate shard blocks: IntermediateShardBlocksInfo
851    /// * concatenated PoT checkpoints
852    ///
853    /// Returns an instance and remaining bytes on success.
854    #[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        // An owned body can't hold more than `u32::MAX` bytes, which PoT checkpoints alone can
892        // exceed. Where `usize` is 32-bit, it can't hold more than
893        // `OwnedAlignedBuffer::MAX_CAPACITY` bytes either, which is not checked here,
894        // `Self::to_owned()` panics on such bodies instead
895        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    /// Create an owned version of this body.
911    ///
912    /// # Panics
913    /// Where `usize` is 32-bit, if the body is longer than [`OwnedAlignedBuffer::MAX_CAPACITY`]
914    ///
915    /// [`OwnedAlignedBuffer::MAX_CAPACITY`]: ab_aligned_buffer::OwnedAlignedBuffer::MAX_CAPACITY
916    #[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    /// Segment roots produced by this shard
925    #[inline(always)]
926    pub fn own_segments(&self) -> Option<OwnSegments<'a>> {
927        self.own_segments
928    }
929
930    /// Intermediate shard blocks
931    #[inline(always)]
932    pub fn intermediate_shard_blocks(&self) -> &IntermediateShardBlocksInfo<'a> {
933        &self.intermediate_shard_blocks
934    }
935
936    /// Proof of time checkpoints from after future proof of time of the parent block to the current
937    /// block's future proof of time (inclusive)
938    #[inline(always)]
939    pub fn pot_checkpoints(&self) -> &'a [PotCheckpoints] {
940        self.pot_checkpoints
941    }
942
943    /// Compute block body root
944    #[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    /// The same as [`Self::root()`], but with an already computed
952    /// [`IntermediateShardBlocksInfo::headers_root()`], which is expensive to compute
953    #[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
969/// Compute the body root of a leaf shard block
970fn 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/// Information about leaf shard block
981#[derive(Debug, Clone)]
982pub struct LeafShardBlockInfo<'a> {
983    /// A block header that corresponds to a leaf shard
984    pub mut(self) header: LeafShardHeader<'a>,
985    /// Root of transactions in the corresponding block
986    pub mut(self) transactions_root: &'a Blake3Hash,
987    /// Segments in the corresponding block
988    pub mut(self) own_segments: Option<OwnSegments<'a>>,
989}
990
991impl<'a> LeafShardBlockInfo<'a> {
992    /// Create an instance from the record of a block in [`LeafShardBlocksInfo`] with its number of
993    /// own segment roots, see [`LeafShardBlocksInfo::try_from_bytes()`] for the layout.
994    ///
995    /// `bytes` must start at an 8-bytes boundary like in the collection, because padding after the
996    /// header depends on their address. Only the structure is checked here, the rest is checked by
997    /// [`Self::is_internally_consistent()`].
998    ///
999    /// Returns an instance and remaining bytes on success.
1000    #[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    /// Create an instance from the bytes of an info, which an owned info stores.
1036    ///
1037    /// `bytes` do not need to be aligned, but padding in the layout depends on their address and
1038    /// must be present in full. The info is checked the same way as each block in
1039    /// [`LeafShardBlocksInfo::try_from_bytes()`].
1040    ///
1041    /// The layout is as follows:
1042    /// * number of own segment roots: u8
1043    /// * padding to 8-bytes boundary with zeroes
1044    /// * block header, padding, root of transactions and own segments, exactly as for each block in
1045    ///   `LeafShardBlocksInfo`
1046    ///
1047    /// Returns an instance and remaining bytes on success.
1048    #[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    /// Check leaf shard block info's internal consistency: the body root must match the header
1065    #[inline]
1066    fn is_internally_consistent(&self) -> bool {
1067        // Also checks blocks without segments, whose body root has a zero leaf for segments
1068        leaf_shard_body_root(self.own_segments.as_ref(), self.transactions_root)
1069            == self.header.result.body_root
1070    }
1071}
1072
1073/// Information about a collection of leaf shard blocks
1074#[derive(Debug, Copy, Clone)]
1075pub struct LeafShardBlocksInfo<'a> {
1076    num_blocks: u16,
1077    bytes: &'a [u8],
1078}
1079
1080impl<'a> LeafShardBlocksInfo<'a> {
1081    /// Create an instance from provided bytes.
1082    ///
1083    /// `bytes` do not need to be aligned, but padding in the layout depends on their address and
1084    /// must be present in full.
1085    ///
1086    /// Blocks must be ordered by shard index, and blocks of the same shard by block number and by
1087    /// local segment index of own segments. The body root of each block must match its header.
1088    ///
1089    /// The layout is as follows:
1090    /// * number of blocks: u16 as unaligned little-endian bytes
1091    /// * for each block:
1092    ///   * number of own segment roots: u8
1093    /// * padding to 8-bytes boundary with zeroes
1094    /// * for each block:
1095    ///   * block header: LeafShardHeader
1096    ///   * padding to 8-bytes boundary with zeroes
1097    ///   * root of transactions: `Blake3Hash`
1098    ///   * local segment index of the first segment root (if any): `LocalSegmentIndex`
1099    ///   * concatenated own segment roots
1100    ///
1101    /// Returns an instance and remaining bytes on success.
1102    #[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    /// Check the order of leaf shard blocks, see [`Self::try_from_bytes()`].
1137    ///
1138    /// Internal consistency of each block is checked by
1139    /// [`LeafShardBlockInfo::is_internally_consistent()`].
1140    #[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            // Ensure increasing order of shard indices, block numbers and local segment indices
1148            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    /// Iterator over leaf shard blocks in a collection
1211    #[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    /// Number of leaf shard blocks
1233    #[inline(always)]
1234    pub const fn len(&self) -> usize {
1235        self.num_blocks as usize
1236    }
1237
1238    /// Returns `true` if there are no leaf shard blocks
1239    #[inline(always)]
1240    pub const fn is_empty(&self) -> bool {
1241        self.num_blocks == 0
1242    }
1243
1244    /// Segments of leaf shard blocks with segments, with positions of their blocks among leaf
1245    /// shard blocks and their shard indices
1246    #[inline]
1247    fn leaf_shards_segments(
1248        &self,
1249    ) -> impl Iterator<Item = (u16, ShardIndex, OwnSegments<'a>)> + use<'a> {
1250        // Blocks come first, so positions never step past `u16::MAX`
1251        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    /// Compute the root of segments of the leaf shard blocks info.
1265    ///
1266    /// Returns the default value for an empty collection of shard blocks.
1267    #[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    /// Compute the root of child block roots, which the header stores.
1274    ///
1275    /// Returns the default value for an empty collection of shard blocks.
1276    #[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/// Block body that corresponds to an intermediate shard
1290#[derive(Debug, Copy, Clone, Yokeable)]
1291// Prevent creation of potentially broken invariants externally
1292#[non_exhaustive]
1293pub struct IntermediateShardBody<'a> {
1294    /// Segments produced by this shard
1295    own_segments: Option<OwnSegments<'a>>,
1296    /// Leaf shard blocks
1297    leaf_shard_blocks: LeafShardBlocksInfo<'a>,
1298    /// All bytes of the body, which owned versions are created from
1299    #[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    /// Create an instance from provided correctly aligned bytes.
1323    ///
1324    /// `bytes` must be 16-bytes aligned, as in owned bodies, because padding in the layout depends
1325    /// on the address of the bytes. Bodies longer than `u32::MAX` bytes are rejected, since owned
1326    /// bodies can't hold them.
1327    ///
1328    /// The layout is as follows:
1329    /// * number of own segment roots: u8
1330    /// * local segment index of the first segment root (if any): unaligned `LocalSegmentIndex`
1331    /// * concatenated own segment roots
1332    /// * leaf shard blocks: LeafShardBlocksInfo
1333    ///
1334    /// Returns an instance and remaining bytes on success.
1335    #[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        // An owned body can't hold more than `u32::MAX` bytes, which leaf shard blocks don't
1365        // exceed with current limits, but might if those change. Where `usize` is 32-bit, it can't
1366        // hold more than `OwnedAlignedBuffer::MAX_CAPACITY` bytes either, which is not checked
1367        // here, `Self::to_owned()` panics on such bodies instead
1368        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    /// Segment roots produced by this shard
1383    #[inline(always)]
1384    pub fn own_segments(&self) -> Option<OwnSegments<'a>> {
1385        self.own_segments
1386    }
1387
1388    /// Leaf shard blocks
1389    #[inline(always)]
1390    pub fn leaf_shard_blocks(&self) -> &LeafShardBlocksInfo<'a> {
1391        &self.leaf_shard_blocks
1392    }
1393
1394    /// Create an owned version of this body.
1395    ///
1396    /// # Panics
1397    /// Where `usize` is 32-bit, if the body is longer than [`OwnedAlignedBuffer::MAX_CAPACITY`]
1398    ///
1399    /// [`OwnedAlignedBuffer::MAX_CAPACITY`]: ab_aligned_buffer::OwnedAlignedBuffer::MAX_CAPACITY
1400    #[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    /// Compute block body root
1409    #[inline]
1410    pub fn root(&self) -> Blake3Hash {
1411        self.root_with_leaf_shard_blocks_root(&self.leaf_shard_blocks.headers_root())
1412    }
1413
1414    /// The same as [`Self::root()`], but with an already computed
1415    /// [`LeafShardBlocksInfo::headers_root()`], which is expensive to compute
1416    #[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/// Collection of transactions
1430#[derive(Debug, Copy, Clone)]
1431pub struct Transactions<'a> {
1432    num_transactions: usize,
1433    bytes: &'a [u8],
1434}
1435
1436impl<'a> Transactions<'a> {
1437    /// Create an instance from provided bytes.
1438    ///
1439    /// `bytes` do not need to be aligned, but padding in the layout depends on their address and
1440    /// must be present in full.
1441    ///
1442    /// The layout is as follows:
1443    /// * number of transactions: u32 as unaligned little-endian bytes
1444    /// * padding to 16-bytes boundary with zeroes
1445    /// * for each transaction
1446    ///   * transaction: Transaction
1447    ///   * padding to 16-bytes boundary with zeroes
1448    ///
1449    /// Returns an instance and remaining bytes on success.
1450    #[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    /// Iterator over transactions in a collection
1474    #[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    /// Number of transactions
1491    #[inline(always)]
1492    pub const fn len(&self) -> usize {
1493        self.num_transactions
1494    }
1495
1496    /// Returns `true` if there are no transactions
1497    #[inline(always)]
1498    pub const fn is_empty(&self) -> bool {
1499        self.num_transactions == 0
1500    }
1501
1502    /// Compute the root of transactions.
1503    ///
1504    /// Returns the default value for an empty collection of transactions.
1505    #[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/// Block body that corresponds to a leaf shard
1517#[derive(Debug, Copy, Clone, Yokeable)]
1518// Prevent creation of potentially broken invariants externally
1519#[non_exhaustive]
1520pub struct LeafShardBody<'a> {
1521    /// Segments produced by this shard
1522    own_segments: Option<OwnSegments<'a>>,
1523    /// User transactions
1524    transactions: Transactions<'a>,
1525    /// All bytes of the body, which owned versions are created from
1526    #[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    /// Create an instance from provided correctly aligned bytes.
1550    ///
1551    /// `bytes` must be 16-bytes aligned, as in owned bodies, because padding in the layout depends
1552    /// on the address of the bytes. Bodies longer than `u32::MAX` bytes are rejected, since owned
1553    /// bodies can't hold them.
1554    ///
1555    /// The layout is as follows:
1556    /// * number of own segment roots: u8
1557    /// * local segment index of the first segment root (if any): unaligned `LocalSegmentIndex`
1558    /// * concatenated own segment roots
1559    /// * transactions: Transactions
1560    ///
1561    /// Returns an instance and remaining bytes on success.
1562    #[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        // An owned body can't hold more than `u32::MAX` bytes, which transactions alone can
1592        // exceed. Where `usize` is 32-bit, it can't hold more than
1593        // `OwnedAlignedBuffer::MAX_CAPACITY` bytes either, which is not checked here,
1594        // `Self::to_owned()` panics on such bodies instead
1595        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    /// Segment roots produced by this shard
1610    #[inline(always)]
1611    pub fn own_segments(&self) -> Option<OwnSegments<'a>> {
1612        self.own_segments
1613    }
1614
1615    /// User transactions
1616    #[inline(always)]
1617    pub fn transactions(&self) -> &Transactions<'a> {
1618        &self.transactions
1619    }
1620
1621    /// Create an owned version of this body.
1622    ///
1623    /// # Panics
1624    /// Where `usize` is 32-bit, if the body is longer than [`OwnedAlignedBuffer::MAX_CAPACITY`]
1625    ///
1626    /// [`OwnedAlignedBuffer::MAX_CAPACITY`]: ab_aligned_buffer::OwnedAlignedBuffer::MAX_CAPACITY
1627    #[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    /// Compute block body root
1636    #[inline]
1637    pub fn root(&self) -> Blake3Hash {
1638        leaf_shard_body_root(self.own_segments.as_ref(), &self.transactions.root())
1639    }
1640}
1641
1642/// Block body that together with [`BlockHeader`] form a [`Block`]
1643///
1644/// [`BlockHeader`]: crate::block::header::BlockHeader
1645/// [`Block`]: crate::block::Block
1646#[derive(Debug, Copy, Clone, From)]
1647pub enum BlockBody<'a> {
1648    /// Block body corresponds to the beacon chain
1649    BeaconChain(BeaconChainBody<'a>),
1650    /// Block body corresponds to an intermediate shard
1651    IntermediateShard(IntermediateShardBody<'a>),
1652    /// Block body corresponds to a leaf shard
1653    LeafShard(LeafShardBody<'a>),
1654}
1655
1656impl<'a> BlockBody<'a> {
1657    /// Try to create a new instance from provided bytes for the provided shard index.
1658    ///
1659    /// `bytes` must be 16-bytes aligned. Bodies longer than `u32::MAX` bytes are rejected.
1660    ///
1661    /// Returns an instance and remaining bytes on success, `None` if too few bytes were given,
1662    /// bytes are not properly aligned or input is otherwise invalid.
1663    #[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    /// Create an owned version of this body.
1682    ///
1683    /// # Panics
1684    /// Where `usize` is 32-bit, if the body is longer than [`OwnedAlignedBuffer::MAX_CAPACITY`]
1685    ///
1686    /// [`OwnedAlignedBuffer::MAX_CAPACITY`]: ab_aligned_buffer::OwnedAlignedBuffer::MAX_CAPACITY
1687    #[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    /// Compute block body root.
1698    ///
1699    /// Block body hash is actually a Merkle Tree Root. The leaves are derived from individual
1700    /// fields this enum in the declaration order.
1701    #[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}