use ark_ec::{AffineRepr, CurveGroup}; use ark_ff::PrimeField; use ark_r1cs_std::fields::nonnative::{params::OptimizationType, AllocatedNonNativeFieldVar}; use ark_r1cs_std::{ alloc::{AllocVar, AllocationMode}, fields::{fp::FpVar, nonnative::NonNativeFieldVar}, ToConstraintFieldGadget, }; use ark_relations::r1cs::{Namespace, SynthesisError}; use ark_std::{One, Zero}; use core::borrow::Borrow; /// NonNativeAffineVar represents an elliptic curve point in Affine represenation in the non-native /// field, over the constraint field. It is not intended to perform operations, but just to contain /// the affine coordinates in order to perform hash operations of the point. #[derive(Debug, Clone)] pub struct NonNativeAffineVar { pub x: Vec>, pub y: Vec>, } impl AllocVar for NonNativeAffineVar where C: CurveGroup, ::BaseField: ark_ff::PrimeField, { fn new_variable>( cs: impl Into>, f: impl FnOnce() -> Result, mode: AllocationMode, ) -> Result { f().and_then(|val| { let cs = cs.into(); let affine = val.borrow().into_affine(); let zero_point = (&C::BaseField::zero(), &C::BaseField::one()); let xy = affine.xy().unwrap_or(zero_point); let x = NonNativeFieldVar::::new_variable( cs.clone(), || Ok(xy.0), mode, )? .to_constraint_field()?; let y = NonNativeFieldVar::::new_variable( cs.clone(), || Ok(xy.1), mode, )? .to_constraint_field()?; Ok(Self { x, y }) }) } } /// point_to_nonnative_limbs is used to compute (outside the circuit) the limbs representation of a /// point that matches the one used in-circuit. #[allow(clippy::type_complexity)] pub fn point_to_nonnative_limbs( p: C, ) -> Result<(Vec, Vec), SynthesisError> where ::BaseField: ark_ff::PrimeField, { let affine = p.into_affine(); if affine.is_zero() { let x = AllocatedNonNativeFieldVar::::get_limbs_representations( &C::BaseField::zero(), OptimizationType::Weight, )?; let y = AllocatedNonNativeFieldVar::::get_limbs_representations( &C::BaseField::one(), OptimizationType::Weight, )?; return Ok((x, y)); } let (x, y) = affine.xy().unwrap(); let x = AllocatedNonNativeFieldVar::::get_limbs_representations( x, OptimizationType::Weight, )?; let y = AllocatedNonNativeFieldVar::::get_limbs_representations( y, OptimizationType::Weight, )?; Ok((x, y)) } #[cfg(test)] mod tests { use super::*; use ark_pallas::{Fr, Projective}; use ark_r1cs_std::alloc::AllocVar; use ark_relations::r1cs::ConstraintSystem; use ark_std::Zero; #[test] fn test_alloc_nonnativeaffinevar_zero() { let cs = ConstraintSystem::::new_ref(); // dealing with the 'zero' point should not panic when doing the unwrap let p = Projective::zero(); NonNativeAffineVar::::new_witness(cs.clone(), || Ok(p)).unwrap(); } }