From 45328b802dd7d28d278ca364d54df0a9c6f337cc Mon Sep 17 00:00:00 2001 From: Alex Xiong Date: Sat, 13 May 2023 15:29:14 +0800 Subject: [PATCH] Initial WASM Support (#254) * add wasm32 target in nix * more try * wip fighting blst * wasm32 success * Replace Arc with Rc, no-default-features on ark-primitives * update CHANGELOG * add additional wasm32 target in CI * fix bench code * fix CI * add no-std check for non-wasm in CI & better std feature activation * wasm-aware MLE type for concurrency --- .github/workflows/build.yml | 10 ++++- .gitignore | 1 + CHANGELOG.md | 1 + README.md | 10 ++++- flake.lock | 42 +++++++++++++------ flake.nix | 33 +++++++++++++-- plonk/Cargo.toml | 18 ++++---- primitives/Cargo.toml | 14 ++++--- primitives/benches/pcs.rs | 5 +-- primitives/src/lib.rs | 4 ++ primitives/src/pcs/mod.rs | 13 ++---- .../src/pcs/multilinear_kzg/batching.rs | 14 +++---- primitives/src/pcs/multilinear_kzg/mod.rs | 21 +++++++--- primitives/src/pcs/multilinear_kzg/util.rs | 20 +++++---- primitives/src/pcs/prelude.rs | 2 +- .../src/signatures/bls_over_bls12381.rs | 20 +++++---- relation/Cargo.toml | 7 ++-- scripts/build_wasm.sh | 4 ++ utilities/Cargo.toml | 4 +- 19 files changed, 163 insertions(+), 80 deletions(-) create mode 100755 scripts/build_wasm.sh diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index f965a02f6..de6b02e88 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -32,6 +32,8 @@ jobs: override: true default: true components: rustfmt, clippy + target: | + wasm32-unknown-unknown - name: Install nightly toolchain uses: actions-rs/toolchain@v1 @@ -64,8 +66,12 @@ jobs: - name: Check all tests and binaries compilation run: cargo check --workspace --tests --lib --bins - - name: Check no_std compilation - run: cargo check --workspace --lib --no-default-features + - name: Check no_std support and WASM compilation + env: + RUSTFLAGS: -C target-cpu=generic + run: | + cargo check --no-default-features + cargo build --target wasm32-unknown-unknown --no-default-features - name: Test run: bash ./scripts/run_tests.sh diff --git a/.gitignore b/.gitignore index d131cde34..f6f7793c4 100644 --- a/.gitignore +++ b/.gitignore @@ -5,6 +5,7 @@ cargo-system-config.toml Cargo.lock *.org +.pre-commit-config.yaml # Test coverage (grcov) default.profraw diff --git a/CHANGELOG.md b/CHANGELOG.md index b069226a5..f9deaca9e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,7 @@ and follow [semantic versioning](https://semver.org/) for our releases. - [#233](https://github.com/EspressoSystems/jellyfish/pull/233) BLS aggregation APIs - [#234](https://github.com/EspressoSystems/jellyfish/pull/234) New `bytes_from_field_elements` util - [#231](https://github.com/EspressoSystems/jellyfish/pull/231) Implemented FK23 for fast amortized opening for univariate PCS +- [#254](https://github.com/EspressoSystems/jellyfish/pull/254) Ensure `no_std` and target WASM support ### Changed diff --git a/README.md b/README.md index 58c53ac2c..3351a4af6 100644 --- a/README.md +++ b/README.md @@ -32,12 +32,20 @@ cargo build Run an example: ``` -cargo run --release --example proof_of_exp +cargo run --release --example proof_of_exp --features test-srs ``` This is a simple example to prove and verify knowledge of exponent. It shows how one may compose a circuit, and then build a proof for the circuit. +### WASM target + +Jellyfish is `no_std` compliant and compilable to WASM target environment, just run: + +``` +./scripts/build_wasm.sh +``` + ### Tests ``` diff --git a/flake.lock b/flake.lock index 512410350..fadc55b5d 100644 --- a/flake.lock +++ b/flake.lock @@ -47,12 +47,15 @@ } }, "flake-utils_3": { + "inputs": { + "systems": "systems" + }, "locked": { - "lastModified": 1659877975, - "narHash": "sha256-zllb8aq3YO3h8B/U0/J1WBgAL8EX5yWf5pMj3G0NAmc=", + "lastModified": 1681202837, + "narHash": "sha256-H+Rh19JDwRtpVPAWp64F+rlEtxUWBAQW28eAi3SRSzg=", "owner": "numtide", "repo": "flake-utils", - "rev": "c0e246b9b83f637f4681389ecabcb2681b4f3af0", + "rev": "cfacdce06f30d2b68473a46042957675eebb3401", "type": "github" }, "original": { @@ -63,11 +66,11 @@ }, "nixpkgs": { "locked": { - "lastModified": 1666109165, - "narHash": "sha256-BMLyNVkr0oONuq3lKlFCRVuYqF75CO68Z8EoCh81Zdk=", + "lastModified": 1683408522, + "narHash": "sha256-9kcPh6Uxo17a3kK3XCHhcWiV1Yu1kYj22RHiymUhMkU=", "owner": "nixos", "repo": "nixpkgs", - "rev": "32096899af23d49010bd8cf6a91695888d9d9e73", + "rev": "897876e4c484f1e8f92009fd11b7d988a121a4e7", "type": "github" }, "original": { @@ -79,11 +82,11 @@ }, "nixpkgs_2": { "locked": { - "lastModified": 1665296151, - "narHash": "sha256-uOB0oxqxN9K7XGF1hcnY+PQnlQJ+3bP2vCn/+Ru/bbc=", + "lastModified": 1681358109, + "narHash": "sha256-eKyxW4OohHQx9Urxi7TQlFBTDWII+F+x2hklDOQPB50=", "owner": "NixOS", "repo": "nixpkgs", - "rev": "14ccaaedd95a488dd7ae142757884d8e125b3363", + "rev": "96ba1c52e54e74c3197f4d43026b3f3d92e83ff9", "type": "github" }, "original": { @@ -129,11 +132,11 @@ "nixpkgs": "nixpkgs_2" }, "locked": { - "lastModified": 1666148516, - "narHash": "sha256-pFgSJzUFsnCTulIzhn3HHImaZpqlMxAvXTrhg0qlMOE=", + "lastModified": 1683080331, + "narHash": "sha256-nGDvJ1DAxZIwdn6ww8IFwzoHb2rqBP4wv/65Wt5vflk=", "owner": "oxalica", "repo": "rust-overlay", - "rev": "3e41700ab6f585b9569112ee7516c74f8d072989", + "rev": "d59c3fa0cba8336e115b376c2d9e91053aa59e56", "type": "github" }, "original": { @@ -141,6 +144,21 @@ "repo": "rust-overlay", "type": "github" } + }, + "systems": { + "locked": { + "lastModified": 1681028828, + "narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=", + "owner": "nix-systems", + "repo": "default", + "rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e", + "type": "github" + }, + "original": { + "owner": "nix-systems", + "repo": "default", + "type": "github" + } } }, "root": "root", diff --git a/flake.nix b/flake.nix index 0ea6a3bdd..72cc46ef7 100644 --- a/flake.nix +++ b/flake.nix @@ -21,13 +21,32 @@ outputs = { self, nixpkgs, flake-utils, flake-compat, rust-overlay, pre-commit-hooks, ... }: flake-utils.lib.eachDefaultSystem (system: let - overlays = [ (import rust-overlay) ]; + overlays = [ + (import rust-overlay) + (self: super: { + rustc = (super.rustc.override { + stdenv = self.stdenv.override { + targetPlatform = super.stdenv.targetPlatform // { + parsed = { + cpu = { name = "wasm32"; }; + vendor = {name = "unknown";}; + kernel = {name = "unknown";}; + abi = {name = "unknown";}; + }; + }; + }; + }).overrideAttrs (attrs: { + configureFlags = attrs.configureFlags ++ ["--set=build.docs=false"]; + }); + }) + ]; pkgs = import nixpkgs { inherit system overlays; }; nightlyToolchain = pkgs.rust-bin.selectLatestNightlyWith (toolchain: toolchain.minimal.override { extensions = [ "rustfmt" ]; }); stableToolchain = pkgs.rust-bin.stable.latest.minimal.override { extensions = [ "clippy" "llvm-tools-preview" "rust-src" ]; + targets = ["wasm32-unknown-unknown"]; }; in with pkgs; { @@ -62,7 +81,8 @@ }; }; }; - devShell = mkShell { + devShell = clang15Stdenv.mkDerivation { + name = "clang15-nix-shell"; buildInputs = [ argbash openssl @@ -72,7 +92,9 @@ stableToolchain nightlyToolchain cargo-sort - + clang-tools_15 + clangStdenv + llvm_15 ] ++ lib.optionals stdenv.isDarwin [ darwin.apple_sdk.frameworks.Security ]; shellHook = '' @@ -81,6 +103,11 @@ # Ensure `cargo fmt` uses `rustfmt` from nightly. export RUSTFMT="${nightlyToolchain}/bin/rustfmt" + + export C_INCLUDE_PATH="${llvmPackages_15.libclang.lib}/lib/clang/15.0.7/include" + export CC=$(which clang) + export AR=$(which llvm-ar) + export CFLAGS="-mcpu=generic" '' # install pre-commit hooks + self.check.${system}.pre-commit-check.shellHook; diff --git a/plonk/Cargo.toml b/plonk/Cargo.toml index 5cc4ee0e5..0e4e7d77f 100644 --- a/plonk/Cargo.toml +++ b/plonk/Cargo.toml @@ -10,10 +10,6 @@ license = { workspace = true } rust-version = { workspace = true } [dependencies] -ark-bls12-377 = "0.4.0" -ark-bls12-381 = "0.4.0" -ark-bn254 = "0.4.0" -ark-bw6-761 = "0.4.0" ark-ec = "0.4.0" ark-ff = { version = "0.4.0", features = [ "asm" ] } ark-poly = "0.4.0" @@ -31,13 +27,17 @@ jf-relation = { path = "../relation", default-features = false } jf-utils = { path = "../utilities" } merlin = { version = "3.0.0", default-features = false } num-bigint = { version = "0.4", default-features = false } -rand_chacha = { version = "0.3.1" } +rand_chacha = { version = "0.3.1", default-features = false } rayon = { version = "1.5.0", optional = true } serde = { version = "1.0", default-features = false, features = ["derive"] } sha3 = "^0.10" tagged-base64 = { git = "https://github.com/espressosystems/tagged-base64", tag = "0.3.0" } [dev-dependencies] +ark-bls12-377 = "0.4.0" +ark-bls12-381 = "0.4.0" +ark-bn254 = "0.4.0" +ark-bw6-761 = "0.4.0" ark-ed-on-bls12-377 = "0.4.0" ark-ed-on-bls12-381 = "0.4.0" ark-ed-on-bn254 = "0.4.0" @@ -51,9 +51,13 @@ harness = false [features] default = ["parallel"] -std = ["ark-std/std", "ark-serialize/std", "ark-ff/std", "ark-ec/std", "ark-poly/std"] +std = [ + "ark-std/std", "ark-serialize/std", "ark-ff/std", "ark-ec/std", "ark-poly/std", + "downcast-rs/std", "itertools/use_std", "jf-primitives/std", "jf-relation/std", + "jf-utils/std", "num-bigint/std", "rand_chacha/std", "sha3/std" +] test_apis = [] # exposing apis for testing purpose parallel = ["ark-ff/parallel", "ark-ec/parallel", "ark-poly/parallel", "jf-utils/parallel", "jf-relation/parallel", "jf-primitives/parallel", - "rayon" ] + "dep:rayon" ] test-srs = [] diff --git a/primitives/Cargo.toml b/primitives/Cargo.toml index c81fdfc1f..3bad8c0a4 100644 --- a/primitives/Cargo.toml +++ b/primitives/Cargo.toml @@ -12,7 +12,7 @@ ark-bls12-377 = "0.4.0" ark-bls12-381 = "0.4.0" ark-bn254 = "0.4.0" ark-bw6-761 = "0.4.0" -ark-crypto-primitives = { version = "0.4.0", features = ["sponge"] } +ark-crypto-primitives = { version = "0.4.0", default-features = false, features = ["sponge"] } ark-ec = "0.4.0" ark-ed-on-bls12-377 = "0.4.0" ark-ed-on-bls12-381 = "0.4.0" @@ -21,8 +21,8 @@ ark-ff = "0.4.0" ark-poly = "0.4.0" ark-serialize = "0.4.0" ark-std = { version = "0.4.0", default-features = false } -blst = "0.3.10" -crypto_box = "0.8.1" +blst = { git = "https://github.com/EspressoSystems/blst.git", branch = "no-std", default-features = false } # TODO: pin to a tag or commit +crypto_box = { version = "0.8.1", default-features = false, features = ["alloc", "u32_backend"] } derivative = { version = "2", features = ["use_core"] } digest = { version = "0.10.1", default-features = false, features = ["alloc"] } displaydoc = { version = "0.2.3", default-features = false } @@ -40,7 +40,7 @@ serde = { version = "1.0", default-features = false, features = ["derive"] } sha2 = { version = "0.10.1", default-features = false } sha3 = { version = "0.10.5", default-features = false } tagged-base64 = { git = "https://github.com/espressosystems/tagged-base64", tag = "0.3.0" } -typenum = { version = "1.15.0", default-features = false } +typenum = { version = "1.15.0", default-features = false, features = ["no_std"] } zeroize = { version = "1.5", default-features = false } [dev-dependencies] @@ -54,7 +54,6 @@ ark-ed-on-bn254 = "0.4.0" bincode = "1.3" criterion = "0.4.0" hashbrown = "0.13.1" -rand_core = { version = "^0.6.0", features = ["getrandom"] } [[bench]] name = "merkle_path" @@ -66,7 +65,10 @@ harness = false [features] default = ["parallel"] -std = [] +std = ["ark-std/std", "ark-serialize/std", "ark-ff/std", "ark-ec/std", + "ark-poly/std", "ark-crypto-primitives/std", "num-bigint/std", + "num-traits/std", "sha2/std", "sha3/std", "zeroize/std", + "itertools/use_std", "rand_chacha/std", "jf-utils/std", "jf-relation/std"] print-trace = ["ark-std/print-trace"] parallel = ["ark-ff/parallel", "ark-ec/parallel", "jf-utils/parallel", "jf-relation/parallel", "rayon" ] diff --git a/primitives/benches/pcs.rs b/primitives/benches/pcs.rs index 418f77a2a..2b91c25f1 100644 --- a/primitives/benches/pcs.rs +++ b/primitives/benches/pcs.rs @@ -13,9 +13,8 @@ mod bench { use ark_bls12_381::{Bls12_381, Fr}; use ark_ff::UniformRand; use ark_poly::{DenseMultilinearExtension, MultilinearExtension}; - use ark_std::sync::Arc; use jf_primitives::pcs::{ - prelude::{MultilinearKzgPCS, PCSError, PolynomialCommitmentScheme}, + prelude::{MultilinearKzgPCS, PCSError, PolynomialCommitmentScheme, MLE}, StructuredReferenceString, }; use jf_utils::test_rng; @@ -36,7 +35,7 @@ mod bench { 10 }; - let poly = Arc::new(DenseMultilinearExtension::rand(nv, &mut rng)); + let poly = MLE::from(DenseMultilinearExtension::rand(nv, &mut rng)); let (ml_ck, ml_vk) = uni_params.0.trim(nv)?; let (uni_ck, uni_vk) = uni_params.1.trim(nv)?; let ck = (ml_ck, uni_ck); diff --git a/primitives/src/lib.rs b/primitives/src/lib.rs index a8061fb1d..00d2476ea 100644 --- a/primitives/src/lib.rs +++ b/primitives/src/lib.rs @@ -16,6 +16,10 @@ extern crate std; #[macro_use] extern crate derivative; +#[cfg(not(feature = "std"))] +#[doc(hidden)] +extern crate alloc; + pub mod aead; pub mod circuit; pub mod commitment; diff --git a/primitives/src/pcs/mod.rs b/primitives/src/pcs/mod.rs index 34dd784e4..a2271591a 100644 --- a/primitives/src/pcs/mod.rs +++ b/primitives/src/pcs/mod.rs @@ -19,7 +19,6 @@ use ark_std::{ borrow::Borrow, fmt::Debug, hash::Hash, - path::Path, rand::{CryptoRng, RngCore}, vec::Vec, }; @@ -32,13 +31,7 @@ pub trait PolynomialCommitmentScheme { /// Structured reference string type SRS: Clone + Debug + StructuredReferenceString; /// Polynomial and its associated types - type Polynomial: Clone - + Debug - + Hash - + PartialEq - + Eq - + CanonicalSerialize - + CanonicalDeserialize; + type Polynomial: Clone + Debug + Hash + PartialEq + Eq; /// Polynomial input domain type Point: Clone + Ord + Debug + Sync + Hash + PartialEq + Eq; /// Polynomial Evaluation @@ -76,7 +69,7 @@ pub trait PolynomialCommitmentScheme { /// If `file=None`, we load the default choice of SRS. fn load_srs_from_file( supported_size: usize, - file: Option<&Path>, + file: Option<&str>, ) -> Result { Self::SRS::load_srs_from_file(supported_size, file) } @@ -218,7 +211,7 @@ pub trait StructuredReferenceString: Sized { /// implemented else where. We only load them into memory here. /// /// If `file=None`, we load the default choice of SRS. - fn load_srs_from_file(_supported_size: usize, _file: Option<&Path>) -> Result { + fn load_srs_from_file(_supported_size: usize, _file: Option<&str>) -> Result { unimplemented!("TODO: implement loading SRS from files"); } } diff --git a/primitives/src/pcs/multilinear_kzg/batching.rs b/primitives/src/pcs/multilinear_kzg/batching.rs index 60b493055..01c49cf21 100644 --- a/primitives/src/pcs/multilinear_kzg/batching.rs +++ b/primitives/src/pcs/multilinear_kzg/batching.rs @@ -8,7 +8,7 @@ use super::{ open_internal, srs::{MultilinearProverParam, MultilinearVerifierParam}, util::{build_l, compute_w_circ_l, merge_polynomials}, - verify_internal, MultilinearKzgBatchProof, + verify_internal, MultilinearKzgBatchProof, MLE, }; use crate::pcs::{ multilinear_kzg::util::get_uni_domain, @@ -18,8 +18,8 @@ use crate::pcs::{ PCSError, PolynomialCommitmentScheme, }; use ark_ec::pairing::Pairing; -use ark_poly::{DenseMultilinearExtension, EvaluationDomain, MultilinearExtension, Polynomial}; -use ark_std::{end_timer, format, start_timer, string::ToString, sync::Arc, vec, vec::Vec}; +use ark_poly::{EvaluationDomain, MultilinearExtension, Polynomial}; +use ark_std::{end_timer, format, start_timer, string::ToString, vec, vec::Vec}; /// Input /// - the prover parameters for univariate KZG, @@ -57,7 +57,7 @@ use ark_std::{end_timer, format, start_timer, string::ToString, sync::Arc, vec, pub(super) fn batch_open_internal( uni_prover_param: &UnivariateProverParam, ml_prover_param: &MultilinearProverParam, - polynomials: &[Arc>], + polynomials: &[MLE], batch_commitment: &Commitment, points: &[Vec], ) -> Result<(MultilinearKzgBatchProof, Vec), PCSError> { @@ -318,7 +318,7 @@ mod tests { fn test_batch_commit_helper( uni_params: &UnivariateUniversalParams, ml_params: &MultilinearUniversalParams, - polys: &[Arc>], + polys: &[MLE], rng: &mut R, ) -> Result<(), PCSError> { let merged_nv = get_batched_nv(polys[0].num_vars(), polys.len()); @@ -422,13 +422,13 @@ mod tests { // normal polynomials let polys1: Vec<_> = (0..5) - .map(|_| Arc::new(DenseMultilinearExtension::rand(4, &mut rng))) + .map(|_| MLE::from(DenseMultilinearExtension::rand(4, &mut rng))) .collect(); test_batch_commit_helper(&uni_params, &ml_params, &polys1, &mut rng)?; // single-variate polynomials let polys1: Vec<_> = (0..5) - .map(|_| Arc::new(DenseMultilinearExtension::rand(1, &mut rng))) + .map(|_| MLE::from(DenseMultilinearExtension::rand(1, &mut rng))) .collect(); test_batch_commit_helper(&uni_params, &ml_params, &polys1, &mut rng)?; diff --git a/primitives/src/pcs/multilinear_kzg/mod.rs b/primitives/src/pcs/multilinear_kzg/mod.rs index 9e6a5e34c..1be7aae4d 100644 --- a/primitives/src/pcs/multilinear_kzg/mod.rs +++ b/primitives/src/pcs/multilinear_kzg/mod.rs @@ -15,6 +15,8 @@ use crate::pcs::{ univariate_kzg::UnivariateKzgProof, PCSError, PolynomialCommitmentScheme, StructuredReferenceString, }; +#[cfg(target_has_atomic = "ptr")] +use alloc::sync::Arc; use ark_ec::{ pairing::Pairing, scalar_mul::{fixed_base::FixedBase, variable_base::VariableBaseMSM}, @@ -30,7 +32,6 @@ use ark_std::{ rand::{CryptoRng, RngCore}, start_timer, string::ToString, - sync::Arc, vec, vec::Vec, One, Zero, @@ -70,11 +71,21 @@ pub struct MultilinearKzgBatchProof { pub q_x_opens: Vec>, } +/// Multi-linear Extension (MLE) polynomial, this type alias is set to owned +/// `DenseMultilinearExtension` on wasm platforms since only message-passing +/// concurrency is supported. And set to `Arc` for +/// platforms that supports atomic operations (e.g. mostly non-wasm, MIPS, x86 +/// etc.) +#[cfg(target_has_atomic = "ptr")] +pub type MLE = Arc>; +#[cfg(not(target_has_atomic = "ptr"))] +pub type MLE = DenseMultilinearExtension; + impl PolynomialCommitmentScheme for MultilinearKzgPCS { // Config type SRS = Srs; // Polynomial and its associated types - type Polynomial = Arc>; + type Polynomial = MLE; type Point = Vec; type Evaluation = E::ScalarField; // Commitments and proofs @@ -427,7 +438,7 @@ mod tests { fn test_single_helper( params: &(MultilinearUniversalParams, UnivariateUniversalParams), - poly: &Arc>, + poly: &MLE, rng: &mut R, ) -> Result<(), PCSError> { let nv = poly.num_vars(); @@ -457,11 +468,11 @@ mod tests { let params = MultilinearKzgPCS::::gen_srs_for_testing(&mut rng, 10)?; // normal polynomials - let poly1 = Arc::new(DenseMultilinearExtension::rand(8, &mut rng)); + let poly1 = MLE::from(DenseMultilinearExtension::rand(8, &mut rng)); test_single_helper(¶ms, &poly1, &mut rng)?; // single-variate polynomials - let poly2 = Arc::new(DenseMultilinearExtension::rand(1, &mut rng)); + let poly2 = MLE::from(DenseMultilinearExtension::rand(1, &mut rng)); test_single_helper(¶ms, &poly2, &mut rng)?; Ok(()) diff --git a/primitives/src/pcs/multilinear_kzg/util.rs b/primitives/src/pcs/multilinear_kzg/util.rs index e580a6013..9249792ad 100644 --- a/primitives/src/pcs/multilinear_kzg/util.rs +++ b/primitives/src/pcs/multilinear_kzg/util.rs @@ -12,7 +12,9 @@ use ark_poly::{ univariate::DensePolynomial, DenseMultilinearExtension, EvaluationDomain, Evaluations, MultilinearExtension, Polynomial, Radix2EvaluationDomain, }; -use ark_std::{end_timer, format, log2, start_timer, string::ToString, sync::Arc, vec, vec::Vec}; +use ark_std::{end_timer, format, log2, start_timer, string::ToString, vec, vec::Vec}; + +use super::MLE; /// Evaluate eq polynomial. use the public one later #[cfg(any(test, feature = "test-srs"))] @@ -130,7 +132,7 @@ pub fn get_batched_nv(num_var: usize, polynomials_len: usize) -> usize { /// merge a set of polynomials. Returns an error if the /// polynomials do not share a same number of nvs. pub fn merge_polynomials( - polynomials: &[Arc>], + polynomials: &[MLE], ) -> Result, PCSError> { let nv = polynomials[0].num_vars(); for poly in polynomials.iter() { @@ -192,7 +194,7 @@ pub(crate) fn build_l( // are included in the `batch_proof`. #[cfg(test)] pub(crate) fn generate_evaluations( - polynomials: &[Arc>], + polynomials: &[MLE], points: &[Vec], ) -> Result, PCSError> { if polynomials.len() != points.len() { @@ -316,7 +318,7 @@ mod test { // 1, 0 |-> 0 // 1, 1 |-> 5 let w_eval = vec![F::zero(), F::from(2u64), F::zero(), F::from(5u64)]; - let w1 = Arc::new(DenseMultilinearExtension::from_evaluations_vec(2, w_eval)); + let w1 = MLE::from(DenseMultilinearExtension::from_evaluations_vec(2, w_eval)); // W2 = x1x2 + x1 whose evaluations are // 0, 0 |-> 0 @@ -324,7 +326,7 @@ mod test { // 1, 0 |-> 1 // 1, 1 |-> 2 let w_eval = vec![F::zero(), F::zero(), F::from(1u64), F::from(2u64)]; - let w2 = Arc::new(DenseMultilinearExtension::from_evaluations_vec(2, w_eval)); + let w2 = MLE::from(DenseMultilinearExtension::from_evaluations_vec(2, w_eval)); // W3 = x1 + x2 whose evaluations are // 0, 0 |-> 0 @@ -332,7 +334,7 @@ mod test { // 1, 0 |-> 1 // 1, 1 |-> 2 let w_eval = vec![F::zero(), F::one(), F::from(1u64), F::from(2u64)]; - let w3 = Arc::new(DenseMultilinearExtension::from_evaluations_vec(2, w_eval)); + let w3 = MLE::from(DenseMultilinearExtension::from_evaluations_vec(2, w_eval)); { // W = (3x1x2 + 2x2)(1-x0) + (x1x2 + x1)x0 @@ -565,15 +567,15 @@ mod test { // Example from page 53: // W1 = 3x1x2 + 2x2 let w_eval = vec![Fr::zero(), Fr::from(2u64), Fr::zero(), Fr::from(5u64)]; - let w1 = Arc::new(DenseMultilinearExtension::from_evaluations_vec(2, w_eval)); + let w1 = MLE::from(DenseMultilinearExtension::from_evaluations_vec(2, w_eval)); // W2 = x1x2 + x1 let w_eval = vec![Fr::zero(), Fr::zero(), Fr::from(1u64), Fr::from(2u64)]; - let w2 = Arc::new(DenseMultilinearExtension::from_evaluations_vec(2, w_eval)); + let w2 = MLE::from(DenseMultilinearExtension::from_evaluations_vec(2, w_eval)); // W3 = x1 + x2 let w_eval = vec![Fr::zero(), Fr::one(), Fr::from(1u64), Fr::from(2u64)]; - let w3 = Arc::new(DenseMultilinearExtension::from_evaluations_vec(2, w_eval)); + let w3 = MLE::from(DenseMultilinearExtension::from_evaluations_vec(2, w_eval)); let r = Fr::from(42u64); diff --git a/primitives/src/pcs/prelude.rs b/primitives/src/pcs/prelude.rs index d52201e8d..34c9e0532 100644 --- a/primitives/src/pcs/prelude.rs +++ b/primitives/src/pcs/prelude.rs @@ -10,7 +10,7 @@ pub use crate::pcs::{ multilinear_kzg::{ srs::{MultilinearProverParam, MultilinearUniversalParams, MultilinearVerifierParam}, util::{get_batched_nv, merge_polynomials}, - MultilinearKzgBatchProof, MultilinearKzgPCS, MultilinearKzgProof, + MultilinearKzgBatchProof, MultilinearKzgPCS, MultilinearKzgProof, MLE, }, structs::Commitment, univariate_kzg::{ diff --git a/primitives/src/signatures/bls_over_bls12381.rs b/primitives/src/signatures/bls_over_bls12381.rs index 8ed755cfb..09080d54d 100644 --- a/primitives/src/signatures/bls_over_bls12381.rs +++ b/primitives/src/signatures/bls_over_bls12381.rs @@ -15,18 +15,19 @@ //! # Examples //! //! ``` -//! use rand_core::{RngCore, OsRng}; +//! use rand_chacha::{ChaCha20Rng, rand_core::SeedableRng}; //! use jf_primitives::signatures::{SignatureScheme, bls_over_bls12381::BLSSignatureScheme}; //! -//! let pp = BLSSignatureScheme::param_gen::(None)?; +//! let pp = BLSSignatureScheme::param_gen::(None)?; //! //! // make sure the PRNG passed has good and trusted entropy. //! // you could use `OsRng` from `rand_core` or `getrandom` crate, //! // or a `SeedableRng` like `ChaChaRng` with seed generated from good randomness source. -//! let (sk, pk) = BLSSignatureScheme::key_gen(&pp, &mut OsRng)?; +//! let mut rng = ChaCha20Rng::from_seed([0u8; 32]); +//! let (sk, pk) = BLSSignatureScheme::key_gen(&pp, &mut rng)?; //! //! let msg = "The quick brown fox jumps over the lazy dog"; -//! let sig = BLSSignatureScheme::sign(&pp, &sk, &msg, &mut OsRng)?; +//! let sig = BLSSignatureScheme::sign(&pp, &sk, &msg, &mut rng)?; //! assert!(BLSSignatureScheme::verify(&pp, &pk, &msg, &sig).is_ok()); //! //! # Ok::<(), Box>(()) @@ -38,16 +39,17 @@ //! reconstruct them later on from IKM. //! //! ``` -//! use rand_core::{RngCore, OsRng}; +//! use rand_chacha::{ChaCha20Rng, rand_core::{SeedableRng, RngCore}}; //! use sha2::{Sha256, Digest}; //! use jf_primitives::signatures::{SignatureScheme, bls_over_bls12381::BLSSignatureScheme}; //! -//! let pp = BLSSignatureScheme::param_gen::(None)?; +//! let mut rng = ChaCha20Rng::from_seed([0u8; 32]); // seed from proper entropy source in practice! +//! let pp = BLSSignatureScheme::param_gen::(None)?; //! //! // NOTE: in practice, please use [`zeroize`][zeroize] to wipe sensitive //! // key materials out of memory. //! let mut ikm = [0u8; 32]; // should be at least 32 bytes -//! OsRng.fill_bytes(&mut ikm); +//! rng.fill_bytes(&mut ikm); //! //! let mut hasher = Sha256::new(); //! hasher.update(b"MY-BLS-SIG-KEYGEN-SALT-DOM-SEP"); @@ -57,11 +59,11 @@ //! let (sk2, pk2) = BLSSignatureScheme::key_gen_v5(&ikm, &salt, b"legal".as_ref())?; //! //! let msg = "I authorize transfering 10 dollars to Alice"; -//! let sig = BLSSignatureScheme::sign(&pp, &sk1, &msg, &mut OsRng)?; +//! let sig = BLSSignatureScheme::sign(&pp, &sk1, &msg, &mut rng)?; //! assert!(BLSSignatureScheme::verify(&pp, &pk1, &msg, &sig).is_ok()); //! //! let msg = "I agree to the Terms and Conditions."; -//! let sig = BLSSignatureScheme::sign(&pp, &sk2, &msg, &mut OsRng)?; +//! let sig = BLSSignatureScheme::sign(&pp, &sk2, &msg, &mut rng)?; //! assert!(BLSSignatureScheme::verify(&pp, &pk2, &msg, &sig).is_ok()); //! //! # Ok::<(), Box>(()) diff --git a/relation/Cargo.toml b/relation/Cargo.toml index 930acc24a..7007a5682 100644 --- a/relation/Cargo.toml +++ b/relation/Cargo.toml @@ -36,7 +36,8 @@ itertools = { version = "0.10.1", default-features = false } [features] default = ["parallel"] -std = ["ark-std/std", "ark-serialize/std", "ark-ff/std", - "ark-ec/std", "ark-poly/std"] +std = ["ark-std/std", "ark-serialize/std", "ark-ff/std", "ark-ec/std", + "ark-poly/std", "downcast-rs/std", "jf-utils/std", "num-bigint/std", + "rand_chacha/std"] parallel = ["ark-ff/parallel", "ark-ec/parallel", "ark-poly/parallel", - "jf-utils/parallel", "rayon" ] + "jf-utils/parallel", "dep:rayon" ] diff --git a/scripts/build_wasm.sh b/scripts/build_wasm.sh new file mode 100755 index 000000000..e7206fdf6 --- /dev/null +++ b/scripts/build_wasm.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +set -e + +RUSTFLAGS="-C target-cpu=generic" cargo build --target wasm32-unknown-unknown --no-default-features \ No newline at end of file diff --git a/utilities/Cargo.toml b/utilities/Cargo.toml index 4332f12d6..870fce9a2 100644 --- a/utilities/Cargo.toml +++ b/utilities/Cargo.toml @@ -28,5 +28,5 @@ ark-ed-on-bn254 = "0.4.0" [features] default = [] -std = ["ark-ff/std", "ark-std/std", "ark-ec/std", "ark-serialize/std"] -parallel = ["ark-ff/parallel", "ark-std/parallel", "ark-ec/parallel", "rayon"] +std = ["ark-ff/std", "ark-std/std", "ark-ec/std", "ark-serialize/std", "digest/std", "serde/std", "sha2/std"] +parallel = ["ark-ff/parallel", "ark-std/parallel", "ark-ec/parallel", "dep:rayon"]