Skip to content

Commit

Permalink
feat(crypto): add no_std support to crypto
Browse files Browse the repository at this point in the history
  • Loading branch information
tdelabro committed Dec 28, 2023
1 parent f96448c commit 34406e0
Show file tree
Hide file tree
Showing 53 changed files with 186 additions and 88 deletions.
4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@ repository = "https://github.com/lambdaclass/lambdaworks"

[workspace.dependencies]
iai-callgrind = "0.3.1"
lambdaworks-crypto = { path = "./crypto", version = "0.3.0" }
lambdaworks-crypto = { path = "./crypto", version = "0.3.0", default-features = false }
lambdaworks-gpu = { path = "./gpu", version = "0.3.0" }
lambdaworks-math = { path = "./math", version = "0.3.0" }
lambdaworks-math = { path = "./math", version = "0.3.0", default-features = false }
stark-platinum-prover = { path = "./provers/stark", version = "0.3.0" }
cairo-platinum-prover = { path = "./provers/cairo", version = "0.3.0" }

Expand Down
1 change: 1 addition & 0 deletions benches/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ starknet-ff = { git = "https://github.com/xJonathanLEI/starknet-rs" }

[dependencies.lambdaworks-math]
path = "../math"
features = ["std"]

[dev-dependencies]
criterion = { version = "0.5.1", default-features = false }
Expand Down
15 changes: 10 additions & 5 deletions crypto/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,13 @@ license.workspace = true
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
lambdaworks-math.workspace = true
sha3 = "0.10"
sha2 = "0.10"
thiserror = "1.0.38"
serde = { version = "1.0", features = ["derive"] }
lambdaworks-math = { workspace = true, features = ["alloc"] }
sha3 = { version = "0.10", default-features = false }
sha2 = { version = "0.10", default-features = false }
thiserror-no-std = { version = "2.0.2", default-features = false }

# Optional
serde = { version = "1.0", default-features = false, features = ["derive"], optional = true }
rayon = { version = "1.8.0", optional = true }

[dev-dependencies]
Expand All @@ -21,6 +23,9 @@ iai-callgrind.workspace = true
rand = "0.8.5"

[features]
default = ["std"]
std = ["lambdaworks-math/std", "thiserror-no-std/std", "serde?/std", "sha2/std", "sha3/std"]
serde = ["dep:serde", "lambdaworks-math/lambdaworks-serde-binary"]
test_fiat_shamir = []
parallel = ["dep:rayon"]

Expand Down
8 changes: 5 additions & 3 deletions crypto/src/commitments/kzg.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
use crate::errors::SrsFromFileError;
use alloc::borrow::ToOwned;
use alloc::vec::Vec;

use super::traits::IsCommitmentScheme;
use core::{marker::PhantomData, mem};
use lambdaworks_math::{
cyclic_group::IsGroup,
elliptic_curve::traits::IsPairing,
Expand All @@ -11,7 +13,6 @@ use lambdaworks_math::{
traits::{Deserializable, Serializable},
unsigned_integer::element::UnsignedInteger,
};
use std::{marker::PhantomData, mem};

#[derive(PartialEq, Clone, Debug)]
pub struct StructuredReferenceString<G1Point, G2Point> {
Expand All @@ -32,12 +33,13 @@ where
}
}

#[cfg(feature = "std")]
impl<G1Point, G2Point> StructuredReferenceString<G1Point, G2Point>
where
G1Point: IsGroup + Deserializable,
G2Point: IsGroup + Deserializable,
{
pub fn from_file(file_path: &str) -> Result<Self, SrsFromFileError> {
pub fn from_file(file_path: &str) -> Result<Self, crate::errors::SrsFromFileError> {
let bytes = std::fs::read(file_path)?;
Ok(Self::deserialize(&bytes)?)
}
Expand Down
1 change: 1 addition & 0 deletions crypto/src/fiat_shamir/default_transcript.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use super::transcript::Transcript;
use alloc::borrow::ToOwned;
use sha3::{Digest, Keccak256};

pub struct DefaultTranscript {
Expand Down
2 changes: 2 additions & 0 deletions crypto/src/hash/hash_to_field.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use alloc::string::String;
use alloc::{vec, vec::Vec};
use lambdaworks_math::{
field::{
element::FieldElement,
Expand Down
2 changes: 2 additions & 0 deletions crypto/src/hash/poseidon/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use alloc::borrow::ToOwned;
use alloc::{vec, vec::Vec};
use lambdaworks_math::field::element::FieldElement as FE;

pub mod parameters;
Expand Down
2 changes: 2 additions & 0 deletions crypto/src/hash/sha3/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use sha3::{Digest, Sha3_256};

pub struct Sha3Hasher;
Expand Down
6 changes: 6 additions & 0 deletions crypto/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
#![cfg_attr(not(feature = "std"), no_std)]

#[macro_use]
extern crate alloc;

pub mod commitments;
#[cfg(feature = "std")]
pub mod errors;
pub mod fiat_shamir;
pub mod hash;
Expand Down
3 changes: 2 additions & 1 deletion crypto/src/merkle_tree/backends/field_element.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use crate::hash::poseidon::Poseidon;

use crate::merkle_tree::traits::IsMerkleTreeBackend;
use core::marker::PhantomData;
use lambdaworks_math::{
field::{element::FieldElement, traits::IsField},
traits::Serializable,
Expand All @@ -9,7 +10,7 @@ use sha3::{
digest::{generic_array::GenericArray, OutputSizeUser},
Digest,
};
use std::marker::PhantomData;

#[derive(Clone)]
pub struct FieldElementBackend<F, D: Digest, const NUM_BYTES: usize> {
phantom1: PhantomData<F>,
Expand Down
3 changes: 2 additions & 1 deletion crypto/src/merkle_tree/backends/field_element_vector.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use std::marker::PhantomData;
use alloc::vec::Vec;
use core::marker::PhantomData;

use crate::hash::poseidon::Poseidon;
use crate::merkle_tree::traits::IsMerkleTreeBackend;
Expand Down
15 changes: 12 additions & 3 deletions crypto/src/merkle_tree/merkle.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,22 @@
use super::{proof::Proof, traits::IsMerkleTreeBackend, utils::*};
use alloc::{vec, vec::Vec};
use thiserror_no_std::Error;

#[derive(Clone, serde::Serialize, serde::Deserialize)]
#[derive(Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct MerkleTree<B: IsMerkleTreeBackend> {
pub root: B::Node,
nodes: Vec<B::Node>,
}

const ROOT: usize = 0;

#[derive(Debug, Error)]
pub enum Error {
#[error("Accessed node was out of boud")]
OutOfBounds,
}

impl<B> MerkleTree<B>
where
B: IsMerkleTreeBackend,
Expand Down Expand Up @@ -46,14 +55,14 @@ where
Some(Proof { merkle_path })
}

fn build_merkle_path(&self, pos: usize) -> Result<Vec<B::Node>, std::io::Error> {
fn build_merkle_path(&self, pos: usize) -> Result<Vec<B::Node>, Error> {
let mut merkle_path = Vec::new();
let mut pos = pos;

while pos != ROOT {
let Some(node) = self.nodes.get(sibling_index(pos)) else {
// out of bounds, exit returning the current merkle_path
return Err(std::io::Error::from(std::io::ErrorKind::InvalidInput));
return Err(Error::OutOfBounds);
};
merkle_path.push(node.clone());

Expand Down
4 changes: 3 additions & 1 deletion crypto/src/merkle_tree/proof.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use alloc::vec::Vec;
use lambdaworks_math::{
errors::DeserializationError,
traits::{Deserializable, Serializable},
Expand All @@ -10,7 +11,8 @@ use super::traits::IsMerkleTreeBackend;
/// `merkle_path` field, in such a way that, if the merkle tree is of height `n`, the
/// `i`-th element of `merkle_path` is the sibling node in the `n - 1 - i`-th check
/// when verifying.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Proof<T: PartialEq + Eq> {
pub merkle_path: Vec<T>,
}
Expand Down
2 changes: 1 addition & 1 deletion crypto/src/merkle_tree/test_merkle.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::marker::PhantomData;
use core::marker::PhantomData;

use lambdaworks_math::field::{element::FieldElement, traits::IsField};

Expand Down
2 changes: 2 additions & 0 deletions crypto/src/merkle_tree/traits.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use alloc::vec::Vec;

#[cfg(feature = "parallel")]
use rayon::prelude::{IntoParallelRefIterator, ParallelIterator};

Expand Down
1 change: 1 addition & 0 deletions crypto/src/merkle_tree/utils.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use super::traits::IsMerkleTreeBackend;
use alloc::vec::Vec;

pub fn sibling_index(node_index: usize) -> usize {
if node_index % 2 == 0 {
Expand Down
4 changes: 3 additions & 1 deletion ensure-no_std/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ edition = "2021"


[dependencies]
lambdaworks-math = { path = "../math", default-features = false }
wee_alloc = "0.4.5"
lambdaworks-math = { path = "../math", default-features = false, features = ["alloc", "lambdaworks-serde-binary", "lambdaworks-serde-string"] }
lambdaworks-crypto = { path = "../crypto", default-features = false, features = ["serde"] }

[profile.dev]
panic = "abort"
Expand Down
5 changes: 5 additions & 0 deletions ensure-no_std/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,10 @@ fn panic(_info: &PanicInfo) -> ! {
loop {}
}

#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;

#[allow(unused_imports)]
use lambdaworks_crypto;
#[allow(unused_imports)]
use lambdaworks_math;
4 changes: 2 additions & 2 deletions examples/merkle-tree-cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ path = "src/main.rs"

[dependencies]
clap = { version = "4.4.6", features = ["derive"] }
lambdaworks-crypto = { workspace = true }
lambdaworks-math = { workspace = true, features = ["lambdaworks-serde-string"] }
lambdaworks-crypto = { workspace = true, features = ["std"] }
lambdaworks-math = { workspace = true, features = ["std", "lambdaworks-serde-string"] }
serde = { version = "1.0" }
serde_json = "1"
bincode = { version = "2.0.0-rc.2", tag = "v2.0.0-rc.2", git = "https://github.com/bincode-org/bincode.git", features= ['serde'] }
2 changes: 1 addition & 1 deletion fuzz/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ publish = false
version = "0.1.1"

[workspace.dependencies]
lambdaworks-math = { path = "../math" }
lambdaworks-math = { path = "../math", features = ["std"] }
lambdaworks-gpu = { path = "../gpu" }
stark-platinum-prover = { path = "../provers/stark" }
libfuzzer-sys = "0.4"
Expand Down
2 changes: 1 addition & 1 deletion fuzz/cuda_fuzz/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ edition.workspace = true
cargo-fuzz = true

[dependencies]
lambdaworks-math = { workspace = true, features = ["cuda"] }
lambdaworks-math = { workspace = true, features = ["std", "cuda"] }
lambdaworks-gpu = { workspace = true, features = ["cuda"] }
honggfuzz = "0.5.55"

Expand Down
2 changes: 1 addition & 1 deletion fuzz/metal_fuzz/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ edition.workspace = true
cargo-fuzz = true

[dependencies]
lambdaworks-math = { workspace = true, features = ["metal"] }
lambdaworks-math = { workspace = true, features = ["std", "metal"] }
lambdaworks-gpu = { workspace = true, features = ["metal"] }
libfuzzer-sys = { workspace = true }

Expand Down
2 changes: 1 addition & 1 deletion fuzz/no_gpu_fuzz/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ edition.workspace = true
cargo-fuzz = true

[dependencies]
lambdaworks-math = { workspace = true }
lambdaworks-math = { workspace = true, features = ["std"] }
lambdaworks-gpu = { workspace = true }
libfuzzer-sys = { workspace = true }
stark-platinum-prover = { workspace = true }
Expand Down
13 changes: 7 additions & 6 deletions math/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ license.workspace = true
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
thiserror = { version = "1.0", optional = true }
serde = { version = "1.0", features = ["derive"], optional = true }
serde_json = { version = "1.0", optional = true }
thiserror-no-std = { version = "2.0.2", default-features = false }
serde = { version = "1.0", features = ["derive"], default-features = false, optional = true }
serde_json = { version = "1.0", default-features = false, optional = true }
proptest = { version = "1.1.0", optional = true }
winter-math = { package = "winter-math", version = "0.6.4", default-features = false, optional = true }
miden-core = { package = "miden-core" , version = "0.7", default-features = false, optional = true }
Expand Down Expand Up @@ -39,9 +39,10 @@ pprof = { version = "0.13.0", features = ["criterion","flamegraph"] }
[features]
rayon = ["dep:rayon"]
default = ["rayon", "std"]
std = ["dep:thiserror"]
lambdaworks-serde-binary = ["dep:serde", "std"]
lambdaworks-serde-string = ["dep:serde", "dep:serde_json", "std"]
std = ["thiserror-no-std/std", "alloc", "serde?/std", "serde_json?/std"]
alloc = ["serde?/alloc", "serde_json?/alloc"]
lambdaworks-serde-binary = ["dep:serde", "alloc"]
lambdaworks-serde-string = ["dep:serde", "dep:serde_json", "alloc"]
proptest = ["dep:proptest"]
winter_compatibility = ["winter-math", "miden-core"]

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ use crate::field::{
use crate::traits::ByteConversion;
use crate::unsigned_integer::element::U384;

#[cfg(feature = "alloc")]
use alloc::vec::Vec;

pub const BLS12381_PRIME_FIELD_ORDER: U384 = U384::from_hex_unchecked("1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab");

// FPBLS12381
Expand Down Expand Up @@ -143,21 +146,21 @@ impl IsSubFieldOf<Degree2ExtensionField> for BLS12381PrimeField {
[FieldElement::from_raw(a), FieldElement::zero()]
}

#[cfg(feature = "std")]
#[cfg(feature = "alloc")]
fn to_subfield_vec(b: <Degree2ExtensionField as IsField>::BaseType) -> Vec<Self::BaseType> {
b.into_iter().map(|x| x.to_raw()).collect()
}
}

impl ByteConversion for FieldElement<Degree2ExtensionField> {
#[cfg(feature = "std")]
#[cfg(feature = "alloc")]
fn to_bytes_be(&self) -> Vec<u8> {
let mut byte_slice = ByteConversion::to_bytes_be(&self.value()[0]);
byte_slice.extend(ByteConversion::to_bytes_be(&self.value()[1]));
byte_slice
}

#[cfg(feature = "std")]
#[cfg(feature = "alloc")]
fn to_bytes_le(&self) -> Vec<u8> {
let mut byte_slice = ByteConversion::to_bytes_le(&self.value()[0]);
byte_slice.extend(ByteConversion::to_bytes_le(&self.value()[1]));
Expand Down
2 changes: 1 addition & 1 deletion math/src/fft/errors.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::field::errors::FieldError;
use thiserror::Error;
use thiserror_no_std::Error;

#[cfg(feature = "metal")]
use lambdaworks_gpu::metal::abstractions::errors::MetalError;
Expand Down
4 changes: 3 additions & 1 deletion math/src/field/element.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ use crate::traits::ByteConversion;
use crate::unsigned_integer::element::UnsignedInteger;
use crate::unsigned_integer::montgomery::MontgomeryAlgorithms;
use crate::unsigned_integer::traits::IsUnsignedInteger;
#[cfg(feature = "alloc")]
use alloc::vec::Vec;
use core::fmt;
use core::fmt::Debug;
use core::iter::Sum;
Expand Down Expand Up @@ -41,7 +43,7 @@ pub struct FieldElement<F: IsField> {
value: F::BaseType,
}

#[cfg(feature = "std")]
#[cfg(feature = "alloc")]
impl<F: IsField> FieldElement<F> {
// Source: https://en.wikipedia.org/wiki/Modular_multiplicative_inverse#Multiple_inverses
pub fn inplace_batch_inverse(numbers: &mut [Self]) -> Result<(), FieldError> {
Expand Down
Loading

0 comments on commit 34406e0

Please sign in to comment.