Skip to content

Commit

Permalink
Serialization options (#660)
Browse files Browse the repository at this point in the history
* initial commit

* change serde_cbor for serde_bare

* bincode de/ser

* remove comparison

* fmt

* restore flag

* fix failing test

* add std feature flag

* conditional  use

* rmv conditional use

* replace std for core

* add cond import

* rmv debug print

* initial commit

* rmv unused import

* rplc todo w unimplemented

* rename features

* fmt

* clippy

* change feature flags

* features fixes

* keep only string on merkle cli

* rmv test files

* fix wrong path

* fix lint

* rmv unused dep
  • Loading branch information
juan518munoz authored Nov 7, 2023
1 parent a4b28b1 commit 24c84ab
Show file tree
Hide file tree
Showing 8 changed files with 114 additions and 17 deletions.
3 changes: 2 additions & 1 deletion examples/merkle-tree-cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ path = "src/main.rs"
[dependencies]
clap = { version = "4.4.6", features = ["derive"] }
lambdaworks-crypto = { workspace = true }
lambdaworks-math = { workspace = true, features = ["lambdaworks-serde"] }
lambdaworks-math = { workspace = true, features = ["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'] }
7 changes: 4 additions & 3 deletions examples/merkle-tree-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,10 @@ use lambdaworks_math::{
elliptic_curve::short_weierstrass::curves::bls12_381::field_extension::BLS12381PrimeField,
field::element::FieldElement,
};
use std::io::BufWriter;
use std::{
fs::{self, File},
io::{self, BufWriter, Write},
io::{self, Write},
};

type FE = FieldElement<BLS12381PrimeField>;
Expand Down Expand Up @@ -66,11 +67,11 @@ fn verify_merkle_proof(
) -> Result<(), io::Error> {
let root_hash: FE = load_fe_from_file(&root_path)?;

let leaf: FE = load_fe_from_file(&leaf_path)?;

let file_str = fs::read_to_string(proof_path)?;
let proof: Proof<FE> = serde_json::from_str(&file_str)?;

let leaf: FE = load_fe_from_file(&leaf_path)?;

match proof.verify::<Poseidon<BLS12381PrimeField>>(&root_hash, index, &leaf) {
true => println!("\x1b[32mMerkle proof verified succesfully\x1b[0m"),
false => println!("\x1b[31mMerkle proof failed verifying\x1b[0m"),
Expand Down
3 changes: 2 additions & 1 deletion math/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@ pprof = { version = "0.13.0", features = ["criterion","flamegraph"] }
rayon = ["dep:rayon"]
default = ["rayon", "std"]
std = ["dep:thiserror"]
lambdaworks-serde = ["dep:serde", "dep:serde_json", "std"]
lambdaworks-serde-binary = ["dep:serde", "std"]
lambdaworks-serde-string = ["dep:serde", "dep:serde_json", "std"]
proptest = ["dep:proptest"]

# gpu
Expand Down
105 changes: 98 additions & 7 deletions math/src/field/element.rs
Original file line number Diff line number Diff line change
@@ -1,22 +1,34 @@
use crate::errors::CreationError;
use crate::field::errors::FieldError;
use crate::field::traits::IsField;
#[cfg(feature = "lambdaworks-serde")]
#[cfg(feature = "lambdaworks-serde-binary")]
use crate::traits::ByteConversion;
use crate::unsigned_integer::element::UnsignedInteger;
use crate::unsigned_integer::montgomery::MontgomeryAlgorithms;
use crate::unsigned_integer::traits::IsUnsignedInteger;
use core::fmt;
use core::fmt::Debug;
use core::iter::Sum;
#[cfg(feature = "lambdaworks-serde")]
#[cfg(any(
feature = "lambdaworks-serde-binary",
feature = "lambdaworks-serde-string"
))]
use core::marker::PhantomData;
use core::ops::{Add, AddAssign, Div, Mul, Neg, Sub};
#[cfg(feature = "lambdaworks-serde")]
#[cfg(any(
feature = "lambdaworks-serde-binary",
feature = "lambdaworks-serde-string"
))]
use serde::de::{self, Deserializer, MapAccess, SeqAccess, Visitor};
#[cfg(feature = "lambdaworks-serde")]
#[cfg(any(
feature = "lambdaworks-serde-binary",
feature = "lambdaworks-serde-string"
))]
use serde::ser::{Serialize, SerializeStruct, Serializer};
#[cfg(feature = "lambdaworks-serde")]
#[cfg(any(
feature = "lambdaworks-serde-binary",
feature = "lambdaworks-serde-string"
))]
use serde::Deserialize;

use super::fields::montgomery_backed_prime_fields::{IsModulus, MontgomeryBackendPrimeField};
Expand Down Expand Up @@ -437,7 +449,7 @@ impl<F: IsPrimeField> FieldElement<F> {
}
}

#[cfg(feature = "lambdaworks-serde")]
#[cfg(feature = "lambdaworks-serde-binary")]
impl<F: IsPrimeField> Serialize for FieldElement<F> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
Expand All @@ -450,7 +462,22 @@ impl<F: IsPrimeField> Serialize for FieldElement<F> {
}
}

#[cfg(feature = "lambdaworks-serde")]
#[cfg(all(
feature = "lambdaworks-serde-string",
not(feature = "lambdaworks-serde-binary")
))]
impl<F: IsPrimeField> Serialize for FieldElement<F> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut state = serializer.serialize_struct("FieldElement", 1)?;
state.serialize_field("value", &F::representative(self.value()).to_string())?;
state.end()
}
}

#[cfg(feature = "lambdaworks-serde-binary")]
impl<'de, F: IsPrimeField> Deserialize<'de> for FieldElement<F> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
Expand Down Expand Up @@ -513,6 +540,70 @@ impl<'de, F: IsPrimeField> Deserialize<'de> for FieldElement<F> {
}
}

#[cfg(all(
feature = "lambdaworks-serde-string",
not(feature = "lambdaworks-serde-binary")
))]
impl<'de, F: IsPrimeField> Deserialize<'de> for FieldElement<F> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
#[derive(Deserialize)]
#[serde(field_identifier, rename_all = "lowercase")]
enum Field {
Value,
}

struct FieldElementVisitor<F>(PhantomData<fn() -> F>);

impl<'de, F: IsPrimeField> Visitor<'de> for FieldElementVisitor<F> {
type Value = FieldElement<F>;

fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("struct FieldElement")
}

fn visit_map<M>(self, mut map: M) -> Result<FieldElement<F>, M::Error>
where
M: MapAccess<'de>,
{
let mut value = None;
while let Some(key) = map.next_key()? {
match key {
Field::Value => {
if value.is_some() {
return Err(de::Error::duplicate_field("value"));
}
value = Some(map.next_value()?);
}
}
}
let value = value.ok_or_else(|| de::Error::missing_field("value"))?;
Ok(FieldElement::from_hex(value).unwrap())
}

fn visit_seq<S>(self, mut seq: S) -> Result<FieldElement<F>, S::Error>
where
S: SeqAccess<'de>,
{
let mut value = None;
while let Some(val) = seq.next_element()? {
if value.is_some() {
return Err(de::Error::duplicate_field("value"));
}
value = Some(val);
}
let value = value.ok_or_else(|| de::Error::missing_field("value"))?;
Ok(FieldElement::from_hex(value).unwrap())
}
}

const FIELDS: &[&str] = &["value"];
deserializer.deserialize_struct("FieldElement", FIELDS, FieldElementVisitor(PhantomData))
}
}

impl<M, const NUM_LIMBS: usize> fmt::Display
for FieldElement<MontgomeryBackendPrimeField<M, NUM_LIMBS>>
where
Expand Down
7 changes: 5 additions & 2 deletions math/src/field/fields/montgomery_backed_prime_fields.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,10 @@ pub trait IsModulus<U>: Debug {
}

#[cfg_attr(
feature = "lambdaworks-serde",
any(
feature = "lambdaworks-serde-binary",
feature = "lambdaworks-serde-string"
),
derive(serde::Serialize, serde::Deserialize)
)]
#[derive(Clone, Debug, Hash, Copy)]
Expand Down Expand Up @@ -465,7 +468,7 @@ mod tests_u384_prime_fields {
}

#[test]
#[cfg(feature = "lambdaworks-serde")]
#[cfg(feature = "lambdaworks-serde-string")]
fn montgomery_backend_serialization_deserialization() {
let x = U384F23Element::from(11_u64);
let x_serialized = serde_json::to_string(&x).unwrap();
Expand Down
2 changes: 1 addition & 1 deletion provers/cairo/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ crate-type = ["cdylib", "rlib"]

[dependencies]
rand = "0.8.5"
lambdaworks-math = { workspace = true , features = ["lambdaworks-serde"] }
lambdaworks-math = { workspace = true , features = ["lambdaworks-serde-binary"] }
lambdaworks-crypto = { workspace = true }
stark-platinum-prover = { workspace = true, features = ["wasm"] }
thiserror = "1.0.38"
Expand Down
2 changes: 1 addition & 1 deletion provers/cairo/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ cargo run --release --features=cli,instruments,parallel verify <proof_path>
For example:

```bash
cargo run --release --features=cli,instruments,parallel verify fibonacci_5.proof
cargo run --release --features=cli,instruments,parallel verify cairo_programs/cairo0/fibonacci_5.proof
```

**To compile Cairo:**
Expand Down
2 changes: 1 addition & 1 deletion provers/stark/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ license.workspace = true
crate-type = ["cdylib", "rlib"]

[dependencies]
lambdaworks-math = { workspace = true , features = ["lambdaworks-serde"] }
lambdaworks-math = { workspace = true , features = ["lambdaworks-serde-binary"] }
lambdaworks-crypto.workspace = true

rand = "0.8.5"
Expand Down

0 comments on commit 24c84ab

Please sign in to comment.