diff --git a/Cargo.lock b/Cargo.lock index 5d708d3703..3758785d44 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -12,6 +12,12 @@ dependencies = [ "regex", ] +[[package]] +name = "adler" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" + [[package]] name = "adler32" version = "1.2.0" @@ -24,7 +30,7 @@ version = "0.7.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9e8b47f52ea9bae42228d07ec09eb676433d7c4ed1ebdf0f1d1c29ed446f1ab8" dependencies = [ - "cfg-if 1.0.0", + "cfg-if", "cipher", "cpufeatures", "opaque-debug 0.3.0", @@ -40,19 +46,19 @@ dependencies = [ ] [[package]] -name = "ansi_term" -version = "0.12.1" +name = "android_system_properties" +version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d52a9bb7ec0cf484c551830a7ce27bd20d67eac647e1befb56b0be4ee39a55d2" +checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" dependencies = [ - "winapi", + "libc", ] [[package]] name = "anyhow" -version = "1.0.57" +version = "1.0.63" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08f9b8508dccb7687a1d6c4ce66b2b0ecef467c94667de27d8d7fe1f8d2a9cdc" +checksum = "a26fa4d7e3f2eebadf743988fc8aec9fa9a9e82611acafd77c1462ed6262440a" [[package]] name = "ark-std" @@ -67,9 +73,9 @@ dependencies = [ [[package]] name = "array-init" -version = "2.0.0" +version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6945cc5422176fc5e602e590c2878d2c2acd9a4fe20a4baa7c28022521698ec6" +checksum = "bfb6d71005dc22a708c7496eee5c8dc0300ee47355de6256c3b35b12b5fef596" [[package]] name = "arrayref" @@ -77,12 +83,6 @@ version = "0.3.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a4c527152e37cf757a3f78aae5a06fbeefdb07ccc535c980a3208ee3060dd544" -[[package]] -name = "arrayvec" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23b62fc65de8e4e7f52534fb52b0f3ed04746ae267519eef2a83941e8085068b" - [[package]] name = "arrayvec" version = "0.7.2" @@ -91,9 +91,9 @@ checksum = "8da52d66c7071e2e3fa2a1e5c6d088fec47b593032b254f5e980de8ea54454d6" [[package]] name = "async-trait" -version = "0.1.53" +version = "0.1.57" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed6aa3524a2dfcf9fe180c51eae2b58738348d819517ceadf95789c51fff7600" +checksum = "76464446b8bc32758d7e88ee1a804d9914cd9b1cb264c029899680b0be29826f" dependencies = [ "proc-macro2", "quote", @@ -176,9 +176,9 @@ checksum = "904dfeac50f3cdaba28fc6f57fdcddb75f49ed61346676a78c4ffe55877802fd" [[package]] name = "base64ct" -version = "1.5.0" +version = "1.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dea908e7347a8c64e378c17e30ef880ad73e3b4498346b055c2c00ea342f3179" +checksum = "ea2b2456fd614d856680dcd9fcc660a51a820fa09daef2e49772b56a193c8474" [[package]] name = "bech32" @@ -216,7 +216,7 @@ name = "bitvec" version = "0.20.5" source = "git+https://github.com/ed255/bitvec.git?rev=5cfc5fa8496c66872d21905e677120fc3e79693c#5cfc5fa8496c66872d21905e677120fc3e79693c" dependencies = [ - "funty", + "funty 1.2.0", "radium 0.6.2", "tap", "wyz 0.2.0", @@ -224,14 +224,14 @@ dependencies = [ [[package]] name = "bitvec" -version = "0.22.3" +version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5237f00a8c86130a0cc317830e558b966dd7850d48a953d998c813f01a41b527" +checksum = "1bc2832c24239b0141d5674bb9174f9d68a8b5b3f2753311927c172ca46f7e9c" dependencies = [ - "funty", - "radium 0.6.2", + "funty 2.0.0", + "radium 0.7.0", "tap", - "wyz 0.4.0", + "wyz 0.5.0", ] [[package]] @@ -245,17 +245,6 @@ dependencies = [ "opaque-debug 0.3.0", ] -[[package]] -name = "blake2b_simd" -version = "0.5.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "afa748e348ad3be8263be728124b24a24f268266f6f5d58af9d75f6a40b5c587" -dependencies = [ - "arrayref", - "arrayvec 0.5.2", - "constant_time_eq", -] - [[package]] name = "blake2b_simd" version = "1.0.0" @@ -263,7 +252,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72936ee4afc7f8f736d1c38383b56480b5497b4617b4a77bdbf1d2ababc76127" dependencies = [ "arrayref", - "arrayvec 0.7.2", + "arrayvec", "constant_time_eq", ] @@ -296,7 +285,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4152116fd6e9dadb291ae18fc1ec3575ed6d84c29642d97890f4b4a3417297e4" dependencies = [ "block-padding 0.2.1", - "generic-array 0.14.5", + "generic-array 0.14.6", ] [[package]] @@ -305,7 +294,7 @@ version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0bf7fe51849ea569fd452f37822f606a5cabb684dc918707a0193fd4664ff324" dependencies = [ - "generic-array 0.14.5", + "generic-array 0.14.6", ] [[package]] @@ -343,9 +332,9 @@ dependencies = [ [[package]] name = "bumpalo" -version = "3.8.0" +version = "3.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f1e260c3a9040a7c19a12468758f4c16f31a81a1fe087482be9570ec864bb6c" +checksum = "c1ad822118d20d2c234f427000d5acc36eabe1e29a348c89b63dd60b13f28e5d" [[package]] name = "bus-mapping" @@ -355,7 +344,7 @@ dependencies = [ "ethers-core", "ethers-providers", "gadgets", - "halo2_proofs 0.1.0-beta.1", + "halo2_proofs 0.2.0", "hex", "itertools", "keccak256", @@ -392,9 +381,9 @@ checksum = "e3b5ca7a04898ad4bcd41c90c5285445ff5b791899bb1b0abdd2a2aa791211d7" [[package]] name = "bytemuck" -version = "1.9.1" +version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cdead85bdec19c194affaeeb670c0e41fe23de31459efd1c174d049269cf02cc" +checksum = "2f5715e491b5a1598fc2bef5a606847b5dc1d48ea625bd3c02c00de8285591da" [[package]] name = "byteorder" @@ -404,18 +393,18 @@ checksum = "14c189c53d098945499cdfa7ecc63567cf3886b3332b312a5b4585d8d3a6a610" [[package]] name = "bytes" -version = "1.1.0" +version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4872d67bab6358e59559027aa3b9157c53d9358c51423c17554809a8858e0f8" +checksum = "ec8a7b6a70fde80372154c65702f00a0f56f3e1c36abbc6c440484be248856db" dependencies = [ "serde", ] [[package]] name = "camino" -version = "1.0.7" +version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6f3132262930b0522068049f5870a856ab8affc80c70d08b6ecb785771a6fc23" +checksum = "88ad0e1e3e88dd237a156ab9f571021b8a158caa0ae44b1968a241efb5144c1e" dependencies = [ "serde", ] @@ -437,7 +426,7 @@ checksum = "4acbb09d9ee8e23699b9634375c72795d095bf268439da88562cf9b501f181fa" dependencies = [ "camino", "cargo-platform", - "semver 1.0.9", + "semver 1.0.13", "serde", "serde_json", ] @@ -454,12 +443,6 @@ version = "1.0.73" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2fff2a6927b3bb87f9595d67196a70493f627687a71d87a0d692242c33f58c11" -[[package]] -name = "cfg-if" -version = "0.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" - [[package]] name = "cfg-if" version = "1.0.0" @@ -468,14 +451,16 @@ checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "chrono" -version = "0.4.19" +version = "0.4.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "670ad68c9088c2a963aaa298cb369688cf3f9465ce5e2d4ca10e6e0098a1ce73" +checksum = "bfd4d1b31faaa3a89d7934dbded3111da0d2ef28e3ebccdb4f0179f5929d1ef1" dependencies = [ - "libc", + "iana-time-zone", + "js-sys", "num-integer", "num-traits", "time", + "wasm-bindgen", "winapi", ] @@ -485,7 +470,7 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7ee52072ec15386f770805afd189a01c8841be8696bed250fa2f13c4c0d6dfb7" dependencies = [ - "generic-array 0.14.5", + "generic-array 0.14.6", ] [[package]] @@ -497,16 +482,13 @@ dependencies = [ "env_logger", "eth-types", "ethers-signers", - "ff 0.11.1", - "group 0.11.0", - "halo2_proofs 0.1.0-beta.1", + "halo2_proofs 0.2.0", "itertools", "keccak256", "mock", "rand", "rand_chacha", "rand_xorshift", - "secp256k1", "zkevm-circuits", ] @@ -576,7 +558,7 @@ dependencies = [ "bech32", "blake2", "digest 0.9.0", - "generic-array 0.14.5", + "generic-array 0.14.6", "hex", "ripemd160", "serde", @@ -603,6 +585,12 @@ dependencies = [ "winapi", ] +[[package]] +name = "const-cstr" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed3d0b5ff30645a68f35ece8cea4556ca14ef8a1651455f789a099a0513532a6" + [[package]] name = "const-oid" version = "0.6.2" @@ -682,9 +670,9 @@ dependencies = [ [[package]] name = "cpufeatures" -version = "0.2.2" +version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59a6001667ab124aebae2a495118e11d30984c3a653e99d86d58971708cf5e4b" +checksum = "dc948ebb96241bb40ab73effeb80d9f93afaad49359d159a5e61be51619fe813" dependencies = [ "libc", ] @@ -695,7 +683,7 @@ version = "1.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b540bd8bc810d3885c6ea91e2018302f68baba2129ab3e88f32389ee9370880d" dependencies = [ - "cfg-if 1.0.0", + "cfg-if", ] [[package]] @@ -736,47 +724,47 @@ dependencies = [ [[package]] name = "crossbeam-channel" -version = "0.5.4" +version = "0.5.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5aaa7bd5fb665c6864b5f963dd9097905c54125909c7aa94c9e18507cdbe6c53" +checksum = "c2dd04ddaf88237dc3b8d8f9a3c1004b506b54b3313403944054d23c0870c521" dependencies = [ - "cfg-if 1.0.0", + "cfg-if", "crossbeam-utils", ] [[package]] name = "crossbeam-deque" -version = "0.8.1" +version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6455c0ca19f0d2fbf751b908d5c55c1f5cbc65e03c4225427254b46890bdde1e" +checksum = "715e8152b692bba2d374b53d4875445368fdf21a94751410af607a5ac677d1fc" dependencies = [ - "cfg-if 1.0.0", + "cfg-if", "crossbeam-epoch", "crossbeam-utils", ] [[package]] name = "crossbeam-epoch" -version = "0.9.8" +version = "0.9.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1145cf131a2c6ba0615079ab6a638f7e1973ac9c2634fcbeaaad6114246efe8c" +checksum = "045ebe27666471bb549370b4b0b3e51b07f56325befa4284db65fc89c02511b1" dependencies = [ "autocfg", - "cfg-if 1.0.0", + "cfg-if", "crossbeam-utils", - "lazy_static", "memoffset", + "once_cell", "scopeguard", ] [[package]] name = "crossbeam-utils" -version = "0.8.8" +version = "0.8.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0bf124c720b7686e3c2663cf54062ab0f68a88af2fb6a030e87e30bf721fcb38" +checksum = "51887d4adc7b564537b15adcfb307936f8075dfcd5f00dde9a9f1d29383682bc" dependencies = [ - "cfg-if 1.0.0", - "lazy_static", + "cfg-if", + "once_cell", ] [[package]] @@ -791,7 +779,7 @@ version = "0.2.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f83bd3bb4314701c568e340cd8cf78c975aa0ca79e03d3f6d1677d5b0c9c0c03" dependencies = [ - "generic-array 0.14.5", + "generic-array 0.14.6", "rand_core", "subtle", "zeroize", @@ -803,7 +791,7 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "03c6a1d5fa1de37e071642dfa44ec552ca5b299adb128fab16138e24b548fd21" dependencies = [ - "generic-array 0.14.5", + "generic-array 0.14.6", "rand_core", "subtle", "zeroize", @@ -811,11 +799,11 @@ dependencies = [ [[package]] name = "crypto-common" -version = "0.1.3" +version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57952ca27b5e3606ff4dd79b0020231aaf9d6aa76dc05fd30137538c50bd3ce8" +checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3" dependencies = [ - "generic-array 0.14.5", + "generic-array 0.14.6", "typenum", ] @@ -825,7 +813,7 @@ version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b584a330336237c1eecd3e94266efb216c56ed91225d634cb2991c5f3fd1aeab" dependencies = [ - "generic-array 0.14.5", + "generic-array 0.14.6", "subtle", ] @@ -835,7 +823,7 @@ version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b1d1a86f49236c215f271d40892d5fc950490551400b02ef360692c29815c714" dependencies = [ - "generic-array 0.14.5", + "generic-array 0.14.6", "subtle", ] @@ -863,9 +851,9 @@ dependencies = [ [[package]] name = "ctor" -version = "0.1.22" +version = "0.1.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f877be4f7c9f246b183111634f75baa039715e3f46ce860677d3b19a69fb229c" +checksum = "cdffe87e1d521a10f9696f833fe502293ea446d7f256c06128293a4119bdf4cb" dependencies = [ "quote", "syn", @@ -917,12 +905,11 @@ dependencies = [ [[package]] name = "deflate" -version = "0.8.6" +version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73770f8e1fe7d64df17ca66ad28994a0a623ea497fa69486e14984e715c5d174" +checksum = "c86f7e25f518f4b81808a2cf1c50996a61f5c2eb394b2393bd87f2a4780a432f" dependencies = [ "adler32", - "byteorder", ] [[package]] @@ -970,9 +957,9 @@ dependencies = [ [[package]] name = "diff" -version = "0.1.12" +version = "0.1.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e25ea47919b1560c4e3b7fe0aaab9becf5b84a10325ddf7db0f0ba5e1026499" +checksum = "56254986775e3233ffa9c4d7d3faaf6d36a2c09d30b20687e9f88bc8bafc16c8" [[package]] name = "digest" @@ -998,7 +985,7 @@ version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d3dd60d1080a57a05ab032377049e0591415d2b31afd7028356dbf3cc6dcb066" dependencies = [ - "generic-array 0.14.5", + "generic-array 0.14.6", ] [[package]] @@ -1017,7 +1004,7 @@ version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b98cf8ebf19c3d1b223e151f99a4f9f0690dca41414773390fc824184ac833e1" dependencies = [ - "cfg-if 1.0.0", + "cfg-if", "dirs-sys-next", ] @@ -1032,6 +1019,15 @@ dependencies = [ "winapi", ] +[[package]] +name = "dlib" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac1b7517328c04c2aa68422fc60a41b92208182142ed04a25879c26c8f878794" +dependencies = [ + "libloading", +] + [[package]] name = "dwrote" version = "0.11.0" @@ -1047,10 +1043,9 @@ dependencies = [ [[package]] name = "ecc" version = "0.1.0" -source = "git+https://github.com/privacy-scaling-explorations/halo2wrong?tag=v2022_06_03#15bb5c9749079b0ee73da4feb740466e64eba740" +source = "git+https://github.com/privacy-scaling-explorations/halo2wrong?tag=v2022_08_24#56639b615295e08e0ef145d8a0c3876f606a7c5c" dependencies = [ - "cfg-if 0.1.10", - "group 0.11.0", + "group 0.12.0", "integer", "num-bigint", "num-integer", @@ -1062,16 +1057,14 @@ dependencies = [ [[package]] name = "ecdsa" version = "0.1.0" -source = "git+https://github.com/privacy-scaling-explorations/halo2wrong?tag=v2022_06_03#15bb5c9749079b0ee73da4feb740466e64eba740" +source = "git+https://github.com/privacy-scaling-explorations/halo2wrong?tag=v2022_08_24#56639b615295e08e0ef145d8a0c3876f606a7c5c" dependencies = [ - "cfg-if 0.1.10", "ecc", - "group 0.11.0", + "group 0.12.0", "num-bigint", "num-integer", "num-traits", "rand", - "secp256k1", "subtle", ] @@ -1089,9 +1082,9 @@ dependencies = [ [[package]] name = "either" -version = "1.6.1" +version = "1.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e78d4f1cc4ae33bbfc157ed5d5a5ef3bc29227303d595861deb238fcec4e9457" +checksum = "90e5c1c8368803113bf0c9584fc495a58b86dc8a29edbf8fe877d21d9507e797" [[package]] name = "elliptic-curve" @@ -1101,7 +1094,7 @@ checksum = "beca177dcb8eb540133e7680baff45e7cc4d93bf22002676cec549f82343721b" dependencies = [ "crypto-bigint 0.2.11", "ff 0.10.1", - "generic-array 0.14.5", + "generic-array 0.14.6", "group 0.10.0", "pkcs8", "rand_core", @@ -1118,7 +1111,7 @@ dependencies = [ "base16ct", "crypto-bigint 0.3.2", "der 0.5.1", - "generic-array 0.14.5", + "generic-array 0.14.6", "rand_core", "subtle", "zeroize", @@ -1130,7 +1123,7 @@ version = "0.8.31" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9852635589dc9f9ea1b6fe9f05b50ef208c85c834a562f0c6abb1c475736ec2b" dependencies = [ - "cfg-if 1.0.0", + "cfg-if", ] [[package]] @@ -1174,9 +1167,7 @@ version = "0.1.0" dependencies = [ "ethers-core", "ethers-signers", - "ff 0.11.1", - "group 0.11.0", - "halo2_proofs 0.1.0-beta.1", + "halo2_proofs 0.2.0", "hex", "itertools", "lazy_static", @@ -1184,10 +1175,9 @@ dependencies = [ "num", "num-bigint", "regex", - "secp256k1", "serde", "serde_json", - "sha3 0.10.1", + "sha3 0.10.2", "subtle", "uint", ] @@ -1277,7 +1267,7 @@ checksum = "658ab90a1fc5f338e8bf6fa6cd614ef4c8d573da40d0c89f45d21c595bda5f3b" dependencies = [ "Inflector", "anyhow", - "cfg-if 1.0.0", + "cfg-if", "ethers-core", "getrandom", "hex", @@ -1312,14 +1302,14 @@ version = "0.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f15e1a2a54bc6bc3f8ea94afafbb374264f8322fcacdae06fefda80a206739ac" dependencies = [ - "arrayvec 0.7.2", + "arrayvec", "bytes", "cargo_metadata", "convert_case", "ecdsa 0.12.4", "elliptic-curve 0.11.12", "ethabi", - "generic-array 0.14.5", + "generic-array 0.14.6", "hex", "k256", "once_cell", @@ -1396,7 +1386,7 @@ dependencies = [ "thiserror", "tokio", "tokio-tungstenite", - "tokio-util 0.6.9", + "tokio-util 0.6.10", "tracing", "tracing-futures", "url", @@ -1423,7 +1413,7 @@ dependencies = [ "futures-util", "hex", "rand", - "semver 1.0.9", + "semver 1.0.13", "sha2 0.9.9", "thiserror", ] @@ -1443,7 +1433,7 @@ dependencies = [ "md-5", "once_cell", "regex", - "semver 1.0.9", + "semver 1.0.13", "serde", "serde_json", "sha2 0.9.9", @@ -1452,16 +1442,6 @@ dependencies = [ "walkdir", ] -[[package]] -name = "expat-sys" -version = "2.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "658f19728920138342f68408b7cf7644d90d4784353d8ebc32e7e8663dbe45fa" -dependencies = [ - "cmake", - "pkg-config", -] - [[package]] name = "external-tracer" version = "0.1.0" @@ -1480,9 +1460,9 @@ checksum = "e88a8acf291dafb59c2d96e8f59828f3838bb1a70398823ade51a84de6a6deed" [[package]] name = "fastrand" -version = "1.7.0" +version = "1.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3fcf0cee53519c866c09b5de1f6c56ff9d647101f81c1964fa632e148896cdf" +checksum = "a7a407cfaa3385c4ae6b23e84623d48c2798d06e3e6a1878f7f59f17b3f86499" dependencies = [ "instant", ] @@ -1499,11 +1479,11 @@ dependencies = [ [[package]] name = "ff" -version = "0.11.1" +version = "0.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "131655483be284720a17d74ff97592b8e76576dc25563148601df2d7c9080924" +checksum = "df689201f395c6b90dfe87127685f8dbfc083a5e779e613575d8bd7314300c3e" dependencies = [ - "bitvec 0.22.3", + "bitvec 1.0.1", "rand_core", "subtle", ] @@ -1534,9 +1514,9 @@ checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" [[package]] name = "font-kit" -version = "0.10.1" +version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46c9a156ec38864999bc9c4156e5f3b50224d4a5578028a64e5a3875caa9ee28" +checksum = "21fe28504d371085fae9ac7a3450f0b289ab71e07c8e57baa3fb68b9e57d6ce5" dependencies = [ "bitflags", "byteorder", @@ -1552,9 +1532,9 @@ dependencies = [ "log", "pathfinder_geometry", "pathfinder_simd", - "servo-fontconfig", "walkdir", "winapi", + "yeslogic-fontconfig-sys", ] [[package]] @@ -1609,11 +1589,17 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1847abb9cb65d566acd5942e94aea9c8f547ad02c98e1649326fc0e8910b8b1e" +[[package]] +name = "funty" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c" + [[package]] name = "futures" -version = "0.3.21" +version = "0.3.24" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f73fe65f54d1e12b726f517d3e2135ca3125a437b6d998caf1962961f7172d9e" +checksum = "7f21eda599937fba36daeb58a22e8f5cee2d14c4a17b5b7739c7c8e5e3b8230c" dependencies = [ "futures-channel", "futures-core", @@ -1626,9 +1612,9 @@ dependencies = [ [[package]] name = "futures-channel" -version = "0.3.21" +version = "0.3.24" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3083ce4b914124575708913bca19bfe887522d6e2e6d0952943f5eac4a74010" +checksum = "30bdd20c28fadd505d0fd6712cdfcb0d4b5648baf45faef7f852afb2399bb050" dependencies = [ "futures-core", "futures-sink", @@ -1636,15 +1622,15 @@ dependencies = [ [[package]] name = "futures-core" -version = "0.3.21" +version = "0.3.24" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c09fd04b7e4073ac7156a9539b57a484a8ea920f79c7c675d05d289ab6110d3" +checksum = "4e5aa3de05362c3fb88de6531e6296e85cde7739cccad4b9dfeeb7f6ebce56bf" [[package]] name = "futures-executor" -version = "0.3.21" +version = "0.3.24" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9420b90cfa29e327d0429f19be13e7ddb68fa1cccb09d65e5706b8c7a749b8a6" +checksum = "9ff63c23854bee61b6e9cd331d523909f238fc7636290b96826e9cfa5faa00ab" dependencies = [ "futures-core", "futures-task", @@ -1653,15 +1639,15 @@ dependencies = [ [[package]] name = "futures-io" -version = "0.3.21" +version = "0.3.24" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc4045962a5a5e935ee2fdedaa4e08284547402885ab326734432bed5d12966b" +checksum = "bbf4d2a7a308fd4578637c0b17c7e1c7ba127b8f6ba00b29f717e9655d85eb68" [[package]] name = "futures-macro" -version = "0.3.21" +version = "0.3.24" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33c1e13800337f4d4d7a316bf45a567dbcb6ffe087f16424852d97e97a91f512" +checksum = "42cd15d1c7456c04dbdf7e88bcd69760d74f3a798d6444e16974b505b0e62f17" dependencies = [ "proc-macro2", "quote", @@ -1670,15 +1656,15 @@ dependencies = [ [[package]] name = "futures-sink" -version = "0.3.21" +version = "0.3.24" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "21163e139fa306126e6eedaf49ecdb4588f939600f0b1e770f4205ee4b7fa868" +checksum = "21b20ba5a92e727ba30e72834706623d94ac93a725410b6a6b6fbc1b07f7ba56" [[package]] name = "futures-task" -version = "0.3.21" +version = "0.3.24" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57c66a976bf5909d801bbef33416c41372779507e7a6b3a5e25e4749c58f776a" +checksum = "a6508c467c73851293f390476d4491cf4d227dbabcd4170f3bb6044959b294f1" [[package]] name = "futures-timer" @@ -1688,9 +1674,9 @@ checksum = "e64b03909df88034c26dc1547e8970b91f98bdb65165d6a4e9110d94263dbb2c" [[package]] name = "futures-util" -version = "0.3.21" +version = "0.3.24" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d8b7abd5d659d9b90c8cba917f6ec750a74e2dc23902ef9cd4cc8c8b22e6036a" +checksum = "44fb6cb1be61cc1d2e43b262516aafcf63b241cffdb1d3fa115f91d9c7b09c90" dependencies = [ "futures-channel", "futures-core", @@ -1710,7 +1696,7 @@ version = "0.1.0" dependencies = [ "digest 0.7.6", "eth-types", - "halo2_proofs 0.1.0-beta.1", + "halo2_proofs 0.2.0", "rand", "rand_xorshift", "sha3 0.7.3", @@ -1737,9 +1723,9 @@ dependencies = [ [[package]] name = "generic-array" -version = "0.14.5" +version = "0.14.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd48d33ec7f05fbfa152300fdad764757cbded343c1aa1cff2fbaf4134851803" +checksum = "bff49e947297f3312447abdca79f45f4738097cc82b06e72054d2223f601f1b9" dependencies = [ "typenum", "version_check", @@ -1754,22 +1740,22 @@ dependencies = [ [[package]] name = "getrandom" -version = "0.2.6" +version = "0.2.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9be70c98951c83b8d2f8f60d7065fa6d5146873094452a1008da8c2f1e4205ad" +checksum = "4eb1a864a501629691edf6c15a593b7a51eebaa1e8468e9ddc623de7c9b58ec6" dependencies = [ - "cfg-if 1.0.0", + "cfg-if", "js-sys", "libc", - "wasi 0.10.0+wasi-snapshot-preview1", + "wasi 0.11.0+wasi-snapshot-preview1", "wasm-bindgen", ] [[package]] name = "gif" -version = "0.11.3" +version = "0.11.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3a7187e78088aead22ceedeee99779455b23fc231fe13ec443f99bb71694e5b" +checksum = "3edd93c6756b4dfaf2709eafcc345ba2636565295c198a9cfbf75fa5e3e00b06" dependencies = [ "color_quant", "weezl", @@ -1803,23 +1789,21 @@ dependencies = [ [[package]] name = "group" -version = "0.11.0" +version = "0.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bc5ac374b108929de78460075f3dc439fa66df9d8fc77e8f12caa5165fcf0c89" +checksum = "7391856def869c1c81063a03457c676fbcd419709c3dfb33d8d319de484b154d" dependencies = [ "byteorder", - "ff 0.11.1", - "rand", + "ff 0.12.0", "rand_core", - "rand_xorshift", "subtle", ] [[package]] name = "h2" -version = "0.3.13" +version = "0.3.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "37a82c6d637fc9515a4694bbf1cb2457b79d81ce52b3108bdeea58b07dd34a57" +checksum = "5ca32592cf21ac7ccab1825cd87f6c9b3d9022c44d086172ed0966bec8af30be" dependencies = [ "bytes", "fnv", @@ -1830,7 +1814,7 @@ dependencies = [ "indexmap", "slab", "tokio", - "tokio-util 0.7.1", + "tokio-util 0.7.3", "tracing", ] @@ -1842,45 +1826,58 @@ checksum = "eabb4a44450da02c90444cf74558da904edde8fb4e9035a9a6a4e15445af0bd7" [[package]] name = "halo2_proofs" -version = "0.1.0-beta.1" -source = "git+https://github.com/privacy-scaling-explorations/halo2.git?tag=v2022_06_03#1fc67702da729b41bfeebc9764c4c6effbd1f9ad" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e925780549adee8364c7f2b685c753f6f3df23bde520c67416e93bf615933760" dependencies = [ - "blake2b_simd 1.0.0", - "bumpalo", - "cfg-if 0.1.10", - "ff 0.11.1", - "group 0.11.0", - "pairing_bn256", + "blake2b_simd", + "ff 0.12.0", + "group 0.12.0", + "pasta_curves", "plotters", - "rand", "rand_core", "rayon", - "subtle", "tabbycat", ] [[package]] name = "halo2_proofs" -version = "0.1.0-beta.3" -source = "git+https://github.com/zcash/halo2.git#406f622e330e23ff91d645d43725e55de665c8e3" +version = "0.2.0" +source = "git+https://github.com/privacy-scaling-explorations/halo2.git?tag=v2022_08_19#0cccba00d16065465c36dce51714637c428bd24c" dependencies = [ - "blake2b_simd 1.0.0", - "bumpalo", - "ff 0.11.1", - "group 0.11.0", - "pasta_curves", + "blake2b_simd", + "ff 0.12.0", + "group 0.12.0", + "halo2curves", "rand_core", "rayon", + "tracing", +] + +[[package]] +name = "halo2curves" +version = "0.2.1" +source = "git+https://github.com/privacy-scaling-explorations/halo2curves?tag=0.2.1#f75ed26c961179186e9cec02cc3f841ca9e3fec1" +dependencies = [ + "ff 0.12.0", + "group 0.12.0", + "lazy_static", + "num-bigint", + "num-traits", + "pasta_curves", + "rand", + "rand_core", + "static_assertions", + "subtle", ] [[package]] name = "halo2wrong" version = "0.1.0" -source = "git+https://github.com/privacy-scaling-explorations/halo2wrong?tag=v2022_06_03#15bb5c9749079b0ee73da4feb740466e64eba740" +source = "git+https://github.com/privacy-scaling-explorations/halo2wrong?tag=v2022_08_24#56639b615295e08e0ef145d8a0c3876f606a7c5c" dependencies = [ - "cfg-if 0.1.10", - "halo2_proofs 0.1.0-beta.1", - "halo2_proofs 0.1.0-beta.3", + "group 0.12.0", + "halo2_proofs 0.2.0", "num-bigint", "num-integer", "num-traits", @@ -1888,9 +1885,9 @@ dependencies = [ [[package]] name = "hashbrown" -version = "0.11.2" +version = "0.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab5ef0d4909ef3724cc8cce6ccc8572c5c817592e9285f5464f8e86f8bd3726e" +checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" [[package]] name = "heck" @@ -1940,7 +1937,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "17ea0a1394df5b6574da6e0c1ade9e78868c9fb0a4e5ef4428e32da4676b85b1" dependencies = [ "digest 0.9.0", - "generic-array 0.14.5", + "generic-array 0.14.6", "hmac 0.8.1", ] @@ -1955,20 +1952,20 @@ dependencies = [ [[package]] name = "http" -version = "0.2.7" +version = "0.2.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff8670570af52249509a86f5e3e18a08c60b177071826898fde8997cf5f6bfbb" +checksum = "75f43d41e26995c17e71ee126451dd3941010b0514a81a9d11f3b341debc2399" dependencies = [ "bytes", "fnv", - "itoa 1.0.1", + "itoa 1.0.3", ] [[package]] name = "http-body" -version = "0.4.4" +version = "0.4.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ff4f84919677303da5f147645dbea6b1881f368d03ac84e1dc09031ebd7b2c6" +checksum = "d5f38f16d184e36f2408a55281cd658ecbd3ca05cce6d6510a176eca393e26d1" dependencies = [ "bytes", "http", @@ -1977,9 +1974,9 @@ dependencies = [ [[package]] name = "httparse" -version = "1.7.1" +version = "1.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "496ce29bb5a52785b44e0f7ca2847ae0bb839c9bd28f69acac9b99d461c0c04c" +checksum = "d897f394bad6a705d5f4104762e116a75639e470d80901eed05a860a95cb1904" [[package]] name = "httpdate" @@ -1995,9 +1992,9 @@ checksum = "9a3a5bfb195931eeb336b2a7b4d761daec841b97f947d34394601737a7bba5e4" [[package]] name = "hyper" -version = "0.14.18" +version = "0.14.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b26ae0a80afebe130861d90abf98e3814a4f28a4c6ffeb5ab8ebb2be311e0ef2" +checksum = "02c929dc5c39e335a03c405292728118860721b10190d98c2a0f0efd5baafbac" dependencies = [ "bytes", "futures-channel", @@ -2008,7 +2005,7 @@ dependencies = [ "http-body", "httparse", "httpdate", - "itoa 1.0.1", + "itoa 1.0.3", "pin-project-lite", "socket2", "tokio", @@ -2025,7 +2022,7 @@ checksum = "d87c48c02e0dc5e3b849a2041db3029fd066650f8f717c07bf8ed78ccb895cac" dependencies = [ "http", "hyper", - "rustls 0.20.4", + "rustls 0.20.6", "tokio", "tokio-rustls 0.23.4", ] @@ -2043,6 +2040,20 @@ dependencies = [ "tokio-native-tls", ] +[[package]] +name = "iana-time-zone" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c495f162af0bf17656d0014a0eded5f3cd2f365fdd204548c2869db89359dc7" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "js-sys", + "once_cell", + "wasm-bindgen", + "winapi", +] + [[package]] name = "ident_case" version = "1.0.1" @@ -2062,16 +2073,15 @@ dependencies = [ [[package]] name = "image" -version = "0.23.14" +version = "0.24.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24ffcb7e7244a9bf19d35bf2883b9c080c4ced3c07a9895572178cdb8f13f6a1" +checksum = "7e30ca2ecf7666107ff827a8e481de6a132a9b687ed3bb20bb1c144a36c00964" dependencies = [ "bytemuck", "byteorder", "color_quant", "jpeg-decoder", - "num-iter", - "num-rational 0.3.2", + "num-rational", "num-traits", "png", ] @@ -2116,9 +2126,9 @@ dependencies = [ [[package]] name = "indexmap" -version = "1.8.1" +version = "1.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f647032dfaa1f8b6dc29bd3edb7bbef4861b8b8007ebb118d6db284fd59f6ee" +checksum = "10a35a97730320ffe8e2d410b5d3b69279b98d2c14bdb8b70ea89ecf7888d41e" dependencies = [ "autocfg", "hashbrown", @@ -2130,7 +2140,7 @@ version = "0.1.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7a5bbe824c507c5da5956355e86a746d82e0e1464f65d862cc5e71da70e94b2c" dependencies = [ - "cfg-if 1.0.0", + "cfg-if", "js-sys", "wasm-bindgen", "web-sys", @@ -2139,16 +2149,14 @@ dependencies = [ [[package]] name = "integer" version = "0.1.0" -source = "git+https://github.com/privacy-scaling-explorations/halo2wrong?tag=v2022_06_03#15bb5c9749079b0ee73da4feb740466e64eba740" +source = "git+https://github.com/privacy-scaling-explorations/halo2wrong?tag=v2022_08_24#56639b615295e08e0ef145d8a0c3876f606a7c5c" dependencies = [ - "cfg-if 0.1.10", - "group 0.11.0", + "group 0.12.0", "maingate", "num-bigint", "num-integer", "num-traits", "rand", - "secp256k1", "subtle", ] @@ -2160,9 +2168,7 @@ dependencies = [ "env_logger", "eth-types", "ethers", - "ff 0.11.1", - "group 0.11.0", - "halo2_proofs 0.1.0-beta.1", + "halo2_proofs 0.2.0", "lazy_static", "log", "paste", @@ -2198,21 +2204,21 @@ checksum = "b71991ff56294aa922b450139ee08b3bfc70982c6b2c7562771375cf73542dd4" [[package]] name = "itoa" -version = "1.0.1" +version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1aab8fc367588b89dcee83ab0fd66b72b50b72fa1904d7095045ace2b0c81c35" +checksum = "6c8af84674fe1f223a982c933a0ee1086ac4d4052aa0fb8060c12c6ad838e754" [[package]] name = "jpeg-decoder" -version = "0.1.22" +version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "229d53d58899083193af11e15917b5640cd40b29ff475a1fe4ef725deb02d0f2" +checksum = "9478aa10f73e7528198d75109c8be5cd7d15fb530238040148d5f9a22d4c5b3b" [[package]] name = "js-sys" -version = "0.3.57" +version = "0.3.59" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "671a26f820db17c2a2750743f1dd03bafd15b98c9f30c7c2628c024c05d73397" +checksum = "258451ab10b34f8af53416d1fdab72c22e805f0c92a1136d59470ec0b11138b2" dependencies = [ "wasm-bindgen", ] @@ -2223,7 +2229,7 @@ version = "0.9.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "903ae2481bcdfdb7b68e0a9baa4b7c9aff600b9ae2e8e5bb5833b8c91ab851ea" dependencies = [ - "cfg-if 1.0.0", + "cfg-if", "ecdsa 0.12.4", "elliptic-curve 0.10.6", "sha2 0.9.9", @@ -2232,17 +2238,16 @@ dependencies = [ [[package]] name = "keccak" -version = "0.1.0" +version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67c21572b4949434e4fc1e1978b99c5f77064153c59d998bf13ecd96fb5ecba7" +checksum = "f9b7d56ba4a8344d6be9729995e6b06f928af29998cdf79fe390cbf6b1fee838" [[package]] name = "keccak256" version = "0.1.0" dependencies = [ "eth-types", - "gadgets", - "halo2_proofs 0.1.0-beta.1", + "halo2_proofs 0.1.0", "itertools", "lazy_static", "num-bigint", @@ -2250,8 +2255,6 @@ dependencies = [ "plotters", "pretty_assertions", "rand", - "strum", - "strum_macros", ] [[package]] @@ -2262,15 +2265,25 @@ checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" [[package]] name = "libc" -version = "0.2.125" +version = "0.2.132" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5916d2ae698f6de9bfb891ad7a8d65c09d232dc58cc4ac433c7da3b2fd84bc2b" +checksum = "8371e4e5341c3a96db127eb2465ac681ced4c433e01dd0e938adbef26ba93ba5" + +[[package]] +name = "libloading" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "efbc0f03f9a775e9f6aed295c6a1ba2253c5757a9e03d55c6caa46a681abcddd" +dependencies = [ + "cfg-if", + "winapi", +] [[package]] name = "libsecp256k1" -version = "0.7.0" +version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0452aac8bab02242429380e9b2f94ea20cea2b37e2c1777a1358799bbe97f37" +checksum = "95b09eff1b35ed3b33b877ced3a691fc7a481919c7e29c53c906226fcf55e2a1" dependencies = [ "arrayref", "base64 0.13.0", @@ -2316,9 +2329,9 @@ dependencies = [ [[package]] name = "lock_api" -version = "0.4.7" +version = "0.4.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "327fa5b6a6940e4699ec49a9beae1ea4845c6bab9314e4f84ac68742139d8c53" +checksum = "9f80bf5aacaf25cbfc8210d1cfb718f2bf3b11c4c54e5afe36c236853a8ec390" dependencies = [ "autocfg", "scopeguard", @@ -2330,16 +2343,15 @@ version = "0.4.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "abb12e687cfb44aa40f41fc3978ef76448f9b6038cad6aef4259d3c095a2382e" dependencies = [ - "cfg-if 1.0.0", + "cfg-if", ] [[package]] name = "maingate" version = "0.1.0" -source = "git+https://github.com/privacy-scaling-explorations/halo2wrong?tag=v2022_06_03#15bb5c9749079b0ee73da4feb740466e64eba740" +source = "git+https://github.com/privacy-scaling-explorations/halo2wrong?tag=v2022_08_24#56639b615295e08e0ef145d8a0c3876f606a7c5c" dependencies = [ - "cfg-if 0.1.10", - "group 0.11.0", + "group 0.12.0", "halo2wrong", "num-bigint", "num-integer", @@ -2388,34 +2400,23 @@ checksum = "2a60c7ce501c71e03a9c9c0d35b861413ae925bd979cc7a4e30d060069aaac8d" [[package]] name = "miniz_oxide" -version = "0.3.7" +version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "791daaae1ed6889560f8c4359194f56648355540573244a5448a83ba1ecc7435" +checksum = "6f5c75688da582b8ffc1f1799e9db273f32133c49e048f614d22ec3256773ccc" dependencies = [ - "adler32", + "adler", ] [[package]] name = "mio" -version = "0.8.2" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52da4364ffb0e4fe33a9841a98a3f3014fb964045ce4f7a45a398243c8d6b0c9" +checksum = "57ee1c23c7c63b0c9250c339ffdc69255f110b298b901b9f6c82547b7b87caaf" dependencies = [ "libc", "log", - "miow", - "ntapi", "wasi 0.11.0+wasi-snapshot-preview1", - "winapi", -] - -[[package]] -name = "miow" -version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9f1c5b025cda876f66ef43a113f91ebc9f4ccef34843000e0adf6ebbab84e21" -dependencies = [ - "winapi", + "windows-sys", ] [[package]] @@ -2451,15 +2452,6 @@ dependencies = [ "tempfile", ] -[[package]] -name = "ntapi" -version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c28774a7fd2fbb4f0babd8237ce554b73af68021b5f695a3cebd6c59bac0980f" -dependencies = [ - "winapi", -] - [[package]] name = "num" version = "0.4.0" @@ -2470,7 +2462,7 @@ dependencies = [ "num-complex", "num-integer", "num-iter", - "num-rational 0.4.0", + "num-rational", "num-traits", ] @@ -2488,9 +2480,9 @@ dependencies = [ [[package]] name = "num-complex" -version = "0.4.1" +version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97fbc387afefefd5e9e39493299f3069e14a140dd34dc19b4c1c1a8fddb6a790" +checksum = "7ae39348c8bc5fbd7f40c727a9925f03517afd2ab27d46702108b6a7e5414c19" dependencies = [ "num-traits", ] @@ -2518,20 +2510,9 @@ dependencies = [ [[package]] name = "num-rational" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12ac428b1cb17fce6f731001d307d351ec70a6d202fc2e60f7d4c5e42d8f4f07" -dependencies = [ - "autocfg", - "num-integer", - "num-traits", -] - -[[package]] -name = "num-rational" -version = "0.4.0" +version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d41702bd167c2df5520b384281bc111a4b5efcf7fbc4c9c222c815b07e0a6a6a" +checksum = "0638a1c9d0a3c0914158145bc76cff373a75a627e6ecbfb71cbe6f453a5a19b0" dependencies = [ "autocfg", "num-bigint", @@ -2560,9 +2541,9 @@ dependencies = [ [[package]] name = "once_cell" -version = "1.10.0" +version = "1.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87f3e037eac156d1775da914196f0f37741a274155e34a0b7e427c35d2a2ecb9" +checksum = "074864da206b4973b84eb91683020dbefd6a8c3f0f38e054d93954e891935e4e" [[package]] name = "oorandom" @@ -2584,12 +2565,12 @@ checksum = "624a8340c38c1b80fd549087862da4ba43e08858af025b236e509b6649fc13d5" [[package]] name = "openssl" -version = "0.10.40" +version = "0.10.41" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fb81a6430ac911acb25fe5ac8f1d2af1b4ea8a4fdfda0f1ee4292af2e2d8eb0e" +checksum = "618febf65336490dfcf20b73f885f5651a0c89c64c2d4a8c3662585a70bf5bd0" dependencies = [ "bitflags", - "cfg-if 1.0.0", + "cfg-if", "foreign-types", "libc", "once_cell", @@ -2616,9 +2597,9 @@ checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf" [[package]] name = "openssl-sys" -version = "0.9.73" +version = "0.9.75" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d5fd19fb3e0a8191c1e34935718976a3e70c112ab9a24af6d7cadccd9d90bc0" +checksum = "e5f9bd0c2710541a3cda73d6f9ac4f1b240de4ae261065d309dbe73d9dceb42f" dependencies = [ "autocfg", "cc", @@ -2636,26 +2617,13 @@ dependencies = [ "winapi", ] -[[package]] -name = "pairing_bn256" -version = "0.1.1" -source = "git+https://github.com/appliedzkp/pairing?tag=v0.1.1#1da2920e0e0b3de5929111e9d6193b6b4f0d99e3" -dependencies = [ - "ff 0.11.1", - "group 0.11.0", - "rand", - "rand_core", - "static_assertions", - "subtle", -] - [[package]] name = "parity-scale-codec" version = "2.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "373b1a4c1338d9cd3d1fa53b3a11bdab5ab6bd80a20f7f7becd76953ae2be909" dependencies = [ - "arrayvec 0.7.2", + "arrayvec", "bitvec 0.20.5", "byte-slice-cast", "impl-trait-for-tuples", @@ -2692,7 +2660,7 @@ version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d76e8e1493bcac0d2766c42737f34458f1c8c50c0d23bcb24ea953affb273216" dependencies = [ - "cfg-if 1.0.0", + "cfg-if", "instant", "libc", "redox_syscall", @@ -2713,13 +2681,13 @@ dependencies = [ [[package]] name = "pasta_curves" -version = "0.3.0" +version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "82b6fc4f73033f6aa52fdde0c38f1f570e7f2c244f22e441f62a144556891b8c" +checksum = "369d7785168ad7ff0cbe467d968ca3e19a927d8536b11ef9c21b4e454b15ba42" dependencies = [ - "blake2b_simd 1.0.0", - "ff 0.11.1", - "group 0.11.0", + "blake2b_simd", + "ff 0.12.0", + "group 0.12.0", "lazy_static", "rand", "static_assertions", @@ -2728,9 +2696,9 @@ dependencies = [ [[package]] name = "paste" -version = "1.0.7" +version = "1.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c520e05135d6e763148b6426a837e239041653ba7becd2e538c076c738025fc" +checksum = "b1de2e551fb905ac83f73f7aedf2f0cb4a0da7e35efa24a202a936269f1f18e1" [[package]] name = "pathfinder_geometry" @@ -2772,10 +2740,11 @@ checksum = "d4fd5641d01c8f18a23da7b6fe29298ff4b55afcccdf78973b24cf3175fee32e" [[package]] name = "pest" -version = "2.1.3" +version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10f4872ae94d7b90ae48754df22fd42ad52ce740b8f370b03da4835417403e53" +checksum = "4b0560d531d1febc25a3c9398a62a71256c0178f2e3443baedd9ad4bb8c9deb4" dependencies = [ + "thiserror", "ucd-trie", ] @@ -2791,18 +2760,18 @@ dependencies = [ [[package]] name = "pin-project" -version = "1.0.10" +version = "1.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "58ad3879ad3baf4e44784bc6a718a8698867bb991f8ce24d1bcbe2cfb4c3a75e" +checksum = "ad29a609b6bcd67fee905812e544992d216af9d755757c05ed2d0e15a74c6ecc" dependencies = [ "pin-project-internal", ] [[package]] name = "pin-project-internal" -version = "1.0.10" +version = "1.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "744b6f092ba29c3650faf274db506afd39944f48420f6c86b17cfe0ee1cb36bb" +checksum = "069bdb1e05adc7a8990dce9cc75370895fbe4e3d58b9b73bf1aee56359344a55" dependencies = [ "proc-macro2", "quote", @@ -2839,9 +2808,9 @@ checksum = "1df8c4ec4b0627e53bdf214615ad287367e482558cf84b109250b37464dc03ae" [[package]] name = "plotters" -version = "0.3.1" +version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32a3fd9ec30b9749ce28cd91f255d569591cdf937fe280c312143e3c4bad6f2a" +checksum = "716b4eeb6c4a1d3ecc956f75b43ec2e8e8ba80026413e70a3f41fd3313d3492b" dependencies = [ "chrono", "font-kit", @@ -2859,15 +2828,15 @@ dependencies = [ [[package]] name = "plotters-backend" -version = "0.3.2" +version = "0.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d88417318da0eaf0fdcdb51a0ee6c3bed624333bff8f946733049380be67ac1c" +checksum = "193228616381fecdc1224c62e96946dfbc73ff4384fba576e052ff8c1bea8142" [[package]] name = "plotters-bitmap" -version = "0.3.1" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "21362fa905695e5618aefd169358f52e0e8bc4a8e05333cf780fda8cddc00b54" +checksum = "0c4a1f21490a6cf4a84c272ad20bd7844ed99a3178187a4c5ab7f2051295beef" dependencies = [ "gif", "image", @@ -2876,18 +2845,18 @@ dependencies = [ [[package]] name = "plotters-svg" -version = "0.3.1" +version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "521fa9638fa597e1dc53e9412a4f9cefb01187ee1f7413076f9e6749e2885ba9" +checksum = "f9a81d2759aae1dae668f783c308bc5c8ebd191ff4184aaa1b37f65a6ae5a56f" dependencies = [ "plotters-backend", ] [[package]] name = "png" -version = "0.16.8" +version = "0.17.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c3287920cb847dee3de33d301c463fba14dda99db24214ddf93f83d3021f4c6" +checksum = "dc38c0ad57efb786dd57b9864e5b18bae478c00c824dc55a38bbc9da95dde3ba" dependencies = [ "bitflags", "crc32fast", @@ -2903,14 +2872,14 @@ checksum = "eb9f9e6e233e5c4a35559a617bf40a4ec447db2e84c20b55a6f83167b7e57872" [[package]] name = "pretty_assertions" -version = "1.2.1" +version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c89f989ac94207d048d92db058e4f6ec7342b0971fc58d1271ca148b799b3563" +checksum = "a25e9bcb20aa780fd0bb16b72403a9064d6b3f22f026946029acb941a50af755" dependencies = [ - "ansi_term", "ctor", "diff", "output_vt100", + "yansi", ] [[package]] @@ -2928,10 +2897,11 @@ dependencies = [ [[package]] name = "proc-macro-crate" -version = "1.1.3" +version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e17d47ce914bf4de440332250b0edd23ce48c005f59fab39d3335866b114f11a" +checksum = "eda0fc3b0fb7c975631757e14d9049da17374063edb6ebbcbc54d880d4fe94e9" dependencies = [ + "once_cell", "thiserror", "toml", ] @@ -2962,18 +2932,18 @@ dependencies = [ [[package]] name = "proc-macro2" -version = "1.0.38" +version = "1.0.43" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9027b48e9d4c9175fa2218adf3557f91c1137021739951d4932f5f8268ac48aa" +checksum = "0a2ca2c61bc9f3d74d2886294ab7b9853abd9c1ad903a3ac7815c58989bb7bab" dependencies = [ - "unicode-xid", + "unicode-ident", ] [[package]] name = "quote" -version = "1.0.18" +version = "1.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1feb54ed693b93a84e14094943b84b7c4eae204c512b7ccb95ab0c66d278ad1" +checksum = "bbe448f377a7d6961e30f5955f9b8d106c3f5e449d493ee1b125c1d43c2b5179" dependencies = [ "proc-macro2", ] @@ -2990,6 +2960,12 @@ version = "0.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "643f8f41a8ebc4c5dc4515c82bb8abd397b527fc20fd681b7c011c2aee5d44fb" +[[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" @@ -3031,9 +3007,9 @@ dependencies = [ [[package]] name = "rayon" -version = "1.5.2" +version = "1.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd249e82c21598a9a426a4e00dd7adc1d640b22445ec8545feef801d1a74c221" +checksum = "bd99e5772ead8baa5215278c9b15bf92087709e9c1b2d1f97cdb5a183c933a7d" dependencies = [ "autocfg", "crossbeam-deque", @@ -3043,9 +3019,9 @@ dependencies = [ [[package]] name = "rayon-core" -version = "1.9.2" +version = "1.9.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f51245e1e62e1f1629cbfec37b5793bbabcaeb90f30e94d2ba03564687353e4" +checksum = "258bcdb5ac6dad48491bb2992db6b7cf74878b0384908af124823d118c99683f" dependencies = [ "crossbeam-channel", "crossbeam-deque", @@ -3055,9 +3031,9 @@ dependencies = [ [[package]] name = "redox_syscall" -version = "0.2.13" +version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62f25bc4c7e55e0b0b7a1d43fb893f4fa1361d0abe38b9ce4f323c2adfe6ef42" +checksum = "fb5a58c1855b4b6819d59012155603f0b22ad30cad752600aadfcb695265519a" dependencies = [ "bitflags", ] @@ -3075,9 +3051,9 @@ dependencies = [ [[package]] name = "regex" -version = "1.5.5" +version = "1.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a11647b6b25ff05a515cb92c365cec08801e83423a235b51e231e1808747286" +checksum = "4c4eb3267174b8c6c2f654116623910a0fef09c4753f8dd83db29c48a0df988b" dependencies = [ "aho-corasick", "memchr", @@ -3092,9 +3068,9 @@ checksum = "6c230d73fb8d8c1b9c0b3135c5142a8acee3a0558fb8db5cf1cb65f8d7862132" [[package]] name = "regex-syntax" -version = "0.6.25" +version = "0.6.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f497285884f3fcff424ffc933e56d7cbca511def0c9831a7f9b5f6153e3cc89b" +checksum = "a3f87b73ce11b1619a3c6332f45341e0047173771e8b8b73f87bfeefb7b56244" [[package]] name = "remove_dir_all" @@ -3107,9 +3083,9 @@ dependencies = [ [[package]] name = "reqwest" -version = "0.11.10" +version = "0.11.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46a1f7aa4f35e5e8b4160449f51afc758f0ce6454315a9fa7d0d113e958c41eb" +checksum = "b75aa69a3f06bbcc66ede33af2af253c6f7a86b1ca0033f60c580a27074fbf92" dependencies = [ "base64 0.13.0", "bytes", @@ -3130,7 +3106,7 @@ dependencies = [ "native-tls", "percent-encoding", "pin-project-lite", - "rustls 0.20.4", + "rustls 0.20.6", "rustls-pemfile", "serde", "serde_json", @@ -3138,11 +3114,12 @@ dependencies = [ "tokio", "tokio-native-tls", "tokio-rustls 0.23.4", + "tower-service", "url", "wasm-bindgen", "wasm-bindgen-futures", "web-sys", - "webpki-roots 0.22.3", + "webpki-roots 0.22.4", "winreg", ] @@ -3214,7 +3191,7 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bfa0f585226d2e68097d4f95d113b15b83a82e819ab25717ec0590d9584ef366" dependencies = [ - "semver 1.0.9", + "semver 1.0.13", ] [[package]] @@ -3232,9 +3209,9 @@ dependencies = [ [[package]] name = "rustls" -version = "0.20.4" +version = "0.20.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4fbfeb8d0ddb84706bc597a5574ab8912817c52a397f819e5b614e2265206921" +checksum = "5aab8ee6c7097ed6057f43c187a62418d0c05a4bd5f18b3571db50ee0f9ce033" dependencies = [ "log", "ring", @@ -3256,24 +3233,24 @@ dependencies = [ [[package]] name = "rustls-pemfile" -version = "0.3.0" +version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ee86d63972a7c661d1536fefe8c3c8407321c3df668891286de28abcd087360" +checksum = "0864aeff53f8c05aa08d86e5ef839d3dfcf07aeba2db32f12db0ef716e87bd55" dependencies = [ "base64 0.13.0", ] [[package]] name = "rustversion" -version = "1.0.6" +version = "1.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2cc38e8fa666e2de3c4aba7edeb5ffc5246c1c2ed0e3d17e560aeeba736b23f" +checksum = "97477e48b4cf8603ad5f7aaf897467cf42ab4218a38ef76fb14c2d6773a6d6a8" [[package]] name = "ryu" -version = "1.0.9" +version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73b4b750c782965c211b42f022f59af1fbceabdd026623714f104152f1ec149f" +checksum = "4501abdff3ae82a1c1b477a17252eb69cee9e66eb915c1abaa4f44d873df9f09" [[package]] name = "salsa20" @@ -3295,12 +3272,12 @@ dependencies = [ [[package]] name = "schannel" -version = "0.1.19" +version = "0.1.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f05ba609c234e60bee0d547fe94a4c7e9da733d1c962cf6e59efa4cd9c8bc75" +checksum = "88d6731146462ea25d9244b2ed5fd1d716d25c52e4d54aa4fb0f3c4e9854dbe2" dependencies = [ "lazy_static", - "winapi", + "windows-sys", ] [[package]] @@ -3343,29 +3320,11 @@ dependencies = [ "untrusted", ] -[[package]] -name = "secp256k1" -version = "0.0.1" -source = "git+https://github.com/privacy-scaling-explorations/halo2wrong?tag=v2022_06_03#15bb5c9749079b0ee73da4feb740466e64eba740" -dependencies = [ - "blake2b_simd 0.5.11", - "cfg-if 0.1.10", - "ff 0.11.1", - "group 0.11.0", - "halo2wrong", - "lazy_static", - "num-bigint", - "num-traits", - "rand", - "static_assertions", - "subtle", -] - [[package]] name = "security-framework" -version = "2.6.1" +version = "2.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2dc14f172faf8a0194a3aded622712b0de276821addc574fa54fc0a1167e10dc" +checksum = "2bc1bb97804af6631813c55739f771071e0f2ed33ee20b68c86ec505d906356c" dependencies = [ "bitflags", "core-foundation", @@ -3395,9 +3354,9 @@ dependencies = [ [[package]] name = "semver" -version = "1.0.9" +version = "1.0.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8cb243bdfdb5936c8dc3c45762a19d12ab4550cdc753bc247637d4ec35a040fd" +checksum = "93f6841e709003d68bb2deee8c343572bf446003ec20a583e76f7b15cebf3711" dependencies = [ "serde", ] @@ -3419,18 +3378,18 @@ checksum = "930c0acf610d3fdb5e2ab6213019aaa04e227ebe9547b0649ba599b16d788bd7" [[package]] name = "serde" -version = "1.0.137" +version = "1.0.144" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61ea8d54c77f8315140a05f4c7237403bf38b72704d031543aa1d16abbf517d1" +checksum = "0f747710de3dcd43b88c9168773254e809d8ddbdf9653b84e2554ab219f17860" dependencies = [ "serde_derive", ] [[package]] name = "serde-aux" -version = "3.0.1" +version = "3.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "93abf9799c576f004252b2a05168d58527fb7c54de12e94b4d12fe3475ffad24" +checksum = "d0a77223b653fa95f3f9864f3eb25b93e4ed170687eb42d85b6b98af21d5e1de" dependencies = [ "serde", "serde_json", @@ -3448,9 +3407,9 @@ dependencies = [ [[package]] name = "serde_derive" -version = "1.0.137" +version = "1.0.144" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f26faba0c3959972377d3b2d306ee9f71faee9714294e41bb777f83f88578be" +checksum = "94ed3a816fb1d101812f83e789f888322c34e291f894f19590dc310963e87a00" dependencies = [ "proc-macro2", "quote", @@ -3459,11 +3418,11 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.81" +version = "1.0.85" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b7ce2b32a1aed03c558dc61a5cd328f15aff2dbc17daad8fb8af04d2100e15c" +checksum = "e55a28e3aaef9d5ce0506d0a14dbba8054ddc7e499ef522dd8b26859ec9d4a44" dependencies = [ - "itoa 1.0.1", + "itoa 1.0.3", "ryu", "serde", ] @@ -3475,32 +3434,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" dependencies = [ "form_urlencoded", - "itoa 1.0.1", + "itoa 1.0.3", "ryu", "serde", ] -[[package]] -name = "servo-fontconfig" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7e3e22fe5fd73d04ebf0daa049d3efe3eae55369ce38ab16d07ddd9ac5c217c" -dependencies = [ - "libc", - "servo-fontconfig-sys", -] - -[[package]] -name = "servo-fontconfig-sys" -version = "5.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e36b879db9892dfa40f95da1c38a835d41634b825fbd8c4c418093d53c24b388" -dependencies = [ - "expat-sys", - "freetype-sys", - "pkg-config", -] - [[package]] name = "sha-1" version = "0.9.8" @@ -3508,7 +3446,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "99cd6713db3cf16b6c84e06321e049a9b9f699826e16096d23bbcc44d15d51a6" dependencies = [ "block-buffer 0.9.0", - "cfg-if 1.0.0", + "cfg-if", "cpufeatures", "digest 0.9.0", "opaque-debug 0.3.0", @@ -3533,7 +3471,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4d58a1e1bf39749807d89cf2d98ac2dfa0ff1cb3faa38fbb64dd88ac8013d800" dependencies = [ "block-buffer 0.9.0", - "cfg-if 1.0.0", + "cfg-if", "cpufeatures", "digest 0.9.0", "opaque-debug 0.3.0", @@ -3575,9 +3513,9 @@ dependencies = [ [[package]] name = "sha3" -version = "0.10.1" +version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "881bf8156c87b6301fc5ca6b27f11eeb2761224c7081e69b409d5a1951a70c86" +checksum = "0a31480366ec990f395a61b7c08122d99bd40544fdb5abcfc1b06bb29994312c" dependencies = [ "digest 0.10.3", "keccak", @@ -3595,21 +3533,24 @@ dependencies = [ [[package]] name = "slab" -version = "0.4.6" +version = "0.4.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb703cfe953bccee95685111adeedb76fabe4e97549a58d16f03ea7b9367bb32" +checksum = "4614a76b2a8be0058caa9dbbaf66d988527d86d003c11a94fbd335d7661edcef" +dependencies = [ + "autocfg", +] [[package]] name = "smallvec" -version = "1.8.0" +version = "1.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2dd574626839106c320a323308629dcb1acfc96e32a8cba364ddc61ac23ee83" +checksum = "2fd0db749597d91ff862fd1d55ea87f7855a744a8425a64695b6fca237d1dad1" [[package]] name = "socket2" -version = "0.4.4" +version = "0.4.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "66d72b759436ae32898a2af0a14218dbf55efde3feeb170eb623637db85ee1e0" +checksum = "10c98bba371b9b22a71a9414e420f92ddeb2369239af08200816169d5e2dd7aa" dependencies = [ "libc", "winapi", @@ -3644,15 +3585,15 @@ checksum = "6446ced80d6c486436db5c078dde11a9f73d42b57fb273121e160b84f63d894c" [[package]] name = "strum" -version = "0.24.0" +version = "0.24.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e96acfc1b70604b8b2f1ffa4c57e59176c7dbb05d556c71ecd2f5498a1dee7f8" +checksum = "063e6045c0e62079840579a7e47a355ae92f60eb74daaf156fb1e84ba164e63f" [[package]] name = "strum_macros" -version = "0.24.0" +version = "0.24.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6878079b17446e4d3eba6192bb0a2950d5b14f0ed8424b852310e5a94345d0ef" +checksum = "1e385be0d24f186b4ce2f9982191e7101bb737312ad61c1f2f984f34bcf85d59" dependencies = [ "heck", "proc-macro2", @@ -3669,13 +3610,13 @@ checksum = "6bdef32e8150c2a081110b42772ffe7d7c9032b606bc226c8260fd97e0976601" [[package]] name = "syn" -version = "1.0.92" +version = "1.0.99" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ff7c592601f11445996a06f8ad0c27f094a58857c2f89e97974ab9235b92c52" +checksum = "58dbef6ec655055e20b86b15a8cc6d439cca19b667537ac6a1369572d151ab13" dependencies = [ "proc-macro2", "quote", - "unicode-xid", + "unicode-ident", ] [[package]] @@ -3701,7 +3642,7 @@ version = "3.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5cdb1ef4eaeeaddc8fbd371e5017057064af0911902ef36b39801f67cc6d79e4" dependencies = [ - "cfg-if 1.0.0", + "cfg-if", "fastrand", "libc", "redox_syscall", @@ -3729,18 +3670,18 @@ dependencies = [ [[package]] name = "thiserror" -version = "1.0.31" +version = "1.0.33" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd829fe32373d27f76265620b5309d0340cb8550f523c1dda251d6298069069a" +checksum = "3d0a539a918745651435ac7db7a18761589a94cd7e94cd56999f828bf73c8a57" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" -version = "1.0.31" +version = "1.0.33" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0396bc89e626244658bef819e22d0cc459e795a5ebe878e6ec336d1674a8d79a" +checksum = "c251e90f708e16c49a16f4917dc2131e75222b72edfa9cb7f7c58ae56aae0c09" dependencies = [ "proc-macro2", "quote", @@ -3794,10 +3735,11 @@ checksum = "cda74da7e1a664f795bb1f8a87ec406fb89a02522cf6e50620d016add6dbbf5c" [[package]] name = "tokio" -version = "1.18.1" +version = "1.20.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dce653fb475565de9f6fb0614b28bca8df2c430c0cf84bcd9c843f15de5414cc" +checksum = "7a8325f63a7d4774dd041e363b2409ed1c5cbbd0f867795e661df066b2b0a581" dependencies = [ + "autocfg", "bytes", "libc", "memchr", @@ -3812,9 +3754,9 @@ dependencies = [ [[package]] name = "tokio-macros" -version = "1.7.0" +version = "1.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b557f72f448c511a979e2564e55d74e6c4432fc96ff4f6241bc6bded342643b7" +checksum = "9724f9a975fb987ef7a3cd9be0350edcbe130698af5b8f7a631e23d42d052484" dependencies = [ "proc-macro2", "quote", @@ -3848,7 +3790,7 @@ version = "0.23.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c43ee83903113e03984cb9e5cebe6c04a5116269e900e3ddba8f068a62adda59" dependencies = [ - "rustls 0.20.4", + "rustls 0.20.6", "tokio", "webpki 0.22.0", ] @@ -3872,9 +3814,9 @@ dependencies = [ [[package]] name = "tokio-util" -version = "0.6.9" +version = "0.6.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e99e1983e5d376cd8eb4b66604d2e99e79f5bd988c3055891dcd8c9e2604cc0" +checksum = "36943ee01a6d67977dd3f84a5a1d2efeb4ada3a1ae771cadfaa535d9d9fc6507" dependencies = [ "bytes", "futures-core", @@ -3886,9 +3828,9 @@ dependencies = [ [[package]] name = "tokio-util" -version = "0.7.1" +version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0edfdeb067411dba2044da6d1cb2df793dd35add7888d73c16e3381ded401764" +checksum = "cc463cd8deddc3770d20f9852143d50bf6094e640b485cb2e189a2099085ff45" dependencies = [ "bytes", "futures-core", @@ -3909,17 +3851,17 @@ dependencies = [ [[package]] name = "tower-service" -version = "0.3.1" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "360dfd1d6d30e05fda32ace2c8c70e9c0a9da713275777f5a4dbb8a1893930c6" +checksum = "b6bc1c9ce2b5135ac7f93c72918fc37feb872bdc6a5533a8b85eb4b86bfdae52" [[package]] name = "tracing" -version = "0.1.34" +version = "0.1.36" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d0ecdcb44a79f0fe9844f0c4f33a342cbcbb5117de8001e6ba0dc2351327d09" +checksum = "2fce9567bd60a67d08a16488756721ba392f24f29006402881e43b19aac64307" dependencies = [ - "cfg-if 1.0.0", + "cfg-if", "pin-project-lite", "tracing-attributes", "tracing-core", @@ -3927,9 +3869,9 @@ dependencies = [ [[package]] name = "tracing-attributes" -version = "0.1.21" +version = "0.1.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc6b8ad3567499f98a1db7a752b07a7c8c7c7c34c332ec00effb2b0027974b7c" +checksum = "11c75893af559bc8e10716548bdef5cb2b983f8e637db9d0e15126b61b484ee2" dependencies = [ "proc-macro2", "quote", @@ -3938,11 +3880,11 @@ dependencies = [ [[package]] name = "tracing-core" -version = "0.1.26" +version = "0.1.29" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f54c8ca710e81886d498c2fd3331b56c93aa248d49de2222ad2742247c60072f" +checksum = "5aeea4303076558a00714b823f9ad67d58a3bbda1df83d8827d21193156e22f7" dependencies = [ - "lazy_static", + "once_cell", ] [[package]] @@ -3963,9 +3905,9 @@ checksum = "59547bce71d9c38b83d9c0e92b6066c4253371f15005def0c30d9657f50c7642" [[package]] name = "ttf-parser" -version = "0.12.3" +version = "0.15.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ae2f58a822f08abdaf668897e96a5656fe72f5a9ce66422423e8849384872e6" +checksum = "7b3e06c9b9d80ed6b745c7159c40b311ad2916abb34a49e9be2653b90db0d8dd" [[package]] name = "tungstenite" @@ -3997,9 +3939,9 @@ checksum = "dcf81ac59edc17cc8697ff311e8f5ef2d99fcbd9817b34cec66f90b6c3dfd987" [[package]] name = "ucd-trie" -version = "0.1.3" +version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56dee185309b50d1f11bfedef0fe6d036842e3fb77413abef29f8f8d1c5d4c1c" +checksum = "89570599c4fe5585de2b388aab47e99f7fa4e9238a1399f707a02e356058141c" [[package]] name = "uint" @@ -4019,11 +3961,17 @@ version = "0.3.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "099b7128301d285f79ddd55b9a83d5e6b9e97c92e0ea0daebee7263e932de992" +[[package]] +name = "unicode-ident" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4f5b37a154999a8f3f98cc23a628d850e154479cd94decf3414696e12e31aaf" + [[package]] name = "unicode-normalization" -version = "0.1.19" +version = "0.1.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d54590932941a9e9266f0832deed84ebe1bf2e4c9e4a3554d393d18f5e854bf9" +checksum = "854cbdc4f7bc6ae19c820d44abdc3277ac3e1b2b93db20a636825d9322fb60e6" dependencies = [ "tinyvec", ] @@ -4034,12 +3982,6 @@ version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ed742d4ea2bd1176e236172c8429aaf54486e7ac098db29ffe6529e0ce50973" -[[package]] -name = "unicode-xid" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "957e51f3646910546462e67d5f7599b9e4fb8acdd304b087a6494730f9eebf04" - [[package]] name = "untrusted" version = "0.7.1" @@ -4121,23 +4063,23 @@ checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" [[package]] name = "wasm-bindgen" -version = "0.2.80" +version = "0.2.82" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "27370197c907c55e3f1a9fbe26f44e937fe6451368324e009cba39e139dc08ad" +checksum = "fc7652e3f6c4706c8d9cd54832c4a4ccb9b5336e2c3bd154d5cccfbf1c1f5f7d" dependencies = [ - "cfg-if 1.0.0", + "cfg-if", "wasm-bindgen-macro", ] [[package]] name = "wasm-bindgen-backend" -version = "0.2.80" +version = "0.2.82" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53e04185bfa3a779273da532f5025e33398409573f348985af9a1cbf3774d3f4" +checksum = "662cd44805586bd52971b9586b1df85cdbbd9112e4ef4d8f41559c334dc6ac3f" dependencies = [ "bumpalo", - "lazy_static", "log", + "once_cell", "proc-macro2", "quote", "syn", @@ -4146,11 +4088,11 @@ dependencies = [ [[package]] name = "wasm-bindgen-futures" -version = "0.4.30" +version = "0.4.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6f741de44b75e14c35df886aff5f1eb73aa114fa5d4d00dcd37b5e01259bf3b2" +checksum = "fa76fb221a1f8acddf5b54ace85912606980ad661ac7a503b4570ffd3a624dad" dependencies = [ - "cfg-if 1.0.0", + "cfg-if", "js-sys", "wasm-bindgen", "web-sys", @@ -4158,9 +4100,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro" -version = "0.2.80" +version = "0.2.82" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "17cae7ff784d7e83a2fe7611cfe766ecf034111b49deb850a3dc7699c08251f5" +checksum = "b260f13d3012071dfb1512849c033b1925038373aea48ced3012c09df952c602" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -4168,9 +4110,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.80" +version = "0.2.82" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "99ec0dc7a4756fffc231aab1b9f2f578d23cd391390ab27f952ae0c9b3ece20b" +checksum = "5be8e654bdd9b79216c2929ab90721aa82faf65c48cdf08bdc4e7f51357b80da" dependencies = [ "proc-macro2", "quote", @@ -4181,9 +4123,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-shared" -version = "0.2.80" +version = "0.2.82" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d554b7f530dee5964d9a9468d95c1f8b8acae4f282807e7d27d4b03099a46744" +checksum = "6598dd0bd3c7d51095ff6531a5b23e02acdc81804e30d8f07afb77b7215a140a" [[package]] name = "wasm-timer" @@ -4202,9 +4144,9 @@ dependencies = [ [[package]] name = "web-sys" -version = "0.3.57" +version = "0.3.59" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b17e741662c70c8bd24ac5c5b18de314a2c26c32bf8346ee1e6f53de919c283" +checksum = "ed055ab27f941423197eb86b2035720b1a3ce40504df082cac2ecc6ed73335a1" dependencies = [ "js-sys", "wasm-bindgen", @@ -4241,18 +4183,18 @@ dependencies = [ [[package]] name = "webpki-roots" -version = "0.22.3" +version = "0.22.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "44d8de8415c823c8abd270ad483c6feeac771fad964890779f9a8cb24fbbc1bf" +checksum = "f1c760f0d366a6c24a02ed7816e23e691f5d92291f94d15e836006fd11b04daf" dependencies = [ "webpki 0.22.0", ] [[package]] name = "weezl" -version = "0.1.6" +version = "0.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c97e489d8f836838d497091de568cf16b117486d529ec5579233521065bd5e4" +checksum = "9193164d4de03a926d909d3bc7c30543cecb35400c02114792c2cae20d5e2dbb" [[package]] name = "winapi" @@ -4285,6 +4227,49 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" +[[package]] +name = "windows-sys" +version = "0.36.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea04155a16a59f9eab786fe12a4a450e75cdb175f9e0d80da1e17db09f55b8d2" +dependencies = [ + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_msvc" +version = "0.36.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bb8c3fd39ade2d67e9874ac4f3db21f0d710bee00fe7cab16949ec184eeaa47" + +[[package]] +name = "windows_i686_gnu" +version = "0.36.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "180e6ccf01daf4c426b846dfc66db1fc518f074baa793aa7d9b9aaeffad6a3b6" + +[[package]] +name = "windows_i686_msvc" +version = "0.36.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2e7917148b2812d1eeafaeb22a97e4813dfa60a3f8f78ebe204bcc88f12f024" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.36.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4dcd171b8776c41b97521e5da127a2d86ad280114807d0b2ab1e462bc764d9e1" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.36.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c811ca4a8c853ef420abd8592ba53ddbbac90410fab6903b3e79972a631f7680" + [[package]] name = "winreg" version = "0.10.1" @@ -4329,13 +4314,31 @@ checksum = "85e60b0d1b5f99db2556934e21937020776a5d31520bf169e851ac44e6420214" [[package]] name = "wyz" -version = "0.4.0" +version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "129e027ad65ce1453680623c3fb5163cbf7107bfe1aa32257e7d0e63f9ced188" +checksum = "30b31594f29d27036c383b53b59ed3476874d518f0efb151b27a4c275141390e" dependencies = [ "tap", ] +[[package]] +name = "yansi" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09041cd90cf85f7f8b2df60c646f853b7f535ce68f85244eb6731cf89fa498ec" + +[[package]] +name = "yeslogic-fontconfig-sys" +version = "3.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2bbd69036d397ebbff671b1b8e4d918610c181c5a16073b96f984a38d08c386" +dependencies = [ + "const-cstr", + "dlib", + "once_cell", + "pkg-config", +] + [[package]] name = "zeroize" version = "1.4.3" @@ -4357,22 +4360,24 @@ dependencies = [ "ethers-core", "ethers-signers", "gadgets", - "group 0.11.0", - "halo2_proofs 0.1.0-beta.1", + "halo2_proofs 0.2.0", "hex", "integer", "itertools", "keccak256", "lazy_static", + "libsecp256k1", "log", "maingate", "mock", + "num", + "num-bigint", "pretty_assertions", "rand", "rand_chacha", "rand_xorshift", - "secp256k1", - "sha3 0.10.1", + "sha3 0.10.2", "strum", "strum_macros", + "subtle", ] diff --git a/Cargo.toml b/Cargo.toml index 693fd53e11..ec0b239506 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,8 +2,8 @@ members = [ "zkevm-circuits", "bus-mapping", - "keccak256", "geth-utils", + "keccak256", "gadgets", "integration-tests", "circuit-benchmarks", @@ -18,7 +18,7 @@ members = [ # and leads to a compilation error. This can be removed once the upstream PR # is resolved: https://github.com/bitvecto-rs/bitvec/pull/141 bitvec = { git = "https://github.com/ed255/bitvec.git", rev = "5cfc5fa8496c66872d21905e677120fc3e79693c" } -halo2_proofs = { git = "https://github.com/privacy-scaling-explorations/halo2.git", tag = "v2022_06_03" } +halo2_proofs = { git = "https://github.com/privacy-scaling-explorations/halo2.git", tag = "v2022_08_19" } # Definition of benchmarks profile to use. [profile.bench] diff --git a/bus-mapping/Cargo.toml b/bus-mapping/Cargo.toml index 8eb107b877..54a2e04b1c 100644 --- a/bus-mapping/Cargo.toml +++ b/bus-mapping/Cargo.toml @@ -13,7 +13,7 @@ mock = { path = "../mock", optional = true } ethers-core = "0.6" ethers-providers = "0.6" -halo2_proofs = { version = "0.1.0-beta.1" } +halo2_proofs = { git = "https://github.com/privacy-scaling-explorations/halo2.git", tag = "v2022_08_19" } itertools = "0.10" lazy_static = "1.4" log = "0.4.14" diff --git a/circuit-benchmarks/Cargo.toml b/circuit-benchmarks/Cargo.toml index 6de4022cec..29f81d740d 100644 --- a/circuit-benchmarks/Cargo.toml +++ b/circuit-benchmarks/Cargo.toml @@ -7,8 +7,7 @@ license = "MIT OR Apache-2.0" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -ff = "0.11" -halo2_proofs = { version = "0.1.0-beta.1" } +halo2_proofs = { git = "https://github.com/privacy-scaling-explorations/halo2.git", tag = "v2022_08_19" } ark-std = { version = "0.3", features = ["print-trace"] } zkevm-circuits = { path = "../zkevm-circuits" } keccak256 = { path = "../keccak256" } @@ -17,8 +16,6 @@ rand_xorshift = "0.3" rand = "0.8" itertools = "0.10" eth-types = { path = "../eth-types" } -secp256k1 = { git = "https://github.com/privacy-scaling-explorations/halo2wrong", tag = "v2022_06_03", features = ["kzg"] } -group = "0.11" env_logger = "0.9" ethers-signers = "0.6" mock = { path="../mock" } diff --git a/circuit-benchmarks/src/bit_keccak.rs b/circuit-benchmarks/src/bit_keccak.rs index 8810793314..b7aa055a2b 100644 --- a/circuit-benchmarks/src/bit_keccak.rs +++ b/circuit-benchmarks/src/bit_keccak.rs @@ -3,11 +3,17 @@ #[cfg(test)] mod tests { use ark_std::{end_timer, start_timer}; - use halo2_proofs::plonk::{create_proof, keygen_pk, keygen_vk, verify_proof, SingleVerifier}; + use halo2_proofs::halo2curves::bn256::Fr; + use halo2_proofs::plonk::{create_proof, keygen_pk, keygen_vk, verify_proof}; + use halo2_proofs::poly::commitment::ParamsProver; + use halo2_proofs::poly::kzg::commitment::{KZGCommitmentScheme, ParamsKZG, ParamsVerifierKZG}; + use halo2_proofs::poly::kzg::multiopen::{ProverSHPLONK, VerifierSHPLONK}; + use halo2_proofs::poly::kzg::strategy::SingleStrategy; use halo2_proofs::{ - pairing::bn256::{Bn256, G1Affine}, - poly::commitment::{Params, ParamsVerifier}, - transcript::{Blake2bRead, Blake2bWrite, Challenge255}, + halo2curves::bn256::{Bn256, G1Affine}, + transcript::{ + Blake2bRead, Blake2bWrite, Challenge255, TranscriptReadBuffer, TranscriptWriterBuffer, + }, }; use rand::SeedableRng; use rand_xorshift::XorShiftRng; @@ -30,7 +36,7 @@ mod tests { circuit.generate_witness(&inputs); // Initialize the polynomial commitment parameters - let rng = XorShiftRng::from_seed([ + let mut rng = XorShiftRng::from_seed([ 0x59, 0x62, 0xbe, 0x5d, 0x76, 0x3d, 0x31, 0x8d, 0x17, 0xdb, 0x37, 0x32, 0x54, 0x06, 0xbc, 0xe5, ]); @@ -38,21 +44,27 @@ mod tests { // Bench setup generation let setup_message = format!("Setup generation with degree = {}", degree); let start1 = start_timer!(|| setup_message); - let general_params: Params = Params::::unsafe_setup::(degree); - let verifier_params: ParamsVerifier = - general_params.verifier(degree as usize * 2).unwrap(); + let general_params = ParamsKZG::::setup(degree, &mut rng); + let verifier_params: ParamsVerifierKZG = general_params.verifier_params().clone(); end_timer!(start1); // Initialize the proving key let vk = keygen_vk(&general_params, &circuit).expect("keygen_vk should not fail"); let pk = keygen_pk(&general_params, vk, &circuit).expect("keygen_pk should not fail"); // Create a proof - let mut transcript = Blake2bWrite::<_, _, Challenge255<_>>::init(vec![]); + let mut transcript = Blake2bWrite::<_, G1Affine, Challenge255<_>>::init(vec![]); // Bench proof generation time let proof_message = format!("Bit Keccak Proof generation with {} rows", degree); let start2 = start_timer!(|| proof_message); - create_proof( + create_proof::< + KZGCommitmentScheme, + ProverSHPLONK<'_, Bn256>, + Challenge255, + XorShiftRng, + Blake2bWrite, G1Affine, Challenge255>, + KeccakBitCircuit, + >( &general_params, &pk, &[circuit], @@ -66,10 +78,16 @@ mod tests { // Bench verification time let start3 = start_timer!(|| "Keccak Proof verification"); - let mut verifier_transcript = Blake2bRead::<_, _, Challenge255<_>>::init(&proof[..]); - let strategy = SingleVerifier::new(&verifier_params); + let mut verifier_transcript = Blake2bRead::<_, G1Affine, Challenge255<_>>::init(&proof[..]); + let strategy = SingleStrategy::new(&general_params); - verify_proof( + verify_proof::< + KZGCommitmentScheme, + VerifierSHPLONK<'_, Bn256>, + Challenge255, + Blake2bRead<&[u8], G1Affine, Challenge255>, + SingleStrategy<'_, Bn256>, + >( &verifier_params, pk.get_vk(), strategy, diff --git a/circuit-benchmarks/src/evm_circuit.rs b/circuit-benchmarks/src/evm_circuit.rs index 4d27af2061..5b8b1395f8 100644 --- a/circuit-benchmarks/src/evm_circuit.rs +++ b/circuit-benchmarks/src/evm_circuit.rs @@ -57,13 +57,17 @@ impl Circuit for TestCircuit { #[cfg(test)] mod evm_circ_benches { use super::*; - use crate::bench_params::DEGREE; use ark_std::{end_timer, start_timer}; - use halo2_proofs::plonk::{create_proof, keygen_pk, keygen_vk, verify_proof, SingleVerifier}; + use halo2_proofs::plonk::{create_proof, keygen_pk, keygen_vk, verify_proof}; + use halo2_proofs::poly::kzg::commitment::{KZGCommitmentScheme, ParamsKZG, ParamsVerifierKZG}; + use halo2_proofs::poly::kzg::multiopen::{ProverSHPLONK, VerifierSHPLONK}; + use halo2_proofs::poly::kzg::strategy::SingleStrategy; use halo2_proofs::{ - pairing::bn256::{Bn256, Fr, G1Affine}, - poly::commitment::{Params, ParamsVerifier}, - transcript::{Blake2bRead, Blake2bWrite, Challenge255}, + halo2curves::bn256::{Bn256, Fr, G1Affine}, + poly::commitment::ParamsProver, + transcript::{ + Blake2bRead, Blake2bWrite, Challenge255, TranscriptReadBuffer, TranscriptWriterBuffer, + }, }; use rand::SeedableRng; use rand_xorshift::XorShiftRng; @@ -78,7 +82,7 @@ mod evm_circ_benches { .expect("Cannot parse DEGREE env var as u32"); let circuit = TestCircuit::::default(); - let rng = XorShiftRng::from_seed([ + let mut rng = XorShiftRng::from_seed([ 0x59, 0x62, 0xbe, 0x5d, 0x76, 0x3d, 0x31, 0x8d, 0x17, 0xdb, 0x37, 0x32, 0x54, 0x06, 0xbc, 0xe5, ]); @@ -86,19 +90,27 @@ mod evm_circ_benches { // Bench setup generation let setup_message = format!("Setup generation with degree = {}", degree); let start1 = start_timer!(|| setup_message); - let general_params: Params = Params::::unsafe_setup::(degree); + let general_params = ParamsKZG::::setup(degree, &mut rng); + let verifier_params: ParamsVerifierKZG = general_params.verifier_params().clone(); end_timer!(start1); - let vk = keygen_vk(&general_params, &circuit).unwrap(); - let pk = keygen_pk(&general_params, vk, &circuit).unwrap(); - - // Prove - let mut transcript = Blake2bWrite::<_, _, Challenge255<_>>::init(vec![]); + // Initialize the proving key + let vk = keygen_vk(&general_params, &circuit).expect("keygen_vk should not fail"); + let pk = keygen_pk(&general_params, vk, &circuit).expect("keygen_pk should not fail"); + // Create a proof + let mut transcript = Blake2bWrite::<_, G1Affine, Challenge255<_>>::init(vec![]); // Bench proof generation time - let proof_message = format!("EVM Proof generation with {} degree", degree); + let proof_message = format!("EVM circuit Proof generation with {} rows", degree); let start2 = start_timer!(|| proof_message); - create_proof( + create_proof::< + KZGCommitmentScheme, + ProverSHPLONK<'_, Bn256>, + Challenge255, + XorShiftRng, + Blake2bWrite, G1Affine, Challenge255>, + TestCircuit, + >( &general_params, &pk, &[circuit], @@ -106,25 +118,29 @@ mod evm_circ_benches { rng, &mut transcript, ) - .unwrap(); + .expect("proof generation should not fail"); let proof = transcript.finalize(); end_timer!(start2); - // Verify - let verifier_params: ParamsVerifier = general_params.verifier(DEGREE * 2).unwrap(); - let mut verifier_transcript = Blake2bRead::<_, _, Challenge255<_>>::init(&proof[..]); - let strategy = SingleVerifier::new(&verifier_params); - // Bench verification time - let start3 = start_timer!(|| "EVM Proof verification"); - verify_proof( + let start3 = start_timer!(|| "EVM circuit Proof verification"); + let mut verifier_transcript = Blake2bRead::<_, G1Affine, Challenge255<_>>::init(&proof[..]); + let strategy = SingleStrategy::new(&general_params); + + verify_proof::< + KZGCommitmentScheme, + VerifierSHPLONK<'_, Bn256>, + Challenge255, + Blake2bRead<&[u8], G1Affine, Challenge255>, + SingleStrategy<'_, Bn256>, + >( &verifier_params, pk.get_vk(), strategy, &[&[]], &mut verifier_transcript, ) - .unwrap(); + .expect("failed to verify bench circuit"); end_timer!(start3); } } diff --git a/circuit-benchmarks/src/keccak_permutation.rs b/circuit-benchmarks/src/keccak_permutation.rs deleted file mode 100644 index 657e299054..0000000000 --- a/circuit-benchmarks/src/keccak_permutation.rs +++ /dev/null @@ -1,152 +0,0 @@ -//! Evm circuit benchmarks - -use eth_types::Field; -use halo2_proofs::{ - circuit::{AssignedCell, Layouter, SimpleFloorPlanner}, - plonk::{Circuit, ConstraintSystem, Error}, -}; -use keccak256::{common::NEXT_INPUTS_LANES, permutation::circuit::KeccakFConfig}; - -#[derive(Default, Clone)] -struct KeccakRoundTestCircuit { - in_state: [F; 25], - next_mixing: Option<[F; NEXT_INPUTS_LANES]>, -} - -impl Circuit for KeccakRoundTestCircuit { - type Config = KeccakFConfig; - type FloorPlanner = SimpleFloorPlanner; - - fn without_witnesses(&self) -> Self { - Self::default() - } - - fn configure(meta: &mut ConstraintSystem) -> Self::Config { - Self::Config::configure(meta) - } - - fn synthesize( - &self, - mut config: Self::Config, - mut layouter: impl Layouter, - ) -> Result<(), Error> { - // Load the table - config.load(&mut layouter)?; - let offset: usize = 0; - - let in_state = layouter.assign_region( - || "Keccak round witnes & flag assignment", - |mut region| { - // Witness `state` - let in_state: [AssignedCell; 25] = { - let mut state: Vec> = Vec::with_capacity(25); - for &val in self.in_state.iter() { - let cell = region.assign_advice( - || "witness input state", - config.advice, - offset, - || Ok(val), - )?; - state.push(cell) - } - state.try_into().unwrap() - }; - Ok(in_state) - }, - )?; - - config.assign_all(&mut layouter, in_state, self.next_mixing)?; - Ok(()) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use ark_std::{end_timer, start_timer}; - use halo2_proofs::plonk::{create_proof, keygen_pk, keygen_vk, verify_proof, SingleVerifier}; - use halo2_proofs::{ - pairing::bn256::{Bn256, Fr, G1Affine}, - poly::commitment::{Params, ParamsVerifier}, - transcript::{Blake2bRead, Blake2bWrite, Challenge255}, - }; - use itertools::Itertools; - use keccak256::common::PERMUTATION; - use keccak256::{arith_helpers::*, common::State, gate_helpers::biguint_to_f}; - use rand::SeedableRng; - use rand_xorshift::XorShiftRng; - use std::env::var; - - #[test] - fn bench_keccak_round() { - let in_state: State = [ - [1, 0, 0, 0, 0], - [0, 0, 0, 0, 0], - [0, 0, 0, 0, 0], - [0, 0, 0, 0, 0], - [0, 0, 0, 0, 0], - ]; - - let mut in_state_biguint = StateBigInt::default(); - - // Generate in_state as `[Fr;25]` - let mut in_state_fp: [Fr; 25] = [Fr::zero(); 25]; - for (x, y) in (0..5).cartesian_product(0..5) { - in_state_fp[5 * x + y] = biguint_to_f(&convert_b2_to_b13(in_state[x][y])); - in_state_biguint[(x, y)] = convert_b2_to_b13(in_state[x][y]); - } - - // Build the circuit - let circuit = KeccakRoundTestCircuit:: { - in_state: in_state_fp, - next_mixing: None, - }; - - let degree: u32 = var("DEGREE") - .expect("No DEGREE env var was provided") - .parse() - .expect("Cannot parse DEGREE env var as u32"); - - let rng = XorShiftRng::from_seed([ - 0x59, 0x62, 0xbe, 0x5d, 0x76, 0x3d, 0x31, 0x8d, 0x17, 0xdb, 0x37, 0x32, 0x54, 0x06, - 0xbc, 0xe5, - ]); - - // Bench setup generation - let setup_message = format!("Setup generation with degree = {}", degree); - let start1 = start_timer!(|| setup_message); - let general_params: Params = Params::::unsafe_setup::(degree); - end_timer!(start1); - - let vk = keygen_vk(&general_params, &circuit).unwrap(); - let pk = keygen_pk(&general_params, vk, &circuit).unwrap(); - - // Prove - let mut transcript = Blake2bWrite::<_, _, Challenge255<_>>::init(vec![]); - - // Bench proof generation time - let proof_message = format!("Keccak Proof generation with {} degree", degree); - let start2 = start_timer!(|| proof_message); - create_proof(&general_params, &pk, &[circuit], &[], rng, &mut transcript).unwrap(); - let proof = transcript.finalize(); - end_timer!(start2); - - // Verify - let verifier_params: ParamsVerifier = - general_params.verifier(PERMUTATION * 2).unwrap(); - let mut verifier_transcript = Blake2bRead::<_, _, Challenge255<_>>::init(&proof[..]); - let strategy = SingleVerifier::new(&verifier_params); - - // Bench verification time - let start3 = start_timer!(|| "Keccak Proof verification"); - verify_proof( - &verifier_params, - pk.get_vk(), - strategy, - &[], - &mut verifier_transcript, - ) - .unwrap(); - end_timer!(start3); - } -} diff --git a/circuit-benchmarks/src/lib.rs b/circuit-benchmarks/src/lib.rs index 18266bdc15..a96a6f3fb1 100644 --- a/circuit-benchmarks/src/lib.rs +++ b/circuit-benchmarks/src/lib.rs @@ -8,10 +8,6 @@ pub mod state_circuit; #[cfg(feature = "benches")] pub mod bench_params; -#[cfg(test)] -#[cfg(feature = "benches")] -pub mod keccak_permutation; - #[cfg(test)] #[cfg(feature = "benches")] pub mod tx_circuit; diff --git a/circuit-benchmarks/src/packed_keccak.rs b/circuit-benchmarks/src/packed_keccak.rs index 032290332a..934df9b8c5 100644 --- a/circuit-benchmarks/src/packed_keccak.rs +++ b/circuit-benchmarks/src/packed_keccak.rs @@ -3,11 +3,16 @@ #[cfg(test)] mod tests { use ark_std::{end_timer, start_timer}; - use halo2_proofs::plonk::{create_proof, keygen_pk, keygen_vk, verify_proof, SingleVerifier}; + use halo2_proofs::plonk::{create_proof, keygen_pk, keygen_vk, verify_proof}; + use halo2_proofs::poly::kzg::commitment::{KZGCommitmentScheme, ParamsKZG, ParamsVerifierKZG}; + use halo2_proofs::poly::kzg::multiopen::{ProverSHPLONK, VerifierSHPLONK}; + use halo2_proofs::poly::kzg::strategy::SingleStrategy; use halo2_proofs::{ - pairing::bn256::{Bn256, G1Affine}, - poly::commitment::{Params, ParamsVerifier}, - transcript::{Blake2bRead, Blake2bWrite, Challenge255}, + halo2curves::bn256::{Bn256, Fr, G1Affine}, + poly::commitment::ParamsProver, + transcript::{ + Blake2bRead, Blake2bWrite, Challenge255, TranscriptReadBuffer, TranscriptWriterBuffer, + }, }; use rand::SeedableRng; use rand_xorshift::XorShiftRng; @@ -30,7 +35,7 @@ mod tests { circuit.generate_witness(&inputs); // Initialize the polynomial commitment parameters - let rng = XorShiftRng::from_seed([ + let mut rng = XorShiftRng::from_seed([ 0x59, 0x62, 0xbe, 0x5d, 0x76, 0x3d, 0x31, 0x8d, 0x17, 0xdb, 0x37, 0x32, 0x54, 0x06, 0xbc, 0xe5, ]); @@ -38,21 +43,27 @@ mod tests { // Bench setup generation let setup_message = format!("Setup generation with degree = {}", degree); let start1 = start_timer!(|| setup_message); - let general_params: Params = Params::::unsafe_setup::(degree); - let verifier_params: ParamsVerifier = - general_params.verifier(degree as usize * 2).unwrap(); + let general_params = ParamsKZG::::setup(degree, &mut rng); + let verifier_params: ParamsVerifierKZG = general_params.verifier_params().clone(); end_timer!(start1); // Initialize the proving key let vk = keygen_vk(&general_params, &circuit).expect("keygen_vk should not fail"); let pk = keygen_pk(&general_params, vk, &circuit).expect("keygen_pk should not fail"); // Create a proof - let mut transcript = Blake2bWrite::<_, _, Challenge255<_>>::init(vec![]); + let mut transcript = Blake2bWrite::<_, G1Affine, Challenge255<_>>::init(vec![]); // Bench proof generation time let proof_message = format!("Packed Keccak Proof generation with {} rows", degree); let start2 = start_timer!(|| proof_message); - create_proof( + create_proof::< + KZGCommitmentScheme, + ProverSHPLONK<'_, Bn256>, + Challenge255, + XorShiftRng, + Blake2bWrite, G1Affine, Challenge255>, + KeccakPackedCircuit, + >( &general_params, &pk, &[circuit], @@ -65,11 +76,17 @@ mod tests { end_timer!(start2); // Bench verification time - let start3 = start_timer!(|| "Keccak Proof verification"); - let mut verifier_transcript = Blake2bRead::<_, _, Challenge255<_>>::init(&proof[..]); - let strategy = SingleVerifier::new(&verifier_params); + let start3 = start_timer!(|| "Packed Keccak Proof verification"); + let mut verifier_transcript = Blake2bRead::<_, G1Affine, Challenge255<_>>::init(&proof[..]); + let strategy = SingleStrategy::new(&general_params); - verify_proof( + verify_proof::< + KZGCommitmentScheme, + VerifierSHPLONK<'_, Bn256>, + Challenge255, + Blake2bRead<&[u8], G1Affine, Challenge255>, + SingleStrategy<'_, Bn256>, + >( &verifier_params, pk.get_vk(), strategy, diff --git a/circuit-benchmarks/src/packed_multi_keccak.rs b/circuit-benchmarks/src/packed_multi_keccak.rs index a8b84c1321..df86436ad0 100644 --- a/circuit-benchmarks/src/packed_multi_keccak.rs +++ b/circuit-benchmarks/src/packed_multi_keccak.rs @@ -3,11 +3,16 @@ #[cfg(test)] mod tests { use ark_std::{end_timer, start_timer}; - use halo2_proofs::plonk::{create_proof, keygen_pk, keygen_vk, verify_proof, SingleVerifier}; + use halo2_proofs::plonk::{create_proof, keygen_pk, keygen_vk, verify_proof}; + use halo2_proofs::poly::kzg::commitment::{KZGCommitmentScheme, ParamsKZG, ParamsVerifierKZG}; + use halo2_proofs::poly::kzg::multiopen::{ProverSHPLONK, VerifierSHPLONK}; + use halo2_proofs::poly::kzg::strategy::SingleStrategy; use halo2_proofs::{ - pairing::bn256::{Bn256, G1Affine}, - poly::commitment::{Params, ParamsVerifier}, - transcript::{Blake2bRead, Blake2bWrite, Challenge255}, + halo2curves::bn256::{Bn256, Fr, G1Affine}, + poly::commitment::ParamsProver, + transcript::{ + Blake2bRead, Blake2bWrite, Challenge255, TranscriptReadBuffer, TranscriptWriterBuffer, + }, }; use rand::SeedableRng; use rand_xorshift::XorShiftRng; @@ -30,7 +35,7 @@ mod tests { circuit.generate_witness(&inputs); // Initialize the polynomial commitment parameters - let rng = XorShiftRng::from_seed([ + let mut rng = XorShiftRng::from_seed([ 0x59, 0x62, 0xbe, 0x5d, 0x76, 0x3d, 0x31, 0x8d, 0x17, 0xdb, 0x37, 0x32, 0x54, 0x06, 0xbc, 0xe5, ]); @@ -38,21 +43,27 @@ mod tests { // Bench setup generation let setup_message = format!("Setup generation with degree = {}", degree); let start1 = start_timer!(|| setup_message); - let general_params: Params = Params::::unsafe_setup::(degree); - let verifier_params: ParamsVerifier = - general_params.verifier(degree as usize * 2).unwrap(); + let general_params = ParamsKZG::::setup(degree, &mut rng); + let verifier_params: ParamsVerifierKZG = general_params.verifier_params().clone(); end_timer!(start1); // Initialize the proving key let vk = keygen_vk(&general_params, &circuit).expect("keygen_vk should not fail"); let pk = keygen_pk(&general_params, vk, &circuit).expect("keygen_pk should not fail"); // Create a proof - let mut transcript = Blake2bWrite::<_, _, Challenge255<_>>::init(vec![]); + let mut transcript = Blake2bWrite::<_, G1Affine, Challenge255<_>>::init(vec![]); // Bench proof generation time - let proof_message = format!("Packed Keccak Multi Proof generation with {} rows", degree); + let proof_message = format!("Packed Multi-Keccak Proof generation with {} rows", degree); let start2 = start_timer!(|| proof_message); - create_proof( + create_proof::< + KZGCommitmentScheme, + ProverSHPLONK<'_, Bn256>, + Challenge255, + XorShiftRng, + Blake2bWrite, G1Affine, Challenge255>, + KeccakPackedCircuit, + >( &general_params, &pk, &[circuit], @@ -65,11 +76,17 @@ mod tests { end_timer!(start2); // Bench verification time - let start3 = start_timer!(|| "Keccak Proof verification"); - let mut verifier_transcript = Blake2bRead::<_, _, Challenge255<_>>::init(&proof[..]); - let strategy = SingleVerifier::new(&verifier_params); + let start3 = start_timer!(|| "Packed Multi-Keccak Proof verification"); + let mut verifier_transcript = Blake2bRead::<_, G1Affine, Challenge255<_>>::init(&proof[..]); + let strategy = SingleStrategy::new(&general_params); - verify_proof( + verify_proof::< + KZGCommitmentScheme, + VerifierSHPLONK<'_, Bn256>, + Challenge255, + Blake2bRead<&[u8], G1Affine, Challenge255>, + SingleStrategy<'_, Bn256>, + >( &verifier_params, pk.get_vk(), strategy, diff --git a/circuit-benchmarks/src/state_circuit.rs b/circuit-benchmarks/src/state_circuit.rs index cb381b9167..910af65f9e 100644 --- a/circuit-benchmarks/src/state_circuit.rs +++ b/circuit-benchmarks/src/state_circuit.rs @@ -2,54 +2,71 @@ #[cfg(test)] mod tests { - use crate::bench_params::DEGREE; use ark_std::{end_timer, start_timer}; - use halo2_proofs::plonk::{create_proof, keygen_pk, keygen_vk, verify_proof, SingleVerifier}; + use halo2_proofs::plonk::{create_proof, keygen_pk, keygen_vk, verify_proof}; + use halo2_proofs::poly::kzg::commitment::{KZGCommitmentScheme, ParamsKZG, ParamsVerifierKZG}; + use halo2_proofs::poly::kzg::multiopen::{ProverSHPLONK, VerifierSHPLONK}; + use halo2_proofs::poly::kzg::strategy::SingleStrategy; use halo2_proofs::{ - pairing::bn256::{Bn256, Fr, G1Affine}, - poly::commitment::{Params, ParamsVerifier}, - transcript::{Blake2bRead, Blake2bWrite, Challenge255}, + halo2curves::bn256::{Bn256, Fr, G1Affine}, + poly::commitment::ParamsProver, + transcript::{ + Blake2bRead, Blake2bWrite, Challenge255, TranscriptReadBuffer, TranscriptWriterBuffer, + }, }; use rand::SeedableRng; use rand_xorshift::XorShiftRng; + use std::env::var; use zkevm_circuits::evm_circuit::witness::RwMap; use zkevm_circuits::state_circuit::StateCircuit; #[cfg_attr(not(feature = "benches"), ignore)] #[test] fn bench_state_circuit_prover() { + let degree: u32 = var("DEGREE") + .expect("No DEGREE env var was provided") + .parse() + .expect("Cannot parse DEGREE env var as u32"); + let empty_circuit = StateCircuit::::new(Fr::default(), RwMap::default(), 1 << 16); // Initialize the polynomial commitment parameters - let rng = XorShiftRng::from_seed([ + let mut rng = XorShiftRng::from_seed([ 0x59, 0x62, 0xbe, 0x5d, 0x76, 0x3d, 0x31, 0x8d, 0x17, 0xdb, 0x37, 0x32, 0x54, 0x06, 0xbc, 0xe5, ]); // Bench setup generation - let setup_message = format!("Setup generation with degree = {}", DEGREE); + let setup_message = format!("Setup generation with degree = {}", degree); let start1 = start_timer!(|| setup_message); - let general_params: Params = - Params::::unsafe_setup::(DEGREE.try_into().unwrap()); - let verifier_params: ParamsVerifier = general_params.verifier(DEGREE * 2).unwrap(); + let general_params = ParamsKZG::::setup(degree, &mut rng); + let verifier_params: ParamsVerifierKZG = general_params.verifier_params().clone(); end_timer!(start1); // Initialize the proving key let vk = keygen_vk(&general_params, &empty_circuit).expect("keygen_vk should not fail"); let pk = keygen_pk(&general_params, vk, &empty_circuit).expect("keygen_pk should not fail"); // Create a proof - let mut transcript = Blake2bWrite::<_, _, Challenge255<_>>::init(vec![]); + let mut transcript = Blake2bWrite::<_, G1Affine, Challenge255<_>>::init(vec![]); let instance = empty_circuit.instance(); let instances: Vec<&[Fr]> = instance.iter().map(|v| v.as_slice()).collect(); + // Bench proof generation time - let proof_message = format!("State Proof generation with {} degree", DEGREE); + let proof_message = format!("State Circuit Proof generation with {} rows", degree); let start2 = start_timer!(|| proof_message); - create_proof( + create_proof::< + KZGCommitmentScheme, + ProverSHPLONK<'_, Bn256>, + Challenge255, + XorShiftRng, + Blake2bWrite, G1Affine, Challenge255>, + StateCircuit, + >( &general_params, &pk, &[empty_circuit], - &[instances.as_slice()], + &[&instances], rng, &mut transcript, ) @@ -58,15 +75,21 @@ mod tests { end_timer!(start2); // Bench verification time - let start3 = start_timer!(|| "State Proof verification"); - let mut verifier_transcript = Blake2bRead::<_, _, Challenge255<_>>::init(&proof[..]); - let strategy = SingleVerifier::new(&verifier_params); + let start3 = start_timer!(|| "State Circuit Proof verification"); + let mut verifier_transcript = Blake2bRead::<_, G1Affine, Challenge255<_>>::init(&proof[..]); + let strategy = SingleStrategy::new(&general_params); - verify_proof( + verify_proof::< + KZGCommitmentScheme, + VerifierSHPLONK<'_, Bn256>, + Challenge255, + Blake2bRead<&[u8], G1Affine, Challenge255>, + SingleStrategy<'_, Bn256>, + >( &verifier_params, pk.get_vk(), strategy, - &[instances.as_slice()], + &[&instances], &mut verifier_transcript, ) .expect("failed to verify bench circuit"); diff --git a/circuit-benchmarks/src/super_circuit.rs b/circuit-benchmarks/src/super_circuit.rs index d4cf1acc20..0b903e8c87 100644 --- a/circuit-benchmarks/src/super_circuit.rs +++ b/circuit-benchmarks/src/super_circuit.rs @@ -2,27 +2,37 @@ #[cfg(test)] mod tests { - use crate::bench_params::DEGREE; use ark_std::{end_timer, start_timer}; - use eth_types::{address, bytecode, geth_types::GethData, Word}; - use ethers_signers::{LocalWallet, Signer}; - use halo2_proofs::plonk::{create_proof, keygen_pk, keygen_vk, verify_proof, SingleVerifier}; + use eth_types::geth_types::GethData; + use eth_types::{address, bytecode, Word}; + use ethers_signers::LocalWallet; + use ethers_signers::Signer; + use halo2_proofs::plonk::{create_proof, keygen_pk, keygen_vk, verify_proof}; + use halo2_proofs::poly::kzg::commitment::{KZGCommitmentScheme, ParamsKZG, ParamsVerifierKZG}; + use halo2_proofs::poly::kzg::multiopen::{ProverSHPLONK, VerifierSHPLONK}; + use halo2_proofs::poly::kzg::strategy::SingleStrategy; use halo2_proofs::{ - pairing::bn256::{Bn256, G1Affine}, - poly::commitment::{Params, ParamsVerifier}, - transcript::{Blake2bRead, Blake2bWrite, Challenge255}, + halo2curves::bn256::{Bn256, Fr, G1Affine}, + poly::commitment::ParamsProver, + transcript::{ + Blake2bRead, Blake2bWrite, Challenge255, TranscriptReadBuffer, TranscriptWriterBuffer, + }, }; use mock::{TestContext, MOCK_CHAIN_ID}; use rand::SeedableRng; use rand_chacha::ChaChaRng; use std::collections::HashMap; + use std::env::var; use zkevm_circuits::super_circuit::SuperCircuit; - use halo2_proofs::pairing::bn256::Fr; - #[cfg_attr(not(feature = "benches"), ignore)] #[test] fn bench_super_circuit_prover() { + let degree: u32 = var("DEGREE") + .expect("No DEGREE env var was provided") + .parse() + .expect("Cannot parse DEGREE env var as u32"); + let mut rng = ChaChaRng::seed_from_u64(2); let chain_id = (*MOCK_CHAIN_ID).as_u64(); @@ -66,25 +76,29 @@ mod tests { let instance_refs: Vec<&[Fr]> = instance.iter().map(|v| &v[..]).collect(); // Bench setup generation - let setup_message = format!("Setup generation with degree = {}", DEGREE); + let setup_message = format!("Setup generation with degree = {}", degree); let start1 = start_timer!(|| setup_message); - let general_params: Params = - Params::::unsafe_setup::(DEGREE.try_into().unwrap()); - let verifier_params: ParamsVerifier = - general_params.verifier((1 << DEGREE) - 64).unwrap(); + let general_params = ParamsKZG::::setup(degree, &mut rng); + let verifier_params: ParamsVerifierKZG = general_params.verifier_params().clone(); end_timer!(start1); // Initialize the proving key let vk = keygen_vk(&general_params, &circuit).expect("keygen_vk should not fail"); let pk = keygen_pk(&general_params, vk, &circuit).expect("keygen_pk should not fail"); - // Create a proof - let mut transcript = Blake2bWrite::<_, _, Challenge255<_>>::init(vec![]); + let mut transcript = Blake2bWrite::<_, G1Affine, Challenge255<_>>::init(vec![]); // Bench proof generation time - let proof_message = format!("State Proof generation with {} degree", DEGREE); + let proof_message = format!("SuperCircuit Proof generation with {} rows", degree); let start2 = start_timer!(|| proof_message); - create_proof( + create_proof::< + KZGCommitmentScheme, + ProverSHPLONK<'_, Bn256>, + Challenge255, + ChaChaRng, + Blake2bWrite, G1Affine, Challenge255>, + SuperCircuit, + >( &general_params, &pk, &[circuit], @@ -97,11 +111,17 @@ mod tests { end_timer!(start2); // Bench verification time - let start3 = start_timer!(|| "State Proof verification"); - let mut verifier_transcript = Blake2bRead::<_, _, Challenge255<_>>::init(&proof[..]); - let strategy = SingleVerifier::new(&verifier_params); - - verify_proof( + let start3 = start_timer!(|| "SuperCircuit Proof verification"); + let mut verifier_transcript = Blake2bRead::<_, G1Affine, Challenge255<_>>::init(&proof[..]); + let strategy = SingleStrategy::new(&general_params); + + verify_proof::< + KZGCommitmentScheme, + VerifierSHPLONK<'_, Bn256>, + Challenge255, + Blake2bRead<&[u8], G1Affine, Challenge255>, + SingleStrategy<'_, Bn256>, + >( &verifier_params, pk.get_vk(), strategy, diff --git a/circuit-benchmarks/src/tx_circuit.rs b/circuit-benchmarks/src/tx_circuit.rs index bab78a32fb..ed92e1da7c 100644 --- a/circuit-benchmarks/src/tx_circuit.rs +++ b/circuit-benchmarks/src/tx_circuit.rs @@ -2,25 +2,31 @@ #[cfg(test)] mod tests { - use crate::bench_params::DEGREE; use ark_std::{end_timer, start_timer}; use env_logger::Env; - use group::{Curve, Group}; - use halo2_proofs::arithmetic::{BaseExt, CurveAffine}; - use halo2_proofs::plonk::{create_proof, keygen_pk, keygen_vk, verify_proof, SingleVerifier}; + use halo2_proofs::halo2curves::CurveAffine; + use halo2_proofs::plonk::{create_proof, keygen_pk, keygen_vk, verify_proof}; + use halo2_proofs::poly::kzg::commitment::{KZGCommitmentScheme, ParamsKZG, ParamsVerifierKZG}; + use halo2_proofs::poly::kzg::multiopen::{ProverSHPLONK, VerifierSHPLONK}; + use halo2_proofs::poly::kzg::strategy::SingleStrategy; use halo2_proofs::{ - pairing::bn256::{Bn256, Fr, G1Affine}, - poly::commitment::{Params, ParamsVerifier}, - transcript::{Blake2bRead, Blake2bWrite, Challenge255}, + arithmetic::FieldExt, + halo2curves::bn256::{Bn256, Fr, G1Affine}, + poly::commitment::ParamsProver, + transcript::{ + Blake2bRead, Blake2bWrite, Challenge255, TranscriptReadBuffer, TranscriptWriterBuffer, + }, }; use rand::SeedableRng; use rand_chacha::ChaCha20Rng; - use secp256k1::Secp256k1Affine; use std::marker::PhantomData; use zkevm_circuits::tx_circuit::{ sign_verify::{SignVerifyChip, POW_RAND_SIZE, VERIF_HEIGHT}, - TxCircuit, + Curve, TxCircuit, }; + use zkevm_circuits::tx_circuit::{Group, Secp256k1Affine}; + + use crate::bench_params::DEGREE; #[cfg_attr(not(feature = "benches"), ignore)] #[test] @@ -58,32 +64,34 @@ mod tests { }; // Bench setup generation - let setup_message = format!( - "Setup generation with degree = {} (MAX_TXS = {})", - DEGREE, MAX_TXS - ); + let setup_message = format!("Setup generation with degree = {}", DEGREE); let start1 = start_timer!(|| setup_message); - let general_params: Params = - Params::::unsafe_setup::(DEGREE.try_into().unwrap()); - let verifier_params: ParamsVerifier = - general_params.verifier(MAX_TXS * VERIF_HEIGHT).unwrap(); + let general_params = ParamsKZG::::setup(DEGREE as u32, &mut rng); + let verifier_params: ParamsVerifierKZG = general_params.verifier_params().clone(); end_timer!(start1); // Initialize the proving key let vk = keygen_vk(&general_params, &circuit).expect("keygen_vk should not fail"); let pk = keygen_pk(&general_params, vk, &circuit).expect("keygen_pk should not fail"); // Create a proof - let mut transcript = Blake2bWrite::<_, _, Challenge255<_>>::init(vec![]); + let mut transcript = Blake2bWrite::<_, G1Affine, Challenge255<_>>::init(vec![]); + let instance_slices: Vec<&[Fr]> = instance.iter().map(|v| &v[..]).collect(); // Bench proof generation time - let proof_message = format!("Tx Proof generation with {} degree", DEGREE); + let proof_message = format!("Packed Multi-Keccak Proof generation with {} rows", DEGREE); let start2 = start_timer!(|| proof_message); - let instance_slices: Vec<&[Fr]> = instance.iter().map(|v| &v[..]).collect(); - create_proof( + create_proof::< + KZGCommitmentScheme, + ProverSHPLONK<'_, Bn256>, + Challenge255, + ChaCha20Rng, + Blake2bWrite, G1Affine, Challenge255>, + TxCircuit, + >( &general_params, &pk, &[circuit], - &[&instance_slices[..]], + &[&instance_slices], rng, &mut transcript, ) @@ -92,15 +100,21 @@ mod tests { end_timer!(start2); // Bench verification time - let start3 = start_timer!(|| "Tx Proof verification"); - let mut verifier_transcript = Blake2bRead::<_, _, Challenge255<_>>::init(&proof[..]); - let strategy = SingleVerifier::new(&verifier_params); + let start3 = start_timer!(|| "Packed Multi-Keccak Proof verification"); + let mut verifier_transcript = Blake2bRead::<_, G1Affine, Challenge255<_>>::init(&proof[..]); + let strategy = SingleStrategy::new(&general_params); - verify_proof( + verify_proof::< + KZGCommitmentScheme, + VerifierSHPLONK<'_, Bn256>, + Challenge255, + Blake2bRead<&[u8], G1Affine, Challenge255>, + SingleStrategy<'_, Bn256>, + >( &verifier_params, pk.get_vk(), strategy, - &[&instance_slices[..]], + &[&instance_slices], &mut verifier_transcript, ) .expect("failed to verify bench circuit"); diff --git a/eth-types/Cargo.toml b/eth-types/Cargo.toml index 0709de9e70..8a4f2547ad 100644 --- a/eth-types/Cargo.toml +++ b/eth-types/Cargo.toml @@ -10,18 +10,15 @@ ethers-core = "0.6" ethers-signers = "0.6" hex = "0.4" lazy_static = "1.4" -halo2_proofs = { version = "0.1.0-beta.1" } +halo2_proofs = { git = "https://github.com/privacy-scaling-explorations/halo2.git", tag = "v2022_08_19" } regex = "1.5.4" serde = {version = "1.0.130", features = ["derive"] } serde_json = "1.0.66" uint = "0.9.1" itertools = "0.10" -secp256k1 = { git = "https://github.com/privacy-scaling-explorations/halo2wrong", tag = "v2022_06_03", features = ["kzg"] } libsecp256k1 = "0.7" subtle = "2.4" sha3 = "0.10" -ff = "0.11" num = "0.4" -group = "0.11" num-bigint = { version = "0.4" } diff --git a/eth-types/src/geth_types.rs b/eth-types/src/geth_types.rs index 9d9205758e..7565d28279 100644 --- a/eth-types/src/geth_types.rs +++ b/eth-types/src/geth_types.rs @@ -8,7 +8,7 @@ use crate::{ use ethers_core::types::TransactionRequest; use ethers_core::utils::keccak256; use ethers_signers::{LocalWallet, Signer}; -use ff::PrimeField; +use halo2_proofs::halo2curves::{group::ff::PrimeField, secp256k1}; use num::Integer; use num_bigint::BigUint; use serde::{Serialize, Serializer}; diff --git a/eth-types/src/lib.rs b/eth-types/src/lib.rs index 5ad2c4ab57..57283c3a7d 100644 --- a/eth-types/src/lib.rs +++ b/eth-types/src/lib.rs @@ -26,7 +26,7 @@ pub use bytecode::Bytecode; pub use error::Error; use halo2_proofs::{ arithmetic::{Field as Halo2Field, FieldExt}, - pairing::{ + halo2curves::{ bn256::{Fq, Fr}, group::ff::PrimeField, }, diff --git a/eth-types/src/sign_types.rs b/eth-types/src/sign_types.rs index 0611479f99..f6bee6980b 100644 --- a/eth-types/src/sign_types.rs +++ b/eth-types/src/sign_types.rs @@ -1,13 +1,19 @@ //! secp256k1 signature types and helper functions. use crate::{ToBigEndian, Word}; -use ff::PrimeField; -use group::{ff::Field as GroupField, prime::PrimeCurveAffine, Curve, GroupEncoding}; -use halo2_proofs::arithmetic::{BaseExt, Coordinates, CurveAffine}; +use halo2_proofs::{ + arithmetic::{CurveAffine, FieldExt}, + halo2curves::{ + group::{ + ff::{Field as GroupField, PrimeField}, + Curve, + }, + secp256k1::{self, Secp256k1Affine}, + Coordinates, + }, +}; use lazy_static::lazy_static; use num_bigint::BigUint; -use secp256k1::Secp256k1Affine; -use std::io::Cursor; use subtle::CtOption; /// Do a secp256k1 signature with a given randomness value. @@ -24,8 +30,8 @@ pub fn sign( .expect("point is the identity") .x(); - let x_repr = &mut Vec::with_capacity(32); - x.write(x_repr).expect("cannot write bytes to array"); + let x_repr = &mut vec![0u8; 32]; + x_repr.copy_from_slice(x.to_bytes().as_slice()); let mut x_bytes = [0u8; 64]; x_bytes[..32].copy_from_slice(&x_repr[..]); @@ -100,10 +106,18 @@ pub fn recover_pk( let pk = libsecp256k1::recover(&msg_hash, &signature, &recovery_id)?; let pk_be = pk.serialize(); let pk_le = pk_bytes_swap_endianness(&pk_be[1..]); - let mut pk_bytes = secp256k1::Serialized::default(); - pk_bytes.as_mut().copy_from_slice(&pk_le[..]); - let pk = Secp256k1Affine::from_bytes(&pk_bytes); - ct_option_ok_or(pk, libsecp256k1::Error::InvalidPublicKey) + let x = ct_option_ok_or( + secp256k1::Fp::from_bytes(pk_le[..32].try_into().unwrap()), + libsecp256k1::Error::InvalidPublicKey, + )?; + let y = ct_option_ok_or( + secp256k1::Fp::from_bytes(pk_le[32..].try_into().unwrap()), + libsecp256k1::Error::InvalidPublicKey, + )?; + ct_option_ok_or( + Secp256k1Affine::from_xy(x, y), + libsecp256k1::Error::InvalidPublicKey, + ) } lazy_static! { @@ -133,13 +147,7 @@ pub fn pk_bytes_swap_endianness(pk: &[T]) -> [T; 64] { pub fn pk_bytes_le(pk: &Secp256k1Affine) -> [u8; 64] { let pk_coord = Option::>::from(pk.coordinates()).expect("point is the identity"); let mut pk_le = [0u8; 64]; - pk_coord - .x() - .write(&mut Cursor::new(&mut pk_le[..32])) - .expect("cannot write bytes to array"); - pk_coord - .y() - .write(&mut Cursor::new(&mut pk_le[32..])) - .expect("cannot write bytes to array"); + pk_le[..32].copy_from_slice(&pk_coord.x().to_bytes()); + pk_le[32..].copy_from_slice(&pk_coord.y().to_bytes()); pk_le } diff --git a/gadgets/Cargo.toml b/gadgets/Cargo.toml index 244b24f1d3..252614040e 100644 --- a/gadgets/Cargo.toml +++ b/gadgets/Cargo.toml @@ -6,7 +6,7 @@ authors = ["The appliedzkp team"] license = "MIT OR Apache-2.0" [dependencies] -halo2_proofs = { version = "0.1.0-beta.1" } +halo2_proofs = { git = "https://github.com/privacy-scaling-explorations/halo2.git", tag = "v2022_08_19" } sha3 = "0.7.2" eth-types = { path = "../eth-types" } digest = "0.7.6" diff --git a/gadgets/src/binary_number.rs b/gadgets/src/binary_number.rs index 232f54548d..e11ce5fe94 100644 --- a/gadgets/src/binary_number.rs +++ b/gadgets/src/binary_number.rs @@ -5,7 +5,7 @@ use crate::util::{and, not, Expr}; use eth_types::Field; use halo2_proofs::{ - circuit::Region, + circuit::{Region, Value}, plonk::{Advice, Column, ConstraintSystem, Error, Expression, Fixed, VirtualCells}, poly::Rotation, }; @@ -180,7 +180,7 @@ where || format!("binary number {:?}", column), column, offset, - || Ok(F::from(bit)), + || Value::known(F::from(bit)), )?; } Ok(()) diff --git a/gadgets/src/evm_word.rs b/gadgets/src/evm_word.rs index 20cc96134f..5b58ff735a 100644 --- a/gadgets/src/evm_word.rs +++ b/gadgets/src/evm_word.rs @@ -10,7 +10,7 @@ use crate::Variable; use digest::{FixedOutput, Input}; use eth_types::Field; use halo2_proofs::{ - circuit::Region, + circuit::{Region, Value}, plonk::{Advice, Column, ConstraintSystem, Error, Expression, Fixed, Selector}, poly::Rotation, }; @@ -116,7 +116,7 @@ impl WordConfig { || format!("load {}", byte), self.byte_lookup, byte.into(), - || Ok(F::from(byte as u64)), + || Value::known(F::from(byte as u64)), )?; } @@ -130,7 +130,7 @@ impl WordConfig { &self, region: &mut Region<'_, F>, offset: usize, - word: [Option; 32], + word: [Value; 32], ) -> Result, Error> { let mut bytes: Vec> = Vec::with_capacity(32); @@ -143,7 +143,7 @@ impl WordConfig { || format!("assign byte {}", idx), *column, offset, - || byte_field_elem.ok_or(Error::Synthesis), + || byte_field_elem, )?; bytes.push(Variable::new(cell, *byte)); @@ -160,8 +160,7 @@ mod tests { arithmetic::Field as Halo2Field, circuit::SimpleFloorPlanner, dev::{FailureLocation, MockProver, VerifyFailure}, - pairing::bn256::Fr as Fp, - pairing::group::ff::PrimeField, + halo2curves::{bn256::Fr as Fp, group::ff::PrimeField}, plonk::{Circuit, Instance}, }; use rand::SeedableRng; @@ -172,7 +171,7 @@ mod tests { fn evm_word() { #[derive(Default)] struct MyCircuit { - word: [Option; 32], + word: [Value; 32], _marker: PhantomData, } @@ -246,7 +245,7 @@ mod tests { word: word .to_repr() .iter() - .map(|b| Some(*b)) + .map(|b| Value::known(*b)) .collect::>() .try_into() .unwrap(), diff --git a/gadgets/src/is_zero.rs b/gadgets/src/is_zero.rs index abee41d252..2615e036fb 100644 --- a/gadgets/src/is_zero.rs +++ b/gadgets/src/is_zero.rs @@ -5,8 +5,8 @@ //! `1/x` otherwise use halo2_proofs::{ - circuit::{Chip, Region}, - pairing::arithmetic::FieldExt, + arithmetic::FieldExt, + circuit::{Chip, Region, Value}, plonk::{Advice, Column, ConstraintSystem, Error, Expression, VirtualCells}, poly::Rotation, }; @@ -23,7 +23,7 @@ pub trait IsZeroInstruction { &self, region: &mut Region<'_, F>, offset: usize, - value: Option, + value: Value, ) -> Result<(), Error>; } @@ -106,7 +106,7 @@ impl IsZeroInstruction for IsZeroChip { &self, region: &mut Region<'_, F>, offset: usize, - value: Option, + value: Value, ) -> Result<(), Error> { let config = self.config(); @@ -115,7 +115,7 @@ impl IsZeroInstruction for IsZeroChip { || "witness inverse of value", config.value_inv, offset, - || value_invert.ok_or(Error::Synthesis), + || value_invert, )?; Ok(()) @@ -140,9 +140,9 @@ mod test { use super::{IsZeroChip, IsZeroConfig, IsZeroInstruction}; use halo2_proofs::{ arithmetic::FieldExt, - circuit::{Layouter, SimpleFloorPlanner}, + circuit::{Layouter, SimpleFloorPlanner, Value}, dev::MockProver, - pairing::bn256::Fr as Fp, + halo2curves::bn256::Fr as Fp, plonk::{Advice, Circuit, Column, ConstraintSystem, Error, Selector}, poly::Rotation, }; @@ -267,7 +267,7 @@ mod test { || "first row value", config.value, 0, - || Ok(first_value), + || Value::known(first_value), )?; let mut value_prev = first_value; @@ -276,17 +276,17 @@ mod test { || "check", config.check, idx + 1, - || Ok(F::from(*check as u64)), + || Value::known(F::from(*check as u64)), )?; region.assign_advice( || "value", config.value, idx + 1, - || Ok(*value), + || Value::known(*value), )?; config.q_enable.enable(&mut region, idx + 1)?; - chip.assign(&mut region, idx + 1, Some(*value - value_prev))?; + chip.assign(&mut region, idx + 1, Value::known(*value - value_prev))?; value_prev = *value; } @@ -406,23 +406,23 @@ mod test { || "check", config.check, idx + 1, - || Ok(F::from(*check as u64)), + || Value::known(F::from(*check as u64)), )?; region.assign_advice( || "value_a", config.value_a, idx + 1, - || Ok(*value_a), + || Value::known(*value_a), )?; region.assign_advice( || "value_b", config.value_b, idx + 1, - || Ok(*value_b), + || Value::known(*value_b), )?; config.q_enable.enable(&mut region, idx + 1)?; - chip.assign(&mut region, idx + 1, Some(*value_a - *value_b))?; + chip.assign(&mut region, idx + 1, Value::known(*value_a - *value_b))?; } Ok(()) diff --git a/gadgets/src/less_than.rs b/gadgets/src/less_than.rs index dd2dfd0dd6..035e036213 100644 --- a/gadgets/src/less_than.rs +++ b/gadgets/src/less_than.rs @@ -3,7 +3,7 @@ use eth_types::Field; use halo2_proofs::{ arithmetic::FieldExt, - circuit::{Chip, Region}, + circuit::{Chip, Region, Value}, plonk::{Advice, Column, ConstraintSystem, Error, Expression, VirtualCells}, poly::Rotation, }; @@ -105,7 +105,7 @@ impl LtInstruction for LtChip { || "lt chip: lt", config.lt, offset, - || Ok(F::from(lt as u64)), + || Value::known(F::from(lt as u64)), )?; let diff = (lhs - rhs) + (if lt { config.range } else { F::zero() }); @@ -116,7 +116,7 @@ impl LtInstruction for LtChip { || format!("lt chip: diff byte {}", idx), *diff_column, offset, - || Ok(F::from(diff_bytes[idx] as u64)), + || Value::known(F::from(diff_bytes[idx] as u64)), )?; } @@ -143,9 +143,9 @@ mod test { use eth_types::Field; use halo2_proofs::{ arithmetic::FieldExt, - circuit::{Layouter, SimpleFloorPlanner}, + circuit::{Layouter, SimpleFloorPlanner, Value}, dev::MockProver, - pairing::bn256::Fr as Fp, + halo2curves::bn256::Fr as Fp, plonk::{Advice, Circuit, Column, ConstraintSystem, Error, Selector}, poly::Rotation, }; @@ -265,7 +265,7 @@ mod test { || "first row value", config.value, 0, - || Ok(first_value), + || Value::known(first_value), )?; let mut value_prev = first_value; @@ -275,13 +275,13 @@ mod test { || "check", config.check, idx + 1, - || Ok(F::from(*check as u64)), + || Value::known(F::from(*check as u64)), )?; region.assign_advice( || "value", config.value, idx + 1, - || Ok(*value), + || Value::known(*value), )?; chip.assign(&mut region, idx + 1, value_prev, *value)?; @@ -391,19 +391,19 @@ mod test { || "check", config.check, idx + 1, - || Ok(F::from(*check as u64)), + || Value::known(F::from(*check as u64)), )?; region.assign_advice( || "value_a", config.value_a, idx + 1, - || Ok(*value_a), + || Value::known(*value_a), )?; region.assign_advice( || "value_b", config.value_b, idx + 1, - || Ok(*value_b), + || Value::known(*value_b), )?; chip.assign(&mut region, idx + 1, *value_a, *value_b)?; } diff --git a/gadgets/src/lib.rs b/gadgets/src/lib.rs index 6d0d05814f..54865a927e 100644 --- a/gadgets/src/lib.rs +++ b/gadgets/src/lib.rs @@ -19,18 +19,21 @@ pub mod monotone; pub mod util; use eth_types::Field; -use halo2_proofs::{circuit::AssignedCell, plonk::Expression}; +use halo2_proofs::{ + circuit::{AssignedCell, Value}, + plonk::Expression, +}; #[allow(dead_code)] /// An assigned cell in the circuit. #[derive(Clone, Debug)] pub struct Variable { assig_cell: AssignedCell, - value: Option, + value: Value, } impl Variable { - pub(crate) fn new(assig_cell: AssignedCell, value: Option) -> Self { + pub(crate) fn new(assig_cell: AssignedCell, value: Value) -> Self { Self { assig_cell, value } } } diff --git a/gadgets/src/monotone.rs b/gadgets/src/monotone.rs index 824451809f..4110dfb250 100644 --- a/gadgets/src/monotone.rs +++ b/gadgets/src/monotone.rs @@ -2,9 +2,9 @@ //! Monotone gadget helps to check if an advice column is monotonically //! increasing within a range. With strict enabled, it disallows equality of two //! cell. -use halo2_proofs::pairing::arithmetic::FieldExt; +use halo2_proofs::arithmetic::FieldExt; use halo2_proofs::{ - circuit::{Chip, Layouter}, + circuit::{Chip, Layouter, Value}, plonk::{Advice, Column, ConstraintSystem, Error, Expression, Fixed, VirtualCells}, poly::Rotation, }; @@ -73,7 +73,7 @@ impl || "range_table_value", self.config.range_table, idx, - || Ok(F::from(idx as u64)), + || Value::known(F::from(idx as u64)), )?; } @@ -107,7 +107,7 @@ impl Chip #[cfg(test)] mod test { - use super::{MonotoneChip, MonotoneConfig}; + use super::{MonotoneChip, MonotoneConfig, Value}; use halo2_proofs::{ arithmetic::FieldExt, circuit::{Layouter, SimpleFloorPlanner}, @@ -115,7 +115,7 @@ mod test { FailureLocation, MockProver, VerifyFailure::{self, Lookup}, }, - pairing::bn256::Fr as Fp, + halo2curves::bn256::Fr as Fp, plonk::{Advice, Circuit, Column, ConstraintSystem, Error, Selector}, }; use std::marker::PhantomData; @@ -180,7 +180,12 @@ mod test { || "witness", |mut region| { for (idx, value) in values.iter().enumerate() { - region.assign_advice(|| "value", config.value, idx, || Ok(*value))?; + region.assign_advice( + || "value", + config.value, + idx, + || Value::known(*value), + )?; if idx > 0 { config.q_enable.enable(&mut region, idx)?; } diff --git a/integration-tests/Cargo.toml b/integration-tests/Cargo.toml index 49f027af3f..6172f3b29e 100644 --- a/integration-tests/Cargo.toml +++ b/integration-tests/Cargo.toml @@ -19,10 +19,8 @@ url = "2.2.2" pretty_assertions = "1.0.0" log = "0.4.14" env_logger = "0.9" -halo2_proofs = { version = "0.1.0-beta.1" } -ff = "0.11" +halo2_proofs = { git = "https://github.com/privacy-scaling-explorations/halo2.git", tag = "v2022_08_19" } rand_chacha = "0.3" -group = "0.11" paste = "1.0" [dev-dependencies] diff --git a/integration-tests/tests/circuits.rs b/integration-tests/tests/circuits.rs index ec190b195b..355d4a3736 100644 --- a/integration-tests/tests/circuits.rs +++ b/integration-tests/tests/circuits.rs @@ -3,12 +3,13 @@ use bus_mapping::circuit_input_builder::BuilderClient; use bus_mapping::operation::OperationContainer; use eth_types::geth_types; -use group::{Curve, Group}; -use halo2_proofs::arithmetic::BaseExt; use halo2_proofs::{ - arithmetic::{CurveAffine, Field}, + arithmetic::{CurveAffine, Field, FieldExt}, dev::MockProver, - pairing::bn256::Fr, + halo2curves::{ + bn256::Fr, + group::{Curve, Group}, + }, }; use integration_tests::{get_client, log_init, GenDataOutput, CHAIN_ID}; use lazy_static::lazy_static; @@ -67,8 +68,7 @@ async fn test_state_circuit_block(block_num: u64) { let circuit = StateCircuit::::new(randomness, rw_map, 1 << 16); let power_of_randomness = circuit.instance(); - use halo2_proofs::pairing::bn256::Fr as Fp; - let prover = MockProver::::run(DEGREE as u32, &circuit, power_of_randomness).unwrap(); + let prover = MockProver::::run(DEGREE as u32, &circuit, power_of_randomness).unwrap(); prover.verify().expect("state_circuit verification failed"); } diff --git a/keccak256/Cargo.toml b/keccak256/Cargo.toml index 6fc9344f1f..870b42ab90 100644 --- a/keccak256/Cargo.toml +++ b/keccak256/Cargo.toml @@ -15,9 +15,6 @@ num-traits = "0.2.14" plotters = { version = "0.3.0", optional = true } eth-types = { path = "../eth-types" } lazy_static = "1.4" -gadgets = { path = "../gadgets" } -strum = "0.24" -strum_macros = "0.24" [dev-dependencies] pretty_assertions = "1.0" diff --git a/keccak256/src/arith_helpers.rs b/keccak256/src/arith_helpers.rs index 0104d81a32..9504c4befe 100644 --- a/keccak256/src/arith_helpers.rs +++ b/keccak256/src/arith_helpers.rs @@ -1,6 +1,5 @@ use crate::common::State; use eth_types::Field; -use halo2_proofs::circuit::AssignedCell; use itertools::Itertools; use num_bigint::BigUint; use num_traits::Zero; @@ -196,66 +195,6 @@ pub fn inspect(x: BigUint, name: &str, base: u8) { println!("inspect {} {} info {:?}", name, x, info); } -pub fn state_to_biguint(state: [F; N]) -> StateBigInt { - StateBigInt { - xy: state - .iter() - .map(|elem| elem.to_repr()) - .map(|bytes| BigUint::from_bytes_le(&bytes)) - .collect(), - } -} - -pub fn state_to_state_bigint(state: [F; N]) -> State { - let mut matrix = [[0u64; 5]; 5]; - - let mut elems: Vec = state - .iter() - .map(|elem| elem.to_repr()) - // This is horrible. But Field does not give much better alternatives - // and refactoring `State` will be done once the - // keccak_all_togheter is done. - .map(|bytes| { - debug_assert!(bytes[8..32] == vec![0u8; 24]); - let mut arr = [0u8; 8]; - arr.copy_from_slice(&bytes[0..8]); - u64::from_le_bytes(arr) - }) - .collect(); - elems.extend(vec![0u64; 25 - N]); - (0..5) - .into_iter() - .for_each(|idx| matrix[idx].copy_from_slice(&elems[5 * idx..(5 * idx + 5)])); - - matrix -} - -pub fn state_bigint_to_field(state: StateBigInt) -> [F; N] { - let mut arr = [F::zero(); N]; - let vector: Vec = state - .xy - .iter() - .map(|elem| { - let mut array = [0u8; 32]; - let bytes = elem.to_bytes_le(); - array[0..bytes.len()].copy_from_slice(&bytes[0..bytes.len()]); - array - }) - .map(|bytes| F::from_repr(bytes).unwrap()) - .collect(); - arr[0..N].copy_from_slice(&vector[0..N]); - arr -} - -/// Returns only the value of a an assigned state cell. -pub fn split_state_cells(state: [AssignedCell; N]) -> [F; N] { - let mut res = [F::zero(); N]; - state.iter().enumerate().for_each(|(idx, assigned_cell)| { - res[idx] = assigned_cell.value().copied().unwrap_or_default() - }); - res -} - pub fn f_from_radix_be(buf: &[u8], base: u8) -> F { let base = F::from(base as u64); buf.iter() diff --git a/keccak256/src/circuit.rs b/keccak256/src/circuit.rs deleted file mode 100644 index 1172fa79d2..0000000000 --- a/keccak256/src/circuit.rs +++ /dev/null @@ -1,8 +0,0 @@ -pub mod padding; -pub mod word_builder; - -pub const MAX_INPUT_BYTES: usize = MAX_INPUT_WORDS * BYTES_PER_WORD; -pub const MAX_INPUT_WORDS: usize = MAX_PERM_ROUNDS * NEXT_INPUTS_WORDS; -pub const BYTES_PER_WORD: usize = 8; -pub const NEXT_INPUTS_WORDS: usize = 17; -pub const MAX_PERM_ROUNDS: usize = 10; diff --git a/keccak256/src/circuit/padding.rs b/keccak256/src/circuit/padding.rs deleted file mode 100644 index b21f18ee48..0000000000 --- a/keccak256/src/circuit/padding.rs +++ /dev/null @@ -1,448 +0,0 @@ -use eth_types::Field; -use gadgets::is_zero::{IsZeroChip, IsZeroConfig, IsZeroInstruction}; -use halo2_proofs::{ - circuit::{AssignedCell, Layouter, Region}, - plonk::{Advice, Column, ConstraintSystem, Error, Expression, Selector}, - poly::Rotation, -}; -use itertools::Itertools; -use std::iter; -use std::marker::PhantomData; - -pub const BYTES_LEN_17_WORDS: usize = 136; - -/// Build word from big endian bytes -#[derive(Debug, Clone)] -pub struct WordConfig { - q_enable: Selector, - word: Column, - _marker: PhantomData, -} -impl WordConfig { - pub fn configure( - meta: &mut ConstraintSystem, - byte: Column, - word: Column, - ) -> Self { - meta.enable_equality(byte); - meta.enable_equality(word); - let q_enable = meta.selector(); - meta.create_gate("build word", |meta| { - let q_enable = meta.query_selector(q_enable); - let byte = meta.query_advice(byte, Rotation::cur()); - let word_cur = meta.query_advice(word, Rotation::cur()); - let word_prev = meta.query_advice(word, Rotation::prev()); - vec![q_enable * (word_cur - Expression::Constant(F::from(256u64)) * word_prev - byte)] - }); - Self { - q_enable, - word, - _marker: PhantomData, - } - } - - pub fn assign_region( - &self, - region: &mut Region<'_, F>, - offset: usize, - bytes: [AssignedCell; 8], - ) -> Result, Error> { - let mut word_cell = bytes[0].copy_advice(|| "first byte", region, self.word, offset)?; - let mut word = bytes[0].value().cloned().unwrap_or_default(); - for (i, byte) in bytes.iter().enumerate().skip(1) { - let real_offset = offset + i; - self.q_enable.enable(region, real_offset)?; - word = word * F::from(256u64) + byte.value().cloned().unwrap_or_default(); - word_cell = region.assign_advice(|| "word", self.word, real_offset, || Ok(word))?; - } - Ok(word_cell) - } -} - -// TODO: byteRLC -#[derive(Debug, Clone)] -pub struct PaddingConfig { - q_all: Selector, - q_without_first: Selector, - q_without_last: Selector, - q_last: Selector, - is_finalize: Column, - byte: Column, - input_len: Column, - acc_len: Column, - diff_is_zero: IsZeroConfig, - is_pad_zone: Column, - padded_byte: Column, - word_config: WordConfig, -} - -impl PaddingConfig { - pub fn configure(meta: &mut ConstraintSystem) -> Self { - let q_all = meta.selector(); - let q_without_first = meta.selector(); - let q_without_last = meta.selector(); - let q_last = meta.selector(); - let is_finalize = meta.advice_column(); - let byte = meta.advice_column(); - let input_len = meta.advice_column(); - let acc_len = meta.advice_column(); - let diff_inv = meta.advice_column(); - let is_pad_zone = meta.advice_column(); - let padded_byte = meta.advice_column(); - let word = meta.advice_column(); - meta.enable_equality(is_finalize); - meta.enable_equality(input_len); - meta.enable_equality(acc_len); - let one = Expression::Constant(F::one()); - let diff_is_zero = IsZeroChip::configure( - meta, - |meta| meta.query_selector(q_all), - |meta| { - meta.query_advice(input_len, Rotation::cur()) - - meta.query_advice(acc_len, Rotation::cur()) - }, - diff_inv, - ); - let word_config = WordConfig::configure(meta, padded_byte, word); - // Check bytes in the pad zone must be 0 - meta.create_gate("all", |meta| { - let q_all = meta.query_selector(q_all); - let is_pad_zone_cur = meta.query_advice(is_pad_zone, Rotation::cur()); - let byte_cur = meta.query_advice(byte, Rotation::cur()); - - vec![q_all * (is_pad_zone_cur * byte_cur)] - }); - // check that - // 1. acc_len is increasing by one in each row - // 2. padded_byte is correctly padded 0x80 from byte - meta.create_gate("without last", |meta| { - let q_without_last = meta.query_selector(q_without_last); - let acc_len_cur = meta.query_advice(acc_len, Rotation::cur()); - let acc_len_next = meta.query_advice(acc_len, Rotation::next()); - let padded_byte_cur = meta.query_advice(padded_byte, Rotation::cur()); - let byte_cur = meta.query_advice(byte, Rotation::cur()); - iter::empty() - .chain(Some(("increase acc_len", acc_len_next - acc_len_cur - one))) - .chain(Some(( - "check padded byte", - padded_byte_cur - - byte_cur - - diff_is_zero.clone().is_zero_expression - * Expression::Constant(F::from(0x80)), - ))) - .map(move |(name, poly)| (name, q_without_last.clone() * poly)) - }); - // Check that cells in the pad_zone column are 0 before the pad, and are 1 after - // the pad. - meta.create_gate("without first", |meta| { - let q_without_first = meta.query_selector(q_without_first); - let is_pad_zone_prev = meta.query_advice(is_pad_zone, Rotation::prev()); - let is_pad_zone_cur = meta.query_advice(is_pad_zone, Rotation::cur()); - vec![( - "check pad_zone", - q_without_first - * (is_pad_zone_cur - - is_pad_zone_prev - - diff_is_zero.clone().is_zero_expression), - )] - }); - // padded_byte is padded 0x80 if pad happens here. padded_byte is also padded - // 0x01 if the state_tag is Finalize - meta.create_gate("last", |meta| { - let q_last = meta.query_selector(q_last); - let is_finalize = meta.query_advice(is_finalize, Rotation::cur()); - let padded_byte_cur = meta.query_advice(padded_byte, Rotation::cur()); - let byte_cur = meta.query_advice(byte, Rotation::cur()); - vec![ - q_last - * (padded_byte_cur - - byte_cur - - diff_is_zero.clone().is_zero_expression - * Expression::Constant(F::from(0x80)) - - is_finalize), - ] - }); - Self { - q_all, - q_without_first, - q_without_last, - q_last, - is_finalize, - byte, - input_len, - acc_len, - diff_is_zero, - is_pad_zone, - padded_byte, - word_config, - } - } - pub fn assign_region( - &self, - layouter: &mut impl Layouter, - is_finalize: AssignedCell, - input_len_cell: AssignedCell, - acc_len_cell: AssignedCell, - bytes: [u8; BYTES_LEN_17_WORDS], - ) -> Result<[AssignedCell; 17], Error> { - let diff_is_zero_chip = IsZeroChip::construct(self.diff_is_zero.clone()); - layouter.assign_region( - || "padding validation", - |mut region| { - const LAST: usize = BYTES_LEN_17_WORDS - 1; - self.q_last.enable(&mut region, LAST)?; - let mut is_pad_zone = F::zero(); - let mut padded_bytes = [0u8; BYTES_LEN_17_WORDS]; - for (offset, &byte) in bytes.iter().enumerate().take(BYTES_LEN_17_WORDS) { - self.q_all.enable(&mut region, offset)?; - if offset != 0 { - self.q_without_first.enable(&mut region, offset)?; - } - if offset != LAST { - self.q_without_last.enable(&mut region, offset)?; - } - is_finalize.clone().copy_advice( - || "flag enable", - &mut region, - self.is_finalize, - offset, - )?; - input_len_cell.copy_advice( - || "input len", - &mut region, - self.input_len, - offset, - )?; - let acc_len = - acc_len_cell.value().cloned().unwrap_or_default() + F::from(offset as u64); - region.assign_advice( - || "acc_len_rest", - self.acc_len, - offset, - || Ok(acc_len), - )?; - let diff_value = - Some(input_len_cell.value().cloned().unwrap_or_default() - acc_len); - let is_zero = diff_value - .map(|diff_value| F::from(diff_value == F::zero())) - .unwrap_or_default(); - diff_is_zero_chip.assign(&mut region, offset, diff_value)?; - - let byte_f = F::from(byte as u64); - region.assign_advice(|| "byte", self.byte, offset, || Ok(byte_f))?; - is_pad_zone += is_zero; - region.assign_advice( - || "is pad zone", - self.is_pad_zone, - offset, - || Ok(is_pad_zone), - )?; - let is_finalize_bit = - is_finalize.value().cloned().unwrap_or_default() == F::one(); - padded_bytes[offset] = byte - + diff_value - .map(|diff_value| (diff_value == F::zero()) as u8) - .unwrap_or_default() - * 0x80u8 - + (((offset == LAST) && is_finalize_bit) as u8); - } - let padded_byte_cells: Result, _> = padded_bytes - .iter() - .take(BYTES_LEN_17_WORDS) - .enumerate() - .map(|(offset, &padded_byte)| { - region.assign_advice( - || "padded byte", - self.padded_byte, - offset, - || Ok(F::from(padded_byte as u64)), - ) - }) - .collect(); - let padded_byte_cells = padded_byte_cells?; - let words: Result, _> = padded_byte_cells - .iter() - .chunks(8) - .into_iter() - .enumerate() - .map(|(idx, chunk)| { - let bytes: [AssignedCell; 8] = - chunk.cloned().collect_vec().try_into().unwrap(); - self.word_config.assign_region(&mut region, idx * 8, bytes) - }) - .collect(); - let words: [AssignedCell; 17] = words?.try_into().unwrap(); - - Ok(words) - }, - ) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use halo2_proofs::{ - circuit::SimpleFloorPlanner, - dev::MockProver, - pairing::bn256::Fr, - plonk::{Advice, Circuit}, - }; - use pretty_assertions::assert_eq; - use rand::{thread_rng, Fill}; - use std::marker::PhantomData; - - struct MyCircuit { - bytes: [u8; BYTES_LEN_17_WORDS], - is_finalize: bool, - input_len: u64, - acc_len: u64, - _marker: PhantomData, - } - impl Default for MyCircuit { - fn default() -> Self { - Self { - bytes: [0; BYTES_LEN_17_WORDS], - is_finalize: true, - input_len: 0, - acc_len: 0, - _marker: PhantomData, - } - } - } - - #[derive(Clone)] - struct MyConfig { - padding_conf: PaddingConfig, - is_finalize: Column, - input_len: Column, - acc_len: Column, - } - - impl Circuit for MyCircuit { - type Config = MyConfig; - type FloorPlanner = SimpleFloorPlanner; - - fn without_witnesses(&self) -> Self { - Self::default() - } - fn configure(meta: &mut ConstraintSystem) -> Self::Config { - let padding_conf = PaddingConfig::configure(meta); - let is_finalize = meta.advice_column(); - let input_len = meta.advice_column(); - let acc_len = meta.advice_column(); - meta.enable_equality(is_finalize); - meta.enable_equality(input_len); - meta.enable_equality(acc_len); - - Self::Config { - padding_conf, - is_finalize, - acc_len, - input_len, - } - } - - fn synthesize( - &self, - config: Self::Config, - mut layouter: impl Layouter, - ) -> Result<(), Error> { - let (is_finalize, input_len, acc_len) = layouter.assign_region( - || "external values", - |mut region| { - let offset = 0; - let is_finalize = region.assign_advice( - || "parent flag", - config.is_finalize, - offset, - || Ok(F::from(self.is_finalize)), - )?; - let input_len = region.assign_advice( - || "input len", - config.input_len, - offset, - || Ok(F::from(self.input_len)), - )?; - let acc_len = region.assign_advice( - || "acc len", - config.acc_len, - offset, - || Ok(F::from(self.acc_len)), - )?; - Ok((is_finalize, input_len, acc_len)) - }, - )?; - - config.padding_conf.assign_region( - &mut layouter, - is_finalize, - input_len, - acc_len, - self.bytes, - )?; - - Ok(()) - } - } - #[test] - fn test_normal_pad() { - let mut bytes = [0; BYTES_LEN_17_WORDS]; - bytes[0] = 1; - let circuit = MyCircuit:: { - bytes, - is_finalize: true, - input_len: 1, - acc_len: 0, - _marker: PhantomData, - }; - let prover = MockProver::::run(9, &circuit, vec![]).unwrap(); - assert_eq!(prover.verify(), Ok(())); - } - - #[test] - fn test_full_pad() { - let circuit = MyCircuit:: { - bytes: [0; BYTES_LEN_17_WORDS], - is_finalize: true, - input_len: 0, - acc_len: 0, - _marker: PhantomData, - }; - let prover = MockProver::::run(9, &circuit, vec![]).unwrap(); - assert_eq!(prover.verify(), Ok(())); - } - - #[test] - fn test_0x81_case() { - let mut bytes = [0u8; BYTES_LEN_17_WORDS]; - let mut rng = thread_rng(); - bytes.try_fill(&mut rng).unwrap(); - bytes[135] = 0; - let circuit = MyCircuit:: { - bytes, - is_finalize: true, - input_len: 135, - acc_len: 0, - _marker: PhantomData, - }; - let prover = MockProver::::run(9, &circuit, vec![]).unwrap(); - assert_eq!(prover.verify(), Ok(())); - } - - #[test] - fn test_no_pad() { - let mut bytes = [0u8; BYTES_LEN_17_WORDS]; - let mut rng = thread_rng(); - bytes.try_fill(&mut rng).unwrap(); - let circuit = MyCircuit:: { - bytes, - is_finalize: false, - input_len: 136, - acc_len: 0, - _marker: PhantomData, - }; - let prover = MockProver::::run(9, &circuit, vec![]).unwrap(); - assert_eq!(prover.verify(), Ok(())); - } -} diff --git a/keccak256/src/circuit/word_builder.rs b/keccak256/src/circuit/word_builder.rs deleted file mode 100644 index 6ea1814a3f..0000000000 --- a/keccak256/src/circuit/word_builder.rs +++ /dev/null @@ -1,347 +0,0 @@ -// Added until this is used by another component -#![allow(dead_code)] -use super::BYTES_PER_WORD; -use crate::permutation::tables::RangeCheckConfig; -use eth_types::Field; -use halo2_proofs::{ - circuit::{AssignedCell, Layouter}, - plonk::{Advice, Column, ConstraintSystem, Error, Expression, Selector}, - poly::Rotation, -}; - -pub type Byte = u8; -pub type AssignedByte = AssignedCell; -pub type AssignedWord = AssignedCell; - -#[derive(Debug, Clone)] -/// Gets 8 Advice columns with the 8bytes to form the word + the final word -/// value of the composed bytes at the end. -pub(crate) struct WordBuilderConfig { - q_enable: Selector, - bytes: [Column; BYTES_PER_WORD], - word: Column, - byte_table: RangeCheckConfig, -} - -impl WordBuilderConfig { - pub(crate) fn configure( - meta: &mut ConstraintSystem, - bytes: [Column; BYTES_PER_WORD], - word: Column, - byte_table: RangeCheckConfig, - ) -> WordBuilderConfig { - let q_enable = meta.complex_selector(); - - // Enable equality for all byte cells. - bytes.iter().for_each(|&byte| meta.enable_equality(byte)); - meta.enable_equality(word); - - bytes.iter().for_each(|&byte| { - meta.lookup("Range check for word byte", |meta| { - let q_enable = meta.query_selector(q_enable); - - vec![( - q_enable * meta.query_advice(byte, Rotation::cur()), - byte_table.range, - )] - }); - }); - - meta.create_gate("Build Word", |meta| { - let q_enable = meta.query_selector(q_enable); - - // Running sum to construct a u64 word with 8 u8 bytes shifted by it's position. - let bytes_sum: Expression = bytes - .iter() - .map(|&column| meta.query_advice(column, Rotation::cur())) - .enumerate() - .map(|(idx, byte_expr)| { - Expression::Constant(F::from(1u64 << (idx * 8))) * byte_expr - }) - .reduce(|acc, byte_shifted| acc + byte_shifted) - // Unwrapping is safe here as we recieve an array that contails all elements. - .unwrap(); - - let word = meta.query_advice(word, Rotation::cur()); - - vec![q_enable * (bytes_sum - word)] - }); - Self { - q_enable, - bytes, - word, - byte_table, - } - } - - pub(crate) fn load(&self, layouter: &mut impl Layouter) -> Result<(), Error> { - self.byte_table.load(layouter) - } - - pub(crate) fn assign_bytes( - &self, - layouter: &mut impl Layouter, - bytes: [AssignedByte; BYTES_PER_WORD], - ) -> Result, Error> { - layouter.assign_region( - || "Word construction", - |mut region| { - let offset = 0; - self.q_enable.enable(&mut region, offset)?; - // Copy bytes to byte columns - let byte_cells: [AssignedByte; BYTES_PER_WORD] = bytes - .iter() - .zip(self.bytes.iter()) - .map(|(byte, &byte_col)| { - byte.copy_advice(|| "Copy byte", &mut region, byte_col, offset) - }) - .collect::>, Error>>()? - .try_into() - .unwrap(); - - // Compute the word formed by the bytes and assign it into the last column of - // the bytes - let word_scalar = byte_cells - .iter() - .enumerate() - .map(|(idx, byte_cell)| { - F::from(1u64 << (idx * 8)) * byte_cell.value().copied().unwrap_or_default() - }) - .reduce(|acc, byte_shifted| acc + byte_shifted) - // Unwrapping is safe here as we recieve an array that contails all elements. - .unwrap(); - - region.assign_advice( - || "Assign byte-constructed Word", - self.word, - offset, - || Ok(word_scalar), - ) - }, - ) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use halo2_proofs::{ - circuit::SimpleFloorPlanner, - dev::{ - metadata::{Column as MetaColumn, Region}, - FailureLocation, MockProver, VerifyFailure, - }, - pairing::bn256::Fr, - plonk::{Advice, Any, Circuit}, - }; - use pretty_assertions::assert_eq; - - #[test] - fn test_word_construction_gate() { - #[derive(Default)] - struct MyCircuit { - bytes: [F; BYTES_PER_WORD], - word: F, - } - - #[derive(Clone)] - struct MyConfig { - word_build_conf: WordBuilderConfig, - bytes: [Column; BYTES_PER_WORD], - word: Column, - } - - impl Circuit for MyCircuit { - type Config = MyConfig; - type FloorPlanner = SimpleFloorPlanner; - - fn without_witnesses(&self) -> Self { - Self::default() - } - - fn configure(meta: &mut ConstraintSystem) -> Self::Config { - // Create WordBuilderConfig - let table = RangeCheckConfig::::configure(meta); - let bytes: [Column; BYTES_PER_WORD] = (0..BYTES_PER_WORD) - .map(|_| { - let column = meta.advice_column(); - meta.enable_equality(column); - column - }) - .collect::>() - .try_into() - .unwrap(); - - let word = meta.advice_column(); - meta.enable_equality(word); - let word_build_conf = WordBuilderConfig::configure(meta, bytes, word, table); - - // Create a MyConfig instance with all the extra columns needed - // for testing purposes - let bytes: [Column; BYTES_PER_WORD] = (0..BYTES_PER_WORD) - .map(|_| { - let column = meta.advice_column(); - meta.enable_equality(column); - column - }) - .collect::>() - .try_into() - .unwrap(); - let word = meta.advice_column(); - meta.enable_equality(word); - - MyConfig { - word_build_conf, - bytes, - word, - } - } - - fn synthesize( - &self, - config: Self::Config, - mut layouter: impl Layouter, - ) -> Result<(), Error> { - config.word_build_conf.byte_table.load(&mut layouter)?; - let bytes = layouter.assign_region( - || "Wittnes of word's bytes", - |mut region| { - let bytes: [AssignedCell; BYTES_PER_WORD] = { - let mut state: Vec> = - Vec::with_capacity(BYTES_PER_WORD); - for (idx, val) in self.bytes.iter().enumerate() { - let cell = region.assign_advice( - || "witness input state", - config.bytes[idx], - 0, - || Ok(*val), - )?; - state.push(cell) - } - state.try_into().unwrap() - }; - Ok(bytes) - }, - )?; - - let circuit_word = config.word_build_conf.assign_bytes(&mut layouter, bytes)?; - - // Add equality constrain between the obtained word from the circuit and the - // witnessed one. - layouter.assign_region( - || "Constraint word to be equal to the test announced one", - |mut region| { - let announced_word = region.assign_advice( - || "Add test word", - config.word, - 0, - || Ok(self.word), - )?; - region.constrain_equal(circuit_word.cell(), announced_word.cell()) - }, - )?; - Ok(()) - } - } - - // Test that the circuit works when we provide correct witnesses. - { - let bytes = [ - Fr::from(0xafu64), - Fr::from(0xafu64), - Fr::from(0xafu64), - Fr::from(0xafu64), - Fr::zero(), - Fr::zero(), - Fr::zero(), - Fr::zero(), - ]; - let word = Fr::from(2947526575u64); - - let circuit = MyCircuit:: { bytes, word }; - - // Test without public inputs - let prover = MockProver::::run(9, &circuit, vec![]).unwrap(); - - assert_eq!(prover.verify(), Ok(())); - } - - // Test that if we pass a byte greater than 255 the lookup will cause the - // circuit to fail. - { - let bytes = [ - Fr::from(0x100u64), - Fr::from(0xafu64), - Fr::from(0xafu64), - Fr::from(0xafu64), - Fr::zero(), - Fr::zero(), - Fr::zero(), - Fr::zero(), - ]; - let word = Fr::from(68730990511u64); - - let circuit = MyCircuit:: { bytes, word }; - - // Test without public inputs - let prover = MockProver::::run(9, &circuit, vec![]).unwrap(); - - assert_eq!( - prover.verify(), - Err(vec![ - VerifyFailure::Lookup { - name: "Range check for word byte", - lookup_index: 0, - location: FailureLocation::InRegion { - region: Region::from((2, "Word construction")), - offset: 0 - } - }, - VerifyFailure::Permutation { - column: MetaColumn::from((Any::Advice, 8)), - row: 0 - }, - VerifyFailure::Permutation { - column: MetaColumn::from((Any::Advice, 17)), - row: 0 - } - ]) - ) - } - - // Test that if the bytes are not equivalent to the announced word, the circuit - // fails. - { - let bytes = [ - Fr::from(0xafu64), - Fr::from(0xafu64), - Fr::from(0xafu64), - Fr::from(0xafu64), - Fr::zero(), - Fr::zero(), - Fr::zero(), - Fr::zero(), - ]; - let word = Fr::from(2947526574u64); - - let circuit = MyCircuit:: { bytes, word }; - - // Test without public inputs - let prover = MockProver::::run(9, &circuit, vec![]).unwrap(); - - assert_eq!( - prover.verify(), - Err(vec![ - VerifyFailure::Permutation { - column: MetaColumn::from((Any::Advice, 8)), - row: 0 - }, - VerifyFailure::Permutation { - column: MetaColumn::from((Any::Advice, 17)), - row: 0 - } - ]) - ) - } - } -} diff --git a/keccak256/src/lib.rs b/keccak256/src/lib.rs index 17d7ab7e25..f94cdeb29e 100644 --- a/keccak256/src/lib.rs +++ b/keccak256/src/lib.rs @@ -2,10 +2,8 @@ // just used in tests pub mod arith_helpers; -pub mod circuit; pub mod common; pub mod gate_helpers; -pub mod permutation; // We build arith module to get test cases for the circuit pub mod keccak_arith; // We build plain module for the purpose of reviewing the circuit diff --git a/keccak256/src/permutation.rs b/keccak256/src/permutation.rs deleted file mode 100644 index 71ccfc205f..0000000000 --- a/keccak256/src/permutation.rs +++ /dev/null @@ -1,7 +0,0 @@ -#![allow(clippy::type_complexity)] -#![allow(clippy::too_many_arguments)] -pub mod circuit; -pub(crate) mod components; -pub(crate) mod generic; -pub(crate) mod rho_helpers; -pub(crate) mod tables; diff --git a/keccak256/src/permutation/circuit.rs b/keccak256/src/permutation/circuit.rs deleted file mode 100644 index e36320e418..0000000000 --- a/keccak256/src/permutation/circuit.rs +++ /dev/null @@ -1,374 +0,0 @@ -use crate::{ - common::{NEXT_INPUTS_LANES, PERMUTATION}, - permutation::{ - generic::GenericConfig, - tables::{Base13toBase9TableConfig, FromBase9TableConfig, StackableTable}, - }, -}; -use eth_types::Field; -use halo2_proofs::{ - circuit::{AssignedCell, Layouter}, - plonk::{Advice, Column, ConstraintSystem, Error, TableColumn}, -}; -use itertools::Itertools; - -use super::{ - components::{ - assign_next_input, assign_rho, assign_theta, assign_xi, convert_from_b9_to_b13, - convert_to_b9_mul_a4, pi_gate_permutation, IotaConstants, - }, - tables::FromBinaryTableConfig, -}; - -#[derive(Clone, Debug)] -pub struct KeccakFConfig { - generic: GenericConfig, - stackable: StackableTable, - base13to9_config: Base13toBase9TableConfig, - from_b9_table: FromBase9TableConfig, - from_b2_table: FromBinaryTableConfig, - pub advice: Column, -} - -impl KeccakFConfig { - // We assume state is received in base-9. - pub fn configure(meta: &mut ConstraintSystem) -> Self { - let advices: [Column; 3] = (0..3) - .map(|_| { - let column = meta.advice_column(); - meta.enable_equality(column); - column - }) - .collect_vec() - .try_into() - .unwrap(); - - let fixed = meta.fixed_column(); - let generic = GenericConfig::configure(meta, advices, fixed); - let stackable_cols: [TableColumn; 3] = (0..3) - .map(|_| meta.lookup_table_column()) - .collect_vec() - .try_into() - .unwrap(); - let base13to9_cols: [TableColumn; 3] = (0..3) - .map(|_| meta.lookup_table_column()) - .collect_vec() - .try_into() - .unwrap(); - let from_base9_cols: [TableColumn; 3] = (0..3) - .map(|_| meta.lookup_table_column()) - .collect_vec() - .try_into() - .unwrap(); - let from_base2_cols: [TableColumn; 3] = (0..3) - .map(|_| meta.lookup_table_column()) - .collect_vec() - .try_into() - .unwrap(); - let stackable = StackableTable::configure(meta, advices, stackable_cols); - let base13to9_config = Base13toBase9TableConfig::configure(meta, advices, base13to9_cols); - let from_b9_table = FromBase9TableConfig::configure(meta, advices, from_base9_cols); - let from_b2_table = FromBinaryTableConfig::configure(meta, advices, from_base2_cols); - - Self { - generic, - stackable, - base13to9_config, - from_b9_table, - from_b2_table, - advice: advices[0], - } - } - - pub fn load(&mut self, layouter: &mut impl Layouter) -> Result<(), Error> { - self.stackable.load(layouter)?; - self.base13to9_config.load(layouter)?; - self.from_b9_table.load(layouter)?; - self.from_b2_table.load(layouter) - } - - // Result b13 state for next round, b2 state for end result - pub fn assign_all( - &self, - layouter: &mut impl Layouter, - in_state: [AssignedCell; 25], - next_mixing: Option<[F; NEXT_INPUTS_LANES]>, - ) -> Result<([AssignedCell; 25], [AssignedCell; 25]), Error> { - let iota_constants = IotaConstants::default(); - let mut state = in_state; - - // First 23 rounds - for round_idx in 0..PERMUTATION { - // State in base-13 - state = assign_theta(&self.generic, layouter, &state)?; - state = assign_rho( - layouter, - &self.base13to9_config, - &self.generic, - &self.stackable, - &state, - )?; - // Outputs in base-9 which is what Pi requires - state = pi_gate_permutation(&state); - state = assign_xi(&self.generic, layouter, &state)?; - - // Last round before Mixing does not run IotaB9 nor BaseConversion - if round_idx == PERMUTATION - 1 { - break; - } - - state[0] = self.generic.add_fixed( - layouter, - &state[0], - &iota_constants.a4_times_round_constants_b9[round_idx], - )?; - - // The resulting state is in Base-9 now. We now convert it to - // base_13 which is what Theta requires again at the - // start of the loop. - state = - convert_from_b9_to_b13(layouter, &self.from_b9_table, &self.generic, state, false)? - .0; - } - let (f_mix, f_no_mix) = self - .stackable - .assign_boolean_flag(layouter, next_mixing.is_some())?; - state[0] = self.generic.conditional_add_const( - layouter, - &state[0], - &f_no_mix, - &iota_constants.a4_times_round_constants_b9[PERMUTATION - 1], - )?; - let next_input = assign_next_input(layouter, &self.advice, &next_mixing)?; - - // Convert to base 9 and multiply by A4 - let next_input = - convert_to_b9_mul_a4(layouter, &self.from_b2_table, &self.generic, &next_input)?; - - for (i, input) in next_input.iter().enumerate() { - state[i] = self - .generic - .conditional_add_advice(layouter, &state[i], &f_mix, input)?; - } - let (mut state_b13, state_b2) = - convert_from_b9_to_b13(layouter, &self.from_b9_table, &self.generic, state, true)?; - let state_b2 = state_b2.unwrap(); - state_b13[0] = self.generic.conditional_add_const( - layouter, - &state_b13[0], - &f_mix, - &iota_constants.round_constant_b13, - )?; - Ok((state_b13, state_b2)) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::{ - arith_helpers::{ - convert_b2_to_b13, convert_b9_lane_to_b2_biguint, state_bigint_to_field, StateBigInt, - }, - common::{State, NEXT_INPUTS_LANES}, - gate_helpers::biguint_to_f, - keccak_arith::KeccakFArith, - }; - - use halo2_proofs::{ - circuit::{Layouter, SimpleFloorPlanner}, - dev::MockProver, - pairing::bn256::Fr as Fp, - plonk::{Circuit, ConstraintSystem, Error}, - }; - - #[test] - fn test_keccak_round() { - #[derive(Default)] - struct MyCircuit { - in_state: [F; 25], - out_state: [F; 25], - next_mixing: Option<[F; NEXT_INPUTS_LANES]>, - } - - impl Circuit for MyCircuit { - type Config = KeccakFConfig; - type FloorPlanner = SimpleFloorPlanner; - - fn without_witnesses(&self) -> Self { - Self::default() - } - - fn configure(meta: &mut ConstraintSystem) -> Self::Config { - Self::Config::configure(meta) - } - - fn synthesize( - &self, - mut config: Self::Config, - mut layouter: impl Layouter, - ) -> Result<(), Error> { - // Load the table - config.load(&mut layouter)?; - - let state: [AssignedCell; 25] = layouter.assign_region( - || "Keccak round Wittnes & flag assignation", - |mut region| { - let state = self - .in_state - .iter() - .enumerate() - .map(|(offset, val)| { - region.assign_advice( - || "witness input state", - config.advice, - offset, - || Ok(*val), - ) - }) - .collect::>, Error>>()?; - - Ok(state.try_into().unwrap()) - }, - )?; - - let (state_b13, state_b2) = - config.assign_all(&mut layouter, state, self.next_mixing)?; - if self.next_mixing.is_some() { - layouter.assign_region( - || "check final states", - |mut region| { - for (assigned, value) in state_b13.iter().zip(self.out_state.iter()) { - region.constrain_constant(assigned.cell(), value)?; - } - Ok(()) - }, - ) - } else { - layouter.assign_region( - || "check final states", - |mut region| { - for (assigned, value) in state_b2.iter().zip(self.out_state.iter()) { - region.constrain_constant(assigned.cell(), value)?; - } - Ok(()) - }, - ) - } - } - } - - let in_state: State = [ - [1, 0, 0, 0, 0], - [0, 0, 0, 0, 0], - [0, 0, 0, 0, 0], - [0, 0, 0, 0, 0], - [0, 0, 0, 0, 0], - ]; - - let next_input: State = [ - [2, 0, 0, 0, 0], - [0, 0, 0, 0, 0], - [0, 0, 0, 0, 0], - [0, 0, 0, 0, 0], - [0, 0, 0, 0, 0], - ]; - - let mut in_state_biguint = StateBigInt::default(); - - // Generate in_state as `[Fp;25]` - let mut in_state_fp: [Fp; 25] = [Fp::zero(); 25]; - for (x, y) in (0..5).cartesian_product(0..5) { - in_state_fp[5 * x + y] = biguint_to_f(&convert_b2_to_b13(in_state[x][y])); - in_state_biguint[(x, y)] = convert_b2_to_b13(in_state[x][y]); - } - - // Compute out_state_mix - let mut out_state_mix = in_state_biguint.clone(); - KeccakFArith::permute_and_absorb(&mut out_state_mix, Some(&next_input)); - - // Compute out_state_non_mix - let mut out_state_non_mix = in_state_biguint.clone(); - KeccakFArith::permute_and_absorb(&mut out_state_non_mix, None); - - for (x, y) in (0..5).cartesian_product(0..5) { - out_state_non_mix[(x, y)] = - convert_b9_lane_to_b2_biguint(out_state_non_mix[(x, y)].clone()) - } - - // Generate out_state as `[Fp;25]` - let out_state_mix: [Fp; 25] = state_bigint_to_field(out_state_mix); - let out_state_non_mix: [Fp; 25] = state_bigint_to_field(out_state_non_mix); - - // Generate next_input (tho one that is not None) in the form `[F;17]` - // Generate next_input as `[Fp;NEXT_INPUTS_LANES]` - let next_input_fp: [Fp; NEXT_INPUTS_LANES] = - state_bigint_to_field(StateBigInt::from(next_input)); - - // When we pass no `mixing_inputs`, we perform the full keccak round - // ending with Mixing executing IotaB9 - { - // With the correct input and output witnesses, the proof should - // pass. - let circuit = MyCircuit:: { - in_state: in_state_fp, - out_state: out_state_non_mix, - next_mixing: None, - }; - - let prover = MockProver::::run(17, &circuit, vec![]).unwrap(); - - assert_eq!(prover.verify(), Ok(()), "is_mixing: false"); - - // With wrong input and/or output witnesses, the proof should fail - // to be verified. - let circuit = MyCircuit:: { - in_state: out_state_non_mix, - out_state: out_state_non_mix, - next_mixing: None, - }; - let k = 17; - let prover = MockProver::::run(k, &circuit, vec![]).unwrap(); - - #[cfg(feature = "dev-graph")] - { - use plotters::prelude::*; - let root = BitMapBackend::new("keccak-f.png", (1024, 16384)).into_drawing_area(); - root.fill(&WHITE).unwrap(); - let root = root.titled("Keccak-F", ("sans-serif", 60)).unwrap(); - halo2_proofs::dev::CircuitLayout::default() - .show_labels(false) - .render(k, &circuit, &root) - .unwrap(); - } - - assert!(prover.verify().is_err()); - } - - // When we pass `mixing_inputs`, we perform the full keccak round ending - // with Mixing executing Absorb + base_conversion + IotaB13 - { - let circuit = MyCircuit:: { - in_state: in_state_fp, - out_state: out_state_mix, - next_mixing: Some(next_input_fp), - }; - - let prover = MockProver::::run(17, &circuit, vec![]).unwrap(); - - assert_eq!(prover.verify(), Ok(()), "is_mixing: true"); - - // With wrong input and/or output witnesses, the proof should fail - // to be verified. - let circuit = MyCircuit:: { - in_state: out_state_non_mix, - out_state: out_state_non_mix, - next_mixing: Some(next_input_fp), - }; - - let prover = MockProver::::run(17, &circuit, vec![]).unwrap(); - - assert!(prover.verify().is_err()); - } - } -} diff --git a/keccak256/src/permutation/components.rs b/keccak256/src/permutation/components.rs deleted file mode 100644 index 7529681974..0000000000 --- a/keccak256/src/permutation/components.rs +++ /dev/null @@ -1,710 +0,0 @@ -use eth_types::Field; -use halo2_proofs::{ - circuit::{AssignedCell, Layouter}, - plonk::{Advice, Column, Error}, -}; -use itertools::Itertools; -use std::convert::TryInto; -use std::vec; - -use super::tables::{FromBinaryTableConfig, NUM_OF_BINARY_CHUNKS_PER_SLICE, NUM_OF_BINARY_SLICES}; - -use crate::{ - arith_helpers::{convert_b2_to_b13, convert_b2_to_b9, A1, A2, A3, A4, B13, B2, B9}, - common::{NEXT_INPUTS_LANES, PERMUTATION, ROTATION_CONSTANTS, ROUND_CONSTANTS}, - gate_helpers::{biguint_to_f, f_to_biguint}, - permutation::{ - generic::GenericConfig, - rho_helpers::{slice_lane, RhoLane}, - tables::{ - Base13toBase9TableConfig, FromBase9TableConfig, StackableTable, - NUM_OF_B9_CHUNKS_PER_SLICE, NUM_OF_B9_SLICES, - }, - }, -}; - -use num_bigint::BigUint; - -pub fn assign_theta( - generic: &GenericConfig, - layouter: &mut impl Layouter, - state: &[AssignedCell; 25], -) -> Result<[AssignedCell; 25], Error> { - let theta_col_sums = (0..5) - .map(|x| { - generic.running_sum( - layouter, - (0..5).map(|y| state[5 * x + y].clone()).collect(), - None, - ) - }) - .collect::, Error>>()?; - - let out_state = (0..5) - .cartesian_product(0..5) - .map(|(x, y)| { - let cells = vec![ - state[5 * x + y].clone(), - theta_col_sums[(x + 4) % 5].clone(), - theta_col_sums[(x + 1) % 5].clone(), - ]; - let vs = vec![F::one(), F::one(), F::from(B13 as u64)]; - generic.linear_combine_consts(layouter, cells, vs, None) - }) - .collect::, Error>>()?; - - Ok(out_state.try_into().unwrap()) -} - -pub fn assign_rho( - layouter: &mut impl Layouter, - base13to9_config: &Base13toBase9TableConfig, - generic: &GenericConfig, - stackable: &StackableTable, - state: &[AssignedCell; 25], -) -> Result<[AssignedCell; 25], Error> { - let mut next_state = vec![]; - let mut step2_od_join = vec![]; - let mut step3_od_join = vec![]; - for (lane_idx, lane) in state.iter().enumerate() { - let rotation = { - let x = lane_idx / 5; - let y = lane_idx % 5; - ROTATION_CONSTANTS[x][y] - }; - let (conversions, special) = - RhoLane::new(f_to_biguint(*lane.value().unwrap_or(&F::zero())), rotation) - .get_full_witness(); - let slices = slice_lane(rotation); - - let (input_coefs, mut output_coefs, step2_od, step3_od) = - base13to9_config.assign_region(layouter, &slices, &conversions)?; - - let input_pobs = conversions - .iter() - .map(|c| biguint_to_f::(&c.input.power_of_base)) - .collect_vec(); - - let mut output_pobs = conversions - .iter() - .map(|c| biguint_to_f::(&c.output.power_of_base)) - .collect_vec(); - // Final output power of base - output_pobs.push(biguint_to_f::(&special.output_pob)); - - let input_from_chunks = - generic.linear_combine_consts(layouter, input_coefs, input_pobs, None)?; - let last_chunk = generic.sub_advice(layouter, lane, &input_from_chunks)?; - - let final_output_coef = stackable.lookup_special_chunks(layouter, &last_chunk)?; - output_coefs.push(final_output_coef); - - let output_lane = - generic.linear_combine_consts(layouter, output_coefs, output_pobs, None)?; - next_state.push(output_lane); - step2_od_join.extend(step2_od); - step3_od_join.extend(step3_od); - } - let step2_sum = generic.running_sum(layouter, step2_od_join, None)?; - let step3_sum = generic.running_sum(layouter, step3_od_join, None)?; - stackable.lookup_range_12(layouter, &[step2_sum])?; - stackable.lookup_range_169(layouter, &[step3_sum])?; - Ok(next_state.try_into().unwrap()) -} - -/// The Keccak Pi step -/// -/// It has no gates. We just have to permute the previous state into the correct -/// order. The copy constrain in the next gate can then enforce the Pi step -/// permutation. -pub fn pi_gate_permutation(state: &[AssignedCell; 25]) -> [AssignedCell; 25] { - (0..5) - .cartesian_product(0..5) - .map(|(x, y)| state[5 * ((x + 3 * y) % 5) + x].clone()) - .collect::>() - .try_into() - .unwrap() -} - -pub fn assign_xi( - generic: &GenericConfig, - layouter: &mut impl Layouter, - state: &[AssignedCell; 25], -) -> Result<[AssignedCell; 25], Error> { - let out_state = (0..5) - .cartesian_product(0..5) - .map(|(x, y)| { - let cells = vec![ - state[5 * x + y].clone(), - state[5 * ((x + 1) % 5) + y].clone(), - state[5 * ((x + 2) % 5) + y].clone(), - ]; - let vs = vec![F::from(A1), F::from(A2), F::from(A3)]; - generic.linear_combine_consts(layouter, cells, vs, None) - }) - .collect::, Error>>()?; - Ok(out_state.try_into().unwrap()) -} - -#[derive(Clone, Debug)] -pub struct IotaConstants { - pub round_constant_b13: F, - pub a4_times_round_constants_b9: [F; PERMUTATION], -} - -impl Default for IotaConstants { - fn default() -> Self { - let round_constant_b13 = - biguint_to_f::(&convert_b2_to_b13(ROUND_CONSTANTS[PERMUTATION - 1])); - - let a4_times_round_constants_b9: [F; 24] = ROUND_CONSTANTS - .iter() - .map(|&x| { - let constant = A4 * convert_b2_to_b9(x); - biguint_to_f::(&constant) - }) - .collect_vec() - .try_into() - .unwrap(); - - Self { - round_constant_b13, - a4_times_round_constants_b9, - } - } -} - -pub fn assign_next_input( - layouter: &mut impl Layouter, - next_input_col: &Column, - next_input: &Option<[F; NEXT_INPUTS_LANES]>, -) -> Result<[AssignedCell; NEXT_INPUTS_LANES], Error> { - let next_input_b9 = layouter.assign_region( - || "next input words", - |mut region| { - let next_input = next_input.map_or( - [None; NEXT_INPUTS_LANES], - |v| -> [Option; NEXT_INPUTS_LANES] { - v.map(|vv| Some(vv)) - .iter() - .cloned() - .collect_vec() - .try_into() - .unwrap() - }, - ); - next_input - .iter() - .enumerate() - .map(|(offset, input)| { - region.assign_advice( - || "next input words", - *next_input_col, - offset, - || Ok(input.unwrap_or_default()), - ) - }) - .collect::, Error>>() - }, - )?; - Ok(next_input_b9.try_into().unwrap()) -} - -pub fn convert_to_b9_mul_a4( - layouter: &mut impl Layouter, - from_b2_table: &FromBinaryTableConfig, - generic: &GenericConfig, - next_input: &[AssignedCell; NEXT_INPUTS_LANES], -) -> Result<[AssignedCell; NEXT_INPUTS_LANES], Error> { - let next_input = next_input - .iter() - .map(|input| { - let (base2s, base9s, _) = from_b2_table.assign_region(layouter, input)?; - let vs = (0..NUM_OF_BINARY_SLICES) - .map(|i| { - biguint_to_f( - &BigUint::from(B2).pow((NUM_OF_BINARY_CHUNKS_PER_SLICE * i) as u32), - ) - }) - .rev() - .collect_vec(); - generic.linear_combine_consts(layouter, base2s, vs, Some(input.clone()))?; - let vs = (0..NUM_OF_BINARY_SLICES) - .map(|i| { - biguint_to_f::( - &BigUint::from(B9).pow((NUM_OF_BINARY_CHUNKS_PER_SLICE * i) as u32), - ) * F::from(A4) - }) - .rev() - .collect_vec(); - let output = generic.linear_combine_consts(layouter, base9s, vs, None)?; - Ok(output) - }) - .collect::>, Error>>()?; - let next_input: [AssignedCell; NEXT_INPUTS_LANES] = next_input.try_into().unwrap(); - Ok(next_input) -} - -pub fn convert_from_b9_to_b13( - layouter: &mut impl Layouter, - from_b9_table: &FromBase9TableConfig, - generic: &GenericConfig, - state: [AssignedCell; 25], - output_b2: bool, -) -> Result<([AssignedCell; 25], Option<[AssignedCell; 25]>), Error> { - let (state_b13, state_b2): (Vec>, Vec>>) = state - .iter() - .map(|lane| { - let (base9s, base_13s, base_2s) = from_b9_table.assign_region(layouter, lane)?; - let vs = (0..NUM_OF_B9_SLICES) - .map(|i| { - biguint_to_f(&BigUint::from(B9).pow((NUM_OF_B9_CHUNKS_PER_SLICE * i) as u32)) - }) - .rev() - .collect_vec(); - generic.linear_combine_consts(layouter, base9s, vs, Some(lane.clone()))?; - let vs = (0..NUM_OF_B9_SLICES) - .map(|i| { - biguint_to_f(&BigUint::from(B13).pow((NUM_OF_B9_CHUNKS_PER_SLICE * i) as u32)) - }) - .rev() - .collect_vec(); - let lane_b13 = generic.linear_combine_consts(layouter, base_13s, vs, None)?; - let lane_b2 = if output_b2 { - let vs = (0..NUM_OF_B9_SLICES) - .map(|i| { - biguint_to_f( - &BigUint::from(B2).pow((NUM_OF_B9_CHUNKS_PER_SLICE * i) as u32), - ) - }) - .rev() - .collect_vec(); - let lane_b2 = generic.linear_combine_consts(layouter, base_2s, vs, None)?; - Some(lane_b2) - } else { - None - }; - Ok((lane_b13, lane_b2)) - }) - .collect::, Error>>()? - .iter() - .cloned() - .unzip(); - let state_b2: Option<[AssignedCell; 25]> = state_b2 - .into_iter() - .collect::>>() - .map(|v| v.try_into().unwrap()); - - Ok((state_b13.try_into().unwrap(), state_b2)) -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::arith_helpers::StateBigInt; - use crate::common::*; - use crate::gate_helpers::biguint_to_f; - use crate::keccak_arith::*; - use halo2_proofs::{ - circuit::{Layouter, SimpleFloorPlanner}, - dev::MockProver, - pairing::bn256::Fr as Fp, - plonk::{Advice, Circuit, Column, ConstraintSystem, Error, TableColumn}, - }; - use itertools::Itertools; - use std::convert::TryInto; - use std::marker::PhantomData; - - #[test] - fn test_theta_gates() { - #[derive(Clone, Debug)] - struct MyConfig { - lane: Column, - generic: GenericConfig, - } - - impl MyConfig { - pub fn configure(meta: &mut ConstraintSystem) -> Self { - let advices: [Column; 3] = (0..3) - .map(|_| { - let column = meta.advice_column(); - meta.enable_equality(column); - column - }) - .collect::>() - .try_into() - .unwrap(); - let fixed = meta.fixed_column(); - - let lane = advices[0]; - let generic = GenericConfig::configure(meta, advices, fixed); - Self { lane, generic } - } - } - #[derive(Default)] - struct MyCircuit { - in_state: [F; 25], - out_state: [F; 25], - _marker: PhantomData, - } - impl Circuit for MyCircuit { - type Config = MyConfig; - type FloorPlanner = SimpleFloorPlanner; - - fn without_witnesses(&self) -> Self { - Self::default() - } - - fn configure(meta: &mut ConstraintSystem) -> Self::Config { - // this column is required by `constrain_constant` - let constant = meta.fixed_column(); - meta.enable_constant(constant); - Self::Config::configure(meta) - } - - fn synthesize( - &self, - config: Self::Config, - mut layouter: impl Layouter, - ) -> Result<(), Error> { - let in_state = layouter.assign_region( - || "Wittnes & assignation", - |mut region| { - // Witness `state` - let in_state: [AssignedCell; 25] = { - let mut state: Vec> = Vec::with_capacity(25); - for (offset, val) in self.in_state.iter().enumerate() { - let cell = region.assign_advice( - || "witness input state", - config.lane, - offset, - || Ok(*val), - )?; - state.push(cell) - } - state.try_into().unwrap() - }; - Ok(in_state) - }, - )?; - - let out_state = assign_theta(&config.generic, &mut layouter, &in_state)?; - - layouter.assign_region( - || "Check outstate", - |mut region| { - for (assigned, value) in out_state.iter().zip(self.out_state.iter()) { - region.constrain_constant(assigned.cell(), value)?; - } - Ok(()) - }, - )?; - Ok(()) - } - } - - let input1: State = [ - [1, 0, 0, 0, 0], - [0, 0, 0, 9223372036854775808, 0], - [0, 0, 0, 0, 0], - [0, 0, 0, 0, 0], - [0, 0, 0, 0, 0], - ]; - let mut in_biguint = StateBigInt::default(); - let mut in_state: [Fp; 25] = [Fp::zero(); 25]; - - for (x, y) in (0..5).cartesian_product(0..5) { - in_biguint[(x, y)] = convert_b2_to_b13(input1[x][y]); - in_state[5 * x + y] = biguint_to_f(&in_biguint[(x, y)]); - } - let s1_arith = KeccakFArith::theta(&in_biguint); - let mut out_state: [Fp; 25] = [Fp::zero(); 25]; - for (x, y) in (0..5).cartesian_product(0..5) { - out_state[5 * x + y] = biguint_to_f(&s1_arith[(x, y)]); - } - - let circuit = MyCircuit:: { - in_state, - out_state, - _marker: PhantomData, - }; - - // Test without public inputs - let prover = MockProver::::run(9, &circuit, vec![]).unwrap(); - - assert_eq!(prover.verify(), Ok(())); - - let mut out_state2 = out_state; - out_state2[0] = Fp::from(5566u64); - - let circuit2 = MyCircuit:: { - in_state, - out_state: out_state2, - _marker: PhantomData, - }; - - let prover = MockProver::::run(9, &circuit2, vec![]).unwrap(); - assert!(prover.verify().is_err()); - } - - #[test] - fn test_rho_gate() { - #[derive(Default)] - struct MyCircuit { - in_state: [F; 25], - out_state: [F; 25], - } - - #[derive(Clone)] - struct MyConfig { - advice: Column, - generic: GenericConfig, - stackable: StackableTable, - base13to9_config: Base13toBase9TableConfig, - } - impl Circuit for MyCircuit { - type Config = MyConfig; - type FloorPlanner = SimpleFloorPlanner; - - fn without_witnesses(&self) -> Self { - Self::default() - } - - fn configure(meta: &mut ConstraintSystem) -> Self::Config { - let advices: [Column; 3] = (0..3) - .map(|_| meta.advice_column()) - .collect::>() - .try_into() - .unwrap(); - - let fixed = meta.fixed_column(); - let stackable_cols: [TableColumn; 3] = (0..3) - .map(|_| meta.lookup_table_column()) - .collect_vec() - .try_into() - .unwrap(); - let base13to9_cols: [TableColumn; 3] = (0..3) - .map(|_| meta.lookup_table_column()) - .collect_vec() - .try_into() - .unwrap(); - let stackable = StackableTable::configure(meta, advices, stackable_cols); - let generic = GenericConfig::configure(meta, advices, fixed); - let base13to9_config = - Base13toBase9TableConfig::configure(meta, advices, base13to9_cols); - - Self::Config { - advice: advices[0], - generic, - stackable, - base13to9_config, - } - } - - fn synthesize( - &self, - mut config: Self::Config, - mut layouter: impl Layouter, - ) -> Result<(), Error> { - config.base13to9_config.load(&mut layouter)?; - config.stackable.load(&mut layouter)?; - let state = layouter.assign_region( - || "assign input state", - |mut region| { - let state = self - .in_state - .iter() - .enumerate() - .map(|(offset, &value)| { - region.assign_advice(|| "lane", config.advice, offset, || Ok(value)) - }) - .collect::>, Error>>()?; - - Ok(state.try_into().unwrap()) - }, - )?; - let out_state = assign_rho( - &mut layouter, - &config.base13to9_config, - &config.generic, - &config.stackable, - &state, - )?; - layouter.assign_region( - || "check final states", - |mut region| { - for (assigned, value) in out_state.iter().zip(self.out_state.iter()) { - region.constrain_constant(assigned.cell(), value)?; - } - Ok(()) - }, - )?; - - Ok(()) - } - } - - let input1: State = [ - [102, 111, 111, 98, 97], - [114, 0, 5, 0, 0], - [0, 0, 0, 0, 0], - [0, 0, 0, 5, 0], - [0, 0, 0, 0, 0], - ]; - let mut in_biguint = StateBigInt::default(); - let mut in_state: [Fp; 25] = [Fp::zero(); 25]; - - for (x, y) in (0..5).cartesian_product(0..5) { - in_biguint[(x, y)] = convert_b2_to_b13(input1[x][y]); - } - let s0_arith = KeccakFArith::theta(&in_biguint); - for (x, y) in (0..5).cartesian_product(0..5) { - in_state[5 * x + y] = biguint_to_f(&s0_arith[(x, y)]); - } - let s1_arith = KeccakFArith::rho(&s0_arith); - let mut out_state: [Fp; 25] = [Fp::zero(); 25]; - for (x, y) in (0..5).cartesian_product(0..5) { - out_state[5 * x + y] = biguint_to_f(&s1_arith[(x, y)]); - } - let circuit = MyCircuit:: { - in_state, - out_state, - }; - let k = 15; - #[cfg(feature = "dev-graph")] - { - use plotters::prelude::*; - let root = - BitMapBackend::new("rho-test-circuit.png", (1024, 16384)).into_drawing_area(); - root.fill(&WHITE).unwrap(); - let root = root.titled("Rho", ("sans-serif", 60)).unwrap(); - halo2_proofs::dev::CircuitLayout::default() - .render(k, &circuit, &root) - .unwrap(); - } - // Test without public inputs - let prover = MockProver::::run(k, &circuit, vec![]).unwrap(); - - assert_eq!(prover.verify(), Ok(())); - } - - #[test] - fn test_xi_gate() { - #[derive(Clone, Debug)] - struct MyConfig { - lane: Column, - generic: GenericConfig, - } - - impl MyConfig { - pub fn configure(meta: &mut ConstraintSystem) -> Self { - let advices: [Column; 3] = (0..3) - .map(|_| { - let column = meta.advice_column(); - meta.enable_equality(column); - column - }) - .collect::>() - .try_into() - .unwrap(); - let fixed = meta.fixed_column(); - - let lane = advices[0]; - let generic = GenericConfig::configure(meta, advices, fixed); - Self { lane, generic } - } - } - #[derive(Default)] - struct MyCircuit { - in_state: [F; 25], - out_state: [F; 25], - _marker: PhantomData, - } - - impl Circuit for MyCircuit { - type Config = MyConfig; - type FloorPlanner = SimpleFloorPlanner; - - fn without_witnesses(&self) -> Self { - Self::default() - } - - fn configure(meta: &mut ConstraintSystem) -> Self::Config { - // this column is required by `constrain_constant` - let constant = meta.fixed_column(); - meta.enable_constant(constant); - Self::Config::configure(meta) - } - - fn synthesize( - &self, - config: Self::Config, - mut layouter: impl Layouter, - ) -> Result<(), Error> { - let in_state = layouter.assign_region( - || "Wittnes & assignation", - |mut region| { - // Witness `state` - let in_state: [AssignedCell; 25] = { - let mut state: Vec> = Vec::with_capacity(25); - for (offset, val) in self.in_state.iter().enumerate() { - let cell = region.assign_advice( - || "witness input state", - config.lane, - offset, - || Ok(*val), - )?; - state.push(cell) - } - state.try_into().unwrap() - }; - Ok(in_state) - }, - )?; - - let out_state = assign_xi(&config.generic, &mut layouter, &in_state)?; - - layouter.assign_region( - || "Check outstate", - |mut region| { - for (assigned, value) in out_state.iter().zip(self.out_state.iter()) { - region.constrain_constant(assigned.cell(), value)?; - } - Ok(()) - }, - )?; - Ok(()) - } - } - - let input1: State = [ - [1, 0, 0, 0, 0], - [0, 0, 0, 0, 0], - [0, 0, 0, 0, 0], - [0, 0, 0, 0, 0], - [0, 0, 0, 0, 0], - ]; - let mut in_biguint = StateBigInt::default(); - let mut in_state: [Fp; 25] = [Fp::zero(); 25]; - - for (x, y) in (0..5).cartesian_product(0..5) { - in_biguint[(x, y)] = convert_b2_to_b9(input1[x][y]); - in_state[5 * x + y] = biguint_to_f(&in_biguint[(x, y)]); - } - let s1_arith = KeccakFArith::xi(&in_biguint); - let mut out_state: [Fp; 25] = [Fp::zero(); 25]; - for (x, y) in (0..5).cartesian_product(0..5) { - out_state[5 * x + y] = biguint_to_f(&s1_arith[(x, y)]); - } - let circuit = MyCircuit:: { - in_state, - out_state, - _marker: PhantomData, - }; - - // Test without public inputs - let prover = MockProver::::run(9, &circuit, vec![]).unwrap(); - - assert_eq!(prover.verify(), Ok(())); - } -} diff --git a/keccak256/src/permutation/generic.rs b/keccak256/src/permutation/generic.rs deleted file mode 100644 index 8a2d264b4b..0000000000 --- a/keccak256/src/permutation/generic.rs +++ /dev/null @@ -1,315 +0,0 @@ -use eth_types::Field; -use halo2_proofs::{ - circuit::{AssignedCell, Layouter}, - plonk::{Advice, Column, ConstraintSystem, Error, Fixed, Selector}, - poly::Rotation, -}; -use itertools::Itertools; -use std::marker::PhantomData; - -/// A versatile gate to do running sum, conditional add, and linear combination, -/// etc. -#[derive(Clone, Debug)] -pub struct GenericConfig { - q_enable: Selector, - io: Column, - left: Column, - right: Column, - _marker: PhantomData, -} - -#[allow(dead_code)] -impl GenericConfig { - pub fn configure( - meta: &mut ConstraintSystem, - advices: [Column; 3], - fixed: Column, - ) -> Self { - let q_enable = meta.selector(); - let [io, left, right] = advices; - meta.enable_equality(io); - meta.enable_equality(left); - meta.enable_equality(right); - meta.enable_constant(fixed); - - meta.create_gate("add", |meta| { - let q_enable = meta.query_selector(q_enable); - let input = meta.query_advice(io, Rotation::cur()); - let output = meta.query_advice(io, Rotation::next()); - let left = meta.query_advice(left, Rotation::cur()); - let right = meta.query_advice(right, Rotation::cur()); - vec![q_enable * (output - input - left * right)] - }); - - Self { - q_enable, - io, - left, - right, - _marker: PhantomData, - } - } - - fn add_generic( - &self, - layouter: &mut impl Layouter, - input: Option<&AssignedCell>, - left: Option<&AssignedCell>, - right: Option<&AssignedCell>, - value: Option<&F>, - ) -> Result, Error> { - layouter.assign_region( - || "add advice", - |mut region| { - let offset = 0; - self.q_enable.enable(&mut region, offset)?; - let input = input - .as_ref() - .map(|input| input.copy_advice(|| "input", &mut region, self.io, offset)) - .unwrap_or_else(|| { - region.assign_advice_from_constant( - || "input is 0", - self.io, - offset, - F::zero(), - ) - })?; - - let left = left - .as_ref() - .map(|x| - // copy x to use as a flag - x.copy_advice(|| "left adv", &mut region, self.left, offset)) - .unwrap_or_else(|| { - // constrain advice to 1 for a simple add. - region.assign_advice_from_constant( - || "left const", - self.left, - offset, - F::one(), - ) - })?; - - let right = right - .as_ref() - .map(|right| { - if value.is_some() { - panic!("right and value can't be both some"); - } - right.copy_advice(|| "right adv", &mut region, self.right, offset) - }) - .unwrap_or_else(|| { - value - .map(|&value| { - region.assign_advice_from_constant( - || "fixed value", - self.right, - offset, - value, - ) - }) - .unwrap_or_else(|| { - // constrain fixed to 1 for a simple add. - region.assign_advice_from_constant( - || "fixed value", - self.right, - offset, - F::one(), - ) - }) - })?; - - let offset = 1; - region.assign_advice( - || "input + x", - self.io, - offset, - || { - input - .value() - .zip(left.value()) - .zip(right.value()) - .map(|((&input, &left), &right)| input + left * right) - .ok_or(Error::Synthesis) - }, - ) - }, - ) - } - /// input += v * x - pub fn add_advice_mul_const( - &self, - layouter: &mut impl Layouter, - input: &AssignedCell, - x: &AssignedCell, - v: &F, - ) -> Result, Error> { - self.add_generic(layouter, Some(input), Some(x), None, Some(v)) - } - /// input -= x - pub fn sub_advice( - &self, - layouter: &mut impl Layouter, - input: &AssignedCell, - x: &AssignedCell, - ) -> Result, Error> { - self.add_generic(layouter, Some(input), Some(x), None, Some(&(-F::one()))) - } - /// input += v - pub fn add_fixed( - &self, - layouter: &mut impl Layouter, - input: &AssignedCell, - value: &F, - ) -> Result, Error> { - self.add_generic(layouter, Some(input), None, None, Some(value)) - } - /// output = input * v - pub fn mul_fixed( - &self, - layouter: &mut impl Layouter, - input: &AssignedCell, - value: &F, - ) -> Result, Error> { - self.add_generic(layouter, None, Some(input), None, Some(value)) - } - /// input += flag * v - /// No boolean check on the flag, we assume the flag is checked before - /// copied to here - pub fn conditional_add_const( - &self, - layouter: &mut impl Layouter, - input: &AssignedCell, - flag: &AssignedCell, - value: &F, - ) -> Result, Error> { - self.add_generic(layouter, Some(input), Some(flag), None, Some(value)) - } - /// input += flag * x - /// No boolean check on the flag, we assume the flag is checked before - /// copied to here - pub fn conditional_add_advice( - &self, - layouter: &mut impl Layouter, - input: &AssignedCell, - flag: &AssignedCell, - x: &AssignedCell, - ) -> Result, Error> { - self.add_generic(layouter, Some(input), Some(flag), Some(x), None) - } - fn linear_combine_generic( - &self, - layouter: &mut impl Layouter, - xs: Vec>, - ys: Option>>, - vs: Option>, - outcome: Option>, - ) -> Result, Error> { - debug_assert_eq!( - ys.is_some(), - vs.is_none(), - "They can't both some or both none" - ); - if let Some(ref vs) = vs { - debug_assert_eq!(xs.len(), vs.len()); - } - if let Some(ref ys) = ys { - debug_assert_eq!(xs.len(), ys.len()); - } - layouter.assign_region( - || "linear combine", - |mut region| { - // | offset | input | x | y | - // | ------ | -----------: | -------: | ------: | - // | 0 | 0 | x0 | y0 | - // | 1 | x0y0 | x1 | y1 | - // | 2 | x0y0 + x1y1 | x2 | y2 | - // | ... | ... | ... | ... | - // | N - 1 | | x_(N-1) | y_(N-1) | - // | N | (sum) | | | - let mut acc = - region.assign_advice_from_constant(|| "input 0", self.io, 0, F::zero())?; - - let mut sum = F::zero(); - for (offset, x) in xs.iter().enumerate() { - self.q_enable.enable(&mut region, offset)?; - x.copy_advice(|| "x", &mut region, self.left, offset)?; - let right = vs - .as_ref() - .map(|vs| { - region.assign_advice_from_constant( - || "v", - self.right, - offset, - vs[offset], - ) - }) - .unwrap_or_else(|| { - ys.as_ref() - .map(|ys| { - ys[offset].copy_advice(|| "y", &mut region, self.right, offset) - }) - .expect("ys should have something") - })?; - acc = region.assign_advice( - || "accumulation", - self.io, - offset + 1, - || { - sum += x - .value() - .zip(right.value()) - .map(|(&x, &right)| x * right) - .ok_or(Error::Synthesis)?; - Ok(sum) - }, - )?; - } - if let Some(outcome) = &outcome { - region.constrain_equal(outcome.cell(), acc.cell())?; - } - if let Some((outcome, acc)) = - outcome.as_ref().and_then(|oc| oc.value().zip(acc.value())) - { - debug_assert_eq!(outcome, acc); - } - Ok(acc) - }, - ) - } - - pub fn linear_combine_consts( - &self, - layouter: &mut impl Layouter, - xs: Vec>, - vs: Vec, - outcome: Option>, - ) -> Result, Error> { - self.linear_combine_generic(layouter, xs, None, Some(vs), outcome) - } - - pub fn linear_combine_advices( - &self, - layouter: &mut impl Layouter, - xs: Vec>, - ys: Vec>, - outcome: Option>, - ) -> Result, Error> { - self.linear_combine_generic(layouter, xs, Some(ys), None, outcome) - } - - pub fn running_sum( - &self, - layouter: &mut impl Layouter, - xs: Vec>, - outcome: Option>, - ) -> Result, Error> { - let len = xs.len(); - self.linear_combine_consts( - layouter, - xs, - (0..len).map(|_| F::one()).collect_vec(), - outcome, - ) - } -} diff --git a/keccak256/src/permutation/rho_helpers.rs b/keccak256/src/permutation/rho_helpers.rs deleted file mode 100644 index a278735e15..0000000000 --- a/keccak256/src/permutation/rho_helpers.rs +++ /dev/null @@ -1,330 +0,0 @@ -use crate::{ - arith_helpers::{convert_b13_coef, convert_b13_lane_to_b9, B13, B9}, - common::LANE_SIZE, -}; -use itertools::Itertools; -use num_bigint::BigUint; -use num_traits::Zero; - -pub const BASE_NUM_OF_CHUNKS: u32 = 4; - -/// Determine how many chunks in a step -/// -/// Usually it's a step of 4 chunks, but the number of chunks could be less near -/// the rotation position and the end of the lane. -pub fn get_step_size(chunk_idx: u32, rotation: u32) -> u32 { - // near the rotation offset position of the lane - let offset = LANE_SIZE - rotation; - if chunk_idx < offset && offset < chunk_idx + BASE_NUM_OF_CHUNKS { - return offset - chunk_idx; - } - // near the end of the lane - if chunk_idx < LANE_SIZE && LANE_SIZE < chunk_idx + BASE_NUM_OF_CHUNKS { - return LANE_SIZE - chunk_idx; - } - BASE_NUM_OF_CHUNKS -} - -/// Slice the lane into chunk indices and steps -/// -/// We ask what's the current chunk index and the step we need to go to the next -/// chunk index. We start chunk_idx from 1 because the 0th chunk is from the low -/// value from the theta step. -pub fn slice_lane(rotation: u32) -> Vec<(u32, u32)> { - let mut chunk_idx = 1; - let mut output = vec![]; - while chunk_idx < LANE_SIZE { - let step = get_step_size(chunk_idx, rotation); - output.push((chunk_idx, step)); - chunk_idx += step; - } - output -} - -/// A mapping from `step` to a overflow detector value -/// -/// See tests for the derivation of the values -pub const OVERFLOW_TRANSFORM: [u32; 5] = [0, 0, 1, 13, 170]; - -/// The sum of the step 2 overflow detectors across all 25 lanes should not -/// greater than this value -/// -/// See tests for the derivation of the values -pub const STEP2_RANGE: u64 = 12; - -/// The sum of the step 3 overflow detectors across all 25 lanes should not -/// greater than this value -/// -/// See tests for the derivation of the values -pub const STEP3_RANGE: u64 = 169; - -/// Get the overflow detector from an input chunks -/// -/// The input is chunks of a base 13 number in big endian. -/// For example, if the input is `[1, 12, 3, 7]`, it represents a coefficient -/// `1*13^3 + 12*13^2 + 3*13 + 7`. The example only happens when `step = 4`. If -/// we have a `step = 3`, the first chunk must be 0. It could be the case that -/// we have `step = 4`, but all of the chunks are 0. That would result our -/// overflow detector value to be 0. -/// -/// In the circuit, if we have a `step = 3`, but a non-zero first chunk is -/// adviced. It would cause the non_zero_chunk_count to be 4, resulting the -/// overflow detector to be 170. -/// -/// This would fail the final overflow detector check. -pub fn get_overflow_detector(b13_chunks: [u8; BASE_NUM_OF_CHUNKS as usize]) -> u32 { - // could be 0, 1, 2, 3, 4 - let non_zero_chunk_count = - BASE_NUM_OF_CHUNKS as usize - b13_chunks.iter().take_while(|x| **x == 0).count(); - // could be 0, 0, 1, 13, 170 - OVERFLOW_TRANSFORM[non_zero_chunk_count] -} - -#[derive(Debug, Clone)] -pub struct Slice { - pub coef: BigUint, - pub power_of_base: BigUint, - pub pre_acc: BigUint, -} - -#[derive(Debug, Clone)] -pub struct OverflowDetector { - pub value: u32, - pub step2_acc: u32, - pub step3_acc: u32, -} - -#[derive(Debug, Clone)] -pub struct Conversion { - pub input: Slice, - pub output: Slice, - pub overflow_detector: OverflowDetector, -} - -#[derive(Debug, Clone)] -pub struct Special { - pub input: BigUint, - pub output_acc_pre: BigUint, - pub output_acc_post: BigUint, - pub output_coef: u8, - pub output_pob: BigUint, -} - -const RHO_LANE_SIZE: usize = 65; - -#[derive(Debug, Clone)] -pub struct RhoLane { - // base 13. 65 chunks - input: BigUint, - // base 9 - pub output: BigUint, - rotation: u32, - // base13 in little endian - chunks: [u8; RHO_LANE_SIZE], - special_high: u8, - special_low: u8, -} - -impl RhoLane { - pub fn new(input: BigUint, rotation: u32) -> Self { - debug_assert!( - input.lt(&BigUint::from(B13).pow(RHO_LANE_SIZE as u32)), - "lane too big" - ); - let mut chunks = input.to_radix_le(B13.into()); - chunks.resize(RHO_LANE_SIZE, 0); - let chunks: [u8; RHO_LANE_SIZE] = chunks.try_into().unwrap(); - let special_high = *chunks.get(64).unwrap(); - let special_low = *chunks.first().unwrap(); - debug_assert!(special_high + special_low < B13, "invalid Rho input lane"); - let output = convert_b13_lane_to_b9(input.clone(), rotation); - - Self { - input, - output, - rotation, - chunks, - special_high, - special_low, - } - } - - pub fn get_full_witness(&self) -> (Vec, Special) { - let mut input_acc = self.input.clone(); - let mut output_acc = BigUint::zero(); - let mut step2_acc: u32 = 0; - let mut step3_acc: u32 = 0; - let conversions: Vec = slice_lane(self.rotation) - .iter() - .map(|&(chunk_idx, step)| { - let chunks = self - .chunks - .get(chunk_idx as usize..(chunk_idx + step) as usize) - .unwrap(); - let input = { - let coef = BigUint::from_radix_le(chunks, B13.into()).unwrap_or_default(); - let power_of_base = BigUint::from(B13).pow(chunk_idx); - let pre_acc = input_acc.clone(); - input_acc -= &coef * &power_of_base; - Slice { - coef, - power_of_base, - pre_acc, - } - }; - let output = { - let converted_chunks = - chunks.iter().map(|&x| convert_b13_coef(x)).collect_vec(); - let coef = - BigUint::from_radix_le(&converted_chunks, B9.into()).unwrap_or_default(); - let power = (chunk_idx + self.rotation) % LANE_SIZE; - let power_of_base = BigUint::from(B9).pow(power); - let pre_acc = output_acc.clone(); - output_acc += &coef * &power_of_base; - Slice { - coef, - power_of_base, - pre_acc, - } - }; - let overflow_detector = { - let mut v = chunks.to_vec(); - // pad to 4 chunks - v.resize(BASE_NUM_OF_CHUNKS as usize, 0); - // to big endian - v.reverse(); - let chunks_be: [u8; BASE_NUM_OF_CHUNKS as usize] = v.try_into().unwrap(); - let value = get_overflow_detector(chunks_be); - match step { - 2 => step2_acc += value, - 3 => step3_acc += value, - _ => {} - }; - OverflowDetector { - value, - step2_acc, - step3_acc, - } - }; - Conversion { - input, - output, - overflow_detector, - } - }) - .collect_vec(); - self.sanity_check(&input_acc); - let special = { - let input = input_acc; - let output_acc_pre = output_acc; - let output_coef = convert_b13_coef(self.special_high + self.special_low); - let output_pob = BigUint::from(B9 as u64).pow(self.rotation); - let output_acc_post = &output_acc_pre + output_coef * output_pob.clone(); - Special { - input, - output_acc_pre, - output_acc_post, - output_coef, - output_pob, - } - }; - (conversions, special) - } - - /// After we run down the input accumulator for the normal chunks, - /// the remaining value should be equal to what the special chunks - /// represent - fn sanity_check(&self, input_acc: &BigUint) { - let expect = (self.special_low as u64) - + (self.special_high as u64) * BigUint::from(B13).pow(LANE_SIZE); - assert_eq!( - *input_acc, expect, - "input_acc got: {:?} expect: {:?} = low({:?}) + high({:?}) * 13**64", - input_acc, expect, self.special_low, self.special_high, - ); - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::arith_helpers::B2; - use crate::common::ROTATION_CONSTANTS; - - /// We have 12 step 1, 12 step 2, and 13 step 3 - /// - /// See tests for more detail - const STEP_COUNTS: [u32; 3] = [12, 12, 13]; - - #[test] - fn test_overflow_counting() { - // counting how many step 1, step 2, and step 3 in the lane slices. - let mut counts = vec![0; BASE_NUM_OF_CHUNKS as usize - 1]; - for rotation in ROTATION_CONSTANTS.iter().flat_map(|r| r.iter()) { - let chunks = slice_lane(*rotation); - for (_, step) in chunks.iter() { - if *step < BASE_NUM_OF_CHUNKS { - counts[*step as usize - 1] += 1; - } - } - } - // We know exactly at setup time there would be 12 step 1, 12 step 2 and - // 13 step 3. - assert_eq!(counts, STEP_COUNTS); - - // We define a mapping overflow g(x), it maps step to a overflow - // detector value We first define g(0) = 0, g(1) = 0 - // Mapping from step 0 is meaningless, because we don't have step 0 - // Mapping step 1 to 0 as the base case. - // Then we define `g(i+1) = g(i) * previous_step_count + 1` - // Because `g(i) * previous_step_count` is the max possible overflow - // detector sum from previous step An overflow in previous step - // would get the `g(i+1)` value from the lookup table and fail - // the final range check - let mut overflow = vec![0, 0]; - for c in counts.iter() { - let elem = overflow.last().cloned().unwrap(); - overflow.push(c * elem + 1); - } - assert_eq!(overflow, OVERFLOW_TRANSFORM); - - let step2 = 2; - assert_eq!( - STEP2_RANGE, - u64::from(STEP_COUNTS[step2 - 1] * OVERFLOW_TRANSFORM[step2]) - ); - - let step3 = 3; - assert_eq!( - STEP3_RANGE, - u64::from(STEP_COUNTS[step3 - 1] * OVERFLOW_TRANSFORM[step3]) - ); - } - #[test] - fn test_rho_lane_rotation() { - // Chosen such that special chunks are all 0 - // The special chunks transformed (high+low) value is 0 too - let rho_arith_input_chunks = [0, 5, 4, 3, 2, 1]; - let rho_arith_lane = - BigUint::from_radix_le(&rho_arith_input_chunks, B13.into()).unwrap_or_default(); - let rho_chunks_transformed_no_special = [5, 4, 3, 2, 1] - .iter() - .map(|&x| convert_b13_coef(x)) - .collect_vec(); - assert_eq!(rho_chunks_transformed_no_special, [1, 0, 1, 0, 1]); - // We need to add back the transformed value of special chunks. - let rho_chunks_transformed = [0, 1, 0, 1, 0, 1]; - let rho_bin_input: u64 = BigUint::from_radix_le(&rho_chunks_transformed, B2.into()) - .unwrap_or_default() - .iter_u64_digits() - .collect_vec()[0]; - assert_eq!(rho_bin_input, 42); - - let rotation = 5; - let lane = RhoLane::new(rho_arith_lane, rotation); - - let (conversions, special) = lane.get_full_witness(); - assert_eq!(conversions.len(), slice_lane(rotation).len()); - assert_eq!(special.output_acc_post, lane.output); - } -} diff --git a/keccak256/src/permutation/tables.rs b/keccak256/src/permutation/tables.rs deleted file mode 100644 index 7fffe593e8..0000000000 --- a/keccak256/src/permutation/tables.rs +++ /dev/null @@ -1,750 +0,0 @@ -use crate::arith_helpers::{convert_b13_coef, convert_b9_coef, f_from_radix_be, B13, B2, B9}; -use crate::common::LANE_SIZE; -use crate::gate_helpers::{biguint_to_f, f_to_biguint}; -use crate::permutation::rho_helpers::{get_overflow_detector, BASE_NUM_OF_CHUNKS}; -use eth_types::Field; -use halo2_proofs::{ - circuit::{AssignedCell, Layouter, Table}, - plonk::{Advice, Column, ConstraintSystem, Error, Selector, TableColumn}, - poly::Rotation, -}; -use itertools::Itertools; -use std::collections::HashMap; -use std::marker::PhantomData; -use strum_macros::{Display, EnumIter}; - -use super::rho_helpers::{Conversion, STEP2_RANGE, STEP3_RANGE}; - -const MAX_CHUNKS: usize = 64; -pub const NUM_OF_BINARY_CHUNKS_PER_SLICE: usize = 16; -pub const NUM_OF_BINARY_SLICES: usize = 4; -pub const NUM_OF_B9_CHUNKS_PER_SLICE: usize = 5; -/// is ceil(`MAX_CHUNKS`/ `NUM_OF_B9_CHUNKS_PER_SLICE`) = 13 -pub const NUM_OF_B9_SLICES: usize = 13; - -#[derive(Debug, Clone)] -struct ThreeColumnsLookup { - q_enable: Selector, - pub(crate) cols: [(Column, TableColumn); 3], - _marker: PhantomData, -} -impl ThreeColumnsLookup { - pub(crate) fn configure( - meta: &mut ConstraintSystem, - adv_cols: [Column; 3], - table_cols: [TableColumn; 3], - name: &'static str, - ) -> Self { - let cols: [(Column, TableColumn); 3] = adv_cols - .iter() - .cloned() - .zip(table_cols.iter().cloned()) - .collect_vec() - .try_into() - .unwrap(); - let q_enable = meta.complex_selector(); - meta.lookup(name, |meta| { - let q_enable = meta.query_selector(q_enable); - let col0_adv = meta.query_advice(cols[0].0, Rotation::cur()); - let col1_adv = meta.query_advice(cols[1].0, Rotation::cur()); - let col2_adv = meta.query_advice(cols[2].0, Rotation::cur()); - - vec![ - (q_enable.clone() * col0_adv, cols[0].1), - (q_enable.clone() * col1_adv, cols[1].1), - (q_enable * col2_adv, cols[2].1), - ] - }); - Self { - q_enable, - cols, - _marker: PhantomData, - } - } -} - -#[derive(EnumIter, Display, Clone, Copy)] -enum TableTags { - Range12 = 0, - Range169, - SpecialChunk, - BooleanFlag, -} - -#[derive(Debug, Clone)] -pub struct StackableTable { - lookup_config: ThreeColumnsLookup, - special_chunks_map: HashMap<[u8; 32], F>, -} - -impl StackableTable { - /// We use col0 for tag that restricts the lookup into certain rows - /// we use col1 and col2 for different purposes depend on the tag - pub(crate) fn configure( - meta: &mut ConstraintSystem, - adv_cols: [Column; 3], - table_cols: [TableColumn; 3], - ) -> Self { - let lookup_config = - ThreeColumnsLookup::configure(meta, adv_cols, table_cols, "stackable lookup"); - let special_chunks_map = HashMap::new(); - Self { - lookup_config, - special_chunks_map, - } - } - - fn load_range( - &self, - table: &mut Table, - offset: usize, - tag: TableTags, - k: u64, - ) -> Result { - let mut offset = offset; - for i in 0..=k { - table.assign_cell( - || format!("tag range{}", tag), - self.lookup_config.cols[0].1, - offset, - || Ok(F::from(tag as u64)), - )?; - table.assign_cell( - || format!("range{}", tag), - self.lookup_config.cols[1].1, - offset, - || Ok(F::from(i)), - )?; - table.assign_cell( - || format!("dummy col range{}", tag), - self.lookup_config.cols[2].1, - offset, - || Ok(F::zero()), - )?; - offset += 1; - } - Ok(offset) - } - /// The table describes all possible combinations of these two variables: - /// - The last input accumulator: `high_value`*(13**64) + `low_value`, and - /// - The last output coef: `convert_b13_coef(high_value + low_value)` - fn load_special_chunks(&mut self, table: &mut Table, offset: usize) -> Result { - let mut offset = offset; - for i in 0..B13 { - for j in 0..(B13 - i) { - let (low, high) = (i, j); - let last_chunk = F::from(low as u64) - + F::from(high as u64) * F::from(B13 as u64).pow(&[LANE_SIZE as u64, 0, 0, 0]); - let output_coef = F::from(convert_b13_coef(low + high) as u64); - self.special_chunks_map - .insert(last_chunk.to_repr(), output_coef); - table.assign_cell( - || "tag special chunks", - self.lookup_config.cols[0].1, - offset, - || Ok(F::from(TableTags::SpecialChunk as u64)), - )?; - table.assign_cell( - || "last chunk", - self.lookup_config.cols[1].1, - offset, - || Ok(last_chunk), - )?; - table.assign_cell( - || "output coef", - self.lookup_config.cols[2].1, - offset, - || Ok(output_coef), - )?; - offset += 1; - } - } - Ok(offset) - } - - fn load_boolean_flag(&self, table: &mut Table, offset: usize) -> Result { - let mut offset = offset; - for (left, right) in [(true, false), (false, true)] { - table.assign_cell( - || "tag boolean flag", - self.lookup_config.cols[0].1, - offset, - || Ok(F::from(TableTags::BooleanFlag as u64)), - )?; - table.assign_cell( - || "left", - self.lookup_config.cols[1].1, - offset, - || Ok(F::from(left)), - )?; - table.assign_cell( - || "right", - self.lookup_config.cols[2].1, - offset, - || Ok(F::from(right)), - )?; - offset += 1; - } - Ok(offset) - } - pub(crate) fn load(&mut self, layouter: &mut impl Layouter) -> Result<(), Error> { - layouter.assign_table( - || "stackable", - |mut table| { - let mut offset = 0; - for &(tag, k) in [ - (TableTags::Range12, STEP2_RANGE), - (TableTags::Range169, STEP3_RANGE), - ] - .iter() - { - offset = self.load_range(&mut table, offset, tag, k)?; - } - offset = self.load_special_chunks(&mut table, offset)?; - self.load_boolean_flag(&mut table, offset)?; - Ok(()) - }, - ) - } - - fn lookup_range( - &self, - layouter: &mut impl Layouter, - values: &[AssignedCell], - tag: TableTags, - ) -> Result<(), Error> { - layouter.assign_region( - || format!("lookup for {}", tag), - |mut region| { - let tag = F::from(tag as u64); - for (offset, v) in values.iter().enumerate() { - self.lookup_config.q_enable.enable(&mut region, offset)?; - region.assign_advice_from_constant( - || "tag", - self.lookup_config.cols[0].0, - offset, - tag, - )?; - v.copy_advice( - || "value", - &mut region, - self.lookup_config.cols[1].0, - offset, - )?; - region.assign_advice_from_constant( - || "dummy", - self.lookup_config.cols[2].0, - offset, - F::zero(), - )?; - } - Ok(()) - }, - ) - } - pub(crate) fn lookup_range_12( - &self, - layouter: &mut impl Layouter, - values: &[AssignedCell], - ) -> Result<(), Error> { - self.lookup_range(layouter, values, TableTags::Range12) - } - pub(crate) fn lookup_range_169( - &self, - layouter: &mut impl Layouter, - values: &[AssignedCell], - ) -> Result<(), Error> { - self.lookup_range(layouter, values, TableTags::Range169) - } - - pub(crate) fn lookup_special_chunks( - &self, - layouter: &mut impl Layouter, - last_chunk: &AssignedCell, - ) -> Result, Error> { - layouter.assign_region( - || "lookup for special chunks", - |mut region| { - let offset = 0; - let tag = F::from(TableTags::SpecialChunk as u64); - self.lookup_config.q_enable.enable(&mut region, offset)?; - region.assign_advice_from_constant( - || "tag", - self.lookup_config.cols[0].0, - offset, - tag, - )?; - last_chunk.copy_advice( - || "last chunk", - &mut region, - self.lookup_config.cols[1].0, - offset, - )?; - region.assign_advice( - || "output coef", - self.lookup_config.cols[2].0, - offset, - || { - last_chunk - .value() - .and_then(|&v| self.special_chunks_map.get(&v.to_repr())) - .map(|v| v.to_owned()) - .ok_or(Error::Synthesis) - }, - ) - }, - ) - } - /// Output two boolean cells. Prover can choose to enable one and disable - /// another, but not both. - pub(crate) fn assign_boolean_flag( - &self, - layouter: &mut impl Layouter, - is_left: bool, - ) -> Result<(AssignedCell, AssignedCell), Error> { - layouter.assign_region( - || "lookup for boolean flag", - |mut region| { - let offset = 0; - self.lookup_config.q_enable.enable(&mut region, offset)?; - region.assign_advice_from_constant( - || "tag", - self.lookup_config.cols[0].0, - offset, - F::from(TableTags::BooleanFlag as u64), - )?; - let left = region.assign_advice( - || "left", - self.lookup_config.cols[1].0, - offset, - || Ok(F::from(is_left)), - )?; - let right = region.assign_advice( - || "right", - self.lookup_config.cols[2].0, - offset, - || Ok(F::from(!is_left)), - )?; - Ok((left, right)) - }, - ) - } -} - -#[derive(Debug, Clone)] -pub struct RangeCheckConfig { - pub range: TableColumn, - _marker: PhantomData, -} - -impl RangeCheckConfig { - pub(crate) fn load(&self, layouter: &mut impl Layouter) -> Result<(), Error> { - layouter.assign_table( - || "range", - |mut table| { - for i in 0..=K { - table.assign_cell(|| "range", self.range, i as usize, || Ok(F::from(i)))?; - } - Ok(()) - }, - ) - } - // dead_code reason: WordBuilderConfig is using it. We defer the decision to - // remove this after WordBuilderConfig is complete - #[allow(dead_code)] - pub(crate) fn configure(meta: &mut ConstraintSystem) -> Self { - Self { - range: meta.lookup_table_column(), - _marker: PhantomData, - } - } -} - -#[derive(Debug, Clone)] -pub struct Base13toBase9TableConfig { - lookup_config: ThreeColumnsLookup, - // mapping from base13 input to base9 output and overflow detector - map: HashMap<[u8; 32], (F, F)>, -} - -impl Base13toBase9TableConfig { - pub(crate) fn load(&mut self, layouter: &mut impl Layouter) -> Result<(), Error> { - layouter.assign_table( - || "13 -> 9", - |mut table| { - // Iterate over all possible 13-ary values of size 4 - for (i, b13_chunks) in (0..BASE_NUM_OF_CHUNKS) - .map(|_| 0..B13) - .multi_cartesian_product() - .enumerate() - { - let input_b13 = f_from_radix_be::(&b13_chunks, B13); - let output_b9 = f_from_radix_be::( - &b13_chunks - .iter() - .map(|&x| convert_b13_coef(x)) - .collect_vec(), - B9, - ); - let overflow_detector = F::from(get_overflow_detector( - b13_chunks.clone().try_into().unwrap(), - ) as u64); - - self.map - .insert(input_b13.to_repr(), (output_b9, overflow_detector)); - table.assign_cell( - || "base 13", - self.lookup_config.cols[0].1, - i, - || Ok(input_b13), - )?; - - table.assign_cell( - || "base 9", - self.lookup_config.cols[1].1, - i, - || Ok(output_b9), - )?; - table.assign_cell( - || "overflow_detector", - self.lookup_config.cols[2].1, - i, - || Ok(overflow_detector), - )?; - } - Ok(()) - }, - ) - } - - /// We use col0 for base 13 input - /// we use col1 for base 9 output - /// we use col2 for overflow detector - pub(crate) fn configure( - meta: &mut ConstraintSystem, - adv_cols: [Column; 3], - table_cols: [TableColumn; 3], - ) -> Self { - let lookup_config = - ThreeColumnsLookup::configure(meta, adv_cols, table_cols, "from base 13"); - let map = HashMap::new(); - Self { lookup_config, map } - } - pub(crate) fn assign_region( - &self, - layouter: &mut impl Layouter, - slices: &[(u32, u32)], - conversions: &[Conversion], - ) -> Result< - ( - Vec>, - Vec>, - Vec>, - Vec>, - ), - Error, - > { - layouter.assign_region( - || "conversion lookup", - |mut region| { - let mut input_coefs: Vec> = vec![]; - let mut output_coefs: Vec> = vec![]; - let mut step2_od: Vec> = vec![]; - let mut step3_od: Vec> = vec![]; - for (offset, (&(_, step), conv)) in - slices.iter().zip(conversions.iter()).enumerate() - { - self.lookup_config.q_enable.enable(&mut region, offset)?; - let input = biguint_to_f::(&conv.input.coef); - let outputs = self.map.get(&input.to_repr()); - let input_coef = region.assign_advice( - || "Input Coef", - self.lookup_config.cols[0].0, - offset, - || Ok(input), - )?; - input_coefs.push(input_coef); - - let output_coef = region.assign_advice( - || "Output Coef", - self.lookup_config.cols[1].0, - offset, - || outputs.map(|o| o.0).ok_or(Error::Synthesis), - )?; - output_coefs.push(output_coef); - - let od = region.assign_advice( - || "Overflow detector", - self.lookup_config.cols[2].0, - offset, - || outputs.map(|o| o.1).ok_or(Error::Synthesis), - )?; - match step { - 1 => region.constrain_constant(od.cell(), F::zero())?, - 2 => step2_od.push(od), - 3 => step3_od.push(od), - 4 => { // Do nothing - } - _ => unreachable!(), - } - } - Ok((input_coefs, output_coefs, step2_od, step3_od)) - }, - ) - } -} - -fn compute_input_coefs( - input: Option<&F>, - base: u8, - num_chunks: usize, -) -> [Option; SLICES] { - input.map_or([None; SLICES], |&input| { - // big-endian - let input_chunks: Vec = { - let raw = f_to_biguint(input); - let mut v = raw.to_radix_le(base.into()); - debug_assert!(v.len() <= MAX_CHUNKS); - // fill 0 to max chunks - v.resize(MAX_CHUNKS, 0); - // v is big-endian now - v.reverse(); - v - }; - // Use rchunks + rev so that the remainder chunks stay at the big-endian - // side - let input_coefs = input_chunks - .rchunks(num_chunks) - .rev() - .map(|chunks| Some(f_from_radix_be(chunks, base))) - .collect_vec(); - input_coefs.try_into().unwrap() - }) -} - -#[derive(Debug, Clone)] -pub struct FromBase9TableConfig { - lookup_config: ThreeColumnsLookup, - // mapping from base9 input to base13 and base2 output - map: HashMap<[u8; 32], (F, F)>, -} - -impl FromBase9TableConfig { - pub fn load(&mut self, layouter: &mut impl Layouter) -> Result<(), Error> { - layouter.assign_table( - || "9 -> (2 and 13)", - |mut table| { - // Iterate over all possible base 9 values of size 5 - for (i, b9_chunks) in (0..NUM_OF_B9_CHUNKS_PER_SLICE) - .map(|_| 0..B9) - .multi_cartesian_product() - .enumerate() - { - let input_b9 = f_from_radix_be::(&b9_chunks, B9); - let converted_chunks: Vec = - b9_chunks.iter().map(|&x| convert_b9_coef(x)).collect_vec(); - let output_b13 = f_from_radix_be::(&converted_chunks, B13); - let output_b2 = f_from_radix_be::(&converted_chunks, B2); - self.map.insert(input_b9.to_repr(), (output_b13, output_b2)); - table.assign_cell( - || "base 9", - self.lookup_config.cols[0].1, - i, - || Ok(input_b9), - )?; - - table.assign_cell( - || "base 13", - self.lookup_config.cols[1].1, - i, - || Ok(output_b13), - )?; - table.assign_cell( - || "base 2", - self.lookup_config.cols[2].1, - i, - || Ok(output_b2), - )?; - } - Ok(()) - }, - ) - } - - pub fn configure( - meta: &mut ConstraintSystem, - adv_cols: [Column; 3], - table_cols: [TableColumn; 3], - ) -> Self { - let lookup_config = ThreeColumnsLookup::configure(meta, adv_cols, table_cols, "from base9"); - let map = HashMap::new(); - Self { lookup_config, map } - } - pub fn assign_region( - &self, - layouter: &mut impl Layouter, - input: &AssignedCell, - ) -> Result< - ( - Vec>, - Vec>, - Vec>, - ), - Error, - > { - let input_coefs = compute_input_coefs::( - input.value(), - B9, - NUM_OF_B9_CHUNKS_PER_SLICE, - ); - layouter.assign_region( - || "base 9", - |mut region| { - let mut input_cells = vec![]; - let mut output_b13_cells = vec![]; - let mut output_b2_cells = vec![]; - for (offset, input_coef) in input_coefs.iter().enumerate() { - self.lookup_config.q_enable.enable(&mut region, offset)?; - let input = region.assign_advice( - || "base 9", - self.lookup_config.cols[0].0, - offset, - || input_coef.ok_or(Error::Synthesis), - )?; - input_cells.push(input.clone()); - let output = input_coef.and_then(|v| self.map.get(&v.to_repr())); - - let output_b13 = region.assign_advice( - || "base 13", - self.lookup_config.cols[1].0, - offset, - || output.map(|v| v.0).ok_or(Error::Synthesis), - )?; - output_b13_cells.push(output_b13); - let output_b2 = region.assign_advice( - || "base 2", - self.lookup_config.cols[2].0, - offset, - || output.map(|v| v.1).ok_or(Error::Synthesis), - )?; - output_b2_cells.push(output_b2); - } - Ok((input_cells, output_b13_cells, output_b2_cells)) - }, - ) - } -} - -#[derive(Debug, Clone)] -pub struct FromBinaryTableConfig { - lookup_config: ThreeColumnsLookup, - /// mapping from base2 input to base9 and base13 output - map: HashMap<[u8; 32], (F, F)>, -} - -impl FromBinaryTableConfig { - pub fn load(&mut self, layouter: &mut impl Layouter) -> Result<(), Error> { - layouter.assign_table( - || "2 -> (9 and 13)", - |mut table| { - for (i, b2_chunks) in (0..NUM_OF_BINARY_CHUNKS_PER_SLICE) - .map(|_| 0..B2) - .multi_cartesian_product() - .enumerate() - { - let input_b2 = f_from_radix_be::(&b2_chunks, B2); - let output_b9 = f_from_radix_be::(&b2_chunks, B9); - let output_b13 = f_from_radix_be::(&b2_chunks, B13); - - self.map.insert(input_b2.to_repr(), (output_b9, output_b13)); - // Iterate over all possible binary values of size 16 - - table.assign_cell( - || "base 2", - self.lookup_config.cols[0].1, - i, - || Ok(input_b2), - )?; - - table.assign_cell( - || "base 9", - self.lookup_config.cols[1].1, - i, - || Ok(output_b9), - )?; - table.assign_cell( - || "base 13", - self.lookup_config.cols[2].1, - i, - || Ok(output_b13), - )?; - } - Ok(()) - }, - ) - } - - pub fn configure( - meta: &mut ConstraintSystem, - adv_cols: [Column; 3], - table_cols: [TableColumn; 3], - ) -> Self { - let lookup_config = ThreeColumnsLookup::configure(meta, adv_cols, table_cols, "from base9"); - let map = HashMap::new(); - Self { lookup_config, map } - } - pub fn assign_region( - &self, - layouter: &mut impl Layouter, - input: &AssignedCell, - ) -> Result< - ( - Vec>, - Vec>, - Vec>, - ), - Error, - > { - let input_coefs = compute_input_coefs::( - input.value(), - B2, - NUM_OF_BINARY_CHUNKS_PER_SLICE, - ); - layouter.assign_region( - || "base 2", - |mut region| { - let mut input_cells = vec![]; - let mut output_b9_cells = vec![]; - let mut output_b13_cells = vec![]; - for (offset, input_coef) in input_coefs.iter().enumerate() { - self.lookup_config.q_enable.enable(&mut region, offset)?; - let input = region.assign_advice( - || "base 2", - self.lookup_config.cols[0].0, - offset, - || input_coef.ok_or(Error::Synthesis), - )?; - input_cells.push(input.clone()); - - let output = input_coef.and_then(|v| self.map.get(&v.to_repr())); - - let output_b9 = region.assign_advice( - || "base 9", - self.lookup_config.cols[1].0, - offset, - || output.map(|v| v.0).ok_or(Error::Synthesis), - )?; - output_b9_cells.push(output_b9); - let output_b13 = region.assign_advice( - || "base 13", - self.lookup_config.cols[2].0, - offset, - || output.map(|v| v.1).ok_or(Error::Synthesis), - )?; - output_b13_cells.push(output_b13); - } - Ok((input_cells, output_b9_cells, output_b13_cells)) - }, - ) - } -} diff --git a/zkevm-circuits/Cargo.toml b/zkevm-circuits/Cargo.toml index a1b7a3ca70..4c11b457f4 100644 --- a/zkevm-circuits/Cargo.toml +++ b/zkevm-circuits/Cargo.toml @@ -8,7 +8,8 @@ license = "MIT OR Apache-2.0" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -halo2_proofs = { version = "0.1.0-beta.1" } +halo2_proofs = { git = "https://github.com/privacy-scaling-explorations/halo2.git", tag = "v2022_08_19" } +num = "0.4" sha3 = "0.10" array-init = "2.0.0" bus-mapping = { path = "../bus-mapping" } @@ -24,18 +25,18 @@ lazy_static = "1.4" keccak256 = { path = "../keccak256"} log = "0.4" env_logger = "0.9" -ecdsa = { git = "https://github.com/privacy-scaling-explorations/halo2wrong", tag = "v2022_06_03", features = ["kzg"] } -secp256k1 = { git = "https://github.com/privacy-scaling-explorations/halo2wrong", tag = "v2022_06_03", features = ["kzg"] } -ecc = { git = "https://github.com/privacy-scaling-explorations/halo2wrong", tag = "v2022_06_03", features = ["kzg"] } -maingate = { git = "https://github.com/privacy-scaling-explorations/halo2wrong", tag = "v2022_06_03", features = ["kzg"] } -integer = { git = "https://github.com/privacy-scaling-explorations/halo2wrong", tag = "v2022_06_03", features = ["kzg"] } -group = "0.11" +ecdsa = { git = "https://github.com/privacy-scaling-explorations/halo2wrong", tag = "v2022_08_24" } +ecc = { git = "https://github.com/privacy-scaling-explorations/halo2wrong", tag = "v2022_08_24" } +maingate = { git = "https://github.com/privacy-scaling-explorations/halo2wrong", tag = "v2022_08_24" } +integer = { git = "https://github.com/privacy-scaling-explorations/halo2wrong", tag = "v2022_08_24" } +libsecp256k1 = "0.7" +num-bigint = { version = "0.4" } +subtle = "2.4" [dev-dependencies] bus-mapping = { path = "../bus-mapping", features = ["test"] } criterion = "0.3" ctor = "0.1.22" -env_logger = "0.9.0" hex = "0.4.3" mock = { path = "../mock" } itertools = "0.10.1" @@ -43,10 +44,6 @@ pretty_assertions = "1.0.0" ethers-signers = "0.6" rand_chacha = "0.3" -[[bench]] -name = "binary_value" -harness = false - [features] default = [] test = [] diff --git a/zkevm-circuits/benches/binary_value.rs b/zkevm-circuits/benches/binary_value.rs deleted file mode 100644 index 59d7bcabeb..0000000000 --- a/zkevm-circuits/benches/binary_value.rs +++ /dev/null @@ -1,315 +0,0 @@ -use std::marker::PhantomData; - -use criterion::{criterion_group, criterion_main, Criterion}; -use halo2_proofs::{ - circuit::{Layouter, Region, SimpleFloorPlanner}, - dev::MockProver, - pairing::{arithmetic::FieldExt, bn256::Fr}, - plonk::{Advice, Circuit, Column, ConstraintSystem, Error, Expression, Fixed}, - poly::Rotation, -}; - -#[derive(Copy, Clone, Debug)] -struct MemoryAddress(F); - -/// Global counter -#[derive(Copy, Clone, Debug)] -struct GlobalCounter(usize); - -#[derive(Copy, Clone, Debug)] -struct Value(F); - -#[derive(Clone, Debug)] -enum ReadWrite { - // flag == 0 - Read(GlobalCounter, Value), - // flag == 1 - Write(GlobalCounter, Value), -} - -impl ReadWrite { - fn global_counter(&self) -> GlobalCounter { - match self { - Self::Read(global_counter, _) | Self::Write(global_counter, _) => *global_counter, - } - } - - fn value(&self) -> Value { - match self { - Self::Read(_, value) | Self::Write(_, value) => *value, - } - } - - fn flag(&self) -> bool { - match self { - Self::Read(..) => false, - Self::Write(..) => true, - } - } -} - -#[derive(Clone, Debug)] -/// All the read/write operations that happen at this address. -pub(crate) struct MemoryOp { - address: MemoryAddress, - global_counters: Vec>>, -} - -#[derive(Clone, Debug)] -pub(crate) struct Config { - q_target: Column, - address: Column, - global_counter: Column, - value: Column, - flag: Column, - binary_table: Column, - _marker: PhantomData, -} - -impl Config { - /// Set up custom gates and lookup arguments for this configuration. - pub(crate) fn configure(meta: &mut ConstraintSystem) -> Self { - let q_target = meta.fixed_column(); - let address = meta.advice_column(); - let global_counter = meta.advice_column(); - let value = meta.advice_column(); - let flag = meta.advice_column(); - let binary_table = meta.fixed_column(); - - if LOOKUP { - meta.lookup_any("binary lookup", |meta| { - let q_target = meta.query_fixed(q_target, Rotation::cur()); - let flag = meta.query_advice(flag, Rotation::cur()); - let binary_table = meta.query_fixed(binary_table, Rotation::cur()); - - vec![(q_target * flag, binary_table)] - }); - } else { - meta.create_gate("Memory operation", |meta| { - let q_target = meta.query_fixed(q_target, Rotation::cur()); - let flag = meta.query_advice(flag, Rotation::cur()); - - // flag == 0 or 1 - // (flag) * (1 - flag) - let bool_check_flag = { - let one = Expression::Constant(F::one()); - flag.clone() * (one - flag) - }; - - vec![q_target * bool_check_flag] - }); - } - - Config { - q_target, - address, - global_counter, - value, - flag, - binary_table, - _marker: PhantomData, - } - } - - pub(crate) fn load(&self, layouter: &mut impl Layouter) -> Result<(), Error> { - layouter.assign_region( - || "binary table", - |mut region| { - for idx in 0..=1 { - region.assign_fixed( - || "binary table", - self.binary_table, - idx, - || Ok(F::from(idx as u64)), - )?; - } - Ok(()) - }, - ) - } - - /// Assign cells. - pub(crate) fn assign(&self, mut layouter: impl Layouter, ops: Vec>) { - layouter - .assign_region( - || "Memory operations", - |mut region| { - let mut offset = 0; - - for (_index, op) in ops.iter().enumerate() { - let address = op.address; - - self.init(&mut region, offset, address)?; - region.assign_fixed( - || "Memory selector", - self.q_target, - offset, - || Ok(F::one()), - )?; - - // Increase offset by 1 after initialising. - offset += 1; - - for global_counter in op.global_counters.iter() { - self.assign_per_counter(&mut region, offset, address, global_counter); - - region.assign_fixed( - || "Memory selector", - self.q_target, - offset, - || Ok(F::one()), - )?; - offset += 1; - } - } - - Ok(()) - }, - ) - .ok(); - } - - /// Initialise first row for a new operation. - fn init( - &self, - region: &mut Region<'_, F>, - offset: usize, - address: MemoryAddress, - ) -> Result<(), Error> { - // Assign `address` - region.assign_advice(|| "init address", self.address, offset, || Ok(address.0))?; - - // Assign `global_counter` - region.assign_advice( - || "init global counter", - self.global_counter, - offset, - || Ok(F::zero()), - )?; - - // Assign `value` - region.assign_advice(|| "init value", self.value, offset, || Ok(F::zero()))?; - - // Assign memory_flag - region.assign_advice(|| "init memory", self.flag, offset, || Ok(F::one()))?; - - Ok(()) - } - - /// Assign cells for each global counter in an operation. - fn assign_per_counter( - &self, - region: &mut Region<'_, F>, - offset: usize, - address: MemoryAddress, - read_write: &Option>, - ) { - region - .assign_advice(|| "address", self.address, offset, || Ok(address.0)) - .ok(); - - let value = read_write - .as_ref() - .map(|read_write| read_write.global_counter().0); - let field_elem = value.map(|value| F::from(value as u64)); - - region - .assign_advice( - || "global counter", - self.global_counter, - offset, - || field_elem.ok_or(Error::Synthesis), - ) - .ok(); - - // Assign `value` - let value = read_write.as_ref().map(|read_write| read_write.value().0); - region - .assign_advice( - || "value", - self.value, - offset, - || value.ok_or(Error::Synthesis), - ) - .ok(); - - let value = read_write.as_ref().map(|read_write| read_write.flag()); - let field_elem = value.map(|value| F::from(value as u64)); - region - .assign_advice( - || "flag", - self.flag, - offset, - || field_elem.ok_or(Error::Synthesis), - ) - .ok(); - } -} - -macro_rules! test_state_circuit { - ($lookup:expr) => {{ - #[derive(Default)] - struct MemoryCircuit { - ops: Vec>, - _marker: PhantomData, - } - - impl Circuit for MemoryCircuit { - type Config = Config; - type FloorPlanner = SimpleFloorPlanner; - - fn without_witnesses(&self) -> Self { - Self::default() - } - - fn configure(meta: &mut ConstraintSystem) -> Self::Config { - Config::configure(meta) - } - - fn synthesize( - &self, - config: Self::Config, - mut layouter: impl Layouter, - ) -> Result<(), Error> { - config.load(&mut layouter)?; - config.assign(layouter, self.ops.clone()); - - Ok(()) - } - } - - let mut ops = vec![]; - for _i in 0..10000 { - let op = MemoryOp { - address: MemoryAddress(Fr::zero()), - global_counters: vec![ - Some(ReadWrite::Write(GlobalCounter(12), Value(Fr::from(12)))), - Some(ReadWrite::Read(GlobalCounter(24), Value(Fr::from(12)))), - ], - }; - ops.push(op); - } - - let circuit = MemoryCircuit:: { - ops, - _marker: PhantomData, - }; - - let prover = MockProver::::run(7, &circuit, vec![]).unwrap(); - assert_eq!(prover.verify(), Ok(())); - }}; -} - -// measuring the value being binary with lookup table (containing 0 and 1) and -// with gate -fn binary() { - test_state_circuit!(true); // with lookup - // test_state_circuit!(false); // with gate -} - -fn criterion_benchmark(c: &mut Criterion) { - c.bench_function("checking binary values", |b| b.iter(binary)); -} - -criterion_group!(benches, criterion_benchmark); -criterion_main!(benches); diff --git a/zkevm-circuits/src/bytecode_circuit/bytecode_unroller.rs b/zkevm-circuits/src/bytecode_circuit/bytecode_unroller.rs index fb34f2f1c4..9043218b4e 100644 --- a/zkevm-circuits/src/bytecode_circuit/bytecode_unroller.rs +++ b/zkevm-circuits/src/bytecode_circuit/bytecode_unroller.rs @@ -9,7 +9,7 @@ use bus_mapping::evm::OpcodeId; use eth_types::{Field, ToLittleEndian, Word}; use gadgets::is_zero::{IsZeroChip, IsZeroConfig, IsZeroInstruction}; use halo2_proofs::{ - circuit::{Layouter, Region}, + circuit::{Layouter, Region, Value}, plonk::{Advice, Column, ConstraintSystem, Error, Expression, Fixed, Selector, VirtualCells}, poly::Rotation, }; @@ -505,7 +505,7 @@ impl Config { || format!("assign q_enable {}", offset), self.q_enable, offset, - || Ok(F::from(enable as u64)), + || Value::known(F::from(enable as u64)), )?; // q_first @@ -513,7 +513,7 @@ impl Config { || format!("assign q_first {}", offset), self.q_first, offset, - || Ok(F::from((offset == 0) as u64)), + || Value::known(F::from((offset == 0) as u64)), )?; // q_last @@ -539,15 +539,15 @@ impl Config { || format!("assign {} {}", name, offset), *column, offset, - || Ok(*value), + || Value::known(*value), )?; } // push_rindex_is_zero_chip - push_rindex_is_zero_chip.assign(region, offset, Some(push_rindex_prev))?; + push_rindex_is_zero_chip.assign(region, offset, Value::known(push_rindex_prev))?; // length_is_zero chip - length_is_zero_chip.assign(region, offset, Some(code_length))?; + length_is_zero_chip.assign(region, offset, Value::known(code_length))?; Ok(()) } @@ -571,7 +571,7 @@ impl Config { || format!("Push table assign {} {}", name, byte), *column, byte, - || Ok(F::from(*value)), + || Value::known(F::from(*value)), )?; } } @@ -654,7 +654,7 @@ mod tests { use super::*; use crate::bytecode_circuit::dev::test_bytecode_circuit_unrolled; use eth_types::Bytecode; - use halo2_proofs::pairing::bn256::Fr; + use halo2_proofs::halo2curves::bn256::Fr; fn get_randomness() -> F { F::from(123456) diff --git a/zkevm-circuits/src/copy_circuit.rs b/zkevm-circuits/src/copy_circuit.rs index 3327966c98..269f6e7b6d 100644 --- a/zkevm-circuits/src/copy_circuit.rs +++ b/zkevm-circuits/src/copy_circuit.rs @@ -10,7 +10,7 @@ use gadgets::{ util::{and, not, or, Expr}, }; use halo2_proofs::{ - circuit::{Layouter, Region}, + circuit::{Layouter, Region, Value}, plonk::{Advice, Column, ConstraintSystem, Error, Expression, Fixed, Selector}, poly::Rotation, }; @@ -453,7 +453,12 @@ impl CopyCircuit { lt_chip: &LtChip, ) -> Result<(), Error> { // q_enable - region.assign_fixed(|| "q_enable", self.q_enable, offset, || Ok(F::one()))?; + region.assign_fixed( + || "q_enable", + self.q_enable, + offset, + || Value::known(F::one()), + )?; // enable q_step on the Read step if copy_step.rw.is_read() { self.q_step.enable(region, offset)?; @@ -471,7 +476,7 @@ impl CopyCircuit { || format!("assign is_first {}", offset), self.copy_table.is_first, offset, - || Ok(if step_idx == 0 { F::one() } else { F::zero() }), + || Value::known(if step_idx == 0 { F::one() } else { F::zero() }), )?; // is_last region.assign_advice( @@ -479,7 +484,7 @@ impl CopyCircuit { self.is_last, offset, || { - Ok(if step_idx == copy_event.steps.len() - 1 { + Value::known(if step_idx == copy_event.steps.len() - 1 { F::one() } else { F::zero() @@ -491,7 +496,7 @@ impl CopyCircuit { || format!("assign id {}", offset), self.copy_table.id, offset, - || Ok(number_or_hash_to_field(id, randomness)), + || Value::known(number_or_hash_to_field(id, randomness)), )?; // addr region.assign_advice( @@ -499,7 +504,7 @@ impl CopyCircuit { self.copy_table.addr, offset, || { - Ok(match copy_step.tag { + Value::known(match copy_step.tag { CopyDataType::TxLog => { let addr = (U256::from(copy_step.addr) + (U256::from(TxLogFieldTag::Data as u64) << 32) @@ -516,42 +521,42 @@ impl CopyCircuit { || format!("assign value {}", offset), self.value, offset, - || Ok(value), + || Value::known(value), )?; // rlc_acc region.assign_advice( || format!("assign rlc_acc {}", offset), self.copy_table.rlc_acc, offset, - || Ok(rlc_acc), + || Value::known(rlc_acc), )?; // is_code region.assign_advice( || format!("assign is_code {}", offset), self.is_code, offset, - || Ok(copy_step.is_code.map_or(F::zero(), |v| F::from(v))), + || Value::known(copy_step.is_code.map_or(F::zero(), |v| F::from(v))), )?; // is_pad region.assign_advice( || format!("assign is_pad {}", offset), self.is_pad, offset, - || Ok(F::from(copy_step.is_pad)), + || Value::known(F::from(copy_step.is_pad)), )?; // rw_counter region.assign_advice( || format!("assign rw_counter {}", offset), self.copy_table.rw_counter, offset, - || Ok(F::from(copy_step.rwc.0 as u64)), + || Value::known(F::from(copy_step.rwc.0 as u64)), )?; // rwc_inc_left region.assign_advice( || format!("assign rwc_inc_left {}", offset), self.copy_table.rwc_inc_left, offset, - || Ok(F::from(copy_step.rwc_inc_left)), + || Value::known(F::from(copy_step.rwc_inc_left)), )?; // tag binary number chip tag_chip.assign(region, offset, ©_step.tag)?; @@ -562,14 +567,14 @@ impl CopyCircuit { || format!("assign src_addr_end {}", offset), self.copy_table.src_addr_end, offset, - || Ok(F::from(copy_event.src_addr_end)), + || Value::known(F::from(copy_event.src_addr_end)), )?; // bytes_left region.assign_advice( || format!("assign bytes_left {}", offset), self.copy_table.bytes_left, offset, - || Ok(F::from(bytes_left)), + || Value::known(F::from(bytes_left)), )?; // lt chip lt_chip.assign( @@ -589,90 +594,95 @@ impl CopyCircuit { tag_chip: &BinaryNumberChip, ) -> Result<(), Error> { // q_enable - region.assign_fixed(|| "q_enable", self.q_enable, offset, || Ok(F::zero()))?; + region.assign_fixed( + || "q_enable", + self.q_enable, + offset, + || Value::known(F::zero()), + )?; // is_first region.assign_advice( || format!("assign is_first {}", offset), self.copy_table.is_first, offset, - || Ok(F::zero()), + || Value::known(F::zero()), )?; // is_last region.assign_advice( || format!("assign is_last {}", offset), self.is_last, offset, - || Ok(F::zero()), + || Value::known(F::zero()), )?; // id region.assign_advice( || format!("assign id {}", offset), self.copy_table.id, offset, - || Ok(F::zero()), + || Value::known(F::zero()), )?; // addr region.assign_advice( || format!("assign addr {}", offset), self.copy_table.addr, offset, - || Ok(F::zero()), + || Value::known(F::zero()), )?; // src_addr_end region.assign_advice( || format!("assign src_addr_end {}", offset), self.copy_table.src_addr_end, offset, - || Ok(F::zero()), + || Value::known(F::zero()), )?; // bytes_left region.assign_advice( || format!("assign bytes_left {}", offset), self.copy_table.bytes_left, offset, - || Ok(F::zero()), + || Value::known(F::zero()), )?; // value region.assign_advice( || format!("assign value {}", offset), self.value, offset, - || Ok(F::zero()), + || Value::known(F::zero()), )?; // rlc_acc region.assign_advice( || format!("assign rlc_acc {}", offset), self.copy_table.rlc_acc, offset, - || Ok(F::zero()), + || Value::known(F::zero()), )?; // is_code region.assign_advice( || format!("assign is_code {}", offset), self.is_code, offset, - || Ok(F::zero()), + || Value::known(F::zero()), )?; // is_pad region.assign_advice( || format!("assign is_pad {}", offset), self.is_pad, offset, - || Ok(F::zero()), + || Value::known(F::zero()), )?; // rw_counter region.assign_advice( || format!("assign rw_counter {}", offset), self.copy_table.rw_counter, offset, - || Ok(F::zero()), + || Value::known(F::zero()), )?; // rwc_inc_left region.assign_advice( || format!("assign rwc_inc_left {}", offset), self.copy_table.rwc_inc_left, offset, - || Ok(F::zero()), + || Value::known(F::zero()), )?; // tag tag_chip.assign(region, offset, &CopyDataType::default())?; diff --git a/zkevm-circuits/src/evm_circuit.rs b/zkevm-circuits/src/evm_circuit.rs index 5fdf87933c..09d54c0100 100644 --- a/zkevm-circuits/src/evm_circuit.rs +++ b/zkevm-circuits/src/evm_circuit.rs @@ -1,7 +1,10 @@ //! The EVM circuit implementation. #![allow(missing_docs)] -use halo2_proofs::{circuit::Layouter, plonk::*}; +use halo2_proofs::{ + circuit::{Layouter, Value}, + plonk::*, +}; mod execution; pub mod param; @@ -75,7 +78,7 @@ impl EvmCircuit { .enumerate() { for (column, value) in self.fixed_table.iter().zip_eq(row) { - region.assign_fixed(|| "", *column, offset, || Ok(value))?; + region.assign_fixed(|| "", *column, offset, || Value::known(value))?; } } @@ -94,7 +97,7 @@ impl EvmCircuit { || "", self.byte_table[0], offset, - || Ok(F::from(offset as u64)), + || Value::known(F::from(offset as u64)), )?; } @@ -370,7 +373,7 @@ mod evm_circuit_stats { use super::*; use crate::evm_circuit::step::ExecutionState; use eth_types::{bytecode, evm_types::OpcodeId, geth_types::GethData}; - use halo2_proofs::pairing::bn256::Fr; + use halo2_proofs::halo2curves::bn256::Fr; use halo2_proofs::plonk::ConstraintSystem; use mock::test_ctx::{helpers::*, TestContext}; use strum::IntoEnumIterator; diff --git a/zkevm-circuits/src/evm_circuit/execution.rs b/zkevm-circuits/src/evm_circuit/execution.rs index 07fd420426..8606d53ccb 100644 --- a/zkevm-circuits/src/evm_circuit/execution.rs +++ b/zkevm-circuits/src/evm_circuit/execution.rs @@ -16,7 +16,7 @@ use crate::{ use eth_types::Field; use halo2_proofs::{ arithmetic::FieldExt, - circuit::{Layouter, Region}, + circuit::{Layouter, Region, Value}, plonk::{Advice, Column, ConstraintSystem, Error, Expression, Selector, VirtualCells}, poly::Rotation, }; @@ -743,7 +743,12 @@ impl ExecutionConfig { .chain(self.advices) { region - .assign_advice(|| "assign advice rows", column, i, || Ok(F::zero())) + .assign_advice( + || "assign advice rows", + column, + i, + || Value::known(F::zero()), + ) .unwrap(); } } @@ -789,7 +794,7 @@ impl ExecutionConfig { || "step selector", self.q_step, offset, - || Ok(if idx == 0 { F::one() } else { F::zero() }), + || Value::known(if idx == 0 { F::one() } else { F::zero() }), )?; let value = if idx == 0 { F::zero() @@ -800,13 +805,13 @@ impl ExecutionConfig { || "step height", self.num_rows_until_next_step, offset, - || Ok(value), + || Value::known(value), )?; region.assign_advice( || "step height inv", self.num_rows_inv, offset, - || Ok(value.invert().unwrap_or(F::zero())), + || Value::known(value.invert().unwrap_or(F::zero())), )?; } @@ -818,13 +823,13 @@ impl ExecutionConfig { || "step height", self.num_rows_until_next_step, offset, - || Ok(F::zero()), + || Value::known(F::zero()), )?; region.assign_advice( || "step height inv", self.q_step, offset, - || Ok(F::zero()), + || Value::known(F::zero()), )?; // If not exact: @@ -1079,10 +1084,10 @@ impl ExecutionConfig { .unwrap_or_else(|| panic!("Execution state unknown: {:?}", step.execution_state)) { let assigned = stored_expression.assign(region, offset)?; - if let Some(v) = assigned.value() { + assigned.value().map(|v| { let name = stored_expression.name.clone(); - assigned_stored_expressions.push((name, *v)) - } + assigned_stored_expressions.push((name, *v)); + }); } Ok(assigned_stored_expressions) } diff --git a/zkevm-circuits/src/evm_circuit/execution/begin_tx.rs b/zkevm-circuits/src/evm_circuit/execution/begin_tx.rs index 87642ba5c4..aeb3aca49a 100644 --- a/zkevm-circuits/src/evm_circuit/execution/begin_tx.rs +++ b/zkevm-circuits/src/evm_circuit/execution/begin_tx.rs @@ -18,6 +18,7 @@ use crate::{ util::Expr, }; use eth_types::{evm_types::GasCost, Field, ToLittleEndian, ToScalar}; +use halo2_proofs::circuit::Value; use halo2_proofs::plonk::Error; #[derive(Clone, Debug)] @@ -225,27 +226,45 @@ impl ExecutionGadget for BeginTxGadget { .map(|idx| block.rws[idx].account_value_pair()); self.tx_id - .assign(region, offset, Some(F::from(tx.id as u64)))?; + .assign(region, offset, Value::known(F::from(tx.id as u64)))?; self.tx_nonce - .assign(region, offset, Some(F::from(tx.nonce)))?; - self.tx_gas.assign(region, offset, Some(F::from(tx.gas)))?; + .assign(region, offset, Value::known(F::from(tx.nonce)))?; + self.tx_gas + .assign(region, offset, Value::known(F::from(tx.gas)))?; self.tx_gas_price .assign(region, offset, Some(tx.gas_price.to_le_bytes()))?; self.mul_gas_fee_by_gas .assign(region, offset, tx.gas_price, tx.gas, gas_fee)?; - self.tx_caller_address - .assign(region, offset, tx.caller_address.to_scalar())?; - self.tx_callee_address - .assign(region, offset, tx.callee_address.to_scalar())?; + self.tx_caller_address.assign( + region, + offset, + Value::known( + tx.caller_address + .to_scalar() + .expect("unexpected Address -> Scalar conversion failure"), + ), + )?; + self.tx_callee_address.assign( + region, + offset, + Value::known( + tx.callee_address + .to_scalar() + .expect("unexpected Address -> Scalar conversion failure"), + ), + )?; self.tx_is_create - .assign(region, offset, Some(F::from(tx.is_create as u64)))?; + .assign(region, offset, Value::known(F::from(tx.is_create as u64)))?; self.tx_call_data_length.assign( region, offset, - Some(F::from(tx.call_data_length as u64)), + Value::known(F::from(tx.call_data_length as u64)), + )?; + self.tx_call_data_gas_cost.assign( + region, + offset, + Value::known(F::from(tx.call_data_gas_cost)), )?; - self.tx_call_data_gas_cost - .assign(region, offset, Some(F::from(tx.call_data_gas_cost)))?; self.reversion_info.assign( region, offset, @@ -265,7 +284,7 @@ impl ExecutionGadget for BeginTxGadget { self.code_hash.assign( region, offset, - Some(RandomLinearCombination::random_linear_combine( + Value::known(RandomLinearCombination::random_linear_combine( callee_code_hash.to_le_bytes(), block.randomness, )), diff --git a/zkevm-circuits/src/evm_circuit/execution/blockhash.rs b/zkevm-circuits/src/evm_circuit/execution/blockhash.rs index 62ac78732c..d49c2848bf 100644 --- a/zkevm-circuits/src/evm_circuit/execution/blockhash.rs +++ b/zkevm-circuits/src/evm_circuit/execution/blockhash.rs @@ -18,7 +18,7 @@ use crate::{ use bus_mapping::evm::OpcodeId; use eth_types::{Field, ToLittleEndian, ToScalar}; use gadgets::util::not; -use halo2_proofs::plonk::Error; +use halo2_proofs::{circuit::Value, plonk::Error}; #[derive(Clone, Debug)] pub(crate) struct BlockHashGadget { @@ -115,8 +115,15 @@ impl ExecutionGadget for BlockHashGadget { let block_number: F = block_number.to_scalar().unwrap(); let current_block_number = block.context.number; - self.current_block_number - .assign(region, offset, current_block_number.to_scalar())?; + self.current_block_number.assign( + region, + offset, + Value::known( + current_block_number + .to_scalar() + .expect("unexpected U256 -> Scalar conversion failure"), + ), + )?; let current_block_number: F = current_block_number.to_scalar().unwrap(); self.block_hash.assign( diff --git a/zkevm-circuits/src/evm_circuit/execution/call.rs b/zkevm-circuits/src/evm_circuit/execution/call.rs index 9c19c2edb2..b171edb38f 100644 --- a/zkevm-circuits/src/evm_circuit/execution/call.rs +++ b/zkevm-circuits/src/evm_circuit/execution/call.rs @@ -27,7 +27,7 @@ use eth_types::{ evm_types::{GasCost, GAS_STIPEND_CALL_WITH_VALUE}, Field, ToLittleEndian, ToScalar, }; -use halo2_proofs::plonk::Error; +use halo2_proofs::{circuit::Value, plonk::Error}; use keccak256::EMPTY_HASH_LE; #[derive(Clone, Debug)] @@ -371,22 +371,29 @@ impl ExecutionGadget for CallGadget { let opcode = step.opcode.unwrap(); self.opcode - .assign(region, offset, Some(F::from(opcode.as_u64())))?; + .assign(region, offset, Value::known(F::from(opcode.as_u64())))?; self.tx_id - .assign(region, offset, Some(F::from(tx_id.low_u64())))?; + .assign(region, offset, Value::known(F::from(tx_id.low_u64())))?; self.reversion_info.assign( region, offset, call.rw_counter_end_of_reversion, call.is_persistent, )?; - self.current_address - .assign(region, offset, current_address.to_scalar())?; + self.current_address.assign( + region, + offset, + Value::known( + current_address + .to_scalar() + .expect("unexpected Address -> Scalar conversion failure"), + ), + )?; self.is_static - .assign(region, offset, Some(F::from(is_static.low_u64())))?; + .assign(region, offset, Value::known(F::from(is_static.low_u64())))?; self.depth - .assign(region, offset, Some(F::from(depth.low_u64())))?; + .assign(region, offset, Value::known(F::from(depth.low_u64())))?; self.gas.assign(region, offset, Some(gas.to_le_bytes()))?; self.callee_address @@ -394,16 +401,16 @@ impl ExecutionGadget for CallGadget { self.value .assign(region, offset, Some(value.to_le_bytes()))?; self.is_success - .assign(region, offset, Some(F::from(is_success.low_u64())))?; + .assign(region, offset, Value::known(F::from(is_success.low_u64())))?; self.gas_is_u64.assign( region, offset, sum::value(&gas.to_le_bytes()[N_BYTES_GAS..]), )?; self.is_warm - .assign(region, offset, Some(F::from(is_warm as u64)))?; + .assign(region, offset, Value::known(F::from(is_warm as u64)))?; self.is_warm_prev - .assign(region, offset, Some(F::from(is_warm_prev as u64)))?; + .assign(region, offset, Value::known(F::from(is_warm_prev as u64)))?; self.callee_reversion_info.assign( region, offset, @@ -431,12 +438,19 @@ impl ExecutionGadget for CallGadget { callee_balance_pair, value, )?; - self.callee_nonce - .assign(region, offset, callee_nonce.to_scalar())?; + self.callee_nonce.assign( + region, + offset, + Value::known( + callee_nonce + .to_scalar() + .expect("unexpected U256 -> Scalar conversion failure"), + ), + )?; self.callee_code_hash.assign( region, offset, - Some(Word::random_linear_combine( + Value::known(Word::random_linear_combine( callee_code_hash.to_le_bytes(), block.randomness, )), diff --git a/zkevm-circuits/src/evm_circuit/execution/calldatacopy.rs b/zkevm-circuits/src/evm_circuit/execution/calldatacopy.rs index 6192ff5d8c..fdd98190a5 100644 --- a/zkevm-circuits/src/evm_circuit/execution/calldatacopy.rs +++ b/zkevm-circuits/src/evm_circuit/execution/calldatacopy.rs @@ -20,7 +20,7 @@ use crate::{ }; use bus_mapping::{circuit_input_builder::CopyDataType, evm::OpcodeId}; use eth_types::{evm_types::GasCost, Field, ToLittleEndian, ToScalar}; -use halo2_proofs::plonk::Error; +use halo2_proofs::{circuit::Value, plonk::Error}; use std::cmp::min; @@ -193,7 +193,7 @@ impl ExecutionGadget for CallDataCopyGadget { self.src_id.assign( region, offset, - Some(F::from(u64::try_from(src_id).unwrap())), + Value::known(F::from(u64::try_from(src_id).unwrap())), )?; // Call data length and call data offset @@ -203,9 +203,9 @@ impl ExecutionGadget for CallDataCopyGadget { (call.call_data_length, call.call_data_offset) }; self.call_data_length - .assign(region, offset, Some(F::from(call_data_length)))?; + .assign(region, offset, Value::known(F::from(call_data_length)))?; self.call_data_offset - .assign(region, offset, Some(F::from(call_data_offset)))?; + .assign(region, offset, Value::known(F::from(call_data_offset)))?; // rw_counter increase from copy lookup is `length` memory writes + a variable // number of memory reads. @@ -223,8 +223,15 @@ impl ExecutionGadget for CallDataCopyGadget { .unwrap_or_default(), ) }; - self.copy_rwc_inc - .assign(region, offset, copy_rwc_inc.to_scalar())?; + self.copy_rwc_inc.assign( + region, + offset, + Value::known( + copy_rwc_inc + .to_scalar() + .expect("unexpected U256 -> Scalar conversion failure"), + ), + )?; // Memory expansion let (_, memory_expansion_gas_cost) = self.memory_expansion.assign( diff --git a/zkevm-circuits/src/evm_circuit/execution/calldataload.rs b/zkevm-circuits/src/evm_circuit/execution/calldataload.rs index c30444bc1e..600a190aa9 100644 --- a/zkevm-circuits/src/evm_circuit/execution/calldataload.rs +++ b/zkevm-circuits/src/evm_circuit/execution/calldataload.rs @@ -1,6 +1,9 @@ use bus_mapping::evm::OpcodeId; use eth_types::{Field, ToLittleEndian}; -use halo2_proofs::plonk::{Error, Expression}; +use halo2_proofs::{ + circuit::Value, + plonk::{Error, Expression}, +}; use crate::{ evm_circuit::{ @@ -201,11 +204,12 @@ impl ExecutionGadget for CallDataLoadGadget { call.caller_id as u64, ) }; - self.src_id.assign(region, offset, Some(F::from(src_id)))?; + self.src_id + .assign(region, offset, Value::known(F::from(src_id)))?; self.call_data_length - .assign(region, offset, Some(F::from(calldata_length)))?; + .assign(region, offset, Value::known(F::from(calldata_length)))?; self.call_data_offset - .assign(region, offset, Some(F::from(calldata_offset)))?; + .assign(region, offset, Value::known(F::from(calldata_offset)))?; let mut calldata_bytes = vec![0u8; N_BYTES_WORD]; let (src_addr, src_addr_end) = ( diff --git a/zkevm-circuits/src/evm_circuit/execution/callvalue.rs b/zkevm-circuits/src/evm_circuit/execution/callvalue.rs index 47e2ed0153..9e4d1a6c0a 100644 --- a/zkevm-circuits/src/evm_circuit/execution/callvalue.rs +++ b/zkevm-circuits/src/evm_circuit/execution/callvalue.rs @@ -14,7 +14,7 @@ use crate::{ }; use bus_mapping::evm::OpcodeId; use eth_types::{Field, ToLittleEndian}; -use halo2_proofs::plonk::Error; +use halo2_proofs::{circuit::Value, plonk::Error}; #[derive(Clone, Debug)] pub(crate) struct CallValueGadget { @@ -76,7 +76,7 @@ impl ExecutionGadget for CallValueGadget { self.call_value.assign( region, offset, - Some(Word::random_linear_combine( + Value::known(Word::random_linear_combine( call_value.to_le_bytes(), block.randomness, )), diff --git a/zkevm-circuits/src/evm_circuit/execution/chainid.rs b/zkevm-circuits/src/evm_circuit/execution/chainid.rs index a7fe6b0228..50523a92ee 100644 --- a/zkevm-circuits/src/evm_circuit/execution/chainid.rs +++ b/zkevm-circuits/src/evm_circuit/execution/chainid.rs @@ -14,7 +14,7 @@ use crate::{ }; use bus_mapping::evm::OpcodeId; use eth_types::{Field, ToLittleEndian}; -use halo2_proofs::plonk::Error; +use halo2_proofs::{circuit::Value, plonk::Error}; #[derive(Clone, Debug)] pub(crate) struct ChainIdGadget { @@ -68,7 +68,7 @@ impl ExecutionGadget for ChainIdGadget { self.chain_id.assign( region, offset, - Some(Word::random_linear_combine( + Value::known(Word::random_linear_combine( chain_id.to_le_bytes(), block.randomness, )), diff --git a/zkevm-circuits/src/evm_circuit/execution/codecopy.rs b/zkevm-circuits/src/evm_circuit/execution/codecopy.rs index a2a23e7987..b00b2d3f00 100644 --- a/zkevm-circuits/src/evm_circuit/execution/codecopy.rs +++ b/zkevm-circuits/src/evm_circuit/execution/codecopy.rs @@ -1,6 +1,6 @@ use bus_mapping::{circuit_input_builder::CopyDataType, evm::OpcodeId}; use eth_types::{evm_types::GasCost, Field, ToLittleEndian, ToScalar}; -use halo2_proofs::plonk::Error; +use halo2_proofs::{circuit::Value, plonk::Error}; use crate::{ evm_circuit::{ @@ -164,8 +164,11 @@ impl ExecutionGadget for CodeCopyGadget { .bytecodes .get(&call.code_hash) .expect("could not find current environment's bytecode"); - self.code_size - .assign(region, offset, Some(F::from(code.bytes.len() as u64)))?; + self.code_size.assign( + region, + offset, + Value::known(F::from(code.bytes.len() as u64)), + )?; // assign the destination memory offset. let memory_address = @@ -182,7 +185,14 @@ impl ExecutionGadget for CodeCopyGadget { self.memory_copier_gas .assign(region, offset, size.as_u64(), memory_expansion_cost)?; // rw_counter increase from copy table lookup is number of bytes copied. - self.copy_rwc_inc.assign(region, offset, size.to_scalar())?; + self.copy_rwc_inc.assign( + region, + offset, + Value::known( + size.to_scalar() + .expect("unexpected U256 -> Scalar conversion failure"), + ), + )?; Ok(()) } diff --git a/zkevm-circuits/src/evm_circuit/execution/codesize.rs b/zkevm-circuits/src/evm_circuit/execution/codesize.rs index d9443e60d9..31fe295452 100644 --- a/zkevm-circuits/src/evm_circuit/execution/codesize.rs +++ b/zkevm-circuits/src/evm_circuit/execution/codesize.rs @@ -1,7 +1,7 @@ use array_init::array_init; use bus_mapping::evm::OpcodeId; use eth_types::Field; -use halo2_proofs::plonk::Error; +use halo2_proofs::{circuit::Value, plonk::Error}; use crate::{ evm_circuit::{ @@ -83,11 +83,11 @@ impl ExecutionGadget for CodesizeGadget { .iter() .zip(codesize.to_le_bytes().iter()) { - c.assign(region, offset, Some(F::from(*b as u64)))?; + c.assign(region, offset, Value::known(F::from(*b as u64)))?; } self.codesize - .assign(region, offset, Some(F::from(codesize)))?; + .assign(region, offset, Value::known(F::from(codesize)))?; Ok(()) } diff --git a/zkevm-circuits/src/evm_circuit/execution/comparator.rs b/zkevm-circuits/src/evm_circuit/execution/comparator.rs index b5dc7a56d7..7358c43a25 100644 --- a/zkevm-circuits/src/evm_circuit/execution/comparator.rs +++ b/zkevm-circuits/src/evm_circuit/execution/comparator.rs @@ -14,7 +14,7 @@ use crate::{ util::Expr, }; use eth_types::{evm_types::OpcodeId, Field, ToLittleEndian}; -use halo2_proofs::plonk::Error; +use halo2_proofs::{circuit::Value, plonk::Error}; #[derive(Clone, Debug)] pub(crate) struct ComparatorGadget { @@ -160,7 +160,7 @@ impl ExecutionGadget for ComparatorGadget { self.a.assign(region, offset, Some(a))?; self.b.assign(region, offset, Some(b))?; self.result - .assign(region, offset, Some(F::from(result.low_u64())))?; + .assign(region, offset, Value::known(F::from(result.low_u64())))?; Ok(()) } diff --git a/zkevm-circuits/src/evm_circuit/execution/dup.rs b/zkevm-circuits/src/evm_circuit/execution/dup.rs index 11fb48b264..9a14b86517 100644 --- a/zkevm-circuits/src/evm_circuit/execution/dup.rs +++ b/zkevm-circuits/src/evm_circuit/execution/dup.rs @@ -12,7 +12,7 @@ use crate::{ util::Expr, }; use eth_types::{evm_types::OpcodeId, Field, ToLittleEndian}; -use halo2_proofs::plonk::Error; +use halo2_proofs::{circuit::Value, plonk::Error}; #[derive(Clone, Debug)] pub(crate) struct DupGadget { @@ -69,7 +69,7 @@ impl ExecutionGadget for DupGadget { self.value.assign( region, offset, - Some(Word::random_linear_combine( + Value::known(Word::random_linear_combine( value.to_le_bytes(), block.randomness, )), diff --git a/zkevm-circuits/src/evm_circuit/execution/end_tx.rs b/zkevm-circuits/src/evm_circuit/execution/end_tx.rs index a72750990f..6ecfc3cef5 100644 --- a/zkevm-circuits/src/evm_circuit/execution/end_tx.rs +++ b/zkevm-circuits/src/evm_circuit/execution/end_tx.rs @@ -20,7 +20,7 @@ use crate::{ util::Expr, }; use eth_types::{evm_types::MAX_REFUND_QUOTIENT_OF_GAS_USED, Field, ToScalar}; -use halo2_proofs::plonk::Error; +use halo2_proofs::{circuit::Value, plonk::Error}; use strum::EnumCount; #[derive(Clone, Debug)] @@ -202,10 +202,12 @@ impl ExecutionGadget for EndTxGadget { [step.rw_indices[3], step.rw_indices[4]].map(|idx| block.rws[idx].account_value_pair()); self.tx_id - .assign(region, offset, Some(F::from(tx.id as u64)))?; - self.tx_gas.assign(region, offset, Some(F::from(tx.gas)))?; + .assign(region, offset, Value::known(F::from(tx.id as u64)))?; + self.tx_gas + .assign(region, offset, Value::known(F::from(tx.gas)))?; let (max_refund, _) = self.max_refund.assign(region, offset, gas_used as u128)?; - self.refund.assign(region, offset, Some(F::from(refund)))?; + self.refund + .assign(region, offset, Value::known(F::from(refund)))?; self.effective_refund.assign( region, offset, @@ -221,8 +223,15 @@ impl ExecutionGadget for EndTxGadget { effective_refund + step.gas_left, gas_fee_refund, )?; - self.tx_caller_address - .assign(region, offset, tx.caller_address.to_scalar())?; + self.tx_caller_address.assign( + region, + offset, + Value::known( + tx.caller_address + .to_scalar() + .expect("unexpected Address -> Scalar conversion failure"), + ), + )?; self.gas_fee_refund.assign( region, offset, @@ -244,8 +253,17 @@ impl ExecutionGadget for EndTxGadget { gas_used, effective_tip * gas_used, )?; - self.coinbase - .assign(region, offset, block.context.coinbase.to_scalar())?; + self.coinbase.assign( + region, + offset, + Value::known( + block + .context + .coinbase + .to_scalar() + .expect("unexpected Address -> Scalar conversion failure"), + ), + )?; self.coinbase_reward.assign( region, offset, @@ -269,12 +287,15 @@ impl ExecutionGadget for EndTxGadget { self.current_cumulative_gas_used.assign( region, offset, - Some(F::from(current_cumulative_gas_used)), + Value::known(F::from(current_cumulative_gas_used)), )?; self.is_first_tx .assign(region, offset, F::from(tx.id as u64), F::one())?; - self.is_persistent - .assign(region, offset, Some(F::from(call.is_persistent as u64)))?; + self.is_persistent.assign( + region, + offset, + Value::known(F::from(call.is_persistent as u64)), + )?; Ok(()) } diff --git a/zkevm-circuits/src/evm_circuit/execution/error_oog_constant.rs b/zkevm-circuits/src/evm_circuit/execution/error_oog_constant.rs index c768cd20c8..2f7c8266cf 100644 --- a/zkevm-circuits/src/evm_circuit/execution/error_oog_constant.rs +++ b/zkevm-circuits/src/evm_circuit/execution/error_oog_constant.rs @@ -9,7 +9,7 @@ use crate::evm_circuit::{ }; use crate::util::Expr; use eth_types::Field; -use halo2_proofs::plonk::Error; +use halo2_proofs::{circuit::Value, plonk::Error}; #[derive(Clone, Debug)] pub(crate) struct ErrorOOGConstantGadget { @@ -58,7 +58,7 @@ impl ExecutionGadget for ErrorOOGConstantGadget { // Inputs/Outputs self.gas_required - .assign(region, offset, Some(F::from(step.gas_cost)))?; + .assign(region, offset, Value::known(F::from(step.gas_cost)))?; // Gas insufficient check // Get `gas_available` variable here once it's available self.insufficient_gas diff --git a/zkevm-circuits/src/evm_circuit/execution/extcodehash.rs b/zkevm-circuits/src/evm_circuit/execution/extcodehash.rs index 2852f9788c..67f26935bb 100644 --- a/zkevm-circuits/src/evm_circuit/execution/extcodehash.rs +++ b/zkevm-circuits/src/evm_circuit/execution/extcodehash.rs @@ -17,8 +17,8 @@ use crate::{ table::{AccountFieldTag, CallContextFieldTag}, util::Expr, }; -use eth_types::{evm_types::GasCost, Field, ToAddress, ToScalar, U256}; -use halo2_proofs::plonk::Error; +use eth_types::{evm_types::GasCost, Field, ToAddress}; +use halo2_proofs::{circuit::Value, plonk::Error}; use keccak256::EMPTY_HASH_LE; #[derive(Clone, Debug)] @@ -138,7 +138,7 @@ impl ExecutionGadget for ExtcodehashGadget { .assign(region, offset, Some(le_bytes))?; self.tx_id - .assign(region, offset, U256::from(tx.id).to_scalar())?; + .assign(region, offset, Value::known(F::from(tx.id as u64)))?; self.reversion_info.assign( region, offset, @@ -152,7 +152,7 @@ impl ExecutionGadget for ExtcodehashGadget { _ => unreachable!(), }; self.is_warm - .assign(region, offset, Some(F::from(is_warm)))?; + .assign(region, offset, Value::known(F::from(is_warm)))?; let [nonce, balance, code_hash] = [5, 6, 7].map(|i| { block.rws[step.rw_indices[i]] @@ -160,9 +160,10 @@ impl ExecutionGadget for ExtcodehashGadget { .value }); - self.nonce.assign(region, offset, Some(nonce))?; - self.balance.assign(region, offset, Some(balance))?; - self.code_hash.assign(region, offset, Some(code_hash))?; + self.nonce.assign(region, offset, Value::known(nonce))?; + self.balance.assign(region, offset, Value::known(balance))?; + self.code_hash + .assign(region, offset, Value::known(code_hash))?; let empty_code_hash_rlc = Word::random_linear_combine(*EMPTY_HASH_LE, block.randomness); self.is_empty.assign( diff --git a/zkevm-circuits/src/evm_circuit/execution/gasprice.rs b/zkevm-circuits/src/evm_circuit/execution/gasprice.rs index 0b5342d555..db44d07781 100644 --- a/zkevm-circuits/src/evm_circuit/execution/gasprice.rs +++ b/zkevm-circuits/src/evm_circuit/execution/gasprice.rs @@ -14,7 +14,7 @@ use crate::{ }; use bus_mapping::evm::OpcodeId; use eth_types::{Field, ToLittleEndian}; -use halo2_proofs::plonk::Error; +use halo2_proofs::{circuit::Value, plonk::Error}; #[derive(Clone, Debug)] pub(crate) struct GasPriceGadget { @@ -75,12 +75,12 @@ impl ExecutionGadget for GasPriceGadget { let gas_price = block.rws[step.rw_indices[1]].stack_value(); self.tx_id - .assign(region, offset, Some(F::from(tx.id as u64)))?; + .assign(region, offset, Value::known(F::from(tx.id as u64)))?; self.gas_price.assign( region, offset, - Some(Word::random_linear_combine( + Value::known(Word::random_linear_combine( gas_price.to_le_bytes(), block.randomness, )), diff --git a/zkevm-circuits/src/evm_circuit/execution/is_zero.rs b/zkevm-circuits/src/evm_circuit/execution/is_zero.rs index 509849d3e3..bbc1efc2fc 100644 --- a/zkevm-circuits/src/evm_circuit/execution/is_zero.rs +++ b/zkevm-circuits/src/evm_circuit/execution/is_zero.rs @@ -13,7 +13,7 @@ use crate::{ }; use bus_mapping::evm::OpcodeId; use eth_types::{Field, ToLittleEndian}; -use halo2_proofs::plonk::Error; +use halo2_proofs::{circuit::Value, plonk::Error}; #[derive(Clone, Debug)] pub(crate) struct IsZeroGadget { @@ -66,7 +66,7 @@ impl ExecutionGadget for IsZeroGadget { let value = block.rws[step.rw_indices[0]].stack_value(); let value = Word::random_linear_combine(value.to_le_bytes(), block.randomness); - self.value.assign(region, offset, Some(value))?; + self.value.assign(region, offset, Value::known(value))?; self.is_zero.assign(region, offset, value)?; Ok(()) diff --git a/zkevm-circuits/src/evm_circuit/execution/jumpi.rs b/zkevm-circuits/src/evm_circuit/execution/jumpi.rs index a0e4bf232f..0d7bdcfa36 100644 --- a/zkevm-circuits/src/evm_circuit/execution/jumpi.rs +++ b/zkevm-circuits/src/evm_circuit/execution/jumpi.rs @@ -18,7 +18,7 @@ use crate::{ util::Expr, }; use eth_types::{evm_types::OpcodeId, Field, ToLittleEndian}; -use halo2_proofs::plonk::Error; +use halo2_proofs::{circuit::Value, plonk::Error}; #[derive(Clone, Debug)] pub(crate) struct JumpiGadget { @@ -105,7 +105,8 @@ impl ExecutionGadget for JumpiGadget { .unwrap(), ), )?; - self.condition.assign(region, offset, Some(condition))?; + self.condition + .assign(region, offset, Value::known(condition))?; self.is_condition_zero.assign(region, offset, condition)?; Ok(()) diff --git a/zkevm-circuits/src/evm_circuit/execution/logs.rs b/zkevm-circuits/src/evm_circuit/execution/logs.rs index f8c73790a1..ff53f85a11 100644 --- a/zkevm-circuits/src/evm_circuit/execution/logs.rs +++ b/zkevm-circuits/src/evm_circuit/execution/logs.rs @@ -21,7 +21,7 @@ use array_init::array_init; use bus_mapping::circuit_input_builder::CopyDataType; use eth_types::Field; use eth_types::{evm_types::GasCost, evm_types::OpcodeId, ToLittleEndian, ToScalar}; -use halo2_proofs::plonk::Error; +use halo2_proofs::{circuit::Value, plonk::Error}; #[derive(Clone, Debug)] pub(crate) struct LogGadget { @@ -224,27 +224,41 @@ impl ExecutionGadget for LogGadget { block.rws[topic_stack_entry].stack_value().to_le_bytes(), block.randomness, ); - self.topic_selectors[i].assign(region, offset, Some(F::one()))?; + self.topic_selectors[i].assign(region, offset, Value::known(F::one()))?; topic_stack_entry.1 += 1; } else { - self.topic_selectors[i].assign(region, offset, Some(F::zero()))?; + self.topic_selectors[i].assign(region, offset, Value::known(F::zero()))?; } - self.topics[i].assign(region, offset, Some(topic))?; + self.topics[i].assign(region, offset, Value::known(topic))?; } - self.contract_address - .assign(region, offset, call.callee_address.to_scalar())?; + self.contract_address.assign( + region, + offset, + Value::known( + call.callee_address + .to_scalar() + .expect("unexpected Address -> Scalar conversion failure"), + ), + )?; self.is_static_call - .assign(region, offset, Some(F::from(call.is_static as u64)))?; + .assign(region, offset, Value::known(F::from(call.is_static as u64)))?; self.is_persistent - .assign(region, offset, Some(F::from(is_persistent)))?; + .assign(region, offset, Value::known(F::from(is_persistent)))?; self.tx_id - .assign(region, offset, Some(F::from(tx.id as u64)))?; + .assign(region, offset, Value::known(F::from(tx.id as u64)))?; // rw_counter increase from copy table lookup is `msize` memory reads + `msize` // log writes. - self.copy_rwc_inc - .assign(region, offset, (msize + msize).to_scalar())?; + self.copy_rwc_inc.assign( + region, + offset, + Value::known( + (msize + msize) + .to_scalar() + .expect("unexpected U256 -> Scalar conversion failure"), + ), + )?; Ok(()) } diff --git a/zkevm-circuits/src/evm_circuit/execution/origin.rs b/zkevm-circuits/src/evm_circuit/execution/origin.rs index 06c633b990..9fb45b00b0 100644 --- a/zkevm-circuits/src/evm_circuit/execution/origin.rs +++ b/zkevm-circuits/src/evm_circuit/execution/origin.rs @@ -15,7 +15,7 @@ use crate::{ }; use bus_mapping::evm::OpcodeId; use eth_types::{Field, ToLittleEndian}; -use halo2_proofs::plonk::Error; +use halo2_proofs::{circuit::Value, plonk::Error}; #[derive(Clone, Debug)] pub(crate) struct OriginGadget { @@ -76,7 +76,7 @@ impl ExecutionGadget for OriginGadget { // Assing TxId. self.tx_id - .assign(region, offset, Some(F::from(tx.id as u64)))?; + .assign(region, offset, Value::known(F::from(tx.id as u64)))?; // Assign Origin addr RLC. self.origin.assign( diff --git a/zkevm-circuits/src/evm_circuit/execution/pop.rs b/zkevm-circuits/src/evm_circuit/execution/pop.rs index d747ebc530..8fe37f4f71 100644 --- a/zkevm-circuits/src/evm_circuit/execution/pop.rs +++ b/zkevm-circuits/src/evm_circuit/execution/pop.rs @@ -13,7 +13,7 @@ use crate::{ }; use bus_mapping::evm::OpcodeId; use eth_types::{Field, ToLittleEndian}; -use halo2_proofs::plonk::Error; +use halo2_proofs::{circuit::Value, plonk::Error}; #[derive(Clone, Debug)] pub(crate) struct PopGadget { @@ -64,7 +64,7 @@ impl ExecutionGadget for PopGadget { self.value.assign( region, offset, - Some(Word::random_linear_combine( + Value::known(Word::random_linear_combine( value.to_le_bytes(), block.randomness, )), diff --git a/zkevm-circuits/src/evm_circuit/execution/push.rs b/zkevm-circuits/src/evm_circuit/execution/push.rs index 5c7bb66aed..f2d03f9806 100644 --- a/zkevm-circuits/src/evm_circuit/execution/push.rs +++ b/zkevm-circuits/src/evm_circuit/execution/push.rs @@ -13,7 +13,7 @@ use crate::{ }; use array_init::array_init; use eth_types::{evm_types::OpcodeId, Field, ToLittleEndian}; -use halo2_proofs::plonk::Error; +use halo2_proofs::{circuit::Value, plonk::Error}; #[derive(Clone, Debug)] pub(crate) struct PushGadget { @@ -134,7 +134,7 @@ impl ExecutionGadget for PushGadget { selector.assign( region, offset, - Some(F::from((idx < num_additional_pushed) as u64)), + Value::known(F::from((idx < num_additional_pushed) as u64)), )?; } diff --git a/zkevm-circuits/src/evm_circuit/execution/return.rs b/zkevm-circuits/src/evm_circuit/execution/return.rs index b70f0320ea..2dc49dbc59 100644 --- a/zkevm-circuits/src/evm_circuit/execution/return.rs +++ b/zkevm-circuits/src/evm_circuit/execution/return.rs @@ -8,7 +8,7 @@ use crate::{ util::Expr, }; use eth_types::Field; -use halo2_proofs::plonk::Error; +use halo2_proofs::{circuit::Value, plonk::Error}; #[derive(Clone, Debug)] pub(crate) struct ReturnGadget { @@ -41,7 +41,7 @@ impl ExecutionGadget for ReturnGadget { ) -> Result<(), Error> { let opcode = step.opcode.unwrap(); self.opcode - .assign(region, offset, Some(F::from(opcode.as_u64())))?; + .assign(region, offset, Value::known(F::from(opcode.as_u64())))?; Ok(()) } diff --git a/zkevm-circuits/src/evm_circuit/execution/selfbalance.rs b/zkevm-circuits/src/evm_circuit/execution/selfbalance.rs index 06b62a3b69..f8ea807303 100644 --- a/zkevm-circuits/src/evm_circuit/execution/selfbalance.rs +++ b/zkevm-circuits/src/evm_circuit/execution/selfbalance.rs @@ -14,7 +14,7 @@ use crate::{ }; use bus_mapping::evm::OpcodeId; use eth_types::{Field, ToLittleEndian, ToScalar}; -use halo2_proofs::plonk::Error; +use halo2_proofs::{circuit::Value, plonk::Error}; #[derive(Clone, Debug)] pub(crate) struct SelfbalanceGadget { @@ -68,14 +68,21 @@ impl ExecutionGadget for SelfbalanceGadget { ) -> Result<(), Error> { self.same_context.assign_exec_step(region, offset, step)?; - self.callee_address - .assign(region, offset, call.callee_address.to_scalar())?; + self.callee_address.assign( + region, + offset, + Value::known( + call.callee_address + .to_scalar() + .expect("unexpected Address -> Scalar conversion failure"), + ), + )?; let self_balance = block.rws[step.rw_indices[2]].stack_value(); self.self_balance.assign( region, offset, - Some(Word::random_linear_combine( + Value::known(Word::random_linear_combine( self_balance.to_le_bytes(), block.randomness, )), diff --git a/zkevm-circuits/src/evm_circuit/execution/sha3.rs b/zkevm-circuits/src/evm_circuit/execution/sha3.rs index 74e6cac130..accb2e9773 100644 --- a/zkevm-circuits/src/evm_circuit/execution/sha3.rs +++ b/zkevm-circuits/src/evm_circuit/execution/sha3.rs @@ -1,7 +1,7 @@ use bus_mapping::{circuit_input_builder::CopyDataType, evm::OpcodeId}; use eth_types::{evm_types::GasCost, Field, ToLittleEndian, ToScalar}; use gadgets::util::{not, Expr}; -use halo2_proofs::plonk::Error; +use halo2_proofs::{circuit::Value, plonk::Error}; use crate::evm_circuit::{ param::N_BYTES_MEMORY_WORD_SIZE, @@ -123,13 +123,20 @@ impl ExecutionGadget for Sha3Gadget { self.sha3_rlc .assign(region, offset, Some(sha3_output.to_le_bytes()))?; - self.copy_rwc_inc.assign(region, offset, size.to_scalar())?; + self.copy_rwc_inc.assign( + region, + offset, + Value::known( + size.to_scalar() + .expect("unexpected U256 -> Scalar conversion failure"), + ), + )?; let values: Vec = (3..3 + (size.low_u64() as usize)) .map(|i| block.rws[step.rw_indices[i]].memory_value()) .collect(); let rlc_acc = rlc::value(values.iter().rev(), block.randomness); - self.rlc_acc.assign(region, offset, Some(rlc_acc))?; + self.rlc_acc.assign(region, offset, Value::known(rlc_acc))?; // Memory expansion and dynamic gas cost for reading it. let (_, memory_expansion_gas_cost) = self.memory_expansion.assign( diff --git a/zkevm-circuits/src/evm_circuit/execution/shl_shr.rs b/zkevm-circuits/src/evm_circuit/execution/shl_shr.rs index cde9ce89c5..b5dc703f95 100644 --- a/zkevm-circuits/src/evm_circuit/execution/shl_shr.rs +++ b/zkevm-circuits/src/evm_circuit/execution/shl_shr.rs @@ -17,7 +17,7 @@ use crate::{ }; use bus_mapping::evm::OpcodeId; use eth_types::{Field, ToLittleEndian, U256}; -use halo2_proofs::plonk::Error; +use halo2_proofs::{circuit::Value, plonk::Error}; /// ShlShrGadget verifies opcode SHL and SHR. /// For SHL, verify pop1 * (2^pop2) % 2^256 == push; @@ -171,7 +171,7 @@ impl ExecutionGadget for ShlShrGadget { self.shift .assign(region, offset, Some(pop1.to_le_bytes()))?; self.shf0 - .assign(region, offset, Some(u64::from(shf0).into()))?; + .assign(region, offset, Value::known(u64::from(shf0).into()))?; self.mul_add_words .assign(region, offset, [quotient, divisor, remainder, dividend])?; let divisor_sum = (0..32).fold(0, |acc, idx| acc + divisor.byte(idx) as u64); diff --git a/zkevm-circuits/src/evm_circuit/execution/signed_comparator.rs b/zkevm-circuits/src/evm_circuit/execution/signed_comparator.rs index 0be4aaab09..46ea013bcb 100644 --- a/zkevm-circuits/src/evm_circuit/execution/signed_comparator.rs +++ b/zkevm-circuits/src/evm_circuit/execution/signed_comparator.rs @@ -14,7 +14,7 @@ use crate::{ util::Expr, }; use eth_types::{evm_types::OpcodeId, Field, ToLittleEndian}; -use halo2_proofs::plonk::Error; +use halo2_proofs::{circuit::Value, plonk::Error}; /// Gadget that implements the ExecutionGadget trait to handle the Opcodes SLT /// and SGT. @@ -206,7 +206,7 @@ impl ExecutionGadget for SignedComparatorGadget { self.a_lt_b.assign( region, offset, - Some(if a < b { F::one() } else { F::zero() }), + Value::known(if a < b { F::one() } else { F::zero() }), )?; self.a.assign(region, offset, Some(a_le_bytes))?; diff --git a/zkevm-circuits/src/evm_circuit/execution/signextend.rs b/zkevm-circuits/src/evm_circuit/execution/signextend.rs index 2358e96d5a..b5af6fdd93 100644 --- a/zkevm-circuits/src/evm_circuit/execution/signextend.rs +++ b/zkevm-circuits/src/evm_circuit/execution/signextend.rs @@ -17,7 +17,7 @@ use crate::{ use array_init::array_init; use bus_mapping::evm::OpcodeId; use eth_types::{Field, ToLittleEndian}; -use halo2_proofs::plonk::Error; +use halo2_proofs::{circuit::Value, plonk::Error}; #[derive(Clone, Debug)] pub(crate) struct SignextendGadget { @@ -185,7 +185,7 @@ impl ExecutionGadget for SignextendGadget { ]); let selector_value = selected + previous_selector_value; self.selectors[i] - .assign(region, offset, Some(selector_value)) + .assign(region, offset, Value::known(selector_value)) .unwrap(); previous_selector_value = selector_value; } @@ -196,7 +196,7 @@ impl ExecutionGadget for SignextendGadget { sign = (value[index[0] as usize] >> 7) as u64; } self.sign_byte - .assign(region, offset, Some(F::from(sign * 0xFF))) + .assign(region, offset, Value::known(F::from(sign * 0xFF))) .unwrap(); Ok(()) diff --git a/zkevm-circuits/src/evm_circuit/execution/sload.rs b/zkevm-circuits/src/evm_circuit/execution/sload.rs index d17b29915c..867eab1c2f 100644 --- a/zkevm-circuits/src/evm_circuit/execution/sload.rs +++ b/zkevm-circuits/src/evm_circuit/execution/sload.rs @@ -15,7 +15,10 @@ use crate::{ util::Expr, }; use eth_types::{evm_types::GasCost, Field, ToLittleEndian, ToScalar}; -use halo2_proofs::plonk::{Error, Expression}; +use halo2_proofs::{ + circuit::Value, + plonk::{Error, Expression}, +}; #[derive(Clone, Debug)] pub(crate) struct SloadGadget { @@ -101,22 +104,29 @@ impl ExecutionGadget for SloadGadget { self.same_context.assign_exec_step(region, offset, step)?; self.tx_id - .assign(region, offset, Some(F::from(tx.id as u64)))?; + .assign(region, offset, Value::known(F::from(tx.id as u64)))?; self.reversion_info.assign( region, offset, call.rw_counter_end_of_reversion, call.is_persistent, )?; - self.callee_address - .assign(region, offset, call.callee_address.to_scalar())?; + self.callee_address.assign( + region, + offset, + Value::known( + call.callee_address + .to_scalar() + .expect("unexpected Address -> Scalar conversion failure"), + ), + )?; let [key, value] = [step.rw_indices[4], step.rw_indices[6]].map(|idx| block.rws[idx].stack_value()); self.key.assign( region, offset, - Some(Word::random_linear_combine( + Value::known(Word::random_linear_combine( key.to_le_bytes(), block.randomness, )), @@ -124,7 +134,7 @@ impl ExecutionGadget for SloadGadget { self.value.assign( region, offset, - Some(Word::random_linear_combine( + Value::known(Word::random_linear_combine( value.to_le_bytes(), block.randomness, )), @@ -134,7 +144,7 @@ impl ExecutionGadget for SloadGadget { self.committed_value.assign( region, offset, - Some(Word::random_linear_combine( + Value::known(Word::random_linear_combine( committed_value.to_le_bytes(), block.randomness, )), @@ -142,7 +152,7 @@ impl ExecutionGadget for SloadGadget { let (_, is_warm) = block.rws[step.rw_indices[7]].tx_access_list_value_pair(); self.is_warm - .assign(region, offset, Some(F::from(is_warm as u64)))?; + .assign(region, offset, Value::known(F::from(is_warm as u64)))?; Ok(()) } diff --git a/zkevm-circuits/src/evm_circuit/execution/sstore.rs b/zkevm-circuits/src/evm_circuit/execution/sstore.rs index 81558315b1..04ed0dc3a2 100644 --- a/zkevm-circuits/src/evm_circuit/execution/sstore.rs +++ b/zkevm-circuits/src/evm_circuit/execution/sstore.rs @@ -17,7 +17,10 @@ use crate::{ }; use eth_types::{evm_types::GasCost, Field, ToLittleEndian, ToScalar}; -use halo2_proofs::plonk::{Error, Expression}; +use halo2_proofs::{ + circuit::Value, + plonk::{Error, Expression}, +}; #[derive(Clone, Debug)] pub(crate) struct SstoreGadget { @@ -145,24 +148,31 @@ impl ExecutionGadget for SstoreGadget { self.same_context.assign_exec_step(region, offset, step)?; self.tx_id - .assign(region, offset, Some(F::from(tx.id as u64)))?; + .assign(region, offset, Value::known(F::from(tx.id as u64)))?; self.is_static - .assign(region, offset, Some(F::from(call.is_static as u64)))?; + .assign(region, offset, Value::known(F::from(call.is_static as u64)))?; self.reversion_info.assign( region, offset, call.rw_counter_end_of_reversion, call.is_persistent, )?; - self.callee_address - .assign(region, offset, call.callee_address.to_scalar())?; + self.callee_address.assign( + region, + offset, + Value::known( + call.callee_address + .to_scalar() + .expect("unexpected Address -> Scalar conversion failure"), + ), + )?; let [key, value] = [step.rw_indices[5], step.rw_indices[6]].map(|idx| block.rws[idx].stack_value()); self.key.assign( region, offset, - Some(Word::random_linear_combine( + Value::known(Word::random_linear_combine( key.to_le_bytes(), block.randomness, )), @@ -170,7 +180,7 @@ impl ExecutionGadget for SstoreGadget { self.value.assign( region, offset, - Some(Word::random_linear_combine( + Value::known(Word::random_linear_combine( value.to_le_bytes(), block.randomness, )), @@ -180,7 +190,7 @@ impl ExecutionGadget for SstoreGadget { self.value_prev.assign( region, offset, - Some(Word::random_linear_combine( + Value::known(Word::random_linear_combine( value_prev.to_le_bytes(), block.randomness, )), @@ -188,7 +198,7 @@ impl ExecutionGadget for SstoreGadget { self.original_value.assign( region, offset, - Some(Word::random_linear_combine( + Value::known(Word::random_linear_combine( original_value.to_le_bytes(), block.randomness, )), @@ -196,11 +206,11 @@ impl ExecutionGadget for SstoreGadget { let (_, is_warm) = block.rws[step.rw_indices[8]].tx_access_list_value_pair(); self.is_warm - .assign(region, offset, Some(F::from(is_warm as u64)))?; + .assign(region, offset, Value::known(F::from(is_warm as u64)))?; let (tx_refund, tx_refund_prev) = block.rws[step.rw_indices[9]].tx_refund_value_pair(); self.tx_refund_prev - .assign(region, offset, Some(F::from(tx_refund_prev)))?; + .assign(region, offset, Value::known(F::from(tx_refund_prev)))?; self.gas_cost.assign( region, @@ -302,12 +312,12 @@ impl SstoreGasGadget { self.value.assign( region, offset, - Some(Word::random_linear_combine(value.to_le_bytes(), randomness)), + Value::known(Word::random_linear_combine(value.to_le_bytes(), randomness)), )?; self.value_prev.assign( region, offset, - Some(Word::random_linear_combine( + Value::known(Word::random_linear_combine( value_prev.to_le_bytes(), randomness, )), @@ -315,13 +325,13 @@ impl SstoreGasGadget { self.original_value.assign( region, offset, - Some(Word::random_linear_combine( + Value::known(Word::random_linear_combine( original_value.to_le_bytes(), randomness, )), )?; self.is_warm - .assign(region, offset, Some(F::from(is_warm as u64)))?; + .assign(region, offset, Value::known(F::from(is_warm as u64)))?; self.value_eq_prev.assign( region, offset, @@ -445,16 +455,16 @@ impl SstoreTxRefundGadget { randomness: F, ) -> Result<(), Error> { self.tx_refund_old - .assign(region, offset, Some(F::from(tx_refund_old)))?; + .assign(region, offset, Value::known(F::from(tx_refund_old)))?; self.value.assign( region, offset, - Some(Word::random_linear_combine(value.to_le_bytes(), randomness)), + Value::known(Word::random_linear_combine(value.to_le_bytes(), randomness)), )?; self.value_prev.assign( region, offset, - Some(Word::random_linear_combine( + Value::known(Word::random_linear_combine( value_prev.to_le_bytes(), randomness, )), @@ -462,7 +472,7 @@ impl SstoreTxRefundGadget { self.original_value.assign( region, offset, - Some(Word::random_linear_combine( + Value::known(Word::random_linear_combine( original_value.to_le_bytes(), randomness, )), diff --git a/zkevm-circuits/src/evm_circuit/execution/stop.rs b/zkevm-circuits/src/evm_circuit/execution/stop.rs index 798f9f1c35..6f230839f4 100644 --- a/zkevm-circuits/src/evm_circuit/execution/stop.rs +++ b/zkevm-circuits/src/evm_circuit/execution/stop.rs @@ -18,7 +18,7 @@ use crate::{ }; use bus_mapping::evm::OpcodeId; use eth_types::Field; -use halo2_proofs::plonk::Error; +use halo2_proofs::{circuit::Value, plonk::Error}; #[derive(Clone, Debug)] pub(crate) struct StopGadget { @@ -106,8 +106,11 @@ impl ExecutionGadget for StopGadget { .bytecodes .get(&call.code_hash) .expect("could not find current environment's bytecode"); - self.code_length - .assign(region, offset, Some(F::from(code.bytes.len() as u64)))?; + self.code_length.assign( + region, + offset, + Value::known(F::from(code.bytes.len() as u64)), + )?; self.is_out_of_range.assign( region, @@ -117,7 +120,7 @@ impl ExecutionGadget for StopGadget { let opcode = step.opcode.unwrap(); self.opcode - .assign(region, offset, Some(F::from(opcode.as_u64())))?; + .assign(region, offset, Value::known(F::from(opcode.as_u64())))?; self.restore_context .assign(region, offset, block, call, step)?; diff --git a/zkevm-circuits/src/evm_circuit/execution/swap.rs b/zkevm-circuits/src/evm_circuit/execution/swap.rs index 9e9373d46f..1c852a2731 100644 --- a/zkevm-circuits/src/evm_circuit/execution/swap.rs +++ b/zkevm-circuits/src/evm_circuit/execution/swap.rs @@ -12,7 +12,7 @@ use crate::{ util::Expr, }; use eth_types::{evm_types::OpcodeId, Field, ToLittleEndian}; -use halo2_proofs::plonk::Error; +use halo2_proofs::{circuit::Value, plonk::Error}; #[derive(Clone, Debug)] pub(crate) struct SwapGadget { @@ -77,7 +77,7 @@ impl ExecutionGadget for SwapGadget { cell.assign( region, offset, - Some(Word::random_linear_combine( + Value::known(Word::random_linear_combine( value.to_le_bytes(), block.randomness, )), diff --git a/zkevm-circuits/src/evm_circuit/step.rs b/zkevm-circuits/src/evm_circuit/step.rs index 880ec10861..00c1ada450 100644 --- a/zkevm-circuits/src/evm_circuit/step.rs +++ b/zkevm-circuits/src/evm_circuit/step.rs @@ -11,6 +11,7 @@ use bus_mapping::evm::OpcodeId; use eth_types::ToLittleEndian; use halo2_proofs::{ arithmetic::FieldExt, + circuit::Value, plonk::{Advice, Column, ConstraintSystem, Error, Expression}, }; use std::iter; @@ -400,13 +401,16 @@ impl DynamicSelectorHalf { ) -> Result<(), Error> { let odd = target % 2 == 1; let pair_index = target / 2; - self.target_odd - .assign(region, offset, Some(if odd { F::one() } else { F::zero() }))?; + self.target_odd.assign( + region, + offset, + Value::known(if odd { F::one() } else { F::zero() }), + )?; for (index, cell) in self.target_pairs.iter().enumerate() { cell.assign( region, offset, - Some(if index == pair_index { + Value::known(if index == pair_index { F::one() } else { F::zero() @@ -510,22 +514,26 @@ impl Step { self.state .execution_state .assign(region, offset, step.execution_state as usize)?; - self.state - .rw_counter - .assign(region, offset, Some(F::from(step.rw_counter as u64)))?; + self.state.rw_counter.assign( + region, + offset, + Value::known(F::from(step.rw_counter as u64)), + )?; self.state .call_id - .assign(region, offset, Some(F::from(call.id as u64)))?; + .assign(region, offset, Value::known(F::from(call.id as u64)))?; self.state .is_root - .assign(region, offset, Some(F::from(call.is_root as u64)))?; - self.state - .is_create - .assign(region, offset, Some(F::from(call.is_create as u64)))?; + .assign(region, offset, Value::known(F::from(call.is_root as u64)))?; + self.state.is_create.assign( + region, + offset, + Value::known(F::from(call.is_create as u64)), + )?; self.state.code_hash.assign( region, offset, - Some(RandomLinearCombination::random_linear_combine( + Value::known(RandomLinearCombination::random_linear_combine( call.code_hash.to_le_bytes(), block.randomness, )), @@ -533,29 +541,29 @@ impl Step { self.state.program_counter.assign( region, offset, - Some(F::from(step.program_counter as u64)), + Value::known(F::from(step.program_counter as u64)), )?; self.state.stack_pointer.assign( region, offset, - Some(F::from(step.stack_pointer as u64)), + Value::known(F::from(step.stack_pointer as u64)), )?; self.state .gas_left - .assign(region, offset, Some(F::from(step.gas_left)))?; + .assign(region, offset, Value::known(F::from(step.gas_left)))?; self.state.memory_word_size.assign( region, offset, - Some(F::from(step.memory_word_size())), + Value::known(F::from(step.memory_word_size())), )?; self.state.reversible_write_counter.assign( region, offset, - Some(F::from(step.reversible_write_counter as u64)), + Value::known(F::from(step.reversible_write_counter as u64)), )?; self.state .log_id - .assign(region, offset, Some(F::from(step.log_id as u64)))?; + .assign(region, offset, Value::known(F::from(step.log_id as u64)))?; Ok(()) } } diff --git a/zkevm-circuits/src/evm_circuit/util.rs b/zkevm-circuits/src/evm_circuit/util.rs index 27e0af544e..79867a4d7a 100644 --- a/zkevm-circuits/src/evm_circuit/util.rs +++ b/zkevm-circuits/src/evm_circuit/util.rs @@ -8,7 +8,7 @@ use crate::{ use eth_types::U256; use halo2_proofs::{ arithmetic::FieldExt, - circuit::{AssignedCell, Region}, + circuit::{AssignedCell, Region, Value}, plonk::{Advice, Assigned, Column, ConstraintSystem, Error, Expression, VirtualCells}, poly::Rotation, }; @@ -43,7 +43,7 @@ impl Cell { &self, region: &mut CachedRegion<'_, '_, F>, offset: usize, - value: Option, + value: Value, ) -> Result, Error> { region.assign_advice( || { @@ -54,7 +54,7 @@ impl Cell { }, self.column, offset + self.rotation, - || value.ok_or(Error::Synthesis), + || value, ) } } @@ -107,7 +107,7 @@ impl<'r, 'b, F: FieldExt> CachedRegion<'r, 'b, F> { to: V, ) -> Result, Error> where - V: FnMut() -> Result + 'v, + V: FnMut() -> Value + 'v, for<'vr> Assigned: From<&'vr VR>, A: Fn() -> AR, AR: Into, @@ -116,11 +116,10 @@ impl<'r, 'b, F: FieldExt> CachedRegion<'r, 'b, F> { let res = self.region.assign_advice(annotation, column, offset, to); // Cache the value if let Result::Ok(cell) = &res { - let call_value = cell.value_field(); - if let Some(value) = call_value { + cell.value_field().map(|f| { self.advice[column.index() - self.width_start][offset - self.height_start] = - value.evaluate(); - } + f.evaluate(); + }); } res } @@ -157,15 +156,25 @@ impl StoredExpression { let value = self.expr.evaluate( &|scalar| scalar, &|_| unimplemented!("selector column"), - &|_, column_index, rotation| region.get_fixed(offset, column_index, rotation), - &|_, column_index, rotation| region.get_advice(offset, column_index, rotation), - &|_, column_index, rotation| region.get_instance(offset, column_index, rotation), + &|fixed_query| { + region.get_fixed(offset, fixed_query.column_index(), fixed_query.rotation()) + }, + &|advide_query| { + region.get_advice(offset, advide_query.column_index(), advide_query.rotation()) + }, + &|instance_query| { + region.get_instance( + offset, + instance_query.column_index(), + instance_query.rotation(), + ) + }, &|a| -a, &|a, b| a + b, &|a, b| a * b, &|a, scalar| a * scalar, ); - self.cell.assign(region, offset, Some(value)) + self.cell.assign(region, offset, Value::known(value)) } } @@ -340,7 +349,9 @@ impl RandomLinearCombination { self.cells .iter() .zip(bytes.iter()) - .map(|(cell, byte)| cell.assign(region, offset, Some(F::from(*byte as u64)))) + .map(|(cell, byte)| { + cell.assign(region, offset, Value::known(F::from(*byte as u64))) + }) .collect() }) } diff --git a/zkevm-circuits/src/evm_circuit/util/common_gadget.rs b/zkevm-circuits/src/evm_circuit/util/common_gadget.rs index ad8c411ca3..66718503ea 100644 --- a/zkevm-circuits/src/evm_circuit/util/common_gadget.rs +++ b/zkevm-circuits/src/evm_circuit/util/common_gadget.rs @@ -17,7 +17,10 @@ use crate::{ util::Expr, }; use eth_types::{Field, ToLittleEndian, ToScalar, U256}; -use halo2_proofs::plonk::{Error, Expression}; +use halo2_proofs::{ + circuit::Value, + plonk::{Error, Expression}, +}; /// Construction of execution state that stays in the same call context, which /// lookups the opcode and verifies the execution state is responsible for it, @@ -67,7 +70,7 @@ impl SameContextGadget { ) -> Result<(), Error> { let opcode = step.opcode.unwrap(); self.opcode - .assign(region, offset, Some(F::from(opcode.as_u64())))?; + .assign(region, offset, Value::known(F::from(opcode.as_u64())))?; self.sufficient_gas_left.assign( region, @@ -217,13 +220,21 @@ impl RestoreContextGadget { caller_reversible_write_counter, ), ] { - cell.assign(region, offset, value.to_scalar())?; + cell.assign( + region, + offset, + Value::known( + value + .to_scalar() + .expect("unexpected U256 -> Scalar conversion failure"), + ), + )?; } self.caller_code_hash.assign( region, offset, - Some(Word::random_linear_combine( + Value::known(Word::random_linear_combine( caller_code_hash.to_le_bytes(), block.randomness, )), diff --git a/zkevm-circuits/src/evm_circuit/util/constraint_builder.rs b/zkevm-circuits/src/evm_circuit/util/constraint_builder.rs index 591165a0a2..f08c87490f 100644 --- a/zkevm-circuits/src/evm_circuit/util/constraint_builder.rs +++ b/zkevm-circuits/src/evm_circuit/util/constraint_builder.rs @@ -12,9 +12,12 @@ use crate::{ util::Expr, }; use eth_types::Field; -use halo2_proofs::plonk::{ - Error, - Expression::{self, Constant}, +use halo2_proofs::{ + circuit::Value, + plonk::{ + Error, + Expression::{self, Constant}, + }, }; use super::{rlc, CachedRegion, CellType, StoredExpression}; @@ -126,10 +129,10 @@ impl ReversionInfo { self.rw_counter_end_of_reversion.assign( region, offset, - Some(F::from(rw_counter_end_of_reversion as u64)), + Value::known(F::from(rw_counter_end_of_reversion as u64)), )?; self.is_persistent - .assign(region, offset, Some(F::from(is_persistent as u64)))?; + .assign(region, offset, Value::known(F::from(is_persistent as u64)))?; Ok(()) } } diff --git a/zkevm-circuits/src/evm_circuit/util/math_gadget.rs b/zkevm-circuits/src/evm_circuit/util/math_gadget.rs index 4270c4ee4e..a665a1960c 100644 --- a/zkevm-circuits/src/evm_circuit/util/math_gadget.rs +++ b/zkevm-circuits/src/evm_circuit/util/math_gadget.rs @@ -7,7 +7,10 @@ use crate::{ util::Expr, }; use eth_types::{Field, ToLittleEndian, ToScalar, Word}; -use halo2_proofs::plonk::{Error, Expression}; +use halo2_proofs::{ + circuit::Value, + plonk::{Error, Expression}, +}; /// Returns `1` when `value == 0`, and returns `0` otherwise. #[derive(Clone, Debug)] @@ -45,7 +48,7 @@ impl IsZeroGadget { value: F, ) -> Result { let inverse = value.invert().unwrap_or(F::zero()); - self.inverse.assign(region, offset, Some(inverse))?; + self.inverse.assign(region, offset, Value::known(inverse))?; Ok(if value.is_zero().into() { F::one() } else { @@ -130,12 +133,12 @@ impl BatchedIsZeroGadget { let is_zero = if let Some(inverse) = values.iter().find_map(|value| Option::from(value.invert())) { self.nonempty_witness - .assign(region, offset, Some(inverse))?; + .assign(region, offset, Value::known(inverse))?; F::zero() } else { F::one() }; - self.is_zero.assign(region, offset, Some(is_zero))?; + self.is_zero.assign(region, offset, Value::known(is_zero))?; Ok(is_zero) } @@ -239,14 +242,27 @@ impl .fold(Word::zero(), |acc, addend_hi| acc + addend_hi); let carry_lo = (sum_of_addends_lo - sum_lo) >> 128; - self.carry_lo.assign(region, offset, carry_lo.to_scalar())?; + self.carry_lo.assign( + region, + offset, + Value::known( + carry_lo + .to_scalar() + .expect("unexpected U256 -> Scalar conversion failure"), + ), + )?; if !CHECK_OVREFLOW { let carry_hi = (sum_of_addends_hi + carry_lo - sum_hi) >> 128; - self.carry_hi - .as_ref() - .unwrap() - .assign(region, offset, carry_hi.to_scalar())?; + self.carry_hi.as_ref().unwrap().assign( + region, + offset, + Value::known( + carry_hi + .to_scalar() + .expect("unexpected U256 -> Scalar conversion failure"), + ), + )?; } Ok(()) @@ -332,7 +348,7 @@ impl MulWordByU64Gadget { .to_le_bytes() .iter(), ) { - cell.assign(region, offset, Some(F::from(*byte as u64)))?; + cell.assign(region, offset, Value::known(F::from(*byte as u64)))?; } Ok(()) @@ -373,7 +389,7 @@ impl RangeCheckGadget { ) -> Result<(), Error> { let bytes = value.to_repr(); for (idx, part) in self.parts.iter().enumerate() { - part.assign(region, offset, Some(F::from(bytes[idx] as u64)))?; + part.assign(region, offset, Value::known(F::from(bytes[idx] as u64)))?; } Ok(()) } @@ -429,14 +445,21 @@ impl LtGadget { ) -> Result<(F, Vec), Error> { // Set `lt` let lt = lhs < rhs; - self.lt - .assign(region, offset, Some(if lt { F::one() } else { F::zero() }))?; + self.lt.assign( + region, + offset, + Value::known(if lt { F::one() } else { F::zero() }), + )?; // Set the bytes of diff let diff = (lhs - rhs) + (if lt { self.range } else { F::zero() }); let diff_bytes = diff.to_repr(); for (idx, diff) in self.diff.iter().enumerate() { - diff.assign(region, offset, Some(F::from(diff_bytes[idx] as u64)))?; + diff.assign( + region, + offset, + Value::known(F::from(diff_bytes[idx] as u64)), + )?; } Ok((if lt { F::one() } else { F::zero() }, diff_bytes.to_vec())) @@ -595,7 +618,7 @@ impl PairSelectGadget { _b: F, ) -> Result<(F, F), Error> { let is_a = if value == a { F::one() } else { F::zero() }; - self.is_a.assign(region, offset, Some(is_a))?; + self.is_a.assign(region, offset, Value::known(is_a))?; Ok((is_a, F::one() - is_a)) } @@ -665,9 +688,9 @@ impl ConstantDivisionGadget { let remainder = numerator % denominator; self.quotient - .assign(region, offset, Some(F::from_u128(quotient)))?; + .assign(region, offset, Value::known(F::from_u128(quotient)))?; self.remainder - .assign(region, offset, Some(F::from_u128(remainder)))?; + .assign(region, offset, Value::known(F::from_u128(remainder)))?; self.quotient_range_check .assign(region, offset, F::from_u128(quotient))?; @@ -864,13 +887,13 @@ impl MulAddWordsGadget { self.carry_lo .iter() .zip(carry_lo.to_le_bytes().iter()) - .map(|(cell, byte)| cell.assign(region, offset, Some(F::from(*byte as u64)))) + .map(|(cell, byte)| cell.assign(region, offset, Value::known(F::from(*byte as u64)))) .collect::, _>>()?; self.carry_hi .iter() .zip(carry_hi.to_le_bytes().iter()) - .map(|(cell, byte)| cell.assign(region, offset, Some(F::from(*byte as u64)))) + .map(|(cell, byte)| cell.assign(region, offset, Value::known(F::from(*byte as u64)))) .collect::, _>>()?; Ok(()) @@ -1122,19 +1145,19 @@ impl MulAddWords512Gadget { self.carry_0 .iter() .zip(carry_0.to_le_bytes().iter()) - .map(|(cell, byte)| cell.assign(region, offset, Some(F::from(*byte as u64)))) + .map(|(cell, byte)| cell.assign(region, offset, Value::known(F::from(*byte as u64)))) .collect::, _>>()?; self.carry_1 .iter() .zip(carry_1.to_le_bytes().iter()) - .map(|(cell, byte)| cell.assign(region, offset, Some(F::from(*byte as u64)))) + .map(|(cell, byte)| cell.assign(region, offset, Value::known(F::from(*byte as u64)))) .collect::, _>>()?; self.carry_2 .iter() .zip(carry_2.to_le_bytes().iter()) - .map(|(cell, byte)| cell.assign(region, offset, Some(F::from(*byte as u64)))) + .map(|(cell, byte)| cell.assign(region, offset, Value::known(F::from(*byte as u64)))) .collect::, _>>()?; Ok(()) } diff --git a/zkevm-circuits/src/evm_circuit/util/memory_gadget.rs b/zkevm-circuits/src/evm_circuit/util/memory_gadget.rs index 4b5658b686..d71f5d4b57 100644 --- a/zkevm-circuits/src/evm_circuit/util/memory_gadget.rs +++ b/zkevm-circuits/src/evm_circuit/util/memory_gadget.rs @@ -13,7 +13,10 @@ use crate::{ }; use array_init::array_init; use eth_types::{evm_types::GasCost, Field, ToLittleEndian, U256}; -use halo2_proofs::plonk::{Error, Expression}; +use halo2_proofs::{ + circuit::Value, + plonk::{Error, Expression}, +}; /// Decodes the usable part of an address stored in a Word pub(crate) mod address_low { @@ -104,7 +107,7 @@ impl MemoryAddressGadget { self.memory_offset.assign( region, offset, - Some(Word::random_linear_combine(memory_offset_bytes, randomness)), + Value::known(Word::random_linear_combine(memory_offset_bytes, randomness)), )?; self.memory_offset_bytes.assign( region, @@ -498,8 +501,8 @@ impl assert_eq!(selectors.len(), MAX_BYTES); for (idx, selector) in selectors.iter().enumerate() { - self.selectors[idx].assign(region, offset, Some(F::from(*selector as u64)))?; - self.bytes[idx].assign(region, offset, Some(F::from(bytes[idx] as u64)))?; + self.selectors[idx].assign(region, offset, Value::known(F::from(*selector as u64)))?; + self.bytes[idx].assign(region, offset, Value::known(F::from(bytes[idx] as u64)))?; // assign bound_dist and bound_dist_is_zero let oob = addr_start + idx as u64 >= addr_end; let bound_dist = if oob { @@ -507,7 +510,7 @@ impl } else { F::from(addr_end - addr_start - idx as u64) }; - self.bound_dist[idx].assign(region, offset, Some(bound_dist))?; + self.bound_dist[idx].assign(region, offset, Value::known(bound_dist))?; self.bound_dist_is_zero[idx].assign(region, offset, bound_dist)?; } Ok(()) diff --git a/zkevm-circuits/src/evm_circuit/witness.rs b/zkevm-circuits/src/evm_circuit/witness.rs index 5c97cb77b7..ef1616884f 100644 --- a/zkevm-circuits/src/evm_circuit/witness.rs +++ b/zkevm-circuits/src/evm_circuit/witness.rs @@ -21,7 +21,7 @@ use eth_types::{evm_types::OpcodeId, ToWord}; use eth_types::{Address, Field, ToLittleEndian, ToScalar, Word}; use eth_types::{ToAddress, U256}; use halo2_proofs::arithmetic::FieldExt; -use halo2_proofs::pairing::bn256::Fr; +use halo2_proofs::halo2curves::bn256::Fr; use itertools::Itertools; use sha3::{Digest, Keccak256}; use std::{collections::HashMap, iter}; diff --git a/zkevm-circuits/src/keccak_circuit/keccak_bit.rs b/zkevm-circuits/src/keccak_circuit/keccak_bit.rs index 03238a42af..b7987702e3 100644 --- a/zkevm-circuits/src/keccak_circuit/keccak_bit.rs +++ b/zkevm-circuits/src/keccak_circuit/keccak_bit.rs @@ -13,7 +13,7 @@ use crate::{ use eth_types::{Field, ToScalar}; use gadgets::util::{and, select, sum, xor}; use halo2_proofs::{ - circuit::{Layouter, Region, SimpleFloorPlanner}, + circuit::{Layouter, Region, SimpleFloorPlanner, Value}, plonk::{Advice, Circuit, Column, ConstraintSystem, Error, Fixed, TableColumn}, poly::Rotation, }; @@ -640,7 +640,7 @@ impl KeccakBitConfig { || format!("assign {} {}", name, offset), *column, offset, - || Ok(*value), + || Value::known(*value), )?; } @@ -655,7 +655,7 @@ impl KeccakBitConfig { || format!("assign {} {}", name, offset), *column, offset, - || Ok(*value), + || Value::known(*value), )?; } @@ -665,7 +665,7 @@ impl KeccakBitConfig { || format!("assign state bit {} {}", idx, offset), *column, offset, - || Ok(F::from(*bit as u64)), + || Value::known(F::from(*bit as u64)), )?; } @@ -675,7 +675,7 @@ impl KeccakBitConfig { || format!("assign theta c bit {} {}", idx, offset), *column, offset, - || Ok(F::from(*bit as u64)), + || Value::known(F::from(*bit as u64)), )?; } @@ -685,7 +685,7 @@ impl KeccakBitConfig { || format!("assign absorb bits {} {}", idx, offset), *column, offset, - || Ok(F::from(*bit as u64)), + || Value::known(F::from(*bit as u64)), )?; } @@ -700,7 +700,7 @@ impl KeccakBitConfig { || format!("assign padding selector {} {}", idx, offset), *column, offset, - || Ok(F::from(*is_padding as u64)), + || Value::known(F::from(*is_padding as u64)), )?; } @@ -711,7 +711,7 @@ impl KeccakBitConfig { || format!("assign padding selector {} {}", idx, offset), *column, offset, - || Ok(*data_rlc), + || Value::known(*data_rlc), )?; } @@ -721,7 +721,7 @@ impl KeccakBitConfig { || format!("assign round constant bit {} {}", *pos, offset), *column, offset, - || Ok(F::from(((ROUND_CST[round] >> *pos) & 1) as u64)), + || Value::known(F::from(((ROUND_CST[round] >> *pos) & 1) as u64)), )?; } @@ -748,7 +748,7 @@ impl KeccakBitConfig { || "theta c output", self.theta_c_table[idx + 1], offset, - || Ok(F::from(*input & 1)), + || Value::known(F::from(*input & 1)), )?; } @@ -756,7 +756,7 @@ impl KeccakBitConfig { || "theta c input", self.theta_c_table[0], offset, - || Ok(F::from(compressed_value)), + || Value::known(F::from(compressed_value)), )?; } Ok(()) @@ -981,7 +981,7 @@ fn multi_keccak(bytes: &[Vec], r: F) -> Vec> { #[cfg(test)] mod tests { use super::*; - use halo2_proofs::{dev::MockProver, pairing::bn256::Fr}; + use halo2_proofs::{dev::MockProver, halo2curves::bn256::Fr}; fn verify(k: u32, inputs: Vec>, success: bool) { let mut circuit = KeccakBitCircuit::new(2usize.pow(k)); diff --git a/zkevm-circuits/src/keccak_circuit/keccak_packed.rs b/zkevm-circuits/src/keccak_circuit/keccak_packed.rs index 84ef94eab0..a9d84dfb78 100644 --- a/zkevm-circuits/src/keccak_circuit/keccak_packed.rs +++ b/zkevm-circuits/src/keccak_circuit/keccak_packed.rs @@ -14,7 +14,7 @@ use eth_types::Word; use eth_types::{Field, ToScalar}; use gadgets::util::{and, select, sum}; use halo2_proofs::{ - circuit::{Layouter, Region, SimpleFloorPlanner}, + circuit::{Layouter, Region, SimpleFloorPlanner, Value}, plonk::{Advice, Circuit, Column, ConstraintSystem, Error, Expression, Fixed, TableColumn}, poly::Rotation, }; @@ -1274,7 +1274,7 @@ impl KeccakPackedConfig { || format!("assign {} {}", name, offset), *column, offset, - || Ok(*value), + || Value::known(*value), )?; } @@ -1309,7 +1309,7 @@ impl KeccakPackedConfig { || format!("assign {} {}", name, offset), *column, offset, - || Ok(*value), + || Value::known(*value), )?; } @@ -1319,7 +1319,7 @@ impl KeccakPackedConfig { || format!("assign state word {} {}", idx, offset), *column, offset, - || Ok(*word), + || Value::known(*word), )?; } @@ -1334,7 +1334,7 @@ impl KeccakPackedConfig { || format!("assign lookup value {} {}", idx, offset), *column, offset, - || Ok(*bit), + || Value::known(*bit), )?; } @@ -1343,7 +1343,12 @@ impl KeccakPackedConfig { || format!("assign round cst {}", offset), self.round_cst, offset, - || Ok(pack_u64(ROUND_CST[round]).to_scalar().unwrap()), + || { + let word: F = pack_u64(ROUND_CST[round]) + .to_scalar() + .expect("unexpected Word -> Scalar conversion failure"); + Value::known(word) + }, )?; Ok(()) @@ -1676,7 +1681,7 @@ fn multi_keccak(bytes: &[Vec], r: F) -> Vec> { #[cfg(test)] mod tests { use super::*; - use halo2_proofs::{dev::MockProver, pairing::bn256::Fr}; + use halo2_proofs::{dev::MockProver, halo2curves::bn256::Fr}; fn verify(k: u32, inputs: Vec>, success: bool) { let mut circuit = KeccakPackedCircuit::new(2usize.pow(k)); diff --git a/zkevm-circuits/src/keccak_circuit/keccak_packed_multi.rs b/zkevm-circuits/src/keccak_circuit/keccak_packed_multi.rs index efad20f7d3..2acfcd3c93 100644 --- a/zkevm-circuits/src/keccak_circuit/keccak_packed_multi.rs +++ b/zkevm-circuits/src/keccak_circuit/keccak_packed_multi.rs @@ -15,7 +15,7 @@ use gadgets::util::{and, select, sum}; use halo2_proofs::arithmetic::FieldExt; use halo2_proofs::plonk::VirtualCells; use halo2_proofs::{ - circuit::{Layouter, Region, SimpleFloorPlanner}, + circuit::{Layouter, Region, SimpleFloorPlanner, Value}, plonk::{Advice, Circuit, Column, ConstraintSystem, Error, Expression, Fixed, TableColumn}, poly::Rotation, }; @@ -1609,7 +1609,7 @@ impl KeccakPackedConfig { || format!("assign {} {}", name, offset), *column, offset, - || Ok(*value), + || Value::known(*value), )?; } @@ -1624,7 +1624,7 @@ impl KeccakPackedConfig { || format!("assign {} {}", name, offset), *column, offset, - || Ok(*value), + || Value::known(*value), )?; } @@ -1639,7 +1639,7 @@ impl KeccakPackedConfig { || format!("assign lookup value {} {}", idx, offset), column.advice, offset, - || Ok(*bit), + || Value::known(*bit), )?; } @@ -1648,7 +1648,7 @@ impl KeccakPackedConfig { || format!("assign round cst {}", offset), self.round_cst, offset, - || Ok(row.round_cst), + || Value::known(row.round_cst), )?; Ok(()) @@ -2047,7 +2047,7 @@ fn multi_keccak(bytes: &[Vec], r: F) -> Vec> { #[cfg(test)] mod tests { use super::*; - use halo2_proofs::{dev::MockProver, pairing::bn256::Fr}; + use halo2_proofs::{dev::MockProver, halo2curves::bn256::Fr}; fn verify(k: u32, inputs: Vec>, success: bool) { let mut circuit = KeccakPackedCircuit::new(2usize.pow(k)); diff --git a/zkevm-circuits/src/keccak_circuit/util.rs b/zkevm-circuits/src/keccak_circuit/util.rs index 5d80ce0fbb..38eada2069 100644 --- a/zkevm-circuits/src/keccak_circuit/util.rs +++ b/zkevm-circuits/src/keccak_circuit/util.rs @@ -2,7 +2,7 @@ use eth_types::{Field, ToScalar, Word}; use halo2_proofs::{ - circuit::Layouter, + circuit::{Layouter, Value}, plonk::{Error, TableColumn}, }; use itertools::Itertools; @@ -374,13 +374,13 @@ pub fn load_normalize_table( || format!("{} input", name), tables[0], offset, - || Ok(F::from(input)), + || Value::known(F::from(input)), )?; table.assign_cell( || format!("{} output", name), tables[1], offset, - || Ok(F::from(output)), + || Value::known(F::from(output)), )?; } Ok(()) @@ -397,9 +397,14 @@ pub fn load_pack_table( || "pack table", |mut table| { for (offset, idx) in (0u64..256).enumerate() { - table.assign_cell(|| "unpacked", tables[0], offset, || Ok(F::from(idx)))?; + table.assign_cell( + || "unpacked", + tables[0], + offset, + || Value::known(F::from(idx)), + )?; let packed: F = pack(&into_bits(&[idx as u8])).to_scalar().unwrap(); - table.assign_cell(|| "packed", tables[1], offset, || Ok(packed))?; + table.assign_cell(|| "packed", tables[1], offset, || Value::known(packed))?; } Ok(()) }, @@ -434,13 +439,13 @@ pub fn load_lookup_table( || format!("{} input", name), tables[0], offset, - || Ok(F::from(input)), + || Value::known(F::from(input)), )?; table.assign_cell( || format!("{} output", name), tables[1], offset, - || Ok(F::from(output)), + || Value::known(F::from(output)), )?; } Ok(()) diff --git a/zkevm-circuits/src/pi_circuit.rs b/zkevm-circuits/src/pi_circuit.rs index a966d5b9ea..84aafc9cc4 100644 --- a/zkevm-circuits/src/pi_circuit.rs +++ b/zkevm-circuits/src/pi_circuit.rs @@ -1,6 +1,5 @@ //! Public Input Circuit implementation -use std::io::Cursor; use std::marker::PhantomData; use eth_types::geth_types::BlockConstants; @@ -11,13 +10,12 @@ use eth_types::{ geth_types::Transaction, Address, Field, ToBigEndian, ToLittleEndian, ToScalar, Word, }; use ethers_core::types::Block; -use halo2_proofs::arithmetic::BaseExt; use halo2_proofs::plonk::Instance; use crate::table::TxFieldTag; use crate::util::random_linear_combine_word as rlc; use halo2_proofs::{ - circuit::{AssignedCell, Layouter, Region, SimpleFloorPlanner}, + circuit::{AssignedCell, Layouter, Region, SimpleFloorPlanner, Value}, plonk::{Advice, Circuit, Column, ConstraintSystem, Error, Fixed, Selector}, poly::Rotation, }; @@ -128,10 +126,7 @@ impl PublicData { .sign_data(chain_id) .expect("Error computing tx_sign_hash"); let mut msg_hash_le = [0u8; 32]; - sign_data - .msg_hash - .write(&mut Cursor::new(&mut msg_hash_le[..])) - .expect("cannot write bytes to array"); + msg_hash_le.copy_from_slice(sign_data.msg_hash.to_bytes().as_slice()); tx_vals.push(TxValues { nonce: tx.nonce, gas_price: tx.gas_price, @@ -345,10 +340,15 @@ impl self.q_tx_table.enable(region, offset)?; // Assign vals to Tx_table - region.assign_advice(|| "tx_id", self.tx_id, offset, || Ok(tx_id))?; - region.assign_fixed(|| "tag", self.tag, offset, || Ok(tag))?; - region.assign_advice(|| "index", self.index, offset, || Ok(index))?; - region.assign_advice(|| "tx_value", self.tx_value, offset, || Ok(tx_value))?; + region.assign_advice(|| "tx_id", self.tx_id, offset, || Value::known(tx_id))?; + region.assign_fixed(|| "tag", self.tag, offset, || Value::known(tag))?; + region.assign_advice(|| "index", self.index, offset, || Value::known(index))?; + region.assign_advice( + || "tx_value", + self.tx_value, + offset, + || Value::known(tx_value), + )?; // Assign vals to raw_public_inputs column let tx_table_len = TX_LEN * MAX_TXS + 1 + MAX_CALLDATA; @@ -361,21 +361,21 @@ impl || "raw_pi.tx_id", self.raw_public_inputs, offset + id_offset, - || Ok(tx_id), + || Value::known(tx_id), )?; region.assign_advice( || "raw_pi.tx_index", self.raw_public_inputs, offset + index_offset, - || Ok(index), + || Value::known(index), )?; region.assign_advice( || "raw_pi.tx_value", self.raw_public_inputs, offset + value_offset, - || Ok(tx_value), + || Value::known(tx_value), )?; // Add copy to vec @@ -402,98 +402,153 @@ impl } // zero row - region.assign_advice(|| "zero", self.block_value, offset, || Ok(F::zero()))?; - region.assign_advice(|| "zero", self.raw_public_inputs, offset, || Ok(F::zero()))?; + region.assign_advice( + || "zero", + self.block_value, + offset, + || Value::known(F::zero()), + )?; + region.assign_advice( + || "zero", + self.raw_public_inputs, + offset, + || Value::known(F::zero()), + )?; raw_pi_vals[offset] = F::zero(); offset += 1; // coinbase let coinbase = block_values.coinbase.to_scalar().unwrap(); - region.assign_advice(|| "coinbase", self.block_value, offset, || Ok(coinbase))?; + region.assign_advice( + || "coinbase", + self.block_value, + offset, + || Value::known(coinbase), + )?; region.assign_advice( || "coinbase", self.raw_public_inputs, offset, - || Ok(coinbase), + || Value::known(coinbase), )?; raw_pi_vals[offset] = coinbase; offset += 1; // gas_limit let gas_limit = F::from(block_values.gas_limit); - region.assign_advice(|| "gas_limit", self.block_value, offset, || Ok(gas_limit))?; + region.assign_advice( + || "gas_limit", + self.block_value, + offset, + || Value::known(gas_limit), + )?; region.assign_advice( || "gas_limit", self.raw_public_inputs, offset, - || Ok(gas_limit), + || Value::known(gas_limit), )?; raw_pi_vals[offset] = gas_limit; offset += 1; // number let number = F::from(block_values.number); - region.assign_advice(|| "number", self.block_value, offset, || Ok(number))?; - region.assign_advice(|| "number", self.raw_public_inputs, offset, || Ok(number))?; + region.assign_advice( + || "number", + self.block_value, + offset, + || Value::known(number), + )?; + region.assign_advice( + || "number", + self.raw_public_inputs, + offset, + || Value::known(number), + )?; raw_pi_vals[offset] = number; offset += 1; // timestamp let timestamp = F::from(block_values.timestamp); - region.assign_advice(|| "timestamp", self.block_value, offset, || Ok(timestamp))?; + region.assign_advice( + || "timestamp", + self.block_value, + offset, + || Value::known(timestamp), + )?; region.assign_advice( || "timestamp", self.raw_public_inputs, offset, - || Ok(timestamp), + || Value::known(timestamp), )?; raw_pi_vals[offset] = timestamp; offset += 1; // difficulty let difficulty = rlc(block_values.difficulty.to_le_bytes(), randomness); - region.assign_advice(|| "difficulty", self.block_value, offset, || Ok(difficulty))?; + region.assign_advice( + || "difficulty", + self.block_value, + offset, + || Value::known(difficulty), + )?; region.assign_advice( || "difficulty", self.raw_public_inputs, offset, - || Ok(difficulty), + || Value::known(difficulty), )?; raw_pi_vals[offset] = difficulty; offset += 1; // base_fee let base_fee = rlc(block_values.base_fee.to_le_bytes(), randomness); - region.assign_advice(|| "base_fee", self.block_value, offset, || Ok(base_fee))?; + region.assign_advice( + || "base_fee", + self.block_value, + offset, + || Value::known(base_fee), + )?; region.assign_advice( || "base_fee", self.raw_public_inputs, offset, - || Ok(base_fee), + || Value::known(base_fee), )?; raw_pi_vals[offset] = base_fee; offset += 1; // chain_id let chain_id = F::from(block_values.chain_id); - region.assign_advice(|| "chain_id", self.block_value, offset, || Ok(chain_id))?; + region.assign_advice( + || "chain_id", + self.block_value, + offset, + || Value::known(chain_id), + )?; let chain_id_cell = region.assign_advice( || "chain_id", self.raw_public_inputs, offset, - || Ok(chain_id), + || Value::known(chain_id), )?; raw_pi_vals[offset] = chain_id; offset += 1; for prev_hash in block_values.history_hashes { let prev_hash = rlc(prev_hash.to_fixed_bytes(), randomness); - region.assign_advice(|| "prev_hash", self.block_value, offset, || Ok(prev_hash))?; + region.assign_advice( + || "prev_hash", + self.block_value, + offset, + || Value::known(prev_hash), + )?; region.assign_advice( || "prev_hash", self.raw_public_inputs, offset, - || Ok(prev_hash), + || Value::known(prev_hash), )?; raw_pi_vals[offset] = prev_hash; offset += 1; @@ -532,7 +587,7 @@ impl || "state.root", self.raw_public_inputs, offset, - || Ok(state_root), + || Value::known(state_root), )?; raw_pi_vals[offset] = state_root; offset += 1; @@ -543,7 +598,7 @@ impl || "parent_block.hash", self.raw_public_inputs, offset, - || Ok(prev_state_root), + || Value::known(prev_state_root), )?; raw_pi_vals[offset] = prev_state_root; Ok([state_root_cell, prev_state_root_cell]) @@ -567,9 +622,14 @@ impl || "rpi_rlc_acc", self.rpi_rlc_acc, offset, - || Ok(rpi_rlc_acc), + || Value::known(rpi_rlc_acc), + )?; + region.assign_advice( + || "rand_rpi", + self.rand_rpi, + offset, + || Value::known(rand_rpi), )?; - region.assign_advice(|| "rand_rpi", self.rand_rpi, offset, || Ok(rand_rpi))?; self.q_end.enable(region, offset)?; // Next rows @@ -580,18 +640,28 @@ impl || "rpi_rlc_acc", self.rpi_rlc_acc, offset, - || Ok(rpi_rlc_acc), + || Value::known(rpi_rlc_acc), + )?; + region.assign_advice( + || "rand_rpi", + self.rand_rpi, + offset, + || Value::known(rand_rpi), )?; - region.assign_advice(|| "rand_rpi", self.rand_rpi, offset, || Ok(rand_rpi))?; self.q_not_end.enable(region, offset)?; } // First row rpi_rlc_acc *= rand_rpi; rpi_rlc_acc += raw_pi_vals[0]; - let rpi_rlc = - region.assign_advice(|| "rpi_rlc_acc", self.rpi_rlc_acc, 0, || Ok(rpi_rlc_acc))?; - let rpi_rand = region.assign_advice(|| "rand_rpi", self.rand_rpi, 0, || Ok(rand_rpi))?; + let rpi_rlc = region.assign_advice( + || "rpi_rlc_acc", + self.rpi_rlc_acc, + 0, + || Value::known(rpi_rlc_acc), + )?; + let rpi_rand = + region.assign_advice(|| "rand_rpi", self.rand_rpi, 0, || Value::known(rand_rpi))?; self.q_not_end.enable(region, 0)?; Ok((rpi_rand, rpi_rlc)) } @@ -776,7 +846,7 @@ mod pi_circuit_test { use crate::test_util::rand_tx; use halo2_proofs::{ dev::{MockProver, VerifyFailure}, - pairing::bn256::Fr, + halo2curves::bn256::Fr, }; use pretty_assertions::assert_eq; use rand::SeedableRng; diff --git a/zkevm-circuits/src/state_circuit.rs b/zkevm-circuits/src/state_circuit.rs index 0c0d2a40c4..2b6dde1db4 100644 --- a/zkevm-circuits/src/state_circuit.rs +++ b/zkevm-circuits/src/state_circuit.rs @@ -19,7 +19,7 @@ use constraint_builder::{ConstraintBuilder, Queries}; use eth_types::{Address, Field}; use gadgets::binary_number::{BinaryNumberChip, BinaryNumberConfig}; use halo2_proofs::{ - circuit::{Layouter, Region, SimpleFloorPlanner}, + circuit::{Layouter, Region, SimpleFloorPlanner, Value}, plonk::{Advice, Circuit, Column, ConstraintSystem, Error, Expression, Fixed, VirtualCells}, poly::Rotation, }; @@ -153,7 +153,12 @@ impl StateCircuitConfig { log::trace!("state circuit assign offset:{} row:{:#?}", offset, row); } - region.assign_fixed(|| "selector", self.selector, offset, || Ok(F::one()))?; + region.assign_fixed( + || "selector", + self.selector, + offset, + || Value::known(F::one()), + )?; tag_chip.assign(region, offset, &row.tag())?; @@ -193,7 +198,7 @@ impl StateCircuitConfig { || "initial_value", self.initial_value, offset, - || Ok(initial_value), + || Value::known(initial_value), )?; } @@ -291,7 +296,12 @@ where let offset = usize::try_from(isize::try_from(padding_length).unwrap() + *row_offset) .unwrap(); - region.assign_advice(|| "override", advice_column, offset, || Ok(f))?; + region.assign_advice( + || "override", + advice_column, + offset, + || Value::known(f), + )?; } } diff --git a/zkevm-circuits/src/state_circuit/lexicographic_ordering.rs b/zkevm-circuits/src/state_circuit/lexicographic_ordering.rs index 3d1afc291a..ebde496300 100644 --- a/zkevm-circuits/src/state_circuit/lexicographic_ordering.rs +++ b/zkevm-circuits/src/state_circuit/lexicographic_ordering.rs @@ -7,7 +7,7 @@ use crate::{ use eth_types::{Field, ToBigEndian}; use gadgets::binary_number::{AsBits, BinaryNumberChip, BinaryNumberConfig}; use halo2_proofs::{ - circuit::Region, + circuit::{Region, Value}, plonk::{Advice, Column, ConstraintSystem, Error, Expression, Fixed, VirtualCells}, poly::Rotation, }; @@ -200,7 +200,7 @@ impl Config { || "upper_limb_difference", self.selector, offset, - || Ok(F::one()), + || Value::known(F::one()), )?; let cur_be_limbs = rw_to_be_limbs(cur); @@ -223,13 +223,13 @@ impl Config { || "limb_difference", self.limb_difference, offset, - || Ok(limb_difference), + || Value::known(limb_difference), )?; region.assign_advice( || "limb_difference_inverse", self.limb_difference_inverse, offset, - || Ok(limb_difference.invert().unwrap()), + || Value::known(limb_difference.invert().unwrap()), )?; Ok(!matches!( diff --git a/zkevm-circuits/src/state_circuit/lookups.rs b/zkevm-circuits/src/state_circuit/lookups.rs index a3bc95ad92..4aa5963be2 100644 --- a/zkevm-circuits/src/state_circuit/lookups.rs +++ b/zkevm-circuits/src/state_circuit/lookups.rs @@ -1,7 +1,7 @@ use crate::table::CallContextFieldTag; use eth_types::Field; use halo2_proofs::{ - circuit::Layouter, + circuit::{Layouter, Value}, plonk::{Column, ConstraintSystem, Error, Expression, Fixed, VirtualCells}, poly::Rotation, }; @@ -109,7 +109,7 @@ impl Chip { || format!("assign {} in u{} fixed column", i, exponent), column, i, - || Ok(F::from(i as u64)), + || Value::known(F::from(i as u64)), )?; } Ok(()) @@ -129,7 +129,7 @@ impl Chip { }, self.config.call_context_field_tag, field_tag as usize, - || Ok(F::from(field_tag as u64)), + || Value::known(F::from(field_tag as u64)), )?; } Ok(()) diff --git a/zkevm-circuits/src/state_circuit/multiple_precision_integer.rs b/zkevm-circuits/src/state_circuit/multiple_precision_integer.rs index 2b1d8baf9a..9987f8c8fc 100644 --- a/zkevm-circuits/src/state_circuit/multiple_precision_integer.rs +++ b/zkevm-circuits/src/state_circuit/multiple_precision_integer.rs @@ -3,7 +3,7 @@ use super::{N_LIMBS_ACCOUNT_ADDRESS, N_LIMBS_RW_COUNTER}; use crate::util::Expr; use eth_types::{Address, Field}; use halo2_proofs::{ - circuit::{Layouter, Region}, + circuit::{Layouter, Region, Value}, plonk::{Advice, Column, ConstraintSystem, Error, Expression, Fixed, VirtualCells}, poly::Rotation, }; @@ -71,7 +71,7 @@ impl Config { || format!("limb[{}] in address mpi", i), self.limbs[i], offset, - || Ok(F::from(limb as u64)), + || Value::known(F::from(limb as u64)), )?; } Ok(()) @@ -90,7 +90,7 @@ impl Config { || format!("limb[{}] in u32 mpi", i), self.limbs[i], offset, - || Ok(F::from(limb as u64)), + || Value::known(F::from(limb as u64)), )?; } Ok(()) diff --git a/zkevm-circuits/src/state_circuit/random_linear_combination.rs b/zkevm-circuits/src/state_circuit/random_linear_combination.rs index c6104590f1..b0687141a5 100644 --- a/zkevm-circuits/src/state_circuit/random_linear_combination.rs +++ b/zkevm-circuits/src/state_circuit/random_linear_combination.rs @@ -1,7 +1,7 @@ use crate::evm_circuit::util::rlc; use eth_types::{Field, ToLittleEndian, U256}; use halo2_proofs::{ - circuit::{Layouter, Region}, + circuit::{Layouter, Region, Value}, plonk::{Advice, Column, ConstraintSystem, Error, Expression, Fixed, VirtualCells}, poly::Rotation, }; @@ -42,7 +42,7 @@ impl Config { || format!("byte[{}] in rlc", i), self.bytes[i], offset, - || Ok(F::from(byte as u64)), + || Value::known(F::from(byte as u64)), )?; } Ok(()) diff --git a/zkevm-circuits/src/state_circuit/test.rs b/zkevm-circuits/src/state_circuit/test.rs index e9fb24ed22..6a725e265d 100644 --- a/zkevm-circuits/src/state_circuit/test.rs +++ b/zkevm-circuits/src/state_circuit/test.rs @@ -12,12 +12,13 @@ use eth_types::{ Address, Field, ToAddress, Word, U256, }; use gadgets::binary_number::AsBits; -use halo2_proofs::poly::commitment::Params; +use halo2_proofs::poly::kzg::commitment::ParamsKZG; use halo2_proofs::{ dev::{MockProver, VerifyFailure}, - pairing::bn256::{Bn256, Fr, G1Affine}, + halo2curves::bn256::{Bn256, Fr}, plonk::{keygen_vk, Advice, Circuit, Column, ConstraintSystem}, }; +use rand::SeedableRng; use std::collections::{BTreeSet, HashMap}; use strum::IntoEnumIterator; @@ -109,8 +110,7 @@ fn degree() { #[test] fn verifying_key_independent_of_rw_length() { let randomness = Fr::from(0xcafeu64); - let degree = 17; - let params = Params::::unsafe_setup::(degree); + let params = ParamsKZG::::setup(17, rand_chacha::ChaCha20Rng::seed_from_u64(2)); let no_rows = StateCircuit::::new(randomness, RwMap::default(), N_ROWS); let one_row = StateCircuit::::new( diff --git a/zkevm-circuits/src/super_circuit.rs b/zkevm-circuits/src/super_circuit.rs index 6a1b794001..fc9bf8a739 100644 --- a/zkevm-circuits/src/super_circuit.rs +++ b/zkevm-circuits/src/super_circuit.rs @@ -68,11 +68,13 @@ use super::copy_circuit::CopyCircuit; use crate::{evm_circuit::witness::block_convert, tx_circuit::sign_verify::POW_RAND_SIZE}; use bus_mapping::mock::BlockData; use eth_types::geth_types::{self, GethData}; -use group::{Curve, Group}; use halo2_proofs::arithmetic::{CurveAffine, Field as Halo2Field}; -use halo2_proofs::pairing::bn256::Fr; +use halo2_proofs::halo2curves::{ + bn256::Fr, + group::{Curve, Group}, + secp256k1::Secp256k1Affine, +}; use rand::RngCore; -use secp256k1::Secp256k1Affine; use strum::IntoEnumIterator; /// Configuration of the Super Circuit diff --git a/zkevm-circuits/src/table.rs b/zkevm-circuits/src/table.rs index c29844de11..4cf149e72b 100644 --- a/zkevm-circuits/src/table.rs +++ b/zkevm-circuits/src/table.rs @@ -12,7 +12,7 @@ use eth_types::{Field, ToAddress, ToLittleEndian, ToScalar, Word, U256}; use gadgets::binary_number::{BinaryNumberChip, BinaryNumberConfig}; use halo2_proofs::{ arithmetic::FieldExt, - circuit::Region, + circuit::{Region, Value}, plonk::{Advice, Column, ConstraintSystem, Error}, }; use halo2_proofs::{circuit::Layouter, plonk::*, poly::Rotation}; @@ -127,7 +127,7 @@ impl TxTable { || "tx table all-zero row", column, offset, - || Ok(F::zero()), + || Value::known(F::zero()), )?; } offset += 1; @@ -140,7 +140,7 @@ impl TxTable { || format!("tx table row {}", offset), *column, offset, - || Ok(value), + || Value::known(value), )?; } offset += 1; @@ -385,7 +385,12 @@ impl RwTable { (self.aux1, row.aux1), (self.aux2, row.aux2), ] { - region.assign_advice(|| "assign rw row on rw table", column, offset, || Ok(value))?; + region.assign_advice( + || "assign rw row on rw table", + column, + offset, + || Value::known(value), + )?; } Ok(()) } @@ -476,7 +481,7 @@ impl BytecodeTable { || "bytecode table all-zero row", column, offset, - || Ok(F::zero()), + || Value::known(F::zero()), )?; } offset += 1; @@ -489,7 +494,7 @@ impl BytecodeTable { || format!("bytecode table row {}", offset), *column, offset, - || Ok(value), + || Value::known(value), )?; } offset += 1; @@ -574,7 +579,7 @@ impl BlockTable { || "block table all-zero row", column, offset, - || Ok(F::zero()), + || Value::known(F::zero()), )?; } offset += 1; @@ -586,7 +591,7 @@ impl BlockTable { || format!("block table row {}", offset), *column, offset, - || Ok(value), + || Value::known(value), )?; } offset += 1; @@ -664,7 +669,7 @@ impl KeccakTable { || "keccak table all-zero row", column, offset, - || Ok(F::zero()), + || Value::known(F::zero()), )?; } offset += 1; @@ -678,7 +683,7 @@ impl KeccakTable { || format!("keccak table row {}", offset), *column, offset, - || Ok(value), + || Value::known(value), )?; } offset += 1; @@ -825,7 +830,7 @@ impl CopyTable { || "copy table all-zero row", column, offset, - || Ok(F::zero()), + || Value::known(F::zero()), )?; } offset += 1; @@ -839,7 +844,7 @@ impl CopyTable { || format!("copy table row {}", offset), *column, offset, - || Ok(value), + || Value::known(value), )?; } tag_chip.assign(&mut region, offset, &tag)?; diff --git a/zkevm-circuits/src/test_util.rs b/zkevm-circuits/src/test_util.rs index cab5139dd1..6b2012f584 100644 --- a/zkevm-circuits/src/test_util.rs +++ b/zkevm-circuits/src/test_util.rs @@ -5,7 +5,7 @@ use ethers_core::types::{NameOrAddress, TransactionRequest}; use ethers_core::utils::keccak256; use ethers_signers::{LocalWallet, Signer}; use halo2_proofs::dev::{MockProver, VerifyFailure}; -use halo2_proofs::pairing::bn256::Fr; +use halo2_proofs::halo2curves::bn256::Fr; use mock::TestContext; use rand::{CryptoRng, Rng}; diff --git a/zkevm-circuits/src/tx_circuit.rs b/zkevm-circuits/src/tx_circuit.rs index 320e2ce57c..e419d1c640 100644 --- a/zkevm-circuits/src/tx_circuit.rs +++ b/zkevm-circuits/src/tx_circuit.rs @@ -14,7 +14,7 @@ use eth_types::{ {geth_types::Transaction, Address, Field, ToLittleEndian, ToScalar}, }; use halo2_proofs::{ - circuit::{AssignedCell, Layouter, Region, SimpleFloorPlanner}, + circuit::{AssignedCell, Layouter, Region, SimpleFloorPlanner, Value}, plonk::{Advice, Circuit, Column, ConstraintSystem, Error, Expression}, }; use itertools::Itertools; @@ -22,8 +22,14 @@ use log::error; use sign_verify::{SignVerifyChip, SignVerifyConfig}; use std::marker::PhantomData; -pub use group::{Curve, Group}; -pub use secp256k1::Secp256k1Affine; +pub use halo2_proofs::halo2curves::{ + group::{ + ff::{Field as GroupField, PrimeField}, + prime::PrimeCurveAffine, + Curve, Group, GroupEncoding, + }, + secp256k1::{self, Secp256k1Affine, Secp256k1Compressed}, +}; pub use sign_verify::{POW_RAND_SIZE, VERIF_HEIGHT}; /// Config for TxCircuit @@ -76,10 +82,25 @@ impl TxCircuitConfig { index: usize, value: F, ) -> Result, Error> { - region.assign_advice(|| "tx_id", self.tx_id, offset, || Ok(F::from(tx_id as u64)))?; - region.assign_advice(|| "tag", self.tag, offset, || Ok(F::from(tag as u64)))?; - region.assign_advice(|| "index", self.index, offset, || Ok(F::from(index as u64)))?; - region.assign_advice(|| "value", self.value, offset, || Ok(value)) + region.assign_advice( + || "tx_id", + self.tx_id, + offset, + || Value::known(F::from(tx_id as u64)), + )?; + region.assign_advice( + || "tag", + self.tag, + offset, + || Value::known(F::from(tag as u64)), + )?; + region.assign_advice( + || "index", + self.index, + offset, + || Value::known(F::from(index as u64)), + )?; + region.assign_advice(|| "value", self.value, offset, || Value::known(value)) } } @@ -159,7 +180,11 @@ impl let address_cell = assigned_sig_verif.address.cell(); let msg_hash_rlc_cell = assigned_sig_verif.msg_hash_rlc.cell(); - let msg_hash_rlc_value = assigned_sig_verif.msg_hash_rlc.value(); + let mut msg_hash_rlc_value = F::zero(); + assigned_sig_verif.msg_hash_rlc.value().map(|f| { + msg_hash_rlc_value = *f; + f + }); for (tag, value) in &[ ( TxFieldTag::Nonce, @@ -199,10 +224,7 @@ impl .fold(0, |acc, byte| acc + if *byte == 0 { 4 } else { 16 }), ), ), - ( - TxFieldTag::TxSignHash, - *msg_hash_rlc_value.unwrap_or(&F::zero()), - ), + (TxFieldTag::TxSignHash, msg_hash_rlc_value), ] { let assigned_cell = config.assign_row(&mut region, offset, i + 1, *tag, 0, *value)?; @@ -285,6 +307,7 @@ impl Circuit config: Self::Config, mut layouter: impl Layouter, ) -> Result<(), Error> { + config.sign_verify.load_range(&mut layouter)?; self.assign(&config, &mut layouter)?; config.keccak_table.load( &mut layouter, @@ -301,11 +324,10 @@ impl Circuit mod tx_circuit_tests { use super::*; use eth_types::address; - use group::{Curve, Group}; use halo2_proofs::{ arithmetic::CurveAffine, dev::{MockProver, VerifyFailure}, - pairing::bn256::Fr, + halo2curves::{bn256::Fr, group::Group}, }; use mock::AddrOrWallet; use pretty_assertions::assert_eq; diff --git a/zkevm-circuits/src/tx_circuit/sign_verify.rs b/zkevm-circuits/src/tx_circuit/sign_verify.rs index f91765eebb..891bd7ebb9 100644 --- a/zkevm-circuits/src/tx_circuit/sign_verify.rs +++ b/zkevm-circuits/src/tx_circuit/sign_verify.rs @@ -14,25 +14,24 @@ use ecdsa::ecdsa::{AssignedEcdsaSig, AssignedPublicKey, EcdsaChip}; use eth_types::sign_types::{pk_bytes_le, pk_bytes_swap_endianness, SignData}; use eth_types::{self, Field}; use gadgets::is_zero::{IsZeroChip, IsZeroConfig, IsZeroInstruction}; +use halo2_proofs::halo2curves::secp256k1::Secp256k1Affine; use halo2_proofs::{ - arithmetic::BaseExt, - circuit::{AssignedCell, Layouter, Region}, + arithmetic::FieldExt, + circuit::{AssignedCell, Layouter, Region, Value}, + halo2curves::secp256k1, plonk::{Advice, Column, ConstraintSystem, Error, Expression, Selector}, poly::Rotation, }; -use integer::{ - AssignedInteger, IntegerChip, IntegerConfig, IntegerInstructions, WrongExt, - NUMBER_OF_LOOKUP_LIMBS, -}; +use integer::{AssignedInteger, IntegerChip, IntegerConfig, IntegerInstructions, Range}; + use itertools::Itertools; use keccak256::plain::Keccak; use log::error; use maingate::{ - Assigned, AssignedValue, MainGate, MainGateConfig, MainGateInstructions, RangeChip, - RangeConfig, RangeInstructions, RegionCtx, UnassignedValue, + AssignedValue, MainGate, MainGateConfig, MainGateInstructions, RangeChip, RangeConfig, + RangeInstructions, RegionCtx, }; -use secp256k1::Secp256k1Affine; -use std::{io::Cursor, marker::PhantomData}; +use std::marker::PhantomData; /// Power of randomness vector size required for the SignVerifyChip pub const POW_RAND_SIZE: usize = 63; @@ -81,7 +80,7 @@ fn copy_integer_bytes_le( || format!("{} byte {}", name, i), dst[i], offset, - || byte.value().ok_or(Error::Synthesis), + || byte.value().copied(), )?; region.constrain_equal(assigned_cell.cell(), byte.cell())?; } @@ -226,7 +225,12 @@ impl SignVerifyConfig { let mut overflow_bit_lengths: Vec = vec![]; overflow_bit_lengths.extend(rns_base.overflow_lengths()); overflow_bit_lengths.extend(rns_scalar.overflow_lengths()); - let range_config = RangeChip::::configure(meta, &main_gate_config, overflow_bit_lengths); + let range_config = RangeChip::::configure( + meta, + &main_gate_config, + vec![BIT_LEN_LIMB / NUMBER_OF_LIMBS, 8], + overflow_bit_lengths, + ); Self { q_enable, @@ -252,10 +256,9 @@ pub(crate) struct KeccakAux { impl SignVerifyConfig { pub(crate) fn load_range(&self, layouter: &mut impl Layouter) -> Result<(), Error> { - let bit_len_lookup = BIT_LEN_LIMB / NUMBER_OF_LOOKUP_LIMBS; - let range_chip = RangeChip::::new(self.range_config.clone(), bit_len_lookup); - range_chip.load_limb_range_table(layouter)?; - range_chip.load_overflow_range_tables(layouter)?; + let range_chip = RangeChip::::new(self.range_config.clone()); + range_chip.load_composition_tables(layouter)?; + range_chip.load_overflow_tables(layouter)?; Ok(()) } @@ -283,7 +286,7 @@ pub(crate) struct AssignedSignatureVerify { // Returns assigned constants [256^1, 256^2, .., 256^{n-1}] fn assign_pows_256( - ctx: &mut RegionCtx<'_, '_, F>, + ctx: &mut RegionCtx<'_, F>, main_gate: &MainGate, n: usize, ) -> Result>, Error> { @@ -297,36 +300,27 @@ fn assign_pows_256( // Return an array of bytes that corresponds to the little endian representation // of the integer, adding the constraints to verify the correctness of the // conversion (byte range check included). -fn integer_to_bytes_le( - ctx: &mut RegionCtx<'_, '_, F>, - main_gate: &MainGate, +fn integer_to_bytes_le( + ctx: &mut RegionCtx<'_, F>, range_chip: &RangeChip, - pows_256: &[AssignedValue], - int: &AssignedInteger, + int: &AssignedInteger, ) -> Result<[AssignedValue; 32], Error> { - let mut int_le = Vec::new(); - int_le.extend(int.limbs()[0].decompose(9, 8).expect("bad decompose")); - int_le.extend(int.limbs()[1].decompose(9, 8).expect("bad decompose")); - int_le.extend(int.limbs()[2].decompose(9, 8).expect("bad decompose")); - int_le.extend(int.limbs()[3].decompose(5, 8).expect("bad decompose")); - let int_le: Vec> = int_le - .iter() - .map(|b| range_chip.range_value(ctx, &UnassignedValue::from(Some(*b)), 8)) - .try_collect() - .map_err(|e| { - error!("RangeChip::range_value error: {:?}", e); - e - })?; - let int_le: [AssignedValue; 32] = int_le.try_into().expect("vec to array of size 32"); - for (j, positions) in [1..9, 1..9, 1..9, 1..5].iter().enumerate() { - let mut acc = int_le[j * 9]; - for i in positions.clone() { - let shifted = main_gate.mul(ctx, &int_le[j * 9 + i], &pows_256[i - 1])?; - acc = main_gate.add(ctx, &acc, &shifted)?; - } - main_gate.assert_equal(ctx, &acc, &(&int.limbs()[j]).into())?; - } - Ok(int_le) + let (_, limb0_bytes) = + range_chip.decompose(ctx, int.limbs()[0].as_ref().value().copied(), 8, 72)?; + let (_, limb1_bytes) = + range_chip.decompose(ctx, int.limbs()[1].as_ref().value().copied(), 8, 72)?; + let (_, limb2_bytes) = + range_chip.decompose(ctx, int.limbs()[2].as_ref().value().copied(), 8, 72)?; + let (_, limb3_bytes) = + range_chip.decompose(ctx, int.limbs()[3].as_ref().value().copied(), 8, 40)?; + Ok(std::iter::empty() + .chain(limb0_bytes) + .chain(limb1_bytes) + .chain(limb2_bytes) + .chain(limb3_bytes) + .collect_vec() + .try_into() + .unwrap()) } /// Helper structure pass around references to all the chips required for an @@ -342,13 +336,10 @@ struct ChipsRef<'a, F: Field, const NUMBER_OF_LIMBS: usize, const BIT_LEN_LIMB: impl SignVerifyChip { fn assign_aux( &self, - region: &mut Region<'_, F>, + ctx: &mut RegionCtx<'_, F>, ecc_chip: &mut GeneralEccChip, ) -> Result<(), Error> { - let ctx_offset = &mut 0; - let ctx = &mut RegionCtx::new(region, ctx_offset); - - ecc_chip.assign_aux_generator(ctx, Some(self.aux_generator))?; + ecc_chip.assign_aux_generator(ctx, Value::known(self.aux_generator))?; ecc_chip.assign_aux(ctx, self.window_size, 1)?; Ok(()) } @@ -367,37 +358,36 @@ impl SignVerifyChip { let (sig_r, sig_s) = signature; let ChipsRef { - main_gate, + main_gate: _, range_chip, ecc_chip, scalar_chip, ecdsa_chip, } = chips; - let integer_r = ecc_chip.new_unassigned_scalar(Some(*sig_r)); - let integer_s = ecc_chip.new_unassigned_scalar(Some(*sig_s)); - let msg_hash = ecc_chip.new_unassigned_scalar(Some(*msg_hash)); + let integer_r = ecc_chip.new_unassigned_scalar(Value::known(*sig_r)); + let integer_s = ecc_chip.new_unassigned_scalar(Value::known(*sig_s)); + let msg_hash = ecc_chip.new_unassigned_scalar(Value::known(*msg_hash)); - let r_assigned = scalar_chip.assign_integer(ctx, integer_r)?; - let s_assigned = scalar_chip.assign_integer(ctx, integer_s)?; + let r_assigned = scalar_chip.assign_integer(ctx, integer_r, Range::Remainder)?; + let s_assigned = scalar_chip.assign_integer(ctx, integer_s, Range::Remainder)?; let sig = AssignedEcdsaSig { r: r_assigned, s: s_assigned, }; - let pk_in_circuit = ecc_chip.assign_point(ctx, Some(*pk))?; + let pk_in_circuit = ecc_chip.assign_point(ctx, Value::known(*pk))?; let pk_assigned = AssignedPublicKey { point: pk_in_circuit, }; - let msg_hash = scalar_chip.assign_integer(ctx, msg_hash)?; + let msg_hash = scalar_chip.assign_integer(ctx, msg_hash, Range::Remainder)?; // Convert (msg_hash, pk_x, pk_y) integers to little endian bytes - let pows_256 = assign_pows_256(ctx, main_gate, 9)?; - let msg_hash_le = integer_to_bytes_le(ctx, main_gate, range_chip, &pows_256, &msg_hash)?; - let pk_x = pk_assigned.point.get_x(); - let pk_x_le = integer_to_bytes_le(ctx, main_gate, range_chip, &pows_256, &pk_x)?; - let pk_y = pk_assigned.point.get_y(); - let pk_y_le = integer_to_bytes_le(ctx, main_gate, range_chip, &pows_256, &pk_y)?; + let msg_hash_le = integer_to_bytes_le(ctx, range_chip, &msg_hash)?; + let pk_x = pk_assigned.point.x(); + let pk_x_le = integer_to_bytes_le(ctx, range_chip, pk_x)?; + let pk_y = pk_assigned.point.y(); + let pk_y_le = integer_to_bytes_le(ctx, range_chip, pk_y)?; // Ref. spec SignVerifyChip 4. Verify the ECDSA signature ecdsa_chip.verify(ctx, &sig, &pk_assigned, &msg_hash)?; @@ -462,16 +452,16 @@ impl SignVerifyChip { // Assign msg_hash_rlc let mut msg_hash_le = [0u8; 32]; - msg_hash - .write(&mut Cursor::new(&mut msg_hash_le[..])) - .expect("cannot write bytes to array"); + msg_hash_le + .as_mut_slice() + .copy_from_slice(msg_hash.to_bytes().as_slice()); let msg_hash_rlc = Word::random_linear_combine(msg_hash_le, randomness); let msg_hash_rlc = if !padding { msg_hash_rlc } else { F::zero() }; let msg_hash_rlc_assigned = region.assign_advice( || "msg_hash_rlc", config.msg_hash_rlc, offset, - || Ok(msg_hash_rlc), + || Value::known(msg_hash_rlc), )?; // Assign pk @@ -481,7 +471,7 @@ impl SignVerifyChip { || format!("pk x byte {}", i), config.pk[0][i], offset, - || Ok(F::from(*byte as u64)), + || Value::known(F::from(*byte as u64)), )?; } for (i, byte) in pk_le[32..].iter().enumerate() { @@ -489,7 +479,7 @@ impl SignVerifyChip { || format!("pk y byte {}", i), config.pk[1][i], offset, - || Ok(F::from(*byte as u64)), + || Value::known(F::from(*byte as u64)), )?; } @@ -506,15 +496,19 @@ impl SignVerifyChip { || format!("pk_hash byte {}", i), config.pk_hash[i], offset, - || Ok(F::from(*byte as u64)), + || Value::known(F::from(*byte as u64)), )?; } let address = if !padding { address } else { F::zero() }; // Assign address and address_is_zero_chip - let address_assigned = - region.assign_advice(|| "address", config.address, offset, || Ok(address))?; - address_is_zero_chip.assign(region, offset, Some(address))?; + let address_assigned = region.assign_advice( + || "address", + config.address, + offset, + || Value::known(address), + )?; + address_is_zero_chip.assign(region, offset, Value::known(address))?; // Assign msg_hash for (i, byte) in msg_hash_le.iter().enumerate() { @@ -522,7 +516,7 @@ impl SignVerifyChip { || format!("msg_hash byte {}", i), config.msg_hash[i], offset, - || Ok(F::from(*byte as u64)), + || Value::known(F::from(*byte as u64)), )?; } @@ -554,17 +548,16 @@ impl SignVerifyChip { return Err(Error::Synthesis); } let main_gate = MainGate::new(config.main_gate_config.clone()); - // TODO: Figure out the best value for RangeChip base_bit_len, when we want to - // range on 8 bits. - let range_chip = RangeChip::new(config.range_config.clone(), 8); + let range_chip = RangeChip::new(config.range_config.clone()); let mut ecc_chip = GeneralEccChip::::new( config.ecc_chip_config(), ); - let scalar_chip = ecc_chip.scalar_field_chip(); + let cloned_ecc_chip = ecc_chip.clone(); + let scalar_chip = cloned_ecc_chip.scalar_field_chip(); layouter.assign_region( || "ecc chip aux", - |mut region| self.assign_aux(&mut region, &mut ecc_chip), + |region| self.assign_aux(&mut RegionCtx::new(region, 0), &mut ecc_chip), )?; let ecdsa_chip = EcdsaChip::new(ecc_chip.clone()); @@ -577,17 +570,17 @@ impl SignVerifyChip { main_gate: &main_gate, range_chip: &range_chip, ecc_chip: &ecc_chip, - scalar_chip: &scalar_chip, + scalar_chip, ecdsa_chip: &ecdsa_chip, }; layouter.assign_region( || "ecdsa chip verification", - |mut region| { + |region| { assigned_ecdsas.clear(); keccak_auxs.clear(); let offset = &mut 0; - let mut ctx = RegionCtx::new(&mut region, offset); + let mut ctx = RegionCtx::new(region, *offset); for i in 0..MAX_VERIF { let signature = if i < signatures.len() { signatures[i].clone() @@ -628,9 +621,6 @@ impl SignVerifyChip { Ok(()) }, )?; - - config.load_range(layouter)?; - Ok(assigned_sig_verifs) } } @@ -647,9 +637,15 @@ mod sign_verify_tests { use crate::util::power_of_randomness_from_instance; use bus_mapping::circuit_input_builder::keccak_inputs_sign_verify; use eth_types::sign_types::sign; - use group::{ff::Field as GroupField, prime::PrimeCurveAffine, Curve, Group}; + use halo2_proofs::arithmetic::Field as HaloField; use halo2_proofs::{ - arithmetic::CurveAffine, circuit::SimpleFloorPlanner, dev::MockProver, pairing::bn256::Fr, + circuit::SimpleFloorPlanner, + dev::MockProver, + halo2curves::{ + bn256::Fr, + group::{Curve, Group}, + CurveAffine, + }, plonk::Circuit, }; use pretty_assertions::assert_eq; @@ -706,6 +702,7 @@ mod sign_verify_tests { &keccak_inputs_sign_verify(&self.signatures), self.randomness, )?; + config.sign_verify.load_range(&mut layouter)?; Ok(()) } } @@ -743,7 +740,7 @@ mod sign_verify_tests { // Generate a test key pair fn gen_key_pair(rng: impl RngCore) -> (secp256k1::Fq, Secp256k1Affine) { // generate a valid signature - let generator = ::generator(); + let generator = Secp256k1Affine::generator(); let sk = secp256k1::Fq::random(rng); let pk = generator * sk; let pk = pk.to_affine();