circomspect_program_structure/utils/
constants.rs

1use anyhow::{anyhow, Error};
2use num_bigint::BigInt;
3use std::fmt;
4use std::str::FromStr;
5
6#[derive(Default, Clone, PartialEq, Eq)]
7pub enum Curve {
8    #[default] // Used for testing.
9    Bn254,
10    Bls12_381,
11    Goldilocks,
12}
13
14impl fmt::Display for Curve {
15    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
16        use Curve::*;
17        match self {
18            Bn254 => write!(f, "BN254"),
19            Bls12_381 => write!(f, "BLS12_381"),
20            Goldilocks => write!(f, "Goldilocks"),
21        }
22    }
23}
24
25impl fmt::Debug for Curve {
26    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
27        write!(f, "{self}")
28    }
29}
30
31impl Curve {
32    fn prime(&self) -> BigInt {
33        use Curve::*;
34        let prime = match self {
35            Bn254 => {
36                "21888242871839275222246405745257275088548364400416034343698204186575808495617"
37            }
38            Bls12_381 => {
39                "52435875175126190479447740508185965837690552500527637822603658699938581184513"
40            }
41            Goldilocks => "18446744069414584321",
42        };
43        BigInt::parse_bytes(prime.as_bytes(), 10).expect("failed to parse prime")
44    }
45}
46
47impl FromStr for Curve {
48    type Err = Error;
49
50    fn from_str(curve: &str) -> Result<Self, Self::Err> {
51        match &curve.to_uppercase()[..] {
52            "BN254" => Ok(Curve::Bn254),
53            "BLS12_381" => Ok(Curve::Bls12_381),
54            "GOLDILOCKS" => Ok(Curve::Goldilocks),
55            _ => Err(anyhow!("failed to parse curve `{curve}`")),
56        }
57    }
58}
59
60#[derive(Clone)]
61pub struct UsefulConstants {
62    curve: Curve,
63    prime: BigInt,
64}
65
66impl UsefulConstants {
67    pub fn new(curve: &Curve) -> UsefulConstants {
68        UsefulConstants { curve: curve.clone(), prime: curve.prime() }
69    }
70
71    /// Returns the used curve.
72    pub fn curve(&self) -> &Curve {
73        &self.curve
74    }
75
76    /// Returns the used prime.
77    pub fn prime(&self) -> &BigInt {
78        &self.prime
79    }
80
81    /// Returns the size in bits of the used prime.
82    pub fn prime_size(&self) -> usize {
83        self.prime.bits()
84    }
85}