From c4c9a48ce522e3b2357616870da8c4a1a5eff31b Mon Sep 17 00:00:00 2001 From: "konrad.stepniak" Date: Fri, 11 Oct 2024 11:51:54 +0300 Subject: [PATCH 1/7] make it #[no_std] comptabile --- Cargo.toml | 14 ++++++++------ src/column_tree_builder.rs | 2 +- src/error.rs | 12 ++++++++---- src/hash_type.rs | 11 +++++++---- src/lib.rs | 20 +++++++++++++++----- src/matrix.rs | 7 ++++--- src/mds.rs | 14 +++++++++----- src/poseidon.rs | 11 +++++++---- src/poseidon_alt.rs | 1 + src/preprocessing.rs | 3 ++- src/round_constants.rs | 3 ++- src/round_numbers.rs | 8 ++++---- src/tree_builder.rs | 2 +- 13 files changed, 69 insertions(+), 39 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 78614839..fd9ffc6b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,17 +9,17 @@ repository = "https://github.com/argumentcomputer/neptune" rust-version = "1.71.0" [dependencies] -bellpepper = { workspace = true } -bellpepper-core = { workspace = true } +bellpepper = { workspace = true, optional = true } +bellpepper-core = { workspace = true, optional = true } blake2s_simd = { workspace = true } blstrs = { workspace = true, optional = true } -byteorder = { workspace = true } ec-gpu = { workspace = true, optional = true } ec-gpu-gen = { workspace = true, optional = true } -ff ={ workspace = true } +libm = { workspace = true } +ff = { workspace = true } generic-array = { workspace = true } pasta_curves = { workspace = true, features = ["serde"] } -serde = { version = "1.0", features = ["derive"] } +serde = { version = "1.0", features = ["derive"], optional = true } trait-set = "0.3.0" abomonation = { version = "0.7.3", optional = true } abomonation_derive = { version = "0.1.0", package = "abomonation_derive_ng", optional = true } @@ -57,7 +57,7 @@ incremental = false codegen-units = 1 [features] -default = ["bls", "pasta"] +default = ["std", "bls", "pasta"] cuda = ["ec-gpu-gen/cuda", "ec-gpu"] opencl = ["ec-gpu-gen/opencl", "ec-gpu"] # The supported arities for Poseidon running on the GPU are specified at compile-time. @@ -74,6 +74,7 @@ strengthened = [] bls = ["blstrs/gpu"] pasta = ["pasta_curves/gpu"] portable = ["blstrs/portable"] +std = ["dep:serde", "dep:bellpepper", "dep:bellpepper-core"] # Unsafe Abomonation-based serialization abomonation = ["dep:abomonation", "dep:abomonation_derive"] @@ -90,6 +91,7 @@ bellpepper = { version = "0.4.0", default-features = false } blake2s_simd = "1.0.1" blstrs = { version = "0.7.0" } ff = "0.13.0" +libm = "0.2.8" generic-array = "1.0" pasta_curves = { version = "0.5" } ec-gpu = { version = "0.2.0" } diff --git a/src/column_tree_builder.rs b/src/column_tree_builder.rs index 60b8f49f..359985f5 100644 --- a/src/column_tree_builder.rs +++ b/src/column_tree_builder.rs @@ -49,7 +49,7 @@ where let end = start + column_count; if end > self.leaf_count { - return Err(Error::Other("too many columns".to_string())); + return Err(Error::Other("too many columns")); } match self.column_batcher { diff --git a/src/error.rs b/src/error.rs index f71bb7da..93063e1c 100644 --- a/src/error.rs +++ b/src/error.rs @@ -1,4 +1,5 @@ -use std::{error, fmt}; +use core::fmt; + #[derive(Debug, Clone)] #[cfg(any(feature = "cuda", feature = "opencl"))] @@ -47,10 +48,11 @@ pub enum Error { FullBuffer, /// Attempt to reference an index element that is out of bounds IndexOutOfBounds, + #[cfg(any(feature = "cuda", feature = "opencl"))] GpuError(String), #[cfg(any(feature = "cuda", feature = "opencl"))] ClError(ClError), - Other(String), + Other(&'static str), } #[cfg(any(feature = "cuda", feature = "opencl"))] @@ -67,9 +69,10 @@ impl From for Error { } } -impl error::Error for Error {} +#[cfg(feature = "std")] +impl std::error::Error for Error {} -impl fmt::Display for Error { +impl core::fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { match self { Error::FullBuffer => write!( @@ -77,6 +80,7 @@ impl fmt::Display for Error { "The size of the buffer cannot be greater than the hash arity." ), Error::IndexOutOfBounds => write!(f, "The referenced index is outs of bounds."), + #[cfg(any(feature = "cuda", feature = "opencl"))] Error::GpuError(s) => write!(f, "GPU Error: {s}"), #[cfg(any(feature = "cuda", feature = "opencl"))] Error::ClError(e) => write!(f, "OpenCL Error: {e}"), diff --git a/src/hash_type.rs b/src/hash_type.rs index 0aca94ee..c2daa234 100644 --- a/src/hash_type.rs +++ b/src/hash_type.rs @@ -16,11 +16,13 @@ use abomonation::Abomonation; #[cfg(feature = "abomonation")] use abomonation_derive::Abomonation; use ff::PrimeField; +#[cfg(feature = "std")] use serde::{Deserialize, Serialize}; -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Eq)] +#[cfg_attr(feature = "std", derive(Serialize, Deserialize))] +#[cfg_attr(feature = "std", serde(bound(serialize = "F: Serialize", deserialize = "F: Deserialize<'de>")))] #[cfg_attr(feature = "abomonation", derive(Abomonation))] -#[serde(bound(serialize = "F: Serialize", deserialize = "F: Deserialize<'de>"))] #[cfg_attr(feature = "abomonation", abomonation_omit_bounds)] pub enum HashType> { MerkleTree, @@ -73,7 +75,8 @@ impl> HashType { } } -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Eq)] +#[cfg_attr(feature = "std", derive(Serialize, Deserialize))] #[cfg_attr(feature = "abomonation", derive(Abomonation))] #[cfg_attr(feature = "abomonation", abomonation_omit_bounds)] pub enum CType> { @@ -82,7 +85,7 @@ pub enum CType> { // This is a bit of a hack, but since `serde(skip)` tags the last variant arm, // the generated code ends up being correct. But, in the future, do not // carelessly add new variants to this enum. - #[serde(skip)] + #[cfg_attr(feature = "std", serde(skip))] #[cfg_attr(feature = "abomonation", abomonation_skip)] _Phantom((F, A)), } diff --git a/src/lib.rs b/src/lib.rs index 63b6da08..630e9516 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,6 +1,10 @@ +#![cfg_attr(not(feature = "std"), no_std)] #![allow(dead_code)] #![allow(unused_imports)] +extern crate alloc; +pub use alloc::vec::Vec; + pub use crate::poseidon::{Arity, Poseidon}; use crate::round_constants::generate_constants; use crate::round_numbers::{round_numbers_base, round_numbers_strengthened}; @@ -11,8 +15,8 @@ use blstrs::Scalar as Fr; pub use error::Error; use ff::PrimeField; use generic_array::GenericArray; +#[cfg(feature = "std")] use serde::{Deserialize, Serialize}; -use std::fmt; use trait_set::trait_set; // See https://www.lurklurk.org/effective-rust/re-export.html @@ -45,8 +49,11 @@ compile_error!("The `strengthened` feature needs the `cuda` and/or `opencl` feat compile_error!("The `cuda` and `opencl` features need the `bls` and/or `pasta` feature to be set"); /// Poseidon circuit +#[cfg(feature = "std")] pub mod circuit; +#[cfg(feature = "std")] pub mod circuit2; +#[cfg(feature = "std")] pub mod circuit2_witness; pub mod error; mod matrix; @@ -60,6 +67,7 @@ mod round_constants; mod round_numbers; /// Sponge +#[cfg(any(test, feature = "std"))] pub mod sponge; /// Hash types and domain separation tags. @@ -97,21 +105,23 @@ trait_set! { pub trait NeptuneField = PrimeField + ec_gpu::GpuName; } +#[cfg(feature = "std")] mod serde_impl; pub(crate) const TEST_SEED: [u8; 16] = [ 0x59, 0x62, 0xbe, 0x5d, 0x76, 0x3d, 0x31, 0x8d, 0x17, 0xdb, 0x37, 0x32, 0x54, 0x06, 0xbc, 0xe5, ]; -#[derive(Copy, Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +#[cfg_attr(feature = "std", derive(Serialize, Deserialize))] #[cfg_attr(feature = "abomonation", derive(Abomonation))] pub enum Strength { Standard, Strengthened, } -impl fmt::Display for Strength { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { +impl core::fmt::Display for Strength { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { match self { Self::Standard => write!(f, "standard"), Self::Strengthened => write!(f, "strengthened"), @@ -183,7 +193,7 @@ fn round_constants(arity: usize, strength: &Strength) -> Vec { let fr_num_bits = F::NUM_BITS; let field_size = { - assert!(fr_num_bits <= u32::from(std::u16::MAX)); + assert!(fr_num_bits <= u32::from(core::u16::MAX)); // It's safe to convert to u16 for compatibility with other types. fr_num_bits as u16 }; diff --git a/src/matrix.rs b/src/matrix.rs index 37ff8cfc..11836e36 100644 --- a/src/matrix.rs +++ b/src/matrix.rs @@ -2,6 +2,7 @@ #![allow(clippy::ptr_arg)] use ff::PrimeField; +use crate::Vec; /// Matrix functions here are, at least for now, quick and dirty — intended only to support precomputation of poseidon optimization. @@ -116,7 +117,7 @@ pub(crate) fn left_apply_matrix(m: &Matrix, v: &[F]) -> Vec "Matrix can only be applied to vector of same size." ); - let mut result = vec![F::ZERO; v.len()]; + let mut result = alloc::vec![F::ZERO; v.len()]; for (result, row) in result.iter_mut().zip(m.iter()) { for (mat_val, vec_val) in row.iter().zip(v) { @@ -137,7 +138,7 @@ pub(crate) fn apply_matrix(m: &Matrix, v: &[F]) -> Vec { "Matrix can only be applied to vector of same size." ); - let mut result = vec![F::ZERO; v.len()]; + let mut result = alloc::vec![F::ZERO; v.len()]; for (j, val) in result.iter_mut().enumerate() { for (i, row) in m.iter().enumerate() { let mut tmp = row[j]; @@ -165,7 +166,7 @@ pub(crate) fn transpose(matrix: &Matrix) -> Matrix { #[allow(clippy::needless_range_loop)] pub(crate) fn make_identity(size: usize) -> Matrix { - let mut result = vec![vec![F::ZERO; size]; size]; + let mut result = alloc::vec![alloc::vec![F::ZERO; size]; size]; for i in 0..size { result[i][i] = F::ONE; } diff --git a/src/mds.rs b/src/mds.rs index fbbdb5d2..c456bdec 100644 --- a/src/mds.rs +++ b/src/mds.rs @@ -6,6 +6,7 @@ use abomonation::Abomonation; #[cfg(feature = "abomonation")] use abomonation_derive::Abomonation; use ff::PrimeField; +#[cfg(feature = "std")] use serde::{Deserialize, Serialize}; use crate::matrix; @@ -13,8 +14,10 @@ use crate::matrix::{ apply_matrix, invert, is_identity, is_invertible, is_square, left_apply_matrix, mat_mul, minor, transpose, Matrix, }; +use crate::Vec; -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Eq)] +#[cfg_attr(feature = "std", derive(Serialize, Deserialize))] #[cfg_attr(feature = "abomonation", derive(Abomonation))] #[cfg_attr(feature = "abomonation", abomonation_bounds(where F::Repr: Abomonation))] pub struct MdsMatrices { @@ -58,7 +61,8 @@ pub(crate) fn derive_mds_matrices(m: Matrix) -> MdsMatrices /// This means its first row and column are each dense, and the interior matrix /// (minor to the element in both the row and column) is the identity. /// We will pluralize this compact structure `sparse_matrixes` to distinguish from `sparse_matrices` from which they are created. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "std", derive(Serialize, Deserialize))] #[cfg_attr(feature = "abomonation", derive(Abomonation))] #[cfg_attr(feature = "abomonation", abomonation_bounds(where F::Repr: Abomonation))] pub struct SparseMatrix { @@ -174,12 +178,12 @@ fn make_prime(m: &Matrix) -> Matrix { .enumerate() .map(|(i, row)| match i { 0 => { - let mut new_row = vec![F::ZERO; row.len()]; + let mut new_row = alloc::vec![F::ZERO; row.len()]; new_row[0] = F::ONE; new_row } _ => { - let mut new_row = vec![F::ZERO; row.len()]; + let mut new_row = alloc::vec![F::ZERO; row.len()]; new_row[1..].copy_from_slice(&row[1..]); new_row } @@ -201,7 +205,7 @@ fn make_double_prime(m: &Matrix, m_hat_inv: &Matrix) -> Mat new_row } _ => { - let mut new_row = vec![F::ZERO; row.len()]; + let mut new_row = alloc::vec![F::ZERO; row.len()]; new_row[0] = w_hat[i - 1]; new_row[i] = F::ONE; new_row diff --git a/src/poseidon.rs b/src/poseidon.rs index 035e3263..25c135c2 100644 --- a/src/poseidon.rs +++ b/src/poseidon.rs @@ -14,10 +14,12 @@ use abomonation::Abomonation; use abomonation_derive::Abomonation; use ff::PrimeField; use generic_array::{sequence::GenericSequence, typenum, ArrayLength, GenericArray}; +#[cfg(feature = "std")] use serde::{Deserialize, Serialize}; -use std::marker::PhantomData; +use core::marker::PhantomData; use typenum::marker_traits::Unsigned; use typenum::*; +use crate::Vec; /// Available arities for the Poseidon hasher. pub trait Arity: ArrayLength { @@ -868,12 +870,12 @@ where } } - let _ = std::mem::replace(&mut self.elements, result); + let _ = core::mem::replace(&mut self.elements, result); } pub(crate) fn product_mds_with_matrix_left(&mut self, matrix: &Matrix) { let result = left_apply_matrix(matrix, &self.elements); - let _ = std::mem::replace( + let _ = core::mem::replace( &mut self.elements, GenericArray::::generate(|i| result[i]), ); @@ -900,9 +902,10 @@ where val.add_assign(&tmp); } - let _ = std::mem::replace(&mut self.elements, result); + let _ = core::mem::replace(&mut self.elements, result); } + #[cfg(feature = "std")] pub(crate) fn debug(&self, msg: &str) { dbg!(msg, &self.constants_offset, &self.elements); } diff --git a/src/poseidon_alt.rs b/src/poseidon_alt.rs index fcb1083a..00e6c9ec 100644 --- a/src/poseidon_alt.rs +++ b/src/poseidon_alt.rs @@ -4,6 +4,7 @@ use crate::poseidon::{Arity, Poseidon}; use crate::{matrix, quintic_s_box}; use ff::PrimeField; +use crate::Vec; //////////////////////////////////////////////////////////////////////////////// /// Correct diff --git a/src/preprocessing.rs b/src/preprocessing.rs index b4b3830f..fad07313 100644 --- a/src/preprocessing.rs +++ b/src/preprocessing.rs @@ -1,6 +1,7 @@ use crate::matrix::{apply_matrix, left_apply_matrix, vec_add}; use crate::mds::MdsMatrices; use crate::quintic_s_box; +use crate::Vec; use ff::PrimeField; // - Compress constants by pushing them back through linear layers and through the identity components of partial layers. @@ -108,7 +109,7 @@ pub(crate) fn compress_round_constants( //////////////////////////////////////////////////////////////////////////////// // Shared between branches, arbitrary initial state representing the output of a previous round's S-Box layer. // X - let initial_state = vec![F::ONE; width]; + let initial_state = alloc::vec![F::ONE; width]; //////////////////////////////////////////////////////////////////////////////// // Compute one step with the given (unpreprocessed) constants. diff --git a/src/round_constants.rs b/src/round_constants.rs index 0007767f..61e7e61c 100644 --- a/src/round_constants.rs +++ b/src/round_constants.rs @@ -1,4 +1,5 @@ use ff::PrimeField; +use crate::Vec; /// From the paper (): /// The round constants are generated using the Grain LFSR [23] in a self-shrinking @@ -38,7 +39,7 @@ pub(crate) fn generate_constants( if n_bytes != 32 { unimplemented!("neptune currently supports 32-byte fields exclusively"); } - assert_eq!((f32::from(field_size) / 8.0).ceil() as usize, n_bytes); + assert_eq!(field_size.div_ceil(8) as usize, n_bytes); let num_constants = (r_f + r_p) * t; let mut init_sequence: Vec = Vec::new(); diff --git a/src/round_numbers.rs b/src/round_numbers.rs index 5defec35..cce45426 100644 --- a/src/round_numbers.rs +++ b/src/round_numbers.rs @@ -37,7 +37,7 @@ pub(crate) fn round_numbers_strengthened(arity: usize) -> (usize, usize) { let (full_round, partial_rounds) = round_numbers_base(arity); // Increase by 25%, rounding up. - let strengthened_partial_rounds = f64::ceil(partial_rounds as f64 * 1.25) as usize; + let strengthened_partial_rounds = libm::ceil(partial_rounds as f64 * 1.25) as usize; (full_round, strengthened_partial_rounds) } @@ -55,7 +55,7 @@ pub(crate) fn calc_round_numbers(t: usize, security_margin: bool) -> (usize, usi if round_numbers_are_secure(t, rf_test, rp_test) { if security_margin { rf_test += 2; - rp_test = (1.075 * rp_test as f32).ceil() as usize; + rp_test = libm::ceilf(1.075 * rp_test as f32) as usize; } let n_sboxes = n_sboxes(t, rf_test, rp_test); if n_sboxes < n_sboxes_min || (n_sboxes == n_sboxes_min && rf_test < rf) { @@ -79,12 +79,12 @@ fn round_numbers_are_secure(t: usize, rf: usize, rp: usize) -> bool { } else { 10.0 }; - let rf_interp = 0.43 * m + t.log2() - rp; + let rf_interp = 0.43 * m + libm::log2f(t) - rp; let rf_grob_1 = 0.21 * n - rp; let rf_grob_2 = (0.14 * n - 1.0 - rp) / (t - 1.0); let rf_max = [rf_stat, rf_interp, rf_grob_1, rf_grob_2] .iter() - .map(|rf| rf.ceil() as usize) + .map(|rf| libm::ceilf(*rf) as usize) .max() .unwrap(); rf >= rf_max diff --git a/src/tree_builder.rs b/src/tree_builder.rs index 6024fa6d..0c070f8c 100644 --- a/src/tree_builder.rs +++ b/src/tree_builder.rs @@ -41,7 +41,7 @@ where let end = start + batch_leaf_count; if end > self.leaf_count { - return Err(Error::Other("too many leaves".to_string())); + return Err(Error::Other("too many leaves")); } self.data[start..end].copy_from_slice(leaves); From e80378c0ef7f4c661f80175343b259512d72dabe Mon Sep 17 00:00:00 2001 From: "konrad.stepniak" Date: Mon, 14 Oct 2024 16:40:08 +0200 Subject: [PATCH 2/7] chore: bump rust to 1.78, msrv to 1.73 and use cargo clippy --- Cargo.toml | 4 ++-- rust-toolchain.toml | 2 +- src/error.rs | 1 - src/hash_type.rs | 5 ++++- src/lib.rs | 2 +- src/matrix.rs | 2 +- src/poseidon.rs | 4 ++-- src/poseidon_alt.rs | 2 +- src/round_constants.rs | 2 +- 9 files changed, 13 insertions(+), 11 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index fd9ffc6b..465e50bc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,12 +1,12 @@ [package] name = "neptune" description = "Poseidon hashing over BLS12-381 for Filecoin." -version = "13.0.0" +version = "14.0.0" authors = ["porcuquine "] edition = "2021" license = "MIT OR Apache-2.0" repository = "https://github.com/argumentcomputer/neptune" -rust-version = "1.71.0" +rust-version = "1.73.0" [dependencies] bellpepper = { workspace = true, optional = true } diff --git a/rust-toolchain.toml b/rust-toolchain.toml index 30d2b8f4..85950331 100644 --- a/rust-toolchain.toml +++ b/rust-toolchain.toml @@ -1,4 +1,4 @@ [toolchain] # The default profile includes rustc, rust-std, cargo, rust-docs, rustfmt and clippy. profile = "default" -channel = "1.76" +channel = "1.78" diff --git a/src/error.rs b/src/error.rs index 93063e1c..34d5ae20 100644 --- a/src/error.rs +++ b/src/error.rs @@ -1,6 +1,5 @@ use core::fmt; - #[derive(Debug, Clone)] #[cfg(any(feature = "cuda", feature = "opencl"))] pub enum ClError { diff --git a/src/hash_type.rs b/src/hash_type.rs index c2daa234..55c7aba1 100644 --- a/src/hash_type.rs +++ b/src/hash_type.rs @@ -21,7 +21,10 @@ use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, PartialEq, Eq)] #[cfg_attr(feature = "std", derive(Serialize, Deserialize))] -#[cfg_attr(feature = "std", serde(bound(serialize = "F: Serialize", deserialize = "F: Deserialize<'de>")))] +#[cfg_attr( + feature = "std", + serde(bound(serialize = "F: Serialize", deserialize = "F: Deserialize<'de>")) +)] #[cfg_attr(feature = "abomonation", derive(Abomonation))] #[cfg_attr(feature = "abomonation", abomonation_omit_bounds)] pub enum HashType> { diff --git a/src/lib.rs b/src/lib.rs index 630e9516..9ccf2910 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -3,7 +3,7 @@ #![allow(unused_imports)] extern crate alloc; -pub use alloc::vec::Vec; +pub use alloc::vec::Vec; pub use crate::poseidon::{Arity, Poseidon}; use crate::round_constants::generate_constants; diff --git a/src/matrix.rs b/src/matrix.rs index 11836e36..ba4fcdef 100644 --- a/src/matrix.rs +++ b/src/matrix.rs @@ -1,8 +1,8 @@ // Allow `&Matrix` in function signatures. #![allow(clippy::ptr_arg)] -use ff::PrimeField; use crate::Vec; +use ff::PrimeField; /// Matrix functions here are, at least for now, quick and dirty — intended only to support precomputation of poseidon optimization. diff --git a/src/poseidon.rs b/src/poseidon.rs index 25c135c2..7a52807a 100644 --- a/src/poseidon.rs +++ b/src/poseidon.rs @@ -6,20 +6,20 @@ use crate::mds::{ }; use crate::poseidon_alt::{hash_correct, hash_optimized_dynamic}; use crate::preprocessing::compress_round_constants; +use crate::Vec; use crate::{matrix, quintic_s_box, BatchHasher, Strength, DEFAULT_STRENGTH}; use crate::{round_constants, round_numbers, Error}; #[cfg(feature = "abomonation")] use abomonation::Abomonation; #[cfg(feature = "abomonation")] use abomonation_derive::Abomonation; +use core::marker::PhantomData; use ff::PrimeField; use generic_array::{sequence::GenericSequence, typenum, ArrayLength, GenericArray}; #[cfg(feature = "std")] use serde::{Deserialize, Serialize}; -use core::marker::PhantomData; use typenum::marker_traits::Unsigned; use typenum::*; -use crate::Vec; /// Available arities for the Poseidon hasher. pub trait Arity: ArrayLength { diff --git a/src/poseidon_alt.rs b/src/poseidon_alt.rs index 00e6c9ec..1f9665cd 100644 --- a/src/poseidon_alt.rs +++ b/src/poseidon_alt.rs @@ -2,9 +2,9 @@ //! These are tested (in `poseidon::test`) to be equivalent to the 'static optimized' version //! used for actual hashing by the neptune library. use crate::poseidon::{Arity, Poseidon}; +use crate::Vec; use crate::{matrix, quintic_s_box}; use ff::PrimeField; -use crate::Vec; //////////////////////////////////////////////////////////////////////////////// /// Correct diff --git a/src/round_constants.rs b/src/round_constants.rs index 61e7e61c..1d955cba 100644 --- a/src/round_constants.rs +++ b/src/round_constants.rs @@ -1,5 +1,5 @@ -use ff::PrimeField; use crate::Vec; +use ff::PrimeField; /// From the paper (): /// The round constants are generated using the Grain LFSR [23] in a self-shrinking From 3fd86f3f385f72bd8ba9249068cf85763c4cc493 Mon Sep 17 00:00:00 2001 From: "konrad.stepniak" Date: Tue, 15 Oct 2024 10:14:39 +0200 Subject: [PATCH 3/7] fix: use std when its possible for floats --- src/round_numbers.rs | 30 +++++++++++++++++++++++++++--- 1 file changed, 27 insertions(+), 3 deletions(-) diff --git a/src/round_numbers.rs b/src/round_numbers.rs index cce45426..ce0e1475 100644 --- a/src/round_numbers.rs +++ b/src/round_numbers.rs @@ -25,6 +25,30 @@ pub(crate) fn round_numbers_base(arity: usize) -> (usize, usize) { calc_round_numbers(t, true) } +#[inline(always)] +fn ceil_f32(x: f32) -> f32 { + #[cfg(feature = "std")] + return f32::ceil(x); + #[cfg(not(feature = "std"))] + return libm::ceil(x); +} + +#[inline(always)] +fn ceil_f64(x: f64) -> f64 { + #[cfg(feature = "std")] + return f64::ceil(x); + #[cfg(not(feature = "std"))] + return libm::ceil(x); +} + +#[inline(always)] +fn log2_f32(x: f32) -> f32 { + #[cfg(feature = "std")] + return f32::log2(x); + #[cfg(not(feature = "std"))] + return libm::log2f(x); +} + // In case of newly-discovered attacks, we may need stronger security. // This option exists so we can preemptively create circuits in order to switch // to them quickly if needed. @@ -37,7 +61,7 @@ pub(crate) fn round_numbers_strengthened(arity: usize) -> (usize, usize) { let (full_round, partial_rounds) = round_numbers_base(arity); // Increase by 25%, rounding up. - let strengthened_partial_rounds = libm::ceil(partial_rounds as f64 * 1.25) as usize; + let strengthened_partial_rounds = ceil_f64(partial_rounds as f64 * 1.25) as usize; (full_round, strengthened_partial_rounds) } @@ -55,7 +79,7 @@ pub(crate) fn calc_round_numbers(t: usize, security_margin: bool) -> (usize, usi if round_numbers_are_secure(t, rf_test, rp_test) { if security_margin { rf_test += 2; - rp_test = libm::ceilf(1.075 * rp_test as f32) as usize; + rp_test = ceil_f32(1.075 * rp_test as f32) as usize; } let n_sboxes = n_sboxes(t, rf_test, rp_test); if n_sboxes < n_sboxes_min || (n_sboxes == n_sboxes_min && rf_test < rf) { @@ -79,7 +103,7 @@ fn round_numbers_are_secure(t: usize, rf: usize, rp: usize) -> bool { } else { 10.0 }; - let rf_interp = 0.43 * m + libm::log2f(t) - rp; + let rf_interp = 0.43 * m + log2_f32(t) - rp; let rf_grob_1 = 0.21 * n - rp; let rf_grob_2 = (0.14 * n - 1.0 - rp) / (t - 1.0); let rf_max = [rf_stat, rf_interp, rf_grob_1, rf_grob_2] From 03fc7c0a23a69cc04bbef8b070797fcd56185d3d Mon Sep 17 00:00:00 2001 From: "konrad.stepniak" Date: Tue, 15 Oct 2024 10:44:23 +0200 Subject: [PATCH 4/7] fix: CI --- .github/workflows/rust.yml | 4 ++-- src/round_numbers.rs | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index a5590f0a..dfb1c41b 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -112,7 +112,7 @@ jobs: - run: nvcc --version - name: CUDA tests run: | - cargo nextest run --release --no-default-features --features cuda,pasta,bls,arity2,arity4,arity8,arity11,arity16,arity24,arity36 + cargo nextest run --release --no-default-features --features std,cuda,pasta,bls,arity2,arity4,arity8,arity11,arity16,arity24,arity36 # Runs the test suite on a self-hosted GPU machine with CUDA and OpenCL enabled (that is using the OpenCL backend for NVIDIA GPUs) test-opencl: @@ -152,4 +152,4 @@ jobs: - run: clinfo - name: OpenCL tests run: | - cargo nextest run --release --all-features + cargo nextest run --release --no-default-features std,strengthened,abomonation,opencl,pasta,bls,arity2,arity4,arity8,arity11,arity16,arity24,arity36 diff --git a/src/round_numbers.rs b/src/round_numbers.rs index ce0e1475..81c6e25d 100644 --- a/src/round_numbers.rs +++ b/src/round_numbers.rs @@ -30,7 +30,7 @@ fn ceil_f32(x: f32) -> f32 { #[cfg(feature = "std")] return f32::ceil(x); #[cfg(not(feature = "std"))] - return libm::ceil(x); + return libm::ceilf(x); } #[inline(always)] @@ -108,7 +108,7 @@ fn round_numbers_are_secure(t: usize, rf: usize, rp: usize) -> bool { let rf_grob_2 = (0.14 * n - 1.0 - rp) / (t - 1.0); let rf_max = [rf_stat, rf_interp, rf_grob_1, rf_grob_2] .iter() - .map(|rf| libm::ceilf(*rf) as usize) + .map(|rf| ceil_f32(*rf) as usize) .max() .unwrap(); rf >= rf_max From 01e755316eb450fdbe5f9d4a4c10a9d3016a19da Mon Sep 17 00:00:00 2001 From: Konrad Stepniak Date: Tue, 26 Nov 2024 17:43:20 +0100 Subject: [PATCH 5/7] refactor: remove unnecessary qualification --- src/error.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/error.rs b/src/error.rs index 34d5ae20..8d8d9833 100644 --- a/src/error.rs +++ b/src/error.rs @@ -71,7 +71,7 @@ impl From for Error { #[cfg(feature = "std")] impl std::error::Error for Error {} -impl core::fmt::Display for Error { +impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { match self { Error::FullBuffer => write!( From cd992b82e5e82fc8baa8e2e7dab62f520258231a Mon Sep 17 00:00:00 2001 From: Konrad Stepniak Date: Tue, 26 Nov 2024 18:06:57 +0100 Subject: [PATCH 6/7] ci: set features correctly on opencl build --- .github/workflows/rust.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index dfb1c41b..6179857e 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -152,4 +152,4 @@ jobs: - run: clinfo - name: OpenCL tests run: | - cargo nextest run --release --no-default-features std,strengthened,abomonation,opencl,pasta,bls,arity2,arity4,arity8,arity11,arity16,arity24,arity36 + cargo nextest run --release --no-default-features --features std,strengthened,abomonation,opencl,pasta,bls,arity2,arity4,arity8,arity11,arity16,arity24,arity36 From fbca73c94919cf7c16a05ac21ece362dce8337f8 Mon Sep 17 00:00:00 2001 From: Konrad Stepniak Date: Tue, 26 Nov 2024 23:03:46 +0100 Subject: [PATCH 7/7] chore: add Unicode 3.0 to allow licenses --- deny.toml | 1 + 1 file changed, 1 insertion(+) diff --git a/deny.toml b/deny.toml index 22b076c7..fef5c012 100644 --- a/deny.toml +++ b/deny.toml @@ -109,6 +109,7 @@ allow = [ "CC0-1.0", "Apache-2.0", "Unicode-DFS-2016", + "Unicode-3.0", ] # List of explicitly disallowed licenses # See https://spdx.org/licenses/ for list of possible licenses