Skip to main content

ab_core_primitives/
sectors.rs

1//! Sectors-related data structures.
2
3#[cfg(test)]
4mod tests;
5
6use crate::hashes::Blake3Hash;
7use crate::nano_u256::NanoU256;
8use crate::pieces::{PieceIndex, PieceOffset, Record};
9use crate::pos::PosSeed;
10use crate::segments::{HistorySize, SuperSegmentRoot};
11use crate::solutions::ShardCommitmentHash;
12use ab_blake3::{single_block_hash, single_block_keyed_hash};
13use ab_io_type::trivial_type::TrivialType;
14use core::hash::Hash;
15use core::iter::Step;
16use core::num::{NonZeroU64, TryFromIntError};
17use core::simd::Simd;
18use derive_more::{Add, AddAssign, Deref, Display, Div, DivAssign, Mul, MulAssign, Sub, SubAssign};
19#[cfg(feature = "scale-codec")]
20use parity_scale_codec::{Decode, Encode, MaxEncodedLen};
21#[cfg(feature = "serde")]
22use serde::{Deserialize, Serialize};
23
24/// Sector index in consensus
25#[derive(
26    Debug,
27    Display,
28    Default,
29    Copy,
30    Clone,
31    Ord,
32    PartialOrd,
33    Eq,
34    PartialEq,
35    Hash,
36    Add,
37    AddAssign,
38    Sub,
39    SubAssign,
40    Mul,
41    MulAssign,
42    Div,
43    DivAssign,
44    TrivialType,
45)]
46#[cfg_attr(feature = "scale-codec", derive(Encode, Decode, MaxEncodedLen))]
47#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
48#[repr(C)]
49pub struct SectorIndex(u16);
50
51impl Step for SectorIndex {
52    #[inline(always)]
53    fn steps_between(start: &Self, end: &Self) -> (usize, Option<usize>) {
54        u16::steps_between(&start.0, &end.0)
55    }
56
57    #[inline(always)]
58    fn forward_checked(start: Self, count: usize) -> Option<Self> {
59        u16::forward_checked(start.0, count).map(Self)
60    }
61
62    #[inline(always)]
63    fn forward_overflowing(start: Self, count: usize) -> (Self, bool) {
64        let (n, overflowing) = u16::forward_overflowing(start.0, count);
65        (Self(n), overflowing)
66    }
67
68    #[inline(always)]
69    fn backward_checked(start: Self, count: usize) -> Option<Self> {
70        u16::backward_checked(start.0, count).map(Self)
71    }
72
73    #[inline(always)]
74    fn backward_overflowing(start: Self, count: usize) -> (Self, bool) {
75        let (n, overflowing) = u16::backward_overflowing(start.0, count);
76        (Self(n), overflowing)
77    }
78}
79
80const impl From<u16> for SectorIndex {
81    #[inline(always)]
82    fn from(value: u16) -> Self {
83        Self(value)
84    }
85}
86
87const impl From<SectorIndex> for u16 {
88    #[inline(always)]
89    fn from(value: SectorIndex) -> Self {
90        value.0
91    }
92}
93
94const impl From<SectorIndex> for u32 {
95    #[inline(always)]
96    fn from(original: SectorIndex) -> Self {
97        u32::from(original.0)
98    }
99}
100
101const impl From<SectorIndex> for u64 {
102    #[inline(always)]
103    fn from(original: SectorIndex) -> Self {
104        u64::from(original.0)
105    }
106}
107
108const impl From<SectorIndex> for usize {
109    #[inline(always)]
110    fn from(original: SectorIndex) -> Self {
111        usize::from(original.0)
112    }
113}
114
115impl SectorIndex {
116    /// Size in bytes
117    pub const SIZE: usize = size_of::<u16>();
118    /// Sector index 0
119    pub const ZERO: Self = Self(0);
120    /// Max sector index
121    pub const MAX: Self = Self(u16::MAX);
122
123    /// Create sector index from bytes.
124    #[inline(always)]
125    pub const fn from_bytes(bytes: [u8; Self::SIZE]) -> Self {
126        Self(u16::from_le_bytes(bytes))
127    }
128
129    /// Convert sector index to bytes.
130    #[inline(always)]
131    pub const fn to_bytes(self) -> [u8; Self::SIZE] {
132        self.0.to_le_bytes()
133    }
134}
135
136/// Challenge used for a particular sector for particular slot
137#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Deref)]
138pub struct SectorSlotChallenge(Blake3Hash);
139
140impl SectorSlotChallenge {
141    /// Index of s-bucket within sector to be audited
142    #[inline]
143    pub fn s_bucket_audit_index(&self) -> SBucket {
144        // As long as number of s-buckets is 2^16, we can pick first two bytes instead of actually
145        // calculating `U256::from_le_bytes(self.0) % Record::NUM_S_BUCKETS)`
146        const {
147            assert!(Record::NUM_S_BUCKETS == 1 << u16::BITS as usize);
148        }
149        SBucket::from(u16::from_le_bytes([self.0[0], self.0[1]]))
150    }
151}
152
153/// Data structure representing sector ID in farmer's plot
154#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
155#[cfg_attr(feature = "scale-codec", derive(Encode, Decode))]
156#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
157pub struct SectorId(Blake3Hash);
158
159impl AsRef<[u8]> for SectorId {
160    #[inline]
161    fn as_ref(&self) -> &[u8] {
162        self.0.as_ref()
163    }
164}
165
166impl SectorId {
167    /// Size in bytes
168    const SIZE: usize = Blake3Hash::SIZE;
169
170    /// Create a new sector ID by deriving it from public key and sector index
171    #[inline]
172    pub fn new(
173        public_key_hash: &Blake3Hash,
174        shard_commitments_root: &ShardCommitmentHash,
175        sector_index: SectorIndex,
176        history_size: HistorySize,
177    ) -> Self {
178        let mut bytes_to_hash =
179            [0; SectorIndex::SIZE + HistorySize::SIZE as usize + ShardCommitmentHash::SIZE];
180        bytes_to_hash[..SectorIndex::SIZE].copy_from_slice(&sector_index.to_bytes());
181        bytes_to_hash[SectorIndex::SIZE..][..HistorySize::SIZE as usize]
182            .copy_from_slice(&history_size.as_non_zero_u64().get().to_le_bytes());
183        bytes_to_hash[SectorIndex::SIZE + HistorySize::SIZE as usize..]
184            .copy_from_slice(shard_commitments_root.as_bytes());
185        Self(Blake3Hash::new(
186            single_block_keyed_hash(public_key_hash, &bytes_to_hash)
187                .expect("Less than a single block worth of bytes; qed"),
188        ))
189    }
190
191    /// Derive piece index that should be stored in sector at `piece_offset` for specified size of
192    /// blockchain history
193    pub fn derive_piece_index(
194        &self,
195        piece_offset: PieceOffset,
196        history_size: HistorySize,
197        max_pieces_in_sector: u16,
198        recent_segments: HistorySize,
199        recent_history_fraction: (HistorySize, HistorySize),
200    ) -> PieceIndex {
201        let recent_segments_in_pieces = recent_segments.in_pieces().get();
202        // Recent history must be at most `recent_history_fraction` of all history to use separate
203        // policy for recent pieces
204        let min_history_size_in_pieces = recent_segments_in_pieces
205            * recent_history_fraction.1.in_pieces().get()
206            / recent_history_fraction.0.in_pieces();
207        let input_hash = {
208            let mut bytes_to_hash = [0; Self::SIZE + PieceOffset::SIZE];
209            bytes_to_hash[..Self::SIZE].copy_from_slice(self.as_ref());
210            bytes_to_hash[Self::SIZE..].copy_from_slice(&piece_offset.to_bytes());
211            NanoU256::from_le_bytes(
212                single_block_hash(&bytes_to_hash)
213                    .expect("Less than a single block worth of bytes; qed"),
214            )
215        };
216        let history_size_in_pieces = history_size.in_pieces().get();
217        let num_interleaved_pieces = 1.max(
218            u64::from(max_pieces_in_sector) * recent_history_fraction.0.in_pieces().get()
219                / recent_history_fraction.1.in_pieces()
220                * 2,
221        );
222
223        let piece_index = if history_size_in_pieces > min_history_size_in_pieces
224            && u64::from(piece_offset) < num_interleaved_pieces
225            && u16::from(piece_offset) % 2 == 1
226        {
227            // For odd piece offsets at the beginning of the sector pick pieces at random from
228            // recent history only
229            (input_hash % recent_segments_in_pieces)
230                + (history_size_in_pieces - recent_segments_in_pieces)
231        } else {
232            input_hash % history_size_in_pieces
233        };
234
235        PieceIndex::from(piece_index)
236    }
237
238    /// Derive sector slot challenge for this sector from provided global challenge
239    pub fn derive_sector_slot_challenge(
240        &self,
241        global_challenge: &Blake3Hash,
242    ) -> SectorSlotChallenge {
243        let sector_slot_challenge = Simd::from(*self.0) ^ Simd::from(**global_challenge);
244        SectorSlotChallenge(sector_slot_challenge.to_array().into())
245    }
246
247    /// Derive evaluation seed
248    pub fn derive_evaluation_seed(&self, piece_offset: PieceOffset) -> PosSeed {
249        let mut bytes_to_hash = [0; Self::SIZE + PieceOffset::SIZE];
250        bytes_to_hash[..Self::SIZE].copy_from_slice(self.as_ref());
251        bytes_to_hash[Self::SIZE..].copy_from_slice(&piece_offset.to_bytes());
252        let evaluation_seed = single_block_hash(&bytes_to_hash)
253            .expect("Less than a single block worth of bytes; qed");
254
255        PosSeed::from(evaluation_seed)
256    }
257
258    /// Derive history size when sector created at `history_size` expires.
259    ///
260    /// Returns `None` on overflow.
261    pub fn derive_expiration_history_size(
262        &self,
263        history_size: HistorySize,
264        sector_expiration_check_super_segment_root: &SuperSegmentRoot,
265        min_sector_lifetime: HistorySize,
266    ) -> Option<HistorySize> {
267        let sector_expiration_check_history_size = history_size
268            .sector_expiration_check(min_sector_lifetime)?
269            .as_non_zero_u64();
270
271        let input_hash = NanoU256::from_le_bytes(
272            single_block_hash(
273                [*self.0, **sector_expiration_check_super_segment_root].as_flattened(),
274            )
275            .expect("Less than a single block worth of bytes; qed"),
276        );
277
278        let last_possible_expiration = min_sector_lifetime
279            .as_non_zero_u64()
280            .checked_add(history_size.as_non_zero_u64().get().checked_mul(4u64)?)?;
281        let expires_in = input_hash
282            % last_possible_expiration
283                .get()
284                .checked_sub(sector_expiration_check_history_size.get())?;
285
286        let expiration_history_size = sector_expiration_check_history_size.get() + expires_in;
287        let expiration_history_size = NonZeroU64::try_from(expiration_history_size).expect(
288            "History size is not zero, so result is not zero even if expires immediately; qed",
289        );
290        Some(HistorySize::new(expiration_history_size))
291    }
292}
293
294/// S-bucket used in consensus
295#[derive(
296    Debug,
297    Display,
298    Default,
299    Copy,
300    Clone,
301    Ord,
302    PartialOrd,
303    Eq,
304    PartialEq,
305    Hash,
306    Add,
307    AddAssign,
308    Sub,
309    SubAssign,
310    Mul,
311    MulAssign,
312    Div,
313    DivAssign,
314)]
315#[cfg_attr(feature = "scale-codec", derive(Encode, Decode, MaxEncodedLen))]
316#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
317#[repr(C)]
318pub struct SBucket(u16);
319
320impl Step for SBucket {
321    #[inline]
322    fn steps_between(start: &Self, end: &Self) -> (usize, Option<usize>) {
323        u16::steps_between(&start.0, &end.0)
324    }
325
326    #[inline]
327    fn forward_checked(start: Self, count: usize) -> Option<Self> {
328        u16::forward_checked(start.0, count).map(Self)
329    }
330
331    #[inline(always)]
332    fn forward_overflowing(start: Self, count: usize) -> (Self, bool) {
333        let (n, overflowing) = u16::forward_overflowing(start.0, count);
334        (Self(n), overflowing)
335    }
336
337    #[inline]
338    fn backward_checked(start: Self, count: usize) -> Option<Self> {
339        u16::backward_checked(start.0, count).map(Self)
340    }
341
342    #[inline(always)]
343    fn backward_overflowing(start: Self, count: usize) -> (Self, bool) {
344        let (n, overflowing) = u16::backward_overflowing(start.0, count);
345        (Self(n), overflowing)
346    }
347}
348
349const impl From<u16> for SBucket {
350    #[inline(always)]
351    fn from(value: u16) -> Self {
352        Self(value)
353    }
354}
355
356const impl From<SBucket> for u16 {
357    #[inline(always)]
358    fn from(value: SBucket) -> Self {
359        value.0
360    }
361}
362
363impl TryFrom<usize> for SBucket {
364    type Error = TryFromIntError;
365
366    #[inline]
367    fn try_from(value: usize) -> Result<Self, Self::Error> {
368        Ok(Self(u16::try_from(value)?))
369    }
370}
371
372impl From<SBucket> for u32 {
373    #[inline]
374    fn from(original: SBucket) -> Self {
375        u32::from(original.0)
376    }
377}
378
379impl From<SBucket> for usize {
380    #[inline]
381    fn from(original: SBucket) -> Self {
382        usize::from(original.0)
383    }
384}
385
386impl SBucket {
387    /// S-bucket 0.
388    pub const ZERO: SBucket = SBucket(0);
389    /// Max s-bucket index
390    pub const MAX: SBucket = SBucket((Record::NUM_S_BUCKETS - 1) as u16);
391}