Skip to main content

ab_core_primitives/
pot.rs

1//! Proof of time-related data structures.
2
3use crate::block::BlockRoot;
4use crate::hashes::Blake3Hash;
5use crate::pieces::RecordChunk;
6use crate::solutions::ShardMembershipEntropy;
7use ab_blake3::single_block_hash;
8use ab_io_type::trivial_type::TrivialType;
9use core::fmt;
10use core::iter::Step;
11use core::num::{NonZeroU8, NonZeroU32};
12use core::str::FromStr;
13use core::time::Duration;
14use derive_more::{
15    Add, AddAssign, AsMut, AsRef, Deref, DerefMut, Display, Div, DivAssign, From, Into, Mul,
16    MulAssign, Sub, SubAssign,
17};
18#[cfg(feature = "scale-codec")]
19use parity_scale_codec::{Decode, Encode, MaxEncodedLen};
20#[cfg(feature = "serde")]
21use serde::{Deserialize, Serialize};
22#[cfg(feature = "serde")]
23use serde::{Deserializer, Serializer};
24use transparent_wrapper::TransparentWrapper;
25
26/// Slot duration
27#[derive(
28    Debug, Display, Default, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, From, Into,
29)]
30#[cfg_attr(feature = "scale-codec", derive(Encode, Decode, MaxEncodedLen))]
31#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
32#[repr(C)]
33pub struct SlotDuration(u16);
34
35impl SlotDuration {
36    /// Size in bytes
37    pub const SIZE: usize = size_of::<u16>();
38
39    /// Create a new instance
40    #[inline(always)]
41    pub const fn from_millis(ms: u16) -> Self {
42        Self(ms)
43    }
44
45    /// Get internal representation
46    #[inline(always)]
47    pub const fn as_millis(self) -> u16 {
48        self.0
49    }
50
51    /// Get the value as [`Duration`] instance
52    #[inline(always)]
53    pub const fn as_duration(self) -> Duration {
54        Duration::from_millis(self.as_millis() as u64)
55    }
56}
57
58/// Slot number
59#[derive(
60    Debug,
61    Display,
62    Default,
63    Copy,
64    Clone,
65    Ord,
66    PartialOrd,
67    Eq,
68    PartialEq,
69    Hash,
70    Add,
71    AddAssign,
72    Sub,
73    SubAssign,
74    Mul,
75    MulAssign,
76    Div,
77    DivAssign,
78    TrivialType,
79)]
80#[cfg_attr(feature = "scale-codec", derive(Encode, Decode, MaxEncodedLen))]
81#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
82#[repr(C)]
83pub struct SlotNumber(u64);
84
85impl Step for SlotNumber {
86    #[inline(always)]
87    fn steps_between(start: &Self, end: &Self) -> (usize, Option<usize>) {
88        u64::steps_between(&start.0, &end.0)
89    }
90
91    #[inline(always)]
92    fn forward_checked(start: Self, count: usize) -> Option<Self> {
93        u64::forward_checked(start.0, count).map(Self)
94    }
95
96    #[inline(always)]
97    fn forward_overflowing(start: Self, count: usize) -> (Self, bool) {
98        let (n, overflowing) = u64::forward_overflowing(start.0, count);
99        (Self(n), overflowing)
100    }
101
102    #[inline(always)]
103    fn backward_checked(start: Self, count: usize) -> Option<Self> {
104        u64::backward_checked(start.0, count).map(Self)
105    }
106
107    #[inline(always)]
108    fn backward_overflowing(start: Self, count: usize) -> (Self, bool) {
109        let (n, overflowing) = u64::backward_overflowing(start.0, count);
110        (Self(n), overflowing)
111    }
112}
113
114const impl From<u64> for SlotNumber {
115    #[inline(always)]
116    fn from(value: u64) -> Self {
117        Self(value)
118    }
119}
120
121const impl From<SlotNumber> for u64 {
122    #[inline(always)]
123    fn from(value: SlotNumber) -> Self {
124        value.0
125    }
126}
127
128impl From<SlotNumber> for u128 {
129    #[inline(always)]
130    fn from(original: SlotNumber) -> Self {
131        u128::from(original.0)
132    }
133}
134
135impl SlotNumber {
136    /// Size in bytes
137    pub const SIZE: usize = size_of::<u64>();
138    /// Slot 0
139    pub const ZERO: Self = Self(0);
140    /// Slot 1
141    pub const ONE: Self = Self(1);
142    /// Max slot
143    pub const MAX: Self = Self(u64::MAX);
144
145    /// Create slot number from bytes
146    #[inline(always)]
147    pub const fn from_bytes(bytes: [u8; Self::SIZE]) -> Self {
148        Self(u64::from_le_bytes(bytes))
149    }
150
151    /// Convert slot number to bytes
152    #[inline(always)]
153    pub const fn to_bytes(self) -> [u8; Self::SIZE] {
154        self.0.to_le_bytes()
155    }
156
157    /// Checked addition, returns `None` on overflow
158    #[inline(always)]
159    pub const fn checked_add(self, rhs: Self) -> Option<Self> {
160        if let Some(n) = self.0.checked_add(rhs.0) {
161            Some(Self(n))
162        } else {
163            None
164        }
165    }
166
167    /// Saturating addition
168    #[inline(always)]
169    pub const fn saturating_add(self, rhs: Self) -> Self {
170        Self(self.0.saturating_add(rhs.0))
171    }
172
173    /// Checked subtraction, returns `None` on underflow
174    #[inline(always)]
175    pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
176        if let Some(n) = self.0.checked_sub(rhs.0) {
177            Some(Self(n))
178        } else {
179            None
180        }
181    }
182
183    /// Saturating subtraction
184    #[inline(always)]
185    pub const fn saturating_sub(self, rhs: Self) -> Self {
186        Self(self.0.saturating_sub(rhs.0))
187    }
188}
189
190/// Proof of time key(input to the encryption).
191#[derive(Default, Copy, Clone, Eq, PartialEq, From, Into, AsRef, AsMut, Deref, DerefMut)]
192#[cfg_attr(feature = "scale-codec", derive(Encode, Decode, MaxEncodedLen))]
193pub struct PotKey([u8; PotKey::SIZE]);
194
195impl fmt::Debug for PotKey {
196    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
197        for byte in self.0 {
198            write!(f, "{byte:02x}")?;
199        }
200        Ok(())
201    }
202}
203
204#[cfg(feature = "serde")]
205#[derive(Serialize, Deserialize)]
206#[serde(transparent)]
207struct PotKeyBinary([u8; PotKey::SIZE]);
208
209#[cfg(feature = "serde")]
210#[derive(Serialize, Deserialize)]
211#[serde(transparent)]
212struct PotKeyHex(#[serde(with = "hex")] [u8; PotKey::SIZE]);
213
214#[cfg(feature = "serde")]
215impl Serialize for PotKey {
216    #[inline]
217    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
218    where
219        S: Serializer,
220    {
221        if serializer.is_human_readable() {
222            PotKeyHex(self.0).serialize(serializer)
223        } else {
224            PotKeyBinary(self.0).serialize(serializer)
225        }
226    }
227}
228
229#[cfg(feature = "serde")]
230impl<'de> Deserialize<'de> for PotKey {
231    #[inline]
232    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
233    where
234        D: Deserializer<'de>,
235    {
236        Ok(Self(if deserializer.is_human_readable() {
237            PotKeyHex::deserialize(deserializer)?.0
238        } else {
239            PotKeyBinary::deserialize(deserializer)?.0
240        }))
241    }
242}
243
244impl fmt::Display for PotKey {
245    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
246        for byte in self.0 {
247            write!(f, "{byte:02x}")?;
248        }
249        Ok(())
250    }
251}
252
253impl FromStr for PotKey {
254    type Err = hex::FromHexError;
255
256    #[inline]
257    fn from_str(s: &str) -> Result<Self, Self::Err> {
258        let mut key = Self::default();
259        hex::decode_to_slice(s, key.as_mut())?;
260
261        Ok(key)
262    }
263}
264
265impl PotKey {
266    /// Size in bytes
267    pub const SIZE: usize = 16;
268}
269
270/// Proof of time seed
271#[derive(Default, Copy, Clone, Eq, PartialEq, Hash, From, Into, AsRef, AsMut, Deref, DerefMut)]
272#[cfg_attr(feature = "scale-codec", derive(Encode, Decode, MaxEncodedLen))]
273pub struct PotSeed([u8; PotSeed::SIZE]);
274
275impl fmt::Debug for PotSeed {
276    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
277        for byte in self.0 {
278            write!(f, "{byte:02x}")?;
279        }
280        Ok(())
281    }
282}
283
284#[cfg(feature = "serde")]
285#[derive(Serialize, Deserialize)]
286#[serde(transparent)]
287struct PotSeedBinary([u8; PotSeed::SIZE]);
288
289#[cfg(feature = "serde")]
290#[derive(Serialize, Deserialize)]
291#[serde(transparent)]
292struct PotSeedHex(#[serde(with = "hex")] [u8; PotSeed::SIZE]);
293
294#[cfg(feature = "serde")]
295impl Serialize for PotSeed {
296    #[inline]
297    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
298    where
299        S: Serializer,
300    {
301        if serializer.is_human_readable() {
302            PotSeedHex(self.0).serialize(serializer)
303        } else {
304            PotSeedBinary(self.0).serialize(serializer)
305        }
306    }
307}
308
309#[cfg(feature = "serde")]
310impl<'de> Deserialize<'de> for PotSeed {
311    #[inline]
312    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
313    where
314        D: Deserializer<'de>,
315    {
316        Ok(Self(if deserializer.is_human_readable() {
317            PotSeedHex::deserialize(deserializer)?.0
318        } else {
319            PotSeedBinary::deserialize(deserializer)?.0
320        }))
321    }
322}
323
324impl fmt::Display for PotSeed {
325    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
326        for byte in self.0 {
327            write!(f, "{byte:02x}")?;
328        }
329        Ok(())
330    }
331}
332
333impl PotSeed {
334    /// Size in bytes
335    pub const SIZE: usize = 16;
336
337    /// Derive initial PoT seed from genesis block root
338    #[inline]
339    pub fn from_genesis(genesis_block_root: &BlockRoot, external_entropy: &[u8]) -> Self {
340        let mut hasher = blake3::Hasher::new();
341        hasher.update(genesis_block_root.as_ref());
342        hasher.update(external_entropy);
343        let hash = hasher.finalize();
344        let mut seed = Self::default();
345        seed.copy_from_slice(&hash.as_bytes()[..Self::SIZE]);
346        seed
347    }
348
349    /// Derive key from proof of time seed
350    #[inline]
351    pub fn key(&self) -> PotKey {
352        let mut key = PotKey::default();
353        key.copy_from_slice(
354            &single_block_hash(&self.0).expect("Less than a single block worth of bytes; qed")
355                [..Self::SIZE],
356        );
357        key
358    }
359}
360
361/// Proof of time output, can be intermediate checkpoint or final slot output
362#[derive(
363    Default,
364    Copy,
365    Clone,
366    Eq,
367    PartialEq,
368    Hash,
369    From,
370    Into,
371    AsRef,
372    AsMut,
373    Deref,
374    DerefMut,
375    TrivialType,
376    TransparentWrapper,
377)]
378#[cfg_attr(feature = "scale-codec", derive(Encode, Decode, MaxEncodedLen))]
379#[repr(C)]
380pub struct PotOutput([u8; PotOutput::SIZE]);
381
382impl fmt::Debug for PotOutput {
383    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
384        for byte in self.0 {
385            write!(f, "{byte:02x}")?;
386        }
387        Ok(())
388    }
389}
390
391#[cfg(feature = "serde")]
392#[derive(Serialize, Deserialize)]
393#[serde(transparent)]
394struct PotOutputBinary([u8; PotOutput::SIZE]);
395
396#[cfg(feature = "serde")]
397#[derive(Serialize, Deserialize)]
398#[serde(transparent)]
399struct PotOutputHex(#[serde(with = "hex")] [u8; PotOutput::SIZE]);
400
401#[cfg(feature = "serde")]
402impl Serialize for PotOutput {
403    #[inline]
404    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
405    where
406        S: Serializer,
407    {
408        if serializer.is_human_readable() {
409            PotOutputHex(self.0).serialize(serializer)
410        } else {
411            PotOutputBinary(self.0).serialize(serializer)
412        }
413    }
414}
415
416#[cfg(feature = "serde")]
417impl<'de> Deserialize<'de> for PotOutput {
418    #[inline]
419    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
420    where
421        D: Deserializer<'de>,
422    {
423        Ok(Self(if deserializer.is_human_readable() {
424            PotOutputHex::deserialize(deserializer)?.0
425        } else {
426            PotOutputBinary::deserialize(deserializer)?.0
427        }))
428    }
429}
430
431impl fmt::Display for PotOutput {
432    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
433        for byte in self.0 {
434            write!(f, "{byte:02x}")?;
435        }
436        Ok(())
437    }
438}
439
440impl PotOutput {
441    /// Size in bytes
442    pub const SIZE: usize = 16;
443
444    /// Derives the global challenge from the output and slot
445    #[inline]
446    pub fn derive_global_challenge(&self, slot: SlotNumber) -> Blake3Hash {
447        let mut bytes_to_hash = [0; Self::SIZE + SlotNumber::SIZE];
448        bytes_to_hash[..Self::SIZE].copy_from_slice(&self.0);
449        bytes_to_hash[Self::SIZE..].copy_from_slice(&slot.to_bytes());
450        Blake3Hash::new(
451            single_block_hash(&bytes_to_hash)
452                .expect("Less than a single block worth of bytes; qed"),
453        )
454    }
455
456    /// Derive seed from proof of time in case entropy injection is not needed
457    #[inline]
458    pub fn seed(&self) -> PotSeed {
459        PotSeed(self.0)
460    }
461
462    /// Derive seed from proof of time with entropy injection
463    #[inline]
464    pub fn seed_with_entropy(&self, entropy: &Blake3Hash) -> PotSeed {
465        let mut bytes_to_hash = [0; Blake3Hash::SIZE + Self::SIZE];
466        bytes_to_hash[..Blake3Hash::SIZE].copy_from_slice(entropy.as_ref());
467        bytes_to_hash[Blake3Hash::SIZE..].copy_from_slice(&self.0);
468        let hash = single_block_hash(&bytes_to_hash)
469            .expect("Less than a single block worth of bytes; qed");
470        let mut seed = PotSeed::default();
471        seed.copy_from_slice(&hash[..Self::SIZE]);
472        seed
473    }
474
475    /// Derive proof of time entropy from chunk and proof of time for injection purposes
476    #[inline]
477    pub fn derive_pot_entropy(&self, solution_chunk: &RecordChunk) -> Blake3Hash {
478        let mut bytes_to_hash = [0; RecordChunk::SIZE + Self::SIZE];
479        bytes_to_hash[..RecordChunk::SIZE].copy_from_slice(solution_chunk.as_ref());
480        bytes_to_hash[RecordChunk::SIZE..].copy_from_slice(&self.0);
481        Blake3Hash::new(
482            single_block_hash(&bytes_to_hash)
483                .expect("Less than a single block worth of bytes; qed"),
484        )
485    }
486
487    /// Derive shard membership entropy
488    #[inline]
489    pub fn shard_membership_entropy(&self) -> ShardMembershipEntropy {
490        ShardMembershipEntropy::new(self.0)
491    }
492}
493
494/// Proof of time checkpoints, result of proving
495#[derive(
496    Debug,
497    Default,
498    Copy,
499    Clone,
500    Eq,
501    PartialEq,
502    Hash,
503    Deref,
504    DerefMut,
505    TrivialType,
506    TransparentWrapper,
507)]
508#[cfg_attr(feature = "scale-codec", derive(Encode, Decode, MaxEncodedLen))]
509#[repr(C)]
510pub struct PotCheckpoints([PotOutput; PotCheckpoints::NUM_CHECKPOINTS.get() as usize]);
511
512impl PotCheckpoints {
513    /// Size in bytes
514    pub const SIZE: usize = PotOutput::SIZE * Self::NUM_CHECKPOINTS.get() as usize;
515    /// Number of PoT checkpoints produced (used to optimize verification)
516    pub const NUM_CHECKPOINTS: NonZeroU8 = NonZeroU8::new(8).expect("Not zero; qed");
517
518    /// Get proof of time output out of checkpoints (last checkpoint)
519    #[inline]
520    pub fn output(&self) -> PotOutput {
521        self.0[Self::NUM_CHECKPOINTS.get() as usize - 1]
522    }
523}
524
525/// Change of parameters to apply to the proof of time chain.
526///
527/// Corresponds to scheduled PoT parameters change, which is applied after the slot of this block.
528/// It is carried into the next blocks until it is applied on or before slot of the current block.
529#[derive(Debug, Copy, Clone, PartialEq, Eq)]
530#[cfg_attr(feature = "scale-codec", derive(Encode, Decode, MaxEncodedLen))]
531#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
532#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
533pub struct PotParametersChange {
534    // TODO: Reduce this to `u16` or even `u8` since it is always an offset relatively to current
535    //  block's slot number
536    /// At which slot change of parameters takes effect
537    pub slot: SlotNumber,
538    /// New number of slot iterations
539    pub slot_iterations: NonZeroU32,
540    /// Entropy that should be injected at this time
541    pub entropy: Blake3Hash,
542}