feat: random base field element

This commit is contained in:
zhenfei
2024-01-04 19:51:41 -05:00
parent bb7ac0d158
commit 2725d23136

View File

@@ -1,12 +1,16 @@
//! This module defines our customized field trait.
use ff::Field;
use ff::PrimeField;
use halo2curves::serde::SerdeObject;
use rand_core::RngCore;
use serde::Serialize;
use crate::{fp2::GoldilocksExt2, Goldilocks, GoldilocksExt3};
pub trait SmallField: PrimeField + Serialize + SerdeObject {
/// Base field
type BaseField;
/// Extension degree of the Field
const DEGREE: usize;
/// Identifier string
@@ -16,12 +20,16 @@ pub trait SmallField: PrimeField + Serialize + SerdeObject {
/// Convert a field elements to a u64 vector
fn to_canonical_u64_vec(&self) -> Vec<u64>;
/// Convert self to limbs of Goldilocks elements
fn to_limbs(&self) -> Vec<Goldilocks>;
fn to_limbs(&self) -> Vec<Self::BaseField>;
/// Convert limbs into self
fn from_limbs(limbs: &[Goldilocks]) -> Self;
fn from_limbs(limbs: &[Self::BaseField]) -> Self;
/// Sample a random over the base field
fn sample_base(rng: impl RngCore) -> Self;
}
impl SmallField for Goldilocks {
type BaseField = Self;
const DEGREE: usize = 1;
const NAME: &'static str = "Goldilocks";
@@ -43,8 +51,14 @@ impl SmallField for Goldilocks {
fn from_limbs(limbs: &[Goldilocks]) -> Self {
limbs[0]
}
fn sample_base(mut rng: impl RngCore) -> Self {
Self::random(&mut rng)
}
}
impl SmallField for GoldilocksExt2 {
type BaseField = Goldilocks;
const DEGREE: usize = 2;
const NAME: &'static str = "GoldilocksExt2";
@@ -71,8 +85,14 @@ impl SmallField for GoldilocksExt2 {
fn from_limbs(limbs: &[Goldilocks]) -> Self {
Self(limbs[..1].try_into().unwrap())
}
fn sample_base(mut rng: impl RngCore) -> Self {
Self::BaseField::random(&mut rng).into()
}
}
impl SmallField for GoldilocksExt3 {
type BaseField = Goldilocks;
const DEGREE: usize = 3;
const NAME: &'static str = "GoldilocksExt3";
@@ -99,4 +119,8 @@ impl SmallField for GoldilocksExt3 {
fn from_limbs(limbs: &[Goldilocks]) -> Self {
Self(limbs[..2].try_into().unwrap())
}
fn sample_base(mut rng: impl RngCore) -> Self {
Self::BaseField::random(&mut rng).into()
}
}