diff --git a/Cargo.lock b/Cargo.lock index fc39b06b1..9637a7977 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -17,6 +17,18 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" +[[package]] +name = "ahash" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +dependencies = [ + "cfg-if", + "once_cell", + "version_check", + "zerocopy", +] + [[package]] name = "aho-corasick" version = "1.1.3" @@ -26,6 +38,12 @@ dependencies = [ "memchr", ] +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + [[package]] name = "android-tzdata" version = "0.1.1" @@ -101,57 +119,153 @@ dependencies = [ name = "arith" version = "0.1.0" dependencies = [ + "ark-bn254", + "ark-ff", "ark-std", "criterion", "ethnum", - "halo2curves", "itertools 0.13.0", "log", - "rand", "serdes", "tynm", ] [[package]] -name = "ark-std" -version = "0.4.0" +name = "ark-bn254" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d69eab57e8d2663efa5c63135b2af4f396d66424f88954c21104125ab6b3e6bc" +dependencies = [ + "ark-ec", + "ark-ff", + "ark-std", +] + +[[package]] +name = "ark-ec" +version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94893f1e0c6eeab764ade8dc4c0db24caf4fe7cbbaafc0eba0a9030f447b5185" +checksum = "43d68f2d516162846c1238e755a7c4d131b892b70cc70c471a8e3ca3ed818fce" dependencies = [ + "ahash", + "ark-ff", + "ark-poly", + "ark-serialize", + "ark-std", + "educe", + "fnv", + "hashbrown", + "itertools 0.13.0", + "num-bigint", + "num-integer", "num-traits", - "rand", + "zeroize", ] [[package]] -name = "arrayref" -version = "0.3.9" +name = "ark-ff" +version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb" +checksum = "a177aba0ed1e0fbb62aa9f6d0502e9b46dad8c2eab04c14258a1212d2557ea70" +dependencies = [ + "ark-ff-asm", + "ark-ff-macros", + "ark-serialize", + "ark-std", + "arrayvec", + "digest", + "educe", + "itertools 0.13.0", + "num-bigint", + "num-traits", + "paste", + "zeroize", +] [[package]] -name = "arrayvec" -version = "0.7.6" +name = "ark-ff-asm" +version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50" +checksum = "62945a2f7e6de02a31fe400aa489f0e0f5b2502e69f95f853adb82a96c7a6b60" +dependencies = [ + "quote", + "syn 2.0.104", +] [[package]] -name = "autocfg" -version = "1.5.0" +name = "ark-ff-macros" +version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" +checksum = "09be120733ee33f7693ceaa202ca41accd5653b779563608f1234f78ae07c4b3" +dependencies = [ + "num-bigint", + "num-traits", + "proc-macro2", + "quote", + "syn 2.0.104", +] [[package]] -name = "babybear" -version = "0.1.0" +name = "ark-poly" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "579305839da207f02b89cd1679e50e67b4331e2f9294a57693e5051b7703fe27" dependencies = [ - "arith", + "ahash", + "ark-ff", + "ark-serialize", "ark-std", - "criterion", - "ethnum", + "educe", + "fnv", + "hashbrown", +] + +[[package]] +name = "ark-serialize" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f4d068aaf107ebcd7dfb52bc748f8030e0fc930ac8e360146ca54c1203088f7" +dependencies = [ + "ark-serialize-derive", + "ark-std", + "arrayvec", + "digest", + "num-bigint", +] + +[[package]] +name = "ark-serialize-derive" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "213888f660fddcca0d257e88e54ac05bca01885f258ccdf695bafd77031bb69d" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.104", +] + +[[package]] +name = "ark-std" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "246a225cc6131e9ee4f24619af0f19d67761fff15d7ccc22e42b80846e69449a" +dependencies = [ + "num-traits", "rand", - "serdes", ] +[[package]] +name = "arrayvec" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50" + +[[package]] +name = "autocfg" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" + [[package]] name = "backtrace" version = "0.3.75" @@ -164,7 +278,7 @@ dependencies = [ "miniz_oxide", "object", "rustc-demangle", - "windows-targets 0.52.6", + "windows-targets", ] [[package]] @@ -178,21 +292,15 @@ name = "bin" version = "0.1.0" dependencies = [ "arith", - "babybear", "bytes", "chrono", "circuit", "clap", "config_macros", - "gf2", - "gf2_128", "gkr", "gkr_engine", "gkr_hashers", - "goldilocks", "log", - "mersenne31", - "mpi", "poly_commit", "polynomials", "serdes", @@ -203,62 +311,12 @@ dependencies = [ "warp", ] -[[package]] -name = "bindgen" -version = "0.72.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f72209734318d0b619a5e0f5129918b848c416e122a3c4ce054e03cb87b726f" -dependencies = [ - "bitflags", - "cexpr", - "clang-sys", - "itertools 0.13.0", - "proc-macro2", - "quote", - "regex", - "rustc-hash", - "shlex", - "syn 2.0.104", -] - [[package]] name = "bitflags" version = "2.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1b8e56985ec62d17e9c1001dc89c88ecd7dc08e47eba5ec7c29c7b5eeecde967" -[[package]] -name = "bitvec" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1bc2832c24239b0141d5674bb9174f9d68a8b5b3f2753311927c172ca46f7e9c" -dependencies = [ - "funty", - "radium", - "tap", - "wyz", -] - -[[package]] -name = "blake2" -version = "0.10.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe" -dependencies = [ - "digest", -] - -[[package]] -name = "blake2b_simd" -version = "1.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06e903a20b159e944f91ec8499fe1e55651480c541ea0a584f5d967c49ad9d99" -dependencies = [ - "arrayref", - "arrayvec", - "constant_time_eq", -] - [[package]] name = "block-buffer" version = "0.10.4" @@ -268,15 +326,6 @@ dependencies = [ "generic-array", ] -[[package]] -name = "build-probe-mpi" -version = "0.1.4" -source = "git+https://github.com/rsmpi/rsmpi?rev=61796831954b679cbe267c1b704ddbcb7fef3715#61796831954b679cbe267c1b704ddbcb7fef3715" -dependencies = [ - "pkg-config", - "shell-words", -] - [[package]] name = "bumpalo" version = "3.19.0" @@ -310,15 +359,6 @@ dependencies = [ "shlex", ] -[[package]] -name = "cexpr" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766" -dependencies = [ - "nom", -] - [[package]] name = "cfg-if" version = "1.0.1" @@ -378,24 +418,11 @@ dependencies = [ "gkr_engine", "gkr_hashers", "log", - "mersenne31", - "mpi", "poly_commit", - "rand", "serdes", - "thiserror 1.0.69", + "thiserror 2.0.12", "transcript", -] - -[[package]] -name = "clang-sys" -version = "1.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b023947811758c97c59bf9d1c188fd619ad4718dcaa767947df1cadb14f39f4" -dependencies = [ - "glob", - "libc", - "libloading", + "wasm-bindgen", ] [[package]] @@ -458,13 +485,8 @@ dependencies = [ name = "config_macros" version = "0.1.0" dependencies = [ - "babybear", - "gf2", "gkr_engine", "gkr_hashers", - "goldilocks", - "halo2curves", - "mersenne31", "poly_commit", "proc-macro2", "quote", @@ -472,21 +494,6 @@ dependencies = [ "transcript", ] -[[package]] -name = "constant_time_eq" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7c74b8349d32d297c9134b8c88677813a227df8f779daa29bfc29c183fe3dca6" - -[[package]] -name = "conv" -version = "0.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78ff10625fd0ac447827aa30ea8b861fead473bb60aeb73af6c1c58caf0d1299" -dependencies = [ - "custom_derive", -] - [[package]] name = "core-foundation-sys" version = "0.8.7" @@ -574,10 +581,9 @@ dependencies = [ "gkr_hashers", "log", "polynomials", - "rand", "serdes", "sumcheck", - "thiserror 1.0.69", + "thiserror 2.0.12", "transcript", ] @@ -597,12 +603,6 @@ dependencies = [ "typenum", ] -[[package]] -name = "custom_derive" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef8ae57c4978a2acd8b869ce6b9ca1dfe817bff704c220209fdef2c0b75a01b9" - [[package]] name = "data-encoding" version = "2.9.0" @@ -628,7 +628,6 @@ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ "block-buffer", "crypto-common", - "subtle", ] [[package]] @@ -642,6 +641,18 @@ dependencies = [ "syn 2.0.104", ] +[[package]] +name = "educe" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d7bc049e1bd8cdeb31b68bbd586a9464ecf9f3944af3958a7a9d0f8b9799417" +dependencies = [ + "enum-ordinalize", + "proc-macro2", + "quote", + "syn 2.0.104", +] + [[package]] name = "either" version = "1.15.0" @@ -657,6 +668,26 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "enum-ordinalize" +version = "4.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fea0dcfa4e54eeb516fe454635a95753ddd39acda650ce703031c6973e315dd5" +dependencies = [ + "enum-ordinalize-derive", +] + +[[package]] +name = "enum-ordinalize-derive" +version = "4.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d28318a75d4aead5c4db25382e8ef717932d0346600cacae6357eb5941bc5ff" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.104", +] + [[package]] name = "env_filter" version = "0.1.3" @@ -692,17 +723,6 @@ version = "1.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ca81e6b4777c89fd810c25a4be2b1bd93ea034fbe58e6a75216a34c6b82c539b" -[[package]] -name = "ff" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393" -dependencies = [ - "bitvec", - "rand_core", - "subtle", -] - [[package]] name = "fnv" version = "1.0.7" @@ -718,12 +738,6 @@ dependencies = [ "percent-encoding", ] -[[package]] -name = "funty" -version = "2.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c" - [[package]] name = "futures-channel" version = "0.3.31" @@ -787,38 +801,6 @@ dependencies = [ "wasi", ] -[[package]] -name = "gf2" -version = "0.1.0" -dependencies = [ - "arith", - "ark-std", - "cfg-if", - "criterion", - "ethnum", - "halo2curves", - "log", - "rand", - "raw-cpuid", - "serdes", - "thiserror 1.0.69", - "tynm", -] - -[[package]] -name = "gf2_128" -version = "0.1.0" -dependencies = [ - "arith", - "ark-std", - "criterion", - "ethnum", - "gf2", - "rand", - "serdes", - "tynm", -] - [[package]] name = "gimli" version = "0.31.1" @@ -831,29 +813,21 @@ version = "0.1.0" dependencies = [ "arith", "ark-std", - "babybear", "circuit", "config_macros", "criterion", "env_logger", "ethnum", - "gf2", - "gf2_128", "gkr_engine", "gkr_hashers", - "goldilocks", - "halo2curves", "log", - "mersenne31", - "mpi", "poly_commit", "polynomials", - "rand", "rayon", "serdes", "sha2", "sumcheck", - "thiserror 1.0.69", + "thiserror 2.0.12", "transcript", "utils", ] @@ -864,17 +838,10 @@ version = "0.1.0" dependencies = [ "arith", "ark-std", - "babybear", - "gf2", - "gf2_128", - "goldilocks", "itertools 0.13.0", - "mersenne31", - "mpi", "polynomials", - "rand", "serdes", - "thiserror 1.0.69", + "thiserror 2.0.12", ] [[package]] @@ -882,41 +849,13 @@ name = "gkr_hashers" version = "0.1.0" dependencies = [ "arith", - "halo2curves", + "ark-bn254", + "ark-std", "serdes", "sha2", "tiny-keccak", ] -[[package]] -name = "glob" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a8d1add55171497b4705a648c6b583acafb01d58050a51727785f0b2c8e0a2b2" - -[[package]] -name = "goldilocks" -version = "0.1.0" -dependencies = [ - "arith", - "ark-std", - "criterion", - "ethnum", - "rand", - "serdes", -] - -[[package]] -name = "group" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63" -dependencies = [ - "ff", - "rand_core", - "subtle", -] - [[package]] name = "h2" version = "0.3.27" @@ -946,35 +885,14 @@ dependencies = [ "crunchy", ] -[[package]] -name = "halo2curves" -version = "0.6.1" -source = "git+https://github.com/PolyhedraZK/halo2curves#abb020f388b519c1f00033e267faa0709b1249e2" -dependencies = [ - "blake2", - "digest", - "ff", - "group", - "lazy_static", - "num-bigint", - "num-traits", - "pairing", - "pasta_curves", - "paste", - "rand", - "rand_core", - "rayon", - "sha2", - "static_assertions", - "subtle", - "unroll", -] - [[package]] name = "hashbrown" version = "0.15.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5971ac85611da7067dbfcabef3c70ebb5606018acd9e2a3903a0da507521e0d5" +dependencies = [ + "allocator-api2", +] [[package]] name = "headers" @@ -1313,9 +1231,6 @@ name = "lazy_static" version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" -dependencies = [ - "spin", -] [[package]] name = "libc" @@ -1323,35 +1238,6 @@ version = "0.2.174" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1171693293099992e19cddea4e8b849964e9846f4acee11b3948bcc337be8776" -[[package]] -name = "libffi" -version = "4.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7681c6fab541f799a829e44a445a0666cf8d8a6cfebf89419e6aed52c604e87" -dependencies = [ - "libc", - "libffi-sys", -] - -[[package]] -name = "libffi-sys" -version = "3.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b0d828d367b4450ed08e7d510dc46636cd660055f50d67ac943bfe788767c29" -dependencies = [ - "cc", -] - -[[package]] -name = "libloading" -version = "0.8.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07033963ba89ebaf1584d767badaa2e8fcec21aedea6b8c0346d487d49c28667" -dependencies = [ - "cfg-if", - "windows-targets 0.53.3", -] - [[package]] name = "litemap" version = "0.8.0" @@ -1390,12 +1276,10 @@ dependencies = [ "criterion", "ethnum", "gkr_hashers", - "halo2curves", "log", - "rand", "raw-cpuid", "serdes", - "thiserror 1.0.69", + "thiserror 2.0.12", "tynm", ] @@ -1441,30 +1325,6 @@ dependencies = [ "windows-sys 0.59.0", ] -[[package]] -name = "mpi" -version = "0.8.0" -source = "git+https://github.com/rsmpi/rsmpi?rev=61796831954b679cbe267c1b704ddbcb7fef3715#61796831954b679cbe267c1b704ddbcb7fef3715" -dependencies = [ - "build-probe-mpi", - "conv", - "libffi", - "mpi-sys", - "once_cell", - "smallvec", - "thiserror 2.0.12", -] - -[[package]] -name = "mpi-sys" -version = "0.2.2" -source = "git+https://github.com/rsmpi/rsmpi?rev=61796831954b679cbe267c1b704ddbcb7fef3715#61796831954b679cbe267c1b704ddbcb7fef3715" -dependencies = [ - "bindgen", - "build-probe-mpi", - "cc", -] - [[package]] name = "multer" version = "2.1.0" @@ -1548,15 +1408,6 @@ version = "11.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e" -[[package]] -name = "pairing" -version = "0.23.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "81fec4625e73cf41ef4bb6846cafa6d44736525f442ba45e407c4a000a13996f" -dependencies = [ - "group", -] - [[package]] name = "parking_lot" version = "0.12.4" @@ -1577,22 +1428,7 @@ dependencies = [ "libc", "redox_syscall", "smallvec", - "windows-targets 0.52.6", -] - -[[package]] -name = "pasta_curves" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3e57598f73cc7e1b2ac63c79c517b31a0877cd7c402cdcaa311b5208de7a095" -dependencies = [ - "blake2b_simd", - "ff", - "group", - "lazy_static", - "rand", - "static_assertions", - "subtle", + "windows-targets", ] [[package]] @@ -1639,12 +1475,6 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" -[[package]] -name = "pkg-config" -version = "0.3.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c" - [[package]] name = "plotters" version = "0.3.7" @@ -1678,24 +1508,21 @@ name = "poly_commit" version = "0.1.0" dependencies = [ "arith", + "ark-bn254", + "ark-ec", + "ark-ff", "ark-std", "criterion", "derivative", "ethnum", - "gf2", - "gf2_128", "gkr_engine", "gkr_hashers", - "goldilocks", - "halo2curves", "itertools 0.13.0", - "mersenne31", "polynomials", - "rand", "rayon", "serdes", "sumcheck", - "thiserror 1.0.69", + "thiserror 2.0.12", "transcript", "transpose", "tree", @@ -1710,9 +1537,7 @@ dependencies = [ "arith", "ark-std", "criterion", - "halo2curves", "itertools 0.13.0", - "rand", "serdes", ] @@ -1767,12 +1592,6 @@ dependencies = [ "proc-macro2", ] -[[package]] -name = "radium" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc33ff2d4973d518d823d61aa239014831e521c75da58e3df4840d3f47749d09" - [[package]] name = "rand" version = "0.8.5" @@ -1876,12 +1695,6 @@ version = "0.1.26" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "56f7d92ca342cea22a06f2121d944b4fd82af56988c270852495420f961d4ace" -[[package]] -name = "rustc-hash" -version = "2.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "357703d41365b4b27c590e3ed91eabb1b663f07c4c084095e60cbed4362dff0d" - [[package]] name = "rustversion" version = "1.0.21" @@ -1963,17 +1776,21 @@ dependencies = [ name = "serdes" version = "0.1.0" dependencies = [ + "ark-bn254", + "ark-ec", + "ark-serialize", + "ark-std", "ethnum", - "halo2curves", - "rand", "serdes_derive", - "thiserror 1.0.69", + "thiserror 2.0.12", + "wasm-bindgen", ] [[package]] name = "serdes_derive" version = "0.1.0" dependencies = [ + "ark-std", "proc-macro2", "quote", "syn 2.0.104", @@ -2001,12 +1818,6 @@ dependencies = [ "digest", ] -[[package]] -name = "shell-words" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24188a676b6ae68c3b2cb3a01be17fbf7240ce009799bb56d5b1409051e78fde" - [[package]] name = "shlex" version = "1.3.0" @@ -2066,12 +1877,6 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3" -[[package]] -name = "static_assertions" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" - [[package]] name = "strength_reduce" version = "0.2.4" @@ -2084,12 +1889,6 @@ version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" -[[package]] -name = "subtle" -version = "2.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" - [[package]] name = "sumcheck" version = "0.1.0" @@ -2141,12 +1940,6 @@ dependencies = [ "syn 2.0.104", ] -[[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.69" @@ -2328,8 +2121,6 @@ dependencies = [ "arith", "ark-std", "criterion", - "gf2", - "gf2_128", "serdes", "tiny-keccak", "tynm", @@ -2387,16 +2178,6 @@ version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5a5f39404a5da50712a4c1eecf25e90dd62b613502b7e925fd4e4d19b5c96512" -[[package]] -name = "unroll" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ad948c1cb799b1a70f836077721a92a35ac177d4daddf4c20a633786d4cf618" -dependencies = [ - "quote", - "syn 1.0.109", -] - [[package]] name = "url" version = "2.5.4" @@ -2635,7 +2416,7 @@ version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" dependencies = [ - "windows-targets 0.52.6", + "windows-targets", ] [[package]] @@ -2644,7 +2425,7 @@ version = "0.59.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" dependencies = [ - "windows-targets 0.52.6", + "windows-targets", ] [[package]] @@ -2653,31 +2434,14 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" dependencies = [ - "windows_aarch64_gnullvm 0.52.6", - "windows_aarch64_msvc 0.52.6", - "windows_i686_gnu 0.52.6", - "windows_i686_gnullvm 0.52.6", - "windows_i686_msvc 0.52.6", - "windows_x86_64_gnu 0.52.6", - "windows_x86_64_gnullvm 0.52.6", - "windows_x86_64_msvc 0.52.6", -] - -[[package]] -name = "windows-targets" -version = "0.53.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d5fe6031c4041849d7c496a8ded650796e7b6ecc19df1a431c1a363342e5dc91" -dependencies = [ - "windows-link", - "windows_aarch64_gnullvm 0.53.0", - "windows_aarch64_msvc 0.53.0", - "windows_i686_gnu 0.53.0", - "windows_i686_gnullvm 0.53.0", - "windows_i686_msvc 0.53.0", - "windows_x86_64_gnu 0.53.0", - "windows_x86_64_gnullvm 0.53.0", - "windows_x86_64_msvc 0.53.0", + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", ] [[package]] @@ -2686,111 +2450,54 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.53.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "86b8d5f90ddd19cb4a147a5fa63ca848db3df085e25fee3cc10b39b6eebae764" - [[package]] name = "windows_aarch64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" -[[package]] -name = "windows_aarch64_msvc" -version = "0.53.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7651a1f62a11b8cbd5e0d42526e55f2c99886c77e007179efff86c2b137e66c" - [[package]] name = "windows_i686_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" -[[package]] -name = "windows_i686_gnu" -version = "0.53.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1dc67659d35f387f5f6c479dc4e28f1d4bb90ddd1a5d3da2e5d97b42d6272c3" - [[package]] name = "windows_i686_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" -[[package]] -name = "windows_i686_gnullvm" -version = "0.53.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ce6ccbdedbf6d6354471319e781c0dfef054c81fbc7cf83f338a4296c0cae11" - [[package]] name = "windows_i686_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" -[[package]] -name = "windows_i686_msvc" -version = "0.53.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "581fee95406bb13382d2f65cd4a908ca7b1e4c2f1917f143ba16efe98a589b5d" - [[package]] name = "windows_x86_64_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" -[[package]] -name = "windows_x86_64_gnu" -version = "0.53.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e55b5ac9ea33f2fc1716d1742db15574fd6fc8dadc51caab1c16a3d3b4190ba" - [[package]] name = "windows_x86_64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.53.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0a6e035dd0599267ce1ee132e51c27dd29437f63325753051e71dd9e42406c57" - [[package]] name = "windows_x86_64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" -[[package]] -name = "windows_x86_64_msvc" -version = "0.53.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "271414315aff87387382ec3d271b52d7ae78726f5d44ac98b4f4030c91880486" - [[package]] name = "writeable" version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ea2f10b9bb0928dfb1b42b65e1f9e36f7f54dbdf08457afefb38afcdec4fa2bb" -[[package]] -name = "wyz" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05f360fc0b24296329c78fda852a1e9ae82de9cf7b27dae4b7f62f118f77b9ed" -dependencies = [ - "tap", -] - [[package]] name = "yoke" version = "0.8.0" @@ -2856,6 +2563,26 @@ dependencies = [ "synstructure", ] +[[package]] +name = "zeroize" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ced3678a2879b30306d323f4542626697a464a97c0a07c9aebf7ebca65cd4dde" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce36e65b0d2999d2aafac989fb249189a141aee1f53c612c1f37d72631959f69" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.104", +] + [[package]] name = "zerotrie" version = "0.2.2" diff --git a/Cargo.toml b/Cargo.toml index 5d47d25ba..5bd2deaa0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,11 +1,11 @@ [workspace] members = [ "arith", # definitions of Field, Extensions, SIMDS - "arith/babybear", - "arith/gf2", - "arith/gf2_128", - "arith/goldilocks", - "arith/mersenne31", + # "arith/babybear", + # "arith/gf2", + # "arith/gf2_128", + # "arith/goldilocks", + # "arith/mersenne31", "arith/polynomials", "bin", # binary executables "circuit", @@ -25,26 +25,24 @@ members = [ resolver = "2" [workspace.dependencies] -ark-std = "0.4" -ark-bn254 = "0.4.0" -ark-ec = "0.4.0" -ark-ff = { version = "0.4" } +ark-std = "0.5" +ark-bn254 = "0.5.0" +ark-ec = "0.5.0" +ark-ff = { version = "0.5" } +ark-serialize = "0.5.0" bytes = "1.6.0" chrono = "0.4.38" clap = { version = "4.1", features = ["derive"] } cfg-if = "1.0" criterion = { version = "0.5", features = ["html_reports"] } env_logger = "0.11.3" -halo2curves = { git = "https://github.com/PolyhedraZK/halo2curves", default-features = false, features = [ - "bits", -] } syn = "2.0" # For parsing Rust code quote = "1.0" # For generating code proc-macro2 = "1.0" # For working with tokens itertools = "0.13" log = "0.4" -mpi = { git = "https://github.com/rsmpi/rsmpi", rev = "61796831954b679cbe267c1b704ddbcb7fef3715" } -rand = "0.8.5" +# mpi = { git = "https://github.com/rsmpi/rsmpi", rev = "61796831954b679cbe267c1b704ddbcb7fef3715" } +# rand = { version = "0.8.5", features = ["std"] } raw-cpuid = "11.1.0" rayon = "1.10" sha2 = "0.10.8" @@ -52,7 +50,7 @@ tiny-keccak = { version = "2.0.2", features = [ "sha3", "keccak" ] } tokio = { version = "1.38.0", features = ["full"] } tynm = { version = "0.1.6", default-features = false } warp = "0.3.7" -thiserror = "1.0.63" +thiserror = { version = "2.0", default-features = false } ethnum = "1.5.0" rand_chacha = "0.3.1" derivative = "2.2.0" diff --git a/arith/Cargo.toml b/arith/Cargo.toml index 8cd0307bf..ef77f7034 100644 --- a/arith/Cargo.toml +++ b/arith/Cargo.toml @@ -4,19 +4,18 @@ version = "0.1.0" edition = "2021" [dependencies] +ark-ff.workspace = true ark-std.workspace = true -criterion.workspace = true +ark-bn254.workspace = true ethnum.workspace = true itertools.workspace = true -halo2curves.workspace = true log.workspace = true -rand.workspace = true tynm.workspace = true serdes = { path = "../serdes" } -[features] -halo2_asm = [ "halo2curves/asm" ] +[dev-dependencies] +criterion.workspace = true [[bench]] name = "fr" diff --git a/arith/babybear/src/babybear_ext.rs b/arith/babybear/src/babybear_ext.rs index f6956e535..dba2545a5 100644 --- a/arith/babybear/src/babybear_ext.rs +++ b/arith/babybear/src/babybear_ext.rs @@ -25,17 +25,17 @@ impl Field for BabyBearExt3 { const FIELD_SIZE: usize = 32 * 3; - const ZERO: Self = BabyBearExt3 { - v: [BabyBear::ZERO, BabyBear::ZERO, BabyBear::ZERO], - }; + // const ZERO: Self = BabyBearExt3 { + // v: [BabyBear::zero(), BabyBear::zero(), BabyBear::zero()], + // }; - const ONE: Self = BabyBearExt3 { - v: [BabyBear::ONE, BabyBear::ZERO, BabyBear::ZERO], - }; + // const ONE: Self = BabyBearExt3 { + // v: [BabyBear::one(), BabyBear::zero(), BabyBear::zero()], + // }; - const INV_2: BabyBearExt3 = BabyBearExt3 { - v: [BabyBear::INV_2, BabyBear::new(0), BabyBear::new(0)], - }; + // const INV_2: BabyBearExt3 = BabyBearExt3 { + // v: [BabyBear::INV_2, BabyBear::new(0), BabyBear::new(0)], + // }; const MODULUS: U256 = BabyBear::MODULUS; @@ -118,9 +118,15 @@ impl ExtensionField for BabyBearExt3 { /// Extension Field const W: u32 = 2; - const X: Self = BabyBearExt3 { - v: [BabyBear::ZERO, BabyBear::ONE, BabyBear::ZERO], - }; + // const X: Self = BabyBearExt3 { + // v: [BabyBear::zero(), BabyBear::one(), BabyBear::zero()], + // }; + + fn x() -> Self { + BabyBearExt3 { + v: [BabyBear::zero(), BabyBear::one(), BabyBear::zero()], + } + } /// Base field for the extension type BaseField = BabyBear; diff --git a/arith/babybear/src/babybear_ext3x16.rs b/arith/babybear/src/babybear_ext3x16.rs index 8e30a79df..623d8d950 100644 --- a/arith/babybear/src/babybear_ext3x16.rs +++ b/arith/babybear/src/babybear_ext3x16.rs @@ -99,9 +99,15 @@ impl ExtensionField for BabyBearExt3x16 { const W: u32 = 2; - const X: Self = BabyBearExt3x16 { - v: [BabyBearx16::ZERO, BabyBearx16::ONE, BabyBearx16::ZERO], - }; + // const X: Self = BabyBearExt3x16 { + // v: [BabyBearx16::zero(), BabyBearx16::one(), BabyBearx16::zero()], + // }; + + fn x() -> Self { + BabyBearExt3x16 { + v: [BabyBearx16::zero(), BabyBearx16::one(), BabyBearx16::zero()], + } + } type BaseField = BabyBearx16; @@ -176,17 +182,17 @@ impl Field for BabyBearExt3x16 { const FIELD_SIZE: usize = 32 * 3; - const ZERO: Self = Self { - v: [BabyBearx16::ZERO; 3], - }; + // const ZERO: Self = Self { + // v: [BabyBearx16::zero(); 3], + // }; - const ONE: Self = Self { - v: [BabyBearx16::ONE, BabyBearx16::ZERO, BabyBearx16::ZERO], - }; + // const ONE: Self = Self { + // v: [BabyBearx16::one(), BabyBearx16::zero(), BabyBearx16::zero()], + // }; - const INV_2: Self = Self { - v: [BabyBearx16::INV_2, BabyBearx16::ZERO, BabyBearx16::ZERO], - }; + // const INV_2: Self = Self { + // v: [BabyBearx16::INV_2, BabyBearx16::zero(), BabyBearx16::zero()], + // }; const MODULUS: U256 = BabyBear::MODULUS; diff --git a/arith/babybear/src/babybearx16/babybear_avx256.rs b/arith/babybear/src/babybearx16/babybear_avx256.rs index 0d65c3248..c3134ce2b 100644 --- a/arith/babybear/src/babybearx16/babybear_avx256.rs +++ b/arith/babybear/src/babybearx16/babybear_avx256.rs @@ -29,8 +29,8 @@ const PACKED_0: __m256i = unsafe { transmute([0; 8]) }; // 1 in Montgomery form const PACKED_1: __m256i = unsafe { transmute([0xffffffe; 8]) }; -// 2^-1 Montgomery form -const PACKED_INV_2: __m256i = unsafe { transmute([0x7ffffff; 8]) }; +// // 2^-1 Montgomery form +// const PACKED_INV_2: __m256i = unsafe { transmute([0x7ffffff; 8]) }; const PACKED_MOD: __m256i = unsafe { transmute([BABY_BEAR_MOD; 8]) }; @@ -71,17 +71,17 @@ impl Field for AVXBabyBear { const SIZE: usize = 512 / 8; - const ZERO: Self = Self { - v: [PACKED_0, PACKED_0], - }; + // const ZERO: Self = Self { + // v: [PACKED_0, PACKED_0], + // }; - const ONE: Self = Self { - v: [PACKED_1, PACKED_1], - }; + // const ONE: Self = Self { + // v: [PACKED_1, PACKED_1], + // }; - const INV_2: Self = Self { - v: [PACKED_INV_2, PACKED_INV_2], - }; + // const INV_2: Self = Self { + // v: [PACKED_INV_2, PACKED_INV_2], + // }; const FIELD_SIZE: usize = 32; @@ -89,7 +89,9 @@ impl Field for AVXBabyBear { #[inline(always)] fn zero() -> Self { - Self::ZERO + Self { + v: [PACKED_0, PACKED_0], + } } #[inline(always)] diff --git a/arith/babybear/src/babybearx16/babybear_avx512.rs b/arith/babybear/src/babybearx16/babybear_avx512.rs index 73d9a1467..fabd7efc6 100644 --- a/arith/babybear/src/babybearx16/babybear_avx512.rs +++ b/arith/babybear/src/babybearx16/babybear_avx512.rs @@ -30,8 +30,8 @@ const PACKED_0: __m512i = unsafe { transmute([0; BABY_BEAR_PACK_SIZE]) }; // 1 in Montgomery form const PACKED_1: __m512i = unsafe { transmute([0xffffffe; BABY_BEAR_PACK_SIZE]) }; -// 2^-1 Montgomery form -const PACKED_INV_2: __m512i = unsafe { transmute([0x7ffffff; BABY_BEAR_PACK_SIZE]) }; +// // 2^-1 Montgomery form +// const PACKED_INV_2: __m512i = unsafe { transmute([0x7ffffff; BABY_BEAR_PACK_SIZE]) }; const PACKED_MOD: __m512i = unsafe { transmute([BABY_BEAR_MOD; BABY_BEAR_PACK_SIZE]) }; @@ -71,11 +71,11 @@ impl Field for AVXBabyBear { const SIZE: usize = 512 / 8; - const ZERO: Self = Self { v: PACKED_0 }; + // const ZERO: Self = Self { v: PACKED_0 }; - const ONE: Self = Self { v: PACKED_1 }; + // const ONE: Self = Self { v: PACKED_1 }; - const INV_2: Self = Self { v: PACKED_INV_2 }; + // const INV_2: Self = Self { v: PACKED_INV_2 }; const FIELD_SIZE: usize = 32; @@ -83,7 +83,7 @@ impl Field for AVXBabyBear { #[inline(always)] fn zero() -> Self { - Self::ZERO + Self { v: PACKED_0 } } #[inline(always)] diff --git a/arith/babybear/src/babybearx16/babybear_neon.rs b/arith/babybear/src/babybearx16/babybear_neon.rs index 0ba81f583..25443f197 100644 --- a/arith/babybear/src/babybearx16/babybear_neon.rs +++ b/arith/babybear/src/babybearx16/babybear_neon.rs @@ -82,7 +82,7 @@ impl Field for NeonBabyBear { const ZERO: Self = Self { v: unsafe { transmute::<[BabyBear; BABY_BEAR_PACK_SIZE], [uint32x4_t; 4]>( - [BabyBear::ZERO; BABY_BEAR_PACK_SIZE], + [BabyBear::zero(); BABY_BEAR_PACK_SIZE], ) }, }; @@ -90,7 +90,7 @@ impl Field for NeonBabyBear { const ONE: Self = Self { v: unsafe { transmute::<[BabyBear; BABY_BEAR_PACK_SIZE], [uint32x4_t; 4]>( - [BabyBear::ONE; BABY_BEAR_PACK_SIZE], + [BabyBear::one(); BABY_BEAR_PACK_SIZE], ) }, }; @@ -106,15 +106,15 @@ impl Field for NeonBabyBear { const MODULUS: U256 = BabyBear::MODULUS; fn zero() -> Self { - Self::ZERO + Self::zero() } fn is_zero(&self) -> bool { - *self == Self::ZERO + *self == Self::zero() } fn one() -> Self { - Self::ONE + Self::one() } fn random_unsafe(mut rng: impl RngCore) -> Self { @@ -218,7 +218,7 @@ impl Debug for NeonBabyBear { impl Default for NeonBabyBear { fn default() -> Self { - Self::ZERO + Self::zero() } } diff --git a/arith/babybear/src/tests.rs b/arith/babybear/src/tests.rs index 76046e216..b2c4d8f61 100644 --- a/arith/babybear/src/tests.rs +++ b/arith/babybear/src/tests.rs @@ -76,7 +76,7 @@ fn baby_bear_two_inverse() { let two = BabyBear::new(2); let two_inverse_canonical: u32 = 1006632961; let two_inverse = BabyBear::new(two_inverse_canonical); - let one = BabyBear::ONE; + let one = BabyBear::one(); assert_eq!(one, two * two_inverse) } diff --git a/arith/benches/fft.rs b/arith/benches/fft.rs index 35f07a40a..50a615db3 100644 --- a/arith/benches/fft.rs +++ b/arith/benches/fft.rs @@ -59,7 +59,7 @@ pub fn halo2_serial_fft(a: &mut [F], omega: F, log_n: u32) { // precompute twiddle factors let twiddles: Vec<_> = (0..(n / 2)) - .scan(F::ONE, |w, _| { + .scan(F::one(), |w, _| { let tw = *w; *w *= ω Some(tw) diff --git a/arith/gf2/Cargo.toml b/arith/gf2/Cargo.toml index fe7c5f26a..d150a5d71 100644 --- a/arith/gf2/Cargo.toml +++ b/arith/gf2/Cargo.toml @@ -8,7 +8,6 @@ arith = { path = "../" } serdes = { path = "../../serdes" } ark-std.workspace = true -halo2curves.workspace = true log.workspace = true rand.workspace = true thiserror.workspace = true diff --git a/arith/gf2/src/gf2.rs b/arith/gf2/src/gf2.rs index 83b64b82c..3dce30787 100644 --- a/arith/gf2/src/gf2.rs +++ b/arith/gf2/src/gf2.rs @@ -52,11 +52,11 @@ impl Field for GF2 { const FIELD_SIZE: usize = 1; // in bits - const ZERO: Self = GF2 { v: 0 }; + // const ZERO: Self = GF2 { v: 0 }; - const ONE: Self = GF2 { v: 1 }; + // const ONE: Self = GF2 { v: 1 }; - const INV_2: Self = GF2 { v: 0 }; + // const INV_2: Self = GF2 { v: 0 }; const MODULUS: U256 = U256([MOD as u128, 0]); @@ -124,7 +124,7 @@ impl Field for GF2 { #[inline(always)] fn mul_by_6(&self) -> Self { - Self::ZERO + Self::zero() } #[inline(always)] diff --git a/arith/gf2/src/gf2x128.rs b/arith/gf2/src/gf2x128.rs index 2625505de..c5c7d4f41 100644 --- a/arith/gf2/src/gf2x128.rs +++ b/arith/gf2/src/gf2x128.rs @@ -22,7 +22,7 @@ impl SimdField for GF2x128 { #[inline(always)] fn scale(&self, challenge: &Self::Scalar) -> Self { if challenge.v == 0 { - ::ZERO + ::zero() } else { *self } @@ -31,8 +31,8 @@ impl SimdField for GF2x128 { #[inline(always)] fn pack_full(base: &Self::Scalar) -> Self { match base.v { - 0 => Self::ZERO, - 1 => Self::ONE, + 0 => Self::zero(), + 1 => Self::one(), _ => panic!("Invalid value for GF2x128: {}", base.v), } } @@ -40,7 +40,7 @@ impl SimdField for GF2x128 { #[inline(always)] fn pack(base_vec: &[Self::Scalar]) -> Self { assert_eq!(base_vec.len(), Self::PACK_SIZE); - let mut packed_to_gf2x64 = [GF2x64::ZERO; Self::PACK_SIZE / GF2x64::PACK_SIZE]; + let mut packed_to_gf2x64 = [GF2x64::zero(); Self::PACK_SIZE / GF2x64::PACK_SIZE]; packed_to_gf2x64 .iter_mut() .zip(base_vec.chunks(GF2x64::PACK_SIZE)) diff --git a/arith/gf2/src/gf2x128/avx.rs b/arith/gf2/src/gf2x128/avx.rs index a61541d69..68f54e0c9 100644 --- a/arith/gf2/src/gf2x128/avx.rs +++ b/arith/gf2/src/gf2x128/avx.rs @@ -42,17 +42,17 @@ impl Field for AVXGF2x128 { const FIELD_SIZE: usize = 1; // in bits - const ZERO: Self = AVXGF2x128 { - v: unsafe { zeroed() }, - }; + // const ZERO: Self = AVXGF2x128 { + // v: unsafe { zeroed() }, + // }; - const ONE: Self = AVXGF2x128 { - v: unsafe { transmute::<[u64; 2], __m128i>([!0u64, !0u64]) }, - }; + // const ONE: Self = AVXGF2x128 { + // v: unsafe { transmute::<[u64; 2], __m128i>([!0u64, !0u64]) }, + // }; - const INV_2: Self = AVXGF2x128 { - v: unsafe { zeroed() }, - }; + // const INV_2: Self = AVXGF2x128 { + // v: unsafe { zeroed() }, + // }; const MODULUS: U256 = unimplemented!(); // should not be used @@ -128,7 +128,7 @@ impl Field for AVXGF2x128 { impl Default for AVXGF2x128 { #[inline(always)] fn default() -> Self { - Self::ZERO + Self::zero() } } @@ -286,9 +286,9 @@ impl From for AVXGF2x128 { fn from(v: u32) -> Self { assert!(v < 2); if v == 0 { - AVXGF2x128::ZERO + AVXGF2x128::zero() } else { - AVXGF2x128::ONE + AVXGF2x128::one() } } } @@ -298,9 +298,9 @@ impl From for AVXGF2x128 { fn from(v: GF2) -> Self { assert!(v.v < 2); if v.v == 0 { - AVXGF2x128::ZERO + AVXGF2x128::zero() } else { - AVXGF2x128::ONE + AVXGF2x128::one() } } } diff --git a/arith/gf2/src/gf2x128/neon.rs b/arith/gf2/src/gf2x128/neon.rs index 376ded5f7..81f52b0af 100644 --- a/arith/gf2/src/gf2x128/neon.rs +++ b/arith/gf2/src/gf2x128/neon.rs @@ -127,7 +127,7 @@ impl Field for NeonGF2x128 { impl Default for NeonGF2x128 { #[inline(always)] fn default() -> Self { - Self::ZERO + Self::zero() } } @@ -287,9 +287,9 @@ impl From for NeonGF2x128 { fn from(v: u32) -> Self { assert!(v < 2); if v == 0 { - NeonGF2x128::ZERO + NeonGF2x128::zero() } else { - NeonGF2x128::ONE + NeonGF2x128::one() } } } @@ -299,9 +299,9 @@ impl From for NeonGF2x128 { fn from(v: GF2) -> Self { assert!(v.v < 2); if v.v == 0 { - NeonGF2x128::ZERO + NeonGF2x128::zero() } else { - NeonGF2x128::ONE + NeonGF2x128::one() } } } diff --git a/arith/gf2/src/gf2x64.rs b/arith/gf2/src/gf2x64.rs index 4c96fc817..da1bd0023 100644 --- a/arith/gf2/src/gf2x64.rs +++ b/arith/gf2/src/gf2x64.rs @@ -21,24 +21,24 @@ impl Field for GF2x64 { const FIELD_SIZE: usize = 1; - const ZERO: Self = GF2x64 { v: 0 }; + // const ZERO: Self = GF2x64 { v: 0 }; - const ONE: Self = GF2x64 { v: !0u64 }; + // const ONE: Self = GF2x64 { v: !0u64 }; - #[doc(hidden)] - const INV_2: Self = unimplemented!(); // NOTE: should not be used + // #[doc(hidden)] + // const INV_2: Self = unimplemented!(); // NOTE: should not be used #[doc(hidden)] const MODULUS: U256 = unimplemented!(); // should not be used #[inline(always)] fn zero() -> Self { - GF2x64::ZERO + GF2x64 { v: 0 } } #[inline(always)] fn one() -> Self { - GF2x64::ONE + GF2x64 { v: !0u64 } } #[inline(always)] @@ -90,7 +90,7 @@ impl Field for GF2x64 { #[inline(always)] fn mul_by_6(&self) -> Self { - Self::ZERO + Self::zero() } } @@ -270,7 +270,7 @@ impl SimdField for GF2x64 { #[inline(always)] fn pack(base_vec: &[Self::Scalar]) -> Self { assert!(base_vec.len() == Self::PACK_SIZE); - let mut packed_to_gf2x8 = [GF2x8::ZERO; Self::PACK_SIZE / GF2x8::PACK_SIZE]; + let mut packed_to_gf2x8 = [GF2x8::zero(); Self::PACK_SIZE / GF2x8::PACK_SIZE]; packed_to_gf2x8 .iter_mut() .zip(base_vec.chunks(GF2x8::PACK_SIZE)) diff --git a/arith/gf2/src/gf2x8.rs b/arith/gf2/src/gf2x8.rs index b4c3a5d3e..bb0f06676 100644 --- a/arith/gf2/src/gf2x8.rs +++ b/arith/gf2/src/gf2x8.rs @@ -21,11 +21,11 @@ impl Field for GF2x8 { const FIELD_SIZE: usize = 1; // in bits - const ZERO: Self = GF2x8 { v: 0 }; + // const ZERO: Self = GF2x8 { v: 0 }; - const ONE: Self = GF2x8 { v: 255 }; + // const ONE: Self = GF2x8 { v: 255 }; - const INV_2: Self = GF2x8 { v: 0 }; + // const INV_2: Self = GF2x8 { v: 0 }; #[doc(hidden)] const MODULUS: U256 = unimplemented!(); // should not be used @@ -89,7 +89,7 @@ impl Field for GF2x8 { #[inline(always)] fn mul_by_6(&self) -> Self { - Self::ZERO + Self::zero() } } @@ -313,7 +313,7 @@ impl Mul for GF2x8 { #[inline(always)] fn mul(self, rhs: GF2) -> GF2x8 { if rhs.is_zero() { - GF2x8::ZERO + GF2x8::zero() } else { self } diff --git a/arith/gf2_128/src/gf2_ext128/avx.rs b/arith/gf2_128/src/gf2_ext128/avx.rs index eb34aef3b..c290984c4 100644 --- a/arith/gf2_128/src/gf2_ext128/avx.rs +++ b/arith/gf2_128/src/gf2_ext128/avx.rs @@ -44,17 +44,17 @@ impl Field for AVXGF2_128 { const FIELD_SIZE: usize = 128; // in bits - const ZERO: Self = AVXGF2_128 { - v: unsafe { std::mem::zeroed() }, - }; + // const ZERO: Self = AVXGF2_128 { + // v: unsafe { std::mem::zeroed() }, + // }; - const ONE: Self = AVXGF2_128 { - v: unsafe { std::mem::transmute::<[i32; 4], __m128i>([1, 0, 0, 0]) }, - }; + // const ONE: Self = AVXGF2_128 { + // v: unsafe { std::mem::transmute::<[i32; 4], __m128i>([1, 0, 0, 0]) }, + // }; - const INV_2: Self = AVXGF2_128 { - v: unsafe { std::mem::zeroed() }, - }; + // const INV_2: Self = AVXGF2_128 { + // v: unsafe { std::mem::zeroed() }, + // }; const MODULUS: U256 = unimplemented!(); // should not be used @@ -131,9 +131,15 @@ impl ExtensionField for AVXGF2_128 { const W: u32 = 0x87; - const X: Self = AVXGF2_128 { - v: unsafe { std::mem::transmute::<[i32; 4], __m128i>([2, 0, 0, 0]) }, - }; + // const X: Self = AVXGF2_128 { + // v: unsafe { std::mem::transmute::<[i32; 4], __m128i>([2, 0, 0, 0]) }, + // }; + + fn x() -> Self { + AVXGF2_128 { + v: unsafe { std::mem::transmute::<[i32; 4], __m128i>([2, 0, 0, 0]) }, + } + } type BaseField = GF2; @@ -187,7 +193,7 @@ impl ExtensionField for AVXGF2_128 { #[inline(always)] fn from_limbs(limbs: &[Self::BaseField]) -> Self { let mut local_limbs = limbs.to_vec(); - local_limbs.resize(Self::DEGREE, Self::BaseField::ZERO); + local_limbs.resize(Self::DEGREE, Self::BaseField::zero()); let mut u32_lanes = [0u32; 4]; local_limbs @@ -208,7 +214,7 @@ impl ExtensionField for AVXGF2_128 { fn to_limbs(&self) -> Vec { let mut u32_extracted: [u32; 4] = unsafe { transmute(self.v) }; - let mut res = vec![Self::BaseField::ZERO; Self::DEGREE]; + let mut res = vec![Self::BaseField::zero(); Self::DEGREE]; u32_extracted .iter_mut() .enumerate() diff --git a/arith/gf2_128/src/gf2_ext128/neon.rs b/arith/gf2_128/src/gf2_ext128/neon.rs index f55d3e720..5fcd67551 100644 --- a/arith/gf2_128/src/gf2_ext128/neon.rs +++ b/arith/gf2_128/src/gf2_ext128/neon.rs @@ -178,7 +178,7 @@ impl ExtensionField for NeonGF2_128 { #[inline(always)] fn from_limbs(limbs: &[Self::BaseField]) -> Self { let mut local_limbs = limbs.to_vec(); - local_limbs.resize(Self::DEGREE, Self::BaseField::ZERO); + local_limbs.resize(Self::DEGREE, Self::BaseField::zero()); let mut u32_lanes = [0u32; 4]; local_limbs @@ -199,7 +199,7 @@ impl ExtensionField for NeonGF2_128 { fn to_limbs(&self) -> Vec { let mut u32_extracted: [u32; 4] = unsafe { transmute(self.v) }; - let mut res = vec![Self::BaseField::ZERO; 128]; + let mut res = vec![Self::BaseField::zero(); 128]; u32_extracted .iter_mut() .enumerate() diff --git a/arith/gf2_128/src/gf2_ext128x8/avx256.rs b/arith/gf2_128/src/gf2_ext128x8/avx256.rs index b17215a3a..f34663ffb 100644 --- a/arith/gf2_128/src/gf2_ext128x8/avx256.rs +++ b/arith/gf2_128/src/gf2_ext128x8/avx256.rs @@ -214,12 +214,12 @@ impl Field for AVX256GF2_128x8 { #[inline(always)] fn double(&self) -> Self { - Self::ZERO + Self::zero() } #[inline(always)] fn mul_by_2(&self) -> Self { - Self::ZERO + Self::zero() } #[inline(always)] @@ -234,7 +234,7 @@ impl Field for AVX256GF2_128x8 { #[inline(always)] fn mul_by_6(&self) -> Self { - Self::ZERO + Self::zero() } } /* @@ -640,9 +640,9 @@ impl ExtensionField for AVX256GF2_128x8 { #[inline(always)] fn from_limbs(limbs: &[Self::BaseField]) -> Self { let mut local_limbs = limbs.to_vec(); - local_limbs.resize(Self::DEGREE, Self::BaseField::ZERO); + local_limbs.resize(Self::DEGREE, Self::BaseField::zero()); - let mut buffer = vec![GF2::ZERO; Self::DEGREE * Self::PACK_SIZE]; + let mut buffer = vec![GF2::zero(); Self::DEGREE * Self::PACK_SIZE]; local_limbs.iter().enumerate().for_each(|(ith_limb, limb)| { let unpacked = limb.unpack(); @@ -663,7 +663,7 @@ impl ExtensionField for AVX256GF2_128x8 { fn to_limbs(&self) -> Vec { let gf2_128s = self.unpack(); - let mut buffer = vec![GF2::ZERO; Self::DEGREE * Self::PACK_SIZE]; + let mut buffer = vec![GF2::zero(); Self::DEGREE * Self::PACK_SIZE]; gf2_128s .iter() .enumerate() diff --git a/arith/gf2_128/src/gf2_ext128x8/avx512.rs b/arith/gf2_128/src/gf2_ext128x8/avx512.rs index 8de2d1daf..b953a035e 100644 --- a/arith/gf2_128/src/gf2_ext128x8/avx512.rs +++ b/arith/gf2_128/src/gf2_ext128x8/avx512.rs @@ -41,10 +41,10 @@ impl ExpSerde for AVX512GF2_128x8 { } } -const PACKED_0: [__m512i; 2] = [ - unsafe { transmute::<[i32; 16], std::arch::x86_64::__m512i>([0; 16]) }, - unsafe { transmute::<[i32; 16], std::arch::x86_64::__m512i>([0; 16]) }, -]; +// const PACKED_0: [__m512i; 2] = [ +// unsafe { transmute::<[i32; 16], std::arch::x86_64::__m512i>([0; 16]) }, +// unsafe { transmute::<[i32; 16], std::arch::x86_64::__m512i>([0; 16]) }, +// ]; const _M512_INV_2: __m512i = unsafe { transmute([ 67_u64, @@ -57,7 +57,7 @@ const _M512_INV_2: __m512i = unsafe { (1_u64) << 63, ]) }; -const PACKED_INV_2: [__m512i; 2] = [_M512_INV_2, _M512_INV_2]; // Should not be used? +// const PACKED_INV_2: [__m512i; 2] = [_M512_INV_2, _M512_INV_2]; // Should not be used? // p(x) = x^128 + x^7 + x^2 + x + 1 impl Field for AVX512GF2_128x8 { @@ -66,18 +66,18 @@ impl Field for AVX512GF2_128x8 { // size in bytes const SIZE: usize = 512 * 2 / 8; - const ZERO: Self = Self { data: PACKED_0 }; + // const ZERO: Self = Self { data: PACKED_0 }; - const ONE: Self = Self { - data: unsafe { - [ - transmute::<[u64; 8], __m512i>([1, 0, 1, 0, 1, 0, 1, 0]), - transmute::<[u64; 8], __m512i>([1, 0, 1, 0, 1, 0, 1, 0]), - ] - }, - }; + // const ONE: Self = Self { + // data: unsafe { + // [ + // transmute::<[u64; 8], __m512i>([1, 0, 1, 0, 1, 0, 1, 0]), + // transmute::<[u64; 8], __m512i>([1, 0, 1, 0, 1, 0, 1, 0]), + // ] + // }, + // }; - const INV_2: Self = Self { data: PACKED_INV_2 }; + // const INV_2: Self = Self { data: PACKED_INV_2 }; const FIELD_SIZE: usize = 128; @@ -197,12 +197,12 @@ impl Field for AVX512GF2_128x8 { #[inline(always)] fn double(&self) -> Self { - Self::ZERO + Self::zero() } #[inline(always)] fn mul_by_2(&self) -> Self { - Self::ZERO + Self::zero() } #[inline(always)] @@ -217,7 +217,7 @@ impl Field for AVX512GF2_128x8 { #[inline(always)] fn mul_by_6(&self) -> Self { - Self::ZERO + Self::zero() } } /* @@ -551,14 +551,25 @@ impl ExtensionField for AVX512GF2_128x8 { const W: u32 = GF2_128::W; - const X: Self = Self { - data: unsafe { - [ - transmute::<[u64; 8], __m512i>([2u64, 0, 2u64, 0, 2u64, 0, 2u64, 0]), - transmute::<[u64; 8], __m512i>([2u64, 0, 2u64, 0, 2u64, 0, 2u64, 0]), - ] - }, - }; + // const X: Self = Self { + // data: unsafe { + // [ + // transmute::<[u64; 8], __m512i>([2u64, 0, 2u64, 0, 2u64, 0, 2u64, 0]), + // transmute::<[u64; 8], __m512i>([2u64, 0, 2u64, 0, 2u64, 0, 2u64, 0]), + // ] + // }, + // }; + + fn x() -> Self { + Self { + data: unsafe { + [ + transmute::<[u64; 8], __m512i>([2u64, 0, 2u64, 0, 2u64, 0, 2u64, 0]), + transmute::<[u64; 8], __m512i>([2u64, 0, 2u64, 0, 2u64, 0, 2u64, 0]), + ] + }, + } + } type BaseField = GF2x8; @@ -645,9 +656,9 @@ impl ExtensionField for AVX512GF2_128x8 { #[inline(always)] fn from_limbs(limbs: &[Self::BaseField]) -> Self { let mut local_limbs = limbs.to_vec(); - local_limbs.resize(Self::DEGREE, Self::BaseField::ZERO); + local_limbs.resize(Self::DEGREE, Self::BaseField::zero()); - let mut buffer = vec![GF2::ZERO; Self::DEGREE * Self::PACK_SIZE]; + let mut buffer = vec![GF2::zero(); Self::DEGREE * Self::PACK_SIZE]; local_limbs.iter().enumerate().for_each(|(ith_limb, limb)| { let unpacked = limb.unpack(); @@ -668,7 +679,7 @@ impl ExtensionField for AVX512GF2_128x8 { fn to_limbs(&self) -> Vec { let gf2_128s = self.unpack(); - let mut buffer = vec![GF2::ZERO; Self::DEGREE * Self::PACK_SIZE]; + let mut buffer = vec![GF2::zero(); Self::DEGREE * Self::PACK_SIZE]; gf2_128s .iter() .enumerate() diff --git a/arith/gf2_128/src/gf2_ext128x8/neon.rs b/arith/gf2_128/src/gf2_ext128x8/neon.rs index 6d23d82b8..301ff2411 100644 --- a/arith/gf2_128/src/gf2_ext128x8/neon.rs +++ b/arith/gf2_128/src/gf2_ext128x8/neon.rs @@ -340,9 +340,9 @@ impl ExtensionField for NeonGF2_128x8 { #[inline(always)] fn from_limbs(limbs: &[Self::BaseField]) -> Self { let mut local_limbs = limbs.to_vec(); - local_limbs.resize(Self::DEGREE, Self::BaseField::ZERO); + local_limbs.resize(Self::DEGREE, Self::BaseField::zero()); - let mut buffer = vec![GF2::ZERO; Self::DEGREE * Self::PACK_SIZE]; + let mut buffer = vec![GF2::zero(); Self::DEGREE * Self::PACK_SIZE]; local_limbs.iter().enumerate().for_each(|(ith_limb, limb)| { let unpacked = limb.unpack(); @@ -363,7 +363,7 @@ impl ExtensionField for NeonGF2_128x8 { fn to_limbs(&self) -> Vec { let gf2_128s = self.unpack(); - let mut buffer = vec![GF2::ZERO; Self::DEGREE * Self::PACK_SIZE]; + let mut buffer = vec![GF2::zero(); Self::DEGREE * Self::PACK_SIZE]; gf2_128s .iter() .enumerate() diff --git a/arith/goldilocks/src/goldilocks.rs b/arith/goldilocks/src/goldilocks.rs index d6b3c0ace..e62d8602b 100644 --- a/arith/goldilocks/src/goldilocks.rs +++ b/arith/goldilocks/src/goldilocks.rs @@ -79,13 +79,13 @@ impl Field for Goldilocks { const SIZE: usize = 64 / 8; - const ZERO: Self = Goldilocks { v: 0 }; + // const ZERO: Self = Goldilocks { v: 0 }; - const ONE: Self = Goldilocks { v: 1 }; + // const ONE: Self = Goldilocks { v: 1 }; - const INV_2: Self = Goldilocks { - v: 0x7FFFFFFF80000001, - }; // (2^63 - 2^31 + 1) + // const INV_2: Self = Goldilocks { + // v: 0x7FFFFFFF80000001, + // }; // (2^63 - 2^31 + 1) const FIELD_SIZE: usize = 64; @@ -155,7 +155,7 @@ impl Neg for Goldilocks { type Output = Goldilocks; #[inline(always)] fn neg(self) -> Self::Output { - Goldilocks::ZERO - self + Goldilocks::zero() - self } } @@ -458,7 +458,7 @@ pub(crate) mod p2_instructions { v: inverse_2exp(k as usize), }; debug_assert!( - Goldilocks { v: *x } * res == Goldilocks::ONE, + Goldilocks { v: *x } * res == Goldilocks::one(), "bug in try_inverse_u64" ); Some(res.v) @@ -582,7 +582,7 @@ pub(crate) mod p2_instructions { // let mut j_less_than_v: Choice = 1.into(); // for j in 2..max_v { - // let tmp_is_one = tmp.ct_eq(&Goldilocks::ONE); + // let tmp_is_one = tmp.ct_eq(&Goldilocks::one()); // let squared = Goldilocks::conditional_select(&tmp, &z, tmp_is_one).square(); // tmp = Goldilocks::conditional_select(&squared, &tmp, tmp_is_one); // let new_z = Goldilocks::conditional_select(&z, &squared, tmp_is_one); @@ -592,7 +592,7 @@ pub(crate) mod p2_instructions { // } // let result = x * z; - // x = Goldilocks::conditional_select(&result, &x, b.ct_eq(&Goldilocks::ONE)); + // x = Goldilocks::conditional_select(&result, &x, b.ct_eq(&Goldilocks::one())); // z = z.square(); // b *= z; // v = k; diff --git a/arith/goldilocks/src/goldilocks_ext.rs b/arith/goldilocks/src/goldilocks_ext.rs index e4140c84a..b27b1dd49 100644 --- a/arith/goldilocks/src/goldilocks_ext.rs +++ b/arith/goldilocks/src/goldilocks_ext.rs @@ -1,12 +1,12 @@ -use std::{ - iter::{Product, Sum}, - ops::{Add, AddAssign, Mul, MulAssign, Neg, Sub, SubAssign}, -}; - use arith::{field_common, ExtensionField, FFTField, Field, SimdField}; + use ethnum::U256; use rand::RngCore; use serdes::ExpSerde; +use std::{ + iter::{Product, Sum}, + ops::{Add, AddAssign, Mul, MulAssign, Neg, Sub, SubAssign}, +}; use crate::{ goldilocks::{mod_reduce_u64, Goldilocks}, @@ -27,17 +27,17 @@ impl Field for GoldilocksExt2 { const FIELD_SIZE: usize = 64 * 2; - const ZERO: Self = GoldilocksExt2 { - v: [Goldilocks::ZERO, Goldilocks::ZERO], - }; + // const ZERO: Self = GoldilocksExt2 { + // v: [Goldilocks::zero(), Goldilocks::zero()], + // }; - const ONE: Self = GoldilocksExt2 { - v: [Goldilocks::ONE, Goldilocks::ZERO], - }; + // const ONE: Self = GoldilocksExt2 { + // v: [Goldilocks::one(), Goldilocks::zero()], + // }; - const INV_2: Self = GoldilocksExt2 { - v: [Goldilocks::INV_2, Goldilocks::ZERO], - }; + // const INV_2: Self = GoldilocksExt2 { + // v: [Goldilocks::INV_2, Goldilocks::zero()], + // }; const MODULUS: U256 = Goldilocks::MODULUS; @@ -82,7 +82,7 @@ impl Field for GoldilocksExt2 { let a_pow_r_minus_1 = self.frobenius(); let a_pow_r = a_pow_r_minus_1 * *self; - debug_assert!(a_pow_r.v[1] == Goldilocks::ZERO); + debug_assert!(a_pow_r.v[1].is_zero()); let a_pow_r_inv = a_pow_r.v[0].inv().expect("inverse does not exist"); let res = [ @@ -124,9 +124,15 @@ impl ExtensionField for GoldilocksExt2 { const W: u32 = 7; // x^2 - 7 is the irreducible polynomial - const X: Self = GoldilocksExt2 { - v: [Goldilocks::ZERO, Goldilocks::ONE], - }; + // const X: Self = GoldilocksExt2 { + // v: [Goldilocks::zero(), Goldilocks::one()], + // }; + + fn x() -> Self { + Self { + v: [Goldilocks::zero(), Goldilocks::one()], + } + } type BaseField = Goldilocks; @@ -351,7 +357,7 @@ impl FFTField for GoldilocksExt2 { fn root_of_unity() -> Self { GoldilocksExt2 { v: [ - Goldilocks::ZERO, + Goldilocks::zero(), Goldilocks { v: 0xd95051a31cf4a6ef, }, @@ -391,7 +397,7 @@ impl GoldilocksExt2 { } let z0square = z0 * z0; - let mut res = [Goldilocks::ZERO; 2]; + let mut res = [Goldilocks::zero(); 2]; res[0] = arr[0] * z0; res[1] = arr[1] * z0square; diff --git a/arith/goldilocks/src/goldilocks_ext2x8.rs b/arith/goldilocks/src/goldilocks_ext2x8.rs index cf77151ce..b722ef3c7 100644 --- a/arith/goldilocks/src/goldilocks_ext2x8.rs +++ b/arith/goldilocks/src/goldilocks_ext2x8.rs @@ -5,7 +5,6 @@ use std::{ }; use arith::{field_common, ExtensionField, FFTField, Field, SimdField}; - use ethnum::U256; use rand::RngCore; use serdes::ExpSerde; @@ -71,7 +70,7 @@ impl From for GoldilocksExt2x8 { fn from(x: Goldilocksx8) -> Self { Self { c0: x, - c1: Goldilocksx8::ZERO, + c1: Goldilocksx8::zero(), } } } @@ -83,10 +82,17 @@ impl ExtensionField for GoldilocksExt2x8 { const W: u32 = 7; - const X: Self = Self { - c0: Goldilocksx8::ZERO, - c1: Goldilocksx8::ONE, - }; + // const X: Self = Self { + // c0: Goldilocksx8::zero(), + // c1: Goldilocksx8::one(), + // }; + + fn x() -> Self { + Self { + c0: Goldilocksx8::zero(), + c1: Goldilocksx8::one(), + } + } #[inline] fn mul_by_base_field(&self, base: &Self::BaseField) -> Self { @@ -158,29 +164,35 @@ impl Field for GoldilocksExt2x8 { const MODULUS: U256 = Goldilocks::MODULUS; - const ZERO: Self = Self { - c0: Goldilocksx8::ZERO, - c1: Goldilocksx8::ZERO, - }; + // const ZERO: Self = Self { + // c0: Goldilocksx8::zero(), + // c1: Goldilocksx8::zero(), + // }; - const ONE: Self = Self { - c0: Goldilocksx8::ONE, - c1: Goldilocksx8::ZERO, - }; + // const ONE: Self = Self { + // c0: Goldilocksx8::one(), + // c1: Goldilocksx8::zero(), + // }; - const INV_2: Self = Self { - c0: Goldilocksx8::INV_2, - c1: Goldilocksx8::ZERO, - }; + // const INV_2: Self = Self { + // c0: Goldilocksx8::INV_2, + // c1: Goldilocksx8::zero(), + // }; #[inline] fn zero() -> Self { - Self::ZERO + Self { + c0: Goldilocksx8::zero(), + c1: Goldilocksx8::zero(), + } } #[inline] fn one() -> Self { - Self::ONE + Self { + c0: Goldilocksx8::one(), + c1: Goldilocksx8::zero(), + } } #[inline] @@ -200,7 +212,7 @@ impl Field for GoldilocksExt2x8 { fn random_bool(mut rng: impl RngCore) -> Self { Self { c0: Goldilocksx8::random_bool(&mut rng), - c1: Goldilocksx8::ZERO, + c1: Goldilocksx8::zero(), } } @@ -293,7 +305,7 @@ impl From for GoldilocksExt2x8 { fn from(value: u32) -> Self { Self { c0: Goldilocksx8::from(value), - c1: Goldilocksx8::ZERO, + c1: Goldilocksx8::zero(), } } } @@ -358,7 +370,7 @@ impl FFTField for GoldilocksExt2x8 { fn root_of_unity() -> Self { let var = GoldilocksExt2 { v: [ - Goldilocks::ZERO, + Goldilocks::zero(), Goldilocks { v: 0xd95051a31cf4a6ef, }, diff --git a/arith/goldilocks/src/goldilocksx8/goldilocks_avx256.rs b/arith/goldilocks/src/goldilocksx8/goldilocks_avx256.rs index 9c60743b0..749a622cd 100644 --- a/arith/goldilocks/src/goldilocksx8/goldilocks_avx256.rs +++ b/arith/goldilocks/src/goldilocksx8/goldilocks_avx256.rs @@ -30,8 +30,8 @@ const PACKED_EPSILON: __m256i = unsafe { transmute([EPSILON; 4]) }; /// Packed zero const PACKED_0: __m256i = unsafe { transmute([0u64; 4]) }; -/// Packed inverse of 2 -const PACKED_INV_2: __m256i = unsafe { transmute([0x7FFFFFFF80000001u64; 4]) }; +// /// Packed inverse of 2 +// const PACKED_INV_2: __m256i = unsafe { transmute([0x7FFFFFFF80000001u64; 4]) }; #[derive(Debug, Clone, Copy)] pub struct AVXGoldilocks { @@ -66,19 +66,19 @@ impl Field for AVXGoldilocks { const SIZE: usize = 512 / 8; - const ZERO: Self = Self { - v: [PACKED_0, PACKED_0], - }; + // const ZERO: Self = Self { + // v: [PACKED_0, PACKED_0], + // }; - const ONE: Self = Self { - v: [unsafe { transmute::<[u64; 4], __m256i>([1; 4]) }, unsafe { - transmute::<[u64; 4], __m256i>([1; 4]) - }], - }; + // const ONE: Self = Self { + // v: [unsafe { transmute::<[u64; 4], __m256i>([1; 4]) }, unsafe { + // transmute::<[u64; 4], __m256i>([1; 4]) + // }], + // }; - const INV_2: Self = Self { - v: [PACKED_INV_2, PACKED_INV_2], - }; + // const INV_2: Self = Self { + // v: [PACKED_INV_2, PACKED_INV_2], + // }; const FIELD_SIZE: usize = 64; @@ -86,12 +86,18 @@ impl Field for AVXGoldilocks { #[inline(always)] fn zero() -> Self { - Self::ZERO + Self { + v: [PACKED_0, PACKED_0], + } } #[inline(always)] fn one() -> Self { - Self::ONE + Self { + v: [unsafe { transmute::<[u64; 4], __m256i>([1; 4]) }, unsafe { + transmute::<[u64; 4], __m256i>([1; 4]) + }], + } } #[inline(always)] diff --git a/arith/goldilocks/src/goldilocksx8/goldilocks_avx512.rs b/arith/goldilocks/src/goldilocksx8/goldilocks_avx512.rs index 3a19371ed..24b8f9efa 100644 --- a/arith/goldilocks/src/goldilocksx8/goldilocks_avx512.rs +++ b/arith/goldilocks/src/goldilocksx8/goldilocks_avx512.rs @@ -27,8 +27,9 @@ const PACKED_EPSILON: __m512i = unsafe { transmute([EPSILON; GOLDILOCKS_PACK_SIZ /// Packed zero const PACKED_0: __m512i = unsafe { transmute([0u64; GOLDILOCKS_PACK_SIZE]) }; -/// Packed inverse of 2 -const PACKED_INV_2: __m512i = unsafe { transmute([0x7FFFFFFF80000001u64; GOLDILOCKS_PACK_SIZE]) }; +// /// Packed inverse of 2 +// const PACKED_INV_2: __m512i = unsafe { transmute([0x7FFFFFFF80000001u64; GOLDILOCKS_PACK_SIZE]) +// }; #[derive(Debug, Clone, Copy)] pub struct AVXGoldilocks { @@ -62,13 +63,13 @@ impl Field for AVXGoldilocks { const SIZE: usize = 512 / 8; - const ZERO: Self = Self { v: PACKED_0 }; + // const ZERO: Self = Self { v: PACKED_0 }; - const ONE: Self = Self { - v: unsafe { transmute::<[u64; 8], __m512i>([1; GOLDILOCKS_PACK_SIZE]) }, - }; + // const ONE: Self = Self { + // v: unsafe { transmute::<[u64; 8], __m512i>([1; GOLDILOCKS_PACK_SIZE]) }, + // }; - const INV_2: Self = Self { v: PACKED_INV_2 }; + // const INV_2: Self = Self { v: PACKED_INV_2 }; const FIELD_SIZE: usize = 64; @@ -76,12 +77,14 @@ impl Field for AVXGoldilocks { #[inline(always)] fn zero() -> Self { - Self::ZERO + Self { v: PACKED_0 } } #[inline(always)] fn one() -> Self { - Self::ONE + Self { + v: unsafe { transmute::<[u64; 8], __m512i>([1; GOLDILOCKS_PACK_SIZE]) }, + } } #[inline(always)] diff --git a/arith/goldilocks/src/goldilocksx8/goldilocks_neon.rs b/arith/goldilocks/src/goldilocksx8/goldilocks_neon.rs index e89d57edf..f1c007408 100644 --- a/arith/goldilocks/src/goldilocksx8/goldilocks_neon.rs +++ b/arith/goldilocks/src/goldilocksx8/goldilocks_neon.rs @@ -31,17 +31,17 @@ impl Field for NeonGoldilocks { const FIELD_SIZE: usize = 64; - const ZERO: Self = Self { - v: [Goldilocks::ZERO; 8], - }; + // const ZERO: Self = Self { + // v: [Goldilocks::zero(); 8], + // }; - const ONE: Self = Self { - v: [Goldilocks::ONE; 8], - }; + // const ONE: Self = Self { + // v: [Goldilocks::one(); 8], + // }; - const INV_2: Self = Self { - v: [Goldilocks::INV_2; 8], - }; + // const INV_2: Self = Self { + // v: [Goldilocks::INV_2; 8], + // }; const MODULUS: U256 = Goldilocks::MODULUS; diff --git a/arith/goldilocks/src/tests.rs b/arith/goldilocks/src/tests.rs index a229cf6a8..208faf062 100644 --- a/arith/goldilocks/src/tests.rs +++ b/arith/goldilocks/src/tests.rs @@ -190,7 +190,7 @@ fn test_exponentiation() { fn test_special_values() { // Test INV_2 assert_eq!( - Goldilocks::INV_2 * Goldilocks::from(2u32), + Goldilocks::from(2u32).inv().unwrap() * Goldilocks::from(2u32), Goldilocks::one() ); @@ -206,7 +206,7 @@ fn test_special_values() { // Test extension field special values assert_eq!( - GoldilocksExt2::X * GoldilocksExt2::X, + GoldilocksExt2::x() * GoldilocksExt2::x(), GoldilocksExt2::from(Goldilocks::from(7u32)) ); } @@ -236,6 +236,6 @@ fn test_edge_cases() { // Test extension field edge cases assert!(GoldilocksExt2::zero().is_zero()); assert!(GoldilocksExt2::zero().inv().is_none()); - let x = GoldilocksExt2::X; + let x = GoldilocksExt2::x(); assert_eq!(x * x, GoldilocksExt2::from(Goldilocks::from(7u32))); } diff --git a/arith/mersenne31/Cargo.toml b/arith/mersenne31/Cargo.toml index cf9ac99ee..842d19ea9 100644 --- a/arith/mersenne31/Cargo.toml +++ b/arith/mersenne31/Cargo.toml @@ -9,9 +9,7 @@ gkr_hashers = { path = "../../hasher" } serdes = { path = "../../serdes" } ark-std.workspace = true -halo2curves.workspace = true log.workspace = true -rand.workspace = true thiserror.workspace = true ethnum.workspace = true diff --git a/arith/mersenne31/src/lib.rs b/arith/mersenne31/src/lib.rs index dca1d3ecd..476deff4c 100644 --- a/arith/mersenne31/src/lib.rs +++ b/arith/mersenne31/src/lib.rs @@ -15,10 +15,10 @@ mod poseidon; mod m31_ext3; pub use m31_ext3::M31Ext3; -/// Degree 6 extension field for Mersenne-31 -/// instantiated by degree 2 extension of degree 3 extension for Mersenne-31 -mod m31_ext6; -pub use m31_ext6::M31Ext6; +// /// Degree 6 extension field for Mersenne-31 +// /// instantiated by degree 2 extension of degree 3 extension for Mersenne-31 +// mod m31_ext6; +// pub use m31_ext6::M31Ext6; /// SIMDx16 for Degree 3 extension field for Mersenne-31 mod m31_ext3x16; diff --git a/arith/mersenne31/src/m31.rs b/arith/mersenne31/src/m31.rs index b1f44d367..50be1edde 100644 --- a/arith/mersenne31/src/m31.rs +++ b/arith/mersenne31/src/m31.rs @@ -5,8 +5,8 @@ use std::{ }; use arith::{field_common, Field, SimdField}; +use ark_std::rand::RngCore; use ethnum::U256; -use rand::RngCore; use serdes::{ExpSerde, SerdeResult}; pub const M31_MOD: u32 = 2147483647; @@ -100,11 +100,11 @@ impl Field for M31 { const SIZE: usize = 32 / 8; - const ZERO: Self = M31 { v: 0 }; + // const ZERO: Self = M31 { v: 0 }; - const ONE: Self = M31 { v: 1 }; + // const ONE: Self = M31 { v: 1 }; - const INV_2: M31 = M31 { v: 1 << 30 }; + // const INV_2: M31 = M31 { v: 1 << 30 }; const FIELD_SIZE: usize = 32; diff --git a/arith/mersenne31/src/m31_ext3.rs b/arith/mersenne31/src/m31_ext3.rs index 6c9338c41..9a68efe47 100644 --- a/arith/mersenne31/src/m31_ext3.rs +++ b/arith/mersenne31/src/m31_ext3.rs @@ -1,5 +1,5 @@ +use ark_std::rand::RngCore; use ethnum::U256; -use rand::RngCore; use std::{ iter::{Product, Sum}, mem::transmute, @@ -29,17 +29,17 @@ impl Field for M31Ext3 { const FIELD_SIZE: usize = 32 * 3; - const ZERO: Self = M31Ext3 { - v: [M31::ZERO, M31::ZERO, M31::ZERO], - }; + // const ZERO: Self = M31Ext3 { + // v: [M31::zero(), M31::zero(), M31::zero()], + // }; - const ONE: Self = M31Ext3 { - v: [M31::ONE, M31::ZERO, M31::ZERO], - }; + // const ONE: Self = M31Ext3 { + // v: [M31::one(), M31::zero(), M31::zero()], + // }; - const INV_2: M31Ext3 = M31Ext3 { - v: [M31::INV_2, M31 { v: 0 }, M31 { v: 0 }], - }; + // const INV_2: M31Ext3 = M31Ext3 { + // v: [M31::INV_2, M31 { v: 0 }, M31 { v: 0 }], + // }; const MODULUS: U256 = M31::MODULUS; @@ -118,9 +118,15 @@ impl ExtensionField for M31Ext3 { /// Extension Field const W: u32 = 5; - const X: Self = M31Ext3 { - v: [M31::ZERO, M31::ONE, M31::ZERO], - }; + // const X: Self = M31Ext3 { + // v: [M31::zero(), M31::one(), M31::zero()], + // }; + + fn x() -> Self { + M31Ext3 { + v: [M31::zero(), M31::one(), M31::zero()], + } + } /// Base field for the extension type BaseField = M31; diff --git a/arith/mersenne31/src/m31_ext3x16.rs b/arith/mersenne31/src/m31_ext3x16.rs index 48ed68c98..53bb6a1cf 100644 --- a/arith/mersenne31/src/m31_ext3x16.rs +++ b/arith/mersenne31/src/m31_ext3x16.rs @@ -4,6 +4,7 @@ use std::{ }; use arith::{field_common, ExtensionField, Field, SimdField}; +use ark_std::rand::RngCore; use ethnum::U256; use serdes::ExpSerde; @@ -95,9 +96,15 @@ impl ExtensionField for M31Ext3x16 { const W: u32 = 5; - const X: Self = M31Ext3x16 { - v: [M31x16::ZERO, M31x16::ONE, M31x16::ZERO], - }; + // const X: Self = M31Ext3x16 { + // v: [M31x16::zero(), M31x16::one(), M31x16::zero()], + // }; + + fn x() -> Self { + M31Ext3x16 { + v: [M31x16::zero(), M31x16::one(), M31x16::zero()], + } + } type BaseField = M31x16; @@ -173,17 +180,17 @@ impl Field for M31Ext3x16 { const FIELD_SIZE: usize = 32 * 3; - const ZERO: Self = Self { - v: [M31x16::ZERO; 3], - }; + // const ZERO: Self = Self { + // v: [M31x16::zero(); 3], + // }; - const ONE: Self = Self { - v: [M31x16::ONE, M31x16::ZERO, M31x16::ZERO], - }; + // const ONE: Self = Self { + // v: [M31x16::one(), M31x16::zero(), M31x16::zero()], + // }; - const INV_2: Self = Self { - v: [M31x16::INV_2, M31x16::ZERO, M31x16::ZERO], - }; + // const INV_2: Self = Self { + // v: [M31x16::INV_2, M31x16::zero(), M31x16::zero()], + // }; const MODULUS: U256 = M31::MODULUS; @@ -207,7 +214,7 @@ impl Field for M31Ext3x16 { } #[inline(always)] - fn random_unsafe(mut rng: impl rand::RngCore) -> Self { + fn random_unsafe(mut rng: impl RngCore) -> Self { M31Ext3x16 { v: [ M31x16::random_unsafe(&mut rng), @@ -218,7 +225,7 @@ impl Field for M31Ext3x16 { } #[inline(always)] - fn random_bool(mut rng: impl rand::RngCore) -> Self { + fn random_bool(mut rng: impl RngCore) -> Self { M31Ext3x16 { v: [ M31x16::random_bool(&mut rng), diff --git a/arith/mersenne31/src/m31_ext6.rs b/arith/mersenne31/src/m31_ext6.rs index d33d21b46..b24903831 100644 --- a/arith/mersenne31/src/m31_ext6.rs +++ b/arith/mersenne31/src/m31_ext6.rs @@ -23,23 +23,25 @@ impl Field for M31Ext6 { const FIELD_SIZE: usize = 32 * 6; - const ZERO: Self = M31Ext6 { - v: [M31Ext3::ZERO, M31Ext3::ZERO], - }; + // const ZERO: Self = M31Ext6 { + // v: [M31Ext3::zero(), M31Ext3::zero()], + // }; - const ONE: Self = M31Ext6 { - v: [M31Ext3::ONE, M31Ext3::ZERO], - }; + // const ONE: Self = M31Ext6 { + // v: [M31Ext3::one(), M31Ext3::zero()], + // }; - const INV_2: M31Ext6 = M31Ext6 { - v: [M31Ext3::INV_2, M31Ext3::ZERO], - }; + // const INV_2: M31Ext6 = M31Ext6 { + // v: [M31Ext3::INV_2, M31Ext3::zero()], + // }; const MODULUS: U256 = M31::MODULUS; #[inline(always)] fn zero() -> Self { - Self::ZERO + M31Ext6 { + v: [M31Ext3::zero(), M31Ext3::zero()], + } } #[inline(always)] @@ -49,7 +51,7 @@ impl Field for M31Ext6 { #[inline(always)] fn one() -> Self { - Self::ONE + Self::one() } fn random_unsafe(mut rng: impl RngCore) -> Self { @@ -63,7 +65,7 @@ impl Field for M31Ext6 { fn random_bool(mut rng: impl RngCore) -> Self { M31Ext6 { - v: [M31Ext3::random_bool(&mut rng), M31Ext3::ZERO], + v: [M31Ext3::random_bool(&mut rng), M31Ext3::zero()], } } @@ -125,7 +127,7 @@ impl ExtensionField for M31Ext6 { const W: u32 = (1 << 31) - 3; const X: Self = M31Ext6 { - v: [M31Ext3::ZERO, M31Ext3::ONE], + v: [M31Ext3::zero(), M31Ext3::one()], }; /// Base field for the extension @@ -209,7 +211,7 @@ impl From for M31Ext6 { #[inline(always)] fn from(x: u32) -> Self { Self { - v: [M31Ext3::from(x), M31Ext3::ZERO], + v: [M31Ext3::from(x), M31Ext3::zero()], } } } @@ -218,7 +220,7 @@ impl From for M31Ext6 { #[inline(always)] fn from(x: M31Ext3) -> Self { Self { - v: [x, M31Ext3::ZERO], + v: [x, M31Ext3::zero()], } } } @@ -260,7 +262,7 @@ fn mul_internal(a: &M31Ext6, b: &M31Ext6) -> M31Ext6 { #[inline(always)] fn square_internal(a: &[M31Ext3; 2]) -> [M31Ext3; 2] { - let mut res = [M31Ext3::ZERO; 2]; + let mut res = [M31Ext3::zero(); 2]; res[0] = a[0].square() - a[1].square().double(); res[1] = a[0] * a[1].double(); res diff --git a/arith/mersenne31/src/m31x16/m31_avx256.rs b/arith/mersenne31/src/m31x16/m31_avx256.rs index cf8a33de6..88aaec6ad 100644 --- a/arith/mersenne31/src/m31x16/m31_avx256.rs +++ b/arith/mersenne31/src/m31x16/m31_avx256.rs @@ -17,7 +17,7 @@ use crate::m31::{M31, M31_MOD}; const M31_PACK_SIZE: usize = 16; const PACKED_MOD: __m256i = unsafe { transmute([M31_MOD; M31_PACK_SIZE / 2]) }; const PACKED_0: __m256i = unsafe { transmute([0; M31_PACK_SIZE / 2]) }; -const PACKED_INV_2: __m256i = unsafe { transmute([1 << 30; M31_PACK_SIZE / 2]) }; +// const PACKED_INV_2: __m256i = unsafe { transmute([1 << 30; M31_PACK_SIZE / 2]) }; #[inline(always)] unsafe fn mod_reduce_epi32(x: __m256i) -> __m256i { @@ -64,17 +64,17 @@ impl Field for AVXM31 { // size in bytes const SIZE: usize = 512 / 8; - const ZERO: Self = Self { - v: [PACKED_0, PACKED_0], - }; + // const ZERO: Self = Self { + // v: [PACKED_0, PACKED_0], + // }; - const ONE: Self = Self { - v: unsafe { transmute::<[u32; 16], [__m256i; 2]>([1; M31_PACK_SIZE]) }, - }; + // const ONE: Self = Self { + // v: unsafe { transmute::<[u32; 16], [__m256i; 2]>([1; M31_PACK_SIZE]) }, + // }; - const INV_2: Self = Self { - v: [PACKED_INV_2, PACKED_INV_2], - }; + // const INV_2: Self = Self { + // v: [PACKED_INV_2, PACKED_INV_2], + // }; const FIELD_SIZE: usize = 32; @@ -301,7 +301,7 @@ impl SimdField for AVXM31 { buffer = (buffer & M31_MOD as u64) + (buffer >> 31); if buffer == M31_MOD as u64 { - Self::Scalar::ZERO + Self::Scalar::zero() } else { Self::Scalar { v: buffer as u32 } } diff --git a/arith/mersenne31/src/m31x16/m31_avx512.rs b/arith/mersenne31/src/m31x16/m31_avx512.rs index 57c993cbf..cd9189753 100644 --- a/arith/mersenne31/src/m31x16/m31_avx512.rs +++ b/arith/mersenne31/src/m31x16/m31_avx512.rs @@ -9,8 +9,8 @@ use std::{ }; use arith::{field_common, Field, SimdField}; +use ark_std::rand::{Rng, RngCore}; use ethnum::U256; -use rand::{Rng, RngCore}; use serdes::{ExpSerde, SerdeResult}; use crate::m31::{M31, M31_MOD}; @@ -18,7 +18,7 @@ use crate::m31::{M31, M31_MOD}; const M31_PACK_SIZE: usize = 16; const PACKED_MOD: __m512i = unsafe { transmute([M31_MOD; M31_PACK_SIZE]) }; const PACKED_0: __m512i = unsafe { transmute([0; M31_PACK_SIZE]) }; -const PACKED_INV_2: __m512i = unsafe { transmute([1 << 30; M31_PACK_SIZE]) }; +// const PACKED_INV_2: __m512i = unsafe { transmute([1 << 30; M31_PACK_SIZE]) }; #[inline(always)] unsafe fn mod_reduce_epi32(x: __m512i) -> __m512i { @@ -61,13 +61,13 @@ impl Field for AVXM31 { // size in bytes const SIZE: usize = 512 / 8; - const ZERO: Self = Self { v: PACKED_0 }; + // const ZERO: Self = Self { v: PACKED_0 }; - const ONE: Self = Self { - v: unsafe { transmute::<[u32; 16], __m512i>([1; M31_PACK_SIZE]) }, - }; + // const ONE: Self = Self { + // v: unsafe { transmute::<[u32; 16], __m512i>([1; M31_PACK_SIZE]) }, + // }; - const INV_2: Self = Self { v: PACKED_INV_2 }; + // const INV_2: Self = Self { v: PACKED_INV_2 }; const FIELD_SIZE: usize = 32; @@ -244,7 +244,7 @@ impl SimdField for AVXM31 { buffer = (buffer & M31_MOD as u64) + (buffer >> 31); if buffer == M31_MOD as u64 { - Self::Scalar::ZERO + Self::Scalar::zero() } else { Self::Scalar { v: buffer as u32 } } diff --git a/arith/mersenne31/src/m31x16/m31_neon.rs b/arith/mersenne31/src/m31x16/m31_neon.rs index 7d479f628..24de264f4 100644 --- a/arith/mersenne31/src/m31x16/m31_neon.rs +++ b/arith/mersenne31/src/m31x16/m31_neon.rs @@ -17,7 +17,7 @@ use crate::{m31::M31_MOD, M31}; const M31_PACK_SIZE: usize = 16; const PACKED_MOD: uint32x4_t = unsafe { transmute([M31_MOD; 4]) }; const PACKED_0: uint32x4_t = unsafe { transmute([0; 4]) }; -const PACKED_INV_2: uint32x4_t = unsafe { transmute([1 << 30; 4]) }; +// const PACKED_INV_2: uint32x4_t = unsafe { transmute([1 << 30; 4]) }; #[inline(always)] fn reduce_sum(x: uint32x4_t) -> uint32x4_t { @@ -69,15 +69,15 @@ impl Field for NeonM31 { const FIELD_SIZE: usize = 32; - const ZERO: Self = Self { v: [PACKED_0; 4] }; + // const ZERO: Self = Self { v: [PACKED_0; 4] }; - const ONE: Self = Self { - v: [unsafe { transmute::<[u32; 4], uint32x4_t>([1; 4]) }; 4], - }; + // const ONE: Self = Self { + // v: [unsafe { transmute::<[u32; 4], uint32x4_t>([1; 4]) }; 4], + // }; - const INV_2: Self = Self { - v: [PACKED_INV_2; 4], - }; + // const INV_2: Self = Self { + // v: [PACKED_INV_2; 4], + // }; const MODULUS: U256 = M31::MODULUS; @@ -322,7 +322,7 @@ impl SimdField for NeonM31 { buffer = (buffer & M31_MOD as u64) + (buffer >> 31); if buffer == M31_MOD as u64 { - Self::Scalar::ZERO + Self::Scalar::zero() } else { Self::Scalar { v: buffer as u32 } } diff --git a/arith/mersenne31/src/tests.rs b/arith/mersenne31/src/tests.rs index 7fdf9fb30..fb6f8c659 100644 --- a/arith/mersenne31/src/tests.rs +++ b/arith/mersenne31/src/tests.rs @@ -1,6 +1,6 @@ use arith::{ - random_extension_field_tests, random_fft_field_tests, random_field_tests, - random_inversion_tests, random_simd_field_tests, SimdField, + random_extension_field_tests, random_field_tests, random_inversion_tests, + random_simd_field_tests, SimdField, }; use arith::{random_from_limbs_to_limbs_tests, Field}; use ark_std::test_rng; @@ -10,7 +10,7 @@ use serdes::ExpSerde; use crate::{ m31::{mod_reduce_u32_safe, M31_MOD}, - M31Ext3, M31Ext3x16, M31Ext6, M31x16, M31, + M31Ext3, M31Ext3x16, M31x16, M31, }; fn get_avx_version() -> &'static str { @@ -76,10 +76,6 @@ fn test_ext_field() { random_extension_field_tests::("M31 Ext3".to_string()); random_simd_field_tests::("Simd M31 Ext3".to_string()); - random_field_tests::("M31 Ext6".to_string()); - random_extension_field_tests::("M31 Ext6".to_string()); - random_fft_field_tests::("M31 Ext6".to_string()); - random_field_tests::("Simd M31 Ext3".to_string()); random_extension_field_tests::("Simd M31 Ext3".to_string()); random_simd_field_tests::("Simd M31 Ext3".to_string()); diff --git a/arith/polynomials/Cargo.toml b/arith/polynomials/Cargo.toml index 62ffdf638..4127717c7 100644 --- a/arith/polynomials/Cargo.toml +++ b/arith/polynomials/Cargo.toml @@ -8,11 +8,11 @@ arith = { path = "../" } serdes = { path = "../../serdes" } ark-std.workspace = true -criterion.workspace = true -halo2curves.workspace = true -rand.workspace = true itertools.workspace = true +[dev-dependencies] +criterion.workspace = true + [[bench]] name = "mle_eval" harness = false diff --git a/arith/polynomials/benches/mle_eval.rs b/arith/polynomials/benches/mle_eval.rs index 920c933ed..14295e0fb 100644 --- a/arith/polynomials/benches/mle_eval.rs +++ b/arith/polynomials/benches/mle_eval.rs @@ -76,7 +76,11 @@ fn bench_eq_xr(c: &mut Criterion) { b.iter(|| { black_box({ let mut eq_x_r = vec![F::zero(); 1 << nv]; - EqPolynomial::::build_eq_x_r_with_buf(point.as_ref(), &F::ONE, &mut eq_x_r); + EqPolynomial::::build_eq_x_r_with_buf( + point.as_ref(), + &F::one(), + &mut eq_x_r, + ); }) }) }); diff --git a/arith/polynomials/src/eq.rs b/arith/polynomials/src/eq.rs index 81e391cd4..09b681fed 100644 --- a/arith/polynomials/src/eq.rs +++ b/arith/polynomials/src/eq.rs @@ -129,7 +129,7 @@ impl EqPolynomial { .map(|r_i| { let mut term = *r_i; if index & 1 == 0 { - term = F::ONE - term; + term = F::one() - term; } index >>= 1; diff --git a/arith/polynomials/src/mle.rs b/arith/polynomials/src/mle.rs index 55b23072e..5153f85a1 100644 --- a/arith/polynomials/src/mle.rs +++ b/arith/polynomials/src/mle.rs @@ -1,7 +1,7 @@ use std::ops::{Add, Index, IndexMut, Mul}; use arith::Field; -use ark_std::log2; +use ark_std::{log2, rand::RngCore}; use crate::{EqPolynomial, MultilinearExtension, MutableMultilinearExtension}; @@ -20,7 +20,7 @@ impl MultiLinearPoly { /// Sample a random polynomials. #[inline] - pub fn random(nv: usize, mut rng: impl rand::RngCore) -> Self { + pub fn random(nv: usize, mut rng: impl RngCore) -> Self { let coeff = (0..1 << nv).map(|_| F::random_unsafe(&mut rng)).collect(); Self { coeffs: coeff } } @@ -283,6 +283,6 @@ impl MutableMultilinearExtension for MultiLinearPoly { } fn lift_to_n_vars(&mut self, n_vars: usize) { - self.coeffs.resize(1 << n_vars, F::ZERO); + self.coeffs.resize(1 << n_vars, F::zero()); } } diff --git a/arith/polynomials/src/ref_mle.rs b/arith/polynomials/src/ref_mle.rs index e610638b5..aff19210b 100644 --- a/arith/polynomials/src/ref_mle.rs +++ b/arith/polynomials/src/ref_mle.rs @@ -27,7 +27,7 @@ pub trait MultilinearExtension: Index + Send + Sync + Add + Mul, { - let mut scratch = vec![EvalF::ZERO; self.hypercube_size()]; + let mut scratch = vec![EvalF::zero(); self.hypercube_size()]; self.evaluate_with_buffer(point, &mut scratch) } @@ -227,6 +227,6 @@ impl<'a, F: Field> MutableMultilinearExtension for MutRefMultiLinearPoly<'a, #[inline(always)] fn lift_to_n_vars(&mut self, n_vars: usize) { - self.coeffs.resize(1 << n_vars, F::ZERO); + self.coeffs.resize(1 << n_vars, F::zero()); } } diff --git a/arith/polynomials/src/tests.rs b/arith/polynomials/src/tests.rs index 45e344824..c690569e4 100644 --- a/arith/polynomials/src/tests.rs +++ b/arith/polynomials/src/tests.rs @@ -1,7 +1,6 @@ use super::*; -use arith::{FFTField, Field}; +use arith::{FFTField, Field, Fr}; use ark_std::test_rng; -use halo2curves::bn256::Fr; #[test] fn test_scaled_eq_xr() { @@ -65,7 +64,7 @@ fn test_eq_xr() { // expander let mut eq_x_r2 = vec![Fr::zero(); 1 << nv]; - EqPolynomial::::build_eq_x_r_with_buf(r.as_ref(), &Fr::ONE, &mut eq_x_r2); + EqPolynomial::::build_eq_x_r_with_buf(r.as_ref(), &Fr::one(), &mut eq_x_r2); assert_eq!(eq_x_r2, eq_x_r0); // jolt @@ -81,7 +80,7 @@ fn test_ref_multilinear_poly() { let es_len = 1 << nv; let es: Vec = (0..es_len).map(|_| Fr::random_unsafe(&mut rng)).collect(); let point: Vec = (0..nv).map(|_| Fr::random_unsafe(&mut rng)).collect(); - let mut scratch = vec![Fr::ZERO; es_len]; + let mut scratch = vec![Fr::zero(); es_len]; let mle_from_ref = RefMultiLinearPoly::::from_ref(&es); @@ -104,7 +103,7 @@ fn test_mut_ref_multilinear_poly() { let mut es: Vec = (0..es_len).map(|_| Fr::random_unsafe(&mut rng)).collect(); let es_cloned = es.clone(); let point: Vec = (0..nv).map(|_| Fr::random_unsafe(&mut rng)).collect(); - let mut scratch = vec![Fr::ZERO; es_len]; + let mut scratch = vec![Fr::zero(); es_len]; let mut mle_from_mut_ref = MutRefMultiLinearPoly::::from_ref(&mut es); @@ -212,19 +211,25 @@ fn test_univariate_poly_evaluation() { fn test_univariate_degree_one_quotient() { { // x^3 + 1 = (x + 1)(x^2 - x + 1) - let mut poly = UnivariatePoly::new(vec![Fr::ONE, Fr::ZERO, Fr::ZERO, Fr::ONE]); + let mut poly = UnivariatePoly::new(vec![Fr::one(), Fr::zero(), Fr::zero(), Fr::one()]); let point = -Fr::from(1u64); poly.root_vanishing_quotient(&[point]); - assert_eq!(poly.coeffs, vec![Fr::ONE, -Fr::ONE, Fr::ONE, Fr::ZERO]); + assert_eq!( + poly.coeffs, + vec![Fr::one(), -Fr::one(), Fr::one(), Fr::zero()] + ); } { // x^3 - 1 = (x-1)(x^2 + x + 1) - let poly = UnivariatePoly::new(vec![-Fr::ONE, Fr::ZERO, Fr::ZERO, Fr::ONE]); + let poly = UnivariatePoly::new(vec![-Fr::one(), Fr::zero(), Fr::zero(), Fr::one()]); let point = Fr::from(1u64); let (div, remainder) = poly.degree_one_quotient(point); - assert_eq!(div.coeffs, vec![Fr::ONE, Fr::ONE, Fr::ONE, Fr::ZERO]); - assert_eq!(remainder, Fr::ZERO) + assert_eq!( + div.coeffs, + vec![Fr::one(), Fr::one(), Fr::one(), Fr::zero()] + ); + assert_eq!(remainder, Fr::zero()); } { // x^3 + 6x^2 + 11x + 6 = (x + 1)(x + 2)(x + 3) @@ -255,7 +260,10 @@ fn test_univariate_degree_one_quotient() { Fr::from(6u64), Fr::from(1u64), ]); - poly.root_vanishing_quotient(&[-Fr::ONE, -Fr::from(2u64), -Fr::from(3u64)]); - assert_eq!(poly.coeffs, vec![Fr::ONE, Fr::ZERO, Fr::ZERO, Fr::ZERO]); + poly.root_vanishing_quotient(&[-Fr::one(), -Fr::from(2u64), -Fr::from(3u64)]); + assert_eq!( + poly.coeffs, + vec![Fr::one(), Fr::zero(), Fr::zero(), Fr::zero()] + ); } } diff --git a/arith/polynomials/src/univariate.rs b/arith/polynomials/src/univariate.rs index e74c5aaa3..ac463033f 100644 --- a/arith/polynomials/src/univariate.rs +++ b/arith/polynomials/src/univariate.rs @@ -1,6 +1,7 @@ use std::ops::{AddAssign, Index, IndexMut, MulAssign}; use arith::{FFTField, Field}; +use ark_std::rand::RngCore; use itertools::izip; #[derive(Debug, Clone, Default)] @@ -49,7 +50,7 @@ impl UnivariatePoly { /// Sample a random polynomials. #[inline] - pub fn random(degree: usize, mut rng: impl rand::RngCore) -> Self { + pub fn random(degree: usize, mut rng: impl RngCore) -> Self { let coeffs = (0..=degree).map(|_| F::random_unsafe(&mut rng)).collect(); Self { coeffs } } @@ -57,7 +58,7 @@ impl UnivariatePoly { /// Evaluation by Horner's rule #[inline] pub fn evaluate(&self, point: F) -> F { - let mut eval = F::ZERO; + let mut eval = F::zero(); self.coeffs.iter().rev().for_each(|t| { eval *= point; eval += *t @@ -81,7 +82,7 @@ impl UnivariatePoly { let final_remainder = div_coeffs[0]; let mut final_div_coeffs = div_coeffs[1..].to_owned(); - final_div_coeffs.resize(self.coeffs.len(), F::ZERO); + final_div_coeffs.resize(self.coeffs.len(), F::zero()); (Self::new(final_div_coeffs), final_remainder) } @@ -100,11 +101,12 @@ impl UnivariatePoly { self.coeffs[i - 1] += remainder; } - assert_eq!(self.coeffs[ith_root], F::ZERO); + assert_eq!(self.coeffs[ith_root], F::zero()); }); self.coeffs.drain(0..roots.len()); - self.coeffs.resize(self.coeffs.len() + roots.len(), F::ZERO); + self.coeffs + .resize(self.coeffs.len() + roots.len(), F::zero()); } } @@ -119,7 +121,7 @@ impl AddAssign<&Self> for UnivariatePoly { #[inline(always)] fn add_assign(&mut self, rhs: &Self) { if rhs.coeffs.len() > self.coeffs.len() { - self.coeffs.resize(rhs.coeffs.len(), F::ZERO); + self.coeffs.resize(rhs.coeffs.len(), F::zero()); } izip!(&mut self.coeffs, &rhs.coeffs).for_each(|(c, r)| *c += r); @@ -135,7 +137,7 @@ impl UnivariateLagrangePolynomial { } #[inline] - pub fn random(degree: usize, mut rng: impl rand::RngCore) -> Self { + pub fn random(degree: usize, mut rng: impl RngCore) -> Self { assert!((degree + 1).is_power_of_two()); let evals = (0..=degree).map(|_| F::random_unsafe(&mut rng)).collect(); Self { evals } @@ -148,10 +150,10 @@ impl UnivariateLagrangePolynomial { let omega = F::two_adic_generator(log_n); let omega_inv = omega.inv().unwrap(); - let nominator_prepare = point.exp(n as u128) - F::ONE; - let denominator_prepare = F::ONE.double().exp(log_n as u128); + let nominator_prepare = point.exp(n as u128) - F::one(); + let denominator_prepare = F::one().double().exp(log_n as u128); - let mut omega_i = F::ONE; + let mut omega_i = F::one(); let mut denominator = denominator_prepare; self.evals @@ -162,7 +164,7 @@ impl UnivariateLagrangePolynomial { let res = if nominator_vanisher.is_zero() { *e_i } else if nominator_prepare.is_zero() { - F::ZERO + F::zero() } else { let nominator = nominator_prepare * nominator_vanisher.inv().unwrap(); *e_i * nominator * denominator.inv().unwrap() @@ -214,11 +216,11 @@ impl EqUnivariatePoly { /// Evaluation in O(\log N) time #[inline] pub fn evaluate(&self, x: F) -> F { - let mut eval = F::ONE; + let mut eval = F::one(); let mut x_pow = x; self.point.iter().for_each(|e| { - eval *= x_pow * e + F::ONE - e; + eval *= x_pow * e + F::one() - e; x_pow = x_pow.square(); }); diff --git a/arith/src/bn254.rs b/arith/src/bn254.rs index a2628d823..ed83f0bc7 100644 --- a/arith/src/bn254.rs +++ b/arith/src/bn254.rs @@ -1,10 +1,11 @@ +use ark_ff::{FftField, Field as ArkField, PrimeField, Zero}; +use ark_std::{rand::RngCore, UniformRand}; use ethnum::U256; -use halo2curves::ff::{Field as Halo2Field, FromUniformBytes, PrimeField}; -use rand::RngCore; +use serdes::ExpSerde; use crate::{ExtensionField, FFTField, Field, SimdField}; -pub use halo2curves::bn256::Fr; +pub use ark_bn254::Fr; pub(crate) const MODULUS: U256 = U256([ 0x2833e84879b9709143e1f593f0000001, @@ -20,14 +21,15 @@ impl Field for Fr { const FIELD_SIZE: usize = 256; - /// zero - const ZERO: Self = Fr::zero(); + // /// zero + // const ZERO: Self = ::zero(); - /// One - const ONE: Self = Fr::one(); + // /// One + // const ONE: Self = ::one(); - /// Inverse of 2 - const INV_2: Self = Fr::TWO_INV; + // /// Inverse of 2 + // // FIXME + // const INV_2: Self = ::one(); /// MODULUS in [u64; 4] const MODULUS: U256 = MODULUS; @@ -38,18 +40,18 @@ impl Field for Fr { /// Zero element #[inline(always)] fn zero() -> Self { - Fr::zero() + ::zero() } #[inline(always)] fn is_zero(&self) -> bool { - *self == Fr::zero() + *self == ::zero() } /// Identity element #[inline(always)] fn one() -> Self { - Fr::one() + ::ONE } // ==================================== @@ -58,8 +60,8 @@ impl Field for Fr { /// create a random element from rng. /// test only -- the output may not be uniformly random. #[inline(always)] - fn random_unsafe(rng: impl RngCore) -> Self { - Fr::random(rng) + fn random_unsafe(mut rng: impl RngCore) -> Self { + Fr::rand(&mut rng) } /// create a random boolean element from rng @@ -77,22 +79,19 @@ impl Field for Fr { // TODO: better implementation fn from_uniform_bytes(bytes: &[u8]) -> Self { assert!(bytes.len() >= 32); - >::from_uniform_bytes( - &[&bytes[..32], [0u8; 32].as_slice()] - .concat() - .try_into() - .unwrap(), - ) + ::from_le_bytes_mod_order(&bytes[..32]) } #[inline(always)] fn from_u256(x: ethnum::U256) -> Self { - Fr::from_bytes(&(x % MODULUS).to_le_bytes()).unwrap() + ::from_le_bytes_mod_order(&x.to_le_bytes()) } #[inline(always)] fn to_u256(&self) -> ethnum::U256 { - ethnum::U256::from_le_bytes(self.to_bytes()) + let mut res = vec![]; + self.serialize_into(&mut res).unwrap(); + ethnum::U256::from_le_bytes(res.try_into().unwrap()) } // ==================================== @@ -114,13 +113,13 @@ impl Field for Fr { #[inline(always)] fn exp(&self, exp: u128) -> Self { let exp_limbs = [exp as u64, (exp >> 64) as u64]; - self.pow_vartime(exp_limbs) + self.pow(exp_limbs) } /// find the inverse of the element; return None if not exist #[inline(always)] fn inv(&self) -> Option { - self.invert().into() + self.inverse() } } @@ -158,7 +157,9 @@ impl ExtensionField for Fr { const W: u32 = 1; // placeholder, doesn't make sense for Fr - const X: Self = Fr::zero(); + fn x() -> Self { + Self::default() + } /// Base field for the extension type BaseField = Self; @@ -185,7 +186,7 @@ impl ExtensionField for Fr { #[inline(always)] fn from_limbs(limbs: &[Self::BaseField]) -> Self { if limbs.len() < Self::DEGREE { - Self::zero() + ::zero() } else { limbs[0] } @@ -199,9 +200,9 @@ impl ExtensionField for Fr { } impl FFTField for Fr { - const TWO_ADICITY: usize = ::S as usize; + const TWO_ADICITY: usize = ::TWO_ADICITY as usize; fn root_of_unity() -> Self { - ::ROOT_OF_UNITY + Self::TWO_ADIC_ROOT_OF_UNITY } } diff --git a/arith/src/bn254xn.rs b/arith/src/bn254xn.rs index 15bcb3ee9..c682b59a5 100644 --- a/arith/src/bn254xn.rs +++ b/arith/src/bn254xn.rs @@ -6,9 +6,10 @@ use std::{ ops::{Add, AddAssign, Mul, MulAssign, Neg, Sub, SubAssign}, }; +use ark_bn254::Fr; +use ark_ff::{Field as ArkField, PrimeField, UniformRand}; +use ark_std::rand::RngCore; use ethnum::U256; -use halo2curves::{bn256::Fr, ff::Field as _}; -use rand::RngCore; use serdes::ExpSerde; use crate::{rep_field_common, ExtensionField, Field, SimdField}; @@ -100,14 +101,14 @@ impl Field for FrxN { const FIELD_SIZE: usize = 256; - /// zero - const ZERO: Self = Self { v: [Fr::zero(); N] }; + // /// zero + // const ZERO: Self = Self { v: [Fr::zero(); N] }; - /// One - const ONE: Self = Self { v: [Fr::one(); N] }; + // /// One + // const ONE: Self = Self { v: [Fr::one(); N] }; - /// Inverse of 2 - const INV_2: Self = Self { v: [Fr::INV_2; N] }; + // /// Inverse of 2 + // const INV_2: Self = Self { v: [Fr::INV_2; N] }; /// MODULUS in [u64; 4] const MODULUS: U256 = super::bn254::MODULUS; @@ -140,7 +141,7 @@ impl Field for FrxN { #[inline(always)] fn random_unsafe(mut rng: impl RngCore) -> Self { Self { - v: std::array::from_fn(|_| Fr::random(&mut rng)), + v: std::array::from_fn(|_| Fr::rand(&mut rng)), } } @@ -176,7 +177,7 @@ impl Field for FrxN { #[inline(always)] fn from_u256(x: ethnum::U256) -> Self { - let v = Fr::from_bytes(&(x % Self::MODULUS).to_le_bytes()).unwrap(); + let v = Fr::from_le_bytes_mod_order(&(x % Self::MODULUS).to_le_bytes()); Self { v: [v; N] } } @@ -205,7 +206,7 @@ impl Field for FrxN { fn exp(&self, exp: u128) -> Self { let exp_limbs = [exp as u64, (exp >> 64) as u64]; Self { - v: std::array::from_fn(|i| self.v[i].pow_vartime(exp_limbs)), + v: std::array::from_fn(|i| self.v[i].pow(exp_limbs)), } } @@ -315,7 +316,9 @@ impl ExtensionField for FrxN { const W: u32 = 1; - const X: Self = Self::ZERO; + fn x() -> Self { + Self::default() + } type BaseField = Self; @@ -328,7 +331,7 @@ impl ExtensionField for FrxN { } fn mul_by_x(&self) -> Self { - self * Self::X + self * Self::x() } fn to_limbs(&self) -> Vec { diff --git a/arith/src/extension_field.rs b/arith/src/extension_field.rs index a291ac74a..2c6a59c69 100644 --- a/arith/src/extension_field.rs +++ b/arith/src/extension_field.rs @@ -14,7 +14,7 @@ pub trait ExtensionField: Mul + From + Field { const W: u32; /// x, i.e, 0 + x + 0 x^2 + 0 x^3 + ... - const X: Self; + fn x() -> Self; /// Base field for the extension type BaseField: Field + Send; diff --git a/arith/src/fft_field.rs b/arith/src/fft_field.rs index dd9fa52d8..86f86783f 100644 --- a/arith/src/fft_field.rs +++ b/arith/src/fft_field.rs @@ -43,7 +43,7 @@ pub trait FFTField: Field { let omega = Self::two_adic_generator(log_n); let omega_inv = omega.inv().unwrap(); - let n_inv = Self::ONE.double().exp(log_n as u128).inv().unwrap(); + let n_inv = Self::one().double().exp(log_n as u128).inv().unwrap(); radix2_fft_single_threaded(evals, omega_inv); evals.iter_mut().for_each(|x| *x *= n_inv); @@ -71,7 +71,9 @@ fn bit_reverse_swap(elems: &mut [F]) { // NOTE(HS) the invariant here is bit swap won't exceed the range, // so we choose to use unchecked to short wire the range check, // s.t., less instructions - unsafe { elems.swap_unchecked(swap_to, i) } + elems.swap(i, swap_to); + + // unsafe { elems.swap_unchecked(swap_to, i) } swap_count += 1; } } @@ -88,7 +90,7 @@ pub fn radix2_fft_single_threaded(coeffs: &mut [F], omega: F) { // precompute twiddle factors let twiddles: Vec<_> = (0..(n / 2)) - .scan(F::ONE, |w, _| { + .scan(F::one(), |w, _| { let tw = *w; *w *= ω Some(tw) @@ -124,8 +126,8 @@ pub fn radix2_fft_single_threaded(coeffs: &mut [F], omega: F) { #[cfg(test)] mod fft_test { + use ark_bn254::Fr; use ark_std::test_rng; - use halo2curves::bn256::Fr; use itertools::izip; use crate::{FFTField, Field}; diff --git a/arith/src/field.rs b/arith/src/field.rs index c876c3d28..050c83325 100644 --- a/arith/src/field.rs +++ b/arith/src/field.rs @@ -1,6 +1,5 @@ -use ark_std::Zero; +use ark_std::{rand::RngCore, Zero}; use ethnum::U256; -use rand::RngCore; use serdes::ExpSerde; use std::{ @@ -52,14 +51,14 @@ pub trait Field: /// Field element size in bits, e.g., log_2(modulus), rounded up to the next power of 2. const FIELD_SIZE: usize; - /// zero - const ZERO: Self; + // /// zero + // const ZERO: Self; - /// One - const ONE: Self; + // /// One + // const ONE: Self; - /// Inverse of 2 - const INV_2: Self; + // /// Inverse of 2 + // const INV_2: Self; /// MODULUS const MODULUS: U256; @@ -68,17 +67,19 @@ pub trait Field: // constants // ==================================== /// Zero element - fn zero() -> Self { - Self::ZERO - } + fn zero() -> Self; + // { + // Self::zero() + // } /// Is zero fn is_zero(&self) -> bool; /// Identity element - fn one() -> Self { - Self::ONE - } + fn one() -> Self; + // { + // Self::one() + // } // ==================================== // generators diff --git a/arith/src/lib.rs b/arith/src/lib.rs index e748f12cb..df47beb04 100644 --- a/arith/src/lib.rs +++ b/arith/src/lib.rs @@ -1,5 +1,5 @@ -#![cfg_attr(target_arch = "x86_64", feature(stdarch_x86_avx512))] -#![feature(slice_swap_unchecked)] +// #![cfg_attr(target_arch = "x86_64", feature(stdarch_x86_avx512))] +// #![feature(slice_swap_unchecked)] mod field; pub use field::*; @@ -24,11 +24,11 @@ mod macros; mod utils; pub use utils::*; -mod benches; -pub use benches::*; +// mod benches; +// pub use benches::*; mod tests; pub use tests::*; -mod monty; -pub use monty::*; +// mod monty; +// pub use monty::*; diff --git a/arith/src/macros.rs b/arith/src/macros.rs index 2ac8d3ff8..0aa8beeab 100644 --- a/arith/src/macros.rs +++ b/arith/src/macros.rs @@ -78,7 +78,7 @@ macro_rules! field_common { where I: Iterator, { - iter.fold(Self::ZERO, |acc, item| acc + item.borrow()) + iter.fold(Self::zero(), |acc, item| acc + item.borrow()) } } @@ -225,7 +225,7 @@ macro_rules! rep_field_common { where I: Iterator, { - iter.fold(Self::ZERO, |acc, item| acc + item.borrow()) + iter.fold(Self::zero(), |acc, item| acc + item.borrow()) } } @@ -234,7 +234,7 @@ macro_rules! rep_field_common { #[inline] fn neg(self) -> $field { - Self::ZERO - self + Self::zero() - self } } diff --git a/arith/src/monty.rs b/arith/src/monty.rs index 5f7679465..00a0ba644 100644 --- a/arith/src/monty.rs +++ b/arith/src/monty.rs @@ -15,6 +15,7 @@ use std::{ ops::{Add, AddAssign, Mul, MulAssign, Neg, Sub, SubAssign}, }; +use ark_std::rand::RngCore; use ethnum::U256; use serdes::{ExpSerde, SerdeResult}; use utils::{from_monty, monty_reduce, to_monty}; @@ -129,7 +130,7 @@ impl Neg for MontyField31 { #[inline(always)] fn neg(self) -> Self::Output { - Self::ZERO - self + Self::zero() - self } } @@ -256,7 +257,7 @@ where where I: Iterator, { - iter.fold(Self::ZERO, |acc, item| acc + item.borrow()) + iter.fold(Self::zero(), |acc, item| acc + item.borrow()) } } @@ -330,39 +331,39 @@ impl Field for MontyField31 { const FIELD_SIZE: usize = 32; - const ZERO: Self = Self::new(0); + // const ZERO: Self = Self::new(0); - const ONE: Self = Self::new(1); + // const ONE: Self = Self::new(1); const MODULUS: U256 = U256([MP::PRIME as u128, 0]); - // See test below - const INV_2: Self = Self { - value: 134217727, - _phantom: PhantomData, - }; + // // See test below + // const INV_2: Self = Self { + // value: 134217727, + // _phantom: PhantomData, + // }; #[inline(always)] fn zero() -> Self { - Self::ZERO + Self::new(0) } #[inline(always)] fn is_zero(&self) -> bool { - *self == Self::ZERO + *self == Self::zero() } #[inline(always)] fn one() -> Self { - Self::ONE + Self::new(1) } /// Uses rejection sampling to avoid bias. - fn random_unsafe(mut rng: impl rand::RngCore) -> Self { + fn random_unsafe(mut rng: impl RngCore) -> Self { Self::new(rng.next_u32()) } - fn random_bool(mut rng: impl rand::RngCore) -> Self { + fn random_bool(mut rng: impl RngCore) -> Self { (rng.next_u32() & 1).into() } diff --git a/arith/src/tests.rs b/arith/src/tests.rs index ce3f4bbec..9f241c8d9 100644 --- a/arith/src/tests.rs +++ b/arith/src/tests.rs @@ -1,12 +1,11 @@ -use ark_std::{end_timer, start_timer, test_rng}; +use ark_std::{end_timer, rand::RngCore, start_timer, test_rng}; use field::{ associativity_tests, commutativity_tests, identity_tests, random_addition_tests, random_doubling_tests, random_expansion_tests, random_multiplication_tests, random_negation_tests, random_serde_tests, random_squaring_tests, random_subtraction_tests, }; -use rand::RngCore; -use crate::{ExtensionField, FFTField, Field, SimdField}; +use crate::{ExtensionField, Field, SimdField}; #[cfg(test)] mod bn254; @@ -86,7 +85,7 @@ pub fn random_extension_field_tests(_name: String) { { let a = F::random_unsafe(&mut rng); - let b = F::X; + let b = F::x(); let ax = a.mul_by_x(); let ab = a * b; assert_eq!(ax, ab); @@ -193,106 +192,106 @@ pub fn random_simd_field_tests(_name: String) { } } -pub fn random_fft_field_tests(_name: String) { - let mut rng = test_rng(); - - for log_degree in [2, 3, 5, 10] { - let degree = 1 << log_degree; - - { - // (x+1)(x^2-1) = x^3 + x^2 - x - 1 - let mut a = vec![F::zero(); degree]; - let mut b = vec![F::zero(); degree]; - let mut c = vec![F::zero(); degree]; - a[0] = F::one(); - a[1] = F::one(); - b[0] = -F::one(); - b[2] = F::one(); - c[0] = -F::one(); - c[1] = -F::one(); - c[2] = F::one(); - c[3] = F::one(); - - F::fft_in_place(&mut a); - F::fft_in_place(&mut b); - - a.iter_mut().zip(b.iter()).for_each(|(a, b)| { - *a *= *b; - }); - - F::ifft_in_place(&mut a); - - assert_eq!(a, c); - } - - { - // (x^(n-1) + 1) * (x + 1) = x^(n-1) + x + 2 - let mut a = vec![F::zero(); degree]; - let mut b = vec![F::zero(); degree]; - let mut c = vec![F::zero(); degree]; - a[0] = F::one(); - a[degree - 1] = F::one(); - b[0] = F::one(); - b[1] = F::one(); - c[0] = F::ONE.double(); - c[1] = F::one(); - c[degree - 1] = F::one(); - - F::fft_in_place(&mut a); - F::fft_in_place(&mut b); - - a.iter_mut().zip(b.iter()).for_each(|(a, b)| { - *a *= *b; - }); - - F::ifft_in_place(&mut a); - - assert_eq!(a, c); - } - } - - for i in [1, 2, 3, 5, 10] { - let degree = 1 << i; - - let mut a = vec![F::zero(); degree]; - let mut b = vec![F::zero(); degree]; - - for i in 0..degree { - a[i] = F::random_unsafe(&mut rng); - b[i] = F::random_unsafe(&mut rng); - } - - let mut a2 = a.clone(); - - F::fft_in_place(&mut a2); - let mut a_add_b = a2.clone(); - let mut a_mul_b = a2.clone(); - - F::ifft_in_place(&mut a2); - assert_eq!(a, a2); - - let mut b2 = b.clone(); - - F::fft_in_place(&mut b2); - a_add_b.iter_mut().zip(b2.iter()).for_each(|(c, b)| *c += b); - a_mul_b.iter_mut().zip(b2.iter()).for_each(|(c, b)| *c *= b); - - F::ifft_in_place(&mut b2); - assert_eq!(b, b2); - - F::ifft_in_place(&mut a_add_b); - let a_add_b_2 = a - .iter() - .zip(b.iter()) - .map(|(&a, &b)| a + b) - .collect::>(); - assert_eq!(a_add_b, a_add_b_2); - - F::ifft_in_place(&mut a_mul_b); - let a_mul_b_2 = schoolbook_mul(&a, &b); - assert_eq!(a_mul_b, a_mul_b_2); - } -} +// pub fn random_fft_field_tests(_name: String) { +// let mut rng = test_rng(); + +// for log_degree in [2, 3, 5, 10] { +// let degree = 1 << log_degree; + +// { +// // (x+1)(x^2-1) = x^3 + x^2 - x - 1 +// let mut a = vec![F::zero(); degree]; +// let mut b = vec![F::zero(); degree]; +// let mut c = vec![F::zero(); degree]; +// a[0] = F::one(); +// a[1] = F::one(); +// b[0] = -F::one(); +// b[2] = F::one(); +// c[0] = -F::one(); +// c[1] = -F::one(); +// c[2] = F::one(); +// c[3] = F::one(); + +// F::fft_in_place(&mut a); +// F::fft_in_place(&mut b); + +// a.iter_mut().zip(b.iter()).for_each(|(a, b)| { +// *a *= *b; +// }); + +// F::ifft_in_place(&mut a); + +// assert_eq!(a, c); +// } + +// { +// // (x^(n-1) + 1) * (x + 1) = x^(n-1) + x + 2 +// let mut a = vec![F::zero(); degree]; +// let mut b = vec![F::zero(); degree]; +// let mut c = vec![F::zero(); degree]; +// a[0] = F::one(); +// a[degree - 1] = F::one(); +// b[0] = F::one(); +// b[1] = F::one(); +// c[0] = F::one().double(); +// c[1] = F::one(); +// c[degree - 1] = F::one(); + +// F::fft_in_place(&mut a); +// F::fft_in_place(&mut b); + +// a.iter_mut().zip(b.iter()).for_each(|(a, b)| { +// *a *= *b; +// }); + +// F::ifft_in_place(&mut a); + +// assert_eq!(a, c); +// } +// } + +// for i in [1, 2, 3, 5, 10] { +// let degree = 1 << i; + +// let mut a = vec![F::zero(); degree]; +// let mut b = vec![F::zero(); degree]; + +// for i in 0..degree { +// a[i] = F::random_unsafe(&mut rng); +// b[i] = F::random_unsafe(&mut rng); +// } + +// let mut a2 = a.clone(); + +// F::fft_in_place(&mut a2); +// let mut a_add_b = a2.clone(); +// let mut a_mul_b = a2.clone(); + +// F::ifft_in_place(&mut a2); +// assert_eq!(a, a2); + +// let mut b2 = b.clone(); + +// F::fft_in_place(&mut b2); +// a_add_b.iter_mut().zip(b2.iter()).for_each(|(c, b)| *c += b); +// a_mul_b.iter_mut().zip(b2.iter()).for_each(|(c, b)| *c *= b); + +// F::ifft_in_place(&mut b2); +// assert_eq!(b, b2); + +// F::ifft_in_place(&mut a_add_b); +// let a_add_b_2 = a +// .iter() +// .zip(b.iter()) +// .map(|(&a, &b)| a + b) +// .collect::>(); +// assert_eq!(a_add_b, a_add_b_2); + +// F::ifft_in_place(&mut a_mul_b); +// let a_mul_b_2 = schoolbook_mul(&a, &b); +// assert_eq!(a_mul_b, a_mul_b_2); +// } +// } /// school book multiplication /// output = a(x) * b(x) mod x^N - 1 mod MODULUS @@ -302,7 +301,7 @@ fn schoolbook_mul(a: &[F], b: &[F]) -> Vec { let degree = a.len(); assert_eq!(degree, b.len()); - let mut buf = vec![F::ZERO; degree << 1]; + let mut buf = vec![F::zero(); degree << 1]; for i in 0..degree { for j in 0..degree { diff --git a/arith/src/tests/bn254.rs b/arith/src/tests/bn254.rs index f1f37f456..3fbc1e6c8 100644 --- a/arith/src/tests/bn254.rs +++ b/arith/src/tests/bn254.rs @@ -1,5 +1,5 @@ +use ark_bn254::Fr; use ark_std::test_rng; -use halo2curves::bn256::Fr; use super::{ random_fft_field_tests, random_field_tests, random_from_limbs_to_limbs_tests, diff --git a/arith/src/tests/field.rs b/arith/src/tests/field.rs index 9f3b78fca..b86293760 100644 --- a/arith/src/tests/field.rs +++ b/arith/src/tests/field.rs @@ -1,5 +1,4 @@ -use ark_std::{end_timer, start_timer}; -use rand::RngCore; +use ark_std::{end_timer, rand::RngCore, start_timer}; use crate::Field; diff --git a/bin/Cargo.toml b/bin/Cargo.toml index 1a65d006a..8a7ca394f 100644 --- a/bin/Cargo.toml +++ b/bin/Cargo.toml @@ -5,16 +5,16 @@ edition = "2024" [dependencies] arith = { path = "../arith" } -babybear = { path = "../arith/babybear" } +# babybear = { path = "../arith/babybear" } config_macros = { path = "../config_macros" } circuit = { path = "../circuit" } -gf2 = { path = "../arith/gf2" } -gf2_128 = { path = "../arith/gf2_128" } +# gf2 = { path = "../arith/gf2" } +# gf2_128 = { path = "../arith/gf2_128" } gkr = { path = "../gkr" } gkr_engine = { path = "../gkr_engine" } gkr_hashers = { path = "../hasher" } -goldilocks = { path = "../arith/goldilocks" } -mersenne31 = { path = "../arith/mersenne31" } +# goldilocks = { path = "../arith/goldilocks" } +# mersenne31 = { path = "../arith/mersenne31" } poly_commit = { path = "../poly_commit" } polynomials = { path = "../arith/polynomials" } serdes = { path = "../serdes" } @@ -26,7 +26,7 @@ bytes.workspace = true chrono.workspace = true clap.workspace = true log.workspace = true -mpi.workspace = true +# mpi.workspace = true tokio.workspace = true warp.workspace = true diff --git a/circuit/Cargo.toml b/circuit/Cargo.toml index b7bc96e69..5038f4b02 100644 --- a/circuit/Cargo.toml +++ b/circuit/Cargo.toml @@ -14,11 +14,12 @@ ark-std.workspace = true bytes.workspace = true ethnum.workspace = true log.workspace = true -mpi.workspace = true -rand.workspace = true +# mpi.workspace = true thiserror.workspace = true +wasm-bindgen = "0.2.92" + [dev-dependencies] config_macros = { path = "../config_macros" } poly_commit = { path = "../poly_commit" } -mersenne31 = { path = "../arith/mersenne31"} +# mersenne31 = { path = "../arith/mersenne31"} diff --git a/circuit/src/ecc_circuit.rs b/circuit/src/ecc_circuit.rs index c05a23881..a96b0071c 100644 --- a/circuit/src/ecc_circuit.rs +++ b/circuit/src/ecc_circuit.rs @@ -1,19 +1,19 @@ +use ark_std::{cmp::max, collections::HashMap, fs, io::Cursor, vec, vec::Vec}; use gkr_engine::FieldEngine; use serdes::{ExpSerde, SerdeResult}; -use std::{cmp::max, collections::HashMap, fs, io::Cursor}; use crate::*; // recursive format used in compiler pub type SegmentId = usize; -#[derive(ExpSerde)] +#[derive(ExpSerde, Debug)] pub struct Allocation { pub i_offset: usize, pub o_offset: usize, } -#[derive(Default)] +#[derive(Default, Debug)] pub struct Segment { pub i_var_num: usize, pub o_var_num: usize, @@ -67,7 +67,7 @@ impl Segment { } } -#[derive(Default)] +#[derive(Default, Debug)] pub struct RecursiveCircuit { pub num_public_inputs: usize, pub num_outputs: usize, @@ -82,6 +82,8 @@ impl RecursiveCircuit { let file_bytes = fs::read(filename)?; let cursor = Cursor::new(file_bytes); + console_log!("Loading circuit from file: {}", filename); + ::deserialize_from(cursor) } diff --git a/circuit/src/layered.rs b/circuit/src/layered.rs index 6a3a33c57..b6b8e0e35 100644 --- a/circuit/src/layered.rs +++ b/circuit/src/layered.rs @@ -1,7 +1,7 @@ mod circuit; mod gates; mod serde; -mod shared_mem; +// mod shared_mem; pub use circuit::*; pub use gates::*; diff --git a/circuit/src/layered/circuit.rs b/circuit/src/layered/circuit.rs index d3ea99eaa..c2c8839ce 100644 --- a/circuit/src/layered/circuit.rs +++ b/circuit/src/layered/circuit.rs @@ -1,10 +1,11 @@ -use std::fs; -use std::io::Cursor; - use arith::{Field, SimdField}; +use ark_std::fs; +use ark_std::io::Cursor; +use ark_std::println; use ark_std::test_rng; -use gkr_engine::{root_println, FieldEngine, GKREngine, MPIConfig, MPIEngine, Transcript}; -use mpi::ffi::ompi_win_t; +use ark_std::{vec, vec::Vec}; +use gkr_engine::{FieldEngine, GKREngine, Transcript}; +// use mpi::ffi::ompi_win_t; use serdes::ExpSerde; use crate::*; @@ -149,7 +150,13 @@ impl Circuit { // Load a circuit from a file and flatten it // Used for verifier pub fn verifier_load_circuit>(filename: &str) -> Self { - let rc = RecursiveCircuit::::load(filename).unwrap(); + let rc = match RecursiveCircuit::::load(filename) { + Ok(circuit) => circuit, + Err(e) => { + console_log!("Failed to load circuit: {}", e); + return Self::default(); + } + }; let mut c = rc.flatten(); c.pre_process_gkr(); c @@ -170,138 +177,136 @@ impl Circuit { // Used in the mpi case, ok if mpi_size = 1, but // circuit.discard_control_of_shared_mem() and mpi_config.free_shared_mem(window) should be // called before the end of the program - pub fn prover_load_circuit>( - filename: &str, - mpi_config: &MPIConfig, - ) -> (Self, *mut ompi_win_t) { - let circuit = if mpi_config.is_root() { - let rc = RecursiveCircuit::::load(filename).unwrap(); - let circuit = rc.flatten(); - Some(circuit) - } else { - None - }; - - let (mut circuit, window) = mpi_config.consume_obj_and_create_shared(circuit); - circuit.pre_process_gkr(); - (circuit, window) - } - - pub fn load_witness_allow_padding_testing_only( - &mut self, - filename: &str, - mpi_config: &MPIConfig, - ) { - let file_bytes = fs::read(filename).unwrap(); - self.load_witness_bytes(&file_bytes, mpi_config, true, true); - } - - pub fn prover_load_witness_file(&mut self, filename: &str, mpi_config: &MPIConfig) { - let file_bytes = fs::read(filename) - .unwrap_or_else(|_| panic!("Failed to read witness file: {filename}")); - self.load_witness_bytes(&file_bytes, mpi_config, true, false); - } - - pub fn verifier_load_witness_file(&mut self, filename: &str, mpi_config: &MPIConfig) { - let file_bytes = fs::read(filename) - .unwrap_or_else(|_| panic!("Failed to read witness file: {filename}")); - self.load_witness_bytes(&file_bytes, mpi_config, false, false); - } - - pub fn load_witness_bytes( - &mut self, - file_bytes: &[u8], - mpi_config: &MPIConfig, - is_prover: bool, - allow_padding_for_testing: bool, // TODO: Consider remove this - ) { - let cursor = Cursor::new(file_bytes); - let mut witness = Witness::::deserialize_from(cursor).unwrap(); - - // sizes for a single piece of witness - let private_input_size = 1 << self.log_input_size(); - let public_input_size = witness.num_public_inputs_per_witness; - let total_size = private_input_size + public_input_size; - assert_eq!(witness.num_private_inputs_per_witness, private_input_size); - root_println!( - mpi_config, - "Witness loaded: {} private inputs, {} public inputs, x{} witnesses", - private_input_size, - public_input_size, - witness.num_witnesses - ); - - // the number of witnesses should be equal to the number of MPI processes * simd width - let desired_number_of_witnesses = C::get_field_pack_size() * mpi_config.world_size(); - - #[allow(clippy::comparison_chain)] - if witness.num_witnesses < desired_number_of_witnesses { - if !allow_padding_for_testing { - panic!( - "Not enough witness, expected {}, got {}", - desired_number_of_witnesses, witness.num_witnesses - ); - } else { - println!( - "Warning: padding witnesses, expected {}, got {}", - desired_number_of_witnesses, witness.num_witnesses - ); - let padding_vec = witness.values[0..total_size].to_vec(); - for _ in witness.num_witnesses..desired_number_of_witnesses { - witness.values.extend_from_slice(&padding_vec); - } - witness.num_witnesses = desired_number_of_witnesses; - } - } else if witness.num_witnesses > desired_number_of_witnesses { - println!( - "Warning: dropping additional witnesses, expected {}, got {}", - desired_number_of_witnesses, witness.num_witnesses - ); - witness - .values - .truncate(desired_number_of_witnesses * total_size); - witness.num_witnesses = desired_number_of_witnesses; - } - - if is_prover { - self.prover_process_witness(witness, mpi_config); - } else { - self.verifier_process_witness(witness, mpi_config); - } - } - - pub fn prover_process_witness(&mut self, witness: Witness, mpi_config: &MPIConfig) { - let rank = mpi_config.world_rank(); - let private_input_size = 1 << self.log_input_size(); - let public_input_size = witness.num_public_inputs_per_witness; - let total_size = - witness.num_private_inputs_per_witness + witness.num_public_inputs_per_witness; - let input = &witness.values[rank * total_size * C::get_field_pack_size() - ..(rank + 1) * total_size * C::get_field_pack_size()]; - let private_input = &mut self.layers[0].input_vals; - let public_input = &mut self.public_input; - - private_input.clear(); - public_input.clear(); - - for i in 0..private_input_size { - let mut private_wit_i = vec![]; - for j in 0..C::get_field_pack_size() { - private_wit_i.push(input[j * total_size + i]); - } - private_input.push(C::SimdCircuitField::pack(&private_wit_i)); - } - - for i in 0..public_input_size { - let mut public_wit_i = vec![]; - for j in 0..C::get_field_pack_size() { - public_wit_i.push(input[j * total_size + private_input_size + i]); - } - public_input.push(C::SimdCircuitField::pack(&public_wit_i)); - } + pub fn prover_load_circuit>(filename: &str) -> Self { + unimplemented!("not used by verifier"); + // let circuit = if mpi_config.is_root() { + // let rc = RecursiveCircuit::::load(filename).unwrap(); + // let circuit = rc.flatten(); + // Some(circuit) + // } else { + // None + // }; + + // let (mut circuit, window) = mpi_config.consume_obj_and_create_shared(circuit); + // circuit.pre_process_gkr(); + // (circuit, window) } - pub fn verifier_process_witness(&mut self, witness: Witness, mpi_config: &MPIConfig) { + // pub fn load_witness_allow_padding_testing_only( + // &mut self, + // filename: &str, + // mpi_config: &MPIConfig, + // ) { + // let file_bytes = fs::read(filename).unwrap(); + // self.load_witness_bytes(&file_bytes, mpi_config, true, true); + // } + + // pub fn prover_load_witness_file(&mut self, filename: &str, mpi_config: &MPIConfig) { + // let file_bytes = fs::read(filename) + // .unwrap_or_else(|_| panic!("Failed to read witness file: {filename}")); + // self.load_witness_bytes(&file_bytes, mpi_config, true, false); + // } + + // pub fn verifier_load_witness_file(&mut self, filename: &str, mpi_config: &MPIConfig) { + // let file_bytes = fs::read(filename) + // .unwrap_or_else(|_| panic!("Failed to read witness file: {filename}")); + // self.load_witness_bytes(&file_bytes, mpi_config, false, false); + // } + + // pub fn load_witness_bytes( + // &mut self, + // file_bytes: &[u8], + // mpi_config: &MPIConfig, + // is_prover: bool, + // allow_padding_for_testing: bool, // TODO: Consider remove this + // ) { + // let cursor = Cursor::new(file_bytes); + // let mut witness = Witness::::deserialize_from(cursor).unwrap(); + + // // sizes for a single piece of witness + // let private_input_size = 1 << self.log_input_size(); + // let public_input_size = witness.num_public_inputs_per_witness; + // let total_size = private_input_size + public_input_size; + // assert_eq!(witness.num_private_inputs_per_witness, private_input_size); + // root_println!( + // mpi_config, + // "Witness loaded: {} private inputs, {} public inputs, x{} witnesses", + // private_input_size, + // public_input_size, + // witness.num_witnesses + // ); + + // // the number of witnesses should be equal to the number of MPI processes * simd width + // let desired_number_of_witnesses = C::get_field_pack_size() * mpi_config.world_size(); + + // #[allow(clippy::comparison_chain)] + // if witness.num_witnesses < desired_number_of_witnesses { + // if !allow_padding_for_testing { + // panic!( + // "Not enough witness, expected {}, got {}", + // desired_number_of_witnesses, witness.num_witnesses + // ); + // } else { + // println!( + // "Warning: padding witnesses, expected {}, got {}", + // desired_number_of_witnesses, witness.num_witnesses + // ); + // let padding_vec = witness.values[0..total_size].to_vec(); + // for _ in witness.num_witnesses..desired_number_of_witnesses { + // witness.values.extend_from_slice(&padding_vec); + // } + // witness.num_witnesses = desired_number_of_witnesses; + // } + // } else if witness.num_witnesses > desired_number_of_witnesses { + // println!( + // "Warning: dropping additional witnesses, expected {}, got {}", + // desired_number_of_witnesses, witness.num_witnesses + // ); + // witness + // .values + // .truncate(desired_number_of_witnesses * total_size); + // witness.num_witnesses = desired_number_of_witnesses; + // } + + // if is_prover { + // self.prover_process_witness(witness, mpi_config); + // } else { + // self.verifier_process_witness(witness, mpi_config); + // } + // } + + // pub fn prover_process_witness(&mut self, witness: Witness, mpi_config: &MPIConfig) { + // let rank = mpi_config.world_rank(); + // let private_input_size = 1 << self.log_input_size(); + // let public_input_size = witness.num_public_inputs_per_witness; + // let total_size = + // witness.num_private_inputs_per_witness + witness.num_public_inputs_per_witness; + // let input = &witness.values[rank * total_size * C::get_field_pack_size() + // ..(rank + 1) * total_size * C::get_field_pack_size()]; + // let private_input = &mut self.layers[0].input_vals; + // let public_input = &mut self.public_input; + + // private_input.clear(); + // public_input.clear(); + + // for i in 0..private_input_size { + // let mut private_wit_i = vec![]; + // for j in 0..C::get_field_pack_size() { + // private_wit_i.push(input[j * total_size + i]); + // } + // private_input.push(C::SimdCircuitField::pack(&private_wit_i)); + // } + + // for i in 0..public_input_size { + // let mut public_wit_i = vec![]; + // for j in 0..C::get_field_pack_size() { + // public_wit_i.push(input[j * total_size + private_input_size + i]); + // } + // public_input.push(C::SimdCircuitField::pack(&public_wit_i)); + // } + // } + + pub fn verifier_process_witness(&mut self, witness: Witness, world_size: &usize) { let private_input_size = 1 << self.log_input_size(); let public_input_size = witness.num_public_inputs_per_witness; let total_size = @@ -310,7 +315,7 @@ impl Circuit { let public_input = &mut self.public_input; public_input.clear(); - for i_rank in 0..mpi_config.world_size() { + for i_rank in 0..*world_size { let input = &witness.values[i_rank * total_size * C::get_field_pack_size() ..(i_rank + 1) * total_size * C::get_field_pack_size()]; @@ -426,7 +431,7 @@ impl Circuit { input_relay_layer.add.push(GateAdd { i_ids: [i], o_id: i, - coef: C::CircuitField::ONE, + coef: C::CircuitField::one(), coef_type: CoefType::Constant, gate_type: 0, }); diff --git a/circuit/src/layered/serde.rs b/circuit/src/layered/serde.rs index 07a048354..9266991e0 100644 --- a/circuit/src/layered/serde.rs +++ b/circuit/src/layered/serde.rs @@ -1,6 +1,6 @@ -use std::io::{Read, Write}; - use arith::Field; +use ark_std::io::{Read, Write}; +use ark_std::{vec, vec::Vec}; use gkr_engine::FieldEngine; use serdes::{ExpSerde, SerdeResult}; @@ -35,7 +35,7 @@ impl ExpSerde for CoefType { } impl ExpSerde for Gate { - fn serialize_into(&self, mut writer: W) -> SerdeResult<()> { + fn serialize_into(&self, mut writer: W) -> SerdeResult<()> { for id in &self.i_ids { id.serialize_into(&mut writer)?; } @@ -73,7 +73,7 @@ impl ExpSerde for Gate { CoefType::Constant, C::CircuitField::deserialize_from(&mut reader)?, ), - 2 => (CoefType::Random, C::CircuitField::ZERO), + 2 => (CoefType::Random, C::CircuitField::zero()), 3 => { if INPUT_NUM > 0 { panic!("Public Input can only be used with constant gates") @@ -81,7 +81,7 @@ impl ExpSerde for Gate { ( CoefType::PublicInput(::deserialize_from(&mut reader)?), - C::CircuitField::ZERO, + C::CircuitField::zero(), ) } _ => unreachable!(), diff --git a/circuit/src/layered/shared_mem.rs b/circuit/src/layered/shared_mem.rs index b6d18e5c1..1dd5c9e79 100644 --- a/circuit/src/layered/shared_mem.rs +++ b/circuit/src/layered/shared_mem.rs @@ -1,6 +1,7 @@ use super::circuit::{Circuit, CircuitLayer, StructureInfo}; use super::gates::{GateAdd, GateConst, GateMul, GateUni}; +use ark_std::{vec, vec::Vec}; use gkr_engine::{FieldEngine, MPISharedMemory}; impl MPISharedMemory for CircuitLayer { diff --git a/circuit/src/lib.rs b/circuit/src/lib.rs index cfc327cc0..d849cd2cb 100644 --- a/circuit/src/lib.rs +++ b/circuit/src/lib.rs @@ -1,3 +1,5 @@ +#![no_std] + mod ecc_circuit; pub use ecc_circuit::*; @@ -9,3 +11,18 @@ pub use witness::*; mod serde; pub use serde::*; + +use ark_std::string::ToString; +use wasm_bindgen::prelude::wasm_bindgen; +// Import the `console.log` function from the `console` object +#[wasm_bindgen] +extern "C" { + #[wasm_bindgen(js_namespace = console)] + fn log(s: &str); +} + +#[macro_export] +// Define a macro to make console.log easier to use +macro_rules! console_log { + ($($t:tt)*) => (log(&format_args!($($t)*).to_string())) +} diff --git a/circuit/src/serde.rs b/circuit/src/serde.rs index 3c7cb6b45..397443ac4 100644 --- a/circuit/src/serde.rs +++ b/circuit/src/serde.rs @@ -1,24 +1,27 @@ use arith::Field; -use gkr_engine::FieldEngine; -use serdes::{ExpSerde, SerdeResult}; -use std::{ +use ark_std::string::ToString; +use ark_std::{ io::{Read, Write}, vec, + vec::Vec, }; +use gkr_engine::FieldEngine; +use serdes::{ExpSerde, SerdeResult}; use super::{Allocation, CoefType, Gate, RecursiveCircuit, Segment, Witness}; -use crate::{GateAdd, GateConst, GateMul, SegmentId}; +use crate::{console_log, log, GateAdd, GateConst, GateMul, SegmentId}; + pub struct CustomGateWrapper { pub custom_gate: Gate, } impl ExpSerde for CustomGateWrapper { - fn serialize_into(&self, mut _writer: W) -> SerdeResult<()> { + fn serialize_into(&self, mut _writer: W) -> SerdeResult<()> { todo!() } fn deserialize_from(mut reader: R) -> SerdeResult { - let gate_type = ::deserialize_from(&mut reader).unwrap(); + let gate_type = ::deserialize_from(&mut reader)?; let i_ids: [usize; INPUT_NUM] = as ExpSerde>::deserialize_from(&mut reader)? .try_into() .unwrap(); @@ -31,7 +34,7 @@ impl ExpSerde for CustomGateWrapper (CoefType::Random, C::CircuitField::ZERO), + 2 => (CoefType::Random, C::CircuitField::zero()), 3 => { if INPUT_NUM > 0 { panic!("Public Input can only be used with constant gates") @@ -39,7 +42,7 @@ impl ExpSerde for CustomGateWrapper::deserialize_from(&mut reader)?), - C::CircuitField::ZERO, + C::CircuitField::zero(), ) } _ => unreachable!(), @@ -58,7 +61,7 @@ impl ExpSerde for CustomGateWrapper ExpSerde for Segment { - fn serialize_into(&self, mut writer: W) -> SerdeResult<()> { + fn serialize_into(&self, mut writer: W) -> SerdeResult<()> { ::serialize_into(&self.i_var_num, &mut writer)?; ::serialize_into(&self.o_var_num, &mut writer)?; @@ -104,7 +107,7 @@ impl ExpSerde for Segment { } } -const VERSION_NUM: usize = 3914834606642317635; // b'CIRCUIT6' +const VERSION_NUM: u64 = 3914834606642317635; // b'CIRCUIT6' impl ExpSerde for RecursiveCircuit { fn serialize_into(&self, mut writer: W) -> SerdeResult<()> { @@ -122,17 +125,19 @@ impl ExpSerde for RecursiveCircuit { } fn deserialize_from(mut reader: R) -> SerdeResult { - let version_num = ::deserialize_from(&mut reader).unwrap(); - assert_eq!(version_num, VERSION_NUM); + console_log!("start deser"); + let version_num = ::deserialize_from(&mut reader)?; + // assert_eq!(version_num as u64, VERSION_NUM); + console_log!("Successfully loaded circuit version: {}", version_num); let expected_mod = ::MODULUS; let mut read_mod = [0u8; 32]; - reader.read_exact(&mut read_mod).unwrap(); + reader.read_exact(&mut read_mod)?; assert_eq!(read_mod, expected_mod.to_le_bytes()); Ok(RecursiveCircuit { - num_public_inputs: ::deserialize_from(&mut reader).unwrap(), - num_outputs: ::deserialize_from(&mut reader).unwrap(), - expected_num_output_zeros: ::deserialize_from(&mut reader).unwrap(), + num_public_inputs: ::deserialize_from(&mut reader)?, + num_outputs: ::deserialize_from(&mut reader)?, + expected_num_output_zeros: ::deserialize_from(&mut reader)?, segments: Vec::>::deserialize_from(&mut reader)?, layers: as ExpSerde>::deserialize_from(&mut reader)?, @@ -141,22 +146,20 @@ impl ExpSerde for RecursiveCircuit { } impl ExpSerde for Witness { - fn serialize_into(&self, mut _writer: W) -> SerdeResult<()> { + fn serialize_into(&self, mut _writer: W) -> SerdeResult<()> { todo!() } fn deserialize_from(mut reader: R) -> SerdeResult { - let num_witnesses = ::deserialize_from(&mut reader).unwrap(); - let num_private_inputs_per_witness = - ::deserialize_from(&mut reader).unwrap(); - let num_public_inputs_per_witness = - ::deserialize_from(&mut reader).unwrap(); - let _modulus = <[u64; 4]>::deserialize_from(&mut reader).unwrap(); + let num_witnesses = ::deserialize_from(&mut reader)?; + let num_private_inputs_per_witness = ::deserialize_from(&mut reader)?; + let num_public_inputs_per_witness = ::deserialize_from(&mut reader)?; + let _modulus = <[u64; 4]>::deserialize_from(&mut reader)?; let mut values = vec![]; for _ in 0..num_witnesses * (num_private_inputs_per_witness + num_public_inputs_per_witness) { - values.push(C::CircuitField::deserialize_from(&mut reader).unwrap()); + values.push(C::CircuitField::deserialize_from(&mut reader)?); } Ok(Self { diff --git a/circuit/src/witness.rs b/circuit/src/witness.rs index cb3c9b1c1..41d007770 100644 --- a/circuit/src/witness.rs +++ b/circuit/src/witness.rs @@ -1,3 +1,4 @@ +use ark_std::vec::Vec; use gkr_engine::FieldEngine; // A direct copy of the witness struct from ecc diff --git a/circuit/tests/shared_mem.rs b/circuit/tests/shared_mem.rs index 6e2c65f5b..a6acfde80 100644 --- a/circuit/tests/shared_mem.rs +++ b/circuit/tests/shared_mem.rs @@ -1,6 +1,7 @@ use std::sync::{Arc, Mutex}; use arith::Field; +use ark_std::test_rng; use circuit::Circuit; use config_macros::declare_gkr_config; use gkr_engine::{ @@ -70,7 +71,7 @@ fn load_circuit(mpi_config: &MPIConfig) -> Option proc_macro::TokenS impl<'a> GKREngine for #config_name<'a> { type FieldConfig = #field_config; - type MPIConfig = MPIConfig<'a>; + // type MPIConfig = MPIConfig<'a>; type TranscriptConfig = #transcript_type_expr; type PCSConfig = #polynomial_commitment_type_expr; const SCHEME: GKRScheme = #scheme_config; diff --git a/crosslayer_prototype/Cargo.toml b/crosslayer_prototype/Cargo.toml index 8dd51e708..973ef4a21 100644 --- a/crosslayer_prototype/Cargo.toml +++ b/crosslayer_prototype/Cargo.toml @@ -15,5 +15,5 @@ transcript = { path = "../transcript" } env_logger.workspace = true ethnum.workspace = true log.workspace = true -rand.workspace = true +# rand.workspace = true thiserror.workspace = true diff --git a/crosslayer_prototype/src/circuit_serde.rs b/crosslayer_prototype/src/circuit_serde.rs index bc1b6fc92..66f67136b 100644 --- a/crosslayer_prototype/src/circuit_serde.rs +++ b/crosslayer_prototype/src/circuit_serde.rs @@ -73,7 +73,7 @@ impl ExpSerde for ECCCrossLayerGate (CoefType::Random, C::CircuitField::ONE), + 2 => (CoefType::Random, C::CircuitField::one()), 3 => { if INPUT_NUM > 0 { panic!("Public Input can only be used with constant gates") @@ -81,7 +81,7 @@ impl ExpSerde for ECCCrossLayerGate::deserialize_from(&mut reader)?), - C::CircuitField::ZERO, + C::CircuitField::zero(), ) } _ => unreachable!(), diff --git a/crosslayer_prototype/src/gates.rs b/crosslayer_prototype/src/gates.rs index 2b8ade32e..3fd9d702c 100644 --- a/crosslayer_prototype/src/gates.rs +++ b/crosslayer_prototype/src/gates.rs @@ -65,7 +65,7 @@ impl CrossLayerRelay { ) -> Self { let o_id = rng.next_u64() as usize % output_size; let i_id = rng.next_u64() as usize % input_size; - let coef = C::CircuitField::ONE; // temporarily support one only + let coef = C::CircuitField::one(); // temporarily support one only Self { o_id, i_id, diff --git a/crosslayer_prototype/src/helper.rs b/crosslayer_prototype/src/helper.rs index 85fa19e19..20ae820b4 100644 --- a/crosslayer_prototype/src/helper.rs +++ b/crosslayer_prototype/src/helper.rs @@ -442,7 +442,7 @@ impl<'a, F: FieldEngine> CrossLayerScatterHelper<'a, F> { let eq_evals_at_rz = &mut self.sp.eq_evals_at_rz0; EqPolynomial::eq_eval_at( self.rz0, - &F::ChallengeField::ONE, + &F::ChallengeField::one(), eq_evals_at_rz, &mut self.sp.eq_evals_first_half, &mut self.sp.eq_evals_second_half, @@ -466,9 +466,9 @@ impl<'a, F: FieldEngine> CrossLayerScatterHelper<'a, F> { if !connections_at_i_layer.is_empty() { *cross_layer_size = connections_at_i_layer.len().next_power_of_two(); // TODO: Allocate this in scratchpad - cir_vals.resize(*cross_layer_size, F::SimdCircuitField::ZERO); - vals.resize(*cross_layer_size, F::Field::ZERO); - hg_vals.resize(*cross_layer_size, F::Field::ZERO); + cir_vals.resize(*cross_layer_size, F::SimdCircuitField::zero()); + vals.resize(*cross_layer_size, F::Field::zero()); + hg_vals.resize(*cross_layer_size, F::Field::zero()); for (idx, (o_id, i_id)) in connections_at_i_layer.iter().enumerate() { cir_vals[idx] = self.circuit_vals.vals[i_layer][*i_id]; @@ -531,7 +531,7 @@ impl<'a, F: FieldEngine> CrossLayerScatterHelper<'a, F> { EqPolynomial::::eq_eval_at( &self.rx, - &F::ChallengeField::ONE, + &F::ChallengeField::one(), eq_evals_at_rx, &mut self.sp.eq_evals_first_half, &mut self.sp.eq_evals_second_half, @@ -539,7 +539,7 @@ impl<'a, F: FieldEngine> CrossLayerScatterHelper<'a, F> { EqPolynomial::::eq_eval_at( &self.r_simd_next, - &F::ChallengeField::ONE, + &F::ChallengeField::one(), &mut self.sp.eq_evals_at_r_simd_at_layer[self.layer.layer_id], &mut self.sp.eq_evals_first_half, &mut self.sp.eq_evals_second_half, @@ -641,7 +641,7 @@ impl<'a, F: FieldEngine> CrossLayerGatherHelper<'a, F> { EqPolynomial::eq_eval_at( self.rz0, - &F::ChallengeField::ONE, + &F::ChallengeField::one(), eq_evals_at_rz, &mut self.sp.eq_evals_first_half, &mut self.sp.eq_evals_second_half, diff --git a/crosslayer_prototype/src/scratchpad.rs b/crosslayer_prototype/src/scratchpad.rs index 1ba837483..01a892171 100644 --- a/crosslayer_prototype/src/scratchpad.rs +++ b/crosslayer_prototype/src/scratchpad.rs @@ -52,9 +52,12 @@ impl CrossLayerProverScratchPad { cross_layer_circuit_vals: vec![vec![]; n_layers], cross_layer_evals: vec![vec![]; n_layers], cross_layer_hg_evals: vec![vec![]; n_layers], - cross_layer_completed_values: vec![F::Field::ONE; n_layers], + cross_layer_completed_values: vec![F::Field::one(); n_layers], eq_evals_at_r_simd_at_layer: vec![ - vec![F::ChallengeField::ONE; F::get_field_pack_size()]; + vec![ + F::ChallengeField::one(); + F::get_field_pack_size() + ]; n_layers ], @@ -76,7 +79,7 @@ impl CrossLayerProverScratchPad { mpi_world_size ) ], - phase2_coef: F::ChallengeField::ZERO, + phase2_coef: F::ChallengeField::zero(), } } } diff --git a/gkr/Cargo.toml b/gkr/Cargo.toml index 6f395570f..65e0ddace 100644 --- a/gkr/Cargo.toml +++ b/gkr/Cargo.toml @@ -5,15 +5,15 @@ edition = "2021" [dependencies] arith = { path = "../arith" } -babybear = { path = "../arith/babybear" } +# babybear = { path = "../arith/babybear" } config_macros = { path = "../config_macros" } circuit = { path = "../circuit" } -gf2 = { path = "../arith/gf2" } -gf2_128 = { path = "../arith/gf2_128" } +# gf2 = { path = "../arith/gf2" } +# gf2_128 = { path = "../arith/gf2_128" } gkr_engine = { path = "../gkr_engine" } gkr_hashers = { path = "../hasher" } -goldilocks = { path = "../arith/goldilocks" } -mersenne31 = { path = "../arith/mersenne31" } +# goldilocks = { path = "../arith/goldilocks" } +# mersenne31 = { path = "../arith/mersenne31" } poly_commit = { path = "../poly_commit" } polynomials = { path = "../arith/polynomials" } serdes = { path = "../serdes" } @@ -24,10 +24,9 @@ utils = { path = "../utils" } ark-std.workspace = true env_logger.workspace = true ethnum.workspace = true -halo2curves.workspace = true log.workspace = true -mpi.workspace = true -rand.workspace = true +# mpi.workspace = true +# rand.workspace = true rayon.workspace = true sha2.workspace = true thiserror.workspace = true diff --git a/gkr/src/prover/snark.rs b/gkr/src/prover/snark.rs index 28a18f7f4..4b2f3fd32 100644 --- a/gkr/src/prover/snark.rs +++ b/gkr/src/prover/snark.rs @@ -202,7 +202,7 @@ impl Prover<'_, Cfg> { inputs.lift_to_n_vars(original_input_vars); open_at.rz.resize( original_input_vars, - ::ChallengeField::ZERO, + ::ChallengeField::zero(), ); if self.mpi_config.is_root() { diff --git a/gkr/src/tests/gkr_correctness.rs b/gkr/src/tests/gkr_correctness.rs index 73b8e7e25..91272ce3c 100644 --- a/gkr/src/tests/gkr_correctness.rs +++ b/gkr/src/tests/gkr_correctness.rs @@ -263,7 +263,7 @@ fn test_gkr_correctness_helper( let mut public_input_gathered = if mpi_config.is_root() { vec![ - ::SimdCircuitField::ZERO; + ::SimdCircuitField::zero(); circuit.public_input.len() * mpi_config.world_size() ] } else { diff --git a/gkr/src/verifier/common.rs b/gkr/src/verifier/common.rs index c0dcc9e94..60538f4ed 100644 --- a/gkr/src/verifier/common.rs +++ b/gkr/src/verifier/common.rs @@ -152,7 +152,7 @@ pub fn sumcheck_verify_gkr_layer( verified &= sum == vx_claim * vy_claim * GKRVerifierHelper::eval_mul(&layer.mul, sp); Some(vy_claim) } else { - verified &= sum == F::ChallengeField::ZERO; + verified &= sum == F::ChallengeField::zero(); None }; diff --git a/gkr/src/verifier/gkr_square.rs b/gkr/src/verifier/gkr_square.rs index 9487e3cbb..f51942888 100644 --- a/gkr/src/verifier/gkr_square.rs +++ b/gkr/src/verifier/gkr_square.rs @@ -141,7 +141,7 @@ pub fn sumcheck_verify_gkr_square_layer( + v_claim.exp(5) * GKRVerifierHelper::eval_pow_5(&layer.uni, sp); transcript.append_field_element(&v_claim); - verified &= sum == C::ChallengeField::ZERO; + verified &= sum == C::ChallengeField::zero(); *current_claim = v_claim; verified diff --git a/gkr_engine/Cargo.toml b/gkr_engine/Cargo.toml index ae021c3c7..00feacb0d 100644 --- a/gkr_engine/Cargo.toml +++ b/gkr_engine/Cargo.toml @@ -5,17 +5,18 @@ edition = "2021" [dependencies] arith = { path = "../arith" } -babybear = { path = "../arith/babybear" } -gf2 = { path = "../arith/gf2" } -gf2_128 = { path = "../arith/gf2_128" } -goldilocks = { path = "../arith/goldilocks" } -mersenne31 = { path = "../arith/mersenne31" } +# babybear = { path = "../arith/babybear" } +# gf2 = { path = "../arith/gf2" } +# gf2_128 = { path = "../arith/gf2_128" } +# goldilocks = { path = "../arith/goldilocks" } +# mersenne31 = { path = "../arith/mersenne31" } polynomials = { path = "../arith/polynomials"} serdes = { path = "../serdes" } + +ark-std.workspace = true thiserror.workspace = true -mpi.workspace = true -rand.workspace = true +# mpi.workspace = true itertools.workspace = true [dev-dependencies] diff --git a/gkr_engine/src/field_engine.rs b/gkr_engine/src/field_engine.rs index d49d2bfad..b0c431e33 100644 --- a/gkr_engine/src/field_engine.rs +++ b/gkr_engine/src/field_engine.rs @@ -1,19 +1,19 @@ -mod babybear_x16; +// mod babybear_x16; mod bn254; -mod bn254_x_n; +// mod bn254_x_n; mod definition; -mod gf2_ext128; -mod goldilocks_x1; -mod goldilocks_x8; -mod m31_x1; -mod m31_x16; +// mod gf2_ext128; +// mod goldilocks_x1; +// mod goldilocks_x8; +// mod m31_x1; +// mod m31_x16; -pub use babybear_x16::*; +// pub use babybear_x16::*; pub use bn254::*; -pub use bn254_x_n::*; +// pub use bn254_x_n::*; pub use definition::*; -pub use gf2_ext128::*; -pub use goldilocks_x1::*; -pub use goldilocks_x8::*; -pub use m31_x1::*; -pub use m31_x16::*; +// pub use gf2_ext128::*; +// pub use goldilocks_x1::*; +// pub use goldilocks_x8::*; +// pub use m31_x1::*; +// pub use m31_x16::*; diff --git a/gkr_engine/src/field_engine/definition.rs b/gkr_engine/src/field_engine/definition.rs index a102a942f..540239a80 100644 --- a/gkr_engine/src/field_engine/definition.rs +++ b/gkr_engine/src/field_engine/definition.rs @@ -5,7 +5,7 @@ use std::ops::{Add, Mul}; use arith::{ExtensionField, Field, SimdField}; use polynomials::MultiLinearPoly; -use crate::{ExpanderSingleVarChallenge, MPIEngine}; +use crate::ExpanderSingleVarChallenge; #[derive(Debug, Clone, PartialEq, Default)] pub enum FieldType { @@ -105,35 +105,36 @@ pub trait FieldEngine: Default + Debug + Clone + Send + Sync + PartialEq + 'stat // x_mpi: &[Self::ChallengeField], scratch_field: &mut [Self::Field], scratch_challenge_field: &mut [Self::ChallengeField], - mpi_config: &impl MPIEngine, + // mpi_config: &impl MPIEngine, ) -> Self::ChallengeField { - assert!( - scratch_challenge_field.len() - >= 1 << cmp::max(challenge.r_simd.len(), challenge.r_mpi.len()) - ); - - let local_simd = - Self::eval_circuit_vals_at_challenge(local_evals, &challenge.rz, scratch_field); - let local_simd_unpacked = local_simd.unpack(); - let local_v = MultiLinearPoly::evaluate_with_buffer( - &local_simd_unpacked, - &challenge.r_simd, - scratch_challenge_field, - ); - - if mpi_config.is_root() { - let mut claimed_v_gathering_buffer = - vec![Self::ChallengeField::zero(); mpi_config.world_size()]; - mpi_config.gather_vec(&[local_v], &mut claimed_v_gathering_buffer); - MultiLinearPoly::evaluate_with_buffer( - &claimed_v_gathering_buffer, - &challenge.r_mpi, - scratch_challenge_field, - ) - } else { - mpi_config.gather_vec(&[local_v], &mut vec![]); - Self::ChallengeField::zero() - } + unimplemented!("not used by verifier") + // assert!( + // scratch_challenge_field.len() + // >= 1 << cmp::max(challenge.r_simd.len(), challenge.r_mpi.len()) + // ); + + // let local_simd = + // Self::eval_circuit_vals_at_challenge(local_evals, &challenge.rz, scratch_field); + // let local_simd_unpacked = local_simd.unpack(); + // let local_v = MultiLinearPoly::evaluate_with_buffer( + // &local_simd_unpacked, + // &challenge.r_simd, + // scratch_challenge_field, + // ); + + // if mpi_config.is_root() { + // let mut claimed_v_gathering_buffer = + // vec![Self::ChallengeField::zero(); mpi_config.world_size()]; + // mpi_config.gather_vec(&[local_v], &mut claimed_v_gathering_buffer); + // MultiLinearPoly::evaluate_with_buffer( + // &claimed_v_gathering_buffer, + // &challenge.r_mpi, + // scratch_challenge_field, + // ) + // } else { + // mpi_config.gather_vec(&[local_v], &mut vec![]); + // Self::ChallengeField::zero() + // } } /// This assumes only a single core holds all the evals, and evaluate it locally diff --git a/gkr_engine/src/lib.rs b/gkr_engine/src/lib.rs index 6396924ca..638a0148f 100644 --- a/gkr_engine/src/lib.rs +++ b/gkr_engine/src/lib.rs @@ -12,18 +12,18 @@ //! - A Config is a struct that implements the Engine trait and contains the parameters for the GKR //! protocol #![allow(clippy::manual_div_ceil)] -#![feature(associated_type_defaults)] +// #![feature(associated_type_defaults)] mod errors; mod field_engine; -mod mpi_engine; +// mod mpi_engine; mod poly_commit; mod scheme; mod transcript; pub use errors::*; pub use field_engine::*; -pub use mpi_engine::*; +// pub use mpi_engine::*; pub use poly_commit::*; pub use scheme::*; pub use transcript::*; @@ -65,8 +65,8 @@ pub trait GKREngine: Send + Sync { /// Configuration for field arithmetic operations type FieldConfig: FieldEngine; - /// Configuration for distributed computing operations - type MPIConfig: MPIEngine; + // /// Configuration for distributed computing operations + // type MPIConfig: MPIEngine; /// Configuration for transcript generation over the challenge field type TranscriptConfig: Transcript; diff --git a/gkr_engine/src/mpi_engine/engine.rs b/gkr_engine/src/mpi_engine/engine.rs index f460677f2..1c64dc758 100644 --- a/gkr_engine/src/mpi_engine/engine.rs +++ b/gkr_engine/src/mpi_engine/engine.rs @@ -269,7 +269,7 @@ impl<'a> MPIEngine for MPIConfig<'a> { if self.world_size == 1 { local_vec.to_vec() } else if self.world_rank == Self::ROOT_RANK { - let mut global_vec = vec![F::ZERO; local_vec.len() * (self.world_size as usize)]; + let mut global_vec = vec![F::zero(); local_vec.len() * (self.world_size as usize)]; self.gather_vec(local_vec, &mut global_vec); for i in 0..local_vec.len() { for j in 1..(self.world_size as usize) { @@ -292,8 +292,8 @@ impl<'a> MPIEngine for MPIConfig<'a> { // but coef[0] is always one in our use case of self.world_size = 1 local_vec.to_vec() } else if self.world_rank == Self::ROOT_RANK { - let mut global_vec = vec![F::ZERO; local_vec.len() * (self.world_size as usize)]; - let mut ret = vec![F::ZERO; local_vec.len()]; + let mut global_vec = vec![F::zero(); local_vec.len() * (self.world_size as usize)]; + let mut ret = vec![F::zero(); local_vec.len()]; self.gather_vec(local_vec, &mut global_vec); for i in 0..local_vec.len() { for j in 0..(self.world_size as usize) { @@ -303,7 +303,7 @@ impl<'a> MPIEngine for MPIConfig<'a> { ret } else { self.gather_vec(local_vec, &mut vec![]); - vec![F::ZERO; local_vec.len()] + vec![F::zero(); local_vec.len()] } } diff --git a/gkr_engine/src/mpi_engine/tests.rs b/gkr_engine/src/mpi_engine/tests.rs index ff9d9ed87..817790354 100644 --- a/gkr_engine/src/mpi_engine/tests.rs +++ b/gkr_engine/src/mpi_engine/tests.rs @@ -9,13 +9,13 @@ use crate::{MPIConfig, MPIEngine}; fn test_gather_vec_helper(mpi_config: &MPIConfig) { const TEST_SIZE: usize = (1 << 10) + 1; - let mut local_vec = vec![M31::ZERO; TEST_SIZE]; + let mut local_vec = vec![M31::zero(); TEST_SIZE]; for i in 0..TEST_SIZE { local_vec[i] = M31::from((mpi_config.world_rank() * TEST_SIZE + i) as u32); } let mut global_vec = if mpi_config.is_root() { - vec![M31::ZERO; TEST_SIZE * mpi_config.world_size()] + vec![M31::zero(); TEST_SIZE * mpi_config.world_size()] } else { vec![] }; diff --git a/gkr_engine/src/poly_commit/definition.rs b/gkr_engine/src/poly_commit/definition.rs index 7c3acb6aa..d1ae03ce6 100644 --- a/gkr_engine/src/poly_commit/definition.rs +++ b/gkr_engine/src/poly_commit/definition.rs @@ -1,9 +1,9 @@ +use ark_std::rand::RngCore; use polynomials::MultilinearExtension; -use rand::RngCore; use serdes::ExpSerde; use std::{fmt::Debug, str::FromStr}; -use crate::{ExpErrors, ExpanderSingleVarChallenge, FieldEngine, MPIEngine, Transcript}; +use crate::{ExpErrors, ExpanderSingleVarChallenge, FieldEngine, Transcript}; pub trait StructuredReferenceString { type PKey: Clone + Debug + ExpSerde + Send + Sync + 'static; @@ -56,7 +56,7 @@ pub trait ExpanderPCS { /// rather than the base field elements. fn gen_or_load_srs_for_testing( params: &Self::Params, - mpi_engine: &impl MPIEngine, + // mpi_engine: &impl MPIEngine, rng: impl RngCore, path: Option<&str>, ) -> Self::SRS { @@ -71,7 +71,7 @@ pub trait ExpanderPCS { } Err(_e) => { // file does not exist; generate SRS and store to file - let srs = Self::gen_srs(params, mpi_engine, rng); + let srs = Self::gen_srs(params, rng); let mut file = std::fs::File::create(path).expect("Failed to create SRS file"); srs.serialize_into(&mut file) @@ -83,13 +83,13 @@ pub trait ExpanderPCS { None => { // no path provided; generate SRS - Self::gen_srs(params, mpi_engine, rng) + Self::gen_srs(params, rng) } } } /// The actual function to generate the SRS. - fn gen_srs(params: &Self::Params, mpi_engine: &impl MPIEngine, rng: impl RngCore) -> Self::SRS; + fn gen_srs(params: &Self::Params, rng: impl RngCore) -> Self::SRS; /// n_input_vars is with respect to the multilinear poly on each machine in MPI, /// also ignore the number of variables stacked in the SIMD field. @@ -97,13 +97,12 @@ pub trait ExpanderPCS { /// Initialize the scratch pad. /// Each process returns its own scratch pad. - fn init_scratch_pad(params: &Self::Params, mpi_engine: &impl MPIEngine) -> Self::ScratchPad; + fn init_scratch_pad(params: &Self::Params) -> Self::ScratchPad; /// Commit to a polynomial. Root process returns the commitment, other processes can return /// arbitrary value. fn commit( params: &Self::Params, - mpi_engine: &impl MPIEngine, proving_key: &::PKey, poly: &impl MultilinearExtension, scratch_pad: &mut Self::ScratchPad, @@ -132,7 +131,6 @@ pub trait ExpanderPCS { /// argument system. fn open( params: &Self::Params, - mpi_engine: &impl MPIEngine, proving_key: &::PKey, poly: &impl MultilinearExtension, x: &ExpanderSingleVarChallenge, @@ -159,7 +157,7 @@ pub trait ExpanderPCS { /// Open a set of polynomials at a set of points. fn multi_points_batch_open( _params: &Self::Params, - _mpi_engine: &impl MPIEngine, + // _mpi_engine: &impl MPIEngine, _proving_key: &::PKey, _polys: &[impl MultilinearExtension], _x: &[ExpanderSingleVarChallenge], diff --git a/gkr_engine/src/transcript/definition.rs b/gkr_engine/src/transcript/definition.rs index fbc6f0dd4..0bb89482b 100644 --- a/gkr_engine/src/transcript/definition.rs +++ b/gkr_engine/src/transcript/definition.rs @@ -42,15 +42,15 @@ pub trait Transcript: Clone + Debug { /// Generate a slice of random bytes. fn generate_u8_slice(&mut self, n_bytes: usize) -> Vec; - fn generate_usize_vector(&mut self, n: usize) -> Vec { - let mut res: Vec = vec![0; n]; - let mut buf = [0u8; 8]; - for e in res.iter_mut() { - buf.copy_from_slice(&self.generate_u8_slice(8)); - *e = usize::from_le_bytes(buf); - } - res - } + // fn generate_usize_vector(&mut self, n: usize) -> Vec { + // let mut res: Vec = vec![0; n]; + // let mut buf = [0u8; 8]; + // for e in res.iter_mut() { + // buf.copy_from_slice(&self.generate_u8_slice(8)); + // *e = usize::from_le_bytes(buf); + // } + // res + // } /// Generate a field element. #[inline(always)] @@ -61,7 +61,7 @@ pub trait Transcript: Clone + Debug { /// Generate a field element vector. #[inline(always)] fn generate_field_elements(&mut self, n: usize) -> Vec { - let mut res = vec![F::ZERO; n]; + let mut res = vec![F::zero(); n]; for e in res.iter_mut() { *e = self.generate_field_element(); } diff --git a/hasher/Cargo.toml b/hasher/Cargo.toml index 0bbdfaaa5..9072d6f11 100644 --- a/hasher/Cargo.toml +++ b/hasher/Cargo.toml @@ -7,7 +7,7 @@ edition = "2021" arith = { path = "../arith" } serdes = { path = "../serdes" } - -halo2curves.workspace = true +ark-std.workspace = true +ark-bn254.workspace = true sha2.workspace = true tiny-keccak.workspace = true diff --git a/hasher/src/lib.rs b/hasher/src/lib.rs index c260c786a..8130f808f 100644 --- a/hasher/src/lib.rs +++ b/hasher/src/lib.rs @@ -1,5 +1,6 @@ -// traits definitions +#![no_std] +// traits definitions mod traits; pub use traits::{FiatShamirHasher, PoseidonStateTrait}; diff --git a/hasher/src/mimc.rs b/hasher/src/mimc.rs index 354c13b9b..844c7c251 100644 --- a/hasher/src/mimc.rs +++ b/hasher/src/mimc.rs @@ -1,5 +1,6 @@ use arith::Field; -use halo2curves::bn256::Fr; +use ark_bn254::Fr; +use ark_std::vec::Vec; use tiny_keccak::{Hasher, Keccak}; use crate::FiatShamirHasher; @@ -11,7 +12,7 @@ pub struct MiMC5FiatShamirHasher { impl MiMC5FiatShamirHasher { fn hash_u8_to_state(&self, input: &[u8]) -> F { - let mut h = F::ZERO; + let mut h = F::zero(); let chunks = input.chunks_exact(F::SIZE); let mut remainder = chunks.remainder().to_vec(); for chunk in chunks { diff --git a/hasher/src/mimc_test.rs b/hasher/src/mimc_test.rs index baf00879c..ae35ce61c 100644 --- a/hasher/src/mimc_test.rs +++ b/hasher/src/mimc_test.rs @@ -1,4 +1,5 @@ use arith::Fr; +use ark_std::vec; use serdes::ExpSerde; use crate::{FiatShamirHasher, MiMC5FiatShamirHasher}; diff --git a/hasher/src/poseidon/impls.rs b/hasher/src/poseidon/impls.rs index b0c0d51a1..971323758 100644 --- a/hasher/src/poseidon/impls.rs +++ b/hasher/src/poseidon/impls.rs @@ -1,6 +1,7 @@ -use std::fmt::Debug; - use arith::Field; +use ark_std::fmt::Debug; +use ark_std::format; +use ark_std::{vec, vec::Vec}; use tiny_keccak::{Hasher, Keccak}; use crate::{FiatShamirHasher, PoseidonStateTrait}; @@ -108,7 +109,7 @@ impl PoseidonPermutation { let mut remainder = chunks.remainder().to_vec(); for chunk in chunks { - let mut state_elts = vec![State::ElemT::ZERO; State::STATE_WIDTH]; + let mut state_elts = vec![State::ElemT::zero(); State::STATE_WIDTH]; for (elem, elts) in chunk .chunks(State::ElemT::SIZE) .zip(state_elts[State::CAPACITY..].iter_mut()) @@ -124,7 +125,7 @@ impl PoseidonPermutation { if !remainder.is_empty() { remainder.resize(u8_chunk_size, 0); - let mut state_elts = vec![State::ElemT::ZERO; State::STATE_WIDTH]; + let mut state_elts = vec![State::ElemT::zero(); State::STATE_WIDTH]; for (elem, elts) in remainder .chunks(State::ElemT::SIZE) .zip(state_elts[State::CAPACITY..].iter_mut()) diff --git a/hasher/src/traits.rs b/hasher/src/traits.rs index e5595db9f..e24333034 100644 --- a/hasher/src/traits.rs +++ b/hasher/src/traits.rs @@ -1,6 +1,7 @@ -use std::{ +use ark_std::{ fmt::Debug, ops::{Add, AddAssign, Mul, MulAssign}, + vec::Vec, }; use arith::Field; diff --git a/poly_commit/Cargo.toml b/poly_commit/Cargo.toml index 9404942ef..79ea11f13 100644 --- a/poly_commit/Cargo.toml +++ b/poly_commit/Cargo.toml @@ -5,7 +5,7 @@ edition = "2021" [dependencies] arith = { path = "../arith" } -gf2 = { path = "../arith/gf2" } +# gf2 = { path = "../arith/gf2" } gkr_engine = { path = "../gkr_engine" } polynomials = { path = "../arith/polynomials"} serdes = { path = "../serdes" } @@ -14,32 +14,33 @@ tree = { path = "../tree" } utils = { path = "../utils" } sumcheck = { path = "../sumcheck" } -ethnum.workspace = true +ark-ec.workspace = true +ark-ff.workspace = true ark-std.workspace = true +ark-bn254.workspace = true derivative.workspace = true -halo2curves.workspace = true +ethnum.workspace = true itertools.workspace = true -rand.workspace = true rayon.workspace = true transpose.workspace = true thiserror.workspace = true [dev-dependencies] -gf2_128 = { path = "../arith/gf2_128" } -mersenne31 = { path = "../arith/mersenne31" } -goldilocks = { path = "../arith/goldilocks" } +# gf2_128 = { path = "../arith/gf2_128" } +# mersenne31 = { path = "../arith/mersenne31" } +# goldilocks = { path = "../arith/goldilocks" } gkr_hashers = { path = "../hasher" } tynm.workspace = true criterion.workspace = true -[[bench]] -name = "orion" -harness = false +# [[bench]] +# name = "orion" +# harness = false -[[bench]] -name = "hyrax" -harness = false +# [[bench]] +# name = "hyrax" +# harness = false [[bench]] name = "kzg" diff --git a/poly_commit/src/batching.rs b/poly_commit/src/batching.rs index c259aa836..ea02678ab 100644 --- a/poly_commit/src/batching.rs +++ b/poly_commit/src/batching.rs @@ -1,11 +1,10 @@ //! Multi-points batch opening //! Uses Rayon to parallelize the computation. use arith::{ExtensionField, Field}; +use ark_ec::{AffineRepr, CurveGroup, VariableBaseMSM}; +use ark_ff::{Field as ArkField, PrimeField, Zero}; use ark_std::log2; use gkr_engine::Transcript; -use halo2curves::group::Curve; -use halo2curves::msm::best_multiexp; -use halo2curves::{ff::PrimeField, CurveAffine}; use polynomials::{EqPolynomial, MultilinearExtension}; use polynomials::{MultiLinearPoly, SumOfProductsPoly}; use rayon::iter::{IndexedParallelIterator, IntoParallelRefIterator, ParallelIterator}; @@ -20,25 +19,24 @@ use utils::timer::Timer; /// - the proof of the sumcheck #[allow(clippy::type_complexity)] pub fn prover_merge_points( - polys: &[impl MultilinearExtension], - points: &[impl AsRef<[C::Scalar]>], + polys: &[impl MultilinearExtension], + points: &[impl AsRef<[C::ScalarField]>], transcript: &mut impl Transcript, ) -> ( - Vec, - MultiLinearPoly, - IOPProof, + Vec, + MultiLinearPoly, + IOPProof, ) where - C: CurveAffine + ExpSerde, - C::Scalar: ExtensionField + PrimeField, - C::ScalarExt: ExtensionField + PrimeField, + C: AffineRepr + ExpSerde, + C::ScalarField: ExtensionField + PrimeField, { let num_vars = polys.iter().map(|p| p.num_vars()).max().unwrap_or(0); let k = polys.len(); let ell = log2(k) as usize; // challenge point t - let t = transcript.generate_field_elements::(ell); + let t = transcript.generate_field_elements::(ell); // eq(t, i) for i in [0..k] let eq_t_i = EqPolynomial::build_eq_x_r(&t); @@ -46,11 +44,11 @@ where // \tilde g_i(b) = eq(t, i) * f_i(b) let timer = Timer::new("Building tilde g_i(b)", true); - let tilde_gs = polys + let tilde_gs: Vec> = polys .par_iter() .enumerate() .map(|(index, f_i)| { - let mut tilde_g_eval = vec![C::Scalar::zero(); 1 << f_i.num_vars()]; + let mut tilde_g_eval = vec![::zero(); 1 << f_i.num_vars()]; for (j, &f_i_eval) in f_i.hypercube_basis_ref().iter().enumerate() { tilde_g_eval[j] = f_i_eval * eq_t_i[index]; } @@ -65,11 +63,15 @@ where // built the virtual polynomial for SumCheck let timer = Timer::new("Building tilde eqs", true); let points = points.iter().map(|p| p.as_ref()).collect::>(); - let tilde_eqs: Vec> = points + let tilde_eqs: Vec> = points .par_iter() .map(|point| { - let mut eq_b_zi = vec![C::Scalar::zero(); 1 << point.len()]; - EqPolynomial::build_eq_x_r_with_buf(point, &C::Scalar::one(), &mut eq_b_zi); + let mut eq_b_zi = vec![::zero(); 1 << point.len()]; + EqPolynomial::build_eq_x_r_with_buf( + point, + &::ONE, + &mut eq_b_zi, + ); MultiLinearPoly { coeffs: eq_b_zi } }) .collect(); @@ -80,7 +82,7 @@ where for (tilde_g, tilde_eq) in tilde_gs.iter().zip(tilde_eqs.into_iter()) { sumcheck_poly.add_pair(tilde_g.clone(), tilde_eq); } - let proof = SumCheck::::prove(&sumcheck_poly, transcript); + let proof = SumCheck::::prove(&sumcheck_poly, transcript); timer.stop(); let a2 = proof.export_point_to_expander(); @@ -89,17 +91,18 @@ where // sumcheck's point \tilde eq_i(a2) = eq(a2, point_i) let timer = Timer::new("Building g'(X)", true); - let mut g_prime_evals = vec![C::Scalar::zero(); 1 << num_vars]; - let eq_i_a2_polys = points + let mut g_prime_evals: Vec = + vec![::zero(); 1 << num_vars]; + let eq_i_a2_polys: Vec = points .par_iter() .map(|point| { let mut padded_point = point.to_vec(); - padded_point.resize(num_vars, C::Scalar::zero()); + padded_point.resize(num_vars, ::zero()); EqPolynomial::eq_vec(a2.as_ref(), &padded_point) }) .collect::>(); - for (tilde_g, eq_i_a2) in tilde_gs.iter().zip(eq_i_a2_polys.iter()) { + for (tilde_g, &eq_i_a2) in tilde_gs.iter().zip(eq_i_a2_polys.iter()) { for (j, &tilde_g_eval) in tilde_g.coeffs.iter().enumerate() { g_prime_evals[j] += tilde_g_eval * eq_i_a2; } @@ -112,16 +115,16 @@ where } pub fn verifier_merge_points( - commitments: &[impl AsRef<[C]>], - points: &[impl AsRef<[C::Scalar]>], - values: &[C::Scalar], - sumcheck_proof: &IOPProof, + commitments: &[impl AsRef<[C::Affine]>], + points: &[impl AsRef<[C::ScalarField]>], + values: &[C::ScalarField], + sumcheck_proof: &IOPProof, transcript: &mut impl Transcript, -) -> (bool, C::Scalar, Vec) +) -> (bool, C::ScalarField, Vec) where - C: CurveAffine + ExpSerde, - C::Scalar: ExtensionField + PrimeField, - C::ScalarExt: ExtensionField + PrimeField, + // C: ExpSerde + + C: CurveGroup, + C::ScalarField: ExtensionField + PrimeField, { let (padded_commitments, padded_points) = pad_commitments_and_points::(commitments, points); @@ -137,16 +140,16 @@ where let a2 = sumcheck_proof.export_point_to_expander(); // challenge point t - let t = transcript.generate_field_elements::(ell); + let t = transcript.generate_field_elements::(ell); let eq_t_i = EqPolynomial::build_eq_x_r(&t); // build g' commitment - let bases = padded_commitments - .iter() - .map(|c| c.as_ref()) - .collect::>(); - let bases_transposed = transpose::(&bases); + // let bases: Vec = padded_commitments + // .iter() + // .map(|c| c.as_ref()) + // .collect::>(); + let bases_transposed = transpose::(padded_commitments.as_slice()); let scalars = padded_points .iter() @@ -155,24 +158,23 @@ where let eq_i_a2 = EqPolynomial::eq_vec(a2.as_ref(), p); eq_i_a2 * eq_t_i[i] }) - .collect::>(); + .collect::>(); let g_prime_commit_elems = bases_transposed .iter() - .map(|base| best_multiexp(&scalars, base)) + .map(|base| VariableBaseMSM::msm(base, &scalars).unwrap()) .collect::>(); - let mut g_prime_commit_affine = vec![C::default(); padded_commitments[0].len()]; - C::Curve::batch_normalize(&g_prime_commit_elems, &mut g_prime_commit_affine); + let g_prime_commit_affine = C::normalize_batch(&g_prime_commit_elems); // ensure \sum_i eq(t, ) * f_i_evals matches the sum via SumCheck - let mut sum = C::Scalar::zero(); + let mut sum = ::zero(); for (i, &e) in eq_t_i.iter().enumerate().take(k) { sum += e * values[i]; } let (verified, subclaim) = - SumCheck::::verify(sum, sumcheck_proof, num_var, transcript); + SumCheck::::verify(sum, sumcheck_proof, num_var, transcript); let tilde_g_eval = subclaim.expected_evaluation; @@ -180,7 +182,7 @@ where } #[inline] -fn transpose(m: &[&[C]]) -> Vec> { +fn transpose(m: &[Vec]) -> Vec> { if m.is_empty() || m[0].is_empty() { return Vec::new(); } @@ -203,13 +205,15 @@ fn transpose(m: &[&[C]]) -> Vec> { #[allow(clippy::type_complexity)] #[allow(unused)] fn pad_polynomials_and_points( - polys: &[impl MultilinearExtension], - points: &[impl AsRef<[C::Scalar]>], -) -> (Vec>, Vec>) + polys: &[impl MultilinearExtension], + points: &[impl AsRef<[C::ScalarField]>], +) -> ( + Vec>, + Vec>, +) where - C: CurveAffine + ExpSerde, - C::Scalar: ExtensionField + PrimeField, - C::ScalarExt: ExtensionField + PrimeField, + C: CurveGroup, + C::ScalarField: Field, { let max_size = polys .iter() @@ -221,7 +225,7 @@ where .iter() .map(|poly| { let mut coeffs = poly.hypercube_basis_ref().to_vec(); - coeffs.resize(max_size, C::Scalar::zero()); + coeffs.resize(max_size, ::zero()); MultiLinearPoly { coeffs } }) .collect::>(); @@ -229,7 +233,7 @@ where .iter() .map(|point| { let mut padded_point = point.as_ref().to_vec(); - padded_point.resize(max_num_vars, C::Scalar::zero()); + padded_point.resize(max_num_vars, ::zero()); padded_point }) .collect::>(); @@ -241,13 +245,11 @@ where // Each commitment is a vector of curve points // This generalizes both KZG and Hyrax commitments fn pad_commitments_and_points( - commitments: &[impl AsRef<[C]>], - points: &[impl AsRef<[C::Scalar]>], -) -> (Vec>, Vec>) + commitments: &[impl AsRef<[C::Affine]>], + points: &[impl AsRef<[C::ScalarField]>], +) -> (Vec>, Vec>) where - C: CurveAffine + ExpSerde, - C::Scalar: ExtensionField + PrimeField, - C::ScalarExt: ExtensionField + PrimeField, + C: CurveGroup, { let max_num_vars = points.iter().map(|p| p.as_ref().len()).max().unwrap_or(0); let max_commit_size = commitments @@ -260,7 +262,7 @@ where .iter() .map(|point| { let mut padded_point = point.as_ref().to_vec(); - padded_point.resize(max_num_vars, C::Scalar::zero()); + padded_point.resize(max_num_vars, ::zero()); padded_point }) .collect::>(); @@ -269,7 +271,7 @@ where .iter() .map(|commitment| { let mut padded_commitment = commitment.as_ref().to_vec(); - padded_commitment.resize(max_commit_size, C::identity()); + padded_commitment.resize(max_commit_size, C::Affine::zero()); padded_commitment }) .collect::>(); diff --git a/poly_commit/src/kzg/bi_kzg/bivariate.rs b/poly_commit/src/kzg/bi_kzg/bivariate.rs index ea08667bb..200b72283 100644 --- a/poly_commit/src/kzg/bi_kzg/bivariate.rs +++ b/poly_commit/src/kzg/bi_kzg/bivariate.rs @@ -1,45 +1,42 @@ -use halo2curves::{ - ff::Field, - group::{prime::PrimeCurveAffine, Curve, Group}, - msm, - pairing::{MillerLoopResult, MultiMillerLoop}, - CurveAffine, -}; +use ark_ec::AffineRepr; +use ark_ec::VariableBaseMSM; +use ark_ec::{pairing::Pairing, CurveGroup}; +use ark_std::rand::RngCore; +use ark_std::One; +use ark_std::UniformRand; use itertools::izip; use serdes::ExpSerde; use crate::*; #[inline(always)] -pub fn generate_coef_form_bi_kzg_local_srs_for_testing( +pub fn generate_coef_form_bi_kzg_local_srs_for_testing( local_length: usize, distributed_parties: usize, party_rank: usize, - mut rng: impl rand::RngCore, + mut rng: impl RngCore, ) -> CoefFormBiKZGLocalSRS where - E::G1Affine: CurveAffine + ExpSerde, - E::G2Affine: CurveAffine + ExpSerde, + E::G1Affine: ExpSerde, + E::G2Affine: ExpSerde, { assert!(local_length.is_power_of_two()); assert!(distributed_parties.is_power_of_two()); assert!(party_rank < distributed_parties); - let tau_x = E::Fr::random(&mut rng); - let tau_y = E::Fr::random(&mut rng); + let tau_x = E::ScalarField::rand(&mut rng); + let tau_y = E::ScalarField::rand(&mut rng); let g1 = E::G1Affine::generator(); let tau_x_geometric_progression = powers_series(&tau_x, local_length); let tau_y_geometric_progression = powers_series(&tau_y, distributed_parties); - let g1_prog = g1.to_curve(); + let g1_prog: E::G1 = g1.into(); let x_coeff_bases = { let mut proj_bases = vec![g1_prog * tau_y_geometric_progression[party_rank]; local_length]; izip!(&mut proj_bases, &tau_x_geometric_progression).for_each(|(b, tau_xi)| *b *= *tau_xi); - - let mut g_bases = vec![E::G1Affine::default(); local_length]; - E::G1::batch_normalize(&proj_bases, &mut g_bases); + let g_bases = ::normalize_batch(&proj_bases); drop(proj_bases); g_bases @@ -54,8 +51,7 @@ where let mut proj_bases = vec![g1_prog; distributed_parties]; izip!(&mut proj_bases, &tau_y_geometric_progression).for_each(|(b, tau_yi)| *b *= *tau_yi); - let mut g_bases = vec![E::G1Affine::default(); distributed_parties]; - E::G1::batch_normalize(&proj_bases, &mut g_bases); + let g_bases = ::normalize_batch(&proj_bases); drop(proj_bases); g_bases @@ -73,24 +69,24 @@ where } #[inline(always)] -pub fn coeff_form_bi_kzg_open_leader( +pub fn coeff_form_bi_kzg_open_leader( srs: &CoefFormBiKZGLocalSRS, - evals_and_opens: &[(E::Fr, E::G1Affine)], - beta: E::Fr, -) -> (E::Fr, BiKZGProof) + evals_and_opens: &[(E::ScalarField, E::G1Affine)], + beta: E::ScalarField, +) -> (E::ScalarField, BiKZGProof) where - E::G1Affine: CurveAffine + ExpSerde, - E::G2Affine: CurveAffine + ExpSerde, + E::G1Affine: ExpSerde, + E::G2Affine: ExpSerde, { assert_eq!(srs.tau_y_srs.powers_of_tau.len(), evals_and_opens.len()); - let x_open: E::G1 = evals_and_opens.iter().map(|(_, o)| o.to_curve()).sum(); - let gammas: Vec = evals_and_opens.iter().map(|(e, _)| *e).collect(); + let x_open: E::G1 = evals_and_opens.iter().map(|(_, o)| E::G1::from(*o)).sum(); + let gammas: Vec = evals_and_opens.iter().map(|(e, _)| *e).collect(); let (div, eval) = univariate_degree_one_quotient(&gammas, beta); - let mut y_open = E::G1::generator() * E::Fr::ZERO; - msm::multiexp_serial(&div, &srs.tau_y_srs.powers_of_tau[..div.len()], &mut y_open); + let y_open: E::G1 = + VariableBaseMSM::msm(&srs.tau_y_srs.powers_of_tau[..div.len()], &div).unwrap(); ( eval, @@ -102,45 +98,44 @@ where } #[inline(always)] -pub fn coeff_form_bi_kzg_verify( +pub fn coeff_form_bi_kzg_verify( vk: BiKZGVerifierParam, comm: E::G1Affine, - alpha: E::Fr, - beta: E::Fr, - eval: E::Fr, + alpha: E::ScalarField, + beta: E::ScalarField, + eval: E::ScalarField, opening: BiKZGProof, ) -> bool where - E::G1Affine: CurveAffine + ExpSerde, - E::G2Affine: CurveAffine + ExpSerde, + E::G1Affine: ExpSerde, + E::G2Affine: ExpSerde, { let g1_eval: E::G1Affine = (E::G1Affine::generator() * eval).into(); let g2_alpha: E::G2 = E::G2Affine::generator() * alpha; let g2_beta: E::G2 = E::G2Affine::generator() * beta; - let gt_result = E::multi_miller_loop(&[ - ( - &opening.quotient_x, - &(vk.tau_x_g2.to_curve() - g2_alpha).to_affine().into(), - ), - ( - &opening.quotient_y, - &(vk.tau_y_g2.to_curve() - g2_beta).to_affine().into(), - ), - (&(g1_eval - comm).into(), &E::G2Affine::generator().into()), - ]); - - gt_result.final_exponentiation().is_identity().into() + let gt_result = E::multi_miller_loop( + &[ + opening.quotient_x, + opening.quotient_y, + (g1_eval - comm).into(), + ], + &[ + (vk.tau_x_g2 - g2_alpha).into(), + (vk.tau_y_g2 - g2_beta).into(), + E::G2Affine::generator().into(), + ], + ); + E::final_exponentiation(gt_result).unwrap().0 == E::TargetField::one() } #[cfg(test)] mod tests { + use arith::Fr; + use ark_bn254::{Bn254, G1Affine, G1Projective}; + use ark_ec::{AffineRepr, CurveGroup}; + use ark_ff::UniformRand; use ark_std::test_rng; - use halo2curves::{ - bn256::{Bn256, Fr, G1Affine, G1}, - ff::Field, - group::{prime::PrimeCurveAffine, Curve}, - }; use itertools::izip; use crate::*; @@ -150,7 +145,7 @@ mod tests { let x_degree = 15; let y_degree = 7; - let party_srs: Vec> = (0..=y_degree) + let party_srs: Vec> = (0..=y_degree) .map(|rank| { let mut rng = test_rng(); generate_coef_form_bi_kzg_local_srs_for_testing( @@ -164,26 +159,29 @@ mod tests { let mut rng = test_rng(); let xy_coeffs: Vec> = (0..=y_degree) - .map(|_| (0..=x_degree).map(|_| Fr::random(&mut rng)).collect()) + .map(|_| (0..=x_degree).map(|_| Fr::rand(&mut rng)).collect()) .collect(); let commitments: Vec<_> = izip!(&party_srs, &xy_coeffs) .map(|(srs, x_coeffs)| coeff_form_uni_kzg_commit(&srs.tau_x_srs, x_coeffs)) .collect(); - let global_commitment_g1: G1 = commitments.iter().map(|c| c.to_curve()).sum::(); - let global_commitment: G1Affine = global_commitment_g1.to_affine(); + let global_commitment_g1: G1Projective = commitments + .iter() + .map(|c| c.into_group()) + .sum::(); + let global_commitment: G1Affine = global_commitment_g1.into_affine(); - let alpha = Fr::random(&mut rng); + let alpha = Fr::rand(&mut rng); let evals_and_opens: Vec<(Fr, G1Affine)> = izip!(&party_srs, &xy_coeffs) .map(|(srs, x_coeffs)| coeff_form_uni_kzg_open_eval(&srs.tau_x_srs, x_coeffs, alpha)) .collect(); - let beta = Fr::random(&mut rng); + let beta = Fr::rand(&mut rng); let (final_eval, final_opening) = coeff_form_bi_kzg_open_leader(&party_srs[0], &evals_and_opens, beta); - let vk: BiKZGVerifierParam = From::from(&party_srs[0]); + let vk: BiKZGVerifierParam = From::from(&party_srs[0]); assert!(coeff_form_bi_kzg_verify( vk, diff --git a/poly_commit/src/kzg/bi_kzg/expander_api.rs b/poly_commit/src/kzg/bi_kzg/expander_api.rs index 07755873e..b1b943418 100644 --- a/poly_commit/src/kzg/bi_kzg/expander_api.rs +++ b/poly_commit/src/kzg/bi_kzg/expander_api.rs @@ -1,14 +1,10 @@ use arith::ExtensionField; +use ark_ec::pairing::Pairing; +use ark_std::rand::RngCore; use gkr_engine::{ - ExpanderPCS, ExpanderSingleVarChallenge, FieldEngine, MPIEngine, PolynomialCommitmentType, + ExpanderPCS, ExpanderSingleVarChallenge, FieldEngine, PolynomialCommitmentType, StructuredReferenceString, Transcript, }; -use halo2curves::{ - ff::PrimeField, - group::prime::PrimeCurveAffine, - pairing::{Engine, MultiMillerLoop}, - CurveAffine, -}; use polynomials::MultilinearExtension; use serdes::ExpSerde; @@ -22,11 +18,11 @@ use crate::{ impl ExpanderPCS for HyperBiKZGPCS where - G: FieldEngine, - E: Engine + MultiMillerLoop, - E::Fr: ExtensionField + PrimeField, - E::G1Affine: ExpSerde + Default + CurveAffine, - E::G2Affine: ExpSerde + Default + CurveAffine, + G: FieldEngine, + E: Pairing, + E::ScalarField: ExtensionField, + E::G1Affine: ExpSerde + Default, + E::G2Affine: ExpSerde + Default, { const NAME: &'static str = "HyperBiKZGForExpander"; @@ -39,100 +35,94 @@ where type ScratchPad = (); type BatchOpening = (); - fn init_scratch_pad(_params: &Self::Params, _mpi_engine: &impl MPIEngine) -> Self::ScratchPad {} + fn init_scratch_pad(_params: &Self::Params) -> Self::ScratchPad {} fn gen_params(n_input_vars: usize, _world_size: usize) -> Self::Params { std::cmp::max(n_input_vars, Self::MINIMUM_SUPPORTED_NUM_VARS) } - fn gen_srs( - params: &Self::Params, - mpi_engine: &impl MPIEngine, - rng: impl rand::RngCore, - ) -> Self::SRS { - let local_num_vars = *params; + fn gen_srs(params: &Self::Params, rng: impl RngCore) -> Self::SRS { + unimplemented!() + // let local_num_vars = *params; - let x_degree_po2 = 1 << local_num_vars; - let y_degree_po2 = mpi_engine.world_size(); - let rank = mpi_engine.world_rank(); + // let x_degree_po2 = 1 << local_num_vars; + // let y_degree_po2 = mpi_engine.world_size(); + // let rank = mpi_engine.world_rank(); - generate_coef_form_bi_kzg_local_srs_for_testing(x_degree_po2, y_degree_po2, rank, rng) + // generate_coef_form_bi_kzg_local_srs_for_testing(x_degree_po2, y_degree_po2, rank, rng) } fn commit( _params: &Self::Params, - mpi_engine: &impl MPIEngine, proving_key: &::PKey, - poly: &impl polynomials::MultilinearExtension, + poly: &impl polynomials::MultilinearExtension, _scratch_pad: &mut Self::ScratchPad, ) -> Option { - // The minimum supported number of variables is 1. - // If the polynomial has no variables, we lift it to a polynomial with 1 variable. - if poly.num_vars() < Self::MINIMUM_SUPPORTED_NUM_VARS { - let poly = lift_poly_to_n_vars(poly, Self::MINIMUM_SUPPORTED_NUM_VARS); - return >::commit( - _params, - mpi_engine, - proving_key, - &poly, - _scratch_pad, - ); - }; - - let local_commitment = - coeff_form_uni_kzg_commit(&proving_key.tau_x_srs, poly.hypercube_basis_ref()); - - if mpi_engine.is_single_process() { - return BiKZGCommitment(local_commitment).into(); - } - - let local_g1 = local_commitment.to_curve(); - let mut root_gathering_commits: Vec = vec![local_g1; mpi_engine.world_size()]; - mpi_engine.gather_vec(&[local_g1], &mut root_gathering_commits); - - if !mpi_engine.is_root() { - return None; - } - - let final_commit = root_gathering_commits.iter().sum::().into(); - - BiKZGCommitment(final_commit).into() + unimplemented!() + // // The minimum supported number of variables is 1. + // // If the polynomial has no variables, we lift it to a polynomial with 1 variable. + // if poly.num_vars() < Self::MINIMUM_SUPPORTED_NUM_VARS { + // let poly = lift_poly_to_n_vars(poly, Self::MINIMUM_SUPPORTED_NUM_VARS); + // return >::commit( + // _params, + // proving_key, + // &poly, + // _scratch_pad, + // ); + // }; + + // let local_commitment = + // coeff_form_uni_kzg_commit(&proving_key.tau_x_srs, poly.hypercube_basis_ref()); + + // if mpi_engine.is_single_process() { + // return BiKZGCommitment(local_commitment).into(); + // } + + // let local_g1: E::G1 = local_commitment.into(); + // let mut root_gathering_commits: Vec = vec![local_g1; mpi_engine.world_size()]; + // mpi_engine.gather_vec(&[local_g1], &mut root_gathering_commits); + + // if !mpi_engine.is_root() { + // return None; + // } + + // let final_commit = root_gathering_commits.iter().sum::().into(); + + // BiKZGCommitment(final_commit).into() } fn open( _params: &Self::Params, - mpi_engine: &impl MPIEngine, proving_key: &::PKey, - poly: &impl MultilinearExtension, + poly: &impl MultilinearExtension, x: &ExpanderSingleVarChallenge, transcript: &mut impl Transcript, _scratch_pad: &Self::ScratchPad, ) -> Option { - if poly.num_vars() < Self::MINIMUM_SUPPORTED_NUM_VARS { - let (poly, x) = lift_poly_and_expander_challenge_to_n_vars( - poly, - x, - Self::MINIMUM_SUPPORTED_NUM_VARS, - ); - return >::open( - _params, - mpi_engine, - proving_key, - &poly, - &x, - transcript, - _scratch_pad, - ); - }; - - coeff_form_hyper_bikzg_open( - proving_key, - mpi_engine, - poly, - &x.local_xs(), - &x.r_mpi, - transcript, - ) + unimplemented!() + // if poly.num_vars() < Self::MINIMUM_SUPPORTED_NUM_VARS { + // let (poly, x) = lift_poly_and_expander_challenge_to_n_vars( + // poly, + // x, + // Self::MINIMUM_SUPPORTED_NUM_VARS, + // ); + // return >::open( + // _params, + // proving_key, + // &poly, + // &x, + // transcript, + // _scratch_pad, + // ); + // }; + + // coeff_form_hyper_bikzg_open( + // proving_key, + // poly, + // &x.local_xs(), + // &x.r_mpi, + // transcript, + // ) } fn verify( diff --git a/poly_commit/src/kzg/bi_kzg/hyper_bikzg.rs b/poly_commit/src/kzg/bi_kzg/hyper_bikzg.rs index 099260c91..8777964c9 100644 --- a/poly_commit/src/kzg/bi_kzg/hyper_bikzg.rs +++ b/poly_commit/src/kzg/bi_kzg/hyper_bikzg.rs @@ -4,460 +4,464 @@ use std::{io::Cursor, iter}; use arith::ExtensionField; -use gkr_engine::{MPIEngine, Transcript}; -use halo2curves::{ - ff::Field, - group::{prime::PrimeCurveAffine, Curve, Group, GroupEncoding}, - pairing::MultiMillerLoop, - CurveAffine, -}; +use arith::Field; +use ark_ec::pairing::Pairing; +use ark_ec::CurveGroup; +use ark_ec::PrimeGroup; +use ark_ff::Field as _; +use gkr_engine::Transcript; use itertools::{chain, izip}; use polynomials::MultilinearExtension; use serdes::ExpSerde; -use transcript::{transcript_root_broadcast, transcript_verifier_sync}; +use transcript::transcript_verifier_sync; use crate::*; -pub fn coeff_form_hyper_bikzg_open( - srs: &CoefFormBiKZGLocalSRS, - mpi_engine: &impl MPIEngine, - coeffs: &impl MultilinearExtension, - local_alphas: &[E::Fr], - mpi_alphas: &[E::Fr], - fs_transcript: &mut impl Transcript, -) -> Option> -where - E: MultiMillerLoop, - E::G1Affine: CurveAffine + ExpSerde, - E::G2Affine: CurveAffine + ExpSerde, - E::Fr: ExtensionField, -{ - // NOTE(HS) deteriorate to vanilla HyperKZG if mpi_alphas is empty, namely single party setting - // since there is no other mpi variables, then the party running is the leader - if mpi_alphas.is_empty() { - let (_, hyperkzg_opening) = coeff_form_uni_hyperkzg_open( - &srs.tau_x_srs, - coeffs.hypercube_basis_ref(), - local_alphas, - fs_transcript, - ); - - let hyper_bikzg_opening: HyperBiKZGOpening = hyperkzg_opening.into(); - return hyper_bikzg_opening.into(); - } - - // - // Locally fold local variables, then commit to construct the poly oracles - // - - let (local_folded_x_oracle_commits, local_folded_x_oracle_coeffs) = - coeff_form_hyperkzg_local_poly_oracles( - &srs.tau_x_srs, - coeffs.hypercube_basis_ref(), - local_alphas, - ); - - let local_final_eval_at_x = { - let last_coeffs = local_folded_x_oracle_coeffs.last().unwrap().clone(); - let last_alpha = local_alphas[local_alphas.len() - 1]; - (E::Fr::ONE - last_alpha) * last_coeffs[0] + last_alpha * last_coeffs[1] - }; - - // - // Leader party gathering evals and oracle commitments - // - - let mut root_gathering_folded_oracle_commits: Vec = - vec![E::G1Affine::default(); mpi_engine.world_size() * local_folded_x_oracle_commits.len()]; - let mut final_evals_at_x: Vec = vec![E::Fr::ZERO; mpi_engine.world_size()]; - - mpi_engine.gather_vec( - &local_folded_x_oracle_commits, - &mut root_gathering_folded_oracle_commits, - ); - mpi_engine.gather_vec(&[local_final_eval_at_x], &mut final_evals_at_x); - - // - // Leader party collect oracle commitments, sum them up for folded oracles - // - - let mut folded_x_oracle_commits: Vec = Vec::new(); - let mut y_oracle_commit: E::G1Affine = E::G1Affine::default(); - - if mpi_engine.is_root() { - let g1_zero = E::G1Affine::default().to_curve(); - let mut folded_x_coms_g1 = vec![g1_zero; local_folded_x_oracle_commits.len()]; - - root_gathering_folded_oracle_commits - .chunks(local_folded_x_oracle_commits.len()) - .for_each(|folded_oracles| { - izip!(&mut folded_x_coms_g1, folded_oracles) - .for_each(|(x_com_i, oracle_i)| *x_com_i += oracle_i.to_curve()) - }); - - folded_x_oracle_commits = vec![E::G1Affine::default(); folded_x_coms_g1.len()]; - E::G1::batch_normalize(&folded_x_coms_g1, &mut folded_x_oracle_commits); - - y_oracle_commit = coeff_form_uni_kzg_commit(&srs.tau_y_srs, &final_evals_at_x); - } - - // - // The leader party continues on folding over "final_evals" over only y variables. - // - - let mut folded_y_oracle_commits: Vec = Vec::new(); - let mut folded_y_oracle_coeffs: Vec> = Vec::new(); - - if mpi_engine.is_root() { - (folded_y_oracle_commits, folded_y_oracle_coeffs) = - coeff_form_hyperkzg_local_poly_oracles(&srs.tau_y_srs, &final_evals_at_x, mpi_alphas); - } - - // - // The leader party feeds all folded oracles into RO, then sync party's transcript state - // - - let mut folded_oracle_commitments: Vec = Vec::new(); - - if mpi_engine.is_root() { - folded_oracle_commitments = { - let mut temp = folded_x_oracle_commits.clone(); - temp.push(y_oracle_commit); - temp.extend_from_slice(&folded_y_oracle_commits); - temp - }; - - chain!( - &folded_x_oracle_commits, - iter::once(&y_oracle_commit), - &folded_y_oracle_commits, - ) - .for_each(|f| fs_transcript.append_u8_slice(f.to_bytes().as_ref())); - } - - transcript_root_broadcast(fs_transcript, mpi_engine); - - let beta_x = fs_transcript.generate_field_element::(); - let beta_y = fs_transcript.generate_field_element::(); - - // - // Local parties run HyperKZG evals at beta_x, -beta_x, beta_x^2 over folded coeffs - // - - let local_folded_x_evals: HyperKZGLocalEvals = coeff_form_hyperkzg_local_evals( - coeffs.hypercube_basis_ref(), - &local_folded_x_oracle_coeffs, - local_alphas, - beta_x, - ); - - let local_exported_folded_x_evals: HyperKZGExportedLocalEvals = - local_folded_x_evals.clone().into(); - - // - // Collect all exported local folded evals at x to the leader party - // - - let mut root_gathering_exported_folded_x_evals: Vec> = - vec![local_exported_folded_x_evals.clone(); mpi_engine.world_size()]; - let mut root_aggregated_x_evals = HyperKZGAggregatedEvals::::default(); - let mut root_folded_y_evals = HyperKZGLocalEvals::::default(); - - { - let mut local_exported_folded_x_evals_bytes: Vec = Vec::new(); - local_exported_folded_x_evals - .serialize_into(&mut local_exported_folded_x_evals_bytes) - .unwrap(); - - let mut gathering_buffer = - vec![0u8; mpi_engine.world_size() * local_exported_folded_x_evals_bytes.len()]; - - mpi_engine.gather_vec(&local_exported_folded_x_evals_bytes, &mut gathering_buffer); - - if mpi_engine.is_root() { - izip!( - &mut root_gathering_exported_folded_x_evals, - gathering_buffer.chunks(local_exported_folded_x_evals_bytes.len()) - ) - .for_each(|(es, bs)| { - let mut cursor = Cursor::new(bs.to_vec()); - *es = HyperKZGExportedLocalEvals::::deserialize_from(&mut cursor).unwrap(); - }) - } - } - - // - // Leader aggregates all local exported evaluations (at x) by evaluating at y - // by three points: beta_y, -beta_y, beta_y^2, then fold the final evals at x, - // which is degree 0 for variable x, along variable y. - // - - if mpi_engine.is_root() { - root_aggregated_x_evals = HyperKZGAggregatedEvals::new_from_exported_evals( - &root_gathering_exported_folded_x_evals, - beta_y, - ); - - root_folded_y_evals = coeff_form_hyperkzg_local_evals( - &final_evals_at_x, - &folded_y_oracle_coeffs, - mpi_alphas, - beta_y, - ); - } - - // - // The leader party feeds all evals into RO, then sync party's transcript state - // - - if mpi_engine.is_root() { - root_aggregated_x_evals.append_to_transcript(fs_transcript); - root_folded_y_evals.append_to_transcript(fs_transcript); - } - - transcript_root_broadcast(fs_transcript, mpi_engine); - - let gamma = fs_transcript.generate_field_element::(); - - // - // The leader party linear combines folded coeffs at y with gamma, - // then broadcast the coeffs back to local. - // - - let mut leader_gamma_aggregated_y_coeffs: Vec = - vec![E::Fr::ZERO; mpi_engine.world_size()]; - - if mpi_engine.is_root() { - leader_gamma_aggregated_y_coeffs = { - let gamma_n = gamma.pow_vartime([local_alphas.len() as u64]); - let mut temp = coeff_form_hyperkzg_local_oracle_polys_aggregate::( - &final_evals_at_x, - &folded_y_oracle_coeffs, - gamma, - ); - temp.iter_mut().for_each(|t| *t *= gamma_n); - temp - }; - } - - // TODO(HS) can be improved to broadcast a vec, returning a coeff to each party - { - let mut serialized_y_coeffs: Vec = Vec::new(); - leader_gamma_aggregated_y_coeffs - .serialize_into(&mut serialized_y_coeffs) - .unwrap(); - - mpi_engine.root_broadcast_bytes(&mut serialized_y_coeffs); - leader_gamma_aggregated_y_coeffs = { - let mut cursor = Cursor::new(serialized_y_coeffs); - Vec::deserialize_from(&mut cursor).unwrap() - }; - } - - // - // Local party compute the linear combined folded coeffs at x with gamma, - // then the degree2 Lagrange over beta_x, -beta_x, beta_x^2, - // then vanish the local aggregated x coeffs at the three points above, - // and commit to the final quotient poly - // - - let mut local_gamma_aggregated_x_coeffs = { - let mut f_gamma_local = coeff_form_hyperkzg_local_oracle_polys_aggregate::( - coeffs.hypercube_basis_ref(), - &local_folded_x_oracle_coeffs, - gamma, - ); - - f_gamma_local[0] += leader_gamma_aggregated_y_coeffs[mpi_engine.world_rank()]; - f_gamma_local - }; - - let local_lagrange_degree2_at_x = { - let mut local_degree_2 = - local_folded_x_evals.interpolate_degree2_aggregated_evals(beta_x, gamma); - - local_degree_2[0] += leader_gamma_aggregated_y_coeffs[mpi_engine.world_rank()]; - local_degree_2 - }; - - let local_gamma_aggregated_x_quotient = { - let mut nom = local_gamma_aggregated_x_coeffs.clone(); - polynomial_add(&mut nom, -E::Fr::ONE, &local_lagrange_degree2_at_x); - univariate_roots_quotient(nom, &[beta_x, -beta_x, beta_x * beta_x]) - }; - - let local_gamma_aggregated_x_quotient_commitment_g1: E::G1 = - coeff_form_uni_kzg_commit(&srs.tau_x_srs, &local_gamma_aggregated_x_quotient).to_curve(); - - // - // Leader collect all the quotient commitment at x, sum it up and feed it to RO, - // then sync transcript state - // - - let mut root_gathering_gamma_aggregated_x_quotient_commitment_g1s: Vec = - vec![E::G1::generator(); mpi_engine.world_size()]; - mpi_engine.gather_vec( - &[local_gamma_aggregated_x_quotient_commitment_g1], - &mut root_gathering_gamma_aggregated_x_quotient_commitment_g1s, - ); - - let mut gamma_aggregated_x_quotient_commitment: E::G1Affine = E::G1Affine::default(); - - if mpi_engine.is_root() { - gamma_aggregated_x_quotient_commitment = - root_gathering_gamma_aggregated_x_quotient_commitment_g1s - .iter() - .sum::() - .to_affine(); - - fs_transcript.append_u8_slice(gamma_aggregated_x_quotient_commitment.to_bytes().as_ref()); - } - - transcript_root_broadcast(fs_transcript, mpi_engine); - - let delta_x = fs_transcript.generate_field_element::(); - - // - // Locally compute the Lagrange-degree2 interpolation at delta_x, pool at leader - // - - let mut degree2_evals_at_delta_x: Vec = vec![E::Fr::ZERO; mpi_engine.world_size()]; - - let local_degree2_eval_at_delta_x = local_lagrange_degree2_at_x[0] - + local_lagrange_degree2_at_x[1] * delta_x - + local_lagrange_degree2_at_x[2] * delta_x * delta_x; - - mpi_engine.gather_vec( - &[local_degree2_eval_at_delta_x], - &mut degree2_evals_at_delta_x, - ); - - // - // Leader does similar thing - quotient at beta_y, -beta_y, beta_y^2, - // commit the quotient polynomial commitment at y, feed it to RO, - // then sync transcript state - // - - let mut leader_quotient_y_coeffs: Vec = vec![E::Fr::ZERO; mpi_engine.world_size()]; - let mut leader_quotient_y_commitment: E::G1Affine = E::G1Affine::default(); - - if mpi_engine.is_root() { - let num_y_coeffs = mpi_engine.world_size(); - - // NOTE(HS) interpolate at beta_y, beta_y2, -beta_y on lagrange_degree2_delta_x - let lagrange_degree2_delta_y = { - let pos_beta_y_pow_series = powers_series(&beta_y, num_y_coeffs); - let neg_beta_y_pow_series = powers_series(&(-beta_y), num_y_coeffs); - let beta_y2_pow_series = powers_series(&(beta_y * beta_y), num_y_coeffs); - - let at_beta_y = univariate_evaluate(°ree2_evals_at_delta_x, &pos_beta_y_pow_series); - let at_neg_beta_y = - univariate_evaluate(°ree2_evals_at_delta_x, &neg_beta_y_pow_series); - let at_beta_y2 = univariate_evaluate(°ree2_evals_at_delta_x, &beta_y2_pow_series); - - coeff_form_degree2_lagrange( - [beta_y, -beta_y, beta_y * beta_y], - [at_beta_y, at_neg_beta_y, at_beta_y2], - ) - }; - - leader_quotient_y_coeffs = { - let mut nom = degree2_evals_at_delta_x.clone(); - polynomial_add(&mut nom, -E::Fr::ONE, &lagrange_degree2_delta_y); - univariate_roots_quotient(nom, &[beta_y, -beta_y, beta_y * beta_y]) - }; - - leader_quotient_y_commitment = - coeff_form_uni_kzg_commit(&srs.tau_y_srs, &leader_quotient_y_coeffs); - - fs_transcript.append_u8_slice(leader_quotient_y_commitment.to_bytes().as_ref()); - } - - transcript_root_broadcast(fs_transcript, mpi_engine); - - let delta_y = fs_transcript.generate_field_element::(); - - // - // Leader send out the quotient on y coefficients back to local parties - // - - // TODO(HS) can be better if the root only send corresponding coeffs to the parties - { - let mut serialized_y_quotient_coeffs: Vec = Vec::new(); - leader_quotient_y_coeffs - .serialize_into(&mut serialized_y_quotient_coeffs) - .unwrap(); - - mpi_engine.root_broadcast_bytes(&mut serialized_y_quotient_coeffs); - leader_quotient_y_coeffs = { - let mut cursor = Cursor::new(serialized_y_quotient_coeffs); - Vec::deserialize_from(&mut cursor).unwrap() - }; - leader_quotient_y_coeffs.resize(mpi_engine.world_size(), E::Fr::ZERO); - } - - // - // Final step for local - trip off the prior quotients at x and y on \pm beta and beta^2 - // - - // NOTE(HS) f_gamma_s - (delta_x - beta_x) ... (delta_x - beta_x2) f_gamma_quotient_s - // - (delta_y - beta_y) ... (delta_y - beta_y2) lagrange_quotient_y - let delta_x_denom = (delta_x - beta_x) * (delta_x - beta_x * beta_x) * (delta_x + beta_x); - let delta_y_denom = (delta_y - beta_y) * (delta_y - beta_y * beta_y) * (delta_y + beta_y); - - polynomial_add( - &mut local_gamma_aggregated_x_coeffs, - -delta_x_denom, - &local_gamma_aggregated_x_quotient, - ); - local_gamma_aggregated_x_coeffs[0] -= - delta_y_denom * leader_quotient_y_coeffs[mpi_engine.world_rank()]; - - // - // BiKZG commit to the last bivariate poly - // - - let mut gathered_eval_opens: Vec<(E::Fr, E::G1Affine)> = - vec![(E::Fr::ZERO, E::G1Affine::default()); mpi_engine.world_size()]; - let local_eval_open = - coeff_form_uni_kzg_open_eval(&srs.tau_x_srs, &local_gamma_aggregated_x_coeffs, delta_x); - - mpi_engine.gather_vec(&[local_eval_open], &mut gathered_eval_opens); - - if !mpi_engine.is_root() { - return None; - } - - let (_, final_opening) = coeff_form_bi_kzg_open_leader(srs, &gathered_eval_opens, delta_y); - - HyperBiKZGOpening { - folded_oracle_commitments, - aggregated_evals: root_aggregated_x_evals, - leader_evals: root_folded_y_evals.into(), - beta_x_commitment: gamma_aggregated_x_quotient_commitment, - beta_y_commitment: leader_quotient_y_commitment, - quotient_delta_x_commitment: final_opening.quotient_x, - quotient_delta_y_commitment: final_opening.quotient_y, - } - .into() -} +// pub fn coeff_form_hyper_bikzg_open( +// srs: &CoefFormBiKZGLocalSRS, +// mpi_engine: &impl MPIEngine, +// coeffs: &impl MultilinearExtension, +// local_alphas: &[E::ScalarField], +// mpi_alphas: &[E::ScalarField], +// fs_transcript: &mut impl Transcript, +// ) -> Option> +// where +// E: Pairing, +// E::G1Affine: ExpSerde, +// E::G2Affine: ExpSerde, +// E::ScalarField: ExtensionField, +// { +// // NOTE(HS) deteriorate to vanilla HyperKZG if mpi_alphas is empty, namely single party +// setting // since there is no other mpi variables, then the party running is the leader +// if mpi_alphas.is_empty() { +// let (_, hyperkzg_opening) = coeff_form_uni_hyperkzg_open( +// &srs.tau_x_srs, +// coeffs.hypercube_basis_ref(), +// local_alphas, +// fs_transcript, +// ); + +// let hyper_bikzg_opening: HyperBiKZGOpening = hyperkzg_opening.into(); +// return hyper_bikzg_opening.into(); +// } + +// // +// // Locally fold local variables, then commit to construct the poly oracles +// // + +// let (local_folded_x_oracle_commits, local_folded_x_oracle_coeffs) = +// coeff_form_hyperkzg_local_poly_oracles( +// &srs.tau_x_srs, +// coeffs.hypercube_basis_ref(), +// local_alphas, +// ); + +// let local_final_eval_at_x = { +// let last_coeffs = local_folded_x_oracle_coeffs.last().unwrap().clone(); +// let last_alpha = local_alphas[local_alphas.len() - 1]; +// (E::ScalarField::one() - last_alpha) * last_coeffs[0] + last_alpha * last_coeffs[1] +// }; + +// // +// // Leader party gathering evals and oracle commitments +// // + +// let mut root_gathering_folded_oracle_commits: Vec = +// vec![E::G1Affine::default(); mpi_engine.world_size() * +// local_folded_x_oracle_commits.len()]; let mut final_evals_at_x: Vec = +// vec![::zero(); mpi_engine.world_size()]; + +// mpi_engine.gather_vec( +// &local_folded_x_oracle_commits, +// &mut root_gathering_folded_oracle_commits, +// ); +// mpi_engine.gather_vec(&[local_final_eval_at_x], &mut final_evals_at_x); + +// // +// // Leader party collect oracle commitments, sum them up for folded oracles +// // + +// let mut folded_x_oracle_commits: Vec = Vec::new(); +// let mut y_oracle_commit: E::G1Affine = E::G1Affine::default(); + +// if mpi_engine.is_root() { +// let g1_zero = E::G1::default(); +// let mut folded_x_coms_g1 = vec![g1_zero; local_folded_x_oracle_commits.len()]; + +// root_gathering_folded_oracle_commits +// .chunks(local_folded_x_oracle_commits.len()) +// .for_each(|folded_oracles| { +// izip!(&mut folded_x_coms_g1, folded_oracles) +// .for_each(|(x_com_i, oracle_i)| *x_com_i += E::G1::from(*oracle_i)) +// }); + +// folded_x_oracle_commits = E::G1::normalize_batch(&folded_x_coms_g1); + +// y_oracle_commit = coeff_form_uni_kzg_commit(&srs.tau_y_srs, &final_evals_at_x); +// } + +// // +// // The leader party continues on folding over "final_evals" over only y variables. +// // + +// let mut folded_y_oracle_commits: Vec = Vec::new(); +// let mut folded_y_oracle_coeffs: Vec> = Vec::new(); + +// if mpi_engine.is_root() { +// (folded_y_oracle_commits, folded_y_oracle_coeffs) = +// coeff_form_hyperkzg_local_poly_oracles(&srs.tau_y_srs, &final_evals_at_x, +// mpi_alphas); } + +// // +// // The leader party feeds all folded oracles into RO, then sync party's transcript state +// // + +// let mut folded_oracle_commitments: Vec = Vec::new(); + +// if mpi_engine.is_root() { +// folded_oracle_commitments = { +// let mut temp = folded_x_oracle_commits.clone(); +// temp.push(y_oracle_commit); +// temp.extend_from_slice(&folded_y_oracle_commits); +// temp +// }; + +// chain!( +// &folded_x_oracle_commits, +// iter::once(&y_oracle_commit), +// &folded_y_oracle_commits, +// ) +// .for_each(|f| fs_transcript.append_serializable_data(f)); +// } + +// transcript_root_broadcast(fs_transcript, mpi_engine); + +// let beta_x = fs_transcript.generate_field_element::(); +// let beta_y = fs_transcript.generate_field_element::(); + +// // +// // Local parties run HyperKZG evals at beta_x, -beta_x, beta_x^2 over folded coeffs +// // + +// let local_folded_x_evals: HyperKZGLocalEvals = coeff_form_hyperkzg_local_evals( +// coeffs.hypercube_basis_ref(), +// &local_folded_x_oracle_coeffs, +// local_alphas, +// beta_x, +// ); + +// let local_exported_folded_x_evals: HyperKZGExportedLocalEvals = +// local_folded_x_evals.clone().into(); + +// // +// // Collect all exported local folded evals at x to the leader party +// // + +// let mut root_gathering_exported_folded_x_evals: Vec> = +// vec![local_exported_folded_x_evals.clone(); mpi_engine.world_size()]; +// let mut root_aggregated_x_evals = HyperKZGAggregatedEvals::::default(); +// let mut root_folded_y_evals = HyperKZGLocalEvals::::default(); + +// { +// let mut local_exported_folded_x_evals_bytes: Vec = Vec::new(); +// local_exported_folded_x_evals +// .serialize_into(&mut local_exported_folded_x_evals_bytes) +// .unwrap(); + +// let mut gathering_buffer = +// vec![0u8; mpi_engine.world_size() * local_exported_folded_x_evals_bytes.len()]; + +// mpi_engine.gather_vec(&local_exported_folded_x_evals_bytes, &mut gathering_buffer); + +// if mpi_engine.is_root() { +// izip!( +// &mut root_gathering_exported_folded_x_evals, +// gathering_buffer.chunks(local_exported_folded_x_evals_bytes.len()) +// ) +// .for_each(|(es, bs)| { +// let mut cursor = Cursor::new(bs.to_vec()); +// *es = HyperKZGExportedLocalEvals::::deserialize_from(&mut cursor).unwrap(); +// }) +// } +// } + +// // +// // Leader aggregates all local exported evaluations (at x) by evaluating at y +// // by three points: beta_y, -beta_y, beta_y^2, then fold the final evals at x, +// // which is degree 0 for variable x, along variable y. +// // + +// if mpi_engine.is_root() { +// root_aggregated_x_evals = HyperKZGAggregatedEvals::new_from_exported_evals( +// &root_gathering_exported_folded_x_evals, +// beta_y, +// ); + +// root_folded_y_evals = coeff_form_hyperkzg_local_evals( +// &final_evals_at_x, +// &folded_y_oracle_coeffs, +// mpi_alphas, +// beta_y, +// ); +// } + +// // +// // The leader party feeds all evals into RO, then sync party's transcript state +// // + +// if mpi_engine.is_root() { +// root_aggregated_x_evals.append_to_transcript(fs_transcript); +// root_folded_y_evals.append_to_transcript(fs_transcript); +// } + +// transcript_root_broadcast(fs_transcript, mpi_engine); + +// let gamma = fs_transcript.generate_field_element::(); + +// // +// // The leader party linear combines folded coeffs at y with gamma, +// // then broadcast the coeffs back to local. +// // + +// let mut leader_gamma_aggregated_y_coeffs: Vec = +// vec![::zero(); mpi_engine.world_size()]; + +// if mpi_engine.is_root() { +// leader_gamma_aggregated_y_coeffs = { +// let gamma_n = gamma.pow([local_alphas.len() as u64]); +// let mut temp = coeff_form_hyperkzg_local_oracle_polys_aggregate::( +// &final_evals_at_x, +// &folded_y_oracle_coeffs, +// gamma, +// ); +// temp.iter_mut().for_each(|t| *t *= gamma_n); +// temp +// }; +// } + +// // TODO(HS) can be improved to broadcast a vec, returning a coeff to each party +// { +// let mut serialized_y_coeffs: Vec = Vec::new(); +// leader_gamma_aggregated_y_coeffs +// .serialize_into(&mut serialized_y_coeffs) +// .unwrap(); + +// mpi_engine.root_broadcast_bytes(&mut serialized_y_coeffs); +// leader_gamma_aggregated_y_coeffs = { +// let mut cursor = Cursor::new(serialized_y_coeffs); +// Vec::deserialize_from(&mut cursor).unwrap() +// }; +// } + +// // +// // Local party compute the linear combined folded coeffs at x with gamma, +// // then the degree2 Lagrange over beta_x, -beta_x, beta_x^2, +// // then vanish the local aggregated x coeffs at the three points above, +// // and commit to the final quotient poly +// // + +// let mut local_gamma_aggregated_x_coeffs = { +// let mut f_gamma_local = coeff_form_hyperkzg_local_oracle_polys_aggregate::( +// coeffs.hypercube_basis_ref(), +// &local_folded_x_oracle_coeffs, +// gamma, +// ); + +// f_gamma_local[0] += leader_gamma_aggregated_y_coeffs[mpi_engine.world_rank()]; +// f_gamma_local +// }; + +// let local_lagrange_degree2_at_x = { +// let mut local_degree_2 = +// local_folded_x_evals.interpolate_degree2_aggregated_evals(beta_x, gamma); + +// local_degree_2[0] += leader_gamma_aggregated_y_coeffs[mpi_engine.world_rank()]; +// local_degree_2 +// }; + +// let local_gamma_aggregated_x_quotient = { +// let mut nom = local_gamma_aggregated_x_coeffs.clone(); +// polynomial_add( +// &mut nom, +// -E::ScalarField::one(), +// &local_lagrange_degree2_at_x, +// ); +// univariate_roots_quotient(nom, &[beta_x, -beta_x, beta_x * beta_x]) +// }; + +// let local_gamma_aggregated_x_quotient_commitment_g1: E::G1 = +// coeff_form_uni_kzg_commit(&srs.tau_x_srs, &local_gamma_aggregated_x_quotient).into(); + +// // +// // Leader collect all the quotient commitment at x, sum it up and feed it to RO, +// // then sync transcript state +// // + +// let mut root_gathering_gamma_aggregated_x_quotient_commitment_g1s: Vec = +// vec![E::G1::generator(); mpi_engine.world_size()]; +// mpi_engine.gather_vec( +// &[local_gamma_aggregated_x_quotient_commitment_g1], +// &mut root_gathering_gamma_aggregated_x_quotient_commitment_g1s, +// ); + +// let mut gamma_aggregated_x_quotient_commitment: E::G1Affine = E::G1Affine::default(); + +// if mpi_engine.is_root() { +// gamma_aggregated_x_quotient_commitment = +// root_gathering_gamma_aggregated_x_quotient_commitment_g1s +// .iter() +// .sum::() +// .into(); + +// fs_transcript.append_serializable_data(&gamma_aggregated_x_quotient_commitment); +// } + +// transcript_root_broadcast(fs_transcript, mpi_engine); + +// let delta_x = fs_transcript.generate_field_element::(); + +// // +// // Locally compute the Lagrange-degree2 interpolation at delta_x, pool at leader +// // + +// let mut degree2_evals_at_delta_x: Vec = +// vec![::zero(); mpi_engine.world_size()]; + +// let local_degree2_eval_at_delta_x = local_lagrange_degree2_at_x[0] +// + local_lagrange_degree2_at_x[1] * delta_x +// + local_lagrange_degree2_at_x[2] * delta_x * delta_x; + +// mpi_engine.gather_vec( +// &[local_degree2_eval_at_delta_x], +// &mut degree2_evals_at_delta_x, +// ); + +// // +// // Leader does similar thing - quotient at beta_y, -beta_y, beta_y^2, +// // commit the quotient polynomial commitment at y, feed it to RO, +// // then sync transcript state +// // + +// let mut leader_quotient_y_coeffs: Vec = +// vec![::zero(); mpi_engine.world_size()]; +// let mut leader_quotient_y_commitment: E::G1Affine = E::G1Affine::default(); + +// if mpi_engine.is_root() { +// let num_y_coeffs = mpi_engine.world_size(); + +// // NOTE(HS) interpolate at beta_y, beta_y2, -beta_y on lagrange_degree2_delta_x +// let lagrange_degree2_delta_y = { +// let pos_beta_y_pow_series = powers_series(&beta_y, num_y_coeffs); +// let neg_beta_y_pow_series = powers_series(&(-beta_y), num_y_coeffs); +// let beta_y2_pow_series = powers_series(&(beta_y * beta_y), num_y_coeffs); + +// let at_beta_y = univariate_evaluate(°ree2_evals_at_delta_x, +// &pos_beta_y_pow_series); let at_neg_beta_y = +// univariate_evaluate(°ree2_evals_at_delta_x, &neg_beta_y_pow_series); +// let at_beta_y2 = univariate_evaluate(°ree2_evals_at_delta_x, &beta_y2_pow_series); + +// coeff_form_degree2_lagrange( +// [beta_y, -beta_y, beta_y * beta_y], +// [at_beta_y, at_neg_beta_y, at_beta_y2], +// ) +// }; + +// leader_quotient_y_coeffs = { +// let mut nom = degree2_evals_at_delta_x.clone(); +// polynomial_add(&mut nom, -E::ScalarField::one(), &lagrange_degree2_delta_y); +// univariate_roots_quotient(nom, &[beta_y, -beta_y, beta_y * beta_y]) +// }; + +// leader_quotient_y_commitment = +// coeff_form_uni_kzg_commit(&srs.tau_y_srs, &leader_quotient_y_coeffs); +// fs_transcript.append_serializable_data(&leader_quotient_y_commitment); +// } + +// transcript_root_broadcast(fs_transcript, mpi_engine); + +// let delta_y = fs_transcript.generate_field_element::(); + +// // +// // Leader send out the quotient on y coefficients back to local parties +// // + +// // TODO(HS) can be better if the root only send corresponding coeffs to the parties +// { +// let mut serialized_y_quotient_coeffs: Vec = Vec::new(); +// leader_quotient_y_coeffs +// .serialize_into(&mut serialized_y_quotient_coeffs) +// .unwrap(); + +// mpi_engine.root_broadcast_bytes(&mut serialized_y_quotient_coeffs); +// leader_quotient_y_coeffs = { +// let mut cursor = Cursor::new(serialized_y_quotient_coeffs); +// Vec::deserialize_from(&mut cursor).unwrap() +// }; +// leader_quotient_y_coeffs.resize(mpi_engine.world_size(), ::zero()); } + +// // +// // Final step for local - trip off the prior quotients at x and y on \pm beta and beta^2 +// // + +// // NOTE(HS) f_gamma_s - (delta_x - beta_x) ... (delta_x - beta_x2) f_gamma_quotient_s +// // - (delta_y - beta_y) ... (delta_y - beta_y2) lagrange_quotient_y +// let delta_x_denom = (delta_x - beta_x) * (delta_x - beta_x * beta_x) * (delta_x + beta_x); +// let delta_y_denom = (delta_y - beta_y) * (delta_y - beta_y * beta_y) * (delta_y + beta_y); + +// polynomial_add( +// &mut local_gamma_aggregated_x_coeffs, +// -delta_x_denom, +// &local_gamma_aggregated_x_quotient, +// ); +// local_gamma_aggregated_x_coeffs[0] -= +// delta_y_denom * leader_quotient_y_coeffs[mpi_engine.world_rank()]; + +// // +// // BiKZG commit to the last bivariate poly +// // + +// let mut gathered_eval_opens: Vec<(E::ScalarField, E::G1Affine)> = +// vec![(::zero(), E::G1Affine::default()); +// mpi_engine.world_size()]; let local_eval_open = +// coeff_form_uni_kzg_open_eval(&srs.tau_x_srs, &local_gamma_aggregated_x_coeffs, delta_x); + +// mpi_engine.gather_vec(&[local_eval_open], &mut gathered_eval_opens); + +// if !mpi_engine.is_root() { +// return None; +// } + +// let (_, final_opening) = coeff_form_bi_kzg_open_leader(srs, &gathered_eval_opens, delta_y); + +// HyperBiKZGOpening { +// folded_oracle_commitments, +// aggregated_evals: root_aggregated_x_evals, +// leader_evals: root_folded_y_evals.into(), +// beta_x_commitment: gamma_aggregated_x_quotient_commitment, +// beta_y_commitment: leader_quotient_y_commitment, +// quotient_delta_x_commitment: final_opening.quotient_x, +// quotient_delta_y_commitment: final_opening.quotient_y, +// } +// .into() +// } #[allow(clippy::too_many_arguments)] pub fn coeff_form_hyper_bikzg_verify( vk: &BiKZGVerifierParam, - local_alphas: &[E::Fr], - mpi_alphas: &[E::Fr], - eval: E::Fr, + local_alphas: &[E::ScalarField], + mpi_alphas: &[E::ScalarField], + eval: E::ScalarField, commitment: E::G1Affine, opening: &HyperBiKZGOpening, fs_transcript: &mut T, ) -> bool where - E: MultiMillerLoop, + E: Pairing, + E::G1Affine: ExpSerde, + E::G2Affine: ExpSerde, + E::ScalarField: ExtensionField, T: Transcript, - E::G1Affine: CurveAffine + ExpSerde, - E::G2Affine: CurveAffine + ExpSerde, - E::Fr: ExtensionField, { // NOTE(HS) deteriorate to vanilla HyperKZG verify if mpi_alphas is empty if mpi_alphas.is_empty() { @@ -481,13 +485,13 @@ where opening .folded_oracle_commitments .iter() - .for_each(|f| fs_transcript.append_u8_slice(f.to_bytes().as_ref())); + .for_each(|f| fs_transcript.append_serializable_data(f)); // NOTE(HS) transcript MPI thing ... transcript_verifier_sync(fs_transcript, mpi_world_size); - let beta_x = fs_transcript.generate_field_element::(); - let beta_y = fs_transcript.generate_field_element::(); + let beta_x = fs_transcript.generate_field_element::(); + let beta_y = fs_transcript.generate_field_element::(); // dbg!(beta_x, beta_y); @@ -549,7 +553,7 @@ where // NOTE(HS) transcript MPI thing ... transcript_verifier_sync(fs_transcript, mpi_world_size); - let gamma = fs_transcript.generate_field_element::(); + let gamma = fs_transcript.generate_field_element::(); // dbg!(gamma); @@ -560,7 +564,7 @@ where iter::once(&commitment).chain(&opening.folded_oracle_commitments), &gamma_power_series ) - .map(|(com, g)| com.to_curve() * g) + .map(|(com, g)| E::G1::from(*com) * g) .sum(); com_g1.into() @@ -568,7 +572,7 @@ where // NOTE(HS) aggregate lagrange degree 2 polys let (y_beta2, y_beta, y_neg_beta) = { - let gamma_n = gamma.pow_vartime([local_alphas.len() as u64]); + let gamma_n = gamma.pow([local_alphas.len() as u64]); let (v_beta2, v_beta, v_neg_beta) = local_final_eval.gamma_aggregate_evals(gamma); (v_beta2 * gamma_n, v_beta * gamma_n, v_neg_beta * gamma_n) @@ -586,12 +590,12 @@ where neg_beta_y_local.interpolate_degree2_aggregated_evals(beta_x, gamma); aggregated_neg_beta_y_locals[0] += y_neg_beta; - fs_transcript.append_u8_slice(opening.beta_x_commitment.to_bytes().as_ref()); + fs_transcript.append_serializable_data(&opening.beta_x_commitment); // NOTE(HS) transcript MPI thing ... transcript_verifier_sync(fs_transcript, mpi_world_size); - let delta_x = fs_transcript.generate_field_element::(); + let delta_x = fs_transcript.generate_field_element::(); // dbg!(delta_x); @@ -609,12 +613,12 @@ where // dbg!(lagrange_degree2_delta_y); - fs_transcript.append_u8_slice(opening.beta_y_commitment.to_bytes().as_ref()); + fs_transcript.append_serializable_data(&opening.beta_y_commitment); // NOTE(HS) transcript MPI thing ... transcript_verifier_sync(fs_transcript, mpi_world_size); - let delta_y = fs_transcript.generate_field_element::(); + let delta_y = fs_transcript.generate_field_element::(); // dbg!(delta_y); @@ -628,7 +632,7 @@ where let delta_x_denom = (delta_x - beta_x) * (delta_x - beta_x * beta_x) * (delta_x + beta_x); let delta_y_denom = (delta_y - beta_y) * (delta_y - beta_y * beta_y) * (delta_y + beta_y); - let com_r = aggregated_oracle_commitment.to_curve() + let com_r: E::G1 = E::G1::from(aggregated_oracle_commitment) - (opening.beta_x_commitment * delta_x_denom) - (opening.beta_y_commitment * delta_y_denom); @@ -641,7 +645,7 @@ where coeff_form_bi_kzg_verify( vk.clone(), - com_r.to_affine(), + com_r.into(), delta_x, delta_y, degree_2_final_eval, diff --git a/poly_commit/src/kzg/bi_kzg/hyper_bikzg_tests.rs b/poly_commit/src/kzg/bi_kzg/hyper_bikzg_tests.rs index 35d327a55..4bff634f1 100644 --- a/poly_commit/src/kzg/bi_kzg/hyper_bikzg_tests.rs +++ b/poly_commit/src/kzg/bi_kzg/hyper_bikzg_tests.rs @@ -1,16 +1,13 @@ use std::iter; -use arith::ExtensionField; +use arith::{ExtensionField, Field, Fr}; +use ark_bn254::{Bn254, G1Affine, G1Projective}; +use ark_ec::CurveGroup; +use ark_ec::{pairing::Pairing, AffineRepr}; +use ark_ff::{Field as ArkField, UniformRand}; use ark_std::test_rng; use gkr_engine::Transcript; use gkr_hashers::MiMC5FiatShamirHasher; -use halo2curves::{ - bn256::{Bn256, Fr, G1Affine, G1}, - ff::Field, - group::{prime::PrimeCurveAffine, Curve, GroupEncoding}, - pairing::MultiMillerLoop, - CurveAffine, -}; use itertools::{chain, izip}; use polynomials::MultiLinearPoly; use serdes::ExpSerde; @@ -26,17 +23,17 @@ use crate::*; fn coeff_form_hyper_bikzg_open_simulate( srs_s: &[CoefFormBiKZGLocalSRS], - coeffs_s: &[Vec], - local_alphas: &[E::Fr], - mpi_alphas: &[E::Fr], + coeffs_s: &[Vec], + local_alphas: &[E::ScalarField], + mpi_alphas: &[E::ScalarField], fs_transcript: &mut T, ) -> HyperBiKZGOpening where - E: MultiMillerLoop, + E: Pairing, T: Transcript, - E::G1Affine: CurveAffine + ExpSerde, - E::G2Affine: CurveAffine + ExpSerde, - E::Fr: ExtensionField, + E::G1Affine: ExpSerde, + E::G2Affine: ExpSerde, + E::ScalarField: ExtensionField, { // NOTE(HS) deteriorate to vanilla HyperKZG if mpi_alphas is empty, namely single party setting if mpi_alphas.is_empty() { @@ -56,20 +53,21 @@ where let (folded_x_oracle_commits_s, folded_x_oracle_coeffs_s): ( Vec>, - Vec>>, + Vec>>, ) = izip!(srs_s, coeffs_s) .map(|(srs, coeffs)| { coeff_form_hyperkzg_local_poly_oracles(&srs.tau_x_srs, coeffs, local_alphas) }) .unzip(); - let final_evals_at_x: Vec = folded_x_oracle_coeffs_s + let final_evals_at_x: Vec = folded_x_oracle_coeffs_s .iter() .map(|folded_x_oracle_coeffs| { let final_coeffs = folded_x_oracle_coeffs.last().unwrap().clone(); let final_alpha = local_alphas[local_alphas.len() - 1]; - (E::Fr::ONE - final_alpha) * final_coeffs[0] + final_alpha * final_coeffs[1] + (::one() - final_alpha) * final_coeffs[0] + + final_alpha * final_coeffs[1] }) .collect(); @@ -81,10 +79,10 @@ where .map(|i| { let ith_fold_commits: E::G1 = folded_x_oracle_commits_s .iter() - .map(|f| f[i].to_curve()) + .map(|f| E::G1::from(f[i])) .sum(); - ith_fold_commits.to_affine() + ith_fold_commits.into_affine() }) .collect(); @@ -113,10 +111,10 @@ where iter::once(&y_oracle_commit), &folded_y_oracle_commits, ) - .for_each(|f| fs_transcript.append_u8_slice(f.to_bytes().as_ref())); + .for_each(|f| fs_transcript.append_serializable_data(f)); - let beta_x = fs_transcript.generate_field_element::(); - let beta_y = fs_transcript.generate_field_element::(); + let beta_x = fs_transcript.generate_field_element::(); + let beta_y = fs_transcript.generate_field_element::(); dbg!(beta_x, beta_y); @@ -159,7 +157,7 @@ where // NOTE(HS) check if the final eval of root evals match with mle poly evaluation dbg!(&root_evals.multilinear_final_eval()); - let gamma = fs_transcript.generate_field_element::(); + let gamma = fs_transcript.generate_field_element::(); dbg!(gamma); @@ -169,7 +167,7 @@ where // let f_gamma_global = { - let gamma_n = gamma.pow_vartime([local_alphas.len() as u64]); + let gamma_n = gamma.pow([local_alphas.len() as u64]); let mut temp = coeff_form_hyperkzg_local_oracle_polys_aggregate::( &final_evals_at_x, &folded_y_oracle_coeffs_s, @@ -186,16 +184,17 @@ where // and commit to the final quotient poly // - let mut f_gamma_s: Vec> = { - let mut f_gamma_s_local: Vec> = izip!(coeffs_s, folded_x_oracle_coeffs_s) - .map(|(coeffs, folded_oracle_coeffs)| { - coeff_form_hyperkzg_local_oracle_polys_aggregate::( - coeffs, - &folded_oracle_coeffs, - gamma, - ) - }) - .collect(); + let mut f_gamma_s: Vec> = { + let mut f_gamma_s_local: Vec> = + izip!(coeffs_s, folded_x_oracle_coeffs_s) + .map(|(coeffs, folded_oracle_coeffs)| { + coeff_form_hyperkzg_local_oracle_polys_aggregate::( + coeffs, + &folded_oracle_coeffs, + gamma, + ) + }) + .collect(); izip!(&mut f_gamma_s_local, &f_gamma_global) .for_each(|(f_g, f_global)| f_g[0] += *f_global); @@ -203,7 +202,7 @@ where f_gamma_s_local }; - let lagrange_degree2_s: Vec<[E::Fr; 3]> = izip!(folded_x_evals_s, &f_gamma_global) + let lagrange_degree2_s: Vec<[E::ScalarField; 3]> = izip!(folded_x_evals_s, &f_gamma_global) .map(|(l, g)| { let mut local_degree_2 = l.interpolate_degree2_aggregated_evals(beta_x, gamma); local_degree_2[0] += g; @@ -211,16 +210,20 @@ where }) .collect(); - let f_gamma_quotient_s: Vec> = izip!(&f_gamma_s, &lagrange_degree2_s) + let f_gamma_quotient_s: Vec> = izip!(&f_gamma_s, &lagrange_degree2_s) .map(|(f_gamma, lagrange_degree2)| { let mut nom = f_gamma.clone(); - polynomial_add(&mut nom, -E::Fr::ONE, lagrange_degree2); + polynomial_add( + &mut nom, + -::one(), + lagrange_degree2, + ); univariate_roots_quotient(nom, &[beta_x, -beta_x, beta_x * beta_x]) }) .collect(); let f_gamma_quotient_com_s: Vec = izip!(srs_s, &f_gamma_quotient_s) .map(|(srs, f_gamma_quotient)| { - coeff_form_uni_kzg_commit(&srs.tau_x_srs, f_gamma_quotient).to_curve() + coeff_form_uni_kzg_commit(&srs.tau_x_srs, f_gamma_quotient).into() }) .collect(); @@ -231,9 +234,9 @@ where let f_gamma_quotient_com_x: E::G1Affine = f_gamma_quotient_com_s.iter().sum::().into(); - fs_transcript.append_u8_slice(f_gamma_quotient_com_x.to_bytes().as_ref()); + fs_transcript.append_serializable_data(&f_gamma_quotient_com_x); - let delta_x = fs_transcript.generate_field_element::(); + let delta_x = fs_transcript.generate_field_element::(); dbg!(delta_x); @@ -241,7 +244,7 @@ where // Locally compute the Lagrange-degree2 interpolation at delta_x, pool at leader // - let lagrange_degree2_delta_x: Vec = lagrange_degree2_s + let lagrange_degree2_delta_x: Vec = lagrange_degree2_s .iter() .map(|l| l[0] + l[1] * delta_x + l[2] * delta_x * delta_x) .collect(); @@ -274,10 +277,17 @@ where // NOTE(HS) vanish over the three beta_y points above, then commit Q_y let mut f_gamma_quotient_y = { let mut nom = lagrange_degree2_delta_x.clone(); - polynomial_add(&mut nom, -E::Fr::ONE, &lagrange_degree2_delta_y); + polynomial_add( + &mut nom, + -::one(), + &lagrange_degree2_delta_y, + ); univariate_roots_quotient(nom, &[beta_y, -beta_y, beta_y * beta_y]) }; - f_gamma_quotient_y.resize(lagrange_degree2_delta_x.len(), E::Fr::ZERO); + f_gamma_quotient_y.resize( + lagrange_degree2_delta_x.len(), + ::zero(), + ); let f_gamma_quotient_com_y = coeff_form_uni_kzg_commit(&srs_s[0].tau_y_srs, &f_gamma_quotient_y); @@ -285,9 +295,9 @@ where dbg!(f_gamma_quotient_y.len()); // NOTE(HS) sample from RO for delta_y - fs_transcript.append_u8_slice(f_gamma_quotient_com_y.to_bytes().as_ref()); + fs_transcript.append_serializable_data(&f_gamma_quotient_com_y); - let delta_y = fs_transcript.generate_field_element::(); + let delta_y = fs_transcript.generate_field_element::(); dbg!(delta_y); @@ -308,7 +318,7 @@ where ); // NOTE(HS) bivariate KZG opening - let evals_and_opens: Vec<(E::Fr, E::G1Affine)> = izip!(srs_s, &f_gamma_s) + let evals_and_opens: Vec<(E::ScalarField, E::G1Affine)> = izip!(srs_s, &f_gamma_s) .map(|(srs, x_coeffs)| coeff_form_uni_kzg_open_eval(&srs.tau_x_srs, x_coeffs, delta_x)) .collect(); @@ -327,19 +337,19 @@ where fn coeff_form_hyper_bikzg_verify_simulate( vk: &BiKZGVerifierParam, - local_alphas: &[E::Fr], - mpi_alphas: &[E::Fr], - eval: E::Fr, + local_alphas: &[E::ScalarField], + mpi_alphas: &[E::ScalarField], + eval: E::ScalarField, commitment: E::G1Affine, opening: &HyperBiKZGOpening, fs_transcript: &mut T, ) -> bool where - E: MultiMillerLoop, + E: Pairing, T: Transcript, - E::G1Affine: CurveAffine + ExpSerde, - E::G2Affine: CurveAffine + ExpSerde, - E::Fr: ExtensionField, + E::G1Affine: ExpSerde, + E::G2Affine: ExpSerde, + E::ScalarField: ExtensionField, { // NOTE(HS) deteriorate to vanilla HyperKZG verify if mpi_alphas is empty if mpi_alphas.is_empty() { @@ -361,10 +371,10 @@ where opening .folded_oracle_commitments .iter() - .for_each(|f| fs_transcript.append_u8_slice(f.to_bytes().as_ref())); + .for_each(|f| fs_transcript.append_serializable_data(f)); - let beta_x = fs_transcript.generate_field_element::(); - let beta_y = fs_transcript.generate_field_element::(); + let beta_x = fs_transcript.generate_field_element::(); + let beta_y = fs_transcript.generate_field_element::(); dbg!(beta_x, beta_y); @@ -423,7 +433,7 @@ where opening.aggregated_evals.append_to_transcript(fs_transcript); opening.leader_evals.append_to_transcript(fs_transcript); - let gamma = fs_transcript.generate_field_element::(); + let gamma = fs_transcript.generate_field_element::(); dbg!(gamma); @@ -434,7 +444,7 @@ where iter::once(&commitment).chain(&opening.folded_oracle_commitments), &gamma_power_series ) - .map(|(com, g)| com.to_curve() * g) + .map(|(com, g)| *com * g) .sum(); com_g1.into() @@ -442,7 +452,7 @@ where // NOTE(HS) aggregate lagrange degree 2 polys let (y_beta2, y_beta, y_neg_beta) = { - let gamma_n = gamma.pow_vartime([local_alphas.len() as u64]); + let gamma_n = gamma.pow([local_alphas.len() as u64]); let (v_beta2, v_beta, v_neg_beta) = local_final_eval.gamma_aggregate_evals(gamma); (v_beta2 * gamma_n, v_beta * gamma_n, v_neg_beta * gamma_n) @@ -460,9 +470,9 @@ where neg_beta_y_local.interpolate_degree2_aggregated_evals(beta_x, gamma); aggregated_neg_beta_y_locals[0] += y_neg_beta; - fs_transcript.append_u8_slice(opening.beta_x_commitment.to_bytes().as_ref()); + fs_transcript.append_serializable_data(&opening.beta_x_commitment); - let delta_x = fs_transcript.generate_field_element::(); + let delta_x = fs_transcript.generate_field_element::(); dbg!(delta_x); @@ -480,9 +490,9 @@ where dbg!(lagrange_degree2_delta_y); - fs_transcript.append_u8_slice(opening.beta_y_commitment.to_bytes().as_ref()); + fs_transcript.append_serializable_data(&opening.beta_y_commitment); - let delta_y = fs_transcript.generate_field_element::(); + let delta_y = fs_transcript.generate_field_element::(); dbg!(delta_y); @@ -496,7 +506,7 @@ where let delta_x_denom = (delta_x - beta_x) * (delta_x - beta_x * beta_x) * (delta_x + beta_x); let delta_y_denom = (delta_y - beta_y) * (delta_y - beta_y * beta_y) * (delta_y + beta_y); - let com_r = aggregated_oracle_commitment.to_curve() + let com_r = aggregated_oracle_commitment - (opening.beta_x_commitment * delta_x_denom) - (opening.beta_y_commitment * delta_y_denom); @@ -509,7 +519,7 @@ where let what = coeff_form_bi_kzg_verify( vk.clone(), - com_r.to_affine(), + com_r.into_affine(), delta_x, delta_y, degree_2_final_eval, @@ -534,10 +544,10 @@ fn test_hyper_bikzg_single_process_simulated_e2e() { let mut rng = test_rng(); - let local_alphas: Vec<_> = (0..x_vars).map(|_| Fr::random(&mut rng)).collect(); - let mpi_alphas: Vec<_> = (0..y_vars).map(|_| Fr::random(&mut rng)).collect(); + let local_alphas: Vec<_> = (0..x_vars).map(|_| Fr::rand(&mut rng)).collect(); + let mpi_alphas: Vec<_> = (0..y_vars).map(|_| Fr::rand(&mut rng)).collect(); - let party_srs: Vec> = (0..=y_degree) + let party_srs: Vec> = (0..=y_degree) .map(|rank| { let mut srs_rng = test_rng(); generate_coef_form_bi_kzg_local_srs_for_testing( @@ -550,7 +560,7 @@ fn test_hyper_bikzg_single_process_simulated_e2e() { .collect(); let xy_coeffs: Vec> = (0..=y_degree) - .map(|_| (0..=x_degree).map(|_| Fr::random(&mut rng)).collect()) + .map(|_| (0..=x_degree).map(|_| Fr::rand(&mut rng)).collect()) .collect(); let all_alphas = { @@ -573,8 +583,8 @@ fn test_hyper_bikzg_single_process_simulated_e2e() { .map(|(srs, x_coeffs)| coeff_form_uni_kzg_commit(&srs.tau_x_srs, x_coeffs)) .collect(); - let global_commitment_g1: G1 = commitments.iter().map(|c| c.to_curve()).sum(); - global_commitment_g1.to_affine() + let global_commitment_g1: G1Projective = commitments.iter().map(|c| c.into_group()).sum(); + global_commitment_g1.into() }; let mut fs_transcript = BytesHashTranscript::>::new(); @@ -588,7 +598,7 @@ fn test_hyper_bikzg_single_process_simulated_e2e() { &mut fs_transcript, ); - let vk: BiKZGVerifierParam = From::from(&party_srs[0]); + let vk: BiKZGVerifierParam = From::from(&party_srs[0]); let what = coeff_form_hyper_bikzg_verify_simulate( &vk, &local_alphas, diff --git a/poly_commit/src/kzg/bi_kzg/pcs_trait_impl.rs b/poly_commit/src/kzg/bi_kzg/pcs_trait_impl.rs index 86b39ff40..132614677 100644 --- a/poly_commit/src/kzg/bi_kzg/pcs_trait_impl.rs +++ b/poly_commit/src/kzg/bi_kzg/pcs_trait_impl.rs @@ -1,12 +1,9 @@ use std::marker::PhantomData; use arith::ExtensionField; +use ark_ec::pairing::Pairing; +use ark_std::rand::RngCore; use gkr_engine::{StructuredReferenceString, Transcript}; -use halo2curves::{ - ff::PrimeField, - pairing::{Engine, MultiMillerLoop}, - CurveAffine, -}; use polynomials::{MultiLinearPoly, MultilinearExtension}; use serdes::ExpSerde; @@ -22,32 +19,32 @@ use super::{ pub struct HyperBiKZGPCS where - E: Engine, - E::Fr: ExtensionField, + E: Pairing, + E::ScalarField: ExtensionField, { _marker_e: PhantomData, } impl HyperBiKZGPCS where - E: Engine, - E::Fr: ExtensionField, + E: Pairing, + E::ScalarField: ExtensionField, { pub const MINIMUM_SUPPORTED_NUM_VARS: usize = 2; } -impl PolynomialCommitmentScheme for HyperBiKZGPCS +impl PolynomialCommitmentScheme for HyperBiKZGPCS where - E: Engine + MultiMillerLoop, - E::Fr: ExtensionField + PrimeField, - E::G1Affine: ExpSerde + Default + CurveAffine, - E::G2Affine: ExpSerde + Default + CurveAffine, + E: Pairing, + E::ScalarField: ExtensionField, + E::G1Affine: ExpSerde + Default, + E::G2Affine: ExpSerde + Default, { const NAME: &'static str = "HyperBiKZGPCS"; type Params = usize; - type Poly = MultiLinearPoly; - type EvalPoint = Vec; + type Poly = MultiLinearPoly; + type EvalPoint = Vec; type ScratchPad = (); type SRS = CoefFormBiKZGLocalSRS; @@ -56,7 +53,7 @@ where fn init_scratch_pad(_params: &Self::Params) -> Self::ScratchPad {} - fn gen_srs_for_testing(params: &Self::Params, rng: impl rand::RngCore) -> (Self::SRS, usize) { + fn gen_srs_for_testing(params: &Self::Params, rng: impl RngCore) -> (Self::SRS, usize) { let local_num_vars = if *params == 0 { 1 } else { *params }; let length = 1 << local_num_vars; @@ -83,7 +80,7 @@ where x: &Self::EvalPoint, _scratch_pad: &Self::ScratchPad, transcript: &mut impl Transcript, - ) -> (E::Fr, Self::Opening) { + ) -> (E::ScalarField, Self::Opening) { let (eval, hyperkzg_opening) = coeff_form_uni_hyperkzg_open( &proving_key.tau_x_srs, poly.hypercube_basis_ref(), @@ -100,7 +97,7 @@ where verifying_key: &::VKey, commitment: &Self::Commitment, x: &Self::EvalPoint, - v: E::Fr, + v: E::ScalarField, opening: &Self::Opening, transcript: &mut impl Transcript, ) -> bool { diff --git a/poly_commit/src/kzg/bi_kzg/structs_bi_kzg.rs b/poly_commit/src/kzg/bi_kzg/structs_bi_kzg.rs index 161a2461b..fa5594b24 100644 --- a/poly_commit/src/kzg/bi_kzg/structs_bi_kzg.rs +++ b/poly_commit/src/kzg/bi_kzg/structs_bi_kzg.rs @@ -1,20 +1,18 @@ +use ark_ec::pairing::Pairing; use derivative::Derivative; use gkr_engine::StructuredReferenceString; -use halo2curves::{pairing::Engine, CurveAffine}; use serdes::{ExpSerde, SerdeResult}; use crate::{CoefFormUniKZGSRS, UniKZGVerifierParams}; #[derive(Clone, Copy, Debug, PartialEq, Eq, Derivative)] #[derivative(Default(bound = ""))] -pub struct BiKZGCommitment(pub E::G1Affine) -where - E::G1Affine: CurveAffine; +pub struct BiKZGCommitment(pub E::G1Affine); // Derive macros does not work for associated types -impl ExpSerde for BiKZGCommitment +impl ExpSerde for BiKZGCommitment where - E::G1Affine: ExpSerde + CurveAffine, + E::G1Affine: ExpSerde, { fn serialize_into(&self, writer: W) -> SerdeResult<()> { self.0.serialize_into(writer) @@ -27,10 +25,10 @@ where #[derive(Clone, Debug, PartialEq, Eq, Derivative, ExpSerde)] #[derivative(Default(bound = ""))] -pub struct CoefFormBiKZGLocalSRS +pub struct CoefFormBiKZGLocalSRS where E::G1Affine: ExpSerde, - E::G2Affine: CurveAffine + ExpSerde, + E::G2Affine: ExpSerde, { pub tau_x_srs: CoefFormUniKZGSRS, pub tau_y_srs: CoefFormUniKZGSRS, @@ -38,10 +36,10 @@ where /// Bivariate KZG PCS verifier's params. #[derive(Copy, Clone, Debug, Eq, PartialEq, Default, ExpSerde)] -pub struct BiKZGVerifierParam +pub struct BiKZGVerifierParam where E::G1Affine: ExpSerde, - E::G2Affine: CurveAffine + ExpSerde, + E::G2Affine: ExpSerde, { /// tau_x over G2. pub tau_x_g2: E::G2Affine, @@ -49,10 +47,10 @@ where pub tau_y_g2: E::G2Affine, } -impl From<&CoefFormBiKZGLocalSRS> for BiKZGVerifierParam +impl From<&CoefFormBiKZGLocalSRS> for BiKZGVerifierParam where E::G1Affine: ExpSerde, - E::G2Affine: CurveAffine + ExpSerde, + E::G2Affine: ExpSerde, { fn from(srs: &CoefFormBiKZGLocalSRS) -> Self { Self { @@ -62,10 +60,10 @@ where } } -impl StructuredReferenceString for CoefFormBiKZGLocalSRS +impl StructuredReferenceString for CoefFormBiKZGLocalSRS where - ::G1Affine: ExpSerde + CurveAffine, - ::G2Affine: ExpSerde + CurveAffine, + E::G1Affine: ExpSerde, + E::G2Affine: ExpSerde, { type PKey = CoefFormBiKZGLocalSRS; type VKey = BiKZGVerifierParam; @@ -76,10 +74,10 @@ where } } -impl From<&BiKZGVerifierParam> for UniKZGVerifierParams +impl From<&BiKZGVerifierParam> for UniKZGVerifierParams where E::G1Affine: ExpSerde, - E::G2Affine: CurveAffine + ExpSerde, + E::G2Affine: ExpSerde, { fn from(value: &BiKZGVerifierParam) -> Self { Self { @@ -90,7 +88,7 @@ where /// Proof for Bi-KZG polynomial commitment scheme. #[derive(Copy, Clone, Debug, Default, PartialEq, Eq)] -pub struct BiKZGProof { +pub struct BiKZGProof { pub quotient_x: E::G1Affine, pub quotient_y: E::G1Affine, } diff --git a/poly_commit/src/kzg/bi_kzg/structs_hyper_bi_kzg.rs b/poly_commit/src/kzg/bi_kzg/structs_hyper_bi_kzg.rs index a16c84eb1..6fc36a599 100644 --- a/poly_commit/src/kzg/bi_kzg/structs_hyper_bi_kzg.rs +++ b/poly_commit/src/kzg/bi_kzg/structs_hyper_bi_kzg.rs @@ -1,14 +1,14 @@ +use ark_ec::pairing::Pairing; use derivative::Derivative; -use halo2curves::pairing::Engine; use serdes::ExpSerde; use crate::*; #[derive(Debug, Clone, Derivative, ExpSerde)] #[derivative(Default(bound = ""))] -pub struct HyperBiKZGOpening +pub struct HyperBiKZGOpening where - E::Fr: ExpSerde, + E::ScalarField: ExpSerde, E::G1Affine: Default + ExpSerde, { pub folded_oracle_commitments: Vec, @@ -23,9 +23,9 @@ where pub quotient_delta_y_commitment: E::G1Affine, } -impl From> for HyperUniKZGOpening +impl From> for HyperUniKZGOpening where - E::Fr: ExpSerde, + E::ScalarField: ExpSerde, E::G1Affine: Default + ExpSerde, { fn from(value: HyperBiKZGOpening) -> Self { @@ -38,9 +38,9 @@ where } } -impl From> for HyperBiKZGOpening +impl From> for HyperBiKZGOpening where - E::Fr: ExpSerde, + E::ScalarField: ExpSerde, E::G1Affine: Default + ExpSerde, { fn from(value: HyperUniKZGOpening) -> Self { diff --git a/poly_commit/src/kzg/uni_kzg/batch.rs b/poly_commit/src/kzg/uni_kzg/batch.rs index 709fb348b..ed7116d83 100644 --- a/poly_commit/src/kzg/uni_kzg/batch.rs +++ b/poly_commit/src/kzg/uni_kzg/batch.rs @@ -1,7 +1,6 @@ use arith::{ExtensionField, Field}; +use ark_ec::{pairing::Pairing, VariableBaseMSM}; use gkr_engine::Transcript; -use halo2curves::group::Group; -use halo2curves::{group::Curve, msm::multiexp_serial, pairing::MultiMillerLoop, CurveAffine}; use polynomials::MultiLinearPoly; use serdes::ExpSerde; @@ -12,20 +11,20 @@ use crate::{ pub(crate) fn kzg_single_point_batch_open( proving_key: &CoefFormUniKZGSRS, - polys: &[MultiLinearPoly], - x: &[E::Fr], + polys: &[MultiLinearPoly], + x: &[E::ScalarField], transcript: &mut impl Transcript, -) -> (Vec, HyperUniKZGOpening) +) -> (Vec, HyperUniKZGOpening) where - E: MultiMillerLoop, - E::G1Affine: CurveAffine + ExpSerde, - E::G2Affine: CurveAffine + ExpSerde, - E::Fr: ExtensionField, + E: Pairing, + E::G1Affine: ExpSerde, + E::G2Affine: ExpSerde, + E::ScalarField: ExtensionField, { - let rlc_randomness = transcript.generate_field_element::(); + let rlc_randomness = transcript.generate_field_element::(); let num_poly = polys.len(); let rlcs = powers_series(&rlc_randomness, num_poly); - let mut buf = vec![E::Fr::default(); polys[0].coeffs.len()]; + let mut buf = vec![E::ScalarField::default(); polys[0].coeffs.len()]; let merged_poly = polys .iter() @@ -57,33 +56,32 @@ where pub(crate) fn kzg_single_point_batch_verify( verifying_key: &UniKZGVerifierParams, commitments: &[E::G1Affine], - x: &[E::Fr], - evals: &[E::Fr], + x: &[E::ScalarField], + evals: &[E::ScalarField], opening: &HyperUniKZGOpening, transcript: &mut impl Transcript, ) -> bool where - E: MultiMillerLoop, - E::G1Affine: CurveAffine + ExpSerde, + E: Pairing, + E::G1Affine: ExpSerde, E::G2Affine: ExpSerde, - E::Fr: ExtensionField + ExpSerde, + E::ScalarField: ExtensionField + ExpSerde, { - let rlc_randomness = transcript.generate_field_element::(); + let rlc_randomness = transcript.generate_field_element::(); let num_poly = commitments.len(); let rlcs = powers_series(&rlc_randomness, num_poly); // stay with single thread as the num_poly is usually small - let mut merged_commitment = E::G1::identity(); - multiexp_serial(&rlcs, commitments, &mut merged_commitment); + let merged_commitment: E::G1 = VariableBaseMSM::msm(commitments, &rlcs).unwrap(); let merged_eval = evals .iter() .zip(rlcs.iter()) - .fold(E::Fr::zero(), |acc, (e, r)| acc + (*e * r)); + .fold(E::ScalarField::zero(), |acc, (e, r)| acc + (*e * r)); coeff_form_uni_hyperkzg_verify( verifying_key, - merged_commitment.to_affine(), + merged_commitment.into(), x, merged_eval, opening, diff --git a/poly_commit/src/kzg/uni_kzg/expander_api.rs b/poly_commit/src/kzg/uni_kzg/expander_api.rs index 3225481af..d18a83782 100644 --- a/poly_commit/src/kzg/uni_kzg/expander_api.rs +++ b/poly_commit/src/kzg/uni_kzg/expander_api.rs @@ -1,13 +1,10 @@ use arith::ExtensionField; +use ark_ec::pairing::Pairing; +use ark_std::rand::RngCore; use gkr_engine::{ - ExpanderPCS, ExpanderSingleVarChallenge, FieldEngine, MPIEngine, PolynomialCommitmentType, + ExpanderPCS, ExpanderSingleVarChallenge, FieldEngine, PolynomialCommitmentType, StructuredReferenceString, Transcript, }; -use halo2curves::{ - ff::PrimeField, - pairing::{Engine, MultiMillerLoop}, - CurveAffine, -}; use polynomials::MultilinearExtension; use serdes::ExpSerde; @@ -22,11 +19,11 @@ use crate::{ impl ExpanderPCS for HyperUniKZGPCS where - G: FieldEngine, - E: Engine + MultiMillerLoop, - E::Fr: ExtensionField + PrimeField, - E::G1Affine: ExpSerde + Default + CurveAffine, - E::G2Affine: ExpSerde + Default + CurveAffine, + G: FieldEngine, + E: Pairing, + E::ScalarField: ExtensionField, + E::G1Affine: ExpSerde + Default, + E::G2Affine: ExpSerde + Default, { const NAME: &'static str = "HyperUniKZGForExpander"; @@ -37,9 +34,9 @@ where type Params = usize; type SRS = CoefFormUniKZGSRS; type ScratchPad = (); - type BatchOpening = BatchOpening; + type BatchOpening = BatchOpening; - fn init_scratch_pad(_params: &Self::Params, _mpi_engine: &impl MPIEngine) -> Self::ScratchPad {} + fn init_scratch_pad(_params: &Self::Params) -> Self::ScratchPad {} fn gen_params(n_input_vars: usize, world_size: usize) -> Self::Params { assert_eq!( @@ -49,11 +46,7 @@ where std::cmp::max(n_input_vars, Self::MINIMUM_SUPPORTED_NUM_VARS) } - fn gen_srs( - params: &Self::Params, - _mpi_engine: &impl MPIEngine, - rng: impl rand::RngCore, - ) -> Self::SRS { + fn gen_srs(params: &Self::Params, rng: impl RngCore) -> Self::SRS { assert!( *params >= Self::MINIMUM_SUPPORTED_NUM_VARS, "params must be at least {}", @@ -65,21 +58,14 @@ where fn commit( params: &Self::Params, - mpi_engine: &impl MPIEngine, proving_key: &::PKey, - poly: &impl polynomials::MultilinearExtension, + poly: &impl polynomials::MultilinearExtension, scratch_pad: &mut Self::ScratchPad, ) -> Option { if poly.num_vars() < Self::MINIMUM_SUPPORTED_NUM_VARS { assert_eq!(*params, Self::MINIMUM_SUPPORTED_NUM_VARS); let poly = lift_poly_to_n_vars(poly, *params); - return >::commit( - params, - mpi_engine, - proving_key, - &poly, - scratch_pad, - ); + return >::commit(params, proving_key, &poly, scratch_pad); } let commitment = coeff_form_uni_kzg_commit(proving_key, poly.hypercube_basis_ref()); @@ -88,9 +74,9 @@ where fn open( params: &Self::Params, - mpi_engine: &impl MPIEngine, + proving_key: &::PKey, - poly: &impl MultilinearExtension, + poly: &impl MultilinearExtension, x: &ExpanderSingleVarChallenge, transcript: &mut impl Transcript, scratch_pad: &Self::ScratchPad, @@ -100,7 +86,6 @@ where let (poly, x) = lift_poly_and_expander_challenge_to_n_vars(poly, x, *params); return >::open( params, - mpi_engine, proving_key, &poly, &x, @@ -154,14 +139,13 @@ where /// Open a set of polynomials at a point. fn multi_points_batch_open( _params: &Self::Params, - _mpi_engine: &impl MPIEngine, proving_key: &::PKey, - polys: &[impl MultilinearExtension], + polys: &[impl MultilinearExtension], x: &[ExpanderSingleVarChallenge], _scratch_pad: &Self::ScratchPad, transcript: &mut impl Transcript, - ) -> (Vec, Self::BatchOpening) { - let points: Vec> = x.iter().map(|p| p.local_xs()).collect(); + ) -> (Vec, Self::BatchOpening) { + let points: Vec> = x.iter().map(|p| p.local_xs()).collect(); multiple_points_batch_open_impl(proving_key, polys, points.as_ref(), transcript) } @@ -171,11 +155,11 @@ where verifying_key: &::VKey, commitments: &[impl AsRef], x: &[ExpanderSingleVarChallenge], - evals: &[E::Fr], + evals: &[E::ScalarField], batch_opening: &Self::BatchOpening, transcript: &mut impl Transcript, ) -> bool { - let points: Vec> = x.iter().map(|p| p.local_xs()).collect(); + let points: Vec> = x.iter().map(|p| p.local_xs()).collect(); multiple_points_batch_verify_impl( verifying_key, diff --git a/poly_commit/src/kzg/uni_kzg/hyper_kzg.rs b/poly_commit/src/kzg/uni_kzg/hyper_kzg.rs index a3f453439..0cab2d1cd 100644 --- a/poly_commit/src/kzg/uni_kzg/hyper_kzg.rs +++ b/poly_commit/src/kzg/uni_kzg/hyper_kzg.rs @@ -1,14 +1,9 @@ use std::iter; use ::utils::timer::Timer; -use arith::ExtensionField; +use arith::{ExtensionField, Field}; +use ark_ec::pairing::Pairing; use gkr_engine::Transcript; -use halo2curves::{ - ff::{Field, PrimeField}, - group::{prime::PrimeCurveAffine, GroupEncoding}, - pairing::{Engine, MultiMillerLoop}, - CurveAffine, -}; use itertools::izip; use polynomials::MultilinearExtension; use rayon::iter::{IndexedParallelIterator, IntoParallelRefIterator, ParallelIterator}; @@ -23,14 +18,14 @@ use crate::{ #[inline(always)] pub(crate) fn coeff_form_hyperkzg_local_poly_oracles( srs: &CoefFormUniKZGSRS, - coeffs: &[E::Fr], - local_alphas: &[E::Fr], -) -> (Vec, Vec>) + coeffs: &[E::ScalarField], + local_alphas: &[E::ScalarField], +) -> (Vec, Vec>) where - E: MultiMillerLoop, - E::G1Affine: CurveAffine + ExpSerde, - E::G2Affine: CurveAffine + ExpSerde, - E::Fr: ExtensionField, + E: Pairing, + E::G1Affine: ExpSerde, + E::G2Affine: ExpSerde, + E::ScalarField: ExtensionField, { let mut local_coeffs = coeffs.to_vec(); @@ -39,7 +34,7 @@ where .map(|alpha| { local_coeffs = local_coeffs .chunks(2) - .map(|c| (E::Fr::ONE - alpha) * c[0] + *alpha * c[1]) + .map(|c| (E::ScalarField::one() - alpha) * c[0] + *alpha * c[1]) .collect(); let folded_oracle_commit = coeff_form_uni_kzg_commit(srs, &local_coeffs); @@ -51,19 +46,18 @@ where #[inline(always)] pub(crate) fn coeff_form_hyperkzg_local_evals( - coeffs: &[E::Fr], - folded_oracle_coeffs: &[Vec], - local_alphas: &[E::Fr], - beta: E::Fr, + coeffs: &[E::ScalarField], + folded_oracle_coeffs: &[Vec], + local_alphas: &[E::ScalarField], + beta: E::ScalarField, ) -> HyperKZGLocalEvals where - E: MultiMillerLoop, - E::G1Affine: CurveAffine, - E::Fr: ExtensionField, + E: Pairing, + E::ScalarField: ExtensionField, { let beta2 = beta * beta; - let beta_inv = beta.invert().unwrap(); - let two_inv = E::Fr::ONE.double().invert().unwrap(); + let beta_inv = beta.inv().unwrap(); + let two_inv = E::ScalarField::one().double().inv().unwrap(); let beta_pow_series = powers_series(&beta, coeffs.len()); let neg_beta_pow_series = powers_series(&(-beta), coeffs.len()); @@ -83,7 +77,7 @@ where let neg_beta_eval = univariate_evaluate(cs, &neg_beta_pow_series); let beta2_eval = two_inv - * ((beta_eval + neg_beta_eval) * (E::Fr::ONE - alpha) + * ((beta_eval + neg_beta_eval) * (E::ScalarField::one() - alpha) + (beta_eval - neg_beta_eval) * beta_inv * alpha); local_evals.beta2_evals.push(beta2_eval); @@ -96,14 +90,13 @@ where #[inline(always)] pub(crate) fn coeff_form_hyperkzg_local_oracle_polys_aggregate( - coeffs: &[E::Fr], - folded_oracle_coeffs: &[Vec], - gamma: E::Fr, -) -> Vec + coeffs: &[E::ScalarField], + folded_oracle_coeffs: &[Vec], + gamma: E::ScalarField, +) -> Vec where - E: MultiMillerLoop, - E::G1Affine: CurveAffine, - E::Fr: ExtensionField, + E: Pairing, + E::ScalarField: ExtensionField, { let gamma_pow_series = powers_series(&gamma, folded_oracle_coeffs.len() + 1); let mut f = coeffs.to_vec(); @@ -115,46 +108,46 @@ where #[inline(always)] pub fn coeff_form_uni_hyperkzg_open( srs: &CoefFormUniKZGSRS, - coeffs: &[E::Fr], - alphas: &[E::Fr], + coeffs: &[E::ScalarField], + alphas: &[E::ScalarField], fs_transcript: &mut T, -) -> (E::Fr, HyperUniKZGOpening) +) -> (E::ScalarField, HyperUniKZGOpening) where - E: MultiMillerLoop, - E::G1Affine: CurveAffine + ExpSerde, - E::G2Affine: CurveAffine + ExpSerde, - E::Fr: ExtensionField, + E: Pairing, + E::G1Affine: ExpSerde, + E::G2Affine: ExpSerde, + E::ScalarField: ExtensionField, T: Transcript, { let (folded_oracle_commitments, folded_oracle_coeffs) = coeff_form_hyperkzg_local_poly_oracles(srs, coeffs, alphas); folded_oracle_commitments.iter().for_each(|f| { - fs_transcript.append_u8_slice(f.to_bytes().as_ref()); + fs_transcript.append_serializable_data(f); }); - let beta = fs_transcript.generate_field_element::(); + let beta = fs_transcript.generate_field_element::(); let beta2 = beta * beta; let local_evals = coeff_form_hyperkzg_local_evals::(coeffs, &folded_oracle_coeffs, alphas, beta); local_evals.append_to_transcript(fs_transcript); - let gamma = fs_transcript.generate_field_element::(); + let gamma = fs_transcript.generate_field_element::(); let mut f_gamma = coeff_form_hyperkzg_local_oracle_polys_aggregate::(coeffs, &folded_oracle_coeffs, gamma); let lagrange_degree2 = local_evals.interpolate_degree2_aggregated_evals(beta, gamma); let f_gamma_quotient = { let mut nom = f_gamma.clone(); - polynomial_add(&mut nom, -E::Fr::ONE, &lagrange_degree2); + polynomial_add(&mut nom, -E::ScalarField::one(), &lagrange_degree2); univariate_roots_quotient(nom, &[beta, beta2, -beta]) }; let beta_x_commitment = coeff_form_uni_kzg_commit(srs, &f_gamma_quotient); - fs_transcript.append_u8_slice(beta_x_commitment.to_bytes().as_ref()); + fs_transcript.append_serializable_data(&beta_x_commitment); - let tau = fs_transcript.generate_field_element::(); + let tau = fs_transcript.generate_field_element::(); let vanishing_at_tau = { let f_gamma_denom = (tau - beta) * (tau + beta) * (tau - beta2); let lagrange_degree2_at_tau = @@ -182,24 +175,24 @@ where pub fn coeff_form_uni_hyperkzg_verify( vk: &UniKZGVerifierParams, comm: E::G1Affine, - alphas: &[E::Fr], - eval: E::Fr, + alphas: &[E::ScalarField], + eval: E::ScalarField, opening: &HyperUniKZGOpening, fs_transcript: &mut T, ) -> bool where - E: MultiMillerLoop, - E::G1Affine: CurveAffine + ExpSerde, + E: Pairing, + E::G1Affine: ExpSerde, E::G2Affine: ExpSerde, - E::Fr: ExtensionField + ExpSerde, + E::ScalarField: ExtensionField + ExpSerde, T: Transcript, { opening .folded_oracle_commitments .iter() - .for_each(|f| fs_transcript.append_u8_slice(f.to_bytes().as_ref())); + .for_each(|f| fs_transcript.append_serializable_data(f)); - let beta = fs_transcript.generate_field_element::(); + let beta = fs_transcript.generate_field_element::(); let beta2 = beta * beta; let local_evals = @@ -211,7 +204,7 @@ where return false; } - let gamma = fs_transcript.generate_field_element::(); + let gamma = fs_transcript.generate_field_element::(); let gamma_pow_series = powers_series(&gamma, alphas.len()); let v_beta = univariate_evaluate(&local_evals.pos_beta_evals, &gamma_pow_series); let v_neg_beta = univariate_evaluate(&local_evals.neg_beta_evals, &gamma_pow_series); @@ -222,13 +215,13 @@ where let folded_g1_oracle_comms: Vec = opening .folded_oracle_commitments .iter() - .map(|c| c.to_curve()) + .map(|c| E::G1::from(*c)) .collect(); let commitment_agg_g1: E::G1 = - comm.to_curve() + univariate_evaluate(&folded_g1_oracle_comms, &gamma_pow_series[1..]); + comm + univariate_evaluate(&folded_g1_oracle_comms, &gamma_pow_series[1..]); - fs_transcript.append_u8_slice(opening.beta_x_commitment.to_bytes().as_ref()); - let tau = fs_transcript.generate_field_element::(); + fs_transcript.append_serializable_data(&opening.beta_x_commitment); + let tau = fs_transcript.generate_field_element::(); let q_weight = (tau - beta) * (tau - beta2) * (tau + beta); let lagrange_eval = @@ -236,7 +229,7 @@ where coeff_form_uni_kzg_verify( vk, - (commitment_agg_g1 - opening.beta_x_commitment.to_curve() * q_weight).into(), + (commitment_agg_g1 - opening.beta_x_commitment * q_weight).into(), tau, lagrange_eval, opening.quotient_delta_x_commitment, @@ -247,22 +240,22 @@ where pub fn multiple_points_batch_open_impl( proving_key: &CoefFormUniKZGSRS, - polys: &[impl MultilinearExtension], - points: &[impl AsRef<[E::Fr]>], + polys: &[impl MultilinearExtension], + points: &[impl AsRef<[E::ScalarField]>], transcript: &mut impl Transcript, -) -> (Vec, BatchOpening) +) -> (Vec, BatchOpening) where - E: Engine + MultiMillerLoop, - E::Fr: ExtensionField + PrimeField, - E::G1Affine: ExpSerde + Default + CurveAffine, - E::G2Affine: ExpSerde + Default + CurveAffine, - PCS: PolynomialCommitmentScheme>, + E: Pairing, + E::ScalarField: ExtensionField, + E::G1Affine: ExpSerde + Default, + E::G2Affine: ExpSerde + Default, + PCS: PolynomialCommitmentScheme>, { let timer = Timer::new("batch_opening", true); // generate evals for each polynomial at its corresponding point let eval_timer = Timer::new("eval all polys", true); let points = points.iter().map(|p| p.as_ref()).collect::>(); - let evals: Vec = polys + let evals: Vec = polys .par_iter() .zip_eq(points.par_iter()) .map(|(poly, point)| poly.evaluate(point)) @@ -292,17 +285,17 @@ where pub fn multiple_points_batch_verify_impl( verifying_key: &UniKZGVerifierParams, commitments: &[impl AsRef>], - points: &[impl AsRef<[E::Fr]>], - values: &[E::Fr], - batch_opening: &BatchOpening, + points: &[impl AsRef<[E::ScalarField]>], + values: &[E::ScalarField], + batch_opening: &BatchOpening, transcript: &mut impl Transcript, ) -> bool where - E: Engine + MultiMillerLoop, - E::Fr: ExtensionField + PrimeField, - E::G1Affine: ExpSerde + Default + CurveAffine, - E::G2Affine: ExpSerde + Default + CurveAffine, - PCS: PolynomialCommitmentScheme>, + E: Pairing, + E::ScalarField: ExtensionField, + E::G1Affine: ExpSerde + Default, + E::G2Affine: ExpSerde + Default, + PCS: PolynomialCommitmentScheme>, { let a2 = batch_opening.sum_check_proof.export_point_to_expander(); @@ -311,7 +304,7 @@ where .map(|c| vec![c.as_ref().0]) .collect::>(); - let (verified, tilde_g_eval, g_prime_commit) = verifier_merge_points::( + let (verified, tilde_g_eval, g_prime_commit) = verifier_merge_points::( &commitments, points, values, diff --git a/poly_commit/src/kzg/uni_kzg/pcs_trait_impl.rs b/poly_commit/src/kzg/uni_kzg/pcs_trait_impl.rs index 7e06d42ea..978cdcae6 100644 --- a/poly_commit/src/kzg/uni_kzg/pcs_trait_impl.rs +++ b/poly_commit/src/kzg/uni_kzg/pcs_trait_impl.rs @@ -1,12 +1,9 @@ use std::marker::PhantomData; use arith::ExtensionField; +use ark_ec::pairing::Pairing; +use ark_std::rand::RngCore; use gkr_engine::{StructuredReferenceString, Transcript}; -use halo2curves::{ - ff::PrimeField, - pairing::{Engine, MultiMillerLoop}, - CurveAffine, -}; use polynomials::MultiLinearPoly; use serdes::ExpSerde; @@ -19,32 +16,32 @@ use super::batch::{kzg_single_point_batch_open, kzg_single_point_batch_verify}; pub struct HyperUniKZGPCS where - E: Engine, - E::Fr: ExtensionField, + E: Pairing, + E::ScalarField: ExtensionField, { _marker_e: PhantomData, } impl HyperUniKZGPCS where - E: Engine, - E::Fr: ExtensionField, + E: Pairing, + E::ScalarField: ExtensionField, { pub const MINIMUM_SUPPORTED_NUM_VARS: usize = 1; } -impl PolynomialCommitmentScheme for HyperUniKZGPCS +impl PolynomialCommitmentScheme for HyperUniKZGPCS where - E: Engine + MultiMillerLoop, - E::Fr: ExtensionField + PrimeField, - E::G1Affine: ExpSerde + Default + CurveAffine, - E::G2Affine: ExpSerde + Default + CurveAffine, + E: Pairing, + E::ScalarField: ExtensionField, + E::G1Affine: ExpSerde + Default, + E::G2Affine: ExpSerde + Default, { const NAME: &'static str = "HyperUniKZGPCS"; type Params = usize; - type Poly = MultiLinearPoly; - type EvalPoint = Vec; + type Poly = MultiLinearPoly; + type EvalPoint = Vec; type ScratchPad = (); type SRS = CoefFormUniKZGSRS; @@ -53,7 +50,7 @@ where fn init_scratch_pad(_params: &Self::Params) -> Self::ScratchPad {} - fn gen_srs_for_testing(params: &Self::Params, rng: impl rand::RngCore) -> (Self::SRS, usize) { + fn gen_srs_for_testing(params: &Self::Params, rng: impl RngCore) -> (Self::SRS, usize) { let local_num_vars = if *params == 0 { 1 } else { *params }; let length = 1 << local_num_vars; @@ -77,7 +74,7 @@ where x: &Self::EvalPoint, _scratch_pad: &Self::ScratchPad, transcript: &mut impl Transcript, - ) -> (E::Fr, Self::Opening) { + ) -> (E::ScalarField, Self::Opening) { coeff_form_uni_hyperkzg_open(proving_key, &poly.coeffs, x, transcript) } @@ -86,7 +83,7 @@ where verifying_key: &::VKey, commitment: &Self::Commitment, x: &Self::EvalPoint, - v: E::Fr, + v: E::ScalarField, opening: &Self::Opening, transcript: &mut impl Transcript, ) -> bool { @@ -94,12 +91,12 @@ where } } -impl BatchOpeningPCS for HyperUniKZGPCS +impl BatchOpeningPCS for HyperUniKZGPCS where - E: Engine + MultiMillerLoop, - E::Fr: ExtensionField + PrimeField, - E::G1Affine: ExpSerde + Default + CurveAffine, - E::G2Affine: ExpSerde + Default + CurveAffine, + E: Pairing, + E::ScalarField: ExtensionField, + E::G1Affine: ExpSerde + Default, + E::G2Affine: ExpSerde + Default, { fn single_point_batch_open( _params: &Self::Params, @@ -108,7 +105,7 @@ where x: &Self::EvalPoint, _scratch_pad: &Self::ScratchPad, transcript: &mut impl Transcript, - ) -> (Vec, Self::Opening) { + ) -> (Vec, Self::Opening) { kzg_single_point_batch_open(proving_key, polys, x, transcript) } @@ -117,7 +114,7 @@ where verifying_key: &::VKey, commitments: &[Self::Commitment], x: &Self::EvalPoint, - evals: &[E::Fr], + evals: &[E::ScalarField], opening: &Self::Opening, transcript: &mut impl Transcript, ) -> bool { @@ -155,7 +152,7 @@ where points: &[Self::EvalPoint], _scratch_pad: &Self::ScratchPad, transcript: &mut impl Transcript, - ) -> (Vec, BatchOpening) { + ) -> (Vec, BatchOpening) { multiple_points_batch_open_impl(proving_key, polys, points, transcript) } @@ -171,8 +168,8 @@ where verifying_key: &::VKey, commitments: &[Self::Commitment], points: &[Self::EvalPoint], - values: &[E::Fr], - batch_opening: &BatchOpening, + values: &[E::ScalarField], + batch_opening: &BatchOpening, transcript: &mut impl Transcript, ) -> bool { multiple_points_batch_verify_impl( diff --git a/poly_commit/src/kzg/uni_kzg/structs_hyper_kzg.rs b/poly_commit/src/kzg/uni_kzg/structs_hyper_kzg.rs index 79dce7714..e21306938 100644 --- a/poly_commit/src/kzg/uni_kzg/structs_hyper_kzg.rs +++ b/poly_commit/src/kzg/uni_kzg/structs_hyper_kzg.rs @@ -1,9 +1,9 @@ use std::ops::{Index, IndexMut}; -use arith::ExtensionField; +use arith::{ExtensionField, Field}; +use ark_ec::pairing::Pairing; use derivative::Derivative; use gkr_engine::Transcript; -use halo2curves::{ff::Field, pairing::Engine}; use itertools::izip; use serdes::ExpSerde; @@ -11,24 +11,24 @@ use crate::*; #[derive(Clone, Debug, Derivative, ExpSerde)] #[derivative(Default(bound = ""))] -pub struct HyperKZGExportedLocalEvals +pub struct HyperKZGExportedLocalEvals where - E::Fr: ExpSerde, + E::ScalarField: ExpSerde, { - pub beta_x2_eval: E::Fr, - pub pos_beta_x_evals: Vec, - pub neg_beta_x_evals: Vec, + pub beta_x2_eval: E::ScalarField, + pub pos_beta_x_evals: Vec, + pub neg_beta_x_evals: Vec, } -impl HyperKZGExportedLocalEvals +impl HyperKZGExportedLocalEvals where - E::Fr: ExpSerde, + E::ScalarField: ExpSerde, { pub(crate) fn new(evals_num: usize) -> Self { Self { - beta_x2_eval: E::Fr::default(), - pos_beta_x_evals: vec![E::Fr::default(); evals_num], - neg_beta_x_evals: vec![E::Fr::default(); evals_num], + beta_x2_eval: E::ScalarField::default(), + pos_beta_x_evals: vec![E::ScalarField::default(); evals_num], + neg_beta_x_evals: vec![E::ScalarField::default(); evals_num], } } @@ -39,7 +39,7 @@ where pub(crate) fn append_to_transcript(&self, fs_transcript: &mut T) where T: Transcript, - E::Fr: ExtensionField, + E::ScalarField: ExtensionField, { fs_transcript.append_field_element(&self.beta_x2_eval); izip!(&self.pos_beta_x_evals, &self.neg_beta_x_evals).for_each( @@ -53,9 +53,9 @@ where #[derive(Clone, Debug, Derivative, ExpSerde)] #[derivative(Default(bound = ""))] -pub struct HyperUniKZGOpening +pub struct HyperUniKZGOpening where - E::Fr: ExpSerde, + E::ScalarField: ExpSerde, E::G1Affine: Default + ExpSerde, { pub folded_oracle_commitments: Vec, @@ -66,20 +66,20 @@ where #[derive(Clone, Debug, Derivative, ExpSerde)] #[derivative(Default(bound = ""))] -pub(crate) struct HyperKZGLocalEvals +pub(crate) struct HyperKZGLocalEvals where - E::Fr: ExpSerde, + E::ScalarField: ExpSerde, { - pub(crate) beta2_evals: Vec, - pub(crate) pos_beta_evals: Vec, - pub(crate) neg_beta_evals: Vec, + pub(crate) beta2_evals: Vec, + pub(crate) pos_beta_evals: Vec, + pub(crate) neg_beta_evals: Vec, } -impl HyperKZGLocalEvals +impl HyperKZGLocalEvals where - E::Fr: ExtensionField, + E::ScalarField: ExtensionField, { - pub(crate) fn new_from_beta2_evals(beta2_eval: E::Fr) -> Self { + pub(crate) fn new_from_beta2_evals(beta2_eval: E::ScalarField) -> Self { Self { beta2_evals: vec![beta2_eval], pos_beta_evals: Vec::new(), @@ -89,11 +89,11 @@ where pub(crate) fn new_from_exported_evals( exported: &HyperKZGExportedLocalEvals, - alphas: &[E::Fr], - beta: E::Fr, + alphas: &[E::ScalarField], + beta: E::ScalarField, ) -> Self { - let beta_inv = beta.invert().unwrap(); - let two_inv = E::Fr::ONE.double().invert().unwrap(); + let beta_inv = beta.inv().unwrap(); + let two_inv = E::ScalarField::one().double().inv().unwrap(); let mut local_evals = Self::new_from_beta2_evals(exported.beta_x2_eval); @@ -104,7 +104,7 @@ where ) .for_each(|(pos_beta_x_eval, neg_beta_x_eval, alpha)| { let beta2_eval = two_inv - * ((*pos_beta_x_eval + *neg_beta_x_eval) * (E::Fr::ONE - alpha) + * ((*pos_beta_x_eval + *neg_beta_x_eval) * (E::ScalarField::one() - alpha) + (*pos_beta_x_eval - *neg_beta_x_eval) * beta_inv * alpha); local_evals.beta2_evals.push(beta2_eval); @@ -125,7 +125,10 @@ where // pos/neg beta evals. // // The return order is the evals at beta2, beta, and -beta. - pub(crate) fn gamma_aggregate_evals(&self, gamma: E::Fr) -> (E::Fr, E::Fr, E::Fr) { + pub(crate) fn gamma_aggregate_evals( + &self, + gamma: E::ScalarField, + ) -> (E::ScalarField, E::ScalarField, E::ScalarField) { assert_eq!(self.pos_beta_evals.len(), self.neg_beta_evals.len()); assert_eq!(self.pos_beta_evals.len() + 1, self.beta2_evals.len()); @@ -139,9 +142,9 @@ where pub(crate) fn interpolate_degree2_aggregated_evals( &self, - beta: E::Fr, - gamma: E::Fr, - ) -> [E::Fr; 3] { + beta: E::ScalarField, + gamma: E::ScalarField, + ) -> [E::ScalarField; 3] { let beta2 = beta * beta; let (v_beta2, v_beta, v_neg_beta) = self.gamma_aggregate_evals(gamma); coeff_form_degree2_lagrange([beta, -beta, beta2], [v_beta, v_neg_beta, v_beta2]) @@ -149,7 +152,7 @@ where // NOTE(HS) the same assumption applies here, that last beta2 eval is the // multilinear polynomial eval, as it folds to univariate poly of degree 0. - pub(crate) fn multilinear_final_eval(&self) -> E::Fr { + pub(crate) fn multilinear_final_eval(&self) -> E::ScalarField { self.beta2_evals[self.beta2_evals.len() - 1] } @@ -165,11 +168,11 @@ where } } -impl Index for HyperKZGExportedLocalEvals +impl Index for HyperKZGExportedLocalEvals where - E::Fr: ExpSerde, + E::ScalarField: ExpSerde, { - type Output = E::Fr; + type Output = E::ScalarField; fn index(&self, index: usize) -> &Self::Output { assert_eq!(self.pos_beta_x_evals.len(), self.neg_beta_x_evals.len()); @@ -189,9 +192,9 @@ where } } -impl IndexMut for HyperKZGExportedLocalEvals +impl IndexMut for HyperKZGExportedLocalEvals where - E::Fr: ExpSerde, + E::ScalarField: ExpSerde, { fn index_mut(&mut self, index: usize) -> &mut Self::Output { assert_eq!(self.pos_beta_x_evals.len(), self.neg_beta_x_evals.len()); @@ -211,9 +214,9 @@ where } } -impl From> for HyperKZGExportedLocalEvals +impl From> for HyperKZGExportedLocalEvals where - E::Fr: ExpSerde, + E::ScalarField: ExpSerde, { fn from(value: HyperKZGLocalEvals) -> Self { Self { @@ -226,22 +229,22 @@ where #[derive(Clone, Debug, Derivative, ExpSerde)] #[derivative(Default(bound = ""))] -pub struct HyperKZGAggregatedEvals +pub struct HyperKZGAggregatedEvals where - E::Fr: ExpSerde, + E::ScalarField: ExpSerde, { pub beta_y2_evals: HyperKZGExportedLocalEvals, pub pos_beta_y_evals: HyperKZGExportedLocalEvals, pub neg_beta_y_evals: HyperKZGExportedLocalEvals, } -impl HyperKZGAggregatedEvals +impl HyperKZGAggregatedEvals where - E::Fr: ExtensionField, + E::ScalarField: ExtensionField, { pub(crate) fn new_from_exported_evals( exported_evals: &[HyperKZGExportedLocalEvals], - beta_y: E::Fr, + beta_y: E::ScalarField, ) -> Self { let evals_len = exported_evals[0].pos_beta_x_evals.len(); let num_local_evals = exported_evals[0].len(); @@ -261,7 +264,7 @@ where let neg_beta_y_pow_series = powers_series(&(-beta_y), num_parties); (0..num_local_evals).for_each(|i| { - let y_poly: Vec = exported_evals.iter().map(|e| e[i]).collect(); + let y_poly: Vec = exported_evals.iter().map(|e| e[i]).collect(); aggregated.beta_y2_evals[i] = univariate_evaluate(&y_poly, &beta_y2_pow_series); aggregated.pos_beta_y_evals[i] = univariate_evaluate(&y_poly, &pos_beta_y_pow_series); diff --git a/poly_commit/src/kzg/uni_kzg/structs_kzg.rs b/poly_commit/src/kzg/uni_kzg/structs_kzg.rs index ffb856af1..d8351bbbd 100644 --- a/poly_commit/src/kzg/uni_kzg/structs_kzg.rs +++ b/poly_commit/src/kzg/uni_kzg/structs_kzg.rs @@ -1,27 +1,22 @@ +use ark_ec::pairing::Pairing; use derivative::Derivative; use gkr_engine::StructuredReferenceString; -use halo2curves::{pairing::Engine, CurveAffine}; use serdes::{ExpSerde, SerdeResult}; #[derive(Clone, Copy, Debug, PartialEq, Eq, Derivative)] #[derivative(Default(bound = ""))] -pub struct UniKZGCommitment(pub E::G1Affine) -where - E::G1Affine: CurveAffine; +pub struct UniKZGCommitment(pub E::G1Affine); -impl AsRef> for UniKZGCommitment -where - E::G1Affine: CurveAffine, -{ +impl AsRef> for UniKZGCommitment { fn as_ref(&self) -> &UniKZGCommitment { self } } // Derive macros does not work for associated types -impl ExpSerde for UniKZGCommitment +impl ExpSerde for UniKZGCommitment where - E::G1Affine: ExpSerde + CurveAffine, + E::G1Affine: ExpSerde, { fn serialize_into(&self, writer: W) -> SerdeResult<()> { self.0.serialize_into(writer) @@ -36,10 +31,10 @@ where /// The univariate polynomial here is of coefficient form. #[derive(Clone, Debug, PartialEq, Eq, Derivative, ExpSerde)] #[derivative(Default(bound = ""))] -pub struct CoefFormUniKZGSRS +pub struct CoefFormUniKZGSRS where E::G1Affine: ExpSerde, - E::G2Affine: CurveAffine + ExpSerde, + E::G2Affine: ExpSerde, { /// power of \tau times the generators of G1, yielding /// \tau^i over G1 with i ranging in \[ 0, 2^n - 1 \] @@ -48,10 +43,10 @@ where pub tau_g2: E::G2Affine, } -impl StructuredReferenceString for CoefFormUniKZGSRS +impl StructuredReferenceString for CoefFormUniKZGSRS where - ::G1Affine: ExpSerde + CurveAffine, - ::G2Affine: ExpSerde + CurveAffine, + ::G1Affine: ExpSerde, + ::G2Affine: ExpSerde, { type PKey = CoefFormUniKZGSRS; type VKey = UniKZGVerifierParams; @@ -64,7 +59,7 @@ where /// Univariate KZG PCS verifier's params. #[derive(Copy, Clone, Debug, PartialEq, Eq, ExpSerde)] -pub struct UniKZGVerifierParams +pub struct UniKZGVerifierParams where E::G2Affine: ExpSerde, { @@ -72,10 +67,10 @@ where pub tau_g2: E::G2Affine, } -impl From<&CoefFormUniKZGSRS> for UniKZGVerifierParams +impl From<&CoefFormUniKZGSRS> for UniKZGVerifierParams where E::G1Affine: ExpSerde, - E::G2Affine: CurveAffine + ExpSerde, + E::G2Affine: ExpSerde, { fn from(value: &CoefFormUniKZGSRS) -> Self { Self { diff --git a/poly_commit/src/kzg/uni_kzg/univariate.rs b/poly_commit/src/kzg/uni_kzg/univariate.rs index 850436e16..cfdb86570 100644 --- a/poly_commit/src/kzg/uni_kzg/univariate.rs +++ b/poly_commit/src/kzg/uni_kzg/univariate.rs @@ -1,32 +1,31 @@ -use halo2curves::{ - ff::Field, - group::{prime::PrimeCurveAffine, Curve, Group}, - msm, - pairing::{MillerLoopResult, MultiMillerLoop}, - CurveAffine, -}; +use ark_ec::AffineRepr; +use ark_ec::CurveGroup; +use ark_ec::{pairing::Pairing, VariableBaseMSM}; +use ark_std::rand::RngCore; +use ark_std::One; +use ark_std::UniformRand; use rayon::prelude::*; use serdes::ExpSerde; use crate::*; #[inline(always)] -pub(crate) fn generate_coef_form_uni_kzg_srs_for_testing( +pub(crate) fn generate_coef_form_uni_kzg_srs_for_testing( length: usize, - mut rng: impl rand::RngCore, + mut rng: impl RngCore, ) -> CoefFormUniKZGSRS where - E::G1Affine: CurveAffine + ExpSerde, - E::G2Affine: CurveAffine + ExpSerde, + E::G1Affine: ExpSerde, + E::G2Affine: ExpSerde, { assert!(length.is_power_of_two()); - let tau = E::Fr::random(&mut rng); + let tau = E::ScalarField::rand(&mut rng); let g1 = E::G1Affine::generator(); let tau_geometric_progression = powers_series(&tau, length); - let g1_prog = g1.to_curve(); + let g1_prog: E::G1 = g1.into(); let coeff_bases = { let mut proj_bases = vec![g1_prog; length]; proj_bases @@ -34,8 +33,7 @@ where .zip(tau_geometric_progression.par_iter()) .for_each(|(b, tau_i)| *b *= tau_i); - let mut g_bases = vec![E::G1Affine::default(); length]; - E::G1::batch_normalize(&proj_bases, &mut g_bases); + let g_bases = E::G1::normalize_batch(&proj_bases); drop(proj_bases); g_bases @@ -48,69 +46,69 @@ where } #[inline(always)] -pub(crate) fn coeff_form_uni_kzg_commit( +pub(crate) fn coeff_form_uni_kzg_commit( srs: &CoefFormUniKZGSRS, - coeffs: &[E::Fr], + coeffs: &[E::ScalarField], ) -> E::G1Affine where - E::G1Affine: CurveAffine + ExpSerde, - E::G2Affine: CurveAffine + ExpSerde, + E::G1Affine: ExpSerde, + E::G2Affine: ExpSerde, { assert!(srs.powers_of_tau.len() >= coeffs.len()); - let com = msm::best_multiexp(coeffs, &srs.powers_of_tau[..coeffs.len()]); + let com: E::G1 = VariableBaseMSM::msm(&srs.powers_of_tau[..coeffs.len()], coeffs).unwrap(); com.into() } #[inline(always)] -pub fn coeff_form_uni_kzg_open_eval( +pub fn coeff_form_uni_kzg_open_eval( srs: &CoefFormUniKZGSRS, - coeffs: &[E::Fr], - alpha: E::Fr, -) -> (E::Fr, E::G1Affine) + coeffs: &[E::ScalarField], + alpha: E::ScalarField, +) -> (E::ScalarField, E::G1Affine) where - E::G1Affine: CurveAffine + ExpSerde, - E::G2Affine: CurveAffine + ExpSerde, + E::G1Affine: ExpSerde, + E::G2Affine: ExpSerde, { assert!(srs.powers_of_tau.len() >= coeffs.len()); let (div, eval) = univariate_degree_one_quotient(coeffs, alpha); - let opening = msm::best_multiexp(&div, &srs.powers_of_tau[..div.len()]); + let opening: E::G1 = VariableBaseMSM::msm(&srs.powers_of_tau[..div.len()], &div).unwrap(); (eval, opening.into()) } #[inline(always)] -pub(crate) fn coeff_form_uni_kzg_verify( +pub(crate) fn coeff_form_uni_kzg_verify( vk: &UniKZGVerifierParams, comm: E::G1Affine, - alpha: E::Fr, - eval: E::Fr, + alpha: E::ScalarField, + eval: E::ScalarField, opening: E::G1Affine, ) -> bool where - E::G1Affine: CurveAffine, E::G2Affine: ExpSerde, { let g1_eval: E::G1Affine = (E::G1Affine::generator() * eval).into(); let g2_alpha: E::G2 = E::G2Affine::generator() * alpha; - let gt_result = E::multi_miller_loop(&[ - ( - &opening, - &(vk.tau_g2.to_curve() - g2_alpha).to_affine().into(), - ), - (&(g1_eval - comm).into(), &E::G2Affine::generator().into()), - ]); + let gt_result = E::multi_miller_loop( + &[opening, (g1_eval - comm).into()], + &[ + (vk.tau_g2 - g2_alpha).into(), + E::G2Affine::generator().into(), + ], + ); - gt_result.final_exponentiation().is_identity().into() + E::final_exponentiation(gt_result).unwrap().0 == E::TargetField::one() } #[cfg(test)] mod tests { + use arith::Fr; + use ark_bn254::Bn254; use ark_std::test_rng; - use halo2curves::bn256::{Bn256, Fr}; use crate::*; @@ -131,8 +129,8 @@ mod tests { let eval = Fr::from(604800u64); let mut rng = test_rng(); - let srs = generate_coef_form_uni_kzg_srs_for_testing::(8, &mut rng); - let vk: UniKZGVerifierParams = From::from(&srs); + let srs = generate_coef_form_uni_kzg_srs_for_testing::(8, &mut rng); + let vk: UniKZGVerifierParams = From::from(&srs); let com = coeff_form_uni_kzg_commit(&srs, &poly); let (actual_eval, opening) = coeff_form_uni_kzg_open_eval(&srs, &poly, alpha); @@ -148,8 +146,8 @@ mod tests { let eval = Fr::from(100u64); let mut rng = test_rng(); - let srs = generate_coef_form_uni_kzg_srs_for_testing::(8, &mut rng); - let vk: UniKZGVerifierParams = From::from(&srs); + let srs = generate_coef_form_uni_kzg_srs_for_testing::(8, &mut rng); + let vk: UniKZGVerifierParams = From::from(&srs); let com = coeff_form_uni_kzg_commit(&srs, &poly); let (actual_eval, opening) = coeff_form_uni_kzg_open_eval(&srs, &poly, alpha); diff --git a/poly_commit/src/kzg/utils.rs b/poly_commit/src/kzg/utils.rs index a4dfb95d6..c04a17595 100644 --- a/poly_commit/src/kzg/utils.rs +++ b/poly_commit/src/kzg/utils.rs @@ -1,11 +1,12 @@ use std::{iter::Sum, ops::Mul}; -use halo2curves::ff::Field; +use arith::Field; +use ark_ff::PrimeField; use itertools::izip; #[inline(always)] -pub(crate) fn powers_series(x: &F, n: usize) -> Vec { - let mut powers = vec![F::ONE]; +pub(crate) fn powers_series(x: &F, n: usize) -> Vec { + let mut powers = vec![F::one()]; let mut cur = *x; for _ in 0..n - 1 { powers.push(cur); @@ -17,7 +18,7 @@ pub(crate) fn powers_series(x: &F, n: usize) -> Vec { /// Given a univariate polynomial of coefficient form f(X) = c0 + c1 X + ... + cn X^n /// and perform the division f(X) / (X - \alpha). #[inline(always)] -pub(crate) fn univariate_degree_one_quotient(coeffs: &[F], alpha: F) -> (Vec, F) { +pub(crate) fn univariate_degree_one_quotient(coeffs: &[F], alpha: F) -> (Vec, F) { let mut div_coeffs = coeffs.to_vec(); for i in (1..coeffs.len()).rev() { @@ -30,7 +31,7 @@ pub(crate) fn univariate_degree_one_quotient(coeffs: &[F], alpha: F) - let final_remainder = div_coeffs[0]; let mut final_div_coeffs = div_coeffs[1..].to_owned(); - final_div_coeffs.resize(coeffs.len(), F::ZERO); + final_div_coeffs.resize(coeffs.len(), F::zero()); (final_div_coeffs, final_remainder) } @@ -46,7 +47,7 @@ pub(crate) fn univariate_roots_quotient(mut coeffs: Vec, roots: &[F coeffs[i - 1] += remainder; } - assert_eq!(coeffs[ith_root], F::ZERO); + assert_eq!(coeffs[ith_root], F::zero()); }); coeffs[roots.len()..].to_owned() @@ -86,7 +87,7 @@ pub(crate) fn univariate_degree_b_quotient( #[inline(always)] pub(crate) fn polynomial_add(coeffs: &mut Vec, weight: F, another_coeffs: &[F]) { if coeffs.len() < another_coeffs.len() { - coeffs.resize(another_coeffs.len(), F::ZERO); + coeffs.resize(another_coeffs.len(), F::zero()); } izip!(coeffs, another_coeffs).for_each(|(c, a)| *c += weight * *a); @@ -97,16 +98,16 @@ pub(crate) fn coeff_form_degree2_lagrange(roots: [F; 3], evals: [F; 3] let [r0, r1, r2] = roots; let [e0, e1, e2] = evals; - let r0_nom = [r1 * r2, -r1 - r2, F::ONE]; - let r0_denom_inv = ((r0 - r1) * (r0 - r2)).invert().unwrap(); + let r0_nom = [r1 * r2, -r1 - r2, F::one()]; + let r0_denom_inv = ((r0 - r1) * (r0 - r2)).inv().unwrap(); let r0_weight = r0_denom_inv * e0; - let r1_nom = [r0 * r2, -r0 - r2, F::ONE]; - let r1_denom_inv = ((r1 - r0) * (r1 - r2)).invert().unwrap(); + let r1_nom = [r0 * r2, -r0 - r2, F::one()]; + let r1_denom_inv = ((r1 - r0) * (r1 - r2)).inv().unwrap(); let r1_weight = r1_denom_inv * e1; - let r2_nom = [r0 * r1, -r0 - r1, F::ONE]; - let r2_denom_inv = ((r2 - r0) * (r2 - r1)).invert().unwrap(); + let r2_nom = [r0 * r1, -r0 - r1, F::one()]; + let r2_denom_inv = ((r2 - r0) * (r2 - r1)).inv().unwrap(); let r2_weight = r2_denom_inv * e2; let combine = |a, b, c| a * r0_weight + b * r1_weight + c * r2_weight; @@ -120,7 +121,7 @@ pub(crate) fn coeff_form_degree2_lagrange(roots: [F; 3], evals: [F; 3] #[cfg(test)] mod test { - use halo2curves::{bn256::Fr, ff::Field}; + use arith::{Field, Fr}; use crate::*; @@ -145,7 +146,7 @@ mod test { Fr::from(0u64) ] ); - assert_eq!(remainder, Fr::ZERO) + assert_eq!(remainder, ::zero()) } { // x^3 - 1 = (x-1)(x^2 + x + 1) @@ -166,7 +167,7 @@ mod test { Fr::from(0u64) ] ); - assert_eq!(remainder, Fr::ZERO) + assert_eq!(remainder, ::zero()) } { // x^3 + 6x^2 + 11x + 6 = (x + 1)(x + 2)(x + 3) diff --git a/poly_commit/src/lib.rs b/poly_commit/src/lib.rs index b0bc946de..db1af6f2c 100644 --- a/poly_commit/src/lib.rs +++ b/poly_commit/src/lib.rs @@ -8,14 +8,14 @@ pub const PCS_SOUNDNESS_BITS: usize = 128; mod utils; pub use utils::expander_pcs_init_testing_only; -pub mod raw; -pub use raw::RawExpanderGKR; +// pub mod raw; +// pub use raw::RawExpanderGKR; -pub mod orion; -pub use orion::*; +// pub mod orion; +// pub use orion::*; -pub mod hyrax; -pub use hyrax::*; +// pub mod hyrax; +// pub use hyrax::*; pub mod kzg; pub use kzg::*; diff --git a/poly_commit/src/orion/linear_code.rs b/poly_commit/src/orion/linear_code.rs index 15bb31236..58f841cce 100644 --- a/poly_commit/src/orion/linear_code.rs +++ b/poly_commit/src/orion/linear_code.rs @@ -272,7 +272,7 @@ impl OrionCode { #[inline(always)] pub fn encode(&self, msg: &[F]) -> OrionResult> { - let mut codeword = vec![F::ZERO; self.code_len()]; + let mut codeword = vec![F::zero(); self.code_len()]; self.encode_in_place(msg, &mut codeword)?; Ok(codeword) } @@ -284,7 +284,7 @@ impl OrionCode { } buffer[..self.msg_len()].copy_from_slice(msg); - let mut scratch = vec![F::ZERO; self.code_len()]; + let mut scratch = vec![F::zero(); self.code_len()]; chain!(&self.g0s, &self.g1s).try_for_each(|g| g.expander_mul(buffer, &mut scratch)) } diff --git a/poly_commit/src/orion/linear_code_tests.rs b/poly_commit/src/orion/linear_code_tests.rs index 7c922297b..ff023f853 100644 --- a/poly_commit/src/orion/linear_code_tests.rs +++ b/poly_commit/src/orion/linear_code_tests.rs @@ -35,8 +35,8 @@ where let weights: Vec<_> = (0..row_num).map(|_| F::random_unsafe(&mut rng)).collect(); // NOTE: generate message and codeword in the slice buffer - let mut message_mat = vec![F::ZERO; row_num * encoder.msg_len()]; - let mut codeword_mat = vec![F::ZERO; row_num * encoder.code_len()]; + let mut message_mat = vec![F::zero(); row_num * encoder.msg_len()]; + let mut codeword_mat = vec![F::zero(); row_num * encoder.code_len()]; message_mat .chunks_mut(encoder.msg_len()) @@ -47,7 +47,7 @@ where }); // NOTE: transpose message and codeword matrix - let mut message_mat_transpose = vec![F::ZERO; row_num * encoder.msg_len()]; + let mut message_mat_transpose = vec![F::zero(); row_num * encoder.msg_len()]; transpose( &message_mat, &mut message_mat_transpose, @@ -55,7 +55,7 @@ where row_num, ); - let mut codeword_mat_transpose = vec![F::ZERO; row_num * encoder.code_len()]; + let mut codeword_mat_transpose = vec![F::zero(); row_num * encoder.code_len()]; transpose( &codeword_mat, &mut codeword_mat_transpose, diff --git a/poly_commit/src/orion/mpi_utils.rs b/poly_commit/src/orion/mpi_utils.rs index 3ed38f840..e0bdce291 100644 --- a/poly_commit/src/orion/mpi_utils.rs +++ b/poly_commit/src/orion/mpi_utils.rs @@ -116,7 +116,7 @@ where let packed_rows = pk.local_num_fs_per_query() / PackF::PACK_SIZE; // NOTE: packed codeword buffer and encode over packed field - let mut codewords = vec![PackF::ZERO; packed_rows * pk.codeword_len()]; + let mut codewords = vec![PackF::zero(); packed_rows * pk.codeword_len()]; izip!( packed_evals.chunks(pk.message_len()), codewords.chunks_mut(pk.codeword_len()) @@ -125,7 +125,7 @@ where // NOTE: transpose codeword s.t., the matrix has codewords being columns if packed_rows > 1 { - let mut scratch = vec![PackF::ZERO; std::cmp::max(packed_rows, pk.codeword_len())]; + let mut scratch = vec![PackF::zero(); std::cmp::max(packed_rows, pk.codeword_len())]; transpose_inplace(&mut codewords, &mut scratch, pk.codeword_len(), packed_rows); drop(scratch) } @@ -136,7 +136,7 @@ where // to commit by merkle tree if !codewords.len().is_power_of_two() { let aligned_po2_len = codewords.len().next_power_of_two(); - codewords.resize(aligned_po2_len, PackF::ZERO); + codewords.resize(aligned_po2_len, PackF::zero()); } // NOTE: ALL-TO-ALL transpose go get other world's slice of codeword @@ -154,7 +154,7 @@ where let codeword_chunk_per_world_len = codeword_po2_chunk_len * packed_rows; // NOTE: now transpose back to row order of each world's codeword slice - let mut scratch = vec![PackF::ZERO; std::cmp::max(codeword_po2_chunk_len, packed_rows)]; + let mut scratch = vec![PackF::zero(); std::cmp::max(codeword_po2_chunk_len, packed_rows)]; codewords .chunks_mut(codeword_chunk_per_world_len) .for_each(|c| transpose_inplace(c, &mut scratch, packed_rows, codeword_po2_chunk_len)); @@ -162,7 +162,7 @@ where } // NOTE: transpose back into column order of the codeword slice - let mut scratch = vec![PackF::ZERO; std::cmp::max(codeword_po2_chunk_len, global_packed_rows)]; + let mut scratch = vec![PackF::zero(); std::cmp::max(codeword_po2_chunk_len, global_packed_rows)]; transpose_inplace( &mut codewords, &mut scratch, diff --git a/poly_commit/src/orion/simd_field_impl.rs b/poly_commit/src/orion/simd_field_impl.rs index a86814b76..f5c9d36c0 100644 --- a/poly_commit/src/orion/simd_field_impl.rs +++ b/poly_commit/src/orion/simd_field_impl.rs @@ -66,10 +66,10 @@ where }; // NOTE: pre-declare the spaces for returning evaluation and proximity queries - let mut eval_row = vec![EvalF::ZERO; msg_size]; + let mut eval_row = vec![EvalF::zero(); msg_size]; let proximity_test_num = pk.proximity_repetitions::(PCS_SOUNDNESS_BITS); - let mut proximity_rows = vec![vec![EvalF::ZERO; msg_size]; proximity_test_num]; + let mut proximity_rows = vec![vec![EvalF::zero(); msg_size]; proximity_test_num]; let random_col_coeffs: Vec<_> = (0..proximity_test_num) .map(|_| { @@ -98,7 +98,7 @@ where } // NOTE: working on evaluation response, evaluate the rest of the response - let mut scratch = vec![EvalF::ZERO; msg_size]; + let mut scratch = vec![EvalF::zero(); msg_size]; let eval = RefMultiLinearPoly::from_ref(&eval_row).evaluate_with_buffer( &point[num_vars_in_com_simd..num_vars_in_com_simd + num_vars_in_msg], &mut scratch, diff --git a/poly_commit/src/orion/simd_field_mpi_impl.rs b/poly_commit/src/orion/simd_field_mpi_impl.rs index 2fe68445e..d46bbb499 100644 --- a/poly_commit/src/orion/simd_field_mpi_impl.rs +++ b/poly_commit/src/orion/simd_field_mpi_impl.rs @@ -71,10 +71,10 @@ where }; // NOTE: pre-declare the spaces for returning evaluation and proximity queries - let mut eval_row = vec![EvalF::ZERO; msg_size]; + let mut eval_row = vec![EvalF::zero(); msg_size]; let proximity_test_num = pk.proximity_repetitions::(PCS_SOUNDNESS_BITS); - let mut proximity_rows = vec![vec![EvalF::ZERO; msg_size]; proximity_test_num]; + let mut proximity_rows = vec![vec![EvalF::zero(); msg_size]; proximity_test_num]; // NOTE: draw randomness from transcript with log random complexity let num_of_local_random_vars = point.len() - num_vars_in_msg; diff --git a/poly_commit/src/orion/utils.rs b/poly_commit/src/orion/utils.rs index 9ada0399e..c532e1244 100644 --- a/poly_commit/src/orion/utils.rs +++ b/poly_commit/src/orion/utils.rs @@ -218,7 +218,7 @@ where let packed_rows = pk.local_num_fs_per_query() / PackF::PACK_SIZE; // NOTE: packed codeword buffer and encode over packed field - let mut codewords = vec![PackF::ZERO; packed_rows * pk.codeword_len()]; + let mut codewords = vec![PackF::zero(); packed_rows * pk.codeword_len()]; izip!( packed_evals.chunks(pk.message_len()), codewords.chunks_mut(pk.codeword_len()) @@ -226,7 +226,7 @@ where .try_for_each(|(evals, codeword)| pk.code_instance.encode_in_place(evals, codeword))?; // NOTE: transpose codeword s.t., the matrix has codewords being columns - let mut scratch = vec![PackF::ZERO; std::cmp::max(packed_rows, pk.codeword_len())]; + let mut scratch = vec![PackF::zero(); std::cmp::max(packed_rows, pk.codeword_len())]; transpose_inplace(&mut codewords, &mut scratch, pk.codeword_len(), packed_rows); drop(scratch); @@ -236,7 +236,7 @@ where // to commit by merkle tree if !codewords.len().is_power_of_two() { let aligned_po2_len = codewords.len().next_power_of_two(); - codewords.resize(aligned_po2_len, PackF::ZERO); + codewords.resize(aligned_po2_len, PackF::zero()); } scratch_pad.interleaved_alphabet_commitment = tree::Tree::compact_new_with_packed_field_elems(codewords); @@ -310,7 +310,7 @@ impl SubsetSumLUTs { Self { entry_bits, - tables: vec![vec![F::ZERO; 1 << entry_bits]; table_num], + tables: vec![vec![F::zero(); 1 << entry_bits]; table_num], } } @@ -318,7 +318,7 @@ impl SubsetSumLUTs { pub fn build(&mut self, weights: &[F]) { assert_eq!(weights.len(), self.entry_bits * self.tables.len()); - self.tables.iter_mut().for_each(|lut| lut.fill(F::ZERO)); + self.tables.iter_mut().for_each(|lut| lut.fill(F::zero())); // NOTE: we are assuming that the table is for {0, 1}-linear combination izip!(&mut self.tables, weights.chunks(self.entry_bits)).for_each( @@ -444,7 +444,7 @@ where { assert_eq!(simd_ext_limbs.len(), simd_base_elems.len() * ExtF::DEGREE); - let mut ext_limbs = vec![F::ZERO; ExtF::DEGREE]; + let mut ext_limbs = vec![F::zero(); ExtF::DEGREE]; izip!(&mut ext_limbs, simd_ext_limbs.chunks(simd_base_elems.len())).for_each( |(e, simd_ext_limb)| { @@ -478,7 +478,7 @@ pub(crate) fn simd_open_linear_combine( let combination_size = eq_col_coeffs.len(); let packed_row_size = combination_size / com_pack_size; - let mut buffer = vec![F::ZERO; com_pack_size * EvalF::DEGREE]; + let mut buffer = vec![F::zero(); com_pack_size * EvalF::DEGREE]; // NOTE: working on evaluation response of tensor code IOP based PCS izip!( @@ -530,7 +530,7 @@ where // NOTE: check SIMD inner product numbers for column sums assert_eq!(fixed_rl.len() % SimdF::PACK_SIZE, 0); - let mut scratch = vec![F::ZERO; fixed_rl.len() * ExtF::DEGREE]; + let mut scratch = vec![F::zero(); fixed_rl.len() * ExtF::DEGREE]; let rl_limbs: Vec<_> = fixed_rl.iter().flat_map(|e| e.to_limbs()).collect(); transpose(&rl_limbs, &mut scratch, ExtF::DEGREE, fixed_rl.len()); let simd_limbs: Vec<_> = scratch.chunks(SimdF::PACK_SIZE).map(SimdF::pack).collect(); diff --git a/poly_commit/src/orion/verify.rs b/poly_commit/src/orion/verify.rs index 810bdb50a..397c29cf4 100644 --- a/poly_commit/src/orion/verify.rs +++ b/poly_commit/src/orion/verify.rs @@ -39,7 +39,7 @@ where let num_vars_in_msg = msg_size.ilog2() as usize; // NOTE: working on evaluation response, evaluate the rest of the response - let mut scratch = vec![EvalF::ZERO; msg_size]; + let mut scratch = vec![EvalF::zero(); msg_size]; let final_eval = RefMultiLinearPoly::from_ref(&proof.eval_row).evaluate_with_buffer( &point[num_vars_in_com_simd..num_vars_in_com_simd + num_vars_in_msg], &mut scratch, diff --git a/poly_commit/src/raw.rs b/poly_commit/src/raw.rs index ece451f42..cd56c702e 100644 --- a/poly_commit/src/raw.rs +++ b/poly_commit/src/raw.rs @@ -1,12 +1,12 @@ /// Raw commitment for multi-linear polynomials use arith::{ExtensionField, Field}; +use ark_std::rand::RngCore; use ethnum::U256; use gkr_engine::{ ExpanderPCS, ExpanderSingleVarChallenge, FieldEngine, MPIEngine, PolynomialCommitmentType, StructuredReferenceString, Transcript, }; use polynomials::{MultiLinearPoly, MultilinearExtension}; -use rand::RngCore; use serdes::{ExpSerde, SerdeResult}; use crate::PolynomialCommitmentScheme; @@ -110,7 +110,7 @@ impl PolynomialCommitmentScheme for RawMultiLinearPCS { MultiLinearPoly::::evaluate_with_buffer( &commitment.evals, x, - &mut vec![F::ZERO; commitment.evals.len()], + &mut vec![F::zero(); commitment.evals.len()], ) == v } } diff --git a/poly_commit/src/traits.rs b/poly_commit/src/traits.rs index 50e529a43..868d885e8 100644 --- a/poly_commit/src/traits.rs +++ b/poly_commit/src/traits.rs @@ -1,6 +1,6 @@ use arith::{ExtensionField, Field}; +use ark_std::rand::RngCore; use gkr_engine::{StructuredReferenceString, Transcript}; -use rand::RngCore; use serdes::ExpSerde; use std::fmt::Debug; use sumcheck::IOPProof; diff --git a/poly_commit/src/utils.rs b/poly_commit/src/utils.rs index 9d9da5e3f..1a14cd247 100644 --- a/poly_commit/src/utils.rs +++ b/poly_commit/src/utils.rs @@ -1,14 +1,11 @@ use arith::Field; use ark_std::test_rng; -use gkr_engine::{ - ExpanderPCS, ExpanderSingleVarChallenge, FieldEngine, MPIEngine, StructuredReferenceString, -}; +use gkr_engine::{ExpanderPCS, ExpanderSingleVarChallenge, FieldEngine, StructuredReferenceString}; use polynomials::{MultiLinearPoly, MultilinearExtension, MutableMultilinearExtension}; #[allow(clippy::type_complexity)] pub fn expander_pcs_init_testing_only>( n_input_vars: usize, - mpi_config: &impl MPIEngine, ) -> ( PCS::Params, ::PKey, @@ -17,17 +14,12 @@ pub fn expander_pcs_init_testing_only>::gen_params(n_input_vars, mpi_config.world_size()); - let pcs_setup = >::gen_or_load_srs_for_testing( - &pcs_params, - mpi_config, - &mut rng, - None, - ); + let pcs_params = >::gen_params(n_input_vars, 16); + let pcs_setup = + >::gen_or_load_srs_for_testing(&pcs_params, &mut rng, None); let (pcs_proving_key, pcs_verification_key) = pcs_setup.into_keys(); - let pcs_scratch = >::init_scratch_pad(&pcs_params, mpi_config); + let pcs_scratch = >::init_scratch_pad(&pcs_params); ( pcs_params, diff --git a/poly_commit/tests/common.rs b/poly_commit/tests/common.rs index dc022d179..662c9e28d 100644 --- a/poly_commit/tests/common.rs +++ b/poly_commit/tests/common.rs @@ -1,12 +1,14 @@ use arith::{ExtensionField, Field}; -use ark_std::test_rng; +use ark_std::{ + rand::{thread_rng, RngCore}, + test_rng, +}; use gkr_engine::{ ExpanderPCS, ExpanderSingleVarChallenge, FieldEngine, MPIConfig, MPIEngine, StructuredReferenceString, Transcript, }; use poly_commit::{BatchOpeningPCS, PolynomialCommitmentScheme}; use polynomials::{MultiLinearPoly, MultilinearExtension}; -use rand::{thread_rng, RngCore}; #[allow(dead_code)] pub fn test_pcs>( @@ -225,7 +227,7 @@ pub fn test_pcs_for_expander_gkr 0 { - rng.next_u32() as usize % (num_vars + 1) + rng.next_u64() as usize % (num_vars + 1) } else { num_vars }; diff --git a/poly_commit/tests/test_bi_kzg.rs b/poly_commit/tests/test_bi_kzg.rs index b0d145045..ebf640b1a 100644 --- a/poly_commit/tests/test_bi_kzg.rs +++ b/poly_commit/tests/test_bi_kzg.rs @@ -1,11 +1,11 @@ mod common; use arith::{Field, Fr}; +use ark_bn254::Bn254; use ark_std::test_rng; use gkr_engine::ExpanderPCS; use gkr_engine::{BN254Config, ExpanderSingleVarChallenge, MPIConfig, MPIEngine, Transcript}; use gkr_hashers::Keccak256hasher; -use halo2curves::bn256::Bn256; use poly_commit::HyperBiKZGPCS; use polynomials::MultiLinearPoly; use transcript::BytesHashTranscript; @@ -21,7 +21,7 @@ fn test_hyper_bi_kzg_pcs_generics(num_vars_start: usize, num_vars_end: usize) { .collect(); let poly = MultiLinearPoly::::random(num_vars, &mut rng); - common::test_pcs::, HyperBiKZGPCS>( + common::test_pcs::, HyperBiKZGPCS>( &num_vars, &poly, &xs, ); }) @@ -61,14 +61,14 @@ fn test_hyper_bi_kzg_for_expander_gkr_generics(mpi_config_ref: &MPIConfig, total dbg!(local_poly.get_num_vars(), local_poly.coeffs[0]); - let params = as ExpanderPCS>::gen_params( + let params = as ExpanderPCS>::gen_params( num_vars_in_each_poly, mpi_config_ref.world_size(), ); common::test_pcs_for_expander_gkr::< BN254Config, BytesHashTranscript, - HyperBiKZGPCS, + HyperBiKZGPCS, >( ¶ms, mpi_config_ref, diff --git a/poly_commit/tests/test_hyrax.rs b/poly_commit/tests/test_hyrax.rs index 9ed3400f4..b90f2f8e3 100644 --- a/poly_commit/tests/test_hyrax.rs +++ b/poly_commit/tests/test_hyrax.rs @@ -1,93 +1,93 @@ -mod common; +// mod common; -use arith::{Field, Fr}; -use ark_std::test_rng; -use gkr_engine::{BN254Config, ExpanderSingleVarChallenge, MPIConfig, MPIEngine, Transcript}; -use gkr_hashers::Keccak256hasher; -use halo2curves::bn256::G1Affine; -use poly_commit::HyraxPCS; -use polynomials::MultiLinearPoly; -use transcript::BytesHashTranscript; +// use arith::{Field, Fr}; +// use ark_std::test_rng; +// use gkr_engine::{BN254Config, ExpanderSingleVarChallenge, MPIConfig, MPIEngine, Transcript}; +// use gkr_hashers::Keccak256hasher; +// use halo2curves::bn256::G1Affine; +// use poly_commit::HyraxPCS; +// use polynomials::MultiLinearPoly; +// use transcript::BytesHashTranscript; -const TEST_REPETITION: usize = 3; +// const TEST_REPETITION: usize = 3; -fn test_hyrax_pcs_generics(num_vars_start: usize, num_vars_end: usize) { - let mut rng = test_rng(); +// fn test_hyrax_pcs_generics(num_vars_start: usize, num_vars_end: usize) { +// let mut rng = test_rng(); - (num_vars_start..=num_vars_end).for_each(|num_vars| { - let xs: Vec<_> = (0..TEST_REPETITION) - .map(|_| -> Vec { (0..num_vars).map(|_| Fr::random_unsafe(&mut rng)).collect() }) - .collect(); - let poly = MultiLinearPoly::::random(num_vars, &mut rng); +// (num_vars_start..=num_vars_end).for_each(|num_vars| { +// let xs: Vec<_> = (0..TEST_REPETITION) +// .map(|_| -> Vec { (0..num_vars).map(|_| Fr::random_unsafe(&mut rng)).collect() }) +// .collect(); +// let poly = MultiLinearPoly::::random(num_vars, &mut rng); - common::test_pcs::, HyraxPCS>( - &num_vars, &poly, &xs, - ); - }) -} +// common::test_pcs::, HyraxPCS>( +// &num_vars, &poly, &xs, +// ); +// }) +// } -#[test] -fn test_hyrax_pcs_e2e() { - test_hyrax_pcs_generics(1, 17) -} +// #[test] +// fn test_hyrax_pcs_e2e() { +// test_hyrax_pcs_generics(1, 17) +// } -fn test_hyrax_for_expander_gkr_generics(mpi_config_ref: &MPIConfig, total_num_vars: usize) { - let mut rng = test_rng(); +// fn test_hyrax_for_expander_gkr_generics(mpi_config_ref: &MPIConfig, total_num_vars: usize) { +// let mut rng = test_rng(); - // NOTE BN254 GKR SIMD pack size = 1, num vars in SIMD is 0 - let num_vars_in_mpi = mpi_config_ref.world_size().ilog2() as usize; - let num_vars_in_each_poly = total_num_vars - num_vars_in_mpi; +// // NOTE BN254 GKR SIMD pack size = 1, num vars in SIMD is 0 +// let num_vars_in_mpi = mpi_config_ref.world_size().ilog2() as usize; +// let num_vars_in_each_poly = total_num_vars - num_vars_in_mpi; - let global_poly = MultiLinearPoly::::random(total_num_vars, &mut rng); - let challenge_point = ExpanderSingleVarChallenge:: { - r_mpi: (0..num_vars_in_mpi) - .map(|_| Fr::random_unsafe(&mut rng)) - .collect(), - r_simd: Vec::new(), - rz: (0..num_vars_in_each_poly) - .map(|_| Fr::random_unsafe(&mut rng)) - .collect(), - }; +// let global_poly = MultiLinearPoly::::random(total_num_vars, &mut rng); +// let challenge_point = ExpanderSingleVarChallenge:: { +// r_mpi: (0..num_vars_in_mpi) +// .map(|_| Fr::random_unsafe(&mut rng)) +// .collect(), +// r_simd: Vec::new(), +// rz: (0..num_vars_in_each_poly) +// .map(|_| Fr::random_unsafe(&mut rng)) +// .collect(), +// }; - let mut transcript = BytesHashTranscript::::new(); +// let mut transcript = BytesHashTranscript::::new(); - // NOTE separate polynomial into different pieces by mpi rank - let poly_vars_stride = (1 << global_poly.get_num_vars()) / mpi_config_ref.world_size(); - let poly_coeff_starts = mpi_config_ref.world_rank() * poly_vars_stride; - let poly_coeff_ends = poly_coeff_starts + poly_vars_stride; - let local_poly = - MultiLinearPoly::new(global_poly.coeffs[poly_coeff_starts..poly_coeff_ends].to_vec()); +// // NOTE separate polynomial into different pieces by mpi rank +// let poly_vars_stride = (1 << global_poly.get_num_vars()) / mpi_config_ref.world_size(); +// let poly_coeff_starts = mpi_config_ref.world_rank() * poly_vars_stride; +// let poly_coeff_ends = poly_coeff_starts + poly_vars_stride; +// let local_poly = +// MultiLinearPoly::new(global_poly.coeffs[poly_coeff_starts..poly_coeff_ends].to_vec()); - dbg!(local_poly.get_num_vars(), local_poly.coeffs[0]); +// dbg!(local_poly.get_num_vars(), local_poly.coeffs[0]); - common::test_pcs_for_expander_gkr::< - BN254Config, - BytesHashTranscript, - HyraxPCS, - >( - &num_vars_in_each_poly, - mpi_config_ref, - &mut transcript, - &local_poly, - &[challenge_point], - Some("../data/hyrax_srs.bin"), - ); -} +// common::test_pcs_for_expander_gkr::< +// BN254Config, +// BytesHashTranscript, +// HyraxPCS, +// >( +// &num_vars_in_each_poly, +// mpi_config_ref, +// &mut transcript, +// &local_poly, +// &[challenge_point], +// Some("../data/hyrax_srs.bin"), +// ); +// } -#[test] -fn test_hyrax_for_expander_gkr() { - let universe = MPIConfig::init().unwrap(); - let world = universe.world(); - let mpi_config = MPIConfig::prover_new(Some(&universe), Some(&world)); - test_hyrax_for_expander_gkr_generics(&mpi_config, 19); -} +// #[test] +// fn test_hyrax_for_expander_gkr() { +// let universe = MPIConfig::init().unwrap(); +// let world = universe.world(); +// let mpi_config = MPIConfig::prover_new(Some(&universe), Some(&world)); +// test_hyrax_for_expander_gkr_generics(&mpi_config, 19); +// } -#[test] -fn test_hyrax_batch_open() { - common::test_batching::, HyraxPCS>(); - common::test_batching_for_expander_gkr::< - BN254Config, - BytesHashTranscript, - HyraxPCS, - >(false); -} +// #[test] +// fn test_hyrax_batch_open() { +// common::test_batching::, HyraxPCS>(); +// common::test_batching_for_expander_gkr::< +// BN254Config, +// BytesHashTranscript, +// HyraxPCS, +// >(false); +// } diff --git a/poly_commit/tests/test_orion.rs b/poly_commit/tests/test_orion.rs index fc48b8e79..84dd5065b 100644 --- a/poly_commit/tests/test_orion.rs +++ b/poly_commit/tests/test_orion.rs @@ -1,141 +1,141 @@ -mod common; - -use arith::{ExtensionField, Field, SimdField}; -use ark_std::test_rng; -use gf2::{GF2x128, GF2x64, GF2x8, GF2}; -use gf2_128::GF2_128; -use gkr_engine::{ - ExpanderSingleVarChallenge, FieldEngine, GF2ExtConfig, Goldilocksx8Config, M31x16Config, - MPIConfig, MPIEngine, Transcript, -}; -use gkr_hashers::Keccak256hasher; -use goldilocks::{Goldilocks, GoldilocksExt2, Goldilocksx8}; -use mersenne31::{M31Ext3, M31x16, M31}; -use poly_commit::*; -use polynomials::MultiLinearPoly; -use transcript::BytesHashTranscript; - -const TEST_REPETITION: usize = 3; - -fn test_orion_simd_pcs_generics( - num_vars_start: usize, - num_vars_end: usize, -) where - F: Field, - SimdF: SimdField, - EvalF: ExtensionField, - ComPackF: SimdField, -{ - let mut rng = test_rng(); - - (num_vars_start..=num_vars_end).for_each(|num_vars| { - let poly_num_vars = num_vars - SimdF::PACK_SIZE.ilog2() as usize; - let xs: Vec<_> = (0..TEST_REPETITION) - .map(|_| -> Vec { - (0..num_vars) - .map(|_| EvalF::random_unsafe(&mut rng)) - .collect() - }) - .collect(); - let poly = MultiLinearPoly::::random(poly_num_vars, &mut rng); - - common::test_pcs::< - EvalF, - BytesHashTranscript, - OrionSIMDFieldPCS, - >(&num_vars, &poly, &xs); - }) -} - -#[test] -fn test_orion_simd_pcs_full_e2e() { - test_orion_simd_pcs_generics::(19, 25); - test_orion_simd_pcs_generics::(19, 25); - test_orion_simd_pcs_generics::(16, 22); - test_orion_simd_pcs_generics::(16, 22) -} - -fn test_orion_for_expander_gkr_generics( - mpi_config_ref: &MPIConfig, - total_num_vars: usize, -) where - C: FieldEngine, - ComPackF: SimdField, - T: Transcript, -{ - let mut rng = test_rng(); - - // NOTE: generate global random polynomial - let num_vars_in_simd = C::SimdCircuitField::PACK_SIZE.ilog2() as usize; - let num_vars_in_mpi = mpi_config_ref.world_size().ilog2() as usize; - let num_vars_in_each_poly = total_num_vars - num_vars_in_mpi - num_vars_in_simd; - let num_vars_in_global_poly = total_num_vars - num_vars_in_simd; - - let global_poly = - MultiLinearPoly::::random(num_vars_in_global_poly, &mut rng); - - // NOTE generate srs for each party, and shared challenge point in each party - let challenge_point = ExpanderSingleVarChallenge:: { - r_mpi: (0..num_vars_in_mpi) - .map(|_| C::ChallengeField::random_unsafe(&mut rng)) - .collect(), - r_simd: (0..num_vars_in_simd) - .map(|_| C::ChallengeField::random_unsafe(&mut rng)) - .collect(), - rz: (0..num_vars_in_each_poly) - .map(|_| C::ChallengeField::random_unsafe(&mut rng)) - .collect(), - }; - - let mut transcript = T::new(); - - dbg!(global_poly.get_num_vars(), global_poly.coeffs[0]); - dbg!(&challenge_point.r_mpi); - dbg!(mpi_config_ref.world_size(), mpi_config_ref.world_rank()); - - // NOTE separate polynomial into different pieces by mpi rank - let poly_vars_stride = (1 << global_poly.get_num_vars()) / mpi_config_ref.world_size(); - let poly_coeff_starts = mpi_config_ref.world_rank() * poly_vars_stride; - let poly_coeff_ends = poly_coeff_starts + poly_vars_stride; - let local_poly = - MultiLinearPoly::new(global_poly.coeffs[poly_coeff_starts..poly_coeff_ends].to_vec()); - - dbg!(local_poly.get_num_vars(), local_poly.coeffs[0]); - - common::test_pcs_for_expander_gkr::< - C, - T, - OrionSIMDFieldPCS, - >( - &num_vars_in_each_poly, - mpi_config_ref, - &mut transcript, - &local_poly, - &[challenge_point], - None, - ); -} - -#[test] -fn test_orion_for_expander_gkr() { - let universe = MPIConfig::init().unwrap(); - let world = universe.world(); - let mpi_config = MPIConfig::prover_new(Some(&universe), Some(&world)); - test_orion_for_expander_gkr_generics::< - GF2ExtConfig, - GF2x128, - BytesHashTranscript, - >(&mpi_config, 25); - - test_orion_for_expander_gkr_generics::< - M31x16Config, - M31x16, - BytesHashTranscript, - >(&mpi_config, 25); - - test_orion_for_expander_gkr_generics::< - Goldilocksx8Config, - Goldilocksx8, - BytesHashTranscript, - >(&mpi_config, 25); -} +// mod common; + +// use arith::{ExtensionField, Field, SimdField}; +// use ark_std::test_rng; +// use gf2::{GF2x128, GF2x64, GF2x8, GF2}; +// use gf2_128::GF2_128; +// use gkr_engine::{ +// ExpanderSingleVarChallenge, FieldEngine, GF2ExtConfig, Goldilocksx8Config, M31x16Config, +// MPIConfig, MPIEngine, Transcript, +// }; +// use gkr_hashers::Keccak256hasher; +// use goldilocks::{Goldilocks, GoldilocksExt2, Goldilocksx8}; +// use mersenne31::{M31Ext3, M31x16, M31}; +// use poly_commit::*; +// use polynomials::MultiLinearPoly; +// use transcript::BytesHashTranscript; + +// const TEST_REPETITION: usize = 3; + +// fn test_orion_simd_pcs_generics( +// num_vars_start: usize, +// num_vars_end: usize, +// ) where +// F: Field, +// SimdF: SimdField, +// EvalF: ExtensionField, +// ComPackF: SimdField, +// { +// let mut rng = test_rng(); + +// (num_vars_start..=num_vars_end).for_each(|num_vars| { +// let poly_num_vars = num_vars - SimdF::PACK_SIZE.ilog2() as usize; +// let xs: Vec<_> = (0..TEST_REPETITION) +// .map(|_| -> Vec { +// (0..num_vars) +// .map(|_| EvalF::random_unsafe(&mut rng)) +// .collect() +// }) +// .collect(); +// let poly = MultiLinearPoly::::random(poly_num_vars, &mut rng); + +// common::test_pcs::< +// EvalF, +// BytesHashTranscript, +// OrionSIMDFieldPCS, +// >(&num_vars, &poly, &xs); +// }) +// } + +// #[test] +// fn test_orion_simd_pcs_full_e2e() { +// test_orion_simd_pcs_generics::(19, 25); +// test_orion_simd_pcs_generics::(19, 25); +// test_orion_simd_pcs_generics::(16, 22); +// test_orion_simd_pcs_generics::(16, +// 22) } + +// fn test_orion_for_expander_gkr_generics( +// mpi_config_ref: &MPIConfig, +// total_num_vars: usize, +// ) where +// C: FieldEngine, +// ComPackF: SimdField, +// T: Transcript, +// { +// let mut rng = test_rng(); + +// // NOTE: generate global random polynomial +// let num_vars_in_simd = C::SimdCircuitField::PACK_SIZE.ilog2() as usize; +// let num_vars_in_mpi = mpi_config_ref.world_size().ilog2() as usize; +// let num_vars_in_each_poly = total_num_vars - num_vars_in_mpi - num_vars_in_simd; +// let num_vars_in_global_poly = total_num_vars - num_vars_in_simd; + +// let global_poly = +// MultiLinearPoly::::random(num_vars_in_global_poly, &mut rng); + +// // NOTE generate srs for each party, and shared challenge point in each party +// let challenge_point = ExpanderSingleVarChallenge:: { +// r_mpi: (0..num_vars_in_mpi) +// .map(|_| C::ChallengeField::random_unsafe(&mut rng)) +// .collect(), +// r_simd: (0..num_vars_in_simd) +// .map(|_| C::ChallengeField::random_unsafe(&mut rng)) +// .collect(), +// rz: (0..num_vars_in_each_poly) +// .map(|_| C::ChallengeField::random_unsafe(&mut rng)) +// .collect(), +// }; + +// let mut transcript = T::new(); + +// dbg!(global_poly.get_num_vars(), global_poly.coeffs[0]); +// dbg!(&challenge_point.r_mpi); +// dbg!(mpi_config_ref.world_size(), mpi_config_ref.world_rank()); + +// // NOTE separate polynomial into different pieces by mpi rank +// let poly_vars_stride = (1 << global_poly.get_num_vars()) / mpi_config_ref.world_size(); +// let poly_coeff_starts = mpi_config_ref.world_rank() * poly_vars_stride; +// let poly_coeff_ends = poly_coeff_starts + poly_vars_stride; +// let local_poly = +// MultiLinearPoly::new(global_poly.coeffs[poly_coeff_starts..poly_coeff_ends].to_vec()); + +// dbg!(local_poly.get_num_vars(), local_poly.coeffs[0]); + +// common::test_pcs_for_expander_gkr::< +// C, +// T, +// OrionSIMDFieldPCS, +// >( +// &num_vars_in_each_poly, +// mpi_config_ref, +// &mut transcript, +// &local_poly, +// &[challenge_point], +// None, +// ); +// } + +// #[test] +// fn test_orion_for_expander_gkr() { +// let universe = MPIConfig::init().unwrap(); +// let world = universe.world(); +// let mpi_config = MPIConfig::prover_new(Some(&universe), Some(&world)); +// test_orion_for_expander_gkr_generics::< +// GF2ExtConfig, +// GF2x128, +// BytesHashTranscript, +// >(&mpi_config, 25); + +// test_orion_for_expander_gkr_generics::< +// M31x16Config, +// M31x16, +// BytesHashTranscript, +// >(&mpi_config, 25); + +// test_orion_for_expander_gkr_generics::< +// Goldilocksx8Config, +// Goldilocksx8, +// BytesHashTranscript, +// >(&mpi_config, 25); +// } diff --git a/poly_commit/tests/test_raw.rs b/poly_commit/tests/test_raw.rs index 44d0c9345..6c53b6287 100644 --- a/poly_commit/tests/test_raw.rs +++ b/poly_commit/tests/test_raw.rs @@ -1,6 +1,7 @@ mod common; use arith::{Field, Fr}; +use ark_std::test_rng; use gkr_engine::{ BN254Config, ExpanderSingleVarChallenge, FieldEngine, GF2ExtConfig, M31x16Config, MPIConfig, MPIEngine, Transcript, @@ -8,14 +9,13 @@ use gkr_engine::{ use gkr_hashers::{Keccak256hasher, SHA256hasher}; use poly_commit::raw::{RawExpanderGKR, RawMultiLinearPCS}; use polynomials::{MultiLinearPoly, RefMultiLinearPoly}; -use rand::thread_rng; use transcript::BytesHashTranscript; #[test] fn test_raw() { // NOTE(HS) 8 variables let params = 8; - let mut rng = thread_rng(); + let mut rng = test_rng(); let poly = MultiLinearPoly::random(params, &mut rng); let xs = (0..100) .map(|_| { @@ -33,7 +33,7 @@ fn test_raw() { fn test_raw_gkr_helper(mpi_config: &MPIConfig, transcript: &mut T) { // NOTE(HS) local variables being 8 let params = 8; - let mut rng = thread_rng(); + let mut rng = test_rng(); let hypercube_basis = (0..(1 << params)) .map(|_| C::SimdCircuitField::random_unsafe(&mut rng)) .collect::>(); diff --git a/poly_commit/tests/test_uni_kzg.rs b/poly_commit/tests/test_uni_kzg.rs index fbc2d8114..149cdd345 100644 --- a/poly_commit/tests/test_uni_kzg.rs +++ b/poly_commit/tests/test_uni_kzg.rs @@ -1,11 +1,11 @@ mod common; use arith::{Field, Fr}; +use ark_bn254::Bn254; use ark_std::test_rng; use gkr_engine::ExpanderPCS; use gkr_engine::{BN254Config, ExpanderSingleVarChallenge, MPIConfig, MPIEngine, Transcript}; use gkr_hashers::Keccak256hasher; -use halo2curves::bn256::Bn256; use poly_commit::HyperUniKZGPCS; use polynomials::MultiLinearPoly; use transcript::BytesHashTranscript; @@ -21,7 +21,7 @@ fn test_hyperkzg_pcs_generics(num_vars_start: usize, num_vars_end: usize) { .collect(); let poly = MultiLinearPoly::::random(num_vars, &mut rng); - common::test_pcs::, HyperUniKZGPCS>( + common::test_pcs::, HyperUniKZGPCS>( &num_vars, &poly, &xs, ); }) @@ -61,14 +61,14 @@ fn test_hyper_unikzg_for_expander_gkr_generics(mpi_config_ref: &MPIConfig, total dbg!(local_poly.get_num_vars(), local_poly.coeffs[0]); - let params = as ExpanderPCS>::gen_params( + let params = as ExpanderPCS>::gen_params( num_vars_in_each_poly, mpi_config_ref.world_size(), ); common::test_pcs_for_expander_gkr::< BN254Config, BytesHashTranscript, - HyperUniKZGPCS, + HyperUniKZGPCS, >( ¶ms, mpi_config_ref, @@ -92,10 +92,10 @@ fn test_hyper_unikzg_for_expander_gkr() { #[test] fn test_uni_kzg_batch_open() { - common::test_batching::, HyperUniKZGPCS>(); + common::test_batching::, HyperUniKZGPCS>(); common::test_batching_for_expander_gkr::< BN254Config, BytesHashTranscript, - HyperUniKZGPCS, + HyperUniKZGPCS, >(true); } diff --git a/serdes/Cargo.toml b/serdes/Cargo.toml index a37a4e632..3960acb01 100644 --- a/serdes/Cargo.toml +++ b/serdes/Cargo.toml @@ -4,11 +4,18 @@ version = "0.1.0" edition = "2021" [dependencies] -thiserror.workspace = true -halo2curves.workspace = true +ark-ec.workspace = true +ark-std.workspace = true +ark-bn254.workspace = true +ark-serialize.workspace = true ethnum.workspace = true +thiserror.workspace = true + +wasm-bindgen = "0.2" serdes_derive = { path = "../serdes_derive" } [dev-dependencies] -rand.workspace = true +# rand.workspace = true + + diff --git a/serdes/src/error.rs b/serdes/src/error.rs index c179a9b18..0f4f71abe 100644 --- a/serdes/src/error.rs +++ b/serdes/src/error.rs @@ -3,7 +3,7 @@ use thiserror::Error; #[derive(Error, Debug)] pub enum SerdeError { #[error("IO Error: {0}")] - IOError(#[from] std::io::Error), + IOError(#[from] ark_std::io::Error), #[error("Deserialization failure")] DeserializeError, @@ -12,4 +12,4 @@ pub enum SerdeError { InvalidVariantIndex(usize), } -pub type SerdeResult = std::result::Result; +pub type SerdeResult = ark_std::result::Result; diff --git a/serdes/src/lib.rs b/serdes/src/lib.rs index b6f7e4195..5a84d9c24 100644 --- a/serdes/src/lib.rs +++ b/serdes/src/lib.rs @@ -1,3 +1,5 @@ +#![no_std] + pub mod error; pub mod macros; pub mod serdes; @@ -5,3 +7,18 @@ pub mod serdes; pub use error::{SerdeError, SerdeResult}; pub use serdes::ExpSerde; pub use serdes_derive::ExpSerde; + +use ark_std::string::ToString; +use wasm_bindgen::prelude::*; +// Import the `console.log` function from the `console` object +#[wasm_bindgen] +extern "C" { + #[wasm_bindgen(js_namespace = console)] + fn log(s: &str); +} + +#[macro_export] +// Define a macro to make console.log easier to use +macro_rules! console_log { + ($($t:tt)*) => (log(&format_args!($($t)*).to_string())) +} diff --git a/serdes/src/serdes.rs b/serdes/src/serdes.rs index 26d61a4ca..1ae481fc9 100644 --- a/serdes/src/serdes.rs +++ b/serdes/src/serdes.rs @@ -1,16 +1,19 @@ -use std::{ +use ark_ec::short_weierstrass::{Affine, SWCurveConfig}; +use ark_serialize::{CanonicalDeserialize, CanonicalSerialize}; +use ark_std::string::ToString; +use ark_std::{ collections::HashMap, hash::Hash, io::{Read, Write}, + string::String, + vec, + vec::Vec, }; - use ethnum::U256; -use halo2curves::{ - bn256::{Fr, G1Affine, G2Affine}, - group::GroupEncoding, -}; -use crate::{exp_serde_for_generic_slices, exp_serde_for_number, SerdeError, SerdeResult}; +use crate::{ + console_log, exp_serde_for_generic_slices, exp_serde_for_number, log, SerdeError, SerdeResult, +}; /// Serde for Arithmetic types such as field and group operations pub trait ExpSerde: Sized { @@ -22,17 +25,17 @@ pub trait ExpSerde: Sized { } impl ExpSerde for () { - fn serialize_into(&self, _writer: W) -> SerdeResult<()> { + fn serialize_into(&self, _writer: W) -> SerdeResult<()> { Ok(()) } - fn deserialize_from(_reader: R) -> SerdeResult { + fn deserialize_from(_reader: R) -> SerdeResult { Ok(()) } } exp_serde_for_number!(u64, 8); -exp_serde_for_number!(usize, 8); +// exp_serde_for_number!(usize, 8); exp_serde_for_number!(u8, 1); exp_serde_for_number!(f64, 8); exp_serde_for_number!(u128, 16); @@ -58,6 +61,16 @@ impl ExpSerde for bool { } } +impl ExpSerde for usize { + fn serialize_into(&self, writer: W) -> SerdeResult<()> { + (*self as u64).serialize_into(writer) + } + + fn deserialize_from(mut reader: R) -> SerdeResult { + u64::deserialize_from(&mut reader).map(|u| u as Self) + } +} + impl ExpSerde for Vec { fn serialize_into(&self, mut writer: W) -> SerdeResult<()> { self.len().serialize_into(&mut writer)?; @@ -77,63 +90,44 @@ impl ExpSerde for Vec { } } -impl ExpSerde for Fr { +impl ExpSerde for ark_bn254::Fr { #[inline(always)] fn serialize_into(&self, mut writer: W) -> SerdeResult<()> { - writer.write_all(self.to_bytes().as_ref())?; + self.serialize_compressed(&mut writer).unwrap(); Ok(()) } #[inline(always)] fn deserialize_from(mut reader: R) -> SerdeResult { - let mut buffer = [0u8; 32]; - reader.read_exact(&mut buffer)?; - match Fr::from_bytes(&buffer).into_option() { - Some(v) => Ok(v), - None => Err(SerdeError::DeserializeError), - } + let res = Self::deserialize_compressed(&mut reader).unwrap(); + Ok(res) } } -impl ExpSerde for G1Affine { - fn serialize_into(&self, writer: W) -> SerdeResult<()> { - let mut buf = [0u8; 32]; - assert!(self.to_bytes().as_ref().len() == 32); - buf.copy_from_slice(self.to_bytes().as_ref()); - buf.serialize_into(writer) - } - - fn deserialize_from(mut reader: R) -> SerdeResult { - let mut buf = [0u8; 32]; - reader.read_exact(&mut buf)?; - - let mut encoding = ::Repr::default(); - encoding.as_mut().copy_from_slice(buf.as_ref()); - match G1Affine::from_bytes(&encoding).into_option() { - Some(a) => Ok(a), - None => Err(SerdeError::DeserializeError), +impl ExpSerde for Affine

{ + #[inline(always)] + fn serialize_into(&self, mut writer: W) -> SerdeResult<()> { + match self.serialize_compressed(&mut writer) { + Ok(()) => Ok(()), + Err(_e) => Err(SerdeError::DeserializeError), } } -} - -impl ExpSerde for G2Affine { - fn serialize_into(&self, writer: W) -> SerdeResult<()> { - let mut buf = [0u8; 64]; - assert!(self.to_bytes().as_ref().len() == 64); - buf.copy_from_slice(self.to_bytes().as_ref()); - buf.serialize_into(writer) - } + #[inline(always)] fn deserialize_from(mut reader: R) -> SerdeResult { - let mut buf = [0u8; 64]; - reader.read_exact(&mut buf)?; - - let mut encoding = ::Repr::default(); - encoding.as_mut().copy_from_slice(buf.as_ref()); - match G2Affine::from_bytes(&encoding).into_option() { - Some(a) => Ok(a), - None => Err(SerdeError::DeserializeError), - } + // let mut buf = [0; 160]; + // reader.read(&mut buf)?; + // console_log!("buf: {:?}", buf); + // let res = match Self::deserialize_compressed_unchecked(&mut buf.as_slice()) { + + let res = match Self::deserialize_compressed_unchecked(&mut reader) { + Ok(res) => res, + Err(e) => { + console_log!("Failed to deserialize Affine: {}", e); + return Err(SerdeError::DeserializeError); + } + }; + Ok(res) } } diff --git a/serdes/tests/basic.rs b/serdes/tests/basic.rs index 7b3541ec5..36a367dbc 100644 --- a/serdes/tests/basic.rs +++ b/serdes/tests/basic.rs @@ -1,6 +1,7 @@ use std::fmt::Debug; -use halo2curves::bn256::{G1Affine, G2Affine}; +use ark_bn254::{G1Affine, G2Affine}; +use ark_std::UniformRand; use serdes::ExpSerde; fn test_serialize_deserialize_helper(obj: T) { @@ -14,8 +15,8 @@ fn test_serialize_deserialize_helper(obj: T) { #[ignore] fn test_g1_g2_serialization() { let mut rng = rand::thread_rng(); - let g1 = G1Affine::random(&mut rng); - let g2 = G2Affine::random(&mut rng); + let g1 = G1Affine::rand(&mut rng); + let g2 = G2Affine::rand(&mut rng); test_serialize_deserialize_helper(g1); test_serialize_deserialize_helper(g2); diff --git a/serdes/tests/serdes_derive.rs b/serdes/tests/serdes_derive.rs index 6fcb9fef9..052831f88 100644 --- a/serdes/tests/serdes_derive.rs +++ b/serdes/tests/serdes_derive.rs @@ -1,5 +1,4 @@ -use std::io::Cursor; - +use ark_std::io::Cursor; use serdes::ExpSerde; #[derive(ExpSerde, Debug, PartialEq)] diff --git a/serdes_derive/Cargo.toml b/serdes_derive/Cargo.toml index 901db4f1d..96e8fada9 100644 --- a/serdes_derive/Cargo.toml +++ b/serdes_derive/Cargo.toml @@ -7,6 +7,8 @@ edition = "2021" proc-macro = true [dependencies] -syn.workspace = true -quote.workspace = true +ark-std.workspace = true + proc-macro2.workspace = true +quote.workspace = true +syn.workspace = true \ No newline at end of file diff --git a/serdes_derive/src/lib.rs b/serdes_derive/src/lib.rs index 4f89242c1..ceb803b5c 100644 --- a/serdes_derive/src/lib.rs +++ b/serdes_derive/src/lib.rs @@ -1,3 +1,7 @@ +#![no_std] + +use ark_std::format; +use ark_std::vec::Vec; use proc_macro::TokenStream; use quote::quote; use syn::{parse_macro_input, Data, DeriveInput, Fields}; @@ -28,7 +32,7 @@ pub fn serdes_derive(input: TokenStream) -> TokenStream { let field_types: Vec<_> = fields.iter().map(|field| &field.ty).collect(); let serialize_impl = quote! { - fn serialize_into(&self, mut writer: W) -> ::serdes::SerdeResult<()> { + fn serialize_into(&self, mut writer: W) -> ::serdes::SerdeResult<()> { #( self.#field_names.serialize_into(&mut writer)?; )* @@ -37,7 +41,7 @@ pub fn serdes_derive(input: TokenStream) -> TokenStream { }; let deserialize_impl = quote! { - fn deserialize_from(mut reader: R) -> ::serdes::SerdeResult { + fn deserialize_from(mut reader: R) -> ::serdes::SerdeResult { Ok(Self { #( #field_names: <#field_types as ::serdes::ExpSerde>::deserialize_from(&mut reader)?, @@ -112,7 +116,7 @@ pub fn serdes_derive(input: TokenStream) -> TokenStream { } } let serialize_variant = quote! { - fn serialize_into(&self, mut writer: W) -> ::serdes::SerdeResult<()> { + fn serialize_into(&self, mut writer: W) -> ::serdes::SerdeResult<()> { match self { #(#serialize_arms)* } @@ -120,7 +124,7 @@ pub fn serdes_derive(input: TokenStream) -> TokenStream { } }; let deserialize_variant = quote! { - fn deserialize_from(mut reader: R) -> ::serdes::SerdeResult { + fn deserialize_from(mut reader: R) -> ::serdes::SerdeResult { let variant_index: u32 = ::serdes::ExpSerde::deserialize_from(&mut reader)?; match variant_index as usize { #(#deserialize_arms)* diff --git a/sumcheck/Cargo.toml b/sumcheck/Cargo.toml index 815e9ee6b..ee6172805 100644 --- a/sumcheck/Cargo.toml +++ b/sumcheck/Cargo.toml @@ -13,12 +13,12 @@ serdes = { path = "../serdes" } transcript = { path = "../transcript" } utils = { path = "../utils" } +ark-std.workspace = true env_logger.workspace = true log.workspace = true rayon.workspace = true [dev-dependencies] -ark-std.workspace = true [features] diff --git a/sumcheck/src/lib.rs b/sumcheck/src/lib.rs index dbaed35c7..468bfc92f 100644 --- a/sumcheck/src/lib.rs +++ b/sumcheck/src/lib.rs @@ -4,7 +4,7 @@ pub use sumcheck::*; mod sumcheck_generic; pub use sumcheck_generic::*; -mod prover_helper; +// mod prover_helper; mod verifier_helper; pub use verifier_helper::*; diff --git a/sumcheck/src/prover_helper.rs b/sumcheck/src/prover_helper.rs index 29d5e1df3..28fcdc8ce 100644 --- a/sumcheck/src/prover_helper.rs +++ b/sumcheck/src/prover_helper.rs @@ -4,5 +4,5 @@ mod simd_gate; mod sumcheck_gkr_square; mod sumcheck_gkr_vanilla; -pub(crate) use sumcheck_gkr_square::SumcheckGkrSquareHelper; +// pub(crate) use sumcheck_gkr_square::SumcheckGkrSquareHelper; pub(crate) use sumcheck_gkr_vanilla::SumcheckGkrVanillaHelper; diff --git a/sumcheck/src/prover_helper/power_gate.rs b/sumcheck/src/prover_helper/power_gate.rs index 8e7266be2..8998a9ec5 100644 --- a/sumcheck/src/prover_helper/power_gate.rs +++ b/sumcheck/src/prover_helper/power_gate.rs @@ -25,7 +25,8 @@ impl SumcheckPowerGateHelper { fn interpolate_3(p_add: &[F::Field; 3], p: &mut [F::Field; D]) { // Calculate coefficients for the interpolating polynomial let p_add_coef_0 = p_add[0]; - let p_add_coef_2 = (p_add[2] - p_add[1] - p_add[1] + p_add[0]) * F::CircuitField::INV_2; + let p_add_coef_2 = + (p_add[2] - p_add[1] - p_add[1] + p_add[0]) * F::CircuitField::from(2).inv().unwrap(); let p_add_coef_1 = p_add[1] - p_add_coef_0 - p_add_coef_2; @@ -62,8 +63,8 @@ impl SumcheckPowerGateHelper { if !gate_exists_5[i * 2] && !gate_exists_5[i * 2 + 1] { continue; } - let mut f_v = [VF::ZERO; D]; - let mut hg_v = [ChallengeF::ZERO; D]; + let mut f_v = [VF::zero(); D]; + let mut hg_v = [ChallengeF::zero(); D]; f_v[0] = src_v[i * 2]; f_v[1] = src_v[i * 2 + 1]; hg_v[0] = bk_hg_5[i * 2]; @@ -81,13 +82,13 @@ impl SumcheckPowerGateHelper { } } - let mut p_add = [EvalF::ZERO; 3]; + let mut p_add = [EvalF::zero(); 3]; for i in 0..eval_size { if !gate_exists_1[i * 2] && !gate_exists_1[i * 2 + 1] { continue; } - let mut f_v = [VF::ZERO; 3]; - let mut hg_v = [ChallengeF::ZERO; 3]; + let mut f_v = [VF::zero(); 3]; + let mut hg_v = [ChallengeF::zero(); 3]; f_v[0] = src_v[i * 2]; f_v[1] = src_v[i * 2 + 1]; hg_v[0] = bk_hg_1[i * 2]; diff --git a/sumcheck/src/prover_helper/product_gate.rs b/sumcheck/src/prover_helper/product_gate.rs index 898b54b89..87a7cb52a 100644 --- a/sumcheck/src/prover_helper/product_gate.rs +++ b/sumcheck/src/prover_helper/product_gate.rs @@ -25,9 +25,9 @@ impl SumcheckProductGateHelper { where EvalF: Field + Mul, { - let mut p0 = EvalF::ZERO; - let mut p1 = EvalF::ZERO; - let mut p2 = EvalF::ZERO; + let mut p0 = EvalF::zero(); + let mut p1 = EvalF::zero(); + let mut p2 = EvalF::zero(); for i in 0..eval_size { if !gate_exists[i * 2] && !gate_exists[i * 2 + 1] { continue; diff --git a/sumcheck/src/prover_helper/simd_gate.rs b/sumcheck/src/prover_helper/simd_gate.rs index e268189d8..022855380 100644 --- a/sumcheck/src/prover_helper/simd_gate.rs +++ b/sumcheck/src/prover_helper/simd_gate.rs @@ -145,7 +145,8 @@ impl SumcheckSimdProdGateHelper { ) { // Calculate coefficients for the interpolating polynomial let p_add_coef_0 = p_add[0]; - let p_add_coef_2 = (p_add[2] - p_add[1] - p_add[1] + p_add[0]) * F::CircuitField::INV_2; + let p_add_coef_2 = + (p_add[2] - p_add[1] - p_add[1] + p_add[0]) * F::CircuitField::from(2).inv().unwrap(); let p_add_coef_1 = p_add[1] - p_add_coef_0 - p_add_coef_2; diff --git a/sumcheck/src/prover_helper/sumcheck_gkr_vanilla.rs b/sumcheck/src/prover_helper/sumcheck_gkr_vanilla.rs index 74bfada9b..e6b389c33 100644 --- a/sumcheck/src/prover_helper/sumcheck_gkr_vanilla.rs +++ b/sumcheck/src/prover_helper/sumcheck_gkr_vanilla.rs @@ -1,6 +1,6 @@ use arith::{Field, SimdField}; use circuit::CircuitLayer; -use gkr_engine::{ExpanderDualVarChallenge, FieldEngine, MPIEngine}; +use gkr_engine::{ExpanderDualVarChallenge, FieldEngine, }; use polynomials::EqPolynomial; use crate::{unpack_and_combine, ProverScratchPad}; @@ -24,7 +24,6 @@ pub(crate) struct SumcheckGkrVanillaHelper<'a, F: FieldEngine> { xy_helper: SumcheckProductGateHelper, simd_var_helper: SumcheckSimdProdGateHelper, - mpi_var_helper: SumcheckSimdProdGateHelper, is_output_layer: bool, } @@ -53,7 +52,6 @@ impl<'a, F: FieldEngine> SumcheckGkrVanillaHelper<'a, F> { challenge: &'a ExpanderDualVarChallenge, alpha: Option, sp: &'a mut ProverScratchPad, - mpi_config: &impl MPIEngine, is_output_layer: bool, ) -> Self { let simd_var_num = F::get_field_pack_size().trailing_zeros() as usize; @@ -73,9 +71,6 @@ impl<'a, F: FieldEngine> SumcheckGkrVanillaHelper<'a, F> { xy_helper: SumcheckProductGateHelper::new(layer.input_var_num), simd_var_helper: SumcheckSimdProdGateHelper::new(simd_var_num), - mpi_var_helper: SumcheckSimdProdGateHelper::new( - mpi_config.world_size().trailing_zeros() as usize, - ), is_output_layer, } } @@ -264,7 +259,7 @@ impl<'a, F: FieldEngine> SumcheckGkrVanillaHelper<'a, F> { // eq_evals_at_rx was thus skipped in the previous round EqPolynomial::::eq_eval_at( &self.challenge.rz_0, - &F::ChallengeField::ONE, + &F::ChallengeField::one(), eq_evals_at_rz0, &mut self.sp.eq_evals_first_half, &mut self.sp.eq_evals_second_half, @@ -342,7 +337,7 @@ impl<'a, F: FieldEngine> SumcheckGkrVanillaHelper<'a, F> { // EQ Polys for next round EqPolynomial::::eq_eval_at( &self.r_mpi_var, - &F::ChallengeField::ONE, + &F::ChallengeField::one(), &mut self.sp.eq_evals_at_r_mpi0, &mut self.sp.eq_evals_first_half, &mut self.sp.eq_evals_second_half, @@ -350,7 +345,7 @@ impl<'a, F: FieldEngine> SumcheckGkrVanillaHelper<'a, F> { EqPolynomial::::eq_eval_at( &self.rx, - &F::ChallengeField::ONE, + &F::ChallengeField::one(), eq_evals_at_rx, &mut self.sp.eq_evals_first_half, &mut self.sp.eq_evals_second_half, @@ -358,7 +353,7 @@ impl<'a, F: FieldEngine> SumcheckGkrVanillaHelper<'a, F> { EqPolynomial::::eq_eval_at( &self.r_simd_var, - &F::ChallengeField::ONE, + &F::ChallengeField::one(), &mut self.sp.eq_evals_at_r_simd0, &mut self.sp.eq_evals_first_half, &mut self.sp.eq_evals_second_half, diff --git a/sumcheck/src/scratch_pad.rs b/sumcheck/src/scratch_pad.rs index 708b45a41..6bd67a0ab 100644 --- a/sumcheck/src/scratch_pad.rs +++ b/sumcheck/src/scratch_pad.rs @@ -66,7 +66,7 @@ impl ProverScratchPad { gate_exists_5: vec![false; max_input_size], gate_exists_1: vec![false; max_input_size], - phase2_coef: F::ChallengeField::ZERO, + phase2_coef: F::ChallengeField::zero(), } } } @@ -112,33 +112,33 @@ impl VerifierScratchPad { let simd_size = F::get_field_pack_size(); let gf2_deg2_eval_coef = if F::FIELD_TYPE == FieldType::GF2Ext128 { - (F::ChallengeField::X - F::ChallengeField::one()) + (F::ChallengeField::x() - F::ChallengeField::one()) .mul_by_x() .inv() .unwrap() } else { - F::ChallengeField::INV_2 + F::ChallengeField::from(2).inv().unwrap() }; let deg3_eval_at = if F::FIELD_TYPE == FieldType::GF2Ext128 { [ - F::ChallengeField::ZERO, - F::ChallengeField::ONE, - F::ChallengeField::X, - F::ChallengeField::X.mul_by_x(), + F::ChallengeField::zero(), + F::ChallengeField::one(), + F::ChallengeField::x(), + F::ChallengeField::x().mul_by_x(), ] } else { [ - F::ChallengeField::ZERO, - F::ChallengeField::ONE, + F::ChallengeField::zero(), + F::ChallengeField::one(), F::ChallengeField::from(2), F::ChallengeField::from(3), ] }; - let mut deg3_lag_denoms_inv = [F::ChallengeField::ZERO; 4]; + let mut deg3_lag_denoms_inv = [F::ChallengeField::zero(); 4]; for i in 0..4 { - let mut denominator = F::ChallengeField::ONE; + let mut denominator = F::ChallengeField::one(); for j in 0..4 { if j == i { continue; @@ -149,8 +149,8 @@ impl VerifierScratchPad { } let deg6_eval_at = [ - F::ChallengeField::ZERO, - F::ChallengeField::ONE, + F::ChallengeField::zero(), + F::ChallengeField::one(), F::ChallengeField::from(2), F::ChallengeField::from(3), F::ChallengeField::from(4), @@ -158,9 +158,9 @@ impl VerifierScratchPad { F::ChallengeField::from(6), ]; - let mut deg6_lag_denoms_inv = [F::ChallengeField::ZERO; 7]; + let mut deg6_lag_denoms_inv = [F::ChallengeField::zero(); 7]; for i in 0..7 { - let mut denominator = F::ChallengeField::ONE; + let mut denominator = F::ChallengeField::one(); for j in 0..7 { if j == i { continue; diff --git a/sumcheck/src/sumcheck.rs b/sumcheck/src/sumcheck.rs index f31d798be..7b9fe35dc 100644 --- a/sumcheck/src/sumcheck.rs +++ b/sumcheck/src/sumcheck.rs @@ -1,143 +1,142 @@ -use circuit::CircuitLayer; -use gkr_engine::{ - ExpanderDualVarChallenge, ExpanderSingleVarChallenge, FieldEngine, MPIConfig, MPIEngine, - Transcript, -}; - -use crate::{ - prover_helper::{SumcheckGkrSquareHelper, SumcheckGkrVanillaHelper}, - utils::transcript_io, - ProverScratchPad, -}; - -/// The degree of the polynomial for sumcheck, which is 2 for non-SIMD/MPI variables -/// and 3 for SIMD/MPI variables. -pub const SUMCHECK_GKR_DEGREE: usize = 2; -pub const SUMCHECK_GKR_SIMD_MPI_DEGREE: usize = 3; - -/// The degree of the polynomial for sumcheck in the GKR square case. -/// It is 6 for both SIMD/MPI and non-SIMD/MPI variables. -pub const SUMCHECK_GKR_SQUARE_DEGREE: usize = 6; - -// FIXME -#[allow(clippy::too_many_arguments)] -#[allow(clippy::type_complexity)] -// essentially the prev level of challenge passes here, once this level is done, new challenge gets -// written back into the prev space -pub fn sumcheck_prove_gkr_layer( - layer: &CircuitLayer, - challenge: &mut ExpanderDualVarChallenge, - alpha: Option, - transcript: &mut T, - sp: &mut ProverScratchPad, - mpi_config: &impl MPIEngine, - is_output_layer: bool, -) -> (F::ChallengeField, Option) { - let mut helper = - SumcheckGkrVanillaHelper::new(layer, challenge, alpha, sp, mpi_config, is_output_layer); - - helper.prepare_simd(); - helper.prepare_mpi(); - - // gkr phase 1 over variable x - helper.prepare_x_vals(); - for i_var in 0..helper.input_var_num { - let evals = helper.poly_evals_at_rx(i_var, SUMCHECK_GKR_DEGREE, mpi_config); - let r = transcript_io::(mpi_config, &evals, transcript); - helper.receive_rx(i_var, r); - log::trace!("x i_var={i_var} evals: {evals:?} r: {r:?}"); - } - - helper.prepare_simd_var_vals(); - for i_var in 0..helper.simd_var_num { - let evals = - helper.poly_evals_at_r_simd_var(i_var, SUMCHECK_GKR_SIMD_MPI_DEGREE, mpi_config); - let r = transcript_io::(mpi_config, &evals, transcript); - helper.receive_r_simd_var(i_var, r); - log::trace!("SIMD i_var={i_var} evals: {evals:?} r: {r:?}"); - } - - helper.prepare_mpi_var_vals(mpi_config); - for i_var in 0..mpi_config.world_size().trailing_zeros() as usize { - let evals = helper.poly_evals_at_r_mpi_var(i_var, SUMCHECK_GKR_SIMD_MPI_DEGREE); - let r = transcript_io::(mpi_config, &evals, transcript); - helper.receive_r_mpi_var(i_var, r); - } - - let vx_claim = helper.vx_claim(); - transcript.append_field_element(&vx_claim); - - // gkr phase 2 over variable y - let mut vy_claim = None; - if !layer.structure_info.skip_sumcheck_phase_two { - helper.prepare_y_vals(mpi_config); - for i_var in 0..helper.input_var_num { - let evals = helper.poly_evals_at_ry(i_var, SUMCHECK_GKR_DEGREE, mpi_config); - let r = transcript_io::(mpi_config, &evals, transcript); - helper.receive_ry(i_var, r); - } - vy_claim = Some(helper.vy_claim(mpi_config)); - transcript.append_field_element(&vy_claim.unwrap()); - } - - let rx = helper.rx; - let ry = if !layer.structure_info.skip_sumcheck_phase_two { - Some(helper.ry) - } else { - None - }; - let r_simd = helper.r_simd_var; - let r_mpi = helper.r_mpi_var; - - *challenge = ExpanderDualVarChallenge::new(rx, ry, r_simd, r_mpi); - (vx_claim, vy_claim) -} - -// FIXME -#[allow(clippy::needless_range_loop)] // todo: remove -#[allow(clippy::type_complexity)] -pub fn sumcheck_prove_gkr_square_layer( - layer: &CircuitLayer, - challenge: &mut ExpanderSingleVarChallenge, - transcript: &mut T, - sp: &mut ProverScratchPad, - mpi_config: &MPIConfig, -) { - const D: usize = SUMCHECK_GKR_SQUARE_DEGREE + 1; - let mut helper = SumcheckGkrSquareHelper::::new(layer, challenge, sp, mpi_config); - - helper.prepare_simd(); - helper.prepare_mpi(); - helper.prepare_g_x_vals(); - - // x-variable sumcheck rounds - for i_var in 0..layer.input_var_num { - let evals = helper.poly_evals_at_x(i_var); - let r = transcript_io::(mpi_config, &evals, transcript); - log::trace!("x i_var={i_var} evals: {evals:?} r: {r:?}"); - helper.receive_x_challenge(i_var, r); - } - - // Unpack SIMD witness polynomial evaluations - helper.prepare_simd_var_vals(); - - // SIMD-variable sumcheck rounds - for i_var in 0..helper.simd_var_num { - let evals = helper.poly_evals_at_simd(i_var); - let r = transcript_io::(mpi_config, &evals, transcript); - log::trace!("SIMD i_var={i_var} evals: {evals:?} r: {r:?}"); - helper.receive_simd_challenge(i_var, r); - } - - helper.prepare_mpi_var_vals(); - for i_var in 0..mpi_config.world_size().trailing_zeros() as usize { - let evals = helper.poly_evals_at_mpi(i_var); - let r = transcript_io::(mpi_config, &evals, transcript); - helper.receive_mpi_challenge(i_var, r); - } - - log::trace!("vx claim: {:?}", helper.vx_claim()); - transcript.append_field_element(&helper.vx_claim()); - - *challenge = ExpanderSingleVarChallenge::new(helper.rx, helper.r_simd_var, helper.r_mpi_var); -} +// use circuit::CircuitLayer; +// use gkr_engine::{ +// ExpanderDualVarChallenge, ExpanderSingleVarChallenge, FieldEngine, +// Transcript, +// }; + +// use crate::{ +// prover_helper::{SumcheckGkrVanillaHelper}, +// // utils::transcript_io, +// ProverScratchPad, +// }; + +// /// The degree of the polynomial for sumcheck, which is 2 for non-SIMD/MPI variables +// /// and 3 for SIMD/MPI variables. +// pub const SUMCHECK_GKR_DEGREE: usize = 2; +// pub const SUMCHECK_GKR_SIMD_MPI_DEGREE: usize = 3; + +// /// The degree of the polynomial for sumcheck in the GKR square case. +// /// It is 6 for both SIMD/MPI and non-SIMD/MPI variables. +// pub const SUMCHECK_GKR_SQUARE_DEGREE: usize = 6; + +// // FIXME +// #[allow(clippy::too_many_arguments)] +// #[allow(clippy::type_complexity)] +// // essentially the prev level of challenge passes here, once this level is done, new challenge +// gets // written back into the prev space +// pub fn sumcheck_prove_gkr_layer( +// layer: &CircuitLayer, +// challenge: &mut ExpanderDualVarChallenge, +// alpha: Option, +// transcript: &mut T, +// sp: &mut ProverScratchPad, +// is_output_layer: bool, +// ) -> (F::ChallengeField, Option) { +// let mut helper = +// SumcheckGkrVanillaHelper::new(layer, challenge, alpha, sp, is_output_layer); + +// helper.prepare_simd(); +// helper.prepare_mpi(); + +// // gkr phase 1 over variable x +// helper.prepare_x_vals(); +// for i_var in 0..helper.input_var_num { +// let evals = helper.poly_evals_at_rx(i_var, SUMCHECK_GKR_DEGREE, mpi_config); +// let r = transcript_io::(mpi_config, &evals, transcript); +// helper.receive_rx(i_var, r); +// log::trace!("x i_var={i_var} evals: {evals:?} r: {r:?}"); +// } + +// helper.prepare_simd_var_vals(); +// for i_var in 0..helper.simd_var_num { +// let evals = +// helper.poly_evals_at_r_simd_var(i_var, SUMCHECK_GKR_SIMD_MPI_DEGREE, mpi_config); +// let r = transcript_io::(mpi_config, &evals, transcript); +// helper.receive_r_simd_var(i_var, r); +// log::trace!("SIMD i_var={i_var} evals: {evals:?} r: {r:?}"); +// } + +// helper.prepare_mpi_var_vals(mpi_config); +// for i_var in 0..mpi_config.world_size().trailing_zeros() as usize { +// let evals = helper.poly_evals_at_r_mpi_var(i_var, SUMCHECK_GKR_SIMD_MPI_DEGREE); +// let r = transcript_io::(mpi_config, &evals, transcript); +// helper.receive_r_mpi_var(i_var, r); +// } + +// let vx_claim = helper.vx_claim(); +// transcript.append_field_element(&vx_claim); + +// // gkr phase 2 over variable y +// let mut vy_claim = None; +// if !layer.structure_info.skip_sumcheck_phase_two { +// helper.prepare_y_vals(mpi_config); +// for i_var in 0..helper.input_var_num { +// let evals = helper.poly_evals_at_ry(i_var, SUMCHECK_GKR_DEGREE, mpi_config); +// let r = transcript_io::(mpi_config, &evals, transcript); +// helper.receive_ry(i_var, r); +// } +// vy_claim = Some(helper.vy_claim(mpi_config)); +// transcript.append_field_element(&vy_claim.unwrap()); +// } + +// let rx = helper.rx; +// let ry = if !layer.structure_info.skip_sumcheck_phase_two { +// Some(helper.ry) +// } else { +// None +// }; +// let r_simd = helper.r_simd_var; +// let r_mpi = helper.r_mpi_var; + +// *challenge = ExpanderDualVarChallenge::new(rx, ry, r_simd, r_mpi); +// (vx_claim, vy_claim) +// } + +// // FIXME +// #[allow(clippy::needless_range_loop)] // todo: remove +// #[allow(clippy::type_complexity)] +// pub fn sumcheck_prove_gkr_square_layer( +// layer: &CircuitLayer, +// challenge: &mut ExpanderSingleVarChallenge, +// transcript: &mut T, +// sp: &mut ProverScratchPad, +// mpi_config: &MPIConfig, +// ) { +// const D: usize = SUMCHECK_GKR_SQUARE_DEGREE + 1; +// let mut helper = SumcheckGkrSquareHelper::::new(layer, challenge, sp, mpi_config); + +// helper.prepare_simd(); +// helper.prepare_mpi(); +// helper.prepare_g_x_vals(); + +// // x-variable sumcheck rounds +// for i_var in 0..layer.input_var_num { +// let evals = helper.poly_evals_at_x(i_var); +// let r = transcript_io::(mpi_config, &evals, transcript); +// log::trace!("x i_var={i_var} evals: {evals:?} r: {r:?}"); +// helper.receive_x_challenge(i_var, r); +// } + +// // Unpack SIMD witness polynomial evaluations +// helper.prepare_simd_var_vals(); + +// // SIMD-variable sumcheck rounds +// for i_var in 0..helper.simd_var_num { +// let evals = helper.poly_evals_at_simd(i_var); +// let r = transcript_io::(mpi_config, &evals, transcript); +// log::trace!("SIMD i_var={i_var} evals: {evals:?} r: {r:?}"); +// helper.receive_simd_challenge(i_var, r); +// } + +// helper.prepare_mpi_var_vals(); +// for i_var in 0..mpi_config.world_size().trailing_zeros() as usize { +// let evals = helper.poly_evals_at_mpi(i_var); +// let r = transcript_io::(mpi_config, &evals, transcript); +// helper.receive_mpi_challenge(i_var, r); +// } + +// log::trace!("vx claim: {:?}", helper.vx_claim()); +// transcript.append_field_element(&helper.vx_claim()); + +// *challenge = ExpanderSingleVarChallenge::new(helper.rx, helper.r_simd_var, helper.r_mpi_var); +// } diff --git a/sumcheck/src/utils.rs b/sumcheck/src/utils.rs index 43728db1e..be9a9b8d8 100644 --- a/sumcheck/src/utils.rs +++ b/sumcheck/src/utils.rs @@ -1,5 +1,5 @@ use arith::{ExtensionField, SimdField}; -use gkr_engine::{MPIEngine, Transcript}; +use gkr_engine::Transcript; #[inline(always)] /// Input @@ -22,22 +22,22 @@ pub fn unpack_and_combine(p: &F, coef: &[F::Scalar]) -> F::Scalar .sum() } -/// Transcript IO between sumcheck steps -#[inline] -pub fn transcript_io(mpi_config: &impl MPIEngine, ps: &[F], transcript: &mut T) -> F -where - F: ExtensionField, - T: Transcript, -{ - // 3 for x, y; 4 for simd var; 7 for pow5, 9 for pow7 - assert!( - ps.len() == 3 || ps.len() == 4 || ps.len() == 7 || ps.len() == 9, - "Unexpected polynomial size" - ); - for p in ps { - transcript.append_field_element(p); - } - let mut r = transcript.generate_field_element::(); - mpi_config.root_broadcast_f(&mut r); - r -} +// /// Transcript IO between sumcheck steps +// #[inline] +// pub fn transcript_io(mpi_config: &impl MPIEngine, ps: &[F], transcript: &mut T) -> F +// where +// F: ExtensionField, +// T: Transcript, +// { +// // 3 for x, y; 4 for simd var; 7 for pow5, 9 for pow7 +// assert!( +// ps.len() == 3 || ps.len() == 4 || ps.len() == 7 || ps.len() == 9, +// "Unexpected polynomial size" +// ); +// for p in ps { +// transcript.append_field_element(p); +// } +// let mut r = transcript.generate_field_element::(); +// mpi_config.root_broadcast_f(&mut r); +// r +// } diff --git a/sumcheck/src/verifier_helper.rs b/sumcheck/src/verifier_helper.rs index 7b89fe5aa..5d3bc3d5a 100644 --- a/sumcheck/src/verifier_helper.rs +++ b/sumcheck/src/verifier_helper.rs @@ -27,7 +27,7 @@ impl GKRVerifierHelper { if is_output_layer { EqPolynomial::::eq_eval_at( &challenge.rz_0, - &F::ChallengeField::ONE, + &F::ChallengeField::one(), &mut sp.eq_evals_at_rz0, &mut sp.eq_evals_first_part, &mut sp.eq_evals_second_part, @@ -46,7 +46,7 @@ impl GKRVerifierHelper { EqPolynomial::::eq_eval_at( &challenge.r_simd, - &F::ChallengeField::ONE, + &F::ChallengeField::one(), &mut sp.eq_evals_at_r_simd, &mut sp.eq_evals_first_part, &mut sp.eq_evals_second_part, @@ -54,7 +54,7 @@ impl GKRVerifierHelper { EqPolynomial::::eq_eval_at( &challenge.r_mpi, - &F::ChallengeField::ONE, + &F::ChallengeField::one(), &mut sp.eq_evals_at_r_mpi, &mut sp.eq_evals_first_part, &mut sp.eq_evals_second_part, @@ -77,7 +77,7 @@ impl GKRVerifierHelper { ) { EqPolynomial::::eq_eval_at( &challenge.rz_0, - &F::ChallengeField::ONE, + &F::ChallengeField::one(), &mut sp.eq_evals_at_rz0, &mut sp.eq_evals_first_part, &mut sp.eq_evals_second_part, @@ -86,7 +86,7 @@ impl GKRVerifierHelper { let alpha = alpha.unwrap(); EqPolynomial::::eq_eval_at( challenge.rz_1.as_ref().unwrap(), - &F::ChallengeField::ONE, + &F::ChallengeField::one(), &mut sp.eq_evals_at_rx, &mut sp.eq_evals_first_part, &mut sp.eq_evals_second_part, @@ -98,7 +98,7 @@ impl GKRVerifierHelper { EqPolynomial::::eq_eval_at( &challenge.r_simd, - &F::ChallengeField::ONE, + &F::ChallengeField::one(), &mut sp.eq_evals_at_r_simd, &mut sp.eq_evals_first_part, &mut sp.eq_evals_second_part, @@ -106,7 +106,7 @@ impl GKRVerifierHelper { EqPolynomial::::eq_eval_at( &challenge.r_mpi, - &F::ChallengeField::ONE, + &F::ChallengeField::one(), &mut sp.eq_evals_at_r_mpi, &mut sp.eq_evals_first_part, &mut sp.eq_evals_second_part, @@ -209,7 +209,7 @@ impl GKRVerifierHelper { pub fn set_rx(rx: &[F::ChallengeField], sp: &mut VerifierScratchPad) { EqPolynomial::::eq_eval_at( rx, - &F::ChallengeField::ONE, + &F::ChallengeField::one(), &mut sp.eq_evals_at_rx, &mut sp.eq_evals_first_part, &mut sp.eq_evals_second_part, @@ -230,7 +230,7 @@ impl GKRVerifierHelper { pub fn set_ry(ry: &[F::ChallengeField], sp: &mut VerifierScratchPad) { EqPolynomial::::eq_eval_at( ry, - &F::ChallengeField::ONE, + &F::ChallengeField::one(), &mut sp.eq_evals_at_ry, &mut sp.eq_evals_first_part, &mut sp.eq_evals_second_part, @@ -257,7 +257,7 @@ impl GKRVerifierHelper { c0 + (c2 * x + c1) * x } else { let c0 = p0; - let c2 = F::ChallengeField::INV_2 * (p2 - p1 - p1 + p0); + let c2 = F::ChallengeField::from(2).inv().unwrap() * (p2 - p1 - p1 + p0); let c1 = p1 - p0 - c2; c0 + (c2 * x + c1) * x } @@ -294,9 +294,9 @@ impl GKRVerifierHelper { _ => panic!("unsupported degree"), }; - let mut v = F::ChallengeField::ZERO; + let mut v = F::ChallengeField::zero(); for i in 0..vals.len() { - let mut numerator = F::ChallengeField::ONE; + let mut numerator = F::ChallengeField::one(); for j in 0..vals.len() { if j == i { continue; diff --git a/transcript/src/lib.rs b/transcript/src/lib.rs index 401dd6eb5..a34ac2773 100644 --- a/transcript/src/lib.rs +++ b/transcript/src/lib.rs @@ -7,7 +7,7 @@ mod random_tape_transcript; pub use random_tape_transcript::RandomTape; mod transcript_utils; -pub use transcript_utils::{transcript_root_broadcast, transcript_verifier_sync}; +pub use transcript_utils::transcript_verifier_sync; #[cfg(test)] mod tests; diff --git a/transcript/src/random_tape_transcript.rs b/transcript/src/random_tape_transcript.rs index 0a77c3d9b..320d85a9a 100644 --- a/transcript/src/random_tape_transcript.rs +++ b/transcript/src/random_tape_transcript.rs @@ -34,7 +34,7 @@ impl Transcript for RandomTape { } let element = self.tape[self.position]; self.position += 1; - let mut element_to_return = F::ZERO; + let mut element_to_return = F::zero(); assert!(F::NAME == ChallengeF::NAME); unsafe { std::ptr::copy_nonoverlapping( diff --git a/transcript/src/transcript_utils.rs b/transcript/src/transcript_utils.rs index a12e9f563..f976819bf 100644 --- a/transcript/src/transcript_utils.rs +++ b/transcript/src/transcript_utils.rs @@ -1,13 +1,13 @@ -use gkr_engine::{MPIEngine, Transcript}; +use gkr_engine::Transcript; -/// broadcast root transcript state. incurs an additional hash if self.world_size > 1 -pub fn transcript_root_broadcast(transcript: &mut impl Transcript, mpi_engine: &impl MPIEngine) { - if mpi_engine.world_size() > 1 { - let mut state = transcript.hash_and_return_state(); - mpi_engine.root_broadcast_bytes(&mut state); - transcript.set_state(&state); - } -} +// /// broadcast root transcript state. incurs an additional hash if self.world_size > 1 +// pub fn transcript_root_broadcast(transcript: &mut impl Transcript, mpi_engine: &impl MPIEngine) { +// if mpi_engine.world_size() > 1 { +// let mut state = transcript.hash_and_return_state(); +// mpi_engine.root_broadcast_bytes(&mut state); +// transcript.set_state(&state); +// } +// } /// Correspondence to 'transcript_root_broadcast' from the verifier side. /// diff --git a/tree/Cargo.toml b/tree/Cargo.toml index 7e78dd863..b389f9f1a 100644 --- a/tree/Cargo.toml +++ b/tree/Cargo.toml @@ -14,8 +14,8 @@ tiny-keccak.workspace = true criterion.workspace = true tynm.workspace = true -gf2 = { path = "../arith/gf2" } -gf2_128 = { path = "../arith/gf2_128" } +# gf2 = { path = "../arith/gf2" } +# gf2_128 = { path = "../arith/gf2_128" } [[bench]] name = "tree" diff --git a/tree/src/leaf.rs b/tree/src/leaf.rs index 18f359cdd..f85b928d3 100644 --- a/tree/src/leaf.rs +++ b/tree/src/leaf.rs @@ -1,5 +1,5 @@ -use std::fmt; -use std::fmt::{Debug, Display}; +use ark_std::fmt; +use ark_std::fmt::{Debug, Display}; use serdes::ExpSerde; use tiny_keccak::{Hasher, Keccak}; diff --git a/tree/src/node.rs b/tree/src/node.rs index 1ae91506a..d68457771 100644 --- a/tree/src/node.rs +++ b/tree/src/node.rs @@ -1,5 +1,4 @@ -use std::{fmt, fmt::Display}; - +use ark_std::{fmt, fmt::Display}; use serdes::ExpSerde; use tiny_keccak::{Hasher, Keccak}; diff --git a/tree/src/path.rs b/tree/src/path.rs index b2c7dbc4b..f591f3314 100644 --- a/tree/src/path.rs +++ b/tree/src/path.rs @@ -1,6 +1,5 @@ -use std::fmt; -use std::fmt::{Debug, Display}; - +use ark_std::fmt; +use ark_std::fmt::{Debug, Display}; use ark_std::{end_timer, start_timer}; use serdes::ExpSerde; @@ -70,7 +69,7 @@ impl Path { current_node = Node::node_hash(¤t_node, node) }; } - + // todo: use timer from util end_timer!(timer); if current_node != *root { println!("path does not match the root"); diff --git a/tree/src/tree.rs b/tree/src/tree.rs index 08a5ac195..52fa4be6d 100644 --- a/tree/src/tree.rs +++ b/tree/src/tree.rs @@ -1,8 +1,7 @@ -use std::fmt; -use std::fmt::{Debug, Display}; -use std::mem::forget; - use arith::{Field, SimdField}; +use ark_std::fmt; +use ark_std::fmt::{Debug, Display}; +use ark_std::mem::forget; use ark_std::{end_timer, log2, start_timer}; use serdes::ExpSerde;