1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
use crate::constants::COMMITMENT_BYTES;
use crate::util::*;
use bls12_381_plus::Scalar;
use serde::{Deserialize, Serialize};
use subtle::CtOption;

/// A challenge generated by fiat-shamir heuristic
#[derive(Debug, Copy, Clone, Eq, PartialEq, Deserialize, Serialize)]
pub struct Challenge(pub Scalar);

impl Default for Challenge {
    fn default() -> Self {
        Challenge(Scalar::zero())
    }
}

impl Challenge {
    /// The number of bytes in a challenge
    pub const BYTES: usize = 32;

    /// Hash arbitrary data to a challenge
    pub fn hash<B: AsRef<[u8]>>(data: B) -> Self {
        Self(hash_to_scalar(data))
    }

    /// Get the byte sequence that represents this challenge
    pub fn to_bytes(&self) -> [u8; Self::BYTES] {
        scalar_to_bytes(self.0)
    }

    /// Convert a big-endian representation of the challenge
    pub fn from_bytes(bytes: &[u8; Self::BYTES]) -> CtOption<Self> {
        scalar_from_bytes(bytes).map(Self)
    }

    /// Convert a 48 byte digest into a challenge
    pub fn from_okm(bytes: &[u8; COMMITMENT_BYTES]) -> Self {
        Self(Scalar::from_okm(bytes))
    }
}

#[cfg(test)]
mod test {
    use crate::constants::COMMITMENT_BYTES;
    use crate::lib::Challenge;

    #[test]
    fn challenge_test() {
        let h = [0_u8; 32];
        let c = Challenge::hash(h);
        let b = c.to_bytes();
        let cb = Challenge::from_bytes(&b).unwrap();
        assert_eq!(c, cb);

        let okm = [0_u8; COMMITMENT_BYTES];
        let co = Challenge::from_okm(&okm);
        let b = co.to_bytes();
        let cb = Challenge::from_bytes(&b).unwrap();
        assert_eq!(co, cb);
    }
}