From f1b97a652093e295d6582dfa94d658da52a0a9c9 Mon Sep 17 00:00:00 2001 From: dark64 Date: Thu, 25 Jun 2020 13:37:11 +0200 Subject: [PATCH 01/54] add stdlib-path argument to cli, remove ZOKRATES_HOME env --- .circleci/config.yml | 10 +-- Cargo.lock | 123 ++++++++++++++++++++++-------- scripts/one_liner.sh | 1 - zokrates_cli/Cargo.toml | 1 + zokrates_cli/src/bin.rs | 27 +++++-- zokrates_cli/tests/integration.rs | 4 + zokrates_fs_resolver/src/lib.rs | 70 ++++++----------- zokrates_test/src/lib.rs | 3 +- 8 files changed, 150 insertions(+), 89 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 4953923eb..e484a792b 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -20,7 +20,7 @@ jobs: command: ./scripts/install_libsnark_prerequisites.sh - run: name: Build - command: ZOKRATES_HOME=$(pwd)/zokrates_stdlib/stdlib/ WITH_LIBSNARK=1 RUSTFLAGS="-D warnings" ./build.sh + command: WITH_LIBSNARK=1 RUSTFLAGS="-D warnings" ./build.sh - save_cache: paths: - /usr/local/cargo/registry @@ -50,10 +50,10 @@ jobs: command: ./scripts/install_libsnark_prerequisites.sh - run: name: Build - command: ZOKRATES_HOME=$(pwd)/zokrates_stdlib/stdlib/ WITH_LIBSNARK=1 RUSTFLAGS="-D warnings" ./build.sh + command: WITH_LIBSNARK=1 RUSTFLAGS="-D warnings" ./build.sh - run: name: Run tests - command: ZOKRATES_HOME=$(pwd)/zokrates_stdlib/stdlib/ WITH_LIBSNARK=1 RUSTFLAGS="-D warnings" ./test.sh + command: WITH_LIBSNARK=1 RUSTFLAGS="-D warnings" ./test.sh # - run: # name: Generate code coverage report # command: ./scripts/cov.sh @@ -84,7 +84,7 @@ jobs: command: ./scripts/install_wasm_testing.sh - run: name: Test on firefox - command: ZOKRATES_HOME=$(pwd)/zokrates_stdlib/stdlib/ cd zokrates_core && wasm-pack test --firefox --headless -- --features wasm + command: cd zokrates_core && wasm-pack test --firefox --headless -- --features wasm integration_test: docker: - image: rustlang/rust:nightly-slim @@ -109,7 +109,7 @@ jobs: command: ./scripts/install_solcjs_deb.sh - run: name: Run integration tests - command: ZOKRATES_HOME=$(pwd)/zokrates_stdlib/stdlib/ WITH_LIBSNARK=1 RUSTFLAGS="-D warnings" ./full_test.sh + command: WITH_LIBSNARK=1 RUSTFLAGS="-D warnings" ./full_test.sh deploy: docker: - image: circleci/python:latest-node diff --git a/Cargo.lock b/Cargo.lock index 4a933dd74..9a636c71e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1,14 +1,5 @@ # This file is automatically @generated by Cargo. # It is not intended for manual editing. -[[package]] -name = "addr2line" -version = "0.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a49806b9dadc843c61e7c97e72490ad7f7220ae249012fbda9ad0609457c0543" -dependencies = [ - "gimli", -] - [[package]] name = "aho-corasick" version = "0.6.10" @@ -27,6 +18,12 @@ dependencies = [ "winapi", ] +[[package]] +name = "arrayref" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4c527152e37cf757a3f78aae5a06fbeefdb07ccc535c980a3208ee3060dd544" + [[package]] name = "arrayvec" version = "0.4.12" @@ -36,6 +33,12 @@ dependencies = [ "nodrop", ] +[[package]] +name = "arrayvec" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cff77d8686867eceff3105329d4698d96c2391c176d5d03adc90c7389162b5b8" + [[package]] name = "assert_cli" version = "0.5.4" @@ -69,17 +72,32 @@ checksum = "f8aac770f1885fd7e387acedd76065302551364496e46b3dd00860b2f8359b9d" [[package]] name = "backtrace" -version = "0.3.48" +version = "0.3.41" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0df2f85c8a2abbe3b7d7e748052fdd9b76a0458fdeb16ad4223f5eca78c7c130" +checksum = "a4ed64ae6d9ebfd9893193c4b2532b1292ec97bd8271c9d7d0fa90cd78a34cba" dependencies = [ - "addr2line", + "backtrace-sys", "cfg-if", "libc", - "object", "rustc-demangle", ] +[[package]] +name = "backtrace-sys" +version = "0.1.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18fbebbe1c9d1f383a9cc7e8ccdb471b91c8d024ee9c2ca5b5346121fe8b4399" +dependencies = [ + "cc", + "libc", +] + +[[package]] +name = "base64" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b41b7ea54a0c9d92199de89e20e58d49f02f8e699814ef3fdf266f6f748d15c7" + [[package]] name = "bellman_ce" version = "0.3.4" @@ -126,11 +144,22 @@ version = "0.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fdc60350286c7c3db13b98e91dbe5c8b6830a6821bc20af5b0c310ce94d74915" dependencies = [ - "arrayvec", + "arrayvec 0.4.12", "byteorder", "constant_time_eq", ] +[[package]] +name = "blake2b_simd" +version = "0.5.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8fb2d74254a3a0b5cac33ac9f8ed0e44aa50378d9dbb2e5d83bd21ed1dc2c8a" +dependencies = [ + "arrayref", + "arrayvec 0.5.1", + "constant_time_eq", +] + [[package]] name = "block-buffer" version = "0.7.3" @@ -212,9 +241,9 @@ dependencies = [ [[package]] name = "cfg-if" -version = "0.1.10" +version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" +checksum = "b486ce3ccf7ffd79fdeb678eac06a9e6c09fc88d33836340becb8fffe87c5e33" [[package]] name = "clap" @@ -319,12 +348,13 @@ dependencies = [ [[package]] name = "crossbeam-queue" -version = "0.2.2" +version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab6bffe714b6bb07e42f201352c34f51fefd355ace793f9e638ebd52d23f98d2" +checksum = "774ba60a54c213d409d5353bda12d49cd68d14e45036a285234c8d6f91f92570" dependencies = [ "cfg-if", "crossbeam-utils", + "maybe-uninit", ] [[package]] @@ -381,6 +411,27 @@ dependencies = [ "generic-array", ] +[[package]] +name = "dirs" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2fddc3610d8f9552384e06ebc87f714e1d0b2b64a99194d2faf36d7ae5f48549" +dependencies = [ + "cfg-if", + "dirs-sys", +] + +[[package]] +name = "dirs-sys" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e93d7f5705de3e49895a2b5e0b8855a1c27f080192ae9c32a6432d50741a57a" +dependencies = [ + "libc", + "redox_users", + "winapi", +] + [[package]] name = "either" version = "1.5.3" @@ -600,12 +651,6 @@ dependencies = [ "wasi", ] -[[package]] -name = "gimli" -version = "0.21.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bcc8e0c9bce37868955864dbecd2b1ab2bdf967e6f28066d65aaac620444b65c" - [[package]] name = "git2" version = "0.13.6" @@ -874,12 +919,6 @@ dependencies = [ "libc", ] -[[package]] -name = "object" -version = "0.19.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9cbca9424c482ee628fa549d9c812e2cd22f1180b9222c9200fdfa6eb31aecb2" - [[package]] name = "once_cell" version = "1.4.0" @@ -1151,6 +1190,17 @@ version = "0.1.56" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2439c63f3f6139d1b57529d16bc3b8bb855230c8efcc5d3a896c8bea7c3b1e84" +[[package]] +name = "redox_users" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09b23093265f8d200fa7b4c2c76297f47e681c655f6f1285a8780d6a022f7431" +dependencies = [ + "getrandom", + "redox_syscall", + "rust-argon2", +] + [[package]] name = "reduce" version = "0.1.2" @@ -1197,6 +1247,18 @@ dependencies = [ "winapi", ] +[[package]] +name = "rust-argon2" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bc8af4bda8e1ff4932523b94d3dd20ee30a87232323eda55903ffd71d2fb017" +dependencies = [ + "base64", + "blake2b_simd", + "constant_time_eq", + "crossbeam-utils", +] + [[package]] name = "rustc-demangle" version = "0.1.16" @@ -1719,6 +1781,7 @@ dependencies = [ "assert_cli", "bincode", "clap", + "dirs", "fs_extra", "glob 0.2.11", "regex", diff --git a/scripts/one_liner.sh b/scripts/one_liner.sh index 7a97575d5..12a029f3f 100755 --- a/scripts/one_liner.sh +++ b/scripts/one_liner.sh @@ -330,7 +330,6 @@ main() { ZoKrates was installed successfully! If this is the first time you're installing ZoKrates run the following: export PATH=$PATH:$HOME/.zokrates/bin -export ZOKRATES_HOME=$HOME/.zokrates/stdlib EOF } diff --git a/zokrates_cli/Cargo.toml b/zokrates_cli/Cargo.toml index f69841792..8fc34242f 100644 --- a/zokrates_cli/Cargo.toml +++ b/zokrates_cli/Cargo.toml @@ -18,6 +18,7 @@ zokrates_abi = { version = "0.1", path = "../zokrates_abi" } zokrates_core = { version = "0.4", path = "../zokrates_core" } zokrates_fs_resolver = { version = "0.5", path = "../zokrates_fs_resolver"} serde_json = "1.0" +dirs = "3.0" [dev-dependencies] glob = "0.2.11" diff --git a/zokrates_cli/src/bin.rs b/zokrates_cli/src/bin.rs index 0976d8906..e193802ac 100644 --- a/zokrates_cli/src/bin.rs +++ b/zokrates_cli/src/bin.rs @@ -4,8 +4,9 @@ // @author Dennis Kuhnert // @date 2017 -mod constants; +extern crate dirs; +mod constants; use constants::*; use clap::{App, AppSettings, Arg, ArgMatches, SubCommand}; @@ -281,7 +282,7 @@ fn cli_compile(sub_matches: &ArgMatches) -> Result<(), String> { ) }; - let resolver = FileSystemResolver::new(); + let resolver = FileSystemResolver::new(sub_matches.value_of("stdlib-path").unwrap()); let artifacts: CompilationArtifacts = compile(source, path, Some(&resolver)).map_err(|e| { format!( @@ -368,7 +369,7 @@ fn cli_check(sub_matches: &ArgMatches) -> Result<(), String> { ) }; - let resolver = FileSystemResolver::new(); + let resolver = FileSystemResolver::new(sub_matches.value_of("stdlib-path").unwrap()); let _ = check::(source, path, Some(&resolver)).map_err(|e| { format!( "Check failed:\n\n{}", @@ -413,6 +414,8 @@ fn cli() -> Result<(), String> { const VERIFICATION_CONTRACT_DEFAULT_PATH: &str = "verifier.sol"; const WITNESS_DEFAULT_PATH: &str = "witness"; const JSON_PROOF_PATH: &str = "proof.json"; + + let default_stdlib_path: PathBuf = dirs::home_dir().unwrap().join(".zokrates/stdlib"); let default_curve = env::var("ZOKRATES_CURVE").unwrap_or(constants::BN128.into()); let default_scheme = env::var("ZOKRATES_PROVING_SCHEME").unwrap_or(constants::G16.into()); let default_solidity_abi = "v1"; @@ -432,6 +435,13 @@ fn cli() -> Result<(), String> { .value_name("FILE") .takes_value(true) .required(true) + ).arg(Arg::with_name("stdlib-path") + .long("stdlib-path") + .help("Path to the standard library") + .value_name("PATH") + .takes_value(true) + .required(true) + .default_value(default_stdlib_path.to_str().unwrap()) ).arg(Arg::with_name("abi_spec") .short("s") .long("abi_spec") @@ -932,7 +942,8 @@ mod tests { let mut source = String::new(); reader.read_to_string(&mut source).unwrap(); - let resolver = FileSystemResolver::new(); + let stdlib = std::fs::canonicalize("../zokrates_stdlib/stdlib").unwrap(); + let resolver = FileSystemResolver::new(stdlib.to_str().unwrap()); let _: CompilationArtifacts = compile(source, path, Some(&resolver)).unwrap(); } @@ -954,7 +965,9 @@ mod tests { let mut source = String::new(); reader.read_to_string(&mut source).unwrap(); - let resolver = FileSystemResolver::new(); + let stdlib = std::fs::canonicalize("../zokrates_stdlib/stdlib").unwrap(); + let resolver = FileSystemResolver::new(stdlib.to_str().unwrap()); + let artifacts: CompilationArtifacts = compile(source, path, Some(&resolver)).unwrap(); @@ -983,7 +996,9 @@ mod tests { let mut source = String::new(); reader.read_to_string(&mut source).unwrap(); - let resolver = FileSystemResolver::new(); + let stdlib = std::fs::canonicalize("../zokrates_stdlib/stdlib").unwrap(); + let resolver = FileSystemResolver::new(stdlib.to_str().unwrap()); + let artifacts: CompilationArtifacts = compile(source, path, Some(&resolver)).unwrap(); diff --git a/zokrates_cli/tests/integration.rs b/zokrates_cli/tests/integration.rs index 60c0a4d9c..15c7742d5 100644 --- a/zokrates_cli/tests/integration.rs +++ b/zokrates_cli/tests/integration.rs @@ -80,12 +80,16 @@ mod integration { // create a tmp folder to store artifacts fs::create_dir(test_case_path).unwrap(); + let stdlib = std::fs::canonicalize("../zokrates_stdlib/stdlib").unwrap(); + // prepare compile arguments let compile = vec![ "../target/release/zokrates", "compile", "-i", program_path.to_str().unwrap(), + "--stdlib-path", + stdlib.to_str().unwrap(), "-s", abi_spec_path.to_str().unwrap(), "-o", diff --git a/zokrates_fs_resolver/src/lib.rs b/zokrates_fs_resolver/src/lib.rs index f0a867890..c5dd01967 100644 --- a/zokrates_fs_resolver/src/lib.rs +++ b/zokrates_fs_resolver/src/lib.rs @@ -5,17 +5,17 @@ use std::path::Path; use std::path::{Component, PathBuf}; use zokrates_common::Resolver; -const ZOKRATES_HOME: &str = &"ZOKRATES_HOME"; - -pub struct FileSystemResolver; +pub struct FileSystemResolver<'a> { + stdlib_root_path: &'a str, +} -impl FileSystemResolver { - pub fn new() -> Self { - FileSystemResolver {} +impl<'a> FileSystemResolver<'a> { + pub fn new(stdlib_root_path: &'a str) -> Self { + FileSystemResolver { stdlib_root_path } } } -impl Resolver for FileSystemResolver { +impl<'a> Resolver for FileSystemResolver<'a> { fn resolve( &self, current_location: PathBuf, @@ -31,20 +31,13 @@ impl Resolver for FileSystemResolver { } // paths starting with `./` or `../` are interpreted relative to the current file - // other paths `abc/def` are interpreted relative to $ZOKRATES_HOME + // other paths `abc/def` are interpreted relative to standard library root path let base = match source.components().next() { Some(Component::CurDir) | Some(Component::ParentDir) => { - Ok(PathBuf::from(current_location).parent().unwrap().into()) + PathBuf::from(current_location).parent().unwrap().into() } - _ => std::env::var(ZOKRATES_HOME) - .map_err(|_| { - io::Error::new( - io::ErrorKind::Other, - "$ZOKRATES_HOME is not set, please set it", - ) - }) - .map(PathBuf::from), - }?; + _ => PathBuf::from(self.stdlib_root_path), + }; let path_owned = base .join(PathBuf::from(import_location.clone())) @@ -74,7 +67,7 @@ mod tests { let file_path = folder.path().join("bar.zok"); File::create(file_path.clone()).unwrap(); - let fs_resolver = FileSystemResolver::new(); + let fs_resolver = FileSystemResolver::new(""); let (_, next_location) = fs_resolver .resolve(file_path.clone(), "./bar.zok".into()) .unwrap(); @@ -83,14 +76,14 @@ mod tests { #[test] fn non_existing_file() { - let fs_resolver = FileSystemResolver::new(); + let fs_resolver = FileSystemResolver::new(""); let res = fs_resolver.resolve("./source.zok".into(), "./rubbish".into()); assert!(res.is_err()); } #[test] fn invalid_location() { - let fs_resolver = FileSystemResolver::new(); + let fs_resolver = FileSystemResolver::new(""); let res = fs_resolver.resolve(",8!-$2abc".into(), "./foo".into()); assert!(res.is_err()); } @@ -102,7 +95,7 @@ mod tests { let dir_path = folder.path().join("dir"); std::fs::create_dir(dir_path.clone()).unwrap(); - let fs_resolver = FileSystemResolver::new(); + let fs_resolver = FileSystemResolver::new(""); let res = fs_resolver.resolve(".".into(), "./dir/".into()); assert!(res.is_err()); } @@ -114,7 +107,7 @@ mod tests { let file_path = folder.path().join("foo.zok"); File::create(file_path.clone()).unwrap(); - let fs_resolver = FileSystemResolver::new(); + let fs_resolver = FileSystemResolver::new(""); let res = fs_resolver.resolve(file_path, ".".into()); assert!(res.is_err()); } @@ -135,10 +128,8 @@ mod tests { let mut file = File::create(file_path.clone()).unwrap(); writeln!(file, "").unwrap(); - // assign HOME folder to ZOKRATES_HOME - std::env::set_var(ZOKRATES_HOME, zokrates_home_folder.path()); - - let fs_resolver = FileSystemResolver::new(); + let stdlib_root_path = zokrates_home_folder.path().to_owned(); + let fs_resolver = FileSystemResolver::new(stdlib_root_path.to_str().unwrap()); let result = fs_resolver.resolve(file_path, "./bar.zok".into()); assert!(result.is_ok()); // the imported file should be the user's @@ -161,10 +152,8 @@ mod tests { let mut file = File::create(file_path.clone()).unwrap(); writeln!(file, "").unwrap(); - // assign HOME folder to ZOKRATES_HOME - std::env::set_var(ZOKRATES_HOME, zokrates_home_folder.path()); - - let fs_resolver = FileSystemResolver::new(); + let stdlib_root_path = zokrates_home_folder.path().to_owned(); + let fs_resolver = FileSystemResolver::new(stdlib_root_path.to_str().unwrap()); let result = fs_resolver.resolve(file_path.clone(), "bar.zok".into()); assert!(result.is_ok()); // the imported file should be the user's @@ -184,7 +173,7 @@ mod tests { let origin_path = source_subfolder.path().join("foo.zok"); File::create(origin_path).unwrap(); - let fs_resolver = FileSystemResolver::new(); + let fs_resolver = FileSystemResolver::new(""); let result = fs_resolver.resolve( source_subfolder.path().to_path_buf().join("foo.zok"), "../bar.zok".into(), @@ -204,26 +193,15 @@ mod tests { let mut file = File::create(file_path).unwrap(); writeln!(file, "").unwrap(); - // assign HOME folder to ZOKRATES_HOME - std::env::set_var(ZOKRATES_HOME, zokrates_home_folder.path()); - - let fs_resolver = FileSystemResolver::new(); + let stdlib_root_path = zokrates_home_folder.path().to_owned(); + let fs_resolver = FileSystemResolver::new(stdlib_root_path.to_str().unwrap()); let result = fs_resolver.resolve("/path/to/source.zok".into(), "./bar.zok".into()); assert!(result.is_err()); } #[test] fn fail_if_not_found_in_std() { - std::env::set_var(ZOKRATES_HOME, ""); - let fs_resolver = FileSystemResolver::new(); - let result = fs_resolver.resolve("/path/to/source.zok".into(), "bar.zok".into()); - assert!(result.is_err()); - } - - #[test] - fn panic_if_home_not_set() { - std::env::remove_var(ZOKRATES_HOME); - let fs_resolver = FileSystemResolver::new(); + let fs_resolver = FileSystemResolver::new(""); let result = fs_resolver.resolve("/path/to/source.zok".into(), "bar.zok".into()); assert!(result.is_err()); } diff --git a/zokrates_test/src/lib.rs b/zokrates_test/src/lib.rs index be0486312..8d7d51622 100644 --- a/zokrates_test/src/lib.rs +++ b/zokrates_test/src/lib.rs @@ -95,7 +95,8 @@ pub fn test_inner(test_path: &str) { fn compile_and_run(t: Tests) { let code = std::fs::read_to_string(&t.entry_point).unwrap(); - let resolver = FileSystemResolver::new(); + let stdlib = std::fs::canonicalize("../zokrates_stdlib/stdlib").unwrap(); + let resolver = FileSystemResolver::new(stdlib.to_str().unwrap()); let artifacts = compile::(code, t.entry_point.clone(), Some(&resolver)).unwrap(); let bin = artifacts.prog(); From 5850f77e1f9c1bfe87cd6e2c5219ee451187763b Mon Sep 17 00:00:00 2001 From: Darko Macesic Date: Fri, 26 Jun 2020 15:16:15 +0200 Subject: [PATCH 02/54] Update bin.rs --- zokrates_cli/src/bin.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zokrates_cli/src/bin.rs b/zokrates_cli/src/bin.rs index e193802ac..fdbc644d1 100644 --- a/zokrates_cli/src/bin.rs +++ b/zokrates_cli/src/bin.rs @@ -440,7 +440,7 @@ fn cli() -> Result<(), String> { .help("Path to the standard library") .value_name("PATH") .takes_value(true) - .required(true) + .required(false) .default_value(default_stdlib_path.to_str().unwrap()) ).arg(Arg::with_name("abi_spec") .short("s") From 30a38b64032ba8c428ee0ad64c5fde3c75a91f26 Mon Sep 17 00:00:00 2001 From: dark64 Date: Tue, 30 Jun 2020 12:04:53 +0200 Subject: [PATCH 03/54] minor changes for clarity --- zokrates_cli/src/bin.rs | 12 +++++++----- zokrates_fs_resolver/src/lib.rs | 22 +++++++++++----------- zokrates_test/src/lib.rs | 2 +- 3 files changed, 19 insertions(+), 17 deletions(-) diff --git a/zokrates_cli/src/bin.rs b/zokrates_cli/src/bin.rs index fdbc644d1..9549ad623 100644 --- a/zokrates_cli/src/bin.rs +++ b/zokrates_cli/src/bin.rs @@ -282,7 +282,8 @@ fn cli_compile(sub_matches: &ArgMatches) -> Result<(), String> { ) }; - let resolver = FileSystemResolver::new(sub_matches.value_of("stdlib-path").unwrap()); + let resolver = + FileSystemResolver::with_stdlib_root(sub_matches.value_of("stdlib-path").unwrap()); let artifacts: CompilationArtifacts = compile(source, path, Some(&resolver)).map_err(|e| { format!( @@ -369,7 +370,8 @@ fn cli_check(sub_matches: &ArgMatches) -> Result<(), String> { ) }; - let resolver = FileSystemResolver::new(sub_matches.value_of("stdlib-path").unwrap()); + let resolver = + FileSystemResolver::with_stdlib_root(sub_matches.value_of("stdlib-path").unwrap()); let _ = check::(source, path, Some(&resolver)).map_err(|e| { format!( "Check failed:\n\n{}", @@ -943,7 +945,7 @@ mod tests { reader.read_to_string(&mut source).unwrap(); let stdlib = std::fs::canonicalize("../zokrates_stdlib/stdlib").unwrap(); - let resolver = FileSystemResolver::new(stdlib.to_str().unwrap()); + let resolver = FileSystemResolver::with_stdlib_root(stdlib.to_str().unwrap()); let _: CompilationArtifacts = compile(source, path, Some(&resolver)).unwrap(); } @@ -966,7 +968,7 @@ mod tests { reader.read_to_string(&mut source).unwrap(); let stdlib = std::fs::canonicalize("../zokrates_stdlib/stdlib").unwrap(); - let resolver = FileSystemResolver::new(stdlib.to_str().unwrap()); + let resolver = FileSystemResolver::with_stdlib_root(stdlib.to_str().unwrap()); let artifacts: CompilationArtifacts = compile(source, path, Some(&resolver)).unwrap(); @@ -997,7 +999,7 @@ mod tests { reader.read_to_string(&mut source).unwrap(); let stdlib = std::fs::canonicalize("../zokrates_stdlib/stdlib").unwrap(); - let resolver = FileSystemResolver::new(stdlib.to_str().unwrap()); + let resolver = FileSystemResolver::with_stdlib_root(stdlib.to_str().unwrap()); let artifacts: CompilationArtifacts = compile(source, path, Some(&resolver)).unwrap(); diff --git a/zokrates_fs_resolver/src/lib.rs b/zokrates_fs_resolver/src/lib.rs index c5dd01967..8d6f5627f 100644 --- a/zokrates_fs_resolver/src/lib.rs +++ b/zokrates_fs_resolver/src/lib.rs @@ -10,7 +10,7 @@ pub struct FileSystemResolver<'a> { } impl<'a> FileSystemResolver<'a> { - pub fn new(stdlib_root_path: &'a str) -> Self { + pub fn with_stdlib_root(stdlib_root_path: &'a str) -> Self { FileSystemResolver { stdlib_root_path } } } @@ -67,7 +67,7 @@ mod tests { let file_path = folder.path().join("bar.zok"); File::create(file_path.clone()).unwrap(); - let fs_resolver = FileSystemResolver::new(""); + let fs_resolver = FileSystemResolver::with_stdlib_root(""); let (_, next_location) = fs_resolver .resolve(file_path.clone(), "./bar.zok".into()) .unwrap(); @@ -76,14 +76,14 @@ mod tests { #[test] fn non_existing_file() { - let fs_resolver = FileSystemResolver::new(""); + let fs_resolver = FileSystemResolver::with_stdlib_root(""); let res = fs_resolver.resolve("./source.zok".into(), "./rubbish".into()); assert!(res.is_err()); } #[test] fn invalid_location() { - let fs_resolver = FileSystemResolver::new(""); + let fs_resolver = FileSystemResolver::with_stdlib_root(""); let res = fs_resolver.resolve(",8!-$2abc".into(), "./foo".into()); assert!(res.is_err()); } @@ -95,7 +95,7 @@ mod tests { let dir_path = folder.path().join("dir"); std::fs::create_dir(dir_path.clone()).unwrap(); - let fs_resolver = FileSystemResolver::new(""); + let fs_resolver = FileSystemResolver::with_stdlib_root(""); let res = fs_resolver.resolve(".".into(), "./dir/".into()); assert!(res.is_err()); } @@ -107,7 +107,7 @@ mod tests { let file_path = folder.path().join("foo.zok"); File::create(file_path.clone()).unwrap(); - let fs_resolver = FileSystemResolver::new(""); + let fs_resolver = FileSystemResolver::with_stdlib_root(""); let res = fs_resolver.resolve(file_path, ".".into()); assert!(res.is_err()); } @@ -129,7 +129,7 @@ mod tests { writeln!(file, "").unwrap(); let stdlib_root_path = zokrates_home_folder.path().to_owned(); - let fs_resolver = FileSystemResolver::new(stdlib_root_path.to_str().unwrap()); + let fs_resolver = FileSystemResolver::with_stdlib_root(stdlib_root_path.to_str().unwrap()); let result = fs_resolver.resolve(file_path, "./bar.zok".into()); assert!(result.is_ok()); // the imported file should be the user's @@ -153,7 +153,7 @@ mod tests { writeln!(file, "").unwrap(); let stdlib_root_path = zokrates_home_folder.path().to_owned(); - let fs_resolver = FileSystemResolver::new(stdlib_root_path.to_str().unwrap()); + let fs_resolver = FileSystemResolver::with_stdlib_root(stdlib_root_path.to_str().unwrap()); let result = fs_resolver.resolve(file_path.clone(), "bar.zok".into()); assert!(result.is_ok()); // the imported file should be the user's @@ -173,7 +173,7 @@ mod tests { let origin_path = source_subfolder.path().join("foo.zok"); File::create(origin_path).unwrap(); - let fs_resolver = FileSystemResolver::new(""); + let fs_resolver = FileSystemResolver::with_stdlib_root(""); let result = fs_resolver.resolve( source_subfolder.path().to_path_buf().join("foo.zok"), "../bar.zok".into(), @@ -194,14 +194,14 @@ mod tests { writeln!(file, "").unwrap(); let stdlib_root_path = zokrates_home_folder.path().to_owned(); - let fs_resolver = FileSystemResolver::new(stdlib_root_path.to_str().unwrap()); + let fs_resolver = FileSystemResolver::with_stdlib_root(stdlib_root_path.to_str().unwrap()); let result = fs_resolver.resolve("/path/to/source.zok".into(), "./bar.zok".into()); assert!(result.is_err()); } #[test] fn fail_if_not_found_in_std() { - let fs_resolver = FileSystemResolver::new(""); + let fs_resolver = FileSystemResolver::with_stdlib_root(""); let result = fs_resolver.resolve("/path/to/source.zok".into(), "bar.zok".into()); assert!(result.is_err()); } diff --git a/zokrates_test/src/lib.rs b/zokrates_test/src/lib.rs index 8d7d51622..878fe952f 100644 --- a/zokrates_test/src/lib.rs +++ b/zokrates_test/src/lib.rs @@ -96,7 +96,7 @@ fn compile_and_run(t: Tests) { let code = std::fs::read_to_string(&t.entry_point).unwrap(); let stdlib = std::fs::canonicalize("../zokrates_stdlib/stdlib").unwrap(); - let resolver = FileSystemResolver::new(stdlib.to_str().unwrap()); + let resolver = FileSystemResolver::with_stdlib_root(stdlib.to_str().unwrap()); let artifacts = compile::(code, t.entry_point.clone(), Some(&resolver)).unwrap(); let bin = artifacts.prog(); From 8c840f9566c820281a25c5a6f791b99ac2d97194 Mon Sep 17 00:00:00 2001 From: dark64 Date: Tue, 30 Jun 2020 12:43:23 +0200 Subject: [PATCH 04/54] remove default value for stdlib-path --- Cargo.lock | 76 +---------------------------------------- zokrates_cli/Cargo.toml | 1 - zokrates_cli/src/bin.rs | 6 +--- 3 files changed, 2 insertions(+), 81 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 9a636c71e..50b9d9151 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -18,12 +18,6 @@ dependencies = [ "winapi", ] -[[package]] -name = "arrayref" -version = "0.3.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4c527152e37cf757a3f78aae5a06fbeefdb07ccc535c980a3208ee3060dd544" - [[package]] name = "arrayvec" version = "0.4.12" @@ -33,12 +27,6 @@ dependencies = [ "nodrop", ] -[[package]] -name = "arrayvec" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cff77d8686867eceff3105329d4698d96c2391c176d5d03adc90c7389162b5b8" - [[package]] name = "assert_cli" version = "0.5.4" @@ -92,12 +80,6 @@ dependencies = [ "libc", ] -[[package]] -name = "base64" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b41b7ea54a0c9d92199de89e20e58d49f02f8e699814ef3fdf266f6f748d15c7" - [[package]] name = "bellman_ce" version = "0.3.4" @@ -144,22 +126,11 @@ version = "0.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fdc60350286c7c3db13b98e91dbe5c8b6830a6821bc20af5b0c310ce94d74915" dependencies = [ - "arrayvec 0.4.12", + "arrayvec", "byteorder", "constant_time_eq", ] -[[package]] -name = "blake2b_simd" -version = "0.5.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d8fb2d74254a3a0b5cac33ac9f8ed0e44aa50378d9dbb2e5d83bd21ed1dc2c8a" -dependencies = [ - "arrayref", - "arrayvec 0.5.1", - "constant_time_eq", -] - [[package]] name = "block-buffer" version = "0.7.3" @@ -411,27 +382,6 @@ dependencies = [ "generic-array", ] -[[package]] -name = "dirs" -version = "3.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2fddc3610d8f9552384e06ebc87f714e1d0b2b64a99194d2faf36d7ae5f48549" -dependencies = [ - "cfg-if", - "dirs-sys", -] - -[[package]] -name = "dirs-sys" -version = "0.3.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e93d7f5705de3e49895a2b5e0b8855a1c27f080192ae9c32a6432d50741a57a" -dependencies = [ - "libc", - "redox_users", - "winapi", -] - [[package]] name = "either" version = "1.5.3" @@ -1190,17 +1140,6 @@ version = "0.1.56" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2439c63f3f6139d1b57529d16bc3b8bb855230c8efcc5d3a896c8bea7c3b1e84" -[[package]] -name = "redox_users" -version = "0.3.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09b23093265f8d200fa7b4c2c76297f47e681c655f6f1285a8780d6a022f7431" -dependencies = [ - "getrandom", - "redox_syscall", - "rust-argon2", -] - [[package]] name = "reduce" version = "0.1.2" @@ -1247,18 +1186,6 @@ dependencies = [ "winapi", ] -[[package]] -name = "rust-argon2" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2bc8af4bda8e1ff4932523b94d3dd20ee30a87232323eda55903ffd71d2fb017" -dependencies = [ - "base64", - "blake2b_simd", - "constant_time_eq", - "crossbeam-utils", -] - [[package]] name = "rustc-demangle" version = "0.1.16" @@ -1781,7 +1708,6 @@ dependencies = [ "assert_cli", "bincode", "clap", - "dirs", "fs_extra", "glob 0.2.11", "regex", diff --git a/zokrates_cli/Cargo.toml b/zokrates_cli/Cargo.toml index 8fc34242f..f69841792 100644 --- a/zokrates_cli/Cargo.toml +++ b/zokrates_cli/Cargo.toml @@ -18,7 +18,6 @@ zokrates_abi = { version = "0.1", path = "../zokrates_abi" } zokrates_core = { version = "0.4", path = "../zokrates_core" } zokrates_fs_resolver = { version = "0.5", path = "../zokrates_fs_resolver"} serde_json = "1.0" -dirs = "3.0" [dev-dependencies] glob = "0.2.11" diff --git a/zokrates_cli/src/bin.rs b/zokrates_cli/src/bin.rs index 9549ad623..c44842c9a 100644 --- a/zokrates_cli/src/bin.rs +++ b/zokrates_cli/src/bin.rs @@ -4,8 +4,6 @@ // @author Dennis Kuhnert // @date 2017 -extern crate dirs; - mod constants; use constants::*; @@ -417,7 +415,6 @@ fn cli() -> Result<(), String> { const WITNESS_DEFAULT_PATH: &str = "witness"; const JSON_PROOF_PATH: &str = "proof.json"; - let default_stdlib_path: PathBuf = dirs::home_dir().unwrap().join(".zokrates/stdlib"); let default_curve = env::var("ZOKRATES_CURVE").unwrap_or(constants::BN128.into()); let default_scheme = env::var("ZOKRATES_PROVING_SCHEME").unwrap_or(constants::G16.into()); let default_solidity_abi = "v1"; @@ -442,8 +439,7 @@ fn cli() -> Result<(), String> { .help("Path to the standard library") .value_name("PATH") .takes_value(true) - .required(false) - .default_value(default_stdlib_path.to_str().unwrap()) + .required(true) ).arg(Arg::with_name("abi_spec") .short("s") .long("abi_spec") From 2ca237be8498410b4890ea9a53f5e4b87df1c676 Mon Sep 17 00:00:00 2001 From: dark64 Date: Tue, 30 Jun 2020 12:50:23 +0200 Subject: [PATCH 05/54] add stdlib-path arg to check command --- zokrates_cli/src/bin.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/zokrates_cli/src/bin.rs b/zokrates_cli/src/bin.rs index c44842c9a..da50245a1 100644 --- a/zokrates_cli/src/bin.rs +++ b/zokrates_cli/src/bin.rs @@ -479,6 +479,12 @@ fn cli() -> Result<(), String> { .value_name("FILE") .takes_value(true) .required(true) + ).arg(Arg::with_name("stdlib-path") + .long("stdlib-path") + .help("Path to the standard library") + .value_name("PATH") + .takes_value(true) + .required(true) ).arg(Arg::with_name("curve") .short("c") .long("curve") From 4c2a1fc74ba9beec81c846e9edf12ca13ef67bfc Mon Sep 17 00:00:00 2001 From: dark64 Date: Tue, 30 Jun 2020 13:57:02 +0200 Subject: [PATCH 06/54] Update docs, set stdlib-path as optional parameter --- Dockerfile | 5 +++-- dev.Dockerfile | 1 - zokrates_book/src/concepts/stdlib.md | 2 +- zokrates_book/src/reference/testing.md | 10 +++------- zokrates_cli/src/bin.rs | 6 ++++-- 5 files changed, 11 insertions(+), 13 deletions(-) diff --git a/Dockerfile b/Dockerfile index f22d41fda..877b69243 100644 --- a/Dockerfile +++ b/Dockerfile @@ -4,9 +4,10 @@ MAINTAINER JacobEberhardt , Thibaut Schaeffer , Thibaut Schaeffer Result<(), String> { .help("Path to the standard library") .value_name("PATH") .takes_value(true) - .required(true) + .required(false) + .default_value("") ).arg(Arg::with_name("abi_spec") .short("s") .long("abi_spec") @@ -484,7 +485,8 @@ fn cli() -> Result<(), String> { .help("Path to the standard library") .value_name("PATH") .takes_value(true) - .required(true) + .required(false) + .default_value("") ).arg(Arg::with_name("curve") .short("c") .long("curve") From 92b35495d06942f4e94d5e2b3be39641e8d97122 Mon Sep 17 00:00:00 2001 From: dark64 Date: Tue, 14 Jul 2020 19:02:56 +0200 Subject: [PATCH 07/54] wrap stdlib root path with Option --- zokrates_fs_resolver/src/lib.rs | 23 +++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/zokrates_fs_resolver/src/lib.rs b/zokrates_fs_resolver/src/lib.rs index 8d6f5627f..891bc5869 100644 --- a/zokrates_fs_resolver/src/lib.rs +++ b/zokrates_fs_resolver/src/lib.rs @@ -5,13 +5,16 @@ use std::path::Path; use std::path::{Component, PathBuf}; use zokrates_common::Resolver; +#[derive(Debug, Default)] pub struct FileSystemResolver<'a> { - stdlib_root_path: &'a str, + stdlib_root_path: Option<&'a str>, } impl<'a> FileSystemResolver<'a> { pub fn with_stdlib_root(stdlib_root_path: &'a str) -> Self { - FileSystemResolver { stdlib_root_path } + FileSystemResolver { + stdlib_root_path: Some(stdlib_root_path), + } } } @@ -36,7 +39,7 @@ impl<'a> Resolver for FileSystemResolver<'a> { Some(Component::CurDir) | Some(Component::ParentDir) => { PathBuf::from(current_location).parent().unwrap().into() } - _ => PathBuf::from(self.stdlib_root_path), + _ => PathBuf::from(self.stdlib_root_path.unwrap_or("")), }; let path_owned = base @@ -67,7 +70,7 @@ mod tests { let file_path = folder.path().join("bar.zok"); File::create(file_path.clone()).unwrap(); - let fs_resolver = FileSystemResolver::with_stdlib_root(""); + let fs_resolver = FileSystemResolver::default(); let (_, next_location) = fs_resolver .resolve(file_path.clone(), "./bar.zok".into()) .unwrap(); @@ -76,14 +79,14 @@ mod tests { #[test] fn non_existing_file() { - let fs_resolver = FileSystemResolver::with_stdlib_root(""); + let fs_resolver = FileSystemResolver::default(); let res = fs_resolver.resolve("./source.zok".into(), "./rubbish".into()); assert!(res.is_err()); } #[test] fn invalid_location() { - let fs_resolver = FileSystemResolver::with_stdlib_root(""); + let fs_resolver = FileSystemResolver::default(); let res = fs_resolver.resolve(",8!-$2abc".into(), "./foo".into()); assert!(res.is_err()); } @@ -95,7 +98,7 @@ mod tests { let dir_path = folder.path().join("dir"); std::fs::create_dir(dir_path.clone()).unwrap(); - let fs_resolver = FileSystemResolver::with_stdlib_root(""); + let fs_resolver = FileSystemResolver::default(); let res = fs_resolver.resolve(".".into(), "./dir/".into()); assert!(res.is_err()); } @@ -107,7 +110,7 @@ mod tests { let file_path = folder.path().join("foo.zok"); File::create(file_path.clone()).unwrap(); - let fs_resolver = FileSystemResolver::with_stdlib_root(""); + let fs_resolver = FileSystemResolver::default(); let res = fs_resolver.resolve(file_path, ".".into()); assert!(res.is_err()); } @@ -173,7 +176,7 @@ mod tests { let origin_path = source_subfolder.path().join("foo.zok"); File::create(origin_path).unwrap(); - let fs_resolver = FileSystemResolver::with_stdlib_root(""); + let fs_resolver = FileSystemResolver::default(); let result = fs_resolver.resolve( source_subfolder.path().to_path_buf().join("foo.zok"), "../bar.zok".into(), @@ -201,7 +204,7 @@ mod tests { #[test] fn fail_if_not_found_in_std() { - let fs_resolver = FileSystemResolver::with_stdlib_root(""); + let fs_resolver = FileSystemResolver::default(); let result = fs_resolver.resolve("/path/to/source.zok".into(), "bar.zok".into()); assert!(result.is_err()); } From 5875a4d70f82b5ca603abcdcb198a12658bf11b9 Mon Sep 17 00:00:00 2001 From: Thibaut Schaeffer Date: Fri, 14 Aug 2020 12:18:00 +0200 Subject: [PATCH 08/54] Update zokrates_fs_resolver/src/lib.rs --- zokrates_fs_resolver/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zokrates_fs_resolver/src/lib.rs b/zokrates_fs_resolver/src/lib.rs index 2e13ccd3e..9da6900e8 100644 --- a/zokrates_fs_resolver/src/lib.rs +++ b/zokrates_fs_resolver/src/lib.rs @@ -34,7 +34,7 @@ impl<'a> Resolver for FileSystemResolver<'a> { } // paths starting with `./` or `../` are interpreted relative to the current file - // other paths `abc/def` are interpreted relative to standard library root path + // other paths `abc/def` are interpreted relative to the standard library root path let base = match source.components().next() { Some(Component::CurDir) | Some(Component::ParentDir) => { PathBuf::from(current_location).parent().unwrap().into() From 676d4e291a2e1edda291c6df83039104a99e292c Mon Sep 17 00:00:00 2001 From: dark64 Date: Fri, 14 Aug 2020 14:17:34 +0200 Subject: [PATCH 09/54] add custom serializer for Type, set raw field as optional in proof --- .../src/proof_system/bellman/groth16.rs | 9 +- .../src/proof_system/libsnark/gm17.rs | 2 +- .../src/proof_system/libsnark/pghr13.rs | 2 +- zokrates_core/src/proof_system/mod.rs | 4 +- zokrates_core/src/typed_absy/abi.rs | 84 ++++++++++++-- zokrates_core/src/typed_absy/types.rs | 104 ++++++++++++++++-- 6 files changed, 176 insertions(+), 29 deletions(-) diff --git a/zokrates_core/src/proof_system/bellman/groth16.rs b/zokrates_core/src/proof_system/bellman/groth16.rs index a75611c38..780171905 100644 --- a/zokrates_core/src/proof_system/bellman/groth16.rs +++ b/zokrates_core/src/proof_system/bellman/groth16.rs @@ -73,9 +73,7 @@ impl ProofSystem for G16 { println!("{}", G16_WARNING); let parameters = Computation::without_witness(program).setup(); - let mut pk: Vec = Vec::new(); - parameters.write(&mut pk).unwrap(); let vk = VerificationKey { @@ -121,10 +119,7 @@ impl ProofSystem for G16 { .map(parse_fr::) .collect::>(); - let mut raw: Vec = Vec::new(); - proof.write(&mut raw).unwrap(); - - Proof::::new(proof_points, inputs, hex::encode(&raw)) + Proof::::new(proof_points, inputs, None) } fn export_solidity_verifier(vk: VerificationKey, abi: SolidityAbi) -> String { @@ -232,9 +227,7 @@ impl ProofSystem for G16 { fn verify(vk: VerificationKey, proof: Proof) -> bool { let vk: VerifyingKey = vk.into_bellman::(); - let pvk: PreparedVerifyingKey = prepare_verifying_key(&vk); - let bellman_proof: BellmanProof = proof.proof.into_bellman::(); let public_inputs: Vec<_> = proof diff --git a/zokrates_core/src/proof_system/libsnark/gm17.rs b/zokrates_core/src/proof_system/libsnark/gm17.rs index cb3f36509..b1fe8e462 100644 --- a/zokrates_core/src/proof_system/libsnark/gm17.rs +++ b/zokrates_core/src/proof_system/libsnark/gm17.rs @@ -239,7 +239,7 @@ impl ProofSystem for GM17 { fn verify(vk: VerificationKey, proof: Proof) -> bool { let vk_raw = hex::decode(vk.raw.clone()).unwrap(); - let proof_raw = hex::decode(proof.raw.clone()).unwrap(); + let proof_raw = hex::decode(proof.raw.unwrap().clone()).unwrap(); let public_inputs: Vec<_> = proof .inputs diff --git a/zokrates_core/src/proof_system/libsnark/pghr13.rs b/zokrates_core/src/proof_system/libsnark/pghr13.rs index 27de4416f..62292dc6f 100644 --- a/zokrates_core/src/proof_system/libsnark/pghr13.rs +++ b/zokrates_core/src/proof_system/libsnark/pghr13.rs @@ -251,7 +251,7 @@ impl ProofSystem for PGHR13 { fn verify(vk: VerificationKey, proof: Proof) -> bool { let vk_raw = hex::decode(vk.raw.clone()).unwrap(); - let proof_raw = hex::decode(proof.raw.clone()).unwrap(); + let proof_raw = hex::decode(proof.raw.unwrap().clone()).unwrap(); let public_inputs: Vec<_> = proof .inputs diff --git a/zokrates_core/src/proof_system/mod.rs b/zokrates_core/src/proof_system/mod.rs index c5eb20fda..2c597de60 100644 --- a/zokrates_core/src/proof_system/mod.rs +++ b/zokrates_core/src/proof_system/mod.rs @@ -42,11 +42,11 @@ impl SolidityAbi { pub struct Proof { proof: T, inputs: Vec, - raw: String, + raw: Option, } impl Proof { - fn new(proof: T, inputs: Vec, raw: String) -> Self { + fn new(proof: T, inputs: Vec, raw: Option) -> Self { Proof { proof, inputs, raw } } } diff --git a/zokrates_core/src/typed_absy/abi.rs b/zokrates_core/src/typed_absy/abi.rs index 206e802a9..bc82206a8 100644 --- a/zokrates_core/src/typed_absy/abi.rs +++ b/zokrates_core/src/typed_absy/abi.rs @@ -32,7 +32,8 @@ mod tests { use std::collections::HashMap; use typed_absy::types::{ArrayType, FunctionKey, StructMember, StructType}; use typed_absy::{ - Parameter, Type, TypedFunction, TypedFunctionSymbol, TypedModule, TypedProgram, Variable, + Parameter, Type, TypedFunction, TypedFunctionSymbol, TypedModule, TypedProgram, UBitwidth, + Variable, }; use zokrates_field::Bn128Field; @@ -95,7 +96,9 @@ mod tests { }; let json = serde_json::to_string(&abi).unwrap(); - assert_eq!(&json, r#"{"inputs":[],"outputs":[]}"#) + assert_eq!(&json, r#"{"inputs":[],"outputs":[]}"#); + let de_abi: Abi = serde_json::from_str(json.as_ref()).unwrap(); + assert_eq!(de_abi, abi); } #[test] @@ -138,7 +141,62 @@ mod tests { } ] }"# - ) + ); + + let de_abi: Abi = serde_json::from_str(json.as_ref()).unwrap(); + assert_eq!(de_abi, abi); + } + + #[test] + fn serialize_uints() { + let abi: Abi = Abi { + inputs: vec![ + AbiInput { + name: String::from("a"), + public: true, + ty: Type::Uint(UBitwidth::B8), + }, + AbiInput { + name: String::from("b"), + public: true, + ty: Type::Uint(UBitwidth::B16), + }, + AbiInput { + name: String::from("c"), + public: true, + ty: Type::Uint(UBitwidth::B32), + }, + ], + outputs: vec![], + }; + + let json = serde_json::to_string_pretty(&abi).unwrap(); + assert_eq!( + &json, + r#"{ + "inputs": [ + { + "name": "a", + "public": true, + "type": "u8" + }, + { + "name": "b", + "public": true, + "type": "u16" + }, + { + "name": "c", + "public": true, + "type": "u32" + } + ], + "outputs": [] +}"# + ); + + let de_abi: Abi = serde_json::from_str(json.as_ref()).unwrap(); + assert_eq!(de_abi, abi); } #[test] @@ -209,7 +267,10 @@ mod tests { } ] }"# - ) + ); + + let de_abi: Abi = serde_json::from_str(json.as_ref()).unwrap(); + assert_eq!(de_abi, abi); } #[test] @@ -272,7 +333,10 @@ mod tests { ], "outputs": [] }"# - ) + ); + + let de_abi: Abi = serde_json::from_str(json.as_ref()).unwrap(); + assert_eq!(de_abi, abi); } #[test] @@ -330,7 +394,10 @@ mod tests { } ] }"# - ) + ); + + let de_abi: Abi = serde_json::from_str(json.as_ref()).unwrap(); + assert_eq!(de_abi, abi); } #[test] @@ -372,6 +439,9 @@ mod tests { } ] }"# - ) + ); + + let de_abi: Abi = serde_json::from_str(json.as_ref()).unwrap(); + assert_eq!(de_abi, abi); } } diff --git a/zokrates_core/src/typed_absy/types.rs b/zokrates_core/src/typed_absy/types.rs index 04688f46d..34e05e72c 100644 --- a/zokrates_core/src/typed_absy/types.rs +++ b/zokrates_core/src/typed_absy/types.rs @@ -5,7 +5,7 @@ pub type Identifier<'ast> = &'ast str; pub type MemberId = String; -#[derive(Clone, PartialEq, Eq, Hash, Serialize, Deserialize, PartialOrd, Ord)] +#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, PartialOrd, Ord)] pub struct StructMember { #[serde(rename = "name")] pub id: MemberId, @@ -13,14 +13,14 @@ pub struct StructMember { pub ty: Box, } -#[derive(Clone, PartialEq, Eq, Hash, Serialize, Deserialize, PartialOrd, Ord)] +#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, PartialOrd, Ord)] pub struct ArrayType { pub size: usize, #[serde(flatten)] pub ty: Box, } -#[derive(Clone, Hash, Serialize, Deserialize, PartialOrd, Ord)] +#[derive(Debug, Clone, Hash, Serialize, Deserialize, PartialOrd, Ord)] pub struct StructType { #[serde(skip)] pub module: PathBuf, @@ -96,21 +96,102 @@ impl fmt::Display for UBitwidth { } } -#[derive(Clone, PartialEq, Eq, Hash, Serialize, Deserialize, PartialOrd, Ord)] -#[serde(tag = "type", content = "components")] +#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] pub enum Type { - #[serde(rename = "field")] FieldElement, - #[serde(rename = "bool")] Boolean, - #[serde(rename = "array")] Array(ArrayType), - #[serde(rename = "struct")] Struct(StructType), - #[serde(rename = "u")] Uint(UBitwidth), } +impl Serialize for Type { + fn serialize(&self, s: S) -> Result<::Ok, ::Error> + where + S: Serializer, + { + match self { + Type::FieldElement => s.serialize_newtype_variant("Type", 0, "type", "field"), + Type::Boolean => s.serialize_newtype_variant("Type", 1, "type", "bool"), + Type::Array(array_type) => { + let mut map = s.serialize_map(Some(2))?; + map.serialize_entry("type", "array")?; + map.serialize_entry("components", array_type)?; + map.end() + } + Type::Struct(struct_type) => { + let mut map = s.serialize_map(Some(2))?; + map.serialize_entry("type", "struct")?; + map.serialize_entry("components", struct_type)?; + map.end() + } + Type::Uint(width) => s.serialize_newtype_variant( + "Type", + 4, + "type", + format!("u{}", width.to_usize()).as_str(), + ), + } + } +} + +impl<'de> Deserialize<'de> for Type { + fn deserialize(d: D) -> Result>::Error> + where + D: Deserializer<'de>, + { + #[derive(Debug, Deserialize)] + #[serde(untagged)] + enum Components { + Array(ArrayType), + Struct(StructType), + } + + #[derive(Debug, Deserialize)] + struct Mapping { + #[serde(rename = "type")] + ty: String, + components: Option, + } + + let mapping = Mapping::deserialize(d)?; + match mapping.ty.as_str() { + "field" => Ok(Type::FieldElement), + "bool" => Ok(Type::Boolean), + "array" => { + let components = mapping.components.ok_or(D::Error::custom(format!( + "Missing `components` field for type `{}`", + mapping.ty + )))?; + match components { + Components::Array(array_type) => Ok(Type::Array(array_type)), + _ => Err(D::Error::custom(format!( + "Invalid `components` field for type `{}`", + mapping.ty + ))), + } + } + "struct" => { + let components = mapping.components.ok_or(D::Error::custom(format!( + "Missing `components` field for type `{}`", + mapping.ty + )))?; + match components { + Components::Struct(struct_type) => Ok(Type::Struct(struct_type)), + _ => Err(D::Error::custom(format!( + "Invalid `components` field for type `{}`", + mapping.ty + ))), + } + } + "u8" => Ok(Type::Uint(UBitwidth::B8)), + "u16" => Ok(Type::Uint(UBitwidth::B16)), + "u32" => Ok(Type::Uint(UBitwidth::B32)), + _ => Err(D::Error::custom(format!("Unknown type `{}`", mapping.ty))), + } + } +} + impl ArrayType { pub fn new(ty: Type, size: usize) -> Self { ArrayType { @@ -250,6 +331,9 @@ impl<'ast> FunctionKey<'ast> { } pub use self::signature::Signature; +use serde::de::Error; +use serde::ser::SerializeMap; +use serde::{Deserialize, Deserializer, Serialize, Serializer}; pub mod signature { use super::*; From 94ffc6e57057bc95960994ca1735235aa4e3e7ad Mon Sep 17 00:00:00 2001 From: dark64 Date: Tue, 25 Aug 2020 17:00:43 +0200 Subject: [PATCH 10/54] strict mapping in type deserialization --- zokrates_core/src/typed_absy/types.rs | 69 ++++++++++++++++++++++----- 1 file changed, 57 insertions(+), 12 deletions(-) diff --git a/zokrates_core/src/typed_absy/types.rs b/zokrates_core/src/typed_absy/types.rs index 34e05e72c..034f0b03a 100644 --- a/zokrates_core/src/typed_absy/types.rs +++ b/zokrates_core/src/typed_absy/types.rs @@ -156,38 +156,83 @@ impl<'de> Deserialize<'de> for Type { let mapping = Mapping::deserialize(d)?; match mapping.ty.as_str() { - "field" => Ok(Type::FieldElement), - "bool" => Ok(Type::Boolean), + "field" => { + if mapping.components.is_some() { + Err(D::Error::custom(format!( + "unexpected `components` field for type `{}`", + mapping.ty + ))) + } else { + Ok(Type::FieldElement) + } + } + "bool" => { + if mapping.components.is_some() { + Err(D::Error::custom(format!( + "unexpected `components` field for type `{}`", + mapping.ty + ))) + } else { + Ok(Type::Boolean) + } + } "array" => { - let components = mapping.components.ok_or(D::Error::custom(format!( - "Missing `components` field for type `{}`", + let components = mapping.components.ok_or(D::Error::custom(format_args!( + "missing `components` field for type `{}'", mapping.ty )))?; match components { Components::Array(array_type) => Ok(Type::Array(array_type)), _ => Err(D::Error::custom(format!( - "Invalid `components` field for type `{}`", + "invalid `components` variant for type `{}`", mapping.ty ))), } } "struct" => { - let components = mapping.components.ok_or(D::Error::custom(format!( - "Missing `components` field for type `{}`", + let components = mapping.components.ok_or(D::Error::custom(format_args!( + "missing `components` field for type `{}'", mapping.ty )))?; match components { Components::Struct(struct_type) => Ok(Type::Struct(struct_type)), _ => Err(D::Error::custom(format!( - "Invalid `components` field for type `{}`", + "invalid `components` variant for type `{}`", mapping.ty ))), } } - "u8" => Ok(Type::Uint(UBitwidth::B8)), - "u16" => Ok(Type::Uint(UBitwidth::B16)), - "u32" => Ok(Type::Uint(UBitwidth::B32)), - _ => Err(D::Error::custom(format!("Unknown type `{}`", mapping.ty))), + "u8" => { + if mapping.components.is_some() { + Err(D::Error::custom(format!( + "unexpected `components` field for type `{}`", + mapping.ty + ))) + } else { + Ok(Type::Uint(UBitwidth::B8)) + } + } + "u16" => { + if mapping.components.is_some() { + Err(D::Error::custom(format!( + "unexpected `components` field for type `{}`", + mapping.ty + ))) + } else { + Ok(Type::Uint(UBitwidth::B16)) + } + } + "u32" => { + if mapping.components.is_some() { + Err(D::Error::custom(format!( + "unexpected `components` field for type `{}`", + mapping.ty + ))) + } else { + Ok(Type::Uint(UBitwidth::B32)) + } + } + _ => Err(D::Error::custom(format!("invalid type `{}`", mapping.ty))), } } } From 41b5a14d5bb807de27269300210b82729093bf55 Mon Sep 17 00:00:00 2001 From: dark64 Date: Tue, 1 Sep 2020 16:04:26 +0200 Subject: [PATCH 11/54] strict types --- zokrates_core/src/typed_absy/types.rs | 65 +++++++-------------------- 1 file changed, 15 insertions(+), 50 deletions(-) diff --git a/zokrates_core/src/typed_absy/types.rs b/zokrates_core/src/typed_absy/types.rs index 034f0b03a..d1eac1db6 100644 --- a/zokrates_core/src/typed_absy/types.rs +++ b/zokrates_core/src/typed_absy/types.rs @@ -154,28 +154,20 @@ impl<'de> Deserialize<'de> for Type { components: Option, } + let strict_type = |m: Mapping, ty: Type| -> Result>::Error> { + match m.components { + Some(_) => Err(D::Error::custom(format!( + "unexpected `components` field for type `{}`", + ty + ))), + None => Ok(ty), + } + }; + let mapping = Mapping::deserialize(d)?; match mapping.ty.as_str() { - "field" => { - if mapping.components.is_some() { - Err(D::Error::custom(format!( - "unexpected `components` field for type `{}`", - mapping.ty - ))) - } else { - Ok(Type::FieldElement) - } - } - "bool" => { - if mapping.components.is_some() { - Err(D::Error::custom(format!( - "unexpected `components` field for type `{}`", - mapping.ty - ))) - } else { - Ok(Type::Boolean) - } - } + "field" => strict_type(mapping, Type::FieldElement), + "bool" => strict_type(mapping, Type::Boolean), "array" => { let components = mapping.components.ok_or(D::Error::custom(format_args!( "missing `components` field for type `{}'", @@ -202,36 +194,9 @@ impl<'de> Deserialize<'de> for Type { ))), } } - "u8" => { - if mapping.components.is_some() { - Err(D::Error::custom(format!( - "unexpected `components` field for type `{}`", - mapping.ty - ))) - } else { - Ok(Type::Uint(UBitwidth::B8)) - } - } - "u16" => { - if mapping.components.is_some() { - Err(D::Error::custom(format!( - "unexpected `components` field for type `{}`", - mapping.ty - ))) - } else { - Ok(Type::Uint(UBitwidth::B16)) - } - } - "u32" => { - if mapping.components.is_some() { - Err(D::Error::custom(format!( - "unexpected `components` field for type `{}`", - mapping.ty - ))) - } else { - Ok(Type::Uint(UBitwidth::B32)) - } - } + "u8" => strict_type(mapping, Type::Uint(UBitwidth::B8)), + "u16" => strict_type(mapping, Type::Uint(UBitwidth::B16)), + "u32" => strict_type(mapping, Type::Uint(UBitwidth::B32)), _ => Err(D::Error::custom(format!("invalid type `{}`", mapping.ty))), } } From b9d033bc8de51ba765320bb4a65ff1d085e933c1 Mon Sep 17 00:00:00 2001 From: dark64 Date: Fri, 11 Sep 2020 00:45:58 +0200 Subject: [PATCH 12/54] field constant range check --- Cargo.lock | 8 +- zokrates_core/src/absy/from_ast.rs | 266 ++++++++++++-------------- zokrates_core/src/absy/mod.rs | 213 +++++++++++---------- zokrates_core/src/absy/node.rs | 20 +- zokrates_core/src/compile.rs | 14 +- zokrates_core/src/imports.rs | 8 +- zokrates_core/src/semantics.rs | 292 ++++++++++++++++------------- 7 files changed, 417 insertions(+), 404 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 1d8d7ac1a..d3e6605e6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1744,7 +1744,7 @@ dependencies = [ [[package]] name = "zokrates_cli" -version = "0.6.0" +version = "0.6.1" dependencies = [ "assert_cli", "bincode", @@ -1767,7 +1767,7 @@ version = "0.1.0" [[package]] name = "zokrates_core" -version = "0.5.0" +version = "0.5.1" dependencies = [ "assert_cli", "bellman_ce", @@ -1825,7 +1825,7 @@ dependencies = [ [[package]] name = "zokrates_fs_resolver" -version = "0.5.0" +version = "0.5.1" dependencies = [ "tempfile", "zokrates_common", @@ -1863,7 +1863,7 @@ dependencies = [ [[package]] name = "zokrates_test" -version = "0.1.2" +version = "0.1.3" dependencies = [ "fs_extra", "glob 0.3.0", diff --git a/zokrates_core/src/absy/from_ast.rs b/zokrates_core/src/absy/from_ast.rs index 1e3aa6355..f553be06f 100644 --- a/zokrates_core/src/absy/from_ast.rs +++ b/zokrates_core/src/absy/from_ast.rs @@ -1,10 +1,12 @@ use absy; use imports; -use zokrates_field::Field; + +use num::ToPrimitive; +use num_bigint::BigUint; use zokrates_pest_ast as pest; -impl<'ast, T: Field> From> for absy::Module<'ast, T> { - fn from(prog: pest::File<'ast>) -> absy::Module { +impl<'ast> From> for absy::Module<'ast> { + fn from(prog: pest::File<'ast>) -> absy::Module<'ast> { absy::Module::with_symbols( prog.structs .into_iter() @@ -20,7 +22,7 @@ impl<'ast, T: Field> From> for absy::Module<'ast, T> { } impl<'ast> From> for absy::ImportNode<'ast> { - fn from(import: pest::ImportDirective<'ast>) -> absy::ImportNode { + fn from(import: pest::ImportDirective<'ast>) -> absy::ImportNode<'ast> { use absy::NodeValue; match import { @@ -44,8 +46,8 @@ impl<'ast> From> for absy::ImportNode<'ast> { } } -impl<'ast, T: Field> From> for absy::SymbolDeclarationNode<'ast, T> { - fn from(definition: pest::StructDefinition<'ast>) -> absy::SymbolDeclarationNode<'ast, T> { +impl<'ast> From> for absy::SymbolDeclarationNode<'ast> { + fn from(definition: pest::StructDefinition<'ast>) -> absy::SymbolDeclarationNode<'ast> { use absy::NodeValue; let span = definition.span; @@ -83,8 +85,8 @@ impl<'ast> From> for absy::StructDefinitionFieldNode<'as } } -impl<'ast, T: Field> From> for absy::SymbolDeclarationNode<'ast, T> { - fn from(function: pest::Function<'ast>) -> absy::SymbolDeclarationNode { +impl<'ast> From> for absy::SymbolDeclarationNode<'ast> { + fn from(function: pest::Function<'ast>) -> absy::SymbolDeclarationNode<'ast> { use absy::NodeValue; let span = function.span; @@ -109,7 +111,7 @@ impl<'ast, T: Field> From> for absy::SymbolDeclarationNode< let id = function.id.span.as_str(); - let function = absy::Function:: { + let function = absy::Function { arguments: function .parameters .into_iter() @@ -133,7 +135,7 @@ impl<'ast, T: Field> From> for absy::SymbolDeclarationNode< } impl<'ast> From> for absy::ParameterNode<'ast> { - fn from(param: pest::Parameter<'ast>) -> absy::ParameterNode { + fn from(param: pest::Parameter<'ast>) -> absy::ParameterNode<'ast> { use absy::NodeValue; let private = param @@ -154,9 +156,7 @@ impl<'ast> From> for absy::ParameterNode<'ast> { } } -fn statements_from_statement<'ast, T: Field>( - statement: pest::Statement<'ast>, -) -> Vec> { +fn statements_from_statement(statement: pest::Statement) -> Vec { match statement { pest::Statement::Definition(s) => statements_from_definition(s), pest::Statement::Iteration(s) => vec![absy::StatementNode::from(s)], @@ -165,9 +165,7 @@ fn statements_from_statement<'ast, T: Field>( } } -fn statements_from_definition<'ast, T: Field>( - definition: pest::DefinitionStatement<'ast>, -) -> Vec> { +fn statements_from_definition(definition: pest::DefinitionStatement) -> Vec { use absy::NodeValue; let lhs = definition.lhs; @@ -177,7 +175,7 @@ fn statements_from_definition<'ast, T: Field>( // Definition or assignment let a = lhs[0].clone(); - let e: absy::ExpressionNode = absy::ExpressionNode::from(definition.expression); + let e: absy::ExpressionNode = absy::ExpressionNode::from(definition.expression); let s = match e.value { absy::Expression::FunctionCall(..) => absy::Statement::MultipleDefinition( @@ -240,8 +238,8 @@ fn statements_from_definition<'ast, T: Field>( } } -impl<'ast, T: Field> From> for absy::StatementNode<'ast, T> { - fn from(statement: pest::ReturnStatement<'ast>) -> absy::StatementNode { +impl<'ast> From> for absy::StatementNode<'ast> { + fn from(statement: pest::ReturnStatement<'ast>) -> absy::StatementNode<'ast> { use absy::NodeValue; absy::Statement::Return( @@ -258,8 +256,8 @@ impl<'ast, T: Field> From> for absy::StatementNode<' } } -impl<'ast, T: Field> From> for absy::StatementNode<'ast, T> { - fn from(statement: pest::AssertionStatement<'ast>) -> absy::StatementNode { +impl<'ast> From> for absy::StatementNode<'ast> { + fn from(statement: pest::AssertionStatement<'ast>) -> absy::StatementNode<'ast> { use absy::NodeValue; absy::Statement::Assertion(absy::ExpressionNode::from(statement.expression)) @@ -267,14 +265,14 @@ impl<'ast, T: Field> From> for absy::StatementNod } } -impl<'ast, T: Field> From> for absy::StatementNode<'ast, T> { - fn from(statement: pest::IterationStatement<'ast>) -> absy::StatementNode { +impl<'ast> From> for absy::StatementNode<'ast> { + fn from(statement: pest::IterationStatement<'ast>) -> absy::StatementNode<'ast> { use absy::NodeValue; let from = absy::ExpressionNode::from(statement.from); let to = absy::ExpressionNode::from(statement.to); let index = statement.index.span.as_str(); let ty = absy::UnresolvedTypeNode::from(statement.ty); - let statements: Vec> = statement + let statements: Vec> = statement .statements .into_iter() .flat_map(|s| statements_from_statement(s)) @@ -286,8 +284,8 @@ impl<'ast, T: Field> From> for absy::StatementNod } } -impl<'ast, T: Field> From> for absy::ExpressionNode<'ast, T> { - fn from(expression: pest::Expression<'ast>) -> absy::ExpressionNode<'ast, T> { +impl<'ast> From> for absy::ExpressionNode<'ast> { + fn from(expression: pest::Expression<'ast>) -> absy::ExpressionNode<'ast> { match expression { pest::Expression::Binary(e) => absy::ExpressionNode::from(e), pest::Expression::Ternary(e) => absy::ExpressionNode::from(e), @@ -302,8 +300,8 @@ impl<'ast, T: Field> From> for absy::ExpressionNode<'ast, } } -impl<'ast, T: Field> From> for absy::ExpressionNode<'ast, T> { - fn from(expression: pest::BinaryExpression<'ast>) -> absy::ExpressionNode<'ast, T> { +impl<'ast> From> for absy::ExpressionNode<'ast> { + fn from(expression: pest::BinaryExpression<'ast>) -> absy::ExpressionNode<'ast> { use absy::NodeValue; match expression.op { pest::BinaryOperator::Add => absy::Expression::Add( @@ -387,8 +385,8 @@ impl<'ast, T: Field> From> for absy::ExpressionNode } } -impl<'ast, T: Field> From> for absy::ExpressionNode<'ast, T> { - fn from(expression: pest::TernaryExpression<'ast>) -> absy::ExpressionNode<'ast, T> { +impl<'ast> From> for absy::ExpressionNode<'ast> { + fn from(expression: pest::TernaryExpression<'ast>) -> absy::ExpressionNode<'ast> { use absy::NodeValue; absy::Expression::IfElse( box absy::ExpressionNode::from(*expression.first), @@ -399,8 +397,8 @@ impl<'ast, T: Field> From> for absy::ExpressionNod } } -impl<'ast, T: Field> From> for absy::SpreadNode<'ast, T> { - fn from(spread: pest::Spread<'ast>) -> absy::SpreadNode<'ast, T> { +impl<'ast> From> for absy::SpreadNode<'ast> { + fn from(spread: pest::Spread<'ast>) -> absy::SpreadNode<'ast> { use absy::NodeValue; absy::Spread { expression: absy::ExpressionNode::from(spread.expression), @@ -409,8 +407,8 @@ impl<'ast, T: Field> From> for absy::SpreadNode<'ast, T> { } } -impl<'ast, T: Field> From> for absy::RangeNode<'ast, T> { - fn from(range: pest::Range<'ast>) -> absy::RangeNode<'ast, T> { +impl<'ast> From> for absy::RangeNode<'ast> { + fn from(range: pest::Range<'ast>) -> absy::RangeNode<'ast> { use absy::NodeValue; let from = range.from.map(|e| absy::ExpressionNode::from(e.0)); @@ -421,10 +419,8 @@ impl<'ast, T: Field> From> for absy::RangeNode<'ast, T> { } } -impl<'ast, T: Field> From> for absy::RangeOrExpression<'ast, T> { - fn from( - range_or_expression: pest::RangeOrExpression<'ast>, - ) -> absy::RangeOrExpression<'ast, T> { +impl<'ast> From> for absy::RangeOrExpression<'ast> { + fn from(range_or_expression: pest::RangeOrExpression<'ast>) -> absy::RangeOrExpression<'ast> { match range_or_expression { pest::RangeOrExpression::Expression(e) => { absy::RangeOrExpression::Expression(absy::ExpressionNode::from(e)) @@ -436,10 +432,10 @@ impl<'ast, T: Field> From> for absy::RangeOrExpres } } -impl<'ast, T: Field> From> for absy::SpreadOrExpression<'ast, T> { +impl<'ast> From> for absy::SpreadOrExpression<'ast> { fn from( spread_or_expression: pest::SpreadOrExpression<'ast>, - ) -> absy::SpreadOrExpression<'ast, T> { + ) -> absy::SpreadOrExpression<'ast> { match spread_or_expression { pest::SpreadOrExpression::Expression(e) => { absy::SpreadOrExpression::Expression(absy::ExpressionNode::from(e)) @@ -451,8 +447,8 @@ impl<'ast, T: Field> From> for absy::SpreadOrExpr } } -impl<'ast, T: Field> From> for absy::ExpressionNode<'ast, T> { - fn from(array: pest::InlineArrayExpression<'ast>) -> absy::ExpressionNode<'ast, T> { +impl<'ast> From> for absy::ExpressionNode<'ast> { + fn from(array: pest::InlineArrayExpression<'ast>) -> absy::ExpressionNode<'ast> { use absy::NodeValue; absy::Expression::InlineArray( array @@ -465,8 +461,8 @@ impl<'ast, T: Field> From> for absy::Expressio } } -impl<'ast, T: Field> From> for absy::ExpressionNode<'ast, T> { - fn from(s: pest::InlineStructExpression<'ast>) -> absy::ExpressionNode<'ast, T> { +impl<'ast> From> for absy::ExpressionNode<'ast> { + fn from(s: pest::InlineStructExpression<'ast>) -> absy::ExpressionNode<'ast> { use absy::NodeValue; absy::Expression::InlineStruct( s.ty.span.as_str().to_string(), @@ -484,16 +480,14 @@ impl<'ast, T: Field> From> for absy::Expressi } } -impl<'ast, T: Field> From> - for absy::ExpressionNode<'ast, T> -{ - fn from(initializer: pest::ArrayInitializerExpression<'ast>) -> absy::ExpressionNode<'ast, T> { +impl<'ast> From> for absy::ExpressionNode<'ast> { + fn from(initializer: pest::ArrayInitializerExpression<'ast>) -> absy::ExpressionNode<'ast> { use absy::NodeValue; let value = absy::ExpressionNode::from(*initializer.value); - let count: absy::ExpressionNode = absy::ExpressionNode::from(initializer.count); + let count: absy::ExpressionNode<'ast> = absy::ExpressionNode::from(initializer.count); let count = match count.value { - absy::Expression::FieldConstant(v) => v.to_dec_string().parse::().unwrap(), + absy::Expression::FieldConstant(v) => v.to_usize().unwrap(), _ => unreachable!(), }; absy::Expression::InlineArray(vec![absy::SpreadOrExpression::Expression(value); count]) @@ -501,8 +495,8 @@ impl<'ast, T: Field> From> } } -impl<'ast, T: Field> From> for absy::ExpressionNode<'ast, T> { - fn from(unary: pest::UnaryExpression<'ast>) -> absy::ExpressionNode<'ast, T> { +impl<'ast> From> for absy::ExpressionNode<'ast> { + fn from(unary: pest::UnaryExpression<'ast>) -> absy::ExpressionNode<'ast> { use absy::NodeValue; match unary.op { @@ -514,8 +508,8 @@ impl<'ast, T: Field> From> for absy::ExpressionNode< } } -impl<'ast, T: Field> From> for absy::ExpressionNode<'ast, T> { - fn from(expression: pest::PostfixExpression<'ast>) -> absy::ExpressionNode<'ast, T> { +impl<'ast> From> for absy::ExpressionNode<'ast> { + fn from(expression: pest::PostfixExpression<'ast>) -> absy::ExpressionNode<'ast> { use absy::NodeValue; let id_str = expression.id.span.as_str(); @@ -548,16 +542,17 @@ impl<'ast, T: Field> From> for absy::ExpressionNod } } -impl<'ast, T: Field> From> for absy::ExpressionNode<'ast, T> { - fn from(expression: pest::ConstantExpression<'ast>) -> absy::ExpressionNode<'ast, T> { +impl<'ast> From> for absy::ExpressionNode<'ast> { + fn from(expression: pest::ConstantExpression<'ast>) -> absy::ExpressionNode<'ast> { use absy::NodeValue; match expression { pest::ConstantExpression::BooleanLiteral(c) => { absy::Expression::BooleanConstant(c.value.parse().unwrap()).span(c.span) } - pest::ConstantExpression::DecimalNumber(n) => { - absy::Expression::FieldConstant(T::try_from_dec_str(&n.value).unwrap()).span(n.span) - } + pest::ConstantExpression::DecimalNumber(n) => absy::Expression::FieldConstant( + BigUint::parse_bytes(&n.value.as_bytes(), 10).unwrap(), + ) + .span(n.span), pest::ConstantExpression::U8(n) => absy::Expression::U8Constant( u8::from_str_radix(&n.value.trim_start_matches("0x"), 16).unwrap(), ) @@ -574,23 +569,23 @@ impl<'ast, T: Field> From> for absy::ExpressionNo } } -impl<'ast, T: Field> From> for absy::ExpressionNode<'ast, T> { - fn from(expression: pest::IdentifierExpression<'ast>) -> absy::ExpressionNode<'ast, T> { +impl<'ast> From> for absy::ExpressionNode<'ast> { + fn from(expression: pest::IdentifierExpression<'ast>) -> absy::ExpressionNode<'ast> { use absy::NodeValue; absy::Expression::Identifier(expression.span.as_str()).span(expression.span) } } -impl<'ast, T: Field> From> for absy::AssigneeNode<'ast, T> { - fn from(expression: pest::IdentifierExpression<'ast>) -> absy::AssigneeNode { +impl<'ast> From> for absy::AssigneeNode<'ast> { + fn from(expression: pest::IdentifierExpression<'ast>) -> absy::AssigneeNode<'ast> { use absy::NodeValue; absy::Assignee::Identifier(expression.span.as_str()).span(expression.span) } } -impl<'ast, T: Field> From> for absy::AssigneeNode<'ast, T> { - fn from(assignee: pest::Assignee<'ast>) -> absy::AssigneeNode { +impl<'ast> From> for absy::AssigneeNode<'ast> { + fn from(assignee: pest::Assignee<'ast>) -> absy::AssigneeNode<'ast> { use absy::NodeValue; let a = absy::AssigneeNode::from(assignee.id); @@ -612,29 +607,28 @@ impl<'ast, T: Field> From> for absy::AssigneeNode<'ast, T> impl<'ast> From> for absy::UnresolvedTypeNode { fn from(t: pest::Type<'ast>) -> absy::UnresolvedTypeNode { + use absy::types::UnresolvedType; use absy::NodeValue; match t { pest::Type::Basic(t) => match t { - pest::BasicType::Field(t) => absy::UnresolvedType::FieldElement.span(t.span), - pest::BasicType::Boolean(t) => absy::UnresolvedType::Boolean.span(t.span), - pest::BasicType::U8(t) => absy::UnresolvedType::Uint(8).span(t.span), - pest::BasicType::U16(t) => absy::UnresolvedType::Uint(16).span(t.span), - pest::BasicType::U32(t) => absy::UnresolvedType::Uint(32).span(t.span), + pest::BasicType::Field(t) => UnresolvedType::FieldElement.span(t.span), + pest::BasicType::Boolean(t) => UnresolvedType::Boolean.span(t.span), + pest::BasicType::U8(t) => UnresolvedType::Uint(8).span(t.span), + pest::BasicType::U16(t) => UnresolvedType::Uint(16).span(t.span), + pest::BasicType::U32(t) => UnresolvedType::Uint(32).span(t.span), }, pest::Type::Array(t) => { let inner_type = match t.ty { pest::BasicOrStructType::Basic(t) => match t { - pest::BasicType::Field(t) => { - absy::UnresolvedType::FieldElement.span(t.span) - } - pest::BasicType::Boolean(t) => absy::UnresolvedType::Boolean.span(t.span), - pest::BasicType::U8(t) => absy::UnresolvedType::Uint(8).span(t.span), - pest::BasicType::U16(t) => absy::UnresolvedType::Uint(16).span(t.span), - pest::BasicType::U32(t) => absy::UnresolvedType::Uint(32).span(t.span), + pest::BasicType::Field(t) => UnresolvedType::FieldElement.span(t.span), + pest::BasicType::Boolean(t) => UnresolvedType::Boolean.span(t.span), + pest::BasicType::U8(t) => UnresolvedType::Uint(8).span(t.span), + pest::BasicType::U16(t) => UnresolvedType::Uint(16).span(t.span), + pest::BasicType::U32(t) => UnresolvedType::Uint(32).span(t.span), }, pest::BasicOrStructType::Struct(t) => { - absy::UnresolvedType::User(t.span.as_str().to_string()).span(t.span) + UnresolvedType::User(t.span.as_str().to_string()).span(t.span) } }; @@ -659,14 +653,14 @@ impl<'ast> From> for absy::UnresolvedTypeNode { }) .rev() .fold(None, |acc, s| match acc { - None => Some(absy::UnresolvedType::array(inner_type.clone(), s)), - Some(acc) => Some(absy::UnresolvedType::array(acc.span(span.clone()), s)), + None => Some(UnresolvedType::array(inner_type.clone(), s)), + Some(acc) => Some(UnresolvedType::array(acc.span(span.clone()), s)), }) .unwrap() .span(span.clone()) } pest::Type::Struct(s) => { - absy::UnresolvedType::User(s.id.span.as_str().to_string()).span(s.span) + UnresolvedType::User(s.id.span.as_str().to_string()).span(s.span) } } } @@ -675,14 +669,14 @@ impl<'ast> From> for absy::UnresolvedTypeNode { #[cfg(test)] mod tests { use super::*; + use absy::types::{UnresolvedSignature, UnresolvedType}; use absy::NodeValue; - use zokrates_field::Bn128Field; #[test] fn return_forty_two() { let source = "def main() -> field: return 42"; let ast = pest::generate_ast(&source).unwrap(); - let expected: absy::Module = absy::Module { + let expected: absy::Module = absy::Module { symbols: vec![absy::SymbolDeclaration { id: &source[4..8], symbol: absy::Symbol::HereFunction( @@ -690,17 +684,17 @@ mod tests { arguments: vec![], statements: vec![absy::Statement::Return( absy::ExpressionList { - expressions: vec![absy::Expression::FieldConstant( - Bn128Field::from(42), - ) + expressions: vec![absy::Expression::FieldConstant(BigUint::from( + 42u32, + )) .into()], } .into(), ) .into()], - signature: absy::UnresolvedSignature::new() + signature: UnresolvedSignature::new() .inputs(vec![]) - .outputs(vec![absy::UnresolvedType::FieldElement.mock()]), + .outputs(vec![UnresolvedType::FieldElement.mock()]), } .into(), ), @@ -708,14 +702,14 @@ mod tests { .into()], imports: vec![], }; - assert_eq!(absy::Module::::from(ast), expected); + assert_eq!(absy::Module::from(ast), expected); } #[test] fn return_true() { let source = "def main() -> bool: return true"; let ast = pest::generate_ast(&source).unwrap(); - let expected: absy::Module = absy::Module { + let expected: absy::Module = absy::Module { symbols: vec![absy::SymbolDeclaration { id: &source[4..8], symbol: absy::Symbol::HereFunction( @@ -728,9 +722,9 @@ mod tests { .into(), ) .into()], - signature: absy::UnresolvedSignature::new() + signature: UnresolvedSignature::new() .inputs(vec![]) - .outputs(vec![absy::UnresolvedType::Boolean.mock()]), + .outputs(vec![UnresolvedType::Boolean.mock()]), } .into(), ), @@ -738,7 +732,7 @@ mod tests { .into()], imports: vec![], }; - assert_eq!(absy::Module::::from(ast), expected); + assert_eq!(absy::Module::from(ast), expected); } #[test] @@ -746,7 +740,7 @@ mod tests { let source = "def main(private field a, bool b) -> field: return 42"; let ast = pest::generate_ast(&source).unwrap(); - let expected: absy::Module = absy::Module { + let expected: absy::Module = absy::Module { symbols: vec![absy::SymbolDeclaration { id: &source[4..8], symbol: absy::Symbol::HereFunction( @@ -755,7 +749,7 @@ mod tests { absy::Parameter::private( absy::Variable::new( &source[23..24], - absy::UnresolvedType::FieldElement.mock(), + UnresolvedType::FieldElement.mock(), ) .into(), ) @@ -763,7 +757,7 @@ mod tests { absy::Parameter::public( absy::Variable::new( &source[31..32], - absy::UnresolvedType::Boolean.mock(), + UnresolvedType::Boolean.mock(), ) .into(), ) @@ -771,20 +765,20 @@ mod tests { ], statements: vec![absy::Statement::Return( absy::ExpressionList { - expressions: vec![absy::Expression::FieldConstant( - Bn128Field::from(42), - ) + expressions: vec![absy::Expression::FieldConstant(BigUint::from( + 42u32, + )) .into()], } .into(), ) .into()], - signature: absy::UnresolvedSignature::new() + signature: UnresolvedSignature::new() .inputs(vec![ - absy::UnresolvedType::FieldElement.mock(), - absy::UnresolvedType::Boolean.mock(), + UnresolvedType::FieldElement.mock(), + UnresolvedType::Boolean.mock(), ]) - .outputs(vec![absy::UnresolvedType::FieldElement.mock()]), + .outputs(vec![UnresolvedType::FieldElement.mock()]), } .into(), ), @@ -793,14 +787,14 @@ mod tests { imports: vec![], }; - assert_eq!(absy::Module::::from(ast), expected); + assert_eq!(absy::Module::from(ast), expected); } mod types { use super::*; /// Helper method to generate the ast for `def main(private {ty} a): return` which we use to check ty - fn wrap(ty: absy::UnresolvedType) -> absy::Module<'static, Bn128Field> { + fn wrap(ty: UnresolvedType) -> absy::Module<'static> { absy::Module { symbols: vec![absy::SymbolDeclaration { id: "main", @@ -817,7 +811,7 @@ mod tests { .into(), ) .into()], - signature: absy::UnresolvedSignature::new().inputs(vec![ty.mock()]), + signature: UnresolvedSignature::new().inputs(vec![ty.mock()]), } .into(), ), @@ -830,31 +824,24 @@ mod tests { #[test] fn array() { let vectors = vec![ - ("field", absy::UnresolvedType::FieldElement), - ("bool", absy::UnresolvedType::Boolean), + ("field", UnresolvedType::FieldElement), + ("bool", UnresolvedType::Boolean), ( "field[2]", - absy::UnresolvedType::Array(box absy::UnresolvedType::FieldElement.mock(), 2), + UnresolvedType::Array(box UnresolvedType::FieldElement.mock(), 2), ), ( "field[2][3]", - absy::UnresolvedType::Array( - box absy::UnresolvedType::Array( - box absy::UnresolvedType::FieldElement.mock(), - 3, - ) - .mock(), + UnresolvedType::Array( + box UnresolvedType::Array(box UnresolvedType::FieldElement.mock(), 3) + .mock(), 2, ), ), ( "bool[2][3]", - absy::UnresolvedType::Array( - box absy::UnresolvedType::Array( - box absy::UnresolvedType::Boolean.mock(), - 3, - ) - .mock(), + UnresolvedType::Array( + box UnresolvedType::Array(box UnresolvedType::Boolean.mock(), 3).mock(), 2, ), ), @@ -864,14 +851,14 @@ mod tests { let source = format!("def main(private {} a): return", ty); let expected = wrap(expected); let ast = pest::generate_ast(&source).unwrap(); - assert_eq!(absy::Module::::from(ast), expected); + assert_eq!(absy::Module::from(ast), expected); } } } mod postfix { use super::*; - fn wrap(expression: absy::Expression<'static, Bn128Field>) -> absy::Module { + fn wrap(expression: absy::Expression<'static>) -> absy::Module { absy::Module { symbols: vec![absy::SymbolDeclaration { id: "main", @@ -885,7 +872,7 @@ mod tests { .into(), ) .into()], - signature: absy::UnresolvedSignature::new(), + signature: UnresolvedSignature::new(), } .into(), ), @@ -906,7 +893,7 @@ mod tests { absy::Expression::Select( box absy::Expression::Identifier("a").into(), box absy::RangeOrExpression::Expression( - absy::Expression::FieldConstant(Bn128Field::from(3)).into(), + absy::Expression::FieldConstant(BigUint::from(3u32)).into(), ) .into(), ), @@ -917,13 +904,13 @@ mod tests { box absy::Expression::Select( box absy::Expression::Identifier("a").into(), box absy::RangeOrExpression::Expression( - absy::Expression::FieldConstant(Bn128Field::from(3)).into(), + absy::Expression::FieldConstant(BigUint::from(3u32)).into(), ) .into(), ) .into(), box absy::RangeOrExpression::Expression( - absy::Expression::FieldConstant(Bn128Field::from(4)).into(), + absy::Expression::FieldConstant(BigUint::from(4u32)).into(), ) .into(), ), @@ -933,11 +920,11 @@ mod tests { absy::Expression::Select( box absy::Expression::FunctionCall( "a", - vec![absy::Expression::FieldConstant(Bn128Field::from(3)).into()], + vec![absy::Expression::FieldConstant(BigUint::from(3u32)).into()], ) .into(), box absy::RangeOrExpression::Expression( - absy::Expression::FieldConstant(Bn128Field::from(4)).into(), + absy::Expression::FieldConstant(BigUint::from(4u32)).into(), ) .into(), ), @@ -948,17 +935,17 @@ mod tests { box absy::Expression::Select( box absy::Expression::FunctionCall( "a", - vec![absy::Expression::FieldConstant(Bn128Field::from(3)).into()], + vec![absy::Expression::FieldConstant(BigUint::from(3u32)).into()], ) .into(), box absy::RangeOrExpression::Expression( - absy::Expression::FieldConstant(Bn128Field::from(4)).into(), + absy::Expression::FieldConstant(BigUint::from(4u32)).into(), ) .into(), ) .into(), box absy::RangeOrExpression::Expression( - absy::Expression::FieldConstant(Bn128Field::from(5)).into(), + absy::Expression::FieldConstant(BigUint::from(5u32)).into(), ) .into(), ), @@ -969,7 +956,7 @@ mod tests { let source = format!("def main(): return {}", source); let expected = wrap(expected); let ast = pest::generate_ast(&source).unwrap(); - assert_eq!(absy::Module::::from(ast), expected); + assert_eq!(absy::Module::from(ast), expected); } } @@ -979,7 +966,7 @@ mod tests { // a call after an array access should be rejected let source = "def main(): return a[2](3)"; let ast = pest::generate_ast(&source).unwrap(); - absy::Module::::from(ast); + absy::Module::from(ast); } #[test] @@ -988,7 +975,7 @@ mod tests { // a call after a call should be rejected let source = "def main(): return a(2)(3)"; let ast = pest::generate_ast(&source).unwrap(); - absy::Module::::from(ast); + absy::Module::from(ast); } } #[test] @@ -1024,8 +1011,7 @@ mod tests { span: span.clone(), }; - let statements: Vec> = - statements_from_definition(definition); + let statements: Vec = statements_from_definition(definition); assert_eq!(statements.len(), 1); match &statements[0].value { @@ -1065,8 +1051,7 @@ mod tests { span: span.clone(), }; - let statements: Vec> = - statements_from_definition(definition); + let statements: Vec = statements_from_definition(definition); assert_eq!(statements.len(), 1); match &statements[0].value { @@ -1123,8 +1108,7 @@ mod tests { span: span.clone(), }; - let statements: Vec> = - statements_from_definition(definition); + let statements: Vec = statements_from_definition(definition); assert_eq!(statements.len(), 2); match &statements[1].value { diff --git a/zokrates_core/src/absy/mod.rs b/zokrates_core/src/absy/mod.rs index bb2d7d095..f416f2311 100644 --- a/zokrates_core/src/absy/mod.rs +++ b/zokrates_core/src/absy/mod.rs @@ -20,8 +20,8 @@ use std::path::PathBuf; use crate::imports::ImportNode; use std::fmt; -use zokrates_field::Field; +use num_bigint::BigUint; use std::collections::HashMap; /// An identifier of a function or a variable @@ -31,33 +31,33 @@ pub type Identifier<'ast> = &'ast str; pub type ModuleId = PathBuf; /// A collection of `Module`s -pub type Modules<'ast, T> = HashMap>; +pub type Modules<'ast> = HashMap>; /// A collection of `SymbolDeclaration`. Duplicates are allowed here as they are fine syntactically. -pub type Declarations<'ast, T> = Vec>; +pub type Declarations<'ast> = Vec>; /// A `Program` is a collection of `Module`s and an id of the main `Module` -pub struct Program<'ast, T> { - pub modules: HashMap>, +pub struct Program<'ast> { + pub modules: HashMap>, pub main: ModuleId, } /// A declaration of a `FunctionSymbol`, be it from an import or a function definition #[derive(PartialEq, Clone, Debug)] -pub struct SymbolDeclaration<'ast, T> { +pub struct SymbolDeclaration<'ast> { pub id: Identifier<'ast>, - pub symbol: Symbol<'ast, T>, + pub symbol: Symbol<'ast>, } #[derive(PartialEq, Clone)] -pub enum Symbol<'ast, T> { +pub enum Symbol<'ast> { HereType(StructDefinitionNode<'ast>), - HereFunction(FunctionNode<'ast, T>), + HereFunction(FunctionNode<'ast>), There(SymbolImportNode<'ast>), Flat(FlatEmbed), } -impl<'ast, T: fmt::Debug> fmt::Debug for Symbol<'ast, T> { +impl<'ast> fmt::Debug for Symbol<'ast> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Symbol::HereType(t) => write!(f, "HereType({:?})", t), @@ -68,7 +68,7 @@ impl<'ast, T: fmt::Debug> fmt::Debug for Symbol<'ast, T> { } } -impl<'ast, T: fmt::Display> fmt::Display for SymbolDeclaration<'ast, T> { +impl<'ast> fmt::Display for SymbolDeclaration<'ast> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.symbol { Symbol::HereType(ref t) => write!(f, "struct {} {}", self.id, t), @@ -81,18 +81,18 @@ impl<'ast, T: fmt::Display> fmt::Display for SymbolDeclaration<'ast, T> { } } -pub type SymbolDeclarationNode<'ast, T> = Node>; +pub type SymbolDeclarationNode<'ast> = Node>; /// A module as a collection of `FunctionDeclaration`s #[derive(Clone, PartialEq)] -pub struct Module<'ast, T> { +pub struct Module<'ast> { /// Symbols of the module - pub symbols: Declarations<'ast, T>, + pub symbols: Declarations<'ast>, pub imports: Vec>, // we still use `imports` as they are not directly converted into `FunctionDeclaration`s after the importer is done, `imports` is empty } -impl<'ast, T: Field> Module<'ast, T> { - pub fn with_symbols>>(i: I) -> Self { +impl<'ast> Module<'ast> { + pub fn with_symbols>>(i: I) -> Self { Module { symbols: i.into_iter().collect(), imports: vec![], @@ -178,7 +178,7 @@ impl<'ast> fmt::Display for SymbolImport<'ast> { } } -impl<'ast, T: Field> fmt::Display for Module<'ast, T> { +impl<'ast> fmt::Display for Module<'ast> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut res = vec![]; res.extend( @@ -197,7 +197,7 @@ impl<'ast, T: Field> fmt::Display for Module<'ast, T> { } } -impl<'ast, T: fmt::Debug> fmt::Debug for Module<'ast, T> { +impl<'ast> fmt::Debug for Module<'ast> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, @@ -218,18 +218,18 @@ impl<'ast, T: fmt::Debug> fmt::Debug for Module<'ast, T> { /// A function defined locally #[derive(Clone, PartialEq)] -pub struct Function<'ast, T> { +pub struct Function<'ast> { /// Arguments of the function pub arguments: Vec>, /// Vector of statements that are executed when running the function - pub statements: Vec>, + pub statements: Vec>, /// function signature pub signature: UnresolvedSignature, } -pub type FunctionNode<'ast, T> = Node>; +pub type FunctionNode<'ast> = Node>; -impl<'ast, T: fmt::Display> fmt::Display for Function<'ast, T> { +impl<'ast> fmt::Display for Function<'ast> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, @@ -248,7 +248,7 @@ impl<'ast, T: fmt::Display> fmt::Display for Function<'ast, T> { } } -impl<'ast, T: fmt::Debug> fmt::Debug for Function<'ast, T> { +impl<'ast> fmt::Debug for Function<'ast> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, @@ -265,15 +265,15 @@ impl<'ast, T: fmt::Debug> fmt::Debug for Function<'ast, T> { /// Something that we can assign to #[derive(Clone, PartialEq)] -pub enum Assignee<'ast, T> { +pub enum Assignee<'ast> { Identifier(Identifier<'ast>), - Select(Box>, Box>), - Member(Box>, Box>), + Select(Box>, Box>), + Member(Box>, Box>), } -pub type AssigneeNode<'ast, T> = Node>; +pub type AssigneeNode<'ast> = Node>; -impl<'ast, T: fmt::Debug> fmt::Debug for Assignee<'ast, T> { +impl<'ast> fmt::Debug for Assignee<'ast> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Assignee::Identifier(ref s) => write!(f, "Identifier({:?})", s), @@ -283,7 +283,7 @@ impl<'ast, T: fmt::Debug> fmt::Debug for Assignee<'ast, T> { } } -impl<'ast, T: fmt::Display> fmt::Display for Assignee<'ast, T> { +impl<'ast> fmt::Display for Assignee<'ast> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Assignee::Identifier(ref s) => write!(f, "{}", s), @@ -295,23 +295,23 @@ impl<'ast, T: fmt::Display> fmt::Display for Assignee<'ast, T> { /// A statement in a `Function` #[derive(Clone, PartialEq)] -pub enum Statement<'ast, T> { - Return(ExpressionListNode<'ast, T>), +pub enum Statement<'ast> { + Return(ExpressionListNode<'ast>), Declaration(VariableNode<'ast>), - Definition(AssigneeNode<'ast, T>, ExpressionNode<'ast, T>), - Assertion(ExpressionNode<'ast, T>), + Definition(AssigneeNode<'ast>, ExpressionNode<'ast>), + Assertion(ExpressionNode<'ast>), For( VariableNode<'ast>, - ExpressionNode<'ast, T>, - ExpressionNode<'ast, T>, - Vec>, + ExpressionNode<'ast>, + ExpressionNode<'ast>, + Vec>, ), - MultipleDefinition(Vec>, ExpressionNode<'ast, T>), + MultipleDefinition(Vec>, ExpressionNode<'ast>), } -pub type StatementNode<'ast, T> = Node>; +pub type StatementNode<'ast> = Node>; -impl<'ast, T: fmt::Display> fmt::Display for Statement<'ast, T> { +impl<'ast> fmt::Display for Statement<'ast> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Statement::Return(ref expr) => write!(f, "return {}", expr), @@ -338,7 +338,7 @@ impl<'ast, T: fmt::Display> fmt::Display for Statement<'ast, T> { } } -impl<'ast, T: fmt::Debug> fmt::Debug for Statement<'ast, T> { +impl<'ast> fmt::Debug for Statement<'ast> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Statement::Return(ref expr) => write!(f, "Return({:?})", expr), @@ -363,18 +363,18 @@ impl<'ast, T: fmt::Debug> fmt::Debug for Statement<'ast, T> { /// An element of an inline array, can be a spread `...a` or an expression `a` #[derive(Clone, PartialEq)] -pub enum SpreadOrExpression<'ast, T> { - Spread(SpreadNode<'ast, T>), - Expression(ExpressionNode<'ast, T>), +pub enum SpreadOrExpression<'ast> { + Spread(SpreadNode<'ast>), + Expression(ExpressionNode<'ast>), } -impl<'ast, T: Field> From> for SpreadOrExpression<'ast, T> { - fn from(e: ExpressionNode<'ast, T>) -> SpreadOrExpression<'ast, T> { +impl<'ast> From> for SpreadOrExpression<'ast> { + fn from(e: ExpressionNode<'ast>) -> SpreadOrExpression<'ast> { SpreadOrExpression::Expression(e) } } -impl<'ast, T: fmt::Display> fmt::Display for SpreadOrExpression<'ast, T> { +impl<'ast> fmt::Display for SpreadOrExpression<'ast> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { SpreadOrExpression::Spread(ref s) => write!(f, "{}", s), @@ -383,7 +383,7 @@ impl<'ast, T: fmt::Display> fmt::Display for SpreadOrExpression<'ast, T> { } } -impl<'ast, T: fmt::Debug> fmt::Debug for SpreadOrExpression<'ast, T> { +impl<'ast> fmt::Debug for SpreadOrExpression<'ast> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { SpreadOrExpression::Spread(ref s) => write!(f, "{:?}", s), @@ -394,12 +394,12 @@ impl<'ast, T: fmt::Debug> fmt::Debug for SpreadOrExpression<'ast, T> { /// The index in an array selector. Can be a range or an expression. #[derive(Clone, PartialEq)] -pub enum RangeOrExpression<'ast, T> { - Range(RangeNode<'ast, T>), - Expression(ExpressionNode<'ast, T>), +pub enum RangeOrExpression<'ast> { + Range(RangeNode<'ast>), + Expression(ExpressionNode<'ast>), } -impl<'ast, T: fmt::Display> fmt::Display for RangeOrExpression<'ast, T> { +impl<'ast> fmt::Display for RangeOrExpression<'ast> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { RangeOrExpression::Range(ref s) => write!(f, "{}", s), @@ -408,7 +408,7 @@ impl<'ast, T: fmt::Display> fmt::Display for RangeOrExpression<'ast, T> { } } -impl<'ast, T: fmt::Debug> fmt::Debug for RangeOrExpression<'ast, T> { +impl<'ast> fmt::Debug for RangeOrExpression<'ast> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { RangeOrExpression::Range(ref s) => write!(f, "{:?}", s), @@ -417,15 +417,15 @@ impl<'ast, T: fmt::Debug> fmt::Debug for RangeOrExpression<'ast, T> { } } -pub type SpreadNode<'ast, T> = Node>; +pub type SpreadNode<'ast> = Node>; -impl<'ast, T: fmt::Display> fmt::Display for Spread<'ast, T> { +impl<'ast> fmt::Display for Spread<'ast> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "...{}", self.expression) } } -impl<'ast, T: fmt::Debug> fmt::Debug for Spread<'ast, T> { +impl<'ast> fmt::Debug for Spread<'ast> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Spread({:?})", self.expression) } @@ -433,20 +433,20 @@ impl<'ast, T: fmt::Debug> fmt::Debug for Spread<'ast, T> { /// A spread #[derive(Clone, PartialEq)] -pub struct Spread<'ast, T> { - pub expression: ExpressionNode<'ast, T>, +pub struct Spread<'ast> { + pub expression: ExpressionNode<'ast>, } /// A range #[derive(Clone, PartialEq)] -pub struct Range<'ast, T> { - pub from: Option>, - pub to: Option>, +pub struct Range<'ast> { + pub from: Option>, + pub to: Option>, } -pub type RangeNode<'ast, T> = Node>; +pub type RangeNode<'ast> = Node>; -impl<'ast, T: fmt::Display> fmt::Display for Range<'ast, T> { +impl<'ast> fmt::Display for Range<'ast> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, @@ -463,7 +463,7 @@ impl<'ast, T: fmt::Display> fmt::Display for Range<'ast, T> { } } -impl<'ast, T: fmt::Debug> fmt::Debug for Range<'ast, T> { +impl<'ast> fmt::Debug for Range<'ast> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Range({:?}, {:?})", self.from, self.to) } @@ -471,52 +471,49 @@ impl<'ast, T: fmt::Debug> fmt::Debug for Range<'ast, T> { /// An expression #[derive(Clone, PartialEq)] -pub enum Expression<'ast, T> { - FieldConstant(T), +pub enum Expression<'ast> { + FieldConstant(BigUint), BooleanConstant(bool), U8Constant(u8), U16Constant(u16), U32Constant(u32), Identifier(Identifier<'ast>), - Add(Box>, Box>), - Sub(Box>, Box>), - Mult(Box>, Box>), - Div(Box>, Box>), - Pow(Box>, Box>), + Add(Box>, Box>), + Sub(Box>, Box>), + Mult(Box>, Box>), + Div(Box>, Box>), + Pow(Box>, Box>), IfElse( - Box>, - Box>, - Box>, + Box>, + Box>, + Box>, ), - FunctionCall(FunctionIdentifier<'ast>, Vec>), - Lt(Box>, Box>), - Le(Box>, Box>), - Eq(Box>, Box>), - Ge(Box>, Box>), - Gt(Box>, Box>), - And(Box>, Box>), - Not(Box>), - InlineArray(Vec>), - InlineStruct(UserTypeId, Vec<(Identifier<'ast>, ExpressionNode<'ast, T>)>), - Select( - Box>, - Box>, - ), - Member(Box>, Box>), - Or(Box>, Box>), - BitXor(Box>, Box>), - BitAnd(Box>, Box>), - BitOr(Box>, Box>), - LeftShift(Box>, Box>), - RightShift(Box>, Box>), -} - -pub type ExpressionNode<'ast, T> = Node>; - -impl<'ast, T: fmt::Display> fmt::Display for Expression<'ast, T> { + FunctionCall(FunctionIdentifier<'ast>, Vec>), + Lt(Box>, Box>), + Le(Box>, Box>), + Eq(Box>, Box>), + Ge(Box>, Box>), + Gt(Box>, Box>), + And(Box>, Box>), + Not(Box>), + InlineArray(Vec>), + InlineStruct(UserTypeId, Vec<(Identifier<'ast>, ExpressionNode<'ast>)>), + Select(Box>, Box>), + Member(Box>, Box>), + Or(Box>, Box>), + BitXor(Box>, Box>), + BitAnd(Box>, Box>), + BitOr(Box>, Box>), + LeftShift(Box>, Box>), + RightShift(Box>, Box>), +} + +pub type ExpressionNode<'ast> = Node>; + +impl<'ast> fmt::Display for Expression<'ast> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - Expression::FieldConstant(ref i) => write!(f, "{}", i), + Expression::FieldConstant(ref i) => write!(f, "{}", i.to_str_radix(10)), Expression::U8Constant(ref i) => write!(f, "{}", i), Expression::U16Constant(ref i) => write!(f, "{}", i), Expression::U32Constant(ref i) => write!(f, "{}", i), @@ -581,7 +578,7 @@ impl<'ast, T: fmt::Display> fmt::Display for Expression<'ast, T> { } } -impl<'ast, T: fmt::Debug> fmt::Debug for Expression<'ast, T> { +impl<'ast> fmt::Debug for Expression<'ast> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Expression::U8Constant(ref i) => write!(f, "{:x}", i), @@ -640,21 +637,21 @@ impl<'ast, T: fmt::Debug> fmt::Debug for Expression<'ast, T> { /// A list of expressions, used in return statements #[derive(Clone, PartialEq)] -pub struct ExpressionList<'ast, T> { - pub expressions: Vec>, +pub struct ExpressionList<'ast> { + pub expressions: Vec>, } -pub type ExpressionListNode<'ast, T> = Node>; +pub type ExpressionListNode<'ast> = Node>; -impl<'ast, T> ExpressionList<'ast, T> { - pub fn new() -> ExpressionList<'ast, T> { +impl<'ast> ExpressionList<'ast> { + pub fn new() -> ExpressionList<'ast> { ExpressionList { expressions: vec![], } } } -impl<'ast, T: fmt::Display> fmt::Display for ExpressionList<'ast, T> { +impl<'ast> fmt::Display for ExpressionList<'ast> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for (i, param) in self.expressions.iter().enumerate() { write!(f, "{}", param)?; @@ -666,7 +663,7 @@ impl<'ast, T: fmt::Display> fmt::Display for ExpressionList<'ast, T> { } } -impl<'ast, T: fmt::Debug> fmt::Debug for ExpressionList<'ast, T> { +impl<'ast> fmt::Debug for ExpressionList<'ast> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "ExpressionList({:?})", self.expressions) } diff --git a/zokrates_core/src/absy/node.rs b/zokrates_core/src/absy/node.rs index 1b4807bea..a2f59ecfd 100644 --- a/zokrates_core/src/absy/node.rs +++ b/zokrates_core/src/absy/node.rs @@ -74,24 +74,24 @@ impl From for Node { use crate::absy::*; use crate::imports::*; -use zokrates_field::Field; +use absy::types::UnresolvedType; -impl<'ast, T: fmt::Display + fmt::Debug + PartialEq> NodeValue for Expression<'ast, T> {} -impl<'ast, T: fmt::Display + fmt::Debug + PartialEq> NodeValue for ExpressionList<'ast, T> {} -impl<'ast, T: fmt::Display + fmt::Debug + PartialEq> NodeValue for Assignee<'ast, T> {} -impl<'ast, T: fmt::Display + fmt::Debug + PartialEq> NodeValue for Statement<'ast, T> {} -impl<'ast, T: Field> NodeValue for SymbolDeclaration<'ast, T> {} +impl<'ast> NodeValue for Expression<'ast> {} +impl<'ast> NodeValue for ExpressionList<'ast> {} +impl<'ast> NodeValue for Assignee<'ast> {} +impl<'ast> NodeValue for Statement<'ast> {} +impl<'ast> NodeValue for SymbolDeclaration<'ast> {} impl NodeValue for UnresolvedType {} impl<'ast> NodeValue for StructDefinition<'ast> {} impl<'ast> NodeValue for StructDefinitionField<'ast> {} -impl<'ast, T: fmt::Display + fmt::Debug + PartialEq> NodeValue for Function<'ast, T> {} -impl<'ast, T: Field> NodeValue for Module<'ast, T> {} +impl<'ast> NodeValue for Function<'ast> {} +impl<'ast> NodeValue for Module<'ast> {} impl<'ast> NodeValue for SymbolImport<'ast> {} impl<'ast> NodeValue for Variable<'ast> {} impl<'ast> NodeValue for Parameter<'ast> {} impl<'ast> NodeValue for Import<'ast> {} -impl<'ast, T: fmt::Display + fmt::Debug + PartialEq> NodeValue for Spread<'ast, T> {} -impl<'ast, T: fmt::Display + fmt::Debug + PartialEq> NodeValue for Range<'ast, T> {} +impl<'ast> NodeValue for Spread<'ast> {} +impl<'ast> NodeValue for Range<'ast> {} impl PartialEq for Node { fn eq(&self, other: &Node) -> bool { diff --git a/zokrates_core/src/compile.rs b/zokrates_core/src/compile.rs index c77b20796..4e10d4817 100644 --- a/zokrates_core/src/compile.rs +++ b/zokrates_core/src/compile.rs @@ -189,7 +189,7 @@ fn check_with_arena<'ast, T: Field, E: Into>( arena: &'ast Arena, ) -> Result<(ZirProgram<'ast, T>, Abi), CompileErrors> { let source = arena.alloc(source); - let compiled = compile_program(source, location.clone(), resolver, &arena)?; + let compiled = compile_program::(source, location.clone(), resolver, &arena)?; // check semantics let typed_ast = Checker::check(compiled).map_err(|errors| { @@ -209,10 +209,10 @@ pub fn compile_program<'ast, T: Field, E: Into>( location: FilePath, resolver: Option<&dyn Resolver>, arena: &'ast Arena, -) -> Result, CompileErrors> { +) -> Result, CompileErrors> { let mut modules = HashMap::new(); - let main = compile_module(&source, location.clone(), resolver, &mut modules, &arena)?; + let main = compile_module::(&source, location.clone(), resolver, &mut modules, &arena)?; modules.insert(location.clone(), main); @@ -226,18 +226,18 @@ pub fn compile_module<'ast, T: Field, E: Into>( source: &'ast str, location: FilePath, resolver: Option<&dyn Resolver>, - modules: &mut HashMap>, + modules: &mut HashMap>, arena: &'ast Arena, -) -> Result, CompileErrors> { +) -> Result, CompileErrors> { let ast = pest::generate_ast(&source) .map_err(|e| CompileErrors::from(CompileErrorInner::from(e).in_file(&location)))?; let ast = process_macros::(ast) .map_err(|e| CompileErrors::from(CompileErrorInner::from(e).in_file(&location)))?; - let module_without_imports: Module = Module::from(ast); + let module_without_imports: Module = Module::from(ast); - Importer::new().apply_imports( + Importer::new().apply_imports::( module_without_imports, location.clone(), resolver, diff --git a/zokrates_core/src/imports.rs b/zokrates_core/src/imports.rs index a927c0f06..a4d5f970f 100644 --- a/zokrates_core/src/imports.rs +++ b/zokrates_core/src/imports.rs @@ -134,12 +134,12 @@ impl Importer { pub fn apply_imports<'ast, T: Field, E: Into>( &self, - destination: Module<'ast, T>, + destination: Module<'ast>, location: PathBuf, resolver: Option<&dyn Resolver>, - modules: &mut HashMap>, + modules: &mut HashMap>, arena: &'ast Arena, - ) -> Result, CompileErrors> { + ) -> Result, CompileErrors> { let mut symbols: Vec<_> = vec![]; for import in destination.imports { @@ -259,7 +259,7 @@ impl Importer { None => { let source = arena.alloc(source); - let compiled = compile_module( + let compiled = compile_module::( source, new_location.clone(), resolver, diff --git a/zokrates_core/src/semantics.rs b/zokrates_core/src/semantics.rs index a1d86468d..52e7b6145 100644 --- a/zokrates_core/src/semantics.rs +++ b/zokrates_core/src/semantics.rs @@ -48,7 +48,7 @@ type TypeMap = HashMap>; #[derive(Debug)] struct State<'ast, T: Field> { /// The modules yet to be checked, which we consume as we explore the dependency tree - modules: Modules<'ast, T>, + modules: Modules<'ast>, /// The already checked modules, which we're returning at the end typed_modules: TypedModules<'ast, T>, /// The user-defined types, which we keep track at this phase only. In later phases, we rely only on basic types and combinations thereof @@ -104,7 +104,7 @@ impl SymbolUnifier { } impl<'ast, T: Field> State<'ast, T> { - fn new(modules: Modules<'ast, T>) -> Self { + fn new(modules: Modules<'ast>) -> Self { State { modules, typed_modules: HashMap::new(), @@ -242,13 +242,13 @@ impl<'ast> Checker<'ast> { /// # Arguments /// /// * `prog` - The `Program` to be checked - pub fn check(prog: Program<'ast, T>) -> Result, Vec> { + pub fn check(prog: Program<'ast>) -> Result, Vec> { Checker::new().check_program(prog) } fn check_program( &mut self, - program: Program<'ast, T>, + program: Program<'ast>, ) -> Result, Vec> { let mut state = State::new(program.modules); @@ -330,7 +330,7 @@ impl<'ast> Checker<'ast> { fn check_symbol_declaration( &mut self, - declaration: SymbolDeclarationNode<'ast, T>, + declaration: SymbolDeclarationNode<'ast>, module_id: &ModuleId, state: &mut State<'ast, T>, functions: &mut HashMap, TypedFunctionSymbol<'ast, T>>, @@ -642,7 +642,7 @@ impl<'ast> Checker<'ast> { fn check_function( &mut self, - funct_node: FunctionNode<'ast, T>, + funct_node: FunctionNode<'ast>, module_id: &ModuleId, types: &TypeMap, ) -> Result, Vec> { @@ -826,7 +826,7 @@ impl<'ast> Checker<'ast> { fn check_statement( &mut self, - stat: StatementNode<'ast, T>, + stat: StatementNode<'ast>, module_id: &ModuleId, types: &TypeMap, ) -> Result, Vec> { @@ -964,7 +964,7 @@ impl<'ast> Checker<'ast> { Expression::FunctionCall(fun_id, arguments) => { // check lhs assignees are defined - let (assignees, errors): (Vec<_>, Vec<_>) = assignees.into_iter().map(|a| self.check_assignee(a, module_id, types)).partition(|r| r.is_ok()); + let (assignees, errors): (Vec<_>, Vec<_>) = assignees.into_iter().map(|a| self.check_assignee::(a, module_id, types)).partition(|r| r.is_ok()); if errors.len() > 0 { return Err(errors.into_iter().map(|e| e.unwrap_err()).collect()); @@ -1024,7 +1024,7 @@ impl<'ast> Checker<'ast> { fn check_assignee( &mut self, - assignee: AssigneeNode<'ast, T>, + assignee: AssigneeNode<'ast>, module_id: &ModuleId, types: &TypeMap, ) -> Result, ErrorInner> { @@ -1112,7 +1112,7 @@ impl<'ast> Checker<'ast> { fn check_spread_or_expression( &mut self, - spread_or_expression: SpreadOrExpression<'ast, T>, + spread_or_expression: SpreadOrExpression<'ast>, module_id: &ModuleId, types: &TypeMap, ) -> Result>, ErrorInner> { @@ -1190,7 +1190,7 @@ impl<'ast> Checker<'ast> { fn check_expression( &mut self, - expr: ExpressionNode<'ast, T>, + expr: ExpressionNode<'ast>, module_id: &ModuleId, types: &TypeMap, ) -> Result, ErrorInner> { @@ -1411,7 +1411,20 @@ impl<'ast> Checker<'ast> { }), } } - Expression::FieldConstant(n) => Ok(FieldElementExpression::Number(n).into()), + Expression::FieldConstant(n) => { + let bits = n.bits(); + let required_bits = T::get_required_bits(); + match bits <= required_bits { + true => Ok(FieldElementExpression::Number(T::from(n)).into()), + false => Err(ErrorInner { + pos: Some(pos), + message: format!( + "Field constant not in the representable range ({} bits)", + required_bits + ), + }), + } + } Expression::U8Constant(n) => Ok(UExpressionInner::Value(n.into()).annotate(8).into()), Expression::U16Constant(n) => Ok(UExpressionInner::Value(n.into()).annotate(16).into()), Expression::U32Constant(n) => Ok(UExpressionInner::Value(n.into()).annotate(32).into()), @@ -2320,6 +2333,7 @@ impl<'ast> Checker<'ast> { mod tests { use super::*; use absy; + use num_bigint::BigUint; use typed_absy; use zokrates_field::Bn128Field; @@ -2327,6 +2341,7 @@ mod tests { mod array { use super::*; + use num_bigint::BigUint; #[test] fn element_type_mismatch() { @@ -2334,36 +2349,36 @@ mod tests { let module_id = "".into(); // [3, true] let a = Expression::InlineArray(vec![ - Expression::FieldConstant(Bn128Field::from(3)).mock().into(), + Expression::FieldConstant(BigUint::from(3u32)).mock().into(), Expression::BooleanConstant(true).mock().into(), ]) .mock(); assert!(Checker::new() - .check_expression(a, &module_id, &types) + .check_expression::(a, &module_id, &types) .is_err()); // [[0], [0, 0]] let a = Expression::InlineArray(vec![ - Expression::InlineArray(vec![Expression::FieldConstant(Bn128Field::from(0)) + Expression::InlineArray(vec![Expression::FieldConstant(BigUint::from(0u32)) .mock() .into()]) .mock() .into(), Expression::InlineArray(vec![ - Expression::FieldConstant(Bn128Field::from(0)).mock().into(), - Expression::FieldConstant(Bn128Field::from(0)).mock().into(), + Expression::FieldConstant(BigUint::from(0u32)).mock().into(), + Expression::FieldConstant(BigUint::from(0u32)).mock().into(), ]) .mock() .into(), ]) .mock(); assert!(Checker::new() - .check_expression(a, &module_id, &types) + .check_expression::(a, &module_id, &types) .is_err()); // [[0], true] let a = Expression::InlineArray(vec![ - Expression::InlineArray(vec![Expression::FieldConstant(Bn128Field::from(0)) + Expression::InlineArray(vec![Expression::FieldConstant(BigUint::from(0u32)) .mock() .into()]) .mock() @@ -2374,7 +2389,7 @@ mod tests { ]) .mock(); assert!(Checker::new() - .check_expression(a, &module_id, &types) + .check_expression::(a, &module_id, &types) .is_err()); } } @@ -2383,8 +2398,8 @@ mod tests { use super::*; /// Helper function to create ((): return) - fn function0() -> FunctionNode<'static, Bn128Field> { - let statements: Vec> = vec![Statement::Return( + fn function0() -> FunctionNode<'static> { + let statements: Vec = vec![Statement::Return( ExpressionList { expressions: vec![], } @@ -2405,8 +2420,8 @@ mod tests { } /// Helper function to create ((private field a): return) - fn function1() -> FunctionNode<'static, Bn128Field> { - let statements: Vec> = vec![Statement::Return( + fn function1() -> FunctionNode<'static> { + let statements: Vec = vec![Statement::Return( ExpressionList { expressions: vec![], } @@ -2474,7 +2489,7 @@ mod tests { // after semantic check, `bar` should import a checked function - let foo: Module = Module { + let foo: Module = Module { symbols: vec![SymbolDeclaration { id: "main", symbol: Symbol::HereFunction(function0()), @@ -2483,7 +2498,7 @@ mod tests { imports: vec![], }; - let bar: Module = Module { + let bar: Module = Module { symbols: vec![SymbolDeclaration { id: "main", symbol: Symbol::There(SymbolImport::with_id_in_module("main", "foo").mock()), @@ -2492,7 +2507,7 @@ mod tests { imports: vec![], }; - let mut state = State::new( + let mut state = State::::new( vec![("foo".into(), foo), ("bar".into(), bar)] .into_iter() .collect(), @@ -2542,7 +2557,7 @@ mod tests { imports: vec![], }; - let mut state = State::new( + let mut state = State::::new( vec![(PathBuf::from(MODULE_ID).into(), module)] .into_iter() .collect(), @@ -2584,7 +2599,7 @@ mod tests { imports: vec![], }; - let mut state = State::new( + let mut state = State::::new( vec![(PathBuf::from(MODULE_ID), module)] .into_iter() .collect(), @@ -2619,7 +2634,7 @@ mod tests { // // should fail - let module: Module = Module { + let module: Module = Module { symbols: vec![ SymbolDeclaration { id: "foo", @@ -2635,7 +2650,8 @@ mod tests { imports: vec![], }; - let mut state = State::new(vec![("main".into(), module)].into_iter().collect()); + let mut state = + State::::new(vec![("main".into(), module)].into_iter().collect()); let mut checker = Checker::new(); assert_eq!( @@ -2672,7 +2688,8 @@ mod tests { imports: vec![], }; - let mut state = State::new(vec![("main".into(), module)].into_iter().collect()); + let mut state = + State::::new(vec![("main".into(), module)].into_iter().collect()); let mut checker = Checker::new(); assert_eq!( @@ -2722,7 +2739,7 @@ mod tests { imports: vec![], }; - let mut state = State::new( + let mut state = State::::new( vec![(PathBuf::from(MODULE_ID), main), ("bar".into(), bar)] .into_iter() .collect(), @@ -2773,7 +2790,7 @@ mod tests { imports: vec![], }; - let mut state = State::new( + let mut state = State::::new( vec![(PathBuf::from(MODULE_ID), main), ("bar".into(), bar)] .into_iter() .collect(), @@ -2797,9 +2814,9 @@ mod tests { functions: HashSet>, ) -> Checker<'ast> { Checker { - scope: scope, - functions: functions, - level: level, + scope, + functions, + level, } } @@ -2807,7 +2824,7 @@ mod tests { fn undefined_variable_in_statement() { // a = b // b undefined - let statement: StatementNode = Statement::Definition( + let statement: StatementNode = Statement::Definition( Assignee::Identifier("a").mock(), Expression::Identifier("b").mock(), ) @@ -2818,7 +2835,7 @@ mod tests { let mut checker = Checker::new(); assert_eq!( - checker.check_statement(statement, &module_id, &types), + checker.check_statement::(statement, &module_id, &types), Err(vec![ErrorInner { pos: Some((Position::mock(), Position::mock())), message: "Identifier \"b\" is undefined".into() @@ -2830,7 +2847,7 @@ mod tests { fn defined_variable_in_statement() { // a = b // b defined - let statement: StatementNode = Statement::Definition( + let statement: StatementNode = Statement::Definition( Assignee::Identifier("a").mock(), Expression::Identifier("b").mock(), ) @@ -2850,7 +2867,7 @@ mod tests { }); let mut checker = new_with_args(scope, 1, HashSet::new()); assert_eq!( - checker.check_statement(statement, &module_id, &types), + checker.check_statement::(statement, &module_id, &types), Ok(TypedStatement::Definition( TypedAssignee::Identifier(typed_absy::Variable::field_element("a")), FieldElementExpression::Identifier("b".into()).into() @@ -2873,7 +2890,7 @@ mod tests { .mock(), Statement::Definition( Assignee::Identifier("a").mock(), - Expression::FieldConstant(Bn128Field::from(1)).mock(), + Expression::FieldConstant(BigUint::from(1u32)).mock(), ) .mock(), ]; @@ -2923,7 +2940,8 @@ mod tests { imports: vec![], }; - let mut state = State::new(vec![("main".into(), module)].into_iter().collect()); + let mut state = + State::::new(vec![("main".into(), module)].into_iter().collect()); let mut checker = Checker::new(); assert_eq!( @@ -2956,7 +2974,7 @@ mod tests { .mock(), Statement::Definition( Assignee::Identifier("a").mock(), - Expression::FieldConstant(Bn128Field::from(1)).mock(), + Expression::FieldConstant(BigUint::from(1u32)).mock(), ) .mock(), ]; @@ -2979,7 +2997,7 @@ mod tests { .mock(), Statement::Definition( Assignee::Identifier("a").mock(), - Expression::FieldConstant(Bn128Field::from(2)).mock(), + Expression::FieldConstant(BigUint::from(2u32)).mock(), ) .mock(), Statement::Return( @@ -3003,7 +3021,7 @@ mod tests { let main_args = vec![]; let main_statements = vec![Statement::Return( ExpressionList { - expressions: vec![Expression::FieldConstant(Bn128Field::from(1)).mock()], + expressions: vec![Expression::FieldConstant(BigUint::from(1u32)).mock()], } .mock(), ) @@ -3041,7 +3059,8 @@ mod tests { imports: vec![], }; - let mut state = State::new(vec![("main".into(), module)].into_iter().collect()); + let mut state = + State::::new(vec![("main".into(), module)].into_iter().collect()); let mut checker = Checker::new(); assert!(checker.check_module(&"main".into(), &mut state).is_ok()); @@ -3057,8 +3076,8 @@ mod tests { let foo_statements = vec![ Statement::For( absy::Variable::new("i", UnresolvedType::FieldElement.mock()).mock(), - Expression::FieldConstant(Bn128Field::from(0)).mock(), - Expression::FieldConstant(Bn128Field::from(10)).mock(), + Expression::FieldConstant(BigUint::from(0u32)).mock(), + Expression::FieldConstant(BigUint::from(10u32)).mock(), vec![], ) .mock(), @@ -3085,7 +3104,7 @@ mod tests { let mut checker = Checker::new(); assert_eq!( - checker.check_function(foo, &module_id, &types), + checker.check_function::(foo, &module_id, &types), Err(vec![ErrorInner { pos: Some((Position::mock(), Position::mock())), message: "Identifier \"i\" is undefined".into() @@ -3115,8 +3134,8 @@ mod tests { let foo_statements = vec![Statement::For( absy::Variable::new("i", UnresolvedType::FieldElement.mock()).mock(), - Expression::FieldConstant(Bn128Field::from(0)).mock(), - Expression::FieldConstant(Bn128Field::from(10)).mock(), + Expression::FieldConstant(BigUint::from(0u32)).mock(), + Expression::FieldConstant(BigUint::from(10u32)).mock(), for_statements, ) .mock()]; @@ -3131,8 +3150,8 @@ mod tests { let foo_statements_checked = vec![TypedStatement::For( typed_absy::Variable::field_element("i"), - FieldElementExpression::Number(Bn128Field::from(0)), - FieldElementExpression::Number(Bn128Field::from(10)), + FieldElementExpression::Number(Bn128Field::from(0u32)), + FieldElementExpression::Number(Bn128Field::from(10u32)), for_statements_checked, )]; @@ -3160,7 +3179,7 @@ mod tests { let mut checker = Checker::new(); assert_eq!( - checker.check_function(foo, &module_id, &types), + checker.check_function::(foo, &module_id, &types), Ok(foo_checked) ); } @@ -3172,7 +3191,7 @@ mod tests { // def bar(): // field a = foo() // should fail - let bar_statements: Vec> = vec![ + let bar_statements: Vec = vec![ Statement::Declaration( absy::Variable::new("a", UnresolvedType::FieldElement.mock()).mock(), ) @@ -3209,7 +3228,7 @@ mod tests { let mut checker = new_with_args(HashSet::new(), 0, functions); assert_eq!( - checker.check_function(bar, &module_id, &types), + checker.check_function::(bar, &module_id, &types), Err(vec![ErrorInner { pos: Some((Position::mock(), Position::mock())), message: @@ -3226,9 +3245,9 @@ mod tests { // def bar(): // 2 == foo() // should fail - let bar_statements: Vec> = vec![Statement::Assertion( + let bar_statements: Vec = vec![Statement::Assertion( Expression::Eq( - box Expression::FieldConstant(Bn128Field::from(2)).mock(), + box Expression::FieldConstant(BigUint::from(2u32)).mock(), box Expression::FunctionCall("foo", vec![]).mock(), ) .mock(), @@ -3260,7 +3279,7 @@ mod tests { let mut checker = new_with_args(HashSet::new(), 0, functions); assert_eq!( - checker.check_function(bar, &module_id, &types), + checker.check_function::(bar, &module_id, &types), Err(vec![ErrorInner { pos: Some((Position::mock(), Position::mock())), message: "Function definition for function foo with signature () -> _ not found." @@ -3274,7 +3293,7 @@ mod tests { // def bar(): // field a = foo() // should fail - let bar_statements: Vec> = vec![ + let bar_statements: Vec = vec![ Statement::Declaration( absy::Variable::new("a", UnresolvedType::FieldElement.mock()).mock(), ) @@ -3301,7 +3320,7 @@ mod tests { let mut checker = new_with_args(HashSet::new(), 0, HashSet::new()); assert_eq!( - checker.check_function(bar, &module_id, &types), + checker.check_function::(bar, &module_id, &types), Err(vec![ErrorInner { pos: Some((Position::mock(), Position::mock())), @@ -3321,11 +3340,11 @@ mod tests { // return 1 // should fail - let foo_statements: Vec> = vec![Statement::Return( + let foo_statements: Vec = vec![Statement::Return( ExpressionList { expressions: vec![ - Expression::FieldConstant(Bn128Field::from(1)).mock(), - Expression::FieldConstant(Bn128Field::from(2)).mock(), + Expression::FieldConstant(BigUint::from(1u32)).mock(), + Expression::FieldConstant(BigUint::from(2u32)).mock(), ], } .mock(), @@ -3349,7 +3368,7 @@ mod tests { } .mock(); - let main_statements: Vec> = vec![ + let main_statements: Vec = vec![ Statement::Declaration( absy::Variable::new("a", UnresolvedType::FieldElement.mock()).mock(), ) @@ -3368,7 +3387,7 @@ mod tests { .mock(), Statement::Return( ExpressionList { - expressions: vec![Expression::FieldConstant(Bn128Field::from(1)).mock()], + expressions: vec![Expression::FieldConstant(BigUint::from(1u32)).mock()], } .mock(), ) @@ -3401,7 +3420,8 @@ mod tests { imports: vec![], }; - let mut state = State::new(vec![("main".into(), module)].into_iter().collect()); + let mut state = + State::::new(vec![("main".into(), module)].into_iter().collect()); let mut checker = new_with_args(HashSet::new(), 0, HashSet::new()); assert_eq!( @@ -3425,11 +3445,11 @@ mod tests { // return 1 // should fail - let foo_statements: Vec> = vec![Statement::Return( + let foo_statements: Vec = vec![Statement::Return( ExpressionList { expressions: vec![ - Expression::FieldConstant(Bn128Field::from(1)).mock(), - Expression::FieldConstant(Bn128Field::from(2)).mock(), + Expression::FieldConstant(BigUint::from(1u32)).mock(), + Expression::FieldConstant(BigUint::from(2u32)).mock(), ], } .mock(), @@ -3449,7 +3469,7 @@ mod tests { } .mock(); - let main_statements: Vec> = vec![ + let main_statements: Vec = vec![ Statement::MultipleDefinition( vec![ Assignee::Identifier("a").mock(), @@ -3493,7 +3513,8 @@ mod tests { imports: vec![], }; - let mut state = State::new(vec![("main".into(), module)].into_iter().collect()); + let mut state = + State::::new(vec![("main".into(), module)].into_iter().collect()); let mut checker = new_with_args(HashSet::new(), 0, HashSet::new()); assert_eq!( @@ -3527,9 +3548,9 @@ mod tests { // return // should fail - let foo_statements: Vec> = vec![Statement::Return( + let foo_statements: Vec = vec![Statement::Return( ExpressionList { - expressions: vec![Expression::FieldConstant(Bn128Field::from(1)).mock()], + expressions: vec![Expression::FieldConstant(BigUint::from(1u32)).mock()], } .mock(), ) @@ -3545,7 +3566,7 @@ mod tests { } .mock(); - let main_statements: Vec> = vec![ + let main_statements: Vec = vec![ Statement::Declaration( absy::Variable::new( "a", @@ -3557,7 +3578,7 @@ mod tests { Statement::Definition( Assignee::Identifier("a".into()).mock(), Expression::InlineArray(vec![absy::SpreadOrExpression::Expression( - Expression::FieldConstant(Bn128Field::from(0)).mock(), + Expression::FieldConstant(BigUint::from(0u32)).mock(), )]) .mock(), ) @@ -3566,7 +3587,7 @@ mod tests { vec![Assignee::Select( box Assignee::Identifier("a").mock(), box RangeOrExpression::Expression( - absy::Expression::FieldConstant(Bn128Field::from(0)).mock(), + absy::Expression::FieldConstant(BigUint::from(0u32)).mock(), ), ) .mock()], @@ -3608,7 +3629,8 @@ mod tests { imports: vec![], }; - let mut state = State::new(vec![("main".into(), module)].into_iter().collect()); + let mut state = + State::::new(vec![("main".into(), module)].into_iter().collect()); let mut checker = new_with_args(HashSet::new(), 0, HashSet::new()); assert_eq!( @@ -3628,9 +3650,9 @@ mod tests { // def bar(): // 1 == foo() // should fail - let bar_statements: Vec> = vec![Statement::Assertion( + let bar_statements: Vec = vec![Statement::Assertion( Expression::Eq( - box Expression::FieldConstant(Bn128Field::from(1)).mock(), + box Expression::FieldConstant(BigUint::from(1u32)).mock(), box Expression::FunctionCall("foo", vec![]).mock(), ) .mock(), @@ -3652,7 +3674,7 @@ mod tests { let mut checker = new_with_args(HashSet::new(), 0, HashSet::new()); assert_eq!( - checker.check_function(bar, &module_id, &types), + checker.check_function::(bar, &module_id, &types), Err(vec![ErrorInner { pos: Some((Position::mock(), Position::mock())), @@ -3667,7 +3689,7 @@ mod tests { // def bar(): // return a, b // should fail - let bar_statements: Vec> = vec![Statement::Return( + let bar_statements: Vec = vec![Statement::Return( ExpressionList { expressions: vec![ Expression::Identifier("a").mock(), @@ -3696,7 +3718,7 @@ mod tests { let mut checker = new_with_args(HashSet::new(), 0, HashSet::new()); assert_eq!( - checker.check_function(bar, &module_id, &types), + checker.check_function::(bar, &module_id, &types), Err(vec![ErrorInner { pos: Some((Position::mock(), Position::mock())), message: "Identifier \"a\" is undefined".into() @@ -3713,7 +3735,7 @@ mod tests { // return a + b // // should pass - let bar_statements: Vec> = vec![ + let bar_statements: Vec = vec![ Statement::Declaration( absy::Variable::new("a", UnresolvedType::FieldElement.mock()).mock(), ) @@ -3814,9 +3836,9 @@ mod tests { // return 1 // // should fail - let main1_statements: Vec> = vec![Statement::Return( + let main1_statements: Vec = vec![Statement::Return( ExpressionList { - expressions: vec![Expression::FieldConstant(Bn128Field::from(1)).mock()], + expressions: vec![Expression::FieldConstant(BigUint::from(1u32)).mock()], } .mock(), ) @@ -3828,9 +3850,9 @@ mod tests { } .mock()]; - let main2_statements: Vec> = vec![Statement::Return( + let main2_statements: Vec = vec![Statement::Return( ExpressionList { - expressions: vec![Expression::FieldConstant(Bn128Field::from(1)).mock()], + expressions: vec![Expression::FieldConstant(BigUint::from(1u32)).mock()], } .mock(), ) @@ -3883,7 +3905,7 @@ mod tests { let mut checker = Checker::new(); assert_eq!( - checker.check_program(program), + checker.check_program::(program), Err(vec![Error { inner: ErrorInner { pos: None, @@ -3976,7 +3998,7 @@ mod tests { ) -> (Checker<'static>, State<'static, Bn128Field>) { let module_id: PathBuf = "".into(); - let module: Module = Module { + let module: Module = Module { imports: vec![], symbols: vec![SymbolDeclaration { id: "Foo", @@ -3985,7 +4007,8 @@ mod tests { .mock()], }; - let mut state = State::new(vec![(module_id.clone(), module)].into_iter().collect()); + let mut state = + State::::new(vec![(module_id.clone(), module)].into_iter().collect()); let mut checker = Checker::new(); @@ -4158,7 +4181,7 @@ mod tests { let module_id: PathBuf = "".into(); - let module: Module = Module { + let module: Module = Module { imports: vec![], symbols: vec![ SymbolDeclaration { @@ -4192,7 +4215,9 @@ mod tests { ], }; - let mut state = State::new(vec![(module_id.clone(), module)].into_iter().collect()); + let mut state = State::::new( + vec![(module_id.clone(), module)].into_iter().collect(), + ); assert!(Checker::new().check_module(&module_id, &mut state).is_ok()); assert_eq!( @@ -4225,7 +4250,7 @@ mod tests { let module_id: PathBuf = "".into(); - let module: Module = Module { + let module: Module = Module { imports: vec![], symbols: vec![SymbolDeclaration { id: "Bar", @@ -4243,7 +4268,9 @@ mod tests { .mock()], }; - let mut state = State::new(vec![(module_id.clone(), module)].into_iter().collect()); + let mut state = State::::new( + vec![(module_id.clone(), module)].into_iter().collect(), + ); assert!(Checker::new().check_module(&module_id, &mut state).is_err()); } @@ -4256,7 +4283,7 @@ mod tests { let module_id: PathBuf = "".into(); - let module: Module = Module { + let module: Module = Module { imports: vec![], symbols: vec![SymbolDeclaration { id: "Foo", @@ -4274,7 +4301,9 @@ mod tests { .mock()], }; - let mut state = State::new(vec![(module_id.clone(), module)].into_iter().collect()); + let mut state = State::::new( + vec![(module_id.clone(), module)].into_iter().collect(), + ); assert!(Checker::new().check_module(&module_id, &mut state).is_err()); } @@ -4288,7 +4317,7 @@ mod tests { let module_id: PathBuf = "".into(); - let module: Module = Module { + let module: Module = Module { imports: vec![], symbols: vec![ SymbolDeclaration { @@ -4322,7 +4351,9 @@ mod tests { ], }; - let mut state = State::new(vec![(module_id.clone(), module)].into_iter().collect()); + let mut state = State::::new( + vec![(module_id.clone(), module)].into_iter().collect(), + ); assert!(Checker::new().check_module(&module_id, &mut state).is_err()); } @@ -4511,13 +4542,13 @@ mod tests { }); assert_eq!( - checker.check_expression( + checker.check_expression::( Expression::Member( box Expression::InlineStruct( "Foo".into(), vec![( "foo", - Expression::FieldConstant(Bn128Field::from(42)).mock() + Expression::FieldConstant(BigUint::from(42u32)).mock() )] ) .mock(), @@ -4529,7 +4560,7 @@ mod tests { ), Ok(FieldElementExpression::Member( box StructExpressionInner::Value(vec![FieldElementExpression::Number( - Bn128Field::from(42) + Bn128Field::from(42u32) ) .into()]) .annotate(StructType::new( @@ -4560,13 +4591,13 @@ mod tests { assert_eq!( checker - .check_expression( + .check_expression::( Expression::Member( box Expression::InlineStruct( "Foo".into(), vec![( "foo", - Expression::FieldConstant(Bn128Field::from(42)).mock() + Expression::FieldConstant(BigUint::from(42u32)).mock() )] ) .mock(), @@ -4601,12 +4632,12 @@ mod tests { assert_eq!( checker - .check_expression( + .check_expression::( Expression::InlineStruct( "Bar".into(), vec![( "foo", - Expression::FieldConstant(Bn128Field::from(42)).mock() + Expression::FieldConstant(BigUint::from(42u32)).mock() )] ) .mock(), @@ -4642,13 +4673,13 @@ mod tests { }); assert_eq!( - checker.check_expression( + checker.check_expression::( Expression::InlineStruct( "Foo".into(), vec![ ( "foo", - Expression::FieldConstant(Bn128Field::from(42)).mock() + Expression::FieldConstant(BigUint::from(42u32)).mock() ), ("bar", Expression::BooleanConstant(true).mock()) ] @@ -4658,7 +4689,7 @@ mod tests { &state.types ), Ok(StructExpressionInner::Value(vec![ - FieldElementExpression::Number(Bn128Field::from(42)).into(), + FieldElementExpression::Number(Bn128Field::from(42u32)).into(), BooleanExpression::Value(true).into() ]) .annotate(StructType::new( @@ -4696,14 +4727,14 @@ mod tests { }); assert_eq!( - checker.check_expression( + checker.check_expression::( Expression::InlineStruct( "Foo".into(), vec![ ("bar", Expression::BooleanConstant(true).mock()), ( "foo", - Expression::FieldConstant(Bn128Field::from(42)).mock() + Expression::FieldConstant(BigUint::from(42u32)).mock() ) ] ) @@ -4712,7 +4743,7 @@ mod tests { &state.types ), Ok(StructExpressionInner::Value(vec![ - FieldElementExpression::Number(Bn128Field::from(42)).into(), + FieldElementExpression::Number(Bn128Field::from(42u32)).into(), BooleanExpression::Value(true).into() ]) .annotate(StructType::new( @@ -4751,12 +4782,12 @@ mod tests { assert_eq!( checker - .check_expression( + .check_expression::( Expression::InlineStruct( "Foo".into(), vec![( "foo", - Expression::FieldConstant(Bn128Field::from(42)).mock() + Expression::FieldConstant(BigUint::from(42u32)).mock() )] ) .mock(), @@ -4795,7 +4826,7 @@ mod tests { assert_eq!( checker - .check_expression( + .check_expression::( Expression::InlineStruct( "Foo".into(), vec![( @@ -4803,7 +4834,7 @@ mod tests { Expression::BooleanConstant(true).mock() ),( "foo", - Expression::FieldConstant(Bn128Field::from(42)).mock() + Expression::FieldConstant(BigUint::from(42u32)).mock() )] ) .mock(), @@ -4816,17 +4847,17 @@ mod tests { assert_eq!( checker - .check_expression( + .check_expression::( Expression::InlineStruct( "Foo".into(), vec![ ( "bar", - Expression::FieldConstant(Bn128Field::from(42)).mock() + Expression::FieldConstant(BigUint::from(42u32)).mock() ), ( "foo", - Expression::FieldConstant(Bn128Field::from(42)).mock() + Expression::FieldConstant(BigUint::from(42u32)).mock() ) ] ) @@ -4844,11 +4875,12 @@ mod tests { mod assignee { use super::*; + use num_bigint::BigUint; #[test] fn identifier() { // a = 42 - let a = Assignee::Identifier::("a").mock(); + let a = Assignee::Identifier("a").mock(); let types = HashMap::new(); let module_id = "".into(); @@ -4865,7 +4897,7 @@ mod tests { .unwrap(); assert_eq!( - checker.check_assignee(a, &module_id, &types), + checker.check_assignee::(a, &module_id, &types), Ok(TypedAssignee::Identifier( typed_absy::Variable::field_element("a") )) @@ -4879,7 +4911,7 @@ mod tests { let a = Assignee::Select( box Assignee::Identifier("a").mock(), box RangeOrExpression::Expression( - Expression::FieldConstant(Bn128Field::from(2)).mock(), + Expression::FieldConstant(BigUint::from(2u32)).mock(), ), ) .mock(); @@ -4904,10 +4936,10 @@ mod tests { .unwrap(); assert_eq!( - checker.check_assignee(a, &module_id, &types), + checker.check_assignee::(a, &module_id, &types), Ok(TypedAssignee::Select( box TypedAssignee::Identifier(typed_absy::Variable::field_array("a", 33)), - box FieldElementExpression::Number(Bn128Field::from(2)).into() + box FieldElementExpression::Number(Bn128Field::from(2u32)).into() )) ); } @@ -4920,12 +4952,12 @@ mod tests { box Assignee::Select( box Assignee::Identifier("a").mock(), box RangeOrExpression::Expression( - Expression::FieldConstant(Bn128Field::from(1)).mock(), + Expression::FieldConstant(BigUint::from(1u32)).mock(), ), ) .mock(), box RangeOrExpression::Expression( - Expression::FieldConstant(Bn128Field::from(2)).mock(), + Expression::FieldConstant(BigUint::from(2u32)).mock(), ), ) .mock(); @@ -4954,7 +4986,7 @@ mod tests { .unwrap(); assert_eq!( - checker.check_assignee(a, &module_id, &types), + checker.check_assignee::(a, &module_id, &types), Ok(TypedAssignee::Select( box TypedAssignee::Select( box TypedAssignee::Identifier(typed_absy::Variable::array( @@ -4962,9 +4994,9 @@ mod tests { Type::array(Type::FieldElement, 33), 42 )), - box FieldElementExpression::Number(Bn128Field::from(1)).into() + box FieldElementExpression::Number(Bn128Field::from(1u32)).into() ), - box FieldElementExpression::Number(Bn128Field::from(2)).into() + box FieldElementExpression::Number(Bn128Field::from(2u32)).into() )) ); } From bb938dbcf5d3e6028b7c7d9baf73136bf55e69d1 Mon Sep 17 00:00:00 2001 From: dark64 Date: Mon, 14 Sep 2020 13:01:19 +0200 Subject: [PATCH 13/54] fix range check, add unit tests for field constant range check (max and max + 1) --- zokrates_core/src/semantics.rs | 57 +++++++++++++++++++++++++--------- 1 file changed, 43 insertions(+), 14 deletions(-) diff --git a/zokrates_core/src/semantics.rs b/zokrates_core/src/semantics.rs index 52e7b6145..3f016160d 100644 --- a/zokrates_core/src/semantics.rs +++ b/zokrates_core/src/semantics.rs @@ -1411,20 +1411,17 @@ impl<'ast> Checker<'ast> { }), } } - Expression::FieldConstant(n) => { - let bits = n.bits(); - let required_bits = T::get_required_bits(); - match bits <= required_bits { - true => Ok(FieldElementExpression::Number(T::from(n)).into()), - false => Err(ErrorInner { - pos: Some(pos), - message: format!( - "Field constant not in the representable range ({} bits)", - required_bits - ), - }), - } - } + Expression::FieldConstant(n) => match n <= T::max_value().to_biguint() { + true => Ok(FieldElementExpression::Number(T::from(n)).into()), + false => Err(ErrorInner { + pos: Some(pos), + message: format!( + "Field constant not in the representable range [{}, {}]", + T::min_value(), + T::max_value() + ), + }), + }, Expression::U8Constant(n) => Ok(UExpressionInner::Value(n.into()).annotate(8).into()), Expression::U16Constant(n) => Ok(UExpressionInner::Value(n.into()).annotate(16).into()), Expression::U32Constant(n) => Ok(UExpressionInner::Value(n.into()).annotate(32).into()), @@ -2339,6 +2336,38 @@ mod tests { const MODULE_ID: &str = ""; + mod constants { + use super::*; + use num_bigint::BigUint; + use std::ops::Add; + + #[test] + fn field_in_range() { + let types = HashMap::new(); + let module_id = "".into(); + + let expr = + Expression::FieldConstant(BigUint::from(Bn128Field::max_value().to_biguint())) + .mock(); + assert!(Checker::new() + .check_expression::(expr, &module_id, &types) + .is_ok()); + } + + #[test] + fn field_overflow() { + let types = HashMap::new(); + let module_id = "".into(); + + let value = Bn128Field::max_value().to_biguint().add(1u32); + let expr = Expression::FieldConstant(BigUint::from(value)).mock(); + + assert!(Checker::new() + .check_expression::(expr, &module_id, &types) + .is_err()); + } + } + mod array { use super::*; use num_bigint::BigUint; From ee319a077c474cec55a879b2e596396f334f6960 Mon Sep 17 00:00:00 2001 From: dark64 Date: Thu, 17 Sep 2020 19:01:30 +0200 Subject: [PATCH 14/54] add TryFrom to Field --- zokrates_core/src/semantics.rs | 10 ++++----- .../src/static_analysis/uint_optimizer.rs | 2 +- zokrates_field/src/lib.rs | 22 +++++++++++++------ 3 files changed, 21 insertions(+), 13 deletions(-) diff --git a/zokrates_core/src/semantics.rs b/zokrates_core/src/semantics.rs index 3f016160d..c252d9574 100644 --- a/zokrates_core/src/semantics.rs +++ b/zokrates_core/src/semantics.rs @@ -1411,17 +1411,17 @@ impl<'ast> Checker<'ast> { }), } } - Expression::FieldConstant(n) => match n <= T::max_value().to_biguint() { - true => Ok(FieldElementExpression::Number(T::from(n)).into()), - false => Err(ErrorInner { + Expression::FieldConstant(n) => Ok(FieldElementExpression::Number( + T::try_from(n).map_err(|_| ErrorInner { pos: Some(pos), message: format!( "Field constant not in the representable range [{}, {}]", T::min_value(), T::max_value() ), - }), - }, + })?, + ) + .into()), Expression::U8Constant(n) => Ok(UExpressionInner::Value(n.into()).annotate(8).into()), Expression::U16Constant(n) => Ok(UExpressionInner::Value(n.into()).annotate(16).into()), Expression::U32Constant(n) => Ok(UExpressionInner::Value(n.into()).annotate(32).into()), diff --git a/zokrates_core/src/static_analysis/uint_optimizer.rs b/zokrates_core/src/static_analysis/uint_optimizer.rs index 5b856f059..30c0034ef 100644 --- a/zokrates_core/src/static_analysis/uint_optimizer.rs +++ b/zokrates_core/src/static_analysis/uint_optimizer.rs @@ -319,7 +319,7 @@ impl<'ast, T: Field> Folder<'ast, T> for UintOptimizer<'ast, T> { force_no_reduce(consequence), force_no_reduce(alternative), ) - .with_max(max) + .with_max(T::try_from(max).unwrap()) } }; diff --git a/zokrates_field/src/lib.rs b/zokrates_field/src/lib.rs index ab5a2a7af..519d0501d 100644 --- a/zokrates_field/src/lib.rs +++ b/zokrates_field/src/lib.rs @@ -9,7 +9,7 @@ use bellman_ce::pairing::Engine; use num_bigint::BigUint; use num_traits::{One, Zero}; use serde::{Deserialize, Serialize}; -use std::convert::From; +use std::convert::{From, TryFrom}; use std::fmt::{Debug, Display}; use std::hash::Hash; use std::ops::{Add, Div, Mul, Sub}; @@ -24,7 +24,7 @@ pub trait Field: + From + From + From - + From + + TryFrom + Zero + One + Clone @@ -130,6 +130,7 @@ mod prime_field { use num_traits::{One, Zero}; use serde_derive::{Deserialize, Serialize}; use std::convert::From; + use std::convert::TryFrom; use std::fmt; use std::fmt::{Debug, Display}; use std::ops::{Add, Div, Mul, Sub}; @@ -298,11 +299,18 @@ mod prime_field { } } - impl From for FieldPrime { - fn from(num: BigUint) -> Self { - let x = ToBigInt::to_bigint(&num).unwrap(); - FieldPrime { - value: &x - x.div_floor(&*P) * &*P, + impl TryFrom for FieldPrime { + type Error = (); + + fn try_from(value: BigUint) -> Result { + match value <= Self::max_value().to_biguint() { + true => { + let x = ToBigInt::to_bigint(&value).unwrap(); + Ok(FieldPrime { + value: &x - x.div_floor(&*P) * &*P, + }) + } + false => Err(()), } } } From d99eed7939042c9f59dc5e705587ac5380f8652e Mon Sep 17 00:00:00 2001 From: dark64 Date: Thu, 17 Sep 2020 19:26:48 +0200 Subject: [PATCH 15/54] fix solidity pairing lib v2, test both abi versions in integration tests --- zokrates_cli/tests/integration.rs | 60 ++++++++++++---------- zokrates_core/src/proof_system/solidity.rs | 18 +++---- 2 files changed, 41 insertions(+), 37 deletions(-) diff --git a/zokrates_cli/tests/integration.rs b/zokrates_cli/tests/integration.rs index 8b4ae83be..e36b90508 100644 --- a/zokrates_cli/tests/integration.rs +++ b/zokrates_cli/tests/integration.rs @@ -240,22 +240,6 @@ mod integration { .succeeds() .unwrap(); - // EXPORT-VERIFIER - assert_cli::Assert::command(&[ - "../target/release/zokrates", - "export-verifier", - "-i", - verification_key_path.to_str().unwrap(), - "-o", - verification_contract_path.to_str().unwrap(), - "--backend", - backend, - "--proving-scheme", - scheme, - ]) - .succeeds() - .unwrap(); - // GENERATE-PROOF assert_cli::Assert::command(&[ "../target/release/zokrates", @@ -292,18 +276,38 @@ mod integration { .succeeds() .unwrap(); - // TEST VERIFIER - assert_cli::Assert::command(&[ - "node", - "test.js", - verification_contract_path.to_str().unwrap(), - proof_path.to_str().unwrap(), - scheme, - "v1", - ]) - .current_dir(concat!(env!("OUT_DIR"), "/contract")) - .succeeds() - .unwrap(); + for abi_version in &["v1", "v2"] { + // EXPORT-VERIFIER + assert_cli::Assert::command(&[ + "../target/release/zokrates", + "export-verifier", + "-i", + verification_key_path.to_str().unwrap(), + "-o", + verification_contract_path.to_str().unwrap(), + "--backend", + backend, + "--proving-scheme", + scheme, + "-a", + abi_version, + ]) + .succeeds() + .unwrap(); + + // TEST VERIFIER + assert_cli::Assert::command(&[ + "node", + "test.js", + verification_contract_path.to_str().unwrap(), + proof_path.to_str().unwrap(), + scheme, + abi_version, + ]) + .current_dir(concat!(env!("OUT_DIR"), "/contract")) + .succeeds() + .unwrap(); + } } } } diff --git a/zokrates_core/src/proof_system/solidity.rs b/zokrates_core/src/proof_system/solidity.rs index bb6b6eb88..fbcc82c69 100644 --- a/zokrates_core/src/proof_system/solidity.rs +++ b/zokrates_core/src/proof_system/solidity.rs @@ -435,7 +435,7 @@ library Pairing { return G1Point(p.X, q - (p.Y % q)); } /// @return r the sum of two points of G1 - function addition(G1Point memory p1, G1Point memory p2) internal returns (G1Point memory r) { + function addition(G1Point memory p1, G1Point memory p2) internal view returns (G1Point memory r) { uint[4] memory input; input[0] = p1.X; input[1] = p1.Y; @@ -443,14 +443,14 @@ library Pairing { input[3] = p2.Y; bool success; assembly { - success := call(sub(gas(), 2000), 6, 0, input, 0xc0, r, 0x60) + success := staticcall(sub(gas(), 2000), 6, input, 0xc0, r, 0x60) // Use "invalid" to make gas estimation work switch success case 0 { invalid() } } require(success); } /// @return r the sum of two points of G2 - function addition(G2Point memory p1, G2Point memory p2) internal returns (G2Point memory r) { + function addition(G2Point memory p1, G2Point memory p2) internal view returns (G2Point memory r) { (r.X[1], r.X[0], r.Y[1], r.Y[0]) = BN256G2.ECTwistAdd(p1.X[1],p1.X[0],p1.Y[1],p1.Y[0],p2.X[1],p2.X[0],p2.Y[1],p2.Y[0]); } /// @return r the product of a point on G1 and a scalar, i.e. @@ -462,7 +462,7 @@ library Pairing { input[2] = s; bool success; assembly { - success := call(sub(gas(), 2000), 7, 0, input, 0x80, r, 0x60) + success := staticcall(sub(gas(), 2000), 7, input, 0x80, r, 0x60) // Use "invalid" to make gas estimation work switch success case 0 { invalid() } } @@ -472,7 +472,7 @@ library Pairing { /// e(p1[0], p2[0]) * .... * e(p1[n], p2[n]) == 1 /// For example pairing([P1(), P1().negate()], [P2(), P2()]) should /// return true. - function pairing(G1Point[] memory p1, G2Point[] memory p2) internal returns (bool) { + function pairing(G1Point[] memory p1, G2Point[] memory p2) internal view returns (bool) { require(p1.length == p2.length); uint elements = p1.length; uint inputSize = elements * 6; @@ -489,7 +489,7 @@ library Pairing { uint[1] memory out; bool success; assembly { - success := call(sub(gas(), 2000), 8, 0, add(input, 0x20), mul(inputSize, 0x20), out, 0x20) + success := staticcall(sub(gas(), 2000), 8, add(input, 0x20), mul(inputSize, 0x20), out, 0x20) // Use "invalid" to make gas estimation work switch success case 0 { invalid() } } @@ -497,7 +497,7 @@ library Pairing { return out[0] != 0; } /// Convenience method for a pairing check for two pairs. - function pairingProd2(G1Point memory a1, G2Point memory a2, G1Point memory b1, G2Point memory b2) internal returns (bool) { + function pairingProd2(G1Point memory a1, G2Point memory a2, G1Point memory b1, G2Point memory b2) internal view returns (bool) { G1Point[] memory p1 = new G1Point[](2); G2Point[] memory p2 = new G2Point[](2); p1[0] = a1; @@ -511,7 +511,7 @@ library Pairing { G1Point memory a1, G2Point memory a2, G1Point memory b1, G2Point memory b2, G1Point memory c1, G2Point memory c2 - ) internal returns (bool) { + ) internal view returns (bool) { G1Point[] memory p1 = new G1Point[](3); G2Point[] memory p2 = new G2Point[](3); p1[0] = a1; @@ -528,7 +528,7 @@ library Pairing { G1Point memory b1, G2Point memory b2, G1Point memory c1, G2Point memory c2, G1Point memory d1, G2Point memory d2 - ) internal returns (bool) { + ) internal view returns (bool) { G1Point[] memory p1 = new G1Point[](4); G2Point[] memory p2 = new G2Point[](4); p1[0] = a1; From d7c45e5bd0324cab8ed73a0408ec49f0e38a3a58 Mon Sep 17 00:00:00 2001 From: dark64 Date: Tue, 22 Sep 2020 11:07:24 +0200 Subject: [PATCH 16/54] fix integration test --- Cargo.lock | 8 ++--- zokrates_cli/tests/contract/test.js | 56 +++++++++++++---------------- 2 files changed, 29 insertions(+), 35 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 1d8d7ac1a..d3e6605e6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1744,7 +1744,7 @@ dependencies = [ [[package]] name = "zokrates_cli" -version = "0.6.0" +version = "0.6.1" dependencies = [ "assert_cli", "bincode", @@ -1767,7 +1767,7 @@ version = "0.1.0" [[package]] name = "zokrates_core" -version = "0.5.0" +version = "0.5.1" dependencies = [ "assert_cli", "bellman_ce", @@ -1825,7 +1825,7 @@ dependencies = [ [[package]] name = "zokrates_fs_resolver" -version = "0.5.0" +version = "0.5.1" dependencies = [ "tempfile", "zokrates_common", @@ -1863,7 +1863,7 @@ dependencies = [ [[package]] name = "zokrates_test" -version = "0.1.2" +version = "0.1.3" dependencies = [ "fs_extra", "glob 0.3.0", diff --git a/zokrates_cli/tests/contract/test.js b/zokrates_cli/tests/contract/test.js index f22194d80..ef6e34136 100644 --- a/zokrates_cli/tests/contract/test.js +++ b/zokrates_cli/tests/contract/test.js @@ -28,8 +28,8 @@ let jsonContractSource = JSON.stringify({ let jsonInterface = JSON.parse(solc.compile(jsonContractSource)); (async () => { const accounts = await web3.eth.getAccounts(); - let abi = jsonInterface.contracts[contractPath]["Verifier"].abi - let bytecode = jsonInterface.contracts[contractPath]["Verifier"].evm.bytecode + let abi = jsonInterface.contracts[contractPath]["Verifier"].abi; + let bytecode = jsonInterface.contracts[contractPath]["Verifier"].evm.bytecode; //There is a solc issue, that for unknown reasons wont link the BN256G2 Library automatically for gm17 v1 and v2 contracts. I dont know why this is happening, //the contracts compile and deploy without any issue on remix. To fix this, the the BN256G2 Library must be compiled and deployed by itself, after that, @@ -37,7 +37,7 @@ let jsonInterface = JSON.parse(solc.compile(jsonContractSource)); if (format == "gm17") { let library = await deployLibrary(); //replace lib placeholder with lib address in bytecode - bytecode.object = bytecode.object.replace(/\_\_\$[a-f0-9]{34}\$\_\_/g, library["_address"].replace("0x", "")) + bytecode.object = bytecode.object.replace(/\_\_\$[a-f0-9]{34}\$\_\_/g, library["_address"].replace("0x", "")); } let contract = new web3.eth.Contract(abi) @@ -50,38 +50,38 @@ let jsonInterface = JSON.parse(solc.compile(jsonContractSource)); }) .on('receipt', (tx) => { if (tx.status == true) { - console.log("Contract Deployed! Gas used: " + tx.gasUsed) + console.log("Contract Deployed! Gas used: " + tx.gasUsed); } }) .then(newContractInstance => { contract = newContractInstance; - Promise.all([makeTransaction(accounts[0], true), makeTransaction(accounts[0], false)]) + Promise.all([makeTransaction(accounts[0], true), makeTransaction(accounts[0], false)]); }) .catch(err => { console.log(err); process.exit(1); - }) + }); function makeTransaction(account, correct) { let proof = getProof(correct); function handleReceipt(tx) { if (tx.status == true && !correct) { - console.log("Verification has been successful with invalid proof data! THIS IS A BUG") - process.exit(1) + console.log("Verification has been successful with invalid proof data! THIS IS A BUG"); + process.exit(1); } if (tx.status == true) { - console.log("Correct proof works! Gas used: " + tx.gasUsed) + console.log("Correct proof works! Gas used: " + tx.gasUsed); } } function handleError(err, correct) { if (!correct) { - console.log("False proof not verified! Success") + console.log("False proof not verified! Success"); } else { console.log(err); - process.exit(1) + process.exit(1); } } @@ -90,46 +90,40 @@ let jsonInterface = JSON.parse(solc.compile(jsonContractSource)); .catch(handleError) : verifyTx_ABIV2(proof, account, correct).on('receipt', handleReceipt) - .catch(handleError) + .catch(handleError); } function verifyTx_ABIV2(proof, account, correct) { + var args = proof[0]; + args = proof[1].length > 0 ? [args, proof[1]] : args; - var arguments = proof[0] - arguments = proof[1].length > 0 ? [arguments[0], proof[1]] : arguments - - contract.methods.verifyTx(...arguments).send({ + return contract.methods.verifyTx(...args).send({ from: account, gas: 5000000 - }) + }); } function verifyTx_ABIV1(proof, account, correct) { - - var arguments = proof[0] - arguments = proof[1].length > 0 ? [...arguments, proof[1]] : arguments + var args = proof[0]; + args = proof[1].length > 0 ? [...args, proof[1]] : args; return contract.methods.verifyTx( - ...arguments + ...args ).send({ from: account, gas: 5000000 - }) + }); } function getProof(correct) { let json = JSON.parse(fs.readFileSync(proofPath)); let inputs = json["inputs"]; - let proof = json["proof"] + let proof = json["proof"]; //falsifies proof to check if verification fails if (!correct) { proof["a"][0] = "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; } - if (abiVersion == "v1") { - return [Object.values(proof), Object.values(inputs)]; - } else if (abiVersion == "v2") { - return [proof, inputs] - } + return [Object.values(proof), Object.values(inputs)]; } //function used for deploying BN256G2 Library, used for gm17 only @@ -150,8 +144,8 @@ let jsonInterface = JSON.parse(solc.compile(jsonContractSource)); }, }); let jsonInterfaceBin = JSON.parse(solc.compile(jsonContractSourceBin)); - let abiLib = jsonInterfaceBin.contracts["BN256G2"]["BN256G2"].abi - let bytecodeLib = jsonInterfaceBin.contracts["BN256G2"]['BN256G2'].evm.bytecode + let abiLib = jsonInterfaceBin.contracts["BN256G2"]["BN256G2"].abi; + let bytecodeLib = jsonInterfaceBin.contracts["BN256G2"]['BN256G2'].evm.bytecode; return new web3.eth.Contract(abiLib) .deploy({ data: '0x' + bytecodeLib.object @@ -165,6 +159,6 @@ let jsonInterface = JSON.parse(solc.compile(jsonContractSource)); console.log("Library couldn't be deployed"); process.exit(1); } - }) + }); } })(); \ No newline at end of file From 3dec9d6cb02289a1e52782a61633216a0ae16eec Mon Sep 17 00:00:00 2001 From: dark64 Date: Tue, 22 Sep 2020 11:49:55 +0200 Subject: [PATCH 17/54] add SPDX license identifier --- zokrates_core/src/proof_system/solidity.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zokrates_core/src/proof_system/solidity.rs b/zokrates_core/src/proof_system/solidity.rs index fbcc82c69..283fe70b9 100644 --- a/zokrates_core/src/proof_system/solidity.rs +++ b/zokrates_core/src/proof_system/solidity.rs @@ -1,4 +1,4 @@ -pub const SOLIDITY_G2_ADDITION_LIB: &str = r#"// This file is LGPL3 Licensed +pub const SOLIDITY_G2_ADDITION_LIB: &str = r#"// SPDX-License-Identifier: LGPL-3.0-only pragma solidity ^0.6.1; /** From 129902491fc1146c2de87ed5d106fb9a0b4b0d20 Mon Sep 17 00:00:00 2001 From: dark64 Date: Tue, 22 Sep 2020 13:11:23 +0200 Subject: [PATCH 18/54] fix undeclared input in contract --- zokrates_cli/tests/contract/test.js | 3 ++- zokrates_core/src/proof_system/bellman/groth16.rs | 2 +- zokrates_core/src/proof_system/libsnark/gm17.rs | 4 ++-- zokrates_core/src/proof_system/libsnark/pghr13.rs | 4 ++-- 4 files changed, 7 insertions(+), 6 deletions(-) diff --git a/zokrates_cli/tests/contract/test.js b/zokrates_cli/tests/contract/test.js index ef6e34136..d6f20a28f 100644 --- a/zokrates_cli/tests/contract/test.js +++ b/zokrates_cli/tests/contract/test.js @@ -26,6 +26,7 @@ let jsonContractSource = JSON.stringify({ }); let jsonInterface = JSON.parse(solc.compile(jsonContractSource)); +console.log(jsonInterface); (async () => { const accounts = await web3.eth.getAccounts(); let abi = jsonInterface.contracts[contractPath]["Verifier"].abi; @@ -95,7 +96,7 @@ let jsonInterface = JSON.parse(solc.compile(jsonContractSource)); function verifyTx_ABIV2(proof, account, correct) { var args = proof[0]; - args = proof[1].length > 0 ? [args, proof[1]] : args; + args = proof[1].length > 0 ? [args, proof[1]] : [args]; return contract.methods.verifyTx(...args).send({ from: account, diff --git a/zokrates_core/src/proof_system/bellman/groth16.rs b/zokrates_core/src/proof_system/bellman/groth16.rs index a75611c38..044243358 100644 --- a/zokrates_core/src/proof_system/bellman/groth16.rs +++ b/zokrates_core/src/proof_system/bellman/groth16.rs @@ -315,7 +315,7 @@ contract Verifier { function verifyTx( Proof memory proof<%input_argument%> ) public view returns (bool r) { - uint[] memory inputValues = new uint[](input.length); + uint[] memory inputValues = new uint[](<%vk_input_length%>); <%input_loop%> if (verify(inputValues, proof) == 0) { return true; diff --git a/zokrates_core/src/proof_system/libsnark/gm17.rs b/zokrates_core/src/proof_system/libsnark/gm17.rs index cb3f36509..70542e669 100644 --- a/zokrates_core/src/proof_system/libsnark/gm17.rs +++ b/zokrates_core/src/proof_system/libsnark/gm17.rs @@ -322,7 +322,7 @@ contract Verifier { function verifyTx( Proof memory proof<%input_argument%> ) public view returns (bool r) { - uint[] memory inputValues = new uint[](input.length); + uint[] memory inputValues = new uint[](<%vk_input_length%>); <%input_loop%> if (verify(inputValues, proof) == 0) { return true; @@ -390,7 +390,7 @@ contract Verifier { proof.a = Pairing.G1Point(a[0], a[1]); proof.b = Pairing.G2Point([b[0][0], b[0][1]], [b[1][0], b[1][1]]); proof.c = Pairing.G1Point(c[0], c[1]); - uint[] memory inputValues = new uint[](input.length); + uint[] memory inputValues = new uint[](<%vk_input_length%>); <%input_loop%> if (verify(inputValues, proof) == 0) { return true; diff --git a/zokrates_core/src/proof_system/libsnark/pghr13.rs b/zokrates_core/src/proof_system/libsnark/pghr13.rs index 27de4416f..f9adb3a97 100644 --- a/zokrates_core/src/proof_system/libsnark/pghr13.rs +++ b/zokrates_core/src/proof_system/libsnark/pghr13.rs @@ -345,7 +345,7 @@ const CONTRACT_TEMPLATE_V2: &str = r#"contract Verifier { function verifyTx( Proof memory proof<%input_argument%> ) public view returns (bool r) { - uint[] memory inputValues = new uint[](input.length); + uint[] memory inputValues = new uint[](<%vk_input_length%>); <%input_loop%> if (verify(inputValues, proof) == 0) { return true; @@ -434,7 +434,7 @@ const CONTRACT_TEMPLATE: &str = r#"contract Verifier { proof.c_p = Pairing.G1Point(c_p[0], c_p[1]); proof.h = Pairing.G1Point(h[0], h[1]); proof.k = Pairing.G1Point(k[0], k[1]); - uint[] memory inputValues = new uint[](input.length); + uint[] memory inputValues = new uint[](<%vk_input_length%>); <%input_loop%> if (verify(inputValues, proof) == 0) { return true; From 79f23f8139b65b019dcb5df16ad910eeadddd124 Mon Sep 17 00:00:00 2001 From: dark64 Date: Tue, 22 Sep 2020 13:36:59 +0200 Subject: [PATCH 19/54] remove euclidean division, comment JUBJUBE from babyjubjubParams --- zokrates_field/src/lib.rs | 4 +--- zokrates_js/Cargo.lock | 4 ++-- zokrates_js/package-lock.json | 2 +- zokrates_js/tests/tests.js | 2 +- zokrates_stdlib/stdlib/ecc/babyjubjubParams.zok | 6 +++--- 5 files changed, 8 insertions(+), 10 deletions(-) diff --git a/zokrates_field/src/lib.rs b/zokrates_field/src/lib.rs index 519d0501d..8683aba97 100644 --- a/zokrates_field/src/lib.rs +++ b/zokrates_field/src/lib.rs @@ -306,9 +306,7 @@ mod prime_field { match value <= Self::max_value().to_biguint() { true => { let x = ToBigInt::to_bigint(&value).unwrap(); - Ok(FieldPrime { - value: &x - x.div_floor(&*P) * &*P, - }) + Ok(FieldPrime { value: x }) } false => Err(()), } diff --git a/zokrates_js/Cargo.lock b/zokrates_js/Cargo.lock index 1f7873660..d2ecb22a1 100644 --- a/zokrates_js/Cargo.lock +++ b/zokrates_js/Cargo.lock @@ -1028,7 +1028,7 @@ version = "0.1.0" [[package]] name = "zokrates_core" -version = "0.5.0" +version = "0.5.1" dependencies = [ "bellman_ce", "bincode 0.8.0", @@ -1070,7 +1070,7 @@ dependencies = [ [[package]] name = "zokrates_js" -version = "1.0.24" +version = "1.0.25" dependencies = [ "bincode 1.3.1", "console_error_panic_hook", diff --git a/zokrates_js/package-lock.json b/zokrates_js/package-lock.json index 1bd95d2df..a405cf014 100644 --- a/zokrates_js/package-lock.json +++ b/zokrates_js/package-lock.json @@ -1,6 +1,6 @@ { "name": "zokrates-js", - "version": "1.0.24", + "version": "1.0.25", "lockfileVersion": 1, "requires": true, "dependencies": { diff --git a/zokrates_js/tests/tests.js b/zokrates_js/tests/tests.js index 57d4a79ca..768b6780e 100644 --- a/zokrates_js/tests/tests.js +++ b/zokrates_js/tests/tests.js @@ -26,7 +26,7 @@ describe('tests', function() { it('should resolve stdlib module', function() { const stdlib = require('../stdlib.json'); assert.doesNotThrow(() => { - const code = `import "${Object.keys(stdlib)[0]}" as func\ndef main(): return`; + const code = `import "${Object.keys(stdlib)[0]}" as func\ndef main() -> (): return`; this.zokrates.compile(code); }); }); diff --git a/zokrates_stdlib/stdlib/ecc/babyjubjubParams.zok b/zokrates_stdlib/stdlib/ecc/babyjubjubParams.zok index 53bf7b8f2..fcc433b1f 100644 --- a/zokrates_stdlib/stdlib/ecc/babyjubjubParams.zok +++ b/zokrates_stdlib/stdlib/ecc/babyjubjubParams.zok @@ -4,7 +4,7 @@ // Note: parameters will be updated soon to be more compatible with zCash's implementation struct BabyJubJubParams { - field JUBJUBE + // field JUBJUBE field JUBJUBC field JUBJUBA field JUBJUBD @@ -18,7 +18,7 @@ struct BabyJubJubParams { def main() -> BabyJubJubParams: // Order of the curve E - field JUBJUBE = 21888242871839275222246405745257275088614511777268538073601725287587578984328 + // field JUBJUBE = 21888242871839275222246405745257275088614511777268538073601725287587578984328 field JUBJUBC = 8 // Cofactor field JUBJUBA = 168700 // Coefficient A field JUBJUBD = 168696 // Coefficient D @@ -40,7 +40,7 @@ return BabyJubJubParams { INFINITY: INFINITY, Gu: Gu, Gv: Gv, - JUBJUBE: JUBJUBE, + // JUBJUBE: JUBJUBE, JUBJUBC: JUBJUBC, MONTA: MONTA, MONTB: MONTB From 558788f8d4c0a5c01554befb3d17ce86f1227342 Mon Sep 17 00:00:00 2001 From: dark64 Date: Tue, 22 Sep 2020 20:15:29 +0200 Subject: [PATCH 20/54] fix mimc7 tests, remove unused config param in zokrates_js --- zokrates_js/src/lib.rs | 1 - zokrates_js/tests/tests.js | 2 +- zokrates_stdlib/tests/tests/hashes/mimc7/mimc7R10.zok | 3 --- zokrates_stdlib/tests/tests/hashes/mimc7/mimc7R20.zok | 3 --- zokrates_stdlib/tests/tests/hashes/mimc7/mimc7R50.zok | 3 --- zokrates_stdlib/tests/tests/hashes/mimc7/mimc7R90.zok | 3 --- zokrates_stdlib/tests/tests/hashes/mimcSponge/mimcSponge.zok | 5 ++--- 7 files changed, 3 insertions(+), 17 deletions(-) diff --git a/zokrates_js/src/lib.rs b/zokrates_js/src/lib.rs index f888f9a11..e4fa9d59a 100644 --- a/zokrates_js/src/lib.rs +++ b/zokrates_js/src/lib.rs @@ -97,7 +97,6 @@ pub fn compile( source: JsValue, location: JsValue, resolve_callback: &js_sys::Function, - config: JsValue, ) -> Result { let resolver = JsResolver::new(resolve_callback); diff --git a/zokrates_js/tests/tests.js b/zokrates_js/tests/tests.js index 768b6780e..57d4a79ca 100644 --- a/zokrates_js/tests/tests.js +++ b/zokrates_js/tests/tests.js @@ -26,7 +26,7 @@ describe('tests', function() { it('should resolve stdlib module', function() { const stdlib = require('../stdlib.json'); assert.doesNotThrow(() => { - const code = `import "${Object.keys(stdlib)[0]}" as func\ndef main() -> (): return`; + const code = `import "${Object.keys(stdlib)[0]}" as func\ndef main(): return`; this.zokrates.compile(code); }); }); diff --git a/zokrates_stdlib/tests/tests/hashes/mimc7/mimc7R10.zok b/zokrates_stdlib/tests/tests/hashes/mimc7/mimc7R10.zok index aa935a7f7..d41fc8c07 100644 --- a/zokrates_stdlib/tests/tests/hashes/mimc7/mimc7R10.zok +++ b/zokrates_stdlib/tests/tests/hashes/mimc7/mimc7R10.zok @@ -3,7 +3,4 @@ import "hashes/mimc7/mimc7R10" def main(): assert(mimc7R10(0, 0) == 6004544488495356385698286530147974336054653445122716140990101827963729149289) assert(mimc7R10(100, 0) == 2977550761518141183167168643824354554080911485709001361112529600968315693145) - assert(mimc7R10(100, 21888242871839275222246405745257275088548364400416034343698204186575808495617) == 2977550761518141183167168643824354554080911485709001361112529600968315693145) - assert(mimc7R10(21888242871839275222246405745257275088548364400416034343698204186575808495618, 1) == 11476724043755138071320043459606423473319855817296339514744600646762741571430) - assert(mimc7R10(21888242871839275222246405745257275088548364400416034343698204186575808495617, 21888242871839275222246405745257275088548364400416034343698204186575808495617) == 6004544488495356385698286530147974336054653445122716140990101827963729149289) return \ No newline at end of file diff --git a/zokrates_stdlib/tests/tests/hashes/mimc7/mimc7R20.zok b/zokrates_stdlib/tests/tests/hashes/mimc7/mimc7R20.zok index b72fe66cc..6ef79bbb9 100644 --- a/zokrates_stdlib/tests/tests/hashes/mimc7/mimc7R20.zok +++ b/zokrates_stdlib/tests/tests/hashes/mimc7/mimc7R20.zok @@ -3,7 +3,4 @@ import "hashes/mimc7/mimc7R20" def main(): assert(mimc7R20(0, 0) == 19139739902058628561064841933381604453445216873412991992755775746150759284829) assert(mimc7R20(100, 0) == 8623418512398828792274158979964869393034224267928014534933203776818702139758) - assert(mimc7R20(100, 21888242871839275222246405745257275088548364400416034343698204186575808495617) == 8623418512398828792274158979964869393034224267928014534933203776818702139758) - assert(mimc7R20(21888242871839275222246405745257275088548364400416034343698204186575808495618, 1) == 15315177265066649795408805007175121550344555424263995530745989936206840798041) - assert(mimc7R20(21888242871839275222246405745257275088548364400416034343698204186575808495617, 21888242871839275222246405745257275088548364400416034343698204186575808495617) == 19139739902058628561064841933381604453445216873412991992755775746150759284829) return \ No newline at end of file diff --git a/zokrates_stdlib/tests/tests/hashes/mimc7/mimc7R50.zok b/zokrates_stdlib/tests/tests/hashes/mimc7/mimc7R50.zok index 500d6a9e7..2f6e513ff 100644 --- a/zokrates_stdlib/tests/tests/hashes/mimc7/mimc7R50.zok +++ b/zokrates_stdlib/tests/tests/hashes/mimc7/mimc7R50.zok @@ -3,7 +3,4 @@ import "hashes/mimc7/mimc7R50" def main(): assert(mimc7R50(0, 0) == 3049953358280347916081509186284461274525472221619157672645224540758481713173) assert(mimc7R50(100, 0) == 18511388995652647480418174218630545482006454713617579894396683237092568946789) - assert(mimc7R50(100, 21888242871839275222246405745257275088548364400416034343698204186575808495617) == 18511388995652647480418174218630545482006454713617579894396683237092568946789) - assert(mimc7R50(21888242871839275222246405745257275088548364400416034343698204186575808495618, 1) == 9149577627043020462780389988155990926223727917856424056384664564191878439702) - assert(mimc7R50(21888242871839275222246405745257275088548364400416034343698204186575808495617, 21888242871839275222246405745257275088548364400416034343698204186575808495617) == 3049953358280347916081509186284461274525472221619157672645224540758481713173) return \ No newline at end of file diff --git a/zokrates_stdlib/tests/tests/hashes/mimc7/mimc7R90.zok b/zokrates_stdlib/tests/tests/hashes/mimc7/mimc7R90.zok index 4d31337ad..0f197d0c0 100644 --- a/zokrates_stdlib/tests/tests/hashes/mimc7/mimc7R90.zok +++ b/zokrates_stdlib/tests/tests/hashes/mimc7/mimc7R90.zok @@ -3,7 +3,4 @@ import "hashes/mimc7/mimc7R90" def main(): assert(mimc7R90(0, 0) == 20281265111705407344053532742843085357648991805359414661661476832595822221514) assert(mimc7R90(100, 0) == 1010054095264022068840870550831559811104631937745987065544478027572003292636) - assert(mimc7R90(100, 21888242871839275222246405745257275088548364400416034343698204186575808495617) == 1010054095264022068840870550831559811104631937745987065544478027572003292636) - assert(mimc7R90(21888242871839275222246405745257275088548364400416034343698204186575808495618, 1) == 8189519586469873426687580455476035992041353456517724932462363814215190642760) - assert(mimc7R90(21888242871839275222246405745257275088548364400416034343698204186575808495617, 21888242871839275222246405745257275088548364400416034343698204186575808495617) == 20281265111705407344053532742843085357648991805359414661661476832595822221514) return \ No newline at end of file diff --git a/zokrates_stdlib/tests/tests/hashes/mimcSponge/mimcSponge.zok b/zokrates_stdlib/tests/tests/hashes/mimcSponge/mimcSponge.zok index 5ada9cc50..4ce6771bc 100644 --- a/zokrates_stdlib/tests/tests/hashes/mimcSponge/mimcSponge.zok +++ b/zokrates_stdlib/tests/tests/hashes/mimcSponge/mimcSponge.zok @@ -1,7 +1,6 @@ import "hashes/mimcSponge/mimcSponge" as mimcSponge def main(): - assert(mimcSponge([1,2], 3) == [20225509322021146255705869525264566735642015554514977326536820959638320229084,13871743498877225461925335509899475799121918157213219438898506786048812913771,21633608428713573518356618235457250173701815120501233429160399974209848779097]) - assert(mimcSponge([0,0], 0) == [20636625426020718969131298365984859231982649550971729229988535915544421356929,6046202021237334713296073963481784771443313518730771623154467767602059802325,16227963524034219233279650312501310147918176407385833422019760797222680144279]) - assert(mimcSponge([21888242871839275222246405745257275088548364400416034343698204186575808495617, 0], 0) == [20636625426020718969131298365984859231982649550971729229988535915544421356929,6046202021237334713296073963481784771443313518730771623154467767602059802325,16227963524034219233279650312501310147918176407385833422019760797222680144279]) + assert(mimcSponge([1,2], 3) == [20225509322021146255705869525264566735642015554514977326536820959638320229084, 13871743498877225461925335509899475799121918157213219438898506786048812913771, 21633608428713573518356618235457250173701815120501233429160399974209848779097]) + assert(mimcSponge([0,0], 0) == [20636625426020718969131298365984859231982649550971729229988535915544421356929, 6046202021237334713296073963481784771443313518730771623154467767602059802325, 16227963524034219233279650312501310147918176407385833422019760797222680144279]) return \ No newline at end of file From 287b2b8f47d3c26cb4b957921213e509e057a3f1 Mon Sep 17 00:00:00 2001 From: dark64 Date: Wed, 23 Sep 2020 21:08:31 +0200 Subject: [PATCH 21/54] zexe iter-1 --- .github/workflows/make-gpr-docker-image.yml | 23 + Cargo.lock | 680 +++++++++++++----- ey.Dockerfile | 18 + test/test.code | 9 + .../book/hashexample_updated_bls12_377.zok | 7 + .../book/hashexample_updated_bw6_761.zok | 7 + zokrates_cli/src/bin.rs | 110 ++- zokrates_cli/src/constants.rs | 14 +- zokrates_cli/src/helpers.rs | 25 +- zokrates_cli/tests/integration.rs | 59 +- zokrates_core/Cargo.toml | 20 +- zokrates_core/src/ir/interpreter.rs | 1 + zokrates_core/src/ir/serialize.rs | 18 +- zokrates_core/src/lib.rs | 8 + .../src/proof_system/bellman/groth16.rs | 45 +- zokrates_core/src/proof_system/bellman/mod.rs | 25 +- .../src/proof_system/libsnark/ffi.rs | 5 +- .../src/proof_system/libsnark/gm17.rs | 33 +- .../src/proof_system/libsnark/pghr13.rs | 38 +- zokrates_core/src/proof_system/mod.rs | 51 +- zokrates_core/src/proof_system/solidity.rs | 15 + zokrates_core/src/proof_system/zexe/gm17.rs | 365 ++++++++++ zokrates_core/src/proof_system/zexe/mod.rs | 304 ++++++++ zokrates_core_test/tests/tests/add.json | 4 +- zokrates_core_test/tests/tests/array_if.json | 4 +- .../tests/tests/arrays/identity.json | 4 +- .../tests/tests/assert_one.json | 4 +- .../tests/tests/bool_compare.json | 4 +- .../tests/tests/fact_up_to_4.json | 4 +- .../tests/tests/precedence.json | 4 +- zokrates_core_test/tests/tests/split_bls.json | 8 +- .../tests/tests/spread_slice.json | 4 +- .../tests/tests/structs/identity.json | 4 +- zokrates_field/Cargo.toml | 9 +- zokrates_field/src/bls12_377.rs | 7 + zokrates_field/src/bls12_381.rs | 3 +- zokrates_field/src/bn128.rs | 7 +- zokrates_field/src/bw6_761.rs | 8 + zokrates_field/src/lib.rs | 148 +++- .../hashes/sha256/512bitPacked_bls12_377.zok | 19 + .../hashes/sha256/512bitPacked_bw6_761.zok | 19 + .../stdlib/utils/pack/bool/pack256.zok | 2 +- .../stdlib/utils/pack/u32/pack128.zok | 4 +- .../stdlib/utils/pack/u32/pack256.zok | 4 +- .../bool/nonStrictUnpack256.zok | 13 + .../utils/pack_bls12_377/bool/unpack128.zok | 11 + .../pack_bls12_377/u32/nonStrictUnpack256.zok | 12 + .../utils/pack_bls12_377/u32/unpack128.zok | 7 + .../utils/pack_bw6_761/bool/unpack128.zok | 11 + .../utils/pack_bw6_761/bool/unpack256.zok | 9 + .../utils/pack_bw6_761/u32/unpack128.zok | 7 + .../utils/pack_bw6_761/u32/unpack256.zok | 8 + zokrates_stdlib/stdlib/verifier/verifier.zok | 6 + .../stdlib/verifier/verifier11.zok | 7 + zokrates_stdlib/stdlib/verifier/verifier2.zok | 5 + zokrates_stdlib/stdlib/verifier/verifier5.zok | 6 + zokrates_stdlib/stdlib/verifier/verifier7.zok | 5 + zokrates_test/src/lib.rs | 10 +- 58 files changed, 1836 insertions(+), 435 deletions(-) create mode 100644 .github/workflows/make-gpr-docker-image.yml create mode 100644 ey.Dockerfile create mode 100644 test/test.code create mode 100644 zokrates_cli/examples/book/hashexample_updated_bls12_377.zok create mode 100644 zokrates_cli/examples/book/hashexample_updated_bw6_761.zok create mode 100644 zokrates_core/src/proof_system/zexe/gm17.rs create mode 100644 zokrates_core/src/proof_system/zexe/mod.rs create mode 100644 zokrates_field/src/bls12_377.rs create mode 100644 zokrates_field/src/bw6_761.rs create mode 100644 zokrates_stdlib/stdlib/hashes/sha256/512bitPacked_bls12_377.zok create mode 100644 zokrates_stdlib/stdlib/hashes/sha256/512bitPacked_bw6_761.zok create mode 100644 zokrates_stdlib/stdlib/utils/pack_bls12_377/bool/nonStrictUnpack256.zok create mode 100644 zokrates_stdlib/stdlib/utils/pack_bls12_377/bool/unpack128.zok create mode 100644 zokrates_stdlib/stdlib/utils/pack_bls12_377/u32/nonStrictUnpack256.zok create mode 100644 zokrates_stdlib/stdlib/utils/pack_bls12_377/u32/unpack128.zok create mode 100644 zokrates_stdlib/stdlib/utils/pack_bw6_761/bool/unpack128.zok create mode 100644 zokrates_stdlib/stdlib/utils/pack_bw6_761/bool/unpack256.zok create mode 100644 zokrates_stdlib/stdlib/utils/pack_bw6_761/u32/unpack128.zok create mode 100644 zokrates_stdlib/stdlib/utils/pack_bw6_761/u32/unpack256.zok create mode 100644 zokrates_stdlib/stdlib/verifier/verifier.zok create mode 100644 zokrates_stdlib/stdlib/verifier/verifier11.zok create mode 100644 zokrates_stdlib/stdlib/verifier/verifier2.zok create mode 100644 zokrates_stdlib/stdlib/verifier/verifier5.zok create mode 100644 zokrates_stdlib/stdlib/verifier/verifier7.zok diff --git a/.github/workflows/make-gpr-docker-image.yml b/.github/workflows/make-gpr-docker-image.yml new file mode 100644 index 000000000..693e33604 --- /dev/null +++ b/.github/workflows/make-gpr-docker-image.yml @@ -0,0 +1,23 @@ +name: GitHub Package Repo Docker Image + +on: + push: + branches: + - 'eyblockchain' + +jobs: + make-gpr-docker-image: + name: Image Release + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v1 + - name: Build container image + uses: mr-smithers-excellent/docker-build-push@v3 + with: + image: zokrates-zexe/zokrates_zexe + dockerfile: ey.Dockerfile + tag: ${{ github.sha }} + registry: docker.pkg.github.com + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} diff --git a/Cargo.lock b/Cargo.lock index 1d8d7ac1a..d5f613246 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1,5 +1,20 @@ # This file is automatically @generated by Cargo. # It is not intended for manual editing. +[[package]] +name = "addr2line" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b6a2d3371669ab3ca9797670853d61402b03d0b4b9ebf33d677dfa720203072" +dependencies = [ + "gimli", +] + +[[package]] +name = "adler" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee2a4ec343196209d6594e19543ae87a39f96d5534d7174822a3ad825dd6ed7e" + [[package]] name = "aho-corasick" version = "0.6.10" @@ -9,6 +24,39 @@ dependencies = [ "memchr", ] +[[package]] +name = "algebra" +version = "0.1.1-alpha.0" +source = "git+https://github.com/dark64/zexe.git?branch=dark64-patch#6d15b91fbbcd9cc9cbbb1f2783a6020be2761e64" +dependencies = [ + "algebra-core", +] + +[[package]] +name = "algebra-core" +version = "0.1.1-alpha.0" +source = "git+https://github.com/dark64/zexe.git?branch=dark64-patch#6d15b91fbbcd9cc9cbbb1f2783a6020be2761e64" +dependencies = [ + "algebra-core-derive", + "derivative", + "field-assembly", + "num-traits 0.2.12", + "rand 0.7.3", + "rayon", + "rustc_version", + "unroll", +] + +[[package]] +name = "algebra-core-derive" +version = "0.1.1-alpha.0" +source = "git+https://github.com/dark64/zexe.git?branch=dark64-patch#6d15b91fbbcd9cc9cbbb1f2783a6020be2761e64" +dependencies = [ + "proc-macro2 1.0.19", + "quote 1.0.7", + "syn 1.0.39", +] + [[package]] name = "ansi_term" version = "0.11.0" @@ -57,43 +105,35 @@ dependencies = [ [[package]] name = "autocfg" -version = "1.0.0" +version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8aac770f1885fd7e387acedd76065302551364496e46b3dd00860b2f8359b9d" +checksum = "cdb031dd78e28731d87d56cc8ffef4a8f36ca26c38fe2de700543e627f8a464a" [[package]] name = "backtrace" -version = "0.3.41" +version = "0.3.50" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4ed64ae6d9ebfd9893193c4b2532b1292ec97bd8271c9d7d0fa90cd78a34cba" +checksum = "46254cf2fdcdf1badb5934448c1bcbe046a56537b3987d96c51a7afc5d03f293" dependencies = [ - "backtrace-sys", + "addr2line", "cfg-if", "libc", + "miniz_oxide", + "object", "rustc-demangle", ] -[[package]] -name = "backtrace-sys" -version = "0.1.37" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "18fbebbe1c9d1f383a9cc7e8ccdb471b91c8d024ee9c2ca5b5346121fe8b4399" -dependencies = [ - "cc", - "libc", -] - [[package]] name = "base64" -version = "0.11.0" +version = "0.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b41b7ea54a0c9d92199de89e20e58d49f02f8e699814ef3fdf266f6f748d15c7" +checksum = "3441f0f7b02788e948e47f457ca01f1d7e6d92c693bc132c22b087d3141c03ff" [[package]] name = "bellman_ce" -version = "0.3.4" +version = "0.3.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e1a2edf80a8ed042463f8888946f70fcd901f1615711bb253b7dc32b9c9fe73" +checksum = "a5ca1343d8690bb4d62e0665116bd4f109e33a642f86908ed107d226a402b0ef" dependencies = [ "bit-vec", "byteorder", @@ -106,6 +146,11 @@ dependencies = [ "web-sys", ] +[[package]] +name = "bench-utils" +version = "0.1.1-alpha.0" +source = "git+https://github.com/dark64/zexe.git?branch=dark64-patch#6d15b91fbbcd9cc9cbbb1f2783a6020be2761e64" + [[package]] name = "bincode" version = "0.8.0" @@ -129,6 +174,18 @@ version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf1de2fe8c75bc145a2f577add951f8134889b4795d47466a54a5c846d691693" +[[package]] +name = "blake2" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94cb07b0da6a73955f8fb85d24c466778e70cda767a568229b104f0264089330" +dependencies = [ + "byte-tools", + "crypto-mac", + "digest", + "opaque-debug", +] + [[package]] name = "blake2b_simd" version = "0.5.10" @@ -203,7 +260,7 @@ version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e5d1b4d380e1bab994591a24c2bdd1b054f64b60bef483a8c598c7c345bc3bbe" dependencies = [ - "error-chain 0.12.2", + "error-chain 0.12.4", "semver", "serde", "serde_derive", @@ -212,24 +269,24 @@ dependencies = [ [[package]] name = "cc" -version = "1.0.54" +version = "1.0.59" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7bbb73db36c1246e9034e307d0fba23f9a2e251faa47ade70c1bd252220c8311" +checksum = "66120af515773fb005778dc07c261bd201ec8ce50bd6e7144c927753fe013381" dependencies = [ "jobserver", ] [[package]] name = "cfg-if" -version = "0.1.9" +version = "0.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b486ce3ccf7ffd79fdeb678eac06a9e6c09fc88d33836340becb8fffe87c5e33" +checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" [[package]] name = "clap" -version = "2.33.1" +version = "2.33.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bdfa80d47f954d53a35a64987ca1422f495b8d6483c0fe9f7117b36c2a792129" +checksum = "37e58ac78573c40708d45522f0d80fa2f01cc4f9b4e2bf749807255454312002" dependencies = [ "ansi_term", "atty", @@ -292,12 +349,12 @@ dependencies = [ [[package]] name = "crossbeam-channel" -version = "0.4.2" +version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cced8691919c02aac3cb0a1bc2e9b73d89e832bf9a06fc579d4e71b68a2da061" +checksum = "09ee0cc8804d5393478d743b035099520087a5186f3b93fa58cec08fa62407b6" dependencies = [ + "cfg-if", "crossbeam-utils", - "maybe-uninit", ] [[package]] @@ -348,6 +405,36 @@ dependencies = [ "lazy_static", ] +[[package]] +name = "crypto-mac" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4434400df11d95d556bac068ddfedd482915eb18fe8bea89bc80b6e4b1c179e5" +dependencies = [ + "generic-array", + "subtle", +] + +[[package]] +name = "crypto-primitives" +version = "0.1.1-alpha.0" +source = "git+https://github.com/dark64/zexe.git?branch=dark64-patch#6d15b91fbbcd9cc9cbbb1f2783a6020be2761e64" +dependencies = [ + "algebra-core", + "bench-utils", + "blake2", + "derivative", + "digest", + "ff-fft", + "gm17", + "groth16", + "r1cs-core", + "r1cs-std", + "rand 0.7.3", + "rayon", + "tracing", +] + [[package]] name = "csv" version = "1.1.3" @@ -372,12 +459,23 @@ dependencies = [ [[package]] name = "ctor" -version = "0.1.14" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39858aa5bac06462d4dd4b9164848eb81ffc4aa5c479746393598fd193afa227" +dependencies = [ + "quote 1.0.7", + "syn 1.0.39", +] + +[[package]] +name = "derivative" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf6b25ee9ac1995c54d7adb2eff8cfffb7260bc774fb63c601ec65467f43cd9d" +checksum = "cb582b60359da160a9477ee80f15c8d784c477e69c217ef2cdd4169c24ea380f" dependencies = [ - "quote 1.0.6", - "syn 1.0.30", + "proc-macro2 1.0.19", + "quote 1.0.7", + "syn 1.0.39", ] [[package]] @@ -423,9 +521,9 @@ dependencies = [ [[package]] name = "either" -version = "1.5.3" +version = "1.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb1f6b1ce1c140482ea30ddd3335fc0024ac7ee112895426e0a629a6c20adfe3" +checksum = "cd56b59865bce947ac5958779cfa508f6c3b9497cc762b7e24a12d11ccde2c4f" [[package]] name = "environment" @@ -444,9 +542,9 @@ dependencies = [ [[package]] name = "error-chain" -version = "0.12.2" +version = "0.12.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d371106cc88ffdfb1eabd7111e432da544f16f3e2d7bf1dfe8bf575f1df045cd" +checksum = "2d2f06b9cac1506ece98fe3231e3cc9c4410ec3d5b1f24ae1c8946f0742cdefc" dependencies = [ "backtrace", "version_check", @@ -468,9 +566,9 @@ version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aa4da3c766cd7a0db8242e326e9e4e081edd567072893ed320008189715366a4" dependencies = [ - "proc-macro2 1.0.18", - "quote 1.0.6", - "syn 1.0.30", + "proc-macro2 1.0.19", + "quote 1.0.7", + "syn 1.0.39", "synstructure", ] @@ -480,6 +578,16 @@ version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e88a8acf291dafb59c2d96e8f59828f3838bb1a70398823ade51a84de6a6deed" +[[package]] +name = "ff-fft" +version = "0.1.1-alpha.0" +source = "git+https://github.com/dark64/zexe.git?branch=dark64-patch#6d15b91fbbcd9cc9cbbb1f2783a6020be2761e64" +dependencies = [ + "algebra-core", + "rand 0.7.3", + "rayon", +] + [[package]] name = "ff_ce" version = "0.9.0" @@ -493,9 +601,9 @@ dependencies = [ [[package]] name = "ff_ce" -version = "0.10.2" +version = "0.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40ced6646e4e98a53da162e38ffe9c865edbd7a2f9ff197067b0a8bf1114bf8a" +checksum = "4592897f75fd1bd178e5ec12d9d7df3d1943464feda2cbce1e708a484e82c8f6" dependencies = [ "byteorder", "ff_derive_ce", @@ -509,12 +617,20 @@ version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "50c052fa6d4c2f12305ec364bfb8ef884836f3f61ea015b202372ff996d1ac4b" dependencies = [ - "num-bigint", + "num-bigint 0.2.6", "num-integer", - "num-traits 0.2.11", - "proc-macro2 1.0.18", - "quote 1.0.6", - "syn 1.0.30", + "num-traits 0.2.12", + "proc-macro2 1.0.19", + "quote 1.0.7", + "syn 1.0.39", +] + +[[package]] +name = "field-assembly" +version = "0.1.1-alpha.0" +source = "git+https://github.com/dark64/zexe.git?branch=dark64-patch#6d15b91fbbcd9cc9cbbb1f2783a6020be2761e64" +dependencies = [ + "mince", ] [[package]] @@ -529,9 +645,9 @@ dependencies = [ [[package]] name = "fs_extra" -version = "1.1.0" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f2a4a2034423744d2cc7ca2068453168dcdb82c438419e639a26bd87839c674" +checksum = "2022715d62ab30faffd124d40b76f4134a550a87792276512b18d63272333394" [[package]] name = "fuchsia-cprng" @@ -640,11 +756,17 @@ dependencies = [ "wasi", ] +[[package]] +name = "gimli" +version = "0.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aaf91faf136cb47367fa430cd46e37a788775e7fa104f8b4bcb3861dc389b724" + [[package]] name = "git2" -version = "0.13.6" +version = "0.13.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11e4b2082980e751c4bf4273e9cbb4a02c655729c8ee8a79f66cad03c8f4d31e" +checksum = "86d97249f21e9542caeee9f8e1d150905cd875bf723f5ff771bdb4852eb83a24" dependencies = [ "bitflags", "libc", @@ -667,11 +789,37 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b919933a397b79c37e33b77bb2aa3dc8eb6e165ad809e58ff75bc7db2e34574" +[[package]] +name = "gm17" +version = "0.1.1-alpha.0" +source = "git+https://github.com/dark64/zexe.git?branch=dark64-patch#6d15b91fbbcd9cc9cbbb1f2783a6020be2761e64" +dependencies = [ + "algebra-core", + "bench-utils", + "ff-fft", + "r1cs-core", + "rand 0.7.3", + "rayon", +] + +[[package]] +name = "groth16" +version = "0.1.1-alpha.0" +source = "git+https://github.com/dark64/zexe.git?branch=dark64-patch#6d15b91fbbcd9cc9cbbb1f2783a6020be2761e64" +dependencies = [ + "algebra-core", + "bench-utils", + "ff-fft", + "r1cs-core", + "rand 0.7.3", + "rayon", +] + [[package]] name = "hermit-abi" -version = "0.1.13" +version = "0.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91780f809e750b0a89f5544be56617ff6b1227ee485bcb06ebe10cdf89bd3b71" +checksum = "3deed196b6e7f9e44a2ae8d94225d80302d81208b1bb673fd21fe634645c85a9" dependencies = [ "libc", ] @@ -704,9 +852,9 @@ dependencies = [ [[package]] name = "itoa" -version = "0.4.5" +version = "0.4.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8b7a7c0c47db5545ed3fef7468ee7bb5b74691498139e4b3f6a20685dc6dd8e" +checksum = "dc6f3ad7b9d11a0c00842ff8de1b60ee58661048eb8049ed33c73594f359d7e6" [[package]] name = "jobserver" @@ -719,9 +867,9 @@ dependencies = [ [[package]] name = "js-sys" -version = "0.3.40" +version = "0.3.44" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce10c23ad2ea25ceca0093bd3192229da4c5b3c0f2de499c1ecac0d98d452177" +checksum = "85a7e2c92a4804dd459b86c339278d0fe87cf93757fae222c3fa3ae75458bc73" dependencies = [ "wasm-bindgen", ] @@ -734,15 +882,15 @@ checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" [[package]] name = "libc" -version = "0.2.71" +version = "0.2.76" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9457b06509d27052635f90d6466700c65095fdf75409b3fbdd903e988b886f49" +checksum = "755456fae044e6fa1ebbbd1b3e902ae19e73097ed4ed87bb79934a867c007bc3" [[package]] name = "libgit2-sys" -version = "0.12.7+1.0.0" +version = "0.12.12+1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bcd07968649bcb7b9351ecfde53ca4d27673cccfdf57c84255ec18710f3153e0" +checksum = "0100ae90655025134424939f1f60e27e879460d451dff6afedde4f8226cbebfc" dependencies = [ "cc", "libc", @@ -754,9 +902,9 @@ dependencies = [ [[package]] name = "libssh2-sys" -version = "0.2.17" +version = "0.2.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d45f516b9b19ea6c940b9f36d36734062a153a2b4cc9ef31d82c54bb9780f525" +checksum = "ca46220853ba1c512fc82826d0834d87b06bcd3c2a42241b7de72f3d2fe17056" dependencies = [ "cc", "libc", @@ -768,9 +916,9 @@ dependencies = [ [[package]] name = "libz-sys" -version = "1.0.25" +version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2eb5e43362e38e2bca2fd5f5134c4d4564a23a5c28e9b95411652021a8675ebe" +checksum = "23b34178653005c1181711c333f0e5604a14a1b5115c814fd42304bdd16245e0" dependencies = [ "cc", "libc", @@ -780,9 +928,9 @@ dependencies = [ [[package]] name = "log" -version = "0.4.8" +version = "0.4.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "14b6052be84e6b71ab17edffc2eeabf5c2c3ae1fdb464aae35ac50c67a44e1f7" +checksum = "4fabed175da42fed1fa0746b0ea71f412aa9d35e76e95e59b192c64b9dc2bf8b" dependencies = [ "cfg-if", ] @@ -813,13 +961,31 @@ checksum = "3728d817d99e5ac407411fa471ff9800a778d88a24685968b36824eaf4bee400" [[package]] name = "memoffset" -version = "0.5.4" +version = "0.5.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4fc2c02a7e374099d4ee95a193111f72d2110197fe200272371758f6c3643d8" +checksum = "c198b026e1bbf08a937e94c6c60f9ec4a2267f5b0d2eec9c1b21b061ce2be55f" dependencies = [ "autocfg", ] +[[package]] +name = "mince" +version = "0.1.1-alpha.0" +source = "git+https://github.com/dark64/zexe.git?branch=dark64-patch#6d15b91fbbcd9cc9cbbb1f2783a6020be2761e64" +dependencies = [ + "quote 1.0.7", + "syn 1.0.39", +] + +[[package]] +name = "miniz_oxide" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4d7559a8a40d0f97e1edea3220f698f78b1c5ab67532e49f68fde3910323b722" +dependencies = [ + "adler", +] + [[package]] name = "num" version = "0.1.42" @@ -828,7 +994,17 @@ checksum = "4703ad64153382334aa8db57c637364c322d3372e097840c72000dabdcf6156e" dependencies = [ "num-integer", "num-iter", - "num-traits 0.2.11", + "num-traits 0.2.12", +] + +[[package]] +name = "num-bigint" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e63899ad0da84ce718c14936262a41cee2c79c981fc0a0e7c7beb47d5a07e8c1" +dependencies = [ + "num-integer", + "num-traits 0.2.12", ] [[package]] @@ -839,29 +1015,29 @@ checksum = "090c7f9998ee0ff65aa5b723e4009f7b217707f1fb5ea551329cc4d6231fb304" dependencies = [ "autocfg", "num-integer", - "num-traits 0.2.11", + "num-traits 0.2.12", "serde", ] [[package]] name = "num-integer" -version = "0.1.42" +version = "0.1.43" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f6ea62e9d81a77cd3ee9a2a5b9b609447857f3d358704331e4ef39eb247fcba" +checksum = "8d59457e662d541ba17869cf51cf177c0b5f0cbf476c66bdc90bf1edac4f875b" dependencies = [ "autocfg", - "num-traits 0.2.11", + "num-traits 0.2.12", ] [[package]] name = "num-iter" -version = "0.1.40" +version = "0.1.41" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dfb0800a0291891dd9f4fe7bd9c19384f98f7fbe0cd0f39a2c6b88b9868bbc00" +checksum = "7a6e6b7c748f995c4c29c5f5ae0248536e04a5739927c74ec0fa564805094b9f" dependencies = [ "autocfg", "num-integer", - "num-traits 0.2.11", + "num-traits 0.2.12", ] [[package]] @@ -870,14 +1046,14 @@ version = "0.1.43" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92e5113e9fd4cc14ded8e499429f396a20f98c772a47cc8622a736e1ec843c31" dependencies = [ - "num-traits 0.2.11", + "num-traits 0.2.12", ] [[package]] name = "num-traits" -version = "0.2.11" +version = "0.2.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c62be47e61d1842b9170f0fdeec8eba98e60e90e5446449a0545e5152acd7096" +checksum = "ac267bcc07f48ee5f8935ab0d24f316fb722d7a1292e2913f0cc196b29ffd611" dependencies = [ "autocfg", ] @@ -892,11 +1068,17 @@ dependencies = [ "libc", ] +[[package]] +name = "object" +version = "0.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ab52be62400ca80aa00285d25253d7f7c437b7375c4de678f5405d3afe82ca5" + [[package]] name = "once_cell" -version = "1.4.0" +version = "1.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b631f7e854af39a1739f401cf34a8a013dfe09eac4fa4dba91e9768bd28168d" +checksum = "260e51e7efe62b592207e9e13a68e43692a7a279171d6ba57abd208bf23645ad" [[package]] name = "opaque-debug" @@ -912,9 +1094,9 @@ checksum = "77af24da69f9d9341038eba93a073b1fdaaa1b788221b00a69bce9e762cb32de" [[package]] name = "openssl-sys" -version = "0.9.57" +version = "0.9.58" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7410fef80af8ac071d4f63755c0ab89ac3df0fd1ea91f1d1f37cf5cec4395990" +checksum = "a842db4709b604f0fe5d1170ae3565899be2ad3d9cbc72dedc789ac0511f78de" dependencies = [ "autocfg", "cc", @@ -934,12 +1116,12 @@ dependencies = [ [[package]] name = "pairing_ce" -version = "0.21.0" +version = "0.21.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f55ca3bd80245b5d43dd4467bc9ab5daf869bd76c6cd3ca54c4499b41923657d" +checksum = "bfc00d65b1d29e0a067a967fcea83d8db261c149f76a557ba73f0304f01cdfde" dependencies = [ "byteorder", - "ff_ce 0.10.2", + "ff_ce 0.10.3", "rand 0.4.6", ] @@ -989,9 +1171,9 @@ checksum = "99b8db626e31e5b81787b9783425769681b347011cc59471e33ea46d2ea0cf55" dependencies = [ "pest", "pest_meta", - "proc-macro2 1.0.18", - "quote 1.0.6", - "syn 1.0.30", + "proc-macro2 1.0.19", + "quote 1.0.7", + "syn 1.0.39", ] [[package]] @@ -1007,22 +1189,22 @@ dependencies = [ [[package]] name = "pin-project" -version = "0.4.19" +version = "0.4.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba3a1acf4a3e70849f8a673497ef984f043f95d2d8252dcdf74d54e6a1e47e8a" +checksum = "ca4433fff2ae79342e497d9f8ee990d174071408f28f726d6d83af93e58e48aa" dependencies = [ "pin-project-internal", ] [[package]] name = "pin-project-internal" -version = "0.4.19" +version = "0.4.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "194e88048b71a3e02eb4ee36a6995fed9b8236c11a7bb9f7247a9d9835b3f265" +checksum = "2c0e815c3ee9a031fdf5af21c10aa17c573c9c6a566328d99e3936c34e36461f" dependencies = [ - "proc-macro2 1.0.18", - "quote 1.0.6", - "syn 1.0.30", + "proc-macro2 1.0.19", + "quote 1.0.7", + "syn 1.0.39", ] [[package]] @@ -1033,15 +1215,15 @@ checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" [[package]] name = "pkg-config" -version = "0.3.17" +version = "0.3.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05da548ad6865900e60eaba7f589cc0783590a92e940c26953ff81ddbab2d677" +checksum = "d36492546b6af1463394d46f0c834346f31548646f6ba10849802c9c9a27ac33" [[package]] name = "ppv-lite86" -version = "0.2.8" +version = "0.2.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "237a5ed80e274dbc66f86bd59c1e25edc039660be53194b5fe0a482e0f2612ea" +checksum = "c36fa947111f5c62a733b652544dd0016a43ce89619538a8ef92724a6f501a20" [[package]] name = "pretty_assertions" @@ -1066,11 +1248,11 @@ dependencies = [ [[package]] name = "proc-macro2" -version = "1.0.18" +version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "beae6331a816b1f65d04c45b078fd8e6c93e8071771f41b8163255bbd8d7c8fa" +checksum = "04f5f085b5d71e2188cb8271e5da0161ad52c3f227a661a3c135fdf28e258b12" dependencies = [ - "unicode-xid 0.2.0", + "unicode-xid 0.2.1", ] [[package]] @@ -1093,11 +1275,32 @@ dependencies = [ [[package]] name = "quote" -version = "1.0.6" +version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "54a21852a652ad6f610c9510194f398ff6f8692e334fd1145fed931f7fbe44ea" +checksum = "aa563d17ecb180e500da1cfd2b028310ac758de548efdd203e18f283af693f37" +dependencies = [ + "proc-macro2 1.0.19", +] + +[[package]] +name = "r1cs-core" +version = "0.1.1-alpha.0" +source = "git+https://github.com/dark64/zexe.git?branch=dark64-patch#6d15b91fbbcd9cc9cbbb1f2783a6020be2761e64" +dependencies = [ + "algebra-core", + "tracing", + "tracing-subscriber", +] + +[[package]] +name = "r1cs-std" +version = "0.1.1-alpha.0" +source = "git+https://github.com/dark64/zexe.git?branch=dark64-patch#6d15b91fbbcd9cc9cbbb1f2783a6020be2761e64" dependencies = [ - "proc-macro2 1.0.18", + "algebra", + "derivative", + "r1cs-core", + "tracing", ] [[package]] @@ -1169,6 +1372,31 @@ dependencies = [ "rand_core 0.5.1", ] +[[package]] +name = "rayon" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfd016f0c045ad38b5251be2c9c0ab806917f82da4d36b2a327e5166adad9270" +dependencies = [ + "autocfg", + "crossbeam-deque", + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91739a34c4355b5434ce54c9086c5895604a9c278586d1f1aa95e04f66b525a0" +dependencies = [ + "crossbeam-channel", + "crossbeam-deque", + "crossbeam-utils", + "lazy_static", + "num_cpus", +] + [[package]] name = "rdrand" version = "0.4.0" @@ -1180,15 +1408,15 @@ dependencies = [ [[package]] name = "redox_syscall" -version = "0.1.56" +version = "0.1.57" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2439c63f3f6139d1b57529d16bc3b8bb855230c8efcc5d3a896c8bea7c3b1e84" +checksum = "41cc0f7e4d5d4544e8861606a285bb08d3e70712ccc7d2b84d7c0ccfaf4b05ce" [[package]] name = "redox_users" -version = "0.3.4" +version = "0.3.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09b23093265f8d200fa7b4c2c76297f47e681c655f6f1285a8780d6a022f7431" +checksum = "de0737333e7a9502c789a36d7c7fa6092a49895d4faa31ca5df163857ded2e9d" dependencies = [ "getrandom", "redox_syscall", @@ -1197,9 +1425,9 @@ dependencies = [ [[package]] name = "reduce" -version = "0.1.2" +version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75b1fa5668b02f2a69746bba558f8f98cc087b123a587fd959122872ad9a3f3c" +checksum = "a4c8549eb79c1fc8c449cb18a2d9b7873a7cb1bf2fcbfe8a3ad8812320544341" [[package]] name = "regex" @@ -1234,18 +1462,18 @@ dependencies = [ [[package]] name = "remove_dir_all" -version = "0.5.2" +version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4a83fa3702a688b9359eccba92d153ac33fd2e8462f9e0e3fdf155239ea7792e" +checksum = "3acd125665422973a33ac9d3dd2df85edad0f4ae9b00dafb1a05e43a9f5ef8e7" dependencies = [ "winapi", ] [[package]] name = "rust-argon2" -version = "0.7.0" +version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2bc8af4bda8e1ff4932523b94d3dd20ee30a87232323eda55903ffd71d2fb017" +checksum = "9dab61250775933275e84053ac235621dfb739556d5c54a2f2e9313b7cf43a19" dependencies = [ "base64", "blake2b_simd", @@ -1259,6 +1487,15 @@ version = "0.1.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4c691c0e608126e00913e33f0ccf3727d5fc84573623b8d65b2df340b5201783" +[[package]] +name = "rustc_version" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "138e3e0acb6c9fb258b19b67cb8abd63c00679d2851805ea151465464fe9030a" +dependencies = [ + "semver", +] + [[package]] name = "ryu" version = "1.0.5" @@ -1304,9 +1541,9 @@ checksum = "388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3" [[package]] name = "serde" -version = "1.0.111" +version = "1.0.115" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c9124df5b40cbd380080b2cc6ab894c040a3070d995f5c9dc77e18c34a8ae37d" +checksum = "e54c9a88f2da7238af84b5101443f0c0d0a3bbdc455e34a5c9497b1903ed55d5" [[package]] name = "serde_bytes" @@ -1319,20 +1556,20 @@ dependencies = [ [[package]] name = "serde_derive" -version = "1.0.111" +version = "1.0.115" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f2c3ac8e6ca1e9c80b8be1023940162bf81ae3cffbb1809474152f2ce1eb250" +checksum = "609feed1d0a73cc36a0182a840a9b37b4a82f0b1150369f0536a9e3f2a31dc48" dependencies = [ - "proc-macro2 1.0.18", - "quote 1.0.6", - "syn 1.0.30", + "proc-macro2 1.0.19", + "quote 1.0.7", + "syn 1.0.39", ] [[package]] name = "serde_json" -version = "1.0.53" +version = "1.0.57" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "993948e75b189211a9b31a7528f950c6adc21f9720b6438ff80a7fa2f864cea2" +checksum = "164eacbdb13512ec2745fb09d51fd5b22b0d65ed294a1dcf7285a360c80a675c" dependencies = [ "itoa", "ryu", @@ -1380,7 +1617,7 @@ checksum = "d6fb8ed853fdc19ce09752d63f3a2e5b5158aeb261520cd75eb618bd60305165" dependencies = [ "bytecount", "cargo_metadata", - "error-chain 0.12.2", + "error-chain 0.12.4", "glob 0.2.11", "pulldown-cmark", "serde_json", @@ -1394,18 +1631,18 @@ version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c111b5bd5695e56cffe5129854aa230b39c93a305372fdbb2668ca2394eea9f8" -[[package]] -name = "smallvec" -version = "1.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7cb5678e1615754284ec264d9bb5b4c27d2018577fd90ac0ceb578591ed5ee4" - [[package]] name = "strsim" version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8ea5119cdb4c55b55d432abb513a0429384878c15dde60cc77b1c99de1a95a6a" +[[package]] +name = "subtle" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d67a5a62ba6e01cb2192ff309324cb4875d0c451d55fe2319433abe7a05a8ee" + [[package]] name = "syn" version = "0.15.44" @@ -1419,25 +1656,25 @@ dependencies = [ [[package]] name = "syn" -version = "1.0.30" +version = "1.0.39" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "93a56fabc59dce20fe48b6c832cc249c713e7ed88fa28b0ee0a3bfcaae5fe4e2" +checksum = "891d8d6567fe7c7f8835a3a98af4208f3846fba258c1bc3c31d6e506239f11f9" dependencies = [ - "proc-macro2 1.0.18", - "quote 1.0.6", - "unicode-xid 0.2.0", + "proc-macro2 1.0.19", + "quote 1.0.7", + "unicode-xid 0.2.1", ] [[package]] name = "synstructure" -version = "0.12.3" +version = "0.12.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67656ea1dc1b41b1451851562ea232ec2e5a80242139f7e679ceccfb5d61f545" +checksum = "b834f2d66f734cb897113e34aaff2f1ab4719ca946f9a7358dba8f8064148701" dependencies = [ - "proc-macro2 1.0.18", - "quote 1.0.6", - "syn 1.0.30", - "unicode-xid 0.2.0", + "proc-macro2 1.0.19", + "quote 1.0.7", + "syn 1.0.39", + "unicode-xid 0.2.1", ] [[package]] @@ -1482,6 +1719,52 @@ dependencies = [ "lazy_static", ] +[[package]] +name = "tinyvec" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "238ce071d267c5710f9d31451efec16c5ee22de34df17cc05e56cbc92e967117" + +[[package]] +name = "tracing" +version = "0.1.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d79ca061b032d6ce30c660fded31189ca0b9922bf483cd70759f13a2d86786c" +dependencies = [ + "cfg-if", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80e0ccfc3378da0cce270c946b676a376943f5cd16aeba64568e7939806f4ada" +dependencies = [ + "proc-macro2 1.0.19", + "quote 1.0.7", + "syn 1.0.39", +] + +[[package]] +name = "tracing-core" +version = "0.1.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5bcf46c1f1f06aeea2d6b81f3c863d0930a596c86ad1920d4e5bad6dd1d7119a" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "tracing-subscriber" +version = "0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82bb5079aa76438620837198db8a5c529fb9878c730bc2b28179b0241cf04c10" +dependencies = [ + "tracing-core", +] + [[package]] name = "typed-arena" version = "1.7.0" @@ -1517,18 +1800,18 @@ dependencies = [ [[package]] name = "unicode-normalization" -version = "0.1.12" +version = "0.1.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5479532badd04e128284890390c1e876ef7a993d0570b3597ae43dfa1d59afa4" +checksum = "6fb19cf769fa8c6a80a162df694621ebeb4dafb606470b2b2fce0be40a98a977" dependencies = [ - "smallvec", + "tinyvec", ] [[package]] name = "unicode-width" -version = "0.1.7" +version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "caaa9d531767d1ff2150b9332433f32a24622147e5ebb1f26409d5da67afd479" +checksum = "9337591893a19b88d8d87f2cec1e73fad5cdfd10e5a6f349f498ad6ea2ffb1e3" [[package]] name = "unicode-xid" @@ -1538,9 +1821,19 @@ checksum = "fc72304796d0818e357ead4e000d19c9c174ab23dc11093ac919054d20a6a7fc" [[package]] name = "unicode-xid" -version = "0.2.0" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "826e7639553986605ec5979c7dd957c7895e93eabed50ab2ffa7f6128a75097c" +checksum = "f7fe0bb3479651439c9112f72b6c505038574c9fbb575ed1bf3b797fa39dd564" + +[[package]] +name = "unroll" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85890b49d9724df33edc575c4bacd5b0081977da22c4c4984d0c62ec44ed6e09" +dependencies = [ + "quote 0.6.13", + "syn 0.15.44", +] [[package]] name = "url" @@ -1561,9 +1854,9 @@ checksum = "b4ae116fef2b7fea257ed6440d3cfcff7f190865f170cdad00bb6465bf18ecba" [[package]] name = "vcpkg" -version = "0.2.9" +version = "0.2.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "55d1e41d56121e07f1e223db0a4def204e45c85425f6a16d462fd07c8d10d74c" +checksum = "6454029bf181f092ad1b853286f23e2c507d8e8194d01d92da4a55c274a5508c" [[package]] name = "vec_map" @@ -1602,9 +1895,9 @@ checksum = "cccddf32554fecc6acb585f82a32a72e28b48f8c4c1883ddfeeeaa96f7d8e519" [[package]] name = "wasm-bindgen" -version = "0.2.63" +version = "0.2.67" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c2dc4aa152834bc334f506c1a06b866416a8b6697d5c9f75b9a689c8486def0" +checksum = "f0563a9a4b071746dd5aedbc3a28c6fe9be4586fb3fbadb67c400d4f53c6b16c" dependencies = [ "cfg-if", "wasm-bindgen-macro", @@ -1612,24 +1905,24 @@ dependencies = [ [[package]] name = "wasm-bindgen-backend" -version = "0.2.63" +version = "0.2.67" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ded84f06e0ed21499f6184df0e0cb3494727b0c5da89534e0fcc55c51d812101" +checksum = "bc71e4c5efa60fb9e74160e89b93353bc24059999c0ae0fb03affc39770310b0" dependencies = [ "bumpalo", "lazy_static", "log", - "proc-macro2 1.0.18", - "quote 1.0.6", - "syn 1.0.30", + "proc-macro2 1.0.19", + "quote 1.0.7", + "syn 1.0.39", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-futures" -version = "0.4.13" +version = "0.4.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "64487204d863f109eb77e8462189d111f27cb5712cc9fdb3461297a76963a2f6" +checksum = "95f8d235a77f880bcef268d379810ea6c0af2eacfa90b1ad5af731776e0c4699" dependencies = [ "cfg-if", "js-sys", @@ -1639,38 +1932,38 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro" -version = "0.2.63" +version = "0.2.67" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "838e423688dac18d73e31edce74ddfac468e37b1506ad163ffaf0a46f703ffe3" +checksum = "97c57cefa5fa80e2ba15641578b44d36e7a64279bc5ed43c6dbaf329457a2ed2" dependencies = [ - "quote 1.0.6", + "quote 1.0.7", "wasm-bindgen-macro-support", ] [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.63" +version = "0.2.67" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3156052d8ec77142051a533cdd686cba889537b213f948cd1d20869926e68e92" +checksum = "841a6d1c35c6f596ccea1f82504a192a60378f64b3bb0261904ad8f2f5657556" dependencies = [ - "proc-macro2 1.0.18", - "quote 1.0.6", - "syn 1.0.30", + "proc-macro2 1.0.19", + "quote 1.0.7", + "syn 1.0.39", "wasm-bindgen-backend", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" -version = "0.2.63" +version = "0.2.67" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c9ba19973a58daf4db6f352eda73dc0e289493cd29fb2632eb172085b6521acd" +checksum = "93b162580e34310e5931c4b792560108b10fd14d64915d7fff8ff00180e70092" [[package]] name = "wasm-bindgen-test" -version = "0.3.13" +version = "0.3.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f0dfda4d3b3f8acbc3c291b09208081c203af457fb14a229783b06e2f128aa7" +checksum = "7d92df9d5715606f9e48f85df3b78cb77ae44a2ea9a5f2a785a97bd0066b9300" dependencies = [ "console_error_panic_hook", "js-sys", @@ -1682,19 +1975,19 @@ dependencies = [ [[package]] name = "wasm-bindgen-test-macro" -version = "0.3.13" +version = "0.3.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2c2e18093f11c19ca4e188c177fecc7c372304c311189f12c2f9bea5b7324ac7" +checksum = "51611ce8e84cba89379d91fc5074bacc5530f69da1c09a2853d906129d12b3b8" dependencies = [ - "proc-macro2 1.0.18", - "quote 1.0.6", + "proc-macro2 1.0.19", + "quote 1.0.7", ] [[package]] name = "web-sys" -version = "0.3.40" +version = "0.3.44" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b72fe77fd39e4bd3eaa4412fd299a0be6b3dfe9d2597e2f1c20beb968f41d17" +checksum = "dda38f4e5ca63eda02c059d243aa25b5f35ab98451e518c51612cd0f1bd19a47" dependencies = [ "js-sys", "wasm-bindgen", @@ -1702,9 +1995,9 @@ dependencies = [ [[package]] name = "winapi" -version = "0.3.8" +version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8093091eeb260906a183e6ae1abdba2ef5ef2257a21801128899c3fc699229c6" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" dependencies = [ "winapi-i686-pc-windows-gnu", "winapi-x86_64-pc-windows-gnu", @@ -1744,7 +2037,7 @@ dependencies = [ [[package]] name = "zokrates_cli" -version = "0.6.0" +version = "0.6.1" dependencies = [ "assert_cli", "bincode", @@ -1767,24 +2060,31 @@ version = "0.1.0" [[package]] name = "zokrates_core" -version = "0.5.0" +version = "0.5.1" dependencies = [ + "algebra", + "algebra-core", "assert_cli", "bellman_ce", "bincode", "cc", "cmake", + "crypto-primitives", "csv", "ff_ce 0.9.0", "git2", "glob 0.2.11", + "gm17", "hex", "lazy_static", "num", - "num-bigint", + "num-bigint 0.1.44", "pairing_ce", "pretty_assertions", + "r1cs-core", + "r1cs-std", "rand 0.4.6", + "rand 0.7.3", "reduce", "regex", "serde", @@ -1810,12 +2110,14 @@ dependencies = [ name = "zokrates_field" version = "0.3.7" dependencies = [ + "algebra", + "algebra-core", "bellman_ce", "bincode", "lazy_static", - "num-bigint", + "num-bigint 0.2.6", "num-integer", - "num-traits 0.2.11", + "num-traits 0.2.12", "rand 0.4.6", "serde", "serde_derive", @@ -1825,7 +2127,7 @@ dependencies = [ [[package]] name = "zokrates_fs_resolver" -version = "0.5.0" +version = "0.5.1" dependencies = [ "tempfile", "zokrates_common", @@ -1863,7 +2165,7 @@ dependencies = [ [[package]] name = "zokrates_test" -version = "0.1.2" +version = "0.1.3" dependencies = [ "fs_extra", "glob 0.3.0", diff --git a/ey.Dockerfile b/ey.Dockerfile new file mode 100644 index 000000000..34773a9c5 --- /dev/null +++ b/ey.Dockerfile @@ -0,0 +1,18 @@ +FROM rust:latest as builder +WORKDIR /src +COPY . . +RUN apt-get update +# RUN apt-get install -y git clang llvm +RUN rustup toolchain install nightly +RUN cargo +nightly build --release + +FROM ubuntu:latest +RUN useradd -u 1000 -m zokrates +WORKDIR /home/zokrates/ +COPY --from=builder --chown=zokrates:zokrates /src/target/release/zokrates /home/zokrates/ +COPY --from=builder --chown=zokrates:zokrates /src/zokrates_stdlib/stdlib /home/zokrates/.zokrates/ +COPY --from=builder --chown=zokrates:zokrates /src/zokrates_cli/examples /home/zokrates/examples/ +ENV ZOKRATES_HOME=/home/zokrates/.zokrates +USER zokrates +ENV PATH=/home/zokrates/:$PATH +CMD ["zokrates", "--version"] diff --git a/test/test.code b/test/test.code new file mode 100644 index 000000000..fd2aaf431 --- /dev/null +++ b/test/test.code @@ -0,0 +1,9 @@ +def main( private field A, field B) -> (): + field C = A + for field i in 0..100000 do + C = (C * i) ** 2 + endfor + C=0 // so that we can always lazily use the same witness for both curves + // CHECK THE INPUT B EQUALS THE CALCULATED thing + B == C + return diff --git a/zokrates_cli/examples/book/hashexample_updated_bls12_377.zok b/zokrates_cli/examples/book/hashexample_updated_bls12_377.zok new file mode 100644 index 000000000..2634226ad --- /dev/null +++ b/zokrates_cli/examples/book/hashexample_updated_bls12_377.zok @@ -0,0 +1,7 @@ +import "hashes/sha256/512bitPacked_bls12_377" as sha256packed + +def main(private field a, private field b, private field c, private field d) -> (field): + field[2] h = sha256packed([a, b, c, d]) + h[0] == 263561599766550617289250058199814760685 + h[1] == 65303172752238645975888084098459749904 + return 1 diff --git a/zokrates_cli/examples/book/hashexample_updated_bw6_761.zok b/zokrates_cli/examples/book/hashexample_updated_bw6_761.zok new file mode 100644 index 000000000..82fcc4afd --- /dev/null +++ b/zokrates_cli/examples/book/hashexample_updated_bw6_761.zok @@ -0,0 +1,7 @@ +import "hashes/sha256/512bitPacked_bw6_761" as sha256packed + +def main(private field a, private field b, private field c, private field d) -> (field): + field[2] h = sha256packed([a, b, c, d]) + h[0] == 263561599766550617289250058199814760685 + h[1] == 65303172752238645975888084098459749904 + return 1 diff --git a/zokrates_cli/src/bin.rs b/zokrates_cli/src/bin.rs index 024a0bd1b..873aefd52 100644 --- a/zokrates_cli/src/bin.rs +++ b/zokrates_cli/src/bin.rs @@ -23,13 +23,15 @@ use zokrates_core::compile::{check, compile, CompilationArtifacts, CompileError} use zokrates_core::ir::{self, ProgEnum}; use zokrates_core::proof_system::bellman::groth16::G16; #[cfg(feature = "libsnark")] -use zokrates_core::proof_system::libsnark::gm17::GM17; +use zokrates_core::proof_system::libsnark::gm17::GM17 as GM17_Libsnark; #[cfg(feature = "libsnark")] use zokrates_core::proof_system::libsnark::pghr13::PGHR13; +use zokrates_core::proof_system::solidity::SolidityAbi; +use zokrates_core::proof_system::zexe::gm17::GM17 as GM17_Zexe; use zokrates_core::proof_system::*; use zokrates_core::typed_absy::abi::Abi; use zokrates_core::typed_absy::{types::Signature, Type}; -use zokrates_field::{Bls12Field, Bn128Field, Field}; +use zokrates_field::{Bls12_377Field, Bls12_381Field, Bn128Field, Bw6_761Field, Field}; use zokrates_fs_resolver::FileSystemResolver; fn main() { @@ -796,16 +798,18 @@ fn cli() -> Result<(), String> { let curve = Curve::try_from(sub_matches.value_of("curve").unwrap())?; match curve { Curve::Bn128 => cli_compile::(sub_matches)?, - Curve::Bls12 => cli_compile::(sub_matches)?, + Curve::Bls12_377 => cli_compile::(sub_matches)?, + Curve::Bls12_381 => cli_compile::(sub_matches)?, + Curve::Bw6_761 => cli_compile::(sub_matches)?, } } ("check", Some(sub_matches)) => { - let curve = sub_matches.value_of("curve").unwrap(); - + let curve = Curve::try_from(sub_matches.value_of("curve").unwrap())?; match curve { - constants::BN128 => cli_check::(sub_matches)?, - constants::BLS12_381 => cli_check::(sub_matches)?, - _ => unreachable!(), + Curve::Bn128 => cli_check::(sub_matches)?, + Curve::Bls12_377 => cli_check::(sub_matches)?, + Curve::Bls12_381 => cli_check::(sub_matches)?, + Curve::Bw6_761 => cli_check::(sub_matches)?, } } ("compute-witness", Some(sub_matches)) => { @@ -818,7 +822,9 @@ fn cli() -> Result<(), String> { match ProgEnum::deserialize(&mut reader)? { ProgEnum::Bn128Program(p) => cli_compute(p, sub_matches)?, - ProgEnum::Bls12Program(p) => cli_compute(p, sub_matches)?, + ProgEnum::Bls12_377Program(p) => cli_compute(p, sub_matches)?, + ProgEnum::Bls12_381Program(p) => cli_compute(p, sub_matches)?, + ProgEnum::Bw6_761Program(p) => cli_compute(p, sub_matches)?, } } ("setup", Some(sub_matches)) => { @@ -834,7 +840,9 @@ fn cli() -> Result<(), String> { sub_matches.value_of("backend").unwrap(), match prog { ProgEnum::Bn128Program(_) => constants::BN128, - ProgEnum::Bls12Program(_) => constants::BLS12_381, + ProgEnum::Bls12_377Program(_) => constants::BLS12_377, + ProgEnum::Bls12_381Program(_) => constants::BLS12_381, + ProgEnum::Bw6_761Program(_) => constants::BW6_761, }, sub_matches.value_of("proving-scheme").unwrap(), ))?; @@ -842,11 +850,18 @@ fn cli() -> Result<(), String> { match dimensions { Dimensions(Backend::Bellman, _, ProvingScheme::G16) => match prog { ProgEnum::Bn128Program(p) => cli_setup::<_, G16>(p, sub_matches), - ProgEnum::Bls12Program(p) => cli_setup::<_, G16>(p, sub_matches), + ProgEnum::Bls12_381Program(p) => cli_setup::<_, G16>(p, sub_matches), + _ => unreachable!(), + }, + Dimensions(Backend::Zexe, _, ProvingScheme::GM17) => match prog { + ProgEnum::Bls12_377Program(p) => cli_setup::<_, GM17_Zexe>(p, sub_matches), + ProgEnum::Bw6_761Program(p) => cli_setup::<_, GM17_Zexe>(p, sub_matches), + ProgEnum::Bn128Program(p) => cli_setup::<_, GM17_Zexe>(p, sub_matches), + _ => unreachable!(), }, #[cfg(feature = "libsnark")] Dimensions(Backend::Libsnark, Curve::Bn128, ProvingScheme::GM17) => match prog { - ProgEnum::Bn128Program(p) => cli_setup::<_, GM17>(p, sub_matches), + ProgEnum::Bn128Program(p) => cli_setup::<_, GM17_Libsnark>(p, sub_matches), _ => unreachable!(), }, #[cfg(feature = "libsnark")] @@ -854,7 +869,6 @@ fn cli() -> Result<(), String> { ProgEnum::Bn128Program(p) => cli_setup::<_, PGHR13>(p, sub_matches), _ => unreachable!(), }, - #[cfg(feature = "libsnark")] _ => unreachable!(), }? } @@ -869,18 +883,26 @@ fn cli() -> Result<(), String> { Dimensions(Backend::Bellman, Curve::Bn128, ProvingScheme::G16) => { cli_export_verifier::(sub_matches) } - Dimensions(Backend::Bellman, Curve::Bls12, ProvingScheme::G16) => { - cli_export_verifier::(sub_matches) + Dimensions(Backend::Bellman, Curve::Bls12_381, ProvingScheme::G16) => { + cli_export_verifier::(sub_matches) + } + Dimensions(Backend::Zexe, Curve::Bls12_377, ProvingScheme::GM17) => { + cli_export_verifier::(sub_matches) + } + Dimensions(Backend::Zexe, Curve::Bw6_761, ProvingScheme::GM17) => { + cli_export_verifier::(sub_matches) + } + Dimensions(Backend::Zexe, Curve::Bn128, ProvingScheme::GM17) => { + cli_export_verifier::(sub_matches) } #[cfg(feature = "libsnark")] Dimensions(Backend::Libsnark, Curve::Bn128, ProvingScheme::GM17) => { - cli_export_verifier::(sub_matches) + cli_export_verifier::(sub_matches) } #[cfg(feature = "libsnark")] Dimensions(Backend::Libsnark, Curve::Bn128, ProvingScheme::PGHR13) => { cli_export_verifier::(sub_matches) } - #[cfg(feature = "libsnark")] _ => unreachable!(), }? } @@ -896,7 +918,9 @@ fn cli() -> Result<(), String> { sub_matches.value_of("backend").unwrap(), match prog { ProgEnum::Bn128Program(_) => constants::BN128, - ProgEnum::Bls12Program(_) => constants::BLS12_381, + ProgEnum::Bls12_381Program(_) => constants::BLS12_381, + ProgEnum::Bls12_377Program(_) => constants::BLS12_377, + ProgEnum::Bw6_761Program(_) => constants::BW6_761, }, sub_matches.value_of("proving-scheme").unwrap(), ))?; @@ -904,11 +928,24 @@ fn cli() -> Result<(), String> { match dimensions { Dimensions(Backend::Bellman, _, ProvingScheme::G16) => match prog { ProgEnum::Bn128Program(p) => cli_generate_proof::<_, G16>(p, sub_matches), - ProgEnum::Bls12Program(p) => cli_generate_proof::<_, G16>(p, sub_matches), + ProgEnum::Bls12_381Program(p) => cli_generate_proof::<_, G16>(p, sub_matches), + _ => unreachable!(), + }, + Dimensions(Backend::Zexe, _, ProvingScheme::GM17) => match prog { + ProgEnum::Bls12_377Program(p) => { + cli_generate_proof::<_, GM17_Zexe>(p, sub_matches) + } + ProgEnum::Bw6_761Program(p) => { + cli_generate_proof::<_, GM17_Zexe>(p, sub_matches) + } + ProgEnum::Bn128Program(p) => cli_generate_proof::<_, GM17_Zexe>(p, sub_matches), + _ => unreachable!(), }, #[cfg(feature = "libsnark")] Dimensions(Backend::Libsnark, Curve::Bn128, ProvingScheme::GM17) => match prog { - ProgEnum::Bn128Program(p) => cli_generate_proof::<_, GM17>(p, sub_matches), + ProgEnum::Bn128Program(p) => { + cli_generate_proof::<_, GM17_Libsnark>(p, sub_matches) + } _ => unreachable!(), }, #[cfg(feature = "libsnark")] @@ -916,7 +953,6 @@ fn cli() -> Result<(), String> { ProgEnum::Bn128Program(p) => cli_generate_proof::<_, PGHR13>(p, sub_matches), _ => unreachable!(), }, - #[cfg(feature = "libsnark")] _ => unreachable!(), }? } @@ -967,18 +1003,26 @@ fn cli() -> Result<(), String> { Dimensions(Backend::Bellman, Curve::Bn128, ProvingScheme::G16) => { cli_verify::(sub_matches) } - Dimensions(Backend::Bellman, Curve::Bls12, ProvingScheme::G16) => { - cli_verify::(sub_matches) + Dimensions(Backend::Bellman, Curve::Bls12_381, ProvingScheme::G16) => { + cli_verify::(sub_matches) + } + Dimensions(Backend::Zexe, Curve::Bls12_377, ProvingScheme::GM17) => { + cli_verify::(sub_matches) + } + Dimensions(Backend::Zexe, Curve::Bw6_761, ProvingScheme::GM17) => { + cli_verify::(sub_matches) + } + Dimensions(Backend::Zexe, Curve::Bn128, ProvingScheme::GM17) => { + cli_verify::(sub_matches) } #[cfg(feature = "libsnark")] Dimensions(Backend::Libsnark, Curve::Bn128, ProvingScheme::GM17) => { - cli_verify::(sub_matches) + cli_verify::(sub_matches) } #[cfg(feature = "libsnark")] Dimensions(Backend::Libsnark, Curve::Bn128, ProvingScheme::PGHR13) => { cli_verify::(sub_matches) } - #[cfg(feature = "libsnark")] _ => unreachable!(), }? } @@ -1022,8 +1066,20 @@ mod tests { let stdlib = std::fs::canonicalize("../zokrates_stdlib/stdlib").unwrap(); let resolver = FileSystemResolver::with_stdlib_root(stdlib.to_str().unwrap()); - let _: CompilationArtifacts = - compile(source, path, Some(&resolver)).unwrap(); + + if path.to_str().unwrap().contains("bls12_381") { + let _: CompilationArtifacts = + compile(source, path, Some(&resolver)).unwrap(); + } else if path.to_str().unwrap().contains("bls12_377") { + let _: CompilationArtifacts = + compile(source, path, Some(&resolver)).unwrap(); + } else if path.to_str().unwrap().contains("bw6_761") { + let _: CompilationArtifacts = + compile(source, path, Some(&resolver)).unwrap(); + } else { + let _: CompilationArtifacts = + compile(source, path, Some(&resolver)).unwrap(); + } } } diff --git a/zokrates_cli/src/constants.rs b/zokrates_cli/src/constants.rs index 5ffa8c43b..2a2bf83f0 100644 --- a/zokrates_cli/src/constants.rs +++ b/zokrates_cli/src/constants.rs @@ -1,21 +1,25 @@ pub const BELLMAN: &str = "bellman"; #[cfg(feature = "libsnark")] pub const LIBSNARK: &str = "libsnark"; +pub const ZEXE: &str = "zexe"; + #[cfg(feature = "libsnark")] -pub const BACKENDS: &[&str] = &[BELLMAN, LIBSNARK]; +pub const BACKENDS: &[&str] = &[BELLMAN, LIBSNARK, ZEXE]; #[cfg(not(feature = "libsnark"))] -pub const BACKENDS: &[&str] = &[BELLMAN]; +pub const BACKENDS: &[&str] = &[BELLMAN, ZEXE]; pub const BN128: &str = "bn128"; pub const BLS12_381: &str = "bls12_381"; -pub const CURVES: &[&str] = &[BN128, BLS12_381]; +pub const BLS12_377: &str = "bls12_377"; +pub const BW6_761: &str = "bw6_761"; +pub const CURVES: &[&str] = &[BN128, BLS12_381, BLS12_377, BW6_761]; pub const G16: &str = "g16"; #[cfg(feature = "libsnark")] pub const PGHR13: &str = "pghr13"; -#[cfg(feature = "libsnark")] pub const GM17: &str = "gm17"; + #[cfg(feature = "libsnark")] pub const SCHEMES: &[&str] = &[G16, PGHR13, GM17]; #[cfg(not(feature = "libsnark"))] -pub const SCHEMES: &[&str] = &[G16]; +pub const SCHEMES: &[&str] = &[G16, GM17]; diff --git a/zokrates_cli/src/helpers.rs b/zokrates_cli/src/helpers.rs index da8bd5c3c..2229876a8 100644 --- a/zokrates_cli/src/helpers.rs +++ b/zokrates_cli/src/helpers.rs @@ -2,20 +2,23 @@ use core::convert::TryFrom; use crate::constants::*; +#[derive(Debug)] pub enum Curve { Bn128, - Bls12, + Bls12_381, + Bls12_377, + Bw6_761, } pub enum Backend { Bellman, + Zexe, #[cfg(feature = "libsnark")] Libsnark, } pub enum ProvingScheme { G16, - #[cfg(feature = "libsnark")] GM17, #[cfg(feature = "libsnark")] PGHR13, @@ -27,7 +30,9 @@ impl TryFrom<&str> for Curve { fn try_from(s: &str) -> Result { match s { BN128 => Ok(Curve::Bn128), - BLS12_381 => Ok(Curve::Bls12), + BLS12_381 => Ok(Curve::Bls12_381), + BLS12_377 => Ok(Curve::Bls12_377), + BW6_761 => Ok(Curve::Bw6_761), _ => Err(format!("Unknown curve {}", s)), } } @@ -39,6 +44,7 @@ impl TryFrom<&str> for Backend { fn try_from(s: &str) -> Result { match s { BELLMAN => Ok(Backend::Bellman), + ZEXE => Ok(Backend::Zexe), #[cfg(feature = "libsnark")] LIBSNARK => Ok(Backend::Libsnark), _ => Err(format!("Unknown backend {}", s)), @@ -52,7 +58,6 @@ impl TryFrom<&str> for ProvingScheme { fn try_from(s: &str) -> Result { match s { G16 => Ok(ProvingScheme::G16), - #[cfg(feature = "libsnark")] GM17 => Ok(ProvingScheme::GM17), #[cfg(feature = "libsnark")] PGHR13 => Ok(ProvingScheme::PGHR13), @@ -75,7 +80,16 @@ impl TryFrom<(&str, &str, &str)> for Dimensions { (Backend::Bellman, Curve::Bn128, ProvingScheme::G16) => { Ok(Dimensions(backend, curve, proving_scheme)) } - (Backend::Bellman, Curve::Bls12, ProvingScheme::G16) => { + (Backend::Bellman, Curve::Bls12_381, ProvingScheme::G16) => { + Ok(Dimensions(backend, curve, proving_scheme)) + } + (Backend::Zexe, Curve::Bls12_377, ProvingScheme::GM17) => { + Ok(Dimensions(backend, curve, proving_scheme)) + } + (Backend::Zexe, Curve::Bw6_761, ProvingScheme::GM17) => { + Ok(Dimensions(backend, curve, proving_scheme)) + } + (Backend::Zexe, Curve::Bn128, ProvingScheme::GM17) => { Ok(Dimensions(backend, curve, proving_scheme)) } #[cfg(feature = "libsnark")] @@ -86,7 +100,6 @@ impl TryFrom<(&str, &str, &str)> for Dimensions { (Backend::Libsnark, Curve::Bn128, ProvingScheme::PGHR13) => { Ok(Dimensions(backend, curve, proving_scheme)) } - #[cfg(feature = "libsnark")] _ => Err(format!( "Unsupported combination of dimensions (backend: {}, curve: {}, proving scheme: {})", s.0, s.1, s.2 diff --git a/zokrates_cli/tests/integration.rs b/zokrates_cli/tests/integration.rs index 8b4ae83be..c711aaa37 100644 --- a/zokrates_cli/tests/integration.rs +++ b/zokrates_cli/tests/integration.rs @@ -218,7 +218,10 @@ mod integration { }; #[cfg(not(feature = "libsnark"))] - let backends = map! {"bellman" => ["g16"]}; + let backends = map! { + "bellman" => ["g16"], + "zexe" => ["gm17"] + }; for (backend, schemes) in backends { for scheme in &schemes { @@ -241,20 +244,22 @@ mod integration { .unwrap(); // EXPORT-VERIFIER - assert_cli::Assert::command(&[ - "../target/release/zokrates", - "export-verifier", - "-i", - verification_key_path.to_str().unwrap(), - "-o", - verification_contract_path.to_str().unwrap(), - "--backend", - backend, - "--proving-scheme", - scheme, - ]) - .succeeds() - .unwrap(); + if backend != "zexe" { + assert_cli::Assert::command(&[ + "../target/release/zokrates", + "export-verifier", + "-i", + verification_key_path.to_str().unwrap(), + "-o", + verification_contract_path.to_str().unwrap(), + "--backend", + backend, + "--proving-scheme", + scheme, + ]) + .succeeds() + .unwrap(); + } // GENERATE-PROOF assert_cli::Assert::command(&[ @@ -293,17 +298,19 @@ mod integration { .unwrap(); // TEST VERIFIER - assert_cli::Assert::command(&[ - "node", - "test.js", - verification_contract_path.to_str().unwrap(), - proof_path.to_str().unwrap(), - scheme, - "v1", - ]) - .current_dir(concat!(env!("OUT_DIR"), "/contract")) - .succeeds() - .unwrap(); + if backend != "zexe" { + assert_cli::Assert::command(&[ + "node", + "test.js", + verification_contract_path.to_str().unwrap(), + proof_path.to_str().unwrap(), + scheme, + "v1", + ]) + .current_dir(concat!(env!("OUT_DIR"), "/contract")) + .succeeds() + .unwrap(); + } } } } diff --git a/zokrates_core/Cargo.toml b/zokrates_core/Cargo.toml index a2962ca82..07273cbb4 100644 --- a/zokrates_core/Cargo.toml +++ b/zokrates_core/Cargo.toml @@ -13,7 +13,8 @@ wasm = ["bellman_ce/wasm"] multicore = ["bellman_ce/multicore"] [dependencies] -num = {version = "0.1.36", default-features = false} +num = { version = "0.1.36", default-features = false } +num-bigint = { version = "0.1.36", default-features = false } lazy_static = "1.4" typed-arena = "1.4.1" reduce = "0.1.1" @@ -30,19 +31,22 @@ ff_ce = "^0.9" zokrates_field = { version = "0.3.0", path = "../zokrates_field" } zokrates_pest_ast = { version = "0.1.0", path = "../zokrates_pest_ast" } zokrates_common = { path = "../zokrates_common" } -rand = "0.4" +rand_0_4 = { version = "0.4", package = "rand" } +rand_0_7 = { version = "0.7", package = "rand" } csv = "1" -bellman_ce = { version = "^0.3", default-features = false } - -[dependencies.num-bigint] -version = "0.2" -features = ["serde"] +pretty_assertions = "0.6.1" +bellman_ce = { version = "^0.3", default-features = false} +gm17 = { git = "https://github.com/dark64/zexe.git", branch = "dark64-patch", version = "0.1.1-alpha.0", features = ["parallel"] } +algebra-core = { git = "https://github.com/dark64/zexe.git", branch = "dark64-patch", version = "0.1.1-alpha.0", features = ["parallel"] } +r1cs-core = { git = "https://github.com/dark64/zexe.git", branch = "dark64-patch", version = "0.1.1-alpha.0"} +algebra = { git = "https://github.com/dark64/zexe.git", branch = "dark64-patch", version = "0.1.1-alpha.0", features = ["bn254", "bls12_377", "bw6_761", "parallel"] } +crypto-primitives = { default-features = false, git = "https://github.com/dark64/zexe.git", branch = "dark64-patch", version = "0.1.1-alpha.0", features = [ "parallel", "gm17", "r1cs" ] } +r1cs-std = { git = "https://github.com/dark64/zexe.git", branch = "dark64-patch", version = "0.1.1-alpha.0", features = ["bls12_377", "parallel"] } [dev-dependencies] glob = "0.2.11" assert_cli = "0.5" wasm-bindgen-test = "0.3.0" -pretty_assertions = "0.6.1" [build-dependencies] cc = { version = "1.0", features = ["parallel"], optional = true } diff --git a/zokrates_core/src/ir/interpreter.rs b/zokrates_core/src/ir/interpreter.rs index 7cd235ec6..d1b15d0b8 100644 --- a/zokrates_core/src/ir/interpreter.rs +++ b/zokrates_core/src/ir/interpreter.rs @@ -1,3 +1,4 @@ +extern crate algebra as zexe_algebra; use crate::flat_absy::flat_variable::FlatVariable; use crate::ir::{LinComb, Prog, QuadComb, Statement, Witness}; use ir::Directive; diff --git a/zokrates_core/src/ir/serialize.rs b/zokrates_core/src/ir/serialize.rs index 5c55a0c1f..7464c5dce 100644 --- a/zokrates_core/src/ir/serialize.rs +++ b/zokrates_core/src/ir/serialize.rs @@ -8,8 +8,10 @@ const ZOKRATES_VERSION_1: &[u8; 4] = &[0, 0, 0, 1]; #[derive(PartialEq, Debug)] pub enum ProgEnum { - Bls12Program(Prog), + Bls12_381Program(Prog), Bn128Program(Prog), + Bls12_377Program(Prog), + Bw6_761Program(Prog), } impl Prog { @@ -42,12 +44,18 @@ impl ProgEnum { .map_err(|_| String::from("Cannot read curve identifier"))?; match curve { - m if m == Bls12Field::id() => Ok(ProgEnum::Bls12Program( + m if m == Bls12_381Field::id() => Ok(ProgEnum::Bls12_381Program( deserialize_from(&mut r, Infinite).unwrap(), )), m if m == Bn128Field::id() => Ok(ProgEnum::Bn128Program( deserialize_from(&mut r, Infinite).unwrap(), )), + m if m == Bls12_377Field::id() => Ok(ProgEnum::Bls12_377Program( + deserialize_from(&mut r, Infinite).unwrap(), + )), + m if m == Bw6_761Field::id() => Ok(ProgEnum::Bw6_761Program( + deserialize_from(&mut r, Infinite).unwrap(), + )), _ => Err(String::from("Unknown curve identifier")), } } else { @@ -64,7 +72,7 @@ mod tests { use super::*; use ir; use std::io::{Cursor, Seek, SeekFrom}; - use zokrates_field::{Bls12Field, Bn128Field}; + use zokrates_field::{Bls12_381Field, Bn128Field}; #[test] fn ser_deser_v1() { @@ -89,7 +97,7 @@ mod tests { assert_eq!(ProgEnum::Bn128Program(p), deserialized_p); - let p: ir::Prog = ir::Prog { + let p: ir::Prog = ir::Prog { main: ir::Function { arguments: vec![], id: "something".to_string(), @@ -108,6 +116,6 @@ mod tests { // deserialize let deserialized_p = ProgEnum::deserialize(buffer).unwrap(); - assert_eq!(ProgEnum::Bls12Program(p), deserialized_p); + assert_eq!(ProgEnum::Bls12_381Program(p), deserialized_p); } } diff --git a/zokrates_core/src/lib.rs b/zokrates_core/src/lib.rs index 5187d467f..99e1dcdfb 100644 --- a/zokrates_core/src/lib.rs +++ b/zokrates_core/src/lib.rs @@ -8,13 +8,21 @@ extern crate serde_json; extern crate typed_arena; #[macro_use] extern crate serde_derive; +extern crate algebra as zexe_algebra; +extern crate algebra_core; extern crate bellman_ce as bellman; extern crate bincode; +extern crate crypto_primitives; extern crate csv; extern crate ff_ce as ff; +extern crate gm17 as zexe_gm17; extern crate hex; extern crate lazy_static; extern crate pairing_ce as pairing; +extern crate r1cs_core; +extern crate r1cs_std; +extern crate rand_0_4; +extern crate rand_0_7; extern crate regex; extern crate zokrates_common; extern crate zokrates_field; diff --git a/zokrates_core/src/proof_system/bellman/groth16.rs b/zokrates_core/src/proof_system/bellman/groth16.rs index a75611c38..c6969c5f8 100644 --- a/zokrates_core/src/proof_system/bellman/groth16.rs +++ b/zokrates_core/src/proof_system/bellman/groth16.rs @@ -5,15 +5,16 @@ use bellman::groth16::{ use pairing::{CurveAffine, Engine}; use regex::Regex; +use ir; +use proof_system::solidity::{ + SolidityAbi, SOLIDITY_G2_ADDITION_LIB, SOLIDITY_PAIRING_LIB, SOLIDITY_PAIRING_LIB_V2, +}; +use proof_system::{G1Affine, G2Affine, Proof, ProofSystem, SetupKeypair}; +use zokrates_field::BellmanFieldExtensions; use zokrates_field::Field; -use crate::ir; use crate::proof_system::bellman::Computation; use crate::proof_system::bellman::{parse_fr, parse_g1, parse_g2}; -use crate::proof_system::solidity::{ - SOLIDITY_G2_ADDITION_LIB, SOLIDITY_PAIRING_LIB, SOLIDITY_PAIRING_LIB_V2, -}; -use proof_system::{G1Affine, G2Affine, Proof, ProofSystem, SetupKeypair, SolidityAbi}; const G16_WARNING: &str = "WARNING: You are using the G16 scheme which is subject to malleability. See zokrates.github.io/toolbox/proving_schemes.html#g16-malleability for implications."; @@ -27,7 +28,7 @@ pub struct ProofPoints { } impl ProofPoints { - fn into_bellman(self) -> BellmanProof { + fn into_bellman(self) -> BellmanProof { BellmanProof { a: serialization::to_g1::(self.a), b: serialization::to_g2::(self.b), @@ -46,7 +47,7 @@ pub struct VerificationKey { } impl VerificationKey { - fn into_bellman(self) -> VerifyingKey { + fn into_bellman(self) -> VerifyingKey { VerifyingKey { alpha_g1: serialization::to_g1::(self.alpha), beta_g1: ::G1Affine::one(), // not used during verification @@ -63,19 +64,15 @@ impl VerificationKey { } } -impl ProofSystem for G16 { +impl ProofSystem for G16 { type VerificationKey = VerificationKey; type ProofPoints = ProofPoints; fn setup(program: ir::Prog) -> SetupKeypair { - #[cfg(not(target_arch = "wasm32"))] - std::env::set_var("BELLMAN_VERBOSE", "0"); println!("{}", G16_WARNING); let parameters = Computation::without_witness(program).setup(); - let mut pk: Vec = Vec::new(); - parameters.write(&mut pk).unwrap(); let vk = VerificationKey { @@ -108,7 +105,6 @@ impl ProofSystem for G16 { let params = Parameters::read(proving_key.as_slice(), true).unwrap(); let proof = computation.clone().prove(¶ms); - let proof_points = ProofPoints { a: parse_g1::(&proof.a), b: parse_g2::(&proof.b), @@ -121,10 +117,7 @@ impl ProofSystem for G16 { .map(parse_fr::) .collect::>(); - let mut raw: Vec = Vec::new(); - proof.write(&mut raw).unwrap(); - - Proof::::new(proof_points, inputs, hex::encode(&raw)) + Proof::::new(proof_points, inputs, None) } fn export_solidity_verifier(vk: VerificationKey, abi: SolidityAbi) -> String { @@ -232,9 +225,7 @@ impl ProofSystem for G16 { fn verify(vk: VerificationKey, proof: Proof) -> bool { let vk: VerifyingKey = vk.into_bellman::(); - let pvk: PreparedVerifyingKey = prepare_verifying_key(&vk); - let bellman_proof: BellmanProof = proof.proof.into_bellman::(); let public_inputs: Vec<_> = proof @@ -242,7 +233,7 @@ impl ProofSystem for G16 { .iter() .map(|s| { T::try_from_str(s.trim_start_matches("0x"), 16) - .expect(format!("Invalid {} value: {}", T::name(), s).as_str()) + .unwrap() .into_bellman() }) .collect::>(); @@ -253,17 +244,22 @@ impl ProofSystem for G16 { mod serialization { use pairing::{from_hex, CurveAffine, Engine}; + use proof_system::{G1Affine, G2Affine}; - use zokrates_field::Field; + use zokrates_field::BellmanFieldExtensions; - pub fn to_g1(g1: G1Affine) -> ::G1Affine { + pub fn to_g1( + g1: G1Affine, + ) -> ::G1Affine { ::G1Affine::from_xy_checked( from_hex(&g1.0).unwrap(), from_hex(&g1.1).unwrap(), ) .unwrap() } - pub fn to_g2(g2: G2Affine) -> ::G2Affine { + pub fn to_g2( + g2: G2Affine, + ) -> ::G2Affine { // apparently the order is reversed let x = T::new_fq2(&(g2.0).1, &(g2.0).0); let y = T::new_fq2(&(g2.1).1, &(g2.1).0); @@ -389,11 +385,12 @@ contract Verifier { #[cfg(test)] mod tests { + use zokrates_field::Bn128Field; + use crate::flat_absy::FlatVariable; use crate::ir::{Function, Interpreter, Prog, Statement}; use super::*; - use zokrates_field::Bn128Field; #[test] fn verify() { diff --git a/zokrates_core/src/proof_system/bellman/mod.rs b/zokrates_core/src/proof_system/bellman/mod.rs index 54b2a53df..527e29c8c 100644 --- a/zokrates_core/src/proof_system/bellman/mod.rs +++ b/zokrates_core/src/proof_system/bellman/mod.rs @@ -1,6 +1,6 @@ pub mod groth16; -extern crate rand; +// extern crate rand; use crate::ir::{CanonicalLinComb, Prog, Statement, Witness}; use bellman::groth16::Proof; @@ -11,10 +11,11 @@ use bellman::groth16::{ use bellman::pairing::ff::ScalarEngine; use bellman::{Circuit, ConstraintSystem, LinearCombination, SynthesisError, Variable}; use std::collections::BTreeMap; +use zokrates_field::BellmanFieldExtensions; use zokrates_field::Field; -use self::rand::ChaChaRng; use crate::flat_absy::FlatVariable; +use rand_0_4::ChaChaRng; pub use self::parse::*; @@ -40,7 +41,7 @@ impl Computation { } } -fn bellman_combination>( +fn bellman_combination>( l: CanonicalLinComb, cs: &mut CS, symbols: &mut BTreeMap, @@ -83,7 +84,7 @@ fn bellman_combination>( .fold(LinearCombination::zero(), |acc, e| acc + e) } -impl Prog { +impl Prog { pub fn synthesize>( self, cs: &mut CS, @@ -160,7 +161,7 @@ impl Prog { } } -impl Computation { +impl Computation { pub fn prove(self, params: &Parameters) -> Proof { let rng = &mut ChaChaRng::new_unseeded(); @@ -198,7 +199,7 @@ impl Computation { } } -impl Circuit for Computation { +impl Circuit for Computation { fn synthesize>( self, cs: &mut CS, @@ -211,7 +212,7 @@ mod parse { use lazy_static::lazy_static; use super::*; - use proof_system::{G1Affine, G2Affine}; + use proof_system::{Fr, G1Affine, G2Affine}; use regex::Regex; lazy_static! { @@ -228,7 +229,7 @@ mod parse { static ref FR_REGEX: Regex = Regex::new(r"Fr\((?P0[xX][0-9a-fA-F]*)\)").unwrap(); } - pub fn parse_g1( + pub fn parse_g1( e: &::G1Affine, ) -> G1Affine { let raw_e = e.to_string(); @@ -239,24 +240,24 @@ mod parse { ) } - pub fn parse_g2( + pub fn parse_g2( e: &::G2Affine, ) -> G2Affine { let raw_e = e.to_string(); let captures = G2_REGEX.captures(&raw_e).unwrap(); G2Affine( - G1Affine( + ( captures.name(&"x1").unwrap().as_str().to_string(), captures.name(&"x0").unwrap().as_str().to_string(), ), - G1Affine( + ( captures.name(&"y1").unwrap().as_str().to_string(), captures.name(&"y0").unwrap().as_str().to_string(), ), ) } - pub fn parse_fr(e: &::Fr) -> String { + pub fn parse_fr(e: &::Fr) -> Fr { let raw_e = e.to_string(); let captures = FR_REGEX.captures(&raw_e).unwrap(); captures.name(&"x").unwrap().as_str().to_string() diff --git a/zokrates_core/src/proof_system/libsnark/ffi.rs b/zokrates_core/src/proof_system/libsnark/ffi.rs index f16b6e90c..065af5ad2 100644 --- a/zokrates_core/src/proof_system/libsnark/ffi.rs +++ b/zokrates_core/src/proof_system/libsnark/ffi.rs @@ -20,7 +20,7 @@ extern "C" { } impl Buffer { - pub fn from_vec(v: &Vec) -> Buffer { + pub unsafe fn from_vec(v: &Vec) -> Buffer { let mut buf = vec![0; v.len()].into_boxed_slice(); buf.copy_from_slice(v.as_slice()); @@ -41,8 +41,7 @@ impl Buffer { Box::from_raw(s); } - /// The purpose of this function is to free memory previously allocated by "malloc" - /// from C standard library. Do not use otherwise. + /// The purpose of this function is to free memory allocated by C. Do not use otherwise. pub fn free(self) { unsafe { __free(self.data) }; } diff --git a/zokrates_core/src/proof_system/libsnark/gm17.rs b/zokrates_core/src/proof_system/libsnark/gm17.rs index cb3f36509..f510b0a9c 100644 --- a/zokrates_core/src/proof_system/libsnark/gm17.rs +++ b/zokrates_core/src/proof_system/libsnark/gm17.rs @@ -2,9 +2,9 @@ use ir; use proof_system::libsnark::ffi::{Buffer, ProofResult, SetupResult}; use proof_system::libsnark::{prepare_generate_proof, prepare_public_inputs, prepare_setup}; use proof_system::solidity::{ - SOLIDITY_G2_ADDITION_LIB, SOLIDITY_PAIRING_LIB, SOLIDITY_PAIRING_LIB_V2, + SolidityAbi, SOLIDITY_G2_ADDITION_LIB, SOLIDITY_PAIRING_LIB, SOLIDITY_PAIRING_LIB_V2, }; -use proof_system::{G1Affine, G2Affine, Proof, ProofSystem, SetupKeypair, SolidityAbi}; +use proof_system::{G1Affine, G2Affine, Proof, ProofSystem, SetupKeypair}; use regex::Regex; use zokrates_field::Bn128Field; @@ -67,7 +67,7 @@ impl ProofSystem for GM17 { let (a_arr, b_arr, c_arr, a_vec, b_vec, c_vec, num_constraints, num_variables, num_inputs) = prepare_setup(program); - let keypair = unsafe { + let (vk, pk) = unsafe { let result: SetupResult = gm17_bn128_setup( a_arr.as_ptr(), b_arr.as_ptr(), @@ -85,16 +85,15 @@ impl ProofSystem for GM17 { let pk: Vec = std::slice::from_raw_parts(result.pk.data, result.pk.length as usize).to_vec(); - // Memory is allocated in C and raw pointers are returned to Rust. The caller has to manually - // free the memory. + // free c allocated buffers result.vk.free(); result.pk.free(); (vk, pk) }; - let vk = serde_json::from_str(String::from_utf8(keypair.0).unwrap().as_str()).unwrap(); - SetupKeypair::new(vk, keypair.1) + let vk = serde_json::from_str(String::from_utf8(vk).unwrap().as_str()).unwrap(); + SetupKeypair::new(vk, pk) } fn generate_proof( @@ -105,9 +104,9 @@ impl ProofSystem for GM17 { let (public_inputs_arr, public_inputs_length, private_inputs_arr, private_inputs_length) = prepare_generate_proof(program, witness); - let mut pk_buffer = Buffer::from_vec(&proving_key); - let proof = unsafe { + let mut pk_buffer = Buffer::from_vec(&proving_key); + let result = gm17_bn128_generate_proof( &mut pk_buffer as *mut _, public_inputs_arr[0].as_ptr(), @@ -122,8 +121,7 @@ impl ProofSystem for GM17 { std::slice::from_raw_parts(result.proof.data, result.proof.length as usize) .to_vec(); - // Memory is allocated in C and raw pointers are returned to Rust. The caller has to manually - // free the memory. + // free c allocated buffer result.proof.free(); proof @@ -239,23 +237,20 @@ impl ProofSystem for GM17 { fn verify(vk: VerificationKey, proof: Proof) -> bool { let vk_raw = hex::decode(vk.raw.clone()).unwrap(); - let proof_raw = hex::decode(proof.raw.clone()).unwrap(); + let proof_raw = hex::decode(proof.raw.unwrap()).unwrap(); let public_inputs: Vec<_> = proof .inputs .iter() - .map(|v| { - Bn128Field::try_from_str(v.as_str().trim_start_matches("0x"), 16) - .expect(format!("Invalid bn128 value: {}", v.as_str()).as_str()) - }) + .map(|v| Bn128Field::try_from_str(v.as_str().trim_start_matches("0x"), 16).unwrap()) .collect(); let (public_inputs_arr, public_inputs_length) = prepare_public_inputs(public_inputs); - let mut vk_buffer = Buffer::from_vec(&vk_raw); - let mut proof_buffer = Buffer::from_vec(&proof_raw); - unsafe { + let mut vk_buffer = Buffer::from_vec(&vk_raw); + let mut proof_buffer = Buffer::from_vec(&proof_raw); + let ans = gm17_bn128_verify( &mut vk_buffer as *mut _, &mut proof_buffer as *mut _, diff --git a/zokrates_core/src/proof_system/libsnark/pghr13.rs b/zokrates_core/src/proof_system/libsnark/pghr13.rs index 27de4416f..e99594a0e 100644 --- a/zokrates_core/src/proof_system/libsnark/pghr13.rs +++ b/zokrates_core/src/proof_system/libsnark/pghr13.rs @@ -2,11 +2,12 @@ use ir; use proof_system::libsnark::ffi::{Buffer, ProofResult, SetupResult}; use proof_system::libsnark::{prepare_generate_proof, prepare_public_inputs, prepare_setup}; use proof_system::solidity::{ - SOLIDITY_G2_ADDITION_LIB, SOLIDITY_PAIRING_LIB, SOLIDITY_PAIRING_LIB_V2, + SolidityAbi, SOLIDITY_G2_ADDITION_LIB, SOLIDITY_PAIRING_LIB, SOLIDITY_PAIRING_LIB_V2, }; -use proof_system::{G1Affine, G2Affine, Proof, ProofSystem, SetupKeypair, SolidityAbi}; +use proof_system::{G1Affine, G2Affine, Proof, ProofSystem, SetupKeypair}; use regex::Regex; +use zokrates_field::bn128::FieldPrime; use zokrates_field::Bn128Field; use zokrates_field::Field; @@ -74,7 +75,7 @@ impl ProofSystem for PGHR13 { let (a_arr, b_arr, c_arr, a_vec, b_vec, c_vec, num_constraints, num_variables, num_inputs) = prepare_setup(program); - let keypair = unsafe { + let (vk, pk) = unsafe { let result: SetupResult = pghr13_bn128_setup( a_arr.as_ptr(), b_arr.as_ptr(), @@ -92,29 +93,28 @@ impl ProofSystem for PGHR13 { let pk: Vec = std::slice::from_raw_parts(result.pk.data, result.pk.length as usize).to_vec(); - // Memory is allocated in C and raw pointers are returned to Rust. The caller has to manually - // free the memory. + // free c allocated buffers result.vk.free(); result.pk.free(); (vk, pk) }; - let vk = serde_json::from_str(String::from_utf8(keypair.0).unwrap().as_str()).unwrap(); - SetupKeypair::new(vk, keypair.1) + let vk = serde_json::from_str(String::from_utf8(vk).unwrap().as_str()).unwrap(); + SetupKeypair::new(vk, pk) } fn generate_proof( - program: ir::Prog, - witness: ir::Witness, + program: ir::Prog, + witness: ir::Witness, proving_key: Vec, ) -> Proof { let (public_inputs_arr, public_inputs_length, private_inputs_arr, private_inputs_length) = prepare_generate_proof(program, witness); - let mut pk_buf = Buffer::from_vec(&proving_key); - let proof = unsafe { + let mut pk_buf = Buffer::from_vec(&proving_key); + let result = pghr13_bn128_generate_proof( &mut pk_buf as *mut _, public_inputs_arr[0].as_ptr(), @@ -129,8 +129,7 @@ impl ProofSystem for PGHR13 { std::slice::from_raw_parts(result.proof.data, result.proof.length as usize) .to_vec(); - // Memory is allocated in C and raw pointers are returned to Rust. The caller has to manually - // free the memory. + // free c allocated buffer result.proof.free(); proof @@ -251,23 +250,20 @@ impl ProofSystem for PGHR13 { fn verify(vk: VerificationKey, proof: Proof) -> bool { let vk_raw = hex::decode(vk.raw.clone()).unwrap(); - let proof_raw = hex::decode(proof.raw.clone()).unwrap(); + let proof_raw = hex::decode(proof.raw.unwrap()).unwrap(); let public_inputs: Vec<_> = proof .inputs .iter() - .map(|v| { - Bn128Field::try_from_str(v.as_str().trim_start_matches("0x"), 16) - .expect(format!("Invalid bn128 value: {}", v.as_str()).as_str()) - }) + .map(|v| Bn128Field::try_from_str(v.as_str().trim_start_matches("0x"), 16).unwrap()) .collect(); let (public_inputs_arr, public_inputs_length) = prepare_public_inputs(public_inputs); - let mut vk_buffer = Buffer::from_vec(&vk_raw); - let mut proof_buffer = Buffer::from_vec(&proof_raw); - unsafe { + let mut vk_buffer = Buffer::from_vec(&vk_raw); + let mut proof_buffer = Buffer::from_vec(&proof_raw); + let ans = pghr13_bn128_verify( &mut vk_buffer as *mut _, &mut proof_buffer as *mut _, diff --git a/zokrates_core/src/proof_system/mod.rs b/zokrates_core/src/proof_system/mod.rs index c5eb20fda..72ee05b4f 100644 --- a/zokrates_core/src/proof_system/mod.rs +++ b/zokrates_core/src/proof_system/mod.rs @@ -1,16 +1,16 @@ pub mod bellman; #[cfg(feature = "libsnark")] pub mod libsnark; +pub mod zexe; -mod solidity; +pub mod solidity; use crate::ir; +use proof_system::solidity::SolidityAbi; use serde::de::DeserializeOwned; use serde::Serialize; use zokrates_field::Field; -// We only need to serialize this struct, there is no need for deserialization as keys are -// used separately in other use cases #[derive(Serialize)] pub struct SetupKeypair { pub vk: V, @@ -23,39 +23,33 @@ impl SetupKeypair { } } -pub enum SolidityAbi { - V1, - V2, -} - -impl SolidityAbi { - pub fn from(v: &str) -> Result { - match v { - "v1" => Ok(SolidityAbi::V1), - "v2" => Ok(SolidityAbi::V2), - _ => Err("Invalid ABI version"), - } - } -} - #[derive(Serialize, Deserialize)] pub struct Proof { proof: T, inputs: Vec, - raw: String, + raw: Option, } impl Proof { - fn new(proof: T, inputs: Vec, raw: String) -> Self { + fn new(proof: T, inputs: Vec, raw: Option) -> Self { Proof { proof, inputs, raw } } } +pub type Fr = String; +pub type Fq = String; +pub type Fq2 = (String, String); + #[derive(Serialize, Deserialize)] -pub struct G1Affine(String, String); +pub struct G1Affine(Fq, Fq); +// When G2 is defined on Fq2 field #[derive(Serialize, Deserialize)] -pub struct G2Affine(G1Affine, G1Affine); +pub struct G2Affine(Fq2, Fq2); + +// When G2 is defined on a Fq field (BW6_761 curve) +#[derive(Serialize, Deserialize)] +pub struct G2AffineFq(Fq, Fq); impl ToString for G1Affine { fn to_string(&self) -> String { @@ -63,9 +57,20 @@ impl ToString for G1Affine { } } +impl ToString for G2AffineFq { + fn to_string(&self) -> String { + format!("{}, {}", self.0, self.1) + } +} impl ToString for G2Affine { fn to_string(&self) -> String { - format!("[{}], [{}]", self.0.to_string(), self.1.to_string()) + format!( + "[{}, {}], [{}, {}]", + (self.0).0, + (self.0).1, + (self.1).0, + (self.1).1 + ) } } diff --git a/zokrates_core/src/proof_system/solidity.rs b/zokrates_core/src/proof_system/solidity.rs index bb6b6eb88..aec75334a 100644 --- a/zokrates_core/src/proof_system/solidity.rs +++ b/zokrates_core/src/proof_system/solidity.rs @@ -1,3 +1,18 @@ +pub enum SolidityAbi { + V1, + V2, +} + +impl SolidityAbi { + pub fn from(v: &str) -> Result { + match v { + "v1" => Ok(SolidityAbi::V1), + "v2" => Ok(SolidityAbi::V2), + _ => Err("Invalid ABI version"), + } + } +} + pub const SOLIDITY_G2_ADDITION_LIB: &str = r#"// This file is LGPL3 Licensed pragma solidity ^0.6.1; diff --git a/zokrates_core/src/proof_system/zexe/gm17.rs b/zokrates_core/src/proof_system/zexe/gm17.rs new file mode 100644 index 000000000..6811099b7 --- /dev/null +++ b/zokrates_core/src/proof_system/zexe/gm17.rs @@ -0,0 +1,365 @@ +use zexe_gm17::{ + prepare_verifying_key, verify_proof, Parameters, PreparedVerifyingKey, Proof as ZexeProof, + VerifyingKey, +}; + +use algebra_core::serialize::{CanonicalDeserialize, CanonicalSerialize}; +use zokrates_field::{ + Bls12_377Field, Bls12_381Field, Bn128Field, Bw6_761Field, Field, ZexeFieldExtensions, +}; + +use crate::ir; +use crate::proof_system::zexe::Computation; +use crate::proof_system::zexe::{parse_fr, parse_g1, parse_g2, parse_g2_fq}; +use proof_system::solidity::SolidityAbi; +use proof_system::{G1Affine, G2Affine, G2AffineFq, Proof, ProofSystem, SetupKeypair}; + +pub struct GM17 {} + +pub trait NotBw6_761Field {} +impl NotBw6_761Field for Bls12_377Field {} +impl NotBw6_761Field for Bls12_381Field {} +impl NotBw6_761Field for Bn128Field {} + +#[derive(Serialize, Deserialize)] +pub struct ProofPoints { + a: G1Affine, + b: G2Affine, + c: G1Affine, +} + +#[derive(Serialize, Deserialize)] +pub struct VerificationKey { + h: G2Affine, + g_alpha: G1Affine, + h_beta: G2Affine, + g_gamma: G1Affine, + h_gamma: G2Affine, + query: Vec, +} + +impl ProofSystem for GM17 { + type VerificationKey = VerificationKey; + type ProofPoints = ProofPoints; + + fn setup(program: ir::Prog) -> SetupKeypair { + let parameters = Computation::without_witness(program).setup(); + + let mut pk: Vec = Vec::new(); + parameters.serialize_uncompressed(&mut pk).unwrap(); + + let vk = VerificationKey { + h: parse_g2::(¶meters.vk.h_g2), + g_alpha: parse_g1::(¶meters.vk.g_alpha_g1), + h_beta: parse_g2::(¶meters.vk.h_beta_g2), + g_gamma: parse_g1::(¶meters.vk.g_gamma_g1), + h_gamma: parse_g2::(¶meters.vk.h_gamma_g2), + query: parameters + .vk + .query + .iter() + .map(|g1| parse_g1::(g1)) + .collect(), + }; + + SetupKeypair::new(vk, pk) + } + + fn generate_proof( + program: ir::Prog, + witness: ir::Witness, + proving_key: Vec, + ) -> Proof { + let computation = Computation::with_witness(program, witness); + let params = + Parameters::<::ZexeEngine>::deserialize_uncompressed( + &mut proving_key.as_slice(), + ) + .unwrap(); + + let proof = computation.clone().prove(¶ms); + let proof_points = ProofPoints { + a: parse_g1::(&proof.a), + b: parse_g2::(&proof.b), + c: parse_g1::(&proof.c), + }; + + let inputs = computation + .public_inputs_values() + .iter() + .map(parse_fr::) + .collect::>(); + + Proof::::new(proof_points, inputs, None) + } + + fn export_solidity_verifier(_vk: VerificationKey, _abi: SolidityAbi) -> String { + unimplemented!() + } + + fn verify(vk: VerificationKey, proof: Proof) -> bool { + let vk = VerifyingKey { + h_g2: serialization::to_g2::(vk.h), + g_alpha_g1: serialization::to_g1::(vk.g_alpha), + h_beta_g2: serialization::to_g2::(vk.h_beta), + g_gamma_g1: serialization::to_g1::(vk.g_gamma), + h_gamma_g2: serialization::to_g2::(vk.h_gamma), + query: vk + .query + .into_iter() + .map(|g1| serialization::to_g1::(g1)) + .collect(), + }; + + let zexe_proof = ZexeProof { + a: serialization::to_g1::(proof.proof.a), + b: serialization::to_g2::(proof.proof.b), + c: serialization::to_g1::(proof.proof.c), + }; + + let pvk: PreparedVerifyingKey<::ZexeEngine> = + prepare_verifying_key(&vk); + + let public_inputs: Vec<_> = proof + .inputs + .iter() + .map(|s| { + T::try_from_str(s.trim_start_matches("0x"), 16) + .unwrap() + .into_zexe() + }) + .collect::>(); + + verify_proof(&pvk, &zexe_proof, &public_inputs).unwrap() + } +} + +#[derive(Serialize, Deserialize)] +pub struct ProofPointsG2Fq { + a: G1Affine, + b: G2AffineFq, + c: G1Affine, +} + +#[derive(Serialize, Deserialize)] +pub struct VerificationKeyG2Fq { + h: G2AffineFq, + g_alpha: G1Affine, + h_beta: G2AffineFq, + g_gamma: G1Affine, + h_gamma: G2AffineFq, + query: Vec, +} + +impl ProofSystem for GM17 { + type VerificationKey = VerificationKeyG2Fq; + type ProofPoints = ProofPointsG2Fq; + + fn setup(program: ir::Prog) -> SetupKeypair { + let parameters = Computation::without_witness(program).setup(); + + let mut pk: Vec = Vec::new(); + parameters.serialize_uncompressed(&mut pk).unwrap(); + + let vk = VerificationKeyG2Fq { + h: parse_g2_fq::(¶meters.vk.h_g2), + g_alpha: parse_g1::(¶meters.vk.g_alpha_g1), + h_beta: parse_g2_fq::(¶meters.vk.h_beta_g2), + g_gamma: parse_g1::(¶meters.vk.g_gamma_g1), + h_gamma: parse_g2_fq::(¶meters.vk.h_gamma_g2), + query: parameters + .vk + .query + .iter() + .map(|g1| parse_g1::(g1)) + .collect(), + }; + + SetupKeypair::new(vk, pk) + } + + fn generate_proof( + program: ir::Prog, + witness: ir::Witness, + proving_key: Vec, + ) -> Proof { + let computation = Computation::with_witness(program, witness); + let params = Parameters::<::ZexeEngine>::deserialize_uncompressed( + &mut proving_key.as_slice(), + ) + .unwrap(); + + let proof = computation.clone().prove(¶ms); + let proof_points = ProofPointsG2Fq { + a: parse_g1::(&proof.a), + b: parse_g2_fq::(&proof.b), + c: parse_g1::(&proof.c), + }; + + let inputs = computation + .public_inputs_values() + .iter() + .map(parse_fr::) + .collect::>(); + + Proof::::new(proof_points, inputs, None) + } + + fn export_solidity_verifier(_vk: VerificationKeyG2Fq, _abi: SolidityAbi) -> String { + unimplemented!() + } + + fn verify(vk: VerificationKeyG2Fq, proof: Proof) -> bool { + let vk = VerifyingKey { + h_g2: serialization::to_g2_fq::(vk.h), + g_alpha_g1: serialization::to_g1::(vk.g_alpha), + h_beta_g2: serialization::to_g2_fq::(vk.h_beta), + g_gamma_g1: serialization::to_g1::(vk.g_gamma), + h_gamma_g2: serialization::to_g2_fq::(vk.h_gamma), + query: vk + .query + .into_iter() + .map(|g1| serialization::to_g1::(g1)) + .collect(), + }; + + let zexe_proof = ZexeProof { + a: serialization::to_g1::(proof.proof.a), + b: serialization::to_g2_fq::(proof.proof.b), + c: serialization::to_g1::(proof.proof.c), + }; + + let pvk: PreparedVerifyingKey<::ZexeEngine> = + prepare_verifying_key(&vk); + + let public_inputs: Vec<_> = proof + .inputs + .iter() + .map(|s| { + Bw6_761Field::try_from_str(s.trim_start_matches("0x"), 16) + .expect(format!("Invalid {} value: {}", Bw6_761Field::name(), s).as_str()) + .into_zexe() + }) + .collect::>(); + + verify_proof(&pvk, &zexe_proof, &public_inputs).unwrap() + } +} + +pub mod serialization { + use algebra_core::{AffineCurve, PairingEngine}; + use num_bigint::BigUint; + use proof_system::{G1Affine, G2Affine, G2AffineFq}; + use std::str::FromStr; + use zokrates_field::ZexeFieldExtensions; + + fn to_dec_string(s: String) -> String { + BigUint::from_bytes_be( + hex::decode(s.strip_prefix("0x").unwrap()) + .unwrap() + .as_slice(), + ) + .to_str_radix(10) + } + + pub fn to_g1( + g1: G1Affine, + ) -> ::G1Affine { + let x = ::Fq::from_str(to_dec_string(g1.0).as_str()) + .map_err(|_| ()) + .unwrap(); + + let y = ::Fq::from_str(to_dec_string(g1.1).as_str()) + .map_err(|_| ()) + .unwrap(); + + ::G1Affine::from_xy_checked(x, y).unwrap() + } + + pub fn to_g2( + g2: G2Affine, + ) -> ::G2Affine { + let x = T::new_fqe(vec![ + to_dec_string((g2.0).0).as_str(), + to_dec_string((g2.0).1).as_str(), + ]); + let y = T::new_fqe(vec![ + to_dec_string((g2.1).0).as_str(), + to_dec_string((g2.1).1).as_str(), + ]); + ::G2Affine::from_xy_checked(x, y).unwrap() + } + + pub fn to_g2_fq( + g2: G2AffineFq, + ) -> ::G2Affine { + let x = T::new_fqe(vec![to_dec_string(g2.0).as_str()]); + let y = T::new_fqe(vec![to_dec_string(g2.1).as_str()]); + ::G2Affine::from_xy_checked(x, y).unwrap() + } +} + +#[cfg(test)] +mod tests { + use crate::flat_absy::FlatVariable; + use crate::ir::{Function, Interpreter, Prog, Statement}; + + use super::*; + use zokrates_field::{Bls12_377Field, Bw6_761Field}; + + #[test] + fn verify_bls12_377_field() { + let program: Prog = Prog { + main: Function { + id: String::from("main"), + arguments: vec![FlatVariable::new(0)], + returns: vec![FlatVariable::public(0)], + statements: vec![Statement::Constraint( + FlatVariable::new(0).into(), + FlatVariable::public(0).into(), + )], + }, + private: vec![false], + }; + + let keypair = GM17::setup(program.clone()); + let interpreter = Interpreter::default(); + + let witness = interpreter + .execute(&program, &vec![Bls12_377Field::from(42)]) + .unwrap(); + + let proof = GM17::generate_proof(program, witness, keypair.pk); + let ans = >::verify(keypair.vk, proof); + + assert!(ans); + } + + #[test] + fn verify_bw6_761_field() { + let program: Prog = Prog { + main: Function { + id: String::from("main"), + arguments: vec![FlatVariable::new(0)], + returns: vec![FlatVariable::public(0)], + statements: vec![Statement::Constraint( + FlatVariable::new(0).into(), + FlatVariable::public(0).into(), + )], + }, + private: vec![false], + }; + + let keypair = GM17::setup(program.clone()); + let interpreter = Interpreter::default(); + + let witness = interpreter + .execute(&program, &vec![Bw6_761Field::from(42)]) + .unwrap(); + + let proof = GM17::generate_proof(program, witness, keypair.pk); + let ans = >::verify(keypair.vk, proof); + + assert!(ans); + } +} \ No newline at end of file diff --git a/zokrates_core/src/proof_system/zexe/mod.rs b/zokrates_core/src/proof_system/zexe/mod.rs new file mode 100644 index 000000000..075a6c9d1 --- /dev/null +++ b/zokrates_core/src/proof_system/zexe/mod.rs @@ -0,0 +1,304 @@ +pub mod gm17; + +use crate::ir::{CanonicalLinComb, Prog, Statement, Witness}; +use zexe_gm17::Proof; +use zexe_gm17::{ + create_random_proof, generate_random_parameters, prepare_verifying_key, verify_proof, + Parameters, +}; + +use crate::flat_absy::FlatVariable; +use algebra_core::PairingEngine; +use r1cs_core::{ + ConstraintSynthesizer, ConstraintSystem, ConstraintSystemRef, LinearCombination, + SynthesisError, Variable, +}; +use std::collections::BTreeMap; +use zokrates_field::{Field, ZexeFieldExtensions}; + +pub use self::parse::*; + +use rand_0_7::SeedableRng; + +#[derive(Clone)] +pub struct Computation { + program: Prog, + witness: Option>, +} + +impl Computation { + pub fn with_witness(program: Prog, witness: Witness) -> Self { + Computation { + program, + witness: Some(witness), + } + } + + pub fn without_witness(program: Prog) -> Self { + Computation { + program, + witness: None, + } + } +} + +fn zexe_combination( + l: CanonicalLinComb, + cs: &mut ConstraintSystem<<::ZexeEngine as PairingEngine>::Fr>, + symbols: &mut BTreeMap, + witness: &mut Witness, +) -> Result< + LinearCombination<<::ZexeEngine as PairingEngine>::Fr>, + SynthesisError, +> { + let lc = + l.0.into_iter() + .map(|(k, v)| { + ( + v.into_zexe(), + symbols + .entry(k) + .or_insert_with(|| { + match k.is_output() { + true => cs.new_input_variable(|| { + Ok(witness + .0 + .remove(&k) + .ok_or(SynthesisError::AssignmentMissing)? + .into_zexe()) + }), + false => cs.new_witness_variable(|| { + Ok(witness + .0 + .remove(&k) + .ok_or(SynthesisError::AssignmentMissing)? + .into_zexe()) + }), + } + .unwrap() + }) + .clone(), + ) + }) + .fold(LinearCombination::zero(), |acc, e| acc + e); + + Ok(lc) +} + +impl Prog { + pub fn generate_constraints( + self, + cs: ConstraintSystemRef<<::ZexeEngine as PairingEngine>::Fr>, + witness: Option>, + ) -> Result<(), SynthesisError> { + // mapping from IR variables + let mut symbols = BTreeMap::new(); + + let mut witness = witness.unwrap_or(Witness::empty()); + + assert!(symbols.insert(FlatVariable::one(), ConstraintSystem::<<::ZexeEngine as PairingEngine>::Fr>::one()).is_none()); + + match cs { + ConstraintSystemRef::CS(rc) => { + let mut cs = rc.borrow_mut(); + symbols.extend( + self.main + .arguments + .iter() + .zip(self.private) + .enumerate() + .map(|(_, (var, private))| { + let wire = match private { + true => cs.new_witness_variable(|| { + Ok(witness + .0 + .remove(&var) + .ok_or(SynthesisError::AssignmentMissing)? + .into_zexe()) + }), + false => cs.new_input_variable(|| { + Ok(witness + .0 + .remove(&var) + .ok_or(SynthesisError::AssignmentMissing)? + .into_zexe()) + }), + } + .unwrap(); + (var.clone(), wire) + }), + ); + + let main = self.main; + + for statement in main.statements { + match statement { + Statement::Constraint(quad, lin) => { + let a = zexe_combination( + quad.left.clone().into_canonical(), + &mut cs, + &mut symbols, + &mut witness, + )?; + let b = zexe_combination( + quad.right.clone().into_canonical(), + &mut cs, + &mut symbols, + &mut witness, + )?; + let c = zexe_combination( + lin.into_canonical(), + &mut cs, + &mut symbols, + &mut witness, + )?; + + cs.enforce_constraint(a, b, c)?; + } + _ => {} + } + } + + Ok(()) + } + ConstraintSystemRef::None => Err(SynthesisError::MissingCS), + } + } +} + +impl Computation { + pub fn prove(self, params: &Parameters) -> Proof { + let rng = &mut rand_0_7::rngs::StdRng::from_entropy(); + + let proof = create_random_proof(self.clone(), params, rng).unwrap(); + + let pvk = prepare_verifying_key(¶ms.vk); + + // extract public inputs + let public_inputs = self.public_inputs_values(); + + assert!(verify_proof(&pvk, &proof, &public_inputs).unwrap()); + + proof + } + + pub fn public_inputs_values(&self) -> Vec<::Fr> { + self.program + .main + .arguments + .clone() + .iter() + .zip(self.program.private.clone()) + .filter(|(_, p)| !p) + .map(|(a, _)| a) + .map(|v| self.witness.clone().unwrap().0.get(v).unwrap().clone()) + .chain(self.witness.clone().unwrap().return_values()) + .map(|v| v.clone().into_zexe()) + .collect() + } + + pub fn setup(self) -> Parameters { + let rng = &mut rand_0_7::rngs::StdRng::from_entropy(); + + // run setup phase + generate_random_parameters(self, rng).unwrap() + } +} + +impl + ConstraintSynthesizer<<::ZexeEngine as PairingEngine>::Fr> + for Computation +{ + fn generate_constraints( + self, + cs: ConstraintSystemRef<<::ZexeEngine as PairingEngine>::Fr>, + ) -> Result<(), SynthesisError> { + self.program.generate_constraints(cs, self.witness) + } +} + +mod parse { + use lazy_static::lazy_static; + + use super::*; + use proof_system::{Fr, G1Affine, G2Affine, G2AffineFq}; + use regex::Regex; + + lazy_static! { + pub static ref G2_REGEX: Regex = Regex::new(r#"GroupAffine\(x=QuadExtField\(Fp\d{3} "\((?P[0-9a-fA-F]*)\)" \+ Fp\d{3} "\((?P[0-9a-fA-F]*)\)" \* u\), y=QuadExtField\(Fp\d{3} "\((?P[0-9a-fA-F]*)\)" \+ Fp\d{3} "\((?P[0-9a-fA-F]*)\)" \* u\)\)"#).unwrap(); + } + + lazy_static! { + static ref G1_REGEX: Regex = + Regex::new(r#"GroupAffine\(x=Fp\d{3} "\((?P[0-9a-fA-F]*)\)", y=Fp\d{3} "\((?P[0-9a-fA-F]*)\)"\)"#) + .unwrap(); + } + + lazy_static! { + static ref FR_REGEX: Regex = Regex::new(r#"Fp\d{3} "\((?P[0-9a-fA-F]*)\)""#).unwrap(); + } + + lazy_static! { + pub static ref G1_G2_REGEX_FQ: Regex = Regex::new(r#"GroupAffine\(x=Fp\d{3} "\((?P[0-9a-fA-F]*)\)", y=Fp\d{3} "\((?P[0-9a-fA-F]*)\)"\)"#).unwrap(); + } + + lazy_static! { + static ref FR_REGEX_FQ: Regex = Regex::new(r#"Fp\d{3} "\((?P[0-9a-fA-F]*)\)""#).unwrap(); + } + + pub fn parse_g1( + e: &::G1Affine, + ) -> G1Affine { + let raw_e = e.to_string(); + match T::name() { + "bw6_761" => { + let captures = G1_G2_REGEX_FQ.captures(&raw_e).unwrap(); + G1Affine( + ("0x".to_string() + captures.name(&"x").unwrap().as_str()).to_string(), + ("0x".to_string() + captures.name(&"y").unwrap().as_str()).to_string(), + ) + } + _ => { + let captures = G1_REGEX.captures(&raw_e).unwrap(); + G1Affine( + ("0x".to_string() + captures.name(&"x").unwrap().as_str()).to_string(), + ("0x".to_string() + captures.name(&"y").unwrap().as_str()).to_string(), + ) + } + } + } + + pub fn parse_g2( + e: &::G2Affine, + ) -> G2Affine { + let raw_e = e.to_string(); + let captures = G2_REGEX.captures(&raw_e).unwrap(); + G2Affine( + ( + ("0x".to_string() + captures.name(&"x0").unwrap().as_str()).to_string(), + ("0x".to_string() + captures.name(&"x1").unwrap().as_str()).to_string(), + ), + ( + ("0x".to_string() + captures.name(&"y0").unwrap().as_str()).to_string(), + ("0x".to_string() + captures.name(&"y1").unwrap().as_str()).to_string(), + ), + ) + } + + pub fn parse_g2_fq( + e: &::G2Affine, + ) -> G2AffineFq { + let raw_e = e.to_string(); + let captures = G1_G2_REGEX_FQ.captures(&raw_e).unwrap(); + G2AffineFq( + ("0x".to_string() + captures.name(&"x").unwrap().as_str()).to_string(), + ("0x".to_string() + captures.name(&"y").unwrap().as_str()).to_string(), + ) + } + + pub fn parse_fr(e: &::Fr) -> Fr { + let raw_e = e.to_string(); + let captures = FR_REGEX.captures(&raw_e).unwrap(); + ("0x".to_string() + captures.name(&"x").unwrap().as_str()).to_string() + } +} diff --git a/zokrates_core_test/tests/tests/add.json b/zokrates_core_test/tests/tests/add.json index 9f92f1395..9a2526ce5 100644 --- a/zokrates_core_test/tests/tests/add.json +++ b/zokrates_core_test/tests/tests/add.json @@ -1,6 +1,6 @@ { "entry_point": "./tests/tests/add.zok", - "curves": ["Bn128", "Bls12"], + "curves": ["Bn128", "Bls12_381", "Bls12_377", "Bw6_761"], "tests": [ { "input": { @@ -26,4 +26,4 @@ } } ] -} \ No newline at end of file +} diff --git a/zokrates_core_test/tests/tests/array_if.json b/zokrates_core_test/tests/tests/array_if.json index e21aecc7f..1a0195409 100644 --- a/zokrates_core_test/tests/tests/array_if.json +++ b/zokrates_core_test/tests/tests/array_if.json @@ -1,6 +1,6 @@ { "entry_point": "./tests/tests/array_if.zok", - "curves": ["Bn128", "Bls12"], + "curves": ["Bn128", "Bls12_381", "Bls12_377", "Bw6_761"], "tests": [ { "input": { @@ -23,4 +23,4 @@ } } ] -} \ No newline at end of file +} diff --git a/zokrates_core_test/tests/tests/arrays/identity.json b/zokrates_core_test/tests/tests/arrays/identity.json index 6f5eb1d24..c8c09190e 100644 --- a/zokrates_core_test/tests/tests/arrays/identity.json +++ b/zokrates_core_test/tests/tests/arrays/identity.json @@ -1,6 +1,6 @@ { "entry_point": "./tests/tests/arrays/identity.code", - "curves": ["Bn128", "Bls12"], + "curves": ["Bn128", "Bls12_381", "Bls12_377", "Bw6_761"], "tests": [ { "input": { @@ -36,4 +36,4 @@ } } ] -} \ No newline at end of file +} diff --git a/zokrates_core_test/tests/tests/assert_one.json b/zokrates_core_test/tests/tests/assert_one.json index 7d1d9968f..0b09dccd0 100644 --- a/zokrates_core_test/tests/tests/assert_one.json +++ b/zokrates_core_test/tests/tests/assert_one.json @@ -1,6 +1,6 @@ { "entry_point": "./tests/tests/assert_one.zok", - "curves": ["Bn128", "Bls12"], + "curves": ["Bn128", "Bls12_381", "Bls12_377", "Bw6_761"], "tests": [ { "input": { @@ -16,4 +16,4 @@ } } ] -} \ No newline at end of file +} diff --git a/zokrates_core_test/tests/tests/bool_compare.json b/zokrates_core_test/tests/tests/bool_compare.json index 1347de068..502380697 100644 --- a/zokrates_core_test/tests/tests/bool_compare.json +++ b/zokrates_core_test/tests/tests/bool_compare.json @@ -1,6 +1,6 @@ { "entry_point": "./tests/tests/bool_compare.zok", - "curves": ["Bn128", "Bls12"], + "curves": ["Bn128", "Bls12_381", "Bls12_377", "Bw6_761"], "tests": [ { "input": { @@ -48,4 +48,4 @@ } } ] -} \ No newline at end of file +} diff --git a/zokrates_core_test/tests/tests/fact_up_to_4.json b/zokrates_core_test/tests/tests/fact_up_to_4.json index f515c6a98..96930c2c0 100644 --- a/zokrates_core_test/tests/tests/fact_up_to_4.json +++ b/zokrates_core_test/tests/tests/fact_up_to_4.json @@ -1,6 +1,6 @@ { "entry_point": "./tests/tests/fact_up_to_4.zok", - "curves": ["Bn128", "Bls12"], + "curves": ["Bn128", "Bls12_381", "Bls12_377", "Bw6_761"], "tests": [ { "input": { @@ -53,4 +53,4 @@ } } ] -} \ No newline at end of file +} diff --git a/zokrates_core_test/tests/tests/precedence.json b/zokrates_core_test/tests/tests/precedence.json index 5cf9609d6..9c2f0b0df 100644 --- a/zokrates_core_test/tests/tests/precedence.json +++ b/zokrates_core_test/tests/tests/precedence.json @@ -1,6 +1,6 @@ { "entry_point": "./tests/tests/precedence.zok", - "curves": ["Bn128", "Bls12"], + "curves": ["Bn128", "Bls12_381", "Bls12_377", "Bw6_761"], "tests": [ { "input": { @@ -13,4 +13,4 @@ } } ] -} \ No newline at end of file +} diff --git a/zokrates_core_test/tests/tests/split_bls.json b/zokrates_core_test/tests/tests/split_bls.json index 304d435d7..ee9ce853d 100644 --- a/zokrates_core_test/tests/tests/split_bls.json +++ b/zokrates_core_test/tests/tests/split_bls.json @@ -1,6 +1,6 @@ { "entry_point": "./tests/tests/split_bls.zok", - "curves": ["Bls12"], + "curves": ["Bls12_381"], "tests": [ { "input": { @@ -8,7 +8,7 @@ }, "output": { "Ok": { - "values": ["0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "1", "1", "0", "1", "0", "0", "1", "1", "0", "0", "0", "1", "0", "0", "0", "0", "1", "0", "1", "1", "0", "0", "0", "0", "0", "0", "1", "0", "1", "0", "0", "0", "0", "0", "1", "0", "1", "1", "1", "0", "1", "1", "0", "0", "0", "0", "1", "1", "1", "1", "0", "0", "0", "0", "0", "1", "1", "0", "1", "0", "0", "0", "1", "1", "0", "1", "1", "0", "0", "1", "0", "0", "0", "0", "0", "0", "0", "1", "1", "0", "1", "1", "0", "1", "0", "1", "1", "0", "1", "0", "0", "1", "1", "0", "1", "1", "0", "1", "0", "1", "1", "1", "1", "0", "1", "0", "1", "0", "0", "1", "1", "1", "1", "0", "1", "0", "0", "1", "0", "1", "1", "0", "1", "1", "0", "0", "0"] + "values": ["0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "1", "1", "0", "1", "0", "0", "1", "1", "0", "0", "0", "1", "0", "0", "0", "0", "1", "0", "1", "1", "0", "0", "0", "0", "0", "0", "1", "0", "1", "0", "0", "0", "0", "0", "1", "0", "1", "1", "1", "0", "1", "1", "0", "0", "0", "0", "1", "1", "1", "1", "0", "0", "0", "0", "0", "1", "1", "0", "1", "0", "0", "0", "1", "1", "0", "1", "1", "0", "0", "1", "0", "0", "0", "0", "0", "0", "0", "1", "1", "0", "1", "1", "0", "1", "0", "1", "1", "0", "1", "0", "0", "1", "1", "0", "1", "1", "0", "1", "0", "1", "1", "1", "1", "0", "1", "0", "1", "0", "0", "1", "1", "1", "1", "0", "1", "0", "0", "1", "0", "1", "1", "0", "1", "1", "0", "0", "0"] } } }, @@ -28,7 +28,7 @@ }, "output": { "Ok": { - "values": ["0", "0", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1"] + "values": ["0", "0", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1"] } } }, @@ -43,4 +43,4 @@ } } ] -} \ No newline at end of file +} diff --git a/zokrates_core_test/tests/tests/spread_slice.json b/zokrates_core_test/tests/tests/spread_slice.json index 84c641ed2..ea0a9c290 100644 --- a/zokrates_core_test/tests/tests/spread_slice.json +++ b/zokrates_core_test/tests/tests/spread_slice.json @@ -1,6 +1,6 @@ { "entry_point": "./tests/tests/spread_slice.zok", - "curves": ["Bn128", "Bls12"], + "curves": ["Bn128", "Bls12_381", "Bls12_377", "Bw6_761"], "max_constraint_count": 9, "tests": [ { @@ -14,4 +14,4 @@ } } ] -} \ No newline at end of file +} diff --git a/zokrates_core_test/tests/tests/structs/identity.json b/zokrates_core_test/tests/tests/structs/identity.json index af3c43e0d..15db3e868 100644 --- a/zokrates_core_test/tests/tests/structs/identity.json +++ b/zokrates_core_test/tests/tests/structs/identity.json @@ -1,6 +1,6 @@ { "entry_point": "./tests/tests/structs/identity.code", - "curves": ["Bn128", "Bls12"], + "curves": ["Bn128", "Bls12_381", "Bls12_377", "Bw6_761"], "tests": [ { "input": { @@ -36,4 +36,4 @@ } } ] -} \ No newline at end of file +} diff --git a/zokrates_field/Cargo.toml b/zokrates_field/Cargo.toml index 959f34bbb..e765a8718 100644 --- a/zokrates_field/Cargo.toml +++ b/zokrates_field/Cargo.toml @@ -10,10 +10,17 @@ serde_derive = "1.0" lazy_static = "1.4" bincode = "0.8.0" serde_json = "1.0" +bellman_ce = { version = "^0.3", default-features = false} +algebra-core = { git = "https://github.com/dark64/zexe.git", branch = "dark64-patch", version = "0.1.1-alpha.0", features = ["parallel"] } sha2 = "0.8.0" num-traits = { version = "0.2", default-features = false } num-integer = { version = "0.1", default-features = false } -bellman_ce = { version = "^0.3", default-features = false } + +[dependencies.algebra] +git = "https://github.com/dark64/zexe.git" +branch = "dark64-patch" +version = "0.1.1-alpha.0" +features = ["bn254", "bls12_377", "bw6_761", "parallel"] [dev-dependencies] rand = "0.4" diff --git a/zokrates_field/src/bls12_377.rs b/zokrates_field/src/bls12_377.rs new file mode 100644 index 000000000..e0df0a84a --- /dev/null +++ b/zokrates_field/src/bls12_377.rs @@ -0,0 +1,7 @@ +use algebra::bls12_377::{Bls12_377, Fq2}; + +prime_field!( + b"8444461749428370424248824938781546531375899335154063827935233455917409239041", + "bls12_377" +); +zexe_extensions!(Bls12_377, Fq2); diff --git a/zokrates_field/src/bls12_381.rs b/zokrates_field/src/bls12_381.rs index 08abcacc2..fa9e867f5 100644 --- a/zokrates_field/src/bls12_381.rs +++ b/zokrates_field/src/bls12_381.rs @@ -2,7 +2,6 @@ use bellman_ce::pairing::bls12_381::{Bls12, Fq2}; prime_field!( b"52435875175126190479447740508185965837690552500527637822603658699938581184513", - Bls12, - Fq2, "bls12_381" ); +bellman_extensions!(Bls12, Fq2); diff --git a/zokrates_field/src/bn128.rs b/zokrates_field/src/bn128.rs index 99396f7c6..4d1865620 100644 --- a/zokrates_field/src/bn128.rs +++ b/zokrates_field/src/bn128.rs @@ -1,12 +1,14 @@ +use algebra::bn254::{Bn254, Fq2 as Bn254_Fq2}; use bellman_ce::pairing::bn256::{Bn256, Fq2}; prime_field!( b"21888242871839275222246405745257275088548364400416034343698204186575808495617", - Bn256, - Fq2, "bn128" ); +bellman_extensions!(Bn256, Fq2); +zexe_extensions!(Bn254, Bn254_Fq2); + #[cfg(test)] mod tests { use super::*; @@ -384,7 +386,6 @@ mod tests { use bellman_ce::pairing::bn256::Fr; use rand::{thread_rng, Rng}; - use Field; #[test] fn fr_to_field_to_fr() { diff --git a/zokrates_field/src/bw6_761.rs b/zokrates_field/src/bw6_761.rs new file mode 100644 index 000000000..35c2b0f4a --- /dev/null +++ b/zokrates_field/src/bw6_761.rs @@ -0,0 +1,8 @@ +use algebra::bw6_761::BW6_761; + +prime_field!( + b"258664426012969094010652733694893533536393512754914660539884262666720468348340822774968888139573360124440321458177", + "bw6_761" +); + +zexe_extensions!(BW6_761); diff --git a/zokrates_field/src/lib.rs b/zokrates_field/src/lib.rs index ab5a2a7af..666e77c38 100644 --- a/zokrates_field/src/lib.rs +++ b/zokrates_field/src/lib.rs @@ -3,7 +3,9 @@ // @author Dennis Kuhnert // @author Jacob Eberhardt // @date 2017 +extern crate algebra_core; +use algebra_core::PairingEngine; use bellman_ce::pairing::ff::ScalarEngine; use bellman_ce::pairing::Engine; use num_bigint::BigUint; @@ -19,6 +21,24 @@ pub trait Pow { fn pow(self, _: RHS) -> Self::Output; } +pub trait BellmanFieldExtensions { + /// An associated type to be able to operate with Bellman ff traits + type BellmanEngine: Engine; + + fn from_bellman(e: ::Fr) -> Self; + fn into_bellman(self) -> ::Fr; + fn new_fq2(c0: &str, c1: &str) -> ::Fqe; +} + +pub trait ZexeFieldExtensions { + /// An associated type to be able to operate with zexe ff traits + type ZexeEngine: PairingEngine; + + fn from_zexe(e: ::Fr) -> Self; + fn into_zexe(self) -> ::Fr; + fn new_fqe(c: Vec<&str>) -> ::Fqe; +} + pub trait Field: From + From @@ -51,24 +71,6 @@ pub trait Field: + num_traits::CheckedAdd + num_traits::CheckedMul { - /// An associated type to be able to operate with Bellman ff traits - type BellmanEngine: Engine; - - fn from_bellman(e: ::Fr) -> Self { - use bellman_ce::pairing::ff::{PrimeField, PrimeFieldRepr}; - let mut res: Vec = vec![]; - e.into_repr().write_le(&mut res).unwrap(); - Self::from_byte_vector(res) - } - - fn into_bellman(self) -> ::Fr { - use bellman_ce::pairing::ff::PrimeField; - let s = self.to_dec_string(); - ::Fr::from_str(&s).unwrap() - } - - fn new_fq2(c0: &str, c1: &str) -> ::Fqe; - /// Returns this `Field`'s contents as little-endian byte vector fn into_byte_vector(&self) -> Vec; /// Returns an element of this `Field` from a little-endian byte vector @@ -122,7 +124,7 @@ pub trait Field: #[macro_use] mod prime_field { macro_rules! prime_field { - ($modulus:expr, $bellman_type:ty, $fq2_type: ident, $name:expr) => { + ($modulus:expr, $name:expr) => { use crate::{Field, Pow}; use lazy_static::lazy_static; use num_bigint::{BigInt, BigUint, Sign, ToBigInt}; @@ -144,19 +146,10 @@ mod prime_field { } impl Field for FieldPrime { - type BellmanEngine = $bellman_type; - fn bits(&self) -> u32 { self.value.bits() as u32 } - fn new_fq2(c0: &str, c1: &str) -> $fq2_type { - $fq2_type { - c0: bellman_ce::pairing::from_hex(c0).unwrap(), - c1: bellman_ce::pairing::from_hex(c1).unwrap(), - } - } - fn to_biguint(&self) -> BigUint { self.value.to_biguint().unwrap() } @@ -509,10 +502,107 @@ mod prime_field { } }; } + + macro_rules! bellman_extensions { + ($bellman_type:ty, $fq2_type:ident) => { + use crate::BellmanFieldExtensions; + use bellman_ce::pairing::ff::ScalarEngine; + + impl BellmanFieldExtensions for FieldPrime { + type BellmanEngine = $bellman_type; + + fn from_bellman(e: ::Fr) -> Self { + use bellman_ce::pairing::ff::{PrimeField, PrimeFieldRepr}; + let mut res: Vec = vec![]; + e.into_repr().write_le(&mut res).unwrap(); + Self::from_byte_vector(res) + } + + fn into_bellman(self) -> ::Fr { + use bellman_ce::pairing::ff::PrimeField; + let s = self.to_dec_string(); + ::Fr::from_str(&s).unwrap() + } + + fn new_fq2( + c0: &str, + c1: &str, + ) -> ::Fqe { + $fq2_type { + c0: bellman_ce::pairing::from_hex(c0).unwrap(), + c1: bellman_ce::pairing::from_hex(c1).unwrap(), + } + } + } + }; + } + + macro_rules! zexe_extensions { + ($zexe_type:ty) => { + use crate::ZexeFieldExtensions; + + impl ZexeFieldExtensions for FieldPrime { + type ZexeEngine = $zexe_type; + + fn from_zexe(e: ::Fr) -> Self { + use algebra_core::{BigInteger, PrimeField}; + let mut res: Vec = vec![]; + e.into_repr().write_le(&mut res).unwrap(); + Self::from_byte_vector(res) + } + + fn into_zexe(self) -> ::Fr { + use core::str::FromStr; + let s = self.to_dec_string(); + ::Fr::from_str(&s).unwrap() + } + + fn new_fqe(c: Vec<&str>) -> ::Fqe { + use core::str::FromStr; + ::Fqe::from_str(c[0]).unwrap() + } + } + }; + ($zexe_type:ty, $fqe_type:ident) => { + use crate::ZexeFieldExtensions; + + impl ZexeFieldExtensions for FieldPrime { + type ZexeEngine = $zexe_type; + + fn from_zexe(e: ::Fr) -> Self { + use algebra_core::{BigInteger, PrimeField}; + let mut res: Vec = vec![]; + e.into_repr().write_le(&mut res).unwrap(); + Self::from_byte_vector(res) + } + + fn into_zexe(self) -> ::Fr { + use core::str::FromStr; + let s = self.to_dec_string(); + ::Fr::from_str(&s).unwrap() + } + + fn new_fqe(c: Vec<&str>) -> ::Fqe { + use core::str::FromStr; + $fqe_type { + c0: ::Fq::from_str(c[0]) + .unwrap(), + c1: ::Fq::from_str(c[1]) + .unwrap(), + _parameters: core::marker::PhantomData, + } + } + } + }; + } } +pub mod bls12_377; pub mod bls12_381; pub mod bn128; +pub mod bw6_761; -pub use bls12_381::FieldPrime as Bls12Field; +pub use bls12_377::FieldPrime as Bls12_377Field; +pub use bls12_381::FieldPrime as Bls12_381Field; pub use bn128::FieldPrime as Bn128Field; +pub use bw6_761::FieldPrime as Bw6_761Field; diff --git a/zokrates_stdlib/stdlib/hashes/sha256/512bitPacked_bls12_377.zok b/zokrates_stdlib/stdlib/hashes/sha256/512bitPacked_bls12_377.zok new file mode 100644 index 000000000..9303f6af8 --- /dev/null +++ b/zokrates_stdlib/stdlib/hashes/sha256/512bitPacked_bls12_377.zok @@ -0,0 +1,19 @@ +import "../../utils/pack/u32/pack128" as pack128 +import "../../utils/pack_bls12_377/u32/unpack128" as unpack128 +import "./512bitPadded" as sha256 +// A function that takes an array of 4 field elements as inputs, unpacks each of them to 128 +// bits (big endian), concatenates them and applies sha256. +// It then returns an array of two field elements, each representing 128 bits of the result. +def main(field[4] preimage) -> (field[2]): + + u32[4] a_bits = unpack128(preimage[0]) + u32[4] b_bits = unpack128(preimage[1]) + u32[4] c_bits = unpack128(preimage[2]) + u32[4] d_bits = unpack128(preimage[3]) + + u32[8] lhs = [...a_bits, ...b_bits] + u32[8] rhs = [...c_bits, ...d_bits] + + u32[8] r = sha256(lhs, rhs) + + return [pack128(r[0..4]), pack128(r[4..8])] diff --git a/zokrates_stdlib/stdlib/hashes/sha256/512bitPacked_bw6_761.zok b/zokrates_stdlib/stdlib/hashes/sha256/512bitPacked_bw6_761.zok new file mode 100644 index 000000000..07737fba4 --- /dev/null +++ b/zokrates_stdlib/stdlib/hashes/sha256/512bitPacked_bw6_761.zok @@ -0,0 +1,19 @@ +import "../../utils/pack/u32/pack128" as pack128 +import "../../utils/pack_bw6_761/u32/unpack128" as unpack128 +import "./512bitPadded" as sha256 +// A function that takes an array of 4 field elements as inputs, unpacks each of them to 128 +// bits (big endian), concatenates them and applies sha256. +// It then returns an array of two field elements, each representing 128 bits of the result. +def main(field[4] preimage) -> (field[2]): + + u32[4] a_bits = unpack128(preimage[0]) + u32[4] b_bits = unpack128(preimage[1]) + u32[4] c_bits = unpack128(preimage[2]) + u32[4] d_bits = unpack128(preimage[3]) + + u32[8] lhs = [...a_bits, ...b_bits] + u32[8] rhs = [...c_bits, ...d_bits] + + u32[8] r = sha256(lhs, rhs) + + return [pack128(r[0..4]), pack128(r[4..8])] diff --git a/zokrates_stdlib/stdlib/utils/pack/bool/pack256.zok b/zokrates_stdlib/stdlib/utils/pack/bool/pack256.zok index 7c5ce3854..21350674c 100644 --- a/zokrates_stdlib/stdlib/utils/pack/bool/pack256.zok +++ b/zokrates_stdlib/stdlib/utils/pack/bool/pack256.zok @@ -3,7 +3,7 @@ // pack 256 big-endian bits into one field element // Note: This is not a injective operation as `p` is smaller than `2**256 - 1` for bn128 // For example, `[0, 0,..., 0]` and `bits(p)` both point to `0` -def main(bool[256] input) -> field: +def main(bool[256] bits) -> field: field out = 0 diff --git a/zokrates_stdlib/stdlib/utils/pack/u32/pack128.zok b/zokrates_stdlib/stdlib/utils/pack/u32/pack128.zok index 42ea81aa3..26e7c28e8 100644 --- a/zokrates_stdlib/stdlib/utils/pack/u32/pack128.zok +++ b/zokrates_stdlib/stdlib/utils/pack/u32/pack128.zok @@ -1,5 +1,3 @@ -#pragma curve bn128 - import "EMBED/u32_to_bits" as to_bits import "../bool/pack128" @@ -8,4 +6,4 @@ def main(u32[4] input) -> field: bool[128] bits = [...to_bits(input[0]), ...to_bits(input[1]), ...to_bits(input[2]), ...to_bits(input[3])] - return pack128(bits) \ No newline at end of file + return pack128(bits) diff --git a/zokrates_stdlib/stdlib/utils/pack/u32/pack256.zok b/zokrates_stdlib/stdlib/utils/pack/u32/pack256.zok index 5a89e6440..962e6825e 100644 --- a/zokrates_stdlib/stdlib/utils/pack/u32/pack256.zok +++ b/zokrates_stdlib/stdlib/utils/pack/u32/pack256.zok @@ -1,5 +1,3 @@ -#pragma curve bn128 - import "EMBED/u32_to_bits" as to_bits import "../bool/pack256" @@ -10,4 +8,4 @@ def main(u32[8] input) -> field: bool[256] bits = [...to_bits(input[0]), ...to_bits(input[1]), ...to_bits(input[2]), ...to_bits(input[3]), ...to_bits(input[4]), ...to_bits(input[5]), ...to_bits(input[6]), ...to_bits(input[7])] - return pack256(bits) \ No newline at end of file + return pack256(bits) diff --git a/zokrates_stdlib/stdlib/utils/pack_bls12_377/bool/nonStrictUnpack256.zok b/zokrates_stdlib/stdlib/utils/pack_bls12_377/bool/nonStrictUnpack256.zok new file mode 100644 index 000000000..2ca49e794 --- /dev/null +++ b/zokrates_stdlib/stdlib/utils/pack_bls12_377/bool/nonStrictUnpack256.zok @@ -0,0 +1,13 @@ +#pragma curve bls12_377 + +// Non-strict version: +// Note that this does not strongly enforce that the commitment is +// in the field. + +import "EMBED/unpack" as unpack + +def main(field i) -> (bool[256]): + + bool[253] b = unpack(i) + + return [false, false, false, ...b] diff --git a/zokrates_stdlib/stdlib/utils/pack_bls12_377/bool/unpack128.zok b/zokrates_stdlib/stdlib/utils/pack_bls12_377/bool/unpack128.zok new file mode 100644 index 000000000..a2a4f0669 --- /dev/null +++ b/zokrates_stdlib/stdlib/utils/pack_bls12_377/bool/unpack128.zok @@ -0,0 +1,11 @@ +#pragma curve bls12_377 + +import "EMBED/unpack" as unpack + +def main(field i) -> (bool[128]): + + bool[253] b = unpack(i) + + b[0..125] == [false; 125] + + return b[125..253] diff --git a/zokrates_stdlib/stdlib/utils/pack_bls12_377/u32/nonStrictUnpack256.zok b/zokrates_stdlib/stdlib/utils/pack_bls12_377/u32/nonStrictUnpack256.zok new file mode 100644 index 000000000..aa7938e90 --- /dev/null +++ b/zokrates_stdlib/stdlib/utils/pack_bls12_377/u32/nonStrictUnpack256.zok @@ -0,0 +1,12 @@ +#pragma curve bls12_377 + +// Non-strict version: +// Note that this does not strongly enforce that the commitment is +// in the field. + +import "../bool/nonStrictUnpack256" as unpack +import "../../casts/bool_256_to_u32_8" as from_bits + +def main(field i) -> (u32[8]): + + return from_bits(unpack(i)) diff --git a/zokrates_stdlib/stdlib/utils/pack_bls12_377/u32/unpack128.zok b/zokrates_stdlib/stdlib/utils/pack_bls12_377/u32/unpack128.zok new file mode 100644 index 000000000..e4a5c8a42 --- /dev/null +++ b/zokrates_stdlib/stdlib/utils/pack_bls12_377/u32/unpack128.zok @@ -0,0 +1,7 @@ +#pragma curve bls12_377 + +import "../bool/unpack128" as unpack +import "../../casts/bool_128_to_u32_4" as from_bits + +def main(field i) -> (u32[4]): + return from_bits(unpack(i)) diff --git a/zokrates_stdlib/stdlib/utils/pack_bw6_761/bool/unpack128.zok b/zokrates_stdlib/stdlib/utils/pack_bw6_761/bool/unpack128.zok new file mode 100644 index 000000000..9d409ca6a --- /dev/null +++ b/zokrates_stdlib/stdlib/utils/pack_bw6_761/bool/unpack128.zok @@ -0,0 +1,11 @@ +#pragma curve bw6_761 + +import "EMBED/unpack" as unpack + +def main(field i) -> (bool[128]): + + bool[377] b = unpack(i) + + b[0..249] == [false; 249] + + return b[249..377] diff --git a/zokrates_stdlib/stdlib/utils/pack_bw6_761/bool/unpack256.zok b/zokrates_stdlib/stdlib/utils/pack_bw6_761/bool/unpack256.zok new file mode 100644 index 000000000..528b82d24 --- /dev/null +++ b/zokrates_stdlib/stdlib/utils/pack_bw6_761/bool/unpack256.zok @@ -0,0 +1,9 @@ +#pragma curve bw6_761 + +import "EMBED/unpack" as unpack + +def main(field i) -> (bool[256]): + + bool[377] b = unpack(i) + + return b[121..377] diff --git a/zokrates_stdlib/stdlib/utils/pack_bw6_761/u32/unpack128.zok b/zokrates_stdlib/stdlib/utils/pack_bw6_761/u32/unpack128.zok new file mode 100644 index 000000000..60c4bfea4 --- /dev/null +++ b/zokrates_stdlib/stdlib/utils/pack_bw6_761/u32/unpack128.zok @@ -0,0 +1,7 @@ +#pragma curve bw6_761 + +import "../bool/unpack128" as unpack +import "../../casts/bool_128_to_u32_4" as from_bits + +def main(field i) -> (u32[4]): + return from_bits(unpack(i)) diff --git a/zokrates_stdlib/stdlib/utils/pack_bw6_761/u32/unpack256.zok b/zokrates_stdlib/stdlib/utils/pack_bw6_761/u32/unpack256.zok new file mode 100644 index 000000000..2df1a5a15 --- /dev/null +++ b/zokrates_stdlib/stdlib/utils/pack_bw6_761/u32/unpack256.zok @@ -0,0 +1,8 @@ +#pragma curve bw6_761 + +import "../bool/unpack256" as unpack +import "../../casts/bool_256_to_u32_8" as from_bits + +def main(field i) -> (u32[8]): + + return from_bits(unpack(i)) diff --git a/zokrates_stdlib/stdlib/verifier/verifier.zok b/zokrates_stdlib/stdlib/verifier/verifier.zok new file mode 100644 index 000000000..73eba84c3 --- /dev/null +++ b/zokrates_stdlib/stdlib/verifier/verifier.zok @@ -0,0 +1,6 @@ +import "EMBED/verify" as verify +// example 1: 137565092005752483748493407438327763169139684140423891873536662628835348517869074662555749289290034670067693169037 72139571997667283518811514205532104215070171737960966802266046947665847059478158336650654132833435721090714539943 86725433690642560275465877140013172902963956098212864793300066153420847889078693035332011673719502025725294990585 5146800790688495090295297863320679569880979262097341538384555974060527428246367729743910738374589247289694509183 157199182011055697109275070122107747397158636176744687490271844487778522970938361603946017952017323222854186826642 128090586433977047290346447727325500999106522203224969725245017120435221824003482965410390284669817584625949158873 242846623199219102294519092470464099825623835022514942761935861255734088072105280496775650976049574668812729130662 199921505013060736410377710379705670795076292689440680632141602368931503404334746204056411491487357103823503332942 1 51618593415644909171351110450182760129199316654826963313869818832752929804897864321134536534430976728900615574493 129682384015693681606749627075354770485732278447522042797230918116715222994717480287967421380069260326111848891300 107857260380611661817545871785573241453173005559353466744943663759160894873700339815411460161917475971920064634595 198808239332695609906436230326243511374923871415614564458695835008682643835220809594443748665087240319790636388914 139663165395409818512381293320009747384362319111063669584453545516359525050890910749415470506136892720148317704511 180466491348666697356845067337590354420817076670243268334418795137053732632868216373776444192344006242202729721425 199405876263141075669345345472147439761990370616069254341388185493501477564711863037613681367498080357858999679916 82183765193095559943855738550510401967141939864770641483020850096933741675629006592709947740972750263743759909116 235667818304241949879589814884998117773684690279805455790276812676255025603328770918165588989570429573000549876824 53093253378089142458938879297218091522595066859906784980660810891645284753970414026364610942918212374501042584933 179969579722769515604672675224061438662996395894430225591003910715298216804709963923217915070721924455120579075568 147441174419609628990639483938877108868825317673431519438840787340833142778801384629100279050711573860909344631695 51618593415644909171351110450182760129199316654826963313869818832752929804897864321134536534430976728900615574493 129682384015693681606749627075354770485732278447522042797230918116715222994717480287967421380069260326111848891300 107857260380611661817545871785573241453173005559353466744943663759160894873700339815411460161917475971920064634595 198808239332695609906436230326243511374923871415614564458695835008682643835220809594443748665087240319790636388914 167890330208433086376513978751711327580456562618444373895888579048783860907864303028081226255132693676348870774490 111470581238289600115537636964914822180221937524137085589416200459498429869257546865551678456382952847650208378004 23647036858389957111023283818345900025536766542464580440401268408908911718370015825168423272490268653569481837709 139814123882173489424127695867288972436731433127284838974098231559275365090908492483258528656413170189902424410309 + +def main(private field[8] proof, private field[1] inputs, private field[20] vk) -> (bool): + bool r = verify(proof, inputs, vk) + return r diff --git a/zokrates_stdlib/stdlib/verifier/verifier11.zok b/zokrates_stdlib/stdlib/verifier/verifier11.zok new file mode 100644 index 000000000..f4b7d8b49 --- /dev/null +++ b/zokrates_stdlib/stdlib/verifier/verifier11.zok @@ -0,0 +1,7 @@ +import "EMBED/verify11" as verify +//example 11: +//180576598777597956957756674411932471179626448439455106956582253365876871683249139593000374395952678482586431471996 129896682429414509120415367653407067702977346485504662987110866696379336547035841003101601020777771480604662235531 140618491025274418301109981164048373443821571938856666201032232225404071122079600420102424167361052643333311505814 35511319933687798911182535185956618523883335245343396189637617751888154126403169573031872453167238868505634962630 92076313419063088301006996221947233437270049364160087713834777394922435937171052389744551892478790599158306729065 58641777955822281595677463401471119027871648279322151544894017935529470599743720850552565239388241009069677600586 240585579936300350369880807496332054834947661306083539553947307350523284245226471685370234370967395878240441381489 175437090400850066443607126309485237484234755382787510717820555198158230973404977075808086810062305892562539939751 1 1 1 1 1 1 1 1 1 1 1 51618593415644909171351110450182760129199316654826963313869818832752929804897864321134536534430976728900615574493 129682384015693681606749627075354770485732278447522042797230918116715222994717480287967421380069260326111848891300 107857260380611661817545871785573241453173005559353466744943663759160894873700339815411460161917475971920064634595 198808239332695609906436230326243511374923871415614564458695835008682643835220809594443748665087240319790636388914 139663165395409818512381293320009747384362319111063669584453545516359525050890910749415470506136892720148317704511 180466491348666697356845067337590354420817076670243268334418795137053732632868216373776444192344006242202729721425 199405876263141075669345345472147439761990370616069254341388185493501477564711863037613681367498080357858999679916 82183765193095559943855738550510401967141939864770641483020850096933741675629006592709947740972750263743759909116 235667818304241949879589814884998117773684690279805455790276812676255025603328770918165588989570429573000549876824 53093253378089142458938879297218091522595066859906784980660810891645284753970414026364610942918212374501042584933 179969579722769515604672675224061438662996395894430225591003910715298216804709963923217915070721924455120579075568 147441174419609628990639483938877108868825317673431519438840787340833142778801384629100279050711573860909344631695 51618593415644909171351110450182760129199316654826963313869818832752929804897864321134536534430976728900615574493 129682384015693681606749627075354770485732278447522042797230918116715222994717480287967421380069260326111848891300 107857260380611661817545871785573241453173005559353466744943663759160894873700339815411460161917475971920064634595 198808239332695609906436230326243511374923871415614564458695835008682643835220809594443748665087240319790636388914 74473370268583513226742071824183380959343491709864497000069583251051491218378271128058280505762658701649336700610 8042120839904039859427126135683532302853384318330655732497454596370172606609424165946699012698522855183164615742 48113552820580812615299530751965809113824351315507267985259211734545009625156590364969208630831872009971019881095 184286009694266500294241220994396355768771687925244871057992199400679141682673068357985960870480562786827785514647 258010892514565820771340046208430728985689918257553826667699138618276913747497993147224445542041747518926076657444 156224845357165318366127253343134132579198020111918390673381505917386051635073774414133110832019181592877711592147 34250874412427177101956825570689301734486366411422669130606100650631724850120786376783453950959454211404519396138 15232115502723101185022390200571788304264525913758172782681121820750618999953227441949204761797443778999514257959 180682466264291366123957019062858099622796267859775231182052327492964034121628958390811801658684995117759344292523 140977727103342853793125612611276737293973539553648054349362012327618491492141055105888883032009189910294082130884 222863322180656999657454679968842236454663240101722811602470906614063901804583731655580281410698252163427126673574 127948824128358819520739025701724303303499418397290798461189656453468101084083218846665849459483446809989414129043 98443110527106282678378056651586701507595957714632256454949014755154639558360335768640841917309024595540917418141 205898070965276093282811755696939051185893888113975154504381356320346053166756710926753384795442629528557413569633 246298678035372203903360461623657954034069993484940506276427001628835540508223269426571254977496748180554098061785 74710034508255692511147359056375315491900345465811843921390300276905416635910535330513770119220452718014940337252 87113734686857095508604356781359806430800803574520356431266883121340618434610002454654068776436483281963151930505 234215752331533285884132834908368198523408848395357436271801340008023952486347060885839222547112494277799085477989 174889204633134780239317685615800823899941230507322743332979881203106684840851704105215381694970326866402912505239 45037391177918313033324179193994049993825087354994487314974080330865879521518995190184996756163692444765649509518 10906324289738064648116695815493324679277753259311712249691249247721519543366558045781181738566358339162486035939 233077352232378063545260318732352861746177119368620023637949664743013570908993097684576412574468971257652225091900 99592389454713431373030999949865800058002638104396269776505697854265092845174600515742749508449978101189458843975 16608323192067079375216954181948784567580341488758491110819502323572714666114916156949780439840289431905615009653 + +def main(private field[8] proof, private field[11] inputs, private field[40] vk) -> (bool): + bool r = verify(proof, inputs, vk) + return r diff --git a/zokrates_stdlib/stdlib/verifier/verifier2.zok b/zokrates_stdlib/stdlib/verifier/verifier2.zok new file mode 100644 index 000000000..e8b7bfec0 --- /dev/null +++ b/zokrates_stdlib/stdlib/verifier/verifier2.zok @@ -0,0 +1,5 @@ +import "EMBED/verify2" as verify +// example 2: 164298555920240567171627298841626553164387307801100206932765621770301745671127480295934416060193264163152298121842 87042439455682058715262775038415289233545142063964550163506969881877341479797681897553780336380107120716704452229 117091840725889231147418174639145513093696099016314204836454849021698720565281444634114282810250657616997403655551 151681850303907264044758829383549686214133948974764973910730833706662633290359870201865990950643165651562697226068 157173903756713063884406067857852985683836049595631244690679979236774695172095319963573144402094051720587909899511 224360929797754853449863520411222621945959181694180226273708042652077731101222105820273077282670369448262972664642 75930422051669910699719424339635257245829815388289458109152091598100563693265103871182868064183718952836702254749 52826734050451182118105919237239916350661359922129391517084871111552953163773715259396705887899427058578938397282 8146837541998854005210856160410543445136568755949189115586542258223627068570 1668167439870663604090590886367632908182802419513806606723693962684805704536 183756877468541630753146585558239220257733956043988301662130604090419880695931822363534849028114306663142781620978 124948497768969458321349233842600165934612985979136363333722058335618824769251038305467931750838114178657585227244 168665037344736886407419786364592474058046027005907144357207106724493462070604835406273235545111193408960307350688 143483302563261025873757274638742867381396658643934382355951553214146831337538779236117137288979693104622236937644 142234866212709361921964611956828211569064504089991720022626037670818089413914553983723519846154644483203701383927 83030278041453992599795341983122880951698754212783394772977893766630277061009300824458616332962111211337326815959 111388994941644087254670333917228679818265953207162157950861239649891343244035800755135003681348391177966779112639 17606113021281609292792936632855540789927216595917739780556312211291788131389684876014072485156264649775107443707 203775396060966035998653026240663707485672240454103403599120208635494150347654974871571140904619072222772968210238 175964161380710869785983079764799620932050509423609475930877656184191231779443866541995174739633737324526011302266 117822361184136773117138077518163207771973327287074140927312877196991173499427000814225474124015943711111993084971 48432799730390283060212971639737929381144412915912076067487930367373379225976418473542520288334436585964057159568 183756877468541630753146585558239220257733956043988301662130604090419880695931822363534849028114306663142781620978 124948497768969458321349233842600165934612985979136363333722058335618824769251038305467931750838114178657585227244 168665037344736886407419786364592474058046027005907144357207106724493462070604835406273235545111193408960307350688 143483302563261025873757274638742867381396658643934382355951553214146831337538779236117137288979693104622236937644 98575377817976877984505376915362689952299726995190465856304453136821602809503400814017285791936778917042311601923 29049914920122439269216362596690254978786929008065526828648806210182052820447137303700164953534251744567848210315 247421540801753608836388781765319482563465239279793914016794097164591193709900687660795593959567835948703004441112 171576131688175722033973226012975986646974209098474719354124277017895963944629843554905505415082792527102524842187 36452945603742174480809846596173046330626415529425427418990191505206643408029586685753686687186307268787553298917 16478751173230720924455000177111658936211240758820525716154084880588097364298192397724194448132614978776786626810 +def main(private field[8] proof, private field[2] inputs, private field[22] vk) -> (bool): + bool r = verify(proof, inputs, vk) + return r diff --git a/zokrates_stdlib/stdlib/verifier/verifier5.zok b/zokrates_stdlib/stdlib/verifier/verifier5.zok new file mode 100644 index 000000000..d8ed7dbb1 --- /dev/null +++ b/zokrates_stdlib/stdlib/verifier/verifier5.zok @@ -0,0 +1,6 @@ +import "EMBED/verify5" as verify +// example 5: 93919249336145447019101190152747452017826655307318317336134204645089529294938687249349675012896492178179698056462 119479952869529695222449869042273592421082263133756665572756419827141653155349179162746946694464314138790060788395 187012311448238853329150903190626923892010001373021191392806609423170810095710131005171033885643902959539089683603 230632685518829110004032357128906884091930790776972192963197371461915285033679623246383782944040189845674474628527 222810708740359390955786116891658621075072058331828437357704819349257497072768210213447094562617057842513839045415 155670558596959485209689045544076213431355729043379491614908539870538354151171287053697534043795807269228220521147 118577412837689190926801237606303522128405770441812140046787693905660307771907171024272098406431452499717216388524 73570507725286622376017498186168530123004210096690494411449625395955945308178654274143435606120217496087112872722 1 1 1 1 1 51618593415644909171351110450182760129199316654826963313869818832752929804897864321134536534430976728900615574493 129682384015693681606749627075354770485732278447522042797230918116715222994717480287967421380069260326111848891300 107857260380611661817545871785573241453173005559353466744943663759160894873700339815411460161917475971920064634595 198808239332695609906436230326243511374923871415614564458695835008682643835220809594443748665087240319790636388914 139663165395409818512381293320009747384362319111063669584453545516359525050890910749415470506136892720148317704511 180466491348666697356845067337590354420817076670243268334418795137053732632868216373776444192344006242202729721425 199405876263141075669345345472147439761990370616069254341388185493501477564711863037613681367498080357858999679916 82183765193095559943855738550510401967141939864770641483020850096933741675629006592709947740972750263743759909116 235667818304241949879589814884998117773684690279805455790276812676255025603328770918165588989570429573000549876824 53093253378089142458938879297218091522595066859906784980660810891645284753970414026364610942918212374501042584933 179969579722769515604672675224061438662996395894430225591003910715298216804709963923217915070721924455120579075568 147441174419609628990639483938877108868825317673431519438840787340833142778801384629100279050711573860909344631695 51618593415644909171351110450182760129199316654826963313869818832752929804897864321134536534430976728900615574493 129682384015693681606749627075354770485732278447522042797230918116715222994717480287967421380069260326111848891300 107857260380611661817545871785573241453173005559353466744943663759160894873700339815411460161917475971920064634595 198808239332695609906436230326243511374923871415614564458695835008682643835220809594443748665087240319790636388914 120076180084881209888531776114516075870161610839218034649724489661582902994403939983384036202784199733754781809514 108247323514425357573116551602974749763748101138301248411725436628201306069372944288777336898282658880098836358205 191072882877685407863403051159805644453754642285350957598730659763912967522679197903762366275892752444032800376100 190308792587728064144634726932531336080818288705715281929284641270366737475459206589415281729930233513047751100660 176193892714694333432358027900572931298063110592192983736528658934647289078393803858591148623369841761720499723239 175492243600667145431965489414273208327390295701896119279372088851666270878626675822210191447285496209864196910000 131715089064560384857328709360130651614977927828805021539779329659078232797907167078669591158245052986186857710968 167387449188068280354762270007395301225835549789620606473695118528353750245815904097740789370385099166663069453835 216261737758274283670300649325473049279771553925087455704802154736789176952469730358764180200660820780933492532276 114850853973568449686480263957612650915252720326613370281382073655758711209867531143930686100626181477663370486040 204576089289721808336201218321080703123109733299162919594093436862578194664495302146644056590192897808154944340252 20188174310383303554697528706169585520532743043352500241293903902233951521133833350606257922541369887404532716106 + +def main(private field[8] proof, private field[5] inputs, private field[28] vk) -> (bool): + bool r = verify(proof, inputs, vk) + return r diff --git a/zokrates_stdlib/stdlib/verifier/verifier7.zok b/zokrates_stdlib/stdlib/verifier/verifier7.zok new file mode 100644 index 000000000..322d8f23c --- /dev/null +++ b/zokrates_stdlib/stdlib/verifier/verifier7.zok @@ -0,0 +1,5 @@ +import "EMBED/verify7" as verify +// example 7: 46972797782523351218186489614847198664374643658260597400327879985608892118426663994615575137380606947996090255350 97327037761454721772628987557641667173982803815226074939030388313256847750679453662030014340564552288112090169529 71822737467433388849374158628670108030211399471356822465985883916021837689439757359036777993110548291752505062691 191270868708412251094772061837074611736561690177101014418543598378666562439632190898380559469845798775111925411790 54351367834716061611644221004362169239165291477806192962291463515281226570976184680139732399461733657239283441914 137005744531125000546690732669313281410842064835892281413530555983272434847876599080915960972304230621250761084860 173990490276586084389831216871032217817142548704567307077189444470989979136617559944056415876431889559306913637447 251601957761887841510604241303790077852036951914075649192617266842791920223989066838364087519035856691099866624579 1 1 1 1 1 1 1 51618593415644909171351110450182760129199316654826963313869818832752929804897864321134536534430976728900615574493 129682384015693681606749627075354770485732278447522042797230918116715222994717480287967421380069260326111848891300 107857260380611661817545871785573241453173005559353466744943663759160894873700339815411460161917475971920064634595 198808239332695609906436230326243511374923871415614564458695835008682643835220809594443748665087240319790636388914 139663165395409818512381293320009747384362319111063669584453545516359525050890910749415470506136892720148317704511 180466491348666697356845067337590354420817076670243268334418795137053732632868216373776444192344006242202729721425 199405876263141075669345345472147439761990370616069254341388185493501477564711863037613681367498080357858999679916 82183765193095559943855738550510401967141939864770641483020850096933741675629006592709947740972750263743759909116 235667818304241949879589814884998117773684690279805455790276812676255025603328770918165588989570429573000549876824 53093253378089142458938879297218091522595066859906784980660810891645284753970414026364610942918212374501042584933 179969579722769515604672675224061438662996395894430225591003910715298216804709963923217915070721924455120579075568 147441174419609628990639483938877108868825317673431519438840787340833142778801384629100279050711573860909344631695 51618593415644909171351110450182760129199316654826963313869818832752929804897864321134536534430976728900615574493 129682384015693681606749627075354770485732278447522042797230918116715222994717480287967421380069260326111848891300 107857260380611661817545871785573241453173005559353466744943663759160894873700339815411460161917475971920064634595 198808239332695609906436230326243511374923871415614564458695835008682643835220809594443748665087240319790636388914 128024038099966279712532974954626721226639442034536191955902283984624525643942494844141887189821650651299232049688 40470997851282200236266813568261134451531393381504151434057591199991495323243987248564615304641816355488014359082 108288075166525596098694289344516409529682857520864518292098201282870120911220482299172075573869327301383965166669 247662936938608007250903891967232825634209088331118930283814824807915751653426295318174176803090544586682099876679 123691913850893714657057958012510424780731232472489772757612700020409662702512807765513483468151386514556121114805 203626573280748469748292241276108814663387363672513944175062683659985523622899981218633473352045941058979323463007 180580682252327234761316195833771296215305351210614833403467305360311509075645261576291605706376579788974038151040 179254608507693030653305364386473270688611526108940446707328223772290792954553582796666834833492032905101796097377 139266909801485192197942561962746059603880134333715004586240832379216829479303052757458379479511497696222050650775 69314059888472889451168249892343638683500173731319144195764735525657758401544520396446885348961362667134552703375 134040696217540605957498067263237289722598870831642128192717367514648871374523331482853870460624398571080900924883 216453389860703781077149475255664923051107994081955178048776121283957786687835392603148292440674127177703538606195 27546062382896811593223904741344318148851578312205836582315714787716401492996749294167112422939029948209697721523 123289013959501133646735421839740917029121937658793105497482631238875151683421007672827445509499133882991659532687 122788408896515135389349214053396001909115973919305910336099521004470519848373725939176616720743513461133945634056 127960792463135144610279182271176527945265362362874875853793254337244967558867486101588611091004656274402156620606 +def main(private field[8] proof, private field[7] inputs, private field[32] vk) -> (bool): + bool r = verify(proof, inputs, vk) + return r diff --git a/zokrates_test/src/lib.rs b/zokrates_test/src/lib.rs index 63fb8f087..64b6d7f57 100644 --- a/zokrates_test/src/lib.rs +++ b/zokrates_test/src/lib.rs @@ -3,12 +3,14 @@ extern crate serde_derive; use std::path::PathBuf; use zokrates_core::ir; -use zokrates_field::{Bls12Field, Bn128Field, Field}; +use zokrates_field::{Bls12_377Field, Bls12_381Field, Bn128Field, Bw6_761Field, Field}; #[derive(Serialize, Deserialize, Clone)] enum Curve { Bn128, - Bls12, + Bls12_381, + Bls12_377, + Bw6_761, } #[derive(Serialize, Deserialize, Clone)] @@ -95,7 +97,9 @@ pub fn test_inner(test_path: &str) { for c in &curves { match c { Curve::Bn128 => compile_and_run::(t.clone()), - Curve::Bls12 => compile_and_run::(t.clone()), + Curve::Bls12_381 => compile_and_run::(t.clone()), + Curve::Bls12_377 => compile_and_run::(t.clone()), + Curve::Bw6_761 => compile_and_run::(t.clone()), } } } From 6e5b097045f7f2d93501069ce332e36b9e094c17 Mon Sep 17 00:00:00 2001 From: dark64 Date: Thu, 24 Sep 2020 13:33:36 +0200 Subject: [PATCH 22/54] add FqeRepr associative type to zexe field extensions --- zokrates_core/src/proof_system/zexe/gm17.rs | 25 ++++++++---------- zokrates_field/src/lib.rs | 28 +++++++++++++++------ 2 files changed, 31 insertions(+), 22 deletions(-) diff --git a/zokrates_core/src/proof_system/zexe/gm17.rs b/zokrates_core/src/proof_system/zexe/gm17.rs index 6811099b7..4d6e85d2d 100644 --- a/zokrates_core/src/proof_system/zexe/gm17.rs +++ b/zokrates_core/src/proof_system/zexe/gm17.rs @@ -38,7 +38,10 @@ pub struct VerificationKey { query: Vec, } -impl ProofSystem for GM17 { +impl ProofSystem for GM17 +where + T: NotBw6_761Field + Field + ZexeFieldExtensions, +{ type VerificationKey = VerificationKey; type ProofPoints = ProofPoints; @@ -276,25 +279,19 @@ pub mod serialization { ::G1Affine::from_xy_checked(x, y).unwrap() } - pub fn to_g2( + pub fn to_g2>( g2: G2Affine, ) -> ::G2Affine { - let x = T::new_fqe(vec![ - to_dec_string((g2.0).0).as_str(), - to_dec_string((g2.0).1).as_str(), - ]); - let y = T::new_fqe(vec![ - to_dec_string((g2.1).0).as_str(), - to_dec_string((g2.1).1).as_str(), - ]); + let x = T::new_fqe([to_dec_string((g2.0).0), to_dec_string((g2.0).1)]); + let y = T::new_fqe([to_dec_string((g2.1).0), to_dec_string((g2.1).1)]); ::G2Affine::from_xy_checked(x, y).unwrap() } - pub fn to_g2_fq( + pub fn to_g2_fq>( g2: G2AffineFq, ) -> ::G2Affine { - let x = T::new_fqe(vec![to_dec_string(g2.0).as_str()]); - let y = T::new_fqe(vec![to_dec_string(g2.1).as_str()]); + let x = T::new_fqe(to_dec_string(g2.0)); + let y = T::new_fqe(to_dec_string(g2.1)); ::G2Affine::from_xy_checked(x, y).unwrap() } } @@ -362,4 +359,4 @@ mod tests { assert!(ans); } -} \ No newline at end of file +} diff --git a/zokrates_field/src/lib.rs b/zokrates_field/src/lib.rs index 666e77c38..007f45c1a 100644 --- a/zokrates_field/src/lib.rs +++ b/zokrates_field/src/lib.rs @@ -33,10 +33,11 @@ pub trait BellmanFieldExtensions { pub trait ZexeFieldExtensions { /// An associated type to be able to operate with zexe ff traits type ZexeEngine: PairingEngine; + type FqeRepr; fn from_zexe(e: ::Fr) -> Self; fn into_zexe(self) -> ::Fr; - fn new_fqe(c: Vec<&str>) -> ::Fqe; + fn new_fqe(value: Self::FqeRepr) -> ::Fqe; } pub trait Field: @@ -543,6 +544,7 @@ mod prime_field { impl ZexeFieldExtensions for FieldPrime { type ZexeEngine = $zexe_type; + type FqeRepr = String; fn from_zexe(e: ::Fr) -> Self { use algebra_core::{BigInteger, PrimeField}; @@ -557,9 +559,12 @@ mod prime_field { ::Fr::from_str(&s).unwrap() } - fn new_fqe(c: Vec<&str>) -> ::Fqe { + fn new_fqe( + value: Self::FqeRepr, + ) -> ::Fqe { use core::str::FromStr; - ::Fqe::from_str(c[0]).unwrap() + ::Fqe::from_str(value.as_str()) + .unwrap() } } }; @@ -568,6 +573,7 @@ mod prime_field { impl ZexeFieldExtensions for FieldPrime { type ZexeEngine = $zexe_type; + type FqeRepr = [String; 2]; fn from_zexe(e: ::Fr) -> Self { use algebra_core::{BigInteger, PrimeField}; @@ -582,13 +588,19 @@ mod prime_field { ::Fr::from_str(&s).unwrap() } - fn new_fqe(c: Vec<&str>) -> ::Fqe { + fn new_fqe( + value: Self::FqeRepr, + ) -> ::Fqe { use core::str::FromStr; $fqe_type { - c0: ::Fq::from_str(c[0]) - .unwrap(), - c1: ::Fq::from_str(c[1]) - .unwrap(), + c0: ::Fq::from_str( + value[0].as_str(), + ) + .unwrap(), + c1: ::Fq::from_str( + value[1].as_str(), + ) + .unwrap(), _parameters: core::marker::PhantomData, } } From 8ff2b57bb25ff15fb6d63a940ea7d686189bac4f Mon Sep 17 00:00:00 2001 From: dark64 Date: Mon, 28 Sep 2020 11:24:20 +0200 Subject: [PATCH 23/54] minor changes --- zokrates_core/src/proof_system/zexe/gm17.rs | 14 +++++++------- zokrates_field/src/lib.rs | 10 +++++----- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/zokrates_core/src/proof_system/zexe/gm17.rs b/zokrates_core/src/proof_system/zexe/gm17.rs index 4d6e85d2d..3271e4217 100644 --- a/zokrates_core/src/proof_system/zexe/gm17.rs +++ b/zokrates_core/src/proof_system/zexe/gm17.rs @@ -12,7 +12,7 @@ use crate::ir; use crate::proof_system::zexe::Computation; use crate::proof_system::zexe::{parse_fr, parse_g1, parse_g2, parse_g2_fq}; use proof_system::solidity::SolidityAbi; -use proof_system::{G1Affine, G2Affine, G2AffineFq, Proof, ProofSystem, SetupKeypair}; +use proof_system::{G1Affine, G2Affine, G2AffineFq, Proof, ProofSystem, SetupKeypair, Fq2}; pub struct GM17 {} @@ -40,7 +40,7 @@ pub struct VerificationKey { impl ProofSystem for GM17 where - T: NotBw6_761Field + Field + ZexeFieldExtensions, + T: NotBw6_761Field + Field + ZexeFieldExtensions, { type VerificationKey = VerificationKey; type ProofPoints = ProofPoints; @@ -252,7 +252,7 @@ impl ProofSystem for GM17 { pub mod serialization { use algebra_core::{AffineCurve, PairingEngine}; use num_bigint::BigUint; - use proof_system::{G1Affine, G2Affine, G2AffineFq}; + use proof_system::{G1Affine, G2Affine, G2AffineFq, Fq2, Fq}; use std::str::FromStr; use zokrates_field::ZexeFieldExtensions; @@ -279,15 +279,15 @@ pub mod serialization { ::G1Affine::from_xy_checked(x, y).unwrap() } - pub fn to_g2>( + pub fn to_g2>( g2: G2Affine, ) -> ::G2Affine { - let x = T::new_fqe([to_dec_string((g2.0).0), to_dec_string((g2.0).1)]); - let y = T::new_fqe([to_dec_string((g2.1).0), to_dec_string((g2.1).1)]); + let x = T::new_fqe((to_dec_string((g2.0).0), to_dec_string((g2.0).1))); + let y = T::new_fqe((to_dec_string((g2.1).0), to_dec_string((g2.1).1))); ::G2Affine::from_xy_checked(x, y).unwrap() } - pub fn to_g2_fq>( + pub fn to_g2_fq>( g2: G2AffineFq, ) -> ::G2Affine { let x = T::new_fqe(to_dec_string(g2.0)); diff --git a/zokrates_field/src/lib.rs b/zokrates_field/src/lib.rs index 007f45c1a..6cbec55dd 100644 --- a/zokrates_field/src/lib.rs +++ b/zokrates_field/src/lib.rs @@ -568,12 +568,12 @@ mod prime_field { } } }; - ($zexe_type:ty, $fqe_type:ident) => { + ($zexe_type:ty, $fq2_type:ident) => { use crate::ZexeFieldExtensions; impl ZexeFieldExtensions for FieldPrime { type ZexeEngine = $zexe_type; - type FqeRepr = [String; 2]; + type FqeRepr = (String, String); fn from_zexe(e: ::Fr) -> Self { use algebra_core::{BigInteger, PrimeField}; @@ -592,13 +592,13 @@ mod prime_field { value: Self::FqeRepr, ) -> ::Fqe { use core::str::FromStr; - $fqe_type { + $fq2_type { c0: ::Fq::from_str( - value[0].as_str(), + value.0.as_str(), ) .unwrap(), c1: ::Fq::from_str( - value[1].as_str(), + value.1.as_str(), ) .unwrap(), _parameters: core::marker::PhantomData, From 3e12130c3087ace9edb79374c089445c838ae721 Mon Sep 17 00:00:00 2001 From: dark64 Date: Mon, 28 Sep 2020 11:38:37 +0200 Subject: [PATCH 24/54] generic vk and proof points in zexe gm17 --- zokrates_core/src/proof_system/zexe/gm17.rs | 69 ++++++++------------- 1 file changed, 26 insertions(+), 43 deletions(-) diff --git a/zokrates_core/src/proof_system/zexe/gm17.rs b/zokrates_core/src/proof_system/zexe/gm17.rs index 3271e4217..f06ab9937 100644 --- a/zokrates_core/src/proof_system/zexe/gm17.rs +++ b/zokrates_core/src/proof_system/zexe/gm17.rs @@ -22,28 +22,28 @@ impl NotBw6_761Field for Bls12_381Field {} impl NotBw6_761Field for Bn128Field {} #[derive(Serialize, Deserialize)] -pub struct ProofPoints { - a: G1Affine, - b: G2Affine, - c: G1Affine, +pub struct ProofPoints { + a: G1, + b: G2, + c: G1, } #[derive(Serialize, Deserialize)] -pub struct VerificationKey { - h: G2Affine, - g_alpha: G1Affine, - h_beta: G2Affine, - g_gamma: G1Affine, - h_gamma: G2Affine, - query: Vec, +pub struct VerificationKey { + h: G2, + g_alpha: G1, + h_beta: G2, + g_gamma: G1, + h_gamma: G2, + query: Vec, } impl ProofSystem for GM17 where T: NotBw6_761Field + Field + ZexeFieldExtensions, { - type VerificationKey = VerificationKey; - type ProofPoints = ProofPoints; + type VerificationKey = VerificationKey; + type ProofPoints = ProofPoints; fn setup(program: ir::Prog) -> SetupKeypair { let parameters = Computation::without_witness(program).setup(); @@ -72,7 +72,7 @@ where program: ir::Prog, witness: ir::Witness, proving_key: Vec, - ) -> Proof { + ) -> Proof { let computation = Computation::with_witness(program, witness); let params = Parameters::<::ZexeEngine>::deserialize_uncompressed( @@ -93,14 +93,14 @@ where .map(parse_fr::) .collect::>(); - Proof::::new(proof_points, inputs, None) + Proof::::new(proof_points, inputs, None) } - fn export_solidity_verifier(_vk: VerificationKey, _abi: SolidityAbi) -> String { + fn export_solidity_verifier(_vk: Self::VerificationKey, _abi: SolidityAbi) -> String { unimplemented!() } - fn verify(vk: VerificationKey, proof: Proof) -> bool { + fn verify(vk: Self::VerificationKey, proof: Proof) -> bool { let vk = VerifyingKey { h_g2: serialization::to_g2::(vk.h), g_alpha_g1: serialization::to_g1::(vk.g_alpha), @@ -137,34 +137,17 @@ where } } -#[derive(Serialize, Deserialize)] -pub struct ProofPointsG2Fq { - a: G1Affine, - b: G2AffineFq, - c: G1Affine, -} - -#[derive(Serialize, Deserialize)] -pub struct VerificationKeyG2Fq { - h: G2AffineFq, - g_alpha: G1Affine, - h_beta: G2AffineFq, - g_gamma: G1Affine, - h_gamma: G2AffineFq, - query: Vec, -} - impl ProofSystem for GM17 { - type VerificationKey = VerificationKeyG2Fq; - type ProofPoints = ProofPointsG2Fq; + type VerificationKey = VerificationKey; + type ProofPoints = ProofPoints; - fn setup(program: ir::Prog) -> SetupKeypair { + fn setup(program: ir::Prog) -> SetupKeypair { let parameters = Computation::without_witness(program).setup(); let mut pk: Vec = Vec::new(); parameters.serialize_uncompressed(&mut pk).unwrap(); - let vk = VerificationKeyG2Fq { + let vk = Self::VerificationKey { h: parse_g2_fq::(¶meters.vk.h_g2), g_alpha: parse_g1::(¶meters.vk.g_alpha_g1), h_beta: parse_g2_fq::(¶meters.vk.h_beta_g2), @@ -185,7 +168,7 @@ impl ProofSystem for GM17 { program: ir::Prog, witness: ir::Witness, proving_key: Vec, - ) -> Proof { + ) -> Proof { let computation = Computation::with_witness(program, witness); let params = Parameters::<::ZexeEngine>::deserialize_uncompressed( &mut proving_key.as_slice(), @@ -193,7 +176,7 @@ impl ProofSystem for GM17 { .unwrap(); let proof = computation.clone().prove(¶ms); - let proof_points = ProofPointsG2Fq { + let proof_points = Self::ProofPoints { a: parse_g1::(&proof.a), b: parse_g2_fq::(&proof.b), c: parse_g1::(&proof.c), @@ -205,14 +188,14 @@ impl ProofSystem for GM17 { .map(parse_fr::) .collect::>(); - Proof::::new(proof_points, inputs, None) + Proof::::new(proof_points, inputs, None) } - fn export_solidity_verifier(_vk: VerificationKeyG2Fq, _abi: SolidityAbi) -> String { + fn export_solidity_verifier(_vk: Self::VerificationKey, _abi: SolidityAbi) -> String { unimplemented!() } - fn verify(vk: VerificationKeyG2Fq, proof: Proof) -> bool { + fn verify(vk: Self::VerificationKey, proof: Proof) -> bool { let vk = VerifyingKey { h_g2: serialization::to_g2_fq::(vk.h), g_alpha_g1: serialization::to_g1::(vk.g_alpha), From 90513aa745f370fefb98190a2f63bb491f09fa2c Mon Sep 17 00:00:00 2001 From: schaeff Date: Mon, 28 Sep 2020 15:20:51 +0200 Subject: [PATCH 25/54] update generated pedersen --- .../stdlib/hashes/pedersen/512bit.zok | 64 ++++++++++--------- 1 file changed, 34 insertions(+), 30 deletions(-) diff --git a/zokrates_stdlib/stdlib/hashes/pedersen/512bit.zok b/zokrates_stdlib/stdlib/hashes/pedersen/512bit.zok index ec5be80cd..65d317af3 100644 --- a/zokrates_stdlib/stdlib/hashes/pedersen/512bit.zok +++ b/zokrates_stdlib/stdlib/hashes/pedersen/512bit.zok @@ -1,3 +1,4 @@ + import "utils/multiplexer/lookup3bitSigned" as sel3s import "utils/multiplexer/lookup2bit" as sel2 import "ecc/babyjubjubParams" as context @@ -15,35 +16,38 @@ import "EMBED/u32_from_bits" as from_bits // #%% // entropy = np.random.bytes(64) // hasher = PedersenHasher("test") +// hasher.hash_bytes(entropy) // print(hasher.dsl_code) -// 512bit to 256bit Pedersen hash using compression of the field elements -def main(u32[16] input) -> u32[8]: - - bool[512] e = [ \ - ...to_bits(input[0]), - ...to_bits(input[1]), - ...to_bits(input[2]), - ...to_bits(input[3]), - ...to_bits(input[4]), - ...to_bits(input[5]), - ...to_bits(input[6]), - ...to_bits(input[7]), - ...to_bits(input[8]), - ...to_bits(input[9]), - ...to_bits(input[10]), - ...to_bits(input[11]), - ...to_bits(input[12]), - ...to_bits(input[13]), - ...to_bits(input[14]), - ...to_bits(input[15]) +def main(u32[16] inputs) -> u32[8]: + bool[513] e = [\ + ...to_bits(inputs[0]), + ...to_bits(inputs[1]), + ...to_bits(inputs[2]), + ...to_bits(inputs[3]), + ...to_bits(inputs[4]), + ...to_bits(inputs[5]), + ...to_bits(inputs[6]), + ...to_bits(inputs[7]), + ...to_bits(inputs[8]), + ...to_bits(inputs[9]), + ...to_bits(inputs[10]), + ...to_bits(inputs[11]), + ...to_bits(inputs[12]), + ...to_bits(inputs[13]), + ...to_bits(inputs[14]), + ...to_bits(inputs[15]), + false ] BabyJubJubParams context = context() field[2] a = context.INFINITY //Infinity + field cx = 0 + field cy = 0 + //Round 0 - field cx = sel3s([e[0], e[1], e[2]], [13418723823902222986275588345615650707197303761863176429873001977640541977977 , 8366451672790208592553809639953117385619257483837439526516290319251622927412, 1785026334726838136757054176272745265857971873904476677125553010508875025629, 15763987975760561753692294837740043971877392788040801334205375164715487005236]) - field cy = sel2([e[0], e[1]], [15255921313433251341520743036334816584226787412845488772781699434149539664639 , 10916775373885716961512013142444429405184550001421868906213743991404593770484, 18533662942827602783563125901366807026309605479742251601915445402562880550265, 12754584346112149619040942896930712185968371085994381911052593922432846916845]) + cx = sel3s([e[0], e[1], e[2]], [13418723823902222986275588345615650707197303761863176429873001977640541977977 , 8366451672790208592553809639953117385619257483837439526516290319251622927412, 1785026334726838136757054176272745265857971873904476677125553010508875025629, 15763987975760561753692294837740043971877392788040801334205375164715487005236]) + cy = sel2([e[0], e[1]], [15255921313433251341520743036334816584226787412845488772781699434149539664639 , 10916775373885716961512013142444429405184550001421868906213743991404593770484, 18533662942827602783563125901366807026309605479742251601915445402562880550265, 12754584346112149619040942896930712185968371085994381911052593922432846916845]) a = add(a, [cx, cy], context) //Round 1 cx = sel3s([e[3], e[4], e[5]], [10096735692467598736728394557736034054031417419721869067082824451240861468728 , 6979151010236415881632946866847657030447196774231162748523315765559549846746, 12137947022495312670974525048647679757468392619153927921382150023166867027471, 10624360821702266736197468438435445939719745367234393212061381062942588576905]) @@ -722,19 +726,19 @@ def main(u32[16] input) -> u32[8]: cy = sel2([e[507], e[508]], [18191174947339798787646910619446409943766046946921136035021645191602921923040 , 16559060177998758852323304784771936179434931576336411584121379336820727372618, 13858115732979799183025726471151602712224733686530960054365665740611187232029, 9933192519609817862698304326029579651414877338671776883175639003837130283966]) a = add(a, [cx, cy], context) //Round 170 - cx = sel3s([e[510], e[511], false], [3342564788366736273905106071612128667477972061160313630133110787799686301495 , 13766193863701503939885263345152684798552605679140222504700163745347162493183, 18523279471468319520962369406962457727155204375043681943707151819380964978377, 8094164074569624021939357073285075790695279643883973800173037824312344195506]) + cx = sel3s([e[510], e[511], e[512]], [3342564788366736273905106071612128667477972061160313630133110787799686301495 , 13766193863701503939885263345152684798552605679140222504700163745347162493183, 18523279471468319520962369406962457727155204375043681943707151819380964978377, 8094164074569624021939357073285075790695279643883973800173037824312344195506]) cy = sel2([e[510], e[511]], [2329094643034533408459502544740928833981119919633412709248656884170940780093 , 3216329736050668550647765981020076413548845117352735257893224753954595290363, 18710403072495673647060422294369054840513840567808020912157404388689648711093, 9785201456176703812798077455183487364035650707229293534561747881523562553649]) a = add(a, [cx, cy], context) bool[256] aC = edwardsCompress(a) return [\ - from_bits(aC[0..32]), - from_bits(aC[32..64]), - from_bits(aC[64..96]), - from_bits(aC[96..128]), - from_bits(aC[128..160]), - from_bits(aC[160..192]), - from_bits(aC[192..224]), + from_bits(aC[0..32]), + from_bits(aC[32..64]), + from_bits(aC[64..96]), + from_bits(aC[96..128]), + from_bits(aC[128..160]), + from_bits(aC[160..192]), + from_bits(aC[192..224]), from_bits(aC[224..256]) ] From 6e7a1c958f7046d12d8f0c83929f35527af1ddf0 Mon Sep 17 00:00:00 2001 From: dark64 Date: Tue, 29 Sep 2020 18:41:53 +0200 Subject: [PATCH 26/54] refactor proof system --- zokrates_cli/src/bin.rs | 207 ++++++----- zokrates_cli/src/helpers.rs | 58 +-- .../src/proof_system/bellman/groth16.rs | 324 ++--------------- zokrates_core/src/proof_system/bellman/mod.rs | 2 + .../src/proof_system/libsnark/gm17.rs | 292 +-------------- .../src/proof_system/libsnark/mod.rs | 2 + .../src/proof_system/libsnark/pghr13.rs | 342 ++---------------- zokrates_core/src/proof_system/mod.rs | 20 +- zokrates_core/src/proof_system/scheme/gm17.rs | 282 +++++++++++++++ .../src/proof_system/scheme/groth16.rs | 254 +++++++++++++ zokrates_core/src/proof_system/scheme/mod.rs | 17 + .../src/proof_system/scheme/pghr13.rs | 316 ++++++++++++++++ zokrates_core/src/proof_system/zexe/gm17.rs | 124 +++---- zokrates_core/src/proof_system/zexe/mod.rs | 2 + 14 files changed, 1155 insertions(+), 1087 deletions(-) create mode 100644 zokrates_core/src/proof_system/scheme/gm17.rs create mode 100644 zokrates_core/src/proof_system/scheme/groth16.rs create mode 100644 zokrates_core/src/proof_system/scheme/mod.rs create mode 100644 zokrates_core/src/proof_system/scheme/pghr13.rs diff --git a/zokrates_cli/src/bin.rs b/zokrates_cli/src/bin.rs index 873aefd52..fd372ecce 100644 --- a/zokrates_cli/src/bin.rs +++ b/zokrates_cli/src/bin.rs @@ -21,13 +21,16 @@ use std::string::String; use zokrates_abi::Encode; use zokrates_core::compile::{check, compile, CompilationArtifacts, CompileError}; use zokrates_core::ir::{self, ProgEnum}; -use zokrates_core::proof_system::bellman::groth16::G16; +use zokrates_core::proof_system::bellman::Bellman; #[cfg(feature = "libsnark")] -use zokrates_core::proof_system::libsnark::gm17::GM17 as GM17_Libsnark; +use zokrates_core::proof_system::libsnark::Libsnark; +use zokrates_core::proof_system::scheme::gm17::GM17; +use zokrates_core::proof_system::scheme::groth16::G16; #[cfg(feature = "libsnark")] -use zokrates_core::proof_system::libsnark::pghr13::PGHR13; +use zokrates_core::proof_system::scheme::pghr13::PGHR13; +use zokrates_core::proof_system::scheme::{Scheme, SolidityCompatibleScheme}; use zokrates_core::proof_system::solidity::SolidityAbi; -use zokrates_core::proof_system::zexe::gm17::GM17 as GM17_Zexe; +use zokrates_core::proof_system::zexe::Zexe; use zokrates_core::proof_system::*; use zokrates_core::typed_absy::abi::Abi; use zokrates_core::typed_absy::{types::Signature, Type}; @@ -41,7 +44,7 @@ fn main() { }) } -fn cli_generate_proof>( +fn cli_generate_proof, B: Backend>( program: ir::Prog, sub_matches: &ArgMatches, ) -> Result<(), String> { @@ -69,7 +72,7 @@ fn cli_generate_proof>( .read_to_end(&mut pk) .map_err(|why| format!("Couldn't read {}: {}", pk_path.display(), why))?; - let proof = P::generate_proof(program, witness, pk); + let proof = B::generate_proof(program, witness, pk); let mut proof_file = File::create(proof_path).unwrap(); let proof = serde_json::to_string_pretty(&proof).unwrap(); @@ -82,7 +85,7 @@ fn cli_generate_proof>( Ok(()) } -fn cli_export_verifier>( +fn cli_export_verifier>( sub_matches: &ArgMatches, ) -> Result<(), String> { println!("Exporting verifier..."); @@ -98,7 +101,7 @@ fn cli_export_verifier>( let abi = SolidityAbi::from(sub_matches.value_of("solidity-abi").unwrap())?; - let verifier = P::export_solidity_verifier(vk, abi); + let verifier = S::export_solidity_verifier(vk, abi); //write output file let output_path = Path::new(sub_matches.value_of("output").unwrap()); @@ -115,7 +118,7 @@ fn cli_export_verifier>( Ok(()) } -fn cli_setup>( +fn cli_setup, B: Backend>( program: ir::Prog, sub_matches: &ArgMatches, ) -> Result<(), String> { @@ -131,7 +134,7 @@ fn cli_setup>( let vk_path = Path::new(sub_matches.value_of("verification-key-path").unwrap()); // run setup phase - let keypair = P::setup(program); + let keypair = B::setup(program); // write verification key let mut vk_file = File::create(vk_path) @@ -397,7 +400,9 @@ fn cli_check(sub_matches: &ArgMatches) -> Result<(), String> { Ok(()) } -fn cli_verify>(sub_matches: &ArgMatches) -> Result<(), String> { +fn cli_verify, B: Backend>( + sub_matches: &ArgMatches, +) -> Result<(), String> { let vk_path = Path::new(sub_matches.value_of("verification-key-path").unwrap()); let vk_file = File::open(&vk_path) .map_err(|why| format!("Couldn't open {}: {}", vk_path.display(), why))?; @@ -417,7 +422,7 @@ fn cli_verify>(sub_matches: &ArgMatches) -> Result<( println!("Performing verification..."); println!( "The verification result is: {}", - match P::verify(vk, proof) { + match B::verify(vk, proof) { true => "PASS", false => "FAIL", } @@ -795,21 +800,21 @@ fn cli() -> Result<(), String> { match matches.subcommand() { ("compile", Some(sub_matches)) => { - let curve = Curve::try_from(sub_matches.value_of("curve").unwrap())?; + let curve = CurveDimension::try_from(sub_matches.value_of("curve").unwrap())?; match curve { - Curve::Bn128 => cli_compile::(sub_matches)?, - Curve::Bls12_377 => cli_compile::(sub_matches)?, - Curve::Bls12_381 => cli_compile::(sub_matches)?, - Curve::Bw6_761 => cli_compile::(sub_matches)?, + CurveDimension::Bn128 => cli_compile::(sub_matches)?, + CurveDimension::Bls12_377 => cli_compile::(sub_matches)?, + CurveDimension::Bls12_381 => cli_compile::(sub_matches)?, + CurveDimension::Bw6_761 => cli_compile::(sub_matches)?, } } ("check", Some(sub_matches)) => { - let curve = Curve::try_from(sub_matches.value_of("curve").unwrap())?; + let curve = CurveDimension::try_from(sub_matches.value_of("curve").unwrap())?; match curve { - Curve::Bn128 => cli_check::(sub_matches)?, - Curve::Bls12_377 => cli_check::(sub_matches)?, - Curve::Bls12_381 => cli_check::(sub_matches)?, - Curve::Bw6_761 => cli_check::(sub_matches)?, + CurveDimension::Bn128 => cli_check::(sub_matches)?, + CurveDimension::Bls12_377 => cli_check::(sub_matches)?, + CurveDimension::Bls12_381 => cli_check::(sub_matches)?, + CurveDimension::Bw6_761 => cli_check::(sub_matches)?, } } ("compute-witness", Some(sub_matches)) => { @@ -848,62 +853,56 @@ fn cli() -> Result<(), String> { ))?; match dimensions { - Dimensions(Backend::Bellman, _, ProvingScheme::G16) => match prog { - ProgEnum::Bn128Program(p) => cli_setup::<_, G16>(p, sub_matches), - ProgEnum::Bls12_381Program(p) => cli_setup::<_, G16>(p, sub_matches), + Dimensions(BackendDimension::Bellman, _, SchemeDimension::G16) => match prog { + ProgEnum::Bn128Program(p) => cli_setup::<_, G16, Bellman>(p, sub_matches), + ProgEnum::Bls12_381Program(p) => cli_setup::<_, G16, Bellman>(p, sub_matches), _ => unreachable!(), }, - Dimensions(Backend::Zexe, _, ProvingScheme::GM17) => match prog { - ProgEnum::Bls12_377Program(p) => cli_setup::<_, GM17_Zexe>(p, sub_matches), - ProgEnum::Bw6_761Program(p) => cli_setup::<_, GM17_Zexe>(p, sub_matches), - ProgEnum::Bn128Program(p) => cli_setup::<_, GM17_Zexe>(p, sub_matches), + Dimensions(BackendDimension::Zexe, _, SchemeDimension::GM17) => match prog { + ProgEnum::Bls12_377Program(p) => cli_setup::<_, GM17, Zexe>(p, sub_matches), + ProgEnum::Bw6_761Program(p) => cli_setup::<_, GM17, Zexe>(p, sub_matches), + ProgEnum::Bn128Program(p) => cli_setup::<_, GM17, Zexe>(p, sub_matches), _ => unreachable!(), }, #[cfg(feature = "libsnark")] - Dimensions(Backend::Libsnark, Curve::Bn128, ProvingScheme::GM17) => match prog { - ProgEnum::Bn128Program(p) => cli_setup::<_, GM17_Libsnark>(p, sub_matches), + Dimensions( + BackendDimension::Libsnark, + CurveDimension::Bn128, + SchemeDimension::GM17, + ) => match prog { + ProgEnum::Bn128Program(p) => cli_setup::<_, GM17, Libsnark>(p, sub_matches), _ => unreachable!(), }, #[cfg(feature = "libsnark")] - Dimensions(Backend::Libsnark, Curve::Bn128, ProvingScheme::PGHR13) => match prog { - ProgEnum::Bn128Program(p) => cli_setup::<_, PGHR13>(p, sub_matches), + Dimensions( + BackendDimension::Libsnark, + CurveDimension::Bn128, + SchemeDimension::PGHR13, + ) => match prog { + ProgEnum::Bn128Program(p) => cli_setup::<_, PGHR13, Libsnark>(p, sub_matches), _ => unreachable!(), }, _ => unreachable!(), }? } ("export-verifier", Some(sub_matches)) => { - let dimensions = Dimensions::try_from(( - sub_matches.value_of("backend").unwrap(), - sub_matches.value_of("curve").unwrap(), - sub_matches.value_of("proving-scheme").unwrap(), - ))?; + let curve = sub_matches.value_of("curve").unwrap(); + let scheme = sub_matches.value_of("proving-scheme").unwrap(); + let curve_dimension = CurveDimension::try_from(curve)?; + let scheme_dimension = SchemeDimension::try_from(scheme)?; - match dimensions { - Dimensions(Backend::Bellman, Curve::Bn128, ProvingScheme::G16) => { + match (curve_dimension, scheme_dimension) { + (CurveDimension::Bn128, SchemeDimension::G16) => { cli_export_verifier::(sub_matches) } - Dimensions(Backend::Bellman, Curve::Bls12_381, ProvingScheme::G16) => { - cli_export_verifier::(sub_matches) - } - Dimensions(Backend::Zexe, Curve::Bls12_377, ProvingScheme::GM17) => { - cli_export_verifier::(sub_matches) - } - Dimensions(Backend::Zexe, Curve::Bw6_761, ProvingScheme::GM17) => { - cli_export_verifier::(sub_matches) - } - Dimensions(Backend::Zexe, Curve::Bn128, ProvingScheme::GM17) => { - cli_export_verifier::(sub_matches) + (CurveDimension::Bn128, SchemeDimension::GM17) => { + cli_export_verifier::(sub_matches) } #[cfg(feature = "libsnark")] - Dimensions(Backend::Libsnark, Curve::Bn128, ProvingScheme::GM17) => { - cli_export_verifier::(sub_matches) - } - #[cfg(feature = "libsnark")] - Dimensions(Backend::Libsnark, Curve::Bn128, ProvingScheme::PGHR13) => { + (CurveDimension::Bn128, SchemeDimension::PGHR13) => { cli_export_verifier::(sub_matches) } - _ => unreachable!(), + _ => Err(format!("Could not export verifier for given dimensions (curve: {}, scheme: {}): not supported", curve, scheme)) }? } ("generate-proof", Some(sub_matches)) => { @@ -926,31 +925,47 @@ fn cli() -> Result<(), String> { ))?; match dimensions { - Dimensions(Backend::Bellman, _, ProvingScheme::G16) => match prog { - ProgEnum::Bn128Program(p) => cli_generate_proof::<_, G16>(p, sub_matches), - ProgEnum::Bls12_381Program(p) => cli_generate_proof::<_, G16>(p, sub_matches), + Dimensions(BackendDimension::Bellman, _, SchemeDimension::G16) => match prog { + ProgEnum::Bn128Program(p) => { + cli_generate_proof::<_, G16, Bellman>(p, sub_matches) + } + ProgEnum::Bls12_381Program(p) => { + cli_generate_proof::<_, G16, Bellman>(p, sub_matches) + } _ => unreachable!(), }, - Dimensions(Backend::Zexe, _, ProvingScheme::GM17) => match prog { + Dimensions(BackendDimension::Zexe, _, SchemeDimension::GM17) => match prog { ProgEnum::Bls12_377Program(p) => { - cli_generate_proof::<_, GM17_Zexe>(p, sub_matches) + cli_generate_proof::<_, GM17, Zexe>(p, sub_matches) } ProgEnum::Bw6_761Program(p) => { - cli_generate_proof::<_, GM17_Zexe>(p, sub_matches) + cli_generate_proof::<_, GM17, Zexe>(p, sub_matches) + } + ProgEnum::Bn128Program(p) => { + cli_generate_proof::<_, GM17, Zexe>(p, sub_matches) } - ProgEnum::Bn128Program(p) => cli_generate_proof::<_, GM17_Zexe>(p, sub_matches), _ => unreachable!(), }, #[cfg(feature = "libsnark")] - Dimensions(Backend::Libsnark, Curve::Bn128, ProvingScheme::GM17) => match prog { + Dimensions( + BackendDimension::Libsnark, + CurveDimension::Bn128, + SchemeDimension::GM17, + ) => match prog { ProgEnum::Bn128Program(p) => { - cli_generate_proof::<_, GM17_Libsnark>(p, sub_matches) + cli_generate_proof::<_, GM17, Libsnark>(p, sub_matches) } _ => unreachable!(), }, #[cfg(feature = "libsnark")] - Dimensions(Backend::Libsnark, Curve::Bn128, ProvingScheme::PGHR13) => match prog { - ProgEnum::Bn128Program(p) => cli_generate_proof::<_, PGHR13>(p, sub_matches), + Dimensions( + BackendDimension::Libsnark, + CurveDimension::Bn128, + SchemeDimension::PGHR13, + ) => match prog { + ProgEnum::Bn128Program(p) => { + cli_generate_proof::<_, PGHR13, Libsnark>(p, sub_matches) + } _ => unreachable!(), }, _ => unreachable!(), @@ -1000,29 +1015,43 @@ fn cli() -> Result<(), String> { ))?; match dimensions { - Dimensions(Backend::Bellman, Curve::Bn128, ProvingScheme::G16) => { - cli_verify::(sub_matches) - } - Dimensions(Backend::Bellman, Curve::Bls12_381, ProvingScheme::G16) => { - cli_verify::(sub_matches) - } - Dimensions(Backend::Zexe, Curve::Bls12_377, ProvingScheme::GM17) => { - cli_verify::(sub_matches) - } - Dimensions(Backend::Zexe, Curve::Bw6_761, ProvingScheme::GM17) => { - cli_verify::(sub_matches) - } - Dimensions(Backend::Zexe, Curve::Bn128, ProvingScheme::GM17) => { - cli_verify::(sub_matches) - } + Dimensions( + BackendDimension::Bellman, + CurveDimension::Bn128, + SchemeDimension::G16, + ) => cli_verify::(sub_matches), + Dimensions( + BackendDimension::Bellman, + CurveDimension::Bls12_381, + SchemeDimension::G16, + ) => cli_verify::(sub_matches), + Dimensions( + BackendDimension::Zexe, + CurveDimension::Bls12_377, + SchemeDimension::GM17, + ) => cli_verify::(sub_matches), + Dimensions( + BackendDimension::Zexe, + CurveDimension::Bw6_761, + SchemeDimension::GM17, + ) => cli_verify::(sub_matches), + Dimensions( + BackendDimension::Zexe, + CurveDimension::Bn128, + SchemeDimension::GM17, + ) => cli_verify::(sub_matches), #[cfg(feature = "libsnark")] - Dimensions(Backend::Libsnark, Curve::Bn128, ProvingScheme::GM17) => { - cli_verify::(sub_matches) - } + Dimensions( + BackendDimension::Libsnark, + CurveDimension::Bn128, + SchemeDimension::GM17, + ) => cli_verify::(sub_matches), #[cfg(feature = "libsnark")] - Dimensions(Backend::Libsnark, Curve::Bn128, ProvingScheme::PGHR13) => { - cli_verify::(sub_matches) - } + Dimensions( + BackendDimension::Libsnark, + CurveDimension::Bn128, + SchemeDimension::PGHR13, + ) => cli_verify::(sub_matches), _ => unreachable!(), }? } diff --git a/zokrates_cli/src/helpers.rs b/zokrates_cli/src/helpers.rs index 2229876a8..c842bb2d3 100644 --- a/zokrates_cli/src/helpers.rs +++ b/zokrates_cli/src/helpers.rs @@ -3,101 +3,105 @@ use core::convert::TryFrom; use crate::constants::*; #[derive(Debug)] -pub enum Curve { +pub enum CurveDimension { Bn128, Bls12_381, Bls12_377, Bw6_761, } -pub enum Backend { +pub enum BackendDimension { Bellman, Zexe, #[cfg(feature = "libsnark")] Libsnark, } -pub enum ProvingScheme { +pub enum SchemeDimension { G16, GM17, #[cfg(feature = "libsnark")] PGHR13, } -impl TryFrom<&str> for Curve { +impl TryFrom<&str> for CurveDimension { type Error = String; fn try_from(s: &str) -> Result { match s { - BN128 => Ok(Curve::Bn128), - BLS12_381 => Ok(Curve::Bls12_381), - BLS12_377 => Ok(Curve::Bls12_377), - BW6_761 => Ok(Curve::Bw6_761), + BN128 => Ok(CurveDimension::Bn128), + BLS12_381 => Ok(CurveDimension::Bls12_381), + BLS12_377 => Ok(CurveDimension::Bls12_377), + BW6_761 => Ok(CurveDimension::Bw6_761), _ => Err(format!("Unknown curve {}", s)), } } } -impl TryFrom<&str> for Backend { +impl TryFrom<&str> for BackendDimension { type Error = String; fn try_from(s: &str) -> Result { match s { - BELLMAN => Ok(Backend::Bellman), - ZEXE => Ok(Backend::Zexe), + BELLMAN => Ok(BackendDimension::Bellman), + ZEXE => Ok(BackendDimension::Zexe), #[cfg(feature = "libsnark")] - LIBSNARK => Ok(Backend::Libsnark), + LIBSNARK => Ok(BackendDimension::Libsnark), _ => Err(format!("Unknown backend {}", s)), } } } -impl TryFrom<&str> for ProvingScheme { +impl TryFrom<&str> for SchemeDimension { type Error = String; fn try_from(s: &str) -> Result { match s { - G16 => Ok(ProvingScheme::G16), - GM17 => Ok(ProvingScheme::GM17), + G16 => Ok(SchemeDimension::G16), + GM17 => Ok(SchemeDimension::GM17), #[cfg(feature = "libsnark")] - PGHR13 => Ok(ProvingScheme::PGHR13), + PGHR13 => Ok(SchemeDimension::PGHR13), _ => Err(format!("Unknown proving scheme {}", s)), } } } -pub struct Dimensions(pub Backend, pub Curve, pub ProvingScheme); +pub struct Dimensions( + pub BackendDimension, + pub CurveDimension, + pub SchemeDimension, +); impl TryFrom<(&str, &str, &str)> for Dimensions { type Error = String; fn try_from(s: (&str, &str, &str)) -> Result { - let backend = Backend::try_from(s.0)?; - let curve = Curve::try_from(s.1)?; - let proving_scheme = ProvingScheme::try_from(s.2)?; + let backend = BackendDimension::try_from(s.0)?; + let curve = CurveDimension::try_from(s.1)?; + let proving_scheme = SchemeDimension::try_from(s.2)?; match (&backend, &curve, &proving_scheme) { - (Backend::Bellman, Curve::Bn128, ProvingScheme::G16) => { + (BackendDimension::Bellman, CurveDimension::Bn128, SchemeDimension::G16) => { Ok(Dimensions(backend, curve, proving_scheme)) } - (Backend::Bellman, Curve::Bls12_381, ProvingScheme::G16) => { + (BackendDimension::Bellman, CurveDimension::Bls12_381, SchemeDimension::G16) => { Ok(Dimensions(backend, curve, proving_scheme)) } - (Backend::Zexe, Curve::Bls12_377, ProvingScheme::GM17) => { + (BackendDimension::Zexe, CurveDimension::Bls12_377, SchemeDimension::GM17) => { Ok(Dimensions(backend, curve, proving_scheme)) } - (Backend::Zexe, Curve::Bw6_761, ProvingScheme::GM17) => { + (BackendDimension::Zexe, CurveDimension::Bw6_761, SchemeDimension::GM17) => { Ok(Dimensions(backend, curve, proving_scheme)) } - (Backend::Zexe, Curve::Bn128, ProvingScheme::GM17) => { + (BackendDimension::Zexe, CurveDimension::Bn128, SchemeDimension::GM17) => { Ok(Dimensions(backend, curve, proving_scheme)) } #[cfg(feature = "libsnark")] - (Backend::Libsnark, Curve::Bn128, ProvingScheme::GM17) => { + (BackendDimension::Libsnark, CurveDimension::Bn128, SchemeDimension::GM17) => { Ok(Dimensions(backend, curve, proving_scheme)) } #[cfg(feature = "libsnark")] - (Backend::Libsnark, Curve::Bn128, ProvingScheme::PGHR13) => { + (BackendDimension::Libsnark, CurveDimension::Bn128, SchemeDimension::PGHR13) => { Ok(Dimensions(backend, curve, proving_scheme)) } _ => Err(format!( diff --git a/zokrates_core/src/proof_system/bellman/groth16.rs b/zokrates_core/src/proof_system/bellman/groth16.rs index c6969c5f8..3033d0b4f 100644 --- a/zokrates_core/src/proof_system/bellman/groth16.rs +++ b/zokrates_core/src/proof_system/bellman/groth16.rs @@ -3,72 +3,22 @@ use bellman::groth16::{ VerifyingKey, }; use pairing::{CurveAffine, Engine}; -use regex::Regex; -use ir; -use proof_system::solidity::{ - SolidityAbi, SOLIDITY_G2_ADDITION_LIB, SOLIDITY_PAIRING_LIB, SOLIDITY_PAIRING_LIB_V2, -}; -use proof_system::{G1Affine, G2Affine, Proof, ProofSystem, SetupKeypair}; +use proof_system::{Backend, Proof, SetupKeypair}; use zokrates_field::BellmanFieldExtensions; use zokrates_field::Field; use crate::proof_system::bellman::Computation; use crate::proof_system::bellman::{parse_fr, parse_g1, parse_g2}; +use ir::{Prog, Witness}; +use proof_system::bellman::Bellman; +use proof_system::scheme::groth16::{ProofPoints, VerificationKey, G16}; +use proof_system::scheme::Scheme; const G16_WARNING: &str = "WARNING: You are using the G16 scheme which is subject to malleability. See zokrates.github.io/toolbox/proving_schemes.html#g16-malleability for implications."; -pub struct G16 {} - -#[derive(Serialize, Deserialize)] -pub struct ProofPoints { - a: G1Affine, - b: G2Affine, - c: G1Affine, -} - -impl ProofPoints { - fn into_bellman(self) -> BellmanProof { - BellmanProof { - a: serialization::to_g1::(self.a), - b: serialization::to_g2::(self.b), - c: serialization::to_g1::(self.c), - } - } -} - -#[derive(Serialize, Deserialize)] -pub struct VerificationKey { - alpha: G1Affine, - beta: G2Affine, - gamma: G2Affine, - delta: G2Affine, - gamma_abc: Vec, -} - -impl VerificationKey { - fn into_bellman(self) -> VerifyingKey { - VerifyingKey { - alpha_g1: serialization::to_g1::(self.alpha), - beta_g1: ::G1Affine::one(), // not used during verification - beta_g2: serialization::to_g2::(self.beta), - gamma_g2: serialization::to_g2::(self.gamma), - delta_g1: ::G1Affine::one(), // not used during verification - delta_g2: serialization::to_g2::(self.delta), - ic: self - .gamma_abc - .into_iter() - .map(|g1| serialization::to_g1::(g1)) - .collect(), - } - } -} - -impl ProofSystem for G16 { - type VerificationKey = VerificationKey; - type ProofPoints = ProofPoints; - - fn setup(program: ir::Prog) -> SetupKeypair { +impl Backend for Bellman { + fn setup(program: Prog) -> SetupKeypair<>::VerificationKey> { println!("{}", G16_WARNING); let parameters = Computation::without_witness(program).setup(); @@ -92,13 +42,10 @@ impl ProofSystem for G16 { } fn generate_proof( - program: ir::Prog, - witness: ir::Witness, + program: Prog, + witness: Witness, proving_key: Vec, - ) -> Proof { - #[cfg(not(target_arch = "wasm32"))] - std::env::set_var("BELLMAN_VERBOSE", "0"); - + ) -> Proof<>::ProofPoints> { println!("{}", G16_WARNING); let computation = Computation::with_witness(program, witness); @@ -117,116 +64,33 @@ impl ProofSystem for G16 { .map(parse_fr::) .collect::>(); - Proof::::new(proof_points, inputs, None) + Proof::new(proof_points, inputs, None) } - fn export_solidity_verifier(vk: VerificationKey, abi: SolidityAbi) -> String { - let (mut template_text, solidity_pairing_lib) = match abi { - SolidityAbi::V1 => ( - String::from(CONTRACT_TEMPLATE), - String::from(SOLIDITY_PAIRING_LIB), - ), - SolidityAbi::V2 => ( - String::from(CONTRACT_TEMPLATE_V2), - String::from(SOLIDITY_PAIRING_LIB_V2), - ), + fn verify( + vk: >::VerificationKey, + proof: Proof<>::ProofPoints>, + ) -> bool { + let vk = VerifyingKey { + alpha_g1: serialization::to_g1::(vk.alpha), + beta_g1: ::G1Affine::one(), // not used during verification + beta_g2: serialization::to_g2::(vk.beta), + gamma_g2: serialization::to_g2::(vk.gamma), + delta_g1: ::G1Affine::one(), // not used during verification + delta_g2: serialization::to_g2::(vk.delta), + ic: vk + .gamma_abc + .into_iter() + .map(|g1| serialization::to_g1::(g1)) + .collect(), }; - let vk_regex = Regex::new(r#"(<%vk_[^i%]*%>)"#).unwrap(); - let vk_gamma_abc_len_regex = Regex::new(r#"(<%vk_gamma_abc_length%>)"#).unwrap(); - let vk_gamma_abc_repeat_regex = Regex::new(r#"(<%vk_gamma_abc_pts%>)"#).unwrap(); - let vk_input_len_regex = Regex::new(r#"(<%vk_input_length%>)"#).unwrap(); - let input_loop = Regex::new(r#"(<%input_loop%>)"#).unwrap(); - let input_argument = Regex::new(r#"(<%input_argument%>)"#).unwrap(); - - template_text = vk_regex - .replace(template_text.as_str(), vk.alpha.to_string().as_str()) - .into_owned(); - - template_text = vk_regex - .replace(template_text.as_str(), vk.beta.to_string().as_str()) - .into_owned(); - - template_text = vk_regex - .replace(template_text.as_str(), vk.gamma.to_string().as_str()) - .into_owned(); - - template_text = vk_regex - .replace(template_text.as_str(), vk.delta.to_string().as_str()) - .into_owned(); - - let gamma_abc_count: usize = vk.gamma_abc.len(); - template_text = vk_gamma_abc_len_regex - .replace( - template_text.as_str(), - format!("{}", gamma_abc_count).as_str(), - ) - .into_owned(); - - template_text = vk_input_len_regex - .replace( - template_text.as_str(), - format!("{}", gamma_abc_count - 1).as_str(), - ) - .into_owned(); - - // feed input values only if there are any - template_text = if gamma_abc_count > 1 { - input_loop.replace( - template_text.as_str(), - r#" - for(uint i = 0; i < input.length; i++){ - inputValues[i] = input[i]; - }"#, - ) - } else { - input_loop.replace(template_text.as_str(), "") - } - .to_string(); - - // take input values as argument only if there are any - template_text = if gamma_abc_count > 1 { - input_argument.replace( - template_text.as_str(), - format!(", uint[{}] memory input", gamma_abc_count - 1).as_str(), - ) - } else { - input_argument.replace(template_text.as_str(), "") - } - .to_string(); - - let mut gamma_abc_repeat_text = String::new(); - for (i, g1) in vk.gamma_abc.iter().enumerate() { - gamma_abc_repeat_text.push_str( - format!( - "vk.gamma_abc[{}] = Pairing.G1Point({});", - i, - g1.to_string().as_str() - ) - .as_str(), - ); - if i < gamma_abc_count - 1 { - gamma_abc_repeat_text.push_str("\n "); - } - } - - template_text = vk_gamma_abc_repeat_regex - .replace(template_text.as_str(), gamma_abc_repeat_text.as_str()) - .into_owned(); - - let re = Regex::new(r"(?P0[xX][0-9a-fA-F]{64})").unwrap(); - template_text = re.replace_all(&template_text, "uint256($v)").to_string(); - - format!( - "{}{}{}", - SOLIDITY_G2_ADDITION_LIB, solidity_pairing_lib, template_text - ) - } - - fn verify(vk: VerificationKey, proof: Proof) -> bool { - let vk: VerifyingKey = vk.into_bellman::(); let pvk: PreparedVerifyingKey = prepare_verifying_key(&vk); - let bellman_proof: BellmanProof = proof.proof.into_bellman::(); + let bellman_proof = BellmanProof { + a: serialization::to_g1::(proof.proof.a), + b: serialization::to_g2::(proof.proof.b), + c: serialization::to_g1::(proof.proof.c), + }; let public_inputs: Vec<_> = proof .inputs @@ -267,122 +131,6 @@ mod serialization { } } -const CONTRACT_TEMPLATE_V2: &str = r#" -contract Verifier { - using Pairing for *; - struct VerifyingKey { - Pairing.G1Point alpha; - Pairing.G2Point beta; - Pairing.G2Point gamma; - Pairing.G2Point delta; - Pairing.G1Point[] gamma_abc; - } - struct Proof { - Pairing.G1Point a; - Pairing.G2Point b; - Pairing.G1Point c; - } - function verifyingKey() pure internal returns (VerifyingKey memory vk) { - vk.alpha = Pairing.G1Point(<%vk_alpha%>); - vk.beta = Pairing.G2Point(<%vk_beta%>); - vk.gamma = Pairing.G2Point(<%vk_gamma%>); - vk.delta = Pairing.G2Point(<%vk_delta%>); - vk.gamma_abc = new Pairing.G1Point[](<%vk_gamma_abc_length%>); - <%vk_gamma_abc_pts%> - } - function verify(uint[] memory input, Proof memory proof) internal view returns (uint) { - uint256 snark_scalar_field = 21888242871839275222246405745257275088548364400416034343698204186575808495617; - VerifyingKey memory vk = verifyingKey(); - require(input.length + 1 == vk.gamma_abc.length); - // Compute the linear combination vk_x - Pairing.G1Point memory vk_x = Pairing.G1Point(0, 0); - for (uint i = 0; i < input.length; i++) { - require(input[i] < snark_scalar_field); - vk_x = Pairing.addition(vk_x, Pairing.scalar_mul(vk.gamma_abc[i + 1], input[i])); - } - vk_x = Pairing.addition(vk_x, vk.gamma_abc[0]); - if(!Pairing.pairingProd4( - proof.a, proof.b, - Pairing.negate(vk_x), vk.gamma, - Pairing.negate(proof.c), vk.delta, - Pairing.negate(vk.alpha), vk.beta)) return 1; - return 0; - } - function verifyTx( - Proof memory proof<%input_argument%> - ) public view returns (bool r) { - uint[] memory inputValues = new uint[](input.length); - <%input_loop%> - if (verify(inputValues, proof) == 0) { - return true; - } else { - return false; - } - } -} -"#; - -const CONTRACT_TEMPLATE: &str = r#" -contract Verifier { - using Pairing for *; - struct VerifyingKey { - Pairing.G1Point alpha; - Pairing.G2Point beta; - Pairing.G2Point gamma; - Pairing.G2Point delta; - Pairing.G1Point[] gamma_abc; - } - struct Proof { - Pairing.G1Point a; - Pairing.G2Point b; - Pairing.G1Point c; - } - function verifyingKey() pure internal returns (VerifyingKey memory vk) { - vk.alpha = Pairing.G1Point(<%vk_alpha%>); - vk.beta = Pairing.G2Point(<%vk_beta%>); - vk.gamma = Pairing.G2Point(<%vk_gamma%>); - vk.delta = Pairing.G2Point(<%vk_delta%>); - vk.gamma_abc = new Pairing.G1Point[](<%vk_gamma_abc_length%>); - <%vk_gamma_abc_pts%> - } - function verify(uint[] memory input, Proof memory proof) internal view returns (uint) { - uint256 snark_scalar_field = 21888242871839275222246405745257275088548364400416034343698204186575808495617; - VerifyingKey memory vk = verifyingKey(); - require(input.length + 1 == vk.gamma_abc.length); - // Compute the linear combination vk_x - Pairing.G1Point memory vk_x = Pairing.G1Point(0, 0); - for (uint i = 0; i < input.length; i++) { - require(input[i] < snark_scalar_field); - vk_x = Pairing.addition(vk_x, Pairing.scalar_mul(vk.gamma_abc[i + 1], input[i])); - } - vk_x = Pairing.addition(vk_x, vk.gamma_abc[0]); - if(!Pairing.pairingProd4( - proof.a, proof.b, - Pairing.negate(vk_x), vk.gamma, - Pairing.negate(proof.c), vk.delta, - Pairing.negate(vk.alpha), vk.beta)) return 1; - return 0; - } - function verifyTx( - uint[2] memory a, - uint[2][2] memory b, - uint[2] memory c<%input_argument%> - ) public view returns (bool r) { - Proof memory proof; - proof.a = Pairing.G1Point(a[0], a[1]); - proof.b = Pairing.G2Point([b[0][0], b[0][1]], [b[1][0], b[1][1]]); - proof.c = Pairing.G1Point(c[0], c[1]); - uint[] memory inputValues = new uint[](<%vk_input_length%>); - <%input_loop%> - if (verify(inputValues, proof) == 0) { - return true; - } else { - return false; - } - } -} -"#; - #[cfg(test)] mod tests { use zokrates_field::Bn128Field; @@ -407,16 +155,16 @@ mod tests { private: vec![false], }; - let keypair = G16::setup(program.clone()); - + let keypair = >::setup(program.clone()); let interpreter = Interpreter::default(); let witness = interpreter .execute(&program, &vec![Bn128Field::from(42)]) .unwrap(); - let proof = G16::generate_proof(program, witness, keypair.pk); - let ans = >::verify(keypair.vk, proof); + let proof = + >::generate_proof(program, witness, keypair.pk); + let ans = >::verify(keypair.vk, proof); assert!(ans); } diff --git a/zokrates_core/src/proof_system/bellman/mod.rs b/zokrates_core/src/proof_system/bellman/mod.rs index 527e29c8c..d7888339c 100644 --- a/zokrates_core/src/proof_system/bellman/mod.rs +++ b/zokrates_core/src/proof_system/bellman/mod.rs @@ -19,6 +19,8 @@ use rand_0_4::ChaChaRng; pub use self::parse::*; +pub struct Bellman; + #[derive(Clone)] pub struct Computation { program: Prog, diff --git a/zokrates_core/src/proof_system/libsnark/gm17.rs b/zokrates_core/src/proof_system/libsnark/gm17.rs index f510b0a9c..3305455ee 100644 --- a/zokrates_core/src/proof_system/libsnark/gm17.rs +++ b/zokrates_core/src/proof_system/libsnark/gm17.rs @@ -1,35 +1,14 @@ -use ir; +use ir::{Prog, Witness}; use proof_system::libsnark::ffi::{Buffer, ProofResult, SetupResult}; -use proof_system::libsnark::{prepare_generate_proof, prepare_public_inputs, prepare_setup}; -use proof_system::solidity::{ - SolidityAbi, SOLIDITY_G2_ADDITION_LIB, SOLIDITY_PAIRING_LIB, SOLIDITY_PAIRING_LIB_V2, +use proof_system::libsnark::{ + prepare_generate_proof, prepare_public_inputs, prepare_setup, Libsnark, }; -use proof_system::{G1Affine, G2Affine, Proof, ProofSystem, SetupKeypair}; -use regex::Regex; - +use proof_system::scheme::gm17::GM17; +use proof_system::scheme::Scheme; +use proof_system::{Backend, Proof, SetupKeypair}; use zokrates_field::Bn128Field; use zokrates_field::Field; -pub struct GM17 {} - -#[derive(Serialize, Deserialize)] -pub struct VerificationKey { - h: G2Affine, - g_alpha: G1Affine, - h_beta: G2Affine, - g_gamma: G1Affine, - h_gamma: G2Affine, - query: Vec, - raw: String, -} - -#[derive(Serialize, Deserialize)] -pub struct ProofPoints { - a: G1Affine, - b: G2Affine, - c: G1Affine, -} - extern "C" { fn gm17_bn128_setup( a: *const u8, @@ -59,11 +38,10 @@ extern "C" { ) -> bool; } -impl ProofSystem for GM17 { - type VerificationKey = VerificationKey; - type ProofPoints = ProofPoints; - - fn setup(program: ir::Prog) -> SetupKeypair { +impl Backend for Libsnark { + fn setup( + program: Prog, + ) -> SetupKeypair<>::VerificationKey> { let (a_arr, b_arr, c_arr, a_vec, b_vec, c_vec, num_constraints, num_variables, num_inputs) = prepare_setup(program); @@ -97,10 +75,10 @@ impl ProofSystem for GM17 { } fn generate_proof( - program: ir::Prog, - witness: ir::Witness, + program: Prog, + witness: Witness, proving_key: Vec, - ) -> Proof { + ) -> Proof<>::ProofPoints> { let (public_inputs_arr, public_inputs_length, private_inputs_arr, private_inputs_length) = prepare_generate_proof(program, witness); @@ -130,114 +108,12 @@ impl ProofSystem for GM17 { serde_json::from_str(String::from_utf8(proof).unwrap().as_str()).unwrap() } - fn export_solidity_verifier(vk: VerificationKey, abi: SolidityAbi) -> String { - let (mut template_text, solidity_pairing_lib) = match abi { - SolidityAbi::V1 => ( - String::from(CONTRACT_TEMPLATE), - String::from(SOLIDITY_PAIRING_LIB), - ), - SolidityAbi::V2 => ( - String::from(CONTRACT_TEMPLATE_V2), - String::from(SOLIDITY_PAIRING_LIB_V2), - ), - }; - - // replace things in template - let vk_regex = Regex::new(r#"(<%vk_[^i%]*%>)"#).unwrap(); - let vk_query_len_regex = Regex::new(r#"(<%vk_query_length%>)"#).unwrap(); - let vk_query_repeat_regex = Regex::new(r#"(<%vk_query_pts%>)"#).unwrap(); - let vk_input_len_regex = Regex::new(r#"(<%vk_input_length%>)"#).unwrap(); - let input_loop = Regex::new(r#"(<%input_loop%>)"#).unwrap(); - let input_argument = Regex::new(r#"(<%input_argument%>)"#).unwrap(); - - template_text = vk_regex - .replace(template_text.as_str(), vk.h.to_string().as_str()) - .into_owned(); - - template_text = vk_regex - .replace(template_text.as_str(), vk.g_alpha.to_string().as_str()) - .into_owned(); - - template_text = vk_regex - .replace(template_text.as_str(), vk.h_beta.to_string().as_str()) - .into_owned(); - - template_text = vk_regex - .replace(template_text.as_str(), vk.g_gamma.to_string().as_str()) - .into_owned(); - - template_text = vk_regex - .replace(template_text.as_str(), vk.h_gamma.to_string().as_str()) - .into_owned(); - - let query_count: usize = vk.query.len(); - template_text = vk_query_len_regex - .replace(template_text.as_str(), format!("{}", query_count).as_str()) - .into_owned(); - - template_text = vk_input_len_regex - .replace( - template_text.as_str(), - format!("{}", query_count - 1).as_str(), - ) - .into_owned(); - - // feed input values only if there are any - template_text = if query_count > 1 { - input_loop.replace( - template_text.as_str(), - r#" - for(uint i = 0; i < input.length; i++){ - inputValues[i] = input[i]; - }"#, - ) - } else { - input_loop.replace(template_text.as_str(), "") - } - .to_string(); - - // take input values as argument only if there are any - template_text = if query_count > 1 { - input_argument.replace( - template_text.as_str(), - format!(", uint[{}] memory input", query_count - 1).as_str(), - ) - } else { - input_argument.replace(template_text.as_str(), "") - } - .to_string(); - - let mut query_repeat_text = String::new(); - for (i, g1) in vk.query.iter().enumerate() { - query_repeat_text.push_str( - format!( - "vk.query[{}] = Pairing.G1Point({});", - i, - g1.to_string().as_str() - ) - .as_str(), - ); - if i < query_count - 1 { - query_repeat_text.push_str("\n "); - } - } - - template_text = vk_query_repeat_regex - .replace(template_text.as_str(), query_repeat_text.as_str()) - .into_owned(); - - let re = Regex::new(r"(?P0[xX][0-9a-fA-F]{64})").unwrap(); - template_text = re.replace_all(&template_text, "uint256($v)").to_string(); - - format!( - "{}{}{}", - SOLIDITY_G2_ADDITION_LIB, solidity_pairing_lib, template_text - ) - } - - fn verify(vk: VerificationKey, proof: Proof) -> bool { - let vk_raw = hex::decode(vk.raw.clone()).unwrap(); - let proof_raw = hex::decode(proof.raw.unwrap()).unwrap(); + fn verify( + vk: >::VerificationKey, + proof: Proof<>::ProofPoints>, + ) -> bool { + let vk_raw = hex::decode(vk.raw.unwrap().clone()).unwrap(); + let proof_raw = hex::decode(proof.raw.unwrap().clone()).unwrap(); let public_inputs: Vec<_> = proof .inputs @@ -265,133 +141,3 @@ impl ProofSystem for GM17 { } } } - -const CONTRACT_TEMPLATE_V2: &str = r#" -contract Verifier { - using Pairing for *; - struct VerifyingKey { - Pairing.G2Point h; - Pairing.G1Point g_alpha; - Pairing.G2Point h_beta; - Pairing.G1Point g_gamma; - Pairing.G2Point h_gamma; - Pairing.G1Point[] query; - } - struct Proof { - Pairing.G1Point a; - Pairing.G2Point b; - Pairing.G1Point c; - } - function verifyingKey() pure internal returns (VerifyingKey memory vk) { - vk.h= Pairing.G2Point(<%vk_h%>); - vk.g_alpha = Pairing.G1Point(<%vk_g_alpha%>); - vk.h_beta = Pairing.G2Point(<%vk_h_beta%>); - vk.g_gamma = Pairing.G1Point(<%vk_g_gamma%>); - vk.h_gamma = Pairing.G2Point(<%vk_h_gamma%>); - vk.query = new Pairing.G1Point[](<%vk_query_length%>); - <%vk_query_pts%> - } - function verify(uint[] memory input, Proof memory proof) internal view returns (uint) { - uint256 snark_scalar_field = 21888242871839275222246405745257275088548364400416034343698204186575808495617; - VerifyingKey memory vk = verifyingKey(); - require(input.length + 1 == vk.query.length); - // Compute the linear combination vk_x - Pairing.G1Point memory vk_x = Pairing.G1Point(0, 0); - for (uint i = 0; i < input.length; i++) { - require(input[i] < snark_scalar_field); - vk_x = Pairing.addition(vk_x, Pairing.scalar_mul(vk.query[i + 1], input[i])); - } - vk_x = Pairing.addition(vk_x, vk.query[0]); - /** - * e(A*G^{alpha}, B*H^{beta}) = e(G^{alpha}, H^{beta}) * e(G^{psi}, H^{gamma}) - * * e(C, H) - * where psi = \sum_{i=0}^l input_i pvk.query[i] - */ - if (!Pairing.pairingProd4(vk.g_alpha, vk.h_beta, vk_x, vk.h_gamma, proof.c, vk.h, Pairing.negate(Pairing.addition(proof.a, vk.g_alpha)), Pairing.addition(proof.b, vk.h_beta))) return 1; - /** - * e(A, H^{gamma}) = e(G^{gamma}, B) - */ - if (!Pairing.pairingProd2(proof.a, vk.h_gamma, Pairing.negate(vk.g_gamma), proof.b)) return 2; - return 0; - } - function verifyTx( - Proof memory proof<%input_argument%> - ) public view returns (bool r) { - uint[] memory inputValues = new uint[](input.length); - <%input_loop%> - if (verify(inputValues, proof) == 0) { - return true; - } else { - return false; - } - } -} -"#; - -const CONTRACT_TEMPLATE: &str = r#" -contract Verifier { - using Pairing for *; - struct VerifyingKey { - Pairing.G2Point h; - Pairing.G1Point g_alpha; - Pairing.G2Point h_beta; - Pairing.G1Point g_gamma; - Pairing.G2Point h_gamma; - Pairing.G1Point[] query; - } - struct Proof { - Pairing.G1Point a; - Pairing.G2Point b; - Pairing.G1Point c; - } - function verifyingKey() pure internal returns (VerifyingKey memory vk) { - vk.h = Pairing.G2Point(<%vk_h%>); - vk.g_alpha = Pairing.G1Point(<%vk_g_alpha%>); - vk.h_beta = Pairing.G2Point(<%vk_h_beta%>); - vk.g_gamma = Pairing.G1Point(<%vk_g_gamma%>); - vk.h_gamma = Pairing.G2Point(<%vk_h_gamma%>); - vk.query = new Pairing.G1Point[](<%vk_query_length%>); - <%vk_query_pts%> - } - function verify(uint[] memory input, Proof memory proof) internal view returns (uint) { - uint256 snark_scalar_field = 21888242871839275222246405745257275088548364400416034343698204186575808495617; - VerifyingKey memory vk = verifyingKey(); - require(input.length + 1 == vk.query.length); - // Compute the linear combination vk_x - Pairing.G1Point memory vk_x = Pairing.G1Point(0, 0); - for (uint i = 0; i < input.length; i++) { - require(input[i] < snark_scalar_field); - vk_x = Pairing.addition(vk_x, Pairing.scalar_mul(vk.query[i + 1], input[i])); - } - vk_x = Pairing.addition(vk_x, vk.query[0]); - /** - * e(A*G^{alpha}, B*H^{beta}) = e(G^{alpha}, H^{beta}) * e(G^{psi}, H^{gamma}) - * * e(C, H) - * where psi = \sum_{i=0}^l input_i pvk.query[i] - */ - if (!Pairing.pairingProd4(vk.g_alpha, vk.h_beta, vk_x, vk.h_gamma, proof.c, vk.h, Pairing.negate(Pairing.addition(proof.a, vk.g_alpha)), Pairing.addition(proof.b, vk.h_beta))) return 1; - /** - * e(A, H^{gamma}) = e(G^{gamma}, b) - */ - if (!Pairing.pairingProd2(proof.a, vk.h_gamma, Pairing.negate(vk.g_gamma), proof.b)) return 2; - return 0; - } - function verifyTx( - uint[2] memory a, - uint[2][2] memory b, - uint[2] memory c<%input_argument%> - ) public view returns (bool r) { - Proof memory proof; - proof.a = Pairing.G1Point(a[0], a[1]); - proof.b = Pairing.G2Point([b[0][0], b[0][1]], [b[1][0], b[1][1]]); - proof.c = Pairing.G1Point(c[0], c[1]); - uint[] memory inputValues = new uint[](input.length); - <%input_loop%> - if (verify(inputValues, proof) == 0) { - return true; - } else { - return false; - } - } -} -"#; diff --git a/zokrates_core/src/proof_system/libsnark/mod.rs b/zokrates_core/src/proof_system/libsnark/mod.rs index 4868ec46c..bc357add9 100644 --- a/zokrates_core/src/proof_system/libsnark/mod.rs +++ b/zokrates_core/src/proof_system/libsnark/mod.rs @@ -8,6 +8,8 @@ use std::cmp::max; use std::collections::HashMap; use zokrates_field::Field; +pub struct Libsnark; + // utility function. Converts a Field's vector-based byte representation to fixed size array. fn vec_as_u8_32_array(vec: &Vec) -> [u8; 32] { assert!(vec.len() <= 32); diff --git a/zokrates_core/src/proof_system/libsnark/pghr13.rs b/zokrates_core/src/proof_system/libsnark/pghr13.rs index e99594a0e..41c16e019 100644 --- a/zokrates_core/src/proof_system/libsnark/pghr13.rs +++ b/zokrates_core/src/proof_system/libsnark/pghr13.rs @@ -1,43 +1,15 @@ -use ir; use proof_system::libsnark::ffi::{Buffer, ProofResult, SetupResult}; -use proof_system::libsnark::{prepare_generate_proof, prepare_public_inputs, prepare_setup}; -use proof_system::solidity::{ - SolidityAbi, SOLIDITY_G2_ADDITION_LIB, SOLIDITY_PAIRING_LIB, SOLIDITY_PAIRING_LIB_V2, +use proof_system::libsnark::{ + prepare_generate_proof, prepare_public_inputs, prepare_setup, Libsnark, }; -use proof_system::{G1Affine, G2Affine, Proof, ProofSystem, SetupKeypair}; -use regex::Regex; +use proof_system::{Backend, Proof, SetupKeypair}; -use zokrates_field::bn128::FieldPrime; +use ir::{Prog, Witness}; +use proof_system::scheme::pghr13::PGHR13; +use proof_system::scheme::Scheme; use zokrates_field::Bn128Field; use zokrates_field::Field; -pub struct PGHR13 {} - -#[derive(Serialize, Deserialize)] -pub struct VerificationKey { - a: G2Affine, - b: G1Affine, - c: G2Affine, - gamma: G2Affine, - gamma_beta_1: G1Affine, - gamma_beta_2: G2Affine, - z: G2Affine, - ic: Vec, - raw: String, -} - -#[derive(Serialize, Deserialize)] -pub struct ProofPoints { - a: G1Affine, - a_p: G1Affine, - b: G2Affine, - b_p: G1Affine, - c: G1Affine, - c_p: G1Affine, - h: G1Affine, - k: G1Affine, -} - extern "C" { fn pghr13_bn128_setup( a: *const u8, @@ -67,11 +39,10 @@ extern "C" { ) -> bool; } -impl ProofSystem for PGHR13 { - type VerificationKey = VerificationKey; - type ProofPoints = ProofPoints; - - fn setup(program: ir::Prog) -> SetupKeypair { +impl Backend for Libsnark { + fn setup( + program: Prog, + ) -> SetupKeypair<>::VerificationKey> { let (a_arr, b_arr, c_arr, a_vec, b_vec, c_vec, num_constraints, num_variables, num_inputs) = prepare_setup(program); @@ -105,25 +76,25 @@ impl ProofSystem for PGHR13 { } fn generate_proof( - program: ir::Prog, - witness: ir::Witness, + program: Prog, + witness: Witness, proving_key: Vec, - ) -> Proof { + ) -> Proof<>::ProofPoints> { let (public_inputs_arr, public_inputs_length, private_inputs_arr, private_inputs_length) = prepare_generate_proof(program, witness); let proof = unsafe { - let mut pk_buf = Buffer::from_vec(&proving_key); + let mut pk_buffer = Buffer::from_vec(&proving_key); let result = pghr13_bn128_generate_proof( - &mut pk_buf as *mut _, + &mut pk_buffer as *mut _, public_inputs_arr[0].as_ptr(), public_inputs_length as i32, private_inputs_arr[0].as_ptr(), private_inputs_length as i32, ); - pk_buf.drop(); // drop the buffer manually + pk_buffer.drop(); // drop the buffer manually let proof: Vec = std::slice::from_raw_parts(result.proof.data, result.proof.length as usize) @@ -138,119 +109,12 @@ impl ProofSystem for PGHR13 { serde_json::from_str(String::from_utf8(proof).unwrap().as_str()).unwrap() } - fn export_solidity_verifier(vk: VerificationKey, abi: SolidityAbi) -> String { - let (mut template_text, solidity_pairing_lib) = match abi { - SolidityAbi::V1 => ( - String::from(CONTRACT_TEMPLATE), - String::from(SOLIDITY_PAIRING_LIB), - ), - SolidityAbi::V2 => ( - String::from(CONTRACT_TEMPLATE_V2), - String::from(SOLIDITY_PAIRING_LIB_V2), - ), - }; - - // replace things in template - let vk_regex = Regex::new(r#"(<%vk_[^i%]*%>)"#).unwrap(); - let vk_ic_len_regex = Regex::new(r#"(<%vk_ic_length%>)"#).unwrap(); - let vk_ic_repeat_regex = Regex::new(r#"(<%vk_ic_pts%>)"#).unwrap(); - let vk_input_len_regex = Regex::new(r#"(<%vk_input_length%>)"#).unwrap(); - let input_loop = Regex::new(r#"(<%input_loop%>)"#).unwrap(); - let input_argument = Regex::new(r#"(<%input_argument%>)"#).unwrap(); - - template_text = vk_regex - .replace(template_text.as_str(), vk.a.to_string().as_str()) - .into_owned(); - - template_text = vk_regex - .replace(template_text.as_str(), vk.b.to_string().as_str()) - .into_owned(); - - template_text = vk_regex - .replace(template_text.as_str(), vk.c.to_string().as_str()) - .into_owned(); - - template_text = vk_regex - .replace(template_text.as_str(), vk.gamma.to_string().as_str()) - .into_owned(); - - template_text = vk_regex - .replace(template_text.as_str(), vk.gamma_beta_1.to_string().as_str()) - .into_owned(); - - template_text = vk_regex - .replace(template_text.as_str(), vk.gamma_beta_2.to_string().as_str()) - .into_owned(); - - template_text = vk_regex - .replace(template_text.as_str(), vk.z.to_string().as_str()) - .into_owned(); - - let ic_count: usize = vk.ic.len(); - template_text = vk_ic_len_regex - .replace(template_text.as_str(), format!("{}", ic_count).as_str()) - .into_owned(); - - template_text = vk_input_len_regex - .replace(template_text.as_str(), format!("{}", ic_count - 1).as_str()) - .into_owned(); - - // feed input values only if there are any - template_text = if ic_count > 1 { - input_loop.replace( - template_text.as_str(), - r#" - for(uint i = 0; i < input.length; i++){ - inputValues[i] = input[i]; - }"#, - ) - } else { - input_loop.replace(template_text.as_str(), "") - } - .to_string(); - - // take input values as argument only if there are any - template_text = if ic_count > 1 { - input_argument.replace( - template_text.as_str(), - format!(", uint[{}] memory input", ic_count - 1).as_str(), - ) - } else { - input_argument.replace(template_text.as_str(), "") - } - .to_string(); - - let mut ic_repeat_text = String::new(); - for (i, g1) in vk.ic.iter().enumerate() { - ic_repeat_text.push_str( - format!( - "vk.ic[{}] = Pairing.G1Point({});", - i, - g1.to_string().as_str() - ) - .as_str(), - ); - if i < ic_count - 1 { - ic_repeat_text.push_str("\n "); - } - } - - template_text = vk_ic_repeat_regex - .replace(template_text.as_str(), ic_repeat_text.as_str()) - .into_owned(); - - let re = Regex::new(r"(?P0[xX][0-9a-fA-F]{64})").unwrap(); - template_text = re.replace_all(&template_text, "uint256($v)").to_string(); - - format!( - "{}{}{}", - SOLIDITY_G2_ADDITION_LIB, solidity_pairing_lib, template_text - ) - } - - fn verify(vk: VerificationKey, proof: Proof) -> bool { - let vk_raw = hex::decode(vk.raw.clone()).unwrap(); - let proof_raw = hex::decode(proof.raw.unwrap()).unwrap(); + fn verify( + vk: >::VerificationKey, + proof: Proof<>::ProofPoints>, + ) -> bool { + let vk_raw = hex::decode(vk.raw.unwrap().clone()).unwrap(); + let proof_raw = hex::decode(proof.raw.unwrap().clone()).unwrap(); let public_inputs: Vec<_> = proof .inputs @@ -278,165 +142,3 @@ impl ProofSystem for PGHR13 { } } } - -const CONTRACT_TEMPLATE_V2: &str = r#"contract Verifier { - using Pairing for *; - struct VerifyingKey { - Pairing.G2Point a; - Pairing.G1Point b; - Pairing.G2Point c; - Pairing.G2Point gamma; - Pairing.G1Point gamma_beta_1; - Pairing.G2Point gamma_beta_2; - Pairing.G2Point z; - Pairing.G1Point[] ic; - } - struct Proof { - Pairing.G1Point a; - Pairing.G1Point a_p; - Pairing.G2Point b; - Pairing.G1Point b_p; - Pairing.G1Point c; - Pairing.G1Point c_p; - Pairing.G1Point k; - Pairing.G1Point h; - } - function verifyingKey() pure internal returns (VerifyingKey memory vk) { - vk.a = Pairing.G2Point(<%vk_a%>); - vk.b = Pairing.G1Point(<%vk_b%>); - vk.c = Pairing.G2Point(<%vk_c%>); - vk.gamma = Pairing.G2Point(<%vk_g%>); - vk.gamma_beta_1 = Pairing.G1Point(<%vk_gb1%>); - vk.gamma_beta_2 = Pairing.G2Point(<%vk_gb2%>); - vk.z = Pairing.G2Point(<%vk_z%>); - vk.ic = new Pairing.G1Point[](<%vk_ic_length%>); - <%vk_ic_pts%> - } - function verify(uint[] memory input, Proof memory proof) internal view returns (uint) { - uint256 snark_scalar_field = 21888242871839275222246405745257275088548364400416034343698204186575808495617; - VerifyingKey memory vk = verifyingKey(); - require(input.length + 1 == vk.ic.length); - // Compute the linear combination vk_x - Pairing.G1Point memory vk_x = Pairing.G1Point(0, 0); - for (uint i = 0; i < input.length; i++) { - require(input[i] < snark_scalar_field); - vk_x = Pairing.addition(vk_x, Pairing.scalar_mul(vk.ic[i + 1], input[i])); - } - vk_x = Pairing.addition(vk_x, vk.ic[0]); - if (!Pairing.pairingProd2(proof.a, vk.a, Pairing.negate(proof.a_p), Pairing.P2())) return 1; - if (!Pairing.pairingProd2(vk.b, proof.b, Pairing.negate(proof.b_p), Pairing.P2())) return 2; - if (!Pairing.pairingProd2(proof.c, vk.c, Pairing.negate(proof.c_p), Pairing.P2())) return 3; - if (!Pairing.pairingProd3( - proof.k, vk.gamma, - Pairing.negate(Pairing.addition(vk_x, Pairing.addition(proof.a, proof.c))), vk.gamma_beta_2, - Pairing.negate(vk.gamma_beta_1), proof.b - )) return 4; - if (!Pairing.pairingProd3( - Pairing.addition(vk_x, proof.a), proof.b, - Pairing.negate(proof.h), vk.z, - Pairing.negate(proof.c), Pairing.P2() - )) return 5; - return 0; - } - function verifyTx( - Proof memory proof<%input_argument%> - ) public view returns (bool r) { - uint[] memory inputValues = new uint[](input.length); - <%input_loop%> - if (verify(inputValues, proof) == 0) { - return true; - } else { - return false; - } - } -} -"#; - -const CONTRACT_TEMPLATE: &str = r#"contract Verifier { - using Pairing for *; - struct VerifyingKey { - Pairing.G2Point a; - Pairing.G1Point b; - Pairing.G2Point c; - Pairing.G2Point gamma; - Pairing.G1Point gamma_beta_1; - Pairing.G2Point gamma_beta_2; - Pairing.G2Point z; - Pairing.G1Point[] ic; - } - struct Proof { - Pairing.G1Point a; - Pairing.G1Point a_p; - Pairing.G2Point b; - Pairing.G1Point b_p; - Pairing.G1Point c; - Pairing.G1Point c_p; - Pairing.G1Point k; - Pairing.G1Point h; - } - function verifyingKey() pure internal returns (VerifyingKey memory vk) { - vk.a = Pairing.G2Point(<%vk_a%>); - vk.b = Pairing.G1Point(<%vk_b%>); - vk.c = Pairing.G2Point(<%vk_c%>); - vk.gamma = Pairing.G2Point(<%vk_g%>); - vk.gamma_beta_1 = Pairing.G1Point(<%vk_gb1%>); - vk.gamma_beta_2 = Pairing.G2Point(<%vk_gb2%>); - vk.z = Pairing.G2Point(<%vk_z%>); - vk.ic = new Pairing.G1Point[](<%vk_ic_length%>); - <%vk_ic_pts%> - } - function verify(uint[] memory input, Proof memory proof) internal view returns (uint) { - uint256 snark_scalar_field = 21888242871839275222246405745257275088548364400416034343698204186575808495617; - VerifyingKey memory vk = verifyingKey(); - require(input.length + 1 == vk.ic.length); - // Compute the linear combination vk_x - Pairing.G1Point memory vk_x = Pairing.G1Point(0, 0); - for (uint i = 0; i < input.length; i++) { - require(input[i] < snark_scalar_field); - vk_x = Pairing.addition(vk_x, Pairing.scalar_mul(vk.ic[i + 1], input[i])); - } - vk_x = Pairing.addition(vk_x, vk.ic[0]); - if (!Pairing.pairingProd2(proof.a, vk.a, Pairing.negate(proof.a_p), Pairing.P2())) return 1; - if (!Pairing.pairingProd2(vk.b, proof.b, Pairing.negate(proof.b_p), Pairing.P2())) return 2; - if (!Pairing.pairingProd2(proof.c, vk.c, Pairing.negate(proof.c_p), Pairing.P2())) return 3; - if (!Pairing.pairingProd3( - proof.k, vk.gamma, - Pairing.negate(Pairing.addition(vk_x, Pairing.addition(proof.a, proof.c))), vk.gamma_beta_2, - Pairing.negate(vk.gamma_beta_1), proof.b - )) return 4; - if (!Pairing.pairingProd3( - Pairing.addition(vk_x, proof.a), proof.b, - Pairing.negate(proof.h), vk.z, - Pairing.negate(proof.c), Pairing.P2() - )) return 5; - return 0; - } - function verifyTx( - uint[2] memory a, - uint[2] memory a_p, - uint[2][2] memory b, - uint[2] memory b_p, - uint[2] memory c, - uint[2] memory c_p, - uint[2] memory h, - uint[2] memory k<%input_argument%> - ) public view returns (bool r) { - Proof memory proof; - proof.a = Pairing.G1Point(a[0], a[1]); - proof.a_p = Pairing.G1Point(a_p[0], a_p[1]); - proof.b = Pairing.G2Point([b[0][0], b[0][1]], [b[1][0], b[1][1]]); - proof.b_p = Pairing.G1Point(b_p[0], b_p[1]); - proof.c = Pairing.G1Point(c[0], c[1]); - proof.c_p = Pairing.G1Point(c_p[0], c_p[1]); - proof.h = Pairing.G1Point(h[0], h[1]); - proof.k = Pairing.G1Point(k[0], k[1]); - uint[] memory inputValues = new uint[](input.length); - <%input_loop%> - if (verify(inputValues, proof) == 0) { - return true; - } else { - return false; - } - } -} -"#; diff --git a/zokrates_core/src/proof_system/mod.rs b/zokrates_core/src/proof_system/mod.rs index 72ee05b4f..79ab82cd3 100644 --- a/zokrates_core/src/proof_system/mod.rs +++ b/zokrates_core/src/proof_system/mod.rs @@ -3,10 +3,11 @@ pub mod bellman; pub mod libsnark; pub mod zexe; +pub mod scheme; pub mod solidity; use crate::ir; -use proof_system::solidity::SolidityAbi; +use proof_system::scheme::Scheme; use serde::de::DeserializeOwned; use serde::Serialize; use zokrates_field::Field; @@ -74,23 +75,14 @@ impl ToString for G2Affine { } } -pub trait ProofSystem -where - Self::VerificationKey: Serialize + DeserializeOwned, - Self::ProofPoints: Serialize + DeserializeOwned, -{ - type VerificationKey; - type ProofPoints; - - fn setup(program: ir::Prog) -> SetupKeypair; +pub trait Backend> { + fn setup(program: ir::Prog) -> SetupKeypair; fn generate_proof( program: ir::Prog, witness: ir::Witness, proving_key: Vec, - ) -> Proof; - - fn export_solidity_verifier(vk: Self::VerificationKey, abi: SolidityAbi) -> String; + ) -> Proof; - fn verify(vk: Self::VerificationKey, proof: Proof) -> bool; + fn verify(vk: S::VerificationKey, proof: Proof) -> bool; } diff --git a/zokrates_core/src/proof_system/scheme/gm17.rs b/zokrates_core/src/proof_system/scheme/gm17.rs new file mode 100644 index 000000000..1a9b857a9 --- /dev/null +++ b/zokrates_core/src/proof_system/scheme/gm17.rs @@ -0,0 +1,282 @@ +use proof_system::scheme::{Scheme, SolidityCompatibleScheme}; +use proof_system::solidity::{ + SolidityAbi, SOLIDITY_G2_ADDITION_LIB, SOLIDITY_PAIRING_LIB, SOLIDITY_PAIRING_LIB_V2, +}; +use proof_system::{G1Affine, G2Affine, G2AffineFq}; +use regex::Regex; +use zokrates_field::{Bls12_377Field, Bls12_381Field, Bn128Field, Bw6_761Field, Field}; + +pub trait NotBw6_761Field {} +impl NotBw6_761Field for Bls12_377Field {} +impl NotBw6_761Field for Bls12_381Field {} +impl NotBw6_761Field for Bn128Field {} + +pub struct GM17; + +#[derive(Serialize, Deserialize)] +pub struct ProofPoints { + pub a: G1, + pub b: G2, + pub c: G1, +} + +#[derive(Serialize, Deserialize)] +pub struct VerificationKey { + pub h: G2, + pub g_alpha: G1, + pub h_beta: G2, + pub g_gamma: G1, + pub h_gamma: G2, + pub query: Vec, + pub raw: Option, +} + +impl Scheme for GM17 { + type VerificationKey = VerificationKey; + type ProofPoints = ProofPoints; +} + +impl Scheme for GM17 { + type VerificationKey = VerificationKey; + type ProofPoints = ProofPoints; +} + +impl SolidityCompatibleScheme for GM17 { + fn export_solidity_verifier( + vk: >::VerificationKey, + abi: SolidityAbi, + ) -> String { + let (mut template_text, solidity_pairing_lib) = match abi { + SolidityAbi::V1 => ( + String::from(CONTRACT_TEMPLATE), + String::from(SOLIDITY_PAIRING_LIB), + ), + SolidityAbi::V2 => ( + String::from(CONTRACT_TEMPLATE_V2), + String::from(SOLIDITY_PAIRING_LIB_V2), + ), + }; + + // replace things in template + let vk_regex = Regex::new(r#"(<%vk_[^i%]*%>)"#).unwrap(); + let vk_query_len_regex = Regex::new(r#"(<%vk_query_length%>)"#).unwrap(); + let vk_query_repeat_regex = Regex::new(r#"(<%vk_query_pts%>)"#).unwrap(); + let vk_input_len_regex = Regex::new(r#"(<%vk_input_length%>)"#).unwrap(); + let input_loop = Regex::new(r#"(<%input_loop%>)"#).unwrap(); + let input_argument = Regex::new(r#"(<%input_argument%>)"#).unwrap(); + + template_text = vk_regex + .replace(template_text.as_str(), vk.h.to_string().as_str()) + .into_owned(); + + template_text = vk_regex + .replace(template_text.as_str(), vk.g_alpha.to_string().as_str()) + .into_owned(); + + template_text = vk_regex + .replace(template_text.as_str(), vk.h_beta.to_string().as_str()) + .into_owned(); + + template_text = vk_regex + .replace(template_text.as_str(), vk.g_gamma.to_string().as_str()) + .into_owned(); + + template_text = vk_regex + .replace(template_text.as_str(), vk.h_gamma.to_string().as_str()) + .into_owned(); + + let query_count: usize = vk.query.len(); + template_text = vk_query_len_regex + .replace(template_text.as_str(), format!("{}", query_count).as_str()) + .into_owned(); + + template_text = vk_input_len_regex + .replace( + template_text.as_str(), + format!("{}", query_count - 1).as_str(), + ) + .into_owned(); + + // feed input values only if there are any + template_text = if query_count > 1 { + input_loop.replace( + template_text.as_str(), + r#" + for(uint i = 0; i < input.length; i++){ + inputValues[i] = input[i]; + }"#, + ) + } else { + input_loop.replace(template_text.as_str(), "") + } + .to_string(); + + // take input values as argument only if there are any + template_text = if query_count > 1 { + input_argument.replace( + template_text.as_str(), + format!(", uint[{}] memory input", query_count - 1).as_str(), + ) + } else { + input_argument.replace(template_text.as_str(), "") + } + .to_string(); + + let mut query_repeat_text = String::new(); + for (i, g1) in vk.query.iter().enumerate() { + query_repeat_text.push_str( + format!( + "vk.query[{}] = Pairing.G1Point({});", + i, + g1.to_string().as_str() + ) + .as_str(), + ); + if i < query_count - 1 { + query_repeat_text.push_str("\n "); + } + } + + template_text = vk_query_repeat_regex + .replace(template_text.as_str(), query_repeat_text.as_str()) + .into_owned(); + + let re = Regex::new(r"(?P0[xX][0-9a-fA-F]{64})").unwrap(); + template_text = re.replace_all(&template_text, "uint256($v)").to_string(); + + format!( + "{}{}{}", + SOLIDITY_G2_ADDITION_LIB, solidity_pairing_lib, template_text + ) + } +} + +const CONTRACT_TEMPLATE_V2: &str = r#" +contract Verifier { + using Pairing for *; + struct VerifyingKey { + Pairing.G2Point h; + Pairing.G1Point g_alpha; + Pairing.G2Point h_beta; + Pairing.G1Point g_gamma; + Pairing.G2Point h_gamma; + Pairing.G1Point[] query; + } + struct Proof { + Pairing.G1Point a; + Pairing.G2Point b; + Pairing.G1Point c; + } + function verifyingKey() pure internal returns (VerifyingKey memory vk) { + vk.h= Pairing.G2Point(<%vk_h%>); + vk.g_alpha = Pairing.G1Point(<%vk_g_alpha%>); + vk.h_beta = Pairing.G2Point(<%vk_h_beta%>); + vk.g_gamma = Pairing.G1Point(<%vk_g_gamma%>); + vk.h_gamma = Pairing.G2Point(<%vk_h_gamma%>); + vk.query = new Pairing.G1Point[](<%vk_query_length%>); + <%vk_query_pts%> + } + function verify(uint[] memory input, Proof memory proof) internal view returns (uint) { + uint256 snark_scalar_field = 21888242871839275222246405745257275088548364400416034343698204186575808495617; + VerifyingKey memory vk = verifyingKey(); + require(input.length + 1 == vk.query.length); + // Compute the linear combination vk_x + Pairing.G1Point memory vk_x = Pairing.G1Point(0, 0); + for (uint i = 0; i < input.length; i++) { + require(input[i] < snark_scalar_field); + vk_x = Pairing.addition(vk_x, Pairing.scalar_mul(vk.query[i + 1], input[i])); + } + vk_x = Pairing.addition(vk_x, vk.query[0]); + /** + * e(A*G^{alpha}, B*H^{beta}) = e(G^{alpha}, H^{beta}) * e(G^{psi}, H^{gamma}) + * * e(C, H) + * where psi = \sum_{i=0}^l input_i pvk.query[i] + */ + if (!Pairing.pairingProd4(vk.g_alpha, vk.h_beta, vk_x, vk.h_gamma, proof.c, vk.h, Pairing.negate(Pairing.addition(proof.a, vk.g_alpha)), Pairing.addition(proof.b, vk.h_beta))) return 1; + /** + * e(A, H^{gamma}) = e(G^{gamma}, B) + */ + if (!Pairing.pairingProd2(proof.a, vk.h_gamma, Pairing.negate(vk.g_gamma), proof.b)) return 2; + return 0; + } + function verifyTx( + Proof memory proof<%input_argument%> + ) public view returns (bool r) { + uint[] memory inputValues = new uint[](input.length); + <%input_loop%> + if (verify(inputValues, proof) == 0) { + return true; + } else { + return false; + } + } +} +"#; + +const CONTRACT_TEMPLATE: &str = r#" +contract Verifier { + using Pairing for *; + struct VerifyingKey { + Pairing.G2Point h; + Pairing.G1Point g_alpha; + Pairing.G2Point h_beta; + Pairing.G1Point g_gamma; + Pairing.G2Point h_gamma; + Pairing.G1Point[] query; + } + struct Proof { + Pairing.G1Point a; + Pairing.G2Point b; + Pairing.G1Point c; + } + function verifyingKey() pure internal returns (VerifyingKey memory vk) { + vk.h = Pairing.G2Point(<%vk_h%>); + vk.g_alpha = Pairing.G1Point(<%vk_g_alpha%>); + vk.h_beta = Pairing.G2Point(<%vk_h_beta%>); + vk.g_gamma = Pairing.G1Point(<%vk_g_gamma%>); + vk.h_gamma = Pairing.G2Point(<%vk_h_gamma%>); + vk.query = new Pairing.G1Point[](<%vk_query_length%>); + <%vk_query_pts%> + } + function verify(uint[] memory input, Proof memory proof) internal view returns (uint) { + uint256 snark_scalar_field = 21888242871839275222246405745257275088548364400416034343698204186575808495617; + VerifyingKey memory vk = verifyingKey(); + require(input.length + 1 == vk.query.length); + // Compute the linear combination vk_x + Pairing.G1Point memory vk_x = Pairing.G1Point(0, 0); + for (uint i = 0; i < input.length; i++) { + require(input[i] < snark_scalar_field); + vk_x = Pairing.addition(vk_x, Pairing.scalar_mul(vk.query[i + 1], input[i])); + } + vk_x = Pairing.addition(vk_x, vk.query[0]); + /** + * e(A*G^{alpha}, B*H^{beta}) = e(G^{alpha}, H^{beta}) * e(G^{psi}, H^{gamma}) + * * e(C, H) + * where psi = \sum_{i=0}^l input_i pvk.query[i] + */ + if (!Pairing.pairingProd4(vk.g_alpha, vk.h_beta, vk_x, vk.h_gamma, proof.c, vk.h, Pairing.negate(Pairing.addition(proof.a, vk.g_alpha)), Pairing.addition(proof.b, vk.h_beta))) return 1; + /** + * e(A, H^{gamma}) = e(G^{gamma}, b) + */ + if (!Pairing.pairingProd2(proof.a, vk.h_gamma, Pairing.negate(vk.g_gamma), proof.b)) return 2; + return 0; + } + function verifyTx( + uint[2] memory a, + uint[2][2] memory b, + uint[2] memory c<%input_argument%> + ) public view returns (bool r) { + Proof memory proof; + proof.a = Pairing.G1Point(a[0], a[1]); + proof.b = Pairing.G2Point([b[0][0], b[0][1]], [b[1][0], b[1][1]]); + proof.c = Pairing.G1Point(c[0], c[1]); + uint[] memory inputValues = new uint[](input.length); + <%input_loop%> + if (verify(inputValues, proof) == 0) { + return true; + } else { + return false; + } + } +} +"#; diff --git a/zokrates_core/src/proof_system/scheme/groth16.rs b/zokrates_core/src/proof_system/scheme/groth16.rs new file mode 100644 index 000000000..f018a5fdb --- /dev/null +++ b/zokrates_core/src/proof_system/scheme/groth16.rs @@ -0,0 +1,254 @@ +use proof_system::scheme::{Scheme, SolidityCompatibleScheme}; +use proof_system::solidity::{ + SolidityAbi, SOLIDITY_G2_ADDITION_LIB, SOLIDITY_PAIRING_LIB, SOLIDITY_PAIRING_LIB_V2, +}; +use proof_system::{G1Affine, G2Affine}; +use regex::Regex; +use zokrates_field::Field; + +pub struct G16; + +#[derive(Serialize, Deserialize)] +pub struct ProofPoints { + pub a: G1, + pub b: G2, + pub c: G1, +} + +#[derive(Serialize, Deserialize)] +pub struct VerificationKey { + pub alpha: G1, + pub beta: G2, + pub gamma: G2, + pub delta: G2, + pub gamma_abc: Vec, +} + +impl Scheme for G16 { + type VerificationKey = VerificationKey; + type ProofPoints = ProofPoints; +} + +impl SolidityCompatibleScheme for G16 { + fn export_solidity_verifier( + vk: >::VerificationKey, + abi: SolidityAbi, + ) -> String { + let (mut template_text, solidity_pairing_lib) = match abi { + SolidityAbi::V1 => ( + String::from(CONTRACT_TEMPLATE), + String::from(SOLIDITY_PAIRING_LIB), + ), + SolidityAbi::V2 => ( + String::from(CONTRACT_TEMPLATE_V2), + String::from(SOLIDITY_PAIRING_LIB_V2), + ), + }; + + let vk_regex = Regex::new(r#"(<%vk_[^i%]*%>)"#).unwrap(); + let vk_gamma_abc_len_regex = Regex::new(r#"(<%vk_gamma_abc_length%>)"#).unwrap(); + let vk_gamma_abc_repeat_regex = Regex::new(r#"(<%vk_gamma_abc_pts%>)"#).unwrap(); + let vk_input_len_regex = Regex::new(r#"(<%vk_input_length%>)"#).unwrap(); + let input_loop = Regex::new(r#"(<%input_loop%>)"#).unwrap(); + let input_argument = Regex::new(r#"(<%input_argument%>)"#).unwrap(); + + template_text = vk_regex + .replace(template_text.as_str(), vk.alpha.to_string().as_str()) + .into_owned(); + + template_text = vk_regex + .replace(template_text.as_str(), vk.beta.to_string().as_str()) + .into_owned(); + + template_text = vk_regex + .replace(template_text.as_str(), vk.gamma.to_string().as_str()) + .into_owned(); + + template_text = vk_regex + .replace(template_text.as_str(), vk.delta.to_string().as_str()) + .into_owned(); + + let gamma_abc_count: usize = vk.gamma_abc.len(); + template_text = vk_gamma_abc_len_regex + .replace( + template_text.as_str(), + format!("{}", gamma_abc_count).as_str(), + ) + .into_owned(); + + template_text = vk_input_len_regex + .replace( + template_text.as_str(), + format!("{}", gamma_abc_count - 1).as_str(), + ) + .into_owned(); + + // feed input values only if there are any + template_text = if gamma_abc_count > 1 { + input_loop.replace( + template_text.as_str(), + r#" + for(uint i = 0; i < input.length; i++){ + inputValues[i] = input[i]; + }"#, + ) + } else { + input_loop.replace(template_text.as_str(), "") + } + .to_string(); + + // take input values as argument only if there are any + template_text = if gamma_abc_count > 1 { + input_argument.replace( + template_text.as_str(), + format!(", uint[{}] memory input", gamma_abc_count - 1).as_str(), + ) + } else { + input_argument.replace(template_text.as_str(), "") + } + .to_string(); + + let mut gamma_abc_repeat_text = String::new(); + for (i, g1) in vk.gamma_abc.iter().enumerate() { + gamma_abc_repeat_text.push_str( + format!( + "vk.gamma_abc[{}] = Pairing.G1Point({});", + i, + g1.to_string().as_str() + ) + .as_str(), + ); + if i < gamma_abc_count - 1 { + gamma_abc_repeat_text.push_str("\n "); + } + } + + template_text = vk_gamma_abc_repeat_regex + .replace(template_text.as_str(), gamma_abc_repeat_text.as_str()) + .into_owned(); + + let re = Regex::new(r"(?P0[xX][0-9a-fA-F]{64})").unwrap(); + template_text = re.replace_all(&template_text, "uint256($v)").to_string(); + + format!( + "{}{}{}", + SOLIDITY_G2_ADDITION_LIB, solidity_pairing_lib, template_text + ) + } +} + +const CONTRACT_TEMPLATE_V2: &str = r#" +contract Verifier { + using Pairing for *; + struct VerifyingKey { + Pairing.G1Point alpha; + Pairing.G2Point beta; + Pairing.G2Point gamma; + Pairing.G2Point delta; + Pairing.G1Point[] gamma_abc; + } + struct Proof { + Pairing.G1Point a; + Pairing.G2Point b; + Pairing.G1Point c; + } + function verifyingKey() pure internal returns (VerifyingKey memory vk) { + vk.alpha = Pairing.G1Point(<%vk_alpha%>); + vk.beta = Pairing.G2Point(<%vk_beta%>); + vk.gamma = Pairing.G2Point(<%vk_gamma%>); + vk.delta = Pairing.G2Point(<%vk_delta%>); + vk.gamma_abc = new Pairing.G1Point[](<%vk_gamma_abc_length%>); + <%vk_gamma_abc_pts%> + } + function verify(uint[] memory input, Proof memory proof) internal view returns (uint) { + uint256 snark_scalar_field = 21888242871839275222246405745257275088548364400416034343698204186575808495617; + VerifyingKey memory vk = verifyingKey(); + require(input.length + 1 == vk.gamma_abc.length); + // Compute the linear combination vk_x + Pairing.G1Point memory vk_x = Pairing.G1Point(0, 0); + for (uint i = 0; i < input.length; i++) { + require(input[i] < snark_scalar_field); + vk_x = Pairing.addition(vk_x, Pairing.scalar_mul(vk.gamma_abc[i + 1], input[i])); + } + vk_x = Pairing.addition(vk_x, vk.gamma_abc[0]); + if(!Pairing.pairingProd4( + proof.a, proof.b, + Pairing.negate(vk_x), vk.gamma, + Pairing.negate(proof.c), vk.delta, + Pairing.negate(vk.alpha), vk.beta)) return 1; + return 0; + } + function verifyTx( + Proof memory proof<%input_argument%> + ) public view returns (bool r) { + uint[] memory inputValues = new uint[](input.length); + <%input_loop%> + if (verify(inputValues, proof) == 0) { + return true; + } else { + return false; + } + } +} +"#; + +const CONTRACT_TEMPLATE: &str = r#" +contract Verifier { + using Pairing for *; + struct VerifyingKey { + Pairing.G1Point alpha; + Pairing.G2Point beta; + Pairing.G2Point gamma; + Pairing.G2Point delta; + Pairing.G1Point[] gamma_abc; + } + struct Proof { + Pairing.G1Point a; + Pairing.G2Point b; + Pairing.G1Point c; + } + function verifyingKey() pure internal returns (VerifyingKey memory vk) { + vk.alpha = Pairing.G1Point(<%vk_alpha%>); + vk.beta = Pairing.G2Point(<%vk_beta%>); + vk.gamma = Pairing.G2Point(<%vk_gamma%>); + vk.delta = Pairing.G2Point(<%vk_delta%>); + vk.gamma_abc = new Pairing.G1Point[](<%vk_gamma_abc_length%>); + <%vk_gamma_abc_pts%> + } + function verify(uint[] memory input, Proof memory proof) internal view returns (uint) { + uint256 snark_scalar_field = 21888242871839275222246405745257275088548364400416034343698204186575808495617; + VerifyingKey memory vk = verifyingKey(); + require(input.length + 1 == vk.gamma_abc.length); + // Compute the linear combination vk_x + Pairing.G1Point memory vk_x = Pairing.G1Point(0, 0); + for (uint i = 0; i < input.length; i++) { + require(input[i] < snark_scalar_field); + vk_x = Pairing.addition(vk_x, Pairing.scalar_mul(vk.gamma_abc[i + 1], input[i])); + } + vk_x = Pairing.addition(vk_x, vk.gamma_abc[0]); + if(!Pairing.pairingProd4( + proof.a, proof.b, + Pairing.negate(vk_x), vk.gamma, + Pairing.negate(proof.c), vk.delta, + Pairing.negate(vk.alpha), vk.beta)) return 1; + return 0; + } + function verifyTx( + uint[2] memory a, + uint[2][2] memory b, + uint[2] memory c<%input_argument%> + ) public view returns (bool r) { + Proof memory proof; + proof.a = Pairing.G1Point(a[0], a[1]); + proof.b = Pairing.G2Point([b[0][0], b[0][1]], [b[1][0], b[1][1]]); + proof.c = Pairing.G1Point(c[0], c[1]); + uint[] memory inputValues = new uint[](<%vk_input_length%>); + <%input_loop%> + if (verify(inputValues, proof) == 0) { + return true; + } else { + return false; + } + } +} +"#; diff --git a/zokrates_core/src/proof_system/scheme/mod.rs b/zokrates_core/src/proof_system/scheme/mod.rs new file mode 100644 index 000000000..93c03afb1 --- /dev/null +++ b/zokrates_core/src/proof_system/scheme/mod.rs @@ -0,0 +1,17 @@ +use proof_system::solidity::SolidityAbi; +use serde::de::DeserializeOwned; +use serde::Serialize; +use zokrates_field::Field; + +pub mod gm17; +pub mod groth16; +pub mod pghr13; + +pub trait Scheme { + type VerificationKey: Serialize + DeserializeOwned; + type ProofPoints: Serialize + DeserializeOwned; +} + +pub trait SolidityCompatibleScheme: Scheme { + fn export_solidity_verifier(vk: Self::VerificationKey, abi: SolidityAbi) -> String; +} diff --git a/zokrates_core/src/proof_system/scheme/pghr13.rs b/zokrates_core/src/proof_system/scheme/pghr13.rs new file mode 100644 index 000000000..28e3144d4 --- /dev/null +++ b/zokrates_core/src/proof_system/scheme/pghr13.rs @@ -0,0 +1,316 @@ +use proof_system::scheme::{Scheme, SolidityCompatibleScheme}; +use proof_system::solidity::{ + SolidityAbi, SOLIDITY_G2_ADDITION_LIB, SOLIDITY_PAIRING_LIB, SOLIDITY_PAIRING_LIB_V2, +}; +use proof_system::{G1Affine, G2Affine}; +use regex::Regex; +use zokrates_field::Field; + +pub struct PGHR13; + +#[derive(Serialize, Deserialize)] +pub struct ProofPoints { + pub a: G1, + pub a_p: G1, + pub b: G2, + pub b_p: G1, + pub c: G1, + pub c_p: G1, + pub h: G1, + pub k: G1, +} + +#[derive(Serialize, Deserialize)] +pub struct VerificationKey { + pub a: G2, + pub b: G1, + pub c: G2, + pub gamma: G2, + pub gamma_beta_1: G1, + pub gamma_beta_2: G2, + pub z: G2, + pub ic: Vec, + pub raw: Option, +} + +impl Scheme for PGHR13 { + type VerificationKey = VerificationKey; + type ProofPoints = ProofPoints; +} + +impl SolidityCompatibleScheme for PGHR13 { + fn export_solidity_verifier( + vk: >::VerificationKey, + abi: SolidityAbi, + ) -> String { + let (mut template_text, solidity_pairing_lib) = match abi { + SolidityAbi::V1 => ( + String::from(CONTRACT_TEMPLATE), + String::from(SOLIDITY_PAIRING_LIB), + ), + SolidityAbi::V2 => ( + String::from(CONTRACT_TEMPLATE_V2), + String::from(SOLIDITY_PAIRING_LIB_V2), + ), + }; + + // replace things in template + let vk_regex = Regex::new(r#"(<%vk_[^i%]*%>)"#).unwrap(); + let vk_ic_len_regex = Regex::new(r#"(<%vk_ic_length%>)"#).unwrap(); + let vk_ic_repeat_regex = Regex::new(r#"(<%vk_ic_pts%>)"#).unwrap(); + let vk_input_len_regex = Regex::new(r#"(<%vk_input_length%>)"#).unwrap(); + let input_loop = Regex::new(r#"(<%input_loop%>)"#).unwrap(); + let input_argument = Regex::new(r#"(<%input_argument%>)"#).unwrap(); + + template_text = vk_regex + .replace(template_text.as_str(), vk.a.to_string().as_str()) + .into_owned(); + + template_text = vk_regex + .replace(template_text.as_str(), vk.b.to_string().as_str()) + .into_owned(); + + template_text = vk_regex + .replace(template_text.as_str(), vk.c.to_string().as_str()) + .into_owned(); + + template_text = vk_regex + .replace(template_text.as_str(), vk.gamma.to_string().as_str()) + .into_owned(); + + template_text = vk_regex + .replace(template_text.as_str(), vk.gamma_beta_1.to_string().as_str()) + .into_owned(); + + template_text = vk_regex + .replace(template_text.as_str(), vk.gamma_beta_2.to_string().as_str()) + .into_owned(); + + template_text = vk_regex + .replace(template_text.as_str(), vk.z.to_string().as_str()) + .into_owned(); + + let ic_count: usize = vk.ic.len(); + template_text = vk_ic_len_regex + .replace(template_text.as_str(), format!("{}", ic_count).as_str()) + .into_owned(); + + template_text = vk_input_len_regex + .replace(template_text.as_str(), format!("{}", ic_count - 1).as_str()) + .into_owned(); + + // feed input values only if there are any + template_text = if ic_count > 1 { + input_loop.replace( + template_text.as_str(), + r#" + for(uint i = 0; i < input.length; i++){ + inputValues[i] = input[i]; + }"#, + ) + } else { + input_loop.replace(template_text.as_str(), "") + } + .to_string(); + + // take input values as argument only if there are any + template_text = if ic_count > 1 { + input_argument.replace( + template_text.as_str(), + format!(", uint[{}] memory input", ic_count - 1).as_str(), + ) + } else { + input_argument.replace(template_text.as_str(), "") + } + .to_string(); + + let mut ic_repeat_text = String::new(); + for (i, g1) in vk.ic.iter().enumerate() { + ic_repeat_text.push_str( + format!( + "vk.ic[{}] = Pairing.G1Point({});", + i, + g1.to_string().as_str() + ) + .as_str(), + ); + if i < ic_count - 1 { + ic_repeat_text.push_str("\n "); + } + } + + template_text = vk_ic_repeat_regex + .replace(template_text.as_str(), ic_repeat_text.as_str()) + .into_owned(); + + let re = Regex::new(r"(?P0[xX][0-9a-fA-F]{64})").unwrap(); + template_text = re.replace_all(&template_text, "uint256($v)").to_string(); + + format!( + "{}{}{}", + SOLIDITY_G2_ADDITION_LIB, solidity_pairing_lib, template_text + ) + } +} + +const CONTRACT_TEMPLATE_V2: &str = r#"contract Verifier { + using Pairing for *; + struct VerifyingKey { + Pairing.G2Point a; + Pairing.G1Point b; + Pairing.G2Point c; + Pairing.G2Point gamma; + Pairing.G1Point gamma_beta_1; + Pairing.G2Point gamma_beta_2; + Pairing.G2Point z; + Pairing.G1Point[] ic; + } + struct Proof { + Pairing.G1Point a; + Pairing.G1Point a_p; + Pairing.G2Point b; + Pairing.G1Point b_p; + Pairing.G1Point c; + Pairing.G1Point c_p; + Pairing.G1Point k; + Pairing.G1Point h; + } + function verifyingKey() pure internal returns (VerifyingKey memory vk) { + vk.a = Pairing.G2Point(<%vk_a%>); + vk.b = Pairing.G1Point(<%vk_b%>); + vk.c = Pairing.G2Point(<%vk_c%>); + vk.gamma = Pairing.G2Point(<%vk_g%>); + vk.gamma_beta_1 = Pairing.G1Point(<%vk_gb1%>); + vk.gamma_beta_2 = Pairing.G2Point(<%vk_gb2%>); + vk.z = Pairing.G2Point(<%vk_z%>); + vk.ic = new Pairing.G1Point[](<%vk_ic_length%>); + <%vk_ic_pts%> + } + function verify(uint[] memory input, Proof memory proof) internal view returns (uint) { + uint256 snark_scalar_field = 21888242871839275222246405745257275088548364400416034343698204186575808495617; + VerifyingKey memory vk = verifyingKey(); + require(input.length + 1 == vk.ic.length); + // Compute the linear combination vk_x + Pairing.G1Point memory vk_x = Pairing.G1Point(0, 0); + for (uint i = 0; i < input.length; i++) { + require(input[i] < snark_scalar_field); + vk_x = Pairing.addition(vk_x, Pairing.scalar_mul(vk.ic[i + 1], input[i])); + } + vk_x = Pairing.addition(vk_x, vk.ic[0]); + if (!Pairing.pairingProd2(proof.a, vk.a, Pairing.negate(proof.a_p), Pairing.P2())) return 1; + if (!Pairing.pairingProd2(vk.b, proof.b, Pairing.negate(proof.b_p), Pairing.P2())) return 2; + if (!Pairing.pairingProd2(proof.c, vk.c, Pairing.negate(proof.c_p), Pairing.P2())) return 3; + if (!Pairing.pairingProd3( + proof.k, vk.gamma, + Pairing.negate(Pairing.addition(vk_x, Pairing.addition(proof.a, proof.c))), vk.gamma_beta_2, + Pairing.negate(vk.gamma_beta_1), proof.b + )) return 4; + if (!Pairing.pairingProd3( + Pairing.addition(vk_x, proof.a), proof.b, + Pairing.negate(proof.h), vk.z, + Pairing.negate(proof.c), Pairing.P2() + )) return 5; + return 0; + } + function verifyTx( + Proof memory proof<%input_argument%> + ) public view returns (bool r) { + uint[] memory inputValues = new uint[](input.length); + <%input_loop%> + if (verify(inputValues, proof) == 0) { + return true; + } else { + return false; + } + } +} +"#; + +const CONTRACT_TEMPLATE: &str = r#"contract Verifier { + using Pairing for *; + struct VerifyingKey { + Pairing.G2Point a; + Pairing.G1Point b; + Pairing.G2Point c; + Pairing.G2Point gamma; + Pairing.G1Point gamma_beta_1; + Pairing.G2Point gamma_beta_2; + Pairing.G2Point z; + Pairing.G1Point[] ic; + } + struct Proof { + Pairing.G1Point a; + Pairing.G1Point a_p; + Pairing.G2Point b; + Pairing.G1Point b_p; + Pairing.G1Point c; + Pairing.G1Point c_p; + Pairing.G1Point k; + Pairing.G1Point h; + } + function verifyingKey() pure internal returns (VerifyingKey memory vk) { + vk.a = Pairing.G2Point(<%vk_a%>); + vk.b = Pairing.G1Point(<%vk_b%>); + vk.c = Pairing.G2Point(<%vk_c%>); + vk.gamma = Pairing.G2Point(<%vk_g%>); + vk.gamma_beta_1 = Pairing.G1Point(<%vk_gb1%>); + vk.gamma_beta_2 = Pairing.G2Point(<%vk_gb2%>); + vk.z = Pairing.G2Point(<%vk_z%>); + vk.ic = new Pairing.G1Point[](<%vk_ic_length%>); + <%vk_ic_pts%> + } + function verify(uint[] memory input, Proof memory proof) internal view returns (uint) { + uint256 snark_scalar_field = 21888242871839275222246405745257275088548364400416034343698204186575808495617; + VerifyingKey memory vk = verifyingKey(); + require(input.length + 1 == vk.ic.length); + // Compute the linear combination vk_x + Pairing.G1Point memory vk_x = Pairing.G1Point(0, 0); + for (uint i = 0; i < input.length; i++) { + require(input[i] < snark_scalar_field); + vk_x = Pairing.addition(vk_x, Pairing.scalar_mul(vk.ic[i + 1], input[i])); + } + vk_x = Pairing.addition(vk_x, vk.ic[0]); + if (!Pairing.pairingProd2(proof.a, vk.a, Pairing.negate(proof.a_p), Pairing.P2())) return 1; + if (!Pairing.pairingProd2(vk.b, proof.b, Pairing.negate(proof.b_p), Pairing.P2())) return 2; + if (!Pairing.pairingProd2(proof.c, vk.c, Pairing.negate(proof.c_p), Pairing.P2())) return 3; + if (!Pairing.pairingProd3( + proof.k, vk.gamma, + Pairing.negate(Pairing.addition(vk_x, Pairing.addition(proof.a, proof.c))), vk.gamma_beta_2, + Pairing.negate(vk.gamma_beta_1), proof.b + )) return 4; + if (!Pairing.pairingProd3( + Pairing.addition(vk_x, proof.a), proof.b, + Pairing.negate(proof.h), vk.z, + Pairing.negate(proof.c), Pairing.P2() + )) return 5; + return 0; + } + function verifyTx( + uint[2] memory a, + uint[2] memory a_p, + uint[2][2] memory b, + uint[2] memory b_p, + uint[2] memory c, + uint[2] memory c_p, + uint[2] memory h, + uint[2] memory k<%input_argument%> + ) public view returns (bool r) { + Proof memory proof; + proof.a = Pairing.G1Point(a[0], a[1]); + proof.a_p = Pairing.G1Point(a_p[0], a_p[1]); + proof.b = Pairing.G2Point([b[0][0], b[0][1]], [b[1][0], b[1][1]]); + proof.b_p = Pairing.G1Point(b_p[0], b_p[1]); + proof.c = Pairing.G1Point(c[0], c[1]); + proof.c_p = Pairing.G1Point(c_p[0], c_p[1]); + proof.h = Pairing.G1Point(h[0], h[1]); + proof.k = Pairing.G1Point(k[0], k[1]); + uint[] memory inputValues = new uint[](input.length); + <%input_loop%> + if (verify(inputValues, proof) == 0) { + return true; + } else { + return false; + } + } +} +"#; diff --git a/zokrates_core/src/proof_system/zexe/gm17.rs b/zokrates_core/src/proof_system/zexe/gm17.rs index f06ab9937..893715da8 100644 --- a/zokrates_core/src/proof_system/zexe/gm17.rs +++ b/zokrates_core/src/proof_system/zexe/gm17.rs @@ -4,48 +4,18 @@ use zexe_gm17::{ }; use algebra_core::serialize::{CanonicalDeserialize, CanonicalSerialize}; -use zokrates_field::{ - Bls12_377Field, Bls12_381Field, Bn128Field, Bw6_761Field, Field, ZexeFieldExtensions, -}; +use zokrates_field::{Bw6_761Field, Field, ZexeFieldExtensions}; -use crate::ir; use crate::proof_system::zexe::Computation; use crate::proof_system::zexe::{parse_fr, parse_g1, parse_g2, parse_g2_fq}; -use proof_system::solidity::SolidityAbi; -use proof_system::{G1Affine, G2Affine, G2AffineFq, Proof, ProofSystem, SetupKeypair, Fq2}; - -pub struct GM17 {} - -pub trait NotBw6_761Field {} -impl NotBw6_761Field for Bls12_377Field {} -impl NotBw6_761Field for Bls12_381Field {} -impl NotBw6_761Field for Bn128Field {} - -#[derive(Serialize, Deserialize)] -pub struct ProofPoints { - a: G1, - b: G2, - c: G1, -} - -#[derive(Serialize, Deserialize)] -pub struct VerificationKey { - h: G2, - g_alpha: G1, - h_beta: G2, - g_gamma: G1, - h_gamma: G2, - query: Vec, -} - -impl ProofSystem for GM17 -where - T: NotBw6_761Field + Field + ZexeFieldExtensions, -{ - type VerificationKey = VerificationKey; - type ProofPoints = ProofPoints; - - fn setup(program: ir::Prog) -> SetupKeypair { +use ir::{Prog, Witness}; +use proof_system::scheme::gm17::{NotBw6_761Field, ProofPoints, VerificationKey, GM17}; +use proof_system::scheme::Scheme; +use proof_system::zexe::Zexe; +use proof_system::{Backend, Fq2, Proof, SetupKeypair}; + +impl + NotBw6_761Field> Backend for Zexe { + fn setup(program: Prog) -> SetupKeypair<>::VerificationKey> { let parameters = Computation::without_witness(program).setup(); let mut pk: Vec = Vec::new(); @@ -63,16 +33,17 @@ where .iter() .map(|g1| parse_g1::(g1)) .collect(), + raw: None, }; SetupKeypair::new(vk, pk) } fn generate_proof( - program: ir::Prog, - witness: ir::Witness, + program: Prog, + witness: Witness, proving_key: Vec, - ) -> Proof { + ) -> Proof<>::ProofPoints> { let computation = Computation::with_witness(program, witness); let params = Parameters::<::ZexeEngine>::deserialize_uncompressed( @@ -93,14 +64,13 @@ where .map(parse_fr::) .collect::>(); - Proof::::new(proof_points, inputs, None) - } - - fn export_solidity_verifier(_vk: Self::VerificationKey, _abi: SolidityAbi) -> String { - unimplemented!() + Proof::new(proof_points, inputs, None) } - fn verify(vk: Self::VerificationKey, proof: Proof) -> bool { + fn verify( + vk: >::VerificationKey, + proof: Proof<>::ProofPoints>, + ) -> bool { let vk = VerifyingKey { h_g2: serialization::to_g2::(vk.h), g_alpha_g1: serialization::to_g1::(vk.g_alpha), @@ -137,17 +107,16 @@ where } } -impl ProofSystem for GM17 { - type VerificationKey = VerificationKey; - type ProofPoints = ProofPoints; - - fn setup(program: ir::Prog) -> SetupKeypair { +impl Backend for Zexe { + fn setup( + program: Prog, + ) -> SetupKeypair<>::VerificationKey> { let parameters = Computation::without_witness(program).setup(); let mut pk: Vec = Vec::new(); parameters.serialize_uncompressed(&mut pk).unwrap(); - let vk = Self::VerificationKey { + let vk = VerificationKey { h: parse_g2_fq::(¶meters.vk.h_g2), g_alpha: parse_g1::(¶meters.vk.g_alpha_g1), h_beta: parse_g2_fq::(¶meters.vk.h_beta_g2), @@ -159,24 +128,26 @@ impl ProofSystem for GM17 { .iter() .map(|g1| parse_g1::(g1)) .collect(), + raw: None, }; SetupKeypair::new(vk, pk) } fn generate_proof( - program: ir::Prog, - witness: ir::Witness, + program: Prog, + witness: Witness, proving_key: Vec, - ) -> Proof { + ) -> Proof<>::ProofPoints> { let computation = Computation::with_witness(program, witness); - let params = Parameters::<::ZexeEngine>::deserialize_uncompressed( - &mut proving_key.as_slice(), - ) - .unwrap(); + let params = + Parameters::<::ZexeEngine>::deserialize_uncompressed( + &mut proving_key.as_slice(), + ) + .unwrap(); let proof = computation.clone().prove(¶ms); - let proof_points = Self::ProofPoints { + let proof_points = ProofPoints { a: parse_g1::(&proof.a), b: parse_g2_fq::(&proof.b), c: parse_g1::(&proof.c), @@ -188,14 +159,13 @@ impl ProofSystem for GM17 { .map(parse_fr::) .collect::>(); - Proof::::new(proof_points, inputs, None) + Proof::new(proof_points, inputs, None) } - fn export_solidity_verifier(_vk: Self::VerificationKey, _abi: SolidityAbi) -> String { - unimplemented!() - } - - fn verify(vk: Self::VerificationKey, proof: Proof) -> bool { + fn verify( + vk: >::VerificationKey, + proof: Proof<>::ProofPoints>, + ) -> bool { let vk = VerifyingKey { h_g2: serialization::to_g2_fq::(vk.h), g_alpha_g1: serialization::to_g1::(vk.g_alpha), @@ -223,7 +193,7 @@ impl ProofSystem for GM17 { .iter() .map(|s| { Bw6_761Field::try_from_str(s.trim_start_matches("0x"), 16) - .expect(format!("Invalid {} value: {}", Bw6_761Field::name(), s).as_str()) + .unwrap() .into_zexe() }) .collect::>(); @@ -235,7 +205,7 @@ impl ProofSystem for GM17 { pub mod serialization { use algebra_core::{AffineCurve, PairingEngine}; use num_bigint::BigUint; - use proof_system::{G1Affine, G2Affine, G2AffineFq, Fq2, Fq}; + use proof_system::{Fq, Fq2, G1Affine, G2Affine, G2AffineFq}; use std::str::FromStr; use zokrates_field::ZexeFieldExtensions; @@ -302,15 +272,16 @@ mod tests { private: vec![false], }; - let keypair = GM17::setup(program.clone()); + let keypair = >::setup(program.clone()); let interpreter = Interpreter::default(); let witness = interpreter .execute(&program, &vec![Bls12_377Field::from(42)]) .unwrap(); - let proof = GM17::generate_proof(program, witness, keypair.pk); - let ans = >::verify(keypair.vk, proof); + let proof = + >::generate_proof(program, witness, keypair.pk); + let ans = >::verify(keypair.vk, proof); assert!(ans); } @@ -330,15 +301,16 @@ mod tests { private: vec![false], }; - let keypair = GM17::setup(program.clone()); + let keypair = >::setup(program.clone()); let interpreter = Interpreter::default(); let witness = interpreter .execute(&program, &vec![Bw6_761Field::from(42)]) .unwrap(); - let proof = GM17::generate_proof(program, witness, keypair.pk); - let ans = >::verify(keypair.vk, proof); + let proof = + >::generate_proof(program, witness, keypair.pk); + let ans = >::verify(keypair.vk, proof); assert!(ans); } diff --git a/zokrates_core/src/proof_system/zexe/mod.rs b/zokrates_core/src/proof_system/zexe/mod.rs index 075a6c9d1..fb831ba80 100644 --- a/zokrates_core/src/proof_system/zexe/mod.rs +++ b/zokrates_core/src/proof_system/zexe/mod.rs @@ -20,6 +20,8 @@ pub use self::parse::*; use rand_0_7::SeedableRng; +pub struct Zexe; + #[derive(Clone)] pub struct Computation { program: Prog, From 6c966e8f92e3dbbed226b4f8d6fa48b9af4997e9 Mon Sep 17 00:00:00 2001 From: schaeff Date: Thu, 1 Oct 2020 14:44:23 +0200 Subject: [PATCH 27/54] stop encoding call identifier with ssa version --- zokrates_core/src/static_analysis/inline.rs | 65 +++++++++++++-------- zokrates_core/src/typed_absy/identifier.rs | 4 +- 2 files changed, 42 insertions(+), 27 deletions(-) diff --git a/zokrates_core/src/static_analysis/inline.rs b/zokrates_core/src/static_analysis/inline.rs index 3962711e8..777ad4bc3 100644 --- a/zokrates_core/src/static_analysis/inline.rs +++ b/zokrates_core/src/static_analysis/inline.rs @@ -351,11 +351,14 @@ impl<'ast, T: Field> Folder<'ast, T> for Inliner<'ast, T> { Err((key, expressions)) => { let tys = key.signature.outputs.clone(); let id = Identifier { - id: CoreIdentifier::Call(key.clone()), - version: *self - .call_count - .get(&(self.module_id().clone(), key.clone())) - .unwrap(), + id: CoreIdentifier::Call( + key.clone(), + *self + .call_count + .get(&(self.module_id().clone(), key.clone())) + .unwrap(), + ), + version: 0, stack: self.stack.clone(), }; self.statement_buffer @@ -388,11 +391,14 @@ impl<'ast, T: Field> Folder<'ast, T> for Inliner<'ast, T> { Err((key, expressions)) => { let tys = key.signature.outputs.clone(); let id = Identifier { - id: CoreIdentifier::Call(key.clone()), - version: *self - .call_count - .get(&(self.module_id().clone(), key.clone())) - .unwrap(), + id: CoreIdentifier::Call( + key.clone(), + *self + .call_count + .get(&(self.module_id().clone(), key.clone())) + .unwrap(), + ), + version: 0, stack: self.stack.clone(), }; self.statement_buffer @@ -440,11 +446,14 @@ impl<'ast, T: Field> Folder<'ast, T> for Inliner<'ast, T> { Err((embed_key, expressions)) => { let tys = key.signature.outputs.clone(); let id = Identifier { - id: CoreIdentifier::Call(key.clone()), - version: *self - .call_count - .get(&(self.module_id().clone(), embed_key.clone())) - .unwrap(), + id: CoreIdentifier::Call( + key.clone(), + *self + .call_count + .get(&(self.module_id().clone(), key.clone())) + .unwrap(), + ), + version: 0, stack: self.stack.clone(), }; self.statement_buffer @@ -493,11 +502,14 @@ impl<'ast, T: Field> Folder<'ast, T> for Inliner<'ast, T> { Err((key, expressions)) => { let tys = key.signature.outputs.clone(); let id = Identifier { - id: CoreIdentifier::Call(key.clone()), - version: *self - .call_count - .get(&(self.module_id().clone(), key.clone())) - .unwrap(), + id: CoreIdentifier::Call( + key.clone(), + *self + .call_count + .get(&(self.module_id().clone(), key.clone())) + .unwrap(), + ), + version: 0, stack: self.stack.clone(), }; self.statement_buffer @@ -531,11 +543,14 @@ impl<'ast, T: Field> Folder<'ast, T> for Inliner<'ast, T> { Err((embed_key, expressions)) => { let tys = key.signature.outputs.clone(); let id = Identifier { - id: CoreIdentifier::Call(key.clone()), - version: *self - .call_count - .get(&(self.module_id().clone(), embed_key.clone())) - .unwrap(), + id: CoreIdentifier::Call( + key.clone(), + *self + .call_count + .get(&(self.module_id().clone(), key.clone())) + .unwrap(), + ), + version: 0, stack: self.stack.clone(), }; self.statement_buffer diff --git a/zokrates_core/src/typed_absy/identifier.rs b/zokrates_core/src/typed_absy/identifier.rs index a22defd29..979536bb8 100644 --- a/zokrates_core/src/typed_absy/identifier.rs +++ b/zokrates_core/src/typed_absy/identifier.rs @@ -6,7 +6,7 @@ use typed_absy::TypedModuleId; pub enum CoreIdentifier<'ast> { Source(&'ast str), Internal(&'static str, usize), - Call(FunctionKey<'ast>), + Call(FunctionKey<'ast>, usize), } impl<'ast> fmt::Display for CoreIdentifier<'ast> { @@ -14,7 +14,7 @@ impl<'ast> fmt::Display for CoreIdentifier<'ast> { match self { CoreIdentifier::Source(s) => write!(f, "{}", s), CoreIdentifier::Internal(s, i) => write!(f, "#INTERNAL#_{}_{}", s, i), - CoreIdentifier::Call(k) => write!(f, "{}", k.to_slug()), + CoreIdentifier::Call(k, i) => write!(f, "{}_{}", k.to_slug(), i), } } } From a9e42c40daae36e3fc467fc57ba230fc606f075e Mon Sep 17 00:00:00 2001 From: schaeff Date: Thu, 1 Oct 2020 16:17:21 +0200 Subject: [PATCH 28/54] implement caching, move call count --- zokrates_core/src/static_analysis/inline.rs | 72 ++++++++++++++------- zokrates_core/src/static_analysis/mod.rs | 1 + 2 files changed, 48 insertions(+), 25 deletions(-) diff --git a/zokrates_core/src/static_analysis/inline.rs b/zokrates_core/src/static_analysis/inline.rs index 777ad4bc3..f86d61862 100644 --- a/zokrates_core/src/static_analysis/inline.rs +++ b/zokrates_core/src/static_analysis/inline.rs @@ -234,15 +234,7 @@ impl<'ast, T: Field> Inliner<'ast, T> { Ok(res) } // if the function is a flat symbol, replace the call with a call to the local function we provide so it can be inlined in flattening - TypedFunctionSymbol::Flat(embed) => { - // increase the number of calls for this function by one - let _ = self - .call_count - .entry((self.module_id().clone(), embed.key::().clone())) - .and_modify(|i| *i += 1) - .or_insert(1); - Err((embed.key::(), expressions.clone())) - } + TypedFunctionSymbol::Flat(embed) => Err((embed.key::(), expressions.clone())), }; res.map(|exprs| { @@ -348,15 +340,16 @@ impl<'ast, T: Field> Folder<'ast, T> for Inliner<'ast, T> { TypedExpression::FieldElement(e) => e, _ => unreachable!(), }, - Err((key, expressions)) => { + Err((embed_key, expressions)) => { let tys = key.signature.outputs.clone(); let id = Identifier { id: CoreIdentifier::Call( key.clone(), *self .call_count - .get(&(self.module_id().clone(), key.clone())) - .unwrap(), + .entry((self.module_id().clone(), embed_key.clone())) + .and_modify(|i| *i += 1) + .or_insert(1), ), version: 0, stack: self.stack.clone(), @@ -364,8 +357,21 @@ impl<'ast, T: Field> Folder<'ast, T> for Inliner<'ast, T> { self.statement_buffer .push(TypedStatement::MultipleDefinition( vec![Variable::with_id_and_type(id.clone(), tys[0].clone())], - TypedExpressionList::FunctionCall(key, expressions, tys), + TypedExpressionList::FunctionCall( + key.clone(), + expressions.clone(), + tys, + ), )); + + self.call_cache_mut() + .entry(key.clone()) + .or_insert_with(|| HashMap::new()) + .insert( + expressions, + vec![FieldElementExpression::Identifier(id.clone()).into()], + ); + FieldElementExpression::Identifier(id) } } @@ -388,15 +394,16 @@ impl<'ast, T: Field> Folder<'ast, T> for Inliner<'ast, T> { TypedExpression::Boolean(e) => e, _ => unreachable!(), }, - Err((key, expressions)) => { + Err((embed_key, expressions)) => { let tys = key.signature.outputs.clone(); let id = Identifier { id: CoreIdentifier::Call( key.clone(), *self .call_count - .get(&(self.module_id().clone(), key.clone())) - .unwrap(), + .entry((self.module_id().clone(), embed_key.clone())) + .and_modify(|i| *i += 1) + .or_insert(1), ), version: 0, stack: self.stack.clone(), @@ -450,8 +457,9 @@ impl<'ast, T: Field> Folder<'ast, T> for Inliner<'ast, T> { key.clone(), *self .call_count - .get(&(self.module_id().clone(), key.clone())) - .unwrap(), + .entry((self.module_id().clone(), embed_key.clone())) + .and_modify(|i| *i += 1) + .or_insert(1), ), version: 0, stack: self.stack.clone(), @@ -499,15 +507,16 @@ impl<'ast, T: Field> Folder<'ast, T> for Inliner<'ast, T> { TypedExpression::Struct(e) => e.into_inner(), _ => unreachable!(), }, - Err((key, expressions)) => { + Err((embed_key, expressions)) => { let tys = key.signature.outputs.clone(); let id = Identifier { id: CoreIdentifier::Call( key.clone(), *self .call_count - .get(&(self.module_id().clone(), key.clone())) - .unwrap(), + .entry((self.module_id().clone(), embed_key.clone())) + .and_modify(|i| *i += 1) + .or_insert(1), ), version: 0, stack: self.stack.clone(), @@ -515,9 +524,21 @@ impl<'ast, T: Field> Folder<'ast, T> for Inliner<'ast, T> { self.statement_buffer .push(TypedStatement::MultipleDefinition( vec![Variable::with_id_and_type(id.clone(), tys[0].clone())], - TypedExpressionList::FunctionCall(key, expressions, tys), + TypedExpressionList::FunctionCall( + key.clone(), + expressions.clone(), + tys, + ), )); - StructExpressionInner::Identifier(id) + + let out = StructExpressionInner::Identifier(id); + + self.call_cache_mut() + .entry(key.clone()) + .or_insert_with(|| HashMap::new()) + .insert(expressions, vec![out.clone().annotate(ty.clone()).into()]); + + out } } } @@ -547,8 +568,9 @@ impl<'ast, T: Field> Folder<'ast, T> for Inliner<'ast, T> { key.clone(), *self .call_count - .get(&(self.module_id().clone(), key.clone())) - .unwrap(), + .entry((self.module_id().clone(), embed_key.clone())) + .and_modify(|i| *i += 1) + .or_insert(1), ), version: 0, stack: self.stack.clone(), diff --git a/zokrates_core/src/static_analysis/mod.rs b/zokrates_core/src/static_analysis/mod.rs index 41c67a99c..c42c1b875 100644 --- a/zokrates_core/src/static_analysis/mod.rs +++ b/zokrates_core/src/static_analysis/mod.rs @@ -39,6 +39,7 @@ impl<'ast, T: Field> TypedProgram<'ast, T> { pub fn analyse(self) -> ZirProgram<'ast, T> { // propagated unrolling let r = PropagatedUnroller::unroll(self).unwrap_or_else(|e| panic!(e)); + // return binding let r = ReturnBinder::bind(r); From b54f03c4e5f833fd3f948e29147ed9a4649ffb7d Mon Sep 17 00:00:00 2001 From: dark64 Date: Fri, 2 Oct 2020 11:19:11 +0200 Subject: [PATCH 29/54] [zexe] remove regex parsing of g1, g2 --- zokrates_core/src/proof_system/zexe/mod.rs | 110 ++++++++++----------- 1 file changed, 55 insertions(+), 55 deletions(-) diff --git a/zokrates_core/src/proof_system/zexe/mod.rs b/zokrates_core/src/proof_system/zexe/mod.rs index fb831ba80..ed85a8285 100644 --- a/zokrates_core/src/proof_system/zexe/mod.rs +++ b/zokrates_core/src/proof_system/zexe/mod.rs @@ -220,69 +220,57 @@ impl } mod parse { - use lazy_static::lazy_static; - use super::*; + use algebra_core::ToBytes; use proof_system::{Fr, G1Affine, G2Affine, G2AffineFq}; - use regex::Regex; - lazy_static! { - pub static ref G2_REGEX: Regex = Regex::new(r#"GroupAffine\(x=QuadExtField\(Fp\d{3} "\((?P[0-9a-fA-F]*)\)" \+ Fp\d{3} "\((?P[0-9a-fA-F]*)\)" \* u\), y=QuadExtField\(Fp\d{3} "\((?P[0-9a-fA-F]*)\)" \+ Fp\d{3} "\((?P[0-9a-fA-F]*)\)" \* u\)\)"#).unwrap(); - } + pub fn parse_g1( + e: &::G1Affine, + ) -> G1Affine { + let mut bytes: Vec = Vec::new(); + e.write(&mut bytes).unwrap(); - lazy_static! { - static ref G1_REGEX: Regex = - Regex::new(r#"GroupAffine\(x=Fp\d{3} "\((?P[0-9a-fA-F]*)\)", y=Fp\d{3} "\((?P[0-9a-fA-F]*)\)"\)"#) - .unwrap(); - } + let length = bytes.len() - 1; // [x, y, infinity] - infinity + let element_length = length / 2; - lazy_static! { - static ref FR_REGEX: Regex = Regex::new(r#"Fp\d{3} "\((?P[0-9a-fA-F]*)\)""#).unwrap(); - } + let mut x = bytes[0..element_length].to_vec(); + let mut y = bytes[element_length..length].to_vec(); - lazy_static! { - pub static ref G1_G2_REGEX_FQ: Regex = Regex::new(r#"GroupAffine\(x=Fp\d{3} "\((?P[0-9a-fA-F]*)\)", y=Fp\d{3} "\((?P[0-9a-fA-F]*)\)"\)"#).unwrap(); - } - - lazy_static! { - static ref FR_REGEX_FQ: Regex = Regex::new(r#"Fp\d{3} "\((?P[0-9a-fA-F]*)\)""#).unwrap(); - } + x.reverse(); + y.reverse(); - pub fn parse_g1( - e: &::G1Affine, - ) -> G1Affine { - let raw_e = e.to_string(); - match T::name() { - "bw6_761" => { - let captures = G1_G2_REGEX_FQ.captures(&raw_e).unwrap(); - G1Affine( - ("0x".to_string() + captures.name(&"x").unwrap().as_str()).to_string(), - ("0x".to_string() + captures.name(&"y").unwrap().as_str()).to_string(), - ) - } - _ => { - let captures = G1_REGEX.captures(&raw_e).unwrap(); - G1Affine( - ("0x".to_string() + captures.name(&"x").unwrap().as_str()).to_string(), - ("0x".to_string() + captures.name(&"y").unwrap().as_str()).to_string(), - ) - } - } + G1Affine( + format!("0x{}", hex::encode(&x)), + format!("0x{}", hex::encode(&y)), + ) } - pub fn parse_g2( + pub fn parse_g2( e: &::G2Affine, ) -> G2Affine { - let raw_e = e.to_string(); - let captures = G2_REGEX.captures(&raw_e).unwrap(); + let mut bytes: Vec = Vec::new(); + e.write(&mut bytes).unwrap(); + + let length = bytes.len() - 1; // [x, y, infinity] - infinity + let element_length = length / 4; + + let mut elements = vec![]; + for i in 0..4 { + let start = i * element_length; + let end = start + element_length; + let mut e = bytes[start..end].to_vec(); + e.reverse(); + elements.push(e); + } + G2Affine( ( - ("0x".to_string() + captures.name(&"x0").unwrap().as_str()).to_string(), - ("0x".to_string() + captures.name(&"x1").unwrap().as_str()).to_string(), + format!("0x{}", hex::encode(&elements[0])), + format!("0x{}", hex::encode(&elements[1])), ), ( - ("0x".to_string() + captures.name(&"y0").unwrap().as_str()).to_string(), - ("0x".to_string() + captures.name(&"y1").unwrap().as_str()).to_string(), + format!("0x{}", hex::encode(&elements[2])), + format!("0x{}", hex::encode(&elements[3])), ), ) } @@ -290,17 +278,29 @@ mod parse { pub fn parse_g2_fq( e: &::G2Affine, ) -> G2AffineFq { - let raw_e = e.to_string(); - let captures = G1_G2_REGEX_FQ.captures(&raw_e).unwrap(); + let mut bytes: Vec = Vec::new(); + e.write(&mut bytes).unwrap(); + + let length = bytes.len() - 1; // [x, y, infinity] - infinity + let element_length = length / 2; + + let mut x = bytes[0..element_length].to_vec(); + let mut y = bytes[element_length..length].to_vec(); + + x.reverse(); + y.reverse(); + G2AffineFq( - ("0x".to_string() + captures.name(&"x").unwrap().as_str()).to_string(), - ("0x".to_string() + captures.name(&"y").unwrap().as_str()).to_string(), + format!("0x{}", hex::encode(&x)), + format!("0x{}", hex::encode(&y)), ) } pub fn parse_fr(e: &::Fr) -> Fr { - let raw_e = e.to_string(); - let captures = FR_REGEX.captures(&raw_e).unwrap(); - ("0x".to_string() + captures.name(&"x").unwrap().as_str()).to_string() + let mut bytes: Vec = Vec::new(); + e.write(&mut bytes).unwrap(); + bytes.reverse(); + + format!("0x{}", hex::encode(&bytes)) } } From 9a35bfae55470a4d5e72c97fc123e62164c71a5d Mon Sep 17 00:00:00 2001 From: dark64 Date: Fri, 2 Oct 2020 12:59:14 +0200 Subject: [PATCH 30/54] revert zexe to offical git repo, use FromBytes to construct g1 and g2 --- Cargo.lock | 24 +++++----- zokrates_core/Cargo.toml | 12 ++--- zokrates_core/src/proof_system/zexe/gm17.rs | 49 +++++++++++---------- zokrates_field/Cargo.toml | 6 +-- 4 files changed, 45 insertions(+), 46 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d5f613246..56dc08852 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -27,7 +27,7 @@ dependencies = [ [[package]] name = "algebra" version = "0.1.1-alpha.0" -source = "git+https://github.com/dark64/zexe.git?branch=dark64-patch#6d15b91fbbcd9cc9cbbb1f2783a6020be2761e64" +source = "git+https://github.com/scipr-lab/zexe.git#85cac1770dddd4da79e9993c5d1dcb5732db08f5" dependencies = [ "algebra-core", ] @@ -35,7 +35,7 @@ dependencies = [ [[package]] name = "algebra-core" version = "0.1.1-alpha.0" -source = "git+https://github.com/dark64/zexe.git?branch=dark64-patch#6d15b91fbbcd9cc9cbbb1f2783a6020be2761e64" +source = "git+https://github.com/scipr-lab/zexe.git#85cac1770dddd4da79e9993c5d1dcb5732db08f5" dependencies = [ "algebra-core-derive", "derivative", @@ -50,7 +50,7 @@ dependencies = [ [[package]] name = "algebra-core-derive" version = "0.1.1-alpha.0" -source = "git+https://github.com/dark64/zexe.git?branch=dark64-patch#6d15b91fbbcd9cc9cbbb1f2783a6020be2761e64" +source = "git+https://github.com/scipr-lab/zexe.git#85cac1770dddd4da79e9993c5d1dcb5732db08f5" dependencies = [ "proc-macro2 1.0.19", "quote 1.0.7", @@ -149,7 +149,7 @@ dependencies = [ [[package]] name = "bench-utils" version = "0.1.1-alpha.0" -source = "git+https://github.com/dark64/zexe.git?branch=dark64-patch#6d15b91fbbcd9cc9cbbb1f2783a6020be2761e64" +source = "git+https://github.com/scipr-lab/zexe.git#85cac1770dddd4da79e9993c5d1dcb5732db08f5" [[package]] name = "bincode" @@ -418,7 +418,7 @@ dependencies = [ [[package]] name = "crypto-primitives" version = "0.1.1-alpha.0" -source = "git+https://github.com/dark64/zexe.git?branch=dark64-patch#6d15b91fbbcd9cc9cbbb1f2783a6020be2761e64" +source = "git+https://github.com/scipr-lab/zexe.git#85cac1770dddd4da79e9993c5d1dcb5732db08f5" dependencies = [ "algebra-core", "bench-utils", @@ -581,7 +581,7 @@ checksum = "e88a8acf291dafb59c2d96e8f59828f3838bb1a70398823ade51a84de6a6deed" [[package]] name = "ff-fft" version = "0.1.1-alpha.0" -source = "git+https://github.com/dark64/zexe.git?branch=dark64-patch#6d15b91fbbcd9cc9cbbb1f2783a6020be2761e64" +source = "git+https://github.com/scipr-lab/zexe.git#85cac1770dddd4da79e9993c5d1dcb5732db08f5" dependencies = [ "algebra-core", "rand 0.7.3", @@ -628,7 +628,7 @@ dependencies = [ [[package]] name = "field-assembly" version = "0.1.1-alpha.0" -source = "git+https://github.com/dark64/zexe.git?branch=dark64-patch#6d15b91fbbcd9cc9cbbb1f2783a6020be2761e64" +source = "git+https://github.com/scipr-lab/zexe.git#85cac1770dddd4da79e9993c5d1dcb5732db08f5" dependencies = [ "mince", ] @@ -792,7 +792,7 @@ checksum = "9b919933a397b79c37e33b77bb2aa3dc8eb6e165ad809e58ff75bc7db2e34574" [[package]] name = "gm17" version = "0.1.1-alpha.0" -source = "git+https://github.com/dark64/zexe.git?branch=dark64-patch#6d15b91fbbcd9cc9cbbb1f2783a6020be2761e64" +source = "git+https://github.com/scipr-lab/zexe.git#85cac1770dddd4da79e9993c5d1dcb5732db08f5" dependencies = [ "algebra-core", "bench-utils", @@ -805,7 +805,7 @@ dependencies = [ [[package]] name = "groth16" version = "0.1.1-alpha.0" -source = "git+https://github.com/dark64/zexe.git?branch=dark64-patch#6d15b91fbbcd9cc9cbbb1f2783a6020be2761e64" +source = "git+https://github.com/scipr-lab/zexe.git#85cac1770dddd4da79e9993c5d1dcb5732db08f5" dependencies = [ "algebra-core", "bench-utils", @@ -971,7 +971,7 @@ dependencies = [ [[package]] name = "mince" version = "0.1.1-alpha.0" -source = "git+https://github.com/dark64/zexe.git?branch=dark64-patch#6d15b91fbbcd9cc9cbbb1f2783a6020be2761e64" +source = "git+https://github.com/scipr-lab/zexe.git#85cac1770dddd4da79e9993c5d1dcb5732db08f5" dependencies = [ "quote 1.0.7", "syn 1.0.39", @@ -1285,7 +1285,7 @@ dependencies = [ [[package]] name = "r1cs-core" version = "0.1.1-alpha.0" -source = "git+https://github.com/dark64/zexe.git?branch=dark64-patch#6d15b91fbbcd9cc9cbbb1f2783a6020be2761e64" +source = "git+https://github.com/scipr-lab/zexe.git#85cac1770dddd4da79e9993c5d1dcb5732db08f5" dependencies = [ "algebra-core", "tracing", @@ -1295,7 +1295,7 @@ dependencies = [ [[package]] name = "r1cs-std" version = "0.1.1-alpha.0" -source = "git+https://github.com/dark64/zexe.git?branch=dark64-patch#6d15b91fbbcd9cc9cbbb1f2783a6020be2761e64" +source = "git+https://github.com/scipr-lab/zexe.git#85cac1770dddd4da79e9993c5d1dcb5732db08f5" dependencies = [ "algebra", "derivative", diff --git a/zokrates_core/Cargo.toml b/zokrates_core/Cargo.toml index 07273cbb4..bd562c0e0 100644 --- a/zokrates_core/Cargo.toml +++ b/zokrates_core/Cargo.toml @@ -36,12 +36,12 @@ rand_0_7 = { version = "0.7", package = "rand" } csv = "1" pretty_assertions = "0.6.1" bellman_ce = { version = "^0.3", default-features = false} -gm17 = { git = "https://github.com/dark64/zexe.git", branch = "dark64-patch", version = "0.1.1-alpha.0", features = ["parallel"] } -algebra-core = { git = "https://github.com/dark64/zexe.git", branch = "dark64-patch", version = "0.1.1-alpha.0", features = ["parallel"] } -r1cs-core = { git = "https://github.com/dark64/zexe.git", branch = "dark64-patch", version = "0.1.1-alpha.0"} -algebra = { git = "https://github.com/dark64/zexe.git", branch = "dark64-patch", version = "0.1.1-alpha.0", features = ["bn254", "bls12_377", "bw6_761", "parallel"] } -crypto-primitives = { default-features = false, git = "https://github.com/dark64/zexe.git", branch = "dark64-patch", version = "0.1.1-alpha.0", features = [ "parallel", "gm17", "r1cs" ] } -r1cs-std = { git = "https://github.com/dark64/zexe.git", branch = "dark64-patch", version = "0.1.1-alpha.0", features = ["bls12_377", "parallel"] } +gm17 = { git = "https://github.com/scipr-lab/zexe.git", features = ["parallel"] } +algebra-core = { git = "https://github.com/scipr-lab/zexe.git", features = ["parallel"] } +r1cs-core = { git = "https://github.com/scipr-lab/zexe.git" } +algebra = { git = "https://github.com/scipr-lab/zexe.git", features = ["bn254", "bls12_377", "bw6_761", "parallel"] } +crypto-primitives = { git = "https://github.com/scipr-lab/zexe.git", features = ["parallel", "gm17", "r1cs"], default-features = false } +r1cs-std = { git = "https://github.com/scipr-lab/zexe.git", features = ["bls12_377", "parallel"] } [dev-dependencies] glob = "0.2.11" diff --git a/zokrates_core/src/proof_system/zexe/gm17.rs b/zokrates_core/src/proof_system/zexe/gm17.rs index 893715da8..24b04b9ab 100644 --- a/zokrates_core/src/proof_system/zexe/gm17.rs +++ b/zokrates_core/src/proof_system/zexe/gm17.rs @@ -203,49 +203,50 @@ impl Backend for Zexe { } pub mod serialization { - use algebra_core::{AffineCurve, PairingEngine}; - use num_bigint::BigUint; + use algebra_core::{FromBytes, PairingEngine}; use proof_system::{Fq, Fq2, G1Affine, G2Affine, G2AffineFq}; - use std::str::FromStr; use zokrates_field::ZexeFieldExtensions; - fn to_dec_string(s: String) -> String { - BigUint::from_bytes_be( - hex::decode(s.strip_prefix("0x").unwrap()) - .unwrap() - .as_slice(), - ) - .to_str_radix(10) + #[inline] + fn decode_hex(value: String) -> Vec { + let mut bytes = hex::decode(value.strip_prefix("0x").unwrap()).unwrap(); + bytes.reverse(); + bytes } pub fn to_g1( g1: G1Affine, ) -> ::G1Affine { - let x = ::Fq::from_str(to_dec_string(g1.0).as_str()) - .map_err(|_| ()) - .unwrap(); - - let y = ::Fq::from_str(to_dec_string(g1.1).as_str()) - .map_err(|_| ()) - .unwrap(); + let mut bytes = vec![]; + bytes.append(&mut decode_hex(g1.0)); + bytes.append(&mut decode_hex(g1.1)); + bytes.push(0u8); // infinity flag - ::G1Affine::from_xy_checked(x, y).unwrap() + ::G1Affine::read(&*bytes).unwrap() } pub fn to_g2>( g2: G2Affine, ) -> ::G2Affine { - let x = T::new_fqe((to_dec_string((g2.0).0), to_dec_string((g2.0).1))); - let y = T::new_fqe((to_dec_string((g2.1).0), to_dec_string((g2.1).1))); - ::G2Affine::from_xy_checked(x, y).unwrap() + let mut bytes = vec![]; + bytes.append(&mut decode_hex((g2.0).0)); + bytes.append(&mut decode_hex((g2.0).1)); + bytes.append(&mut decode_hex((g2.1).0)); + bytes.append(&mut decode_hex((g2.1).1)); + bytes.push(0u8); // infinity flag + + ::G2Affine::read(&*bytes).unwrap() } pub fn to_g2_fq>( g2: G2AffineFq, ) -> ::G2Affine { - let x = T::new_fqe(to_dec_string(g2.0)); - let y = T::new_fqe(to_dec_string(g2.1)); - ::G2Affine::from_xy_checked(x, y).unwrap() + let mut bytes = vec![]; + bytes.append(&mut decode_hex(g2.0)); + bytes.append(&mut decode_hex(g2.1)); + bytes.push(0u8); // infinity flag + + ::G2Affine::read(&*bytes).unwrap() } } diff --git a/zokrates_field/Cargo.toml b/zokrates_field/Cargo.toml index e765a8718..8aa25f8b8 100644 --- a/zokrates_field/Cargo.toml +++ b/zokrates_field/Cargo.toml @@ -11,15 +11,13 @@ lazy_static = "1.4" bincode = "0.8.0" serde_json = "1.0" bellman_ce = { version = "^0.3", default-features = false} -algebra-core = { git = "https://github.com/dark64/zexe.git", branch = "dark64-patch", version = "0.1.1-alpha.0", features = ["parallel"] } +algebra-core = { git = "https://github.com/scipr-lab/zexe.git", features = ["parallel"] } sha2 = "0.8.0" num-traits = { version = "0.2", default-features = false } num-integer = { version = "0.1", default-features = false } [dependencies.algebra] -git = "https://github.com/dark64/zexe.git" -branch = "dark64-patch" -version = "0.1.1-alpha.0" +git = "https://github.com/scipr-lab/zexe.git" features = ["bn254", "bls12_377", "bw6_761", "parallel"] [dev-dependencies] From c974499f914b460655729c18b4cea5b5daa3dcbd Mon Sep 17 00:00:00 2001 From: dark64 Date: Fri, 2 Oct 2020 13:13:29 +0200 Subject: [PATCH 31/54] fix zokrates js --- zokrates_js/Cargo.lock | 495 +++++++++++++++++++++++++++++++++- zokrates_js/package-lock.json | 2 +- zokrates_js/src/lib.rs | 18 +- 3 files changed, 498 insertions(+), 17 deletions(-) diff --git a/zokrates_js/Cargo.lock b/zokrates_js/Cargo.lock index 1f7873660..d6888a7dd 100644 --- a/zokrates_js/Cargo.lock +++ b/zokrates_js/Cargo.lock @@ -24,6 +24,48 @@ dependencies = [ "memchr", ] +[[package]] +name = "algebra" +version = "0.1.1-alpha.0" +source = "git+https://github.com/scipr-lab/zexe.git#85cac1770dddd4da79e9993c5d1dcb5732db08f5" +dependencies = [ + "algebra-core", +] + +[[package]] +name = "algebra-core" +version = "0.1.1-alpha.0" +source = "git+https://github.com/scipr-lab/zexe.git#85cac1770dddd4da79e9993c5d1dcb5732db08f5" +dependencies = [ + "algebra-core-derive", + "derivative", + "field-assembly", + "num-traits 0.2.12", + "rand 0.7.3", + "rayon", + "rustc_version", + "unroll", +] + +[[package]] +name = "algebra-core-derive" +version = "0.1.1-alpha.0" +source = "git+https://github.com/scipr-lab/zexe.git#85cac1770dddd4da79e9993c5d1dcb5732db08f5" +dependencies = [ + "proc-macro2 1.0.18", + "quote 1.0.7", + "syn 1.0.34", +] + +[[package]] +name = "ansi_term" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee49baf6cb617b853aa8d93bf420db2383fab46d314482ca2803b40d5fde979b" +dependencies = [ + "winapi", +] + [[package]] name = "autocfg" version = "1.0.0" @@ -56,10 +98,15 @@ dependencies = [ "futures", "num_cpus", "pairing_ce", - "rand", + "rand 0.4.6", "web-sys", ] +[[package]] +name = "bench-utils" +version = "0.1.1-alpha.0" +source = "git+https://github.com/scipr-lab/zexe.git#85cac1770dddd4da79e9993c5d1dcb5732db08f5" + [[package]] name = "bincode" version = "0.8.0" @@ -87,6 +134,18 @@ version = "0.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5f0dc55f2d8a1a85650ac47858bb001b4c0dd73d79e3c455a842925e68d29cd3" +[[package]] +name = "blake2" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94cb07b0da6a73955f8fb85d24c466778e70cda767a568229b104f0264089330" +dependencies = [ + "byte-tools", + "crypto-mac", + "digest", + "opaque-debug", +] + [[package]] name = "block-buffer" version = "0.7.3" @@ -154,6 +213,83 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "crossbeam-channel" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b153fe7cbef478c567df0f972e02e6d736db11affe43dfc9c56a9374d1adfb87" +dependencies = [ + "crossbeam-utils", + "maybe-uninit", +] + +[[package]] +name = "crossbeam-deque" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f02af974daeee82218205558e51ec8768b48cf524bd01d550abe5573a608285" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", + "maybe-uninit", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "058ed274caafc1f60c4997b5fc07bf7dc7cca454af7c6e81edffe5f33f70dace" +dependencies = [ + "autocfg", + "cfg-if", + "crossbeam-utils", + "lazy_static", + "maybe-uninit", + "memoffset", + "scopeguard", +] + +[[package]] +name = "crossbeam-utils" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3c7c73a2d1e9fc0886a08b93e98eb643461230d5f1925e4036204d5f2e261a8" +dependencies = [ + "autocfg", + "cfg-if", + "lazy_static", +] + +[[package]] +name = "crypto-mac" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4434400df11d95d556bac068ddfedd482915eb18fe8bea89bc80b6e4b1c179e5" +dependencies = [ + "generic-array", + "subtle", +] + +[[package]] +name = "crypto-primitives" +version = "0.1.1-alpha.0" +source = "git+https://github.com/scipr-lab/zexe.git#85cac1770dddd4da79e9993c5d1dcb5732db08f5" +dependencies = [ + "algebra-core", + "bench-utils", + "blake2", + "derivative", + "digest", + "ff-fft", + "gm17", + "groth16", + "r1cs-core", + "r1cs-std", + "rand 0.7.3", + "rayon", + "tracing", +] + [[package]] name = "csv" version = "1.1.3" @@ -176,6 +312,33 @@ dependencies = [ "memchr", ] +[[package]] +name = "ctor" +version = "0.1.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7fbaabec2c953050352311293be5c6aba8e141ba19d6811862b232d6fd020484" +dependencies = [ + "quote 1.0.7", + "syn 1.0.34", +] + +[[package]] +name = "derivative" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb582b60359da160a9477ee80f15c8d784c477e69c217ef2cdd4169c24ea380f" +dependencies = [ + "proc-macro2 1.0.18", + "quote 1.0.7", + "syn 1.0.34", +] + +[[package]] +name = "difference" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "524cbf6897b527295dff137cec09ecf3a05f4fddffd7dfcd1585403449e74198" + [[package]] name = "digest" version = "0.8.1" @@ -219,6 +382,16 @@ version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e88a8acf291dafb59c2d96e8f59828f3838bb1a70398823ade51a84de6a6deed" +[[package]] +name = "ff-fft" +version = "0.1.1-alpha.0" +source = "git+https://github.com/scipr-lab/zexe.git#85cac1770dddd4da79e9993c5d1dcb5732db08f5" +dependencies = [ + "algebra-core", + "rand 0.7.3", + "rayon", +] + [[package]] name = "ff_ce" version = "0.9.0" @@ -227,7 +400,7 @@ checksum = "83c0a6a2c53b0bd6d8cae976816dc8a171e0554c03f304e3dac110473e0219fd" dependencies = [ "byteorder", "hex", - "rand", + "rand 0.4.6", ] [[package]] @@ -239,7 +412,7 @@ dependencies = [ "byteorder", "ff_derive_ce", "hex", - "rand", + "rand 0.4.6", ] [[package]] @@ -248,7 +421,7 @@ version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "50c052fa6d4c2f12305ec364bfb8ef884836f3f61ea015b202372ff996d1ac4b" dependencies = [ - "num-bigint", + "num-bigint 0.2.6", "num-integer", "num-traits 0.2.12", "proc-macro2 1.0.18", @@ -256,6 +429,14 @@ dependencies = [ "syn 1.0.34", ] +[[package]] +name = "field-assembly" +version = "0.1.1-alpha.0" +source = "git+https://github.com/scipr-lab/zexe.git#85cac1770dddd4da79e9993c5d1dcb5732db08f5" +dependencies = [ + "mince", +] + [[package]] name = "from-pest" version = "0.3.1" @@ -361,12 +542,49 @@ dependencies = [ "typenum", ] +[[package]] +name = "getrandom" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc587bc0ec293155d5bfa6b9891ec18a1e330c234f896ea47fbada4cadbe47e6" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + [[package]] name = "gimli" version = "0.22.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aaf91faf136cb47367fa430cd46e37a788775e7fa104f8b4bcb3861dc389b724" +[[package]] +name = "gm17" +version = "0.1.1-alpha.0" +source = "git+https://github.com/scipr-lab/zexe.git#85cac1770dddd4da79e9993c5d1dcb5732db08f5" +dependencies = [ + "algebra-core", + "bench-utils", + "ff-fft", + "r1cs-core", + "rand 0.7.3", + "rayon", +] + +[[package]] +name = "groth16" +version = "0.1.1-alpha.0" +source = "git+https://github.com/scipr-lab/zexe.git#85cac1770dddd4da79e9993c5d1dcb5732db08f5" +dependencies = [ + "algebra-core", + "bench-utils", + "ff-fft", + "r1cs-core", + "rand 0.7.3", + "rayon", +] + [[package]] name = "hermit-abi" version = "0.1.15" @@ -433,12 +651,36 @@ version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3e2e65a1a2e43cfcb47a895c4c8b10d1f4a61097f9f254f183aee60cad9c651d" +[[package]] +name = "maybe-uninit" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60302e4db3a61da70c0cb7991976248362f30319e88850c487b9b95bbf059e00" + [[package]] name = "memchr" version = "2.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3728d817d99e5ac407411fa471ff9800a778d88a24685968b36824eaf4bee400" +[[package]] +name = "memoffset" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "043175f069eda7b85febe4a74abbaeff828d9f8b448515d3151a14a3542811aa" +dependencies = [ + "autocfg", +] + +[[package]] +name = "mince" +version = "0.1.1-alpha.0" +source = "git+https://github.com/scipr-lab/zexe.git#85cac1770dddd4da79e9993c5d1dcb5732db08f5" +dependencies = [ + "quote 1.0.7", + "syn 1.0.34", +] + [[package]] name = "miniz_oxide" version = "0.4.0" @@ -459,6 +701,16 @@ dependencies = [ "num-traits 0.2.12", ] +[[package]] +name = "num-bigint" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e63899ad0da84ce718c14936262a41cee2c79c981fc0a0e7c7beb47d5a07e8c1" +dependencies = [ + "num-integer", + "num-traits 0.2.12", +] + [[package]] name = "num-bigint" version = "0.2.6" @@ -538,6 +790,15 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2839e79665f131bdb5782e51f2c6c9599c133c6098982a54c794358bf432529c" +[[package]] +name = "output_vt100" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53cdc5b785b7a58c5aad8216b3dfa114df64b0b06ae6e1501cef91df2fbdf8f9" +dependencies = [ + "winapi", +] + [[package]] name = "pairing_ce" version = "0.21.1" @@ -546,7 +807,7 @@ checksum = "bfc00d65b1d29e0a067a967fcea83d8db261c149f76a557ba73f0304f01cdfde" dependencies = [ "byteorder", "ff_ce 0.10.3", - "rand", + "rand 0.4.6", ] [[package]] @@ -625,12 +886,36 @@ dependencies = [ "syn 1.0.34", ] +[[package]] +name = "pin-project-lite" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e555d9e657502182ac97b539fb3dae8b79cda19e3e4f8ffb5e8de4f18df93c95" + [[package]] name = "pin-utils" version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" +[[package]] +name = "ppv-lite86" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c36fa947111f5c62a733b652544dd0016a43ce89619538a8ef92724a6f501a20" + +[[package]] +name = "pretty_assertions" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f81e1644e1b54f5a68959a29aa86cde704219254669da328ecfdf6a1f09d427" +dependencies = [ + "ansi_term", + "ctor", + "difference", + "output_vt100", +] + [[package]] name = "proc-macro2" version = "0.4.30" @@ -667,6 +952,27 @@ dependencies = [ "proc-macro2 1.0.18", ] +[[package]] +name = "r1cs-core" +version = "0.1.1-alpha.0" +source = "git+https://github.com/scipr-lab/zexe.git#85cac1770dddd4da79e9993c5d1dcb5732db08f5" +dependencies = [ + "algebra-core", + "tracing", + "tracing-subscriber", +] + +[[package]] +name = "r1cs-std" +version = "0.1.1-alpha.0" +source = "git+https://github.com/scipr-lab/zexe.git#85cac1770dddd4da79e9993c5d1dcb5732db08f5" +dependencies = [ + "algebra", + "derivative", + "r1cs-core", + "tracing", +] + [[package]] name = "rand" version = "0.4.6" @@ -680,6 +986,29 @@ dependencies = [ "winapi", ] +[[package]] +name = "rand" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a6b1679d49b24bbfe0c803429aa1874472f50d9b363131f0e89fc356b544d03" +dependencies = [ + "getrandom", + "libc", + "rand_chacha", + "rand_core 0.5.1", + "rand_hc", +] + +[[package]] +name = "rand_chacha" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4c8ed856279c9737206bf725bf36935d8666ead7aa69b52be55af369d193402" +dependencies = [ + "ppv-lite86", + "rand_core 0.5.1", +] + [[package]] name = "rand_core" version = "0.3.1" @@ -695,6 +1024,49 @@ version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9c33a3c44ca05fa6f1807d8e6743f3824e8509beca625669633be0acbdf509dc" +[[package]] +name = "rand_core" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90bde5296fc891b0cef12a6d03ddccc162ce7b2aff54160af9338f8d40df6d19" +dependencies = [ + "getrandom", +] + +[[package]] +name = "rand_hc" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca3129af7b92a17112d59ad498c6f81eaf463253766b90396d39ea7a39d6613c" +dependencies = [ + "rand_core 0.5.1", +] + +[[package]] +name = "rayon" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dcf6960dc9a5b4ee8d3e4c5787b4a112a8818e0290a42ff664ad60692fdf2032" +dependencies = [ + "autocfg", + "crossbeam-deque", + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8c4fec834fb6e6d2dd5eece3c7b432a52f0ba887cf40e595190c4107edc08bf" +dependencies = [ + "crossbeam-channel", + "crossbeam-deque", + "crossbeam-utils", + "lazy_static", + "num_cpus", +] + [[package]] name = "rdrand" version = "0.4.0" @@ -747,12 +1119,42 @@ version = "0.1.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4c691c0e608126e00913e33f0ccf3727d5fc84573623b8d65b2df340b5201783" +[[package]] +name = "rustc_version" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "138e3e0acb6c9fb258b19b67cb8abd63c00679d2851805ea151465464fe9030a" +dependencies = [ + "semver", +] + [[package]] name = "ryu" version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "71d301d4193d031abdd79ff7e3dd721168a9572ef3fe51a1517aba235bd8f86e" +[[package]] +name = "scopeguard" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd" + +[[package]] +name = "semver" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d7eb9ef2c18661902cc47e535f9bc51b78acd254da71d375c2f6720d9a40403" +dependencies = [ + "semver-parser", +] + +[[package]] +name = "semver-parser" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3" + [[package]] name = "serde" version = "1.0.114" @@ -832,6 +1234,12 @@ version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c111b5bd5695e56cffe5129854aa230b39c93a305372fdbb2668ca2394eea9f8" +[[package]] +name = "subtle" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d67a5a62ba6e01cb2192ff309324cb4875d0c451d55fe2319433abe7a05a8ee" + [[package]] name = "syn" version = "0.15.44" @@ -875,6 +1283,47 @@ dependencies = [ "lazy_static", ] +[[package]] +name = "tracing" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b0987850db3733619253fe60e17cb59b82d37c7e6c0236bb81e4d6b87c879f27" +dependencies = [ + "cfg-if", + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80e0ccfc3378da0cce270c946b676a376943f5cd16aeba64568e7939806f4ada" +dependencies = [ + "proc-macro2 1.0.18", + "quote 1.0.7", + "syn 1.0.34", +] + +[[package]] +name = "tracing-core" +version = "0.1.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f50de3927f93d202783f4513cda820ab47ef17f624b03c096e86ef00c67e6b5f" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "tracing-subscriber" +version = "0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82bb5079aa76438620837198db8a5c529fb9878c730bc2b28179b0241cf04c10" +dependencies = [ + "tracing-core", +] + [[package]] name = "typed-arena" version = "1.7.0" @@ -911,6 +1360,16 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f7fe0bb3479651439c9112f72b6c505038574c9fbb575ed1bf3b797fa39dd564" +[[package]] +name = "unroll" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85890b49d9724df33edc575c4bacd5b0081977da22c4c4984d0c62ec44ed6e09" +dependencies = [ + "quote 0.6.13", + "syn 0.15.44", +] + [[package]] name = "utf8-ranges" version = "1.0.4" @@ -923,6 +1382,12 @@ version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6a02e4885ed3bc0f2de90ea6dd45ebcbb66dacffe03547fadbb0eeae2770887d" +[[package]] +name = "wasi" +version = "0.9.0+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cccddf32554fecc6acb585f82a32a72e28b48f8c4c1883ddfeeeaa96f7d8e519" + [[package]] name = "wasm-bindgen" version = "0.2.65" @@ -1028,18 +1493,26 @@ version = "0.1.0" [[package]] name = "zokrates_core" -version = "0.5.0" +version = "0.5.1" dependencies = [ + "algebra", + "algebra-core", "bellman_ce", "bincode 0.8.0", + "crypto-primitives", "csv", "ff_ce 0.9.0", + "gm17", "hex", "lazy_static", "num", - "num-bigint", + "num-bigint 0.1.44", "pairing_ce", - "rand", + "pretty_assertions", + "r1cs-core", + "r1cs-std", + "rand 0.4.6", + "rand 0.7.3", "reduce", "regex", "serde", @@ -1056,10 +1529,12 @@ dependencies = [ name = "zokrates_field" version = "0.3.7" dependencies = [ + "algebra", + "algebra-core", "bellman_ce", "bincode 0.8.0", "lazy_static", - "num-bigint", + "num-bigint 0.2.6", "num-integer", "num-traits 0.2.12", "serde", @@ -1070,7 +1545,7 @@ dependencies = [ [[package]] name = "zokrates_js" -version = "1.0.24" +version = "1.0.25" dependencies = [ "bincode 1.3.1", "console_error_panic_hook", diff --git a/zokrates_js/package-lock.json b/zokrates_js/package-lock.json index 1bd95d2df..a405cf014 100644 --- a/zokrates_js/package-lock.json +++ b/zokrates_js/package-lock.json @@ -1,6 +1,6 @@ { "name": "zokrates-js", - "version": "1.0.24", + "version": "1.0.25", "lockfileVersion": 1, "requires": true, "dependencies": { diff --git a/zokrates_js/src/lib.rs b/zokrates_js/src/lib.rs index f888f9a11..5ab875028 100644 --- a/zokrates_js/src/lib.rs +++ b/zokrates_js/src/lib.rs @@ -8,8 +8,11 @@ use zokrates_common::Resolver; use zokrates_core::compile::{compile as core_compile, CompilationArtifacts, CompileError}; use zokrates_core::imports::Error; use zokrates_core::ir; -use zokrates_core::proof_system::bellman::groth16::G16; -use zokrates_core::proof_system::{ProofSystem, SolidityAbi}; +use zokrates_core::proof_system::bellman::Bellman; +use zokrates_core::proof_system::scheme::groth16::G16; +use zokrates_core::proof_system::scheme::{SolidityCompatibleScheme}; +use zokrates_core::proof_system::solidity::SolidityAbi; +use zokrates_core::proof_system::Backend; use zokrates_core::typed_absy::abi::Abi; use zokrates_core::typed_absy::types::Signature; use zokrates_field::Bn128Field; @@ -97,7 +100,6 @@ pub fn compile( source: JsValue, location: JsValue, resolve_callback: &js_sys::Function, - config: JsValue, ) -> Result { let resolver = JsResolver::new(resolve_callback); @@ -161,7 +163,7 @@ pub fn compute_witness(artifacts: JsValue, args: JsValue) -> Result Result { let input: Vec = program.into_serde().unwrap(); let program_flattened = deserialize_program(&input)?; - let keypair = G16::setup(program_flattened); + let keypair = >::setup(program_flattened); Ok(JsValue::from_serde(&keypair).unwrap()) } @@ -170,7 +172,7 @@ pub fn export_solidity_verifier(vk: JsValue, abi_version: JsValue) -> Result>::export_solidity_verifier( + let verifier = >::export_solidity_verifier( vk.into_serde().unwrap(), abi_version, ); @@ -188,7 +190,11 @@ pub fn generate_proof(program: JsValue, witness: JsValue, pk: JsValue) -> Result .map_err(|err| JsValue::from_str(&format!("Could not read witness: {}", err)))?; let proving_key: Vec = pk.into_serde().unwrap(); - let proof = G16::generate_proof(program_flattened, ir_witness, proving_key); + let proof = >::generate_proof( + program_flattened, + ir_witness, + proving_key, + ); Ok(JsValue::from_serde(&proof).unwrap()) } From 409ae350f73e171603f7b7d22c451c2c053b03e2 Mon Sep 17 00:00:00 2001 From: dark64 Date: Mon, 5 Oct 2020 13:16:49 +0200 Subject: [PATCH 32/54] remove FqeRepr --- zokrates_core/src/proof_system/zexe/gm17.rs | 10 ++--- zokrates_field/src/bls12_377.rs | 4 +- zokrates_field/src/bn128.rs | 4 +- zokrates_field/src/lib.rs | 49 --------------------- 4 files changed, 9 insertions(+), 58 deletions(-) diff --git a/zokrates_core/src/proof_system/zexe/gm17.rs b/zokrates_core/src/proof_system/zexe/gm17.rs index 24b04b9ab..672b12ee5 100644 --- a/zokrates_core/src/proof_system/zexe/gm17.rs +++ b/zokrates_core/src/proof_system/zexe/gm17.rs @@ -12,9 +12,9 @@ use ir::{Prog, Witness}; use proof_system::scheme::gm17::{NotBw6_761Field, ProofPoints, VerificationKey, GM17}; use proof_system::scheme::Scheme; use proof_system::zexe::Zexe; -use proof_system::{Backend, Fq2, Proof, SetupKeypair}; +use proof_system::{Backend, Proof, SetupKeypair}; -impl + NotBw6_761Field> Backend for Zexe { +impl Backend for Zexe { fn setup(program: Prog) -> SetupKeypair<>::VerificationKey> { let parameters = Computation::without_witness(program).setup(); @@ -204,7 +204,7 @@ impl Backend for Zexe { pub mod serialization { use algebra_core::{FromBytes, PairingEngine}; - use proof_system::{Fq, Fq2, G1Affine, G2Affine, G2AffineFq}; + use proof_system::{G1Affine, G2Affine, G2AffineFq}; use zokrates_field::ZexeFieldExtensions; #[inline] @@ -225,7 +225,7 @@ pub mod serialization { ::G1Affine::read(&*bytes).unwrap() } - pub fn to_g2>( + pub fn to_g2( g2: G2Affine, ) -> ::G2Affine { let mut bytes = vec![]; @@ -238,7 +238,7 @@ pub mod serialization { ::G2Affine::read(&*bytes).unwrap() } - pub fn to_g2_fq>( + pub fn to_g2_fq( g2: G2AffineFq, ) -> ::G2Affine { let mut bytes = vec![]; diff --git a/zokrates_field/src/bls12_377.rs b/zokrates_field/src/bls12_377.rs index e0df0a84a..24b28c892 100644 --- a/zokrates_field/src/bls12_377.rs +++ b/zokrates_field/src/bls12_377.rs @@ -1,7 +1,7 @@ -use algebra::bls12_377::{Bls12_377, Fq2}; +use algebra::bls12_377::{Bls12_377}; prime_field!( b"8444461749428370424248824938781546531375899335154063827935233455917409239041", "bls12_377" ); -zexe_extensions!(Bls12_377, Fq2); +zexe_extensions!(Bls12_377); diff --git a/zokrates_field/src/bn128.rs b/zokrates_field/src/bn128.rs index 4d1865620..c2314f87b 100644 --- a/zokrates_field/src/bn128.rs +++ b/zokrates_field/src/bn128.rs @@ -1,4 +1,4 @@ -use algebra::bn254::{Bn254, Fq2 as Bn254_Fq2}; +use algebra::bn254::{Bn254}; use bellman_ce::pairing::bn256::{Bn256, Fq2}; prime_field!( @@ -7,7 +7,7 @@ prime_field!( ); bellman_extensions!(Bn256, Fq2); -zexe_extensions!(Bn254, Bn254_Fq2); +zexe_extensions!(Bn254); #[cfg(test)] mod tests { diff --git a/zokrates_field/src/lib.rs b/zokrates_field/src/lib.rs index 6cbec55dd..cf7000d10 100644 --- a/zokrates_field/src/lib.rs +++ b/zokrates_field/src/lib.rs @@ -33,11 +33,9 @@ pub trait BellmanFieldExtensions { pub trait ZexeFieldExtensions { /// An associated type to be able to operate with zexe ff traits type ZexeEngine: PairingEngine; - type FqeRepr; fn from_zexe(e: ::Fr) -> Self; fn into_zexe(self) -> ::Fr; - fn new_fqe(value: Self::FqeRepr) -> ::Fqe; } pub trait Field: @@ -544,7 +542,6 @@ mod prime_field { impl ZexeFieldExtensions for FieldPrime { type ZexeEngine = $zexe_type; - type FqeRepr = String; fn from_zexe(e: ::Fr) -> Self { use algebra_core::{BigInteger, PrimeField}; @@ -558,52 +555,6 @@ mod prime_field { let s = self.to_dec_string(); ::Fr::from_str(&s).unwrap() } - - fn new_fqe( - value: Self::FqeRepr, - ) -> ::Fqe { - use core::str::FromStr; - ::Fqe::from_str(value.as_str()) - .unwrap() - } - } - }; - ($zexe_type:ty, $fq2_type:ident) => { - use crate::ZexeFieldExtensions; - - impl ZexeFieldExtensions for FieldPrime { - type ZexeEngine = $zexe_type; - type FqeRepr = (String, String); - - fn from_zexe(e: ::Fr) -> Self { - use algebra_core::{BigInteger, PrimeField}; - let mut res: Vec = vec![]; - e.into_repr().write_le(&mut res).unwrap(); - Self::from_byte_vector(res) - } - - fn into_zexe(self) -> ::Fr { - use core::str::FromStr; - let s = self.to_dec_string(); - ::Fr::from_str(&s).unwrap() - } - - fn new_fqe( - value: Self::FqeRepr, - ) -> ::Fqe { - use core::str::FromStr; - $fq2_type { - c0: ::Fq::from_str( - value.0.as_str(), - ) - .unwrap(), - c1: ::Fq::from_str( - value.1.as_str(), - ) - .unwrap(), - _parameters: core::marker::PhantomData, - } - } } }; } From 978877a2bc67188734ed26f422940c78c9232c9a Mon Sep 17 00:00:00 2001 From: dark64 Date: Mon, 5 Oct 2020 14:11:25 +0200 Subject: [PATCH 33/54] update num-bigint version --- Cargo.lock | 16 +++------------- zokrates_core/Cargo.toml | 2 +- zokrates_field/src/lib.rs | 1 + 3 files changed, 5 insertions(+), 14 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 56dc08852..f5547fdcf 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -617,7 +617,7 @@ version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "50c052fa6d4c2f12305ec364bfb8ef884836f3f61ea015b202372ff996d1ac4b" dependencies = [ - "num-bigint 0.2.6", + "num-bigint", "num-integer", "num-traits 0.2.12", "proc-macro2 1.0.19", @@ -997,16 +997,6 @@ dependencies = [ "num-traits 0.2.12", ] -[[package]] -name = "num-bigint" -version = "0.1.44" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e63899ad0da84ce718c14936262a41cee2c79c981fc0a0e7c7beb47d5a07e8c1" -dependencies = [ - "num-integer", - "num-traits 0.2.12", -] - [[package]] name = "num-bigint" version = "0.2.6" @@ -2078,7 +2068,7 @@ dependencies = [ "hex", "lazy_static", "num", - "num-bigint 0.1.44", + "num-bigint", "pairing_ce", "pretty_assertions", "r1cs-core", @@ -2115,7 +2105,7 @@ dependencies = [ "bellman_ce", "bincode", "lazy_static", - "num-bigint 0.2.6", + "num-bigint", "num-integer", "num-traits 0.2.12", "rand 0.4.6", diff --git a/zokrates_core/Cargo.toml b/zokrates_core/Cargo.toml index bd562c0e0..764651fb6 100644 --- a/zokrates_core/Cargo.toml +++ b/zokrates_core/Cargo.toml @@ -14,7 +14,7 @@ multicore = ["bellman_ce/multicore"] [dependencies] num = { version = "0.1.36", default-features = false } -num-bigint = { version = "0.1.36", default-features = false } +num-bigint = { version = "0.2", default-features = false } lazy_static = "1.4" typed-arena = "1.4.1" reduce = "0.1.1" diff --git a/zokrates_field/src/lib.rs b/zokrates_field/src/lib.rs index e6a3263b0..3a1b5f3a0 100644 --- a/zokrates_field/src/lib.rs +++ b/zokrates_field/src/lib.rs @@ -4,6 +4,7 @@ // @author Jacob Eberhardt // @date 2017 extern crate algebra_core; +extern crate num_bigint; use algebra_core::PairingEngine; use bellman_ce::pairing::ff::ScalarEngine; From aa81666d8a2eaac789a4ca545be12ad1de4b35ec Mon Sep 17 00:00:00 2001 From: dark64 Date: Mon, 5 Oct 2020 14:28:28 +0200 Subject: [PATCH 34/54] remove old imports --- zokrates_core/tests/wasm.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/zokrates_core/tests/wasm.rs b/zokrates_core/tests/wasm.rs index fd9a89a63..b30d0318e 100644 --- a/zokrates_core/tests/wasm.rs +++ b/zokrates_core/tests/wasm.rs @@ -6,10 +6,9 @@ extern crate zokrates_field; use wasm_bindgen_test::*; use zokrates_core::flat_absy::FlatVariable; use zokrates_core::ir::{Function, Interpreter, Prog, Statement}; -use zokrates_core::proof_system::{Backend, ProofSystem}; +use zokrates_core::proof_system::Backend; use zokrates_field::Bn128Field; -use zokrates_core::proof_system::bellman::groth16::G16; use zokrates_core::proof_system::bellman::Bellman; use zokrates_core::proof_system::scheme::groth16::G16; From 23791b2052ebb24a6226d27ba6f54e87c4cbbe67 Mon Sep 17 00:00:00 2001 From: dark64 Date: Mon, 5 Oct 2020 15:16:52 +0200 Subject: [PATCH 35/54] stdlib cleanup --- .../book/hashexample_updated_bls12_377.zok | 7 ------- .../book/hashexample_updated_bw6_761.zok | 7 ------- .../hashes/sha256/512bitPacked_bls12_377.zok | 19 ------------------- .../hashes/sha256/512bitPacked_bw6_761.zok | 19 ------------------- .../bool/nonStrictUnpack256.zok | 13 ------------- .../utils/pack_bls12_377/bool/unpack128.zok | 11 ----------- .../pack_bls12_377/u32/nonStrictUnpack256.zok | 12 ------------ .../utils/pack_bls12_377/u32/unpack128.zok | 7 ------- .../utils/pack_bw6_761/bool/unpack128.zok | 11 ----------- .../utils/pack_bw6_761/bool/unpack256.zok | 9 --------- .../utils/pack_bw6_761/u32/unpack128.zok | 7 ------- .../utils/pack_bw6_761/u32/unpack256.zok | 8 -------- zokrates_stdlib/stdlib/verifier/verifier.zok | 6 ------ .../stdlib/verifier/verifier11.zok | 7 ------- zokrates_stdlib/stdlib/verifier/verifier2.zok | 5 ----- zokrates_stdlib/stdlib/verifier/verifier5.zok | 6 ------ zokrates_stdlib/stdlib/verifier/verifier7.zok | 5 ----- 17 files changed, 159 deletions(-) delete mode 100644 zokrates_cli/examples/book/hashexample_updated_bls12_377.zok delete mode 100644 zokrates_cli/examples/book/hashexample_updated_bw6_761.zok delete mode 100644 zokrates_stdlib/stdlib/hashes/sha256/512bitPacked_bls12_377.zok delete mode 100644 zokrates_stdlib/stdlib/hashes/sha256/512bitPacked_bw6_761.zok delete mode 100644 zokrates_stdlib/stdlib/utils/pack_bls12_377/bool/nonStrictUnpack256.zok delete mode 100644 zokrates_stdlib/stdlib/utils/pack_bls12_377/bool/unpack128.zok delete mode 100644 zokrates_stdlib/stdlib/utils/pack_bls12_377/u32/nonStrictUnpack256.zok delete mode 100644 zokrates_stdlib/stdlib/utils/pack_bls12_377/u32/unpack128.zok delete mode 100644 zokrates_stdlib/stdlib/utils/pack_bw6_761/bool/unpack128.zok delete mode 100644 zokrates_stdlib/stdlib/utils/pack_bw6_761/bool/unpack256.zok delete mode 100644 zokrates_stdlib/stdlib/utils/pack_bw6_761/u32/unpack128.zok delete mode 100644 zokrates_stdlib/stdlib/utils/pack_bw6_761/u32/unpack256.zok delete mode 100644 zokrates_stdlib/stdlib/verifier/verifier.zok delete mode 100644 zokrates_stdlib/stdlib/verifier/verifier11.zok delete mode 100644 zokrates_stdlib/stdlib/verifier/verifier2.zok delete mode 100644 zokrates_stdlib/stdlib/verifier/verifier5.zok delete mode 100644 zokrates_stdlib/stdlib/verifier/verifier7.zok diff --git a/zokrates_cli/examples/book/hashexample_updated_bls12_377.zok b/zokrates_cli/examples/book/hashexample_updated_bls12_377.zok deleted file mode 100644 index 2634226ad..000000000 --- a/zokrates_cli/examples/book/hashexample_updated_bls12_377.zok +++ /dev/null @@ -1,7 +0,0 @@ -import "hashes/sha256/512bitPacked_bls12_377" as sha256packed - -def main(private field a, private field b, private field c, private field d) -> (field): - field[2] h = sha256packed([a, b, c, d]) - h[0] == 263561599766550617289250058199814760685 - h[1] == 65303172752238645975888084098459749904 - return 1 diff --git a/zokrates_cli/examples/book/hashexample_updated_bw6_761.zok b/zokrates_cli/examples/book/hashexample_updated_bw6_761.zok deleted file mode 100644 index 82fcc4afd..000000000 --- a/zokrates_cli/examples/book/hashexample_updated_bw6_761.zok +++ /dev/null @@ -1,7 +0,0 @@ -import "hashes/sha256/512bitPacked_bw6_761" as sha256packed - -def main(private field a, private field b, private field c, private field d) -> (field): - field[2] h = sha256packed([a, b, c, d]) - h[0] == 263561599766550617289250058199814760685 - h[1] == 65303172752238645975888084098459749904 - return 1 diff --git a/zokrates_stdlib/stdlib/hashes/sha256/512bitPacked_bls12_377.zok b/zokrates_stdlib/stdlib/hashes/sha256/512bitPacked_bls12_377.zok deleted file mode 100644 index 9303f6af8..000000000 --- a/zokrates_stdlib/stdlib/hashes/sha256/512bitPacked_bls12_377.zok +++ /dev/null @@ -1,19 +0,0 @@ -import "../../utils/pack/u32/pack128" as pack128 -import "../../utils/pack_bls12_377/u32/unpack128" as unpack128 -import "./512bitPadded" as sha256 -// A function that takes an array of 4 field elements as inputs, unpacks each of them to 128 -// bits (big endian), concatenates them and applies sha256. -// It then returns an array of two field elements, each representing 128 bits of the result. -def main(field[4] preimage) -> (field[2]): - - u32[4] a_bits = unpack128(preimage[0]) - u32[4] b_bits = unpack128(preimage[1]) - u32[4] c_bits = unpack128(preimage[2]) - u32[4] d_bits = unpack128(preimage[3]) - - u32[8] lhs = [...a_bits, ...b_bits] - u32[8] rhs = [...c_bits, ...d_bits] - - u32[8] r = sha256(lhs, rhs) - - return [pack128(r[0..4]), pack128(r[4..8])] diff --git a/zokrates_stdlib/stdlib/hashes/sha256/512bitPacked_bw6_761.zok b/zokrates_stdlib/stdlib/hashes/sha256/512bitPacked_bw6_761.zok deleted file mode 100644 index 07737fba4..000000000 --- a/zokrates_stdlib/stdlib/hashes/sha256/512bitPacked_bw6_761.zok +++ /dev/null @@ -1,19 +0,0 @@ -import "../../utils/pack/u32/pack128" as pack128 -import "../../utils/pack_bw6_761/u32/unpack128" as unpack128 -import "./512bitPadded" as sha256 -// A function that takes an array of 4 field elements as inputs, unpacks each of them to 128 -// bits (big endian), concatenates them and applies sha256. -// It then returns an array of two field elements, each representing 128 bits of the result. -def main(field[4] preimage) -> (field[2]): - - u32[4] a_bits = unpack128(preimage[0]) - u32[4] b_bits = unpack128(preimage[1]) - u32[4] c_bits = unpack128(preimage[2]) - u32[4] d_bits = unpack128(preimage[3]) - - u32[8] lhs = [...a_bits, ...b_bits] - u32[8] rhs = [...c_bits, ...d_bits] - - u32[8] r = sha256(lhs, rhs) - - return [pack128(r[0..4]), pack128(r[4..8])] diff --git a/zokrates_stdlib/stdlib/utils/pack_bls12_377/bool/nonStrictUnpack256.zok b/zokrates_stdlib/stdlib/utils/pack_bls12_377/bool/nonStrictUnpack256.zok deleted file mode 100644 index 2ca49e794..000000000 --- a/zokrates_stdlib/stdlib/utils/pack_bls12_377/bool/nonStrictUnpack256.zok +++ /dev/null @@ -1,13 +0,0 @@ -#pragma curve bls12_377 - -// Non-strict version: -// Note that this does not strongly enforce that the commitment is -// in the field. - -import "EMBED/unpack" as unpack - -def main(field i) -> (bool[256]): - - bool[253] b = unpack(i) - - return [false, false, false, ...b] diff --git a/zokrates_stdlib/stdlib/utils/pack_bls12_377/bool/unpack128.zok b/zokrates_stdlib/stdlib/utils/pack_bls12_377/bool/unpack128.zok deleted file mode 100644 index a2a4f0669..000000000 --- a/zokrates_stdlib/stdlib/utils/pack_bls12_377/bool/unpack128.zok +++ /dev/null @@ -1,11 +0,0 @@ -#pragma curve bls12_377 - -import "EMBED/unpack" as unpack - -def main(field i) -> (bool[128]): - - bool[253] b = unpack(i) - - b[0..125] == [false; 125] - - return b[125..253] diff --git a/zokrates_stdlib/stdlib/utils/pack_bls12_377/u32/nonStrictUnpack256.zok b/zokrates_stdlib/stdlib/utils/pack_bls12_377/u32/nonStrictUnpack256.zok deleted file mode 100644 index aa7938e90..000000000 --- a/zokrates_stdlib/stdlib/utils/pack_bls12_377/u32/nonStrictUnpack256.zok +++ /dev/null @@ -1,12 +0,0 @@ -#pragma curve bls12_377 - -// Non-strict version: -// Note that this does not strongly enforce that the commitment is -// in the field. - -import "../bool/nonStrictUnpack256" as unpack -import "../../casts/bool_256_to_u32_8" as from_bits - -def main(field i) -> (u32[8]): - - return from_bits(unpack(i)) diff --git a/zokrates_stdlib/stdlib/utils/pack_bls12_377/u32/unpack128.zok b/zokrates_stdlib/stdlib/utils/pack_bls12_377/u32/unpack128.zok deleted file mode 100644 index e4a5c8a42..000000000 --- a/zokrates_stdlib/stdlib/utils/pack_bls12_377/u32/unpack128.zok +++ /dev/null @@ -1,7 +0,0 @@ -#pragma curve bls12_377 - -import "../bool/unpack128" as unpack -import "../../casts/bool_128_to_u32_4" as from_bits - -def main(field i) -> (u32[4]): - return from_bits(unpack(i)) diff --git a/zokrates_stdlib/stdlib/utils/pack_bw6_761/bool/unpack128.zok b/zokrates_stdlib/stdlib/utils/pack_bw6_761/bool/unpack128.zok deleted file mode 100644 index 9d409ca6a..000000000 --- a/zokrates_stdlib/stdlib/utils/pack_bw6_761/bool/unpack128.zok +++ /dev/null @@ -1,11 +0,0 @@ -#pragma curve bw6_761 - -import "EMBED/unpack" as unpack - -def main(field i) -> (bool[128]): - - bool[377] b = unpack(i) - - b[0..249] == [false; 249] - - return b[249..377] diff --git a/zokrates_stdlib/stdlib/utils/pack_bw6_761/bool/unpack256.zok b/zokrates_stdlib/stdlib/utils/pack_bw6_761/bool/unpack256.zok deleted file mode 100644 index 528b82d24..000000000 --- a/zokrates_stdlib/stdlib/utils/pack_bw6_761/bool/unpack256.zok +++ /dev/null @@ -1,9 +0,0 @@ -#pragma curve bw6_761 - -import "EMBED/unpack" as unpack - -def main(field i) -> (bool[256]): - - bool[377] b = unpack(i) - - return b[121..377] diff --git a/zokrates_stdlib/stdlib/utils/pack_bw6_761/u32/unpack128.zok b/zokrates_stdlib/stdlib/utils/pack_bw6_761/u32/unpack128.zok deleted file mode 100644 index 60c4bfea4..000000000 --- a/zokrates_stdlib/stdlib/utils/pack_bw6_761/u32/unpack128.zok +++ /dev/null @@ -1,7 +0,0 @@ -#pragma curve bw6_761 - -import "../bool/unpack128" as unpack -import "../../casts/bool_128_to_u32_4" as from_bits - -def main(field i) -> (u32[4]): - return from_bits(unpack(i)) diff --git a/zokrates_stdlib/stdlib/utils/pack_bw6_761/u32/unpack256.zok b/zokrates_stdlib/stdlib/utils/pack_bw6_761/u32/unpack256.zok deleted file mode 100644 index 2df1a5a15..000000000 --- a/zokrates_stdlib/stdlib/utils/pack_bw6_761/u32/unpack256.zok +++ /dev/null @@ -1,8 +0,0 @@ -#pragma curve bw6_761 - -import "../bool/unpack256" as unpack -import "../../casts/bool_256_to_u32_8" as from_bits - -def main(field i) -> (u32[8]): - - return from_bits(unpack(i)) diff --git a/zokrates_stdlib/stdlib/verifier/verifier.zok b/zokrates_stdlib/stdlib/verifier/verifier.zok deleted file mode 100644 index 73eba84c3..000000000 --- a/zokrates_stdlib/stdlib/verifier/verifier.zok +++ /dev/null @@ -1,6 +0,0 @@ -import "EMBED/verify" as verify -// example 1: 137565092005752483748493407438327763169139684140423891873536662628835348517869074662555749289290034670067693169037 72139571997667283518811514205532104215070171737960966802266046947665847059478158336650654132833435721090714539943 86725433690642560275465877140013172902963956098212864793300066153420847889078693035332011673719502025725294990585 5146800790688495090295297863320679569880979262097341538384555974060527428246367729743910738374589247289694509183 157199182011055697109275070122107747397158636176744687490271844487778522970938361603946017952017323222854186826642 128090586433977047290346447727325500999106522203224969725245017120435221824003482965410390284669817584625949158873 242846623199219102294519092470464099825623835022514942761935861255734088072105280496775650976049574668812729130662 199921505013060736410377710379705670795076292689440680632141602368931503404334746204056411491487357103823503332942 1 51618593415644909171351110450182760129199316654826963313869818832752929804897864321134536534430976728900615574493 129682384015693681606749627075354770485732278447522042797230918116715222994717480287967421380069260326111848891300 107857260380611661817545871785573241453173005559353466744943663759160894873700339815411460161917475971920064634595 198808239332695609906436230326243511374923871415614564458695835008682643835220809594443748665087240319790636388914 139663165395409818512381293320009747384362319111063669584453545516359525050890910749415470506136892720148317704511 180466491348666697356845067337590354420817076670243268334418795137053732632868216373776444192344006242202729721425 199405876263141075669345345472147439761990370616069254341388185493501477564711863037613681367498080357858999679916 82183765193095559943855738550510401967141939864770641483020850096933741675629006592709947740972750263743759909116 235667818304241949879589814884998117773684690279805455790276812676255025603328770918165588989570429573000549876824 53093253378089142458938879297218091522595066859906784980660810891645284753970414026364610942918212374501042584933 179969579722769515604672675224061438662996395894430225591003910715298216804709963923217915070721924455120579075568 147441174419609628990639483938877108868825317673431519438840787340833142778801384629100279050711573860909344631695 51618593415644909171351110450182760129199316654826963313869818832752929804897864321134536534430976728900615574493 129682384015693681606749627075354770485732278447522042797230918116715222994717480287967421380069260326111848891300 107857260380611661817545871785573241453173005559353466744943663759160894873700339815411460161917475971920064634595 198808239332695609906436230326243511374923871415614564458695835008682643835220809594443748665087240319790636388914 167890330208433086376513978751711327580456562618444373895888579048783860907864303028081226255132693676348870774490 111470581238289600115537636964914822180221937524137085589416200459498429869257546865551678456382952847650208378004 23647036858389957111023283818345900025536766542464580440401268408908911718370015825168423272490268653569481837709 139814123882173489424127695867288972436731433127284838974098231559275365090908492483258528656413170189902424410309 - -def main(private field[8] proof, private field[1] inputs, private field[20] vk) -> (bool): - bool r = verify(proof, inputs, vk) - return r diff --git a/zokrates_stdlib/stdlib/verifier/verifier11.zok b/zokrates_stdlib/stdlib/verifier/verifier11.zok deleted file mode 100644 index f4b7d8b49..000000000 --- a/zokrates_stdlib/stdlib/verifier/verifier11.zok +++ /dev/null @@ -1,7 +0,0 @@ -import "EMBED/verify11" as verify -//example 11: -//180576598777597956957756674411932471179626448439455106956582253365876871683249139593000374395952678482586431471996 129896682429414509120415367653407067702977346485504662987110866696379336547035841003101601020777771480604662235531 140618491025274418301109981164048373443821571938856666201032232225404071122079600420102424167361052643333311505814 35511319933687798911182535185956618523883335245343396189637617751888154126403169573031872453167238868505634962630 92076313419063088301006996221947233437270049364160087713834777394922435937171052389744551892478790599158306729065 58641777955822281595677463401471119027871648279322151544894017935529470599743720850552565239388241009069677600586 240585579936300350369880807496332054834947661306083539553947307350523284245226471685370234370967395878240441381489 175437090400850066443607126309485237484234755382787510717820555198158230973404977075808086810062305892562539939751 1 1 1 1 1 1 1 1 1 1 1 51618593415644909171351110450182760129199316654826963313869818832752929804897864321134536534430976728900615574493 129682384015693681606749627075354770485732278447522042797230918116715222994717480287967421380069260326111848891300 107857260380611661817545871785573241453173005559353466744943663759160894873700339815411460161917475971920064634595 198808239332695609906436230326243511374923871415614564458695835008682643835220809594443748665087240319790636388914 139663165395409818512381293320009747384362319111063669584453545516359525050890910749415470506136892720148317704511 180466491348666697356845067337590354420817076670243268334418795137053732632868216373776444192344006242202729721425 199405876263141075669345345472147439761990370616069254341388185493501477564711863037613681367498080357858999679916 82183765193095559943855738550510401967141939864770641483020850096933741675629006592709947740972750263743759909116 235667818304241949879589814884998117773684690279805455790276812676255025603328770918165588989570429573000549876824 53093253378089142458938879297218091522595066859906784980660810891645284753970414026364610942918212374501042584933 179969579722769515604672675224061438662996395894430225591003910715298216804709963923217915070721924455120579075568 147441174419609628990639483938877108868825317673431519438840787340833142778801384629100279050711573860909344631695 51618593415644909171351110450182760129199316654826963313869818832752929804897864321134536534430976728900615574493 129682384015693681606749627075354770485732278447522042797230918116715222994717480287967421380069260326111848891300 107857260380611661817545871785573241453173005559353466744943663759160894873700339815411460161917475971920064634595 198808239332695609906436230326243511374923871415614564458695835008682643835220809594443748665087240319790636388914 74473370268583513226742071824183380959343491709864497000069583251051491218378271128058280505762658701649336700610 8042120839904039859427126135683532302853384318330655732497454596370172606609424165946699012698522855183164615742 48113552820580812615299530751965809113824351315507267985259211734545009625156590364969208630831872009971019881095 184286009694266500294241220994396355768771687925244871057992199400679141682673068357985960870480562786827785514647 258010892514565820771340046208430728985689918257553826667699138618276913747497993147224445542041747518926076657444 156224845357165318366127253343134132579198020111918390673381505917386051635073774414133110832019181592877711592147 34250874412427177101956825570689301734486366411422669130606100650631724850120786376783453950959454211404519396138 15232115502723101185022390200571788304264525913758172782681121820750618999953227441949204761797443778999514257959 180682466264291366123957019062858099622796267859775231182052327492964034121628958390811801658684995117759344292523 140977727103342853793125612611276737293973539553648054349362012327618491492141055105888883032009189910294082130884 222863322180656999657454679968842236454663240101722811602470906614063901804583731655580281410698252163427126673574 127948824128358819520739025701724303303499418397290798461189656453468101084083218846665849459483446809989414129043 98443110527106282678378056651586701507595957714632256454949014755154639558360335768640841917309024595540917418141 205898070965276093282811755696939051185893888113975154504381356320346053166756710926753384795442629528557413569633 246298678035372203903360461623657954034069993484940506276427001628835540508223269426571254977496748180554098061785 74710034508255692511147359056375315491900345465811843921390300276905416635910535330513770119220452718014940337252 87113734686857095508604356781359806430800803574520356431266883121340618434610002454654068776436483281963151930505 234215752331533285884132834908368198523408848395357436271801340008023952486347060885839222547112494277799085477989 174889204633134780239317685615800823899941230507322743332979881203106684840851704105215381694970326866402912505239 45037391177918313033324179193994049993825087354994487314974080330865879521518995190184996756163692444765649509518 10906324289738064648116695815493324679277753259311712249691249247721519543366558045781181738566358339162486035939 233077352232378063545260318732352861746177119368620023637949664743013570908993097684576412574468971257652225091900 99592389454713431373030999949865800058002638104396269776505697854265092845174600515742749508449978101189458843975 16608323192067079375216954181948784567580341488758491110819502323572714666114916156949780439840289431905615009653 - -def main(private field[8] proof, private field[11] inputs, private field[40] vk) -> (bool): - bool r = verify(proof, inputs, vk) - return r diff --git a/zokrates_stdlib/stdlib/verifier/verifier2.zok b/zokrates_stdlib/stdlib/verifier/verifier2.zok deleted file mode 100644 index e8b7bfec0..000000000 --- a/zokrates_stdlib/stdlib/verifier/verifier2.zok +++ /dev/null @@ -1,5 +0,0 @@ -import "EMBED/verify2" as verify -// example 2: 164298555920240567171627298841626553164387307801100206932765621770301745671127480295934416060193264163152298121842 87042439455682058715262775038415289233545142063964550163506969881877341479797681897553780336380107120716704452229 117091840725889231147418174639145513093696099016314204836454849021698720565281444634114282810250657616997403655551 151681850303907264044758829383549686214133948974764973910730833706662633290359870201865990950643165651562697226068 157173903756713063884406067857852985683836049595631244690679979236774695172095319963573144402094051720587909899511 224360929797754853449863520411222621945959181694180226273708042652077731101222105820273077282670369448262972664642 75930422051669910699719424339635257245829815388289458109152091598100563693265103871182868064183718952836702254749 52826734050451182118105919237239916350661359922129391517084871111552953163773715259396705887899427058578938397282 8146837541998854005210856160410543445136568755949189115586542258223627068570 1668167439870663604090590886367632908182802419513806606723693962684805704536 183756877468541630753146585558239220257733956043988301662130604090419880695931822363534849028114306663142781620978 124948497768969458321349233842600165934612985979136363333722058335618824769251038305467931750838114178657585227244 168665037344736886407419786364592474058046027005907144357207106724493462070604835406273235545111193408960307350688 143483302563261025873757274638742867381396658643934382355951553214146831337538779236117137288979693104622236937644 142234866212709361921964611956828211569064504089991720022626037670818089413914553983723519846154644483203701383927 83030278041453992599795341983122880951698754212783394772977893766630277061009300824458616332962111211337326815959 111388994941644087254670333917228679818265953207162157950861239649891343244035800755135003681348391177966779112639 17606113021281609292792936632855540789927216595917739780556312211291788131389684876014072485156264649775107443707 203775396060966035998653026240663707485672240454103403599120208635494150347654974871571140904619072222772968210238 175964161380710869785983079764799620932050509423609475930877656184191231779443866541995174739633737324526011302266 117822361184136773117138077518163207771973327287074140927312877196991173499427000814225474124015943711111993084971 48432799730390283060212971639737929381144412915912076067487930367373379225976418473542520288334436585964057159568 183756877468541630753146585558239220257733956043988301662130604090419880695931822363534849028114306663142781620978 124948497768969458321349233842600165934612985979136363333722058335618824769251038305467931750838114178657585227244 168665037344736886407419786364592474058046027005907144357207106724493462070604835406273235545111193408960307350688 143483302563261025873757274638742867381396658643934382355951553214146831337538779236117137288979693104622236937644 98575377817976877984505376915362689952299726995190465856304453136821602809503400814017285791936778917042311601923 29049914920122439269216362596690254978786929008065526828648806210182052820447137303700164953534251744567848210315 247421540801753608836388781765319482563465239279793914016794097164591193709900687660795593959567835948703004441112 171576131688175722033973226012975986646974209098474719354124277017895963944629843554905505415082792527102524842187 36452945603742174480809846596173046330626415529425427418990191505206643408029586685753686687186307268787553298917 16478751173230720924455000177111658936211240758820525716154084880588097364298192397724194448132614978776786626810 -def main(private field[8] proof, private field[2] inputs, private field[22] vk) -> (bool): - bool r = verify(proof, inputs, vk) - return r diff --git a/zokrates_stdlib/stdlib/verifier/verifier5.zok b/zokrates_stdlib/stdlib/verifier/verifier5.zok deleted file mode 100644 index d8ed7dbb1..000000000 --- a/zokrates_stdlib/stdlib/verifier/verifier5.zok +++ /dev/null @@ -1,6 +0,0 @@ -import "EMBED/verify5" as verify -// example 5: 93919249336145447019101190152747452017826655307318317336134204645089529294938687249349675012896492178179698056462 119479952869529695222449869042273592421082263133756665572756419827141653155349179162746946694464314138790060788395 187012311448238853329150903190626923892010001373021191392806609423170810095710131005171033885643902959539089683603 230632685518829110004032357128906884091930790776972192963197371461915285033679623246383782944040189845674474628527 222810708740359390955786116891658621075072058331828437357704819349257497072768210213447094562617057842513839045415 155670558596959485209689045544076213431355729043379491614908539870538354151171287053697534043795807269228220521147 118577412837689190926801237606303522128405770441812140046787693905660307771907171024272098406431452499717216388524 73570507725286622376017498186168530123004210096690494411449625395955945308178654274143435606120217496087112872722 1 1 1 1 1 51618593415644909171351110450182760129199316654826963313869818832752929804897864321134536534430976728900615574493 129682384015693681606749627075354770485732278447522042797230918116715222994717480287967421380069260326111848891300 107857260380611661817545871785573241453173005559353466744943663759160894873700339815411460161917475971920064634595 198808239332695609906436230326243511374923871415614564458695835008682643835220809594443748665087240319790636388914 139663165395409818512381293320009747384362319111063669584453545516359525050890910749415470506136892720148317704511 180466491348666697356845067337590354420817076670243268334418795137053732632868216373776444192344006242202729721425 199405876263141075669345345472147439761990370616069254341388185493501477564711863037613681367498080357858999679916 82183765193095559943855738550510401967141939864770641483020850096933741675629006592709947740972750263743759909116 235667818304241949879589814884998117773684690279805455790276812676255025603328770918165588989570429573000549876824 53093253378089142458938879297218091522595066859906784980660810891645284753970414026364610942918212374501042584933 179969579722769515604672675224061438662996395894430225591003910715298216804709963923217915070721924455120579075568 147441174419609628990639483938877108868825317673431519438840787340833142778801384629100279050711573860909344631695 51618593415644909171351110450182760129199316654826963313869818832752929804897864321134536534430976728900615574493 129682384015693681606749627075354770485732278447522042797230918116715222994717480287967421380069260326111848891300 107857260380611661817545871785573241453173005559353466744943663759160894873700339815411460161917475971920064634595 198808239332695609906436230326243511374923871415614564458695835008682643835220809594443748665087240319790636388914 120076180084881209888531776114516075870161610839218034649724489661582902994403939983384036202784199733754781809514 108247323514425357573116551602974749763748101138301248411725436628201306069372944288777336898282658880098836358205 191072882877685407863403051159805644453754642285350957598730659763912967522679197903762366275892752444032800376100 190308792587728064144634726932531336080818288705715281929284641270366737475459206589415281729930233513047751100660 176193892714694333432358027900572931298063110592192983736528658934647289078393803858591148623369841761720499723239 175492243600667145431965489414273208327390295701896119279372088851666270878626675822210191447285496209864196910000 131715089064560384857328709360130651614977927828805021539779329659078232797907167078669591158245052986186857710968 167387449188068280354762270007395301225835549789620606473695118528353750245815904097740789370385099166663069453835 216261737758274283670300649325473049279771553925087455704802154736789176952469730358764180200660820780933492532276 114850853973568449686480263957612650915252720326613370281382073655758711209867531143930686100626181477663370486040 204576089289721808336201218321080703123109733299162919594093436862578194664495302146644056590192897808154944340252 20188174310383303554697528706169585520532743043352500241293903902233951521133833350606257922541369887404532716106 - -def main(private field[8] proof, private field[5] inputs, private field[28] vk) -> (bool): - bool r = verify(proof, inputs, vk) - return r diff --git a/zokrates_stdlib/stdlib/verifier/verifier7.zok b/zokrates_stdlib/stdlib/verifier/verifier7.zok deleted file mode 100644 index 322d8f23c..000000000 --- a/zokrates_stdlib/stdlib/verifier/verifier7.zok +++ /dev/null @@ -1,5 +0,0 @@ -import "EMBED/verify7" as verify -// example 7: 46972797782523351218186489614847198664374643658260597400327879985608892118426663994615575137380606947996090255350 97327037761454721772628987557641667173982803815226074939030388313256847750679453662030014340564552288112090169529 71822737467433388849374158628670108030211399471356822465985883916021837689439757359036777993110548291752505062691 191270868708412251094772061837074611736561690177101014418543598378666562439632190898380559469845798775111925411790 54351367834716061611644221004362169239165291477806192962291463515281226570976184680139732399461733657239283441914 137005744531125000546690732669313281410842064835892281413530555983272434847876599080915960972304230621250761084860 173990490276586084389831216871032217817142548704567307077189444470989979136617559944056415876431889559306913637447 251601957761887841510604241303790077852036951914075649192617266842791920223989066838364087519035856691099866624579 1 1 1 1 1 1 1 51618593415644909171351110450182760129199316654826963313869818832752929804897864321134536534430976728900615574493 129682384015693681606749627075354770485732278447522042797230918116715222994717480287967421380069260326111848891300 107857260380611661817545871785573241453173005559353466744943663759160894873700339815411460161917475971920064634595 198808239332695609906436230326243511374923871415614564458695835008682643835220809594443748665087240319790636388914 139663165395409818512381293320009747384362319111063669584453545516359525050890910749415470506136892720148317704511 180466491348666697356845067337590354420817076670243268334418795137053732632868216373776444192344006242202729721425 199405876263141075669345345472147439761990370616069254341388185493501477564711863037613681367498080357858999679916 82183765193095559943855738550510401967141939864770641483020850096933741675629006592709947740972750263743759909116 235667818304241949879589814884998117773684690279805455790276812676255025603328770918165588989570429573000549876824 53093253378089142458938879297218091522595066859906784980660810891645284753970414026364610942918212374501042584933 179969579722769515604672675224061438662996395894430225591003910715298216804709963923217915070721924455120579075568 147441174419609628990639483938877108868825317673431519438840787340833142778801384629100279050711573860909344631695 51618593415644909171351110450182760129199316654826963313869818832752929804897864321134536534430976728900615574493 129682384015693681606749627075354770485732278447522042797230918116715222994717480287967421380069260326111848891300 107857260380611661817545871785573241453173005559353466744943663759160894873700339815411460161917475971920064634595 198808239332695609906436230326243511374923871415614564458695835008682643835220809594443748665087240319790636388914 128024038099966279712532974954626721226639442034536191955902283984624525643942494844141887189821650651299232049688 40470997851282200236266813568261134451531393381504151434057591199991495323243987248564615304641816355488014359082 108288075166525596098694289344516409529682857520864518292098201282870120911220482299172075573869327301383965166669 247662936938608007250903891967232825634209088331118930283814824807915751653426295318174176803090544586682099876679 123691913850893714657057958012510424780731232472489772757612700020409662702512807765513483468151386514556121114805 203626573280748469748292241276108814663387363672513944175062683659985523622899981218633473352045941058979323463007 180580682252327234761316195833771296215305351210614833403467305360311509075645261576291605706376579788974038151040 179254608507693030653305364386473270688611526108940446707328223772290792954553582796666834833492032905101796097377 139266909801485192197942561962746059603880134333715004586240832379216829479303052757458379479511497696222050650775 69314059888472889451168249892343638683500173731319144195764735525657758401544520396446885348961362667134552703375 134040696217540605957498067263237289722598870831642128192717367514648871374523331482853870460624398571080900924883 216453389860703781077149475255664923051107994081955178048776121283957786687835392603148292440674127177703538606195 27546062382896811593223904741344318148851578312205836582315714787716401492996749294167112422939029948209697721523 123289013959501133646735421839740917029121937658793105497482631238875151683421007672827445509499133882991659532687 122788408896515135389349214053396001909115973919305910336099521004470519848373725939176616720743513461133945634056 127960792463135144610279182271176527945265362362874875853793254337244967558867486101588611091004656274402156620606 -def main(private field[8] proof, private field[7] inputs, private field[32] vk) -> (bool): - bool r = verify(proof, inputs, vk) - return r From 4c245ba7551a1875418f12c16f590371df492e1b Mon Sep 17 00:00:00 2001 From: dark64 Date: Mon, 5 Oct 2020 15:32:31 +0200 Subject: [PATCH 36/54] update wasm-bindgen-test version --- zokrates_core/Cargo.toml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/zokrates_core/Cargo.toml b/zokrates_core/Cargo.toml index 764651fb6..5c83a5065 100644 --- a/zokrates_core/Cargo.toml +++ b/zokrates_core/Cargo.toml @@ -11,6 +11,7 @@ default = ["bellman_ce/nolog"] libsnark = ["cc", "cmake", "git2"] wasm = ["bellman_ce/wasm"] multicore = ["bellman_ce/multicore"] +zexe = [] [dependencies] num = { version = "0.1.36", default-features = false } @@ -46,7 +47,7 @@ r1cs-std = { git = "https://github.com/scipr-lab/zexe.git", features = ["bls12_3 [dev-dependencies] glob = "0.2.11" assert_cli = "0.5" -wasm-bindgen-test = "0.3.0" +wasm-bindgen-test = "^0.3.0" [build-dependencies] cc = { version = "1.0", features = ["parallel"], optional = true } From 950518664885d479a46225abbc58f13080c5e162 Mon Sep 17 00:00:00 2001 From: dark64 Date: Tue, 6 Oct 2020 12:46:43 +0200 Subject: [PATCH 37/54] separate zexe as a feature --- zokrates_cli/Cargo.toml | 2 +- zokrates_core/Cargo.toml | 16 ++++++++-------- zokrates_core/src/ir/interpreter.rs | 1 - zokrates_core/src/lib.rs | 6 ++++++ zokrates_core/src/proof_system/mod.rs | 1 + 5 files changed, 16 insertions(+), 10 deletions(-) diff --git a/zokrates_cli/Cargo.toml b/zokrates_cli/Cargo.toml index 9d74b9aed..a49e3b61f 100644 --- a/zokrates_cli/Cargo.toml +++ b/zokrates_cli/Cargo.toml @@ -15,7 +15,7 @@ bincode = "0.8.0" regex = "0.2" zokrates_field = { version = "0.3", path = "../zokrates_field" } zokrates_abi = { version = "0.1", path = "../zokrates_abi" } -zokrates_core = { version = "0.5", path = "../zokrates_core" } +zokrates_core = { version = "0.5", path = "../zokrates_core", features = ["zexe"] } zokrates_fs_resolver = { version = "0.5", path = "../zokrates_fs_resolver"} serde_json = "1.0" dirs = "3.0.1" diff --git a/zokrates_core/Cargo.toml b/zokrates_core/Cargo.toml index 5c83a5065..852830a51 100644 --- a/zokrates_core/Cargo.toml +++ b/zokrates_core/Cargo.toml @@ -11,7 +11,7 @@ default = ["bellman_ce/nolog"] libsnark = ["cc", "cmake", "git2"] wasm = ["bellman_ce/wasm"] multicore = ["bellman_ce/multicore"] -zexe = [] +zexe = ["gm17", "algebra-core", "r1cs-core", "algebra", "crypto-primitives", "r1cs-std"] [dependencies] num = { version = "0.1.36", default-features = false } @@ -36,13 +36,13 @@ rand_0_4 = { version = "0.4", package = "rand" } rand_0_7 = { version = "0.7", package = "rand" } csv = "1" pretty_assertions = "0.6.1" -bellman_ce = { version = "^0.3", default-features = false} -gm17 = { git = "https://github.com/scipr-lab/zexe.git", features = ["parallel"] } -algebra-core = { git = "https://github.com/scipr-lab/zexe.git", features = ["parallel"] } -r1cs-core = { git = "https://github.com/scipr-lab/zexe.git" } -algebra = { git = "https://github.com/scipr-lab/zexe.git", features = ["bn254", "bls12_377", "bw6_761", "parallel"] } -crypto-primitives = { git = "https://github.com/scipr-lab/zexe.git", features = ["parallel", "gm17", "r1cs"], default-features = false } -r1cs-std = { git = "https://github.com/scipr-lab/zexe.git", features = ["bls12_377", "parallel"] } +bellman_ce = { version = "^0.3", default-features = false } +gm17 = { git = "https://github.com/scipr-lab/zexe.git", features = ["parallel"], optional = true } +algebra-core = { git = "https://github.com/scipr-lab/zexe.git", features = ["parallel"], optional = true } +r1cs-core = { git = "https://github.com/scipr-lab/zexe.git", optional = true } +algebra = { git = "https://github.com/scipr-lab/zexe.git", features = ["bn254", "bls12_377", "bw6_761", "parallel"], optional = true } +crypto-primitives = { git = "https://github.com/scipr-lab/zexe.git", features = ["parallel", "gm17", "r1cs"], default-features = false, optional = true } +r1cs-std = { git = "https://github.com/scipr-lab/zexe.git", features = ["bls12_377", "parallel"], optional = true } [dev-dependencies] glob = "0.2.11" diff --git a/zokrates_core/src/ir/interpreter.rs b/zokrates_core/src/ir/interpreter.rs index d1b15d0b8..7cd235ec6 100644 --- a/zokrates_core/src/ir/interpreter.rs +++ b/zokrates_core/src/ir/interpreter.rs @@ -1,4 +1,3 @@ -extern crate algebra as zexe_algebra; use crate::flat_absy::flat_variable::FlatVariable; use crate::ir::{LinComb, Prog, QuadComb, Statement, Witness}; use ir::Directive; diff --git a/zokrates_core/src/lib.rs b/zokrates_core/src/lib.rs index 99e1dcdfb..7c2249f4e 100644 --- a/zokrates_core/src/lib.rs +++ b/zokrates_core/src/lib.rs @@ -8,18 +8,24 @@ extern crate serde_json; extern crate typed_arena; #[macro_use] extern crate serde_derive; +#[cfg(feature = "zexe")] extern crate algebra as zexe_algebra; +#[cfg(feature = "zexe")] extern crate algebra_core; extern crate bellman_ce as bellman; extern crate bincode; +#[cfg(feature = "zexe")] extern crate crypto_primitives; extern crate csv; extern crate ff_ce as ff; +#[cfg(feature = "zexe")] extern crate gm17 as zexe_gm17; extern crate hex; extern crate lazy_static; extern crate pairing_ce as pairing; +#[cfg(feature = "zexe")] extern crate r1cs_core; +#[cfg(feature = "zexe")] extern crate r1cs_std; extern crate rand_0_4; extern crate rand_0_7; diff --git a/zokrates_core/src/proof_system/mod.rs b/zokrates_core/src/proof_system/mod.rs index 79ab82cd3..6eb5b9735 100644 --- a/zokrates_core/src/proof_system/mod.rs +++ b/zokrates_core/src/proof_system/mod.rs @@ -1,6 +1,7 @@ pub mod bellman; #[cfg(feature = "libsnark")] pub mod libsnark; +#[cfg(feature = "zexe")] pub mod zexe; pub mod scheme; From b7270008d0dc02856ae18083d602db7150f59f50 Mon Sep 17 00:00:00 2001 From: dark64 Date: Tue, 6 Oct 2020 15:08:11 +0200 Subject: [PATCH 38/54] add verify to zokrates js --- Cargo.lock | 101 +------ zokrates_cli/Cargo.toml | 2 +- zokrates_core/Cargo.toml | 16 +- zokrates_core/src/lib.rs | 5 +- .../src/proof_system/bellman/groth16.rs | 5 +- zokrates_core/src/proof_system/mod.rs | 1 + zokrates_field/Cargo.toml | 6 +- zokrates_js/Cargo.lock | 284 +----------------- zokrates_js/Cargo.toml | 2 +- zokrates_js/index.d.ts | 16 +- zokrates_js/src/lib.rs | 21 +- zokrates_js/tests/tests.js | 27 ++ zokrates_js/wrapper.js | 3 + 13 files changed, 81 insertions(+), 408 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index f5547fdcf..bb6169e8e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -174,18 +174,6 @@ version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf1de2fe8c75bc145a2f577add951f8134889b4795d47466a54a5c846d691693" -[[package]] -name = "blake2" -version = "0.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94cb07b0da6a73955f8fb85d24c466778e70cda767a568229b104f0264089330" -dependencies = [ - "byte-tools", - "crypto-mac", - "digest", - "opaque-debug", -] - [[package]] name = "blake2b_simd" version = "0.5.10" @@ -405,36 +393,6 @@ dependencies = [ "lazy_static", ] -[[package]] -name = "crypto-mac" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4434400df11d95d556bac068ddfedd482915eb18fe8bea89bc80b6e4b1c179e5" -dependencies = [ - "generic-array", - "subtle", -] - -[[package]] -name = "crypto-primitives" -version = "0.1.1-alpha.0" -source = "git+https://github.com/scipr-lab/zexe.git#85cac1770dddd4da79e9993c5d1dcb5732db08f5" -dependencies = [ - "algebra-core", - "bench-utils", - "blake2", - "derivative", - "digest", - "ff-fft", - "gm17", - "groth16", - "r1cs-core", - "r1cs-std", - "rand 0.7.3", - "rayon", - "tracing", -] - [[package]] name = "csv" version = "1.1.3" @@ -802,19 +760,6 @@ dependencies = [ "rayon", ] -[[package]] -name = "groth16" -version = "0.1.1-alpha.0" -source = "git+https://github.com/scipr-lab/zexe.git#85cac1770dddd4da79e9993c5d1dcb5732db08f5" -dependencies = [ - "algebra-core", - "bench-utils", - "ff-fft", - "r1cs-core", - "rand 0.7.3", - "rayon", -] - [[package]] name = "hermit-abi" version = "0.1.15" @@ -1197,6 +1142,12 @@ dependencies = [ "syn 1.0.39", ] +[[package]] +name = "pin-project-lite" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e555d9e657502182ac97b539fb3dae8b79cda19e3e4f8ffb5e8de4f18df93c95" + [[package]] name = "pin-utils" version = "0.1.0" @@ -1282,17 +1233,6 @@ dependencies = [ "tracing-subscriber", ] -[[package]] -name = "r1cs-std" -version = "0.1.1-alpha.0" -source = "git+https://github.com/scipr-lab/zexe.git#85cac1770dddd4da79e9993c5d1dcb5732db08f5" -dependencies = [ - "algebra", - "derivative", - "r1cs-core", - "tracing", -] - [[package]] name = "rand" version = "0.4.6" @@ -1627,12 +1567,6 @@ version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8ea5119cdb4c55b55d432abb513a0429384878c15dde60cc77b1c99de1a95a6a" -[[package]] -name = "subtle" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d67a5a62ba6e01cb2192ff309324cb4875d0c451d55fe2319433abe7a05a8ee" - [[package]] name = "syn" version = "0.15.44" @@ -1717,31 +1651,20 @@ checksum = "238ce071d267c5710f9d31451efec16c5ee22de34df17cc05e56cbc92e967117" [[package]] name = "tracing" -version = "0.1.19" +version = "0.1.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6d79ca061b032d6ce30c660fded31189ca0b9922bf483cd70759f13a2d86786c" +checksum = "b0987850db3733619253fe60e17cb59b82d37c7e6c0236bb81e4d6b87c879f27" dependencies = [ "cfg-if", - "tracing-attributes", + "pin-project-lite", "tracing-core", ] -[[package]] -name = "tracing-attributes" -version = "0.1.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "80e0ccfc3378da0cce270c946b676a376943f5cd16aeba64568e7939806f4ada" -dependencies = [ - "proc-macro2 1.0.19", - "quote 1.0.7", - "syn 1.0.39", -] - [[package]] name = "tracing-core" -version = "0.1.16" +version = "0.1.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5bcf46c1f1f06aeea2d6b81f3c863d0930a596c86ad1920d4e5bad6dd1d7119a" +checksum = "f50de3927f93d202783f4513cda820ab47ef17f624b03c096e86ef00c67e6b5f" dependencies = [ "lazy_static", ] @@ -2059,7 +1982,6 @@ dependencies = [ "bincode", "cc", "cmake", - "crypto-primitives", "csv", "ff_ce 0.9.0", "git2", @@ -2072,7 +1994,6 @@ dependencies = [ "pairing_ce", "pretty_assertions", "r1cs-core", - "r1cs-std", "rand 0.4.6", "rand 0.7.3", "reduce", diff --git a/zokrates_cli/Cargo.toml b/zokrates_cli/Cargo.toml index a49e3b61f..c90c23e1a 100644 --- a/zokrates_cli/Cargo.toml +++ b/zokrates_cli/Cargo.toml @@ -15,7 +15,7 @@ bincode = "0.8.0" regex = "0.2" zokrates_field = { version = "0.3", path = "../zokrates_field" } zokrates_abi = { version = "0.1", path = "../zokrates_abi" } -zokrates_core = { version = "0.5", path = "../zokrates_core", features = ["zexe"] } +zokrates_core = { version = "0.5", path = "../zokrates_core", features = ["multicore", "zexe"] } zokrates_fs_resolver = { version = "0.5", path = "../zokrates_fs_resolver"} serde_json = "1.0" dirs = "3.0.1" diff --git a/zokrates_core/Cargo.toml b/zokrates_core/Cargo.toml index 852830a51..99f80beb1 100644 --- a/zokrates_core/Cargo.toml +++ b/zokrates_core/Cargo.toml @@ -7,11 +7,11 @@ readme = "README.md" build = "build.rs" [features] -default = ["bellman_ce/nolog"] +default = [] libsnark = ["cc", "cmake", "git2"] -wasm = ["bellman_ce/wasm"] +wasm = ["bellman_ce/nolog", "bellman_ce/wasm"] multicore = ["bellman_ce/multicore"] -zexe = ["gm17", "algebra-core", "r1cs-core", "algebra", "crypto-primitives", "r1cs-std"] +zexe = ["gm17", "algebra-core", "r1cs-core", "algebra"] [dependencies] num = { version = "0.1.36", default-features = false } @@ -37,12 +37,10 @@ rand_0_7 = { version = "0.7", package = "rand" } csv = "1" pretty_assertions = "0.6.1" bellman_ce = { version = "^0.3", default-features = false } -gm17 = { git = "https://github.com/scipr-lab/zexe.git", features = ["parallel"], optional = true } -algebra-core = { git = "https://github.com/scipr-lab/zexe.git", features = ["parallel"], optional = true } -r1cs-core = { git = "https://github.com/scipr-lab/zexe.git", optional = true } -algebra = { git = "https://github.com/scipr-lab/zexe.git", features = ["bn254", "bls12_377", "bw6_761", "parallel"], optional = true } -crypto-primitives = { git = "https://github.com/scipr-lab/zexe.git", features = ["parallel", "gm17", "r1cs"], default-features = false, optional = true } -r1cs-std = { git = "https://github.com/scipr-lab/zexe.git", features = ["bls12_377", "parallel"], optional = true } +gm17 = { git = "https://github.com/scipr-lab/zexe.git", features = ["parallel"], default-features = false, optional = true } +algebra-core = { git = "https://github.com/scipr-lab/zexe.git", features = ["parallel"], default-features = false, optional = true } +r1cs-core = { git = "https://github.com/scipr-lab/zexe.git", default-features = false, optional = true } +algebra = { git = "https://github.com/scipr-lab/zexe.git", features = ["bn254", "bls12_377", "bw6_761", "parallel"], default-features = false, optional = true } [dev-dependencies] glob = "0.2.11" diff --git a/zokrates_core/src/lib.rs b/zokrates_core/src/lib.rs index 7c2249f4e..41b16851c 100644 --- a/zokrates_core/src/lib.rs +++ b/zokrates_core/src/lib.rs @@ -8,14 +8,13 @@ extern crate serde_json; extern crate typed_arena; #[macro_use] extern crate serde_derive; + #[cfg(feature = "zexe")] extern crate algebra as zexe_algebra; #[cfg(feature = "zexe")] extern crate algebra_core; extern crate bellman_ce as bellman; extern crate bincode; -#[cfg(feature = "zexe")] -extern crate crypto_primitives; extern crate csv; extern crate ff_ce as ff; #[cfg(feature = "zexe")] @@ -25,8 +24,6 @@ extern crate lazy_static; extern crate pairing_ce as pairing; #[cfg(feature = "zexe")] extern crate r1cs_core; -#[cfg(feature = "zexe")] -extern crate r1cs_std; extern crate rand_0_4; extern crate rand_0_7; extern crate regex; diff --git a/zokrates_core/src/proof_system/bellman/groth16.rs b/zokrates_core/src/proof_system/bellman/groth16.rs index 3033d0b4f..abf20060a 100644 --- a/zokrates_core/src/proof_system/bellman/groth16.rs +++ b/zokrates_core/src/proof_system/bellman/groth16.rs @@ -115,11 +115,10 @@ mod serialization { pub fn to_g1( g1: G1Affine, ) -> ::G1Affine { - ::G1Affine::from_xy_checked( + ::G1Affine::from_xy_unchecked( from_hex(&g1.0).unwrap(), from_hex(&g1.1).unwrap(), ) - .unwrap() } pub fn to_g2( g2: G2Affine, @@ -127,7 +126,7 @@ mod serialization { // apparently the order is reversed let x = T::new_fq2(&(g2.0).1, &(g2.0).0); let y = T::new_fq2(&(g2.1).1, &(g2.1).0); - ::G2Affine::from_xy_checked(x, y).unwrap() + ::G2Affine::from_xy_unchecked(x, y) } } diff --git a/zokrates_core/src/proof_system/mod.rs b/zokrates_core/src/proof_system/mod.rs index 6eb5b9735..1aaf2f7e6 100644 --- a/zokrates_core/src/proof_system/mod.rs +++ b/zokrates_core/src/proof_system/mod.rs @@ -29,6 +29,7 @@ impl SetupKeypair { pub struct Proof { proof: T, inputs: Vec, + #[serde(skip_serializing_if = "Option::is_none")] raw: Option, } diff --git a/zokrates_field/Cargo.toml b/zokrates_field/Cargo.toml index 8aa25f8b8..a40edbdfa 100644 --- a/zokrates_field/Cargo.toml +++ b/zokrates_field/Cargo.toml @@ -10,15 +10,15 @@ serde_derive = "1.0" lazy_static = "1.4" bincode = "0.8.0" serde_json = "1.0" -bellman_ce = { version = "^0.3", default-features = false} -algebra-core = { git = "https://github.com/scipr-lab/zexe.git", features = ["parallel"] } +bellman_ce = { version = "^0.3", default-features = false } +algebra-core = { git = "https://github.com/scipr-lab/zexe.git", default-features = false } sha2 = "0.8.0" num-traits = { version = "0.2", default-features = false } num-integer = { version = "0.1", default-features = false } [dependencies.algebra] git = "https://github.com/scipr-lab/zexe.git" -features = ["bn254", "bls12_377", "bw6_761", "parallel"] +features = ["bn254", "bls12_377", "bw6_761"] [dev-dependencies] rand = "0.4" diff --git a/zokrates_js/Cargo.lock b/zokrates_js/Cargo.lock index d6888a7dd..7aae1fac6 100644 --- a/zokrates_js/Cargo.lock +++ b/zokrates_js/Cargo.lock @@ -37,26 +37,14 @@ name = "algebra-core" version = "0.1.1-alpha.0" source = "git+https://github.com/scipr-lab/zexe.git#85cac1770dddd4da79e9993c5d1dcb5732db08f5" dependencies = [ - "algebra-core-derive", "derivative", "field-assembly", "num-traits 0.2.12", "rand 0.7.3", - "rayon", "rustc_version", "unroll", ] -[[package]] -name = "algebra-core-derive" -version = "0.1.1-alpha.0" -source = "git+https://github.com/scipr-lab/zexe.git#85cac1770dddd4da79e9993c5d1dcb5732db08f5" -dependencies = [ - "proc-macro2 1.0.18", - "quote 1.0.7", - "syn 1.0.34", -] - [[package]] name = "ansi_term" version = "0.11.0" @@ -102,11 +90,6 @@ dependencies = [ "web-sys", ] -[[package]] -name = "bench-utils" -version = "0.1.1-alpha.0" -source = "git+https://github.com/scipr-lab/zexe.git#85cac1770dddd4da79e9993c5d1dcb5732db08f5" - [[package]] name = "bincode" version = "0.8.0" @@ -134,18 +117,6 @@ version = "0.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5f0dc55f2d8a1a85650ac47858bb001b4c0dd73d79e3c455a842925e68d29cd3" -[[package]] -name = "blake2" -version = "0.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94cb07b0da6a73955f8fb85d24c466778e70cda767a568229b104f0264089330" -dependencies = [ - "byte-tools", - "crypto-mac", - "digest", - "opaque-debug", -] - [[package]] name = "block-buffer" version = "0.7.3" @@ -213,83 +184,6 @@ dependencies = [ "wasm-bindgen", ] -[[package]] -name = "crossbeam-channel" -version = "0.4.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b153fe7cbef478c567df0f972e02e6d736db11affe43dfc9c56a9374d1adfb87" -dependencies = [ - "crossbeam-utils", - "maybe-uninit", -] - -[[package]] -name = "crossbeam-deque" -version = "0.7.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f02af974daeee82218205558e51ec8768b48cf524bd01d550abe5573a608285" -dependencies = [ - "crossbeam-epoch", - "crossbeam-utils", - "maybe-uninit", -] - -[[package]] -name = "crossbeam-epoch" -version = "0.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "058ed274caafc1f60c4997b5fc07bf7dc7cca454af7c6e81edffe5f33f70dace" -dependencies = [ - "autocfg", - "cfg-if", - "crossbeam-utils", - "lazy_static", - "maybe-uninit", - "memoffset", - "scopeguard", -] - -[[package]] -name = "crossbeam-utils" -version = "0.7.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3c7c73a2d1e9fc0886a08b93e98eb643461230d5f1925e4036204d5f2e261a8" -dependencies = [ - "autocfg", - "cfg-if", - "lazy_static", -] - -[[package]] -name = "crypto-mac" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4434400df11d95d556bac068ddfedd482915eb18fe8bea89bc80b6e4b1c179e5" -dependencies = [ - "generic-array", - "subtle", -] - -[[package]] -name = "crypto-primitives" -version = "0.1.1-alpha.0" -source = "git+https://github.com/scipr-lab/zexe.git#85cac1770dddd4da79e9993c5d1dcb5732db08f5" -dependencies = [ - "algebra-core", - "bench-utils", - "blake2", - "derivative", - "digest", - "ff-fft", - "gm17", - "groth16", - "r1cs-core", - "r1cs-std", - "rand 0.7.3", - "rayon", - "tracing", -] - [[package]] name = "csv" version = "1.1.3" @@ -382,16 +276,6 @@ version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e88a8acf291dafb59c2d96e8f59828f3838bb1a70398823ade51a84de6a6deed" -[[package]] -name = "ff-fft" -version = "0.1.1-alpha.0" -source = "git+https://github.com/scipr-lab/zexe.git#85cac1770dddd4da79e9993c5d1dcb5732db08f5" -dependencies = [ - "algebra-core", - "rand 0.7.3", - "rayon", -] - [[package]] name = "ff_ce" version = "0.9.0" @@ -421,7 +305,7 @@ version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "50c052fa6d4c2f12305ec364bfb8ef884836f3f61ea015b202372ff996d1ac4b" dependencies = [ - "num-bigint 0.2.6", + "num-bigint", "num-integer", "num-traits 0.2.12", "proc-macro2 1.0.18", @@ -559,32 +443,6 @@ version = "0.22.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aaf91faf136cb47367fa430cd46e37a788775e7fa104f8b4bcb3861dc389b724" -[[package]] -name = "gm17" -version = "0.1.1-alpha.0" -source = "git+https://github.com/scipr-lab/zexe.git#85cac1770dddd4da79e9993c5d1dcb5732db08f5" -dependencies = [ - "algebra-core", - "bench-utils", - "ff-fft", - "r1cs-core", - "rand 0.7.3", - "rayon", -] - -[[package]] -name = "groth16" -version = "0.1.1-alpha.0" -source = "git+https://github.com/scipr-lab/zexe.git#85cac1770dddd4da79e9993c5d1dcb5732db08f5" -dependencies = [ - "algebra-core", - "bench-utils", - "ff-fft", - "r1cs-core", - "rand 0.7.3", - "rayon", -] - [[package]] name = "hermit-abi" version = "0.1.15" @@ -651,27 +509,12 @@ version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3e2e65a1a2e43cfcb47a895c4c8b10d1f4a61097f9f254f183aee60cad9c651d" -[[package]] -name = "maybe-uninit" -version = "2.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "60302e4db3a61da70c0cb7991976248362f30319e88850c487b9b95bbf059e00" - [[package]] name = "memchr" version = "2.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3728d817d99e5ac407411fa471ff9800a778d88a24685968b36824eaf4bee400" -[[package]] -name = "memoffset" -version = "0.5.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "043175f069eda7b85febe4a74abbaeff828d9f8b448515d3151a14a3542811aa" -dependencies = [ - "autocfg", -] - [[package]] name = "mince" version = "0.1.1-alpha.0" @@ -701,16 +544,6 @@ dependencies = [ "num-traits 0.2.12", ] -[[package]] -name = "num-bigint" -version = "0.1.44" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e63899ad0da84ce718c14936262a41cee2c79c981fc0a0e7c7beb47d5a07e8c1" -dependencies = [ - "num-integer", - "num-traits 0.2.12", -] - [[package]] name = "num-bigint" version = "0.2.6" @@ -886,12 +719,6 @@ dependencies = [ "syn 1.0.34", ] -[[package]] -name = "pin-project-lite" -version = "0.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e555d9e657502182ac97b539fb3dae8b79cda19e3e4f8ffb5e8de4f18df93c95" - [[package]] name = "pin-utils" version = "0.1.0" @@ -952,27 +779,6 @@ dependencies = [ "proc-macro2 1.0.18", ] -[[package]] -name = "r1cs-core" -version = "0.1.1-alpha.0" -source = "git+https://github.com/scipr-lab/zexe.git#85cac1770dddd4da79e9993c5d1dcb5732db08f5" -dependencies = [ - "algebra-core", - "tracing", - "tracing-subscriber", -] - -[[package]] -name = "r1cs-std" -version = "0.1.1-alpha.0" -source = "git+https://github.com/scipr-lab/zexe.git#85cac1770dddd4da79e9993c5d1dcb5732db08f5" -dependencies = [ - "algebra", - "derivative", - "r1cs-core", - "tracing", -] - [[package]] name = "rand" version = "0.4.6" @@ -1042,31 +848,6 @@ dependencies = [ "rand_core 0.5.1", ] -[[package]] -name = "rayon" -version = "1.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dcf6960dc9a5b4ee8d3e4c5787b4a112a8818e0290a42ff664ad60692fdf2032" -dependencies = [ - "autocfg", - "crossbeam-deque", - "either", - "rayon-core", -] - -[[package]] -name = "rayon-core" -version = "1.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8c4fec834fb6e6d2dd5eece3c7b432a52f0ba887cf40e595190c4107edc08bf" -dependencies = [ - "crossbeam-channel", - "crossbeam-deque", - "crossbeam-utils", - "lazy_static", - "num_cpus", -] - [[package]] name = "rdrand" version = "0.4.0" @@ -1134,12 +915,6 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "71d301d4193d031abdd79ff7e3dd721168a9572ef3fe51a1517aba235bd8f86e" -[[package]] -name = "scopeguard" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd" - [[package]] name = "semver" version = "0.9.0" @@ -1234,12 +1009,6 @@ version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c111b5bd5695e56cffe5129854aa230b39c93a305372fdbb2668ca2394eea9f8" -[[package]] -name = "subtle" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d67a5a62ba6e01cb2192ff309324cb4875d0c451d55fe2319433abe7a05a8ee" - [[package]] name = "syn" version = "0.15.44" @@ -1283,47 +1052,6 @@ dependencies = [ "lazy_static", ] -[[package]] -name = "tracing" -version = "0.1.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0987850db3733619253fe60e17cb59b82d37c7e6c0236bb81e4d6b87c879f27" -dependencies = [ - "cfg-if", - "pin-project-lite", - "tracing-attributes", - "tracing-core", -] - -[[package]] -name = "tracing-attributes" -version = "0.1.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "80e0ccfc3378da0cce270c946b676a376943f5cd16aeba64568e7939806f4ada" -dependencies = [ - "proc-macro2 1.0.18", - "quote 1.0.7", - "syn 1.0.34", -] - -[[package]] -name = "tracing-core" -version = "0.1.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f50de3927f93d202783f4513cda820ab47ef17f624b03c096e86ef00c67e6b5f" -dependencies = [ - "lazy_static", -] - -[[package]] -name = "tracing-subscriber" -version = "0.2.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "82bb5079aa76438620837198db8a5c529fb9878c730bc2b28179b0241cf04c10" -dependencies = [ - "tracing-core", -] - [[package]] name = "typed-arena" version = "1.7.0" @@ -1495,22 +1223,16 @@ version = "0.1.0" name = "zokrates_core" version = "0.5.1" dependencies = [ - "algebra", - "algebra-core", "bellman_ce", "bincode 0.8.0", - "crypto-primitives", "csv", "ff_ce 0.9.0", - "gm17", "hex", "lazy_static", "num", - "num-bigint 0.1.44", + "num-bigint", "pairing_ce", "pretty_assertions", - "r1cs-core", - "r1cs-std", "rand 0.4.6", "rand 0.7.3", "reduce", @@ -1534,7 +1256,7 @@ dependencies = [ "bellman_ce", "bincode 0.8.0", "lazy_static", - "num-bigint 0.2.6", + "num-bigint", "num-integer", "num-traits 0.2.12", "serde", diff --git a/zokrates_js/Cargo.toml b/zokrates_js/Cargo.toml index ad2fb07dc..18488e2d9 100644 --- a/zokrates_js/Cargo.toml +++ b/zokrates_js/Cargo.toml @@ -13,7 +13,7 @@ js-sys = "0.3.33" serde = { version = "^1.0.59", features = ["derive"] } serde_json = "1.0" wasm-bindgen = { version = "0.2.46", features = ["serde-serialize"] } -zokrates_core = { path = "../zokrates_core", features = ["wasm"] } +zokrates_core = { path = "../zokrates_core", features = ["wasm"], default-features = false } zokrates_common = { path = "../zokrates_common" } zokrates_field = { path = "../zokrates_field" } zokrates_abi = { path = "../zokrates_abi" } diff --git a/zokrates_js/index.d.ts b/zokrates_js/index.d.ts index 58395f2b0..8df5bf4db 100644 --- a/zokrates_js/index.d.ts +++ b/zokrates_js/index.d.ts @@ -1,7 +1,10 @@ declare module 'zokrates-js' { - export type G1Affine = [string, string]; - export type G2Affine = [G1Affine, G1Affine]; + export type Fq = string; + export type Fq2 = [Fq, Fq]; + + export type G1Affine = [Fq, Fq]; + export type G2Affine = [Fq2, Fq2]; export type ProvingKey = Uint8Array; export type SolidityAbi = "v1" | "v2"; @@ -17,8 +20,7 @@ declare module 'zokrates-js' { beta: G2Affine, gamma: G2Affine, delta: G2Affine, - gamma_abc: G1Affine[], - raw: string, + gamma_abc: G1Affine[] } export interface ProofPoints { @@ -29,8 +31,7 @@ declare module 'zokrates-js' { export interface Proof { proof: ProofPoints, - inputs: string[], - raw: string + inputs: string[] } export interface ResolverResult { @@ -57,8 +58,9 @@ declare module 'zokrates-js' { compile(source: string, options?: CompileOptions): CompilationArtifacts; setup(program: Uint8Array): SetupKeypair; computeWitness(artifacts: CompilationArtifacts, args: any[]): ComputationResult; - exportSolidityVerifier(verifyingKey: VerificationKey, abi: SolidityAbi): string; + exportSolidityVerifier(verificationKey: VerificationKey, abi: SolidityAbi): string; generateProof(program: Uint8Array, witness: string, provingKey: Uint8Array): Proof; + verify(verificationKey: VerificationKey, proof: Proof): boolean; } export interface Metadata { diff --git a/zokrates_js/src/lib.rs b/zokrates_js/src/lib.rs index 5ab875028..0d0593424 100644 --- a/zokrates_js/src/lib.rs +++ b/zokrates_js/src/lib.rs @@ -10,9 +10,9 @@ use zokrates_core::imports::Error; use zokrates_core::ir; use zokrates_core::proof_system::bellman::Bellman; use zokrates_core::proof_system::scheme::groth16::G16; -use zokrates_core::proof_system::scheme::{SolidityCompatibleScheme}; +use zokrates_core::proof_system::scheme::{Scheme, SolidityCompatibleScheme}; use zokrates_core::proof_system::solidity::SolidityAbi; -use zokrates_core::proof_system::Backend; +use zokrates_core::proof_system::{Backend, Proof}; use zokrates_core::typed_absy::abi::Abi; use zokrates_core::typed_absy::types::Signature; use zokrates_field::Bn128Field; @@ -35,12 +35,6 @@ pub struct ComputationResult { output: String, } -impl ResolverResult { - fn into_tuple(self) -> (String, PathBuf) { - (self.source, PathBuf::from(self.location)) - } -} - #[inline] fn deserialize_program(value: &Vec) -> Result, JsValue> { deserialize(&value) @@ -90,7 +84,7 @@ impl<'a> Resolver for JsResolver<'a> { ))) } else { let result: ResolverResult = value.into_serde().unwrap(); - Ok(result.into_tuple()) + Ok((result.source, PathBuf::from(result.location))) } } } @@ -199,6 +193,15 @@ pub fn generate_proof(program: JsValue, witness: JsValue, pk: JsValue) -> Result Ok(JsValue::from_serde(&proof).unwrap()) } +#[wasm_bindgen] +pub fn verify(vk: JsValue, proof: JsValue) -> Result { + let vk: >::VerificationKey = vk.into_serde().unwrap(); + let proof: Proof<>::ProofPoints> = proof.into_serde().unwrap(); + + let ans = >::verify(vk, proof); + Ok(JsValue::from_serde(&ans).unwrap()) +} + #[wasm_bindgen(start)] pub fn main_js() -> Result<(), JsValue> { console_error_panic_hook::set_once(); diff --git a/zokrates_js/tests/tests.js b/zokrates_js/tests/tests.js index 57d4a79ca..2064f0035 100644 --- a/zokrates_js/tests/tests.js +++ b/zokrates_js/tests/tests.js @@ -124,4 +124,31 @@ describe('tests', function() { }) }); }); + + describe("verify", () => { + it('should pass', function() { + assert.doesNotThrow(() => { + const code = 'def main(private field a) -> field: return a * a'; + const artifacts = this.zokrates.compile(code); + const computationResult = this.zokrates.computeWitness(artifacts, ["2"]) + const keypair = this.zokrates.setup(artifacts.program); + const proof = this.zokrates.generateProof(artifacts.program, computationResult.witness, keypair.pk); + + assert(this.zokrates.verify(keypair.vk, proof) == true); + }) + }); + it('should fail', function() { + assert.doesNotThrow(() => { + const code = 'def main(private field a) -> field: return a * a'; + const artifacts = this.zokrates.compile(code); + const computationResult = this.zokrates.computeWitness(artifacts, ["2"]) + const keypair = this.zokrates.setup(artifacts.program); + let proof = this.zokrates.generateProof(artifacts.program, computationResult.witness, keypair.pk); + + // falsify proof + proof["proof"]["a"][0] = "0x0000000000000000000000000000000000000000000000000000000000000000"; + assert(this.zokrates.verify(keypair.vk, proof) == false); + }) + }); + }); }); \ No newline at end of file diff --git a/zokrates_js/wrapper.js b/zokrates_js/wrapper.js index 0f1041e02..f1df79e85 100644 --- a/zokrates_js/wrapper.js +++ b/zokrates_js/wrapper.js @@ -61,6 +61,9 @@ module.exports = (dep) => { }, generateProof: (program, witness, provingKey) => { return zokrates.generate_proof(program, witness, provingKey); + }, + verify: (verificationKey, proof) => { + return zokrates.verify(verificationKey, proof); } } }; \ No newline at end of file From 3a9354f7d3982299258991916383ce7224e1ee81 Mon Sep 17 00:00:00 2001 From: dark64 Date: Tue, 6 Oct 2020 15:40:06 +0200 Subject: [PATCH 39/54] limit test threads to 1 for integration tests --- full_test.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/full_test.sh b/full_test.sh index ca3c16200..afbbc09a9 100755 --- a/full_test.sh +++ b/full_test.sh @@ -3,4 +3,4 @@ # Exit if any subcommand fails set -e -cargo test --release -- --ignored +cargo test --release -- --ignored --test-threads=1 From 999f9017d5528c34109d282177cfcd5a683900bb Mon Sep 17 00:00:00 2001 From: dark64 Date: Tue, 6 Oct 2020 15:58:24 +0200 Subject: [PATCH 40/54] remove github workflow --- .github/workflows/make-gpr-docker-image.yml | 23 --------------------- ey.Dockerfile | 18 ---------------- 2 files changed, 41 deletions(-) delete mode 100644 .github/workflows/make-gpr-docker-image.yml delete mode 100644 ey.Dockerfile diff --git a/.github/workflows/make-gpr-docker-image.yml b/.github/workflows/make-gpr-docker-image.yml deleted file mode 100644 index 693e33604..000000000 --- a/.github/workflows/make-gpr-docker-image.yml +++ /dev/null @@ -1,23 +0,0 @@ -name: GitHub Package Repo Docker Image - -on: - push: - branches: - - 'eyblockchain' - -jobs: - make-gpr-docker-image: - name: Image Release - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v1 - - name: Build container image - uses: mr-smithers-excellent/docker-build-push@v3 - with: - image: zokrates-zexe/zokrates_zexe - dockerfile: ey.Dockerfile - tag: ${{ github.sha }} - registry: docker.pkg.github.com - username: ${{ github.actor }} - password: ${{ secrets.GITHUB_TOKEN }} diff --git a/ey.Dockerfile b/ey.Dockerfile deleted file mode 100644 index 34773a9c5..000000000 --- a/ey.Dockerfile +++ /dev/null @@ -1,18 +0,0 @@ -FROM rust:latest as builder -WORKDIR /src -COPY . . -RUN apt-get update -# RUN apt-get install -y git clang llvm -RUN rustup toolchain install nightly -RUN cargo +nightly build --release - -FROM ubuntu:latest -RUN useradd -u 1000 -m zokrates -WORKDIR /home/zokrates/ -COPY --from=builder --chown=zokrates:zokrates /src/target/release/zokrates /home/zokrates/ -COPY --from=builder --chown=zokrates:zokrates /src/zokrates_stdlib/stdlib /home/zokrates/.zokrates/ -COPY --from=builder --chown=zokrates:zokrates /src/zokrates_cli/examples /home/zokrates/examples/ -ENV ZOKRATES_HOME=/home/zokrates/.zokrates -USER zokrates -ENV PATH=/home/zokrates/:$PATH -CMD ["zokrates", "--version"] From 5de2d3a9b2d3d683befca33737edee46d5960c66 Mon Sep 17 00:00:00 2001 From: dark64 Date: Wed, 7 Oct 2020 15:23:07 +0200 Subject: [PATCH 41/54] features fix --- Cargo.lock | 65 ---------------------------------------- zokrates_abi/Cargo.toml | 2 +- zokrates_core/Cargo.toml | 6 ++-- 3 files changed, 4 insertions(+), 69 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index bb6169e8e..b34d8b2a1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -42,7 +42,6 @@ dependencies = [ "field-assembly", "num-traits 0.2.12", "rand 0.7.3", - "rayon", "rustc_version", "unroll", ] @@ -543,7 +542,6 @@ source = "git+https://github.com/scipr-lab/zexe.git#85cac1770dddd4da79e9993c5d1d dependencies = [ "algebra-core", "rand 0.7.3", - "rayon", ] [[package]] @@ -757,7 +755,6 @@ dependencies = [ "ff-fft", "r1cs-core", "rand 0.7.3", - "rayon", ] [[package]] @@ -1142,12 +1139,6 @@ dependencies = [ "syn 1.0.39", ] -[[package]] -name = "pin-project-lite" -version = "0.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e555d9e657502182ac97b539fb3dae8b79cda19e3e4f8ffb5e8de4f18df93c95" - [[package]] name = "pin-utils" version = "0.1.0" @@ -1229,8 +1220,6 @@ version = "0.1.1-alpha.0" source = "git+https://github.com/scipr-lab/zexe.git#85cac1770dddd4da79e9993c5d1dcb5732db08f5" dependencies = [ "algebra-core", - "tracing", - "tracing-subscriber", ] [[package]] @@ -1302,31 +1291,6 @@ dependencies = [ "rand_core 0.5.1", ] -[[package]] -name = "rayon" -version = "1.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cfd016f0c045ad38b5251be2c9c0ab806917f82da4d36b2a327e5166adad9270" -dependencies = [ - "autocfg", - "crossbeam-deque", - "either", - "rayon-core", -] - -[[package]] -name = "rayon-core" -version = "1.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91739a34c4355b5434ce54c9086c5895604a9c278586d1f1aa95e04f66b525a0" -dependencies = [ - "crossbeam-channel", - "crossbeam-deque", - "crossbeam-utils", - "lazy_static", - "num_cpus", -] - [[package]] name = "rdrand" version = "0.4.0" @@ -1649,35 +1613,6 @@ version = "0.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "238ce071d267c5710f9d31451efec16c5ee22de34df17cc05e56cbc92e967117" -[[package]] -name = "tracing" -version = "0.1.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0987850db3733619253fe60e17cb59b82d37c7e6c0236bb81e4d6b87c879f27" -dependencies = [ - "cfg-if", - "pin-project-lite", - "tracing-core", -] - -[[package]] -name = "tracing-core" -version = "0.1.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f50de3927f93d202783f4513cda820ab47ef17f624b03c096e86ef00c67e6b5f" -dependencies = [ - "lazy_static", -] - -[[package]] -name = "tracing-subscriber" -version = "0.2.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "82bb5079aa76438620837198db8a5c529fb9878c730bc2b28179b0241cf04c10" -dependencies = [ - "tracing-core", -] - [[package]] name = "typed-arena" version = "1.7.0" diff --git a/zokrates_abi/Cargo.toml b/zokrates_abi/Cargo.toml index 27f7e0391..08d4e96d0 100644 --- a/zokrates_abi/Cargo.toml +++ b/zokrates_abi/Cargo.toml @@ -6,7 +6,7 @@ edition = "2018" [dependencies] zokrates_field = { version = "0.3", path = "../zokrates_field" } -zokrates_core = { version = "0.5", path = "../zokrates_core" } +zokrates_core = { version = "0.5", path = "../zokrates_core", default-features = false } serde = "1.0" serde_derive = "1.0" serde_json = "1.0" \ No newline at end of file diff --git a/zokrates_core/Cargo.toml b/zokrates_core/Cargo.toml index 99f80beb1..47d5d9e0c 100644 --- a/zokrates_core/Cargo.toml +++ b/zokrates_core/Cargo.toml @@ -37,10 +37,10 @@ rand_0_7 = { version = "0.7", package = "rand" } csv = "1" pretty_assertions = "0.6.1" bellman_ce = { version = "^0.3", default-features = false } -gm17 = { git = "https://github.com/scipr-lab/zexe.git", features = ["parallel"], default-features = false, optional = true } -algebra-core = { git = "https://github.com/scipr-lab/zexe.git", features = ["parallel"], default-features = false, optional = true } +gm17 = { git = "https://github.com/scipr-lab/zexe.git", default-features = false, optional = true } +algebra-core = { git = "https://github.com/scipr-lab/zexe.git", default-features = false, optional = true } r1cs-core = { git = "https://github.com/scipr-lab/zexe.git", default-features = false, optional = true } -algebra = { git = "https://github.com/scipr-lab/zexe.git", features = ["bn254", "bls12_377", "bw6_761", "parallel"], default-features = false, optional = true } +algebra = { git = "https://github.com/scipr-lab/zexe.git", features = ["bn254", "bls12_377", "bw6_761"], default-features = false, optional = true } [dev-dependencies] glob = "0.2.11" From 2b3183a6d3f83c844f681758acd1b3869ea71104 Mon Sep 17 00:00:00 2001 From: schaeff Date: Thu, 8 Oct 2020 10:43:14 +0200 Subject: [PATCH 42/54] fix tests of compile issues, change struct handling to make tests pass --- .../{error => compile_errors}/assert.zok | 0 .../{error => compile_errors}/empty-error.zok | 0 .../no_struct_equivalence.zok} | 0 .../out_of_for_scope.zok | 0 .../{error => compile_errors}/shadowing.zok | 0 .../compile_errors/too_many_return.zok | 2 + .../{error => compile_errors}/unassigned.zok | 0 .../wrongsyntax-error.zok | 0 .../examples/error/forbidden_power_base.zok | 2 - .../lt_overflow_p_minus_one.zok | 4 +- zokrates_cli/src/bin.rs | 15 +++--- zokrates_core/src/compile.rs | 24 +++++----- zokrates_core/src/semantics.rs | 9 ++-- zokrates_core/src/typed_absy/types.rs | 46 +++++++++++-------- 14 files changed, 57 insertions(+), 45 deletions(-) rename zokrates_cli/examples/{error => compile_errors}/assert.zok (100%) rename zokrates_cli/examples/{error => compile_errors}/empty-error.zok (100%) rename zokrates_cli/examples/{error/struct_if_else.zok => compile_errors/no_struct_equivalence.zok} (100%) rename zokrates_cli/examples/{error => compile_errors}/out_of_for_scope.zok (100%) rename zokrates_cli/examples/{error => compile_errors}/shadowing.zok (100%) create mode 100644 zokrates_cli/examples/compile_errors/too_many_return.zok rename zokrates_cli/examples/{error => compile_errors}/unassigned.zok (100%) rename zokrates_cli/examples/{error => compile_errors}/wrongsyntax-error.zok (100%) delete mode 100644 zokrates_cli/examples/error/forbidden_power_base.zok diff --git a/zokrates_cli/examples/error/assert.zok b/zokrates_cli/examples/compile_errors/assert.zok similarity index 100% rename from zokrates_cli/examples/error/assert.zok rename to zokrates_cli/examples/compile_errors/assert.zok diff --git a/zokrates_cli/examples/error/empty-error.zok b/zokrates_cli/examples/compile_errors/empty-error.zok similarity index 100% rename from zokrates_cli/examples/error/empty-error.zok rename to zokrates_cli/examples/compile_errors/empty-error.zok diff --git a/zokrates_cli/examples/error/struct_if_else.zok b/zokrates_cli/examples/compile_errors/no_struct_equivalence.zok similarity index 100% rename from zokrates_cli/examples/error/struct_if_else.zok rename to zokrates_cli/examples/compile_errors/no_struct_equivalence.zok diff --git a/zokrates_cli/examples/error/out_of_for_scope.zok b/zokrates_cli/examples/compile_errors/out_of_for_scope.zok similarity index 100% rename from zokrates_cli/examples/error/out_of_for_scope.zok rename to zokrates_cli/examples/compile_errors/out_of_for_scope.zok diff --git a/zokrates_cli/examples/error/shadowing.zok b/zokrates_cli/examples/compile_errors/shadowing.zok similarity index 100% rename from zokrates_cli/examples/error/shadowing.zok rename to zokrates_cli/examples/compile_errors/shadowing.zok diff --git a/zokrates_cli/examples/compile_errors/too_many_return.zok b/zokrates_cli/examples/compile_errors/too_many_return.zok new file mode 100644 index 000000000..8b1dec6fa --- /dev/null +++ b/zokrates_cli/examples/compile_errors/too_many_return.zok @@ -0,0 +1,2 @@ +def main(): + return 1 \ No newline at end of file diff --git a/zokrates_cli/examples/error/unassigned.zok b/zokrates_cli/examples/compile_errors/unassigned.zok similarity index 100% rename from zokrates_cli/examples/error/unassigned.zok rename to zokrates_cli/examples/compile_errors/unassigned.zok diff --git a/zokrates_cli/examples/error/wrongsyntax-error.zok b/zokrates_cli/examples/compile_errors/wrongsyntax-error.zok similarity index 100% rename from zokrates_cli/examples/error/wrongsyntax-error.zok rename to zokrates_cli/examples/compile_errors/wrongsyntax-error.zok diff --git a/zokrates_cli/examples/error/forbidden_power_base.zok b/zokrates_cli/examples/error/forbidden_power_base.zok deleted file mode 100644 index 40c8b00c2..000000000 --- a/zokrates_cli/examples/error/forbidden_power_base.zok +++ /dev/null @@ -1,2 +0,0 @@ -def main(field a) -> field: - return a*2**3 \ No newline at end of file diff --git a/zokrates_cli/examples/runtime_errors/lt_overflow_p_minus_one.zok b/zokrates_cli/examples/runtime_errors/lt_overflow_p_minus_one.zok index ec594e621..fd7aca409 100644 --- a/zokrates_cli/examples/runtime_errors/lt_overflow_p_minus_one.zok +++ b/zokrates_cli/examples/runtime_errors/lt_overflow_p_minus_one.zok @@ -2,6 +2,6 @@ // /!\ should be called with a = 0 def main(field a) -> bool: - field p = 21888242871839275222246405745257275088548364400416034343698204186575808495617 + a + field p = 21888242871839275222246405745257275088548364400416034343698204186575808495616 + a // we added a = 0 to prevent the condition to be evaluated at compile time - return 0 < p - 1 \ No newline at end of file + return 0 < p \ No newline at end of file diff --git a/zokrates_cli/src/bin.rs b/zokrates_cli/src/bin.rs index 024a0bd1b..9bafde62b 100644 --- a/zokrates_cli/src/bin.rs +++ b/zokrates_cli/src/bin.rs @@ -994,7 +994,7 @@ mod tests { use super::*; #[test] - fn examples() { + fn compile_examples() { for p in glob("./examples/**/*").expect("Failed to read glob pattern") { let path = match p { Ok(x) => x, @@ -1007,9 +1007,7 @@ mod tests { assert!(path.extension().expect("extension expected") == "zok"); - if path.to_str().unwrap().contains("error") { - continue; - } + let should_error = path.to_str().unwrap().contains("compile_errors"); println!("Testing {:?}", path); @@ -1022,13 +1020,14 @@ mod tests { let stdlib = std::fs::canonicalize("../zokrates_stdlib/stdlib").unwrap(); let resolver = FileSystemResolver::with_stdlib_root(stdlib.to_str().unwrap()); - let _: CompilationArtifacts = - compile(source, path, Some(&resolver)).unwrap(); + let res = compile::(source, path, Some(&resolver)); + + assert_eq!(res.is_err(), should_error); } } #[test] - fn examples_with_input_success() { + fn execute_examples_ok() { //these examples should compile and run for p in glob("./examples/test*").expect("Failed to read glob pattern") { let path = match p { @@ -1059,7 +1058,7 @@ mod tests { #[test] #[should_panic] - fn examples_with_input_failure() { + fn execute_examples_err() { //these examples should compile but not run for p in glob("./examples/runtime_errors/*").expect("Failed to read glob pattern") { let path = match p { diff --git a/zokrates_core/src/compile.rs b/zokrates_core/src/compile.rs index 4e10d4817..0653f4065 100644 --- a/zokrates_core/src/compile.rs +++ b/zokrates_core/src/compile.rs @@ -292,7 +292,7 @@ mod test { #[test] fn use_struct_declaration_types() { - // when importing types and renaming them, we use the top-most renaming in the ABI + // when importing types and renaming them, we use the canonical struct names in the ABI // // main.zok // from foo import Foo as FooMain @@ -305,7 +305,7 @@ mod test { // struct Bar { field a } // Expected resolved type for FooMain: - // FooMain { BarFoo b } + // Foo { Bar b } let main = r#" from "foo" import Foo as FooMain @@ -370,21 +370,21 @@ struct Bar { field a } inputs: vec![AbiInput { name: "f".into(), public: true, - ty: Type::Struct(StructType { - module: "main".into(), - name: "FooMain".into(), - members: vec![StructMember { + ty: Type::Struct(StructType::new( + "foo".into(), + "Foo".into(), + vec![StructMember { id: "b".into(), - ty: box Type::Struct(StructType { - module: "foo".into(), - name: "BarFoo".into(), - members: vec![StructMember { + ty: box Type::Struct(StructType::new( + "bar".into(), + "Bar".into(), + vec![StructMember { id: "a".into(), ty: box Type::FieldElement }] - }) + )) }] - }) + )) }], outputs: vec![] } diff --git a/zokrates_core/src/semantics.rs b/zokrates_core/src/semantics.rs index c252d9574..bc3490f44 100644 --- a/zokrates_core/src/semantics.rs +++ b/zokrates_core/src/semantics.rs @@ -16,7 +16,7 @@ use zokrates_field::Field; use crate::parser::Position; use crate::absy::types::{UnresolvedSignature, UnresolvedType, UserTypeId}; -use crate::typed_absy::types::{FunctionKey, Signature, Type}; +use crate::typed_absy::types::{FunctionKey, Signature, StructLocation, Type}; use std::hash::{Hash, Hasher}; use typed_absy::types::{ArrayType, StructMember}; @@ -124,6 +124,7 @@ impl fmt::Display for ErrorInner { } /// A function query in the current module. +#[derive(Debug)] struct FunctionQuery<'ast> { id: Identifier<'ast>, inputs: Vec, @@ -439,8 +440,10 @@ impl<'ast> Checker<'ast> { // rename the type to the declared symbol let t = match t { Type::Struct(t) => Type::Struct(StructType { - module: module_id.clone(), - name: declaration.id.into(), + location: Some(StructLocation { + name: declaration.id.into(), + module: module_id.clone() + }), ..t }), _ => unreachable!() diff --git a/zokrates_core/src/typed_absy/types.rs b/zokrates_core/src/typed_absy/types.rs index d1eac1db6..caffa86b8 100644 --- a/zokrates_core/src/typed_absy/types.rs +++ b/zokrates_core/src/typed_absy/types.rs @@ -1,5 +1,5 @@ use std::fmt; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; pub type Identifier<'ast> = &'ast str; @@ -20,17 +20,25 @@ pub struct ArrayType { pub ty: Box, } -#[derive(Debug, Clone, Hash, Serialize, Deserialize, PartialOrd, Ord)] -pub struct StructType { +#[derive(Debug, Clone, Hash, Serialize, Deserialize, PartialOrd, Ord, Eq, PartialEq)] +pub struct StructLocation { #[serde(skip)] pub module: PathBuf, pub name: String, +} + +#[derive(Debug, Clone, Hash, Serialize, Deserialize, PartialOrd, Ord)] +pub struct StructType { + #[serde(flatten)] + pub canonical_location: StructLocation, + #[serde(skip)] + pub location: Option, pub members: Vec, } impl PartialEq for StructType { fn eq(&self, other: &Self) -> bool { - self.members.eq(&other.members) + self.canonical_location.eq(&other.canonical_location) && self.members.eq(&other.members) } } @@ -39,8 +47,8 @@ impl Eq for StructType {} impl StructType { pub fn new(module: PathBuf, name: String, members: Vec) -> Self { StructType { - module, - name, + canonical_location: StructLocation { module, name }, + location: None, members, } } @@ -52,6 +60,18 @@ impl StructType { pub fn iter(&self) -> std::slice::Iter { self.members.iter() } + + fn location(&self) -> &StructLocation { + &self.location.as_ref().unwrap_or(&self.canonical_location) + } + + pub fn name(&self) -> &str { + &self.location().name + } + + pub fn module(&self) -> &Path { + &self.location().module + } } impl IntoIterator for StructType { @@ -230,7 +250,7 @@ impl fmt::Display for Type { Type::Struct(ref struct_type) => write!( f, "{} {{{}}}", - struct_type.name, + struct_type.name(), struct_type .members .iter() @@ -249,17 +269,7 @@ impl fmt::Debug for Type { Type::Boolean => write!(f, "bool"), Type::Uint(ref bitwidth) => write!(f, "u{}", bitwidth), Type::Array(ref array_type) => write!(f, "{}[{}]", array_type.ty, array_type.size), - Type::Struct(ref struct_type) => write!( - f, - "{} {{{}}}", - struct_type.name, - struct_type - .members - .iter() - .map(|member| format!("{}: {}", member.id, member.ty)) - .collect::>() - .join(", ") - ), + Type::Struct(ref struct_type) => write!(f, "{:?}", struct_type), } } } From 4b2dd517b7a8e16cfa683f0e54996d39ea5ab756 Mon Sep 17 00:00:00 2001 From: dark64 Date: Fri, 9 Oct 2020 12:54:19 +0200 Subject: [PATCH 43/54] remove test dir --- test/test.code | 9 --------- 1 file changed, 9 deletions(-) delete mode 100644 test/test.code diff --git a/test/test.code b/test/test.code deleted file mode 100644 index fd2aaf431..000000000 --- a/test/test.code +++ /dev/null @@ -1,9 +0,0 @@ -def main( private field A, field B) -> (): - field C = A - for field i in 0..100000 do - C = (C * i) ** 2 - endfor - C=0 // so that we can always lazily use the same witness for both curves - // CHECK THE INPUT B EQUALS THE CALCULATED thing - B == C - return From 66438e8610c6cccfbfe82f51e6a16e3051cec506 Mon Sep 17 00:00:00 2001 From: dark64 Date: Wed, 14 Oct 2020 18:27:39 +0200 Subject: [PATCH 44/54] libsnark refactor --- zokrates_core/lib/gm17.cpp | 155 +++++++++------ zokrates_core/lib/pghr13.cpp | 186 +++++++++++------- zokrates_core/lib/util.tcc | 120 ++++++----- .../src/proof_system/bellman/groth16.rs | 7 +- zokrates_core/src/proof_system/bellman/mod.rs | 4 +- .../src/proof_system/libsnark/gm17.rs | 120 +++++++++-- .../src/proof_system/libsnark/mod.rs | 54 +++++ .../src/proof_system/libsnark/pghr13.rs | 143 +++++++++++++- zokrates_core/src/proof_system/mod.rs | 6 +- zokrates_core/src/proof_system/scheme/gm17.rs | 5 +- .../src/proof_system/scheme/groth16.rs | 2 +- .../src/proof_system/scheme/pghr13.rs | 9 +- zokrates_core/src/proof_system/solidity.rs | 36 ++-- zokrates_core/src/proof_system/zexe/gm17.rs | 6 +- 14 files changed, 609 insertions(+), 244 deletions(-) diff --git a/zokrates_core/lib/gm17.cpp b/zokrates_core/lib/gm17.cpp index 5349f31fc..78e57c7db 100644 --- a/zokrates_core/lib/gm17.cpp +++ b/zokrates_core/lib/gm17.cpp @@ -24,52 +24,60 @@ using namespace libsnark; namespace gm17 { template -std::string serializeVerificationKey(r1cs_se_ppzksnark_verification_key* vk) +buffer_t serialize_verification_key(r1cs_se_ppzksnark_verification_key* vk) { - std::stringstream ss; - unsigned queryLength = vk->query.size(); - - ss << "{"; - ss << "\"h\":" << outputPointG2AffineAsHexJson(vk->H) << ","; - ss << "\"g_alpha\":" << outputPointG1AffineAsHexJson(vk->G_alpha) << ","; - ss << "\"h_beta\":" << outputPointG2AffineAsHexJson(vk->H_beta) << ","; - ss << "\"g_gamma\":" << outputPointG1AffineAsHexJson(vk->G_gamma) << ","; - ss << "\"h_gamma\":" << outputPointG2AffineAsHexJson(vk->H_gamma) << ","; - ss << "\"query\":["; - for (size_t i = 0; i < queryLength; ++i) { - if (i != 0) - ss << ","; - ss << outputPointG1AffineAsHexJson(vk->query[i]); - } - ss << "],"; - ss << "\"raw\":\"" << encodeToHexString<2>(serialize(*vk)) << "\""; - ss << "}"; - std::string str = ss.str(); - return str; + const size_t QUERY_COUNT = vk->query.size(); + + const size_t G1_SIZE = Q * sizeof(mp_limb_t) * 2; // [x, y] + const size_t G2_SIZE = Q * sizeof(mp_limb_t) * 4; // [[x0, x1], [y0, y1]] + + const size_t LENGTH = + (G1_SIZE * 2) + + (G2_SIZE * 3) + + (QUERY_COUNT * G1_SIZE); + + // [ ----------------- LENGTH ------------------ ] + // [ h, G_alpha, H_beta, G_gamma, H_gamma, query ] + + buffer_t buffer; + buffer.data = (uint8_t*)malloc(LENGTH); + buffer.length = LENGTH; + + uint8_t* ptr = buffer.data; + serialize_g2_affine(vk->H, ptr); + serialize_g1_affine(vk->G_alpha, ptr); + serialize_g2_affine(vk->H_beta, ptr); + serialize_g1_affine(vk->G_gamma, ptr); + serialize_g2_affine(vk->H_gamma, ptr); + + for (size_t i = 0; i < QUERY_COUNT; ++i) + serialize_g1_affine(vk->query[i], ptr); + + return buffer; } -template -std::string serializeProof(r1cs_se_ppzksnark_proof* proof, const uint8_t* public_inputs, int32_t public_inputs_length) +template +buffer_t serialize_proof(r1cs_se_ppzksnark_proof* proof) { - std::stringstream ss; - ss << "{"; - ss << "\"proof\":{"; - ss << "\"a\":" << outputPointG1AffineAsHexJson(proof->A) << ","; - ss << "\"b\":" << outputPointG2AffineAsHexJson(proof->B) << ","; - ss << "\"c\":" << outputPointG1AffineAsHexJson(proof->C); - ss << "},"; - ss << "\"inputs\":["; - for (int i = 1; i < public_inputs_length; i++) { - if (i != 1) { - ss << ","; - } - ss << outputInputAsHex(libsnarkBigintFromBytes(public_inputs + (i * R * sizeof(mp_limb_t)))); - } - ss << "],"; - ss << "\"raw\":\"" << encodeToHexString<2>(serialize(*proof)) << "\""; - ss << "}"; - std::string str = ss.str(); - return str; + const size_t G1_SIZE = Q * sizeof(mp_limb_t) * 2; // [x, y] + const size_t G2_SIZE = Q * sizeof(mp_limb_t) * 4; // [[x0, x1], [y0, y1]] + + const size_t LENGTH = (G1_SIZE * 2) + G2_SIZE; + + // [ ---------- LENGTH ---------- ] + // [ G1_SIZE, G2_SIZE, G1_SIZE ] + // [ a, b, c ] + + buffer_t buffer; + buffer.data = (uint8_t*)malloc(LENGTH); + buffer.length = LENGTH; + + uint8_t* ptr = buffer.data; + serialize_g1_affine(proof->A, ptr); + serialize_g2_affine(proof->B, ptr); + serialize_g1_affine(proof->C, ptr); + + return buffer; } template @@ -81,23 +89,22 @@ setup_result_t setup(const uint8_t* a, const uint8_t* b, const uint8_t* c, int32 // initialize curve parameters ppT::init_public_params(); - auto cs = createConstraintSystem(a, b, c, a_len, b_len, c_len, constraints, variables, inputs); + auto cs = create_constraint_system(a, b, c, a_len, b_len, c_len, constraints, variables, inputs); assert(cs.num_variables() >= (unsigned)inputs); assert(cs.num_inputs() == (unsigned)inputs); assert(cs.num_constraints() == (unsigned)constraints); r1cs_se_ppzksnark_keypair keypair = r1cs_se_ppzksnark_generator(cs); - auto vk = serializeVerificationKey(&keypair.vk); - buffer_t vk_buf = createBuffer(vk); - buffer_t pk_buf = createBuffer(keypair.pk); + buffer_t vk_buf = serialize_verification_key(&keypair.vk); + buffer_t pk_buf = create_buffer(keypair.pk); setup_result_t result(vk_buf, pk_buf); return result; } template -proof_result_t generateProof(buffer_t* pk_buf, const uint8_t* public_inputs, int32_t public_inputs_length, const uint8_t* private_inputs, int32_t private_inputs_length) +proof_result_t generate_proof(buffer_t* pk_buf, const uint8_t* public_inputs, int32_t public_inputs_length, const uint8_t* private_inputs, int32_t private_inputs_length) { libff::inhibit_profiling_info = true; libff::inhibit_profiling_counters = true; @@ -106,14 +113,14 @@ proof_result_t generateProof(buffer_t* pk_buf, const uint8_t* public_inputs, int ppT::init_public_params(); r1cs_se_ppzksnark_proving_key proving_key; - fromBuffer>(pk_buf, proving_key); + from_buffer>(pk_buf, proving_key); r1cs_variable_assignment> full_variable_assignment; for (int i = 1; i < public_inputs_length; i++) { - full_variable_assignment.push_back(libff::Fr(libsnarkBigintFromBytes(public_inputs + (i * R * sizeof(mp_limb_t))))); + full_variable_assignment.push_back(libff::Fr(to_libff_bigint(public_inputs + (i * R * sizeof(mp_limb_t))))); } for (int i = 0; i < private_inputs_length; i++) { - full_variable_assignment.push_back(libff::Fr(libsnarkBigintFromBytes(private_inputs + (i * R * sizeof(mp_limb_t))))); + full_variable_assignment.push_back(libff::Fr(to_libff_bigint(private_inputs + (i * R * sizeof(mp_limb_t))))); } r1cs_primary_input> primary_input( @@ -125,14 +132,12 @@ proof_result_t generateProof(buffer_t* pk_buf, const uint8_t* public_inputs, int full_variable_assignment.end()); r1cs_se_ppzksnark_proof proof = r1cs_se_ppzksnark_prover(proving_key, primary_input, auxiliary_input); - std::string json = serializeProof(&proof, public_inputs, public_inputs_length); - - buffer_t proof_buf = createBuffer(json); + buffer_t proof_buf = serialize_proof(&proof); proof_result_t result(proof_buf); return result; } -template +template bool verify(buffer_t* vk_buf, buffer_t* proof_buf, const uint8_t* public_inputs, int32_t public_inputs_length) { libff::inhibit_profiling_info = true; @@ -141,15 +146,36 @@ bool verify(buffer_t* vk_buf, buffer_t* proof_buf, const uint8_t* public_inputs, // initialize curve parameters ppT::init_public_params(); - r1cs_se_ppzksnark_verification_key vk; - r1cs_se_ppzksnark_proof proof; - - fromBuffer>(vk_buf, vk); - fromBuffer>(proof_buf, proof); + uint8_t *ptr = vk_buf->data; + const G2 H = deserialize_g2_affine(ptr); + const G1 G_alpha = deserialize_g1_affine(ptr); + const G2 H_beta = deserialize_g2_affine(ptr); + const G1 G_gamma = deserialize_g1_affine(ptr); + const G2 H_gamma = deserialize_g2_affine(ptr); + + libff::G1_vector query_G1_vector; + + const size_t query_count = ((vk_buf->data + vk_buf->length) - ptr) / (Q * sizeof(mp_limb_t) * 2); + for (size_t i = 0; i < query_count; i++) + { + auto query = deserialize_g1_affine(ptr); + query_G1_vector.push_back(query); + } + + const r1cs_se_ppzksnark_verification_key vk(H, G_alpha, H_beta, G_gamma, H_gamma, std::move(query_G1_vector)); + + ptr = proof_buf->data; + G1 a = deserialize_g1_affine(ptr); + G2 b = deserialize_g2_affine(ptr); + G1 c = deserialize_g1_affine(ptr); + r1cs_se_ppzksnark_proof proof( + std::move(a), + std::move(b), + std::move(c)); r1cs_primary_input> primary_input; for (int i = 0; i < public_inputs_length; i++) { - primary_input.push_back(libff::Fr(libsnarkBigintFromBytes(public_inputs + (i * R * sizeof(mp_limb_t))))); + primary_input.push_back(libff::Fr(to_libff_bigint(public_inputs + (i * R * sizeof(mp_limb_t))))); } return r1cs_se_ppzksnark_verifier_strong_IC(vk, primary_input, proof); @@ -171,7 +197,7 @@ proof_result_t gm17_bn128_generate_proof(buffer_t* pk_buf, const uint8_t* private_inputs, int32_t private_inputs_length) { - return gm17::generateProof(vk_buf, proof_buf, public_inputs, public_inputs_length); + return gm17::verify(vk_buf, proof_buf, public_inputs, public_inputs_length); } \ No newline at end of file diff --git a/zokrates_core/lib/pghr13.cpp b/zokrates_core/lib/pghr13.cpp index ca99ea5d6..8fc33b8d8 100644 --- a/zokrates_core/lib/pghr13.cpp +++ b/zokrates_core/lib/pghr13.cpp @@ -15,6 +15,8 @@ #include "libff/algebra/curves/alt_bn128/alt_bn128_pp.hpp" // contains required interfaces and types (keypair, proof, generator, prover, verifier) #include +#include +#include using namespace libsnark; @@ -23,59 +25,67 @@ using namespace libsnark; namespace pghr13 { template -std::string serializeVerificationKey(r1cs_ppzksnark_verification_key* vk) +buffer_t serialize_verification_key(r1cs_ppzksnark_verification_key* vk) { - std::stringstream ss; - unsigned icLength = vk->encoded_IC_query.rest.indices.size(); - - ss << "{"; - ss << "\"a\":" << outputPointG2AffineAsHexJson(vk->alphaA_g2) << ","; - ss << "\"b\":" << outputPointG1AffineAsHexJson(vk->alphaB_g1) << ","; - ss << "\"c\":" << outputPointG2AffineAsHexJson(vk->alphaC_g2) << ","; - ss << "\"gamma\":" << outputPointG2AffineAsHexJson(vk->gamma_g2) << ","; - ss << "\"gamma_beta_1\":" << outputPointG1AffineAsHexJson(vk->gamma_beta_g1) << ","; - ss << "\"gamma_beta_2\":" << outputPointG2AffineAsHexJson(vk->gamma_beta_g2) << ","; - ss << "\"z\":" << outputPointG2AffineAsHexJson(vk->rC_Z_g2) << ","; - ss << "\"ic\":["; - ss << outputPointG1AffineAsHexJson(vk->encoded_IC_query.first); - for (size_t i = 0; i < icLength; ++i) { - ss << ","; - ss << outputPointG1AffineAsHexJson(vk->encoded_IC_query.rest.values[i]); - } - ss << "],"; - ss << "\"raw\":\"" << encodeToHexString<2>(serialize(*vk)) << "\""; - ss << "}"; - std::string str = ss.str(); - return str; + const size_t QUERY_COUNT = vk->encoded_IC_query.rest.indices.size(); + + const size_t G1_SIZE = Q * sizeof(mp_limb_t) * 2; // [x, y] + const size_t G2_SIZE = Q * sizeof(mp_limb_t) * 4; // [[x0, x1], [y0, y1]] + + const size_t LENGTH = + (G1_SIZE * 3) + + (G2_SIZE * 5) + + (QUERY_COUNT * G1_SIZE); + + // [ -------------------- LENGTH --------------------- ] + // [ a, b, c, gamma, gamma_beta_1, gamma_beta_2, z, ic ] + + buffer_t buffer; + buffer.data = (uint8_t*)malloc(LENGTH); + buffer.length = LENGTH; + + uint8_t* ptr = buffer.data; + serialize_g2_affine(vk->alphaA_g2, ptr); + serialize_g1_affine(vk->alphaB_g1, ptr); + serialize_g2_affine(vk->alphaC_g2, ptr); + serialize_g2_affine(vk->gamma_g2, ptr); + serialize_g1_affine(vk->gamma_beta_g1, ptr); + serialize_g2_affine(vk->gamma_beta_g2, ptr); + serialize_g2_affine(vk->rC_Z_g2, ptr); + serialize_g1_affine(vk->encoded_IC_query.first, ptr); + + for (size_t i = 0; i < QUERY_COUNT; ++i) + serialize_g1_affine(vk->encoded_IC_query.rest.values[i], ptr); + + return buffer; } -template -std::string serializeProof(r1cs_ppzksnark_proof* proof, const uint8_t* public_inputs, int public_inputs_length) +template +buffer_t serialize_proof(r1cs_ppzksnark_proof* proof) { - std::stringstream ss; - ss << "{"; - ss << "\"proof\":{"; - ss << "\"a\":" << outputPointG1AffineAsHexJson(proof->g_A.g) << ","; - ss << "\"a_p\":" << outputPointG1AffineAsHexJson(proof->g_A.h) << ","; - ss << "\"b\":" << outputPointG2AffineAsHexJson(proof->g_B.g) << ","; - ss << "\"b_p\":" << outputPointG1AffineAsHexJson(proof->g_B.h) << ","; - ss << "\"c\":" << outputPointG1AffineAsHexJson(proof->g_C.g) << ","; - ss << "\"c_p\":" << outputPointG1AffineAsHexJson(proof->g_C.h) << ","; - ss << "\"h\":" << outputPointG1AffineAsHexJson(proof->g_H) << ","; - ss << "\"k\":" << outputPointG1AffineAsHexJson(proof->g_K); - ss << "},"; - ss << "\"inputs\":["; - for (int i = 1; i < public_inputs_length; i++) { - if (i != 1) { - ss << ","; - } - ss << outputInputAsHex(libsnarkBigintFromBytes(public_inputs + (i * R * sizeof(mp_limb_t)))); - } - ss << "],"; - ss << "\"raw\":\"" << encodeToHexString<2>(serialize(*proof)) << "\""; - ss << "}"; - std::string str = ss.str(); - return str; + const size_t G1_SIZE = Q * sizeof(mp_limb_t) * 2; // [x, y] + const size_t G2_SIZE = Q * sizeof(mp_limb_t) * 4; // [[x0, x1], [y0, y1]] + + const size_t LENGTH = (G1_SIZE * 7) + G2_SIZE; + + // [ ------------- LENGTH -------------- ] + // [ a, a_p, b, b_p, c, c_p, h, k ] + + buffer_t buffer; + buffer.data = (uint8_t*)malloc(LENGTH); + buffer.length = LENGTH; + + uint8_t* ptr = buffer.data; + serialize_g1_affine(proof->g_A.g, ptr); + serialize_g1_affine(proof->g_A.h, ptr); + serialize_g2_affine(proof->g_B.g, ptr); + serialize_g1_affine(proof->g_B.h, ptr); + serialize_g1_affine(proof->g_C.g, ptr); + serialize_g1_affine(proof->g_C.h, ptr); + serialize_g1_affine(proof->g_H, ptr); + serialize_g1_affine(proof->g_K, ptr); + + return buffer; } template @@ -87,23 +97,22 @@ setup_result_t setup(const uint8_t* a, const uint8_t* b, const uint8_t* c, int32 // initialize curve parameters ppT::init_public_params(); - auto cs = createConstraintSystem(a, b, c, a_len, b_len, c_len, constraints, variables, inputs); + auto cs = create_constraint_system(a, b, c, a_len, b_len, c_len, constraints, variables, inputs); assert(cs.num_variables() >= (unsigned)inputs); assert(cs.num_inputs() == (unsigned)inputs); assert(cs.num_constraints() == (unsigned)constraints); r1cs_ppzksnark_keypair keypair = r1cs_ppzksnark_generator(cs); - auto vk = serializeVerificationKey(&keypair.vk); - buffer_t vk_buf = createBuffer(vk); - buffer_t pk_buf = createBuffer(keypair.pk); + buffer_t vk_buf = serialize_verification_key(&keypair.vk); + buffer_t pk_buf = create_buffer(keypair.pk); setup_result_t result(vk_buf, pk_buf); return result; } template -proof_result_t generateProof(buffer_t* pk_buf, const uint8_t* public_inputs, int32_t public_inputs_length, const uint8_t* private_inputs, int32_t private_inputs_length) +proof_result_t generate_proof(buffer_t* pk_buf, const uint8_t* public_inputs, int32_t public_inputs_length, const uint8_t* private_inputs, int32_t private_inputs_length) { libff::inhibit_profiling_info = true; libff::inhibit_profiling_counters = true; @@ -112,15 +121,15 @@ proof_result_t generateProof(buffer_t* pk_buf, const uint8_t* public_inputs, int ppT::init_public_params(); r1cs_ppzksnark_proving_key proving_key; - fromBuffer>(pk_buf, proving_key); + from_buffer>(pk_buf, proving_key); // assign variables based on witness values, excludes ~one r1cs_variable_assignment> full_variable_assignment; for (int i = 1; i < public_inputs_length; i++) { - full_variable_assignment.push_back(libff::Fr(libsnarkBigintFromBytes(public_inputs + (i * R * sizeof(mp_limb_t))))); + full_variable_assignment.push_back(libff::Fr(to_libff_bigint(public_inputs + (i * R * sizeof(mp_limb_t))))); } for (int i = 0; i < private_inputs_length; i++) { - full_variable_assignment.push_back(libff::Fr(libsnarkBigintFromBytes(private_inputs + (i * R * sizeof(mp_limb_t))))); + full_variable_assignment.push_back(libff::Fr(to_libff_bigint(private_inputs + (i * R * sizeof(mp_limb_t))))); } r1cs_primary_input> primary_input( @@ -132,14 +141,12 @@ proof_result_t generateProof(buffer_t* pk_buf, const uint8_t* public_inputs, int full_variable_assignment.end()); r1cs_ppzksnark_proof proof = r1cs_ppzksnark_prover(proving_key, primary_input, auxiliary_input); - std::string json = serializeProof(&proof, public_inputs, public_inputs_length); - - buffer_t proof_buf = createBuffer(json); + buffer_t proof_buf = serialize_proof(&proof); proof_result_t result(proof_buf); return result; } -template +template bool verify(buffer_t* vk_buf, buffer_t* proof_buf, const uint8_t* public_inputs, int32_t public_inputs_length) { libff::inhibit_profiling_info = true; @@ -148,15 +155,53 @@ bool verify(buffer_t* vk_buf, buffer_t* proof_buf, const uint8_t* public_inputs, // initialize curve parameters ppT::init_public_params(); - r1cs_ppzksnark_verification_key vk; - r1cs_ppzksnark_proof proof; + uint8_t *ptr = vk_buf->data; + const G2 alphaA_g2 = deserialize_g2_affine(ptr); + const G1 alphaB_g1 = deserialize_g1_affine(ptr); + const G2 alphaC_g2 = deserialize_g2_affine(ptr); + const G2 gamma_g2 = deserialize_g2_affine(ptr); + const G1 gamma_beta_g1 = deserialize_g1_affine(ptr); + const G2 gamma_beta_g2 = deserialize_g2_affine(ptr); + const G2 rC_Z_g2 = deserialize_g2_affine(ptr); + G1 ic_first = deserialize_g1_affine(ptr); + + std::vector ic_rest; + const size_t ic_rest_count = ((vk_buf->data + vk_buf->length) - ptr) / (Q * sizeof(mp_limb_t) * 2); + for (size_t i = 0; i < ic_rest_count; i++) + { + auto ic_query = deserialize_g1_affine(ptr); + ic_rest.push_back(ic_query); + } - fromBuffer>(vk_buf, vk); - fromBuffer>(proof_buf, proof); + accumulation_vector eIC(std::move(ic_first), std::move(ic_rest)); + const r1cs_ppzksnark_verification_key vk(alphaA_g2, alphaB_g1, alphaC_g2, gamma_g2, gamma_beta_g1, gamma_beta_g2, rC_Z_g2, eIC); + + ptr = proof_buf->data; + const G1 g_A_g = deserialize_g1_affine(ptr); + const G1 g_A_h = deserialize_g1_affine(ptr); + const G2 g_B_g = deserialize_g2_affine(ptr); + const G1 g_B_h = deserialize_g1_affine(ptr); + const G1 g_C_g = deserialize_g1_affine(ptr); + const G1 g_C_h = deserialize_g1_affine(ptr); + + knowledge_commitment g_A(g_A_g, g_A_h); + knowledge_commitment g_B(g_B_g, g_B_h); + knowledge_commitment g_C(g_C_g, g_C_h); + + G1 g_H = deserialize_g1_affine(ptr); + G1 g_K = deserialize_g1_affine(ptr); + + const r1cs_ppzksnark_proof proof( + std::move(g_A), + std::move(g_B), + std::move(g_C), + std::move(g_H), + std::move(g_K) + ); r1cs_primary_input> primary_input; for (int i = 0; i < public_inputs_length; i++) { - primary_input.push_back(libff::Fr(libsnarkBigintFromBytes(public_inputs + (i * R * sizeof(mp_limb_t))))); + primary_input.push_back(libff::Fr(to_libff_bigint(public_inputs + (i * R * sizeof(mp_limb_t))))); } return r1cs_ppzksnark_verifier_strong_IC(vk, primary_input, proof); } @@ -177,7 +222,7 @@ proof_result_t pghr13_bn128_generate_proof(buffer_t* pk_buf, const uint8_t* private_inputs, int32_t private_inputs_length) { - return pghr13::generateProof(vk_buf, proof_buf, public_inputs, public_inputs_length); + return pghr13::verify(vk_buf, proof_buf, public_inputs, public_inputs_length); } \ No newline at end of file diff --git a/zokrates_core/lib/util.tcc b/zokrates_core/lib/util.tcc index 4392b1f4e..d529d4c0c 100644 --- a/zokrates_core/lib/util.tcc +++ b/zokrates_core/lib/util.tcc @@ -8,67 +8,92 @@ #include #include -template -std::string encodeToHexString(const std::string& in) -{ - std::ostringstream out; - out << std::setfill('0'); - for (unsigned char const& c : in) { - out << std::hex << std::setw(W) << static_cast(c); - } - return out.str(); -} - -// conversion byte[N] <-> libsnark bigint. +// conversion byte[N] -> libsnark bigint template -libff::bigint libsnarkBigintFromBytes(const uint8_t* _x) +libff::bigint to_libff_bigint(const uint8_t* input) { libff::bigint x; for (unsigned i = 0; i < N; i++) { for (unsigned j = 0; j < 8; j++) { - x.data[N - 1 - i] |= uint64_t(_x[i * 8 + j]) << (8 * (7 - j)); + x.data[N - 1 - i] |= uint64_t(input[i * 8 + j]) << (8 * (7 - j)); } } return x; } +// conversion libsnark bigint -> byte[N] template -std::string hexStringFromLibsnarkBigint(libff::bigint _x) +void from_libff_bigint(libff::bigint x, uint8_t* out) { - uint8_t x[N * sizeof(mp_limb_t)]; for (unsigned i = 0; i < N; i++) { for (unsigned j = 0; j < 8; j++) { - x[i * 8 + j] = uint8_t(uint64_t(_x.data[N - 1 - i]) >> (8 * (7 - j))); + out[i * 8 + j] = uint8_t(uint64_t(x.data[N - 1 - i]) >> (8 * (7 - j))); } } - std::string tmp((char*)x, N * sizeof(mp_limb_t)); - return encodeToHexString<2>(tmp); -} - -template -std::string outputInputAsHex(libff::bigint _x) -{ - return "\"0x" + hexStringFromLibsnarkBigint(_x) + "\""; } template -std::string outputPointG1AffineAsHexJson(G1 _p) +void serialize_g1_affine(G1 point, uint8_t*& buffer) { - G1 aff = _p; + const size_t ELEMENT_SIZE = Q * sizeof(mp_limb_t); + + G1 aff = point; aff.to_affine_coordinates(); - return "[\"0x" + hexStringFromLibsnarkBigint(aff.X.as_bigint()) + "\",\"0x" + hexStringFromLibsnarkBigint(aff.Y.as_bigint()) + "\"]"; + + auto x = aff.X.as_bigint(); + auto y = aff.Y.as_bigint(); + + from_libff_bigint(x, buffer); buffer += ELEMENT_SIZE; + from_libff_bigint(y, buffer); buffer += ELEMENT_SIZE; } template -std::string outputPointG2AffineAsHexJson(G2 _p) +void serialize_g2_affine(G2 point, uint8_t*& buffer) { - G2 aff = _p; + const size_t ELEMENT_SIZE = Q * sizeof(mp_limb_t); + + G2 aff = point; aff.to_affine_coordinates(); - return "[[\"0x" + hexStringFromLibsnarkBigint(aff.X.c1.as_bigint()) + "\",\"0x" + hexStringFromLibsnarkBigint(aff.X.c0.as_bigint()) + "\"], [\"0x" + hexStringFromLibsnarkBigint(aff.Y.c1.as_bigint()) + "\", \"0x" + hexStringFromLibsnarkBigint(aff.Y.c0.as_bigint()) + "\"]]"; + + auto x0 = aff.X.c0.as_bigint(); + auto x1 = aff.X.c1.as_bigint(); + auto y0 = aff.Y.c0.as_bigint(); + auto y1 = aff.Y.c1.as_bigint(); + + from_libff_bigint(x0, buffer); buffer += ELEMENT_SIZE; + from_libff_bigint(x1, buffer); buffer += ELEMENT_SIZE; + from_libff_bigint(y0, buffer); buffer += ELEMENT_SIZE; + from_libff_bigint(y1, buffer); buffer += ELEMENT_SIZE; +} + +template +G1 deserialize_g1_affine(uint8_t*& buffer) +{ + const size_t ELEMENT_SIZE = Q * sizeof(mp_limb_t); + + auto x = to_libff_bigint(buffer); buffer += ELEMENT_SIZE; + auto y = to_libff_bigint(buffer); buffer += ELEMENT_SIZE; + + return G1(Fq(x), Fq(y), Fq::one()); +} + +template +G2 deserialize_g2_affine(uint8_t*& buffer) +{ + const size_t ELEMENT_SIZE = Q * sizeof(mp_limb_t); + + auto x0 = to_libff_bigint(buffer); buffer += ELEMENT_SIZE; + auto x1 = to_libff_bigint(buffer); buffer += ELEMENT_SIZE; + auto y0 = to_libff_bigint(buffer); buffer += ELEMENT_SIZE; + auto y1 = to_libff_bigint(buffer); buffer += ELEMENT_SIZE; + + auto x = Fq2(x0, x1); + auto y = Fq2(y0, y1); + return G2(x, y, Fq2::one()); } template