serai/crypto/dalek-ff-group/src/lib.rs

399 lines
9.7 KiB
Rust
Raw Normal View History

#![no_std]
use core::{
ops::{Deref, Add, AddAssign, Sub, SubAssign, Neg, Mul, MulAssign},
borrow::Borrow,
2022-07-15 05:26:07 +00:00
iter::{Iterator, Sum},
};
Utilize zeroize (#76) * Apply Zeroize to nonces used in Bulletproofs Also makes bit decomposition constant time for a given amount of outputs. * Fix nonce reuse for single-signer CLSAG * Attach Zeroize to most structures in Monero, and ZOnDrop to anything with private data * Zeroize private keys and nonces * Merge prepare_outputs and prepare_transactions * Ensure CLSAG is constant time * Pass by borrow where needed, bug fixes The past few commitments have been one in-progress chunk which I've broken up as best read. * Add Zeroize to FROST structs Still needs to zeroize internally, yet next step. Not quite as aggressive as Monero, partially due to the limitations of HashMaps, partially due to less concern about metadata, yet does still delete a few smaller items of metadata (group key, context string...). * Remove Zeroize from most Monero multisig structs These structs largely didn't have private data, just fields with private data, yet those fields implemented ZeroizeOnDrop making them already covered. While there is still traces of the transaction left in RAM, fully purging that was never the intent. * Use Zeroize within dleq bitvec doesn't offer Zeroize, so a manual zeroing has been implemented. * Use Zeroize for random_nonce It isn't perfect, due to the inability to zeroize the digest, and due to kp256 requiring a few transformations. It does the best it can though. Does move the per-curve random_nonce to a provided one, which is allowed as of https://github.com/cfrg/draft-irtf-cfrg-frost/pull/231. * Use Zeroize on FROST keygen/signing * Zeroize constant time multiexp. * Correct when FROST keygen zeroizes * Move the FROST keys Arc into FrostKeys Reduces amount of instances in memory. * Manually implement Debug for FrostCore to not leak the secret share * Misc bug fixes * clippy + multiexp test bug fixes * Correct FROST key gen share summation It leaked our own share for ourself. * Fix cross-group DLEq tests
2022-08-03 08:25:18 +00:00
use zeroize::Zeroize;
2022-07-10 20:48:08 +00:00
use subtle::{ConstantTimeEq, ConditionallySelectable};
use rand_core::RngCore;
use digest::{consts::U64, Digest};
2022-07-10 20:48:08 +00:00
use subtle::{Choice, CtOption};
pub use curve25519_dalek as dalek;
use dalek::{
constants,
2022-06-03 19:35:42 +00:00
traits::Identity,
scalar::Scalar as DScalar,
edwards::{
2022-07-15 05:26:07 +00:00
EdwardsPoint as DEdwardsPoint, EdwardsBasepointTable as DEdwardsBasepointTable,
CompressedEdwardsY as DCompressedEdwards,
},
ristretto::{
2022-07-15 05:26:07 +00:00
RistrettoPoint as DRistrettoPoint, RistrettoBasepointTable as DRistrettoBasepointTable,
CompressedRistretto as DCompressedRistretto,
},
};
use ff::{Field, PrimeField, FieldBits, PrimeFieldBits};
use group::{Group, GroupEncoding, prime::PrimeGroup};
pub mod field;
// Convert a boolean to a Choice in a *presumably* constant time manner
fn choice(value: bool) -> Choice {
2022-09-17 08:35:08 +00:00
Choice::from(u8::from(value))
}
macro_rules! deref_borrow {
($Source: ident, $Target: ident) => {
impl Deref for $Source {
type Target = $Target;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl Borrow<$Target> for $Source {
fn borrow(&self) -> &$Target {
&self.0
}
}
impl Borrow<$Target> for &$Source {
fn borrow(&self) -> &$Target {
&self.0
}
}
2022-07-15 05:26:07 +00:00
};
}
2022-07-10 20:48:08 +00:00
#[doc(hidden)]
#[macro_export]
macro_rules! constant_time {
($Value: ident, $Inner: ident) => {
impl ConstantTimeEq for $Value {
2022-07-15 05:26:07 +00:00
fn ct_eq(&self, other: &Self) -> Choice {
self.0.ct_eq(&other.0)
}
}
2022-07-10 20:48:08 +00:00
impl ConditionallySelectable for $Value {
fn conditional_select(a: &Self, b: &Self, choice: Choice) -> Self {
$Value($Inner::conditional_select(&a.0, &b.0, choice))
}
}
2022-07-15 05:26:07 +00:00
};
2022-07-10 20:48:08 +00:00
}
2022-07-10 20:48:08 +00:00
#[doc(hidden)]
#[macro_export]
macro_rules! math_op {
(
$Value: ident,
$Other: ident,
$Op: ident,
$op_fn: ident,
$Assign: ident,
$assign_fn: ident,
$function: expr
) => {
impl $Op<$Other> for $Value {
type Output = $Value;
fn $op_fn(self, other: $Other) -> Self::Output {
Self($function(self.0, other.0))
}
}
2022-07-10 20:48:08 +00:00
impl $Assign<$Other> for $Value {
fn $assign_fn(&mut self, other: $Other) {
self.0 = $function(self.0, other.0);
}
}
2022-07-10 20:48:08 +00:00
impl<'a> $Op<&'a $Other> for $Value {
type Output = $Value;
fn $op_fn(self, other: &'a $Other) -> Self::Output {
Self($function(self.0, other.0))
}
}
2022-07-10 20:48:08 +00:00
impl<'a> $Assign<&'a $Other> for $Value {
fn $assign_fn(&mut self, other: &'a $Other) {
self.0 = $function(self.0, other.0);
}
}
2022-07-15 05:26:07 +00:00
};
2022-07-10 20:48:08 +00:00
}
2022-07-10 20:48:08 +00:00
#[doc(hidden)]
FROST Ed448 (#107) * Theoretical ed448 impl * Fixes * Basic tests * More efficient scalarmul Precomputes a table to minimize additions required. * Add a torsion test * Split into a constant and variable time backend The variable time one is still far too slow, at 53s for the tests (~5s a scalarmul). It should be usable as a PoC though. * Rename unsafe Ed448 It's not only unworthy of the Serai branding and deserves more clarity in the name. * Add wide reduction to ed448 * Add Zeroize to Ed448 * Rename Ed448 group.rs to point.rs * Minor lint to FROST * Ed448 ciphersuite with 8032 test vector * Macro out the backend fields * Slight efficiency improvement to point decompression * Disable the multiexp test in FROST for Ed448 * fmt + clippy ed448 * Fix an infinite loop in the constant time ed448 backend * Add b"chal" to the 8032 context string for Ed448 Successfully tests against proposed vectors for the FROST IETF draft. * Fix fmt and clippy * Use a tabled pow algorithm in ed448's const backend * Slight tweaks to variable time backend Stop from_repr(MODULUS) from passing. * Use extended points Almost two orders of magnitude faster. * Efficient ed448 doubling * Remove the variable time backend With the recent performance improvements, the constant time backend is now 4x faster than the variable time backend was. While the variable time backend remains much faster, and the constant time backend is still slow compared to other libraries, it's sufficiently performant now. The FROST test, which runs a series of multiexps over the curve, does take 218.26s while Ristretto takes 1 and secp256k1 takes 4.57s. While 50x slower than secp256k1 is horrible, it's ~1.5 orders of magntiude, which is close enough to the desire stated in https://github.com/serai-dex/serai/issues/108 to meet it. Largely makes this library safe to use. * Correct constants in ed448 * Rename unsafe-ed448 to minimal-ed448 Enables all FROST tests against it. * No longer require the hazmat feature to use ed448 * Remove extraneous as_refs
2022-08-29 07:32:59 +00:00
#[macro_export(local_inner_macros)]
2022-07-10 20:48:08 +00:00
macro_rules! math {
($Value: ident, $Factor: ident, $add: expr, $sub: expr, $mul: expr) => {
math_op!($Value, $Value, Add, add, AddAssign, add_assign, $add);
math_op!($Value, $Value, Sub, sub, SubAssign, sub_assign, $sub);
math_op!($Value, $Factor, Mul, mul, MulAssign, mul_assign, $mul);
2022-07-15 05:26:07 +00:00
};
2022-07-10 20:48:08 +00:00
}
FROST Ed448 (#107) * Theoretical ed448 impl * Fixes * Basic tests * More efficient scalarmul Precomputes a table to minimize additions required. * Add a torsion test * Split into a constant and variable time backend The variable time one is still far too slow, at 53s for the tests (~5s a scalarmul). It should be usable as a PoC though. * Rename unsafe Ed448 It's not only unworthy of the Serai branding and deserves more clarity in the name. * Add wide reduction to ed448 * Add Zeroize to Ed448 * Rename Ed448 group.rs to point.rs * Minor lint to FROST * Ed448 ciphersuite with 8032 test vector * Macro out the backend fields * Slight efficiency improvement to point decompression * Disable the multiexp test in FROST for Ed448 * fmt + clippy ed448 * Fix an infinite loop in the constant time ed448 backend * Add b"chal" to the 8032 context string for Ed448 Successfully tests against proposed vectors for the FROST IETF draft. * Fix fmt and clippy * Use a tabled pow algorithm in ed448's const backend * Slight tweaks to variable time backend Stop from_repr(MODULUS) from passing. * Use extended points Almost two orders of magnitude faster. * Efficient ed448 doubling * Remove the variable time backend With the recent performance improvements, the constant time backend is now 4x faster than the variable time backend was. While the variable time backend remains much faster, and the constant time backend is still slow compared to other libraries, it's sufficiently performant now. The FROST test, which runs a series of multiexps over the curve, does take 218.26s while Ristretto takes 1 and secp256k1 takes 4.57s. While 50x slower than secp256k1 is horrible, it's ~1.5 orders of magntiude, which is close enough to the desire stated in https://github.com/serai-dex/serai/issues/108 to meet it. Largely makes this library safe to use. * Correct constants in ed448 * Rename unsafe-ed448 to minimal-ed448 Enables all FROST tests against it. * No longer require the hazmat feature to use ed448 * Remove extraneous as_refs
2022-08-29 07:32:59 +00:00
#[doc(hidden)]
#[macro_export(local_inner_macros)]
2022-07-10 20:48:08 +00:00
macro_rules! math_neg {
($Value: ident, $Factor: ident, $add: expr, $sub: expr, $mul: expr) => {
math!($Value, $Factor, $add, $sub, $mul);
2022-07-10 20:48:08 +00:00
impl Neg for $Value {
type Output = Self;
2022-07-15 05:26:07 +00:00
fn neg(self) -> Self::Output {
Self(-self.0)
}
}
2022-07-15 05:26:07 +00:00
};
}
#[doc(hidden)]
#[macro_export]
macro_rules! from_wrapper {
($wrapper: ident, $inner: ident, $uint: ident) => {
impl From<$uint> for $wrapper {
2022-07-15 05:26:07 +00:00
fn from(a: $uint) -> $wrapper {
Self($inner::from(a))
}
}
2022-07-15 05:26:07 +00:00
};
}
#[doc(hidden)]
FROST Ed448 (#107) * Theoretical ed448 impl * Fixes * Basic tests * More efficient scalarmul Precomputes a table to minimize additions required. * Add a torsion test * Split into a constant and variable time backend The variable time one is still far too slow, at 53s for the tests (~5s a scalarmul). It should be usable as a PoC though. * Rename unsafe Ed448 It's not only unworthy of the Serai branding and deserves more clarity in the name. * Add wide reduction to ed448 * Add Zeroize to Ed448 * Rename Ed448 group.rs to point.rs * Minor lint to FROST * Ed448 ciphersuite with 8032 test vector * Macro out the backend fields * Slight efficiency improvement to point decompression * Disable the multiexp test in FROST for Ed448 * fmt + clippy ed448 * Fix an infinite loop in the constant time ed448 backend * Add b"chal" to the 8032 context string for Ed448 Successfully tests against proposed vectors for the FROST IETF draft. * Fix fmt and clippy * Use a tabled pow algorithm in ed448's const backend * Slight tweaks to variable time backend Stop from_repr(MODULUS) from passing. * Use extended points Almost two orders of magnitude faster. * Efficient ed448 doubling * Remove the variable time backend With the recent performance improvements, the constant time backend is now 4x faster than the variable time backend was. While the variable time backend remains much faster, and the constant time backend is still slow compared to other libraries, it's sufficiently performant now. The FROST test, which runs a series of multiexps over the curve, does take 218.26s while Ristretto takes 1 and secp256k1 takes 4.57s. While 50x slower than secp256k1 is horrible, it's ~1.5 orders of magntiude, which is close enough to the desire stated in https://github.com/serai-dex/serai/issues/108 to meet it. Largely makes this library safe to use. * Correct constants in ed448 * Rename unsafe-ed448 to minimal-ed448 Enables all FROST tests against it. * No longer require the hazmat feature to use ed448 * Remove extraneous as_refs
2022-08-29 07:32:59 +00:00
#[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);
2022-07-15 05:26:07 +00:00
};
}
/// Wrapper around the dalek Scalar type
Utilize zeroize (#76) * Apply Zeroize to nonces used in Bulletproofs Also makes bit decomposition constant time for a given amount of outputs. * Fix nonce reuse for single-signer CLSAG * Attach Zeroize to most structures in Monero, and ZOnDrop to anything with private data * Zeroize private keys and nonces * Merge prepare_outputs and prepare_transactions * Ensure CLSAG is constant time * Pass by borrow where needed, bug fixes The past few commitments have been one in-progress chunk which I've broken up as best read. * Add Zeroize to FROST structs Still needs to zeroize internally, yet next step. Not quite as aggressive as Monero, partially due to the limitations of HashMaps, partially due to less concern about metadata, yet does still delete a few smaller items of metadata (group key, context string...). * Remove Zeroize from most Monero multisig structs These structs largely didn't have private data, just fields with private data, yet those fields implemented ZeroizeOnDrop making them already covered. While there is still traces of the transaction left in RAM, fully purging that was never the intent. * Use Zeroize within dleq bitvec doesn't offer Zeroize, so a manual zeroing has been implemented. * Use Zeroize for random_nonce It isn't perfect, due to the inability to zeroize the digest, and due to kp256 requiring a few transformations. It does the best it can though. Does move the per-curve random_nonce to a provided one, which is allowed as of https://github.com/cfrg/draft-irtf-cfrg-frost/pull/231. * Use Zeroize on FROST keygen/signing * Zeroize constant time multiexp. * Correct when FROST keygen zeroizes * Move the FROST keys Arc into FrostKeys Reduces amount of instances in memory. * Manually implement Debug for FrostCore to not leak the secret share * Misc bug fixes * clippy + multiexp test bug fixes * Correct FROST key gen share summation It leaked our own share for ourself. * Fix cross-group DLEq tests
2022-08-03 08:25:18 +00:00
#[derive(Clone, Copy, PartialEq, Eq, Default, Debug, Zeroize)]
pub struct Scalar(pub DScalar);
deref_borrow!(Scalar, DScalar);
2022-07-10 20:48:08 +00:00
constant_time!(Scalar, DScalar);
math_neg!(Scalar, Scalar, DScalar::add, DScalar::sub, DScalar::mul);
from_uint!(Scalar, DScalar);
impl Scalar {
/// Perform wide reduction on a 64-byte array to create a Scalar without bias
pub fn from_bytes_mod_order_wide(bytes: &[u8; 64]) -> Scalar {
Self(DScalar::from_bytes_mod_order_wide(bytes))
}
/// Derive a Scalar without bias from a digest via wide reduction
pub fn from_hash<D: Digest<OutputSize = U64>>(hash: D) -> Scalar {
let mut output = [0u8; 64];
output.copy_from_slice(&hash.finalize());
let res = Scalar(DScalar::from_bytes_mod_order_wide(&output));
output.zeroize();
res
}
}
impl Field for Scalar {
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))
}
2022-07-15 05:26:07 +00:00
fn zero() -> Self {
Self(DScalar::zero())
}
fn one() -> Self {
Self(DScalar::one())
}
fn square(&self) -> Self {
*self * self
}
fn double(&self) -> Self {
*self + self
}
fn invert(&self) -> CtOption<Self> {
2022-07-08 20:05:17 +00:00
CtOption::new(Self(self.0.invert()), !self.is_zero())
}
2022-07-15 05:26:07 +00:00
fn sqrt(&self) -> CtOption<Self> {
unimplemented!()
}
fn is_zero(&self) -> Choice {
self.0.ct_eq(&DScalar::zero())
}
fn cube(&self) -> Self {
*self * self * self
}
fn pow_vartime<S: AsRef<[u64]>>(&self, _exp: S) -> Self {
unimplemented!()
}
}
impl PrimeField for Scalar {
type Repr = [u8; 32];
const NUM_BITS: u32 = 253;
const CAPACITY: u32 = 252;
fn from_repr(bytes: [u8; 32]) -> CtOption<Self> {
let scalar = DScalar::from_canonical_bytes(bytes);
// TODO: This unwrap_or isn't constant time, yet do we have an alternative?
CtOption::new(Scalar(scalar.unwrap_or_else(DScalar::zero)), choice(scalar.is_some()))
}
2022-07-15 05:26:07 +00:00
fn to_repr(&self) -> [u8; 32] {
self.0.to_bytes()
}
2022-06-03 19:35:42 +00:00
const S: u32 = 2;
2022-07-15 05:26:07 +00:00
fn is_odd(&self) -> Choice {
2022-08-31 05:05:30 +00:00
choice(self.to_le_bits()[0])
2022-07-15 05:26:07 +00:00
}
fn multiplicative_generator() -> Self {
2u64.into()
}
fn root_of_unity() -> Self {
unimplemented!()
}
}
impl PrimeFieldBits for Scalar {
type ReprBits = [u8; 32];
fn to_le_bits(&self) -> FieldBits<Self::ReprBits> {
self.to_repr().into()
}
fn char_le_bits() -> FieldBits<Self::ReprBits> {
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()
}
}
impl Sum<Scalar> for Scalar {
fn sum<I: Iterator<Item = Scalar>>(iter: I) -> Scalar {
Self(DScalar::sum(iter))
}
}
macro_rules! dalek_group {
(
$Point: ident,
$DPoint: ident,
$torsion_free: expr,
$Table: ident,
$DTable: ident,
$DCompressed: ident,
$BASEPOINT_POINT: ident,
$BASEPOINT_TABLE: ident
) => {
/// Wrapper around the dalek Point type. For Ed25519, this is restricted to the prime subgroup
Utilize zeroize (#76) * Apply Zeroize to nonces used in Bulletproofs Also makes bit decomposition constant time for a given amount of outputs. * Fix nonce reuse for single-signer CLSAG * Attach Zeroize to most structures in Monero, and ZOnDrop to anything with private data * Zeroize private keys and nonces * Merge prepare_outputs and prepare_transactions * Ensure CLSAG is constant time * Pass by borrow where needed, bug fixes The past few commitments have been one in-progress chunk which I've broken up as best read. * Add Zeroize to FROST structs Still needs to zeroize internally, yet next step. Not quite as aggressive as Monero, partially due to the limitations of HashMaps, partially due to less concern about metadata, yet does still delete a few smaller items of metadata (group key, context string...). * Remove Zeroize from most Monero multisig structs These structs largely didn't have private data, just fields with private data, yet those fields implemented ZeroizeOnDrop making them already covered. While there is still traces of the transaction left in RAM, fully purging that was never the intent. * Use Zeroize within dleq bitvec doesn't offer Zeroize, so a manual zeroing has been implemented. * Use Zeroize for random_nonce It isn't perfect, due to the inability to zeroize the digest, and due to kp256 requiring a few transformations. It does the best it can though. Does move the per-curve random_nonce to a provided one, which is allowed as of https://github.com/cfrg/draft-irtf-cfrg-frost/pull/231. * Use Zeroize on FROST keygen/signing * Zeroize constant time multiexp. * Correct when FROST keygen zeroizes * Move the FROST keys Arc into FrostKeys Reduces amount of instances in memory. * Manually implement Debug for FrostCore to not leak the secret share * Misc bug fixes * clippy + multiexp test bug fixes * Correct FROST key gen share summation It leaked our own share for ourself. * Fix cross-group DLEq tests
2022-08-03 08:25:18 +00:00
#[derive(Clone, Copy, PartialEq, Eq, Debug, Zeroize)]
pub struct $Point(pub $DPoint);
deref_borrow!($Point, $DPoint);
2022-07-10 20:48:08 +00:00
constant_time!($Point, $DPoint);
math_neg!($Point, Scalar, $DPoint::add, $DPoint::sub, $DPoint::mul);
pub const $BASEPOINT_POINT: $Point = $Point(constants::$BASEPOINT_POINT);
impl Sum<$Point> for $Point {
2022-07-15 05:26:07 +00:00
fn sum<I: Iterator<Item = $Point>>(iter: I) -> $Point {
Self($DPoint::sum(iter))
}
}
impl<'a> Sum<&'a $Point> for $Point {
2022-07-15 05:26:07 +00:00
fn sum<I: Iterator<Item = &'a $Point>>(iter: I) -> $Point {
Self($DPoint::sum(iter))
}
}
impl Group for $Point {
type Scalar = Scalar;
fn random(mut rng: impl RngCore) -> Self {
loop {
let mut bytes = field::FieldElement::random(&mut rng).to_repr();
bytes[31] |= u8::try_from(rng.next_u32() % 2).unwrap() << 7;
let opt = Self::from_bytes(&bytes);
if opt.is_some().into() {
return opt.unwrap();
}
}
2022-07-15 05:26:07 +00:00
}
fn identity() -> Self {
Self($DPoint::identity())
}
fn generator() -> Self {
$BASEPOINT_POINT
}
fn is_identity(&self) -> Choice {
self.0.ct_eq(&$DPoint::identity())
}
fn double(&self) -> Self {
*self + self
}
}
impl GroupEncoding for $Point {
type Repr = [u8; 32];
fn from_bytes(bytes: &Self::Repr) -> CtOption<Self> {
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)))
}
fn from_bytes_unchecked(bytes: &Self::Repr) -> CtOption<Self> {
$Point::from_bytes(bytes)
}
fn to_bytes(&self) -> Self::Repr {
self.0.compress().to_bytes()
}
}
impl PrimeGroup for $Point {}
/// Wrapper around the dalek Table type, offering efficient multiplication against the
/// basepoint
pub struct $Table(pub $DTable);
deref_borrow!($Table, $DTable);
pub const $BASEPOINT_TABLE: $Table = $Table(constants::$BASEPOINT_TABLE);
impl Mul<Scalar> for &$Table {
type Output = $Point;
2022-07-15 05:26:07 +00:00
fn mul(self, b: Scalar) -> $Point {
$Point(&b.0 * &self.0)
}
}
};
}
dalek_group!(
EdwardsPoint,
DEdwardsPoint,
|point: DEdwardsPoint| point.is_torsion_free(),
EdwardsBasepointTable,
DEdwardsBasepointTable,
DCompressedEdwards,
ED25519_BASEPOINT_POINT,
ED25519_BASEPOINT_TABLE
);
impl EdwardsPoint {
pub fn mul_by_cofactor(&self) -> EdwardsPoint {
EdwardsPoint(self.0.mul_by_cofactor())
}
}
dalek_group!(
RistrettoPoint,
DRistrettoPoint,
|_| true,
RistrettoBasepointTable,
DRistrettoBasepointTable,
DCompressedRistretto,
RISTRETTO_BASEPOINT_POINT,
RISTRETTO_BASEPOINT_TABLE
);