Skip to main content

ab_core_primitives/
solutions.rs

1//! Solutions-related data structures and functions.
2
3#[cfg(all(test, feature = "alloc"))]
4mod tests;
5
6use crate::block::BlockNumber;
7use crate::ed25519::Ed25519PublicKey;
8use crate::hashes::Blake3Hash;
9use crate::pieces::{PieceOffset, Record, RecordChunk, RecordProof, RecordRoot, SegmentProof};
10use crate::pos::{PosProof, PosSeed};
11use crate::pot::{PotOutput, SlotNumber};
12use crate::sectors::{SBucket, SectorId, SectorIndex, SectorSlotChallenge};
13use crate::segments::{
14    HistorySize, LocalSegmentIndex, SegmentIndex, SegmentRoot, SuperSegmentRoot,
15};
16use crate::shard::{NumShards, RealShardKind, ShardIndex, ShardKind};
17use ab_blake3::single_block_keyed_hash;
18use ab_io_type::trivial_type::TrivialType;
19use ab_merkle_tree::blake3::BalancedMerkleTree;
20use blake3::{Hash, OUT_LEN};
21use core::fmt;
22use core::simd::Simd;
23use derive_more::{
24    Add, AddAssign, AsMut, AsRef, Deref, DerefMut, Display, From, Into, Sub, SubAssign,
25};
26#[cfg(feature = "scale-codec")]
27use parity_scale_codec::{Decode, Encode, MaxEncodedLen};
28#[cfg(feature = "serde")]
29use serde::{Deserialize, Serialize};
30#[cfg(feature = "serde")]
31use serde::{Deserializer, Serializer};
32#[cfg(feature = "serde")]
33use serde_big_array::BigArray;
34use transparent_wrapper::TransparentWrapper;
35
36/// Solution distance
37#[derive(
38    Debug, Display, Default, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, From, Into,
39)]
40#[cfg_attr(feature = "scale-codec", derive(Encode, Decode, MaxEncodedLen))]
41#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
42#[repr(C)]
43pub struct SolutionDistance(u64);
44
45impl SolutionDistance {
46    /// Maximum value
47    pub const MAX: Self = Self(u64::MAX / 2);
48
49    // TODO: Remove once `From` is stable
50    /// Create a new instance
51    #[inline(always)]
52    pub const fn from_u64(n: u64) -> Self {
53        Self(n)
54    }
55
56    /// Calculate solution distance for given parameters.
57    ///
58    /// Typically used as a primitive to check whether solution distance is within solution range
59    /// (see [`Self::is_within()`]).
60    pub fn calculate(
61        global_challenge: &Blake3Hash,
62        chunk: &[u8; 32],
63        sector_slot_challenge: &SectorSlotChallenge,
64    ) -> Self {
65        let audit_chunk = single_block_keyed_hash(sector_slot_challenge, chunk)
66            .expect("Less than a single block worth of bytes; qed");
67        let audit_chunk_as_solution_range = SolutionRange::from_bytes([
68            audit_chunk[0],
69            audit_chunk[1],
70            audit_chunk[2],
71            audit_chunk[3],
72            audit_chunk[4],
73            audit_chunk[5],
74            audit_chunk[6],
75            audit_chunk[7],
76        ]);
77        let global_challenge_as_solution_range =
78            SolutionRange::from_bytes(global_challenge.as_chunks().0[0]);
79
80        global_challenge_as_solution_range.bidirectional_distance(audit_chunk_as_solution_range)
81    }
82
83    /// Check if solution distance is within the provided solution range
84    pub const fn is_within(self, solution_range: SolutionRange) -> bool {
85        self.0 <= u64::from(solution_range) / 2
86    }
87}
88
89/// Solution range
90#[derive(
91    Debug,
92    Display,
93    Default,
94    Copy,
95    Clone,
96    Ord,
97    PartialOrd,
98    Eq,
99    PartialEq,
100    Hash,
101    Add,
102    AddAssign,
103    Sub,
104    SubAssign,
105    TrivialType,
106)]
107#[cfg_attr(feature = "scale-codec", derive(Encode, Decode, MaxEncodedLen))]
108#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
109#[repr(C)]
110pub struct SolutionRange(u64);
111
112const impl From<u64> for SolutionRange {
113    #[inline(always)]
114    fn from(value: u64) -> Self {
115        Self(value)
116    }
117}
118
119const impl From<SolutionRange> for u64 {
120    #[inline(always)]
121    fn from(value: SolutionRange) -> Self {
122        value.0
123    }
124}
125
126impl SolutionRange {
127    /// Size in bytes
128    pub const SIZE: usize = size_of::<u64>();
129    /// Minimum value
130    pub const MIN: Self = Self(u64::MIN);
131    /// Maximum value
132    pub const MAX: Self = Self(u64::MAX);
133
134    /// Create a new instance from bytes
135    #[inline(always)]
136    pub fn to_bytes(self) -> [u8; 8] {
137        self.0.to_le_bytes()
138    }
139
140    /// Create a new instance from bytes
141    #[inline(always)]
142    pub fn from_bytes(bytes: [u8; 8]) -> Self {
143        Self(u64::from_le_bytes(bytes))
144    }
145
146    /// Computes the following:
147    /// ```text
148    /// MAX * slot_probability / chunks * s_buckets / pieces
149    /// ```
150    #[inline]
151    pub const fn from_pieces(pieces: u64, slot_probability: (u64, u64)) -> Self {
152        let solution_range = u64::MAX
153            // Account for slot probability
154            / slot_probability.1 * slot_probability.0
155            // Now take the probability of hitting occupied s-bucket in a piece into account
156            / Record::NUM_CHUNKS as u64
157            * Record::NUM_S_BUCKETS as u64;
158
159        // Take the number of pieces into account
160        Self(solution_range / pieces)
161    }
162
163    /// Computes the following:
164    /// ```text
165    /// MAX * slot_probability / chunks * s_buckets / solution_range
166    /// ```
167    #[inline]
168    pub const fn to_pieces(self, slot_probability: (u64, u64)) -> u64 {
169        let pieces = u64::MAX
170            // Account for slot probability
171            / slot_probability.1 * slot_probability.0
172            // Now take the probability of hitting occupied s-bucket in sector into account
173            / Record::NUM_CHUNKS as u64
174            * Record::NUM_S_BUCKETS as u64;
175
176        // Take solution range into account
177        pieces / self.0
178    }
179
180    /// Expands the global solution range to a solution range that corresponds to a leaf shard.
181    ///
182    /// Global solution range is updated based on the beacon chain information, while a farmer also
183    /// creates intermediate shard and leaf shard solutions with a wider solution range.
184    #[inline]
185    pub const fn to_leaf_shard(self, num_shards: NumShards) -> Self {
186        Self(
187            self.0
188                .saturating_mul(u64::from(num_shards.leaf_shards().get())),
189        )
190    }
191
192    /// Expands the global solution range to a solution range that corresponds to an intermediate
193    /// shard
194    #[inline]
195    pub const fn to_intermediate_shard(self, num_shards: NumShards) -> Self {
196        Self(
197            self.0
198                .saturating_mul(u64::from(num_shards.intermediate_shards().get())),
199        )
200    }
201
202    /// Bidirectional distance between two solution ranges
203    #[inline]
204    pub const fn bidirectional_distance(self, other: Self) -> SolutionDistance {
205        let a = self.0;
206        let b = other.0;
207        let diff = a.wrapping_sub(b);
208        let diff2 = b.wrapping_sub(a);
209        // Find smaller diff between 2 directions
210        SolutionDistance::from_u64(if diff < diff2 { diff } else { diff2 })
211    }
212
213    /// Derives next solution range
214    #[inline]
215    pub fn derive_next(
216        self,
217        slots_in_last_interval: SlotNumber,
218        slot_probability: (u64, u64),
219        retarget_interval: BlockNumber,
220    ) -> Self {
221        // The idea here is to keep block production at the same pace while space pledged on the
222        // network changes. For this, we adjust the previous solution range according to actual and
223        // expected number of blocks per retarget interval.
224        //
225        // Below is code analogous to the following, but without using floats:
226        // ```rust
227        // let actual_slots_per_block = slots_in_last_interval as f64 / retarget_interval as f64;
228        // let expected_slots_per_block =
229        //     slot_probability.1 as f64 / slot_probability.0 as f64;
230        // let adjustment_factor =
231        //     (actual_slots_per_block / expected_slots_per_block).clamp(0.25, 4.0);
232        //
233        // next_solution_range =
234        //     (solution_ranges.current as f64 * adjustment_factor).round() as u64;
235        // ```
236        let current_solution_range = self.0;
237        let next_solution_range = u64::try_from(
238            u128::from(current_solution_range)
239                .saturating_mul(u128::from(slots_in_last_interval))
240                .saturating_mul(u128::from(slot_probability.0))
241                / u128::from(u64::from(retarget_interval))
242                / u128::from(slot_probability.1),
243        );
244
245        Self(next_solution_range.unwrap_or(u64::MAX).clamp(
246            current_solution_range / 4,
247            current_solution_range.saturating_mul(4),
248        ))
249    }
250}
251
252// Quick test to ensure the functions above are the inverse of each other
253const {
254    assert!(SolutionRange::from_pieces(1, (1, 6)).to_pieces((1, 6)) == 1);
255    assert!(SolutionRange::from_pieces(3, (1, 6)).to_pieces((1, 6)) == 3);
256    assert!(SolutionRange::from_pieces(5, (1, 6)).to_pieces((1, 6)) == 5);
257}
258
259/// Proof for chunk contained within a record.
260#[derive(Copy, Clone, Eq, PartialEq, Hash, Deref, DerefMut, From, Into, TrivialType)]
261#[cfg_attr(feature = "scale-codec", derive(Encode, Decode, MaxEncodedLen))]
262#[repr(C)]
263pub struct ChunkProof([[u8; OUT_LEN]; ChunkProof::NUM_HASHES]);
264
265impl fmt::Debug for ChunkProof {
266    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
267        write!(f, "[")?;
268        for hash in self.0 {
269            for byte in hash {
270                write!(f, "{byte:02x}")?;
271            }
272            write!(f, ", ")?;
273        }
274        write!(f, "]")?;
275        Ok(())
276    }
277}
278
279#[cfg(feature = "serde")]
280#[derive(Serialize, Deserialize)]
281#[serde(transparent)]
282struct ChunkProofBinary(#[serde(with = "BigArray")] [[u8; OUT_LEN]; ChunkProof::NUM_HASHES]);
283
284#[cfg(feature = "serde")]
285#[derive(Serialize, Deserialize, TransparentWrapper)]
286#[serde(transparent)]
287#[repr(transparent)]
288struct ChunkProofHexHash(#[serde(with = "hex")] [u8; OUT_LEN]);
289
290#[cfg(feature = "serde")]
291#[derive(Serialize, Deserialize)]
292#[serde(transparent)]
293struct ChunkProofHex([ChunkProofHexHash; ChunkProof::NUM_HASHES]);
294
295#[cfg(feature = "serde")]
296impl Serialize for ChunkProof {
297    #[inline]
298    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
299    where
300        S: Serializer,
301    {
302        if serializer.is_human_readable() {
303            ChunkProofHex(<[ChunkProofHexHash; Self::NUM_HASHES]>::wrap(self.0))
304                .serialize(serializer)
305        } else {
306            ChunkProofBinary(self.0).serialize(serializer)
307        }
308    }
309}
310
311#[cfg(feature = "serde")]
312impl<'de> Deserialize<'de> for ChunkProof {
313    #[inline]
314    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
315    where
316        D: Deserializer<'de>,
317    {
318        Ok(Self(if deserializer.is_human_readable() {
319            ChunkProofHex::deserialize(deserializer)?.0.peel()
320        } else {
321            ChunkProofBinary::deserialize(deserializer)?.0
322        }))
323    }
324}
325
326impl Default for ChunkProof {
327    #[inline]
328    fn default() -> Self {
329        Self([[0; OUT_LEN]; _])
330    }
331}
332
333impl AsRef<[u8]> for ChunkProof {
334    #[inline]
335    fn as_ref(&self) -> &[u8] {
336        self.0.as_flattened()
337    }
338}
339
340impl AsMut<[u8]> for ChunkProof {
341    #[inline]
342    fn as_mut(&mut self) -> &mut [u8] {
343        self.0.as_flattened_mut()
344    }
345}
346
347impl ChunkProof {
348    /// Size of chunk proof in bytes.
349    pub const SIZE: usize = OUT_LEN * Self::NUM_HASHES;
350    const NUM_HASHES: usize = Record::NUM_S_BUCKETS.ilog2() as usize;
351}
352
353/// Solution verification errors
354#[derive(Debug, Eq, PartialEq, thiserror::Error)]
355pub enum SolutionVerifyError {
356    /// Invalid piece offset
357    #[error("Piece verification failed")]
358    InvalidPieceOffset {
359        /// Index of the piece that failed verification
360        piece_offset: u16,
361        /// How many pieces one sector is supposed to contain (max)
362        max_pieces_in_sector: u16,
363    },
364    /// History size is in the future
365    #[error("History size {solution} is in the future, current is {current}")]
366    FutureHistorySize {
367        /// Current history size
368        current: HistorySize,
369        /// History size solution was created for
370        solution: HistorySize,
371    },
372    /// Sector expired
373    #[error("Sector expired")]
374    SectorExpired {
375        /// Expiration history size
376        expiration_history_size: HistorySize,
377        /// Current history size
378        current_history_size: HistorySize,
379    },
380    /// Segment of the piece the sector requires is not in the super segment
381    #[error(
382        "Segment {segment_index} is not in the super segment with max segment index \
383        {max_segment_index} and {num_segments} segments"
384    )]
385    PieceSegmentNotInSuperSegment {
386        /// Segment index of the piece the sector requires at the piece offset
387        segment_index: SegmentIndex,
388        /// Max index of the segment in the super segment
389        max_segment_index: SegmentIndex,
390        /// Number of segments in the super segment
391        num_segments: u32,
392    },
393    /// Record does not belong to the segment
394    #[error("Record does not belong to the segment")]
395    RecordNotInSegment,
396    /// Segment doesn't belong to the super segment
397    #[error("Segment doesn't belong to the super segment")]
398    SegmentNotInSuperSegment,
399    /// Solution is outside the solution range
400    #[error("Solution distance {solution_distance} is outside of solution range {solution_range}")]
401    OutsideSolutionRange {
402        /// Solution range
403        solution_range: SolutionRange,
404        /// Solution distance
405        solution_distance: SolutionDistance,
406    },
407    /// Invalid proof of space
408    #[error("Invalid proof of space")]
409    InvalidProofOfSpace,
410    /// Invalid shard commitment
411    #[error("Invalid shard commitment")]
412    InvalidShardCommitment,
413    /// Invalid input shard
414    #[error("Invalid input shard {shard_index} ({shard_kind:?})")]
415    InvalidInputShard {
416        /// Input shard index
417        shard_index: ShardIndex,
418        /// Input shard kind
419        shard_kind: Option<ShardKind>,
420    },
421    /// Invalid solution shard
422    #[error(
423        "Invalid solution shard {solution_shard_index} (parent {solution_parent_shard_index:?}), \
424        expected shard {expected_shard_index} ({expected_shard_kind:?})"
425    )]
426    InvalidSolutionShard {
427        /// Solution shard index
428        solution_shard_index: ShardIndex,
429        /// Solution shard index
430        solution_parent_shard_index: Option<ShardIndex>,
431        /// Expected shard index
432        expected_shard_index: ShardIndex,
433        /// Expected shard kind
434        expected_shard_kind: RealShardKind,
435    },
436    /// Invalid chunk proof
437    #[error("Invalid chunk proof")]
438    InvalidChunkProof,
439    /// Invalid history size
440    #[error("Invalid history size")]
441    InvalidHistorySize,
442}
443
444/// Parameters for stateless solution verification.
445///
446/// These only include the information already contained in the block itself, meaning verification
447/// of different blocks can be done concurrently.
448#[derive(Debug, Clone)]
449#[cfg_attr(feature = "scale-codec", derive(Encode, Decode, MaxEncodedLen))]
450pub struct SolutionVerifyStatelessParams {
451    /// Shard for which the solution is built
452    pub shard_index: ShardIndex,
453    /// Proof of time for which solution is built
454    pub proof_of_time: PotOutput,
455    /// Solution range
456    pub solution_range: SolutionRange,
457    /// Shard membership entropy
458    pub shard_membership_entropy: ShardMembershipEntropy,
459    /// The number of shards in the network
460    pub num_shards: NumShards,
461}
462
463/// Parameters for checking piece validity used in a solution
464#[derive(Debug, Clone)]
465#[cfg_attr(feature = "scale-codec", derive(Encode, Decode, MaxEncodedLen))]
466pub struct SolutionVerifyPieceParams {
467    /// How many pieces one sector is supposed to contain (max)
468    pub max_pieces_in_sector: u16,
469    /// Root of the super segment that contains the segment of the piece the sector requires at the
470    /// piece offset, see [`SectorId::derive_piece_index()`]
471    pub super_segment_root: SuperSegmentRoot,
472    /// Number of segments in the super segment
473    pub num_segments: u32,
474    /// Max index of the segment in the super segment
475    pub max_segment_index: SegmentIndex,
476    /// Number of latest archived segments that are considered "recent history"
477    pub recent_segments: HistorySize,
478    /// Fraction of pieces from the "recent history" (`recent_segments`) in each sector
479    pub recent_history_fraction: (HistorySize, HistorySize),
480    /// Minimum lifetime of a plotted sector, measured in archived segments
481    pub min_sector_lifetime: HistorySize,
482    /// Current size of the history
483    pub current_history_size: HistorySize,
484    /// Super segment root that contains a segment at `min_sector_lifetime` from sector creation
485    /// (if exists)
486    pub sector_expiration_check_super_segment_root: Option<SuperSegmentRoot>,
487}
488
489/// Parameters for full solution verification
490#[derive(Debug, Clone)]
491#[cfg_attr(feature = "scale-codec", derive(Encode, Decode, MaxEncodedLen))]
492pub struct SolutionVerifyFullParams {
493    /// Parameters for stateless solution verification
494    pub stateless: SolutionVerifyStatelessParams,
495    /// Parameters for checking piece validity used in a solution
496    pub piece: SolutionVerifyPieceParams,
497}
498
499/// Proof-of-time verifier to be used in [`Solution::verify_full()`]
500pub trait SolutionPotVerifier {
501    /// Check whether proof created earlier is valid
502    fn is_proof_valid(seed: &PosSeed, s_bucket: SBucket, proof: &PosProof) -> bool;
503}
504
505/// Entropy used for shard membership assignment
506#[derive(
507    Default,
508    Copy,
509    Clone,
510    Eq,
511    PartialEq,
512    Ord,
513    PartialOrd,
514    Hash,
515    From,
516    Into,
517    AsRef,
518    AsMut,
519    Deref,
520    DerefMut,
521    TrivialType,
522    TransparentWrapper,
523)]
524#[cfg_attr(feature = "scale-codec", derive(Encode, Decode, MaxEncodedLen))]
525#[repr(C)]
526pub struct ShardMembershipEntropy([u8; ShardMembershipEntropy::SIZE]);
527
528impl fmt::Display for ShardMembershipEntropy {
529    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
530        for byte in self.0 {
531            write!(f, "{byte:02x}")?;
532        }
533        Ok(())
534    }
535}
536
537#[cfg(feature = "serde")]
538#[derive(Serialize, Deserialize)]
539#[serde(transparent)]
540struct ShardMembershipEntropyBinary([u8; ShardMembershipEntropy::SIZE]);
541
542#[cfg(feature = "serde")]
543#[derive(Serialize, Deserialize)]
544#[serde(transparent)]
545struct ShardMembershipEntropyHex(#[serde(with = "hex")] [u8; ShardMembershipEntropy::SIZE]);
546
547#[cfg(feature = "serde")]
548impl Serialize for ShardMembershipEntropy {
549    #[inline]
550    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
551    where
552        S: Serializer,
553    {
554        if serializer.is_human_readable() {
555            ShardMembershipEntropyHex(self.0).serialize(serializer)
556        } else {
557            ShardMembershipEntropyBinary(self.0).serialize(serializer)
558        }
559    }
560}
561
562#[cfg(feature = "serde")]
563impl<'de> Deserialize<'de> for ShardMembershipEntropy {
564    #[inline]
565    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
566    where
567        D: Deserializer<'de>,
568    {
569        Ok(Self(if deserializer.is_human_readable() {
570            ShardMembershipEntropyHex::deserialize(deserializer)?.0
571        } else {
572            ShardMembershipEntropyBinary::deserialize(deserializer)?.0
573        }))
574    }
575}
576
577impl fmt::Debug for ShardMembershipEntropy {
578    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
579        for byte in self.0 {
580            write!(f, "{byte:02x}")?;
581        }
582        Ok(())
583    }
584}
585
586impl AsRef<[u8]> for ShardMembershipEntropy {
587    #[inline(always)]
588    fn as_ref(&self) -> &[u8] {
589        &self.0
590    }
591}
592
593impl AsMut<[u8]> for ShardMembershipEntropy {
594    #[inline(always)]
595    fn as_mut(&mut self) -> &mut [u8] {
596        &mut self.0
597    }
598}
599
600impl ShardMembershipEntropy {
601    /// Size in bytes
602    pub const SIZE: usize = PotOutput::SIZE;
603
604    /// Create a new instance
605    #[inline(always)]
606    pub const fn new(bytes: [u8; Self::SIZE]) -> Self {
607        Self(bytes)
608    }
609
610    /// Get internal representation
611    #[inline(always)]
612    pub const fn as_bytes(&self) -> &[u8; Self::SIZE] {
613        &self.0
614    }
615}
616
617/// Reduced hash used for shard assignment
618#[derive(
619    Default,
620    Copy,
621    Clone,
622    Eq,
623    PartialEq,
624    Ord,
625    PartialOrd,
626    Hash,
627    From,
628    Into,
629    AsRef,
630    AsMut,
631    Deref,
632    DerefMut,
633    TrivialType,
634    TransparentWrapper,
635)]
636#[cfg_attr(feature = "scale-codec", derive(Encode, Decode, MaxEncodedLen))]
637#[repr(C)]
638pub struct ShardCommitmentHash([u8; ShardCommitmentHash::SIZE]);
639
640impl fmt::Display for ShardCommitmentHash {
641    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
642        for byte in self.0 {
643            write!(f, "{byte:02x}")?;
644        }
645        Ok(())
646    }
647}
648
649#[cfg(feature = "serde")]
650#[derive(Serialize, Deserialize)]
651#[serde(transparent)]
652struct ShardCommitmentHashBinary([u8; ShardCommitmentHash::SIZE]);
653
654#[cfg(feature = "serde")]
655#[derive(Serialize, Deserialize)]
656#[serde(transparent)]
657struct ShardCommitmentHashHex(#[serde(with = "hex")] [u8; ShardCommitmentHash::SIZE]);
658
659#[cfg(feature = "serde")]
660impl Serialize for ShardCommitmentHash {
661    #[inline]
662    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
663    where
664        S: Serializer,
665    {
666        if serializer.is_human_readable() {
667            ShardCommitmentHashHex(self.0).serialize(serializer)
668        } else {
669            ShardCommitmentHashBinary(self.0).serialize(serializer)
670        }
671    }
672}
673
674#[cfg(feature = "serde")]
675impl<'de> Deserialize<'de> for ShardCommitmentHash {
676    #[inline]
677    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
678    where
679        D: Deserializer<'de>,
680    {
681        Ok(Self(if deserializer.is_human_readable() {
682            ShardCommitmentHashHex::deserialize(deserializer)?.0
683        } else {
684            ShardCommitmentHashBinary::deserialize(deserializer)?.0
685        }))
686    }
687}
688
689impl fmt::Debug for ShardCommitmentHash {
690    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
691        for byte in self.0 {
692            write!(f, "{byte:02x}")?;
693        }
694        Ok(())
695    }
696}
697
698impl AsRef<[u8]> for ShardCommitmentHash {
699    #[inline(always)]
700    fn as_ref(&self) -> &[u8] {
701        &self.0
702    }
703}
704
705impl AsMut<[u8]> for ShardCommitmentHash {
706    #[inline(always)]
707    fn as_mut(&mut self) -> &mut [u8] {
708        &mut self.0
709    }
710}
711
712impl From<Hash> for ShardCommitmentHash {
713    #[inline(always)]
714    fn from(value: Hash) -> Self {
715        let bytes = value.as_bytes();
716        Self(*bytes)
717        // Self([
718        //     bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
719        // ])
720    }
721}
722
723impl ShardCommitmentHash {
724    // TODO: Reduce to 8 bytes once Merkle Tree implementation exists that produces such hashes
725    /// Size in bytes
726    pub const SIZE: usize = 32;
727
728    /// Create a new instance
729    #[inline(always)]
730    pub const fn new(hash: [u8; Self::SIZE]) -> Self {
731        Self(hash)
732    }
733
734    /// Get internal representation
735    #[inline(always)]
736    pub const fn as_bytes(&self) -> &[u8; Self::SIZE] {
737        &self.0
738    }
739}
740
741/// Information about shard commitments in the solution
742#[derive(Clone, Copy, Debug, Eq, PartialEq, TrivialType)]
743#[cfg_attr(feature = "scale-codec", derive(Encode, Decode, MaxEncodedLen))]
744#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
745#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
746#[repr(C)]
747pub struct SolutionShardCommitment {
748    /// Root of the Merkle Tree of shard commitments
749    pub root: ShardCommitmentHash,
750    /// Proof for the shard commitment used the solution
751    pub proof: [ShardCommitmentHash; SolutionShardCommitment::NUM_LEAVES.ilog2() as usize],
752    /// Shard commitment leaf used for the solution
753    pub leaf: ShardCommitmentHash,
754}
755
756impl SolutionShardCommitment {
757    /// Number of leaves in a Merkle Tree of shard commitments
758    pub const NUM_LEAVES: usize = 2u32.pow(20) as usize;
759}
760
761/// Farmer solution for slot challenge.
762#[derive(Clone, Copy, Debug, Eq, PartialEq, TrivialType)]
763#[cfg_attr(feature = "scale-codec", derive(Encode, Decode, MaxEncodedLen))]
764#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
765#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
766#[repr(C)]
767pub struct Solution {
768    /// Public key of the farmer that created the solution
769    pub public_key_hash: Blake3Hash,
770    /// Farmer's shard commitment
771    pub shard_commitment: SolutionShardCommitment,
772    /// Local segment index of the piece
773    pub piece_local_segment_index: LocalSegmentIndex,
774    /// Segment root
775    pub segment_root: SegmentRoot,
776    /// Segment proof
777    pub segment_proof: SegmentProof,
778    /// Record root that can use used to verify that the piece was included in blockchain history
779    pub record_root: RecordRoot,
780    /// Proof that the record (root) belongs to a segment
781    pub record_proof: RecordProof,
782    /// Chunk at the below piece offset
783    pub chunk: RecordChunk,
784    /// Proof for the above chunk
785    pub chunk_proof: ChunkProof,
786    /// Proof of space for piece offset
787    pub proof_of_space: PosProof,
788    /// Size of the blockchain history at the time of sector creation
789    pub history_size: HistorySize,
790    /// Index of the sector where the solution was found
791    pub sector_index: SectorIndex,
792    /// Pieces offset within sector
793    pub piece_offset: PieceOffset,
794    /// Shard index on which the piece was archived
795    pub piece_shard_index: ShardIndex,
796}
797
798impl Solution {
799    /// Fake solution for the genesis block
800    pub fn genesis_solution() -> Self {
801        Self {
802            public_key_hash: Ed25519PublicKey::default().hash(),
803            shard_commitment: SolutionShardCommitment {
804                root: ShardCommitmentHash::default(),
805                proof: [ShardCommitmentHash::default(); _],
806                leaf: ShardCommitmentHash::default(),
807            },
808            piece_local_segment_index: LocalSegmentIndex::ZERO,
809            segment_root: SegmentRoot::default(),
810            segment_proof: SegmentProof::default(),
811            record_root: RecordRoot::default(),
812            record_proof: RecordProof::default(),
813            chunk: RecordChunk::default(),
814            chunk_proof: ChunkProof::default(),
815            proof_of_space: PosProof::default(),
816            history_size: HistorySize::from(SegmentIndex::ZERO),
817            sector_index: SectorIndex::ZERO,
818            piece_offset: PieceOffset::default(),
819            piece_shard_index: ShardIndex::BEACON_CHAIN,
820        }
821    }
822
823    #[inline]
824    fn sector_id(&self) -> SectorId {
825        SectorId::new(
826            &self.public_key_hash,
827            &self.shard_commitment.root,
828            self.sector_index,
829            self.history_size,
830        )
831    }
832
833    /// Check solution validity
834    pub fn verify_full<PotVerifier>(
835        &self,
836        slot: SlotNumber,
837        params: &SolutionVerifyFullParams,
838    ) -> Result<(), SolutionVerifyError>
839    where
840        PotVerifier: SolutionPotVerifier,
841    {
842        let sector_id = self.sector_id();
843
844        self.verify_stateless_inner::<PotVerifier>(&sector_id, slot, &params.stateless)?;
845
846        self.verify_piece_inner(&sector_id, &params.piece)
847    }
848
849    /// Stateless solution verification.
850    ///
851    /// Checks most things, except checking that the piece belongs to the global history.
852    ///
853    /// For piece verification use [`Self::verify_piece()`] or call [`Self::verify_full()`] for more
854    /// efficient verification of both at once.
855    pub fn verify_stateless<PotVerifier>(
856        &self,
857        slot: SlotNumber,
858        params: &SolutionVerifyStatelessParams,
859    ) -> Result<(), SolutionVerifyError>
860    where
861        PotVerifier: SolutionPotVerifier,
862    {
863        let sector_id = self.sector_id();
864
865        self.verify_stateless_inner::<PotVerifier>(&sector_id, slot, params)
866    }
867
868    fn verify_stateless_inner<PotVerifier>(
869        &self,
870        sector_id: &SectorId,
871        slot: SlotNumber,
872        params: &SolutionVerifyStatelessParams,
873    ) -> Result<(), SolutionVerifyError>
874    where
875        PotVerifier: SolutionPotVerifier,
876    {
877        let SolutionVerifyStatelessParams {
878            shard_index,
879            proof_of_time,
880            solution_range,
881            shard_membership_entropy,
882            num_shards,
883        } = params;
884
885        let shard_kind = shard_index
886            .shard_kind()
887            .and_then(ShardKind::to_real)
888            .ok_or(SolutionVerifyError::InvalidInputShard {
889                shard_index: *shard_index,
890                shard_kind: shard_index.shard_kind(),
891            })?;
892
893        let (solution_shard_index, shard_commitment_index) = num_shards
894            .derive_shard_index_and_shard_commitment_index(
895                &self.public_key_hash,
896                &self.shard_commitment.root,
897                shard_membership_entropy,
898                self.history_size,
899            );
900
901        // Adjust solution range according to shard kind
902        let solution_range = match shard_kind {
903            RealShardKind::BeaconChain => *solution_range,
904            RealShardKind::IntermediateShard => {
905                if solution_shard_index.parent_shard() != Some(*shard_index) {
906                    return Err(SolutionVerifyError::InvalidSolutionShard {
907                        solution_shard_index,
908                        solution_parent_shard_index: solution_shard_index.parent_shard(),
909                        expected_shard_index: *shard_index,
910                        expected_shard_kind: RealShardKind::IntermediateShard,
911                    });
912                }
913
914                solution_range.to_intermediate_shard(*num_shards)
915            }
916            RealShardKind::LeafShard => {
917                if solution_shard_index != *shard_index {
918                    return Err(SolutionVerifyError::InvalidSolutionShard {
919                        solution_shard_index,
920                        solution_parent_shard_index: solution_shard_index.parent_shard(),
921                        expected_shard_index: *shard_index,
922                        expected_shard_kind: RealShardKind::LeafShard,
923                    });
924                }
925
926                solution_range.to_leaf_shard(*num_shards)
927            }
928        };
929
930        if !BalancedMerkleTree::<{ SolutionShardCommitment::NUM_LEAVES }>::verify(
931            &self.shard_commitment.root,
932            self.shard_commitment.proof.peel_ref(),
933            shard_commitment_index as usize,
934            *self.shard_commitment.leaf,
935        ) {
936            return Err(SolutionVerifyError::InvalidShardCommitment);
937        }
938
939        let global_challenge = proof_of_time.derive_global_challenge(slot);
940        let sector_slot_challenge = sector_id.derive_sector_slot_challenge(&global_challenge);
941        let s_bucket_audit_index = sector_slot_challenge.s_bucket_audit_index();
942
943        // Check that proof of space is valid
944        if !PotVerifier::is_proof_valid(
945            &sector_id.derive_evaluation_seed(self.piece_offset),
946            s_bucket_audit_index,
947            &self.proof_of_space,
948        ) {
949            return Err(SolutionVerifyError::InvalidProofOfSpace);
950        }
951
952        let masked_chunk =
953            (Simd::from(*self.chunk) ^ Simd::from(*self.proof_of_space.hash())).to_array();
954
955        let solution_distance =
956            SolutionDistance::calculate(&global_challenge, &masked_chunk, &sector_slot_challenge);
957
958        if !solution_distance.is_within(solution_range) {
959            return Err(SolutionVerifyError::OutsideSolutionRange {
960                solution_range,
961                solution_distance,
962            });
963        }
964
965        // Check that chunk belongs to the record
966        if !BalancedMerkleTree::<{ Record::NUM_S_BUCKETS }>::verify(
967            &self.record_root,
968            &self.chunk_proof,
969            usize::from(s_bucket_audit_index),
970            *self.chunk,
971        ) {
972            return Err(SolutionVerifyError::InvalidChunkProof);
973        }
974
975        Ok(())
976    }
977
978    /// Verify the piece details of the solution
979    pub fn verify_piece(
980        &self,
981        piece_check_params: &SolutionVerifyPieceParams,
982    ) -> Result<(), SolutionVerifyError> {
983        let sector_id = self.sector_id();
984
985        self.verify_piece_inner(&sector_id, piece_check_params)
986    }
987
988    fn verify_piece_inner(
989        &self,
990        sector_id: &SectorId,
991        piece_check_params: &SolutionVerifyPieceParams,
992    ) -> Result<(), SolutionVerifyError> {
993        let SolutionVerifyPieceParams {
994            max_pieces_in_sector,
995            super_segment_root,
996            num_segments,
997            max_segment_index,
998            recent_segments,
999            recent_history_fraction,
1000            min_sector_lifetime,
1001            current_history_size,
1002            sector_expiration_check_super_segment_root,
1003        } = piece_check_params;
1004
1005        if &self.history_size > current_history_size {
1006            return Err(SolutionVerifyError::FutureHistorySize {
1007                current: *current_history_size,
1008                solution: self.history_size,
1009            });
1010        }
1011
1012        if u16::from(self.piece_offset) >= *max_pieces_in_sector {
1013            return Err(SolutionVerifyError::InvalidPieceOffset {
1014                piece_offset: u16::from(self.piece_offset),
1015                max_pieces_in_sector: *max_pieces_in_sector,
1016            });
1017        }
1018
1019        if let Some(sector_expiration_check_super_segment_root) =
1020            sector_expiration_check_super_segment_root
1021        {
1022            let Some(expiration_history_size) = sector_id.derive_expiration_history_size(
1023                self.history_size,
1024                sector_expiration_check_super_segment_root,
1025                *min_sector_lifetime,
1026            ) else {
1027                return Err(SolutionVerifyError::InvalidHistorySize);
1028            };
1029
1030            if expiration_history_size <= *current_history_size {
1031                return Err(SolutionVerifyError::SectorExpired {
1032                    expiration_history_size,
1033                    current_history_size: *current_history_size,
1034                });
1035            }
1036        }
1037
1038        let piece_index = sector_id.derive_piece_index(
1039            self.piece_offset,
1040            self.history_size,
1041            *max_pieces_in_sector,
1042            *recent_segments,
1043            *recent_history_fraction,
1044        );
1045        let segment_index = piece_index.segment_index();
1046
1047        let Some(segment_position) =
1048            segment_index.position_in_super_segment(*max_segment_index, *num_segments)
1049        else {
1050            return Err(SolutionVerifyError::PieceSegmentNotInSuperSegment {
1051                segment_index,
1052                max_segment_index: *max_segment_index,
1053                num_segments: *num_segments,
1054            });
1055        };
1056
1057        // Check that record belongs to the segment
1058        if !self.record_root.is_valid(
1059            &self.segment_root,
1060            &self.record_proof,
1061            piece_index.position(),
1062        ) {
1063            return Err(SolutionVerifyError::RecordNotInSegment);
1064        }
1065
1066        // Check that segment belongs to the super segment (global history)
1067        if !self.segment_root.is_valid(
1068            self.piece_shard_index,
1069            self.piece_local_segment_index,
1070            segment_position,
1071            &self.segment_proof,
1072            *num_segments,
1073            super_segment_root,
1074        ) {
1075            return Err(SolutionVerifyError::SegmentNotInSuperSegment);
1076        }
1077
1078        Ok(())
1079    }
1080}