1#[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
49pub trait GenericOwnedBlockBody:
51 Clone + fmt::Debug + Send + Sync + Into<OwnedBlockBody> + 'static
52{
53 const SHARD_KIND: RealShardKind;
55
56 type Body<'a>: GenericBlockBody<'a>
58 where
59 Self: 'a;
60
61 fn from_buffer(buffer: SharedAlignedBuffer) -> Result<Self, SharedAlignedBuffer>;
63
64 fn buffer(&self) -> &SharedAlignedBuffer;
66
67 fn ref_count(&self) -> usize;
69
70 fn body(&self) -> &Self::Body<'_>;
72
73 fn root(&self) -> Blake3Hash;
75}
76
77#[derive(Debug, thiserror::Error)]
79pub enum OwnedLeafShardBodyError {
80 #[error("Too many own segment roots: {actual}")]
82 TooManyOwnSegmentRoots {
83 actual: usize,
85 },
86 #[error("Own segment index overflow, first local segment index: {first_local_segment_index}")]
88 OwnSegmentIndexOverflow {
89 first_local_segment_index: LocalSegmentIndex,
91 },
92 #[error(
94 "Own segment indices are not consecutive: {local_segment_index} after \
95 {previous_local_segment_index}"
96 )]
97 NonConsecutiveOwnSegmentIndices {
98 previous_local_segment_index: LocalSegmentIndex,
100 local_segment_index: LocalSegmentIndex,
102 },
103 #[error("Block body is too large")]
105 BlockBodyIsTooLarge,
106}
107
108pub impl(self) trait WritableBodyTransaction {
113 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 fn add_transaction<T>(&mut self, transaction: T) -> Result<(), OwnedLeafShardBodyError>
157 where
158 T: WritableBodyTransaction,
159 {
160 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 unsafe {
175 self.buffer.set_len(old_buffer_len);
176 }
177 return Err(OwnedLeafShardBodyError::BlockBodyIsTooLarge);
178 }
179
180 Ok(())
181 }
182
183 #[inline(always)]
185 fn finish(self) -> OwnedAlignedBuffer {
186 self.buffer
187 }
188
189 #[inline(always)]
191 fn inc_transaction_count(&mut self) {
192 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 #[inline(always)]
211 fn dec_transaction_count(&mut self) {
212 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#[derive(Debug)]
229struct RecordTooLarge;
230
231fn 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#[derive(Debug, Yokeable)]
270struct YokeableIntermediateShardBlockInfo<'a>(IntermediateShardBlockInfo<'a>);
271
272#[derive(Debug, Clone)]
277pub struct OwnedIntermediateShardBlockInfo {
278 inner: Arc<Yoke<YokeableIntermediateShardBlockInfo<'static>, SharedAlignedBuffer>>,
279}
280
281impl OwnedIntermediateShardBlockInfo {
282 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 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 #[inline]
389 pub fn from_buffer(buffer: SharedAlignedBuffer) -> Result<Self, SharedAlignedBuffer> {
390 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 #[inline(always)]
413 pub fn buffer(&self) -> &SharedAlignedBuffer {
414 self.inner.backing_cart()
415 }
416
417 #[inline(always)]
419 pub fn info(&self) -> &IntermediateShardBlockInfo<'_> {
420 let YokeableIntermediateShardBlockInfo(info) = self.inner.get();
421 info
422 }
423}
424
425#[derive(Debug, Yokeable)]
428struct YokeableLeafShardBlockInfo<'a>(LeafShardBlockInfo<'a>);
429
430#[derive(Debug, Clone)]
435pub struct OwnedLeafShardBlockInfo {
436 inner: Arc<Yoke<YokeableLeafShardBlockInfo<'static>, SharedAlignedBuffer>>,
437}
438
439impl OwnedLeafShardBlockInfo {
440 pub fn from_block(block: &LeafShardBlock<'_>) -> Self {
442 let own_segments = block.body.own_segments();
443
444 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 #[inline]
482 pub fn from_buffer(buffer: SharedAlignedBuffer) -> Result<Self, SharedAlignedBuffer> {
483 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 #[inline(always)]
505 pub fn buffer(&self) -> &SharedAlignedBuffer {
506 self.inner.backing_cart()
507 }
508
509 #[inline(always)]
511 pub fn info(&self) -> &LeafShardBlockInfo<'_> {
512 let YokeableLeafShardBlockInfo(info) = self.inner.get();
513 info
514 }
515}
516
517#[derive(Debug, thiserror::Error)]
519pub enum OwnedBeaconChainBodyError {
520 #[error("Too many PoT checkpoints: {actual}")]
522 TooManyPotCheckpoints {
523 actual: usize,
525 },
526 #[error("Too many own segment roots: {actual}")]
528 TooManyOwnSegmentRoots {
529 actual: usize,
531 },
532 #[error("Own segment index overflow, first local segment index: {first_local_segment_index}")]
534 OwnSegmentIndexOverflow {
535 first_local_segment_index: LocalSegmentIndex,
537 },
538 #[error(
540 "Own segment indices are not consecutive: {local_segment_index} after \
541 {previous_local_segment_index}"
542 )]
543 NonConsecutiveOwnSegmentIndices {
544 previous_local_segment_index: LocalSegmentIndex,
546 local_segment_index: LocalSegmentIndex,
548 },
549 #[error("Too many intermediate shard blocks: {actual}")]
551 TooManyIntermediateShardBlocks {
552 actual: usize,
554 },
555 #[error("Block body is too large")]
557 BlockBodyIsTooLarge,
558 #[error("Intermediate shard blocks are inconsistent")]
564 InconsistentIntermediateShardBlocks,
565}
566
567#[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 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 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 let pot_checkpoints_size = num_pot_checkpoints
639 .checked_mul(PotCheckpoints::SIZE as u32)
640 .ok_or(OwnedBeaconChainBodyError::BlockBodyIsTooLarge)?;
641 let fixed_size = (
642 u32::SIZE
644 + u8::SIZE
646 + if num_own_segment_roots > 0 { LocalSegmentIndex::SIZE } else { 0 }
648 + u32::from(num_own_segment_roots) * SegmentRoot::SIZE as u32
650 + u16::SIZE
652 + u32::from(num_blocks) * (u8::SIZE + 2 * u16::SIZE)
655 )
656 .next_multiple_of(u32::from(Alignment::of::<u64>().get()));
658 #[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 let intermediate_shard_blocks_size =
674 u32::from(num_blocks) * OwnedIntermediateShardHeader::MAX_ALLOCATION * 2;
675 #[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 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 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 {
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 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 OwnedBeaconChainBodyError::InconsistentIntermediateShardBlocks
792 })
793 }
794
795 #[inline]
797 pub fn from_buffer(buffer: SharedAlignedBuffer) -> Result<Self, SharedAlignedBuffer> {
798 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 #[inline(always)]
819 pub fn buffer(&self) -> &SharedAlignedBuffer {
820 self.inner.backing_cart()
821 }
822
823 #[inline(always)]
825 pub fn ref_count(&self) -> usize {
826 Arc::count(&self.inner)
827 }
828
829 #[inline(always)]
831 pub fn body(&self) -> &BeaconChainBody<'_> {
832 self.inner.get()
833 }
834
835 #[inline(always)]
837 pub fn root(&self) -> Blake3Hash {
838 self.body().root()
839 }
840}
841
842#[derive(Debug, thiserror::Error)]
844pub enum OwnedIntermediateShardBodyError {
845 #[error("Too many own segment roots: {actual}")]
847 TooManyOwnSegmentRoots {
848 actual: usize,
850 },
851 #[error("Own segment index overflow, first local segment index: {first_local_segment_index}")]
853 OwnSegmentIndexOverflow {
854 first_local_segment_index: LocalSegmentIndex,
856 },
857 #[error(
859 "Own segment indices are not consecutive: {local_segment_index} after \
860 {previous_local_segment_index}"
861 )]
862 NonConsecutiveOwnSegmentIndices {
863 previous_local_segment_index: LocalSegmentIndex,
865 local_segment_index: LocalSegmentIndex,
867 },
868 #[error("Too many leaf shard blocks: {actual}")]
870 TooManyLeafShardBlocks {
871 actual: usize,
873 },
874 #[error("Leaf shard blocks are inconsistent")]
880 InconsistentLeafShardBlocks,
881}
882
883#[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 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 u8::SIZE
948 + if num_own_segment_roots > 0 { LocalSegmentIndex::SIZE } else { 0 }
950 + u32::from(num_own_segment_roots) * SegmentRoot::SIZE as u32
952 + u16::SIZE
954 + u32::from(num_blocks) * u8::SIZE
956 )
957 .next_multiple_of(u32::from(Alignment::of::<u64>().get()))
959 + 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 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 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 {
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 OwnedIntermediateShardBodyError::InconsistentLeafShardBlocks
1044 })
1045 }
1046
1047 #[inline]
1049 pub fn from_buffer(buffer: SharedAlignedBuffer) -> Result<Self, SharedAlignedBuffer> {
1050 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 #[inline(always)]
1071 pub fn buffer(&self) -> &SharedAlignedBuffer {
1072 self.inner.backing_cart()
1073 }
1074
1075 #[inline(always)]
1077 pub fn ref_count(&self) -> usize {
1078 Arc::count(&self.inner)
1079 }
1080
1081 #[inline(always)]
1083 pub fn body(&self) -> &IntermediateShardBody<'_> {
1084 self.inner.get()
1085 }
1086
1087 #[inline(always)]
1089 pub fn root(&self) -> Blake3Hash {
1090 self.body().root()
1091 }
1092}
1093
1094#[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 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 let mut buffer = OwnedAlignedBuffer::with_capacity(
1151 (
1152 u8::SIZE
1154 + if num_own_segment_roots > 0 {
1156 LocalSegmentIndex::SIZE
1157 } else {
1158 0
1159 }
1160 + u32::from(num_own_segment_roots) * SegmentRoot::SIZE as u32
1162 + u32::SIZE
1164 )
1165 .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 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 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 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 #[inline]
1225 pub fn from_buffer(buffer: SharedAlignedBuffer) -> Result<Self, SharedAlignedBuffer> {
1226 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 #[inline(always)]
1247 pub fn buffer(&self) -> &SharedAlignedBuffer {
1248 self.inner.backing_cart()
1249 }
1250
1251 #[inline(always)]
1253 pub fn ref_count(&self) -> usize {
1254 Arc::count(&self.inner)
1255 }
1256
1257 #[inline(always)]
1259 pub fn body(&self) -> &LeafShardBody<'_> {
1260 self.inner.get()
1261 }
1262
1263 #[inline(always)]
1265 pub fn root(&self) -> Blake3Hash {
1266 self.body().root()
1267 }
1268}
1269
1270#[derive(Debug, Clone)]
1272pub struct OwnedLeafShardBlockBodyBuilder {
1273 transaction_builder: TransactionBuilder,
1274}
1275
1276impl OwnedLeafShardBlockBodyBuilder {
1277 #[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 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#[derive(Debug, Clone, From)]
1303pub enum OwnedBlockBody {
1304 BeaconChain(OwnedBeaconChainBody),
1306 IntermediateShard(OwnedIntermediateShardBody),
1308 LeafShard(OwnedLeafShardBody),
1310}
1311
1312impl OwnedBlockBody {
1313 #[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 #[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 #[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 #[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 #[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}