Skip to main content

ab_core_primitives/block/body/
owned.rs

1//! Data structures related to the owned version of [`BlockBody`]
2
3// Slow under Miri and these features don't change what the tests exercise, so under Miri they only
4// run with just `alloc` or with all features (like when testing the whole workspace)
5#[cfg(all(
6    test,
7    any(
8        not(miri),
9        not(any(
10            feature = "ed25519",
11            feature = "parallel",
12            feature = "scale-codec",
13            feature = "serde"
14        )),
15        all(
16            feature = "ed25519",
17            feature = "parallel",
18            feature = "scale-codec",
19            feature = "serde"
20        ),
21    ),
22))]
23mod tests;
24
25use crate::block::body::{
26    BeaconChainBody, BlockBody, GenericBlockBody, IntermediateShardBlockCounts,
27    IntermediateShardBlockInfo, IntermediateShardBody, LeafShardBlockInfo, LeafShardBody,
28    OwnSegments,
29};
30use crate::block::header::LeafShardHeader;
31use crate::block::header::owned::{OwnedIntermediateShardHeader, OwnedLeafShardHeader};
32use crate::block::{IntermediateShardBlock, LeafShardBlock};
33use crate::hashes::Blake3Hash;
34use crate::pot::PotCheckpoints;
35use crate::segments::{LocalSegmentIndex, SegmentRoot};
36use crate::shard::{RealShardKind, ShardIndex};
37use crate::transaction::Transaction;
38use crate::transaction::owned::OwnedTransaction;
39use ab_aligned_buffer::alignment::{Align8, Align16};
40use ab_aligned_buffer::{OwnedAlignedBuffer, SharedAlignedBuffer};
41use ab_io_type::alignment::Alignment;
42use ab_io_type::trivial_type::TrivialType;
43use core::fmt;
44use core::iter::{Step, TrustedLen};
45use derive_more::From;
46use triomphe::Arc;
47use yoke::{Yoke, Yokeable};
48
49/// Generic owned block body
50pub trait GenericOwnedBlockBody:
51    Clone + fmt::Debug + Send + Sync + Into<OwnedBlockBody> + 'static
52{
53    /// Shard kind
54    const SHARD_KIND: RealShardKind;
55
56    /// Block body
57    type Body<'a>: GenericBlockBody<'a>
58    where
59        Self: 'a;
60
61    /// Create an owned body from a buffer
62    fn from_buffer(buffer: SharedAlignedBuffer) -> Result<Self, SharedAlignedBuffer>;
63
64    /// Inner buffer with block body contents
65    fn buffer(&self) -> &SharedAlignedBuffer;
66
67    /// Number of clones in memory
68    fn ref_count(&self) -> usize;
69
70    /// Get a regular block body out of the owned version
71    fn body(&self) -> &Self::Body<'_>;
72
73    /// Compute block body root, see [`GenericBlockBody::root()`] for details
74    fn root(&self) -> Blake3Hash;
75}
76
77/// Errors for [`OwnedLeafShardBody`]
78#[derive(Debug, thiserror::Error)]
79pub enum OwnedLeafShardBodyError {
80    /// Too many own segment roots
81    #[error("Too many own segment roots: {actual}")]
82    TooManyOwnSegmentRoots {
83        /// Actual number of own segment roots
84        actual: usize,
85    },
86    /// Local segment index after the last own segment root doesn't fit into `u64`
87    #[error("Own segment index overflow, first local segment index: {first_local_segment_index}")]
88    OwnSegmentIndexOverflow {
89        /// Local segment index of the first own segment root
90        first_local_segment_index: LocalSegmentIndex,
91    },
92    /// Local segment indices of own segment roots are not consecutive
93    #[error(
94        "Own segment indices are not consecutive: {local_segment_index} after \
95        {previous_local_segment_index}"
96    )]
97    NonConsecutiveOwnSegmentIndices {
98        /// Local segment index of the previous own segment root
99        previous_local_segment_index: LocalSegmentIndex,
100        /// Local segment index that doesn't follow the previous one
101        local_segment_index: LocalSegmentIndex,
102    },
103    /// Block body is too large
104    #[error("Block body is too large")]
105    BlockBodyIsTooLarge,
106}
107
108/// Transaction that can be written into the body.
109///
110/// Can't be implemented outside of this module, because block body builders rely on it appending
111/// exactly one correctly encoded transaction to the buffer or leaving it unchanged.
112pub impl(self) trait WritableBodyTransaction {
113    /// Write this transaction into the body.
114    ///
115    /// Returns [`OwnedLeafShardBodyError::BlockBodyIsTooLarge`] and leaves the buffer unchanged if
116    /// the body becomes too large.
117    fn write_into(&self, buffer: &mut OwnedAlignedBuffer) -> Result<(), OwnedLeafShardBodyError>;
118}
119
120impl WritableBodyTransaction for Transaction<'_> {
121    #[inline(always)]
122    fn write_into(&self, buffer: &mut OwnedAlignedBuffer) -> Result<(), OwnedLeafShardBodyError> {
123        buffer
124            .append(self.bytes())
125            .map_err(|_error| OwnedLeafShardBodyError::BlockBodyIsTooLarge)
126    }
127}
128
129impl WritableBodyTransaction for &OwnedTransaction {
130    #[inline(always)]
131    fn write_into(&self, buffer: &mut OwnedAlignedBuffer) -> Result<(), OwnedLeafShardBodyError> {
132        buffer
133            .append(self.buffer().as_slice())
134            .map_err(|_error| OwnedLeafShardBodyError::BlockBodyIsTooLarge)
135    }
136}
137
138#[derive(Debug, Clone)]
139struct TransactionBuilder {
140    num_transactions_offset: usize,
141    buffer: OwnedAlignedBuffer,
142}
143
144impl TransactionBuilder {
145    fn new(num_transactions_offset: usize, buffer: OwnedAlignedBuffer) -> Self {
146        Self {
147            num_transactions_offset,
148            buffer,
149        }
150    }
151
152    /// Add transaction to the body.
153    ///
154    /// Returns [`OwnedLeafShardBodyError::BlockBodyIsTooLarge`] and leaves the body unchanged if it
155    /// becomes too large.
156    fn add_transaction<T>(&mut self, transaction: T) -> Result<(), OwnedLeafShardBodyError>
157    where
158        T: WritableBodyTransaction,
159    {
160        // The buffer is already aligned, because padding follows the number of transactions and
161        // each transaction
162        self.inc_transaction_count();
163
164        let old_buffer_len = self.buffer.len();
165
166        if let Err(error) = transaction.write_into(&mut self.buffer) {
167            self.dec_transaction_count();
168            return Err(error);
169        }
170
171        if self.buffer.pad_to_alignment::<Align16>().is_err() {
172            self.dec_transaction_count();
173            // SAFETY: Length was obtained from the same buffer before the last write
174            unsafe {
175                self.buffer.set_len(old_buffer_len);
176            }
177            return Err(OwnedLeafShardBodyError::BlockBodyIsTooLarge);
178        }
179
180        Ok(())
181    }
182
183    /// Finish building block body
184    #[inline(always)]
185    fn finish(self) -> OwnedAlignedBuffer {
186        self.buffer
187    }
188
189    /// Increase the number of stored transactions
190    #[inline(always)]
191    fn inc_transaction_count(&mut self) {
192        // SAFETY: Constructor ensures the offset is valid and has space for `u32` (but not
193        // necessarily aligned)
194        unsafe {
195            let num_transactions_ptr = self
196                .buffer
197                .as_mut_ptr()
198                .byte_add(self.num_transactions_offset)
199                .cast::<u32>();
200            let num_transactions = num_transactions_ptr.read_unaligned();
201            let num_transactions = num_transactions.checked_add(1).expect(
202                "Each transaction takes at least `TransactionHeader::SIZE` bytes of the buffer, \
203                which can't be longer than `u32::MAX` bytes; qed",
204            );
205            num_transactions_ptr.write_unaligned(num_transactions);
206        }
207    }
208
209    /// Decrease the number of stored transactions
210    #[inline(always)]
211    fn dec_transaction_count(&mut self) {
212        // SAFETY: Constructor ensures the offset is valid and has space for `u32` (but not
213        // necessarily aligned)
214        unsafe {
215            let num_transactions_ptr = self
216                .buffer
217                .as_mut_ptr()
218                .byte_add(self.num_transactions_offset)
219                .cast::<u32>();
220            let num_transactions = num_transactions_ptr.read_unaligned();
221            let num_transactions = num_transactions.saturating_sub(1);
222            num_transactions_ptr.write_unaligned(num_transactions);
223        }
224    }
225}
226
227/// The record of a child shard block doesn't fit into the buffer
228#[derive(Debug)]
229struct RecordTooLarge;
230
231/// Append the record of a leaf shard block as in an intermediate shard body, see
232/// [`LeafShardBlocksInfo::try_from_bytes()`] for the layout.
233///
234/// The length of the buffer must be a multiple of 8 for the record to parse. Returns an error if
235/// the record doesn't fit into the buffer, part of it might have been appended already.
236///
237/// [`LeafShardBlocksInfo::try_from_bytes()`]:
238/// crate::block::body::LeafShardBlocksInfo::try_from_bytes
239fn append_leaf_shard_block_record(
240    buffer: &mut OwnedAlignedBuffer,
241    header: &LeafShardHeader<'_>,
242    transactions_root: &Blake3Hash,
243    own_segments: Option<&OwnSegments<'_>>,
244) -> Result<(), RecordTooLarge> {
245    buffer
246        .append(header.bytes())
247        .map_err(|_error| RecordTooLarge)?;
248    buffer
249        .pad_to_alignment::<Align8>()
250        .map_err(|_error| RecordTooLarge)?;
251
252    buffer
253        .append(transactions_root.as_bytes())
254        .map_err(|_error| RecordTooLarge)?;
255    if let Some(own_segments) = own_segments {
256        buffer
257            .append(own_segments.first_local_segment_index.as_bytes())
258            .map_err(|_error| RecordTooLarge)?;
259        buffer
260            .append(SegmentRoot::slice_as_bytes(own_segments.segment_roots))
261            .map_err(|_error| RecordTooLarge)?;
262    }
263
264    Ok(())
265}
266
267// TODO: Derive `Yokeable` for `IntermediateShardBlockInfo` directly once `syn` can parse `mut`
268//  restrictions of its fields: https://github.com/dtolnay/syn/issues/1987
269#[derive(Debug, Yokeable)]
270struct YokeableIntermediateShardBlockInfo<'a>(IntermediateShardBlockInfo<'a>);
271
272/// An owned version of [`IntermediateShardBlockInfo`].
273///
274/// It is well suited for sending over the network and keeping in memory independently of any block
275/// until a beacon chain block includes it.
276#[derive(Debug, Clone)]
277pub struct OwnedIntermediateShardBlockInfo {
278    inner: Arc<Yoke<YokeableIntermediateShardBlockInfo<'static>, SharedAlignedBuffer>>,
279}
280
281impl OwnedIntermediateShardBlockInfo {
282    /// Create an owned info of an intermediate shard block
283    pub fn from_block(block: &IntermediateShardBlock<'_>) -> Self {
284        let own_segments = block.body.own_segments();
285        let leaf_shard_blocks = block.body.leaf_shard_blocks();
286
287        // Counts with padding, the header with the largest seal and own segments, then for each
288        // leaf shard block with segments its number of segment roots and segments, then padding
289        let (num_leaf_shard_blocks_with_segments, capacity) = leaf_shard_blocks
290            .leaf_shards_segments()
291            .try_fold(
292                (
293                    0u16,
294                    (u8::SIZE + 2 * u16::SIZE)
295                        .next_multiple_of(u32::from(Alignment::of::<u64>().get()))
296                        + OwnedIntermediateShardHeader::MAX_ALLOCATION
297                        + own_segments.map_or_default(|own_segments| {
298                            LocalSegmentIndex::SIZE
299                                + u32::from(own_segments.num_segment_roots().get())
300                                    * SegmentRoot::SIZE as u32
301                        }),
302                ),
303                |(num_leaf_shard_blocks_with_segments, capacity),
304                 (_position, _shard_index, own_segments)| {
305                    Some((
306                        num_leaf_shard_blocks_with_segments.checked_add(1)?,
307                        capacity.checked_add(
308                            u8::SIZE
309                                + u16::SIZE
310                                + ShardIndex::SIZE
311                                + LocalSegmentIndex::SIZE
312                                + u32::from(own_segments.num_segment_roots().get())
313                                    * SegmentRoot::SIZE as u32,
314                        )?,
315                    ))
316                },
317            )
318            .and_then(|(num_leaf_shard_blocks_with_segments, capacity)| {
319                Some((
320                    num_leaf_shard_blocks_with_segments,
321                    capacity.checked_next_multiple_of(u32::from(Alignment::of::<u64>().get()))?,
322                ))
323            })
324            .expect(
325                "At most `u16::MAX` leaf shard blocks with at most `u8::MAX` segment roots each \
326                take less than 1 GiB, which is below `OwnedAlignedBuffer::MAX_CAPACITY`; qed",
327            );
328
329        let mut buffer = OwnedAlignedBuffer::with_capacity(capacity);
330        buffer
331            .append(
332                &IntermediateShardBlockCounts {
333                    num_own_segment_roots: own_segments
334                        .map_or_default(|own_segments| own_segments.num_segment_roots().get()),
335                    num_leaf_shard_blocks: u16::try_from(leaf_shard_blocks.len())
336                        .expect("A body stores the number of leaf shard blocks as `u16`; qed"),
337                    num_leaf_shard_blocks_with_segments,
338                }
339                .to_bytes(),
340            )
341            .expect("Enough capacity was allocated above; qed");
342        buffer
343            .pad_to_alignment::<Align8>()
344            .expect("Enough capacity was allocated above; qed");
345        buffer
346            .append(block.header.bytes())
347            .expect("Enough capacity was allocated above; qed");
348        if let Some(own_segments) = &own_segments {
349            buffer
350                .append(own_segments.first_local_segment_index.as_bytes())
351                .expect("Enough capacity was allocated above; qed");
352            buffer
353                .append(SegmentRoot::slice_as_bytes(own_segments.segment_roots))
354                .expect("Enough capacity was allocated above; qed");
355        }
356        for (_position, _shard_index, own_segments) in leaf_shard_blocks.leaf_shards_segments() {
357            buffer
358                .append(&[own_segments.num_segment_roots().get()])
359                .expect("Enough capacity was allocated above; qed");
360        }
361        for (position, shard_index, own_segments) in leaf_shard_blocks.leaf_shards_segments() {
362            buffer
363                .append(&position.to_le_bytes())
364                .expect("Enough capacity was allocated above; qed");
365            buffer
366                .append(shard_index.as_bytes())
367                .expect("Enough capacity was allocated above; qed");
368            buffer
369                .append(own_segments.first_local_segment_index.as_bytes())
370                .expect("Enough capacity was allocated above; qed");
371            buffer
372                .append(SegmentRoot::slice_as_bytes(own_segments.segment_roots))
373                .expect("Enough capacity was allocated above; qed");
374        }
375        buffer
376            .pad_to_alignment::<Align8>()
377            .expect("Enough capacity was allocated above; qed");
378
379        Self::from_buffer(buffer.into_shared()).expect(
380            "Written the way the parser reads it from a block that passed the same checks; qed",
381        )
382    }
383
384    /// Create an owned info from a buffer.
385    ///
386    /// The info is checked the same way as each info in a beacon chain body, its seal is not
387    /// checked.
388    #[inline]
389    pub fn from_buffer(buffer: SharedAlignedBuffer) -> Result<Self, SharedAlignedBuffer> {
390        // TODO: Cloning is cheap, but will not be necessary if/when this is resolved:
391        //  https://github.com/unicode-org/icu4x/issues/6665
392        let inner = Yoke::try_attach_to_cart(buffer.clone(), |buffer| {
393            let Some((info, extra_bytes)) =
394                IntermediateShardBlockInfo::try_from_standalone_bytes(buffer)
395            else {
396                return Err(());
397            };
398            if !extra_bytes.is_empty() {
399                return Err(());
400            }
401
402            Ok(YokeableIntermediateShardBlockInfo(info))
403        })
404        .map_err(move |()| buffer)?;
405
406        Ok(Self {
407            inner: Arc::new(inner),
408        })
409    }
410
411    /// Inner buffer with info contents
412    #[inline(always)]
413    pub fn buffer(&self) -> &SharedAlignedBuffer {
414        self.inner.backing_cart()
415    }
416
417    /// Get [`IntermediateShardBlockInfo`] out of [`OwnedIntermediateShardBlockInfo`]
418    #[inline(always)]
419    pub fn info(&self) -> &IntermediateShardBlockInfo<'_> {
420        let YokeableIntermediateShardBlockInfo(info) = self.inner.get();
421        info
422    }
423}
424
425// TODO: Derive `Yokeable` for `LeafShardBlockInfo` directly once `syn` can parse `mut` restrictions
426//  of its fields: https://github.com/dtolnay/syn/issues/1987
427#[derive(Debug, Yokeable)]
428struct YokeableLeafShardBlockInfo<'a>(LeafShardBlockInfo<'a>);
429
430/// An owned version of [`LeafShardBlockInfo`].
431///
432/// It is well suited for sending over the network and keeping in memory independently of any block
433/// until an intermediate shard block includes it.
434#[derive(Debug, Clone)]
435pub struct OwnedLeafShardBlockInfo {
436    inner: Arc<Yoke<YokeableLeafShardBlockInfo<'static>, SharedAlignedBuffer>>,
437}
438
439impl OwnedLeafShardBlockInfo {
440    /// Create an owned info of a leaf shard block
441    pub fn from_block(block: &LeafShardBlock<'_>) -> Self {
442        let own_segments = block.body.own_segments();
443
444        // The number of own segment roots with padding, the header with the largest seal and
445        // padding, the root of transactions and own segments
446        let capacity = (u8::SIZE.next_multiple_of(u32::from(Alignment::of::<u64>().get()))
447            + OwnedLeafShardHeader::MAX_ALLOCATION)
448            .next_multiple_of(u32::from(Alignment::of::<u64>().get()))
449            + <Blake3Hash as TrivialType>::SIZE
450            + own_segments.map_or_default(|own_segments| {
451                LocalSegmentIndex::SIZE
452                    + u32::from(own_segments.num_segment_roots().get()) * SegmentRoot::SIZE as u32
453            });
454
455        let mut buffer = OwnedAlignedBuffer::with_capacity(capacity);
456        buffer
457            .append(&[
458                own_segments.map_or_default(|own_segments| own_segments.num_segment_roots().get())
459            ])
460            .expect("Enough capacity was allocated above; qed");
461        buffer
462            .pad_to_alignment::<Align8>()
463            .expect("Enough capacity was allocated above; qed");
464        append_leaf_shard_block_record(
465            &mut buffer,
466            &block.header,
467            &block.body.transactions().root(),
468            own_segments.as_ref(),
469        )
470        .expect("Enough capacity was allocated above; qed");
471
472        Self::from_buffer(buffer.into_shared()).expect(
473            "Written the way the parser reads it from a block that passed the same checks; qed",
474        )
475    }
476
477    /// Create an owned info from a buffer.
478    ///
479    /// The info is checked the same way as each info in an intermediate shard body, its seal is
480    /// not checked.
481    #[inline]
482    pub fn from_buffer(buffer: SharedAlignedBuffer) -> Result<Self, SharedAlignedBuffer> {
483        // TODO: Cloning is cheap, but will not be necessary if/when this is resolved:
484        //  https://github.com/unicode-org/icu4x/issues/6665
485        let inner = Yoke::try_attach_to_cart(buffer.clone(), |buffer| {
486            let Some((info, extra_bytes)) = LeafShardBlockInfo::try_from_standalone_bytes(buffer)
487            else {
488                return Err(());
489            };
490            if !extra_bytes.is_empty() {
491                return Err(());
492            }
493
494            Ok(YokeableLeafShardBlockInfo(info))
495        })
496        .map_err(move |()| buffer)?;
497
498        Ok(Self {
499            inner: Arc::new(inner),
500        })
501    }
502
503    /// Inner buffer with info contents
504    #[inline(always)]
505    pub fn buffer(&self) -> &SharedAlignedBuffer {
506        self.inner.backing_cart()
507    }
508
509    /// Get [`LeafShardBlockInfo`] out of [`OwnedLeafShardBlockInfo`]
510    #[inline(always)]
511    pub fn info(&self) -> &LeafShardBlockInfo<'_> {
512        let YokeableLeafShardBlockInfo(info) = self.inner.get();
513        info
514    }
515}
516
517/// Errors for [`OwnedBeaconChainBody`]
518#[derive(Debug, thiserror::Error)]
519pub enum OwnedBeaconChainBodyError {
520    /// Too many PoT checkpoints
521    #[error("Too many PoT checkpoints: {actual}")]
522    TooManyPotCheckpoints {
523        /// Actual number of PoT checkpoints
524        actual: usize,
525    },
526    /// Too many own segment roots
527    #[error("Too many own segment roots: {actual}")]
528    TooManyOwnSegmentRoots {
529        /// Actual number of own segment roots
530        actual: usize,
531    },
532    /// Local segment index after the last own segment root doesn't fit into `u64`
533    #[error("Own segment index overflow, first local segment index: {first_local_segment_index}")]
534    OwnSegmentIndexOverflow {
535        /// Local segment index of the first own segment root
536        first_local_segment_index: LocalSegmentIndex,
537    },
538    /// Local segment indices of own segment roots are not consecutive
539    #[error(
540        "Own segment indices are not consecutive: {local_segment_index} after \
541        {previous_local_segment_index}"
542    )]
543    NonConsecutiveOwnSegmentIndices {
544        /// Local segment index of the previous own segment root
545        previous_local_segment_index: LocalSegmentIndex,
546        /// Local segment index that doesn't follow the previous one
547        local_segment_index: LocalSegmentIndex,
548    },
549    /// Too many intermediate shard blocks
550    #[error("Too many intermediate shard blocks: {actual}")]
551    TooManyIntermediateShardBlocks {
552        /// Actual number of intermediate shard blocks
553        actual: usize,
554    },
555    /// Block body is too large
556    #[error("Block body is too large")]
557    BlockBodyIsTooLarge,
558    /// Intermediate shard blocks are not in the order described in
559    /// [`IntermediateShardBlocksInfo::try_from_bytes()`]
560    ///
561    /// [`IntermediateShardBlocksInfo::try_from_bytes()`]:
562    /// crate::block::body::IntermediateShardBlocksInfo::try_from_bytes
563    #[error("Intermediate shard blocks are inconsistent")]
564    InconsistentIntermediateShardBlocks,
565}
566
567/// An owned version of [`BeaconChainBody`].
568///
569/// It is correctly aligned in memory and well suited for sending and receiving over the network
570/// efficiently or storing in memory or on disk.
571#[derive(Debug, Clone)]
572pub struct OwnedBeaconChainBody {
573    inner: Arc<Yoke<BeaconChainBody<'static>, SharedAlignedBuffer>>,
574}
575
576impl GenericOwnedBlockBody for OwnedBeaconChainBody {
577    const SHARD_KIND: RealShardKind = RealShardKind::BeaconChain;
578
579    type Body<'a> = BeaconChainBody<'a>;
580
581    #[inline(always)]
582    fn from_buffer(buffer: SharedAlignedBuffer) -> Result<Self, SharedAlignedBuffer> {
583        Self::from_buffer(buffer)
584    }
585
586    #[inline(always)]
587    fn buffer(&self) -> &SharedAlignedBuffer {
588        self.buffer()
589    }
590
591    #[inline(always)]
592    fn ref_count(&self) -> usize {
593        self.ref_count()
594    }
595
596    #[inline(always)]
597    fn body(&self) -> &Self::Body<'_> {
598        self.body()
599    }
600
601    #[inline(always)]
602    fn root(&self) -> Blake3Hash {
603        self.root()
604    }
605}
606
607impl OwnedBeaconChainBody {
608    /// Create a new instance
609    pub fn new<'a, OS, ISB>(
610        own_segments: OS,
611        intermediate_shard_blocks: ISB,
612        pot_checkpoints: &[PotCheckpoints],
613    ) -> Result<Self, OwnedBeaconChainBodyError>
614    where
615        OS: TrustedLen<Item = (LocalSegmentIndex, SegmentRoot)>,
616        // Infos come from parsed beacon chain bodies or from
617        // `OwnedIntermediateShardBlockInfo::info()`
618        ISB: TrustedLen<Item = IntermediateShardBlockInfo<'a>> + 'a,
619    {
620        let num_pot_checkpoints = pot_checkpoints.len();
621        let num_pot_checkpoints = u32::try_from(num_pot_checkpoints).map_err(|_error| {
622            OwnedBeaconChainBodyError::TooManyPotCheckpoints {
623                actual: num_pot_checkpoints,
624            }
625        })?;
626        let num_own_segment_roots = own_segments.size_hint().0;
627        let num_own_segment_roots = u8::try_from(num_own_segment_roots).map_err(|_error| {
628            OwnedBeaconChainBodyError::TooManyOwnSegmentRoots {
629                actual: num_own_segment_roots,
630            }
631        })?;
632        let num_blocks = intermediate_shard_blocks.size_hint().0;
633        let num_blocks = u16::try_from(num_blocks).map_err(|_error| {
634            OwnedBeaconChainBodyError::TooManyIntermediateShardBlocks { actual: num_blocks }
635        })?;
636
637        // A body can't hold more than `u32::MAX` bytes of PoT checkpoints
638        let pot_checkpoints_size = num_pot_checkpoints
639            .checked_mul(PotCheckpoints::SIZE as u32)
640            .ok_or(OwnedBeaconChainBodyError::BlockBodyIsTooLarge)?;
641        let fixed_size = (
642            // Number of PoT checkpoints
643            u32::SIZE
644                // Number of own segment roots
645                + u8::SIZE
646                // Local segment index of the first own segment root
647                + if num_own_segment_roots > 0 { LocalSegmentIndex::SIZE } else { 0 }
648                // Own segment roots
649                + u32::from(num_own_segment_roots) * SegmentRoot::SIZE as u32
650                // Number of intermediate shard blocks
651                + u16::SIZE
652                // Numbers of own segment roots, leaf shard blocks and leaf shard blocks with
653                // segments of each block
654                + u32::from(num_blocks) * (u8::SIZE + 2 * u16::SIZE)
655        )
656            // Padding to 8-bytes boundary
657            .next_multiple_of(u32::from(Alignment::of::<u64>().get()));
658        // Everything except intermediate shard blocks is known upfront, so a body that doesn't fit
659        // into a buffer even without them is rejected before anything is allocated or copied
660        #[cfg_attr(
661            target_pointer_width = "64",
662            expect(
663                clippy::absurd_extreme_comparisons,
664                reason = "`MAX_CAPACITY` is `u32::MAX` where `usize` is 64-bit"
665            )
666        )]
667        let min_size = fixed_size
668            .checked_add(pot_checkpoints_size)
669            .filter(|&size| size <= OwnedAlignedBuffer::<Align16>::MAX_CAPACITY)
670            .ok_or(OwnedBeaconChainBodyError::BlockBodyIsTooLarge)?;
671        // This is only an estimate of intermediate shard blocks to get in the ballpark where
672        // reallocation should not be necessary in many cases
673        let intermediate_shard_blocks_size =
674            u32::from(num_blocks) * OwnedIntermediateShardHeader::MAX_ALLOCATION * 2;
675        // The estimate can make the capacity larger than any body can be
676        #[cfg_attr(
677            target_pointer_width = "64",
678            expect(
679                clippy::unnecessary_min_or_max,
680                reason = "`MAX_CAPACITY` is `u32::MAX` where `usize` is 64-bit"
681            )
682        )]
683        let mut buffer = OwnedAlignedBuffer::with_capacity(
684            min_size
685                .saturating_add(intermediate_shard_blocks_size)
686                .min(OwnedAlignedBuffer::<Align16>::MAX_CAPACITY),
687        );
688
689        buffer
690            .append(&num_pot_checkpoints.to_le_bytes())
691            .expect("Fixed size data structures that are guaranteed to fit; qed");
692
693        buffer
694            .append(&[num_own_segment_roots])
695            .expect("Fixed size data structures that are guaranteed to fit; qed");
696        let mut own_segments = own_segments.peekable();
697        if let Some(&(first_local_segment_index, _own_segment_root)) = own_segments.peek() {
698            // The parser rejects bodies where the index after the last segment root doesn't fit
699            // into `u64`
700            if LocalSegmentIndex::forward_checked(
701                first_local_segment_index,
702                usize::from(num_own_segment_roots),
703            )
704            .is_none()
705            {
706                return Err(OwnedBeaconChainBodyError::OwnSegmentIndexOverflow {
707                    first_local_segment_index,
708                });
709            }
710            buffer
711                .append(first_local_segment_index.as_bytes())
712                .expect("Checked size above; qed");
713        }
714        let mut previous_local_segment_index = None;
715        for (local_segment_index, own_segment_root) in own_segments {
716            // Only the first local segment index is stored, the rest must follow it one by one
717            if let Some(previous_local_segment_index) = previous_local_segment_index
718                && LocalSegmentIndex::forward_checked(previous_local_segment_index, 1)
719                    != Some(local_segment_index)
720            {
721                return Err(OwnedBeaconChainBodyError::NonConsecutiveOwnSegmentIndices {
722                    previous_local_segment_index,
723                    local_segment_index,
724                });
725            }
726            previous_local_segment_index = Some(local_segment_index);
727
728            buffer
729                .append(own_segment_root.as_ref())
730                .expect("Checked size above; qed");
731        }
732        // TODO: Would be nice for `IntermediateShardBlocksInfo` to have API to write this by itself
733        {
734            buffer
735                .append(&num_blocks.to_le_bytes())
736                .expect("Fixed size data structures that are guaranteed to fit; qed");
737            let mut segments_roots_num_cursor = buffer.len() as usize;
738            for _ in 0..num_blocks {
739                // Placeholder values for the number of own segment roots, number of leaf shard
740                // blocks and number of leaf shard blocks with segments
741                buffer
742                    .append(&[0; IntermediateShardBlockCounts::SIZE])
743                    .expect("Checked size above; qed");
744            }
745            buffer
746                .pad_to_alignment::<Align8>()
747                .expect("Checked size above; qed");
748            for intermediate_shard_block in intermediate_shard_blocks {
749                let counts = IntermediateShardBlockCounts {
750                    num_own_segment_roots: intermediate_shard_block
751                        .own_segments
752                        .as_ref()
753                        .map_or_default(|own_segments| own_segments.num_segment_roots().get()),
754                    num_leaf_shard_blocks: intermediate_shard_block.num_leaf_shard_blocks(),
755                    num_leaf_shard_blocks_with_segments: intermediate_shard_block
756                        .num_leaf_shard_blocks_with_segments(),
757                };
758                buffer.as_mut_slice()[segments_roots_num_cursor..]
759                    [..IntermediateShardBlockCounts::SIZE]
760                    .copy_from_slice(&counts.to_bytes());
761                segments_roots_num_cursor += IntermediateShardBlockCounts::SIZE;
762
763                buffer
764                    .append(intermediate_shard_block.header.bytes())
765                    .map_err(|_error| OwnedBeaconChainBodyError::BlockBodyIsTooLarge)?;
766                if let Some(own_segments) = &intermediate_shard_block.own_segments {
767                    buffer
768                        .append(own_segments.first_local_segment_index.as_bytes())
769                        .map_err(|_error| OwnedBeaconChainBodyError::BlockBodyIsTooLarge)?;
770                    buffer
771                        .append(SegmentRoot::slice_as_bytes(own_segments.segment_roots))
772                        .map_err(|_error| OwnedBeaconChainBodyError::BlockBodyIsTooLarge)?;
773                }
774                buffer
775                    .append(intermediate_shard_block.leaf_shards_segments_bytes)
776                    .map_err(|_error| OwnedBeaconChainBodyError::BlockBodyIsTooLarge)?;
777                buffer
778                    .pad_to_alignment::<Align8>()
779                    .map_err(|_error| OwnedBeaconChainBodyError::BlockBodyIsTooLarge)?;
780            }
781        }
782
783        buffer
784            .append(PotCheckpoints::slice_as_bytes(pot_checkpoints))
785            .map_err(|_error| OwnedBeaconChainBodyError::BlockBodyIsTooLarge)?;
786
787        Self::from_buffer(buffer.into_shared()).map_err(|_buffer| {
788            // Everything is written the way the parser reads it, and infos can only be created by
789            // parsers that check them, so only the order of intermediate shard blocks can be
790            // rejected
791            OwnedBeaconChainBodyError::InconsistentIntermediateShardBlocks
792        })
793    }
794
795    /// Create an owned body from a buffer
796    #[inline]
797    pub fn from_buffer(buffer: SharedAlignedBuffer) -> Result<Self, SharedAlignedBuffer> {
798        // TODO: Cloning is cheap, but will not be necessary if/when this is resolved:
799        //  https://github.com/unicode-org/icu4x/issues/6665
800        let inner = Yoke::try_attach_to_cart(buffer.clone(), |buffer| {
801            let Some((body, extra_bytes)) = BeaconChainBody::try_from_bytes(buffer) else {
802                return Err(());
803            };
804            if !extra_bytes.is_empty() {
805                return Err(());
806            }
807
808            Ok(body)
809        })
810        .map_err(move |()| buffer)?;
811
812        Ok(Self {
813            inner: Arc::new(inner),
814        })
815    }
816
817    /// Inner buffer with block body contents
818    #[inline(always)]
819    pub fn buffer(&self) -> &SharedAlignedBuffer {
820        self.inner.backing_cart()
821    }
822
823    /// Number of clones in memory
824    #[inline(always)]
825    pub fn ref_count(&self) -> usize {
826        Arc::count(&self.inner)
827    }
828
829    /// Get [`BeaconChainBody`] out of [`OwnedBeaconChainBody`]
830    #[inline(always)]
831    pub fn body(&self) -> &BeaconChainBody<'_> {
832        self.inner.get()
833    }
834
835    /// Compute block body root, see [`BeaconChainBody::root()`] for details
836    #[inline(always)]
837    pub fn root(&self) -> Blake3Hash {
838        self.body().root()
839    }
840}
841
842/// Errors for [`OwnedIntermediateShardBody`]
843#[derive(Debug, thiserror::Error)]
844pub enum OwnedIntermediateShardBodyError {
845    /// Too many own segment roots
846    #[error("Too many own segment roots: {actual}")]
847    TooManyOwnSegmentRoots {
848        /// Actual number of own segment roots
849        actual: usize,
850    },
851    /// Local segment index after the last own segment root doesn't fit into `u64`
852    #[error("Own segment index overflow, first local segment index: {first_local_segment_index}")]
853    OwnSegmentIndexOverflow {
854        /// Local segment index of the first own segment root
855        first_local_segment_index: LocalSegmentIndex,
856    },
857    /// Local segment indices of own segment roots are not consecutive
858    #[error(
859        "Own segment indices are not consecutive: {local_segment_index} after \
860        {previous_local_segment_index}"
861    )]
862    NonConsecutiveOwnSegmentIndices {
863        /// Local segment index of the previous own segment root
864        previous_local_segment_index: LocalSegmentIndex,
865        /// Local segment index that doesn't follow the previous one
866        local_segment_index: LocalSegmentIndex,
867    },
868    /// Too many leaf shard blocks
869    #[error("Too many leaf shard blocks: {actual}")]
870    TooManyLeafShardBlocks {
871        /// Actual number of leaf shard blocks
872        actual: usize,
873    },
874    /// Leaf shard blocks are not in the order described in
875    /// [`LeafShardBlocksInfo::try_from_bytes()`]
876    ///
877    /// [`LeafShardBlocksInfo::try_from_bytes()`]:
878    /// crate::block::body::LeafShardBlocksInfo::try_from_bytes
879    #[error("Leaf shard blocks are inconsistent")]
880    InconsistentLeafShardBlocks,
881}
882
883/// An owned version of [`IntermediateShardBody`].
884///
885/// It is correctly aligned in memory and well suited for sending and receiving over the network
886/// efficiently or storing in memory or on disk.
887#[derive(Debug, Clone)]
888pub struct OwnedIntermediateShardBody {
889    inner: Arc<Yoke<IntermediateShardBody<'static>, SharedAlignedBuffer>>,
890}
891
892impl GenericOwnedBlockBody for OwnedIntermediateShardBody {
893    const SHARD_KIND: RealShardKind = RealShardKind::IntermediateShard;
894
895    type Body<'a> = IntermediateShardBody<'a>;
896
897    #[inline(always)]
898    fn from_buffer(buffer: SharedAlignedBuffer) -> Result<Self, SharedAlignedBuffer> {
899        Self::from_buffer(buffer)
900    }
901
902    #[inline(always)]
903    fn buffer(&self) -> &SharedAlignedBuffer {
904        self.buffer()
905    }
906
907    #[inline(always)]
908    fn ref_count(&self) -> usize {
909        self.ref_count()
910    }
911
912    #[inline(always)]
913    fn body(&self) -> &Self::Body<'_> {
914        self.body()
915    }
916
917    #[inline(always)]
918    fn root(&self) -> Blake3Hash {
919        self.root()
920    }
921}
922
923impl OwnedIntermediateShardBody {
924    /// Create a new instance
925    pub fn new<'a, OS, LSB>(
926        own_segments: OS,
927        leaf_shard_blocks: LSB,
928    ) -> Result<Self, OwnedIntermediateShardBodyError>
929    where
930        OS: TrustedLen<Item = (LocalSegmentIndex, SegmentRoot)>,
931        LSB: TrustedLen<Item = LeafShardBlockInfo<'a>> + 'a,
932    {
933        let num_own_segment_roots = own_segments.size_hint().0;
934        let num_own_segment_roots = u8::try_from(num_own_segment_roots).map_err(|_error| {
935            OwnedIntermediateShardBodyError::TooManyOwnSegmentRoots {
936                actual: num_own_segment_roots,
937            }
938        })?;
939        let num_blocks = leaf_shard_blocks.size_hint().0;
940        let num_blocks = u16::try_from(num_blocks).map_err(|_error| {
941            OwnedIntermediateShardBodyError::TooManyLeafShardBlocks { actual: num_blocks }
942        })?;
943
944        let mut buffer = OwnedAlignedBuffer::with_capacity(
945            (
946                // Number of own segment roots
947                u8::SIZE
948                    // Local segment index of the first own segment root
949                    + if num_own_segment_roots > 0 { LocalSegmentIndex::SIZE } else { 0 }
950                    // Own segment roots
951                    + u32::from(num_own_segment_roots) * SegmentRoot::SIZE as u32
952                    // Number of leaf shard blocks
953                    + u16::SIZE
954                    // Numbers of own segment roots of each block
955                    + u32::from(num_blocks) * u8::SIZE
956            )
957            // Padding to 8-bytes boundary
958            .next_multiple_of(u32::from(Alignment::of::<u64>().get()))
959                // This is only an estimate of leaf shard blocks to get in the ballpark where
960                // reallocation should not be necessary
961                + u32::from(num_blocks) * OwnedLeafShardHeader::MAX_ALLOCATION * 2,
962        );
963
964        buffer
965            .append(&[num_own_segment_roots])
966            .expect("Fixed size data structures that are guaranteed to fit; qed");
967        let mut own_segments = own_segments.peekable();
968        if let Some(&(first_local_segment_index, _own_segment_root)) = own_segments.peek() {
969            // The parser rejects bodies where the index after the last segment root doesn't fit
970            // into `u64`
971            if LocalSegmentIndex::forward_checked(
972                first_local_segment_index,
973                usize::from(num_own_segment_roots),
974            )
975            .is_none()
976            {
977                return Err(OwnedIntermediateShardBodyError::OwnSegmentIndexOverflow {
978                    first_local_segment_index,
979                });
980            }
981            buffer
982                .append(first_local_segment_index.as_bytes())
983                .expect("Enough capacity was allocated above; qed");
984        }
985        let mut previous_local_segment_index = None;
986        for (local_segment_index, own_segment_root) in own_segments {
987            // Only the first local segment index is stored, the rest must follow it one by one
988            if let Some(previous_local_segment_index) = previous_local_segment_index
989                && LocalSegmentIndex::forward_checked(previous_local_segment_index, 1)
990                    != Some(local_segment_index)
991            {
992                return Err(
993                    OwnedIntermediateShardBodyError::NonConsecutiveOwnSegmentIndices {
994                        previous_local_segment_index,
995                        local_segment_index,
996                    },
997                );
998            }
999            previous_local_segment_index = Some(local_segment_index);
1000
1001            buffer
1002                .append(own_segment_root.as_ref())
1003                .expect("Enough capacity was allocated above; qed");
1004        }
1005        // TODO: Would be nice for `LeafShardBlocksInfo` to have API to write this by itself
1006        {
1007            buffer
1008                .append(&num_blocks.to_le_bytes())
1009                .expect("Fixed size data structures that are guaranteed to fit; qed");
1010            let mut own_segments_roots_num_cursor = buffer.len() as usize;
1011            for _ in 0..num_blocks {
1012                buffer
1013                    .append(&[0])
1014                    .expect("Enough capacity was allocated above; qed");
1015            }
1016            buffer
1017                .pad_to_alignment::<Align8>()
1018                .expect("Enough capacity was allocated above; qed");
1019            for leaf_shard_block in leaf_shard_blocks {
1020                if let Some(own_segments) = &leaf_shard_block.own_segments {
1021                    buffer.as_mut_slice()[own_segments_roots_num_cursor] =
1022                        own_segments.num_segment_roots().get();
1023                }
1024                own_segments_roots_num_cursor += 1;
1025
1026                append_leaf_shard_block_record(
1027                    &mut buffer,
1028                    &leaf_shard_block.header,
1029                    leaf_shard_block.transactions_root,
1030                    leaf_shard_block.own_segments.as_ref(),
1031                )
1032                .expect(
1033                    "Bodies with at most `u16::MAX` leaf shard blocks with at most `u8::MAX` \
1034                    segment roots each are smaller than 1 GiB, which fits into a buffer even where \
1035                    `usize` is 32-bit; qed",
1036                );
1037            }
1038        }
1039
1040        Self::from_buffer(buffer.into_shared()).map_err(|_buffer| {
1041            // Everything is written the way the parser reads it, and infos can only be created by
1042            // parsers that check them, so only the order of leaf shard blocks can be rejected
1043            OwnedIntermediateShardBodyError::InconsistentLeafShardBlocks
1044        })
1045    }
1046
1047    /// Create an owned body from a buffer
1048    #[inline]
1049    pub fn from_buffer(buffer: SharedAlignedBuffer) -> Result<Self, SharedAlignedBuffer> {
1050        // TODO: Cloning is cheap, but will not be necessary if/when this is resolved:
1051        //  https://github.com/unicode-org/icu4x/issues/6665
1052        let inner = Yoke::try_attach_to_cart(buffer.clone(), |buffer| {
1053            let Some((body, extra_bytes)) = IntermediateShardBody::try_from_bytes(buffer) else {
1054                return Err(());
1055            };
1056            if !extra_bytes.is_empty() {
1057                return Err(());
1058            }
1059
1060            Ok(body)
1061        })
1062        .map_err(move |()| buffer)?;
1063
1064        Ok(Self {
1065            inner: Arc::new(inner),
1066        })
1067    }
1068
1069    /// Inner buffer with block body contents
1070    #[inline(always)]
1071    pub fn buffer(&self) -> &SharedAlignedBuffer {
1072        self.inner.backing_cart()
1073    }
1074
1075    /// Number of clones in memory
1076    #[inline(always)]
1077    pub fn ref_count(&self) -> usize {
1078        Arc::count(&self.inner)
1079    }
1080
1081    /// Get [`IntermediateShardBody`] out of [`OwnedIntermediateShardBody`]
1082    #[inline(always)]
1083    pub fn body(&self) -> &IntermediateShardBody<'_> {
1084        self.inner.get()
1085    }
1086
1087    /// Compute block body root, see [`IntermediateShardBody::root()`] for details
1088    #[inline(always)]
1089    pub fn root(&self) -> Blake3Hash {
1090        self.body().root()
1091    }
1092}
1093
1094/// An owned version of [`LeafShardBody`].
1095///
1096/// It is correctly aligned in memory and well suited for sending and receiving over the network
1097/// efficiently or storing in memory or on disk.
1098#[derive(Debug, Clone)]
1099pub struct OwnedLeafShardBody {
1100    inner: Arc<Yoke<LeafShardBody<'static>, SharedAlignedBuffer>>,
1101}
1102
1103impl GenericOwnedBlockBody for OwnedLeafShardBody {
1104    const SHARD_KIND: RealShardKind = RealShardKind::LeafShard;
1105
1106    type Body<'a> = LeafShardBody<'a>;
1107
1108    #[inline(always)]
1109    fn from_buffer(buffer: SharedAlignedBuffer) -> Result<Self, SharedAlignedBuffer> {
1110        Self::from_buffer(buffer)
1111    }
1112
1113    #[inline(always)]
1114    fn buffer(&self) -> &SharedAlignedBuffer {
1115        self.buffer()
1116    }
1117
1118    #[inline(always)]
1119    fn ref_count(&self) -> usize {
1120        self.ref_count()
1121    }
1122
1123    #[inline(always)]
1124    fn body(&self) -> &Self::Body<'_> {
1125        self.body()
1126    }
1127
1128    #[inline(always)]
1129    fn root(&self) -> Blake3Hash {
1130        self.root()
1131    }
1132}
1133
1134impl OwnedLeafShardBody {
1135    /// Initialize building of [`OwnedLeafShardBody`]
1136    pub fn init<OS>(
1137        own_segments: OS,
1138    ) -> Result<OwnedLeafShardBlockBodyBuilder, OwnedLeafShardBodyError>
1139    where
1140        OS: TrustedLen<Item = (LocalSegmentIndex, SegmentRoot)>,
1141    {
1142        let num_own_segment_roots = own_segments.size_hint().0;
1143        let num_own_segment_roots = u8::try_from(num_own_segment_roots).map_err(|_error| {
1144            OwnedLeafShardBodyError::TooManyOwnSegmentRoots {
1145                actual: num_own_segment_roots,
1146            }
1147        })?;
1148
1149        // Transactions are not known yet, the buffer grows when they are added
1150        let mut buffer = OwnedAlignedBuffer::with_capacity(
1151            (
1152                // Number of own segment roots
1153                u8::SIZE
1154                    // Local segment index of the first own segment root
1155                    + if num_own_segment_roots > 0 {
1156                        LocalSegmentIndex::SIZE
1157                    } else {
1158                        0
1159                    }
1160                    // Own segment roots
1161                    + u32::from(num_own_segment_roots) * SegmentRoot::SIZE as u32
1162                    // Number of transactions
1163                    + u32::SIZE
1164            )
1165                // Padding to 16-bytes boundary
1166                .next_multiple_of(u32::from(Alignment::MAX.get())),
1167        );
1168
1169        buffer
1170            .append(&[num_own_segment_roots])
1171            .expect("Fixed size data structures that are guaranteed to fit; qed");
1172        let mut own_segments = own_segments.peekable();
1173        if let Some(&(first_local_segment_index, _own_segment_root)) = own_segments.peek() {
1174            // The parser rejects bodies where the index after the last segment root doesn't fit
1175            // into `u64`
1176            if LocalSegmentIndex::forward_checked(
1177                first_local_segment_index,
1178                usize::from(num_own_segment_roots),
1179            )
1180            .is_none()
1181            {
1182                return Err(OwnedLeafShardBodyError::OwnSegmentIndexOverflow {
1183                    first_local_segment_index,
1184                });
1185            }
1186            buffer
1187                .append(first_local_segment_index.as_bytes())
1188                .expect("Enough capacity was allocated above; qed");
1189        }
1190        let mut previous_local_segment_index = None;
1191        for (local_segment_index, own_segment_root) in own_segments {
1192            // Only the first local segment index is stored, the rest must follow it one by one
1193            if let Some(previous_local_segment_index) = previous_local_segment_index
1194                && LocalSegmentIndex::forward_checked(previous_local_segment_index, 1)
1195                    != Some(local_segment_index)
1196            {
1197                return Err(OwnedLeafShardBodyError::NonConsecutiveOwnSegmentIndices {
1198                    previous_local_segment_index,
1199                    local_segment_index,
1200                });
1201            }
1202            previous_local_segment_index = Some(local_segment_index);
1203
1204            buffer
1205                .append(own_segment_root.as_ref())
1206                .expect("Enough capacity was allocated above; qed");
1207        }
1208
1209        let num_transactions_offset = buffer.len() as usize;
1210        buffer
1211            .append(&0u32.to_le_bytes())
1212            .expect("Enough capacity was allocated above; qed");
1213        // The parser expects padding after the number of transactions even if there are none
1214        buffer
1215            .pad_to_alignment::<Align16>()
1216            .expect("Enough capacity was allocated above; qed");
1217
1218        Ok(OwnedLeafShardBlockBodyBuilder {
1219            transaction_builder: TransactionBuilder::new(num_transactions_offset, buffer),
1220        })
1221    }
1222
1223    /// Create an owned body from a buffer
1224    #[inline]
1225    pub fn from_buffer(buffer: SharedAlignedBuffer) -> Result<Self, SharedAlignedBuffer> {
1226        // TODO: Cloning is cheap, but will not be necessary if/when this is resolved:
1227        //  https://github.com/unicode-org/icu4x/issues/6665
1228        let inner = Yoke::try_attach_to_cart(buffer.clone(), |buffer| {
1229            let Some((body, extra_bytes)) = LeafShardBody::try_from_bytes(buffer) else {
1230                return Err(());
1231            };
1232            if !extra_bytes.is_empty() {
1233                return Err(());
1234            }
1235
1236            Ok(body)
1237        })
1238        .map_err(move |()| buffer)?;
1239
1240        Ok(Self {
1241            inner: Arc::new(inner),
1242        })
1243    }
1244
1245    /// Inner buffer with block body contents
1246    #[inline(always)]
1247    pub fn buffer(&self) -> &SharedAlignedBuffer {
1248        self.inner.backing_cart()
1249    }
1250
1251    /// Number of clones in memory
1252    #[inline(always)]
1253    pub fn ref_count(&self) -> usize {
1254        Arc::count(&self.inner)
1255    }
1256
1257    /// Get [`LeafShardBody`] out of [`OwnedLeafShardBody`]
1258    #[inline(always)]
1259    pub fn body(&self) -> &LeafShardBody<'_> {
1260        self.inner.get()
1261    }
1262
1263    /// Compute block body root, see [`LeafShardBody::root()`] for details
1264    #[inline(always)]
1265    pub fn root(&self) -> Blake3Hash {
1266        self.body().root()
1267    }
1268}
1269
1270/// Builder for [`OwnedLeafShardBody`] that allows to add more transactions
1271#[derive(Debug, Clone)]
1272pub struct OwnedLeafShardBlockBodyBuilder {
1273    transaction_builder: TransactionBuilder,
1274}
1275
1276impl OwnedLeafShardBlockBodyBuilder {
1277    /// Add transaction to the body
1278    #[inline(always)]
1279    pub fn add_transaction<T>(&mut self, transaction: T) -> Result<(), OwnedLeafShardBodyError>
1280    where
1281        T: WritableBodyTransaction,
1282    {
1283        self.transaction_builder.add_transaction(transaction)?;
1284
1285        Ok(())
1286    }
1287
1288    /// Finish building block body
1289    pub fn finish(self) -> OwnedLeafShardBody {
1290        OwnedLeafShardBody::from_buffer(self.transaction_builder.finish().into_shared()).expect(
1291            "`init()` wrote valid own segments and a zero number of transactions, each added \
1292            transaction is an already parsed one followed by padding and increments that number, \
1293            and the buffer is 16-byte aligned and can't be longer than `u32::MAX` bytes; qed",
1294        )
1295    }
1296}
1297
1298/// An owned version of [`BlockBody`].
1299///
1300/// It is correctly aligned in memory and well suited for sending and receiving over the network
1301/// efficiently or storing in memory or on disk.
1302#[derive(Debug, Clone, From)]
1303pub enum OwnedBlockBody {
1304    /// Block body corresponds to the beacon chain
1305    BeaconChain(OwnedBeaconChainBody),
1306    /// Block body corresponds to an intermediate shard
1307    IntermediateShard(OwnedIntermediateShardBody),
1308    /// Block body corresponds to a leaf shard
1309    LeafShard(OwnedLeafShardBody),
1310}
1311
1312impl OwnedBlockBody {
1313    /// Create an owned body from a buffer
1314    #[inline]
1315    pub fn from_buffer(
1316        buffer: SharedAlignedBuffer,
1317        shard_kind: RealShardKind,
1318    ) -> Result<Self, SharedAlignedBuffer> {
1319        Ok(match shard_kind {
1320            RealShardKind::BeaconChain => {
1321                Self::BeaconChain(OwnedBeaconChainBody::from_buffer(buffer)?)
1322            }
1323            RealShardKind::IntermediateShard => {
1324                Self::IntermediateShard(OwnedIntermediateShardBody::from_buffer(buffer)?)
1325            }
1326            RealShardKind::LeafShard => Self::LeafShard(OwnedLeafShardBody::from_buffer(buffer)?),
1327        })
1328    }
1329
1330    /// Inner buffer block body contents
1331    #[inline]
1332    pub fn buffer(&self) -> &SharedAlignedBuffer {
1333        match self {
1334            Self::BeaconChain(owned_body) => owned_body.buffer(),
1335            Self::IntermediateShard(owned_body) => owned_body.buffer(),
1336            Self::LeafShard(owned_body) => owned_body.buffer(),
1337        }
1338    }
1339
1340    /// Number of clones in memory
1341    #[inline(always)]
1342    pub fn ref_count(&self) -> usize {
1343        match self {
1344            Self::BeaconChain(owned_body) => owned_body.ref_count(),
1345            Self::IntermediateShard(owned_body) => owned_body.ref_count(),
1346            Self::LeafShard(owned_body) => owned_body.ref_count(),
1347        }
1348    }
1349
1350    /// Get [`BlockBody`] out of [`OwnedBlockBody`]
1351    #[inline]
1352    pub fn body(&self) -> BlockBody<'_> {
1353        match self {
1354            Self::BeaconChain(owned_body) => BlockBody::BeaconChain(*owned_body.body()),
1355            Self::IntermediateShard(owned_body) => BlockBody::IntermediateShard(*owned_body.body()),
1356            Self::LeafShard(owned_body) => BlockBody::LeafShard(*owned_body.body()),
1357        }
1358    }
1359
1360    /// Compute block body root, see [`BlockBody::root()`] for details
1361    #[inline]
1362    pub fn root(&self) -> Blake3Hash {
1363        match self {
1364            Self::BeaconChain(owned_body) => owned_body.root(),
1365            Self::IntermediateShard(owned_body) => owned_body.root(),
1366            Self::LeafShard(owned_body) => owned_body.root(),
1367        }
1368    }
1369}