diff --git a/dockerfiles/stages/1-build-deps b/dockerfiles/stages/1-build-deps index 3e5348cc6e5..8260a26c3a6 100644 --- a/dockerfiles/stages/1-build-deps +++ b/dockerfiles/stages/1-build-deps @@ -25,7 +25,7 @@ ARG GO_CAPNP_VERSION=v3.0.0-alpha.5 # - src/lib/crypto/proof-systems/rust-toolchain.toml ARG RUST_VERSION=1.72 # Nightly Rust Version used for WebAssembly builds -# - src/lib/crypto/kimchi_bindings/wasm/rust-toolchain.toml +# - src/lib/crypto/proof-systems/plonk-wasm/rust-toolchain.toml ARG RUST_NIGHTLY=2023-09-01 # wasm-pack version ARG WASM_PACK_VERSION=v0.12.1 diff --git a/nix/rust.nix b/nix/rust.nix index dad90f34a49..3285fab5027 100644 --- a/nix/rust.nix +++ b/nix/rust.nix @@ -9,8 +9,6 @@ let }; toolchainHashes = { "1.72" = "sha256-dxE7lmCFWlq0nl/wKcmYvpP9zqQbBitAQgZ1zx9Ooik="; - "nightly-2023-09-01" = - "sha256-zek9JAnRaoX8V0U2Y5ssXVe9tvoQ0ERGXfUCUGYdrMA="; # copy the placeholder line with the correct toolchain name when adding a new toolchain # That is, # 1. Put the correct version name; @@ -89,7 +87,7 @@ in { }; kimchi-rust = rustChannelFromToolchainFileOf - ../src/lib/crypto/kimchi_bindings/wasm/rust-toolchain.toml; + ../src/lib/crypto/proof-systems/rust-toolchain.toml; # TODO: raise issue on nixpkgs and remove workaround when fix is applied kimchi-rust-wasm = (final.kimchi-rust.rust.override { @@ -111,7 +109,7 @@ in { }; plonk_wasm = let - lock = ../src/lib/crypto/kimchi_bindings/wasm/Cargo.lock; + lock = ../src/lib/crypto/proof-systems/Cargo.lock; deps = builtins.listToAttrs (map (pkg: { inherit (pkg) name; @@ -120,7 +118,7 @@ in { rustPlatform = rustPlatformFor final.kimchi-rust-wasm; - wasm-bindgen-cli = rustPlatform.buildRustPackage rec { + wasm-bindgen-cli = final.rustPlatform.buildRustPackage rec { pname = "wasm-bindgen-cli"; version = deps.wasm-bindgen.version; src = final.fetchCrate { @@ -148,10 +146,10 @@ in { pname = "plonk_wasm"; version = "0.1.0"; src = final.lib.sourceByRegex ../src [ - "^lib(/crypto(/kimchi_bindings(/wasm(/.*)?)?)?)?$" "^lib(/crypto(/proof-systems(/.*)?)?)?$" ]; - sourceRoot = "source/lib/crypto/kimchi_bindings/wasm"; + buildAndTestSubdir = "plonk-wasm"; + sourceRoot = "source/lib/crypto/proof-systems"; nativeBuildInputs = [ final.wasm-pack wasm-bindgen-cli ]; buildInputs = with final; lib.optional stdenv.isDarwin libiconv; cargoLock.lockFile = lock; @@ -178,8 +176,8 @@ in { ( set -x export RUSTFLAGS="-C target-feature=+atomics,+bulk-memory,+mutable-globals -C link-arg=--no-check-features -C link-arg=--max-memory=4294967296" - wasm-pack build --mode no-install --target nodejs --out-dir $out/nodejs ./. -- --features nodejs - wasm-pack build --mode no-install --target web --out-dir $out/web ./. + wasm-pack build --mode no-install --target nodejs --out-dir $out/nodejs ./plonk-wasm -- --features nodejs + wasm-pack build --mode no-install --target web --out-dir $out/web ./plonk-wasm ) runHook postBuild ''; diff --git a/src/dune-project b/src/dune-project index 5fcb5e58038..dfb4af5886f 100644 --- a/src/dune-project +++ b/src/dune-project @@ -59,7 +59,7 @@ (package (name heap_usage)) (package (name hex)) (package (name immutable_array)) -(package (name inline_test_quiet_logs)) +(package (name inline_test_quiet_logs) (allow_empty)) (package (name integers_stubs_js)) (package (name integration_test_local_engine)) (package (name integration_test_lib)) diff --git a/src/lib/crypto/kimchi_bindings/js/bindings/README.md b/src/lib/crypto/kimchi_bindings/js/bindings/README.md index c6c2ee2a8d6..791410c5e65 100644 --- a/src/lib/crypto/kimchi_bindings/js/bindings/README.md +++ b/src/lib/crypto/kimchi_bindings/js/bindings/README.md @@ -12,7 +12,7 @@ This way, when calling the function `FunnyLittleModule.do_cool_thingies`, we tel We use this for many things. Many things in the code base rely of implementations in Rust. For example, we use Kimchi to generate proofs! So in order to tell OCaml to generate a Kimchi proof, we need to point it to the correct function that's living in the Rust proof-systems repository. -The other side of the `external` keyword is somewhere in the Rust bindings layer, more specifically somewhere in `src/lib/crypto/kimchi_bindings/wasm/src` - in our case where we want to establish bindings between OCaml that has been compiled to JavaScript using JSOO and Rust (compiled to WASM). +The other side of the `external` keyword is somewhere in the Rust bindings layer, more specifically somewhere in `src/lib/crypto/proof-systems/plonk-wasm/src` - in our case where we want to establish bindings between OCaml that has been compiled to JavaScript using JSOO and Rust (compiled to WASM). For example, the implementation of `caml_do_cool_thingies` could look like this: diff --git a/src/lib/crypto/kimchi_bindings/js/node_js/build.sh b/src/lib/crypto/kimchi_bindings/js/node_js/build.sh index 41a7c57bc5c..8c3d67e52d4 100755 --- a/src/lib/crypto/kimchi_bindings/js/node_js/build.sh +++ b/src/lib/crypto/kimchi_bindings/js/node_js/build.sh @@ -1,10 +1,12 @@ #!/usr/bin/env bash set -euo pipefail +# When using nix this is already cached if [[ -z "${PLONK_WASM_NODEJS-}" ]]; then export RUSTFLAGS="-C target-feature=+atomics,+bulk-memory,+mutable-globals -C link-arg=--no-check-features -C link-arg=--max-memory=4294967296" - # The version should stay in line with the one in kimchi_bindings/wasm/rust-toolchain.toml - rustup run nightly-2023-09-01 wasm-pack build --target nodejs --out-dir ../js/node_js ../../wasm -- -Z build-std=panic_abort,std --features nodejs + # The rust version should stay in line with the one in kimchi_bindings/wasm/rust-toolchain.toml + # TODO: change out-dir to be relative to PWD when we upgrade to wasm-pack 0.13 (see https://github.com/rustwasm/wasm-pack/issues/704) + rustup run 1.72 wasm-pack build --target nodejs --out-dir ../../kimchi_bindings/js/node_js ../../../proof-systems/plonk-wasm -- --features nodejs else cp "$PLONK_WASM_NODEJS"/* -R . fi diff --git a/src/lib/crypto/kimchi_bindings/js/node_js/dune b/src/lib/crypto/kimchi_bindings/js/node_js/dune index fdf020725f1..27ed0f5a1e9 100644 --- a/src/lib/crypto/kimchi_bindings/js/node_js/dune +++ b/src/lib/crypto/kimchi_bindings/js/node_js/dune @@ -20,15 +20,15 @@ (deps build.sh ../../dune-build-root - ../../wasm/Cargo.toml - ../../wasm/Cargo.lock - (source_tree ../../wasm/src) - (source_tree ../../wasm/.cargo/config) + ../../../proof-systems/Cargo.toml + ../../../proof-systems/Cargo.lock + (source_tree ../../../proof-systems/plonk-wasm/src) + (source_tree ../../proof-systems/plonk-wasm/.cargo/config) (source_tree ../../../proof-systems)) (locks /cargo-lock) ; lock for rustup (action (progn - (run chmod -R +w ../../wasm .) + (run chmod -R +w ../../../proof-systems/plonk-wasm .) (setenv CARGO_TARGET_DIR "%{read:../../dune-build-root}/cargo_kimchi_wasm" diff --git a/src/lib/crypto/kimchi_bindings/js/web/build.sh b/src/lib/crypto/kimchi_bindings/js/web/build.sh index f99564ef81d..535d5cd702d 100755 --- a/src/lib/crypto/kimchi_bindings/js/web/build.sh +++ b/src/lib/crypto/kimchi_bindings/js/web/build.sh @@ -1,10 +1,12 @@ #!/usr/bin/env bash set -euo pipefail +# When using nix this is already cached if [[ -z "${PLONK_WASM_WEB-}" ]]; then export RUSTFLAGS="-C target-feature=+atomics,+bulk-memory,+mutable-globals -C link-arg=--no-check-features -C link-arg=--max-memory=4294967296" # The version should stay in line with the one in kimchi_bindings/wasm/rust-toolchain.toml - rustup run nightly-2023-09-01 wasm-pack build --target web --out-dir ../js/web ../../wasm -- -Z build-std=panic_abort,std + # TODO: change out-dir to be relative to PWD when we upgrade to wasm-pack 0.13 (see https://github.com/rustwasm/wasm-pack/issues/704) + rustup run 1.72 wasm-pack build --target web --out-dir ../../kimchi_bindings/js/web ../../../proof-systems/plonk-wasm else cp "$PLONK_WASM_WEB"/* -R . fi diff --git a/src/lib/crypto/kimchi_bindings/js/web/dune b/src/lib/crypto/kimchi_bindings/js/web/dune index 392437d0ec6..a04b38388d1 100644 --- a/src/lib/crypto/kimchi_bindings/js/web/dune +++ b/src/lib/crypto/kimchi_bindings/js/web/dune @@ -19,16 +19,16 @@ flags.sexp) (deps build.sh - ../../wasm/Cargo.toml - ../../wasm/Cargo.lock + ../../../proof-systems/plonk-wasm/Cargo.toml + ../../../proof-systems/Cargo.lock ../../dune-build-root - (source_tree ../../wasm/src) - (source_tree ../../wasm/.cargo/config) + (source_tree ../../../proof-systems/plonk-wasm/src) + (source_tree ../../../proof-systems/plonk-wasm/.cargo/config) (source_tree ../../../proof-systems)) (locks /cargo-lock) ; lock for rustup (action (progn - (run chmod -R +w ../../wasm .) + (run chmod -R +w ../../../proof-systems/plonk-wasm .) (setenv CARGO_TARGET_DIR "%{read:../../dune-build-root}/cargo_kimchi_wasm" diff --git a/src/lib/crypto/kimchi_bindings/wasm/.cargo/config b/src/lib/crypto/kimchi_bindings/wasm/.cargo/config deleted file mode 100644 index 9600999e0cb..00000000000 --- a/src/lib/crypto/kimchi_bindings/wasm/.cargo/config +++ /dev/null @@ -1,8 +0,0 @@ -[build] -target = "wasm32-unknown-unknown" - -[target.wasm32-unknown-unknown] -rustflags = ["-C", "target-feature=+atomics,+bulk-memory", "-C", "link-arg=--no-check-features"] - -[unstable] -build-std = ["panic_abort", "std"] diff --git a/src/lib/crypto/kimchi_bindings/wasm/.gitignore b/src/lib/crypto/kimchi_bindings/wasm/.gitignore deleted file mode 100644 index eb5a316cbd1..00000000000 --- a/src/lib/crypto/kimchi_bindings/wasm/.gitignore +++ /dev/null @@ -1 +0,0 @@ -target diff --git a/src/lib/crypto/kimchi_bindings/wasm/Cargo.lock b/src/lib/crypto/kimchi_bindings/wasm/Cargo.lock deleted file mode 100644 index 91f508b5b8c..00000000000 --- a/src/lib/crypto/kimchi_bindings/wasm/Cargo.lock +++ /dev/null @@ -1,1456 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -version = 3 - -[[package]] -name = "ahash" -version = "0.8.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e89da841a80418a9b391ebaea17f5c112ffaaa96f621d2c285b5174da76b9011" -dependencies = [ - "cfg-if", - "once_cell", - "version_check", - "zerocopy", -] - -[[package]] -name = "alga" -version = "0.9.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f823d037a7ec6ea2197046bafd4ae150e6bc36f9ca347404f46a46823fa84f2" -dependencies = [ - "approx", - "num-complex 0.2.4", - "num-traits", -] - -[[package]] -name = "android-tzdata" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e999941b234f3131b00bc13c22d06e8c5ff726d1b6318ac7eb276997bbb4fef0" - -[[package]] -name = "android_system_properties" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" -dependencies = [ - "libc", -] - -[[package]] -name = "approx" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0e60b75072ecd4168020818c0107f2857bb6c4e64252d8d3983f6263b40a5c3" -dependencies = [ - "num-traits", -] - -[[package]] -name = "ark-ec" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "defd9a439d56ac24968cca0571f598a61bc8c55f71d50a89cda591cb750670ba" -dependencies = [ - "ark-ff", - "ark-poly", - "ark-serialize", - "ark-std", - "derivative", - "hashbrown 0.13.2", - "itertools 0.10.5", - "num-traits", - "rayon", - "zeroize", -] - -[[package]] -name = "ark-ff" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec847af850f44ad29048935519032c33da8aa03340876d351dfab5660d2966ba" -dependencies = [ - "ark-ff-asm", - "ark-ff-macros", - "ark-serialize", - "ark-std", - "derivative", - "digest", - "itertools 0.10.5", - "num-bigint", - "num-traits", - "paste", - "rayon", - "rustc_version", - "zeroize", -] - -[[package]] -name = "ark-ff-asm" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ed4aa4fe255d0bc6d79373f7e31d2ea147bcf486cba1be5ba7ea85abdb92348" -dependencies = [ - "quote", - "syn 1.0.109", -] - -[[package]] -name = "ark-ff-macros" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7abe79b0e4288889c4574159ab790824d0033b9fdcb2a112a3182fac2e514565" -dependencies = [ - "num-bigint", - "num-traits", - "proc-macro2", - "quote", - "syn 1.0.109", -] - -[[package]] -name = "ark-poly" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d320bfc44ee185d899ccbadfa8bc31aab923ce1558716e1997a1e74057fe86bf" -dependencies = [ - "ark-ff", - "ark-serialize", - "ark-std", - "derivative", - "hashbrown 0.13.2", - "rayon", -] - -[[package]] -name = "ark-serialize" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "adb7b85a02b83d2f22f89bd5cac66c9c89474240cb6207cb1efc16d098e822a5" -dependencies = [ - "ark-serialize-derive", - "ark-std", - "digest", - "num-bigint", -] - -[[package]] -name = "ark-serialize-derive" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae3281bc6d0fd7e549af32b52511e1302185bd688fd3359fa36423346ff682ea" -dependencies = [ - "proc-macro2", - "quote", - "syn 1.0.109", -] - -[[package]] -name = "ark-std" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94893f1e0c6eeab764ade8dc4c0db24caf4fe7cbbaafc0eba0a9030f447b5185" -dependencies = [ - "num-traits", - "rand", - "rayon", -] - -[[package]] -name = "array-init" -version = "2.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d62b7694a562cdf5a74227903507c56ab2cc8bdd1f781ed5cb4cf9c9f810bfc" - -[[package]] -name = "autocfg" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" - -[[package]] -name = "base64" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8" - -[[package]] -name = "base64" -version = "0.22.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" - -[[package]] -name = "bcs" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85b6598a2f5d564fb7855dc6b06fd1c38cff5a72bd8b863a4d021938497b440a" -dependencies = [ - "serde", - "thiserror", -] - -[[package]] -name = "blake2" -version = "0.10.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe" -dependencies = [ - "digest", -] - -[[package]] -name = "block-buffer" -version = "0.10.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" -dependencies = [ - "generic-array", -] - -[[package]] -name = "bumpalo" -version = "3.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f30e7476521f6f8af1a1c4c0b8cc94f0bee37d91763d0ca2665f299b6cd8aec" - -[[package]] -name = "byteorder" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" - -[[package]] -name = "cc" -version = "1.0.83" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1174fb0b6ec23863f8b971027804a42614e347eafb0a95bf0b12cdae21fc4d0" -dependencies = [ - "libc", -] - -[[package]] -name = "cfg-if" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" - -[[package]] -name = "chrono" -version = "0.4.31" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f2c685bad3eb3d45a01354cedb7d5faa66194d1d58ba6e267a8de788f79db38" -dependencies = [ - "android-tzdata", - "iana-time-zone", - "num-traits", - "serde", - "windows-targets", -] - -[[package]] -name = "console_error_panic_hook" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a06aeb73f470f66dcdbf7223caeebb85984942f22f1adb2a088cf9668146bbbc" -dependencies = [ - "cfg-if", - "wasm-bindgen", -] - -[[package]] -name = "core-foundation-sys" -version = "0.8.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e496a50fda8aacccc86d7529e2c1e0892dbd0f898a6b5645b5561b89c3210efa" - -[[package]] -name = "cpufeatures" -version = "0.2.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3fbc60abd742b35f2492f808e1abbb83d45f72db402e14c55057edc9c7b1e9e4" -dependencies = [ - "libc", -] - -[[package]] -name = "crossbeam-deque" -version = "0.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce6fd6f855243022dcecf8702fef0c297d4338e226845fe067f6341ad9fa0cef" -dependencies = [ - "cfg-if", - "crossbeam-epoch", - "crossbeam-utils", -] - -[[package]] -name = "crossbeam-epoch" -version = "0.9.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae211234986c545741a7dc064309f67ee1e5ad243d0e48335adc0484d960bcc7" -dependencies = [ - "autocfg", - "cfg-if", - "crossbeam-utils", - "memoffset", - "scopeguard", -] - -[[package]] -name = "crossbeam-utils" -version = "0.8.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a22b2d63d4d1dc0b7f1b6b2747dd0088008a9be28b6ddf0b1e7d335e3037294" -dependencies = [ - "cfg-if", -] - -[[package]] -name = "crypto-common" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3" -dependencies = [ - "generic-array", - "typenum", -] - -[[package]] -name = "darling" -version = "0.20.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0209d94da627ab5605dcccf08bb18afa5009cfbef48d8a8b7d7bdbc79be25c5e" -dependencies = [ - "darling_core", - "darling_macro", -] - -[[package]] -name = "darling_core" -version = "0.20.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "177e3443818124b357d8e76f53be906d60937f0d3a90773a664fa63fa253e621" -dependencies = [ - "fnv", - "ident_case", - "proc-macro2", - "quote", - "strsim", - "syn 2.0.32", -] - -[[package]] -name = "darling_macro" -version = "0.20.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "836a9bbc7ad63342d6d6e7b815ccab164bc77a2d95d84bc3117a8c0d5c98e2d5" -dependencies = [ - "darling_core", - "quote", - "syn 2.0.32", -] - -[[package]] -name = "deranged" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f32d04922c60427da6f9fef14d042d9edddef64cb9d4ce0d64d0685fbeb1fd3" -dependencies = [ - "powerfmt", - "serde", -] - -[[package]] -name = "derivative" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fcc3dd5e9e9c0b295d6e1e4d811fb6f157d5ffd784b8d202fc62eac8035a770b" -dependencies = [ - "proc-macro2", - "quote", - "syn 1.0.109", -] - -[[package]] -name = "digest" -version = "0.10.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" -dependencies = [ - "block-buffer", - "crypto-common", - "subtle", -] - -[[package]] -name = "either" -version = "1.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a26ae43d7bcc3b814de94796a5e736d4029efb0ee900c12e2d54c993ad1a1e07" - -[[package]] -name = "equivalent" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5" - -[[package]] -name = "fnv" -version = "1.0.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" - -[[package]] -name = "generic-array" -version = "0.14.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" -dependencies = [ - "typenum", - "version_check", -] - -[[package]] -name = "getrandom" -version = "0.2.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be4136b2a15dd319360be1c07d9933517ccf0be8f16bf62a3bee4f0d618df427" -dependencies = [ - "cfg-if", - "js-sys", - "libc", - "wasi", - "wasm-bindgen", -] - -[[package]] -name = "groupmap" -version = "0.1.0" -dependencies = [ - "ark-ec", - "ark-ff", - "rand", -] - -[[package]] -name = "hashbrown" -version = "0.12.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" - -[[package]] -name = "hashbrown" -version = "0.13.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "43a3c133739dddd0d2990f9a4bdf8eb4b21ef50e4851ca85ab661199821d510e" -dependencies = [ - "ahash", -] - -[[package]] -name = "hashbrown" -version = "0.14.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" - -[[package]] -name = "heck" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" - -[[package]] -name = "hermit-abi" -version = "0.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d77f7ec81a6d05a3abb01ab6eb7590f6083d08449fe5a1c8b1e620283546ccb7" - -[[package]] -name = "hex" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" -dependencies = [ - "serde", -] - -[[package]] -name = "iana-time-zone" -version = "0.1.58" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8326b86b6cff230b97d0d312a6c40a60726df3332e721f72a1b035f451663b20" -dependencies = [ - "android_system_properties", - "core-foundation-sys", - "iana-time-zone-haiku", - "js-sys", - "wasm-bindgen", - "windows-core", -] - -[[package]] -name = "iana-time-zone-haiku" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" -dependencies = [ - "cc", -] - -[[package]] -name = "ident_case" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" - -[[package]] -name = "indexmap" -version = "1.9.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99" -dependencies = [ - "autocfg", - "hashbrown 0.12.3", - "serde", -] - -[[package]] -name = "indexmap" -version = "2.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68b900aa2f7301e21c36462b170ee99994de34dff39a4a6a528e80e7376d07e5" -dependencies = [ - "equivalent", - "hashbrown 0.14.5", - "serde", -] - -[[package]] -name = "internal-tracing" -version = "0.1.0" - -[[package]] -name = "itertools" -version = "0.10.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0fd2260e829bddf4cb6ea802289de2f86d6a7a690192fbe91b3f46e0f2c8473" -dependencies = [ - "either", -] - -[[package]] -name = "itertools" -version = "0.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba291022dbbd398a455acf126c1e341954079855bc60dfdda641363bd6922569" -dependencies = [ - "either", -] - -[[package]] -name = "itoa" -version = "1.0.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af150ab688ff2122fcef229be89cb50dd66af9e01a4ff320cc137eecc9bacc38" - -[[package]] -name = "js-sys" -version = "0.3.64" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c5f195fe497f702db0f318b07fdd68edb16955aed830df8363d837542f8f935a" -dependencies = [ - "wasm-bindgen", -] - -[[package]] -name = "kimchi" -version = "0.1.0" -dependencies = [ - "ark-ec", - "ark-ff", - "ark-poly", - "ark-serialize", - "blake2", - "groupmap", - "hex", - "internal-tracing", - "itertools 0.12.1", - "log", - "mina-curves", - "mina-poseidon", - "num-bigint", - "num-derive", - "num-integer", - "num-traits", - "o1-utils", - "once_cell", - "poly-commitment", - "rand", - "rand_core", - "rayon", - "rmp-serde", - "serde", - "serde_with", - "strum", - "strum_macros", - "thiserror", - "turshi", - "wasm-bindgen", -] - -[[package]] -name = "libc" -version = "0.2.149" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a08173bc88b7955d1b3145aa561539096c421ac8debde8cbc3612ec635fee29b" - -[[package]] -name = "libm" -version = "0.2.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ec2a862134d2a7d32d7983ddcdd1c4923530833c9f2ea1a44fc5fa473989058" - -[[package]] -name = "log" -version = "0.4.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5e6163cb8c49088c2c36f57875e58ccd8c87c7427f7fbd50ea6710b2f3f2e8f" - -[[package]] -name = "matrixmultiply" -version = "0.3.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7574c1cf36da4798ab73da5b215bbf444f50718207754cb522201d78d1cd0ff2" -dependencies = [ - "autocfg", - "rawpointer", -] - -[[package]] -name = "memoffset" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a634b1c61a95585bd15607c6ab0c4e5b226e695ff2800ba0cdccddf208c406c" -dependencies = [ - "autocfg", -] - -[[package]] -name = "mina-curves" -version = "0.1.0" -dependencies = [ - "ark-ec", - "ark-ff", - "num-bigint", -] - -[[package]] -name = "mina-poseidon" -version = "0.1.0" -dependencies = [ - "ark-ec", - "ark-ff", - "ark-poly", - "ark-serialize", - "mina-curves", - "o1-utils", - "once_cell", - "rand", - "rayon", - "serde", - "serde_with", -] - -[[package]] -name = "ndarray" -version = "0.15.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "adb12d4e967ec485a5f71c6311fe28158e9d6f4bc4a447b474184d0f91a8fa32" -dependencies = [ - "matrixmultiply", - "num-complex 0.4.4", - "num-integer", - "num-traits", - "rawpointer", -] - -[[package]] -name = "num-bigint" -version = "0.4.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "608e7659b5c3d7cba262d894801b9ec9d00de989e8a82bd4bef91d08da45cdc0" -dependencies = [ - "autocfg", - "num-integer", - "num-traits", - "rand", - "serde", -] - -[[package]] -name = "num-complex" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6b19411a9719e753aff12e5187b74d60d3dc449ec3f4dc21e3989c3f554bc95" -dependencies = [ - "autocfg", - "num-traits", -] - -[[package]] -name = "num-complex" -version = "0.4.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ba157ca0885411de85d6ca030ba7e2a83a28636056c7c699b07c8b6f7383214" -dependencies = [ - "num-traits", -] - -[[package]] -name = "num-conv" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "51d515d32fb182ee37cda2ccdcb92950d6a3c2893aa280e540671c2cd0f3b1d9" - -[[package]] -name = "num-derive" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed3955f1a9c7c0c15e092f9c887db08b1fc683305fdf6eb6684f22555355e202" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.32", -] - -[[package]] -name = "num-integer" -version = "0.1.45" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "225d3389fb3509a24c93f5c29eb6bde2586b98d9f016636dff58d7c6f7569cd9" -dependencies = [ - "autocfg", - "num-traits", -] - -[[package]] -name = "num-traits" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39e3200413f237f41ab11ad6d161bc7239c84dcb631773ccd7de3dfe4b5c267c" -dependencies = [ - "autocfg", - "libm", -] - -[[package]] -name = "num_cpus" -version = "1.16.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4161fcb6d602d4d2081af7c3a45852d875a03dd337a6bfdd6e06407b61342a43" -dependencies = [ - "hermit-abi", - "libc", -] - -[[package]] -name = "o1-utils" -version = "0.1.0" -dependencies = [ - "ark-ec", - "ark-ff", - "ark-poly", - "ark-serialize", - "bcs", - "hex", - "num-bigint", - "num-integer", - "num-traits", - "rand", - "rand_core", - "rayon", - "rmp-serde", - "serde", - "serde_with", - "sha2", - "thiserror", -] - -[[package]] -name = "once_cell" -version = "1.18.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd8b5dd2ae5ed71462c540258bedcb51965123ad7e7ccf4b9a8cafaa4a63576d" - -[[package]] -name = "paste" -version = "1.0.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "de3145af08024dea9fa9914f381a17b8fc6034dfb00f3a84013f7ff43f29ed4c" - -[[package]] -name = "plonk_wasm" -version = "0.1.0" -dependencies = [ - "ark-ec", - "ark-ff", - "ark-poly", - "ark-serialize", - "array-init", - "base64 0.13.1", - "console_error_panic_hook", - "getrandom", - "groupmap", - "js-sys", - "kimchi", - "libc", - "mina-curves", - "mina-poseidon", - "num-bigint", - "o1-utils", - "once_cell", - "paste", - "poly-commitment", - "proc-macro2", - "quote", - "rand", - "rayon", - "rmp-serde", - "serde", - "serde-wasm-bindgen", - "serde_json", - "serde_with", - "spmc", - "sprs", - "wasm-bindgen", - "wasm-bindgen-test", - "web-sys", -] - -[[package]] -name = "poly-commitment" -version = "0.1.0" -dependencies = [ - "ark-ec", - "ark-ff", - "ark-poly", - "ark-serialize", - "blake2", - "groupmap", - "itertools 0.12.1", - "mina-curves", - "mina-poseidon", - "o1-utils", - "once_cell", - "rand", - "rand_core", - "rayon", - "rmp-serde", - "serde", - "serde_with", - "thiserror", -] - -[[package]] -name = "powerfmt" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" - -[[package]] -name = "ppv-lite86" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de" - -[[package]] -name = "proc-macro2" -version = "1.0.66" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "18fb31db3f9bddb2ea821cde30a9f70117e3f119938b5ee630b7403aa6e2ead9" -dependencies = [ - "unicode-ident", -] - -[[package]] -name = "quote" -version = "1.0.33" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5267fca4496028628a95160fc423a33e8b2e6af8a5302579e322e4b520293cae" -dependencies = [ - "proc-macro2", -] - -[[package]] -name = "rand" -version = "0.8.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" -dependencies = [ - "libc", - "rand_chacha", - "rand_core", -] - -[[package]] -name = "rand_chacha" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" -dependencies = [ - "ppv-lite86", - "rand_core", -] - -[[package]] -name = "rand_core" -version = "0.6.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" -dependencies = [ - "getrandom", -] - -[[package]] -name = "rawpointer" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "60a357793950651c4ed0f3f52338f53b2f809f32d83a07f72909fa13e4c6c1e3" - -[[package]] -name = "rayon" -version = "1.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c27db03db7734835b3f53954b534c91069375ce6ccaa2e065441e07d9b6cdb1" -dependencies = [ - "either", - "rayon-core", -] - -[[package]] -name = "rayon-core" -version = "1.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ce3fb6ad83f861aac485e76e1985cd109d9a3713802152be56c3b1f0e0658ed" -dependencies = [ - "crossbeam-deque", - "crossbeam-utils", -] - -[[package]] -name = "rmp" -version = "0.8.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f9860a6cc38ed1da53456442089b4dfa35e7cedaa326df63017af88385e6b20" -dependencies = [ - "byteorder", - "num-traits", - "paste", -] - -[[package]] -name = "rmp-serde" -version = "1.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bffea85eea980d8a74453e5d02a8d93028f3c34725de143085a844ebe953258a" -dependencies = [ - "byteorder", - "rmp", - "serde", -] - -[[package]] -name = "rustc_version" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfa0f585226d2e68097d4f95d113b15b83a82e819ab25717ec0590d9584ef366" -dependencies = [ - "semver", -] - -[[package]] -name = "rustversion" -version = "1.0.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ffc183a10b4478d04cbbbfc96d0873219d962dd5accaff2ffbd4ceb7df837f4" - -[[package]] -name = "ryu" -version = "1.0.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ad4cc8da4ef723ed60bced201181d83791ad433213d8c24efffda1eec85d741" - -[[package]] -name = "scoped-tls" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294" - -[[package]] -name = "scopeguard" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" - -[[package]] -name = "semver" -version = "1.0.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61697e0a1c7e512e84a621326239844a24d8207b4669b41bc18b32ea5cbf988b" - -[[package]] -name = "serde" -version = "1.0.193" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25dd9975e68d0cb5aa1120c288333fc98731bd1dd12f561e468ea4728c042b89" -dependencies = [ - "serde_derive", -] - -[[package]] -name = "serde-wasm-bindgen" -version = "0.4.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3b4c031cd0d9014307d82b8abf653c0290fbdaeb4c02d00c63cf52f728628bf" -dependencies = [ - "js-sys", - "serde", - "wasm-bindgen", -] - -[[package]] -name = "serde_derive" -version = "1.0.193" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "43576ca501357b9b071ac53cdc7da8ef0cbd9493d8df094cd821777ea6e894d3" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.32", -] - -[[package]] -name = "serde_json" -version = "1.0.109" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb0652c533506ad7a2e353cce269330d6afd8bdfb6d75e0ace5b35aacbd7b9e9" -dependencies = [ - "itoa", - "ryu", - "serde", -] - -[[package]] -name = "serde_with" -version = "3.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69cecfa94848272156ea67b2b1a53f20fc7bc638c4a46d2f8abde08f05f4b857" -dependencies = [ - "base64 0.22.1", - "chrono", - "hex", - "indexmap 1.9.3", - "indexmap 2.5.0", - "serde", - "serde_derive", - "serde_json", - "serde_with_macros", - "time", -] - -[[package]] -name = "serde_with_macros" -version = "3.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a8fee4991ef4f274617a51ad4af30519438dacb2f56ac773b08a1922ff743350" -dependencies = [ - "darling", - "proc-macro2", - "quote", - "syn 2.0.32", -] - -[[package]] -name = "sha2" -version = "0.10.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "793db75ad2bcafc3ffa7c68b215fee268f537982cd901d132f89c6343f3a3dc8" -dependencies = [ - "cfg-if", - "cpufeatures", - "digest", -] - -[[package]] -name = "smallvec" -version = "1.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "942b4a808e05215192e39f4ab80813e599068285906cc91aa64f923db842bd5a" - -[[package]] -name = "spmc" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "02a8428da277a8e3a15271d79943e80ccc2ef254e78813a166a08d65e4c3ece5" - -[[package]] -name = "sprs" -version = "0.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "88bab60b0a18fb9b3e0c26e92796b3c3a278bf5fa4880f5ad5cc3bdfb843d0b1" -dependencies = [ - "alga", - "ndarray", - "num-complex 0.4.4", - "num-traits", - "num_cpus", - "rayon", - "smallvec", -] - -[[package]] -name = "strsim" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" - -[[package]] -name = "strum" -version = "0.26.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8fec0f0aef304996cf250b31b5a10dee7980c85da9d759361292b8bca5a18f06" - -[[package]] -name = "strum_macros" -version = "0.26.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c6bee85a5a24955dc440386795aa378cd9cf82acd5f764469152d2270e581be" -dependencies = [ - "heck", - "proc-macro2", - "quote", - "rustversion", - "syn 2.0.32", -] - -[[package]] -name = "subtle" -version = "2.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "81cdd64d312baedb58e21336b31bc043b77e01cc99033ce76ef539f78e965ebc" - -[[package]] -name = "syn" -version = "1.0.109" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - -[[package]] -name = "syn" -version = "2.0.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "239814284fd6f1a4ffe4ca893952cdd93c224b6a1571c9a9eadd670295c0c9e2" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - -[[package]] -name = "thiserror" -version = "1.0.40" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "978c9a314bd8dc99be594bc3c175faaa9794be04a5a5e153caba6915336cebac" -dependencies = [ - "thiserror-impl", -] - -[[package]] -name = "thiserror-impl" -version = "1.0.40" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9456a42c5b0d803c8cd86e73dd7cc9edd429499f37a3550d286d5e86720569f" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.32", -] - -[[package]] -name = "time" -version = "0.3.36" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5dfd88e563464686c916c7e46e623e520ddc6d79fa6641390f2e3fa86e83e885" -dependencies = [ - "deranged", - "itoa", - "num-conv", - "powerfmt", - "serde", - "time-core", - "time-macros", -] - -[[package]] -name = "time-core" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef927ca75afb808a4d64dd374f00a2adf8d0fcff8e7b184af886c3c87ec4a3f3" - -[[package]] -name = "time-macros" -version = "0.2.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f252a68540fde3a3877aeea552b832b40ab9a69e318efd078774a01ddee1ccf" -dependencies = [ - "num-conv", - "time-core", -] - -[[package]] -name = "turshi" -version = "0.1.0" -dependencies = [ - "ark-ff", - "hex", - "o1-utils", -] - -[[package]] -name = "typenum" -version = "1.17.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "42ff0bf0c66b8238c6f3b578df37d0b7848e55df8577b3f74f92a69acceeb825" - -[[package]] -name = "unicode-ident" -version = "1.0.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b" - -[[package]] -name = "version_check" -version = "0.9.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" - -[[package]] -name = "wasi" -version = "0.11.0+wasi-snapshot-preview1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" - -[[package]] -name = "wasm-bindgen" -version = "0.2.87" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7706a72ab36d8cb1f80ffbf0e071533974a60d0a308d01a5d0375bf60499a342" -dependencies = [ - "cfg-if", - "wasm-bindgen-macro", -] - -[[package]] -name = "wasm-bindgen-backend" -version = "0.2.87" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ef2b6d3c510e9625e5fe6f509ab07d66a760f0885d858736483c32ed7809abd" -dependencies = [ - "bumpalo", - "log", - "once_cell", - "proc-macro2", - "quote", - "syn 2.0.32", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-futures" -version = "0.4.37" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c02dbc21516f9f1f04f187958890d7e6026df8d16540b7ad9492bc34a67cea03" -dependencies = [ - "cfg-if", - "js-sys", - "wasm-bindgen", - "web-sys", -] - -[[package]] -name = "wasm-bindgen-macro" -version = "0.2.87" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dee495e55982a3bd48105a7b947fd2a9b4a8ae3010041b9e0faab3f9cd028f1d" -dependencies = [ - "quote", - "wasm-bindgen-macro-support", -] - -[[package]] -name = "wasm-bindgen-macro-support" -version = "0.2.87" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "54681b18a46765f095758388f2d0cf16eb8d4169b639ab575a8f5693af210c7b" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.32", - "wasm-bindgen-backend", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-shared" -version = "0.2.87" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca6ad05a4870b2bf5fe995117d3728437bd27d7cd5f06f13c17443ef369775a1" - -[[package]] -name = "wasm-bindgen-test" -version = "0.3.37" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e6e302a7ea94f83a6d09e78e7dc7d9ca7b186bc2829c24a22d0753efd680671" -dependencies = [ - "console_error_panic_hook", - "js-sys", - "scoped-tls", - "wasm-bindgen", - "wasm-bindgen-futures", - "wasm-bindgen-test-macro", -] - -[[package]] -name = "wasm-bindgen-test-macro" -version = "0.3.37" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ecb993dd8c836930ed130e020e77d9b2e65dd0fbab1b67c790b0f5d80b11a575" -dependencies = [ - "proc-macro2", - "quote", -] - -[[package]] -name = "web-sys" -version = "0.3.64" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b85cbef8c220a6abc02aefd892dfc0fc23afb1c6a426316ec33253a3877249b" -dependencies = [ - "js-sys", - "wasm-bindgen", -] - -[[package]] -name = "windows-core" -version = "0.51.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1f8cf84f35d2db49a46868f947758c7a1138116f7fac3bc844f43ade1292e64" -dependencies = [ - "windows-targets", -] - -[[package]] -name = "windows-targets" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" -dependencies = [ - "windows_aarch64_gnullvm", - "windows_aarch64_msvc", - "windows_i686_gnu", - "windows_i686_msvc", - "windows_x86_64_gnu", - "windows_x86_64_gnullvm", - "windows_x86_64_msvc", -] - -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" - -[[package]] -name = "windows_aarch64_msvc" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" - -[[package]] -name = "windows_i686_gnu" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" - -[[package]] -name = "windows_i686_msvc" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" - -[[package]] -name = "windows_x86_64_gnu" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" - -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" - -[[package]] -name = "zerocopy" -version = "0.7.35" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b9b4fd18abc82b8136838da5d50bae7bdea537c574d8dc1a34ed098d6c166f0" -dependencies = [ - "zerocopy-derive", -] - -[[package]] -name = "zerocopy-derive" -version = "0.7.35" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.32", -] - -[[package]] -name = "zeroize" -version = "1.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a0956f1ba7c7909bfb66c2e9e4124ab6f6482560f6628b5aaeba39207c9aad9" -dependencies = [ - "zeroize_derive", -] - -[[package]] -name = "zeroize_derive" -version = "1.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce36e65b0d2999d2aafac989fb249189a141aee1f53c612c1f37d72631959f69" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.32", -] diff --git a/src/lib/crypto/kimchi_bindings/wasm/Cargo.toml b/src/lib/crypto/kimchi_bindings/wasm/Cargo.toml deleted file mode 100644 index 1be61923e36..00000000000 --- a/src/lib/crypto/kimchi_bindings/wasm/Cargo.toml +++ /dev/null @@ -1,92 +0,0 @@ -[package] -name = "plonk_wasm" -version = "0.1.0" -authors = ["opensource@o1labs.org"] -description = "WASM stubs for plonk proof systems" -repository = "https://github.com/MinaProtocol/mina" -license = "MIT/Apache-2.0" -edition = "2018" - -[lib] -name = "plonk_wasm" -crate-type = ["cdylib"] - -################################# Dependencies ################################ - -[dependencies] -array-init = "2.0.0" -base64 = "0.13.0" -console_error_panic_hook = { version = "0.1.6" } -getrandom = { version = "0.2", features = ["js"] } -js-sys = "0.3" -libc = "0.2.62" -num-bigint = { version = "0.4.0" } -once_cell = "1.10.0" -paste = "1.0.5" -# Version for proc-macro2 needs to be 1.0.60+ to be compatible with newer rust -# versions https://github.com/rust-lang/rust/issues/113152 -proc-macro2 = { version = "=1.0.66", features = ["default", "proc-macro"] } -quote = "1.0.31" -rand = { version = "0.8.0" } -rayon = { version = "1" } -rmp-serde = "1.0.0" -sprs = { version = "0.11.0" } -spmc = { version = "0.3.0" } -serde = "1.0.171" -serde_json = "1.0.103" -serde_with = ">=2.1.0" -serde-wasm-bindgen = ">=0.4" -# Check it is up-to-date with the version in proof-systems/Cargo.toml -wasm-bindgen = { version = "=0.2.87" } -web-sys = { version = "0.3.35", features = [ - "Window", - "Document", - "HtmlElement", - "Text", - "Node", - "Element", -] } - -# arkworks -ark-ec = { version = "0.4.2", features = ["parallel"] } -ark-ff = { version = "0.4.2", features = ["parallel", "asm"] } -ark-poly = { version = "0.4.2", features = ["parallel"] } -ark-serialize = "0.4.2" - -# proof-systems -groupmap = { path = "../../proof-systems/groupmap" } -kimchi = { path = "../../proof-systems/kimchi", features = ["wasm_types"] } -mina-curves = { path = "../../proof-systems/curves" } -mina-poseidon = { path = "../../proof-systems/poseidon" } -o1-utils = { path = "../../proof-systems/utils" } -poly-commitment = { path = "../../proof-systems/poly-commitment" } - -[dev-dependencies] -wasm-bindgen-test = ">=0.3.0" - -[profile.release] -debug = true - -[features] -nodejs = [] - -[package.metadata.wasm-pack.profile.release] -wasm-opt = false -#wasm-opt = ["-O4", "--detect-features", "--enable-mutable-globals" ] -#wasm-opt = ["-O4", "--enable-mutable-globals"] - -[build] -rustflags = [ - "-C", - "target-feature=+atomics,+bulk-memory", - "-C", - "link-arg=--no-check-features", -] - -[target.wasm32-unknown-unknown] -rustflags = [ - "-C", - "target-feature=+atomics,+bulk-memory", - "-C", - "link-arg=--no-check-features", -] diff --git a/src/lib/crypto/kimchi_bindings/wasm/README.md b/src/lib/crypto/kimchi_bindings/wasm/README.md deleted file mode 100644 index 4cf6353e13f..00000000000 --- a/src/lib/crypto/kimchi_bindings/wasm/README.md +++ /dev/null @@ -1,34 +0,0 @@ -# Kimchi WASM - -This code allows us to compile parts of Kimchi into [Web Assembly (WASM)](https://webassembly.org/). - -## Requirements - -For this to work, you will need to install the following dependencies: - -- [wasm-pack](https://rustwasm.github.io/wasm-pack/installer/) -- [wasm-bindgen-cli](https://rustwasm.github.io/docs/wasm-bindgen/reference/cli.html) (optional) - -## Usage - -To build for nodejs: - -```console -$ wasm-pack build --mode no-install --target nodejs --out-dir ./nodejs ./. -- --features nodejs -``` - -To build for web browsers: - -```console -$ wasm-pack build --mode no-install --target web --out-dir ./web ./. -``` - -Note that optimized versions of these commands are available in: - -- [/src/lib/crypto/kimchi_bindings/js/node_js/build.sh](/src/lib/crypto/kimchi_bindings/js/node_js/build.sh) (also called from the `dune` file in the same folder) -- [/src/lib/crypto/kimchi_bindings/js/web/build.sh](/src/lib/crypto/kimchi_bindings/js/web/build.sh) (also called from the `dune` file in the same folder) - -## Resources - -- [Rust WASM book](https://rustwasm.github.io/docs/book/game-of-life/hello-world.html) -- [WASM-bindgen book](https://rustwasm.github.io/docs/wasm-bindgen/) diff --git a/src/lib/crypto/kimchi_bindings/wasm/dune b/src/lib/crypto/kimchi_bindings/wasm/dune deleted file mode 100644 index 1e073fbe82f..00000000000 --- a/src/lib/crypto/kimchi_bindings/wasm/dune +++ /dev/null @@ -1,3 +0,0 @@ -(data_only_dirs src) - -(dirs :standard \ target) diff --git a/src/lib/crypto/kimchi_bindings/wasm/rust-toolchain.toml b/src/lib/crypto/kimchi_bindings/wasm/rust-toolchain.toml deleted file mode 100644 index b04d9639e65..00000000000 --- a/src/lib/crypto/kimchi_bindings/wasm/rust-toolchain.toml +++ /dev/null @@ -1,6 +0,0 @@ -# A nightly is necessary to enable the use of #![feature] -[toolchain] -# This should stay in line with the versions in -# - kimchi_bindings/js/node_js/build.sh -# - kimchi_bindings/js/web/build.sh -channel = "nightly-2023-09-01" # roughly matches 1.72 diff --git a/src/lib/crypto/kimchi_bindings/wasm/src/arkworks/bigint_256.rs b/src/lib/crypto/kimchi_bindings/wasm/src/arkworks/bigint_256.rs deleted file mode 100644 index 9fd2e7aa2d0..00000000000 --- a/src/lib/crypto/kimchi_bindings/wasm/src/arkworks/bigint_256.rs +++ /dev/null @@ -1,143 +0,0 @@ -use ark_ff::{BigInt, BigInteger as ark_BigInteger, BigInteger256}; -use ark_serialize::{CanonicalDeserialize, CanonicalSerialize, Write}; -use num_bigint::BigUint; -use std::cmp::Ordering::{Equal, Greater, Less}; -use std::convert::TryInto; -use wasm_bindgen::convert::{FromWasmAbi, IntoWasmAbi}; -use wasm_bindgen::prelude::*; - -// -// Handy constants -// - -const BIGINT256_NUM_BITS: i32 = 256; -const BIGINT256_LIMB_BITS: i32 = 64; -const BIGINT256_LIMB_BYTES: i32 = BIGINT256_LIMB_BITS / 8; -const BIGINT256_NUM_LIMBS: i32 = - (BIGINT256_NUM_BITS + BIGINT256_LIMB_BITS - 1) / BIGINT256_LIMB_BITS; -const BIGINT256_NUM_BYTES: usize = (BIGINT256_NUM_LIMBS as usize) * 8; - -pub struct WasmBigInteger256(pub BigInteger256); - -impl wasm_bindgen::describe::WasmDescribe for WasmBigInteger256 { - fn describe() { - as wasm_bindgen::describe::WasmDescribe>::describe() - } -} - -impl FromWasmAbi for WasmBigInteger256 { - type Abi = as FromWasmAbi>::Abi; - unsafe fn from_abi(js: Self::Abi) -> Self { - let bytes: Vec = FromWasmAbi::from_abi(js); - // TODO this used FromBytes before arkworks 0.4.2, check serialization is consistent after update - WasmBigInteger256(BigInteger256::deserialize_compressed(bytes.as_slice()).unwrap()) - } -} - -impl IntoWasmAbi for WasmBigInteger256 { - type Abi = as FromWasmAbi>::Abi; - fn into_abi(self) -> Self::Abi { - let mut bytes: Vec = vec![]; - bytes.write_all(self.0.to_bytes_le().as_slice()).unwrap(); - bytes.into_abi() - } -} - -pub fn to_biguint(x: &BigInteger256) -> BigUint { - let x_ = x.0.as_ptr() as *const u8; - let x_ = unsafe { std::slice::from_raw_parts(x_, BIGINT256_NUM_BYTES) }; - num_bigint::BigUint::from_bytes_le(x_) -} - -pub fn of_biguint(x: &BigUint) -> BigInteger256 { - let mut bytes = x.to_bytes_le(); - bytes.resize(BIGINT256_NUM_BYTES, 0); - let limbs = bytes.as_ptr(); - let limbs = limbs as *const [u64; BIGINT256_NUM_LIMBS as usize]; - let limbs = unsafe { &(*limbs) }; - BigInt(*limbs) -} - -#[wasm_bindgen] -pub fn caml_bigint_256_of_numeral(s: String, _len: u32, base: u32) -> WasmBigInteger256 { - match BigUint::parse_bytes(&s.into_bytes(), base) { - Some(data) => WasmBigInteger256(of_biguint(&data)), - None => panic!("caml_bigint_256_of_numeral"), - } -} - -#[wasm_bindgen] -pub fn caml_bigint_256_of_decimal_string(s: String) -> WasmBigInteger256 { - match BigUint::parse_bytes(&s.into_bytes(), 10) { - Some(data) => WasmBigInteger256(of_biguint(&data)), - None => panic!("caml_bigint_256_of_decimal_string"), - } -} - -#[wasm_bindgen] -pub fn caml_bigint_256_num_limbs() -> i32 { - BIGINT256_NUM_LIMBS -} - -#[wasm_bindgen] -pub fn caml_bigint_256_bytes_per_limb() -> i32 { - BIGINT256_LIMB_BYTES -} - -#[wasm_bindgen] -pub fn caml_bigint_256_div(x: WasmBigInteger256, y: WasmBigInteger256) -> WasmBigInteger256 { - let res: BigUint = to_biguint(&x.0) / to_biguint(&y.0); - WasmBigInteger256(of_biguint(&res)) -} - -#[wasm_bindgen] -pub fn caml_bigint_256_compare(x: WasmBigInteger256, y: WasmBigInteger256) -> i8 { - match x.0.cmp(&y.0) { - Less => -1, - Equal => 0, - Greater => 1, - } -} - -#[wasm_bindgen] -pub fn caml_bigint_256_print(x: WasmBigInteger256) { - println!("{}", to_biguint(&x.0)); -} - -#[wasm_bindgen] -pub fn caml_bigint_256_to_string(x: WasmBigInteger256) -> String { - to_biguint(&x.0).to_string() -} - -#[wasm_bindgen] -pub fn caml_bigint_256_test_bit(x: WasmBigInteger256, i: i32) -> bool { - match i.try_into() { - Ok(i) => x.0.get_bit(i), - Err(_) => panic!("caml_bigint_256_test_bit"), - } -} - -#[wasm_bindgen] -pub fn caml_bigint_256_to_bytes(x: WasmBigInteger256) -> Vec { - let mut serialized_bytes = vec![]; - x.0.serialize_compressed(&mut serialized_bytes) - .expect("serialize failed"); - serialized_bytes -} - -#[wasm_bindgen] -pub fn caml_bigint_256_of_bytes(x: &[u8]) -> WasmBigInteger256 { - let len = std::mem::size_of::(); - if x.len() != len { - panic!("caml_bigint_256_of_bytes"); - }; - // TODO this used FromBytes before arkworks 0.4.2, check serialization is consistent after update - WasmBigInteger256( - BigInteger256::deserialize_compressed(&mut &x[..]).expect("deserialization error"), - ) -} - -#[wasm_bindgen] -pub fn caml_bigint_256_deep_copy(x: WasmBigInteger256) -> WasmBigInteger256 { - x -} diff --git a/src/lib/crypto/kimchi_bindings/wasm/src/arkworks/group_affine.rs b/src/lib/crypto/kimchi_bindings/wasm/src/arkworks/group_affine.rs deleted file mode 100644 index 07e5971d207..00000000000 --- a/src/lib/crypto/kimchi_bindings/wasm/src/arkworks/group_affine.rs +++ /dev/null @@ -1,220 +0,0 @@ -use crate::arkworks::pasta_fp::WasmPastaFp; -use crate::arkworks::pasta_fq::WasmPastaFq; -use mina_curves::pasta::{ - curves::{ - pallas::G_GENERATOR_X as GeneratorPallasX, pallas::G_GENERATOR_Y as GeneratorPallasY, - vesta::G_GENERATOR_X as GeneratorVestaX, vesta::G_GENERATOR_Y as GeneratorVestaY, - }, - Pallas as AffinePallas, Vesta as AffineVesta, -}; -use wasm_bindgen::prelude::*; - -// -// handy types -// - -#[wasm_bindgen] -#[derive(Clone, Copy, Debug)] -pub struct WasmGPallas { - pub x: WasmPastaFp, - pub y: WasmPastaFp, - pub infinity: bool, -} - -#[wasm_bindgen] -#[derive(Clone, Copy, Debug)] -pub struct WasmGVesta { - pub x: WasmPastaFq, - pub y: WasmPastaFq, - pub infinity: bool, -} - -// Conversions from/to AffineVesta - -impl From for WasmGVesta { - fn from(point: AffineVesta) -> Self { - WasmGVesta { - x: point.x.into(), - y: point.y.into(), - infinity: point.infinity, - } - } -} - -impl From<&AffineVesta> for WasmGVesta { - fn from(point: &AffineVesta) -> Self { - WasmGVesta { - x: point.x.into(), - y: point.y.into(), - infinity: point.infinity, - } - } -} - -impl From for AffineVesta { - fn from(point: WasmGVesta) -> Self { - AffineVesta { - x: point.x.into(), - y: point.y.into(), - infinity: point.infinity, - } - } -} - -impl From<&WasmGVesta> for AffineVesta { - fn from(point: &WasmGVesta) -> Self { - AffineVesta { - x: point.x.into(), - y: point.y.into(), - infinity: point.infinity, - } - } -} - -// Conversion from/to AffinePallas - -impl From for WasmGPallas { - fn from(point: AffinePallas) -> Self { - WasmGPallas { - x: point.x.into(), - y: point.y.into(), - infinity: point.infinity, - } - } -} - -impl From<&AffinePallas> for WasmGPallas { - fn from(point: &AffinePallas) -> Self { - WasmGPallas { - x: point.x.into(), - y: point.y.into(), - infinity: point.infinity, - } - } -} - -impl From for AffinePallas { - fn from(point: WasmGPallas) -> Self { - AffinePallas { - x: point.x.into(), - y: point.y.into(), - infinity: point.infinity, - } - } -} - -impl From<&WasmGPallas> for AffinePallas { - fn from(point: &WasmGPallas) -> Self { - AffinePallas { - x: point.x.into(), - y: point.y.into(), - infinity: point.infinity, - } - } -} - -#[wasm_bindgen] -pub fn caml_pallas_affine_one() -> WasmGPallas { - WasmGPallas { - x: WasmPastaFp::from(GeneratorPallasX), - y: WasmPastaFp::from(GeneratorPallasY), - infinity: false, - } -} - -#[wasm_bindgen] -pub fn caml_vesta_affine_one() -> WasmGVesta { - WasmGVesta { - x: WasmPastaFq::from(GeneratorVestaX), - y: WasmPastaFq::from(GeneratorVestaY), - infinity: false, - } -} - -/* -#[wasm_bindgen] -pub fn caml_pasta_pallas_one() -> WasmPallasGProjective { - ProjectivePallas::prime_subgroup_generator().into() -} - -#[wasm_bindgen] -pub fn caml_pasta_pallas_add( - x: &WasmPallasGProjective, - y: &WasmPallasGProjective, -) -> WasmPallasGProjective { - (**x + **y).into() -} - -#[wasm_bindgen] -pub fn caml_pasta_pallas_sub( - x: &WasmPallasGProjective, - y: &WasmPallasGProjective, -) -> WasmPallasGProjective { - (**x - **y).into() -} - -#[wasm_bindgen] -pub fn caml_pasta_pallas_negate(x: &WasmPallasGProjective) -> WasmPallasGProjective { - (-(**x)).into() -} - -#[wasm_bindgen] -pub fn caml_pasta_pallas_double(x: &WasmPallasGProjective) -> WasmPallasGProjective { - (x.double()).into() -} - -#[wasm_bindgen] -pub fn caml_pasta_pallas_scale(x: &WasmPallasGProjective, y: WasmPastaFq) -> WasmPallasGProjective { - (x.mul(y.0)).into() -} - -#[wasm_bindgen] -pub fn caml_pasta_pallas_random() -> WasmPallasGProjective { - let rng = &mut rand_core::OsRng; - WasmPallasGProjective(UniformRand::rand(rng)) -} - -#[wasm_bindgen] -pub fn caml_pasta_pallas_rng(i: u32) -> WasmPallasGProjective { - let i: u64 = i.into(); - let mut rng: StdRng = rand::SeedableRng::seed_from_u64(i); - WasmPallasGProjective(UniformRand::rand(&mut rng)) -} - -#[wasm_bindgen] -pub fn caml_pasta_pallas_endo_base() -> WasmPastaFp { - let (endo_q, _endo_r) = poly_commitment::srs::endos::(); - WasmPastaFp(endo_q) -} - -#[wasm_bindgen] -pub fn caml_pasta_pallas_endo_scalar() -> WasmPastaFq { - let (_endo_q, endo_r) = poly_commitment::srs::endos::(); - WasmPastaFq(endo_r) -} - -#[wasm_bindgen] -pub fn caml_pasta_pallas_to_affine(x: &WasmPallasGProjective) -> WasmPallasGAffine { - Into::<&GProjective>::into(x).into_affine().into() -} - -#[wasm_bindgen] -pub fn caml_pasta_pallas_of_affine(x: &WasmPallasGAffine) -> WasmPallasGProjective { - Into::::into(x).into_projective().into() -} - -#[wasm_bindgen] -pub fn caml_pasta_pallas_of_affine_coordinates(x: WasmPastaFp, y: WasmPastaFp) -> WasmPallasGProjective { - GProjective::new_unchecked(x.0, y.0, Fp::one()).into() -} - -#[wasm_bindgen] -pub fn caml_pasta_pallas_affine_deep_copy(x: &WasmPallasGAffine) -> WasmPallasGAffine { - x.clone() -} - -#[wasm_bindgen] -pub fn caml_pasta_pallas_affine_one() -> WasmPallasGAffine { - GAffine::prime_subgroup_generator().into() -} -*/ diff --git a/src/lib/crypto/kimchi_bindings/wasm/src/arkworks/group_projective.rs b/src/lib/crypto/kimchi_bindings/wasm/src/arkworks/group_projective.rs deleted file mode 100644 index 0af3d3c80ae..00000000000 --- a/src/lib/crypto/kimchi_bindings/wasm/src/arkworks/group_projective.rs +++ /dev/null @@ -1,192 +0,0 @@ -use std::ops::{Add, Deref, Neg, Sub}; -use wasm_bindgen::prelude::*; - -use mina_curves::pasta::{ProjectivePallas, ProjectiveVesta}; - -// Pallas -#[wasm_bindgen] -#[derive(Clone, Copy)] -pub struct WasmPallasGProjective(ProjectivePallas); - -impl AsRef for WasmPallasGProjective { - fn as_ref(&self) -> &WasmPallasGProjective { - self - } -} - -impl Deref for WasmPallasGProjective { - type Target = ProjectivePallas; - - fn deref(&self) -> &Self::Target { - &self.0 - } -} - -// Handy implementations - -impl From for WasmPallasGProjective { - fn from(x: ProjectivePallas) -> Self { - WasmPallasGProjective(x) - } -} - -impl From<&ProjectivePallas> for WasmPallasGProjective { - fn from(x: &ProjectivePallas) -> Self { - WasmPallasGProjective(*x) - } -} - -impl From for ProjectivePallas { - fn from(x: WasmPallasGProjective) -> Self { - x.0 - } -} - -impl From<&WasmPallasGProjective> for ProjectivePallas { - fn from(x: &WasmPallasGProjective) -> Self { - x.0 - } -} - -impl Add for WasmPallasGProjective { - type Output = Self; - - fn add(self, other: Self) -> Self { - Self(self.0 + other.0) - } -} - -impl Add for &WasmPallasGProjective { - type Output = WasmPallasGProjective; - - fn add(self, other: Self) -> Self::Output { - WasmPallasGProjective(self.0 + other.0) - } -} - -impl Sub for WasmPallasGProjective { - type Output = WasmPallasGProjective; - - fn sub(self, other: Self) -> Self::Output { - WasmPallasGProjective(self.0 - other.0) - } -} - -impl Sub for &WasmPallasGProjective { - type Output = WasmPallasGProjective; - - fn sub(self, other: Self) -> Self::Output { - WasmPallasGProjective(self.0 - other.0) - } -} - -impl Neg for WasmPallasGProjective { - type Output = WasmPallasGProjective; - - fn neg(self) -> Self::Output { - WasmPallasGProjective(-self.0) - } -} - -impl Neg for &WasmPallasGProjective { - type Output = WasmPallasGProjective; - - fn neg(self) -> Self::Output { - WasmPallasGProjective(-self.0) - } -} - -// Vesta - -#[wasm_bindgen] -#[derive(Clone, Copy)] -pub struct WasmVestaGProjective(ProjectiveVesta); - -impl AsRef for WasmVestaGProjective { - fn as_ref(&self) -> &WasmVestaGProjective { - self - } -} - -impl Deref for WasmVestaGProjective { - type Target = ProjectiveVesta; - - fn deref(&self) -> &Self::Target { - &self.0 - } -} - -// -// Handy implementations -// - -impl From for WasmVestaGProjective { - fn from(x: ProjectiveVesta) -> Self { - WasmVestaGProjective(x) - } -} - -impl From<&ProjectiveVesta> for WasmVestaGProjective { - fn from(x: &ProjectiveVesta) -> Self { - WasmVestaGProjective(*x) - } -} - -impl From for ProjectiveVesta { - fn from(x: WasmVestaGProjective) -> Self { - x.0 - } -} - -impl From<&WasmVestaGProjective> for ProjectiveVesta { - fn from(x: &WasmVestaGProjective) -> Self { - x.0 - } -} - -impl Add for WasmVestaGProjective { - type Output = Self; - - fn add(self, other: Self) -> Self { - Self(self.0 + other.0) - } -} -impl Add for &WasmVestaGProjective { - type Output = WasmVestaGProjective; - - fn add(self, other: Self) -> Self::Output { - WasmVestaGProjective(self.0 + other.0) - } -} - -impl Sub for WasmVestaGProjective { - type Output = WasmVestaGProjective; - - fn sub(self, other: Self) -> Self::Output { - WasmVestaGProjective(self.0 - other.0) - } -} - -impl Sub for &WasmVestaGProjective { - type Output = WasmVestaGProjective; - - fn sub(self, other: Self) -> Self::Output { - WasmVestaGProjective(self.0 - other.0) - } -} - -impl Neg for WasmVestaGProjective { - type Output = WasmVestaGProjective; - - fn neg(self) -> Self::Output { - WasmVestaGProjective(-self.0) - } -} - -impl Neg for &WasmVestaGProjective { - type Output = WasmVestaGProjective; - - fn neg(self) -> Self::Output { - WasmVestaGProjective(-self.0) - } -} diff --git a/src/lib/crypto/kimchi_bindings/wasm/src/arkworks/mod.rs b/src/lib/crypto/kimchi_bindings/wasm/src/arkworks/mod.rs deleted file mode 100644 index b1d5af216c6..00000000000 --- a/src/lib/crypto/kimchi_bindings/wasm/src/arkworks/mod.rs +++ /dev/null @@ -1,32 +0,0 @@ -//! This module contains wrapper types to Arkworks types. -//! To use Arkwork types in OCaml, you have to convert to these types, -//! and convert back from them to use them in Rust. -//! -//! For example: -//! -//! ``` -//! use marlin_plonk_bindings::arkworks::CamlBiginteger256; -//! use ark_ff::BigInteger256; -//! -//! #[ocaml::func] -//! pub fn caml_add(x: CamlBigInteger256, y: CamlBigInteger256) -> CamlBigInteger256 { -//! let x: BigInteger256 = x.into(); -//! let y: BigInteger256 = y.into(); -//! (x + y).into() -//! } -//! ``` -//! - -pub mod bigint_256; -pub mod group_affine; -pub mod group_projective; -pub mod pasta_fp; -pub mod pasta_fq; - -// re-export what's important - -pub use bigint_256::WasmBigInteger256; -pub use group_affine::{WasmGPallas, WasmGVesta}; -pub use group_projective::{WasmPallasGProjective, WasmVestaGProjective}; -pub use pasta_fp::WasmPastaFp; -pub use pasta_fq::WasmPastaFq; diff --git a/src/lib/crypto/kimchi_bindings/wasm/src/arkworks/pasta_fp.rs b/src/lib/crypto/kimchi_bindings/wasm/src/arkworks/pasta_fp.rs deleted file mode 100644 index c8d2c7f0aaf..00000000000 --- a/src/lib/crypto/kimchi_bindings/wasm/src/arkworks/pasta_fp.rs +++ /dev/null @@ -1,245 +0,0 @@ -use crate::arkworks::bigint_256::{self, WasmBigInteger256}; -use ark_ff::{ - fields::{Field, PrimeField}, - FftField, One, UniformRand, Zero, -}; -use ark_poly::{EvaluationDomain, Radix2EvaluationDomain as Domain}; -use ark_serialize::{CanonicalDeserialize, CanonicalSerialize}; -use mina_curves::pasta::fields::fft::FpParameters; -use mina_curves::pasta::{fields::fp::FpParameters as Fp_params, Fp}; -use num_bigint::BigUint; -use rand::rngs::StdRng; -use std::cmp::Ordering::{Equal, Greater, Less}; -use wasm_bindgen::convert::{FromWasmAbi, IntoWasmAbi, OptionFromWasmAbi, OptionIntoWasmAbi}; -use wasm_bindgen::prelude::*; - -#[repr(C)] -#[derive(Clone, Copy, Debug)] -pub struct WasmPastaFp(pub Fp); - -impl crate::wasm_flat_vector::FlatVectorElem for WasmPastaFp { - const FLATTENED_SIZE: usize = std::mem::size_of::(); - fn flatten(self) -> Vec { - let mut bytes: Vec = Vec::with_capacity(Self::FLATTENED_SIZE); - self.0.serialize_compressed(&mut bytes).unwrap(); - bytes - } - fn unflatten(flat: Vec) -> Self { - WasmPastaFp(Fp::deserialize_compressed(flat.as_slice()).unwrap()) - } -} - -impl From for WasmPastaFp { - fn from(x: Fp) -> Self { - WasmPastaFp(x) - } -} - -impl From for Fp { - fn from(x: WasmPastaFp) -> Self { - x.0 - } -} - -impl<'a> From<&'a WasmPastaFp> for &'a Fp { - fn from(x: &'a WasmPastaFp) -> Self { - &x.0 - } -} - -impl wasm_bindgen::describe::WasmDescribe for WasmPastaFp { - fn describe() { - as wasm_bindgen::describe::WasmDescribe>::describe() - } -} - -impl FromWasmAbi for WasmPastaFp { - type Abi = as FromWasmAbi>::Abi; - unsafe fn from_abi(js: Self::Abi) -> Self { - let bytes: Vec = FromWasmAbi::from_abi(js); - WasmPastaFp(Fp::deserialize_compressed(bytes.as_slice()).unwrap()) - } -} - -impl IntoWasmAbi for WasmPastaFp { - type Abi = as FromWasmAbi>::Abi; - fn into_abi(self) -> Self::Abi { - let mut bytes: Vec = vec![]; - self.0.serialize_compressed(&mut bytes).unwrap(); - bytes.into_abi() - } -} - -impl OptionIntoWasmAbi for WasmPastaFp { - fn none() -> Self::Abi { - as OptionIntoWasmAbi>::none() - } -} - -impl OptionFromWasmAbi for WasmPastaFp { - fn is_none(abi: &Self::Abi) -> bool { - as OptionFromWasmAbi>::is_none(abi) - } -} - -#[wasm_bindgen] -pub fn caml_pasta_fp_size_in_bits() -> isize { - Fp_params::MODULUS_BITS as isize -} - -#[wasm_bindgen] -pub fn caml_pasta_fp_size() -> WasmBigInteger256 { - WasmBigInteger256(Fp_params::MODULUS) -} - -#[wasm_bindgen] -pub fn caml_pasta_fp_add(x: WasmPastaFp, y: WasmPastaFp) -> WasmPastaFp { - WasmPastaFp(x.0 + y.0) -} - -#[wasm_bindgen] -pub fn caml_pasta_fp_sub(x: WasmPastaFp, y: WasmPastaFp) -> WasmPastaFp { - WasmPastaFp(x.0 - y.0) -} - -#[wasm_bindgen] -pub fn caml_pasta_fp_negate(x: WasmPastaFp) -> WasmPastaFp { - WasmPastaFp(-x.0) -} - -#[wasm_bindgen] -pub fn caml_pasta_fp_mul(x: WasmPastaFp, y: WasmPastaFp) -> WasmPastaFp { - WasmPastaFp(x.0 * y.0) -} - -#[wasm_bindgen] -pub fn caml_pasta_fp_div(x: WasmPastaFp, y: WasmPastaFp) -> WasmPastaFp { - WasmPastaFp(x.0 / y.0) -} - -#[wasm_bindgen] -pub fn caml_pasta_fp_inv(x: WasmPastaFp) -> Option { - x.0.inverse().map(WasmPastaFp) -} - -#[wasm_bindgen] -pub fn caml_pasta_fp_square(x: WasmPastaFp) -> WasmPastaFp { - WasmPastaFp(x.0.square()) -} - -#[wasm_bindgen] -pub fn caml_pasta_fp_is_square(x: WasmPastaFp) -> bool { - let s = x.0.pow(Fp_params::MODULUS_MINUS_ONE_DIV_TWO); - s.is_zero() || s.is_one() -} - -#[wasm_bindgen] -pub fn caml_pasta_fp_sqrt(x: WasmPastaFp) -> Option { - x.0.sqrt().map(WasmPastaFp) -} - -#[wasm_bindgen] -pub fn caml_pasta_fp_of_int(i: i32) -> WasmPastaFp { - WasmPastaFp(Fp::from(i as u64)) -} - -#[wasm_bindgen] -pub fn caml_pasta_fp_to_string(x: WasmPastaFp) -> String { - bigint_256::to_biguint(&x.0.into_bigint()).to_string() -} - -#[wasm_bindgen] -pub fn caml_pasta_fp_of_string(s: String) -> Result { - let biguint = BigUint::parse_bytes(s.as_bytes(), 10) - .ok_or(JsValue::from_str("caml_pasta_fp_of_string"))?; - - match Fp::from_bigint(bigint_256::of_biguint(&biguint)) { - Some(x) => Ok(x.into()), - None => Err(JsValue::from_str("caml_pasta_fp_of_string")), - } -} - -#[wasm_bindgen] -pub fn caml_pasta_fp_print(x: WasmPastaFp) { - println!("{}", bigint_256::to_biguint(&(x.0.into_bigint()))); -} - -#[wasm_bindgen] -pub fn caml_pasta_fp_compare(x: WasmPastaFp, y: WasmPastaFp) -> i32 { - match x.0.cmp(&y.0) { - Less => -1, - Equal => 0, - Greater => 1, - } -} - -#[wasm_bindgen] -pub fn caml_pasta_fp_equal(x: WasmPastaFp, y: WasmPastaFp) -> bool { - x.0 == y.0 -} - -#[wasm_bindgen] -pub fn caml_pasta_fp_random() -> WasmPastaFp { - WasmPastaFp(UniformRand::rand(&mut rand::thread_rng())) -} - -#[wasm_bindgen] -pub fn caml_pasta_fp_rng(i: i32) -> WasmPastaFp { - // We only care about entropy here, so we force a conversion i32 -> u32. - let i: u64 = (i as u32).into(); - let mut rng: StdRng = rand::SeedableRng::seed_from_u64(i); - WasmPastaFp(UniformRand::rand(&mut rng)) -} - -#[wasm_bindgen] -pub fn caml_pasta_fp_to_bigint(x: WasmPastaFp) -> WasmBigInteger256 { - WasmBigInteger256(x.0.into_bigint()) -} - -#[wasm_bindgen] -pub fn caml_pasta_fp_of_bigint(x: WasmBigInteger256) -> Result { - match Fp::from_bigint(x.0) { - Some(x) => Ok(x.into()), - None => Err(JsValue::from_str("caml_pasta_fp_of_bigint")), - } -} - -#[wasm_bindgen] -pub fn caml_pasta_fp_two_adic_root_of_unity() -> WasmPastaFp { - WasmPastaFp(::TWO_ADIC_ROOT_OF_UNITY) -} - -#[wasm_bindgen] -pub fn caml_pasta_fp_domain_generator(log2_size: i32) -> WasmPastaFp { - match Domain::new(1 << log2_size) { - Some(x) => WasmPastaFp(x.group_gen), - None => panic!("caml_pasta_fp_domain_generator"), - } -} - -#[wasm_bindgen] -pub fn caml_pasta_fp_to_bytes(x: WasmPastaFp) -> Vec { - let len = std::mem::size_of::(); - let mut str: Vec = Vec::with_capacity(len); - str.resize(len, 0); - let str_as_fp: *mut Fp = str.as_mut_ptr().cast::(); - unsafe { - *str_as_fp = x.0; - } - str -} - -#[wasm_bindgen] -pub fn caml_pasta_fp_of_bytes(x: &[u8]) -> WasmPastaFp { - let len = std::mem::size_of::(); - if x.len() != len { - panic!("caml_pasta_fp_of_bytes"); - }; - let x = unsafe { *(x.as_ptr() as *const Fp) }; - WasmPastaFp(x) -} - -#[wasm_bindgen] -pub fn caml_pasta_fp_deep_copy(x: WasmPastaFp) -> WasmPastaFp { - x -} diff --git a/src/lib/crypto/kimchi_bindings/wasm/src/arkworks/pasta_fq.rs b/src/lib/crypto/kimchi_bindings/wasm/src/arkworks/pasta_fq.rs deleted file mode 100644 index 229cea96bbc..00000000000 --- a/src/lib/crypto/kimchi_bindings/wasm/src/arkworks/pasta_fq.rs +++ /dev/null @@ -1,245 +0,0 @@ -use crate::arkworks::bigint_256::{self, WasmBigInteger256}; -use ark_ff::{ - fields::{Field, PrimeField}, - FftField, One, UniformRand, Zero, -}; -use ark_poly::{EvaluationDomain, Radix2EvaluationDomain as Domain}; -use ark_serialize::{CanonicalDeserialize, CanonicalSerialize}; -use mina_curves::pasta::fields::fft::FpParameters; -use mina_curves::pasta::{fields::fq::FqParameters as Fq_params, Fq}; -use num_bigint::BigUint; -use rand::rngs::StdRng; -use std::cmp::Ordering::{Equal, Greater, Less}; -use wasm_bindgen::convert::{FromWasmAbi, IntoWasmAbi, OptionFromWasmAbi, OptionIntoWasmAbi}; -use wasm_bindgen::prelude::*; - -#[repr(C)] -#[derive(Clone, Copy, Debug)] -pub struct WasmPastaFq(pub Fq); - -impl crate::wasm_flat_vector::FlatVectorElem for WasmPastaFq { - const FLATTENED_SIZE: usize = std::mem::size_of::(); - fn flatten(self) -> Vec { - let mut bytes: Vec = Vec::with_capacity(Self::FLATTENED_SIZE); - self.0.serialize_compressed(&mut bytes).unwrap(); - bytes - } - fn unflatten(flat: Vec) -> Self { - WasmPastaFq(Fq::deserialize_compressed(flat.as_slice()).unwrap()) - } -} - -impl From for WasmPastaFq { - fn from(x: Fq) -> Self { - WasmPastaFq(x) - } -} - -impl From for Fq { - fn from(x: WasmPastaFq) -> Self { - x.0 - } -} - -impl<'a> From<&'a WasmPastaFq> for &'a Fq { - fn from(x: &'a WasmPastaFq) -> Self { - &x.0 - } -} - -impl wasm_bindgen::describe::WasmDescribe for WasmPastaFq { - fn describe() { - as wasm_bindgen::describe::WasmDescribe>::describe() - } -} - -impl FromWasmAbi for WasmPastaFq { - type Abi = as FromWasmAbi>::Abi; - unsafe fn from_abi(js: Self::Abi) -> Self { - let bytes: Vec = FromWasmAbi::from_abi(js); - WasmPastaFq(Fq::deserialize_compressed(bytes.as_slice()).unwrap()) - } -} - -impl IntoWasmAbi for WasmPastaFq { - type Abi = as FromWasmAbi>::Abi; - fn into_abi(self) -> Self::Abi { - let mut bytes: Vec = vec![]; - self.0.serialize_compressed(&mut bytes).unwrap(); - bytes.into_abi() - } -} - -impl OptionIntoWasmAbi for WasmPastaFq { - fn none() -> Self::Abi { - as OptionIntoWasmAbi>::none() - } -} - -impl OptionFromWasmAbi for WasmPastaFq { - fn is_none(abi: &Self::Abi) -> bool { - as OptionFromWasmAbi>::is_none(abi) - } -} - -#[wasm_bindgen] -pub fn caml_pasta_fq_size_in_bits() -> isize { - Fq_params::MODULUS_BITS as isize -} - -#[wasm_bindgen] -pub fn caml_pasta_fq_size() -> WasmBigInteger256 { - WasmBigInteger256(Fq_params::MODULUS) -} - -#[wasm_bindgen] -pub fn caml_pasta_fq_add(x: WasmPastaFq, y: WasmPastaFq) -> WasmPastaFq { - WasmPastaFq(x.0 + y.0) -} - -#[wasm_bindgen] -pub fn caml_pasta_fq_sub(x: WasmPastaFq, y: WasmPastaFq) -> WasmPastaFq { - WasmPastaFq(x.0 - y.0) -} - -#[wasm_bindgen] -pub fn caml_pasta_fq_negate(x: WasmPastaFq) -> WasmPastaFq { - WasmPastaFq(-x.0) -} - -#[wasm_bindgen] -pub fn caml_pasta_fq_mul(x: WasmPastaFq, y: WasmPastaFq) -> WasmPastaFq { - WasmPastaFq(x.0 * y.0) -} - -#[wasm_bindgen] -pub fn caml_pasta_fq_div(x: WasmPastaFq, y: WasmPastaFq) -> WasmPastaFq { - WasmPastaFq(x.0 / y.0) -} - -#[wasm_bindgen] -pub fn caml_pasta_fq_inv(x: WasmPastaFq) -> Option { - x.0.inverse().map(WasmPastaFq) -} - -#[wasm_bindgen] -pub fn caml_pasta_fq_square(x: WasmPastaFq) -> WasmPastaFq { - WasmPastaFq(x.0.square()) -} - -#[wasm_bindgen] -pub fn caml_pasta_fq_is_square(x: WasmPastaFq) -> bool { - let s = x.0.pow(Fq_params::MODULUS_MINUS_ONE_DIV_TWO); - s.is_zero() || s.is_one() -} - -#[wasm_bindgen] -pub fn caml_pasta_fq_sqrt(x: WasmPastaFq) -> Option { - x.0.sqrt().map(WasmPastaFq) -} - -#[wasm_bindgen] -pub fn caml_pasta_fq_of_int(i: i32) -> WasmPastaFq { - WasmPastaFq(Fq::from(i as u64)) -} - -#[wasm_bindgen] -pub fn caml_pasta_fq_to_string(x: WasmPastaFq) -> String { - bigint_256::to_biguint(&x.0.into_bigint()).to_string() -} - -#[wasm_bindgen] -pub fn caml_pasta_fq_of_string(s: String) -> Result { - let biguint = BigUint::parse_bytes(s.as_bytes(), 10) - .ok_or(JsValue::from_str("caml_pasta_fq_of_string"))?; - - match Fq::from_bigint(bigint_256::of_biguint(&biguint)) { - Some(x) => Ok(x.into()), - None => Err(JsValue::from_str("caml_pasta_fq_of_string")), - } -} - -#[wasm_bindgen] -pub fn caml_pasta_fq_print(x: WasmPastaFq) { - println!("{}", bigint_256::to_biguint(&(x.0.into_bigint()))); -} - -#[wasm_bindgen] -pub fn caml_pasta_fq_compare(x: WasmPastaFq, y: WasmPastaFq) -> i32 { - match x.0.cmp(&y.0) { - Less => -1, - Equal => 0, - Greater => 1, - } -} - -#[wasm_bindgen] -pub fn caml_pasta_fq_equal(x: WasmPastaFq, y: WasmPastaFq) -> bool { - x.0 == y.0 -} - -#[wasm_bindgen] -pub fn caml_pasta_fq_random() -> WasmPastaFq { - WasmPastaFq(UniformRand::rand(&mut rand::thread_rng())) -} - -#[wasm_bindgen] -pub fn caml_pasta_fq_rng(i: i32) -> WasmPastaFq { - // We only care about entropy here, so we force a conversion i32 -> u32. - let i: u64 = (i as u32).into(); - let mut rng: StdRng = rand::SeedableRng::seed_from_u64(i); - WasmPastaFq(UniformRand::rand(&mut rng)) -} - -#[wasm_bindgen] -pub fn caml_pasta_fq_to_bigint(x: WasmPastaFq) -> WasmBigInteger256 { - WasmBigInteger256(x.0.into_bigint()) -} - -#[wasm_bindgen] -pub fn caml_pasta_fq_of_bigint(x: WasmBigInteger256) -> Result { - match Fq::from_bigint(x.0) { - Some(x) => Ok(x.into()), - None => Err(JsValue::from_str("caml_pasta_fq_of_bigint")), - } -} - -#[wasm_bindgen] -pub fn caml_pasta_fq_two_adic_root_of_unity() -> WasmPastaFq { - WasmPastaFq(::TWO_ADIC_ROOT_OF_UNITY) -} - -#[wasm_bindgen] -pub fn caml_pasta_fq_domain_generator(log2_size: i32) -> WasmPastaFq { - match Domain::new(1 << log2_size) { - Some(x) => WasmPastaFq(x.group_gen), - None => panic!("caml_pasta_fq_domain_generator"), - } -} - -#[wasm_bindgen] -pub fn caml_pasta_fq_to_bytes(x: WasmPastaFq) -> Vec { - let len = std::mem::size_of::(); - let mut str: Vec = Vec::with_capacity(len); - str.resize(len, 0); - let str_as_fq: *mut Fq = str.as_mut_ptr().cast::(); - unsafe { - *str_as_fq = x.0; - } - str -} - -#[wasm_bindgen] -pub fn caml_pasta_fq_of_bytes(x: &[u8]) -> WasmPastaFq { - let len = std::mem::size_of::(); - if x.len() != len { - panic!("caml_pasta_fq_of_bytes"); - }; - let x = unsafe { *(x.as_ptr() as *const Fq) }; - WasmPastaFq(x) -} - -#[wasm_bindgen] -pub fn caml_pasta_fq_deep_copy(x: WasmPastaFq) -> WasmPastaFq { - x -} diff --git a/src/lib/crypto/kimchi_bindings/wasm/src/circuit.rs b/src/lib/crypto/kimchi_bindings/wasm/src/circuit.rs deleted file mode 100644 index 6d4f389f672..00000000000 --- a/src/lib/crypto/kimchi_bindings/wasm/src/circuit.rs +++ /dev/null @@ -1,36 +0,0 @@ -use ark_ff::PrimeField; -use kimchi::circuits::constraints::ConstraintSystem; -use kimchi::circuits::gate::CircuitGate; -use mina_curves::pasta::Fp; -use serde::Serialize; -use wasm_bindgen::prelude::wasm_bindgen; - -use crate::pasta_fp_plonk_index::WasmPastaFpPlonkIndex; - -#[derive(Serialize)] -struct Circuit -where - F: PrimeField, -{ - public_input_size: usize, - #[serde(bound = "CircuitGate: Serialize")] - gates: Vec>, -} - -impl From<&ConstraintSystem> for Circuit -where - F: PrimeField, -{ - fn from(cs: &ConstraintSystem) -> Self { - Circuit { - public_input_size: cs.public, - gates: cs.gates.clone(), - } - } -} - -#[wasm_bindgen] -pub fn prover_to_json(prover_index: &WasmPastaFpPlonkIndex) -> String { - let circuit: Circuit = (&prover_index.0.cs).into(); - serde_json::to_string(&circuit).expect("couldn't serialize constraints") -} diff --git a/src/lib/crypto/kimchi_bindings/wasm/src/gate_vector.rs b/src/lib/crypto/kimchi_bindings/wasm/src/gate_vector.rs deleted file mode 100644 index ef9bc93da4e..00000000000 --- a/src/lib/crypto/kimchi_bindings/wasm/src/gate_vector.rs +++ /dev/null @@ -1,198 +0,0 @@ -//! A GateVector: this is used to represent a list of gates. - -use crate::wasm_flat_vector::WasmFlatVector; -use kimchi::circuits::{ - gate::GateType, - gate::{Circuit, CircuitGate}, - wires::Wire, -}; -use o1_utils::hasher::CryptoDigest; -use wasm_bindgen::prelude::*; - -use paste::paste; - -#[wasm_bindgen] -#[derive(Clone, Copy, Debug)] -pub struct WasmGateWires( - pub Wire, - pub Wire, - pub Wire, - pub Wire, - pub Wire, - pub Wire, - pub Wire, -); - -#[wasm_bindgen] -impl WasmGateWires { - #[wasm_bindgen(constructor)] - pub fn new(w0: Wire, w1: Wire, w2: Wire, w3: Wire, w4: Wire, w5: Wire, w6: Wire) -> Self { - WasmGateWires(w0, w1, w2, w3, w4, w5, w6) - } -} - -macro_rules! impl_gate_vector { - ($name: ident, - $WasmF: ty, - $F: ty, - $field_name: ident) => { - paste! { - #[wasm_bindgen] - pub struct []( - #[wasm_bindgen(skip)] pub Vec>); - pub type WasmGateVector = []; - - #[wasm_bindgen] - pub struct [] { - pub typ: GateType, // type of the gate - pub wires: WasmGateWires, // gate wires - #[wasm_bindgen(skip)] pub coeffs: Vec<$WasmF>, // constraints vector - } - - #[wasm_bindgen] - impl [] { - #[wasm_bindgen(constructor)] - pub fn new( - typ: GateType, - wires: WasmGateWires, - coeffs: WasmFlatVector<$WasmF>) -> Self { - Self { - typ, - wires, - coeffs: coeffs.into(), - } - } - } - - impl From> for [] - { - fn from(cg: CircuitGate<$F>) -> Self { - Self { - typ: cg.typ, - wires: WasmGateWires( - cg.wires[0], - cg.wires[1], - cg.wires[2], - cg.wires[3], - cg.wires[4], - cg.wires[5], - cg.wires[6]), - coeffs: cg.coeffs.into_iter().map(Into::into).collect(), - } - } - } - - impl From<&CircuitGate<$F>> for [] - { - fn from(cg: &CircuitGate<$F>) -> Self { - Self { - typ: cg.typ, - wires: WasmGateWires( - cg.wires[0], - cg.wires[1], - cg.wires[2], - cg.wires[3], - cg.wires[4], - cg.wires[5], - cg.wires[6]), - coeffs: cg.coeffs.clone().into_iter().map(Into::into).collect(), - } - } - } - - impl From<[]> for CircuitGate<$F> - { - fn from(ccg: []) -> Self { - Self { - typ: ccg.typ, - wires: [ - ccg.wires.0, - ccg.wires.1, - ccg.wires.2, - ccg.wires.3, - ccg.wires.4, - ccg.wires.5, - ccg.wires.6 - ], - coeffs: ccg.coeffs.into_iter().map(Into::into).collect(), - } - } - } - - #[wasm_bindgen] - pub fn []() -> WasmGateVector { - [](Vec::new()) - } - - #[wasm_bindgen] - pub fn []( - v: &mut WasmGateVector, - gate: [], - ) { - let gate: CircuitGate<$F> = gate.into(); - v.0.push(gate); - } - - #[wasm_bindgen] - pub fn []( - v: &WasmGateVector, - i: i32, - ) -> [] { - (&(v.0)[i as usize]).into() - } - - #[wasm_bindgen] - pub fn []( - v: &WasmGateVector, - ) -> usize { - v.0.len() - } - - #[wasm_bindgen] - pub fn []( - v: &mut WasmGateVector, - t: Wire, - h: Wire, - ) { - (v.0)[t.row as usize].wires[t.col as usize] = h.into(); - } - - #[wasm_bindgen] - pub fn []( - public_input_size: usize, - v: &WasmGateVector - ) -> Box<[u8]> { - Circuit::new(public_input_size, &(v.0)).digest().to_vec().into_boxed_slice() - } - - #[wasm_bindgen] - pub fn []( - public_input_size: usize, - v: &WasmGateVector - ) -> String { - let circuit = Circuit::new(public_input_size, &v.0); - serde_json::to_string(&circuit).expect("couldn't serialize constraints") - } - } - }; -} - -pub mod fp { - use super::*; - use crate::arkworks::WasmPastaFp as WasmF; - use mina_curves::pasta::Fp as F; - - impl_gate_vector!(fp, WasmF, F, Fp); -} - -// -// Fq -// - -pub mod fq { - use super::*; - use crate::arkworks::WasmPastaFq as WasmF; - use mina_curves::pasta::Fq as F; - - impl_gate_vector!(fq, WasmF, F, Fq); -} diff --git a/src/lib/crypto/kimchi_bindings/wasm/src/lib.rs b/src/lib/crypto/kimchi_bindings/wasm/src/lib.rs deleted file mode 100644 index 3f994cc2caa..00000000000 --- a/src/lib/crypto/kimchi_bindings/wasm/src/lib.rs +++ /dev/null @@ -1,114 +0,0 @@ -#![feature(get_mut_unchecked)] -//! The Marlin_plonk_stubs crate exports some functionalities -//! and structures from the following the Rust crates to OCaml: -//! -//! * [Marlin](https://github.com/o1-labs/marlin), -//! a PLONK implementation. -//! * [Arkworks](http://arkworks.rs/), -//! a math library that Marlin builds on top of. -//! - -use wasm_bindgen::prelude::*; - -mod wasm_flat_vector; -mod wasm_vector; - -#[wasm_bindgen] -extern "C" { - pub fn alert(s: &str); -} - -#[wasm_bindgen] -pub fn greet(name: &str) { - alert(&format!("Hello, {name}!")); -} - -#[wasm_bindgen] -extern "C" { - #[wasm_bindgen(js_namespace = console)] - fn log(s: &str); -} - -// produces a warning, but can be useful -// macro_rules! console_log { -// ($($t:tt)*) => (crate::log(&format_args!($($t)*).to_string())) -// } - -#[wasm_bindgen] -pub fn console_log(s: &str) { - log(s); -} - -#[wasm_bindgen] -pub fn create_zero_u32_ptr() -> *mut u32 { - Box::into_raw(std::boxed::Box::new(0)) -} - -#[wasm_bindgen] -pub fn free_u32_ptr(ptr: *mut u32) { - let _drop_me = unsafe { std::boxed::Box::from_raw(ptr) }; -} - -#[wasm_bindgen] -pub fn set_u32_ptr(ptr: *mut u32, arg: u32) { - // The rust docs explicitly forbid using this for cross-thread syncronization. Oh well, we - // don't have anything better. As long as it works in practice, we haven't upset the undefined - // behavior dragons. - unsafe { - std::ptr::write_volatile(ptr, arg); - } -} - -#[allow(unreachable_code)] -#[wasm_bindgen] -pub fn wait_until_non_zero(ptr: *const u32) -> u32 { - // The rust docs explicitly forbid using this for cross-thread syncronization. Oh well, we - // don't have anything better. As long as it works in practice, we haven't upset the undefined - // behavior dragons. - loop { - let contents = unsafe { std::ptr::read_volatile(ptr) }; - if contents != 0 { - return contents; - } - } - unreachable!(); -} - -pub mod rayon; - -/// Arkworks types -pub mod arkworks; - -/// Utils -pub mod urs_utils; // TODO: move this logic to proof-systems - -/// Vectors -pub mod gate_vector; - -pub mod poly_comm; -/// Curves -pub mod projective; - -/// SRS -pub mod srs; - -/// Indexes -pub mod pasta_fp_plonk_index; -pub mod pasta_fq_plonk_index; - -/// Verifier indexes/keys -pub mod plonk_verifier_index; - -/// Oracles -pub mod oracles; - -/// Proofs -pub mod plonk_proof; - -/// Poseidon -pub mod poseidon; - -// exposes circuit for inspection -pub mod circuit; - -pub mod wasm_ocaml_serde; diff --git a/src/lib/crypto/kimchi_bindings/wasm/src/oracles.rs b/src/lib/crypto/kimchi_bindings/wasm/src/oracles.rs deleted file mode 100644 index 47262466b80..00000000000 --- a/src/lib/crypto/kimchi_bindings/wasm/src/oracles.rs +++ /dev/null @@ -1,325 +0,0 @@ -use kimchi::circuits::scalars::RandomOracles; -use kimchi::proof::ProverProof; -use kimchi::verifier_index::VerifierIndex as DlogVerifierIndex; -use mina_poseidon::{ - self, - constants::PlonkSpongeConstantsKimchi, - sponge::{DefaultFqSponge, DefaultFrSponge}, - FqSponge, -}; -use paste::paste; -use poly_commitment::commitment::{shift_scalar, PolyComm}; -use poly_commitment::ipa::OpeningProof; -use poly_commitment::SRS; -use wasm_bindgen::prelude::*; -// use wasm_bindgen::convert::{IntoWasmAbi, FromWasmAbi}; -use crate::wasm_vector::WasmVector; -// use crate::wasm_flat_vector::WasmFlatVector; -use ark_ff::{One, Zero}; - -// -// CamlOracles -// - -// -// Implementation -// - -macro_rules! impl_oracles { - ($WasmF: ty, - $F: ty, - $WasmG: ty, - $G: ty, - $WasmPolyComm: ty, - $WasmProverProof: ty, - $index: ty, - $curve_params: ty, - $field_name: ident) => { - - paste! { - use crate::wasm_flat_vector::WasmFlatVector; - use mina_poseidon::sponge::ScalarChallenge; - - #[wasm_bindgen] - #[derive(Clone, Copy)] - pub struct [] { - pub joint_combiner_chal: Option<$WasmF>, - pub joint_combiner: Option<$WasmF>, - pub beta: $WasmF, - pub gamma: $WasmF, - pub alpha_chal: $WasmF, - pub alpha: $WasmF, - pub zeta: $WasmF, - pub v: $WasmF, - pub u: $WasmF, - pub zeta_chal: $WasmF, - pub v_chal: $WasmF, - pub u_chal: $WasmF, - } - type WasmRandomOracles = []; - - #[wasm_bindgen] - impl [] { - #[allow(clippy::too_many_arguments)] - #[wasm_bindgen(constructor)] - pub fn new( - joint_combiner_chal: Option<$WasmF>, - joint_combiner: Option<$WasmF>, - beta: $WasmF, - gamma: $WasmF, - alpha_chal: $WasmF, - alpha: $WasmF, - zeta: $WasmF, - v: $WasmF, - u: $WasmF, - zeta_chal: $WasmF, - v_chal: $WasmF, - u_chal: $WasmF) -> Self { - Self { - joint_combiner_chal, - joint_combiner, - beta, - gamma, - alpha_chal, - alpha, - zeta, - v, - u, - zeta_chal, - v_chal, - u_chal, - } - } - } - - impl From> for WasmRandomOracles - { - fn from(ro: RandomOracles<$F>) -> Self { - Self { - joint_combiner_chal: ro.joint_combiner.as_ref().map(|x| x.0.0.into()), - joint_combiner: ro.joint_combiner.as_ref().map(|x| x.1.into()), - beta: ro.beta.into(), - gamma: ro.gamma.into(), - alpha_chal: ro.alpha_chal.0.into(), - alpha: ro.alpha.into(), - zeta: ro.zeta.into(), - v: ro.v.into(), - u: ro.u.into(), - zeta_chal: ro.zeta_chal.0.into(), - v_chal: ro.v_chal.0.into(), - u_chal: ro.u_chal.0.into(), - } - } - } - - impl Into> for WasmRandomOracles - { - fn into(self) -> RandomOracles<$F> { - let joint_combiner = - match (self.joint_combiner_chal, self.joint_combiner) { - (Some(joint_combiner_chal), Some(joint_combiner)) => { - Some((ScalarChallenge(joint_combiner_chal.into()), joint_combiner.into())) - }, - _ => None - }; - RandomOracles { - joint_combiner, - beta: self.beta.into(), - gamma: self.gamma.into(), - alpha_chal: ScalarChallenge(self.alpha_chal.into()), - alpha: self.alpha.into(), - zeta: self.zeta.into(), - v: self.v.into(), - u: self.u.into(), - zeta_chal: ScalarChallenge(self.zeta_chal.into()), - v_chal: ScalarChallenge(self.v_chal.into()), - u_chal: ScalarChallenge(self.u_chal.into()), - } - } - } - - #[wasm_bindgen] - #[derive(Clone)] - pub struct [] { - pub o: [], - pub p_eval0: $WasmF, - pub p_eval1: $WasmF, - #[wasm_bindgen(skip)] - pub opening_prechallenges: WasmFlatVector<$WasmF>, - pub digest_before_evaluations: $WasmF, - } - - #[wasm_bindgen] - impl [] { - #[wasm_bindgen(constructor)] - pub fn new( - o: WasmRandomOracles, - p_eval0: $WasmF, - p_eval1: $WasmF, - opening_prechallenges: WasmFlatVector<$WasmF>, - digest_before_evaluations: $WasmF) -> Self { - Self {o, p_eval0, p_eval1, opening_prechallenges, digest_before_evaluations} - } - - #[wasm_bindgen(getter)] - pub fn opening_prechallenges(&self) -> WasmFlatVector<$WasmF> { - self.opening_prechallenges.clone() - } - - #[wasm_bindgen(setter)] - pub fn set_opening_prechallenges(&mut self, x: WasmFlatVector<$WasmF>) { - self.opening_prechallenges = x; - } - } - - #[wasm_bindgen] - pub fn [<$F:snake _oracles_create>]( - lgr_comm: WasmVector<$WasmPolyComm>, // the bases to commit polynomials - index: $index, // parameters - proof: $WasmProverProof, // the final proof (contains public elements at the beginning) - ) -> Result<[], JsError> { - // conversions - let result = crate::rayon::run_in_pool(|| { - let index: DlogVerifierIndex<$G, OpeningProof<$G>> = index.into(); - - let lgr_comm: Vec> = lgr_comm - .into_iter() - .take(proof.public.len()) - .map(Into::into) - .collect(); - let lgr_comm_refs: Vec<_> = lgr_comm.iter().collect(); - - let p_comm = PolyComm::<$G>::multi_scalar_mul( - &lgr_comm_refs, - &proof - .public - .iter() - .map(|a| a.clone().into()) - .map(|s: $F| -s) - .collect::>(), - ); - let p_comm = { - index - .srs() - .mask_custom( - p_comm.clone(), - &p_comm.map(|_| $F::one()), - ) - .unwrap() - .commitment - }; - - let (proof, public_input): (ProverProof<$G, OpeningProof<$G>>, Vec<$F>) = proof.into(); - - let oracles_result = - proof.oracles::< - DefaultFqSponge<$curve_params, PlonkSpongeConstantsKimchi>, - DefaultFrSponge<$F, PlonkSpongeConstantsKimchi> - >(&index, &p_comm, Some(&public_input)); - let oracles_result = match oracles_result { - Err(e) => { - return Err(format!("oracles_create: {}", e)); - } - Ok(cs) => cs, - }; - - let (mut sponge, combined_inner_product, p_eval, digest, oracles) = ( - oracles_result.fq_sponge, - oracles_result.combined_inner_product, - oracles_result.public_evals, - oracles_result.digest, - oracles_result.oracles, - ); - - sponge.absorb_fr(&[shift_scalar::<$G>(combined_inner_product)]); - - let opening_prechallenges = proof - .proof - .prechallenges(&mut sponge) - .into_iter() - .map(|x| x.0.into()) - .collect(); - - Ok((oracles, p_eval, opening_prechallenges, digest)) - }); - - match result { - Ok((oracles, p_eval, opening_prechallenges, digest)) => Ok([] { - o: oracles.into(), - p_eval0: p_eval[0][0].into(), - p_eval1: p_eval[1][0].into(), - opening_prechallenges, - digest_before_evaluations: digest.into() - }), - Err(err) => Err(JsError::new(&err)) - } - } - - #[wasm_bindgen] - pub fn [<$F:snake _oracles_dummy>]() -> [] { - [] { - o: RandomOracles::<$F>::default().into(), - p_eval0: $F::zero().into(), - p_eval1: $F::zero().into(), - opening_prechallenges: vec![].into(), - digest_before_evaluations: $F::zero().into(), - } - } - - #[wasm_bindgen] - pub fn [<$F:snake _oracles_deep_copy>]( - x: $WasmProverProof, - ) -> $WasmProverProof { - x - } - } - } -} - -// -// -// - -pub mod fp { - use super::*; - use crate::{ - arkworks::WasmPastaFp, plonk_proof::fp::WasmFpProverProof as WasmProverProof, - plonk_verifier_index::fp::WasmFpPlonkVerifierIndex as WasmPlonkVerifierIndex, - poly_comm::vesta::WasmFpPolyComm as WasmPolyComm, - }; - use mina_curves::pasta::{Fp, Vesta as GAffine, VestaParameters}; - - impl_oracles!( - WasmPastaFp, - Fp, - WasmGVesta, - GAffine, - WasmPolyComm, - WasmProverProof, - WasmPlonkVerifierIndex, - VestaParameters, - Fp - ); -} - -pub mod fq { - use super::*; - use crate::{ - arkworks::WasmPastaFq, plonk_proof::fq::WasmFqProverProof as WasmProverProof, - plonk_verifier_index::fq::WasmFqPlonkVerifierIndex as WasmPlonkVerifierIndex, - poly_comm::pallas::WasmFqPolyComm as WasmPolyComm, - }; - use mina_curves::pasta::{Fq, Pallas as GAffine, PallasParameters}; - - impl_oracles!( - WasmPastaFq, - Fq, - WasmGPallas, - GAffine, - WasmPolyComm, - WasmProverProof, - WasmPlonkVerifierIndex, - PallasParameters, - Fq - ); -} diff --git a/src/lib/crypto/kimchi_bindings/wasm/src/pasta_fp_plonk_index.rs b/src/lib/crypto/kimchi_bindings/wasm/src/pasta_fp_plonk_index.rs deleted file mode 100644 index 16f3eb47c76..00000000000 --- a/src/lib/crypto/kimchi_bindings/wasm/src/pasta_fp_plonk_index.rs +++ /dev/null @@ -1,300 +0,0 @@ -use ark_poly::EvaluationDomain; -use kimchi::circuits::lookup::runtime_tables::RuntimeTableCfg; - -use crate::arkworks::WasmPastaFp; -use crate::gate_vector::fp::WasmGateVector; -use crate::srs::fp::WasmFpSrs as WasmSrs; -use crate::wasm_flat_vector::WasmFlatVector; -use crate::wasm_vector::{fp::*, WasmVector}; -use kimchi::circuits::lookup::tables::LookupTable; -use kimchi::circuits::{constraints::ConstraintSystem, gate::CircuitGate}; -use kimchi::linearization::expr_linearization; -use kimchi::poly_commitment::ipa::OpeningProof; -use kimchi::prover_index::ProverIndex; -use mina_curves::pasta::{Fp, Pallas as GAffineOther, Vesta as GAffine, VestaParameters}; -use mina_poseidon::{constants::PlonkSpongeConstantsKimchi, sponge::DefaultFqSponge}; -use poly_commitment::SRS; -use serde::{Deserialize, Serialize}; -use std::{ - fs::{File, OpenOptions}, - io::{BufReader, BufWriter, Seek, SeekFrom::Start}, -}; -use wasm_bindgen::prelude::*; - -// -// CamlPastaFpPlonkIndex (custom type) -// - -/// Boxed so that we don't store large proving indexes in the OCaml heap. -#[wasm_bindgen] -pub struct WasmPastaFpPlonkIndex( - #[wasm_bindgen(skip)] pub Box>>, -); - -// This should mimic LookupTable structure -#[wasm_bindgen] -pub struct WasmPastaFpLookupTable { - #[wasm_bindgen(skip)] - pub id: i32, - #[wasm_bindgen(skip)] - pub data: WasmVecVecFp, -} - -// Converter from WasmPastaFpLookupTable to LookupTable, used by the binding -// below. -impl From for LookupTable { - fn from(wasm_lt: WasmPastaFpLookupTable) -> LookupTable { - LookupTable { - id: wasm_lt.id, - data: wasm_lt.data.0, - } - } -} - -// JS constructor for js/bindings.js -#[wasm_bindgen] -impl WasmPastaFpLookupTable { - #[wasm_bindgen(constructor)] - pub fn new(id: i32, data: WasmVecVecFp) -> WasmPastaFpLookupTable { - WasmPastaFpLookupTable { id, data } - } -} - -// Runtime table config - -#[wasm_bindgen] -pub struct WasmPastaFpRuntimeTableCfg { - #[wasm_bindgen(skip)] - pub id: i32, - #[wasm_bindgen(skip)] - pub first_column: WasmFlatVector, -} - -// JS constructor for js/bindings.js -#[wasm_bindgen] -impl WasmPastaFpRuntimeTableCfg { - #[wasm_bindgen(constructor)] - pub fn new(id: i32, first_column: WasmFlatVector) -> Self { - Self { id, first_column } - } -} - -impl From for RuntimeTableCfg { - fn from(wasm_rt_table_cfg: WasmPastaFpRuntimeTableCfg) -> Self { - Self { - id: wasm_rt_table_cfg.id, - first_column: wasm_rt_table_cfg - .first_column - .into_iter() - .map(Into::into) - .collect(), - } - } -} - -// CamlPastaFpPlonkIndex methods -// - -// Change js/web/worker-spec.js accordingly -#[wasm_bindgen] -pub fn caml_pasta_fp_plonk_index_create( - gates: &WasmGateVector, - public_: i32, - lookup_tables: WasmVector, - runtime_table_cfgs: WasmVector, - prev_challenges: i32, - srs: &WasmSrs, -) -> Result { - console_error_panic_hook::set_once(); - let index = crate::rayon::run_in_pool(|| { - // flatten the permutation information (because OCaml has a different way of keeping track of permutations) - let gates: Vec<_> = gates - .0 - .iter() - .map(|gate| CircuitGate:: { - typ: gate.typ, - wires: gate.wires, - coeffs: gate.coeffs.clone(), - }) - .collect(); - - let rust_runtime_table_cfgs: Vec> = - runtime_table_cfgs.into_iter().map(Into::into).collect(); - - let rust_lookup_tables: Vec> = - lookup_tables.into_iter().map(Into::into).collect(); - - // create constraint system - let cs = match ConstraintSystem::::create(gates) - .public(public_ as usize) - .prev_challenges(prev_challenges as usize) - .lookup(rust_lookup_tables) - .runtime(if rust_runtime_table_cfgs.is_empty() { - None - } else { - Some(rust_runtime_table_cfgs) - }) - .build() - { - Err(_) => { - return Err("caml_pasta_fp_plonk_index_create: could not create constraint system"); - } - Ok(cs) => cs, - }; - - // endo - let (endo_q, _endo_r) = poly_commitment::ipa::endos::(); - - srs.0.get_lagrange_basis(cs.domain.d1); - - let mut index = - ProverIndex::>::create(cs, endo_q, srs.0.clone()); - // Compute and cache the verifier index digest - index.compute_verifier_index_digest::>(); - Ok(index) - }); - - // create index - match index { - Ok(index) => Ok(WasmPastaFpPlonkIndex(Box::new(index))), - Err(str) => Err(JsError::new(str)), - } -} - -#[wasm_bindgen] -pub fn caml_pasta_fp_plonk_index_max_degree(index: &WasmPastaFpPlonkIndex) -> i32 { - index.0.srs.max_poly_size() as i32 -} - -#[wasm_bindgen] -pub fn caml_pasta_fp_plonk_index_public_inputs(index: &WasmPastaFpPlonkIndex) -> i32 { - index.0.cs.public as i32 -} - -#[wasm_bindgen] -pub fn caml_pasta_fp_plonk_index_domain_d1_size(index: &WasmPastaFpPlonkIndex) -> i32 { - index.0.cs.domain.d1.size() as i32 -} - -#[wasm_bindgen] -pub fn caml_pasta_fp_plonk_index_domain_d4_size(index: &WasmPastaFpPlonkIndex) -> i32 { - index.0.cs.domain.d4.size() as i32 -} - -#[wasm_bindgen] -pub fn caml_pasta_fp_plonk_index_domain_d8_size(index: &WasmPastaFpPlonkIndex) -> i32 { - index.0.cs.domain.d8.size() as i32 -} - -#[wasm_bindgen] -pub fn caml_pasta_fp_plonk_index_decode( - bytes: &[u8], - srs: &WasmSrs, -) -> Result { - let mut deserializer = rmp_serde::Deserializer::new(bytes); - let mut index = - ProverIndex::>::deserialize(&mut deserializer) - .map_err(|e| JsError::new(&format!("caml_pasta_fp_plonk_index_decode: {}", e)))?; - - index.srs = srs.0.clone(); - let (linearization, powers_of_alpha) = expr_linearization(Some(&index.cs.feature_flags), true); - index.linearization = linearization; - index.powers_of_alpha = powers_of_alpha; - - Ok(WasmPastaFpPlonkIndex(Box::new(index))) -} - -#[wasm_bindgen] -pub fn caml_pasta_fp_plonk_index_encode(index: &WasmPastaFpPlonkIndex) -> Result, JsError> { - let mut buffer = Vec::new(); - let mut serializer = rmp_serde::Serializer::new(&mut buffer); - index - .0 - .serialize(&mut serializer) - .map_err(|e| JsError::new(&format!("caml_pasta_fp_plonk_index_encode: {}", e)))?; - Ok(buffer) -} - -#[wasm_bindgen] -pub fn caml_pasta_fp_plonk_index_read( - offset: Option, - srs: &WasmSrs, - path: String, -) -> Result { - // read from file - let file = match File::open(path) { - Err(_) => return Err(JsValue::from_str("caml_pasta_fp_plonk_index_read")), - Ok(file) => file, - }; - let mut r = BufReader::new(file); - - // optional offset in file - if let Some(offset) = offset { - r.seek(Start(offset as u64)) - .map_err(|err| JsValue::from_str(&format!("caml_pasta_fp_plonk_index_read: {err}")))?; - } - - // deserialize the index - let mut t = ProverIndex::>::deserialize( - &mut rmp_serde::Deserializer::new(r), - ) - .map_err(|err| JsValue::from_str(&format!("caml_pasta_fp_plonk_index_read: {err}")))?; - t.srs = srs.0.clone(); - let (linearization, powers_of_alpha) = expr_linearization(Some(&t.cs.feature_flags), true); - t.linearization = linearization; - t.powers_of_alpha = powers_of_alpha; - - // - Ok(WasmPastaFpPlonkIndex(Box::new(t))) -} - -#[wasm_bindgen] -pub fn caml_pasta_fp_plonk_index_write( - append: Option, - index: &WasmPastaFpPlonkIndex, - path: String, -) -> Result<(), JsValue> { - let file = OpenOptions::new() - .append(append.unwrap_or(true)) - .open(path) - .map_err(|_| JsValue::from_str("caml_pasta_fp_plonk_index_write"))?; - let w = BufWriter::new(file); - index - .0 - .serialize(&mut rmp_serde::Serializer::new(w)) - .map_err(|e| JsValue::from_str(&format!("caml_pasta_fp_plonk_index_read: {e}"))) -} - -#[wasm_bindgen] -pub fn caml_pasta_fp_plonk_index_serialize(index: &WasmPastaFpPlonkIndex) -> String { - let serialized = rmp_serde::to_vec(&index.0).unwrap(); - base64::encode(serialized) -} - -// helpers - -fn format_field(f: &Fp) -> String { - // TODO this could be much nicer, should end up as "1", "-1", "0" etc - format!("{f}") -} - -pub fn format_circuit_gate(i: usize, gate: &CircuitGate) -> String { - let coeffs = gate - .coeffs - .iter() - .map(format_field) - .collect::>() - .join("\n"); - let wires = gate - .wires - .iter() - .enumerate() - .filter(|(j, wire)| wire.row != i || wire.col != *j) - .map(|(j, wire)| format!("({}, {}) --> ({}, {})", i, j, wire.row, wire.col)) - .collect::>() - .join("\n"); - format!( - "c[{}][{:?}]:\nconstraints\n{}\nwires\n{}\n", - i, gate.typ, coeffs, wires - ) -} diff --git a/src/lib/crypto/kimchi_bindings/wasm/src/pasta_fq_plonk_index.rs b/src/lib/crypto/kimchi_bindings/wasm/src/pasta_fq_plonk_index.rs deleted file mode 100644 index 86c61d01e12..00000000000 --- a/src/lib/crypto/kimchi_bindings/wasm/src/pasta_fq_plonk_index.rs +++ /dev/null @@ -1,271 +0,0 @@ -use ark_poly::EvaluationDomain; -use kimchi::circuits::lookup::runtime_tables::RuntimeTableCfg; - -use crate::arkworks::WasmPastaFq; -use crate::gate_vector::fq::WasmGateVector; -use crate::srs::fq::WasmFqSrs as WasmSrs; -use crate::wasm_flat_vector::WasmFlatVector; -use crate::wasm_vector::{fq::*, WasmVector}; -use kimchi::circuits::lookup::tables::LookupTable; -use kimchi::circuits::{constraints::ConstraintSystem, gate::CircuitGate}; -use kimchi::linearization::expr_linearization; -use kimchi::poly_commitment::ipa::OpeningProof; -use kimchi::prover_index::ProverIndex; -use mina_curves::pasta::{Fq, Pallas as GAffine, PallasParameters, Vesta as GAffineOther}; -use mina_poseidon::{constants::PlonkSpongeConstantsKimchi, sponge::DefaultFqSponge}; -use poly_commitment::SRS; -use serde::{Deserialize, Serialize}; -use std::{ - fs::{File, OpenOptions}, - io::{BufReader, BufWriter, Seek, SeekFrom::Start}, -}; -use wasm_bindgen::prelude::*; - -// -// CamlPastaFqPlonkIndex (custom type) -// - -/// Boxed so that we don't store large proving indexes in the OCaml heap. -#[wasm_bindgen] -pub struct WasmPastaFqPlonkIndex( - #[wasm_bindgen(skip)] pub Box>>, -); - -#[wasm_bindgen] -pub struct WasmPastaFqLookupTable { - #[wasm_bindgen(skip)] - pub id: i32, - #[wasm_bindgen(skip)] - pub data: WasmVecVecFq, -} - -impl From for LookupTable { - fn from(wasm_lt: WasmPastaFqLookupTable) -> LookupTable { - LookupTable { - id: wasm_lt.id, - data: wasm_lt.data.0, - } - } -} - -// JS constructor for js/bindings.js -#[wasm_bindgen] -impl WasmPastaFqLookupTable { - #[wasm_bindgen(constructor)] - pub fn new(id: i32, data: WasmVecVecFq) -> WasmPastaFqLookupTable { - WasmPastaFqLookupTable { id, data } - } -} - -// Runtime table config - -#[wasm_bindgen] -pub struct WasmPastaFqRuntimeTableCfg { - #[wasm_bindgen(skip)] - pub id: i32, - #[wasm_bindgen(skip)] - pub first_column: WasmFlatVector, -} - -impl From for RuntimeTableCfg { - fn from(wasm_rt_cfg: WasmPastaFqRuntimeTableCfg) -> Self { - Self { - id: wasm_rt_cfg.id, - first_column: wasm_rt_cfg - .first_column - .into_iter() - .map(Into::into) - .collect(), - } - } -} - -// JS constructor for js/bindings.js -#[wasm_bindgen] -impl WasmPastaFqRuntimeTableCfg { - #[wasm_bindgen(constructor)] - pub fn new(id: i32, first_column: WasmFlatVector) -> Self { - Self { id, first_column } - } -} - -// -// CamlPastaFqPlonkIndex methods -// - -// Change js/web/worker-spec.js accordingly -#[wasm_bindgen] -pub fn caml_pasta_fq_plonk_index_create( - gates: &WasmGateVector, - public_: i32, - lookup_tables: WasmVector, - runtime_table_cfgs: WasmVector, - prev_challenges: i32, - srs: &WasmSrs, -) -> Result { - console_error_panic_hook::set_once(); - let index = crate::rayon::run_in_pool(|| { - // flatten the permutation information (because OCaml has a different way of keeping track of permutations) - let gates: Vec<_> = gates - .0 - .iter() - .map(|gate| CircuitGate:: { - typ: gate.typ, - wires: gate.wires, - coeffs: gate.coeffs.clone(), - }) - .collect(); - - let rust_runtime_table_cfgs: Vec> = - runtime_table_cfgs.into_iter().map(Into::into).collect(); - - let rust_lookup_tables: Vec> = - lookup_tables.into_iter().map(Into::into).collect(); - - // create constraint system - let cs = match ConstraintSystem::::create(gates) - .public(public_ as usize) - .prev_challenges(prev_challenges as usize) - .lookup(rust_lookup_tables) - .runtime(if rust_runtime_table_cfgs.is_empty() { - None - } else { - Some(rust_runtime_table_cfgs) - }) - .build() - { - Err(_) => { - return Err("caml_pasta_fq_plonk_index_create: could not create constraint system"); - } - Ok(cs) => cs, - }; - - // endo - let (endo_q, _endo_r) = poly_commitment::ipa::endos::(); - - srs.0.get_lagrange_basis(cs.domain.d1); - - let mut index = - ProverIndex::>::create(cs, endo_q, srs.0.clone()); - // Compute and cache the verifier index digest - index.compute_verifier_index_digest::>(); - - Ok(index) - }); - - // create index - match index { - Ok(index) => Ok(WasmPastaFqPlonkIndex(Box::new(index))), - Err(str) => Err(JsError::new(str)), - } -} - -#[wasm_bindgen] -pub fn caml_pasta_fq_plonk_index_max_degree(index: &WasmPastaFqPlonkIndex) -> i32 { - index.0.srs.max_poly_size() as i32 -} - -#[wasm_bindgen] -pub fn caml_pasta_fq_plonk_index_public_inputs(index: &WasmPastaFqPlonkIndex) -> i32 { - index.0.cs.public as i32 -} - -#[wasm_bindgen] -pub fn caml_pasta_fq_plonk_index_domain_d1_size(index: &WasmPastaFqPlonkIndex) -> i32 { - index.0.cs.domain.d1.size() as i32 -} - -#[wasm_bindgen] -pub fn caml_pasta_fq_plonk_index_domain_d4_size(index: &WasmPastaFqPlonkIndex) -> i32 { - index.0.cs.domain.d4.size() as i32 -} - -#[wasm_bindgen] -pub fn caml_pasta_fq_plonk_index_domain_d8_size(index: &WasmPastaFqPlonkIndex) -> i32 { - index.0.cs.domain.d8.size() as i32 -} - -#[wasm_bindgen] -pub fn caml_pasta_fq_plonk_index_decode( - bytes: &[u8], - srs: &WasmSrs, -) -> Result { - let mut deserializer = rmp_serde::Deserializer::new(bytes); - let mut index = - ProverIndex::>::deserialize(&mut deserializer) - .map_err(|e| JsError::new(&format!("caml_pasta_fq_plonk_index_decode: {}", e)))?; - - index.srs = srs.0.clone(); - let (linearization, powers_of_alpha) = expr_linearization(Some(&index.cs.feature_flags), true); - index.linearization = linearization; - index.powers_of_alpha = powers_of_alpha; - - Ok(WasmPastaFqPlonkIndex(Box::new(index))) -} - -#[wasm_bindgen] -pub fn caml_pasta_fq_plonk_index_encode(index: &WasmPastaFqPlonkIndex) -> Result, JsError> { - let mut buffer = Vec::new(); - let mut serializer = rmp_serde::Serializer::new(&mut buffer); - index - .0 - .serialize(&mut serializer) - .map_err(|e| JsError::new(&format!("caml_pasta_fq_plonk_index_encode: {}", e)))?; - Ok(buffer) -} - -#[wasm_bindgen] -pub fn caml_pasta_fq_plonk_index_read( - offset: Option, - srs: &WasmSrs, - path: String, -) -> Result { - // read from file - let file = match File::open(path) { - Err(_) => return Err(JsValue::from_str("caml_pasta_fq_plonk_index_read")), - Ok(file) => file, - }; - let mut r = BufReader::new(file); - - // optional offset in file - if let Some(offset) = offset { - r.seek(Start(offset as u64)) - .map_err(|err| JsValue::from_str(&format!("caml_pasta_fq_plonk_index_read: {err}")))?; - } - - // deserialize the index - let mut t = ProverIndex::>::deserialize( - &mut rmp_serde::Deserializer::new(r), - ) - .map_err(|err| JsValue::from_str(&format!("caml_pasta_fq_plonk_index_read: {err}")))?; - t.srs = srs.0.clone(); - let (linearization, powers_of_alpha) = expr_linearization(Some(&t.cs.feature_flags), true); - t.linearization = linearization; - t.powers_of_alpha = powers_of_alpha; - - // - Ok(WasmPastaFqPlonkIndex(Box::new(t))) -} - -#[wasm_bindgen] -pub fn caml_pasta_fq_plonk_index_write( - append: Option, - index: &WasmPastaFqPlonkIndex, - path: String, -) -> Result<(), JsValue> { - let file = OpenOptions::new() - .append(append.unwrap_or(true)) - .open(path) - .map_err(|_| JsValue::from_str("caml_pasta_fq_plonk_index_write"))?; - let w = BufWriter::new(file); - index - .0 - .serialize(&mut rmp_serde::Serializer::new(w)) - .map_err(|e| JsValue::from_str(&format!("caml_pasta_fq_plonk_index_read: {e}"))) -} - -#[wasm_bindgen] -pub fn caml_pasta_fq_plonk_index_serialize(index: &WasmPastaFqPlonkIndex) -> String { - let serialized = rmp_serde::to_vec(&index.0).unwrap(); - base64::encode(serialized) -} diff --git a/src/lib/crypto/kimchi_bindings/wasm/src/plonk_proof.rs b/src/lib/crypto/kimchi_bindings/wasm/src/plonk_proof.rs deleted file mode 100644 index 3017af8ce23..00000000000 --- a/src/lib/crypto/kimchi_bindings/wasm/src/plonk_proof.rs +++ /dev/null @@ -1,912 +0,0 @@ -// use kimchi::circuits::expr::{Linearization, PolishToken, Variable, Column}; -// use kimchi::circuits::gate::{GateType, CurrOrNext}; -use crate::wasm_flat_vector::WasmFlatVector; -use crate::wasm_vector::fp::WasmVecVecFp; -use crate::wasm_vector::fq::WasmVecVecFq; -use crate::wasm_vector::WasmVector; -use paste::paste; -use std::convert::TryInto; -use wasm_bindgen::prelude::*; -// use std::sync::Arc; -// use poly_commitment::srs::SRS; -use kimchi::circuits::lookup::runtime_tables::RuntimeTable; -// use kimchi::index::{expr_linearization, VerifierIndex as DlogVerifierIndex}; -// use ark_poly::{EvaluationDomain, Radix2EvaluationDomain as Domain}; -use ark_ec::AffineRepr; -use ark_ff::One; -use array_init::array_init; -use kimchi::circuits::wires::COLUMNS; -use kimchi::verifier::Context; -use std::array; -// use std::path::Path; -use groupmap::GroupMap; -use kimchi::proof::{ - LookupCommitments, PointEvaluations, ProofEvaluations, ProverCommitments, ProverProof, - RecursionChallenge, -}; -use kimchi::prover_index::ProverIndex; -use kimchi::verifier::batch_verify; -use mina_poseidon::{ - constants::PlonkSpongeConstantsKimchi, - sponge::{DefaultFqSponge, DefaultFrSponge}, -}; -use poly_commitment::SRS as _; -use poly_commitment::{ - commitment::{CommitmentCurve, PolyComm}, - ipa::OpeningProof, -}; -use serde::{Deserialize, Serialize}; - -#[wasm_bindgen] -extern "C" { - #[wasm_bindgen(js_namespace = console)] - fn log(s: &str); -} - -macro_rules! impl_proof { - ( - $name: ident, - $WasmG: ty, - $G: ty, - $WasmF: ty, - $F: ty, - $WasmPolyComm: ty, - $WasmSrs: ty, - $GOther: ty, - $FrSpongeParams: path, - $FqSpongeParams: path, - $WasmIndex: ty, - $WasmVerifierIndex: ty, - $field_name: ident - ) => { - paste! { - type WasmVecVecF = []; - - #[derive(Clone)] - pub struct []( - ProofEvaluations>> - ); - type WasmProofEvaluations = []; - - impl wasm_bindgen::describe::WasmDescribe for WasmProofEvaluations { - fn describe() { - ::describe() - } - } - - impl wasm_bindgen::convert::FromWasmAbi for WasmProofEvaluations { - type Abi = ::Abi; - unsafe fn from_abi(js: Self::Abi) -> Self { - let js: JsValue = wasm_bindgen::convert::FromWasmAbi::from_abi(js); - Self( - ProofEvaluations::deserialize( - crate::wasm_ocaml_serde::de::Deserializer::from(js), - ) - .unwrap(), - ) - } - } - - impl wasm_bindgen::convert::IntoWasmAbi for WasmProofEvaluations { - type Abi = ::Abi; - fn into_abi(self) -> Self::Abi { - let js = self - .0 - .serialize(&crate::wasm_ocaml_serde::ser::Serializer::new()) - .unwrap(); - wasm_bindgen::convert::IntoWasmAbi::into_abi(js) - } - } - - impl From<&WasmProofEvaluations> for ProofEvaluations>> { - fn from(x: &WasmProofEvaluations) -> Self { - x.0.clone() - } - } - - impl From for ProofEvaluations>> { - fn from(x: WasmProofEvaluations) -> Self { - x.0 - } - } - - impl From<&ProofEvaluations>>> for WasmProofEvaluations { - fn from(x: &ProofEvaluations>>) -> Self { - Self(x.clone()) - } - } - - impl From>>> for WasmProofEvaluations { - fn from(x: ProofEvaluations>>) -> Self { - Self(x) - } - } - - #[wasm_bindgen] - #[derive(Clone)] - pub struct [] - { - #[wasm_bindgen(skip)] - pub sorted: WasmVector<$WasmPolyComm>, - #[wasm_bindgen(skip)] - pub aggreg: $WasmPolyComm, - #[wasm_bindgen(skip)] - pub runtime: Option<$WasmPolyComm>, - } - - type WasmLookupCommitments = []; - - #[wasm_bindgen] - impl [] { - #[wasm_bindgen(constructor)] - pub fn new( - sorted: WasmVector<$WasmPolyComm>, - aggreg: $WasmPolyComm, - runtime: Option<$WasmPolyComm>) -> Self { - WasmLookupCommitments { sorted, aggreg, runtime } - } - - #[wasm_bindgen(getter)] - pub fn sorted(&self) -> WasmVector<$WasmPolyComm> { - self.sorted.clone() - } - - #[wasm_bindgen(getter)] - pub fn aggreg(&self) -> $WasmPolyComm { - self.aggreg.clone() - } - - #[wasm_bindgen(getter)] - pub fn runtime(&self) -> Option<$WasmPolyComm> { - self.runtime.clone() - } - - #[wasm_bindgen(setter)] - pub fn set_sorted(&mut self, s: WasmVector<$WasmPolyComm>) { - self.sorted = s - } - - #[wasm_bindgen(setter)] - pub fn set_aggreg(&mut self, a: $WasmPolyComm) { - self.aggreg = a - } - - #[wasm_bindgen(setter)] - pub fn set_runtime(&mut self, r: Option<$WasmPolyComm>) { - self.runtime = r - } - } - - - impl From<&LookupCommitments<$G>> for WasmLookupCommitments { - fn from(x: &LookupCommitments<$G>) -> Self { - WasmLookupCommitments { - sorted: x.sorted.iter().map(Into::into).collect(), - aggreg: x.aggreg.clone().into(), - runtime: x.runtime.clone().map(Into::into) - } - } - } - - impl From> for WasmLookupCommitments { - fn from(x: LookupCommitments<$G>) -> Self { - WasmLookupCommitments { - sorted: x.sorted.into_iter().map(Into::into).collect(), - aggreg: x.aggreg.into(), - runtime: x.runtime.map(Into::into) - } - } - } - - impl From<&WasmLookupCommitments> for LookupCommitments<$G> { - fn from(x: &WasmLookupCommitments) -> Self { - LookupCommitments { - sorted: x.sorted.iter().map(Into::into).collect(), - aggreg: x.aggreg.clone().into(), - runtime: x.runtime.clone().map(Into::into) - } - } - } - - impl From for LookupCommitments<$G> { - fn from(x: WasmLookupCommitments) -> Self { - LookupCommitments { - sorted: x.sorted.into_iter().map(Into::into).collect(), - aggreg: x.aggreg.into(), - runtime: x.runtime.map(Into::into) - } - } - } - - #[wasm_bindgen] - #[derive(Clone)] - pub struct [] - { - #[wasm_bindgen(skip)] - pub w_comm: WasmVector<$WasmPolyComm>, - #[wasm_bindgen(skip)] - pub z_comm: $WasmPolyComm, - #[wasm_bindgen(skip)] - pub t_comm: $WasmPolyComm, - #[wasm_bindgen(skip)] - pub lookup: Option, - } - type WasmProverCommitments = []; - - #[wasm_bindgen] - impl [] { - #[wasm_bindgen(constructor)] - pub fn new( - w_comm: WasmVector<$WasmPolyComm>, - z_comm: $WasmPolyComm, - t_comm: $WasmPolyComm, - lookup: Option - ) -> Self { - WasmProverCommitments { w_comm, z_comm, t_comm, lookup } - } - - #[wasm_bindgen(getter)] - pub fn w_comm(&self) -> WasmVector<$WasmPolyComm> { - self.w_comm.clone() - } - #[wasm_bindgen(getter)] - pub fn z_comm(&self) -> $WasmPolyComm { - self.z_comm.clone() - } - #[wasm_bindgen(getter)] - pub fn t_comm(&self) -> $WasmPolyComm { - self.t_comm.clone() - } - - #[wasm_bindgen(getter)] - pub fn lookup(&self) -> Option { - self.lookup.clone() - } - - #[wasm_bindgen(setter)] - pub fn set_w_comm(&mut self, x: WasmVector<$WasmPolyComm>) { - self.w_comm = x - } - #[wasm_bindgen(setter)] - pub fn set_z_comm(&mut self, x: $WasmPolyComm) { - self.z_comm = x - } - #[wasm_bindgen(setter)] - pub fn set_t_comm(&mut self, x: $WasmPolyComm) { - self.t_comm = x - } - - #[wasm_bindgen(setter)] - pub fn set_lookup(&mut self, l: Option) { - self.lookup = l - } - } - - impl From<&ProverCommitments<$G>> for WasmProverCommitments { - fn from(x: &ProverCommitments<$G>) -> Self { - WasmProverCommitments { - w_comm: x.w_comm.iter().map(Into::into).collect(), - z_comm: x.z_comm.clone().into(), - t_comm: x.t_comm.clone().into(), - lookup: x.lookup.clone().map(Into::into) - } - } - } - - impl From> for WasmProverCommitments { - fn from(x: ProverCommitments<$G>) -> Self { - WasmProverCommitments { - w_comm: x.w_comm.iter().map(Into::into).collect(), - z_comm: x.z_comm.into(), - t_comm: x.t_comm.into(), - lookup: x.lookup.map(Into::into), - } - } - } - - impl From<&WasmProverCommitments> for ProverCommitments<$G> { - fn from(x: &WasmProverCommitments) -> Self { - ProverCommitments { - w_comm: array_init(|i| x.w_comm[i].clone().into()), - z_comm: x.z_comm.clone().into(), - t_comm: x.t_comm.clone().into(), - lookup: x.lookup.clone().map(Into::into), - } - } - } - - impl From for ProverCommitments<$G> { - fn from(x: WasmProverCommitments) -> Self { - ProverCommitments { - w_comm: array_init(|i| (&x.w_comm[i]).into()), - z_comm: x.z_comm.into(), - t_comm: x.t_comm.into(), - lookup: x.lookup.map(Into::into), - } - } - } - - #[wasm_bindgen] - #[derive(Clone, Debug)] - pub struct [] { - #[wasm_bindgen(skip)] - pub lr_0: WasmVector<$WasmG>, // vector of rounds of L commitments - #[wasm_bindgen(skip)] - pub lr_1: WasmVector<$WasmG>, // vector of rounds of R commitments - #[wasm_bindgen(skip)] - pub delta: $WasmG, - pub z1: $WasmF, - pub z2: $WasmF, - #[wasm_bindgen(skip)] - pub sg: $WasmG, - } - type WasmOpeningProof = []; - - #[wasm_bindgen] - impl [] { - #[wasm_bindgen(constructor)] - pub fn new( - lr_0: WasmVector<$WasmG>, - lr_1: WasmVector<$WasmG>, - delta: $WasmG, - z1: $WasmF, - z2: $WasmF, - sg: $WasmG) -> Self { - WasmOpeningProof { lr_0, lr_1, delta, z1, z2, sg } - } - - #[wasm_bindgen(getter)] - pub fn lr_0(&self) -> WasmVector<$WasmG> { - self.lr_0.clone() - } - #[wasm_bindgen(getter)] - pub fn lr_1(&self) -> WasmVector<$WasmG> { - self.lr_1.clone() - } - #[wasm_bindgen(getter)] - pub fn delta(&self) -> $WasmG { - self.delta.clone() - } - #[wasm_bindgen(getter)] - pub fn sg(&self) -> $WasmG { - self.sg.clone() - } - - #[wasm_bindgen(setter)] - pub fn set_lr_0(&mut self, lr_0: WasmVector<$WasmG>) { - self.lr_0 = lr_0 - } - #[wasm_bindgen(setter)] - pub fn set_lr_1(&mut self, lr_1: WasmVector<$WasmG>) { - self.lr_1 = lr_1 - } - #[wasm_bindgen(setter)] - pub fn set_delta(&mut self, delta: $WasmG) { - self.delta = delta - } - #[wasm_bindgen(setter)] - pub fn set_sg(&mut self, sg: $WasmG) { - self.sg = sg - } - } - - impl From<&WasmOpeningProof> for OpeningProof<$G> { - fn from(x: &WasmOpeningProof) -> Self { - OpeningProof { - lr: x.lr_0.clone().into_iter().zip(x.lr_1.clone().into_iter()).map(|(x, y)| (x.into(), y.into())).collect(), - delta: x.delta.clone().into(), - z1: x.z1.into(), - z2: x.z2.into(), - sg: x.sg.clone().into(), - } - } - } - - impl From for OpeningProof<$G> { - fn from(x: WasmOpeningProof) -> Self { - let WasmOpeningProof {lr_0, lr_1, delta, z1, z2, sg} = x; - OpeningProof { - lr: lr_0.into_iter().zip(lr_1.into_iter()).map(|(x, y)| (x.into(), y.into())).collect(), - delta: delta.into(), - z1: z1.into(), - z2: z2.into(), - sg: sg.into(), - } - } - } - - impl From<&OpeningProof<$G>> for WasmOpeningProof { - fn from(x: &OpeningProof<$G>) -> Self { - let (lr_0, lr_1) = x.lr.clone().into_iter().map(|(x, y)| (x.into(), y.into())).unzip(); - WasmOpeningProof { - lr_0, - lr_1, - delta: x.delta.clone().into(), - z1: x.z1.into(), - z2: x.z2.into(), - sg: x.sg.clone().into(), - } - } - } - - impl From> for WasmOpeningProof { - fn from(x: OpeningProof<$G>) -> Self { - let (lr_0, lr_1) = x.lr.clone().into_iter().map(|(x, y)| (x.into(), y.into())).unzip(); - WasmOpeningProof { - lr_0, - lr_1, - delta: x.delta.clone().into(), - z1: x.z1.into(), - z2: x.z2.into(), - sg: x.sg.clone().into(), - } - } - } - - #[wasm_bindgen] - pub struct [] { - #[wasm_bindgen(skip)] - pub commitments: WasmProverCommitments, - #[wasm_bindgen(skip)] - pub proof: WasmOpeningProof, - // OCaml doesn't have sized arrays, so we have to convert to a tuple.. - #[wasm_bindgen(skip)] - pub evals: WasmProofEvaluations, - pub ft_eval1: $WasmF, - #[wasm_bindgen(skip)] - pub public: WasmFlatVector<$WasmF>, - #[wasm_bindgen(skip)] - pub prev_challenges_scalars: Vec>, - #[wasm_bindgen(skip)] - pub prev_challenges_comms: WasmVector<$WasmPolyComm>, - } - type WasmProverProof = []; - - impl From<(&ProverProof<$G, OpeningProof<$G>>, &Vec<$F>)> for WasmProverProof { - fn from((x, public): (&ProverProof<$G, OpeningProof<$G>>, &Vec<$F>)) -> Self { - let (scalars, comms) = - x.prev_challenges - .iter() - .map(|RecursionChallenge { chals, comm }| { - (chals.clone().into(), comm.into()) - }) - .unzip(); - WasmProverProof { - commitments: x.commitments.clone().into(), - proof: x.proof.clone().into(), - evals: x.evals.clone().into(), - ft_eval1: x.ft_eval1.clone().into(), - public: public.clone().into_iter().map(Into::into).collect(), - prev_challenges_scalars: scalars, - prev_challenges_comms: comms, - } - } - } - - impl From<(ProverProof<$G, OpeningProof<$G>>, Vec<$F>)> for WasmProverProof { - fn from((x, public): (ProverProof<$G, OpeningProof<$G>>, Vec<$F>)) -> Self { - let ProverProof {ft_eval1, commitments, proof, evals , prev_challenges} = x; - let (scalars, comms) = - prev_challenges - .into_iter() - .map(|RecursionChallenge { chals, comm }| (chals.into(), comm.into())) - .unzip(); - WasmProverProof { - commitments: commitments.into(), - proof: proof.into(), - evals: evals.into(), - ft_eval1: ft_eval1.clone().into(), - public: public.into_iter().map(Into::into).collect(), - prev_challenges_scalars: scalars, - prev_challenges_comms: comms, - } - } - } - - impl From<&WasmProverProof> for (ProverProof<$G, OpeningProof<$G>>, Vec<$F>) { - fn from(x: &WasmProverProof) -> Self { - let proof = ProverProof { - commitments: x.commitments.clone().into(), - proof: x.proof.clone().into(), - evals: x.evals.clone().into(), - prev_challenges: - (&x.prev_challenges_scalars) - .into_iter() - .zip((&x.prev_challenges_comms).into_iter()) - .map(|(chals, comm)| { - RecursionChallenge { - chals: chals.clone(), - comm: comm.into(), - } - }) - .collect(), - ft_eval1: x.ft_eval1.clone().into() - }; - let public = x.public.clone().into_iter().map(Into::into).collect(); - (proof, public) - } - } - - impl From for (ProverProof<$G, OpeningProof<$G>>, Vec<$F>) { - fn from(x: WasmProverProof) -> Self { - let proof =ProverProof { - commitments: x.commitments.into(), - proof: x.proof.into(), - evals: x.evals.into(), - prev_challenges: - (x.prev_challenges_scalars) - .into_iter() - .zip((x.prev_challenges_comms).into_iter()) - .map(|(chals, comm)| { - RecursionChallenge { - chals: chals.into(), - comm: comm.into(), - } - }) - .collect(), - ft_eval1: x.ft_eval1.into() - }; - let public = x.public.into_iter().map(Into::into).collect(); - (proof, public) - } - } - - #[wasm_bindgen] - impl [] { - #[wasm_bindgen(constructor)] - pub fn new( - commitments: WasmProverCommitments, - proof: WasmOpeningProof, - evals: WasmProofEvaluations, - ft_eval1: $WasmF, - public_: WasmFlatVector<$WasmF>, - prev_challenges_scalars: WasmVecVecF, - prev_challenges_comms: WasmVector<$WasmPolyComm>) -> Self { - WasmProverProof { - commitments, - proof, - evals, - ft_eval1, - public: public_, - prev_challenges_scalars: prev_challenges_scalars.0, - prev_challenges_comms, - } - } - - #[wasm_bindgen(getter)] - pub fn commitments(&self) -> WasmProverCommitments { - self.commitments.clone() - } - #[wasm_bindgen(getter)] - pub fn proof(&self) -> WasmOpeningProof { - self.proof.clone() - } - #[wasm_bindgen(getter)] - pub fn evals(&self) -> WasmProofEvaluations { - self.evals.clone() - } - #[wasm_bindgen(getter)] - pub fn public_(&self) -> WasmFlatVector<$WasmF> { - self.public.clone() - } - #[wasm_bindgen(getter)] - pub fn prev_challenges_scalars(&self) -> WasmVecVecF { - [](self.prev_challenges_scalars.clone()) - } - #[wasm_bindgen(getter)] - pub fn prev_challenges_comms(&self) -> WasmVector<$WasmPolyComm> { - self.prev_challenges_comms.clone() - } - - #[wasm_bindgen(setter)] - pub fn set_commitments(&mut self, commitments: WasmProverCommitments) { - self.commitments = commitments - } - #[wasm_bindgen(setter)] - pub fn set_proof(&mut self, proof: WasmOpeningProof) { - self.proof = proof - } - #[wasm_bindgen(setter)] - pub fn set_evals(&mut self, evals: WasmProofEvaluations) { - self.evals = evals - } - #[wasm_bindgen(setter)] - pub fn set_public_(&mut self, public_: WasmFlatVector<$WasmF>) { - self.public = public_ - } - #[wasm_bindgen(setter)] - pub fn set_prev_challenges_scalars(&mut self, prev_challenges_scalars: WasmVecVecF) { - self.prev_challenges_scalars = prev_challenges_scalars.0 - } - #[wasm_bindgen(setter)] - pub fn set_prev_challenges_comms(&mut self, prev_challenges_comms: WasmVector<$WasmPolyComm>) { - self.prev_challenges_comms = prev_challenges_comms - } - - #[wasm_bindgen] - pub fn serialize(&self) -> String { - let (proof, _public_input) = self.into(); - let serialized = rmp_serde::to_vec(&proof).unwrap(); - base64::encode(serialized) - } - } - - #[wasm_bindgen] - pub struct [] { - id: i32, - data: WasmFlatVector<$WasmF> - } - type WasmRuntimeTable = []; - - #[wasm_bindgen] - impl [] { - #[wasm_bindgen(constructor)] - pub fn new(id: i32, data: WasmFlatVector<$WasmF>) -> WasmRuntimeTable { - WasmRuntimeTable {id, data} - } - } - - impl From<[]> for RuntimeTable<$F> { - fn from(wasm_rt: WasmRuntimeTable) -> RuntimeTable<$F> { - RuntimeTable { - id: wasm_rt.id.into(), - data: wasm_rt.data.into_iter().map(Into::into).collect() - } - } - } - - #[wasm_bindgen] - pub fn [<$name:snake _create>]( - index: &$WasmIndex, - witness: WasmVecVecF, - wasm_runtime_tables: WasmVector, - prev_challenges: WasmFlatVector<$WasmF>, - prev_sgs: WasmVector<$WasmG>, - ) -> Result { - console_error_panic_hook::set_once(); - let (maybe_proof, public_input) = crate::rayon::run_in_pool(|| { - index.0.srs.get_lagrange_basis(index.0.as_ref().cs.domain.d1); - let prev: Vec> = { - if prev_challenges.is_empty() { - Vec::new() - } else { - let challenges_per_sg = prev_challenges.len() / prev_sgs.len(); - prev_sgs - .into_iter() - .map(Into::<$G>::into) - .enumerate() - .map(|(i, sg)| { - let chals = - prev_challenges[(i * challenges_per_sg)..(i + 1) * challenges_per_sg] - .iter() - .map(|a| a.clone().into()) - .collect(); - let comm = PolyComm::<$G> { - chunks: vec![sg], - }; - RecursionChallenge { chals, comm } - }) - .collect() - } - }; - - let rust_runtime_tables: Vec> = wasm_runtime_tables.into_iter().map(Into::into).collect(); - - let witness: [Vec<_>; COLUMNS] = witness.0 - .try_into() - .expect("the witness should be a column of 15 vectors"); - - let index: &ProverIndex<$G, OpeningProof<$G>> = &index.0.as_ref(); - - let public_input = witness[0][0..index.cs.public].to_vec(); - - // Release the runtime lock so that other threads can run using it while we generate the proof. - let group_map = GroupMap::<_>::setup(); - let maybe_proof = ProverProof::create_recursive::< - DefaultFqSponge<_, PlonkSpongeConstantsKimchi>, - DefaultFrSponge<_, PlonkSpongeConstantsKimchi>, - _>(&group_map, witness, &rust_runtime_tables, index, prev, None, - &mut rand::rngs::OsRng - ); - (maybe_proof, public_input) - }); - - return match maybe_proof { - Ok(proof) => Ok((proof, public_input).into()), - Err(err) => Err(JsError::from(err)) - } - } - - #[wasm_bindgen] - pub fn [<$name:snake _verify>]( - index: $WasmVerifierIndex, - proof: WasmProverProof, - ) -> bool { - crate::rayon::run_in_pool(|| { - let group_map = <$G as CommitmentCurve>::Map::setup(); - let verifier_index = &index.into(); - let (proof, public_input) = &proof.into(); - batch_verify::< - $G, - DefaultFqSponge<_, PlonkSpongeConstantsKimchi>, - DefaultFrSponge<_, PlonkSpongeConstantsKimchi>, - OpeningProof<$G> - >( - &group_map, - &[Context { verifier_index, proof, public_input }] - ).is_ok() - }) - } - - #[wasm_bindgen] - pub struct [](Vec>>); - - #[wasm_bindgen] - impl [] { - #[wasm_bindgen(constructor)] - pub fn create(n: i32) -> Self { - [](Vec::with_capacity(n as usize)) - } - - #[wasm_bindgen] - pub fn push(&mut self, x: WasmVector<$WasmPolyComm>) { - self.0.push(x.into_iter().map(Into::into).collect()) - } - } - - #[wasm_bindgen] - pub fn [<$name:snake _batch_verify>]( - indexes: WasmVector<$WasmVerifierIndex>, - proofs: WasmVector, - ) -> bool { - crate::rayon::run_in_pool(|| { - let ts: Vec<_> = indexes - .into_iter() - .zip(proofs.into_iter()) - .map(|(index, proof)| (index.into(), proof.into())) - .collect(); - let ts: Vec<_> = ts.iter().map(|(verifier_index, (proof, public_input))| Context { verifier_index, proof, public_input}).collect(); - let group_map = GroupMap::<_>::setup(); - - batch_verify::< - $G, - DefaultFqSponge<_, PlonkSpongeConstantsKimchi>, - DefaultFrSponge<_, PlonkSpongeConstantsKimchi>, - OpeningProof<$G> - >(&group_map, &ts) - .is_ok() - }) - } - - #[wasm_bindgen] - pub fn [<$name:snake _dummy>]() -> WasmProverProof { - fn comm() -> PolyComm<$G> { - let g = $G::generator(); - PolyComm { - chunks: vec![g, g, g], - } - } - - let prev = RecursionChallenge { - chals: vec![$F::one(), $F::one()], - comm: comm(), - }; - let prev_challenges = vec![prev.clone(), prev.clone(), prev.clone()]; - - let g = $G::generator(); - let proof = OpeningProof { - lr: vec![(g, g), (g, g), (g, g)], - z1: $F::one(), - z2: $F::one(), - delta: g, - sg: g, - }; - let eval = || PointEvaluations { - zeta: vec![$F::one()], - zeta_omega: vec![$F::one()], - }; - let evals = ProofEvaluations { - w: array_init(|_| eval()), - coefficients: array_init(|_| eval()), - z: eval(), - s: array_init(|_| eval()), - generic_selector: eval(), - poseidon_selector: eval(), - complete_add_selector: eval(), - mul_selector: eval(), - emul_selector: eval(), - endomul_scalar_selector: eval(), - range_check0_selector: None, - range_check1_selector: None, - foreign_field_add_selector: None, - foreign_field_mul_selector: None, - xor_selector: None, - rot_selector: None, - lookup_aggregation: None, - lookup_table: None, - lookup_sorted: array::from_fn(|_| None), - runtime_lookup_table: None, - runtime_lookup_table_selector: None, - xor_lookup_selector: None, - lookup_gate_lookup_selector: None, - range_check_lookup_selector: None, - foreign_field_mul_lookup_selector: None, - public: None, - }; - - let dlogproof = ProverProof { - commitments: ProverCommitments { - w_comm: array_init(|_| comm()), - z_comm: comm(), - t_comm: comm(), - lookup: None, - }, - proof, - evals, - ft_eval1: $F::one(), - prev_challenges, - }; - - let public = vec![$F::one(), $F::one()]; - (dlogproof, public).into() - } - - #[wasm_bindgen] - pub fn [<$name:snake _deep_copy>]( - x: WasmProverProof - ) -> WasmProverProof { - x - } - } - } -} - -pub mod fp { - use super::*; - use crate::arkworks::{WasmGVesta, WasmPastaFp}; - use crate::pasta_fp_plonk_index::WasmPastaFpPlonkIndex; - use crate::plonk_verifier_index::fp::WasmFpPlonkVerifierIndex as WasmPlonkVerifierIndex; - use crate::poly_comm::vesta::WasmFpPolyComm as WasmPolyComm; - use mina_curves::pasta::{Fp, Vesta as GAffine}; - - impl_proof!( - caml_pasta_fp_plonk_proof, - WasmGVesta, - GAffine, - WasmPastaFp, - Fp, - WasmPolyComm, - WasmSrs, - GAffineOther, - mina_poseidon::pasta::fp_kimchi, - mina_poseidon::pasta::fq_kimchi, - WasmPastaFpPlonkIndex, - WasmPlonkVerifierIndex, - Fp - ); -} - -pub mod fq { - use super::*; - use crate::arkworks::{WasmGPallas, WasmPastaFq}; - use crate::pasta_fq_plonk_index::WasmPastaFqPlonkIndex; - use crate::plonk_verifier_index::fq::WasmFqPlonkVerifierIndex as WasmPlonkVerifierIndex; - use crate::poly_comm::pallas::WasmFqPolyComm as WasmPolyComm; - use mina_curves::pasta::{Fq, Pallas as GAffine}; - - impl_proof!( - caml_pasta_fq_plonk_proof, - WasmGPallas, - GAffine, - WasmPastaFq, - Fq, - WasmPolyComm, - WasmSrs, - GAffineOther, - mina_poseidon::pasta::fq_kimchi, - mina_poseidon::pasta::fp_kimchi, - WasmPastaFqPlonkIndex, - WasmPlonkVerifierIndex, - Fq - ); -} diff --git a/src/lib/crypto/kimchi_bindings/wasm/src/plonk_verifier_index.rs b/src/lib/crypto/kimchi_bindings/wasm/src/plonk_verifier_index.rs deleted file mode 100644 index a0a68815fd6..00000000000 --- a/src/lib/crypto/kimchi_bindings/wasm/src/plonk_verifier_index.rs +++ /dev/null @@ -1,1065 +0,0 @@ -use crate::wasm_vector::WasmVector; -use ark_ec::AffineRepr; -use ark_ff::One; -use ark_poly::{EvaluationDomain, Radix2EvaluationDomain as Domain}; -use array_init::array_init; -use kimchi::circuits::{ - constraints::FeatureFlags, - lookup::index::LookupSelectors, - lookup::lookups::{LookupFeatures, LookupInfo, LookupPatterns}, - polynomials::permutation::{permutation_vanishing_polynomial, zk_w, Shifts}, - wires::{COLUMNS, PERMUTS}, -}; -use kimchi::linearization::expr_linearization; -use kimchi::poly_commitment::ipa::OpeningProof; -use kimchi::verifier_index::{LookupVerifierIndex, VerifierIndex as DlogVerifierIndex}; -use paste::paste; -use poly_commitment::commitment::PolyComm; -use poly_commitment::ipa::SRS; -use poly_commitment::SRS as _; -use std::path::Path; -use std::sync::Arc; -use wasm_bindgen::prelude::*; - -macro_rules! impl_verification_key { - ( - $name: ident, - $WasmG: ty, - $G: ty, - $WasmF: ty, - $F: ty, - $WasmPolyComm: ty, - $WasmSrs: ty, - $GOther: ty, - $FrSpongeParams: path, - $FqSpongeParams: path, - $WasmIndex: ty, - $field_name: ident - ) => { - paste! { - #[wasm_bindgen] - #[derive(Clone, Copy)] - pub struct [] { - pub log_size_of_group: i32, - pub group_gen: $WasmF, - } - type WasmDomain = []; - - #[wasm_bindgen] - impl []{ - #[wasm_bindgen(constructor)] - pub fn new(log_size_of_group: i32, group_gen: $WasmF) -> Self { - WasmDomain {log_size_of_group, group_gen} - } - } - - #[wasm_bindgen] - #[derive(Clone)] - pub struct [] { - #[wasm_bindgen(skip)] - pub sigma_comm: WasmVector<$WasmPolyComm>, - #[wasm_bindgen(skip)] - pub coefficients_comm: WasmVector<$WasmPolyComm>, - #[wasm_bindgen(skip)] - pub generic_comm: $WasmPolyComm, - #[wasm_bindgen(skip)] - pub psm_comm: $WasmPolyComm, - #[wasm_bindgen(skip)] - pub complete_add_comm: $WasmPolyComm, - #[wasm_bindgen(skip)] - pub mul_comm: $WasmPolyComm, - #[wasm_bindgen(skip)] - pub emul_comm: $WasmPolyComm, - #[wasm_bindgen(skip)] - pub endomul_scalar_comm: $WasmPolyComm, - #[wasm_bindgen(skip)] - pub xor_comm: Option<$WasmPolyComm>, - #[wasm_bindgen(skip)] - pub range_check0_comm: Option<$WasmPolyComm>, - #[wasm_bindgen(skip)] - pub range_check1_comm: Option<$WasmPolyComm>, - #[wasm_bindgen(skip)] - pub foreign_field_add_comm: Option<$WasmPolyComm>, - #[wasm_bindgen(skip)] - pub foreign_field_mul_comm: Option<$WasmPolyComm>, - #[wasm_bindgen(skip)] - pub rot_comm: Option<$WasmPolyComm> - } - - type WasmPlonkVerificationEvals = []; - - - #[wasm_bindgen] - impl [] { - #[allow(clippy::too_many_arguments)] - #[wasm_bindgen(constructor)] - pub fn new( - sigma_comm: WasmVector<$WasmPolyComm>, - coefficients_comm: WasmVector<$WasmPolyComm>, - generic_comm: &$WasmPolyComm, - psm_comm: &$WasmPolyComm, - complete_add_comm: &$WasmPolyComm, - mul_comm: &$WasmPolyComm, - emul_comm: &$WasmPolyComm, - endomul_scalar_comm: &$WasmPolyComm, - xor_comm: Option<$WasmPolyComm>, - range_check0_comm: Option<$WasmPolyComm>, - range_check1_comm: Option<$WasmPolyComm>, - foreign_field_add_comm: Option<$WasmPolyComm>, - foreign_field_mul_comm: Option<$WasmPolyComm>, - rot_comm: Option<$WasmPolyComm>, - ) -> Self { - WasmPlonkVerificationEvals { - sigma_comm: sigma_comm.clone(), - coefficients_comm: coefficients_comm.clone(), - generic_comm: generic_comm.clone(), - psm_comm: psm_comm.clone(), - complete_add_comm: complete_add_comm.clone(), - mul_comm: mul_comm.clone(), - emul_comm: emul_comm.clone(), - endomul_scalar_comm: endomul_scalar_comm.clone(), - xor_comm: xor_comm.clone(), - range_check0_comm: range_check0_comm.clone(), - range_check1_comm: range_check1_comm.clone(), - foreign_field_mul_comm: foreign_field_mul_comm.clone(), - foreign_field_add_comm: foreign_field_add_comm.clone(), - rot_comm: rot_comm.clone(), - } - } - - #[wasm_bindgen(getter)] - pub fn sigma_comm(&self) -> WasmVector<$WasmPolyComm> { - self.sigma_comm.clone() - } - - #[wasm_bindgen(setter)] - pub fn set_sigma_comm(&mut self, x: WasmVector<$WasmPolyComm>) { - self.sigma_comm = x; - } - - #[wasm_bindgen(getter)] - pub fn coefficients_comm(&self) -> WasmVector<$WasmPolyComm> { - self.coefficients_comm.clone() - } - - #[wasm_bindgen(setter)] - pub fn set_coefficients_comm(&mut self, x: WasmVector<$WasmPolyComm>) { - self.coefficients_comm = x; - } - - #[wasm_bindgen(getter)] - pub fn generic_comm(&self) -> $WasmPolyComm { - self.generic_comm.clone() - } - - #[wasm_bindgen(setter)] - pub fn set_generic_comm(&mut self, x: $WasmPolyComm) { - self.generic_comm = x; - } - - #[wasm_bindgen(getter)] - pub fn psm_comm(&self) -> $WasmPolyComm { - self.psm_comm.clone() - } - - #[wasm_bindgen(setter)] - pub fn set_psm_comm(&mut self, x: $WasmPolyComm) { - self.psm_comm = x; - } - - #[wasm_bindgen(getter)] - pub fn complete_add_comm(&self) -> $WasmPolyComm { - self.complete_add_comm.clone() - } - - #[wasm_bindgen(setter)] - pub fn set_complete_add_comm(&mut self, x: $WasmPolyComm) { - self.complete_add_comm = x; - } - - #[wasm_bindgen(getter)] - pub fn mul_comm(&self) -> $WasmPolyComm { - self.mul_comm.clone() - } - - #[wasm_bindgen(setter)] - pub fn set_mul_comm(&mut self, x: $WasmPolyComm) { - self.mul_comm = x; - } - - #[wasm_bindgen(getter)] - pub fn emul_comm(&self) -> $WasmPolyComm { - self.emul_comm.clone() - } - - #[wasm_bindgen(setter)] - pub fn set_emul_comm(&mut self, x: $WasmPolyComm) { - self.emul_comm = x; - } - - #[wasm_bindgen(getter)] - pub fn endomul_scalar_comm(&self) -> $WasmPolyComm { - self.endomul_scalar_comm.clone() - } - - #[wasm_bindgen(setter)] - pub fn set_endomul_scalar_comm(&mut self, x: $WasmPolyComm) { - self.endomul_scalar_comm = x; - } - - #[wasm_bindgen(getter)] - pub fn xor_comm(&self) -> Option<$WasmPolyComm> { - self.xor_comm.clone() - } - - #[wasm_bindgen(setter)] - pub fn set_xor_comm(&mut self, x: Option<$WasmPolyComm>) { - self.xor_comm = x; - } - - #[wasm_bindgen(getter)] - pub fn rot_comm(&self) -> Option<$WasmPolyComm> { - self.rot_comm.clone() - } - - #[wasm_bindgen(setter)] - pub fn set_rot_comm(&mut self, x: Option<$WasmPolyComm>) { - self.rot_comm = x; - } - - #[wasm_bindgen(getter)] - pub fn range_check0_comm(&self) -> Option<$WasmPolyComm> { - self.range_check0_comm.clone() - } - - #[wasm_bindgen(setter)] - pub fn set_range_check0_comm(&mut self, x: Option<$WasmPolyComm>) { - self.range_check0_comm = x; - } - - #[wasm_bindgen(getter)] - pub fn range_check1_comm(&self) -> Option<$WasmPolyComm> { - self.range_check1_comm.clone() - } - - #[wasm_bindgen(setter)] - pub fn set_range_check1_comm(&mut self, x: Option<$WasmPolyComm>) { - self.range_check1_comm = x; - } - - #[wasm_bindgen(getter)] - pub fn foreign_field_add_comm(&self) -> Option<$WasmPolyComm> { - self.foreign_field_add_comm.clone() - } - - #[wasm_bindgen(setter)] - pub fn set_foreign_field_add_comm(&mut self, x: Option<$WasmPolyComm>) { - self.foreign_field_add_comm = x; - } - - #[wasm_bindgen(getter)] - pub fn foreign_field_mul_comm(&self) -> Option<$WasmPolyComm> { - self.foreign_field_mul_comm.clone() - } - - #[wasm_bindgen(setter)] - pub fn set_foreign_field_mul_comm(&mut self, x: Option<$WasmPolyComm>) { - self.foreign_field_mul_comm = x; - } - - } - - #[derive(Clone, Copy)] - #[wasm_bindgen] - pub struct [] { - pub s0: $WasmF, - pub s1: $WasmF, - pub s2: $WasmF, - pub s3: $WasmF, - pub s4: $WasmF, - pub s5: $WasmF, - pub s6: $WasmF, - } - type WasmShifts = []; - - #[wasm_bindgen] - impl [] { - #[wasm_bindgen(constructor)] - pub fn new( - s0: $WasmF, - s1: $WasmF, - s2: $WasmF, - s3: $WasmF, - s4: $WasmF, - s5: $WasmF, - s6: $WasmF - ) -> Self { - Self { s0, s1, s2, s3, s4, s5, s6} - } - } - - #[wasm_bindgen] - #[derive(Clone)] - pub struct [] { - #[wasm_bindgen(skip)] - pub xor: Option<$WasmPolyComm>, - #[wasm_bindgen(skip)] - pub lookup : Option<$WasmPolyComm>, - #[wasm_bindgen(skip)] - pub range_check: Option<$WasmPolyComm>, - #[wasm_bindgen(skip)] - pub ffmul: Option<$WasmPolyComm>, - } - - type WasmLookupSelectors = []; - - impl From for LookupSelectors> { - fn from(x: WasmLookupSelectors) -> Self { - Self { - xor: x.xor.map(Into::into), - lookup: x.lookup.map(Into::into), - range_check: x.range_check.map(Into::into), - ffmul: x.ffmul.map(Into::into), - } - } - } - - impl From<&WasmLookupSelectors> for LookupSelectors> { - fn from(x: &WasmLookupSelectors) -> Self { - Self { - xor: x.xor.clone().map(Into::into), - lookup: x.lookup.clone().map(Into::into), - range_check: x.range_check.clone().map(Into::into), - ffmul: x.ffmul.clone().map(Into::into), - } - } - } - - impl From<&LookupSelectors>> for WasmLookupSelectors { - fn from(x: &LookupSelectors>) -> Self { - Self { - xor: x.xor.clone().map(Into::into), - lookup: x.lookup.clone().map(Into::into), - range_check: x.range_check.clone().map(Into::into), - ffmul: x.ffmul.clone().map(Into::into), - } - } - } - - impl From>> for WasmLookupSelectors { - fn from(x: LookupSelectors>) -> Self { - Self { - xor: x.xor.clone().map(Into::into), - lookup: x.lookup.clone().map(Into::into), - range_check: x.range_check.clone().map(Into::into), - ffmul: x.ffmul.clone().map(Into::into), - } - } - } - - #[wasm_bindgen] - impl [] { - #[wasm_bindgen(constructor)] - pub fn new( - xor: Option<$WasmPolyComm>, - lookup: Option<$WasmPolyComm>, - range_check: Option<$WasmPolyComm>, - ffmul: Option<$WasmPolyComm> - ) -> Self { - Self { - xor, - lookup, - range_check, - ffmul - } - } - - #[wasm_bindgen(getter)] - pub fn xor(&self) -> Option<$WasmPolyComm> { - self.xor.clone() - } - - #[wasm_bindgen(setter)] - pub fn set_xor(&mut self, x: Option<$WasmPolyComm>) { - self.xor = x - } - - #[wasm_bindgen(getter)] - pub fn lookup(&self) -> Option<$WasmPolyComm> { - self.lookup.clone() - } - - #[wasm_bindgen(setter)] - pub fn set_lookup(&mut self, x: Option<$WasmPolyComm>) { - self.lookup = x - } - - #[wasm_bindgen(getter)] - pub fn ffmul(&self) -> Option<$WasmPolyComm> { - self.ffmul.clone() - } - - #[wasm_bindgen(setter)] - pub fn set_ffmul(&mut self, x: Option<$WasmPolyComm>) { - self.ffmul = x - } - - #[wasm_bindgen(getter)] - pub fn range_check(&self) -> Option<$WasmPolyComm> { - self.range_check.clone() - } - - #[wasm_bindgen(setter)] - pub fn set_range_check(&mut self, x: Option<$WasmPolyComm>) { - self.range_check = x - } - } - - #[wasm_bindgen] - #[derive(Clone)] - pub struct [] { - pub joint_lookup_used: bool, - - #[wasm_bindgen(skip)] - pub lookup_table: WasmVector<$WasmPolyComm>, - - #[wasm_bindgen(skip)] - pub lookup_selectors: WasmLookupSelectors, - - #[wasm_bindgen(skip)] - pub table_ids: Option<$WasmPolyComm>, - - #[wasm_bindgen(skip)] - pub lookup_info: LookupInfo, - - #[wasm_bindgen(skip)] - pub runtime_tables_selector: Option<$WasmPolyComm>, - } - - type WasmLookupVerifierIndex = []; - - impl From<&LookupVerifierIndex<$G>> for WasmLookupVerifierIndex { - fn from(x: &LookupVerifierIndex<$G>) -> Self { - Self { - joint_lookup_used: x.joint_lookup_used.into(), - lookup_table: x.lookup_table.clone().iter().map(Into::into).collect(), - lookup_selectors: x.lookup_selectors.clone().into(), - table_ids: x.table_ids.clone().map(Into::into), - lookup_info: x.lookup_info.clone(), - runtime_tables_selector: x.runtime_tables_selector.clone().map(Into::into) - } - } - } - - impl From> for WasmLookupVerifierIndex { - fn from(x: LookupVerifierIndex<$G>) -> Self { - Self { - joint_lookup_used: x.joint_lookup_used.into(), - lookup_table: x.lookup_table.iter().map(Into::into).collect(), - lookup_selectors: x.lookup_selectors.into(), - table_ids: x.table_ids.map(Into::into), - lookup_info: x.lookup_info, - runtime_tables_selector: x.runtime_tables_selector.map(Into::into) - } - } - } - - - impl From<&WasmLookupVerifierIndex> for LookupVerifierIndex<$G> { - fn from(x: &WasmLookupVerifierIndex) -> Self { - Self { - joint_lookup_used: x.joint_lookup_used.into(), - lookup_table: x.lookup_table.clone().iter().map(Into::into).collect(), - lookup_selectors: x.lookup_selectors.clone().into(), - table_ids: x.table_ids.clone().map(Into::into), - lookup_info: x.lookup_info, - runtime_tables_selector: x.runtime_tables_selector.clone().map(Into::into) - } - } - } - - impl From for LookupVerifierIndex<$G> { - fn from(x: WasmLookupVerifierIndex) -> Self { - Self { - joint_lookup_used: x.joint_lookup_used.into(), - lookup_table: x.lookup_table.iter().map(Into::into).collect(), - lookup_selectors: x.lookup_selectors.into(), - table_ids: x.table_ids.map(Into::into), - lookup_info: x.lookup_info, - runtime_tables_selector: x.runtime_tables_selector.map(Into::into) - } - } - } - - #[wasm_bindgen] - impl [] { - #[wasm_bindgen(constructor)] - pub fn new( - joint_lookup_used: bool, - lookup_table: WasmVector<$WasmPolyComm>, - lookup_selectors: WasmLookupSelectors, - table_ids: Option<$WasmPolyComm>, - lookup_info: &LookupInfo, - runtime_tables_selector: Option<$WasmPolyComm> - ) -> WasmLookupVerifierIndex { - WasmLookupVerifierIndex { - joint_lookup_used, - lookup_table, - lookup_selectors, - table_ids, - lookup_info: lookup_info.clone(), - runtime_tables_selector - } - } - - #[wasm_bindgen(getter)] - pub fn lookup_table(&self) -> WasmVector<$WasmPolyComm> { - self.lookup_table.clone() - } - - #[wasm_bindgen(setter)] - pub fn set_lookup_table(&mut self, x: WasmVector<$WasmPolyComm>) { - self.lookup_table = x - } - - #[wasm_bindgen(getter)] - pub fn lookup_selectors(&self) -> WasmLookupSelectors { - self.lookup_selectors.clone() - } - - #[wasm_bindgen(setter)] - pub fn set_lookup_selectors(&mut self, x: WasmLookupSelectors) { - self.lookup_selectors = x - } - - #[wasm_bindgen(getter)] - pub fn table_ids(&self) -> Option<$WasmPolyComm>{ - self.table_ids.clone() - } - - #[wasm_bindgen(setter)] - pub fn set_table_ids(&mut self, x: Option<$WasmPolyComm>) { - self.table_ids = x - } - - #[wasm_bindgen(getter)] - pub fn lookup_info(&self) -> LookupInfo { - self.lookup_info.clone() - } - - #[wasm_bindgen(setter)] - pub fn set_lookup_info(&mut self, x: LookupInfo) { - self.lookup_info = x - } - - #[wasm_bindgen(getter)] - pub fn runtime_tables_selector(&self) -> Option<$WasmPolyComm> { - self.runtime_tables_selector.clone() - } - - #[wasm_bindgen(setter)] - pub fn set_runtime_tables_selector(&mut self, x: Option<$WasmPolyComm>) { - self.runtime_tables_selector = x - } - } - - #[wasm_bindgen] - #[derive(Clone)] - pub struct [] { - pub domain: WasmDomain, - pub max_poly_size: i32, - pub public_: i32, - pub prev_challenges: i32, - #[wasm_bindgen(skip)] - pub srs: $WasmSrs, - #[wasm_bindgen(skip)] - pub evals: WasmPlonkVerificationEvals, - pub shifts: WasmShifts, - #[wasm_bindgen(skip)] - pub lookup_index: Option, - pub zk_rows: isize, - } - type WasmPlonkVerifierIndex = []; - - #[wasm_bindgen] - impl [] { - #[wasm_bindgen(constructor)] - pub fn new( - domain: &WasmDomain, - max_poly_size: i32, - public_: i32, - prev_challenges: i32, - srs: &$WasmSrs, - evals: &WasmPlonkVerificationEvals, - shifts: &WasmShifts, - lookup_index: Option, - zk_rows: isize, - ) -> Self { - WasmPlonkVerifierIndex { - domain: domain.clone(), - max_poly_size, - public_, - prev_challenges, - srs: srs.clone(), - evals: evals.clone(), - shifts: shifts.clone(), - lookup_index: lookup_index.clone(), - zk_rows, - } - } - - #[wasm_bindgen(getter)] - pub fn srs(&self) -> $WasmSrs { - self.srs.clone() - } - - #[wasm_bindgen(setter)] - pub fn set_srs(&mut self, x: $WasmSrs) { - self.srs = x - } - - #[wasm_bindgen(getter)] - pub fn evals(&self) -> WasmPlonkVerificationEvals { - self.evals.clone() - } - - #[wasm_bindgen(setter)] - pub fn set_evals(&mut self, x: WasmPlonkVerificationEvals) { - self.evals = x - } - - #[wasm_bindgen(getter)] - pub fn lookup_index(&self) -> Option { - self.lookup_index.clone() - } - - #[wasm_bindgen(setter)] - pub fn set_lookup_index(&mut self, li: Option) { - self.lookup_index = li - } - } - - pub fn to_wasm<'a>( - srs: &Arc>, - vi: DlogVerifierIndex<$G, OpeningProof<$G>>, - ) -> WasmPlonkVerifierIndex { - WasmPlonkVerifierIndex { - domain: WasmDomain { - log_size_of_group: vi.domain.log_size_of_group as i32, - group_gen: vi.domain.group_gen.into(), - }, - max_poly_size: vi.max_poly_size as i32, - public_: vi.public as i32, - prev_challenges: vi.prev_challenges as i32, - srs: srs.into(), - evals: WasmPlonkVerificationEvals { - sigma_comm: IntoIterator::into_iter(vi.sigma_comm).map(From::from).collect(), - coefficients_comm: IntoIterator::into_iter(vi.coefficients_comm).map(From::from).collect(), - generic_comm: vi.generic_comm.into(), - psm_comm: vi.psm_comm.into(), - complete_add_comm: vi.complete_add_comm.into(), - mul_comm: vi.mul_comm.into(), - emul_comm: vi.emul_comm.into(), - endomul_scalar_comm: vi.endomul_scalar_comm.into(), - xor_comm: vi.xor_comm.map(|v| v.into()), - range_check0_comm: vi.range_check0_comm.map(|v| v.into()), - range_check1_comm: vi.range_check1_comm.map(|v| v.into()), - foreign_field_add_comm: vi.foreign_field_add_comm.map(|v| v.into()), - foreign_field_mul_comm: vi.foreign_field_mul_comm.map(|v| v.into()), - rot_comm: vi.rot_comm.map(|v| v.into()) - }, - shifts: - WasmShifts { - s0: vi.shift[0].into(), - s1: vi.shift[1].into(), - s2: vi.shift[2].into(), - s3: vi.shift[3].into(), - s4: vi.shift[4].into(), - s5: vi.shift[5].into(), - s6: vi.shift[6].into(), - }, - lookup_index: vi.lookup_index.map(Into::into), - zk_rows: vi.zk_rows as isize, - } - } - - /* pub fn to_wasm_copy<'a>( - srs: &Arc>, - vi: &DlogVerifierIndex, - ) -> WasmPlonkVerifierIndex { - WasmPlonkVerifierIndex { - domain: WasmDomain { - log_size_of_group: vi.domain.log_size_of_group as i32, - group_gen: vi.domain.group_gen.clone().into(), - }, - max_poly_size: vi.max_poly_size as i32, - srs: srs.clone().into(), - evals: WasmPlonkVerificationEvals { - sigma_comm: vi.sigma_comm.iter().map(From::from).collect(), - coefficients_comm: vi.coefficients_comm.iter().map(From::from).collect(), - generic_comm: vi.generic_comm.clone().into(), - psm_comm: vi.psm_comm.clone().into(), - complete_add_comm: vi.complete_add_comm.clone().into(), - mul_comm: vi.mul_comm.clone().into(), - emul_comm: vi.emul_comm.clone().into(), - endomul_scalar_comm: vi.endomul_scalar_comm.clone().into(), - }, - shifts: - WasmShifts { - s0: vi.shift[0].clone().into(), - s1: vi.shift[1].clone().into(), - s2: vi.shift[2].clone().into(), - s3: vi.shift[3].clone().into(), - s4: vi.shift[4].clone().into(), - s5: vi.shift[5].clone().into(), - s6: vi.shift[6].clone().into(), - }, - linearization: [](Box::new(vi.linearization.clone())), - } - } */ - - fn compute_feature_flags(index: &WasmPlonkVerifierIndex) -> FeatureFlags { - let xor = index.evals.xor_comm.is_some(); - let range_check0 = index.evals.range_check0_comm.is_some(); - let range_check1 = index.evals.range_check1_comm.is_some(); - let foreign_field_add = index.evals.foreign_field_add_comm.is_some(); - let foreign_field_mul = index.evals.foreign_field_mul_comm.is_some(); - let rot = index.evals.rot_comm.is_some(); - - let lookup = index - .lookup_index.as_ref() - .map_or(false, |li| li.lookup_info.features.patterns.lookup); - - let runtime_tables = index - .lookup_index.as_ref() - .map_or(false, |li| li.runtime_tables_selector.is_some()); - - let patterns = LookupPatterns { - xor, - lookup, - range_check: range_check0 || range_check1 || rot, - foreign_field_mul, - }; - - FeatureFlags { - range_check0, - range_check1, - foreign_field_add, - foreign_field_mul, - xor, - rot, - lookup_features: LookupFeatures { - patterns, - joint_lookup_used: patterns.joint_lookups_used(), - uses_runtime_tables: runtime_tables, - }, - } - } - - pub fn of_wasm( - index: WasmPlonkVerifierIndex, - ) -> (DlogVerifierIndex>, Arc>) { - let max_poly_size = index.max_poly_size; - let public_ = index.public_; - let prev_challenges = index.prev_challenges; - let log_size_of_group = index.domain.log_size_of_group; - let srs = &index.srs; - let evals = &index.evals; - let shifts = &index.shifts; - - /* - let urs_copy = Rc::clone(&*urs); - let urs_copy_outer = Rc::clone(&*urs); - let srs = { - // We know that the underlying value is still alive, because we never convert any of our - // Rc<_>s into weak pointers. - SRSValue::Ref(unsafe { &*Rc::into_raw(urs_copy) }) - }; */ - let (endo_q, _endo_r) = poly_commitment::ipa::endos::<$GOther>(); - let domain = Domain::<$F>::new(1 << log_size_of_group).unwrap(); - - let feature_flags = compute_feature_flags(&index); - let (linearization, powers_of_alpha) = expr_linearization(Some(&feature_flags), true); - - let index = { - let zk_rows = index.zk_rows as u64; - - DlogVerifierIndex { - domain, - - sigma_comm: array_init(|i| (&evals.sigma_comm[i]).into()), - generic_comm: (&evals.generic_comm).into(), - coefficients_comm: array_init(|i| (&evals.coefficients_comm[i]).into()), - - psm_comm: (&evals.psm_comm).into(), - - complete_add_comm: (&evals.complete_add_comm).into(), - mul_comm: (&evals.mul_comm).into(), - emul_comm: (&evals.emul_comm).into(), - - endomul_scalar_comm: (&evals.endomul_scalar_comm).into(), - xor_comm: (&evals.xor_comm).as_ref().map(Into::into), - range_check0_comm: (&evals.range_check0_comm).as_ref().map(Into::into), - range_check1_comm: (&evals.range_check1_comm).as_ref().map(Into::into), - foreign_field_add_comm: (&evals.foreign_field_add_comm).as_ref().map(Into::into), - foreign_field_mul_comm: (&evals.foreign_field_mul_comm).as_ref().map(Into::into), - rot_comm: (&evals.rot_comm).as_ref().map(Into::into), - - w: { - let res = once_cell::sync::OnceCell::new(); - res.set(zk_w(domain, zk_rows)).unwrap(); - res - }, - endo: endo_q, - max_poly_size: max_poly_size as usize, - public: public_ as usize, - prev_challenges: prev_challenges as usize, - permutation_vanishing_polynomial_m: { - let res = once_cell::sync::OnceCell::new(); - res.set(permutation_vanishing_polynomial(domain, zk_rows)).unwrap(); - res - }, - shift: [ - shifts.s0.into(), - shifts.s1.into(), - shifts.s2.into(), - shifts.s3.into(), - shifts.s4.into(), - shifts.s5.into(), - shifts.s6.into() - ], - srs: { - Arc::clone(&srs.0) - }, - - zk_rows, - - linearization, - powers_of_alpha, - lookup_index: index.lookup_index.map(Into::into), - } - }; - (index, srs.0.clone()) - } - - impl From for DlogVerifierIndex<$G, OpeningProof<$G>> { - fn from(index: WasmPlonkVerifierIndex) -> Self { - of_wasm(index).0 - } - } - - pub fn read_raw( - offset: Option, - srs: &$WasmSrs, - path: String, - ) -> Result>, JsValue> { - let path = Path::new(&path); - let (endo_q, _endo_r) = poly_commitment::ipa::endos::(); - DlogVerifierIndex::<$G, OpeningProof<$G>>::from_file( - srs.0.clone(), - path, - offset.map(|x| x as u64), - endo_q, - ).map_err(|e| JsValue::from_str(format!("read_raw: {}", e).as_str())) - } - - #[wasm_bindgen] - pub fn [<$name:snake _read>]( - offset: Option, - srs: &$WasmSrs, - path: String, - ) -> Result { - let vi = read_raw(offset, srs, path)?; - Ok(to_wasm(srs, vi.into())) - } - - #[wasm_bindgen] - pub fn [<$name:snake _write>]( - append: Option, - index: WasmPlonkVerifierIndex, - path: String, - ) -> Result<(), JsValue> { - let index: DlogVerifierIndex<$G, OpeningProof<$G>> = index.into(); - let path = Path::new(&path); - index.to_file(path, append).map_err(|e| { - println!("{}", e); - JsValue::from_str("caml_pasta_fp_plonk_verifier_index_raw_read") - }) - } - - // TODO understand what serialization format we need - - // #[wasm_bindgen] - // pub fn [<$name:snake _serialize>]( - // index: WasmPlonkVerifierIndex, - // ) -> Box<[u8]> { - // let index: DlogVerifierIndex<$G> = index.into(); - // rmp_serde::to_vec(&index).unwrap().into_boxed_slice() - // } - - // #[wasm_bindgen] - // pub fn [<$name:snake _deserialize>]( - // srs: &$WasmSrs, - // index: Box<[u8]>, - // ) -> WasmPlonkVerifierIndex { - // let mut vi: DlogVerifierIndex<$G> = rmp_serde::from_slice(&index).unwrap(); - // vi.linearization = expr_linearization(vi.domain, false, false, None); - // return to_wasm(srs, vi.into()) - // } - - #[wasm_bindgen] - pub fn [<$name:snake _serialize>]( - index: WasmPlonkVerifierIndex, - ) -> String { - let index: DlogVerifierIndex<$G, OpeningProof<$G>> = index.into(); - serde_json::to_string(&index).unwrap() - } - - #[wasm_bindgen] - pub fn [<$name:snake _deserialize>]( - srs: &$WasmSrs, - index: String, - ) -> Result { - let vi: Result>, serde_json::Error> = serde_json::from_str(&index); - match vi { - Ok(vi) => Ok(to_wasm(srs, vi)), - Err(e) => Err(JsError::new(&(e.to_string()))), - } - } - - #[wasm_bindgen] - pub fn [<$name:snake _create>]( - index: &$WasmIndex, - ) -> WasmPlonkVerifierIndex { - index.0.srs.get_lagrange_basis(index.0.as_ref().cs.domain.d1); - let verifier_index = index.0.as_ref().verifier_index(); - to_wasm(&index.0.as_ref().srs, verifier_index) - } - - #[wasm_bindgen] - pub fn [<$name:snake _shifts>](log2_size: i32) -> WasmShifts { - let domain = Domain::<$F>::new(1 << log2_size).unwrap(); - let shifts = Shifts::new(&domain); - let s = shifts.shifts(); - WasmShifts { - s0: s[0].clone().into(), - s1: s[1].clone().into(), - s2: s[2].clone().into(), - s3: s[3].clone().into(), - s4: s[4].clone().into(), - s5: s[5].clone().into(), - s6: s[6].clone().into(), - } - } - - #[wasm_bindgen] - pub fn [<$name:snake _dummy>]() -> WasmPlonkVerifierIndex { - fn comm() -> $WasmPolyComm { - let g: $WasmG = $G::generator().into(); - $WasmPolyComm { - shifted: None, - unshifted: vec![g].into(), - } - } - fn vec_comm(num: usize) -> WasmVector<$WasmPolyComm> { - (0..num).map(|_| comm()).collect() - } - - WasmPlonkVerifierIndex { - domain: WasmDomain { - log_size_of_group: 1, - group_gen: $F::one().into(), - }, - max_poly_size: 0, - public_: 0, - prev_challenges: 0, - srs: $WasmSrs(Arc::new(SRS::create(0))), - evals: WasmPlonkVerificationEvals { - sigma_comm: vec_comm(PERMUTS), - coefficients_comm: vec_comm(COLUMNS), - generic_comm: comm(), - psm_comm: comm(), - complete_add_comm: comm(), - mul_comm: comm(), - emul_comm: comm(), - endomul_scalar_comm: comm(), - xor_comm: None, - range_check0_comm: None, - range_check1_comm: None, - foreign_field_add_comm: None, - foreign_field_mul_comm: None, - rot_comm: None, - }, - shifts: - WasmShifts { - s0: $F::one().into(), - s1: $F::one().into(), - s2: $F::one().into(), - s3: $F::one().into(), - s4: $F::one().into(), - s5: $F::one().into(), - s6: $F::one().into(), - }, - lookup_index: None, - zk_rows: 3, - } - } - - #[wasm_bindgen] - pub fn [<$name:snake _deep_copy>]( - x: &WasmPlonkVerifierIndex, - ) -> WasmPlonkVerifierIndex { - x.clone() - } - - } - } -} - -pub mod fp { - use super::*; - use crate::arkworks::{WasmGVesta, WasmPastaFp}; - use crate::pasta_fp_plonk_index::WasmPastaFpPlonkIndex; - use crate::poly_comm::vesta::WasmFpPolyComm as WasmPolyComm; - use crate::srs::fp::WasmFpSrs; - use mina_curves::pasta::{Fp, Pallas as GAffineOther, Vesta as GAffine}; - - impl_verification_key!( - caml_pasta_fp_plonk_verifier_index, - WasmGVesta, - GAffine, - WasmPastaFp, - Fp, - WasmPolyComm, - WasmFpSrs, - GAffineOther, - mina_poseidon::pasta::fp_kimchi, - mina_poseidon::pasta::fq_kimchi, - WasmPastaFpPlonkIndex, - Fp - ); -} - -pub mod fq { - use super::*; - use crate::arkworks::{WasmGPallas, WasmPastaFq}; - use crate::pasta_fq_plonk_index::WasmPastaFqPlonkIndex; - use crate::poly_comm::pallas::WasmFqPolyComm as WasmPolyComm; - use crate::srs::fq::WasmFqSrs; - use mina_curves::pasta::{Fq, Pallas as GAffine, Vesta as GAffineOther}; - - impl_verification_key!( - caml_pasta_fq_plonk_verifier_index, - WasmGPallas, - GAffine, - WasmPastaFq, - Fq, - WasmPolyComm, - WasmFqSrs, - GAffineOther, - mina_poseidon::pasta::fq_kimchi, - mina_poseidon::pasta::fp_kimchi, - WasmPastaFqPlonkIndex, - Fq - ); -} diff --git a/src/lib/crypto/kimchi_bindings/wasm/src/poly_comm.rs b/src/lib/crypto/kimchi_bindings/wasm/src/poly_comm.rs deleted file mode 100644 index 6c9ef6edf7f..00000000000 --- a/src/lib/crypto/kimchi_bindings/wasm/src/poly_comm.rs +++ /dev/null @@ -1,115 +0,0 @@ -use crate::wasm_vector::WasmVector; -use paste::paste; -macro_rules! impl_poly_comm { - ( - $WasmG: ty, - $G: ty, - $field_name: ident - /* - $CamlScalarField: ty, - $BaseField: ty, - $CamlBaseField: ty, - $Projective: ty */ - ) => { - paste! { - use wasm_bindgen::prelude::*; - use poly_commitment::commitment::PolyComm; - - #[wasm_bindgen] - #[derive(Clone)] - pub struct [] { - #[wasm_bindgen(skip)] - pub unshifted: WasmVector<$WasmG>, - pub shifted: Option<$WasmG>, - } - - type WasmPolyComm = []; - - #[wasm_bindgen] - impl [] { - #[wasm_bindgen(constructor)] - pub fn new(unshifted: WasmVector<$WasmG>, shifted: Option<$WasmG>) -> Self { - assert!( - shifted.is_none(), - "mina#14628: Shifted commitments are deprecated and must not be used" - ); - WasmPolyComm { unshifted, shifted } - } - - #[wasm_bindgen(getter)] - pub fn unshifted(&self) -> WasmVector<$WasmG> { - self.unshifted.clone() - } - - #[wasm_bindgen(setter)] - pub fn set_unshifted(&mut self, x: WasmVector<$WasmG>) { - self.unshifted = x - } - } - - impl From> for WasmPolyComm { - fn from(x: PolyComm<$G>) -> Self { - let PolyComm { chunks } = x; - let unshifted: Vec<$WasmG> = - chunks.into_iter().map(|x| x.into()).collect(); - WasmPolyComm { - unshifted: unshifted.into(), - shifted: None - } - } - } - - impl From<&PolyComm<$G>> for WasmPolyComm { - fn from(x: &PolyComm<$G>) -> Self { - let unshifted: Vec<$WasmG> = - x.chunks.iter().map(|x| x.into()).collect(); - WasmPolyComm { - unshifted: unshifted.into(), - shifted: None, - } - } - } - - impl From for PolyComm<$G> { - fn from(x: WasmPolyComm) -> Self { - let WasmPolyComm {unshifted, shifted} = x; - assert!( - shifted.is_none(), - "mina#14628: Shifted commitments are deprecated and must not be used" - ); - PolyComm { - chunks: (*unshifted).iter().map(|x| { (*x).into() }).collect(), - } - } - } - - impl From<&WasmPolyComm> for PolyComm<$G> { - fn from(x: &WasmPolyComm) -> Self { - assert!( - x.shifted.is_none(), - "mina#14628: Shifted commitments are deprecated and must not be used" - ); - PolyComm { - chunks: x.unshifted.iter().map(|x| { (*x).into() }).collect(), - } - } - } - } - }; -} - -pub mod pallas { - use super::*; - use crate::arkworks::group_affine::WasmGPallas; - use mina_curves::pasta::Pallas as GAffine; - - impl_poly_comm!(WasmGPallas, GAffine, Fq); -} - -pub mod vesta { - use super::*; - use crate::arkworks::group_affine::WasmGVesta; - use mina_curves::pasta::Vesta as GAffine; - - impl_poly_comm!(WasmGVesta, GAffine, Fp); -} diff --git a/src/lib/crypto/kimchi_bindings/wasm/src/poseidon.rs b/src/lib/crypto/kimchi_bindings/wasm/src/poseidon.rs deleted file mode 100644 index 378505665a6..00000000000 --- a/src/lib/crypto/kimchi_bindings/wasm/src/poseidon.rs +++ /dev/null @@ -1,44 +0,0 @@ -use mina_curves::pasta::{Fp, Fq}; -use mina_poseidon::{constants::PlonkSpongeConstantsKimchi, permutation::poseidon_block_cipher}; -use wasm_bindgen::prelude::*; - -use crate::{ - arkworks::{WasmPastaFp, WasmPastaFq}, - wasm_flat_vector::WasmFlatVector, -}; - -// fp - -#[wasm_bindgen] -pub fn caml_pasta_fp_poseidon_block_cipher( - state: WasmFlatVector, -) -> WasmFlatVector { - let mut state_vec: Vec = state.into_iter().map(Into::into).collect(); - poseidon_block_cipher::( - mina_poseidon::pasta::fp_kimchi::static_params(), - &mut state_vec, - ); - state_vec - .iter() - .map(|f| WasmPastaFp(*f)) - .collect::>() - .into() -} - -// fq - -#[wasm_bindgen] -pub fn caml_pasta_fq_poseidon_block_cipher( - state: WasmFlatVector, -) -> WasmFlatVector { - let mut state_vec: Vec = state.into_iter().map(Into::into).collect(); - poseidon_block_cipher::( - mina_poseidon::pasta::fq_kimchi::static_params(), - &mut state_vec, - ); - state_vec - .iter() - .map(|f| WasmPastaFq(*f)) - .collect::>() - .into() -} diff --git a/src/lib/crypto/kimchi_bindings/wasm/src/projective.rs b/src/lib/crypto/kimchi_bindings/wasm/src/projective.rs deleted file mode 100644 index 3da74f3318b..00000000000 --- a/src/lib/crypto/kimchi_bindings/wasm/src/projective.rs +++ /dev/null @@ -1,152 +0,0 @@ -use ark_ec::{AffineRepr, CurveGroup, Group}; -use ark_ff::UniformRand; -use paste::paste; -use rand::rngs::StdRng; - -use wasm_bindgen::prelude::*; - -macro_rules! impl_projective { - ($name: ident, - $GroupProjective: ty, - $CamlG: ty, - $CamlScalarField: ty, - $BaseField: ty, - $CamlBaseField: ty, - $Projective: ty) => { - - paste! { - #[wasm_bindgen] - pub fn []() -> $GroupProjective { - $Projective::generator().into() - } - - #[wasm_bindgen] - pub fn []( - x: &$GroupProjective, - y: &$GroupProjective, - ) -> $GroupProjective { - x.as_ref() + y.as_ref() - } - - #[wasm_bindgen] - pub fn []( - x: &$GroupProjective, - y: &$GroupProjective, - ) -> $GroupProjective { - x.as_ref() - y.as_ref() - } - - #[wasm_bindgen] - pub fn []( - x: &$GroupProjective, - ) -> $GroupProjective { - -(*x.as_ref()) - } - - #[wasm_bindgen] - pub fn []( - x: &$GroupProjective, - ) -> $GroupProjective { - x.as_ref().double().into() - } - - #[wasm_bindgen] - pub fn []( - x: &$GroupProjective, - y: $CamlScalarField, - ) -> $GroupProjective { - let y: ark_ff::BigInteger256 = y.0.into(); - x.as_ref().mul_bigint(&y).into() - } - - #[wasm_bindgen] - pub fn []() -> $GroupProjective { - let rng = &mut rand::rngs::OsRng; - let proj: $Projective = UniformRand::rand(rng); - proj.into() - } - - #[wasm_bindgen] - pub fn [](i: u32) -> $GroupProjective { - // We only care about entropy here, so we force a conversion i32 -> u32. - let i: u64 = (i as u32).into(); - let mut rng: StdRng = rand::SeedableRng::seed_from_u64(i); - let proj: $Projective = UniformRand::rand(&mut rng); - proj.into() - } - - #[wasm_bindgen] - pub extern "C" fn []() -> $CamlBaseField { - let (endo_q, _endo_r) = poly_commitment::ipa::endos::(); - endo_q.into() - } - - #[wasm_bindgen] - pub extern "C" fn []() -> $CamlScalarField { - let (_endo_q, endo_r) = poly_commitment::ipa::endos::(); - endo_r.into() - } - - #[wasm_bindgen] - pub fn []( - x: &$GroupProjective - ) -> $CamlG { - x.as_ref().into_affine().into() - } - - #[wasm_bindgen] - pub fn [](x: $CamlG) -> $GroupProjective { - Into::::into(x).into_group().into() - } - - #[wasm_bindgen] - pub fn [](x: $CamlBaseField, y: $CamlBaseField) -> $GroupProjective { - let res = $Projective::new_unchecked(x.into(), y.into(), <$BaseField as ark_ff::One>::one()); - res.into() - } - - #[wasm_bindgen] - pub fn [](x: $CamlG) -> $CamlG { - x - } - } - } -} - -pub mod pallas { - use super::*; - use crate::arkworks::group_affine::WasmGPallas; - use crate::arkworks::group_projective::WasmPallasGProjective; - use crate::arkworks::pasta_fp::WasmPastaFp; - use crate::arkworks::pasta_fq::WasmPastaFq; - use mina_curves::pasta::{Fp, Pallas as GAffine, ProjectivePallas}; - - impl_projective!( - pallas, - WasmPallasGProjective, - WasmGPallas, - WasmPastaFq, - Fp, - WasmPastaFp, - ProjectivePallas - ); -} - -pub mod vesta { - use super::*; - use crate::arkworks::group_affine::WasmGVesta; - use crate::arkworks::group_projective::WasmVestaGProjective; - use crate::arkworks::pasta_fp::WasmPastaFp; - use crate::arkworks::pasta_fq::WasmPastaFq; - use mina_curves::pasta::{Fq, ProjectiveVesta, Vesta as GAffine}; - - impl_projective!( - vesta, - WasmVestaGProjective, - WasmGVesta, - WasmPastaFp, - Fq, - WasmPastaFq, - ProjectiveVesta - ); -} diff --git a/src/lib/crypto/kimchi_bindings/wasm/src/rayon.rs b/src/lib/crypto/kimchi_bindings/wasm/src/rayon.rs deleted file mode 100644 index f638b0c7d77..00000000000 --- a/src/lib/crypto/kimchi_bindings/wasm/src/rayon.rs +++ /dev/null @@ -1,157 +0,0 @@ -/* - * Copyright 2022 Google Inc. All Rights Reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -use js_sys::Promise; -use spmc::{channel, Receiver, Sender}; -use wasm_bindgen::prelude::*; - -#[cfg(feature = "nodejs")] -use js_sys::JsString; - -static mut THREAD_POOL: Option = None; - -pub fn run_in_pool(op: OP) -> R -where - OP: FnOnce() -> R + Send, - R: Send, -{ - let pool = unsafe { THREAD_POOL.as_ref().unwrap() }; - pool.install(op) -} - -#[wasm_bindgen] -#[doc(hidden)] -pub struct PoolBuilder { - num_threads: usize, - sender: Sender, - receiver: Receiver, -} - -#[cfg(not(feature = "nodejs"))] -#[wasm_bindgen] -extern "C" { - #[wasm_bindgen(js_name = startWorkers)] - fn start_workers(module: JsValue, memory: JsValue, builder: PoolBuilder) -> Promise; -} -#[cfg(feature = "nodejs")] -#[wasm_bindgen] -extern "C" { - #[wasm_bindgen(js_name = startWorkers)] - fn start_workers(module: JsString, memory: JsValue, builder: PoolBuilder) -> Promise; -} -#[wasm_bindgen] -extern "C" { - #[wasm_bindgen(js_name = terminateWorkers)] - fn terminate_workers() -> Promise; -} - -#[wasm_bindgen] -impl PoolBuilder { - fn new(num_threads: usize) -> Self { - let (sender, receiver) = channel(); - Self { - num_threads, - sender, - receiver, - } - } - - #[wasm_bindgen(js_name = numThreads)] - pub fn num_threads(&self) -> usize { - self.num_threads - } - - pub fn receiver(&self) -> *const Receiver { - &self.receiver - } - - // This should be called by the JS side once all the Workers are spawned. - // Important: it must take `self` by reference, otherwise - // `start_worker_thread` will try to receive a message on a moved value. - pub fn build(&mut self) { - unsafe { - THREAD_POOL = Some( - rayon::ThreadPoolBuilder::new() - .num_threads(self.num_threads) - // We could use postMessage here instead of Rust channels, - // but currently we can't due to a Chrome bug that will cause - // the main thread to lock up before it even sends the message: - // https://bugs.chromium.org/p/chromium/issues/detail?id=1075645 - .spawn_handler(move |thread| { - // Note: `send` will return an error if there are no receivers. - // We can use it because all the threads are spawned and ready to accept - // messages by the time we call `build()` to instantiate spawn handler. - self.sender.send(thread).unwrap_throw(); - Ok(()) - }) - .build() - .unwrap_throw(), - ) - } - } -} - -#[cfg(feature = "nodejs")] -#[wasm_bindgen(js_name = initThreadPool)] -#[doc(hidden)] -pub fn init_thread_pool(num_threads: usize, worker_source: JsString) -> Promise { - start_workers( - worker_source, - wasm_bindgen::memory(), - PoolBuilder::new(num_threads), - ) -} - -#[cfg(not(feature = "nodejs"))] -#[wasm_bindgen(js_name = initThreadPool)] -#[doc(hidden)] -pub fn init_thread_pool(num_threads: usize) -> Promise { - start_workers( - wasm_bindgen::module(), - wasm_bindgen::memory(), - PoolBuilder::new(num_threads), - ) -} - -#[wasm_bindgen(js_name = exitThreadPool)] -#[doc(hidden)] -pub fn exit_thread_pool() -> Promise { - unsafe { - let promise = terminate_workers(); - THREAD_POOL = None; - promise - } -} - -#[wasm_bindgen] -#[allow(clippy::not_unsafe_ptr_arg_deref)] -#[doc(hidden)] -pub fn wbg_rayon_start_worker(receiver: *const Receiver) -where - // Statically assert that it's safe to accept `Receiver` from another thread. - Receiver: Sync, -{ - // This is safe, because we know it came from a reference to PoolBuilder, - // allocated on the heap by wasm-bindgen and dropped only once all the - // threads are running. - // - // The only way to violate safety is if someone externally calls - // `exports.wbg_rayon_start_worker(garbageValue)`, but then no Rust tools - // would prevent us from issues anyway. - let receiver = unsafe { &*receiver }; - // Wait for a task (`ThreadBuilder`) on the channel, and, once received, - // start executing it. - // - // On practice this will start running Rayon's internal event loop. - receiver.recv().unwrap_throw().run(); -} diff --git a/src/lib/crypto/kimchi_bindings/wasm/src/srs.rs b/src/lib/crypto/kimchi_bindings/wasm/src/srs.rs deleted file mode 100644 index 84bb117b563..00000000000 --- a/src/lib/crypto/kimchi_bindings/wasm/src/srs.rs +++ /dev/null @@ -1,370 +0,0 @@ -use crate::wasm_flat_vector::WasmFlatVector; -use crate::wasm_vector::WasmVector; -use ark_poly::DenseUVPolynomial; -use ark_poly::{univariate::DensePolynomial, EvaluationDomain, Evaluations}; -use paste::paste; -use poly_commitment::SRS as ISRS; -use poly_commitment::{commitment::b_poly_coefficients, hash_map_cache::HashMapCache, ipa::SRS}; -use serde::{Deserialize, Serialize}; -use std::ops::Deref; -use std::{ - fs::{File, OpenOptions}, - io::{BufReader, BufWriter, Seek, SeekFrom::Start}, - sync::Arc, -}; -use wasm_bindgen::prelude::*; - -macro_rules! impl_srs { - ($name: ident, - $WasmF: ty, - $WasmG: ty, - $F: ty, - $G: ty, - $WasmPolyComm: ty, - $field_name: ident) => { - paste! { - #[wasm_bindgen] - #[derive(Clone)] - pub struct []( - #[wasm_bindgen(skip)] - pub Arc>); - - impl Deref for [] { - type Target = Arc>; - - fn deref(&self) -> &Self::Target { &self.0 } - } - - impl From>> for [] { - fn from(x: Arc>) -> Self { - [](x) - } - } - - impl From<&Arc>> for [] { - fn from(x: &Arc>) -> Self { - [](x.clone()) - } - } - - impl From<[]> for Arc> { - fn from(x: []) -> Self { - x.0 - } - } - - impl From<&[]> for Arc> { - fn from(x: &[]) -> Self { - x.0.clone() - } - } - - impl<'a> From<&'a []> for &'a Arc> { - fn from(x: &'a []) -> Self { - &x.0 - } - } - - #[wasm_bindgen] - pub fn [<$name:snake _create>](depth: i32) -> [] { - Arc::new(SRS::create(depth as usize)).into() - } - - #[wasm_bindgen] - pub fn [<$name:snake _add_lagrange_basis>]( - srs: &[], - log2_size: i32, - ) { - crate::rayon::run_in_pool(|| { - let domain = EvaluationDomain::<$F>::new(1 << (log2_size as usize)).expect("invalid domain size"); - srs.get_lagrange_basis(domain); - }); - } - - #[wasm_bindgen] - pub fn [<$name:snake _write>]( - append: Option, - srs: &[], - path: String, - ) -> Result<(), JsValue> { - let file = OpenOptions::new() - .append(append.unwrap_or(true)) - .open(path) - .map_err(|err| { - JsValue::from_str(format!("caml_pasta_fp_urs_write: {}", err).as_str()) - })?; - let file = BufWriter::new(file); - - srs.0.serialize(&mut rmp_serde::Serializer::new(file)) - .map_err(|e| JsValue::from_str(format!("caml_pasta_fp_urs_write: {}", e).as_str())) - } - - #[wasm_bindgen] - pub fn [<$name:snake _read>]( - offset: Option, - path: String, - ) -> Result]>, JsValue> { - let file = File::open(path).map_err(|err| { - JsValue::from_str(format!("caml_pasta_fp_urs_read: {}", err).as_str()) - })?; - let mut reader = BufReader::new(file); - - if let Some(offset) = offset { - reader.seek(Start(offset as u64)).map_err(|err| { - JsValue::from_str(format!("caml_pasta_fp_urs_read: {}", err).as_str()) - })?; - } - - // TODO: shouldn't we just error instead of returning None? - let srs = match SRS::<$G>::deserialize(&mut rmp_serde::Deserializer::new(reader)) { - Ok(srs) => srs, - Err(_) => return Ok(None), - }; - - Ok(Some(Arc::new(srs).into())) - } - - #[wasm_bindgen] - pub fn [<$name:snake _lagrange_commitment>]( - srs: &[], - domain_size: i32, - i: i32, - ) -> Result<$WasmPolyComm, JsValue> { - let x_domain = EvaluationDomain::<$F>::new(domain_size as usize).ok_or_else(|| { - JsValue::from_str("caml_pasta_fp_urs_lagrange_commitment") - })?; - let basis = - crate::rayon::run_in_pool(|| { - srs.get_lagrange_basis(x_domain) - }); - - Ok(basis[i as usize].clone().into()) - } - - #[wasm_bindgen] - pub fn [<$name:snake _commit_evaluations>]( - srs: &[], - domain_size: i32, - evals: WasmFlatVector<$WasmF>, - ) -> Result<$WasmPolyComm, JsValue> { - let x_domain = EvaluationDomain::<$F>::new(domain_size as usize).ok_or_else(|| { - JsValue::from_str("caml_pasta_fp_urs_commit_evaluations") - })?; - - let evals = evals.into_iter().map(Into::into).collect(); - let p = Evaluations::<$F>::from_vec_and_domain(evals, x_domain).interpolate(); - - Ok(srs.commit_non_hiding(&p, 1).into()) - } - - #[wasm_bindgen] - pub fn [<$name:snake _b_poly_commitment>]( - srs: &[], - chals: WasmFlatVector<$WasmF>, - ) -> Result<$WasmPolyComm, JsValue> { - let result = crate::rayon::run_in_pool(|| { - let chals: Vec<$F> = chals.into_iter().map(Into::into).collect(); - let coeffs = b_poly_coefficients(&chals); - let p = DensePolynomial::<$F>::from_coefficients_vec(coeffs); - srs.commit_non_hiding(&p, 1) - }); - Ok(result.into()) - } - - #[wasm_bindgen] - pub fn [<$name:snake _batch_accumulator_check>]( - srs: &[], - comms: WasmVector<$WasmG>, - chals: WasmFlatVector<$WasmF>, - ) -> bool { - crate::rayon::run_in_pool(|| { - let comms: Vec<_> = comms.into_iter().map(Into::into).collect(); - let chals: Vec<_> = chals.into_iter().map(Into::into).collect(); - crate::urs_utils::batch_dlog_accumulator_check(&srs, &comms, &chals) - }) - } - - #[wasm_bindgen] - pub fn [<$name:snake _batch_accumulator_generate>]( - srs: &[], - comms: i32, - chals: WasmFlatVector<$WasmF>, - ) -> WasmVector<$WasmG> { - crate::urs_utils::batch_dlog_accumulator_generate::<$G>( - &srs, - comms as usize, - &chals.into_iter().map(From::from).collect(), - ).into_iter().map(Into::into).collect() - } - - #[wasm_bindgen] - pub fn [<$name:snake _h>](srs: &[]) -> $WasmG { - srs.h.into() - } - } - } -} - -// -// Fp -// - -pub mod fp { - use super::*; - use crate::arkworks::{WasmGVesta as WasmG, WasmPastaFp}; - use crate::poly_comm::vesta::WasmFpPolyComm as WasmPolyComm; - use mina_curves::pasta::{Fp, Vesta as G}; - - impl_srs!(caml_fp_srs, WasmPastaFp, WasmG, Fp, G, WasmPolyComm, Fp); - - #[wasm_bindgen] - pub fn caml_fp_srs_create_parallel(depth: i32) -> WasmFpSrs { - crate::rayon::run_in_pool(|| Arc::new(SRS::::create_parallel(depth as usize)).into()) - } - - // return the cloned srs in a form that we can store on the js side - #[wasm_bindgen] - pub fn caml_fp_srs_get(srs: &WasmFpSrs) -> WasmVector { - // return a vector which consists of h, then all the gs - let mut h_and_gs: Vec = vec![srs.0.h.into()]; - h_and_gs.extend(srs.0.g.iter().map(|x: &G| WasmG::from(*x))); - h_and_gs.into() - } - - // set the srs from a vector of h and gs - #[wasm_bindgen] - pub fn caml_fp_srs_set(h_and_gs: WasmVector) -> WasmFpSrs { - // return a vector which consists of h, then all the gs - let mut h_and_gs: Vec = h_and_gs.into_iter().map(|x| x.into()).collect(); - let h = h_and_gs.remove(0); - let g = h_and_gs; - let srs = SRS:: { - h, - g, - lagrange_bases: HashMapCache::new(), - }; - Arc::new(srs).into() - } - - // maybe get lagrange commitment - #[wasm_bindgen] - pub fn caml_fp_srs_maybe_lagrange_commitment( - srs: &WasmFpSrs, - domain_size: i32, - i: i32, - ) -> Option { - if !(srs.0.lagrange_bases.contains_key(&(domain_size as usize))) { - return None; - } - let basis = srs.get_lagrange_basis_from_domain_size(domain_size as usize); - Some(basis[i as usize].clone().into()) - } - - // set entire lagrange basis from input - #[wasm_bindgen] - pub fn caml_fp_srs_set_lagrange_basis( - srs: &WasmFpSrs, - domain_size: i32, - input_bases: WasmVector, - ) { - srs.lagrange_bases - .get_or_generate(domain_size as usize, || { - input_bases.into_iter().map(Into::into).collect() - }); - } - - // compute & add lagrange basis internally, return the entire basis - #[wasm_bindgen] - pub fn caml_fp_srs_get_lagrange_basis( - srs: &WasmFpSrs, - domain_size: i32, - ) -> WasmVector { - // compute lagrange basis - let basis = crate::rayon::run_in_pool(|| { - let domain = - EvaluationDomain::::new(domain_size as usize).expect("invalid domain size"); - srs.get_lagrange_basis(domain) - }); - basis.iter().map(Into::into).collect() - } -} - -pub mod fq { - use super::*; - use crate::arkworks::{WasmGPallas as WasmG, WasmPastaFq}; - use crate::poly_comm::pallas::WasmFqPolyComm as WasmPolyComm; - use mina_curves::pasta::{Fq, Pallas as G}; - - impl_srs!(caml_fq_srs, WasmPastaFq, WasmG, Fq, G, WasmPolyComm, Fq); - - #[wasm_bindgen] - pub fn caml_fq_srs_create_parallel(depth: i32) -> WasmFqSrs { - crate::rayon::run_in_pool(|| Arc::new(SRS::::create_parallel(depth as usize)).into()) - } - - // return the cloned srs in a form that we can store on the js side - #[wasm_bindgen] - pub fn caml_fq_srs_get(srs: &WasmFqSrs) -> WasmVector { - // return a vector which consists of h, then all the gs - let mut h_and_gs: Vec = vec![srs.0.h.into()]; - h_and_gs.extend(srs.0.g.iter().map(|x: &G| WasmG::from(*x))); - h_and_gs.into() - } - - // set the srs from a vector of h and gs - #[wasm_bindgen] - pub fn caml_fq_srs_set(h_and_gs: WasmVector) -> WasmFqSrs { - // return a vector which consists of h, then all the gs - let mut h_and_gs: Vec = h_and_gs.into_iter().map(|x| x.into()).collect(); - let h = h_and_gs.remove(0); - let g = h_and_gs; - let srs = SRS:: { - h, - g, - lagrange_bases: HashMapCache::new(), - }; - Arc::new(srs).into() - } - - // maybe get lagrange commitment - #[wasm_bindgen] - pub fn caml_fq_srs_maybe_lagrange_commitment( - srs: &WasmFqSrs, - domain_size: i32, - i: i32, - ) -> Option { - if !(srs.0.lagrange_bases.contains_key(&(domain_size as usize))) { - return None; - } - let basis = srs.get_lagrange_basis_from_domain_size(domain_size as usize); - Some(basis[i as usize].clone().into()) - } - - // set entire lagrange basis from input - #[wasm_bindgen] - pub fn caml_fq_srs_set_lagrange_basis( - srs: &WasmFqSrs, - domain_size: i32, - input_bases: WasmVector, - ) { - srs.lagrange_bases - .get_or_generate(domain_size as usize, || { - input_bases.into_iter().map(Into::into).collect() - }); - } - - // compute & add lagrange basis internally, return the entire basis - #[wasm_bindgen] - pub fn caml_fq_srs_get_lagrange_basis( - srs: &WasmFqSrs, - domain_size: i32, - ) -> WasmVector { - // compute lagrange basis - let basis = crate::rayon::run_in_pool(|| { - let domain = - EvaluationDomain::::new(domain_size as usize).expect("invalid domain size"); - srs.get_lagrange_basis(domain) - }); - basis.iter().map(Into::into).collect() - } -} diff --git a/src/lib/crypto/kimchi_bindings/wasm/src/urs_utils.rs b/src/lib/crypto/kimchi_bindings/wasm/src/urs_utils.rs deleted file mode 100644 index 0ff8387daca..00000000000 --- a/src/lib/crypto/kimchi_bindings/wasm/src/urs_utils.rs +++ /dev/null @@ -1,101 +0,0 @@ -use ark_ec::{CurveGroup, VariableBaseMSM}; -use ark_ff::{batch_inversion, One, PrimeField, UniformRand, Zero}; -use poly_commitment::{ - commitment::{b_poly_coefficients, CommitmentCurve}, - ipa::SRS, -}; -use rayon::prelude::*; - -// TODO: Not compatible with variable rounds -pub fn batch_dlog_accumulator_check( - urs: &SRS, - comms: &[G], - chals: &[G::ScalarField], -) -> bool { - let k = comms.len(); - - if k == 0 { - assert_eq!(chals.len(), 0); - return true; - } - - let rounds = chals.len() / k; - assert_eq!(chals.len() % rounds, 0); - - let rs = { - let r = G::ScalarField::rand(&mut rand::rngs::OsRng); - let mut rs = vec![G::ScalarField::one(); k]; - for i in 1..k { - rs[i] = r * rs[i - 1]; - } - rs - }; - - let mut points = urs.g.clone(); - let n = points.len(); - points.extend(comms); - - let mut scalars = vec![G::ScalarField::zero(); n]; - scalars.extend(&rs[..]); - - let chal_invs = { - let mut cs = chals.to_vec(); - batch_inversion(&mut cs); - cs - }; - - let termss: Vec<_> = chals - .par_iter() - .zip(chal_invs) - .chunks(rounds) - .zip(rs) - .map(|(chunk, r)| { - let chals: Vec<_> = chunk.iter().map(|(c, _)| **c).collect(); - let mut s = b_poly_coefficients(&chals); - s.iter_mut().for_each(|c| *c *= &r); - s - }) - .collect(); - - for terms in termss { - assert_eq!(terms.len(), n); - for i in 0..n { - scalars[i] -= &terms[i]; - } - } - - let scalars: Vec<_> = scalars.iter().map(|x| x.into_bigint()).collect(); - G::Group::msm_bigint(&points, &scalars) == G::Group::zero() -} - -pub fn batch_dlog_accumulator_generate( - urs: &SRS, - num_comms: usize, - chals: &Vec, -) -> Vec { - let k = num_comms; - - if k == 0 { - assert_eq!(chals.len(), 0); - return vec![]; - } - - let rounds = chals.len() / k; - assert_eq!(chals.len() % rounds, 0); - - let comms: Vec<_> = chals - .into_par_iter() - .chunks(rounds) - .map(|chals| { - let chals: Vec = chals.into_iter().copied().collect(); - let scalars: Vec<_> = b_poly_coefficients(&chals) - .into_iter() - .map(|x| x.into_bigint()) - .collect(); - let points: Vec<_> = urs.g.clone(); - G::Group::msm_bigint(&points, &scalars).into_affine() - }) - .collect(); - - comms -} diff --git a/src/lib/crypto/kimchi_bindings/wasm/src/wasm_flat_vector.rs b/src/lib/crypto/kimchi_bindings/wasm/src/wasm_flat_vector.rs deleted file mode 100644 index 82b9bc0a0e8..00000000000 --- a/src/lib/crypto/kimchi_bindings/wasm/src/wasm_flat_vector.rs +++ /dev/null @@ -1,150 +0,0 @@ -//! The flat vector is a vector of fixed-size elements that we want to expose directly to js-of-ocaml -//! (so that we can access a `Vec` cheaply, -//! by just passing a pointer to a continuous memory region instead of copying. -//! The wasmvector is a normal heap-allocated vector, -//! where we leave it on the rust heap and just keep a pointer around. -//! We use flat for fields, normal for gates etc. -//! -//! Accessing Rust vector values is not the same as accessing an array. -//! Each indexing (e.g. `some_vec[3]`) is costly as it is implemented as a function call. -//! Knowing that, plus the fact that field elements are implemented as `[u32; 8]`, we know that we incur the cost of following several pointers. -//! To decrease that cost, we flatten such arrays, going from something like -//! -//! ```ignore -//! [[a0, a1, ..., a7], [b0, b1, ..., b7], ...] -//! ``` -//! -//! to a flattened vector like: -//! -//! ```ignore -//! [a0, a1, ..., a7, b0, b1, ..., b7, ...] -//! ``` - -use wasm_bindgen::convert::{FromWasmAbi, IntoWasmAbi, OptionFromWasmAbi, OptionIntoWasmAbi}; - -use std::convert::From; -use std::ops::Deref; - -#[derive(Clone, Debug)] -pub struct WasmFlatVector(Vec); - -pub trait FlatVectorElem { - const FLATTENED_SIZE: usize; - fn flatten(self) -> Vec; - fn unflatten(flat: Vec) -> Self; -} - -impl Deref for WasmFlatVector { - type Target = Vec; - - fn deref(&self) -> &Self::Target { - &self.0 - } -} - -impl From> for WasmFlatVector { - fn from(x: Vec) -> Self { - WasmFlatVector(x) - } -} - -impl From> for Vec { - fn from(x: WasmFlatVector) -> Self { - x.0 - } -} - -impl<'a, T> From<&'a WasmFlatVector> for &'a Vec { - fn from(x: &'a WasmFlatVector) -> Self { - &x.0 - } -} - -impl std::iter::IntoIterator for WasmFlatVector { - type Item = as std::iter::IntoIterator>::Item; - type IntoIter = as std::iter::IntoIterator>::IntoIter; - fn into_iter(self) -> Self::IntoIter { - self.0.into_iter() - } -} - -impl<'a, T> std::iter::IntoIterator for &'a WasmFlatVector { - type Item = <&'a Vec as std::iter::IntoIterator>::Item; - type IntoIter = <&'a Vec as std::iter::IntoIterator>::IntoIter; - fn into_iter(self) -> Self::IntoIter { - self.0.iter() - } -} - -impl std::iter::FromIterator for WasmFlatVector { - fn from_iter(iter: I) -> WasmFlatVector - where - I: IntoIterator, - { - WasmFlatVector(std::iter::FromIterator::from_iter(iter)) - } -} - -impl std::default::Default for WasmFlatVector { - fn default() -> Self { - WasmFlatVector(std::default::Default::default()) - } -} - -impl std::iter::Extend for WasmFlatVector { - fn extend(&mut self, iter: I) - where - I: IntoIterator, - { - self.0.extend(iter) - } -} - -impl wasm_bindgen::describe::WasmDescribe for WasmFlatVector { - fn describe() { - as wasm_bindgen::describe::WasmDescribe>::describe() - } -} - -impl FromWasmAbi for WasmFlatVector { - type Abi = as FromWasmAbi>::Abi; - unsafe fn from_abi(js: Self::Abi) -> Self { - let data: Vec = FromWasmAbi::from_abi(js); - let mut res: Vec = Vec::with_capacity(data.len() / T::FLATTENED_SIZE); - - let mut buf = Vec::with_capacity(T::FLATTENED_SIZE); - for x in data.into_iter() { - assert!(buf.len() < T::FLATTENED_SIZE); - buf.push(x); - if buf.len() >= T::FLATTENED_SIZE { - res.push(T::unflatten(buf)); - buf = Vec::with_capacity(T::FLATTENED_SIZE); - } - } - assert_eq!(buf.len(), 0); - WasmFlatVector(res) - } -} - -impl OptionFromWasmAbi for WasmFlatVector { - fn is_none(x: &Self::Abi) -> bool { - as OptionFromWasmAbi>::is_none(x) - } -} - -impl IntoWasmAbi for WasmFlatVector { - type Abi = as FromWasmAbi>::Abi; - fn into_abi(self) -> Self::Abi { - let mut data: Vec = Vec::with_capacity(self.0.len() * T::FLATTENED_SIZE); - for x in self.0.into_iter() { - data.extend(x.flatten().into_iter()); - } - IntoWasmAbi::into_abi(data) - } -} - -impl OptionIntoWasmAbi for WasmFlatVector { - fn none() -> Self::Abi { - as OptionIntoWasmAbi>::none() - } -} diff --git a/src/lib/crypto/kimchi_bindings/wasm/src/wasm_ocaml_serde/de.rs b/src/lib/crypto/kimchi_bindings/wasm/src/wasm_ocaml_serde/de.rs deleted file mode 100644 index d990e856a13..00000000000 --- a/src/lib/crypto/kimchi_bindings/wasm/src/wasm_ocaml_serde/de.rs +++ /dev/null @@ -1,304 +0,0 @@ -use js_sys::{Array, ArrayBuffer, Number, Uint8Array}; -use serde::de::value::SeqDeserializer; -use serde::de::{self, Error as _, IntoDeserializer}; -use wasm_bindgen::{JsCast, JsValue, UnwrapThrowExt}; - -use super::{Error, Result}; - -struct SeqAccess { - iter: js_sys::IntoIter, -} - -impl<'de> de::SeqAccess<'de> for SeqAccess { - type Error = Error; - - fn next_element_seed>( - &mut self, - seed: T, - ) -> Result> { - Ok(match self.iter.next().transpose()? { - Some(value) => Some(seed.deserialize(Deserializer::from(value))?), - None => None, - }) - } -} - -struct ObjectAccess { - data: Array, - fields: std::slice::Iter<'static, &'static str>, - idx: u32, - next_value: Option, -} - -impl ObjectAccess { - fn new(data: Array, fields: &'static [&'static str]) -> Self { - // We start the index at 1, due to some js-of-ocaml expecting the first element to be 0 - // this is due to OCaml implementation details. - Self { - data, - idx: 1, - fields: fields.iter(), - next_value: None, - } - } -} - -fn str_deserializer(s: &str) -> de::value::StrDeserializer { - de::IntoDeserializer::into_deserializer(s) -} - -impl<'de> de::MapAccess<'de> for ObjectAccess { - type Error = Error; - - fn next_key_seed>(&mut self, seed: K) -> Result> { - debug_assert!(self.next_value.is_none()); - - match self.fields.next() { - None => Ok(None), - Some(field) => { - self.next_value = Some(Deserializer::from(self.data.get(self.idx))); - self.idx += 1; - Ok(Some(seed.deserialize(str_deserializer(field))?)) - } - } - } - - fn next_value_seed>(&mut self, seed: V) -> Result { - seed.deserialize(self.next_value.take().unwrap_throw()) - } -} - -pub struct Deserializer(JsValue); - -// Can't use `serde_wasm_bindgen::de::Deserializer`, its `value` field is private. -impl From for Deserializer { - fn from(value: JsValue) -> Self { - Self(value) - } -} - -// Ideally this would be implemented for `JsValue` instead, but we can't because -// of the orphan rule. -impl<'de> IntoDeserializer<'de, Error> for Deserializer { - type Deserializer = Self; - - fn into_deserializer(self) -> Self::Deserializer { - self - } -} - -impl Deserializer { - fn as_bytes(&self) -> Option> { - if let Some(v) = self.0.dyn_ref::() { - Some(v.to_vec()) - } else { - /* We can hit this case when the values have come from the non-serde conversions. */ - self.0 - .dyn_ref::() - .map(|v| Uint8Array::new(v).to_vec()) - } - } -} - -impl<'de> de::Deserializer<'de> for Deserializer { - type Error = Error; - - fn deserialize_any>(self, _: V) -> Result { - Err(Error::custom( - "Inferring the serialized type is not implemented", - )) - } - - fn deserialize_unit>(self, visitor: V) -> Result { - visitor.visit_unit() - } - - fn deserialize_unit_struct>( - self, - _: &'static str, - _: V, - ) -> Result { - Err(Error::custom( - "Deserializing unit structs is not implemented", - )) - } - - fn deserialize_bool>(self, visitor: V) -> Result { - let x = self.0.unchecked_into::().as_f64().unwrap() as u32; - visitor.visit_bool(x != 0) - } - - fn deserialize_f32>(self, visitor: V) -> Result { - visitor.visit_f32(self.0.unchecked_into::().as_f64().unwrap() as f32) - } - - fn deserialize_f64>(self, visitor: V) -> Result { - visitor.visit_f64(self.0.unchecked_into::().as_f64().unwrap()) - } - - fn deserialize_identifier>(self, _: V) -> Result { - Err(Error::custom("Deserializing strings is not implemented")) - } - - fn deserialize_str>(self, _: V) -> Result { - Err(Error::custom("Deserializing strings is not implemented")) - } - - fn deserialize_string>(self, _: V) -> Result { - Err(Error::custom("Deserializing strings is not implemented")) - } - - fn deserialize_i8>(self, visitor: V) -> Result { - visitor.visit_i8(self.0.unchecked_into::().as_f64().unwrap() as i8) - } - - fn deserialize_i16>(self, visitor: V) -> Result { - visitor.visit_i16(self.0.unchecked_into::().as_f64().unwrap() as i16) - } - - fn deserialize_i32>(self, visitor: V) -> Result { - visitor.visit_i32(self.0.unchecked_into::().as_f64().unwrap() as i32) - } - - fn deserialize_u8>(self, visitor: V) -> Result { - visitor.visit_u8(self.0.unchecked_into::().as_f64().unwrap() as u8) - } - - fn deserialize_u16>(self, visitor: V) -> Result { - visitor.visit_u16(self.0.unchecked_into::().as_f64().unwrap() as u16) - } - - fn deserialize_u32>(self, visitor: V) -> Result { - visitor.visit_u32(self.0.unchecked_into::().as_f64().unwrap() as u32) - } - - fn deserialize_i64>(self, _visitor: V) -> Result { - Err(Error::custom("Deserializing i64 is not implemented")) - } - - fn deserialize_u64>(self, _visitor: V) -> Result { - Err(Error::custom("Deserializing u64 is not implemented")) - } - - fn deserialize_i128>(self, _visitor: V) -> Result { - Err(Error::custom("Deserializing i128 is not implemented")) - } - - fn deserialize_u128>(self, _visitor: V) -> Result { - Err(Error::custom("Deserializing u128 is not implemented")) - } - - fn deserialize_char>(self, visitor: V) -> Result { - visitor.visit_char((self.0.unchecked_into::().as_f64().unwrap() as u8) as char) - } - - // Serde can deserialize `visit_unit` into `None`, but can't deserialize arbitrary value - // as `Some`, so we need to provide own simple implementation. - fn deserialize_option>(self, visitor: V) -> Result { - if let Ok(arr) = self.0.dyn_into::() { - visitor.visit_some(Into::::into(arr.get(1))) - } else { - visitor.visit_none() - } - } - - fn deserialize_newtype_struct>( - self, - _name: &'static str, - _visitor: V, - ) -> Result { - Err(Error::custom( - "Deserializing newtype structus is not implemented", - )) - } - - fn deserialize_seq>(self, visitor: V) -> Result { - let arr = self.0.unchecked_into::(); - visitor.visit_seq(SeqDeserializer::new( - arr.iter().skip(1).map(Deserializer::from), - )) - } - - fn deserialize_tuple>(self, _len: usize, visitor: V) -> Result { - self.deserialize_seq(visitor) - } - - fn deserialize_tuple_struct>( - self, - _name: &'static str, - _len: usize, - _visitor: V, - ) -> Result { - Err(Error::custom( - "Deserializing tuple structs is not implemented", - )) - } - - fn deserialize_map>(self, _visitor: V) -> Result { - Err(Error::custom("Deserializing maps is not implemented")) - } - - fn deserialize_struct>( - self, - _name: &'static str, - fields: &'static [&'static str], - visitor: V, - ) -> Result { - let arr = self.0.unchecked_into::(); - visitor.visit_map(ObjectAccess::new(arr, fields)) - } - - fn deserialize_enum>( - self, - _: &'static str, - _: &'static [&'static str], - _: V, - ) -> Result { - Err(Error::custom("Deserializing enums is not implemented")) - } - - fn deserialize_ignored_any>(self, visitor: V) -> Result { - visitor.visit_unit() - } - - fn deserialize_bytes>(self, visitor: V) -> Result { - self.deserialize_byte_buf(visitor) - } - - fn deserialize_byte_buf>(self, visitor: V) -> Result { - if let Some(bytes) = self.as_bytes() { - visitor.visit_byte_buf(bytes) - } else { - Err(Error::custom("Type error while deserializing bytes")) - } - } - - #[inline] - fn is_human_readable(&self) -> bool { - false - } -} - -impl<'de> de::VariantAccess<'de> for Deserializer { - type Error = Error; - - fn unit_variant(self) -> Result<()> { - Err(Error::custom("Deserializing variants is not implemented")) - } - - fn newtype_variant_seed>(self, _: T) -> Result { - Err(Error::custom("Deserializing variants is not implemented")) - } - - fn tuple_variant>(self, _: usize, _: V) -> Result { - Err(Error::custom("Deserializing variants is not implemented")) - } - - fn struct_variant>( - self, - _: &'static [&'static str], - _: V, - ) -> Result { - Err(Error::custom("Deserializing variants is not implemented")) - } -} diff --git a/src/lib/crypto/kimchi_bindings/wasm/src/wasm_ocaml_serde/mod.rs b/src/lib/crypto/kimchi_bindings/wasm/src/wasm_ocaml_serde/mod.rs deleted file mode 100644 index 320dfd7b319..00000000000 --- a/src/lib/crypto/kimchi_bindings/wasm/src/wasm_ocaml_serde/mod.rs +++ /dev/null @@ -1,33 +0,0 @@ -//! This module constructs a serde serializer (and deserializer) to convert Rust structures to (and from) Js types expected by js-of-ocaml. -//! js-of-ocaml expects arrays of values instead of objects, so a Rust structure like: -//! -//! ```ignore -//! { a: F, b: Vec, c: SomeType } -//! ``` -//! -//! must be converted to an array that looks like this: -//! -//! ```ignore -//! // notice the leading 0, which is an artifact of OCaml's memory layout and how js-of-ocaml is implemented. -//! [0, a, b, c] -//! ``` -//! See the following example on how to use it: -//! -//! ``` -//! #[derive(serde::Serialize, serde::Deserialize)] -//! struct Thing { a: usize, b: u32 } -//! -//! let serializer = crate::wasm_ocaml_serde::ser::Serializer::new(); -//! let thing = Thing { a: 5, b: 6 }; -//! let js_value = serde::Serialize::serialize(thing, &mut serializer).unwrap(); -//! assert_eq!(format!("{}", js_value), "[0, 5, 6]"); -//! ``` - -use wasm_bindgen::prelude::*; - -pub mod de; -pub mod ser; - -pub use serde_wasm_bindgen::Error; - -pub type Result = core::result::Result; diff --git a/src/lib/crypto/kimchi_bindings/wasm/src/wasm_ocaml_serde/ser.rs b/src/lib/crypto/kimchi_bindings/wasm/src/wasm_ocaml_serde/ser.rs deleted file mode 100644 index ab4a4f9e95e..00000000000 --- a/src/lib/crypto/kimchi_bindings/wasm/src/wasm_ocaml_serde/ser.rs +++ /dev/null @@ -1,319 +0,0 @@ -use js_sys::{Array, Uint8Array}; -use serde::ser::{self, Error as _, Serialize}; -use wasm_bindgen::prelude::*; - -use super::{Error, Result}; - -pub struct ErrorSerializer; - -impl ser::SerializeTupleVariant for ErrorSerializer { - type Ok = JsValue; - type Error = Error; - - fn serialize_field(&mut self, _: &T) -> Result<()> { - Err(Error::custom("Serializing variants is not implemented")) - } - - fn end(self) -> Result { - Err(Error::custom("Serializing variants is not implemented")) - } -} - -impl ser::SerializeStructVariant for ErrorSerializer { - type Ok = JsValue; - type Error = Error; - - fn serialize_field(&mut self, _: &'static str, _: &T) -> Result<()> { - Err(Error::custom("Serializing variants is not implemented")) - } - - fn end(self) -> Result { - Err(Error::custom("Serializing variants is not implemented")) - } -} - -pub struct ArraySerializer<'s> { - serializer: &'s Serializer, - res: Array, - idx: u32, -} - -impl<'s> ArraySerializer<'s> { - pub fn new(serializer: &'s Serializer) -> Self { - let res = Array::new(); - res.set(0, JsValue::from(0u32)); - Self { - serializer, - res, - idx: 1, - } - } -} - -impl ser::SerializeSeq for ArraySerializer<'_> { - type Ok = JsValue; - type Error = Error; - - fn serialize_element(&mut self, value: &T) -> Result<()> { - self.res.set(self.idx, value.serialize(self.serializer)?); - self.idx += 1; - Ok(()) - } - - fn end(self) -> Result { - Ok(self.res.into()) - } -} - -impl ser::SerializeTuple for ArraySerializer<'_> { - type Ok = JsValue; - type Error = Error; - - fn serialize_element(&mut self, value: &T) -> Result<()> { - ser::SerializeSeq::serialize_element(self, value) - } - - fn end(self) -> Result { - Ok(self.res.into()) - } -} - -impl ser::SerializeTupleStruct for ArraySerializer<'_> { - type Ok = JsValue; - type Error = Error; - - fn serialize_field(&mut self, value: &T) -> Result<()> { - ser::SerializeTuple::serialize_element(self, value) - } - - fn end(self) -> Result { - Ok(self.res.into()) - } -} - -impl ser::SerializeMap for ErrorSerializer { - type Ok = JsValue; - type Error = Error; - - fn serialize_key(&mut self, _: &T) -> Result<()> { - Err(Error::custom("Serializing maps is not implemented")) - } - - fn serialize_value(&mut self, _: &T) -> Result<()> { - Err(Error::custom("Serializing maps is not implemented")) - } - - fn end(self) -> Result { - Err(Error::custom("Serializing maps is not implemented")) - } -} - -impl ser::SerializeStruct for ArraySerializer<'_> { - type Ok = JsValue; - type Error = Error; - - fn serialize_field(&mut self, _: &'static str, value: &T) -> Result<()> { - ser::SerializeSeq::serialize_element(self, value) - } - - fn end(self) -> Result { - Ok(self.res.into()) - } -} - -#[derive(Default)] -pub struct Serializer(serde_wasm_bindgen::Serializer); - -impl Serializer { - pub fn new() -> Self { - Self(serde_wasm_bindgen::Serializer::new()) - } -} - -impl<'s> ser::Serializer for &'s Serializer { - type Ok = JsValue; - type Error = Error; - - type SerializeSeq = ArraySerializer<'s>; - type SerializeTuple = ArraySerializer<'s>; - type SerializeTupleStruct = ArraySerializer<'s>; - type SerializeTupleVariant = ErrorSerializer; - type SerializeMap = ErrorSerializer; - type SerializeStruct = ArraySerializer<'s>; - type SerializeStructVariant = ErrorSerializer; - - #[inline] - fn is_human_readable(&self) -> bool { - false - } - - fn serialize_bool(self, v: bool) -> Result { - if v { - self.0.serialize_u32(1) - } else { - self.0.serialize_u32(0) - } - } - - fn serialize_i8(self, v: i8) -> Result { - self.0.serialize_i8(v) - } - - fn serialize_i16(self, v: i16) -> Result { - self.0.serialize_i16(v) - } - - fn serialize_i32(self, v: i32) -> Result { - self.0.serialize_i32(v) - } - - fn serialize_u8(self, v: u8) -> Result { - self.0.serialize_u8(v) - } - - fn serialize_u16(self, v: u16) -> Result { - self.0.serialize_u16(v) - } - - fn serialize_u32(self, v: u32) -> Result { - self.0.serialize_u32(v) - } - - fn serialize_f32(self, v: f32) -> Result { - self.0.serialize_f32(v) - } - - fn serialize_f64(self, v: f64) -> Result { - self.0.serialize_f64(v) - } - - fn serialize_str(self, _: &str) -> Result { - /* The bindings call caml_string_of_jsstring; not clear what to do here without digging in - further. */ - Err(Error::custom("Serializing strings is not implemented")) - } - - fn serialize_i64(self, _: i64) -> Result { - /* Custom type in OCaml */ - Err(Error::custom("Serializing i64 is not implemented")) - } - - fn serialize_u64(self, _: u64) -> Result { - /* Custom type in OCaml */ - Err(Error::custom("Serializing u64 is not implemented")) - } - - fn serialize_i128(self, _: i128) -> Result { - /* Custom type in OCaml */ - Err(Error::custom("Serializing i128 is not implemented")) - } - - fn serialize_u128(self, _: u128) -> Result { - /* Custom type in OCaml */ - Err(Error::custom("Serializing u128 is not implemented")) - } - - fn serialize_char(self, v: char) -> Result { - self.0.serialize_u32(v as u32) - } - - fn serialize_bytes(self, v: &[u8]) -> Result { - Ok(JsValue::from(Uint8Array::new( - unsafe { Uint8Array::view(v) }.as_ref(), - ))) - } - - fn serialize_none(self) -> Result { - self.0.serialize_u32(0) - } - - fn serialize_some(self, value: &T) -> Result { - let res = Array::new(); - res.set(0, JsValue::from(0u32)); - res.set(1, value.serialize(self)?); - Ok(res.into()) - } - - fn serialize_unit(self) -> Result { - self.0.serialize_u32(0) - } - - fn serialize_unit_struct(self, _: &'static str) -> Result { - Err(Error::custom("Serializing unit structs is not implemented")) - } - - fn serialize_unit_variant(self, _: &'static str, _: u32, _: &'static str) -> Result { - Err(Error::custom( - "Serializing unit variants is not implemented", - )) - } - - fn serialize_newtype_struct(self, _: &'static str, _: &T) -> Result { - Err(Error::custom( - "Serializing newtype structs is not implemented", - )) - } - - fn serialize_newtype_variant( - self, - _: &'static str, - _: u32, - _: &'static str, - _: &T, - ) -> Result { - Err(Error::custom( - "Serializing newtype variants is not implemented", - )) - } - - // TODO: Figure out if there is a way to detect and serialise `Set` differently. - fn serialize_seq(self, _: Option) -> Result { - Ok(ArraySerializer::new(self)) - } - - fn serialize_tuple(self, _: usize) -> Result { - Ok(ArraySerializer::new(self)) - } - - fn serialize_tuple_struct( - self, - _: &'static str, - _: usize, - ) -> Result { - Err(Error::custom( - "Serializing tuple structs is not implemented", - )) - } - - fn serialize_tuple_variant( - self, - _: &'static str, - _: u32, - _: &'static str, - _: usize, - ) -> Result { - Err(Error::custom( - "Serializing tuple variants is not implemented", - )) - } - - fn serialize_map(self, _: Option) -> Result { - Err(Error::custom("Serializing maps is not implemented")) - } - - fn serialize_struct(self, _: &'static str, _: usize) -> Result { - Ok(ArraySerializer::new(self)) - } - - fn serialize_struct_variant( - self, - _: &'static str, - _: u32, - _: &'static str, - _: usize, - ) -> Result { - Err(Error::custom( - "Serializing struct variants is not implemented", - )) - } -} diff --git a/src/lib/crypto/kimchi_bindings/wasm/src/wasm_vector.rs b/src/lib/crypto/kimchi_bindings/wasm/src/wasm_vector.rs deleted file mode 100644 index 2ee0f6ef27a..00000000000 --- a/src/lib/crypto/kimchi_bindings/wasm/src/wasm_vector.rs +++ /dev/null @@ -1,166 +0,0 @@ -use crate::wasm_flat_vector::WasmFlatVector; -use paste::paste; -use std::convert::From; -use std::ops::Deref; -use wasm_bindgen::convert::{FromWasmAbi, IntoWasmAbi, OptionFromWasmAbi, OptionIntoWasmAbi}; -use wasm_bindgen::prelude::*; - -#[derive(Clone, Debug)] -pub struct WasmVector(Vec); - -impl Deref for WasmVector { - type Target = Vec; - - fn deref(&self) -> &Self::Target { - &self.0 - } -} - -impl From> for WasmVector { - fn from(x: Vec) -> Self { - WasmVector(x) - } -} - -impl From> for Vec { - fn from(x: WasmVector) -> Self { - x.0 - } -} - -impl<'a, T> From<&'a WasmVector> for &'a Vec { - fn from(x: &'a WasmVector) -> Self { - &x.0 - } -} - -impl std::iter::IntoIterator for WasmVector { - type Item = as std::iter::IntoIterator>::Item; - type IntoIter = as std::iter::IntoIterator>::IntoIter; - fn into_iter(self) -> Self::IntoIter { - self.0.into_iter() - } -} - -impl<'a, T> std::iter::IntoIterator for &'a WasmVector { - type Item = <&'a Vec as std::iter::IntoIterator>::Item; - type IntoIter = <&'a Vec as std::iter::IntoIterator>::IntoIter; - fn into_iter(self) -> Self::IntoIter { - self.0.iter() - } -} - -impl std::iter::FromIterator for WasmVector { - fn from_iter(iter: I) -> WasmVector - where - I: IntoIterator, - { - WasmVector(std::iter::FromIterator::from_iter(iter)) - } -} - -impl std::default::Default for WasmVector { - fn default() -> Self { - WasmVector(std::default::Default::default()) - } -} - -impl std::iter::Extend for WasmVector { - fn extend(&mut self, iter: I) - where - I: IntoIterator, - { - self.0.extend(iter) - } -} - -impl wasm_bindgen::describe::WasmDescribe for WasmVector { - fn describe() { - as wasm_bindgen::describe::WasmDescribe>::describe() - } -} - -impl> FromWasmAbi for WasmVector { - type Abi = as FromWasmAbi>::Abi; - unsafe fn from_abi(js: Self::Abi) -> Self { - let pointers: Vec = FromWasmAbi::from_abi(js); - WasmVector( - pointers - .into_iter() - .map(|x| FromWasmAbi::from_abi(x)) - .collect(), - ) - } -} - -impl> OptionFromWasmAbi for WasmVector { - fn is_none(x: &Self::Abi) -> bool { - as OptionFromWasmAbi>::is_none(x) - } -} - -impl> IntoWasmAbi for WasmVector { - type Abi = as FromWasmAbi>::Abi; - fn into_abi(self) -> Self::Abi { - let pointers: Vec = self - .0 - .into_iter() - .map(|x| IntoWasmAbi::into_abi(x)) - .collect(); - IntoWasmAbi::into_abi(pointers) - } -} - -impl> OptionIntoWasmAbi for WasmVector { - fn none() -> Self::Abi { - as OptionIntoWasmAbi>::none() - } -} - -macro_rules! impl_vec_vec_fp { - ( $F:ty, $WasmF:ty ) => { - paste! { - #[wasm_bindgen] - pub struct [](#[wasm_bindgen(skip)] pub Vec>); - - #[wasm_bindgen] - impl [] { - #[wasm_bindgen(constructor)] - pub fn create(n: i32) -> Self { - [](Vec::with_capacity(n as usize)) - } - - #[wasm_bindgen] - pub fn push(&mut self, x: WasmFlatVector<$WasmF>) { - self.0.push(x.into_iter().map(Into::into).collect()) - } - - #[wasm_bindgen] - pub fn get(&self, i: i32) -> WasmFlatVector<$WasmF> { - self.0[i as usize].clone().into_iter().map(Into::into).collect() - } - - #[wasm_bindgen] - pub fn set(&mut self, i: i32, x: WasmFlatVector<$WasmF>) { - self.0[i as usize] = x.into_iter().map(Into::into).collect() - } - } - } - }; -} - -pub mod fp { - use super::*; - use crate::arkworks::WasmPastaFp; - use mina_curves::pasta::Fp; - - impl_vec_vec_fp!(Fp, WasmPastaFp); -} - -pub mod fq { - use super::*; - use crate::arkworks::WasmPastaFq; - use mina_curves::pasta::Fq; - - impl_vec_vec_fp!(Fq, WasmPastaFq); -} diff --git a/src/lib/crypto/proof-systems b/src/lib/crypto/proof-systems index c54f985d5fe..55634927012 160000 --- a/src/lib/crypto/proof-systems +++ b/src/lib/crypto/proof-systems @@ -1 +1 @@ -Subproject commit c54f985d5fe28dc5f34a275884bee486e0861521 +Subproject commit 5563492701291a4b811860b342430a46a70a3710