Skip to main content

ab_core_primitives/
shard.rs

1//! Shard-related primitives
2
3#[cfg(test)]
4mod tests;
5
6use crate::hashes::Blake3Hash;
7use crate::nano_u256::NanoU256;
8use crate::segments::HistorySize;
9use crate::solutions::{ShardCommitmentHash, ShardMembershipEntropy, SolutionShardCommitment};
10use ab_blake3::single_block_keyed_hash;
11use ab_io_type::trivial_type::TrivialType;
12use core::num::{NonZeroU16, NonZeroU32, NonZeroU128};
13use core::ops::RangeInclusive;
14use derive_more::Display;
15#[cfg(feature = "scale-codec")]
16use parity_scale_codec::{Decode, Encode, Input, MaxEncodedLen};
17#[cfg(feature = "serde")]
18use serde::{Deserialize, Deserializer, Serialize};
19
20const INTERMEDIATE_SHARDS_RANGE: RangeInclusive<u32> = 1..=1023;
21const INTERMEDIATE_SHARD_BITS: u32 = 10;
22const INTERMEDIATE_SHARD_MASK: u32 = u32::MAX >> (u32::BITS - INTERMEDIATE_SHARD_BITS);
23
24/// A kind of shard.
25///
26/// Schematically, the hierarchy of shards is as follows:
27/// ```text
28///                          Beacon chain
29///                          /          \
30///      Intermediate shard 1            Intermediate shard 2
31///              /  \                            /  \
32/// Leaf shard 11   Leaf shard 12   Leaf shard 21   Leaf shard 22
33/// ```
34///
35/// Beacon chain has index 0, intermediate shards indices 1..=1023. Leaf shards share the same least
36/// significant 10 bits as their respective intermediate shards, so leaf shards of intermediate
37/// shard 1 have indices like 1025,2049,3073,etc.
38///
39/// If represented as least significant bits first (as it will be in the formatted address):
40/// ```text
41/// Intermediate shard bits
42///     \            /
43///      1000_0000_0001_0000_0000
44///                 /            \
45///                Leaf shard bits
46/// ```
47///
48/// Note that shards that have 10 least significant bits set to 0 (corresponds to the beacon chain)
49/// are not leaf shards, in fact, they are not even physical shards that have nodes in general. The
50/// meaning of these shards is TBD, currently they are called "phantom" shards and may end up
51/// containing some system contracts with special meaning, but no blocks will ever exist for such
52/// shards.
53#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
54pub enum ShardKind {
55    /// Beacon chain shard
56    BeaconChain,
57    /// Intermediate shard directly below the beacon chain that has child shards
58    IntermediateShard,
59    /// Leaf shard, which doesn't have child shards
60    LeafShard,
61    /// TODO
62    Phantom,
63}
64
65impl ShardKind {
66    /// Try to convert to real shard kind.
67    ///
68    /// Returns `None` for phantom shard.
69    #[inline(always)]
70    pub fn to_real(self) -> Option<RealShardKind> {
71        match self {
72            ShardKind::BeaconChain => Some(RealShardKind::BeaconChain),
73            ShardKind::IntermediateShard => Some(RealShardKind::IntermediateShard),
74            ShardKind::LeafShard => Some(RealShardKind::LeafShard),
75            ShardKind::Phantom => None,
76        }
77    }
78}
79
80/// Real shard kind for which a block may exist, see [`ShardKind`] for more details
81#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
82pub enum RealShardKind {
83    /// Beacon chain shard
84    BeaconChain,
85    /// Intermediate shard directly below the beacon chain that has child shards
86    IntermediateShard,
87    /// Leaf shard, which doesn't have child shards
88    LeafShard,
89}
90
91impl From<RealShardKind> for ShardKind {
92    #[inline(always)]
93    fn from(shard_kind: RealShardKind) -> Self {
94        match shard_kind {
95            RealShardKind::BeaconChain => ShardKind::BeaconChain,
96            RealShardKind::IntermediateShard => ShardKind::IntermediateShard,
97            RealShardKind::LeafShard => ShardKind::LeafShard,
98        }
99    }
100}
101
102/// Shard index
103#[derive(Debug, Display, Copy, Clone, Hash, Ord, PartialOrd, Eq, PartialEq, TrivialType)]
104#[cfg_attr(feature = "scale-codec", derive(Encode, Decode, MaxEncodedLen))]
105#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
106#[repr(C)]
107pub struct ShardIndex(u32);
108
109const impl Default for ShardIndex {
110    #[inline(always)]
111    fn default() -> Self {
112        Self::BEACON_CHAIN
113    }
114}
115
116const impl From<ShardIndex> for u32 {
117    #[inline(always)]
118    fn from(shard_index: ShardIndex) -> Self {
119        shard_index.0
120    }
121}
122
123impl ShardIndex {
124    /// Beacon chain
125    pub const BEACON_CHAIN: Self = Self(0);
126    /// Max possible shard index
127    pub const MAX_SHARD_INDEX: u32 = Self::MAX_SHARDS.get() - 1;
128    /// Max possible number of shards
129    pub const MAX_SHARDS: NonZeroU32 = NonZeroU32::new(2u32.pow(20)).expect("Not zero; qed");
130    /// Max possible number of addresses per shard
131    pub const MAX_ADDRESSES_PER_SHARD: NonZeroU128 =
132        NonZeroU128::new(2u128.pow(108)).expect("Not zero; qed");
133
134    /// Create shard index from `u32`.
135    ///
136    /// Returns `None` if `shard_index > ShardIndex::MAX_SHARD_INDEX`
137    ///
138    /// This is typically only necessary for low-level code.
139    #[inline(always)]
140    pub const fn new(shard_index: u32) -> Option<Self> {
141        if shard_index > Self::MAX_SHARD_INDEX {
142            return None;
143        }
144
145        Some(Self(shard_index))
146    }
147
148    /// Whether the shard index corresponds to the beacon chain
149    #[inline(always)]
150    pub const fn is_beacon_chain(&self) -> bool {
151        self.0 == Self::BEACON_CHAIN.0
152    }
153
154    /// Whether the shard index corresponds to an intermediate shard
155    #[inline(always)]
156    pub const fn is_intermediate_shard(&self) -> bool {
157        self.0 >= *INTERMEDIATE_SHARDS_RANGE.start() && self.0 <= *INTERMEDIATE_SHARDS_RANGE.end()
158    }
159
160    /// Whether the shard index corresponds to an intermediate shard
161    #[inline(always)]
162    pub const fn is_leaf_shard(&self) -> bool {
163        if self.0 <= *INTERMEDIATE_SHARDS_RANGE.end() || self.0 > Self::MAX_SHARD_INDEX {
164            return false;
165        }
166
167        self.0 & INTERMEDIATE_SHARD_MASK != 0
168    }
169
170    /// Whether the shard index corresponds to a real shard
171    #[inline(always)]
172    pub const fn is_real(&self) -> bool {
173        !self.is_phantom_shard()
174    }
175
176    /// Whether the shard index corresponds to a phantom shard
177    #[inline(always)]
178    pub const fn is_phantom_shard(&self) -> bool {
179        if self.0 <= *INTERMEDIATE_SHARDS_RANGE.end() || self.0 > Self::MAX_SHARD_INDEX {
180            return false;
181        }
182
183        self.0 & INTERMEDIATE_SHARD_MASK == 0
184    }
185
186    /// Check if this shard is a child shard of `parent`
187    #[inline(always)]
188    pub const fn is_child_of(self, parent: Self) -> bool {
189        match self.shard_kind() {
190            Some(ShardKind::BeaconChain) => false,
191            Some(ShardKind::IntermediateShard | ShardKind::Phantom) => parent.is_beacon_chain(),
192            Some(ShardKind::LeafShard) => {
193                // Check that the least significant bits match
194                self.0 & INTERMEDIATE_SHARD_MASK == parent.0
195            }
196            None => false,
197        }
198    }
199
200    /// Get index of the parent shard (for leaf and intermediate shards)
201    #[inline(always)]
202    pub const fn parent_shard(self) -> Option<ShardIndex> {
203        match self.shard_kind()? {
204            ShardKind::BeaconChain => None,
205            ShardKind::IntermediateShard | ShardKind::Phantom => Some(ShardIndex::BEACON_CHAIN),
206            ShardKind::LeafShard => Some(Self(self.0 & INTERMEDIATE_SHARD_MASK)),
207        }
208    }
209
210    /// Get shard kind
211    #[inline(always)]
212    pub const fn shard_kind(&self) -> Option<ShardKind> {
213        if self.0 == Self::BEACON_CHAIN.0 {
214            Some(ShardKind::BeaconChain)
215        } else if self.0 >= *INTERMEDIATE_SHARDS_RANGE.start()
216            && self.0 <= *INTERMEDIATE_SHARDS_RANGE.end()
217        {
218            Some(ShardKind::IntermediateShard)
219        } else if self.0 > Self::MAX_SHARD_INDEX {
220            None
221        } else if self.0 & INTERMEDIATE_SHARD_MASK == 0 {
222            // Check if the least significant bits correspond to the beacon chain
223            Some(ShardKind::Phantom)
224        } else {
225            Some(ShardKind::LeafShard)
226        }
227    }
228}
229
230/// Unchecked number of shards in the network.
231///
232/// Should be converted into [`NumShards`] before use.
233#[derive(Debug, Copy, Clone, Eq, PartialEq, TrivialType)]
234#[cfg_attr(feature = "scale-codec", derive(Encode, Decode, MaxEncodedLen))]
235#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
236#[repr(C)]
237pub struct NumShardsUnchecked {
238    /// The number of intermediate shards
239    pub intermediate_shards: u16,
240    /// The number of leaf shards per intermediate shard
241    pub leaf_shards_per_intermediate_shard: u16,
242}
243
244impl From<NumShards> for NumShardsUnchecked {
245    fn from(value: NumShards) -> Self {
246        Self {
247            intermediate_shards: value.intermediate_shards.get(),
248            leaf_shards_per_intermediate_shard: value.leaf_shards_per_intermediate_shard.get(),
249        }
250    }
251}
252
253/// Number of shards in the network
254#[derive(Debug, Copy, Clone, Eq, PartialEq)]
255#[cfg_attr(feature = "scale-codec", derive(Encode, MaxEncodedLen))]
256#[cfg_attr(feature = "serde", derive(Serialize))]
257pub struct NumShards {
258    /// The number of intermediate shards
259    intermediate_shards: NonZeroU16,
260    /// The number of leaf shards per intermediate shard
261    leaf_shards_per_intermediate_shard: NonZeroU16,
262}
263
264#[cfg(feature = "scale-codec")]
265impl Decode for NumShards {
266    fn decode<I>(input: &mut I) -> Result<Self, parity_scale_codec::Error>
267    where
268        I: Input,
269    {
270        let intermediate_shards = Decode::decode(input)
271            .map_err(|error| error.chain("Could not decode `NumShards::intermediate_shards`"))?;
272        let leaf_shards_per_intermediate_shard = Decode::decode(input).map_err(|error| {
273            error.chain("Could not decode `NumShards::leaf_shards_per_intermediate_shard`")
274        })?;
275
276        Self::new(intermediate_shards, leaf_shards_per_intermediate_shard)
277            .ok_or_else(|| "Invalid `NumShards`".into())
278    }
279}
280
281#[cfg(feature = "serde")]
282impl<'de> Deserialize<'de> for NumShards {
283    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
284    where
285        D: Deserializer<'de>,
286    {
287        #[derive(Deserialize)]
288        struct NumShards {
289            intermediate_shards: NonZeroU16,
290            leaf_shards_per_intermediate_shard: NonZeroU16,
291        }
292
293        let num_shards_inner = NumShards::deserialize(deserializer)?;
294
295        Self::new(
296            num_shards_inner.intermediate_shards,
297            num_shards_inner.leaf_shards_per_intermediate_shard,
298        )
299        .ok_or_else(|| serde::de::Error::custom("Invalid `NumShards`"))
300    }
301}
302
303impl TryFrom<NumShardsUnchecked> for NumShards {
304    type Error = ();
305
306    fn try_from(value: NumShardsUnchecked) -> Result<Self, Self::Error> {
307        Self::new(
308            NonZeroU16::new(value.intermediate_shards).ok_or(())?,
309            NonZeroU16::new(value.leaf_shards_per_intermediate_shard).ok_or(())?,
310        )
311        .ok_or(())
312    }
313}
314
315impl NumShards {
316    /// Create a new instance from a number of intermediate shards and leaf shards per
317    /// intermediate shard.
318    ///
319    /// Returns `None` if inputs are invalid.
320    ///
321    /// This is typically only necessary for low-level code.
322    #[inline(always)]
323    pub const fn new(
324        intermediate_shards: NonZeroU16,
325        leaf_shards_per_intermediate_shard: NonZeroU16,
326    ) -> Option<Self> {
327        if intermediate_shards.get()
328            > (*INTERMEDIATE_SHARDS_RANGE.end() - *INTERMEDIATE_SHARDS_RANGE.start() + 1) as u16
329        {
330            return None;
331        }
332
333        // Leaf shards are numbered in the bits of shard indices above those of intermediate shards
334        if u32::from(leaf_shards_per_intermediate_shard.get())
335            > (ShardIndex::MAX_SHARD_INDEX >> INTERMEDIATE_SHARD_BITS)
336        {
337            return None;
338        }
339
340        Some(Self {
341            intermediate_shards,
342            leaf_shards_per_intermediate_shard,
343        })
344    }
345
346    /// The number of intermediate shards
347    #[inline(always)]
348    pub const fn intermediate_shards(self) -> NonZeroU16 {
349        self.intermediate_shards
350    }
351    /// The number of leaf shards per intermediate shard
352    #[inline(always)]
353    pub const fn leaf_shards_per_intermediate_shard(self) -> NonZeroU16 {
354        self.leaf_shards_per_intermediate_shard
355    }
356
357    /// Total number of leaf shards in the network
358    #[inline(always)]
359    pub const fn leaf_shards(&self) -> NonZeroU32 {
360        NonZeroU32::new(
361            self.intermediate_shards.get() as u32
362                * self.leaf_shards_per_intermediate_shard.get() as u32,
363        )
364        .expect("Not zero; qed")
365    }
366
367    /// Iterator over all intermediate shards
368    #[inline(always)]
369    pub fn iter_intermediate_shards(&self) -> impl Iterator<Item = ShardIndex> {
370        INTERMEDIATE_SHARDS_RANGE
371            .take(usize::from(self.intermediate_shards.get()))
372            .map(ShardIndex)
373    }
374
375    /// Iterator over all leaf shards
376    #[inline(always)]
377    pub fn iter_leaf_shards(&self) -> impl Iterator<Item = ShardIndex> {
378        self.iter_intermediate_shards()
379            .flat_map(|intermediate_shard| {
380                // Leaf shards are numbered from 1, 0 is the intermediate shard itself
381                (1..=u32::from(self.leaf_shards_per_intermediate_shard.get())).map(
382                    move |leaf_shard_index| {
383                        ShardIndex(
384                            (leaf_shard_index << INTERMEDIATE_SHARD_BITS) | intermediate_shard.0,
385                        )
386                    },
387                )
388            })
389    }
390
391    /// Derive shard index that should be used in a solution
392    #[inline]
393    pub fn derive_shard_index(
394        &self,
395        public_key_hash: &Blake3Hash,
396        shard_commitments_root: &ShardCommitmentHash,
397        shard_membership_entropy: &ShardMembershipEntropy,
398        history_size: HistorySize,
399    ) -> ShardIndex {
400        let hash = single_block_keyed_hash(public_key_hash, &{
401            let mut bytes_to_hash = [0u8; {
402                ShardCommitmentHash::SIZE
403                    + ShardMembershipEntropy::SIZE
404                    + HistorySize::SIZE as usize
405            }];
406            bytes_to_hash[..ShardCommitmentHash::SIZE]
407                .copy_from_slice(shard_commitments_root.as_bytes());
408            bytes_to_hash[ShardCommitmentHash::SIZE..][..ShardMembershipEntropy::SIZE]
409                .copy_from_slice(shard_membership_entropy.as_bytes());
410            bytes_to_hash[ShardCommitmentHash::SIZE + ShardMembershipEntropy::SIZE..]
411                .copy_from_slice(history_size.as_bytes());
412            bytes_to_hash
413        })
414        .expect("Input is smaller than block size; qed");
415        // Going through `NanoU256` because the total number of shards is not guaranteed to be a
416        // power of two
417        let shard_index_offset =
418            NanoU256::from_le_bytes(hash) % u64::from(self.leaf_shards().get());
419
420        self.iter_leaf_shards()
421            .nth(shard_index_offset as usize)
422            .unwrap_or(ShardIndex::BEACON_CHAIN)
423    }
424
425    /// Derive shard commitment index that should be used in a solution.
426    ///
427    /// Returned index is always within `0`..[`SolutionShardCommitment::NUM_LEAVES`] range.
428    #[inline]
429    pub fn derive_shard_commitment_index(
430        &self,
431        public_key_hash: &Blake3Hash,
432        shard_commitments_root: &ShardCommitmentHash,
433        shard_membership_entropy: &ShardMembershipEntropy,
434        history_size: HistorySize,
435    ) -> u32 {
436        let hash = single_block_keyed_hash(public_key_hash, &{
437            let mut bytes_to_hash = [0u8; {
438                ShardCommitmentHash::SIZE
439                    + ShardMembershipEntropy::SIZE
440                    + HistorySize::SIZE as usize
441            }];
442            bytes_to_hash[..ShardCommitmentHash::SIZE]
443                .copy_from_slice(shard_commitments_root.as_bytes());
444            bytes_to_hash[ShardCommitmentHash::SIZE..][..ShardMembershipEntropy::SIZE]
445                .copy_from_slice(shard_membership_entropy.as_bytes());
446            bytes_to_hash[ShardCommitmentHash::SIZE + ShardMembershipEntropy::SIZE..]
447                .copy_from_slice(history_size.as_bytes());
448            bytes_to_hash
449        })
450        .expect("Input is smaller than block size; qed");
451        const {
452            assert!(SolutionShardCommitment::NUM_LEAVES.is_power_of_two());
453        }
454        u32::from_le_bytes([hash[0], hash[1], hash[2], hash[3]])
455            % SolutionShardCommitment::NUM_LEAVES as u32
456    }
457
458    /// More efficient version of [`Self::derive_shard_index()`] and
459    /// [`Self::derive_shard_commitment_index()`] in a single call, see those functions for details
460    #[inline]
461    pub fn derive_shard_index_and_shard_commitment_index(
462        &self,
463        public_key_hash: &Blake3Hash,
464        shard_commitments_root: &ShardCommitmentHash,
465        shard_membership_entropy: &ShardMembershipEntropy,
466        history_size: HistorySize,
467    ) -> (ShardIndex, u32) {
468        let hash = single_block_keyed_hash(public_key_hash, &{
469            let mut bytes_to_hash = [0u8; {
470                ShardCommitmentHash::SIZE
471                    + ShardMembershipEntropy::SIZE
472                    + HistorySize::SIZE as usize
473            }];
474            bytes_to_hash[..ShardCommitmentHash::SIZE]
475                .copy_from_slice(shard_commitments_root.as_bytes());
476            bytes_to_hash[ShardCommitmentHash::SIZE..][..ShardMembershipEntropy::SIZE]
477                .copy_from_slice(shard_membership_entropy.as_bytes());
478            bytes_to_hash[ShardCommitmentHash::SIZE + ShardMembershipEntropy::SIZE..]
479                .copy_from_slice(history_size.as_bytes());
480            bytes_to_hash
481        })
482        .expect("Input is smaller than block size; qed");
483
484        // Going through `NanoU256` because the total number of shards is not guaranteed to be a
485        // power of two
486        let shard_index_offset =
487            NanoU256::from_le_bytes(hash) % u64::from(self.leaf_shards().get());
488
489        let shard_index = self
490            .iter_leaf_shards()
491            .nth(shard_index_offset as usize)
492            .unwrap_or(ShardIndex::BEACON_CHAIN);
493
494        const {
495            assert!(SolutionShardCommitment::NUM_LEAVES.is_power_of_two());
496        }
497        let shard_commitment_index = u32::from_le_bytes([hash[0], hash[1], hash[2], hash[3]])
498            % SolutionShardCommitment::NUM_LEAVES as u32;
499
500        (shard_index, shard_commitment_index)
501    }
502}