1#[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#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
54pub enum ShardKind {
55 BeaconChain,
57 IntermediateShard,
59 LeafShard,
61 Phantom,
63}
64
65impl ShardKind {
66 #[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#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
82pub enum RealShardKind {
83 BeaconChain,
85 IntermediateShard,
87 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#[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 pub const BEACON_CHAIN: Self = Self(0);
126 pub const MAX_SHARD_INDEX: u32 = Self::MAX_SHARDS.get() - 1;
128 pub const MAX_SHARDS: NonZeroU32 = NonZeroU32::new(2u32.pow(20)).expect("Not zero; qed");
130 pub const MAX_ADDRESSES_PER_SHARD: NonZeroU128 =
132 NonZeroU128::new(2u128.pow(108)).expect("Not zero; qed");
133
134 #[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 #[inline(always)]
150 pub const fn is_beacon_chain(&self) -> bool {
151 self.0 == Self::BEACON_CHAIN.0
152 }
153
154 #[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 #[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 #[inline(always)]
172 pub const fn is_real(&self) -> bool {
173 !self.is_phantom_shard()
174 }
175
176 #[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 #[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 self.0 & INTERMEDIATE_SHARD_MASK == parent.0
195 }
196 None => false,
197 }
198 }
199
200 #[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 #[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 Some(ShardKind::Phantom)
224 } else {
225 Some(ShardKind::LeafShard)
226 }
227 }
228}
229
230#[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 pub intermediate_shards: u16,
240 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#[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 intermediate_shards: NonZeroU16,
260 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 #[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 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 #[inline(always)]
348 pub const fn intermediate_shards(self) -> NonZeroU16 {
349 self.intermediate_shards
350 }
351 #[inline(always)]
353 pub const fn leaf_shards_per_intermediate_shard(self) -> NonZeroU16 {
354 self.leaf_shards_per_intermediate_shard
355 }
356
357 #[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 #[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 #[inline(always)]
377 pub fn iter_leaf_shards(&self) -> impl Iterator<Item = ShardIndex> {
378 self.iter_intermediate_shards()
379 .flat_map(|intermediate_shard| {
380 (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 #[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 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 #[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 #[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 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}