1#[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#[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 pub const MAX: Self = Self(u64::MAX / 2);
48
49 #[inline(always)]
52 pub const fn from_u64(n: u64) -> Self {
53 Self(n)
54 }
55
56 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 pub const fn is_within(self, solution_range: SolutionRange) -> bool {
85 self.0 <= u64::from(solution_range) / 2
86 }
87}
88
89#[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 pub const SIZE: usize = size_of::<u64>();
129 pub const MIN: Self = Self(u64::MIN);
131 pub const MAX: Self = Self(u64::MAX);
133
134 #[inline(always)]
136 pub fn to_bytes(self) -> [u8; 8] {
137 self.0.to_le_bytes()
138 }
139
140 #[inline(always)]
142 pub fn from_bytes(bytes: [u8; 8]) -> Self {
143 Self(u64::from_le_bytes(bytes))
144 }
145
146 #[inline]
151 pub const fn from_pieces(pieces: u64, slot_probability: (u64, u64)) -> Self {
152 let solution_range = u64::MAX
153 / slot_probability.1 * slot_probability.0
155 / Record::NUM_CHUNKS as u64
157 * Record::NUM_S_BUCKETS as u64;
158
159 Self(solution_range / pieces)
161 }
162
163 #[inline]
168 pub const fn to_pieces(self, slot_probability: (u64, u64)) -> u64 {
169 let pieces = u64::MAX
170 / slot_probability.1 * slot_probability.0
172 / Record::NUM_CHUNKS as u64
174 * Record::NUM_S_BUCKETS as u64;
175
176 pieces / self.0
178 }
179
180 #[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 #[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 #[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 SolutionDistance::from_u64(if diff < diff2 { diff } else { diff2 })
211 }
212
213 #[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 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
252const {
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#[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 pub const SIZE: usize = OUT_LEN * Self::NUM_HASHES;
350 const NUM_HASHES: usize = Record::NUM_S_BUCKETS.ilog2() as usize;
351}
352
353#[derive(Debug, Eq, PartialEq, thiserror::Error)]
355pub enum SolutionVerifyError {
356 #[error("Piece verification failed")]
358 InvalidPieceOffset {
359 piece_offset: u16,
361 max_pieces_in_sector: u16,
363 },
364 #[error("History size {solution} is in the future, current is {current}")]
366 FutureHistorySize {
367 current: HistorySize,
369 solution: HistorySize,
371 },
372 #[error("Sector expired")]
374 SectorExpired {
375 expiration_history_size: HistorySize,
377 current_history_size: HistorySize,
379 },
380 #[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: SegmentIndex,
388 max_segment_index: SegmentIndex,
390 num_segments: u32,
392 },
393 #[error("Record does not belong to the segment")]
395 RecordNotInSegment,
396 #[error("Segment doesn't belong to the super segment")]
398 SegmentNotInSuperSegment,
399 #[error("Solution distance {solution_distance} is outside of solution range {solution_range}")]
401 OutsideSolutionRange {
402 solution_range: SolutionRange,
404 solution_distance: SolutionDistance,
406 },
407 #[error("Invalid proof of space")]
409 InvalidProofOfSpace,
410 #[error("Invalid shard commitment")]
412 InvalidShardCommitment,
413 #[error("Invalid input shard {shard_index} ({shard_kind:?})")]
415 InvalidInputShard {
416 shard_index: ShardIndex,
418 shard_kind: Option<ShardKind>,
420 },
421 #[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: ShardIndex,
429 solution_parent_shard_index: Option<ShardIndex>,
431 expected_shard_index: ShardIndex,
433 expected_shard_kind: RealShardKind,
435 },
436 #[error("Invalid chunk proof")]
438 InvalidChunkProof,
439 #[error("Invalid history size")]
441 InvalidHistorySize,
442}
443
444#[derive(Debug, Clone)]
449#[cfg_attr(feature = "scale-codec", derive(Encode, Decode, MaxEncodedLen))]
450pub struct SolutionVerifyStatelessParams {
451 pub shard_index: ShardIndex,
453 pub proof_of_time: PotOutput,
455 pub solution_range: SolutionRange,
457 pub shard_membership_entropy: ShardMembershipEntropy,
459 pub num_shards: NumShards,
461}
462
463#[derive(Debug, Clone)]
465#[cfg_attr(feature = "scale-codec", derive(Encode, Decode, MaxEncodedLen))]
466pub struct SolutionVerifyPieceParams {
467 pub max_pieces_in_sector: u16,
469 pub super_segment_root: SuperSegmentRoot,
472 pub num_segments: u32,
474 pub max_segment_index: SegmentIndex,
476 pub recent_segments: HistorySize,
478 pub recent_history_fraction: (HistorySize, HistorySize),
480 pub min_sector_lifetime: HistorySize,
482 pub current_history_size: HistorySize,
484 pub sector_expiration_check_super_segment_root: Option<SuperSegmentRoot>,
487}
488
489#[derive(Debug, Clone)]
491#[cfg_attr(feature = "scale-codec", derive(Encode, Decode, MaxEncodedLen))]
492pub struct SolutionVerifyFullParams {
493 pub stateless: SolutionVerifyStatelessParams,
495 pub piece: SolutionVerifyPieceParams,
497}
498
499pub trait SolutionPotVerifier {
501 fn is_proof_valid(seed: &PosSeed, s_bucket: SBucket, proof: &PosProof) -> bool;
503}
504
505#[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 pub const SIZE: usize = PotOutput::SIZE;
603
604 #[inline(always)]
606 pub const fn new(bytes: [u8; Self::SIZE]) -> Self {
607 Self(bytes)
608 }
609
610 #[inline(always)]
612 pub const fn as_bytes(&self) -> &[u8; Self::SIZE] {
613 &self.0
614 }
615}
616
617#[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 }
721}
722
723impl ShardCommitmentHash {
724 pub const SIZE: usize = 32;
727
728 #[inline(always)]
730 pub const fn new(hash: [u8; Self::SIZE]) -> Self {
731 Self(hash)
732 }
733
734 #[inline(always)]
736 pub const fn as_bytes(&self) -> &[u8; Self::SIZE] {
737 &self.0
738 }
739}
740
741#[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 pub root: ShardCommitmentHash,
750 pub proof: [ShardCommitmentHash; SolutionShardCommitment::NUM_LEAVES.ilog2() as usize],
752 pub leaf: ShardCommitmentHash,
754}
755
756impl SolutionShardCommitment {
757 pub const NUM_LEAVES: usize = 2u32.pow(20) as usize;
759}
760
761#[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 pub public_key_hash: Blake3Hash,
770 pub shard_commitment: SolutionShardCommitment,
772 pub piece_local_segment_index: LocalSegmentIndex,
774 pub segment_root: SegmentRoot,
776 pub segment_proof: SegmentProof,
778 pub record_root: RecordRoot,
780 pub record_proof: RecordProof,
782 pub chunk: RecordChunk,
784 pub chunk_proof: ChunkProof,
786 pub proof_of_space: PosProof,
788 pub history_size: HistorySize,
790 pub sector_index: SectorIndex,
792 pub piece_offset: PieceOffset,
794 pub piece_shard_index: ShardIndex,
796}
797
798impl Solution {
799 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 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>(§or_id, slot, ¶ms.stateless)?;
845
846 self.verify_piece_inner(§or_id, ¶ms.piece)
847 }
848
849 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>(§or_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 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 if !PotVerifier::is_proof_valid(
945 §or_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, §or_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 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 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(§or_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 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 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}