#[cfg(test)]
use fiat_crypto::curve25519_64::fiat_25519_sub;
use fiat_crypto::curve25519_64::{
fiat_25519_add, fiat_25519_carry, fiat_25519_carry_mul, fiat_25519_carry_square,
fiat_25519_from_bytes, fiat_25519_loose_field_element, fiat_25519_opp, fiat_25519_relax,
fiat_25519_selectznz, fiat_25519_tight_field_element, fiat_25519_to_bytes,
};
use subtle::{Choice, ConditionallyNegatable, ConditionallySelectable, ConstantTimeEq};
#[derive(Clone, Copy)]
pub(crate) struct FieldElement(fiat_25519_tight_field_element);
impl core::fmt::Debug for FieldElement {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str("FieldElement(")?;
for byte in self.as_bytes() {
write!(f, "{byte:02x}")?;
}
f.write_str(")")
}
}
impl FieldElement {
pub(crate) const ZERO: Self = Self(fiat_25519_tight_field_element([0, 0, 0, 0, 0]));
pub(crate) const ONE: Self = Self(fiat_25519_tight_field_element([1, 0, 0, 0, 0]));
pub(crate) const MONTGOMERY_A: Self =
Self(fiat_25519_tight_field_element([486_662, 0, 0, 0, 0]));
pub(crate) fn from_bytes(bytes: &[u8; 32]) -> Self {
let mut masked = *bytes;
masked[31] &= 0x7f;
let mut out = fiat_25519_tight_field_element([0; 5]);
fiat_25519_from_bytes(&mut out, &masked);
Self(out)
}
pub(crate) fn as_bytes(&self) -> [u8; 32] {
let mut out = [0u8; 32];
fiat_25519_to_bytes(&mut out, &self.0);
out
}
fn relax(&self) -> fiat_25519_loose_field_element {
let mut out = fiat_25519_loose_field_element([0; 5]);
fiat_25519_relax(&mut out, &self.0);
out
}
fn from_loose(loose: &fiat_25519_loose_field_element) -> Self {
let mut out = fiat_25519_tight_field_element([0; 5]);
fiat_25519_carry(&mut out, loose);
Self(out)
}
pub(crate) fn add(&self, rhs: &Self) -> Self {
let mut out = fiat_25519_loose_field_element([0; 5]);
fiat_25519_add(&mut out, &self.0, &rhs.0);
Self::from_loose(&out)
}
#[cfg(test)]
pub(crate) fn sub(&self, rhs: &Self) -> Self {
let mut out = fiat_25519_loose_field_element([0; 5]);
fiat_25519_sub(&mut out, &self.0, &rhs.0);
Self::from_loose(&out)
}
pub(crate) fn neg(&self) -> Self {
let mut out = fiat_25519_loose_field_element([0; 5]);
fiat_25519_opp(&mut out, &self.0);
Self::from_loose(&out)
}
pub(crate) fn mul(&self, rhs: &Self) -> Self {
let mut out = fiat_25519_tight_field_element([0; 5]);
fiat_25519_carry_mul(&mut out, &self.relax(), &rhs.relax());
Self(out)
}
pub(crate) fn square(&self) -> Self {
let mut out = fiat_25519_tight_field_element([0; 5]);
fiat_25519_carry_square(&mut out, &self.relax());
Self(out)
}
pub(crate) fn square2(&self) -> Self {
let sq = self.square();
sq.add(&sq)
}
pub(crate) fn pow2k(&self, k: u32) -> Self {
let mut acc = *self;
for _ in 0..k {
acc = acc.square();
}
acc
}
fn pow22501(&self) -> (Self, Self) {
let t0 = self.square(); let t1 = t0.square().square(); let t2 = self.mul(&t1); let t3 = t0.mul(&t2); let t4 = t3.square(); let t5 = t2.mul(&t4); let t6 = t5.pow2k(5); let t7 = t6.mul(&t5); let t8 = t7.pow2k(10); let t9 = t8.mul(&t7); let t10 = t9.pow2k(20); let t11 = t10.mul(&t9); let t12 = t11.pow2k(10); let t13 = t12.mul(&t7); let t14 = t13.pow2k(50); let t15 = t14.mul(&t13); let t16 = t15.pow2k(100); let t17 = t16.mul(&t15); let t18 = t17.pow2k(50); let t19 = t18.mul(&t13); (t19, t3)
}
pub(crate) fn pow_p58(&self) -> Self {
let (t19, _) = self.pow22501();
t19.pow2k(2).mul(self)
}
pub(crate) fn invert(&self) -> Self {
let (t19, t3) = self.pow22501();
t19.pow2k(5).mul(&t3)
}
pub(crate) fn is_negative(&self) -> Choice {
Choice::from(self.as_bytes()[0] & 1)
}
pub(crate) fn sqrt_ratio_i(u: &Self, v: &Self) -> (Choice, Self) {
let v3 = v.square().mul(v);
let v7 = v3.square().mul(v);
let mut r = u.mul(&v3).mul(&u.mul(&v7).pow_p58());
let check = v.mul(&r.square());
let i = Self::sqrt_m1();
let neg_u = u.neg();
let correct_sign_sqrt = check.ct_eq(u);
let flipped_sign_sqrt = check.ct_eq(&neg_u);
let flipped_sign_sqrt_i = check.ct_eq(&neg_u.mul(&i));
let r_prime = i.mul(&r);
r.conditional_assign(&r_prime, flipped_sign_sqrt | flipped_sign_sqrt_i);
let r_is_negative = r.is_negative();
r.conditional_negate(r_is_negative);
(correct_sign_sqrt | flipped_sign_sqrt, r)
}
pub(crate) fn sqrt_m1() -> Self {
let two = Self::ONE.add(&Self::ONE);
let (t19, _) = two.pow22501(); t19.pow2k(3).mul(&two.square().mul(&two))
}
pub(crate) fn ct_eq_fe(&self, other: &Self) -> Choice {
self.as_bytes().ct_eq(&other.as_bytes())
}
}
impl ConstantTimeEq for FieldElement {
fn ct_eq(&self, other: &Self) -> Choice {
self.as_bytes().ct_eq(&other.as_bytes())
}
}
impl ConditionallySelectable for FieldElement {
fn conditional_select(a: &Self, b: &Self, choice: Choice) -> Self {
let mut out = [0u64; 5];
fiat_25519_selectznz(&mut out, choice.unwrap_u8(), &a.0.0, &b.0.0);
Self(fiat_25519_tight_field_element(out))
}
}
impl ConditionallyNegatable for FieldElement {
fn conditional_negate(&mut self, choice: Choice) {
let neg = self.neg();
self.conditional_assign(&neg, choice);
}
}
#[cfg(test)]
mod tests {
use super::*;
fn fe(n: u64) -> FieldElement {
let mut b = [0u8; 32];
b[..8].copy_from_slice(&n.to_le_bytes());
FieldElement::from_bytes(&b)
}
#[test]
fn add_sub_round_trip() {
let a = fe(12345);
let b = fe(999);
assert_eq!(a.add(&b).sub(&b).as_bytes(), a.as_bytes());
}
#[test]
fn negation_is_additive_inverse() {
let a = fe(7);
assert_eq!(a.add(&a.neg()).as_bytes(), FieldElement::ZERO.as_bytes());
}
#[test]
fn multiplication_matches_repeated_addition() {
let a = fe(37);
let five = fe(5);
let by_add = a.add(&a).add(&a).add(&a).add(&a);
assert_eq!(a.mul(&five).as_bytes(), by_add.as_bytes());
}
#[test]
fn square_matches_self_multiplication() {
let a = fe(0x1234_5678);
assert_eq!(a.square().as_bytes(), a.mul(&a).as_bytes());
}
#[test]
fn inversion_round_trips() {
for n in 1..50u64 {
let a = fe(n);
assert_eq!(
a.mul(&a.invert()).as_bytes(),
FieldElement::ONE.as_bytes(),
"inversion failed for {n}"
);
}
}
#[test]
fn inverting_zero_yields_zero() {
assert_eq!(
FieldElement::ZERO.invert().as_bytes(),
FieldElement::ZERO.as_bytes()
);
}
#[test]
fn sqrt_m1_squares_to_minus_one() {
let i = FieldElement::sqrt_m1();
assert_eq!(
i.square().as_bytes(),
FieldElement::ONE.neg().as_bytes(),
"sqrt(-1)^2 must be -1"
);
}
#[test]
fn sqrt_ratio_finds_real_roots() {
let (ok, r) = FieldElement::sqrt_ratio_i(&fe(4), &FieldElement::ONE);
assert!(bool::from(ok));
assert_eq!(r.square().as_bytes(), fe(4).as_bytes());
}
#[test]
fn sqrt_ratio_reports_non_squares() {
let mut squares = 0;
let mut non_squares = 0;
for n in 1..80u64 {
let (ok, r) = FieldElement::sqrt_ratio_i(&fe(n), &FieldElement::ONE);
if bool::from(ok) {
squares += 1;
assert_eq!(r.square().as_bytes(), fe(n).as_bytes());
} else {
non_squares += 1;
}
}
assert!(squares > 0 && non_squares > 0, "expected a mix of both");
}
#[test]
fn canonical_roots_are_non_negative() {
for n in 1..40u64 {
let (ok, r) = FieldElement::sqrt_ratio_i(&fe(n), &FieldElement::ONE);
if bool::from(ok) {
assert!(!bool::from(r.is_negative()), "root of {n} was negative");
}
}
}
#[test]
fn conditional_select_picks_the_right_branch() {
let a = fe(11);
let b = fe(22);
assert_eq!(
FieldElement::conditional_select(&a, &b, Choice::from(0)).as_bytes(),
a.as_bytes()
);
assert_eq!(
FieldElement::conditional_select(&a, &b, Choice::from(1)).as_bytes(),
b.as_bytes()
);
}
#[test]
fn high_bit_is_masked_on_decode() {
let mut a = [0u8; 32];
a[0] = 9;
let mut b = a;
b[31] |= 0x80;
assert_eq!(
FieldElement::from_bytes(&a).as_bytes(),
FieldElement::from_bytes(&b).as_bytes()
);
}
}