From 7c3538982999007c839c6a0d74b1f67d2ec9d598 Mon Sep 17 00:00:00 2001 From: schaeff Date: Wed, 11 May 2022 10:00:11 +0200 Subject: [PATCH 01/19] start split to crates --- Cargo.lock | 330 ++-- Cargo.toml | 4 + zokrates_ark/Cargo.toml | 10 + .../ark => zokrates_ark/src}/gm17.rs | 4 +- .../ark => zokrates_ark/src}/groth16.rs | 4 +- .../ark/mod.rs => zokrates_ark/src/lib.rs | 2 +- .../ark => zokrates_ark/src}/marlin.rs | 4 +- zokrates_ast/Cargo.toml | 20 + .../src => zokrates_ast/src/common}/embed.rs | 100 +- zokrates_ast/src/common/error.rs | 82 + zokrates_ast/src/common/mod.rs | 11 + .../src/common/parameter.rs | 31 +- .../src/common/solvers.rs | 0 .../src/common/variable.rs | 34 +- zokrates_ast/src/flat/folder.rs | 92 ++ .../src/flat}/mod.rs | 110 +- .../src/ir/expression.rs | 71 +- .../src/ir/folder.rs | 14 +- .../src/ir/from_flat.rs | 2 +- {zokrates_core => zokrates_ast}/src/ir/mod.rs | 32 +- .../src/ir/serialize.rs | 34 +- .../src/ir/smtlib2.rs | 10 +- .../src/ir/visitor.rs | 12 +- .../src/ir/witness.rs | 33 +- zokrates_ast/src/lib.rs | 10 + .../src/typed}/abi.rs | 6 +- .../src/typed}/folder.rs | 4 +- .../src/typed}/identifier.rs | 2 +- .../src/typed}/integer.rs | 8 +- .../src/typed}/mod.rs | 26 +- .../src/typed}/parameter.rs | 4 +- .../src/typed}/result_folder.rs | 4 +- .../src/typed}/types.rs | 4 +- .../src/typed}/uint.rs | 4 +- .../src/typed}/variable.rs | 12 +- zokrates_ast/src/untyped/from_ast.rs | 1398 +++++++++++++++++ .../absy => zokrates_ast/src/untyped}/mod.rs | 12 +- .../absy => zokrates_ast/src/untyped}/node.rs | 4 +- .../src/untyped}/parameter.rs | 2 +- .../src/untyped}/position.rs | 0 .../src/untyped}/types.rs | 8 +- .../src/untyped}/variable.rs | 6 +- .../src/zir/folder.rs | 0 .../src/zir/from_typed.rs | 2 +- .../src/zir/identifier.rs | 2 +- .../src/zir/mod.rs | 2 +- .../src/zir/parameter.rs | 0 .../src/zir/result_folder.rs | 0 .../src/zir/types.rs | 0 .../src/zir/uint.rs | 0 .../src/zir/variable.rs | 0 zokrates_core/Cargo.toml | 3 +- zokrates_core/src/absy/from_ast.rs | 1386 ---------------- zokrates_core/src/compile.rs | 5 +- zokrates_core/src/flatten/mod.rs | 269 ++-- zokrates_core/src/imports.rs | 3 +- zokrates_core/src/lib.rs | 12 +- zokrates_core/src/optimizer/canonicalizer.rs | 2 +- zokrates_core/src/optimizer/directive.rs | 12 +- zokrates_core/src/optimizer/duplicate.rs | 26 +- zokrates_core/src/optimizer/mod.rs | 76 +- zokrates_core/src/optimizer/redefinition.rs | 71 +- zokrates_core/src/optimizer/tautology.rs | 6 +- zokrates_core/src/parser/mod.rs | 3 - zokrates_core/src/parser/tokenize/mod.rs | 3 - .../src/proof_system/bellman/groth16.rs | 14 +- zokrates_core/src/proof_system/bellman/mod.rs | 70 +- .../src/proof_system/libsnark/gm17.rs | 4 +- .../src/proof_system/libsnark/mod.rs | 2 +- .../src/proof_system/libsnark/pghr13.rs | 4 +- zokrates_core/src/proof_system/mod.rs | 4 +- zokrates_core/src/semantics.rs | 2 - .../src/static_analysis/branch_isolator.rs | 2 +- .../constant_argument_checker.rs | 2 +- .../src/static_analysis/constant_resolver.rs | 2 +- .../src/static_analysis/flat_propagation.rs | 76 +- zokrates_core/src/static_analysis/mod.rs | 127 +- .../src/static_analysis/propagation.rs | 2 +- .../src/static_analysis/reducer/inline.rs | 2 +- .../static_analysis/reducer/shallow_ssa.rs | 2 +- .../src/static_analysis/struct_concretizer.rs | 2 +- .../src/static_analysis/uint_optimizer.rs | 2 +- .../src/static_analysis/unconstrained_vars.rs | 18 +- .../static_analysis/variable_write_remover.rs | 2 +- .../src/static_analysis/zir_propagation.rs | 10 +- zokrates_interpreter/Cargo.toml | 10 + .../src/lib.rs | 72 +- 87 files changed, 2504 insertions(+), 2370 deletions(-) create mode 100644 zokrates_ark/Cargo.toml rename {zokrates_core/src/proof_system/ark => zokrates_ark/src}/gm17.rs (98%) rename {zokrates_core/src/proof_system/ark => zokrates_ark/src}/groth16.rs (98%) rename zokrates_core/src/proof_system/ark/mod.rs => zokrates_ark/src/lib.rs (99%) rename {zokrates_core/src/proof_system/ark => zokrates_ark/src}/marlin.rs (99%) create mode 100644 zokrates_ast/Cargo.toml rename {zokrates_core/src => zokrates_ast/src/common}/embed.rs (91%) create mode 100644 zokrates_ast/src/common/error.rs create mode 100644 zokrates_ast/src/common/mod.rs rename zokrates_core/src/flat_absy/flat_parameter.rs => zokrates_ast/src/common/parameter.rs (50%) rename zokrates_core/src/solvers/mod.rs => zokrates_ast/src/common/solvers.rs (100%) rename zokrates_core/src/flat_absy/flat_variable.rs => zokrates_ast/src/common/variable.rs (71%) create mode 100644 zokrates_ast/src/flat/folder.rs rename {zokrates_core/src/flat_absy => zokrates_ast/src/flat}/mod.rs (71%) rename {zokrates_core => zokrates_ast}/src/ir/expression.rs (82%) rename {zokrates_core => zokrates_ast}/src/ir/folder.rs (85%) rename {zokrates_core => zokrates_ast}/src/ir/from_flat.rs (98%) rename {zokrates_core => zokrates_ast}/src/ir/mod.rs (85%) rename {zokrates_core => zokrates_ast}/src/ir/serialize.rs (92%) rename {zokrates_core => zokrates_ast}/src/ir/smtlib2.rs (93%) rename {zokrates_core => zokrates_ast}/src/ir/visitor.rs (89%) rename {zokrates_core => zokrates_ast}/src/ir/witness.rs (82%) create mode 100644 zokrates_ast/src/lib.rs rename {zokrates_core/src/typed_absy => zokrates_ast/src/typed}/abi.rs (99%) rename {zokrates_core/src/typed_absy => zokrates_ast/src/typed}/folder.rs (99%) rename {zokrates_core/src/typed_absy => zokrates_ast/src/typed}/identifier.rs (97%) rename {zokrates_core/src/typed_absy => zokrates_ast/src/typed}/integer.rs (99%) rename {zokrates_core/src/typed_absy => zokrates_ast/src/typed}/mod.rs (99%) rename {zokrates_core/src/typed_absy => zokrates_ast/src/typed}/parameter.rs (91%) rename {zokrates_core/src/typed_absy => zokrates_ast/src/typed}/result_folder.rs (99%) rename {zokrates_core/src/typed_absy => zokrates_ast/src/typed}/types.rs (99%) rename {zokrates_core/src/typed_absy => zokrates_ast/src/typed}/uint.rs (99%) rename {zokrates_core/src/typed_absy => zokrates_ast/src/typed}/variable.rs (88%) create mode 100644 zokrates_ast/src/untyped/from_ast.rs rename {zokrates_core/src/absy => zokrates_ast/src/untyped}/mod.rs (98%) rename {zokrates_core/src/absy => zokrates_ast/src/untyped}/node.rs (97%) rename {zokrates_core/src/absy => zokrates_ast/src/untyped}/parameter.rs (96%) rename {zokrates_core/src/parser/tokenize => zokrates_ast/src/untyped}/position.rs (100%) rename {zokrates_core/src/absy => zokrates_ast/src/untyped}/types.rs (96%) rename {zokrates_core/src/absy => zokrates_ast/src/untyped}/variable.rs (88%) rename {zokrates_core => zokrates_ast}/src/zir/folder.rs (100%) rename {zokrates_core => zokrates_ast}/src/zir/from_typed.rs (97%) rename {zokrates_core => zokrates_ast}/src/zir/identifier.rs (95%) rename {zokrates_core => zokrates_ast}/src/zir/mod.rs (99%) rename {zokrates_core => zokrates_ast}/src/zir/parameter.rs (100%) rename {zokrates_core => zokrates_ast}/src/zir/result_folder.rs (100%) rename {zokrates_core => zokrates_ast}/src/zir/types.rs (100%) rename {zokrates_core => zokrates_ast}/src/zir/uint.rs (100%) rename {zokrates_core => zokrates_ast}/src/zir/variable.rs (100%) delete mode 100644 zokrates_core/src/absy/from_ast.rs delete mode 100644 zokrates_core/src/parser/mod.rs delete mode 100644 zokrates_core/src/parser/tokenize/mod.rs create mode 100644 zokrates_interpreter/Cargo.toml rename zokrates_core/src/ir/interpreter.rs => zokrates_interpreter/src/lib.rs (87%) diff --git a/Cargo.lock b/Cargo.lock index 1f27e682..3865c1d8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -140,7 +140,7 @@ dependencies = [ "ark-serialize", "ark-std", "derivative", - "num-traits 0.2.14", + "num-traits 0.2.15", "zeroize", ] @@ -156,7 +156,7 @@ dependencies = [ "ark-std", "derivative", "num-bigint 0.4.3", - "num-traits 0.2.14", + "num-traits 0.2.15", "paste", "rustc_version", "zeroize", @@ -168,8 +168,8 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "db02d390bf6643fb404d3d22d31aee1c4bc4459600aef9113833d17e786c6e44" dependencies = [ - "quote 1.0.17", - "syn 1.0.91", + "quote 1.0.18", + "syn 1.0.92", ] [[package]] @@ -179,9 +179,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "db2fd794a08ccb318058009eefdf15bcaaaaf6f8161eb3345f907222bac38b20" dependencies = [ "num-bigint 0.4.3", - "num-traits 0.2.14", - "quote 1.0.17", - "syn 1.0.91", + "num-traits 0.2.15", + "quote 1.0.18", + "syn 1.0.92", ] [[package]] @@ -246,7 +246,7 @@ dependencies = [ "derivative", "num-bigint 0.4.3", "num-integer", - "num-traits 0.2.14", + "num-traits 0.2.15", "tracing", ] @@ -291,7 +291,7 @@ dependencies = [ "ark-std", "derivative", "num-bigint 0.4.3", - "num-traits 0.2.14", + "num-traits 0.2.15", "tracing", ] @@ -323,9 +323,9 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8dd4e5f0bf8285d5ed538d27fab7411f3e297908fd93c62195de8bee3f199e82" dependencies = [ - "proc-macro2 1.0.37", - "quote 1.0.17", - "syn 1.0.91", + "proc-macro2 1.0.38", + "quote 1.0.18", + "syn 1.0.92", ] [[package]] @@ -345,7 +345,7 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1df2c09229cbc5a028b1d70e00fdb2acee28b1055dfb5ca73eea49c5a25c4e7c" dependencies = [ - "num-traits 0.2.14", + "num-traits 0.2.15", "rand 0.8.5", ] @@ -402,9 +402,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7862e21c893d65a1650125d157eaeec691439379a1cee17ee49031b79236ada4" dependencies = [ "proc-macro-error", - "proc-macro2 1.0.37", - "quote 1.0.17", - "syn 1.0.91", + "proc-macro2 1.0.38", + "quote 1.0.18", + "syn 1.0.92", ] [[package]] @@ -415,9 +415,9 @@ checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" [[package]] name = "backtrace" -version = "0.3.64" +version = "0.3.65" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e121dee8023ce33ab248d9ce1493df03c3b38a659b240096fcbd7048ff9c31f" +checksum = "11a17d453482a265fd5f8479f2a3f405566e6ca627837aaddb85af8b1ab8ef61" dependencies = [ "addr2line", "cc", @@ -644,7 +644,7 @@ checksum = "4acbb09d9ee8e23699b9634375c72795d095bf268439da88562cf9b501f181fa" dependencies = [ "camino", "cargo-platform", - "semver 1.0.7", + "semver 1.0.9", "serde", "serde_json", ] @@ -866,8 +866,8 @@ version = "0.1.22" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f877be4f7c9f246b183111634f75baa039715e3f46ce860677d3b19a69fb229c" dependencies = [ - "quote 1.0.17", - "syn 1.0.91", + "quote 1.0.18", + "syn 1.0.92", ] [[package]] @@ -876,9 +876,9 @@ version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fcc3dd5e9e9c0b295d6e1e4d811fb6f157d5ffd784b8d202fc62eac8035a770b" dependencies = [ - "proc-macro2 1.0.37", - "quote 1.0.17", - "syn 1.0.91", + "proc-macro2 1.0.38", + "quote 1.0.18", + "syn 1.0.92", ] [[package]] @@ -1044,9 +1044,9 @@ version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aa4da3c766cd7a0db8242e326e9e4e081edd567072893ed320008189715366a4" dependencies = [ - "proc-macro2 1.0.37", - "quote 1.0.17", - "syn 1.0.91", + "proc-macro2 1.0.38", + "quote 1.0.18", + "syn 1.0.92", "synstructure", ] @@ -1096,10 +1096,10 @@ checksum = "50c052fa6d4c2f12305ec364bfb8ef884836f3f61ea015b202372ff996d1ac4b" dependencies = [ "num-bigint 0.2.6", "num-integer", - "num-traits 0.2.14", - "proc-macro2 1.0.37", - "quote 1.0.17", - "syn 1.0.91", + "num-traits 0.2.15", + "proc-macro2 1.0.38", + "quote 1.0.18", + "syn 1.0.92", ] [[package]] @@ -1287,9 +1287,9 @@ dependencies = [ [[package]] name = "hashbrown" -version = "0.12.0" +version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8c21d40587b92fa6a6c6e3c1bdbf87d75511db5672f9c93175574b3a00df1758" +checksum = "db0d4cf898abf0081f964436dc980e96670a0f36863e4b83aaacdb65c9d7ccc3" dependencies = [ "ahash", ] @@ -1354,9 +1354,9 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "11d7a9f6330b71fea57921c9b61c47ee6e84f72d394754eff6163ae67e7395eb" dependencies = [ - "proc-macro2 1.0.37", - "quote 1.0.17", - "syn 1.0.91", + "proc-macro2 1.0.38", + "quote 1.0.18", + "syn 1.0.92", ] [[package]] @@ -1434,15 +1434,15 @@ dependencies = [ [[package]] name = "libc" -version = "0.2.122" +version = "0.2.125" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec647867e2bf0772e28c8bcde4f0d19a9216916e890543b5a03ed8ef27b8f259" +checksum = "5916d2ae698f6de9bfb891ad7a8d65c09d232dc58cc4ac433c7da3b2fd84bc2b" [[package]] name = "log" -version = "0.4.16" +version = "0.4.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6389c490849ff5bc16be905ae24bc913a9c8892e19b2341dbc175e14c341c2b8" +checksum = "abb12e687cfb44aa40f41fc3978ef76448f9b6038cad6aef4259d3c095a2382e" dependencies = [ "cfg-if 1.0.0", ] @@ -1461,9 +1461,9 @@ checksum = "60302e4db3a61da70c0cb7991976248362f30319e88850c487b9b95bbf059e00" [[package]] name = "memchr" -version = "2.4.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "308cc39be01b73d0d18f82a0e7b2a3df85245f84af96fdddc5d202d27e47b86a" +checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d" [[package]] name = "memoffset" @@ -1476,12 +1476,11 @@ dependencies = [ [[package]] name = "miniz_oxide" -version = "0.4.4" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a92518e98c078586bc6c934028adcca4c92a53d6a958196de835170a01d84e4b" +checksum = "d2b29bd4bc3f33391105ebee3589c19197c4271e3e5a9ec9bfe8127eeff8f082" dependencies = [ "adler", - "autocfg", ] [[package]] @@ -1498,7 +1497,7 @@ checksum = "4703ad64153382334aa8db57c637364c322d3372e097840c72000dabdcf6156e" dependencies = [ "num-integer", "num-iter", - "num-traits 0.2.14", + "num-traits 0.2.15", ] [[package]] @@ -1512,7 +1511,7 @@ dependencies = [ "num-integer", "num-iter", "num-rational", - "num-traits 0.2.14", + "num-traits 0.2.15", ] [[package]] @@ -1523,7 +1522,7 @@ checksum = "090c7f9998ee0ff65aa5b723e4009f7b217707f1fb5ea551329cc4d6231fb304" dependencies = [ "autocfg", "num-integer", - "num-traits 0.2.14", + "num-traits 0.2.15", "serde", ] @@ -1535,37 +1534,37 @@ checksum = "f93ab6289c7b344a8a9f60f88d80aa20032336fe78da341afc91c8a2341fc75f" dependencies = [ "autocfg", "num-integer", - "num-traits 0.2.14", + "num-traits 0.2.15", ] [[package]] name = "num-complex" -version = "0.4.0" +version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26873667bbbb7c5182d4a37c1add32cdf09f841af72da53318fdb81543c15085" +checksum = "97fbc387afefefd5e9e39493299f3069e14a140dd34dc19b4c1c1a8fddb6a790" dependencies = [ - "num-traits 0.2.14", + "num-traits 0.2.15", ] [[package]] name = "num-integer" -version = "0.1.44" +version = "0.1.45" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2cc698a63b549a70bc047073d2949cce27cd1c7b0a4a862d08a8031bc2801db" +checksum = "225d3389fb3509a24c93f5c29eb6bde2586b98d9f016636dff58d7c6f7569cd9" dependencies = [ "autocfg", - "num-traits 0.2.14", + "num-traits 0.2.15", ] [[package]] name = "num-iter" -version = "0.1.42" +version = "0.1.43" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2021c8337a54d21aca0d59a92577a029af9431cb59b909b03252b9c164fad59" +checksum = "7d03e6c028c5dc5cac6e2dec0efda81fc887605bb3d884578bb6d6bf7514e252" dependencies = [ "autocfg", "num-integer", - "num-traits 0.2.14", + "num-traits 0.2.15", ] [[package]] @@ -1577,7 +1576,7 @@ dependencies = [ "autocfg", "num-bigint 0.4.3", "num-integer", - "num-traits 0.2.14", + "num-traits 0.2.15", ] [[package]] @@ -1586,14 +1585,14 @@ version = "0.1.43" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92e5113e9fd4cc14ded8e499429f396a20f98c772a47cc8622a736e1ec843c31" dependencies = [ - "num-traits 0.2.14", + "num-traits 0.2.15", ] [[package]] name = "num-traits" -version = "0.2.14" +version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a64b1ec5cda2586e284722486d802acf1f7dbdc623e2bfc57e65ca1cd099290" +checksum = "578ede34cf02f8924ab9447f50c28075b4d3e5b269972345e7e0372b38c6cdcd" dependencies = [ "autocfg", ] @@ -1624,16 +1623,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3b0498641e53dd6ac1a4f22547548caa6864cc4933784319cd1775271c5a46ce" dependencies = [ "proc-macro-crate", - "proc-macro2 1.0.37", - "quote 1.0.17", - "syn 1.0.91", + "proc-macro2 1.0.38", + "quote 1.0.18", + "syn 1.0.92", ] [[package]] name = "object" -version = "0.27.1" +version = "0.28.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67ac1d3f9a1d3616fd9a60c8d74296f22406a238b6a72f5cc1e6f314df4ffbf9" +checksum = "e42c982f2d955fac81dd7e1d0e1426a7d702acd9c98d19ab01083a6a0328c424" dependencies = [ "memchr", ] @@ -1697,9 +1696,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c45ed1f39709f5a89338fab50e59816b2e8815f5bb58276e7ddf9afd495f73f8" dependencies = [ "proc-macro-crate", - "proc-macro2 1.0.37", - "quote 1.0.17", - "syn 1.0.91", + "proc-macro2 1.0.38", + "quote 1.0.18", + "syn 1.0.92", ] [[package]] @@ -1748,9 +1747,9 @@ checksum = "99b8db626e31e5b81787b9783425769681b347011cc59471e33ea46d2ea0cf55" dependencies = [ "pest", "pest_meta", - "proc-macro2 1.0.37", - "quote 1.0.17", - "syn 1.0.91", + "proc-macro2 1.0.38", + "quote 1.0.18", + "syn 1.0.92", ] [[package]] @@ -1782,9 +1781,9 @@ dependencies = [ [[package]] name = "pin-project-lite" -version = "0.2.8" +version = "0.2.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e280fbe77cc62c91527259e9442153f4688736748d24660126286329742b4c6c" +checksum = "e0a7ae3ac2f1173085d398531c705756c94a4c56843785df85a60c1a0afac116" [[package]] name = "pin-utils" @@ -1840,9 +1839,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c" dependencies = [ "proc-macro-error-attr", - "proc-macro2 1.0.37", - "quote 1.0.17", - "syn 1.0.91", + "proc-macro2 1.0.38", + "quote 1.0.18", + "syn 1.0.92", "version_check", ] @@ -1852,8 +1851,8 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869" dependencies = [ - "proc-macro2 1.0.37", - "quote 1.0.17", + "proc-macro2 1.0.38", + "quote 1.0.18", "version_check", ] @@ -1868,11 +1867,11 @@ dependencies = [ [[package]] name = "proc-macro2" -version = "1.0.37" +version = "1.0.38" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec757218438d5fda206afc041538b2f6d889286160d649a86a24d37e1235afd1" +checksum = "9027b48e9d4c9175fa2218adf3557f91c1137021739951d4932f5f8268ac48aa" dependencies = [ - "unicode-xid 0.2.2", + "unicode-xid 0.2.3", ] [[package]] @@ -1897,11 +1896,11 @@ dependencies = [ [[package]] name = "quote" -version = "1.0.17" +version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "632d02bff7f874a36f33ea8bb416cd484b90cc66c1194b1a1110d067a7013f58" +checksum = "a1feb54ed693b93a84e14094943b84b7c4eae204c512b7ccb95ab0c66d278ad1" dependencies = [ - "proc-macro2 1.0.37", + "proc-macro2 1.0.38", ] [[package]] @@ -2059,13 +2058,13 @@ dependencies = [ [[package]] name = "revm" -version = "1.2.0" -source = "git+https://github.com/bluealloy/revm#5f789910838ca144feb196dd91f88f5b5b1fe923" +version = "1.3.1" +source = "git+https://github.com/bluealloy/revm#8c63ba6c7f3667064608c2489c3e4b3e54451110" dependencies = [ "arrayref", "auto_impl", "bytes", - "hashbrown 0.12.0", + "hashbrown 0.12.1", "num_enum", "primitive-types", "revm_precompiles", @@ -2075,8 +2074,8 @@ dependencies = [ [[package]] name = "revm_precompiles" -version = "0.4.0" -source = "git+https://github.com/bluealloy/revm#5f789910838ca144feb196dd91f88f5b5b1fe923" +version = "1.0.0" +source = "git+https://github.com/bluealloy/revm#8c63ba6c7f3667064608c2489c3e4b3e54451110" dependencies = [ "bytes", "num 0.4.0", @@ -2183,9 +2182,9 @@ dependencies = [ [[package]] name = "secp256k1-sys" -version = "0.5.0" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07b5b9d7322572e1f3aeed208668ce87789b3645dbb73082c5ce99a004103a35" +checksum = "aa6f71720acd498e888501dd485d54bb437735f02dd95eb717dac5aee6631894" dependencies = [ "cc", ] @@ -2201,9 +2200,9 @@ dependencies = [ [[package]] name = "semver" -version = "1.0.7" +version = "1.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d65bd28f48be7196d222d95b9243287f48d27aca604e08497513019ff0502cc4" +checksum = "8cb243bdfdb5936c8dc3c45762a19d12ab4550cdc753bc247637d4ec35a040fd" dependencies = [ "serde", ] @@ -2219,9 +2218,9 @@ dependencies = [ [[package]] name = "serde" -version = "1.0.136" +version = "1.0.137" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce31e24b01e1e524df96f1c2fdd054405f8d7376249a5110886fb4b658484789" +checksum = "61ea8d54c77f8315140a05f4c7237403bf38b72704d031543aa1d16abbf517d1" dependencies = [ "serde_derive", ] @@ -2238,20 +2237,20 @@ dependencies = [ [[package]] name = "serde_derive" -version = "1.0.136" +version = "1.0.137" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08597e7152fcd306f41838ed3e37be9eaeed2b61c42e2117266a554fab4662f9" +checksum = "1f26faba0c3959972377d3b2d306ee9f71faee9714294e41bb777f83f88578be" dependencies = [ - "proc-macro2 1.0.37", - "quote 1.0.17", - "syn 1.0.91", + "proc-macro2 1.0.38", + "quote 1.0.18", + "syn 1.0.92", ] [[package]] name = "serde_json" -version = "1.0.79" +version = "1.0.81" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e8d9fa5c3b304765ce1fd9c4c8a3de2c8db365a5b91be52f186efc675681d95" +checksum = "9b7ce2b32a1aed03c558dc61a5cd328f15aff2dbc17daad8fb8af04d2100e15c" dependencies = [ "indexmap", "itoa 1.0.1", @@ -2411,13 +2410,13 @@ dependencies = [ [[package]] name = "syn" -version = "1.0.91" +version = "1.0.92" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b683b2b825c8eef438b77c36a06dc262294da3d5a5813fac20da149241dcd44d" +checksum = "7ff7c592601f11445996a06f8ad0c27f094a58857c2f89e97974ab9235b92c52" dependencies = [ - "proc-macro2 1.0.37", - "quote 1.0.17", - "unicode-xid 0.2.2", + "proc-macro2 1.0.38", + "quote 1.0.18", + "unicode-xid 0.2.3", ] [[package]] @@ -2426,10 +2425,10 @@ version = "0.12.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f36bdaa60a83aca3921b5259d5400cbf5e90fc51931376a9bd4a0eb79aa7210f" dependencies = [ - "proc-macro2 1.0.37", - "quote 1.0.17", - "syn 1.0.91", - "unicode-xid 0.2.2", + "proc-macro2 1.0.38", + "quote 1.0.18", + "syn 1.0.92", + "unicode-xid 0.2.3", ] [[package]] @@ -2482,22 +2481,22 @@ dependencies = [ [[package]] name = "thiserror" -version = "1.0.30" +version = "1.0.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "854babe52e4df1653706b98fcfc05843010039b406875930a70e4d9644e5c417" +checksum = "bd829fe32373d27f76265620b5309d0340cb8550f523c1dda251d6298069069a" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" -version = "1.0.30" +version = "1.0.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aa32fd3f627f367fe16f893e2597ae3c05020f8bba2666a4e6ea73d377e5714b" +checksum = "0396bc89e626244658bef819e22d0cc459e795a5ebe878e6ec336d1674a8d79a" dependencies = [ - "proc-macro2 1.0.37", - "quote 1.0.17", - "syn 1.0.91", + "proc-macro2 1.0.38", + "quote 1.0.18", + "syn 1.0.92", ] [[package]] @@ -2520,18 +2519,18 @@ dependencies = [ [[package]] name = "toml" -version = "0.5.8" +version = "0.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a31142970826733df8241ef35dc040ef98c679ab14d7c3e54d827099b3acecaa" +checksum = "8d82e1a7758622a465f8cee077614c73484dac5b836c02ff6a40d5d1010324d7" dependencies = [ "serde", ] [[package]] name = "tracing" -version = "0.1.32" +version = "0.1.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4a1bdf54a7c28a2bbf701e1d2233f6c77f473486b94bee4f9678da5a148dca7f" +checksum = "5d0ecdcb44a79f0fe9844f0c4f33a342cbcbb5117de8001e6ba0dc2351327d09" dependencies = [ "cfg-if 1.0.0", "pin-project-lite", @@ -2541,20 +2540,20 @@ dependencies = [ [[package]] name = "tracing-attributes" -version = "0.1.20" +version = "0.1.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e65ce065b4b5c53e73bb28912318cb8c9e9ad3921f1d669eb0e68b4c8143a2b" +checksum = "cc6b8ad3567499f98a1db7a752b07a7c8c7c7c34c332ec00effb2b0027974b7c" dependencies = [ - "proc-macro2 1.0.37", - "quote 1.0.17", - "syn 1.0.91", + "proc-macro2 1.0.38", + "quote 1.0.18", + "syn 1.0.92", ] [[package]] name = "tracing-core" -version = "0.1.24" +version = "0.1.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90442985ee2f57c9e1b548ee72ae842f4a9a20e3f417cc38dbc5dc684d9bb4ee" +checksum = "f54c8ca710e81886d498c2fd3331b56c93aa248d49de2222ad2742247c60072f" [[package]] name = "typed-arena" @@ -2615,9 +2614,9 @@ checksum = "fc72304796d0818e357ead4e000d19c9c174ab23dc11093ac919054d20a6a7fc" [[package]] name = "unicode-xid" -version = "0.2.2" +version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ccb82d61f80a663efe1f787a51b16b5a51e3314d6ac365b08639f52387b33f3" +checksum = "957e51f3646910546462e67d5f7599b9e4fb8acdd304b087a6494730f9eebf04" [[package]] name = "utf8-ranges" @@ -2679,9 +2678,9 @@ dependencies = [ "bumpalo", "lazy_static", "log", - "proc-macro2 1.0.37", - "quote 1.0.17", - "syn 1.0.91", + "proc-macro2 1.0.38", + "quote 1.0.18", + "syn 1.0.92", "wasm-bindgen-shared", ] @@ -2703,7 +2702,7 @@ version = "0.2.80" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "17cae7ff784d7e83a2fe7611cfe766ecf034111b49deb850a3dc7699c08251f5" dependencies = [ - "quote 1.0.17", + "quote 1.0.18", "wasm-bindgen-macro-support", ] @@ -2713,9 +2712,9 @@ version = "0.2.80" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "99ec0dc7a4756fffc231aab1b9f2f578d23cd391390ab27f952ae0c9b3ece20b" dependencies = [ - "proc-macro2 1.0.37", - "quote 1.0.17", - "syn 1.0.91", + "proc-macro2 1.0.38", + "quote 1.0.18", + "syn 1.0.92", "wasm-bindgen-backend", "wasm-bindgen-shared", ] @@ -2746,8 +2745,8 @@ version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a77c5a6f82cc6093a321ca5fb3dc9327fe51675d477b3799b4a9375bac3b7b4c" dependencies = [ - "proc-macro2 1.0.37", - "quote 1.0.17", + "proc-macro2 1.0.38", + "quote 1.0.18", ] [[package]] @@ -2802,9 +2801,9 @@ dependencies = [ [[package]] name = "zeroize" -version = "1.5.4" +version = "1.5.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7eb5728b8afd3f280a869ce1d4c554ffaed35f45c231fc41bfbd0381bef50317" +checksum = "94693807d016b2f2d2e14420eb3bfcca689311ff775dcf113d74ea624b7cdf07" dependencies = [ "zeroize_derive", ] @@ -2815,9 +2814,9 @@ version = "1.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f8f187641dad4f680d25c4bfc4225b418165984179f26ca76ec4fb6441d3a17" dependencies = [ - "proc-macro2 1.0.37", - "quote 1.0.17", - "syn 1.0.91", + "proc-macro2 1.0.38", + "quote 1.0.18", + "syn 1.0.92", "synstructure", ] @@ -2832,6 +2831,28 @@ dependencies = [ "zokrates_field", ] +[[package]] +name = "zokrates_ark" +version = "0.1.0" +dependencies = [ + "zokrates_ast", + "zokrates_field", +] + +[[package]] +name = "zokrates_ast" +version = "0.1.0" +dependencies = [ + "cfg-if 0.1.10", + "csv", + "num-bigint 0.2.6", + "serde", + "serde_cbor", + "serde_json", + "zokrates_field", + "zokrates_pest_ast", +] + [[package]] name = "zokrates_cli" version = "0.7.13" @@ -2911,15 +2932,16 @@ dependencies = [ "reduce", "regex 0.2.11", "serde", - "serde_cbor", "serde_json", "sha3 0.9.1", "typed-arena", "wasm-bindgen-test", + "zokrates_ast", "zokrates_common", "zokrates_embed", "zokrates_field", "zokrates_fs_resolver", + "zokrates_interpreter", "zokrates_pest_ast", ] @@ -2965,7 +2987,7 @@ dependencies = [ "lazy_static", "num-bigint 0.2.6", "num-integer", - "num-traits 0.2.14", + "num-traits 0.2.15", "rand 0.4.6", "serde", "serde_derive", @@ -2981,6 +3003,16 @@ dependencies = [ "zokrates_common", ] +[[package]] +name = "zokrates_interpreter" +version = "0.1.0" +dependencies = [ + "num 0.1.42", + "num-bigint 0.2.6", + "zokrates_ast", + "zokrates_field", +] + [[package]] name = "zokrates_parser" version = "0.2.6" diff --git a/Cargo.toml b/Cargo.toml index 80ac413c..b93fb355 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,6 +11,10 @@ members = [ "zokrates_test", "zokrates_core_test", "zokrates_solidity_test", + "zokrates_ark", + "zokrates_ast", + "zokrates_interpreter", + "zokrates_embed", ] exclude = ["zokrates_js"] \ No newline at end of file diff --git a/zokrates_ark/Cargo.toml b/zokrates_ark/Cargo.toml new file mode 100644 index 00000000..2658fc61 --- /dev/null +++ b/zokrates_ark/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "zokrates_ark" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +zokrates_field = { version = "0.5", path = "../zokrates_field", default-features = false } +zokrates_ast = { version = "0.1", path = "../zokrates_ast", default-features = false } diff --git a/zokrates_core/src/proof_system/ark/gm17.rs b/zokrates_ark/src/gm17.rs similarity index 98% rename from zokrates_core/src/proof_system/ark/gm17.rs rename to zokrates_ark/src/gm17.rs index 79fd6eff..6ef10a92 100644 --- a/zokrates_core/src/proof_system/ark/gm17.rs +++ b/zokrates_ark/src/gm17.rs @@ -6,7 +6,6 @@ use ark_gm17::{ use ark_serialize::{CanonicalDeserialize, CanonicalSerialize}; use zokrates_field::{ArkFieldExtensions, Bw6_761Field, Field}; -use crate::ir::{ProgIterator, Statement, Witness}; use crate::proof_system::ark::Computation; use crate::proof_system::ark::{parse_fr, parse_g1, parse_g2, parse_g2_fq}; use crate::proof_system::ark::{serialization, Ark}; @@ -15,6 +14,7 @@ use crate::proof_system::{Backend, NonUniversalBackend, Proof, SetupKeypair}; use crate::proof_system::{NotBw6_761Field, Scheme}; use ark_bw6_761::BW6_761; use rand_0_8::{rngs::StdRng, SeedableRng}; +use zokrates_ast::ir::{ProgIterator, Statement, Witness}; impl NonUniversalBackend for Ark { fn setup>>( @@ -209,7 +209,7 @@ impl Backend for Ark { #[cfg(test)] mod tests { use crate::flat_absy::{FlatParameter, FlatVariable}; - use crate::ir::{Interpreter, Prog, Statement}; + use zokrates_ast::ir::{Interpreter, Prog, Statement}; use super::*; use zokrates_field::{Bls12_377Field, Bw6_761Field}; diff --git a/zokrates_core/src/proof_system/ark/groth16.rs b/zokrates_ark/src/groth16.rs similarity index 98% rename from zokrates_core/src/proof_system/ark/groth16.rs rename to zokrates_ark/src/groth16.rs index 87ef2721..13fc867f 100644 --- a/zokrates_core/src/proof_system/ark/groth16.rs +++ b/zokrates_ark/src/groth16.rs @@ -8,7 +8,6 @@ use ark_serialize::{CanonicalDeserialize, CanonicalSerialize}; use zokrates_field::Field; use zokrates_field::{ArkFieldExtensions, Bw6_761Field}; -use crate::ir::{ProgIterator, Statement, Witness}; use crate::proof_system::ark::Computation; use crate::proof_system::ark::{parse_fr, serialization, Ark}; use crate::proof_system::ark::{parse_g1, parse_g2}; @@ -16,6 +15,7 @@ use crate::proof_system::groth16::{ProofPoints, VerificationKey, G16}; use crate::proof_system::Scheme; use ark_bw6_761::BW6_761; use rand_0_8::{rngs::StdRng, SeedableRng}; +use zokrates_ast::ir::{ProgIterator, Statement, Witness}; 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."; @@ -213,7 +213,7 @@ impl NonUniversalBackend for Ark { #[cfg(test)] mod tests { use crate::flat_absy::{FlatParameter, FlatVariable}; - use crate::ir::{Interpreter, Prog, Statement}; + use zokrates_ast::ir::{Interpreter, Prog, Statement}; use super::*; use zokrates_field::{Bls12_377Field, Bw6_761Field}; diff --git a/zokrates_core/src/proof_system/ark/mod.rs b/zokrates_ark/src/lib.rs similarity index 99% rename from zokrates_core/src/proof_system/ark/mod.rs rename to zokrates_ark/src/lib.rs index 192d7303..40f090c6 100644 --- a/zokrates_core/src/proof_system/ark/mod.rs +++ b/zokrates_ark/src/lib.rs @@ -3,13 +3,13 @@ pub mod groth16; pub mod marlin; use crate::flat_absy::FlatVariable; -use crate::ir::{CanonicalLinComb, ProgIterator, Statement, Witness}; use ark_ec::PairingEngine; use ark_relations::r1cs::{ ConstraintSynthesizer, ConstraintSystem, ConstraintSystemRef, LinearCombination, SynthesisError, Variable, }; use std::collections::BTreeMap; +use zokrates_ast::ir::{CanonicalLinComb, ProgIterator, Statement, Witness}; use zokrates_field::{ArkFieldExtensions, Field}; pub use self::parse::*; diff --git a/zokrates_core/src/proof_system/ark/marlin.rs b/zokrates_ark/src/marlin.rs similarity index 99% rename from zokrates_core/src/proof_system/ark/marlin.rs rename to zokrates_ark/src/marlin.rs index 15a813db..576acd84 100644 --- a/zokrates_core/src/proof_system/ark/marlin.rs +++ b/zokrates_ark/src/marlin.rs @@ -23,13 +23,13 @@ use std::marker::PhantomData; use zokrates_field::{ArkFieldExtensions, Field}; -use crate::ir::{ProgIterator, Statement, Witness}; use crate::proof_system::ark::Ark; use crate::proof_system::ark::Computation; use crate::proof_system::ark::{parse_fr, parse_g1, parse_g2, serialization}; use crate::proof_system::marlin::{self, KZGVerifierKey, ProofPoints, VerificationKey}; use crate::proof_system::Scheme; use crate::proof_system::{Backend, Proof, SetupKeypair, UniversalBackend}; +use zokrates_ast::ir::{ProgIterator, Statement, Witness}; const MINIMUM_CONSTRAINT_COUNT: usize = 2; @@ -387,7 +387,7 @@ impl Backend for Ark { #[cfg(test)] mod tests { use crate::flat_absy::{FlatParameter, FlatVariable}; - use crate::ir::{Interpreter, Prog, QuadComb, Statement}; + use zokrates_ast::ir::{Interpreter, Prog, QuadComb, Statement}; use super::*; use crate::proof_system::scheme::Marlin; diff --git a/zokrates_ast/Cargo.toml b/zokrates_ast/Cargo.toml new file mode 100644 index 00000000..63288786 --- /dev/null +++ b/zokrates_ast/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "zokrates_ast" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +zokrates_pest_ast = { version = "0.2.0", path = "../zokrates_pest_ast" } +cfg-if = "0.1" +zokrates_field = { version = "0.5", path = "../zokrates_field", default-features = false } +serde = { version = "1.0", features = ["derive"] } +csv = "1" +serde_cbor = "0.11.2" +num-bigint = { version = "0.2", default-features = false } +serde_json = { version = "1.0", features = ["preserve_order"] } + + + + diff --git a/zokrates_core/src/embed.rs b/zokrates_ast/src/common/embed.rs similarity index 91% rename from zokrates_core/src/embed.rs rename to zokrates_ast/src/common/embed.rs index 54906148..47551172 100644 --- a/zokrates_core/src/embed.rs +++ b/zokrates_ast/src/common/embed.rs @@ -1,16 +1,13 @@ -use crate::absy::{ - types::{UnresolvedSignature, UnresolvedType}, - ConstantGenericNode, Expression, -}; -use crate::flat_absy::{ - FlatDirective, FlatExpression, FlatFunctionIterator, FlatParameter, FlatStatement, - FlatVariable, RuntimeError, -}; -use crate::solvers::Solver; -use crate::typed_absy::types::{ +use crate::common::{Parameter, RuntimeError, Solver, Variable}; +use crate::flat::{FlatDirective, FlatExpression, FlatFunctionIterator, FlatStatement}; +use crate::typed::types::{ ConcreteGenericsAssignment, DeclarationConstant, DeclarationSignature, DeclarationType, GenericIdentifier, }; +use crate::untyped::{ + types::{UnresolvedSignature, UnresolvedType}, + ConstantGenericNode, Expression, +}; use std::collections::HashMap; use zokrates_field::Field; @@ -324,7 +321,7 @@ fn flat_expression_from_vec(v: &[(usize, T)]) -> FlatExpression { let (key, val) = v[0].clone(); FlatExpression::Mult( box FlatExpression::Number(val), - box FlatExpression::Identifier(FlatVariable::new(key)), + box FlatExpression::Identifier(Variable::new(key)), ) } n => { @@ -347,6 +344,7 @@ fn flat_expression_from_vec(v: &[(usize, T)]) -> FlatExpression { #[cfg(feature = "bellman")] pub fn sha256_round( ) -> FlatFunctionIterator>> { + use zokrates_ast::ir::RuntimeError; use zokrates_field::Bn128Field; assert_eq!(T::id(), Bn128Field::id()); @@ -383,14 +381,14 @@ pub fn sha256_round( .clone() .into_iter() .chain(current_hash_argument_indices.clone()) - .map(|i| FlatParameter { - id: FlatVariable::new(i), + .map(|i| Parameter { + id: Variable::new(i), private: true, }) .collect(); // define a binding of the first variable in the constraint system to one let one_binding_statement = FlatStatement::Condition( - FlatVariable::new(0).into(), + Variable::new(0).into(), FlatExpression::Number(T::from(1)), RuntimeError::BellmanOneBinding, ); @@ -398,8 +396,8 @@ pub fn sha256_round( // bind input and current_hash to inputs input_indices.chain(current_hash_indices).zip(input_argument_indices.clone().into_iter().chain(current_hash_argument_indices.clone())).map(|(cs_index, argument_index)| { FlatStatement::Condition( - FlatVariable::new(cs_index).into(), - FlatVariable::new(argument_index).into(), + Variable::new(cs_index).into(), + Variable::new(argument_index).into(), RuntimeError::BellmanInputBinding ) }); @@ -418,14 +416,14 @@ pub fn sha256_round( }); // define which subset of the witness is returned - let outputs = output_indices.map(|o| FlatExpression::Identifier(FlatVariable::new(o))); + let outputs = output_indices.map(|o| FlatExpression::Identifier(Variable::new(o))); // insert a directive to set the witness based on the bellman gadget and inputs let directive_statement = FlatStatement::Directive(FlatDirective { - outputs: cs_indices.map(FlatVariable::new).collect(), + outputs: cs_indices.map(Variable::new).collect(), inputs: input_argument_indices .into_iter() .chain(current_hash_argument_indices) - .map(|i| FlatVariable::new(i).into()) + .map(|i| Variable::new(i).into()) .collect(), solver: Solver::Sha256Round, }); @@ -433,7 +431,7 @@ pub fn sha256_round( let return_statements = outputs .into_iter() .enumerate() - .map(|(index, e)| FlatStatement::Definition(FlatVariable::public(index), e)); + .map(|(index, e)| FlatStatement::Definition(Variable::public(index), e)); let statements = std::iter::once(directive_statement) .chain(std::iter::once(one_binding_statement)) .chain(input_binding_statements) @@ -451,6 +449,7 @@ pub fn sha256_round( pub fn snark_verify_bls12_377( n: usize, ) -> FlatFunctionIterator>> { + use zokrates_ast::ir::RuntimeError; use zokrates_field::Bw6_761Field; assert_eq!(T::id(), Bw6_761Field::id()); @@ -471,15 +470,15 @@ pub fn snark_verify_bls12_377( let input_arguments = input_argument_indices .clone() - .map(|i| FlatParameter::private(FlatVariable::new(i))); + .map(|i| Parameter::private(Variable::new(i))); let proof_arguments = proof_argument_indices .clone() - .map(|i| FlatParameter::private(FlatVariable::new(i))); + .map(|i| Parameter::private(Variable::new(i))); let vk_arguments = vk_argument_indices .clone() - .map(|i| FlatParameter::private(FlatVariable::new(i))); + .map(|i| Parameter::private(Variable::new(i))); let arguments = input_arguments .chain(proof_arguments) @@ -487,7 +486,7 @@ pub fn snark_verify_bls12_377( .collect(); let one_binding_statement = FlatStatement::Condition( - FlatExpression::Identifier(FlatVariable::new(0)), + FlatExpression::Identifier(Variable::new(0)), FlatExpression::Number(T::from(1)), RuntimeError::ArkOneBinding, ); @@ -503,8 +502,8 @@ pub fn snark_verify_bls12_377( ) .map(|(cs_index, argument_index)| { FlatStatement::Condition( - FlatVariable::new(cs_index).into(), - FlatVariable::new(argument_index).into(), + Variable::new(cs_index).into(), + Variable::new(argument_index).into(), RuntimeError::ArkInputBinding, ) }) @@ -527,17 +526,17 @@ pub fn snark_verify_bls12_377( .collect(); let return_statement = FlatStatement::Definition( - FlatVariable::public(0), - FlatExpression::Identifier(FlatVariable::new(out_index)), + Variable::public(0), + FlatExpression::Identifier(Variable::new(out_index)), ); // insert a directive to set the witness let directive_statement = FlatStatement::Directive(FlatDirective { - outputs: cs_indices.map(FlatVariable::new).collect(), + outputs: cs_indices.map(Variable::new).collect(), inputs: input_argument_indices .chain(proof_argument_indices) .chain(vk_argument_indices) - .map(|i| FlatVariable::new(i).into()) + .map(|i| Variable::new(i).into()) .collect(), solver: Solver::SnarkVerifyBls12377(n), }); @@ -556,11 +555,11 @@ pub fn snark_verify_bls12_377( } fn use_variable( - layout: &mut HashMap, + layout: &mut HashMap, name: String, index: &mut usize, -) -> FlatVariable { - let var = FlatVariable::new(*index); +) -> Variable { + let var = Variable::new(*index); layout.insert(name, var); *index += 1; var @@ -581,8 +580,8 @@ pub fn unpack_to_bitwidth( let mut layout = HashMap::new(); - let arguments = vec![FlatParameter { - id: FlatVariable::new(0), + let arguments = vec![Parameter { + id: Variable::new(0), private: true, }]; @@ -594,7 +593,7 @@ pub fn unpack_to_bitwidth( &mut counter, ))]; - let directive_outputs: Vec = (0..bit_width) + let directive_outputs: Vec = (0..bit_width) .map(|index| use_variable(&mut layout, format!("o{}", index), &mut counter)) .collect(); @@ -610,7 +609,7 @@ pub fn unpack_to_bitwidth( // o253, o252, ... o{253 - (bit_width - 1)} are bits let mut statements: Vec> = (0..bit_width) .map(|index| { - let bit = FlatExpression::Identifier(FlatVariable::new(bit_width - index)); + let bit = FlatExpression::Identifier(Variable::new(bit_width - index)); FlatStatement::Condition( bit.clone(), FlatExpression::Mult(box bit.clone(), box bit.clone()), @@ -626,7 +625,7 @@ pub fn unpack_to_bitwidth( lhs_sum = FlatExpression::Add( box lhs_sum, box FlatExpression::Mult( - box FlatExpression::Identifier(FlatVariable::new(bit_width - i)), + box FlatExpression::Identifier(Variable::new(bit_width - i)), box FlatExpression::Number(T::from(2).pow(i)), ), ); @@ -635,7 +634,7 @@ pub fn unpack_to_bitwidth( statements.push(FlatStatement::Condition( lhs_sum, FlatExpression::Mult( - box FlatExpression::Identifier(FlatVariable::new(0)), + box FlatExpression::Identifier(Variable::new(0)), box FlatExpression::Number(T::from(1)), ), RuntimeError::Sum, @@ -654,7 +653,7 @@ pub fn unpack_to_bitwidth( outputs .into_iter() .enumerate() - .map(|(index, e)| FlatStatement::Definition(FlatVariable::public(index), e)), + .map(|(index, e)| FlatStatement::Definition(Variable::public(index), e)), ); FlatFunctionIterator { @@ -678,18 +677,15 @@ mod tests { let unpack = unpack_to_bitwidth::(Bn128Field::get_required_bits()).collect(); - assert_eq!( - unpack.arguments, - vec![FlatParameter::private(FlatVariable::new(0))] - ); + assert_eq!(unpack.arguments, vec![Parameter::private(Variable::new(0))]); assert_eq!( unpack.statements[0], FlatStatement::Directive(FlatDirective::new( (0..Bn128Field::get_required_bits()) - .map(|i| FlatVariable::new(i + 1)) + .map(|i| Variable::new(i + 1)) .collect(), Solver::bits(Bn128Field::get_required_bits()), - vec![FlatVariable::new(0)] + vec![Variable::new(0)] )) ); assert_eq!( @@ -703,7 +699,7 @@ mod tests { #[cfg(test)] mod sha256 { use super::*; - use crate::ir::Interpreter; + use zokrates_ast::ir::Interpreter; #[test] fn generate_sha256_constraints() { @@ -732,14 +728,14 @@ mod tests { // function input should be offset by variable_count assert_eq!( compiled.arguments[0].id, - FlatVariable::new(directive.outputs.len() + 1) + Variable::new(directive.outputs.len() + 1) ); // bellman variable #0: index 0 should equal 1 assert_eq!( compiled.statements[1], FlatStatement::Condition( - FlatVariable::new(0).into(), + Variable::new(0).into(), FlatExpression::Number(Bn128Field::from(1)), RuntimeError::BellmanOneBinding ) @@ -749,8 +745,8 @@ mod tests { assert_eq!( compiled.statements[2], FlatStatement::Condition( - FlatVariable::new(1).into(), - FlatVariable::new(26936).into(), + Variable::new(1).into(), + Variable::new(26936).into(), RuntimeError::BellmanInputBinding ) ); @@ -761,7 +757,7 @@ mod tests { .map(Bn128Field::from) .collect(); - let ir = crate::ir::from_flat::from_flat(compiled); + let ir = zokrates_ast::ir::from_flat::from_flat(compiled); let interpreter = Interpreter::default(); interpreter.execute(ir, &input).unwrap(); diff --git a/zokrates_ast/src/common/error.rs b/zokrates_ast/src/common/error.rs new file mode 100644 index 00000000..c1fe0656 --- /dev/null +++ b/zokrates_ast/src/common/error.rs @@ -0,0 +1,82 @@ +use serde::{Deserialize, Serialize}; +use std::fmt; + +#[derive(Debug, Clone, Serialize, Deserialize, Hash, PartialEq, Eq)] +pub enum RuntimeError { + BellmanConstraint, + BellmanOneBinding, + BellmanInputBinding, + ArkConstraint, + ArkOneBinding, + ArkInputBinding, + Bitness, + Sum, + Equal, + Le, + BranchIsolation, + ConstantLtBitness, + ConstantLtSum, + LtBitness, + LtSum, + LtFinalBitness, + LtFinalSum, + LtSymetric, + Or, + Xor, + Inverse, + Euclidean, + ShaXor, + Division, + SourceAssertion(String), + ArgumentBitness, + SelectRangeCheck, +} + +impl RuntimeError { + pub fn is_malicious(&self) -> bool { + use RuntimeError::*; + + !matches!( + self, + SourceAssertion(_) | Inverse | LtSum | SelectRangeCheck | ArgumentBitness + ) + } +} + +impl fmt::Display for RuntimeError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + use RuntimeError::*; + + let msg = match self { + BellmanConstraint => "Bellman constraint is unsatisfied", + BellmanOneBinding => "Bellman ~one binding is unsatisfied", + BellmanInputBinding => "Bellman input binding is unsatisfied", + ArkConstraint => "Ark constraint is unsatisfied", + ArkOneBinding => "Ark ~one binding is unsatisfied", + ArkInputBinding => "Ark input binding is unsatisfied", + Bitness => "Bitness check failed", + Sum => "Sum check failed", + Equal => "Equal check failed", + Le => "Constant Le check failed", + BranchIsolation => "Branch isolation failed", + ConstantLtBitness => "Bitness check failed in constant Lt check", + ConstantLtSum => "Sum check failed in constant Lt check", + LtBitness => "Bitness check failed in Lt check", + LtSum => "Sum check failed in Lt check", + LtFinalBitness => "Bitness check failed in final Lt check", + LtFinalSum => "Sum check failed in final Lt check", + LtSymetric => "Symetrical check failed in Lt check", + Or => "Or check failed", + Xor => "Xor check failed", + Inverse => "Division by zero", + Euclidean => "Euclidean check failed", + ShaXor => "Internal Sha check failed", + Division => "Division check failed", + SourceAssertion(m) => m.as_str(), + ArgumentBitness => "Argument bitness check failed", + SelectRangeCheck => "Out of bounds array access", + }; + + write!(f, "{}", msg) + } +} diff --git a/zokrates_ast/src/common/mod.rs b/zokrates_ast/src/common/mod.rs new file mode 100644 index 00000000..c7d5e0b4 --- /dev/null +++ b/zokrates_ast/src/common/mod.rs @@ -0,0 +1,11 @@ +pub mod embed; +mod error; +mod parameter; +mod solvers; +mod variable; + +pub use self::embed::FlatEmbed; +pub use self::error::RuntimeError; +pub use self::parameter::Parameter; +pub use self::solvers::Solver; +pub use self::variable::Variable; diff --git a/zokrates_core/src/flat_absy/flat_parameter.rs b/zokrates_ast/src/common/parameter.rs similarity index 50% rename from zokrates_core/src/flat_absy/flat_parameter.rs rename to zokrates_ast/src/common/parameter.rs index c54ec5e7..4b17395f 100644 --- a/zokrates_core/src/flat_absy/flat_parameter.rs +++ b/zokrates_ast/src/common/parameter.rs @@ -1,47 +1,44 @@ -use crate::flat_absy::flat_variable::FlatVariable; +use super::variable::Variable; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::fmt; #[derive(Serialize, Deserialize, Hash, Eq, PartialEq, Clone, Copy)] -pub struct FlatParameter { - pub id: FlatVariable, +pub struct Parameter { + pub id: Variable, pub private: bool, } -impl FlatParameter { - fn new(id: FlatVariable, private: bool) -> Self { - FlatParameter { id, private } +impl Parameter { + fn new(id: Variable, private: bool) -> Self { + Parameter { id, private } } - pub fn public(v: FlatVariable) -> Self { + pub fn public(v: Variable) -> Self { Self::new(v, false) } - pub fn private(v: FlatVariable) -> Self { + pub fn private(v: Variable) -> Self { Self::new(v, true) } } -impl fmt::Display for FlatParameter { +impl fmt::Display for Parameter { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let visibility = if self.private { "private " } else { "" }; write!(f, "{}{}", visibility, self.id) } } -impl fmt::Debug for FlatParameter { +impl fmt::Debug for Parameter { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "FlatParameter(id: {:?})", self.id) + write!(f, "Parameter(id: {:?})", self.id) } } -impl FlatParameter { - pub fn apply_substitution( - self, - substitution: &HashMap, - ) -> FlatParameter { - FlatParameter { +impl Parameter { + pub fn apply_substitution(self, substitution: &HashMap) -> Parameter { + Parameter { id: *substitution.get(&self.id).unwrap(), private: self.private, } diff --git a/zokrates_core/src/solvers/mod.rs b/zokrates_ast/src/common/solvers.rs similarity index 100% rename from zokrates_core/src/solvers/mod.rs rename to zokrates_ast/src/common/solvers.rs diff --git a/zokrates_core/src/flat_absy/flat_variable.rs b/zokrates_ast/src/common/variable.rs similarity index 71% rename from zokrates_core/src/flat_absy/flat_variable.rs rename to zokrates_ast/src/common/variable.rs index 1fe3f6b4..7a6b9b01 100644 --- a/zokrates_core/src/flat_absy/flat_variable.rs +++ b/zokrates_ast/src/common/variable.rs @@ -7,23 +7,23 @@ use std::fmt; // id == 0 for ~one // id < 0 for public outputs #[derive(Serialize, Deserialize, Clone, PartialEq, Hash, Eq, Ord, PartialOrd, Copy)] -pub struct FlatVariable { +pub struct Variable { id: isize, } -impl FlatVariable { +impl Variable { pub fn new(id: usize) -> Self { - FlatVariable { + Variable { id: 1 + id as isize, } } pub fn one() -> Self { - FlatVariable { id: 0 } + Variable { id: 0 } } pub fn public(id: usize) -> Self { - FlatVariable { + Variable { id: -(id as isize) - 1, } } @@ -35,21 +35,21 @@ impl FlatVariable { pub fn try_from_human_readable(s: &str) -> Result { if s == "~one" { - return Ok(FlatVariable::one()); + return Ok(Variable::one()); } let mut public = s.split("~out_"); match public.nth(1) { Some(v) => { let v = v.parse().map_err(|_| s)?; - Ok(FlatVariable::public(v)) + Ok(Variable::public(v)) } None => { let mut private = s.split('_'); match private.nth(1) { Some(v) => { let v = v.parse().map_err(|_| s)?; - Ok(FlatVariable::new(v)) + Ok(Variable::new(v)) } None => Err(s), } @@ -58,7 +58,7 @@ impl FlatVariable { } } -impl fmt::Display for FlatVariable { +impl fmt::Display for Variable { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.id { 0 => write!(f, "~one"), @@ -68,7 +68,7 @@ impl fmt::Display for FlatVariable { } } -impl fmt::Debug for FlatVariable { +impl fmt::Debug for Variable { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.id { 0 => write!(f, "~one"), @@ -78,8 +78,8 @@ impl fmt::Debug for FlatVariable { } } -impl FlatVariable { - pub fn apply_substitution(self, substitution: &HashMap) -> &Self { +impl Variable { + pub fn apply_substitution(self, substitution: &HashMap) -> &Self { substitution.get(&self).unwrap() } @@ -94,18 +94,18 @@ mod tests { #[test] fn one() { - assert_eq!(format!("{}", FlatVariable::one()), "~one"); + assert_eq!(format!("{}", Variable::one()), "~one"); } #[test] fn public() { - assert_eq!(format!("{}", FlatVariable::public(0)), "~out_0"); - assert_eq!(format!("{}", FlatVariable::public(42)), "~out_42"); + assert_eq!(format!("{}", Variable::public(0)), "~out_0"); + assert_eq!(format!("{}", Variable::public(42)), "~out_42"); } #[test] fn private() { - assert_eq!(format!("{}", FlatVariable::new(0)), "_0"); - assert_eq!(format!("{}", FlatVariable::new(42)), "_42"); + assert_eq!(format!("{}", Variable::new(0)), "_0"); + assert_eq!(format!("{}", Variable::new(42)), "_42"); } } diff --git a/zokrates_ast/src/flat/folder.rs b/zokrates_ast/src/flat/folder.rs new file mode 100644 index 00000000..a000c8b4 --- /dev/null +++ b/zokrates_ast/src/flat/folder.rs @@ -0,0 +1,92 @@ +// Generic walk through an IR AST. Not mutating in place + +use super::*; +use crate::common::Variable; +use zokrates_field::Field; + +pub trait Folder: Sized { + fn fold_program(&mut self, p: FlatProg) -> FlatProg { + fold_program(self, p) + } + + fn fold_argument(&mut self, p: Parameter) -> Parameter { + fold_argument(self, p) + } + + fn fold_variable(&mut self, v: Variable) -> Variable { + fold_variable(self, v) + } + + fn fold_statement(&mut self, s: FlatStatement) -> Vec> { + fold_statement(self, s) + } + + fn fold_expression(&mut self, e: FlatExpression) -> FlatExpression { + fold_expression(self, e) + } + + fn fold_directive(&mut self, d: FlatDirective) -> FlatDirective { + fold_directive(self, d) + } +} + +pub fn fold_program>(f: &mut F, p: FlatProg) -> FlatProg { + FlatProg { + arguments: p + .arguments + .into_iter() + .map(|a| f.fold_argument(a)) + .collect(), + statements: p + .statements + .into_iter() + .flat_map(|s| f.fold_statement(s)) + .collect(), + return_count: p.return_count, + } +} + +pub fn fold_statement>( + f: &mut F, + s: FlatStatement, +) -> Vec> { + // match s { + // Statement::Constraint(quad, lin, message) => vec![Statement::Constraint( + // f.fold_quadratic_combination(quad), + // f.fold_linear_combination(lin), + // message, + // )], + // Statement::Directive(dir) => vec![Statement::Directive(f.fold_directive(dir))], + // } + unimplemented!() +} + +pub fn fold_expression>( + f: &mut F, + e: FlatExpression, +) -> FlatExpression { + unimplemented!() +} + +pub fn fold_directive>(f: &mut F, ds: FlatDirective) -> FlatDirective { + FlatDirective { + inputs: ds + .inputs + .into_iter() + .map(|e| f.fold_expression(e)) + .collect(), + outputs: ds.outputs.into_iter().map(|o| f.fold_variable(o)).collect(), + ..ds + } +} + +pub fn fold_argument>(f: &mut F, a: Parameter) -> Parameter { + Parameter { + id: f.fold_variable(a.id), + private: a.private, + } +} + +pub fn fold_variable>(_f: &mut F, v: Variable) -> Variable { + v +} diff --git a/zokrates_core/src/flat_absy/mod.rs b/zokrates_ast/src/flat/mod.rs similarity index 71% rename from zokrates_core/src/flat_absy/mod.rs rename to zokrates_ast/src/flat/mod.rs index 01260145..27ac6e7f 100644 --- a/zokrates_core/src/flat_absy/mod.rs +++ b/zokrates_ast/src/flat/mod.rs @@ -5,99 +5,17 @@ //! @author Jacob Eberhardt //! @date 2017 -pub mod flat_parameter; -pub mod flat_variable; +pub mod folder; -pub use self::flat_parameter::FlatParameter; -pub use self::flat_variable::FlatVariable; +pub use crate::common::Parameter; +pub use crate::common::RuntimeError; +pub use crate::common::Variable; -use serde::{Deserialize, Serialize}; - -use crate::solvers::Solver; +use crate::common::Solver; use std::collections::HashMap; use std::fmt; use zokrates_field::Field; -#[derive(Debug, Clone, Serialize, Deserialize, Hash, PartialEq, Eq)] -pub enum RuntimeError { - BellmanConstraint, - BellmanOneBinding, - BellmanInputBinding, - ArkConstraint, - ArkOneBinding, - ArkInputBinding, - Bitness, - Sum, - Equal, - Le, - BranchIsolation, - ConstantLtBitness, - ConstantLtSum, - LtBitness, - LtSum, - LtFinalBitness, - LtFinalSum, - LtSymetric, - Or, - Xor, - Inverse, - Euclidean, - ShaXor, - Division, - SourceAssertion(String), - ArgumentBitness, - SelectRangeCheck, -} - -impl RuntimeError { - pub(crate) fn is_malicious(&self) -> bool { - use RuntimeError::*; - - !matches!( - self, - SourceAssertion(_) | Inverse | LtSum | SelectRangeCheck | ArgumentBitness - ) - } -} - -impl fmt::Display for RuntimeError { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - use RuntimeError::*; - - let msg = match self { - BellmanConstraint => "Bellman constraint is unsatisfied", - BellmanOneBinding => "Bellman ~one binding is unsatisfied", - BellmanInputBinding => "Bellman input binding is unsatisfied", - ArkConstraint => "Ark constraint is unsatisfied", - ArkOneBinding => "Ark ~one binding is unsatisfied", - ArkInputBinding => "Ark input binding is unsatisfied", - Bitness => "Bitness check failed", - Sum => "Sum check failed", - Equal => "Equal check failed", - Le => "Constant Le check failed", - BranchIsolation => "Branch isolation failed", - ConstantLtBitness => "Bitness check failed in constant Lt check", - ConstantLtSum => "Sum check failed in constant Lt check", - LtBitness => "Bitness check failed in Lt check", - LtSum => "Sum check failed in Lt check", - LtFinalBitness => "Bitness check failed in final Lt check", - LtFinalSum => "Sum check failed in final Lt check", - LtSymetric => "Symetrical check failed in Lt check", - Or => "Or check failed", - Xor => "Xor check failed", - Inverse => "Division by zero", - Euclidean => "Euclidean check failed", - ShaXor => "Internal Sha check failed", - Division => "Division check failed", - SourceAssertion(m) => m.as_str(), - ArgumentBitness => "Argument bitness check failed", - SelectRangeCheck => "Out of bounds array access", - }; - - write!(f, "{}", msg) - } -} - pub type FlatProg = FlatFunction; pub type FlatFunction = FlatFunctionIterator>>; @@ -107,7 +25,7 @@ pub type FlatProgIterator = FlatFunctionIterator; #[derive(Clone, PartialEq, Debug)] pub struct FlatFunctionIterator>> { /// Arguments of the function - pub arguments: Vec, + pub arguments: Vec, /// Vector of statements that are executed when running the function pub statements: I, /// Number of outputs @@ -157,7 +75,7 @@ impl fmt::Display for FlatFunction { #[derive(Clone, PartialEq, Debug)] pub enum FlatStatement { Condition(FlatExpression, FlatExpression, RuntimeError), - Definition(FlatVariable, FlatExpression), + Definition(Variable, FlatExpression), Directive(FlatDirective), } @@ -176,7 +94,7 @@ impl fmt::Display for FlatStatement { impl FlatStatement { pub fn apply_substitution( self, - substitution: &HashMap, + substitution: &HashMap, ) -> FlatStatement { match self { FlatStatement::Definition(id, x) => FlatStatement::Definition( @@ -213,13 +131,13 @@ impl FlatStatement { #[derive(Clone, Hash, Debug, PartialEq, Eq)] pub struct FlatDirective { pub inputs: Vec>, - pub outputs: Vec, + pub outputs: Vec, pub solver: Solver, } impl FlatDirective { pub fn new>>( - outputs: Vec, + outputs: Vec, solver: Solver, inputs: Vec, ) -> Self { @@ -257,7 +175,7 @@ impl fmt::Display for FlatDirective { #[derive(Clone, PartialEq, Eq, Hash, Debug)] pub enum FlatExpression { Number(T), - Identifier(FlatVariable), + Identifier(Variable), Add(Box>, Box>), Sub(Box>, Box>), Mult(Box>, Box>), @@ -272,7 +190,7 @@ impl From for FlatExpression { impl FlatExpression { pub fn apply_substitution( self, - substitution: &HashMap, + substitution: &HashMap, ) -> FlatExpression { match self { e @ FlatExpression::Number(_) => e, @@ -328,8 +246,8 @@ impl fmt::Display for FlatExpression { } } -impl From for FlatExpression { - fn from(v: FlatVariable) -> FlatExpression { +impl From for FlatExpression { + fn from(v: Variable) -> FlatExpression { FlatExpression::Identifier(v) } } diff --git a/zokrates_core/src/ir/expression.rs b/zokrates_ast/src/ir/expression.rs similarity index 82% rename from zokrates_core/src/ir/expression.rs rename to zokrates_ast/src/ir/expression.rs index 57ec2753..a32a1293 100644 --- a/zokrates_core/src/ir/expression.rs +++ b/zokrates_ast/src/ir/expression.rs @@ -1,4 +1,5 @@ -use crate::flat_absy::FlatVariable; +use super::Witness; +use crate::common::Variable; use serde::{Deserialize, Serialize}; use std::collections::btree_map::{BTreeMap, Entry}; use std::fmt; @@ -54,10 +55,10 @@ impl fmt::Display for QuadComb { } #[derive(Clone, Debug, Serialize, Deserialize, Hash, PartialEq, Eq)] -pub struct LinComb(pub Vec<(FlatVariable, T)>); +pub struct LinComb(pub Vec<(Variable, T)>); #[derive(PartialEq, PartialOrd, Clone, Eq, Ord, Hash, Debug, Serialize, Deserialize)] -pub struct CanonicalLinComb(pub BTreeMap); +pub struct CanonicalLinComb(pub BTreeMap); #[derive(PartialEq, PartialOrd, Clone, Eq, Ord, Hash, Debug, Serialize, Deserialize)] pub struct CanonicalQuadComb { @@ -81,7 +82,7 @@ impl From> for LinComb { } impl LinComb { - pub fn summand>(mult: U, var: FlatVariable) -> LinComb { + pub fn summand>(mult: U, var: Variable) -> LinComb { let res = vec![(var, mult.into())]; LinComb(res) @@ -105,7 +106,7 @@ impl LinComb { // take the first variable in the lincomb let first = &self.0[0].0; - if first != &FlatVariable::one() { + if first != &Variable::one() { return Err(self); } @@ -119,7 +120,13 @@ impl LinComb { } } - pub fn try_summand(self) -> Result<(FlatVariable, T), Self> { + pub fn is_assignee(&self, witness: &Witness) -> bool { + self.0.len() == 1 + && self.0.get(0).unwrap().1 == T::from(1) + && !witness.0.contains_key(&self.0.get(0).unwrap().0) + } + + pub fn try_summand(self) -> Result<(Variable, T), Self> { match self.0.len() { // if the lincomb is empty, it is not reduceable to a summand 0 => Err(self), @@ -143,7 +150,7 @@ impl LinComb { } pub fn one() -> LinComb { - Self::summand(1, FlatVariable::one()) + Self::summand(1, Variable::one()) } } @@ -212,8 +219,8 @@ impl fmt::Display for LinComb { } } -impl From for LinComb { - fn from(v: FlatVariable) -> LinComb { +impl From for LinComb { + fn from(v: Variable) -> LinComb { let r = vec![(v, T::one())]; LinComb(r) } @@ -277,32 +284,32 @@ mod tests { #[test] fn add_zero() { let a: LinComb = LinComb::zero(); - let b: LinComb = FlatVariable::new(42).into(); + let b: LinComb = Variable::new(42).into(); let c = a + b.clone(); assert_eq!(c, b); } #[test] fn add() { - let a: LinComb = FlatVariable::new(42).into(); - let b: LinComb = FlatVariable::new(42).into(); + let a: LinComb = Variable::new(42).into(); + let b: LinComb = Variable::new(42).into(); let c = a + b; let expected_vec = vec![ - (FlatVariable::new(42), Bn128Field::from(1)), - (FlatVariable::new(42), Bn128Field::from(1)), + (Variable::new(42), Bn128Field::from(1)), + (Variable::new(42), Bn128Field::from(1)), ]; assert_eq!(c, LinComb(expected_vec)); } #[test] fn sub() { - let a: LinComb = FlatVariable::new(42).into(); - let b: LinComb = FlatVariable::new(42).into(); + let a: LinComb = Variable::new(42).into(); + let b: LinComb = Variable::new(42).into(); let c = a - b; let expected_vec = vec![ - (FlatVariable::new(42), Bn128Field::from(1)), - (FlatVariable::new(42), Bn128Field::from(-1)), + (Variable::new(42), Bn128Field::from(1)), + (Variable::new(42), Bn128Field::from(-1)), ]; assert_eq!(c, LinComb(expected_vec)); @@ -311,7 +318,7 @@ mod tests { #[test] fn display() { let a: LinComb = - LinComb::from(FlatVariable::new(42)) + LinComb::summand(3, FlatVariable::new(21)); + LinComb::from(Variable::new(42)) + LinComb::summand(3, Variable::new(21)); assert_eq!(&a.to_string(), "1 * _42 + 3 * _21"); let zero: LinComb = LinComb::zero(); assert_eq!(&zero.to_string(), "0"); @@ -322,8 +329,8 @@ mod tests { use super::*; #[test] fn from_linear() { - let a: LinComb = LinComb::summand(3, FlatVariable::new(42)) - + LinComb::summand(4, FlatVariable::new(33)); + let a: LinComb = + LinComb::summand(3, Variable::new(42)) + LinComb::summand(4, Variable::new(33)); let expected = QuadComb { left: LinComb::one(), right: a.clone(), @@ -344,14 +351,14 @@ mod tests { #[test] fn display() { let a: QuadComb = QuadComb { - left: LinComb::summand(3, FlatVariable::new(42)) - + LinComb::summand(4, FlatVariable::new(33)), - right: LinComb::summand(1, FlatVariable::new(21)), + left: LinComb::summand(3, Variable::new(42)) + + LinComb::summand(4, Variable::new(33)), + right: LinComb::summand(1, Variable::new(21)), }; assert_eq!(&a.to_string(), "(3 * _42 + 4 * _33) * (1 * _21)"); let a: QuadComb = QuadComb { left: LinComb::zero(), - right: LinComb::summand(1, FlatVariable::new(21)), + right: LinComb::summand(1, Variable::new(21)), }; assert_eq!(&a.to_string(), "(0) * (1 * _21)"); } @@ -363,19 +370,19 @@ mod tests { #[test] fn try_summand() { let summand = LinComb(vec![ - (FlatVariable::new(42), Bn128Field::from(1)), - (FlatVariable::new(42), Bn128Field::from(2)), - (FlatVariable::new(42), Bn128Field::from(3)), + (Variable::new(42), Bn128Field::from(1)), + (Variable::new(42), Bn128Field::from(2)), + (Variable::new(42), Bn128Field::from(3)), ]); assert_eq!( summand.try_summand(), - Ok((FlatVariable::new(42), Bn128Field::from(6))) + Ok((Variable::new(42), Bn128Field::from(6))) ); let not_summand = LinComb(vec![ - (FlatVariable::new(41), Bn128Field::from(1)), - (FlatVariable::new(42), Bn128Field::from(2)), - (FlatVariable::new(42), Bn128Field::from(3)), + (Variable::new(41), Bn128Field::from(1)), + (Variable::new(42), Bn128Field::from(2)), + (Variable::new(42), Bn128Field::from(3)), ]); assert!(not_summand.try_summand().is_err()); diff --git a/zokrates_core/src/ir/folder.rs b/zokrates_ast/src/ir/folder.rs similarity index 85% rename from zokrates_core/src/ir/folder.rs rename to zokrates_ast/src/ir/folder.rs index a50c71f6..753a3836 100644 --- a/zokrates_core/src/ir/folder.rs +++ b/zokrates_ast/src/ir/folder.rs @@ -1,7 +1,7 @@ // Generic walk through an IR AST. Not mutating in place -use crate::flat_absy::flat_variable::FlatVariable; -use crate::ir::*; +use super::*; +use crate::common::Variable; use zokrates_field::Field; pub trait Folder: Sized { @@ -9,11 +9,11 @@ pub trait Folder: Sized { fold_program(self, p) } - fn fold_argument(&mut self, p: FlatParameter) -> FlatParameter { + fn fold_argument(&mut self, p: Parameter) -> Parameter { fold_argument(self, p) } - fn fold_variable(&mut self, v: FlatVariable) -> FlatVariable { + fn fold_variable(&mut self, v: Variable) -> Variable { fold_variable(self, v) } @@ -91,13 +91,13 @@ pub fn fold_directive>(f: &mut F, ds: Directive) -> Di } } -pub fn fold_argument>(f: &mut F, a: FlatParameter) -> FlatParameter { - FlatParameter { +pub fn fold_argument>(f: &mut F, a: Parameter) -> Parameter { + Parameter { id: f.fold_variable(a.id), private: a.private, } } -pub fn fold_variable>(_f: &mut F, v: FlatVariable) -> FlatVariable { +pub fn fold_variable>(_f: &mut F, v: Variable) -> Variable { v } diff --git a/zokrates_core/src/ir/from_flat.rs b/zokrates_ast/src/ir/from_flat.rs similarity index 98% rename from zokrates_core/src/ir/from_flat.rs rename to zokrates_ast/src/ir/from_flat.rs index 640336b3..c6a4e4e5 100644 --- a/zokrates_core/src/ir/from_flat.rs +++ b/zokrates_ast/src/ir/from_flat.rs @@ -1,7 +1,7 @@ use crate::flat_absy::{ FlatDirective, FlatExpression, FlatProgIterator, FlatStatement, FlatVariable, }; -use crate::ir::{Directive, LinComb, ProgIterator, QuadComb, Statement}; +use zokrates_ast::ir::{Directive, LinComb, ProgIterator, QuadComb, Statement}; use zokrates_field::Field; impl QuadComb { diff --git a/zokrates_core/src/ir/mod.rs b/zokrates_ast/src/ir/mod.rs similarity index 85% rename from zokrates_core/src/ir/mod.rs rename to zokrates_ast/src/ir/mod.rs index 1b96ea00..430b1525 100644 --- a/zokrates_core/src/ir/mod.rs +++ b/zokrates_ast/src/ir/mod.rs @@ -1,6 +1,4 @@ -use crate::flat_absy::flat_parameter::FlatParameter; -use crate::flat_absy::{FlatVariable, RuntimeError}; -use crate::solvers::Solver; +//use crate::solvers::Solver; use serde::{Deserialize, Serialize}; use std::fmt; use std::hash::Hash; @@ -8,8 +6,7 @@ use zokrates_field::Field; mod expression; pub mod folder; -pub mod from_flat; -mod interpreter; +//pub mod from_flat; mod serialize; pub mod smtlib2; pub mod visitor; @@ -18,8 +15,11 @@ mod witness; pub use self::expression::QuadComb; pub use self::expression::{CanonicalLinComb, LinComb}; pub use self::serialize::ProgEnum; +pub use crate::common::Parameter; +pub use crate::common::RuntimeError; +pub use crate::common::Solver; +pub use crate::common::Variable; -pub use self::interpreter::{Error, ExecutionResult, Interpreter}; pub use self::witness::Witness; #[derive(Debug, Serialize, Deserialize, Clone, Hash, PartialEq, Eq)] @@ -29,7 +29,7 @@ pub enum Statement { } impl Statement { - pub fn definition>>(v: FlatVariable, e: U) -> Self { + pub fn definition>>(v: Variable, e: U) -> Self { Statement::Constraint(e.into(), v.into(), None) } @@ -41,7 +41,7 @@ impl Statement { #[derive(Clone, Debug, Serialize, Deserialize, Hash, PartialEq, Eq)] pub struct Directive { pub inputs: Vec>, - pub outputs: Vec, + pub outputs: Vec, pub solver: Solver, } @@ -78,13 +78,13 @@ pub type Prog = ProgIterator>>; #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default)] pub struct ProgIterator>> { - pub arguments: Vec, + pub arguments: Vec, pub return_count: usize, pub statements: I, } impl>> ProgIterator { - pub fn new(arguments: Vec, statements: I, return_count: usize) -> Self { + pub fn new(arguments: Vec, statements: I, return_count: usize) -> Self { Self { arguments, return_count, @@ -100,8 +100,8 @@ impl>> ProgIterator { } } - pub fn returns(&self) -> Vec { - (0..self.return_count).map(FlatVariable::public).collect() + pub fn returns(&self) -> Vec { + (0..self.return_count).map(Variable::public).collect() } pub fn public_count(&self) -> usize { @@ -156,7 +156,7 @@ impl fmt::Display for Prog { f, "\treturn {}", (0..self.return_count) - .map(FlatVariable::public) + .map(Variable::public) .map(|e| format!("{}", e)) .collect::>() .join(", ") @@ -176,10 +176,10 @@ mod tests { fn print_constraint() { let c: Statement = Statement::Constraint( QuadComb::from_linear_combinations( - FlatVariable::new(42).into(), - FlatVariable::new(42).into(), + Variable::new(42).into(), + Variable::new(42).into(), ), - FlatVariable::new(42).into(), + Variable::new(42).into(), None, ); assert_eq!(format!("{}", c), "(1 * _42) * (1 * _42) == 1 * _42") diff --git a/zokrates_core/src/ir/serialize.rs b/zokrates_ast/src/ir/serialize.rs similarity index 92% rename from zokrates_core/src/ir/serialize.rs rename to zokrates_ast/src/ir/serialize.rs index fecf1324..ea03f00d 100644 --- a/zokrates_core/src/ir/serialize.rs +++ b/zokrates_ast/src/ir/serialize.rs @@ -1,7 +1,4 @@ -use crate::{ - ir::{ProgIterator, Statement}, - static_analysis::UnconstrainedVariableDetector, -}; +use super::{ProgIterator, Statement}; use serde_cbor::{self, StreamDeserializer}; use std::io::{Read, Write}; use zokrates_field::*; @@ -60,7 +57,7 @@ impl>> ProgIterator { /// serialize a program iterator, returning the number of constraints serialized /// Note that we only return constraints, not other statements such as directives pub fn serialize(self, mut w: W) -> Result { - use crate::ir::folder::Folder; + //use super::folder::Folder; w.write_all(ZOKRATES_MAGIC)?; w.write_all(ZOKRATES_VERSION_2)?; @@ -69,7 +66,7 @@ impl>> ProgIterator { serde_cbor::to_writer(&mut w, &self.arguments)?; serde_cbor::to_writer(&mut w, &self.return_count)?; - let mut unconstrained_variable_detector = UnconstrainedVariableDetector::new(&self); + //let mut unconstrained_variable_detector = UnconstrainedVariableDetector::new(&self); let statements = self.statements.into_iter(); @@ -78,16 +75,17 @@ impl>> ProgIterator { if matches!(s, Statement::Constraint(..)) { count += 1; } - let s = unconstrained_variable_detector.fold_statement(s); - for s in s { - serde_cbor::to_writer(&mut w, &s)?; - } + //let s = unconstrained_variable_detector.fold_statement(s); + //for s in s { + serde_cbor::to_writer(&mut w, &s)?; + //} } - unconstrained_variable_detector - .finalize() - .map(|_| count) - .map_err(|count| format!("Error: Found {} unconstrained variable(s)", count).into()) + // unconstrained_variable_detector + // .finalize() + // .map(|_| count) + // .map_err(|count| format!("Error: Found {} unconstrained variable(s)", count).into()) + Ok(count) } } @@ -137,7 +135,7 @@ impl<'de, R: Read> struct ArgumentsVisitor; impl<'de> serde::de::Visitor<'de> for ArgumentsVisitor { - type Value = Vec; + type Value = Vec; fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { formatter.write_str("seq of flat param") } @@ -239,13 +237,13 @@ impl<'de, R: Read> #[cfg(test)] mod tests { use super::*; - use crate::ir; + use crate::ir::Prog; use std::io::{Cursor, Seek, SeekFrom}; use zokrates_field::{Bls12_381Field, Bn128Field}; #[test] fn ser_deser_v2() { - let p: ir::Prog = ir::Prog::default(); + let p: Prog = Prog::default(); let mut buffer = Cursor::new(vec![]); p.clone().serialize(&mut buffer).unwrap(); @@ -258,7 +256,7 @@ mod tests { assert_eq!(ProgEnum::Bn128Program(p), deserialized_p.collect()); - let p: ir::Prog = ir::Prog::default(); + let p: Prog = Prog::default(); let mut buffer = Cursor::new(vec![]); p.clone().serialize(&mut buffer).unwrap(); diff --git a/zokrates_core/src/ir/smtlib2.rs b/zokrates_ast/src/ir/smtlib2.rs similarity index 93% rename from zokrates_core/src/ir/smtlib2.rs rename to zokrates_ast/src/ir/smtlib2.rs index 560a1b90..66e78ccf 100644 --- a/zokrates_core/src/ir/smtlib2.rs +++ b/zokrates_ast/src/ir/smtlib2.rs @@ -21,11 +21,11 @@ impl fmt::Display for SMTLib2Display<'_, T> { } struct FlatVariableCollector { - variables: BTreeSet, + variables: BTreeSet, } impl Visitor for FlatVariableCollector { - fn visit_variable(&mut self, v: &FlatVariable) { + fn visit_variable(&mut self, v: &Variable) { self.variables.insert(*v); } } @@ -33,10 +33,10 @@ impl Visitor for FlatVariableCollector { impl SMTLib2 for Prog { fn to_smtlib2(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut collector = FlatVariableCollector { - variables: BTreeSet::::new(), + variables: BTreeSet::::new(), }; collector.visit_module(self); - collector.variables.insert(FlatVariable::one()); + collector.variables.insert(Variable::one()); writeln!(f, "; Auto generated by ZoKrates")?; writeln!( @@ -122,7 +122,7 @@ impl SMTLib2 for LinComb { } } -impl SMTLib2 for FlatVariable { +impl SMTLib2 for Variable { fn to_smtlib2(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "|{}|", self) } diff --git a/zokrates_core/src/ir/visitor.rs b/zokrates_ast/src/ir/visitor.rs similarity index 89% rename from zokrates_core/src/ir/visitor.rs rename to zokrates_ast/src/ir/visitor.rs index 236ade45..8de5a1f5 100644 --- a/zokrates_core/src/ir/visitor.rs +++ b/zokrates_ast/src/ir/visitor.rs @@ -1,7 +1,7 @@ // Generic walk through an IR AST. Not mutating in place -use crate::flat_absy::flat_variable::FlatVariable; -use crate::ir::*; +use super::*; +use crate::common::Variable; use zokrates_field::Field; pub trait Visitor: Sized { @@ -9,11 +9,11 @@ pub trait Visitor: Sized { visit_module(self, p) } - fn visit_argument(&mut self, p: &FlatParameter) { + fn visit_argument(&mut self, p: &Parameter) { visit_argument(self, p) } - fn visit_variable(&mut self, v: &FlatVariable) { + fn visit_variable(&mut self, v: &Variable) { visit_variable(self, v) } @@ -85,11 +85,11 @@ pub fn visit_directive>(f: &mut F, ds: &Directive) { } } -pub fn visit_argument>(f: &mut F, a: &FlatParameter) { +pub fn visit_argument>(f: &mut F, a: &Parameter) { f.visit_variable(&a.id) } -pub fn visit_variable>(_f: &mut F, _v: &FlatVariable) {} +pub fn visit_variable>(_f: &mut F, _v: &Variable) {} pub fn visit_value>(_f: &mut F, _v: &T) {} diff --git a/zokrates_core/src/ir/witness.rs b/zokrates_ast/src/ir/witness.rs similarity index 82% rename from zokrates_core/src/ir/witness.rs rename to zokrates_ast/src/ir/witness.rs index 865556b5..e1ef7090 100644 --- a/zokrates_core/src/ir/witness.rs +++ b/zokrates_ast/src/ir/witness.rs @@ -1,12 +1,12 @@ -use crate::flat_absy::FlatVariable; +use crate::common::Variable; use std::collections::{BTreeMap, HashMap}; use std::fmt; use std::io; use std::io::{Read, Write}; use zokrates_field::Field; -#[derive(Clone, Debug, PartialEq)] -pub struct Witness(pub BTreeMap); +#[derive(Clone, Debug, PartialEq, Default)] +pub struct Witness(pub BTreeMap); impl Witness { pub fn return_values(&self) -> Vec { @@ -17,11 +17,15 @@ impl Witness { .collect::>(); (0..out.len()) - .map(|i| *out.get(&FlatVariable::public(i)).unwrap()) + .map(|i| *out.get(&Variable::public(i)).unwrap()) .cloned() .collect() } + pub fn insert(&mut self, var: Variable, val: T) -> Option { + self.0.insert(var, val) + } + pub fn format_outputs(&self) -> String { self.0 .iter() @@ -63,13 +67,12 @@ impl Witness { .deserialize::<(String, String)>() .map(|r| { r.map(|(variable, value)| { - let variable = - FlatVariable::try_from_human_readable(&variable).map_err(|why| { - io::Error::new( - io::ErrorKind::Other, - format!("Invalid variable in witness: {}", why), - ) - })?; + let variable = Variable::try_from_human_readable(&variable).map_err(|why| { + io::Error::new( + io::ErrorKind::Other, + format!("Invalid variable in witness: {}", why), + ) + })?; let value = T::try_from_dec_str(&value).map_err(|_| { io::Error::new( io::ErrorKind::Other, @@ -83,7 +86,7 @@ impl Witness { e => io::Error::new(io::ErrorKind::Other, format!("{:?}", e)), })? }) - .collect::>>()?; + .collect::>>()?; Ok(Witness(map)) } @@ -116,9 +119,9 @@ mod tests { fn serialize_deserialize() { let w = Witness( vec![ - (FlatVariable::new(42), Bn128Field::from(42)), - (FlatVariable::public(8), Bn128Field::from(8)), - (FlatVariable::one(), Bn128Field::from(1)), + (Variable::new(42), Bn128Field::from(42)), + (Variable::public(8), Bn128Field::from(8)), + (Variable::one(), Bn128Field::from(1)), ] .into_iter() .collect(), diff --git a/zokrates_ast/src/lib.rs b/zokrates_ast/src/lib.rs new file mode 100644 index 00000000..797b8561 --- /dev/null +++ b/zokrates_ast/src/lib.rs @@ -0,0 +1,10 @@ +#![feature(box_patterns, box_syntax)] + +pub mod common; +pub mod flat; +pub mod ir; +pub mod typed; +pub mod untyped; +pub mod zir; + +pub use common::Solver; diff --git a/zokrates_core/src/typed_absy/abi.rs b/zokrates_ast/src/typed/abi.rs similarity index 99% rename from zokrates_core/src/typed_absy/abi.rs rename to zokrates_ast/src/typed/abi.rs index 4bcd11b6..897cc2c8 100644 --- a/zokrates_core/src/typed_absy/abi.rs +++ b/zokrates_ast/src/typed/abi.rs @@ -1,4 +1,4 @@ -use crate::typed_absy::types::{ConcreteSignature, ConcreteType}; +use crate::typed::types::{ConcreteSignature, ConcreteType}; use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)] @@ -30,10 +30,10 @@ impl Abi { #[cfg(test)] mod tests { use super::*; - use crate::typed_absy::types::{ + use crate::typed::types::{ ConcreteArrayType, ConcreteFunctionKey, ConcreteStructMember, ConcreteStructType, UBitwidth, }; - use crate::typed_absy::{ + use crate::typed::{ parameter::DeclarationParameter, variable::DeclarationVariable, ConcreteTupleType, ConcreteType, TypedFunction, TypedFunctionSymbol, TypedFunctionSymbolDeclaration, TypedModule, TypedProgram, diff --git a/zokrates_core/src/typed_absy/folder.rs b/zokrates_ast/src/typed/folder.rs similarity index 99% rename from zokrates_core/src/typed_absy/folder.rs rename to zokrates_ast/src/typed/folder.rs index 1f0aba6d..3dda0ee0 100644 --- a/zokrates_core/src/typed_absy/folder.rs +++ b/zokrates_ast/src/typed/folder.rs @@ -1,7 +1,7 @@ // Generic walk through a typed AST. Not mutating in place -use crate::typed_absy::types::*; -use crate::typed_absy::*; +use crate::typed::types::*; +use crate::typed::*; use zokrates_field::Field; pub trait Fold<'ast, T: Field>: Sized { diff --git a/zokrates_core/src/typed_absy/identifier.rs b/zokrates_ast/src/typed/identifier.rs similarity index 97% rename from zokrates_core/src/typed_absy/identifier.rs rename to zokrates_ast/src/typed/identifier.rs index 56246eb5..2eb64390 100644 --- a/zokrates_core/src/typed_absy/identifier.rs +++ b/zokrates_ast/src/typed/identifier.rs @@ -1,4 +1,4 @@ -use crate::typed_absy::CanonicalConstantIdentifier; +use crate::typed::CanonicalConstantIdentifier; use std::convert::TryInto; use std::fmt; diff --git a/zokrates_core/src/typed_absy/integer.rs b/zokrates_ast/src/typed/integer.rs similarity index 99% rename from zokrates_core/src/typed_absy/integer.rs rename to zokrates_ast/src/typed/integer.rs index 79b00113..60d70782 100644 --- a/zokrates_core/src/typed_absy/integer.rs +++ b/zokrates_ast/src/typed/integer.rs @@ -1,10 +1,10 @@ -use crate::typed_absy::types::{ +use crate::typed::types::{ ArrayType, DeclarationArrayType, DeclarationConstant, DeclarationStructMember, DeclarationStructType, DeclarationTupleType, DeclarationType, GArrayType, GStructType, GTupleType, GType, GenericIdentifier, StructType, TupleType, Type, }; -use crate::typed_absy::UBitwidth; -use crate::typed_absy::{ +use crate::typed::UBitwidth; +use crate::typed::{ ArrayExpression, ArrayExpressionInner, BooleanExpression, Conditional, ConditionalExpression, Expr, FieldElementExpression, Select, SelectExpression, StructExpression, StructExpressionInner, TupleExpression, TupleExpressionInner, Typed, TypedExpression, @@ -791,7 +791,7 @@ impl<'ast, T> From for IntExpression<'ast, T> { #[cfg(test)] mod tests { use super::*; - use crate::typed_absy::ConditionalKind; + use crate::typed::ConditionalKind; use zokrates_field::Bn128Field; #[test] diff --git a/zokrates_core/src/typed_absy/mod.rs b/zokrates_ast/src/typed/mod.rs similarity index 99% rename from zokrates_core/src/typed_absy/mod.rs rename to zokrates_ast/src/typed/mod.rs index c10ebf74..8ee9d622 100644 --- a/zokrates_core/src/typed_absy/mod.rs +++ b/zokrates_ast/src/typed/mod.rs @@ -25,28 +25,28 @@ pub use self::types::{ GArrayType, GStructType, GType, GenericIdentifier, IntoTypes, Signature, StructType, TupleType, Type, Types, UBitwidth, }; -use crate::parser::Position; -use crate::typed_absy::types::ConcreteGenericsAssignment; +use crate::typed::types::ConcreteGenericsAssignment; +use crate::untyped::Position; pub use self::variable::{ConcreteVariable, DeclarationVariable, GVariable, Variable}; use std::marker::PhantomData; use std::path::{Path, PathBuf}; -pub use crate::typed_absy::integer::IntExpression; -pub use crate::typed_absy::uint::{bitwidth, UExpression, UExpressionInner, UMetadata}; +pub use crate::typed::integer::IntExpression; +pub use crate::typed::uint::{bitwidth, UExpression, UExpressionInner, UMetadata}; -use crate::embed::FlatEmbed; +use crate::common::FlatEmbed; use std::collections::BTreeMap; use std::convert::{TryFrom, TryInto}; use std::fmt; -pub use crate::typed_absy::types::{ArrayType, FunctionKey, MemberId}; +pub use crate::typed::types::{ArrayType, FunctionKey, MemberId}; use zokrates_field::Field; pub use self::folder::Folder; -use crate::typed_absy::abi::{Abi, AbiInput}; +use crate::typed::abi::{Abi, AbiInput}; use std::ops::{Add, Div, Mul, Sub}; pub use self::identifier::Identifier; @@ -109,7 +109,7 @@ impl<'ast, T: Field> TypedProgram<'ast, T> { .iter() .map(|p| { types::ConcreteType::try_from( - crate::typed_absy::types::try_from_g_type::< + crate::typed::types::try_from_g_type::< DeclarationConstant<'ast, T>, UExpression<'ast, T>, >(p.id._type.clone()) @@ -129,7 +129,7 @@ impl<'ast, T: Field> TypedProgram<'ast, T> { .iter() .map(|ty| { types::ConcreteType::try_from( - crate::typed_absy::types::try_from_g_type::< + crate::typed::types::try_from_g_type::< DeclarationConstant<'ast, T>, UExpression<'ast, T>, >(ty.clone()) @@ -2236,7 +2236,7 @@ impl<'ast, T: Clone> Member<'ast, T> for UExpression<'ast, T> { fn member(s: StructExpression<'ast, T>, id: MemberId) -> Self { let ty = s.ty().members.iter().find(|member| id == member.id); let bitwidth = match ty { - Some(crate::typed_absy::types::StructMember { + Some(crate::typed::types::StructMember { ty: box Type::Uint(bitwidth), .. }) => *bitwidth, @@ -2250,7 +2250,7 @@ impl<'ast, T: Clone> Member<'ast, T> for ArrayExpression<'ast, T> { fn member(s: StructExpression<'ast, T>, id: MemberId) -> Self { let ty = s.ty().members.iter().find(|member| id == member.id); let (ty, size) = match ty { - Some(crate::typed_absy::types::StructMember { + Some(crate::typed::types::StructMember { ty: box Type::Array(array_ty), .. }) => (*array_ty.ty.clone(), array_ty.size.clone()), @@ -2264,7 +2264,7 @@ impl<'ast, T: Clone> Member<'ast, T> for StructExpression<'ast, T> { fn member(s: StructExpression<'ast, T>, id: MemberId) -> Self { let ty = s.ty().members.iter().find(|member| id == member.id); let struct_ty = match ty { - Some(crate::typed_absy::types::StructMember { + Some(crate::typed::types::StructMember { ty: box Type::Struct(struct_ty), .. }) => struct_ty.clone(), @@ -2278,7 +2278,7 @@ impl<'ast, T: Clone> Member<'ast, T> for TupleExpression<'ast, T> { fn member(s: StructExpression<'ast, T>, id: MemberId) -> Self { let ty = s.ty().members.iter().find(|member| id == member.id); let tuple_ty = match ty { - Some(crate::typed_absy::types::StructMember { + Some(crate::typed::types::StructMember { ty: box Type::Tuple(tuple_ty), .. }) => tuple_ty.clone(), diff --git a/zokrates_core/src/typed_absy/parameter.rs b/zokrates_ast/src/typed/parameter.rs similarity index 91% rename from zokrates_core/src/typed_absy/parameter.rs rename to zokrates_ast/src/typed/parameter.rs index 34dbb5b0..4fad5c82 100644 --- a/zokrates_core/src/typed_absy/parameter.rs +++ b/zokrates_ast/src/typed/parameter.rs @@ -1,5 +1,5 @@ -use crate::typed_absy::types::DeclarationConstant; -use crate::typed_absy::GVariable; +use crate::typed::types::DeclarationConstant; +use crate::typed::GVariable; use std::fmt; #[derive(Clone, PartialEq, Eq, Hash)] diff --git a/zokrates_core/src/typed_absy/result_folder.rs b/zokrates_ast/src/typed/result_folder.rs similarity index 99% rename from zokrates_core/src/typed_absy/result_folder.rs rename to zokrates_ast/src/typed/result_folder.rs index 842e9852..dad24578 100644 --- a/zokrates_core/src/typed_absy/result_folder.rs +++ b/zokrates_ast/src/typed/result_folder.rs @@ -1,7 +1,7 @@ // Generic walk through a typed AST. Not mutating in place -use crate::typed_absy::types::*; -use crate::typed_absy::*; +use crate::typed::types::*; +use crate::typed::*; use zokrates_field::Field; pub trait ResultFold<'ast, T: Field>: Sized { diff --git a/zokrates_core/src/typed_absy/types.rs b/zokrates_ast/src/typed/types.rs similarity index 99% rename from zokrates_core/src/typed_absy/types.rs rename to zokrates_ast/src/typed/types.rs index f817c65f..8e35f589 100644 --- a/zokrates_core/src/typed_absy/types.rs +++ b/zokrates_ast/src/typed/types.rs @@ -1,7 +1,7 @@ -use crate::typed_absy::{ +use crate::typed::{ CoreIdentifier, Identifier, OwnedTypedModuleId, TypedExpression, UExpression, UExpressionInner, }; -use crate::typed_absy::{TryFrom, TryInto}; +use crate::typed::{TryFrom, TryInto}; use serde::{de::Error, ser::SerializeMap, Deserialize, Deserializer, Serialize, Serializer}; use std::collections::BTreeMap; use std::fmt; diff --git a/zokrates_core/src/typed_absy/uint.rs b/zokrates_ast/src/typed/uint.rs similarity index 99% rename from zokrates_core/src/typed_absy/uint.rs rename to zokrates_ast/src/typed/uint.rs index 09c34689..51579e6b 100644 --- a/zokrates_core/src/typed_absy/uint.rs +++ b/zokrates_ast/src/typed/uint.rs @@ -1,5 +1,5 @@ -use crate::typed_absy::types::UBitwidth; -use crate::typed_absy::*; +use crate::typed::types::UBitwidth; +use crate::typed::*; use std::ops::{Add, Div, Mul, Neg, Not, Rem, Sub}; use zokrates_field::Field; diff --git a/zokrates_core/src/typed_absy/variable.rs b/zokrates_ast/src/typed/variable.rs similarity index 88% rename from zokrates_core/src/typed_absy/variable.rs rename to zokrates_ast/src/typed/variable.rs index f287eda5..e4eadffe 100644 --- a/zokrates_core/src/typed_absy/variable.rs +++ b/zokrates_ast/src/typed/variable.rs @@ -1,8 +1,8 @@ -use crate::typed_absy::types::{DeclarationConstant, GStructType, UBitwidth}; -use crate::typed_absy::types::{GType, SpecializationError}; -use crate::typed_absy::Identifier; -use crate::typed_absy::UExpression; -use crate::typed_absy::{TryFrom, TryInto}; +use crate::typed::types::{DeclarationConstant, GStructType, UBitwidth}; +use crate::typed::types::{GType, SpecializationError}; +use crate::typed::Identifier; +use crate::typed::UExpression; +use crate::typed::{TryFrom, TryInto}; use std::fmt; #[derive(Clone, PartialEq, Hash, Eq, PartialOrd, Ord)] @@ -36,7 +36,7 @@ impl<'ast, T> From> for Variable<'ast, T> { pub fn try_from_g_variable, U>( v: GVariable, ) -> Result, SpecializationError> { - let _type = crate::typed_absy::types::try_from_g_type(v._type)?; + let _type = crate::typed::types::try_from_g_type(v._type)?; Ok(GVariable { _type, id: v.id }) } diff --git a/zokrates_ast/src/untyped/from_ast.rs b/zokrates_ast/src/untyped/from_ast.rs new file mode 100644 index 00000000..8a79989d --- /dev/null +++ b/zokrates_ast/src/untyped/from_ast.rs @@ -0,0 +1,1398 @@ +use crate::untyped; + +use num_bigint::BigUint; +use std::path::Path; +use zokrates_pest_ast as pest; + +impl<'ast> From> for untyped::Module<'ast> { + fn from(file: pest::File<'ast>) -> untyped::Module<'ast> { + untyped::Module::with_symbols(file.declarations.into_iter().flat_map(|d| match d { + pest::SymbolDeclaration::Import(i) => import_directive_to_symbol_vec(i), + pest::SymbolDeclaration::Constant(c) => vec![c.into()], + pest::SymbolDeclaration::Struct(s) => vec![s.into()], + pest::SymbolDeclaration::Type(t) => vec![t.into()], + pest::SymbolDeclaration::Function(f) => vec![f.into()], + })) + } +} + +fn import_directive_to_symbol_vec( + import: pest::ImportDirective, +) -> Vec { + use crate::untyped::NodeValue; + + match import { + pest::ImportDirective::Main(import) => { + let span = import.span; + let source = Path::new(import.source.span.as_str()); + let id = "main"; + let alias = import.alias.map(|a| a.span.as_str()); + + let import = untyped::CanonicalImport { + source, + id: untyped::SymbolIdentifier::from(id).alias(alias), + } + .span(span.clone()); + + vec![untyped::SymbolDeclaration { + id: alias.unwrap_or(id), + symbol: untyped::Symbol::Here(untyped::SymbolDefinition::Import(import)), + } + .span(span.clone())] + } + pest::ImportDirective::From(import) => { + let span = import.span; + let source = Path::new(import.source.span.as_str()); + import + .symbols + .into_iter() + .map(|symbol| { + let alias = symbol + .alias + .as_ref() + .map(|a| a.span.as_str()) + .unwrap_or_else(|| symbol.id.span.as_str()); + + let import = untyped::CanonicalImport { + source, + id: untyped::SymbolIdentifier::from(symbol.id.span.as_str()) + .alias(Some(alias)), + } + .span(span.clone()); + + untyped::SymbolDeclaration { + id: alias, + symbol: untyped::Symbol::Here(untyped::SymbolDefinition::Import(import)), + } + .span(span.clone()) + }) + .collect() + } + } +} + +impl<'ast> From> for untyped::SymbolDeclarationNode<'ast> { + fn from(definition: pest::StructDefinition<'ast>) -> untyped::SymbolDeclarationNode<'ast> { + use crate::untyped::NodeValue; + + let span = definition.span; + + let id = definition.id.span.as_str(); + + let ty = untyped::StructDefinition { + generics: definition + .generics + .into_iter() + .map(untyped::ConstantGenericNode::from) + .collect(), + fields: definition + .fields + .into_iter() + .map(untyped::StructDefinitionFieldNode::from) + .collect(), + } + .span(span.clone()); + + untyped::SymbolDeclaration { + id, + symbol: untyped::Symbol::Here(untyped::SymbolDefinition::Struct(ty)), + } + .span(span) + } +} + +impl<'ast> From> for untyped::StructDefinitionFieldNode<'ast> { + fn from(field: pest::StructField<'ast>) -> untyped::StructDefinitionFieldNode<'ast> { + use crate::untyped::NodeValue; + + let span = field.span; + + let id = field.id.span.as_str(); + + let ty = untyped::UnresolvedTypeNode::from(field.ty); + + untyped::StructDefinitionField { id, ty }.span(span) + } +} + +impl<'ast> From> for untyped::SymbolDeclarationNode<'ast> { + fn from(definition: pest::ConstantDefinition<'ast>) -> untyped::SymbolDeclarationNode<'ast> { + use crate::untyped::NodeValue; + + let span = definition.span; + let id = definition.id.span.as_str(); + + let ty = untyped::ConstantDefinition { + ty: definition.ty.into(), + expression: definition.expression.into(), + } + .span(span.clone()); + + untyped::SymbolDeclaration { + id, + symbol: untyped::Symbol::Here(untyped::SymbolDefinition::Constant(ty)), + } + .span(span) + } +} + +impl<'ast> From> for untyped::SymbolDeclarationNode<'ast> { + fn from(definition: pest::TypeDefinition<'ast>) -> untyped::SymbolDeclarationNode<'ast> { + use crate::untyped::NodeValue; + + let span = definition.span; + let id = definition.id.span.as_str(); + + let ty = untyped::TypeDefinition { + generics: definition + .generics + .into_iter() + .map(untyped::ConstantGenericNode::from) + .collect(), + ty: definition.ty.into(), + } + .span(span.clone()); + + untyped::SymbolDeclaration { + id, + symbol: untyped::Symbol::Here(untyped::SymbolDefinition::Type(ty)), + } + .span(span) + } +} + +impl<'ast> From> for untyped::SymbolDeclarationNode<'ast> { + fn from(function: pest::FunctionDefinition<'ast>) -> untyped::SymbolDeclarationNode<'ast> { + use crate::untyped::NodeValue; + + let span = function.span; + + let signature = untyped::UnresolvedSignature::new() + .generics( + function + .generics + .into_iter() + .map(untyped::ConstantGenericNode::from) + .collect(), + ) + .inputs( + function + .parameters + .clone() + .into_iter() + .map(|p| untyped::UnresolvedTypeNode::from(p.ty)) + .collect(), + ) + .outputs( + function + .returns + .clone() + .into_iter() + .map(untyped::UnresolvedTypeNode::from) + .collect(), + ); + + let id = function.id.span.as_str(); + + let function = untyped::Function { + arguments: function + .parameters + .into_iter() + .map(untyped::ParameterNode::from) + .collect(), + statements: function + .statements + .into_iter() + .flat_map(statements_from_statement) + .collect(), + signature, + } + .span(span.clone()); + + untyped::SymbolDeclaration { + id, + symbol: untyped::Symbol::Here(untyped::SymbolDefinition::Function(function)), + } + .span(span) + } +} + +impl<'ast> From> for untyped::ConstantGenericNode<'ast> { + fn from(g: pest::IdentifierExpression<'ast>) -> untyped::ConstantGenericNode<'ast> { + use untyped::NodeValue; + + let name = g.span.as_str(); + + name.span(g.span) + } +} + +impl<'ast> From> for untyped::ParameterNode<'ast> { + fn from(param: pest::Parameter<'ast>) -> untyped::ParameterNode<'ast> { + use crate::untyped::NodeValue; + + let private = param + .visibility + .map(|v| match v { + pest::Visibility::Private(_) => true, + pest::Visibility::Public(_) => false, + }) + .unwrap_or(false); + + let variable = untyped::Variable::new( + param.id.span.as_str(), + untyped::UnresolvedTypeNode::from(param.ty), + ) + .span(param.id.span); + + untyped::Parameter::new(variable, private).span(param.span) + } +} + +fn statements_from_statement(statement: pest::Statement) -> Vec { + match statement { + pest::Statement::Definition(s) => statements_from_definition(s), + pest::Statement::Iteration(s) => vec![untyped::StatementNode::from(s)], + pest::Statement::Assertion(s) => vec![untyped::StatementNode::from(s)], + pest::Statement::Return(s) => vec![untyped::StatementNode::from(s)], + } +} + +fn statements_from_definition( + definition: pest::DefinitionStatement, +) -> Vec { + use crate::untyped::NodeValue; + + let lhs = definition.lhs; + + match lhs.len() { + 1 => { + // Definition or assignment + let a = lhs[0].clone(); + + let e: untyped::ExpressionNode = untyped::ExpressionNode::from(definition.expression); + + match a { + pest::TypedIdentifierOrAssignee::TypedIdentifier(i) => { + let declaration = untyped::Statement::Declaration( + untyped::Variable::new( + i.identifier.span.as_str(), + untyped::UnresolvedTypeNode::from(i.ty), + ) + .span(i.identifier.span.clone()), + ) + .span(definition.span.clone()); + + let s = match e.value { + untyped::Expression::FunctionCall(..) => { + untyped::Statement::MultipleDefinition( + vec![untyped::AssigneeNode::from(i.identifier.clone())], + e, + ) + } + _ => untyped::Statement::Definition( + untyped::AssigneeNode::from(i.identifier.clone()), + e, + ), + }; + + vec![declaration, s.span(definition.span)] + } + pest::TypedIdentifierOrAssignee::Assignee(a) => { + let s = match e.value { + untyped::Expression::FunctionCall(..) => { + untyped::Statement::MultipleDefinition( + vec![untyped::AssigneeNode::from(a)], + e, + ) + } + _ => untyped::Statement::Definition(untyped::AssigneeNode::from(a), e), + }; + + vec![s.span(definition.span)] + } + } + } + _ => { + // Multidefinition + let declarations = lhs.clone().into_iter().filter_map(|i| match i { + pest::TypedIdentifierOrAssignee::TypedIdentifier(i) => { + let ty = i.ty; + let id = i.identifier; + + Some( + untyped::Statement::Declaration( + untyped::Variable::new( + id.span.as_str(), + untyped::UnresolvedTypeNode::from(ty), + ) + .span(id.span), + ) + .span(i.span), + ) + } + _ => None, + }); + + let lhs = lhs + .into_iter() + .map(|i| match i { + pest::TypedIdentifierOrAssignee::TypedIdentifier(i) => { + untyped::Assignee::Identifier(i.identifier.span.as_str()) + .span(i.identifier.span) + } + pest::TypedIdentifierOrAssignee::Assignee(a) => untyped::AssigneeNode::from(a), + }) + .collect(); + + let multi_def = untyped::Statement::MultipleDefinition( + lhs, + untyped::ExpressionNode::from(definition.expression), + ) + .span(definition.span); + + declarations.chain(std::iter::once(multi_def)).collect() + } + } +} + +impl<'ast> From> for untyped::StatementNode<'ast> { + fn from(statement: pest::ReturnStatement<'ast>) -> untyped::StatementNode<'ast> { + use crate::untyped::NodeValue; + + untyped::Statement::Return( + untyped::ExpressionList { + expressions: statement + .expressions + .into_iter() + .map(untyped::ExpressionNode::from) + .collect(), + } + .span(statement.span.clone()), + ) + .span(statement.span) + } +} + +impl<'ast> From> for untyped::StatementNode<'ast> { + fn from(statement: pest::AssertionStatement<'ast>) -> untyped::StatementNode<'ast> { + use crate::untyped::NodeValue; + + untyped::Statement::Assertion( + untyped::ExpressionNode::from(statement.expression), + statement.message.map(|m| m.value), + ) + .span(statement.span) + } +} + +impl<'ast> From> for untyped::StatementNode<'ast> { + fn from(statement: pest::IterationStatement<'ast>) -> untyped::StatementNode<'ast> { + use crate::untyped::NodeValue; + let from = untyped::ExpressionNode::from(statement.from); + let to = untyped::ExpressionNode::from(statement.to); + let index = statement.index.span.as_str(); + let ty = untyped::UnresolvedTypeNode::from(statement.ty); + let statements: Vec> = statement + .statements + .into_iter() + .flat_map(statements_from_statement) + .collect(); + + let var = untyped::Variable::new(index, ty).span(statement.index.span); + + untyped::Statement::For(var, from, to, statements).span(statement.span) + } +} + +impl<'ast> From> for untyped::ExpressionNode<'ast> { + fn from(expression: pest::Expression<'ast>) -> untyped::ExpressionNode<'ast> { + match expression { + pest::Expression::Binary(e) => untyped::ExpressionNode::from(e), + pest::Expression::Ternary(e) => untyped::ExpressionNode::from(e), + pest::Expression::IfElse(e) => untyped::ExpressionNode::from(e), + pest::Expression::Literal(e) => untyped::ExpressionNode::from(e), + pest::Expression::Identifier(e) => untyped::ExpressionNode::from(e), + pest::Expression::Postfix(e) => untyped::ExpressionNode::from(e), + pest::Expression::InlineArray(e) => untyped::ExpressionNode::from(e), + pest::Expression::InlineTuple(e) => untyped::ExpressionNode::from(e), + pest::Expression::InlineStruct(e) => untyped::ExpressionNode::from(e), + pest::Expression::ArrayInitializer(e) => untyped::ExpressionNode::from(e), + pest::Expression::Unary(e) => untyped::ExpressionNode::from(e), + } + } +} + +impl<'ast> From> for untyped::ExpressionNode<'ast> { + fn from(expression: pest::BinaryExpression<'ast>) -> untyped::ExpressionNode<'ast> { + use crate::untyped::NodeValue; + match expression.op { + pest::BinaryOperator::Add => untyped::Expression::Add( + box untyped::ExpressionNode::from(*expression.left), + box untyped::ExpressionNode::from(*expression.right), + ), + pest::BinaryOperator::Sub => untyped::Expression::Sub( + box untyped::ExpressionNode::from(*expression.left), + box untyped::ExpressionNode::from(*expression.right), + ), + pest::BinaryOperator::Mul => untyped::Expression::Mult( + box untyped::ExpressionNode::from(*expression.left), + box untyped::ExpressionNode::from(*expression.right), + ), + pest::BinaryOperator::Div => untyped::Expression::Div( + box untyped::ExpressionNode::from(*expression.left), + box untyped::ExpressionNode::from(*expression.right), + ), + pest::BinaryOperator::Rem => untyped::Expression::Rem( + box untyped::ExpressionNode::from(*expression.left), + box untyped::ExpressionNode::from(*expression.right), + ), + pest::BinaryOperator::Eq => untyped::Expression::Eq( + box untyped::ExpressionNode::from(*expression.left), + box untyped::ExpressionNode::from(*expression.right), + ), + pest::BinaryOperator::Lt => untyped::Expression::Lt( + box untyped::ExpressionNode::from(*expression.left), + box untyped::ExpressionNode::from(*expression.right), + ), + pest::BinaryOperator::Lte => untyped::Expression::Le( + box untyped::ExpressionNode::from(*expression.left), + box untyped::ExpressionNode::from(*expression.right), + ), + pest::BinaryOperator::Gt => untyped::Expression::Gt( + box untyped::ExpressionNode::from(*expression.left), + box untyped::ExpressionNode::from(*expression.right), + ), + pest::BinaryOperator::Gte => untyped::Expression::Ge( + box untyped::ExpressionNode::from(*expression.left), + box untyped::ExpressionNode::from(*expression.right), + ), + pest::BinaryOperator::And => untyped::Expression::And( + box untyped::ExpressionNode::from(*expression.left), + box untyped::ExpressionNode::from(*expression.right), + ), + pest::BinaryOperator::Or => untyped::Expression::Or( + box untyped::ExpressionNode::from(*expression.left), + box untyped::ExpressionNode::from(*expression.right), + ), + pest::BinaryOperator::Pow => untyped::Expression::Pow( + box untyped::ExpressionNode::from(*expression.left), + box untyped::ExpressionNode::from(*expression.right), + ), + pest::BinaryOperator::BitXor => untyped::Expression::BitXor( + box untyped::ExpressionNode::from(*expression.left), + box untyped::ExpressionNode::from(*expression.right), + ), + pest::BinaryOperator::LeftShift => untyped::Expression::LeftShift( + box untyped::ExpressionNode::from(*expression.left), + box untyped::ExpressionNode::from(*expression.right), + ), + pest::BinaryOperator::RightShift => untyped::Expression::RightShift( + box untyped::ExpressionNode::from(*expression.left), + box untyped::ExpressionNode::from(*expression.right), + ), + pest::BinaryOperator::BitAnd => untyped::Expression::BitAnd( + box untyped::ExpressionNode::from(*expression.left), + box untyped::ExpressionNode::from(*expression.right), + ), + pest::BinaryOperator::BitOr => untyped::Expression::BitOr( + box untyped::ExpressionNode::from(*expression.left), + box untyped::ExpressionNode::from(*expression.right), + ), + // rewrite (a != b)` as `!(a == b)` + pest::BinaryOperator::NotEq => untyped::Expression::Not( + box untyped::Expression::Eq( + box untyped::ExpressionNode::from(*expression.left), + box untyped::ExpressionNode::from(*expression.right), + ) + .span(expression.span.clone()), + ), + } + .span(expression.span) + } +} + +impl<'ast> From> for untyped::ExpressionNode<'ast> { + fn from(expression: pest::IfElseExpression<'ast>) -> untyped::ExpressionNode<'ast> { + use crate::untyped::NodeValue; + untyped::Expression::Conditional( + box untyped::ExpressionNode::from(*expression.condition), + box untyped::ExpressionNode::from(*expression.consequence), + box untyped::ExpressionNode::from(*expression.alternative), + untyped::ConditionalKind::IfElse, + ) + .span(expression.span) + } +} + +impl<'ast> From> for untyped::ExpressionNode<'ast> { + fn from(expression: pest::TernaryExpression<'ast>) -> untyped::ExpressionNode<'ast> { + use crate::untyped::NodeValue; + untyped::Expression::Conditional( + box untyped::ExpressionNode::from(*expression.condition), + box untyped::ExpressionNode::from(*expression.consequence), + box untyped::ExpressionNode::from(*expression.alternative), + untyped::ConditionalKind::Ternary, + ) + .span(expression.span) + } +} + +impl<'ast> From> for untyped::SpreadNode<'ast> { + fn from(spread: pest::Spread<'ast>) -> untyped::SpreadNode<'ast> { + use crate::untyped::NodeValue; + untyped::Spread { + expression: untyped::ExpressionNode::from(spread.expression), + } + .span(spread.span) + } +} + +impl<'ast> From> for untyped::RangeNode<'ast> { + fn from(range: pest::Range<'ast>) -> untyped::RangeNode<'ast> { + use crate::untyped::NodeValue; + + let from = range.from.map(|e| untyped::ExpressionNode::from(e.0)); + + let to = range.to.map(|e| untyped::ExpressionNode::from(e.0)); + + untyped::Range { from, to }.span(range.span) + } +} + +impl<'ast> From> for untyped::RangeOrExpression<'ast> { + fn from( + range_or_expression: pest::RangeOrExpression<'ast>, + ) -> untyped::RangeOrExpression<'ast> { + match range_or_expression { + pest::RangeOrExpression::Expression(e) => { + untyped::RangeOrExpression::Expression(untyped::ExpressionNode::from(e)) + } + pest::RangeOrExpression::Range(r) => { + untyped::RangeOrExpression::Range(untyped::RangeNode::from(r)) + } + } + } +} + +impl<'ast> From> for untyped::SpreadOrExpression<'ast> { + fn from( + spread_or_expression: pest::SpreadOrExpression<'ast>, + ) -> untyped::SpreadOrExpression<'ast> { + match spread_or_expression { + pest::SpreadOrExpression::Expression(e) => { + untyped::SpreadOrExpression::Expression(untyped::ExpressionNode::from(e)) + } + pest::SpreadOrExpression::Spread(s) => { + untyped::SpreadOrExpression::Spread(untyped::SpreadNode::from(s)) + } + } + } +} + +impl<'ast> From> for untyped::ExpressionNode<'ast> { + fn from(array: pest::InlineArrayExpression<'ast>) -> untyped::ExpressionNode<'ast> { + use crate::untyped::NodeValue; + untyped::Expression::InlineArray( + array + .expressions + .into_iter() + .map(untyped::SpreadOrExpression::from) + .collect(), + ) + .span(array.span) + } +} + +impl<'ast> From> for untyped::ExpressionNode<'ast> { + fn from(tuple: pest::InlineTupleExpression<'ast>) -> untyped::ExpressionNode<'ast> { + use crate::untyped::NodeValue; + untyped::Expression::InlineTuple( + tuple + .elements + .into_iter() + .map(untyped::ExpressionNode::from) + .collect(), + ) + .span(tuple.span) + } +} + +impl<'ast> From> for untyped::ExpressionNode<'ast> { + fn from(s: pest::InlineStructExpression<'ast>) -> untyped::ExpressionNode<'ast> { + use crate::untyped::NodeValue; + untyped::Expression::InlineStruct( + s.ty.span.as_str().to_string(), + s.members + .into_iter() + .map(|member| { + ( + member.id.span.as_str(), + untyped::ExpressionNode::from(member.expression), + ) + }) + .collect(), + ) + .span(s.span) + } +} + +impl<'ast> From> for untyped::ExpressionNode<'ast> { + fn from(initializer: pest::ArrayInitializerExpression<'ast>) -> untyped::ExpressionNode<'ast> { + use crate::untyped::NodeValue; + + let value = untyped::ExpressionNode::from(*initializer.value); + let count = untyped::ExpressionNode::from(*initializer.count); + untyped::Expression::ArrayInitializer(box value, box count).span(initializer.span) + } +} + +impl<'ast> From> for untyped::ExpressionNode<'ast> { + fn from(unary: pest::UnaryExpression<'ast>) -> untyped::ExpressionNode<'ast> { + use crate::untyped::NodeValue; + + let expression = Box::new(untyped::ExpressionNode::from(*unary.expression)); + + match unary.op { + pest::UnaryOperator::Not(..) => untyped::Expression::Not(expression), + pest::UnaryOperator::Neg(..) => untyped::Expression::Neg(expression), + pest::UnaryOperator::Pos(..) => untyped::Expression::Pos(expression), + } + .span(unary.span) + } +} + +impl<'ast> From> for untyped::ExpressionNode<'ast> { + fn from(expression: pest::PostfixExpression<'ast>) -> untyped::ExpressionNode<'ast> { + use crate::untyped::NodeValue; + + let base = untyped::ExpressionNode::from(*expression.base); + + // pest::PostFixExpression contains an array of "accesses": `a(34)[42]` is represented as `[a, [Call(34), Select(42)]]`, but untyped::ExpressionNode + // is recursive, so it is `Select(Call(a, 34), 42)`. We apply this transformation here + // we start with the base, and we fold the array of accesses by wrapping the current value + expression + .accesses + .into_iter() + .fold(base, |acc, a| match a { + pest::Access::Call(a) => untyped::Expression::FunctionCall( + Box::new(acc), + a.explicit_generics.map(|explicit_generics| { + explicit_generics + .values + .into_iter() + .map(|i| match i { + pest::ConstantGenericValue::Underscore(_) => None, + pest::ConstantGenericValue::Value(v) => { + Some(untyped::ExpressionNode::from(v)) + } + pest::ConstantGenericValue::Identifier(i) => Some( + untyped::Expression::Identifier(i.span.as_str()).span(i.span), + ), + }) + .collect() + }), + a.arguments + .expressions + .into_iter() + .map(untyped::ExpressionNode::from) + .collect(), + ) + .span(a.span), + pest::Access::Select(a) => untyped::Expression::Select( + box acc, + box untyped::RangeOrExpression::from(a.expression), + ) + .span(a.span), + pest::Access::Dot(m) => match m.inner { + pest::IdentifierOrDecimal::Identifier(id) => { + untyped::Expression::Member(box acc, box id.span.as_str()).span(m.span) + } + pest::IdentifierOrDecimal::Decimal(id) => { + untyped::Expression::Element(box acc, id.span.as_str().parse().unwrap()) + .span(m.span) + } + }, + }) + } +} + +impl<'ast> From> for untyped::ExpressionNode<'ast> { + fn from(expression: pest::DecimalLiteralExpression<'ast>) -> untyped::ExpressionNode<'ast> { + use crate::untyped::NodeValue; + + match expression.suffix { + Some(suffix) => match suffix { + pest::DecimalSuffix::Field(_) => untyped::Expression::FieldConstant( + BigUint::parse_bytes(expression.value.span.as_str().as_bytes(), 10).unwrap(), + ), + pest::DecimalSuffix::U64(_) => untyped::Expression::U64Constant( + expression.value.span.as_str().parse().unwrap(), + ), + pest::DecimalSuffix::U32(_) => untyped::Expression::U32Constant( + expression.value.span.as_str().parse().unwrap(), + ), + pest::DecimalSuffix::U16(_) => untyped::Expression::U16Constant( + expression.value.span.as_str().parse().unwrap(), + ), + pest::DecimalSuffix::U8(_) => { + untyped::Expression::U8Constant(expression.value.span.as_str().parse().unwrap()) + } + } + .span(expression.span), + None => untyped::Expression::IntConstant( + BigUint::parse_bytes(expression.value.span.as_str().as_bytes(), 10).unwrap(), + ) + .span(expression.span), + } + } +} + +impl<'ast> From> for untyped::ExpressionNode<'ast> { + fn from(expression: pest::HexLiteralExpression<'ast>) -> untyped::ExpressionNode<'ast> { + use crate::untyped::NodeValue; + + match expression.value { + pest::HexNumberExpression::U64(e) => { + untyped::Expression::U64Constant(u64::from_str_radix(e.span.as_str(), 16).unwrap()) + } + pest::HexNumberExpression::U32(e) => { + untyped::Expression::U32Constant(u32::from_str_radix(e.span.as_str(), 16).unwrap()) + } + pest::HexNumberExpression::U16(e) => { + untyped::Expression::U16Constant(u16::from_str_radix(e.span.as_str(), 16).unwrap()) + } + pest::HexNumberExpression::U8(e) => { + untyped::Expression::U8Constant(u8::from_str_radix(e.span.as_str(), 16).unwrap()) + } + } + .span(expression.span) + } +} + +impl<'ast> From> for untyped::ExpressionNode<'ast> { + fn from(expression: pest::LiteralExpression<'ast>) -> untyped::ExpressionNode<'ast> { + use crate::untyped::NodeValue; + + match expression { + pest::LiteralExpression::BooleanLiteral(c) => { + untyped::Expression::BooleanConstant(c.value.parse().unwrap()).span(c.span) + } + pest::LiteralExpression::DecimalLiteral(n) => untyped::ExpressionNode::from(n), + pest::LiteralExpression::HexLiteral(n) => untyped::ExpressionNode::from(n), + } + } +} + +impl<'ast> From> for untyped::ExpressionNode<'ast> { + fn from(expression: pest::IdentifierExpression<'ast>) -> untyped::ExpressionNode<'ast> { + use crate::untyped::NodeValue; + untyped::Expression::Identifier(expression.span.as_str()).span(expression.span) + } +} + +impl<'ast> From> for untyped::AssigneeNode<'ast> { + fn from(expression: pest::IdentifierExpression<'ast>) -> untyped::AssigneeNode<'ast> { + use crate::untyped::NodeValue; + + untyped::Assignee::Identifier(expression.span.as_str()).span(expression.span) + } +} + +impl<'ast> From> for untyped::AssigneeNode<'ast> { + fn from(assignee: pest::Assignee<'ast>) -> untyped::AssigneeNode<'ast> { + use crate::untyped::NodeValue; + + let a = untyped::AssigneeNode::from(assignee.id); + let span = assignee.span; + + assignee.accesses.into_iter().fold(a, |acc, s| { + match s { + pest::AssigneeAccess::Select(s) => untyped::Assignee::Select( + box acc, + box untyped::RangeOrExpression::from(s.expression), + ), + pest::AssigneeAccess::Dot(a) => match a.inner { + pest::IdentifierOrDecimal::Identifier(id) => { + untyped::Assignee::Member(box acc, box id.span.as_str()) + } + pest::IdentifierOrDecimal::Decimal(id) => { + untyped::Assignee::Element(box acc, id.span.as_str().parse().unwrap()) + } + }, + } + .span(span.clone()) + }) + } +} + +impl<'ast> From> for untyped::UnresolvedTypeNode<'ast> { + fn from(t: pest::Type<'ast>) -> untyped::UnresolvedTypeNode<'ast> { + use crate::untyped::types::UnresolvedType; + use crate::untyped::NodeValue; + + match t { + pest::Type::Basic(t) => match t { + 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::BasicType::U64(t) => UnresolvedType::Uint(64).span(t.span), + }, + pest::Type::Array(t) => { + let inner_type = match t.ty { + pest::BasicOrStructOrTupleType::Basic(t) => match t { + 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::BasicType::U64(t) => UnresolvedType::Uint(64).span(t.span), + }, + pest::BasicOrStructOrTupleType::Struct(t) => UnresolvedType::User( + t.id.span.as_str().to_string(), + t.explicit_generics.map(|explicit_generics| { + explicit_generics + .values + .into_iter() + .map(|i| match i { + pest::ConstantGenericValue::Underscore(_) => None, + pest::ConstantGenericValue::Value(v) => { + Some(untyped::ExpressionNode::from(v)) + } + pest::ConstantGenericValue::Identifier(i) => Some( + untyped::Expression::Identifier(i.span.as_str()) + .span(i.span), + ), + }) + .collect() + }), + ) + .span(t.span), + pest::BasicOrStructOrTupleType::Tuple(t) => UnresolvedType::Tuple( + t.elements + .into_iter() + .map(untyped::UnresolvedTypeNode::from) + .collect(), + ) + .span(t.span), + }; + + let span = t.span; + + t.dimensions + .into_iter() + .map(untyped::ExpressionNode::from) + .rev() + .fold(None, |acc, s| match acc { + 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) => UnresolvedType::User( + s.id.span.as_str().to_string(), + s.explicit_generics.map(|explicit_generics| { + explicit_generics + .values + .into_iter() + .map(|i| match i { + pest::ConstantGenericValue::Underscore(_) => None, + pest::ConstantGenericValue::Value(v) => { + Some(untyped::ExpressionNode::from(v)) + } + pest::ConstantGenericValue::Identifier(i) => { + Some(untyped::Expression::Identifier(i.span.as_str()).span(i.span)) + } + }) + .collect() + }), + ) + .span(s.span), + pest::Type::Tuple(t) => UnresolvedType::Tuple( + t.elements + .into_iter() + .map(untyped::UnresolvedTypeNode::from) + .collect(), + ) + .span(t.span), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::untyped::types::{UnresolvedSignature, UnresolvedType}; + use crate::untyped::NodeValue; + + #[test] + fn return_forty_two() { + let source = "def main() -> field: return 42"; + let ast = pest::generate_ast(source).unwrap(); + let expected: untyped::Module = untyped::Module { + symbols: vec![untyped::SymbolDeclaration { + id: &source[4..8], + symbol: untyped::Symbol::Here(untyped::SymbolDefinition::Function( + untyped::Function { + arguments: vec![], + statements: vec![untyped::Statement::Return( + untyped::ExpressionList { + expressions: vec![ + untyped::Expression::IntConstant(42usize.into()).into() + ], + } + .into(), + ) + .into()], + signature: UnresolvedSignature::new() + .inputs(vec![]) + .outputs(vec![UnresolvedType::FieldElement.mock()]), + } + .into(), + )), + } + .into()], + }; + assert_eq!(untyped::Module::from(ast), expected); + } + + #[test] + fn return_true() { + let source = "def main() -> bool: return true"; + let ast = pest::generate_ast(source).unwrap(); + let expected: untyped::Module = + untyped::Module { + symbols: vec![untyped::SymbolDeclaration { + id: &source[4..8], + symbol: untyped::Symbol::Here(untyped::SymbolDefinition::Function( + untyped::Function { + arguments: vec![], + statements: vec![untyped::Statement::Return( + untyped::ExpressionList { + expressions: vec![ + untyped::Expression::BooleanConstant(true).into() + ], + } + .into(), + ) + .into()], + signature: UnresolvedSignature::new() + .inputs(vec![]) + .outputs(vec![UnresolvedType::Boolean.mock()]), + } + .into(), + )), + } + .into()], + }; + assert_eq!(untyped::Module::from(ast), expected); + } + + #[test] + fn arguments() { + let source = "def main(private field a, bool b) -> field: return 42"; + let ast = pest::generate_ast(source).unwrap(); + + let expected: untyped::Module = untyped::Module { + symbols: vec![untyped::SymbolDeclaration { + id: &source[4..8], + symbol: untyped::Symbol::Here(untyped::SymbolDefinition::Function( + untyped::Function { + arguments: vec![ + untyped::Parameter::private( + untyped::Variable::new( + &source[23..24], + UnresolvedType::FieldElement.mock(), + ) + .into(), + ) + .into(), + untyped::Parameter::public( + untyped::Variable::new( + &source[31..32], + UnresolvedType::Boolean.mock(), + ) + .into(), + ) + .into(), + ], + statements: vec![untyped::Statement::Return( + untyped::ExpressionList { + expressions: vec![ + untyped::Expression::IntConstant(42usize.into()).into() + ], + } + .into(), + ) + .into()], + signature: UnresolvedSignature::new() + .inputs(vec![ + UnresolvedType::FieldElement.mock(), + UnresolvedType::Boolean.mock(), + ]) + .outputs(vec![UnresolvedType::FieldElement.mock()]), + } + .into(), + )), + } + .into()], + }; + + assert_eq!(untyped::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: UnresolvedType<'static>) -> untyped::Module<'static> { + untyped::Module { + symbols: vec![untyped::SymbolDeclaration { + id: "main", + symbol: untyped::Symbol::Here(untyped::SymbolDefinition::Function( + untyped::Function { + arguments: vec![untyped::Parameter::private( + untyped::Variable::new("a", ty.clone().mock()).into(), + ) + .into()], + statements: vec![untyped::Statement::Return( + untyped::ExpressionList { + expressions: vec![], + } + .into(), + ) + .into()], + signature: UnresolvedSignature::new().inputs(vec![ty.mock()]), + } + .into(), + )), + } + .into()], + } + } + + #[test] + fn array() { + let vectors = vec![ + ("field", UnresolvedType::FieldElement), + ("bool", UnresolvedType::Boolean), + ( + "field[2]", + untyped::UnresolvedType::Array( + box untyped::UnresolvedType::FieldElement.mock(), + untyped::Expression::IntConstant(2usize.into()).mock(), + ), + ), + ( + "field[2][3]", + untyped::UnresolvedType::Array( + box untyped::UnresolvedType::Array( + box untyped::UnresolvedType::FieldElement.mock(), + untyped::Expression::IntConstant(3usize.into()).mock(), + ) + .mock(), + untyped::Expression::IntConstant(2usize.into()).mock(), + ), + ), + ( + "bool[2][3u32]", + untyped::UnresolvedType::Array( + box untyped::UnresolvedType::Array( + box untyped::UnresolvedType::Boolean.mock(), + untyped::Expression::U32Constant(3u32).mock(), + ) + .mock(), + untyped::Expression::IntConstant(2usize.into()).mock(), + ), + ), + ]; + + for (ty, expected) in vectors { + let source = format!("def main(private {} a): return", ty); + let expected = wrap(expected); + let ast = pest::generate_ast(&source).unwrap(); + assert_eq!(untyped::Module::from(ast), expected); + } + } + } + + mod postfix { + use super::*; + fn wrap(expression: untyped::Expression<'static>) -> untyped::Module { + untyped::Module { + symbols: vec![untyped::SymbolDeclaration { + id: "main", + symbol: untyped::Symbol::Here(untyped::SymbolDefinition::Function( + untyped::Function { + arguments: vec![], + statements: vec![untyped::Statement::Return( + untyped::ExpressionList { + expressions: vec![expression.into()], + } + .into(), + ) + .into()], + signature: UnresolvedSignature::new(), + } + .into(), + )), + } + .into()], + } + } + + #[test] + fn success() { + // we basically accept `()?[]*` : an optional call at first, then only array accesses + + let vectors = vec![ + ("a", untyped::Expression::Identifier("a")), + ( + "a[3]", + untyped::Expression::Select( + box untyped::Expression::Identifier("a").into(), + box untyped::RangeOrExpression::Expression( + untyped::Expression::IntConstant(3usize.into()).into(), + ), + ), + ), + ( + "a[3][4]", + untyped::Expression::Select( + box untyped::Expression::Select( + box untyped::Expression::Identifier("a").into(), + box untyped::RangeOrExpression::Expression( + untyped::Expression::IntConstant(3usize.into()).into(), + ), + ) + .into(), + box untyped::RangeOrExpression::Expression( + untyped::Expression::IntConstant(4usize.into()).into(), + ), + ), + ), + ( + "a(3)[4]", + untyped::Expression::Select( + box untyped::Expression::FunctionCall( + box untyped::Expression::Identifier("a").mock(), + None, + vec![untyped::Expression::IntConstant(3usize.into()).into()], + ) + .into(), + box untyped::RangeOrExpression::Expression( + untyped::Expression::IntConstant(4usize.into()).into(), + ), + ), + ), + ( + "a(3)[4][5]", + untyped::Expression::Select( + box untyped::Expression::Select( + box untyped::Expression::FunctionCall( + box untyped::Expression::Identifier("a").mock(), + None, + vec![untyped::Expression::IntConstant(3usize.into()).into()], + ) + .into(), + box untyped::RangeOrExpression::Expression( + untyped::Expression::IntConstant(4usize.into()).into(), + ), + ) + .into(), + box untyped::RangeOrExpression::Expression( + untyped::Expression::IntConstant(5usize.into()).into(), + ), + ), + ), + ]; + + for (source, expected) in vectors { + let source = format!("def main(): return {}", source); + let expected = wrap(expected); + let ast = pest::generate_ast(&source).unwrap(); + assert_eq!(untyped::Module::from(ast), expected); + } + } + + #[test] + fn call_array_element() { + // a call after an array access should be accepted + let source = "def main(): return a[2](3)"; + let ast = pest::generate_ast(source).unwrap(); + assert_eq!( + untyped::Module::from(ast), + wrap(untyped::Expression::FunctionCall( + box untyped::Expression::Select( + box untyped::Expression::Identifier("a").mock(), + box untyped::RangeOrExpression::Expression( + untyped::Expression::IntConstant(2u32.into()).mock() + ) + ) + .mock(), + None, + vec![untyped::Expression::IntConstant(3u32.into()).mock()], + )) + ); + } + + #[test] + fn call_call_result() { + // a call after a call should be accepted + let source = "def main(): return a(2)(3)"; + + let ast = pest::generate_ast(source).unwrap(); + assert_eq!( + untyped::Module::from(ast), + wrap(untyped::Expression::FunctionCall( + box untyped::Expression::FunctionCall( + box untyped::Expression::Identifier("a").mock(), + None, + vec![untyped::Expression::IntConstant(2u32.into()).mock()] + ) + .mock(), + None, + vec![untyped::Expression::IntConstant(3u32.into()).mock()], + )) + ); + } + } + #[test] + fn declarations() { + use self::pest::Span; + + let span = Span::new("", 0, 0).unwrap(); + + // For different definitions, we generate declarations + // Case 1: `id = expr` where `expr` is not a function call + // This is a simple assignment, doesn't implicitely declare a variable + // A `Definition` is generated and no `Declaration`s + + let definition = pest::DefinitionStatement { + lhs: vec![pest::TypedIdentifierOrAssignee::Assignee(pest::Assignee { + id: pest::IdentifierExpression { + value: String::from("a"), + span: span.clone(), + }, + accesses: vec![], + span: span.clone(), + })], + expression: pest::Expression::Literal(pest::LiteralExpression::DecimalLiteral( + pest::DecimalLiteralExpression { + value: pest::DecimalNumber { + span: Span::new("1", 0, 1).unwrap(), + }, + suffix: None, + span: span.clone(), + }, + )), + span: span.clone(), + }; + + let statements: Vec = statements_from_definition(definition); + + assert_eq!(statements.len(), 1); + match &statements[0].value { + untyped::Statement::Definition(..) => {} + s => { + panic!("should be a Definition, found {}", s); + } + }; + + // Case 2: `id = expr` where `expr` is a function call + // A MultiDef is generated + + let definition = pest::DefinitionStatement { + lhs: vec![pest::TypedIdentifierOrAssignee::Assignee(pest::Assignee { + id: pest::IdentifierExpression { + value: String::from("a"), + span: span.clone(), + }, + accesses: vec![], + span: span.clone(), + })], + expression: pest::Expression::Postfix(pest::PostfixExpression { + base: box pest::Expression::Identifier(pest::IdentifierExpression { + value: String::from("foo"), + span: span.clone(), + }), + accesses: vec![pest::Access::Call(pest::CallAccess { + explicit_generics: None, + arguments: pest::Arguments { + expressions: vec![], + span: span.clone(), + }, + span: span.clone(), + })], + span: span.clone(), + }), + span: span.clone(), + }; + + let statements: Vec = statements_from_definition(definition); + + assert_eq!(statements.len(), 1); + match &statements[0].value { + untyped::Statement::MultipleDefinition(..) => {} + s => { + panic!("should be a Definition, found {}", s); + } + }; + // Case 3: `ids = expr` where `expr` is a function call + // This implicitely declares all variables which are type annotated + + // `field a, b = foo()` + + let definition = pest::DefinitionStatement { + lhs: vec![ + pest::TypedIdentifierOrAssignee::TypedIdentifier(pest::TypedIdentifier { + ty: pest::Type::Basic(pest::BasicType::Field(pest::FieldType { + span: span.clone(), + })), + identifier: pest::IdentifierExpression { + value: String::from("a"), + span: span.clone(), + }, + span: span.clone(), + }), + pest::TypedIdentifierOrAssignee::Assignee(pest::Assignee { + id: pest::IdentifierExpression { + value: String::from("b"), + span: span.clone(), + }, + accesses: vec![], + span: span.clone(), + }), + ], + expression: pest::Expression::Postfix(pest::PostfixExpression { + base: box pest::Expression::Identifier(pest::IdentifierExpression { + value: String::from("foo"), + span: span.clone(), + }), + accesses: vec![pest::Access::Call(pest::CallAccess { + explicit_generics: None, + arguments: pest::Arguments { + expressions: vec![], + span: span.clone(), + }, + span: span.clone(), + })], + span: span.clone(), + }), + span: span.clone(), + }; + + let statements: Vec = statements_from_definition(definition); + + assert_eq!(statements.len(), 2); + match &statements[1].value { + untyped::Statement::MultipleDefinition(..) => {} + s => { + panic!("should be a Definition, found {}", s); + } + }; + } +} diff --git a/zokrates_core/src/absy/mod.rs b/zokrates_ast/src/untyped/mod.rs similarity index 98% rename from zokrates_core/src/absy/mod.rs rename to zokrates_ast/src/untyped/mod.rs index c9caa5dd..a0afe35e 100644 --- a/zokrates_core/src/absy/mod.rs +++ b/zokrates_ast/src/untyped/mod.rs @@ -8,14 +8,16 @@ mod from_ast; mod node; pub mod parameter; +mod position; pub mod types; pub mod variable; -pub use crate::absy::node::{Node, NodeValue}; -pub use crate::absy::parameter::{Parameter, ParameterNode}; -use crate::absy::types::{UnresolvedSignature, UnresolvedType, UserTypeId}; -pub use crate::absy::variable::{Variable, VariableNode}; -use crate::embed::FlatEmbed; +pub use self::node::{Node, NodeValue}; +pub use self::parameter::{Parameter, ParameterNode}; +pub use self::position::Position; +use self::types::{UnresolvedSignature, UnresolvedType, UserTypeId}; +pub use self::variable::{Variable, VariableNode}; +use crate::common::FlatEmbed; use std::path::{Path, PathBuf}; use std::fmt; diff --git a/zokrates_core/src/absy/node.rs b/zokrates_ast/src/untyped/node.rs similarity index 97% rename from zokrates_core/src/absy/node.rs rename to zokrates_ast/src/untyped/node.rs index 0332ad57..75c9d598 100644 --- a/zokrates_core/src/absy/node.rs +++ b/zokrates_ast/src/untyped/node.rs @@ -1,4 +1,3 @@ -use crate::parser::Position; use std::fmt; use zokrates_pest_ast::Span; @@ -81,8 +80,7 @@ impl From for Node { } } -use crate::absy::types::UnresolvedType; -use crate::absy::*; +use super::*; impl<'ast> NodeValue for Expression<'ast> {} impl<'ast> NodeValue for ExpressionList<'ast> {} diff --git a/zokrates_core/src/absy/parameter.rs b/zokrates_ast/src/untyped/parameter.rs similarity index 96% rename from zokrates_core/src/absy/parameter.rs rename to zokrates_ast/src/untyped/parameter.rs index cc103321..14700678 100644 --- a/zokrates_core/src/absy/parameter.rs +++ b/zokrates_ast/src/untyped/parameter.rs @@ -1,4 +1,4 @@ -use crate::absy::{Node, VariableNode}; +use super::{Node, VariableNode}; use std::fmt; #[derive(Clone, PartialEq)] diff --git a/zokrates_core/src/parser/tokenize/position.rs b/zokrates_ast/src/untyped/position.rs similarity index 100% rename from zokrates_core/src/parser/tokenize/position.rs rename to zokrates_ast/src/untyped/position.rs diff --git a/zokrates_core/src/absy/types.rs b/zokrates_ast/src/untyped/types.rs similarity index 96% rename from zokrates_core/src/absy/types.rs rename to zokrates_ast/src/untyped/types.rs index 924e72cf..1bdbded3 100644 --- a/zokrates_core/src/absy/types.rs +++ b/zokrates_ast/src/untyped/types.rs @@ -1,5 +1,5 @@ -use crate::absy::ExpressionNode; -use crate::absy::UnresolvedTypeNode; +use super::ExpressionNode; +use super::UnresolvedTypeNode; use std::fmt; pub type Identifier<'ast> = &'ast str; @@ -76,10 +76,10 @@ impl<'ast> UnresolvedType<'ast> { pub use self::signature::UnresolvedSignature; mod signature { - use crate::absy::ConstantGenericNode; + use crate::untyped::ConstantGenericNode; use std::fmt; - use crate::absy::UnresolvedTypeNode; + use crate::untyped::UnresolvedTypeNode; #[derive(Clone, PartialEq, Default)] pub struct UnresolvedSignature<'ast> { diff --git a/zokrates_core/src/absy/variable.rs b/zokrates_ast/src/untyped/variable.rs similarity index 88% rename from zokrates_core/src/absy/variable.rs rename to zokrates_ast/src/untyped/variable.rs index 6b8f9b60..c7bcbe21 100644 --- a/zokrates_core/src/absy/variable.rs +++ b/zokrates_ast/src/untyped/variable.rs @@ -1,8 +1,8 @@ -use crate::absy::types::UnresolvedType; -use crate::absy::{Node, UnresolvedTypeNode}; +use super::types::UnresolvedType; +use super::{Node, UnresolvedTypeNode}; use std::fmt; -use crate::absy::Identifier; +use super::Identifier; #[derive(Clone, PartialEq)] pub struct Variable<'ast> { diff --git a/zokrates_core/src/zir/folder.rs b/zokrates_ast/src/zir/folder.rs similarity index 100% rename from zokrates_core/src/zir/folder.rs rename to zokrates_ast/src/zir/folder.rs diff --git a/zokrates_core/src/zir/from_typed.rs b/zokrates_ast/src/zir/from_typed.rs similarity index 97% rename from zokrates_core/src/zir/from_typed.rs rename to zokrates_ast/src/zir/from_typed.rs index 3b5b9384..fb3f9475 100644 --- a/zokrates_core/src/zir/from_typed.rs +++ b/zokrates_ast/src/zir/from_typed.rs @@ -1,4 +1,4 @@ -use crate::typed_absy; +use crate::typed as typed_absy; use crate::zir; impl From for zir::types::Signature { diff --git a/zokrates_core/src/zir/identifier.rs b/zokrates_ast/src/zir/identifier.rs similarity index 95% rename from zokrates_core/src/zir/identifier.rs rename to zokrates_ast/src/zir/identifier.rs index 5d379c2a..f010f2f8 100644 --- a/zokrates_core/src/zir/identifier.rs +++ b/zokrates_ast/src/zir/identifier.rs @@ -1,7 +1,7 @@ use crate::zir::types::MemberId; use std::fmt; -use crate::typed_absy::Identifier as CoreIdentifier; +use crate::typed::Identifier as CoreIdentifier; #[derive(Debug, PartialEq, Clone, Hash, Eq)] pub enum Identifier<'ast> { diff --git a/zokrates_core/src/zir/mod.rs b/zokrates_ast/src/zir/mod.rs similarity index 99% rename from zokrates_core/src/zir/mod.rs rename to zokrates_ast/src/zir/mod.rs index 2f7dcd89..f93ea719 100644 --- a/zokrates_core/src/zir/mod.rs +++ b/zokrates_ast/src/zir/mod.rs @@ -10,9 +10,9 @@ mod variable; pub use self::parameter::Parameter; pub use self::types::Type; pub use self::variable::Variable; +use crate::common::FlatEmbed; pub use crate::zir::uint::{ShouldReduce, UExpression, UExpressionInner, UMetadata}; -use crate::embed::FlatEmbed; use crate::zir::types::Signature; use std::convert::TryFrom; use std::fmt; diff --git a/zokrates_core/src/zir/parameter.rs b/zokrates_ast/src/zir/parameter.rs similarity index 100% rename from zokrates_core/src/zir/parameter.rs rename to zokrates_ast/src/zir/parameter.rs diff --git a/zokrates_core/src/zir/result_folder.rs b/zokrates_ast/src/zir/result_folder.rs similarity index 100% rename from zokrates_core/src/zir/result_folder.rs rename to zokrates_ast/src/zir/result_folder.rs diff --git a/zokrates_core/src/zir/types.rs b/zokrates_ast/src/zir/types.rs similarity index 100% rename from zokrates_core/src/zir/types.rs rename to zokrates_ast/src/zir/types.rs diff --git a/zokrates_core/src/zir/uint.rs b/zokrates_ast/src/zir/uint.rs similarity index 100% rename from zokrates_core/src/zir/uint.rs rename to zokrates_ast/src/zir/uint.rs diff --git a/zokrates_core/src/zir/variable.rs b/zokrates_ast/src/zir/variable.rs similarity index 100% rename from zokrates_core/src/zir/variable.rs rename to zokrates_ast/src/zir/variable.rs diff --git a/zokrates_core/Cargo.toml b/zokrates_core/Cargo.toml index 67176eb2..e469112a 100644 --- a/zokrates_core/Cargo.toml +++ b/zokrates_core/Cargo.toml @@ -26,13 +26,14 @@ reduce = "0.1.1" # serialization and deserialization serde = { version = "1.0", features = ["derive"] } serde_json = { version = "1.0", features = ["preserve_order"] } -serde_cbor = "0.11.2" hex = "0.4.2" regex = "0.2" zokrates_field = { version = "0.5.0", path = "../zokrates_field", default-features = false } zokrates_pest_ast = { version = "0.2.0", path = "../zokrates_pest_ast" } zokrates_common = { path = "../zokrates_common" } zokrates_embed = { version = "0.1.0", path = "../zokrates_embed" } +zokrates_interpreter = { version = "0.1", path = "../zokrates_interpreter" } +zokrates_ast = { version = "0.1", path = "../zokrates_ast" } getrandom = { version = "0.2", features = ["js", "wasm-bindgen"] } rand_0_4 = { version = "0.4", package = "rand" } rand_0_8 = { version = "0.8", package = "rand" } diff --git a/zokrates_core/src/absy/from_ast.rs b/zokrates_core/src/absy/from_ast.rs deleted file mode 100644 index 81b0ccc8..00000000 --- a/zokrates_core/src/absy/from_ast.rs +++ /dev/null @@ -1,1386 +0,0 @@ -use crate::absy; - -use crate::absy::SymbolDefinition; -use num_bigint::BigUint; -use std::path::Path; -use zokrates_pest_ast as pest; - -impl<'ast> From> for absy::Module<'ast> { - fn from(file: pest::File<'ast>) -> absy::Module<'ast> { - absy::Module::with_symbols(file.declarations.into_iter().flat_map(|d| match d { - pest::SymbolDeclaration::Import(i) => import_directive_to_symbol_vec(i), - pest::SymbolDeclaration::Constant(c) => vec![c.into()], - pest::SymbolDeclaration::Struct(s) => vec![s.into()], - pest::SymbolDeclaration::Type(t) => vec![t.into()], - pest::SymbolDeclaration::Function(f) => vec![f.into()], - })) - } -} - -fn import_directive_to_symbol_vec( - import: pest::ImportDirective, -) -> Vec { - use crate::absy::NodeValue; - - match import { - pest::ImportDirective::Main(import) => { - let span = import.span; - let source = Path::new(import.source.span.as_str()); - let id = "main"; - let alias = import.alias.map(|a| a.span.as_str()); - - let import = absy::CanonicalImport { - source, - id: absy::SymbolIdentifier::from(id).alias(alias), - } - .span(span.clone()); - - vec![absy::SymbolDeclaration { - id: alias.unwrap_or(id), - symbol: absy::Symbol::Here(absy::SymbolDefinition::Import(import)), - } - .span(span.clone())] - } - pest::ImportDirective::From(import) => { - let span = import.span; - let source = Path::new(import.source.span.as_str()); - import - .symbols - .into_iter() - .map(|symbol| { - let alias = symbol - .alias - .as_ref() - .map(|a| a.span.as_str()) - .unwrap_or_else(|| symbol.id.span.as_str()); - - let import = absy::CanonicalImport { - source, - id: absy::SymbolIdentifier::from(symbol.id.span.as_str()) - .alias(Some(alias)), - } - .span(span.clone()); - - absy::SymbolDeclaration { - id: alias, - symbol: absy::Symbol::Here(absy::SymbolDefinition::Import(import)), - } - .span(span.clone()) - }) - .collect() - } - } -} - -impl<'ast> From> for absy::SymbolDeclarationNode<'ast> { - fn from(definition: pest::StructDefinition<'ast>) -> absy::SymbolDeclarationNode<'ast> { - use crate::absy::NodeValue; - - let span = definition.span; - - let id = definition.id.span.as_str(); - - let ty = absy::StructDefinition { - generics: definition - .generics - .into_iter() - .map(absy::ConstantGenericNode::from) - .collect(), - fields: definition - .fields - .into_iter() - .map(absy::StructDefinitionFieldNode::from) - .collect(), - } - .span(span.clone()); - - absy::SymbolDeclaration { - id, - symbol: absy::Symbol::Here(absy::SymbolDefinition::Struct(ty)), - } - .span(span) - } -} - -impl<'ast> From> for absy::StructDefinitionFieldNode<'ast> { - fn from(field: pest::StructField<'ast>) -> absy::StructDefinitionFieldNode<'ast> { - use crate::absy::NodeValue; - - let span = field.span; - - let id = field.id.span.as_str(); - - let ty = absy::UnresolvedTypeNode::from(field.ty); - - absy::StructDefinitionField { id, ty }.span(span) - } -} - -impl<'ast> From> for absy::SymbolDeclarationNode<'ast> { - fn from(definition: pest::ConstantDefinition<'ast>) -> absy::SymbolDeclarationNode<'ast> { - use crate::absy::NodeValue; - - let span = definition.span; - let id = definition.id.span.as_str(); - - let ty = absy::ConstantDefinition { - ty: definition.ty.into(), - expression: definition.expression.into(), - } - .span(span.clone()); - - absy::SymbolDeclaration { - id, - symbol: absy::Symbol::Here(absy::SymbolDefinition::Constant(ty)), - } - .span(span) - } -} - -impl<'ast> From> for absy::SymbolDeclarationNode<'ast> { - fn from(definition: pest::TypeDefinition<'ast>) -> absy::SymbolDeclarationNode<'ast> { - use crate::absy::NodeValue; - - let span = definition.span; - let id = definition.id.span.as_str(); - - let ty = absy::TypeDefinition { - generics: definition - .generics - .into_iter() - .map(absy::ConstantGenericNode::from) - .collect(), - ty: definition.ty.into(), - } - .span(span.clone()); - - absy::SymbolDeclaration { - id, - symbol: absy::Symbol::Here(SymbolDefinition::Type(ty)), - } - .span(span) - } -} - -impl<'ast> From> for absy::SymbolDeclarationNode<'ast> { - fn from(function: pest::FunctionDefinition<'ast>) -> absy::SymbolDeclarationNode<'ast> { - use crate::absy::NodeValue; - - let span = function.span; - - let signature = absy::UnresolvedSignature::new() - .generics( - function - .generics - .into_iter() - .map(absy::ConstantGenericNode::from) - .collect(), - ) - .inputs( - function - .parameters - .clone() - .into_iter() - .map(|p| absy::UnresolvedTypeNode::from(p.ty)) - .collect(), - ) - .outputs( - function - .returns - .clone() - .into_iter() - .map(absy::UnresolvedTypeNode::from) - .collect(), - ); - - let id = function.id.span.as_str(); - - let function = absy::Function { - arguments: function - .parameters - .into_iter() - .map(absy::ParameterNode::from) - .collect(), - statements: function - .statements - .into_iter() - .flat_map(statements_from_statement) - .collect(), - signature, - } - .span(span.clone()); - - absy::SymbolDeclaration { - id, - symbol: absy::Symbol::Here(absy::SymbolDefinition::Function(function)), - } - .span(span) - } -} - -impl<'ast> From> for absy::ConstantGenericNode<'ast> { - fn from(g: pest::IdentifierExpression<'ast>) -> absy::ConstantGenericNode<'ast> { - use absy::NodeValue; - - let name = g.span.as_str(); - - name.span(g.span) - } -} - -impl<'ast> From> for absy::ParameterNode<'ast> { - fn from(param: pest::Parameter<'ast>) -> absy::ParameterNode<'ast> { - use crate::absy::NodeValue; - - let private = param - .visibility - .map(|v| match v { - pest::Visibility::Private(_) => true, - pest::Visibility::Public(_) => false, - }) - .unwrap_or(false); - - let variable = absy::Variable::new( - param.id.span.as_str(), - absy::UnresolvedTypeNode::from(param.ty), - ) - .span(param.id.span); - - absy::Parameter::new(variable, private).span(param.span) - } -} - -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)], - pest::Statement::Assertion(s) => vec![absy::StatementNode::from(s)], - pest::Statement::Return(s) => vec![absy::StatementNode::from(s)], - } -} - -fn statements_from_definition(definition: pest::DefinitionStatement) -> Vec { - use crate::absy::NodeValue; - - let lhs = definition.lhs; - - match lhs.len() { - 1 => { - // Definition or assignment - let a = lhs[0].clone(); - - let e: absy::ExpressionNode = absy::ExpressionNode::from(definition.expression); - - match a { - pest::TypedIdentifierOrAssignee::TypedIdentifier(i) => { - let declaration = absy::Statement::Declaration( - absy::Variable::new( - i.identifier.span.as_str(), - absy::UnresolvedTypeNode::from(i.ty), - ) - .span(i.identifier.span.clone()), - ) - .span(definition.span.clone()); - - let s = match e.value { - absy::Expression::FunctionCall(..) => absy::Statement::MultipleDefinition( - vec![absy::AssigneeNode::from(i.identifier.clone())], - e, - ), - _ => absy::Statement::Definition( - absy::AssigneeNode::from(i.identifier.clone()), - e, - ), - }; - - vec![declaration, s.span(definition.span)] - } - pest::TypedIdentifierOrAssignee::Assignee(a) => { - let s = match e.value { - absy::Expression::FunctionCall(..) => absy::Statement::MultipleDefinition( - vec![absy::AssigneeNode::from(a)], - e, - ), - _ => absy::Statement::Definition(absy::AssigneeNode::from(a), e), - }; - - vec![s.span(definition.span)] - } - } - } - _ => { - // Multidefinition - let declarations = lhs.clone().into_iter().filter_map(|i| match i { - pest::TypedIdentifierOrAssignee::TypedIdentifier(i) => { - let ty = i.ty; - let id = i.identifier; - - Some( - absy::Statement::Declaration( - absy::Variable::new( - id.span.as_str(), - absy::UnresolvedTypeNode::from(ty), - ) - .span(id.span), - ) - .span(i.span), - ) - } - _ => None, - }); - - let lhs = lhs - .into_iter() - .map(|i| match i { - pest::TypedIdentifierOrAssignee::TypedIdentifier(i) => { - absy::Assignee::Identifier(i.identifier.span.as_str()) - .span(i.identifier.span) - } - pest::TypedIdentifierOrAssignee::Assignee(a) => absy::AssigneeNode::from(a), - }) - .collect(); - - let multi_def = absy::Statement::MultipleDefinition( - lhs, - absy::ExpressionNode::from(definition.expression), - ) - .span(definition.span); - - declarations.chain(std::iter::once(multi_def)).collect() - } - } -} - -impl<'ast> From> for absy::StatementNode<'ast> { - fn from(statement: pest::ReturnStatement<'ast>) -> absy::StatementNode<'ast> { - use crate::absy::NodeValue; - - absy::Statement::Return( - absy::ExpressionList { - expressions: statement - .expressions - .into_iter() - .map(absy::ExpressionNode::from) - .collect(), - } - .span(statement.span.clone()), - ) - .span(statement.span) - } -} - -impl<'ast> From> for absy::StatementNode<'ast> { - fn from(statement: pest::AssertionStatement<'ast>) -> absy::StatementNode<'ast> { - use crate::absy::NodeValue; - - absy::Statement::Assertion( - absy::ExpressionNode::from(statement.expression), - statement.message.map(|m| m.value), - ) - .span(statement.span) - } -} - -impl<'ast> From> for absy::StatementNode<'ast> { - fn from(statement: pest::IterationStatement<'ast>) -> absy::StatementNode<'ast> { - use crate::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 - .statements - .into_iter() - .flat_map(statements_from_statement) - .collect(); - - let var = absy::Variable::new(index, ty).span(statement.index.span); - - absy::Statement::For(var, from, to, statements).span(statement.span) - } -} - -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), - pest::Expression::IfElse(e) => absy::ExpressionNode::from(e), - pest::Expression::Literal(e) => absy::ExpressionNode::from(e), - pest::Expression::Identifier(e) => absy::ExpressionNode::from(e), - pest::Expression::Postfix(e) => absy::ExpressionNode::from(e), - pest::Expression::InlineArray(e) => absy::ExpressionNode::from(e), - pest::Expression::InlineTuple(e) => absy::ExpressionNode::from(e), - pest::Expression::InlineStruct(e) => absy::ExpressionNode::from(e), - pest::Expression::ArrayInitializer(e) => absy::ExpressionNode::from(e), - pest::Expression::Unary(e) => absy::ExpressionNode::from(e), - } - } -} - -impl<'ast> From> for absy::ExpressionNode<'ast> { - fn from(expression: pest::BinaryExpression<'ast>) -> absy::ExpressionNode<'ast> { - use crate::absy::NodeValue; - match expression.op { - pest::BinaryOperator::Add => absy::Expression::Add( - box absy::ExpressionNode::from(*expression.left), - box absy::ExpressionNode::from(*expression.right), - ), - pest::BinaryOperator::Sub => absy::Expression::Sub( - box absy::ExpressionNode::from(*expression.left), - box absy::ExpressionNode::from(*expression.right), - ), - pest::BinaryOperator::Mul => absy::Expression::Mult( - box absy::ExpressionNode::from(*expression.left), - box absy::ExpressionNode::from(*expression.right), - ), - pest::BinaryOperator::Div => absy::Expression::Div( - box absy::ExpressionNode::from(*expression.left), - box absy::ExpressionNode::from(*expression.right), - ), - pest::BinaryOperator::Rem => absy::Expression::Rem( - box absy::ExpressionNode::from(*expression.left), - box absy::ExpressionNode::from(*expression.right), - ), - pest::BinaryOperator::Eq => absy::Expression::Eq( - box absy::ExpressionNode::from(*expression.left), - box absy::ExpressionNode::from(*expression.right), - ), - pest::BinaryOperator::Lt => absy::Expression::Lt( - box absy::ExpressionNode::from(*expression.left), - box absy::ExpressionNode::from(*expression.right), - ), - pest::BinaryOperator::Lte => absy::Expression::Le( - box absy::ExpressionNode::from(*expression.left), - box absy::ExpressionNode::from(*expression.right), - ), - pest::BinaryOperator::Gt => absy::Expression::Gt( - box absy::ExpressionNode::from(*expression.left), - box absy::ExpressionNode::from(*expression.right), - ), - pest::BinaryOperator::Gte => absy::Expression::Ge( - box absy::ExpressionNode::from(*expression.left), - box absy::ExpressionNode::from(*expression.right), - ), - pest::BinaryOperator::And => absy::Expression::And( - box absy::ExpressionNode::from(*expression.left), - box absy::ExpressionNode::from(*expression.right), - ), - pest::BinaryOperator::Or => absy::Expression::Or( - box absy::ExpressionNode::from(*expression.left), - box absy::ExpressionNode::from(*expression.right), - ), - pest::BinaryOperator::Pow => absy::Expression::Pow( - box absy::ExpressionNode::from(*expression.left), - box absy::ExpressionNode::from(*expression.right), - ), - pest::BinaryOperator::BitXor => absy::Expression::BitXor( - box absy::ExpressionNode::from(*expression.left), - box absy::ExpressionNode::from(*expression.right), - ), - pest::BinaryOperator::LeftShift => absy::Expression::LeftShift( - box absy::ExpressionNode::from(*expression.left), - box absy::ExpressionNode::from(*expression.right), - ), - pest::BinaryOperator::RightShift => absy::Expression::RightShift( - box absy::ExpressionNode::from(*expression.left), - box absy::ExpressionNode::from(*expression.right), - ), - pest::BinaryOperator::BitAnd => absy::Expression::BitAnd( - box absy::ExpressionNode::from(*expression.left), - box absy::ExpressionNode::from(*expression.right), - ), - pest::BinaryOperator::BitOr => absy::Expression::BitOr( - box absy::ExpressionNode::from(*expression.left), - box absy::ExpressionNode::from(*expression.right), - ), - // rewrite (a != b)` as `!(a == b)` - pest::BinaryOperator::NotEq => absy::Expression::Not( - box absy::Expression::Eq( - box absy::ExpressionNode::from(*expression.left), - box absy::ExpressionNode::from(*expression.right), - ) - .span(expression.span.clone()), - ), - } - .span(expression.span) - } -} - -impl<'ast> From> for absy::ExpressionNode<'ast> { - fn from(expression: pest::IfElseExpression<'ast>) -> absy::ExpressionNode<'ast> { - use crate::absy::NodeValue; - absy::Expression::Conditional( - box absy::ExpressionNode::from(*expression.condition), - box absy::ExpressionNode::from(*expression.consequence), - box absy::ExpressionNode::from(*expression.alternative), - absy::ConditionalKind::IfElse, - ) - .span(expression.span) - } -} - -impl<'ast> From> for absy::ExpressionNode<'ast> { - fn from(expression: pest::TernaryExpression<'ast>) -> absy::ExpressionNode<'ast> { - use crate::absy::NodeValue; - absy::Expression::Conditional( - box absy::ExpressionNode::from(*expression.condition), - box absy::ExpressionNode::from(*expression.consequence), - box absy::ExpressionNode::from(*expression.alternative), - absy::ConditionalKind::Ternary, - ) - .span(expression.span) - } -} - -impl<'ast> From> for absy::SpreadNode<'ast> { - fn from(spread: pest::Spread<'ast>) -> absy::SpreadNode<'ast> { - use crate::absy::NodeValue; - absy::Spread { - expression: absy::ExpressionNode::from(spread.expression), - } - .span(spread.span) - } -} - -impl<'ast> From> for absy::RangeNode<'ast> { - fn from(range: pest::Range<'ast>) -> absy::RangeNode<'ast> { - use crate::absy::NodeValue; - - let from = range.from.map(|e| absy::ExpressionNode::from(e.0)); - - let to = range.to.map(|e| absy::ExpressionNode::from(e.0)); - - absy::Range { from, to }.span(range.span) - } -} - -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)) - } - pest::RangeOrExpression::Range(r) => { - absy::RangeOrExpression::Range(absy::RangeNode::from(r)) - } - } - } -} - -impl<'ast> From> for absy::SpreadOrExpression<'ast> { - fn from( - spread_or_expression: pest::SpreadOrExpression<'ast>, - ) -> absy::SpreadOrExpression<'ast> { - match spread_or_expression { - pest::SpreadOrExpression::Expression(e) => { - absy::SpreadOrExpression::Expression(absy::ExpressionNode::from(e)) - } - pest::SpreadOrExpression::Spread(s) => { - absy::SpreadOrExpression::Spread(absy::SpreadNode::from(s)) - } - } - } -} - -impl<'ast> From> for absy::ExpressionNode<'ast> { - fn from(array: pest::InlineArrayExpression<'ast>) -> absy::ExpressionNode<'ast> { - use crate::absy::NodeValue; - absy::Expression::InlineArray( - array - .expressions - .into_iter() - .map(absy::SpreadOrExpression::from) - .collect(), - ) - .span(array.span) - } -} - -impl<'ast> From> for absy::ExpressionNode<'ast> { - fn from(tuple: pest::InlineTupleExpression<'ast>) -> absy::ExpressionNode<'ast> { - use crate::absy::NodeValue; - absy::Expression::InlineTuple( - tuple - .elements - .into_iter() - .map(absy::ExpressionNode::from) - .collect(), - ) - .span(tuple.span) - } -} - -impl<'ast> From> for absy::ExpressionNode<'ast> { - fn from(s: pest::InlineStructExpression<'ast>) -> absy::ExpressionNode<'ast> { - use crate::absy::NodeValue; - absy::Expression::InlineStruct( - s.ty.span.as_str().to_string(), - s.members - .into_iter() - .map(|member| { - ( - member.id.span.as_str(), - absy::ExpressionNode::from(member.expression), - ) - }) - .collect(), - ) - .span(s.span) - } -} - -impl<'ast> From> for absy::ExpressionNode<'ast> { - fn from(initializer: pest::ArrayInitializerExpression<'ast>) -> absy::ExpressionNode<'ast> { - use crate::absy::NodeValue; - - let value = absy::ExpressionNode::from(*initializer.value); - let count = absy::ExpressionNode::from(*initializer.count); - absy::Expression::ArrayInitializer(box value, box count).span(initializer.span) - } -} - -impl<'ast> From> for absy::ExpressionNode<'ast> { - fn from(unary: pest::UnaryExpression<'ast>) -> absy::ExpressionNode<'ast> { - use crate::absy::NodeValue; - - let expression = Box::new(absy::ExpressionNode::from(*unary.expression)); - - match unary.op { - pest::UnaryOperator::Not(..) => absy::Expression::Not(expression), - pest::UnaryOperator::Neg(..) => absy::Expression::Neg(expression), - pest::UnaryOperator::Pos(..) => absy::Expression::Pos(expression), - } - .span(unary.span) - } -} - -impl<'ast> From> for absy::ExpressionNode<'ast> { - fn from(expression: pest::PostfixExpression<'ast>) -> absy::ExpressionNode<'ast> { - use crate::absy::NodeValue; - - let base = absy::ExpressionNode::from(*expression.base); - - // pest::PostFixExpression contains an array of "accesses": `a(34)[42]` is represented as `[a, [Call(34), Select(42)]]`, but absy::ExpressionNode - // is recursive, so it is `Select(Call(a, 34), 42)`. We apply this transformation here - // we start with the base, and we fold the array of accesses by wrapping the current value - expression - .accesses - .into_iter() - .fold(base, |acc, a| match a { - pest::Access::Call(a) => absy::Expression::FunctionCall( - Box::new(acc), - a.explicit_generics.map(|explicit_generics| { - explicit_generics - .values - .into_iter() - .map(|i| match i { - pest::ConstantGenericValue::Underscore(_) => None, - pest::ConstantGenericValue::Value(v) => { - Some(absy::ExpressionNode::from(v)) - } - pest::ConstantGenericValue::Identifier(i) => { - Some(absy::Expression::Identifier(i.span.as_str()).span(i.span)) - } - }) - .collect() - }), - a.arguments - .expressions - .into_iter() - .map(absy::ExpressionNode::from) - .collect(), - ) - .span(a.span), - pest::Access::Select(a) => absy::Expression::Select( - box acc, - box absy::RangeOrExpression::from(a.expression), - ) - .span(a.span), - pest::Access::Dot(m) => match m.inner { - pest::IdentifierOrDecimal::Identifier(id) => { - absy::Expression::Member(box acc, box id.span.as_str()).span(m.span) - } - pest::IdentifierOrDecimal::Decimal(id) => { - absy::Expression::Element(box acc, id.span.as_str().parse().unwrap()) - .span(m.span) - } - }, - }) - } -} - -impl<'ast> From> for absy::ExpressionNode<'ast> { - fn from(expression: pest::DecimalLiteralExpression<'ast>) -> absy::ExpressionNode<'ast> { - use crate::absy::NodeValue; - - match expression.suffix { - Some(suffix) => match suffix { - pest::DecimalSuffix::Field(_) => absy::Expression::FieldConstant( - BigUint::parse_bytes(expression.value.span.as_str().as_bytes(), 10).unwrap(), - ), - pest::DecimalSuffix::U64(_) => { - absy::Expression::U64Constant(expression.value.span.as_str().parse().unwrap()) - } - pest::DecimalSuffix::U32(_) => { - absy::Expression::U32Constant(expression.value.span.as_str().parse().unwrap()) - } - pest::DecimalSuffix::U16(_) => { - absy::Expression::U16Constant(expression.value.span.as_str().parse().unwrap()) - } - pest::DecimalSuffix::U8(_) => { - absy::Expression::U8Constant(expression.value.span.as_str().parse().unwrap()) - } - } - .span(expression.span), - None => absy::Expression::IntConstant( - BigUint::parse_bytes(expression.value.span.as_str().as_bytes(), 10).unwrap(), - ) - .span(expression.span), - } - } -} - -impl<'ast> From> for absy::ExpressionNode<'ast> { - fn from(expression: pest::HexLiteralExpression<'ast>) -> absy::ExpressionNode<'ast> { - use crate::absy::NodeValue; - - match expression.value { - pest::HexNumberExpression::U64(e) => { - absy::Expression::U64Constant(u64::from_str_radix(e.span.as_str(), 16).unwrap()) - } - pest::HexNumberExpression::U32(e) => { - absy::Expression::U32Constant(u32::from_str_radix(e.span.as_str(), 16).unwrap()) - } - pest::HexNumberExpression::U16(e) => { - absy::Expression::U16Constant(u16::from_str_radix(e.span.as_str(), 16).unwrap()) - } - pest::HexNumberExpression::U8(e) => { - absy::Expression::U8Constant(u8::from_str_radix(e.span.as_str(), 16).unwrap()) - } - } - .span(expression.span) - } -} - -impl<'ast> From> for absy::ExpressionNode<'ast> { - fn from(expression: pest::LiteralExpression<'ast>) -> absy::ExpressionNode<'ast> { - use crate::absy::NodeValue; - - match expression { - pest::LiteralExpression::BooleanLiteral(c) => { - absy::Expression::BooleanConstant(c.value.parse().unwrap()).span(c.span) - } - pest::LiteralExpression::DecimalLiteral(n) => absy::ExpressionNode::from(n), - pest::LiteralExpression::HexLiteral(n) => absy::ExpressionNode::from(n), - } - } -} - -impl<'ast> From> for absy::ExpressionNode<'ast> { - fn from(expression: pest::IdentifierExpression<'ast>) -> absy::ExpressionNode<'ast> { - use crate::absy::NodeValue; - absy::Expression::Identifier(expression.span.as_str()).span(expression.span) - } -} - -impl<'ast> From> for absy::AssigneeNode<'ast> { - fn from(expression: pest::IdentifierExpression<'ast>) -> absy::AssigneeNode<'ast> { - use crate::absy::NodeValue; - - absy::Assignee::Identifier(expression.span.as_str()).span(expression.span) - } -} - -impl<'ast> From> for absy::AssigneeNode<'ast> { - fn from(assignee: pest::Assignee<'ast>) -> absy::AssigneeNode<'ast> { - use crate::absy::NodeValue; - - let a = absy::AssigneeNode::from(assignee.id); - let span = assignee.span; - - assignee.accesses.into_iter().fold(a, |acc, s| { - match s { - pest::AssigneeAccess::Select(s) => { - absy::Assignee::Select(box acc, box absy::RangeOrExpression::from(s.expression)) - } - pest::AssigneeAccess::Dot(a) => match a.inner { - pest::IdentifierOrDecimal::Identifier(id) => { - absy::Assignee::Member(box acc, box id.span.as_str()) - } - pest::IdentifierOrDecimal::Decimal(id) => { - absy::Assignee::Element(box acc, id.span.as_str().parse().unwrap()) - } - }, - } - .span(span.clone()) - }) - } -} - -impl<'ast> From> for absy::UnresolvedTypeNode<'ast> { - fn from(t: pest::Type<'ast>) -> absy::UnresolvedTypeNode<'ast> { - use crate::absy::types::UnresolvedType; - use crate::absy::NodeValue; - - match t { - pest::Type::Basic(t) => match t { - 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::BasicType::U64(t) => UnresolvedType::Uint(64).span(t.span), - }, - pest::Type::Array(t) => { - let inner_type = match t.ty { - pest::BasicOrStructOrTupleType::Basic(t) => match t { - 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::BasicType::U64(t) => UnresolvedType::Uint(64).span(t.span), - }, - pest::BasicOrStructOrTupleType::Struct(t) => UnresolvedType::User( - t.id.span.as_str().to_string(), - t.explicit_generics.map(|explicit_generics| { - explicit_generics - .values - .into_iter() - .map(|i| match i { - pest::ConstantGenericValue::Underscore(_) => None, - pest::ConstantGenericValue::Value(v) => { - Some(absy::ExpressionNode::from(v)) - } - pest::ConstantGenericValue::Identifier(i) => Some( - absy::Expression::Identifier(i.span.as_str()).span(i.span), - ), - }) - .collect() - }), - ) - .span(t.span), - pest::BasicOrStructOrTupleType::Tuple(t) => UnresolvedType::Tuple( - t.elements - .into_iter() - .map(absy::UnresolvedTypeNode::from) - .collect(), - ) - .span(t.span), - }; - - let span = t.span; - - t.dimensions - .into_iter() - .map(absy::ExpressionNode::from) - .rev() - .fold(None, |acc, s| match acc { - 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) => UnresolvedType::User( - s.id.span.as_str().to_string(), - s.explicit_generics.map(|explicit_generics| { - explicit_generics - .values - .into_iter() - .map(|i| match i { - pest::ConstantGenericValue::Underscore(_) => None, - pest::ConstantGenericValue::Value(v) => { - Some(absy::ExpressionNode::from(v)) - } - pest::ConstantGenericValue::Identifier(i) => { - Some(absy::Expression::Identifier(i.span.as_str()).span(i.span)) - } - }) - .collect() - }), - ) - .span(s.span), - pest::Type::Tuple(t) => UnresolvedType::Tuple( - t.elements - .into_iter() - .map(absy::UnresolvedTypeNode::from) - .collect(), - ) - .span(t.span), - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::absy::types::{UnresolvedSignature, UnresolvedType}; - use crate::absy::NodeValue; - - #[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 { - symbols: vec![absy::SymbolDeclaration { - id: &source[4..8], - symbol: absy::Symbol::Here(absy::SymbolDefinition::Function( - absy::Function { - arguments: vec![], - statements: vec![absy::Statement::Return( - absy::ExpressionList { - expressions: vec![ - absy::Expression::IntConstant(42usize.into()).into() - ], - } - .into(), - ) - .into()], - signature: UnresolvedSignature::new() - .inputs(vec![]) - .outputs(vec![UnresolvedType::FieldElement.mock()]), - } - .into(), - )), - } - .into()], - }; - 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 { - symbols: vec![absy::SymbolDeclaration { - id: &source[4..8], - symbol: absy::Symbol::Here(absy::SymbolDefinition::Function( - absy::Function { - arguments: vec![], - statements: vec![absy::Statement::Return( - absy::ExpressionList { - expressions: vec![absy::Expression::BooleanConstant(true).into()], - } - .into(), - ) - .into()], - signature: UnresolvedSignature::new() - .inputs(vec![]) - .outputs(vec![UnresolvedType::Boolean.mock()]), - } - .into(), - )), - } - .into()], - }; - assert_eq!(absy::Module::from(ast), expected); - } - - #[test] - fn arguments() { - 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 { - symbols: vec![absy::SymbolDeclaration { - id: &source[4..8], - symbol: absy::Symbol::Here(absy::SymbolDefinition::Function( - absy::Function { - arguments: vec![ - absy::Parameter::private( - absy::Variable::new( - &source[23..24], - UnresolvedType::FieldElement.mock(), - ) - .into(), - ) - .into(), - absy::Parameter::public( - absy::Variable::new( - &source[31..32], - UnresolvedType::Boolean.mock(), - ) - .into(), - ) - .into(), - ], - statements: vec![absy::Statement::Return( - absy::ExpressionList { - expressions: vec![ - absy::Expression::IntConstant(42usize.into()).into() - ], - } - .into(), - ) - .into()], - signature: UnresolvedSignature::new() - .inputs(vec![ - UnresolvedType::FieldElement.mock(), - UnresolvedType::Boolean.mock(), - ]) - .outputs(vec![UnresolvedType::FieldElement.mock()]), - } - .into(), - )), - } - .into()], - }; - - 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: UnresolvedType<'static>) -> absy::Module<'static> { - absy::Module { - symbols: vec![absy::SymbolDeclaration { - id: "main", - symbol: absy::Symbol::Here(absy::SymbolDefinition::Function( - absy::Function { - arguments: vec![absy::Parameter::private( - absy::Variable::new("a", ty.clone().mock()).into(), - ) - .into()], - statements: vec![absy::Statement::Return( - absy::ExpressionList { - expressions: vec![], - } - .into(), - ) - .into()], - signature: UnresolvedSignature::new().inputs(vec![ty.mock()]), - } - .into(), - )), - } - .into()], - } - } - - #[test] - fn array() { - let vectors = vec![ - ("field", UnresolvedType::FieldElement), - ("bool", UnresolvedType::Boolean), - ( - "field[2]", - absy::UnresolvedType::Array( - box absy::UnresolvedType::FieldElement.mock(), - absy::Expression::IntConstant(2usize.into()).mock(), - ), - ), - ( - "field[2][3]", - absy::UnresolvedType::Array( - box absy::UnresolvedType::Array( - box absy::UnresolvedType::FieldElement.mock(), - absy::Expression::IntConstant(3usize.into()).mock(), - ) - .mock(), - absy::Expression::IntConstant(2usize.into()).mock(), - ), - ), - ( - "bool[2][3u32]", - absy::UnresolvedType::Array( - box absy::UnresolvedType::Array( - box absy::UnresolvedType::Boolean.mock(), - absy::Expression::U32Constant(3u32).mock(), - ) - .mock(), - absy::Expression::IntConstant(2usize.into()).mock(), - ), - ), - ]; - - for (ty, expected) in vectors { - 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); - } - } - } - - mod postfix { - use super::*; - fn wrap(expression: absy::Expression<'static>) -> absy::Module { - absy::Module { - symbols: vec![absy::SymbolDeclaration { - id: "main", - symbol: absy::Symbol::Here(absy::SymbolDefinition::Function( - absy::Function { - arguments: vec![], - statements: vec![absy::Statement::Return( - absy::ExpressionList { - expressions: vec![expression.into()], - } - .into(), - ) - .into()], - signature: UnresolvedSignature::new(), - } - .into(), - )), - } - .into()], - } - } - - #[test] - fn success() { - // we basically accept `()?[]*` : an optional call at first, then only array accesses - - let vectors = vec![ - ("a", absy::Expression::Identifier("a")), - ( - "a[3]", - absy::Expression::Select( - box absy::Expression::Identifier("a").into(), - box absy::RangeOrExpression::Expression( - absy::Expression::IntConstant(3usize.into()).into(), - ), - ), - ), - ( - "a[3][4]", - absy::Expression::Select( - box absy::Expression::Select( - box absy::Expression::Identifier("a").into(), - box absy::RangeOrExpression::Expression( - absy::Expression::IntConstant(3usize.into()).into(), - ), - ) - .into(), - box absy::RangeOrExpression::Expression( - absy::Expression::IntConstant(4usize.into()).into(), - ), - ), - ), - ( - "a(3)[4]", - absy::Expression::Select( - box absy::Expression::FunctionCall( - box absy::Expression::Identifier("a").mock(), - None, - vec![absy::Expression::IntConstant(3usize.into()).into()], - ) - .into(), - box absy::RangeOrExpression::Expression( - absy::Expression::IntConstant(4usize.into()).into(), - ), - ), - ), - ( - "a(3)[4][5]", - absy::Expression::Select( - box absy::Expression::Select( - box absy::Expression::FunctionCall( - box absy::Expression::Identifier("a").mock(), - None, - vec![absy::Expression::IntConstant(3usize.into()).into()], - ) - .into(), - box absy::RangeOrExpression::Expression( - absy::Expression::IntConstant(4usize.into()).into(), - ), - ) - .into(), - box absy::RangeOrExpression::Expression( - absy::Expression::IntConstant(5usize.into()).into(), - ), - ), - ), - ]; - - for (source, expected) in vectors { - 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); - } - } - - #[test] - fn call_array_element() { - // a call after an array access should be accepted - let source = "def main(): return a[2](3)"; - let ast = pest::generate_ast(source).unwrap(); - assert_eq!( - absy::Module::from(ast), - wrap(absy::Expression::FunctionCall( - box absy::Expression::Select( - box absy::Expression::Identifier("a").mock(), - box absy::RangeOrExpression::Expression( - absy::Expression::IntConstant(2u32.into()).mock() - ) - ) - .mock(), - None, - vec![absy::Expression::IntConstant(3u32.into()).mock()], - )) - ); - } - - #[test] - fn call_call_result() { - // a call after a call should be accepted - let source = "def main(): return a(2)(3)"; - - let ast = pest::generate_ast(source).unwrap(); - assert_eq!( - absy::Module::from(ast), - wrap(absy::Expression::FunctionCall( - box absy::Expression::FunctionCall( - box absy::Expression::Identifier("a").mock(), - None, - vec![absy::Expression::IntConstant(2u32.into()).mock()] - ) - .mock(), - None, - vec![absy::Expression::IntConstant(3u32.into()).mock()], - )) - ); - } - } - #[test] - fn declarations() { - use self::pest::Span; - - let span = Span::new("", 0, 0).unwrap(); - - // For different definitions, we generate declarations - // Case 1: `id = expr` where `expr` is not a function call - // This is a simple assignment, doesn't implicitely declare a variable - // A `Definition` is generated and no `Declaration`s - - let definition = pest::DefinitionStatement { - lhs: vec![pest::TypedIdentifierOrAssignee::Assignee(pest::Assignee { - id: pest::IdentifierExpression { - value: String::from("a"), - span: span.clone(), - }, - accesses: vec![], - span: span.clone(), - })], - expression: pest::Expression::Literal(pest::LiteralExpression::DecimalLiteral( - pest::DecimalLiteralExpression { - value: pest::DecimalNumber { - span: Span::new("1", 0, 1).unwrap(), - }, - suffix: None, - span: span.clone(), - }, - )), - span: span.clone(), - }; - - let statements: Vec = statements_from_definition(definition); - - assert_eq!(statements.len(), 1); - match &statements[0].value { - absy::Statement::Definition(..) => {} - s => { - panic!("should be a Definition, found {}", s); - } - }; - - // Case 2: `id = expr` where `expr` is a function call - // A MultiDef is generated - - let definition = pest::DefinitionStatement { - lhs: vec![pest::TypedIdentifierOrAssignee::Assignee(pest::Assignee { - id: pest::IdentifierExpression { - value: String::from("a"), - span: span.clone(), - }, - accesses: vec![], - span: span.clone(), - })], - expression: pest::Expression::Postfix(pest::PostfixExpression { - base: box pest::Expression::Identifier(pest::IdentifierExpression { - value: String::from("foo"), - span: span.clone(), - }), - accesses: vec![pest::Access::Call(pest::CallAccess { - explicit_generics: None, - arguments: pest::Arguments { - expressions: vec![], - span: span.clone(), - }, - span: span.clone(), - })], - span: span.clone(), - }), - span: span.clone(), - }; - - let statements: Vec = statements_from_definition(definition); - - assert_eq!(statements.len(), 1); - match &statements[0].value { - absy::Statement::MultipleDefinition(..) => {} - s => { - panic!("should be a Definition, found {}", s); - } - }; - // Case 3: `ids = expr` where `expr` is a function call - // This implicitely declares all variables which are type annotated - - // `field a, b = foo()` - - let definition = pest::DefinitionStatement { - lhs: vec![ - pest::TypedIdentifierOrAssignee::TypedIdentifier(pest::TypedIdentifier { - ty: pest::Type::Basic(pest::BasicType::Field(pest::FieldType { - span: span.clone(), - })), - identifier: pest::IdentifierExpression { - value: String::from("a"), - span: span.clone(), - }, - span: span.clone(), - }), - pest::TypedIdentifierOrAssignee::Assignee(pest::Assignee { - id: pest::IdentifierExpression { - value: String::from("b"), - span: span.clone(), - }, - accesses: vec![], - span: span.clone(), - }), - ], - expression: pest::Expression::Postfix(pest::PostfixExpression { - base: box pest::Expression::Identifier(pest::IdentifierExpression { - value: String::from("foo"), - span: span.clone(), - }), - accesses: vec![pest::Access::Call(pest::CallAccess { - explicit_generics: None, - arguments: pest::Arguments { - expressions: vec![], - span: span.clone(), - }, - span: span.clone(), - })], - span: span.clone(), - }), - span: span.clone(), - }; - - let statements: Vec = statements_from_definition(definition); - - assert_eq!(statements.len(), 2); - match &statements[1].value { - absy::Statement::MultipleDefinition(..) => {} - s => { - panic!("should be a Definition, found {}", s); - } - }; - } -} diff --git a/zokrates_core/src/compile.rs b/zokrates_core/src/compile.rs index f8804bbf..f7986766 100644 --- a/zokrates_core/src/compile.rs +++ b/zokrates_core/src/compile.rs @@ -6,7 +6,6 @@ use crate::absy::{Module, OwnedModuleId, Program}; use crate::flatten::FlattenerIterator; use crate::imports::{self, Importer}; -use crate::ir; use crate::macros; use crate::semantics::{self, Checker}; use crate::static_analysis; @@ -19,6 +18,7 @@ use std::fmt; use std::io; use std::path::{Path, PathBuf}; use typed_arena::Arena; +use zokrates_ast::ir; use zokrates_common::Resolver; use zokrates_field::Field; use zokrates_pest_ast as pest; @@ -204,7 +204,8 @@ pub fn compile<'ast, T: Field, E: Into>( // convert to ir log::debug!("Convert to IR"); - let ir_prog = ir::from_flat::from_flat(program_flattened); + //let ir_prog = ir::from_flat::from_flat(program_flattened); + let ir_prog = unimplemented!(); // optimize log::debug!("Optimise IR"); diff --git a/zokrates_core/src/flatten/mod.rs b/zokrates_core/src/flatten/mod.rs index 64fc11b5..a724825b 100644 --- a/zokrates_core/src/flatten/mod.rs +++ b/zokrates_core/src/flatten/mod.rs @@ -8,19 +8,26 @@ mod utils; use self::utils::flat_expression_from_bits; -use crate::ir::Interpreter; +use zokrates_ast::zir::{ShouldReduce, UMetadata, ZirExpressionList}; +use zokrates_interpreter::Interpreter; use crate::compile::CompileConfig; -use crate::embed::FlatEmbed; -use crate::flat_absy::{RuntimeError, *}; -use crate::solvers::Solver; +use crate::flat_absy::*; use crate::zir::types::{Type, UBitwidth}; -use crate::zir::*; +use crate::zir::{ + BooleanExpression, FieldElementExpression, Identifier, IfElse, Parameter as ZirParameter, + UExpression, UExpressionInner, Variable as ZirVariable, ZirExpression, ZirFunction, + ZirStatement, +}; use std::collections::{ hash_map::{Entry, HashMap}, VecDeque, }; use std::convert::TryFrom; +use zokrates_ast::common::embed::*; +use zokrates_ast::common::FlatEmbed; +use zokrates_ast::common::{RuntimeError, Variable}; +use zokrates_ast::ir::Solver; use zokrates_field::Field; type FlatStatements = VecDeque>; @@ -29,26 +36,27 @@ type FlatStatements = VecDeque>; /// /// # Arguments /// * `funct` - `ZirFunction` that will be flattened -impl<'ast, T: Field> FlattenerIterator<'ast, T> { - pub fn from_function_and_config(funct: ZirFunction<'ast, T>, config: CompileConfig) -> Self { - let mut flattener = Flattener::new(config); - let mut statements_flattened = FlatStatements::new(); - // push parameters - let arguments_flattened = funct - .arguments - .into_iter() - .map(|p| flattener.use_parameter(&p, &mut statements_flattened)) - .collect(); +pub fn from_function_and_config<'ast, T: Field>( + funct: ZirFunction<'ast, T>, + config: CompileConfig, +) -> FlattenerIterator<'ast, T> { + let mut flattener = Flattener::new(config); + let mut statements_flattened = FlatStatements::new(); + // push parameters + let arguments_flattened = funct + .arguments + .into_iter() + .map(|p| flattener.use_parameter(&p, &mut statements_flattened)) + .collect(); - FlattenerIterator { - arguments: arguments_flattened, - statements: FlattenerIteratorInner { - statements: funct.statements.into(), - statements_flattened, - flattener, - }, - return_count: funct.signature.outputs.len(), - } + FlattenerIterator { + arguments: arguments_flattened, + statements: FlattenerIteratorInner { + statements: funct.statements.into(), + statements_flattened, + flattener, + }, + return_count: funct.signature.outputs.len(), } } @@ -85,8 +93,8 @@ pub struct Flattener<'ast, T> { config: CompileConfig, /// Index of the next introduced variable while processing the program. next_var_idx: usize, - /// `FlatVariable`s corresponding to each `Identifier` - layout: HashMap, FlatVariable>, + /// `Variable`s corresponding to each `Identifier` + layout: HashMap, Variable>, /// Cached bit decompositions to avoid re-generating them bits_cache: HashMap, Vec>>, } @@ -200,14 +208,14 @@ impl FlatUExpression { } } -impl From for RuntimeError { - fn from(error: crate::zir::RuntimeError) -> Self { - match error { - crate::zir::RuntimeError::SourceAssertion(s) => RuntimeError::SourceAssertion(s), - crate::zir::RuntimeError::SelectRangeCheck => RuntimeError::SelectRangeCheck, - } - } -} +// impl From for RuntimeError { +// fn from(error: crate::zir::RuntimeError) -> Self { +// match error { +// crate::zir::RuntimeError::SourceAssertion(s) => RuntimeError::SourceAssertion(s), +// crate::zir::RuntimeError::SelectRangeCheck => RuntimeError::SelectRangeCheck, +// } +// } +// } impl<'ast, T: Field> Flattener<'ast, T> { /// Returns a `Flattener` with fresh `layout`. @@ -225,7 +233,7 @@ impl<'ast, T: Field> Flattener<'ast, T> { &mut self, e: FlatExpression, statements_flattened: &mut FlatStatements, - ) -> FlatVariable { + ) -> Variable { match e { FlatExpression::Identifier(id) => id, e => { @@ -774,7 +782,7 @@ impl<'ast, T: Field> Flattener<'ast, T> { let sub_width = bit_width + 1; // define variables for the bits - let shifted_sub_bits_be: Vec = + let shifted_sub_bits_be: Vec = (0..sub_width).map(|_| self.use_sym()).collect(); // add a directive to get the bits @@ -1160,19 +1168,17 @@ impl<'ast, T: Field> Flattener<'ast, T> { FlatEmbed::Unpack => self.flatten_embed_call_aux( statements_flattened, params, - crate::embed::unpack_to_bitwidth(generics[0] as usize), + unpack_to_bitwidth(generics[0] as usize), ), #[cfg(feature = "bellman")] - FlatEmbed::Sha256Round => self.flatten_embed_call_aux( - statements_flattened, - params, - crate::embed::sha256_round(), - ), + FlatEmbed::Sha256Round => { + self.flatten_embed_call_aux(statements_flattened, params, sha256_round()) + } #[cfg(feature = "ark")] FlatEmbed::SnarkVerifyBls12377 => self.flatten_embed_call_aux( statements_flattened, params, - crate::embed::snark_verify_bls12_377::(generics[0] as usize), + snark_verify_bls12_377::(generics[0] as usize), ), _ => unreachable!(), }, @@ -1191,7 +1197,7 @@ impl<'ast, T: Field> Flattener<'ast, T> { // Rename Parameters, assign them to values in call. Resolve complex expressions with definitions let params_flattened = params.into_iter().map(|e| e.get_field_unchecked()); - let return_values = (0..funct.return_count).map(FlatVariable::public); + let return_values = (0..funct.return_count).map(Variable::public); for (concrete_argument, formal_argument) in params_flattened.zip(funct.arguments) { let new_var = self.define(concrete_argument, statements_flattened); @@ -2315,9 +2321,10 @@ impl<'ast, T: Field> Flattener<'ast, T> { .collect(); statements_flattened.extend( - flat_expressions.into_iter().enumerate().map(|(index, e)| { - FlatStatement::Definition(FlatVariable::public(index), e) - }), + flat_expressions + .into_iter() + .enumerate() + .map(|(index, e)| FlatStatement::Definition(Variable::public(index), e)), ); } ZirStatement::IfElse(condition, consequence, alternative) => { @@ -2629,11 +2636,11 @@ impl<'ast, T: Field> Flattener<'ast, T> { } } - /// Returns a fresh FlatVariable for a given Variable + /// Returns a fresh Variable for a given Variable /// # Arguments /// /// * `variable` - a variable in the program being flattened - fn use_variable(&mut self, variable: &Variable<'ast>) -> FlatVariable { + fn use_variable(&mut self, variable: &ZirVariable<'ast>) -> Variable { let var = self.issue_new_variable(); self.layout.insert(variable.id.clone(), var); @@ -2647,17 +2654,17 @@ impl<'ast, T: Field> Flattener<'ast, T> { /// * `flat_variable` - an existing flat variable fn use_variable_with_existing( &mut self, - variable: &Variable<'ast>, - flat_variable: FlatVariable, + variable: &ZirVariable<'ast>, + flat_variable: Variable, ) { self.layout.insert(variable.id.clone(), flat_variable); } fn use_parameter( &mut self, - parameter: &Parameter<'ast>, + parameter: &ZirParameter<'ast>, statements_flattened: &mut FlatStatements, - ) -> FlatParameter { + ) -> Parameter { let variable = self.use_variable(¶meter.id); match parameter.id.get_type() { @@ -2682,20 +2689,20 @@ impl<'ast, T: Field> Flattener<'ast, T> { Type::FieldElement => {} } - FlatParameter { + Parameter { id: variable, private: parameter.private, } } - fn issue_new_variable(&mut self) -> FlatVariable { - let var = FlatVariable::new(self.next_var_idx); + fn issue_new_variable(&mut self) -> Variable { + let var = Variable::new(self.next_var_idx); self.next_var_idx += 1; var } // create an internal variable. We do not register it in the layout - fn use_sym(&mut self) -> FlatVariable { + fn use_sym(&mut self) -> Variable { self.issue_new_variable() } } @@ -2755,17 +2762,17 @@ mod tests { return_count: 0, statements: vec![ FlatStatement::Definition( - FlatVariable::new(0), + Variable::new(0), FlatExpression::Number(Bn128Field::from(1)), ), FlatStatement::Definition( - FlatVariable::new(1), + Variable::new(1), FlatExpression::Number(Bn128Field::from(1)), ), FlatStatement::Condition( - FlatExpression::Identifier(FlatVariable::new(1)), + FlatExpression::Identifier(Variable::new(1)), FlatExpression::Mult( - box FlatExpression::Identifier(FlatVariable::new(0)), + box FlatExpression::Identifier(Variable::new(0)), box FlatExpression::Number(Bn128Field::from(1)), ), zir::RuntimeError::mock().into(), @@ -2823,18 +2830,18 @@ mod tests { return_count: 0, statements: vec![ FlatStatement::Definition( - FlatVariable::new(0), + Variable::new(0), FlatExpression::Number(Bn128Field::from(1)), ), FlatStatement::Definition( - FlatVariable::new(1), + Variable::new(1), FlatExpression::Number(Bn128Field::from(2)), ), FlatStatement::Condition( - FlatExpression::Identifier(FlatVariable::new(1)), + FlatExpression::Identifier(Variable::new(1)), FlatExpression::Mult( box FlatExpression::Add( - box FlatExpression::Identifier(FlatVariable::new(0)), + box FlatExpression::Identifier(Variable::new(0)), box FlatExpression::Number(Bn128Field::from(1)), ), box FlatExpression::Number(Bn128Field::from(1)), @@ -2896,13 +2903,13 @@ mod tests { return_count: 0, statements: vec![ FlatStatement::Definition( - FlatVariable::new(0), + Variable::new(0), FlatExpression::Number(Bn128Field::from(42)), ), FlatStatement::Condition( FlatExpression::Number(Bn128Field::from(42)), FlatExpression::Mult( - box FlatExpression::Identifier(FlatVariable::new(0)), + box FlatExpression::Identifier(Variable::new(0)), box FlatExpression::Number(Bn128Field::from(1)), ), zir::RuntimeError::mock().into(), @@ -2958,17 +2965,17 @@ mod tests { return_count: 0, statements: vec![ FlatStatement::Definition( - FlatVariable::new(0), + Variable::new(0), FlatExpression::Number(Bn128Field::from(2)), ), FlatStatement::Definition( - FlatVariable::new(1), + Variable::new(1), FlatExpression::Number(Bn128Field::from(2)), ), FlatStatement::Condition( - FlatExpression::Identifier(FlatVariable::new(1)), + FlatExpression::Identifier(Variable::new(1)), FlatExpression::Mult( - box FlatExpression::Identifier(FlatVariable::new(0)), + box FlatExpression::Identifier(Variable::new(0)), box FlatExpression::Number(Bn128Field::from(1)), ), zir::RuntimeError::mock().into(), @@ -3033,22 +3040,22 @@ mod tests { return_count: 0, statements: vec![ FlatStatement::Definition( - FlatVariable::new(0), + Variable::new(0), FlatExpression::Number(Bn128Field::from(2)), ), FlatStatement::Definition( - FlatVariable::new(1), + Variable::new(1), FlatExpression::Number(Bn128Field::from(2)), ), FlatStatement::Definition( - FlatVariable::new(2), + Variable::new(2), FlatExpression::Number(Bn128Field::from(4)), ), FlatStatement::Condition( - FlatExpression::Identifier(FlatVariable::new(2)), + FlatExpression::Identifier(Variable::new(2)), FlatExpression::Mult( - box FlatExpression::Identifier(FlatVariable::new(0)), - box FlatExpression::Identifier(FlatVariable::new(1)), + box FlatExpression::Identifier(Variable::new(0)), + box FlatExpression::Identifier(Variable::new(1)), ), zir::RuntimeError::mock().into(), ), @@ -3112,22 +3119,22 @@ mod tests { return_count: 0, statements: vec![ FlatStatement::Definition( - FlatVariable::new(0), + Variable::new(0), FlatExpression::Number(Bn128Field::from(2)), ), FlatStatement::Definition( - FlatVariable::new(1), + Variable::new(1), FlatExpression::Number(Bn128Field::from(2)), ), FlatStatement::Definition( - FlatVariable::new(2), + Variable::new(2), FlatExpression::Number(Bn128Field::from(4)), ), FlatStatement::Condition( - FlatExpression::Identifier(FlatVariable::new(2)), + FlatExpression::Identifier(Variable::new(2)), FlatExpression::Mult( - box FlatExpression::Identifier(FlatVariable::new(0)), - box FlatExpression::Identifier(FlatVariable::new(1)), + box FlatExpression::Identifier(Variable::new(0)), + box FlatExpression::Identifier(Variable::new(1)), ), zir::RuntimeError::mock().into(), ), @@ -3199,33 +3206,33 @@ mod tests { return_count: 0, statements: vec![ FlatStatement::Definition( - FlatVariable::new(0), + Variable::new(0), FlatExpression::Number(Bn128Field::from(4)), ), FlatStatement::Definition( - FlatVariable::new(1), + Variable::new(1), FlatExpression::Number(Bn128Field::from(4)), ), FlatStatement::Definition( - FlatVariable::new(2), + Variable::new(2), FlatExpression::Number(Bn128Field::from(8)), ), FlatStatement::Definition( - FlatVariable::new(3), + Variable::new(3), FlatExpression::Number(Bn128Field::from(2)), ), FlatStatement::Definition( - FlatVariable::new(4), + Variable::new(4), FlatExpression::Mult( - box FlatExpression::Identifier(FlatVariable::new(2)), - box FlatExpression::Identifier(FlatVariable::new(3)), + box FlatExpression::Identifier(Variable::new(2)), + box FlatExpression::Identifier(Variable::new(3)), ), ), FlatStatement::Condition( - FlatExpression::Identifier(FlatVariable::new(4)), + FlatExpression::Identifier(Variable::new(4)), FlatExpression::Mult( - box FlatExpression::Identifier(FlatVariable::new(0)), - box FlatExpression::Identifier(FlatVariable::new(1)), + box FlatExpression::Identifier(Variable::new(0)), + box FlatExpression::Identifier(Variable::new(1)), ), zir::RuntimeError::mock().into(), ), @@ -3274,16 +3281,16 @@ mod tests { return_count: 1, statements: vec![ FlatStatement::Definition( - FlatVariable::new(0), + Variable::new(0), FlatExpression::Number(Bn128Field::from(7)), ), FlatStatement::Definition( - FlatVariable::new(1), + Variable::new(1), FlatExpression::Number(Bn128Field::from(1)), ), FlatStatement::Definition( - FlatVariable::public(0), - FlatExpression::Identifier(FlatVariable::new(1)), + Variable::public(0), + FlatExpression::Identifier(Variable::new(1)), ), ], }; @@ -3333,19 +3340,19 @@ mod tests { return_count: 1, statements: vec![ FlatStatement::Definition( - FlatVariable::new(0), + Variable::new(0), FlatExpression::Number(Bn128Field::from(7)), ), FlatStatement::Definition( - FlatVariable::new(1), + Variable::new(1), FlatExpression::Mult( box FlatExpression::Number(Bn128Field::from(1)), - box FlatExpression::Identifier(FlatVariable::new(0)), + box FlatExpression::Identifier(Variable::new(0)), ), ), FlatStatement::Definition( - FlatVariable::public(0), - FlatExpression::Identifier(FlatVariable::new(1)), + Variable::public(0), + FlatExpression::Identifier(Variable::new(1)), ), ], }; @@ -3412,54 +3419,54 @@ mod tests { return_count: 1, statements: vec![ FlatStatement::Definition( - FlatVariable::new(0), + Variable::new(0), FlatExpression::Number(Bn128Field::from(7)), ), FlatStatement::Definition( - FlatVariable::new(1), + Variable::new(1), FlatExpression::Mult( - box FlatExpression::Identifier(FlatVariable::new(0)), - box FlatExpression::Identifier(FlatVariable::new(0)), + box FlatExpression::Identifier(Variable::new(0)), + box FlatExpression::Identifier(Variable::new(0)), ), ), FlatStatement::Definition( - FlatVariable::new(2), + Variable::new(2), FlatExpression::Mult( - box FlatExpression::Identifier(FlatVariable::new(1)), - box FlatExpression::Identifier(FlatVariable::new(1)), + box FlatExpression::Identifier(Variable::new(1)), + box FlatExpression::Identifier(Variable::new(1)), ), ), FlatStatement::Definition( - FlatVariable::new(3), + Variable::new(3), FlatExpression::Mult( - box FlatExpression::Identifier(FlatVariable::new(2)), - box FlatExpression::Identifier(FlatVariable::new(2)), + box FlatExpression::Identifier(Variable::new(2)), + box FlatExpression::Identifier(Variable::new(2)), ), ), FlatStatement::Definition( - FlatVariable::new(4), + Variable::new(4), FlatExpression::Mult( box FlatExpression::Number(Bn128Field::from(1)), - box FlatExpression::Identifier(FlatVariable::new(0)), + box FlatExpression::Identifier(Variable::new(0)), ), ), FlatStatement::Definition( - FlatVariable::new(5), + Variable::new(5), FlatExpression::Mult( - box FlatExpression::Identifier(FlatVariable::new(4)), - box FlatExpression::Identifier(FlatVariable::new(2)), + box FlatExpression::Identifier(Variable::new(4)), + box FlatExpression::Identifier(Variable::new(2)), ), ), FlatStatement::Definition( - FlatVariable::new(6), + Variable::new(6), FlatExpression::Mult( - box FlatExpression::Identifier(FlatVariable::new(5)), - box FlatExpression::Identifier(FlatVariable::new(3)), + box FlatExpression::Identifier(Variable::new(5)), + box FlatExpression::Identifier(Variable::new(3)), ), ), FlatStatement::Definition( - FlatVariable::public(0), - FlatExpression::Identifier(FlatVariable::new(6)), + Variable::public(0), + FlatExpression::Identifier(Variable::new(6)), ), ], }; @@ -3556,22 +3563,22 @@ mod tests { flattener.flatten_statement(&mut statements_flattened, statement); // define b - let b = FlatVariable::new(0); + let b = Variable::new(0); // define new wires for members of Div - let five = FlatVariable::new(1); - let b0 = FlatVariable::new(2); + let five = Variable::new(1); + let b0 = Variable::new(2); // Define inverse of denominator to prevent div by 0 - let invb0 = FlatVariable::new(3); + let invb0 = Variable::new(3); // Define inverse - let sym_0 = FlatVariable::new(4); + let sym_0 = Variable::new(4); // Define result, which is first member to next Div - let sym_1 = FlatVariable::new(5); + let sym_1 = Variable::new(5); // Define second member - let b1 = FlatVariable::new(6); + let b1 = Variable::new(6); // Define inverse of denominator to prevent div by 0 - let invb1 = FlatVariable::new(7); + let invb1 = Variable::new(7); // Define inverse - let sym_2 = FlatVariable::new(8); + let sym_2 = Variable::new(8); assert_eq!( statements_flattened, diff --git a/zokrates_core/src/imports.rs b/zokrates_core/src/imports.rs index 00814b74..760bbbdc 100644 --- a/zokrates_core/src/imports.rs +++ b/zokrates_core/src/imports.rs @@ -7,8 +7,6 @@ use crate::absy::*; use crate::compile::parse_module; use crate::compile::{CompileErrorInner, CompileErrors}; -use crate::embed::FlatEmbed; -use crate::parser::Position; use std::collections::HashMap; use std::fmt; use std::io; @@ -16,6 +14,7 @@ use std::path::{Path, PathBuf}; use crate::absy::types::UnresolvedType; use typed_arena::Arena; +use zokrates_ast::common::FlatEmbed; use zokrates_common::Resolver; use zokrates_field::Field; diff --git a/zokrates_core/src/lib.rs b/zokrates_core/src/lib.rs index 955218a2..ae703cda 100644 --- a/zokrates_core/src/lib.rs +++ b/zokrates_core/src/lib.rs @@ -8,20 +8,16 @@ cfg_if::cfg_if! { } } -mod embed; mod flatten; pub mod imports; mod macros; mod optimizer; -mod parser; mod semantics; -mod solvers; mod static_analysis; -mod zir; +use zokrates_ast::zir; -pub mod absy; +pub use zokrates_ast::untyped as absy; pub mod compile; -pub mod flat_absy; -pub mod ir; +pub use zokrates_ast::flat as flat_absy; pub mod proof_system; -pub mod typed_absy; +pub use zokrates_ast::typed as typed_absy; diff --git a/zokrates_core/src/optimizer/canonicalizer.rs b/zokrates_core/src/optimizer/canonicalizer.rs index d5c6bae3..4a65bc85 100644 --- a/zokrates_core/src/optimizer/canonicalizer.rs +++ b/zokrates_core/src/optimizer/canonicalizer.rs @@ -1,4 +1,4 @@ -use crate::ir::{folder::Folder, LinComb}; +use zokrates_ast::ir::{folder::Folder, LinComb}; use zokrates_field::Field; #[derive(Default)] diff --git a/zokrates_core/src/optimizer/directive.rs b/zokrates_core/src/optimizer/directive.rs index f651c551..afabc87b 100644 --- a/zokrates_core/src/optimizer/directive.rs +++ b/zokrates_core/src/optimizer/directive.rs @@ -9,22 +9,20 @@ // c := b // ``` -use crate::flat_absy::flat_variable::FlatVariable; -use crate::ir::folder::*; -use crate::ir::*; -use crate::solvers::Solver; use std::collections::hash_map::{Entry, HashMap}; +use zokrates_ast::ir::folder::*; +use zokrates_ast::ir::*; use zokrates_field::Field; #[derive(Debug, Default)] pub struct DirectiveOptimizer { - calls: HashMap<(Solver, Vec>), Vec>, + calls: HashMap<(Solver, Vec>), Vec>, /// Map of renamings for reassigned variables while processing the program. - substitution: HashMap, + substitution: HashMap, } impl Folder for DirectiveOptimizer { - fn fold_variable(&mut self, v: FlatVariable) -> FlatVariable { + fn fold_variable(&mut self, v: Variable) -> Variable { *self.substitution.get(&v).unwrap_or(&v) } diff --git a/zokrates_core/src/optimizer/duplicate.rs b/zokrates_core/src/optimizer/duplicate.rs index 7edd2c99..ea596403 100644 --- a/zokrates_core/src/optimizer/duplicate.rs +++ b/zokrates_core/src/optimizer/duplicate.rs @@ -1,9 +1,9 @@ //! Module containing the `DuplicateOptimizer` to remove duplicate constraints -use crate::ir::folder::*; -use crate::ir::*; use crate::optimizer::canonicalizer::Canonicalizer; use std::collections::{hash_map::DefaultHasher, HashSet}; +use zokrates_ast::ir::folder::*; +use zokrates_ast::ir::*; use zokrates_field::Field; type Hash = u64; @@ -53,7 +53,7 @@ impl Folder for DuplicateOptimizer { #[cfg(test)] mod tests { use super::*; - use crate::flat_absy::FlatVariable; + use crate::flat_absy::Variable; use zokrates_field::Bn128Field; #[test] @@ -62,15 +62,15 @@ mod tests { statements: vec![ Statement::constraint( QuadComb::from_linear_combinations( - LinComb::summand(3, FlatVariable::new(3)), - LinComb::summand(3, FlatVariable::new(3)), + LinComb::summand(3, Variable::new(3)), + LinComb::summand(3, Variable::new(3)), ), LinComb::one(), ), Statement::constraint( QuadComb::from_linear_combinations( - LinComb::summand(3, FlatVariable::new(42)), - LinComb::summand(3, FlatVariable::new(3)), + LinComb::summand(3, Variable::new(42)), + LinComb::summand(3, Variable::new(3)), ), LinComb::zero(), ), @@ -91,8 +91,8 @@ mod tests { fn remove_duplicates() { let constraint = Statement::constraint( QuadComb::from_linear_combinations( - LinComb::summand(3, FlatVariable::new(3)), - LinComb::summand(3, FlatVariable::new(3)), + LinComb::summand(3, Variable::new(3)), + LinComb::summand(3, Variable::new(3)), ), LinComb::one(), ); @@ -103,8 +103,8 @@ mod tests { constraint.clone(), Statement::constraint( QuadComb::from_linear_combinations( - LinComb::summand(3, FlatVariable::new(42)), - LinComb::summand(3, FlatVariable::new(3)), + LinComb::summand(3, Variable::new(42)), + LinComb::summand(3, Variable::new(3)), ), LinComb::zero(), ), @@ -120,8 +120,8 @@ mod tests { constraint, Statement::constraint( QuadComb::from_linear_combinations( - LinComb::summand(3, FlatVariable::new(42)), - LinComb::summand(3, FlatVariable::new(3)), + LinComb::summand(3, Variable::new(42)), + LinComb::summand(3, Variable::new(3)), ), LinComb::zero(), ), diff --git a/zokrates_core/src/optimizer/mod.rs b/zokrates_core/src/optimizer/mod.rs index 051519f0..cecee2e3 100644 --- a/zokrates_core/src/optimizer/mod.rs +++ b/zokrates_core/src/optimizer/mod.rs @@ -16,50 +16,46 @@ use self::duplicate::DuplicateOptimizer; use self::redefinition::RedefinitionOptimizer; use self::tautology::TautologyOptimizer; -use crate::ir::{ProgIterator, Statement}; +use zokrates_ast::ir::{ProgIterator, Statement}; use zokrates_field::Field; -impl>> ProgIterator { - pub fn optimize(self) -> ProgIterator>> { - // remove redefinitions - log::debug!( - "Optimizer: Remove redefinitions and tautologies and directives and duplicates" - ); +pub fn optimize>>( + p: ProgIterator, +) -> ProgIterator>> { + // remove redefinitions + log::debug!("Optimizer: Remove redefinitions and tautologies and directives and duplicates"); - // define all optimizer steps - let mut redefinition_optimizer = RedefinitionOptimizer::init(&self); - let mut tautologies_optimizer = TautologyOptimizer::default(); - let mut directive_optimizer = DirectiveOptimizer::default(); - let mut canonicalizer = Canonicalizer::default(); - let mut duplicate_optimizer = DuplicateOptimizer::default(); + // define all optimizer steps + let mut redefinition_optimizer = RedefinitionOptimizer::init(&p); + let mut tautologies_optimizer = TautologyOptimizer::default(); + let mut directive_optimizer = DirectiveOptimizer::default(); + let mut canonicalizer = Canonicalizer::default(); + let mut duplicate_optimizer = DuplicateOptimizer::default(); - use crate::ir::folder::Folder; + use zokrates_ast::ir::folder::Folder; - let r = ProgIterator { - arguments: self - .arguments - .into_iter() - .map(|a| redefinition_optimizer.fold_argument(a)) - .map(|a| { - >::fold_argument(&mut tautologies_optimizer, a) - }) - .map(|a| directive_optimizer.fold_argument(a)) - .map(|a| { - >::fold_argument(&mut duplicate_optimizer, a) - }) - .collect(), - statements: self - .statements - .into_iter() - .flat_map(move |s| redefinition_optimizer.fold_statement(s)) - .flat_map(move |s| tautologies_optimizer.fold_statement(s)) - .flat_map(move |s| canonicalizer.fold_statement(s)) - .flat_map(move |s| directive_optimizer.fold_statement(s)) - .flat_map(move |s| duplicate_optimizer.fold_statement(s)), - return_count: self.return_count, - }; + let r = ProgIterator { + arguments: p + .arguments + .into_iter() + .map(|a| redefinition_optimizer.fold_argument(a)) + .map(|a| { + >::fold_argument(&mut tautologies_optimizer, a) + }) + .map(|a| directive_optimizer.fold_argument(a)) + .map(|a| >::fold_argument(&mut duplicate_optimizer, a)) + .collect(), + statements: p + .statements + .into_iter() + .flat_map(move |s| redefinition_optimizer.fold_statement(s)) + .flat_map(move |s| tautologies_optimizer.fold_statement(s)) + .flat_map(move |s| canonicalizer.fold_statement(s)) + .flat_map(move |s| directive_optimizer.fold_statement(s)) + .flat_map(move |s| duplicate_optimizer.fold_statement(s)), + return_count: p.return_count, + }; - log::debug!("Done"); - r - } + log::debug!("Done"); + r } diff --git a/zokrates_core/src/optimizer/redefinition.rs b/zokrates_core/src/optimizer/redefinition.rs index 0d35c5eb..14e42cd7 100644 --- a/zokrates_core/src/optimizer/redefinition.rs +++ b/zokrates_core/src/optimizer/redefinition.rs @@ -36,26 +36,27 @@ // - `q == k * v if v isn't in i`: insert `v` into `i` and return `c_0` // - otherwise return `c_0` -use crate::flat_absy::flat_variable::FlatVariable; -use crate::ir::folder::Folder; -use crate::ir::LinComb; -use crate::ir::*; +use crate::flat_absy::Variable; use std::collections::{HashMap, HashSet}; +use zokrates_ast::ir::folder::Folder; +use zokrates_ast::ir::LinComb; +use zokrates_ast::ir::*; use zokrates_field::Field; +use zokrates_interpreter::Interpreter; #[derive(Debug)] pub struct RedefinitionOptimizer { /// Map of renamings for reassigned variables while processing the program. - substitution: HashMap>, + substitution: HashMap>, /// Set of variables that should not be substituted - pub ignore: HashSet, + pub ignore: HashSet, } impl RedefinitionOptimizer { pub fn init>>(p: &ProgIterator) -> Self { RedefinitionOptimizer { substitution: HashMap::new(), - ignore: vec![FlatVariable::one()] + ignore: vec![Variable::one()] .into_iter() .chain(p.arguments.iter().map(|p| p.id)) .chain(p.returns()) @@ -156,7 +157,7 @@ impl Folder for RedefinitionOptimizer { let inputs: Vec<_> = inputs .into_iter() .map(|i| { - i.map(|v| LinComb::summand(v, FlatVariable::one()).into()) + i.map(|v| LinComb::summand(v, Variable::one()).into()) .unwrap_or_else(|q| q) }) .collect(); @@ -197,7 +198,7 @@ impl Folder for RedefinitionOptimizer { #[cfg(test)] mod tests { use super::*; - use crate::flat_absy::FlatParameter; + use crate::flat_absy::Parameter; use zokrates_field::Bn128Field; #[test] @@ -207,9 +208,9 @@ mod tests { // z = y // return z - let x = FlatParameter::public(FlatVariable::new(0)); - let y = FlatVariable::new(1); - let out = FlatVariable::public(0); + let x = Parameter::public(Variable::new(0)); + let y = Variable::new(1); + let out = Variable::public(0); let p: Prog = Prog { arguments: vec![x], @@ -235,8 +236,8 @@ mod tests { // def main(x): // one = x - let one = FlatVariable::one(); - let x = FlatParameter::public(FlatVariable::new(0)); + let one = Variable::one(); + let x = Parameter::public(Variable::new(0)); let p: Prog = Prog { arguments: vec![x], @@ -264,10 +265,10 @@ mod tests { // x == x // will be eliminated as a tautology // return x - let x = FlatParameter::public(FlatVariable::new(0)); - let y = FlatVariable::new(1); - let z = FlatVariable::new(2); - let out = FlatVariable::public(0); + let x = Parameter::public(Variable::new(0)); + let y = Variable::new(1); + let z = Variable::new(2); + let out = Variable::public(0); let p: Prog = Prog { arguments: vec![x], @@ -308,13 +309,13 @@ mod tests { // def main(x): // return x, 1 - let x = FlatParameter::public(FlatVariable::new(0)); - let y = FlatVariable::new(1); - let z = FlatVariable::new(2); - let t = FlatVariable::new(3); - let w = FlatVariable::new(4); - let out_1 = FlatVariable::public(0); - let out_0 = FlatVariable::public(1); + let x = Parameter::public(Variable::new(0)); + let y = Variable::new(1); + let z = Variable::new(2); + let t = Variable::new(3); + let w = Variable::new(4); + let out_1 = Variable::public(0); + let out_0 = Variable::public(1); let p: Prog = Prog { arguments: vec![x], @@ -358,12 +359,12 @@ mod tests { // 1*x + 1*y + 2*x + 2*y + 3*x + 3*y == 6*x + 6*y // will be eliminated as a tautology // ~out_0 = 6*x + 6*y - let x = FlatParameter::public(FlatVariable::new(0)); - let y = FlatParameter::public(FlatVariable::new(1)); - let a = FlatVariable::new(2); - let b = FlatVariable::new(3); - let c = FlatVariable::new(4); - let r = FlatVariable::public(0); + let x = Parameter::public(Variable::new(0)); + let y = Parameter::public(Variable::new(1)); + let a = Variable::new(2); + let b = Variable::new(3); + let c = Variable::new(4); + let r = Variable::public(0); let p: Prog = Prog { arguments: vec![x, y], @@ -427,9 +428,9 @@ mod tests { // z = x // return - let x = FlatParameter::public(FlatVariable::new(0)); - let y = FlatParameter::public(FlatVariable::new(1)); - let z = FlatVariable::new(2); + let x = Parameter::public(Variable::new(0)); + let y = Parameter::public(Variable::new(1)); + let z = Variable::new(2); let p: Prog = Prog { arguments: vec![x, y], @@ -460,7 +461,7 @@ mod tests { // unchanged - let x = FlatParameter::public(FlatVariable::new(0)); + let x = Parameter::public(Variable::new(0)); let p: Prog = Prog { arguments: vec![x], diff --git a/zokrates_core/src/optimizer/tautology.rs b/zokrates_core/src/optimizer/tautology.rs index e1146d3a..4a9ce847 100644 --- a/zokrates_core/src/optimizer/tautology.rs +++ b/zokrates_core/src/optimizer/tautology.rs @@ -5,9 +5,9 @@ // // This makes the assumption that ~one has value 1, as should be guaranteed by the verifier -use crate::ir::folder::fold_statement; -use crate::ir::folder::Folder; -use crate::ir::*; +use zokrates_ast::ir::folder::fold_statement; +use zokrates_ast::ir::folder::Folder; +use zokrates_ast::ir::*; use zokrates_field::Field; #[derive(Default)] diff --git a/zokrates_core/src/parser/mod.rs b/zokrates_core/src/parser/mod.rs deleted file mode 100644 index 7c903042..00000000 --- a/zokrates_core/src/parser/mod.rs +++ /dev/null @@ -1,3 +0,0 @@ -mod tokenize; - -pub use crate::parser::tokenize::Position; diff --git a/zokrates_core/src/parser/tokenize/mod.rs b/zokrates_core/src/parser/tokenize/mod.rs deleted file mode 100644 index 12044aff..00000000 --- a/zokrates_core/src/parser/tokenize/mod.rs +++ /dev/null @@ -1,3 +0,0 @@ -mod position; - -pub use self::position::Position; diff --git a/zokrates_core/src/proof_system/bellman/groth16.rs b/zokrates_core/src/proof_system/bellman/groth16.rs index 43127a34..c29a8dec 100644 --- a/zokrates_core/src/proof_system/bellman/groth16.rs +++ b/zokrates_core/src/proof_system/bellman/groth16.rs @@ -8,7 +8,6 @@ use crate::proof_system::{Backend, MpcBackend, NonUniversalBackend, Proof, Setup use zokrates_field::BellmanFieldExtensions; use zokrates_field::Field; -use crate::ir::{ProgIterator, Statement, Witness}; use crate::proof_system::bellman::Bellman; use crate::proof_system::bellman::Computation; use crate::proof_system::bellman::{parse_g1, parse_g2}; @@ -17,6 +16,7 @@ use crate::proof_system::Scheme; use phase2::MPCParameters; use rand_0_4::Rng; use std::io::{Read, Write}; +use zokrates_ast::ir::{ProgIterator, Statement, Witness}; 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."; @@ -197,20 +197,18 @@ pub mod serialization { #[cfg(test)] mod tests { use zokrates_field::Bn128Field; + use zokrates_interpreter::Interpreter; use super::*; - use crate::flat_absy::{FlatParameter, FlatVariable}; - use crate::ir::{Interpreter, Prog, Statement}; + use crate::flat_absy::{Parameter, Variable}; + use zokrates_ast::ir::{Prog, Statement}; #[test] fn verify() { let program: Prog = Prog { - arguments: vec![FlatParameter::public(FlatVariable::new(0))], + arguments: vec![Parameter::public(Variable::new(0))], return_count: 1, - statements: vec![Statement::constraint( - FlatVariable::new(0), - FlatVariable::public(0), - )], + statements: vec![Statement::constraint(Variable::new(0), Variable::public(0))], }; let keypair = >::setup(program.clone()); diff --git a/zokrates_core/src/proof_system/bellman/mod.rs b/zokrates_core/src/proof_system/bellman/mod.rs index 3e3cd2fc..67c81bb5 100644 --- a/zokrates_core/src/proof_system/bellman/mod.rs +++ b/zokrates_core/src/proof_system/bellman/mod.rs @@ -1,18 +1,20 @@ pub mod groth16; -use crate::ir::{CanonicalLinComb, ProgIterator, Statement, Witness}; use bellman::groth16::Proof; use bellman::groth16::{ create_random_proof, generate_random_parameters, prepare_verifying_key, verify_proof, Parameters, }; use bellman::pairing::ff::ScalarEngine; -use bellman::{Circuit, ConstraintSystem, LinearCombination, SynthesisError, Variable}; +use bellman::{ + Circuit, ConstraintSystem, LinearCombination, SynthesisError, Variable as BellmanVariable, +}; use std::collections::BTreeMap; +use zokrates_ast::common::Variable; +use zokrates_ast::ir::{CanonicalLinComb, ProgIterator, Statement, Witness}; use zokrates_field::BellmanFieldExtensions; use zokrates_field::Field; -use crate::flat_absy::FlatVariable; use rand_0_4::ChaChaRng; pub use self::parse::*; @@ -44,7 +46,7 @@ impl>> Computation { fn bellman_combination>( l: CanonicalLinComb, cs: &mut CS, - symbols: &mut BTreeMap, + symbols: &mut BTreeMap, witness: &mut Witness, ) -> LinearCombination { l.0.into_iter() @@ -81,18 +83,17 @@ fn bellman_combination>> ProgIterator { +impl>> Computation { pub fn synthesize>( self, cs: &mut CS, - witness: Option>, ) -> Result<(), SynthesisError> { // mapping from IR variables let mut symbols = BTreeMap::new(); - let mut witness = witness.unwrap_or_else(Witness::empty); + let mut witness = self.witness.unwrap_or_else(Witness::empty); - assert!(symbols.insert(FlatVariable::one(), CS::one()).is_none()); + assert!(symbols.insert(Variable::one(), CS::one()).is_none()); symbols.extend(self.arguments.iter().enumerate().map(|(index, p)| { let wire = match p.private { @@ -246,14 +247,14 @@ mod parse { #[cfg(test)] mod tests { use super::*; - use crate::ir::Interpreter; - use crate::ir::LinComb; + use zokrates_ast::ir::LinComb; use zokrates_field::Bn128Field; + use zokrates_interpreter::Interpreter; mod prove { use super::*; - use crate::flat_absy::FlatParameter; - use crate::ir::Prog; + use crate::flat_absy::Parameter; + use zokrates_ast::ir::Prog; #[test] fn empty() { @@ -271,12 +272,9 @@ mod tests { #[test] fn identity() { let program: Prog = Prog { - arguments: vec![FlatParameter::private(FlatVariable::new(0))], + arguments: vec![Parameter::private(Variable::new(0))], return_count: 1, - statements: vec![Statement::constraint( - FlatVariable::new(0), - FlatVariable::public(0), - )], + statements: vec![Statement::constraint(Variable::new(0), Variable::public(0))], }; let interpreter = Interpreter::default(); @@ -294,12 +292,9 @@ mod tests { #[test] fn public_identity() { let program: Prog = Prog { - arguments: vec![FlatParameter::public(FlatVariable::new(0))], + arguments: vec![Parameter::public(Variable::new(0))], return_count: 1, - statements: vec![Statement::constraint( - FlatVariable::new(0), - FlatVariable::public(0), - )], + statements: vec![Statement::constraint(Variable::new(0), Variable::public(0))], }; let interpreter = Interpreter::default(); @@ -319,10 +314,7 @@ mod tests { let program: Prog = Prog { arguments: vec![], return_count: 1, - statements: vec![Statement::constraint( - FlatVariable::one(), - FlatVariable::public(0), - )], + statements: vec![Statement::constraint(Variable::one(), Variable::public(0))], }; let interpreter = Interpreter::default(); @@ -340,18 +332,18 @@ mod tests { // private variables can be unordered let program: Prog = Prog { arguments: vec![ - FlatParameter::private(FlatVariable::new(42)), - FlatParameter::public(FlatVariable::new(51)), + Parameter::private(Variable::new(42)), + Parameter::public(Variable::new(51)), ], return_count: 2, statements: vec![ Statement::constraint( - LinComb::from(FlatVariable::new(42)) + LinComb::from(FlatVariable::new(51)), - FlatVariable::public(0), + LinComb::from(Variable::new(42)) + LinComb::from(Variable::new(51)), + Variable::public(0), ), Statement::constraint( - LinComb::from(FlatVariable::one()) + LinComb::from(FlatVariable::new(42)), - FlatVariable::public(1), + LinComb::from(Variable::one()) + LinComb::from(Variable::new(42)), + Variable::public(1), ), ], }; @@ -370,11 +362,11 @@ mod tests { #[test] fn one() { let program: Prog = Prog { - arguments: vec![FlatParameter::public(FlatVariable::new(42))], + arguments: vec![Parameter::public(Variable::new(42))], return_count: 1, statements: vec![Statement::constraint( - LinComb::from(FlatVariable::new(42)) + LinComb::one(), - FlatVariable::public(0), + LinComb::from(Variable::new(42)) + LinComb::one(), + Variable::public(0), )], }; @@ -394,13 +386,13 @@ mod tests { fn with_directives() { let program: Prog = Prog { arguments: vec![ - FlatParameter::private(FlatVariable::new(42)), - FlatParameter::public(FlatVariable::new(51)), + Parameter::private(Variable::new(42)), + Parameter::public(Variable::new(51)), ], return_count: 1, statements: vec![Statement::constraint( - LinComb::from(FlatVariable::new(42)) + LinComb::from(FlatVariable::new(51)), - FlatVariable::public(0), + LinComb::from(Variable::new(42)) + LinComb::from(Variable::new(51)), + Variable::public(0), )], }; diff --git a/zokrates_core/src/proof_system/libsnark/gm17.rs b/zokrates_core/src/proof_system/libsnark/gm17.rs index 1d13d635..83915cdb 100644 --- a/zokrates_core/src/proof_system/libsnark/gm17.rs +++ b/zokrates_core/src/proof_system/libsnark/gm17.rs @@ -1,4 +1,3 @@ -use crate::ir::{ProgIterator, Statement, Witness}; use crate::proof_system::gm17::{ProofPoints, VerificationKey, GM17}; use crate::proof_system::libsnark::ffi::{c_free, Buffer, ProofResult, SetupResult}; use crate::proof_system::libsnark::{ @@ -7,6 +6,7 @@ use crate::proof_system::libsnark::{ use crate::proof_system::Scheme; use crate::proof_system::{Backend, G1Affine, G2Affine, NonUniversalBackend, Proof, SetupKeypair}; use std::io::{BufReader, BufWriter, Write}; +use zokrates_ast::ir::{ProgIterator, Statement, Witness}; use zokrates_field::{Bn128Field, Field}; extern "C" { @@ -197,7 +197,7 @@ impl NonUniversalBackend for Libsnark { mod tests { use super::*; use crate::flat_absy::{FlatParameter, FlatVariable}; - use crate::ir::{Interpreter, Prog, Statement}; + use zokrates_ast::ir::{Interpreter, Prog, Statement}; use zokrates_field::Bn128Field; #[test] diff --git a/zokrates_core/src/proof_system/libsnark/mod.rs b/zokrates_core/src/proof_system/libsnark/mod.rs index 9a4ee0cc..bc152dc4 100644 --- a/zokrates_core/src/proof_system/libsnark/mod.rs +++ b/zokrates_core/src/proof_system/libsnark/mod.rs @@ -3,9 +3,9 @@ pub mod gm17; pub mod pghr13; use crate::flat_absy::FlatVariable; -use crate::ir::{self, Statement}; use std::cmp::max; use std::collections::HashMap; +use zokrates_ast::ir::{self, Statement}; use zokrates_field::Field; pub struct Libsnark; diff --git a/zokrates_core/src/proof_system/libsnark/pghr13.rs b/zokrates_core/src/proof_system/libsnark/pghr13.rs index 9c884036..f2d26528 100644 --- a/zokrates_core/src/proof_system/libsnark/pghr13.rs +++ b/zokrates_core/src/proof_system/libsnark/pghr13.rs @@ -4,11 +4,11 @@ use crate::proof_system::libsnark::{ }; use crate::proof_system::{Backend, G1Affine, G2Affine, NonUniversalBackend, Proof, SetupKeypair}; -use crate::ir::{ProgIterator, Statement, Witness}; use crate::proof_system::libsnark::serialization::{read_g1, read_g2, write_g1, write_g2}; use crate::proof_system::pghr13::{ProofPoints, VerificationKey, PGHR13}; use crate::proof_system::Scheme; use std::io::{BufReader, BufWriter, Write}; +use zokrates_ast::ir::{ProgIterator, Statement, Witness}; use zokrates_field::Bn128Field; use zokrates_field::Field; @@ -227,7 +227,7 @@ impl NonUniversalBackend for Libsnark { mod tests { use super::*; use crate::flat_absy::{FlatParameter, FlatVariable}; - use crate::ir::{Interpreter, Prog, Statement}; + use zokrates_ast::ir::{Interpreter, Prog, Statement}; use zokrates_field::Bn128Field; #[test] diff --git a/zokrates_core/src/proof_system/mod.rs b/zokrates_core/src/proof_system/mod.rs index e2e7210f..64e30928 100644 --- a/zokrates_core/src/proof_system/mod.rs +++ b/zokrates_core/src/proof_system/mod.rs @@ -1,5 +1,3 @@ -#[cfg(feature = "ark")] -pub mod ark; #[cfg(feature = "bellman")] pub mod bellman; #[cfg(feature = "libsnark")] @@ -13,7 +11,7 @@ mod solidity; pub use self::scheme::*; pub use self::solidity::*; -use crate::ir; +use zokrates_ast::ir; use serde::de::DeserializeOwned; use serde::{Deserialize, Serialize}; diff --git a/zokrates_core/src/semantics.rs b/zokrates_core/src/semantics.rs index 7e3c2626..f907274b 100644 --- a/zokrates_core/src/semantics.rs +++ b/zokrates_core/src/semantics.rs @@ -15,8 +15,6 @@ use std::fmt; use std::path::PathBuf; use zokrates_field::Field; -use crate::parser::Position; - use crate::absy::types::{UnresolvedSignature, UnresolvedType, UserTypeId}; use crate::typed_absy::types::{ diff --git a/zokrates_core/src/static_analysis/branch_isolator.rs b/zokrates_core/src/static_analysis/branch_isolator.rs index 77580386..4ad54d28 100644 --- a/zokrates_core/src/static_analysis/branch_isolator.rs +++ b/zokrates_core/src/static_analysis/branch_isolator.rs @@ -3,8 +3,8 @@ // `if c then a else b fi` becomes `if c then { a } else { b } fi`, and down the line any statements resulting from trating `a` and `b` can be safely kept inside the respective blocks. -use crate::typed_absy::folder::*; use crate::typed_absy::*; +use zokrates_ast::typed::folder::*; use zokrates_field::Field; pub struct Isolator; diff --git a/zokrates_core/src/static_analysis/constant_argument_checker.rs b/zokrates_core/src/static_analysis/constant_argument_checker.rs index 42bb3b66..160eb806 100644 --- a/zokrates_core/src/static_analysis/constant_argument_checker.rs +++ b/zokrates_core/src/static_analysis/constant_argument_checker.rs @@ -1,4 +1,3 @@ -use crate::embed::FlatEmbed; use crate::typed_absy::TypedProgram; use crate::typed_absy::{ result_folder::ResultFolder, @@ -6,6 +5,7 @@ use crate::typed_absy::{ Constant, TypedExpressionListInner, Types, UBitwidth, UExpressionInner, }; use std::fmt; +use zokrates_ast::common::FlatEmbed; use zokrates_field::Field; pub struct ConstantArgumentChecker; diff --git a/zokrates_core/src/static_analysis/constant_resolver.rs b/zokrates_core/src/static_analysis/constant_resolver.rs index 546b9b56..62fe07cc 100644 --- a/zokrates_core/src/static_analysis/constant_resolver.rs +++ b/zokrates_core/src/static_analysis/constant_resolver.rs @@ -2,9 +2,9 @@ // This does *not* reduce constants to their literal value // This step cannot fail as the imports were checked during semantics -use crate::typed_absy::folder::*; use crate::typed_absy::*; use std::collections::HashMap; +use zokrates_ast::typed::folder::*; use zokrates_field::Field; // a map of the canonical constants in this program. with all imported constants reduced to their canonical value diff --git a/zokrates_core/src/static_analysis/flat_propagation.rs b/zokrates_core/src/static_analysis/flat_propagation.rs index caa58473..36d9a72e 100644 --- a/zokrates_core/src/static_analysis/flat_propagation.rs +++ b/zokrates_core/src/static_analysis/flat_propagation.rs @@ -6,26 +6,36 @@ use crate::flat_absy::*; use std::collections::HashMap; +use zokrates_ast::flat::folder::*; use zokrates_field::Field; -pub trait Propagate { - fn propagate(self) -> Self; +struct Propagator { + constants: HashMap, } -pub trait PropagateWithContext { - fn propagate(self, constants: &mut HashMap) -> Self; -} +impl Folder for Propagator { + fn fold_statement(&mut self, s: FlatStatement) -> Vec> { + match s { + FlatStatement::Definition(var, expr) => match self.fold_expression(expr) { + FlatExpression::Number(n) => { + self.constants.insert(var, n); + vec![] + } + e => vec![FlatStatement::Definition(var, e)], + }, + s => fold_statement(self, s), + } + } -impl PropagateWithContext for FlatExpression { - fn propagate(self, constants: &mut HashMap) -> FlatExpression { - match self { + fn fold_expression(&mut self, e: FlatExpression) -> FlatExpression { + match e { FlatExpression::Number(n) => FlatExpression::Number(n), - FlatExpression::Identifier(id) => match constants.get(&id) { + FlatExpression::Identifier(id) => match self.constants.get(&id) { Some(c) => FlatExpression::Number(c.clone()), None => FlatExpression::Identifier(id), }, FlatExpression::Add(box e1, box e2) => { - match (e1.propagate(constants), e2.propagate(constants)) { + match (self.fold_expression(e1), self.fold_expression(e2)) { (FlatExpression::Number(n1), FlatExpression::Number(n2)) => { FlatExpression::Number(n1 + n2) } @@ -33,7 +43,7 @@ impl PropagateWithContext for FlatExpression { } } FlatExpression::Sub(box e1, box e2) => { - match (e1.propagate(constants), e2.propagate(constants)) { + match (self.fold_expression(e1), self.fold_expression(e2)) { (FlatExpression::Number(n1), FlatExpression::Number(n2)) => { FlatExpression::Number(n1 - n2) } @@ -41,7 +51,7 @@ impl PropagateWithContext for FlatExpression { } } FlatExpression::Mult(box e1, box e2) => { - match (e1.propagate(constants), e2.propagate(constants)) { + match (self.fold_expression(e1), self.fold_expression(e2)) { (FlatExpression::Number(n1), FlatExpression::Number(n2)) => { FlatExpression::Number(n1 * n2) } @@ -52,48 +62,6 @@ impl PropagateWithContext for FlatExpression { } } -impl FlatStatement { - fn propagate(self, constants: &mut HashMap) -> Option> { - match self { - FlatStatement::Definition(var, expr) => match expr.propagate(constants) { - FlatExpression::Number(n) => { - constants.insert(var, n); - None - } - e => Some(FlatStatement::Definition(var, e)), - }, - FlatStatement::Condition(e1, e2, message) => Some(FlatStatement::Condition( - e1.propagate(constants), - e2.propagate(constants), - message, - )), - FlatStatement::Directive(d) => Some(FlatStatement::Directive(FlatDirective { - inputs: d - .inputs - .into_iter() - .map(|i| i.propagate(constants)) - .collect(), - ..d - })), - } - } -} - -impl Propagate for FlatFunction { - fn propagate(self) -> FlatFunction { - let mut constants = HashMap::new(); - - FlatFunction { - statements: self - .statements - .into_iter() - .filter_map(|s| s.propagate(&mut constants)) - .collect(), - ..self - } - } -} - #[cfg(test)] mod tests { use super::*; diff --git a/zokrates_core/src/static_analysis/mod.rs b/zokrates_core/src/static_analysis/mod.rs index ed362863..2629f0e1 100644 --- a/zokrates_core/src/static_analysis/mod.rs +++ b/zokrates_core/src/static_analysis/mod.rs @@ -89,81 +89,82 @@ impl fmt::Display for Error { } } -impl<'ast, T: Field> TypedProgram<'ast, T> { - pub fn analyse(self, config: &CompileConfig) -> Result<(ZirProgram<'ast, T>, Abi), Error> { - // inline user-defined constants - log::debug!("Static analyser: Inline constants"); - let r = ConstantResolver::inline(self); +pub fn analyse<'ast, T: Field>( + p: TypedProgram<'ast, T>, + config: &CompileConfig, +) -> Result<(ZirProgram<'ast, T>, Abi), Error> { + // inline user-defined constants + log::debug!("Static analyser: Inline constants"); + let r = ConstantResolver::inline(p); + log::trace!("\n{}", r); + + // isolate branches + let r = if config.isolate_branches { + log::debug!("Static analyser: Isolate branches"); + let r = Isolator::isolate(r); log::trace!("\n{}", r); + r + } else { + log::debug!("Static analyser: Branch isolation skipped"); + r + }; - // isolate branches - let r = if config.isolate_branches { - log::debug!("Static analyser: Isolate branches"); - let r = Isolator::isolate(r); - log::trace!("\n{}", r); - r - } else { - log::debug!("Static analyser: Branch isolation skipped"); - r - }; + // reduce the program to a single function + log::debug!("Static analyser: Reduce program"); + let r = reduce_program(r).map_err(Error::from)?; + log::trace!("\n{}", r); - // reduce the program to a single function - log::debug!("Static analyser: Reduce program"); - let r = reduce_program(r).map_err(Error::from)?; - log::trace!("\n{}", r); + log::debug!("Static analyser: Propagate"); + let r = Propagator::propagate(r)?; + log::trace!("\n{}", r); - log::debug!("Static analyser: Propagate"); - let r = Propagator::propagate(r)?; - log::trace!("\n{}", r); + log::debug!("Static analyser: Concretize structs"); + let r = StructConcretizer::concretize(r); + log::trace!("\n{}", r); - log::debug!("Static analyser: Concretize structs"); - let r = StructConcretizer::concretize(r); - log::trace!("\n{}", r); + // generate abi + log::debug!("Static analyser: Generate abi"); + let abi = r.abi(); - // generate abi - log::debug!("Static analyser: Generate abi"); - let abi = r.abi(); + // propagate + log::debug!("Static analyser: Propagate"); + let r = Propagator::propagate(r).map_err(Error::from)?; + log::trace!("\n{}", r); - // propagate - log::debug!("Static analyser: Propagate"); - let r = Propagator::propagate(r).map_err(Error::from)?; - log::trace!("\n{}", r); + // remove assignment to variable index + log::debug!("Static analyser: Remove variable index"); + let r = VariableWriteRemover::apply(r); + log::trace!("\n{}", r); - // remove assignment to variable index - log::debug!("Static analyser: Remove variable index"); - let r = VariableWriteRemover::apply(r); - log::trace!("\n{}", r); + // detect non constant shifts and constant lt bounds + log::debug!("Static analyser: Detect non constant arguments"); + let r = ConstantArgumentChecker::check(r).map_err(Error::from)?; + log::trace!("\n{}", r); - // detect non constant shifts and constant lt bounds - log::debug!("Static analyser: Detect non constant arguments"); - let r = ConstantArgumentChecker::check(r).map_err(Error::from)?; - log::trace!("\n{}", r); + // detect out of bounds reads and writes + log::debug!("Static analyser: Detect out of bound accesses"); + let r = OutOfBoundsChecker::check(r).map_err(Error::from)?; + log::trace!("\n{}", r); - // detect out of bounds reads and writes - log::debug!("Static analyser: Detect out of bound accesses"); - let r = OutOfBoundsChecker::check(r).map_err(Error::from)?; - log::trace!("\n{}", r); + // redefine conditions + log::debug!("Static analyser: Redefine conditions"); + let r = ConditionRedefiner::redefine(r); + log::trace!("\n{}", r); - // redefine conditions - log::debug!("Static analyser: Redefine conditions"); - let r = ConditionRedefiner::redefine(r); - log::trace!("\n{}", r); + // convert to zir, removing complex types + log::debug!("Static analyser: Convert to zir"); + let zir = Flattener::flatten(r); + log::trace!("\n{}", zir); - // convert to zir, removing complex types - log::debug!("Static analyser: Convert to zir"); - let zir = Flattener::flatten(r); - log::trace!("\n{}", zir); + // apply propagation in zir + log::debug!("Static analyser: Apply propagation in zir"); + let zir = ZirPropagator::propagate(zir).map_err(Error::from)?; + log::trace!("\n{}", zir); - // apply propagation in zir - log::debug!("Static analyser: Apply propagation in zir"); - let zir = ZirPropagator::propagate(zir).map_err(Error::from)?; - log::trace!("\n{}", zir); + // optimize uint expressions + log::debug!("Static analyser: Optimize uints"); + let zir = UintOptimizer::optimize(zir); + log::trace!("\n{}", zir); - // optimize uint expressions - log::debug!("Static analyser: Optimize uints"); - let zir = UintOptimizer::optimize(zir); - log::trace!("\n{}", zir); - - Ok((zir, abi)) - } + Ok((zir, abi)) } diff --git a/zokrates_core/src/static_analysis/propagation.rs b/zokrates_core/src/static_analysis/propagation.rs index 6922d8c0..33ce5ca6 100644 --- a/zokrates_core/src/static_analysis/propagation.rs +++ b/zokrates_core/src/static_analysis/propagation.rs @@ -7,13 +7,13 @@ //! @author Thibaut Schaeffer //! @date 2018 -use crate::embed::FlatEmbed; use crate::typed_absy::result_folder::*; use crate::typed_absy::types::Type; use crate::typed_absy::*; use std::collections::HashMap; use std::convert::{TryFrom, TryInto}; use std::fmt; +use zokrates_ast::common::FlatEmbed; use zokrates_field::Field; pub type Constants<'ast, T> = HashMap, TypedExpression<'ast, T>>; diff --git a/zokrates_core/src/static_analysis/reducer/inline.rs b/zokrates_core/src/static_analysis/reducer/inline.rs index 51efdbdc..3303766f 100644 --- a/zokrates_core/src/static_analysis/reducer/inline.rs +++ b/zokrates_core/src/static_analysis/reducer/inline.rs @@ -25,7 +25,6 @@ // - The body of the function is in SSA form // - The return value(s) are assigned to internal variables -use crate::embed::FlatEmbed; use crate::static_analysis::reducer::Output; use crate::static_analysis::reducer::ShallowTransformer; use crate::static_analysis::reducer::Versions; @@ -38,6 +37,7 @@ use crate::typed_absy::{ Signature, TypedExpression, TypedFunctionSymbol, TypedFunctionSymbolDeclaration, TypedProgram, TypedStatement, Types, UExpression, UExpressionInner, Variable, }; +use zokrates_ast::common::FlatEmbed; use zokrates_field::Field; pub enum InlineError<'ast, T> { diff --git a/zokrates_core/src/static_analysis/reducer/shallow_ssa.rs b/zokrates_core/src/static_analysis/reducer/shallow_ssa.rs index 33d6d930..44ef2922 100644 --- a/zokrates_core/src/static_analysis/reducer/shallow_ssa.rs +++ b/zokrates_core/src/static_analysis/reducer/shallow_ssa.rs @@ -24,10 +24,10 @@ // endfor // return b_3 // we leave versions b_1 and b_2 to make b accessible and modifiable inside the for-loop -use crate::typed_absy::folder::*; use crate::typed_absy::types::ConcreteGenericsAssignment; use crate::typed_absy::types::Type; use crate::typed_absy::*; +use zokrates_ast::typed::folder::*; use zokrates_field::Field; diff --git a/zokrates_core/src/static_analysis/struct_concretizer.rs b/zokrates_core/src/static_analysis/struct_concretizer.rs index 71502cc1..e3d30f14 100644 --- a/zokrates_core/src/static_analysis/struct_concretizer.rs +++ b/zokrates_core/src/static_analysis/struct_concretizer.rs @@ -5,7 +5,6 @@ // for structs, `Foo { field[N] a }` is propagated to `Foo<42> { field[N] a }`. The missing step is replacing `N` by `42` // *inside* the canonical type, so that it can be concretized in the same way arrays are. -use crate::typed_absy::folder::*; use crate::typed_absy::{ types::{ ConcreteGenericsAssignment, DeclarationArrayType, DeclarationConstant, @@ -14,6 +13,7 @@ use crate::typed_absy::{ DeclarationStructType, GenericIdentifier, TypedProgram, }; use std::marker::PhantomData; +use zokrates_ast::typed::folder::*; use zokrates_field::Field; pub struct StructConcretizer<'ast, T> { diff --git a/zokrates_core/src/static_analysis/uint_optimizer.rs b/zokrates_core/src/static_analysis/uint_optimizer.rs index 7219b652..65796bd2 100644 --- a/zokrates_core/src/static_analysis/uint_optimizer.rs +++ b/zokrates_core/src/static_analysis/uint_optimizer.rs @@ -1,8 +1,8 @@ -use crate::embed::FlatEmbed; use crate::zir::folder::*; use crate::zir::*; use std::collections::HashMap; use std::ops::{BitAnd, Shl, Shr}; +use zokrates_ast::common::FlatEmbed; use zokrates_field::Field; #[derive(Default)] diff --git a/zokrates_core/src/static_analysis/unconstrained_vars.rs b/zokrates_core/src/static_analysis/unconstrained_vars.rs index 807ceae4..ad52b4d8 100644 --- a/zokrates_core/src/static_analysis/unconstrained_vars.rs +++ b/zokrates_core/src/static_analysis/unconstrained_vars.rs @@ -1,15 +1,15 @@ -use crate::flat_absy::FlatParameter; -use crate::flat_absy::FlatVariable; -use crate::ir::folder::Folder; -use crate::ir::Directive; -use crate::ir::ProgIterator; -use crate::ir::Statement; use std::collections::HashSet; +use zokrates_ast::ir::folder::Folder; +use zokrates_ast::ir::Directive; +use zokrates_ast::ir::Parameter; +use zokrates_ast::ir::ProgIterator; +use zokrates_ast::ir::Statement; +use zokrates_ast::ir::Variable; use zokrates_field::Field; #[derive(Debug)] pub struct UnconstrainedVariableDetector { - pub(self) variables: HashSet, + pub(self) variables: HashSet, } impl UnconstrainedVariableDetector { @@ -33,10 +33,10 @@ impl UnconstrainedVariableDetector { } impl Folder for UnconstrainedVariableDetector { - fn fold_argument(&mut self, p: FlatParameter) -> FlatParameter { + fn fold_argument(&mut self, p: Parameter) -> Parameter { p } - fn fold_variable(&mut self, v: FlatVariable) -> FlatVariable { + fn fold_variable(&mut self, v: Variable) -> Variable { self.variables.remove(&v); v } diff --git a/zokrates_core/src/static_analysis/variable_write_remover.rs b/zokrates_core/src/static_analysis/variable_write_remover.rs index bbd68c28..4a6040d4 100644 --- a/zokrates_core/src/static_analysis/variable_write_remover.rs +++ b/zokrates_core/src/static_analysis/variable_write_remover.rs @@ -4,10 +4,10 @@ //! @author Thibaut Schaeffer //! @date 2018 -use crate::typed_absy::folder::*; use crate::typed_absy::types::{MemberId, Type}; use crate::typed_absy::*; use std::collections::HashSet; +use zokrates_ast::typed::folder::*; use zokrates_field::Field; pub struct VariableWriteRemover; diff --git a/zokrates_core/src/static_analysis/zir_propagation.rs b/zokrates_core/src/static_analysis/zir_propagation.rs index db0d8eb1..d06ba04d 100644 --- a/zokrates_core/src/static_analysis/zir_propagation.rs +++ b/zokrates_core/src/static_analysis/zir_propagation.rs @@ -707,10 +707,8 @@ mod tests { use crate::zir::RuntimeError; use zokrates_field::Bn128Field; - impl RuntimeError { - pub fn mock() -> Self { - RuntimeError::SourceAssertion(String::default()) - } + pub fn mock() -> RuntimeError { + RuntimeError::SourceAssertion(String::default()) } #[test] @@ -727,7 +725,7 @@ mod tests { box FieldElementExpression::Number(Bn128Field::from(1)), ), ), - RuntimeError::mock(), + mock(), )]; let mut propagator = ZirPropagator::default(); @@ -747,7 +745,7 @@ mod tests { box FieldElementExpression::Identifier("x".into()), box FieldElementExpression::Identifier("y".into()), ), - RuntimeError::mock() + mock() )] ); } diff --git a/zokrates_interpreter/Cargo.toml b/zokrates_interpreter/Cargo.toml new file mode 100644 index 00000000..f18876b0 --- /dev/null +++ b/zokrates_interpreter/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "zokrates_interpreter" +version = "0.1.0" +edition = "2021" + +[dependencies] +zokrates_field = { version = "0.5", path = "../zokrates_field", default-features = false } +zokrates_ast = { version = "0.1", path = "../zokrates_ast", default-features = false } +num = { version = "0.1.36", default-features = false } +num-bigint = { version = "0.2", default-features = false } diff --git a/zokrates_core/src/ir/interpreter.rs b/zokrates_interpreter/src/lib.rs similarity index 87% rename from zokrates_core/src/ir/interpreter.rs rename to zokrates_interpreter/src/lib.rs index 67a91a02..ea6cabcb 100644 --- a/zokrates_core/src/ir/interpreter.rs +++ b/zokrates_interpreter/src/lib.rs @@ -1,10 +1,8 @@ -use crate::flat_absy::flat_variable::FlatVariable; -use crate::flat_absy::RuntimeError; -use crate::ir::{LinComb, ProgIterator, QuadComb, Statement, Witness}; -use crate::solvers::Solver; -use serde::{Deserialize, Serialize}; -use std::collections::BTreeMap; +use num::traits::ops::checked::CheckedDiv; use std::fmt; +use zokrates_ast::ir::{ + LinComb, ProgIterator, QuadComb, RuntimeError, Solver, Statement, Variable, Witness, +}; use zokrates_field::Field; pub type ExecutionResult = Result, Error>; @@ -31,8 +29,8 @@ impl Interpreter { inputs: &[T], ) -> ExecutionResult { self.check_inputs(&program, inputs)?; - let mut witness = BTreeMap::new(); - witness.insert(FlatVariable::one(), T::one()); + let mut witness = Witness::default(); + witness.insert(Variable::one(), T::one()); for (arg, value) in program.arguments.iter().zip(inputs.iter()) { witness.insert(arg.id, value.clone()); @@ -42,12 +40,12 @@ impl Interpreter { match statement { Statement::Constraint(quad, lin, error) => match lin.is_assignee(&witness) { true => { - let val = quad.evaluate(&witness).unwrap(); + let val = evaluate_quad(&witness, &quad).unwrap(); witness.insert(lin.0.get(0).unwrap().0, val); } false => { - let lhs_value = quad.evaluate(&witness).unwrap(); - let rhs_value = lin.evaluate(&witness).unwrap(); + let lhs_value = evaluate_quad(&witness, &quad).unwrap(); + let rhs_value = evaluate_lin(&witness, &lin).unwrap(); if lhs_value != rhs_value { return Err(Error::UnsatisfiedConstraint { error }); } @@ -57,7 +55,7 @@ impl Interpreter { let mut inputs: Vec<_> = d .inputs .iter() - .map(|i| i.evaluate(&witness).unwrap()) + .map(|i| evaluate_quad(&witness, i).unwrap()) .collect(); let res = match (&d.solver, self.should_try_out_of_range) { @@ -78,7 +76,7 @@ impl Interpreter { } } - Ok(Witness(witness)) + Ok(witness) } fn try_solve_with_out_of_range_bits(bit_width: usize, input: T) -> Vec { @@ -239,42 +237,30 @@ impl Interpreter { #[derive(Debug)] pub struct EvaluationError; -impl LinComb { - fn evaluate(&self, witness: &BTreeMap) -> Result { - self.0 - .iter() - .map(|(var, mult)| { - witness - .get(var) - .map(|v| v.clone() * mult) - .ok_or(EvaluationError) - }) // get each term - .collect::, _>>() // fail if any term isn't found - .map(|v| v.iter().fold(T::from(0), |acc, t| acc + t)) // return the sum - } - - fn is_assignee(&self, witness: &BTreeMap) -> bool { - self.0.len() == 1 - && self.0.get(0).unwrap().1 == T::from(1) - && !witness.contains_key(&self.0.get(0).unwrap().0) - } -} - -impl QuadComb { - pub fn evaluate(&self, witness: &BTreeMap) -> Result { - let left = self.left.evaluate(witness)?; - let right = self.right.evaluate(witness)?; - Ok(left * right) - } -} - -#[derive(PartialEq, Serialize, Deserialize, Clone)] +#[derive(PartialEq, Clone)] pub enum Error { UnsatisfiedConstraint { error: Option }, Solver, WrongInputCount { expected: usize, received: usize }, } +fn evaluate_lin(w: &Witness, l: &LinComb) -> Result { + l.0.iter() + .map(|(var, mult)| { + w.0.get(var) + .map(|v| v.clone() * mult) + .ok_or(EvaluationError) + }) // get each term + .collect::, _>>() // fail if any term isn't found + .map(|v| v.iter().fold(T::from(0), |acc, t| acc + t)) // return the sum +} + +pub fn evaluate_quad(w: &Witness, q: &QuadComb) -> Result { + let left = evaluate_lin(w, &q.left)?; + let right = evaluate_lin(w, &q.right)?; + Ok(left * right) +} + impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { From ed04267a9a0b9c50fd19ec85a0b894eed040c638 Mon Sep 17 00:00:00 2001 From: schaeff Date: Fri, 13 May 2022 12:34:05 +0200 Subject: [PATCH 02/19] complete refactor --- Cargo.lock | 122 ++- Cargo.toml | 4 +- zokrates_abi/Cargo.toml | 2 +- zokrates_abi/src/lib.rs | 6 +- zokrates_ark/Cargo.toml | 24 + zokrates_ark/src/gm17.rs | 200 ++-- zokrates_ark/src/groth16.rs | 136 +-- zokrates_ark/src/lib.rs | 103 +- zokrates_ark/src/marlin.rs | 39 +- zokrates_ast/Cargo.toml | 8 +- zokrates_ast/src/common/embed.rs | 119 ++- zokrates_ast/src/common/error.rs | 9 + zokrates_ast/src/flat/folder.rs | 35 +- .../src/ir/check.rs | 12 +- zokrates_ast/src/ir/from_flat.rs | 36 +- zokrates_ast/src/ir/mod.rs | 3 +- zokrates_ast/src/ir/serialize.rs | 23 +- zokrates_ast/src/typed/mod.rs | 6 - zokrates_ast/src/typed/parameter.rs | 1 - zokrates_ast/src/typed/variable.rs | 5 - zokrates_ast/src/untyped/node.rs | 1 - zokrates_ast/src/zir/mod.rs | 6 + zokrates_ast/src/zir/uint.rs | 5 + zokrates_bellman/Cargo.toml | 28 + .../src}/groth16.rs | 27 +- .../mod.rs => zokrates_bellman/src/lib.rs | 29 +- zokrates_cli/Cargo.toml | 14 +- zokrates_cli/src/bin.rs | 5 +- zokrates_cli/src/ops/compute_witness.rs | 11 +- zokrates_cli/src/ops/export_verifier.rs | 2 +- zokrates_cli/src/ops/generate_proof.rs | 19 +- zokrates_cli/src/ops/generate_smtlib2.rs | 4 +- zokrates_cli/src/ops/inspect.rs | 3 +- zokrates_cli/src/ops/mpc/beacon.rs | 4 +- zokrates_cli/src/ops/mpc/contribute.rs | 4 +- zokrates_cli/src/ops/mpc/export.rs | 4 +- zokrates_cli/src/ops/mpc/init.rs | 7 +- zokrates_cli/src/ops/mpc/verify.rs | 7 +- zokrates_cli/src/ops/print_proof.rs | 4 +- zokrates_cli/src/ops/setup.rs | 19 +- zokrates_cli/src/ops/universal_setup.rs | 8 +- zokrates_cli/src/ops/verify.rs | 16 +- zokrates_cli/tests/integration.rs | 6 +- zokrates_core/Cargo.toml | 48 +- zokrates_core/src/compile.rs | 29 +- zokrates_core/src/flatten/mod.rs | 87 +- zokrates_core/src/flatten/utils.rs | 2 +- zokrates_core/src/imports.rs | 4 +- zokrates_core/src/lib.rs | 16 +- zokrates_core/src/optimizer/duplicate.rs | 2 +- zokrates_core/src/optimizer/redefinition.rs | 4 +- zokrates_core/src/semantics.rs | 157 +-- .../src/static_analysis/branch_isolator.rs | 2 +- .../static_analysis/condition_redefiner.rs | 4 +- .../constant_argument_checker.rs | 8 +- .../src/static_analysis/constant_inliner.rs | 973 ------------------ .../src/static_analysis/constant_resolver.rs | 6 +- .../src/static_analysis/flat_propagation.rs | 15 +- .../static_analysis/flatten_complex_types.rs | 490 +++++---- zokrates_core/src/static_analysis/mod.rs | 6 +- .../src/static_analysis/out_of_bounds.rs | 6 +- .../src/static_analysis/propagation.rs | 6 +- .../reducer/constants_reader.rs | 2 +- .../reducer/constants_writer.rs | 14 +- .../src/static_analysis/reducer/inline.rs | 14 +- .../src/static_analysis/reducer/mod.rs | 18 +- .../static_analysis/reducer/shallow_ssa.rs | 14 +- .../src/static_analysis/struct_concretizer.rs | 6 +- zokrates_core/src/static_analysis/trimmer.rs | 4 +- .../src/static_analysis/uint_optimizer.rs | 4 +- .../static_analysis/variable_write_remover.rs | 4 +- .../src/static_analysis/zir_propagation.rs | 22 +- zokrates_interpreter/Cargo.toml | 10 + zokrates_interpreter/src/lib.rs | 6 +- zokrates_libsnark/Cargo.toml | 15 + {zokrates_core => zokrates_libsnark}/build.rs | 6 - .../lib/ffi.cpp | 0 .../lib/ffi.hpp | 0 .../lib/gm17.cpp | 0 .../lib/gm17.hpp | 0 .../lib/pghr13.cpp | 0 .../lib/pghr13.hpp | 0 .../lib/util.tcc | 0 .../libsnark => zokrates_libsnark/src}/ffi.rs | 0 .../src}/gm17.rs | 0 .../mod.rs => zokrates_libsnark/src/lib.rs | 0 .../src}/pghr13.rs | 0 zokrates_proof_systems/Cargo.toml | 15 + .../src/lib.rs | 47 +- .../src}/scheme/gm17.rs | 24 +- .../src}/scheme/groth16.rs | 8 +- .../src}/scheme/marlin.rs | 10 +- .../src}/scheme/mod.rs | 0 .../src}/scheme/pghr13.rs | 6 +- .../src}/solidity.rs | 2 +- .../src}/to_token.rs | 29 +- zokrates_test/Cargo.toml | 9 + zokrates_test/src/lib.rs | 20 +- .../tests/out_of_range.rs | 6 +- .../tests/wasm.rs | 18 +- 100 files changed, 1146 insertions(+), 2178 deletions(-) rename zokrates_core/src/static_analysis/unconstrained_vars.rs => zokrates_ast/src/ir/check.rs (84%) create mode 100644 zokrates_bellman/Cargo.toml rename {zokrates_core/src/proof_system/bellman => zokrates_bellman/src}/groth16.rs (91%) rename zokrates_core/src/proof_system/bellman/mod.rs => zokrates_bellman/src/lib.rs (95%) delete mode 100644 zokrates_core/src/static_analysis/constant_inliner.rs create mode 100644 zokrates_libsnark/Cargo.toml rename {zokrates_core => zokrates_libsnark}/build.rs (96%) rename {zokrates_core => zokrates_libsnark}/lib/ffi.cpp (100%) rename {zokrates_core => zokrates_libsnark}/lib/ffi.hpp (100%) rename {zokrates_core => zokrates_libsnark}/lib/gm17.cpp (100%) rename {zokrates_core => zokrates_libsnark}/lib/gm17.hpp (100%) rename {zokrates_core => zokrates_libsnark}/lib/pghr13.cpp (100%) rename {zokrates_core => zokrates_libsnark}/lib/pghr13.hpp (100%) rename {zokrates_core => zokrates_libsnark}/lib/util.tcc (100%) rename {zokrates_core/src/proof_system/libsnark => zokrates_libsnark/src}/ffi.rs (100%) rename {zokrates_core/src/proof_system/libsnark => zokrates_libsnark/src}/gm17.rs (100%) rename zokrates_core/src/proof_system/libsnark/mod.rs => zokrates_libsnark/src/lib.rs (100%) rename {zokrates_core/src/proof_system/libsnark => zokrates_libsnark/src}/pghr13.rs (100%) create mode 100644 zokrates_proof_systems/Cargo.toml rename zokrates_core/src/proof_system/mod.rs => zokrates_proof_systems/src/lib.rs (80%) rename {zokrates_core/src/proof_system => zokrates_proof_systems/src}/scheme/gm17.rs (89%) rename {zokrates_core/src/proof_system => zokrates_proof_systems/src}/scheme/groth16.rs (96%) rename {zokrates_core/src/proof_system => zokrates_proof_systems/src}/scheme/marlin.rs (98%) rename {zokrates_core/src/proof_system => zokrates_proof_systems/src}/scheme/mod.rs (100%) rename {zokrates_core/src/proof_system => zokrates_proof_systems/src}/scheme/pghr13.rs (97%) rename {zokrates_core/src/proof_system => zokrates_proof_systems/src}/solidity.rs (99%) rename {zokrates_core/src/proof_system => zokrates_proof_systems/src}/to_token.rs (90%) rename {zokrates_core => zokrates_test}/tests/out_of_range.rs (97%) rename {zokrates_core => zokrates_test}/tests/wasm.rs (58%) diff --git a/Cargo.lock b/Cargo.lock index 3865c1d8..49b4bf2c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1065,17 +1065,6 @@ dependencies = [ "instant", ] -[[package]] -name = "ff_ce" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "83c0a6a2c53b0bd6d8cae976816dc8a171e0554c03f304e3dac110473e0219fd" -dependencies = [ - "byteorder", - "hex 0.4.3", - "rand 0.4.6", -] - [[package]] name = "ff_ce" version = "0.10.3" @@ -1671,7 +1660,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bfc00d65b1d29e0a067a967fcea83d8db261c149f76a557ba73f0304f01cdfde" dependencies = [ "byteorder", - "ff_ce 0.10.3", + "ff_ce", "rand 0.4.6", ] @@ -2827,7 +2816,7 @@ dependencies = [ "serde", "serde_derive", "serde_json", - "zokrates_core", + "zokrates_ast", "zokrates_field", ] @@ -2835,24 +2824,62 @@ dependencies = [ name = "zokrates_ark" version = "0.1.0" dependencies = [ + "ark-bls12-377", + "ark-bn254", + "ark-bw6-761", + "ark-crypto-primitives", + "ark-ec", + "ark-ff", + "ark-gm17", + "ark-groth16", + "ark-marlin", + "ark-poly", + "ark-poly-commit", + "ark-relations", + "ark-serialize", + "digest 0.9.0", + "hex 0.4.3", + "rand 0.8.5", + "sha3 0.9.1", "zokrates_ast", "zokrates_field", + "zokrates_interpreter", + "zokrates_proof_systems", ] [[package]] name = "zokrates_ast" version = "0.1.0" dependencies = [ + "ark-bls12-377", "cfg-if 0.1.10", "csv", "num-bigint 0.2.6", + "pairing_ce", "serde", "serde_cbor", "serde_json", + "zokrates_embed", "zokrates_field", "zokrates_pest_ast", ] +[[package]] +name = "zokrates_bellman" +version = "0.1.0" +dependencies = [ + "bellman_ce", + "getrandom", + "hex 0.4.3", + "pairing_ce", + "phase2", + "rand 0.4.6", + "zokrates_ast", + "zokrates_field", + "zokrates_interpreter", + "zokrates_proof_systems", +] + [[package]] name = "zokrates_cli" version = "0.7.13" @@ -2881,10 +2908,16 @@ dependencies = [ "tempdir", "typed-arena", "zokrates_abi", + "zokrates_ark", + "zokrates_ast", + "zokrates_bellman", "zokrates_common", "zokrates_core", "zokrates_field", "zokrates_fs_resolver", + "zokrates_interpreter", + "zokrates_libsnark", + "zokrates_proof_systems", "zokrates_solidity_test", ] @@ -2896,46 +2929,17 @@ version = "0.1.0" name = "zokrates_core" version = "0.6.12" dependencies = [ - "ark-bls12-377", - "ark-bn254", - "ark-bw6-761", - "ark-crypto-primitives", - "ark-ec", - "ark-ff", - "ark-gm17", - "ark-groth16", - "ark-marlin", - "ark-poly", - "ark-poly-commit", - "ark-relations", - "ark-serialize", - "bellman_ce", - "cc", "cfg-if 0.1.10", - "cmake", "csv", - "digest 0.9.0", - "ethabi", - "ff_ce 0.9.0", - "getrandom", - "hex 0.4.3", "lazy_static", "log", "num 0.1.42", "num-bigint 0.2.6", - "pairing_ce", - "phase2", "pretty_assertions", - "primitive-types", - "rand 0.4.6", - "rand 0.8.5", "reduce", - "regex 0.2.11", "serde", "serde_json", - "sha3 0.9.1", "typed-arena", - "wasm-bindgen-test", "zokrates_ast", "zokrates_common", "zokrates_embed", @@ -3007,12 +3011,25 @@ dependencies = [ name = "zokrates_interpreter" version = "0.1.0" dependencies = [ + "ark-bls12-377", "num 0.1.42", "num-bigint 0.2.6", + "pairing_ce", + "serde", "zokrates_ast", + "zokrates_embed", "zokrates_field", ] +[[package]] +name = "zokrates_libsnark" +version = "0.1.0" +dependencies = [ + "cc", + "cmake", + "zokrates_proof_systems", +] + [[package]] name = "zokrates_parser" version = "0.2.6" @@ -3034,6 +3051,21 @@ dependencies = [ "zokrates_parser", ] +[[package]] +name = "zokrates_proof_systems" +version = "0.1.0" +dependencies = [ + "cfg-if 0.1.10", + "ethabi", + "hex 0.4.3", + "primitive-types", + "rand 0.4.6", + "regex 0.2.11", + "serde", + "zokrates_ast", + "zokrates_field", +] + [[package]] name = "zokrates_solidity_test" version = "0.1.0" @@ -3065,10 +3097,16 @@ dependencies = [ "serde_derive", "serde_json", "typed-arena", + "wasm-bindgen-test", "zokrates_abi", + "zokrates_ark", + "zokrates_ast", + "zokrates_common", "zokrates_core", "zokrates_field", "zokrates_fs_resolver", + "zokrates_interpreter", + "zokrates_proof_systems", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index b93fb355..15ceed38 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,6 +15,8 @@ members = [ "zokrates_ast", "zokrates_interpreter", "zokrates_embed", + "zokrates_bellman", + "zokrates_proof_systems", ] -exclude = ["zokrates_js"] \ No newline at end of file +exclude = ["zokrates_js", "zokrates_libsnark"] \ No newline at end of file diff --git a/zokrates_abi/Cargo.toml b/zokrates_abi/Cargo.toml index bacda59f..1fccb51c 100644 --- a/zokrates_abi/Cargo.toml +++ b/zokrates_abi/Cargo.toml @@ -6,7 +6,7 @@ edition = "2018" [dependencies] zokrates_field = { version = "0.5", path = "../zokrates_field", default-features = false } -zokrates_core = { version = "0.6", path = "../zokrates_core", default-features = false } +zokrates_ast = { version = "0.1", path = "../zokrates_ast", default-features = false } serde = "1.0" serde_derive = "1.0" serde_json = { version = "1.0", features = ["preserve_order"] } diff --git a/zokrates_abi/src/lib.rs b/zokrates_abi/src/lib.rs index 80e3005e..59b7f40c 100644 --- a/zokrates_abi/src/lib.rs +++ b/zokrates_abi/src/lib.rs @@ -15,7 +15,7 @@ impl Encode for Inputs { } use std::fmt; -use zokrates_core::typed_absy::types::{ConcreteType, UBitwidth}; +use zokrates_ast::typed::types::{ConcreteType, UBitwidth}; use zokrates_field::Field; @@ -380,9 +380,7 @@ pub fn parse_strict_json( #[cfg(test)] mod tests { use super::*; - use zokrates_core::typed_absy::types::{ - ConcreteStructMember, ConcreteStructType, ConcreteType, - }; + use zokrates_ast::typed::types::{ConcreteStructMember, ConcreteStructType, ConcreteType}; use zokrates_field::Bn128Field; #[test] diff --git a/zokrates_ark/Cargo.toml b/zokrates_ark/Cargo.toml index 2658fc61..6c538640 100644 --- a/zokrates_ark/Cargo.toml +++ b/zokrates_ark/Cargo.toml @@ -8,3 +8,27 @@ edition = "2021" [dependencies] zokrates_field = { version = "0.5", path = "../zokrates_field", default-features = false } zokrates_ast = { version = "0.1", path = "../zokrates_ast", default-features = false } +zokrates_proof_systems = { version = "0.1", path = "../zokrates_proof_systems", default-features = false } + +ark-ff = { version = "^0.3.0", default-features = false } +ark-ec = { version = "^0.3.0", default-features = false } +ark-bn254 = { version = "^0.3.0", features = ["curve"], default-features = false } +ark-bls12-377 = { version = "^0.3.0", features = ["curve"], default-features = false } +ark-bw6-761 = { version = "^0.3.0", default-features = false } +ark-gm17 = { version = "^0.3.0", default-features = false } +ark-groth16 = { version = "^0.3.0", default-features = false } +ark-serialize = { version = "^0.3.0", default-features = false } +ark-relations = { version = "^0.3.0", default-features = false } +ark-marlin = { git = "https://github.com/arkworks-rs/marlin", rev = "63cfd82", default-features = false } +ark-poly = { version = "^0.3.0", default-features = false } +ark-poly-commit = { version = "^0.3.0", default-features = false } +ark-crypto-primitives = { version = "^0.3.0", default-features = false } +sha3 = { version = "0.9" } +digest = { version = "0.9" } +rand_0_8 = { version = "0.8", package = "rand" } +hex = "0.4.2" + +[dev-dependencies] +zokrates_interpreter = { version = "0.1", path = "../zokrates_interpreter" } + + diff --git a/zokrates_ark/src/gm17.rs b/zokrates_ark/src/gm17.rs index 6ef10a92..114e3403 100644 --- a/zokrates_ark/src/gm17.rs +++ b/zokrates_ark/src/gm17.rs @@ -4,19 +4,18 @@ use ark_gm17::{ VerifyingKey, GM17 as ArkGM17, }; use ark_serialize::{CanonicalDeserialize, CanonicalSerialize}; -use zokrates_field::{ArkFieldExtensions, Bw6_761Field, Field}; +use zokrates_field::{ArkFieldExtensions, Field}; -use crate::proof_system::ark::Computation; -use crate::proof_system::ark::{parse_fr, parse_g1, parse_g2, parse_g2_fq}; -use crate::proof_system::ark::{serialization, Ark}; -use crate::proof_system::gm17::{ProofPoints, VerificationKey, GM17}; -use crate::proof_system::{Backend, NonUniversalBackend, Proof, SetupKeypair}; -use crate::proof_system::{NotBw6_761Field, Scheme}; -use ark_bw6_761::BW6_761; +use crate::Computation; +use crate::{parse_fr, parse_g1, parse_g2}; +use crate::{serialization, Ark}; use rand_0_8::{rngs::StdRng, SeedableRng}; use zokrates_ast::ir::{ProgIterator, Statement, Witness}; +use zokrates_proof_systems::gm17::{ProofPoints, VerificationKey, GM17}; +use zokrates_proof_systems::Scheme; +use zokrates_proof_systems::{Backend, NonUniversalBackend, Proof, SetupKeypair}; -impl NonUniversalBackend for Ark { +impl NonUniversalBackend for Ark { fn setup>>( program: ProgIterator, ) -> SetupKeypair<>::VerificationKey> { @@ -41,7 +40,7 @@ impl NonUniversalBackend Backend for Ark { +impl Backend for Ark { fn generate_proof>>( program: ProgIterator, witness: Witness, @@ -109,107 +108,108 @@ impl Backend for Ark { } } -impl NonUniversalBackend for Ark { - fn setup>>( - program: ProgIterator, - ) -> SetupKeypair<>::VerificationKey> { - let computation = Computation::without_witness(program); +// impl NonUniversalBackend for Ark { +// fn setup>>( +// program: ProgIterator, +// ) -> SetupKeypair<>::VerificationKey> { +// let computation = Computation::without_witness(program); - let rng = &mut StdRng::from_entropy(); - let (pk, vk) = ArkGM17::::circuit_specific_setup(computation, rng).unwrap(); +// let rng = &mut StdRng::from_entropy(); +// let (pk, vk) = ArkGM17::::circuit_specific_setup(computation, rng).unwrap(); - let mut pk_vec: Vec = Vec::new(); - pk.serialize_uncompressed(&mut pk_vec).unwrap(); +// let mut pk_vec: Vec = Vec::new(); +// pk.serialize_uncompressed(&mut pk_vec).unwrap(); - let vk = VerificationKey { - h: parse_g2_fq::(&vk.h_g2), - g_alpha: parse_g1::(&vk.g_alpha_g1), - h_beta: parse_g2_fq::(&vk.h_beta_g2), - g_gamma: parse_g1::(&vk.g_gamma_g1), - h_gamma: parse_g2_fq::(&vk.h_gamma_g2), - query: vk.query.iter().map(parse_g1::).collect(), - }; +// let vk = VerificationKey { +// h: parse_g2_fq::(&vk.h_g2), +// g_alpha: parse_g1::(&vk.g_alpha_g1), +// h_beta: parse_g2_fq::(&vk.h_beta_g2), +// g_gamma: parse_g1::(&vk.g_gamma_g1), +// h_gamma: parse_g2_fq::(&vk.h_gamma_g2), +// query: vk.query.iter().map(parse_g1::).collect(), +// }; - SetupKeypair::new(vk, pk_vec) - } -} +// SetupKeypair::new(vk, pk_vec) +// } +// } -impl Backend for Ark { - fn generate_proof>>( - program: ProgIterator, - witness: Witness, - proving_key: Vec, - ) -> Proof { - let computation = Computation::with_witness(program, witness); +// impl Backend for Ark { +// fn generate_proof>>( +// program: ProgIterator, +// witness: Witness, +// proving_key: Vec, +// ) -> Proof { +// let computation = Computation::with_witness(program, witness); - let inputs = computation - .public_inputs_values() - .iter() - .map(parse_fr::) - .collect::>(); +// let inputs = computation +// .public_inputs_values() +// .iter() +// .map(parse_fr::) +// .collect::>(); - let pk = - ProvingKey::<::ArkEngine>::deserialize_uncompressed( - &mut proving_key.as_slice(), - ) - .unwrap(); +// let pk = +// ProvingKey::<::ArkEngine>::deserialize_uncompressed( +// &mut proving_key.as_slice(), +// ) +// .unwrap(); - let rng = &mut StdRng::from_entropy(); - let proof = ArkGM17::::prove(&pk, computation, rng).unwrap(); +// let rng = &mut StdRng::from_entropy(); +// let proof = ArkGM17::::prove(&pk, computation, rng).unwrap(); - let proof_points = ProofPoints { - a: parse_g1::(&proof.a), - b: parse_g2_fq::(&proof.b), - c: parse_g1::(&proof.c), - }; +// let proof_points = ProofPoints { +// a: parse_g1::(&proof.a), +// b: parse_g2_fq::(&proof.b), +// c: parse_g1::(&proof.c), +// }; - Proof::new(proof_points, inputs) - } +// Proof::new(proof_points, inputs) +// } - fn verify( - vk: >::VerificationKey, - 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(serialization::to_g1::) - .collect(), - }; +// fn verify( +// vk: >::VerificationKey, +// 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(serialization::to_g1::) +// .collect(), +// }; - let ark_proof = ArkProof { - a: serialization::to_g1::(proof.proof.a), - b: serialization::to_g2_fq::(proof.proof.b), - c: serialization::to_g1::(proof.proof.c), - }; +// let ark_proof = ArkProof { +// 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<::ArkEngine> = - prepare_verifying_key(&vk); +// let pvk: PreparedVerifyingKey<::ArkEngine> = +// prepare_verifying_key(&vk); - let public_inputs: Vec<_> = proof - .inputs - .iter() - .map(|s| { - Bw6_761Field::try_from_str(s.trim_start_matches("0x"), 16) - .unwrap() - .into_ark() - }) - .collect::>(); +// let public_inputs: Vec<_> = proof +// .inputs +// .iter() +// .map(|s| { +// Bw6_761Field::try_from_str(s.trim_start_matches("0x"), 16) +// .unwrap() +// .into_ark() +// }) +// .collect::>(); - verify_proof(&pvk, &ark_proof, &public_inputs).unwrap() - } -} +// verify_proof(&pvk, &ark_proof, &public_inputs).unwrap() +// } +// } #[cfg(test)] mod tests { - use crate::flat_absy::{FlatParameter, FlatVariable}; - use zokrates_ast::ir::{Interpreter, Prog, Statement}; + use zokrates_ast::flat::{Parameter, Variable}; + use zokrates_ast::ir::{Prog, Statement}; + use zokrates_interpreter::Interpreter; use super::*; use zokrates_field::{Bls12_377Field, Bw6_761Field}; @@ -217,12 +217,9 @@ mod tests { #[test] fn verify_bls12_377_field() { let program: Prog = Prog { - arguments: vec![FlatParameter::public(FlatVariable::new(0))], + arguments: vec![Parameter::public(Variable::new(0))], return_count: 1, - statements: vec![Statement::constraint( - FlatVariable::new(0), - FlatVariable::public(0), - )], + statements: vec![Statement::constraint(Variable::new(0), Variable::public(0))], }; let keypair = >::setup(program.clone()); @@ -242,12 +239,9 @@ mod tests { #[test] fn verify_bw6_761_field() { let program: Prog = Prog { - arguments: vec![FlatParameter::public(FlatVariable::new(0))], + arguments: vec![Parameter::public(Variable::new(0))], return_count: 1, - statements: vec![Statement::constraint( - FlatVariable::new(0), - FlatVariable::public(0), - )], + statements: vec![Statement::constraint(Variable::new(0), Variable::public(0))], }; let keypair = >::setup(program.clone()); diff --git a/zokrates_ark/src/groth16.rs b/zokrates_ark/src/groth16.rs index 13fc867f..58fb124c 100644 --- a/zokrates_ark/src/groth16.rs +++ b/zokrates_ark/src/groth16.rs @@ -1,25 +1,24 @@ -use crate::proof_system::{Backend, NonUniversalBackend, NotBw6_761Field, Proof, SetupKeypair}; use ark_crypto_primitives::SNARK; use ark_groth16::{ prepare_verifying_key, verify_proof, Groth16, PreparedVerifyingKey, Proof as ArkProof, ProvingKey, VerifyingKey, }; use ark_serialize::{CanonicalDeserialize, CanonicalSerialize}; +use zokrates_field::ArkFieldExtensions; use zokrates_field::Field; -use zokrates_field::{ArkFieldExtensions, Bw6_761Field}; +use zokrates_proof_systems::{Backend, NonUniversalBackend, Proof, SetupKeypair}; -use crate::proof_system::ark::Computation; -use crate::proof_system::ark::{parse_fr, serialization, Ark}; -use crate::proof_system::ark::{parse_g1, parse_g2}; -use crate::proof_system::groth16::{ProofPoints, VerificationKey, G16}; -use crate::proof_system::Scheme; -use ark_bw6_761::BW6_761; +use crate::Computation; +use crate::{parse_fr, serialization, Ark}; +use crate::{parse_g1, parse_g2}; use rand_0_8::{rngs::StdRng, SeedableRng}; use zokrates_ast::ir::{ProgIterator, Statement, Witness}; +use zokrates_proof_systems::groth16::{ProofPoints, VerificationKey, G16}; +use zokrates_proof_systems::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."; -impl Backend for Ark { +impl Backend for Ark { fn generate_proof>>( program: ProgIterator, witness: Witness, @@ -86,7 +85,7 @@ impl Backend for Ark { } } -impl NonUniversalBackend for Ark { +impl NonUniversalBackend for Ark { fn setup>>( program: ProgIterator, ) -> SetupKeypair<>::VerificationKey> { @@ -112,108 +111,11 @@ impl NonUniversalBackend for Ark { - fn generate_proof>>( - program: ProgIterator, - witness: Witness, - proving_key: Vec, - ) -> Proof { - println!("{}", G16_WARNING); - - let computation = Computation::with_witness(program, witness); - - let inputs = computation - .public_inputs_values() - .iter() - .map(parse_fr::) - .collect::>(); - - let pk = - ProvingKey::::deserialize_uncompressed(&mut proving_key.as_slice()).unwrap(); - - let rng = &mut StdRng::from_entropy(); - let proof = Groth16::::prove(&pk, computation, rng).unwrap(); - - let proof_points = ProofPoints { - a: parse_g1::(&proof.a), - b: parse_g2::(&proof.b), - c: parse_g1::(&proof.c), - }; - - Proof::new(proof_points, inputs) - } - - fn verify( - vk: >::VerificationKey, - proof: Proof, - ) -> bool { - let vk = VerifyingKey { - alpha_g1: serialization::to_g1::(vk.alpha), - beta_g2: serialization::to_g2::(vk.beta), - gamma_g2: serialization::to_g2::(vk.gamma), - delta_g2: serialization::to_g2::(vk.delta), - gamma_abc_g1: vk - .gamma_abc - .into_iter() - .map(serialization::to_g1::) - .collect(), - }; - - let pvk: PreparedVerifyingKey = prepare_verifying_key(&vk); - let ark_proof = ArkProof { - 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 - .iter() - .map(|s| { - Bw6_761Field::try_from_str(s.trim_start_matches("0x"), 16) - .unwrap() - .into_ark() - }) - .collect::>(); - - verify_proof(&pvk, &ark_proof, &public_inputs).unwrap() - } -} - -impl NonUniversalBackend for Ark { - fn setup>>( - program: ProgIterator, - ) -> SetupKeypair<>::VerificationKey> { - println!("{}", G16_WARNING); - - let computation = Computation::without_witness(program); - - let rng = &mut StdRng::from_entropy(); - let (pk, vk) = Groth16::::circuit_specific_setup(computation, rng).unwrap(); - - let mut pk_vec: Vec = Vec::new(); - pk.serialize_uncompressed(&mut pk_vec).unwrap(); - - let vk = VerificationKey { - alpha: parse_g1::(&vk.alpha_g1), - beta: parse_g2::(&vk.beta_g2), - gamma: parse_g2::(&vk.gamma_g2), - delta: parse_g2::(&vk.delta_g2), - gamma_abc: vk - .gamma_abc_g1 - .iter() - .map(parse_g1::) - .collect(), - }; - - SetupKeypair::new(vk, pk_vec) - } -} - #[cfg(test)] mod tests { - use crate::flat_absy::{FlatParameter, FlatVariable}; - use zokrates_ast::ir::{Interpreter, Prog, Statement}; + use zokrates_ast::flat::{Parameter, Variable}; + use zokrates_ast::ir::{Prog, Statement}; + use zokrates_interpreter::Interpreter; use super::*; use zokrates_field::{Bls12_377Field, Bw6_761Field}; @@ -221,12 +123,9 @@ mod tests { #[test] fn verify_bls12_377_field() { let program: Prog = Prog { - arguments: vec![FlatParameter::public(FlatVariable::new(0))], + arguments: vec![Parameter::public(Variable::new(0))], return_count: 1, - statements: vec![Statement::constraint( - FlatVariable::new(0), - FlatVariable::public(0), - )], + statements: vec![Statement::constraint(Variable::new(0), Variable::public(0))], }; let keypair = >::setup(program.clone()); @@ -249,12 +148,9 @@ mod tests { #[test] fn verify_bw6_761_field() { let program: Prog = Prog { - arguments: vec![FlatParameter::public(FlatVariable::new(0))], + arguments: vec![Parameter::public(Variable::new(0))], return_count: 1, - statements: vec![Statement::constraint( - FlatVariable::new(0), - FlatVariable::public(0), - )], + statements: vec![Statement::constraint(Variable::new(0), Variable::public(0))], }; let keypair = >::setup(program.clone()); diff --git a/zokrates_ark/src/lib.rs b/zokrates_ark/src/lib.rs index 40f090c6..b64ef9f0 100644 --- a/zokrates_ark/src/lib.rs +++ b/zokrates_ark/src/lib.rs @@ -2,16 +2,22 @@ pub mod gm17; pub mod groth16; pub mod marlin; -use crate::flat_absy::FlatVariable; use ark_ec::PairingEngine; use ark_relations::r1cs::{ ConstraintSynthesizer, ConstraintSystem, ConstraintSystemRef, LinearCombination, - SynthesisError, Variable, + SynthesisError, Variable as ArkVariable, }; use std::collections::BTreeMap; +use zokrates_ast::common::Variable; use zokrates_ast::ir::{CanonicalLinComb, ProgIterator, Statement, Witness}; use zokrates_field::{ArkFieldExtensions, Field}; +use zokrates_field::{Bls12_377Field, Bls12_381Field, Bn128Field}; +pub trait NotBw6_761Field {} +impl NotBw6_761Field for Bls12_377Field {} +impl NotBw6_761Field for Bls12_381Field {} +impl NotBw6_761Field for Bn128Field {} + pub use self::parse::*; pub struct Ark; @@ -41,7 +47,7 @@ impl>> Computation { fn ark_combination( l: CanonicalLinComb, cs: &mut ConstraintSystem<<::ArkEngine as PairingEngine>::Fr>, - symbols: &mut BTreeMap, + symbols: &mut BTreeMap, witness: &mut Witness, ) -> LinearCombination<<::ArkEngine as PairingEngine>::Fr> { l.0.into_iter() @@ -72,23 +78,35 @@ fn ark_combination( .fold(LinearCombination::zero(), |acc, e| acc + e) } -impl>> ProgIterator { - pub fn generate_constraints( +impl>> Computation { + pub fn public_inputs_values(&self) -> Vec<::Fr> { + self.program + .public_inputs(self.witness.as_ref().unwrap()) + .iter() + .map(|v| v.clone().into_ark()) + .collect() + } +} + +impl>> + ConstraintSynthesizer<<::ArkEngine as PairingEngine>::Fr> + for Computation +{ + fn generate_constraints( self, cs: ConstraintSystemRef<<::ArkEngine as PairingEngine>::Fr>, - witness: Option>, ) -> Result<(), SynthesisError> { // mapping from IR variables let mut symbols = BTreeMap::new(); - let mut witness = witness.unwrap_or_else(Witness::empty); + let mut witness = self.witness.unwrap_or_else(Witness::empty); - assert!(symbols.insert(FlatVariable::one(), ConstraintSystem::<<::ArkEngine as PairingEngine>::Fr>::one()).is_none()); + assert!(symbols.insert(Variable::one(), ConstraintSystem::<<::ArkEngine as PairingEngine>::Fr>::one()).is_none()); match cs { ConstraintSystemRef::CS(rc) => { let mut cs = rc.borrow_mut(); - symbols.extend(self.arguments.iter().enumerate().map(|(_, p)| { + symbols.extend(self.program.arguments.iter().enumerate().map(|(_, p)| { let wire = match p.private { true => cs.new_witness_variable(|| { Ok(witness @@ -109,7 +127,7 @@ impl>> ProgIt (p.id, wire) })); - for statement in self.statements { + for statement in self.program.statements { if let Statement::Constraint(quad, lin, _) = statement { let a = ark_combination( quad.left.clone().into_canonical(), @@ -141,32 +159,10 @@ impl>> ProgIt } } -impl>> Computation { - pub fn public_inputs_values(&self) -> Vec<::Fr> { - self.program - .public_inputs(self.witness.as_ref().unwrap()) - .iter() - .map(|v| v.clone().into_ark()) - .collect() - } -} - -impl>> - ConstraintSynthesizer<<::ArkEngine as PairingEngine>::Fr> - for Computation -{ - fn generate_constraints( - self, - cs: ConstraintSystemRef<<::ArkEngine as PairingEngine>::Fr>, - ) -> Result<(), SynthesisError> { - self.program.generate_constraints(cs, self.witness) - } -} - mod parse { use super::*; - use crate::proof_system::{Fr, G1Affine, G2Affine, G2AffineFq}; use ark_ff::ToBytes; + use zokrates_proof_systems::{Fr, G1Affine, G2Affine, G2AffineFq, G2AffineFq2}; pub fn parse_g1( e: &::G1Affine, @@ -207,7 +203,7 @@ mod parse { elements.push(e); } - G2Affine( + G2Affine::Fq2(G2AffineFq2( ( format!("0x{}", hex::encode(&elements[0])), format!("0x{}", hex::encode(&elements[1])), @@ -216,12 +212,12 @@ mod parse { format!("0x{}", hex::encode(&elements[2])), format!("0x{}", hex::encode(&elements[3])), ), - ) + )) } pub fn parse_g2_fq( e: &::G2Affine, - ) -> G2AffineFq { + ) -> G2Affine { let mut bytes: Vec = Vec::new(); e.write(&mut bytes).unwrap(); @@ -234,10 +230,10 @@ mod parse { x.reverse(); y.reverse(); - G2AffineFq( + G2Affine::Fq(G2AffineFq( format!("0x{}", hex::encode(&x)), format!("0x{}", hex::encode(&y)), - ) + )) } pub fn parse_fr(e: &::Fr) -> Fr { @@ -250,10 +246,10 @@ mod parse { } pub mod serialization { - use crate::proof_system::{G1Affine, G2Affine, G2AffineFq}; use ark_ec::PairingEngine; use ark_ff::FromBytes; use zokrates_field::ArkFieldExtensions; + use zokrates_proof_systems::{G1Affine, G2Affine}; #[inline] fn decode_hex(value: String) -> Vec { @@ -273,22 +269,21 @@ pub mod serialization { pub fn to_g2(g2: G2Affine) -> ::G2Affine { 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 mut bytes = vec![]; - bytes.append(&mut decode_hex(g2.0)); - bytes.append(&mut decode_hex(g2.1)); - bytes.push(0u8); // infinity flag + match g2 { + G2Affine::Fq(g2) => { + bytes.append(&mut decode_hex(g2.0)); + bytes.append(&mut decode_hex(g2.1)); + bytes.push(0u8); // infinity flag + } + G2Affine::Fq2(g2) => { + 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() } diff --git a/zokrates_ark/src/marlin.rs b/zokrates_ark/src/marlin.rs index 576acd84..2ed6a4de 100644 --- a/zokrates_ark/src/marlin.rs +++ b/zokrates_ark/src/marlin.rs @@ -23,13 +23,13 @@ use std::marker::PhantomData; use zokrates_field::{ArkFieldExtensions, Field}; -use crate::proof_system::ark::Ark; -use crate::proof_system::ark::Computation; -use crate::proof_system::ark::{parse_fr, parse_g1, parse_g2, serialization}; -use crate::proof_system::marlin::{self, KZGVerifierKey, ProofPoints, VerificationKey}; -use crate::proof_system::Scheme; -use crate::proof_system::{Backend, Proof, SetupKeypair, UniversalBackend}; +use crate::Ark; +use crate::Computation; +use crate::{parse_fr, parse_g1, parse_g2, serialization}; use zokrates_ast::ir::{ProgIterator, Statement, Witness}; +use zokrates_proof_systems::marlin::{self, KZGVerifierKey, ProofPoints, VerificationKey}; +use zokrates_proof_systems::Scheme; +use zokrates_proof_systems::{Backend, Proof, SetupKeypair, UniversalBackend}; const MINIMUM_CONSTRAINT_COUNT: usize = 2; @@ -386,27 +386,28 @@ impl Backend for Ark { #[cfg(test)] mod tests { - use crate::flat_absy::{FlatParameter, FlatVariable}; - use zokrates_ast::ir::{Interpreter, Prog, QuadComb, Statement}; + use zokrates_ast::flat::{Parameter, Variable}; + use zokrates_ast::ir::{Prog, QuadComb, Statement}; + use zokrates_interpreter::Interpreter; use super::*; - use crate::proof_system::scheme::Marlin; use zokrates_field::{Bls12_377Field, Bw6_761Field}; + use zokrates_proof_systems::Marlin; #[test] fn verify_bls12_377_field() { let program: Prog = Prog { - arguments: vec![FlatParameter::private(FlatVariable::new(0))], + arguments: vec![Parameter::private(Variable::new(0))], return_count: 1, statements: vec![ Statement::constraint( QuadComb::from_linear_combinations( - FlatVariable::new(0).into(), - FlatVariable::new(0).into(), + Variable::new(0).into(), + Variable::new(0).into(), ), - FlatVariable::new(1), + Variable::new(1), ), - Statement::constraint(FlatVariable::new(1), FlatVariable::public(0)), + Statement::constraint(Variable::new(1), Variable::public(0)), ], }; @@ -429,17 +430,17 @@ mod tests { #[test] fn verify_bw6_761_field() { let program: Prog = Prog { - arguments: vec![FlatParameter::private(FlatVariable::new(0))], + arguments: vec![Parameter::private(Variable::new(0))], return_count: 1, statements: vec![ Statement::constraint( QuadComb::from_linear_combinations( - FlatVariable::new(0).into(), - FlatVariable::new(0).into(), + Variable::new(0).into(), + Variable::new(0).into(), ), - FlatVariable::new(1), + Variable::new(1), ), - Statement::constraint(FlatVariable::new(1), FlatVariable::public(0)), + Statement::constraint(Variable::new(1), Variable::public(0)), ], }; diff --git a/zokrates_ast/Cargo.toml b/zokrates_ast/Cargo.toml index 63288786..8f27808f 100644 --- a/zokrates_ast/Cargo.toml +++ b/zokrates_ast/Cargo.toml @@ -3,7 +3,10 @@ name = "zokrates_ast" version = "0.1.0" edition = "2021" -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html +[features] +default = ["bellman", "ark"] +bellman = ["zokrates_field/bellman", "pairing_ce"] +ark = ["ark-bls12-377"] [dependencies] zokrates_pest_ast = { version = "0.2.0", path = "../zokrates_pest_ast" } @@ -14,6 +17,9 @@ csv = "1" serde_cbor = "0.11.2" num-bigint = { version = "0.2", default-features = false } serde_json = { version = "1.0", features = ["preserve_order"] } +zokrates_embed = { version = "0.1.0", path = "../zokrates_embed" } +pairing_ce = { version = "^0.21", optional = true } +ark-bls12-377 = { version = "^0.3.0", features = ["curve"], default-features = false, optional = true } diff --git a/zokrates_ast/src/common/embed.rs b/zokrates_ast/src/common/embed.rs index 47551172..71342c00 100644 --- a/zokrates_ast/src/common/embed.rs +++ b/zokrates_ast/src/common/embed.rs @@ -344,7 +344,6 @@ fn flat_expression_from_vec(v: &[(usize, T)]) -> FlatExpression { #[cfg(feature = "bellman")] pub fn sha256_round( ) -> FlatFunctionIterator>> { - use zokrates_ast::ir::RuntimeError; use zokrates_field::Bn128Field; assert_eq!(T::id(), Bn128Field::id()); @@ -449,7 +448,6 @@ pub fn sha256_round( pub fn snark_verify_bls12_377( n: usize, ) -> FlatFunctionIterator>> { - use zokrates_ast::ir::RuntimeError; use zokrates_field::Bw6_761Field; assert_eq!(T::id(), Bw6_761Field::id()); @@ -695,72 +693,73 @@ mod tests { } } - #[cfg(feature = "bellman")] - #[cfg(test)] - mod sha256 { - use super::*; - use zokrates_ast::ir::Interpreter; + // MOVE TO CORE + // #[cfg(feature = "bellman")] + // #[cfg(test)] + // mod sha256 { + // use super::*; + // use crate::ir::Interpreter; - #[test] - fn generate_sha256_constraints() { - let compiled = sha256_round::(); + // #[test] + // fn generate_sha256_constraints() { + // let compiled = sha256_round::(); - let compiled = compiled.collect(); + // let compiled = compiled.collect(); - // function should have 768 inputs - assert_eq!(compiled.arguments.len(), 768); + // // function should have 768 inputs + // assert_eq!(compiled.arguments.len(), 768); - // function should return 256 values - assert_eq!(compiled.return_count, 256,); + // // function should return 256 values + // assert_eq!(compiled.return_count, 256,); - // directive should take 768 inputs and return n_var outputs - let directive = compiled - .statements - .iter() - .filter_map(|s| match s { - FlatStatement::Directive(d) => Some(d.clone()), - _ => None, - }) - .next() - .unwrap(); - assert_eq!(directive.inputs.len(), 768); - assert_eq!(directive.outputs.len(), 26935); - // function input should be offset by variable_count - assert_eq!( - compiled.arguments[0].id, - Variable::new(directive.outputs.len() + 1) - ); + // // directive should take 768 inputs and return n_var outputs + // let directive = compiled + // .statements + // .iter() + // .filter_map(|s| match s { + // FlatStatement::Directive(d) => Some(d.clone()), + // _ => None, + // }) + // .next() + // .unwrap(); + // assert_eq!(directive.inputs.len(), 768); + // assert_eq!(directive.outputs.len(), 26935); + // // function input should be offset by variable_count + // assert_eq!( + // compiled.arguments[0].id, + // Variable::new(directive.outputs.len() + 1) + // ); - // bellman variable #0: index 0 should equal 1 - assert_eq!( - compiled.statements[1], - FlatStatement::Condition( - Variable::new(0).into(), - FlatExpression::Number(Bn128Field::from(1)), - RuntimeError::BellmanOneBinding - ) - ); + // // bellman variable #0: index 0 should equal 1 + // assert_eq!( + // compiled.statements[1], + // FlatStatement::Condition( + // Variable::new(0).into(), + // FlatExpression::Number(Bn128Field::from(1)), + // RuntimeError::BellmanOneBinding + // ) + // ); - // bellman input #0: index 1 should equal zokrates input #0: index v_count - assert_eq!( - compiled.statements[2], - FlatStatement::Condition( - Variable::new(1).into(), - Variable::new(26936).into(), - RuntimeError::BellmanInputBinding - ) - ); + // // bellman input #0: index 1 should equal zokrates input #0: index v_count + // assert_eq!( + // compiled.statements[2], + // FlatStatement::Condition( + // Variable::new(1).into(), + // Variable::new(26936).into(), + // RuntimeError::BellmanInputBinding + // ) + // ); - let input: Vec<_> = (0..512) - .map(|_| 0) - .chain((0..256).map(|_| 1)) - .map(Bn128Field::from) - .collect(); + // let input: Vec<_> = (0..512) + // .map(|_| 0) + // .chain((0..256).map(|_| 1)) + // .map(Bn128Field::from) + // .collect(); - let ir = zokrates_ast::ir::from_flat::from_flat(compiled); + // let ir = zokrates_ast::ir::from_flat::from_flat(compiled); - let interpreter = Interpreter::default(); - interpreter.execute(ir, &input).unwrap(); - } - } + // let interpreter = Interpreter::default(); + // interpreter.execute(ir, &input).unwrap(); + // } + // } } diff --git a/zokrates_ast/src/common/error.rs b/zokrates_ast/src/common/error.rs index c1fe0656..f1d8b2d1 100644 --- a/zokrates_ast/src/common/error.rs +++ b/zokrates_ast/src/common/error.rs @@ -32,6 +32,15 @@ pub enum RuntimeError { SelectRangeCheck, } +impl From for RuntimeError { + fn from(error: crate::zir::RuntimeError) -> Self { + match error { + crate::zir::RuntimeError::SourceAssertion(s) => RuntimeError::SourceAssertion(s), + crate::zir::RuntimeError::SelectRangeCheck => RuntimeError::SelectRangeCheck, + } + } +} + impl RuntimeError { pub fn is_malicious(&self) -> bool { use RuntimeError::*; diff --git a/zokrates_ast/src/flat/folder.rs b/zokrates_ast/src/flat/folder.rs index a000c8b4..254f2d5f 100644 --- a/zokrates_ast/src/flat/folder.rs +++ b/zokrates_ast/src/flat/folder.rs @@ -50,22 +50,37 @@ pub fn fold_statement>( f: &mut F, s: FlatStatement, ) -> Vec> { - // match s { - // Statement::Constraint(quad, lin, message) => vec![Statement::Constraint( - // f.fold_quadratic_combination(quad), - // f.fold_linear_combination(lin), - // message, - // )], - // Statement::Directive(dir) => vec![Statement::Directive(f.fold_directive(dir))], - // } - unimplemented!() + match s { + FlatStatement::Condition(left, right, error) => vec![FlatStatement::Condition( + f.fold_expression(left), + f.fold_expression(right), + error, + )], + FlatStatement::Definition(v, e) => vec![FlatStatement::Definition( + f.fold_variable(v), + f.fold_expression(e), + )], + FlatStatement::Directive(d) => vec![FlatStatement::Directive(f.fold_directive(d))], + } } pub fn fold_expression>( f: &mut F, e: FlatExpression, ) -> FlatExpression { - unimplemented!() + match e { + FlatExpression::Number(n) => FlatExpression::Number(n), + FlatExpression::Identifier(id) => FlatExpression::Identifier(f.fold_variable(id)), + FlatExpression::Add(box left, box right) => { + FlatExpression::Add(box f.fold_expression(left), box f.fold_expression(right)) + } + FlatExpression::Sub(box left, box right) => { + FlatExpression::Sub(box f.fold_expression(left), box f.fold_expression(right)) + } + FlatExpression::Mult(box left, box right) => { + FlatExpression::Mult(box f.fold_expression(left), box f.fold_expression(right)) + } + } } pub fn fold_directive>(f: &mut F, ds: FlatDirective) -> FlatDirective { diff --git a/zokrates_core/src/static_analysis/unconstrained_vars.rs b/zokrates_ast/src/ir/check.rs similarity index 84% rename from zokrates_core/src/static_analysis/unconstrained_vars.rs rename to zokrates_ast/src/ir/check.rs index ad52b4d8..11c5fd84 100644 --- a/zokrates_core/src/static_analysis/unconstrained_vars.rs +++ b/zokrates_ast/src/ir/check.rs @@ -1,10 +1,10 @@ +use crate::ir::folder::Folder; +use crate::ir::Directive; +use crate::ir::Parameter; +use crate::ir::ProgIterator; +use crate::ir::Statement; +use crate::ir::Variable; use std::collections::HashSet; -use zokrates_ast::ir::folder::Folder; -use zokrates_ast::ir::Directive; -use zokrates_ast::ir::Parameter; -use zokrates_ast::ir::ProgIterator; -use zokrates_ast::ir::Statement; -use zokrates_ast::ir::Variable; use zokrates_field::Field; #[derive(Debug)] diff --git a/zokrates_ast/src/ir/from_flat.rs b/zokrates_ast/src/ir/from_flat.rs index c6a4e4e5..abe2b075 100644 --- a/zokrates_ast/src/ir/from_flat.rs +++ b/zokrates_ast/src/ir/from_flat.rs @@ -1,7 +1,5 @@ -use crate::flat_absy::{ - FlatDirective, FlatExpression, FlatProgIterator, FlatStatement, FlatVariable, -}; -use zokrates_ast::ir::{Directive, LinComb, ProgIterator, QuadComb, Statement}; +use crate::flat::{FlatDirective, FlatExpression, FlatProgIterator, FlatStatement, Variable}; +use crate::ir::{Directive, LinComb, ProgIterator, QuadComb, Statement}; use zokrates_field::Field; impl QuadComb { @@ -33,7 +31,7 @@ impl From> for LinComb { fn from(flat_expression: FlatExpression) -> LinComb { match flat_expression { FlatExpression::Number(ref n) if *n == T::from(0) => LinComb::zero(), - FlatExpression::Number(n) => LinComb::summand(n, FlatVariable::one()), + FlatExpression::Number(n) => LinComb::summand(n, Variable::one()), FlatExpression::Identifier(id) => LinComb::from(id), FlatExpression::Add(box e1, box e2) => LinComb::from(e1) + LinComb::from(e2), FlatExpression::Sub(box e1, box e2) => LinComb::from(e1) - LinComb::from(e2), @@ -48,7 +46,7 @@ impl From> for LinComb { FlatExpression::Mult( box FlatExpression::Number(n1), box FlatExpression::Number(n2), - ) => LinComb::summand(n1 * n2, FlatVariable::one()), + ) => LinComb::summand(n1 * n2, Variable::one()), e => unreachable!("{}", e), } } @@ -109,7 +107,7 @@ mod tests { fn one() { // 1 let one = FlatExpression::Number(Bn128Field::from(1)); - let expected: LinComb = FlatVariable::one().into(); + let expected: LinComb = Variable::one().into(); assert_eq!(LinComb::from(one), expected); } @@ -117,7 +115,7 @@ mod tests { fn forty_two() { // 42 let one = FlatExpression::Number(Bn128Field::from(42)); - let expected: LinComb = LinComb::summand(42, FlatVariable::one()); + let expected: LinComb = LinComb::summand(42, Variable::one()); assert_eq!(LinComb::from(one), expected); } @@ -125,11 +123,11 @@ mod tests { fn add() { // x + y let add = FlatExpression::Add( - box FlatExpression::Identifier(FlatVariable::new(42)), - box FlatExpression::Identifier(FlatVariable::new(21)), + box FlatExpression::Identifier(Variable::new(42)), + box FlatExpression::Identifier(Variable::new(21)), ); let expected: LinComb = - LinComb::summand(1, FlatVariable::new(42)) + LinComb::summand(1, FlatVariable::new(21)); + LinComb::summand(1, Variable::new(42)) + LinComb::summand(1, Variable::new(21)); assert_eq!(LinComb::from(add), expected); } @@ -139,15 +137,15 @@ mod tests { let add = FlatExpression::Add( box FlatExpression::Mult( box FlatExpression::Number(Bn128Field::from(42)), - box FlatExpression::Identifier(FlatVariable::new(42)), + box FlatExpression::Identifier(Variable::new(42)), ), box FlatExpression::Mult( box FlatExpression::Number(Bn128Field::from(21)), - box FlatExpression::Identifier(FlatVariable::new(21)), + box FlatExpression::Identifier(Variable::new(21)), ), ); - let expected: LinComb = LinComb::summand(42, FlatVariable::new(42)) - + LinComb::summand(21, FlatVariable::new(21)); + let expected: LinComb = + LinComb::summand(42, Variable::new(42)) + LinComb::summand(21, Variable::new(21)); assert_eq!(LinComb::from(add), expected); } @@ -156,16 +154,16 @@ mod tests { // x*42 + y*21 let add = FlatExpression::Add( box FlatExpression::Mult( - box FlatExpression::Identifier(FlatVariable::new(42)), + box FlatExpression::Identifier(Variable::new(42)), box FlatExpression::Number(Bn128Field::from(42)), ), box FlatExpression::Mult( - box FlatExpression::Identifier(FlatVariable::new(21)), + box FlatExpression::Identifier(Variable::new(21)), box FlatExpression::Number(Bn128Field::from(21)), ), ); - let expected: LinComb = LinComb::summand(42, FlatVariable::new(42)) - + LinComb::summand(21, FlatVariable::new(21)); + let expected: LinComb = + LinComb::summand(42, Variable::new(42)) + LinComb::summand(21, Variable::new(21)); assert_eq!(LinComb::from(add), expected); } } diff --git a/zokrates_ast/src/ir/mod.rs b/zokrates_ast/src/ir/mod.rs index 430b1525..e8dff12b 100644 --- a/zokrates_ast/src/ir/mod.rs +++ b/zokrates_ast/src/ir/mod.rs @@ -4,9 +4,10 @@ use std::fmt; use std::hash::Hash; use zokrates_field::Field; +mod check; mod expression; pub mod folder; -//pub mod from_flat; +pub mod from_flat; mod serialize; pub mod smtlib2; pub mod visitor; diff --git a/zokrates_ast/src/ir/serialize.rs b/zokrates_ast/src/ir/serialize.rs index ea03f00d..0737c31e 100644 --- a/zokrates_ast/src/ir/serialize.rs +++ b/zokrates_ast/src/ir/serialize.rs @@ -1,3 +1,5 @@ +use crate::ir::check::UnconstrainedVariableDetector; + use super::{ProgIterator, Statement}; use serde_cbor::{self, StreamDeserializer}; use std::io::{Read, Write}; @@ -57,7 +59,7 @@ impl>> ProgIterator { /// serialize a program iterator, returning the number of constraints serialized /// Note that we only return constraints, not other statements such as directives pub fn serialize(self, mut w: W) -> Result { - //use super::folder::Folder; + use super::folder::Folder; w.write_all(ZOKRATES_MAGIC)?; w.write_all(ZOKRATES_VERSION_2)?; @@ -66,7 +68,7 @@ impl>> ProgIterator { serde_cbor::to_writer(&mut w, &self.arguments)?; serde_cbor::to_writer(&mut w, &self.return_count)?; - //let mut unconstrained_variable_detector = UnconstrainedVariableDetector::new(&self); + let mut unconstrained_variable_detector = UnconstrainedVariableDetector::new(&self); let statements = self.statements.into_iter(); @@ -75,17 +77,16 @@ impl>> ProgIterator { if matches!(s, Statement::Constraint(..)) { count += 1; } - //let s = unconstrained_variable_detector.fold_statement(s); - //for s in s { - serde_cbor::to_writer(&mut w, &s)?; - //} + let s = unconstrained_variable_detector.fold_statement(s); + for s in s { + serde_cbor::to_writer(&mut w, &s)?; + } } - // unconstrained_variable_detector - // .finalize() - // .map(|_| count) - // .map_err(|count| format!("Error: Found {} unconstrained variable(s)", count).into()) - Ok(count) + unconstrained_variable_detector + .finalize() + .map(|_| count) + .map_err(|count| format!("Error: Found {} unconstrained variable(s)", count).into()) } } diff --git a/zokrates_ast/src/typed/mod.rs b/zokrates_ast/src/typed/mod.rs index 8ee9d622..bf6d8365 100644 --- a/zokrates_ast/src/typed/mod.rs +++ b/zokrates_ast/src/typed/mod.rs @@ -85,12 +85,6 @@ pub struct TypedProgram<'ast, T> { pub main: OwnedTypedModuleId, } -impl<'ast, T> TypedProgram<'ast, T> { - pub fn main_function(&self) -> TypedFunction<'ast, T> { - unimplemented!() - } -} - impl<'ast, T: Field> TypedProgram<'ast, T> { pub fn abi(&self) -> Abi { let main = &self.modules[&self.main] diff --git a/zokrates_ast/src/typed/parameter.rs b/zokrates_ast/src/typed/parameter.rs index 4fad5c82..45b0dcae 100644 --- a/zokrates_ast/src/typed/parameter.rs +++ b/zokrates_ast/src/typed/parameter.rs @@ -8,7 +8,6 @@ pub struct GParameter<'ast, S> { pub private: bool, } -#[cfg(test)] impl<'ast, S> From> for GParameter<'ast, S> { fn from(v: GVariable<'ast, S>) -> Self { GParameter { diff --git a/zokrates_ast/src/typed/variable.rs b/zokrates_ast/src/typed/variable.rs index e4eadffe..53b3b555 100644 --- a/zokrates_ast/src/typed/variable.rs +++ b/zokrates_ast/src/typed/variable.rs @@ -54,11 +54,6 @@ impl<'ast, S: Clone> GVariable<'ast, S> { Self::with_id_and_type(id, GType::uint(bitwidth)) } - #[cfg(test)] - pub fn field_array>>(id: I, size: S) -> Self { - Self::array(id, GType::FieldElement, size) - } - pub fn array>, U: Into>(id: I, ty: GType, size: U) -> Self { Self::with_id_and_type(id, GType::array((ty, size.into()))) } diff --git a/zokrates_ast/src/untyped/node.rs b/zokrates_ast/src/untyped/node.rs index 75c9d598..2bc09eae 100644 --- a/zokrates_ast/src/untyped/node.rs +++ b/zokrates_ast/src/untyped/node.rs @@ -52,7 +52,6 @@ pub trait NodeValue: fmt::Display + fmt::Debug + Sized + PartialEq { Node::new(start, end, self) } - #[cfg(test)] fn mock(self) -> Node { Node::new(Position::mock(), Position::mock(), self) } diff --git a/zokrates_ast/src/zir/mod.rs b/zokrates_ast/src/zir/mod.rs index f93ea719..ff73b966 100644 --- a/zokrates_ast/src/zir/mod.rs +++ b/zokrates_ast/src/zir/mod.rs @@ -100,6 +100,12 @@ impl fmt::Display for RuntimeError { } } +impl RuntimeError { + pub fn mock() -> Self { + RuntimeError::SourceAssertion(String::default()) + } +} + /// A statement in a `ZirFunction` #[derive(Clone, PartialEq, Hash, Eq, Debug)] pub enum ZirStatement<'ast, T> { diff --git a/zokrates_ast/src/zir/uint.rs b/zokrates_ast/src/zir/uint.rs index 3e3b51a2..ee9a2302 100644 --- a/zokrates_ast/src/zir/uint.rs +++ b/zokrates_ast/src/zir/uint.rs @@ -4,12 +4,14 @@ use crate::zir::BooleanExpression; use zokrates_field::Field; impl<'ast, T: Field> UExpression<'ast, T> { + #[allow(clippy::should_implement_trait)] pub fn add(self, other: Self) -> UExpression<'ast, T> { let bitwidth = self.bitwidth; assert_eq!(bitwidth, other.bitwidth); UExpressionInner::Add(box self, box other).annotate(bitwidth) } + #[allow(clippy::should_implement_trait)] pub fn sub(self, other: Self) -> UExpression<'ast, T> { let bitwidth = self.bitwidth; assert_eq!(bitwidth, other.bitwidth); @@ -27,12 +29,14 @@ impl<'ast, T: Field> UExpression<'ast, T> { UExpressionInner::Mult(box self, box other).annotate(bitwidth) } + #[allow(clippy::should_implement_trait)] pub fn div(self, other: Self) -> UExpression<'ast, T> { let bitwidth = self.bitwidth; assert_eq!(bitwidth, other.bitwidth); UExpressionInner::Div(box self, box other).annotate(bitwidth) } + #[allow(clippy::should_implement_trait)] pub fn rem(self, other: Self) -> UExpression<'ast, T> { let bitwidth = self.bitwidth; assert_eq!(bitwidth, other.bitwidth); @@ -45,6 +49,7 @@ impl<'ast, T: Field> UExpression<'ast, T> { UExpressionInner::Xor(box self, box other).annotate(bitwidth) } + #[allow(clippy::should_implement_trait)] pub fn not(self) -> UExpression<'ast, T> { let bitwidth = self.bitwidth; UExpressionInner::Not(box self).annotate(bitwidth) diff --git a/zokrates_bellman/Cargo.toml b/zokrates_bellman/Cargo.toml new file mode 100644 index 00000000..9b9e483d --- /dev/null +++ b/zokrates_bellman/Cargo.toml @@ -0,0 +1,28 @@ +[package] +name = "zokrates_bellman" +version = "0.1.0" +edition = "2021" + +[features] +wasm = ["bellman/nolog", "bellman/wasm"] +multicore = ["bellman/multicore", "phase2/multicore"] + +[dependencies] +zokrates_field = { version = "0.5", path = "../zokrates_field", default-features = false } +zokrates_ast = { version = "0.1", path = "../zokrates_ast", default-features = false } +zokrates_proof_systems = { version = "0.1", path = "../zokrates_proof_systems", default-features = false } + +bellman = { package = "bellman_ce", version = "^0.3", default-features = false } +pairing = { package = "pairing_ce", version = "^0.21" } +phase2 = { git = "https://github.com/Zokrates/phase2", default-features = false } +rand_0_4 = { version = "0.4", package = "rand" }# +getrandom = { version = "0.2", features = ["js", "wasm-bindgen"] } +hex = "0.4.2" + +[dev-dependencies] +zokrates_interpreter = { version = "0.1", path = "../zokrates_interpreter" } + + + + + diff --git a/zokrates_core/src/proof_system/bellman/groth16.rs b/zokrates_bellman/src/groth16.rs similarity index 91% rename from zokrates_core/src/proof_system/bellman/groth16.rs rename to zokrates_bellman/src/groth16.rs index c29a8dec..17650780 100644 --- a/zokrates_core/src/proof_system/bellman/groth16.rs +++ b/zokrates_bellman/src/groth16.rs @@ -4,19 +4,19 @@ use bellman::groth16::{ }; use pairing::{ff::to_hex, CurveAffine, Engine}; -use crate::proof_system::{Backend, MpcBackend, NonUniversalBackend, Proof, SetupKeypair}; use zokrates_field::BellmanFieldExtensions; use zokrates_field::Field; +use zokrates_proof_systems::{Backend, MpcBackend, NonUniversalBackend, Proof, SetupKeypair}; -use crate::proof_system::bellman::Bellman; -use crate::proof_system::bellman::Computation; -use crate::proof_system::bellman::{parse_g1, parse_g2}; -use crate::proof_system::groth16::{ProofPoints, VerificationKey, G16}; -use crate::proof_system::Scheme; +use crate::Bellman; +use crate::Computation; +use crate::{parse_g1, parse_g2}; use phase2::MPCParameters; use rand_0_4::Rng; use std::io::{Read, Write}; use zokrates_ast::ir::{ProgIterator, Statement, Witness}; +use zokrates_proof_systems::groth16::{ProofPoints, VerificationKey, G16}; +use zokrates_proof_systems::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."; @@ -157,8 +157,8 @@ impl MpcBackend for Bellman { pub mod serialization { use super::*; - use crate::proof_system::{G1Affine, G2Affine}; use pairing::from_hex; + use zokrates_proof_systems::{G1Affine, G2Affine}; pub fn parameters_to_verification_key( parameters: &Parameters, @@ -188,9 +188,14 @@ pub mod serialization { pub fn to_g2( g2: G2Affine, ) -> ::G2Affine { - let x = T::new_fq2(&(g2.0).0, &(g2.0).1); - let y = T::new_fq2(&(g2.1).0, &(g2.1).1); - ::G2Affine::from_xy_unchecked(x, y) + match g2 { + G2Affine::Fq2(g2) => { + let x = T::new_fq2(&(g2.0).0, &(g2.0).1); + let y = T::new_fq2(&(g2.1).0, &(g2.1).1); + ::G2Affine::from_xy_unchecked(x, y) + } + _ => unreachable!(), + } } } @@ -200,7 +205,7 @@ mod tests { use zokrates_interpreter::Interpreter; use super::*; - use crate::flat_absy::{Parameter, Variable}; + use zokrates_ast::common::{Parameter, Variable}; use zokrates_ast::ir::{Prog, Statement}; #[test] diff --git a/zokrates_core/src/proof_system/bellman/mod.rs b/zokrates_bellman/src/lib.rs similarity index 95% rename from zokrates_core/src/proof_system/bellman/mod.rs rename to zokrates_bellman/src/lib.rs index 67c81bb5..f6413f18 100644 --- a/zokrates_core/src/proof_system/bellman/mod.rs +++ b/zokrates_bellman/src/lib.rs @@ -83,8 +83,10 @@ fn bellman_combination>> Computation { - pub fn synthesize>( +impl>> + Circuit for Computation +{ + fn synthesize>( self, cs: &mut CS, ) -> Result<(), SynthesisError> { @@ -95,7 +97,7 @@ impl>> Co assert!(symbols.insert(Variable::one(), CS::one()).is_none()); - symbols.extend(self.arguments.iter().enumerate().map(|(index, p)| { + symbols.extend(self.program.arguments.iter().enumerate().map(|(index, p)| { let wire = match p.private { true => cs.alloc( || format!("PRIVATE_INPUT_{}", index), @@ -122,7 +124,7 @@ impl>> Co (p.id, wire) })); - for statement in self.statements { + for statement in self.program.statements { if let Statement::Constraint(quad, lin, _) = statement { let a = &bellman_combination( quad.left.into_canonical(), @@ -193,21 +195,10 @@ impl>> Co } } -impl>> - Circuit for Computation -{ - fn synthesize>( - self, - cs: &mut CS, - ) -> Result<(), SynthesisError> { - self.program.synthesize(cs, self.witness) - } -} - mod parse { use super::*; - use crate::proof_system::{G1Affine, G2Affine}; - use pairing_ce::CurveAffine; + use pairing::CurveAffine; + use zokrates_proof_systems::{G1Affine, G2Affine, G2AffineFq2}; fn to_hex(bytes: &[u8]) -> String { let mut hex = hex::encode(bytes); @@ -240,7 +231,7 @@ mod parse { let y1 = to_hex(iter.next().unwrap()); let y0 = to_hex(iter.next().unwrap()); - G2Affine((x0, x1), (y0, y1)) + G2Affine::Fq2(G2AffineFq2((x0, x1), (y0, y1))) } } @@ -253,7 +244,7 @@ mod tests { mod prove { use super::*; - use crate::flat_absy::Parameter; + use zokrates_ast::flat::Parameter; use zokrates_ast::ir::Prog; #[test] diff --git a/zokrates_cli/Cargo.toml b/zokrates_cli/Cargo.toml index 5109b5bc..1b0708aa 100644 --- a/zokrates_cli/Cargo.toml +++ b/zokrates_cli/Cargo.toml @@ -7,9 +7,9 @@ edition = "2018" [features] default = ["bellman", "ark"] -libsnark = ["zokrates_core/libsnark", "zokrates_common/libsnark"] -bellman = ["zokrates_core/bellman", "zokrates_common/bellman"] -ark = ["zokrates_core/ark", "zokrates_common/ark"] +libsnark = ["zokrates_libsnark"] +bellman = ["zokrates_bellman", "zokrates_core/bellman"] +ark = ["zokrates_ark", "zokrates_core/ark"] [dependencies] log = "0.4" @@ -21,6 +21,8 @@ regex = "0.2" zokrates_field = { version = "0.5", path = "../zokrates_field", default-features = false } zokrates_abi = { version = "0.1", path = "../zokrates_abi" } zokrates_core = { version = "0.6", path = "../zokrates_core", default-features = false } +zokrates_ast = { version = "0.1", path = "../zokrates_ast", default-features = false } +zokrates_interpreter = { version = "0.1", path = "../zokrates_interpreter", default-features = false } typed-arena = "1.4.1" zokrates_fs_resolver = { version = "0.5", path = "../zokrates_fs_resolver"} zokrates_common = { version = "0.1", path = "../zokrates_common" } @@ -35,6 +37,12 @@ hex = "0.3.1" blake2 = "0.8.1" sha2 = "0.10.0" +# Backends +zokrates_proof_systems = { version = "0.1", path = "../zokrates_proof_systems", default-features = false } +zokrates_libsnark = { version = "0.1", path = "../zokrates_libsnark", default-features = false, optional = true } +zokrates_ark = { version = "0.1", path = "../zokrates_ark", default-features = false, optional = true } +zokrates_bellman = { version = "0.1", path = "../zokrates_bellman", default-features = false, optional = true } + [dev-dependencies] glob = "0.2.11" assert_cli = "0.5" diff --git a/zokrates_cli/src/bin.rs b/zokrates_cli/src/bin.rs index cca7d11e..7035ef53 100644 --- a/zokrates_cli/src/bin.rs +++ b/zokrates_cli/src/bin.rs @@ -122,7 +122,6 @@ mod tests { use std::string::String; use typed_arena::Arena; use zokrates_core::compile::{compile, CompilationArtifacts, CompileConfig}; - use zokrates_core::ir; use zokrates_field::Bn128Field; use zokrates_fs_resolver::FileSystemResolver; @@ -217,7 +216,7 @@ mod tests { ) .unwrap(); - let interpreter = ir::Interpreter::default(); + let interpreter = zokrates_interpreter::Interpreter::default(); let _ = interpreter .execute(artifacts.prog(), &[Bn128Field::from(0)]) @@ -257,7 +256,7 @@ mod tests { ) .unwrap(); - let interpreter = ir::Interpreter::default(); + let interpreter = zokrates_interpreter::Interpreter::default(); let res = interpreter.execute(artifacts.prog(), &[Bn128Field::from(0)]); diff --git a/zokrates_cli/src/ops/compute_witness.rs b/zokrates_cli/src/ops/compute_witness.rs index 944451df..2b2a8ae7 100644 --- a/zokrates_cli/src/ops/compute_witness.rs +++ b/zokrates_cli/src/ops/compute_witness.rs @@ -5,10 +5,11 @@ use std::fs::File; use std::io::{stdin, BufReader, BufWriter, Read}; use std::path::Path; use zokrates_abi::Encode; -use zokrates_core::ir; -use zokrates_core::ir::ProgEnum; -use zokrates_core::typed_absy::abi::Abi; -use zokrates_core::typed_absy::types::{ConcreteSignature, ConcreteType}; +use zokrates_ast::ir::{self, ProgEnum}; +use zokrates_ast::typed::{ + abi::Abi, + types::{ConcreteSignature, ConcreteType}, +}; use zokrates_field::Field; pub fn subcommand() -> App<'static, 'static> { @@ -156,7 +157,7 @@ fn cli_compute>>( } .map_err(|e| format!("Could not parse argument: {}", e))?; - let interpreter = ir::Interpreter::default(); + let interpreter = zokrates_interpreter::Interpreter::default(); let witness = interpreter .execute(ir_prog, &arguments.encode()) diff --git a/zokrates_cli/src/ops/export_verifier.rs b/zokrates_cli/src/ops/export_verifier.rs index 1ab395f6..e5086cde 100644 --- a/zokrates_cli/src/ops/export_verifier.rs +++ b/zokrates_cli/src/ops/export_verifier.rs @@ -6,8 +6,8 @@ use std::io::{BufReader, BufWriter, Write}; use std::path::Path; use zokrates_common::constants; use zokrates_common::helpers::{CurveParameter, SchemeParameter}; -use zokrates_core::proof_system::*; use zokrates_field::Bn128Field; +use zokrates_proof_systems::*; pub fn subcommand() -> App<'static, 'static> { SubCommand::with_name("export-verifier") diff --git a/zokrates_cli/src/ops/generate_proof.rs b/zokrates_cli/src/ops/generate_proof.rs index 9c1b1d6f..7b7e237f 100644 --- a/zokrates_cli/src/ops/generate_proof.rs +++ b/zokrates_cli/src/ops/generate_proof.rs @@ -4,19 +4,18 @@ use std::convert::TryFrom; use std::fs::File; use std::io::{BufReader, Read, Write}; use std::path::Path; +#[cfg(feature = "ark")] +use zokrates_ark::Ark; +use zokrates_ast::ir::{self, ProgEnum}; +#[cfg(feature = "bellman")] +use zokrates_bellman::Bellman; use zokrates_common::constants; use zokrates_common::helpers::*; -use zokrates_core::ir; -use zokrates_core::ir::ProgEnum; -#[cfg(feature = "ark")] -use zokrates_core::proof_system::ark::Ark; -#[cfg(feature = "bellman")] -use zokrates_core::proof_system::bellman::Bellman; -#[cfg(feature = "libsnark")] -use zokrates_core::proof_system::libsnark::Libsnark; -#[cfg(any(feature = "bellman", feature = "ark", feature = "libsnark"))] -use zokrates_core::proof_system::*; use zokrates_field::Field; +#[cfg(feature = "libsnark")] +use zokrates_libsnark::Libsnark; +#[cfg(any(feature = "bellman", feature = "ark", feature = "libsnark"))] +use zokrates_proof_systems::*; pub fn subcommand() -> App<'static, 'static> { SubCommand::with_name("generate-proof") diff --git a/zokrates_cli/src/ops/generate_smtlib2.rs b/zokrates_cli/src/ops/generate_smtlib2.rs index 127dc6ad..b1bf6f6a 100644 --- a/zokrates_cli/src/ops/generate_smtlib2.rs +++ b/zokrates_cli/src/ops/generate_smtlib2.rs @@ -3,9 +3,7 @@ use clap::{App, Arg, ArgMatches, SubCommand}; use std::fs::File; use std::io::{BufReader, Write}; use std::path::Path; -use zokrates_core::ir; -use zokrates_core::ir::smtlib2::SMTLib2Display; -use zokrates_core::ir::ProgEnum; +use zokrates_ast::ir::{self, smtlib2::SMTLib2Display, ProgEnum}; use zokrates_field::Field; pub fn subcommand() -> App<'static, 'static> { diff --git a/zokrates_cli/src/ops/inspect.rs b/zokrates_cli/src/ops/inspect.rs index 571ba5c3..523d664a 100644 --- a/zokrates_cli/src/ops/inspect.rs +++ b/zokrates_cli/src/ops/inspect.rs @@ -3,8 +3,7 @@ use clap::{App, Arg, ArgMatches, SubCommand}; use std::fs::File; use std::io::{BufReader, BufWriter, Write}; use std::path::{Path, PathBuf}; -use zokrates_core::ir; -use zokrates_core::ir::ProgEnum; +use zokrates_ast::ir::{self, ProgEnum}; use zokrates_field::Field; pub fn subcommand() -> App<'static, 'static> { diff --git a/zokrates_cli/src/ops/mpc/beacon.rs b/zokrates_cli/src/ops/mpc/beacon.rs index 0e3e39c8..b5af669e 100644 --- a/zokrates_cli/src/ops/mpc/beacon.rs +++ b/zokrates_cli/src/ops/mpc/beacon.rs @@ -3,10 +3,10 @@ use clap::{App, Arg, ArgMatches, SubCommand}; use std::fs::File; use std::io::{BufReader, BufWriter}; use std::path::Path; +use zokrates_bellman::Bellman; use zokrates_common::constants::{BLS12_381, BN128}; -use zokrates_core::proof_system::bellman::Bellman; -use zokrates_core::proof_system::{MpcBackend, MpcScheme, G16}; use zokrates_field::{BellmanFieldExtensions, Bls12_381Field, Bn128Field, Field}; +use zokrates_proof_systems::{MpcBackend, MpcScheme, G16}; pub fn subcommand() -> App<'static, 'static> { SubCommand::with_name("beacon") diff --git a/zokrates_cli/src/ops/mpc/contribute.rs b/zokrates_cli/src/ops/mpc/contribute.rs index f5820949..3490f381 100644 --- a/zokrates_cli/src/ops/mpc/contribute.rs +++ b/zokrates_cli/src/ops/mpc/contribute.rs @@ -3,10 +3,10 @@ use clap::{App, Arg, ArgMatches, SubCommand}; use std::fs::File; use std::io::{BufReader, BufWriter}; use std::path::Path; +use zokrates_bellman::Bellman; use zokrates_common::constants::{BLS12_381, BN128}; -use zokrates_core::proof_system::bellman::Bellman; -use zokrates_core::proof_system::{MpcBackend, MpcScheme, G16}; use zokrates_field::{BellmanFieldExtensions, Bls12_381Field, Bn128Field, Field}; +use zokrates_proof_systems::{MpcBackend, MpcScheme, G16}; pub fn subcommand() -> App<'static, 'static> { SubCommand::with_name("contribute") diff --git a/zokrates_cli/src/ops/mpc/export.rs b/zokrates_cli/src/ops/mpc/export.rs index 1923a947..b9ea3fbc 100644 --- a/zokrates_cli/src/ops/mpc/export.rs +++ b/zokrates_cli/src/ops/mpc/export.rs @@ -3,10 +3,10 @@ use clap::{App, Arg, ArgMatches, SubCommand}; use std::fs::File; use std::io::{BufReader, Write}; use std::path::Path; +use zokrates_bellman::Bellman; use zokrates_common::constants::{BLS12_381, BN128}; -use zokrates_core::proof_system::bellman::Bellman; -use zokrates_core::proof_system::{MpcBackend, MpcScheme, G16}; use zokrates_field::{BellmanFieldExtensions, Bls12_381Field, Bn128Field, Field}; +use zokrates_proof_systems::{MpcBackend, MpcScheme, G16}; pub fn subcommand() -> App<'static, 'static> { SubCommand::with_name("export") diff --git a/zokrates_cli/src/ops/mpc/init.rs b/zokrates_cli/src/ops/mpc/init.rs index 465b68e0..71136366 100644 --- a/zokrates_cli/src/ops/mpc/init.rs +++ b/zokrates_cli/src/ops/mpc/init.rs @@ -3,11 +3,10 @@ use clap::{App, Arg, ArgMatches, SubCommand}; use std::fs::File; use std::io::{BufReader, BufWriter}; use std::path::Path; -use zokrates_core::ir; -use zokrates_core::ir::ProgEnum; -use zokrates_core::proof_system::bellman::Bellman; -use zokrates_core::proof_system::{MpcBackend, MpcScheme, G16}; +use zokrates_ast::ir::{self, ProgEnum}; +use zokrates_bellman::Bellman; use zokrates_field::{BellmanFieldExtensions, Field}; +use zokrates_proof_systems::{MpcBackend, MpcScheme, G16}; pub fn subcommand() -> App<'static, 'static> { SubCommand::with_name("init") diff --git a/zokrates_cli/src/ops/mpc/verify.rs b/zokrates_cli/src/ops/mpc/verify.rs index b734991f..6beca03d 100644 --- a/zokrates_cli/src/ops/mpc/verify.rs +++ b/zokrates_cli/src/ops/mpc/verify.rs @@ -3,11 +3,10 @@ use clap::{App, Arg, ArgMatches, SubCommand}; use std::fs::File; use std::io::BufReader; use std::path::Path; -use zokrates_core::ir; -use zokrates_core::ir::ProgEnum; -use zokrates_core::proof_system::bellman::Bellman; -use zokrates_core::proof_system::{MpcBackend, MpcScheme, G16}; +use zokrates_ast::ir::{self, ProgEnum}; +use zokrates_bellman::Bellman; use zokrates_field::{BellmanFieldExtensions, Field}; +use zokrates_proof_systems::{MpcBackend, MpcScheme, G16}; pub fn subcommand() -> App<'static, 'static> { SubCommand::with_name("verify") diff --git a/zokrates_cli/src/ops/print_proof.rs b/zokrates_cli/src/ops/print_proof.rs index 9c597e0d..c26ad769 100644 --- a/zokrates_cli/src/ops/print_proof.rs +++ b/zokrates_cli/src/ops/print_proof.rs @@ -5,10 +5,10 @@ use std::fs::File; use std::path::Path; use zokrates_common::constants as common_constants; use zokrates_common::helpers::{CurveParameter, SchemeParameter}; -use zokrates_core::proof_system::{ +use zokrates_field::Bn128Field; +use zokrates_proof_systems::{ Marlin, Proof, SolidityCompatibleField, SolidityCompatibleScheme, G16, GM17, PGHR13, }; -use zokrates_field::Bn128Field; pub fn subcommand() -> App<'static, 'static> { SubCommand::with_name("print-proof") diff --git a/zokrates_cli/src/ops/setup.rs b/zokrates_cli/src/ops/setup.rs index 8b1248ac..419454a5 100644 --- a/zokrates_cli/src/ops/setup.rs +++ b/zokrates_cli/src/ops/setup.rs @@ -4,19 +4,18 @@ use std::convert::TryFrom; use std::fs::File; use std::io::{BufReader, Write}; use std::path::Path; +#[cfg(feature = "ark")] +use zokrates_ark::Ark; +use zokrates_ast::ir::{self, ProgEnum}; +#[cfg(feature = "bellman")] +use zokrates_bellman::Bellman; use zokrates_common::constants; use zokrates_common::helpers::*; -use zokrates_core::ir; -use zokrates_core::ir::ProgEnum; -#[cfg(feature = "ark")] -use zokrates_core::proof_system::ark::Ark; -#[cfg(feature = "bellman")] -use zokrates_core::proof_system::bellman::Bellman; -#[cfg(feature = "libsnark")] -use zokrates_core::proof_system::libsnark::Libsnark; -#[cfg(any(feature = "bellman", feature = "ark", feature = "libsnark"))] -use zokrates_core::proof_system::*; use zokrates_field::Field; +#[cfg(feature = "libsnark")] +use zokrates_libsnark::Libsnark; +#[cfg(any(feature = "bellman", feature = "ark", feature = "libsnark"))] +use zokrates_proof_systems::*; pub fn subcommand() -> App<'static, 'static> { SubCommand::with_name("setup") diff --git a/zokrates_cli/src/ops/universal_setup.rs b/zokrates_cli/src/ops/universal_setup.rs index ac1a9b04..8d673b28 100644 --- a/zokrates_cli/src/ops/universal_setup.rs +++ b/zokrates_cli/src/ops/universal_setup.rs @@ -4,13 +4,13 @@ use std::convert::TryFrom; use std::fs::File; use std::io::Write; use std::path::Path; +#[cfg(feature = "ark")] +use zokrates_ark::Ark; use zokrates_common::constants; use zokrates_common::helpers::*; -#[cfg(feature = "ark")] -use zokrates_core::proof_system::ark::Ark; -#[cfg(any(feature = "bellman", feature = "ark", feature = "libsnark"))] -use zokrates_core::proof_system::*; use zokrates_field::{Bls12_377Field, Bls12_381Field, Bn128Field, Bw6_761Field, Field}; +#[cfg(any(feature = "bellman", feature = "ark", feature = "libsnark"))] +use zokrates_proof_systems::*; pub fn subcommand() -> App<'static, 'static> { SubCommand::with_name("universal-setup") diff --git a/zokrates_cli/src/ops/verify.rs b/zokrates_cli/src/ops/verify.rs index 4402df9c..ba7d4bee 100644 --- a/zokrates_cli/src/ops/verify.rs +++ b/zokrates_cli/src/ops/verify.rs @@ -4,17 +4,17 @@ use std::convert::TryFrom; use std::fs::File; use std::io::BufReader; use std::path::Path; +#[cfg(feature = "ark")] +use zokrates_ark::Ark; +#[cfg(feature = "bellman")] +use zokrates_bellman::Bellman; use zokrates_common::constants; use zokrates_common::helpers::*; -#[cfg(feature = "ark")] -use zokrates_core::proof_system::ark::Ark; -#[cfg(feature = "bellman")] -use zokrates_core::proof_system::bellman::Bellman; -#[cfg(feature = "libsnark")] -use zokrates_core::proof_system::libsnark::Libsnark; -#[cfg(any(feature = "bellman", feature = "ark", feature = "libsnark"))] -use zokrates_core::proof_system::*; use zokrates_field::{Bls12_377Field, Bls12_381Field, Bn128Field, Bw6_761Field, Field}; +#[cfg(feature = "libsnark")] +use zokrates_libsnark::Libsnark; +#[cfg(any(feature = "bellman", feature = "ark", feature = "libsnark"))] +use zokrates_proof_systems::*; pub fn subcommand() -> App<'static, 'static> { SubCommand::with_name("verify") diff --git a/zokrates_cli/tests/integration.rs b/zokrates_cli/tests/integration.rs index 47d65abb..d51e5f3e 100644 --- a/zokrates_cli/tests/integration.rs +++ b/zokrates_cli/tests/integration.rs @@ -19,12 +19,12 @@ mod integration { use std::path::Path; use tempdir::TempDir; use zokrates_abi::{parse_strict, Encode}; - use zokrates_core::proof_system::{ + use zokrates_ast::typed::abi::Abi; + use zokrates_field::Bn128Field; + use zokrates_proof_systems::{ to_token::ToToken, Marlin, Proof, SolidityCompatibleScheme, G16, GM17, PGHR13, SOLIDITY_G2_ADDITION_LIB, }; - use zokrates_core::typed_absy::abi::Abi; - use zokrates_field::Bn128Field; macro_rules! map( { diff --git a/zokrates_core/Cargo.toml b/zokrates_core/Cargo.toml index e469112a..0ae9abfb 100644 --- a/zokrates_core/Cargo.toml +++ b/zokrates_core/Cargo.toml @@ -5,15 +5,12 @@ edition = "2018" authors = ["Jacob Eberhardt ", "Dennis Kuhnert "] repository = "https://github.com/Zokrates/ZoKrates" readme = "README.md" -build = "build.rs" [features] -default = ["bellman", "ark"] -libsnark = ["cc", "cmake"] -bellman = ["bellman_ce", "pairing_ce", "ff_ce", "zokrates_field/bellman"] -wasm = ["bellman_ce/nolog", "bellman_ce/wasm"] -multicore = ["bellman_ce/multicore", "phase2/multicore"] -ark = ["ark-ff", "ark-ec", "ark-bls12-377", "ark-bw6-761", "ark-gm17", "ark-groth16", "ark-crypto-primitives", "ark-serialize", "ark-relations", "ark-marlin", "ark-poly", "ark-poly-commit", "sha3", "digest"] +default = ["ark", "bellman"] +ark = ["zokrates_ast/ark"] +bellman = ["zokrates_ast/bellman"] +libsnark = [] [dependencies] log = "0.4" @@ -26,49 +23,14 @@ reduce = "0.1.1" # serialization and deserialization serde = { version = "1.0", features = ["derive"] } serde_json = { version = "1.0", features = ["preserve_order"] } -hex = "0.4.2" -regex = "0.2" zokrates_field = { version = "0.5.0", path = "../zokrates_field", default-features = false } zokrates_pest_ast = { version = "0.2.0", path = "../zokrates_pest_ast" } -zokrates_common = { path = "../zokrates_common" } +zokrates_common = { version = "0.1", path = "../zokrates_common" } zokrates_embed = { version = "0.1.0", path = "../zokrates_embed" } zokrates_interpreter = { version = "0.1", path = "../zokrates_interpreter" } zokrates_ast = { version = "0.1", path = "../zokrates_ast" } -getrandom = { version = "0.2", features = ["js", "wasm-bindgen"] } -rand_0_4 = { version = "0.4", package = "rand" } -rand_0_8 = { version = "0.8", package = "rand" } csv = "1" -phase2 = { git = "https://github.com/Zokrates/phase2", default-features = false } - -# bellman -bellman_ce = { version = "^0.3", default-features = false, optional = true } -pairing_ce = { version = "^0.21", optional = true } -ff_ce = { version = "^0.9", optional = true } - -# ark -ark-ff = { version = "^0.3.0", default-features = false, optional = true } -ark-ec = { version = "^0.3.0", default-features = false, optional = true } -ark-bn254 = { version = "^0.3.0", features = ["curve"], default-features = false, optional = true } -ark-bls12-377 = { version = "^0.3.0", features = ["curve"], default-features = false, optional = true } -ark-bw6-761 = { version = "^0.3.0", default-features = false, optional = true } -ark-gm17 = { version = "^0.3.0", default-features = false, optional = true } -ark-groth16 = { version = "^0.3.0", default-features = false, optional = true } -ark-serialize = { version = "^0.3.0", default-features = false, optional = true } -ark-relations = { version = "^0.3.0", default-features = false, optional = true } -ark-marlin = { git = "https://github.com/arkworks-rs/marlin", rev = "63cfd82", default-features = false, optional = true } -ark-poly = { version = "^0.3.0", default-features = false, optional = true } -ark-poly-commit = { version = "^0.3.0", default-features = false, optional = true } -ark-crypto-primitives = { version = "^0.3.0", default-features = false, optional = true } -sha3 = { version = "0.9", optional = true } -digest = { version = "0.9", optional = true } -ethabi = "17.0.0" -primitive-types = { version = "0.11", features = ["rlp"] } [dev-dependencies] -wasm-bindgen-test = "^0.3.0" pretty_assertions = "0.6.1" zokrates_fs_resolver = { version = "0.5", path = "../zokrates_fs_resolver"} - -[build-dependencies] -cc = { version = "1.0", features = ["parallel"], optional = true } -cmake = { version = "=0.1.45", optional = true } diff --git a/zokrates_core/src/compile.rs b/zokrates_core/src/compile.rs index f7986766..5b1febd5 100644 --- a/zokrates_core/src/compile.rs +++ b/zokrates_core/src/compile.rs @@ -3,14 +3,12 @@ //! @file compile.rs //! @author Thibaut Schaeffer //! @date 2018 -use crate::absy::{Module, OwnedModuleId, Program}; -use crate::flatten::FlattenerIterator; +use crate::flatten::from_function_and_config; use crate::imports::{self, Importer}; use crate::macros; +use crate::optimizer::optimize; use crate::semantics::{self, Checker}; -use crate::static_analysis; -use crate::typed_absy::abi::Abi; -use crate::zir::ZirProgram; +use crate::static_analysis::{self, analyse}; use macros::process_macros; use serde::{Deserialize, Serialize}; use std::collections::HashMap; @@ -18,7 +16,10 @@ use std::fmt; use std::io; use std::path::{Path, PathBuf}; use typed_arena::Arena; -use zokrates_ast::ir; +use zokrates_ast::ir::{self, from_flat::from_flat}; +use zokrates_ast::typed::abi::Abi; +use zokrates_ast::untyped::{Module, OwnedModuleId, Program}; +use zokrates_ast::zir::ZirProgram; use zokrates_common::Resolver; use zokrates_field::Field; use zokrates_pest_ast as pest; @@ -195,21 +196,20 @@ pub fn compile<'ast, T: Field, E: Into>( arena: &'ast Arena, ) -> Result> + 'ast>, CompileErrors> { - let (typed_ast, abi): (crate::zir::ZirProgram<'_, T>, _) = + let (typed_ast, abi): (zokrates_ast::zir::ZirProgram<'_, T>, _) = check_with_arena(source, location, resolver, &config, arena)?; // flatten input program log::debug!("Flatten"); - let program_flattened = FlattenerIterator::from_function_and_config(typed_ast.main, config); + let program_flattened = from_function_and_config(typed_ast.main, config); // convert to ir log::debug!("Convert to IR"); - //let ir_prog = ir::from_flat::from_flat(program_flattened); - let ir_prog = unimplemented!(); + let ir_prog = from_flat(program_flattened); // optimize log::debug!("Optimise IR"); - let optimized_ir_prog = ir_prog.optimize(); + let optimized_ir_prog = optimize(ir_prog); Ok(CompilationArtifacts { prog: optimized_ir_prog, @@ -254,8 +254,7 @@ fn check_with_arena<'ast, T: Field, E: Into>( log::debug!("Run static analysis"); // analyse (unroll and constant propagation) - typed_ast - .analyse(config) + analyse(typed_ast, config) .map_err(|e| CompileErrors(vec![CompileErrorInner::from(e).in_file(&main_module)])) } @@ -361,8 +360,8 @@ mod test { mod abi { use super::*; - use crate::typed_absy::abi::*; - use crate::typed_absy::types::*; + use zokrates_ast::typed::abi::*; + use zokrates_ast::typed::types::*; #[test] fn use_struct_declaration_types() { diff --git a/zokrates_core/src/flatten/mod.rs b/zokrates_core/src/flatten/mod.rs index a724825b..48553a89 100644 --- a/zokrates_core/src/flatten/mod.rs +++ b/zokrates_core/src/flatten/mod.rs @@ -12,13 +12,6 @@ use zokrates_ast::zir::{ShouldReduce, UMetadata, ZirExpressionList}; use zokrates_interpreter::Interpreter; use crate::compile::CompileConfig; -use crate::flat_absy::*; -use crate::zir::types::{Type, UBitwidth}; -use crate::zir::{ - BooleanExpression, FieldElementExpression, Identifier, IfElse, Parameter as ZirParameter, - UExpression, UExpressionInner, Variable as ZirVariable, ZirExpression, ZirFunction, - ZirStatement, -}; use std::collections::{ hash_map::{Entry, HashMap}, VecDeque, @@ -27,7 +20,14 @@ use std::convert::TryFrom; use zokrates_ast::common::embed::*; use zokrates_ast::common::FlatEmbed; use zokrates_ast::common::{RuntimeError, Variable}; +use zokrates_ast::flat::*; use zokrates_ast::ir::Solver; +use zokrates_ast::zir::types::{Type, UBitwidth}; +use zokrates_ast::zir::{ + BooleanExpression, FieldElementExpression, Identifier, IfElse, Parameter as ZirParameter, + UExpression, UExpressionInner, Variable as ZirVariable, ZirExpression, ZirFunction, + ZirStatement, +}; use zokrates_field::Field; type FlatStatements = VecDeque>; @@ -36,10 +36,10 @@ type FlatStatements = VecDeque>; /// /// # Arguments /// * `funct` - `ZirFunction` that will be flattened -pub fn from_function_and_config<'ast, T: Field>( - funct: ZirFunction<'ast, T>, +pub fn from_function_and_config( + funct: ZirFunction, config: CompileConfig, -) -> FlattenerIterator<'ast, T> { +) -> FlattenerIterator { let mut flattener = Flattener::new(config); let mut statements_flattened = FlatStatements::new(); // push parameters @@ -208,15 +208,6 @@ impl FlatUExpression { } } -// impl From for RuntimeError { -// fn from(error: crate::zir::RuntimeError) -> Self { -// match error { -// crate::zir::RuntimeError::SourceAssertion(s) => RuntimeError::SourceAssertion(s), -// crate::zir::RuntimeError::SelectRangeCheck => RuntimeError::SelectRangeCheck, -// } -// } -// } - impl<'ast, T: Field> Flattener<'ast, T> { /// Returns a `Flattener` with fresh `layout`. fn new(config: CompileConfig) -> Flattener<'ast, T> { @@ -2710,13 +2701,13 @@ impl<'ast, T: Field> Flattener<'ast, T> { #[cfg(test)] mod tests { use super::*; - use crate::zir; - use crate::zir::types::Signature; - use crate::zir::types::Type; + use zokrates_ast::zir; + use zokrates_ast::zir::types::Signature; + use zokrates_ast::zir::types::Type; use zokrates_field::Bn128Field; fn flatten_function(f: ZirFunction) -> FlatProg { - FlattenerIterator::from_function_and_config(f, CompileConfig::default()).collect() + from_function_and_config(f, CompileConfig::default()).collect() } #[test] @@ -2734,11 +2725,11 @@ mod tests { arguments: vec![], statements: vec![ ZirStatement::Definition( - Variable::boolean("x".into()), + zir::Variable::boolean("x".into()), BooleanExpression::Value(true).into(), ), ZirStatement::Definition( - Variable::boolean("y".into()), + zir::Variable::boolean("y".into()), BooleanExpression::Value(true).into(), ), ZirStatement::Assertion( @@ -2798,11 +2789,11 @@ mod tests { arguments: vec![], statements: vec![ ZirStatement::Definition( - Variable::field_element("x"), + zir::Variable::field_element("x"), FieldElementExpression::Number(Bn128Field::from(1)).into(), ), ZirStatement::Definition( - Variable::field_element("y"), + zir::Variable::field_element("y"), FieldElementExpression::Number(Bn128Field::from(2)).into(), ), ZirStatement::Assertion( @@ -2872,7 +2863,7 @@ mod tests { arguments: vec![], statements: vec![ ZirStatement::Definition( - Variable::uint("x".into(), 32), + zir::Variable::uint("x".into(), 32), ZirExpression::Uint( UExpressionInner::Value(42) .annotate(32) @@ -2936,11 +2927,11 @@ mod tests { arguments: vec![], statements: vec![ ZirStatement::Definition( - Variable::field_element("x"), + zir::Variable::field_element("x"), FieldElementExpression::Number(Bn128Field::from(2)).into(), ), ZirStatement::Definition( - Variable::field_element("y"), + zir::Variable::field_element("y"), FieldElementExpression::Number(Bn128Field::from(2)).into(), ), ZirStatement::Assertion( @@ -3004,15 +2995,15 @@ mod tests { arguments: vec![], statements: vec![ ZirStatement::Definition( - Variable::field_element("x"), + zir::Variable::field_element("x"), FieldElementExpression::Number(Bn128Field::from(2)).into(), ), ZirStatement::Definition( - Variable::field_element("y"), + zir::Variable::field_element("y"), FieldElementExpression::Number(Bn128Field::from(2)).into(), ), ZirStatement::Definition( - Variable::field_element("z"), + zir::Variable::field_element("z"), FieldElementExpression::Number(Bn128Field::from(4)).into(), ), ZirStatement::Assertion( @@ -3083,15 +3074,15 @@ mod tests { arguments: vec![], statements: vec![ ZirStatement::Definition( - Variable::field_element("x"), + zir::Variable::field_element("x"), FieldElementExpression::Number(Bn128Field::from(2)).into(), ), ZirStatement::Definition( - Variable::field_element("y"), + zir::Variable::field_element("y"), FieldElementExpression::Number(Bn128Field::from(2)).into(), ), ZirStatement::Definition( - Variable::field_element("z"), + zir::Variable::field_element("z"), FieldElementExpression::Number(Bn128Field::from(4)).into(), ), ZirStatement::Assertion( @@ -3164,19 +3155,19 @@ mod tests { arguments: vec![], statements: vec![ ZirStatement::Definition( - Variable::field_element("x"), + zir::Variable::field_element("x"), FieldElementExpression::Number(Bn128Field::from(4)).into(), ), ZirStatement::Definition( - Variable::field_element("y"), + zir::Variable::field_element("y"), FieldElementExpression::Number(Bn128Field::from(4)).into(), ), ZirStatement::Definition( - Variable::field_element("z"), + zir::Variable::field_element("z"), FieldElementExpression::Number(Bn128Field::from(8)).into(), ), ZirStatement::Definition( - Variable::field_element("t"), + zir::Variable::field_element("t"), FieldElementExpression::Number(Bn128Field::from(2)).into(), ), ZirStatement::Assertion( @@ -3257,11 +3248,11 @@ mod tests { arguments: vec![], statements: vec![ ZirStatement::Definition( - Variable::field_element("a"), + zir::Variable::field_element("a"), FieldElementExpression::Number(Bn128Field::from(7)).into(), ), ZirStatement::Definition( - Variable::field_element("b"), + zir::Variable::field_element("b"), FieldElementExpression::Pow( box FieldElementExpression::Identifier("a".into()), box 0u32.into(), @@ -3316,11 +3307,11 @@ mod tests { arguments: vec![], statements: vec![ ZirStatement::Definition( - Variable::field_element("a"), + zir::Variable::field_element("a"), FieldElementExpression::Number(Bn128Field::from(7)).into(), ), ZirStatement::Definition( - Variable::field_element("b"), + zir::Variable::field_element("b"), FieldElementExpression::Pow( box FieldElementExpression::Identifier("a".into()), box 1u32.into(), @@ -3395,11 +3386,11 @@ mod tests { arguments: vec![], statements: vec![ ZirStatement::Definition( - Variable::field_element("a"), + zir::Variable::field_element("a"), FieldElementExpression::Number(Bn128Field::from(7)).into(), ), ZirStatement::Definition( - Variable::field_element("b"), + zir::Variable::field_element("b"), FieldElementExpression::Pow( box FieldElementExpression::Identifier("a".into()), box 13u32.into(), @@ -3542,12 +3533,12 @@ mod tests { let mut statements_flattened = FlatStatements::new(); let definition = ZirStatement::Definition( - Variable::field_element("b"), + zir::Variable::field_element("b"), FieldElementExpression::Number(Bn128Field::from(42)).into(), ); let statement = ZirStatement::Definition( - Variable::field_element("a"), + zir::Variable::field_element("a"), FieldElementExpression::Div( box FieldElementExpression::Div( box FieldElementExpression::Number(Bn128Field::from(5)), diff --git a/zokrates_core/src/flatten/utils.rs b/zokrates_core/src/flatten/utils.rs index 8fd7b8ef..6fc25792 100644 --- a/zokrates_core/src/flatten/utils.rs +++ b/zokrates_core/src/flatten/utils.rs @@ -1,4 +1,4 @@ -use crate::flat_absy::*; +use zokrates_ast::flat::*; use zokrates_field::Field; pub fn flat_expression_from_bits(v: Vec>) -> FlatExpression { diff --git a/zokrates_core/src/imports.rs b/zokrates_core/src/imports.rs index 760bbbdc..e734762b 100644 --- a/zokrates_core/src/imports.rs +++ b/zokrates_core/src/imports.rs @@ -4,17 +4,17 @@ //! @author Thibaut Schaeffer //! @date 2018 -use crate::absy::*; use crate::compile::parse_module; use crate::compile::{CompileErrorInner, CompileErrors}; use std::collections::HashMap; use std::fmt; use std::io; use std::path::{Path, PathBuf}; +use zokrates_ast::untyped::*; -use crate::absy::types::UnresolvedType; use typed_arena::Arena; use zokrates_ast::common::FlatEmbed; +use zokrates_ast::untyped::types::UnresolvedType; use zokrates_common::Resolver; use zokrates_field::Field; diff --git a/zokrates_core/src/lib.rs b/zokrates_core/src/lib.rs index ae703cda..b6cebfcb 100644 --- a/zokrates_core/src/lib.rs +++ b/zokrates_core/src/lib.rs @@ -1,23 +1,9 @@ #![feature(box_patterns, box_syntax)] -cfg_if::cfg_if! { - if #[cfg(feature = "bellman")] { - extern crate bellman_ce as bellman; - extern crate ff_ce as ff; - extern crate pairing_ce as pairing; - } -} - +pub mod compile; mod flatten; pub mod imports; mod macros; mod optimizer; mod semantics; mod static_analysis; -use zokrates_ast::zir; - -pub use zokrates_ast::untyped as absy; -pub mod compile; -pub use zokrates_ast::flat as flat_absy; -pub mod proof_system; -pub use zokrates_ast::typed as typed_absy; diff --git a/zokrates_core/src/optimizer/duplicate.rs b/zokrates_core/src/optimizer/duplicate.rs index ea596403..68c95409 100644 --- a/zokrates_core/src/optimizer/duplicate.rs +++ b/zokrates_core/src/optimizer/duplicate.rs @@ -53,7 +53,7 @@ impl Folder for DuplicateOptimizer { #[cfg(test)] mod tests { use super::*; - use crate::flat_absy::Variable; + use zokrates_ast::flat::Variable; use zokrates_field::Bn128Field; #[test] diff --git a/zokrates_core/src/optimizer/redefinition.rs b/zokrates_core/src/optimizer/redefinition.rs index 14e42cd7..3445f7fa 100644 --- a/zokrates_core/src/optimizer/redefinition.rs +++ b/zokrates_core/src/optimizer/redefinition.rs @@ -36,8 +36,8 @@ // - `q == k * v if v isn't in i`: insert `v` into `i` and return `c_0` // - otherwise return `c_0` -use crate::flat_absy::Variable; use std::collections::{HashMap, HashSet}; +use zokrates_ast::flat::Variable; use zokrates_ast::ir::folder::Folder; use zokrates_ast::ir::LinComb; use zokrates_ast::ir::*; @@ -198,7 +198,7 @@ impl Folder for RedefinitionOptimizer { #[cfg(test)] mod tests { use super::*; - use crate::flat_absy::Parameter; + use zokrates_ast::flat::Parameter; use zokrates_field::Bn128Field; #[test] diff --git a/zokrates_core/src/semantics.rs b/zokrates_core/src/semantics.rs index f907274b..83f0345b 100644 --- a/zokrates_core/src/semantics.rs +++ b/zokrates_core/src/semantics.rs @@ -4,26 +4,26 @@ //! @author Thibaut Schaeffer //! @date 2017 -use crate::absy::Identifier; -use crate::absy::*; -use crate::typed_absy::types::{GGenericsAssignment, GenericsAssignment}; -use crate::typed_absy::*; -use crate::typed_absy::{DeclarationParameter, DeclarationVariable, Variable}; use num_bigint::BigUint; use std::collections::{btree_map::Entry, BTreeMap, BTreeSet, HashMap, HashSet}; use std::fmt; use std::path::PathBuf; +use zokrates_ast::typed::types::{GGenericsAssignment, GenericsAssignment}; +use zokrates_ast::typed::*; +use zokrates_ast::typed::{DeclarationParameter, DeclarationVariable, Variable}; +use zokrates_ast::untyped::Identifier; +use zokrates_ast::untyped::*; use zokrates_field::Field; -use crate::absy::types::{UnresolvedSignature, UnresolvedType, UserTypeId}; +use zokrates_ast::untyped::types::{UnresolvedSignature, UnresolvedType, UserTypeId}; -use crate::typed_absy::types::{ +use std::hash::{Hash, Hasher}; +use zokrates_ast::typed::types::{ check_type, specialize_declaration_type, ArrayType, DeclarationArrayType, DeclarationConstant, DeclarationFunctionKey, DeclarationSignature, DeclarationStructMember, DeclarationStructType, DeclarationTupleType, DeclarationType, GenericIdentifier, StructLocation, StructMember, TupleType, }; -use std::hash::{Hash, Hasher}; #[derive(PartialEq, Debug)] pub struct ErrorInner { @@ -902,7 +902,7 @@ impl<'ast, T: Field> Checker<'ast, T> { self.insert_into_scope(Variable::with_id_and_type(CoreIdentifier::Constant(CanonicalConstantIdentifier::new( declaration.id, module_id.into(), - )), crate::typed_absy::types::try_from_g_type(ty.clone()).unwrap())); + )), zokrates_ast::typed::types::try_from_g_type(ty.clone()).unwrap())); state .constants @@ -1137,7 +1137,7 @@ impl<'ast, T: Field> Checker<'ast, T> { let ty = specialize_declaration_type(decl_v.clone()._type, &generics).unwrap(); - match self.insert_into_scope(crate::typed_absy::variable::Variable { + match self.insert_into_scope(zokrates_ast::typed::variable::Variable { id: decl_v.clone().id, _type: ty, }) { @@ -1638,7 +1638,7 @@ impl<'ast, T: Field> Checker<'ast, T> { fn check_variable( &mut self, - v: crate::absy::VariableNode<'ast>, + v: zokrates_ast::untyped::VariableNode<'ast>, module_id: &ModuleId, types: &TypeMap<'ast, T>, ) -> Result, Vec> { @@ -1651,7 +1651,7 @@ impl<'ast, T: Field> Checker<'ast, T> { fn check_for_loop( &mut self, - var: crate::absy::VariableNode<'ast>, + var: zokrates_ast::untyped::VariableNode<'ast>, range: (ExpressionNode<'ast>, ExpressionNode<'ast>), statements: Vec>, pos: (Position, Position), @@ -2475,11 +2475,11 @@ impl<'ast, T: Field> Checker<'ast, T> { })?; let kind = match kind { - crate::absy::ConditionalKind::IfElse => { - crate::typed_absy::ConditionalKind::IfElse + zokrates_ast::untyped::ConditionalKind::IfElse => { + zokrates_ast::typed::ConditionalKind::IfElse } - crate::absy::ConditionalKind::Ternary => { - crate::typed_absy::ConditionalKind::Ternary + zokrates_ast::untyped::ConditionalKind::Ternary => { + zokrates_ast::typed::ConditionalKind::Ternary } }; @@ -3627,9 +3627,9 @@ impl<'ast, T: Field> Checker<'ast, T> { #[cfg(test)] mod tests { use super::*; - use crate::absy; - use crate::typed_absy; use lazy_static::lazy_static; + use zokrates_ast::typed; + use zokrates_ast::untyped; use zokrates_field::Bn128Field; lazy_static! { @@ -3752,8 +3752,8 @@ mod tests { ) .mock()]; - let arguments = vec![absy::Parameter { - id: absy::Variable::new("a", UnresolvedType::FieldElement.mock()).mock(), + let arguments = vec![untyped::Parameter { + id: untyped::Variable::new("a", UnresolvedType::FieldElement.mock()).mock(), private: true, } .mock()]; @@ -3955,8 +3955,8 @@ mod tests { let mut f0 = function0(); - f0.value.arguments = vec![absy::Parameter::private( - absy::Variable::new( + f0.value.arguments = vec![untyped::Parameter::private( + untyped::Variable::new( "a", UnresolvedType::array( UnresolvedType::FieldElement.mock(), @@ -3976,8 +3976,8 @@ mod tests { .mock()]); let mut f1 = function0(); - f1.value.arguments = vec![absy::Parameter::private( - absy::Variable::new( + f1.value.arguments = vec![untyped::Parameter::private( + untyped::Variable::new( "a", UnresolvedType::array( UnresolvedType::FieldElement.mock(), @@ -4064,8 +4064,8 @@ mod tests { let mut foo = function0(); - foo.value.arguments = vec![absy::Parameter::private( - absy::Variable::new( + foo.value.arguments = vec![untyped::Parameter::private( + untyped::Variable::new( "a", UnresolvedType::array( UnresolvedType::FieldElement.mock(), @@ -4474,7 +4474,7 @@ mod tests { assert_eq!( checker.check_statement(statement, &*MODULE_ID, &TypeMap::new()), Ok(TypedStatement::Definition( - TypedAssignee::Identifier(typed_absy::Variable::field_element("a")), + TypedAssignee::Identifier(typed::Variable::field_element("a")), FieldElementExpression::Identifier("b".into()).into() )) ); @@ -4491,7 +4491,7 @@ mod tests { let foo_args = vec![]; let foo_statements = vec![ Statement::Declaration( - absy::Variable::new("a", UnresolvedType::FieldElement.mock()).mock(), + untyped::Variable::new("a", UnresolvedType::FieldElement.mock()).mock(), ) .mock(), Statement::Definition( @@ -4576,7 +4576,7 @@ mod tests { let foo_args = vec![]; let foo_statements = vec![ Statement::Declaration( - absy::Variable::new("a", UnresolvedType::FieldElement.mock()).mock(), + untyped::Variable::new("a", UnresolvedType::FieldElement.mock()).mock(), ) .mock(), Statement::Definition( @@ -4603,7 +4603,7 @@ mod tests { let bar_args = vec![]; let bar_statements = vec![ Statement::Declaration( - absy::Variable::new("a", UnresolvedType::FieldElement.mock()).mock(), + untyped::Variable::new("a", UnresolvedType::FieldElement.mock()).mock(), ) .mock(), Statement::Definition( @@ -4679,7 +4679,7 @@ mod tests { // should fail let foo_statements: Vec = vec![ Statement::For( - absy::Variable::new("i", UnresolvedType::Uint(32).mock()).mock(), + untyped::Variable::new("i", UnresolvedType::Uint(32).mock()).mock(), Expression::IntConstant(0usize.into()).mock(), Expression::IntConstant(10usize.into()).mock(), vec![], @@ -4726,7 +4726,7 @@ mod tests { let for_statements = vec![ Statement::Declaration( - absy::Variable::new("a", UnresolvedType::Uint(32).mock()).mock(), + untyped::Variable::new("a", UnresolvedType::Uint(32).mock()).mock(), ) .mock(), Statement::Definition( @@ -4738,7 +4738,7 @@ mod tests { let foo_statements = vec![ Statement::For( - absy::Variable::new("i", UnresolvedType::Uint(32).mock()).mock(), + untyped::Variable::new("i", UnresolvedType::Uint(32).mock()).mock(), Expression::IntConstant(0usize.into()).mock(), Expression::IntConstant(10usize.into()).mock(), for_statements, @@ -4754,9 +4754,9 @@ mod tests { ]; let for_statements_checked = vec![ - TypedStatement::Declaration(typed_absy::Variable::uint("a", UBitwidth::B32)), + TypedStatement::Declaration(typed::Variable::uint("a", UBitwidth::B32)), TypedStatement::Definition( - TypedAssignee::Identifier(typed_absy::Variable::uint("a", UBitwidth::B32)), + TypedAssignee::Identifier(typed::Variable::uint("a", UBitwidth::B32)), UExpressionInner::Identifier("i".into()) .annotate(UBitwidth::B32) .into(), @@ -4765,7 +4765,7 @@ mod tests { let foo_statements_checked = vec![ TypedStatement::For( - typed_absy::Variable::uint("i", UBitwidth::B32), + typed::Variable::uint("i", UBitwidth::B32), 0u32.into(), 10u32.into(), for_statements_checked, @@ -4805,7 +4805,7 @@ mod tests { // should fail let bar_statements: Vec = vec![ Statement::Declaration( - absy::Variable::new("a", UnresolvedType::FieldElement.mock()).mock(), + untyped::Variable::new("a", UnresolvedType::FieldElement.mock()).mock(), ) .mock(), Statement::MultipleDefinition( @@ -4928,7 +4928,7 @@ mod tests { // should fail let bar_statements: Vec = vec![ Statement::Declaration( - absy::Variable::new("a", UnresolvedType::FieldElement.mock()).mock(), + untyped::Variable::new("a", UnresolvedType::FieldElement.mock()).mock(), ) .mock(), Statement::MultipleDefinition( @@ -4990,8 +4990,8 @@ mod tests { .mock()]; let foo = Function { - arguments: vec![crate::absy::Parameter { - id: absy::Variable::new("x", UnresolvedType::FieldElement.mock()).mock(), + arguments: vec![zokrates_ast::untyped::Parameter { + id: untyped::Variable::new("x", UnresolvedType::FieldElement.mock()).mock(), private: false, } .mock()], @@ -5007,11 +5007,11 @@ mod tests { let main_statements: Vec = vec![ Statement::Declaration( - absy::Variable::new("a", UnresolvedType::FieldElement.mock()).mock(), + untyped::Variable::new("a", UnresolvedType::FieldElement.mock()).mock(), ) .mock(), Statement::Declaration( - absy::Variable::new("b", UnresolvedType::FieldElement.mock()).mock(), + untyped::Variable::new("b", UnresolvedType::FieldElement.mock()).mock(), ) .mock(), Statement::MultipleDefinition( @@ -5201,7 +5201,7 @@ mod tests { let main_statements: Vec = vec![ Statement::Declaration( - absy::Variable::new( + untyped::Variable::new( "a", UnresolvedType::array( UnresolvedType::FieldElement.mock(), @@ -5214,7 +5214,7 @@ mod tests { .mock(), Statement::Definition( Assignee::Identifier("a").mock(), - Expression::InlineArray(vec![absy::SpreadOrExpression::Expression( + Expression::InlineArray(vec![untyped::SpreadOrExpression::Expression( Expression::IntConstant(0usize.into()).mock(), )]) .mock(), @@ -5224,7 +5224,7 @@ mod tests { vec![Assignee::Select( box Assignee::Identifier("a").mock(), box RangeOrExpression::Expression( - absy::Expression::IntConstant(0usize.into()).mock(), + untyped::Expression::IntConstant(0usize.into()).mock(), ), ) .mock()], @@ -5373,11 +5373,11 @@ mod tests { // should pass let bar_statements: Vec = vec![ Statement::Declaration( - absy::Variable::new("a", UnresolvedType::FieldElement.mock()).mock(), + untyped::Variable::new("a", UnresolvedType::FieldElement.mock()).mock(), ) .mock(), Statement::Declaration( - absy::Variable::new("b", UnresolvedType::FieldElement.mock()).mock(), + untyped::Variable::new("b", UnresolvedType::FieldElement.mock()).mock(), ) .mock(), Statement::MultipleDefinition( @@ -5403,12 +5403,12 @@ mod tests { ]; let bar_statements_checked: Vec> = vec![ - TypedStatement::Declaration(typed_absy::Variable::field_element("a")), - TypedStatement::Declaration(typed_absy::Variable::field_element("b")), + TypedStatement::Declaration(typed::Variable::field_element("a")), + TypedStatement::Declaration(typed::Variable::field_element("b")), TypedStatement::MultipleDefinition( vec![ - typed_absy::Variable::field_element("a").into(), - typed_absy::Variable::field_element("b").into(), + typed::Variable::field_element("a").into(), + typed::Variable::field_element("b").into(), ], TypedExpressionList::function_call( DeclarationFunctionKey::with_location((*MODULE_ID).clone(), "foo").signature( @@ -5477,12 +5477,12 @@ mod tests { let mut f = function0(); f.value.arguments = vec![ - absy::Parameter::private( - absy::Variable::new("a", UnresolvedType::FieldElement.mock()).mock(), + untyped::Parameter::private( + untyped::Variable::new("a", UnresolvedType::FieldElement.mock()).mock(), ) .mock(), - absy::Parameter::private( - absy::Variable::new("a", UnresolvedType::Boolean.mock()).mock(), + untyped::Parameter::private( + untyped::Variable::new("a", UnresolvedType::Boolean.mock()).mock(), ) .mock(), ]; @@ -5520,8 +5520,8 @@ mod tests { ) .mock()]; - let main1_arguments = vec![crate::absy::Parameter { - id: absy::Variable::new("a", UnresolvedType::FieldElement.mock()).mock(), + let main1_arguments = vec![zokrates_ast::untyped::Parameter { + id: untyped::Variable::new("a", UnresolvedType::FieldElement.mock()).mock(), private: false, } .mock()]; @@ -5599,7 +5599,7 @@ mod tests { let mut checker: Checker = Checker::default(); let _: Result, Vec> = checker.check_statement( Statement::Declaration( - absy::Variable::new("a", UnresolvedType::FieldElement.mock()).mock(), + untyped::Variable::new("a", UnresolvedType::FieldElement.mock()).mock(), ) .mock(), &*MODULE_ID, @@ -5608,7 +5608,7 @@ mod tests { let s2_checked: Result, Vec> = checker .check_statement( Statement::Declaration( - absy::Variable::new("a", UnresolvedType::FieldElement.mock()).mock(), + untyped::Variable::new("a", UnresolvedType::FieldElement.mock()).mock(), ) .mock(), &*MODULE_ID, @@ -5633,7 +5633,7 @@ mod tests { let mut checker: Checker = Checker::default(); let _: Result, Vec> = checker.check_statement( Statement::Declaration( - absy::Variable::new("a", UnresolvedType::FieldElement.mock()).mock(), + untyped::Variable::new("a", UnresolvedType::FieldElement.mock()).mock(), ) .mock(), &*MODULE_ID, @@ -5642,7 +5642,7 @@ mod tests { let s2_checked: Result, Vec> = checker .check_statement( Statement::Declaration( - absy::Variable::new("a", UnresolvedType::Boolean.mock()).mock(), + untyped::Variable::new("a", UnresolvedType::Boolean.mock()).mock(), ) .mock(), &*MODULE_ID, @@ -5659,7 +5659,7 @@ mod tests { mod structs { use super::*; - use crate::typed_absy::types::StructMember; + use zokrates_ast::typed::types::StructMember; /// solver function to create a module at location "" with a single symbol `Foo { foo: field }` fn create_module_with_foo( @@ -6395,8 +6395,8 @@ mod tests { let mut foo_field = function0(); - foo_field.value.arguments = vec![absy::Parameter::private( - absy::Variable { + foo_field.value.arguments = vec![untyped::Parameter::private( + untyped::Variable { id: "a", _type: UnresolvedType::FieldElement.mock(), } @@ -6416,8 +6416,8 @@ mod tests { let mut foo_u32 = function0(); - foo_u32.value.arguments = vec![absy::Parameter::private( - absy::Variable { + foo_u32.value.arguments = vec![untyped::Parameter::private( + untyped::Variable { id: "a", _type: UnresolvedType::Uint(32).mock(), } @@ -6453,17 +6453,17 @@ mod tests { UnresolvedSignature::new().outputs(vec![UnresolvedType::FieldElement.mock()]); let m = Module::with_symbols(vec![ - absy::SymbolDeclaration { + untyped::SymbolDeclaration { id: "foo", symbol: Symbol::Here(SymbolDefinition::Function(foo_field)), } .mock(), - absy::SymbolDeclaration { + untyped::SymbolDeclaration { id: "foo", symbol: Symbol::Here(SymbolDefinition::Function(foo_u32)), } .mock(), - absy::SymbolDeclaration { + untyped::SymbolDeclaration { id: "main", symbol: Symbol::Here(SymbolDefinition::Function(main)), } @@ -6502,7 +6502,7 @@ mod tests { checker .check_statement( Statement::Declaration( - absy::Variable::new("a", UnresolvedType::FieldElement.mock()).mock(), + untyped::Variable::new("a", UnresolvedType::FieldElement.mock()).mock(), ) .mock(), &*MODULE_ID, @@ -6512,9 +6512,9 @@ mod tests { assert_eq!( checker.check_assignee(a, &*MODULE_ID, &TypeMap::new()), - Ok(TypedAssignee::Identifier( - typed_absy::Variable::field_element("a") - )) + Ok(TypedAssignee::Identifier(typed::Variable::field_element( + "a" + ))) ); } @@ -6534,7 +6534,7 @@ mod tests { checker .check_statement( Statement::Declaration( - absy::Variable::new( + untyped::Variable::new( "a", UnresolvedType::array( UnresolvedType::FieldElement.mock(), @@ -6553,9 +6553,10 @@ mod tests { assert_eq!( checker.check_assignee(a, &*MODULE_ID, &TypeMap::new()), Ok(TypedAssignee::Select( - box TypedAssignee::Identifier(typed_absy::Variable::field_array( + box TypedAssignee::Identifier(typed::Variable::array( "a", - 33u32.into() + GType::FieldElement, + 33u32 )), box 2u32.into() )) @@ -6584,7 +6585,7 @@ mod tests { checker .check_statement( Statement::Declaration( - absy::Variable::new( + untyped::Variable::new( "a", UnresolvedType::array( UnresolvedType::array( @@ -6608,7 +6609,7 @@ mod tests { checker.check_assignee(a, &*MODULE_ID, &TypeMap::new()), Ok(TypedAssignee::Select( box TypedAssignee::Select( - box TypedAssignee::Identifier(typed_absy::Variable::array( + box TypedAssignee::Identifier(typed::Variable::array( "a", Type::array((Type::FieldElement, 33u32)), 42u32, diff --git a/zokrates_core/src/static_analysis/branch_isolator.rs b/zokrates_core/src/static_analysis/branch_isolator.rs index 4ad54d28..ee41233a 100644 --- a/zokrates_core/src/static_analysis/branch_isolator.rs +++ b/zokrates_core/src/static_analysis/branch_isolator.rs @@ -3,8 +3,8 @@ // `if c then a else b fi` becomes `if c then { a } else { b } fi`, and down the line any statements resulting from trating `a` and `b` can be safely kept inside the respective blocks. -use crate::typed_absy::*; use zokrates_ast::typed::folder::*; +use zokrates_ast::typed::*; use zokrates_field::Field; pub struct Isolator; diff --git a/zokrates_core/src/static_analysis/condition_redefiner.rs b/zokrates_core/src/static_analysis/condition_redefiner.rs index b09f68ba..b4a5fc70 100644 --- a/zokrates_core/src/static_analysis/condition_redefiner.rs +++ b/zokrates_core/src/static_analysis/condition_redefiner.rs @@ -1,4 +1,4 @@ -use crate::typed_absy::{ +use zokrates_ast::typed::{ folder::*, BlockExpression, BooleanExpression, Conditional, ConditionalExpression, ConditionalOrExpression, CoreIdentifier, Expr, Identifier, TypedProgram, TypedStatement, Variable, @@ -89,7 +89,7 @@ impl<'ast, T: Field> Folder<'ast, T> for ConditionRedefiner<'ast, T> { #[cfg(test)] mod tests { use super::*; - use crate::typed_absy::{ + use zokrates_ast::typed::{ Block, BooleanExpression, Conditional, ConditionalKind, FieldElementExpression, Type, }; use zokrates_field::Bn128Field; diff --git a/zokrates_core/src/static_analysis/constant_argument_checker.rs b/zokrates_core/src/static_analysis/constant_argument_checker.rs index 160eb806..5846073e 100644 --- a/zokrates_core/src/static_analysis/constant_argument_checker.rs +++ b/zokrates_core/src/static_analysis/constant_argument_checker.rs @@ -1,11 +1,11 @@ -use crate::typed_absy::TypedProgram; -use crate::typed_absy::{ +use std::fmt; +use zokrates_ast::common::FlatEmbed; +use zokrates_ast::typed::TypedProgram; +use zokrates_ast::typed::{ result_folder::ResultFolder, result_folder::{fold_expression_list_inner, fold_uint_expression_inner}, Constant, TypedExpressionListInner, Types, UBitwidth, UExpressionInner, }; -use std::fmt; -use zokrates_ast::common::FlatEmbed; use zokrates_field::Field; pub struct ConstantArgumentChecker; diff --git a/zokrates_core/src/static_analysis/constant_inliner.rs b/zokrates_core/src/static_analysis/constant_inliner.rs deleted file mode 100644 index d2b803e8..00000000 --- a/zokrates_core/src/static_analysis/constant_inliner.rs +++ /dev/null @@ -1,973 +0,0 @@ -use crate::static_analysis::Propagator; -use crate::typed_absy::result_folder::*; -use crate::typed_absy::types::DeclarationConstant; -use crate::typed_absy::*; -use std::collections::HashMap; -use std::convert::TryInto; -use std::fmt; -use zokrates_field::Field; - -type ProgramConstants<'ast, T> = - HashMap, TypedExpression<'ast, T>>>; - -#[derive(Debug, PartialEq)] -pub enum Error { - Type(String), -} - -impl fmt::Display for Error { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match self { - Error::Type(s) => write!(f, "{}", s), - } - } -} -pub struct ConstantInliner<'ast, T> { - modules: TypedModules<'ast, T>, - location: OwnedTypedModuleId, - constants: ProgramConstants<'ast, T>, -} - -impl<'ast, 'a, T: Field> ConstantInliner<'ast, T> { - pub fn new( - modules: TypedModules<'ast, T>, - location: OwnedTypedModuleId, - constants: ProgramConstants<'ast, T>, - ) -> Self { - ConstantInliner { - modules, - location, - constants, - } - } - pub fn inline(p: TypedProgram<'ast, T>) -> Result, Error> { - let constants = ProgramConstants::new(); - let mut inliner = ConstantInliner::new(p.modules.clone(), p.main.clone(), constants); - inliner.fold_program(p) - } - - fn change_location(&mut self, location: OwnedTypedModuleId) -> OwnedTypedModuleId { - let prev = self.location.clone(); - self.location = location; - self.constants.entry(self.location.clone()).or_default(); - prev - } - - fn treated(&self, id: &TypedModuleId) -> bool { - self.constants.contains_key(id) - } - - fn get_constant( - &self, - id: &CanonicalConstantIdentifier<'ast>, - ) -> Option> { - self.constants - .get(&id.module) - .and_then(|constants| constants.get(&id.id.into())) - .cloned() - } - - fn get_constant_for_identifier( - &self, - id: &Identifier<'ast>, - ) -> Option> { - self.constants - .get(&self.location) - .and_then(|constants| constants.get(&id)) - .cloned() - } -} - -impl<'ast, T: Field> ResultFolder<'ast, T> for ConstantInliner<'ast, T> { - type Error = Error; - - fn fold_program( - &mut self, - p: TypedProgram<'ast, T>, - ) -> Result, Self::Error> { - self.fold_module_id(p.main.clone())?; - - Ok(TypedProgram { - modules: std::mem::take(&mut self.modules), - ..p - }) - } - - fn fold_module_id( - &mut self, - id: OwnedTypedModuleId, - ) -> Result { - // anytime we encounter a module id, visit the corresponding module if it hasn't been done yet - if !self.treated(&id) { - let current_m_id = self.change_location(id.clone()); - let m = self.modules.remove(&id).unwrap(); - let m = self.fold_module(m)?; - self.modules.insert(id.clone(), m); - self.change_location(current_m_id); - } - Ok(id) - } - - fn fold_module( - &mut self, - m: TypedModule<'ast, T>, - ) -> Result, Self::Error> { - Ok(TypedModule { - constants: m - .constants - .into_iter() - .map(|(id, tc)| { - - let id = self.fold_canonical_constant_identifier(id)?; - - let constant = match tc { - TypedConstantSymbol::There(imported_id) => { - // visit the imported symbol. This triggers visiting the corresponding module if needed - let imported_id = self.fold_canonical_constant_identifier(imported_id)?; - // after that, the constant must have been defined defined in the global map. It is already reduced - // to a literal, so running propagation isn't required - self.get_constant(&imported_id).unwrap() - } - TypedConstantSymbol::Here(c) => { - let non_propagated_constant = fold_constant(self, c)?.expression; - // folding the constant above only reduces it to an expression containing only literals, not to a single literal. - // propagating with an empty map of constants reduces it to a single literal - Propagator::with_constants(&mut HashMap::default()) - .fold_expression(non_propagated_constant) - .unwrap() - } - }; - - if crate::typed_absy::types::try_from_g_type::<_, UExpression<'ast, T>>(*id.ty.clone()).unwrap() == constant.get_type() { - // add to the constant map. The value added is always a single litteral - self.constants - .get_mut(&self.location) - .unwrap() - .insert(id.id.into(), constant.clone()); - - Ok(( - id, - TypedConstantSymbol::Here(TypedConstant { - expression: constant, - }), - )) - } else { - Err(Error::Type(format!("Expression of type `{}` cannot be assigned to constant `{}` of type `{}`", constant.get_type(), id.id, id.ty))) - } - }) - .collect::, _>>()?, - functions: m - .functions - .into_iter() - .map::, _>(|(key, fun)| { - Ok(( - self.fold_declaration_function_key(key)?, - self.fold_function_symbol(fun)?, - )) - }) - .collect::, _>>() - .into_iter() - .flatten() - .collect(), - }) - } - - fn fold_declaration_constant( - &mut self, - c: DeclarationConstant<'ast>, - ) -> Result, Self::Error> { - match c { - // replace constants by their concrete value in declaration types - DeclarationConstant::Constant(id) => { - let id = CanonicalConstantIdentifier { - module: self.fold_module_id(id.module)?, - ..id - }; - - Ok(DeclarationConstant::Concrete(match self.get_constant(&id).unwrap() { - TypedExpression::Uint(UExpression { - inner: UExpressionInner::Value(v), - .. - }) => v as u32, - _ => unreachable!("all constants found in declaration types should be reduceable to u32 literals"), - })) - } - c => Ok(c), - } - } - - fn fold_field_expression( - &mut self, - e: FieldElementExpression<'ast, T>, - ) -> Result, Self::Error> { - match e { - FieldElementExpression::Identifier(ref id) => { - match self.get_constant_for_identifier(id) { - Some(c) => Ok(c.try_into().unwrap()), - None => fold_field_expression(self, e), - } - } - e => fold_field_expression(self, e), - } - } - - fn fold_boolean_expression( - &mut self, - e: BooleanExpression<'ast, T>, - ) -> Result, Self::Error> { - match e { - BooleanExpression::Identifier(ref id) => match self.get_constant_for_identifier(id) { - Some(c) => Ok(c.try_into().unwrap()), - None => fold_boolean_expression(self, e), - }, - e => fold_boolean_expression(self, e), - } - } - - fn fold_uint_expression_inner( - &mut self, - size: UBitwidth, - e: UExpressionInner<'ast, T>, - ) -> Result, Self::Error> { - match e { - UExpressionInner::Identifier(ref id) => match self.get_constant_for_identifier(id) { - Some(c) => { - let e: UExpression<'ast, T> = c.try_into().unwrap(); - Ok(e.into_inner()) - } - None => fold_uint_expression_inner(self, size, e), - }, - e => fold_uint_expression_inner(self, size, e), - } - } - - fn fold_array_expression_inner( - &mut self, - ty: &ArrayType<'ast, T>, - e: ArrayExpressionInner<'ast, T>, - ) -> Result, Self::Error> { - match e { - ArrayExpressionInner::Identifier(ref id) => { - match self.get_constant_for_identifier(id) { - Some(c) => { - let e: ArrayExpression<'ast, T> = c.try_into().unwrap(); - Ok(e.into_inner()) - } - None => fold_array_expression_inner(self, ty, e), - } - } - e => fold_array_expression_inner(self, ty, e), - } - } - - fn fold_struct_expression_inner( - &mut self, - ty: &StructType<'ast, T>, - e: StructExpressionInner<'ast, T>, - ) -> Result, Self::Error> { - match e { - StructExpressionInner::Identifier(ref id) => match self.get_constant_for_identifier(id) - { - Some(c) => { - let e: StructExpression<'ast, T> = c.try_into().unwrap(); - Ok(e.into_inner()) - } - None => fold_struct_expression_inner(self, ty, e), - }, - e => fold_struct_expression_inner(self, ty, e), - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::typed_absy::types::DeclarationSignature; - use crate::typed_absy::{ - DeclarationArrayType, DeclarationFunctionKey, DeclarationType, FieldElementExpression, - GType, Identifier, TypedConstant, TypedExpression, TypedFunction, TypedFunctionSymbol, - TypedStatement, - }; - use zokrates_field::Bn128Field; - - #[test] - fn inline_const_field() { - // const field a = 1 - // - // def main() -> field: - // return a - - let const_id = "a"; - let main: TypedFunction = TypedFunction { - arguments: vec![], - statements: vec![TypedStatement::Return(vec![ - FieldElementExpression::Identifier(Identifier::from(const_id)).into(), - ])], - signature: DeclarationSignature::new() - .inputs(vec![]) - .outputs(vec![DeclarationType::FieldElement]), - }; - - let constants: TypedConstantSymbols<_> = vec![( - CanonicalConstantIdentifier::new( - const_id, - "main".into(), - DeclarationType::FieldElement, - ), - TypedConstantSymbol::Here(TypedConstant::new(TypedExpression::FieldElement( - FieldElementExpression::Number(Bn128Field::from(1)), - ))), - )] - .into_iter() - .collect(); - - let program = TypedProgram { - main: "main".into(), - modules: vec![( - "main".into(), - TypedModule { - functions: vec![( - DeclarationFunctionKey::with_location("main", "main").signature( - DeclarationSignature::new() - .inputs(vec![]) - .outputs(vec![DeclarationType::FieldElement]), - ), - TypedFunctionSymbol::Here(main), - )] - .into_iter() - .collect(), - constants: constants.clone(), - }, - )] - .into_iter() - .collect(), - }; - - let program = ConstantInliner::inline(program); - - let expected_main = TypedFunction { - arguments: vec![], - statements: vec![TypedStatement::Return(vec![ - FieldElementExpression::Number(Bn128Field::from(1)).into(), - ])], - signature: DeclarationSignature::new() - .inputs(vec![]) - .outputs(vec![DeclarationType::FieldElement]), - }; - - let expected_program: TypedProgram = TypedProgram { - main: "main".into(), - modules: vec![( - "main".into(), - TypedModule { - functions: vec![( - DeclarationFunctionKey::with_location("main", "main").signature( - DeclarationSignature::new() - .inputs(vec![]) - .outputs(vec![DeclarationType::FieldElement]), - ), - TypedFunctionSymbol::Here(expected_main), - )] - .into_iter() - .collect(), - constants, - }, - )] - .into_iter() - .collect(), - }; - - assert_eq!(program, Ok(expected_program)) - } - - #[test] - fn inline_const_boolean() { - // const bool a = true - // - // def main() -> bool: - // return a - - let const_id = "a"; - let main: TypedFunction = TypedFunction { - arguments: vec![], - statements: vec![TypedStatement::Return(vec![BooleanExpression::Identifier( - Identifier::from(const_id), - ) - .into()])], - signature: DeclarationSignature::new() - .inputs(vec![]) - .outputs(vec![DeclarationType::Boolean]), - }; - - let constants: TypedConstantSymbols<_> = vec![( - CanonicalConstantIdentifier::new(const_id, "main".into(), DeclarationType::Boolean), - TypedConstantSymbol::Here(TypedConstant::new(TypedExpression::Boolean( - BooleanExpression::Value(true), - ))), - )] - .into_iter() - .collect(); - - let program = TypedProgram { - main: "main".into(), - modules: vec![( - "main".into(), - TypedModule { - functions: vec![( - DeclarationFunctionKey::with_location("main", "main").signature( - DeclarationSignature::new() - .inputs(vec![]) - .outputs(vec![DeclarationType::Boolean]), - ), - TypedFunctionSymbol::Here(main), - )] - .into_iter() - .collect(), - constants: constants.clone(), - }, - )] - .into_iter() - .collect(), - }; - - let program = ConstantInliner::inline(program); - - let expected_main = TypedFunction { - arguments: vec![], - statements: vec![TypedStatement::Return(vec![ - BooleanExpression::Value(true).into() - ])], - signature: DeclarationSignature::new() - .inputs(vec![]) - .outputs(vec![DeclarationType::Boolean]), - }; - - let expected_program: TypedProgram = TypedProgram { - main: "main".into(), - modules: vec![( - "main".into(), - TypedModule { - functions: vec![( - DeclarationFunctionKey::with_location("main", "main").signature( - DeclarationSignature::new() - .inputs(vec![]) - .outputs(vec![DeclarationType::Boolean]), - ), - TypedFunctionSymbol::Here(expected_main), - )] - .into_iter() - .collect(), - constants, - }, - )] - .into_iter() - .collect(), - }; - - assert_eq!(program, Ok(expected_program)) - } - - #[test] - fn inline_const_uint() { - // const u32 a = 0x00000001 - // - // def main() -> u32: - // return a - - let const_id = "a"; - let main: TypedFunction = TypedFunction { - arguments: vec![], - statements: vec![TypedStatement::Return(vec![UExpressionInner::Identifier( - Identifier::from(const_id), - ) - .annotate(UBitwidth::B32) - .into()])], - signature: DeclarationSignature::new() - .inputs(vec![]) - .outputs(vec![DeclarationType::Uint(UBitwidth::B32)]), - }; - - let constants: TypedConstantSymbols<_> = vec![( - CanonicalConstantIdentifier::new( - const_id, - "main".into(), - DeclarationType::Uint(UBitwidth::B32), - ), - TypedConstantSymbol::Here(TypedConstant::new( - UExpressionInner::Value(1u128) - .annotate(UBitwidth::B32) - .into(), - )), - )] - .into_iter() - .collect(); - - let program = TypedProgram { - main: "main".into(), - modules: vec![( - "main".into(), - TypedModule { - functions: vec![( - DeclarationFunctionKey::with_location("main", "main").signature( - DeclarationSignature::new() - .inputs(vec![]) - .outputs(vec![DeclarationType::Uint(UBitwidth::B32)]), - ), - TypedFunctionSymbol::Here(main), - )] - .into_iter() - .collect(), - constants: constants.clone(), - }, - )] - .into_iter() - .collect(), - }; - - let program = ConstantInliner::inline(program); - - let expected_main = TypedFunction { - arguments: vec![], - statements: vec![TypedStatement::Return(vec![UExpressionInner::Value(1u128) - .annotate(UBitwidth::B32) - .into()])], - signature: DeclarationSignature::new() - .inputs(vec![]) - .outputs(vec![DeclarationType::Uint(UBitwidth::B32)]), - }; - - let expected_program: TypedProgram = TypedProgram { - main: "main".into(), - modules: vec![( - "main".into(), - TypedModule { - functions: vec![( - DeclarationFunctionKey::with_location("main", "main").signature( - DeclarationSignature::new() - .inputs(vec![]) - .outputs(vec![DeclarationType::Uint(UBitwidth::B32)]), - ), - TypedFunctionSymbol::Here(expected_main), - )] - .into_iter() - .collect(), - constants, - }, - )] - .into_iter() - .collect(), - }; - - assert_eq!(program, Ok(expected_program)) - } - - #[test] - fn inline_const_field_array() { - // const field[2] a = [2, 2] - // - // def main() -> field: - // return a[0] + a[1] - - let const_id = "a"; - let main: TypedFunction = TypedFunction { - arguments: vec![], - statements: vec![TypedStatement::Return(vec![FieldElementExpression::Add( - FieldElementExpression::select( - ArrayExpressionInner::Identifier(Identifier::from(const_id)) - .annotate(GType::FieldElement, 2u32), - UExpressionInner::Value(0u128).annotate(UBitwidth::B32), - ) - .into(), - FieldElementExpression::select( - ArrayExpressionInner::Identifier(Identifier::from(const_id)) - .annotate(GType::FieldElement, 2u32), - UExpressionInner::Value(1u128).annotate(UBitwidth::B32), - ) - .into(), - ) - .into()])], - signature: DeclarationSignature::new() - .inputs(vec![]) - .outputs(vec![DeclarationType::FieldElement]), - }; - - let constants: TypedConstantSymbols<_> = vec![( - CanonicalConstantIdentifier::new( - const_id, - "main".into(), - DeclarationType::Array(DeclarationArrayType::new( - DeclarationType::FieldElement, - 2u32, - )), - ), - TypedConstantSymbol::Here(TypedConstant::new(TypedExpression::Array( - ArrayExpressionInner::Value( - vec![ - FieldElementExpression::Number(Bn128Field::from(2)).into(), - FieldElementExpression::Number(Bn128Field::from(2)).into(), - ] - .into(), - ) - .annotate(GType::FieldElement, 2u32), - ))), - )] - .into_iter() - .collect(); - - let program = TypedProgram { - main: "main".into(), - modules: vec![( - "main".into(), - TypedModule { - functions: vec![( - DeclarationFunctionKey::with_location("main", "main").signature( - DeclarationSignature::new() - .inputs(vec![]) - .outputs(vec![DeclarationType::FieldElement]), - ), - TypedFunctionSymbol::Here(main), - )] - .into_iter() - .collect(), - constants: constants.clone(), - }, - )] - .into_iter() - .collect(), - }; - - let program = ConstantInliner::inline(program); - - let expected_main = TypedFunction { - arguments: vec![], - statements: vec![TypedStatement::Return(vec![FieldElementExpression::Add( - FieldElementExpression::select( - ArrayExpressionInner::Value( - vec![ - FieldElementExpression::Number(Bn128Field::from(2)).into(), - FieldElementExpression::Number(Bn128Field::from(2)).into(), - ] - .into(), - ) - .annotate(GType::FieldElement, 2u32), - UExpressionInner::Value(0u128).annotate(UBitwidth::B32), - ) - .into(), - FieldElementExpression::select( - ArrayExpressionInner::Value( - vec![ - FieldElementExpression::Number(Bn128Field::from(2)).into(), - FieldElementExpression::Number(Bn128Field::from(2)).into(), - ] - .into(), - ) - .annotate(GType::FieldElement, 2u32), - UExpressionInner::Value(1u128).annotate(UBitwidth::B32), - ) - .into(), - ) - .into()])], - signature: DeclarationSignature::new() - .inputs(vec![]) - .outputs(vec![DeclarationType::FieldElement]), - }; - - let expected_program: TypedProgram = TypedProgram { - main: "main".into(), - modules: vec![( - "main".into(), - TypedModule { - functions: vec![( - DeclarationFunctionKey::with_location("main", "main").signature( - DeclarationSignature::new() - .inputs(vec![]) - .outputs(vec![DeclarationType::FieldElement]), - ), - TypedFunctionSymbol::Here(expected_main), - )] - .into_iter() - .collect(), - constants, - }, - )] - .into_iter() - .collect(), - }; - - assert_eq!(program, Ok(expected_program)) - } - - #[test] - fn inline_nested_const_field() { - // const field a = 1 - // const field b = a + 1 - // - // def main() -> field: - // return b - - let const_a_id = "a"; - let const_b_id = "b"; - - let main: TypedFunction = TypedFunction { - arguments: vec![], - statements: vec![TypedStatement::Return(vec![ - FieldElementExpression::Identifier(Identifier::from(const_b_id)).into(), - ])], - signature: DeclarationSignature::new() - .inputs(vec![]) - .outputs(vec![DeclarationType::FieldElement]), - }; - - let program = TypedProgram { - main: "main".into(), - modules: vec![( - "main".into(), - TypedModule { - functions: vec![( - DeclarationFunctionKey::with_location("main", "main").signature( - DeclarationSignature::new() - .inputs(vec![]) - .outputs(vec![DeclarationType::FieldElement]), - ), - TypedFunctionSymbol::Here(main), - )] - .into_iter() - .collect(), - constants: vec![ - ( - CanonicalConstantIdentifier::new( - const_a_id, - "main".into(), - DeclarationType::FieldElement, - ), - TypedConstantSymbol::Here(TypedConstant::new( - TypedExpression::FieldElement(FieldElementExpression::Number( - Bn128Field::from(1), - )), - )), - ), - ( - CanonicalConstantIdentifier::new( - const_b_id, - "main".into(), - DeclarationType::FieldElement, - ), - TypedConstantSymbol::Here(TypedConstant::new( - TypedExpression::FieldElement(FieldElementExpression::Add( - box FieldElementExpression::Identifier(Identifier::from( - const_a_id, - )), - box FieldElementExpression::Number(Bn128Field::from(1)), - )), - )), - ), - ] - .into_iter() - .collect(), - }, - )] - .into_iter() - .collect(), - }; - - let program = ConstantInliner::inline(program); - - let expected_main = TypedFunction { - arguments: vec![], - statements: vec![TypedStatement::Return(vec![ - FieldElementExpression::Number(Bn128Field::from(2)).into(), - ])], - signature: DeclarationSignature::new() - .inputs(vec![]) - .outputs(vec![DeclarationType::FieldElement]), - }; - - let expected_program: TypedProgram = TypedProgram { - main: "main".into(), - modules: vec![( - "main".into(), - TypedModule { - functions: vec![( - DeclarationFunctionKey::with_location("main", "main").signature( - DeclarationSignature::new() - .inputs(vec![]) - .outputs(vec![DeclarationType::FieldElement]), - ), - TypedFunctionSymbol::Here(expected_main), - )] - .into_iter() - .collect(), - constants: vec![ - ( - CanonicalConstantIdentifier::new( - const_a_id, - "main".into(), - DeclarationType::FieldElement, - ), - TypedConstantSymbol::Here(TypedConstant::new( - TypedExpression::FieldElement(FieldElementExpression::Number( - Bn128Field::from(1), - )), - )), - ), - ( - CanonicalConstantIdentifier::new( - const_b_id, - "main".into(), - DeclarationType::FieldElement, - ), - TypedConstantSymbol::Here(TypedConstant::new( - TypedExpression::FieldElement(FieldElementExpression::Number( - Bn128Field::from(2), - )), - )), - ), - ] - .into_iter() - .collect(), - }, - )] - .into_iter() - .collect(), - }; - - assert_eq!(program, Ok(expected_program)) - } - - #[test] - fn inline_imported_constant() { - // --------------------- - // module `foo` - // -------------------- - // const field FOO = 42 - // - // def main(): - // return - // - // --------------------- - // module `main` - // --------------------- - // from "foo" import FOO - // - // def main() -> field: - // return FOO - - let foo_const_id = "FOO"; - let foo_module = TypedModule { - functions: vec![( - DeclarationFunctionKey::with_location("main", "main") - .signature(DeclarationSignature::new().inputs(vec![]).outputs(vec![])), - TypedFunctionSymbol::Here(TypedFunction { - arguments: vec![], - statements: vec![], - signature: DeclarationSignature::new().inputs(vec![]).outputs(vec![]), - }), - )] - .into_iter() - .collect(), - constants: vec![( - CanonicalConstantIdentifier::new( - foo_const_id, - "foo".into(), - DeclarationType::FieldElement, - ), - TypedConstantSymbol::Here(TypedConstant::new(TypedExpression::FieldElement( - FieldElementExpression::Number(Bn128Field::from(42)), - ))), - )] - .into_iter() - .collect(), - }; - - let main_module = TypedModule { - functions: vec![( - DeclarationFunctionKey::with_location("main", "main").signature( - DeclarationSignature::new() - .inputs(vec![]) - .outputs(vec![DeclarationType::FieldElement]), - ), - TypedFunctionSymbol::Here(TypedFunction { - arguments: vec![], - statements: vec![TypedStatement::Return(vec![ - FieldElementExpression::Identifier(Identifier::from(foo_const_id)).into(), - ])], - signature: DeclarationSignature::new() - .inputs(vec![]) - .outputs(vec![DeclarationType::FieldElement]), - }), - )] - .into_iter() - .collect(), - constants: vec![( - CanonicalConstantIdentifier::new( - foo_const_id, - "main".into(), - DeclarationType::FieldElement, - ), - TypedConstantSymbol::There(CanonicalConstantIdentifier::new( - foo_const_id, - "foo".into(), - DeclarationType::FieldElement, - )), - )] - .into_iter() - .collect(), - }; - - let program = TypedProgram { - main: "main".into(), - modules: vec![ - ("main".into(), main_module), - ("foo".into(), foo_module.clone()), - ] - .into_iter() - .collect(), - }; - - let program = ConstantInliner::inline(program); - let expected_main_module = TypedModule { - functions: vec![( - DeclarationFunctionKey::with_location("main", "main").signature( - DeclarationSignature::new() - .inputs(vec![]) - .outputs(vec![DeclarationType::FieldElement]), - ), - TypedFunctionSymbol::Here(TypedFunction { - arguments: vec![], - statements: vec![TypedStatement::Return(vec![ - FieldElementExpression::Number(Bn128Field::from(42)).into(), - ])], - signature: DeclarationSignature::new() - .inputs(vec![]) - .outputs(vec![DeclarationType::FieldElement]), - }), - )] - .into_iter() - .collect(), - constants: vec![( - CanonicalConstantIdentifier::new( - foo_const_id, - "main".into(), - DeclarationType::FieldElement, - ), - TypedConstantSymbol::Here(TypedConstant::new(TypedExpression::FieldElement( - FieldElementExpression::Number(Bn128Field::from(42)), - ))), - )] - .into_iter() - .collect(), - }; - - let expected_program: TypedProgram = TypedProgram { - main: "main".into(), - modules: vec![ - ("main".into(), expected_main_module), - ("foo".into(), foo_module), - ] - .into_iter() - .collect(), - }; - - assert_eq!(program, Ok(expected_program)) - } -} diff --git a/zokrates_core/src/static_analysis/constant_resolver.rs b/zokrates_core/src/static_analysis/constant_resolver.rs index 62fe07cc..b4d7fdac 100644 --- a/zokrates_core/src/static_analysis/constant_resolver.rs +++ b/zokrates_core/src/static_analysis/constant_resolver.rs @@ -2,9 +2,9 @@ // This does *not* reduce constants to their literal value // This step cannot fail as the imports were checked during semantics -use crate::typed_absy::*; use std::collections::HashMap; use zokrates_ast::typed::folder::*; +use zokrates_ast::typed::*; use zokrates_field::Field; // a map of the canonical constants in this program. with all imported constants reduced to their canonical value @@ -109,8 +109,8 @@ impl<'ast, T: Field> Folder<'ast, T> for ConstantResolver<'ast, T> { #[cfg(test)] mod tests { use super::*; - use crate::typed_absy::types::DeclarationSignature; - use crate::typed_absy::{ + use zokrates_ast::typed::types::DeclarationSignature; + use zokrates_ast::typed::{ DeclarationArrayType, DeclarationFunctionKey, DeclarationType, FieldElementExpression, GType, Identifier, TypedConstant, TypedExpression, TypedFunction, TypedFunctionSymbol, TypedStatement, diff --git a/zokrates_core/src/static_analysis/flat_propagation.rs b/zokrates_core/src/static_analysis/flat_propagation.rs index 36d9a72e..f69b9313 100644 --- a/zokrates_core/src/static_analysis/flat_propagation.rs +++ b/zokrates_core/src/static_analysis/flat_propagation.rs @@ -4,11 +4,12 @@ //! @author Thibaut Schaeffer //! @date 2018 -use crate::flat_absy::*; use std::collections::HashMap; use zokrates_ast::flat::folder::*; +use zokrates_ast::flat::*; use zokrates_field::Field; +#[derive(Default)] struct Propagator { constants: HashMap, } @@ -77,39 +78,45 @@ mod tests { #[test] fn add() { + let mut propagator = Propagator::default(); + let e = FlatExpression::Add( box FlatExpression::Number(Bn128Field::from(2)), box FlatExpression::Number(Bn128Field::from(3)), ); assert_eq!( - e.propagate(&mut HashMap::new()), + propagator.fold_expression(e), FlatExpression::Number(Bn128Field::from(5)) ); } #[test] fn sub() { + let mut propagator = Propagator::default(); + let e = FlatExpression::Sub( box FlatExpression::Number(Bn128Field::from(3)), box FlatExpression::Number(Bn128Field::from(2)), ); assert_eq!( - e.propagate(&mut HashMap::new()), + propagator.fold_expression(e), FlatExpression::Number(Bn128Field::from(1)) ); } #[test] fn mult() { + let mut propagator = Propagator::default(); + let e = FlatExpression::Mult( box FlatExpression::Number(Bn128Field::from(3)), box FlatExpression::Number(Bn128Field::from(2)), ); assert_eq!( - e.propagate(&mut HashMap::new()), + propagator.fold_expression(e), FlatExpression::Number(Bn128Field::from(6)) ); } diff --git a/zokrates_core/src/static_analysis/flatten_complex_types.rs b/zokrates_core/src/static_analysis/flatten_complex_types.rs index 1d8ab686..cdbe2367 100644 --- a/zokrates_core/src/static_analysis/flatten_complex_types.rs +++ b/zokrates_core/src/static_analysis/flatten_complex_types.rs @@ -1,7 +1,7 @@ -use crate::typed_absy::types::UBitwidth; -use crate::typed_absy::{self, Expr}; -use crate::zir; use std::marker::PhantomData; +use zokrates_ast::typed::types::UBitwidth; +use zokrates_ast::typed::{self, Expr}; +use zokrates_ast::zir; use zokrates_field::Field; use std::convert::{TryFrom, TryInto}; @@ -13,23 +13,23 @@ pub struct Flattener { fn flatten_identifier_rec<'ast>( id: zir::SourceIdentifier<'ast>, - ty: &typed_absy::types::ConcreteType, + ty: &typed::types::ConcreteType, ) -> Vec> { match ty { - typed_absy::ConcreteType::Int => unreachable!(), - typed_absy::ConcreteType::FieldElement => vec![zir::Variable { + typed::ConcreteType::Int => unreachable!(), + typed::ConcreteType::FieldElement => vec![zir::Variable { id: zir::Identifier::Source(id), _type: zir::Type::FieldElement, }], - typed_absy::types::ConcreteType::Boolean => vec![zir::Variable { + typed::types::ConcreteType::Boolean => vec![zir::Variable { id: zir::Identifier::Source(id), _type: zir::Type::Boolean, }], - typed_absy::types::ConcreteType::Uint(bitwidth) => vec![zir::Variable { + typed::types::ConcreteType::Uint(bitwidth) => vec![zir::Variable { id: zir::Identifier::Source(id), _type: zir::Type::uint(bitwidth.to_usize()), }], - typed_absy::types::ConcreteType::Array(array_type) => (0..array_type.size) + typed::types::ConcreteType::Array(array_type) => (0..array_type.size) .flat_map(|i| { flatten_identifier_rec( zir::SourceIdentifier::Select(box id.clone(), i), @@ -37,7 +37,7 @@ fn flatten_identifier_rec<'ast>( ) }) .collect(), - typed_absy::types::ConcreteType::Struct(members) => members + typed::types::ConcreteType::Struct(members) => members .iter() .flat_map(|struct_member| { flatten_identifier_rec( @@ -46,7 +46,7 @@ fn flatten_identifier_rec<'ast>( ) }) .collect(), - typed_absy::types::ConcreteType::Tuple(tuple_ty) => tuple_ty + typed::types::ConcreteType::Tuple(tuple_ty) => tuple_ty .elements .iter() .enumerate() @@ -65,7 +65,7 @@ trait Flatten<'ast, T: Field> { ) -> Vec>; } -impl<'ast, T: Field> Flatten<'ast, T> for typed_absy::FieldElementExpression<'ast, T> { +impl<'ast, T: Field> Flatten<'ast, T> for typed::FieldElementExpression<'ast, T> { fn flatten( self, f: &mut Flattener, @@ -75,7 +75,7 @@ impl<'ast, T: Field> Flatten<'ast, T> for typed_absy::FieldElementExpression<'as } } -impl<'ast, T: Field> Flatten<'ast, T> for typed_absy::BooleanExpression<'ast, T> { +impl<'ast, T: Field> Flatten<'ast, T> for typed::BooleanExpression<'ast, T> { fn flatten( self, f: &mut Flattener, @@ -85,7 +85,7 @@ impl<'ast, T: Field> Flatten<'ast, T> for typed_absy::BooleanExpression<'ast, T> } } -impl<'ast, T: Field> Flatten<'ast, T> for typed_absy::UExpression<'ast, T> { +impl<'ast, T: Field> Flatten<'ast, T> for typed::UExpression<'ast, T> { fn flatten( self, f: &mut Flattener, @@ -95,7 +95,7 @@ impl<'ast, T: Field> Flatten<'ast, T> for typed_absy::UExpression<'ast, T> { } } -impl<'ast, T: Field> Flatten<'ast, T> for typed_absy::ArrayExpression<'ast, T> { +impl<'ast, T: Field> Flatten<'ast, T> for typed::ArrayExpression<'ast, T> { fn flatten( self, f: &mut Flattener, @@ -105,7 +105,7 @@ impl<'ast, T: Field> Flatten<'ast, T> for typed_absy::ArrayExpression<'ast, T> { } } -impl<'ast, T: Field> Flatten<'ast, T> for typed_absy::StructExpression<'ast, T> { +impl<'ast, T: Field> Flatten<'ast, T> for typed::StructExpression<'ast, T> { fn flatten( self, f: &mut Flattener, @@ -115,7 +115,7 @@ impl<'ast, T: Field> Flatten<'ast, T> for typed_absy::StructExpression<'ast, T> } } -impl<'ast, T: Field> Flatten<'ast, T> for typed_absy::TupleExpression<'ast, T> { +impl<'ast, T: Field> Flatten<'ast, T> for typed::TupleExpression<'ast, T> { fn flatten( self, f: &mut Flattener, @@ -126,84 +126,78 @@ impl<'ast, T: Field> Flatten<'ast, T> for typed_absy::TupleExpression<'ast, T> { } impl<'ast, T: Field> Flattener { - pub fn flatten(p: typed_absy::TypedProgram) -> zir::ZirProgram { + pub fn flatten(p: typed::TypedProgram) -> zir::ZirProgram { let mut f = Flattener::default(); f.fold_program(p) } - fn fold_program(&mut self, p: typed_absy::TypedProgram<'ast, T>) -> zir::ZirProgram<'ast, T> { + fn fold_program(&mut self, p: typed::TypedProgram<'ast, T>) -> zir::ZirProgram<'ast, T> { fold_program(self, p) } - fn fold_function( - &mut self, - f: typed_absy::TypedFunction<'ast, T>, - ) -> zir::ZirFunction<'ast, T> { + fn fold_function(&mut self, f: typed::TypedFunction<'ast, T>) -> zir::ZirFunction<'ast, T> { fold_function(self, f) } fn fold_declaration_parameter( &mut self, - p: typed_absy::DeclarationParameter<'ast, T>, + p: typed::DeclarationParameter<'ast, T>, ) -> Vec> { let private = p.private; - self.fold_variable(crate::typed_absy::variable::try_from_g_variable(p.id).unwrap()) + self.fold_variable(zokrates_ast::typed::variable::try_from_g_variable(p.id).unwrap()) .into_iter() .map(|v| zir::Parameter { id: v, private }) .collect() } - fn fold_name(&mut self, n: typed_absy::Identifier<'ast>) -> zir::SourceIdentifier<'ast> { + fn fold_name(&mut self, n: typed::Identifier<'ast>) -> zir::SourceIdentifier<'ast> { zir::SourceIdentifier::Basic(n) } - fn fold_variable(&mut self, v: typed_absy::Variable<'ast, T>) -> Vec> { + fn fold_variable(&mut self, v: typed::Variable<'ast, T>) -> Vec> { let ty = v.get_type(); let id = self.fold_name(v.id); - let ty = typed_absy::types::ConcreteType::try_from(ty).unwrap(); + let ty = typed::types::ConcreteType::try_from(ty).unwrap(); flatten_identifier_rec(id, &ty) } - fn fold_assignee( - &mut self, - a: typed_absy::TypedAssignee<'ast, T>, - ) -> Vec> { + fn fold_assignee(&mut self, a: typed::TypedAssignee<'ast, T>) -> Vec> { match a { - typed_absy::TypedAssignee::Identifier(v) => self.fold_variable(v), - typed_absy::TypedAssignee::Select(box a, box i) => { - use typed_absy::Typed; - let count = match typed_absy::ConcreteType::try_from(a.get_type()).unwrap() { - typed_absy::ConcreteType::Array(array_ty) => array_ty.ty.get_primitive_count(), + typed::TypedAssignee::Identifier(v) => self.fold_variable(v), + typed::TypedAssignee::Select(box a, box i) => { + use typed::Typed; + let count = match typed::ConcreteType::try_from(a.get_type()).unwrap() { + typed::ConcreteType::Array(array_ty) => array_ty.ty.get_primitive_count(), _ => unreachable!(), }; let a = self.fold_assignee(a); match i.as_inner() { - typed_absy::UExpressionInner::Value(index) => { + typed::UExpressionInner::Value(index) => { a[*index as usize * count..(*index as usize + 1) * count].to_vec() } i => unreachable!("index {:?} not allowed, should be a constant", i), } } - typed_absy::TypedAssignee::Member(box a, m) => { - use typed_absy::Typed; + typed::TypedAssignee::Member(box a, m) => { + use typed::Typed; - let (offset, size) = match typed_absy::ConcreteType::try_from(a.get_type()).unwrap() - { - typed_absy::ConcreteType::Struct(struct_type) => struct_type - .members - .iter() - .fold((0, None), |(offset, size), member| match size { - Some(_) => (offset, size), - None => match m == member.id { - true => (offset, Some(member.ty.get_primitive_count())), - false => (offset + member.ty.get_primitive_count(), None), - }, - }), - _ => unreachable!(), - }; + let (offset, size) = + match typed::ConcreteType::try_from(a.get_type()).unwrap() { + typed::ConcreteType::Struct(struct_type) => struct_type + .members + .iter() + .fold((0, None), |(offset, size), member| match size { + Some(_) => (offset, size), + None => match m == member.id { + true => (offset, Some(member.ty.get_primitive_count())), + false => (offset + member.ty.get_primitive_count(), None), + }, + }), + _ => unreachable!(), + }; let size = size.unwrap(); @@ -211,11 +205,11 @@ impl<'ast, T: Field> Flattener { a[offset..offset + size].to_vec() } - typed_absy::TypedAssignee::Element(box a, index) => { - use typed_absy::Typed; + typed::TypedAssignee::Element(box a, index) => { + use typed::Typed; - let tuple_ty = typed_absy::ConcreteTupleType::try_from( - typed_absy::ConcreteType::try_from(a.get_type()).unwrap(), + let tuple_ty = typed::ConcreteTupleType::try_from( + typed::ConcreteType::try_from(a.get_type()).unwrap(), ) .unwrap(); @@ -238,7 +232,7 @@ impl<'ast, T: Field> Flattener { fn fold_statement( &mut self, statements_buffer: &mut Vec>, - s: typed_absy::TypedStatement<'ast, T>, + s: typed::TypedStatement<'ast, T>, ) { fold_statement(self, statements_buffer, s) } @@ -246,13 +240,13 @@ impl<'ast, T: Field> Flattener { fn fold_expression_or_spread( &mut self, statements_buffer: &mut Vec>, - e: typed_absy::TypedExpressionOrSpread<'ast, T>, + e: typed::TypedExpressionOrSpread<'ast, T>, ) -> Vec> { match e { - typed_absy::TypedExpressionOrSpread::Expression(e) => { + typed::TypedExpressionOrSpread::Expression(e) => { self.fold_expression(statements_buffer, e) } - typed_absy::TypedExpressionOrSpread::Spread(s) => { + typed::TypedExpressionOrSpread::Spread(s) => { self.fold_array_expression(statements_buffer, s.array) } } @@ -261,35 +255,29 @@ impl<'ast, T: Field> Flattener { fn fold_expression( &mut self, statements_buffer: &mut Vec>, - e: typed_absy::TypedExpression<'ast, T>, + e: typed::TypedExpression<'ast, T>, ) -> Vec> { match e { - typed_absy::TypedExpression::FieldElement(e) => { + typed::TypedExpression::FieldElement(e) => { vec![self.fold_field_expression(statements_buffer, e).into()] } - typed_absy::TypedExpression::Boolean(e) => { + typed::TypedExpression::Boolean(e) => { vec![self.fold_boolean_expression(statements_buffer, e).into()] } - typed_absy::TypedExpression::Uint(e) => { + typed::TypedExpression::Uint(e) => { vec![self.fold_uint_expression(statements_buffer, e).into()] } - typed_absy::TypedExpression::Array(e) => { - self.fold_array_expression(statements_buffer, e) - } - typed_absy::TypedExpression::Struct(e) => { - self.fold_struct_expression(statements_buffer, e) - } - typed_absy::TypedExpression::Tuple(e) => { - self.fold_tuple_expression(statements_buffer, e) - } - typed_absy::TypedExpression::Int(_) => unreachable!(), + typed::TypedExpression::Array(e) => self.fold_array_expression(statements_buffer, e), + typed::TypedExpression::Struct(e) => self.fold_struct_expression(statements_buffer, e), + typed::TypedExpression::Tuple(e) => self.fold_tuple_expression(statements_buffer, e), + typed::TypedExpression::Int(_) => unreachable!(), } } fn fold_array_expression( &mut self, statements_buffer: &mut Vec>, - e: typed_absy::ArrayExpression<'ast, T>, + e: typed::ArrayExpression<'ast, T>, ) -> Vec> { fold_array_expression(self, statements_buffer, e) } @@ -297,7 +285,7 @@ impl<'ast, T: Field> Flattener { fn fold_struct_expression( &mut self, statements_buffer: &mut Vec>, - e: typed_absy::StructExpression<'ast, T>, + e: typed::StructExpression<'ast, T>, ) -> Vec> { fold_struct_expression(self, statements_buffer, e) } @@ -305,7 +293,7 @@ impl<'ast, T: Field> Flattener { fn fold_tuple_expression( &mut self, statements_buffer: &mut Vec>, - e: typed_absy::TupleExpression<'ast, T>, + e: typed::TupleExpression<'ast, T>, ) -> Vec> { fold_tuple_expression(self, statements_buffer, e) } @@ -313,10 +301,10 @@ impl<'ast, T: Field> Flattener { fn fold_expression_list( &mut self, statements_buffer: &mut Vec>, - es: typed_absy::TypedExpressionList<'ast, T>, + es: typed::TypedExpressionList<'ast, T>, ) -> zir::ZirExpressionList<'ast, T> { match es.into_inner() { - typed_absy::TypedExpressionListInner::EmbedCall(embed, generics, arguments) => { + typed::TypedExpressionListInner::EmbedCall(embed, generics, arguments) => { zir::ZirExpressionList::EmbedCall( embed, generics, @@ -333,7 +321,7 @@ impl<'ast, T: Field> Flattener { fn fold_conditional_expression>( &mut self, statements_buffer: &mut Vec>, - c: typed_absy::ConditionalExpression<'ast, T, E>, + c: typed::ConditionalExpression<'ast, T, E>, ) -> Vec> { fold_conditional_expression(self, statements_buffer, c) } @@ -341,7 +329,7 @@ impl<'ast, T: Field> Flattener { fn fold_member_expression( &mut self, statements_buffer: &mut Vec>, - m: typed_absy::MemberExpression<'ast, T, E>, + m: typed::MemberExpression<'ast, T, E>, ) -> Vec> { fold_member_expression(self, statements_buffer, m) } @@ -349,7 +337,7 @@ impl<'ast, T: Field> Flattener { fn fold_element_expression( &mut self, statements_buffer: &mut Vec>, - e: typed_absy::ElementExpression<'ast, T, E>, + e: typed::ElementExpression<'ast, T, E>, ) -> Vec> { fold_element_expression(self, statements_buffer, e) } @@ -357,7 +345,7 @@ impl<'ast, T: Field> Flattener { fn fold_select_expression( &mut self, statements_buffer: &mut Vec>, - select: typed_absy::SelectExpression<'ast, T, E>, + select: typed::SelectExpression<'ast, T, E>, ) -> Vec> { fold_select_expression(self, statements_buffer, select) } @@ -365,7 +353,7 @@ impl<'ast, T: Field> Flattener { fn fold_eq_expression>( &mut self, statements_buffer: &mut Vec>, - eq: typed_absy::EqExpression, + eq: typed::EqExpression, ) -> zir::BooleanExpression<'ast, T> { fold_eq_expression(self, statements_buffer, eq) } @@ -373,21 +361,21 @@ impl<'ast, T: Field> Flattener { fn fold_field_expression( &mut self, statements_buffer: &mut Vec>, - e: typed_absy::FieldElementExpression<'ast, T>, + e: typed::FieldElementExpression<'ast, T>, ) -> zir::FieldElementExpression<'ast, T> { fold_field_expression(self, statements_buffer, e) } fn fold_boolean_expression( &mut self, statements_buffer: &mut Vec>, - e: typed_absy::BooleanExpression<'ast, T>, + e: typed::BooleanExpression<'ast, T>, ) -> zir::BooleanExpression<'ast, T> { fold_boolean_expression(self, statements_buffer, e) } fn fold_uint_expression( &mut self, statements_buffer: &mut Vec>, - e: typed_absy::UExpression<'ast, T>, + e: typed::UExpression<'ast, T>, ) -> zir::UExpression<'ast, T> { fold_uint_expression(self, statements_buffer, e) } @@ -396,7 +384,7 @@ impl<'ast, T: Field> Flattener { &mut self, statements_buffer: &mut Vec>, bitwidth: UBitwidth, - e: typed_absy::UExpressionInner<'ast, T>, + e: typed::UExpressionInner<'ast, T>, ) -> zir::UExpressionInner<'ast, T> { fold_uint_expression_inner(self, statements_buffer, bitwidth, e) } @@ -404,9 +392,9 @@ impl<'ast, T: Field> Flattener { fn fold_array_expression_inner( &mut self, statements_buffer: &mut Vec>, - ty: &typed_absy::types::ConcreteType, + ty: &typed::types::ConcreteType, size: u32, - e: typed_absy::ArrayExpressionInner<'ast, T>, + e: typed::ArrayExpressionInner<'ast, T>, ) -> Vec> { fold_array_expression_inner(self, statements_buffer, ty, size, e) } @@ -414,8 +402,8 @@ impl<'ast, T: Field> Flattener { fn fold_struct_expression_inner( &mut self, statements_buffer: &mut Vec>, - ty: &typed_absy::types::ConcreteStructType, - e: typed_absy::StructExpressionInner<'ast, T>, + ty: &typed::types::ConcreteStructType, + e: typed::StructExpressionInner<'ast, T>, ) -> Vec> { fold_struct_expression_inner(self, statements_buffer, ty, e) } @@ -423,8 +411,8 @@ impl<'ast, T: Field> Flattener { fn fold_tuple_expression_inner( &mut self, statements_buffer: &mut Vec>, - ty: &typed_absy::types::ConcreteTupleType, - e: typed_absy::TupleExpressionInner<'ast, T>, + ty: &typed::types::ConcreteTupleType, + e: typed::TupleExpressionInner<'ast, T>, ) -> Vec> { fold_tuple_expression_inner(self, statements_buffer, ty, e) } @@ -433,16 +421,16 @@ impl<'ast, T: Field> Flattener { fn fold_statement<'ast, T: Field>( f: &mut Flattener, statements_buffer: &mut Vec>, - s: typed_absy::TypedStatement<'ast, T>, + s: typed::TypedStatement<'ast, T>, ) { let res = match s { - typed_absy::TypedStatement::Return(expressions) => vec![zir::ZirStatement::Return( + typed::TypedStatement::Return(expressions) => vec![zir::ZirStatement::Return( expressions .into_iter() .flat_map(|e| f.fold_expression(statements_buffer, e)) .collect(), )], - typed_absy::TypedStatement::Definition(a, e) => { + typed::TypedStatement::Definition(a, e) => { let a = f.fold_assignee(a); let e = f.fold_expression(statements_buffer, e); assert_eq!(a.len(), e.len()); @@ -451,21 +439,21 @@ fn fold_statement<'ast, T: Field>( .map(|(a, e)| zir::ZirStatement::Definition(a, e)) .collect() } - typed_absy::TypedStatement::Declaration(..) => { + typed::TypedStatement::Declaration(..) => { unreachable!() } - typed_absy::TypedStatement::Assertion(e, error) => { + typed::TypedStatement::Assertion(e, error) => { let e = f.fold_boolean_expression(statements_buffer, e); let error = match error { - typed_absy::RuntimeError::SourceAssertion(metadata) => { + typed::RuntimeError::SourceAssertion(metadata) => { zir::RuntimeError::SourceAssertion(metadata.to_string()) } - typed_absy::RuntimeError::SelectRangeCheck => zir::RuntimeError::SelectRangeCheck, + typed::RuntimeError::SelectRangeCheck => zir::RuntimeError::SelectRangeCheck, }; vec![zir::ZirStatement::Assertion(e, error)] } - typed_absy::TypedStatement::For(..) => unreachable!(), - typed_absy::TypedStatement::MultipleDefinition(variables, elist) => { + typed::TypedStatement::For(..) => unreachable!(), + typed::TypedStatement::MultipleDefinition(variables, elist) => { vec![zir::ZirStatement::MultipleDefinition( variables .into_iter() @@ -474,8 +462,8 @@ fn fold_statement<'ast, T: Field>( f.fold_expression_list(statements_buffer, elist), )] } - typed_absy::TypedStatement::PushCallLog(..) => vec![], - typed_absy::TypedStatement::PopCallLog => vec![], + typed::TypedStatement::PushCallLog(..) => vec![], + typed::TypedStatement::PopCallLog => vec![], }; statements_buffer.extend(res); @@ -484,22 +472,22 @@ fn fold_statement<'ast, T: Field>( fn fold_array_expression_inner<'ast, T: Field>( f: &mut Flattener, statements_buffer: &mut Vec>, - ty: &typed_absy::types::ConcreteType, + ty: &typed::types::ConcreteType, size: u32, - array: typed_absy::ArrayExpressionInner<'ast, T>, + array: typed::ArrayExpressionInner<'ast, T>, ) -> Vec> { match array { - typed_absy::ArrayExpressionInner::Block(block) => { + typed::ArrayExpressionInner::Block(block) => { block .statements .into_iter() .for_each(|s| f.fold_statement(statements_buffer, s)); f.fold_array_expression(statements_buffer, *block.value) } - typed_absy::ArrayExpressionInner::Identifier(id) => { + typed::ArrayExpressionInner::Identifier(id) => { let variables = flatten_identifier_rec( f.fold_name(id), - &typed_absy::types::ConcreteType::array((ty.clone(), size)), + &typed::types::ConcreteType::array((ty.clone(), size)), ); variables .into_iter() @@ -512,7 +500,7 @@ fn fold_array_expression_inner<'ast, T: Field>( }) .collect() } - typed_absy::ArrayExpressionInner::Value(exprs) => { + typed::ArrayExpressionInner::Value(exprs) => { let exprs: Vec<_> = exprs .into_iter() .flat_map(|e| f.fold_expression_or_spread(statements_buffer, e)) @@ -522,17 +510,15 @@ fn fold_array_expression_inner<'ast, T: Field>( exprs } - typed_absy::ArrayExpressionInner::FunctionCall(..) => unreachable!(), - typed_absy::ArrayExpressionInner::Conditional(c) => { + typed::ArrayExpressionInner::FunctionCall(..) => unreachable!(), + typed::ArrayExpressionInner::Conditional(c) => { f.fold_conditional_expression(statements_buffer, c) } - typed_absy::ArrayExpressionInner::Member(m) => { - f.fold_member_expression(statements_buffer, m) - } - typed_absy::ArrayExpressionInner::Select(select) => { + typed::ArrayExpressionInner::Member(m) => f.fold_member_expression(statements_buffer, m), + typed::ArrayExpressionInner::Select(select) => { f.fold_select_expression(statements_buffer, select) } - typed_absy::ArrayExpressionInner::Slice(box array, box from, box to) => { + typed::ArrayExpressionInner::Slice(box array, box from, box to) => { let array = f.fold_array_expression(statements_buffer, array); let from = f.fold_uint_expression(statements_buffer, from); let to = f.fold_uint_expression(statements_buffer, to); @@ -549,7 +535,7 @@ fn fold_array_expression_inner<'ast, T: Field>( _ => unreachable!(), } } - typed_absy::ArrayExpressionInner::Repeat(box e, box count) => { + typed::ArrayExpressionInner::Repeat(box e, box count) => { let e = f.fold_expression(statements_buffer, e); let count = f.fold_uint_expression(statements_buffer, count); @@ -560,7 +546,7 @@ fn fold_array_expression_inner<'ast, T: Field>( _ => unreachable!(), } } - typed_absy::ArrayExpressionInner::Element(element) => { + typed::ArrayExpressionInner::Element(element) => { f.fold_element_expression(statements_buffer, element) } } @@ -569,21 +555,21 @@ fn fold_array_expression_inner<'ast, T: Field>( fn fold_struct_expression_inner<'ast, T: Field>( f: &mut Flattener, statements_buffer: &mut Vec>, - ty: &typed_absy::types::ConcreteStructType, - struc: typed_absy::StructExpressionInner<'ast, T>, + ty: &typed::types::ConcreteStructType, + struc: typed::StructExpressionInner<'ast, T>, ) -> Vec> { match struc { - typed_absy::StructExpressionInner::Block(block) => { + typed::StructExpressionInner::Block(block) => { block .statements .into_iter() .for_each(|s| f.fold_statement(statements_buffer, s)); f.fold_struct_expression(statements_buffer, *block.value) } - typed_absy::StructExpressionInner::Identifier(id) => { + typed::StructExpressionInner::Identifier(id) => { let variables = flatten_identifier_rec( f.fold_name(id), - &typed_absy::types::ConcreteType::struc(ty.clone()), + &typed::types::ConcreteType::struc(ty.clone()), ); variables .into_iter() @@ -596,21 +582,19 @@ fn fold_struct_expression_inner<'ast, T: Field>( }) .collect() } - typed_absy::StructExpressionInner::Value(exprs) => exprs + typed::StructExpressionInner::Value(exprs) => exprs .into_iter() .flat_map(|e| f.fold_expression(statements_buffer, e)) .collect(), - typed_absy::StructExpressionInner::FunctionCall(..) => unreachable!(), - typed_absy::StructExpressionInner::Conditional(c) => { + typed::StructExpressionInner::FunctionCall(..) => unreachable!(), + typed::StructExpressionInner::Conditional(c) => { f.fold_conditional_expression(statements_buffer, c) } - typed_absy::StructExpressionInner::Member(m) => { - f.fold_member_expression(statements_buffer, m) - } - typed_absy::StructExpressionInner::Select(select) => { + typed::StructExpressionInner::Member(m) => f.fold_member_expression(statements_buffer, m), + typed::StructExpressionInner::Select(select) => { f.fold_select_expression(statements_buffer, select) } - typed_absy::StructExpressionInner::Element(element) => { + typed::StructExpressionInner::Element(element) => { f.fold_element_expression(statements_buffer, element) } } @@ -619,21 +603,21 @@ fn fold_struct_expression_inner<'ast, T: Field>( fn fold_tuple_expression_inner<'ast, T: Field>( f: &mut Flattener, statements_buffer: &mut Vec>, - ty: &typed_absy::types::ConcreteTupleType, - tuple: typed_absy::TupleExpressionInner<'ast, T>, + ty: &typed::types::ConcreteTupleType, + tuple: typed::TupleExpressionInner<'ast, T>, ) -> Vec> { match tuple { - typed_absy::TupleExpressionInner::Block(block) => { + typed::TupleExpressionInner::Block(block) => { block .statements .into_iter() .for_each(|s| f.fold_statement(statements_buffer, s)); f.fold_tuple_expression(statements_buffer, *block.value) } - typed_absy::TupleExpressionInner::Identifier(id) => { + typed::TupleExpressionInner::Identifier(id) => { let variables = flatten_identifier_rec( f.fold_name(id), - &typed_absy::types::ConcreteType::tuple(ty.clone()), + &typed::types::ConcreteType::tuple(ty.clone()), ); variables .into_iter() @@ -646,21 +630,19 @@ fn fold_tuple_expression_inner<'ast, T: Field>( }) .collect() } - typed_absy::TupleExpressionInner::Value(exprs) => exprs + typed::TupleExpressionInner::Value(exprs) => exprs .into_iter() .flat_map(|e| f.fold_expression(statements_buffer, e)) .collect(), - typed_absy::TupleExpressionInner::FunctionCall(..) => unreachable!(), - typed_absy::TupleExpressionInner::Conditional(c) => { + typed::TupleExpressionInner::FunctionCall(..) => unreachable!(), + typed::TupleExpressionInner::Conditional(c) => { f.fold_conditional_expression(statements_buffer, c) } - typed_absy::TupleExpressionInner::Member(m) => { - f.fold_member_expression(statements_buffer, m) - } - typed_absy::TupleExpressionInner::Select(select) => { + typed::TupleExpressionInner::Member(m) => f.fold_member_expression(statements_buffer, m), + typed::TupleExpressionInner::Select(select) => { f.fold_select_expression(statements_buffer, select) } - typed_absy::TupleExpressionInner::Element(element) => { + typed::TupleExpressionInner::Element(element) => { f.fold_element_expression(statements_buffer, element) } } @@ -669,14 +651,14 @@ fn fold_tuple_expression_inner<'ast, T: Field>( fn fold_member_expression<'ast, T: Field, E>( f: &mut Flattener, statements_buffer: &mut Vec>, - m: typed_absy::MemberExpression<'ast, T, E>, + m: typed::MemberExpression<'ast, T, E>, ) -> Vec> { let s = *m.struc; let id = m.id; let members = s.ty(); - let size = typed_absy::types::ConcreteType::try_from( + let size = typed::types::ConcreteType::try_from( *members .iter() .find(|member| member.id == id) @@ -691,7 +673,7 @@ fn fold_member_expression<'ast, T: Field, E>( .iter() .take_while(|member| member.id != id) .map(|member| { - typed_absy::types::ConcreteType::try_from(*member.ty.clone()) + typed::types::ConcreteType::try_from(*member.ty.clone()) .unwrap() .get_primitive_count() }) @@ -705,14 +687,14 @@ fn fold_member_expression<'ast, T: Field, E>( fn fold_element_expression<'ast, T: Field, E>( f: &mut Flattener, statements_buffer: &mut Vec>, - e: typed_absy::ElementExpression<'ast, T, E>, + e: typed::ElementExpression<'ast, T, E>, ) -> Vec> { let t = *e.tuple; let id = e.index; let tuple_ty = t.ty(); - let size = typed_absy::types::ConcreteType::try_from( + let size = typed::types::ConcreteType::try_from( tuple_ty .elements .iter() @@ -730,7 +712,7 @@ fn fold_element_expression<'ast, T: Field, E>( .iter() .take(id as usize) .map(|ty| { - typed_absy::types::ConcreteType::try_from(ty.clone()) + typed::types::ConcreteType::try_from(ty.clone()) .unwrap() .get_primitive_count() }) @@ -744,9 +726,9 @@ fn fold_element_expression<'ast, T: Field, E>( fn fold_select_expression<'ast, T: Field, E>( f: &mut Flattener, statements_buffer: &mut Vec>, - select: typed_absy::SelectExpression<'ast, T, E>, + select: typed::SelectExpression<'ast, T, E>, ) -> Vec> { - let size = typed_absy::types::ConcreteType::try_from(*select.array.ty().clone().ty) + let size = typed::types::ConcreteType::try_from(*select.array.ty().clone().ty) .unwrap() .get_primitive_count(); @@ -774,7 +756,7 @@ fn fold_select_expression<'ast, T: Field, E>( }) .into_iter() .map(|a| { - use crate::zir::Typed; + use zokrates_ast::zir::Typed; let ty = a[0].get_type(); @@ -819,7 +801,7 @@ fn fold_select_expression<'ast, T: Field, E>( fn fold_conditional_expression<'ast, T: Field, E: Flatten<'ast, T>>( f: &mut Flattener, statements_buffer: &mut Vec>, - c: typed_absy::ConditionalExpression<'ast, T, E>, + c: typed::ConditionalExpression<'ast, T, E>, ) -> Vec> { let mut consequence_statements = vec![]; let mut alternative_statements = vec![]; @@ -838,7 +820,7 @@ fn fold_conditional_expression<'ast, T: Field, E: Flatten<'ast, T>>( )); } - use crate::zir::IfElse; + use zokrates_ast::zir::IfElse; consequence .into_iter() @@ -861,47 +843,42 @@ fn fold_conditional_expression<'ast, T: Field, E: Flatten<'ast, T>>( fn fold_field_expression<'ast, T: Field>( f: &mut Flattener, statements_buffer: &mut Vec>, - e: typed_absy::FieldElementExpression<'ast, T>, + e: typed::FieldElementExpression<'ast, T>, ) -> zir::FieldElementExpression<'ast, T> { match e { - typed_absy::FieldElementExpression::Number(n) => zir::FieldElementExpression::Number(n), - typed_absy::FieldElementExpression::Identifier(id) => { - zir::FieldElementExpression::Identifier( - flatten_identifier_rec( - f.fold_name(id), - &typed_absy::types::ConcreteType::FieldElement, - ) + typed::FieldElementExpression::Number(n) => zir::FieldElementExpression::Number(n), + typed::FieldElementExpression::Identifier(id) => zir::FieldElementExpression::Identifier( + flatten_identifier_rec(f.fold_name(id), &typed::types::ConcreteType::FieldElement) .pop() .unwrap() .id, - ) - } - typed_absy::FieldElementExpression::Add(box e1, box e2) => { + ), + typed::FieldElementExpression::Add(box e1, box e2) => { let e1 = f.fold_field_expression(statements_buffer, e1); let e2 = f.fold_field_expression(statements_buffer, e2); zir::FieldElementExpression::Add(box e1, box e2) } - typed_absy::FieldElementExpression::Sub(box e1, box e2) => { + typed::FieldElementExpression::Sub(box e1, box e2) => { let e1 = f.fold_field_expression(statements_buffer, e1); let e2 = f.fold_field_expression(statements_buffer, e2); zir::FieldElementExpression::Sub(box e1, box e2) } - typed_absy::FieldElementExpression::Mult(box e1, box e2) => { + typed::FieldElementExpression::Mult(box e1, box e2) => { let e1 = f.fold_field_expression(statements_buffer, e1); let e2 = f.fold_field_expression(statements_buffer, e2); zir::FieldElementExpression::Mult(box e1, box e2) } - typed_absy::FieldElementExpression::Div(box e1, box e2) => { + typed::FieldElementExpression::Div(box e1, box e2) => { let e1 = f.fold_field_expression(statements_buffer, e1); let e2 = f.fold_field_expression(statements_buffer, e2); zir::FieldElementExpression::Div(box e1, box e2) } - typed_absy::FieldElementExpression::Pow(box e1, box e2) => { + typed::FieldElementExpression::Pow(box e1, box e2) => { let e1 = f.fold_field_expression(statements_buffer, e1); let e2 = f.fold_uint_expression(statements_buffer, e2); zir::FieldElementExpression::Pow(box e1, box e2) } - typed_absy::FieldElementExpression::Neg(box e) => { + typed::FieldElementExpression::Neg(box e) => { let e = f.fold_field_expression(statements_buffer, e); zir::FieldElementExpression::Sub( @@ -909,35 +886,33 @@ fn fold_field_expression<'ast, T: Field>( box e, ) } - typed_absy::FieldElementExpression::Pos(box e) => { - f.fold_field_expression(statements_buffer, e) - } - typed_absy::FieldElementExpression::Conditional(c) => f + typed::FieldElementExpression::Pos(box e) => f.fold_field_expression(statements_buffer, e), + typed::FieldElementExpression::Conditional(c) => f .fold_conditional_expression(statements_buffer, c) .pop() .unwrap() .try_into() .unwrap(), - typed_absy::FieldElementExpression::FunctionCall(..) => unreachable!(""), - typed_absy::FieldElementExpression::Select(select) => f + typed::FieldElementExpression::FunctionCall(..) => unreachable!(""), + typed::FieldElementExpression::Select(select) => f .fold_select_expression(statements_buffer, select) .pop() .unwrap() .try_into() .unwrap(), - typed_absy::FieldElementExpression::Member(m) => f + typed::FieldElementExpression::Member(m) => f .fold_member_expression(statements_buffer, m) .pop() .unwrap() .try_into() .unwrap(), - typed_absy::FieldElementExpression::Element(element) => f + typed::FieldElementExpression::Element(element) => f .fold_element_expression(statements_buffer, element) .pop() .unwrap() .try_into() .unwrap(), - typed_absy::FieldElementExpression::Block(block) => { + typed::FieldElementExpression::Block(block) => { block .statements .into_iter() @@ -981,7 +956,7 @@ fn conjunction_tree<'ast, T: Field>( fn fold_eq_expression<'ast, T: Field, E: Flatten<'ast, T>>( f: &mut Flattener, statements_buffer: &mut Vec>, - e: typed_absy::EqExpression, + e: typed::EqExpression, ) -> zir::BooleanExpression<'ast, T> { let left = e.left.flatten(f, statements_buffer); let right = e.right.flatten(f, statements_buffer); @@ -991,103 +966,103 @@ fn fold_eq_expression<'ast, T: Field, E: Flatten<'ast, T>>( fn fold_boolean_expression<'ast, T: Field>( f: &mut Flattener, statements_buffer: &mut Vec>, - e: typed_absy::BooleanExpression<'ast, T>, + e: typed::BooleanExpression<'ast, T>, ) -> zir::BooleanExpression<'ast, T> { match e { - typed_absy::BooleanExpression::Block(block) => { + typed::BooleanExpression::Block(block) => { block .statements .into_iter() .for_each(|s| f.fold_statement(statements_buffer, s)); f.fold_boolean_expression(statements_buffer, *block.value) } - typed_absy::BooleanExpression::Value(v) => zir::BooleanExpression::Value(v), - typed_absy::BooleanExpression::Identifier(id) => zir::BooleanExpression::Identifier( - flatten_identifier_rec(f.fold_name(id), &typed_absy::types::ConcreteType::Boolean) + typed::BooleanExpression::Value(v) => zir::BooleanExpression::Value(v), + typed::BooleanExpression::Identifier(id) => zir::BooleanExpression::Identifier( + flatten_identifier_rec(f.fold_name(id), &typed::types::ConcreteType::Boolean) .pop() .unwrap() .id, ), - typed_absy::BooleanExpression::FieldEq(e) => f.fold_eq_expression(statements_buffer, e), - typed_absy::BooleanExpression::BoolEq(e) => f.fold_eq_expression(statements_buffer, e), - typed_absy::BooleanExpression::ArrayEq(e) => f.fold_eq_expression(statements_buffer, e), - typed_absy::BooleanExpression::StructEq(e) => f.fold_eq_expression(statements_buffer, e), - typed_absy::BooleanExpression::TupleEq(e) => f.fold_eq_expression(statements_buffer, e), - typed_absy::BooleanExpression::UintEq(e) => f.fold_eq_expression(statements_buffer, e), - typed_absy::BooleanExpression::FieldLt(box e1, box e2) => { + typed::BooleanExpression::FieldEq(e) => f.fold_eq_expression(statements_buffer, e), + typed::BooleanExpression::BoolEq(e) => f.fold_eq_expression(statements_buffer, e), + typed::BooleanExpression::ArrayEq(e) => f.fold_eq_expression(statements_buffer, e), + typed::BooleanExpression::StructEq(e) => f.fold_eq_expression(statements_buffer, e), + typed::BooleanExpression::TupleEq(e) => f.fold_eq_expression(statements_buffer, e), + typed::BooleanExpression::UintEq(e) => f.fold_eq_expression(statements_buffer, e), + typed::BooleanExpression::FieldLt(box e1, box e2) => { let e1 = f.fold_field_expression(statements_buffer, e1); let e2 = f.fold_field_expression(statements_buffer, e2); zir::BooleanExpression::FieldLt(box e1, box e2) } - typed_absy::BooleanExpression::FieldLe(box e1, box e2) => { + typed::BooleanExpression::FieldLe(box e1, box e2) => { let e1 = f.fold_field_expression(statements_buffer, e1); let e2 = f.fold_field_expression(statements_buffer, e2); zir::BooleanExpression::FieldLe(box e1, box e2) } - typed_absy::BooleanExpression::FieldGt(box e1, box e2) => { + typed::BooleanExpression::FieldGt(box e1, box e2) => { let e1 = f.fold_field_expression(statements_buffer, e1); let e2 = f.fold_field_expression(statements_buffer, e2); zir::BooleanExpression::FieldGt(box e1, box e2) } - typed_absy::BooleanExpression::FieldGe(box e1, box e2) => { + typed::BooleanExpression::FieldGe(box e1, box e2) => { let e1 = f.fold_field_expression(statements_buffer, e1); let e2 = f.fold_field_expression(statements_buffer, e2); zir::BooleanExpression::FieldGe(box e1, box e2) } - typed_absy::BooleanExpression::UintLt(box e1, box e2) => { + typed::BooleanExpression::UintLt(box e1, box e2) => { let e1 = f.fold_uint_expression(statements_buffer, e1); let e2 = f.fold_uint_expression(statements_buffer, e2); zir::BooleanExpression::UintLt(box e1, box e2) } - typed_absy::BooleanExpression::UintLe(box e1, box e2) => { + typed::BooleanExpression::UintLe(box e1, box e2) => { let e1 = f.fold_uint_expression(statements_buffer, e1); let e2 = f.fold_uint_expression(statements_buffer, e2); zir::BooleanExpression::UintLe(box e1, box e2) } - typed_absy::BooleanExpression::UintGt(box e1, box e2) => { + typed::BooleanExpression::UintGt(box e1, box e2) => { let e1 = f.fold_uint_expression(statements_buffer, e1); let e2 = f.fold_uint_expression(statements_buffer, e2); zir::BooleanExpression::UintGt(box e1, box e2) } - typed_absy::BooleanExpression::UintGe(box e1, box e2) => { + typed::BooleanExpression::UintGe(box e1, box e2) => { let e1 = f.fold_uint_expression(statements_buffer, e1); let e2 = f.fold_uint_expression(statements_buffer, e2); zir::BooleanExpression::UintGe(box e1, box e2) } - typed_absy::BooleanExpression::Or(box e1, box e2) => { + typed::BooleanExpression::Or(box e1, box e2) => { let e1 = f.fold_boolean_expression(statements_buffer, e1); let e2 = f.fold_boolean_expression(statements_buffer, e2); zir::BooleanExpression::Or(box e1, box e2) } - typed_absy::BooleanExpression::And(box e1, box e2) => { + typed::BooleanExpression::And(box e1, box e2) => { let e1 = f.fold_boolean_expression(statements_buffer, e1); let e2 = f.fold_boolean_expression(statements_buffer, e2); zir::BooleanExpression::And(box e1, box e2) } - typed_absy::BooleanExpression::Not(box e) => { + typed::BooleanExpression::Not(box e) => { let e = f.fold_boolean_expression(statements_buffer, e); zir::BooleanExpression::Not(box e) } - typed_absy::BooleanExpression::Conditional(c) => f + typed::BooleanExpression::Conditional(c) => f .fold_conditional_expression(statements_buffer, c) .pop() .unwrap() .try_into() .unwrap(), - typed_absy::BooleanExpression::FunctionCall(..) => unreachable!(), - typed_absy::BooleanExpression::Select(select) => f + typed::BooleanExpression::FunctionCall(..) => unreachable!(), + typed::BooleanExpression::Select(select) => f .fold_select_expression(statements_buffer, select) .pop() .unwrap() .try_into() .unwrap(), - typed_absy::BooleanExpression::Member(m) => f + typed::BooleanExpression::Member(m) => f .fold_member_expression(statements_buffer, m) .pop() .unwrap() .try_into() .unwrap(), - typed_absy::BooleanExpression::Element(m) => f + typed::BooleanExpression::Element(m) => f .fold_element_expression(statements_buffer, m) .pop() .unwrap() @@ -1099,7 +1074,7 @@ fn fold_boolean_expression<'ast, T: Field>( fn fold_uint_expression<'ast, T: Field>( f: &mut Flattener, statements_buffer: &mut Vec>, - e: typed_absy::UExpression<'ast, T>, + e: typed::UExpression<'ast, T>, ) -> zir::UExpression<'ast, T> { f.fold_uint_expression_inner(statements_buffer, e.bitwidth, e.inner) .annotate(e.bitwidth.to_usize()) @@ -1109,10 +1084,10 @@ fn fold_uint_expression_inner<'ast, T: Field>( f: &mut Flattener, statements_buffer: &mut Vec>, bitwidth: UBitwidth, - e: typed_absy::UExpressionInner<'ast, T>, + e: typed::UExpressionInner<'ast, T>, ) -> zir::UExpressionInner<'ast, T> { match e { - typed_absy::UExpressionInner::Block(block) => { + typed::UExpressionInner::Block(block) => { block .statements .into_iter() @@ -1120,130 +1095,127 @@ fn fold_uint_expression_inner<'ast, T: Field>( f.fold_uint_expression(statements_buffer, *block.value) .into_inner() } - typed_absy::UExpressionInner::Value(v) => zir::UExpressionInner::Value(v), - typed_absy::UExpressionInner::Identifier(id) => zir::UExpressionInner::Identifier( - flatten_identifier_rec( - f.fold_name(id), - &typed_absy::types::ConcreteType::Uint(bitwidth), - ) - .pop() - .unwrap() - .id, + typed::UExpressionInner::Value(v) => zir::UExpressionInner::Value(v), + typed::UExpressionInner::Identifier(id) => zir::UExpressionInner::Identifier( + flatten_identifier_rec(f.fold_name(id), &typed::types::ConcreteType::Uint(bitwidth)) + .pop() + .unwrap() + .id, ), - typed_absy::UExpressionInner::Add(box left, box right) => { + typed::UExpressionInner::Add(box left, box right) => { let left = f.fold_uint_expression(statements_buffer, left); let right = f.fold_uint_expression(statements_buffer, right); zir::UExpressionInner::Add(box left, box right) } - typed_absy::UExpressionInner::Sub(box left, box right) => { + typed::UExpressionInner::Sub(box left, box right) => { let left = f.fold_uint_expression(statements_buffer, left); let right = f.fold_uint_expression(statements_buffer, right); zir::UExpressionInner::Sub(box left, box right) } - typed_absy::UExpressionInner::FloorSub(..) => unreachable!(), - typed_absy::UExpressionInner::Mult(box left, box right) => { + typed::UExpressionInner::FloorSub(..) => unreachable!(), + typed::UExpressionInner::Mult(box left, box right) => { let left = f.fold_uint_expression(statements_buffer, left); let right = f.fold_uint_expression(statements_buffer, right); zir::UExpressionInner::Mult(box left, box right) } - typed_absy::UExpressionInner::Div(box left, box right) => { + typed::UExpressionInner::Div(box left, box right) => { let left = f.fold_uint_expression(statements_buffer, left); let right = f.fold_uint_expression(statements_buffer, right); zir::UExpressionInner::Div(box left, box right) } - typed_absy::UExpressionInner::Rem(box left, box right) => { + typed::UExpressionInner::Rem(box left, box right) => { let left = f.fold_uint_expression(statements_buffer, left); let right = f.fold_uint_expression(statements_buffer, right); zir::UExpressionInner::Rem(box left, box right) } - typed_absy::UExpressionInner::Xor(box left, box right) => { + typed::UExpressionInner::Xor(box left, box right) => { let left = f.fold_uint_expression(statements_buffer, left); let right = f.fold_uint_expression(statements_buffer, right); zir::UExpressionInner::Xor(box left, box right) } - typed_absy::UExpressionInner::And(box left, box right) => { + typed::UExpressionInner::And(box left, box right) => { let left = f.fold_uint_expression(statements_buffer, left); let right = f.fold_uint_expression(statements_buffer, right); zir::UExpressionInner::And(box left, box right) } - typed_absy::UExpressionInner::Or(box left, box right) => { + typed::UExpressionInner::Or(box left, box right) => { let left = f.fold_uint_expression(statements_buffer, left); let right = f.fold_uint_expression(statements_buffer, right); zir::UExpressionInner::Or(box left, box right) } - typed_absy::UExpressionInner::LeftShift(box e, box by) => { + typed::UExpressionInner::LeftShift(box e, box by) => { let e = f.fold_uint_expression(statements_buffer, e); let by = match by.as_inner() { - typed_absy::UExpressionInner::Value(by) => by, + typed::UExpressionInner::Value(by) => by, _ => unreachable!("static analysis should have made sure that this is constant"), }; zir::UExpressionInner::LeftShift(box e, *by as u32) } - typed_absy::UExpressionInner::RightShift(box e, box by) => { + typed::UExpressionInner::RightShift(box e, box by) => { let e = f.fold_uint_expression(statements_buffer, e); let by = match by.as_inner() { - typed_absy::UExpressionInner::Value(by) => by, + typed::UExpressionInner::Value(by) => by, _ => unreachable!("static analysis should have made sure that this is constant"), }; zir::UExpressionInner::RightShift(box e, *by as u32) } - typed_absy::UExpressionInner::Not(box e) => { + typed::UExpressionInner::Not(box e) => { let e = f.fold_uint_expression(statements_buffer, e); zir::UExpressionInner::Not(box e) } - typed_absy::UExpressionInner::Neg(box e) => { + typed::UExpressionInner::Neg(box e) => { let bitwidth = e.bitwidth(); f.fold_uint_expression( statements_buffer, - typed_absy::UExpressionInner::Value(0).annotate(bitwidth) - e, + typed::UExpressionInner::Value(0).annotate(bitwidth) - e, ) .into_inner() } - typed_absy::UExpressionInner::Pos(box e) => { + typed::UExpressionInner::Pos(box e) => { let e = f.fold_uint_expression(statements_buffer, e); e.into_inner() } - typed_absy::UExpressionInner::FunctionCall(..) => { + typed::UExpressionInner::FunctionCall(..) => { unreachable!("function calls should have been removed") } - typed_absy::UExpressionInner::Select(select) => zir::UExpression::try_from( + typed::UExpressionInner::Select(select) => zir::UExpression::try_from( f.fold_select_expression(statements_buffer, select) .pop() .unwrap(), ) .unwrap() .into_inner(), - typed_absy::UExpressionInner::Member(m) => zir::UExpression::try_from( + typed::UExpressionInner::Member(m) => zir::UExpression::try_from( f.fold_member_expression(statements_buffer, m) .pop() .unwrap(), ) .unwrap() .into_inner(), - typed_absy::UExpressionInner::Element(m) => zir::UExpression::try_from( + typed::UExpressionInner::Element(m) => zir::UExpression::try_from( f.fold_element_expression(statements_buffer, m) .pop() .unwrap(), ) .unwrap() .into_inner(), - typed_absy::UExpressionInner::Conditional(c) => zir::UExpression::try_from( + typed::UExpressionInner::Conditional(c) => zir::UExpression::try_from( f.fold_conditional_expression(statements_buffer, c) .pop() .unwrap(), @@ -1255,7 +1227,7 @@ fn fold_uint_expression_inner<'ast, T: Field>( fn fold_function<'ast, T: Field>( f: &mut Flattener, - fun: typed_absy::TypedFunction<'ast, T>, + fun: typed::TypedFunction<'ast, T>, ) -> zir::ZirFunction<'ast, T> { let mut main_statements_buffer = vec![]; @@ -1270,10 +1242,10 @@ fn fold_function<'ast, T: Field>( .flat_map(|a| f.fold_declaration_parameter(a)) .collect(), statements: main_statements_buffer, - signature: typed_absy::types::ConcreteSignature::try_from( - crate::typed_absy::types::try_from_g_signature::< - crate::typed_absy::types::DeclarationConstant<'ast, T>, - crate::typed_absy::UExpression<'ast, T>, + signature: typed::types::ConcreteSignature::try_from( + zokrates_ast::typed::types::try_from_g_signature::< + zokrates_ast::typed::types::DeclarationConstant<'ast, T>, + zokrates_ast::typed::UExpression<'ast, T>, >(fun.signature) .unwrap(), ) @@ -1285,12 +1257,12 @@ fn fold_function<'ast, T: Field>( fn fold_array_expression<'ast, T: Field>( f: &mut Flattener, statements_buffer: &mut Vec>, - e: typed_absy::ArrayExpression<'ast, T>, + e: typed::ArrayExpression<'ast, T>, ) -> Vec> { let size: u32 = e.size().try_into().unwrap(); f.fold_array_expression_inner( statements_buffer, - &typed_absy::types::ConcreteType::try_from(e.inner_type().clone()).unwrap(), + &typed::types::ConcreteType::try_from(e.inner_type().clone()).unwrap(), size, e.into_inner(), ) @@ -1299,11 +1271,11 @@ fn fold_array_expression<'ast, T: Field>( fn fold_struct_expression<'ast, T: Field>( f: &mut Flattener, statements_buffer: &mut Vec>, - e: typed_absy::StructExpression<'ast, T>, + e: typed::StructExpression<'ast, T>, ) -> Vec> { f.fold_struct_expression_inner( statements_buffer, - &typed_absy::types::ConcreteStructType::try_from(e.ty().clone()).unwrap(), + &typed::types::ConcreteStructType::try_from(e.ty().clone()).unwrap(), e.into_inner(), ) } @@ -1311,18 +1283,18 @@ fn fold_struct_expression<'ast, T: Field>( fn fold_tuple_expression<'ast, T: Field>( f: &mut Flattener, statements_buffer: &mut Vec>, - e: typed_absy::TupleExpression<'ast, T>, + e: typed::TupleExpression<'ast, T>, ) -> Vec> { f.fold_tuple_expression_inner( statements_buffer, - &typed_absy::types::ConcreteTupleType::try_from(e.ty().clone()).unwrap(), + &typed::types::ConcreteTupleType::try_from(e.ty().clone()).unwrap(), e.into_inner(), ) } fn fold_program<'ast, T: Field>( f: &mut Flattener, - mut p: typed_absy::TypedProgram<'ast, T>, + mut p: typed::TypedProgram<'ast, T>, ) -> zir::ZirProgram<'ast, T> { let main_module = p.modules.remove(&p.main).unwrap(); @@ -1332,7 +1304,7 @@ fn fold_program<'ast, T: Field>( .unwrap() .symbol; let main_function = match main_function { - typed_absy::TypedFunctionSymbol::Here(main) => main, + typed::TypedFunctionSymbol::Here(main) => main, _ => unreachable!(), }; diff --git a/zokrates_core/src/static_analysis/mod.rs b/zokrates_core/src/static_analysis/mod.rs index 2629f0e1..3a54df89 100644 --- a/zokrates_core/src/static_analysis/mod.rs +++ b/zokrates_core/src/static_analysis/mod.rs @@ -15,7 +15,6 @@ mod propagation; mod reducer; mod struct_concretizer; mod uint_optimizer; -mod unconstrained_vars; mod variable_write_remover; mod zir_propagation; @@ -32,10 +31,9 @@ use self::variable_write_remover::VariableWriteRemover; use crate::compile::CompileConfig; use crate::static_analysis::constant_resolver::ConstantResolver; use crate::static_analysis::zir_propagation::ZirPropagator; -use crate::typed_absy::{abi::Abi, TypedProgram}; -use crate::zir::ZirProgram; use std::fmt; -pub use unconstrained_vars::UnconstrainedVariableDetector; +use zokrates_ast::typed::{abi::Abi, TypedProgram}; +use zokrates_ast::zir::ZirProgram; use zokrates_field::Field; #[derive(Debug)] diff --git a/zokrates_core/src/static_analysis/out_of_bounds.rs b/zokrates_core/src/static_analysis/out_of_bounds.rs index 679ca152..7cdc88b6 100644 --- a/zokrates_core/src/static_analysis/out_of_bounds.rs +++ b/zokrates_core/src/static_analysis/out_of_bounds.rs @@ -1,8 +1,8 @@ -use crate::typed_absy::{ +use std::fmt; +use zokrates_ast::typed::{ result_folder::*, Expr, SelectExpression, SelectOrExpression, Type, TypedAssignee, TypedProgram, UExpressionInner, }; -use std::fmt; use zokrates_field::Field; #[derive(Default)] @@ -47,7 +47,7 @@ impl<'ast, T: Field> ResultFolder<'ast, T> for OutOfBoundsChecker { ) -> Result, Error> { match a { TypedAssignee::Select(box array, box index) => { - use crate::typed_absy::Typed; + use zokrates_ast::typed::Typed; let array = self.fold_assignee(array)?; diff --git a/zokrates_core/src/static_analysis/propagation.rs b/zokrates_core/src/static_analysis/propagation.rs index 33ce5ca6..d73962b3 100644 --- a/zokrates_core/src/static_analysis/propagation.rs +++ b/zokrates_core/src/static_analysis/propagation.rs @@ -7,13 +7,13 @@ //! @author Thibaut Schaeffer //! @date 2018 -use crate::typed_absy::result_folder::*; -use crate::typed_absy::types::Type; -use crate::typed_absy::*; use std::collections::HashMap; use std::convert::{TryFrom, TryInto}; use std::fmt; use zokrates_ast::common::FlatEmbed; +use zokrates_ast::typed::result_folder::*; +use zokrates_ast::typed::types::Type; +use zokrates_ast::typed::*; use zokrates_field::Field; pub type Constants<'ast, T> = HashMap, TypedExpression<'ast, T>>; diff --git a/zokrates_core/src/static_analysis/reducer/constants_reader.rs b/zokrates_core/src/static_analysis/reducer/constants_reader.rs index 8fb1d4a1..5e62a6eb 100644 --- a/zokrates_core/src/static_analysis/reducer/constants_reader.rs +++ b/zokrates_core/src/static_analysis/reducer/constants_reader.rs @@ -1,7 +1,7 @@ // given a (partial) map of values for program constants, replace where applicable constants by their value use crate::static_analysis::reducer::ConstantDefinitions; -use crate::typed_absy::{ +use zokrates_ast::typed::{ folder::*, ArrayExpression, ArrayExpressionInner, ArrayType, BooleanExpression, CoreIdentifier, DeclarationConstant, Expr, FieldElementExpression, Identifier, StructExpression, StructExpressionInner, StructType, TypedProgram, TypedSymbolDeclaration, UBitwidth, diff --git a/zokrates_core/src/static_analysis/reducer/constants_writer.rs b/zokrates_core/src/static_analysis/reducer/constants_writer.rs index f84c24b0..6a5a05d0 100644 --- a/zokrates_core/src/static_analysis/reducer/constants_writer.rs +++ b/zokrates_core/src/static_analysis/reducer/constants_writer.rs @@ -3,12 +3,12 @@ use crate::static_analysis::reducer::{ constants_reader::ConstantsReader, reduce_function, ConstantDefinitions, Error, }; -use crate::typed_absy::{ +use std::collections::{BTreeMap, HashSet}; +use zokrates_ast::typed::{ result_folder::*, types::ConcreteGenericsAssignment, OwnedTypedModuleId, TypedConstant, TypedConstantSymbol, TypedConstantSymbolDeclaration, TypedModuleId, TypedProgram, TypedSymbolDeclaration, UExpression, }; -use std::collections::{BTreeMap, HashSet}; use zokrates_field::Field; pub struct ConstantsWriter<'ast, T> { @@ -105,11 +105,11 @@ impl<'ast, T: Field> ResultFolder<'ast, T> for ConstantsWriter<'ast, T> { // if constants were used in the rhs, they are now defined in the map // replace them in the expression - use crate::typed_absy::folder::Folder; + use zokrates_ast::typed::folder::Folder; let c = ConstantsReader::with_constants(&self.constants).fold_constant(c); - use crate::typed_absy::{DeclarationSignature, TypedFunction, TypedStatement}; + use zokrates_ast::typed::{DeclarationSignature, TypedFunction, TypedStatement}; // wrap this expression in a function let wrapper = TypedFunction { @@ -130,13 +130,13 @@ impl<'ast, T: Field> ResultFolder<'ast, T> for ConstantsWriter<'ast, T> { assert_eq!(expressions.len(), 1); let constant_expression = expressions.pop().unwrap(); - use crate::typed_absy::Constant; + use zokrates_ast::typed::Constant; if !constant_expression.is_constant() { return Err(Error::ConstantReduction(id.id.to_string(), id.module)); }; - use crate::typed_absy::Typed; - if crate::typed_absy::types::try_from_g_type::<_, UExpression<'ast, T>>( + use zokrates_ast::typed::Typed; + if zokrates_ast::typed::types::try_from_g_type::<_, UExpression<'ast, T>>( c.ty.clone(), ) .unwrap() diff --git a/zokrates_core/src/static_analysis/reducer/inline.rs b/zokrates_core/src/static_analysis/reducer/inline.rs index 3303766f..c0160839 100644 --- a/zokrates_core/src/static_analysis/reducer/inline.rs +++ b/zokrates_core/src/static_analysis/reducer/inline.rs @@ -28,16 +28,16 @@ use crate::static_analysis::reducer::Output; use crate::static_analysis::reducer::ShallowTransformer; use crate::static_analysis::reducer::Versions; -use crate::typed_absy::types::{ConcreteGenericsAssignment, IntoTypes}; -use crate::typed_absy::CoreIdentifier; -use crate::typed_absy::Identifier; -use crate::typed_absy::TypedAssignee; -use crate::typed_absy::{ +use zokrates_ast::common::FlatEmbed; +use zokrates_ast::typed::types::{ConcreteGenericsAssignment, IntoTypes}; +use zokrates_ast::typed::CoreIdentifier; +use zokrates_ast::typed::Identifier; +use zokrates_ast::typed::TypedAssignee; +use zokrates_ast::typed::{ ConcreteFunctionKey, ConcreteSignature, ConcreteVariable, DeclarationFunctionKey, Expr, Signature, TypedExpression, TypedFunctionSymbol, TypedFunctionSymbolDeclaration, TypedProgram, TypedStatement, Types, UExpression, UExpressionInner, Variable, }; -use zokrates_ast::common::FlatEmbed; use zokrates_field::Field; pub enum InlineError<'ast, T> { @@ -89,7 +89,7 @@ pub fn inline_call<'a, 'ast, T: Field, E: Expr<'ast, T>>( ) -> InlineResult<'ast, T> { use std::convert::TryFrom; - use crate::typed_absy::Typed; + use zokrates_ast::typed::Typed; let output_types = output.clone().into_types(); diff --git a/zokrates_core/src/static_analysis/reducer/mod.rs b/zokrates_core/src/static_analysis/reducer/mod.rs index 943ae036..094033c5 100644 --- a/zokrates_core/src/static_analysis/reducer/mod.rs +++ b/zokrates_core/src/static_analysis/reducer/mod.rs @@ -17,14 +17,14 @@ mod inline; mod shallow_ssa; use self::inline::{inline_call, InlineError}; -use crate::typed_absy::result_folder::*; -use crate::typed_absy::types::ConcreteGenericsAssignment; -use crate::typed_absy::types::GGenericsAssignment; -use crate::typed_absy::CanonicalConstantIdentifier; -use crate::typed_absy::Folder; use std::collections::HashMap; +use zokrates_ast::typed::result_folder::*; +use zokrates_ast::typed::types::ConcreteGenericsAssignment; +use zokrates_ast::typed::types::GGenericsAssignment; +use zokrates_ast::typed::CanonicalConstantIdentifier; +use zokrates_ast::typed::Folder; -use crate::typed_absy::{ +use zokrates_ast::typed::{ ArrayExpressionInner, ArrayType, BlockExpression, CoreIdentifier, Expr, FunctionCall, FunctionCallExpression, FunctionCallOrExpression, Id, Identifier, OwnedTypedModuleId, TypedExpression, TypedExpressionList, TypedExpressionListInner, TypedFunction, @@ -640,9 +640,9 @@ fn compute_hash(f: &TypedFunction) -> u64 { #[cfg(test)] mod tests { use super::*; - use crate::typed_absy::types::DeclarationConstant; - use crate::typed_absy::types::DeclarationSignature; - use crate::typed_absy::{ + use zokrates_ast::typed::types::DeclarationConstant; + use zokrates_ast::typed::types::DeclarationSignature; + use zokrates_ast::typed::{ ArrayExpression, ArrayExpressionInner, DeclarationFunctionKey, DeclarationType, DeclarationVariable, FieldElementExpression, GenericIdentifier, Identifier, OwnedTypedModuleId, Select, Type, TypedExpression, TypedExpressionList, diff --git a/zokrates_core/src/static_analysis/reducer/shallow_ssa.rs b/zokrates_core/src/static_analysis/reducer/shallow_ssa.rs index 44ef2922..b82d70ad 100644 --- a/zokrates_core/src/static_analysis/reducer/shallow_ssa.rs +++ b/zokrates_core/src/static_analysis/reducer/shallow_ssa.rs @@ -24,10 +24,10 @@ // endfor // return b_3 // we leave versions b_1 and b_2 to make b accessible and modifiable inside the for-loop -use crate::typed_absy::types::ConcreteGenericsAssignment; -use crate::typed_absy::types::Type; -use crate::typed_absy::*; use zokrates_ast::typed::folder::*; +use zokrates_ast::typed::types::ConcreteGenericsAssignment; +use zokrates_ast::typed::types::Type; +use zokrates_ast::typed::*; use zokrates_field::Field; @@ -192,7 +192,7 @@ impl<'ast, 'a, T: Field> Folder<'ast, T> for ShallowTransformer<'ast, 'a> { #[cfg(test)] mod tests { use super::*; - use crate::typed_absy::types::DeclarationSignature; + use zokrates_ast::typed::types::DeclarationSignature; use zokrates_field::Bn128Field; mod normal { use super::*; @@ -336,7 +336,7 @@ mod tests { #[test] fn incremental_multiple_definition() { - use crate::typed_absy::types::Type; + use zokrates_ast::typed::types::Type; // field a // a = 2 @@ -575,7 +575,7 @@ mod tests { mod for_loop { use super::*; - use crate::typed_absy::types::GGenericsAssignment; + use zokrates_ast::typed::types::GGenericsAssignment; #[test] fn treat_loop() { // def main(field a) -> field: @@ -773,7 +773,7 @@ mod tests { mod function_call { use super::*; - use crate::typed_absy::types::GGenericsAssignment; + use zokrates_ast::typed::types::GGenericsAssignment; // test that function calls are left in #[test] fn treat_calls() { diff --git a/zokrates_core/src/static_analysis/struct_concretizer.rs b/zokrates_core/src/static_analysis/struct_concretizer.rs index e3d30f14..208a472a 100644 --- a/zokrates_core/src/static_analysis/struct_concretizer.rs +++ b/zokrates_core/src/static_analysis/struct_concretizer.rs @@ -5,15 +5,15 @@ // for structs, `Foo { field[N] a }` is propagated to `Foo<42> { field[N] a }`. The missing step is replacing `N` by `42` // *inside* the canonical type, so that it can be concretized in the same way arrays are. -use crate::typed_absy::{ +use std::marker::PhantomData; +use zokrates_ast::typed::folder::*; +use zokrates_ast::typed::{ types::{ ConcreteGenericsAssignment, DeclarationArrayType, DeclarationConstant, DeclarationStructMember, GGenericsAssignment, }, DeclarationStructType, GenericIdentifier, TypedProgram, }; -use std::marker::PhantomData; -use zokrates_ast::typed::folder::*; use zokrates_field::Field; pub struct StructConcretizer<'ast, T> { diff --git a/zokrates_core/src/static_analysis/trimmer.rs b/zokrates_core/src/static_analysis/trimmer.rs index 1db07400..f4a2f406 100644 --- a/zokrates_core/src/static_analysis/trimmer.rs +++ b/zokrates_core/src/static_analysis/trimmer.rs @@ -1,5 +1,5 @@ -use crate::typed_absy::TypedModule; -use crate::typed_absy::{TypedFunctionSymbol, TypedProgram}; +use zokrates_ast::typed::TypedModule; +use zokrates_ast::typed::{TypedFunctionSymbol, TypedProgram}; use zokrates_field::Field; pub struct Trimmer; diff --git a/zokrates_core/src/static_analysis/uint_optimizer.rs b/zokrates_core/src/static_analysis/uint_optimizer.rs index 65796bd2..7bcf6069 100644 --- a/zokrates_core/src/static_analysis/uint_optimizer.rs +++ b/zokrates_core/src/static_analysis/uint_optimizer.rs @@ -1,8 +1,8 @@ -use crate::zir::folder::*; -use crate::zir::*; use std::collections::HashMap; use std::ops::{BitAnd, Shl, Shr}; use zokrates_ast::common::FlatEmbed; +use zokrates_ast::zir::folder::*; +use zokrates_ast::zir::*; use zokrates_field::Field; #[derive(Default)] diff --git a/zokrates_core/src/static_analysis/variable_write_remover.rs b/zokrates_core/src/static_analysis/variable_write_remover.rs index 4a6040d4..0dfbf61c 100644 --- a/zokrates_core/src/static_analysis/variable_write_remover.rs +++ b/zokrates_core/src/static_analysis/variable_write_remover.rs @@ -4,10 +4,10 @@ //! @author Thibaut Schaeffer //! @date 2018 -use crate::typed_absy::types::{MemberId, Type}; -use crate::typed_absy::*; use std::collections::HashSet; use zokrates_ast::typed::folder::*; +use zokrates_ast::typed::types::{MemberId, Type}; +use zokrates_ast::typed::*; use zokrates_field::Field; pub struct VariableWriteRemover; diff --git a/zokrates_core/src/static_analysis/zir_propagation.rs b/zokrates_core/src/static_analysis/zir_propagation.rs index d06ba04d..0b2fc5cc 100644 --- a/zokrates_core/src/static_analysis/zir_propagation.rs +++ b/zokrates_core/src/static_analysis/zir_propagation.rs @@ -1,12 +1,12 @@ -use crate::zir::result_folder::fold_statement; -use crate::zir::result_folder::ResultFolder; -use crate::zir::types::UBitwidth; -use crate::zir::{ +use std::collections::HashMap; +use std::fmt; +use zokrates_ast::zir::result_folder::fold_statement; +use zokrates_ast::zir::result_folder::ResultFolder; +use zokrates_ast::zir::types::UBitwidth; +use zokrates_ast::zir::{ BooleanExpression, FieldElementExpression, Identifier, RuntimeError, UExpression, UExpressionInner, ZirExpression, ZirProgram, ZirStatement, }; -use std::collections::HashMap; -use std::fmt; use zokrates_field::Field; type Constants<'ast, T> = HashMap, ZirExpression<'ast, T>>; @@ -704,13 +704,9 @@ impl<'ast, T: Field> ResultFolder<'ast, T> for ZirPropagator<'ast, T> { #[cfg(test)] mod tests { use super::*; - use crate::zir::RuntimeError; + use zokrates_ast::zir::RuntimeError; use zokrates_field::Bn128Field; - pub fn mock() -> RuntimeError { - RuntimeError::SourceAssertion(String::default()) - } - #[test] fn propagation() { // assert([x, 1] == [y, 1]) @@ -725,7 +721,7 @@ mod tests { box FieldElementExpression::Number(Bn128Field::from(1)), ), ), - mock(), + RuntimeError::mock(), )]; let mut propagator = ZirPropagator::default(); @@ -745,7 +741,7 @@ mod tests { box FieldElementExpression::Identifier("x".into()), box FieldElementExpression::Identifier("y".into()), ), - mock() + RuntimeError::mock() )] ); } diff --git a/zokrates_interpreter/Cargo.toml b/zokrates_interpreter/Cargo.toml index f18876b0..9f7b4bbd 100644 --- a/zokrates_interpreter/Cargo.toml +++ b/zokrates_interpreter/Cargo.toml @@ -3,8 +3,18 @@ name = "zokrates_interpreter" version = "0.1.0" edition = "2021" +[features] +default = ["bellman", "ark"] +bellman = ["zokrates_field/bellman", "pairing_ce"] +ark = ["ark-bls12-377"] + [dependencies] zokrates_field = { version = "0.5", path = "../zokrates_field", default-features = false } zokrates_ast = { version = "0.1", path = "../zokrates_ast", default-features = false } num = { version = "0.1.36", default-features = false } num-bigint = { version = "0.2", default-features = false } +pairing_ce = { version = "^0.21", optional = true } +ark-bls12-377 = { version = "^0.3.0", features = ["curve"], default-features = false, optional = true } +zokrates_embed = { version = "0.1.0", path = "../zokrates_embed" } +serde = { version = "1.0", features = ["derive"] } + diff --git a/zokrates_interpreter/src/lib.rs b/zokrates_interpreter/src/lib.rs index ea6cabcb..bedf3d16 100644 --- a/zokrates_interpreter/src/lib.rs +++ b/zokrates_interpreter/src/lib.rs @@ -1,4 +1,4 @@ -use num::traits::ops::checked::CheckedDiv; +use serde::{Deserialize, Serialize}; use std::fmt; use zokrates_ast::ir::{ LinComb, ProgIterator, QuadComb, RuntimeError, Solver, Statement, Variable, Witness, @@ -207,7 +207,7 @@ impl Interpreter { generate_sha256_round_witness::(&i, &h) .into_iter() .map(|x| { - use bellman_ce::pairing::ff::{PrimeField, PrimeFieldRepr}; + use pairing_ce::ff::{PrimeField, PrimeFieldRepr}; let mut res: Vec = vec![]; x.into_repr().write_le(&mut res).unwrap(); T::from_byte_vector(res) @@ -237,7 +237,7 @@ impl Interpreter { #[derive(Debug)] pub struct EvaluationError; -#[derive(PartialEq, Clone)] +#[derive(PartialEq, Clone, Serialize, Deserialize)] pub enum Error { UnsatisfiedConstraint { error: Option }, Solver, diff --git a/zokrates_libsnark/Cargo.toml b/zokrates_libsnark/Cargo.toml new file mode 100644 index 00000000..e755747e --- /dev/null +++ b/zokrates_libsnark/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "zokrates_libsnark" +version = "0.1.0" +edition = "2021" +build = "build.rs" + +[dependencies] +zokrates_proof_systems = { version = "0.1", path = "../zokrates_proof_systems" } + +[dev-dependencies] +zokrates_interpreter = { version = "0.1", path = "../zokrates_interpreter" } + +[build-dependencies] +cc = { version = "1.0", features = ["parallel"] } +cmake = { version = "=0.1.45" } \ No newline at end of file diff --git a/zokrates_core/build.rs b/zokrates_libsnark/build.rs similarity index 96% rename from zokrates_core/build.rs rename to zokrates_libsnark/build.rs index 7f48be14..20242705 100644 --- a/zokrates_core/build.rs +++ b/zokrates_libsnark/build.rs @@ -1,10 +1,4 @@ -#[cfg(feature = "libsnark")] -extern crate cc; -#[cfg(feature = "libsnark")] -extern crate cmake; - fn main() { - #[cfg(feature = "libsnark")] { use std::env; use std::path::PathBuf; diff --git a/zokrates_core/lib/ffi.cpp b/zokrates_libsnark/lib/ffi.cpp similarity index 100% rename from zokrates_core/lib/ffi.cpp rename to zokrates_libsnark/lib/ffi.cpp diff --git a/zokrates_core/lib/ffi.hpp b/zokrates_libsnark/lib/ffi.hpp similarity index 100% rename from zokrates_core/lib/ffi.hpp rename to zokrates_libsnark/lib/ffi.hpp diff --git a/zokrates_core/lib/gm17.cpp b/zokrates_libsnark/lib/gm17.cpp similarity index 100% rename from zokrates_core/lib/gm17.cpp rename to zokrates_libsnark/lib/gm17.cpp diff --git a/zokrates_core/lib/gm17.hpp b/zokrates_libsnark/lib/gm17.hpp similarity index 100% rename from zokrates_core/lib/gm17.hpp rename to zokrates_libsnark/lib/gm17.hpp diff --git a/zokrates_core/lib/pghr13.cpp b/zokrates_libsnark/lib/pghr13.cpp similarity index 100% rename from zokrates_core/lib/pghr13.cpp rename to zokrates_libsnark/lib/pghr13.cpp diff --git a/zokrates_core/lib/pghr13.hpp b/zokrates_libsnark/lib/pghr13.hpp similarity index 100% rename from zokrates_core/lib/pghr13.hpp rename to zokrates_libsnark/lib/pghr13.hpp diff --git a/zokrates_core/lib/util.tcc b/zokrates_libsnark/lib/util.tcc similarity index 100% rename from zokrates_core/lib/util.tcc rename to zokrates_libsnark/lib/util.tcc diff --git a/zokrates_core/src/proof_system/libsnark/ffi.rs b/zokrates_libsnark/src/ffi.rs similarity index 100% rename from zokrates_core/src/proof_system/libsnark/ffi.rs rename to zokrates_libsnark/src/ffi.rs diff --git a/zokrates_core/src/proof_system/libsnark/gm17.rs b/zokrates_libsnark/src/gm17.rs similarity index 100% rename from zokrates_core/src/proof_system/libsnark/gm17.rs rename to zokrates_libsnark/src/gm17.rs diff --git a/zokrates_core/src/proof_system/libsnark/mod.rs b/zokrates_libsnark/src/lib.rs similarity index 100% rename from zokrates_core/src/proof_system/libsnark/mod.rs rename to zokrates_libsnark/src/lib.rs diff --git a/zokrates_core/src/proof_system/libsnark/pghr13.rs b/zokrates_libsnark/src/pghr13.rs similarity index 100% rename from zokrates_core/src/proof_system/libsnark/pghr13.rs rename to zokrates_libsnark/src/pghr13.rs diff --git a/zokrates_proof_systems/Cargo.toml b/zokrates_proof_systems/Cargo.toml new file mode 100644 index 00000000..c323d612 --- /dev/null +++ b/zokrates_proof_systems/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "zokrates_proof_systems" +version = "0.1.0" +edition = "2021" + +[dependencies] +zokrates_ast = { version = "0.1", path = "../zokrates_ast" } +serde = { version = "1.0", features = ["derive"] } +zokrates_field = { version = "0.5.0", path = "../zokrates_field", default-features = false } +hex = "0.4.2" +regex = "0.2" +cfg-if = "0.1" +ethabi = "17.0.0" +primitive-types = { version = "0.11", features = ["rlp"] } +rand_0_4 = { version = "0.4", package = "rand" } diff --git a/zokrates_core/src/proof_system/mod.rs b/zokrates_proof_systems/src/lib.rs similarity index 80% rename from zokrates_core/src/proof_system/mod.rs rename to zokrates_proof_systems/src/lib.rs index 64e30928..87afaae0 100644 --- a/zokrates_core/src/proof_system/mod.rs +++ b/zokrates_proof_systems/src/lib.rs @@ -1,8 +1,3 @@ -#[cfg(feature = "bellman")] -pub mod bellman; -#[cfg(feature = "libsnark")] -pub mod libsnark; - pub mod to_token; mod scheme; @@ -15,20 +10,11 @@ use zokrates_ast::ir; use serde::de::DeserializeOwned; use serde::{Deserialize, Serialize}; -use zokrates_field::{Bls12_377Field, Bls12_381Field, Bn128Field, Field}; -cfg_if::cfg_if! { - if #[cfg(feature = "bellman")] { - use rand_0_4::Rng; - use std::io::{Read, Write}; - use zokrates_field::BellmanFieldExtensions; - } -} +use rand_0_4::Rng; +use std::io::{Read, Write}; -pub trait NotBw6_761Field {} -impl NotBw6_761Field for Bls12_377Field {} -impl NotBw6_761Field for Bls12_381Field {} -impl NotBw6_761Field for Bn128Field {} +use zokrates_field::Field; #[derive(Serialize)] pub struct SetupKeypair { @@ -50,7 +36,7 @@ pub struct Proof> { #[allow(dead_code)] impl> Proof { - fn new(proof: S::ProofPoints, inputs: Vec) -> Self { + pub fn new(proof: S::ProofPoints, inputs: Vec) -> Self { Proof { proof, inputs } } } @@ -62,13 +48,29 @@ pub type Fq2 = (String, String); #[derive(Serialize, Deserialize, Clone, Debug)] pub struct G1Affine(pub Fq, pub Fq); +#[derive(Serialize, Deserialize, Clone)] +#[serde(untagged)] +pub enum G2Affine { + Fq2(G2AffineFq2), + Fq(G2AffineFq), +} + +impl ToString for G2Affine { + fn to_string(&self) -> String { + match self { + G2Affine::Fq(e) => e.to_string(), + G2Affine::Fq2(e) => e.to_string(), + } + } +} + // When G2 is defined on Fq2 field #[derive(Serialize, Deserialize, Clone)] -pub struct G2Affine(Fq2, Fq2); +pub struct G2AffineFq2(pub Fq2, pub Fq2); // When G2 is defined on a Fq field (BW6_761 curve) #[derive(Serialize, Deserialize, Clone)] -pub struct G2AffineFq(Fq, Fq); +pub struct G2AffineFq(pub Fq, pub Fq); impl ToString for G1Affine { fn to_string(&self) -> String { @@ -81,7 +83,7 @@ impl ToString for G2AffineFq { format!("{}, {}", self.0, self.1) } } -impl ToString for G2Affine { +impl ToString for G2AffineFq2 { fn to_string(&self) -> String { format!( "[{}, {}], [{}, {}]", @@ -117,8 +119,7 @@ pub trait UniversalBackend>: Backend { ) -> Result, String>; } -#[cfg(feature = "bellman")] -pub trait MpcBackend> { +pub trait MpcBackend> { fn initialize>>( program: ir::ProgIterator, phase1_radix: &mut R, diff --git a/zokrates_core/src/proof_system/scheme/gm17.rs b/zokrates_proof_systems/src/scheme/gm17.rs similarity index 89% rename from zokrates_core/src/proof_system/scheme/gm17.rs rename to zokrates_proof_systems/src/scheme/gm17.rs index 6882e243..1a4dd00f 100644 --- a/zokrates_core/src/proof_system/scheme/gm17.rs +++ b/zokrates_proof_systems/src/scheme/gm17.rs @@ -1,12 +1,9 @@ -use crate::proof_system::scheme::{NonUniversalScheme, Scheme}; -use crate::proof_system::solidity::{solidity_pairing_lib, SOLIDITY_G2_ADDITION_LIB}; -use crate::proof_system::{ - G1Affine, G2Affine, G2AffineFq, NotBw6_761Field, SolidityCompatibleField, - SolidityCompatibleScheme, -}; +use crate::scheme::{NonUniversalScheme, Scheme}; +use crate::solidity::{solidity_pairing_lib, SOLIDITY_G2_ADDITION_LIB}; +use crate::{G1Affine, G2Affine, SolidityCompatibleField, SolidityCompatibleScheme}; use regex::Regex; use serde::{Deserialize, Serialize}; -use zokrates_field::{Bw6_761Field, Field}; +use zokrates_field::Field; #[allow(clippy::upper_case_acronyms)] pub struct GM17; @@ -28,21 +25,14 @@ pub struct VerificationKey { pub query: Vec, } -impl NonUniversalScheme for GM17 {} +impl NonUniversalScheme for GM17 {} -impl NonUniversalScheme for GM17 {} - -impl Scheme for GM17 { +impl Scheme for GM17 { type VerificationKey = VerificationKey; type ProofPoints = ProofPoints; } -impl Scheme for GM17 { - type VerificationKey = VerificationKey; - type ProofPoints = ProofPoints; -} - -impl SolidityCompatibleScheme for GM17 { +impl SolidityCompatibleScheme for GM17 { type Proof = Self::ProofPoints; fn export_solidity_verifier(vk: >::VerificationKey) -> String { diff --git a/zokrates_core/src/proof_system/scheme/groth16.rs b/zokrates_proof_systems/src/scheme/groth16.rs similarity index 96% rename from zokrates_core/src/proof_system/scheme/groth16.rs rename to zokrates_proof_systems/src/scheme/groth16.rs index c1f526a9..953efa12 100644 --- a/zokrates_core/src/proof_system/scheme/groth16.rs +++ b/zokrates_proof_systems/src/scheme/groth16.rs @@ -1,8 +1,6 @@ -use crate::proof_system::scheme::{NonUniversalScheme, Scheme}; -use crate::proof_system::solidity::solidity_pairing_lib; -use crate::proof_system::{ - G1Affine, G2Affine, MpcScheme, SolidityCompatibleField, SolidityCompatibleScheme, -}; +use crate::scheme::{NonUniversalScheme, Scheme}; +use crate::solidity::solidity_pairing_lib; +use crate::{G1Affine, G2Affine, MpcScheme, SolidityCompatibleField, SolidityCompatibleScheme}; use regex::Regex; use serde::{Deserialize, Serialize}; use zokrates_field::Field; diff --git a/zokrates_core/src/proof_system/scheme/marlin.rs b/zokrates_proof_systems/src/scheme/marlin.rs similarity index 98% rename from zokrates_core/src/proof_system/scheme/marlin.rs rename to zokrates_proof_systems/src/scheme/marlin.rs index 75b32d68..caeeedd1 100644 --- a/zokrates_core/src/proof_system/scheme/marlin.rs +++ b/zokrates_proof_systems/src/scheme/marlin.rs @@ -1,8 +1,6 @@ -use crate::proof_system::scheme::{Scheme, UniversalScheme}; -use crate::proof_system::solidity::{ - solidity_pairing_lib, SolidityCompatibleField, SolidityCompatibleScheme, -}; -use crate::proof_system::{Fr, G1Affine, G2Affine, NotBw6_761Field}; +use crate::scheme::{Scheme, UniversalScheme}; +use crate::solidity::{solidity_pairing_lib, SolidityCompatibleField, SolidityCompatibleScheme}; +use crate::{Fr, G1Affine, G2Affine}; use serde::{Deserialize, Serialize}; use zokrates_field::Field; @@ -86,7 +84,7 @@ impl Scheme for Marlin { impl UniversalScheme for Marlin {} -impl SolidityCompatibleScheme for Marlin { +impl SolidityCompatibleScheme for Marlin { type Proof = SolidityProof; fn export_solidity_verifier(vk: >::VerificationKey) -> String { diff --git a/zokrates_core/src/proof_system/scheme/mod.rs b/zokrates_proof_systems/src/scheme/mod.rs similarity index 100% rename from zokrates_core/src/proof_system/scheme/mod.rs rename to zokrates_proof_systems/src/scheme/mod.rs diff --git a/zokrates_core/src/proof_system/scheme/pghr13.rs b/zokrates_proof_systems/src/scheme/pghr13.rs similarity index 97% rename from zokrates_core/src/proof_system/scheme/pghr13.rs rename to zokrates_proof_systems/src/scheme/pghr13.rs index 1dcf2184..581a83e9 100644 --- a/zokrates_core/src/proof_system/scheme/pghr13.rs +++ b/zokrates_proof_systems/src/scheme/pghr13.rs @@ -1,6 +1,6 @@ -use crate::proof_system::scheme::{NonUniversalScheme, Scheme}; -use crate::proof_system::solidity::solidity_pairing_lib; -use crate::proof_system::{G1Affine, G2Affine, SolidityCompatibleField, SolidityCompatibleScheme}; +use crate::scheme::{NonUniversalScheme, Scheme}; +use crate::solidity::solidity_pairing_lib; +use crate::{G1Affine, G2Affine, SolidityCompatibleField, SolidityCompatibleScheme}; use regex::Regex; use serde::{Deserialize, Serialize}; use zokrates_field::Field; diff --git a/zokrates_core/src/proof_system/solidity.rs b/zokrates_proof_systems/src/solidity.rs similarity index 99% rename from zokrates_core/src/proof_system/solidity.rs rename to zokrates_proof_systems/src/solidity.rs index 5bc93326..f30e27f8 100644 --- a/zokrates_core/src/proof_system/solidity.rs +++ b/zokrates_proof_systems/src/solidity.rs @@ -1,4 +1,4 @@ -use crate::proof_system::Scheme; +use crate::Scheme; use serde::{de::DeserializeOwned, Serialize}; use zokrates_field::{Bn128Field, Field}; diff --git a/zokrates_core/src/proof_system/to_token.rs b/zokrates_proof_systems/src/to_token.rs similarity index 90% rename from zokrates_core/src/proof_system/to_token.rs rename to zokrates_proof_systems/src/to_token.rs index e813e1cb..3c3dae53 100644 --- a/zokrates_core/src/proof_system/to_token.rs +++ b/zokrates_proof_systems/src/to_token.rs @@ -2,8 +2,8 @@ use ethabi::Token; use primitive_types::U256; use super::{ - Fr, G1Affine, G2Affine, Marlin, NotBw6_761Field, SolidityCompatibleField, - SolidityCompatibleScheme, G16, GM17, PGHR13, + Fr, G1Affine, G2Affine, Marlin, SolidityCompatibleField, SolidityCompatibleScheme, G16, GM17, + PGHR13, }; /// Helper methods for parsing group structure @@ -15,16 +15,19 @@ pub fn encode_g1_element(g: &G1Affine) -> (U256, U256) { } pub fn encode_g2_element(g: &G2Affine) -> ((U256, U256), (U256, U256)) { - ( - ( - U256::from(&hex::decode(&g.0 .0.trim_start_matches("0x")).unwrap()[..]), - U256::from(&hex::decode(&g.0 .1.trim_start_matches("0x")).unwrap()[..]), + match g { + G2Affine::Fq2(g) => ( + ( + U256::from(&hex::decode(&g.0 .0.trim_start_matches("0x")).unwrap()[..]), + U256::from(&hex::decode(&g.0 .1.trim_start_matches("0x")).unwrap()[..]), + ), + ( + U256::from(&hex::decode(&g.1 .0.trim_start_matches("0x")).unwrap()[..]), + U256::from(&hex::decode(&g.1 .1.trim_start_matches("0x")).unwrap()[..]), + ), ), - ( - U256::from(&hex::decode(&g.1 .0.trim_start_matches("0x")).unwrap()[..]), - U256::from(&hex::decode(&g.1 .1.trim_start_matches("0x")).unwrap()[..]), - ), - ) + _ => unreachable!(), + } } pub fn encode_fr_element(f: &Fr) -> U256 { @@ -124,7 +127,7 @@ impl ToToken for G16 { } } -impl ToToken for GM17 { +impl ToToken for GM17 { fn to_token(proof: Self::Proof) -> Token { let a = { let (x, y) = encode_g1_element(&proof.a); @@ -155,7 +158,7 @@ impl ToToken for GM17 { } } -impl ToToken for Marlin { +impl ToToken for Marlin { fn to_token(proof: Self::Proof) -> Token { let comms_1_token = Token::Array( proof diff --git a/zokrates_test/Cargo.toml b/zokrates_test/Cargo.toml index a12ba340..30fb5e7a 100644 --- a/zokrates_test/Cargo.toml +++ b/zokrates_test/Cargo.toml @@ -7,11 +7,20 @@ edition = "2018" [dependencies] zokrates_field = { version = "0.5.0", path = "../zokrates_field" } zokrates_core = { version = "0.6", path = "../zokrates_core" } +zokrates_ast = { version = "0.1", path = "../zokrates_ast" } +zokrates_interpreter = { version = "0.1", path = "../zokrates_interpreter" } zokrates_fs_resolver = { version = "0.5", path = "../zokrates_fs_resolver" } zokrates_abi = { version = "0.1", path = "../zokrates_abi" } +zokrates_common = { version = "0.1", path = "../zokrates_common" } serde = "1.0" serde_derive = "1.0" serde_json = { version = "1.0", features = ["preserve_order"] } typed-arena = "1.4.1" +[dev-dependencies] +wasm-bindgen-test = "^0.3.0" +zokrates_ark = { version = "0.1", path = "../zokrates_ark" } +zokrates_proof_systems = { version = "0.1", path = "../zokrates_proof_systems" } + + [lib] diff --git a/zokrates_test/src/lib.rs b/zokrates_test/src/lib.rs index 7ddbaf09..10e5ff65 100644 --- a/zokrates_test/src/lib.rs +++ b/zokrates_test/src/lib.rs @@ -5,11 +5,8 @@ use std::fs::File; use std::io::BufReader; use std::path::{Path, PathBuf}; -use zokrates_core::ir; -use zokrates_core::{ - compile::{compile, CompileConfig}, - typed_absy::ConcreteType, -}; +use zokrates_ast::typed::ConcreteType; +use zokrates_core::compile::{compile, CompileConfig}; use zokrates_field::{Bls12_377Field, Bls12_381Field, Bn128Field, Bw6_761Field, Field}; use zokrates_fs_resolver::FileSystemResolver; @@ -43,7 +40,7 @@ struct Test { pub output: TestResult, } -type TestResult = Result; +type TestResult = Result; #[derive(Serialize, Deserialize, Clone, PartialEq, Debug)] struct Output { @@ -67,7 +64,10 @@ fn try_parse_abi_val( zokrates_abi::parse_strict_json(s, types).map(|v| v.encode()) } -fn compare(result: Result, expected: TestResult) -> Result<(), String> { +fn compare( + result: Result, + expected: TestResult, +) -> Result<(), String> { if result != expected { return Err(format!("Expected {:?} but found {:?}", expected, result)); } @@ -146,7 +146,7 @@ fn compile_and_run(t: Tests) { ); }; - let interpreter = zokrates_core::ir::Interpreter::default(); + let interpreter = zokrates_interpreter::Interpreter::default(); let with_abi = t.abi.unwrap_or(true); for test in t.tests.into_iter() { @@ -167,7 +167,7 @@ fn compile_and_run(t: Tests) { let output = interpreter.execute(bin.clone(), &input); use zokrates_abi::Decode; - let output: Result = output.map(|witness| Output { + let output: Result = output.map(|witness| Output { values: zokrates_abi::Values::decode( witness.return_values(), if with_abi { @@ -178,7 +178,7 @@ fn compile_and_run(t: Tests) { .iter() .flat_map(|t| { (0..t.get_primitive_count()) - .map(|_| zokrates_core::typed_absy::ConcreteType::FieldElement) + .map(|_| zokrates_ast::typed::ConcreteType::FieldElement) }) .collect() }, diff --git a/zokrates_core/tests/out_of_range.rs b/zokrates_test/tests/out_of_range.rs similarity index 97% rename from zokrates_core/tests/out_of_range.rs rename to zokrates_test/tests/out_of_range.rs index 723aec0a..565c96cf 100644 --- a/zokrates_core/tests/out_of_range.rs +++ b/zokrates_test/tests/out_of_range.rs @@ -6,12 +6,10 @@ use std::io; use typed_arena::Arena; use zokrates_common::Resolver; use zokrates_core::compile::CompileConfig; -use zokrates_core::{ - compile::{compile, CompilationArtifacts}, - ir::Interpreter, -}; +use zokrates_core::compile::{compile, CompilationArtifacts}; use zokrates_field::Bn128Field; use zokrates_fs_resolver::FileSystemResolver; +use zokrates_interpreter::Interpreter; #[test] fn lt_field() { diff --git a/zokrates_core/tests/wasm.rs b/zokrates_test/tests/wasm.rs similarity index 58% rename from zokrates_core/tests/wasm.rs rename to zokrates_test/tests/wasm.rs index 123a2028..32efefd3 100644 --- a/zokrates_core/tests/wasm.rs +++ b/zokrates_test/tests/wasm.rs @@ -4,23 +4,21 @@ extern crate wasm_bindgen_test; extern crate zokrates_core; extern crate zokrates_field; use wasm_bindgen_test::*; -use zokrates_core::flat_absy::{FlatParameter, FlatVariable}; -use zokrates_core::ir::{Interpreter, Prog, Statement}; -use zokrates_core::proof_system::{Backend, NonUniversalBackend}; +use zokrates_ast::flat::{Parameter, Variable}; +use zokrates_ast::ir::{Prog, Statement}; use zokrates_field::Bn128Field; +use zokrates_interpreter::Interpreter; +use zokrates_proof_systems::{Backend, NonUniversalBackend}; -use zokrates_core::proof_system::ark::Ark; -use zokrates_core::proof_system::groth16::G16; +use zokrates_ark::Ark; +use zokrates_proof_systems::groth16::G16; #[wasm_bindgen_test] fn generate_proof() { let program: Prog = Prog { - arguments: vec![FlatParameter::public(FlatVariable::new(0))], + arguments: vec![Parameter::public(Variable::new(0))], return_count: 1, - statements: vec![Statement::constraint( - FlatVariable::new(0), - FlatVariable::new(0), - )], + statements: vec![Statement::constraint(Variable::new(0), Variable::new(0))], }; let interpreter = Interpreter::default(); From 3c517d800239fa5e4a4cbd79c1f6c3ccd53a27a4 Mon Sep 17 00:00:00 2001 From: schaeff Date: Fri, 13 May 2022 13:56:35 +0200 Subject: [PATCH 03/19] fix zokrates_libsnark and add it to workspace --- Cargo.lock | 4 ++++ Cargo.toml | 3 ++- zokrates_libsnark/Cargo.toml | 5 ++++- zokrates_libsnark/build.rs | 1 + zokrates_libsnark/src/gm17.rs | 17 +++++++++------ zokrates_libsnark/src/lib.rs | 38 +++++++++++++++++---------------- zokrates_libsnark/src/pghr13.rs | 29 ++++++++++++------------- 7 files changed, 55 insertions(+), 42 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 49b4bf2c..44ab891c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3027,6 +3027,10 @@ version = "0.1.0" dependencies = [ "cc", "cmake", + "hex 0.4.3", + "zokrates_ast", + "zokrates_field", + "zokrates_interpreter", "zokrates_proof_systems", ] diff --git a/Cargo.toml b/Cargo.toml index 15ceed38..8723ab9e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,7 +16,8 @@ members = [ "zokrates_interpreter", "zokrates_embed", "zokrates_bellman", + "zokrates_libsnark", "zokrates_proof_systems", ] -exclude = ["zokrates_js", "zokrates_libsnark"] \ No newline at end of file +exclude = ["zokrates_js"] \ No newline at end of file diff --git a/zokrates_libsnark/Cargo.toml b/zokrates_libsnark/Cargo.toml index e755747e..d8ae7bb7 100644 --- a/zokrates_libsnark/Cargo.toml +++ b/zokrates_libsnark/Cargo.toml @@ -5,7 +5,10 @@ edition = "2021" build = "build.rs" [dependencies] -zokrates_proof_systems = { version = "0.1", path = "../zokrates_proof_systems" } +zokrates_field = { version = "0.5", path = "../zokrates_field", default-features = false } +zokrates_ast = { version = "0.1", path = "../zokrates_ast", default-features = false } +zokrates_proof_systems = { version = "0.1", path = "../zokrates_proof_systems", default-features = false } +hex = "0.4.2" [dev-dependencies] zokrates_interpreter = { version = "0.1", path = "../zokrates_interpreter" } diff --git a/zokrates_libsnark/build.rs b/zokrates_libsnark/build.rs index 20242705..000d3c31 100644 --- a/zokrates_libsnark/build.rs +++ b/zokrates_libsnark/build.rs @@ -1,4 +1,5 @@ fn main() { + #[cfg(not(target_os = "macos"))] { use std::env; use std::path::PathBuf; diff --git a/zokrates_libsnark/src/gm17.rs b/zokrates_libsnark/src/gm17.rs index 83915cdb..3cc2497f 100644 --- a/zokrates_libsnark/src/gm17.rs +++ b/zokrates_libsnark/src/gm17.rs @@ -1,13 +1,16 @@ -use crate::proof_system::gm17::{ProofPoints, VerificationKey, GM17}; -use crate::proof_system::libsnark::ffi::{c_free, Buffer, ProofResult, SetupResult}; -use crate::proof_system::libsnark::{ - prepare_generate_proof, prepare_public_inputs, prepare_setup, serialization::*, Libsnark, +use crate::ffi::{c_free, Buffer, ProofResult, SetupResult}; +use crate::{prepare_generate_proof, prepare_public_inputs, prepare_setup, Libsnark}; +use zokrates_proof_systems::{ + Backend, G1Affine, G2Affine, NonUniversalBackend, Proof, SetupKeypair, }; -use crate::proof_system::Scheme; -use crate::proof_system::{Backend, G1Affine, G2Affine, NonUniversalBackend, Proof, SetupKeypair}; + +use crate::serialization::{read_g1, read_g2, write_g1, write_g2}; use std::io::{BufReader, BufWriter, Write}; use zokrates_ast::ir::{ProgIterator, Statement, Witness}; -use zokrates_field::{Bn128Field, Field}; +use zokrates_field::Bn128Field; +use zokrates_field::Field; +use zokrates_proof_systems::gm17::{ProofPoints, VerificationKey, GM17}; +use zokrates_proof_systems::Scheme; extern "C" { fn gm17_bn128_setup( diff --git a/zokrates_libsnark/src/lib.rs b/zokrates_libsnark/src/lib.rs index bc152dc4..3590d838 100644 --- a/zokrates_libsnark/src/lib.rs +++ b/zokrates_libsnark/src/lib.rs @@ -2,9 +2,9 @@ mod ffi; pub mod gm17; pub mod pghr13; -use crate::flat_absy::FlatVariable; use std::cmp::max; use std::collections::HashMap; +use zokrates_ast::common::Variable; use zokrates_ast::ir::{self, Statement}; use zokrates_field::Field; @@ -197,10 +197,7 @@ pub fn prepare_generate_proof( /// /// * `variables` - A mutual map that maps all existing variables to their index. /// * `var` - Variable to be searched for. -pub fn provide_variable_idx( - variables: &mut HashMap, - var: &FlatVariable, -) -> usize { +pub fn provide_variable_idx(variables: &mut HashMap, var: &Variable) -> usize { let index = variables.len(); *variables.entry(*var).or_insert(index) } @@ -215,14 +212,14 @@ pub fn provide_variable_idx( pub fn r1cs_program( prog: ir::Prog, ) -> ( - Vec, + Vec, usize, Vec>, Vec>, Vec>, ) { - let mut variables: HashMap = HashMap::new(); - provide_variable_idx(&mut variables, &FlatVariable::one()); + let mut variables: HashMap = HashMap::new(); + provide_variable_idx(&mut variables, &Variable::one()); for x in prog.arguments.iter().filter(|p| !p.private) { provide_variable_idx(&mut variables, &x.id); @@ -233,7 +230,7 @@ pub fn r1cs_program( let main_return_count = prog.returns().len(); for i in 0..main_return_count { - provide_variable_idx(&mut variables, &FlatVariable::public(i)); + provide_variable_idx(&mut variables, &Variable::public(i)); } // position where private part of witness starts @@ -287,18 +284,18 @@ pub fn r1cs_program( } // Convert map back into list ordered by index - let mut variables_list = vec![FlatVariable::new(0); variables.len()]; + let mut variables_list = vec![Variable::new(0); variables.len()]; for (k, v) in variables.drain() { - assert_eq!(variables_list[v], FlatVariable::new(0)); + assert_eq!(variables_list[v], Variable::new(0)); variables_list[v] = k; } (variables_list, private_inputs_offset, a, b, c) } pub mod serialization { - use crate::proof_system::{G1Affine, G2Affine}; use std::io::Read; use std::io::Write; + use zokrates_proof_systems::{G1Affine, G2Affine, G2AffineFq2}; #[inline] fn decode_hex(value: &String) -> Vec { @@ -324,7 +321,7 @@ pub mod serialization { let mut buffer = [0; 128]; reader.read_exact(&mut buffer).map_err(|_| ())?; - Ok(G2Affine( + Ok(G2Affine::Fq2(G2AffineFq2( ( encode_hex(&buffer[0..32].to_vec()), encode_hex(&buffer[32..64].to_vec()), @@ -333,7 +330,7 @@ pub mod serialization { encode_hex(&buffer[64..96].to_vec()), encode_hex(&buffer[96..128].to_vec()), ), - )) + ))) } pub fn write_g1(writer: &mut W, g1: &G1Affine) { @@ -342,9 +339,14 @@ pub mod serialization { } pub fn write_g2(writer: &mut W, g2: &G2Affine) { - writer.write(decode_hex(&(g2.0).0).as_ref()).unwrap(); - writer.write(decode_hex(&(g2.0).1).as_ref()).unwrap(); - writer.write(decode_hex(&(g2.1).0).as_ref()).unwrap(); - writer.write(decode_hex(&(g2.1).1).as_ref()).unwrap(); + match g2 { + G2Affine::Fq2(g2) => { + writer.write(decode_hex(&(g2.0).0).as_ref()).unwrap(); + writer.write(decode_hex(&(g2.0).1).as_ref()).unwrap(); + writer.write(decode_hex(&(g2.1).0).as_ref()).unwrap(); + writer.write(decode_hex(&(g2.1).1).as_ref()).unwrap(); + } + _ => unreachable!(), + } } } diff --git a/zokrates_libsnark/src/pghr13.rs b/zokrates_libsnark/src/pghr13.rs index f2d26528..b6e92f97 100644 --- a/zokrates_libsnark/src/pghr13.rs +++ b/zokrates_libsnark/src/pghr13.rs @@ -1,16 +1,16 @@ -use crate::proof_system::libsnark::ffi::{c_free, Buffer, ProofResult, SetupResult}; -use crate::proof_system::libsnark::{ - prepare_generate_proof, prepare_public_inputs, prepare_setup, Libsnark, +use crate::ffi::{c_free, Buffer, ProofResult, SetupResult}; +use crate::{prepare_generate_proof, prepare_public_inputs, prepare_setup, Libsnark}; +use zokrates_proof_systems::{ + Backend, G1Affine, G2Affine, NonUniversalBackend, Proof, SetupKeypair, }; -use crate::proof_system::{Backend, G1Affine, G2Affine, NonUniversalBackend, Proof, SetupKeypair}; -use crate::proof_system::libsnark::serialization::{read_g1, read_g2, write_g1, write_g2}; -use crate::proof_system::pghr13::{ProofPoints, VerificationKey, PGHR13}; -use crate::proof_system::Scheme; +use crate::serialization::{read_g1, read_g2, write_g1, write_g2}; use std::io::{BufReader, BufWriter, Write}; use zokrates_ast::ir::{ProgIterator, Statement, Witness}; use zokrates_field::Bn128Field; use zokrates_field::Field; +use zokrates_proof_systems::pghr13::{ProofPoints, VerificationKey, PGHR13}; +use zokrates_proof_systems::Scheme; extern "C" { fn pghr13_bn128_setup( @@ -222,23 +222,22 @@ impl NonUniversalBackend for Libsnark { } } -#[cfg(feature = "libsnark")] #[cfg(test)] +#[cfg(not(target_os = "macos"))] + mod tests { use super::*; - use crate::flat_absy::{FlatParameter, FlatVariable}; - use zokrates_ast::ir::{Interpreter, Prog, Statement}; + use zokrates_ast::flat::{Parameter, Variable}; + use zokrates_ast::ir::{Prog, Statement}; use zokrates_field::Bn128Field; + use zokrates_interpreter::Interpreter; #[test] fn verify() { let program: Prog = Prog { - arguments: vec![FlatParameter::private(FlatVariable::new(0))], + arguments: vec![Parameter::private(Variable::new(0))], return_count: 1, - statements: vec![Statement::constraint( - FlatVariable::new(0), - FlatVariable::public(0), - )], + statements: vec![Statement::constraint(Variable::new(0), Variable::public(0))], }; let keypair = >::setup(program.clone()); From 46e41687b5ebc4c9c92bb1483a08f8851ba39211 Mon Sep 17 00:00:00 2001 From: schaeff Date: Fri, 13 May 2022 14:29:14 +0200 Subject: [PATCH 04/19] fix features --- zokrates_cli/Cargo.toml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/zokrates_cli/Cargo.toml b/zokrates_cli/Cargo.toml index 1b0708aa..99979e98 100644 --- a/zokrates_cli/Cargo.toml +++ b/zokrates_cli/Cargo.toml @@ -7,9 +7,9 @@ edition = "2018" [features] default = ["bellman", "ark"] -libsnark = ["zokrates_libsnark"] -bellman = ["zokrates_bellman", "zokrates_core/bellman"] -ark = ["zokrates_ark", "zokrates_core/ark"] +libsnark = ["zokrates_libsnark", "zokrates_common/libsnark"] +bellman = ["zokrates_bellman", "zokrates_core/bellman", "zokrates_common/bellman"] +ark = ["zokrates_ark", "zokrates_core/ark", "zokrates_common/ark"] [dependencies] log = "0.4" @@ -25,7 +25,7 @@ zokrates_ast = { version = "0.1", path = "../zokrates_ast", default-features = f zokrates_interpreter = { version = "0.1", path = "../zokrates_interpreter", default-features = false } typed-arena = "1.4.1" zokrates_fs_resolver = { version = "0.5", path = "../zokrates_fs_resolver"} -zokrates_common = { version = "0.1", path = "../zokrates_common" } +zokrates_common = { version = "0.1", path = "../zokrates_common", default-features = false } serde_json = { version = "1.0", features = ["preserve_order"] } serde = { version = "1.0", features = ["derive"] } dirs = "3.0.1" From 25f48a0386dac0cffa9a3f2260cc124dd0adf6db Mon Sep 17 00:00:00 2001 From: schaeff Date: Fri, 13 May 2022 14:51:58 +0200 Subject: [PATCH 05/19] clippy libsnark, fix wasm test in circle config --- .circleci/config.yml | 4 +- zokrates_libsnark/build.rs | 4 +- zokrates_libsnark/src/ffi.rs | 2 +- zokrates_libsnark/src/lib.rs | 108 +++++++++++++++-------------------- 4 files changed, 51 insertions(+), 67 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 22d9f760..7afa23a6 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -68,8 +68,8 @@ jobs: - run: name: Test on firefox command: | - cd zokrates_core - wasm-pack test --firefox --headless -- --no-default-features --features "wasm ark" + cd zokrates_test + wasm-pack test --firefox --headless - save-sccache-cache integration_test: docker: diff --git a/zokrates_libsnark/build.rs b/zokrates_libsnark/build.rs index 000d3c31..bf7f2779 100644 --- a/zokrates_libsnark/build.rs +++ b/zokrates_libsnark/build.rs @@ -6,8 +6,8 @@ fn main() { use std::process::Command; // fetch libsnark source - const LIBSNARK_URL: &'static str = "https://github.com/scipr-lab/libsnark.git"; - const LIBSNARK_COMMIT: &'static str = "f7c87b88744ecfd008126d415494d9b34c4c1b20"; + const LIBSNARK_URL: &str = "https://github.com/scipr-lab/libsnark.git"; + const LIBSNARK_COMMIT: &str = "f7c87b88744ecfd008126d415494d9b34c4c1b20"; let out_path = PathBuf::from(env::var("OUT_DIR").unwrap()); let libsnark_source_path = &out_path.join("libsnark"); diff --git a/zokrates_libsnark/src/ffi.rs b/zokrates_libsnark/src/ffi.rs index 0cc03f94..8b2e9b16 100644 --- a/zokrates_libsnark/src/ffi.rs +++ b/zokrates_libsnark/src/ffi.rs @@ -20,7 +20,7 @@ extern "C" { } impl Buffer { - pub fn from_vec(v: &Vec) -> Buffer { + pub fn from_vec(v: &[u8]) -> Buffer { let data = v.as_ptr(); let len = v.len(); diff --git a/zokrates_libsnark/src/lib.rs b/zokrates_libsnark/src/lib.rs index 3590d838..bab5c560 100644 --- a/zokrates_libsnark/src/lib.rs +++ b/zokrates_libsnark/src/lib.rs @@ -11,7 +11,7 @@ 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] { +fn vec_as_u8_32_array(vec: &[u8]) -> [u8; 32] { assert!(vec.len() <= 32); let mut array = [0u8; 32]; for (index, byte) in vec.iter().enumerate() { @@ -32,6 +32,7 @@ pub fn prepare_public_inputs(public_inputs: Vec) -> (Vec<[u8; 32]>, } // proof-system-independent preparation for the setup phase +#[allow(clippy::type_complexity)] pub fn prepare_setup( program: ir::Prog, ) -> ( @@ -46,33 +47,33 @@ pub fn prepare_setup( usize, ) { // transform to R1CS - let (variables, public_variables_count, a, b, c) = r1cs_program(program); + let (variables, public_variables_count, constraints) = r1cs_program(program); let num_inputs = public_variables_count - 1; + let num_constraints = constraints.len(); - let num_constraints = a.len(); let num_variables = variables.len(); // Create single A,B,C vectors of tuples (constraint_number, variable_id, variable_value) let mut a_vec = vec![]; let mut b_vec = vec![]; let mut c_vec = vec![]; - for row in 0..num_constraints { - for &(idx, ref val) in &a[row] { + for (row, (a, b, c)) in constraints.iter().enumerate() { + for &(idx, ref val) in a { a_vec.push(( row as i32, idx as i32, vec_as_u8_32_array(&val.to_byte_vector()), )); } - for &(idx, ref val) in &b[row] { + for &(idx, ref val) in b { b_vec.push(( row as i32, idx as i32, vec_as_u8_32_array(&val.to_byte_vector()), )); } - for &(idx, ref val) in &c[row] { + for &(idx, ref val) in c { c_vec.push(( row as i32, idx as i32, @@ -97,10 +98,9 @@ pub fn prepare_setup( let mut a_arr: Vec = vec![0u8; STRUCT_SIZE * a_vec.len()]; let mut b_arr: Vec = vec![0u8; STRUCT_SIZE * b_vec.len()]; let mut c_arr: Vec = vec![0u8; STRUCT_SIZE * c_vec.len()]; - use std::mem::transmute; for (id, (row, idx, val)) in a_vec.iter().enumerate() { - let row_bytes: [u8; ROW_SIZE] = unsafe { transmute(row.to_le()) }; - let idx_bytes: [u8; IDX_SIZE] = unsafe { transmute(idx.to_le()) }; + let row_bytes: [u8; ROW_SIZE] = row.to_le().to_ne_bytes(); + let idx_bytes: [u8; IDX_SIZE] = idx.to_le().to_ne_bytes(); for x in 0..ROW_SIZE { a_arr[id * STRUCT_SIZE + x] = row_bytes[x]; @@ -113,8 +113,8 @@ pub fn prepare_setup( } } for (id, (row, idx, val)) in b_vec.iter().enumerate() { - let row_bytes: [u8; ROW_SIZE] = unsafe { transmute(row.to_le()) }; - let idx_bytes: [u8; IDX_SIZE] = unsafe { transmute(idx.to_le()) }; + let row_bytes: [u8; ROW_SIZE] = row.to_le().to_ne_bytes(); + let idx_bytes: [u8; IDX_SIZE] = idx.to_le().to_ne_bytes(); for x in 0..ROW_SIZE { b_arr[id * STRUCT_SIZE + x] = row_bytes[x]; @@ -127,8 +127,8 @@ pub fn prepare_setup( } } for (id, (row, idx, val)) in c_vec.iter().enumerate() { - let row_bytes: [u8; ROW_SIZE] = unsafe { transmute(row.to_le()) }; - let idx_bytes: [u8; IDX_SIZE] = unsafe { transmute(idx.to_le()) }; + let row_bytes: [u8; ROW_SIZE] = row.to_le().to_ne_bytes(); + let idx_bytes: [u8; IDX_SIZE] = idx.to_le().to_ne_bytes(); for x in 0..ROW_SIZE { c_arr[id * STRUCT_SIZE + x] = row_bytes[x]; @@ -160,12 +160,12 @@ pub fn prepare_generate_proof( witness: ir::Witness, ) -> (Vec<[u8; 32]>, usize, Vec<[u8; 32]>, usize) { // recover variable order from the program - let (variables, public_variables_count, _, _, _) = r1cs_program(program); + let (variables, public_variables_count, _) = r1cs_program(program); let witness: Vec<_> = variables.iter().map(|x| witness.0[x].clone()).collect(); // split witness into public and private inputs at offset - let mut public_inputs: Vec<_> = witness.clone(); + let mut public_inputs: Vec<_> = witness; let private_inputs: Vec<_> = public_inputs.split_off(public_variables_count); let public_inputs_length = public_inputs.len(); @@ -202,6 +202,9 @@ pub fn provide_variable_idx(variables: &mut HashMap, var: &Vari *variables.entry(*var).or_insert(index) } +type LinComb = Vec<(usize, T)>; +type Constraint = (LinComb, LinComb, LinComb); + /// Calculates one R1CS row representation of a program and returns (V, A, B, C) so that: /// * `V` contains all used variables and the index in the vector represents the used number in `A`, `B`, `C` /// * `* = ` for a witness `x` @@ -209,15 +212,7 @@ pub fn provide_variable_idx(variables: &mut HashMap, var: &Vari /// # Arguments /// /// * `prog` - The program the representation is calculated for. -pub fn r1cs_program( - prog: ir::Prog, -) -> ( - Vec, - usize, - Vec>, - Vec>, - Vec>, -) { +pub fn r1cs_program(prog: ir::Prog) -> (Vec, usize, Vec>) { let mut variables: HashMap = HashMap::new(); provide_variable_idx(&mut variables, &Variable::one()); @@ -242,45 +237,39 @@ pub fn r1cs_program( Statement::Directive(..) => None, }) { for (k, _) in &quad.left.0 { - provide_variable_idx(&mut variables, &k); + provide_variable_idx(&mut variables, k); } for (k, _) in &quad.right.0 { - provide_variable_idx(&mut variables, &k); + provide_variable_idx(&mut variables, k); } for (k, _) in &lin.0 { - provide_variable_idx(&mut variables, &k); + provide_variable_idx(&mut variables, k); } } - let mut a = vec![]; - let mut b = vec![]; - let mut c = vec![]; + let mut constraints = vec![]; // second pass to convert program to raw sparse vectors for (quad, lin) in prog.statements.into_iter().filter_map(|s| match s { Statement::Constraint(quad, lin, _) => Some((quad, lin)), Statement::Directive(..) => None, }) { - a.push( + constraints.push(( quad.left .0 .into_iter() - .map(|(k, v)| (variables.get(&k).unwrap().clone(), v)) + .map(|(k, v)| (*variables.get(&k).unwrap(), v)) .collect(), - ); - b.push( quad.right .0 .into_iter() - .map(|(k, v)| (variables.get(&k).unwrap().clone(), v)) + .map(|(k, v)| (*variables.get(&k).unwrap(), v)) .collect(), - ); - c.push( lin.0 .into_iter() - .map(|(k, v)| (variables.get(&k).unwrap().clone(), v)) + .map(|(k, v)| (*variables.get(&k).unwrap(), v)) .collect(), - ); + )); } // Convert map back into list ordered by index @@ -289,16 +278,17 @@ pub fn r1cs_program( assert_eq!(variables_list[v], Variable::new(0)); variables_list[v] = k; } - (variables_list, private_inputs_offset, a, b, c) + (variables_list, private_inputs_offset, constraints) } pub mod serialization { + use std::io::Error; use std::io::Read; use std::io::Write; use zokrates_proof_systems::{G1Affine, G2Affine, G2AffineFq2}; #[inline] - fn decode_hex(value: &String) -> Vec { + fn decode_hex(value: &str) -> Vec { hex::decode(value.strip_prefix("0x").unwrap()).unwrap() } @@ -307,44 +297,38 @@ pub mod serialization { format!("0x{}", hex::encode(data)) } - pub fn read_g1(reader: &mut R) -> Result { + pub fn read_g1(reader: &mut R) -> Result { let mut buffer = [0; 64]; - reader.read_exact(&mut buffer).map_err(|_| ())?; + reader.read_exact(&mut buffer)?; Ok(G1Affine( - encode_hex(&buffer[0..32].to_vec()), - encode_hex(&buffer[32..64].to_vec()), + encode_hex(&buffer[0..32]), + encode_hex(&buffer[32..64]), )) } - pub fn read_g2(reader: &mut R) -> Result { + pub fn read_g2(reader: &mut R) -> Result { let mut buffer = [0; 128]; - reader.read_exact(&mut buffer).map_err(|_| ())?; + reader.read_exact(&mut buffer)?; Ok(G2Affine::Fq2(G2AffineFq2( - ( - encode_hex(&buffer[0..32].to_vec()), - encode_hex(&buffer[32..64].to_vec()), - ), - ( - encode_hex(&buffer[64..96].to_vec()), - encode_hex(&buffer[96..128].to_vec()), - ), + (encode_hex(&buffer[0..32]), encode_hex(&buffer[32..64])), + (encode_hex(&buffer[64..96]), encode_hex(&buffer[96..128])), ))) } pub fn write_g1(writer: &mut W, g1: &G1Affine) { - writer.write(decode_hex(&g1.0).as_ref()).unwrap(); - writer.write(decode_hex(&g1.1).as_ref()).unwrap(); + writer.write_all(decode_hex(&g1.0).as_ref()).unwrap(); + writer.write_all(decode_hex(&g1.1).as_ref()).unwrap(); } pub fn write_g2(writer: &mut W, g2: &G2Affine) { match g2 { G2Affine::Fq2(g2) => { - writer.write(decode_hex(&(g2.0).0).as_ref()).unwrap(); - writer.write(decode_hex(&(g2.0).1).as_ref()).unwrap(); - writer.write(decode_hex(&(g2.1).0).as_ref()).unwrap(); - writer.write(decode_hex(&(g2.1).1).as_ref()).unwrap(); + writer.write_all(decode_hex(&(g2.0).0).as_ref()).unwrap(); + writer.write_all(decode_hex(&(g2.0).1).as_ref()).unwrap(); + writer.write_all(decode_hex(&(g2.1).0).as_ref()).unwrap(); + writer.write_all(decode_hex(&(g2.1).1).as_ref()).unwrap(); } _ => unreachable!(), } From 6d566481f1250413d87af85b36d27c21b9dc14e4 Mon Sep 17 00:00:00 2001 From: schaeff Date: Fri, 13 May 2022 16:01:29 +0200 Subject: [PATCH 06/19] fix zjs --- Cargo.lock | 35 ++++- Cargo.toml | 3 +- zokrates_abi/Cargo.toml | 5 + zokrates_ark/Cargo.toml | 2 +- zokrates_ast/Cargo.toml | 6 +- zokrates_bellman/Cargo.toml | 2 +- zokrates_core/Cargo.toml | 12 +- zokrates_embed/Cargo.toml | 26 ++-- zokrates_embed/src/lib.rs | 2 + zokrates_interpreter/Cargo.toml | 13 +- zokrates_js/Cargo.lock | 223 +++++++++--------------------- zokrates_js/Cargo.toml | 12 +- zokrates_js/src/lib.rs | 18 +-- zokrates_proof_systems/Cargo.toml | 2 +- 14 files changed, 162 insertions(+), 199 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 44ab891c..880ecc82 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1265,6 +1265,12 @@ version = "1.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eabb4a44450da02c90444cf74558da904edde8fb4e9035a9a6a4e15445af0bd7" +[[package]] +name = "hashbrown" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7afe4a420e3fe79967a00898cc1f4db7c8a49a9333a29f8a4bd76a253d5cd04" + [[package]] name = "hashbrown" version = "0.11.2" @@ -1350,12 +1356,12 @@ dependencies = [ [[package]] name = "indexmap" -version = "1.8.1" +version = "1.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f647032dfaa1f8b6dc29bd3edb7bbef4861b8b8007ebb118d6db284fd59f6ee" +checksum = "824845a0bf897a9042383849b02c1bc219c2383772efcd5c6f9766fa4b81aef3" dependencies = [ "autocfg", - "hashbrown 0.11.2", + "hashbrown 0.9.1", ] [[package]] @@ -2655,6 +2661,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "27370197c907c55e3f1a9fbe26f44e937fe6451368324e009cba39e139dc08ad" dependencies = [ "cfg-if 1.0.0", + "serde", + "serde_json", "wasm-bindgen-macro", ] @@ -3021,6 +3029,27 @@ dependencies = [ "zokrates_field", ] +[[package]] +name = "zokrates_js" +version = "1.0.42" +dependencies = [ + "console_error_panic_hook", + "indexmap", + "js-sys", + "serde", + "serde_json", + "typed-arena", + "wasm-bindgen", + "zokrates_abi", + "zokrates_ark", + "zokrates_ast", + "zokrates_common", + "zokrates_core", + "zokrates_field", + "zokrates_interpreter", + "zokrates_proof_systems", +] + [[package]] name = "zokrates_libsnark" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 8723ab9e..bc9e27b8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,6 +18,7 @@ members = [ "zokrates_bellman", "zokrates_libsnark", "zokrates_proof_systems", + "zokrates_js", ] -exclude = ["zokrates_js"] \ No newline at end of file +exclude = [] \ No newline at end of file diff --git a/zokrates_abi/Cargo.toml b/zokrates_abi/Cargo.toml index 1fccb51c..953aa53f 100644 --- a/zokrates_abi/Cargo.toml +++ b/zokrates_abi/Cargo.toml @@ -4,6 +4,11 @@ version = "0.1.7" authors = ["Thibaut Schaeffer "] edition = "2018" +[features] +default = ["ark", "bellman"] +ark = ["zokrates_ast/ark"] +bellman = ["zokrates_ast/bellman"] + [dependencies] zokrates_field = { version = "0.5", path = "../zokrates_field", default-features = false } zokrates_ast = { version = "0.1", path = "../zokrates_ast", default-features = false } diff --git a/zokrates_ark/Cargo.toml b/zokrates_ark/Cargo.toml index 6c538640..a90cbd26 100644 --- a/zokrates_ark/Cargo.toml +++ b/zokrates_ark/Cargo.toml @@ -29,6 +29,6 @@ rand_0_8 = { version = "0.8", package = "rand" } hex = "0.4.2" [dev-dependencies] -zokrates_interpreter = { version = "0.1", path = "../zokrates_interpreter" } +zokrates_interpreter = { version = "0.1", path = "../zokrates_interpreter", features = ["ark"] } diff --git a/zokrates_ast/Cargo.toml b/zokrates_ast/Cargo.toml index 8f27808f..bb22c519 100644 --- a/zokrates_ast/Cargo.toml +++ b/zokrates_ast/Cargo.toml @@ -5,8 +5,8 @@ edition = "2021" [features] default = ["bellman", "ark"] -bellman = ["zokrates_field/bellman", "pairing_ce"] -ark = ["ark-bls12-377"] +bellman = ["zokrates_field/bellman", "pairing_ce", "zokrates_embed/bellman"] +ark = ["ark-bls12-377", "zokrates_embed/ark"] [dependencies] zokrates_pest_ast = { version = "0.2.0", path = "../zokrates_pest_ast" } @@ -17,7 +17,7 @@ csv = "1" serde_cbor = "0.11.2" num-bigint = { version = "0.2", default-features = false } serde_json = { version = "1.0", features = ["preserve_order"] } -zokrates_embed = { version = "0.1.0", path = "../zokrates_embed" } +zokrates_embed = { version = "0.1.0", path = "../zokrates_embed", default-features = false } pairing_ce = { version = "^0.21", optional = true } ark-bls12-377 = { version = "^0.3.0", features = ["curve"], default-features = false, optional = true } diff --git a/zokrates_bellman/Cargo.toml b/zokrates_bellman/Cargo.toml index 9b9e483d..852b1fbe 100644 --- a/zokrates_bellman/Cargo.toml +++ b/zokrates_bellman/Cargo.toml @@ -20,7 +20,7 @@ getrandom = { version = "0.2", features = ["js", "wasm-bindgen"] } hex = "0.4.2" [dev-dependencies] -zokrates_interpreter = { version = "0.1", path = "../zokrates_interpreter" } +zokrates_interpreter = { version = "0.1", path = "../zokrates_interpreter", features = ["bellman"] } diff --git a/zokrates_core/Cargo.toml b/zokrates_core/Cargo.toml index 0ae9abfb..b9da5598 100644 --- a/zokrates_core/Cargo.toml +++ b/zokrates_core/Cargo.toml @@ -8,8 +8,8 @@ readme = "README.md" [features] default = ["ark", "bellman"] -ark = ["zokrates_ast/ark"] -bellman = ["zokrates_ast/bellman"] +ark = ["zokrates_ast/ark", "zokrates_embed/ark", "zokrates_common/ark", "zokrates_interpreter/ark"] +bellman = ["zokrates_ast/bellman", "zokrates_embed/bellman", "zokrates_common/bellman", "zokrates_interpreter/bellman"] libsnark = [] [dependencies] @@ -25,10 +25,10 @@ serde = { version = "1.0", features = ["derive"] } serde_json = { version = "1.0", features = ["preserve_order"] } zokrates_field = { version = "0.5.0", path = "../zokrates_field", default-features = false } zokrates_pest_ast = { version = "0.2.0", path = "../zokrates_pest_ast" } -zokrates_common = { version = "0.1", path = "../zokrates_common" } -zokrates_embed = { version = "0.1.0", path = "../zokrates_embed" } -zokrates_interpreter = { version = "0.1", path = "../zokrates_interpreter" } -zokrates_ast = { version = "0.1", path = "../zokrates_ast" } +zokrates_common = { version = "0.1", path = "../zokrates_common", default-features = false } +zokrates_embed = { version = "0.1.0", path = "../zokrates_embed", default-features = false } +zokrates_interpreter = { version = "0.1", path = "../zokrates_interpreter", default-features = false } +zokrates_ast = { version = "0.1", path = "../zokrates_ast", default-features = false } csv = "1" [dev-dependencies] diff --git a/zokrates_embed/Cargo.toml b/zokrates_embed/Cargo.toml index 34b15011..3e91069c 100644 --- a/zokrates_embed/Cargo.toml +++ b/zokrates_embed/Cargo.toml @@ -5,20 +5,22 @@ authors = ["schaeff "] edition = "2018" [features] -default = [] +default = ["ark", "bellman"] +ark = ["ark-bls12-377", "ark-bw6-761", "ark-gm17", "ark-relations", "ark-crypto-primitives", "ark-r1cs-std", "ark-std", "ark-ec", "ark-ff", "sapling-crypto_ce"] +bellman = ["bellman_ce"] wasm = ["bellman_ce/wasm", "sapling-crypto_ce/wasm"] multicore = ["bellman_ce/multicore", "sapling-crypto_ce/multicore"] [dependencies] zokrates_field = { version = "0.5.0", path = "../zokrates_field", default-features = false } -bellman_ce = { version = "^0.3", default-features = false } -sapling-crypto_ce = { version = "^0.1", default-features = false } -ark-bls12-377 = { version = "^0.3.0", features = ["curve", "r1cs"], default-features = false } -ark-bw6-761 = { version = "^0.3.0", default-features = false } -ark-gm17 = { version = "^0.3.0", default-features = false, features = ["r1cs"] } -ark-relations = { version = "^0.3.0", default-features = false } -ark-crypto-primitives = { version = "^0.3.0", default-features = false, features = ["r1cs"] } -ark-r1cs-std = { version = "^0.3.0", default-features = false } -ark-std = { version = "^0.3.0", default-features = false } -ark-ec = { version = "^0.3.0", default-features = false } -ark-ff = { version = "^0.3.0", default-features = false} \ No newline at end of file +bellman_ce = { version = "^0.3", default-features = false, optional = true } +sapling-crypto_ce = { version = "^0.1", default-features = false, optional = true } +ark-bls12-377 = { version = "^0.3.0", features = ["curve", "r1cs"], default-features = false, optional = true } +ark-bw6-761 = { version = "^0.3.0", default-features = false, optional = true } +ark-gm17 = { version = "^0.3.0", default-features = false, features = ["r1cs"], optional = true } +ark-relations = { version = "^0.3.0", default-features = false, optional = true } +ark-crypto-primitives = { version = "^0.3.0", default-features = false, features = ["r1cs"], optional = true } +ark-r1cs-std = { version = "^0.3.0", default-features = false, optional = true } +ark-std = { version = "^0.3.0", default-features = false, optional = true } +ark-ec = { version = "^0.3.0", default-features = false, optional = true } +ark-ff = { version = "^0.3.0", default-features = false, optional = true} \ No newline at end of file diff --git a/zokrates_embed/src/lib.rs b/zokrates_embed/src/lib.rs index b22972f3..2c873e2d 100644 --- a/zokrates_embed/src/lib.rs +++ b/zokrates_embed/src/lib.rs @@ -1,4 +1,6 @@ +#[cfg(feature = "ark")] pub mod ark; +#[cfg(feature = "bellman")] pub mod bellman; #[derive(Debug, Clone)] diff --git a/zokrates_interpreter/Cargo.toml b/zokrates_interpreter/Cargo.toml index 9f7b4bbd..c3e2262f 100644 --- a/zokrates_interpreter/Cargo.toml +++ b/zokrates_interpreter/Cargo.toml @@ -5,16 +5,21 @@ edition = "2021" [features] default = ["bellman", "ark"] -bellman = ["zokrates_field/bellman", "pairing_ce"] -ark = ["ark-bls12-377"] +bellman = ["zokrates_field/bellman", "pairing_ce", "zokrates_embed/bellman", "zokrates_ast/bellman"] +ark = ["ark-bls12-377", "zokrates_embed/ark", "zokrates_ast/ark"] [dependencies] zokrates_field = { version = "0.5", path = "../zokrates_field", default-features = false } zokrates_ast = { version = "0.1", path = "../zokrates_ast", default-features = false } +zokrates_embed = { version = "0.1.0", path = "../zokrates_embed", default-features = false } + num = { version = "0.1.36", default-features = false } num-bigint = { version = "0.2", default-features = false } -pairing_ce = { version = "^0.21", optional = true } + ark-bls12-377 = { version = "^0.3.0", features = ["curve"], default-features = false, optional = true } -zokrates_embed = { version = "0.1.0", path = "../zokrates_embed" } + +pairing_ce = { version = "^0.21", optional = true } + + serde = { version = "1.0", features = ["derive"] } diff --git a/zokrates_js/Cargo.lock b/zokrates_js/Cargo.lock index 7eea4220..d2623b7c 100644 --- a/zokrates_js/Cargo.lock +++ b/zokrates_js/Cargo.lock @@ -380,7 +380,6 @@ dependencies = [ "num_cpus", "pairing_ce", "rand 0.4.6", - "web-sys", ] [[package]] @@ -423,16 +422,6 @@ dependencies = [ "opaque-debug 0.3.0", ] -[[package]] -name = "blake2-rfc" -version = "0.2.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d6d530bdd2d52966a6d03b7a964add7ae1a288d25214066fd4b600f0f796400" -dependencies = [ - "arrayvec 0.4.12", - "constant_time_eq", -] - [[package]] name = "blake2-rfc_bellman_edition" version = "0.0.1" @@ -566,78 +555,6 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "245097e9a4535ee1e3e3931fcfcd55a796a44c643e8596ff6566d68f09b87bbc" -[[package]] -name = "crossbeam" -version = "0.7.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69323bff1fb41c635347b8ead484a5ca6c3f11914d784170b158d8449ab07f8e" -dependencies = [ - "cfg-if 0.1.10", - "crossbeam-channel", - "crossbeam-deque", - "crossbeam-epoch", - "crossbeam-queue", - "crossbeam-utils", -] - -[[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.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c20ff29ded3204c5106278a81a38f4b482636ed4fa1e6cfbeef193291beb29ed" -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 0.1.10", - "crossbeam-utils", - "lazy_static", - "maybe-uninit", - "memoffset", - "scopeguard", -] - -[[package]] -name = "crossbeam-queue" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "774ba60a54c213d409d5353bda12d49cd68d14e45036a285234c8d6f91f92570" -dependencies = [ - "cfg-if 0.1.10", - "crossbeam-utils", - "maybe-uninit", -] - -[[package]] -name = "crossbeam-utils" -version = "0.7.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3c7c73a2d1e9fc0886a08b93e98eb643461230d5f1925e4036204d5f2e261a8" -dependencies = [ - "autocfg", - "cfg-if 0.1.10", - "lazy_static", -] - [[package]] name = "crunchy" version = "0.2.2" @@ -967,10 +884,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7fcd999463524c52659517fe2cea98493cfe485d10565e7b0fb07dbba7ad2753" dependencies = [ "cfg-if 1.0.0", - "js-sys", "libc", "wasi", - "wasm-bindgen", ] [[package]] @@ -1120,27 +1035,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.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "308cc39be01b73d0d18f82a0e7b2a3df85245f84af96fdddc5d202d27e47b86a" -[[package]] -name = "memoffset" -version = "0.5.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "043175f069eda7b85febe4a74abbaeff828d9f8b448515d3151a14a3542811aa" -dependencies = [ - "autocfg", -] - [[package]] name = "miniz_oxide" version = "0.4.4" @@ -1366,22 +1266,6 @@ dependencies = [ "sha-1", ] -[[package]] -name = "phase2" -version = "0.2.2" -source = "git+https://github.com/Zokrates/phase2#971123223b9cb8c628e885120b120f1ddb413553" -dependencies = [ - "bellman_ce", - "blake2", - "blake2-rfc", - "byteorder", - "crossbeam", - "getrandom", - "num_cpus", - "pairing_ce", - "rand 0.4.6", -] - [[package]] name = "pin-project-lite" version = "0.2.7" @@ -1637,12 +1521,6 @@ dependencies = [ "tiny-keccak", ] -[[package]] -name = "scopeguard" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd" - [[package]] name = "semver" version = "0.11.0" @@ -2020,16 +1898,6 @@ version = "0.2.78" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0237232789cf037d5480773fe568aac745bfe2afbc11a863e97901780a6b47cc" -[[package]] -name = "web-sys" -version = "0.3.55" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38eb105f1c59d9eaa6b5cdc92b859d85b926e82cb2e0945cd0c9259faa6fe9fb" -dependencies = [ - "js-sys", - "wasm-bindgen", -] - [[package]] name = "winapi" version = "0.3.9" @@ -2084,24 +1952,21 @@ dependencies = [ [[package]] name = "zokrates_abi" -version = "0.1.6" +version = "0.1.7" dependencies = [ "serde", "serde_derive", "serde_json", - "zokrates_core", + "zokrates_ast", "zokrates_field", ] [[package]] -name = "zokrates_common" +name = "zokrates_ark" version = "0.1.0" - -[[package]] -name = "zokrates_core" -version = "0.6.11" dependencies = [ "ark-bls12-377", + "ark-bn254", "ark-bw6-761", "ark-crypto-primitives", "ark-ec", @@ -2113,31 +1978,54 @@ dependencies = [ "ark-poly-commit", "ark-relations", "ark-serialize", - "bellman_ce", + "digest 0.9.0", + "hex", + "rand 0.8.5", + "sha3 0.9.1", + "zokrates_ast", + "zokrates_field", + "zokrates_proof_systems", +] + +[[package]] +name = "zokrates_ast" +version = "0.1.0" +dependencies = [ + "ark-bls12-377", + "cfg-if 0.1.10", + "csv", + "num-bigint 0.2.6", + "serde", + "serde_cbor", + "serde_json", + "zokrates_embed", + "zokrates_field", + "zokrates_pest_ast", +] + +[[package]] +name = "zokrates_common" +version = "0.1.0" + +[[package]] +name = "zokrates_core" +version = "0.6.12" +dependencies = [ "cfg-if 0.1.10", "csv", - "digest 0.9.0", - "ethabi", - "getrandom", - "hex", "lazy_static", "log", "num", "num-bigint 0.2.6", - "phase2", - "primitive-types", - "rand 0.4.6", - "rand 0.8.5", "reduce", - "regex 0.2.11", "serde", - "serde_cbor", "serde_json", - "sha3 0.9.1", "typed-arena", + "zokrates_ast", "zokrates_common", "zokrates_embed", "zokrates_field", + "zokrates_interpreter", "zokrates_pest_ast", ] @@ -2154,7 +2042,6 @@ dependencies = [ "ark-r1cs-std", "ark-relations", "ark-std", - "bellman_ce", "sapling-crypto_ce", "zokrates_field", ] @@ -2170,7 +2057,6 @@ dependencies = [ "ark-ec", "ark-ff", "ark-serialize", - "bellman_ce", "bincode", "lazy_static", "num-bigint 0.2.6", @@ -2182,9 +2068,22 @@ dependencies = [ "sha2", ] +[[package]] +name = "zokrates_interpreter" +version = "0.1.0" +dependencies = [ + "ark-bls12-377", + "num", + "num-bigint 0.2.6", + "serde", + "zokrates_ast", + "zokrates_embed", + "zokrates_field", +] + [[package]] name = "zokrates_js" -version = "1.0.41" +version = "1.0.42" dependencies = [ "console_error_panic_hook", "indexmap", @@ -2194,6 +2093,7 @@ dependencies = [ "typed-arena", "wasm-bindgen", "zokrates_abi", + "zokrates_ark", "zokrates_common", "zokrates_core", "zokrates_field", @@ -2217,3 +2117,18 @@ dependencies = [ "pest-ast", "zokrates_parser", ] + +[[package]] +name = "zokrates_proof_systems" +version = "0.1.0" +dependencies = [ + "cfg-if 0.1.10", + "ethabi", + "hex", + "primitive-types", + "rand 0.4.6", + "regex 0.2.11", + "serde", + "zokrates_ast", + "zokrates_field", +] diff --git a/zokrates_js/Cargo.toml b/zokrates_js/Cargo.toml index 63269c1d..0e35e15c 100644 --- a/zokrates_js/Cargo.toml +++ b/zokrates_js/Cargo.toml @@ -13,10 +13,14 @@ serde = { version = "^1.0.59", features = ["derive"] } serde_json = { version = "1.0", features = ["preserve_order"] } wasm-bindgen = { version = "0.2.46", features = ["serde-serialize"] } typed-arena = "1.4.1" -zokrates_core = { path = "../zokrates_core", features = ["wasm", "ark"], default-features = false } -zokrates_common = { path = "../zokrates_common" } -zokrates_field = { path = "../zokrates_field" } -zokrates_abi = { path = "../zokrates_abi" } +zokrates_core = { path = "../zokrates_core", default-features = false, features = ["ark"] } +zokrates_ark = { path = "../zokrates_ark", default-features = false} +zokrates_common = { path = "../zokrates_common", default-features = false, features = ["ark"] } +zokrates_proof_systems = { path = "../zokrates_proof_systems", default-features = false } +zokrates_ast = { path = "../zokrates_ast", default-features = false, features = ["ark"] } +zokrates_interpreter = { path = "../zokrates_interpreter", default-features = false, features = ["ark"] } +zokrates_field = { path = "../zokrates_field", default-features = false } +zokrates_abi = { path = "../zokrates_abi", default-features = false, features = ["ark"] } console_error_panic_hook = "0.1.6" indexmap = "~1.6.2" # see https://github.com/rustwasm/wasm-bindgen/issues/2770#issuecomment-1041102532 \ No newline at end of file diff --git a/zokrates_js/src/lib.rs b/zokrates_js/src/lib.rs index 061609b8..984ea168 100644 --- a/zokrates_js/src/lib.rs +++ b/zokrates_js/src/lib.rs @@ -6,23 +6,23 @@ use std::path::PathBuf; use typed_arena::Arena; use wasm_bindgen::prelude::*; use zokrates_abi::{parse_strict, Decode, Encode, Inputs}; +use zokrates_ark::Ark; +use zokrates_ast::ir; +use zokrates_ast::ir::ProgEnum; +use zokrates_ast::typed::abi::Abi; +use zokrates_ast::typed::types::{ConcreteSignature, ConcreteType}; use zokrates_common::helpers::{CurveParameter, SchemeParameter}; use zokrates_common::Resolver; use zokrates_core::compile::{ compile as core_compile, CompilationArtifacts, CompileConfig, CompileError, }; use zokrates_core::imports::Error; -use zokrates_core::ir; -use zokrates_core::ir::ProgEnum; -use zokrates_core::proof_system::ark::Ark; -use zokrates_core::proof_system::groth16::G16; -use zokrates_core::proof_system::{ +use zokrates_field::{Bls12_377Field, Bls12_381Field, Bn128Field, Bw6_761Field, Field}; +use zokrates_proof_systems::groth16::G16; +use zokrates_proof_systems::{ Backend, Marlin, NonUniversalBackend, NonUniversalScheme, Proof, Scheme, SolidityCompatibleField, SolidityCompatibleScheme, UniversalBackend, UniversalScheme, GM17, }; -use zokrates_core::typed_absy::abi::Abi; -use zokrates_core::typed_absy::types::{ConcreteSignature, ConcreteType}; -use zokrates_field::{Bls12_377Field, Bls12_381Field, Bn128Field, Bw6_761Field, Field}; #[wasm_bindgen] pub struct CompilationResult { @@ -170,7 +170,7 @@ mod internal { (inputs, signature) }; - let interpreter = ir::Interpreter::default(); + let interpreter = zokrates_interpreter::Interpreter::default(); let witness = interpreter .execute(program, &inputs.encode()) diff --git a/zokrates_proof_systems/Cargo.toml b/zokrates_proof_systems/Cargo.toml index c323d612..11e0e160 100644 --- a/zokrates_proof_systems/Cargo.toml +++ b/zokrates_proof_systems/Cargo.toml @@ -4,7 +4,7 @@ version = "0.1.0" edition = "2021" [dependencies] -zokrates_ast = { version = "0.1", path = "../zokrates_ast" } +zokrates_ast = { version = "0.1", path = "../zokrates_ast", default-features = false } serde = { version = "1.0", features = ["derive"] } zokrates_field = { version = "0.5.0", path = "../zokrates_field", default-features = false } hex = "0.4.2" From 7e6b00c34c076e78cb4bad99e88e53ba5228d706 Mon Sep 17 00:00:00 2001 From: schaeff Date: Mon, 16 May 2022 17:18:13 +0200 Subject: [PATCH 07/19] add getrandom to fix js build --- Cargo.lock | 1 + zokrates_js/Cargo.lock | 2134 ----------------------------- zokrates_js/package-lock.json | 2 +- zokrates_proof_systems/Cargo.toml | 1 + 4 files changed, 3 insertions(+), 2135 deletions(-) delete mode 100644 zokrates_js/Cargo.lock diff --git a/Cargo.lock b/Cargo.lock index 880ecc82..2416d699 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3090,6 +3090,7 @@ version = "0.1.0" dependencies = [ "cfg-if 0.1.10", "ethabi", + "getrandom", "hex 0.4.3", "primitive-types", "rand 0.4.6", diff --git a/zokrates_js/Cargo.lock b/zokrates_js/Cargo.lock deleted file mode 100644 index d2623b7c..00000000 --- a/zokrates_js/Cargo.lock +++ /dev/null @@ -1,2134 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -version = 3 - -[[package]] -name = "addr2line" -version = "0.16.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e61f2b7f93d2c7d2b08263acaa4a363b3e276806c68af6134c44f523bf1aacd" -dependencies = [ - "gimli", -] - -[[package]] -name = "adler" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" - -[[package]] -name = "ahash" -version = "0.7.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fcb51a0695d8f838b1ee009b3fbf66bda078cd64590202a864a8f3e8c4315c47" -dependencies = [ - "getrandom", - "once_cell", - "version_check", -] - -[[package]] -name = "aho-corasick" -version = "0.6.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "81ce3d38065e618af2d7b77e10c5ad9a069859b4be3c2250f674af3840d9c8a5" -dependencies = [ - "memchr", -] - -[[package]] -name = "aho-corasick" -version = "0.7.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e37cfd5e7657ada45f742d6e99ca5788580b5c529dc78faf11ece6dc702656f" -dependencies = [ - "memchr", -] - -[[package]] -name = "ark-bls12-377" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc41c02c0d18a226947ee9ee023b1d957bdb6a68fc22ac296722935a9fef423c" -dependencies = [ - "ark-ec", - "ark-ff", - "ark-r1cs-std", - "ark-std", -] - -[[package]] -name = "ark-bls12-381" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65be532f9dd1e98ad0150b037276cde464c6f371059e6dd02c0222395761f6aa" -dependencies = [ - "ark-ec", - "ark-ff", - "ark-std", -] - -[[package]] -name = "ark-bn254" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea691771ebbb28aea556c044e2e5c5227398d840cee0c34d4d20fa8eb2689e8c" -dependencies = [ - "ark-ec", - "ark-ff", - "ark-std", -] - -[[package]] -name = "ark-bw6-761" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5abb465edcdee2bec3eff283e43f1c2414d1a4f6eaeb8e3de02aba3695d0520b" -dependencies = [ - "ark-bls12-377", - "ark-ec", - "ark-ff", - "ark-std", -] - -[[package]] -name = "ark-crypto-primitives" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff773c0ef8c655c98071d3026a63950798a66b2f45baef22d8334c1756f1bd18" -dependencies = [ - "ark-ec", - "ark-ff", - "ark-nonnative-field", - "ark-r1cs-std", - "ark-relations", - "ark-serialize", - "ark-snark", - "ark-std", - "blake2", - "derivative", - "digest 0.9.0", - "tracing", -] - -[[package]] -name = "ark-ec" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dea978406c4b1ca13c2db2373b05cc55429c3575b8b21f1b9ee859aa5b03dd42" -dependencies = [ - "ark-ff", - "ark-serialize", - "ark-std", - "derivative", - "num-traits 0.2.14", - "zeroize", -] - -[[package]] -name = "ark-ff" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b3235cc41ee7a12aaaf2c575a2ad7b46713a8a50bda2fc3b003a04845c05dd6" -dependencies = [ - "ark-ff-asm", - "ark-ff-macros", - "ark-serialize", - "ark-std", - "derivative", - "num-bigint 0.4.2", - "num-traits 0.2.14", - "paste", - "rustc_version", - "zeroize", -] - -[[package]] -name = "ark-ff-asm" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "db02d390bf6643fb404d3d22d31aee1c4bc4459600aef9113833d17e786c6e44" -dependencies = [ - "quote 1.0.10", - "syn 1.0.80", -] - -[[package]] -name = "ark-ff-macros" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "db2fd794a08ccb318058009eefdf15bcaaaaf6f8161eb3345f907222bac38b20" -dependencies = [ - "num-bigint 0.4.2", - "num-traits 0.2.14", - "quote 1.0.10", - "syn 1.0.80", -] - -[[package]] -name = "ark-gm17" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94713045868e99a606a89825ff5a901667ba707ad1966a32c7f3a4d4dbcc0e9a" -dependencies = [ - "ark-crypto-primitives", - "ark-ec", - "ark-ff", - "ark-poly", - "ark-r1cs-std", - "ark-relations", - "ark-serialize", - "ark-std", - "derivative", - "tracing", -] - -[[package]] -name = "ark-groth16" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38f8fff7468e947130b5caf9bdd27de8b913cf30e15104b4f0cd301726b3d897" -dependencies = [ - "ark-crypto-primitives", - "ark-ec", - "ark-ff", - "ark-poly", - "ark-relations", - "ark-serialize", - "ark-std", -] - -[[package]] -name = "ark-marlin" -version = "0.3.0" -source = "git+https://github.com/arkworks-rs/marlin?rev=63cfd82#63cfd82b10161fdf8da86b3401204c7370501a98" -dependencies = [ - "ark-ff", - "ark-poly", - "ark-poly-commit", - "ark-relations", - "ark-serialize", - "ark-std", - "derivative", - "digest 0.9.0", -] - -[[package]] -name = "ark-nonnative-field" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "440ad4569974910adbeb84422b7e622b79e08d27142afd113785b7fcfb446186" -dependencies = [ - "ark-ec", - "ark-ff", - "ark-r1cs-std", - "ark-relations", - "ark-std", - "derivative", - "num-bigint 0.4.2", - "num-integer", - "num-traits 0.2.14", - "tracing", -] - -[[package]] -name = "ark-poly" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b0f78f47537c2f15706db7e98fe64cc1711dbf9def81218194e17239e53e5aa" -dependencies = [ - "ark-ff", - "ark-serialize", - "ark-std", - "derivative", - "hashbrown 0.11.2", -] - -[[package]] -name = "ark-poly-commit" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a71ddfa72bad1446cab7bbecb6018dbbdc9abcbc3a0065483ae5186ad2a64dcd" -dependencies = [ - "ark-ec", - "ark-ff", - "ark-poly", - "ark-serialize", - "ark-std", - "derivative", - "digest 0.9.0", - "tracing", -] - -[[package]] -name = "ark-r1cs-std" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22e8fdacb1931f238a0d866ced1e916a49d36de832fd8b83dc916b718ae72893" -dependencies = [ - "ark-ec", - "ark-ff", - "ark-relations", - "ark-std", - "derivative", - "num-bigint 0.4.2", - "num-traits 0.2.14", - "tracing", -] - -[[package]] -name = "ark-relations" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4cba4c1c99792a6834bd97f7fd76578ec2cd58d2afc5139a17e1d1bec65b38f6" -dependencies = [ - "ark-ff", - "ark-std", - "tracing", -] - -[[package]] -name = "ark-serialize" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d6c2b318ee6e10f8c2853e73a83adc0ccb88995aa978d8a3408d492ab2ee671" -dependencies = [ - "ark-serialize-derive", - "ark-std", - "digest 0.9.0", -] - -[[package]] -name = "ark-serialize-derive" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8dd4e5f0bf8285d5ed538d27fab7411f3e297908fd93c62195de8bee3f199e82" -dependencies = [ - "proc-macro2 1.0.30", - "quote 1.0.10", - "syn 1.0.80", -] - -[[package]] -name = "ark-snark" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0dc3dff1a5f67a9c0b34df32b079752d8dd17f1e9d06253da0453db6c1b7cc8a" -dependencies = [ - "ark-ff", - "ark-relations", - "ark-std", -] - -[[package]] -name = "ark-std" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1df2c09229cbc5a028b1d70e00fdb2acee28b1055dfb5ca73eea49c5a25c4e7c" -dependencies = [ - "num-traits 0.2.14", - "rand 0.8.5", -] - -[[package]] -name = "arrayvec" -version = "0.4.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd9fd44efafa8690358b7408d253adf110036b88f55672a933f01d616ad9b1b9" -dependencies = [ - "nodrop", -] - -[[package]] -name = "arrayvec" -version = "0.7.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8da52d66c7071e2e3fa2a1e5c6d088fec47b593032b254f5e980de8ea54454d6" - -[[package]] -name = "autocfg" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cdb031dd78e28731d87d56cc8ffef4a8f36ca26c38fe2de700543e627f8a464a" - -[[package]] -name = "backtrace" -version = "0.3.62" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "091bcdf2da9950f96aa522681ce805e6857f6ca8df73833d35736ab2dc78e152" -dependencies = [ - "addr2line", - "cc", - "cfg-if 1.0.0", - "libc", - "miniz_oxide", - "object", - "rustc-demangle", -] - -[[package]] -name = "bellman_ce" -version = "0.3.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a5ca1343d8690bb4d62e0665116bd4f109e33a642f86908ed107d226a402b0ef" -dependencies = [ - "bit-vec", - "byteorder", - "cfg-if 0.1.10", - "futures", - "num_cpus", - "pairing_ce", - "rand 0.4.6", -] - -[[package]] -name = "bincode" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e103c8b299b28a9c6990458b7013dc4a8356a9b854c51b9883241f5866fac36e" -dependencies = [ - "byteorder", - "num-traits 0.1.43", - "serde", -] - -[[package]] -name = "bit-vec" -version = "0.6.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "349f9b6a179ed607305526ca489b34ad0a41aed5f7980fa90eb03160b69598fb" - -[[package]] -name = "bitvec" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1489fcb93a5bb47da0462ca93ad252ad6af2145cce58d10d46a83931ba9f016b" -dependencies = [ - "funty", - "radium", - "tap", - "wyz", -] - -[[package]] -name = "blake2" -version = "0.9.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0a4e37d16930f5459780f5621038b6382b9bb37c19016f39fb6b5808d831f174" -dependencies = [ - "crypto-mac", - "digest 0.9.0", - "opaque-debug 0.3.0", -] - -[[package]] -name = "blake2-rfc_bellman_edition" -version = "0.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fdc60350286c7c3db13b98e91dbe5c8b6830a6821bc20af5b0c310ce94d74915" -dependencies = [ - "arrayvec 0.4.12", - "byteorder", - "constant_time_eq", -] - -[[package]] -name = "block-buffer" -version = "0.7.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0940dc441f31689269e10ac70eb1002a3a1d3ad1390e030043662eb7fe4688b" -dependencies = [ - "block-padding 0.1.5", - "byte-tools", - "byteorder", - "generic-array 0.12.4", -] - -[[package]] -name = "block-buffer" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4152116fd6e9dadb291ae18fc1ec3575ed6d84c29642d97890f4b4a3417297e4" -dependencies = [ - "block-padding 0.2.1", - "generic-array 0.14.4", -] - -[[package]] -name = "block-buffer" -version = "0.10.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0bf7fe51849ea569fd452f37822f606a5cabb684dc918707a0193fd4664ff324" -dependencies = [ - "generic-array 0.14.4", -] - -[[package]] -name = "block-padding" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa79dedbb091f449f1f39e53edf88d5dbe95f895dae6135a8d7b881fb5af73f5" -dependencies = [ - "byte-tools", -] - -[[package]] -name = "block-padding" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d696c370c750c948ada61c69a0ee2cbbb9c50b1019ddb86d9317157a99c2cae" - -[[package]] -name = "bstr" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba3569f383e8f1598449f1a423e72e99569137b47740b1da11ef19af3d5c3223" -dependencies = [ - "lazy_static", - "memchr", - "regex-automata", - "serde", -] - -[[package]] -name = "bumpalo" -version = "3.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f1e260c3a9040a7c19a12468758f4c16f31a81a1fe087482be9570ec864bb6c" - -[[package]] -name = "byte-slice-cast" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87c5fdd0166095e1d463fc6cc01aa8ce547ad77a4e84d42eb6762b084e28067e" - -[[package]] -name = "byte-tools" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3b5ca7a04898ad4bcd41c90c5285445ff5b791899bb1b0abdd2a2aa791211d7" - -[[package]] -name = "byteorder" -version = "1.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "14c189c53d098945499cdfa7ecc63567cf3886b3332b312a5b4585d8d3a6a610" - -[[package]] -name = "bytes" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4872d67bab6358e59559027aa3b9157c53d9358c51423c17554809a8858e0f8" - -[[package]] -name = "cc" -version = "1.0.71" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "79c2681d6594606957bbb8631c4b90a7fcaaa72cdb714743a437b156d6a7eedd" - -[[package]] -name = "cfg-if" -version = "0.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" - -[[package]] -name = "cfg-if" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" - -[[package]] -name = "console_error_panic_hook" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a06aeb73f470f66dcdbf7223caeebb85984942f22f1adb2a088cf9668146bbbc" -dependencies = [ - "cfg-if 1.0.0", - "wasm-bindgen", -] - -[[package]] -name = "constant_time_eq" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "245097e9a4535ee1e3e3931fcfcd55a796a44c643e8596ff6566d68f09b87bbc" - -[[package]] -name = "crunchy" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a81dae078cea95a014a339291cec439d2f232ebe854a9d672b796c6afafa9b7" - -[[package]] -name = "crypto-common" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57952ca27b5e3606ff4dd79b0020231aaf9d6aa76dc05fd30137538c50bd3ce8" -dependencies = [ - "generic-array 0.14.4", - "typenum", -] - -[[package]] -name = "crypto-mac" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b584a330336237c1eecd3e94266efb216c56ed91225d634cb2991c5f3fd1aeab" -dependencies = [ - "generic-array 0.14.4", - "subtle", -] - -[[package]] -name = "csv" -version = "1.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22813a6dc45b335f9bade10bf7271dc477e81113e89eb251a0bc2a8a81c536e1" -dependencies = [ - "bstr", - "csv-core", - "itoa", - "ryu", - "serde", -] - -[[package]] -name = "csv-core" -version = "0.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b2466559f260f48ad25fe6317b3c8dac77b5bdb5763ac7d9d6103530663bc90" -dependencies = [ - "memchr", -] - -[[package]] -name = "derivative" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fcc3dd5e9e9c0b295d6e1e4d811fb6f157d5ffd784b8d202fc62eac8035a770b" -dependencies = [ - "proc-macro2 1.0.30", - "quote 1.0.10", - "syn 1.0.80", -] - -[[package]] -name = "digest" -version = "0.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3d0c8c8752312f9713efd397ff63acb9f85585afbf179282e720e7704954dd5" -dependencies = [ - "generic-array 0.12.4", -] - -[[package]] -name = "digest" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3dd60d1080a57a05ab032377049e0591415d2b31afd7028356dbf3cc6dcb066" -dependencies = [ - "generic-array 0.14.4", -] - -[[package]] -name = "digest" -version = "0.10.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2fb860ca6fafa5552fb6d0e816a69c8e49f0908bf524e30a90d97c85892d506" -dependencies = [ - "block-buffer 0.10.2", - "crypto-common", -] - -[[package]] -name = "either" -version = "1.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e78d4f1cc4ae33bbfc157ed5d5a5ef3bc29227303d595861deb238fcec4e9457" - -[[package]] -name = "ethabi" -version = "17.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b69517146dfab88e9238c00c724fd8e277951c3cc6f22b016d72f422a832213e" -dependencies = [ - "ethereum-types", - "hex", - "once_cell", - "regex 1.5.5", - "serde", - "serde_json", - "sha3 0.10.1", - "thiserror", - "uint", -] - -[[package]] -name = "ethbloom" -version = "0.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11da94e443c60508eb62cf256243a64da87304c2802ac2528847f79d750007ef" -dependencies = [ - "crunchy", - "fixed-hash", - "impl-rlp", - "impl-serde", - "tiny-keccak", -] - -[[package]] -name = "ethereum-types" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2827b94c556145446fcce834ca86b7abf0c39a805883fe20e72c5bfdb5a0dc6" -dependencies = [ - "ethbloom", - "fixed-hash", - "impl-rlp", - "impl-serde", - "primitive-types", - "uint", -] - -[[package]] -name = "failure" -version = "0.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d32e9bd16cc02eae7db7ef620b392808b89f6a5e16bb3497d159c6b92a0f4f86" -dependencies = [ - "backtrace", - "failure_derive", -] - -[[package]] -name = "failure_derive" -version = "0.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aa4da3c766cd7a0db8242e326e9e4e081edd567072893ed320008189715366a4" -dependencies = [ - "proc-macro2 1.0.30", - "quote 1.0.10", - "syn 1.0.80", - "synstructure", -] - -[[package]] -name = "fake-simd" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e88a8acf291dafb59c2d96e8f59828f3838bb1a70398823ade51a84de6a6deed" - -[[package]] -name = "ff_ce" -version = "0.10.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4592897f75fd1bd178e5ec12d9d7df3d1943464feda2cbce1e708a484e82c8f6" -dependencies = [ - "byteorder", - "ff_derive_ce", - "hex", - "rand 0.4.6", -] - -[[package]] -name = "ff_derive_ce" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50c052fa6d4c2f12305ec364bfb8ef884836f3f61ea015b202372ff996d1ac4b" -dependencies = [ - "num-bigint 0.2.6", - "num-integer", - "num-traits 0.2.14", - "proc-macro2 1.0.30", - "quote 1.0.10", - "syn 1.0.80", -] - -[[package]] -name = "fixed-hash" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cfcf0ed7fe52a17a03854ec54a9f76d6d84508d1c0e66bc1793301c73fc8493c" -dependencies = [ - "byteorder", - "rand 0.8.5", - "rustc-hex", - "static_assertions", -] - -[[package]] -name = "from-pest" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aba9389cedcba1fb3a2aa2ed00f584f2606bce8e0106614a17327a24513bc60f" -dependencies = [ - "pest", - "void", -] - -[[package]] -name = "fuchsia-cprng" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a06f77d526c1a601b7c4cdd98f54b5eaabffc14d5f2f0296febdc7f357c6d3ba" - -[[package]] -name = "funty" -version = "2.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c" - -[[package]] -name = "futures" -version = "0.3.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a12aa0eb539080d55c3f2d45a67c3b58b6b0773c1a3ca2dfec66d58c97fd66ca" -dependencies = [ - "futures-channel", - "futures-core", - "futures-executor", - "futures-io", - "futures-sink", - "futures-task", - "futures-util", -] - -[[package]] -name = "futures-channel" -version = "0.3.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5da6ba8c3bb3c165d3c7319fc1cc8304facf1fb8db99c5de877183c08a273888" -dependencies = [ - "futures-core", - "futures-sink", -] - -[[package]] -name = "futures-core" -version = "0.3.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "88d1c26957f23603395cd326b0ffe64124b818f4449552f960d815cfba83a53d" - -[[package]] -name = "futures-executor" -version = "0.3.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "45025be030969d763025784f7f355043dc6bc74093e4ecc5000ca4dc50d8745c" -dependencies = [ - "futures-core", - "futures-task", - "futures-util", -] - -[[package]] -name = "futures-io" -version = "0.3.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "522de2a0fe3e380f1bc577ba0474108faf3f6b18321dbf60b3b9c39a75073377" - -[[package]] -name = "futures-sink" -version = "0.3.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "36ea153c13024fe480590b3e3d4cad89a0cfacecc24577b68f86c6ced9c2bc11" - -[[package]] -name = "futures-task" -version = "0.3.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d3d00f4eddb73e498a54394f228cd55853bdf059259e8e7bc6e69d408892e99" - -[[package]] -name = "futures-util" -version = "0.3.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "36568465210a3a6ee45e1f165136d68671471a501e632e9a98d96872222b5481" -dependencies = [ - "autocfg", - "futures-channel", - "futures-core", - "futures-io", - "futures-sink", - "futures-task", - "memchr", - "pin-project-lite", - "pin-utils", - "slab", -] - -[[package]] -name = "generic-array" -version = "0.12.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ffdf9f34f1447443d37393cc6c2b8313aebddcd96906caf34e54c68d8e57d7bd" -dependencies = [ - "typenum", -] - -[[package]] -name = "generic-array" -version = "0.14.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "501466ecc8a30d1d3b7fc9229b122b2ce8ed6e9d9223f1138d4babb253e51817" -dependencies = [ - "typenum", - "version_check", -] - -[[package]] -name = "getrandom" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7fcd999463524c52659517fe2cea98493cfe485d10565e7b0fb07dbba7ad2753" -dependencies = [ - "cfg-if 1.0.0", - "libc", - "wasi", -] - -[[package]] -name = "gimli" -version = "0.25.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0a01e0497841a3b2db4f8afa483cce65f7e96a3498bd6c541734792aeac8fe7" - -[[package]] -name = "half" -version = "1.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eabb4a44450da02c90444cf74558da904edde8fb4e9035a9a6a4e15445af0bd7" - -[[package]] -name = "hashbrown" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7afe4a420e3fe79967a00898cc1f4db7c8a49a9333a29f8a4bd76a253d5cd04" - -[[package]] -name = "hashbrown" -version = "0.11.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab5ef0d4909ef3724cc8cce6ccc8572c5c817592e9285f5464f8e86f8bd3726e" -dependencies = [ - "ahash", -] - -[[package]] -name = "hermit-abi" -version = "0.1.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33" -dependencies = [ - "libc", -] - -[[package]] -name = "hex" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" - -[[package]] -name = "impl-codec" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba6a270039626615617f3f36d15fc827041df3b78c439da2cadfa47455a77f2f" -dependencies = [ - "parity-scale-codec", -] - -[[package]] -name = "impl-rlp" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f28220f89297a075ddc7245cd538076ee98b01f2a9c23a53a4f1105d5a322808" -dependencies = [ - "rlp", -] - -[[package]] -name = "impl-serde" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4551f042f3438e64dbd6226b20527fc84a6e1fe65688b58746a2f53623f25f5c" -dependencies = [ - "serde", -] - -[[package]] -name = "impl-trait-for-tuples" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11d7a9f6330b71fea57921c9b61c47ee6e84f72d394754eff6163ae67e7395eb" -dependencies = [ - "proc-macro2 1.0.30", - "quote 1.0.10", - "syn 1.0.80", -] - -[[package]] -name = "indexmap" -version = "1.6.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "824845a0bf897a9042383849b02c1bc219c2383772efcd5c6f9766fa4b81aef3" -dependencies = [ - "autocfg", - "hashbrown 0.9.1", -] - -[[package]] -name = "itertools" -version = "0.7.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d47946d458e94a1b7bcabbf6521ea7c037062c81f534615abcad76e84d4970d" -dependencies = [ - "either", -] - -[[package]] -name = "itoa" -version = "0.4.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b71991ff56294aa922b450139ee08b3bfc70982c6b2c7562771375cf73542dd4" - -[[package]] -name = "js-sys" -version = "0.3.55" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7cc9ffccd38c451a86bf13657df244e9c3f37493cce8e5e21e940963777acc84" -dependencies = [ - "wasm-bindgen", -] - -[[package]] -name = "keccak" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67c21572b4949434e4fc1e1978b99c5f77064153c59d998bf13ecd96fb5ecba7" - -[[package]] -name = "lazy_static" -version = "1.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" - -[[package]] -name = "libc" -version = "0.2.104" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b2f96d100e1cf1929e7719b7edb3b90ab5298072638fccd77be9ce942ecdfce" - -[[package]] -name = "log" -version = "0.4.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "51b9bbe6c47d51fc3e1a9b945965946b4c44142ab8792c50835a980d362c2710" -dependencies = [ - "cfg-if 1.0.0", -] - -[[package]] -name = "maplit" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e2e65a1a2e43cfcb47a895c4c8b10d1f4a61097f9f254f183aee60cad9c651d" - -[[package]] -name = "memchr" -version = "2.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "308cc39be01b73d0d18f82a0e7b2a3df85245f84af96fdddc5d202d27e47b86a" - -[[package]] -name = "miniz_oxide" -version = "0.4.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a92518e98c078586bc6c934028adcca4c92a53d6a958196de835170a01d84e4b" -dependencies = [ - "adler", - "autocfg", -] - -[[package]] -name = "nodrop" -version = "0.1.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72ef4a56884ca558e5ddb05a1d1e7e1bfd9a68d9ed024c21704cc98872dae1bb" - -[[package]] -name = "num" -version = "0.1.42" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4703ad64153382334aa8db57c637364c322d3372e097840c72000dabdcf6156e" -dependencies = [ - "num-integer", - "num-iter", - "num-traits 0.2.14", -] - -[[package]] -name = "num-bigint" -version = "0.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "090c7f9998ee0ff65aa5b723e4009f7b217707f1fb5ea551329cc4d6231fb304" -dependencies = [ - "autocfg", - "num-integer", - "num-traits 0.2.14", - "serde", -] - -[[package]] -name = "num-bigint" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "74e768dff5fb39a41b3bcd30bb25cf989706c90d028d1ad71971987aa309d535" -dependencies = [ - "autocfg", - "num-integer", - "num-traits 0.2.14", -] - -[[package]] -name = "num-integer" -version = "0.1.44" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2cc698a63b549a70bc047073d2949cce27cd1c7b0a4a862d08a8031bc2801db" -dependencies = [ - "autocfg", - "num-traits 0.2.14", -] - -[[package]] -name = "num-iter" -version = "0.1.42" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2021c8337a54d21aca0d59a92577a029af9431cb59b909b03252b9c164fad59" -dependencies = [ - "autocfg", - "num-integer", - "num-traits 0.2.14", -] - -[[package]] -name = "num-traits" -version = "0.1.43" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92e5113e9fd4cc14ded8e499429f396a20f98c772a47cc8622a736e1ec843c31" -dependencies = [ - "num-traits 0.2.14", -] - -[[package]] -name = "num-traits" -version = "0.2.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a64b1ec5cda2586e284722486d802acf1f7dbdc623e2bfc57e65ca1cd099290" -dependencies = [ - "autocfg", -] - -[[package]] -name = "num_cpus" -version = "1.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05499f3756671c15885fee9034446956fff3f243d6077b91e5767df161f766b3" -dependencies = [ - "hermit-abi", - "libc", -] - -[[package]] -name = "object" -version = "0.27.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c821014c18301591b89b843809ef953af9e3df0496c232d5c0611b0a52aac363" -dependencies = [ - "memchr", -] - -[[package]] -name = "once_cell" -version = "1.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87f3e037eac156d1775da914196f0f37741a274155e34a0b7e427c35d2a2ecb9" - -[[package]] -name = "opaque-debug" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2839e79665f131bdb5782e51f2c6c9599c133c6098982a54c794358bf432529c" - -[[package]] -name = "opaque-debug" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "624a8340c38c1b80fd549087862da4ba43e08858af025b236e509b6649fc13d5" - -[[package]] -name = "pairing_ce" -version = "0.21.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfc00d65b1d29e0a067a967fcea83d8db261c149f76a557ba73f0304f01cdfde" -dependencies = [ - "byteorder", - "ff_ce", - "rand 0.4.6", -] - -[[package]] -name = "parity-scale-codec" -version = "3.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8b44461635bbb1a0300f100a841e571e7d919c81c73075ef5d152ffdb521066" -dependencies = [ - "arrayvec 0.7.2", - "bitvec", - "byte-slice-cast", - "impl-trait-for-tuples", - "parity-scale-codec-derive", - "serde", -] - -[[package]] -name = "parity-scale-codec-derive" -version = "3.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c45ed1f39709f5a89338fab50e59816b2e8815f5bb58276e7ddf9afd495f73f8" -dependencies = [ - "proc-macro-crate", - "proc-macro2 1.0.30", - "quote 1.0.10", - "syn 1.0.80", -] - -[[package]] -name = "paste" -version = "1.0.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c520e05135d6e763148b6426a837e239041653ba7becd2e538c076c738025fc" - -[[package]] -name = "pest" -version = "2.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10f4872ae94d7b90ae48754df22fd42ad52ce740b8f370b03da4835417403e53" -dependencies = [ - "ucd-trie", -] - -[[package]] -name = "pest-ast" -version = "0.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3fbf404899169771dd6a32c84248b83cd67a26cc7cc957aac87661490e1227e4" -dependencies = [ - "itertools", - "proc-macro2 0.4.30", - "quote 0.6.13", - "single", - "syn 0.15.44", -] - -[[package]] -name = "pest_derive" -version = "2.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "833d1ae558dc601e9a60366421196a8d94bc0ac980476d0b67e1d0988d72b2d0" -dependencies = [ - "pest", - "pest_generator", -] - -[[package]] -name = "pest_generator" -version = "2.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "99b8db626e31e5b81787b9783425769681b347011cc59471e33ea46d2ea0cf55" -dependencies = [ - "pest", - "pest_meta", - "proc-macro2 1.0.30", - "quote 1.0.10", - "syn 1.0.80", -] - -[[package]] -name = "pest_meta" -version = "2.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "54be6e404f5317079812fc8f9f5279de376d8856929e21c184ecf6bbd692a11d" -dependencies = [ - "maplit", - "pest", - "sha-1", -] - -[[package]] -name = "pin-project-lite" -version = "0.2.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d31d11c69a6b52a174b42bdc0c30e5e11670f90788b2c471c31c1d17d449443" - -[[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.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3ca011bd0129ff4ae15cd04c4eef202cadf6c51c21e47aba319b4e0501db741" - -[[package]] -name = "primitive-types" -version = "0.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e28720988bff275df1f51b171e1b2a18c30d194c4d2b61defdacecd625a5d94a" -dependencies = [ - "fixed-hash", - "impl-codec", - "impl-rlp", - "impl-serde", - "uint", -] - -[[package]] -name = "proc-macro-crate" -version = "1.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e17d47ce914bf4de440332250b0edd23ce48c005f59fab39d3335866b114f11a" -dependencies = [ - "thiserror", - "toml", -] - -[[package]] -name = "proc-macro2" -version = "0.4.30" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf3d2011ab5c909338f7887f4fc896d35932e29146c12c8d01da6b22a80ba759" -dependencies = [ - "unicode-xid 0.1.0", -] - -[[package]] -name = "proc-macro2" -version = "1.0.30" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "edc3358ebc67bc8b7fa0c007f945b0b18226f78437d61bec735a9eb96b61ee70" -dependencies = [ - "unicode-xid 0.2.2", -] - -[[package]] -name = "quote" -version = "0.6.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ce23b6b870e8f94f81fb0a363d65d86675884b34a09043c81e5562f11c1f8e1" -dependencies = [ - "proc-macro2 0.4.30", -] - -[[package]] -name = "quote" -version = "1.0.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38bc8cc6a5f2e3655e0899c1b848643b2562f853f114bfec7be120678e3ace05" -dependencies = [ - "proc-macro2 1.0.30", -] - -[[package]] -name = "radium" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc33ff2d4973d518d823d61aa239014831e521c75da58e3df4840d3f47749d09" - -[[package]] -name = "rand" -version = "0.4.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "552840b97013b1a26992c11eac34bdd778e464601a4c2054b5f0bff7c6761293" -dependencies = [ - "fuchsia-cprng", - "libc", - "rand_core 0.3.1", - "rdrand", - "winapi", -] - -[[package]] -name = "rand" -version = "0.8.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" -dependencies = [ - "libc", - "rand_chacha", - "rand_core 0.6.3", -] - -[[package]] -name = "rand_chacha" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" -dependencies = [ - "ppv-lite86", - "rand_core 0.6.3", -] - -[[package]] -name = "rand_core" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a6fdeb83b075e8266dcc8762c22776f6877a63111121f5f8c7411e5be7eed4b" -dependencies = [ - "rand_core 0.4.2", -] - -[[package]] -name = "rand_core" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c33a3c44ca05fa6f1807d8e6743f3824e8509beca625669633be0acbdf509dc" - -[[package]] -name = "rand_core" -version = "0.6.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d34f1408f55294453790c48b2f1ebbb1c5b4b7563eb1f418bcfcfdbb06ebb4e7" -dependencies = [ - "getrandom", -] - -[[package]] -name = "rdrand" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "678054eb77286b51581ba43620cc911abf02758c91f93f479767aed0f90458b2" -dependencies = [ - "rand_core 0.3.1", -] - -[[package]] -name = "reduce" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "16d2dc47b68ac15ea328cd7ebe01d7d512ed29787f7d534ad2a3c341328b35d7" - -[[package]] -name = "regex" -version = "0.2.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9329abc99e39129fcceabd24cf5d85b4671ef7c29c50e972bc5afe32438ec384" -dependencies = [ - "aho-corasick 0.6.10", - "memchr", - "regex-syntax 0.5.6", - "thread_local", - "utf8-ranges", -] - -[[package]] -name = "regex" -version = "1.5.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a11647b6b25ff05a515cb92c365cec08801e83423a235b51e231e1808747286" -dependencies = [ - "aho-corasick 0.7.18", - "memchr", - "regex-syntax 0.6.25", -] - -[[package]] -name = "regex-automata" -version = "0.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c230d73fb8d8c1b9c0b3135c5142a8acee3a0558fb8db5cf1cb65f8d7862132" - -[[package]] -name = "regex-syntax" -version = "0.5.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d707a4fa2637f2dca2ef9fd02225ec7661fe01a53623c1e6515b6916511f7a7" -dependencies = [ - "ucd-util", -] - -[[package]] -name = "regex-syntax" -version = "0.6.25" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f497285884f3fcff424ffc933e56d7cbca511def0c9831a7f9b5f6153e3cc89b" - -[[package]] -name = "rlp" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "999508abb0ae792aabed2460c45b89106d97fe4adac593bdaef433c2605847b5" -dependencies = [ - "bytes", - "rustc-hex", -] - -[[package]] -name = "rustc-demangle" -version = "0.1.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ef03e0a2b150c7a90d01faf6254c9c48a41e95fb2a8c2ac1c6f0d2b9aefc342" - -[[package]] -name = "rustc-hex" -version = "2.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e75f6a532d0fd9f7f13144f392b6ad56a32696bfcd9c78f797f16bbb6f072d6" - -[[package]] -name = "rustc_version" -version = "0.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0dfe2087c51c460008730de8b57e6a320782fbfb312e1f4d520e6c6fae155ee" -dependencies = [ - "semver", -] - -[[package]] -name = "ryu" -version = "1.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "71d301d4193d031abdd79ff7e3dd721168a9572ef3fe51a1517aba235bd8f86e" - -[[package]] -name = "sapling-crypto_ce" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c4ff5309ec3e4bd800ad4ab3f71e9b76e9ea81c9f0eda6efa16008afbe440b3" -dependencies = [ - "bellman_ce", - "blake2-rfc_bellman_edition", - "byteorder", - "digest 0.8.1", - "rand 0.4.6", - "serde", - "serde_derive", - "sha2", - "tiny-keccak", -] - -[[package]] -name = "semver" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f301af10236f6df4160f7c3f04eec6dbc70ace82d23326abad5edee88801c6b6" -dependencies = [ - "semver-parser", -] - -[[package]] -name = "semver-parser" -version = "0.10.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "00b0bef5b7f9e0df16536d3961cfb6e84331c065b4066afb39768d0e319411f7" -dependencies = [ - "pest", -] - -[[package]] -name = "serde" -version = "1.0.130" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f12d06de37cf59146fbdecab66aa99f9fe4f78722e3607577a5375d66bd0c913" -dependencies = [ - "serde_derive", -] - -[[package]] -name = "serde_cbor" -version = "0.11.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2bef2ebfde456fb76bbcf9f59315333decc4fda0b2b44b420243c11e0f5ec1f5" -dependencies = [ - "half", - "serde", -] - -[[package]] -name = "serde_derive" -version = "1.0.130" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7bc1a1ab1961464eae040d96713baa5a724a8152c1222492465b54322ec508b" -dependencies = [ - "proc-macro2 1.0.30", - "quote 1.0.10", - "syn 1.0.80", -] - -[[package]] -name = "serde_json" -version = "1.0.68" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f690853975602e1bfe1ccbf50504d67174e3bcf340f23b5ea9992e0587a52d8" -dependencies = [ - "indexmap", - "itoa", - "ryu", - "serde", -] - -[[package]] -name = "sha-1" -version = "0.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f7d94d0bede923b3cea61f3f1ff57ff8cdfd77b400fb8f9998949e0cf04163df" -dependencies = [ - "block-buffer 0.7.3", - "digest 0.8.1", - "fake-simd", - "opaque-debug 0.2.3", -] - -[[package]] -name = "sha2" -version = "0.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a256f46ea78a0c0d9ff00077504903ac881a1dafdc20da66545699e7776b3e69" -dependencies = [ - "block-buffer 0.7.3", - "digest 0.8.1", - "fake-simd", - "opaque-debug 0.2.3", -] - -[[package]] -name = "sha3" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f81199417d4e5de3f04b1e871023acea7389672c4135918f05aa9cbf2f2fa809" -dependencies = [ - "block-buffer 0.9.0", - "digest 0.9.0", - "keccak", - "opaque-debug 0.3.0", -] - -[[package]] -name = "sha3" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "881bf8156c87b6301fc5ca6b27f11eeb2761224c7081e69b409d5a1951a70c86" -dependencies = [ - "digest 0.10.3", - "keccak", -] - -[[package]] -name = "single" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd5add732a1ab689845591a1b50339cf5310b563e08dc5813c65991f30369ea2" -dependencies = [ - "failure", -] - -[[package]] -name = "slab" -version = "0.4.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9def91fd1e018fe007022791f865d0ccc9b3a0d5001e01aabb8b40e46000afb5" - -[[package]] -name = "static_assertions" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" - -[[package]] -name = "subtle" -version = "2.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6bdef32e8150c2a081110b42772ffe7d7c9032b606bc226c8260fd97e0976601" - -[[package]] -name = "syn" -version = "0.15.44" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ca4b3b69a77cbe1ffc9e198781b7acb0c7365a883670e8f1c1bc66fba79a5c5" -dependencies = [ - "proc-macro2 0.4.30", - "quote 0.6.13", - "unicode-xid 0.1.0", -] - -[[package]] -name = "syn" -version = "1.0.80" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d010a1623fbd906d51d650a9916aaefc05ffa0e4053ff7fe601167f3e715d194" -dependencies = [ - "proc-macro2 1.0.30", - "quote 1.0.10", - "unicode-xid 0.2.2", -] - -[[package]] -name = "synstructure" -version = "0.12.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f36bdaa60a83aca3921b5259d5400cbf5e90fc51931376a9bd4a0eb79aa7210f" -dependencies = [ - "proc-macro2 1.0.30", - "quote 1.0.10", - "syn 1.0.80", - "unicode-xid 0.2.2", -] - -[[package]] -name = "tap" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" - -[[package]] -name = "thiserror" -version = "1.0.30" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "854babe52e4df1653706b98fcfc05843010039b406875930a70e4d9644e5c417" -dependencies = [ - "thiserror-impl", -] - -[[package]] -name = "thiserror-impl" -version = "1.0.30" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aa32fd3f627f367fe16f893e2597ae3c05020f8bba2666a4e6ea73d377e5714b" -dependencies = [ - "proc-macro2 1.0.30", - "quote 1.0.10", - "syn 1.0.80", -] - -[[package]] -name = "thread_local" -version = "0.3.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c6b53e329000edc2b34dbe8545fd20e55a333362d0a321909685a19bd28c3f1b" -dependencies = [ - "lazy_static", -] - -[[package]] -name = "tiny-keccak" -version = "2.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2c9d3793400a45f954c52e73d068316d76b6f4e36977e3fcebb13a2721e80237" -dependencies = [ - "crunchy", -] - -[[package]] -name = "toml" -version = "0.5.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a31142970826733df8241ef35dc040ef98c679ab14d7c3e54d827099b3acecaa" -dependencies = [ - "serde", -] - -[[package]] -name = "tracing" -version = "0.1.29" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "375a639232caf30edfc78e8d89b2d4c375515393e7af7e16f01cd96917fb2105" -dependencies = [ - "cfg-if 1.0.0", - "pin-project-lite", - "tracing-attributes", - "tracing-core", -] - -[[package]] -name = "tracing-attributes" -version = "0.1.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f4f480b8f81512e825f337ad51e94c1eb5d3bbdf2b363dcd01e2b19a9ffe3f8e" -dependencies = [ - "proc-macro2 1.0.30", - "quote 1.0.10", - "syn 1.0.80", -] - -[[package]] -name = "tracing-core" -version = "0.1.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f4ed65637b8390770814083d20756f87bfa2c21bf2f110babdc5438351746e4" - -[[package]] -name = "typed-arena" -version = "1.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9b2228007eba4120145f785df0f6c92ea538f5a3635a612ecf4e334c8c1446d" - -[[package]] -name = "typenum" -version = "1.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b63708a265f51345575b27fe43f9500ad611579e764c79edbc2037b1121959ec" - -[[package]] -name = "ucd-trie" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56dee185309b50d1f11bfedef0fe6d036842e3fb77413abef29f8f8d1c5d4c1c" - -[[package]] -name = "ucd-util" -version = "0.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c85f514e095d348c279b1e5cd76795082cf15bd59b93207832abe0b1d8fed236" - -[[package]] -name = "uint" -version = "0.9.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12f03af7ccf01dd611cc450a0d10dbc9b745770d096473e2faf0ca6e2d66d1e0" -dependencies = [ - "byteorder", - "crunchy", - "hex", - "static_assertions", -] - -[[package]] -name = "unicode-xid" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc72304796d0818e357ead4e000d19c9c174ab23dc11093ac919054d20a6a7fc" - -[[package]] -name = "unicode-xid" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ccb82d61f80a663efe1f787a51b16b5a51e3314d6ac365b08639f52387b33f3" - -[[package]] -name = "utf8-ranges" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4ae116fef2b7fea257ed6440d3cfcff7f190865f170cdad00bb6465bf18ecba" - -[[package]] -name = "version_check" -version = "0.9.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5fecdca9a5291cc2b8dcf7dc02453fee791a280f3743cb0905f8822ae463b3fe" - -[[package]] -name = "void" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6a02e4885ed3bc0f2de90ea6dd45ebcbb66dacffe03547fadbb0eeae2770887d" - -[[package]] -name = "wasi" -version = "0.10.2+wasi-snapshot-preview1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd6fbd9a79829dd1ad0cc20627bf1ed606756a7f77edff7b66b7064f9cb327c6" - -[[package]] -name = "wasm-bindgen" -version = "0.2.78" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "632f73e236b219150ea279196e54e610f5dbafa5d61786303d4da54f84e47fce" -dependencies = [ - "cfg-if 1.0.0", - "serde", - "serde_json", - "wasm-bindgen-macro", -] - -[[package]] -name = "wasm-bindgen-backend" -version = "0.2.78" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a317bf8f9fba2476b4b2c85ef4c4af8ff39c3c7f0cdfeed4f82c34a880aa837b" -dependencies = [ - "bumpalo", - "lazy_static", - "log", - "proc-macro2 1.0.30", - "quote 1.0.10", - "syn 1.0.80", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-macro" -version = "0.2.78" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d56146e7c495528bf6587663bea13a8eb588d39b36b679d83972e1a2dbbdacf9" -dependencies = [ - "quote 1.0.10", - "wasm-bindgen-macro-support", -] - -[[package]] -name = "wasm-bindgen-macro-support" -version = "0.2.78" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7803e0eea25835f8abdc585cd3021b3deb11543c6fe226dcd30b228857c5c5ab" -dependencies = [ - "proc-macro2 1.0.30", - "quote 1.0.10", - "syn 1.0.80", - "wasm-bindgen-backend", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-shared" -version = "0.2.78" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0237232789cf037d5480773fe568aac745bfe2afbc11a863e97901780a6b47cc" - -[[package]] -name = "winapi" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" -dependencies = [ - "winapi-i686-pc-windows-gnu", - "winapi-x86_64-pc-windows-gnu", -] - -[[package]] -name = "winapi-i686-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" - -[[package]] -name = "winapi-x86_64-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" - -[[package]] -name = "wyz" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "30b31594f29d27036c383b53b59ed3476874d518f0efb151b27a4c275141390e" -dependencies = [ - "tap", -] - -[[package]] -name = "zeroize" -version = "1.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf68b08513768deaa790264a7fac27a58cbf2705cfcdc9448362229217d7e970" -dependencies = [ - "zeroize_derive", -] - -[[package]] -name = "zeroize_derive" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bdff2024a851a322b08f179173ae2ba620445aef1e838f0c196820eade4ae0c7" -dependencies = [ - "proc-macro2 1.0.30", - "quote 1.0.10", - "syn 1.0.80", - "synstructure", -] - -[[package]] -name = "zokrates_abi" -version = "0.1.7" -dependencies = [ - "serde", - "serde_derive", - "serde_json", - "zokrates_ast", - "zokrates_field", -] - -[[package]] -name = "zokrates_ark" -version = "0.1.0" -dependencies = [ - "ark-bls12-377", - "ark-bn254", - "ark-bw6-761", - "ark-crypto-primitives", - "ark-ec", - "ark-ff", - "ark-gm17", - "ark-groth16", - "ark-marlin", - "ark-poly", - "ark-poly-commit", - "ark-relations", - "ark-serialize", - "digest 0.9.0", - "hex", - "rand 0.8.5", - "sha3 0.9.1", - "zokrates_ast", - "zokrates_field", - "zokrates_proof_systems", -] - -[[package]] -name = "zokrates_ast" -version = "0.1.0" -dependencies = [ - "ark-bls12-377", - "cfg-if 0.1.10", - "csv", - "num-bigint 0.2.6", - "serde", - "serde_cbor", - "serde_json", - "zokrates_embed", - "zokrates_field", - "zokrates_pest_ast", -] - -[[package]] -name = "zokrates_common" -version = "0.1.0" - -[[package]] -name = "zokrates_core" -version = "0.6.12" -dependencies = [ - "cfg-if 0.1.10", - "csv", - "lazy_static", - "log", - "num", - "num-bigint 0.2.6", - "reduce", - "serde", - "serde_json", - "typed-arena", - "zokrates_ast", - "zokrates_common", - "zokrates_embed", - "zokrates_field", - "zokrates_interpreter", - "zokrates_pest_ast", -] - -[[package]] -name = "zokrates_embed" -version = "0.1.7" -dependencies = [ - "ark-bls12-377", - "ark-bw6-761", - "ark-crypto-primitives", - "ark-ec", - "ark-ff", - "ark-gm17", - "ark-r1cs-std", - "ark-relations", - "ark-std", - "sapling-crypto_ce", - "zokrates_field", -] - -[[package]] -name = "zokrates_field" -version = "0.5.1" -dependencies = [ - "ark-bls12-377", - "ark-bls12-381", - "ark-bn254", - "ark-bw6-761", - "ark-ec", - "ark-ff", - "ark-serialize", - "bincode", - "lazy_static", - "num-bigint 0.2.6", - "num-integer", - "num-traits 0.2.14", - "serde", - "serde_derive", - "serde_json", - "sha2", -] - -[[package]] -name = "zokrates_interpreter" -version = "0.1.0" -dependencies = [ - "ark-bls12-377", - "num", - "num-bigint 0.2.6", - "serde", - "zokrates_ast", - "zokrates_embed", - "zokrates_field", -] - -[[package]] -name = "zokrates_js" -version = "1.0.42" -dependencies = [ - "console_error_panic_hook", - "indexmap", - "js-sys", - "serde", - "serde_json", - "typed-arena", - "wasm-bindgen", - "zokrates_abi", - "zokrates_ark", - "zokrates_common", - "zokrates_core", - "zokrates_field", -] - -[[package]] -name = "zokrates_parser" -version = "0.2.6" -dependencies = [ - "pest", - "pest_derive", -] - -[[package]] -name = "zokrates_pest_ast" -version = "0.2.6" -dependencies = [ - "from-pest", - "lazy_static", - "pest", - "pest-ast", - "zokrates_parser", -] - -[[package]] -name = "zokrates_proof_systems" -version = "0.1.0" -dependencies = [ - "cfg-if 0.1.10", - "ethabi", - "hex", - "primitive-types", - "rand 0.4.6", - "regex 0.2.11", - "serde", - "zokrates_ast", - "zokrates_field", -] diff --git a/zokrates_js/package-lock.json b/zokrates_js/package-lock.json index 3d15e0c8..0c975d22 100644 --- a/zokrates_js/package-lock.json +++ b/zokrates_js/package-lock.json @@ -1,6 +1,6 @@ { "name": "zokrates-js", - "version": "1.0.41", + "version": "1.0.42", "lockfileVersion": 1, "requires": true, "dependencies": { diff --git a/zokrates_proof_systems/Cargo.toml b/zokrates_proof_systems/Cargo.toml index 11e0e160..5fc9ee2c 100644 --- a/zokrates_proof_systems/Cargo.toml +++ b/zokrates_proof_systems/Cargo.toml @@ -13,3 +13,4 @@ cfg-if = "0.1" ethabi = "17.0.0" primitive-types = { version = "0.11", features = ["rlp"] } rand_0_4 = { version = "0.4", package = "rand" } +getrandom = { version = "0.2", features = ["js"] } \ No newline at end of file From 3f8c96f825e37e0d126c798d5c3c66ff4fc4f673 Mon Sep 17 00:00:00 2001 From: schaeff Date: Tue, 17 May 2022 11:13:41 +0200 Subject: [PATCH 08/19] fix cpp format, add changelog --- .circleci/config.yml | 2 +- changelogs/unreleased/1151-schaeff | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) create mode 100644 changelogs/unreleased/1151-schaeff diff --git a/.circleci/config.yml b/.circleci/config.yml index 7afa23a6..0cb80ecc 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -54,7 +54,7 @@ jobs: - checkout - run: name: Check cpp format (clang-format) - command: run-clang-format.py -r $(pwd)/zokrates_core/lib + command: run-clang-format.py -r $(pwd)/zokrates_libsnark/lib wasm_test: docker: - image: zokrates/env:latest diff --git a/changelogs/unreleased/1151-schaeff b/changelogs/unreleased/1151-schaeff new file mode 100644 index 00000000..ceac4401 --- /dev/null +++ b/changelogs/unreleased/1151-schaeff @@ -0,0 +1 @@ +Split codebase into smaller crates \ No newline at end of file From 4e9389ed4e7b9bcfa740beb4b4142e584eef2f29 Mon Sep 17 00:00:00 2001 From: schaeff Date: Tue, 17 May 2022 11:37:18 +0200 Subject: [PATCH 09/19] use large instance for wasm test --- .circleci/config.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.circleci/config.yml b/.circleci/config.yml index 0cb80ecc..71e8e43c 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -58,6 +58,7 @@ jobs: wasm_test: docker: - image: zokrates/env:latest + resource_class: large steps: - checkout - run: From 8a1e02de1f3db9acd546867cbc14a421b4104519 Mon Sep 17 00:00:00 2001 From: schaeff Date: Tue, 17 May 2022 11:43:07 +0200 Subject: [PATCH 10/19] remove libsnark feature from core, updates test script --- test.sh | 2 +- zokrates_core/Cargo.toml | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/test.sh b/test.sh index 1b42db0b..b5146888 100755 --- a/test.sh +++ b/test.sh @@ -5,7 +5,7 @@ set -e if [ -n "$WITH_LIBSNARK" ]; then # run specifically the libsnark tests inside zokrates_core - cargo test -j 4 --release --package zokrates_core --features="libsnark" libsnark -- --test-threads=1 + cargo test -j 4 --release --package zokrates_libsnark libsnark -- --test-threads=1 fi # run all tests without libsnark on diff --git a/zokrates_core/Cargo.toml b/zokrates_core/Cargo.toml index b9da5598..1f46cecf 100644 --- a/zokrates_core/Cargo.toml +++ b/zokrates_core/Cargo.toml @@ -10,7 +10,6 @@ readme = "README.md" default = ["ark", "bellman"] ark = ["zokrates_ast/ark", "zokrates_embed/ark", "zokrates_common/ark", "zokrates_interpreter/ark"] bellman = ["zokrates_ast/bellman", "zokrates_embed/bellman", "zokrates_common/bellman", "zokrates_interpreter/bellman"] -libsnark = [] [dependencies] log = "0.4" From 0c56a9eecae12ad32baecaa681a4af077f125b11 Mon Sep 17 00:00:00 2001 From: schaeff Date: Tue, 17 May 2022 12:05:38 +0200 Subject: [PATCH 11/19] fix gm17 test --- zokrates_libsnark/src/gm17.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zokrates_libsnark/src/gm17.rs b/zokrates_libsnark/src/gm17.rs index 3cc2497f..65304b3a 100644 --- a/zokrates_libsnark/src/gm17.rs +++ b/zokrates_libsnark/src/gm17.rs @@ -195,8 +195,8 @@ impl NonUniversalBackend for Libsnark { } } -#[cfg(feature = "libsnark")] #[cfg(test)] +#[cfg(not(target_os = "macos"))] mod tests { use super::*; use crate::flat_absy::{FlatParameter, FlatVariable}; From 1b69bc10de7c991c05d8c2f6c76937d104eabc81 Mon Sep 17 00:00:00 2001 From: schaeff Date: Tue, 17 May 2022 16:08:11 +0200 Subject: [PATCH 12/19] fix gm17 --- zokrates_libsnark/src/gm17.rs | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/zokrates_libsnark/src/gm17.rs b/zokrates_libsnark/src/gm17.rs index 65304b3a..77077419 100644 --- a/zokrates_libsnark/src/gm17.rs +++ b/zokrates_libsnark/src/gm17.rs @@ -199,19 +199,17 @@ impl NonUniversalBackend for Libsnark { #[cfg(not(target_os = "macos"))] mod tests { use super::*; - use crate::flat_absy::{FlatParameter, FlatVariable}; - use zokrates_ast::ir::{Interpreter, Prog, Statement}; + use zokrates_ast::flat::{Parameter, Variable}; + use zokrates_ast::ir::{Prog, Statement}; use zokrates_field::Bn128Field; + use zokrates_interpreter::Interpreter; #[test] fn verify() { let program: Prog = Prog { - arguments: vec![FlatParameter::private(FlatVariable::new(0))], + arguments: vec![FlatParameter::private(Variable::new(0))], return_count: 1, - statements: vec![Statement::constraint( - FlatVariable::new(0), - FlatVariable::public(0), - )], + statements: vec![Statement::constraint(Variable::new(0), Variable::public(0))], }; let keypair = >::setup(program.clone()); From c233b555b05dea0798bc32834c6407ad518c309f Mon Sep 17 00:00:00 2001 From: schaeff Date: Tue, 17 May 2022 16:47:34 +0200 Subject: [PATCH 13/19] fix gm17 --- zokrates_libsnark/src/gm17.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zokrates_libsnark/src/gm17.rs b/zokrates_libsnark/src/gm17.rs index 77077419..72aec3e0 100644 --- a/zokrates_libsnark/src/gm17.rs +++ b/zokrates_libsnark/src/gm17.rs @@ -207,7 +207,7 @@ mod tests { #[test] fn verify() { let program: Prog = Prog { - arguments: vec![FlatParameter::private(Variable::new(0))], + arguments: vec![Parameter::private(Variable::new(0))], return_count: 1, statements: vec![Statement::constraint(Variable::new(0), Variable::public(0))], }; From 82c7869a5f87b16b9e85438d1689723eadf7694a Mon Sep 17 00:00:00 2001 From: schaeff Date: Thu, 19 May 2022 12:38:42 +0200 Subject: [PATCH 14/19] drop support for libsnark --- .circleci/config.yml | 10 - Cargo.lock | 26 -- Cargo.toml | 1 - Dockerfile.env | 7 - build.sh | 6 +- build_release.sh | 6 +- dev.Dockerfile | 5 - integration_test.sh | 6 +- scripts/clang-format.sh | 8 - scripts/cov.sh | 17 - test.sh | 6 - zokrates_book/src/toolbox/proving_schemes.md | 7 - zokrates_cli/Cargo.toml | 2 - zokrates_cli/src/bin.rs | 12 +- zokrates_cli/src/cli_constants.rs | 22 +- zokrates_cli/src/ops/export_verifier.rs | 4 - zokrates_cli/src/ops/generate_proof.rs | 22 +- zokrates_cli/src/ops/mod.rs | 6 +- zokrates_cli/src/ops/setup.rs | 22 +- zokrates_cli/src/ops/universal_setup.rs | 2 +- zokrates_cli/src/ops/verify.rs | 12 +- zokrates_cli/tests/integration.rs | 8 - zokrates_common/Cargo.toml | 1 - zokrates_common/src/constants.rs | 1 - zokrates_common/src/helpers.rs | 8 - zokrates_libsnark/Cargo.toml | 18 - zokrates_libsnark/build.rs | 92 ----- zokrates_libsnark/lib/ffi.cpp | 6 - zokrates_libsnark/lib/ffi.hpp | 37 -- zokrates_libsnark/lib/gm17.cpp | 216 ------------ zokrates_libsnark/lib/gm17.hpp | 42 --- zokrates_libsnark/lib/pghr13.cpp | 240 ------------- zokrates_libsnark/lib/pghr13.hpp | 42 --- zokrates_libsnark/lib/util.tcc | 187 ----------- zokrates_libsnark/src/ffi.rs | 32 -- zokrates_libsnark/src/gm17.rs | 228 ------------- zokrates_libsnark/src/lib.rs | 336 ------------------- zokrates_libsnark/src/pghr13.rs | 256 -------------- 38 files changed, 19 insertions(+), 1940 deletions(-) delete mode 100755 scripts/clang-format.sh delete mode 100755 scripts/cov.sh delete mode 100644 zokrates_libsnark/Cargo.toml delete mode 100644 zokrates_libsnark/build.rs delete mode 100644 zokrates_libsnark/lib/ffi.cpp delete mode 100644 zokrates_libsnark/lib/ffi.hpp delete mode 100644 zokrates_libsnark/lib/gm17.cpp delete mode 100644 zokrates_libsnark/lib/gm17.hpp delete mode 100644 zokrates_libsnark/lib/pghr13.cpp delete mode 100644 zokrates_libsnark/lib/pghr13.hpp delete mode 100644 zokrates_libsnark/lib/util.tcc delete mode 100644 zokrates_libsnark/src/ffi.rs delete mode 100644 zokrates_libsnark/src/gm17.rs delete mode 100644 zokrates_libsnark/src/lib.rs delete mode 100644 zokrates_libsnark/src/pghr13.rs diff --git a/.circleci/config.yml b/.circleci/config.yml index 71e8e43c..4bc00ba7 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -47,14 +47,6 @@ jobs: no_output_timeout: 1h command: WITH_LIBSNARK=1 RUSTFLAGS="-D warnings" ./test.sh - save-sccache-cache - cpp_format: - docker: - - image: zokrates/env:latest - steps: - - checkout - - run: - name: Check cpp format (clang-format) - command: run-clang-format.py -r $(pwd)/zokrates_libsnark/lib wasm_test: docker: - image: zokrates/env:latest @@ -256,7 +248,6 @@ workflows: jobs: - build - test - - cpp_format - wasm_test - integration_test - zokrates_js_build @@ -315,7 +306,6 @@ workflows: requires: - build - test - - cpp_format - wasm_test - integration_test - zokrates_js_build diff --git a/Cargo.lock b/Cargo.lock index 2416d699..30ba2b68 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -654,9 +654,6 @@ name = "cc" version = "1.0.73" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2fff2a6927b3bb87f9595d67196a70493f627687a71d87a0d692242c33f58c11" -dependencies = [ - "jobserver", -] [[package]] name = "cfg-if" @@ -1394,15 +1391,6 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1aab8fc367588b89dcee83ab0fd66b72b50b72fa1904d7095045ace2b0c81c35" -[[package]] -name = "jobserver" -version = "0.1.24" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af25a77299a7f711a01975c35a6a424eb6862092cc2d6c72c4ed6cbc56dfc1fa" -dependencies = [ - "libc", -] - [[package]] name = "js-sys" version = "0.3.57" @@ -2924,7 +2912,6 @@ dependencies = [ "zokrates_field", "zokrates_fs_resolver", "zokrates_interpreter", - "zokrates_libsnark", "zokrates_proof_systems", "zokrates_solidity_test", ] @@ -3050,19 +3037,6 @@ dependencies = [ "zokrates_proof_systems", ] -[[package]] -name = "zokrates_libsnark" -version = "0.1.0" -dependencies = [ - "cc", - "cmake", - "hex 0.4.3", - "zokrates_ast", - "zokrates_field", - "zokrates_interpreter", - "zokrates_proof_systems", -] - [[package]] name = "zokrates_parser" version = "0.2.6" diff --git a/Cargo.toml b/Cargo.toml index bc9e27b8..b09fa804 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,7 +16,6 @@ members = [ "zokrates_interpreter", "zokrates_embed", "zokrates_bellman", - "zokrates_libsnark", "zokrates_proof_systems", "zokrates_js", ] diff --git a/Dockerfile.env b/Dockerfile.env index eee307da..1be291a8 100644 --- a/Dockerfile.env +++ b/Dockerfile.env @@ -15,14 +15,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ curl \ build-essential \ software-properties-common \ - cmake \ - gnupg \ - libboost-all-dev \ - libgmp3-dev \ - libprocps-dev \ - libssl-dev \ pkg-config \ - clang-format \ python-is-python3 \ python-markdown \ && add-apt-repository ppa:mozillateam/ppa \ diff --git a/build.sh b/build.sh index 64994644..c467308b 100755 --- a/build.sh +++ b/build.sh @@ -3,8 +3,4 @@ # Exit if any subcommand fails set -e -if [ -n "$WITH_LIBSNARK" ]; then - cargo build --package zokrates_cli --features="libsnark" -else - cargo build --package zokrates_cli -fi \ No newline at end of file +cargo build --package zokrates_cli \ No newline at end of file diff --git a/build_release.sh b/build_release.sh index d57d78c7..dbc89108 100755 --- a/build_release.sh +++ b/build_release.sh @@ -4,8 +4,4 @@ set -e export RUSTFLAGS="--remap-path-prefix=$PWD=" -if [ -n "$WITH_LIBSNARK" ]; then - cargo build --release --package zokrates_cli --features="libsnark" -else - cargo build --release --package zokrates_cli -fi +cargo build --release --package zokrates_cli diff --git a/dev.Dockerfile b/dev.Dockerfile index abffa9d0..267cf436 100644 --- a/dev.Dockerfile +++ b/dev.Dockerfile @@ -4,11 +4,6 @@ MAINTAINER JacobEberhardt , Thibaut Schaeffer Result<(), String> { universal_setup::subcommand(), #[cfg(feature = "bellman")] mpc::subcommand(), - #[cfg(any(feature = "bellman", feature = "ark", feature = "libsnark"))] + #[cfg(any(feature = "bellman", feature = "ark"))] setup::subcommand(), export_verifier::subcommand(), - #[cfg(any(feature = "bellman", feature = "ark", feature = "libsnark"))] + #[cfg(any(feature = "bellman", feature = "ark"))] generate_proof::subcommand(), generate_smtlib2::subcommand(), print_proof::subcommand(), - #[cfg(any(feature = "bellman", feature = "ark", feature = "libsnark"))] + #[cfg(any(feature = "bellman", feature = "ark"))] verify::subcommand()]) .get_matches(); @@ -69,14 +69,14 @@ fn cli() -> Result<(), String> { ("universal-setup", Some(sub_matches)) => universal_setup::exec(sub_matches), #[cfg(feature = "bellman")] ("mpc", Some(sub_matches)) => mpc::exec(sub_matches), - #[cfg(any(feature = "bellman", feature = "ark", feature = "libsnark"))] + #[cfg(any(feature = "bellman", feature = "ark"))] ("setup", Some(sub_matches)) => setup::exec(sub_matches), ("export-verifier", Some(sub_matches)) => export_verifier::exec(sub_matches), - #[cfg(any(feature = "bellman", feature = "ark", feature = "libsnark"))] + #[cfg(any(feature = "bellman", feature = "ark"))] ("generate-proof", Some(sub_matches)) => generate_proof::exec(sub_matches), ("generate-smtlib2", Some(sub_matches)) => generate_smtlib2::exec(sub_matches), ("print-proof", Some(sub_matches)) => print_proof::exec(sub_matches), - #[cfg(any(feature = "bellman", feature = "ark", feature = "libsnark"))] + #[cfg(any(feature = "bellman", feature = "ark"))] ("verify", Some(sub_matches)) => verify::exec(sub_matches), _ => unreachable!(), } diff --git a/zokrates_cli/src/cli_constants.rs b/zokrates_cli/src/cli_constants.rs index b9c372d1..31e5867f 100644 --- a/zokrates_cli/src/cli_constants.rs +++ b/zokrates_cli/src/cli_constants.rs @@ -21,20 +21,8 @@ lazy_static! { .unwrap(); } -#[cfg(any(feature = "bellman", feature = "ark", feature = "libsnark"))] -pub const BACKENDS: &[&str] = if cfg!(feature = "libsnark") { - if cfg!(feature = "ark") { - if cfg!(feature = "bellman") { - &[BELLMAN, LIBSNARK, ARK] - } else { - &[LIBSNARK, ARK] - } - } else if cfg!(feature = "bellman") { - &[BELLMAN, LIBSNARK] - } else { - &[LIBSNARK] - } -} else if cfg!(feature = "ark") { +#[cfg(any(feature = "bellman", feature = "ark"))] +pub const BACKENDS: &[&str] = if cfg!(feature = "ark") { if cfg!(feature = "bellman") { &[BELLMAN, ARK] } else { @@ -48,10 +36,6 @@ pub const BACKENDS: &[&str] = if cfg!(feature = "libsnark") { pub const CURVES: &[&str] = &[BN128, BLS12_381, BLS12_377, BW6_761]; -pub const SCHEMES: &[&str] = if cfg!(feature = "libsnark") { - &[G16, GM17, PGHR13, MARLIN] -} else { - &[G16, GM17, MARLIN] -}; +pub const SCHEMES: &[&str] = &[G16, GM17, MARLIN]; pub const UNIVERSAL_SCHEMES: &[&str] = &[MARLIN]; diff --git a/zokrates_cli/src/ops/export_verifier.rs b/zokrates_cli/src/ops/export_verifier.rs index e5086cde..c9624be2 100644 --- a/zokrates_cli/src/ops/export_verifier.rs +++ b/zokrates_cli/src/ops/export_verifier.rs @@ -69,10 +69,6 @@ pub fn exec(sub_matches: &ArgMatches) -> Result<(), String> { (CurveParameter::Bn128, SchemeParameter::GM17) => { cli_export_verifier::(sub_matches) } - #[cfg(feature = "libsnark")] - (CurveParameter::Bn128, SchemeParameter::PGHR13) => { - cli_export_verifier::(sub_matches) - } (CurveParameter::Bn128, SchemeParameter::MARLIN) => { cli_export_verifier::(sub_matches) } diff --git a/zokrates_cli/src/ops/generate_proof.rs b/zokrates_cli/src/ops/generate_proof.rs index 7b7e237f..7c47c042 100644 --- a/zokrates_cli/src/ops/generate_proof.rs +++ b/zokrates_cli/src/ops/generate_proof.rs @@ -12,9 +12,7 @@ use zokrates_bellman::Bellman; use zokrates_common::constants; use zokrates_common::helpers::*; use zokrates_field::Field; -#[cfg(feature = "libsnark")] -use zokrates_libsnark::Libsnark; -#[cfg(any(feature = "bellman", feature = "ark", feature = "libsnark"))] +#[cfg(any(feature = "bellman", feature = "ark"))] use zokrates_proof_systems::*; pub fn subcommand() -> App<'static, 'static> { @@ -131,24 +129,6 @@ pub fn exec(sub_matches: &ArgMatches) -> Result<(), String> { } ProgEnum::Bw6_761Program(p) => cli_generate_proof::<_, _, Marlin, Ark>(p, sub_matches), }, - #[cfg(feature = "libsnark")] - Parameters(BackendParameter::Libsnark, CurveParameter::Bn128, SchemeParameter::GM17) => { - match prog { - ProgEnum::Bn128Program(p) => { - cli_generate_proof::<_, _, GM17, Libsnark>(p, sub_matches) - } - _ => unreachable!(), - } - } - #[cfg(feature = "libsnark")] - Parameters(BackendParameter::Libsnark, CurveParameter::Bn128, SchemeParameter::PGHR13) => { - match prog { - ProgEnum::Bn128Program(p) => { - cli_generate_proof::<_, _, PGHR13, Libsnark>(p, sub_matches) - } - _ => unreachable!(), - } - } _ => unreachable!(), } } diff --git a/zokrates_cli/src/ops/mod.rs b/zokrates_cli/src/ops/mod.rs index 2a25ee69..e82dd506 100644 --- a/zokrates_cli/src/ops/mod.rs +++ b/zokrates_cli/src/ops/mod.rs @@ -2,16 +2,16 @@ pub mod check; pub mod compile; pub mod compute_witness; pub mod export_verifier; -#[cfg(any(feature = "bellman", feature = "ark", feature = "libsnark"))] +#[cfg(any(feature = "bellman", feature = "ark"))] pub mod generate_proof; pub mod generate_smtlib2; pub mod inspect; #[cfg(feature = "bellman")] pub mod mpc; pub mod print_proof; -#[cfg(any(feature = "bellman", feature = "ark", feature = "libsnark"))] +#[cfg(any(feature = "bellman", feature = "ark"))] pub mod setup; #[cfg(feature = "ark")] pub mod universal_setup; -#[cfg(any(feature = "bellman", feature = "ark", feature = "libsnark"))] +#[cfg(any(feature = "bellman", feature = "ark"))] pub mod verify; diff --git a/zokrates_cli/src/ops/setup.rs b/zokrates_cli/src/ops/setup.rs index 419454a5..d84f59ee 100644 --- a/zokrates_cli/src/ops/setup.rs +++ b/zokrates_cli/src/ops/setup.rs @@ -12,9 +12,7 @@ use zokrates_bellman::Bellman; use zokrates_common::constants; use zokrates_common::helpers::*; use zokrates_field::Field; -#[cfg(feature = "libsnark")] -use zokrates_libsnark::Libsnark; -#[cfg(any(feature = "bellman", feature = "ark", feature = "libsnark"))] +#[cfg(any(feature = "bellman", feature = "ark"))] use zokrates_proof_systems::*; pub fn subcommand() -> App<'static, 'static> { @@ -164,24 +162,6 @@ pub fn exec(sub_matches: &ArgMatches) -> Result<(), String> { } } } - #[cfg(feature = "libsnark")] - Parameters(BackendParameter::Libsnark, CurveParameter::Bn128, SchemeParameter::GM17) => { - match prog { - ProgEnum::Bn128Program(p) => { - cli_setup_non_universal::<_, _, GM17, Libsnark>(p, sub_matches) - } - _ => unreachable!(), - } - } - #[cfg(feature = "libsnark")] - Parameters(BackendParameter::Libsnark, CurveParameter::Bn128, SchemeParameter::PGHR13) => { - match prog { - ProgEnum::Bn128Program(p) => { - cli_setup_non_universal::<_, _, PGHR13, Libsnark>(p, sub_matches) - } - _ => unreachable!(), - } - } _ => unreachable!(), } } diff --git a/zokrates_cli/src/ops/universal_setup.rs b/zokrates_cli/src/ops/universal_setup.rs index 8d673b28..98bc8892 100644 --- a/zokrates_cli/src/ops/universal_setup.rs +++ b/zokrates_cli/src/ops/universal_setup.rs @@ -9,7 +9,7 @@ use zokrates_ark::Ark; use zokrates_common::constants; use zokrates_common::helpers::*; use zokrates_field::{Bls12_377Field, Bls12_381Field, Bn128Field, Bw6_761Field, Field}; -#[cfg(any(feature = "bellman", feature = "ark", feature = "libsnark"))] +#[cfg(any(feature = "bellman", feature = "ark"))] use zokrates_proof_systems::*; pub fn subcommand() -> App<'static, 'static> { diff --git a/zokrates_cli/src/ops/verify.rs b/zokrates_cli/src/ops/verify.rs index ba7d4bee..b83e4831 100644 --- a/zokrates_cli/src/ops/verify.rs +++ b/zokrates_cli/src/ops/verify.rs @@ -11,9 +11,7 @@ use zokrates_bellman::Bellman; use zokrates_common::constants; use zokrates_common::helpers::*; use zokrates_field::{Bls12_377Field, Bls12_381Field, Bn128Field, Bw6_761Field, Field}; -#[cfg(feature = "libsnark")] -use zokrates_libsnark::Libsnark; -#[cfg(any(feature = "bellman", feature = "ark", feature = "libsnark"))] +#[cfg(any(feature = "bellman", feature = "ark"))] use zokrates_proof_systems::*; pub fn subcommand() -> App<'static, 'static> { @@ -126,14 +124,6 @@ pub fn exec(sub_matches: &ArgMatches) -> Result<(), String> { Parameters(BackendParameter::Ark, CurveParameter::Bw6_761, SchemeParameter::MARLIN) => { cli_verify::(sub_matches) } - #[cfg(feature = "libsnark")] - Parameters(BackendParameter::Libsnark, CurveParameter::Bn128, SchemeParameter::GM17) => { - cli_verify::(sub_matches) - } - #[cfg(feature = "libsnark")] - Parameters(BackendParameter::Libsnark, CurveParameter::Bn128, SchemeParameter::PGHR13) => { - cli_verify::(sub_matches) - } _ => unreachable!(), } } diff --git a/zokrates_cli/tests/integration.rs b/zokrates_cli/tests/integration.rs index d51e5f3e..9388823f 100644 --- a/zokrates_cli/tests/integration.rs +++ b/zokrates_cli/tests/integration.rs @@ -233,14 +233,6 @@ mod integration { ); } - #[cfg(feature = "libsnark")] - let backends = map! { - "bellman" => vec!["g16"], - "libsnark" => vec!["pghr13"], - "ark" => vec!["g16", "gm17", "marlin"] - }; - - #[cfg(not(feature = "libsnark"))] let backends = map! { "bellman" => vec!["g16"], "ark" => vec!["g16", "gm17", "marlin"] diff --git a/zokrates_common/Cargo.toml b/zokrates_common/Cargo.toml index bb36776b..f9c688b0 100644 --- a/zokrates_common/Cargo.toml +++ b/zokrates_common/Cargo.toml @@ -10,7 +10,6 @@ edition = "2018" default = ["bellman", "ark"] bellman = [] ark = [] -libsnark = [] [dependencies] \ No newline at end of file diff --git a/zokrates_common/src/constants.rs b/zokrates_common/src/constants.rs index 3279ba56..0ef486b0 100644 --- a/zokrates_common/src/constants.rs +++ b/zokrates_common/src/constants.rs @@ -1,6 +1,5 @@ pub const BELLMAN: &str = "bellman"; pub const ARK: &str = "ark"; -pub const LIBSNARK: &str = "libsnark"; pub const BN128: &str = "bn128"; pub const BLS12_381: &str = "bls12_381"; diff --git a/zokrates_common/src/helpers.rs b/zokrates_common/src/helpers.rs index bb29f548..785b460c 100644 --- a/zokrates_common/src/helpers.rs +++ b/zokrates_common/src/helpers.rs @@ -15,8 +15,6 @@ pub enum BackendParameter { Bellman, #[cfg(feature = "ark")] Ark, - #[cfg(feature = "libsnark")] - Libsnark, } #[allow(clippy::upper_case_acronyms)] @@ -51,8 +49,6 @@ impl TryFrom<&str> for BackendParameter { BELLMAN => Ok(BackendParameter::Bellman), #[cfg(feature = "ark")] ARK => Ok(BackendParameter::Ark), - #[cfg(feature = "libsnark")] - LIBSNARK => Ok(BackendParameter::Libsnark), _ => Err(format!("Unknown backend {}", s)), } } @@ -116,10 +112,6 @@ impl TryFrom<(&str, &str, &str)> for Parameters { (BackendParameter::Ark, CurveParameter::Bls12_377, SchemeParameter::MARLIN) => Ok(()), #[cfg(feature = "ark")] (BackendParameter::Ark, CurveParameter::Bw6_761, SchemeParameter::MARLIN) => Ok(()), - #[cfg(feature = "libsnark")] - (BackendParameter::Libsnark, CurveParameter::Bn128, SchemeParameter::GM17) => Ok(()), - #[cfg(feature = "libsnark")] - (BackendParameter::Libsnark, CurveParameter::Bn128, SchemeParameter::PGHR13) => Ok(()), _ => Err(format!( "Unsupported combination of parameters (backend: {}, curve: {}, proving scheme: {})", s.0, s.1, s.2 diff --git a/zokrates_libsnark/Cargo.toml b/zokrates_libsnark/Cargo.toml deleted file mode 100644 index d8ae7bb7..00000000 --- a/zokrates_libsnark/Cargo.toml +++ /dev/null @@ -1,18 +0,0 @@ -[package] -name = "zokrates_libsnark" -version = "0.1.0" -edition = "2021" -build = "build.rs" - -[dependencies] -zokrates_field = { version = "0.5", path = "../zokrates_field", default-features = false } -zokrates_ast = { version = "0.1", path = "../zokrates_ast", default-features = false } -zokrates_proof_systems = { version = "0.1", path = "../zokrates_proof_systems", default-features = false } -hex = "0.4.2" - -[dev-dependencies] -zokrates_interpreter = { version = "0.1", path = "../zokrates_interpreter" } - -[build-dependencies] -cc = { version = "1.0", features = ["parallel"] } -cmake = { version = "=0.1.45" } \ No newline at end of file diff --git a/zokrates_libsnark/build.rs b/zokrates_libsnark/build.rs deleted file mode 100644 index bf7f2779..00000000 --- a/zokrates_libsnark/build.rs +++ /dev/null @@ -1,92 +0,0 @@ -fn main() { - #[cfg(not(target_os = "macos"))] - { - use std::env; - use std::path::PathBuf; - use std::process::Command; - - // fetch libsnark source - const LIBSNARK_URL: &str = "https://github.com/scipr-lab/libsnark.git"; - const LIBSNARK_COMMIT: &str = "f7c87b88744ecfd008126d415494d9b34c4c1b20"; - - let out_path = PathBuf::from(env::var("OUT_DIR").unwrap()); - let libsnark_source_path = &out_path.join("libsnark"); - - if !libsnark_source_path.exists() { - // Clone the repository - let _ = Command::new("git") - .current_dir(out_path) - .args(&["clone", "--no-checkout", LIBSNARK_URL]) - .status() - .unwrap(); - - // Checkout the specific commit - let _ = Command::new("git") - .current_dir(libsnark_source_path) - .args(&["checkout", "-f", LIBSNARK_COMMIT]) - .status() - .unwrap(); - - // Unencrypted `git://` protocol is no longer supported on GitHub - // so we replace all submodule urls to use `https://` - let gitmodules_path = libsnark_source_path.join(".gitmodules"); - let gitmodules = std::fs::read_to_string(&gitmodules_path) - .unwrap() - .replace("git://", "https://"); - - std::fs::write(&gitmodules_path, gitmodules).unwrap(); - - // Update all submodules recursively - let _ = Command::new("git") - .current_dir(libsnark_source_path) - .args(&["submodule", "update", "--init", "--recursive"]) - .status() - .unwrap(); - } - - // build libsnark - let libsnark = cmake::Config::new(libsnark_source_path) - .define("WITH_SUPERCOP", "OFF") - .define("WITH_PROCPS", "OFF") - .define("WITH_SUPERCOP", "OFF") - .define("CURVE", "ALT_BN128") - .define("USE_PT_COMPRESSION", "OFF") - .define("MONTGOMERY_OUTPUT", "ON") - .define("BINARY_OUTPUT", "ON") - .define("DMULTICORE", "ON") - .build(); - - // build backends - cc::Build::new() - .cpp(true) - .debug(cfg!(debug_assertions)) - .flag("-std=c++11") - .include(libsnark_source_path) - .include(libsnark_source_path.join("depends/libff")) - .include(libsnark_source_path.join("depends/libfqfft")) - .define("CURVE_ALT_BN128", None) - .file("lib/ffi.cpp") - .file("lib/gm17.cpp") - .file("lib/pghr13.cpp") - .compile("libsnark_wrapper.a"); - - println!( - "cargo:rustc-link-search=native={}", - libsnark.join("lib").display() - ); - - println!("cargo:rustc-link-lib=gmp"); - println!("cargo:rustc-link-lib=gmpxx"); - - #[cfg(debug_assertions)] - { - println!("cargo:rustc-link-lib=static=snarkd"); - println!("cargo:rustc-link-lib=static=ffd"); - } - #[cfg(not(debug_assertions))] - { - println!("cargo:rustc-link-lib=static=snark"); - println!("cargo:rustc-link-lib=static=ff"); - } - } -} diff --git a/zokrates_libsnark/lib/ffi.cpp b/zokrates_libsnark/lib/ffi.cpp deleted file mode 100644 index a4e0f72a..00000000 --- a/zokrates_libsnark/lib/ffi.cpp +++ /dev/null @@ -1,6 +0,0 @@ -#include "ffi.hpp" - -void c_free(uint8_t* ptr) -{ - free(ptr); -} \ No newline at end of file diff --git a/zokrates_libsnark/lib/ffi.hpp b/zokrates_libsnark/lib/ffi.hpp deleted file mode 100644 index b1c32ea6..00000000 --- a/zokrates_libsnark/lib/ffi.hpp +++ /dev/null @@ -1,37 +0,0 @@ -#pragma once - -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -struct buffer_t { - uint8_t* data; - int32_t length; -}; - -struct setup_result_t { - buffer_t vk; - buffer_t pk; - setup_result_t(buffer_t& vk_buf, buffer_t& pk_buf) - : vk(vk_buf) - , pk(pk_buf) - { - } -}; - -struct proof_result_t { - buffer_t proof; - proof_result_t(buffer_t& proof_buf) - : proof(proof_buf) - { - } -}; - -void c_free(uint8_t* ptr); - -#ifdef __cplusplus -} // extern "C" -#endif \ No newline at end of file diff --git a/zokrates_libsnark/lib/gm17.cpp b/zokrates_libsnark/lib/gm17.cpp deleted file mode 100644 index 12d2540a..00000000 --- a/zokrates_libsnark/lib/gm17.cpp +++ /dev/null @@ -1,216 +0,0 @@ -/** - * @file gm17.cpp - * @author Jacob Eberhardt - * @date 2017 - */ - -#include "gm17.hpp" - -#include -#include -#include - -// contains definition of alt_bn128 ec public parameters -#include "libff/algebra/curves/alt_bn128/alt_bn128_pp.hpp" - -// contains required interfaces and types (keypair, proof, generator, prover, verifier) -#include - -using namespace libsnark; - -#include "util.tcc" - -namespace gm17 { - -template -buffer_t serialize_verification_key(r1cs_se_ppzksnark_verification_key* vk) -{ - 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); - - assert(ptr == buffer.data + buffer.length); - return buffer; -} - -template -buffer_t serialize_proof(r1cs_se_ppzksnark_proof* proof) -{ - 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); - - assert(ptr == buffer.data + buffer.length); - return buffer; -} - -template -setup_result_t setup(const uint8_t* a, const uint8_t* b, const uint8_t* c, int32_t a_len, int32_t b_len, int32_t c_len, int32_t constraints, int32_t variables, int32_t inputs) -{ - libff::inhibit_profiling_info = true; - libff::inhibit_profiling_counters = true; - - // initialize curve parameters - ppT::init_public_params(); - - 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); - - 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 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; - - // initialize curve parameters - ppT::init_public_params(); - - r1cs_se_ppzksnark_proving_key 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(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(to_libff_bigint(private_inputs + (i * R * sizeof(mp_limb_t))))); - } - - r1cs_primary_input> primary_input( - full_variable_assignment.begin(), - full_variable_assignment.begin() + public_inputs_length - 1); - - r1cs_primary_input> auxiliary_input( - full_variable_assignment.begin() + public_inputs_length - 1, - full_variable_assignment.end()); - - r1cs_se_ppzksnark_proof proof = r1cs_se_ppzksnark_prover(proving_key, primary_input, auxiliary_input); - buffer_t proof_buf = serialize_proof(&proof); - proof_result_t result(proof_buf); - return result; -} - -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; - libff::inhibit_profiling_counters = true; - - // initialize curve parameters - ppT::init_public_params(); - - 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(to_libff_bigint(public_inputs + (i * R * sizeof(mp_limb_t))))); - } - - return r1cs_se_ppzksnark_verifier_strong_IC(vk, primary_input, proof); -} -} - -setup_result_t gm17_bn128_setup(const uint8_t* a, const uint8_t* b, const uint8_t* c, int32_t a_len, int32_t b_len, int32_t c_len, int32_t constraints, int32_t variables, int32_t inputs) -{ - return gm17::setup(a, b, c, a_len, b_len, c_len, constraints, variables, inputs); -} - -proof_result_t gm17_bn128_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) -{ - return gm17::generate_proof(pk_buf, - public_inputs, - public_inputs_length, - private_inputs, - private_inputs_length); -} - -bool gm17_bn128_verify(buffer_t* vk_buf, buffer_t* proof_buf, const uint8_t* public_inputs, int32_t 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_libsnark/lib/gm17.hpp b/zokrates_libsnark/lib/gm17.hpp deleted file mode 100644 index 96e8cf97..00000000 --- a/zokrates_libsnark/lib/gm17.hpp +++ /dev/null @@ -1,42 +0,0 @@ -/** - * @file gm17.hpp - * @author Jacob Eberhardt - * @date 2017 - */ - -#pragma once - -#ifdef __cplusplus -extern "C" { -#endif - -#include "ffi.hpp" - -setup_result_t gm17_bn128_setup( - const uint8_t* a, - const uint8_t* b, - const uint8_t* c, - int32_t a_len, - int32_t b_len, - int32_t c_len, - int32_t constraints, - int32_t variables, - int32_t inputs); - -proof_result_t gm17_bn128_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); - -bool gm17_bn128_verify( - buffer_t* vk_buf, - buffer_t* proof_buf, - const uint8_t* public_inputs, - int32_t public_inputs_length); - -#ifdef __cplusplus -} // extern "C" -#endif \ No newline at end of file diff --git a/zokrates_libsnark/lib/pghr13.cpp b/zokrates_libsnark/lib/pghr13.cpp deleted file mode 100644 index de222398..00000000 --- a/zokrates_libsnark/lib/pghr13.cpp +++ /dev/null @@ -1,240 +0,0 @@ -/** - * @file pghr13.cpp - * @author Jacob Eberhardt - * @date 2017 - */ - -#include "pghr13.hpp" - -#include -#include -#include - -// contains definition of alt_bn128 ec public parameters -#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; - -#include "util.tcc" - -namespace pghr13 { - -template -buffer_t serialize_verification_key(r1cs_ppzksnark_verification_key* vk) -{ - 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); - - assert(ptr == buffer.data + buffer.length); - return buffer; -} - -template -buffer_t serialize_proof(r1cs_ppzksnark_proof* proof) -{ - 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); - - assert(ptr == buffer.data + buffer.length); - return buffer; -} - -template -setup_result_t setup(const uint8_t* a, const uint8_t* b, const uint8_t* c, int32_t a_len, int32_t b_len, int32_t c_len, int32_t constraints, int32_t variables, int32_t inputs) -{ - libff::inhibit_profiling_info = true; - libff::inhibit_profiling_counters = true; - - // initialize curve parameters - ppT::init_public_params(); - - 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); - - 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 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; - - // initialize curve parameters - ppT::init_public_params(); - - r1cs_ppzksnark_proving_key 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(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(to_libff_bigint(private_inputs + (i * R * sizeof(mp_limb_t))))); - } - - r1cs_primary_input> primary_input( - full_variable_assignment.begin(), - full_variable_assignment.begin() + public_inputs_length - 1); - - r1cs_primary_input> auxiliary_input( - full_variable_assignment.begin() + public_inputs_length - 1, - full_variable_assignment.end()); - - r1cs_ppzksnark_proof proof = r1cs_ppzksnark_prover(proving_key, primary_input, auxiliary_input); - buffer_t proof_buf = serialize_proof(&proof); - proof_result_t result(proof_buf); - return result; -} - -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; - libff::inhibit_profiling_counters = true; - - // initialize curve parameters - ppT::init_public_params(); - - 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); - } - - 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(to_libff_bigint(public_inputs + (i * R * sizeof(mp_limb_t))))); - } - return r1cs_ppzksnark_verifier_strong_IC(vk, primary_input, proof); -} -} - -setup_result_t pghr13_bn128_setup(const uint8_t* a, const uint8_t* b, const uint8_t* c, int32_t a_len, int32_t b_len, int32_t c_len, int32_t constraints, int32_t variables, int32_t inputs) -{ - return pghr13::setup(a, b, c, a_len, b_len, c_len, constraints, variables, inputs); -} - -proof_result_t pghr13_bn128_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) -{ - return pghr13::generate_proof(pk_buf, - public_inputs, - public_inputs_length, - private_inputs, - private_inputs_length); -} - -bool pghr13_bn128_verify(buffer_t* vk_buf, buffer_t* proof_buf, const uint8_t* public_inputs, int32_t 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_libsnark/lib/pghr13.hpp b/zokrates_libsnark/lib/pghr13.hpp deleted file mode 100644 index 9f88cc56..00000000 --- a/zokrates_libsnark/lib/pghr13.hpp +++ /dev/null @@ -1,42 +0,0 @@ -/** - * @file pghr13.hpp - * @author Jacob Eberhardt - * @date 2017 - */ - -#pragma once - -#ifdef __cplusplus -extern "C" { -#endif - -#include "ffi.hpp" - -setup_result_t pghr13_bn128_setup( - const uint8_t* a, - const uint8_t* b, - const uint8_t* c, - int32_t a_len, - int32_t b_len, - int32_t c_len, - int32_t constraints, - int32_t variables, - int32_t inputs); - -proof_result_t pghr13_bn128_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); - -bool pghr13_bn128_verify( - buffer_t* vk_buf, - buffer_t* proof_buf, - const uint8_t* public_inputs, - int32_t public_inputs_length); - -#ifdef __cplusplus -} // extern "C" -#endif \ No newline at end of file diff --git a/zokrates_libsnark/lib/util.tcc b/zokrates_libsnark/lib/util.tcc deleted file mode 100644 index 53d11bfd..00000000 --- a/zokrates_libsnark/lib/util.tcc +++ /dev/null @@ -1,187 +0,0 @@ -#pragma once - -#include "ffi.hpp" - -#include -#include -#include -#include -#include - -// conversion byte[N] -> libsnark bigint -template -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(input[i * 8 + j]) << (8 * (7 - j)); - } - } - return x; -} - -// conversion libsnark bigint -> byte[N] -template -void from_libff_bigint(libff::bigint x, uint8_t* out) -{ - for (unsigned i = 0; i < N; i++) { - for (unsigned j = 0; j < 8; j++) { - out[i * 8 + j] = uint8_t(uint64_t(x.data[N - 1 - i]) >> (8 * (7 - j))); - } - } -} - -template -void serialize_g1_affine(G1 point, uint8_t*& buffer) -{ - const size_t ELEMENT_SIZE = Q * sizeof(mp_limb_t); - - G1 aff = point; - aff.to_affine_coordinates(); - - 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 -void serialize_g2_affine(G2 point, uint8_t*& buffer) -{ - const size_t ELEMENT_SIZE = Q * sizeof(mp_limb_t); - - G2 aff = point; - aff.to_affine_coordinates(); - - 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