* Partial move to ff 0.13

It turns out the newly released k256 0.12 isn't on ff 0.13, preventing further
work at this time.

* Update all crates to work on ff 0.13

The provided curves still need to be expanded to fit the new API.

* Finish adding dalek-ff-group ff 0.13 constants

* Correct FieldElement::product definition

Also stops exporting macros.

* Test most new parts of ff 0.13

* Additionally test ff-group-tests with BLS12-381 and the pasta curves

We only tested curves from RustCrypto. Now we test a curve offered by zk-crypto,
the group behind ff/group, and the pasta curves, which is by Zcash (though
Zcash developers are also behind zk-crypto).

* Finish Ed448

Fully specifies all constants, passes all tests in ff-group-tests, and finishes moving to ff-0.13.

* Add RustCrypto/elliptic-curves to allowed git repos

Needed due to k256/p256 incorrectly defining product.

* Finish writing ff 0.13 tests

* Add additional comments to dalek

* Further comments

* Update ethereum-serai to ff 0.13
This commit is contained in:
Luke Parker
2023-03-28 04:38:01 -04:00
committed by GitHub
parent a9f6300e86
commit 79aff5d4c8
59 changed files with 865 additions and 429 deletions

View File

@@ -19,8 +19,8 @@ digest = "0.10"
zeroize = { version = "^1.5", features = ["zeroize_derive"] }
subtle = "^2.4"
ff = { version = "0.12", features = ["bits"] }
group = "0.12"
ff = "0.13"
group = "0.13"
crypto-bigint = "0.5"

View File

@@ -1,4 +1,7 @@
use core::ops::{DerefMut, Add, AddAssign, Sub, SubAssign, Neg, Mul, MulAssign};
use core::{
ops::{DerefMut, Add, AddAssign, Sub, SubAssign, Neg, Mul, MulAssign},
iter::{Sum, Product},
};
use zeroize::Zeroize;
use rand_core::RngCore;
@@ -12,7 +15,7 @@ use crypto_bigint::{Integer, NonZero, Encoding, U256, U512};
use group::ff::{Field, PrimeField, FieldBits, PrimeFieldBits};
use crate::{u8_from_bool, constant_time, math, from_uint};
use crate::{u8_from_bool, constant_time, math_op, math, from_wrapper, from_uint};
// 2^255 - 19
// Uses saturating_sub because checked_sub isn't available at compile time
@@ -107,18 +110,15 @@ impl<'a> Neg for &'a FieldElement {
}
impl Field for FieldElement {
const ZERO: Self = Self(U256::ZERO);
const ONE: Self = Self(U256::ONE);
fn random(mut rng: impl RngCore) -> Self {
let mut bytes = [0; 64];
rng.fill_bytes(&mut bytes);
FieldElement(reduce(U512::from_le_bytes(bytes)))
}
fn zero() -> Self {
Self(U256::ZERO)
}
fn one() -> Self {
Self(U256::ONE)
}
fn square(&self) -> Self {
FieldElement(reduce(self.0.square()))
}
@@ -138,12 +138,68 @@ impl Field for FieldElement {
let candidate = Self::conditional_select(&tv2, &tv1, tv1.square().ct_eq(self));
CtOption::new(candidate, candidate.square().ct_eq(self))
}
fn sqrt_ratio(u: &FieldElement, v: &FieldElement) -> (Choice, FieldElement) {
let i = SQRT_M1;
let u = *u;
let v = *v;
let v3 = v.square() * v;
let v7 = v3.square() * v;
let mut r = (u * v3) * (u * v7).pow(MOD_5_8);
let check = v * r.square();
let correct_sign = check.ct_eq(&u);
let flipped_sign = check.ct_eq(&(-u));
let flipped_sign_i = check.ct_eq(&((-u) * i));
r.conditional_assign(&(r * i), flipped_sign | flipped_sign_i);
let r_is_negative = r.is_odd();
r.conditional_negate(r_is_negative);
(correct_sign | flipped_sign, r)
}
}
impl PrimeField for FieldElement {
type Repr = [u8; 32];
// Big endian representation of the modulus
const MODULUS: &'static str = "7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed";
const NUM_BITS: u32 = 255;
const CAPACITY: u32 = 254;
// 2.invert()
const TWO_INV: Self = FieldElement(U256::from_be_hex(
"3ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7",
));
// This was calculated with the method from the ff crate docs
// SageMath GF(modulus).primitive_element()
const MULTIPLICATIVE_GENERATOR: Self = Self(U256::from_u8(2));
// This was set per the specification in the ff crate docs
// The number of leading zero bits in the little-endian bit representation of (modulus - 1)
const S: u32 = 2;
// This was calculated via the formula from the ff crate docs
// Self::MULTIPLICATIVE_GENERATOR ** ((modulus - 1) >> Self::S)
const ROOT_OF_UNITY: Self = FieldElement(U256::from_be_hex(
"2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0",
));
// Self::ROOT_OF_UNITY.invert()
const ROOT_OF_UNITY_INV: Self = FieldElement(U256::from_be_hex(
"547cdb7fb03e20f4d4b2ff66c2042858d0bce7f952d01b873b11e4d8b5f15f3d",
));
// This was calculated via the formula from the ff crate docs
// Self::MULTIPLICATIVE_GENERATOR ** (2 ** Self::S)
const DELTA: Self = FieldElement(U256::from_be_hex(
"0000000000000000000000000000000000000000000000000000000000000010",
));
fn from_repr(bytes: [u8; 32]) -> CtOption<Self> {
let res = Self(U256::from_le_bytes(bytes));
CtOption::new(res, res.0.ct_lt(&MODULUS))
@@ -152,23 +208,12 @@ impl PrimeField for FieldElement {
self.0.to_le_bytes()
}
// This was set per the specification in the ff crate docs
// The number of leading zero bits in the little-endian bit representation of (modulus - 1)
const S: u32 = 2;
fn is_odd(&self) -> Choice {
self.0.is_odd()
}
fn multiplicative_generator() -> Self {
// This was calculated with the method from the ff crate docs
// SageMath GF(modulus).primitive_element()
2u64.into()
}
fn root_of_unity() -> Self {
// This was calculated via the formula from the ff crate docs
// Self::multiplicative_generator() ** ((modulus - 1) >> Self::S)
FieldElement(U256::from_be_hex(
"2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0",
))
fn from_u128(num: u128) -> Self {
Self::from(num)
}
}
@@ -193,13 +238,13 @@ impl FieldElement {
/// Perform an exponentation.
pub fn pow(&self, other: FieldElement) -> FieldElement {
let mut table = [FieldElement::one(); 16];
let mut table = [FieldElement::ONE; 16];
table[1] = *self;
for i in 2 .. 16 {
table[i] = table[i - 1] * self;
}
let mut res = FieldElement::one();
let mut res = FieldElement::ONE;
let mut bits = 0;
for (i, mut bit) in other.to_le_bits().iter_mut().rev().enumerate() {
bits <<= 1;
@@ -257,6 +302,38 @@ impl FieldElement {
}
}
impl Sum<FieldElement> for FieldElement {
fn sum<I: Iterator<Item = FieldElement>>(iter: I) -> FieldElement {
let mut res = FieldElement::ZERO;
for item in iter {
res += item;
}
res
}
}
impl<'a> Sum<&'a FieldElement> for FieldElement {
fn sum<I: Iterator<Item = &'a FieldElement>>(iter: I) -> FieldElement {
iter.cloned().sum()
}
}
impl Product<FieldElement> for FieldElement {
fn product<I: Iterator<Item = FieldElement>>(iter: I) -> FieldElement {
let mut res = FieldElement::ONE;
for item in iter {
res *= item;
}
res
}
}
impl<'a> Product<&'a FieldElement> for FieldElement {
fn product<I: Iterator<Item = &'a FieldElement>>(iter: I) -> FieldElement {
iter.cloned().product()
}
}
#[test]
fn test_wide_modulus() {
let mut wide = [0; 64];
@@ -275,9 +352,8 @@ fn test_sqrt_m1() {
// 2 ** ((MODULUS - 1) // 4) % MODULUS
assert_eq!(
SQRT_M1,
FieldElement::from(2u8).pow(FieldElement(
(FieldElement::zero() - FieldElement::one()).0.wrapping_div(&U256::from(4u8))
))
FieldElement::from(2u8)
.pow(FieldElement((FieldElement::ZERO - FieldElement::ONE).0.wrapping_div(&U256::from(4u8))))
);
}

View File

@@ -1,11 +1,11 @@
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
#![no_std]
#![no_std] // Prevents writing new code, in what should be a simple wrapper, which requires std
#![doc = include_str!("../README.md")]
use core::{
borrow::Borrow,
ops::{Deref, DerefMut, Add, AddAssign, Sub, SubAssign, Neg, Mul, MulAssign},
iter::{Iterator, Sum},
iter::{Iterator, Sum, Product},
hash::{Hash, Hasher},
};
@@ -30,7 +30,7 @@ use dalek::{
pub use constants::{ED25519_BASEPOINT_TABLE, RISTRETTO_BASEPOINT_TABLE};
use group::{
ff::{Field, PrimeField, FieldBits, PrimeFieldBits},
ff::{Field, PrimeField, FieldBits, PrimeFieldBits, helpers::sqrt_ratio_generic},
Group, GroupEncoding,
prime::PrimeGroup,
};
@@ -90,8 +90,6 @@ macro_rules! deref_borrow {
};
}
#[doc(hidden)]
#[macro_export]
macro_rules! constant_time {
($Value: ident, $Inner: ident) => {
impl ConstantTimeEq for $Value {
@@ -107,9 +105,8 @@ macro_rules! constant_time {
}
};
}
pub(crate) use constant_time;
#[doc(hidden)]
#[macro_export]
macro_rules! math_op {
(
$Value: ident,
@@ -144,9 +141,8 @@ macro_rules! math_op {
}
};
}
pub(crate) use math_op;
#[doc(hidden)]
#[macro_export(local_inner_macros)]
macro_rules! math {
($Value: ident, $Factor: ident, $add: expr, $sub: expr, $mul: expr) => {
math_op!($Value, $Value, Add, add, AddAssign, add_assign, $add);
@@ -154,9 +150,8 @@ macro_rules! math {
math_op!($Value, $Factor, Mul, mul, MulAssign, mul_assign, $mul);
};
}
pub(crate) use math;
#[doc(hidden)]
#[macro_export(local_inner_macros)]
macro_rules! math_neg {
($Value: ident, $Factor: ident, $add: expr, $sub: expr, $mul: expr) => {
math!($Value, $Factor, $add, $sub, $mul);
@@ -170,8 +165,6 @@ macro_rules! math_neg {
};
}
#[doc(hidden)]
#[macro_export]
macro_rules! from_wrapper {
($wrapper: ident, $inner: ident, $uint: ident) => {
impl From<$uint> for $wrapper {
@@ -181,17 +174,18 @@ macro_rules! from_wrapper {
}
};
}
pub(crate) use from_wrapper;
#[doc(hidden)]
#[macro_export(local_inner_macros)]
macro_rules! from_uint {
($wrapper: ident, $inner: ident) => {
from_wrapper!($wrapper, $inner, u8);
from_wrapper!($wrapper, $inner, u16);
from_wrapper!($wrapper, $inner, u32);
from_wrapper!($wrapper, $inner, u64);
from_wrapper!($wrapper, $inner, u128);
};
}
pub(crate) use from_uint;
/// Wrapper around the dalek Scalar type.
#[derive(Clone, Copy, PartialEq, Eq, Default, Debug, Zeroize)]
@@ -207,13 +201,13 @@ const MODULUS: U256 =
impl Scalar {
pub fn pow(&self, other: Scalar) -> Scalar {
let mut table = [Scalar::one(); 16];
let mut table = [Scalar::ONE; 16];
table[1] = *self;
for i in 2 .. 16 {
table[i] = table[i - 1] * self;
}
let mut res = Scalar::one();
let mut res = Scalar::ONE;
let mut bits = 0;
for (i, mut bit) in other.to_le_bits().iter_mut().rev().enumerate() {
bits <<= 1;
@@ -250,18 +244,19 @@ impl Scalar {
}
impl Field for Scalar {
const ZERO: Scalar = Scalar(DScalar::from_bits([0; 32]));
const ONE: Scalar = Scalar(DScalar::from_bits({
let mut bytes = [0; 32];
bytes[0] = 1;
bytes
}));
fn random(mut rng: impl RngCore) -> Self {
let mut r = [0; 64];
rng.fill_bytes(&mut r);
Self(DScalar::from_bytes_mod_order_wide(&r))
}
fn zero() -> Self {
Self(DScalar::zero())
}
fn one() -> Self {
Self(DScalar::one())
}
fn square(&self) -> Self {
*self * self
}
@@ -271,36 +266,77 @@ impl Field for Scalar {
fn invert(&self) -> CtOption<Self> {
CtOption::new(Self(self.0.invert()), !self.is_zero())
}
fn sqrt(&self) -> CtOption<Self> {
let mod_3_8 = MODULUS.saturating_add(&U256::from_u8(3)).wrapping_div(&U256::from_u8(8));
let mod_3_8 = Scalar::from_repr(mod_3_8.to_le_bytes()).unwrap();
let sqrt_m1 = MODULUS.saturating_sub(&U256::from_u8(1)).wrapping_div(&U256::from_u8(4));
let sqrt_m1 = Scalar::one().double().pow(Scalar::from_repr(sqrt_m1.to_le_bytes()).unwrap());
let sqrt_m1 = Scalar::from(2u8).pow(Scalar::from_repr(sqrt_m1.to_le_bytes()).unwrap());
let tv1 = self.pow(mod_3_8);
let tv2 = tv1 * sqrt_m1;
let candidate = Self::conditional_select(&tv2, &tv1, tv1.square().ct_eq(self));
CtOption::new(candidate, candidate.square().ct_eq(self))
}
fn sqrt_ratio(num: &Self, div: &Self) -> (Choice, Self) {
sqrt_ratio_generic(num, div)
}
}
impl PrimeField for Scalar {
type Repr = [u8; 32];
const MODULUS: &'static str = "1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed";
const NUM_BITS: u32 = 253;
const CAPACITY: u32 = 252;
// 2.invert()
const TWO_INV: Scalar = Scalar(DScalar::from_bits([
247, 233, 122, 46, 141, 49, 9, 44, 107, 206, 123, 81, 239, 124, 111, 10, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 8,
]));
// This was calculated with the method from the ff crate docs
// SageMath GF(modulus).primitive_element()
const MULTIPLICATIVE_GENERATOR: Scalar = Scalar(DScalar::from_bits({
let mut bytes = [0; 32];
bytes[0] = 2;
bytes
}));
// This was set per the specification in the ff crate docs
// The number of leading zero bits in the little-endian bit representation of (modulus - 1)
const S: u32 = 2;
// This was calculated via the formula from the ff crate docs
// Self::MULTIPLICATIVE_GENERATOR ** ((modulus - 1) >> Self::S)
const ROOT_OF_UNITY: Scalar = Scalar(DScalar::from_bits([
212, 7, 190, 235, 223, 117, 135, 190, 254, 131, 206, 66, 83, 86, 240, 14, 122, 194, 193, 171,
96, 109, 61, 125, 231, 129, 121, 224, 16, 115, 74, 9,
]));
// Self::ROOT_OF_UNITY.invert()
const ROOT_OF_UNITY_INV: Scalar = Scalar(DScalar::from_bits([
25, 204, 55, 113, 58, 237, 138, 153, 215, 24, 41, 96, 139, 163, 238, 5, 134, 61, 62, 84, 159,
146, 194, 130, 24, 126, 134, 31, 239, 140, 181, 6,
]));
// This was calculated via the formula from the ff crate docs
// Self::MULTIPLICATIVE_GENERATOR ** (2 ** Self::S)
const DELTA: Scalar = Scalar(DScalar::from_bits([
16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
]));
fn from_repr(bytes: [u8; 32]) -> CtOption<Self> {
let scalar = DScalar::from_canonical_bytes(bytes);
// TODO: This unwrap_or isn't constant time, yet we don't exactly have an alternative...
CtOption::new(Scalar(scalar.unwrap_or_else(DScalar::zero)), choice(scalar.is_some()))
// TODO: This unwrap_or_else isn't constant time, yet we don't exactly have an alternative...
CtOption::new(Scalar(scalar.unwrap_or_else(DScalar::zero)), choice(black_box(scalar).is_some()))
}
fn to_repr(&self) -> [u8; 32] {
self.0.to_bytes()
}
// This was set per the specification in the ff crate docs
// The number of leading zero bits in the little-endian bit representation of (modulus - 1)
const S: u32 = 2;
fn is_odd(&self) -> Choice {
// This is probably overkill? Yet it's better safe than sorry since this is a complete
// decomposition of the scalar
@@ -315,19 +351,9 @@ impl PrimeField for Scalar {
}
res
}
fn multiplicative_generator() -> Self {
// This was calculated with the method from the ff crate docs
// SageMath GF(modulus).primitive_element()
2u64.into()
}
fn root_of_unity() -> Self {
// This was calculated via the formula from the ff crate docs
// Self::multiplicative_generator() ** ((modulus - 1) >> Self::S)
Scalar::from_repr([
212, 7, 190, 235, 223, 117, 135, 190, 254, 131, 206, 66, 83, 86, 240, 14, 122, 194, 193, 171,
96, 109, 61, 125, 231, 129, 121, 224, 16, 115, 74, 9,
])
.unwrap()
fn from_u128(num: u128) -> Self {
Self::from(num)
}
}
@@ -339,7 +365,7 @@ impl PrimeFieldBits for Scalar {
}
fn char_le_bits() -> FieldBits<Self::ReprBits> {
let mut bytes = (Scalar::zero() - Scalar::one()).to_repr();
let mut bytes = (Scalar::ZERO - Scalar::ONE).to_repr();
bytes[0] += 1;
debug_assert_eq!(DScalar::from_bytes_mod_order(bytes), DScalar::zero());
bytes.into()
@@ -352,6 +378,24 @@ impl Sum<Scalar> for Scalar {
}
}
impl<'a> Sum<&'a Scalar> for Scalar {
fn sum<I: Iterator<Item = &'a Scalar>>(iter: I) -> Scalar {
Self(DScalar::sum(iter))
}
}
impl Product<Scalar> for Scalar {
fn product<I: Iterator<Item = Scalar>>(iter: I) -> Scalar {
Self(DScalar::product(iter))
}
}
impl<'a> Product<&'a Scalar> for Scalar {
fn product<I: Iterator<Item = &'a Scalar>>(iter: I) -> Scalar {
Self(DScalar::product(iter))
}
}
macro_rules! dalek_group {
(
$Point: ident,
@@ -420,7 +464,10 @@ macro_rules! dalek_group {
let decompressed = $DCompressed(*bytes).decompress();
// TODO: Same note on unwrap_or as above
let point = decompressed.unwrap_or($DPoint::identity());
CtOption::new($Point(point), choice(decompressed.is_some()) & choice($torsion_free(point)))
CtOption::new(
$Point(point),
choice(black_box(decompressed).is_some()) & choice($torsion_free(point)),
)
}
fn from_bytes_unchecked(bytes: &Self::Repr) -> CtOption<Self> {