snarkvm_circuit_types_field/
lib.rs#![forbid(unsafe_code)]
#![allow(clippy::too_many_arguments)]
#![cfg_attr(test, allow(clippy::assertions_on_result_states))]
mod helpers;
pub mod add;
pub mod compare;
pub mod div;
pub mod div_unchecked;
pub mod double;
pub mod equal;
pub mod inverse;
pub mod mul;
pub mod neg;
pub mod pow;
pub mod square;
pub mod square_root;
pub mod sub;
pub mod ternary;
#[cfg(test)]
use console::{TestRng, Uniform};
#[cfg(test)]
use snarkvm_circuit_environment::{assert_count, assert_output_mode, assert_scope, count, output_mode};
use snarkvm_circuit_environment::prelude::*;
use snarkvm_circuit_types_boolean::Boolean;
#[derive(Clone)]
pub struct Field<E: Environment> {
linear_combination: LinearCombination<E::BaseField>,
bits_le: OnceCell<Vec<Boolean<E>>>,
}
impl<E: Environment> FieldTrait for Field<E> {}
impl<E: Environment> Default for Field<E> {
fn default() -> Self {
Self::zero()
}
}
#[cfg(feature = "console")]
impl<E: Environment> Inject for Field<E> {
type Primitive = console::Field<E::Network>;
fn new(mode: Mode, field: Self::Primitive) -> Self {
Self { linear_combination: E::new_variable(mode, *field).into(), bits_le: Default::default() }
}
}
#[cfg(feature = "console")]
impl<E: Environment> Eject for Field<E> {
type Primitive = console::Field<E::Network>;
fn eject_mode(&self) -> Mode {
self.linear_combination.mode()
}
fn eject_value(&self) -> Self::Primitive {
console::Field::new(self.linear_combination.value())
}
}
#[cfg(feature = "console")]
impl<E: Environment> Parser for Field<E> {
#[inline]
fn parse(string: &str) -> ParserResult<Self> {
let (string, field) = console::Field::parse(string)?;
let (string, mode) = opt(pair(tag("."), Mode::parse))(string)?;
match mode {
Some((_, mode)) => Ok((string, Field::new(mode, field))),
None => Ok((string, Field::new(Mode::Constant, field))),
}
}
}
#[cfg(feature = "console")]
impl<E: Environment> FromStr for Field<E> {
type Err = Error;
#[inline]
fn from_str(string: &str) -> Result<Self> {
match Self::parse(string) {
Ok((remainder, object)) => {
ensure!(remainder.is_empty(), "Failed to parse string. Found invalid character in: \"{remainder}\"");
Ok(object)
}
Err(error) => bail!("Failed to parse string. {error}"),
}
}
}
#[cfg(feature = "console")]
impl<E: Environment> TypeName for Field<E> {
#[inline]
fn type_name() -> &'static str {
console::Field::<E::Network>::type_name()
}
}
#[cfg(feature = "console")]
impl<E: Environment> Debug for Field<E> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Display::fmt(self, f)
}
}
#[cfg(feature = "console")]
impl<E: Environment> Display for Field<E> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}.{}", self.eject_value(), self.eject_mode())
}
}
impl<E: Environment> From<LinearCombination<E::BaseField>> for Field<E> {
fn from(linear_combination: LinearCombination<E::BaseField>) -> Self {
Self { linear_combination, bits_le: Default::default() }
}
}
impl<E: Environment> From<&LinearCombination<E::BaseField>> for Field<E> {
fn from(linear_combination: &LinearCombination<E::BaseField>) -> Self {
From::from(linear_combination.clone())
}
}
impl<E: Environment> From<Field<E>> for LinearCombination<E::BaseField> {
fn from(field: Field<E>) -> Self {
From::from(&field)
}
}
impl<E: Environment> From<&Field<E>> for LinearCombination<E::BaseField> {
fn from(field: &Field<E>) -> Self {
field.linear_combination.clone()
}
}
#[cfg(test)]
mod tests {
use super::*;
use snarkvm_circuit_environment::Circuit;
const ITERATIONS: u64 = 10_000;
fn check_display(mode: Mode, element: console::Field<<Circuit as Environment>::Network>) -> Result<()> {
let candidate = Field::<Circuit>::new(mode, element);
assert_eq!(format!("{element}.{mode}"), format!("{candidate}"));
let candidate_recovered = Field::<Circuit>::from_str(&format!("{candidate}"))?;
assert_eq!(candidate.eject_value(), candidate_recovered.eject_value());
Ok(())
}
#[test]
fn test_display() -> Result<()> {
let mut rng = TestRng::default();
for _ in 0..ITERATIONS {
let element = Uniform::rand(&mut rng);
check_display(Mode::Constant, element)?;
check_display(Mode::Public, element)?;
check_display(Mode::Private, element)?;
}
Ok(())
}
#[test]
fn test_display_zero() {
let zero = console::Field::<<Circuit as Environment>::Network>::zero();
let candidate = Field::<Circuit>::new(Mode::Constant, zero);
assert_eq!("0field.constant", &format!("{candidate}"));
let candidate = Field::<Circuit>::new(Mode::Public, zero);
assert_eq!("0field.public", &format!("{candidate}"));
let candidate = Field::<Circuit>::new(Mode::Private, zero);
assert_eq!("0field.private", &format!("{candidate}"));
}
#[test]
fn test_display_one() {
let one = console::Field::<<Circuit as Environment>::Network>::one();
let candidate = Field::<Circuit>::new(Mode::Constant, one);
assert_eq!("1field.constant", &format!("{candidate}"));
let candidate = Field::<Circuit>::new(Mode::Public, one);
assert_eq!("1field.public", &format!("{candidate}"));
let candidate = Field::<Circuit>::new(Mode::Private, one);
assert_eq!("1field.private", &format!("{candidate}"));
}
#[test]
fn test_display_two() {
let one = console::Field::<<Circuit as Environment>::Network>::one();
let two = one + one;
let candidate = Field::<Circuit>::new(Mode::Constant, two);
assert_eq!("2field.constant", &format!("{candidate}"));
let candidate = Field::<Circuit>::new(Mode::Public, two);
assert_eq!("2field.public", &format!("{candidate}"));
let candidate = Field::<Circuit>::new(Mode::Private, two);
assert_eq!("2field.private", &format!("{candidate}"));
}
#[test]
fn test_parser() {
type Primitive = console::Field<<Circuit as Environment>::Network>;
let (_, candidate) = Field::<Circuit>::parse("5field").unwrap();
assert_eq!(Primitive::from_str("5field").unwrap(), candidate.eject_value());
assert!(candidate.is_constant());
let (_, candidate) = Field::<Circuit>::parse("5_field").unwrap();
assert_eq!(Primitive::from_str("5field").unwrap(), candidate.eject_value());
assert!(candidate.is_constant());
let (_, candidate) = Field::<Circuit>::parse("1_5_field").unwrap();
assert_eq!(Primitive::from_str("15field").unwrap(), candidate.eject_value());
assert!(candidate.is_constant());
let (_, candidate) = Field::<Circuit>::parse("5field.constant").unwrap();
assert_eq!(Primitive::from_str("5field").unwrap(), candidate.eject_value());
assert!(candidate.is_constant());
let (_, candidate) = Field::<Circuit>::parse("5_field.constant").unwrap();
assert_eq!(Primitive::from_str("5field").unwrap(), candidate.eject_value());
assert!(candidate.is_constant());
let (_, candidate) = Field::<Circuit>::parse("1_5_field.constant").unwrap();
assert_eq!(Primitive::from_str("15field").unwrap(), candidate.eject_value());
assert!(candidate.is_constant());
let (_, candidate) = Field::<Circuit>::parse("5field.public").unwrap();
assert_eq!(Primitive::from_str("5field").unwrap(), candidate.eject_value());
assert!(candidate.is_public());
let (_, candidate) = Field::<Circuit>::parse("5_field.public").unwrap();
assert_eq!(Primitive::from_str("5field").unwrap(), candidate.eject_value());
assert!(candidate.is_public());
let (_, candidate) = Field::<Circuit>::parse("1_5_field.public").unwrap();
assert_eq!(Primitive::from_str("15field").unwrap(), candidate.eject_value());
assert!(candidate.is_public());
let (_, candidate) = Field::<Circuit>::parse("5field.private").unwrap();
assert_eq!(Primitive::from_str("5field").unwrap(), candidate.eject_value());
assert!(candidate.is_private());
let (_, candidate) = Field::<Circuit>::parse("5_field.private").unwrap();
assert_eq!(Primitive::from_str("5field").unwrap(), candidate.eject_value());
assert!(candidate.is_private());
let (_, candidate) = Field::<Circuit>::parse("1_5_field.private").unwrap();
assert_eq!(Primitive::from_str("15field").unwrap(), candidate.eject_value());
assert!(candidate.is_private());
let mut rng = TestRng::default();
for mode in [Mode::Constant, Mode::Public, Mode::Private] {
for _ in 0..ITERATIONS {
let value = Uniform::rand(&mut rng);
let expected = Field::<Circuit>::new(mode, value);
let (_, candidate) = Field::<Circuit>::parse(&format!("{expected}")).unwrap();
assert_eq!(expected.eject_value(), candidate.eject_value());
assert_eq!(mode, candidate.eject_mode());
}
}
}
}