1pub mod body;
4pub mod header;
5#[cfg(feature = "alloc")]
6pub mod owned;
7
8use crate::block::body::{
9 BeaconChainBody, BlockBody, GenericBlockBody, IntermediateShardBody, LeafShardBlocksInfo,
10 LeafShardBody,
11};
12use crate::block::header::{
13 BeaconChainHeader, BlockHeader, GenericBlockHeader, IntermediateShardHeader, LeafShardHeader,
14};
15#[cfg(feature = "alloc")]
16use crate::block::owned::{
17 GenericOwnedBlock, OwnedBeaconChainBlock, OwnedBlock, OwnedIntermediateShardBlock,
18 OwnedLeafShardBlock,
19};
20use crate::hashes::Blake3Hash;
21use crate::shard::{RealShardKind, ShardIndex};
22use crate::solutions::SolutionRange;
23#[cfg(feature = "serde")]
24use ::serde::{Deserialize, Serialize};
25use ab_io_type::alignment::Alignment;
26use ab_io_type::trivial_type::TrivialType;
27use core::fmt;
28use core::iter::Step;
29use derive_more::{
30 Add, AddAssign, AsMut, AsRef, Deref, DerefMut, Display, From, Into, Sub, SubAssign,
31};
32#[cfg(feature = "scale-codec")]
33use parity_scale_codec::{Decode, Encode, MaxEncodedLen};
34use transparent_wrapper::TransparentWrapper;
35
36#[derive(
38 Debug,
39 Display,
40 Default,
41 Copy,
42 Clone,
43 Ord,
44 PartialOrd,
45 Eq,
46 PartialEq,
47 Hash,
48 Add,
49 AddAssign,
50 Sub,
51 SubAssign,
52 TrivialType,
53)]
54#[cfg_attr(feature = "scale-codec", derive(Encode, Decode, MaxEncodedLen))]
55#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
56#[cfg_attr(feature = "serde", serde(transparent))]
57#[repr(C)]
58pub struct BlockNumber(u64);
59
60impl Step for BlockNumber {
61 #[inline(always)]
62 fn steps_between(start: &Self, end: &Self) -> (usize, Option<usize>) {
63 u64::steps_between(&start.0, &end.0)
64 }
65
66 #[inline(always)]
67 fn forward_checked(start: Self, count: usize) -> Option<Self> {
68 u64::forward_checked(start.0, count).map(Self)
69 }
70
71 #[inline(always)]
72 fn forward_overflowing(start: Self, count: usize) -> (Self, bool) {
73 let (n, overflowing) = u64::forward_overflowing(start.0, count);
74 (Self(n), overflowing)
75 }
76
77 #[inline(always)]
78 fn backward_checked(start: Self, count: usize) -> Option<Self> {
79 u64::backward_checked(start.0, count).map(Self)
80 }
81
82 #[inline(always)]
83 fn backward_overflowing(start: Self, count: usize) -> (Self, bool) {
84 let (n, overflowing) = u64::backward_overflowing(start.0, count);
85 (Self(n), overflowing)
86 }
87}
88
89const impl From<u64> for BlockNumber {
90 #[inline(always)]
91 fn from(value: u64) -> Self {
92 Self(value)
93 }
94}
95
96const impl From<BlockNumber> for u64 {
97 #[inline(always)]
98 fn from(value: BlockNumber) -> Self {
99 value.0
100 }
101}
102
103impl BlockNumber {
104 pub const SIZE: usize = size_of::<u64>();
106 pub const ZERO: BlockNumber = BlockNumber(0);
108 pub const ONE: BlockNumber = BlockNumber(1);
110 pub const MAX: BlockNumber = BlockNumber(u64::MAX);
112
113 #[inline(always)]
115 pub const fn from_bytes(bytes: [u8; Self::SIZE]) -> Self {
116 Self(u64::from_le_bytes(bytes))
117 }
118
119 #[inline(always)]
121 pub const fn to_bytes(self) -> [u8; Self::SIZE] {
122 self.0.to_le_bytes()
123 }
124
125 #[inline(always)]
127 pub const fn checked_add(self, rhs: Self) -> Option<Self> {
128 if let Some(n) = self.0.checked_add(rhs.0) {
129 Some(Self(n))
130 } else {
131 None
132 }
133 }
134
135 #[inline(always)]
137 pub const fn saturating_add(self, rhs: Self) -> Self {
138 Self(self.0.saturating_add(rhs.0))
139 }
140
141 #[inline(always)]
143 pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
144 if let Some(n) = self.0.checked_sub(rhs.0) {
145 Some(Self(n))
146 } else {
147 None
148 }
149 }
150
151 #[inline(always)]
153 pub const fn saturating_sub(self, rhs: Self) -> Self {
154 Self(self.0.saturating_sub(rhs.0))
155 }
156}
157
158#[derive(
160 Debug,
161 Display,
162 Default,
163 Copy,
164 Clone,
165 Ord,
166 PartialOrd,
167 Eq,
168 PartialEq,
169 Hash,
170 From,
171 Into,
172 Add,
173 AddAssign,
174 Sub,
175 SubAssign,
176 TrivialType,
177)]
178#[cfg_attr(feature = "scale-codec", derive(Encode, Decode, MaxEncodedLen))]
179#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
180#[cfg_attr(feature = "serde", serde(transparent))]
181#[repr(C)]
182pub struct BlockTimestamp(u64);
183
184impl BlockTimestamp {
185 pub const SIZE: usize = size_of::<u64>();
187
188 #[inline(always)]
190 pub const fn from_millis(ms: u64) -> Self {
191 Self(ms)
192 }
193
194 #[inline(always)]
196 pub const fn as_millis(self) -> u64 {
197 self.0
198 }
199
200 #[inline(always)]
202 pub const fn checked_add(self, rhs: Self) -> Option<Self> {
203 if let Some(n) = self.0.checked_add(rhs.0) {
204 Some(Self(n))
205 } else {
206 None
207 }
208 }
209
210 #[inline(always)]
212 pub const fn saturating_add(self, rhs: Self) -> Self {
213 Self(self.0.saturating_add(rhs.0))
214 }
215
216 #[inline(always)]
218 pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
219 if let Some(n) = self.0.checked_sub(rhs.0) {
220 Some(Self(n))
221 } else {
222 None
223 }
224 }
225
226 #[inline(always)]
228 pub const fn saturating_sub(self, rhs: Self) -> Self {
229 Self(self.0.saturating_sub(rhs.0))
230 }
231}
232
233#[derive(
238 Debug,
239 Display,
240 Default,
241 Copy,
242 Clone,
243 Eq,
244 PartialEq,
245 Ord,
246 PartialOrd,
247 Hash,
248 From,
249 Into,
250 AsRef,
251 AsMut,
252 Deref,
253 DerefMut,
254 TrivialType,
255 TransparentWrapper,
256)]
257#[cfg_attr(feature = "scale-codec", derive(Encode, Decode, MaxEncodedLen))]
258#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
259#[cfg_attr(feature = "serde", serde(transparent))]
260#[repr(C)]
261pub struct BlockRoot(Blake3Hash);
262
263impl AsRef<[u8]> for BlockRoot {
264 #[inline(always)]
265 fn as_ref(&self) -> &[u8] {
266 self.0.as_ref()
267 }
268}
269
270impl AsMut<[u8]> for BlockRoot {
271 #[inline(always)]
272 fn as_mut(&mut self) -> &mut [u8] {
273 self.0.as_mut()
274 }
275}
276
277impl BlockRoot {
278 pub const SIZE: usize = Blake3Hash::SIZE;
280
281 #[inline(always)]
283 pub const fn new(hash: Blake3Hash) -> Self {
284 Self(hash)
285 }
286}
287
288pub impl(self) trait GenericBlock<'a>
293where
294 Self: Clone + fmt::Debug + Send + Sync,
295{
296 const SHARD_KIND: RealShardKind;
298
299 type Header: GenericBlockHeader<'a>;
301 type Body: GenericBlockBody<'a>;
303 #[cfg(feature = "alloc")]
305 type Owned: GenericOwnedBlock<Block<'a> = Self>
306 where
307 Self: 'a;
308
309 fn header(&self) -> &Self::Header;
311
312 fn body(&self) -> &Self::Body;
314
315 #[cfg(feature = "alloc")]
322 fn to_owned(self) -> Self::Owned;
323}
324
325#[derive(Debug, Clone)]
330pub struct BeaconChainBlock<'a> {
331 pub mut(self) header: BeaconChainHeader<'a>,
333 pub mut(self) body: BeaconChainBody<'a>,
335}
336
337impl<'a> BeaconChainBlock<'a> {
338 #[inline]
348 pub fn try_from_bytes(bytes: &'a [u8]) -> Option<(Self, &'a [u8])> {
349 if !Alignment::MAX.is_slice_aligned(bytes) {
350 return None;
351 }
352
353 let (header, remainder) = BeaconChainHeader::try_from_bytes(bytes)?;
354 let remainder = align_to_and_ensure_zero_padding(remainder, Alignment::MAX)?;
355 let (body, remainder) = BeaconChainBody::try_from_bytes(remainder)?;
356
357 let block = Self { header, body };
358
359 if !block.is_internally_consistent() {
361 return None;
362 }
363
364 Some((block, remainder))
365 }
366
367 #[inline]
371 fn is_internally_consistent(&self) -> bool {
372 let intermediate_shard_blocks_root = self.body.intermediate_shard_blocks().headers_root();
375
376 self.body
379 .root_with_intermediate_shard_blocks_root(&intermediate_shard_blocks_root)
380 == self.header.result.body_root
381 && *self.header.intermediate_shard_blocks_root() == intermediate_shard_blocks_root
382 }
383
384 #[cfg(feature = "alloc")]
391 #[inline(always)]
392 pub fn to_owned(self) -> OwnedBeaconChainBlock {
393 OwnedBeaconChainBlock::from_block(self)
394 }
395}
396
397impl<'a> GenericBlock<'a> for BeaconChainBlock<'a> {
398 const SHARD_KIND: RealShardKind = RealShardKind::BeaconChain;
399
400 type Header = BeaconChainHeader<'a>;
401 type Body = BeaconChainBody<'a>;
402 #[cfg(feature = "alloc")]
403 type Owned = OwnedBeaconChainBlock;
404
405 #[inline(always)]
406 fn header(&self) -> &Self::Header {
407 &self.header
408 }
409
410 #[inline(always)]
411 fn body(&self) -> &Self::Body {
412 &self.body
413 }
414
415 #[cfg(feature = "alloc")]
416 #[inline(always)]
417 fn to_owned(self) -> Self::Owned {
418 self.to_owned()
419 }
420}
421
422#[derive(Debug, Clone)]
427pub struct IntermediateShardBlock<'a> {
428 pub mut(self) header: IntermediateShardHeader<'a>,
430 pub mut(self) body: IntermediateShardBody<'a>,
432}
433
434impl<'a> IntermediateShardBlock<'a> {
435 #[inline]
445 pub fn try_from_bytes(bytes: &'a [u8]) -> Option<(Self, &'a [u8])> {
446 if !Alignment::MAX.is_slice_aligned(bytes) {
447 return None;
448 }
449
450 let (header, remainder) = IntermediateShardHeader::try_from_bytes(bytes)?;
451 let remainder = align_to_and_ensure_zero_padding(remainder, Alignment::MAX)?;
452 let (body, remainder) = IntermediateShardBody::try_from_bytes(remainder)?;
453
454 let block = Self { header, body };
455
456 if !block.is_internally_consistent() {
458 return None;
459 }
460
461 Some((block, remainder))
462 }
463
464 #[inline]
468 fn is_internally_consistent(&self) -> bool {
469 let leaf_shard_blocks_root = self.body.leaf_shard_blocks().headers_root();
472
473 self.body
474 .root_with_leaf_shard_blocks_root(&leaf_shard_blocks_root)
475 == self.header.result.body_root
476 && *self.header.leaf_shard_blocks_root() == leaf_shard_blocks_root
477 && Self::find_leaf_shard_block_of_another_shard(
478 self.body.leaf_shard_blocks(),
479 self.header.prefix.shard_index,
480 )
481 .is_none()
482 }
483
484 #[inline]
489 fn find_leaf_shard_block_of_another_shard(
490 leaf_shard_blocks: &LeafShardBlocksInfo<'_>,
491 shard_index: ShardIndex,
492 ) -> Option<ShardIndex> {
493 leaf_shard_blocks
494 .iter()
495 .map(|leaf_shard_block| leaf_shard_block.header.prefix.shard_index)
496 .find(|leaf_shard_index| !leaf_shard_index.is_child_of(shard_index))
497 }
498
499 #[cfg(feature = "alloc")]
506 #[inline(always)]
507 pub fn to_owned(self) -> OwnedIntermediateShardBlock {
508 OwnedIntermediateShardBlock::from_block(self)
509 }
510}
511
512impl<'a> GenericBlock<'a> for IntermediateShardBlock<'a> {
513 const SHARD_KIND: RealShardKind = RealShardKind::IntermediateShard;
514
515 type Header = IntermediateShardHeader<'a>;
516 type Body = IntermediateShardBody<'a>;
517 #[cfg(feature = "alloc")]
518 type Owned = OwnedIntermediateShardBlock;
519
520 #[inline(always)]
521 fn header(&self) -> &Self::Header {
522 &self.header
523 }
524
525 #[inline(always)]
526 fn body(&self) -> &Self::Body {
527 &self.body
528 }
529
530 #[cfg(feature = "alloc")]
531 #[inline(always)]
532 fn to_owned(self) -> Self::Owned {
533 self.to_owned()
534 }
535}
536
537#[derive(Debug, Clone)]
542pub struct LeafShardBlock<'a> {
543 pub mut(self) header: LeafShardHeader<'a>,
545 pub mut(self) body: LeafShardBody<'a>,
547}
548
549impl<'a> LeafShardBlock<'a> {
550 #[inline]
560 pub fn try_from_bytes(bytes: &'a [u8]) -> Option<(Self, &'a [u8])> {
561 if !Alignment::MAX.is_slice_aligned(bytes) {
562 return None;
563 }
564
565 let (header, remainder) = LeafShardHeader::try_from_bytes(bytes)?;
566 let remainder = align_to_and_ensure_zero_padding(remainder, Alignment::MAX)?;
567 let (body, remainder) = LeafShardBody::try_from_bytes(remainder)?;
568
569 let block = Self { header, body };
570
571 if !block.is_internally_consistent() {
573 return None;
574 }
575
576 Some((block, remainder))
577 }
578
579 #[inline]
583 fn is_internally_consistent(&self) -> bool {
584 self.body.root() == self.header.result.body_root
585 }
586
587 #[cfg(feature = "alloc")]
594 #[inline(always)]
595 pub fn to_owned(self) -> OwnedLeafShardBlock {
596 OwnedLeafShardBlock::from_block(self)
597 }
598}
599
600impl<'a> GenericBlock<'a> for LeafShardBlock<'a> {
601 const SHARD_KIND: RealShardKind = RealShardKind::LeafShard;
602
603 type Header = LeafShardHeader<'a>;
604 type Body = LeafShardBody<'a>;
605 #[cfg(feature = "alloc")]
606 type Owned = OwnedLeafShardBlock;
607
608 #[inline(always)]
609 fn header(&self) -> &Self::Header {
610 &self.header
611 }
612
613 #[inline(always)]
614 fn body(&self) -> &Self::Body {
615 &self.body
616 }
617
618 #[cfg(feature = "alloc")]
619 #[inline(always)]
620 fn to_owned(self) -> Self::Owned {
621 self.to_owned()
622 }
623}
624
625#[derive(Debug, Clone, From)]
627pub enum Block<'a> {
628 BeaconChain(BeaconChainBlock<'a>),
630 IntermediateShard(IntermediateShardBlock<'a>),
632 LeafShard(LeafShardBlock<'a>),
634}
635
636impl<'a> Block<'a> {
637 #[inline]
648 pub fn try_from_bytes(bytes: &'a [u8]) -> Option<(Self, &'a [u8])> {
649 match BlockHeader::shard_kind_from_bytes(bytes)? {
650 RealShardKind::BeaconChain => {
651 let (block_header, remainder) = BeaconChainBlock::try_from_bytes(bytes)?;
652 Some((Self::BeaconChain(block_header), remainder))
653 }
654 RealShardKind::IntermediateShard => {
655 let (block_header, remainder) = IntermediateShardBlock::try_from_bytes(bytes)?;
656 Some((Self::IntermediateShard(block_header), remainder))
657 }
658 RealShardKind::LeafShard => {
659 let (block_header, remainder) = LeafShardBlock::try_from_bytes(bytes)?;
660 Some((Self::LeafShard(block_header), remainder))
661 }
662 }
663 }
664
665 #[inline(always)]
667 pub fn header(&self) -> BlockHeader<'a> {
668 match self {
669 Self::BeaconChain(block) => BlockHeader::BeaconChain(block.header.clone()),
670 Self::IntermediateShard(block) => BlockHeader::IntermediateShard(block.header.clone()),
671 Self::LeafShard(block) => BlockHeader::LeafShard(block.header.clone()),
672 }
673 }
674
675 #[inline(always)]
677 pub fn body(&self) -> BlockBody<'a> {
678 match self {
679 Self::BeaconChain(block) => BlockBody::BeaconChain(block.body),
680 Self::IntermediateShard(block) => BlockBody::IntermediateShard(block.body),
681 Self::LeafShard(block) => BlockBody::LeafShard(block.body),
682 }
683 }
684
685 #[cfg(feature = "alloc")]
692 #[inline(always)]
693 pub fn to_owned(self) -> OwnedBlock {
694 match self {
695 Self::BeaconChain(block) => block.to_owned().into(),
696 Self::IntermediateShard(block) => block.to_owned().into(),
697 Self::LeafShard(block) => block.to_owned().into(),
698 }
699 }
700}
701
702#[derive(
706 Debug,
707 Display,
708 Default,
709 Copy,
710 Clone,
711 Ord,
712 PartialOrd,
713 Eq,
714 PartialEq,
715 Hash,
716 Add,
717 AddAssign,
718 Sub,
719 SubAssign,
720)]
721#[cfg_attr(feature = "scale-codec", derive(Encode, Decode, MaxEncodedLen))]
722#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
723#[repr(C)]
724pub struct BlockWeight(u128);
725
726const impl From<u128> for BlockWeight {
727 #[inline(always)]
728 fn from(value: u128) -> Self {
729 Self(value)
730 }
731}
732
733const impl From<BlockWeight> for u128 {
734 #[inline(always)]
735 fn from(value: BlockWeight) -> Self {
736 value.0
737 }
738}
739
740impl BlockWeight {
741 pub const SIZE: usize = size_of::<u128>();
743 pub const ZERO: BlockWeight = BlockWeight(0);
745 pub const MAX: BlockWeight = BlockWeight(u128::MAX);
747
748 pub const fn from_solution_range(solution_range: SolutionRange) -> Self {
750 Self::from(u128::from(
751 u64::from(SolutionRange::MAX) - u64::from(solution_range),
752 ))
753 }
754}
755
756fn align_to_and_ensure_zero_padding(bytes: &[u8], alignment: Alignment) -> Option<&[u8]> {
760 let padding_len = bytes.as_ptr().align_offset(usize::from(alignment.get()));
761 let (padding, remainder) = bytes.split_at_checked(padding_len)?;
762
763 if padding.iter().any(|&byte| byte != 0) {
765 return None;
766 }
767
768 Some(remainder)
769}